From 8fb67fed85a38fe95ef62ada598430553a66738d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20=C4=86wirko?= Date: Sun, 21 Apr 2024 22:26:31 +0200 Subject: [PATCH 1/5] migrate to sdk v13 --- CHANGELOG.md | 11 + build/elven.js | 55030 +++++++++++++++++++- build/types/elven.d.ts | 13 +- build/types/utils/amount.d.ts | 21 + esbuild.config.cjs | 2 +- example/elven.js | 55030 +++++++++++++++++++- example/index.html | 57 +- package-lock.json | 1020 +- package.json | 25 +- src/elven.ts | 30 +- src/interaction/post-send-tx.ts | 7 +- src/interaction/pre-send-tx.ts | 4 +- src/interaction/web-wallet-tx-finalize.ts | 2 +- src/main.ts | 2 +- src/utils/amount.ts | 46 + tsconfig.json | 2 +- 16 files changed, 110608 insertions(+), 694 deletions(-) create mode 100644 build/types/utils/amount.d.ts create mode 100644 src/utils/amount.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c980f2..dbfc1e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +### [0.18.0](https://github.com/elven-js/elven.js/releases/tag/v0.18.0) (2024-04-21) +- switch to SDK v13 +- breaking: `SmartContract` is no longer exported, use `SmartContractTransactionsFactory` +- breaking: `GasEstimator` removed +- breaking: `ContractFunction` removed, pass normal strings +- breaking: `TransactionPayload` removed, you can now pass `Uint8Array` instead +- update examples +- update reexported functions and helpers +- return transaction on network in `onTxFinalized` +- added two amount related helper functions: `parseAmount` and `formatAmount` + ### [0.17.0](https://github.com/elven-js/elven.js/releases/tag/v0.17.0) (2024-01-29) - remove onLoginEnd and onLogoutEnd callbacks. With success and failure callbacks, they are not needed - fix duplicate callbacks calls diff --git a/build/elven.js b/build/elven.js index 4a74182..aab57b0 100644 --- a/build/elven.js +++ b/build/elven.js @@ -1,53 +1,54986 @@ -var D4=Object.create;var Ef=Object.defineProperty;var P4=Object.getOwnPropertyDescriptor;var R4=Object.getOwnPropertyNames;var B4=Object.getPrototypeOf,L4=Object.prototype.hasOwnProperty;var TS=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var he=(t,e)=>()=>(t&&(e=t(t=0)),e);var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ft=(t,e)=>{for(var r in e)Ef(t,r,{get:e[r],enumerable:!0})},wf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of R4(e))!L4.call(t,i)&&i!==r&&Ef(t,i,{get:()=>e[i],enumerable:!(n=P4(e,i))||n.enumerable});return t},Qt=(t,e,r)=>(wf(t,e,"default"),r&&wf(r,e,"default")),be=(t,e,r)=>(r=t!=null?D4(B4(t)):{},wf(e||!t||!t.__esModule?Ef(r,"default",{value:t,enumerable:!0}):r,t)),ht=t=>wf(Ef({},"__esModule",{value:!0}),t);var $0=v(vf=>{"use strict";l();vf.byteLength=M4;vf.toByteArray=q4;vf.fromByteArray=k4;var sn=[],Tr=[],F4=typeof Uint8Array<"u"?Uint8Array:Array,W0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ts=0,CS=W0.length;Ts0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function M4(t){var e=xS(t),r=e[0],n=e[1];return(r+n)*3/4-n}function U4(t,e,r){return(e+r)*3/4-r}function q4(t){var e,r=xS(t),n=r[0],i=r[1],s=new F4(U4(t,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tr[t.charCodeAt(u)]<<2|Tr[t.charCodeAt(u+1)]>>4,s[o++]=e&255),i===1&&(e=Tr[t.charCodeAt(u)]<<10|Tr[t.charCodeAt(u+1)]<<4|Tr[t.charCodeAt(u+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function V4(t){return sn[t>>18&63]+sn[t>>12&63]+sn[t>>6&63]+sn[t&63]}function H4(t,e,r){for(var n,i=[],s=e;sa?a:o+s));return n===1?(e=t[r-1],i.push(sn[e>>2]+sn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(sn[e>>10]+sn[e>>4&63]+sn[e<<2&63]+"=")),i.join("")}});var Y0=v(K0=>{l();K0.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,u=(1<>1,f=-7,d=r?i-1:0,g=r?-1:1,m=t[e+d];for(d+=g,s=m&(1<<-f)-1,m>>=-f,f+=a;f>0;s=s*256+t[e+d],d+=g,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=g,f-=8);if(s===0)s=1-c;else{if(s===u)return o?NaN:(m?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(m?-1:1)*o*Math.pow(2,s-n)};K0.write=function(t,e,r,n,i,s){var o,a,u,c=s*8-i-1,f=(1<>1,g=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,m=n?0:s-1,y=n?1:-1,A=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+d>=1?e+=g/u:e+=g*Math.pow(2,1-d),e*u>=2&&(o++,u/=2),o+d>=f?(a=0,o=f):o+d>=1?(a=(e*u-1)*Math.pow(2,i),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+m]=a&255,m+=y,a/=256,i-=8);for(o=o<0;t[r+m]=o&255,m+=y,o/=256,c-=8);t[r+m-y]|=A*128}});var HS=v(No=>{"use strict";l();var J0=$0(),xo=Y0(),NS=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;No.Buffer=$;No.SlowBuffer=$4;No.INSPECT_MAX_BYTES=50;var Af=2147483647;No.kMaxLength=Af;$.TYPED_ARRAY_SUPPORT=G4();!$.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 G4(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty($.prototype,"parent",{enumerable:!0,get:function(){if($.isBuffer(this))return this.buffer}});Object.defineProperty($.prototype,"offset",{enumerable:!0,get:function(){if($.isBuffer(this))return this.byteOffset}});function zn(t){if(t>Af)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,$.prototype),e}function $(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return tm(t)}return PS(t,e,r)}$.poolSize=8192;function PS(t,e,r){if(typeof t=="string")return Q4(t,e);if(ArrayBuffer.isView(t))return z4(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(on(t,ArrayBuffer)||t&&on(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(on(t,SharedArrayBuffer)||t&&on(t.buffer,SharedArrayBuffer)))return Z0(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return $.from(n,e,r);var i=W4(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return $.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}$.from=function(t,e,r){return PS(t,e,r)};Object.setPrototypeOf($.prototype,Uint8Array.prototype);Object.setPrototypeOf($,Uint8Array);function RS(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function j4(t,e,r){return RS(t),t<=0?zn(t):e!==void 0?typeof r=="string"?zn(t).fill(e,r):zn(t).fill(e):zn(t)}$.alloc=function(t,e,r){return j4(t,e,r)};function tm(t){return RS(t),zn(t<0?0:rm(t)|0)}$.allocUnsafe=function(t){return tm(t)};$.allocUnsafeSlow=function(t){return tm(t)};function Q4(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!$.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=BS(t,e)|0,n=zn(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function X0(t){for(var e=t.length<0?0:rm(t.length)|0,r=zn(e),n=0;n=Af)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Af.toString(16)+" bytes");return t|0}function $4(t){return+t!=t&&(t=0),$.alloc(+t)}$.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==$.prototype};$.compare=function(e,r){if(on(e,Uint8Array)&&(e=$.from(e,e.offset,e.byteLength)),on(r,Uint8Array)&&(r=$.from(r,r.offset,r.byteLength)),!$.isBuffer(e)||!$.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?$.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if($.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function BS(t,e){if($.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||on(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return em(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return VS(t).length;default:if(i)return n?-1:em(t).length;e=(""+e).toLowerCase(),i=!0}}$.byteLength=BS;function K4(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return s5(this,e,r);case"utf8":case"utf-8":return FS(this,e,r);case"ascii":return n5(this,e,r);case"latin1":case"binary":return i5(this,e,r);case"base64":return t5(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return o5(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}$.prototype._isBuffer=!0;function Cs(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}$.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};NS&&($.prototype[NS]=$.prototype.inspect);$.prototype.compare=function(e,r,n,i,s){if(on(e,Uint8Array)&&(e=$.from(e,e.offset,e.byteLength)),!$.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-r,u=Math.min(o,a),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,nm(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=$.from(e,n)),$.isBuffer(e))return e.length===0?-1:OS(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):OS(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function OS(t,e,r,n,i){var s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function u(m,y){return s===1?m[y]:m.readUInt16BE(y*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-a),c=r;c>=0;c--){for(var d=!0,g=0;gi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Y4(this,e,r,n);case"utf8":case"utf-8":return J4(this,e,r,n);case"ascii":case"latin1":case"binary":return X4(this,e,r,n);case"base64":return Z4(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return e5(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};$.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function t5(t,e,r){return e===0&&r===t.length?J0.fromByteArray(t):J0.fromByteArray(t.slice(e,r))}function FS(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+a<=r){var u,c,f,d;switch(a){case 1:s<128&&(o=s);break;case 2:u=t[i+1],(u&192)===128&&(d=(s&31)<<6|u&63,d>127&&(o=d));break;case 3:u=t[i+1],c=t[i+2],(u&192)===128&&(c&192)===128&&(d=(s&15)<<12|(u&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:u=t[i+1],c=t[i+2],f=t[i+3],(u&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(u&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return r5(n)}var DS=4096;function r5(t){var e=t.length;if(e<=DS)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}$.prototype.readUintLE=$.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};$.prototype.readUint8=$.prototype.readUInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]};$.prototype.readUint16LE=$.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]|this[e+1]<<8};$.prototype.readUint16BE=$.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]<<8|this[e+1]};$.prototype.readUint32LE=$.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};$.prototype.readUint32BE=$.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};$.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};$.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};$.prototype.readInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};$.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};$.prototype.readInt16BE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};$.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};$.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};$.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),xo.read(this,e,!0,23,4)};$.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),xo.read(this,e,!1,23,4)};$.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),xo.read(this,e,!0,52,8)};$.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),xo.read(this,e,!1,52,8)};function lr(t,e,r,n,i,s){if(!$.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}$.prototype.writeUintLE=$.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;lr(this,e,r,n,s,0)}var o=1,a=0;for(this[r]=e&255;++a>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;lr(this,e,r,n,s,0)}var o=n-1,a=1;for(this[r+o]=e&255;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+n};$.prototype.writeUint8=$.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,1,255,0),this[r]=e&255,r+1};$.prototype.writeUint16LE=$.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};$.prototype.writeUint16BE=$.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};$.prototype.writeUint32LE=$.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};$.prototype.writeUint32BE=$.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};$.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);lr(this,e,r,n,s-1,-s)}var o=0,a=1,u=0;for(this[r]=e&255;++o>0)-u&255;return r+n};$.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);lr(this,e,r,n,s-1,-s)}var o=n-1,a=1,u=0;for(this[r+o]=e&255;--o>=0&&(a*=256);)e<0&&u===0&&this[r+o+1]!==0&&(u=1),this[r+o]=(e/a>>0)-u&255;return r+n};$.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};$.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};$.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};$.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};$.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function MS(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function US(t,e,r,n,i){return e=+e,r=r>>>0,i||MS(t,e,r,4,34028234663852886e22,-34028234663852886e22),xo.write(t,e,r,n,23,4),r+4}$.prototype.writeFloatLE=function(e,r,n){return US(this,e,r,!0,n)};$.prototype.writeFloatBE=function(e,r,n){return US(this,e,r,!1,n)};function qS(t,e,r,n,i){return e=+e,r=r>>>0,i||MS(t,e,r,8,17976931348623157e292,-17976931348623157e292),xo.write(t,e,r,n,52,8),r+8}$.prototype.writeDoubleLE=function(e,r,n){return qS(this,e,r,!0,n)};$.prototype.writeDoubleBE=function(e,r,n){return qS(this,e,r,!1,n)};$.prototype.copy=function(e,r,n,i){if(!$.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function c5(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function VS(t){return J0.toByteArray(u5(t))}function bf(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function on(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function nm(t){return t!==t}var f5=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var zS=v(($se,QS)=>{l();var vt=QS.exports={},an,un;function im(){throw new Error("setTimeout has not been defined")}function sm(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?an=setTimeout:an=im}catch{an=im}try{typeof clearTimeout=="function"?un=clearTimeout:un=sm}catch{un=sm}})();function kS(t){if(an===setTimeout)return setTimeout(t,0);if((an===im||!an)&&setTimeout)return an=setTimeout,setTimeout(t,0);try{return an(t,0)}catch{try{return an.call(null,t,0)}catch{return an.call(this,t,0)}}}function d5(t){if(un===clearTimeout)return clearTimeout(t);if((un===sm||!un)&&clearTimeout)return un=clearTimeout,clearTimeout(t);try{return un(t)}catch{try{return un.call(null,t)}catch{return un.call(this,t)}}}var Wn=[],Oo=!1,xs,If=-1;function h5(){!Oo||!xs||(Oo=!1,xs.length?Wn=xs.concat(Wn):If=-1,Wn.length&&GS())}function GS(){if(!Oo){var t=kS(h5);Oo=!0;for(var e=Wn.length;e;){for(xs=Wn,Wn=[];++If1)for(var r=1;r{h=be(HS()),p=be(zS()),p5=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=p5});var Yt=v((WS,_f)=>{l();(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,i=Math.floor,s="[BigNumber Error] ",o=s+"Number primitive has more than 15 significant digits: ",a=1e14,u=14,c=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],d=1e7,g=1e9;function m(S){var N,_,T,B=U.prototype={constructor:U,toString:null,valueOf:null},X=new U(1),z=20,k=4,Q=-7,K=21,ye=-1e7,ce=1e7,ie=!1,J=1,oe=0,re={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},se="0123456789abcdefghijklmnopqrstuvwxyz";function U(w,E){var I,P,C,D,L,x,F,G,V=this;if(!(V instanceof U))return new U(w,E);if(E==null){if(w&&w._isBigNumber===!0){V.s=w.s,!w.c||w.e>ce?V.c=V.e=null:w.e=10;L/=10,D++);D>ce?V.c=V.e=null:(V.e=D,V.c=[w]);return}G=String(w)}else{if(!r.test(G=String(w)))return T(V,G,x);V.s=G.charCodeAt(0)==45?(G=G.slice(1),-1):1}(D=G.indexOf("."))>-1&&(G=G.replace(".","")),(L=G.search(/e/i))>0?(D<0&&(D=L),D+=+G.slice(L+1),G=G.substring(0,L)):D<0&&(D=G.length)}else{if(R(E,2,se.length,"Base"),E==10)return V=new U(w),ae(V,z+V.e+1,k);if(G=String(w),x=typeof w=="number"){if(w*0!=0)return T(V,G,x,E);if(V.s=1/w<0?(G=G.slice(1),-1):1,U.DEBUG&&G.replace(/^0\.0*|\./,"").length>15)throw Error(o+w)}else V.s=G.charCodeAt(0)===45?(G=G.slice(1),-1):1;for(I=se.slice(0,E),D=L=0,F=G.length;LD){D=F;continue}}else if(!C&&(G==G.toUpperCase()&&(G=G.toLowerCase())||G==G.toLowerCase()&&(G=G.toUpperCase()))){C=!0,L=-1,D=0;continue}return T(V,String(w),x,E)}x=!1,G=_(G,E,10,V.s),(D=G.indexOf("."))>-1?G=G.replace(".",""):D=G.length}for(L=0;G.charCodeAt(L)===48;L++);for(F=G.length;G.charCodeAt(--F)===48;);if(G=G.slice(L,++F)){if(F-=L,x&&U.DEBUG&&F>15&&(w>c||w!==i(w)))throw Error(o+V.s*w);if((D=D-L-1)>ce)V.c=V.e=null;else if(D=-g&&C<=g&&C===i(C)){if(P[0]===0){if(C===0&&P.length===1)return!0;break e}if(E=(C+1)%u,E<1&&(E+=u),String(P[0]).length==E){for(E=0;E=a||I!==i(I))break e;if(I!==0)return!0}}}else if(P===null&&C===null&&(D===null||D===1||D===-1))return!0;throw Error(s+"Invalid BigNumber: "+w)},U.maximum=U.max=function(){return ue(arguments,B.lt)},U.minimum=U.min=function(){return ue(arguments,B.gt)},U.random=function(){var w=9007199254740992,E=Math.random()*w&2097151?function(){return i(Math.random()*w)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var P,C,D,L,x,F=0,G=[],V=new U(X);if(I==null?I=z:R(I,0,g),L=n(I/u),ie)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(L*=2));F>>11),x>=9e15?(C=crypto.getRandomValues(new Uint32Array(2)),P[F]=C[0],P[F+1]=C[1]):(G.push(x%1e14),F+=2);F=L/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(L*=7);F=9e15?crypto.randomBytes(7).copy(P,F):(G.push(x%1e14),F+=7);F=L/7}else throw ie=!1,Error(s+"crypto unavailable");if(!ie)for(;F=10;x/=10,F++);FC-1&&(x[L+1]==null&&(x[L+1]=0),x[L+1]+=x[L]/C|0,x[L]%=C)}return x.reverse()}return function(I,P,C,D,L){var x,F,G,V,ee,Ae,Se,Be,it=I.indexOf("."),dt=z,De=k;for(it>=0&&(V=oe,oe=0,I=I.replace(".",""),Be=new U(P),Ae=Be.pow(I.length-it),oe=V,Be.c=E(b(A(Ae.c),Ae.e,"0"),10,C,w),Be.e=Be.c.length),Se=E(I,P,C,L?(x=se,w):(x=w,se)),G=V=Se.length;Se[--V]==0;Se.pop());if(!Se[0])return x.charAt(0);if(it<0?--G:(Ae.c=Se,Ae.e=G,Ae.s=D,Ae=N(Ae,Be,dt,De,C),Se=Ae.c,ee=Ae.r,G=Ae.e),F=G+dt+1,it=Se[F],V=C/2,ee=ee||F<0||Se[F+1]!=null,ee=De<4?(it!=null||ee)&&(De==0||De==(Ae.s<0?3:2)):it>V||it==V&&(De==4||ee||De==6&&Se[F-1]&1||De==(Ae.s<0?8:7)),F<1||!Se[0])I=ee?b(x.charAt(1),-dt,x.charAt(0)):x.charAt(0);else{if(Se.length=F,ee)for(--C;++Se[--F]>C;)Se[F]=0,F||(++G,Se=[1].concat(Se));for(V=Se.length;!Se[--V];);for(it=0,I="";it<=V;I+=x.charAt(Se[it++]));I=b(I,G,x.charAt(0))}return I}}(),N=function(){function w(P,C,D){var L,x,F,G,V=0,ee=P.length,Ae=C%d,Se=C/d|0;for(P=P.slice();ee--;)F=P[ee]%d,G=P[ee]/d|0,L=Se*F+G*Ae,x=Ae*F+L%d*d+V,V=(x/D|0)+(L/d|0)+Se*G,P[ee]=x%D;return V&&(P=[V].concat(P)),P}function E(P,C,D,L){var x,F;if(D!=L)F=D>L?1:-1;else for(x=F=0;xC[x]?1:-1;break}return F}function I(P,C,D,L){for(var x=0;D--;)P[D]-=x,x=P[D]1;P.splice(0,1));}return function(P,C,D,L,x){var F,G,V,ee,Ae,Se,Be,it,dt,De,Ve,Lt,wi,_s,Ss,cr,Qn,Kt=P.s==C.s?1:-1,Ft=P.c,Je=C.c;if(!Ft||!Ft[0]||!Je||!Je[0])return new U(!P.s||!C.s||(Ft?Je&&Ft[0]==Je[0]:!Je)?NaN:Ft&&Ft[0]==0||!Je?Kt*0:Kt/0);for(it=new U(Kt),dt=it.c=[],G=P.e-C.e,Kt=D+G+1,x||(x=a,G=y(P.e/u)-y(C.e/u),Kt=Kt/u|0),V=0;Je[V]==(Ft[V]||0);V++);if(Je[V]>(Ft[V]||0)&&G--,Kt<0)dt.push(1),ee=!0;else{for(_s=Ft.length,cr=Je.length,V=0,Kt+=2,Ae=i(x/(Je[0]+1)),Ae>1&&(Je=w(Je,Ae,x),Ft=w(Ft,Ae,x),cr=Je.length,_s=Ft.length),wi=cr,De=Ft.slice(0,cr),Ve=De.length;Ve=x/2&&Ss++;do{if(Ae=0,F=E(Je,De,cr,Ve),F<0){if(Lt=De[0],cr!=Ve&&(Lt=Lt*x+(De[1]||0)),Ae=i(Lt/Ss),Ae>1)for(Ae>=x&&(Ae=x-1),Se=w(Je,Ae,x),Be=Se.length,Ve=De.length;E(Se,De,Be,Ve)==1;)Ae--,I(Se,cr=10;Kt/=10,V++);ae(it,D+(it.e=V+G*u-1)+1,L,ee)}else it.e=G,it.r=+ee;return it}}();function fe(w,E,I,P){var C,D,L,x,F;if(I==null?I=k:R(I,0,8),!w.c)return w.toString();if(C=w.c[0],L=w.e,E==null)F=A(w.c),F=P==1||P==2&&(L<=Q||L>=K)?M(F,L):b(F,L,"0");else if(w=ae(new U(w),E,I),D=w.e,F=A(w.c),x=F.length,P==1||P==2&&(E<=D||D<=Q)){for(;xx){if(--E>0)for(F+=".";E--;F+="0");}else if(E+=D-x,E>0)for(D+1==x&&(F+=".");E--;F+="0");return w.s<0&&C?"-"+F:F}function ue(w,E){for(var I,P=1,C=new U(w[0]);P=10;C/=10,P++);return(I=P+I*u-1)>ce?w.c=w.e=null:I=10;x/=10,C++);if(D=E-C,D<0)D+=u,L=E,F=ee[G=0],V=F/Ae[C-L-1]%10|0;else if(G=n((D+1)/u),G>=ee.length)if(P){for(;ee.length<=G;ee.push(0));F=V=0,C=1,D%=u,L=D-u+1}else break e;else{for(F=x=ee[G],C=1;x>=10;x/=10,C++);D%=u,L=D-u+C,V=L<0?0:F/Ae[C-L-1]%10|0}if(P=P||E<0||ee[G+1]!=null||(L<0?F:F%Ae[C-L-1]),P=I<4?(V||P)&&(I==0||I==(w.s<0?3:2)):V>5||V==5&&(I==4||P||I==6&&(D>0?L>0?F/Ae[C-L]:0:ee[G-1])%10&1||I==(w.s<0?8:7)),E<1||!ee[0])return ee.length=0,P?(E-=w.e+1,ee[0]=Ae[(u-E%u)%u],w.e=-E||0):ee[0]=w.e=0,w;if(D==0?(ee.length=G,x=1,G--):(ee.length=G+1,x=Ae[u-D],ee[G]=L>0?i(F/Ae[C-L]%Ae[L])*x:0),P)for(;;)if(G==0){for(D=1,L=ee[0];L>=10;L/=10,D++);for(L=ee[0]+=x,x=1;L>=10;L/=10,x++);D!=x&&(w.e++,ee[0]==a&&(ee[0]=1));break}else{if(ee[G]+=x,ee[G]!=a)break;ee[G--]=0,x=1}for(D=ee.length;ee[--D]===0;ee.pop());}w.e>ce?w.c=w.e=null:w.e=K?M(E,I):b(E,I,"0"),w.s<0?"-"+E:E)}return B.absoluteValue=B.abs=function(){var w=new U(this);return w.s<0&&(w.s=1),w},B.comparedTo=function(w,E){return O(this,new U(w,E))},B.decimalPlaces=B.dp=function(w,E){var I,P,C,D=this;if(w!=null)return R(w,0,g),E==null?E=k:R(E,0,8),ae(new U(D),w+D.e+1,E);if(!(I=D.c))return null;if(P=((C=I.length-1)-y(this.e/u))*u,C=I[C])for(;C%10==0;C/=10,P--);return P<0&&(P=0),P},B.dividedBy=B.div=function(w,E){return N(this,new U(w,E),z,k)},B.dividedToIntegerBy=B.idiv=function(w,E){return N(this,new U(w,E),0,1)},B.exponentiatedBy=B.pow=function(w,E){var I,P,C,D,L,x,F,G,V,ee=this;if(w=new U(w),w.c&&!w.isInteger())throw Error(s+"Exponent not an integer: "+le(w));if(E!=null&&(E=new U(E)),x=w.e>14,!ee.c||!ee.c[0]||ee.c[0]==1&&!ee.e&&ee.c.length==1||!w.c||!w.c[0])return V=new U(Math.pow(+le(ee),x?2-q(w):+le(w))),E?V.mod(E):V;if(F=w.s<0,E){if(E.c?!E.c[0]:!E.s)return new U(NaN);P=!F&&ee.isInteger()&&E.isInteger(),P&&(ee=ee.mod(E))}else{if(w.e>9&&(ee.e>0||ee.e<-1||(ee.e==0?ee.c[0]>1||x&&ee.c[1]>=24e7:ee.c[0]<8e13||x&&ee.c[0]<=9999975e7)))return D=ee.s<0&&q(w)?-0:0,ee.e>-1&&(D=1/D),new U(F?1/D:D);oe&&(D=n(oe/u+2))}for(x?(I=new U(.5),F&&(w.s=1),G=q(w)):(C=Math.abs(+le(w)),G=C%2),V=new U(X);;){if(G){if(V=V.times(ee),!V.c)break;D?V.c.length>D&&(V.c.length=D):P&&(V=V.mod(E))}if(C){if(C=i(C/2),C===0)break;G=C%2}else if(w=w.times(I),ae(w,w.e+1,1),w.e>14)G=q(w);else{if(C=+le(w),C===0)break;G=C%2}ee=ee.times(ee),D?ee.c&&ee.c.length>D&&(ee.c.length=D):P&&(ee=ee.mod(E))}return P?V:(F&&(V=X.div(V)),E?V.mod(E):D?ae(V,oe,k,L):V)},B.integerValue=function(w){var E=new U(this);return w==null?w=k:R(w,0,8),ae(E,E.e+1,w)},B.isEqualTo=B.eq=function(w,E){return O(this,new U(w,E))===0},B.isFinite=function(){return!!this.c},B.isGreaterThan=B.gt=function(w,E){return O(this,new U(w,E))>0},B.isGreaterThanOrEqualTo=B.gte=function(w,E){return(E=O(this,new U(w,E)))===1||E===0},B.isInteger=function(){return!!this.c&&y(this.e/u)>this.c.length-2},B.isLessThan=B.lt=function(w,E){return O(this,new U(w,E))<0},B.isLessThanOrEqualTo=B.lte=function(w,E){return(E=O(this,new U(w,E)))===-1||E===0},B.isNaN=function(){return!this.s},B.isNegative=function(){return this.s<0},B.isPositive=function(){return this.s>0},B.isZero=function(){return!!this.c&&this.c[0]==0},B.minus=function(w,E){var I,P,C,D,L=this,x=L.s;if(w=new U(w,E),E=w.s,!x||!E)return new U(NaN);if(x!=E)return w.s=-E,L.plus(w);var F=L.e/u,G=w.e/u,V=L.c,ee=w.c;if(!F||!G){if(!V||!ee)return V?(w.s=-E,w):new U(ee?L:NaN);if(!V[0]||!ee[0])return ee[0]?(w.s=-E,w):new U(V[0]?L:k==3?-0:0)}if(F=y(F),G=y(G),V=V.slice(),x=F-G){for((D=x<0)?(x=-x,C=V):(G=F,C=ee),C.reverse(),E=x;E--;C.push(0));C.reverse()}else for(P=(D=(x=V.length)<(E=ee.length))?x:E,x=E=0;E0)for(;E--;V[I++]=0);for(E=a-1;P>x;){if(V[--P]=0;){for(I=0,Ae=Lt[C]%dt,Se=Lt[C]/dt|0,L=F,D=C+L;D>C;)G=Ve[--L]%dt,V=Ve[L]/dt|0,x=Se*G+V*Ae,G=Ae*G+x%dt*dt+Be[D]+I,I=(G/it|0)+(x/dt|0)+Se*V,Be[D--]=G%it;Be[D]=I}return I?++P:Be.splice(0,1),de(w,Be,P)},B.negated=function(){var w=new U(this);return w.s=-w.s||null,w},B.plus=function(w,E){var I,P=this,C=P.s;if(w=new U(w,E),E=w.s,!C||!E)return new U(NaN);if(C!=E)return w.s=-E,P.minus(w);var D=P.e/u,L=w.e/u,x=P.c,F=w.c;if(!D||!L){if(!x||!F)return new U(C/0);if(!x[0]||!F[0])return F[0]?w:new U(x[0]?P:C*0)}if(D=y(D),L=y(L),x=x.slice(),C=D-L){for(C>0?(L=D,I=F):(C=-C,I=x),I.reverse();C--;I.push(0));I.reverse()}for(C=x.length,E=F.length,C-E<0&&(I=F,F=x,x=I,E=C),C=0;E;)C=(x[--E]=x[E]+F[E]+C)/a|0,x[E]=a===x[E]?0:x[E]%a;return C&&(x=[C].concat(x),++L),de(w,x,L)},B.precision=B.sd=function(w,E){var I,P,C,D=this;if(w!=null&&w!==!!w)return R(w,1,g),E==null?E=k:R(E,0,8),ae(new U(D),w,E);if(!(I=D.c))return null;if(C=I.length-1,P=C*u+1,C=I[C]){for(;C%10==0;C/=10,P--);for(C=I[0];C>=10;C/=10,P++);}return w&&D.e+1>P&&(P=D.e+1),P},B.shiftedBy=function(w){return R(w,-c,c),this.times("1e"+w)},B.squareRoot=B.sqrt=function(){var w,E,I,P,C,D=this,L=D.c,x=D.s,F=D.e,G=z+4,V=new U("0.5");if(x!==1||!L||!L[0])return new U(!x||x<0&&(!L||L[0])?NaN:L?D:1/0);if(x=Math.sqrt(+le(D)),x==0||x==1/0?(E=A(L),(E.length+F)%2==0&&(E+="0"),x=Math.sqrt(+E),F=y((F+1)/2)-(F<0||F%2),x==1/0?E="5e"+F:(E=x.toExponential(),E=E.slice(0,E.indexOf("e")+1)+F),I=new U(E)):I=new U(x+""),I.c[0]){for(F=I.e,x=F+G,x<3&&(x=0);;)if(C=I,I=V.times(C.plus(N(D,C,G,1))),A(C.c).slice(0,x)===(E=A(I.c)).slice(0,x))if(I.e0&&Be>0){for(D=Be%x||x,V=Se.substr(0,D);D0&&(V+=G+Se.slice(D)),Ae&&(V="-"+V)}P=ee?V+(I.decimalSeparator||"")+((F=+I.fractionGroupSize)?ee.replace(new RegExp("\\d{"+F+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):ee):V}return(I.prefix||"")+P+(I.suffix||"")},B.toFraction=function(w){var E,I,P,C,D,L,x,F,G,V,ee,Ae,Se=this,Be=Se.c;if(w!=null&&(x=new U(w),!x.isInteger()&&(x.c||x.s!==1)||x.lt(X)))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+le(x));if(!Be)return new U(Se);for(E=new U(X),G=I=new U(X),P=F=new U(X),Ae=A(Be),D=E.e=Ae.length-Se.e-1,E.c[0]=f[(L=D%u)<0?u+L:L],w=!w||x.comparedTo(E)>0?D>0?E:G:x,L=ce,ce=1/0,x=new U(Ae),F.c[0]=0;V=N(x,E,0,1),C=I.plus(V.times(P)),C.comparedTo(w)!=1;)I=P,P=C,G=F.plus(V.times(C=G)),F=C,E=x.minus(V.times(C=E)),x=C;return C=N(w.minus(I),P,0,1),F=F.plus(C.times(G)),I=I.plus(C.times(P)),F.s=G.s=Se.s,D=D*2,ee=N(G,P,D,k).minus(Se).abs().comparedTo(N(F,I,D,k).minus(Se).abs())<1?[G,P]:[F,I],ce=L,ee},B.toNumber=function(){return+le(this)},B.toPrecision=function(w,E){return w!=null&&R(w,1,g),fe(this,w,E,2)},B.toString=function(w){var E,I=this,P=I.s,C=I.e;return C===null?P?(E="Infinity",P<0&&(E="-"+E)):E="NaN":(w==null?E=C<=Q||C>=K?M(A(I.c),C):b(A(I.c),C,"0"):w===10?(I=ae(new U(I),z+C+1,k),E=b(A(I.c),I.e,"0")):(R(w,2,se.length,"Base"),E=_(b(A(I.c),C,"0"),10,w,P,!0)),P<0&&I.c[0]&&(E="-"+E)),E},B.valueOf=B.toJSON=function(){return le(this)},B._isBigNumber=!0,S!=null&&U.set(S),U}function y(S){var N=S|0;return S>0||S===N?N:N-1}function A(S){for(var N,_,T=1,B=S.length,X=S[0]+"";TK^_?1:-1;for(k=(Q=B.length)<(K=X.length)?Q:K,z=0;zX[z]^_?1:-1;return Q==K?0:Q>K^_?1:-1}function R(S,N,_,T){if(S_||S!==i(S))throw Error(s+(T||"Argument")+(typeof S=="number"?S_?" out of range: ":" not an integer: ":" not a primitive number: ")+String(S))}function q(S){var N=S.c.length-1;return y(S.e/u)==N&&S.c[N]%2!=0}function M(S,N){return(S.length>1?S.charAt(0)+"."+S.slice(1):S)+(N<0?"e":"e+")+N}function b(S,N,_){var T,B;if(N<0){for(B=_+".";++N;B+=_);S=B+S}else if(T=S.length,++N>T){for(B=_,N-=T;--N;B+=_);S+=B}else N{"use strict";l();Object.defineProperty(pe,"__esModule",{value:!0});pe.ErrIsCompletedFieldIsMissingOnTransaction=pe.ErrGasLimitShouldBe0ForInnerTransaction=pe.ErrInvalidRelayedV2BuilderArguments=pe.ErrInvalidRelayedV1BuilderArguments=pe.ErrNotImplemented=pe.ErrContractInteraction=pe.ErrCodec=pe.ErrCannotParseTransactionOutcome=pe.ErrCannotParseContractResults=pe.ErrMissingFieldOnEnum=pe.ErrMissingFieldOnStruct=pe.ErrTypingSystem=pe.ErrMock=pe.ErrContractHasNoAddress=pe.ErrContract=pe.ErrExpectedTransactionEventsNotFound=pe.ErrExpectedTransactionStatusNotReached=pe.ErrTransactionWatcherTimeout=pe.ErrAsyncTimerAborted=pe.ErrAsyncTimerAlreadyRunning=pe.ErrInvalidFunctionName=pe.ErrSignatureCannotCreate=pe.ErrTransactionOptionsInvalid=pe.ErrTransactionVersionInvalid=pe.ErrNonceInvalid=pe.ErrNotEnoughGas=pe.ErrAddressEmpty=pe.ErrAddressBadHrp=pe.ErrAddressCannotCreate=pe.ErrUnexpectedCondition=pe.ErrInvariantFailed=pe.ErrBadType=pe.ErrUnsupportedOperation=pe.ErrInvalidArgument=pe.Err=void 0;var Pe=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};pe.Err=Pe;var om=class extends Pe{constructor(e,r){super(`Invalid argument: ${e}`,r)}};pe.ErrInvalidArgument=om;var am=class extends Pe{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};pe.ErrUnsupportedOperation=am;var um=class extends Pe{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};pe.ErrBadType=um;var cm=class extends Pe{constructor(e){super(`Invariant failed: [${e}]`)}};pe.ErrInvariantFailed=cm;var lm=class extends Pe{constructor(e){super(`Unexpected condition: [${e}]`)}};pe.ErrUnexpectedCondition=lm;var fm=class extends Pe{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};pe.ErrAddressCannotCreate=fm;var dm=class extends Pe{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};pe.ErrAddressBadHrp=dm;var hm=class extends Pe{constructor(){super("Address is empty")}};pe.ErrAddressEmpty=hm;var pm=class extends Pe{constructor(e){super(`Not enough gas provided: ${e}`)}};pe.ErrNotEnoughGas=pm;var gm=class extends Pe{constructor(e){super(`Invalid nonce: ${e}`)}};pe.ErrNonceInvalid=gm;var ym=class extends Pe{constructor(e){super(`Invalid transaction version: ${e}`)}};pe.ErrTransactionVersionInvalid=ym;var mm=class extends Pe{constructor(e){super(`Invalid transaction options: ${e}`)}};pe.ErrTransactionOptionsInvalid=mm;var wm=class extends Pe{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};pe.ErrSignatureCannotCreate=wm;var Em=class extends Pe{constructor(){super("Invalid function name")}};pe.ErrInvalidFunctionName=Em;var vm=class extends Pe{constructor(){super("Async timer already running")}};pe.ErrAsyncTimerAlreadyRunning=vm;var Am=class extends Pe{constructor(){super("Async timer aborted")}};pe.ErrAsyncTimerAborted=Am;var bm=class extends Pe{constructor(){super("TransactionWatcher has timed out")}};pe.ErrTransactionWatcherTimeout=bm;var Im=class extends Pe{constructor(){super("Expected transaction status not reached")}};pe.ErrExpectedTransactionStatusNotReached=Im;var _m=class extends Pe{constructor(){super("Expected transaction events not found")}};pe.ErrExpectedTransactionEventsNotFound=_m;var Sf=class extends Pe{constructor(e){super(e)}};pe.ErrContract=Sf;var Sm=class extends Sf{constructor(){super(` +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, { + get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] +}) : x3)(function(x3) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x3 + '" is not supported'); +}); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod2) => function __require2() { + return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; +}; +var __export = (target, all) => { + for (var name2 in all) + __defProp(target, name2, { get: all[name2], enumerable: true }); +}; +var __copyProps = (to, from3, except, desc) => { + if (from3 && typeof from3 === "object" || typeof from3 === "function") { + for (let key of __getOwnPropNames(from3)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default")); +var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, + mod2 +)); +var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); + +// node_modules/base64-js/index.js +var require_base64_js = __commonJS({ + "node_modules/base64-js/index.js"(exports2) { + "use strict"; + init_shim(); + exports2.byteLength = byteLength; + exports2.toByteArray = toByteArray; + exports2.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i2 = 0, len = code2.length; i2 < len; ++i2) { + lookup[i2] = code2[i2]; + revLookup[code2.charCodeAt(i2)] = i2; + } + var i2; + var len; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) + validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i3; + for (i3 = 0; i3 < len2; i3 += 4) { + tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i3 = start; i3 < end; i3 += 3) { + tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) { + parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); + } + } +}); + +// node_modules/ieee754/index.js +var require_ieee754 = __commonJS({ + "node_modules/ieee754/index.js"(exports2) { + init_shim(); + exports2.read = function(buffer, offset, isLE, mLen, nBytes) { + var e2, m3; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i2 = isLE ? nBytes - 1 : 0; + var d3 = isLE ? -1 : 1; + var s2 = buffer[offset + i2]; + i2 += d3; + e2 = s2 & (1 << -nBits) - 1; + s2 >>= -nBits; + nBits += eLen; + for (; nBits > 0; e2 = e2 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { + } + m3 = e2 & (1 << -nBits) - 1; + e2 >>= -nBits; + nBits += mLen; + for (; nBits > 0; m3 = m3 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { + } + if (e2 === 0) { + e2 = 1 - eBias; + } else if (e2 === eMax) { + return m3 ? NaN : (s2 ? -1 : 1) * Infinity; + } else { + m3 = m3 + Math.pow(2, mLen); + e2 = e2 - eBias; + } + return (s2 ? -1 : 1) * m3 * Math.pow(2, e2 - mLen); + }; + exports2.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e2, m3, c4; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i2 = isLE ? 0 : nBytes - 1; + var d3 = isLE ? 1 : -1; + var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m3 = isNaN(value) ? 1 : 0; + e2 = eMax; + } else { + e2 = Math.floor(Math.log(value) / Math.LN2); + if (value * (c4 = Math.pow(2, -e2)) < 1) { + e2--; + c4 *= 2; + } + if (e2 + eBias >= 1) { + value += rt / c4; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c4 >= 2) { + e2++; + c4 /= 2; + } + if (e2 + eBias >= eMax) { + m3 = 0; + e2 = eMax; + } else if (e2 + eBias >= 1) { + m3 = (value * c4 - 1) * Math.pow(2, mLen); + e2 = e2 + eBias; + } else { + m3 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e2 = 0; + } + } + for (; mLen >= 8; buffer[offset + i2] = m3 & 255, i2 += d3, m3 /= 256, mLen -= 8) { + } + e2 = e2 << mLen | m3; + eLen += mLen; + for (; eLen > 0; buffer[offset + i2] = e2 & 255, i2 += d3, e2 /= 256, eLen -= 8) { + } + buffer[offset + i2 - d3] |= s2 * 128; + }; + } +}); + +// node_modules/node-stdlib-browser/node_modules/buffer/index.js +var require_buffer = __commonJS({ + "node_modules/node-stdlib-browser/node_modules/buffer/index.js"(exports2) { + "use strict"; + init_shim(); + var base642 = require_base64_js(); + var ieee754 = require_ieee754(); + var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports2.Buffer = Buffer2; + exports2.SlowBuffer = SlowBuffer; + exports2.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports2.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { + try { + var arr = new Uint8Array(1); + var proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e2) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.byteOffset; + } + }); + function createBuffer(length2) { + if (length2 > K_MAX_LENGTH) { + throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); + } + var buf = new Uint8Array(length2); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe2(arg); + } + return from3(arg, encodingOrOffset, length2); + } + Buffer2.poolSize = 8192; + function from3(value, encodingOrOffset, length2) { + if (typeof value === "string") { + return fromString3(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer2.from(valueOf, encodingOrOffset, length2); + } + var b4 = fromObject(value); + if (b4) + return b4; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer2.from( + value[Symbol.toPrimitive]("string"), + encodingOrOffset, + length2 + ); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + Buffer2.from = function(value, encodingOrOffset, length2) { + return from3(value, encodingOrOffset, length2); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe2(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe2(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe2(size); + }; + function fromString3(string2, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + var length2 = byteLength(string2, encoding) | 0; + var buf = createBuffer(length2); + var actual = buf.write(string2, encoding); + if (actual !== length2) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + var length2 = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length2); + for (var i2 = 0; i2 < length2; i2 += 1) { + buf[i2] = array[i2] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array, byteOffset, length2) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length2 || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + var buf; + if (byteOffset === void 0 && length2 === void 0) { + buf = new Uint8Array(array); + } else if (length2 === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length2); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length2) { + if (length2 >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length2 | 0; + } + function SlowBuffer(length2) { + if (+length2 != length2) { + length2 = 0; + } + return Buffer2.alloc(+length2); + } + Buffer2.isBuffer = function isBuffer(b4) { + return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; + }; + Buffer2.compare = function compare3(a3, b4) { + if (isInstance(a3, Uint8Array)) + a3 = Buffer2.from(a3, a3.offset, a3.byteLength); + if (isInstance(b4, Uint8Array)) + b4 = Buffer2.from(b4, b4.offset, b4.byteLength); + if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a3 === b4) + return 0; + var x3 = a3.length; + var y4 = b4.length; + for (var i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { + if (a3[i2] !== b4[i2]) { + x3 = a3[i2]; + y4 = b4[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding) { + switch (String(encoding).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 true; + default: + return false; + } + }; + Buffer2.concat = function concat2(list, length2) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + var i2; + if (length2 === void 0) { + length2 = 0; + for (i2 = 0; i2 < list.length; ++i2) { + length2 += list[i2].length; + } + } + var buffer = Buffer2.allocUnsafe(length2); + var pos = 0; + for (i2 = 0; i2 < list.length; ++i2) { + var buf = list[i2]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer2.from(buf).copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer; + }; + function byteLength(string2, encoding) { + if (Buffer2.isBuffer(string2)) { + return string2.length; + } + if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { + return string2.byteLength; + } + if (typeof string2 !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 + ); + } + var len = string2.length; + var mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) + return 0; + var loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string2).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string2).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string2).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength; + function slowToString(encoding, start, end) { + var loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) + encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b4, n3, m3) { + var i2 = b4[n3]; + b4[n3] = b4[m3]; + b4[m3] = i2; + } + Buffer2.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (var i2 = 0; i2 < len; i2 += 2) { + swap(this, i2, i2 + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (var i2 = 0; i2 < len; i2 += 4) { + swap(this, i2, i2 + 3); + swap(this, i2 + 1, i2 + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (var i2 = 0; i2 < len; i2 += 8) { + swap(this, i2, i2 + 7); + swap(this, i2 + 1, i2 + 6); + swap(this, i2 + 2, i2 + 5); + swap(this, i2 + 3, i2 + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString3() { + var length2 = this.length; + if (length2 === 0) + return ""; + if (arguments.length === 0) + return utf8Slice(this, 0, length2); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals4(b4) { + if (!Buffer2.isBuffer(b4)) + throw new TypeError("Argument must be a Buffer"); + if (this === b4) + return true; + return Buffer2.compare(this, b4) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + var str = ""; + var max = exports2.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) + str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) + return 0; + var x3 = thisEnd - thisStart; + var y4 = end - start; + var len = Math.min(x3, y4); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + for (var i2 = 0; i2 < len; ++i2) { + if (thisCopy[i2] !== targetCopy[i2]) { + x3 = thisCopy[i2]; + y4 = targetCopy[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + if (buffer.length === 0) + return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer.length - 1; + } + if (byteOffset < 0) + byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) + return -1; + else + byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) + byteOffset = 0; + else + return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read2(buf, i3) { + if (indexSize === 1) { + return buf[i3]; + } else { + return buf.readUInt16BE(i3 * indexSize); + } + } + var i2; + if (dir) { + var foundIndex = -1; + for (i2 = byteOffset; i2 < arrLength; i2++) { + if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { + if (foundIndex === -1) + foundIndex = i2; + if (i2 - foundIndex + 1 === valLength) + return foundIndex * indexSize; + } else { + if (foundIndex !== -1) + i2 -= i2 - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength; + for (i2 = byteOffset; i2 >= 0; i2--) { + var found = true; + for (var j2 = 0; j2 < valLength; j2++) { + if (read2(arr, i2 + j2) !== read2(val, j2)) { + found = false; + break; + } + } + if (found) + return i2; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string2, offset, length2) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length2) { + length2 = remaining; + } else { + length2 = Number(length2); + if (length2 > remaining) { + length2 = remaining; + } + } + var strLen = string2.length; + if (length2 > strLen / 2) { + length2 = strLen / 2; + } + for (var i2 = 0; i2 < length2; ++i2) { + var parsed = parseInt(string2.substr(i2 * 2, 2), 16); + if (numberIsNaN(parsed)) + return i2; + buf[offset + i2] = parsed; + } + return i2; + } + function utf8Write(buf, string2, offset, length2) { + return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); + } + function asciiWrite(buf, string2, offset, length2) { + return blitBuffer(asciiToBytes(string2), buf, offset, length2); + } + function base64Write(buf, string2, offset, length2) { + return blitBuffer(base64ToBytes(string2), buf, offset, length2); + } + function ucs2Write(buf, string2, offset, length2) { + return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); + } + Buffer2.prototype.write = function write(string2, offset, length2, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length2 = this.length; + offset = 0; + } else if (length2 === void 0 && typeof offset === "string") { + encoding = offset; + length2 = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length2)) { + length2 = length2 >>> 0; + if (encoding === void 0) + encoding = "utf8"; + } else { + encoding = length2; + length2 = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + var remaining = this.length - offset; + if (length2 === void 0 || length2 > remaining) + length2 = remaining; + if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) + encoding = "utf8"; + var loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string2, offset, length2); + case "utf8": + case "utf-8": + return utf8Write(this, string2, offset, length2); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string2, offset, length2); + case "base64": + return base64Write(this, string2, offset, length2); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string2, offset, length2); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base642.fromByteArray(buf); + } else { + return base642.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i2 = start; + while (i2 < end) { + var firstByte = buf[i2]; + var codePoint = null; + var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i2 + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i2 + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + fourthByte = buf[i2 + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i2 += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + var res = ""; + var i2 = 0; + while (i2 < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); + for (var i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); + for (var i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2]); + } + return ret; + } + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) + start = 0; + if (!end || end < 0 || end > len) + end = len; + var out = ""; + for (var i2 = start; i2 < end; ++i2) { + out += hexSliceLookupTable[buf[i2]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ""; + for (var i2 = 0; i2 < bytes.length - 1; i2 += 2) { + res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) + start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) + end = 0; + } else if (end > len) { + end = len; + } + if (end < start) + end = start; + var newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset, ext, length2) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError("offset is not uint"); + if (offset + ext > length2) + throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + var val = this[offset]; + var mul = 1; + var i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength2, this.length); + } + var val = this[offset + --byteLength2]; + var mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset + --byteLength2] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + var val = this[offset]; + var mul = 1; + var i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + var i2 = byteLength2; + var mul = 1; + var val = this[offset + --i2]; + while (i2 > 0 && (mul *= 256)) { + val += this[offset + --i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) + return this[offset]; + return (255 - this[offset] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer2.isBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + var mul = 1; + var i2 = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + var i2 = byteLength2 - 1; + var mul = 1; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + var i2 = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + var i2 = byteLength2 - 1; + var mul = 1; + var sub = 0; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 127, -128); + if (value < 0) + value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + if (value < 0) + value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + if (offset < 0) + throw new RangeError("Index out of range"); + } + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + Buffer2.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) + throw new TypeError("argument should be a Buffer"); + if (!start) + start = 0; + if (!end && end !== 0) + end = this.length; + if (targetStart >= target.length) + targetStart = target.length; + if (!targetStart) + targetStart = 0; + if (end > 0 && end < start) + end = start; + if (end === start) + return 0; + if (target.length === 0 || this.length === 0) + return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) + throw new RangeError("Index out of range"); + if (end < 0) + throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) + end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + var len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + var code2 = val.charCodeAt(0); + if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { + val = code2; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) + val = 0; + var i2; + if (typeof val === "number") { + for (i2 = start; i2 < end; ++i2) { + this[i2] = val; + } + } else { + var bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); + var len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i2 = 0; i2 < end - start; ++i2) { + this[i2 + start] = bytes[i2 % len]; + } + } + return this; + }; + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) + return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + function utf8ToBytes(string2, units) { + units = units || Infinity; + var codePoint; + var length2 = string2.length; + var leadSurrogate = null; + var bytes = []; + for (var i2 = 0; i2 < length2; ++i2) { + codePoint = string2.charCodeAt(i2); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } else if (i2 + 1 === length2) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) + break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) + break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) + break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) + break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str) { + var byteArray = []; + for (var i2 = 0; i2 < str.length; ++i2) { + byteArray.push(str.charCodeAt(i2) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + var c4, hi, lo; + var byteArray = []; + for (var i2 = 0; i2 < str.length; ++i2) { + if ((units -= 2) < 0) + break; + c4 = str.charCodeAt(i2); + hi = c4 >> 8; + lo = c4 % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base642.toByteArray(base64clean(str)); + } + function blitBuffer(src2, dst, offset, length2) { + for (var i2 = 0; i2 < length2; ++i2) { + if (i2 + offset >= dst.length || i2 >= src2.length) + break; + dst[i2 + offset] = src2[i2]; + } + return i2; + } + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + var hexSliceLookupTable = function() { + var alphabet2 = "0123456789abcdef"; + var table = new Array(256); + for (var i2 = 0; i2 < 16; ++i2) { + var i16 = i2 * 16; + for (var j2 = 0; j2 < 16; ++j2) { + table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; + } + } + return table; + }(); + } +}); + +// node_modules/process/browser.js +var require_browser = __commonJS({ + "node_modules/process/browser.js"(exports2, module2) { + init_shim(); + var process2 = module2.exports = {}; + var cachedSetTimeout; + var cachedClearTimeout; + function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); + } + function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + if (typeof setTimeout === "function") { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e2) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === "function") { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e2) { + cachedClearTimeout = defaultClearTimeout; + } + })(); + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); + } + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + return cachedSetTimeout(fun, 0); + } catch (e2) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e3) { + return cachedSetTimeout.call(this, fun, 0); + } + } + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); + } + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + return cachedClearTimeout(marker); + } catch (e2) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e3) { + return cachedClearTimeout.call(this, marker); + } + } + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + process2.nextTick = function(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i2 = 1; i2 < arguments.length; i2++) { + args[i2 - 1] = arguments[i2]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function() { + this.fun.apply(null, this.array); + }; + process2.title = "browser"; + process2.browser = true; + process2.env = {}; + process2.argv = []; + process2.version = ""; + process2.versions = {}; + function noop() { + } + process2.on = noop; + process2.addListener = noop; + process2.once = noop; + process2.off = noop; + process2.removeListener = noop; + process2.removeAllListeners = noop; + process2.emit = noop; + process2.prependListener = noop; + process2.prependOnceListener = noop; + process2.listeners = function(name2) { + return []; + }; + process2.binding = function(name2) { + throw new Error("process.binding is not supported"); + }; + process2.cwd = function() { + return "/"; + }; + process2.chdir = function(dir) { + throw new Error("process.chdir is not supported"); + }; + process2.umask = function() { + return 0; + }; + } +}); + +// node_modules/node-stdlib-browser/helpers/esbuild/shim.js +var import_buffer, import_process, _globalThis, global; +var init_shim = __esm({ + "node_modules/node-stdlib-browser/helpers/esbuild/shim.js"() { + import_buffer = __toESM(require_buffer()); + import_process = __toESM(require_browser()); + _globalThis = function(Object2) { + function get2() { + var _global2 = this || self; + delete Object2.prototype.__magic__; + return _global2; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get2(); + } else { + Object2.defineProperty(Object2.prototype, "__magic__", { + configurable: true, + get: get2 + }); + var _global = __magic__; + return _global; + } + }(Object); + global = _globalThis; + } +}); + +// node_modules/bignumber.js/bignumber.js +var require_bignumber = __commonJS({ + "node_modules/bignumber.js/bignumber.js"(exports2, module2) { + init_shim(); + (function(globalObject) { + "use strict"; + var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; + function clone2(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber3(v2, b4) { + var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber3)) + return new BigNumber3(v2, b4); + if (b4 == null) { + if (v2 && v2._isBigNumber === true) { + x3.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v2.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v2.e; + x3.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric2.test(str = String(v2))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i2 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i2; + e2 += +str.slice(i2 + 1); + str = str.substring(0, i2); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + if (b4 == 10 && alphabetHasNormalDecimalDigits) { + x3 = new BigNumber3(v2); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric(x3, str, isNum, b4); + x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits2 + v2); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet2 = ALPHABET.slice(0, b4); + e2 = i2 = 0; + for (len = str.length; i2 < len; i2++) { + if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { + if (c4 == ".") { + if (i2 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i2 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v2), isNum, b4); + } + } + isNum = false; + str = convertBase(str, b4, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i2 = 0; str.charCodeAt(i2) === 48; i2++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i2, ++len)) { + len -= i2; + if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { + throw Error(tooManyDigits2 + x3.s * v2); + } + if ((e2 = e2 - i2 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i2 = (e2 + 1) % LOG_BASE2; + if (e2 < 0) + i2 += LOG_BASE2; + if (i2 < len) { + if (i2) + x3.c.push(+str.slice(0, i2)); + for (len -= LOG_BASE2; i2 < len; ) { + x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); + } + i2 = LOG_BASE2 - (str = str.slice(i2)).length; + } else { + i2 -= len; + } + for (; i2--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber3.clone = clone2; + BigNumber3.ROUND_UP = 0; + BigNumber3.ROUND_DOWN = 1; + BigNumber3.ROUND_CEIL = 2; + BigNumber3.ROUND_FLOOR = 3; + BigNumber3.ROUND_HALF_UP = 4; + BigNumber3.ROUND_HALF_DOWN = 5; + BigNumber3.ROUND_HALF_EVEN = 6; + BigNumber3.ROUND_HALF_CEIL = 7; + BigNumber3.ROUND_HALF_FLOOR = 8; + BigNumber3.EUCLID = 9; + BigNumber3.config = BigNumber3.set = function(obj) { + var p3, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 8, p3); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, 0, p3); + intCheck2(v2[1], 0, MAX2, p3); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p3 = "RANGE")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, -1, p3); + intCheck2(v2[1], 1, MAX2, p3); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p3 = "CRYPTO")) { + v2 = obj[p3]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError2 + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError2 + p3 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 9, p3); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p3 = "FORMAT")) { + v2 = obj[p3]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError2 + p3 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p3 = "ALPHABET")) { + v2 = obj[p3]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; + ALPHABET = v2; + } else { + throw Error(bignumberError2 + p3 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError2 + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber3.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber3.DEBUG) + return true; + var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c4) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { + if (c4[0] === 0) { + if (e2 === 0 && c4.length === 1) + return true; + break out; + } + i2 = (e2 + 1) % LOG_BASE2; + if (i2 < 1) + i2 += LOG_BASE2; + if (String(c4[0]).length == i2) { + for (i2 = 0; i2 < c4.length; i2++) { + n3 = c4[i2]; + if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError2 + "Invalid BigNumber: " + v2); + }; + BigNumber3.maximum = BigNumber3.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber3.minimum = BigNumber3.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber3.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor2(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck2(dp, 0, MAX2); + k4 = mathceil2(dp / LOG_BASE2); + if (CRYPTO) { + if (crypto.getRandomValues) { + a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); + for (; i2 < k4; ) { + v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); + if (v2 >= 9e15) { + b4 = crypto.getRandomValues(new Uint32Array(2)); + a3[i2] = b4[0]; + a3[i2 + 1] = b4[1]; + } else { + c4.push(v2 % 1e14); + i2 += 2; + } + } + i2 = k4 / 2; + } else if (crypto.randomBytes) { + a3 = crypto.randomBytes(k4 *= 7); + for (; i2 < k4; ) { + v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a3, i2); + } else { + c4.push(v2 % 1e14); + i2 += 7; + } + } + i2 = k4 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError2 + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i2 < k4; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c4[i2++] = v2 % 1e14; + } + } + k4 = c4[--i2]; + dp %= LOG_BASE2; + if (k4 && dp) { + v2 = POWS_TEN2[LOG_BASE2 - dp]; + c4[i2] = mathfloor2(k4 / v2) * v2; + } + for (; c4[i2] === 0; c4.pop(), i2--) + ; + if (i2 < 0) { + c4 = [e2 = 0]; + } else { + for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) + ; + for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) + ; + if (i2 < LOG_BASE2) + e2 -= LOG_BASE2 - i2; + } + rand.e = e2; + rand.c = c4; + return rand; + }; + }(); + BigNumber3.sum = function() { + var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); + for (; i2 < args.length; ) + sum = sum.plus(args[i2++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet2) { + var j2, arr = [0], arrL, i2 = 0, len = str.length; + for (; i2 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet2.indexOf(str.charAt(i2++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i2 >= 0) { + k4 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y4 = new BigNumber3(baseIn); + x3 = y4.pow(str.length - i2); + POW_PRECISION = k4; + y4.c = toBaseOut( + toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), + 10, + baseOut, + decimal + ); + y4.e = y4.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); + e2 = k4 = xc.length; + for (; xc[--k4] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet2.charAt(0); + if (i2 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign2; + x3 = div(x3, y4, dp, rm, baseOut); + xc = x3.c; + r = x3.r; + e2 = x3.e; + } + d3 = e2 + dp + 1; + i2 = xc[d3]; + k4 = baseOut / 2; + r = r || d3 < 0 || xc[d3 + 1] != null; + r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (d3 < 1 || !xc[0]) { + str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); + } else { + xc.length = d3; + if (r) { + for (--baseOut; ++xc[--d3] > baseOut; ) { + xc[d3] = 0; + if (!d3) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k4 = xc.length; !xc[--k4]; ) + ; + for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) + ; + str = toFixedPoint2(str, e2, alphabet2.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x3, k4, base3) { + var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; + for (x3 = x3.slice(); i2--; ) { + xlo = x3[i2] % SQRT_BASE2; + xhi = x3[i2] / SQRT_BASE2 | 0; + m3 = khi * xlo + xhi * klo; + temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; + carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; + x3[i2] = temp % base3; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare4(a3, b4, aL, bL) { + var i2, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i2 = cmp = 0; i2 < aL; i2++) { + if (a3[i2] != b4[i2]) { + cmp = a3[i2] > b4[i2] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a3, b4, aL, base3) { + var i2 = 0; + for (; aL--; ) { + a3[aL] -= i2; + i2 = a3[aL] < b4[aL] ? 1 : 0; + a3[aL] = i2 * base3 + a3[aL] - b4[aL]; + } + for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) + ; + } + return function(x3, y4, dp, rm, base3) { + var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber3( + // Return NaN if either NaN, or both Infinity or 0. + !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber3(s2); + qc = q2.c = []; + e2 = x3.e - y4.e; + s2 = dp + e2 + 1; + if (!base3) { + base3 = BASE2; + e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); + s2 = s2 / LOG_BASE2 | 0; + } + for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) + ; + if (yc[i2] > (xc[i2] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i2 = 0; + s2 += 2; + n3 = mathfloor2(base3 / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base3); + xc = multiply(xc, n3, base3); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base3 / 2) + yc0++; + do { + n3 = 0; + cmp = compare4(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base3 + (rem[1] || 0); + n3 = mathfloor2(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base3) + n3 = base3 - 1; + prod = multiply(yc, n3, base3); + prodL = prod.length; + remL = rem.length; + while (compare4(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base3); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base3); + remL = rem.length; + if (cmp == -1) { + while (compare4(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base3); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i2++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base3 == BASE2) { + for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) + ; + round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format(n3, i2, rm, id) { + var c0, e2, ne, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne = n3.e; + if (i2 == null) { + str = coeffToString2(n3.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); + } else { + n3 = round(new BigNumber3(n3), i2, rm); + e2 = n3.e; + str = coeffToString2(n3.c); + len = str.length; + if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { + for (; len < i2; str += "0", len++) + ; + str = toExponential2(str, e2); + } else { + i2 -= ne; + str = toFixedPoint2(str, e2, "0"); + if (e2 + 1 > len) { + if (--i2 > 0) + for (str += "."; i2--; str += "0") + ; + } else { + i2 += e2 - len; + if (i2 > 0) { + if (e2 + 1 == len) + str += "."; + for (; i2--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, n3) { + var k4, y4, i2 = 1, x3 = new BigNumber3(args[0]); + for (; i2 < args.length; i2++) { + y4 = new BigNumber3(args[i2]); + if (!y4.s || (k4 = compare3(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { + x3 = y4; + } + } + return x3; + } + function normalise(n3, c4, e2) { + var i2 = 1, j2 = c4.length; + for (; !c4[--j2]; c4.pop()) + ; + for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) + ; + if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e2 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e2; + n3.c = c4; + } + return n3; + } + parseNumeric = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b4) { + var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m3, p1, p22) { + base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; + return !b4 || b4 == base3 ? p1 : m3; + }); + if (b4) { + base3 = b4; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber3(s2, base3); + } + if (BigNumber3.DEBUG) { + throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm, r) { + var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; + if (xc) { + out: { + for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) + ; + i2 = sd - d3; + if (i2 < 0) { + i2 += LOG_BASE2; + j2 = sd; + n3 = xc[ni = 0]; + rd = mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); + } else { + ni = mathceil2((i2 + 1) / LOG_BASE2); + if (ni >= xc.length) { + if (r) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d3 = 1; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + 1; + } else { + break out; + } + } else { + n3 = k4 = xc[ni]; + for (d3 = 1; k4 >= 10; k4 /= 10, d3++) + ; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + d3; + rd = j2 < 0 ? 0 : mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); + } + } + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i2 == 0) { + xc.length = ni; + k4 = 1; + ni--; + } else { + xc.length = ni + 1; + k4 = pows10[LOG_BASE2 - i2]; + xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; + } + if (r) { + for (; ; ) { + if (ni == 0) { + for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) + ; + j2 = xc[0] += k4; + for (k4 = 1; j2 >= 10; j2 /= 10, k4++) + ; + if (i2 != k4) { + x3.e++; + if (xc[0] == BASE2) + xc[0] = 1; + } + break; + } else { + xc[ni] += k4; + if (xc[ni] != BASE2) + break; + xc[ni--] = 0; + k4 = 1; + } + } + } + for (i2 = xc.length; xc[--i2] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n3) { + var str, e2 = n3.e; + if (e2 === null) + return n3.toString(); + str = coeffToString2(n3.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber3(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c4, n3, v2, x3 = this; + if (dp != null) { + intCheck2(dp, 0, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), dp + x3.e + 1, rm); + } + if (!(c4 = x3.c)) + return null; + n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; + if (v2 = c4[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m3) { + var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; + n3 = new BigNumber3(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); + } + if (m3 != null) + m3 = new BigNumber3(m3); + nIsBig = n3.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { + y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd2(n3)) : +valueOf(n3))); + return m3 ? y4.mod(m3) : y4; + } + nIsNeg = n3.s < 0; + if (m3) { + if (m3.c ? !m3.c[0] : !m3.s) + return new BigNumber3(NaN); + isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); + if (isModExp) + x3 = x3.mod(m3); + } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { + k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; + if (x3.e > -1) + k4 = 1 / k4; + return new BigNumber3(nIsNeg ? 1 / k4 : k4); + } else if (POW_PRECISION) { + k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); + } + if (nIsBig) { + half = new BigNumber3(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd2(n3); + } else { + i2 = Math.abs(+valueOf(n3)); + nIsOdd = i2 % 2; + } + y4 = new BigNumber3(ONE); + for (; ; ) { + if (nIsOdd) { + y4 = y4.times(x3); + if (!y4.c) + break; + if (k4) { + if (y4.c.length > k4) + y4.c.length = k4; + } else if (isModExp) { + y4 = y4.mod(m3); + } + } + if (i2) { + i2 = mathfloor2(i2 / 2); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd2(n3); + } else { + i2 = +valueOf(n3); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } + } + x3 = x3.times(x3); + if (k4) { + if (x3.c && x3.c.length > k4) + x3.c.length = k4; + } else if (isModExp) { + x3 = x3.mod(m3); + } + } + if (isModExp) + return y4; + if (nIsNeg) + y4 = ONE.div(y4); + return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber3(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y4, b4) { + var i2, j2, t, xLTy, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.plus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (xLTy = a3 < 0) { + a3 = -a3; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); + for (b4 = a3; b4--; t.push(0)) + ; + t.reverse(); + } else { + j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; + for (a3 = b4 = 0; b4 < j2; b4++) { + if (xc[b4] != yc[b4]) { + xLTy = xc[b4] < yc[b4]; + break; + } + } + } + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y4.s = -y4.s; + } + b4 = (j2 = yc.length) - (i2 = xc.length); + if (b4 > 0) + for (; b4--; xc[i2++] = 0) + ; + b4 = BASE2 - 1; + for (; j2 > a3; ) { + if (xc[--j2] < yc[j2]) { + for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) + ; + --xc[i2]; + xc[j2] += BASE2; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y4.s = ROUNDING_MODE == 3 ? -1 : 1; + y4.c = [y4.e = 0]; + return y4; + } + return normalise(y4, xc, ye); + }; + P2.modulo = P2.mod = function(y4, b4) { + var q2, s2, x3 = this; + y4 = new BigNumber3(y4, b4); + if (!x3.c || !y4.s || y4.c && !y4.c[0]) { + return new BigNumber3(NaN); + } else if (!y4.c || x3.c && !x3.c[0]) { + return new BigNumber3(x3); + } + if (MODULO_MODE == 9) { + s2 = y4.s; + y4.s = 1; + q2 = div(x3, y4, 0, 3); + y4.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y4, 0, MODULO_MODE); + } + y4 = x3.minus(q2.times(y4)); + if (!y4.c[0] && MODULO_MODE == 1) + y4.s = x3.s; + return y4; + }; + P2.multipliedBy = P2.times = function(y4, b4) { + var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y4.c = y4.e = y4.s = null; + } else { + y4.s *= x3.s; + if (!xc || !yc) { + y4.c = y4.e = null; + } else { + y4.c = [0]; + y4.e = 0; + } + } + return y4; + } + e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); + y4.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i2 = xcL; + xcL = ycL; + ycL = i2; + } + for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) + ; + base3 = BASE2; + sqrtBase = SQRT_BASE2; + for (i2 = ycL; --i2 >= 0; ) { + c4 = 0; + ylo = yc[i2] % sqrtBase; + yhi = yc[i2] / sqrtBase | 0; + for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { + xlo = xc[--k4] % sqrtBase; + xhi = xc[k4] / sqrtBase | 0; + m3 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; + c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base3; + } + zc[j2] = c4; + } + if (c4) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y4, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber3(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y4, b4) { + var t, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.minus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber3(a3 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (a3 > 0) { + ye = xe; + t = yc; + } else { + a3 = -a3; + t = xc; + } + t.reverse(); + for (; a3--; t.push(0)) + ; + t.reverse(); + } + a3 = xc.length; + b4 = yc.length; + if (a3 - b4 < 0) { + t = yc; + yc = xc; + xc = t; + b4 = a3; + } + for (a3 = 0; b4; ) { + a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; + xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; + } + if (a3) { + xc = [a3].concat(xc); + ++ye; + } + return normalise(y4, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm) { + var c4, n3, v2, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck2(sd, 1, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), sd, rm); + } + if (!(c4 = x3.c)) + return null; + v2 = c4.length - 1; + n3 = v2 * LOG_BASE2 + 1; + if (v2 = c4[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x3.e + 1 > n3) + n3 = x3.e + 1; + return n3; + }; + P2.shiftedBy = function(k4) { + intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); + return this.times("1e" + k4); + }; + P2.squareRoot = P2.sqrt = function() { + var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); + if (s2 !== 1 || !c4 || !c4[0]) { + return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString2(c4); + if ((n3.length + e2) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e2; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; + } + r = new BigNumber3(n3); + } else { + r = new BigNumber3(s2 + ""); + } + if (r.c[0]) { + e2 = r.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t = r; + r = half.times(t.plus(div(x3, t, dp, 1))); + if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { + if (r.e < e2) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + if (t.times(t).eq(x3)) { + r = t; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m3 = !r.times(r).eq(x3); + } + break; + } + } + } + } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp++; + } + return format(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format2) { + var str, x3 = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError2 + "Argument not an object: " + format2); + } + str = x3.toFixed(dp, rm); + if (x3.c) { + var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) { + i2 = g1; + g1 = g22; + g22 = i2; + len -= i2; + } + if (g1 > 0 && len > 0) { + i2 = len % g1 || g1; + intPart = intDigits.substr(0, i2); + for (; i2 < len; i2 += g1) + intPart += groupSeparator + intDigits.substr(i2, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i2); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format2.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P2.toFraction = function(md) { + var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; + if (md != null) { + n3 = new BigNumber3(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber3(x3); + d3 = new BigNumber3(ONE); + n1 = d0 = new BigNumber3(ONE); + d1 = n0 = new BigNumber3(ONE); + s2 = coeffToString2(xc); + e2 = d3.e = s2.length - x3.e - 1; + d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; + md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber3(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d3, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d3 = n3.minus(q2.times(d22 = d3)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( + div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck2(sd, 1, MAX2); + return format(this, sd, rm, 2); + }; + P2.toString = function(b4) { + var str, n3 = this, s2 = n3.s, e2 = n3.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b4 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); + } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { + n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + if (configObject != null) + BigNumber3.set(configObject); + return BigNumber3; + } + function bitFloor2(n3) { + var i2 = n3 | 0; + return n3 > 0 || n3 === i2 ? i2 : i2 - 1; + } + function coeffToString2(a3) { + var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; + for (; i2 < j2; ) { + s2 = a3[i2++] + ""; + z3 = LOG_BASE2 - s2.length; + for (; z3--; s2 = "0" + s2) + ; + r += s2; + } + for (j2 = r.length; r.charCodeAt(--j2) === 48; ) + ; + return r.slice(0, j2 + 1 || 1); + } + function compare3(x3, y4) { + var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; + if (!i2 || !j2) + return null; + a3 = xc && !xc[0]; + b4 = yc && !yc[0]; + if (a3 || b4) + return a3 ? b4 ? 0 : -j2 : i2; + if (i2 != j2) + return i2; + a3 = i2 < 0; + b4 = k4 == l4; + if (!xc || !yc) + return b4 ? 0 : !xc ^ a3 ? 1 : -1; + if (!b4) + return k4 > l4 ^ a3 ? 1 : -1; + j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; + for (i2 = 0; i2 < j2; i2++) + if (xc[i2] != yc[i2]) + return xc[i2] > yc[i2] ^ a3 ? 1 : -1; + return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; + } + function intCheck2(n3, min, max, name2) { + if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { + throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } + } + function isOdd2(n3) { + var k4 = n3.c.length - 1; + return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; + } + function toExponential2(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + function toFixedPoint2(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + "."; ++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len; --e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; + } + BigNumber2 = clone2(); + BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; + if (typeof define == "function" && define.amd) { + define(function() { + return BigNumber2; + }); + } else if (typeof module2 != "undefined" && module2.exports) { + module2.exports = BigNumber2; + } else { + if (!globalObject) { + globalObject = typeof self != "undefined" && self ? self : window; + } + globalObject.BigNumber = BigNumber2; + } + })(exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/errors.js +var require_errors = __commonJS({ + "node_modules/@multiversx/sdk-core/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrParseTransactionOutcome = exports2.ErrInvalidInnerTransaction = exports2.ErrBadUsage = exports2.ErrInvalidTokenIdentifier = exports2.ErrIsCompletedFieldIsMissingOnTransaction = exports2.ErrGasLimitShouldBe0ForInnerTransaction = exports2.ErrInvalidRelayedV2BuilderArguments = exports2.ErrInvalidRelayedV1BuilderArguments = exports2.ErrNotImplemented = exports2.ErrContractInteraction = exports2.ErrCodec = exports2.ErrCannotParseTransactionOutcome = exports2.ErrCannotParseContractResults = exports2.ErrMissingFieldOnEnum = exports2.ErrMissingFieldOnStruct = exports2.ErrTypingSystem = exports2.ErrMock = exports2.ErrContractHasNoAddress = exports2.ErrContract = exports2.ErrExpectedTransactionEventsNotFound = exports2.ErrExpectedTransactionStatusNotReached = exports2.ErrTransactionWatcherTimeout = exports2.ErrAsyncTimerAborted = exports2.ErrAsyncTimerAlreadyRunning = exports2.ErrInvalidFunctionName = exports2.ErrSignatureCannotCreate = exports2.ErrTransactionOptionsInvalid = exports2.ErrTransactionVersionInvalid = exports2.ErrNonceInvalid = exports2.ErrNotEnoughGas = exports2.ErrAddressEmpty = exports2.ErrAddressBadHrp = exports2.ErrAddressCannotCreate = exports2.ErrUnexpectedCondition = exports2.ErrInvariantFailed = exports2.ErrBadType = exports2.ErrUnsupportedOperation = exports2.ErrInvalidArgument = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + /** + * Returns a pretty, friendly summary for the error or for the chain of errros (if appropriate). + */ + summary() { + let result = []; + result.push({ name: this.name, message: this.message }); + let inner = this.inner; + while (inner) { + result.push({ name: inner.name, message: inner.message }); + inner = inner.inner; + } + return result; + } + }; + exports2.Err = Err; + var ErrInvalidArgument = class extends Err { + constructor(message, inner) { + super(`Invalid argument: ${message}`, inner); + } + }; + exports2.ErrInvalidArgument = ErrInvalidArgument; + var ErrUnsupportedOperation = class extends Err { + constructor(operation, reason = "not specified") { + super(`Operation "${operation}" not supported. Reason: ${reason}`); + } + }; + exports2.ErrUnsupportedOperation = ErrUnsupportedOperation; + var ErrBadType = class extends Err { + constructor(name2, type, value) { + super(`Bad type of "${name2}": ${value}. Expected type: ${type}`); + } + }; + exports2.ErrBadType = ErrBadType; + var ErrInvariantFailed = class extends Err { + constructor(message) { + super(`Invariant failed: [${message}]`); + } + }; + exports2.ErrInvariantFailed = ErrInvariantFailed; + var ErrUnexpectedCondition = class extends Err { + constructor(message) { + super(`Unexpected condition: [${message}]`); + } + }; + exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; + var ErrAddressCannotCreate = class extends Err { + constructor(input, inner) { + let message = `Cannot create address from: ${input}`; + super(message, inner); + } + }; + exports2.ErrAddressCannotCreate = ErrAddressCannotCreate; + var ErrAddressBadHrp = class extends Err { + constructor(expected, got) { + super(`Wrong address HRP. Expected: ${expected}, got ${got}`); + } + }; + exports2.ErrAddressBadHrp = ErrAddressBadHrp; + var ErrAddressEmpty = class extends Err { + constructor() { + super(`Address is empty`); + } + }; + exports2.ErrAddressEmpty = ErrAddressEmpty; + var ErrNotEnoughGas = class extends Err { + constructor(value) { + super(`Not enough gas provided: ${value}`); + } + }; + exports2.ErrNotEnoughGas = ErrNotEnoughGas; + var ErrNonceInvalid = class extends Err { + constructor(value) { + super(`Invalid nonce: ${value}`); + } + }; + exports2.ErrNonceInvalid = ErrNonceInvalid; + var ErrTransactionVersionInvalid = class extends Err { + constructor(value) { + super(`Invalid transaction version: ${value}`); + } + }; + exports2.ErrTransactionVersionInvalid = ErrTransactionVersionInvalid; + var ErrTransactionOptionsInvalid = class extends Err { + constructor(value) { + super(`Invalid transaction options: ${value}`); + } + }; + exports2.ErrTransactionOptionsInvalid = ErrTransactionOptionsInvalid; + var ErrSignatureCannotCreate = class extends Err { + constructor(input, inner) { + let message = `Cannot create signature from: ${input}`; + super(message, inner); + } + }; + exports2.ErrSignatureCannotCreate = ErrSignatureCannotCreate; + var ErrInvalidFunctionName = class extends Err { + constructor() { + super(`Invalid function name`); + } + }; + exports2.ErrInvalidFunctionName = ErrInvalidFunctionName; + var ErrAsyncTimerAlreadyRunning = class extends Err { + constructor() { + super("Async timer already running"); + } + }; + exports2.ErrAsyncTimerAlreadyRunning = ErrAsyncTimerAlreadyRunning; + var ErrAsyncTimerAborted = class extends Err { + constructor() { + super("Async timer aborted"); + } + }; + exports2.ErrAsyncTimerAborted = ErrAsyncTimerAborted; + var ErrTransactionWatcherTimeout = class extends Err { + constructor() { + super(`TransactionWatcher has timed out`); + } + }; + exports2.ErrTransactionWatcherTimeout = ErrTransactionWatcherTimeout; + var ErrExpectedTransactionStatusNotReached = class extends Err { + constructor() { + super(`Expected transaction status not reached`); + } + }; + exports2.ErrExpectedTransactionStatusNotReached = ErrExpectedTransactionStatusNotReached; + var ErrExpectedTransactionEventsNotFound = class extends Err { + constructor() { + super(`Expected transaction events not found`); + } + }; + exports2.ErrExpectedTransactionEventsNotFound = ErrExpectedTransactionEventsNotFound; + var ErrContract = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrContract = ErrContract; + var ErrContractHasNoAddress = class extends ErrContract { + constructor() { + super(` The smart contract has no address set. Make sure you provide the address in the constructor, or call setAddress() appropriately. If you need to recompute the address of the contract, make use of SmartContract.computeAddress() (static method). -`)}};pe.ErrContractHasNoAddress=Sm;var Tm=class extends Pe{constructor(e){super(e)}};pe.ErrMock=Tm;var Cm=class extends Pe{constructor(e){super(e)}};pe.ErrTypingSystem=Cm;var xm=class extends Pe{constructor(e,r){super(`field ${e} does not exist on struct ${r}`)}};pe.ErrMissingFieldOnStruct=xm;var Nm=class extends Pe{constructor(e,r){super(`field ${e} does not exist on enum ${r}`)}};pe.ErrMissingFieldOnEnum=Nm;var Om=class extends Pe{constructor(e){super(`cannot parse contract results: ${e}`)}};pe.ErrCannotParseContractResults=Om;var Dm=class extends Pe{constructor(e,r){super(`cannot parse outcome of transaction ${e}: ${r}`)}};pe.ErrCannotParseTransactionOutcome=Dm;var Pm=class extends Pe{constructor(e){super(e)}};pe.ErrCodec=Pm;var Rm=class extends Pe{constructor(e){super(e)}};pe.ErrContractInteraction=Rm;var Bm=class extends Pe{constructor(){super("Method not yet implemented")}};pe.ErrNotImplemented=Bm;var Lm=class extends Pe{constructor(){super("invalid arguments for relayed v1 builder")}};pe.ErrInvalidRelayedV1BuilderArguments=Lm;var Fm=class extends Pe{constructor(){super("invalid arguments for relayed v2 builder")}};pe.ErrInvalidRelayedV2BuilderArguments=Fm;var Mm=class extends Pe{constructor(){super("gas limit must be 0 for the inner transaction for relayed v2")}};pe.ErrGasLimitShouldBe0ForInnerTransaction=Mm;var Um=class extends Pe{constructor(){super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`.")}};pe.ErrIsCompletedFieldIsMissingOnTransaction=Um});var Vm=v(Ei=>{"use strict";l();var g5=Ei&&Ei.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ei,"__esModule",{value:!0});Ei.TokenPayment=Ei.TokenTransfer=void 0;var ju=g5(Yt()),y5=Le(),$S="EGLD",KS=18;ju.default.set({ROUNDING_MODE:1});var Tf=class t{constructor(e){let r=new ju.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new y5.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0}static egldFromAmount(e){let r=new ju.default(e).shiftedBy(KS).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:$S,nonce:0,amountAsBigInteger:e,numDecimals:KS})}static fungibleFromAmount(e,r,n){let i=new ju.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new ju.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amountAsBigInteger.toFixed(0)}valueOf(){return this.amountAsBigInteger}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.tokenIdentifier==$S}isFungible(){return this.nonce==0}};Ei.TokenTransfer=Tf;var qm=class extends Tf{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};Ei.TokenPayment=qm});var Ns=v(Xe=>{"use strict";l();Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ARGUMENTS_SEPARATOR=Xe.ESDT_TRANSFER_VALUE=Xe.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Xe.ESDTNFT_TRANSFER_FUNCTION_NAME=Xe.ESDT_TRANSFER_FUNCTION_NAME=Xe.ESDT_TRANSFER_GAS_LIMIT=Xe.TRANSACTION_VERSION_WITH_OPTIONS=Xe.TRANSACTION_VERSION_DEFAULT=Xe.TRANSACTION_OPTIONS_TX_GUARDED=Xe.TRANSACTION_OPTIONS_TX_HASH_SIGN=Xe.TRANSACTION_OPTIONS_DEFAULT=Xe.TRANSACTION_MIN_GAS_PRICE=void 0;Xe.TRANSACTION_MIN_GAS_PRICE=1e9;Xe.TRANSACTION_OPTIONS_DEFAULT=0;Xe.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Xe.TRANSACTION_OPTIONS_TX_GUARDED=2;Xe.TRANSACTION_VERSION_DEFAULT=1;Xe.TRANSACTION_VERSION_WITH_OPTIONS=2;Xe.ESDT_TRANSFER_GAS_LIMIT=5e5;Xe.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Xe.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Xe.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Xe.ESDT_TRANSFER_VALUE="0";Xe.ARGUMENTS_SEPARATOR="@"});var br=v(ot=>{"use strict";l();var m5=ot&&ot.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),w5=ot&&ot.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),E5=ot&&ot.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&m5(e,t,r);return w5(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.isEmpty=ot.guardEmpty=ot.guardNotEmpty=ot.guardLength=ot.guardSameLength=ot.guardValueIsSetWithMessage=ot.guardValueIsSet=ot.guardTrue=void 0;var Do=E5(Le());function v5(t,e){if(!t)throw new Do.ErrInvariantFailed(`[<${e}>] isn't true`)}ot.guardTrue=v5;function A5(t,e){YS(`${t} isn't set (null or undefined)`,e)}ot.guardValueIsSet=A5;function YS(t,e){if(e==null||e===void 0)throw new Do.ErrInvariantFailed(t)}ot.guardValueIsSetWithMessage=YS;function b5(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new Do.ErrInvariantFailed("arrays do not have the same length")}ot.guardSameLength=b5;function I5(t,e){let r=t.length||0;if(r!=e)throw new Do.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}ot.guardLength=I5;function _5(t,e){if(Hm(t))throw new Do.ErrInvariantFailed(`${e} is empty`)}ot.guardNotEmpty=_5;function S5(t,e){if(!Hm(t))throw new Do.ErrInvariantFailed(`${e} is not empty`)}ot.guardEmpty=S5;function Hm(t){return t.isEmpty?t.isEmpty():t.length===0}ot.isEmpty=Hm});var JS=v(Cf=>{"use strict";l();Object.defineProperty(Cf,"__esModule",{value:!0});Cf.getJavascriptPrototypesInHierarchy=void 0;function T5(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}Cf.getJavascriptPrototypesInHierarchy=T5});var Ct=v(Tt=>{"use strict";l();Object.defineProperty(Tt,"__esModule",{value:!0});Tt.NullType=Tt.TypePlaceholder=Tt.isTyped=Tt.PrimitiveValue=Tt.TypedValue=Tt.CustomType=Tt.PrimitiveType=Tt.TypeCardinality=Tt.Type=void 0;var km=JS(),XS=br(),vi=class t{constructor(e,r=[],n=Qu.fixed(1)){XS.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return km.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return XS.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return km.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};Tt.Type=vi;vi.ClassName="Type";var Qu=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};Tt.TypeCardinality=Qu;Qu.MaxCardinality=4096;var xf=class t extends vi{constructor(e){super(e)}getClassName(){return t.ClassName}};Tt.PrimitiveType=xf;xf.ClassName="PrimitiveType";var Nf=class t extends vi{getClassName(){return t.ClassName}};Tt.CustomType=Nf;Nf.ClassName="CustomType";var zu=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return km.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};Tt.TypedValue=zu;zu.ClassName="TypedValue";var Of=class t extends zu{constructor(e){super(e)}getClassName(){return t.ClassName}};Tt.PrimitiveValue=Of;Of.ClassName="PrimitiveValue";function C5(t){return t.belongsToTypesystem!==void 0}Tt.isTyped=C5;var Df=class t extends vi{constructor(){super("...")}getClassName(){return t.ClassName}};Tt.TypePlaceholder=Df;Df.ClassName="TypePlaceholder";var Pf=class t extends vi{constructor(){super("?")}getClassName(){return t.ClassName}};Tt.NullType=Pf;Pf.ClassName="NullType"});var ZS=v((Po,Ro)=>{l();(function(t){var e=typeof Po=="object"&&Po&&!Po.nodeType&&Po,r=typeof Ro=="object"&&Ro&&!Ro.nodeType&&Ro,n=typeof global=="object"&&global;(n.global===n||n.window===n||n.self===n)&&(t=n);var i,s=2147483647,o=36,a=1,u=26,c=38,f=700,d=72,g=128,m="-",y=/^xn--/,A=/[^\x20-\x7E]/,O=/[\x2E\u3002\uFF0E\uFF61]/g,R={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},q=o-a,M=Math.floor,b=String.fromCharCode,S;function N(J){throw new RangeError(R[J])}function _(J,oe){for(var re=J.length,se=[];re--;)se[re]=oe(J[re]);return se}function T(J,oe){var re=J.split("@"),se="";re.length>1&&(se=re[0]+"@",J=re[1]),J=J.replace(O,".");var U=J.split("."),fe=_(U,oe).join(".");return se+fe}function B(J){for(var oe=[],re=0,se=J.length,U,fe;re=55296&&U<=56319&&re65535&&(oe-=65536,re+=b(oe>>>10&1023|55296),oe=56320|oe&1023),re+=b(oe),re}).join("")}function z(J){return J-48<10?J-22:J-65<26?J-65:J-97<26?J-97:o}function k(J,oe){return J+22+75*(J<26)-((oe!=0)<<5)}function Q(J,oe,re){var se=0;for(J=re?M(J/f):J>>1,J+=M(J/oe);J>q*u>>1;se+=o)J=M(J/q);return M(se+(q+1)*J/(J+c))}function K(J){var oe=[],re=J.length,se,U=0,fe=g,ue=d,de,ae,le,w,E,I,P,C,D;for(de=J.lastIndexOf(m),de<0&&(de=0),ae=0;ae=128&&N("not-basic"),oe.push(J.charCodeAt(ae));for(le=de>0?de+1:0;le=re&&N("invalid-input"),P=z(J.charCodeAt(le++)),(P>=o||P>M((s-U)/E))&&N("overflow"),U+=P*E,C=I<=ue?a:I>=ue+u?u:I-ue,!(PM(s/D)&&N("overflow"),E*=D;se=oe.length+1,ue=Q(U-w,se,w==0),M(U/se)>s-fe&&N("overflow"),fe+=M(U/se),U%=se,oe.splice(U++,0,fe)}return X(oe)}function ye(J){var oe,re,se,U,fe,ue,de,ae,le,w,E,I=[],P,C,D,L;for(J=B(J),P=J.length,oe=g,re=0,fe=d,ue=0;ue=oe&&EM((s-re)/C)&&N("overflow"),re+=(de-oe)*C,oe=de,ue=0;ues&&N("overflow"),E==oe){for(ae=re,le=o;w=le<=fe?a:le>=fe+u?u:le-fe,!(ae{"use strict";l();var tT=ZS();function x5(t,e){this.__proto__=new Error(e),this.__proto__.name="BackslashError",this.offset=t}function Gm(t){return t>="0"&&t<="7"}function N5(t){return t>="0"&&t<="9"||t>="a"&&t<="f"||t>="A"&&t<="F"}function eT(t){return t=parseInt(t,16),tT.ucs2.encode([t])}function rT(t,e,r){var n=!1,i=[];function s(u){var c=t[u];if(!N5(c))throw new x5(u,"Unexpected token ILLEGAL");return c}for(;e{l();var oT=nT();cT.exports={validate:O5,parse:D5};function O5(t,e){var r;if(e=e||!1,typeof t!="string")r="Input must be a string";else try{Rf(t,0,e,!1)}catch(n){r=n.message}return r}function D5(t,e){if(typeof t!="string")throw new Error("Input must be a string");e=e||!1;var r=Rf(t,0,e,!0);return r.value}function aT(t,e){for(var r=t.length,n=e,i,s=e;s-1&&t[r]==="\\";)n++,r--;return n%2===0}function L5(t,e,r,n){for(var i=e,s=",",o=[],a=e;Os(t[a]);)a++;if(t[a]==="]")return{start:e,end:a,value:o};for(;s===",";){var u=Rf(t,i,r,n),c=aT(t,u.end);n&&o.push(u.value),i=c.end,s=c.value}return{start:e,end:i,value:o}}function F5(t,e){return t.substr(e,4)==="true"}function M5(t,e){return t.substr(e,5)==="false"}function U5(t,e){return t.substr(e,4)==="null"}var q5=new RegExp(/^\s$/);function Os(t){return q5.test(t)}var V5=new RegExp(/^\d$/);function iT(t){return V5.test(t)}function Kn(t,e,r){var n=10,i;t.length{"use strict";l();var H5=cn&&cn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),k5=cn&&cn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),G5=cn&&cn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H5(e,t,r);return k5(e,t),e};Object.defineProperty(cn,"__esModule",{value:!0});cn.TypeExpressionParser=void 0;var fT=G5(Le()),j5=Ct(),Q5=lT(),Qm=class{parse(e){let r=this.doParse(e),n=Object.keys(r);if(n.length!=1)throw new fT.ErrTypingSystem(`bad type expression: ${e}`);let i=n[0];return this.nodeToType(i,r[i])}doParse(e){let r=this.getJsonedString(e);try{return Q5.parse(r)}catch{throw new fT.ErrTypingSystem(`cannot parse type expression: ${e}. internal json: ${r}.`)}}getJsonedString(e){let r="";for(var n=0;n"?a!=">"?r+=": {} }":r+="}":o==","?u==">"||(a==">"?r+=",":r+=": {},"):r+=o}let i=/(:|\{|\}|,|\s)/,s=r.replace(/utf\-8\sstring/ig,"utf-8-string").split(i).filter(o=>o);return r=s.map(o=>i.test(o)?o:`"${o}"`).map(o=>o.replace(/utf\-8\-string/ig,"utf-8 string")).join(""),s.length==1?`{${r}: {}}`:`{${r}}`}nodeToType(e,r){e.charAt(e.length-1)==="1"&&(e=e.slice(0,-1));let n=Object.keys(r).map(i=>this.nodeToType(i,r[i]));return new j5.Type(e,n)}};cn.TypeExpressionParser=Qm});var Wm=v(Ai=>{"use strict";l();Object.defineProperty(Ai,"__esModule",{value:!0});Ai.EndpointParameterDefinition=Ai.EndpointModifiers=Ai.EndpointDefinition=void 0;var z5=Wu(),dT="?",W5="N / A",zm=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?dT:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>$u.fromJSON(s)),n=e.outputs.map(s=>$u.fromJSON(s)),i=new Bf(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};Ai.EndpointDefinition=zm;var Bf=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};Ai.EndpointModifiers=Bf;var $u=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new z5.TypeExpressionParser().parse(e.type);return new t(e.name||dT,e.description||W5,r)}};Ai.EndpointParameterDefinition=$u});var Bo=v(fr=>{"use strict";l();var $5=fr&&fr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),K5=fr&&fr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Y5=fr&&fr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$5(e,t,r);return K5(e,t),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.Fields=fr.Field=fr.FieldDefinition=void 0;var $m=Y5(Le()),J5=Wu(),Km=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new J5.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};fr.FieldDefinition=Km;var Ym=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new $m.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new $m.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};fr.Field=Ym;var Jm=class{static checkTyping(e,r){if(e.length!=r.length)throw new $m.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";l();Object.defineProperty(bi,"__esModule",{value:!0});bi.EnumValue=bi.EnumVariantDefinition=bi.EnumType=void 0;var X5=Le(),Xm=br(),Lf=Bo(),pT=Ct(),hT=256,Ff=class t extends pT.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>Mf.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>Object.assign(Object.assign({},n),{discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return Xm.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return Xm.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};bi.EnumType=Ff;Ff.ClassName="EnumType";var Mf=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],Xm.guardTrue(rLf.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Lf.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};bi.EnumVariantDefinition=Mf;var Uf=class t extends pT.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();Lf.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=Lf.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new X5.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};bi.EnumValue=Uf;Uf.ClassName="EnumValue"});var yT=v(Lo=>{"use strict";l();Object.defineProperty(Lo,"__esModule",{value:!0});Lo.EventTopicDefinition=Lo.EventDefinition=void 0;var Z5=Wu(),gT="?",Zm=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?gT:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>qf.fromJSON(n));return new t(e.identifier,r)}};Lo.EventDefinition=Zm;var qf=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Z5.TypeExpressionParser().parse(e.type);return new t({name:e.name||gT,type:r,indexed:e.indexed})}};Lo.EventTopicDefinition=qf});var Mo=v(Fo=>{"use strict";l();Object.defineProperty(Fo,"__esModule",{value:!0});Fo.Struct=Fo.StructType=void 0;var eq=Le(),Vf=Bo(),mT=Ct(),Hf=class t extends mT.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>Vf.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Vf.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Fo.StructType=Hf;Hf.ClassName="StructType";var kf=class t extends mT.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();Vf.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new eq.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return Vf.Fields.equals(r,n)}};Fo.Struct=kf;kf.ClassName="Struct"});var tw=v((Coe,vT)=>{"use strict";l();var jf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ew={};for(Yu=0;Yu>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function wT(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Uo(e)^n>>5}for(e=Uo(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=wT(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Uo(n)^o,i+=jf.charAt(o)}for(s=0;s<6;++s)n=Uo(n);for(n^=1,s=0;s<6;++s){var a=n>>(5-s)*5&31;i+=jf.charAt(a)}return i}function ET(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var a=wT(s);if(typeof a=="string")return a;for(var u=[],c=0;c=o.length)&&u.push(d)}return a!==1?"Invalid checksum for "+t:{prefix:s,words:u}}function rq(){var t=ET.apply(null,arguments);if(typeof t=="object")return t}function nq(t){var e=ET.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function Qf(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<=e)return"Excess padding";if(i<{"use strict";l();var uq=ln&&ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),cq=ln&&ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),AT=ln&&ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&uq(e,t,r);return cq(e,t),e};Object.defineProperty(ln,"__esModule",{value:!0});ln.Address=void 0;var qo=AT(tw()),Vo=AT(Le()),zf="erd",Wf=32,lq="0".repeat(16),rw=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(e instanceof h.Buffer)return t.fromBuffer(e);if(typeof e=="string")return t.fromString(e);throw new Vo.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=Wf)throw new Vo.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return h.Buffer.from(e,"hex").length==Wf}static fromHex(e){if(!t.isValidHex(e))throw new Vo.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t}static fromBech32(e){let r;try{r=qo.decode(e)}catch(s){throw new Vo.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=zf)throw new Vo.ErrAddressBadHrp(zf,n);let i=h.Buffer.from(qo.fromWords(r.words));if(i.length!=Wf)throw new Vo.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=qo.decodeUnsafe(e),n=r?.prefix,i=r?h.Buffer.from(qo.fromWords(r.words)):void 0;return!(n!==zf||i?.length!==Wf)}hex(){return this.isEmpty()?"":this.valueHex}bech32(){if(this.isEmpty())return"";let e=qo.toWords(this.pubkey());return qo.encode(zf,e)}pubkey(){return this.isEmpty()?h.Buffer.from([]):h.Buffer.from(this.valueHex,"hex")}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.bech32()}toJSON(){return{bech32:this.bech32(),pubkey:this.hex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.hex().startsWith(lq)}};ln.Address=rw});var ko=v(Ho=>{"use strict";l();Object.defineProperty(Ho,"__esModule",{value:!0});Ho.AddressValue=Ho.AddressType=void 0;var fq=pt(),bT=Ct(),Ju=class t extends bT.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};Ho.AddressType=Ju;Ju.ClassName="AddressType";var $f=class t extends bT.PrimitiveValue{constructor(e){super(new Ju),this.value=new fq.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};Ho.AddressValue=$f;$f.ClassName="AddressValue"});var Yf=v(Go=>{"use strict";l();Object.defineProperty(Go,"__esModule",{value:!0});Go.OptionalValue=Go.OptionalType=void 0;var dq=br(),Xu=Ct(),Zu=class t extends Xu.Type{constructor(e){super("Optional",[e],Xu.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Xu.NullType.ClassName);return r||n}};Go.OptionalType=Zu;Zu.ClassName="OptionalType";var Kf=class t extends Xu.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new Zu(new Xu.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return dq.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){var r;return((r=this.value)===null||r===void 0?void 0:r.equals(e.value))||!1}};Go.OptionalValue=Kf;Kf.ClassName="OptionalValue"});var tc=v(jo=>{"use strict";l();Object.defineProperty(jo,"__esModule",{value:!0});jo.BooleanValue=jo.BooleanType=void 0;var IT=Ct(),ec=class t extends IT.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};jo.BooleanType=ec;ec.ClassName="BooleanType";var Jf=class t extends IT.PrimitiveValue{constructor(e){super(new ec),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};jo.BooleanValue=Jf;Jf.ClassName="BooleanValue"});var Ii=v(Qo=>{"use strict";l();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.BytesValue=Qo.BytesType=void 0;var _T=Ct(),rc=class t extends _T.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Qo.BytesType=rc;rc.ClassName="BytesType";var Xf=class t extends _T.PrimitiveValue{constructor(e){super(new rc),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=h.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=h.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Qo.BytesValue=Xf;Xf.ClassName="BytesValue"});var TT=v(zo=>{"use strict";l();Object.defineProperty(zo,"__esModule",{value:!0});zo.CodeMetadataValue=zo.CodeMetadataType=void 0;var ST=Ct(),Zf=class extends ST.PrimitiveType{constructor(){super("CodeMetadata")}};zo.CodeMetadataType=Zf;var nw=class extends ST.PrimitiveValue{constructor(e){super(new Zf),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};zo.CodeMetadataValue=nw});var td=v(Wo=>{"use strict";l();Object.defineProperty(Wo,"__esModule",{value:!0});Wo.CompositeValue=Wo.CompositeType=void 0;var hq=br(),iw=Ct(),nc=class t extends iw.Type{constructor(...e){super("Composite",e,iw.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};Wo.CompositeType=nc;nc.ClassName="CompositeType";var ed=class t extends iw.TypedValue{constructor(e,r){super(e),hq.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new nc(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";l();Object.defineProperty(rd,"__esModule",{value:!0});rd.CollectionOfTypedValues=void 0;var sw=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";l();Object.defineProperty(fn,"__esModule",{value:!0});fn.List=fn.OptionValue=fn.ListType=fn.OptionType=void 0;var pq=br(),gq=ow(),Ps=Ct(),Ds=class t extends Ps.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Ps.NullType.ClassName);return r||n}};fn.OptionType=Ds;Ds.ClassName="OptionType";var ic=class t extends Ps.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};fn.ListType=ic;ic.ClassName="ListType";var nd=class t extends Ps.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new Ds(new Ps.NullType);return new t(e)}static newMissingTyped(e){return new t(new Ds(e))}static newProvided(e){let r=new Ds(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return pq.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){var r;return((r=this.value)===null||r===void 0?void 0:r.equals(e.value))||!1}};fn.OptionValue=nd;nd.ClassName="OptionValue";var id=class t extends Ps.TypedValue{constructor(e,r){super(e),this.backingCollection=new gq.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new Ps.TypePlaceholder,[]);let r=e[0].getType(),n=new ic(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};fn.List=id;id.ClassName="List"});var ad=v($o=>{"use strict";l();Object.defineProperty($o,"__esModule",{value:!0});$o.ArrayVec=$o.ArrayVecType=void 0;var CT=br(),yq=ow(),xT=Ct(),sd=class t extends xT.Type{constructor(e,r){super("Array",[r]),CT.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};$o.ArrayVecType=sd;sd.ClassName="ArrayVecType";var od=class t extends xT.TypedValue{constructor(e,r){super(e),CT.guardLength(r,e.length),this.backingCollection=new yq.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};$o.ArrayVec=od;od.ClassName="ArrayVec"});var ac=v(Ko=>{"use strict";l();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.H256Value=Ko.H256Type=void 0;var NT=Ct(),oc=class t extends NT.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};Ko.H256Type=oc;oc.ClassName="H256Type";var ud=class t extends NT.PrimitiveValue{constructor(e){super(new oc),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};Ko.H256Value=ud;ud.ClassName="H256Value"});var ld=v(Yo=>{"use strict";l();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.NothingValue=Yo.NothingType=void 0;var OT=Ct(),uc=class t extends OT.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};Yo.NothingType=uc;uc.ClassName="NothingType";var cd=class t extends OT.PrimitiveValue{constructor(){super(new uc)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};Yo.NothingValue=cd;cd.ClassName="NothingValue"});var Ec=v(Ce=>{"use strict";l();var mq=Ce&&Ce.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wq=Ce&&Ce.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Eq=Ce&&Ce.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mq(e,t,r);return wq(e,t),e},vq=Ce&&Ce.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ce,"__esModule",{value:!0});Ce.BigIntValue=Ce.BigUIntValue=Ce.I64Value=Ce.U64Value=Ce.I32Value=Ce.U32Value=Ce.I16Value=Ce.U16Value=Ce.I8Value=Ce.U8Value=Ce.NumericalValue=Ce.BigIntType=Ce.BigUIntType=Ce.I64Type=Ce.U64Type=Ce.I32Type=Ce.U32Type=Ce.I16Type=Ce.U16Type=Ce.I8Type=Ce.U8Type=Ce.NumericalType=void 0;var DT=Eq(Le()),PT=Ct(),Rs=vq(Yt()),dr=class t extends PT.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ce.NumericalType=dr;dr.ClassName="NumericalType";var cc=class t extends dr{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ce.U8Type=cc;cc.ClassName="U8Type";var lc=class t extends dr{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ce.I8Type=lc;lc.ClassName="I8Type";var fc=class t extends dr{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ce.U16Type=fc;fc.ClassName="U16Type";var dc=class t extends dr{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ce.I16Type=dc;dc.ClassName="I16Type";var hc=class t extends dr{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ce.U32Type=hc;hc.ClassName="U32Type";var pc=class t extends dr{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ce.I32Type=pc;pc.ClassName="I32Type";var gc=class t extends dr{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ce.U64Type=gc;gc.ClassName="U64Type";var yc=class t extends dr{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ce.I64Type=yc;yc.ClassName="I64Type";var mc=class t extends dr{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ce.BigUIntType=mc;mc.ClassName="BigUIntType";var wc=class t extends dr{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ce.BigIntType=wc;wc.ClassName="BigIntType";var hr=class t extends PT.PrimitiveValue{constructor(e,r){if(super(e),this.value=new Rs.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new DT.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new DT.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ce.NumericalValue=hr;hr.ClassName="NumericalValue";var fd=class t extends hr{constructor(e){super(new cc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.U8Value=fd;fd.ClassName="U8Value";var dd=class t extends hr{constructor(e){super(new lc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.I8Value=dd;dd.ClassName="I8Value";var hd=class t extends hr{constructor(e){super(new fc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.U16Value=hd;hd.ClassName="U16Value";var pd=class t extends hr{constructor(e){super(new dc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.I16Value=pd;pd.ClassName="I16Value";var gd=class t extends hr{constructor(e){super(new hc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.U32Value=gd;gd.ClassName="U32Value";var yd=class t extends hr{constructor(e){super(new pc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.I32Value=yd;yd.ClassName="I32Value";var md=class t extends hr{constructor(e){super(new gc,e)}getClassName(){return t.ClassName}};Ce.U64Value=md;md.ClassName="U64Value";var wd=class t extends hr{constructor(e){super(new yc,e)}getClassName(){return t.ClassName}};Ce.I64Value=wd;wd.ClassName="I64Value";var Ed=class t extends hr{constructor(e){super(new mc,e)}getClassName(){return t.ClassName}};Ce.BigUIntValue=Ed;Ed.ClassName="BigUIntValue";var vd=class t extends hr{constructor(e){super(new wc,e)}getClassName(){return t.ClassName}};Ce.BigIntValue=vd;vd.ClassName="BigIntValue"});var bd=v(Jo=>{"use strict";l();Object.defineProperty(Jo,"__esModule",{value:!0});Jo.StringValue=Jo.StringType=void 0;var RT=Ct(),vc=class t extends RT.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};Jo.StringType=vc;vc.ClassName="StringType";var Ad=class t extends RT.PrimitiveValue{constructor(e){super(new vc),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=h.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};Jo.StringValue=Ad;Ad.ClassName="StringValue"});var Zo=v(Xo=>{"use strict";l();Object.defineProperty(Xo,"__esModule",{value:!0});Xo.TokenIdentifierValue=Xo.TokenIdentifierType=void 0;var BT=Ct(),Aq="EGLD",Ac=class t extends BT.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};Xo.TokenIdentifierType=Ac;Ac.ClassName="TokenIdentifierType";var Id=class t extends BT.PrimitiveValue{constructor(e){super(new Ac),this.value=e}static egld(){return new t(Aq)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};Xo.TokenIdentifierValue=Id;Id.ClassName="TokenIdentifierValue"});var Sd=v(Cr=>{"use strict";l();var bq=Cr&&Cr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Iq=Cr&&Cr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_q=Cr&&Cr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&bq(e,t,r);return Iq(e,t),e};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.Tuple=Cr.TupleType=void 0;var Sq=_q(Le()),LT=Bo(),FT=Mo(),bc=class t extends FT.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new LT.FieldDefinition(MT(i),"anonymous tuple field",n))}};Cr.TupleType=bc;bc.ClassName="TupleType";function MT(t){return`field${t}`}var _d=class t extends FT.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Sq.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new bc(...r),i=e.map((s,o)=>new LT.Field(s,MT(o)));return new t(n,i)}};Cr.Tuple=_d;_d.ClassName="Tuple"});var xd=v(_i=>{"use strict";l();Object.defineProperty(_i,"__esModule",{value:!0});_i.VariadicValue=_i.CountedVariadicType=_i.VariadicType=void 0;var ea=Ct(),Bs=class t extends ea.Type{constructor(e,r=!1){super("Variadic",[e],ea.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};_i.VariadicType=Bs;Bs.ClassName="VariadicType";var Td=class extends ea.Type{constructor(e){super("Variadic",[e],ea.TypeCardinality.variable())}getClassName(){return Bs.ClassName}};_i.CountedVariadicType=Td;Td.ClassName="VariadicType";var Cd=class t extends ea.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Bs(new ea.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Bs(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";l();var Tq=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Cq=hn&&hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xq=hn&&hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Tq(e,t,r);return Cq(e,t),e};Object.defineProperty(hn,"__esModule",{value:!0});hn.TypeMapper=void 0;var UT=xq(Le()),Nq=ko(),aw=Yf(),Oq=tc(),Dq=Ii(),Pq=TT(),Nd=td(),uw=Ku(),Rq=Bo(),qT=sc(),dn=ad(),Bq=ac(),VT=ld(),xr=Ec(),Lq=bd(),HT=Mo(),kT=Zo(),Si=Sd(),Od=xd(),cw=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new qT.OptionType(r[0])],["List",(...r)=>new qT.ListType(r[0])],["VarArgs",(...r)=>new Od.VariadicType(r[0])],["MultiResultVec",(...r)=>new Od.VariadicType(r[0])],["variadic",(...r)=>new Od.VariadicType(r[0])],["counted-variadic",(...r)=>new Od.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new aw.OptionalType(r[0])],["optional",(...r)=>new aw.OptionalType(r[0])],["OptionalResult",(...r)=>new aw.OptionalType(r[0])],["multi",(...r)=>new Nd.CompositeType(...r)],["MultiArg",(...r)=>new Nd.CompositeType(...r)],["MultiResult",(...r)=>new Nd.CompositeType(...r)],["multi",(...r)=>new Nd.CompositeType(...r)],["tuple",(...r)=>new Si.TupleType(...r)],["tuple2",(...r)=>new Si.TupleType(...r)],["tuple3",(...r)=>new Si.TupleType(...r)],["tuple4",(...r)=>new Si.TupleType(...r)],["tuple5",(...r)=>new Si.TupleType(...r)],["tuple6",(...r)=>new Si.TupleType(...r)],["tuple7",(...r)=>new Si.TupleType(...r)],["tuple8",(...r)=>new Si.TupleType(...r)],["array2",(...r)=>new dn.ArrayVecType(2,r[0])],["array8",(...r)=>new dn.ArrayVecType(8,r[0])],["array16",(...r)=>new dn.ArrayVecType(16,r[0])],["array20",(...r)=>new dn.ArrayVecType(20,r[0])],["array32",(...r)=>new dn.ArrayVecType(32,r[0])],["array46",(...r)=>new dn.ArrayVecType(46,r[0])],["array48",(...r)=>new dn.ArrayVecType(48,r[0])],["array64",(...r)=>new dn.ArrayVecType(64,r[0])],["array128",(...r)=>new dn.ArrayVecType(128,r[0])],["array256",(...r)=>new dn.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new xr.U8Type],["u16",new xr.U16Type],["u32",new xr.U32Type],["u64",new xr.U64Type],["U64",new xr.U64Type],["BigUint",new xr.BigUIntType],["i8",new xr.I8Type],["i16",new xr.I16Type],["i32",new xr.I32Type],["i64",new xr.I64Type],["Bigint",new xr.BigIntType],["BigInt",new xr.BigIntType],["bool",new Oq.BooleanType],["bytes",new Dq.BytesType],["Address",new Nq.AddressType],["H256",new Bq.H256Type],["utf-8 string",new Lq.StringType],["TokenIdentifier",new kT.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new kT.TokenIdentifierType],["CodeMetadata",new Pq.CodeMetadataType],["nothing",new VT.NothingType],["AsyncCall",new VT.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new UT.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(uw.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(HT.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new HT.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new uw.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new uw.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new Rq.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new UT.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};hn.TypeMapper=cw});var WT=v(pn=>{"use strict";l();var Fq=pn&&pn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Mq=pn&&pn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Uq=pn&&pn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Fq(e,t,r);return Mq(e,t),e};Object.defineProperty(pn,"__esModule",{value:!0});pn.AbiRegistry=void 0;var GT=Uq(Le()),Ic=br(),_c=Wm(),jT=Ku(),fw=yT(),QT=Mo(),qq=lw(),Vq="?",dw=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||Vq,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],a=_c.EndpointDefinition.fromJSON(Object.assign({name:"constructor"},n)),u=i.map(m=>_c.EndpointDefinition.fromJSON(m)),c=[];for(let m in s){let y=s[m];if(y.type=="struct")c.push(QT.StructType.fromJSON({name:m,fields:y.fields}));else if(y.type=="enum"||y.type=="explicit-enum")c.push(jT.EnumType.fromJSON({name:m,variants:y.variants}));else throw new GT.ErrTypingSystem(`Cannot handle custom type: ${m}`)}let f=o.map(m=>fw.EventDefinition.fromJSON(m));return new t({name:r,constructorDefinition:a,endpoints:u,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return Ic.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(QT.StructType.ClassName));return Ic.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(jT.EnumType.ClassName));return Ic.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return Ic.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return Ic.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new qq.TypeMapper([]),r=[];for(let a of this.customTypes)this.mapCustomTypeDepthFirst(a,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new GT.ErrTypingSystem("Did not re-map all custom types");let n=zT(this.constructorDefinition,e),i=[];for(let a of this.endpoints)i.push(zT(a,e));let s=this.events.map(a=>Hq(a,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(a=>a.getName()==e.getName())>=0)return;for(let a of e.getNamesOfDependencies()){let u=r.find(c=>c.getName()==a);u&&this.mapCustomTypeDepthFirst(u,r,n,i)}let o=n.mapType(e);i.push(o)}};pn.AbiRegistry=dw;function zT(t,e){let r=t.input.map(i=>new _c.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new _c.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new _c.EndpointDefinition(t.name,r,n,t.modifiers)}function Hq(t,e){let r=t.inputs.map(n=>new fw.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new fw.EventDefinition(t.identifier,r)}});var KT=v(ta=>{"use strict";l();Object.defineProperty(ta,"__esModule",{value:!0});ta.createListOfTokenIdentifiers=ta.createListOfAddresses=void 0;var kq=ko(),$T=sc(),Gq=Zo();function jq(t){let e=t.map(n=>new kq.AddressValue(n));return $T.List.fromItems(e)}ta.createListOfAddresses=jq;function Qq(t){let e=t.map(n=>new Gq.TokenIdentifierValue(n));return $T.List.fromItems(e)}ta.createListOfTokenIdentifiers=Qq});var cC=v(Jt=>{"use strict";l();var zq=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Wq=Jt&&Jt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$q=Jt&&Jt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zq(e,t,r);return Wq(e,t),e};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.onPrimitiveTypeSelect=Jt.onPrimitiveValueSelect=Jt.onTypedValueSelect=Jt.onTypeSelect=void 0;var Pd=$q(Le()),YT=ko(),JT=tc(),XT=Ii(),ZT=Ku(),Dd=sc(),eC=ac(),tC=Ec(),rC=ld(),nC=Mo(),iC=Zo(),sC=Sd(),oC=Ct(),aC=ad(),uC=bd();function Kq(t,e){if(t.hasExactClass(Dd.OptionType.ClassName))return e.onOption();if(t.hasExactClass(Dd.ListType.ClassName))return e.onList();if(t.hasExactClass(aC.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(oC.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(nC.StructType.ClassName))return e.onStruct();if(t.hasExactClass(sC.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(ZT.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`type isn't known: ${t}`)}Jt.onTypeSelect=Kq;function Yq(t,e){if(t.hasClassOrSuperclass(oC.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(Dd.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(Dd.List.ClassName))return e.onList();if(t.hasExactClass(aC.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(nC.Struct.ClassName))return e.onStruct();if(t.hasExactClass(sC.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(ZT.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`value isn't typed: ${t}`)}Jt.onTypedValueSelect=Yq;function Jq(t,e){if(t.hasExactClass(JT.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(tC.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(YT.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(XT.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(uC.StringValue.ClassName))return e.onString();if(t.hasExactClass(eC.H256Value.ClassName))return e.onH256();if(t.hasExactClass(iC.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(rC.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Jt.onPrimitiveValueSelect=Jq;function Xq(t,e){if(t.hasExactClass(JT.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(tC.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(YT.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(XT.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(uC.StringType.ClassName))return e.onString();if(t.hasExactClass(eC.H256Type.ClassName))return e.onH256();if(t.hasExactClass(iC.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(rC.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Jt.onPrimitiveTypeSelect=Xq});var xt=v(He=>{"use strict";l();var Zq=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),at=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Zq(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});at(WT(),He);at(ko(),He);at(Yf(),He);at(tc(),He);at(Ii(),He);at(td(),He);at(Wm(),He);at(Ku(),He);at(KT(),He);at(Bo(),He);at(sc(),He);at(ad(),He);at(ac(),He);at(cC(),He);at(ld(),He);at(Ec(),He);at(bd(),He);at(Mo(),He);at(Zo(),He);at(Sd(),He);at(Wu(),He);at(lw(),He);at(Ct(),He);at(xd(),He)});var fC=v(gn=>{"use strict";l();var eV=gn&&gn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),tV=gn&&gn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rV=gn&&gn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&eV(e,t,r);return tV(e,t),e};Object.defineProperty(gn,"__esModule",{value:!0});gn.OptionValueBinaryCodec=void 0;var lC=rV(Le()),Rd=xt(),hw=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[Rd.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new lC.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[Rd.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new Rd.OptionValue(r);if(e[0]!=1)throw new lC.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new Rd.OptionValue(r,n)}encodeNested(e){return e.isSet()?h.Buffer.concat([h.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):h.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?h.Buffer.concat([h.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):h.Buffer.from([])}};gn.OptionValueBinaryCodec=hw});var dC=v(Bd=>{"use strict";l();Object.defineProperty(Bd,"__esModule",{value:!0});Bd.AddressBinaryCodec=void 0;var nV=pt(),iV=xt(),pw=class{decodeNested(e){let r=e.slice(0,32),n=new nV.Address(r);return[new iV.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};Bd.AddressBinaryCodec=pw});var pC=v(yn=>{"use strict";l();var sV=yn&&yn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),oV=yn&&yn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),aV=yn&&yn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sV(e,t,r);return oV(e,t),e};Object.defineProperty(yn,"__esModule",{value:!0});yn.BooleanBinaryCodec=void 0;var uV=aV(Le()),hC=xt(),Sc=class t{decodeNested(e){let r=e.readUInt8(0);return[new hC.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new uV.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new hC.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?h.Buffer.from([t.TRUE]):h.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?h.Buffer.from([t.TRUE]):h.Buffer.from([])}};yn.BooleanBinaryCodec=Sc;Sc.TRUE=1;Sc.FALSE=0});var Fd=v(Ld=>{"use strict";l();Object.defineProperty(Ld,"__esModule",{value:!0});Ld.SizeOfU32=void 0;Ld.SizeOfU32=4});var Md=v(mn=>{"use strict";l();var cV=mn&&mn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(mn,"__esModule",{value:!0});mn.zeroPadStringIfOddLength=mn.isPaddedHex=mn.numberToPaddedHex=void 0;var lV=cV(Yt());function fV(t){let e=new lV.default(t).toString(16);return gC(e)}mn.numberToPaddedHex=fV;function dV(t){t=t||"";let e=h.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}mn.isPaddedHex=dV;function gC(t){return t=t||"",t.length%2==1?"0"+t:t}mn.zeroPadStringIfOddLength=gC});var Tc=v(Nt=>{"use strict";l();var hV=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.prependByteToBuffer=Nt.flipBufferBitsInPlace=Nt.getHexMagnitudeOfBigInt=Nt.bigIntToBuffer=Nt.bufferToBigInt=Nt.cloneBuffer=Nt.isMsbZero=Nt.isMsbOne=void 0;var gw=hV(Yt()),pV=Md();function yC(t,e=0){return t[e]>>7==1}Nt.isMsbOne=yC;function gV(t,e=0){return!yC(t,e)}Nt.isMsbZero=gV;function yV(t){let e=h.Buffer.alloc(t.length);return t.copy(e),e}Nt.cloneBuffer=yV;function mV(t){let e=t.toString("hex");return new gw.default(`0x${e}`,16)}Nt.bufferToBigInt=mV;function wV(t){let e=mC(t);return h.Buffer.from(e,"hex")}Nt.bigIntToBuffer=wV;function mC(t){return t=new gw.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new gw.default(-1))),pV.numberToPaddedHex(t)):""}Nt.getHexMagnitudeOfBigInt=mC;function EV(t){for(let e=0;e{"use strict";l();var AV=ra&&ra.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ra,"__esModule",{value:!0});ra.NumericalBinaryCodec=void 0;var Cc=AV(Yt()),yw=xt(),wC=Fd(),At=Tc(),mw=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=wC.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),a=i+n;return[o,a]}decodeTopLevel(e,r){let n=At.cloneBuffer(e);if(e.length==0)return new yw.NumericalValue(r,new Cc.default(0));if(!r.withSign||At.isMsbZero(n)){let c=At.bufferToBigInt(n);return new yw.NumericalValue(r,c)}At.flipBufferBitsInPlace(n);let u=At.bufferToBigInt(n).multipliedBy(new Cc.default(-1)).minus(new Cc.default(1));return new yw.NumericalValue(r,u)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=h.Buffer.alloc(wC.SizeOfU32);return n.writeUInt32BE(r.length),h.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return h.Buffer.alloc(r,0);if(!e.withSign){let o=At.bigIntToBuffer(e.value),a=h.Buffer.alloc(r-o.length,0);return h.Buffer.concat([a,o])}if(e.value.isPositive()){let o=At.bigIntToBuffer(e.value);At.isMsbOne(o)&&(o=At.prependByteToBuffer(o,0));let a=h.Buffer.alloc(r-o.length,0);return h.Buffer.concat([a,o])}let n=e.value.plus(new Cc.default(1)),i=At.bigIntToBuffer(n);At.flipBufferBitsInPlace(i),At.isMsbZero(i)&&(i=At.prependByteToBuffer(i,255));let s=h.Buffer.alloc(r-i.length,255);return h.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?h.Buffer.alloc(0):r?this.encodePrimitive(e):At.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=At.bigIntToBuffer(e.value);return At.isMsbOne(i)&&(i=At.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Cc.default(1)),n=At.bigIntToBuffer(r);return At.flipBufferBitsInPlace(n),At.isMsbZero(n)&&(n=At.prependByteToBuffer(n,255)),n}};ra.NumericalBinaryCodec=mw});var vC=v(Ud=>{"use strict";l();Object.defineProperty(Ud,"__esModule",{value:!0});Ud.H256BinaryCodec=void 0;var bV=ac(),ww=class{decodeNested(e){let r=e.slice(0,32);return[new bV.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Ud.H256BinaryCodec=ww});var Hd=v(Vd=>{"use strict";l();Object.defineProperty(Vd,"__esModule",{value:!0});Vd.BytesBinaryCodec=void 0;var AC=Ii(),qd=Fd(),Ew=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(qd.SizeOfU32,qd.SizeOfU32+r);return[new AC.BytesValue(n),qd.SizeOfU32+r]}decodeTopLevel(e){return new AC.BytesValue(e)}encodeNested(e){let r=h.Buffer.alloc(qd.SizeOfU32);return r.writeUInt32BE(e.getLength()),h.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Vd.BytesBinaryCodec=Ew});var IC=v(kd=>{"use strict";l();Object.defineProperty(kd,"__esModule",{value:!0});kd.TokenIdentifierCodec=void 0;var IV=Ii(),bC=Zo(),_V=Hd(),vw=class{constructor(){this.bytesCodec=new _V.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new bC.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new bC.TokenIdentifierValue(r.toString())}encodeNested(e){let r=IV.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return h.Buffer.from(e.valueOf())}};kd.TokenIdentifierCodec=vw});var SC=v(Gd=>{"use strict";l();Object.defineProperty(Gd,"__esModule",{value:!0});Gd.NothingCodec=void 0;var _C=xt(),Aw=class{decodeNested(){return[new _C.NothingValue,0]}decodeTopLevel(){return new _C.NothingValue}encodeNested(){return h.Buffer.from([])}encodeTopLevel(){return h.Buffer.from([])}};Gd.NothingCodec=Aw});var CC=v(jd=>{"use strict";l();Object.defineProperty(jd,"__esModule",{value:!0});jd.StringBinaryCodec=void 0;var TC=xt(),SV=Ii(),TV=Hd(),bw=class{constructor(){this.bytesBinaryCodec=new TV.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new TC.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new TC.StringValue(e.toString())}encodeNested(e){let r=SV.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return h.Buffer.from(e.valueOf())}};jd.StringBinaryCodec=bw});var xC=v(zd=>{"use strict";l();Object.defineProperty(zd,"__esModule",{value:!0});zd.PrimitiveBinaryCodec=void 0;var Qd=xt(),CV=dC(),xV=pC(),NV=EC(),OV=vC(),DV=Hd(),PV=IC(),RV=SC(),BV=CC(),Iw=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new xV.BooleanBinaryCodec,this.numericalCodec=new NV.NumericalBinaryCodec,this.addressCodec=new CV.AddressBinaryCodec,this.h256Codec=new OV.H256BinaryCodec,this.bytesCodec=new DV.BytesBinaryCodec,this.stringCodec=new BV.StringBinaryCodec,this.tokenIdentifierCodec=new PV.TokenIdentifierCodec,this.nothingCodec=new RV.NothingCodec}decodeNested(e,r){return Qd.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Qd.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Qd.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Qd.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};zd.PrimitiveBinaryCodec=Iw});var DC=v(Wd=>{"use strict";l();Object.defineProperty(Wd,"__esModule",{value:!0});Wd.ListBinaryCodec=void 0;var NC=xt(),OC=Fd(),_w=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,a=OC.SizeOfU32;e=o.slice(a);for(let u=0;u0;){let[a,u]=this.binaryCodec.decodeNested(e,n);i.push(a),o+=u,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new NC.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=h.Buffer.alloc(OC.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return h.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return h.Buffer.concat(r)}};Wd.ListBinaryCodec=_w});var Tw=v($d=>{"use strict";l();Object.defineProperty($d,"__esModule",{value:!0});$d.FieldsBinaryCodec=void 0;var LV=xt(),Sw=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,a]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(a),i+=a;let u=new LV.Field(o,s.name);n.push(u)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return h.Buffer.concat(r)}};$d.FieldsBinaryCodec=Sw});var xw=v(Kd=>{"use strict";l();Object.defineProperty(Kd,"__esModule",{value:!0});Kd.StructBinaryCodec=void 0;var FV=xt(),MV=Tw(),Cw=class{constructor(e){this.fieldsCodec=new MV.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new FV.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Kd.StructBinaryCodec=Cw});var PC=v(Jd=>{"use strict";l();Object.defineProperty(Jd,"__esModule",{value:!0});Jd.EnumBinaryCodec=void 0;var Yd=xt(),UV=Tw(),Nw=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new UV.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[a,u]=this.fieldsCodec.decodeNested(e,o);return[new Yd.EnumValue(r,s,a),i+u]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Yd.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Yd.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return h.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Yd.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return h.Buffer.concat([o,i])}};Jd.EnumBinaryCodec=Nw});var RC=v(Xd=>{"use strict";l();Object.defineProperty(Xd,"__esModule",{value:!0});Xd.TupleBinaryCodec=void 0;var qV=xw(),Ow=class{constructor(e){this.structCodec=new qV.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Xd.TupleBinaryCodec=Ow});var BC=v(Zd=>{"use strict";l();Object.defineProperty(Zd,"__esModule",{value:!0});Zd.ArrayVecBinaryCodec=void 0;var VV=xt(),Dw=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let a=0;a{"use strict";l();var HV=Nr&&Nr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),kV=Nr&&Nr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GV=Nr&&Nr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&HV(e,t,r);return kV(e,t),e};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.BinaryCodecConstraints=Nr.BinaryCodec=void 0;var LC=GV(Le()),eh=xt(),FC=br(),jV=fC(),QV=xC(),zV=DC(),WV=xw(),$V=PC(),KV=RC(),YV=BC(),Pw=class{constructor(e=null){this.constraints=e||new th,this.optionCodec=new jV.OptionValueBinaryCodec(this),this.listCodec=new zV.ListBinaryCodec(this),this.arrayCodec=new YV.ArrayVecBinaryCodec(this),this.primitiveCodec=new QV.PrimitiveBinaryCodec(this),this.structCodec=new WV.StructBinaryCodec(this),this.tupleCodec=new KV.TupleBinaryCodec(this),this.enumCodec=new $V.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),eh.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=eh.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return FC.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),eh.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return FC.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),eh.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Nr.BinaryCodec=Pw;var th=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new LC.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new LC.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Nr.BinaryCodecConstraints=th});var MC=v(Or=>{"use strict";l();var JV=Or&&Or.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Or,"__esModule",{value:!0});Or.decodeBigNumber=Or.decodeString=Or.decodeBool=Or.decodeUnsignedNumber=void 0;var XV=JV(Yt()),rh=xt(),ZV=Rw(),nh=new ZV.BinaryCodec;function eH(t){let e=nh.decodeTopLevel(t,new rh.BigUIntType);return Number(e.valueOf())}Or.decodeUnsignedNumber=eH;function tH(t){return!!nh.decodeTopLevel(t,new rh.BooleanType).valueOf()}Or.decodeBool=tH;function rH(t){let e=nh.decodeTopLevel(t,new rh.BytesType);return String(e.valueOf())}Or.decodeString=rH;function nH(t){let e=nh.decodeTopLevel(t,new rh.BigUIntType);return new XV.default(e.valueOf())}Or.decodeBigNumber=nH});var Bw=v(Ti=>{"use strict";l();var iH=Ti&&Ti.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),UC=Ti&&Ti.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&iH(e,t,r)};Object.defineProperty(Ti,"__esModule",{value:!0});UC(Rw(),Ti);UC(MC(),Ti)});var na=v(ih=>{"use strict";l();Object.defineProperty(ih,"__esModule",{value:!0});ih.ArgSerializer=void 0;var qC=Ns(),sH=Bw(),VC=xt(),Lw=Yf(),Fw=td(),Mw=xd(),oH={codec:new sH.BinaryCodec},Uw=class{constructor(e){e=Object.assign(Object.assign({},oH),e),this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split(qC.ARGUMENTS_SEPARATOR).map(r=>h.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join(qC.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(Lw.OptionalValue.ClassName)){let u=o;u.isSet()&&i(u.getTypedValue());return}if(o.hasExactClass(Mw.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(Fw.CompositeValue.ClassName)){let u=o;for(let c of u.getItems())i(c);return}let a=r.codec.encodeTopLevel(o);n.push(a)}function s(o){if(o.getType().isCounted){let u=new VC.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(u))}for(let u of o.getItems())i(u)}return n}};ih.ArgSerializer=Uw});var ah=v(oh=>{"use strict";l();Object.defineProperty(oh,"__esModule",{value:!0});oh.Compatibility=void 0;var aH=pt(),sh=class{static guardAddressIsSetAndNonZero(e,r,n){this.areWarningsEnabled&&(!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==aH.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`))}};oh.Compatibility=sh;sh.areWarningsEnabled=!0});var HC=v(wn=>{"use strict";l();var uH=wn&&wn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),cH=wn&&wn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),lH=wn&&wn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&uH(e,t,r);return cH(e,t),e};Object.defineProperty(wn,"__esModule",{value:!0});wn.Hash=void 0;var fH=lH(Le()),qw=class t{constructor(e){if(!e)this.hash=h.Buffer.from([]);else if(e instanceof h.Buffer)this.hash=e;else if(typeof e=="string")this.hash=h.Buffer.from(e,"hex");else throw new fH.ErrBadType("hash","buffer | string",e)}static empty(){return new t(h.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};wn.Hash=qw});var xc=v(Dr=>{"use strict";l();var dH=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),hH=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),pH=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&dH(e,t,r);return hH(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.TransactionOptions=Dr.TransactionVersion=void 0;var Wr=Ns(),kC=pH(Le()),Vw=class t{constructor(e){if(e=Number(e),e<1)throw new kC.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(Wr.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(Wr.TRANSACTION_VERSION_WITH_OPTIONS)}valueOf(){return this.value}};Dr.TransactionVersion=Vw;var Hw=class t{constructor(e){if(e=Number(e),e<0)throw new kC.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(Wr.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=Wr.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN)==Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&Wr.TRANSACTION_OPTIONS_TX_GUARDED)==Wr.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=Wr.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};Dr.TransactionOptions=Hw});var jC=v((mue,GC)=>{"use strict";l();GC.exports=gH;function gH(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";l();var uh=WC;uh.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var ia=new Array(64),zC=new Array(123);for($r=0;$r<64;)zC[ia[$r]=$r<26?$r+65:$r<52?$r+71:$r<62?$r-4:$r-59|43]=$r++;var $r;uh.encode=function(e,r,n){for(var i=null,s=[],o=0,a=0,u;r>2],u=(c&3)<<4,a=1;break;case 1:s[o++]=ia[u|c>>4],u=(c&15)<<2,a=2;break;case 2:s[o++]=ia[u|c>>6],s[o++]=ia[c&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=ia[u],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var QC="invalid encoding";uh.decode=function(e,r,n){for(var i=n,s=0,o,a=0;a1)break;if((u=zC[u])===void 0)throw Error(QC);switch(s){case 0:o=u,s=1;break;case 1:r[n++]=o<<2|(u&48)>>4,o=u,s=2;break;case 2:r[n++]=(o&15)<<4|(u&60)>>2,o=u,s=3;break;case 3:r[n++]=(o&3)<<6|u,s=0;break}}if(s===1)throw Error(QC);return n-i};uh.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var YC=v((Aue,KC)=>{"use strict";l();KC.exports=ch;function ch(){this._listeners={}}ch.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};ch.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";l();rx.exports=JC(JC);function JC(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(u,c,f){e[0]=u,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(u,c,f){e[0]=u,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(u,c){return r[0]=u[c],r[1]=u[c+1],r[2]=u[c+2],r[3]=u[c+3],e[0]}function a(u,c){return r[3]=u[c],r[2]=u[c+1],r[1]=u[c+2],r[0]=u[c+3],e[0]}t.readFloatLE=n?o:a,t.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var u=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-u)*8388608)&8388607;n((a<<31|u+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,XC),t.writeFloatBE=e.bind(null,ZC);function r(n,i,s){var o=n(i,s),a=(o>>31)*2+1,u=o>>>23&255,c=o&8388607;return u===255?c?NaN:a*(1/0):u===0?a*1401298464324817e-60*c:a*Math.pow(2,u-150)*(c+8388608)}t.readFloatLE=r.bind(null,ex),t.readFloatBE=r.bind(null,tx)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(u,c,f){e[0]=u,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(u,c,f){e[0]=u,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(u,c){return r[0]=u[c],r[1]=u[c+1],r[2]=u[c+2],r[3]=u[c+3],r[4]=u[c+4],r[5]=u[c+5],r[6]=u[c+6],r[7]=u[c+7],e[0]}function a(u,c){return r[7]=u[c],r[6]=u[c+1],r[5]=u[c+2],r[4]=u[c+3],r[3]=u[c+4],r[2]=u[c+5],r[1]=u[c+6],r[0]=u[c+7],e[0]}t.readDoubleLE=n?o:a,t.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,u){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,a,u+i),n(1/o>0?0:2147483648,a,u+s);else if(isNaN(o))n(0,a,u+i),n(2146959360,a,u+s);else if(o>17976931348623157e292)n(0,a,u+i),n((c<<31|2146435072)>>>0,a,u+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,a,u+i),n((c<<31|f/4294967296)>>>0,a,u+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,a,u+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,a,u+s)}}}t.writeDoubleLE=e.bind(null,XC,0,4),t.writeDoubleBE=e.bind(null,ZC,4,0);function r(n,i,s,o,a){var u=n(o,a+i),c=n(o,a+s),f=(c>>31)*2+1,d=c>>>20&2047,g=4294967296*(c&1048575)+u;return d===2047?g?NaN:f*(1/0):d===0?f*5e-324*g:f*Math.pow(2,d-1075)*(g+4503599627370496)}t.readDoubleLE=r.bind(null,ex,0,4),t.readDoubleBE=r.bind(null,tx,4,0)}(),t}function XC(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function ZC(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function ex(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function tx(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var ix=v((exports,module)=>{"use strict";l();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var ox=v(sx=>{"use strict";l();var kw=sx;kw.length=function(e){for(var r=0,n=0,i=0;i191&&u<224?o[a++]=(u&31)<<6|e[r++]&63:u>239&&u<365?(u=((u&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[a++]=55296+(u>>10),o[a++]=56320+(u&1023)):o[a++]=(u&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};kw.write=function(e,r,n){for(var i=n,s,o,a=0;a>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var ux=v((xue,ax)=>{"use strict";l();ax.exports=yH;function yH(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(u){if(u<1||u>i)return t(u);o+u>n&&(s=t(n),o=0);var c=e.call(s,o,o+=u);return o&7&&(o=(o|7)+1),c}}});var lx=v((Oue,cx)=>{"use strict";l();cx.exports=qt;var Nc=xi();function qt(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ls=qt.zero=new qt(0,0);Ls.toNumber=function(){return 0};Ls.zzEncode=Ls.zzDecode=function(){return this};Ls.length=function(){return 1};var mH=qt.zeroHash="\0\0\0\0\0\0\0\0";qt.fromNumber=function(e){if(e===0)return Ls;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new qt(n,i)};qt.from=function(e){if(typeof e=="number")return qt.fromNumber(e);if(Nc.isString(e))if(Nc.Long)e=Nc.Long.fromString(e);else return qt.fromNumber(parseInt(e,10));return e.low||e.high?new qt(e.low>>>0,e.high>>>0):Ls};qt.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};qt.prototype.toLong=function(e){return Nc.Long?new Nc.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Ci=String.prototype.charCodeAt;qt.fromHash=function(e){return e===mH?Ls:new qt((Ci.call(e,0)|Ci.call(e,1)<<8|Ci.call(e,2)<<16|Ci.call(e,3)<<24)>>>0,(Ci.call(e,4)|Ci.call(e,5)<<8|Ci.call(e,6)<<16|Ci.call(e,7)<<24)>>>0)};qt.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};qt.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};qt.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};qt.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var xi=v(Gw=>{"use strict";l();var Ie=Gw;Ie.asPromise=jC();Ie.base64=$C();Ie.EventEmitter=YC();Ie.float=nx();Ie.inquire=ix();Ie.utf8=ox();Ie.pool=ux();Ie.LongBits=lx();Ie.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);Ie.global=Ie.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||Gw;Ie.emptyArray=Object.freeze?Object.freeze([]):[];Ie.emptyObject=Object.freeze?Object.freeze({}):{};Ie.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Ie.isString=function(e){return typeof e=="string"||e instanceof String};Ie.isObject=function(e){return e&&typeof e=="object"};Ie.isset=Ie.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Ie.Buffer=function(){try{var t=Ie.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();Ie._Buffer_from=null;Ie._Buffer_allocUnsafe=null;Ie.newBuffer=function(e){return typeof e=="number"?Ie.Buffer?Ie._Buffer_allocUnsafe(e):new Ie.Array(e):Ie.Buffer?Ie._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Ie.Array=typeof Uint8Array<"u"?Uint8Array:Array;Ie.Long=Ie.global.dcodeIO&&Ie.global.dcodeIO.Long||Ie.global.Long||Ie.inquire("long");Ie.key2Re=/^true|false|0|1$/;Ie.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Ie.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Ie.longToHash=function(e){return e?Ie.LongBits.from(e).toHash():Ie.LongBits.zeroHash};Ie.longFromHash=function(e,r){var n=Ie.LongBits.fromHash(e);return Ie.Long?Ie.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function fx(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};Ie.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";l();yx.exports=Ue;var Pr=xi(),jw,lh=Pr.LongBits,hx=Pr.base64,px=Pr.utf8;function Oc(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function zw(){}function wH(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Oc(zw,0,0),this.tail=this.head,this.states=null}var gx=function(){return Pr.Buffer?function(){return(Ue.create=function(){return new jw})()}:function(){return new Ue}};Ue.create=gx();Ue.alloc=function(e){return new Pr.Array(e)};Pr.Array!==Array&&(Ue.alloc=Pr.pool(Ue.alloc,Pr.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Oc(e,r,n),this.len+=r,this};function Ww(t,e,r){e[r]=t&255}function EH(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function $w(t,e){this.len=t,this.next=void 0,this.val=e}$w.prototype=Object.create(Oc.prototype);$w.prototype.fn=EH;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new $w((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(Kw,10,lh.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Kw(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=lh.from(e);return this._push(Kw,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=lh.from(e).zzEncode();return this._push(Kw,r.length(),r)};Ue.prototype.bool=function(e){return this._push(Ww,1,e?1:0)};function Qw(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(Qw,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=lh.from(e);return this._push(Qw,4,r.lo)._push(Qw,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Pr.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Pr.float.writeDoubleLE,8,e)};var vH=Pr.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(Ww,1,0);if(Pr.isString(e)){var n=Ue.alloc(r=hx.length(e));hx.decode(e,n,0),e=n}return this.uint32(r)._push(vH,r,e)};Ue.prototype.string=function(e){var r=px.length(e);return r?this.uint32(r)._push(px.write,r,e):this._push(Ww,1,0)};Ue.prototype.fork=function(){return this.states=new wH(this),this.head=this.tail=new Oc(zw,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Oc(zw,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){jw=t,Ue.create=gx(),jw._configure()}});var Ex=v((Fue,wx)=>{"use strict";l();wx.exports=En;var mx=Yw();(En.prototype=Object.create(mx.prototype)).constructor=En;var Ni=xi();function En(){mx.call(this)}En._configure=function(){En.alloc=Ni._Buffer_allocUnsafe,En.writeBytesBuffer=Ni.Buffer&&Ni.Buffer.prototype instanceof Uint8Array&&Ni.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(En.writeBytesBuffer,r,e),this};function AH(t,e,r){t.length<40?Ni.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}En.prototype.string=function(e){var r=Ni.Buffer.byteLength(e);return this.uint32(r),r&&this._push(AH,r,e),this};En._configure()});var Zw=v((Uue,_x)=>{"use strict";l();_x.exports=bt;var vn=xi(),Xw,bx=vn.LongBits,bH=vn.utf8;function Kr(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function bt(t){this.buf=t,this.pos=0,this.len=t.length}var vx=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new bt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new bt(e);throw Error("illegal buffer")},Ix=function(){return vn.Buffer?function(r){return(bt.create=function(i){return vn.Buffer.isBuffer(i)?new Xw(i):vx(i)})(r)}:vx};bt.create=Ix();bt.prototype._slice=vn.Array.prototype.subarray||vn.Array.prototype.slice;bt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Kr(this,10);return e}}();bt.prototype.int32=function(){return this.uint32()|0};bt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Jw(){var t=new bx(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Kr(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Kr(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}bt.prototype.bool=function(){return this.uint32()!==0};function fh(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}bt.prototype.fixed32=function(){if(this.pos+4>this.len)throw Kr(this,4);return fh(this.buf,this.pos+=4)};bt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Kr(this,4);return fh(this.buf,this.pos+=4)|0};function Ax(){if(this.pos+8>this.len)throw Kr(this,8);return new bx(fh(this.buf,this.pos+=4),fh(this.buf,this.pos+=4))}bt.prototype.float=function(){if(this.pos+4>this.len)throw Kr(this,4);var e=vn.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};bt.prototype.double=function(){if(this.pos+8>this.len)throw Kr(this,4);var e=vn.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};bt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Kr(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(r,n):r===n?new this.buf.constructor(0):this._slice.call(this.buf,r,n)};bt.prototype.string=function(){var e=this.bytes();return bH.read(e,0,e.length)};bt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Kr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Kr(this);while(this.buf[this.pos++]&128);return this};bt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};bt._configure=function(t){Xw=t,bt.create=Ix(),Xw._configure();var e=vn.Long?"toLong":"toNumber";vn.merge(bt.prototype,{int64:function(){return Jw.call(this)[e](!1)},uint64:function(){return Jw.call(this)[e](!0)},sint64:function(){return Jw.call(this).zzDecode()[e](!1)},fixed64:function(){return Ax.call(this)[e](!0)},sfixed64:function(){return Ax.call(this)[e](!1)}})}});var xx=v((Vue,Cx)=>{"use strict";l();Cx.exports=Fs;var Tx=Zw();(Fs.prototype=Object.create(Tx.prototype)).constructor=Fs;var Sx=xi();function Fs(t){Tx.call(this,t)}Fs._configure=function(){Sx.Buffer&&(Fs.prototype._slice=Sx.Buffer.prototype.slice)};Fs.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Fs._configure()});var Ox=v((kue,Nx)=>{"use strict";l();Nx.exports=Dc;var eE=xi();(Dc.prototype=Object.create(eE.EventEmitter.prototype)).constructor=Dc;function Dc(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");eE.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Dc.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return eE.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(u,c){if(u)return o.emit("error",u,e),s(u);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(a){o.emit("error",a,e),setTimeout(function(){s(a)},0);return}};Dc.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var Px=v(Dx=>{"use strict";l();var IH=Dx;IH.Service=Ox()});var Bx=v((zue,Rx)=>{"use strict";l();Rx.exports={}});var Mx=v(Fx=>{"use strict";l();var pr=Fx;pr.build="minimal";pr.Writer=Yw();pr.BufferWriter=Ex();pr.Reader=Zw();pr.BufferReader=xx();pr.util=xi();pr.rpc=Px();pr.roots=Bx();pr.configure=Lx;function Lx(){pr.util._configure(),pr.Writer._configure(pr.BufferWriter),pr.Reader._configure(pr.BufferReader)}Lx()});var qx=v((Yue,Ux)=>{"use strict";l();Ux.exports=Mx()});var Hx=v((Xue,Vx)=>{"use strict";l();var sa=qx(),dh=sa.Reader,_H=sa.Writer,Z=sa.util,Pc=sa.roots.default||(sa.roots.default={});Pc.proto=function(){var t={};return t.Transaction=function(){function e(r){if(r)for(var n=Object.keys(r),i=0;i>>3){case 1:o.Nonce=n.uint64();break;case 2:o.Value=n.bytes();break;case 3:o.RcvAddr=n.bytes();break;case 4:o.RcvUserName=n.bytes();break;case 5:o.SndAddr=n.bytes();break;case 6:o.SndUserName=n.bytes();break;case 7:o.GasPrice=n.uint64();break;case 8:o.GasLimit=n.uint64();break;case 9:o.Data=n.bytes();break;case 10:o.ChainID=n.bytes();break;case 11:o.Version=n.uint32();break;case 12:o.Signature=n.bytes();break;case 13:o.Options=n.uint32();break;case 14:o.GuardAddr=n.bytes();break;case 15:o.GuardSignature=n.bytes();break;default:n.skipType(a&7);break}}return o},e.decodeDelimited=function(n){return n instanceof dh||(n=new dh(n)),this.decode(n,n.uint32())},e.verify=function(n){return typeof n!="object"||n===null?"object expected":n.Nonce!=null&&n.hasOwnProperty("Nonce")&&!Z.isInteger(n.Nonce)&&!(n.Nonce&&Z.isInteger(n.Nonce.low)&&Z.isInteger(n.Nonce.high))?"Nonce: integer|Long expected":n.Value!=null&&n.hasOwnProperty("Value")&&!(n.Value&&typeof n.Value.length=="number"||Z.isString(n.Value))?"Value: buffer expected":n.RcvAddr!=null&&n.hasOwnProperty("RcvAddr")&&!(n.RcvAddr&&typeof n.RcvAddr.length=="number"||Z.isString(n.RcvAddr))?"RcvAddr: buffer expected":n.RcvUserName!=null&&n.hasOwnProperty("RcvUserName")&&!(n.RcvUserName&&typeof n.RcvUserName.length=="number"||Z.isString(n.RcvUserName))?"RcvUserName: buffer expected":n.SndAddr!=null&&n.hasOwnProperty("SndAddr")&&!(n.SndAddr&&typeof n.SndAddr.length=="number"||Z.isString(n.SndAddr))?"SndAddr: buffer expected":n.SndUserName!=null&&n.hasOwnProperty("SndUserName")&&!(n.SndUserName&&typeof n.SndUserName.length=="number"||Z.isString(n.SndUserName))?"SndUserName: buffer expected":n.GasPrice!=null&&n.hasOwnProperty("GasPrice")&&!Z.isInteger(n.GasPrice)&&!(n.GasPrice&&Z.isInteger(n.GasPrice.low)&&Z.isInteger(n.GasPrice.high))?"GasPrice: integer|Long expected":n.GasLimit!=null&&n.hasOwnProperty("GasLimit")&&!Z.isInteger(n.GasLimit)&&!(n.GasLimit&&Z.isInteger(n.GasLimit.low)&&Z.isInteger(n.GasLimit.high))?"GasLimit: integer|Long expected":n.Data!=null&&n.hasOwnProperty("Data")&&!(n.Data&&typeof n.Data.length=="number"||Z.isString(n.Data))?"Data: buffer expected":n.ChainID!=null&&n.hasOwnProperty("ChainID")&&!(n.ChainID&&typeof n.ChainID.length=="number"||Z.isString(n.ChainID))?"ChainID: buffer expected":n.Version!=null&&n.hasOwnProperty("Version")&&!Z.isInteger(n.Version)?"Version: integer expected":n.Signature!=null&&n.hasOwnProperty("Signature")&&!(n.Signature&&typeof n.Signature.length=="number"||Z.isString(n.Signature))?"Signature: buffer expected":n.Options!=null&&n.hasOwnProperty("Options")&&!Z.isInteger(n.Options)?"Options: integer expected":n.GuardAddr!=null&&n.hasOwnProperty("GuardAddr")&&!(n.GuardAddr&&typeof n.GuardAddr.length=="number"||Z.isString(n.GuardAddr))?"GuardAddr: buffer expected":n.GuardSignature!=null&&n.hasOwnProperty("GuardSignature")&&!(n.GuardSignature&&typeof n.GuardSignature.length=="number"||Z.isString(n.GuardSignature))?"GuardSignature: buffer expected":null},e.fromObject=function(n){if(n instanceof Pc.proto.Transaction)return n;var i=new Pc.proto.Transaction;return n.Nonce!=null&&(Z.Long?(i.Nonce=Z.Long.fromValue(n.Nonce)).unsigned=!0:typeof n.Nonce=="string"?i.Nonce=parseInt(n.Nonce,10):typeof n.Nonce=="number"?i.Nonce=n.Nonce:typeof n.Nonce=="object"&&(i.Nonce=new Z.LongBits(n.Nonce.low>>>0,n.Nonce.high>>>0).toNumber(!0))),n.Value!=null&&(typeof n.Value=="string"?Z.base64.decode(n.Value,i.Value=Z.newBuffer(Z.base64.length(n.Value)),0):n.Value.length&&(i.Value=n.Value)),n.RcvAddr!=null&&(typeof n.RcvAddr=="string"?Z.base64.decode(n.RcvAddr,i.RcvAddr=Z.newBuffer(Z.base64.length(n.RcvAddr)),0):n.RcvAddr.length&&(i.RcvAddr=n.RcvAddr)),n.RcvUserName!=null&&(typeof n.RcvUserName=="string"?Z.base64.decode(n.RcvUserName,i.RcvUserName=Z.newBuffer(Z.base64.length(n.RcvUserName)),0):n.RcvUserName.length&&(i.RcvUserName=n.RcvUserName)),n.SndAddr!=null&&(typeof n.SndAddr=="string"?Z.base64.decode(n.SndAddr,i.SndAddr=Z.newBuffer(Z.base64.length(n.SndAddr)),0):n.SndAddr.length&&(i.SndAddr=n.SndAddr)),n.SndUserName!=null&&(typeof n.SndUserName=="string"?Z.base64.decode(n.SndUserName,i.SndUserName=Z.newBuffer(Z.base64.length(n.SndUserName)),0):n.SndUserName.length&&(i.SndUserName=n.SndUserName)),n.GasPrice!=null&&(Z.Long?(i.GasPrice=Z.Long.fromValue(n.GasPrice)).unsigned=!0:typeof n.GasPrice=="string"?i.GasPrice=parseInt(n.GasPrice,10):typeof n.GasPrice=="number"?i.GasPrice=n.GasPrice:typeof n.GasPrice=="object"&&(i.GasPrice=new Z.LongBits(n.GasPrice.low>>>0,n.GasPrice.high>>>0).toNumber(!0))),n.GasLimit!=null&&(Z.Long?(i.GasLimit=Z.Long.fromValue(n.GasLimit)).unsigned=!0:typeof n.GasLimit=="string"?i.GasLimit=parseInt(n.GasLimit,10):typeof n.GasLimit=="number"?i.GasLimit=n.GasLimit:typeof n.GasLimit=="object"&&(i.GasLimit=new Z.LongBits(n.GasLimit.low>>>0,n.GasLimit.high>>>0).toNumber(!0))),n.Data!=null&&(typeof n.Data=="string"?Z.base64.decode(n.Data,i.Data=Z.newBuffer(Z.base64.length(n.Data)),0):n.Data.length&&(i.Data=n.Data)),n.ChainID!=null&&(typeof n.ChainID=="string"?Z.base64.decode(n.ChainID,i.ChainID=Z.newBuffer(Z.base64.length(n.ChainID)),0):n.ChainID.length&&(i.ChainID=n.ChainID)),n.Version!=null&&(i.Version=n.Version>>>0),n.Signature!=null&&(typeof n.Signature=="string"?Z.base64.decode(n.Signature,i.Signature=Z.newBuffer(Z.base64.length(n.Signature)),0):n.Signature.length&&(i.Signature=n.Signature)),n.Options!=null&&(i.Options=n.Options>>>0),n.GuardAddr!=null&&(typeof n.GuardAddr=="string"?Z.base64.decode(n.GuardAddr,i.GuardAddr=Z.newBuffer(Z.base64.length(n.GuardAddr)),0):n.GuardAddr.length&&(i.GuardAddr=n.GuardAddr)),n.GuardSignature!=null&&(typeof n.GuardSignature=="string"?Z.base64.decode(n.GuardSignature,i.GuardSignature=Z.newBuffer(Z.base64.length(n.GuardSignature)),0):n.GuardSignature.length&&(i.GuardSignature=n.GuardSignature)),i},e.toObject=function(n,i){i||(i={});var s={};if(i.defaults){if(Z.Long){var o=new Z.Long(0,0,!0);s.Nonce=i.longs===String?o.toString():i.longs===Number?o.toNumber():o}else s.Nonce=i.longs===String?"0":0;if(i.bytes===String?s.Value="":(s.Value=[],i.bytes!==Array&&(s.Value=Z.newBuffer(s.Value))),i.bytes===String?s.RcvAddr="":(s.RcvAddr=[],i.bytes!==Array&&(s.RcvAddr=Z.newBuffer(s.RcvAddr))),i.bytes===String?s.RcvUserName="":(s.RcvUserName=[],i.bytes!==Array&&(s.RcvUserName=Z.newBuffer(s.RcvUserName))),i.bytes===String?s.SndAddr="":(s.SndAddr=[],i.bytes!==Array&&(s.SndAddr=Z.newBuffer(s.SndAddr))),i.bytes===String?s.SndUserName="":(s.SndUserName=[],i.bytes!==Array&&(s.SndUserName=Z.newBuffer(s.SndUserName))),Z.Long){var o=new Z.Long(0,0,!0);s.GasPrice=i.longs===String?o.toString():i.longs===Number?o.toNumber():o}else s.GasPrice=i.longs===String?"0":0;if(Z.Long){var o=new Z.Long(0,0,!0);s.GasLimit=i.longs===String?o.toString():i.longs===Number?o.toNumber():o}else s.GasLimit=i.longs===String?"0":0;i.bytes===String?s.Data="":(s.Data=[],i.bytes!==Array&&(s.Data=Z.newBuffer(s.Data))),i.bytes===String?s.ChainID="":(s.ChainID=[],i.bytes!==Array&&(s.ChainID=Z.newBuffer(s.ChainID))),s.Version=0,i.bytes===String?s.Signature="":(s.Signature=[],i.bytes!==Array&&(s.Signature=Z.newBuffer(s.Signature))),s.Options=0,i.bytes===String?s.GuardAddr="":(s.GuardAddr=[],i.bytes!==Array&&(s.GuardAddr=Z.newBuffer(s.GuardAddr))),i.bytes===String?s.GuardSignature="":(s.GuardSignature=[],i.bytes!==Array&&(s.GuardSignature=Z.newBuffer(s.GuardSignature)))}return n.Nonce!=null&&n.hasOwnProperty("Nonce")&&(typeof n.Nonce=="number"?s.Nonce=i.longs===String?String(n.Nonce):n.Nonce:s.Nonce=i.longs===String?Z.Long.prototype.toString.call(n.Nonce):i.longs===Number?new Z.LongBits(n.Nonce.low>>>0,n.Nonce.high>>>0).toNumber(!0):n.Nonce),n.Value!=null&&n.hasOwnProperty("Value")&&(s.Value=i.bytes===String?Z.base64.encode(n.Value,0,n.Value.length):i.bytes===Array?Array.prototype.slice.call(n.Value):n.Value),n.RcvAddr!=null&&n.hasOwnProperty("RcvAddr")&&(s.RcvAddr=i.bytes===String?Z.base64.encode(n.RcvAddr,0,n.RcvAddr.length):i.bytes===Array?Array.prototype.slice.call(n.RcvAddr):n.RcvAddr),n.RcvUserName!=null&&n.hasOwnProperty("RcvUserName")&&(s.RcvUserName=i.bytes===String?Z.base64.encode(n.RcvUserName,0,n.RcvUserName.length):i.bytes===Array?Array.prototype.slice.call(n.RcvUserName):n.RcvUserName),n.SndAddr!=null&&n.hasOwnProperty("SndAddr")&&(s.SndAddr=i.bytes===String?Z.base64.encode(n.SndAddr,0,n.SndAddr.length):i.bytes===Array?Array.prototype.slice.call(n.SndAddr):n.SndAddr),n.SndUserName!=null&&n.hasOwnProperty("SndUserName")&&(s.SndUserName=i.bytes===String?Z.base64.encode(n.SndUserName,0,n.SndUserName.length):i.bytes===Array?Array.prototype.slice.call(n.SndUserName):n.SndUserName),n.GasPrice!=null&&n.hasOwnProperty("GasPrice")&&(typeof n.GasPrice=="number"?s.GasPrice=i.longs===String?String(n.GasPrice):n.GasPrice:s.GasPrice=i.longs===String?Z.Long.prototype.toString.call(n.GasPrice):i.longs===Number?new Z.LongBits(n.GasPrice.low>>>0,n.GasPrice.high>>>0).toNumber(!0):n.GasPrice),n.GasLimit!=null&&n.hasOwnProperty("GasLimit")&&(typeof n.GasLimit=="number"?s.GasLimit=i.longs===String?String(n.GasLimit):n.GasLimit:s.GasLimit=i.longs===String?Z.Long.prototype.toString.call(n.GasLimit):i.longs===Number?new Z.LongBits(n.GasLimit.low>>>0,n.GasLimit.high>>>0).toNumber(!0):n.GasLimit),n.Data!=null&&n.hasOwnProperty("Data")&&(s.Data=i.bytes===String?Z.base64.encode(n.Data,0,n.Data.length):i.bytes===Array?Array.prototype.slice.call(n.Data):n.Data),n.ChainID!=null&&n.hasOwnProperty("ChainID")&&(s.ChainID=i.bytes===String?Z.base64.encode(n.ChainID,0,n.ChainID.length):i.bytes===Array?Array.prototype.slice.call(n.ChainID):n.ChainID),n.Version!=null&&n.hasOwnProperty("Version")&&(s.Version=n.Version),n.Signature!=null&&n.hasOwnProperty("Signature")&&(s.Signature=i.bytes===String?Z.base64.encode(n.Signature,0,n.Signature.length):i.bytes===Array?Array.prototype.slice.call(n.Signature):n.Signature),n.Options!=null&&n.hasOwnProperty("Options")&&(s.Options=n.Options),n.GuardAddr!=null&&n.hasOwnProperty("GuardAddr")&&(s.GuardAddr=i.bytes===String?Z.base64.encode(n.GuardAddr,0,n.GuardAddr.length):i.bytes===Array?Array.prototype.slice.call(n.GuardAddr):n.GuardAddr),n.GuardSignature!=null&&n.hasOwnProperty("GuardSignature")&&(s.GuardSignature=i.bytes===String?Z.base64.encode(n.GuardSignature,0,n.GuardSignature.length):i.bytes===Array?Array.prototype.slice.call(n.GuardSignature):n.GuardSignature),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,sa.util.toJSONOptions)},e}(),t}();Vx.exports=Pc});var kx=v(Rr=>{"use strict";l();var SH=Rr&&Rr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),TH=Rr&&Rr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),CH=Rr&&Rr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&SH(e,t,r);return TH(e,t),e},xH=Rr&&Rr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rr,"__esModule",{value:!0});Rr.ProtoSerializer=void 0;var NH=xH(Yt()),tE=pt(),OH=Ns(),DH=CH(Le()),PH=Tc(),rE=class{serializeTransaction(e){let r=Hx().proto,n=new tE.Address(e.getReceiver().bech32()).pubkey(),i=new tE.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?h.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?h.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:h.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==OH.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let u=e.getGuardian();s.GuardAddr=new tE.Address(u.bech32()).pubkey(),s.GuardSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return h.Buffer.from(o)}serializeTransactionValue(e){let r=new NH.default(e.toString());if(r.isZero())return h.Buffer.from([0,0]);let n=PH.bigIntToBuffer(r);return n=h.Buffer.concat([h.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new DH.ErrUnsupportedOperation("deserializeTransaction")}};Rr.ProtoSerializer=rE});var Gx=v(Ms=>{"use strict";l();var RH=Ms&&Ms.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),BH=Ms&&Ms.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&RH(e,t,r)};Object.defineProperty(Ms,"__esModule",{value:!0});BH(kx(),Ms)});var Rc=v(Br=>{"use strict";l();var LH=Br&&Br.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FH=Br&&Br.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),MH=Br&&Br.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LH(e,t,r);return FH(e,t),e};Object.defineProperty(Br,"__esModule",{value:!0});Br.interpretSignatureAsBuffer=Br.Signature=void 0;var jx=MH(Le()),Qx=64,nE=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof h.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new jx.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return h.Buffer.from(e,"hex").length==Qx}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=Qx)throw new jx.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Br.Signature=nE;function UH(t){if(ArrayBuffer.isView(t))return h.Buffer.from(t);if(t.hex!=null)return h.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Br.interpretSignatureAsBuffer=UH});var Yn=v(hh=>{"use strict";l();Object.defineProperty(hh,"__esModule",{value:!0});hh.TransactionPayload=void 0;var iE=class t{constructor(e){this.data=h.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=h.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>h.Buffer.from(e,"hex"))}length(){return h.Buffer.from(this.data).length}};hh.TransactionPayload=iE});var sE=v((uce,zx)=>{l();Jn.notEqual=VH;Jn.notOk=HH;Jn.equal=qH;Jn.ok=Jn;zx.exports=Jn;function qH(t,e,r){Jn(t==e,r)}function VH(t,e,r){Jn(t!=e,r)}function HH(t,e){Jn(!t,e)}function Jn(t,e){if(!t)throw new Error(e||"AssertionError")}});var qs=v(ca=>{"use strict";l();var oE=$0(),aa=Y0(),Wx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;ca.Buffer=W;ca.SlowBuffer=WH;ca.INSPECT_MAX_BYTES=50;var ph=2147483647;ca.kMaxLength=ph;W.TYPED_ARRAY_SUPPORT=kH();!W.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 kH(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(W.prototype,"parent",{enumerable:!0,get:function(){if(W.isBuffer(this))return this.buffer}});Object.defineProperty(W.prototype,"offset",{enumerable:!0,get:function(){if(W.isBuffer(this))return this.byteOffset}});function Xn(t){if(t>ph)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,W.prototype),e}function W(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return lE(t)}return Jx(t,e,r)}W.poolSize=8192;function Jx(t,e,r){if(typeof t=="string")return jH(t,e);if(ArrayBuffer.isView(t))return QH(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(An(t,ArrayBuffer)||t&&An(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(An(t,SharedArrayBuffer)||t&&An(t.buffer,SharedArrayBuffer)))return uE(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return W.from(n,e,r);let i=zH(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return W.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}W.from=function(t,e,r){return Jx(t,e,r)};Object.setPrototypeOf(W.prototype,Uint8Array.prototype);Object.setPrototypeOf(W,Uint8Array);function Xx(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function GH(t,e,r){return Xx(t),t<=0?Xn(t):e!==void 0?typeof r=="string"?Xn(t).fill(e,r):Xn(t).fill(e):Xn(t)}W.alloc=function(t,e,r){return GH(t,e,r)};function lE(t){return Xx(t),Xn(t<0?0:fE(t)|0)}W.allocUnsafe=function(t){return lE(t)};W.allocUnsafeSlow=function(t){return lE(t)};function jH(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!W.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=Zx(t,e)|0,n=Xn(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function aE(t){let e=t.length<0?0:fE(t.length)|0,r=Xn(e);for(let n=0;n=ph)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ph.toString(16)+" bytes");return t|0}function WH(t){return+t!=t&&(t=0),W.alloc(+t)}W.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==W.prototype};W.compare=function(e,r){if(An(e,Uint8Array)&&(e=W.from(e,e.offset,e.byteLength)),An(r,Uint8Array)&&(r=W.from(r,r.offset,r.byteLength)),!W.isBuffer(e)||!W.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let n=e.length,i=r.length;for(let s=0,o=Math.min(n,i);si.length?(W.isBuffer(o)||(o=W.from(o)),o.copy(i,s)):Uint8Array.prototype.set.call(i,o,s);else if(W.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function Zx(t,e){if(W.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||An(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return cE(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return uN(t).length;default:if(i)return n?-1:cE(t).length;e=(""+e).toLowerCase(),i=!0}}W.byteLength=Zx;function $H(t,e,r){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return ik(this,e,r);case"utf8":case"utf-8":return tN(this,e,r);case"ascii":return rk(this,e,r);case"latin1":case"binary":return nk(this,e,r);case"base64":return ek(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}W.prototype._isBuffer=!0;function Us(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}W.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;rr&&(e+=" ... "),""};Wx&&(W.prototype[Wx]=W.prototype.inspect);W.prototype.compare=function(e,r,n,i,s){if(An(e,Uint8Array)&&(e=W.from(e,e.offset,e.byteLength)),!W.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;let o=s-i,a=n-r,u=Math.min(o,a),c=this.slice(i,s),f=e.slice(r,n);for(let d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,hE(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=W.from(e,n)),W.isBuffer(e))return e.length===0?-1:$x(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):$x(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function $x(t,e,r,n,i){let s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function u(f,d){return s===1?f[d]:f.readUInt16BE(d*s)}let c;if(i){let f=-1;for(c=r;co&&(r=o-a),c=r;c>=0;c--){let f=!0;for(let d=0;di&&(n=i)):n=i;let s=e.length;n>s/2&&(n=s/2);let o;for(o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return KH(this,e,r,n);case"utf8":case"utf-8":return YH(this,e,r,n);case"ascii":case"latin1":case"binary":return JH(this,e,r,n);case"base64":return XH(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ZH(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};W.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ek(t,e,r){return e===0&&r===t.length?oE.fromByteArray(t):oE.fromByteArray(t.slice(e,r))}function tN(t,e,r){r=Math.min(t.length,r);let n=[],i=e;for(;i239?4:s>223?3:s>191?2:1;if(i+a<=r){let u,c,f,d;switch(a){case 1:s<128&&(o=s);break;case 2:u=t[i+1],(u&192)===128&&(d=(s&31)<<6|u&63,d>127&&(o=d));break;case 3:u=t[i+1],c=t[i+2],(u&192)===128&&(c&192)===128&&(d=(s&15)<<12|(u&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:u=t[i+1],c=t[i+2],f=t[i+3],(u&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(u&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return tk(n)}var Kx=4096;function tk(t){let e=t.length;if(e<=Kx)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn)&&(r=n);let i="";for(let s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}W.prototype.readUintLE=W.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Vt(e,r,this.length);let i=this[e],s=1,o=0;for(;++o>>0,r=r>>>0,n||Vt(e,r,this.length);let i=this[e+--r],s=1;for(;r>0&&(s*=256);)i+=this[e+--r]*s;return i};W.prototype.readUint8=W.prototype.readUInt8=function(e,r){return e=e>>>0,r||Vt(e,1,this.length),this[e]};W.prototype.readUint16LE=W.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Vt(e,2,this.length),this[e]|this[e+1]<<8};W.prototype.readUint16BE=W.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Vt(e,2,this.length),this[e]<<8|this[e+1]};W.prototype.readUint32LE=W.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};W.prototype.readUint32BE=W.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};W.prototype.readBigUInt64LE=Oi(function(e){e=e>>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<>>0,r=r>>>0,n||Vt(e,r,this.length);let i=this[e],s=1,o=0;for(;++o=s&&(i-=Math.pow(2,8*r)),i};W.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Vt(e,r,this.length);let i=r,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};W.prototype.readInt8=function(e,r){return e=e>>>0,r||Vt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};W.prototype.readInt16LE=function(e,r){e=e>>>0,r||Vt(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};W.prototype.readInt16BE=function(e,r){e=e>>>0,r||Vt(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};W.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};W.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};W.prototype.readBigInt64LE=Oi(function(e){e=e>>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,r||Vt(e,4,this.length),aa.read(this,e,!0,23,4)};W.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),aa.read(this,e,!1,23,4)};W.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Vt(e,8,this.length),aa.read(this,e,!0,52,8)};W.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Vt(e,8,this.length),aa.read(this,e,!1,52,8)};function gr(t,e,r,n,i,s){if(!W.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}W.prototype.writeUintLE=W.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;gr(this,e,r,n,a,0)}let s=1,o=0;for(this[r]=e&255;++o>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;gr(this,e,r,n,a,0)}let s=n-1,o=1;for(this[r+s]=e&255;--s>=0&&(o*=256);)this[r+s]=e/o&255;return r+n};W.prototype.writeUint8=W.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,1,255,0),this[r]=e&255,r+1};W.prototype.writeUint16LE=W.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};W.prototype.writeUint16BE=W.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};W.prototype.writeUint32LE=W.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};W.prototype.writeUint32BE=W.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function rN(t,e,r,n,i){aN(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,r}function nN(t,e,r,n,i){aN(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o=o>>8,t[r+2]=o,o=o>>8,t[r+1]=o,o=o>>8,t[r]=o,r+8}W.prototype.writeBigUInt64LE=Oi(function(e,r=0){return rN(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});W.prototype.writeBigUInt64BE=Oi(function(e,r=0){return nN(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});W.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let u=Math.pow(2,8*n-1);gr(this,e,r,n,u-1,-u)}let s=0,o=1,a=0;for(this[r]=e&255;++s>0)-a&255;return r+n};W.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let u=Math.pow(2,8*n-1);gr(this,e,r,n,u-1,-u)}let s=n-1,o=1,a=0;for(this[r+s]=e&255;--s>=0&&(o*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};W.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};W.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};W.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};W.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};W.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};W.prototype.writeBigInt64LE=Oi(function(e,r=0){return rN(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});W.prototype.writeBigInt64BE=Oi(function(e,r=0){return nN(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function iN(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function sN(t,e,r,n,i){return e=+e,r=r>>>0,i||iN(t,e,r,4,34028234663852886e22,-34028234663852886e22),aa.write(t,e,r,n,23,4),r+4}W.prototype.writeFloatLE=function(e,r,n){return sN(this,e,r,!0,n)};W.prototype.writeFloatBE=function(e,r,n){return sN(this,e,r,!1,n)};function oN(t,e,r,n,i){return e=+e,r=r>>>0,i||iN(t,e,r,8,17976931348623157e292,-17976931348623157e292),aa.write(t,e,r,n,52,8),r+8}W.prototype.writeDoubleLE=function(e,r,n){return oN(this,e,r,!0,n)};W.prototype.writeDoubleBE=function(e,r,n){return oN(this,e,r,!1,n)};W.prototype.copy=function(e,r,n,i){if(!W.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s2**32?i=Yx(String(r)):typeof r=="bigint"&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=Yx(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function Yx(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function ok(t,e,r){ua(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&Bc(e,t.length-(r+1))}function aN(t,e,r,n,i,s){if(t>r||t3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(s+1)*8}${o}`:a=`>= -(2${o} ** ${(s+1)*8-1}${o}) and < 2 ** ${(s+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${r}${o}`,new oa.ERR_OUT_OF_RANGE("value",a,t)}ok(n,i,s)}function ua(t,e){if(typeof t!="number")throw new oa.ERR_INVALID_ARG_TYPE(e,"number",t)}function Bc(t,e,r){throw Math.floor(t)!==t?(ua(t,r),new oa.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new oa.ERR_BUFFER_OUT_OF_BOUNDS:new oa.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var ak=/[^+/0-9A-Za-z-_]/g;function uk(t){if(t=t.split("=")[0],t=t.trim().replace(ak,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function cE(t,e){e=e||1/0;let r,n=t.length,i=null,s=[];for(let o=0;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function ck(t){let e=[];for(let r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function uN(t){return oE.toByteArray(uk(t))}function gh(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function An(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function hE(t){return t!==t}var fk=function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let n=r*16;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Oi(t){return typeof BigInt>"u"?dk:t}function dk(){throw new Error("BigInt not supported")}});var lN=v((hce,cN)=>{l();cN.exports=pE;pE.supported=typeof WebAssembly<"u";function pE(t){if(!pE.supported)return null;var e=t&&t.imports,r=hk("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(u){i.exports.memory.grow(Math.ceil(Math.abs(u-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(u){if(i.exports)return u();if(n){n.then(u.bind(null,null)).catch(u);return}try{if(t&&t.async)throw new Error("async");a({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(a)}o(u)}function a(u){i.exports=u.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function hk(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(pk)):new(qs()).Buffer(t,"base64")}function pk(t){return t.charCodeAt(0)}});var mN=v((mce,In)=>{l();var bn=sE(),Ze=lN()(),Zn=64,yh=[];In.exports=Lr;var fN=In.exports.BYTES_MIN=16,dN=In.exports.BYTES_MAX=64,gce=In.exports.BYTES=32,hN=In.exports.KEYBYTES_MIN=16,pN=In.exports.KEYBYTES_MAX=64,yce=In.exports.KEYBYTES=32,gN=In.exports.SALTBYTES=16,yN=In.exports.PERSONALBYTES=16;function Lr(t,e,r,n,i){if(!(this instanceof Lr))return new Lr(t,e,r,n,i);if(!(Ze&&Ze.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(bn(t>=fN,"digestLength must be at least "+fN+", was given "+t),bn(t<=dN,"digestLength must be at most "+dN+", was given "+t),e!=null&&bn(e.length>=hN,"key must be at least "+hN+", was given "+e.length),e!=null&&bn(e.length<=pN,"key must be at least "+pN+", was given "+e.length),r!=null&&bn(r.length===gN,"salt must be exactly "+gN+", was given "+r.length),n!=null&&bn(n.length===yN,"personal must be exactly "+yN+", was given "+n.length)),yh.length||(yh.push(Zn),Zn+=216),this.digestLength=t,this.finalized=!1,this.pointer=yh.pop(),Ze.memory.fill(0,0,64),Ze.memory[0]=this.digestLength,Ze.memory[1]=e?e.length:0,Ze.memory[2]=1,Ze.memory[3]=1,r&&Ze.memory.set(r,32),n&&Ze.memory.set(n,48),this.pointer+216>Ze.memory.length&&Ze.realloc(this.pointer+216),Ze.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),Ze.memory.fill(0,Zn,Zn+e.length),Ze.memory[this.pointer+200]=128)}Lr.prototype.update=function(t){return bn(this.finalized===!1,"Hash instance finalized"),bn(t,"input must be TypedArray or Buffer"),Zn+t.length>Ze.memory.length&&Ze.realloc(Zn+t.length),Ze.memory.set(t,Zn),Ze.exports.blake2b_update(this.pointer,Zn,Zn+t.length),this};Lr.prototype.digest=function(t){if(bn(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,yh.push(this.pointer),Ze.exports.blake2b_final(this.pointer),!t||t==="binary")return Ze.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return yk(Ze.memory,this.pointer+128,this.digestLength);bn(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{l();var Ri=sE(),Fc=mN();function mh(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function wN(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function SN(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Di(t,e,r,n,i,s){var o=Lc[i],a=Lc[i+1],u=Lc[s],c=Lc[s+1];mh(xe,t,e),wN(xe,t,o,a);var f=xe[n]^xe[t],d=xe[n+1]^xe[t+1];xe[n]=d,xe[n+1]=f,mh(xe,r,n),f=xe[e]^xe[r],d=xe[e+1]^xe[r+1],xe[e]=f>>>24^d<<8,xe[e+1]=d>>>24^f<<8,mh(xe,t,e),wN(xe,t,u,c),f=xe[n]^xe[t],d=xe[n+1]^xe[t+1],xe[n]=f>>>16^d<<16,xe[n+1]=d>>>16^f<<16,mh(xe,r,n),f=xe[e]^xe[r],d=xe[e+1]^xe[r+1],xe[e]=d>>>31^f<<1,xe[e+1]=f>>>31^d<<1}var TN=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),wk=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Xt=new Uint8Array(wk.map(function(t){return t*2})),xe=new Uint32Array(32),Lc=new Uint32Array(32);function CN(t,e){var r=0;for(r=0;r<16;r++)xe[r]=t.h[r],xe[r+16]=TN[r];for(xe[24]=xe[24]^t.t,xe[25]=xe[25]^t.t/4294967296,e&&(xe[28]=~xe[28],xe[29]=~xe[29]),r=0;r<32;r++)Lc[r]=SN(t.b,4*r);for(r=0;r<12;r++)Di(0,8,16,24,Xt[r*16+0],Xt[r*16+1]),Di(2,10,18,26,Xt[r*16+2],Xt[r*16+3]),Di(4,12,20,28,Xt[r*16+4],Xt[r*16+5]),Di(6,14,22,30,Xt[r*16+6],Xt[r*16+7]),Di(0,10,20,30,Xt[r*16+8],Xt[r*16+9]),Di(2,12,22,24,Xt[r*16+10],Xt[r*16+11]),Di(4,14,16,26,Xt[r*16+12],Xt[r*16+13]),Di(6,8,18,28,Xt[r*16+14],Xt[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^xe[r]^xe[r+16]}var Pi=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function la(t,e,r,n){Pi.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Pi[0]=t,e&&(Pi[1]=e.length),Pi[2]=1,Pi[3]=1,r&&Pi.set(r,32),n&&Pi.set(n,48);for(var i=0;i<16;i++)this.h[i]=TN[i]^SN(Pi,i*4);e&&(xN(this,e),this.c=128)}la.prototype.update=function(t){return Ri(t!=null,"input must be Uint8Array or Buffer"),xN(this,t),this};la.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Ri(e.length>=this.outlen,"out must have at least outlen bytes of space"),Ek(this,e),t==="hex"?vk(e):e};la.prototype.final=la.prototype.digest;la.ready=function(t){Fc.ready(function(){t()})};function xN(t,e){for(var r=0;r>2]>>8*(r&3);return e}function vk(t){for(var e="",r=0;r=EN,"outlen must be at least "+EN+", was given "+e),Ri(e<=vN,"outlen must be at most "+vN+", was given "+e),r!=null&&Ri(r.length>=AN,"key must be at least "+AN+", was given "+r.length),r!=null&&Ri(r.length<=bN,"key must be at most "+bN+", was given "+r.length),n!=null&&Ri(n.length===IN,"salt must be exactly "+IN+", was given "+n.length),i!=null&&Ri(i.length===_N,"personal must be exactly "+_N+", was given "+i.length)),new NN(e,r,n,i)};yr.exports.ready=function(t){Fc.ready(function(){t()})};yr.exports.WASM_SUPPORTED=Fc.SUPPORTED;yr.exports.WASM_LOADED=!1;var EN=yr.exports.BYTES_MIN=16,vN=yr.exports.BYTES_MAX=64,Ece=yr.exports.BYTES=32,AN=yr.exports.KEYBYTES_MIN=16,bN=yr.exports.KEYBYTES_MAX=64,vce=yr.exports.KEYBYTES=32,IN=yr.exports.SALTBYTES=16,_N=yr.exports.PERSONALBYTES=16;Fc.ready(function(t){t||(yr.exports.WASM_LOADED=!0,NN=Fc)})});var Yr=v(Fr=>{"use strict";l();var bk=Fr&&Fr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ik=Fr&&Fr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_k=Fr&&Fr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&bk(e,t,r);return Ik(e,t),e};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.TransactionHash=Fr.Transaction=void 0;var fa=Yt(),Mc=pt(),Sk=ah(),Tk=Ns(),Ck=_k(Le()),xk=HC(),ei=xc(),Nk=Gx(),wh=Rc(),ON=Yn(),Ok=br(),Dk=gE(),Pk=32,yE=class t{constructor({nonce:e,value:r,sender:n,receiver:i,senderUsername:s,receiverUsername:o,gasPrice:a,gasLimit:u,data:c,chainID:f,version:d,options:g,guardian:m}){this.nonce=e||0,this.value=r?new fa.BigNumber(r.toString()).toFixed(0):0,this.sender=n,this.receiver=i,this.senderUsername=s||"",this.receiverUsername=o||"",this.gasPrice=a||Tk.TRANSACTION_MIN_GAS_PRICE,this.gasLimit=u,this.data=c||new ON.TransactionPayload,this.chainID=f,this.version=d?new ei.TransactionVersion(d.valueOf()):ei.TransactionVersion.withDefaultVersion(),this.options=g?new ei.TransactionOptions(g.valueOf()):ei.TransactionOptions.withDefaultOptions(),this.guardian=m||Mc.Address.empty(),this.signature=h.Buffer.from([]),this.guardianSignature=h.Buffer.from([]),this.hash=da.empty()}getNonce(){return this.nonce}setNonce(e){this.nonce=e}getValue(){return this.value}setValue(e){this.value=e}getSender(){return this.sender}setSender(e){this.sender=e}getReceiver(){return this.receiver}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return this.guardian}getGasPrice(){return this.gasPrice}setGasPrice(e){this.gasPrice=e}getGasLimit(){return this.gasLimit}setGasLimit(e){this.gasLimit=e}getData(){return this.data}getChainID(){return this.chainID}setChainID(e){this.chainID=e}getVersion(){return this.version}setVersion(e){this.version=new ei.TransactionVersion(e.valueOf())}getOptions(){return new ei.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=new ei.TransactionOptions(e.valueOf())}getSignature(){return this.signature}getGuardianSignature(){return this.guardianSignature}setGuardian(e){this.guardian=e}getHash(){return Ok.guardNotEmpty(this.hash,"hash"),this.hash}serializeForSigning(){let e=this.toPlainObject();e.signature&&delete e.signature,e.guardianSignature&&delete e.guardianSignature,e.guardian||delete e.guardian;let r=JSON.stringify(e);return h.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.bech32().length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){var e;let r={nonce:this.nonce.valueOf(),value:this.value.toString(),receiver:this.receiver.bech32(),sender:this.sender.bech32(),senderUsername:this.senderUsername?h.Buffer.from(this.senderUsername).toString("base64"):void 0,receiverUsername:this.receiverUsername?h.Buffer.from(this.receiverUsername).toString("base64"):void 0,gasPrice:this.gasPrice.valueOf(),gasLimit:this.gasLimit.valueOf(),data:this.data.length()==0?void 0:this.data.encoded(),chainID:this.chainID.valueOf(),version:this.getVersion().valueOf(),options:this.getOptions().valueOf()==0?void 0:this.getOptions().valueOf(),guardian:!((e=this.guardian)===null||e===void 0)&&e.bech32()?this.guardian.bech32()==""?void 0:this.guardian.bech32():void 0,signature:this.signature.toString("hex")?this.signature.toString("hex"):void 0,guardianSignature:this.guardianSignature.toString("hex")?this.guardianSignature.toString("hex"):void 0};return Sk.Compatibility.guardAddressIsSetAndNonZero(new Mc.Address(r.sender),"'sender' of transaction","pass the actual sender to the Transaction constructor"),r}static fromPlainObject(e){let r=new t({nonce:Number(e.nonce),value:new fa.BigNumber(e.value).toFixed(0),receiver:Mc.Address.fromString(e.receiver),receiverUsername:e.receiverUsername?h.Buffer.from(e.receiverUsername,"base64").toString():void 0,sender:Mc.Address.fromString(e.sender),senderUsername:e.senderUsername?h.Buffer.from(e.senderUsername,"base64").toString():void 0,guardian:e.guardian?Mc.Address.fromString(e.guardian):void 0,gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:new ON.TransactionPayload(h.Buffer.from(e.data||"","base64")),chainID:String(e.chainID),version:new ei.TransactionVersion(e.version),options:e.options!=null?new ei.TransactionOptions(e.options):void 0});return e.signature&&r.applySignature(new wh.Signature(e.signature)),e.guardianSignature&&r.applyGuardianSignature(new wh.Signature(e.guardianSignature)),r}applySignature(e){this.signature=wh.interpretSignatureAsBuffer(e),this.hash=da.compute(this)}applyGuardianSignature(e){this.guardianSignature=wh.interpretSignatureAsBuffer(e),this.hash=da.compute(this)}toSendable(){return this.toPlainObject()}computeFee(e){let r=e.MinGasLimit.valueOf()+this.data.length()*e.GasPerDataByte.valueOf();if(r>this.gasLimit.valueOf())throw new Ck.ErrNotEnoughGas(this.gasLimit.valueOf());let n=new fa.BigNumber(this.gasPrice.valueOf()),i=new fa.BigNumber(r).multipliedBy(n);if(r===this.gasLimit.valueOf())return i;let s=new fa.BigNumber(this.gasLimit.valueOf()-r),o=n.multipliedBy(new fa.BigNumber(e.GasPriceModifier.valueOf())),a=s.multipliedBy(o);return i.plus(a)}};Fr.Transaction=yE;var da=class t extends xk.Hash{constructor(e){super(e)}static compute(e){let n=new Nk.ProtoSerializer().serializeTransaction(e),i=Dk(Pk).update(n).digest("hex");return new t(i)}};Fr.TransactionHash=da});var vE=v(vh=>{"use strict";l();Object.defineProperty(vh,"__esModule",{value:!0});vh.TransferTransactionsFactory=void 0;var mE=na(),Jr=xt(),Eh=Yr(),wE=Yn(),EE=class{constructor(e){this.gasEstimator=e}createEGLDTransfer(e){var r;let n=((r=e.data)===null||r===void 0?void 0:r.length())||0,i=this.gasEstimator.forEGLDTransfer(n);return new Eh.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||i,data:e.data,chainID:e.chainID})}createESDTTransfer(e){let{argumentsString:r}=new mE.ArgSerializer().valuesToString([Jr.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new Jr.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Eh.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){let{argumentsString:r}=new mE.ArgSerializer().valuesToString([Jr.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new Jr.U64Value(e.tokenTransfer.nonce),new Jr.BigUIntValue(e.tokenTransfer.valueOf()),new Jr.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Eh.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){let r=[new Jr.AddressValue(e.destination),new Jr.U16Value(e.tokenTransfers.length)];for(let u of e.tokenTransfers)r.push(Jr.BytesValue.fromUTF8(u.tokenIdentifier),new Jr.U64Value(u.nonce),new Jr.BigUIntValue(u.valueOf()));let{argumentsString:n}=new mE.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new wE.TransactionPayload(i),o=s.length()||0,a=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Eh.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||a,data:s,chainID:e.chainID})}};vh.TransferTransactionsFactory=EE});var bE=v(Vs=>{"use strict";l();Object.defineProperty(Vs,"__esModule",{value:!0});Vs.GasEstimator=Vs.DefaultGasConfiguration=void 0;Vs.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Rk=1e5,DN=8e5,AE=class{constructor(e){this.gasConfiguration=e||Vs.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Rk}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+DN}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+DN)*r+this.gasConfiguration.gasPerDataByte*e}};Vs.GasEstimator=AE});var ha=v(Ah=>{"use strict";l();Object.defineProperty(Ah,"__esModule",{value:!0});Ah.Account=void 0;var Bk=pt(),IE=class{constructor(e){this.address=new Bk.Address,this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};Ah.Account=IE});var pa=v(ks=>{"use strict";l();Object.defineProperty(ks,"__esModule",{value:!0});ks.Logger=ks.LogLevel=void 0;var Hs;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Hs=ks.LogLevel||(ks.LogLevel={}));var bh=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Hs.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Hs.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Hs.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Hs.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Hs.Error||console.error(e,r)}};ks.Logger=bh;bh.logLevel=Hs.Debug});var TE=v(_n=>{"use strict";l();var Lk=_n&&_n.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Fk=_n&&_n.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mk=_n&&_n.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lk(e,t,r);return Fk(e,t),e};Object.defineProperty(_n,"__esModule",{value:!0});_n.AsyncTimer=void 0;var Uk=Mk(Le()),qk=Le(),_E=pa(),SE=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new Uk.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,_E.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){_E.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new qk.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(_E.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};_n.AsyncTimer=SE});var Ih=v(ga=>{"use strict";l();var Mr=ga&&ga.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ga,"__esModule",{value:!0});ga.TransactionWatcher=void 0;var CE=TE(),Bi=Le(),PN=pa(),Li=class t{constructor(e,r={}){this.fetcher=new xE(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}awaitPending(e){return Mr(this,void 0,void 0,function*(){let r=s=>s.status.isPending(),n=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),i=()=>new Bi.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)})}awaitCompleted(e){return Mr(this,void 0,void 0,function*(){let r=s=>{if(s.isCompleted===void 0)throw new Bi.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),i=()=>new Bi.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)})}awaitAllEvents(e,r){return Mr(this,void 0,void 0,function*(){let n=o=>{let a=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>a.includes(c))},i=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),s=()=>new Bi.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)})}awaitAnyEvent(e,r){return Mr(this,void 0,void 0,function*(){let n=o=>{let a=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>a.includes(c))!=null},i=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),s=()=>new Bi.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)})}awaitOnCondition(e,r){return Mr(this,void 0,void 0,function*(){let n=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),i=()=>new Bi.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)})}awaitConditionally(e,r,n){return Mr(this,void 0,void 0,function*(){let i=new CE.AsyncTimer("watcher:periodic"),s=new CE.AsyncTimer("watcher:patience"),o=new CE.AsyncTimer("watcher:timeout"),a=!1,u,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),a=!0});!a;){yield i.start(this.pollingIntervalMilliseconds);try{if(u=yield r(),c=e(u),c||a)break}catch(f){if(PN.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Bi.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Bi.Err))throw f}}if(c&&(yield s.start(this.patienceMilliseconds)),o.isStopped()||o.stop(),!u||!c)throw n();return u})}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};ga.TransactionWatcher=Li;Li.DefaultPollingInterval=6e3;Li.DefaultTimeout=Li.DefaultPollingInterval*15;Li.DefaultPatience=0;Li.NoopOnStatusReceived=t=>{};var xE=class{constructor(e){this.fetcher=e}getTransaction(e){return Mr(this,void 0,void 0,function*(){return PN.Logger.debug(`transactionWatcher, getTransaction(${e})`),yield this.fetcher.getTransaction(e)})}}});var NE=v(_h=>{"use strict";l();Object.defineProperty(_h,"__esModule",{value:!0});_h.CodeMetadata=void 0;var Uc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBuffer(e){if(e.length<2)throw new Error("Buffer is too short.");let r=e[0],n=e[1],i=(r&t.ByteZero.Upgradeable)!==0,s=(r&t.ByteZero.Readable)!==0,o=(n&t.ByteOne.Payable)!==0,a=(n&t.ByteOne.PayableBySc)!==0;return new t(i,s,o,a)}toggleUpgradeable(e){this.upgradeable=e}toggleReadable(e){this.readable=e}togglePayable(e){this.payable=e}togglePayableBySc(e){this.payableBySc=e}toBuffer(){let e=0,r=0;return this.upgradeable&&(e|=t.ByteZero.Upgradeable),this.readable&&(e|=t.ByteZero.Readable),this.payable&&(r|=t.ByteOne.Payable),this.payableBySc&&(r|=t.ByteOne.PayableBySc),h.Buffer.from([e,r])}toString(){return this.toBuffer().toString("hex")}toJSON(){return{upgradeable:this.upgradeable,readable:this.readable,payable:this.payable,payableBySc:this.payableBySc}}equals(e){return this.upgradeable==e.upgradeable&&this.readable==e.readable&&this.payable==e.payable&&this.payableBySc==e.payableBySc}};_h.CodeMetadata=Uc;Uc.ByteZero={Upgradeable:1,Reserved2:2,Readable:4};Uc.ByteOne={Reserved1:1,Payable:2,PayableBySc:4}});var qc=v(Sn=>{"use strict";l();var Vk=Sn&&Sn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Hk=Sn&&Sn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kk=Sn&&Sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Vk(e,t,r);return Hk(e,t),e};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.ContractFunction=void 0;var Gk=kk(Le()),OE=class t{constructor(e){if(this.name=e,e==null)throw new Gk.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Sn.ContractFunction=OE});var RE=v(Ur=>{"use strict";l();var jk=Ur&&Ur.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Qk=Ur&&Ur.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zk=Ur&&Ur.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&jk(e,t,r);return Qk(e,t),e},Wk=Ur&&Ur.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.InteractionChecker=void 0;var DE=zk(Le()),$k=Wk(Yt()),PE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new $k.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new DE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new DE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let a=0;a{"use strict";l();Object.defineProperty(Sh,"__esModule",{value:!0});Sh.Query=void 0;var Kk=pt(),Yk=na(),BE=class{constructor(e){this.caller=e.caller||new Kk.Address,this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new Yk.ArgSerializer().valuesToStrings(this.args)}};Sh.Query=BE});var UE=v(Th=>{"use strict";l();Object.defineProperty(Th,"__esModule",{value:!0});Th.Interaction=void 0;var RN=pt(),Jk=ah(),LE=Ns(),FE=qc(),Xk=RE(),Zk=Vc(),ya=xt(),ME=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=new RN.Address,this.sender=new RN.Address,this.isWithSingleESDTTransfer=!1,this.isWithSingleESDTNFTTransfer=!1,this.isWithMultiESDTNFTTransfer=!1,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=new ma([],this)}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers.getTransfers()}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){Jk.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=this.explicitReceiver||this.contract.getAddress(),r=this.function,n=this.args;this.isWithSingleESDTTransfer?(r=new FE.ContractFunction(LE.ESDT_TRANSFER_FUNCTION_NAME),n=this.tokenTransfers.buildArgsForSingleESDTTransfer()):this.isWithSingleESDTNFTTransfer?(e=this.sender,r=new FE.ContractFunction(LE.ESDTNFT_TRANSFER_FUNCTION_NAME),n=this.tokenTransfers.buildArgsForSingleESDTNFTTransfer()):this.isWithMultiESDTNFTTransfer&&(e=this.sender,r=new FE.ContractFunction(LE.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME),n=this.tokenTransfers.buildArgsForMultiESDTNFTTransfer());let i=this.contract.call({func:r,gasLimit:this.gasLimit,gasPrice:this.gasPrice,args:n,value:this.value,receiver:e,chainID:this.chainID,caller:this.sender});return i.setNonce(this.nonce),i}buildQuery(){return new Zk.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.isWithSingleESDTTransfer=!0,this.tokenTransfers=new ma([e],this),this}withSingleESDTNFTTransfer(e,r){return this.isWithSingleESDTNFTTransfer=!0,this.tokenTransfers=new ma([e],this),r&&(this.sender=r),this}withMultiESDTNFTTransfer(e,r){return this.isWithMultiESDTNFTTransfer=!0,this.tokenTransfers=new ma(e,this),r&&(this.sender=r),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new Xk.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};Th.Interaction=ME;var ma=class{constructor(e,r){this.transfers=e,this.interaction=r}getTransfers(){return this.transfers}buildArgsForSingleESDTTransfer(){let e=this.transfers[0];return[this.getTypedTokenIdentifier(e),this.getTypedTokenQuantity(e),this.getTypedInteractionFunction(),...this.getInteractionArguments()]}buildArgsForSingleESDTNFTTransfer(){let e=this.transfers[0];return[this.getTypedTokenIdentifier(e),this.getTypedTokenNonce(e),this.getTypedTokenQuantity(e),this.getTypedTokensReceiver(),this.getTypedInteractionFunction(),...this.getInteractionArguments()]}buildArgsForMultiESDTNFTTransfer(){let e=[];e.push(this.getTypedTokensReceiver()),e.push(this.getTypedNumberOfTransfers());for(let r of this.transfers)e.push(this.getTypedTokenIdentifier(r)),e.push(this.getTypedTokenNonce(r)),e.push(this.getTypedTokenQuantity(r));return e.push(this.getTypedInteractionFunction()),e.push(...this.getInteractionArguments()),e}getTypedNumberOfTransfers(){return new ya.U8Value(this.transfers.length)}getTypedTokenIdentifier(e){return ya.BytesValue.fromUTF8(e.tokenIdentifier)}getTypedTokenNonce(e){return new ya.U64Value(e.nonce)}getTypedTokenQuantity(e){return new ya.BigUIntValue(e.amountAsBigInteger)}getTypedTokensReceiver(){return new ya.AddressValue(this.interaction.getContractAddress())}getTypedInteractionFunction(){return ya.BytesValue.fromUTF8(this.interaction.getFunction().valueOf())}getInteractionArguments(){return this.interaction.getArguments()}}});var BN=v(Ch=>{"use strict";l();Object.defineProperty(Ch,"__esModule",{value:!0});Ch.ArgumentErrorContext=void 0;var eG=Le(),qE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new eG.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) -Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};Ch.ArgumentErrorContext=qE});var HE=v(Gs=>{"use strict";l();var tG=Gs&&Gs.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Gs,"__esModule",{value:!0});Gs.NativeSerializer=void 0;var rG=tG(Yt()),nG=pt(),VE=Le(),iG=Md(),sG=BN(),_e=xt(),oG;(function(t){function e(b,S){b=b||[],r(b,S),n(S)&&(b=i(b,S));let N=S.input,_=[];for(let T=0;T0&&S[0].type.getCardinality().isComposite()&&(_=1/0,T=!0);for(let B of S){if(B.type.getCardinality().isSingular())break;N-=1}return{min:N,max:_,variadic:T}}function o(b,S,N){if(b&&b.belongsToTypesystem)return b;if(S instanceof _e.OptionType)return a(b,S,N);if(S instanceof _e.OptionalType)return u(b,S,N);if(S instanceof _e.VariadicType)return c(b,S,N);if(S instanceof _e.CompositeType)return d(b,S,N);if(S instanceof _e.TupleType)return g(b,S,N);if(S instanceof _e.StructType)return m(b,S,N);if(S instanceof _e.ListType)return f(b,S,N);if(S instanceof _e.PrimitiveType)return y(b,S,N);if(S instanceof _e.EnumType)return A(b,S,N);N.throwError(`convertToTypedValue: unhandled type ${S}`)}function a(b,S,N){if(b==null)return _e.OptionValue.newMissing();let _=o(b,S.getFirstTypeParameter(),N);return _e.OptionValue.newProvided(_)}function u(b,S,N){if(b==null)return new _e.OptionalValue(S);let _=o(b,S.getFirstTypeParameter(),N);return new _e.OptionalValue(S,_)}function c(b,S,N){if(S.isCounted)throw new VE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');b==null&&(b=[]),b.map===void 0&&N.convertError(b,"Variadic");let _=b.map(function(T){return o(T,S.getFirstTypeParameter(),N)});return new _e.VariadicValue(S,_)}function f(b,S,N){b.map===void 0&&N.convertError(b,"List");let _=b.map(function(T){return o(T,S.getFirstTypeParameter(),N)});return new _e.List(S,_)}function d(b,S,N){let _=[],T=S.getTypeParameters();N.guardSameLength(b,T);for(let B=0;B{"use strict";l();Object.defineProperty(Xr,"__esModule",{value:!0});Xr.ContractCallPayloadBuilder=Xr.ContractUpgradePayloadBuilder=Xr.ContractDeployPayloadBuilder=Xr.ArwenVirtualMachine=void 0;var QE=Yn(),zE=br(),aG=na();Xr.ArwenVirtualMachine="0500";var kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${Xr.ArwenVirtualMachine}@${r}`;return n=WE(n,this.arguments),new QE.TransactionPayload(n)}};Xr.ContractDeployPayloadBuilder=kE;var GE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=WE(n,this.arguments),new QE.TransactionPayload(n)}};Xr.ContractUpgradePayloadBuilder=GE;var jE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=WE(e,this.arguments),new QE.TransactionPayload(e)}};Xr.ContractCallPayloadBuilder=jE;function WE(t,e){let{argumentsString:r,count:n}=new aG.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var ti=v((Zce,KE)=>{"use strict";l();var wa=typeof Reflect=="object"?Reflect:null,LN=wa&&typeof wa.apply=="function"?wa.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},xh;wa&&typeof wa.ownKeys=="function"?xh=wa.ownKeys:Object.getOwnPropertySymbols?xh=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:xh=function(e){return Object.getOwnPropertyNames(e)};function uG(t){console&&console.warn&&console.warn(t)}var MN=Number.isNaN||function(e){return e!==e};function We(){We.init.call(this)}KE.exports=We;KE.exports.once=dG;We.EventEmitter=We;We.prototype._events=void 0;We.prototype._eventsCount=0;We.prototype._maxListeners=void 0;var FN=10;function Nh(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(We,"defaultMaxListeners",{enumerable:!0,get:function(){return FN},set:function(t){if(typeof t!="number"||t<0||MN(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");FN=t}});We.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};We.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||MN(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function UN(t){return t._maxListeners===void 0?We.defaultMaxListeners:t._maxListeners}We.prototype.getMaxListeners=function(){return UN(this)};We.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=s[e];if(u===void 0)return!1;if(typeof u=="function")LN(u,this,r);else for(var c=u.length,f=GN(u,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,uG(a)}return t}We.prototype.addListener=function(e,r){return qN(this,e,r,!1)};We.prototype.on=We.prototype.addListener;We.prototype.prependListener=function(e,r){return qN(this,e,r,!0)};function cG(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function VN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=cG.bind(n);return i.listener=r,n.wrapFn=i,i}We.prototype.once=function(e,r){return Nh(r),this.on(e,VN(this,e,r)),this};We.prototype.prependOnceListener=function(e,r){return Nh(r),this.prependListener(e,VN(this,e,r)),this};We.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Nh(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():lG(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};We.prototype.off=We.prototype.removeListener;We.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function HN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?fG(i):GN(i,i.length)}We.prototype.listeners=function(e){return HN(this,e,!0)};We.prototype.rawListeners=function(e){return HN(this,e,!1)};We.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):kN.call(t,e)};We.prototype.listenerCount=kN;function kN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}We.prototype.eventNames=function(){return this._eventsCount>0?xh(this._events):[]};function GN(t,e){for(var r=new Array(e),n=0;n{l();QN.exports=ti().EventEmitter});var JE=v(()=>{l()});var JN=v((ole,YN)=>{"use strict";l();function zN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function WN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Oh.alloc(0);for(var n=Oh.allocUnsafe(r>>>0),i=this.head,s=0;i;)AG(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(a===o.length?s+=o:s+=o.slice(0,r),r-=a,r===0){a===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(a));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Oh.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,a=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,a),r-=a,r===0){a===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(a));break}++s}return this.length-=s,n}},{key:vG,value:function(r,n){return XE(this,WN(WN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var ev=v((ule,ZN)=>{"use strict";l();function bG(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,p.default.nextTick(ZE,this,t)):p.default.nextTick(ZE,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?p.default.nextTick(Dh,r):(r._writableState.errorEmitted=!0,p.default.nextTick(XN,r,s)):p.default.nextTick(XN,r,s):e?(p.default.nextTick(Dh,r),e(s)):p.default.nextTick(Dh,r)}),this)}function XN(t,e){ZE(t,e),Dh(t)}function Dh(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function IG(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function ZE(t,e){t.emit("error",e)}function _G(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}ZN.exports={destroy:bG,undestroy:IG,errorOrDestroy:_G}});var js=v((lle,rO)=>{"use strict";l();function SG(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var tO={};function qr(t,e,r){r||(r=Error);function n(s,o,a){return typeof e=="string"?e:e(s,o,a)}var i=function(s){SG(o,s);function o(a,u,c){return s.call(this,n(a,u,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,tO[t]=i}function eO(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function TG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function CG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function xG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}qr("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);qr("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&TG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(CG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(eO(e,"type"));else{var s=xG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(eO(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);qr("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");qr("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});qr("ERR_STREAM_PREMATURE_CLOSE","Premature close");qr("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});qr("ERR_MULTIPLE_CALLBACK","Callback called multiple times");qr("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");qr("ERR_STREAM_WRITE_AFTER_END","write after end");qr("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);qr("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);qr("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");rO.exports.codes=tO});var tv=v((dle,nO)=>{"use strict";l();var NG=js().codes.ERR_INVALID_OPT_VALUE;function OG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function DG(t,e,r,n){var i=OG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new NG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}nO.exports={getHighWaterMark:DG}});var Ea=v((ple,rv)=>{l();typeof Object.create=="function"?rv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:rv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var sO=v((yle,iO)=>{l();iO.exports=PG;function PG(t,e){if(nv("noDeprecation"))return t;var r=!1;function n(){if(!r){if(nv("throwDeprecation"))throw new Error(e);nv("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function nv(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var ov=v((wle,fO)=>{"use strict";l();fO.exports=gt;function aO(t){var e=this;this.next=null,this.entry=null,this.finish=function(){sj(e,t)}}var va;gt.WritableState=kc;var RG={deprecate:sO()},uO=YE(),Rh=qs().Buffer,BG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function LG(t){return Rh.from(t)}function FG(t){return Rh.isBuffer(t)||t instanceof BG}var sv=ev(),MG=tv(),UG=MG.getHighWaterMark,Fi=js().codes,qG=Fi.ERR_INVALID_ARG_TYPE,VG=Fi.ERR_METHOD_NOT_IMPLEMENTED,HG=Fi.ERR_MULTIPLE_CALLBACK,kG=Fi.ERR_STREAM_CANNOT_PIPE,GG=Fi.ERR_STREAM_DESTROYED,jG=Fi.ERR_STREAM_NULL_VALUES,QG=Fi.ERR_STREAM_WRITE_AFTER_END,zG=Fi.ERR_UNKNOWN_ENCODING,Aa=sv.errorOrDestroy;Ea()(gt,uO);function WG(){}function kc(t,e,r){va=va||Qs(),t=t||{},typeof r!="boolean"&&(r=e instanceof va),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=UG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){ej(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new aO(this)}kc.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(kc.prototype,"buffer",{get:RG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var Ph;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Ph=Function.prototype[Symbol.hasInstance],Object.defineProperty(gt,Symbol.hasInstance,{value:function(e){return Ph.call(this,e)?!0:this!==gt?!1:e&&e._writableState instanceof kc}})):Ph=function(e){return e instanceof this};function gt(t){va=va||Qs();var e=this instanceof va;if(!e&&!Ph.call(gt,this))return new gt(t);this._writableState=new kc(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),uO.call(this)}gt.prototype.pipe=function(){Aa(this,new kG)};function $G(t,e){var r=new QG;Aa(t,r),p.default.nextTick(e,r)}function KG(t,e,r,n){var i;return r===null?i=new jG:typeof r!="string"&&!e.objectMode&&(i=new qG("chunk",["string","Buffer"],r)),i?(Aa(t,i),p.default.nextTick(n,i),!1):!0}gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&FG(t);return s&&!Rh.isBuffer(t)&&(t=LG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=WG),n.ending?$G(this,r):(s||KG(this,n,t,r))&&(n.pendingcb++,i=JG(this,n,s,t,e,r)),i};gt.prototype.cork=function(){this._writableState.corked++};gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&cO(this,t))};gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new zG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function YG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=Rh.from(e,r)),e}Object.defineProperty(gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function JG(t,e,r,n,i,s){if(!r){var o=YG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var a=e.objectMode?1:n.length;e.length+=a;var u=e.length{"use strict";l();var oj=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};hO.exports=Tn;var dO=cv(),uv=ov();Ea()(Tn,dO);for(av=oj(uv.prototype),Bh=0;Bh{l();var Fh=qs(),Cn=Fh.Buffer;function pO(t,e){for(var r in t)e[r]=t[r]}Cn.from&&Cn.alloc&&Cn.allocUnsafe&&Cn.allocUnsafeSlow?gO.exports=Fh:(pO(Fh,lv),lv.Buffer=zs);function zs(t,e,r){return Cn(t,e,r)}zs.prototype=Object.create(Cn.prototype);pO(Cn,zs);zs.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Cn(t,e,r)};zs.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Cn(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};zs.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Cn(t)};zs.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fh.SlowBuffer(t)}});var hv=v(wO=>{"use strict";l();var dv=yO().Buffer,mO=dv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function cj(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function lj(t){var e=cj(t);if(typeof e!="string"&&(dv.isEncoding===mO||!mO(t)))throw new Error("Unknown encoding: "+t);return e||t}wO.StringDecoder=Gc;function Gc(t){this.encoding=lj(t);var e;switch(this.encoding){case"utf16le":this.text=yj,this.end=mj,e=4;break;case"utf8":this.fillLast=hj,e=4;break;case"base64":this.text=wj,this.end=Ej,e=3;break;default:this.write=vj,this.end=Aj;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=dv.allocUnsafe(e)}Gc.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function fj(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function dj(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function hj(t){var e=this.lastTotal-this.lastNeed,r=dj(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function pj(t,e){var r=fj(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function gj(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function yj(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function mj(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function wj(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Ej(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function vj(t){return t.toString(this.encoding)}function Aj(t){return t&&t.length?this.write(t):""}});var Mh=v((Sle,AO)=>{"use strict";l();var EO=js().codes.ERR_STREAM_PREMATURE_CLOSE;function bj(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";l();var Uh;function Mi(t,e,r){return e=Sj(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Sj(t){var e=Tj(t,"string");return typeof e=="symbol"?e:String(e)}function Tj(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Cj=Mh(),Ui=Symbol("lastResolve"),Ws=Symbol("lastReject"),jc=Symbol("error"),qh=Symbol("ended"),$s=Symbol("lastPromise"),pv=Symbol("handlePromise"),Ks=Symbol("stream");function qi(t,e){return{value:t,done:e}}function xj(t){var e=t[Ui];if(e!==null){var r=t[Ks].read();r!==null&&(t[$s]=null,t[Ui]=null,t[Ws]=null,e(qi(r,!1)))}}function Nj(t){p.default.nextTick(xj,t)}function Oj(t,e){return function(r,n){t.then(function(){if(e[qh]){r(qi(void 0,!0));return}e[pv](r,n)},n)}}var Dj=Object.getPrototypeOf(function(){}),Pj=Object.setPrototypeOf((Uh={get stream(){return this[Ks]},next:function(){var e=this,r=this[jc];if(r!==null)return Promise.reject(r);if(this[qh])return Promise.resolve(qi(void 0,!0));if(this[Ks].destroyed)return new Promise(function(o,a){p.default.nextTick(function(){e[jc]?a(e[jc]):o(qi(void 0,!0))})});var n=this[$s],i;if(n)i=new Promise(Oj(n,this));else{var s=this[Ks].read();if(s!==null)return Promise.resolve(qi(s,!1));i=new Promise(this[pv])}return this[$s]=i,i}},Mi(Uh,Symbol.asyncIterator,function(){return this}),Mi(Uh,"return",function(){var e=this;return new Promise(function(r,n){e[Ks].destroy(null,function(i){if(i){n(i);return}r(qi(void 0,!0))})})}),Uh),Dj),Rj=function(e){var r,n=Object.create(Pj,(r={},Mi(r,Ks,{value:e,writable:!0}),Mi(r,Ui,{value:null,writable:!0}),Mi(r,Ws,{value:null,writable:!0}),Mi(r,jc,{value:null,writable:!0}),Mi(r,qh,{value:e._readableState.endEmitted,writable:!0}),Mi(r,pv,{value:function(s,o){var a=n[Ks].read();a?(n[$s]=null,n[Ui]=null,n[Ws]=null,s(qi(a,!1))):(n[Ui]=s,n[Ws]=o)},writable:!0}),r));return n[$s]=null,Cj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Ws];s!==null&&(n[$s]=null,n[Ui]=null,n[Ws]=null,s(i)),n[jc]=i;return}var o=n[Ui];o!==null&&(n[$s]=null,n[Ui]=null,n[Ws]=null,o(qi(void 0,!0))),n[qh]=!0}),e.on("readable",Nj.bind(null,n)),n};bO.exports=Rj});var SO=v((Nle,_O)=>{l();_O.exports=function(){throw new Error("Readable.from is not available in the browser")}});var cv=v((Ple,LO)=>{"use strict";l();LO.exports=qe;var ba;qe.ReadableState=NO;var Dle=ti().EventEmitter,xO=function(e,r){return e.listeners(r).length},zc=YE(),Vh=qs().Buffer,Bj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function Lj(t){return Vh.from(t)}function Fj(t){return Vh.isBuffer(t)||t instanceof Bj}var gv=JE(),Ne;gv&&gv.debuglog?Ne=gv.debuglog("stream"):Ne=function(){};var Mj=JN(),bv=ev(),Uj=tv(),qj=Uj.getHighWaterMark,Hh=js().codes,Vj=Hh.ERR_INVALID_ARG_TYPE,Hj=Hh.ERR_STREAM_PUSH_AFTER_EOF,kj=Hh.ERR_METHOD_NOT_IMPLEMENTED,Gj=Hh.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Ia,yv,mv;Ea()(qe,zc);var Qc=bv.errorOrDestroy,wv=["error","close","destroy","pause","resume"];function jj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function NO(t,e,r){ba=ba||Qs(),t=t||{},typeof r!="boolean"&&(r=e instanceof ba),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=qj(this,t,"readableHighWaterMark",r),this.buffer=new Mj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Ia||(Ia=hv().StringDecoder),this.decoder=new Ia(t.encoding),this.encoding=t.encoding)}function qe(t){if(ba=ba||Qs(),!(this instanceof qe))return new qe(t);var e=this instanceof ba;this._readableState=new NO(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),zc.call(this)}Object.defineProperty(qe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});qe.prototype.destroy=bv.destroy;qe.prototype._undestroy=bv.undestroy;qe.prototype._destroy=function(t,e){e(t)};qe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=Vh.from(t,e),e=""),n=!0),OO(this,t,e,!1,n)};qe.prototype.unshift=function(t){return OO(this,t,null,!0,!1)};function OO(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Wj(t,s);else{var o;if(i||(o=Qj(s,e)),o)Qc(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==Vh.prototype&&(e=Lj(e)),n)s.endEmitted?Qc(t,new Gj):Ev(t,s,e,!0);else if(s.ended)Qc(t,new Hj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?Ev(t,s,e,!1):Av(t,s)):Ev(t,s,e,!1)}else n||(s.reading=!1,Av(t,s))}return!s.ended&&(s.length=TO?t=TO:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function CO(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=zj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}qe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?vv(this):kh(this),null;if(t=CO(t,e),t===0&&e.ended)return e.length===0&&vv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=RO(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&vv(this)),i!==null&&this.emit("data",i),i};function Wj(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?kh(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,DO(t)))}}function kh(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,p.default.nextTick(DO,t))}function DO(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,Iv(t)}function Av(t,e){e.readingMore||(e.readingMore=!0,p.default.nextTick($j,t,e))}function $j(t,e){for(;!e.reading&&!e.ended&&(e.length1&&BO(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function g(O){Ne("onerror",O),A(),t.removeListener("error",g),xO(t,"error")===0&&Qc(t,O)}jj(t,"error",g);function m(){t.removeListener("finish",y),A()}t.once("close",m);function y(){Ne("onfinish"),t.removeListener("close",m),A()}t.once("finish",y);function A(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Kj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&xO(t,"data")&&(r.flowing=!0,Iv(t))}}qe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?kh(this):n.reading||p.default.nextTick(Yj,this)),r};qe.prototype.addListener=qe.prototype.on;qe.prototype.removeListener=function(t,e){var r=zc.prototype.removeListener.call(this,t,e);return t==="readable"&&p.default.nextTick(PO,this),r};qe.prototype.removeAllListeners=function(t){var e=zc.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&p.default.nextTick(PO,this),e};function PO(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Yj(t){Ne("readable nexttick read 0"),t.read(0)}qe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Jj(this,t)),t.paused=!1,this};function Jj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,p.default.nextTick(Xj,t,e))}function Xj(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),Iv(t),e.flowing&&!e.reading&&t.read(0)}qe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Iv(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}qe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var a=e.push(o);a||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(a){return function(){return t[a].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function vv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,p.default.nextTick(Zj,e,t))}function Zj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(qe.from=function(t,e){return mv===void 0&&(mv=SO()),mv(qe,t,e)});function BO(t,e){for(var r=0,n=t.length;r{"use strict";l();MO.exports=ri;var Gh=js().codes,eQ=Gh.ERR_METHOD_NOT_IMPLEMENTED,tQ=Gh.ERR_MULTIPLE_CALLBACK,rQ=Gh.ERR_TRANSFORM_ALREADY_TRANSFORMING,nQ=Gh.ERR_TRANSFORM_WITH_LENGTH_0,jh=Qs();Ea()(ri,jh);function iQ(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new tQ);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";l();qO.exports=Wc;var UO=_v();Ea()(Wc,UO);function Wc(t){if(!(this instanceof Wc))return new Wc(t);UO.call(this,t)}Wc.prototype._transform=function(t,e,r){r(null,t)}});var QO=v((Ule,jO)=>{"use strict";l();var Sv;function oQ(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var GO=js().codes,aQ=GO.ERR_MISSING_ARGS,uQ=GO.ERR_STREAM_DESTROYED;function HO(t){if(t)throw t}function cQ(t){return t.setHeader&&typeof t.abort=="function"}function lQ(t,e,r,n){n=oQ(n);var i=!1;t.on("close",function(){i=!0}),Sv===void 0&&(Sv=Mh()),Sv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,cQ(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new uQ("pipe"))}}}function kO(t){t()}function fQ(t,e){return t.pipe(e)}function dQ(t){return!t.length||typeof t[t.length-1]!="function"?HO:t.pop()}function hQ(){for(var t=arguments.length,e=new Array(t),r=0;r0;return lQ(o,u,c,function(f){i||(i=f),f&&s.forEach(kO),!u&&(s.forEach(kO),n(i))})});return e.reduce(fQ)}jO.exports=hQ});var Tv=v((Vr,zO)=>{l();Vr=zO.exports=cv();Vr.Stream=Vr;Vr.Readable=Vr;Vr.Writable=ov();Vr.Duplex=Qs();Vr.Transform=_v();Vr.PassThrough=VO();Vr.finished=Mh();Vr.pipeline=QO()});var KO=v((Hle,$O)=>{l();var{Transform:pQ}=Tv();$O.exports=t=>class WO extends pQ{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!h.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return h.Buffer.isBuffer(r)||(r=h.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new WO(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var XO=v((Gle,JO)=>{l();var{Transform:gQ}=Tv();JO.exports=t=>class YO extends gQ{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!h.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return h.Buffer.isBuffer(r)||(r=h.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new YO(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var e2=v((Qle,ZO)=>{l();var yQ=KO(),mQ=XO();ZO.exports=function(t){let e=yQ(t),r=mQ(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var n2=v(r2=>{l();var t2=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];r2.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],a=t[5]^t[15]^t[25]^t[35]^t[45],u=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],g=f^(i<<1|s>>>31),m=d^(s<<1|i>>>31),y=t[0]^g,A=t[1]^m,O=t[10]^g,R=t[11]^m,q=t[20]^g,M=t[21]^m,b=t[30]^g,S=t[31]^m,N=t[40]^g,_=t[41]^m;g=r^(o<<1|a>>>31),m=n^(a<<1|o>>>31);let T=t[2]^g,B=t[3]^m,X=t[12]^g,z=t[13]^m,k=t[22]^g,Q=t[23]^m,K=t[32]^g,ye=t[33]^m,ce=t[42]^g,ie=t[43]^m;g=i^(u<<1|c>>>31),m=s^(c<<1|u>>>31);let J=t[4]^g,oe=t[5]^m,re=t[14]^g,se=t[15]^m,U=t[24]^g,fe=t[25]^m,ue=t[34]^g,de=t[35]^m,ae=t[44]^g,le=t[45]^m;g=o^(f<<1|d>>>31),m=a^(d<<1|f>>>31);let w=t[6]^g,E=t[7]^m,I=t[16]^g,P=t[17]^m,C=t[26]^g,D=t[27]^m,L=t[36]^g,x=t[37]^m,F=t[46]^g,G=t[47]^m;g=u^(r<<1|n>>>31),m=c^(n<<1|r>>>31);let V=t[8]^g,ee=t[9]^m,Ae=t[18]^g,Se=t[19]^m,Be=t[28]^g,it=t[29]^m,dt=t[38]^g,De=t[39]^m,Ve=t[48]^g,Lt=t[49]^m,wi=y,_s=A,Ss=R<<4|O>>>28,cr=O<<4|R>>>28,Qn=q<<3|M>>>29,Kt=M<<3|q>>>29,Ft=S<<9|b>>>23,Je=b<<9|S>>>23,s0=N<<18|_>>>14,o0=_<<18|N>>>14,a0=T<<1|B>>>31,u0=B<<1|T>>>31,c0=z<<12|X>>>20,l0=X<<12|z>>>20,f0=k<<10|Q>>>22,d0=Q<<10|k>>>22,h0=ye<<13|K>>>19,p0=K<<13|ye>>>19,g0=ce<<2|ie>>>30,y0=ie<<2|ce>>>30,m0=oe<<30|J>>>2,w0=J<<30|oe>>>2,E0=re<<6|se>>>26,v0=se<<6|re>>>26,A0=fe<<11|U>>>21,b0=U<<11|fe>>>21,I0=ue<<15|de>>>17,_0=de<<15|ue>>>17,S0=le<<29|ae>>>3,T0=ae<<29|le>>>3,C0=w<<28|E>>>4,x0=E<<28|w>>>4,N0=P<<23|I>>>9,O0=I<<23|P>>>9,D0=C<<25|D>>>7,P0=D<<25|C>>>7,R0=L<<21|x>>>11,B0=x<<21|L>>>11,L0=G<<24|F>>>8,F0=F<<24|G>>>8,M0=V<<27|ee>>>5,U0=ee<<27|V>>>5,q0=Ae<<20|Se>>>12,V0=Se<<20|Ae>>>12,H0=it<<7|Be>>>25,k0=Be<<7|it>>>25,G0=dt<<8|De>>>24,j0=De<<8|dt>>>24,Q0=Ve<<14|Lt>>>18,z0=Lt<<14|Ve>>>18;t[0]=wi^~c0&A0,t[1]=_s^~l0&b0,t[10]=C0^~q0&Qn,t[11]=x0^~V0&Kt,t[20]=a0^~E0&D0,t[21]=u0^~v0&P0,t[30]=M0^~Ss&f0,t[31]=U0^~cr&d0,t[40]=m0^~N0&H0,t[41]=w0^~O0&k0,t[2]=c0^~A0&R0,t[3]=l0^~b0&B0,t[12]=q0^~Qn&h0,t[13]=V0^~Kt&p0,t[22]=E0^~D0&G0,t[23]=v0^~P0&j0,t[32]=Ss^~f0&I0,t[33]=cr^~d0&_0,t[42]=N0^~H0&Ft,t[43]=O0^~k0&Je,t[4]=A0^~R0&Q0,t[5]=b0^~B0&z0,t[14]=Qn^~h0&S0,t[15]=Kt^~p0&T0,t[24]=D0^~G0&s0,t[25]=P0^~j0&o0,t[34]=f0^~I0&L0,t[35]=d0^~_0&F0,t[44]=H0^~Ft&g0,t[45]=k0^~Je&y0,t[6]=R0^~Q0&wi,t[7]=B0^~z0&_s,t[16]=h0^~S0&C0,t[17]=p0^~T0&x0,t[26]=G0^~s0&a0,t[27]=j0^~o0&u0,t[36]=I0^~L0&M0,t[37]=_0^~F0&U0,t[46]=Ft^~g0&m0,t[47]=Je^~y0&w0,t[8]=Q0^~wi&c0,t[9]=z0^~_s&l0,t[18]=S0^~C0&q0,t[19]=T0^~x0&V0,t[28]=s0^~a0&E0,t[29]=o0^~u0&v0,t[38]=L0^~M0&Ss,t[39]=F0^~U0&cr,t[48]=g0^~m0&N0,t[49]=y0^~w0&O0,t[0]^=t2[e*2],t[1]^=t2[e*2+1]}}});var s2=v((Kle,i2)=>{l();var Qh=n2();function _a(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}_a.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};_a.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(Qh.p1600(this.state),this.count=0);return e};_a.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};i2.exports=_a});var Cv=v((Jle,o2)=>{l();o2.exports=e2()(s2())});var Dv=v(Sa=>{"use strict";l();var wQ=Sa&&Sa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Sa,"__esModule",{value:!0});Sa.SmartContract=void 0;var EQ=wQ(Yt()),$c=pt(),xv=ah(),vQ=Le(),Nv=Yr(),AQ=br(),bQ=Tc(),a2=NE(),u2=qc(),c2=UE(),IQ=HE(),_Q=Vc(),zh=$E(),SQ=Cv(),Ov=class{constructor(e={}){this.address=new $c.Address,this.methodsExplicit={},this.methods={},this.address=e.address||new $c.Address,this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new u2.ContractFunction(i);return new c2.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new u2.ContractFunction(i),a=IQ.NativeSerializer.nativeToTypedValues(s||[],n);return new c2.Interaction(e,o,a||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return AQ.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:a,chainID:u}){xv.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()"),n=n||new a2.CodeMetadata,i=i||[],s=s||0;let c=new zh.ContractDeployPayloadBuilder().setCode(r).setCodeMetadata(n).setInitArgs(i).build();return new Nv.Transaction({receiver:$c.Address.Zero(),sender:e,value:s,gasLimit:o,gasPrice:a,data:c,chainID:u})}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:a,chainID:u}){xv.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress(),n=n||new a2.CodeMetadata,i=i||[],s=s||0;let c=new zh.ContractUpgradePayloadBuilder().setCode(r).setCodeMetadata(n).setInitArgs(i).build();return new Nv.Transaction({sender:e,receiver:this.getAddress(),value:s,gasLimit:o,gasPrice:a,data:c,chainID:u})}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:a,caller:u}){xv.Compatibility.guardAddressIsSetAndNonZero(u,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress(),r=r||[],n=n||0;let c=new zh.ContractCallPayloadBuilder().setFunction(e).setArgs(r).build();return new Nv.Transaction({sender:u,receiver:s||this.getAddress(),value:n,gasLimit:i,gasPrice:o,data:c,chainID:a})}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new _Q.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new vQ.ErrContractHasNoAddress}static computeAddress(e,r){let n=h.Buffer.alloc(8,0),i=new $c.Address(e.bech32()).pubkey(),s=i.slice(30),o=h.Buffer.alloc(8),a=new EQ.default(r.valueOf().toString(10)),u=bQ.bigIntToBuffer(a);o.write(u.reverse().toString("hex"),"hex");let c=h.Buffer.concat([i,o]),f=SQ("keccak256").update(c).digest(),d=h.Buffer.from(zh.ArwenVirtualMachine,"hex"),g=h.Buffer.concat([n,d,f.slice(10,30),s]);return new $c.Address(g)}};Sa.SmartContract=Ov});var Wh=v(Ys=>{"use strict";l();Object.defineProperty(Ys,"__esModule",{value:!0});Ys.SignableMessage=Ys.MESSAGE_PREFIX=void 0;var TQ=pt(),CQ=Rc(),xQ=Cv();Ys.MESSAGE_PREFIX=`Elrond Signed Message: -`;var Pv=class{constructor(e){this.message=h.Buffer.from([]),this.signature=h.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=new TQ.Address,Object.assign(this,e)}serializeForSigning(){let e=h.Buffer.from(this.message.length.toString()),r=h.Buffer.concat([e,this.message]),n=h.Buffer.concat([h.Buffer.from(Ys.MESSAGE_PREFIX),r]);return xQ("keccak256").update(n).digest()}serializeForSigningRaw(){return h.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=CQ.interpretSignatureAsBuffer(e)}getMessageSize(){let e=h.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};Ys.SignableMessage=Pv});var Rv=v(l2=>{"use strict";l();Object.defineProperty(l2,"__esModule",{value:!0})});var Ta=v(Ht=>{"use strict";l();var NQ=Ht&&Ht.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),OQ=Ht&&Ht.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),DQ=Ht&&Ht.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&NQ(e,t,r);return OQ(e,t),e};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.zeroPadStringIfOddLength=Ht.isPaddedHex=Ht.numberToPaddedHex=Ht.Nonce=Ht.Address=void 0;var f2=DQ(tw()),PQ="erd",Bv=class t{constructor(e){this.value=e}static fromPubkey(e){let r=f2.toWords(e),n=f2.encode(PQ,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};Ht.Address=Bv;var Lv=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return d2(this.value)}};Ht.Nonce=Lv;function d2(t){let e=t.toString(16);return h2(e)}Ht.numberToPaddedHex=d2;function RQ(t){t=t||"";let e=h.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Ht.isPaddedHex=RQ;function h2(t){return t=t||"",t.length%2==1?"0"+t:t}Ht.zeroPadStringIfOddLength=h2});var p2=v(Vi=>{"use strict";l();var BQ=Vi&&Vi.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vi,"__esModule",{value:!0});Vi.EsdtContractAddress=Vi.MaxUint64AsBigNumber=void 0;var LQ=BQ(Yt()),FQ=Ta();Vi.MaxUint64AsBigNumber=new LQ.default("18446744073709551615");Vi.EsdtContractAddress=new FQ.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var Mv=v(Ca=>{"use strict";l();var MQ=Ca&&Ca.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ca,"__esModule",{value:!0});Ca.ContractQueryResponse=void 0;var UQ=MQ(Yt()),qQ=p2(),Fv=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new UQ.default(e.gasRemaining||e.GasRemaining||0),o=qQ.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>h.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Ca.ContractQueryResponse=Fv});var g2=v(Hi=>{"use strict";l();Object.defineProperty(Hi,"__esModule",{value:!0});Hi.ErrAccountNotConnected=Hi.ErrCannotSignSingleTransaction=Hi.Err=void 0;var Kc=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Hi.Err=Kc;var Uv=class extends Kc{constructor(){super("Cannot sign single transaction.")}};Hi.ErrCannotSignSingleTransaction=Uv;var qv=class extends Kc{constructor(){super("Account is not connected.")}};Hi.ErrAccountNotConnected=qv});var y2=v(Yc=>{"use strict";l();Object.defineProperty(Yc,"__esModule",{value:!0});Yc.Operation=void 0;var VQ;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(VQ=Yc.Operation||(Yc.Operation={}))});var Vv=v(xa=>{"use strict";l();var ki=xa&&xa.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(xa,"__esModule",{value:!0});xa.ExtensionProvider=void 0;var HQ=Yr(),m2=g2(),Jc=y2(),Xc=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return ki(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return ki(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(Jc.Operation.Connect,n),this.account.address})}logout(){return ki(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(Jc.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return ki(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return ki(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return ki(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new m2.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new m2.ErrAccountNotConnected}signTransactions(e){return ki(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(Jc.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>HQ.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return ki(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(Jc.Operation.SignMessage,r)).signature,s=h.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(Jc.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};xa.ExtensionProvider=Xc;Xc._instance=new Xc});function QQ(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){zQ(t);return}return e}function zQ(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Zc(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.at(-1)==='"'&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!jQ.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(kQ.test(t)||GQ.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,QQ)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var kQ,GQ,jQ,b2=he(()=>{l();kQ=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,GQ=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,jQ=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function WQ(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Mt(t,...e){try{return WQ(t(...e))}catch(r){return Promise.reject(r)}}function $Q(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function KQ(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function el(t){if($Q(t))return String(t);if(KQ(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return el(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function I2(){if(typeof h.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function _2(t){if(typeof t=="string")return t;I2();let e=h.Buffer.from(t).toString("base64");return Hv+e}function S2(t){return typeof t!="string"||!t.startsWith(Hv)?t:(I2(),h.Buffer.from(t.slice(Hv.length),"base64"))}function ir(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function T2(...t){return ir(t.join(":"))}function tl(t){return t=ir(t),t?t+":":""}var Hv,C2=he(()=>{l();Hv="base64:"});function O2(t={}){let e={mounts:{"":t.driver||JQ()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=ir(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await x2(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},a=(c,f,d)=>{let g=new Map,m=y=>{let A=g.get(y.base);return A||(A={driver:y.driver,base:y.base,items:[]},g.set(y.base,A)),A};for(let y of c){let A=typeof y=="string",O=ir(A?y:y.key),R=A?void 0:y.value,q=A||!y.options?f:{...f,...y.options},M=r(O);m(M).items.push({key:O,value:R,relativeKey:M.relativeKey,options:q})}return Promise.all([...g.values()].map(y=>d(y))).then(y=>y.flat())},u={hasItem(c,f={}){c=ir(c);let{relativeKey:d,driver:g}=r(c);return Mt(g.hasItem,d,f)},getItem(c,f={}){c=ir(c);let{relativeKey:d,driver:g}=r(c);return Mt(g.getItem,d,f).then(m=>Zc(m))},getItems(c,f){return a(c,f,d=>d.driver.getItems?Mt(d.driver.getItems,d.items.map(g=>({key:g.relativeKey,options:g.options})),f).then(g=>g.map(m=>({key:T2(d.base,m.key),value:Zc(m.value)}))):Promise.all(d.items.map(g=>Mt(d.driver.getItem,g.relativeKey,g.options).then(m=>({key:g.key,value:Zc(m)})))))},getItemRaw(c,f={}){c=ir(c);let{relativeKey:d,driver:g}=r(c);return g.getItemRaw?Mt(g.getItemRaw,d,f):Mt(g.getItem,d,f).then(m=>S2(m))},async setItem(c,f,d={}){if(f===void 0)return u.removeItem(c);c=ir(c);let{relativeKey:g,driver:m}=r(c);m.setItem&&(await Mt(m.setItem,g,el(f),d),m.watch||i("update",c))},async setItems(c,f){await a(c,f,async d=>{d.driver.setItems&&await Mt(d.driver.setItems,d.items.map(g=>({key:g.relativeKey,value:el(g.value),options:g.options})),f),d.driver.setItem&&await Promise.all(d.items.map(g=>Mt(d.driver.setItem,g.relativeKey,el(g.value),g.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return u.removeItem(c,d);c=ir(c);let{relativeKey:g,driver:m}=r(c);if(m.setItemRaw)await Mt(m.setItemRaw,g,f,d);else if(m.setItem)await Mt(m.setItem,g,_2(f),d);else return;m.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=ir(c);let{relativeKey:d,driver:g}=r(c);g.removeItem&&(await Mt(g.removeItem,d,f),(f.removeMeta||f.removeMata)&&await Mt(g.removeItem,d+"$",f),g.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=ir(c);let{relativeKey:d,driver:g}=r(c),m=Object.create(null);if(g.getMeta&&Object.assign(m,await Mt(g.getMeta,d,f)),!f.nativeOnly){let y=await Mt(g.getItem,d+"$",f).then(A=>Zc(A));y&&typeof y=="object"&&(typeof y.atime=="string"&&(y.atime=new Date(y.atime)),typeof y.mtime=="string"&&(y.mtime=new Date(y.mtime)),Object.assign(m,y))}return m},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=tl(c);let d=n(c,!0),g=[],m=[];for(let y of d){let O=(await Mt(y.driver.getKeys,y.relativeBase,f)).map(R=>y.mountpoint+ir(R)).filter(R=>!g.some(q=>R.startsWith(q)));m.push(...O),g=[y.mountpoint,...g.filter(R=>!R.startsWith(y.mountpoint))]}return c?m.filter(y=>y.startsWith(c)&&!y.endsWith("$")):m.filter(y=>!y.endsWith("$"))},async clear(c,f={}){c=tl(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return Mt(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let g=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(g.map(m=>d.driver.removeItem(m,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>N2(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=tl(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,g)=>g.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(x2(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),u},async unmount(c,f=!0){c=tl(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await N2(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=ir(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=ir(c),n(c,f.parents).map(g=>({driver:g.driver,base:g.mountpoint}))}};return u}function x2(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function N2(t){typeof t.dispose=="function"&&await Mt(t.dispose)}var YQ,JQ,D2=he(()=>{l();b2();C2();YQ="memory",JQ=()=>{let t=new Map;return{name:YQ,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function Js(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Gv(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=Js(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function rl(){return kv||(kv=Gv("keyval-store","keyval")),kv}function jv(t,e=rl()){return e("readonly",r=>Js(r.get(t)))}function P2(t,e,r=rl()){return r("readwrite",n=>(n.put(e,t),Js(n.transaction)))}function R2(t,e=rl()){return e("readwrite",r=>(r.delete(t),Js(r.transaction)))}function B2(t=rl()){return t("readwrite",e=>(e.clear(),Js(e.transaction)))}function XQ(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Js(t.transaction)}function L2(t=rl()){return t("readonly",e=>{if(e.getAllKeys)return Js(e.getAllKeys());let r=[];return XQ(e,n=>r.push(n.key)).then(()=>r)})}var kv,F2=he(()=>{l()});var M2={};ft(M2,{safeJsonParse:()=>ji,safeJsonStringify:()=>Qi});function ji(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return e7(t)}catch{return t}}function Qi(t){return typeof t=="string"?t:ZQ(t)||""}var ZQ,e7,nl=he(()=>{l();ZQ=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),e7=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var q2={};ft(q2,{KeyValueStorage:()=>$v,default:()=>$v});function s7(t){var e;return[t[0],ji((e=t[1])!=null?e:"")]}var t7,r7,n7,i7,zv,Qv,Jh,Wv,o7,U2,a7,u7,$v,V2=he(()=>{l();D2();F2();nl();t7="idb-keyval",r7=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Gv(t.dbName,t.storeName)),{name:t7,options:t,async hasItem(i){return!(typeof await jv(r(i),n)>"u")},async getItem(i){return await jv(r(i),n)??null},setItem(i,s){return P2(r(i),s,n)},removeItem(i){return R2(r(i),n)},getKeys(){return L2(n)},clear(){return B2(n)}}},n7="WALLET_CONNECT_V2_INDEXED_DB",i7="keyvaluestorage",zv=class{constructor(){this.indexedDb=O2({driver:r7({dbName:n7,storeName:i7})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Qi(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Qv=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Jh={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Qv<"u"&&Qv.localStorage?Jh.exports=Qv.localStorage:typeof window<"u"&&window.localStorage?Jh.exports=window.localStorage:Jh.exports=new e})();Wv=class{constructor(){this.localStorage=Jh.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(s7)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return ji(r)}async setItem(e,r){this.localStorage.setItem(e,Qi(r))}async removeItem(e){this.localStorage.removeItem(e)}},o7="wc_storage_version",U2=1,a7=async(t,e,r)=>{let n=o7,i=await e.getItem(n);if(i&&i>=U2){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let a=s.shift();if(!a)continue;let u=a.toLowerCase();if(u.includes("wc@")||u.includes("walletconnect")||u.includes("wc_")||u.includes("wallet_connect")){let c=await t.getItem(a);await e.setItem(a,c),o.push(a)}}await e.setItem(n,U2),r(e),u7(t,o)},u7=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},$v=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new Wv;this.storage=e;try{let r=new zv;a7(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zr={};ft(Zr,{__assign:()=>Yv,__asyncDelegator:()=>A7,__asyncGenerator:()=>v7,__asyncValues:()=>b7,__await:()=>il,__awaiter:()=>p7,__classPrivateFieldGet:()=>T7,__classPrivateFieldSet:()=>C7,__createBinding:()=>y7,__decorate:()=>f7,__exportStar:()=>m7,__extends:()=>c7,__generator:()=>g7,__importDefault:()=>S7,__importStar:()=>_7,__makeTemplateObject:()=>I7,__metadata:()=>h7,__param:()=>d7,__read:()=>H2,__rest:()=>l7,__spread:()=>w7,__spreadArrays:()=>E7,__values:()=>Jv});function c7(t,e){Kv(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function l7(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function d7(t,e){return function(r,n){e(r,n,t)}}function h7(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function p7(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})}function g7(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(f){return u([c,f])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function H2(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function w7(){for(var t=[],e=0;e1||a(g,m)})})}function a(g,m){try{u(n[g](m))}catch(y){d(s[0][3],y)}}function u(g){g.value instanceof il?Promise.resolve(g.value.v).then(c,f):d(s[0][2],g)}function c(g){a("next",g)}function f(g){a("throw",g)}function d(g,m){g(m),s.shift(),s.length&&a(s[0][0],s[0][1])}}function A7(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:il(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function b7(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Jv=="function"?Jv(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,u){o=t[s](o),i(a,u,o.done,o.value)})}}function i(s,o,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a})},o)}}function I7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function _7(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function S7(t){return t&&t.__esModule?t:{default:t}}function T7(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function C7(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Kv,Yv,en=he(()=>{l();Kv=function(t,e){return Kv=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Kv(t,e)};Yv=function(){return Yv=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";l();Object.defineProperty(Xh,"__esModule",{value:!0});Xh.delay=void 0;function x7(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}Xh.delay=x7});var G2=v(Na=>{"use strict";l();Object.defineProperty(Na,"__esModule",{value:!0});Na.ONE_THOUSAND=Na.ONE_HUNDRED=void 0;Na.ONE_HUNDRED=100;Na.ONE_THOUSAND=1e3});var j2=v(ge=>{"use strict";l();Object.defineProperty(ge,"__esModule",{value:!0});ge.ONE_YEAR=ge.FOUR_WEEKS=ge.THREE_WEEKS=ge.TWO_WEEKS=ge.ONE_WEEK=ge.THIRTY_DAYS=ge.SEVEN_DAYS=ge.FIVE_DAYS=ge.THREE_DAYS=ge.ONE_DAY=ge.TWENTY_FOUR_HOURS=ge.TWELVE_HOURS=ge.SIX_HOURS=ge.THREE_HOURS=ge.ONE_HOUR=ge.SIXTY_MINUTES=ge.THIRTY_MINUTES=ge.TEN_MINUTES=ge.FIVE_MINUTES=ge.ONE_MINUTE=ge.SIXTY_SECONDS=ge.THIRTY_SECONDS=ge.TEN_SECONDS=ge.FIVE_SECONDS=ge.ONE_SECOND=void 0;ge.ONE_SECOND=1;ge.FIVE_SECONDS=5;ge.TEN_SECONDS=10;ge.THIRTY_SECONDS=30;ge.SIXTY_SECONDS=60;ge.ONE_MINUTE=ge.SIXTY_SECONDS;ge.FIVE_MINUTES=ge.ONE_MINUTE*5;ge.TEN_MINUTES=ge.ONE_MINUTE*10;ge.THIRTY_MINUTES=ge.ONE_MINUTE*30;ge.SIXTY_MINUTES=ge.ONE_MINUTE*60;ge.ONE_HOUR=ge.SIXTY_MINUTES;ge.THREE_HOURS=ge.ONE_HOUR*3;ge.SIX_HOURS=ge.ONE_HOUR*6;ge.TWELVE_HOURS=ge.ONE_HOUR*12;ge.TWENTY_FOUR_HOURS=ge.ONE_HOUR*24;ge.ONE_DAY=ge.TWENTY_FOUR_HOURS;ge.THREE_DAYS=ge.ONE_DAY*3;ge.FIVE_DAYS=ge.ONE_DAY*5;ge.SEVEN_DAYS=ge.ONE_DAY*7;ge.THIRTY_DAYS=ge.ONE_DAY*30;ge.ONE_WEEK=ge.SEVEN_DAYS;ge.TWO_WEEKS=ge.ONE_WEEK*2;ge.THREE_WEEKS=ge.ONE_WEEK*3;ge.FOUR_WEEKS=ge.ONE_WEEK*4;ge.ONE_YEAR=ge.ONE_DAY*365});var Xv=v(Zh=>{"use strict";l();Object.defineProperty(Zh,"__esModule",{value:!0});var Q2=(en(),ht(Zr));Q2.__exportStar(G2(),Zh);Q2.__exportStar(j2(),Zh)});var W2=v(Oa=>{"use strict";l();Object.defineProperty(Oa,"__esModule",{value:!0});Oa.fromMiliseconds=Oa.toMiliseconds=void 0;var z2=Xv();function N7(t){return t*z2.ONE_THOUSAND}Oa.toMiliseconds=N7;function O7(t){return Math.floor(t/z2.ONE_THOUSAND)}Oa.fromMiliseconds=O7});var K2=v(ep=>{"use strict";l();Object.defineProperty(ep,"__esModule",{value:!0});var $2=(en(),ht(Zr));$2.__exportStar(k2(),ep);$2.__exportStar(W2(),ep)});var Y2=v(sl=>{"use strict";l();Object.defineProperty(sl,"__esModule",{value:!0});sl.Watch=void 0;var tp=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};sl.Watch=tp;sl.default=tp});var J2=v(rp=>{"use strict";l();Object.defineProperty(rp,"__esModule",{value:!0});rp.IWatch=void 0;var Zv=class{};rp.IWatch=Zv});var X2=v(e1=>{"use strict";l();Object.defineProperty(e1,"__esModule",{value:!0});var D7=(en(),ht(Zr));D7.__exportStar(J2(),e1)});var Xs=v(Da=>{"use strict";l();Object.defineProperty(Da,"__esModule",{value:!0});var np=(en(),ht(Zr));np.__exportStar(K2(),Da);np.__exportStar(Y2(),Da);np.__exportStar(X2(),Da);np.__exportStar(Xv(),Da)});var t1,Z2=he(()=>{l();t1=class{}});var r1={};ft(r1,{IEvents:()=>t1});var n1=he(()=>{l();Z2()});var eD=v(ip=>{"use strict";l();Object.defineProperty(ip,"__esModule",{value:!0});ip.IHeartBeat=void 0;var P7=(n1(),ht(r1)),i1=class extends P7.IEvents{constructor(e){super()}};ip.IHeartBeat=i1});var o1=v(s1=>{"use strict";l();Object.defineProperty(s1,"__esModule",{value:!0});var R7=(en(),ht(Zr));R7.__exportStar(eD(),s1)});var tD=v(Pa=>{"use strict";l();Object.defineProperty(Pa,"__esModule",{value:!0});Pa.HEARTBEAT_EVENTS=Pa.HEARTBEAT_INTERVAL=void 0;var B7=Xs();Pa.HEARTBEAT_INTERVAL=B7.FIVE_SECONDS;Pa.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var u1=v(a1=>{"use strict";l();Object.defineProperty(a1,"__esModule",{value:!0});var L7=(en(),ht(Zr));L7.__exportStar(tD(),a1)});var rD=v(sp=>{"use strict";l();Object.defineProperty(sp,"__esModule",{value:!0});sp.HeartBeat=void 0;var c1=(en(),ht(Zr)),F7=ti(),M7=Xs(),U7=o1(),l1=u1(),f1=class t extends U7.IHeartBeat{constructor(e){super(e),this.events=new F7.EventEmitter,this.interval=l1.HEARTBEAT_INTERVAL,this.interval=e?.interval||l1.HEARTBEAT_INTERVAL}static init(e){return c1.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return c1.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return c1.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),M7.toMiliseconds(this.interval))})}pulse(){this.events.emit(l1.HEARTBEAT_EVENTS.pulse)}};sp.HeartBeat=f1});var nD=v(ol=>{"use strict";l();Object.defineProperty(ol,"__esModule",{value:!0});var d1=(en(),ht(Zr));d1.__exportStar(rD(),ol);d1.__exportStar(o1(),ol);d1.__exportStar(u1(),ol)});var sD=v((Ide,iD)=>{"use strict";l();function q7(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}iD.exports=V7;function V7(t,e,r){var n=r&&r.stringify||q7,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var a=1;a-1?d:0,t.charCodeAt(m+1)){case 100:case 102:if(f>=u||e[f]==null)break;d=u||e[f]==null)break;d=u||e[f]===void 0)break;d",d=m+2,m++;break}c+=n(e[f]),d=m+2,m++;break;case 115:if(f>=u)break;d{"use strict";l();var oD=sD();cD.exports=xn;var al=Y7().console||{},H7={mapHttpRequest:op,mapHttpResponse:op,wrapRequestSerializer:h1,wrapResponseSerializer:h1,wrapErrorSerializer:h1,req:op,res:op,err:z7};function k7(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function xn(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||al;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=k7(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let a=t.level||"info",u=Object.create(r);u.log||(u.log=ul),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:d,set:g});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:W7(t)};u.levels=xn.levels,u.level=a,u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=ul,u.serializers=n,u._serialize=i,u._stdErrSerialize=s,u.child=m,e&&(u._logEvent=p1());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function g(y){if(y!=="silent"&&!this.levels.values[y])throw Error("unknown level "+y);this._level=y,Ra(c,u,"error","log"),Ra(c,u,"fatal","error"),Ra(c,u,"warn","error"),Ra(c,u,"info","log"),Ra(c,u,"debug","log"),Ra(c,u,"trace","log")}function m(y,A){if(!y)throw new Error("missing bindings for child Pino");A=A||{},i&&y.serializers&&(A.serializers=y.serializers);let O=A.serializers;if(i&&O){var R=Object.assign({},n,O),q=t.browser.serialize===!0?Object.keys(R):i;delete y.serializers,ap([y],q,R,this._stdErrSerialize)}function M(b){this._childLevel=(b._childLevel|0)+1,this.error=Ba(b,y,"error"),this.fatal=Ba(b,y,"fatal"),this.warn=Ba(b,y,"warn"),this.info=Ba(b,y,"info"),this.debug=Ba(b,y,"debug"),this.trace=Ba(b,y,"trace"),R&&(this.serializers=R,this._serialize=q),e&&(this._logEvent=p1([].concat(b._logEvent.bindings,y)))}return M.prototype=this,new M(this)}return u}xn.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};xn.stdSerializers=H7;xn.stdTimeFunctions=Object.assign({},{nullTime:aD,epochTime:uD,unixTime:$7,isoTime:K7});function Ra(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?ul:i[r]?i[r]:al[r]||al[n]||ul,G7(t,e,r)}function G7(t,e,r){!t.transmit&&e[r]===ul||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===al?al:this;for(var u=0;u-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Ba(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;i{"use strict";l();Object.defineProperty(La,"__esModule",{value:!0});La.PINO_CUSTOM_CONTEXT_KEY=La.PINO_LOGGER_DEFAULTS=void 0;La.PINO_LOGGER_DEFAULTS={level:"info"};La.PINO_CUSTOM_CONTEXT_KEY="custom_context"});var gD=v(mr=>{"use strict";l();Object.defineProperty(mr,"__esModule",{value:!0});mr.generateChildLogger=mr.formatChildLoggerContext=mr.getLoggerContext=mr.setBrowserLoggerContext=mr.getBrowserLoggerContext=mr.getDefaultLoggerOptions=void 0;var Fa=g1();function J7(t){return Object.assign(Object.assign({},t),{level:t?.level||Fa.PINO_LOGGER_DEFAULTS.level})}mr.getDefaultLoggerOptions=J7;function fD(t,e=Fa.PINO_CUSTOM_CONTEXT_KEY){return t[e]||""}mr.getBrowserLoggerContext=fD;function dD(t,e,r=Fa.PINO_CUSTOM_CONTEXT_KEY){return t[r]=e,t}mr.setBrowserLoggerContext=dD;function hD(t,e=Fa.PINO_CUSTOM_CONTEXT_KEY){let r="";return typeof t.bindings>"u"?r=fD(t,e):r=t.bindings().context||"",r}mr.getLoggerContext=hD;function pD(t,e,r=Fa.PINO_CUSTOM_CONTEXT_KEY){let n=hD(t,r);return n.trim()?`${n}/${e}`:e}mr.formatChildLoggerContext=pD;function X7(t,e,r=Fa.PINO_CUSTOM_CONTEXT_KEY){let n=pD(t,e,r),i=t.child({context:n});return dD(i,n,r)}mr.generateChildLogger=X7});var m1=v(Ma=>{"use strict";l();Object.defineProperty(Ma,"__esModule",{value:!0});Ma.pino=void 0;var y1=(en(),ht(Zr)),Z7=y1.__importDefault(lD());Object.defineProperty(Ma,"pino",{enumerable:!0,get:function(){return Z7.default}});y1.__exportStar(g1(),Ma);y1.__exportStar(gD(),Ma)});var F1=v(Ot=>{"use strict";l();Object.defineProperty(Ot,"__esModule",{value:!0});var Ua=(n1(),ht(r1)),yD=ti();function e9(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var t9=e9(yD),w1=class extends Ua.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},E1=class{constructor(e,r,n){this.core=e,this.logger=r}},v1=class extends Ua.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},A1=class{constructor(e,r){this.logger=e,this.core=r}},b1=class extends Ua.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},I1=class extends Ua.IEvents{constructor(e){super()}},_1=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},S1=class{constructor(){this.map=new Map}},T1=class extends Ua.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},C1=class{constructor(e,r){this.core=e,this.logger=r}},x1=class extends Ua.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},N1=class{constructor(e,r){this.logger=e,this.core=r}},O1=class{constructor(e,r){this.projectId=e,this.logger=r}},D1=class{constructor(e,r){this.projectId=e,this.logger=r}},P1=class extends t9.default{constructor(){super()}},R1=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},B1=class extends yD.EventEmitter{constructor(){super()}},L1=class{constructor(e){this.client=e}};Ot.ICore=w1,Ot.ICrypto=E1,Ot.IEchoClient=D1,Ot.IEngine=L1,Ot.IEngineEvents=B1,Ot.IExpirer=x1,Ot.IJsonRpcHistory=v1,Ot.IKeyChain=C1,Ot.IMessageTracker=A1,Ot.IPairing=N1,Ot.IPublisher=b1,Ot.IRelayer=I1,Ot.ISignClient=R1,Ot.ISignClientEvents=P1,Ot.IStore=_1,Ot.ISubscriber=T1,Ot.ISubscriberTopicMap=S1,Ot.IVerify=O1});var wD=v(up=>{"use strict";l();Object.defineProperty(up,"__esModule",{value:!0});up.BrowserRandomSource=void 0;var mD=65536,M1=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";l();Object.defineProperty(U1,"__esModule",{value:!0});function r9(t){for(var e=0;e{l()});var vD=v(cp=>{"use strict";l();Object.defineProperty(cp,"__esModule",{value:!0});cp.NodeRandomSource=void 0;var n9=Hr(),q1=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof TS<"u"){let e=ED();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";l();Object.defineProperty(lp,"__esModule",{value:!0});lp.SystemRandomSource=void 0;var i9=wD(),s9=vD(),V1=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new i9.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new s9.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};lp.SystemRandomSource=V1});var bD=v(Ir=>{"use strict";l();Object.defineProperty(Ir,"__esModule",{value:!0});function o9(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}Ir.mul=Math.imul||o9;function a9(t,e){return t+e|0}Ir.add=a9;function u9(t,e){return t-e|0}Ir.sub=u9;function c9(t,e){return t<>>32-e}Ir.rotl=c9;function l9(t,e){return t<<32-e|t>>>e}Ir.rotr=l9;function f9(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}Ir.isInteger=Number.isInteger||f9;Ir.MAX_SAFE_INTEGER=9007199254740991;Ir.isSafeInteger=function(t){return Ir.isInteger(t)&&t>=-Ir.MAX_SAFE_INTEGER&&t<=Ir.MAX_SAFE_INTEGER}});var qa=v(Oe=>{"use strict";l();Object.defineProperty(Oe,"__esModule",{value:!0});var ID=bD();function d9(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}Oe.readInt16BE=d9;function h9(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}Oe.readUint16BE=h9;function p9(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}Oe.readInt16LE=p9;function g9(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}Oe.readUint16LE=g9;function _D(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}Oe.writeUint16BE=_D;Oe.writeInt16BE=_D;function SD(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}Oe.writeUint16LE=SD;Oe.writeInt16LE=SD;function H1(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}Oe.readInt32BE=H1;function k1(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}Oe.readUint32BE=k1;function G1(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}Oe.readInt32LE=G1;function j1(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}Oe.readUint32LE=j1;function fp(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}Oe.writeUint32BE=fp;Oe.writeInt32BE=fp;function dp(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}Oe.writeUint32LE=dp;Oe.writeInt32LE=dp;function y9(t,e){e===void 0&&(e=0);var r=H1(t,e),n=H1(t,e+4);return r*4294967296+n-(n>>31)*4294967296}Oe.readInt64BE=y9;function m9(t,e){e===void 0&&(e=0);var r=k1(t,e),n=k1(t,e+4);return r*4294967296+n}Oe.readUint64BE=m9;function w9(t,e){e===void 0&&(e=0);var r=G1(t,e),n=G1(t,e+4);return n*4294967296+r-(r>>31)*4294967296}Oe.readInt64LE=w9;function E9(t,e){e===void 0&&(e=0);var r=j1(t,e),n=j1(t,e+4);return n*4294967296+r}Oe.readUint64LE=E9;function TD(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),fp(t/4294967296>>>0,e,r),fp(t>>>0,e,r+4),e}Oe.writeUint64BE=TD;Oe.writeInt64BE=TD;function CD(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),dp(t>>>0,e,r),dp(t/4294967296>>>0,e,r+4),e}Oe.writeUint64LE=CD;Oe.writeInt64LE=CD;function v9(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}Oe.readUintBE=v9;function A9(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}Oe.writeUintBE=b9;function I9(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!ID.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";l();Object.defineProperty(er,"__esModule",{value:!0});er.randomStringForEntropy=er.randomString=er.randomUint32=er.randomBytes=er.defaultRandomSource=void 0;var P9=AD(),R9=qa(),xD=Hr();er.defaultRandomSource=new P9.SystemRandomSource;function Q1(t,e=er.defaultRandomSource){return e.randomBytes(t)}er.randomBytes=Q1;function B9(t=er.defaultRandomSource){let e=Q1(4,t),r=(0,R9.readUint32LE)(e);return(0,xD.wipe)(e),r}er.randomUint32=B9;var ND="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function OD(t,e=ND,r=er.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=Q1(Math.ceil(t*256/s),r);for(let a=0;a0;a++){let u=o[a];u{"use strict";l();Object.defineProperty(ni,"__esModule",{value:!0});var Ha=qa(),Va=Hr();ni.DIGEST_LENGTH=64;ni.BLOCK_SIZE=128;var PD=function(){function t(){this.digestLength=ni.DIGEST_LENGTH,this.blockSize=ni.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Va.wipe(this._buffer),Va.wipe(this._tempHi),Va.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(z1(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=z1(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var a=n+1;a0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Va.wipe(e.stateHi),Va.wipe(e.stateLo),e.buffer&&Va.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();ni.SHA512=PD;var DD=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function z1(t,e,r,n,i,s,o){for(var a=r[0],u=r[1],c=r[2],f=r[3],d=r[4],g=r[5],m=r[6],y=r[7],A=n[0],O=n[1],R=n[2],q=n[3],M=n[4],b=n[5],S=n[6],N=n[7],_,T,B,X,z,k,Q,K;o>=128;){for(var ye=0;ye<16;ye++){var ce=8*ye+s;t[ye]=Ha.readUint32BE(i,ce),e[ye]=Ha.readUint32BE(i,ce+4)}for(var ye=0;ye<80;ye++){var ie=a,J=u,oe=c,re=f,se=d,U=g,fe=m,ue=y,de=A,ae=O,le=R,w=q,E=M,I=b,P=S,C=N;if(_=y,T=N,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=(d>>>14|M<<18)^(d>>>18|M<<14)^(M>>>9|d<<23),T=(M>>>14|d<<18)^(M>>>18|d<<14)^(d>>>9|M<<23),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=d&g^~d&m,T=M&b^~M&S,z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=DD[ye*2],T=DD[ye*2+1],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=t[ye%16],T=e[ye%16],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,B=Q&65535|K<<16,X=z&65535|k<<16,_=B,T=X,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=(a>>>28|A<<4)^(A>>>2|a<<30)^(A>>>7|a<<25),T=(A>>>28|a<<4)^(a>>>2|A<<30)^(a>>>7|A<<25),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=a&u^a&c^u&c,T=A&O^A&R^O&R,z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,ue=Q&65535|K<<16,C=z&65535|k<<16,_=re,T=w,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=B,T=X,z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,re=Q&65535|K<<16,w=z&65535|k<<16,u=ie,c=J,f=oe,d=re,g=se,m=U,y=fe,a=ue,O=de,R=ae,q=le,M=w,b=E,S=I,N=P,A=C,ye%16===15)for(var ce=0;ce<16;ce++)_=t[ce],T=e[ce],z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=t[(ce+9)%16],T=e[(ce+9)%16],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,B=t[(ce+1)%16],X=e[(ce+1)%16],_=(B>>>1|X<<31)^(B>>>8|X<<24)^B>>>7,T=(X>>>1|B<<31)^(X>>>8|B<<24)^(X>>>7|B<<25),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,B=t[(ce+14)%16],X=e[(ce+14)%16],_=(B>>>19|X<<13)^(X>>>29|B<<3)^B>>>6,T=(X>>>19|B<<13)^(B>>>29|X<<3)^(X>>>6|B<<26),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,t[ce]=Q&65535|K<<16,e[ce]=z&65535|k<<16}_=a,T=A,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[0],T=n[0],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[0]=a=Q&65535|K<<16,n[0]=A=z&65535|k<<16,_=u,T=O,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[1],T=n[1],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[1]=u=Q&65535|K<<16,n[1]=O=z&65535|k<<16,_=c,T=R,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[2],T=n[2],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[2]=c=Q&65535|K<<16,n[2]=R=z&65535|k<<16,_=f,T=q,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[3],T=n[3],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[3]=f=Q&65535|K<<16,n[3]=q=z&65535|k<<16,_=d,T=M,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[4],T=n[4],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[4]=d=Q&65535|K<<16,n[4]=M=z&65535|k<<16,_=g,T=b,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[5],T=n[5],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[5]=g=Q&65535|K<<16,n[5]=b=z&65535|k<<16,_=m,T=S,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[6],T=n[6],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[6]=m=Q&65535|K<<16,n[6]=S=z&65535|k<<16,_=y,T=N,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[7],T=n[7],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[7]=y=Q&65535|K<<16,n[7]=N=z&65535|k<<16,s+=128,o-=128}return s}function F9(t){var e=new PD;e.update(t);var r=e.digest();return e.clean(),r}ni.hash=F9});var WD=v(ke=>{"use strict";l();Object.defineProperty(ke,"__esModule",{value:!0});ke.convertSecretKeyToX25519=ke.convertPublicKeyToX25519=ke.verify=ke.sign=ke.extractPublicKeyFromSecretKey=ke.generateKeyPair=ke.generateKeyPairFromSeed=ke.SEED_LENGTH=ke.SECRET_KEY_LENGTH=ke.PUBLIC_KEY_LENGTH=ke.SIGNATURE_LENGTH=void 0;var M9=cl(),ll=RD(),UD=Hr();ke.SIGNATURE_LENGTH=64;ke.PUBLIC_KEY_LENGTH=32;ke.SECRET_KEY_LENGTH=64;ke.SEED_LENGTH=32;function Te(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,qD(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function VD(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function FD(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return fl(r,t),fl(n,e),VD(r,n)}function HD(t){let e=new Uint8Array(32);return fl(e,t),e[0]&1}function k9(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Zs(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function to(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function $e(t,e,r){let n,i,s=0,o=0,a=0,u=0,c=0,f=0,d=0,g=0,m=0,y=0,A=0,O=0,R=0,q=0,M=0,b=0,S=0,N=0,_=0,T=0,B=0,X=0,z=0,k=0,Q=0,K=0,ye=0,ce=0,ie=0,J=0,oe=0,re=r[0],se=r[1],U=r[2],fe=r[3],ue=r[4],de=r[5],ae=r[6],le=r[7],w=r[8],E=r[9],I=r[10],P=r[11],C=r[12],D=r[13],L=r[14],x=r[15];n=e[0],s+=n*re,o+=n*se,a+=n*U,u+=n*fe,c+=n*ue,f+=n*de,d+=n*ae,g+=n*le,m+=n*w,y+=n*E,A+=n*I,O+=n*P,R+=n*C,q+=n*D,M+=n*L,b+=n*x,n=e[1],o+=n*re,a+=n*se,u+=n*U,c+=n*fe,f+=n*ue,d+=n*de,g+=n*ae,m+=n*le,y+=n*w,A+=n*E,O+=n*I,R+=n*P,q+=n*C,M+=n*D,b+=n*L,S+=n*x,n=e[2],a+=n*re,u+=n*se,c+=n*U,f+=n*fe,d+=n*ue,g+=n*de,m+=n*ae,y+=n*le,A+=n*w,O+=n*E,R+=n*I,q+=n*P,M+=n*C,b+=n*D,S+=n*L,N+=n*x,n=e[3],u+=n*re,c+=n*se,f+=n*U,d+=n*fe,g+=n*ue,m+=n*de,y+=n*ae,A+=n*le,O+=n*w,R+=n*E,q+=n*I,M+=n*P,b+=n*C,S+=n*D,N+=n*L,_+=n*x,n=e[4],c+=n*re,f+=n*se,d+=n*U,g+=n*fe,m+=n*ue,y+=n*de,A+=n*ae,O+=n*le,R+=n*w,q+=n*E,M+=n*I,b+=n*P,S+=n*C,N+=n*D,_+=n*L,T+=n*x,n=e[5],f+=n*re,d+=n*se,g+=n*U,m+=n*fe,y+=n*ue,A+=n*de,O+=n*ae,R+=n*le,q+=n*w,M+=n*E,b+=n*I,S+=n*P,N+=n*C,_+=n*D,T+=n*L,B+=n*x,n=e[6],d+=n*re,g+=n*se,m+=n*U,y+=n*fe,A+=n*ue,O+=n*de,R+=n*ae,q+=n*le,M+=n*w,b+=n*E,S+=n*I,N+=n*P,_+=n*C,T+=n*D,B+=n*L,X+=n*x,n=e[7],g+=n*re,m+=n*se,y+=n*U,A+=n*fe,O+=n*ue,R+=n*de,q+=n*ae,M+=n*le,b+=n*w,S+=n*E,N+=n*I,_+=n*P,T+=n*C,B+=n*D,X+=n*L,z+=n*x,n=e[8],m+=n*re,y+=n*se,A+=n*U,O+=n*fe,R+=n*ue,q+=n*de,M+=n*ae,b+=n*le,S+=n*w,N+=n*E,_+=n*I,T+=n*P,B+=n*C,X+=n*D,z+=n*L,k+=n*x,n=e[9],y+=n*re,A+=n*se,O+=n*U,R+=n*fe,q+=n*ue,M+=n*de,b+=n*ae,S+=n*le,N+=n*w,_+=n*E,T+=n*I,B+=n*P,X+=n*C,z+=n*D,k+=n*L,Q+=n*x,n=e[10],A+=n*re,O+=n*se,R+=n*U,q+=n*fe,M+=n*ue,b+=n*de,S+=n*ae,N+=n*le,_+=n*w,T+=n*E,B+=n*I,X+=n*P,z+=n*C,k+=n*D,Q+=n*L,K+=n*x,n=e[11],O+=n*re,R+=n*se,q+=n*U,M+=n*fe,b+=n*ue,S+=n*de,N+=n*ae,_+=n*le,T+=n*w,B+=n*E,X+=n*I,z+=n*P,k+=n*C,Q+=n*D,K+=n*L,ye+=n*x,n=e[12],R+=n*re,q+=n*se,M+=n*U,b+=n*fe,S+=n*ue,N+=n*de,_+=n*ae,T+=n*le,B+=n*w,X+=n*E,z+=n*I,k+=n*P,Q+=n*C,K+=n*D,ye+=n*L,ce+=n*x,n=e[13],q+=n*re,M+=n*se,b+=n*U,S+=n*fe,N+=n*ue,_+=n*de,T+=n*ae,B+=n*le,X+=n*w,z+=n*E,k+=n*I,Q+=n*P,K+=n*C,ye+=n*D,ce+=n*L,ie+=n*x,n=e[14],M+=n*re,b+=n*se,S+=n*U,N+=n*fe,_+=n*ue,T+=n*de,B+=n*ae,X+=n*le,z+=n*w,k+=n*E,Q+=n*I,K+=n*P,ye+=n*C,ce+=n*D,ie+=n*L,J+=n*x,n=e[15],b+=n*re,S+=n*se,N+=n*U,_+=n*fe,T+=n*ue,B+=n*de,X+=n*ae,z+=n*le,k+=n*w,Q+=n*E,K+=n*I,ye+=n*P,ce+=n*C,ie+=n*D,J+=n*L,oe+=n*x,s+=38*S,o+=38*N,a+=38*_,u+=38*T,c+=38*B,f+=38*X,d+=38*z,g+=38*k,m+=38*Q,y+=38*K,A+=38*ye,O+=38*ce,R+=38*ie,q+=38*J,M+=38*oe,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=a,t[3]=u,t[4]=c,t[5]=f,t[6]=d,t[7]=g,t[8]=m,t[9]=y,t[10]=A,t[11]=O,t[12]=R,t[13]=q,t[14]=M,t[15]=b}function eo(t,e){$e(t,e,e)}function kD(t,e){let r=Te(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)eo(r,r),n!==2&&n!==4&&$e(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function G9(t,e){let r=Te(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)eo(r,r),n!==1&&$e(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function Y1(t,e){let r=Te(),n=Te(),i=Te(),s=Te(),o=Te(),a=Te(),u=Te(),c=Te(),f=Te();to(r,t[1],t[0]),to(f,e[1],e[0]),$e(r,r,f),Zs(n,t[0],t[1]),Zs(f,e[0],e[1]),$e(n,n,f),$e(i,t[3],e[3]),$e(i,i,V9),$e(s,t[2],e[2]),Zs(s,s,s),to(o,n,r),to(a,s,i),Zs(u,s,i),Zs(c,n,r),$e(t[0],o,a),$e(t[1],c,u),$e(t[2],u,a),$e(t[3],o,c)}function MD(t,e,r){for(let n=0;n<4;n++)qD(t[n],e[n],r)}function X1(t,e){let r=Te(),n=Te(),i=Te();kD(i,e[2]),$e(r,e[0],i),$e(n,e[1],i),fl(t,n),t[31]^=HD(r)<<7}function GD(t,e,r){zi(t[0],K1),zi(t[1],ka),zi(t[2],ka),zi(t[3],K1);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;MD(t,e,i),Y1(e,t),Y1(t,t),MD(t,e,i)}}function Z1(t,e){let r=[Te(),Te(),Te(),Te()];zi(r[0],BD),zi(r[1],LD),zi(r[2],ka),$e(r[3],BD,LD),GD(t,r,e)}function jD(t){if(t.length!==ke.SEED_LENGTH)throw new Error(`ed25519: seed must be ${ke.SEED_LENGTH} bytes`);let e=(0,ll.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[Te(),Te(),Te(),Te()];Z1(n,e),X1(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}ke.generateKeyPairFromSeed=jD;function j9(t){let e=(0,M9.randomBytes)(32,t),r=jD(e);return(0,UD.wipe)(e),r}ke.generateKeyPair=j9;function Q9(t){if(t.length!==ke.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${ke.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}ke.extractPublicKeyFromSecretKey=Q9;var $1=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function QD(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*$1[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*$1[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function J1(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;QD(t,e)}function z9(t,e){let r=new Float64Array(64),n=[Te(),Te(),Te(),Te()],i=(0,ll.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new ll.SHA512;o.update(s.subarray(32)),o.update(e);let a=o.digest();o.clean(),J1(a),Z1(n,a),X1(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let u=o.digest();J1(u);for(let c=0;c<32;c++)r[c]=a[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=u[c]*i[f];return QD(s.subarray(32),r),s}ke.sign=z9;function zD(t,e){let r=Te(),n=Te(),i=Te(),s=Te(),o=Te(),a=Te(),u=Te();return zi(t[2],ka),k9(t[1],e),eo(i,t[1]),$e(s,i,q9),to(i,i,t[2]),Zs(s,t[2],s),eo(o,s),eo(a,o),$e(u,a,o),$e(r,u,i),$e(r,r,s),G9(r,r),$e(r,r,i),$e(r,r,s),$e(r,r,s),$e(t[0],r,s),eo(n,t[0]),$e(n,n,s),FD(n,i)&&$e(t[0],t[0],H9),eo(n,t[0]),$e(n,n,s),FD(n,i)?-1:(HD(t[0])===e[31]>>7&&to(t[0],K1,t[0]),$e(t[3],t[0],t[1]),0)}function W9(t,e,r){let n=new Uint8Array(32),i=[Te(),Te(),Te(),Te()],s=[Te(),Te(),Te(),Te()];if(r.length!==ke.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${ke.SIGNATURE_LENGTH} bytes`);if(zD(s,t))return!1;let o=new ll.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let a=o.digest();return J1(a),GD(i,s,a),Z1(s,r.subarray(32)),Y1(i,s),X1(n,i),!VD(r,n)}ke.verify=W9;function $9(t){let e=[Te(),Te(),Te(),Te()];if(zD(e,t))throw new Error("Ed25519: invalid public key");let r=Te(),n=Te(),i=e[1];Zs(r,ka,i),to(n,ka,i),kD(n,n),$e(r,r,n);let s=new Uint8Array(32);return fl(s,r),s}ke.convertPublicKeyToX25519=$9;function K9(t){let e=(0,ll.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,UD.wipe)(e),r}ke.convertSecretKeyToX25519=K9});var hp,pp,ro,Ga,gp,dl,yp,mp,wp,ja,Ep,vp,$D,KD,Ap=he(()=>{l();hp="EdDSA",pp="JWT",ro=".",Ga="base64url",gp="utf8",dl="utf8",yp=":",mp="did",wp="key",ja="base58btc",Ep="z",vp="K36",$D=32,KD=32});function Wi(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var hl=he(()=>{l()});function Qa(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Wi(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var bp=he(()=>{l();hl()});function Ip(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=Qa(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Wi(r)}var eA=he(()=>{l();bp();hl()});function Y9(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,b=new Uint8Array(M);R!==q;){for(var S=y[R],N=0,_=M-1;(S!==0||N>>0,b[_]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");O=N,R++}for(var T=M-O;T!==M&&b[T]===0;)T++;for(var B=u.repeat(A);T>>0,M=new Uint8Array(q);y[A];){var b=r[y.charCodeAt(A)];if(b===255)return;for(var S=0,N=q-1;(b!==0||S>>0,M[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");R=S,A++}if(y[A]!==" "){for(var _=q-R;_!==q&&M[_]===0;)_++;for(var T=new Uint8Array(O+(q-_)),B=O;_!==q;)T[B++]=M[_++];return T}}}function m(y){var A=g(y);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:g,decode:m}}var J9,X9,YD,JD=he(()=>{l();J9=Y9,X9=J9,YD=X9});var yhe,XD,ii,ZD,eP,$i=he(()=>{l();yhe=new Uint8Array(0),XD=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},ZD=t=>new TextEncoder().encode(t),eP=t=>new TextDecoder().decode(t)});var tA,rA,nA,rP,iA,za,Ki,Z9,ez,yt,tn=he(()=>{l();JD();$i();tA=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},rA=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rP(this,e)}},nA=class{constructor(e){this.decoders=e}or(e){return rP(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},rP=(t,e)=>new nA({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),iA=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new tA(e,r,n),this.decoder=new rA(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},za=({name:t,prefix:e,encode:r,decode:n})=>new iA(t,e,r,n),Ki=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=YD(r,e);return za({prefix:t,name:e,encode:n,decode:s=>ii(i(s))})},Z9=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(a-=8,o[c++]=255&u>>a)}if(a>=r||255&u<<8-a)throw new SyntaxError("Unexpected end of data");return o},ez=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<za({prefix:e,name:t,encode(i){return ez(i,n,r)},decode(i){return Z9(i,n,r,t)}})});var sA={};ft(sA,{identity:()=>tz});var tz,nP=he(()=>{l();tn();$i();tz=za({prefix:"\0",name:"identity",encode:t=>eP(t),decode:t=>ZD(t)})});var oA={};ft(oA,{base2:()=>rz});var rz,iP=he(()=>{l();tn();rz=yt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var aA={};ft(aA,{base8:()=>nz});var nz,sP=he(()=>{l();tn();nz=yt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var uA={};ft(uA,{base10:()=>iz});var iz,oP=he(()=>{l();tn();iz=Ki({prefix:"9",name:"base10",alphabet:"0123456789"})});var cA={};ft(cA,{base16:()=>sz,base16upper:()=>oz});var sz,oz,aP=he(()=>{l();tn();sz=yt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oz=yt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var lA={};ft(lA,{base32:()=>Wa,base32hex:()=>lz,base32hexpad:()=>dz,base32hexpadupper:()=>hz,base32hexupper:()=>fz,base32pad:()=>uz,base32padupper:()=>cz,base32upper:()=>az,base32z:()=>pz});var Wa,az,uz,cz,lz,fz,dz,hz,pz,fA=he(()=>{l();tn();Wa=yt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),az=yt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),uz=yt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cz=yt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lz=yt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fz=yt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dz=yt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hz=yt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pz=yt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var dA={};ft(dA,{base36:()=>gz,base36upper:()=>yz});var gz,yz,uP=he(()=>{l();tn();gz=Ki({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yz=Ki({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var hA={};ft(hA,{base58btc:()=>Nn,base58flickr:()=>mz});var Nn,mz,pA=he(()=>{l();tn();Nn=Ki({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mz=Ki({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var gA={};ft(gA,{base64:()=>wz,base64pad:()=>Ez,base64url:()=>vz,base64urlpad:()=>Az});var wz,Ez,vz,Az,cP=he(()=>{l();tn();wz=yt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ez=yt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vz=yt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Az=yt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var yA={};ft(yA,{base256emoji:()=>Tz});function _z(t){return t.reduce((e,r)=>(e+=bz[r],e),"")}function Sz(t){let e=[];for(let r of t){let n=Iz[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var lP,bz,Iz,Tz,fP=he(()=>{l();tn();lP=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),bz=lP.reduce((t,e,r)=>(t[r]=e,t),[]),Iz=lP.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);Tz=za({prefix:"\u{1F680}",name:"base256emoji",encode:_z,decode:Sz})});function pP(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Oz;)e[r++]=t&255|dP,t/=128;for(;t&Nz;)e[r++]=t&255|dP,t>>>=7;return e[r]=t|0,pP.bytes=r-n+1,e}function mA(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw mA.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&hP)<=Pz);return mA.bytes=s-n,r}var Cz,dP,xz,Nz,Oz,Dz,Pz,hP,Rz,Bz,Lz,Fz,Mz,Uz,qz,Vz,Hz,kz,Gz,jz,pl,gP=he(()=>{l();Cz=pP,dP=128,xz=127,Nz=~xz,Oz=Math.pow(2,31);Dz=mA,Pz=128,hP=127;Rz=Math.pow(2,7),Bz=Math.pow(2,14),Lz=Math.pow(2,21),Fz=Math.pow(2,28),Mz=Math.pow(2,35),Uz=Math.pow(2,42),qz=Math.pow(2,49),Vz=Math.pow(2,56),Hz=Math.pow(2,63),kz=function(t){return t{l();gP();gl=(t,e=0)=>[pl.decode(t,e),pl.decode.bytes],$a=(t,e,r=0)=>(pl.encode(t,e,r),e),Ka=t=>pl.encodingLength(t)});var no,yP,mP,Ya,ml=he(()=>{l();$i();Sp();no=(t,e)=>{let r=e.byteLength,n=Ka(t),i=n+Ka(r),s=new Uint8Array(i+r);return $a(t,s,0),$a(r,s,n),s.set(e,i),new Ya(t,r,e,s)},yP=t=>{let e=ii(t),[r,n]=gl(e),[i,s]=gl(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Ya(r,i,o,e)},mP=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&XD(t.bytes,e.bytes),Ya=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var EA,wA,vA=he(()=>{l();ml();EA=({name:t,code:e,encode:r})=>new wA(t,e,r),wA=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?no(this.code,r):r.then(n=>no(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var AA={};ft(AA,{sha256:()=>Qz,sha512:()=>zz});var EP,Qz,zz,vP=he(()=>{l();vA();EP=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Qz=EA({name:"sha2-256",code:18,encode:EP("SHA-256")}),zz=EA({name:"sha2-512",code:19,encode:EP("SHA-512")})});var bA={};ft(bA,{identity:()=>Kz});var AP,Wz,bP,$z,Kz,IP=he(()=>{l();$i();ml();AP=0,Wz="identity",bP=ii,$z=t=>no(AP,bP(t)),Kz={code:AP,name:Wz,encode:bP,digest:$z}});var _P=he(()=>{l();$i()});var rpe,npe,SP=he(()=>{l();rpe=new TextEncoder,npe=new TextDecoder});var xp,Xz,Zz,eW,wl,tW,TP,CP,Tp,Cp,rW,nW,iW,xP=he(()=>{l();Sp();ml();pA();fA();$i();xp=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Cp,byteLength:Cp,code:Tp,version:Tp,multihash:Tp,bytes:Tp,_baseCache:Cp,asCID:Cp})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==wl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==tW)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=no(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&mP(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return Zz(r,i,e||Nn.encoder);default:return eW(r,i,e||Wa.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return nW(/^0\.0/,iW),!!(e&&(e[CP]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||TP(r,n,i.bytes))}else if(e!=null&&e[CP]===!0){let{version:r,multihash:n,code:i}=e,s=yP(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==wl)throw new Error(`Version 0 CID must use dag-pb (code: ${wl}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=TP(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,wl,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=ii(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new Ya(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,g]=gl(e.subarray(r));return r+=g,d},i=n(),s=wl;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),u=n(),c=r+u,f=c-o;return{version:i,codec:s,multihashCode:a,digestSize:u,multihashSize:f,size:c}}static parse(e,r){let[n,i]=Xz(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},Xz=(t,e)=>{switch(t[0]){case"Q":{let r=e||Nn;return[Nn.prefix,r.decode(`${Nn.prefix}${t}`)]}case Nn.prefix:{let r=e||Nn;return[Nn.prefix,r.decode(t)]}case Wa.prefix:{let r=e||Wa;return[Wa.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Zz=(t,e,r)=>{let{prefix:n}=r;if(n!==Nn.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},eW=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},wl=112,tW=18,TP=(t,e,r)=>{let n=Ka(t),i=n+Ka(e),s=new Uint8Array(i+r.byteLength);return $a(t,s,0),$a(e,s,n),s.set(r,i),s},CP=Symbol.for("@ipld/js-cid/CID"),Tp={writable:!1,configurable:!1,enumerable:!0},Cp={writable:!1,enumerable:!1,configurable:!1},rW="0.0.0-dev",nW=(t,e)=>{if(t.test(rW))console.warn(e);else throw new Error(e)},iW=`CID.isCID(v) is deprecated and will be removed in the next major release. +`); + } + }; + exports2.ErrContractHasNoAddress = ErrContractHasNoAddress; + var ErrMock = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrMock = ErrMock; + var ErrTypingSystem = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrTypingSystem = ErrTypingSystem; + var ErrMissingFieldOnStruct = class extends Err { + constructor(fieldName, structName) { + super(`field ${fieldName} does not exist on struct ${structName}`); + } + }; + exports2.ErrMissingFieldOnStruct = ErrMissingFieldOnStruct; + var ErrMissingFieldOnEnum = class extends Err { + constructor(fieldName, enumName) { + super(`field ${fieldName} does not exist on enum ${enumName}`); + } + }; + exports2.ErrMissingFieldOnEnum = ErrMissingFieldOnEnum; + var ErrCannotParseContractResults = class extends Err { + constructor(details) { + super(`cannot parse contract results: ${details}`); + } + }; + exports2.ErrCannotParseContractResults = ErrCannotParseContractResults; + var ErrCannotParseTransactionOutcome = class extends Err { + constructor(transactionHash, message) { + super(`cannot parse outcome of transaction ${transactionHash}: ${message}`); + } + }; + exports2.ErrCannotParseTransactionOutcome = ErrCannotParseTransactionOutcome; + var ErrCodec = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrCodec = ErrCodec; + var ErrContractInteraction = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrContractInteraction = ErrContractInteraction; + var ErrNotImplemented = class extends Err { + constructor() { + super("Method not yet implemented"); + } + }; + exports2.ErrNotImplemented = ErrNotImplemented; + var ErrInvalidRelayedV1BuilderArguments = class extends Err { + constructor() { + super("invalid arguments for relayed v1 builder"); + } + }; + exports2.ErrInvalidRelayedV1BuilderArguments = ErrInvalidRelayedV1BuilderArguments; + var ErrInvalidRelayedV2BuilderArguments = class extends Err { + constructor() { + super("invalid arguments for relayed v2 builder"); + } + }; + exports2.ErrInvalidRelayedV2BuilderArguments = ErrInvalidRelayedV2BuilderArguments; + var ErrGasLimitShouldBe0ForInnerTransaction = class extends Err { + constructor() { + super("gas limit must be 0 for the inner transaction for relayed v2"); + } + }; + exports2.ErrGasLimitShouldBe0ForInnerTransaction = ErrGasLimitShouldBe0ForInnerTransaction; + var ErrIsCompletedFieldIsMissingOnTransaction = class extends Err { + constructor() { + super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`."); + } + }; + exports2.ErrIsCompletedFieldIsMissingOnTransaction = ErrIsCompletedFieldIsMissingOnTransaction; + var ErrInvalidTokenIdentifier = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrInvalidTokenIdentifier = ErrInvalidTokenIdentifier; + var ErrBadUsage = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrBadUsage = ErrBadUsage; + var ErrInvalidInnerTransaction = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrInvalidInnerTransaction = ErrInvalidInnerTransaction; + var ErrParseTransactionOutcome = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrParseTransactionOutcome = ErrParseTransactionOutcome; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokens.js +var require_tokens = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokens.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenPayment = exports2.TokenComputer = exports2.TokenTransfer = exports2.Token = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var errors_1 = require_errors(); + var EGLDTokenIdentifier = "EGLD"; + var EGLDNumDecimals = 18; + bignumber_js_1.default.set({ ROUNDING_MODE: 1 }); + var Token2 = class { + constructor(options) { + this.identifier = options.identifier; + this.nonce = options.nonce || 0n; + } + }; + exports2.Token = Token2; + var TokenTransfer2 = class _TokenTransfer { + constructor(options) { + if (this.isLegacyTokenTransferOptions(options)) { + const amount = new bignumber_js_1.default(options.amountAsBigInteger); + if (!amount.isInteger() || amount.isNegative()) { + throw new errors_1.ErrInvalidArgument(`bad amountAsBigInteger: ${options.amountAsBigInteger}`); + } + this.tokenIdentifier = options.tokenIdentifier; + this.nonce = options.nonce; + this.amountAsBigInteger = amount; + this.numDecimals = options.numDecimals || 0; + this.token = new Token2({ + identifier: options.tokenIdentifier, + nonce: BigInt(options.nonce) + }); + this.amount = BigInt(this.amountAsBigInteger.toFixed(0)); + } else { + this.token = options.token; + this.amount = options.amount; + this.tokenIdentifier = options.token.identifier; + this.nonce = Number(options.token.nonce); + this.amountAsBigInteger = new bignumber_js_1.default(this.amount.toString()); + this.numDecimals = 0; + } + } + isLegacyTokenTransferOptions(options) { + return options.tokenIdentifier !== void 0; + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static egldFromAmount(amount) { + const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(EGLDNumDecimals).decimalPlaces(0); + return this.egldFromBigInteger(amountAsBigInteger); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static egldFromBigInteger(amountAsBigInteger) { + return new _TokenTransfer({ + tokenIdentifier: EGLDTokenIdentifier, + nonce: 0, + amountAsBigInteger, + numDecimals: EGLDNumDecimals + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static fungibleFromAmount(tokenIdentifier, amount, numDecimals) { + const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); + return this.fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals = 0) { + return new _TokenTransfer({ + tokenIdentifier, + nonce: 0, + amountAsBigInteger, + numDecimals + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static nonFungible(tokenIdentifier, nonce) { + return new _TokenTransfer({ + tokenIdentifier, + nonce, + amountAsBigInteger: 1, + numDecimals: 0 + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static semiFungible(tokenIdentifier, nonce, quantity) { + return new _TokenTransfer({ + tokenIdentifier, + nonce, + amountAsBigInteger: quantity, + numDecimals: 0 + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static metaEsdtFromAmount(tokenIdentifier, nonce, amount, numDecimals) { + const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); + return this.metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals = 0) { + return new _TokenTransfer({ + tokenIdentifier, + nonce, + amountAsBigInteger, + numDecimals + }); + } + toString() { + return this.amount.toString(); + } + /** + * Legacy function. Use the "amount" field instead. + */ + valueOf() { + return new bignumber_js_1.default(this.amount.toString()); + } + /** + * Legacy function. For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. + */ + toPrettyString() { + return `${this.toAmount()} ${this.tokenIdentifier}`; + } + toAmount() { + return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals); + } + /** + * Legacy function. Within your code, don't mix native values (EGLD) and custom (ESDT) tokens. + * See "TransferTransactionsFactory.createTransactionForNativeTokenTransfer()" vs. "TransferTransactionsFactory.createTransactionForESDTTokenTransfer()". + */ + isEgld() { + return this.token.identifier == EGLDTokenIdentifier; + } + /** + * Legacy function. Use "TokenComputer.isFungible(token)" instead. + */ + isFungible() { + return this.token.nonce == 0n; + } + }; + exports2.TokenTransfer = TokenTransfer2; + var TokenComputer2 = class { + constructor() { + } + isFungible(token) { + return token.nonce === 0n; + } + extractNonceFromExtendedIdentifier(identifier) { + const parts = identifier.split("-"); + this.checkIfExtendedIdentifierWasProvided(parts); + this.checkLengthOfRandomSequence(parts[1]); + if (parts.length == 2) { + return 0; + } + const hexNonce = import_buffer.Buffer.from(parts[2], "hex"); + return decodeUnsignedNumber(hexNonce); + } + extractIdentifierFromExtendedIdentifier(identifier) { + const parts = identifier.split("-"); + this.checkIfExtendedIdentifierWasProvided(parts); + this.ensureTokenTickerValidity(parts[0]); + this.checkLengthOfRandomSequence(parts[1]); + return parts[0] + "-" + parts[1]; + } + checkIfExtendedIdentifierWasProvided(tokenParts) { + const MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 2; + const MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 3; + if (tokenParts.length < MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED || tokenParts.length > MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED) { + throw new errors_1.ErrInvalidTokenIdentifier("Invalid extended token identifier provided"); + } + } + checkLengthOfRandomSequence(randomSequence) { + const TOKEN_RANDOM_SEQUENCE_LENGTH = 6; + if (randomSequence.length !== TOKEN_RANDOM_SEQUENCE_LENGTH) { + throw new errors_1.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length"); + } + } + ensureTokenTickerValidity(ticker) { + const MIN_TICKER_LENGTH = 3; + const MAX_TICKER_LENGTH = 10; + if (ticker.length < MIN_TICKER_LENGTH || ticker.length > MAX_TICKER_LENGTH) { + throw new errors_1.ErrInvalidTokenIdentifier(`The token ticker should be between ${MIN_TICKER_LENGTH} and ${MAX_TICKER_LENGTH} characters`); + } + if (!ticker.match(/^[a-zA-Z0-9]+$/)) { + throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters"); + } + if (!(ticker == ticker.toUpperCase())) { + throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should be upper case"); + } + } + }; + exports2.TokenComputer = TokenComputer2; + function decodeUnsignedNumber(arg) { + return arg.readUIntBE(0, arg.length); + } + var TokenPayment = class extends TokenTransfer2 { + constructor(tokenIdentifier, nonce, amountAsBigInteger, numDecimals) { + super({ + tokenIdentifier, + nonce, + amountAsBigInteger, + numDecimals + }); + } + }; + exports2.TokenPayment = TokenPayment; + } +}); + +// node_modules/@multiversx/sdk-core/out/constants.js +var require_constants = __commonJS({ + "node_modules/@multiversx/sdk-core/out/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UNKNOWN_SIGNER = exports2.SDK_JS_SIGNER = exports2.METACHAIN_ID = exports2.WasmVirtualMachine = exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = exports2.BECH32_ADDRESS_LENGTH = exports2.HEX_TRANSACTION_HASH_LENGTH = exports2.MESSAGE_PREFIX = exports2.DEFAULT_MESSAGE_VERSION = exports2.ESDT_CONTRACT_ADDRESS = exports2.DEFAULT_HRP = exports2.DELEGATION_MANAGER_SC_ADDRESS = exports2.CONTRACT_DEPLOY_ADDRESS = exports2.VM_TYPE_WASM_VM = exports2.ARGUMENTS_SEPARATOR = exports2.ESDT_TRANSFER_VALUE = exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_GAS_LIMIT = exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = exports2.TRANSACTION_VERSION_DEFAULT = exports2.TRANSACTION_OPTIONS_TX_GUARDED = exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = exports2.TRANSACTION_OPTIONS_DEFAULT = exports2.TRANSACTION_MIN_GAS_PRICE = void 0; + exports2.TRANSACTION_MIN_GAS_PRICE = 1e9; + exports2.TRANSACTION_OPTIONS_DEFAULT = 0; + exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = 1; + exports2.TRANSACTION_OPTIONS_TX_GUARDED = 2; + exports2.TRANSACTION_VERSION_DEFAULT = 2; + exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = 2; + exports2.ESDT_TRANSFER_GAS_LIMIT = 5e5; + exports2.ESDT_TRANSFER_FUNCTION_NAME = "ESDTTransfer"; + exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = "ESDTNFTTransfer"; + exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = "MultiESDTNFTTransfer"; + exports2.ESDT_TRANSFER_VALUE = "0"; + exports2.ARGUMENTS_SEPARATOR = "@"; + exports2.VM_TYPE_WASM_VM = new Uint8Array([5, 0]); + exports2.CONTRACT_DEPLOY_ADDRESS = "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"; + exports2.DELEGATION_MANAGER_SC_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"; + exports2.DEFAULT_HRP = "erd"; + exports2.ESDT_CONTRACT_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"; + exports2.DEFAULT_MESSAGE_VERSION = 1; + exports2.MESSAGE_PREFIX = "Elrond Signed Message:\n"; + exports2.HEX_TRANSACTION_HASH_LENGTH = 64; + exports2.BECH32_ADDRESS_LENGTH = 62; + exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = 3; + exports2.WasmVirtualMachine = "0500"; + exports2.METACHAIN_ID = 4294967295; + exports2.SDK_JS_SIGNER = "sdk-js"; + exports2.UNKNOWN_SIGNER = "unknown"; + } +}); + +// node_modules/@multiversx/sdk-core/out/logger.js +var require_logger = __commonJS({ + "node_modules/@multiversx/sdk-core/out/logger.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Logger = exports2.LogLevel = void 0; + var LogLevel; + (function(LogLevel2) { + LogLevel2[LogLevel2["Trace"] = 0] = "Trace"; + LogLevel2[LogLevel2["Debug"] = 1] = "Debug"; + LogLevel2[LogLevel2["Info"] = 2] = "Info"; + LogLevel2[LogLevel2["Warn"] = 3] = "Warn"; + LogLevel2[LogLevel2["Error"] = 4] = "Error"; + LogLevel2[LogLevel2["None"] = 5] = "None"; + })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); + var Logger = class _Logger { + static setLevel(logLevel) { + _Logger.logLevel = logLevel; + } + static trace(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Debug) { + return; + } + console.debug(message, optionalParams); + } + static debug(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Debug) { + return; + } + console.debug(message, optionalParams); + } + static info(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Info) { + return; + } + console.log(message, optionalParams); + } + static warn(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Warn) { + return; + } + console.warn(message, optionalParams); + } + static error(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Error) { + return; + } + console.error(message, optionalParams); + } + }; + exports2.Logger = Logger; + Logger.logLevel = LogLevel.Debug; + } +}); + +// node_modules/@multiversx/sdk-core/out/networkParams.js +var require_networkParams = __commonJS({ + "node_modules/@multiversx/sdk-core/out/networkParams.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionOptions = exports2.TransactionVersion = void 0; + var constants_1 = require_constants(); + var errors = __importStar2(require_errors()); + var TransactionVersion2 = class _TransactionVersion { + /** + * Creates a TransactionVersion object given a value. + */ + constructor(value) { + value = Number(value); + if (value < 1) { + throw new errors.ErrTransactionVersionInvalid(value); + } + this.value = value; + } + /** + * Creates a TransactionVersion object with the default version setting + */ + static withDefaultVersion() { + return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); + } + /** + * Creates a TransactionVersion object with the VERSION setting for enabling options + */ + static withTxOptions() { + return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); + } + valueOf() { + return this.value; + } + }; + exports2.TransactionVersion = TransactionVersion2; + var TransactionOptions2 = class _TransactionOptions { + /** + * Creates a TransactionOptions from a numeric value. + */ + constructor(value) { + value = Number(value); + if (value < 0) { + throw new errors.ErrTransactionOptionsInvalid(value); + } + this.value = value; + } + /** + * Creates a TransactionOptions object with the default options. + */ + static withDefaultOptions() { + return new _TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); + } + /** + * Creates a TransactionOptions object from a set of options. + */ + static withOptions(options) { + let value = 0; + if (options.hashSign) { + value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + if (options.guarded) { + value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + return new _TransactionOptions(value); + } + /** + * Returns true if the "hash sign" option is set. + */ + isWithHashSign() { + return (this.value & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + /** + * Returns true if the "guarded transaction" option is set. + */ + isWithGuardian() { + return (this.value & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + /** + * Sets the "hash sign" option. + */ + setWithHashSign() { + this.value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + /** + * Sets the "guarded transaction" option. + */ + setWithGuardian() { + this.value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + valueOf() { + return this.value; + } + }; + exports2.TransactionOptions = TransactionOptions2; + } +}); + +// node_modules/bech32/index.js +var require_bech32 = __commonJS({ + "node_modules/bech32/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + var ALPHABET_MAP = {}; + for (z3 = 0; z3 < ALPHABET.length; z3++) { + x3 = ALPHABET.charAt(z3); + if (ALPHABET_MAP[x3] !== void 0) + throw new TypeError(x3 + " is ambiguous"); + ALPHABET_MAP[x3] = z3; + } + var x3; + var z3; + function polymodStep(pre) { + var b4 = pre >> 25; + return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; + } + function prefixChk(prefix) { + var chk = 1; + for (var i2 = 0; i2 < prefix.length; ++i2) { + var c4 = prefix.charCodeAt(i2); + if (c4 < 33 || c4 > 126) + return "Invalid prefix (" + prefix + ")"; + chk = polymodStep(chk) ^ c4 >> 5; + } + chk = polymodStep(chk); + for (i2 = 0; i2 < prefix.length; ++i2) { + var v2 = prefix.charCodeAt(i2); + chk = polymodStep(chk) ^ v2 & 31; + } + return chk; + } + function encode5(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) + throw new TypeError("Exceeds length limit"); + prefix = prefix.toLowerCase(); + var chk = prefixChk(prefix); + if (typeof chk === "string") + throw new Error(chk); + var result = prefix + "1"; + for (var i2 = 0; i2 < words.length; ++i2) { + var x4 = words[i2]; + if (x4 >> 5 !== 0) + throw new Error("Non 5-bit word"); + chk = polymodStep(chk) ^ x4; + result += ALPHABET.charAt(x4); + } + for (i2 = 0; i2 < 6; ++i2) { + chk = polymodStep(chk); + } + chk ^= 1; + for (i2 = 0; i2 < 6; ++i2) { + var v2 = chk >> (5 - i2) * 5 & 31; + result += ALPHABET.charAt(v2); + } + return result; + } + function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) + return str + " too short"; + if (str.length > LIMIT) + return "Exceeds length limit"; + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) + return "Mixed-case string " + str; + str = lowered; + var split = str.lastIndexOf("1"); + if (split === -1) + return "No separator character for " + str; + if (split === 0) + return "Missing prefix for " + str; + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) + return "Data too short"; + var chk = prefixChk(prefix); + if (typeof chk === "string") + return chk; + var words = []; + for (var i2 = 0; i2 < wordChars.length; ++i2) { + var c4 = wordChars.charAt(i2); + var v2 = ALPHABET_MAP[c4]; + if (v2 === void 0) + return "Unknown character " + c4; + chk = polymodStep(chk) ^ v2; + if (i2 + 6 >= wordChars.length) + continue; + words.push(v2); + } + if (chk !== 1) + return "Invalid checksum for " + str; + return { prefix, words }; + } + function decodeUnsafe() { + var res = __decode.apply(null, arguments); + if (typeof res === "object") + return res; + } + function decode6(str) { + var res = __decode.apply(null, arguments); + if (typeof res === "object") + return res; + throw new Error(res); + } + function convert(data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + var result = []; + for (var i2 = 0; i2 < data.length; ++i2) { + value = value << inBits | data[i2]; + bits += inBits; + while (bits >= outBits) { + bits -= outBits; + result.push(value >> bits & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push(value << outBits - bits & maxV); + } + } else { + if (bits >= inBits) + return "Excess padding"; + if (value << outBits - bits & maxV) + return "Non-zero padding"; + } + return result; + } + function toWordsUnsafe(bytes) { + var res = convert(bytes, 8, 5, true); + if (Array.isArray(res)) + return res; + } + function toWords(bytes) { + var res = convert(bytes, 8, 5, true); + if (Array.isArray(res)) + return res; + throw new Error(res); + } + function fromWordsUnsafe(words) { + var res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + } + function fromWords(words) { + var res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + throw new Error(res); + } + module2.exports = { + decodeUnsafe, + decode: decode6, + encode: encode5, + toWordsUnsafe, + toWords, + fromWordsUnsafe, + fromWords + }; + } +}); + +// node_modules/@multiversx/sdk-core/out/utils.codec.js +var require_utils_codec = __commonJS({ + "node_modules/@multiversx/sdk-core/out/utils.codec.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addressToHex = exports2.bigIntToHex = exports2.byteArrayToHex = exports2.boolToHex = exports2.utf8ToHex = exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var contractsCodecUtils = __importStar2(require_utils()); + function numberToPaddedHex(value) { + let hexableNumber; + if (typeof value === "bigint" || typeof value === "number") { + hexableNumber = value; + } else { + hexableNumber = new bignumber_js_1.default(value); + } + const hex = hexableNumber.toString(16); + return zeroPadStringIfOddLength(hex); + } + exports2.numberToPaddedHex = numberToPaddedHex; + function isPaddedHex(input) { + input = input || ""; + let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); + return input.toUpperCase() == decodedThenEncoded.toUpperCase(); + } + exports2.isPaddedHex = isPaddedHex; + function zeroPadStringIfOddLength(input) { + input = input || ""; + if (input.length % 2 == 1) { + return "0" + input; + } + return input; + } + exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; + function utf8ToHex(value) { + const hex = import_buffer.Buffer.from(value).toString("hex"); + return zeroPadStringIfOddLength(hex); + } + exports2.utf8ToHex = utf8ToHex; + function boolToHex(value) { + return utf8ToHex(value.toString()); + } + exports2.boolToHex = boolToHex; + function byteArrayToHex(byteArray) { + const hexString = import_buffer.Buffer.from(byteArray).toString("hex"); + return zeroPadStringIfOddLength(hexString); + } + exports2.byteArrayToHex = byteArrayToHex; + function bigIntToHex(value) { + if (value == 0) { + return ""; + } + return contractsCodecUtils.getHexMagnitudeOfBigInt(value); + } + exports2.bigIntToHex = bigIntToHex; + function addressToHex(address) { + const buffer = address_1.Address.fromBech32(address.toString()).pubkey(); + return buffer.toString("hex"); + } + exports2.addressToHex = addressToHex; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js +var require_utils = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.prependByteToBuffer = exports2.flipBufferBitsInPlace = exports2.getHexMagnitudeOfBigInt = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.cloneBuffer = exports2.isMsbZero = exports2.isMsbOne = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var utils_codec_1 = require_utils_codec(); + function isMsbOne(buffer, byteIndex = 0) { + let byte = buffer[byteIndex]; + let bit = byte >> 7; + let isSet = bit == 1; + return isSet; + } + exports2.isMsbOne = isMsbOne; + function isMsbZero(buffer, byteIndex = 0) { + return !isMsbOne(buffer, byteIndex); + } + exports2.isMsbZero = isMsbZero; + function cloneBuffer(buffer) { + let clone2 = import_buffer.Buffer.alloc(buffer.length); + buffer.copy(clone2); + return clone2; + } + exports2.cloneBuffer = cloneBuffer; + function bufferToBigInt(buffer) { + let hex = buffer.toString("hex"); + return new bignumber_js_1.default(`0x${hex}`, 16); + } + exports2.bufferToBigInt = bufferToBigInt; + function bigIntToBuffer(value) { + let hex = getHexMagnitudeOfBigInt(value); + return import_buffer.Buffer.from(hex, "hex"); + } + exports2.bigIntToBuffer = bigIntToBuffer; + function getHexMagnitudeOfBigInt(value) { + value = new bignumber_js_1.default(value); + if (!value) { + return ""; + } + if (value.isNegative()) { + value = value.multipliedBy(new bignumber_js_1.default(-1)); + } + return utils_codec_1.numberToPaddedHex(value); + } + exports2.getHexMagnitudeOfBigInt = getHexMagnitudeOfBigInt; + function flipBufferBitsInPlace(buffer) { + for (let i2 = 0; i2 < buffer.length; i2++) { + buffer[i2] = ~buffer[i2]; + } + } + exports2.flipBufferBitsInPlace = flipBufferBitsInPlace; + function prependByteToBuffer(buffer, byte) { + return import_buffer.Buffer.concat([import_buffer.Buffer.from([byte]), buffer]); + } + exports2.prependByteToBuffer = prependByteToBuffer; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js +var require_codec = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bufferToHex = exports2.addressToHex = exports2.bigIntToHex = exports2.utf8ToHex = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.stringToBuffer = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var contractsCodecUtils = __importStar2(require_utils()); + var codecUtils = __importStar2(require_utils_codec()); + function stringToBuffer(value) { + return import_buffer.Buffer.from(value); + } + exports2.stringToBuffer = stringToBuffer; + function bufferToBigInt(buffer) { + if (buffer.length == 0) { + return new bignumber_js_1.default(0); + } + return contractsCodecUtils.bufferToBigInt(buffer); + } + exports2.bufferToBigInt = bufferToBigInt; + function bigIntToBuffer(value) { + if (value == 0) { + return import_buffer.Buffer.from([]); + } + return contractsCodecUtils.bigIntToBuffer(value); + } + exports2.bigIntToBuffer = bigIntToBuffer; + var utils_codec_1 = require_utils_codec(); + Object.defineProperty(exports2, "utf8ToHex", { enumerable: true, get: function() { + return utils_codec_1.utf8ToHex; + } }); + Object.defineProperty(exports2, "bigIntToHex", { enumerable: true, get: function() { + return utils_codec_1.bigIntToHex; + } }); + Object.defineProperty(exports2, "addressToHex", { enumerable: true, get: function() { + return utils_codec_1.addressToHex; + } }); + function bufferToHex(value) { + const hex = value.toString("hex"); + return codecUtils.zeroPadStringIfOddLength(hex); + } + exports2.bufferToHex = bufferToHex; + } +}); + +// node_modules/events/events.js +var require_events = __commonJS({ + "node_modules/events/events.js"(exports2, module2) { + "use strict"; + init_shim(); + var R2 = typeof Reflect === "object" ? Reflect : null; + var ReflectApply = R2 && typeof R2.apply === "function" ? R2.apply : function ReflectApply2(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }; + var ReflectOwnKeys; + if (R2 && typeof R2.ownKeys === "function") { + ReflectOwnKeys = R2.ownKeys; + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target); + }; + } + function ProcessEmitWarning(warning) { + if (console && console.warn) + console.warn(warning); + } + var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { + return value !== value; + }; + function EventEmitter2() { + EventEmitter2.init.call(this); + } + module2.exports = EventEmitter2; + module2.exports.once = once; + EventEmitter2.EventEmitter = EventEmitter2; + EventEmitter2.prototype._events = void 0; + EventEmitter2.prototype._eventsCount = 0; + EventEmitter2.prototype._maxListeners = void 0; + var defaultMaxListeners = 10; + function checkListener(listener) { + if (typeof listener !== "function") { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + } + Object.defineProperty(EventEmitter2, "defaultMaxListeners", { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); + } + defaultMaxListeners = arg; + } + }); + EventEmitter2.init = function() { + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + }; + EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n3) { + if (typeof n3 !== "number" || n3 < 0 || NumberIsNaN(n3)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n3 + "."); + } + this._maxListeners = n3; + return this; + }; + function _getMaxListeners(that) { + if (that._maxListeners === void 0) + return EventEmitter2.defaultMaxListeners; + return that._maxListeners; + } + EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; + EventEmitter2.prototype.emit = function emit(type) { + var args = []; + for (var i2 = 1; i2 < arguments.length; i2++) + args.push(arguments[i2]); + var doError = type === "error"; + var events = this._events; + if (events !== void 0) + doError = doError && events.error === void 0; + else if (!doError) + return false; + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + throw er; + } + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); + err.context = er; + throw err; + } + var handler = events[type]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i2 = 0; i2 < len; ++i2) + ReflectApply(listeners[i2], this, args); + } + return true; + }; + function _addListener(target, type, listener, prepend) { + var m3; + var events; + var existing; + checkListener(listener); + events = target._events; + if (events === void 0) { + events = target._events = /* @__PURE__ */ Object.create(null); + target._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + target.emit( + "newListener", + type, + listener.listener ? listener.listener : listener + ); + events = target._events; + } + existing = events[type]; + } + if (existing === void 0) { + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m3 = _getMaxListeners(target); + if (m3 > 0 && existing.length > m3 && !existing.warned) { + existing.warned = true; + var w4 = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w4.name = "MaxListenersExceededWarning"; + w4.emitter = target; + w4.type = type; + w4.count = existing.length; + ProcessEmitWarning(w4); + } + } + return target; + } + EventEmitter2.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; + EventEmitter2.prototype.prependListener = function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } + } + function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: void 0, target, type, listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + EventEmitter2.prototype.once = function once2(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + EventEmitter2.prototype.removeListener = function removeListener(type, listener) { + var list, events, position, i2, originalListener; + checkListener(listener); + events = this._events; + if (events === void 0) + return this; + list = events[type]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit("removeListener", type, list.listener || listener); + } + } else if (typeof list !== "function") { + position = -1; + for (i2 = list.length - 1; i2 >= 0; i2--) { + if (list[i2] === listener || list[i2].listener === listener) { + originalListener = list[i2].listener; + position = i2; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events[type] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type, originalListener || listener); + } + return this; + }; + EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; + EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { + var listeners, events, i2; + events = this._events; + if (events === void 0) + return this; + if (events.removeListener === void 0) { + if (arguments.length === 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type]; + } + return this; + } + if (arguments.length === 0) { + var keys2 = Object.keys(events); + var key; + for (i2 = 0; i2 < keys2.length; ++i2) { + key = keys2[i2]; + if (key === "removeListener") + continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return this; + } + listeners = events[type]; + if (typeof listeners === "function") { + this.removeListener(type, listeners); + } else if (listeners !== void 0) { + for (i2 = listeners.length - 1; i2 >= 0; i2--) { + this.removeListener(type, listeners[i2]); + } + } + return this; + }; + function _listeners(target, type, unwrap) { + var events = target._events; + if (events === void 0) + return []; + var evlistener = events[type]; + if (evlistener === void 0) + return []; + if (typeof evlistener === "function") + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + } + EventEmitter2.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; + EventEmitter2.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; + EventEmitter2.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } + }; + EventEmitter2.prototype.listenerCount = listenerCount; + function listenerCount(type) { + var events = this._events; + if (events !== void 0) { + var evlistener = events[type]; + if (typeof evlistener === "function") { + return 1; + } else if (evlistener !== void 0) { + return evlistener.length; + } + } + return 0; + } + EventEmitter2.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; + function arrayClone(arr, n3) { + var copy = new Array(n3); + for (var i2 = 0; i2 < n3; ++i2) + copy[i2] = arr[i2]; + return copy; + } + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i2 = 0; i2 < ret.length; ++i2) { + ret[i2] = arr[i2].listener || arr[i2]; + } + return ret; + } + function once(emitter, name2) { + return new Promise(function(resolve, reject) { + function errorListener(err) { + emitter.removeListener(name2, resolver); + reject(err); + } + function resolver() { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + resolve([].slice.call(arguments)); + } + ; + eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); + if (name2 !== "error") { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); + } + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === "function") { + eventTargetAgnosticAddListener(emitter, "error", handler, flags); + } + } + function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { + if (typeof emitter.on === "function") { + if (flags.once) { + emitter.once(name2, listener); + } else { + emitter.on(name2, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name2, function wrapListener(arg) { + if (flags.once) { + emitter.removeEventListener(name2, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/stream-browser.js +var require_stream_browser = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/stream-browser.js"(exports2, module2) { + init_shim(); + module2.exports = require_events().EventEmitter; + } +}); + +// node_modules/buffer/index.js +var require_buffer2 = __commonJS({ + "node_modules/buffer/index.js"(exports2) { + "use strict"; + init_shim(); + var base642 = require_base64_js(); + var ieee754 = require_ieee754(); + var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports2.Buffer = Buffer2; + exports2.SlowBuffer = SlowBuffer; + exports2.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports2.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e2) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.byteOffset; + } + }); + function createBuffer(length2) { + if (length2 > K_MAX_LENGTH) { + throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); + } + const buf = new Uint8Array(length2); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe2(arg); + } + return from3(arg, encodingOrOffset, length2); + } + Buffer2.poolSize = 8192; + function from3(value, encodingOrOffset, length2) { + if (typeof value === "string") { + return fromString3(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer2.from(valueOf, encodingOrOffset, length2); + } + const b4 = fromObject(value); + if (b4) + return b4; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length2); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + Buffer2.from = function(value, encodingOrOffset, length2) { + return from3(value, encodingOrOffset, length2); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe2(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe2(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe2(size); + }; + function fromString3(string2, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length2 = byteLength(string2, encoding) | 0; + let buf = createBuffer(length2); + const actual = buf.write(string2, encoding); + if (actual !== length2) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + const length2 = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length2); + for (let i2 = 0; i2 < length2; i2 += 1) { + buf[i2] = array[i2] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array, byteOffset, length2) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length2 || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length2 === void 0) { + buf = new Uint8Array(array); + } else if (length2 === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length2); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length2) { + if (length2 >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length2 | 0; + } + function SlowBuffer(length2) { + if (+length2 != length2) { + length2 = 0; + } + return Buffer2.alloc(+length2); + } + Buffer2.isBuffer = function isBuffer(b4) { + return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; + }; + Buffer2.compare = function compare3(a3, b4) { + if (isInstance(a3, Uint8Array)) + a3 = Buffer2.from(a3, a3.offset, a3.byteLength); + if (isInstance(b4, Uint8Array)) + b4 = Buffer2.from(b4, b4.offset, b4.byteLength); + if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a3 === b4) + return 0; + let x3 = a3.length; + let y4 = b4.length; + for (let i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { + if (a3[i2] !== b4[i2]) { + x3 = a3[i2]; + y4 = b4[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding) { + switch (String(encoding).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 true; + default: + return false; + } + }; + Buffer2.concat = function concat2(list, length2) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + let i2; + if (length2 === void 0) { + length2 = 0; + for (i2 = 0; i2 < list.length; ++i2) { + length2 += list[i2].length; + } + } + const buffer = Buffer2.allocUnsafe(length2); + let pos = 0; + for (i2 = 0; i2 < list.length; ++i2) { + let buf = list[i2]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer2.isBuffer(buf)) + buf = Buffer2.from(buf); + buf.copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer; + }; + function byteLength(string2, encoding) { + if (Buffer2.isBuffer(string2)) { + return string2.length; + } + if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { + return string2.byteLength; + } + if (typeof string2 !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 + ); + } + const len = string2.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) + return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string2).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string2).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string2).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength; + function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) + encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b4, n3, m3) { + const i2 = b4[n3]; + b4[n3] = b4[m3]; + b4[m3] = i2; + } + Buffer2.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i2 = 0; i2 < len; i2 += 2) { + swap(this, i2, i2 + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i2 = 0; i2 < len; i2 += 4) { + swap(this, i2, i2 + 3); + swap(this, i2 + 1, i2 + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i2 = 0; i2 < len; i2 += 8) { + swap(this, i2, i2 + 7); + swap(this, i2 + 1, i2 + 6); + swap(this, i2 + 2, i2 + 5); + swap(this, i2 + 3, i2 + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString3() { + const length2 = this.length; + if (length2 === 0) + return ""; + if (arguments.length === 0) + return utf8Slice(this, 0, length2); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals4(b4) { + if (!Buffer2.isBuffer(b4)) + throw new TypeError("Argument must be a Buffer"); + if (this === b4) + return true; + return Buffer2.compare(this, b4) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + let str = ""; + const max = exports2.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) + str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) + return 0; + let x3 = thisEnd - thisStart; + let y4 = end - start; + const len = Math.min(x3, y4); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i2 = 0; i2 < len; ++i2) { + if (thisCopy[i2] !== targetCopy[i2]) { + x3 = thisCopy[i2]; + y4 = targetCopy[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + if (buffer.length === 0) + return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer.length - 1; + } + if (byteOffset < 0) + byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) + return -1; + else + byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) + byteOffset = 0; + else + return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read2(buf, i3) { + if (indexSize === 1) { + return buf[i3]; + } else { + return buf.readUInt16BE(i3 * indexSize); + } + } + let i2; + if (dir) { + let foundIndex = -1; + for (i2 = byteOffset; i2 < arrLength; i2++) { + if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { + if (foundIndex === -1) + foundIndex = i2; + if (i2 - foundIndex + 1 === valLength) + return foundIndex * indexSize; + } else { + if (foundIndex !== -1) + i2 -= i2 - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength; + for (i2 = byteOffset; i2 >= 0; i2--) { + let found = true; + for (let j2 = 0; j2 < valLength; j2++) { + if (read2(arr, i2 + j2) !== read2(val, j2)) { + found = false; + break; + } + } + if (found) + return i2; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string2, offset, length2) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (!length2) { + length2 = remaining; + } else { + length2 = Number(length2); + if (length2 > remaining) { + length2 = remaining; + } + } + const strLen = string2.length; + if (length2 > strLen / 2) { + length2 = strLen / 2; + } + let i2; + for (i2 = 0; i2 < length2; ++i2) { + const parsed = parseInt(string2.substr(i2 * 2, 2), 16); + if (numberIsNaN(parsed)) + return i2; + buf[offset + i2] = parsed; + } + return i2; + } + function utf8Write(buf, string2, offset, length2) { + return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); + } + function asciiWrite(buf, string2, offset, length2) { + return blitBuffer(asciiToBytes(string2), buf, offset, length2); + } + function base64Write(buf, string2, offset, length2) { + return blitBuffer(base64ToBytes(string2), buf, offset, length2); + } + function ucs2Write(buf, string2, offset, length2) { + return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); + } + Buffer2.prototype.write = function write(string2, offset, length2, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length2 = this.length; + offset = 0; + } else if (length2 === void 0 && typeof offset === "string") { + encoding = offset; + length2 = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length2)) { + length2 = length2 >>> 0; + if (encoding === void 0) + encoding = "utf8"; + } else { + encoding = length2; + length2 = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset; + if (length2 === void 0 || length2 > remaining) + length2 = remaining; + if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) + encoding = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string2, offset, length2); + case "utf8": + case "utf-8": + return utf8Write(this, string2, offset, length2); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string2, offset, length2); + case "base64": + return base64Write(this, string2, offset, length2); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string2, offset, length2); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base642.fromByteArray(buf); + } else { + return base642.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i2 = start; + while (i2 < end) { + const firstByte = buf[i2]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i2 + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i2 + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + fourthByte = buf[i2 + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i2 += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i2 = 0; + while (i2 < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2]); + } + return ret; + } + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) + start = 0; + if (!end || end < 0 || end > len) + end = len; + let out = ""; + for (let i2 = start; i2 < end; ++i2) { + out += hexSliceLookupTable[buf[i2]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i2 = 0; i2 < bytes.length - 1; i2 += 2) { + res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) + start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) + end = 0; + } else if (end > len) { + end = len; + } + if (end < start) + end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset, ext, length2) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError("offset is not uint"); + if (offset + ext > length2) + throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength2, this.length); + } + let val = this[offset + --byteLength2]; + let mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset + --byteLength2] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; + const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); + }); + Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }); + Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let i2 = byteLength2; + let mul = 1; + let val = this[offset + --i2]; + while (i2 > 0 && (mul *= 256)) { + val += this[offset + --i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) + return this[offset]; + return (255 - this[offset] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + const val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + const val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); + }); + Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); + }); + Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer2.isBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let mul = 1; + let i2 = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let i2 = byteLength2 - 1; + let mul = 1; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + function wrtBigUInt64LE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset; + } + function wrtBigUInt64BE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8; + } + Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i2 = 0; + let mul = 1; + let sub = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i2 = byteLength2 - 1; + let mul = 1; + let sub = 0; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 127, -128); + if (value < 0) + value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + if (value < 0) + value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + if (offset < 0) + throw new RangeError("Index out of range"); + } + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + Buffer2.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) + throw new TypeError("argument should be a Buffer"); + if (!start) + start = 0; + if (!end && end !== 0) + end = this.length; + if (targetStart >= target.length) + targetStart = target.length; + if (!targetStart) + targetStart = 0; + if (end > 0 && end < start) + end = start; + if (end === start) + return 0; + if (target.length === 0 || this.length === 0) + return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) + throw new RangeError("Index out of range"); + if (end < 0) + throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) + end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code2 = val.charCodeAt(0); + if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { + val = code2; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) + val = 0; + let i2; + if (typeof val === "number") { + for (i2 = start; i2 < end; ++i2) { + this[i2] = val; + } + } else { + const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i2 = 0; i2 < end - start; ++i2) { + this[i2 + start] = bytes[i2 % len]; + } + } + return this; + }; + var errors = {}; + function E4(sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; + } + E4( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name2) { + if (name2) { + return `${name2} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E4( + "ERR_INVALID_ARG_TYPE", + function(name2, actual) { + return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E4( + "ERR_OUT_OF_RANGE", + function(str, range, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg += ` It must be ${range}. Received ${received}`; + return msg; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i2 = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i2 >= start + 4; i2 -= 3) { + res = `_${val.slice(i2 - 3, i2)}${res}`; + } + return `${val.slice(0, i2)}${res}`; + } + function checkBounds(buf, offset, byteLength2) { + validateNumber(offset, "offset"); + if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { + boundsError(offset, buf.length - (byteLength2 + 1)); + } + } + function checkIntBI(value, min, max, buf, offset, byteLength2) { + if (value > max || value < min) { + const n3 = typeof min === "bigint" ? "n" : ""; + let range; + if (byteLength2 > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n3} and < 2${n3} ** ${(byteLength2 + 1) * 8}${n3}`; + } else { + range = `>= -(2${n3} ** ${(byteLength2 + 1) * 8 - 1}${n3}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n3}`; + } + } else { + range = `>= ${min}${n3} and <= ${max}${n3}`; + } + throw new errors.ERR_OUT_OF_RANGE("value", range, value); + } + checkBounds(buf, offset, byteLength2); + } + function validateNumber(value, name2) { + if (typeof value !== "number") { + throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value); + } + } + function boundsError(value, length2, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); + } + if (length2 < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors.ERR_OUT_OF_RANGE( + type || "offset", + `>= ${type ? 1 : 0} and <= ${length2}`, + value + ); + } + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) + return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + function utf8ToBytes(string2, units) { + units = units || Infinity; + let codePoint; + const length2 = string2.length; + let leadSurrogate = null; + const bytes = []; + for (let i2 = 0; i2 < length2; ++i2) { + codePoint = string2.charCodeAt(i2); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } else if (i2 + 1 === length2) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) + break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) + break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) + break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) + break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str) { + const byteArray = []; + for (let i2 = 0; i2 < str.length; ++i2) { + byteArray.push(str.charCodeAt(i2) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + let c4, hi, lo; + const byteArray = []; + for (let i2 = 0; i2 < str.length; ++i2) { + if ((units -= 2) < 0) + break; + c4 = str.charCodeAt(i2); + hi = c4 >> 8; + lo = c4 % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base642.toByteArray(base64clean(str)); + } + function blitBuffer(src2, dst, offset, length2) { + let i2; + for (i2 = 0; i2 < length2; ++i2) { + if (i2 + offset >= dst.length || i2 >= src2.length) + break; + dst[i2 + offset] = src2[i2]; + } + return i2; + } + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + var hexSliceLookupTable = function() { + const alphabet2 = "0123456789abcdef"; + const table = new Array(256); + for (let i2 = 0; i2 < 16; ++i2) { + const i16 = i2 * 16; + for (let j2 = 0; j2 < 16; ++j2) { + table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; + } + } + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; + } + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); + } + } +}); + +// (disabled):node_modules/util/util.js +var require_util = __commonJS({ + "(disabled):node_modules/util/util.js"() { + init_shim(); + } +}); + +// node_modules/readable-stream/lib/internal/streams/buffer_list.js +var require_buffer_list = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { + "use strict"; + init_shim(); + function ownKeys(object, enumerableOnly) { + var keys2 = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys2.push.apply(keys2, symbols); + } + return keys2; + } + function _objectSpread(target) { + for (var i2 = 1; i2 < arguments.length; i2++) { + var source = null != arguments[i2] ? arguments[i2] : {}; + i2 % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i2 = 0; i2 < props.length; i2++) { + var descriptor = props[i2]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) + return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") + return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var _require = require_buffer2(); + var Buffer2 = _require.Buffer; + var _require2 = require_util(); + var inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src2, target, offset) { + Buffer2.prototype.copy.call(src2, target, offset); + } + module2.exports = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v2) { + var entry = { + data: v2, + next: null + }; + if (this.length > 0) + this.tail.next = entry; + else + this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v2) { + var entry = { + data: v2, + next: this.head + }; + if (this.length === 0) + this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) + return; + var ret = this.head.data; + if (this.length === 1) + this.head = this.tail = null; + else + this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear2() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s2) { + if (this.length === 0) + return ""; + var p3 = this.head; + var ret = "" + p3.data; + while (p3 = p3.next) + ret += s2 + p3.data; + return ret; + } + }, { + key: "concat", + value: function concat2(n3) { + if (this.length === 0) + return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n3 >>> 0); + var p3 = this.head; + var i2 = 0; + while (p3) { + copyBuffer(p3.data, ret, i2); + i2 += p3.data.length; + p3 = p3.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n3, hasStrings) { + var ret; + if (n3 < this.head.data.length) { + ret = this.head.data.slice(0, n3); + this.head.data = this.head.data.slice(n3); + } else if (n3 === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n3) : this._getBuffer(n3); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n3) { + var p3 = this.head; + var c4 = 1; + var ret = p3.data; + n3 -= ret.length; + while (p3 = p3.next) { + var str = p3.data; + var nb = n3 > str.length ? str.length : n3; + if (nb === str.length) + ret += str; + else + ret += str.slice(0, n3); + n3 -= nb; + if (n3 === 0) { + if (nb === str.length) { + ++c4; + if (p3.next) + this.head = p3.next; + else + this.head = this.tail = null; + } else { + this.head = p3; + p3.data = str.slice(nb); + } + break; + } + ++c4; + } + this.length -= c4; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n3) { + var ret = Buffer2.allocUnsafe(n3); + var p3 = this.head; + var c4 = 1; + p3.data.copy(ret); + n3 -= p3.data.length; + while (p3 = p3.next) { + var buf = p3.data; + var nb = n3 > buf.length ? buf.length : n3; + buf.copy(ret, ret.length - n3, 0, nb); + n3 -= nb; + if (n3 === 0) { + if (nb === buf.length) { + ++c4; + if (p3.next) + this.head = p3.next; + else + this.head = this.tail = null; + } else { + this.head = p3; + p3.data = buf.slice(nb); + } + break; + } + ++c4; + } + this.length -= c4; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_4, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + } +}); + +// node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { + "use strict"; + init_shim(); + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + import_process.default.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + import_process.default.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + import_process.default.nextTick(emitCloseNT, _this); + } + } else if (cb) { + import_process.default.nextTick(emitCloseNT, _this); + cb(err2); + } else { + import_process.default.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) + return; + if (self2._readableState && !self2._readableState.emitClose) + return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream, err) { + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) + stream.destroy(err); + else + stream.emit("error", err); + } + module2.exports = { + destroy, + undestroy, + errorOrDestroy + }; + } +}); + +// node_modules/readable-stream/errors-browser.js +var require_errors_browser = __commonJS({ + "node_modules/readable-stream/errors-browser.js"(exports2, module2) { + "use strict"; + init_shim(); + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; + } + var codes = {}; + function createErrorType(code2, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /* @__PURE__ */ function(_Base) { + _inheritsLoose(NodeError2, _Base); + function NodeError2(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + return NodeError2; + }(Base); + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code2; + codes[code2] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function(i2) { + return String(i2); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name2, value) { + return 'The value "' + value + '" is invalid for option "' + name2 + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) { + var determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + var msg; + if (endsWith(name2, " argument")) { + msg = "The ".concat(name2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } else { + var type = includes(name2, ".") ? "property" : "argument"; + msg = 'The "'.concat(name2, '" ').concat(type, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name2) { + return "The " + name2 + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name2) { + return "Cannot call " + name2 + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + module2.exports.codes = codes; + } +}); + +// node_modules/readable-stream/lib/internal/streams/state.js +var require_state = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { + "use strict"; + init_shim(); + var ERR_INVALID_OPT_VALUE = require_errors_browser().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name2 = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name2, hwm); + } + return Math.floor(hwm); + } + return state.objectMode ? 16 : 16 * 1024; + } + module2.exports = { + getHighWaterMark + }; + } +}); + +// node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/inherits/inherits_browser.js"(exports2, module2) { + init_shim(); + if (typeof Object.create === "function") { + module2.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module2.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + } +}); + +// node_modules/util-deprecate/browser.js +var require_browser2 = __commonJS({ + "node_modules/util-deprecate/browser.js"(exports2, module2) { + init_shim(); + module2.exports = deprecate2; + function deprecate2(fn, msg) { + if (config("noDeprecation")) { + return fn; + } + var warned = false; + function deprecated() { + if (!warned) { + if (config("throwDeprecation")) { + throw new Error(msg); + } else if (config("traceDeprecation")) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + return deprecated; + } + function config(name2) { + try { + if (!global.localStorage) + return false; + } catch (_4) { + return false; + } + var val = global.localStorage[name2]; + if (null == val) + return false; + return String(val).toLowerCase() === "true"; + } + } +}); + +// node_modules/readable-stream/lib/_stream_writable.js +var require_stream_writable = __commonJS({ + "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Writable; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: require_browser2() + }; + var Stream = require_stream_browser(); + var Buffer2 = require_buffer2().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors_browser().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; + var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; + var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + require_inherits_browser()(Writable, Stream); + function nop() { + } + function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") + isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_4) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) + return true; + if (this !== Writable) + return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) + return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + this.writable = true; + if (options) { + if (typeof options.write === "function") + this._write = options.write; + if (typeof options.writev === "function") + this._writev = options.writev; + if (typeof options.destroy === "function") + this._destroy = options.destroy; + if (typeof options.final === "function") + this._final = options.final; + } + Stream.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream, er); + import_process.default.nextTick(cb, er); + } + function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream, er); + import_process.default.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (isBuf) + encoding = "buffer"; + else if (!encoding) + encoding = state.defaultEncoding; + if (typeof cb !== "function") + cb = nop; + if (state.ending) + writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) + clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") + encoding = encoding.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) + throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + if (!ret) + state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) + state.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + import_process.default.nextTick(cb, er); + import_process.default.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + finishMaybe(stream, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== "function") + throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) + onwriteError(stream, state, sync, er, cb); + else { + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + import_process.default.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit("drain"); + } + } + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + var l4 = state.bufferedRequestCount; + var buffer = new Array(l4); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) + allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, "", holder.finish); + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + if (state.writing) { + break; + } + } + if (entry === null) + state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) + this.write(chunk, encoding); + if (state.corked) { + state.corked = 1; + this.uncork(); + } + if (!state.ending) + endWritable(this, state, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function(err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit("prefinish"); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === "function" && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + import_process.default.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit("prefinish"); + } + } + } + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit("finish"); + if (state.autoDestroy) { + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; + } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + import_process.default.nextTick(cb); + else + stream.once("finish", cb); + } + state.ended = true; + stream.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set2(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + } +}); + +// node_modules/readable-stream/lib/_stream_duplex.js +var require_stream_duplex = __commonJS({ + "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { + "use strict"; + init_shim(); + var objectKeys = Object.keys || function(obj) { + var keys3 = []; + for (var key in obj) + keys3.push(key); + return keys3; + }; + module2.exports = Duplex; + var Readable = require_stream_readable(); + var Writable = require_stream_writable(); + require_inherits_browser()(Duplex, Readable); + { + keys2 = objectKeys(Writable.prototype); + for (v2 = 0; v2 < keys2.length; v2++) { + method = keys2[v2]; + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; + } + } + var keys2; + var method; + var v2; + function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) + this.readable = false; + if (options.writable === false) + this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) + return; + import_process.default.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set2(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + } +}); + +// node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/safe-buffer/index.js"(exports2, module2) { + init_shim(); + var buffer = require_buffer2(); + var Buffer2 = buffer.Buffer; + function copyProps(src2, dst) { + for (var key in src2) { + dst[key] = src2[key]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module2.exports = buffer; + } else { + copyProps(buffer, exports2); + exports2.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length2) { + return Buffer2(arg, encodingOrOffset, length2); + } + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length2); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer.SlowBuffer(size); + }; + } +}); + +// node_modules/string_decoder/lib/string_decoder.js +var require_string_decoder = __commonJS({ + "node_modules/string_decoder/lib/string_decoder.js"(exports2) { + "use strict"; + init_shim(); + var Buffer2 = require_safe_buffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _normalizeEncoding(enc) { + if (!enc) + return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) + return; + enc = ("" + enc).toLowerCase(); + retried = true; + } + } + } + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) + throw new Error("Unknown encoding: " + enc); + return nenc || enc; + } + exports2.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); + } + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) + return ""; + var r; + var i2; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === void 0) + return ""; + i2 = this.lastNeed; + this.lastNeed = 0; + } else { + i2 = 0; + } + if (i2 < buf.length) + return r ? r + this.text(buf, i2) : this.text(buf, i2); + return r || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + function utf8CheckByte(byte) { + if (byte <= 127) + return 0; + else if (byte >> 5 === 6) + return 2; + else if (byte >> 4 === 14) + return 3; + else if (byte >> 3 === 30) + return 4; + return byte >> 6 === 2 ? -1 : -2; + } + function utf8CheckIncomplete(self2, buf, i2) { + var j2 = buf.length - 1; + if (j2 < i2) + return 0; + var nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) + self2.lastNeed = nb - 1; + return nb; + } + if (--j2 < i2 || nb === -2) + return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) + self2.lastNeed = nb - 2; + return nb; + } + if (--j2 < i2 || nb === -2) + return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) + nb = 0; + else + self2.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + function utf8CheckExtraBytes(self2, buf, p3) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "\uFFFD"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "\uFFFD"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "\uFFFD"; + } + } + } + } + function utf8FillLast(buf) { + var p3 = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p3); + if (r !== void 0) + return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p3, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p3, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i2) { + var total = utf8CheckIncomplete(this, buf, i2); + if (!this.lastNeed) + return buf.toString("utf8", i2); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i2, end); + } + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) + return r + "\uFFFD"; + return r; + } + function utf16Text(buf, i2) { + if ((buf.length - i2) % 2 === 0) { + var r = buf.toString("utf16le", i2); + if (r) { + var c4 = r.charCodeAt(r.length - 1); + if (c4 >= 55296 && c4 <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i2, buf.length - 1); + } + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); + } + return r; + } + function base64Text(buf, i2) { + var n3 = (buf.length - i2) % 3; + if (n3 === 0) + return buf.toString("base64", i2); + this.lastNeed = 3 - n3; + this.lastTotal = 3; + if (n3 === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i2, buf.length - n3); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) + return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/end-of-stream.js +var require_end_of_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { + "use strict"; + init_shim(); + var ERR_STREAM_PREMATURE_CLOSE = require_errors_browser().codes.ERR_STREAM_PREMATURE_CLOSE; + function once(callback) { + var called = false; + return function() { + if (called) + return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop() { + } + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + function eos(stream, opts, callback) { + if (typeof opts === "function") + return eos(stream, null, opts); + if (!opts) + opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream.writable) + onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish2() { + writable = false; + writableEnded = true; + if (!readable) + callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend2() { + readable = false; + readableEnded = true; + if (!writable) + callback.call(stream); + }; + var onerror = function onerror2(err) { + callback.call(stream, err); + }; + var onclose = function onclose2() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) + err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) + err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest2() { + stream.req.on("finish", onfinish); + }; + if (isRequest(stream)) { + stream.on("complete", onfinish); + stream.on("abort", onclose); + if (stream.req) + onrequest(); + else + stream.on("request", onrequest); + } else if (writable && !stream._writableState) { + stream.on("end", onlegacyfinish); + stream.on("close", onlegacyfinish); + } + stream.on("end", onend); + stream.on("finish", onfinish); + if (opts.error !== false) + stream.on("error", onerror); + stream.on("close", onclose); + return function() { + stream.removeListener("complete", onfinish); + stream.removeListener("abort", onclose); + stream.removeListener("request", onrequest); + if (stream.req) + stream.req.removeListener("finish", onfinish); + stream.removeListener("end", onlegacyfinish); + stream.removeListener("close", onlegacyfinish); + stream.removeListener("finish", onfinish); + stream.removeListener("end", onend); + stream.removeListener("error", onerror); + stream.removeListener("close", onclose); + }; + } + module2.exports = eos; + } +}); + +// node_modules/readable-stream/lib/internal/streams/async_iterator.js +var require_async_iterator = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { + "use strict"; + init_shim(); + var _Object$setPrototypeO; + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) + return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") + return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = require_end_of_stream(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + function onReadable(iter) { + import_process.default.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + import_process.default.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator[kLastReject]; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(void 0, true)); + } + iterator[kEnded] = true; + }); + stream.on("readable", onReadable.bind(null, iterator)); + return iterator; + }; + module2.exports = createReadableStreamAsyncIterator; + } +}); + +// node_modules/readable-stream/lib/internal/streams/from-browser.js +var require_from_browser = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/from-browser.js"(exports2, module2) { + init_shim(); + module2.exports = function() { + throw new Error("Readable.from is not available in the browser"); + }; + } +}); + +// node_modules/readable-stream/lib/_stream_readable.js +var require_stream_readable = __commonJS({ + "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Readable; + var Duplex; + Readable.ReadableState = ReadableState; + var EE = require_events().EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type) { + return emitter.listeners(type).length; + }; + var Stream = require_stream_browser(); + var Buffer2 = require_buffer2().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = require_util(); + var debug; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function debug2() { + }; + } + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors_browser().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from3; + require_inherits_browser()(Readable, Stream); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") + return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") + isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require_string_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable)) + return new Readable(options); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + this.readable = true; + if (options) { + if (typeof options.read === "function") + this._read = options.read; + if (typeof options.destroy === "function") + this._destroy = options.destroy; + } + Stream.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set2(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug("readableAddChunk", chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) + er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) + errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else + addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) + addChunk(stream, state, chunk, false); + else + maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit("data", chunk); + } else { + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) + state.buffer.unshift(chunk); + else + state.buffer.push(chunk); + if (state.needReadable) + emitReadable(stream); + } + maybeReadMore(stream, state); + } + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require_string_decoder().StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + this._readableState.encoding = this._readableState.decoder.encoding; + var p3 = this._readableState.buffer.head; + var content = ""; + while (p3 !== null) { + content += decoder.write(p3.data); + p3 = p3.next; + } + this._readableState.buffer.clear(); + if (content !== "") + this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n3) { + if (n3 >= MAX_HWM) { + n3 = MAX_HWM; + } else { + n3--; + n3 |= n3 >>> 1; + n3 |= n3 >>> 2; + n3 |= n3 >>> 4; + n3 |= n3 >>> 8; + n3 |= n3 >>> 16; + n3++; + } + return n3; + } + function howMuchToRead(n3, state) { + if (n3 <= 0 || state.length === 0 && state.ended) + return 0; + if (state.objectMode) + return 1; + if (n3 !== n3) { + if (state.flowing && state.length) + return state.buffer.head.data.length; + else + return state.length; + } + if (n3 > state.highWaterMark) + state.highWaterMark = computeNewHighWaterMark(n3); + if (n3 <= state.length) + return n3; + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + Readable.prototype.read = function(n3) { + debug("read", n3); + n3 = parseInt(n3, 10); + var state = this._readableState; + var nOrig = n3; + if (n3 !== 0) + state.emittedReadable = false; + if (n3 === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) + endReadable(this); + else + emitReadable(this); + return null; + } + n3 = howMuchToRead(n3, state); + if (n3 === 0 && state.ended) { + if (state.length === 0) + endReadable(this); + return null; + } + var doRead = state.needReadable; + debug("need readable", doRead); + if (state.length === 0 || state.length - n3 < state.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + if (state.length === 0) + state.needReadable = true; + this._read(state.highWaterMark); + state.sync = false; + if (!state.reading) + n3 = howMuchToRead(nOrig, state); + } + var ret; + if (n3 > 0) + ret = fromList(n3, state); + else + ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n3 = 0; + } else { + state.length -= n3; + state.awaitDrain = 0; + } + if (state.length === 0) { + if (!state.ended) + state.needReadable = true; + if (nOrig !== n3 && state.ended) + endReadable(this); + } + if (ret !== null) + this.emit("data", ret); + return ret; + }; + function onEofChunk(stream, state) { + debug("onEofChunk"); + if (state.ended) + return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + emitReadable(stream); + } else { + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } + function emitReadable(stream) { + var state = stream._readableState; + debug("emitReadable", state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + import_process.default.nextTick(emitReadable_, stream); + } + } + function emitReadable_(stream) { + var state = stream._readableState; + debug("emitReadable_", state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit("readable"); + state.emittedReadable = false; + } + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + import_process.default.nextTick(maybeReadMore_, stream, state); + } + } + function maybeReadMore_(stream, state) { + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug("maybeReadMore read 0"); + stream.read(0); + if (len === state.length) + break; + } + state.readingMore = false; + } + Readable.prototype._read = function(n3) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src2 = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== import_process.default.stdout && dest !== import_process.default.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) + import_process.default.nextTick(endFn); + else + src2.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src2) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src2); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src2.removeListener("end", onend); + src2.removeListener("end", unpipe); + src2.removeListener("data", ondata); + cleanedUp = true; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) + ondrain(); + } + src2.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + var ret = dest.write(chunk); + debug("dest.write", ret); + if (ret === false) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state.awaitDrain); + state.awaitDrain++; + } + src2.pause(); + } + } + function onerror(er) { + debug("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) + errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src2.unpipe(dest); + } + dest.emit("pipe", src2); + if (!state.flowing) { + debug("pipe resume"); + src2.resume(); + } + return dest; + }; + function pipeOnDrain(src2) { + return function pipeOnDrainFunctionResult() { + var state = src2._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src2, "data")) { + state.flowing = true; + flow(src2); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state.pipesCount === 0) + return this; + if (state.pipesCount === 1) { + if (dest && dest !== state.pipes) + return this; + if (!dest) + dest = state.pipes; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) + dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i2 = 0; i2 < len; i2++) + dests[i2].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index = indexOf(state.pipes, dest); + if (index === -1) + return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === "data") { + state.readableListening = this.listenerCount("readable") > 0; + if (state.flowing !== false) + this.resume(); + } else if (ev === "readable") { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug("on readable", state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + import_process.default.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + import_process.default.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.removeAllListeners = function(ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + import_process.default.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state = self2._readableState; + state.readableListening = self2.listenerCount("readable") > 0; + if (state.resumeScheduled && !state.paused) { + state.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + import_process.default.nextTick(resume_, stream, state); + } + } + function resume_(stream, state) { + debug("resume", state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit("resume"); + flow(stream); + if (state.flowing && !state.reading) + stream.read(0); + } + Readable.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream) { + var state = stream._readableState; + debug("flow", state.flowing); + while (state.flowing && stream.read() !== null) + ; + } + Readable.prototype.wrap = function(stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + _this.push(chunk); + } + _this.push(null); + }); + stream.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (state.objectMode && (chunk === null || chunk === void 0)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + for (var i2 in stream) { + if (this[i2] === void 0 && typeof stream[i2] === "function") { + this[i2] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i2); + } + } + for (var n3 = 0; n3 < kProxyEvents.length; n3++) { + stream.on(kProxyEvents[n3], this.emit.bind(this, kProxyEvents[n3])); + } + this._read = function(n4) { + debug("wrapped _read", n4); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = require_async_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.flowing; + }, + set: function set2(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.length; + } + }); + function fromList(n3, state) { + if (state.length === 0) + return null; + var ret; + if (state.objectMode) + ret = state.buffer.shift(); + else if (!n3 || n3 >= state.length) { + if (state.decoder) + ret = state.buffer.join(""); + else if (state.buffer.length === 1) + ret = state.buffer.first(); + else + ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + ret = state.buffer.consume(n3, state.decoder); + } + return ret; + } + function endReadable(stream) { + var state = stream._readableState; + debug("endReadable", state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + import_process.default.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + debug("endReadableNT", state.endEmitted, state.length); + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit("end"); + if (state.autoDestroy) { + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable.from = function(iterable, opts) { + if (from3 === void 0) { + from3 = require_from_browser(); + } + return from3(Readable, iterable, opts); + }; + } + function indexOf(xs, x3) { + for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { + if (xs[i2] === x3) + return i2; + } + return -1; + } + } +}); + +// node_modules/readable-stream/lib/_stream_transform.js +var require_stream_transform = __commonJS({ + "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Transform; + var _require$codes = require_errors_browser().codes; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; + var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + require_inherits_browser()(Transform, Duplex); + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") + this._transform = options.transform; + if (typeof options.flush === "function") + this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n3) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream, er, data) { + if (er) + return stream.emit("error", er); + if (data != null) + stream.push(data); + if (stream._writableState.length) + throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) + throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + } +}); + +// node_modules/readable-stream/lib/_stream_passthrough.js +var require_stream_passthrough = __commonJS({ + "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = PassThrough; + var Transform = require_stream_transform(); + require_inherits_browser()(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { + "use strict"; + init_shim(); + var eos; + function once(callback) { + var called = false; + return function() { + if (called) + return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = require_errors_browser().codes; + var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop(err) { + if (err) + throw err; + } + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on("close", function() { + closed = true; + }); + if (eos === void 0) + eos = require_end_of_stream(); + eos(stream, { + readable: reading, + writable: writing + }, function(err) { + if (err) + return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) + return; + if (destroyed) + return; + destroyed = true; + if (isRequest(stream)) + return stream.abort(); + if (typeof stream.destroy === "function") + return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe(from3, to) { + return from3.pipe(to); + } + function popCallback(streams) { + if (!streams.length) + return noop; + if (typeof streams[streams.length - 1] !== "function") + return noop; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) + streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error; + var destroys = streams.map(function(stream, i2) { + var reading = i2 < streams.length - 1; + var writing = i2 > 0; + return destroyer(stream, reading, writing, function(err) { + if (!error) + error = err; + if (err) + destroys.forEach(call); + if (reading) + return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + module2.exports = pipeline; + } +}); + +// node_modules/readable-stream/readable-browser.js +var require_readable_browser = __commonJS({ + "node_modules/readable-stream/readable-browser.js"(exports2, module2) { + init_shim(); + exports2 = module2.exports = require_stream_readable(); + exports2.Stream = exports2; + exports2.Readable = exports2; + exports2.Writable = require_stream_writable(); + exports2.Duplex = require_stream_duplex(); + exports2.Transform = require_stream_transform(); + exports2.PassThrough = require_stream_passthrough(); + exports2.finished = require_end_of_stream(); + exports2.pipeline = require_pipeline(); + } +}); + +// node_modules/keccak/lib/api/keccak.js +var require_keccak = __commonJS({ + "node_modules/keccak/lib/api/keccak.js"(exports2, module2) { + init_shim(); + var { Transform } = require_readable_browser(); + module2.exports = (KeccakState) => class Keccak extends Transform { + constructor(rate, capacity, delimitedSuffix, hashBitLength, options) { + super(options); + this._rate = rate; + this._capacity = capacity; + this._delimitedSuffix = delimitedSuffix; + this._hashBitLength = hashBitLength; + this._options = options; + this._state = new KeccakState(); + this._state.initialize(rate, capacity); + this._finalized = false; + } + _transform(chunk, encoding, callback) { + let error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + callback(error); + } + _flush(callback) { + let error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } + callback(error); + } + update(data, encoding) { + if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") + throw new TypeError("Data must be a string or a buffer"); + if (this._finalized) + throw new Error("Digest already called"); + if (!import_buffer.Buffer.isBuffer(data)) + data = import_buffer.Buffer.from(data, encoding); + this._state.absorb(data); + return this; + } + digest(encoding) { + if (this._finalized) + throw new Error("Digest already called"); + this._finalized = true; + if (this._delimitedSuffix) + this._state.absorbLastFewBits(this._delimitedSuffix); + let digest2 = this._state.squeeze(this._hashBitLength / 8); + if (encoding !== void 0) + digest2 = digest2.toString(encoding); + this._resetState(); + return digest2; + } + // remove result from memory + _resetState() { + this._state.initialize(this._rate, this._capacity); + return this; + } + // because sometimes we need hash right now and little later + _clone() { + const clone2 = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options); + this._state.copy(clone2._state); + clone2._finalized = this._finalized; + return clone2; + } + }; + } +}); + +// node_modules/keccak/lib/api/shake.js +var require_shake = __commonJS({ + "node_modules/keccak/lib/api/shake.js"(exports2, module2) { + init_shim(); + var { Transform } = require_readable_browser(); + module2.exports = (KeccakState) => class Shake extends Transform { + constructor(rate, capacity, delimitedSuffix, options) { + super(options); + this._rate = rate; + this._capacity = capacity; + this._delimitedSuffix = delimitedSuffix; + this._options = options; + this._state = new KeccakState(); + this._state.initialize(rate, capacity); + this._finalized = false; + } + _transform(chunk, encoding, callback) { + let error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + callback(error); + } + _flush() { + } + _read(size) { + this.push(this.squeeze(size)); + } + update(data, encoding) { + if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") + throw new TypeError("Data must be a string or a buffer"); + if (this._finalized) + throw new Error("Squeeze already called"); + if (!import_buffer.Buffer.isBuffer(data)) + data = import_buffer.Buffer.from(data, encoding); + this._state.absorb(data); + return this; + } + squeeze(dataByteLength, encoding) { + if (!this._finalized) { + this._finalized = true; + this._state.absorbLastFewBits(this._delimitedSuffix); + } + let data = this._state.squeeze(dataByteLength); + if (encoding !== void 0) + data = data.toString(encoding); + return data; + } + _resetState() { + this._state.initialize(this._rate, this._capacity); + return this; + } + _clone() { + const clone2 = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options); + this._state.copy(clone2._state); + clone2._finalized = this._finalized; + return clone2; + } + }; + } +}); + +// node_modules/keccak/lib/api/index.js +var require_api = __commonJS({ + "node_modules/keccak/lib/api/index.js"(exports2, module2) { + init_shim(); + var createKeccak = require_keccak(); + var createShake = require_shake(); + module2.exports = function(KeccakState) { + const Keccak = createKeccak(KeccakState); + const Shake = createShake(KeccakState); + return function(algorithm, options) { + const hash = typeof algorithm === "string" ? algorithm.toLowerCase() : algorithm; + switch (hash) { + case "keccak224": + return new Keccak(1152, 448, null, 224, options); + case "keccak256": + return new Keccak(1088, 512, null, 256, options); + case "keccak384": + return new Keccak(832, 768, null, 384, options); + case "keccak512": + return new Keccak(576, 1024, null, 512, options); + case "sha3-224": + return new Keccak(1152, 448, 6, 224, options); + case "sha3-256": + return new Keccak(1088, 512, 6, 256, options); + case "sha3-384": + return new Keccak(832, 768, 6, 384, options); + case "sha3-512": + return new Keccak(576, 1024, 6, 512, options); + case "shake128": + return new Shake(1344, 256, 31, options); + case "shake256": + return new Shake(1088, 512, 31, options); + default: + throw new Error("Invald algorithm: " + algorithm); + } + }; + }; + } +}); + +// node_modules/keccak/lib/keccak-state-unroll.js +var require_keccak_state_unroll = __commonJS({ + "node_modules/keccak/lib/keccak-state-unroll.js"(exports2) { + init_shim(); + var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + exports2.p1600 = function(s2) { + for (let round = 0; round < 24; ++round) { + const lo0 = s2[0] ^ s2[10] ^ s2[20] ^ s2[30] ^ s2[40]; + const hi0 = s2[1] ^ s2[11] ^ s2[21] ^ s2[31] ^ s2[41]; + const lo1 = s2[2] ^ s2[12] ^ s2[22] ^ s2[32] ^ s2[42]; + const hi1 = s2[3] ^ s2[13] ^ s2[23] ^ s2[33] ^ s2[43]; + const lo2 = s2[4] ^ s2[14] ^ s2[24] ^ s2[34] ^ s2[44]; + const hi2 = s2[5] ^ s2[15] ^ s2[25] ^ s2[35] ^ s2[45]; + const lo3 = s2[6] ^ s2[16] ^ s2[26] ^ s2[36] ^ s2[46]; + const hi3 = s2[7] ^ s2[17] ^ s2[27] ^ s2[37] ^ s2[47]; + const lo4 = s2[8] ^ s2[18] ^ s2[28] ^ s2[38] ^ s2[48]; + const hi4 = s2[9] ^ s2[19] ^ s2[29] ^ s2[39] ^ s2[49]; + let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31); + let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31); + const t1slo0 = s2[0] ^ lo; + const t1shi0 = s2[1] ^ hi; + const t1slo5 = s2[10] ^ lo; + const t1shi5 = s2[11] ^ hi; + const t1slo10 = s2[20] ^ lo; + const t1shi10 = s2[21] ^ hi; + const t1slo15 = s2[30] ^ lo; + const t1shi15 = s2[31] ^ hi; + const t1slo20 = s2[40] ^ lo; + const t1shi20 = s2[41] ^ hi; + lo = lo0 ^ (lo2 << 1 | hi2 >>> 31); + hi = hi0 ^ (hi2 << 1 | lo2 >>> 31); + const t1slo1 = s2[2] ^ lo; + const t1shi1 = s2[3] ^ hi; + const t1slo6 = s2[12] ^ lo; + const t1shi6 = s2[13] ^ hi; + const t1slo11 = s2[22] ^ lo; + const t1shi11 = s2[23] ^ hi; + const t1slo16 = s2[32] ^ lo; + const t1shi16 = s2[33] ^ hi; + const t1slo21 = s2[42] ^ lo; + const t1shi21 = s2[43] ^ hi; + lo = lo1 ^ (lo3 << 1 | hi3 >>> 31); + hi = hi1 ^ (hi3 << 1 | lo3 >>> 31); + const t1slo2 = s2[4] ^ lo; + const t1shi2 = s2[5] ^ hi; + const t1slo7 = s2[14] ^ lo; + const t1shi7 = s2[15] ^ hi; + const t1slo12 = s2[24] ^ lo; + const t1shi12 = s2[25] ^ hi; + const t1slo17 = s2[34] ^ lo; + const t1shi17 = s2[35] ^ hi; + const t1slo22 = s2[44] ^ lo; + const t1shi22 = s2[45] ^ hi; + lo = lo2 ^ (lo4 << 1 | hi4 >>> 31); + hi = hi2 ^ (hi4 << 1 | lo4 >>> 31); + const t1slo3 = s2[6] ^ lo; + const t1shi3 = s2[7] ^ hi; + const t1slo8 = s2[16] ^ lo; + const t1shi8 = s2[17] ^ hi; + const t1slo13 = s2[26] ^ lo; + const t1shi13 = s2[27] ^ hi; + const t1slo18 = s2[36] ^ lo; + const t1shi18 = s2[37] ^ hi; + const t1slo23 = s2[46] ^ lo; + const t1shi23 = s2[47] ^ hi; + lo = lo3 ^ (lo0 << 1 | hi0 >>> 31); + hi = hi3 ^ (hi0 << 1 | lo0 >>> 31); + const t1slo4 = s2[8] ^ lo; + const t1shi4 = s2[9] ^ hi; + const t1slo9 = s2[18] ^ lo; + const t1shi9 = s2[19] ^ hi; + const t1slo14 = s2[28] ^ lo; + const t1shi14 = s2[29] ^ hi; + const t1slo19 = s2[38] ^ lo; + const t1shi19 = s2[39] ^ hi; + const t1slo24 = s2[48] ^ lo; + const t1shi24 = s2[49] ^ hi; + const t2slo0 = t1slo0; + const t2shi0 = t1shi0; + const t2slo16 = t1shi5 << 4 | t1slo5 >>> 28; + const t2shi16 = t1slo5 << 4 | t1shi5 >>> 28; + const t2slo7 = t1slo10 << 3 | t1shi10 >>> 29; + const t2shi7 = t1shi10 << 3 | t1slo10 >>> 29; + const t2slo23 = t1shi15 << 9 | t1slo15 >>> 23; + const t2shi23 = t1slo15 << 9 | t1shi15 >>> 23; + const t2slo14 = t1slo20 << 18 | t1shi20 >>> 14; + const t2shi14 = t1shi20 << 18 | t1slo20 >>> 14; + const t2slo10 = t1slo1 << 1 | t1shi1 >>> 31; + const t2shi10 = t1shi1 << 1 | t1slo1 >>> 31; + const t2slo1 = t1shi6 << 12 | t1slo6 >>> 20; + const t2shi1 = t1slo6 << 12 | t1shi6 >>> 20; + const t2slo17 = t1slo11 << 10 | t1shi11 >>> 22; + const t2shi17 = t1shi11 << 10 | t1slo11 >>> 22; + const t2slo8 = t1shi16 << 13 | t1slo16 >>> 19; + const t2shi8 = t1slo16 << 13 | t1shi16 >>> 19; + const t2slo24 = t1slo21 << 2 | t1shi21 >>> 30; + const t2shi24 = t1shi21 << 2 | t1slo21 >>> 30; + const t2slo20 = t1shi2 << 30 | t1slo2 >>> 2; + const t2shi20 = t1slo2 << 30 | t1shi2 >>> 2; + const t2slo11 = t1slo7 << 6 | t1shi7 >>> 26; + const t2shi11 = t1shi7 << 6 | t1slo7 >>> 26; + const t2slo2 = t1shi12 << 11 | t1slo12 >>> 21; + const t2shi2 = t1slo12 << 11 | t1shi12 >>> 21; + const t2slo18 = t1slo17 << 15 | t1shi17 >>> 17; + const t2shi18 = t1shi17 << 15 | t1slo17 >>> 17; + const t2slo9 = t1shi22 << 29 | t1slo22 >>> 3; + const t2shi9 = t1slo22 << 29 | t1shi22 >>> 3; + const t2slo5 = t1slo3 << 28 | t1shi3 >>> 4; + const t2shi5 = t1shi3 << 28 | t1slo3 >>> 4; + const t2slo21 = t1shi8 << 23 | t1slo8 >>> 9; + const t2shi21 = t1slo8 << 23 | t1shi8 >>> 9; + const t2slo12 = t1slo13 << 25 | t1shi13 >>> 7; + const t2shi12 = t1shi13 << 25 | t1slo13 >>> 7; + const t2slo3 = t1slo18 << 21 | t1shi18 >>> 11; + const t2shi3 = t1shi18 << 21 | t1slo18 >>> 11; + const t2slo19 = t1shi23 << 24 | t1slo23 >>> 8; + const t2shi19 = t1slo23 << 24 | t1shi23 >>> 8; + const t2slo15 = t1slo4 << 27 | t1shi4 >>> 5; + const t2shi15 = t1shi4 << 27 | t1slo4 >>> 5; + const t2slo6 = t1slo9 << 20 | t1shi9 >>> 12; + const t2shi6 = t1shi9 << 20 | t1slo9 >>> 12; + const t2slo22 = t1shi14 << 7 | t1slo14 >>> 25; + const t2shi22 = t1slo14 << 7 | t1shi14 >>> 25; + const t2slo13 = t1slo19 << 8 | t1shi19 >>> 24; + const t2shi13 = t1shi19 << 8 | t1slo19 >>> 24; + const t2slo4 = t1slo24 << 14 | t1shi24 >>> 18; + const t2shi4 = t1shi24 << 14 | t1slo24 >>> 18; + s2[0] = t2slo0 ^ ~t2slo1 & t2slo2; + s2[1] = t2shi0 ^ ~t2shi1 & t2shi2; + s2[10] = t2slo5 ^ ~t2slo6 & t2slo7; + s2[11] = t2shi5 ^ ~t2shi6 & t2shi7; + s2[20] = t2slo10 ^ ~t2slo11 & t2slo12; + s2[21] = t2shi10 ^ ~t2shi11 & t2shi12; + s2[30] = t2slo15 ^ ~t2slo16 & t2slo17; + s2[31] = t2shi15 ^ ~t2shi16 & t2shi17; + s2[40] = t2slo20 ^ ~t2slo21 & t2slo22; + s2[41] = t2shi20 ^ ~t2shi21 & t2shi22; + s2[2] = t2slo1 ^ ~t2slo2 & t2slo3; + s2[3] = t2shi1 ^ ~t2shi2 & t2shi3; + s2[12] = t2slo6 ^ ~t2slo7 & t2slo8; + s2[13] = t2shi6 ^ ~t2shi7 & t2shi8; + s2[22] = t2slo11 ^ ~t2slo12 & t2slo13; + s2[23] = t2shi11 ^ ~t2shi12 & t2shi13; + s2[32] = t2slo16 ^ ~t2slo17 & t2slo18; + s2[33] = t2shi16 ^ ~t2shi17 & t2shi18; + s2[42] = t2slo21 ^ ~t2slo22 & t2slo23; + s2[43] = t2shi21 ^ ~t2shi22 & t2shi23; + s2[4] = t2slo2 ^ ~t2slo3 & t2slo4; + s2[5] = t2shi2 ^ ~t2shi3 & t2shi4; + s2[14] = t2slo7 ^ ~t2slo8 & t2slo9; + s2[15] = t2shi7 ^ ~t2shi8 & t2shi9; + s2[24] = t2slo12 ^ ~t2slo13 & t2slo14; + s2[25] = t2shi12 ^ ~t2shi13 & t2shi14; + s2[34] = t2slo17 ^ ~t2slo18 & t2slo19; + s2[35] = t2shi17 ^ ~t2shi18 & t2shi19; + s2[44] = t2slo22 ^ ~t2slo23 & t2slo24; + s2[45] = t2shi22 ^ ~t2shi23 & t2shi24; + s2[6] = t2slo3 ^ ~t2slo4 & t2slo0; + s2[7] = t2shi3 ^ ~t2shi4 & t2shi0; + s2[16] = t2slo8 ^ ~t2slo9 & t2slo5; + s2[17] = t2shi8 ^ ~t2shi9 & t2shi5; + s2[26] = t2slo13 ^ ~t2slo14 & t2slo10; + s2[27] = t2shi13 ^ ~t2shi14 & t2shi10; + s2[36] = t2slo18 ^ ~t2slo19 & t2slo15; + s2[37] = t2shi18 ^ ~t2shi19 & t2shi15; + s2[46] = t2slo23 ^ ~t2slo24 & t2slo20; + s2[47] = t2shi23 ^ ~t2shi24 & t2shi20; + s2[8] = t2slo4 ^ ~t2slo0 & t2slo1; + s2[9] = t2shi4 ^ ~t2shi0 & t2shi1; + s2[18] = t2slo9 ^ ~t2slo5 & t2slo6; + s2[19] = t2shi9 ^ ~t2shi5 & t2shi6; + s2[28] = t2slo14 ^ ~t2slo10 & t2slo11; + s2[29] = t2shi14 ^ ~t2shi10 & t2shi11; + s2[38] = t2slo19 ^ ~t2slo15 & t2slo16; + s2[39] = t2shi19 ^ ~t2shi15 & t2shi16; + s2[48] = t2slo24 ^ ~t2slo20 & t2slo21; + s2[49] = t2shi24 ^ ~t2shi20 & t2shi21; + s2[0] ^= P1600_ROUND_CONSTANTS[round * 2]; + s2[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]; + } + }; + } +}); + +// node_modules/keccak/lib/keccak.js +var require_keccak2 = __commonJS({ + "node_modules/keccak/lib/keccak.js"(exports2, module2) { + init_shim(); + var keccakState = require_keccak_state_unroll(); + function Keccak() { + this.state = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + this.blockSize = null; + this.count = 0; + this.squeezing = false; + } + Keccak.prototype.initialize = function(rate, capacity) { + for (let i2 = 0; i2 < 50; ++i2) + this.state[i2] = 0; + this.blockSize = rate / 8; + this.count = 0; + this.squeezing = false; + }; + Keccak.prototype.absorb = function(data) { + for (let i2 = 0; i2 < data.length; ++i2) { + this.state[~~(this.count / 4)] ^= data[i2] << 8 * (this.count % 4); + this.count += 1; + if (this.count === this.blockSize) { + keccakState.p1600(this.state); + this.count = 0; + } + } + }; + Keccak.prototype.absorbLastFewBits = function(bits) { + this.state[~~(this.count / 4)] ^= bits << 8 * (this.count % 4); + if ((bits & 128) !== 0 && this.count === this.blockSize - 1) + keccakState.p1600(this.state); + this.state[~~((this.blockSize - 1) / 4)] ^= 128 << 8 * ((this.blockSize - 1) % 4); + keccakState.p1600(this.state); + this.count = 0; + this.squeezing = true; + }; + Keccak.prototype.squeeze = function(length2) { + if (!this.squeezing) + this.absorbLastFewBits(1); + const output = import_buffer.Buffer.alloc(length2); + for (let i2 = 0; i2 < length2; ++i2) { + output[i2] = this.state[~~(this.count / 4)] >>> 8 * (this.count % 4) & 255; + this.count += 1; + if (this.count === this.blockSize) { + keccakState.p1600(this.state); + this.count = 0; + } + } + return output; + }; + Keccak.prototype.copy = function(dest) { + for (let i2 = 0; i2 < 50; ++i2) + dest.state[i2] = this.state[i2]; + dest.blockSize = this.blockSize; + dest.count = this.count; + dest.squeezing = this.squeezing; + }; + module2.exports = Keccak; + } +}); + +// node_modules/keccak/js.js +var require_js = __commonJS({ + "node_modules/keccak/js.js"(exports2, module2) { + init_shim(); + module2.exports = require_api()(require_keccak2()); + } +}); + +// node_modules/@multiversx/sdk-core/out/address.js +var require_address = __commonJS({ + "node_modules/@multiversx/sdk-core/out/address.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AddressComputer = exports2.Address = void 0; + var bech32 = __importStar2(require_bech32()); + var bignumber_js_1 = __importDefault2(require_bignumber()); + var constants_1 = require_constants(); + var errors = __importStar2(require_errors()); + var codec_1 = require_codec(); + var createKeccakHash = require_js(); + var HRP = "erd"; + var PUBKEY_LENGTH = 32; + var SMART_CONTRACT_HEX_PUBKEY_PREFIX = "0".repeat(16); + var Address5 = class _Address { + /** + * Creates an address object, given a raw string (whether a hex pubkey or a Bech32 address), a sequence of bytes, or another Address object. + */ + constructor(value) { + this.valueHex = ""; + if (!value) { + return; + } + if (value instanceof _Address) { + return _Address.fromAddress(value); + } + if (ArrayBuffer.isView(value)) { + return _Address.fromBuffer(import_buffer.Buffer.from(value)); + } + if (typeof value === "string") { + return _Address.fromString(value); + } + throw new errors.ErrAddressCannotCreate(value); + } + /** + * Creates an address object from another address object + */ + static fromAddress(address) { + return _Address.fromValidHex(address.valueHex); + } + static fromValidHex(value) { + let result = _Address.empty(); + result.valueHex = value; + return result; + } + /** + * Creates an address object from a Buffer + */ + static fromBuffer(buffer) { + if (buffer.length != PUBKEY_LENGTH) { + throw new errors.ErrAddressCannotCreate(buffer); + } + return _Address.fromValidHex(buffer.toString("hex")); + } + /** + * Creates an address object from a string (hex or bech32) + */ + static fromString(value) { + if (_Address.isValidHex(value)) { + return _Address.fromValidHex(value); + } + return _Address.fromBech32(value); + } + static isValidHex(value) { + return import_buffer.Buffer.from(value, "hex").length == PUBKEY_LENGTH; + } + /** + * Creates an address object from a hex-encoded string + */ + static fromHex(value) { + if (!_Address.isValidHex(value)) { + throw new errors.ErrAddressCannotCreate(value); + } + return _Address.fromValidHex(value); + } + /** + * Creates an empty address object. + * Generally speaking, this should not be used by client code (internal use only). + */ + static empty() { + return new _Address(""); + } + /** + * Creates an address object from a bech32-encoded string + */ + static fromBech32(value) { + let decoded; + try { + decoded = bech32.decode(value); + } catch (err) { + throw new errors.ErrAddressCannotCreate(value, err); + } + const prefix = decoded.prefix; + if (prefix != HRP) { + throw new errors.ErrAddressBadHrp(HRP, prefix); + } + const pubkey = import_buffer.Buffer.from(bech32.fromWords(decoded.words)); + if (pubkey.length != PUBKEY_LENGTH) { + throw new errors.ErrAddressCannotCreate(value); + } + return _Address.fromValidHex(pubkey.toString("hex")); + } + /** + * Performs address validation without throwing errors + */ + static isValid(value) { + const decoded = bech32.decodeUnsafe(value); + const prefix = decoded?.prefix; + const pubkey = decoded ? import_buffer.Buffer.from(bech32.fromWords(decoded.words)) : void 0; + if (prefix !== HRP || pubkey?.length !== PUBKEY_LENGTH) { + return false; + } + return true; + } + /** + * Use {@link toHex} instead. + */ + hex() { + return this.toHex(); + } + /** + * Returns the hex representation of the address (pubkey) + */ + toHex() { + if (this.isEmpty()) { + return ""; + } + return this.valueHex; + } + /** + * Use {@link toBech32} instead. + */ + bech32() { + return this.toBech32(); + } + /** + * Returns the bech32 representation of the address + */ + toBech32() { + if (this.isEmpty()) { + return ""; + } + let words = bech32.toWords(this.pubkey()); + let address = bech32.encode(HRP, words); + return address; + } + /** + * Use {@link getPublicKey} instead. + */ + pubkey() { + return this.getPublicKey(); + } + /** + * Returns the pubkey as raw bytes (buffer) + */ + getPublicKey() { + if (this.isEmpty()) { + return import_buffer.Buffer.from([]); + } + return import_buffer.Buffer.from(this.valueHex, "hex"); + } + /** + * Returns the human-readable-part of the bech32 addresses. + * The HRP is currently hardcoded to "erd". + */ + getHrp() { + return HRP; + } + /** + * Returns whether the address is empty. + */ + isEmpty() { + return !this.valueHex; + } + /** + * Compares the address to another address + */ + equals(other) { + if (!other) { + return false; + } + return this.valueHex == other.valueHex; + } + /** + * Returns the bech32 representation of the address + */ + toString() { + return this.toBech32(); + } + /** + * Converts the address to a pretty, plain JavaScript object. + */ + toJSON() { + return { + bech32: this.toBech32(), + pubkey: this.toHex() + }; + } + /** + * Creates the Zero address (the one that should be used when deploying smart contracts). + * Generally speaking, this should not be used by client code (internal use only). + */ + static Zero() { + return new _Address("0".repeat(64)); + } + /** + * Use {@link isSmartContract} instead. + */ + isContractAddress() { + return this.isSmartContract(); + } + /** + * Returns whether the address is a smart contract address. + */ + isSmartContract() { + return this.toHex().startsWith(SMART_CONTRACT_HEX_PUBKEY_PREFIX); + } + }; + exports2.Address = Address5; + var AddressComputer = class { + constructor(numberOfShardsWithoutMeta) { + this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || constants_1.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; + } + computeContractAddress(deployer, deploymentNonce) { + const initialPadding = import_buffer.Buffer.alloc(8, 0); + const ownerPubkey = deployer.getPublicKey(); + const shardSelector = ownerPubkey.slice(30); + const ownerNonceBytes = import_buffer.Buffer.alloc(8); + const bigNonce = new bignumber_js_1.default(deploymentNonce.toString()); + const bigNonceBuffer = codec_1.bigIntToBuffer(bigNonce); + ownerNonceBytes.write(bigNonceBuffer.reverse().toString("hex"), "hex"); + const bytesToHash = import_buffer.Buffer.concat([ownerPubkey, ownerNonceBytes]); + const hash = createKeccakHash("keccak256").update(bytesToHash).digest(); + const vmTypeBytes = import_buffer.Buffer.from(constants_1.WasmVirtualMachine, "hex"); + const addressBytes = import_buffer.Buffer.concat([initialPadding, vmTypeBytes, hash.slice(10, 30), shardSelector]); + return new Address5(addressBytes); + } + getShardOfAddress(address) { + return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); + } + getShardOfPubkey(pubkey, numberOfShards) { + const maskHigh = parseInt("11", 2); + const maskLow = parseInt("01", 2); + const lastByteOfPubkey = pubkey[31]; + if (this.isPubkeyOfMetachain(pubkey)) { + return constants_1.METACHAIN_ID; + } + let shard = lastByteOfPubkey & maskHigh; + if (shard > numberOfShards - 1) { + shard = lastByteOfPubkey & maskLow; + } + return shard; + } + isPubkeyOfMetachain(pubkey) { + const metachainPrefix = import_buffer.Buffer.from([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + const pubkeyPrefix = import_buffer.Buffer.from(pubkey).slice(0, metachainPrefix.length); + if (metachainPrefix.equals(pubkeyPrefix)) { + return true; + } + const zeroAddress = import_buffer.Buffer.alloc(32); + if (zeroAddress.equals(import_buffer.Buffer.from(pubkey))) { + return true; + } + return false; + } + }; + exports2.AddressComputer = AddressComputer; + } +}); + +// node_modules/@multiversx/sdk-core/out/utils.js +var require_utils2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/utils.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isEmpty = exports2.guardEmpty = exports2.guardNotEmpty = exports2.guardLength = exports2.guardSameLength = exports2.guardValueIsSetWithMessage = exports2.guardValueIsSet = exports2.guardTrue = void 0; + var errors = __importStar2(require_errors()); + function guardTrue(value, what) { + if (!value) { + throw new errors.ErrInvariantFailed(`[<${what}>] isn't true`); + } + } + exports2.guardTrue = guardTrue; + function guardValueIsSet(name2, value) { + guardValueIsSetWithMessage(`${name2} isn't set (null or undefined)`, value); + } + exports2.guardValueIsSet = guardValueIsSet; + function guardValueIsSetWithMessage(message, value) { + if (value == null || value === void 0) { + throw new errors.ErrInvariantFailed(message); + } + } + exports2.guardValueIsSetWithMessage = guardValueIsSetWithMessage; + function guardSameLength(a3, b4) { + a3 = a3 || []; + b4 = b4 || []; + if (a3.length != b4.length) { + throw new errors.ErrInvariantFailed("arrays do not have the same length"); + } + } + exports2.guardSameLength = guardSameLength; + function guardLength(withLength, expectedLength) { + let actualLength = withLength.length || 0; + if (actualLength != expectedLength) { + throw new errors.ErrInvariantFailed(`wrong length, expected: ${expectedLength}, actual: ${actualLength}`); + } + } + exports2.guardLength = guardLength; + function guardNotEmpty(value, what) { + if (isEmpty(value)) { + throw new errors.ErrInvariantFailed(`${what} is empty`); + } + } + exports2.guardNotEmpty = guardNotEmpty; + function guardEmpty(value, what) { + if (!isEmpty(value)) { + throw new errors.ErrInvariantFailed(`${what} is not empty`); + } + } + exports2.guardEmpty = guardEmpty; + function isEmpty(value) { + if (value.isEmpty) { + return value.isEmpty(); + } + return value.length === 0; + } + exports2.isEmpty = isEmpty; + } +}); + +// node_modules/@multiversx/sdk-core/out/abi/typeFormula.js +var require_typeFormula = __commonJS({ + "node_modules/@multiversx/sdk-core/out/abi/typeFormula.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeFormula = void 0; + var TypeFormula = class { + constructor(name2, typeParameters) { + this.name = name2; + this.typeParameters = typeParameters; + } + toString() { + if (this.typeParameters.length > 0) { + const typeParameters = this.typeParameters.map((typeParameter) => typeParameter.toString()).join(", "); + return `${this.name}<${typeParameters}>`; + } else { + return this.name; + } + } + }; + exports2.TypeFormula = TypeFormula; + } +}); + +// node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js +var require_typeFormulaParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeFormulaParser = void 0; + var typeFormula_1 = require_typeFormula(); + var TypeFormulaParser = class _TypeFormulaParser { + parseExpression(expression) { + expression = expression.trim(); + const tokens = this.tokenizeExpression(expression).filter((token) => token !== _TypeFormulaParser.COMMA); + const stack = []; + for (const token of tokens) { + if (this.isPunctuation(token)) { + if (this.isEndOfTypeParameters(token)) { + const typeFormula = this.acquireTypeWithParameters(stack); + stack.push(typeFormula); + } else if (this.isBeginningOfTypeParameters(token)) { + stack.push(token); + } else { + throw new Error(`Unexpected token (punctuation): ${token}`); + } + } else { + stack.push(token); + } + } + if (stack.length !== 1) { + throw new Error(`Unexpected stack length at end of parsing: ${stack.length}`); + } + if (_TypeFormulaParser.PUNCTUATION.includes(stack[0])) { + throw new Error("Unexpected root element."); + } + const item = stack[0]; + if (item instanceof typeFormula_1.TypeFormula) { + return item; + } else if (typeof item === "string") { + return new typeFormula_1.TypeFormula(item, []); + } else { + throw new Error(`Unexpected item on stack: ${item}`); + } + } + tokenizeExpression(expression) { + const tokens = []; + let currentToken = ""; + for (const character of expression) { + if (this.isPunctuation(character)) { + if (currentToken) { + tokens.push(currentToken.trim()); + currentToken = ""; + } + tokens.push(character); + } else { + currentToken += character; + } + } + if (currentToken) { + tokens.push(currentToken.trim()); + } + return tokens; + } + acquireTypeWithParameters(stack) { + const typeParameters = this.acquireTypeParameters(stack); + const typeName = stack.pop(); + const typeFormula = new typeFormula_1.TypeFormula(typeName, typeParameters.reverse()); + return typeFormula; + } + acquireTypeParameters(stack) { + const typeParameters = []; + while (true) { + const item = stack.pop(); + if (item === void 0) { + throw new Error("Badly specified type parameters"); + } + if (this.isBeginningOfTypeParameters(item)) { + break; + } + if (item instanceof typeFormula_1.TypeFormula) { + typeParameters.push(item); + } else if (typeof item === "string") { + typeParameters.push(new typeFormula_1.TypeFormula(item, [])); + } else { + throw new Error(`Unexpected type parameter object in stack: ${item}`); + } + } + return typeParameters; + } + isPunctuation(token) { + return _TypeFormulaParser.PUNCTUATION.includes(token); + } + isEndOfTypeParameters(token) { + return token === _TypeFormulaParser.END_TYPE_PARAMETERS; + } + isBeginningOfTypeParameters(token) { + return token === _TypeFormulaParser.BEGIN_TYPE_PARAMETERS; + } + }; + exports2.TypeFormulaParser = TypeFormulaParser; + TypeFormulaParser.BEGIN_TYPE_PARAMETERS = "<"; + TypeFormulaParser.END_TYPE_PARAMETERS = ">"; + TypeFormulaParser.COMMA = ","; + TypeFormulaParser.PUNCTUATION = [ + TypeFormulaParser.COMMA, + TypeFormulaParser.BEGIN_TYPE_PARAMETERS, + TypeFormulaParser.END_TYPE_PARAMETERS + ]; + } +}); + +// node_modules/@multiversx/sdk-core/out/reflection.js +var require_reflection = __commonJS({ + "node_modules/@multiversx/sdk-core/out/reflection.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getJavascriptPrototypesInHierarchy = void 0; + function getJavascriptPrototypesInHierarchy(obj, filter) { + let prototypes = []; + let prototype = Object.getPrototypeOf(obj); + while (prototype && filter(prototype)) { + prototypes.push(prototype); + prototype = Object.getPrototypeOf(prototype); + } + return prototypes; + } + exports2.getJavascriptPrototypesInHierarchy = getJavascriptPrototypesInHierarchy; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js +var require_types = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NullType = exports2.TypePlaceholder = exports2.isTyped = exports2.PrimitiveValue = exports2.TypedValue = exports2.CustomType = exports2.PrimitiveType = exports2.TypeCardinality = exports2.Type = void 0; + var reflection_1 = require_reflection(); + var utils_1 = require_utils2(); + var Type = class _Type { + constructor(name2, typeParameters = [], cardinality = TypeCardinality.fixed(1)) { + utils_1.guardValueIsSet("name", name2); + this.name = name2; + this.typeParameters = typeParameters; + this.cardinality = cardinality; + } + getName() { + return this.name; + } + getClassName() { + return _Type.ClassName; + } + getClassHierarchy() { + let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); + let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); + return classNames; + } + /** + * Gets the fully qualified name of the type, to allow for better (efficient and non-ambiguous) type comparison within the custom typesystem. + */ + getFullyQualifiedName() { + let joinedTypeParameters = this.getTypeParameters().map((type) => type.getFullyQualifiedName()).join(", "); + return this.isGenericType() ? `multiversx:types:${this.getName()}<${joinedTypeParameters}>` : `multiversx:types:${this.getName()}`; + } + hasExactClass(className) { + return this.getClassName() == className; + } + hasClassOrSuperclass(className) { + let hierarchy = this.getClassHierarchy(); + return hierarchy.includes(className); + } + getTypeParameters() { + return this.typeParameters; + } + isGenericType() { + return this.typeParameters.length > 0; + } + getFirstTypeParameter() { + utils_1.guardTrue(this.typeParameters.length > 0, "type parameters length > 0"); + return this.typeParameters[0]; + } + /** + * Generates type expressions similar to mx-sdk-rs. + */ + toString() { + let typeParameters = this.getTypeParameters().map((type) => type.toString()).join(", "); + let typeParametersExpression = typeParameters ? `<${typeParameters}>` : ""; + return `${this.name}${typeParametersExpression}`; + } + equals(other) { + return _Type.equals(this, other); + } + static equals(a3, b4) { + return a3.getFullyQualifiedName() == b4.getFullyQualifiedName(); + } + static equalsMany(a3, b4) { + return a3.every((type, i2) => type.equals(b4[i2])); + } + static isAssignableFromMany(a3, b4) { + return a3.every((type, i2) => type.isAssignableFrom(b4[i2])); + } + differs(other) { + return !this.equals(other); + } + valueOf() { + return this.name; + } + /** + * Inspired from: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom + * For (most) generics, type invariance is expected (assumed) - neither covariance, nor contravariance are supported yet (will be supported in a next release). + * + * One exception though: for {@link OptionType}, we simulate covariance for missing (not provided) values. + * For example, Option is assignable from Option. + * For more details, see the implementation of {@link OptionType} and @{@link OptionalType}. + * + * Also see: + * - https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) + * - https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance + */ + isAssignableFrom(other) { + let invariantTypeParameters = _Type.equalsMany(this.getTypeParameters(), other.getTypeParameters()); + if (!invariantTypeParameters) { + return false; + } + let fullyQualifiedNameOfThis = this.getFullyQualifiedName(); + let fullyQualifiedNamesInHierarchyOfOther = _Type.getFullyQualifiedNamesInHierarchy(other); + if (fullyQualifiedNamesInHierarchyOfOther.includes(fullyQualifiedNameOfThis)) { + return true; + } + return other.hasClassOrSuperclass(this.getClassName()); + } + static getFullyQualifiedNamesInHierarchy(type) { + let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(type, (prototype) => prototype.belongsToTypesystem); + let fullyQualifiedNames = prototypes.map((prototype) => prototype.getFullyQualifiedName.call(type)); + return fullyQualifiedNames; + } + getNamesOfDependencies() { + const dependencies = []; + for (const type of this.typeParameters) { + dependencies.push(type.getName()); + dependencies.push(...type.getNamesOfDependencies()); + } + return [...new Set(dependencies)]; + } + /** + * Converts the account to a pretty, plain JavaScript object. + */ + toJSON() { + return { + name: this.name, + typeParameters: this.typeParameters.map((item) => item.toJSON()) + }; + } + getCardinality() { + return this.cardinality; + } + /** + * A special marker for types within the custom typesystem. + */ + belongsToTypesystem() { + } + }; + exports2.Type = Type; + Type.ClassName = "Type"; + var TypeCardinality = class _TypeCardinality { + constructor(lowerBound, upperBound) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + } + static fixed(value) { + return new _TypeCardinality(value, value); + } + static variable(value) { + return new _TypeCardinality(0, value); + } + isSingular() { + return this.lowerBound == 1 && this.upperBound == 1; + } + isSingularOrNone() { + return this.lowerBound == 0 && this.upperBound == 1; + } + isComposite() { + return this.upperBound != 1; + } + isFixed() { + return this.lowerBound == this.upperBound; + } + getLowerBound() { + return this.lowerBound; + } + getUpperBound() { + return this.upperBound || _TypeCardinality.MaxCardinality; + } + }; + exports2.TypeCardinality = TypeCardinality; + TypeCardinality.MaxCardinality = 4096; + var PrimitiveType = class _PrimitiveType extends Type { + constructor(name2) { + super(name2); + } + getClassName() { + return _PrimitiveType.ClassName; + } + }; + exports2.PrimitiveType = PrimitiveType; + PrimitiveType.ClassName = "PrimitiveType"; + var CustomType = class _CustomType extends Type { + getClassName() { + return _CustomType.ClassName; + } + }; + exports2.CustomType = CustomType; + CustomType.ClassName = "CustomType"; + var TypedValue = class _TypedValue { + constructor(type) { + this.type = type; + } + getClassName() { + return _TypedValue.ClassName; + } + getClassHierarchy() { + let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); + let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); + return classNames; + } + getType() { + return this.type; + } + hasExactClass(className) { + return this.getClassName() == className; + } + hasClassOrSuperclass(className) { + let hierarchy = this.getClassHierarchy(); + return hierarchy.includes(className); + } + /** + * A special marker for values within the custom typesystem. + */ + belongsToTypesystem() { + } + }; + exports2.TypedValue = TypedValue; + TypedValue.ClassName = "TypedValue"; + var PrimitiveValue = class _PrimitiveValue extends TypedValue { + constructor(type) { + super(type); + } + getClassName() { + return _PrimitiveValue.ClassName; + } + }; + exports2.PrimitiveValue = PrimitiveValue; + PrimitiveValue.ClassName = "PrimitiveValue"; + function isTyped(value) { + return value.belongsToTypesystem !== void 0; + } + exports2.isTyped = isTyped; + var TypePlaceholder = class _TypePlaceholder extends Type { + constructor() { + super("..."); + } + getClassName() { + return _TypePlaceholder.ClassName; + } + }; + exports2.TypePlaceholder = TypePlaceholder; + TypePlaceholder.ClassName = "TypePlaceholder"; + var NullType = class _NullType extends Type { + constructor() { + super("?"); + } + getClassName() { + return _NullType.ClassName; + } + }; + exports2.NullType = NullType; + NullType.ClassName = "NullType"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js +var require_typeExpressionParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeExpressionParser = void 0; + var typeFormulaParser_1 = require_typeFormulaParser(); + var errors_1 = require_errors(); + var types_1 = require_types(); + var TypeExpressionParser = class { + constructor() { + this.backingTypeFormulaParser = new typeFormulaParser_1.TypeFormulaParser(); + } + parse(expression) { + try { + return this.doParse(expression); + } catch (e2) { + throw new errors_1.ErrTypingSystem(`Failed to parse type expression: ${expression}. Error: ${e2}`); + } + } + doParse(expression) { + const typeFormula = this.backingTypeFormulaParser.parseExpression(expression); + const type = this.typeFormulaToType(typeFormula); + return type; + } + typeFormulaToType(typeFormula) { + const typeParameters = typeFormula.typeParameters.map((typeFormula2) => this.typeFormulaToType(typeFormula2)); + return new types_1.Type(typeFormula.name, typeParameters); + } + }; + exports2.TypeExpressionParser = TypeExpressionParser; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js +var require_endpoint = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EndpointParameterDefinition = exports2.EndpointModifiers = exports2.EndpointDefinition = void 0; + var typeExpressionParser_1 = require_typeExpressionParser(); + var NamePlaceholder = "?"; + var DescriptionPlaceholder = "N / A"; + var EndpointDefinition = class _EndpointDefinition { + constructor(name2, input, output, modifiers) { + this.input = []; + this.output = []; + this.name = name2; + this.input = input || []; + this.output = output || []; + this.modifiers = modifiers; + } + isConstructor() { + return this.name == "constructor"; + } + static fromJSON(json) { + json.name = json.name == null ? NamePlaceholder : json.name; + json.onlyOwner = json.onlyOwner || false; + json.payableInTokens = json.payableInTokens || []; + json.inputs = json.inputs || []; + json.outputs = json.outputs || []; + let input = json.inputs.map((param) => EndpointParameterDefinition.fromJSON(param)); + let output = json.outputs.map((param) => EndpointParameterDefinition.fromJSON(param)); + let modifiers = new EndpointModifiers(json.mutability, json.payableInTokens, json.onlyOwner); + return new _EndpointDefinition(json.name, input, output, modifiers); + } + }; + exports2.EndpointDefinition = EndpointDefinition; + var EndpointModifiers = class { + constructor(mutability, payableInTokens, onlyOwner) { + this.mutability = mutability || ""; + this.payableInTokens = payableInTokens || []; + this.onlyOwner = onlyOwner || false; + } + isPayableInEGLD() { + return this.isPayableInToken("EGLD"); + } + isPayableInToken(token) { + if (this.payableInTokens.includes(token)) { + return true; + } + if (this.payableInTokens.includes(`!${token}`)) { + return false; + } + if (this.payableInTokens.includes("*")) { + return true; + } + return false; + } + isPayable() { + return this.payableInTokens.length != 0; + } + isReadonly() { + return this.mutability == "readonly"; + } + isOnlyOwner() { + return this.onlyOwner; + } + }; + exports2.EndpointModifiers = EndpointModifiers; + var EndpointParameterDefinition = class _EndpointParameterDefinition { + constructor(name2, description, type) { + this.name = name2; + this.description = description; + this.type = type; + } + static fromJSON(json) { + let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); + return new _EndpointParameterDefinition(json.name || NamePlaceholder, json.description || DescriptionPlaceholder, parsedType); + } + }; + exports2.EndpointParameterDefinition = EndpointParameterDefinition; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js +var require_fields = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Fields = exports2.Field = exports2.FieldDefinition = void 0; + var errors = __importStar2(require_errors()); + var typeExpressionParser_1 = require_typeExpressionParser(); + var FieldDefinition = class _FieldDefinition { + constructor(name2, description, type) { + this.name = name2; + this.description = description; + this.type = type; + } + static fromJSON(json) { + let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); + return new _FieldDefinition(json.name, json.description, parsedType); + } + }; + exports2.FieldDefinition = FieldDefinition; + var Field = class { + constructor(value, name2 = "") { + this.value = value; + this.name = name2; + } + checkTyping(expectedDefinition) { + const actualType = this.value.getType(); + if (!actualType.equals(expectedDefinition.type)) { + throw new errors.ErrTypingSystem(`check type of field "${expectedDefinition.name}; expected: ${expectedDefinition.type}, actual: ${actualType}"`); + } + if (this.name != expectedDefinition.name) { + throw new errors.ErrTypingSystem(`check name of field "${expectedDefinition.name}"`); + } + } + equals(other) { + return this.name == other.name && this.value.equals(other.value); + } + }; + exports2.Field = Field; + var Fields = class { + static checkTyping(fields, definitions) { + if (fields.length != definitions.length) { + throw new errors.ErrTypingSystem("fields length vs. field definitions length"); + } + for (let i2 = 0; i2 < fields.length; i2++) { + let field = fields[i2]; + let definition = definitions[i2]; + field.checkTyping(definition); + } + } + static equals(actual, expected) { + if (actual.length != expected.length) { + return false; + } + for (let i2 = 0; i2 < actual.length; i2++) { + let selfField = actual[i2]; + let otherField = expected[i2]; + if (!selfField.equals(otherField)) { + return false; + } + } + return true; + } + static getNamesOfTypeDependencies(definitions) { + const dependencies = []; + for (const definition of definitions) { + dependencies.push(definition.type.getName()); + dependencies.push(...definition.type.getNamesOfDependencies()); + } + return [...new Set(dependencies)]; + } + }; + exports2.Fields = Fields; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js +var require_enum = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EnumValue = exports2.EnumVariantDefinition = exports2.EnumType = void 0; + var errors_1 = require_errors(); + var utils_1 = require_utils2(); + var fields_1 = require_fields(); + var types_1 = require_types(); + var SimpleEnumMaxDiscriminant = 256; + var EnumType = class _EnumType extends types_1.CustomType { + constructor(name2, variants) { + super(name2); + this.variants = []; + this.variants = variants; + } + getClassName() { + return _EnumType.ClassName; + } + static fromJSON(json) { + const rawVariants = _EnumType.assignMissingDiscriminants(json.variants || []); + const variants = rawVariants.map((variant) => EnumVariantDefinition.fromJSON(variant)); + return new _EnumType(json.name, variants); + } + // For some enums (e.g. some "explicit-enum" types), the discriminants are missing. + static assignMissingDiscriminants(variants) { + const allDiscriminantsAreMissing = variants.every((variant) => variant.discriminant == void 0); + if (!allDiscriminantsAreMissing) { + return variants; + } + return variants.map((variant, index) => { + return { + ...variant, + discriminant: index + }; + }); + } + getVariantByDiscriminant(discriminant) { + let result = this.variants.find((e2) => e2.discriminant == discriminant); + utils_1.guardValueIsSet(`variant by discriminant (${discriminant})`, result); + return result; + } + getVariantByName(name2) { + let result = this.variants.find((e2) => e2.name == name2); + utils_1.guardValueIsSet(`variant by name (${name2})`, result); + return result; + } + getNamesOfDependencies() { + const dependencies = []; + for (const variant of this.variants) { + dependencies.push(...variant.getNamesOfDependencies()); + } + return [...new Set(dependencies)]; + } + }; + exports2.EnumType = EnumType; + EnumType.ClassName = "EnumType"; + var EnumVariantDefinition = class _EnumVariantDefinition { + constructor(name2, discriminant, fieldsDefinitions = []) { + this.fieldsDefinitions = []; + utils_1.guardTrue(discriminant < SimpleEnumMaxDiscriminant, `discriminant for simple enum should be less than ${SimpleEnumMaxDiscriminant}`); + this.name = name2; + this.discriminant = discriminant; + this.fieldsDefinitions = fieldsDefinitions; + } + static fromJSON(json) { + let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); + return new _EnumVariantDefinition(json.name, json.discriminant, definitions); + } + getFieldsDefinitions() { + return this.fieldsDefinitions; + } + getFieldDefinition(name2) { + return this.fieldsDefinitions.find((item) => item.name == name2); + } + getNamesOfDependencies() { + return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); + } + }; + exports2.EnumVariantDefinition = EnumVariantDefinition; + var EnumValue = class _EnumValue extends types_1.TypedValue { + constructor(type, variant, fields) { + super(type); + this.fields = []; + this.name = variant.name; + this.discriminant = variant.discriminant; + this.fields = fields; + this.fieldsByName = new Map(fields.map((field) => [field.name, field])); + let definitions = variant.getFieldsDefinitions(); + fields_1.Fields.checkTyping(this.fields, definitions); + } + getClassName() { + return _EnumValue.ClassName; + } + /** + * Utility (named constructor) to create a simple (i.e. without fields) enum value. + */ + static fromName(type, name2) { + let variant = type.getVariantByName(name2); + return new _EnumValue(type, variant, []); + } + /** + * Utility (named constructor) to create a simple (i.e. without fields) enum value. + */ + static fromDiscriminant(type, discriminant) { + let variant = type.getVariantByDiscriminant(discriminant); + return new _EnumValue(type, variant, []); + } + equals(other) { + if (!this.getType().equals(other.getType())) { + return false; + } + let selfFields = this.getFields(); + let otherFields = other.getFields(); + const nameIsSame = this.name == other.name; + const discriminantIsSame = this.discriminant == other.discriminant; + const fieldsAreSame = fields_1.Fields.equals(selfFields, otherFields); + return nameIsSame && discriminantIsSame && fieldsAreSame; + } + getFields() { + return this.fields; + } + getFieldValue(name2) { + let field = this.fieldsByName.get(name2); + if (field) { + return field.value.valueOf(); + } + throw new errors_1.ErrMissingFieldOnEnum(name2, this.getType().getName()); + } + valueOf() { + let result = { name: this.name, fields: [] }; + this.fields.forEach((field, index) => result.fields[index] = field.value.valueOf()); + return result; + } + }; + exports2.EnumValue = EnumValue; + EnumValue.ClassName = "EnumValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js +var require_event = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EventTopicDefinition = exports2.EventDefinition = void 0; + var typeExpressionParser_1 = require_typeExpressionParser(); + var NamePlaceholder = "?"; + var EventDefinition = class _EventDefinition { + constructor(identifier, inputs) { + this.inputs = []; + this.identifier = identifier; + this.inputs = inputs || []; + } + static fromJSON(json) { + json.identifier = json.identifier == null ? NamePlaceholder : json.identifier; + json.inputs = json.inputs || []; + const inputs = json.inputs.map((param) => EventTopicDefinition.fromJSON(param)); + return new _EventDefinition(json.identifier, inputs); + } + }; + exports2.EventDefinition = EventDefinition; + var EventTopicDefinition = class _EventTopicDefinition { + constructor(options) { + this.name = options.name; + this.type = options.type; + this.indexed = options.indexed; + } + static fromJSON(json) { + const parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); + return new _EventTopicDefinition({ + name: json.name || NamePlaceholder, + type: parsedType, + indexed: json.indexed + }); + } + }; + exports2.EventTopicDefinition = EventTopicDefinition; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js +var require_struct = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Struct = exports2.StructType = void 0; + var errors_1 = require_errors(); + var fields_1 = require_fields(); + var types_1 = require_types(); + var StructType = class _StructType extends types_1.CustomType { + constructor(name2, fieldsDefinitions) { + super(name2); + this.fieldsDefinitions = []; + this.fieldsDefinitions = fieldsDefinitions; + } + getClassName() { + return _StructType.ClassName; + } + static fromJSON(json) { + let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); + return new _StructType(json.name, definitions); + } + getFieldsDefinitions() { + return this.fieldsDefinitions; + } + getFieldDefinition(name2) { + return this.fieldsDefinitions.find((item) => item.name == name2); + } + getNamesOfDependencies() { + return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); + } + }; + exports2.StructType = StructType; + StructType.ClassName = "StructType"; + var Struct = class _Struct extends types_1.TypedValue { + /** + * One can only set fields at initialization time. + */ + constructor(type, fields) { + super(type); + this.fields = fields; + this.fieldsByName = new Map(fields.map((field) => [field.name, field])); + this.checkTyping(); + } + getClassName() { + return _Struct.ClassName; + } + checkTyping() { + let type = this.getType(); + let definitions = type.getFieldsDefinitions(); + fields_1.Fields.checkTyping(this.fields, definitions); + } + getFields() { + return this.fields; + } + getFieldValue(name2) { + let field = this.fieldsByName.get(name2); + if (field) { + return field.value.valueOf(); + } + throw new errors_1.ErrMissingFieldOnStruct(name2, this.getType().getName()); + } + valueOf() { + let result = {}; + for (const field of this.fields) { + result[field.name] = field.value.valueOf(); + } + return result; + } + equals(other) { + if (!this.getType().equals(other.getType())) { + return false; + } + let selfFields = this.getFields(); + let otherFields = other.getFields(); + return fields_1.Fields.equals(selfFields, otherFields); + } + }; + exports2.Struct = Struct; + Struct.ClassName = "Struct"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js +var require_address2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AddressValue = exports2.AddressType = void 0; + var address_1 = require_address(); + var types_1 = require_types(); + var AddressType2 = class _AddressType extends types_1.PrimitiveType { + constructor() { + super("Address"); + } + getClassName() { + return _AddressType.ClassName; + } + }; + exports2.AddressType = AddressType2; + AddressType2.ClassName = "AddressType"; + var AddressValue2 = class _AddressValue extends types_1.PrimitiveValue { + constructor(value) { + super(new AddressType2()); + this.value = new address_1.Address(value.bech32()); + } + getClassName() { + return _AddressValue.ClassName; + } + /** + * Returns whether two objects have the same value. + * + * @param other another AddressValue + */ + equals(other) { + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + }; + exports2.AddressValue = AddressValue2; + AddressValue2.ClassName = "AddressValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js +var require_algebraic = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OptionalValue = exports2.OptionalType = void 0; + var utils_1 = require_utils2(); + var types_1 = require_types(); + var OptionalType = class _OptionalType extends types_1.Type { + constructor(typeParameter) { + super("Optional", [typeParameter], types_1.TypeCardinality.variable(1)); + } + getClassName() { + return _OptionalType.ClassName; + } + isAssignableFrom(type) { + if (!type.hasExactClass(_OptionalType.ClassName)) { + return false; + } + let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); + let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); + return invariantTypeParameters || fakeCovarianceToNull; + } + }; + exports2.OptionalType = OptionalType; + OptionalType.ClassName = "OptionalType"; + var OptionalValue = class _OptionalValue extends types_1.TypedValue { + constructor(type, value = null) { + super(type); + this.value = value; + } + getClassName() { + return _OptionalValue.ClassName; + } + /** + * Creates an OptionalValue, as not provided (missing). + */ + static newMissing() { + let type = new OptionalType(new types_1.NullType()); + return new _OptionalValue(type); + } + isSet() { + return this.value ? true : false; + } + getTypedValue() { + utils_1.guardValueIsSet("value", this.value); + return this.value; + } + valueOf() { + return this.value ? this.value.valueOf() : null; + } + equals(other) { + return this.value?.equals(other.value) || false; + } + }; + exports2.OptionalValue = OptionalValue; + OptionalValue.ClassName = "OptionalValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js +var require_boolean = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BooleanValue = exports2.BooleanType = void 0; + var types_1 = require_types(); + var BooleanType2 = class _BooleanType extends types_1.PrimitiveType { + constructor() { + super("bool"); + } + getClassName() { + return _BooleanType.ClassName; + } + }; + exports2.BooleanType = BooleanType2; + BooleanType2.ClassName = "BooleanType"; + var BooleanValue2 = class _BooleanValue extends types_1.PrimitiveValue { + constructor(value) { + super(new BooleanType2()); + this.value = value; + } + getClassName() { + return _BooleanValue.ClassName; + } + /** + * Returns whether two objects have the same value. + * + * @param other another BooleanValue + */ + equals(other) { + return this.value === other.value; + } + isTrue() { + return this.value === true; + } + isFalse() { + return !this.isTrue(); + } + valueOf() { + return this.value; + } + }; + exports2.BooleanValue = BooleanValue2; + BooleanValue2.ClassName = "BooleanValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js +var require_bytes = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesValue = exports2.BytesType = void 0; + var types_1 = require_types(); + var BytesType2 = class _BytesType extends types_1.PrimitiveType { + constructor() { + super("bytes"); + } + getClassName() { + return _BytesType.ClassName; + } + }; + exports2.BytesType = BytesType2; + BytesType2.ClassName = "BytesType"; + var BytesValue2 = class _BytesValue extends types_1.PrimitiveValue { + constructor(value) { + super(new BytesType2()); + this.value = value; + } + getClassName() { + return _BytesValue.ClassName; + } + /** + * Creates a BytesValue from a utf-8 string. + */ + static fromUTF8(value) { + let buffer = import_buffer.Buffer.from(value, "utf-8"); + return new _BytesValue(buffer); + } + /** + * Creates a BytesValue from a hex-encoded string. + */ + static fromHex(value) { + let buffer = import_buffer.Buffer.from(value, "hex"); + return new _BytesValue(buffer); + } + getLength() { + return this.value.length; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + if (this.getLength() != other.getLength()) { + return false; + } + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + toString() { + return this.value.toString(); + } + }; + exports2.BytesValue = BytesValue2; + BytesValue2.ClassName = "BytesValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js +var require_codeMetadata = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CodeMetadataValue = exports2.CodeMetadataType = void 0; + var types_1 = require_types(); + var CodeMetadataType = class extends types_1.PrimitiveType { + constructor() { + super("CodeMetadata"); + } + }; + exports2.CodeMetadataType = CodeMetadataType; + var CodeMetadataValue = class extends types_1.PrimitiveValue { + constructor(value) { + super(new CodeMetadataType()); + this.value = value; + } + equals(other) { + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + }; + exports2.CodeMetadataValue = CodeMetadataValue; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js +var require_composite = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CompositeValue = exports2.CompositeType = void 0; + var utils_1 = require_utils2(); + var types_1 = require_types(); + var CompositeType = class _CompositeType extends types_1.Type { + constructor(...typeParameters) { + super("Composite", typeParameters, types_1.TypeCardinality.variable(typeParameters.length)); + } + getClassName() { + return _CompositeType.ClassName; + } + }; + exports2.CompositeType = CompositeType; + CompositeType.ClassName = "CompositeType"; + var CompositeValue = class _CompositeValue extends types_1.TypedValue { + constructor(type, items) { + super(type); + utils_1.guardLength(items, type.getTypeParameters().length); + this.items = items; + } + getClassName() { + return _CompositeValue.ClassName; + } + static fromItems(...items) { + let typeParameters = items.map((value) => value.getType()); + let type = new CompositeType(...typeParameters); + return new _CompositeValue(type, items); + } + getItems() { + return this.items; + } + valueOf() { + return this.items.map((item) => item?.valueOf()); + } + equals(other) { + if (this.getType().differs(other.getType())) { + return false; + } + for (let i2 = 0; i2 < this.items.length; i2++) { + let selfItem = this.items[i2]; + let otherItem = other.items[i2]; + if (!selfItem.equals(otherItem)) { + return false; + } + } + return true; + } + }; + exports2.CompositeValue = CompositeValue; + CompositeValue.ClassName = "CompositeValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js +var require_collections = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CollectionOfTypedValues = void 0; + var CollectionOfTypedValues = class { + constructor(items) { + this.items = items; + } + getLength() { + return this.items.length; + } + getItems() { + return this.items; + } + valueOf() { + return this.items.map((item) => item.valueOf()); + } + equals(other) { + if (this.getLength() != other.getLength()) { + return false; + } + for (let i2 = 0; i2 < this.getLength(); i2++) { + let selfItem = this.items[i2]; + let otherItem = other.items[i2]; + if (!selfItem.equals(otherItem)) { + return false; + } + } + return true; + } + }; + exports2.CollectionOfTypedValues = CollectionOfTypedValues; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js +var require_generic = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.List = exports2.OptionValue = exports2.ListType = exports2.OptionType = void 0; + var utils_1 = require_utils2(); + var collections_1 = require_collections(); + var types_1 = require_types(); + var OptionType = class _OptionType extends types_1.Type { + constructor(typeParameter) { + super("Option", [typeParameter]); + } + getClassName() { + return _OptionType.ClassName; + } + isAssignableFrom(type) { + if (!type.hasExactClass(_OptionType.ClassName)) { + return false; + } + let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); + let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); + return invariantTypeParameters || fakeCovarianceToNull; + } + }; + exports2.OptionType = OptionType; + OptionType.ClassName = "OptionType"; + var ListType = class _ListType extends types_1.Type { + constructor(typeParameter) { + super("List", [typeParameter]); + } + getClassName() { + return _ListType.ClassName; + } + }; + exports2.ListType = ListType; + ListType.ClassName = "ListType"; + var OptionValue = class _OptionValue extends types_1.TypedValue { + constructor(type, value = null) { + super(type); + this.value = value; + } + getClassName() { + return _OptionValue.ClassName; + } + /** + * Creates an OptionValue, as a missing option argument. + */ + static newMissing() { + let type = new OptionType(new types_1.NullType()); + return new _OptionValue(type); + } + static newMissingTyped(type) { + return new _OptionValue(new OptionType(type)); + } + /** + * Creates an OptionValue, as a provided option argument. + */ + static newProvided(typedValue) { + let type = new OptionType(typedValue.getType()); + return new _OptionValue(type, typedValue); + } + isSet() { + return this.value ? true : false; + } + getTypedValue() { + utils_1.guardValueIsSet("value", this.value); + return this.value; + } + valueOf() { + return this.value ? this.value.valueOf() : null; + } + equals(other) { + return this.value?.equals(other.value) || false; + } + }; + exports2.OptionValue = OptionValue; + OptionValue.ClassName = "OptionValue"; + var List = class _List extends types_1.TypedValue { + /** + * + * @param type the type of this TypedValue (an instance of ListType), not the type parameter of the ListType + * @param items the items, having the type type.getFirstTypeParameter() + */ + constructor(type, items) { + super(type); + this.backingCollection = new collections_1.CollectionOfTypedValues(items); + } + getClassName() { + return _List.ClassName; + } + static fromItems(items) { + if (items.length == 0) { + return new _List(new types_1.TypePlaceholder(), []); + } + let typeParameter = items[0].getType(); + let listType = new ListType(typeParameter); + return new _List(listType, items); + } + getLength() { + return this.backingCollection.getLength(); + } + getItems() { + return this.backingCollection.getItems(); + } + valueOf() { + return this.backingCollection.valueOf(); + } + equals(other) { + return this.backingCollection.equals(other.backingCollection); + } + }; + exports2.List = List; + List.ClassName = "List"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js +var require_genericArray = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArrayVec = exports2.ArrayVecType = void 0; + var utils_1 = require_utils2(); + var collections_1 = require_collections(); + var types_1 = require_types(); + var ArrayVecType = class _ArrayVecType extends types_1.Type { + constructor(length2, typeParameter) { + super("Array", [typeParameter]); + utils_1.guardTrue(length2 > 0, "array length > 0"); + this.length = length2; + } + getClassName() { + return _ArrayVecType.ClassName; + } + }; + exports2.ArrayVecType = ArrayVecType; + ArrayVecType.ClassName = "ArrayVecType"; + var ArrayVec = class _ArrayVec extends types_1.TypedValue { + constructor(type, items) { + super(type); + utils_1.guardLength(items, type.length); + this.backingCollection = new collections_1.CollectionOfTypedValues(items); + } + getClassName() { + return _ArrayVec.ClassName; + } + getLength() { + return this.backingCollection.getLength(); + } + getItems() { + return this.backingCollection.getItems(); + } + valueOf() { + return this.backingCollection.valueOf(); + } + equals(other) { + return this.backingCollection.equals(other.backingCollection); + } + }; + exports2.ArrayVec = ArrayVec; + ArrayVec.ClassName = "ArrayVec"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js +var require_h256 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.H256Value = exports2.H256Type = void 0; + var types_1 = require_types(); + var H256Type = class _H256Type extends types_1.PrimitiveType { + constructor() { + super("H256"); + } + getClassName() { + return _H256Type.ClassName; + } + }; + exports2.H256Type = H256Type; + H256Type.ClassName = "H256Type"; + var H256Value = class _H256Value extends types_1.PrimitiveValue { + constructor(value) { + super(new H256Type()); + this.value = value; + } + getClassName() { + return _H256Value.ClassName; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + }; + exports2.H256Value = H256Value; + H256Value.ClassName = "H256Value"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js +var require_nothing = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NothingValue = exports2.NothingType = void 0; + var types_1 = require_types(); + var NothingType = class _NothingType extends types_1.PrimitiveType { + constructor() { + super("nothing"); + } + getClassName() { + return _NothingType.ClassName; + } + }; + exports2.NothingType = NothingType; + NothingType.ClassName = "NothingType"; + var NothingValue = class _NothingValue extends types_1.PrimitiveValue { + constructor() { + super(new NothingType()); + } + getClassName() { + return _NothingValue.ClassName; + } + equals(_other) { + return false; + } + valueOf() { + return {}; + } + }; + exports2.NothingValue = NothingValue; + NothingValue.ClassName = "NothingValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js +var require_numerical = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BigIntValue = exports2.BigUIntValue = exports2.I64Value = exports2.U64Value = exports2.I32Value = exports2.U32Value = exports2.I16Value = exports2.U16Value = exports2.I8Value = exports2.U8Value = exports2.NumericalValue = exports2.BigIntType = exports2.BigUIntType = exports2.I64Type = exports2.U64Type = exports2.I32Type = exports2.U32Type = exports2.I16Type = exports2.U16Type = exports2.I8Type = exports2.U8Type = exports2.NumericalType = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var errors = __importStar2(require_errors()); + var types_1 = require_types(); + var NumericalType = class _NumericalType extends types_1.PrimitiveType { + constructor(name2, sizeInBytes, withSign) { + super(name2); + this.sizeInBytes = sizeInBytes; + this.withSign = withSign; + } + getClassName() { + return _NumericalType.ClassName; + } + hasFixedSize() { + return this.sizeInBytes ? true : false; + } + hasArbitrarySize() { + return !this.hasFixedSize(); + } + }; + exports2.NumericalType = NumericalType; + NumericalType.ClassName = "NumericalType"; + var U8Type2 = class _U8Type extends NumericalType { + constructor() { + super("u8", 1, false); + } + getClassName() { + return _U8Type.ClassName; + } + }; + exports2.U8Type = U8Type2; + U8Type2.ClassName = "U8Type"; + var I8Type = class _I8Type extends NumericalType { + constructor() { + super("i8", 1, true); + } + getClassName() { + return _I8Type.ClassName; + } + }; + exports2.I8Type = I8Type; + I8Type.ClassName = "I8Type"; + var U16Type2 = class _U16Type extends NumericalType { + constructor() { + super("u16", 2, false); + } + getClassName() { + return _U16Type.ClassName; + } + }; + exports2.U16Type = U16Type2; + U16Type2.ClassName = "U16Type"; + var I16Type = class _I16Type extends NumericalType { + constructor() { + super("i16", 2, true); + } + getClassName() { + return _I16Type.ClassName; + } + }; + exports2.I16Type = I16Type; + I16Type.ClassName = "I16Type"; + var U32Type2 = class _U32Type extends NumericalType { + constructor() { + super("u32", 4, false); + } + getClassName() { + return _U32Type.ClassName; + } + }; + exports2.U32Type = U32Type2; + U32Type2.ClassName = "U32Type"; + var I32Type = class _I32Type extends NumericalType { + constructor() { + super("i32", 4, true); + } + getClassName() { + return _I32Type.ClassName; + } + }; + exports2.I32Type = I32Type; + I32Type.ClassName = "I32Type"; + var U64Type2 = class _U64Type extends NumericalType { + constructor() { + super("u64", 8, false); + } + getClassName() { + return _U64Type.ClassName; + } + }; + exports2.U64Type = U64Type2; + U64Type2.ClassName = "U64Type"; + var I64Type = class _I64Type extends NumericalType { + constructor() { + super("i64", 8, true); + } + getClassName() { + return _I64Type.ClassName; + } + }; + exports2.I64Type = I64Type; + I64Type.ClassName = "I64Type"; + var BigUIntType2 = class _BigUIntType extends NumericalType { + constructor() { + super("BigUint", 0, false); + } + getClassName() { + return _BigUIntType.ClassName; + } + }; + exports2.BigUIntType = BigUIntType2; + BigUIntType2.ClassName = "BigUIntType"; + var BigIntType = class _BigIntType extends NumericalType { + constructor() { + super("Bigint", 0, true); + } + getClassName() { + return _BigIntType.ClassName; + } + }; + exports2.BigIntType = BigIntType; + BigIntType.ClassName = "BigIntType"; + var NumericalValue = class _NumericalValue extends types_1.PrimitiveValue { + constructor(type, value) { + super(type); + if (typeof value === "bigint") { + value = value.toString(); + } + this.value = new bignumber_js_1.default(value); + this.sizeInBytes = type.sizeInBytes; + this.withSign = type.withSign; + if (this.value.isNaN()) { + throw new errors.ErrInvalidArgument(`not a number: ${value}`); + } + if (!this.withSign && this.value.isNegative()) { + throw new errors.ErrInvalidArgument(`negative, but type is unsigned: ${value}`); + } + } + getClassName() { + return _NumericalValue.ClassName; + } + /** + * Returns whether two objects have the same value. + * + * @param other another NumericalValue + */ + equals(other) { + return this.value.isEqualTo(other.value); + } + valueOf() { + return this.value; + } + toString() { + return this.value.toString(); + } + }; + exports2.NumericalValue = NumericalValue; + NumericalValue.ClassName = "NumericalValue"; + var U8Value2 = class _U8Value extends NumericalValue { + constructor(value) { + super(new U8Type2(), value); + } + getClassName() { + return _U8Value.ClassName; + } + }; + exports2.U8Value = U8Value2; + U8Value2.ClassName = "U8Value"; + var I8Value = class _I8Value extends NumericalValue { + constructor(value) { + super(new I8Type(), value); + } + getClassName() { + return _I8Value.ClassName; + } + }; + exports2.I8Value = I8Value; + I8Value.ClassName = "I8Value"; + var U16Value2 = class _U16Value extends NumericalValue { + constructor(value) { + super(new U16Type2(), value); + } + getClassName() { + return _U16Value.ClassName; + } + }; + exports2.U16Value = U16Value2; + U16Value2.ClassName = "U16Value"; + var I16Value = class _I16Value extends NumericalValue { + constructor(value) { + super(new I16Type(), value); + } + getClassName() { + return _I16Value.ClassName; + } + }; + exports2.I16Value = I16Value; + I16Value.ClassName = "I16Value"; + var U32Value2 = class _U32Value extends NumericalValue { + constructor(value) { + super(new U32Type2(), value); + } + getClassName() { + return _U32Value.ClassName; + } + }; + exports2.U32Value = U32Value2; + U32Value2.ClassName = "U32Value"; + var I32Value = class _I32Value extends NumericalValue { + constructor(value) { + super(new I32Type(), value); + } + getClassName() { + return _I32Value.ClassName; + } + }; + exports2.I32Value = I32Value; + I32Value.ClassName = "I32Value"; + var U64Value2 = class _U64Value extends NumericalValue { + constructor(value) { + super(new U64Type2(), value); + } + getClassName() { + return _U64Value.ClassName; + } + }; + exports2.U64Value = U64Value2; + U64Value2.ClassName = "U64Value"; + var I64Value = class _I64Value extends NumericalValue { + constructor(value) { + super(new I64Type(), value); + } + getClassName() { + return _I64Value.ClassName; + } + }; + exports2.I64Value = I64Value; + I64Value.ClassName = "I64Value"; + var BigUIntValue2 = class _BigUIntValue extends NumericalValue { + constructor(value) { + super(new BigUIntType2(), value); + } + getClassName() { + return _BigUIntValue.ClassName; + } + }; + exports2.BigUIntValue = BigUIntValue2; + BigUIntValue2.ClassName = "BigUIntValue"; + var BigIntValue = class _BigIntValue extends NumericalValue { + constructor(value) { + super(new BigIntType(), value); + } + getClassName() { + return _BigIntValue.ClassName; + } + }; + exports2.BigIntValue = BigIntValue; + BigIntValue.ClassName = "BigIntValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js +var require_string = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StringValue = exports2.StringType = void 0; + var types_1 = require_types(); + var StringType = class _StringType extends types_1.PrimitiveType { + constructor() { + super("utf-8 string"); + } + getClassName() { + return _StringType.ClassName; + } + }; + exports2.StringType = StringType; + StringType.ClassName = "StringType"; + var StringValue = class _StringValue extends types_1.PrimitiveValue { + constructor(value) { + super(new StringType()); + this.value = value; + } + getClassName() { + return _StringValue.ClassName; + } + /** + * Creates a StringValue from a utf-8 string. + */ + static fromUTF8(value) { + return new _StringValue(value); + } + /** + * Creates a StringValue from a hex-encoded string. + */ + static fromHex(value) { + let decodedValue = import_buffer.Buffer.from(value, "hex").toString(); + return new _StringValue(decodedValue); + } + getLength() { + return this.value.length; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + return this.value === other.value; + } + valueOf() { + return this.value; + } + }; + exports2.StringValue = StringValue; + StringValue.ClassName = "StringValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js +var require_tokenIdentifier = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenIdentifierValue = exports2.TokenIdentifierType = void 0; + var types_1 = require_types(); + var EGLDTokenIdentifier = "EGLD"; + var TokenIdentifierType = class _TokenIdentifierType extends types_1.PrimitiveType { + constructor() { + super("TokenIdentifier"); + } + getClassName() { + return _TokenIdentifierType.ClassName; + } + }; + exports2.TokenIdentifierType = TokenIdentifierType; + TokenIdentifierType.ClassName = "TokenIdentifierType"; + var TokenIdentifierValue = class _TokenIdentifierValue extends types_1.PrimitiveValue { + constructor(value) { + super(new TokenIdentifierType()); + this.value = value; + } + static egld() { + return new _TokenIdentifierValue(EGLDTokenIdentifier); + } + static esdtTokenIdentifier(identifier) { + return new _TokenIdentifierValue(identifier); + } + getClassName() { + return _TokenIdentifierValue.ClassName; + } + getLength() { + return this.value.length; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + if (this.getLength() != other.getLength()) { + return false; + } + return this.value == other.value; + } + valueOf() { + return this.value; + } + toString() { + return this.value.toString(); + } + }; + exports2.TokenIdentifierValue = TokenIdentifierValue; + TokenIdentifierValue.ClassName = "TokenIdentifierValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js +var require_tuple = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Tuple = exports2.TupleType = void 0; + var errors = __importStar2(require_errors()); + var fields_1 = require_fields(); + var struct_1 = require_struct(); + var TupleType = class _TupleType extends struct_1.StructType { + constructor(...typeParameters) { + super(_TupleType.prepareName(typeParameters), _TupleType.prepareFieldDefinitions(typeParameters)); + } + getClassName() { + return _TupleType.ClassName; + } + static prepareName(typeParameters) { + let fields = typeParameters.map((type) => type.toString()).join(", "); + let result = `tuple<${fields}>`; + return result; + } + static prepareFieldDefinitions(typeParameters) { + let result = typeParameters.map((type, i2) => new fields_1.FieldDefinition(prepareFieldName(i2), "anonymous tuple field", type)); + return result; + } + }; + exports2.TupleType = TupleType; + TupleType.ClassName = "TupleType"; + function prepareFieldName(fieldIndex) { + return `field${fieldIndex}`; + } + var Tuple = class _Tuple extends struct_1.Struct { + constructor(type, fields) { + super(type, fields); + } + getClassName() { + return _Tuple.ClassName; + } + static fromItems(items) { + if (items.length < 1) { + throw new errors.ErrTypingSystem("bad tuple items"); + } + let fieldsTypes = items.map((item) => item.getType()); + let tupleType = new TupleType(...fieldsTypes); + let fields = items.map((item, i2) => new fields_1.Field(item, prepareFieldName(i2))); + return new _Tuple(tupleType, fields); + } + }; + exports2.Tuple = Tuple; + Tuple.ClassName = "Tuple"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js +var require_variadic = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.VariadicValue = exports2.CountedVariadicType = exports2.VariadicType = void 0; + var types_1 = require_types(); + var VariadicType = class _VariadicType extends types_1.Type { + constructor(typeParameter, isCounted = false) { + super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); + this.isCounted = isCounted; + } + getClassName() { + return _VariadicType.ClassName; + } + }; + exports2.VariadicType = VariadicType; + VariadicType.ClassName = "VariadicType"; + var CountedVariadicType = class extends types_1.Type { + constructor(typeParameter) { + super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); + } + getClassName() { + return VariadicType.ClassName; + } + }; + exports2.CountedVariadicType = CountedVariadicType; + CountedVariadicType.ClassName = "VariadicType"; + var VariadicValue = class _VariadicValue extends types_1.TypedValue { + /** + * + * @param type the type of this TypedValue (an instance of VariadicType), not the type parameter of the VariadicType + * @param items the items, having the type type.getFirstTypeParameter() + */ + constructor(type, items) { + super(type); + this.items = items; + } + getClassName() { + return _VariadicValue.ClassName; + } + static fromItems(...items) { + return this.createFromItems(items, false); + } + static fromItemsCounted(...items) { + return this.createFromItems(items, true); + } + static createFromItems(items, isCounted) { + if (items.length == 0) { + return new _VariadicValue(new VariadicType(new types_1.TypePlaceholder(), isCounted), []); + } + const typeParameter = items[0].getType(); + return new _VariadicValue(new VariadicType(typeParameter, isCounted), items); + } + getItems() { + return this.items; + } + valueOf() { + return this.items.map((item) => item.valueOf()); + } + equals(other) { + if (this.getType().differs(other.getType())) { + return false; + } + for (let i2 = 0; i2 < this.items.length; i2++) { + let selfItem = this.items[i2]; + let otherItem = other.items[i2]; + if (!selfItem.equals(otherItem)) { + return false; + } + } + return true; + } + }; + exports2.VariadicValue = VariadicValue; + VariadicValue.ClassName = "VariadicValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js +var require_typeMapper = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeMapper = void 0; + var errors = __importStar2(require_errors()); + var address_1 = require_address2(); + var algebraic_1 = require_algebraic(); + var boolean_1 = require_boolean(); + var bytes_1 = require_bytes(); + var codeMetadata_1 = require_codeMetadata(); + var composite_1 = require_composite(); + var enum_1 = require_enum(); + var fields_1 = require_fields(); + var generic_1 = require_generic(); + var genericArray_1 = require_genericArray(); + var h256_1 = require_h256(); + var nothing_1 = require_nothing(); + var numerical_1 = require_numerical(); + var string_1 = require_string(); + var struct_1 = require_struct(); + var tokenIdentifier_1 = require_tokenIdentifier(); + var tuple_1 = require_tuple(); + var variadic_1 = require_variadic(); + var TypeMapper = class { + constructor(learnedTypes = []) { + this.openTypesFactories = /* @__PURE__ */ new Map([ + ["Option", (...typeParameters) => new generic_1.OptionType(typeParameters[0])], + ["List", (...typeParameters) => new generic_1.ListType(typeParameters[0])], + // For the following open generics, we use a slightly different typing than the one defined by mx-sdk-rs (temporary workaround). + ["VarArgs", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], + ["MultiResultVec", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], + ["variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], + ["counted-variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0], true)], + ["OptionalArg", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], + ["optional", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], + ["OptionalResult", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], + ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + ["MultiArg", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + ["MultiResult", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + // Perhaps we can adjust the ABI generator to only output "tuple", instead of "tupleN"? + ["tuple", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple2", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple3", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple4", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple5", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple6", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple7", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple8", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + // Known-length arrays. + // TODO: Handle these in typeExpressionParser! + ["array2", (...typeParameters) => new genericArray_1.ArrayVecType(2, typeParameters[0])], + ["array8", (...typeParameters) => new genericArray_1.ArrayVecType(8, typeParameters[0])], + ["array16", (...typeParameters) => new genericArray_1.ArrayVecType(16, typeParameters[0])], + ["array20", (...typeParameters) => new genericArray_1.ArrayVecType(20, typeParameters[0])], + ["array32", (...typeParameters) => new genericArray_1.ArrayVecType(32, typeParameters[0])], + ["array46", (...typeParameters) => new genericArray_1.ArrayVecType(46, typeParameters[0])], + ["array48", (...typeParameters) => new genericArray_1.ArrayVecType(48, typeParameters[0])], + ["array64", (...typeParameters) => new genericArray_1.ArrayVecType(64, typeParameters[0])], + ["array128", (...typeParameters) => new genericArray_1.ArrayVecType(128, typeParameters[0])], + ["array256", (...typeParameters) => new genericArray_1.ArrayVecType(256, typeParameters[0])] + ]); + this.closedTypesMap = /* @__PURE__ */ new Map([ + ["u8", new numerical_1.U8Type()], + ["u16", new numerical_1.U16Type()], + ["u32", new numerical_1.U32Type()], + ["u64", new numerical_1.U64Type()], + ["U64", new numerical_1.U64Type()], + ["BigUint", new numerical_1.BigUIntType()], + ["i8", new numerical_1.I8Type()], + ["i16", new numerical_1.I16Type()], + ["i32", new numerical_1.I32Type()], + ["i64", new numerical_1.I64Type()], + ["Bigint", new numerical_1.BigIntType()], + ["BigInt", new numerical_1.BigIntType()], + ["bool", new boolean_1.BooleanType()], + ["bytes", new bytes_1.BytesType()], + ["Address", new address_1.AddressType()], + ["H256", new h256_1.H256Type()], + ["utf-8 string", new string_1.StringType()], + ["TokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], + ["EgldOrEsdtTokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], + ["CodeMetadata", new codeMetadata_1.CodeMetadataType()], + ["nothing", new nothing_1.NothingType()], + ["AsyncCall", new nothing_1.NothingType()] + ]); + this.learnedTypesMap = /* @__PURE__ */ new Map(); + for (const type of learnedTypes) { + this.learnedTypesMap.set(type.getName(), type); + } + } + /** + * Maps a "raw type" object to a "known (specific) type" object. + * In the process, it also learns the new type. + * Can only map types if their dependencies were previously learned (through mapping). + */ + mapType(type) { + let mappedType = this.mapTypeRecursively(type); + if (mappedType) { + if (!mappedType.isGenericType()) { + this.learnType(mappedType); + } + return mappedType; + } + throw new errors.ErrTypingSystem(`Cannot map the type "${type.getName()}" to a known type`); + } + mapTypeRecursively(type) { + let isGeneric = type.isGenericType(); + let previouslyLearnedType = this.learnedTypesMap.get(type.getName()); + if (previouslyLearnedType) { + return previouslyLearnedType; + } + let knownClosedType = this.closedTypesMap.get(type.getName()); + if (knownClosedType) { + return knownClosedType; + } + if (type.hasExactClass(enum_1.EnumType.ClassName)) { + return this.mapEnumType(type); + } + if (type.hasExactClass(struct_1.StructType.ClassName)) { + return this.mapStructType(type); + } + if (isGeneric) { + return this.mapGenericType(type); + } + return null; + } + learnType(type) { + this.learnedTypesMap.delete(type.getName()); + this.learnedTypesMap.set(type.getName(), type); + } + mapStructType(type) { + let mappedFields = this.mappedFields(type.getFieldsDefinitions()); + let mappedStruct = new struct_1.StructType(type.getName(), mappedFields); + return mappedStruct; + } + mapEnumType(type) { + let variants = type.variants.map((variant) => new enum_1.EnumVariantDefinition(variant.name, variant.discriminant, this.mappedFields(variant.getFieldsDefinitions()))); + let mappedEnum = new enum_1.EnumType(type.getName(), variants); + return mappedEnum; + } + mappedFields(definitions) { + return definitions.map((definition) => new fields_1.FieldDefinition(definition.name, definition.description, this.mapType(definition.type))); + } + mapGenericType(type) { + let typeParameters = type.getTypeParameters(); + let mappedTypeParameters = typeParameters.map((item) => this.mapType(item)); + let factory = this.openTypesFactories.get(type.getName()); + if (!factory) { + throw new errors.ErrTypingSystem(`Cannot map the generic type "${type.getName()}" to a known type`); + } + return factory(...mappedTypeParameters); + } + }; + exports2.TypeMapper = TypeMapper; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js +var require_abiRegistry = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbiRegistry = void 0; + var errors = __importStar2(require_errors()); + var utils_1 = require_utils2(); + var endpoint_1 = require_endpoint(); + var enum_1 = require_enum(); + var event_1 = require_event(); + var struct_1 = require_struct(); + var typeMapper_1 = require_typeMapper(); + var interfaceNamePlaceholder = "?"; + var AbiRegistry = class _AbiRegistry { + constructor(options) { + this.endpoints = []; + this.customTypes = []; + this.events = []; + this.name = options.name; + this.constructorDefinition = options.constructorDefinition; + this.endpoints = options.endpoints; + this.customTypes = options.customTypes; + this.events = options.events || []; + } + static create(options) { + const name2 = options.name || interfaceNamePlaceholder; + const constructor = options.constructor || {}; + const endpoints = options.endpoints || []; + const types = options.types || {}; + const events = options.events || []; + const constructorDefinition = endpoint_1.EndpointDefinition.fromJSON({ name: "constructor", ...constructor }); + const endpointDefinitions = endpoints.map((item) => endpoint_1.EndpointDefinition.fromJSON(item)); + const customTypes = []; + for (const customTypeName in types) { + const typeDefinition = types[customTypeName]; + if (typeDefinition.type == "struct") { + customTypes.push(struct_1.StructType.fromJSON({ name: customTypeName, fields: typeDefinition.fields })); + } else if (typeDefinition.type == "enum" || typeDefinition.type == "explicit-enum") { + customTypes.push(enum_1.EnumType.fromJSON({ name: customTypeName, variants: typeDefinition.variants })); + } else { + throw new errors.ErrTypingSystem(`Cannot handle custom type: ${customTypeName}`); + } + } + const eventDefinitions = events.map((item) => event_1.EventDefinition.fromJSON(item)); + const registry = new _AbiRegistry({ + name: name2, + constructorDefinition, + endpoints: endpointDefinitions, + customTypes, + events: eventDefinitions + }); + const remappedRegistry = registry.remapToKnownTypes(); + return remappedRegistry; + } + getCustomType(name2) { + const result = this.customTypes.find((e2) => e2.getName() == name2); + utils_1.guardValueIsSetWithMessage(`custom type [${name2}] not found`, result); + return result; + } + getStruct(name2) { + const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(struct_1.StructType.ClassName)); + utils_1.guardValueIsSetWithMessage(`struct [${name2}] not found`, result); + return result; + } + getStructs(names) { + return names.map((name2) => this.getStruct(name2)); + } + getEnum(name2) { + const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(enum_1.EnumType.ClassName)); + utils_1.guardValueIsSetWithMessage(`enum [${name2}] not found`, result); + return result; + } + getEnums(names) { + return names.map((name2) => this.getEnum(name2)); + } + getEndpoints() { + return this.endpoints; + } + getEndpoint(name2) { + const result = this.endpoints.find((e2) => e2.name == name2); + utils_1.guardValueIsSetWithMessage(`endpoint [${name2}] not found`, result); + return result; + } + getEvent(name2) { + const result = this.events.find((e2) => e2.identifier == name2); + utils_1.guardValueIsSetWithMessage(`event [${name2}] not found`, result); + return result; + } + /** + * Right after loading ABI definitions into a registry, the endpoints and the custom types (structs, enums) + * use raw types for their I/O parameters (in the case of endpoints), or for their fields (in the case of structs). + * + * A raw type is merely an instance of {@link Type}, with a given name and type parameters (if it's a generic type). + * + * Though, for most (development) purposes, we'd like to operate using known, specific types (e.g. {@link List}, {@link U8Type} etc.). + * This function increases the specificity of the types used by parameter / field definitions within a registry (on best-efforts basis). + * The result is an equivalent, more explicit ABI registry. + */ + remapToKnownTypes() { + const mapper = new typeMapper_1.TypeMapper([]); + const newCustomTypes = []; + for (const type of this.customTypes) { + this.mapCustomTypeDepthFirst(type, this.customTypes, mapper, newCustomTypes); + } + if (this.customTypes.length != newCustomTypes.length) { + throw new errors.ErrTypingSystem("Did not re-map all custom types"); + } + const newConstructor = mapEndpoint(this.constructorDefinition, mapper); + const newEndpoints = []; + for (const endpoint of this.endpoints) { + newEndpoints.push(mapEndpoint(endpoint, mapper)); + } + const newEvents = this.events.map((event) => mapEvent(event, mapper)); + const newRegistry = new _AbiRegistry({ + name: this.name, + constructorDefinition: newConstructor, + endpoints: newEndpoints, + customTypes: newCustomTypes, + events: newEvents + }); + return newRegistry; + } + mapCustomTypeDepthFirst(typeToMap, allTypesToMap, mapper, mappedTypes) { + const hasBeenMapped = mappedTypes.findIndex((type) => type.getName() == typeToMap.getName()) >= 0; + if (hasBeenMapped) { + return; + } + for (const typeName of typeToMap.getNamesOfDependencies()) { + const dependencyType = allTypesToMap.find((type) => type.getName() == typeName); + if (!dependencyType) { + continue; + } + this.mapCustomTypeDepthFirst(dependencyType, allTypesToMap, mapper, mappedTypes); + } + const mappedType = mapper.mapType(typeToMap); + mappedTypes.push(mappedType); + } + }; + exports2.AbiRegistry = AbiRegistry; + function mapEndpoint(endpoint, mapper) { + const newInput = endpoint.input.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); + const newOutput = endpoint.output.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); + return new endpoint_1.EndpointDefinition(endpoint.name, newInput, newOutput, endpoint.modifiers); + } + function mapEvent(event, mapper) { + const newInputs = event.inputs.map((e2) => new event_1.EventTopicDefinition({ + name: e2.name, + type: mapper.mapType(e2.type), + indexed: e2.indexed + })); + return new event_1.EventDefinition(event.identifier, newInputs); + } + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js +var require_factory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createListOfTokenIdentifiers = exports2.createListOfAddresses = void 0; + var address_1 = require_address2(); + var generic_1 = require_generic(); + var tokenIdentifier_1 = require_tokenIdentifier(); + function createListOfAddresses(addresses) { + let addressesTyped = addresses.map((address) => new address_1.AddressValue(address)); + let list = generic_1.List.fromItems(addressesTyped); + return list; + } + exports2.createListOfAddresses = createListOfAddresses; + function createListOfTokenIdentifiers(identifiers) { + let identifiersTyped = identifiers.map((identifier) => new tokenIdentifier_1.TokenIdentifierValue(identifier)); + let list = generic_1.List.fromItems(identifiersTyped); + return list; + } + exports2.createListOfTokenIdentifiers = createListOfTokenIdentifiers; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js +var require_matchers = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.onPrimitiveTypeSelect = exports2.onPrimitiveValueSelect = exports2.onTypedValueSelect = exports2.onTypeSelect = void 0; + var errors = __importStar2(require_errors()); + var address_1 = require_address2(); + var boolean_1 = require_boolean(); + var bytes_1 = require_bytes(); + var enum_1 = require_enum(); + var generic_1 = require_generic(); + var h256_1 = require_h256(); + var numerical_1 = require_numerical(); + var nothing_1 = require_nothing(); + var struct_1 = require_struct(); + var tokenIdentifier_1 = require_tokenIdentifier(); + var tuple_1 = require_tuple(); + var types_1 = require_types(); + var genericArray_1 = require_genericArray(); + var string_1 = require_string(); + function onTypeSelect(type, selectors) { + if (type.hasExactClass(generic_1.OptionType.ClassName)) { + return selectors.onOption(); + } + if (type.hasExactClass(generic_1.ListType.ClassName)) { + return selectors.onList(); + } + if (type.hasExactClass(genericArray_1.ArrayVecType.ClassName)) { + return selectors.onArray(); + } + if (type.hasClassOrSuperclass(types_1.PrimitiveType.ClassName)) { + return selectors.onPrimitive(); + } + if (type.hasExactClass(struct_1.StructType.ClassName)) { + return selectors.onStruct(); + } + if (type.hasExactClass(tuple_1.TupleType.ClassName)) { + return selectors.onTuple(); + } + if (type.hasExactClass(enum_1.EnumType.ClassName)) { + return selectors.onEnum(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`type isn't known: ${type}`); + } + exports2.onTypeSelect = onTypeSelect; + function onTypedValueSelect(value, selectors) { + if (value.hasClassOrSuperclass(types_1.PrimitiveValue.ClassName)) { + return selectors.onPrimitive(); + } + if (value.hasExactClass(generic_1.OptionValue.ClassName)) { + return selectors.onOption(); + } + if (value.hasExactClass(generic_1.List.ClassName)) { + return selectors.onList(); + } + if (value.hasExactClass(genericArray_1.ArrayVec.ClassName)) { + return selectors.onArray(); + } + if (value.hasExactClass(struct_1.Struct.ClassName)) { + return selectors.onStruct(); + } + if (value.hasExactClass(tuple_1.Tuple.ClassName)) { + return selectors.onTuple(); + } + if (value.hasExactClass(enum_1.EnumValue.ClassName)) { + return selectors.onEnum(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`value isn't typed: ${value}`); + } + exports2.onTypedValueSelect = onTypedValueSelect; + function onPrimitiveValueSelect(value, selectors) { + if (value.hasExactClass(boolean_1.BooleanValue.ClassName)) { + return selectors.onBoolean(); + } + if (value.hasClassOrSuperclass(numerical_1.NumericalValue.ClassName)) { + return selectors.onNumerical(); + } + if (value.hasExactClass(address_1.AddressValue.ClassName)) { + return selectors.onAddress(); + } + if (value.hasExactClass(bytes_1.BytesValue.ClassName)) { + return selectors.onBytes(); + } + if (value.hasExactClass(string_1.StringValue.ClassName)) { + return selectors.onString(); + } + if (value.hasExactClass(h256_1.H256Value.ClassName)) { + return selectors.onH256(); + } + if (value.hasExactClass(tokenIdentifier_1.TokenIdentifierValue.ClassName)) { + return selectors.onTypeIdentifier(); + } + if (value.hasExactClass(nothing_1.NothingValue.ClassName)) { + return selectors.onNothing(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`value isn't a primitive: ${value.getType()}`); + } + exports2.onPrimitiveValueSelect = onPrimitiveValueSelect; + function onPrimitiveTypeSelect(type, selectors) { + if (type.hasExactClass(boolean_1.BooleanType.ClassName)) { + return selectors.onBoolean(); + } + if (type.hasClassOrSuperclass(numerical_1.NumericalType.ClassName)) { + return selectors.onNumerical(); + } + if (type.hasExactClass(address_1.AddressType.ClassName)) { + return selectors.onAddress(); + } + if (type.hasExactClass(bytes_1.BytesType.ClassName)) { + return selectors.onBytes(); + } + if (type.hasExactClass(string_1.StringType.ClassName)) { + return selectors.onString(); + } + if (type.hasExactClass(h256_1.H256Type.ClassName)) { + return selectors.onH256(); + } + if (type.hasExactClass(tokenIdentifier_1.TokenIdentifierType.ClassName)) { + return selectors.onTokenIndetifier(); + } + if (type.hasExactClass(nothing_1.NothingType.ClassName)) { + return selectors.onNothing(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`type isn't a known primitive: ${type}`); + } + exports2.onPrimitiveTypeSelect = onPrimitiveTypeSelect; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js +var require_typesystem = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_abiRegistry(), exports2); + __exportStar2(require_address2(), exports2); + __exportStar2(require_algebraic(), exports2); + __exportStar2(require_boolean(), exports2); + __exportStar2(require_bytes(), exports2); + __exportStar2(require_composite(), exports2); + __exportStar2(require_endpoint(), exports2); + __exportStar2(require_enum(), exports2); + __exportStar2(require_factory(), exports2); + __exportStar2(require_fields(), exports2); + __exportStar2(require_generic(), exports2); + __exportStar2(require_genericArray(), exports2); + __exportStar2(require_h256(), exports2); + __exportStar2(require_matchers(), exports2); + __exportStar2(require_nothing(), exports2); + __exportStar2(require_numerical(), exports2); + __exportStar2(require_string(), exports2); + __exportStar2(require_struct(), exports2); + __exportStar2(require_tokenIdentifier(), exports2); + __exportStar2(require_tuple(), exports2); + __exportStar2(require_typeExpressionParser(), exports2); + __exportStar2(require_typeMapper(), exports2); + __exportStar2(require_types(), exports2); + __exportStar2(require_variadic(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js +var require_option = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OptionValueBinaryCodec = void 0; + var errors = __importStar2(require_errors()); + var typesystem_1 = require_typesystem(); + var OptionValueBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, type) { + if (buffer[0] == 0) { + return [typesystem_1.OptionValue.newMissingTyped(type), 1]; + } + if (buffer[0] != 1) { + throw new errors.ErrCodec("invalid buffer for optional value"); + } + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); + return [typesystem_1.OptionValue.newProvided(decoded), decodedLength + 1]; + } + decodeTopLevel(buffer, type) { + if (buffer.length == 0) { + return new typesystem_1.OptionValue(type); + } + if (buffer[0] != 1) { + throw new errors.ErrCodec("invalid buffer for optional value"); + } + let [decoded, _decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); + return new typesystem_1.OptionValue(type, decoded); + } + encodeNested(optionValue) { + if (optionValue.isSet()) { + return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); + } + return import_buffer.Buffer.from([0]); + } + encodeTopLevel(optionValue) { + if (optionValue.isSet()) { + return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); + } + return import_buffer.Buffer.from([]); + } + }; + exports2.OptionValueBinaryCodec = OptionValueBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js +var require_address3 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AddressBinaryCodec = void 0; + var address_1 = require_address(); + var typesystem_1 = require_typesystem(); + var AddressBinaryCodec = class { + /** + * Reads and decodes an AddressValue from a given buffer. + * + * @param buffer the input buffer + */ + decodeNested(buffer) { + let slice = buffer.slice(0, 32); + let value = new address_1.Address(slice); + return [new typesystem_1.AddressValue(value), 32]; + } + /** + * Reads and decodes an AddressValue from a given buffer. + * + * @param buffer the input buffer + */ + decodeTopLevel(buffer) { + let [decoded, _length] = this.decodeNested(buffer); + return decoded; + } + /** + * Encodes an AddressValue to a buffer. + */ + encodeNested(primitive) { + return primitive.valueOf().pubkey(); + } + /** + * Encodes an AddressValue to a buffer. + */ + encodeTopLevel(primitive) { + return primitive.valueOf().pubkey(); + } + }; + exports2.AddressBinaryCodec = AddressBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js +var require_boolean2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BooleanBinaryCodec = void 0; + var errors = __importStar2(require_errors()); + var typesystem_1 = require_typesystem(); + var BooleanBinaryCodec = class _BooleanBinaryCodec { + decodeNested(buffer) { + let byte = buffer.readUInt8(0); + return [new typesystem_1.BooleanValue(byte == _BooleanBinaryCodec.TRUE), 1]; + } + decodeTopLevel(buffer) { + if (buffer.length > 1) { + throw new errors.ErrInvalidArgument("buffer should be of size <= 1"); + } + let firstByte = buffer[0]; + return new typesystem_1.BooleanValue(firstByte == _BooleanBinaryCodec.TRUE); + } + encodeNested(primitive) { + if (primitive.isTrue()) { + return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); + } + return import_buffer.Buffer.from([_BooleanBinaryCodec.FALSE]); + } + encodeTopLevel(primitive) { + if (primitive.isTrue()) { + return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); + } + return import_buffer.Buffer.from([]); + } + }; + exports2.BooleanBinaryCodec = BooleanBinaryCodec; + BooleanBinaryCodec.TRUE = 1; + BooleanBinaryCodec.FALSE = 0; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js +var require_constants2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SizeOfU32 = void 0; + exports2.SizeOfU32 = 4; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js +var require_numerical2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NumericalBinaryCodec = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var typesystem_1 = require_typesystem(); + var constants_1 = require_constants2(); + var utils_1 = require_utils(); + var NumericalBinaryCodec = class { + decodeNested(buffer, type) { + let offset = 0; + let length2 = type.sizeInBytes; + if (!length2) { + offset = constants_1.SizeOfU32; + length2 = buffer.readUInt32BE(0); + } + let payload = buffer.slice(offset, offset + length2); + let result = this.decodeTopLevel(payload, type); + let decodedLength = length2 + offset; + return [result, decodedLength]; + } + decodeTopLevel(buffer, type) { + let payload = utils_1.cloneBuffer(buffer); + let empty2 = buffer.length == 0; + if (empty2) { + return new typesystem_1.NumericalValue(type, new bignumber_js_1.default(0)); + } + let isPositive = !type.withSign || utils_1.isMsbZero(payload); + if (isPositive) { + let value2 = utils_1.bufferToBigInt(payload); + return new typesystem_1.NumericalValue(type, value2); + } + utils_1.flipBufferBitsInPlace(payload); + let value = utils_1.bufferToBigInt(payload); + let negativeValue = value.multipliedBy(new bignumber_js_1.default(-1)); + let negativeValueMinusOne = negativeValue.minus(new bignumber_js_1.default(1)); + return new typesystem_1.NumericalValue(type, negativeValueMinusOne); + } + encodeNested(primitive) { + if (primitive.sizeInBytes) { + return this.encodeNestedFixedSize(primitive, primitive.sizeInBytes); + } + let buffer = this.encodeTopLevel(primitive); + let length2 = import_buffer.Buffer.alloc(constants_1.SizeOfU32); + length2.writeUInt32BE(buffer.length); + return import_buffer.Buffer.concat([length2, buffer]); + } + encodeNestedFixedSize(primitive, size) { + if (primitive.value.isZero()) { + return import_buffer.Buffer.alloc(size, 0); + } + if (!primitive.withSign) { + const buffer2 = utils_1.bigIntToBuffer(primitive.value); + const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); + return import_buffer.Buffer.concat([paddingBytes2, buffer2]); + } + if (primitive.value.isPositive()) { + let buffer2 = utils_1.bigIntToBuffer(primitive.value); + if (utils_1.isMsbOne(buffer2)) { + buffer2 = utils_1.prependByteToBuffer(buffer2, 0); + } + const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); + return import_buffer.Buffer.concat([paddingBytes2, buffer2]); + } + let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); + let buffer = utils_1.bigIntToBuffer(valuePlusOne); + utils_1.flipBufferBitsInPlace(buffer); + if (utils_1.isMsbZero(buffer)) { + buffer = utils_1.prependByteToBuffer(buffer, 255); + } + const paddingBytes = import_buffer.Buffer.alloc(size - buffer.length, 255); + return import_buffer.Buffer.concat([paddingBytes, buffer]); + } + encodeTopLevel(primitive) { + let withSign = primitive.withSign; + if (primitive.value.isZero()) { + return import_buffer.Buffer.alloc(0); + } + if (!withSign) { + return utils_1.bigIntToBuffer(primitive.value); + } + return this.encodePrimitive(primitive); + } + encodePrimitive(primitive) { + if (primitive.value.isPositive()) { + let buffer2 = utils_1.bigIntToBuffer(primitive.value); + if (utils_1.isMsbOne(buffer2)) { + buffer2 = utils_1.prependByteToBuffer(buffer2, 0); + } + return buffer2; + } + let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); + let buffer = utils_1.bigIntToBuffer(valuePlusOne); + utils_1.flipBufferBitsInPlace(buffer); + if (utils_1.isMsbZero(buffer)) { + buffer = utils_1.prependByteToBuffer(buffer, 255); + } + return buffer; + } + }; + exports2.NumericalBinaryCodec = NumericalBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js +var require_h2562 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.H256BinaryCodec = void 0; + var h256_1 = require_h256(); + var H256BinaryCodec = class { + /** + * Reads and decodes a H256Value from a given buffer. + * + * @param buffer the input buffer + */ + decodeNested(buffer) { + let slice = buffer.slice(0, 32); + return [new h256_1.H256Value(slice), 32]; + } + /** + * Reads and decodes a H256Value from a given buffer. + * + * @param buffer the input buffer + */ + decodeTopLevel(buffer) { + let [decoded, _length] = this.decodeNested(buffer); + return decoded; + } + /** + * Encodes a H256Value to a buffer. + */ + encodeNested(primitive) { + return primitive.valueOf(); + } + /** + * Encodes a H256Value to a buffer. + */ + encodeTopLevel(primitive) { + return primitive.valueOf(); + } + }; + exports2.H256BinaryCodec = H256BinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js +var require_bytes2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesBinaryCodec = void 0; + var bytes_1 = require_bytes(); + var constants_1 = require_constants2(); + var BytesBinaryCodec = class { + decodeNested(buffer) { + let length2 = buffer.readUInt32BE(0); + let payload = buffer.slice(constants_1.SizeOfU32, constants_1.SizeOfU32 + length2); + let result = new bytes_1.BytesValue(payload); + return [result, constants_1.SizeOfU32 + length2]; + } + decodeTopLevel(buffer) { + return new bytes_1.BytesValue(buffer); + } + encodeNested(bytes) { + let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); + lengthBuffer.writeUInt32BE(bytes.getLength()); + let buffer = import_buffer.Buffer.concat([lengthBuffer, bytes.valueOf()]); + return buffer; + } + encodeTopLevel(bytes) { + return bytes.valueOf(); + } + }; + exports2.BytesBinaryCodec = BytesBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js +var require_tokenIdentifier2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenIdentifierCodec = void 0; + var bytes_1 = require_bytes(); + var tokenIdentifier_1 = require_tokenIdentifier(); + var bytes_2 = require_bytes2(); + var TokenIdentifierCodec = class { + constructor() { + this.bytesCodec = new bytes_2.BytesBinaryCodec(); + } + decodeNested(buffer) { + let [bytesValue, length2] = this.bytesCodec.decodeNested(buffer); + return [new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()), length2]; + } + decodeTopLevel(buffer) { + let bytesValue = this.bytesCodec.decodeTopLevel(buffer); + return new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()); + } + encodeNested(tokenIdentifier) { + let bytesValue = bytes_1.BytesValue.fromUTF8(tokenIdentifier.valueOf()); + return this.bytesCodec.encodeNested(bytesValue); + } + encodeTopLevel(tokenIdentifier) { + return import_buffer.Buffer.from(tokenIdentifier.valueOf()); + } + }; + exports2.TokenIdentifierCodec = TokenIdentifierCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js +var require_nothing2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NothingCodec = void 0; + var typesystem_1 = require_typesystem(); + var NothingCodec = class { + decodeNested() { + return [new typesystem_1.NothingValue(), 0]; + } + decodeTopLevel() { + return new typesystem_1.NothingValue(); + } + encodeNested() { + return import_buffer.Buffer.from([]); + } + encodeTopLevel() { + return import_buffer.Buffer.from([]); + } + }; + exports2.NothingCodec = NothingCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js +var require_string2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StringBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var bytes_1 = require_bytes(); + var bytes_2 = require_bytes2(); + var StringBinaryCodec = class { + constructor() { + this.bytesBinaryCodec = new bytes_2.BytesBinaryCodec(); + } + decodeNested(buffer) { + let [decoded, length2] = this.bytesBinaryCodec.decodeNested(buffer); + let decodedAsString = new typesystem_1.StringValue(decoded.valueOf().toString()); + return [decodedAsString, length2]; + } + decodeTopLevel(buffer) { + return new typesystem_1.StringValue(buffer.toString()); + } + encodeNested(value) { + let valueAsBytes = bytes_1.BytesValue.fromUTF8(value.valueOf()); + return this.bytesBinaryCodec.encodeNested(valueAsBytes); + } + encodeTopLevel(value) { + return import_buffer.Buffer.from(value.valueOf()); + } + }; + exports2.StringBinaryCodec = StringBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js +var require_primitive = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PrimitiveBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var address_1 = require_address3(); + var boolean_1 = require_boolean2(); + var numerical_1 = require_numerical2(); + var h256_1 = require_h2562(); + var bytes_1 = require_bytes2(); + var tokenIdentifier_1 = require_tokenIdentifier2(); + var nothing_1 = require_nothing2(); + var string_1 = require_string2(); + var PrimitiveBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + this.booleanCodec = new boolean_1.BooleanBinaryCodec(); + this.numericalCodec = new numerical_1.NumericalBinaryCodec(); + this.addressCodec = new address_1.AddressBinaryCodec(); + this.h256Codec = new h256_1.H256BinaryCodec(); + this.bytesCodec = new bytes_1.BytesBinaryCodec(); + this.stringCodec = new string_1.StringBinaryCodec(); + this.tokenIdentifierCodec = new tokenIdentifier_1.TokenIdentifierCodec(); + this.nothingCodec = new nothing_1.NothingCodec(); + } + decodeNested(buffer, type) { + return typesystem_1.onPrimitiveTypeSelect(type, { + onBoolean: () => this.booleanCodec.decodeNested(buffer), + onNumerical: () => this.numericalCodec.decodeNested(buffer, type), + onAddress: () => this.addressCodec.decodeNested(buffer), + onBytes: () => this.bytesCodec.decodeNested(buffer), + onString: () => this.stringCodec.decodeNested(buffer), + onH256: () => this.h256Codec.decodeNested(buffer), + onTokenIndetifier: () => this.tokenIdentifierCodec.decodeNested(buffer), + onNothing: () => this.nothingCodec.decodeNested() + }); + } + decodeTopLevel(buffer, type) { + return typesystem_1.onPrimitiveTypeSelect(type, { + onBoolean: () => this.booleanCodec.decodeTopLevel(buffer), + onNumerical: () => this.numericalCodec.decodeTopLevel(buffer, type), + onAddress: () => this.addressCodec.decodeTopLevel(buffer), + onBytes: () => this.bytesCodec.decodeTopLevel(buffer), + onString: () => this.stringCodec.decodeTopLevel(buffer), + onH256: () => this.h256Codec.decodeTopLevel(buffer), + onTokenIndetifier: () => this.tokenIdentifierCodec.decodeTopLevel(buffer), + onNothing: () => this.nothingCodec.decodeTopLevel() + }); + } + encodeNested(value) { + return typesystem_1.onPrimitiveValueSelect(value, { + onBoolean: () => this.booleanCodec.encodeNested(value), + onNumerical: () => this.numericalCodec.encodeNested(value), + onAddress: () => this.addressCodec.encodeNested(value), + onBytes: () => this.bytesCodec.encodeNested(value), + onString: () => this.stringCodec.encodeNested(value), + onH256: () => this.h256Codec.encodeNested(value), + onTypeIdentifier: () => this.tokenIdentifierCodec.encodeNested(value), + onNothing: () => this.nothingCodec.encodeNested() + }); + } + encodeTopLevel(value) { + return typesystem_1.onPrimitiveValueSelect(value, { + onBoolean: () => this.booleanCodec.encodeTopLevel(value), + onNumerical: () => this.numericalCodec.encodeTopLevel(value), + onAddress: () => this.addressCodec.encodeTopLevel(value), + onBytes: () => this.bytesCodec.encodeTopLevel(value), + onString: () => this.stringCodec.encodeTopLevel(value), + onH256: () => this.h256Codec.encodeTopLevel(value), + onTypeIdentifier: () => this.tokenIdentifierCodec.encodeTopLevel(value), + onNothing: () => this.nothingCodec.encodeTopLevel() + }); + } + }; + exports2.PrimitiveBinaryCodec = PrimitiveBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js +var require_list = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ListBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var constants_1 = require_constants2(); + var ListBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, type) { + let typeParameter = type.getFirstTypeParameter(); + let result = []; + let numItems = buffer.readUInt32BE(0); + this.binaryCodec.constraints.checkListLength(numItems); + let originalBuffer = buffer; + let offset = constants_1.SizeOfU32; + buffer = originalBuffer.slice(offset); + for (let i2 = 0; i2 < numItems; i2++) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); + result.push(decoded); + offset += decodedLength; + buffer = originalBuffer.slice(offset); + } + return [new typesystem_1.List(type, result), offset]; + } + decodeTopLevel(buffer, type) { + let typeParameter = type.getFirstTypeParameter(); + let result = []; + let originalBuffer = buffer; + let offset = 0; + while (buffer.length > 0) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); + result.push(decoded); + offset += decodedLength; + buffer = originalBuffer.slice(offset); + this.binaryCodec.constraints.checkListLength(result.length); + } + return new typesystem_1.List(type, result); + } + encodeNested(list) { + this.binaryCodec.constraints.checkListLength(list.getLength()); + let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); + lengthBuffer.writeUInt32BE(list.getLength()); + let itemsBuffers = []; + for (const item of list.getItems()) { + let itemBuffer = this.binaryCodec.encodeNested(item); + itemsBuffers.push(itemBuffer); + } + let buffer = import_buffer.Buffer.concat([lengthBuffer, ...itemsBuffers]); + return buffer; + } + encodeTopLevel(list) { + this.binaryCodec.constraints.checkListLength(list.getLength()); + let itemsBuffers = []; + for (const item of list.getItems()) { + let itemBuffer = this.binaryCodec.encodeNested(item); + itemsBuffers.push(itemBuffer); + } + let buffer = import_buffer.Buffer.concat(itemsBuffers); + return buffer; + } + }; + exports2.ListBinaryCodec = ListBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js +var require_fields2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FieldsBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var FieldsBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, fieldDefinitions) { + let fields = []; + let totalLength = 0; + for (const fieldDefinition of fieldDefinitions) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, fieldDefinition.type); + buffer = buffer.slice(decodedLength); + totalLength += decodedLength; + let field = new typesystem_1.Field(decoded, fieldDefinition.name); + fields.push(field); + } + return [fields, totalLength]; + } + encodeNested(fields) { + let buffers = []; + for (const field of fields) { + let fieldBuffer = this.binaryCodec.encodeNested(field.value); + buffers.push(fieldBuffer); + } + return import_buffer.Buffer.concat(buffers); + } + }; + exports2.FieldsBinaryCodec = FieldsBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js +var require_struct2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StructBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var fields_1 = require_fields2(); + var StructBinaryCodec = class { + constructor(binaryCodec) { + this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); + } + decodeTopLevel(buffer, type) { + let [decoded] = this.decodeNested(buffer, type); + return decoded; + } + decodeNested(buffer, type) { + let fieldDefinitions = type.getFieldsDefinitions(); + let [fields, offset] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); + let struct = new typesystem_1.Struct(type, fields); + return [struct, offset]; + } + encodeNested(struct) { + let fields = struct.getFields(); + let buffer = this.fieldsCodec.encodeNested(fields); + return buffer; + } + encodeTopLevel(struct) { + return this.encodeNested(struct); + } + }; + exports2.StructBinaryCodec = StructBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js +var require_enum2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EnumBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var fields_1 = require_fields2(); + var EnumBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); + } + decodeTopLevel(buffer, type) { + let [enumValue] = this.decodeNested(buffer, type); + return enumValue; + } + decodeNested(buffer, type) { + let [discriminant, lengthOfDiscriminant] = this.readDiscriminant(buffer); + buffer = buffer.slice(lengthOfDiscriminant); + let variant = type.getVariantByDiscriminant(discriminant); + let fieldDefinitions = variant.getFieldsDefinitions(); + let [fields, lengthOfFields] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); + let enumValue = new typesystem_1.EnumValue(type, variant, fields); + return [enumValue, lengthOfDiscriminant + lengthOfFields]; + } + readDiscriminant(buffer) { + let [value, length2] = this.binaryCodec.decodeNested(buffer, new typesystem_1.U8Type()); + let discriminant = value.valueOf(); + return [discriminant, length2]; + } + encodeNested(enumValue) { + let discriminant = new typesystem_1.U8Value(enumValue.discriminant); + let discriminantBuffer = this.binaryCodec.encodeNested(discriminant); + let fields = enumValue.getFields(); + let fieldsBuffer = this.fieldsCodec.encodeNested(fields); + return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); + } + encodeTopLevel(enumValue) { + let fields = enumValue.getFields(); + let hasFields = fields.length > 0; + let fieldsBuffer = this.fieldsCodec.encodeNested(fields); + let discriminant = new typesystem_1.U8Value(enumValue.discriminant); + let discriminantBuffer = hasFields ? this.binaryCodec.encodeNested(discriminant) : this.binaryCodec.encodeTopLevel(discriminant); + return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); + } + }; + exports2.EnumBinaryCodec = EnumBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js +var require_tuple2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TupleBinaryCodec = void 0; + var struct_1 = require_struct2(); + var TupleBinaryCodec = class { + constructor(binaryCodec) { + this.structCodec = new struct_1.StructBinaryCodec(binaryCodec); + } + decodeTopLevel(buffer, type) { + return this.structCodec.decodeTopLevel(buffer, type); + } + decodeNested(buffer, type) { + return this.structCodec.decodeNested(buffer, type); + } + encodeNested(struct) { + return this.structCodec.encodeNested(struct); + } + encodeTopLevel(struct) { + return this.structCodec.encodeTopLevel(struct); + } + }; + exports2.TupleBinaryCodec = TupleBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js +var require_arrayVec = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArrayVecBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var ArrayVecBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, type) { + let arrayLength = type.length; + let typeParameter = type.getFirstTypeParameter(); + let result = []; + let totalLength = 0; + for (let i2 = 0; i2 < arrayLength; i2++) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); + result.push(decoded); + totalLength += decodedLength; + buffer = buffer.slice(decodedLength); + } + return [new typesystem_1.ArrayVec(type, result), totalLength]; + } + decodeTopLevel(buffer, type) { + let [result, _4] = this.decodeNested(buffer, type); + return result; + } + encodeNested(array) { + let itemsBuffers = []; + for (const item of array.getItems()) { + let itemBuffer = this.binaryCodec.encodeNested(item); + itemsBuffers.push(itemBuffer); + } + return import_buffer.Buffer.concat(itemsBuffers); + } + encodeTopLevel(array) { + return this.encodeNested(array); + } + }; + exports2.ArrayVecBinaryCodec = ArrayVecBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js +var require_binary = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryCodecConstraints = exports2.BinaryCodec = void 0; + var errors = __importStar2(require_errors()); + var typesystem_1 = require_typesystem(); + var utils_1 = require_utils2(); + var option_1 = require_option(); + var primitive_1 = require_primitive(); + var list_1 = require_list(); + var struct_1 = require_struct2(); + var enum_1 = require_enum2(); + var tuple_1 = require_tuple2(); + var arrayVec_1 = require_arrayVec(); + var BinaryCodec = class { + constructor(constraints = null) { + this.constraints = constraints || new BinaryCodecConstraints(); + this.optionCodec = new option_1.OptionValueBinaryCodec(this); + this.listCodec = new list_1.ListBinaryCodec(this); + this.arrayCodec = new arrayVec_1.ArrayVecBinaryCodec(this); + this.primitiveCodec = new primitive_1.PrimitiveBinaryCodec(this); + this.structCodec = new struct_1.StructBinaryCodec(this); + this.tupleCodec = new tuple_1.TupleBinaryCodec(this); + this.enumCodec = new enum_1.EnumBinaryCodec(this); + } + decodeTopLevel(buffer, type) { + this.constraints.checkBufferLength(buffer); + let typedValue = typesystem_1.onTypeSelect(type, { + onOption: () => this.optionCodec.decodeTopLevel(buffer, type.getFirstTypeParameter()), + onList: () => this.listCodec.decodeTopLevel(buffer, type), + onArray: () => this.arrayCodec.decodeTopLevel(buffer, type), + onPrimitive: () => this.primitiveCodec.decodeTopLevel(buffer, type), + onStruct: () => this.structCodec.decodeTopLevel(buffer, type), + onTuple: () => this.tupleCodec.decodeTopLevel(buffer, type), + onEnum: () => this.enumCodec.decodeTopLevel(buffer, type) + }); + return typedValue; + } + decodeNested(buffer, type) { + this.constraints.checkBufferLength(buffer); + let [typedResult, decodedLength] = typesystem_1.onTypeSelect(type, { + onOption: () => this.optionCodec.decodeNested(buffer, type.getFirstTypeParameter()), + onList: () => this.listCodec.decodeNested(buffer, type), + onArray: () => this.arrayCodec.decodeNested(buffer, type), + onPrimitive: () => this.primitiveCodec.decodeNested(buffer, type), + onStruct: () => this.structCodec.decodeNested(buffer, type), + onTuple: () => this.tupleCodec.decodeNested(buffer, type), + onEnum: () => this.enumCodec.decodeNested(buffer, type) + }); + return [typedResult, decodedLength]; + } + encodeNested(typedValue) { + utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); + return typesystem_1.onTypedValueSelect(typedValue, { + onPrimitive: () => this.primitiveCodec.encodeNested(typedValue), + onOption: () => this.optionCodec.encodeNested(typedValue), + onList: () => this.listCodec.encodeNested(typedValue), + onArray: () => this.arrayCodec.encodeNested(typedValue), + onStruct: () => this.structCodec.encodeNested(typedValue), + onTuple: () => this.tupleCodec.encodeNested(typedValue), + onEnum: () => this.enumCodec.encodeNested(typedValue) + }); + } + encodeTopLevel(typedValue) { + utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); + return typesystem_1.onTypedValueSelect(typedValue, { + onPrimitive: () => this.primitiveCodec.encodeTopLevel(typedValue), + onOption: () => this.optionCodec.encodeTopLevel(typedValue), + onList: () => this.listCodec.encodeTopLevel(typedValue), + onArray: () => this.arrayCodec.encodeTopLevel(typedValue), + onStruct: () => this.structCodec.encodeTopLevel(typedValue), + onTuple: () => this.tupleCodec.encodeTopLevel(typedValue), + onEnum: () => this.enumCodec.encodeTopLevel(typedValue) + }); + } + }; + exports2.BinaryCodec = BinaryCodec; + var BinaryCodecConstraints = class { + constructor(init) { + this.maxBufferLength = init?.maxBufferLength || 256e3; + this.maxListLength = init?.maxListLength || 128e3; + } + checkBufferLength(buffer) { + if (buffer.length > this.maxBufferLength) { + throw new errors.ErrCodec(`Buffer too large: ${buffer.length} > ${this.maxBufferLength}`); + } + } + /** + * This constraint avoids computer-freezing decode bugs (e.g. due to invalid ABI or struct definitions). + */ + checkListLength(length2) { + if (length2 > this.maxListLength) { + throw new errors.ErrCodec(`List too large: ${length2} > ${this.maxListLength}`); + } + } + }; + exports2.BinaryCodecConstraints = BinaryCodecConstraints; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js +var require_binaryCodecUtils = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decodeBigNumber = exports2.decodeString = exports2.decodeBool = exports2.decodeUnsignedNumber = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var typesystem_1 = require_typesystem(); + var binary_1 = require_binary(); + var Codec2 = new binary_1.BinaryCodec(); + function decodeUnsignedNumber(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); + let raw = Number(value.valueOf()); + return raw; + } + exports2.decodeUnsignedNumber = decodeUnsignedNumber; + function decodeBool(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BooleanType()); + let raw = Boolean(value.valueOf()); + return raw; + } + exports2.decodeBool = decodeBool; + function decodeString(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BytesType()); + let raw = String(value.valueOf()); + return raw; + } + exports2.decodeString = decodeString; + function decodeBigNumber(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); + let raw = new bignumber_js_1.default(value.valueOf()); + return raw; + } + exports2.decodeBigNumber = decodeBigNumber; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js +var require_codec2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_binary(), exports2); + __exportStar2(require_binaryCodecUtils(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js +var require_argSerializer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArgSerializer = void 0; + var constants_1 = require_constants(); + var codec_1 = require_codec2(); + var typesystem_1 = require_typesystem(); + var algebraic_1 = require_algebraic(); + var composite_1 = require_composite(); + var variadic_1 = require_variadic(); + var defaultArgSerializerOptions = { + codec: new codec_1.BinaryCodec() + }; + var ArgSerializer = class { + constructor(options) { + options = { ...defaultArgSerializerOptions, ...options }; + this.codec = options.codec; + } + /** + * Reads typed values from an arguments string (e.g. aa@bb@@cc), given parameter definitions. + */ + stringToValues(joinedString, parameters) { + let buffers = this.stringToBuffers(joinedString); + let values = this.buffersToValues(buffers, parameters); + return values; + } + /** + * Reads raw buffers from an arguments string (e.g. aa@bb@@cc). + */ + stringToBuffers(joinedString) { + return joinedString.split(constants_1.ARGUMENTS_SEPARATOR).map((item) => import_buffer.Buffer.from(item, "hex")); + } + /** + * Decodes a set of buffers into a set of typed values, given parameter definitions. + */ + buffersToValues(buffers, parameters) { + const self2 = this; + buffers = buffers || []; + let values = []; + let bufferIndex = 0; + let numBuffers = buffers.length; + for (let i2 = 0; i2 < parameters.length; i2++) { + let parameter = parameters[i2]; + let type = parameter.type; + let value = readValue(type); + values.push(value); + } + function readValue(type) { + if (type.hasExactClass(algebraic_1.OptionalType.ClassName)) { + const typedValue2 = readValue(type.getFirstTypeParameter()); + return new algebraic_1.OptionalValue(type, typedValue2); + } + if (type.hasExactClass(variadic_1.VariadicType.ClassName)) { + return readVariadicValue(type); + } + if (type.hasExactClass(composite_1.CompositeType.ClassName)) { + const typedValues = []; + for (const typeParameter of type.getTypeParameters()) { + typedValues.push(readValue(typeParameter)); + } + return new composite_1.CompositeValue(type, typedValues); + } + const typedValue = decodeNextBuffer(type); + return typedValue; + } + function readVariadicValue(type) { + const variadicType = type; + const typedValues = []; + if (variadicType.isCounted) { + const count = readValue(new typesystem_1.U32Type()).valueOf().toNumber(); + for (let i2 = 0; i2 < count; i2++) { + typedValues.push(readValue(type.getFirstTypeParameter())); + } + } else { + while (!hasReachedTheEnd()) { + typedValues.push(readValue(type.getFirstTypeParameter())); + } + } + return new variadic_1.VariadicValue(variadicType, typedValues); + } + function decodeNextBuffer(type) { + if (hasReachedTheEnd()) { + return null; + } + let buffer = buffers[bufferIndex++]; + let decodedValue = self2.codec.decodeTopLevel(buffer, type); + return decodedValue; + } + function hasReachedTheEnd() { + return bufferIndex >= numBuffers; + } + return values; + } + /** + * Serializes a set of typed values into an arguments string (e.g. aa@bb@@cc). + */ + valuesToString(values) { + let strings = this.valuesToStrings(values); + let argumentsString = strings.join(constants_1.ARGUMENTS_SEPARATOR); + let count = strings.length; + return { argumentsString, count }; + } + /** + * Serializes a set of typed values into a set of strings. + */ + valuesToStrings(values) { + let buffers = this.valuesToBuffers(values); + let strings = buffers.map((buffer) => buffer.toString("hex")); + return strings; + } + /** + * Serializes a set of typed values into a set of strings buffers. + * Variadic types and composite types might result into none, one or more buffers. + */ + valuesToBuffers(values) { + const self2 = this; + const buffers = []; + for (const value of values) { + handleValue(value); + } + function handleValue(value) { + if (value.hasExactClass(algebraic_1.OptionalValue.ClassName)) { + const valueAsOptional = value; + if (valueAsOptional.isSet()) { + handleValue(valueAsOptional.getTypedValue()); + } + return; + } + if (value.hasExactClass(variadic_1.VariadicValue.ClassName)) { + handleVariadicValue(value); + return; + } + if (value.hasExactClass(composite_1.CompositeValue.ClassName)) { + const valueAsComposite = value; + for (const item of valueAsComposite.getItems()) { + handleValue(item); + } + return; + } + const buffer = self2.codec.encodeTopLevel(value); + buffers.push(buffer); + } + function handleVariadicValue(value) { + const variadicType = value.getType(); + if (variadicType.isCounted) { + const countValue = new typesystem_1.U32Value(value.getItems().length); + buffers.push(self2.codec.encodeTopLevel(countValue)); + } + for (const item of value.getItems()) { + handleValue(item); + } + } + return buffers; + } + }; + exports2.ArgSerializer = ArgSerializer; + } +}); + +// node_modules/nanoassert/index.js +var require_nanoassert = __commonJS({ + "node_modules/nanoassert/index.js"(exports2, module2) { + init_shim(); + assert.notEqual = notEqual; + assert.notOk = notOk; + assert.equal = equal; + assert.ok = assert; + module2.exports = assert; + function equal(a3, b4, m3) { + assert(a3 == b4, m3); + } + function notEqual(a3, b4, m3) { + assert(a3 != b4, m3); + } + function notOk(t, m3) { + assert(!t, m3); + } + function assert(t, m3) { + if (!t) + throw new Error(m3 || "AssertionError"); + } + } +}); + +// node_modules/blake2b-wasm/blake2b.js +var require_blake2b = __commonJS({ + "node_modules/blake2b-wasm/blake2b.js"(exports2, module2) { + init_shim(); + module2.exports = loadWebAssembly; + loadWebAssembly.supported = typeof WebAssembly !== "undefined"; + function loadWebAssembly(opts) { + if (!loadWebAssembly.supported) + return null; + var imp = opts && opts.imports; + var wasm = toUint8Array("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"); + var ready = null; + var mod2 = { + buffer: wasm, + memory: null, + exports: null, + realloc, + onload + }; + onload(function() { + }); + return mod2; + function realloc(size) { + mod2.exports.memory.grow(Math.ceil(Math.abs(size - mod2.memory.length) / 65536)); + mod2.memory = new Uint8Array(mod2.exports.memory.buffer); + } + function onload(cb) { + if (mod2.exports) + return cb(); + if (ready) { + ready.then(cb.bind(null, null)).catch(cb); + return; + } + try { + if (opts && opts.async) + throw new Error("async"); + setup({ instance: new WebAssembly.Instance(new WebAssembly.Module(wasm), imp) }); + } catch (err) { + ready = WebAssembly.instantiate(wasm, imp).then(setup); + } + onload(cb); + } + function setup(w4) { + mod2.exports = w4.instance.exports; + mod2.memory = mod2.exports.memory && mod2.exports.memory.buffer && new Uint8Array(mod2.exports.memory.buffer); + } + } + function toUint8Array(s2) { + if (typeof atob === "function") + return new Uint8Array(atob(s2).split("").map(charCodeAt)); + return new (require_buffer2()).Buffer(s2, "base64"); + } + function charCodeAt(c4) { + return c4.charCodeAt(0); + } + } +}); + +// node_modules/blake2b-wasm/index.js +var require_blake2b_wasm = __commonJS({ + "node_modules/blake2b-wasm/index.js"(exports2, module2) { + init_shim(); + var assert = require_nanoassert(); + var wasm = require_blake2b()(); + var head = 64; + var freeList = []; + module2.exports = Blake2b; + var BYTES_MIN = module2.exports.BYTES_MIN = 16; + var BYTES_MAX = module2.exports.BYTES_MAX = 64; + var BYTES = module2.exports.BYTES = 32; + var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; + var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; + var KEYBYTES = module2.exports.KEYBYTES = 32; + var SALTBYTES = module2.exports.SALTBYTES = 16; + var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; + function Blake2b(digestLength, key, salt, personal, noAssert) { + if (!(this instanceof Blake2b)) + return new Blake2b(digestLength, key, salt, personal, noAssert); + if (!(wasm && wasm.exports)) + throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)"); + if (!digestLength) + digestLength = 32; + if (noAssert !== true) { + assert(digestLength >= BYTES_MIN, "digestLength must be at least " + BYTES_MIN + ", was given " + digestLength); + assert(digestLength <= BYTES_MAX, "digestLength must be at most " + BYTES_MAX + ", was given " + digestLength); + if (key != null) + assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); + if (key != null) + assert(key.length <= KEYBYTES_MAX, "key must be at least " + KEYBYTES_MAX + ", was given " + key.length); + if (salt != null) + assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); + if (personal != null) + assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); + } + if (!freeList.length) { + freeList.push(head); + head += 216; + } + this.digestLength = digestLength; + this.finalized = false; + this.pointer = freeList.pop(); + wasm.memory.fill(0, 0, 64); + wasm.memory[0] = this.digestLength; + wasm.memory[1] = key ? key.length : 0; + wasm.memory[2] = 1; + wasm.memory[3] = 1; + if (salt) + wasm.memory.set(salt, 32); + if (personal) + wasm.memory.set(personal, 48); + if (this.pointer + 216 > wasm.memory.length) + wasm.realloc(this.pointer + 216); + wasm.exports.blake2b_init(this.pointer, this.digestLength); + if (key) { + this.update(key); + wasm.memory.fill(0, head, head + key.length); + wasm.memory[this.pointer + 200] = 128; + } + } + Blake2b.prototype.update = function(input) { + assert(this.finalized === false, "Hash instance finalized"); + assert(input, "input must be TypedArray or Buffer"); + if (head + input.length > wasm.memory.length) + wasm.realloc(head + input.length); + wasm.memory.set(input, head); + wasm.exports.blake2b_update(this.pointer, head, head + input.length); + return this; + }; + Blake2b.prototype.digest = function(enc) { + assert(this.finalized === false, "Hash instance finalized"); + this.finalized = true; + freeList.push(this.pointer); + wasm.exports.blake2b_final(this.pointer); + if (!enc || enc === "binary") { + return wasm.memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength); + } + if (enc === "hex") { + return hexSlice(wasm.memory, this.pointer + 128, this.digestLength); + } + assert(enc.length >= this.digestLength, "input must be TypedArray or Buffer"); + for (var i2 = 0; i2 < this.digestLength; i2++) { + enc[i2] = wasm.memory[this.pointer + 128 + i2]; + } + return enc; + }; + Blake2b.prototype.final = Blake2b.prototype.digest; + Blake2b.WASM = wasm && wasm.buffer; + Blake2b.SUPPORTED = typeof WebAssembly !== "undefined"; + Blake2b.ready = function(cb) { + if (!cb) + cb = noop; + if (!wasm) + return cb(new Error("WebAssembly not supported")); + var p3 = new Promise(function(reject, resolve) { + wasm.onload(function(err) { + if (err) + resolve(); + else + reject(); + cb(err); + }); + }); + return p3; + }; + Blake2b.prototype.ready = Blake2b.ready; + function noop() { + } + function hexSlice(buf, start, len) { + var str = ""; + for (var i2 = 0; i2 < len; i2++) + str += toHex(buf[start + i2]); + return str; + } + function toHex(n3) { + if (n3 < 16) + return "0" + n3.toString(16); + return n3.toString(16); + } + } +}); + +// node_modules/blake2b/index.js +var require_blake2b2 = __commonJS({ + "node_modules/blake2b/index.js"(exports2, module2) { + init_shim(); + var assert = require_nanoassert(); + var b2wasm = require_blake2b_wasm(); + function ADD64AA(v3, a3, b4) { + var o0 = v3[a3] + v3[b4]; + var o1 = v3[a3 + 1] + v3[b4 + 1]; + if (o0 >= 4294967296) { + o1++; + } + v3[a3] = o0; + v3[a3 + 1] = o1; + } + function ADD64AC(v3, a3, b0, b1) { + var o0 = v3[a3] + b0; + if (b0 < 0) { + o0 += 4294967296; + } + var o1 = v3[a3 + 1] + b1; + if (o0 >= 4294967296) { + o1++; + } + v3[a3] = o0; + v3[a3 + 1] = o1; + } + function B2B_GET32(arr, i2) { + return arr[i2] ^ arr[i2 + 1] << 8 ^ arr[i2 + 2] << 16 ^ arr[i2 + 3] << 24; + } + function B2B_G(a3, b4, c4, d3, ix, iy) { + var x0 = m3[ix]; + var x1 = m3[ix + 1]; + var y0 = m3[iy]; + var y1 = m3[iy + 1]; + ADD64AA(v2, a3, b4); + ADD64AC(v2, a3, x0, x1); + var xor0 = v2[d3] ^ v2[a3]; + var xor1 = v2[d3 + 1] ^ v2[a3 + 1]; + v2[d3] = xor1; + v2[d3 + 1] = xor0; + ADD64AA(v2, c4, d3); + xor0 = v2[b4] ^ v2[c4]; + xor1 = v2[b4 + 1] ^ v2[c4 + 1]; + v2[b4] = xor0 >>> 24 ^ xor1 << 8; + v2[b4 + 1] = xor1 >>> 24 ^ xor0 << 8; + ADD64AA(v2, a3, b4); + ADD64AC(v2, a3, y0, y1); + xor0 = v2[d3] ^ v2[a3]; + xor1 = v2[d3 + 1] ^ v2[a3 + 1]; + v2[d3] = xor0 >>> 16 ^ xor1 << 16; + v2[d3 + 1] = xor1 >>> 16 ^ xor0 << 16; + ADD64AA(v2, c4, d3); + xor0 = v2[b4] ^ v2[c4]; + xor1 = v2[b4 + 1] ^ v2[c4 + 1]; + v2[b4] = xor1 >>> 31 ^ xor0 << 1; + v2[b4 + 1] = xor0 >>> 31 ^ xor1 << 1; + } + var BLAKE2B_IV32 = new Uint32Array([ + 4089235720, + 1779033703, + 2227873595, + 3144134277, + 4271175723, + 1013904242, + 1595750129, + 2773480762, + 2917565137, + 1359893119, + 725511199, + 2600822924, + 4215389547, + 528734635, + 327033209, + 1541459225 + ]); + var SIGMA8 = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + 11, + 8, + 12, + 0, + 5, + 2, + 15, + 13, + 10, + 14, + 3, + 6, + 7, + 1, + 9, + 4, + 7, + 9, + 3, + 1, + 13, + 12, + 11, + 14, + 2, + 6, + 5, + 10, + 4, + 0, + 15, + 8, + 9, + 0, + 5, + 7, + 2, + 4, + 10, + 15, + 14, + 1, + 11, + 12, + 6, + 8, + 3, + 13, + 2, + 12, + 6, + 10, + 0, + 11, + 8, + 3, + 4, + 13, + 7, + 5, + 15, + 14, + 1, + 9, + 12, + 5, + 1, + 15, + 14, + 13, + 4, + 10, + 0, + 7, + 6, + 3, + 9, + 2, + 8, + 11, + 13, + 11, + 7, + 14, + 12, + 1, + 3, + 9, + 5, + 0, + 15, + 4, + 8, + 6, + 2, + 10, + 6, + 15, + 14, + 9, + 11, + 3, + 0, + 8, + 12, + 2, + 13, + 7, + 1, + 4, + 10, + 5, + 10, + 2, + 8, + 4, + 7, + 6, + 1, + 5, + 15, + 11, + 9, + 14, + 3, + 12, + 13, + 0, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3 + ]; + var SIGMA82 = new Uint8Array(SIGMA8.map(function(x3) { + return x3 * 2; + })); + var v2 = new Uint32Array(32); + var m3 = new Uint32Array(32); + function blake2bCompress(ctx, last) { + var i2 = 0; + for (i2 = 0; i2 < 16; i2++) { + v2[i2] = ctx.h[i2]; + v2[i2 + 16] = BLAKE2B_IV32[i2]; + } + v2[24] = v2[24] ^ ctx.t; + v2[25] = v2[25] ^ ctx.t / 4294967296; + if (last) { + v2[28] = ~v2[28]; + v2[29] = ~v2[29]; + } + for (i2 = 0; i2 < 32; i2++) { + m3[i2] = B2B_GET32(ctx.b, 4 * i2); + } + for (i2 = 0; i2 < 12; i2++) { + B2B_G(0, 8, 16, 24, SIGMA82[i2 * 16 + 0], SIGMA82[i2 * 16 + 1]); + B2B_G(2, 10, 18, 26, SIGMA82[i2 * 16 + 2], SIGMA82[i2 * 16 + 3]); + B2B_G(4, 12, 20, 28, SIGMA82[i2 * 16 + 4], SIGMA82[i2 * 16 + 5]); + B2B_G(6, 14, 22, 30, SIGMA82[i2 * 16 + 6], SIGMA82[i2 * 16 + 7]); + B2B_G(0, 10, 20, 30, SIGMA82[i2 * 16 + 8], SIGMA82[i2 * 16 + 9]); + B2B_G(2, 12, 22, 24, SIGMA82[i2 * 16 + 10], SIGMA82[i2 * 16 + 11]); + B2B_G(4, 14, 16, 26, SIGMA82[i2 * 16 + 12], SIGMA82[i2 * 16 + 13]); + B2B_G(6, 8, 18, 28, SIGMA82[i2 * 16 + 14], SIGMA82[i2 * 16 + 15]); + } + for (i2 = 0; i2 < 16; i2++) { + ctx.h[i2] = ctx.h[i2] ^ v2[i2] ^ v2[i2 + 16]; + } + } + var parameter_block = new Uint8Array([ + 0, + 0, + 0, + 0, + // 0: outlen, keylen, fanout, depth + 0, + 0, + 0, + 0, + // 4: leaf length, sequential mode + 0, + 0, + 0, + 0, + // 8: node offset + 0, + 0, + 0, + 0, + // 12: node offset + 0, + 0, + 0, + 0, + // 16: node depth, inner length, rfu + 0, + 0, + 0, + 0, + // 20: rfu + 0, + 0, + 0, + 0, + // 24: rfu + 0, + 0, + 0, + 0, + // 28: rfu + 0, + 0, + 0, + 0, + // 32: salt + 0, + 0, + 0, + 0, + // 36: salt + 0, + 0, + 0, + 0, + // 40: salt + 0, + 0, + 0, + 0, + // 44: salt + 0, + 0, + 0, + 0, + // 48: personal + 0, + 0, + 0, + 0, + // 52: personal + 0, + 0, + 0, + 0, + // 56: personal + 0, + 0, + 0, + 0 + // 60: personal + ]); + function Blake2b(outlen, key, salt, personal) { + parameter_block.fill(0); + this.b = new Uint8Array(128); + this.h = new Uint32Array(16); + this.t = 0; + this.c = 0; + this.outlen = outlen; + parameter_block[0] = outlen; + if (key) + parameter_block[1] = key.length; + parameter_block[2] = 1; + parameter_block[3] = 1; + if (salt) + parameter_block.set(salt, 32); + if (personal) + parameter_block.set(personal, 48); + for (var i2 = 0; i2 < 16; i2++) { + this.h[i2] = BLAKE2B_IV32[i2] ^ B2B_GET32(parameter_block, i2 * 4); + } + if (key) { + blake2bUpdate(this, key); + this.c = 128; + } + } + Blake2b.prototype.update = function(input) { + assert(input != null, "input must be Uint8Array or Buffer"); + blake2bUpdate(this, input); + return this; + }; + Blake2b.prototype.digest = function(out) { + var buf = !out || out === "binary" || out === "hex" ? new Uint8Array(this.outlen) : out; + assert(buf.length >= this.outlen, "out must have at least outlen bytes of space"); + blake2bFinal(this, buf); + if (out === "hex") + return hexSlice(buf); + return buf; + }; + Blake2b.prototype.final = Blake2b.prototype.digest; + Blake2b.ready = function(cb) { + b2wasm.ready(function() { + cb(); + }); + }; + function blake2bUpdate(ctx, input) { + for (var i2 = 0; i2 < input.length; i2++) { + if (ctx.c === 128) { + ctx.t += ctx.c; + blake2bCompress(ctx, false); + ctx.c = 0; + } + ctx.b[ctx.c++] = input[i2]; + } + } + function blake2bFinal(ctx, out) { + ctx.t += ctx.c; + while (ctx.c < 128) { + ctx.b[ctx.c++] = 0; + } + blake2bCompress(ctx, true); + for (var i2 = 0; i2 < ctx.outlen; i2++) { + out[i2] = ctx.h[i2 >> 2] >> 8 * (i2 & 3); + } + return out; + } + function hexSlice(buf) { + var str = ""; + for (var i2 = 0; i2 < buf.length; i2++) + str += toHex(buf[i2]); + return str; + } + function toHex(n3) { + if (n3 < 16) + return "0" + n3.toString(16); + return n3.toString(16); + } + var Proto = Blake2b; + module2.exports = function createHash(outlen, key, salt, personal, noAssert) { + if (noAssert !== true) { + assert(outlen >= BYTES_MIN, "outlen must be at least " + BYTES_MIN + ", was given " + outlen); + assert(outlen <= BYTES_MAX, "outlen must be at most " + BYTES_MAX + ", was given " + outlen); + if (key != null) + assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); + if (key != null) + assert(key.length <= KEYBYTES_MAX, "key must be at most " + KEYBYTES_MAX + ", was given " + key.length); + if (salt != null) + assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); + if (personal != null) + assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); + } + return new Proto(outlen, key, salt, personal); + }; + module2.exports.ready = function(cb) { + b2wasm.ready(function() { + cb(); + }); + }; + module2.exports.WASM_SUPPORTED = b2wasm.SUPPORTED; + module2.exports.WASM_LOADED = false; + var BYTES_MIN = module2.exports.BYTES_MIN = 16; + var BYTES_MAX = module2.exports.BYTES_MAX = 64; + var BYTES = module2.exports.BYTES = 32; + var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; + var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; + var KEYBYTES = module2.exports.KEYBYTES = 32; + var SALTBYTES = module2.exports.SALTBYTES = 16; + var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; + b2wasm.ready(function(err) { + if (!err) { + module2.exports.WASM_LOADED = true; + Proto = b2wasm; + } + }); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/code.js +var require_code = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/code.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Code = void 0; + var createHasher = require_blake2b2(); + var CODE_HASH_LENGTH = 32; + var Code = class _Code { + constructor(hex) { + this.hex = hex; + } + /** + * Creates a Code object from a buffer (sequence of bytes). + */ + static fromBuffer(code2) { + return new _Code(code2.toString("hex")); + } + /** + * Creates a Code object from a hex-encoded string. + */ + static fromHex(hex) { + return new _Code(hex); + } + /** + * Returns the bytecode as a hex-encoded string. + */ + toString() { + return this.hex; + } + valueOf() { + return import_buffer.Buffer.from(this.hex, "hex"); + } + computeHash() { + const hash = createHasher(CODE_HASH_LENGTH).update(this.valueOf()).digest(); + return import_buffer.Buffer.from(hash); + } + }; + exports2.Code = Code; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js +var require_codeMetadata2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CodeMetadata = void 0; + var CodeMetadata = class _CodeMetadata { + /** + * Creates a metadata object. By default, set the `upgradeable` attribute, and uset all others. + * + * @param upgradeable Whether the contract is upgradeable + * @param readable Whether other contracts can read this contract's data (without calling one of its pure functions) + * @param payable Whether the contract is payable + * @param payableBySc Whether the contract is payable by other smart contracts + */ + constructor(upgradeable = true, readable = false, payable = false, payableBySc = false) { + this.upgradeable = upgradeable; + this.readable = readable; + this.payable = payable; + this.payableBySc = payableBySc; + } + static fromBytes(bytes) { + return _CodeMetadata.fromBuffer(import_buffer.Buffer.from(bytes)); + } + /** + * Creates a metadata object from a buffer. + */ + static fromBuffer(buffer) { + if (buffer.length < this.codeMetadataLength) { + throw new Error("Buffer is too short."); + } + const byteZero = buffer[0]; + const byteOne = buffer[1]; + const upgradeable = (byteZero & _CodeMetadata.ByteZero.Upgradeable) !== 0; + const readable = (byteZero & _CodeMetadata.ByteZero.Readable) !== 0; + const payable = (byteOne & _CodeMetadata.ByteOne.Payable) !== 0; + const payableBySc = (byteOne & _CodeMetadata.ByteOne.PayableBySc) !== 0; + return new _CodeMetadata(upgradeable, readable, payable, payableBySc); + } + /** + * Adjust the metadata (the `upgradeable` attribute), when preparing the deployment transaction. + */ + toggleUpgradeable(value) { + this.upgradeable = value; + } + /** + * Adjust the metadata (the `readable` attribute), when preparing the deployment transaction. + */ + toggleReadable(value) { + this.readable = value; + } + /** + * Adjust the metadata (the `payable` attribute), when preparing the deployment transaction. + */ + togglePayable(value) { + this.payable = value; + } + /** + * Adjust the metadata (the `payableBySc` attribute), when preparing the deployment transaction. + */ + togglePayableBySc(value) { + this.payableBySc = value; + } + /** + * Converts the metadata to the protocol-friendly representation. + */ + toBuffer() { + let byteZero = 0; + let byteOne = 0; + if (this.upgradeable) { + byteZero |= _CodeMetadata.ByteZero.Upgradeable; + } + if (this.readable) { + byteZero |= _CodeMetadata.ByteZero.Readable; + } + if (this.payable) { + byteOne |= _CodeMetadata.ByteOne.Payable; + } + if (this.payableBySc) { + byteOne |= _CodeMetadata.ByteOne.PayableBySc; + } + return import_buffer.Buffer.from([byteZero, byteOne]); + } + /** + * Converts the metadata to a hex-encoded string. + */ + toString() { + return this.toBuffer().toString("hex"); + } + /** + * Converts the metadata to a pretty, plain JavaScript object. + */ + toJSON() { + return { + upgradeable: this.upgradeable, + readable: this.readable, + payable: this.payable, + payableBySc: this.payableBySc + }; + } + equals(other) { + return this.upgradeable == other.upgradeable && this.readable == other.readable && this.payable == other.payable && this.payableBySc == other.payableBySc; + } + }; + exports2.CodeMetadata = CodeMetadata; + CodeMetadata.codeMetadataLength = 2; + CodeMetadata.ByteZero = { + Upgradeable: 1, + Reserved2: 2, + Readable: 4 + }; + CodeMetadata.ByteOne = { + Reserved1: 1, + Payable: 2, + PayableBySc: 4 + }; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/function.js +var require_function = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/function.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractFunction = void 0; + var errors = __importStar2(require_errors()); + var ContractFunction = class _ContractFunction { + /** + * Creates a ContractFunction object, given its name. + * + * @param name the name of the function + */ + constructor(name2) { + this.name = name2; + if (name2 == null) { + throw new errors.ErrInvalidFunctionName(); + } + } + /** + * Null-object pattern: creates an empty ContractFunction object. + */ + static none() { + return new _ContractFunction("untitled"); + } + /** + * Returns the name of the function. + */ + toString() { + return this.name; + } + valueOf() { + return this.name; + } + }; + exports2.ContractFunction = ContractFunction; + } +}); + +// node_modules/@multiversx/sdk-core/out/compatibility.js +var require_compatibility = __commonJS({ + "node_modules/@multiversx/sdk-core/out/compatibility.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Compatibility = void 0; + var address_1 = require_address(); + var Compatibility = class { + /** + * For internal use only. + */ + static guardAddressIsSetAndNonZero(address, context, resolution) { + if (!address || address.bech32() == "") { + console.warn(`${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); + } else if (address.bech32() == address_1.Address.Zero().bech32()) { + console.warn(`${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); + } + } + }; + exports2.Compatibility = Compatibility; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionPayload.js +var require_transactionPayload = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionPayload.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionPayload = void 0; + var TransactionPayload = class _TransactionPayload { + /** + * Creates a TransactionPayload from a utf-8 string or from a buffer. + */ + constructor(data) { + this.data = import_buffer.Buffer.from(data || []); + } + /** + * Creates a TransactionPayload from a base-64 encoded string. + */ + static fromEncoded(encoded) { + if (!encoded) { + return new _TransactionPayload(""); + } + let decoded = import_buffer.Buffer.from(encoded, "base64").toString(); + return new _TransactionPayload(decoded); + } + /** + * Returns whether the "data" is void. + */ + isEmpty() { + return this.data.length == 0; + } + /** + * Returns the base-64 representation of the data. + */ + encoded() { + return this.data.toString("base64"); + } + /** + * Returns the data as a buffer. + */ + valueOf() { + return this.data; + } + toString() { + return this.data.toString(); + } + getEncodedArguments() { + return this.toString().split("@"); + } + getRawArguments() { + return this.getEncodedArguments().map((argument) => import_buffer.Buffer.from(argument, "hex")); + } + /** + * Returns the length of the data. + */ + length() { + return import_buffer.Buffer.from(this.data).length; + } + }; + exports2.TransactionPayload = TransactionPayload; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js +var require_transactionBuilder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionBuilder = void 0; + var constants_1 = require_constants(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var TransactionBuilder = class { + constructor(options) { + this.config = options.config; + this.sender = options.sender; + this.receiver = options.receiver; + this.dataParts = options.dataParts; + this.providedGasLimit = options.gasLimit; + this.addDataMovementGas = options.addDataMovementGas; + this.amount = options.amount; + } + computeGasLimit(payload) { + if (!this.addDataMovementGas) { + return this.providedGasLimit; + } + const dataMovementGas = this.config.minGasLimit + this.config.gasLimitPerByte * BigInt(payload.length()); + const gasLimit = dataMovementGas + this.providedGasLimit; + return gasLimit; + } + buildTransactionPayload() { + const data = this.dataParts.join(constants_1.ARGUMENTS_SEPARATOR); + return new transactionPayload_1.TransactionPayload(data); + } + build() { + const data = this.buildTransactionPayload(); + const gasLimit = this.computeGasLimit(data); + return new transaction_1.Transaction({ + sender: this.sender.bech32(), + receiver: this.receiver.bech32(), + gasLimit, + value: this.amount || 0n, + data: data.valueOf(), + chainID: this.config.chainID + }); + } + }; + exports2.TransactionBuilder = TransactionBuilder; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js +var require_delegationTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DelegationTransactionsFactory = void 0; + var address_1 = require_address(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var transactionBuilder_1 = require_transactionBuilder(); + var DelegationTransactionsFactory = class { + constructor(options) { + this.config = options.config; + this.argSerializer = new smartcontracts_1.ArgSerializer(); + } + createTransactionForNewDelegationContract(options) { + const dataParts = [ + "createNewDelegationContract", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.BigUIntValue(options.totalDelegationCap), + new smartcontracts_1.BigUIntValue(options.serviceFee) + ]) + ]; + const executionGasLimit = this.config.gasLimitCreateDelegationContract + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.DELEGATION_MANAGER_SC_ADDRESS), + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true, + amount: options.amount + }).build(); + } + createTransactionForAddingNodes(options) { + if (options.publicKeys.length !== options.signedMessages.length) { + throw new errors_1.Err("The number of public keys should match the number of signed messages"); + } + const signedMessagesAsTypedValues = options.signedMessages.map((message) => new smartcontracts_1.BytesValue(import_buffer.Buffer.from(message))); + const messagesAsStrings = this.argSerializer.valuesToStrings(signedMessagesAsTypedValues); + const numNodes = options.publicKeys.length; + const dataParts = ["addNodes"]; + for (let i2 = 0; i2 < numNodes; i2++) { + dataParts.push(...[options.publicKeys[i2].hex(), messagesAsStrings[i2]]); + } + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), + addDataMovementGas: true + }).build(); + } + createTransactionForRemovingNodes(options) { + const dataParts = ["removeNodes"]; + for (const key of options.publicKeys) { + dataParts.push(key.hex()); + } + const numNodes = options.publicKeys.length; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), + addDataMovementGas: true + }).build(); + } + createTransactionForStakingNodes(options) { + let dataParts = ["stakeNodes"]; + for (const key of options.publicKeys) { + dataParts = dataParts.concat(key.hex()); + } + const numNodes = options.publicKeys.length; + const additionalGasForAllNodes = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode; + const executionGasLimit = additionalGasForAllNodes + this.config.gasLimitStake + this.config.gasLimitDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnbondingNodes(options) { + let dataParts = ["unBondNodes"]; + for (const key of options.publicKeys) { + dataParts = dataParts.concat(key.hex()); + } + const numNodes = options.publicKeys.length; + const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnbond + this.config.gasLimitDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnstakingNodes(options) { + let dataParts = ["unStakeNodes"]; + for (const key of options.publicKeys) { + dataParts = dataParts.concat(key.hex()); + } + const numNodes = options.publicKeys.length; + const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnstake + this.config.gasLimitDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnjailingNodes(options) { + const dataParts = ["unJailNodes"]; + for (const key of options.publicKeys) { + dataParts.push(key.hex()); + } + const numNodes = options.publicKeys.length; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), + addDataMovementGas: true + }).build(); + } + createTransactionForChangingServiceFee(options) { + const dataParts = [ + "changeServiceFee", + this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.serviceFee)])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForModifyingDelegationCap(options) { + const dataParts = [ + "modifyTotalDelegationCap", + this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.delegationCap)])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingAutomaticActivation(options) { + const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0]]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnsettingAutomaticActivation(options) { + const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0]]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingCapCheckOnRedelegateRewards(options) { + const dataParts = [ + "setCheckCapOnReDelegateRewards", + this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnsettingCapCheckOnRedelegateRewards(options) { + const dataParts = [ + "setCheckCapOnReDelegateRewards", + this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingMetadata(options) { + const dataParts = [ + "setMetaData", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.name), + new smartcontracts_1.StringValue(options.website), + new smartcontracts_1.StringValue(options.identifier) + ]) + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + computeExecutionGasLimitForNodesManagement(numNodes) { + const additionalGasForAllNodes = this.config.additionalGasLimitPerValidatorNode * BigInt(numNodes); + return this.config.gasLimitDelegationOperations + additionalGasForAllNodes; + } + }; + exports2.DelegationTransactionsFactory = DelegationTransactionsFactory; + } +}); + +// node_modules/json-bigint/lib/stringify.js +var require_stringify = __commonJS({ + "node_modules/json-bigint/lib/stringify.js"(exports2, module2) { + init_shim(); + var BigNumber2 = require_bignumber(); + var JSON2 = module2.exports; + (function() { + "use strict"; + function f4(n3) { + return n3 < 10 ? "0" + n3 : n3; + } + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { + // table of character substitutions + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\" + }, rep; + function quote(string2) { + escapable.lastIndex = 0; + return escapable.test(string2) ? '"' + string2.replace(escapable, function(a3) { + var c4 = meta[a3]; + return typeof c4 === "string" ? c4 : "\\u" + ("0000" + a3.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string2 + '"'; + } + function str(key, holder) { + var i2, k4, v2, length2, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber2 || BigNumber2.isBigNumber(value)); + if (value && typeof value === "object" && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + if (typeof rep === "function") { + value = rep.call(holder, key, value); + } + switch (typeof value) { + case "string": + if (isBigNumber) { + return value; + } else { + return quote(value); + } + case "number": + return isFinite(value) ? String(value) : "null"; + case "boolean": + case "null": + case "bigint": + return String(value); + case "object": + if (!value) { + return "null"; + } + gap += indent; + partial = []; + if (Object.prototype.toString.apply(value) === "[object Array]") { + length2 = value.length; + for (i2 = 0; i2 < length2; i2 += 1) { + partial[i2] = str(i2, value) || "null"; + } + v2 = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]"; + gap = mind; + return v2; + } + if (rep && typeof rep === "object") { + length2 = rep.length; + for (i2 = 0; i2 < length2; i2 += 1) { + if (typeof rep[i2] === "string") { + k4 = rep[i2]; + v2 = str(k4, value); + if (v2) { + partial.push(quote(k4) + (gap ? ": " : ":") + v2); + } + } + } + } else { + Object.keys(value).forEach(function(k5) { + var v3 = str(k5, value); + if (v3) { + partial.push(quote(k5) + (gap ? ": " : ":") + v3); + } + }); + } + v2 = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; + gap = mind; + return v2; + } + } + if (typeof JSON2.stringify !== "function") { + JSON2.stringify = function(value, replacer, space) { + var i2; + gap = ""; + indent = ""; + if (typeof space === "number") { + for (i2 = 0; i2 < space; i2 += 1) { + indent += " "; + } + } else if (typeof space === "string") { + indent = space; + } + rep = replacer; + if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { + throw new Error("JSON.stringify"); + } + return str("", { "": value }); + }; + } + })(); + } +}); + +// node_modules/json-bigint/lib/parse.js +var require_parse = __commonJS({ + "node_modules/json-bigint/lib/parse.js"(exports2, module2) { + init_shim(); + var BigNumber2 = null; + var suspectProtoRx2 = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; + var suspectConstructorRx2 = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; + var json_parse = function(options) { + "use strict"; + var _options = { + strict: false, + // not being strict means do not generate syntax errors for "duplicate key" + storeAsString: false, + // toggles whether the values should be stored as BigNumber (default) or a string + alwaysParseAsBig: false, + // toggles whether all numbers should be Big + useNativeBigInt: false, + // toggles whether to use native BigInt instead of bignumber.js + protoAction: "error", + constructorAction: "error" + }; + if (options !== void 0 && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; + _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; + if (typeof options.constructorAction !== "undefined") { + if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { + _options.constructorAction = options.constructorAction; + } else { + throw new Error( + `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` + ); + } + } + if (typeof options.protoAction !== "undefined") { + if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { + _options.protoAction = options.protoAction; + } else { + throw new Error( + `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` + ); + } + } + } + var at, ch, escapee = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: " " + }, text, error = function(m3) { + throw { + name: "SyntaxError", + message: m3, + at, + text + }; + }, next = function(c4) { + if (c4 && c4 !== ch) { + error("Expected '" + c4 + "' instead of '" + ch + "'"); + } + ch = text.charAt(at); + at += 1; + return ch; + }, number = function() { + var number2, string3 = ""; + if (ch === "-") { + string3 = "-"; + next("-"); + } + while (ch >= "0" && ch <= "9") { + string3 += ch; + next(); + } + if (ch === ".") { + string3 += "."; + while (next() && ch >= "0" && ch <= "9") { + string3 += ch; + } + } + if (ch === "e" || ch === "E") { + string3 += ch; + next(); + if (ch === "-" || ch === "+") { + string3 += ch; + next(); + } + while (ch >= "0" && ch <= "9") { + string3 += ch; + next(); + } + } + number2 = +string3; + if (!isFinite(number2)) { + error("Bad number"); + } else { + if (BigNumber2 == null) + BigNumber2 = require_bignumber(); + if (string3.length > 15) + return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber2(string3); + else + return !_options.alwaysParseAsBig ? number2 : _options.useNativeBigInt ? BigInt(number2) : new BigNumber2(number2); + } + }, string2 = function() { + var hex, i2, string3 = "", uffff; + if (ch === '"') { + var startAt = at; + while (next()) { + if (ch === '"') { + if (at - 1 > startAt) + string3 += text.substring(startAt, at - 1); + next(); + return string3; + } + if (ch === "\\") { + if (at - 1 > startAt) + string3 += text.substring(startAt, at - 1); + next(); + if (ch === "u") { + uffff = 0; + for (i2 = 0; i2 < 4; i2 += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string3 += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === "string") { + string3 += escapee[ch]; + } else { + break; + } + startAt = at; + } + } + } + error("Bad string"); + }, white = function() { + while (ch && ch <= " ") { + next(); + } + }, word = function() { + switch (ch) { + case "t": + next("t"); + next("r"); + next("u"); + next("e"); + return true; + case "f": + next("f"); + next("a"); + next("l"); + next("s"); + next("e"); + return false; + case "n": + next("n"); + next("u"); + next("l"); + next("l"); + return null; + } + error("Unexpected '" + ch + "'"); + }, value, array = function() { + var array2 = []; + if (ch === "[") { + next("["); + white(); + if (ch === "]") { + next("]"); + return array2; + } + while (ch) { + array2.push(value()); + white(); + if (ch === "]") { + next("]"); + return array2; + } + next(","); + white(); + } + } + error("Bad array"); + }, object = function() { + var key, object2 = /* @__PURE__ */ Object.create(null); + if (ch === "{") { + next("{"); + white(); + if (ch === "}") { + next("}"); + return object2; + } + while (ch) { + key = string2(); + white(); + next(":"); + if (_options.strict === true && Object.hasOwnProperty.call(object2, key)) { + error('Duplicate key "' + key + '"'); + } + if (suspectProtoRx2.test(key) === true) { + if (_options.protoAction === "error") { + error("Object contains forbidden prototype property"); + } else if (_options.protoAction === "ignore") { + value(); + } else { + object2[key] = value(); + } + } else if (suspectConstructorRx2.test(key) === true) { + if (_options.constructorAction === "error") { + error("Object contains forbidden constructor property"); + } else if (_options.constructorAction === "ignore") { + value(); + } else { + object2[key] = value(); + } + } else { + object2[key] = value(); + } + white(); + if (ch === "}") { + next("}"); + return object2; + } + next(","); + white(); + } + } + error("Bad object"); + }; + value = function() { + white(); + switch (ch) { + case "{": + return object(); + case "[": + return array(); + case '"': + return string2(); + case "-": + return number(); + default: + return ch >= "0" && ch <= "9" ? number() : word(); + } + }; + return function(source, reviver) { + var result; + text = source + ""; + at = 0; + ch = " "; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + return typeof reviver === "function" ? function walk(holder, key) { + var k4, v2, value2 = holder[key]; + if (value2 && typeof value2 === "object") { + Object.keys(value2).forEach(function(k5) { + v2 = walk(value2, k5); + if (v2 !== void 0) { + value2[k5] = v2; + } else { + delete value2[k5]; + } + }); + } + return reviver.call(holder, key, value2); + }({ "": result }, "") : result; + }; + }; + module2.exports = json_parse; + } +}); + +// node_modules/json-bigint/index.js +var require_json_bigint = __commonJS({ + "node_modules/json-bigint/index.js"(exports2, module2) { + init_shim(); + var json_stringify = require_stringify().stringify; + var json_parse = require_parse(); + module2.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + }; + }; + module2.exports.parse = json_parse(); + module2.exports.stringify = json_stringify; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js +var require_relayedTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RelayedTransactionsFactory = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var transaction_1 = require_transaction(); + var JSONbig = require_json_bigint(); + var RelayedTransactionsFactory = class { + constructor(options) { + this.config = options.config; + } + createRelayedV1Transaction(options) { + if (!options.innerTransaction.gasLimit) { + throw new errors_1.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); + } + if (!options.innerTransaction.signature.length) { + throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); + } + const serializedTransaction = this.prepareInnerTransactionForRelayedV1(options.innerTransaction); + const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; + const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); + const gasLimit = this.config.minGasLimit + additionalGasForDataLength + options.innerTransaction.gasLimit; + return new transaction_1.Transaction({ + chainID: this.config.chainID, + sender: options.relayerAddress.bech32(), + receiver: options.innerTransaction.sender, + gasLimit, + data: import_buffer.Buffer.from(data) + }); + } + createRelayedV2Transaction(options) { + if (options.innerTransaction.gasLimit) { + throw new errors_1.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction"); + } + if (!options.innerTransaction.signature.length) { + throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + new smartcontracts_1.AddressValue(address_1.Address.fromBech32(options.innerTransaction.receiver)), + new smartcontracts_1.U64Value(new bignumber_js_1.default(options.innerTransaction.nonce.toString())), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.data)), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.signature)) + ]); + const data = `relayedTxV2@${argumentsString}`; + const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); + const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; + return new transaction_1.Transaction({ + sender: options.relayerAddress.bech32(), + receiver: options.innerTransaction.sender, + value: 0n, + gasLimit, + chainID: this.config.chainID, + data: import_buffer.Buffer.from(data), + version: options.innerTransaction.version, + options: options.innerTransaction.options + }); + } + prepareInnerTransactionForRelayedV1(innerTransaction) { + const txObject = { + nonce: innerTransaction.nonce, + sender: address_1.Address.fromBech32(innerTransaction.sender).pubkey().toString("base64"), + receiver: address_1.Address.fromBech32(innerTransaction.receiver).pubkey().toString("base64"), + value: innerTransaction.value, + gasPrice: innerTransaction.gasPrice, + gasLimit: innerTransaction.gasLimit, + data: import_buffer.Buffer.from(innerTransaction.data).toString("base64"), + signature: import_buffer.Buffer.from(innerTransaction.signature).toString("base64"), + chainID: import_buffer.Buffer.from(innerTransaction.chainID).toString("base64"), + version: innerTransaction.version, + options: innerTransaction.options.valueOf() == 0 ? void 0 : innerTransaction.options, + guardian: innerTransaction.guardian ? address_1.Address.fromBech32(innerTransaction.guardian).pubkey().toString("base64") : void 0, + guardianSignature: innerTransaction.guardianSignature.length ? import_buffer.Buffer.from(innerTransaction.guardianSignature).toString("base64") : void 0, + sndUserName: innerTransaction.senderUsername ? import_buffer.Buffer.from(innerTransaction.senderUsername).toString("base64") : void 0, + rcvUserName: innerTransaction.receiverUsername ? import_buffer.Buffer.from(innerTransaction.receiverUsername).toString("base64") : void 0 + }; + return JSONbig.stringify(txObject); + } + }; + exports2.RelayedTransactionsFactory = RelayedTransactionsFactory; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js +var require_argumentErrorContext = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArgumentErrorContext = void 0; + var errors_1 = require_errors(); + var ArgumentErrorContext = class { + constructor(endpointName, argumentIndex, parameterDefinition) { + this.endpointName = endpointName; + this.argumentIndex = argumentIndex; + this.parameterDefinition = parameterDefinition; + } + throwError(specificError) { + throw new errors_1.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) +Nested error: ${specificError}`); + } + convertError(native, typeName) { + this.throwError(`Can't convert argument (argument: ${native}, type ${typeof native}), wanted type: ${typeName})`); + } + unhandledType(functionName, type) { + this.throwError(`Unhandled type (function: ${functionName}, type: ${type})`); + } + guardSameLength(native, valueTypes) { + native = native || []; + if (native.length != valueTypes.length) { + this.throwError(`Incorrect composite type length: have ${native.length}, expected ${valueTypes.length} (argument: ${native})`); + } + } + guardHasField(native, fieldName) { + native = native || {}; + if (!(fieldName in native)) { + this.throwError(`Struct argument does not contain a field named "${fieldName}" (argument: ${JSON.stringify(native)})`); + } + } + }; + exports2.ArgumentErrorContext = ArgumentErrorContext; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js +var require_nativeSerializer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NativeSerializer = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var errors_1 = require_errors(); + var utils_codec_1 = require_utils_codec(); + var argumentErrorContext_1 = require_argumentErrorContext(); + var typesystem_1 = require_typesystem(); + var NativeSerializer; + (function(NativeSerializer2) { + function nativeToTypedValues(args, endpoint) { + args = args || []; + checkArgumentsCardinality(args, endpoint); + if (hasNonCountedVariadicParameter(endpoint)) { + args = repackNonCountedVariadicParameters(args, endpoint); + } else { + } + let parameters = endpoint.input; + let values = []; + for (let i2 = 0; i2 < parameters.length; i2++) { + let parameter = parameters[i2]; + let errorContext = new argumentErrorContext_1.ArgumentErrorContext(endpoint.name, i2, parameter); + let value = convertToTypedValue(args[i2], parameter.type, errorContext); + values.push(value); + } + return values; + } + NativeSerializer2.nativeToTypedValues = nativeToTypedValues; + function checkArgumentsCardinality(args, endpoint) { + const { min, max } = getArgumentsCardinality(endpoint.input); + if (!(min <= args.length && args.length <= max)) { + throw new errors_1.ErrInvalidArgument(`Wrong number of arguments for endpoint ${endpoint.name}: expected between ${min} and ${max} arguments, have ${args.length}`); + } + } + function hasNonCountedVariadicParameter(endpoint) { + const lastParameter = endpoint.input[endpoint.input.length - 1]; + return lastParameter?.type instanceof typesystem_1.VariadicType && !lastParameter.type.isCounted; + } + function repackNonCountedVariadicParameters(args, endpoint) { + const lastEndpointParamIndex = endpoint.input.length - 1; + const argAtIndex = args[lastEndpointParamIndex]; + if (argAtIndex?.belongsToTypesystem) { + const isVariadicValue = argAtIndex.hasClassOrSuperclass(typesystem_1.VariadicValue.ClassName); + if (!isVariadicValue) { + throw new errors_1.ErrInvalidArgument(`Wrong argument type for endpoint ${endpoint.name}: typed value provided; expected variadic type, have ${argAtIndex.getClassName()}`); + } + } else { + args[lastEndpointParamIndex] = args.slice(lastEndpointParamIndex); + } + return args; + } + function getArgumentsCardinality(parameters) { + let reversed = [...parameters].reverse(); + let min = parameters.length; + let max = parameters.length; + let variadic = false; + if (reversed.length > 0 && reversed[0].type.getCardinality().isComposite()) { + max = Infinity; + variadic = true; + } + for (let parameter of reversed) { + if (parameter.type.getCardinality().isSingular()) { + break; + } + min -= 1; + } + return { min, max, variadic }; + } + NativeSerializer2.getArgumentsCardinality = getArgumentsCardinality; + function convertToTypedValue(value, type, errorContext) { + if (value && value.belongsToTypesystem) { + return value; + } + if (type instanceof typesystem_1.OptionType) { + return toOptionValue(value, type, errorContext); + } + if (type instanceof typesystem_1.OptionalType) { + return toOptionalValue(value, type, errorContext); + } + if (type instanceof typesystem_1.VariadicType) { + return toVariadicValue(value, type, errorContext); + } + if (type instanceof typesystem_1.CompositeType) { + return toCompositeValue(value, type, errorContext); + } + if (type instanceof typesystem_1.TupleType) { + return toTupleValue(value, type, errorContext); + } + if (type instanceof typesystem_1.StructType) { + return toStructValue(value, type, errorContext); + } + if (type instanceof typesystem_1.ListType) { + return toListValue(value, type, errorContext); + } + if (type instanceof typesystem_1.PrimitiveType) { + return toPrimitive(value, type, errorContext); + } + if (type instanceof typesystem_1.EnumType) { + return toEnumValue(value, type, errorContext); + } + errorContext.throwError(`convertToTypedValue: unhandled type ${type}`); + } + function toOptionValue(native, type, errorContext) { + if (native == null) { + return typesystem_1.OptionValue.newMissing(); + } + let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); + return typesystem_1.OptionValue.newProvided(converted); + } + function toOptionalValue(native, type, errorContext) { + if (native == null) { + return new typesystem_1.OptionalValue(type); + } + let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); + return new typesystem_1.OptionalValue(type, converted); + } + function toVariadicValue(native, type, errorContext) { + if (type.isCounted) { + throw new errors_1.ErrInvalidArgument(`Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"`); + } + if (native == null) { + native = []; + } + if (native.map === void 0) { + errorContext.convertError(native, "Variadic"); + } + let converted = native.map(function(item) { + return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); + }); + return new typesystem_1.VariadicValue(type, converted); + } + function toListValue(native, type, errorContext) { + if (native.map === void 0) { + errorContext.convertError(native, "List"); + } + let converted = native.map(function(item) { + return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); + }); + return new typesystem_1.List(type, converted); + } + function toCompositeValue(native, type, errorContext) { + let typedValues = []; + let typeParameters = type.getTypeParameters(); + errorContext.guardSameLength(native, typeParameters); + for (let i2 = 0; i2 < typeParameters.length; i2++) { + typedValues.push(convertToTypedValue(native[i2], typeParameters[i2], errorContext)); + } + return new typesystem_1.CompositeValue(type, typedValues); + } + function toTupleValue(native, type, errorContext) { + let typedValues = []; + const fields = type.getFieldsDefinitions(); + errorContext.guardSameLength(native, fields); + for (let i2 = 0; i2 < fields.length; i2++) { + typedValues.push(convertToTypedValue(native[i2], fields[i2].type, errorContext)); + } + return typesystem_1.Tuple.fromItems(typedValues); + } + function toStructValue(native, type, errorContext) { + let structFieldValues = []; + const fields = type.getFieldsDefinitions(); + for (let i2 = 0; i2 < fields.length; i2++) { + const fieldName = fields[i2].name; + errorContext.guardHasField(native, fieldName); + const fieldNativeValue = native[fieldName]; + const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); + structFieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); + } + return new typesystem_1.Struct(type, structFieldValues); + } + function toPrimitive(native, type, errorContext) { + if (type instanceof typesystem_1.NumericalType) { + let number = new bignumber_js_1.default(native); + return convertNumericalType(number, type, errorContext); + } + if (type instanceof typesystem_1.BytesType) { + return convertNativeToBytesValue(native, errorContext); + } + if (type instanceof typesystem_1.AddressType) { + return new typesystem_1.AddressValue(convertNativeToAddress(native, errorContext)); + } + if (type instanceof typesystem_1.BooleanType) { + return new typesystem_1.BooleanValue(native); + } + if (type instanceof typesystem_1.TokenIdentifierType) { + return new typesystem_1.TokenIdentifierValue(convertNativeToString(native, errorContext)); + } + errorContext.throwError(`(function: toPrimitive) unsupported type ${type}`); + } + function toEnumValue(native, type, errorContext) { + if (typeof native === "number") { + return typesystem_1.EnumValue.fromDiscriminant(type, native); + } + if (typeof native === "string") { + return typesystem_1.EnumValue.fromName(type, native); + } + if (typeof native === "object") { + errorContext.guardHasField(native, "name"); + const variant = type.getVariantByName(native.name); + errorContext.guardHasField(native, "fields"); + const nativeFields = native.fields; + const fieldValues = []; + const fields = variant.getFieldsDefinitions(); + for (let i2 = 0; i2 < fields.length; i2++) { + const fieldName = fields[i2].name; + errorContext.guardHasField(nativeFields, fieldName); + const fieldNativeValue = nativeFields[fieldName]; + const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); + fieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); + } + return new typesystem_1.EnumValue(type, variant, fieldValues); + } + errorContext.throwError(`(function: toEnumValue) unsupported native type ${typeof native}`); + } + function convertNativeToBytesValue(native, errorContext) { + const innerValue = native.valueOf(); + if (native === void 0) { + errorContext.convertError(native, "BytesValue"); + } + if (native instanceof import_buffer.Buffer) { + return new typesystem_1.BytesValue(native); + } + if (typeof native === "string") { + return typesystem_1.BytesValue.fromUTF8(native); + } + if (innerValue instanceof import_buffer.Buffer) { + return new typesystem_1.BytesValue(innerValue); + } + if (typeof innerValue === "number") { + return typesystem_1.BytesValue.fromHex(utils_codec_1.numberToPaddedHex(innerValue)); + } + errorContext.convertError(native, "BytesValue"); + } + function convertNativeToString(native, errorContext) { + if (native === void 0) { + errorContext.convertError(native, "Buffer"); + } + if (native instanceof import_buffer.Buffer) { + return native.toString(); + } + if (typeof native === "string") { + return native; + } + errorContext.convertError(native, "Buffer"); + } + function convertNativeToAddress(native, errorContext) { + if (native.bech32) { + return native; + } + if (native.getAddress) { + return native.getAddress(); + } + switch (native.constructor) { + case import_buffer.Buffer: + case String: + return new address_1.Address(native); + default: + errorContext.convertError(native, "Address"); + } + } + NativeSerializer2.convertNativeToAddress = convertNativeToAddress; + function convertNumericalType(number, type, errorContext) { + switch (type.constructor) { + case typesystem_1.U8Type: + return new typesystem_1.U8Value(number); + case typesystem_1.I8Type: + return new typesystem_1.I8Value(number); + case typesystem_1.U16Type: + return new typesystem_1.U16Value(number); + case typesystem_1.I16Type: + return new typesystem_1.I16Value(number); + case typesystem_1.U32Type: + return new typesystem_1.U32Value(number); + case typesystem_1.I32Type: + return new typesystem_1.I32Value(number); + case typesystem_1.U64Type: + return new typesystem_1.U64Value(number); + case typesystem_1.I64Type: + return new typesystem_1.I64Value(number); + case typesystem_1.BigUIntType: + return new typesystem_1.BigUIntValue(number); + case typesystem_1.BigIntType: + return new typesystem_1.BigIntValue(number); + default: + errorContext.unhandledType("convertNumericalType", type); + } + } + })(NativeSerializer = exports2.NativeSerializer || (exports2.NativeSerializer = {})); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js +var require_tokenTransfersDataBuilder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenTransfersDataBuilder = void 0; + var argSerializer_1 = require_argSerializer(); + var typesystem_1 = require_typesystem(); + var tokens_1 = require_tokens(); + var TokenTransfersDataBuilder = class { + constructor() { + this.tokenComputer = new tokens_1.TokenComputer(); + this.argsSerializer = new argSerializer_1.ArgSerializer(); + } + buildDataPartsForESDTTransfer(transfer) { + const args = this.argsSerializer.valuesToStrings([ + new typesystem_1.TokenIdentifierValue(transfer.token.identifier), + new typesystem_1.BigUIntValue(transfer.amount) + ]); + return ["ESDTTransfer", ...args]; + } + buildDataPartsForSingleESDTNFTTransfer(transfer, receiver) { + const token = transfer.token; + const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(token.identifier); + const args = this.argsSerializer.valuesToStrings([ + new typesystem_1.TokenIdentifierValue(identifier), + new typesystem_1.BigUIntValue(token.nonce), + new typesystem_1.BigUIntValue(transfer.amount), + new typesystem_1.AddressValue(receiver) + ]); + return ["ESDTNFTTransfer", ...args]; + } + buildDataPartsForMultiESDTNFTTransfer(receiver, transfers) { + const argsTyped = [new typesystem_1.AddressValue(receiver), new typesystem_1.U32Value(transfers.length)]; + for (const transfer of transfers) { + const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(transfer.token.identifier); + argsTyped.push(...[ + new typesystem_1.TokenIdentifierValue(identifier), + new typesystem_1.BigUIntValue(transfer.token.nonce), + new typesystem_1.BigUIntValue(transfer.amount) + ]); + } + const args = this.argsSerializer.valuesToStrings(argsTyped); + return ["MultiESDTNFTTransfer", ...args]; + } + }; + exports2.TokenTransfersDataBuilder = TokenTransfersDataBuilder; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js +var require_smartContractTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractTransactionsFactory = void 0; + var address_1 = require_address(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var smartcontracts_1 = require_smartcontracts(); + var nativeSerializer_1 = require_nativeSerializer(); + var tokens_1 = require_tokens(); + var utils_codec_1 = require_utils_codec(); + var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); + var transactionBuilder_1 = require_transactionBuilder(); + var SmartContractTransactionsFactory2 = class { + constructor(options) { + this.config = options.config; + this.abi = options.abi; + this.tokenComputer = new tokens_1.TokenComputer(); + this.dataArgsBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); + } + createTransactionForDeploy(options) { + const nativeTransferAmount = options.nativeTransferAmount ?? 0n; + const isUpgradeable = options.isUpgradeable ?? true; + const isReadable = options.isReadable ?? true; + const isPayable = options.isPayable ?? false; + const isPayableBySmartContract = options.isPayableBySmartContract ?? true; + const args = options.arguments || []; + const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); + const dataParts = [utils_codec_1.byteArrayToHex(options.bytecode), utils_codec_1.byteArrayToHex(constants_1.VM_TYPE_WASM_VM), metadata.toString()]; + const endpoint = this.abi?.constructorDefinition; + const preparedArgs = this.argsToDataParts(args, endpoint); + dataParts.push(...preparedArgs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.CONTRACT_DEPLOY_ADDRESS), + dataParts, + gasLimit: options.gasLimit, + addDataMovementGas: false, + amount: nativeTransferAmount + }).build(); + } + createTransactionForExecute(options) { + const args = options.arguments || []; + const tokenTransfer = options.tokenTransfers || []; + const nativeTransferAmount = options.nativeTransferAmount ?? 0n; + const numberOfTokens = tokenTransfer.length; + if (nativeTransferAmount && numberOfTokens) { + throw new errors_1.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)"); + } + let receiver = options.contract; + let dataParts = []; + if (numberOfTokens === 1) { + const transfer = tokenTransfer[0]; + if (this.tokenComputer.isFungible(transfer.token)) { + dataParts = this.dataArgsBuilder.buildDataPartsForESDTTransfer(transfer); + } else { + dataParts = this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); + receiver = options.sender; + } + } else if (numberOfTokens > 1) { + dataParts = this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(receiver, tokenTransfer); + receiver = options.sender; + } + dataParts.push(dataParts.length ? utils_codec_1.utf8ToHex(options.function) : options.function); + const endpoint = this.abi?.getEndpoint(options.function); + const preparedArgs = this.argsToDataParts(args, endpoint); + dataParts.push(...preparedArgs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver, + dataParts, + gasLimit: options.gasLimit, + addDataMovementGas: false, + amount: nativeTransferAmount + }).build(); + } + createTransactionForUpgrade(options) { + const nativeTransferAmount = options.nativeTransferAmount ?? 0n; + const isUpgradeable = options.isUpgradeable ?? true; + const isReadable = options.isReadable ?? true; + const isPayable = options.isPayable ?? false; + const isPayableBySmartContract = options.isPayableBySmartContract ?? true; + const args = options.arguments || []; + const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); + const dataParts = ["upgradeContract", utils_codec_1.byteArrayToHex(options.bytecode), metadata.toString()]; + const endpoint = this.getEndpointForUpgrade(); + const preparedArgs = this.argsToDataParts(args, endpoint); + dataParts.push(...preparedArgs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.contract, + dataParts, + gasLimit: options.gasLimit, + addDataMovementGas: false, + amount: nativeTransferAmount + }).build(); + } + getEndpointForUpgrade() { + if (!this.abi) { + return void 0; + } + try { + return this.abi.getEndpoint("upgrade"); + } catch (error) { + logger_1.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."); + return this.abi.constructorDefinition; + } + } + createTransactionForClaimingDeveloperRewards(options) { + const dataParts = ["ClaimDeveloperRewards"]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.contract, + dataParts, + gasLimit: this.config.gasLimitClaimDeveloperRewards, + addDataMovementGas: false + }).build(); + } + createTransactionForChangingOwnerAddress(options) { + const dataParts = ["ChangeOwnerAddress", address_1.Address.fromBech32(options.newOwner.bech32()).toHex()]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.contract, + dataParts, + gasLimit: this.config.gasLimitChangeOwnerAddress, + addDataMovementGas: false + }).build(); + } + argsToDataParts(args, endpoint) { + if (endpoint) { + const typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args, endpoint); + return new smartcontracts_1.ArgSerializer().valuesToStrings(typedArgs); + } + if (this.areArgsOfTypedValue(args)) { + return new smartcontracts_1.ArgSerializer().valuesToStrings(args); + } + throw new errors_1.Err("Can't convert args to TypedValues"); + } + areArgsOfTypedValue(args) { + for (const arg of args) { + if (!arg.belongsToTypesystem) { + return false; + } + } + return true; + } + }; + exports2.SmartContractTransactionsFactory = SmartContractTransactionsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js +var require_tokenManagementTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenManagementTransactionsFactory = void 0; + var address_1 = require_address(); + var constants_1 = require_constants(); + var logger_1 = require_logger(); + var smartcontracts_1 = require_smartcontracts(); + var transactionBuilder_1 = require_transactionBuilder(); + var TokenManagementTransactionsFactory2 = class { + constructor(options) { + this.config = options.config; + this.argSerializer = new smartcontracts_1.ArgSerializer(); + this.trueAsString = "true"; + this.falseAsString = "false"; + } + createTransactionForIssuingFungible(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.BigUIntValue(options.initialSupply), + new smartcontracts_1.BigUIntValue(options.numDecimals), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["issue", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForIssuingSemiFungible(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canTransferNFTCreateRole"), + new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["issueSemiFungible", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForIssuingNonFungible(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canTransferNFTCreateRole"), + new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["issueNonFungible", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForRegisteringMetaESDT(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.BigUIntValue(options.numDecimals), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canTransferNFTCreateRole"), + new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["registerMetaESDT", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForRegisteringAndSettingRoles(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const dataParts = [ + "registerAndSetAllRoles", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.StringValue(options.tokenType), + new smartcontracts_1.BigUIntValue(options.numDecimals) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForSettingBurnRoleGlobally(options) { + const dataParts = [ + "setBurnRoleGlobally", + ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitToggleBurnRoleGlobally, + addDataMovementGas: true + }).build(); + } + createTransactionForUnsettingBurnRoleGlobally(options) { + const dataParts = [ + "unsetBurnRoleGlobally", + ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitToggleBurnRoleGlobally, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingSpecialRoleOnFungibleToken(options) { + const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; + options.addRoleLocalMint ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalMint")) : 0; + options.addRoleLocalBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalBurn")) : 0; + options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; + const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingSpecialRoleOnSemiFungibleToken(options) { + const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; + options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; + options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; + options.addRoleNFTAddQuantity ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddQuantity")) : 0; + options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; + const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingSpecialRoleOnMetaESDT(options) { + return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(options); + } + createTransactionForSettingSpecialRoleOnNonFungibleToken(options) { + const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; + options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; + options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; + options.addRoleNFTUpdateAttributes ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTUpdateAttributes")) : 0; + options.addRoleNFTAddURI ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddURI")) : 0; + options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; + const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true + }).build(); + } + createTransactionForCreatingNFT(options) { + const dataParts = [ + "ESDTNFTCreate", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.initialQuantity), + new smartcontracts_1.StringValue(options.name), + new smartcontracts_1.BigUIntValue(options.royalties), + new smartcontracts_1.StringValue(options.hash), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)), + ...options.uris.map((uri) => new smartcontracts_1.StringValue(uri)) + ]) + ]; + const nftData = options.name + options.hash + options.attributes + options.uris.join(""); + const storageGasLimit = this.config.gasLimitStorePerByte + BigInt(nftData.length); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftCreate + storageGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForPausing(options) { + const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)])]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitPausing, + addDataMovementGas: true + }).build(); + } + createTransactionForUnpausing(options) { + const dataParts = [ + "unPause", + ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitPausing, + addDataMovementGas: true + }).build(); + } + createTransactionForFreezing(options) { + const dataParts = [ + "freeze", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.AddressValue(options.user) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitFreezing, + addDataMovementGas: true + }).build(); + } + createTransactionForUnfreezing(options) { + const dataParts = [ + "UnFreeze", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.AddressValue(options.user) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitFreezing, + addDataMovementGas: true + }).build(); + } + createTransactionForWiping(options) { + const dataParts = [ + "wipe", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.AddressValue(options.user) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitWiping, + addDataMovementGas: true + }).build(); + } + createTransactionForLocalMint(options) { + const dataParts = [ + "ESDTLocalMint", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.supplyToMint) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtLocalMint, + addDataMovementGas: true + }).build(); + } + createTransactionForLocalBurning(options) { + const dataParts = [ + "ESDTLocalBurn", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.supplyToBurn) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtLocalBurn, + addDataMovementGas: true + }).build(); + } + createTransactionForUpdatingAttributes(options) { + const dataParts = [ + "ESDTNFTUpdateAttributes", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.tokenNonce), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftUpdateAttributes, + addDataMovementGas: true + }).build(); + } + createTransactionForAddingQuantity(options) { + const dataParts = [ + "ESDTNFTAddQuantity", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.tokenNonce), + new smartcontracts_1.BigUIntValue(options.quantityToAdd) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftAddQuantity, + addDataMovementGas: true + }).build(); + } + createTransactionForBurningQuantity(options) { + const dataParts = [ + "ESDTNFTBurn", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.tokenNonce), + new smartcontracts_1.BigUIntValue(options.quantityToBurn) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftBurn, + addDataMovementGas: true + }).build(); + } + notifyAboutUnsettingBurnRoleGlobally() { + logger_1.Logger.info(` +========== +IMPORTANT! +========== +You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); + } + boolToString(value) { + if (value) { + return this.trueAsString; + } + return this.falseAsString; + } + }; + exports2.TokenManagementTransactionsFactory = TokenManagementTransactionsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js +var require_transactionsFactoryConfig = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionsFactoryConfig = void 0; + var constants_1 = require_constants(); + var TransactionsFactoryConfig2 = class { + constructor(options) { + this.chainID = options.chainID; + this.addressHrp = constants_1.DEFAULT_HRP; + this.minGasLimit = 50000n; + this.gasLimitPerByte = 1500n; + this.gasLimitIssue = 60000000n; + this.gasLimitToggleBurnRoleGlobally = 60000000n; + this.gasLimitEsdtLocalMint = 300000n; + this.gasLimitEsdtLocalBurn = 300000n; + this.gasLimitSetSpecialRole = 60000000n; + this.gasLimitPausing = 60000000n; + this.gasLimitFreezing = 60000000n; + this.gasLimitWiping = 60000000n; + this.gasLimitEsdtNftCreate = 3000000n; + this.gasLimitEsdtNftUpdateAttributes = 1000000n; + this.gasLimitEsdtNftAddQuantity = 1000000n; + this.gasLimitEsdtNftBurn = 1000000n; + this.gasLimitStorePerByte = 10000n; + this.issueCost = 50000000000000000n; + this.gasLimitStake = 5000000n; + this.gasLimitUnstake = 5000000n; + this.gasLimitUnbond = 5000000n; + this.gasLimitCreateDelegationContract = 50000000n; + this.gasLimitDelegationOperations = 1000000n; + this.additionalGasLimitPerValidatorNode = 6000000n; + this.additionalGasLimitForDelegationOperations = 10000000n; + this.gasLimitSaveKeyValue = 100000n; + this.gasLimitPersistPerByte = 1000n; + this.gasLimitSetGuardian = 250000n; + this.gasLimitGuardAccount = 250000n; + this.gasLimitUnguardAccount = 250000n; + this.gasLimitESDTTransfer = 200000n; + this.gasLimitESDTNFTTransfer = 200000n; + this.gasLimitMultiESDTNFTTransfer = 200000n; + this.gasLimitClaimDeveloperRewards = 6000000n; + this.gasLimitChangeOwnerAddress = 6000000n; + } + }; + exports2.TransactionsFactoryConfig = TransactionsFactoryConfig2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js +var require_transferTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransferTransactionsFactory = void 0; + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var tokens_1 = require_tokens(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); + var transactionBuilder_1 = require_transactionBuilder(); + var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; + var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; + var TransferTransactionsFactory2 = class { + /** + * Should be instantiated using `Config` and `TokenComputer`. + * Instantiating this class using GasEstimator represents the legacy version of this class. + * The legacy version contains methods like `createEGLDTransfer`, `createESDTTransfer`, `createESDTNFTTransfer` and `createMultiESDTNFTTransfer`. + * This was done in order to minimize breaking changes in client code. + */ + constructor(options) { + if (this.isGasEstimator(options)) { + this.gasEstimator = options; + } else { + this.config = options.config; + this.tokenComputer = new tokens_1.TokenComputer(); + this.tokenTransfersDataBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); + } + } + isGasEstimator(options) { + return typeof options === "object" && typeof options.forEGLDTransfer === "function" && typeof options.forESDTTransfer === "function" && typeof options.forESDTNFTTransfer === "function" && typeof options.forMultiESDTNFTTransfer === "function"; + } + isGasEstimatorDefined() { + return this.gasEstimator !== void 0; + } + ensureMembersAreDefined() { + if (this.config === void 0) { + throw new errors_1.Err("'config' is not defined"); + } + if (this.tokenTransfersDataBuilder === void 0) { + throw new errors_1.Err("`dataArgsBuilder is not defined`"); + } + if (this.tokenComputer === void 0) { + throw new errors_1.Err("`tokenComputer is not defined`"); + } + } + createTransactionForNativeTokenTransfer(options) { + this.ensureMembersAreDefined(); + const data = options.data || new Uint8Array(); + return new transaction_1.Transaction({ + sender: options.sender.bech32(), + receiver: options.receiver.bech32(), + chainID: this.config.chainID, + gasLimit: this.computeGasForMoveBalance(this.config, data), + data, + value: options.nativeAmount + }); + } + createTransactionForESDTTokenTransfer(options) { + this.ensureMembersAreDefined(); + const numberOfTransfers = options.tokenTransfers.length; + if (numberOfTransfers === 0) { + throw new errors_1.ErrBadUsage("No token transfer has been provided"); + } + if (numberOfTransfers === 1) { + return this.createSingleESDTTransferTransaction(options); + } + const dataParts = this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(options.receiver, options.tokenTransfers); + const extraGasForTransfer = this.config.gasLimitMultiESDTNFTTransfer * BigInt(numberOfTransfers) + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: extraGasForTransfer, + addDataMovementGas: true + }).build(); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForNativeTokenTransfer} instead. + */ + createEGLDTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method."); + } + const dataLength = args.data?.length() || 0; + const estimatedGasLimit = this.gasEstimator.forEGLDTransfer(dataLength); + return new transaction_1.Transaction({ + nonce: args.nonce, + value: args.value, + receiver: args.receiver, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: args.data, + chainID: args.chainID + }); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForESDTTokenTransfer} instead. + */ + createESDTTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + // The token identifier + smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), + // The transfered amount + new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()) + ]); + const data = `ESDTTransfer@${argumentsString}`; + const transactionPayload = new transactionPayload_1.TransactionPayload(data); + const dataLength = transactionPayload.length() || 0; + const estimatedGasLimit = this.gasEstimator.forESDTTransfer(dataLength); + return new transaction_1.Transaction({ + nonce: args.nonce, + receiver: args.receiver, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: transactionPayload, + chainID: args.chainID + }); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForESDTTokenTransfer} instead. + */ + createESDTNFTTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + // The token identifier + smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), + // The nonce of the token + new smartcontracts_1.U64Value(args.tokenTransfer.nonce), + // The transferred quantity + new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()), + // The destination address + new smartcontracts_1.AddressValue(args.destination) + ]); + const data = `ESDTNFTTransfer@${argumentsString}`; + const transactionPayload = new transactionPayload_1.TransactionPayload(data); + const dataLength = transactionPayload.length() || 0; + const estimatedGasLimit = this.gasEstimator.forESDTNFTTransfer(dataLength); + return new transaction_1.Transaction({ + nonce: args.nonce, + receiver: args.sender, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: transactionPayload, + chainID: args.chainID + }); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForESDTTokenTransfer} instead. + */ + createMultiESDTNFTTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); + } + const parts = [ + // The destination address + new smartcontracts_1.AddressValue(args.destination), + // Number of tokens + new smartcontracts_1.U16Value(args.tokenTransfers.length) + ]; + for (const payment of args.tokenTransfers) { + parts.push(...[ + // The token identifier + smartcontracts_1.BytesValue.fromUTF8(payment.tokenIdentifier), + // The nonce of the token + new smartcontracts_1.U64Value(payment.nonce), + // The transfered quantity + new smartcontracts_1.BigUIntValue(payment.valueOf()) + ]); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString(parts); + const data = `MultiESDTNFTTransfer@${argumentsString}`; + const transactionPayload = new transactionPayload_1.TransactionPayload(data); + const dataLength = transactionPayload.length() || 0; + const estimatedGasLimit = this.gasEstimator.forMultiESDTNFTTransfer(dataLength, args.tokenTransfers.length); + return new transaction_1.Transaction({ + nonce: args.nonce, + receiver: args.sender, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: transactionPayload, + chainID: args.chainID + }); + } + createSingleESDTTransferTransaction(options) { + this.ensureMembersAreDefined(); + let dataParts = []; + const transfer = options.tokenTransfers[0]; + let extraGasForTransfer = 0n; + let receiver = options.receiver; + if (this.tokenComputer.isFungible(transfer.token)) { + dataParts = this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(transfer); + extraGasForTransfer = this.config.gasLimitESDTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_TRANSFER); + } else { + dataParts = this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); + extraGasForTransfer = this.config.gasLimitESDTNFTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); + receiver = options.sender; + } + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver, + dataParts, + gasLimit: extraGasForTransfer, + addDataMovementGas: true + }).build(); + } + computeGasForMoveBalance(config, data) { + return config.minGasLimit + config.gasLimitPerByte * BigInt(data.length); + } + }; + exports2.TransferTransactionsFactory = TransferTransactionsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js +var require_accountTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AccountTransactionsFactory = void 0; + var address_1 = require_address(); + var transactionBuilder_1 = require_transactionBuilder(); + var AccountTransactionsFactory = class { + constructor(options) { + this.config = options.config; + } + createTransactionForSavingKeyValue(options) { + const functionName = "SaveKeyValue"; + const keyValueParts = this.computeDataPartsForSavingKeyValue(options.keyValuePairs); + const dataParts = [functionName, ...keyValueParts]; + const extraGas = this.computeExtraGasForSavingKeyValue(options.keyValuePairs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: extraGas, + addDataMovementGas: true + }).build(); + } + computeExtraGasForSavingKeyValue(keyValuePairs) { + let extraGas = 0n; + keyValuePairs.forEach((value, key) => { + extraGas += this.config.gasLimitPersistPerByte * BigInt(key.length + value.length) + this.config.gasLimitStorePerByte * BigInt(value.length); + }); + return extraGas + this.config.gasLimitSaveKeyValue; + } + computeDataPartsForSavingKeyValue(keyValuePairs) { + const dataParts = []; + keyValuePairs.forEach((value, key) => { + dataParts.push(...[import_buffer.Buffer.from(key).toString("hex"), import_buffer.Buffer.from(value).toString("hex")]); + }); + return dataParts; + } + createTransactionForSettingGuardian(options) { + const dataParts = [ + "SetGuardian", + address_1.Address.fromBech32(options.guardianAddress.bech32()).toHex(), + import_buffer.Buffer.from(options.serviceID).toString("hex") + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitSetGuardian, + addDataMovementGas: true + }).build(); + } + createTransactionForGuardingAccount(options) { + const dataParts = ["GuardAccount"]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitGuardAccount, + addDataMovementGas: true + }).build(); + } + createTransactionForUnguardingAccount(options) { + const dataParts = ["UnGuardAccount"]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitUnguardAccount, + addDataMovementGas: true + }).build(); + } + }; + exports2.AccountTransactionsFactory = AccountTransactionsFactory; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js +var require_transactionsFactories = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_delegationTransactionsFactory(), exports2); + __exportStar2(require_relayedTransactionsFactory(), exports2); + __exportStar2(require_smartContractTransactionsFactory(), exports2); + __exportStar2(require_tokenManagementTransactionsFactory(), exports2); + __exportStar2(require_transactionsFactoryConfig(), exports2); + __exportStar2(require_transferTransactionsFactory(), exports2); + __exportStar2(require_accountTransactionsFactory(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js +var require_interactionChecker = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InteractionChecker = void 0; + var errors = __importStar2(require_errors()); + var bignumber_js_1 = __importDefault2(require_bignumber()); + var InteractionChecker = class { + checkInteraction(interaction, definition) { + this.checkPayable(interaction, definition); + this.checkArguments(interaction, definition); + } + checkPayable(interaction, definition) { + let hasValue = !new bignumber_js_1.default(interaction.getValue().toString()).isZero(); + let isPayableInEGLD = definition.modifiers.isPayableInEGLD(); + if (hasValue && !isPayableInEGLD) { + throw new errors.ErrContractInteraction("cannot send EGLD value to non-payable"); + } + } + checkArguments(interaction, definition) { + let formalArguments = definition.input; + let actualArguments = interaction.getArguments(); + let numFormalArguments = formalArguments.length; + let numActualArguments = actualArguments.length; + if (numFormalArguments != numActualArguments) { + throw new errors.ErrContractInteraction(`bad arguments, expected: ${numFormalArguments}, got: ${numActualArguments}`); + } + for (let i2 = 0; i2 < numFormalArguments; i2++) { + let expectedType = formalArguments[i2].type; + let argument = actualArguments[i2]; + let actualType = argument.getType(); + let ok = expectedType.isAssignableFrom(actualType); + if (!ok) { + throw new errors.ErrContractInteraction(`type mismatch at index ${i2}, expected: ${expectedType}, got: ${actualType}`); + } + } + } + }; + exports2.InteractionChecker = InteractionChecker; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/query.js +var require_query = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/query.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Query = void 0; + var address_1 = require_address(); + var argSerializer_1 = require_argSerializer(); + var Query2 = class { + constructor(obj) { + this.caller = obj.caller || address_1.Address.empty(); + this.address = obj.address; + this.func = obj.func; + this.args = obj.args || []; + this.value = obj.value || 0; + } + getEncodedArguments() { + return new argSerializer_1.ArgSerializer().valuesToStrings(this.args); + } + }; + exports2.Query = Query2; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js +var require_interaction = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Interaction = void 0; + var address_1 = require_address(); + var compatibility_1 = require_compatibility(); + var constants_1 = require_constants(); + var tokens_1 = require_tokens(); + var transactionsFactories_1 = require_transactionsFactories(); + var interactionChecker_1 = require_interactionChecker(); + var query_1 = require_query(); + var Interaction = class { + constructor(contract, func, args) { + this.nonce = 0; + this.value = "0"; + this.gasLimit = 0; + this.gasPrice = void 0; + this.chainID = ""; + this.querent = address_1.Address.empty(); + this.sender = address_1.Address.empty(); + this.version = constants_1.TRANSACTION_VERSION_DEFAULT; + this.contract = contract; + this.function = func; + this.args = args; + this.tokenTransfers = []; + } + getContractAddress() { + return this.contract.getAddress(); + } + getFunction() { + return this.function; + } + getEndpoint() { + return this.contract.getEndpoint(this.function); + } + getArguments() { + return this.args; + } + getValue() { + return this.value; + } + getTokenTransfers() { + return this.tokenTransfers; + } + getGasLimit() { + return this.gasLimit; + } + getExplicitReceiver() { + return this.explicitReceiver; + } + buildTransaction() { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(this.sender, "'sender' of interaction", "use interaction.withSender()"); + const factoryConfig = new transactionsFactories_1.TransactionsFactoryConfig({ chainID: this.chainID.valueOf() }); + const factory = new transactionsFactories_1.SmartContractTransactionsFactory({ + config: factoryConfig + }); + const transaction = factory.createTransactionForExecute({ + sender: this.sender, + contract: this.contract.getAddress(), + function: this.function.valueOf(), + gasLimit: BigInt(this.gasLimit.valueOf()), + arguments: this.args, + nativeTransferAmount: BigInt(this.value.toString()), + tokenTransfers: this.tokenTransfers + }); + transaction.chainID = this.chainID.valueOf(); + transaction.nonce = BigInt(this.nonce.valueOf()); + transaction.version = this.version; + if (this.gasPrice) { + transaction.gasPrice = BigInt(this.gasPrice.valueOf()); + } + return transaction; + } + buildQuery() { + return new query_1.Query({ + address: this.contract.getAddress(), + func: this.function, + args: this.args, + // Value will be set using "withValue()". + value: this.value, + caller: this.querent + }); + } + withValue(value) { + this.value = value; + return this; + } + withSingleESDTTransfer(transfer) { + this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); + return this; + } + withSingleESDTNFTTransfer(transfer) { + this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); + return this; + } + withMultiESDTNFTTransfer(transfers) { + this.tokenTransfers = transfers.map((transfer) => new tokens_1.TokenTransfer(transfer)); + return this; + } + withGasLimit(gasLimit) { + this.gasLimit = gasLimit; + return this; + } + withGasPrice(gasPrice) { + this.gasPrice = gasPrice; + return this; + } + withNonce(nonce) { + this.nonce = nonce; + return this; + } + useThenIncrementNonceOf(account) { + return this.withNonce(account.getNonceThenIncrement()); + } + withChainID(chainID) { + this.chainID = chainID; + return this; + } + withSender(sender) { + this.sender = sender; + return this; + } + withVersion(version2) { + this.version = version2; + return this; + } + /** + * Sets the "caller" field on contract queries. + */ + withQuerent(querent) { + this.querent = querent; + return this; + } + withExplicitReceiver(receiver) { + this.explicitReceiver = receiver; + return this; + } + /** + * To perform custom checking, extend {@link Interaction} and override this method. + */ + check() { + new interactionChecker_1.InteractionChecker().checkInteraction(this, this.getEndpoint()); + return this; + } + }; + exports2.Interaction = Interaction; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js +var require_interface = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js +var require_dist = __commonJS({ + "node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bech32m = exports2.bech32 = void 0; + var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + var ALPHABET_MAP = {}; + for (let z3 = 0; z3 < ALPHABET.length; z3++) { + const x3 = ALPHABET.charAt(z3); + ALPHABET_MAP[x3] = z3; + } + function polymodStep(pre) { + const b4 = pre >> 25; + return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; + } + function prefixChk(prefix) { + let chk = 1; + for (let i2 = 0; i2 < prefix.length; ++i2) { + const c4 = prefix.charCodeAt(i2); + if (c4 < 33 || c4 > 126) + return "Invalid prefix (" + prefix + ")"; + chk = polymodStep(chk) ^ c4 >> 5; + } + chk = polymodStep(chk); + for (let i2 = 0; i2 < prefix.length; ++i2) { + const v2 = prefix.charCodeAt(i2); + chk = polymodStep(chk) ^ v2 & 31; + } + return chk; + } + function convert(data, inBits, outBits, pad) { + let value = 0; + let bits = 0; + const maxV = (1 << outBits) - 1; + const result = []; + for (let i2 = 0; i2 < data.length; ++i2) { + value = value << inBits | data[i2]; + bits += inBits; + while (bits >= outBits) { + bits -= outBits; + result.push(value >> bits & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push(value << outBits - bits & maxV); + } + } else { + if (bits >= inBits) + return "Excess padding"; + if (value << outBits - bits & maxV) + return "Non-zero padding"; + } + return result; + } + function toWords(bytes) { + return convert(bytes, 8, 5, true); + } + function fromWordsUnsafe(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + } + function fromWords(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + throw new Error(res); + } + function getLibraryFromEncoding(encoding) { + let ENCODING_CONST; + if (encoding === "bech32") { + ENCODING_CONST = 1; + } else { + ENCODING_CONST = 734539939; + } + function encode5(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) + throw new TypeError("Exceeds length limit"); + prefix = prefix.toLowerCase(); + let chk = prefixChk(prefix); + if (typeof chk === "string") + throw new Error(chk); + let result = prefix + "1"; + for (let i2 = 0; i2 < words.length; ++i2) { + const x3 = words[i2]; + if (x3 >> 5 !== 0) + throw new Error("Non 5-bit word"); + chk = polymodStep(chk) ^ x3; + result += ALPHABET.charAt(x3); + } + for (let i2 = 0; i2 < 6; ++i2) { + chk = polymodStep(chk); + } + chk ^= ENCODING_CONST; + for (let i2 = 0; i2 < 6; ++i2) { + const v2 = chk >> (5 - i2) * 5 & 31; + result += ALPHABET.charAt(v2); + } + return result; + } + function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) + return str + " too short"; + if (str.length > LIMIT) + return "Exceeds length limit"; + const lowered = str.toLowerCase(); + const uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) + return "Mixed-case string " + str; + str = lowered; + const split = str.lastIndexOf("1"); + if (split === -1) + return "No separator character for " + str; + if (split === 0) + return "Missing prefix for " + str; + const prefix = str.slice(0, split); + const wordChars = str.slice(split + 1); + if (wordChars.length < 6) + return "Data too short"; + let chk = prefixChk(prefix); + if (typeof chk === "string") + return chk; + const words = []; + for (let i2 = 0; i2 < wordChars.length; ++i2) { + const c4 = wordChars.charAt(i2); + const v2 = ALPHABET_MAP[c4]; + if (v2 === void 0) + return "Unknown character " + c4; + chk = polymodStep(chk) ^ v2; + if (i2 + 6 >= wordChars.length) + continue; + words.push(v2); + } + if (chk !== ENCODING_CONST) + return "Invalid checksum for " + str; + return { prefix, words }; + } + function decodeUnsafe(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === "object") + return res; + } + function decode6(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === "object") + return res; + throw new Error(res); + } + return { + decodeUnsafe, + decode: decode6, + encode: encode5, + toWords, + fromWordsUnsafe, + fromWords + }; + } + exports2.bech32 = getLibraryFromEncoding("bech32"); + exports2.bech32m = getLibraryFromEncoding("bech32m"); + } +}); + +// node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js +var require_transaction_decoder = __commonJS({ + "node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenTransferProperties = exports2.TransactionMetadataTransfer = exports2.TransactionMetadata = exports2.TransactionToDecode = exports2.TransactionDecoder = void 0; + var bech32_1 = require_dist(); + var TransactionDecoder = class { + getTransactionMetadata(transaction) { + const metadata = this.getNormalTransactionMetadata(transaction); + const esdtMetadata = this.getEsdtTransactionMetadata(metadata); + if (esdtMetadata) { + return esdtMetadata; + } + const nftMetadata = this.getNftTransferMetadata(metadata); + if (nftMetadata) { + return nftMetadata; + } + const multiMetadata = this.getMultiTransferMetadata(metadata); + if (multiMetadata) { + return multiMetadata; + } + return metadata; + } + getNormalTransactionMetadata(transaction) { + const metadata = new TransactionMetadata(); + metadata.sender = transaction.sender; + metadata.receiver = transaction.receiver; + metadata.value = BigInt(transaction.value); + if (transaction.data) { + const decodedData = this.base64Decode(transaction.data); + const dataComponents = decodedData.split("@"); + const args = dataComponents.slice(1); + if (args.every((x3) => this.isSmartContractArgument(x3))) { + metadata.functionName = dataComponents[0]; + metadata.functionArgs = args; + } + if (metadata.functionName === "relayedTx" && metadata.functionArgs && metadata.functionArgs.length === 1) { + try { + const relayedTransaction = JSON.parse(this.hexToString(metadata.functionArgs[0])); + relayedTransaction.value = relayedTransaction.value.toString(); + relayedTransaction.sender = this.bech32Encode(this.base64ToHex(relayedTransaction.sender)); + relayedTransaction.receiver = this.bech32Encode(this.base64ToHex(relayedTransaction.receiver)); + return this.getNormalTransactionMetadata(relayedTransaction); + } catch (error) { + } + } + if (metadata.functionName === "relayedTxV2" && metadata.functionArgs && metadata.functionArgs.length === 4) { + try { + const relayedTransaction = new TransactionToDecode(); + relayedTransaction.sender = transaction.receiver; + relayedTransaction.receiver = this.bech32Encode(metadata.functionArgs[0]); + relayedTransaction.data = this.base64Encode(this.hexToString(metadata.functionArgs[2])); + relayedTransaction.value = "0"; + return this.getNormalTransactionMetadata(relayedTransaction); + } catch (error) { + } + } + } + return metadata; + } + getMultiTransferMetadata(metadata) { + if (metadata.sender !== metadata.receiver) { + return void 0; + } + if (metadata.functionName !== "MultiESDTNFTTransfer") { + return void 0; + } + const args = metadata.functionArgs; + if (!args) { + return void 0; + } + if (args.length < 3) { + return void 0; + } + if (!this.isAddressValid(args[0])) { + return void 0; + } + const receiver = this.bech32Encode(args[0]); + const transferCount = this.hexToNumber(args[1]); + const result = new TransactionMetadata(); + if (!result.transfers) { + result.transfers = []; + } + let index = 2; + for (let i2 = 0; i2 < transferCount; i2++) { + const identifier = this.hexToString(args[index++]); + const nonce = args[index++]; + const value = this.hexToBigInt(args[index++]); + if (nonce) { + result.transfers.push({ + value, + properties: { + collection: identifier, + identifier: `${identifier}-${nonce}` + } + }); + } else { + result.transfers.push({ + value, + properties: { + token: identifier + } + }); + } + } + result.sender = metadata.sender; + result.receiver = receiver; + if (args.length > index) { + result.functionName = this.hexToString(args[index++]); + result.functionArgs = args.slice(index++); + } + return result; + } + getNftTransferMetadata(metadata) { + if (metadata.sender !== metadata.receiver) { + return void 0; + } + if (metadata.functionName !== "ESDTNFTTransfer") { + return void 0; + } + const args = metadata.functionArgs; + if (!args) { + return void 0; + } + if (args.length < 4) { + return void 0; + } + if (!this.isAddressValid(args[3])) { + return void 0; + } + const collectionIdentifier = this.hexToString(args[0]); + const nonce = args[1]; + const value = this.hexToBigInt(args[2]); + const receiver = this.bech32Encode(args[3]); + const result = new TransactionMetadata(); + result.sender = metadata.sender; + result.receiver = receiver; + result.value = value; + if (args.length > 4) { + result.functionName = this.hexToString(args[4]); + result.functionArgs = args.slice(5); + } + result.transfers = [{ + value, + properties: { + collection: collectionIdentifier, + identifier: `${collectionIdentifier}-${nonce}` + } + }]; + return result; + } + base64Encode(str) { + return import_buffer.Buffer.from(str).toString("base64"); + } + base64Decode(str) { + return import_buffer.Buffer.from(str, "base64").toString("binary"); + } + hexToNumber(hex) { + return parseInt(hex, 16); + } + getEsdtTransactionMetadata(metadata) { + if (metadata.functionName !== "ESDTTransfer") { + return void 0; + } + const args = metadata.functionArgs; + if (!args) { + return void 0; + } + if (args.length < 2) { + return void 0; + } + const tokenIdentifier = this.hexToString(args[0]); + const value = this.hexToBigInt(args[1]); + const result = new TransactionMetadata(); + result.sender = metadata.sender; + result.receiver = metadata.receiver; + if (args.length > 2) { + result.functionName = this.hexToString(args[2]); + result.functionArgs = args.slice(3); + } + result.transfers = [{ + value, + properties: { + identifier: tokenIdentifier + } + }]; + result.value = value; + return result; + } + bech32Encode(address) { + const pubKey = import_buffer.Buffer.from(address, "hex"); + const words = bech32_1.bech32.toWords(pubKey); + return bech32_1.bech32.encode("erd", words); + } + isAddressValid(address) { + return import_buffer.Buffer.from(address, "hex").length == 32; + } + isSmartContractArgument(arg) { + if (!this.isHex(arg)) { + return false; + } + if (arg.length % 2 !== 0) { + return false; + } + return true; + } + isHex(value) { + return new RegExp(/[^a-f0-9]/gi).test(value) === false; + } + base64ToHex(str) { + return import_buffer.Buffer.from(str, "base64").toString("hex"); + } + hexToString(hex) { + return import_buffer.Buffer.from(hex, "hex").toString("ascii"); + } + hexToBigInt(hex) { + if (!hex) { + return BigInt(0); + } + return BigInt("0x" + hex); + } + }; + exports2.TransactionDecoder = TransactionDecoder; + var TransactionToDecode = class { + constructor() { + this.sender = ""; + this.receiver = ""; + this.data = ""; + this.value = "0"; + } + }; + exports2.TransactionToDecode = TransactionToDecode; + var TransactionMetadata = class { + constructor() { + this.sender = ""; + this.receiver = ""; + this.value = BigInt(0); + } + }; + exports2.TransactionMetadata = TransactionMetadata; + var TransactionMetadataTransfer = class { + constructor() { + this.value = BigInt(0); + } + }; + exports2.TransactionMetadataTransfer = TransactionMetadataTransfer; + var TokenTransferProperties = class { + }; + exports2.TokenTransferProperties = TokenTransferProperties; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js +var require_returnCode = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReturnCode = void 0; + var ReturnCode = class _ReturnCode { + constructor(text) { + this.text = text; + } + static fromBuffer(buffer) { + let text = buffer.toString(); + return new _ReturnCode(text); + } + toString() { + return this.text; + } + valueOf() { + return this.text; + } + equals(other) { + if (!other) { + return false; + } + return this.text == other.text; + } + isSuccess() { + return this.equals(_ReturnCode.Ok) || this.equals(_ReturnCode.None); + } + }; + exports2.ReturnCode = ReturnCode; + ReturnCode.None = new ReturnCode(""); + ReturnCode.Ok = new ReturnCode("ok"); + ReturnCode.FunctionNotFound = new ReturnCode("function not found"); + ReturnCode.FunctionWrongSignature = new ReturnCode("wrong signature for function"); + ReturnCode.ContractNotFound = new ReturnCode("contract not found"); + ReturnCode.UserError = new ReturnCode("user error"); + ReturnCode.OutOfGas = new ReturnCode("out of gas"); + ReturnCode.AccountCollision = new ReturnCode("account collision"); + ReturnCode.OutOfFunds = new ReturnCode("out of funds"); + ReturnCode.CallStackOverFlow = new ReturnCode("call stack overflow"); + ReturnCode.ContractInvalid = new ReturnCode("contract invalid"); + ReturnCode.ExecutionFailed = new ReturnCode("execution failed"); + ReturnCode.Unknown = new ReturnCode("unknown"); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js +var require_resultsParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ResultsParser = void 0; + var transaction_decoder_1 = require_transaction_decoder(); + var address_1 = require_address(); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var argSerializer_1 = require_argSerializer(); + var returnCode_1 = require_returnCode(); + var WellKnownEvents; + (function(WellKnownEvents2) { + WellKnownEvents2["OnTransactionCompleted"] = "completedTxEvent"; + WellKnownEvents2["OnSignalError"] = "signalError"; + WellKnownEvents2["OnWriteLog"] = "writeLog"; + })(WellKnownEvents || (WellKnownEvents = {})); + var WellKnownTopics; + (function(WellKnownTopics2) { + WellKnownTopics2["TooMuchGas"] = "@too much gas provided for processing"; + })(WellKnownTopics || (WellKnownTopics = {})); + var defaultResultsParserOptions = { + argsSerializer: new argSerializer_1.ArgSerializer() + }; + var ResultsParser = class { + constructor(options) { + options = { ...defaultResultsParserOptions, ...options }; + this.argsSerializer = options.argsSerializer; + } + /** + * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. + */ + parseQueryResponse(queryResponse, endpoint) { + let parts = queryResponse.getReturnDataParts(); + let values = this.argsSerializer.buffersToValues(parts, endpoint.output); + let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); + return { + returnCode, + returnMessage: queryResponse.returnMessage, + values, + firstValue: values[0], + secondValue: values[1], + thirdValue: values[2], + lastValue: values[values.length - 1] + }; + } + /** + * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. + */ + parseUntypedQueryResponse(queryResponse) { + let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); + return { + returnCode, + returnMessage: queryResponse.returnMessage, + values: queryResponse.getReturnDataParts() + }; + } + /** + * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. + */ + parseOutcome(transaction, endpoint) { + const untypedBundle = this.parseUntypedOutcome(transaction); + const typedBundle = this.parseOutcomeFromUntypedBundle(untypedBundle, endpoint); + return typedBundle; + } + /** + * @internal + * For internal use only. + */ + parseOutcomeFromUntypedBundle(bundle, endpoint) { + const values = this.argsSerializer.buffersToValues(bundle.values, endpoint.output); + return { + returnCode: bundle.returnCode, + returnMessage: bundle.returnMessage, + values, + firstValue: values[0], + secondValue: values[1], + thirdValue: values[2], + lastValue: values[values.length - 1] + }; + } + /** + * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. + */ + parseUntypedOutcome(transaction) { + let bundle; + let transactionMetadata = this.parseTransactionMetadata(transaction); + bundle = this.createBundleOnSimpleMoveBalance(transaction); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on simple move balance"); + return bundle; + } + bundle = this.createBundleOnInvalidTransaction(transaction); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on invalid transaction"); + return bundle; + } + bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.contractResults); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on easily found result with return data"); + return bundle; + } + bundle = this.createBundleOnSignalError(transaction.logs); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on signal error"); + return bundle; + } + bundle = this.createBundleOnTooMuchGasWarning(transaction.logs); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"); + return bundle; + } + bundle = this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(transaction.logs, transaction.sender); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"); + return bundle; + } + bundle = this.createBundleWithCustomHeuristics(transaction, transactionMetadata); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): with custom heuristics"); + return bundle; + } + bundle = this.createBundleWithFallbackHeuristics(transaction, transactionMetadata); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): with fallback heuristics"); + return bundle; + } + throw new errors_1.ErrCannotParseContractResults(`transaction ${transaction.hash.toString()}`); + } + parseTransactionMetadata(transaction) { + return new transaction_decoder_1.TransactionDecoder().getTransactionMetadata({ + sender: transaction.sender.bech32(), + receiver: transaction.receiver.bech32(), + data: transaction.data.toString("base64"), + value: transaction.value.toString() + }); + } + createBundleOnSimpleMoveBalance(transaction) { + let noResults = transaction.contractResults.items.length == 0; + let noLogs = transaction.logs.events.length == 0; + if (noResults && noLogs) { + return { + returnCode: returnCode_1.ReturnCode.None, + returnMessage: returnCode_1.ReturnCode.None.toString(), + values: [] + }; + } + return null; + } + createBundleOnInvalidTransaction(transaction) { + if (transaction.status.isInvalid()) { + if (transaction.receipt.data) { + return { + returnCode: returnCode_1.ReturnCode.OutOfFunds, + returnMessage: transaction.receipt.data, + values: [] + }; + } + } + return null; + } + createBundleOnEasilyFoundResultWithReturnData(results) { + let resultItemWithReturnData = results.items.find((item) => item.nonce.valueOf() != 0 && item.data.startsWith("@")); + if (!resultItemWithReturnData) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data); + let returnMessage = resultItemWithReturnData.returnMessage || returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + createBundleOnSignalError(logs) { + let eventSignalError = logs.findSingleOrNoneEvent(WellKnownEvents.OnSignalError); + if (!eventSignalError) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventSignalError.data); + let lastTopic = eventSignalError.getLastTopic(); + let returnMessage = lastTopic?.toString() || returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + createBundleOnTooMuchGasWarning(logs) { + let eventTooMuchGas = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.toString().startsWith(WellKnownTopics.TooMuchGas)) != void 0); + if (!eventTooMuchGas) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data); + let lastTopic = eventTooMuchGas.getLastTopic(); + let returnMessage = lastTopic?.toString() || returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + createBundleOnWriteLogWhereFirstTopicEqualsAddress(logs, address) { + let hexAddress = new address_1.Address(address.bech32()).hex(); + let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.hex() == hexAddress) != void 0); + if (!eventWriteLogWhereTopicIsSender) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventWriteLogWhereTopicIsSender.data); + let returnMessage = returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + /** + * Override this method (in a subclass of {@link ResultsParser}) if the basic heuristics of the parser are not sufficient. + */ + createBundleWithCustomHeuristics(_transaction, _transactionMetadata) { + return null; + } + createBundleWithFallbackHeuristics(transaction, transactionMetadata) { + let contractAddress = new address_1.Address(transactionMetadata.receiver); + for (const resultItem of transaction.contractResults.items) { + let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { + let addressIsSender = event.address.bech32() == transaction.sender.bech32(); + let firstTopicIsContract = event.topics[0]?.hex() == contractAddress.hex(); + return addressIsSender && firstTopicIsContract; + }); + if (writeLogWithReturnData) { + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(writeLogWithReturnData.data); + let returnMessage = returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + } + return null; + } + sliceDataFieldInParts(data) { + let startingIndex = 1; + if (data.startsWith("ESDTTransfer")) { + startingIndex = 3; + } else { + } + let parts = this.argsSerializer.stringToBuffers(data); + let returnCodePart = parts[startingIndex] || import_buffer.Buffer.from([]); + let returnDataParts = parts.slice(startingIndex + 1); + if (returnCodePart.length == 0) { + throw new errors_1.ErrCannotParseContractResults("no return code"); + } + let returnCode = returnCode_1.ReturnCode.fromBuffer(returnCodePart); + return { returnCode, returnDataParts }; + } + /** + * Legacy method, use "TransactionEventsParser.parseEvent()" instead. + */ + parseEvent(transactionEvent, eventDefinition) { + const topics = transactionEvent.topics.map((topic) => import_buffer.Buffer.from(topic.valueOf())).slice(1); + const legacyData = transactionEvent.dataPayload?.valueOf() || import_buffer.Buffer.from([]); + const dataItems = transactionEvent.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; + if (dataItems.length === 0) { + if (legacyData.length) { + dataItems.push(import_buffer.Buffer.from(legacyData)); + } + } + return this.doParseEvent({ topics, dataItems, eventDefinition }); + } + /** + * @internal + * For internal use only. + * + * Once the legacy "ResultParser" is deprecated & removed, this logic will be absorbed into "TransactionEventsParser". + */ + doParseEvent(options) { + const result = {}; + const indexedInputs = options.eventDefinition.inputs.filter((input) => input.indexed); + const decodedTopics = this.argsSerializer.buffersToValues(options.topics, indexedInputs); + for (let i2 = 0; i2 < indexedInputs.length; i2++) { + result[indexedInputs[i2].name] = decodedTopics[i2].valueOf(); + } + const nonIndexedInputs = options.eventDefinition.inputs.filter((input) => !input.indexed); + const decodedDataParts = this.argsSerializer.buffersToValues(options.dataItems, nonIndexedInputs); + for (let i2 = 0; i2 < nonIndexedInputs.length; i2++) { + result[nonIndexedInputs[i2].name] = decodedDataParts[i2].valueOf(); + } + return result; + } + }; + exports2.ResultsParser = ResultsParser; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js +var require_smartContract = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContract = void 0; + var address_1 = require_address(); + var compatibility_1 = require_compatibility(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var smartContractTransactionsFactory_1 = require_smartContractTransactionsFactory(); + var transactionsFactoryConfig_1 = require_transactionsFactoryConfig(); + var utils_1 = require_utils2(); + var codeMetadata_1 = require_codeMetadata2(); + var function_1 = require_function(); + var interaction_1 = require_interaction(); + var nativeSerializer_1 = require_nativeSerializer(); + var query_1 = require_query(); + var SmartContract = class { + /** + * Create a SmartContract object by providing its address on the Network. + */ + constructor(options = {}) { + this.address = address_1.Address.empty(); + this.methodsExplicit = {}; + this.methods = {}; + this.address = options.address || address_1.Address.empty(); + this.abi = options.abi; + if (this.abi) { + this.setupMethods(); + } + } + setupMethods() { + let contract = this; + let abi = this.getAbi(); + for (const definition of abi.getEndpoints()) { + let functionName = definition.name; + this.methodsExplicit[functionName] = function(args) { + let func = new function_1.ContractFunction(functionName); + let interaction = new interaction_1.Interaction(contract, func, args || []); + return interaction; + }; + this.methods[functionName] = function(args) { + let func = new function_1.ContractFunction(functionName); + let typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args || [], definition); + let interaction = new interaction_1.Interaction(contract, func, typedArgs || []); + return interaction; + }; + } + } + /** + * Sets the address, as on Network. + */ + setAddress(address) { + this.address = address; + } + /** + * Gets the address, as on Network. + */ + getAddress() { + return this.address; + } + getAbi() { + utils_1.guardValueIsSet("abi", this.abi); + return this.abi; + } + getEndpoint(name2) { + return this.getAbi().getEndpoint(name2); + } + /** + * Creates a {@link Transaction} for deploying the Smart Contract to the Network. + */ + deploy({ deployer, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(deployer, "'deployer' of SmartContract.deploy()", "pass the actual address to deploy()"); + const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); + const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ + config, + abi: this.abi + }); + const bytecode = import_buffer.Buffer.from(code2.toString(), "hex"); + const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); + const transaction = factory.createTransactionForDeploy({ + sender: deployer, + bytecode, + gasLimit: BigInt(gasLimit.valueOf()), + arguments: initArguments, + isUpgradeable: metadataAsJson.upgradeable, + isReadable: metadataAsJson.readable, + isPayable: metadataAsJson.payable, + isPayableBySmartContract: metadataAsJson.payableBySc + }); + transaction.setChainID(chainID); + transaction.setValue(value ?? 0); + transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); + return transaction; + } + getMetadataPropertiesAsObject(codeMetadata) { + let metadata; + if (codeMetadata) { + metadata = codeMetadata_1.CodeMetadata.fromBytes(import_buffer.Buffer.from(codeMetadata.toString(), "hex")); + } else { + metadata = new codeMetadata_1.CodeMetadata(); + } + const metadataAsJson = metadata.toJSON(); + return metadataAsJson; + } + /** + * Creates a {@link Transaction} for upgrading the Smart Contract on the Network. + */ + upgrade({ caller, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.upgrade()", "pass the actual address to upgrade()"); + this.ensureHasAddress(); + const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); + const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ + config, + abi: this.abi + }); + const bytecode = Uint8Array.from(import_buffer.Buffer.from(code2.toString(), "hex")); + const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); + const transaction = factory.createTransactionForUpgrade({ + sender: caller, + contract: this.getAddress(), + bytecode, + gasLimit: BigInt(gasLimit.valueOf()), + arguments: initArguments, + isUpgradeable: metadataAsJson.upgradeable, + isReadable: metadataAsJson.readable, + isPayable: metadataAsJson.payable, + isPayableBySmartContract: metadataAsJson.payableBySc + }); + transaction.setChainID(chainID); + transaction.setValue(value ?? 0); + transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); + return transaction; + } + /** + * Creates a {@link Transaction} for calling (a function of) the Smart Contract. + */ + call({ func, args, value, gasLimit, receiver, gasPrice, chainID, caller }) { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.call()", "pass the actual address to call()"); + this.ensureHasAddress(); + const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); + const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ + config, + abi: this.abi + }); + args = args || []; + value = value || 0; + const transaction = factory.createTransactionForExecute({ + sender: caller, + contract: receiver ? receiver : this.getAddress(), + function: func.toString(), + gasLimit: BigInt(gasLimit.valueOf()), + arguments: args + }); + transaction.setChainID(chainID); + transaction.setValue(value); + transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); + return transaction; + } + createQuery({ func, args, value, caller }) { + this.ensureHasAddress(); + return new query_1.Query({ + address: this.getAddress(), + func, + args, + value, + caller + }); + } + ensureHasAddress() { + if (!this.getAddress().bech32()) { + throw new errors_1.ErrContractHasNoAddress(); + } + } + /** + * Computes the address of a Smart Contract. + * The address is computed deterministically, from the address of the owner and the nonce of the deployment transaction. + * + * @param owner The owner of the Smart Contract + * @param nonce The owner nonce used for the deployment transaction + */ + static computeAddress(owner, nonce) { + const deployer = address_1.Address.fromBech32(owner.bech32()); + const addressComputer = new address_1.AddressComputer(); + return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); + } + }; + exports2.SmartContract = SmartContract; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js +var require_transactionPayloadBuilders = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractCallPayloadBuilder = exports2.ContractUpgradePayloadBuilder = exports2.ContractDeployPayloadBuilder = void 0; + var constants_1 = require_constants(); + var transactionPayload_1 = require_transactionPayload(); + var utils_1 = require_utils2(); + var argSerializer_1 = require_argSerializer(); + var ContractDeployPayloadBuilder = class { + constructor() { + this.code = null; + this.codeMetadata = ""; + this.arguments = []; + } + /** + * Sets the code of the Smart Contract. + */ + setCode(code2) { + this.code = code2; + return this; + } + /** + * Sets the code metadata of the Smart Contract. + */ + setCodeMetadata(codeMetadata) { + this.codeMetadata = codeMetadata; + return this; + } + /** + * Adds constructor (`init`) arguments. + */ + addInitArg(arg) { + this.arguments.push(arg); + return this; + } + /** + * Sets constructor (`init`) arguments. + */ + setInitArgs(args) { + this.arguments = args; + return this; + } + /** + * Builds the {@link TransactionPayload}. + */ + build() { + utils_1.guardValueIsSet("code", this.code); + let code2 = this.code.toString(); + let codeMetadata = this.codeMetadata.toString(); + let data = `${code2}@${constants_1.WasmVirtualMachine}@${codeMetadata}`; + data = appendArgumentsToString(data, this.arguments); + return new transactionPayload_1.TransactionPayload(data); + } + }; + exports2.ContractDeployPayloadBuilder = ContractDeployPayloadBuilder; + var ContractUpgradePayloadBuilder = class { + constructor() { + this.code = null; + this.codeMetadata = ""; + this.arguments = []; + } + /** + * Sets the code of the Smart Contract. + */ + setCode(code2) { + this.code = code2; + return this; + } + /** + * Sets the code metadata of the Smart Contract. + */ + setCodeMetadata(codeMetadata) { + this.codeMetadata = codeMetadata; + return this; + } + /** + * Adds upgrade (`init`) arguments. + */ + addInitArg(arg) { + this.arguments.push(arg); + return this; + } + /** + * Sets upgrade (`init`) arguments. + */ + setInitArgs(args) { + this.arguments = args; + return this; + } + /** + * Builds the {@link TransactionPayload}. + */ + build() { + utils_1.guardValueIsSet("code", this.code); + let code2 = this.code.toString(); + let codeMetadata = this.codeMetadata.toString(); + let data = `upgradeContract@${code2}@${codeMetadata}`; + data = appendArgumentsToString(data, this.arguments); + return new transactionPayload_1.TransactionPayload(data); + } + }; + exports2.ContractUpgradePayloadBuilder = ContractUpgradePayloadBuilder; + var ContractCallPayloadBuilder = class { + constructor() { + this.contractFunction = null; + this.arguments = []; + } + /** + * Sets the function to be called (executed). + */ + setFunction(contractFunction) { + this.contractFunction = contractFunction; + return this; + } + /** + * Adds a function argument. + */ + addArg(arg) { + this.arguments.push(arg); + return this; + } + /** + * Sets the function arguments. + */ + setArgs(args) { + this.arguments = args; + return this; + } + /** + * Builds the {@link TransactionPayload}. + */ + build() { + utils_1.guardValueIsSet("calledFunction", this.contractFunction); + let data = this.contractFunction.toString(); + data = appendArgumentsToString(data, this.arguments); + return new transactionPayload_1.TransactionPayload(data); + } + }; + exports2.ContractCallPayloadBuilder = ContractCallPayloadBuilder; + function appendArgumentsToString(to, values) { + let { argumentsString, count } = new argSerializer_1.ArgSerializer().valuesToString(values); + if (count == 0) { + return to; + } + return `${to}@${argumentsString}`; + } + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/index.js +var require_smartcontracts = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_argSerializer(), exports2); + __exportStar2(require_code(), exports2); + __exportStar2(require_codec2(), exports2); + __exportStar2(require_codeMetadata2(), exports2); + __exportStar2(require_function(), exports2); + __exportStar2(require_interaction(), exports2); + __exportStar2(require_interactionChecker(), exports2); + __exportStar2(require_interface(), exports2); + __exportStar2(require_nativeSerializer(), exports2); + __exportStar2(require_query(), exports2); + __exportStar2(require_resultsParser(), exports2); + __exportStar2(require_returnCode(), exports2); + __exportStar2(require_smartContract(), exports2); + __exportStar2(require_transactionPayloadBuilders(), exports2); + __exportStar2(require_typesystem(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js +var require_resources = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.gatherAllEvents = exports2.findEventsByFirstTopic = exports2.findEventsByIdentifier = exports2.findEventsByPredicate = exports2.SmartContractCallOutcome = exports2.TransactionOutcome = exports2.SmartContractResult = exports2.TransactionLogs = exports2.TransactionEvent = void 0; + var TransactionEvent = class { + constructor(init) { + this.address = ""; + this.identifier = ""; + this.topics = []; + this.dataItems = []; + Object.assign(this, init); + } + }; + exports2.TransactionEvent = TransactionEvent; + var TransactionLogs2 = class { + constructor(init) { + this.address = ""; + this.events = []; + Object.assign(this, init); + } + }; + exports2.TransactionLogs = TransactionLogs2; + var SmartContractResult = class { + constructor(init) { + this.sender = ""; + this.receiver = ""; + this.data = new Uint8Array(); + this.logs = new TransactionLogs2({}); + Object.assign(this, init); + } + }; + exports2.SmartContractResult = SmartContractResult; + var TransactionOutcome = class { + constructor(init) { + this.directSmartContractCallOutcome = new SmartContractCallOutcome({}); + this.smartContractResults = []; + this.logs = new TransactionLogs2({}); + Object.assign(this, init); + } + }; + exports2.TransactionOutcome = TransactionOutcome; + var SmartContractCallOutcome = class { + constructor(init) { + this.function = ""; + this.returnDataParts = []; + this.returnMessage = ""; + this.returnCode = ""; + Object.assign(this, init); + } + }; + exports2.SmartContractCallOutcome = SmartContractCallOutcome; + function findEventsByPredicate(transactionOutcome, predicate) { + return gatherAllEvents(transactionOutcome).filter(predicate); + } + exports2.findEventsByPredicate = findEventsByPredicate; + function findEventsByIdentifier(transactionOutcome, identifier) { + return findEventsByPredicate(transactionOutcome, (event) => event.identifier == identifier); + } + exports2.findEventsByIdentifier = findEventsByIdentifier; + function findEventsByFirstTopic(transactionOutcome, topic) { + return findEventsByPredicate(transactionOutcome, (event) => event.topics[0]?.toString() == topic); + } + exports2.findEventsByFirstTopic = findEventsByFirstTopic; + function gatherAllEvents(transactionOutcome) { + const allEvents = []; + allEvents.push(...transactionOutcome.logs.events); + for (const item of transactionOutcome.smartContractResults) { + allEvents.push(...item.logs.events); + } + return allEvents; + } + exports2.gatherAllEvents = gatherAllEvents; + } +}); + +// node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js +var require_transactionsConverter = __commonJS({ + "node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionsConverter = void 0; + var smartcontracts_1 = require_smartcontracts(); + var transaction_1 = require_transaction(); + var resources_1 = require_resources(); + var TransactionsConverter = class { + transactionToPlainObject(transaction) { + const plainObject = { + nonce: Number(transaction.nonce), + value: transaction.value.toString(), + receiver: transaction.receiver, + sender: transaction.sender, + senderUsername: this.toBase64OrUndefined(transaction.senderUsername), + receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), + gasPrice: Number(transaction.gasPrice), + gasLimit: Number(transaction.gasLimit), + data: this.toBase64OrUndefined(transaction.data), + chainID: transaction.chainID.valueOf(), + version: transaction.version, + options: transaction.options == 0 ? void 0 : transaction.options, + guardian: transaction.guardian ? transaction.guardian : void 0, + signature: this.toHexOrUndefined(transaction.signature), + guardianSignature: this.toHexOrUndefined(transaction.guardianSignature) + }; + return plainObject; + } + toBase64OrUndefined(value) { + return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; + } + toHexOrUndefined(value) { + return value && value.length ? import_buffer.Buffer.from(value).toString("hex") : void 0; + } + plainObjectToTransaction(object) { + const transaction = new transaction_1.Transaction({ + nonce: BigInt(object.nonce), + value: BigInt(object.value || ""), + receiver: object.receiver, + receiverUsername: this.bufferFromBase64(object.receiverUsername).toString(), + sender: object.sender, + senderUsername: this.bufferFromBase64(object.senderUsername).toString(), + guardian: object.guardian, + gasPrice: BigInt(object.gasPrice), + gasLimit: BigInt(object.gasLimit), + data: this.bufferFromBase64(object.data), + chainID: String(object.chainID), + version: Number(object.version), + options: Number(object.options), + signature: this.bufferFromHex(object.signature), + guardianSignature: this.bufferFromHex(object.guardianSignature) + }); + return transaction; + } + bufferFromBase64(value) { + return import_buffer.Buffer.from(value || "", "base64"); + } + bufferFromHex(value) { + return import_buffer.Buffer.from(value || "", "hex"); + } + transactionOnNetworkToOutcome(transactionOnNetwork) { + const legacyResultsParser = new smartcontracts_1.ResultsParser(); + const callOutcomeBundle = legacyResultsParser.parseUntypedOutcome(transactionOnNetwork); + const callOutcome = new resources_1.SmartContractCallOutcome({ + function: transactionOnNetwork.function, + returnCode: callOutcomeBundle.returnCode.toString(), + returnMessage: callOutcomeBundle.returnMessage, + returnDataParts: callOutcomeBundle.values + }); + const contractResults = transactionOnNetwork.contractResults.items.map((result) => this.smartContractResultOnNetworkToSmartContractResult(result)); + const logs = new resources_1.TransactionLogs({ + address: transactionOnNetwork.logs.address.bech32(), + events: transactionOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) + }); + return new resources_1.TransactionOutcome({ + logs, + smartContractResults: contractResults, + directSmartContractCallOutcome: callOutcome + }); + } + smartContractResultOnNetworkToSmartContractResult(resultOnNetwork) { + return new resources_1.SmartContractResult({ + sender: resultOnNetwork.sender.bech32(), + receiver: resultOnNetwork.receiver.bech32(), + data: import_buffer.Buffer.from(resultOnNetwork.data), + logs: new resources_1.TransactionLogs({ + address: resultOnNetwork.logs.address.bech32(), + events: resultOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) + }) + }); + } + eventOnNetworkToEvent(eventOnNetwork) { + const legacyData = eventOnNetwork.dataPayload?.valueOf() || import_buffer.Buffer.from(eventOnNetwork.data || ""); + const dataItems = eventOnNetwork.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; + if (dataItems.length === 0) { + if (legacyData.length) { + dataItems.push(import_buffer.Buffer.from(legacyData)); + } + } + return new resources_1.TransactionEvent({ + address: eventOnNetwork.address.bech32(), + identifier: eventOnNetwork.identifier, + topics: eventOnNetwork.topics.map((topic) => import_buffer.Buffer.from(topic.hex(), "hex")), + dataItems + }); + } + }; + exports2.TransactionsConverter = TransactionsConverter; + } +}); + +// node_modules/@multiversx/sdk-core/out/hash.js +var require_hash = __commonJS({ + "node_modules/@multiversx/sdk-core/out/hash.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Hash = void 0; + var errors = __importStar2(require_errors()); + var Hash = class _Hash { + /** + * Creates a new Hash object. + * + * @param hash The hash, as a Buffer or a hex-encoded string. + */ + constructor(hash) { + if (!hash) { + this.hash = import_buffer.Buffer.from([]); + } else if (hash instanceof import_buffer.Buffer) { + this.hash = hash; + } else if (typeof hash === "string") { + this.hash = import_buffer.Buffer.from(hash, "hex"); + } else { + throw new errors.ErrBadType("hash", "buffer | string", hash); + } + } + static empty() { + return new _Hash(import_buffer.Buffer.from([])); + } + /** + * Returns whether the hash is empty (not computed). + */ + isEmpty() { + return this.hash.length == 0; + } + toString() { + return this.hex(); + } + hex() { + return this.hash.toString("hex"); + } + valueOf() { + return this.hash; + } + }; + exports2.Hash = Hash; + } +}); + +// node_modules/@multiversx/sdk-core/out/signature.js +var require_signature = __commonJS({ + "node_modules/@multiversx/sdk-core/out/signature.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.interpretSignatureAsBuffer = exports2.Signature = void 0; + var errors = __importStar2(require_errors()); + var SIGNATURE_LENGTH = 64; + var Signature = class _Signature { + constructor(value) { + this.valueHex = ""; + if (!value) { + return; + } + if (typeof value === "string") { + return _Signature.fromHex(value); + } + if (value instanceof import_buffer.Buffer) { + return _Signature.fromBuffer(value); + } + } + static empty() { + return new _Signature(); + } + static fromHex(value) { + if (value.startsWith("0x")) { + value = value.slice(2); + } + if (!_Signature.isValidHex(value)) { + throw new errors.ErrSignatureCannotCreate(value); + } + return _Signature.fromValidHex(value); + } + static isValidHex(value) { + return import_buffer.Buffer.from(value, "hex").length == SIGNATURE_LENGTH; + } + static fromValidHex(value) { + let result = new _Signature(); + result.valueHex = value; + return result; + } + static fromBuffer(buffer) { + if (buffer.length != SIGNATURE_LENGTH) { + throw new errors.ErrSignatureCannotCreate(buffer); + } + return _Signature.fromValidHex(buffer.toString("hex")); + } + hex() { + return this.valueHex; + } + }; + exports2.Signature = Signature; + function interpretSignatureAsBuffer(signature) { + if (ArrayBuffer.isView(signature)) { + return import_buffer.Buffer.from(signature); + } else if (signature.hex != null) { + return import_buffer.Buffer.from(signature.hex(), "hex"); + } + throw new Error(`Object cannot be interpreted as a signature: ${signature}`); + } + exports2.interpretSignatureAsBuffer = interpretSignatureAsBuffer; + } +}); + +// node_modules/@protobufjs/aspromise/index.js +var require_aspromise = __commonJS({ + "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = asPromise; + function asPromise(fn, ctx) { + var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params2 = new Array(arguments.length - 1), offset2 = 0; + while (offset2 < params2.length) + params2[offset2++] = arguments[offset2]; + resolve.apply(null, params2); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); + } + } +}); + +// node_modules/@protobufjs/base64/index.js +var require_base64 = __commonJS({ + "node_modules/@protobufjs/base64/index.js"(exports2) { + "use strict"; + init_shim(); + var base642 = exports2; + base642.length = function length2(string2) { + var p3 = string2.length; + if (!p3) + return 0; + var n3 = 0; + while (--p3 % 4 > 1 && string2.charAt(p3) === "=") + ++n3; + return Math.ceil(string2.length * 3) / 4 - n3; + }; + var b64 = new Array(64); + var s64 = new Array(123); + for (i2 = 0; i2 < 64; ) + s64[b64[i2] = i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 - 59 | 43] = i2++; + var i2; + base642.encode = function encode5(buffer, start, end) { + var parts = null, chunk = []; + var i3 = 0, j2 = 0, t; + while (start < end) { + var b4 = buffer[start++]; + switch (j2) { + case 0: + chunk[i3++] = b64[b4 >> 2]; + t = (b4 & 3) << 4; + j2 = 1; + break; + case 1: + chunk[i3++] = b64[t | b4 >> 4]; + t = (b4 & 15) << 2; + j2 = 2; + break; + case 2: + chunk[i3++] = b64[t | b4 >> 6]; + chunk[i3++] = b64[b4 & 63]; + j2 = 0; + break; + } + if (i3 > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i3 = 0; + } + } + if (j2) { + chunk[i3++] = b64[t]; + chunk[i3++] = 61; + if (j2 === 1) + chunk[i3++] = 61; + } + if (parts) { + if (i3) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i3))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i3)); + }; + var invalidEncoding = "invalid encoding"; + base642.decode = function decode6(string2, buffer, offset) { + var start = offset; + var j2 = 0, t; + for (var i3 = 0; i3 < string2.length; ) { + var c4 = string2.charCodeAt(i3++); + if (c4 === 61 && j2 > 1) + break; + if ((c4 = s64[c4]) === void 0) + throw Error(invalidEncoding); + switch (j2) { + case 0: + t = c4; + j2 = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c4 & 48) >> 4; + t = c4; + j2 = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c4 & 60) >> 2; + t = c4; + j2 = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c4; + j2 = 0; + break; + } + } + if (j2 === 1) + throw Error(invalidEncoding); + return offset - start; + }; + base642.test = function test(string2) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string2); + }; + } +}); + +// node_modules/@protobufjs/eventemitter/index.js +var require_eventemitter = __commonJS({ + "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = EventEmitter2; + function EventEmitter2() { + this._listeners = {}; + } + EventEmitter2.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn, + ctx: ctx || this + }); + return this; + }; + EventEmitter2.prototype.off = function off(evt, fn) { + if (evt === void 0) + this._listeners = {}; + else { + if (fn === void 0) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i2 = 0; i2 < listeners.length; ) + if (listeners[i2].fn === fn) + listeners.splice(i2, 1); + else + ++i2; + } + } + return this; + }; + EventEmitter2.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], i2 = 1; + for (; i2 < arguments.length; ) + args.push(arguments[i2++]); + for (i2 = 0; i2 < listeners.length; ) + listeners[i2].fn.apply(listeners[i2++].ctx, args); + } + return this; + }; + } +}); + +// node_modules/@protobufjs/float/index.js +var require_float = __commonJS({ + "node_modules/@protobufjs/float/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = factory(factory); + function factory(exports3) { + if (typeof Float32Array !== "undefined") + (function() { + var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + })(); + else + (function() { + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign2 = val < 0 ? 1 : 0; + if (sign2) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? ( + /* positive */ + 0 + ) : ( + /* negative 0 */ + 2147483648 + ), buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 34028234663852886e22) + writeUint((sign2 << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 11754943508222875e-54) + writeUint((sign2 << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign2 << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), sign2 = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; + return exponent === 255 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 1401298464324817e-60 * mantissa : sign2 * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + })(); + if (typeof Float64Array !== "undefined") + (function() { + var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + })(); + else + (function() { + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign2 = val < 0 ? 1 : 0; + if (sign2) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? ( + /* positive */ + 0 + ) : ( + /* negative 0 */ + 2147483648 + ), buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 17976931348623157e292) { + writeUint(0, buf, pos + off0); + writeUint((sign2 << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 22250738585072014e-324) { + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign2 << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign2 << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); + var sign2 = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 5e-324 * mantissa : sign2 * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + })(); + return exports3; + } + function writeUintLE(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + function writeUintBE(val, buf, pos) { + buf[pos] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; + } + function readUintLE(buf, pos) { + return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; + } + function readUintBE(buf, pos) { + return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; + } + } +}); + +// node_modules/@protobufjs/inquire/index.js +var require_inquire = __commonJS({ + "node_modules/@protobufjs/inquire/index.js"(exports, module) { + "use strict"; + init_shim(); + module.exports = inquire; + function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/, "re"))(moduleName); + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e2) { + } + return null; + } + } +}); + +// node_modules/@protobufjs/utf8/index.js +var require_utf8 = __commonJS({ + "node_modules/@protobufjs/utf8/index.js"(exports2) { + "use strict"; + init_shim(); + var utf8 = exports2; + utf8.length = function utf8_length(string2) { + var len = 0, c4 = 0; + for (var i2 = 0; i2 < string2.length; ++i2) { + c4 = string2.charCodeAt(i2); + if (c4 < 128) + len += 1; + else if (c4 < 2048) + len += 2; + else if ((c4 & 64512) === 55296 && (string2.charCodeAt(i2 + 1) & 64512) === 56320) { + ++i2; + len += 4; + } else + len += 3; + } + return len; + }; + utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, chunk = [], i2 = 0, t; + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i2++] = t; + else if (t > 191 && t < 224) + chunk[i2++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536; + chunk[i2++] = 55296 + (t >> 10); + chunk[i2++] = 56320 + (t & 1023); + } else + chunk[i2++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i2 > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i2 = 0; + } + } + if (parts) { + if (i2) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i2)); + }; + utf8.write = function utf8_write(string2, buffer, offset) { + var start = offset, c1, c22; + for (var i2 = 0; i2 < string2.length; ++i2) { + c1 = string2.charCodeAt(i2); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 64512) === 55296 && ((c22 = string2.charCodeAt(i2 + 1)) & 64512) === 56320) { + c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023); + ++i2; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; + }; + } +}); + +// node_modules/@protobufjs/pool/index.js +var require_pool = __commonJS({ + "node_modules/@protobufjs/pool/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = pool; + function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX2 = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size2) { + if (size2 < 1 || size2 > MAX2) + return alloc(size2); + if (offset + size2 > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size2); + if (offset & 7) + offset = (offset | 7) + 1; + return buf; + }; + } + } +}); + +// node_modules/protobufjs/src/util/longbits.js +var require_longbits = __commonJS({ + "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = LongBits; + var util = require_minimal(); + function LongBits(lo, hi) { + this.lo = lo >>> 0; + this.hi = hi >>> 0; + } + var zero = LongBits.zero = new LongBits(0, 0); + zero.toNumber = function() { + return 0; + }; + zero.zzEncode = zero.zzDecode = function() { + return this; + }; + zero.length = function() { + return 1; + }; + var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign2 = value < 0; + if (sign2) + value = -value; + var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; + if (sign2) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); + }; + LongBits.from = function from3(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; + }; + LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; + }; + LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; + }; + var charCodeAt = String.prototype.charCodeAt; + LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, + (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 + ); + }; + LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24, + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); + }; + LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = (this.lo << 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = (this.hi >>> 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.length = function length2() { + var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; + return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; + }; + } +}); + +// node_modules/protobufjs/src/util/minimal.js +var require_minimal = __commonJS({ + "node_modules/protobufjs/src/util/minimal.js"(exports2) { + "use strict"; + init_shim(); + var util = exports2; + util.asPromise = require_aspromise(); + util.base64 = require_base64(); + util.EventEmitter = require_eventemitter(); + util.float = require_float(); + util.inquire = require_inquire(); + util.utf8 = require_utf8(); + util.pool = require_pool(); + util.LongBits = require_longbits(); + util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); + util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; + util.emptyArray = Object.freeze ? Object.freeze([]) : ( + /* istanbul ignore next */ + [] + ); + util.emptyObject = Object.freeze ? Object.freeze({}) : ( + /* istanbul ignore next */ + {} + ); + util.isInteger = Number.isInteger || /* istanbul ignore next */ + function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; + }; + util.isString = function isString2(value) { + return typeof value === "string" || value instanceof String; + }; + util.isObject = function isObject(value) { + return value && typeof value === "object"; + }; + util.isset = /** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ + util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; + }; + util.Buffer = function() { + try { + var Buffer2 = util.inquire("buffer").Buffer; + return Buffer2.prototype.utf8Write ? Buffer2 : ( + /* istanbul ignore next */ + null + ); + } catch (e2) { + return null; + } + }(); + util._Buffer_from = null; + util._Buffer_allocUnsafe = null; + util.newBuffer = function newBuffer(sizeOrArray) { + return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); + }; + util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + util.Long = /* istanbul ignore next */ + util.global.dcodeIO && /* istanbul ignore next */ + util.global.dcodeIO.Long || /* istanbul ignore next */ + util.global.Long || util.inquire("long"); + util.key2Re = /^true|false|0|1$/; + util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + util.longToHash = function longToHash(value) { + return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; + }; + util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); + }; + function merge(dst, src2, ifNotSet) { + for (var keys2 = Object.keys(src2), i2 = 0; i2 < keys2.length; ++i2) + if (dst[keys2[i2]] === void 0 || !ifNotSet) + dst[keys2[i2]] = src2[keys2[i2]]; + return dst; + } + util.merge = merge; + util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); + }; + function newError(name2) { + function CustomError(message, properties) { + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + Object.defineProperty(this, "message", { get: function() { + return message; + } }); + if (Error.captureStackTrace) + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + if (properties) + merge(this, properties); + } + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true + }, + name: { + get: function get2() { + return name2; + }, + set: void 0, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true + }, + toString: { + value: function value() { + return this.name + ": " + this.message; + }, + writable: true, + enumerable: false, + configurable: true + } + }); + return CustomError; + } + util.newError = newError; + util.ProtocolError = newError("ProtocolError"); + util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i2 = 0; i2 < fieldNames.length; ++i2) + fieldMap[fieldNames[i2]] = 1; + return function() { + for (var keys2 = Object.keys(this), i3 = keys2.length - 1; i3 > -1; --i3) + if (fieldMap[keys2[i3]] === 1 && this[keys2[i3]] !== void 0 && this[keys2[i3]] !== null) + return keys2[i3]; + }; + }; + util.oneOfSetter = function setOneOf(fieldNames) { + return function(name2) { + for (var i2 = 0; i2 < fieldNames.length; ++i2) + if (fieldNames[i2] !== name2) + delete this[fieldNames[i2]]; + }; + }; + util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true + }; + util._configure = function() { + var Buffer2 = util.Buffer; + if (!Buffer2) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer2(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer2(size); + }; + }; + } +}); + +// node_modules/protobufjs/src/writer.js +var require_writer = __commonJS({ + "node_modules/protobufjs/src/writer.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Writer; + var util = require_minimal(); + var BufferWriter; + var LongBits = util.LongBits; + var base642 = util.base64; + var utf8 = util.utf8; + function Op(fn, len, val) { + this.fn = fn; + this.len = len; + this.next = void 0; + this.val = val; + } + function noop() { + } + function State(writer) { + this.head = writer.head; + this.tail = writer.tail; + this.len = writer.len; + this.next = writer.states; + } + function Writer() { + this.len = 0; + this.head = new Op(noop, 0, 0); + this.tail = this.head; + this.states = null; + } + var create2 = function create3() { + return util.Buffer ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } : function create_array() { + return new Writer(); + }; + }; + Writer.create = create2(); + Writer.alloc = function alloc(size) { + return new util.Array(size); + }; + if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; + }; + function writeByte(val, buf, pos) { + buf[pos] = val & 255; + } + function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; + } + function VarintOp(len, val) { + this.len = len; + this.next = void 0; + this.val = val; + } + VarintOp.prototype = Object.create(Op.prototype); + VarintOp.prototype.fn = writeVarint32; + Writer.prototype.uint32 = function write_uint32(value) { + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, + value + )).len; + return this; + }; + Writer.prototype.int32 = function write_int32(value) { + return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); + }; + Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); + }; + function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; + } + Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.int64 = Writer.prototype.uint64; + Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); + }; + function writeFixed32(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); + }; + Writer.prototype.sfixed32 = Writer.prototype.fixed32; + Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); + }; + Writer.prototype.sfixed64 = Writer.prototype.fixed64; + Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); + }; + Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); + }; + var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytes_for(val, buf, pos) { + for (var i2 = 0; i2 < val.length; ++i2) + buf[pos + i2] = val[i2]; + }; + Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base642.length(value)); + base642.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); + }; + Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); + }; + Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; + }; + Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; + }; + Writer.prototype.ldelim = function ldelim() { + var head = this.head, tail = this.tail, len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; + this.tail = tail; + this.len += len; + } + return this; + }; + Writer.prototype.finish = function finish() { + var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + return buf; + }; + Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create2(); + BufferWriter._configure(); + }; + } +}); + +// node_modules/protobufjs/src/writer_buffer.js +var require_writer_buffer = __commonJS({ + "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = BufferWriter; + var Writer = require_writer(); + (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + var util = require_minimal(); + function BufferWriter() { + Writer.call(this); + } + BufferWriter._configure = function() { + BufferWriter.alloc = util._Buffer_allocUnsafe; + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) + val.copy(buf, pos, 0, val.length); + else + for (var i2 = 0; i2 < val.length; ) + buf[pos++] = val[i2++]; + }; + }; + BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; + }; + function writeStringBuffer(val, buf, pos) { + if (val.length < 40) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); + } + BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; + }; + BufferWriter._configure(); + } +}); + +// node_modules/protobufjs/src/reader.js +var require_reader = __commonJS({ + "node_modules/protobufjs/src/reader.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Reader; + var util = require_minimal(); + var BufferReader; + var LongBits = util.LongBits; + var utf8 = util.utf8; + function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); + } + function Reader(buffer) { + this.buf = buffer; + this.pos = 0; + this.len = buffer.length; + } + var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } : function create_array2(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + var create2 = function create3() { + return util.Buffer ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer2) { + return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); + })(buffer); + } : create_array; + }; + Reader.create = create2(); + Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ + util.Array.prototype.slice; + Reader.prototype.uint32 = /* @__PURE__ */ function read_uint32_setup() { + var value = 4294967295; + return function read_uint32() { + value = (this.buf[this.pos] & 127) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; + }(); + Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; + }; + Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; + }; + function readLongVarint() { + var bits = new LongBits(0, 0); + var i2 = 0; + if (this.len - this.pos > 4) { + for (; i2 < 4; ++i2) { + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i2 = 0; + } else { + for (; i2 < 3; ++i2) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i2 * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { + for (; i2 < 5; ++i2) { + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i2 < 5; ++i2) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + throw Error("invalid varint encoding"); + } + Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; + }; + function readFixed32_end(buf, end) { + return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; + } + Reader.prototype.fixed32 = function read_fixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4); + }; + Reader.prototype.sfixed32 = function read_sfixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4) | 0; + }; + function readFixed64() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); + } + Reader.prototype.float = function read_float() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; + }; + Reader.prototype.double = function read_double() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; + }; + Reader.prototype.bytes = function read_bytes() { + var length2 = this.uint32(), start = this.pos, end = this.pos + length2; + if (end > this.len) + throw indexOutOfRange(this, length2); + this.pos += length2; + if (Array.isArray(this.buf)) + return this.buf.slice(start, end); + if (start === end) { + var nativeBuffer = util.Buffer; + return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); + }; + Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); + }; + Reader.prototype.skip = function skip(length2) { + if (typeof length2 === "number") { + if (this.pos + length2 > this.len) + throw indexOutOfRange(this, length2); + this.pos += length2; + } else { + do { + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; + }; + Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; + }; + Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create2(); + BufferReader._configure(); + var fn = util.Long ? "toLong" : ( + /* istanbul ignore next */ + "toNumber" + ); + util.merge(Reader.prototype, { + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + }); + }; + } +}); + +// node_modules/protobufjs/src/reader_buffer.js +var require_reader_buffer = __commonJS({ + "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = BufferReader; + var Reader = require_reader(); + (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + var util = require_minimal(); + function BufferReader(buffer) { + Reader.call(this, buffer); + } + BufferReader._configure = function() { + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; + }; + BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); + return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); + }; + BufferReader._configure(); + } +}); + +// node_modules/protobufjs/src/rpc/service.js +var require_service = __commonJS({ + "node_modules/protobufjs/src/rpc/service.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Service; + var util = require_minimal(); + (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + function Service(rpcImpl, requestDelimited, responseDelimited) { + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + util.EventEmitter.call(this); + this.rpcImpl = rpcImpl; + this.requestDelimited = Boolean(requestDelimited); + this.responseDelimited = Boolean(responseDelimited); + } + Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + if (!request) + throw TypeError("request must be specified"); + var self2 = this; + if (!callback) + return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request); + if (!self2.rpcImpl) { + setTimeout(function() { + callback(Error("already ended")); + }, 0); + return void 0; + } + try { + return self2.rpcImpl( + method, + requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + if (err) { + self2.emit("error", err, method); + return callback(err); + } + if (response === null) { + self2.end( + /* endedByRPC */ + true + ); + return void 0; + } + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err2) { + self2.emit("error", err2, method); + return callback(err2); + } + } + self2.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self2.emit("error", err, method); + setTimeout(function() { + callback(err); + }, 0); + return void 0; + } + }; + Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; + }; + } +}); + +// node_modules/protobufjs/src/rpc.js +var require_rpc = __commonJS({ + "node_modules/protobufjs/src/rpc.js"(exports2) { + "use strict"; + init_shim(); + var rpc = exports2; + rpc.Service = require_service(); + } +}); + +// node_modules/protobufjs/src/roots.js +var require_roots = __commonJS({ + "node_modules/protobufjs/src/roots.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = {}; + } +}); + +// node_modules/protobufjs/src/index-minimal.js +var require_index_minimal = __commonJS({ + "node_modules/protobufjs/src/index-minimal.js"(exports2) { + "use strict"; + init_shim(); + var protobuf = exports2; + protobuf.build = "minimal"; + protobuf.Writer = require_writer(); + protobuf.BufferWriter = require_writer_buffer(); + protobuf.Reader = require_reader(); + protobuf.BufferReader = require_reader_buffer(); + protobuf.util = require_minimal(); + protobuf.rpc = require_rpc(); + protobuf.roots = require_roots(); + protobuf.configure = configure; + function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); + } + configure(); + } +}); + +// node_modules/protobufjs/minimal.js +var require_minimal2 = __commonJS({ + "node_modules/protobufjs/minimal.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = require_index_minimal(); + } +}); + +// node_modules/@multiversx/sdk-core/out/proto/compiled.js +var require_compiled = __commonJS({ + "node_modules/@multiversx/sdk-core/out/proto/compiled.js"(exports2, module2) { + "use strict"; + init_shim(); + (function(global2, factory) { + if (typeof define === "function" && define.amd) + define(["protobufjs/minimal"], factory); + else if (typeof __require === "function" && typeof module2 === "object" && module2 && module2.exports) + module2.exports = factory(require_minimal2()); + })(exports2, function($protobuf) { + "use strict"; + var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; + var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); + $root.proto = function() { + var proto = {}; + proto.Transaction = function() { + function Transaction4(properties) { + if (properties) { + for (var keys2 = Object.keys(properties), i2 = 0; i2 < keys2.length; ++i2) + if (properties[keys2[i2]] != null) + this[keys2[i2]] = properties[keys2[i2]]; + } + } + Transaction4.prototype.Nonce = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; + Transaction4.prototype.Value = $util.newBuffer([]); + Transaction4.prototype.RcvAddr = $util.newBuffer([]); + Transaction4.prototype.RcvUserName = $util.newBuffer([]); + Transaction4.prototype.SndAddr = $util.newBuffer([]); + Transaction4.prototype.SndUserName = $util.newBuffer([]); + Transaction4.prototype.GasPrice = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; + Transaction4.prototype.GasLimit = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; + Transaction4.prototype.Data = $util.newBuffer([]); + Transaction4.prototype.ChainID = $util.newBuffer([]); + Transaction4.prototype.Version = 0; + Transaction4.prototype.Signature = $util.newBuffer([]); + Transaction4.prototype.Options = 0; + Transaction4.prototype.GuardianAddr = $util.newBuffer([]); + Transaction4.prototype.GuardianSignature = $util.newBuffer([]); + Transaction4.create = function create2(properties) { + return new Transaction4(properties); + }; + Transaction4.encode = function encode5(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.Nonce != null && Object.hasOwnProperty.call(message, "Nonce")) + writer.uint32( + /* id 1, wireType 0 =*/ + 8 + ).uint64(message.Nonce); + if (message.Value != null && Object.hasOwnProperty.call(message, "Value")) + writer.uint32( + /* id 2, wireType 2 =*/ + 18 + ).bytes(message.Value); + if (message.RcvAddr != null && Object.hasOwnProperty.call(message, "RcvAddr")) + writer.uint32( + /* id 3, wireType 2 =*/ + 26 + ).bytes(message.RcvAddr); + if (message.RcvUserName != null && Object.hasOwnProperty.call(message, "RcvUserName")) + writer.uint32( + /* id 4, wireType 2 =*/ + 34 + ).bytes(message.RcvUserName); + if (message.SndAddr != null && Object.hasOwnProperty.call(message, "SndAddr")) + writer.uint32( + /* id 5, wireType 2 =*/ + 42 + ).bytes(message.SndAddr); + if (message.SndUserName != null && Object.hasOwnProperty.call(message, "SndUserName")) + writer.uint32( + /* id 6, wireType 2 =*/ + 50 + ).bytes(message.SndUserName); + if (message.GasPrice != null && Object.hasOwnProperty.call(message, "GasPrice")) + writer.uint32( + /* id 7, wireType 0 =*/ + 56 + ).uint64(message.GasPrice); + if (message.GasLimit != null && Object.hasOwnProperty.call(message, "GasLimit")) + writer.uint32( + /* id 8, wireType 0 =*/ + 64 + ).uint64(message.GasLimit); + if (message.Data != null && Object.hasOwnProperty.call(message, "Data")) + writer.uint32( + /* id 9, wireType 2 =*/ + 74 + ).bytes(message.Data); + if (message.ChainID != null && Object.hasOwnProperty.call(message, "ChainID")) + writer.uint32( + /* id 10, wireType 2 =*/ + 82 + ).bytes(message.ChainID); + if (message.Version != null && Object.hasOwnProperty.call(message, "Version")) + writer.uint32( + /* id 11, wireType 0 =*/ + 88 + ).uint32(message.Version); + if (message.Signature != null && Object.hasOwnProperty.call(message, "Signature")) + writer.uint32( + /* id 12, wireType 2 =*/ + 98 + ).bytes(message.Signature); + if (message.Options != null && Object.hasOwnProperty.call(message, "Options")) + writer.uint32( + /* id 13, wireType 0 =*/ + 104 + ).uint32(message.Options); + if (message.GuardianAddr != null && Object.hasOwnProperty.call(message, "GuardianAddr")) + writer.uint32( + /* id 14, wireType 2 =*/ + 114 + ).bytes(message.GuardianAddr); + if (message.GuardianSignature != null && Object.hasOwnProperty.call(message, "GuardianSignature")) + writer.uint32( + /* id 15, wireType 2 =*/ + 122 + ).bytes(message.GuardianSignature); + return writer; + }; + Transaction4.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + Transaction4.decode = function decode6(reader, length2) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length2 === void 0 ? reader.len : reader.pos + length2, message = new $root.proto.Transaction(); + while (reader.pos < end) { + var tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + message.Nonce = reader.uint64(); + break; + } + case 2: { + message.Value = reader.bytes(); + break; + } + case 3: { + message.RcvAddr = reader.bytes(); + break; + } + case 4: { + message.RcvUserName = reader.bytes(); + break; + } + case 5: { + message.SndAddr = reader.bytes(); + break; + } + case 6: { + message.SndUserName = reader.bytes(); + break; + } + case 7: { + message.GasPrice = reader.uint64(); + break; + } + case 8: { + message.GasLimit = reader.uint64(); + break; + } + case 9: { + message.Data = reader.bytes(); + break; + } + case 10: { + message.ChainID = reader.bytes(); + break; + } + case 11: { + message.Version = reader.uint32(); + break; + } + case 12: { + message.Signature = reader.bytes(); + break; + } + case 13: { + message.Options = reader.uint32(); + break; + } + case 14: { + message.GuardianAddr = reader.bytes(); + break; + } + case 15: { + message.GuardianSignature = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + Transaction4.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + Transaction4.verify = function verify2(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.Nonce != null && message.hasOwnProperty("Nonce")) { + if (!$util.isInteger(message.Nonce) && !(message.Nonce && $util.isInteger(message.Nonce.low) && $util.isInteger(message.Nonce.high))) + return "Nonce: integer|Long expected"; + } + if (message.Value != null && message.hasOwnProperty("Value")) { + if (!(message.Value && typeof message.Value.length === "number" || $util.isString(message.Value))) + return "Value: buffer expected"; + } + if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) { + if (!(message.RcvAddr && typeof message.RcvAddr.length === "number" || $util.isString(message.RcvAddr))) + return "RcvAddr: buffer expected"; + } + if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) { + if (!(message.RcvUserName && typeof message.RcvUserName.length === "number" || $util.isString(message.RcvUserName))) + return "RcvUserName: buffer expected"; + } + if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) { + if (!(message.SndAddr && typeof message.SndAddr.length === "number" || $util.isString(message.SndAddr))) + return "SndAddr: buffer expected"; + } + if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) { + if (!(message.SndUserName && typeof message.SndUserName.length === "number" || $util.isString(message.SndUserName))) + return "SndUserName: buffer expected"; + } + if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) { + if (!$util.isInteger(message.GasPrice) && !(message.GasPrice && $util.isInteger(message.GasPrice.low) && $util.isInteger(message.GasPrice.high))) + return "GasPrice: integer|Long expected"; + } + if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) { + if (!$util.isInteger(message.GasLimit) && !(message.GasLimit && $util.isInteger(message.GasLimit.low) && $util.isInteger(message.GasLimit.high))) + return "GasLimit: integer|Long expected"; + } + if (message.Data != null && message.hasOwnProperty("Data")) { + if (!(message.Data && typeof message.Data.length === "number" || $util.isString(message.Data))) + return "Data: buffer expected"; + } + if (message.ChainID != null && message.hasOwnProperty("ChainID")) { + if (!(message.ChainID && typeof message.ChainID.length === "number" || $util.isString(message.ChainID))) + return "ChainID: buffer expected"; + } + if (message.Version != null && message.hasOwnProperty("Version")) { + if (!$util.isInteger(message.Version)) + return "Version: integer expected"; + } + if (message.Signature != null && message.hasOwnProperty("Signature")) { + if (!(message.Signature && typeof message.Signature.length === "number" || $util.isString(message.Signature))) + return "Signature: buffer expected"; + } + if (message.Options != null && message.hasOwnProperty("Options")) { + if (!$util.isInteger(message.Options)) + return "Options: integer expected"; + } + if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) { + if (!(message.GuardianAddr && typeof message.GuardianAddr.length === "number" || $util.isString(message.GuardianAddr))) + return "GuardianAddr: buffer expected"; + } + if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) { + if (!(message.GuardianSignature && typeof message.GuardianSignature.length === "number" || $util.isString(message.GuardianSignature))) + return "GuardianSignature: buffer expected"; + } + return null; + }; + Transaction4.fromObject = function fromObject(object) { + if (object instanceof $root.proto.Transaction) + return object; + var message = new $root.proto.Transaction(); + if (object.Nonce != null) { + if ($util.Long) + (message.Nonce = $util.Long.fromValue(object.Nonce)).unsigned = true; + else if (typeof object.Nonce === "string") + message.Nonce = parseInt(object.Nonce, 10); + else if (typeof object.Nonce === "number") + message.Nonce = object.Nonce; + else if (typeof object.Nonce === "object") + message.Nonce = new $util.LongBits(object.Nonce.low >>> 0, object.Nonce.high >>> 0).toNumber(true); + } + if (object.Value != null) { + if (typeof object.Value === "string") + $util.base64.decode(object.Value, message.Value = $util.newBuffer($util.base64.length(object.Value)), 0); + else if (object.Value.length >= 0) + message.Value = object.Value; + } + if (object.RcvAddr != null) { + if (typeof object.RcvAddr === "string") + $util.base64.decode(object.RcvAddr, message.RcvAddr = $util.newBuffer($util.base64.length(object.RcvAddr)), 0); + else if (object.RcvAddr.length >= 0) + message.RcvAddr = object.RcvAddr; + } + if (object.RcvUserName != null) { + if (typeof object.RcvUserName === "string") + $util.base64.decode(object.RcvUserName, message.RcvUserName = $util.newBuffer($util.base64.length(object.RcvUserName)), 0); + else if (object.RcvUserName.length >= 0) + message.RcvUserName = object.RcvUserName; + } + if (object.SndAddr != null) { + if (typeof object.SndAddr === "string") + $util.base64.decode(object.SndAddr, message.SndAddr = $util.newBuffer($util.base64.length(object.SndAddr)), 0); + else if (object.SndAddr.length >= 0) + message.SndAddr = object.SndAddr; + } + if (object.SndUserName != null) { + if (typeof object.SndUserName === "string") + $util.base64.decode(object.SndUserName, message.SndUserName = $util.newBuffer($util.base64.length(object.SndUserName)), 0); + else if (object.SndUserName.length >= 0) + message.SndUserName = object.SndUserName; + } + if (object.GasPrice != null) { + if ($util.Long) + (message.GasPrice = $util.Long.fromValue(object.GasPrice)).unsigned = true; + else if (typeof object.GasPrice === "string") + message.GasPrice = parseInt(object.GasPrice, 10); + else if (typeof object.GasPrice === "number") + message.GasPrice = object.GasPrice; + else if (typeof object.GasPrice === "object") + message.GasPrice = new $util.LongBits(object.GasPrice.low >>> 0, object.GasPrice.high >>> 0).toNumber(true); + } + if (object.GasLimit != null) { + if ($util.Long) + (message.GasLimit = $util.Long.fromValue(object.GasLimit)).unsigned = true; + else if (typeof object.GasLimit === "string") + message.GasLimit = parseInt(object.GasLimit, 10); + else if (typeof object.GasLimit === "number") + message.GasLimit = object.GasLimit; + else if (typeof object.GasLimit === "object") + message.GasLimit = new $util.LongBits(object.GasLimit.low >>> 0, object.GasLimit.high >>> 0).toNumber(true); + } + if (object.Data != null) { + if (typeof object.Data === "string") + $util.base64.decode(object.Data, message.Data = $util.newBuffer($util.base64.length(object.Data)), 0); + else if (object.Data.length >= 0) + message.Data = object.Data; + } + if (object.ChainID != null) { + if (typeof object.ChainID === "string") + $util.base64.decode(object.ChainID, message.ChainID = $util.newBuffer($util.base64.length(object.ChainID)), 0); + else if (object.ChainID.length >= 0) + message.ChainID = object.ChainID; + } + if (object.Version != null) + message.Version = object.Version >>> 0; + if (object.Signature != null) { + if (typeof object.Signature === "string") + $util.base64.decode(object.Signature, message.Signature = $util.newBuffer($util.base64.length(object.Signature)), 0); + else if (object.Signature.length >= 0) + message.Signature = object.Signature; + } + if (object.Options != null) + message.Options = object.Options >>> 0; + if (object.GuardianAddr != null) { + if (typeof object.GuardianAddr === "string") + $util.base64.decode(object.GuardianAddr, message.GuardianAddr = $util.newBuffer($util.base64.length(object.GuardianAddr)), 0); + else if (object.GuardianAddr.length >= 0) + message.GuardianAddr = object.GuardianAddr; + } + if (object.GuardianSignature != null) { + if (typeof object.GuardianSignature === "string") + $util.base64.decode(object.GuardianSignature, message.GuardianSignature = $util.newBuffer($util.base64.length(object.GuardianSignature)), 0); + else if (object.GuardianSignature.length >= 0) + message.GuardianSignature = object.GuardianSignature; + } + return message; + }; + Transaction4.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.Nonce = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.Nonce = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.Value = ""; + else { + object.Value = []; + if (options.bytes !== Array) + object.Value = $util.newBuffer(object.Value); + } + if (options.bytes === String) + object.RcvAddr = ""; + else { + object.RcvAddr = []; + if (options.bytes !== Array) + object.RcvAddr = $util.newBuffer(object.RcvAddr); + } + if (options.bytes === String) + object.RcvUserName = ""; + else { + object.RcvUserName = []; + if (options.bytes !== Array) + object.RcvUserName = $util.newBuffer(object.RcvUserName); + } + if (options.bytes === String) + object.SndAddr = ""; + else { + object.SndAddr = []; + if (options.bytes !== Array) + object.SndAddr = $util.newBuffer(object.SndAddr); + } + if (options.bytes === String) + object.SndUserName = ""; + else { + object.SndUserName = []; + if (options.bytes !== Array) + object.SndUserName = $util.newBuffer(object.SndUserName); + } + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.GasPrice = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.GasPrice = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.GasLimit = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.GasLimit = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.Data = ""; + else { + object.Data = []; + if (options.bytes !== Array) + object.Data = $util.newBuffer(object.Data); + } + if (options.bytes === String) + object.ChainID = ""; + else { + object.ChainID = []; + if (options.bytes !== Array) + object.ChainID = $util.newBuffer(object.ChainID); + } + object.Version = 0; + if (options.bytes === String) + object.Signature = ""; + else { + object.Signature = []; + if (options.bytes !== Array) + object.Signature = $util.newBuffer(object.Signature); + } + object.Options = 0; + if (options.bytes === String) + object.GuardianAddr = ""; + else { + object.GuardianAddr = []; + if (options.bytes !== Array) + object.GuardianAddr = $util.newBuffer(object.GuardianAddr); + } + if (options.bytes === String) + object.GuardianSignature = ""; + else { + object.GuardianSignature = []; + if (options.bytes !== Array) + object.GuardianSignature = $util.newBuffer(object.GuardianSignature); + } + } + if (message.Nonce != null && message.hasOwnProperty("Nonce")) + if (typeof message.Nonce === "number") + object.Nonce = options.longs === String ? String(message.Nonce) : message.Nonce; + else + object.Nonce = options.longs === String ? $util.Long.prototype.toString.call(message.Nonce) : options.longs === Number ? new $util.LongBits(message.Nonce.low >>> 0, message.Nonce.high >>> 0).toNumber(true) : message.Nonce; + if (message.Value != null && message.hasOwnProperty("Value")) + object.Value = options.bytes === String ? $util.base64.encode(message.Value, 0, message.Value.length) : options.bytes === Array ? Array.prototype.slice.call(message.Value) : message.Value; + if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) + object.RcvAddr = options.bytes === String ? $util.base64.encode(message.RcvAddr, 0, message.RcvAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvAddr) : message.RcvAddr; + if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) + object.RcvUserName = options.bytes === String ? $util.base64.encode(message.RcvUserName, 0, message.RcvUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvUserName) : message.RcvUserName; + if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) + object.SndAddr = options.bytes === String ? $util.base64.encode(message.SndAddr, 0, message.SndAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndAddr) : message.SndAddr; + if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) + object.SndUserName = options.bytes === String ? $util.base64.encode(message.SndUserName, 0, message.SndUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndUserName) : message.SndUserName; + if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) + if (typeof message.GasPrice === "number") + object.GasPrice = options.longs === String ? String(message.GasPrice) : message.GasPrice; + else + object.GasPrice = options.longs === String ? $util.Long.prototype.toString.call(message.GasPrice) : options.longs === Number ? new $util.LongBits(message.GasPrice.low >>> 0, message.GasPrice.high >>> 0).toNumber(true) : message.GasPrice; + if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) + if (typeof message.GasLimit === "number") + object.GasLimit = options.longs === String ? String(message.GasLimit) : message.GasLimit; + else + object.GasLimit = options.longs === String ? $util.Long.prototype.toString.call(message.GasLimit) : options.longs === Number ? new $util.LongBits(message.GasLimit.low >>> 0, message.GasLimit.high >>> 0).toNumber(true) : message.GasLimit; + if (message.Data != null && message.hasOwnProperty("Data")) + object.Data = options.bytes === String ? $util.base64.encode(message.Data, 0, message.Data.length) : options.bytes === Array ? Array.prototype.slice.call(message.Data) : message.Data; + if (message.ChainID != null && message.hasOwnProperty("ChainID")) + object.ChainID = options.bytes === String ? $util.base64.encode(message.ChainID, 0, message.ChainID.length) : options.bytes === Array ? Array.prototype.slice.call(message.ChainID) : message.ChainID; + if (message.Version != null && message.hasOwnProperty("Version")) + object.Version = message.Version; + if (message.Signature != null && message.hasOwnProperty("Signature")) + object.Signature = options.bytes === String ? $util.base64.encode(message.Signature, 0, message.Signature.length) : options.bytes === Array ? Array.prototype.slice.call(message.Signature) : message.Signature; + if (message.Options != null && message.hasOwnProperty("Options")) + object.Options = message.Options; + if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) + object.GuardianAddr = options.bytes === String ? $util.base64.encode(message.GuardianAddr, 0, message.GuardianAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianAddr) : message.GuardianAddr; + if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) + object.GuardianSignature = options.bytes === String ? $util.base64.encode(message.GuardianSignature, 0, message.GuardianSignature.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianSignature) : message.GuardianSignature; + return object; + }; + Transaction4.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + Transaction4.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === void 0) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/proto.Transaction"; + }; + return Transaction4; + }(); + return proto; + }(); + return $root; + }); + } +}); + +// node_modules/@multiversx/sdk-core/out/proto/serializer.js +var require_serializer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/proto/serializer.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProtoSerializer = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var constants_1 = require_constants(); + var errors = __importStar2(require_errors()); + var utils_1 = require_utils(); + var ProtoSerializer = class { + /** + * Serializes a Transaction object to a Buffer. Handles low-level conversion logic and field-mappings as well. + */ + serializeTransaction(transaction) { + const proto = require_compiled().proto; + const receiverPubkey = new address_1.Address(transaction.getReceiver().bech32()).pubkey(); + const senderPubkey = new address_1.Address(transaction.getSender().bech32()).pubkey(); + let protoTransaction = new proto.Transaction({ + // mx-chain-go's serializer handles nonce == 0 differently, thus we treat 0 as "undefined". + Nonce: transaction.getNonce().valueOf() ? transaction.getNonce().valueOf() : void 0, + Value: this.serializeTransactionValue(transaction.getValue()), + RcvAddr: receiverPubkey, + RcvUserName: transaction.getReceiverUsername() ? import_buffer.Buffer.from(transaction.getReceiverUsername()).toString("base64") : void 0, + SndAddr: senderPubkey, + SndUserName: transaction.getSenderUsername() ? import_buffer.Buffer.from(transaction.getSenderUsername()).toString("base64") : void 0, + GasPrice: transaction.getGasPrice().valueOf(), + GasLimit: transaction.getGasLimit().valueOf(), + Data: transaction.getData().length() == 0 ? null : transaction.getData().valueOf(), + ChainID: import_buffer.Buffer.from(transaction.getChainID().valueOf()), + Version: transaction.getVersion().valueOf(), + Signature: transaction.getSignature() + }); + if (transaction.getOptions().valueOf() !== constants_1.TRANSACTION_OPTIONS_DEFAULT) { + protoTransaction.Options = transaction.getOptions().valueOf(); + } + if (transaction.isGuardedTransaction()) { + const guardianAddress = transaction.getGuardian(); + protoTransaction.GuardianAddr = new address_1.Address(guardianAddress.bech32()).pubkey(); + protoTransaction.GuardianSignature = transaction.getGuardianSignature(); + } + const encoded = proto.Transaction.encode(protoTransaction).finish(); + const buffer = import_buffer.Buffer.from(encoded); + return buffer; + } + /** + * Custom serialization, compatible with mx-chain-go. + */ + serializeTransactionValue(transactionValue) { + let value = new bignumber_js_1.default(transactionValue.toString()); + if (value.isZero()) { + return import_buffer.Buffer.from([0, 0]); + } + let buffer = utils_1.bigIntToBuffer(value); + buffer = import_buffer.Buffer.concat([import_buffer.Buffer.from([0]), buffer]); + return buffer; + } + deserializeTransaction(_buffer) { + throw new errors.ErrUnsupportedOperation("deserializeTransaction"); + } + }; + exports2.ProtoSerializer = ProtoSerializer; + } +}); + +// node_modules/@multiversx/sdk-core/out/proto/index.js +var require_proto = __commonJS({ + "node_modules/@multiversx/sdk-core/out/proto/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_serializer(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionComputer.js +var require_transactionComputer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionComputer.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionComputer = void 0; + var errors = __importStar2(require_errors()); + var bignumber_js_1 = __importDefault2(require_bignumber()); + var proto_1 = require_proto(); + var transaction_1 = require_transaction(); + var constants_1 = require_constants(); + var createTransactionHasher = require_blake2b2(); + var createKeccakHash = require_js(); + var TRANSACTION_HASH_LENGTH = 32; + var TransactionComputer2 = class { + constructor() { + } + computeTransactionFee(transaction, networkConfig2) { + const moveBalanceGas = BigInt(networkConfig2.MinGasLimit + transaction.data.length * networkConfig2.GasPerDataByte); + if (moveBalanceGas > transaction.gasLimit) { + throw new errors.ErrNotEnoughGas(parseInt(transaction.gasLimit.toString(), 10)); + } + const gasPrice = transaction.gasPrice; + const feeForMove = moveBalanceGas * gasPrice; + if (moveBalanceGas === transaction.gasLimit) { + return feeForMove; + } + const diff = transaction.gasLimit - moveBalanceGas; + const modifiedGasPrice = BigInt(new bignumber_js_1.default(gasPrice.toString()).multipliedBy(new bignumber_js_1.default(networkConfig2.GasPriceModifier)).toFixed(0)); + const processingFee = diff * modifiedGasPrice; + return feeForMove + processingFee; + } + computeBytesForSigning(transaction) { + this.ensureValidTransactionFields(transaction); + const plainTransaction = this.toPlainObjectForSigning(transaction); + const serialized = JSON.stringify(plainTransaction); + return new Uint8Array(import_buffer.Buffer.from(serialized)); + } + computeBytesForVerifying(transaction) { + const isTxSignedByHash = this.hasOptionsSetForHashSigning(transaction); + if (isTxSignedByHash) { + return this.computeHashForSigning(transaction); + } + return this.computeBytesForSigning(transaction); + } + computeHashForSigning(transaction) { + const plainTransaction = this.toPlainObjectForSigning(transaction); + const signable = import_buffer.Buffer.from(JSON.stringify(plainTransaction)); + return createKeccakHash("keccak256").update(signable).digest(); + } + computeTransactionHash(transaction) { + const serializer = new proto_1.ProtoSerializer(); + const buffer = serializer.serializeTransaction(new transaction_1.Transaction(transaction)); + const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); + return import_buffer.Buffer.from(hash, "hex"); + } + hasOptionsSetForGuardedTransaction(transaction) { + return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + hasOptionsSetForHashSigning(transaction) { + return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + applyGuardian(transaction, guardian) { + if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { + transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; + } + transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + transaction.guardian = guardian; + } + applyOptionsForHashSigning(transaction) { + if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { + transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; + } + transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + toPlainObjectForSigning(transaction) { + return { + nonce: Number(transaction.nonce), + value: transaction.value.toString(), + receiver: transaction.receiver, + sender: transaction.sender, + senderUsername: this.toBase64OrUndefined(transaction.senderUsername), + receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), + gasPrice: Number(transaction.gasPrice), + gasLimit: Number(transaction.gasLimit), + data: this.toBase64OrUndefined(transaction.data), + chainID: transaction.chainID, + version: transaction.version, + options: transaction.options ? transaction.options : void 0, + guardian: transaction.guardian ? transaction.guardian : void 0 + }; + } + toBase64OrUndefined(value) { + return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; + } + ensureValidTransactionFields(transaction) { + if (transaction.sender.length !== constants_1.BECH32_ADDRESS_LENGTH) { + throw new errors.ErrBadUsage("Invalid `sender` field. Should be the bech32 address of the sender."); + } + if (transaction.receiver.length !== constants_1.BECH32_ADDRESS_LENGTH) { + throw new errors.ErrBadUsage("Invalid `receiver` field. Should be the bech32 address of the receiver."); + } + if (!transaction.chainID.length) { + throw new errors.ErrBadUsage("The `chainID` field is not set"); + } + if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { + if (this.hasOptionsSetForGuardedTransaction(transaction) || this.hasOptionsSetForHashSigning(transaction)) { + throw new errors.ErrBadUsage(`Non-empty transaction options requires transaction version >= ${constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`); + } + } + } + }; + exports2.TransactionComputer = TransactionComputer2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transaction.js +var require_transaction = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transaction.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionHash = exports2.Transaction = void 0; + var bignumber_js_1 = require_bignumber(); + var address_1 = require_address(); + var constants_1 = require_constants(); + var transactionsConverter_1 = require_transactionsConverter(); + var hash_1 = require_hash(); + var networkParams_1 = require_networkParams(); + var signature_1 = require_signature(); + var transactionPayload_1 = require_transactionPayload(); + var transactionComputer_1 = require_transactionComputer(); + var Transaction4 = class { + /** + * Creates a new Transaction object. + */ + constructor(options) { + this.nonce = BigInt(options.nonce?.valueOf() || 0n); + this.value = options.value ? BigInt(new bignumber_js_1.BigNumber(options.value.toString()).toFixed(0)) : 0n; + this.sender = this.addressAsBech32(options.sender); + this.receiver = this.addressAsBech32(options.receiver); + this.senderUsername = options.senderUsername || ""; + this.receiverUsername = options.receiverUsername || ""; + this.gasPrice = BigInt(options.gasPrice?.valueOf() || constants_1.TRANSACTION_MIN_GAS_PRICE); + this.gasLimit = BigInt(options.gasLimit.valueOf()); + this.data = options.data?.valueOf() || new Uint8Array(); + this.chainID = options.chainID.valueOf(); + this.version = Number(options.version?.valueOf() || constants_1.TRANSACTION_VERSION_DEFAULT); + this.options = Number(options.options?.valueOf() || constants_1.TRANSACTION_OPTIONS_DEFAULT); + this.guardian = options.guardian ? this.addressAsBech32(options.guardian) : ""; + this.signature = options.signature || import_buffer.Buffer.from([]); + this.guardianSignature = options.guardianSignature || import_buffer.Buffer.from([]); + } + addressAsBech32(address) { + return typeof address === "string" ? address : address.bech32(); + } + /** + * Legacy method, use the "nonce" property instead. + */ + getNonce() { + return Number(this.nonce); + } + /** + * Legacy method, use the "nonce" property instead. + * Sets the account sequence number of the sender. Must be done prior signing. + */ + setNonce(nonce) { + this.nonce = BigInt(nonce.valueOf()); + } + /** + * Legacy method, use the "value" property instead. + */ + getValue() { + return this.value; + } + /** + * Legacy method, use the "value" property instead. + */ + setValue(value) { + this.value = BigInt(value.toString()); + } + /** + * Legacy method, use the "sender" property instead. + */ + getSender() { + return address_1.Address.fromBech32(this.sender); + } + /** + * Legacy method, use the "sender" property instead. + */ + setSender(sender) { + this.sender = typeof sender === "string" ? sender : sender.bech32(); + } + /** + * Legacy method, use the "receiver" property instead. + */ + getReceiver() { + return address_1.Address.fromBech32(this.receiver); + } + /** + * Legacy method, use the "senderUsername" property instead. + */ + getSenderUsername() { + return this.senderUsername; + } + /** + * Legacy method, use the "senderUsername" property instead. + */ + setSenderUsername(senderUsername) { + this.senderUsername = senderUsername; + } + /** + * Legacy method, use the "receiverUsername" property instead. + */ + getReceiverUsername() { + return this.receiverUsername; + } + /** + * Legacy method, use the "receiverUsername" property instead. + */ + setReceiverUsername(receiverUsername) { + this.receiverUsername = receiverUsername; + } + /** + * Legacy method, use the "guardian" property instead. + */ + getGuardian() { + return new address_1.Address(this.guardian); + } + /** + * Legacy method, use the "gasPrice" property instead. + */ + getGasPrice() { + return Number(this.gasPrice); + } + /** + * Legacy method, use the "gasPrice" property instead. + */ + setGasPrice(gasPrice) { + this.gasPrice = BigInt(gasPrice.valueOf()); + } + /** + * Legacy method, use the "gasLimit" property instead. + */ + getGasLimit() { + return Number(this.gasLimit); + } + /** + * Legacy method, use the "gasLimit" property instead. + */ + setGasLimit(gasLimit) { + this.gasLimit = BigInt(gasLimit.valueOf()); + } + /** + * Legacy method, use the "data" property instead. + */ + getData() { + return new transactionPayload_1.TransactionPayload(import_buffer.Buffer.from(this.data)); + } + /** + * Legacy method, use the "chainID" property instead. + */ + getChainID() { + return this.chainID; + } + /** + * Legacy method, use the "chainID" property instead. + */ + setChainID(chainID) { + this.chainID = chainID.valueOf(); + } + /** + * Legacy method, use the "version" property instead. + */ + getVersion() { + return new networkParams_1.TransactionVersion(this.version); + } + /** + * Legacy method, use the "version" property instead. + */ + setVersion(version2) { + this.version = version2.valueOf(); + } + /** + * Legacy method, use the "options" property instead. + */ + getOptions() { + return new networkParams_1.TransactionOptions(this.options.valueOf()); + } + /** + * Legacy method, use the "options" property instead. + * + * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. + */ + setOptions(options) { + this.options = options.valueOf(); + } + /** + * Legacy method, use the "signature" property instead. + */ + getSignature() { + return import_buffer.Buffer.from(this.signature); + } + /** + * Legacy method, use the "guardianSignature" property instead. + */ + getGuardianSignature() { + return import_buffer.Buffer.from(this.guardianSignature); + } + /** + * Legacy method, use the "guardian" property instead. + */ + setGuardian(guardian) { + this.guardian = typeof guardian === "string" ? guardian : guardian.bech32(); + } + /** + * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. + */ + getHash() { + return TransactionHash.compute(this); + } + /** + * Legacy method, use "TransactionComputer.computeBytesForSigning()" instead. + * Serializes a transaction to a sequence of bytes, ready to be signed. + * This function is called internally by signers. + */ + serializeForSigning() { + const computer = new transactionComputer_1.TransactionComputer(); + const bytes = computer.computeBytesForSigning(this); + return import_buffer.Buffer.from(bytes); + } + /** + * Checks the integrity of the guarded transaction + */ + isGuardedTransaction() { + const hasGuardian = this.guardian.length > 0; + const hasGuardianSignature = this.guardianSignature.length > 0; + return this.getOptions().isWithGuardian() && hasGuardian && hasGuardianSignature; + } + /** + * Legacy method, use "TransactionsConverter.transactionToPlainObject()" instead. + * + * Converts the transaction object into a ready-to-serialize, plain JavaScript object. + * This function is called internally within the signing procedure. + */ + toPlainObject() { + const converter = new transactionsConverter_1.TransactionsConverter(); + return converter.transactionToPlainObject(this); + } + /** + * Legacy method, use "TransactionsConverter.plainObjectToTransaction()" instead. + * Converts a plain object transaction into a Transaction Object. + * + * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() + */ + static fromPlainObject(plainObjectTransaction) { + const converter = new transactionsConverter_1.TransactionsConverter(); + return converter.plainObjectToTransaction(plainObjectTransaction); + } + /** + * Legacy method, use the "signature" property instead. + * Applies the signature on the transaction. + * + * @param signature The signature, as computed by a signer. + */ + applySignature(signature) { + this.signature = signature_1.interpretSignatureAsBuffer(signature); + } + /** + * Legacy method, use the "guardianSignature" property instead. + * Applies the guardian signature on the transaction. + * + * @param guardianSignature The signature, as computed by a signer. + */ + applyGuardianSignature(guardianSignature) { + this.guardianSignature = signature_1.interpretSignatureAsBuffer(guardianSignature); + } + /** + * Converts a transaction to a ready-to-broadcast object. + * Called internally by the network provider. + */ + toSendable() { + return this.toPlainObject(); + } + /** + * Legacy method, use "TransactionComputer.computeTransactionFee()" instead. + * + * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties + * @param networkConfig {@link NetworkConfig} + */ + computeFee(networkConfig2) { + const computer = new transactionComputer_1.TransactionComputer(); + const fee = computer.computeTransactionFee(this, networkConfig2); + return new bignumber_js_1.BigNumber(fee.toString()); + } + }; + exports2.Transaction = Transaction4; + var TransactionHash = class _TransactionHash extends hash_1.Hash { + constructor(hash) { + super(hash); + } + /** + * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. + * Computes the hash of a transaction. + */ + static compute(transaction) { + const computer = new transactionComputer_1.TransactionComputer(); + const hash = computer.computeTransactionHash(transaction); + return new _TransactionHash(import_buffer.Buffer.from(hash).toString("hex")); + } + }; + exports2.TransactionHash = TransactionHash; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js +var require_tokenOperationsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenOperationsFactory = void 0; + var constants_1 = require_constants(); + var logger_1 = require_logger(); + var networkParams_1 = require_networkParams(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var codec_1 = require_codec(); + var TokenOperationsFactory2 = class { + constructor(config) { + this.config = config; + this.trueAsHex = codec_1.utf8ToHex("true"); + this.falseAsHex = codec_1.utf8ToHex("false"); + } + issueFungible(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "issue", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.bigIntToHex(args.initialSupply), + codec_1.bigIntToHex(args.numDecimals), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + notifyAboutUnsettingBurnRoleGlobally() { + logger_1.Logger.info(` +========== +IMPORTANT! +========== +You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); + } + issueSemiFungible(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "issueSemiFungible", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canTransferNFTCreateRole"), + args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + issueNonFungible(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "issueNonFungible", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canTransferNFTCreateRole"), + args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + registerMetaESDT(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "registerMetaESDT", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.bigIntToHex(args.numDecimals), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canTransferNFTCreateRole"), + args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + registerAndSetAllRoles(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "registerAndSetAllRoles", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.utf8ToHex(args.tokenType), + codec_1.bigIntToHex(args.numDecimals) + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + setBurnRoleGlobally(args) { + const parts = ["setBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, + dataParts: parts + }); + } + unsetBurnRoleGlobally(args) { + const parts = ["unsetBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, + dataParts: parts + }); + } + setSpecialRoleOnFungible(args) { + const parts = [ + "setSpecialRole", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.addressToHex(args.user), + ...args.addRoleLocalMint ? [codec_1.utf8ToHex("ESDTRoleLocalMint")] : [], + ...args.addRoleLocalBurn ? [codec_1.utf8ToHex("ESDTRoleLocalBurn")] : [] + ]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitSetSpecialRole, + dataParts: parts + }); + } + setSpecialRoleOnSemiFungible(args) { + const parts = [ + "setSpecialRole", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.addressToHex(args.user), + ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], + ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], + ...args.addRoleNFTAddQuantity ? [codec_1.utf8ToHex("ESDTRoleNFTAddQuantity")] : [], + ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] + ]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitSetSpecialRole, + dataParts: parts + }); + } + setSpecialRoleOnMetaESDT(args) { + return this.setSpecialRoleOnSemiFungible(args); + } + setSpecialRoleOnNonFungible(args) { + const parts = [ + "setSpecialRole", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.addressToHex(args.user), + ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], + ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], + ...args.addRoleNFTUpdateAttributes ? [codec_1.utf8ToHex("ESDTRoleNFTUpdateAttributes")] : [], + ...args.addRoleNFTAddURI ? [codec_1.utf8ToHex("ESDTRoleNFTAddURI")] : [], + ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] + ]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitSetSpecialRole, + dataParts: parts + }); + } + nftCreate(args) { + const parts = [ + "ESDTNFTCreate", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.initialQuantity), + codec_1.utf8ToHex(args.name), + codec_1.bigIntToHex(args.royalties), + codec_1.utf8ToHex(args.hash), + codec_1.bufferToHex(args.attributes), + ...args.uris.map(codec_1.utf8ToHex) + ]; + const nftData = args.name + args.hash + args.attributes + args.uris.join(""); + const storageGasLimit = nftData.length * this.config.gasLimitStorePerByte.valueOf(); + return this.createTransaction({ + sender: args.creator, + receiver: args.creator, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTCreate.valueOf() + storageGasLimit.valueOf(), + dataParts: parts + }); + } + pause(args) { + const parts = ["pause", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitPausing, + dataParts: parts + }); + } + unpause(args) { + const parts = ["unPause", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitPausing, + dataParts: parts + }); + } + freeze(args) { + const parts = ["freeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitFreezing, + dataParts: parts + }); + } + unfreeze(args) { + const parts = ["unFreeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitFreezing, + dataParts: parts + }); + } + wipe(args) { + const parts = ["wipe", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitWiping, + dataParts: parts + }); + } + localMint(args) { + const parts = ["ESDTLocalMint", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToMint)]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTLocalMint, + dataParts: parts + }); + } + localBurn(args) { + const parts = ["ESDTLocalBurn", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToBurn)]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTLocalBurn, + dataParts: parts + }); + } + updateAttributes(args) { + const parts = [ + "ESDTNFTUpdateAttributes", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.tokenNonce), + codec_1.bufferToHex(args.attributes) + ]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTUpdateAttributes, + dataParts: parts + }); + } + addQuantity(args) { + const parts = [ + "ESDTNFTAddQuantity", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.tokenNonce), + codec_1.bigIntToHex(args.quantityToAdd) + ]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTAddQuantity, + dataParts: parts + }); + } + burnQuantity(args) { + const parts = [ + "ESDTNFTBurn", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.tokenNonce), + codec_1.bigIntToHex(args.quantityToBurn) + ]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTBurn, + dataParts: parts + }); + } + createTransaction({ sender, receiver, nonce, value, gasPrice, gasLimitHint, executionGasLimit, dataParts }) { + const payload = this.buildTransactionPayload(dataParts); + const gasLimit = gasLimitHint || this.computeGasLimit(payload, executionGasLimit); + const version2 = new networkParams_1.TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); + const options = new networkParams_1.TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); + return new transaction_1.Transaction({ + chainID: this.config.chainID, + sender, + receiver, + gasLimit, + gasPrice, + nonce: nonce || 0, + value: value || 0, + data: payload, + version: version2, + options + }); + } + buildTransactionPayload(parts) { + const data = parts.join(constants_1.ARGUMENTS_SEPARATOR); + return new transactionPayload_1.TransactionPayload(data); + } + computeGasLimit(payload, executionGas) { + const dataMovementGas = this.config.minGasLimit.valueOf() + this.config.gasLimitPerByte.valueOf() * payload.length(); + return dataMovementGas + executionGas.valueOf(); + } + }; + exports2.TokenOperationsFactory = TokenOperationsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js +var require_tokenOperationsFactoryConfig = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenOperationsFactoryConfig = void 0; + var address_1 = require_address(); + var TokenOperationsFactoryConfig2 = class { + constructor(chainID) { + this.minGasPrice = 1e9; + this.minGasLimit = 5e4; + this.gasLimitPerByte = 1500; + this.gasLimitIssue = 6e7; + this.gasLimitToggleBurnRoleGlobally = 6e7; + this.gasLimitESDTLocalMint = 3e5; + this.gasLimitESDTLocalBurn = 3e5; + this.gasLimitSetSpecialRole = 6e7; + this.gasLimitPausing = 6e7; + this.gasLimitFreezing = 6e7; + this.gasLimitWiping = 6e7; + this.gasLimitESDTNFTCreate = 3e6; + this.gasLimitESDTNFTUpdateAttributes = 1e6; + this.gasLimitESDTNFTAddQuantity = 1e6; + this.gasLimitESDTNFTBurn = 1e6; + this.gasLimitStorePerByte = 5e4; + this.issueCost = "50000000000000000"; + this.esdtContractAddress = address_1.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); + this.chainID = chainID; + } + }; + exports2.TokenOperationsFactoryConfig = TokenOperationsFactoryConfig2; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js +var require_tokenOperationsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenOperationsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var codec_1 = require_codec(); + var TokenOperationsOutcomeParser2 = class { + parseIssueFungible(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "issue"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseIssueNonFungible(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "issueNonFungible"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseIssueSemiFungible(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "issueSemiFungible"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseRegisterMetaESDT(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "registerMetaESDT"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseRegisterAndSetAllRoles(transaction) { + this.ensureNoError(transaction); + const eventRegister = this.findSingleEventByIdentifier(transaction, "registerAndSetAllRoles"); + const tokenIdentifier = this.extractTokenIdentifier(eventRegister); + const eventSetRole = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); + const roles = eventSetRole.topics.slice(3).map((topic) => topic.valueOf().toString()); + return { tokenIdentifier, roles }; + } + parseSetBurnRoleGlobally(transaction) { + this.ensureNoError(transaction); + return {}; + } + parseUnsetBurnRoleGlobally(transaction) { + this.ensureNoError(transaction); + return {}; + } + parseSetSpecialRole(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); + const userAddress = event.address.toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const roles = event.topics.slice(3).map((topic) => topic.valueOf().toString()); + return { userAddress, tokenIdentifier, roles }; + } + parseNFTCreate(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTCreate"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const initialQuantity = this.extractAmount(event); + return { tokenIdentifier, nonce, initialQuantity }; + } + parseLocalMint(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalMint"); + const userAddress = event.address.toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const mintedSupply = this.extractAmount(event); + return { userAddress, tokenIdentifier, nonce, mintedSupply }; + } + parseLocalBurn(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalBurn"); + const userAddress = event.address.toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntSupply = this.extractAmount(event); + return { userAddress, tokenIdentifier, nonce, burntSupply }; + } + parsePause(transaction) { + this.ensureNoError(transaction); + const _4 = this.findSingleEventByIdentifier(transaction, "ESDTPause"); + return {}; + } + parseUnpause(transaction) { + this.ensureNoError(transaction); + const _4 = this.findSingleEventByIdentifier(transaction, "ESDTUnPause"); + return {}; + } + parseFreeze(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTFreeze"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + const userAddress = this.extractAddress(event); + return { userAddress, tokenIdentifier, nonce, balance }; + } + parseUnfreeze(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTUnFreeze"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + const userAddress = this.extractAddress(event); + return { userAddress, tokenIdentifier, nonce, balance }; + } + parseWipe(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTWipe"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + const userAddress = this.extractAddress(event); + return { userAddress, tokenIdentifier, nonce, balance }; + } + parseUpdateAttributes(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTUpdateAttributes"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const attributes = event.topics[3]?.valueOf(); + return { tokenIdentifier, nonce, attributes }; + } + parseAddQuantity(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTAddQuantity"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const addedQuantity = this.extractAmount(event); + return { tokenIdentifier, nonce, addedQuantity }; + } + parseBurnQuantity(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTBurn"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntQuantity = this.extractAmount(event); + return { tokenIdentifier, nonce, burntQuantity }; + } + ensureNoError(transaction) { + for (const event of transaction.logs.events) { + if (event.identifier == "signalError") { + const data = import_buffer.Buffer.from(event.data.substring(1), "hex").toString(); + const message = event.topics[1]?.valueOf().toString(); + throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `encountered signalError: ${message} (${data})`); + } + } + } + findSingleEventByIdentifier(transaction, identifier) { + const events = this.gatherAllEvents(transaction).filter((event) => event.identifier == identifier); + if (events.length == 0) { + throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `cannot find event of type ${identifier}`); + } + if (events.length > 1) { + throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `more than one event of type ${identifier}`); + } + return events[0]; + } + gatherAllEvents(transaction) { + const allEvents = []; + allEvents.push(...transaction.logs.events); + for (const item of transaction.contractResults.items) { + allEvents.push(...item.logs.events); + } + return allEvents; + } + extractTokenIdentifier(event) { + return event.topics[0]?.valueOf().toString(); + } + extractNonce(event) { + return codec_1.bufferToBigInt(event.topics[1]?.valueOf()).toFixed(0); + } + extractAmount(event) { + return codec_1.bufferToBigInt(event.topics[2]?.valueOf()).toFixed(0); + } + extractAddress(event) { + return address_1.Address.fromBuffer(event.topics[3]?.valueOf()).toString(); + } + }; + exports2.TokenOperationsOutcomeParser = TokenOperationsOutcomeParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/index.js +var require_tokenOperations = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_tokenOperationsFactory(), exports2); + __exportStar2(require_tokenOperationsFactoryConfig(), exports2); + __exportStar2(require_tokenOperationsOutcomeParser(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js +var require_delegationTransactionsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DelegationTransactionsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var resources_1 = require_resources(); + var DelegationTransactionsOutcomeParser = class { + constructor() { + } + parseCreateNewDelegationContract(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "SCDeploy"); + return events.map((event) => ({ contractAddress: this.extractContractAddress(event) })); + } + ensureNoError(transactionEvents) { + for (const event of transactionEvents) { + if (event.identifier == "signalError") { + const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; + const message = this.decodeTopicAsString(event.topics[1]); + throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); + } + } + } + extractContractAddress(event) { + if (!event.topics[0]?.length) { + return ""; + } + const address = import_buffer.Buffer.from(event.topics[0]); + return address_1.Address.fromBuffer(address).bech32(); + } + decodeTopicAsString(topic) { + return import_buffer.Buffer.from(topic).toString(); + } + }; + exports2.DelegationTransactionsOutcomeParser = DelegationTransactionsOutcomeParser; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js +var require_smartContractTransactionsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractTransactionsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var resources_1 = require_resources(); + var SmartContractTransactionsOutcomeParser2 = class { + constructor(options) { + this.abi = options?.abi; + this.legacyResultsParser = options?.legacyResultsParser || new smartcontracts_1.ResultsParser(); + } + parseDeploy(options) { + const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; + const events = resources_1.findEventsByIdentifier(options.transactionOutcome, "SCDeploy"); + const contracts = events.map((event) => this.parseScDeployEvent(event)); + return { + returnCode: directCallOutcome.returnCode, + returnMessage: directCallOutcome.returnMessage, + contracts + }; + } + parseScDeployEvent(event) { + const topicForAddress = event.topics[0]; + const topicForOwnerAddress = event.topics[1]; + const topicForCodeHash = event.topics[2]; + const address = topicForAddress?.length ? new address_1.Address(topicForAddress).toBech32() : ""; + const ownerAddress = topicForOwnerAddress?.length ? new address_1.Address(topicForOwnerAddress).toBech32() : ""; + const codeHash = topicForCodeHash; + return { + address, + ownerAddress, + codeHash + }; + } + parseExecute(options) { + const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; + if (!this.abi) { + return { + values: directCallOutcome.returnDataParts, + returnCode: directCallOutcome.returnCode, + returnMessage: directCallOutcome.returnMessage + }; + } + const functionName = options.function || directCallOutcome.function; + if (!functionName) { + throw new errors_1.Err(`Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?`); + } + const endpoint = this.abi.getEndpoint(functionName); + const legacyUntypedBundle = { + returnCode: new smartcontracts_1.ReturnCode(directCallOutcome.returnCode), + returnMessage: directCallOutcome.returnMessage, + values: directCallOutcome.returnDataParts.map((part) => import_buffer.Buffer.from(part)) + }; + const legacyTypedBundle = this.legacyResultsParser.parseOutcomeFromUntypedBundle(legacyUntypedBundle, endpoint); + return { + values: legacyTypedBundle.values.map((value) => value.valueOf()), + returnCode: legacyTypedBundle.returnCode.toString(), + returnMessage: legacyTypedBundle.returnMessage + }; + } + }; + exports2.SmartContractTransactionsOutcomeParser = SmartContractTransactionsOutcomeParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js +var require_tokenManagementTransactionsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenManagementTransactionsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var utils_1 = require_utils(); + var resources_1 = require_resources(); + var TokenManagementTransactionsOutcomeParser2 = class { + constructor() { + } + parseIssueFungible(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "issue"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseIssueNonFungible(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueNonFungible"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseIssueSemiFungible(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueSemiFungible"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseRegisterMetaEsdt(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "registerMetaESDT"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseRegisterAndSetAllRoles(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const registerEvents = resources_1.findEventsByIdentifier(transactionOutcome, "registerAndSetAllRoles"); + const setRoleEvents = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); + if (registerEvents.length !== setRoleEvents.length) { + throw new errors_1.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events."); + } + return registerEvents.map((registerEvent, index) => { + const tokenIdentifier = this.extractTokenIdentifier(registerEvent); + const encodedRoles = setRoleEvents[index].topics.slice(3); + const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); + return { tokenIdentifier, roles }; + }); + } + parseSetBurnRoleGlobally(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + } + parseUnsetBurnRoleGlobally(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + } + parseSetSpecialRole(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); + return events.map((event) => this.getOutputForSetSpecialRoleEvent(event)); + } + getOutputForSetSpecialRoleEvent(event) { + const userAddress = event.address; + const tokenIdentifier = this.extractTokenIdentifier(event); + const encodedRoles = event.topics.slice(3); + const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); + return { userAddress, tokenIdentifier, roles }; + } + parseNftCreate(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTCreate"); + return events.map((event) => this.getOutputForNftCreateEvent(event)); + } + getOutputForNftCreateEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const amount = this.extractAmount(event); + return { tokenIdentifier, nonce, initialQuantity: amount }; + } + parseLocalMint(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalMint"); + return events.map((event) => this.getOutputForLocalMintEvent(event)); + } + getOutputForLocalMintEvent(event) { + const userAddress = event.address; + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const mintedSupply = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + mintedSupply + }; + } + parseLocalBurn(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalBurn"); + return events.map((event) => this.getOutputForLocalBurnEvent(event)); + } + getOutputForLocalBurnEvent(event) { + const userAddress = event.address; + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntSupply = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + burntSupply + }; + } + parsePause(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTPause"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseUnpause(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnPause"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseFreeze(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTFreeze"); + return events.map((event) => this.getOutputForFreezeEvent(event)); + } + getOutputForFreezeEvent(event) { + const userAddress = this.extractAddress(event); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + balance + }; + } + parseUnfreeze(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnFreeze"); + return events.map((event) => this.getOutputForUnfreezeEvent(event)); + } + getOutputForUnfreezeEvent(event) { + const userAddress = this.extractAddress(event); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + balance + }; + } + parseWipe(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTWipe"); + return events.map((event) => this.getOutputForWipeEvent(event)); + } + getOutputForWipeEvent(event) { + const userAddress = this.extractAddress(event); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + balance + }; + } + parseUpdateAttributes(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTUpdateAttributes"); + return events.map((event) => this.getOutputForUpdateAttributesEvent(event)); + } + getOutputForUpdateAttributesEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const attributes = event.topics[3] ? event.topics[3] : new Uint8Array(); + return { + tokenIdentifier, + nonce, + attributes + }; + } + parseAddQuantity(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTAddQuantity"); + return events.map((event) => this.getOutputForAddQuantityEvent(event)); + } + getOutputForAddQuantityEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const addedQuantity = this.extractAmount(event); + return { + tokenIdentifier, + nonce, + addedQuantity + }; + } + parseBurnQuantity(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTBurn"); + return events.map((event) => this.getOutputForBurnQuantityEvent(event)); + } + getOutputForBurnQuantityEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntQuantity = this.extractAmount(event); + return { + tokenIdentifier, + nonce, + burntQuantity + }; + } + ensureNoError(transactionEvents) { + for (const event of transactionEvents) { + if (event.identifier == "signalError") { + const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; + const message = this.decodeTopicAsString(event.topics[1]); + throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); + } + } + } + extractTokenIdentifier(event) { + if (!event.topics[0]?.length) { + return ""; + } + return this.decodeTopicAsString(event.topics[0]); + } + extractNonce(event) { + if (!event.topics[1]?.length) { + return BigInt(0); + } + const nonce = import_buffer.Buffer.from(event.topics[1]); + return BigInt(utils_1.bufferToBigInt(nonce).toFixed(0)); + } + extractAmount(event) { + if (!event.topics[2]?.length) { + return BigInt(0); + } + const amount = import_buffer.Buffer.from(event.topics[2]); + return BigInt(utils_1.bufferToBigInt(amount).toFixed(0)); + } + extractAddress(event) { + if (!event.topics[3]?.length) { + return ""; + } + const address = import_buffer.Buffer.from(event.topics[3]); + return address_1.Address.fromBuffer(address).bech32(); + } + decodeTopicAsString(topic) { + return import_buffer.Buffer.from(topic).toString(); + } + }; + exports2.TokenManagementTransactionsOutcomeParser = TokenManagementTransactionsOutcomeParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js +var require_transactionEventsParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionEventsParser = void 0; + var smartcontracts_1 = require_smartcontracts(); + var TransactionEventsParser2 = class { + constructor(options) { + this.legacyResultsParser = new smartcontracts_1.ResultsParser(); + this.abi = options.abi; + this.firstTopicIsIdentifier = options.firstTopicIsIdentifier ?? true; + } + parseEvents(options) { + const results = []; + for (const event of options.events) { + const parsedEvent = this.parseEvent({ event }); + results.push(parsedEvent); + } + return results; + } + parseEvent(options) { + const topics = options.event.topics.map((topic) => import_buffer.Buffer.from(topic)); + const abiIdentifier = this.firstTopicIsIdentifier ? topics[0]?.toString() : options.event.identifier; + if (this.firstTopicIsIdentifier) { + topics.shift(); + } + const dataItems = options.event.dataItems.map((dataItem) => import_buffer.Buffer.from(dataItem)); + const eventDefinition = this.abi.getEvent(abiIdentifier); + const parsedEvent = this.legacyResultsParser.doParseEvent({ + topics, + dataItems, + eventDefinition + }); + return parsedEvent; + } + }; + exports2.TransactionEventsParser = TransactionEventsParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js +var require_transactionsOutcomeParsers = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_delegationTransactionsOutcomeParser(), exports2); + __exportStar2(require_resources(), exports2); + __exportStar2(require_smartContractTransactionsOutcomeParser(), exports2); + __exportStar2(require_tokenManagementTransactionsOutcomeParser(), exports2); + __exportStar2(require_transactionEventsParser(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/account.js +var require_account = __commonJS({ + "node_modules/@multiversx/sdk-core/out/account.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Account = void 0; + var address_1 = require_address(); + var Account5 = class { + /** + * Creates an account object from an address + */ + constructor(address) { + this.address = address_1.Address.empty(); + this.nonce = 0; + this.balance = "0"; + this.address = address; + } + /** + * Updates account properties (such as nonce, balance). + */ + update(obj) { + this.nonce = obj.nonce; + this.balance = obj.balance; + } + /** + * Increments (locally) the nonce (the account sequence number). + */ + incrementNonce() { + this.nonce = this.nonce.valueOf() + 1; + } + /** + * Gets then increments (locally) the nonce (the account sequence number). + */ + getNonceThenIncrement() { + let nonce = this.nonce; + this.nonce = this.nonce.valueOf() + 1; + return nonce; + } + /** + * Converts the account to a pretty, plain JavaScript object. + */ + toJSON() { + return { + address: this.address.bech32(), + nonce: this.nonce.valueOf(), + balance: this.balance.toString() + }; + } + }; + exports2.Account = Account5; + } +}); + +// node_modules/@multiversx/sdk-core/out/message.js +var require_message = __commonJS({ + "node_modules/@multiversx/sdk-core/out/message.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MessageComputer = exports2.Message = void 0; + var constants_1 = require_constants(); + var address_1 = require_address(); + var createKeccakHash = require_js(); + var Message2 = class { + constructor(options) { + this.data = options.data; + this.signature = options.signature; + this.address = options.address; + this.version = options.version || constants_1.DEFAULT_MESSAGE_VERSION; + this.signer = options.signer || constants_1.SDK_JS_SIGNER; + } + }; + exports2.Message = Message2; + var MessageComputer2 = class { + constructor() { + } + computeBytesForSigning(message) { + const messageSize = import_buffer.Buffer.from(message.data.length.toString()); + const signableMessage = import_buffer.Buffer.concat([messageSize, message.data]); + let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); + return createKeccakHash("keccak256").update(bytesToHash).digest(); + } + computeBytesForVerifying(message) { + return this.computeBytesForSigning(message); + } + packMessage(message) { + return { + message: import_buffer.Buffer.from(message.data).toString("hex"), + signature: message.signature ? import_buffer.Buffer.from(message.signature).toString("hex") : "", + address: message.address ? message.address.bech32() : "", + version: message.version, + signer: message.signer + }; + } + unpackMessage(packedMessage) { + const dataHex = this.trimHexPrefix(packedMessage.message); + const data = import_buffer.Buffer.from(dataHex, "hex"); + const signatureHex = this.trimHexPrefix(packedMessage.signature || ""); + const signature = import_buffer.Buffer.from(signatureHex, "hex"); + let address = void 0; + if (packedMessage.address) { + address = address_1.Address.fromBech32(packedMessage.address); + } + const version2 = packedMessage.version || constants_1.DEFAULT_MESSAGE_VERSION; + const signer = packedMessage.signer || constants_1.UNKNOWN_SIGNER; + return new Message2({ + data, + signature, + address, + version: version2, + signer + }); + } + trimHexPrefix(data) { + if (data.startsWith("0x") || data.startsWith("0X")) { + return data.slice(2); + } + return data; + } + }; + exports2.MessageComputer = MessageComputer2; + } +}); + +// node_modules/@multiversx/sdk-core/out/asyncTimer.js +var require_asyncTimer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/asyncTimer.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AsyncTimer = void 0; + var errors = __importStar2(require_errors()); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var AsyncTimer = class { + /** + * Creates an AsyncTimer. + */ + constructor(name2) { + this.timeoutHandle = null; + this.rejectionFunc = null; + this.name = name2; + this.correlationTag = 0; + } + /** + * Starts the timer. + * @param timeout The time (in milliseconds) to wait until resolving the promise. + */ + start(timeout) { + if (this.timeoutHandle) { + throw new errors.ErrAsyncTimerAlreadyRunning(); + } + this.correlationTag++; + logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`); + return new Promise((resolve, reject) => { + this.rejectionFunc = reject; + let timeoutCallback = () => { + this.rejectionFunc = null; + this.stop(); + resolve(); + }; + this.timeoutHandle = setTimeout(timeoutCallback, timeout); + }); + } + /** + * Aborts the timer: rejects the promise (if any) and stops the timer. + */ + abort() { + logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`); + if (this.rejectionFunc) { + this.rejectionFunc(new errors_1.ErrAsyncTimerAborted()); + this.rejectionFunc = null; + } + this.stop(); + } + /** + * Stops the timer. + */ + stop() { + if (this.isStopped()) { + return; + } + logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`); + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = null; + } + } + /** + * Returns whether the timer is stopped. + */ + isStopped() { + return this.timeoutHandle ? false : true; + } + }; + exports2.AsyncTimer = AsyncTimer; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionWatcher.js +var require_transactionWatcher = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionWatcher.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionWatcher = void 0; + var asyncTimer_1 = require_asyncTimer(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var TransactionWatcher3 = class _TransactionWatcher { + /** + * A transaction watcher (awaiter). + * + * @param fetcher The transaction fetcher + * @param options The options + * @param options.pollingIntervalMilliseconds The polling interval, in milliseconds + * @param options.timeoutMilliseconds The timeout, in milliseconds + * @param options.patienceMilliseconds The patience: an extra time (in milliseconds) to wait, after the transaction has reached its desired status. Currently there's a delay between the moment a transaction is marked as "completed" and the moment its outcome (contract results, events and logs) is available. + */ + constructor(fetcher, options = {}) { + this.fetcher = new TransactionFetcherWithTracing(fetcher); + this.pollingIntervalMilliseconds = options.pollingIntervalMilliseconds || _TransactionWatcher.DefaultPollingInterval; + this.timeoutMilliseconds = options.timeoutMilliseconds || _TransactionWatcher.DefaultTimeout; + this.patienceMilliseconds = options.patienceMilliseconds || _TransactionWatcher.DefaultPatience; + } + /** + * Waits until the transaction reaches the "pending" status. + * @param txHash The hex-encoded transaction hash + */ + async awaitPending(transactionOrTxHash) { + const isPending = (transaction) => transaction.status.isPending(); + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); + return this.awaitConditionally(isPending, doFetch, errorProvider); + } + /** + * Waits until the transaction is completely processed. + * @param txHash The hex-encoded transaction hash + */ + async awaitCompleted(transactionOrTxHash) { + const isCompleted = (transactionOnNetwork) => { + if (transactionOnNetwork.isCompleted === void 0) { + throw new errors_1.ErrIsCompletedFieldIsMissingOnTransaction(); + } + return transactionOnNetwork.isCompleted; + }; + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); + return this.awaitConditionally(isCompleted, doFetch, errorProvider); + } + async awaitAllEvents(transactionOrTxHash, events) { + const foundAllEvents = (transactionOnNetwork) => { + const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); + const allAreFound = events.every((event) => allEventIdentifiers.includes(event)); + return allAreFound; + }; + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); + return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); + } + async awaitAnyEvent(transactionOrTxHash, events) { + const foundAnyEvent = (transactionOnNetwork) => { + const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); + const anyIsFound = events.find((event) => allEventIdentifiers.includes(event)) != void 0; + return anyIsFound; + }; + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); + return this.awaitConditionally(foundAnyEvent, doFetch, errorProvider); + } + async awaitOnCondition(transactionOrTxHash, condition) { + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); + return this.awaitConditionally(condition, doFetch, errorProvider); + } + transactionOrTxHashToTxHash(transactionOrTxHash) { + const hash = typeof transactionOrTxHash === "string" ? transactionOrTxHash : transactionOrTxHash.getHash().hex(); + if (hash.length !== constants_1.HEX_TRANSACTION_HASH_LENGTH) { + throw new errors_1.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${constants_1.HEX_TRANSACTION_HASH_LENGTH}.`); + } + return hash; + } + async awaitConditionally(isSatisfied, doFetch, createError) { + const periodicTimer = new asyncTimer_1.AsyncTimer("watcher:periodic"); + const patienceTimer = new asyncTimer_1.AsyncTimer("watcher:patience"); + const timeoutTimer = new asyncTimer_1.AsyncTimer("watcher:timeout"); + let stop = false; + let fetchedData = void 0; + let satisfied = false; + timeoutTimer.start(this.timeoutMilliseconds).finally(() => { + timeoutTimer.stop(); + stop = true; + }); + while (!stop) { + await periodicTimer.start(this.pollingIntervalMilliseconds); + try { + fetchedData = await doFetch(); + satisfied = isSatisfied(fetchedData); + if (satisfied || stop) { + break; + } + } catch (error) { + logger_1.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."); + if (error instanceof errors_1.ErrIsCompletedFieldIsMissingOnTransaction) { + throw error; + } + if (!(error instanceof errors_1.Err)) { + throw error; + } + } + } + if (satisfied) { + await patienceTimer.start(this.patienceMilliseconds); + } + if (!timeoutTimer.isStopped()) { + timeoutTimer.stop(); + } + if (!fetchedData || !satisfied) { + throw createError(); + } + return fetchedData; + } + getAllTransactionEvents(transaction) { + const result = [...transaction.logs.events]; + for (const resultItem of transaction.contractResults.items) { + result.push(...resultItem.logs.events); + } + return result; + } + }; + exports2.TransactionWatcher = TransactionWatcher3; + TransactionWatcher3.DefaultPollingInterval = 6e3; + TransactionWatcher3.DefaultTimeout = TransactionWatcher3.DefaultPollingInterval * 15; + TransactionWatcher3.DefaultPatience = 0; + TransactionWatcher3.NoopOnStatusReceived = (_4) => { + }; + var TransactionFetcherWithTracing = class { + constructor(fetcher) { + this.fetcher = fetcher; + } + async getTransaction(txHash) { + logger_1.Logger.debug(`transactionWatcher, getTransaction(${txHash})`); + return await this.fetcher.getTransaction(txHash); + } + }; + } +}); + +// node_modules/@multiversx/sdk-core/out/signableMessage.js +var require_signableMessage = __commonJS({ + "node_modules/@multiversx/sdk-core/out/signableMessage.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SignableMessage = void 0; + var address_1 = require_address(); + var signature_1 = require_signature(); + var constants_1 = require_constants(); + var createKeccakHash = require_js(); + var SignableMessage3 = class { + constructor(init) { + this.message = import_buffer.Buffer.from([]); + this.signature = import_buffer.Buffer.from([]); + this.version = 1; + this.signer = "ErdJS"; + this.address = address_1.Address.empty(); + Object.assign(this, init); + } + serializeForSigning() { + const messageSize = import_buffer.Buffer.from(this.message.length.toString()); + const signableMessage = import_buffer.Buffer.concat([messageSize, this.message]); + let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); + return createKeccakHash("keccak256").update(bytesToHash).digest(); + } + serializeForSigningRaw() { + return import_buffer.Buffer.concat([this.getMessageSize(), this.message]); + } + getSignature() { + return this.signature; + } + applySignature(signature) { + this.signature = signature_1.interpretSignatureAsBuffer(signature); + } + getMessageSize() { + const messageSize = import_buffer.Buffer.alloc(4); + messageSize.writeUInt32BE(this.message.length, 0); + return messageSize; + } + toJSON() { + return { + address: this.address.bech32(), + message: "0x" + this.message.toString("hex"), + signature: "0x" + this.signature.toString("hex"), + version: this.version, + signer: this.signer + }; + } + }; + exports2.SignableMessage = SignableMessage3; + } +}); + +// node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js +var require_bignumber2 = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js"(exports2, module2) { + init_shim(); + (function(globalObject) { + "use strict"; + var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; + function clone2(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + function BigNumber3(v2, b4) { + var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber3)) + return new BigNumber3(v2, b4); + if (b4 == null) { + if (v2 && v2._isBigNumber === true) { + x3.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v2.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v2.e; + x3.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric2.test(str = String(v2))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i2 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i2; + e2 += +str.slice(i2 + 1); + str = str.substring(0, i2); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + if (b4 == 10) { + x3 = new BigNumber3(v2); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric(x3, str, isNum, b4); + x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits2 + v2); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet2 = ALPHABET.slice(0, b4); + e2 = i2 = 0; + for (len = str.length; i2 < len; i2++) { + if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { + if (c4 == ".") { + if (i2 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i2 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v2), isNum, b4); + } + } + isNum = false; + str = convertBase(str, b4, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i2 = 0; str.charCodeAt(i2) === 48; i2++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i2, ++len)) { + len -= i2; + if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { + throw Error(tooManyDigits2 + x3.s * v2); + } + if ((e2 = e2 - i2 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i2 = (e2 + 1) % LOG_BASE2; + if (e2 < 0) + i2 += LOG_BASE2; + if (i2 < len) { + if (i2) + x3.c.push(+str.slice(0, i2)); + for (len -= LOG_BASE2; i2 < len; ) { + x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); + } + i2 = LOG_BASE2 - (str = str.slice(i2)).length; + } else { + i2 -= len; + } + for (; i2--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber3.clone = clone2; + BigNumber3.ROUND_UP = 0; + BigNumber3.ROUND_DOWN = 1; + BigNumber3.ROUND_CEIL = 2; + BigNumber3.ROUND_FLOOR = 3; + BigNumber3.ROUND_HALF_UP = 4; + BigNumber3.ROUND_HALF_DOWN = 5; + BigNumber3.ROUND_HALF_EVEN = 6; + BigNumber3.ROUND_HALF_CEIL = 7; + BigNumber3.ROUND_HALF_FLOOR = 8; + BigNumber3.EUCLID = 9; + BigNumber3.config = BigNumber3.set = function(obj) { + var p3, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 8, p3); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, 0, p3); + intCheck2(v2[1], 0, MAX2, p3); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p3 = "RANGE")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, -1, p3); + intCheck2(v2[1], 1, MAX2, p3); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p3 = "CRYPTO")) { + v2 = obj[p3]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError2 + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError2 + p3 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 9, p3); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p3 = "FORMAT")) { + v2 = obj[p3]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError2 + p3 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p3 = "ALPHABET")) { + v2 = obj[p3]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + ALPHABET = v2; + } else { + throw Error(bignumberError2 + p3 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError2 + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber3.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber3.DEBUG) + return true; + var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c4) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { + if (c4[0] === 0) { + if (e2 === 0 && c4.length === 1) + return true; + break out; + } + i2 = (e2 + 1) % LOG_BASE2; + if (i2 < 1) + i2 += LOG_BASE2; + if (String(c4[0]).length == i2) { + for (i2 = 0; i2 < c4.length; i2++) { + n3 = c4[i2]; + if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError2 + "Invalid BigNumber: " + v2); + }; + BigNumber3.maximum = BigNumber3.max = function() { + return maxOrMin(arguments, P2.lt); + }; + BigNumber3.minimum = BigNumber3.min = function() { + return maxOrMin(arguments, P2.gt); + }; + BigNumber3.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor2(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck2(dp, 0, MAX2); + k4 = mathceil2(dp / LOG_BASE2); + if (CRYPTO) { + if (crypto.getRandomValues) { + a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); + for (; i2 < k4; ) { + v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); + if (v2 >= 9e15) { + b4 = crypto.getRandomValues(new Uint32Array(2)); + a3[i2] = b4[0]; + a3[i2 + 1] = b4[1]; + } else { + c4.push(v2 % 1e14); + i2 += 2; + } + } + i2 = k4 / 2; + } else if (crypto.randomBytes) { + a3 = crypto.randomBytes(k4 *= 7); + for (; i2 < k4; ) { + v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a3, i2); + } else { + c4.push(v2 % 1e14); + i2 += 7; + } + } + i2 = k4 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError2 + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i2 < k4; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c4[i2++] = v2 % 1e14; + } + } + k4 = c4[--i2]; + dp %= LOG_BASE2; + if (k4 && dp) { + v2 = POWS_TEN2[LOG_BASE2 - dp]; + c4[i2] = mathfloor2(k4 / v2) * v2; + } + for (; c4[i2] === 0; c4.pop(), i2--) + ; + if (i2 < 0) { + c4 = [e2 = 0]; + } else { + for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) + ; + for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) + ; + if (i2 < LOG_BASE2) + e2 -= LOG_BASE2 - i2; + } + rand.e = e2; + rand.c = c4; + return rand; + }; + }(); + BigNumber3.sum = function() { + var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); + for (; i2 < args.length; ) + sum = sum.plus(args[i2++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet2) { + var j2, arr = [0], arrL, i2 = 0, len = str.length; + for (; i2 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet2.indexOf(str.charAt(i2++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i2 >= 0) { + k4 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y4 = new BigNumber3(baseIn); + x3 = y4.pow(str.length - i2); + POW_PRECISION = k4; + y4.c = toBaseOut( + toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), + 10, + baseOut, + decimal + ); + y4.e = y4.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); + e2 = k4 = xc.length; + for (; xc[--k4] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet2.charAt(0); + if (i2 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign2; + x3 = div(x3, y4, dp, rm, baseOut); + xc = x3.c; + r = x3.r; + e2 = x3.e; + } + d3 = e2 + dp + 1; + i2 = xc[d3]; + k4 = baseOut / 2; + r = r || d3 < 0 || xc[d3 + 1] != null; + r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (d3 < 1 || !xc[0]) { + str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); + } else { + xc.length = d3; + if (r) { + for (--baseOut; ++xc[--d3] > baseOut; ) { + xc[d3] = 0; + if (!d3) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k4 = xc.length; !xc[--k4]; ) + ; + for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) + ; + str = toFixedPoint2(str, e2, alphabet2.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x3, k4, base3) { + var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; + for (x3 = x3.slice(); i2--; ) { + xlo = x3[i2] % SQRT_BASE2; + xhi = x3[i2] / SQRT_BASE2 | 0; + m3 = khi * xlo + xhi * klo; + temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; + carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; + x3[i2] = temp % base3; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare4(a3, b4, aL, bL) { + var i2, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i2 = cmp = 0; i2 < aL; i2++) { + if (a3[i2] != b4[i2]) { + cmp = a3[i2] > b4[i2] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a3, b4, aL, base3) { + var i2 = 0; + for (; aL--; ) { + a3[aL] -= i2; + i2 = a3[aL] < b4[aL] ? 1 : 0; + a3[aL] = i2 * base3 + a3[aL] - b4[aL]; + } + for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) + ; + } + return function(x3, y4, dp, rm, base3) { + var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber3( + // Return NaN if either NaN, or both Infinity or 0. + !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber3(s2); + qc = q2.c = []; + e2 = x3.e - y4.e; + s2 = dp + e2 + 1; + if (!base3) { + base3 = BASE2; + e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); + s2 = s2 / LOG_BASE2 | 0; + } + for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) + ; + if (yc[i2] > (xc[i2] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i2 = 0; + s2 += 2; + n3 = mathfloor2(base3 / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base3); + xc = multiply(xc, n3, base3); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base3 / 2) + yc0++; + do { + n3 = 0; + cmp = compare4(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base3 + (rem[1] || 0); + n3 = mathfloor2(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base3) + n3 = base3 - 1; + prod = multiply(yc, n3, base3); + prodL = prod.length; + remL = rem.length; + while (compare4(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base3); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base3); + remL = rem.length; + if (cmp == -1) { + while (compare4(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base3); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i2++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base3 == BASE2) { + for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) + ; + round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format(n3, i2, rm, id) { + var c0, e2, ne, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne = n3.e; + if (i2 == null) { + str = coeffToString2(n3.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); + } else { + n3 = round(new BigNumber3(n3), i2, rm); + e2 = n3.e; + str = coeffToString2(n3.c); + len = str.length; + if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { + for (; len < i2; str += "0", len++) + ; + str = toExponential2(str, e2); + } else { + i2 -= ne; + str = toFixedPoint2(str, e2, "0"); + if (e2 + 1 > len) { + if (--i2 > 0) + for (str += "."; i2--; str += "0") + ; + } else { + i2 += e2 - len; + if (i2 > 0) { + if (e2 + 1 == len) + str += "."; + for (; i2--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, method) { + var n3, i2 = 1, m3 = new BigNumber3(args[0]); + for (; i2 < args.length; i2++) { + n3 = new BigNumber3(args[i2]); + if (!n3.s) { + m3 = n3; + break; + } else if (method.call(m3, n3)) { + m3 = n3; + } + } + return m3; + } + function normalise(n3, c4, e2) { + var i2 = 1, j2 = c4.length; + for (; !c4[--j2]; c4.pop()) + ; + for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) + ; + if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e2 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e2; + n3.c = c4; + } + return n3; + } + parseNumeric = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b4) { + var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m3, p1, p22) { + base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; + return !b4 || b4 == base3 ? p1 : m3; + }); + if (b4) { + base3 = b4; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber3(s2, base3); + } + if (BigNumber3.DEBUG) { + throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm, r) { + var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; + if (xc) { + out: { + for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) + ; + i2 = sd - d3; + if (i2 < 0) { + i2 += LOG_BASE2; + j2 = sd; + n3 = xc[ni = 0]; + rd = n3 / pows10[d3 - j2 - 1] % 10 | 0; + } else { + ni = mathceil2((i2 + 1) / LOG_BASE2); + if (ni >= xc.length) { + if (r) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d3 = 1; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + 1; + } else { + break out; + } + } else { + n3 = k4 = xc[ni]; + for (d3 = 1; k4 >= 10; k4 /= 10, d3++) + ; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + d3; + rd = j2 < 0 ? 0 : n3 / pows10[d3 - j2 - 1] % 10 | 0; + } + } + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i2 == 0) { + xc.length = ni; + k4 = 1; + ni--; + } else { + xc.length = ni + 1; + k4 = pows10[LOG_BASE2 - i2]; + xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; + } + if (r) { + for (; ; ) { + if (ni == 0) { + for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) + ; + j2 = xc[0] += k4; + for (k4 = 1; j2 >= 10; j2 /= 10, k4++) + ; + if (i2 != k4) { + x3.e++; + if (xc[0] == BASE2) + xc[0] = 1; + } + break; + } else { + xc[ni] += k4; + if (xc[ni] != BASE2) + break; + xc[ni--] = 0; + k4 = 1; + } + } + } + for (i2 = xc.length; xc[--i2] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n3) { + var str, e2 = n3.e; + if (e2 === null) + return n3.toString(); + str = coeffToString2(n3.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber3(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c4, n3, v2, x3 = this; + if (dp != null) { + intCheck2(dp, 0, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), dp + x3.e + 1, rm); + } + if (!(c4 = x3.c)) + return null; + n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; + if (v2 = c4[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m3) { + var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; + n3 = new BigNumber3(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); + } + if (m3 != null) + m3 = new BigNumber3(m3); + nIsBig = n3.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { + y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? 2 - isOdd2(n3) : +valueOf(n3))); + return m3 ? y4.mod(m3) : y4; + } + nIsNeg = n3.s < 0; + if (m3) { + if (m3.c ? !m3.c[0] : !m3.s) + return new BigNumber3(NaN); + isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); + if (isModExp) + x3 = x3.mod(m3); + } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { + k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; + if (x3.e > -1) + k4 = 1 / k4; + return new BigNumber3(nIsNeg ? 1 / k4 : k4); + } else if (POW_PRECISION) { + k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); + } + if (nIsBig) { + half = new BigNumber3(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd2(n3); + } else { + i2 = Math.abs(+valueOf(n3)); + nIsOdd = i2 % 2; + } + y4 = new BigNumber3(ONE); + for (; ; ) { + if (nIsOdd) { + y4 = y4.times(x3); + if (!y4.c) + break; + if (k4) { + if (y4.c.length > k4) + y4.c.length = k4; + } else if (isModExp) { + y4 = y4.mod(m3); + } + } + if (i2) { + i2 = mathfloor2(i2 / 2); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd2(n3); + } else { + i2 = +valueOf(n3); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } + } + x3 = x3.times(x3); + if (k4) { + if (x3.c && x3.c.length > k4) + x3.c.length = k4; + } else if (isModExp) { + x3 = x3.mod(m3); + } + } + if (isModExp) + return y4; + if (nIsNeg) + y4 = ONE.div(y4); + return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber3(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y4, b4) { + var i2, j2, t, xLTy, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.plus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (xLTy = a3 < 0) { + a3 = -a3; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); + for (b4 = a3; b4--; t.push(0)) + ; + t.reverse(); + } else { + j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; + for (a3 = b4 = 0; b4 < j2; b4++) { + if (xc[b4] != yc[b4]) { + xLTy = xc[b4] < yc[b4]; + break; + } + } + } + if (xLTy) + t = xc, xc = yc, yc = t, y4.s = -y4.s; + b4 = (j2 = yc.length) - (i2 = xc.length); + if (b4 > 0) + for (; b4--; xc[i2++] = 0) + ; + b4 = BASE2 - 1; + for (; j2 > a3; ) { + if (xc[--j2] < yc[j2]) { + for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) + ; + --xc[i2]; + xc[j2] += BASE2; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y4.s = ROUNDING_MODE == 3 ? -1 : 1; + y4.c = [y4.e = 0]; + return y4; + } + return normalise(y4, xc, ye); + }; + P2.modulo = P2.mod = function(y4, b4) { + var q2, s2, x3 = this; + y4 = new BigNumber3(y4, b4); + if (!x3.c || !y4.s || y4.c && !y4.c[0]) { + return new BigNumber3(NaN); + } else if (!y4.c || x3.c && !x3.c[0]) { + return new BigNumber3(x3); + } + if (MODULO_MODE == 9) { + s2 = y4.s; + y4.s = 1; + q2 = div(x3, y4, 0, 3); + y4.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y4, 0, MODULO_MODE); + } + y4 = x3.minus(q2.times(y4)); + if (!y4.c[0] && MODULO_MODE == 1) + y4.s = x3.s; + return y4; + }; + P2.multipliedBy = P2.times = function(y4, b4) { + var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y4.c = y4.e = y4.s = null; + } else { + y4.s *= x3.s; + if (!xc || !yc) { + y4.c = y4.e = null; + } else { + y4.c = [0]; + y4.e = 0; + } + } + return y4; + } + e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); + y4.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) + zc = xc, xc = yc, yc = zc, i2 = xcL, xcL = ycL, ycL = i2; + for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) + ; + base3 = BASE2; + sqrtBase = SQRT_BASE2; + for (i2 = ycL; --i2 >= 0; ) { + c4 = 0; + ylo = yc[i2] % sqrtBase; + yhi = yc[i2] / sqrtBase | 0; + for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { + xlo = xc[--k4] % sqrtBase; + xhi = xc[k4] / sqrtBase | 0; + m3 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; + c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base3; + } + zc[j2] = c4; + } + if (c4) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y4, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber3(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y4, b4) { + var t, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.minus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber3(a3 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (a3 > 0) { + ye = xe; + t = yc; + } else { + a3 = -a3; + t = xc; + } + t.reverse(); + for (; a3--; t.push(0)) + ; + t.reverse(); + } + a3 = xc.length; + b4 = yc.length; + if (a3 - b4 < 0) + t = yc, yc = xc, xc = t, b4 = a3; + for (a3 = 0; b4; ) { + a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; + xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; + } + if (a3) { + xc = [a3].concat(xc); + ++ye; + } + return normalise(y4, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm) { + var c4, n3, v2, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck2(sd, 1, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), sd, rm); + } + if (!(c4 = x3.c)) + return null; + v2 = c4.length - 1; + n3 = v2 * LOG_BASE2 + 1; + if (v2 = c4[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x3.e + 1 > n3) + n3 = x3.e + 1; + return n3; + }; + P2.shiftedBy = function(k4) { + intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); + return this.times("1e" + k4); + }; + P2.squareRoot = P2.sqrt = function() { + var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); + if (s2 !== 1 || !c4 || !c4[0]) { + return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString2(c4); + if ((n3.length + e2) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e2; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; + } + r = new BigNumber3(n3); + } else { + r = new BigNumber3(s2 + ""); + } + if (r.c[0]) { + e2 = r.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t = r; + r = half.times(t.plus(div(x3, t, dp, 1))); + if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { + if (r.e < e2) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + if (t.times(t).eq(x3)) { + r = t; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m3 = !r.times(r).eq(x3); + } + break; + } + } + } + } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp++; + } + return format(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format2) { + var str, x3 = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError2 + "Argument not an object: " + format2); + } + str = x3.toFixed(dp, rm); + if (x3.c) { + var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) + i2 = g1, g1 = g22, g22 = i2, len -= i2; + if (g1 > 0 && len > 0) { + i2 = len % g1 || g1; + intPart = intDigits.substr(0, i2); + for (; i2 < len; i2 += g1) + intPart += groupSeparator + intDigits.substr(i2, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i2); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format2.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P2.toFraction = function(md) { + var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; + if (md != null) { + n3 = new BigNumber3(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber3(x3); + d3 = new BigNumber3(ONE); + n1 = d0 = new BigNumber3(ONE); + d1 = n0 = new BigNumber3(ONE); + s2 = coeffToString2(xc); + e2 = d3.e = s2.length - x3.e - 1; + d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; + md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber3(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d3, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d3 = n3.minus(q2.times(d22 = d3)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( + div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck2(sd, 1, MAX2); + return format(this, sd, rm, 2); + }; + P2.toString = function(b4) { + var str, n3 = this, s2 = n3.s, e2 = n3.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b4 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); + } else if (b4 === 10) { + n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + if (configObject != null) + BigNumber3.set(configObject); + return BigNumber3; + } + function bitFloor2(n3) { + var i2 = n3 | 0; + return n3 > 0 || n3 === i2 ? i2 : i2 - 1; + } + function coeffToString2(a3) { + var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; + for (; i2 < j2; ) { + s2 = a3[i2++] + ""; + z3 = LOG_BASE2 - s2.length; + for (; z3--; s2 = "0" + s2) + ; + r += s2; + } + for (j2 = r.length; r.charCodeAt(--j2) === 48; ) + ; + return r.slice(0, j2 + 1 || 1); + } + function compare3(x3, y4) { + var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; + if (!i2 || !j2) + return null; + a3 = xc && !xc[0]; + b4 = yc && !yc[0]; + if (a3 || b4) + return a3 ? b4 ? 0 : -j2 : i2; + if (i2 != j2) + return i2; + a3 = i2 < 0; + b4 = k4 == l4; + if (!xc || !yc) + return b4 ? 0 : !xc ^ a3 ? 1 : -1; + if (!b4) + return k4 > l4 ^ a3 ? 1 : -1; + j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; + for (i2 = 0; i2 < j2; i2++) + if (xc[i2] != yc[i2]) + return xc[i2] > yc[i2] ^ a3 ? 1 : -1; + return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; + } + function intCheck2(n3, min, max, name2) { + if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { + throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } + } + function isOdd2(n3) { + var k4 = n3.c.length - 1; + return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; + } + function toExponential2(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + function toFixedPoint2(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + "."; ++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len; --e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; + } + BigNumber2 = clone2(); + BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; + if (typeof define == "function" && define.amd) { + define(function() { + return BigNumber2; + }); + } else if (typeof module2 != "undefined" && module2.exports) { + module2.exports = BigNumber2; + } else { + if (!globalObject) { + globalObject = typeof self != "undefined" && self ? self : window; + } + globalObject.BigNumber = BigNumber2; + } + })(exports2); + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/primitives.js +var require_primitives = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/primitives.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = exports2.Nonce = exports2.Address = void 0; + var bech32 = __importStar2(require_bech32()); + var HRP = "erd"; + var Address5 = class _Address { + constructor(value) { + this.value = value; + } + static fromPubkey(pubkey) { + let words = bech32.toWords(pubkey); + let address = bech32.encode(HRP, words); + return new _Address(address); + } + bech32() { + return this.value; + } + toString() { + return this.bech32(); + } + }; + exports2.Address = Address5; + var Nonce = class { + constructor(value) { + this.value = value; + } + valueOf() { + return this.value; + } + hex() { + return numberToPaddedHex(this.value); + } + }; + exports2.Nonce = Nonce; + function numberToPaddedHex(value) { + let hex = value.toString(16); + return zeroPadStringIfOddLength(hex); + } + exports2.numberToPaddedHex = numberToPaddedHex; + function isPaddedHex(input) { + input = input || ""; + let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); + return input.toUpperCase() == decodedThenEncoded.toUpperCase(); + } + exports2.isPaddedHex = isPaddedHex; + function zeroPadStringIfOddLength(input) { + input = input || ""; + if (input.length % 2 == 1) { + return "0" + input; + } + return input; + } + exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/constants.js +var require_constants3 = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/constants.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EsdtContractAddress = exports2.MaxUint64AsBigNumber = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber2()); + var primitives_1 = require_primitives(); + exports2.MaxUint64AsBigNumber = new bignumber_js_1.default("18446744073709551615"); + exports2.EsdtContractAddress = new primitives_1.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js +var require_contractQueryResponse = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractQueryResponse = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber2()); + var constants_1 = require_constants3(); + var ContractQueryResponse3 = class _ContractQueryResponse { + constructor(init) { + this.returnData = (init === null || init === void 0 ? void 0 : init.returnData) || []; + this.returnCode = (init === null || init === void 0 ? void 0 : init.returnCode) || ""; + this.returnMessage = (init === null || init === void 0 ? void 0 : init.returnMessage) || ""; + this.gasUsed = (init === null || init === void 0 ? void 0 : init.gasUsed) || 0; + } + /** + * Constructs a QueryResponse object from a HTTP response (as returned by the provider). + */ + static fromHttpResponse(payload) { + let returnData = payload["returnData"] || payload["ReturnData"]; + let returnCode = payload["returnCode"] || payload["ReturnCode"]; + let returnMessage = payload["returnMessage"] || payload["ReturnMessage"]; + let gasRemaining = new bignumber_js_1.default(payload["gasRemaining"] || payload["GasRemaining"] || 0); + let gasUsed = constants_1.MaxUint64AsBigNumber.minus(gasRemaining).toNumber(); + return new _ContractQueryResponse({ + returnData, + returnCode, + returnMessage, + gasUsed + }); + } + getReturnDataParts() { + return this.returnData.map((item) => import_buffer.Buffer.from(item || "", "base64")); + } + /** + * Converts the object to a pretty, plain JavaScript object. + */ + toJSON() { + return { + returnData: this.returnData, + returnCode: this.returnCode, + returnMessage: this.returnMessage, + gasUsed: this.gasUsed.valueOf() + }; + } + }; + exports2.ContractQueryResponse = ContractQueryResponse3; + } +}); + +// node_modules/@multiversx/sdk-extension-provider/out/errors.js +var require_errors2 = __commonJS({ + "node_modules/@multiversx/sdk-extension-provider/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrAccountNotConnected = exports2.ErrCannotSignSingleTransaction = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + }; + exports2.Err = Err; + var ErrCannotSignSingleTransaction = class extends Err { + constructor() { + super("Cannot sign single transaction."); + } + }; + exports2.ErrCannotSignSingleTransaction = ErrCannotSignSingleTransaction; + var ErrAccountNotConnected = class extends Err { + constructor() { + super("Account is not connected."); + } + }; + exports2.ErrAccountNotConnected = ErrAccountNotConnected; + } +}); + +// node_modules/@multiversx/sdk-extension-provider/out/operation.js +var require_operation = __commonJS({ + "node_modules/@multiversx/sdk-extension-provider/out/operation.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Operation = void 0; + var Operation; + (function(Operation2) { + Operation2["Connect"] = "connect"; + Operation2["Logout"] = "logout"; + Operation2["SignTransactions"] = "signTransactions"; + Operation2["SignMessage"] = "signMessage"; + Operation2["CancelAction"] = "cancelAction"; + })(Operation = exports2.Operation || (exports2.Operation = {})); + } +}); + +// node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js +var require_extensionProvider = __commonJS({ + "node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ExtensionProvider = void 0; + var transaction_1 = require_transaction(); + var errors_1 = require_errors2(); + var operation_1 = require_operation(); + var ExtensionProvider3 = class _ExtensionProvider { + constructor() { + this.account = { address: "" }; + this.initialized = false; + if (_ExtensionProvider._instance) { + throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new."); + } + _ExtensionProvider._instance = this; + } + static getInstance() { + return _ExtensionProvider._instance; + } + setAddress(address) { + this.account.address = address; + return _ExtensionProvider._instance; + } + init() { + return __awaiter2(this, void 0, void 0, function* () { + if (window && window.elrondWallet) { + this.initialized = true; + } + return this.initialized; + }); + } + login(options = {}) { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.initialized) { + throw new Error("Extension provider is not initialised, call init() first"); + } + const { token } = options; + const data = token ? token : ""; + yield this.startBgrMsgChannel(operation_1.Operation.Connect, data); + return this.account.address; + }); + } + logout() { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.initialized) { + throw new Error("Extension provider is not initialised, call init() first"); + } + try { + yield this.startBgrMsgChannel(operation_1.Operation.Logout, this.account.address); + this.disconnect(); + } catch (error) { + console.warn("Extension origin url is already cleared!", error); + } + return true; + }); + } + disconnect() { + this.account = { address: "" }; + } + getAddress() { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.initialized) { + throw new Error("Extension provider is not initialised, call init() first"); + } + return this.account ? this.account.address : ""; + }); + } + isInitialized() { + return this.initialized; + } + // TODO: In V3, this will not be an async function anymore. + isConnected() { + return __awaiter2(this, void 0, void 0, function* () { + return Boolean(this.account.address); + }); + } + signTransaction(transaction) { + return __awaiter2(this, void 0, void 0, function* () { + this.ensureConnected(); + const signedTransactions = yield this.signTransactions([transaction]); + if (signedTransactions.length != 1) { + throw new errors_1.ErrCannotSignSingleTransaction(); + } + return signedTransactions[0]; + }); + } + ensureConnected() { + if (!this.account.address) { + throw new errors_1.ErrAccountNotConnected(); + } + } + signTransactions(transactions) { + return __awaiter2(this, void 0, void 0, function* () { + this.ensureConnected(); + const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignTransactions, { + from: this.account.address, + transactions: transactions.map((transaction) => transaction.toPlainObject()) + }); + try { + const transactionsResponse = extensionResponse.map((transaction) => transaction_1.Transaction.fromPlainObject(transaction)); + return transactionsResponse; + } catch (error) { + throw new Error(`Transaction canceled: ${error.message}.`); + } + }); + } + signMessage(message) { + return __awaiter2(this, void 0, void 0, function* () { + this.ensureConnected(); + const data = { + account: this.account.address, + message: message.message.toString() + }; + const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignMessage, data); + const signatureHex = extensionResponse.signature; + const signature = import_buffer.Buffer.from(signatureHex, "hex"); + message.applySignature(signature); + return message; + }); + } + cancelAction() { + return this.startBgrMsgChannel(operation_1.Operation.CancelAction, {}); + } + startBgrMsgChannel(operation, connectData) { + return new Promise((resolve) => { + window.postMessage({ + target: "erdw-inpage", + type: operation, + data: connectData + }, window.origin); + const eventHandler = (event) => { + if (event.isTrusted && event.data.target === "erdw-contentScript") { + if (event.data.type === "connectResponse") { + if (event.data.data && Boolean(event.data.data.address)) { + this.account = event.data.data; + } + window.removeEventListener("message", eventHandler); + resolve(event.data.data); + } else { + window.removeEventListener("message", eventHandler); + resolve(event.data.data); + } + } + }; + window.addEventListener("message", eventHandler, false); + }); + } + }; + exports2.ExtensionProvider = ExtensionProvider3; + ExtensionProvider3._instance = new ExtensionProvider3(); + } +}); + +// node_modules/destr/dist/index.mjs +function jsonParseTransform(key, value) { + if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) { + warnKeyDropped(key); + return; + } + return value; +} +function warnKeyDropped(key) { + console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`); +} +function destr(value, options = {}) { + if (typeof value !== "string") { + return value; + } + const _value = value.trim(); + if ( + // eslint-disable-next-line unicorn/prefer-at + value[0] === '"' && value.endsWith('"') && !value.includes("\\") + ) { + return _value.slice(1, -1); + } + if (_value.length <= 9) { + const _lval = _value.toLowerCase(); + if (_lval === "true") { + return true; + } + if (_lval === "false") { + return false; + } + if (_lval === "undefined") { + return void 0; + } + if (_lval === "null") { + return null; + } + if (_lval === "nan") { + return Number.NaN; + } + if (_lval === "infinity") { + return Number.POSITIVE_INFINITY; + } + if (_lval === "-infinity") { + return Number.NEGATIVE_INFINITY; + } + } + if (!JsonSigRx.test(value)) { + if (options.strict) { + throw new SyntaxError("[destr] Invalid JSON"); + } + return value; + } + try { + if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) { + if (options.strict) { + throw new Error("[destr] Possible prototype pollution"); + } + return JSON.parse(value, jsonParseTransform); + } + return JSON.parse(value); + } catch (error) { + if (options.strict) { + throw error; + } + return value; + } +} +var suspectProtoRx, suspectConstructorRx, JsonSigRx; +var init_dist = __esm({ + "node_modules/destr/dist/index.mjs"() { + init_shim(); + suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/; + suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; + JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; + } +}); + +// node_modules/unstorage/dist/shared/unstorage.8581f561.mjs +function wrapToPromise(value) { + if (!value || typeof value.then !== "function") { + return Promise.resolve(value); + } + return value; +} +function asyncCall(function_, ...arguments_) { + try { + return wrapToPromise(function_(...arguments_)); + } catch (error) { + return Promise.reject(error); + } +} +function isPrimitive(value) { + const type = typeof value; + return value === null || type !== "object" && type !== "function"; +} +function isPureObject(value) { + const proto = Object.getPrototypeOf(value); + return !proto || proto.isPrototypeOf(Object); +} +function stringify(value) { + if (isPrimitive(value)) { + return String(value); + } + if (isPureObject(value) || Array.isArray(value)) { + return JSON.stringify(value); + } + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + throw new Error("[unstorage] Cannot stringify value!"); +} +function checkBufferSupport() { + if (typeof import_buffer.Buffer === void 0) { + throw new TypeError("[unstorage] Buffer is not supported!"); + } +} +function serializeRaw(value) { + if (typeof value === "string") { + return value; + } + checkBufferSupport(); + const base642 = import_buffer.Buffer.from(value).toString("base64"); + return BASE64_PREFIX + base642; +} +function deserializeRaw(value) { + if (typeof value !== "string") { + return value; + } + if (!value.startsWith(BASE64_PREFIX)) { + return value; + } + checkBufferSupport(); + return import_buffer.Buffer.from(value.slice(BASE64_PREFIX.length), "base64"); +} +function normalizeKey(key) { + if (!key) { + return ""; + } + return key.split("?")[0].replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, ""); +} +function joinKeys(...keys2) { + return normalizeKey(keys2.join(":")); +} +function normalizeBaseKey(base3) { + base3 = normalizeKey(base3); + return base3 ? base3 + ":" : ""; +} +var BASE64_PREFIX; +var init_unstorage_8581f561 = __esm({ + "node_modules/unstorage/dist/shared/unstorage.8581f561.mjs"() { + init_shim(); + BASE64_PREFIX = "base64:"; + } +}); + +// node_modules/unstorage/dist/index.mjs +function defineDriver(factory) { + return factory; +} +function createStorage(options = {}) { + const context = { + mounts: { "": options.driver || memory() }, + mountpoints: [""], + watching: false, + watchListeners: [], + unwatch: {} + }; + const getMount = (key) => { + for (const base3 of context.mountpoints) { + if (key.startsWith(base3)) { + return { + base: base3, + relativeKey: key.slice(base3.length), + driver: context.mounts[base3] + }; + } + } + return { + base: "", + relativeKey: key, + driver: context.mounts[""] + }; + }; + const getMounts = (base3, includeParent) => { + return context.mountpoints.filter( + (mountpoint) => mountpoint.startsWith(base3) || includeParent && base3.startsWith(mountpoint) + ).map((mountpoint) => ({ + relativeBase: base3.length > mountpoint.length ? base3.slice(mountpoint.length) : void 0, + mountpoint, + driver: context.mounts[mountpoint] + })); + }; + const onChange = (event, key) => { + if (!context.watching) { + return; + } + key = normalizeKey(key); + for (const listener of context.watchListeners) { + listener(event, key); + } + }; + const startWatch = async () => { + if (context.watching) { + return; + } + context.watching = true; + for (const mountpoint in context.mounts) { + context.unwatch[mountpoint] = await watch( + context.mounts[mountpoint], + onChange, + mountpoint + ); + } + }; + const stopWatch = async () => { + if (!context.watching) { + return; + } + for (const mountpoint in context.unwatch) { + await context.unwatch[mountpoint](); + } + context.unwatch = {}; + context.watching = false; + }; + const runBatch = (items, commonOptions, cb) => { + const batches = /* @__PURE__ */ new Map(); + const getBatch = (mount) => { + let batch = batches.get(mount.base); + if (!batch) { + batch = { + driver: mount.driver, + base: mount.base, + items: [] + }; + batches.set(mount.base, batch); + } + return batch; + }; + for (const item of items) { + const isStringItem = typeof item === "string"; + const key = normalizeKey(isStringItem ? item : item.key); + const value = isStringItem ? void 0 : item.value; + const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options }; + const mount = getMount(key); + getBatch(mount).items.push({ + key, + value, + relativeKey: mount.relativeKey, + options: options2 + }); + } + return Promise.all([...batches.values()].map((batch) => cb(batch))).then( + (r) => r.flat() + ); + }; + const storage = { + // Item + hasItem(key, opts = {}) { + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + return asyncCall(driver.hasItem, relativeKey, opts); + }, + getItem(key, opts = {}) { + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + return asyncCall(driver.getItem, relativeKey, opts).then( + (value) => destr(value) + ); + }, + getItems(items, commonOptions) { + return runBatch(items, commonOptions, (batch) => { + if (batch.driver.getItems) { + return asyncCall( + batch.driver.getItems, + batch.items.map((item) => ({ + key: item.relativeKey, + options: item.options + })), + commonOptions + ).then( + (r) => r.map((item) => ({ + key: joinKeys(batch.base, item.key), + value: destr(item.value) + })) + ); + } + return Promise.all( + batch.items.map((item) => { + return asyncCall( + batch.driver.getItem, + item.relativeKey, + item.options + ).then((value) => ({ + key: item.key, + value: destr(value) + })); + }) + ); + }); + }, + getItemRaw(key, opts = {}) { + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (driver.getItemRaw) { + return asyncCall(driver.getItemRaw, relativeKey, opts); + } + return asyncCall(driver.getItem, relativeKey, opts).then( + (value) => deserializeRaw(value) + ); + }, + async setItem(key, value, opts = {}) { + if (value === void 0) { + return storage.removeItem(key); + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (!driver.setItem) { + return; + } + await asyncCall(driver.setItem, relativeKey, stringify(value), opts); + if (!driver.watch) { + onChange("update", key); + } + }, + async setItems(items, commonOptions) { + await runBatch(items, commonOptions, async (batch) => { + if (batch.driver.setItems) { + return asyncCall( + batch.driver.setItems, + batch.items.map((item) => ({ + key: item.relativeKey, + value: stringify(item.value), + options: item.options + })), + commonOptions + ); + } + if (!batch.driver.setItem) { + return; + } + await Promise.all( + batch.items.map((item) => { + return asyncCall( + batch.driver.setItem, + item.relativeKey, + stringify(item.value), + item.options + ); + }) + ); + }); + }, + async setItemRaw(key, value, opts = {}) { + if (value === void 0) { + return storage.removeItem(key, opts); + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (driver.setItemRaw) { + await asyncCall(driver.setItemRaw, relativeKey, value, opts); + } else if (driver.setItem) { + await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts); + } else { + return; + } + if (!driver.watch) { + onChange("update", key); + } + }, + async removeItem(key, opts = {}) { + if (typeof opts === "boolean") { + opts = { removeMeta: opts }; + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (!driver.removeItem) { + return; + } + await asyncCall(driver.removeItem, relativeKey, opts); + if (opts.removeMeta || opts.removeMata) { + await asyncCall(driver.removeItem, relativeKey + "$", opts); + } + if (!driver.watch) { + onChange("remove", key); + } + }, + // Meta + async getMeta(key, opts = {}) { + if (typeof opts === "boolean") { + opts = { nativeOnly: opts }; + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + const meta = /* @__PURE__ */ Object.create(null); + if (driver.getMeta) { + Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts)); + } + if (!opts.nativeOnly) { + const value = await asyncCall( + driver.getItem, + relativeKey + "$", + opts + ).then((value_) => destr(value_)); + if (value && typeof value === "object") { + if (typeof value.atime === "string") { + value.atime = new Date(value.atime); + } + if (typeof value.mtime === "string") { + value.mtime = new Date(value.mtime); + } + Object.assign(meta, value); + } + } + return meta; + }, + setMeta(key, value, opts = {}) { + return this.setItem(key + "$", value, opts); + }, + removeMeta(key, opts = {}) { + return this.removeItem(key + "$", opts); + }, + // Keys + async getKeys(base3, opts = {}) { + base3 = normalizeBaseKey(base3); + const mounts = getMounts(base3, true); + let maskedMounts = []; + const allKeys = []; + for (const mount of mounts) { + const rawKeys = await asyncCall( + mount.driver.getKeys, + mount.relativeBase, + opts + ); + const keys2 = rawKeys.map((key) => mount.mountpoint + normalizeKey(key)).filter((key) => !maskedMounts.some((p3) => key.startsWith(p3))); + allKeys.push(...keys2); + maskedMounts = [ + mount.mountpoint, + ...maskedMounts.filter((p3) => !p3.startsWith(mount.mountpoint)) + ]; + } + return base3 ? allKeys.filter((key) => key.startsWith(base3) && !key.endsWith("$")) : allKeys.filter((key) => !key.endsWith("$")); + }, + // Utils + async clear(base3, opts = {}) { + base3 = normalizeBaseKey(base3); + await Promise.all( + getMounts(base3, false).map(async (m3) => { + if (m3.driver.clear) { + return asyncCall(m3.driver.clear, m3.relativeBase, opts); + } + if (m3.driver.removeItem) { + const keys2 = await m3.driver.getKeys(m3.relativeBase || "", opts); + return Promise.all( + keys2.map((key) => m3.driver.removeItem(key, opts)) + ); + } + }) + ); + }, + async dispose() { + await Promise.all( + Object.values(context.mounts).map((driver) => dispose(driver)) + ); + }, + async watch(callback) { + await startWatch(); + context.watchListeners.push(callback); + return async () => { + context.watchListeners = context.watchListeners.filter( + (listener) => listener !== callback + ); + if (context.watchListeners.length === 0) { + await stopWatch(); + } + }; + }, + async unwatch() { + context.watchListeners = []; + await stopWatch(); + }, + // Mount + mount(base3, driver) { + base3 = normalizeBaseKey(base3); + if (base3 && context.mounts[base3]) { + throw new Error(`already mounted at ${base3}`); + } + if (base3) { + context.mountpoints.push(base3); + context.mountpoints.sort((a3, b4) => b4.length - a3.length); + } + context.mounts[base3] = driver; + if (context.watching) { + Promise.resolve(watch(driver, onChange, base3)).then((unwatcher) => { + context.unwatch[base3] = unwatcher; + }).catch(console.error); + } + return storage; + }, + async unmount(base3, _dispose = true) { + base3 = normalizeBaseKey(base3); + if (!base3 || !context.mounts[base3]) { + return; + } + if (context.watching && base3 in context.unwatch) { + context.unwatch[base3](); + delete context.unwatch[base3]; + } + if (_dispose) { + await dispose(context.mounts[base3]); + } + context.mountpoints = context.mountpoints.filter((key) => key !== base3); + delete context.mounts[base3]; + }, + getMount(key = "") { + key = normalizeKey(key) + ":"; + const m3 = getMount(key); + return { + driver: m3.driver, + base: m3.base + }; + }, + getMounts(base3 = "", opts = {}) { + base3 = normalizeKey(base3); + const mounts = getMounts(base3, opts.parents); + return mounts.map((m3) => ({ + driver: m3.driver, + base: m3.mountpoint + })); + } + }; + return storage; +} +function watch(driver, onChange, base3) { + return driver.watch ? driver.watch((event, key) => onChange(event, base3 + key)) : () => { + }; +} +async function dispose(driver) { + if (typeof driver.dispose === "function") { + await asyncCall(driver.dispose); + } +} +var DRIVER_NAME, memory; +var init_dist2 = __esm({ + "node_modules/unstorage/dist/index.mjs"() { + init_shim(); + init_dist(); + init_unstorage_8581f561(); + DRIVER_NAME = "memory"; + memory = defineDriver(() => { + const data = /* @__PURE__ */ new Map(); + return { + name: DRIVER_NAME, + options: {}, + hasItem(key) { + return data.has(key); + }, + getItem(key) { + return data.get(key) ?? null; + }, + getItemRaw(key) { + return data.get(key) ?? null; + }, + setItem(key, value) { + data.set(key, value); + }, + setItemRaw(key, value) { + data.set(key, value); + }, + removeItem(key) { + data.delete(key); + }, + getKeys() { + return Array.from(data.keys()); + }, + clear() { + data.clear(); + }, + dispose() { + data.clear(); + } + }; + }); + } +}); + +// node_modules/idb-keyval/dist/index.js +function promisifyRequest(request) { + return new Promise((resolve, reject) => { + request.oncomplete = request.onsuccess = () => resolve(request.result); + request.onabort = request.onerror = () => reject(request.error); + }); +} +function createStore(dbName, storeName) { + const request = indexedDB.open(dbName); + request.onupgradeneeded = () => request.result.createObjectStore(storeName); + const dbp = promisifyRequest(request); + return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName))); +} +function defaultGetStore() { + if (!defaultGetStoreFunc) { + defaultGetStoreFunc = createStore("keyval-store", "keyval"); + } + return defaultGetStoreFunc; +} +function get(key, customStore = defaultGetStore()) { + return customStore("readonly", (store) => promisifyRequest(store.get(key))); +} +function set(key, value, customStore = defaultGetStore()) { + return customStore("readwrite", (store) => { + store.put(value, key); + return promisifyRequest(store.transaction); + }); +} +function del(key, customStore = defaultGetStore()) { + return customStore("readwrite", (store) => { + store.delete(key); + return promisifyRequest(store.transaction); + }); +} +function clear(customStore = defaultGetStore()) { + return customStore("readwrite", (store) => { + store.clear(); + return promisifyRequest(store.transaction); + }); +} +function eachCursor(store, callback) { + store.openCursor().onsuccess = function() { + if (!this.result) + return; + callback(this.result); + this.result.continue(); + }; + return promisifyRequest(store.transaction); +} +function keys(customStore = defaultGetStore()) { + return customStore("readonly", (store) => { + if (store.getAllKeys) { + return promisifyRequest(store.getAllKeys()); + } + const items = []; + return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items); + }); +} +var defaultGetStoreFunc; +var init_dist3 = __esm({ + "node_modules/idb-keyval/dist/index.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/safe-json/dist/esm/index.js +var esm_exports = {}; +__export(esm_exports, { + safeJsonParse: () => safeJsonParse, + safeJsonStringify: () => safeJsonStringify +}); +function safeJsonParse(value) { + if (typeof value !== "string") { + throw new Error(`Cannot safe json parse value of type ${typeof value}`); + } + try { + return JSONParse(value); + } catch (_a) { + return value; + } +} +function safeJsonStringify(value) { + return typeof value === "string" ? value : JSONStringify(value) || ""; +} +var JSONStringify, JSONParse; +var init_esm = __esm({ + "node_modules/@walletconnect/safe-json/dist/esm/index.js"() { + init_shim(); + JSONStringify = (data) => JSON.stringify(data, (_4, value) => typeof value === "bigint" ? value.toString() + "n" : value); + JSONParse = (json) => { + const numbersBiggerThanMaxInt = /([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g; + const serializedData = json.replace(numbersBiggerThanMaxInt, '$1"$2n"$3'); + return JSON.parse(serializedData, (_4, value) => { + const isCustomFormatBigInt = typeof value === "string" && value.match(/^\d+n$/); + if (isCustomFormatBigInt) + return BigInt(value.substring(0, value.length - 1)); + return value; + }); + }; + } +}); + +// node_modules/@walletconnect/keyvaluestorage/dist/index.es.js +var index_es_exports = {}; +__export(index_es_exports, { + KeyValueStorage: () => h, + default: () => h +}); +function k(i2) { + var t; + return [i2[0], safeJsonParse((t = i2[1]) != null ? t : "")]; +} +var x, z, D, E, _, l, c, K, N, y, O, j, h; +var init_index_es = __esm({ + "node_modules/@walletconnect/keyvaluestorage/dist/index.es.js"() { + init_shim(); + init_dist2(); + init_dist3(); + init_esm(); + x = "idb-keyval"; + z = (i2 = {}) => { + const t = i2.base && i2.base.length > 0 ? `${i2.base}:` : "", e2 = (s2) => t + s2; + let n3; + return i2.dbName && i2.storeName && (n3 = createStore(i2.dbName, i2.storeName)), { name: x, options: i2, async hasItem(s2) { + return !(typeof await get(e2(s2), n3) > "u"); + }, async getItem(s2) { + return await get(e2(s2), n3) ?? null; + }, setItem(s2, a3) { + return set(e2(s2), a3, n3); + }, removeItem(s2) { + return del(e2(s2), n3); + }, getKeys() { + return keys(n3); + }, clear() { + return clear(n3); + } }; + }; + D = "WALLET_CONNECT_V2_INDEXED_DB"; + E = "keyvaluestorage"; + _ = class { + constructor() { + this.indexedDb = createStorage({ driver: z({ dbName: D, storeName: E }) }); + } + async getKeys() { + return this.indexedDb.getKeys(); + } + async getEntries() { + return (await this.indexedDb.getItems(await this.indexedDb.getKeys())).map((t) => [t.key, t.value]); + } + async getItem(t) { + const e2 = await this.indexedDb.getItem(t); + if (e2 !== null) + return e2; + } + async setItem(t, e2) { + await this.indexedDb.setItem(t, safeJsonStringify(e2)); + } + async removeItem(t) { + await this.indexedDb.removeItem(t); + } + }; + l = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; + c = { exports: {} }; + (function() { + let i2; + function t() { + } + i2 = t, i2.prototype.getItem = function(e2) { + return this.hasOwnProperty(e2) ? String(this[e2]) : null; + }, i2.prototype.setItem = function(e2, n3) { + this[e2] = String(n3); + }, i2.prototype.removeItem = function(e2) { + delete this[e2]; + }, i2.prototype.clear = function() { + const e2 = this; + Object.keys(e2).forEach(function(n3) { + e2[n3] = void 0, delete e2[n3]; + }); + }, i2.prototype.key = function(e2) { + return e2 = e2 || 0, Object.keys(this)[e2]; + }, i2.prototype.__defineGetter__("length", function() { + return Object.keys(this).length; + }), typeof l < "u" && l.localStorage ? c.exports = l.localStorage : typeof window < "u" && window.localStorage ? c.exports = window.localStorage : c.exports = new t(); + })(); + K = class { + constructor() { + this.localStorage = c.exports; + } + async getKeys() { + return Object.keys(this.localStorage); + } + async getEntries() { + return Object.entries(this.localStorage).map(k); + } + async getItem(t) { + const e2 = this.localStorage.getItem(t); + if (e2 !== null) + return safeJsonParse(e2); + } + async setItem(t, e2) { + this.localStorage.setItem(t, safeJsonStringify(e2)); + } + async removeItem(t) { + this.localStorage.removeItem(t); + } + }; + N = "wc_storage_version"; + y = 1; + O = async (i2, t, e2) => { + const n3 = N, s2 = await t.getItem(n3); + if (s2 && s2 >= y) { + e2(t); + return; + } + const a3 = await i2.getKeys(); + if (!a3.length) { + e2(t); + return; + } + const m3 = []; + for (; a3.length; ) { + const r = a3.shift(); + if (!r) + continue; + const o2 = r.toLowerCase(); + if (o2.includes("wc@") || o2.includes("walletconnect") || o2.includes("wc_") || o2.includes("wallet_connect")) { + const f4 = await i2.getItem(r); + await t.setItem(r, f4), m3.push(r); + } + } + await t.setItem(n3, y), e2(t), j(i2, m3); + }; + j = async (i2, t) => { + t.length && t.forEach(async (e2) => { + await i2.removeItem(e2); + }); + }; + h = class { + constructor() { + this.initialized = false, this.setInitialized = (e2) => { + this.storage = e2, this.initialized = true; + }; + const t = new K(); + this.storage = t; + try { + const e2 = new _(); + O(t, e2, this.setInitialized); + } catch { + this.initialized = true; + } + } + async getKeys() { + return await this.initialize(), this.storage.getKeys(); + } + async getEntries() { + return await this.initialize(), this.storage.getEntries(); + } + async getItem(t) { + return await this.initialize(), this.storage.getItem(t); + } + async setItem(t, e2) { + return await this.initialize(), this.storage.setItem(t, e2); + } + async removeItem(t) { + return await this.initialize(), this.storage.removeItem(t); + } + async initialize() { + this.initialized || await new Promise((t) => { + const e2 = setInterval(() => { + this.initialized && (clearInterval(e2), t()); + }, 20); + }); + } + }; + } +}); + +// node_modules/tslib/tslib.es6.js +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __read: () => __read, + __rest: () => __rest, + __spread: () => __spread, + __spreadArrays: () => __spreadArrays, + __values: () => __values +}); +function __extends(d3, b4) { + extendStatics(d3, b4); + function __() { + this.constructor = d3; + } + d3.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); +} +function __rest(s2, e2) { + var t = {}; + for (var p3 in s2) + if (Object.prototype.hasOwnProperty.call(s2, p3) && e2.indexOf(p3) < 0) + t[p3] = s2[p3]; + if (s2 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i2 = 0, p3 = Object.getOwnPropertySymbols(s2); i2 < p3.length; i2++) { + if (e2.indexOf(p3[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p3[i2])) + t[p3[i2]] = s2[p3[i2]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c4 = arguments.length, r = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i2 = decorators.length - 1; i2 >= 0; i2--) + if (d3 = decorators[i2]) + r = (c4 < 3 ? d3(r) : c4 > 3 ? d3(target, key, r) : d3(target, key)) || r; + return c4 > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _4 = { label: 0, sent: function() { + if (t[0] & 1) + throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f4, y4, t, g3; + return g3 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() { + return this; + }), g3; + function verb(n3) { + return function(v2) { + return step([n3, v2]); + }; + } + function step(op) { + if (f4) + throw new TypeError("Generator is already executing."); + while (_4) + try { + if (f4 = 1, y4 && (t = op[0] & 2 ? y4["return"] : op[0] ? y4["throw"] || ((t = y4["return"]) && t.call(y4), 0) : y4.next) && !(t = t.call(y4, op[1])).done) + return t; + if (y4 = 0, t) + op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _4.label++; + return { value: op[1], done: false }; + case 5: + _4.label++; + y4 = op[1]; + op = [0]; + continue; + case 7: + op = _4.ops.pop(); + _4.trys.pop(); + continue; + default: + if (!(t = _4.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _4 = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _4.label = op[1]; + break; + } + if (op[0] === 6 && _4.label < t[1]) { + _4.label = t[1]; + t = op; + break; + } + if (t && _4.label < t[2]) { + _4.label = t[2]; + _4.ops.push(op); + break; + } + if (t[2]) + _4.ops.pop(); + _4.trys.pop(); + continue; + } + op = body.call(thisArg, _4); + } catch (e2) { + op = [6, e2]; + y4 = 0; + } finally { + f4 = t = 0; + } + if (op[0] & 5) + throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __createBinding(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; +} +function __exportStar(m3, exports2) { + for (var p3 in m3) + if (p3 !== "default" && !exports2.hasOwnProperty(p3)) + exports2[p3] = m3[p3]; +} +function __values(o2) { + var s2 = typeof Symbol === "function" && Symbol.iterator, m3 = s2 && o2[s2], i2 = 0; + if (m3) + return m3.call(o2); + if (o2 && typeof o2.length === "number") + return { + next: function() { + if (o2 && i2 >= o2.length) + o2 = void 0; + return { value: o2 && o2[i2++], done: !o2 }; + } + }; + throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o2, n3) { + var m3 = typeof Symbol === "function" && o2[Symbol.iterator]; + if (!m3) + return o2; + var i2 = m3.call(o2), r, ar = [], e2; + try { + while ((n3 === void 0 || n3-- > 0) && !(r = i2.next()).done) + ar.push(r.value); + } catch (error) { + e2 = { error }; + } finally { + try { + if (r && !r.done && (m3 = i2["return"])) + m3.call(i2); + } finally { + if (e2) + throw e2.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i2 = 0; i2 < arguments.length; i2++) + ar = ar.concat(__read(arguments[i2])); + return ar; +} +function __spreadArrays() { + for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) + s2 += arguments[i2].length; + for (var r = Array(s2), k4 = 0, i2 = 0; i2 < il; i2++) + for (var a3 = arguments[i2], j2 = 0, jl = a3.length; j2 < jl; j2++, k4++) + r[k4] = a3[j2]; + return r; +} +function __await(v2) { + return this instanceof __await ? (this.v = v2, this) : new __await(v2); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g3 = generator.apply(thisArg, _arguments || []), i2, q2 = []; + return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2; + function verb(n3) { + if (g3[n3]) + i2[n3] = function(v2) { + return new Promise(function(a3, b4) { + q2.push([n3, v2, a3, b4]) > 1 || resume(n3, v2); + }); + }; + } + function resume(n3, v2) { + try { + step(g3[n3](v2)); + } catch (e2) { + settle(q2[0][3], e2); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f4, v2) { + if (f4(v2), q2.shift(), q2.length) + resume(q2[0][0], q2[0][1]); + } +} +function __asyncDelegator(o2) { + var i2, p3; + return i2 = {}, verb("next"), verb("throw", function(e2) { + throw e2; + }), verb("return"), i2[Symbol.iterator] = function() { + return this; + }, i2; + function verb(n3, f4) { + i2[n3] = o2[n3] ? function(v2) { + return (p3 = !p3) ? { value: __await(o2[n3](v2)), done: n3 === "return" } : f4 ? f4(v2) : v2; + } : f4; + } +} +function __asyncValues(o2) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m3 = o2[Symbol.asyncIterator], i2; + return m3 ? m3.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2); + function verb(n3) { + i2[n3] = o2[n3] && function(v2) { + return new Promise(function(resolve, reject) { + v2 = o2[n3](v2), settle(resolve, reject, v2.done, v2.value); + }); + }; + } + function settle(resolve, reject, d3, v2) { + Promise.resolve(v2).then(function(v3) { + resolve({ value: v3, done: d3 }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (Object.hasOwnProperty.call(mod2, k4)) + result[k4] = mod2[k4]; + } + result.default = mod2; + return result; +} +function __importDefault(mod2) { + return mod2 && mod2.__esModule ? mod2 : { default: mod2 }; +} +function __classPrivateFieldGet(receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); +} +function __classPrivateFieldSet(receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; +} +var extendStatics, __assign; +var init_tslib_es6 = __esm({ + "node_modules/tslib/tslib.es6.js"() { + init_shim(); + extendStatics = function(d3, b4) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b5) { + d4.__proto__ = b5; + } || function(d4, b5) { + for (var p3 in b5) + if (b5.hasOwnProperty(p3)) + d4[p3] = b5[p3]; + }; + return extendStatics(d3, b4); + }; + __assign = function() { + __assign = Object.assign || function __assign2(t) { + for (var s2, i2 = 1, n3 = arguments.length; i2 < n3; i2++) { + s2 = arguments[i2]; + for (var p3 in s2) + if (Object.prototype.hasOwnProperty.call(s2, p3)) + t[p3] = s2[p3]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/utils/delay.js +var require_delay = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/utils/delay.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = void 0; + function delay(timeout) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(true); + }, timeout); + }); + } + exports2.delay = delay; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/constants/misc.js +var require_misc = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/constants/misc.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ONE_THOUSAND = exports2.ONE_HUNDRED = void 0; + exports2.ONE_HUNDRED = 100; + exports2.ONE_THOUSAND = 1e3; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/constants/time.js +var require_time = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/constants/time.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ONE_YEAR = exports2.FOUR_WEEKS = exports2.THREE_WEEKS = exports2.TWO_WEEKS = exports2.ONE_WEEK = exports2.THIRTY_DAYS = exports2.SEVEN_DAYS = exports2.FIVE_DAYS = exports2.THREE_DAYS = exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS = exports2.TWELVE_HOURS = exports2.SIX_HOURS = exports2.THREE_HOURS = exports2.ONE_HOUR = exports2.SIXTY_MINUTES = exports2.THIRTY_MINUTES = exports2.TEN_MINUTES = exports2.FIVE_MINUTES = exports2.ONE_MINUTE = exports2.SIXTY_SECONDS = exports2.THIRTY_SECONDS = exports2.TEN_SECONDS = exports2.FIVE_SECONDS = exports2.ONE_SECOND = void 0; + exports2.ONE_SECOND = 1; + exports2.FIVE_SECONDS = 5; + exports2.TEN_SECONDS = 10; + exports2.THIRTY_SECONDS = 30; + exports2.SIXTY_SECONDS = 60; + exports2.ONE_MINUTE = exports2.SIXTY_SECONDS; + exports2.FIVE_MINUTES = exports2.ONE_MINUTE * 5; + exports2.TEN_MINUTES = exports2.ONE_MINUTE * 10; + exports2.THIRTY_MINUTES = exports2.ONE_MINUTE * 30; + exports2.SIXTY_MINUTES = exports2.ONE_MINUTE * 60; + exports2.ONE_HOUR = exports2.SIXTY_MINUTES; + exports2.THREE_HOURS = exports2.ONE_HOUR * 3; + exports2.SIX_HOURS = exports2.ONE_HOUR * 6; + exports2.TWELVE_HOURS = exports2.ONE_HOUR * 12; + exports2.TWENTY_FOUR_HOURS = exports2.ONE_HOUR * 24; + exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS; + exports2.THREE_DAYS = exports2.ONE_DAY * 3; + exports2.FIVE_DAYS = exports2.ONE_DAY * 5; + exports2.SEVEN_DAYS = exports2.ONE_DAY * 7; + exports2.THIRTY_DAYS = exports2.ONE_DAY * 30; + exports2.ONE_WEEK = exports2.SEVEN_DAYS; + exports2.TWO_WEEKS = exports2.ONE_WEEK * 2; + exports2.THREE_WEEKS = exports2.ONE_WEEK * 3; + exports2.FOUR_WEEKS = exports2.ONE_WEEK * 4; + exports2.ONE_YEAR = exports2.ONE_DAY * 365; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/constants/index.js +var require_constants4 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/constants/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_misc(), exports2); + tslib_1.__exportStar(require_time(), exports2); + } +}); + +// node_modules/@walletconnect/time/dist/cjs/utils/convert.js +var require_convert = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/utils/convert.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.fromMiliseconds = exports2.toMiliseconds = void 0; + var constants_1 = require_constants4(); + function toMiliseconds(seconds) { + return seconds * constants_1.ONE_THOUSAND; + } + exports2.toMiliseconds = toMiliseconds; + function fromMiliseconds2(miliseconds) { + return Math.floor(miliseconds / constants_1.ONE_THOUSAND); + } + exports2.fromMiliseconds = fromMiliseconds2; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/utils/index.js +var require_utils3 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/utils/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_delay(), exports2); + tslib_1.__exportStar(require_convert(), exports2); + } +}); + +// node_modules/@walletconnect/time/dist/cjs/watch.js +var require_watch = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/watch.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Watch = void 0; + var Watch = class { + constructor() { + this.timestamps = /* @__PURE__ */ new Map(); + } + start(label) { + if (this.timestamps.has(label)) { + throw new Error(`Watch already started for label: ${label}`); + } + this.timestamps.set(label, { started: Date.now() }); + } + stop(label) { + const timestamp = this.get(label); + if (typeof timestamp.elapsed !== "undefined") { + throw new Error(`Watch already stopped for label: ${label}`); + } + const elapsed = Date.now() - timestamp.started; + this.timestamps.set(label, { started: timestamp.started, elapsed }); + } + get(label) { + const timestamp = this.timestamps.get(label); + if (typeof timestamp === "undefined") { + throw new Error(`No timestamp found for label: ${label}`); + } + return timestamp; + } + elapsed(label) { + const timestamp = this.get(label); + const elapsed = timestamp.elapsed || Date.now() - timestamp.started; + return elapsed; + } + }; + exports2.Watch = Watch; + exports2.default = Watch; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/types/watch.js +var require_watch2 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/types/watch.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.IWatch = void 0; + var IWatch = class { + }; + exports2.IWatch = IWatch; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/types/index.js +var require_types2 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/types/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_watch2(), exports2); + } +}); + +// node_modules/@walletconnect/time/dist/cjs/index.js +var require_cjs = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_utils3(), exports2); + tslib_1.__exportStar(require_watch(), exports2); + tslib_1.__exportStar(require_types2(), exports2); + tslib_1.__exportStar(require_constants4(), exports2); + } +}); + +// node_modules/@walletconnect/events/dist/esm/events.js +var IEvents; +var init_events = __esm({ + "node_modules/@walletconnect/events/dist/esm/events.js"() { + init_shim(); + IEvents = class { + }; + } +}); + +// node_modules/@walletconnect/events/dist/esm/index.js +var esm_exports2 = {}; +__export(esm_exports2, { + IEvents: () => IEvents +}); +var init_esm2 = __esm({ + "node_modules/@walletconnect/events/dist/esm/index.js"() { + init_shim(); + init_events(); + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js +var require_heartbeat = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.IHeartBeat = void 0; + var events_1 = (init_esm2(), __toCommonJS(esm_exports2)); + var IHeartBeat = class extends events_1.IEvents { + constructor(opts) { + super(); + } + }; + exports2.IHeartBeat = IHeartBeat; + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js +var require_types3 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_heartbeat(), exports2); + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js +var require_heartbeat2 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HEARTBEAT_EVENTS = exports2.HEARTBEAT_INTERVAL = void 0; + var time_1 = require_cjs(); + exports2.HEARTBEAT_INTERVAL = time_1.FIVE_SECONDS; + exports2.HEARTBEAT_EVENTS = { + pulse: "heartbeat_pulse" + }; + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js +var require_constants5 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_heartbeat2(), exports2); + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js +var require_heartbeat3 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HeartBeat = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var events_1 = require_events(); + var time_1 = require_cjs(); + var types_1 = require_types3(); + var constants_1 = require_constants5(); + var HeartBeat = class _HeartBeat extends types_1.IHeartBeat { + constructor(opts) { + super(opts); + this.events = new events_1.EventEmitter(); + this.interval = constants_1.HEARTBEAT_INTERVAL; + this.interval = (opts === null || opts === void 0 ? void 0 : opts.interval) || constants_1.HEARTBEAT_INTERVAL; + } + static init(opts) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const heartbeat = new _HeartBeat(opts); + yield heartbeat.init(); + return heartbeat; + }); + } + init() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + yield this.initialize(); + }); + } + stop() { + clearInterval(this.intervalRef); + } + on(event, listener) { + this.events.on(event, listener); + } + once(event, listener) { + this.events.once(event, listener); + } + off(event, listener) { + this.events.off(event, listener); + } + removeListener(event, listener) { + this.events.removeListener(event, listener); + } + initialize() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + this.intervalRef = setInterval(() => this.pulse(), time_1.toMiliseconds(this.interval)); + }); + } + pulse() { + this.events.emit(constants_1.HEARTBEAT_EVENTS.pulse); + } + }; + exports2.HeartBeat = HeartBeat; + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/index.js +var require_cjs2 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_heartbeat3(), exports2); + tslib_1.__exportStar(require_types3(), exports2); + tslib_1.__exportStar(require_constants5(), exports2); + } +}); + +// node_modules/quick-format-unescaped/index.js +var require_quick_format_unescaped = __commonJS({ + "node_modules/quick-format-unescaped/index.js"(exports2, module2) { + "use strict"; + init_shim(); + function tryStringify(o2) { + try { + return JSON.stringify(o2); + } catch (e2) { + return '"[Circular]"'; + } + } + module2.exports = format; + function format(f4, args, opts) { + var ss = opts && opts.stringify || tryStringify; + var offset = 1; + if (typeof f4 === "object" && f4 !== null) { + var len = args.length + offset; + if (len === 1) + return f4; + var objects = new Array(len); + objects[0] = ss(f4); + for (var index = 1; index < len; index++) { + objects[index] = ss(args[index]); + } + return objects.join(" "); + } + if (typeof f4 !== "string") { + return f4; + } + var argLen = args.length; + if (argLen === 0) + return f4; + var str = ""; + var a3 = 1 - offset; + var lastPos = -1; + var flen = f4 && f4.length || 0; + for (var i2 = 0; i2 < flen; ) { + if (f4.charCodeAt(i2) === 37 && i2 + 1 < flen) { + lastPos = lastPos > -1 ? lastPos : 0; + switch (f4.charCodeAt(i2 + 1)) { + case 100: + case 102: + if (a3 >= argLen) + break; + if (args[a3] == null) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += Number(args[a3]); + lastPos = i2 + 2; + i2++; + break; + case 105: + if (a3 >= argLen) + break; + if (args[a3] == null) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += Math.floor(Number(args[a3])); + lastPos = i2 + 2; + i2++; + break; + case 79: + case 111: + case 106: + if (a3 >= argLen) + break; + if (args[a3] === void 0) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + var type = typeof args[a3]; + if (type === "string") { + str += "'" + args[a3] + "'"; + lastPos = i2 + 2; + i2++; + break; + } + if (type === "function") { + str += args[a3].name || ""; + lastPos = i2 + 2; + i2++; + break; + } + str += ss(args[a3]); + lastPos = i2 + 2; + i2++; + break; + case 115: + if (a3 >= argLen) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += String(args[a3]); + lastPos = i2 + 2; + i2++; + break; + case 37: + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += "%"; + lastPos = i2 + 2; + i2++; + a3--; + break; + } + ++a3; + } + ++i2; + } + if (lastPos === -1) + return f4; + else if (lastPos < flen) { + str += f4.slice(lastPos); + } + return str; + } + } +}); + +// node_modules/pino/browser.js +var require_browser3 = __commonJS({ + "node_modules/pino/browser.js"(exports2, module2) { + "use strict"; + init_shim(); + var format = require_quick_format_unescaped(); + module2.exports = pino; + var _console = pfGlobalThisOrFallback().console || {}; + var stdSerializers = { + mapHttpRequest: mock, + mapHttpResponse: mock, + wrapRequestSerializer: passthrough, + wrapResponseSerializer: passthrough, + wrapErrorSerializer: passthrough, + req: mock, + res: mock, + err: asErrValue + }; + function shouldSerialize(serialize, serializers) { + if (Array.isArray(serialize)) { + const hasToFilter = serialize.filter(function(k4) { + return k4 !== "!stdSerializers.err"; + }); + return hasToFilter; + } else if (serialize === true) { + return Object.keys(serializers); + } + return false; + } + function pino(opts) { + opts = opts || {}; + opts.browser = opts.browser || {}; + const transmit2 = opts.browser.transmit; + if (transmit2 && typeof transmit2.send !== "function") { + throw Error("pino: transmit option must have a send function"); + } + const proto = opts.browser.write || _console; + if (opts.browser.write) + opts.browser.asObject = true; + const serializers = opts.serializers || {}; + const serialize = shouldSerialize(opts.browser.serialize, serializers); + let stdErrSerialize = opts.browser.serialize; + if (Array.isArray(opts.browser.serialize) && opts.browser.serialize.indexOf("!stdSerializers.err") > -1) + stdErrSerialize = false; + const levels = ["error", "fatal", "warn", "info", "debug", "trace"]; + if (typeof proto === "function") { + proto.error = proto.fatal = proto.warn = proto.info = proto.debug = proto.trace = proto; + } + if (opts.enabled === false) + opts.level = "silent"; + const level = opts.level || "info"; + const logger = Object.create(proto); + if (!logger.log) + logger.log = noop; + Object.defineProperty(logger, "levelVal", { + get: getLevelVal + }); + Object.defineProperty(logger, "level", { + get: getLevel, + set: setLevel + }); + const setOpts = { + transmit: transmit2, + serialize, + asObject: opts.browser.asObject, + levels, + timestamp: getTimeFunction(opts) + }; + logger.levels = pino.levels; + logger.level = level; + logger.setMaxListeners = logger.getMaxListeners = logger.emit = logger.addListener = logger.on = logger.prependListener = logger.once = logger.prependOnceListener = logger.removeListener = logger.removeAllListeners = logger.listeners = logger.listenerCount = logger.eventNames = logger.write = logger.flush = noop; + logger.serializers = serializers; + logger._serialize = serialize; + logger._stdErrSerialize = stdErrSerialize; + logger.child = child; + if (transmit2) + logger._logEvent = createLogEventShape(); + function getLevelVal() { + return this.level === "silent" ? Infinity : this.levels.values[this.level]; + } + function getLevel() { + return this._level; + } + function setLevel(level2) { + if (level2 !== "silent" && !this.levels.values[level2]) { + throw Error("unknown level " + level2); + } + this._level = level2; + set2(setOpts, logger, "error", "log"); + set2(setOpts, logger, "fatal", "error"); + set2(setOpts, logger, "warn", "error"); + set2(setOpts, logger, "info", "log"); + set2(setOpts, logger, "debug", "log"); + set2(setOpts, logger, "trace", "log"); + } + function child(bindings, childOptions) { + if (!bindings) { + throw new Error("missing bindings for child Pino"); + } + childOptions = childOptions || {}; + if (serialize && bindings.serializers) { + childOptions.serializers = bindings.serializers; + } + const childOptionsSerializers = childOptions.serializers; + if (serialize && childOptionsSerializers) { + var childSerializers = Object.assign({}, serializers, childOptionsSerializers); + var childSerialize = opts.browser.serialize === true ? Object.keys(childSerializers) : serialize; + delete bindings.serializers; + applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize); + } + function Child(parent) { + this._childLevel = (parent._childLevel | 0) + 1; + this.error = bind(parent, bindings, "error"); + this.fatal = bind(parent, bindings, "fatal"); + this.warn = bind(parent, bindings, "warn"); + this.info = bind(parent, bindings, "info"); + this.debug = bind(parent, bindings, "debug"); + this.trace = bind(parent, bindings, "trace"); + if (childSerializers) { + this.serializers = childSerializers; + this._serialize = childSerialize; + } + if (transmit2) { + this._logEvent = createLogEventShape( + [].concat(parent._logEvent.bindings, bindings) + ); + } + } + Child.prototype = this; + return new Child(this); + } + return logger; + } + pino.levels = { + values: { + fatal: 60, + error: 50, + warn: 40, + info: 30, + debug: 20, + trace: 10 + }, + labels: { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal" + } + }; + pino.stdSerializers = stdSerializers; + pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime }); + function set2(opts, logger, level, fallback) { + const proto = Object.getPrototypeOf(logger); + logger[level] = logger.levelVal > logger.levels.values[level] ? noop : proto[level] ? proto[level] : _console[level] || _console[fallback] || noop; + wrap(opts, logger, level); + } + function wrap(opts, logger, level) { + if (!opts.transmit && logger[level] === noop) + return; + logger[level] = /* @__PURE__ */ function(write) { + return function LOG() { + const ts = opts.timestamp(); + const args = new Array(arguments.length); + const proto = Object.getPrototypeOf && Object.getPrototypeOf(this) === _console ? _console : this; + for (var i2 = 0; i2 < args.length; i2++) + args[i2] = arguments[i2]; + if (opts.serialize && !opts.asObject) { + applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize); + } + if (opts.asObject) + write.call(proto, asObject(this, level, args, ts)); + else + write.apply(proto, args); + if (opts.transmit) { + const transmitLevel = opts.transmit.level || logger.level; + const transmitValue = pino.levels.values[transmitLevel]; + const methodValue = pino.levels.values[level]; + if (methodValue < transmitValue) + return; + transmit(this, { + ts, + methodLevel: level, + methodValue, + transmitLevel, + transmitValue: pino.levels.values[opts.transmit.level || logger.level], + send: opts.transmit.send, + val: logger.levelVal + }, args); + } + }; + }(logger[level]); + } + function asObject(logger, level, args, ts) { + if (logger._serialize) + applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize); + const argsCloned = args.slice(); + let msg = argsCloned[0]; + const o2 = {}; + if (ts) { + o2.time = ts; + } + o2.level = pino.levels.values[level]; + let lvl = (logger._childLevel | 0) + 1; + if (lvl < 1) + lvl = 1; + if (msg !== null && typeof msg === "object") { + while (lvl-- && typeof argsCloned[0] === "object") { + Object.assign(o2, argsCloned.shift()); + } + msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : void 0; + } else if (typeof msg === "string") + msg = format(argsCloned.shift(), argsCloned); + if (msg !== void 0) + o2.msg = msg; + return o2; + } + function applySerializers(args, serialize, serializers, stdErrSerialize) { + for (const i2 in args) { + if (stdErrSerialize && args[i2] instanceof Error) { + args[i2] = pino.stdSerializers.err(args[i2]); + } else if (typeof args[i2] === "object" && !Array.isArray(args[i2])) { + for (const k4 in args[i2]) { + if (serialize && serialize.indexOf(k4) > -1 && k4 in serializers) { + args[i2][k4] = serializers[k4](args[i2][k4]); + } + } + } + } + } + function bind(parent, bindings, level) { + return function() { + const args = new Array(1 + arguments.length); + args[0] = bindings; + for (var i2 = 1; i2 < args.length; i2++) { + args[i2] = arguments[i2 - 1]; + } + return parent[level].apply(this, args); + }; + } + function transmit(logger, opts, args) { + const send = opts.send; + const ts = opts.ts; + const methodLevel = opts.methodLevel; + const methodValue = opts.methodValue; + const val = opts.val; + const bindings = logger._logEvent.bindings; + applySerializers( + args, + logger._serialize || Object.keys(logger.serializers), + logger.serializers, + logger._stdErrSerialize === void 0 ? true : logger._stdErrSerialize + ); + logger._logEvent.ts = ts; + logger._logEvent.messages = args.filter(function(arg) { + return bindings.indexOf(arg) === -1; + }); + logger._logEvent.level.label = methodLevel; + logger._logEvent.level.value = methodValue; + send(methodLevel, logger._logEvent, val); + logger._logEvent = createLogEventShape(bindings); + } + function createLogEventShape(bindings) { + return { + ts: 0, + messages: [], + bindings: bindings || [], + level: { label: "", value: 0 } + }; + } + function asErrValue(err) { + const obj = { + type: err.constructor.name, + msg: err.message, + stack: err.stack + }; + for (const key in err) { + if (obj[key] === void 0) { + obj[key] = err[key]; + } + } + return obj; + } + function getTimeFunction(opts) { + if (typeof opts.timestamp === "function") { + return opts.timestamp; + } + if (opts.timestamp === false) { + return nullTime; + } + return epochTime; + } + function mock() { + return {}; + } + function passthrough(a3) { + return a3; + } + function noop() { + } + function nullTime() { + return false; + } + function epochTime() { + return Date.now(); + } + function unixTime() { + return Math.round(Date.now() / 1e3); + } + function isoTime() { + return new Date(Date.now()).toISOString(); + } + function pfGlobalThisOrFallback() { + function defd(o2) { + return typeof o2 !== "undefined" && o2; + } + try { + if (typeof globalThis !== "undefined") + return globalThis; + Object.defineProperty(Object.prototype, "globalThis", { + get: function() { + delete Object.prototype.globalThis; + return this.globalThis = this; + }, + configurable: true + }); + return globalThis; + } catch (e2) { + return defd(self) || defd(window) || defd(this) || {}; + } + } + } +}); + +// node_modules/@walletconnect/logger/dist/index.es.js +var index_es_exports2 = {}; +__export(index_es_exports2, { + MAX_LOG_SIZE_IN_BYTES_DEFAULT: () => l2, + PINO_CUSTOM_CONTEXT_KEY: () => n, + PINO_LOGGER_DEFAULTS: () => c2, + formatChildLoggerContext: () => w, + generateChildLogger: () => E2, + generateClientLogger: () => C, + generatePlatformLogger: () => A, + generateServerLogger: () => I, + getBrowserLoggerContext: () => v, + getDefaultLoggerOptions: () => k2, + getLoggerContext: () => y2, + pino: () => import_pino2.default, + setBrowserLoggerContext: () => b +}); +function k2(r) { + return g(i({}, r), { level: r?.level || c2.level }); +} +function v(r, e2 = n) { + return r[e2] || ""; +} +function b(r, e2, t = n) { + return r[t] = e2, r; +} +function y2(r, e2 = n) { + let t = ""; + return typeof r.bindings > "u" ? t = v(r, e2) : t = r.bindings().context || "", t; +} +function w(r, e2, t = n) { + const o2 = y2(r, t); + return o2.trim() ? `${o2}/${e2}` : e2; +} +function E2(r, e2, t = n) { + const o2 = w(r, e2, t), a3 = r.child({ context: o2 }); + return b(a3, o2, t); +} +function C(r) { + var e2, t; + const o2 = new m((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); + return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace", browser: g(i({}, (t = r.opts) == null ? void 0 : t.browser), { write: (a3) => o2.write(a3) }) })), chunkLoggerController: o2 }; +} +function I(r) { + var e2; + const t = new B((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); + return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace" }), t), chunkLoggerController: t }; +} +function A(r) { + return typeof r.loggerOverride < "u" && typeof r.loggerOverride != "string" ? { logger: r.loggerOverride, chunkLoggerController: null } : typeof window < "u" ? C(r) : I(r); +} +var import_pino, import_pino2, c2, n, l2, O2, d, L, m, B, x2, S, _2, p, T, z2, f, i, g; +var init_index_es2 = __esm({ + "node_modules/@walletconnect/logger/dist/index.es.js"() { + init_shim(); + import_pino = __toESM(require_browser3()); + import_pino2 = __toESM(require_browser3()); + init_esm(); + c2 = { level: "info" }; + n = "custom_context"; + l2 = 1e3 * 1024; + O2 = class { + constructor(e2) { + this.nodeValue = e2, this.sizeInBytes = new TextEncoder().encode(this.nodeValue).length, this.next = null; + } + get value() { + return this.nodeValue; + } + get size() { + return this.sizeInBytes; + } + }; + d = class { + constructor(e2) { + this.head = null, this.tail = null, this.lengthInNodes = 0, this.maxSizeInBytes = e2, this.sizeInBytes = 0; + } + append(e2) { + const t = new O2(e2); + if (t.size > this.maxSizeInBytes) + throw new Error(`[LinkedList] Value too big to insert into list: ${e2} with size ${t.size}`); + for (; this.size + t.size > this.maxSizeInBytes; ) + this.shift(); + this.head ? (this.tail && (this.tail.next = t), this.tail = t) : (this.head = t, this.tail = t), this.lengthInNodes++, this.sizeInBytes += t.size; + } + shift() { + if (!this.head) + return; + const e2 = this.head; + this.head = this.head.next, this.head || (this.tail = null), this.lengthInNodes--, this.sizeInBytes -= e2.size; + } + toArray() { + const e2 = []; + let t = this.head; + for (; t !== null; ) + e2.push(t.value), t = t.next; + return e2; + } + get length() { + return this.lengthInNodes; + } + get size() { + return this.sizeInBytes; + } + toOrderedArray() { + return Array.from(this); + } + [Symbol.iterator]() { + let e2 = this.head; + return { next: () => { + if (!e2) + return { done: true, value: null }; + const t = e2.value; + return e2 = e2.next, { done: false, value: t }; + } }; + } + }; + L = class { + constructor(e2, t = l2) { + this.level = e2 ?? "error", this.levelValue = import_pino.levels.values[this.level], this.MAX_LOG_SIZE_IN_BYTES = t, this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); + } + forwardToConsole(e2, t) { + t === import_pino.levels.values.error ? console.error(e2) : t === import_pino.levels.values.warn ? console.warn(e2) : t === import_pino.levels.values.debug ? console.debug(e2) : t === import_pino.levels.values.trace ? console.trace(e2) : console.log(e2); + } + appendToLogs(e2) { + this.logs.append(safeJsonStringify({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), log: e2 })); + const t = typeof e2 == "string" ? JSON.parse(e2).level : e2.level; + t >= this.levelValue && this.forwardToConsole(e2, t); + } + getLogs() { + return this.logs; + } + clearLogs() { + this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); + } + getLogArray() { + return Array.from(this.logs); + } + logsToBlob(e2) { + const t = this.getLogArray(); + return t.push(safeJsonStringify({ extraMetadata: e2 })), new Blob(t, { type: "application/json" }); + } + }; + m = class { + constructor(e2, t = l2) { + this.baseChunkLogger = new L(e2, t); + } + write(e2) { + this.baseChunkLogger.appendToLogs(e2); + } + getLogs() { + return this.baseChunkLogger.getLogs(); + } + clearLogs() { + this.baseChunkLogger.clearLogs(); + } + getLogArray() { + return this.baseChunkLogger.getLogArray(); + } + logsToBlob(e2) { + return this.baseChunkLogger.logsToBlob(e2); + } + downloadLogsBlobInBrowser(e2) { + const t = URL.createObjectURL(this.logsToBlob(e2)), o2 = document.createElement("a"); + o2.href = t, o2.download = `walletconnect-logs-${(/* @__PURE__ */ new Date()).toISOString()}.txt`, document.body.appendChild(o2), o2.click(), document.body.removeChild(o2), URL.revokeObjectURL(t); + } + }; + B = class { + constructor(e2, t = l2) { + this.baseChunkLogger = new L(e2, t); + } + write(e2) { + this.baseChunkLogger.appendToLogs(e2); + } + getLogs() { + return this.baseChunkLogger.getLogs(); + } + clearLogs() { + this.baseChunkLogger.clearLogs(); + } + getLogArray() { + return this.baseChunkLogger.getLogArray(); + } + logsToBlob(e2) { + return this.baseChunkLogger.logsToBlob(e2); + } + }; + x2 = Object.defineProperty; + S = Object.defineProperties; + _2 = Object.getOwnPropertyDescriptors; + p = Object.getOwnPropertySymbols; + T = Object.prototype.hasOwnProperty; + z2 = Object.prototype.propertyIsEnumerable; + f = (r, e2, t) => e2 in r ? x2(r, e2, { enumerable: true, configurable: true, writable: true, value: t }) : r[e2] = t; + i = (r, e2) => { + for (var t in e2 || (e2 = {})) + T.call(e2, t) && f(r, t, e2[t]); + if (p) + for (var t of p(e2)) + z2.call(e2, t) && f(r, t, e2[t]); + return r; + }; + g = (r, e2) => S(r, _2(e2)); + } +}); + +// node_modules/@walletconnect/types/dist/index.cjs.js +var require_index_cjs = __commonJS({ + "node_modules/@walletconnect/types/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var r = (init_esm2(), __toCommonJS(esm_exports2)); + var c4 = require_events(); + function i2(t) { + return t && typeof t == "object" && "default" in t ? t : { default: t }; + } + var n3 = i2(c4); + var l4 = class extends r.IEvents { + constructor(s2) { + super(), this.opts = s2, this.protocol = "wc", this.version = 2; + } + }; + var a3 = class { + constructor(s2, e2, o2) { + this.core = s2, this.logger = e2; + } + }; + var u3 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.core = s2, this.logger = e2, this.records = /* @__PURE__ */ new Map(); + } + }; + var I2 = class { + constructor(s2, e2) { + this.logger = s2, this.core = e2; + } + }; + var h5 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.relayer = s2, this.logger = e2; + } + }; + var g3 = class extends r.IEvents { + constructor(s2) { + super(); + } + }; + var p3 = class { + constructor(s2, e2, o2, _4) { + this.core = s2, this.logger = e2, this.name = o2; + } + }; + var E4 = class { + constructor() { + this.map = /* @__PURE__ */ new Map(); + } + }; + var v2 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.relayer = s2, this.logger = e2; + } + }; + var d3 = class { + constructor(s2, e2) { + this.core = s2, this.logger = e2; + } + }; + var y4 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.core = s2, this.logger = e2; + } + }; + var b4 = class { + constructor(s2, e2) { + this.logger = s2, this.core = e2; + } + }; + var C3 = class { + constructor(s2, e2) { + this.projectId = s2, this.logger = e2; + } + }; + var f4 = class { + constructor(s2, e2) { + this.projectId = s2, this.logger = e2; + } + }; + var x3 = class extends n3.default { + constructor() { + super(); + } + }; + var S4 = class { + constructor(s2) { + this.opts = s2, this.protocol = "wc", this.version = 2; + } + }; + var M = class extends c4.EventEmitter { + constructor() { + super(); + } + }; + var P2 = class { + constructor(s2) { + this.client = s2; + } + }; + exports2.ICore = l4, exports2.ICrypto = a3, exports2.IEchoClient = f4, exports2.IEngine = P2, exports2.IEngineEvents = M, exports2.IExpirer = y4, exports2.IJsonRpcHistory = u3, exports2.IKeyChain = d3, exports2.IMessageTracker = I2, exports2.IPairing = b4, exports2.IPublisher = h5, exports2.IRelayer = g3, exports2.ISignClient = S4, exports2.ISignClientEvents = x3, exports2.IStore = p3, exports2.ISubscriber = v2, exports2.ISubscriberTopicMap = E4, exports2.IVerify = C3; + } +}); + +// node_modules/@stablelib/random/lib/source/browser.js +var require_browser4 = __commonJS({ + "node_modules/@stablelib/random/lib/source/browser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BrowserRandomSource = void 0; + var QUOTA = 65536; + var BrowserRandomSource = class { + constructor() { + this.isAvailable = false; + this.isInstantiated = false; + const browserCrypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; + if (browserCrypto && browserCrypto.getRandomValues !== void 0) { + this._crypto = browserCrypto; + this.isAvailable = true; + this.isInstantiated = true; + } + } + randomBytes(length2) { + if (!this.isAvailable || !this._crypto) { + throw new Error("Browser random byte generator is not available."); + } + const out = new Uint8Array(length2); + for (let i2 = 0; i2 < out.length; i2 += QUOTA) { + this._crypto.getRandomValues(out.subarray(i2, i2 + Math.min(out.length - i2, QUOTA))); + } + return out; + } + }; + exports2.BrowserRandomSource = BrowserRandomSource; + } +}); + +// node_modules/@stablelib/wipe/lib/wipe.js +var require_wipe = __commonJS({ + "node_modules/@stablelib/wipe/lib/wipe.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function wipe(array) { + for (var i2 = 0; i2 < array.length; i2++) { + array[i2] = 0; + } + return array; + } + exports2.wipe = wipe; + } +}); + +// (disabled):crypto +var require_crypto = __commonJS({ + "(disabled):crypto"() { + init_shim(); + } +}); + +// node_modules/@stablelib/random/lib/source/node.js +var require_node = __commonJS({ + "node_modules/@stablelib/random/lib/source/node.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NodeRandomSource = void 0; + var wipe_1 = require_wipe(); + var NodeRandomSource = class { + constructor() { + this.isAvailable = false; + this.isInstantiated = false; + if (typeof __require !== "undefined") { + const nodeCrypto = require_crypto(); + if (nodeCrypto && nodeCrypto.randomBytes) { + this._crypto = nodeCrypto; + this.isAvailable = true; + this.isInstantiated = true; + } + } + } + randomBytes(length2) { + if (!this.isAvailable || !this._crypto) { + throw new Error("Node.js random byte generator is not available."); + } + let buffer = this._crypto.randomBytes(length2); + if (buffer.length !== length2) { + throw new Error("NodeRandomSource: got fewer bytes than requested"); + } + const out = new Uint8Array(length2); + for (let i2 = 0; i2 < out.length; i2++) { + out[i2] = buffer[i2]; + } + (0, wipe_1.wipe)(buffer); + return out; + } + }; + exports2.NodeRandomSource = NodeRandomSource; + } +}); + +// node_modules/@stablelib/random/lib/source/system.js +var require_system = __commonJS({ + "node_modules/@stablelib/random/lib/source/system.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SystemRandomSource = void 0; + var browser_1 = require_browser4(); + var node_1 = require_node(); + var SystemRandomSource = class { + constructor() { + this.isAvailable = false; + this.name = ""; + this._source = new browser_1.BrowserRandomSource(); + if (this._source.isAvailable) { + this.isAvailable = true; + this.name = "Browser"; + return; + } + this._source = new node_1.NodeRandomSource(); + if (this._source.isAvailable) { + this.isAvailable = true; + this.name = "Node"; + return; + } + } + randomBytes(length2) { + if (!this.isAvailable) { + throw new Error("System random byte generator is not available."); + } + return this._source.randomBytes(length2); + } + }; + exports2.SystemRandomSource = SystemRandomSource; + } +}); + +// node_modules/@stablelib/int/lib/int.js +var require_int = __commonJS({ + "node_modules/@stablelib/int/lib/int.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function imulShim(a3, b4) { + var ah = a3 >>> 16 & 65535, al = a3 & 65535; + var bh = b4 >>> 16 & 65535, bl = b4 & 65535; + return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; + } + exports2.mul = Math.imul || imulShim; + function add(a3, b4) { + return a3 + b4 | 0; + } + exports2.add = add; + function sub(a3, b4) { + return a3 - b4 | 0; + } + exports2.sub = sub; + function rotl(x3, n3) { + return x3 << n3 | x3 >>> 32 - n3; + } + exports2.rotl = rotl; + function rotr(x3, n3) { + return x3 << 32 - n3 | x3 >>> n3; + } + exports2.rotr = rotr; + function isIntegerShim(n3) { + return typeof n3 === "number" && isFinite(n3) && Math.floor(n3) === n3; + } + exports2.isInteger = Number.isInteger || isIntegerShim; + exports2.MAX_SAFE_INTEGER = 9007199254740991; + exports2.isSafeInteger = function(n3) { + return exports2.isInteger(n3) && (n3 >= -exports2.MAX_SAFE_INTEGER && n3 <= exports2.MAX_SAFE_INTEGER); + }; + } +}); + +// node_modules/@stablelib/binary/lib/binary.js +var require_binary2 = __commonJS({ + "node_modules/@stablelib/binary/lib/binary.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var int_1 = require_int(); + function readInt16BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 0] << 8 | array[offset + 1]) << 16 >> 16; + } + exports2.readInt16BE = readInt16BE; + function readUint16BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 0] << 8 | array[offset + 1]) >>> 0; + } + exports2.readUint16BE = readUint16BE; + function readInt16LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 1] << 8 | array[offset]) << 16 >> 16; + } + exports2.readInt16LE = readInt16LE; + function readUint16LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 1] << 8 | array[offset]) >>> 0; + } + exports2.readUint16LE = readUint16LE; + function writeUint16BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(2); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 8; + out[offset + 1] = value >>> 0; + return out; + } + exports2.writeUint16BE = writeUint16BE; + exports2.writeInt16BE = writeUint16BE; + function writeUint16LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(2); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 0; + out[offset + 1] = value >>> 8; + return out; + } + exports2.writeUint16LE = writeUint16LE; + exports2.writeInt16LE = writeUint16LE; + function readInt32BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]; + } + exports2.readInt32BE = readInt32BE; + function readUint32BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]) >>> 0; + } + exports2.readUint32BE = readUint32BE; + function readInt32LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]; + } + exports2.readInt32LE = readInt32LE; + function readUint32LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]) >>> 0; + } + exports2.readUint32LE = readUint32LE; + function writeUint32BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 24; + out[offset + 1] = value >>> 16; + out[offset + 2] = value >>> 8; + out[offset + 3] = value >>> 0; + return out; + } + exports2.writeUint32BE = writeUint32BE; + exports2.writeInt32BE = writeUint32BE; + function writeUint32LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 0; + out[offset + 1] = value >>> 8; + out[offset + 2] = value >>> 16; + out[offset + 3] = value >>> 24; + return out; + } + exports2.writeUint32LE = writeUint32LE; + exports2.writeInt32LE = writeUint32LE; + function readInt64BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var hi = readInt32BE(array, offset); + var lo = readInt32BE(array, offset + 4); + return hi * 4294967296 + lo - (lo >> 31) * 4294967296; + } + exports2.readInt64BE = readInt64BE; + function readUint64BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var hi = readUint32BE(array, offset); + var lo = readUint32BE(array, offset + 4); + return hi * 4294967296 + lo; + } + exports2.readUint64BE = readUint64BE; + function readInt64LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var lo = readInt32LE(array, offset); + var hi = readInt32LE(array, offset + 4); + return hi * 4294967296 + lo - (lo >> 31) * 4294967296; + } + exports2.readInt64LE = readInt64LE; + function readUint64LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var lo = readUint32LE(array, offset); + var hi = readUint32LE(array, offset + 4); + return hi * 4294967296 + lo; + } + exports2.readUint64LE = readUint64LE; + function writeUint64BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + writeUint32BE(value / 4294967296 >>> 0, out, offset); + writeUint32BE(value >>> 0, out, offset + 4); + return out; + } + exports2.writeUint64BE = writeUint64BE; + exports2.writeInt64BE = writeUint64BE; + function writeUint64LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + writeUint32LE(value >>> 0, out, offset); + writeUint32LE(value / 4294967296 >>> 0, out, offset + 4); + return out; + } + exports2.writeUint64LE = writeUint64LE; + exports2.writeInt64LE = writeUint64LE; + function readUintBE(bitLength, array, offset) { + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("readUintBE supports only bitLengths divisible by 8"); + } + if (bitLength / 8 > array.length - offset) { + throw new Error("readUintBE: array is too short for the given bitLength"); + } + var result = 0; + var mul = 1; + for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { + result += array[i2] * mul; + mul *= 256; + } + return result; + } + exports2.readUintBE = readUintBE; + function readUintLE(bitLength, array, offset) { + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("readUintLE supports only bitLengths divisible by 8"); + } + if (bitLength / 8 > array.length - offset) { + throw new Error("readUintLE: array is too short for the given bitLength"); + } + var result = 0; + var mul = 1; + for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { + result += array[i2] * mul; + mul *= 256; + } + return result; + } + exports2.readUintLE = readUintLE; + function writeUintBE(bitLength, value, out, offset) { + if (out === void 0) { + out = new Uint8Array(bitLength / 8); + } + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("writeUintBE supports only bitLengths divisible by 8"); + } + if (!int_1.isSafeInteger(value)) { + throw new Error("writeUintBE value must be an integer"); + } + var div = 1; + for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { + out[i2] = value / div & 255; + div *= 256; + } + return out; + } + exports2.writeUintBE = writeUintBE; + function writeUintLE(bitLength, value, out, offset) { + if (out === void 0) { + out = new Uint8Array(bitLength / 8); + } + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("writeUintLE supports only bitLengths divisible by 8"); + } + if (!int_1.isSafeInteger(value)) { + throw new Error("writeUintLE value must be an integer"); + } + var div = 1; + for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { + out[i2] = value / div & 255; + div *= 256; + } + return out; + } + exports2.writeUintLE = writeUintLE; + function readFloat32BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat32(offset); + } + exports2.readFloat32BE = readFloat32BE; + function readFloat32LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat32(offset, true); + } + exports2.readFloat32LE = readFloat32LE; + function readFloat64BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat64(offset); + } + exports2.readFloat64BE = readFloat64BE; + function readFloat64LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat64(offset, true); + } + exports2.readFloat64LE = readFloat64LE; + function writeFloat32BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat32(offset, value); + return out; + } + exports2.writeFloat32BE = writeFloat32BE; + function writeFloat32LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat32(offset, value, true); + return out; + } + exports2.writeFloat32LE = writeFloat32LE; + function writeFloat64BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat64(offset, value); + return out; + } + exports2.writeFloat64BE = writeFloat64BE; + function writeFloat64LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat64(offset, value, true); + return out; + } + exports2.writeFloat64LE = writeFloat64LE; + } +}); + +// node_modules/@stablelib/random/lib/random.js +var require_random = __commonJS({ + "node_modules/@stablelib/random/lib/random.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomStringForEntropy = exports2.randomString = exports2.randomUint32 = exports2.randomBytes = exports2.defaultRandomSource = void 0; + var system_1 = require_system(); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + exports2.defaultRandomSource = new system_1.SystemRandomSource(); + function randomBytes2(length2, prng = exports2.defaultRandomSource) { + return prng.randomBytes(length2); + } + exports2.randomBytes = randomBytes2; + function randomUint32(prng = exports2.defaultRandomSource) { + const buf = randomBytes2(4, prng); + const result = (0, binary_1.readUint32LE)(buf); + (0, wipe_1.wipe)(buf); + return result; + } + exports2.randomUint32 = randomUint32; + var ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + function randomString(length2, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { + if (charset.length < 2) { + throw new Error("randomString charset is too short"); + } + if (charset.length > 256) { + throw new Error("randomString charset is too long"); + } + let out = ""; + const charsLen = charset.length; + const maxByte = 256 - 256 % charsLen; + while (length2 > 0) { + const buf = randomBytes2(Math.ceil(length2 * 256 / maxByte), prng); + for (let i2 = 0; i2 < buf.length && length2 > 0; i2++) { + const randomByte = buf[i2]; + if (randomByte < maxByte) { + out += charset.charAt(randomByte % charsLen); + length2--; + } + } + (0, wipe_1.wipe)(buf); + } + return out; + } + exports2.randomString = randomString; + function randomStringForEntropy(bits, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { + const length2 = Math.ceil(bits / (Math.log(charset.length) / Math.LN2)); + return randomString(length2, charset, prng); + } + exports2.randomStringForEntropy = randomStringForEntropy; + } +}); + +// node_modules/@stablelib/sha512/lib/sha512.js +var require_sha512 = __commonJS({ + "node_modules/@stablelib/sha512/lib/sha512.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + exports2.DIGEST_LENGTH = 64; + exports2.BLOCK_SIZE = 128; + var SHA512 = ( + /** @class */ + function() { + function SHA5122() { + this.digestLength = exports2.DIGEST_LENGTH; + this.blockSize = exports2.BLOCK_SIZE; + this._stateHi = new Int32Array(8); + this._stateLo = new Int32Array(8); + this._tempHi = new Int32Array(16); + this._tempLo = new Int32Array(16); + this._buffer = new Uint8Array(256); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + this.reset(); + } + SHA5122.prototype._initState = function() { + this._stateHi[0] = 1779033703; + this._stateHi[1] = 3144134277; + this._stateHi[2] = 1013904242; + this._stateHi[3] = 2773480762; + this._stateHi[4] = 1359893119; + this._stateHi[5] = 2600822924; + this._stateHi[6] = 528734635; + this._stateHi[7] = 1541459225; + this._stateLo[0] = 4089235720; + this._stateLo[1] = 2227873595; + this._stateLo[2] = 4271175723; + this._stateLo[3] = 1595750129; + this._stateLo[4] = 2917565137; + this._stateLo[5] = 725511199; + this._stateLo[6] = 4215389547; + this._stateLo[7] = 327033209; + }; + SHA5122.prototype.reset = function() { + this._initState(); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + return this; + }; + SHA5122.prototype.clean = function() { + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._tempHi); + wipe_1.wipe(this._tempLo); + this.reset(); + }; + SHA5122.prototype.update = function(data, dataLength) { + if (dataLength === void 0) { + dataLength = data.length; + } + if (this._finished) { + throw new Error("SHA512: can't update because hash was finished."); + } + var dataPos = 0; + this._bytesHashed += dataLength; + if (this._bufferLength > 0) { + while (this._bufferLength < exports2.BLOCK_SIZE && dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + if (this._bufferLength === this.blockSize) { + hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize); + this._bufferLength = 0; + } + } + if (dataLength >= this.blockSize) { + dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength); + dataLength %= this.blockSize; + } + while (dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + return this; + }; + SHA5122.prototype.finish = function(out) { + if (!this._finished) { + var bytesHashed = this._bytesHashed; + var left = this._bufferLength; + var bitLenHi = bytesHashed / 536870912 | 0; + var bitLenLo = bytesHashed << 3; + var padLength = bytesHashed % 128 < 112 ? 128 : 256; + this._buffer[left] = 128; + for (var i2 = left + 1; i2 < padLength - 8; i2++) { + this._buffer[i2] = 0; + } + binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); + binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); + hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength); + this._finished = true; + } + for (var i2 = 0; i2 < this.digestLength / 8; i2++) { + binary_1.writeUint32BE(this._stateHi[i2], out, i2 * 8); + binary_1.writeUint32BE(this._stateLo[i2], out, i2 * 8 + 4); + } + return this; + }; + SHA5122.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + SHA5122.prototype.saveState = function() { + if (this._finished) { + throw new Error("SHA256: cannot save finished state"); + } + return { + stateHi: new Int32Array(this._stateHi), + stateLo: new Int32Array(this._stateLo), + buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, + bufferLength: this._bufferLength, + bytesHashed: this._bytesHashed + }; + }; + SHA5122.prototype.restoreState = function(savedState) { + this._stateHi.set(savedState.stateHi); + this._stateLo.set(savedState.stateLo); + this._bufferLength = savedState.bufferLength; + if (savedState.buffer) { + this._buffer.set(savedState.buffer); + } + this._bytesHashed = savedState.bytesHashed; + this._finished = false; + return this; + }; + SHA5122.prototype.cleanSavedState = function(savedState) { + wipe_1.wipe(savedState.stateHi); + wipe_1.wipe(savedState.stateLo); + if (savedState.buffer) { + wipe_1.wipe(savedState.buffer); + } + savedState.bufferLength = 0; + savedState.bytesHashed = 0; + }; + return SHA5122; + }() + ); + exports2.SHA512 = SHA512; + var K2 = new Int32Array([ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 + ]); + function hashBlocks(wh, wl, hh, hl, m3, pos, len) { + var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; + var h5, l4; + var th, tl; + var a3, b4, c4, d3; + while (len >= 128) { + for (var i2 = 0; i2 < 16; i2++) { + var j2 = 8 * i2 + pos; + wh[i2] = binary_1.readUint32BE(m3, j2); + wl[i2] = binary_1.readUint32BE(m3, j2 + 4); + } + for (var i2 = 0; i2 < 80; i2++) { + var bh0 = ah0; + var bh1 = ah1; + var bh2 = ah2; + var bh3 = ah3; + var bh4 = ah4; + var bh5 = ah5; + var bh6 = ah6; + var bh7 = ah7; + var bl0 = al0; + var bl1 = al1; + var bl2 = al2; + var bl3 = al3; + var bl4 = al4; + var bl5 = al5; + var bl6 = al6; + var bl7 = al7; + h5 = ah7; + l4 = al7; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); + l4 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = ah4 & ah5 ^ ~ah4 & ah6; + l4 = al4 & al5 ^ ~al4 & al6; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = K2[i2 * 2]; + l4 = K2[i2 * 2 + 1]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = wh[i2 % 16]; + l4 = wl[i2 % 16]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + th = c4 & 65535 | d3 << 16; + tl = a3 & 65535 | b4 << 16; + h5 = th; + l4 = tl; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); + l4 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; + l4 = al0 & al1 ^ al0 & al2 ^ al1 & al2; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + bh7 = c4 & 65535 | d3 << 16; + bl7 = a3 & 65535 | b4 << 16; + h5 = bh3; + l4 = bl3; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = th; + l4 = tl; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + bh3 = c4 & 65535 | d3 << 16; + bl3 = a3 & 65535 | b4 << 16; + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + if (i2 % 16 === 15) { + for (var j2 = 0; j2 < 16; j2++) { + h5 = wh[j2]; + l4 = wl[j2]; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = wh[(j2 + 9) % 16]; + l4 = wl[(j2 + 9) % 16]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + th = wh[(j2 + 1) % 16]; + tl = wl[(j2 + 1) % 16]; + h5 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; + l4 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + th = wh[(j2 + 14) % 16]; + tl = wl[(j2 + 14) % 16]; + h5 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; + l4 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + wh[j2] = c4 & 65535 | d3 << 16; + wl[j2] = a3 & 65535 | b4 << 16; + } + } + } + h5 = ah0; + l4 = al0; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[0]; + l4 = hl[0]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[0] = ah0 = c4 & 65535 | d3 << 16; + hl[0] = al0 = a3 & 65535 | b4 << 16; + h5 = ah1; + l4 = al1; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[1]; + l4 = hl[1]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[1] = ah1 = c4 & 65535 | d3 << 16; + hl[1] = al1 = a3 & 65535 | b4 << 16; + h5 = ah2; + l4 = al2; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[2]; + l4 = hl[2]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[2] = ah2 = c4 & 65535 | d3 << 16; + hl[2] = al2 = a3 & 65535 | b4 << 16; + h5 = ah3; + l4 = al3; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[3]; + l4 = hl[3]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[3] = ah3 = c4 & 65535 | d3 << 16; + hl[3] = al3 = a3 & 65535 | b4 << 16; + h5 = ah4; + l4 = al4; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[4]; + l4 = hl[4]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[4] = ah4 = c4 & 65535 | d3 << 16; + hl[4] = al4 = a3 & 65535 | b4 << 16; + h5 = ah5; + l4 = al5; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[5]; + l4 = hl[5]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[5] = ah5 = c4 & 65535 | d3 << 16; + hl[5] = al5 = a3 & 65535 | b4 << 16; + h5 = ah6; + l4 = al6; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[6]; + l4 = hl[6]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[6] = ah6 = c4 & 65535 | d3 << 16; + hl[6] = al6 = a3 & 65535 | b4 << 16; + h5 = ah7; + l4 = al7; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[7]; + l4 = hl[7]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[7] = ah7 = c4 & 65535 | d3 << 16; + hl[7] = al7 = a3 & 65535 | b4 << 16; + pos += 128; + len -= 128; + } + return pos; + } + function hash(data) { + var h5 = new SHA512(); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.hash = hash; + } +}); + +// node_modules/@stablelib/ed25519/lib/ed25519.js +var require_ed25519 = __commonJS({ + "node_modules/@stablelib/ed25519/lib/ed25519.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.convertSecretKeyToX25519 = exports2.convertPublicKeyToX25519 = exports2.verify = exports2.sign = exports2.extractPublicKeyFromSecretKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.SEED_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = exports2.SIGNATURE_LENGTH = void 0; + var random_1 = require_random(); + var sha512_1 = require_sha512(); + var wipe_1 = require_wipe(); + exports2.SIGNATURE_LENGTH = 64; + exports2.PUBLIC_KEY_LENGTH = 32; + exports2.SECRET_KEY_LENGTH = 64; + exports2.SEED_LENGTH = 32; + function gf(init) { + const r = new Float64Array(16); + if (init) { + for (let i2 = 0; i2 < init.length; i2++) { + r[i2] = init[i2]; + } + } + return r; + } + var _9 = new Uint8Array(32); + _9[0] = 9; + var gf0 = gf(); + var gf1 = gf([1]); + var D2 = gf([ + 30883, + 4953, + 19914, + 30187, + 55467, + 16705, + 2637, + 112, + 59544, + 30585, + 16505, + 36039, + 65139, + 11119, + 27886, + 20995 + ]); + var D22 = gf([ + 61785, + 9906, + 39828, + 60374, + 45398, + 33411, + 5274, + 224, + 53552, + 61171, + 33010, + 6542, + 64743, + 22239, + 55772, + 9222 + ]); + var X = gf([ + 54554, + 36645, + 11616, + 51542, + 42930, + 38181, + 51040, + 26924, + 56412, + 64982, + 57905, + 49316, + 21502, + 52590, + 14035, + 8553 + ]); + var Y = gf([ + 26200, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214 + ]); + var I2 = gf([ + 41136, + 18958, + 6951, + 50414, + 58488, + 44335, + 6150, + 12099, + 55207, + 15867, + 153, + 11085, + 57099, + 20417, + 9344, + 11139 + ]); + function set25519(r, a3) { + for (let i2 = 0; i2 < 16; i2++) { + r[i2] = a3[i2] | 0; + } + } + function car25519(o2) { + let c4 = 1; + for (let i2 = 0; i2 < 16; i2++) { + let v2 = o2[i2] + c4 + 65535; + c4 = Math.floor(v2 / 65536); + o2[i2] = v2 - c4 * 65536; + } + o2[0] += c4 - 1 + 37 * (c4 - 1); + } + function sel25519(p3, q2, b4) { + const c4 = ~(b4 - 1); + for (let i2 = 0; i2 < 16; i2++) { + const t = c4 & (p3[i2] ^ q2[i2]); + p3[i2] ^= t; + q2[i2] ^= t; + } + } + function pack25519(o2, n3) { + const m3 = gf(); + const t = gf(); + for (let i2 = 0; i2 < 16; i2++) { + t[i2] = n3[i2]; + } + car25519(t); + car25519(t); + car25519(t); + for (let j2 = 0; j2 < 2; j2++) { + m3[0] = t[0] - 65517; + for (let i2 = 1; i2 < 15; i2++) { + m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); + m3[i2 - 1] &= 65535; + } + m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); + const b4 = m3[15] >> 16 & 1; + m3[14] &= 65535; + sel25519(t, m3, 1 - b4); + } + for (let i2 = 0; i2 < 16; i2++) { + o2[2 * i2] = t[i2] & 255; + o2[2 * i2 + 1] = t[i2] >> 8; + } + } + function verify32(x3, y4) { + let d3 = 0; + for (let i2 = 0; i2 < 32; i2++) { + d3 |= x3[i2] ^ y4[i2]; + } + return (1 & d3 - 1 >>> 8) - 1; + } + function neq25519(a3, b4) { + const c4 = new Uint8Array(32); + const d3 = new Uint8Array(32); + pack25519(c4, a3); + pack25519(d3, b4); + return verify32(c4, d3); + } + function par25519(a3) { + const d3 = new Uint8Array(32); + pack25519(d3, a3); + return d3[0] & 1; + } + function unpack25519(o2, n3) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); + } + o2[15] &= 32767; + } + function add(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] + b4[i2]; + } + } + function sub(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] - b4[i2]; + } + } + function mul(o2, a3, b4) { + let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; + v2 = a3[0]; + t0 += v2 * b0; + t1 += v2 * b1; + t2 += v2 * b22; + t3 += v2 * b32; + t4 += v2 * b42; + t5 += v2 * b5; + t6 += v2 * b6; + t7 += v2 * b7; + t8 += v2 * b8; + t9 += v2 * b9; + t10 += v2 * b10; + t11 += v2 * b11; + t12 += v2 * b12; + t13 += v2 * b13; + t14 += v2 * b14; + t15 += v2 * b15; + v2 = a3[1]; + t1 += v2 * b0; + t2 += v2 * b1; + t3 += v2 * b22; + t4 += v2 * b32; + t5 += v2 * b42; + t6 += v2 * b5; + t7 += v2 * b6; + t8 += v2 * b7; + t9 += v2 * b8; + t10 += v2 * b9; + t11 += v2 * b10; + t12 += v2 * b11; + t13 += v2 * b12; + t14 += v2 * b13; + t15 += v2 * b14; + t16 += v2 * b15; + v2 = a3[2]; + t2 += v2 * b0; + t3 += v2 * b1; + t4 += v2 * b22; + t5 += v2 * b32; + t6 += v2 * b42; + t7 += v2 * b5; + t8 += v2 * b6; + t9 += v2 * b7; + t10 += v2 * b8; + t11 += v2 * b9; + t12 += v2 * b10; + t13 += v2 * b11; + t14 += v2 * b12; + t15 += v2 * b13; + t16 += v2 * b14; + t17 += v2 * b15; + v2 = a3[3]; + t3 += v2 * b0; + t4 += v2 * b1; + t5 += v2 * b22; + t6 += v2 * b32; + t7 += v2 * b42; + t8 += v2 * b5; + t9 += v2 * b6; + t10 += v2 * b7; + t11 += v2 * b8; + t12 += v2 * b9; + t13 += v2 * b10; + t14 += v2 * b11; + t15 += v2 * b12; + t16 += v2 * b13; + t17 += v2 * b14; + t18 += v2 * b15; + v2 = a3[4]; + t4 += v2 * b0; + t5 += v2 * b1; + t6 += v2 * b22; + t7 += v2 * b32; + t8 += v2 * b42; + t9 += v2 * b5; + t10 += v2 * b6; + t11 += v2 * b7; + t12 += v2 * b8; + t13 += v2 * b9; + t14 += v2 * b10; + t15 += v2 * b11; + t16 += v2 * b12; + t17 += v2 * b13; + t18 += v2 * b14; + t19 += v2 * b15; + v2 = a3[5]; + t5 += v2 * b0; + t6 += v2 * b1; + t7 += v2 * b22; + t8 += v2 * b32; + t9 += v2 * b42; + t10 += v2 * b5; + t11 += v2 * b6; + t12 += v2 * b7; + t13 += v2 * b8; + t14 += v2 * b9; + t15 += v2 * b10; + t16 += v2 * b11; + t17 += v2 * b12; + t18 += v2 * b13; + t19 += v2 * b14; + t20 += v2 * b15; + v2 = a3[6]; + t6 += v2 * b0; + t7 += v2 * b1; + t8 += v2 * b22; + t9 += v2 * b32; + t10 += v2 * b42; + t11 += v2 * b5; + t12 += v2 * b6; + t13 += v2 * b7; + t14 += v2 * b8; + t15 += v2 * b9; + t16 += v2 * b10; + t17 += v2 * b11; + t18 += v2 * b12; + t19 += v2 * b13; + t20 += v2 * b14; + t21 += v2 * b15; + v2 = a3[7]; + t7 += v2 * b0; + t8 += v2 * b1; + t9 += v2 * b22; + t10 += v2 * b32; + t11 += v2 * b42; + t12 += v2 * b5; + t13 += v2 * b6; + t14 += v2 * b7; + t15 += v2 * b8; + t16 += v2 * b9; + t17 += v2 * b10; + t18 += v2 * b11; + t19 += v2 * b12; + t20 += v2 * b13; + t21 += v2 * b14; + t22 += v2 * b15; + v2 = a3[8]; + t8 += v2 * b0; + t9 += v2 * b1; + t10 += v2 * b22; + t11 += v2 * b32; + t12 += v2 * b42; + t13 += v2 * b5; + t14 += v2 * b6; + t15 += v2 * b7; + t16 += v2 * b8; + t17 += v2 * b9; + t18 += v2 * b10; + t19 += v2 * b11; + t20 += v2 * b12; + t21 += v2 * b13; + t22 += v2 * b14; + t23 += v2 * b15; + v2 = a3[9]; + t9 += v2 * b0; + t10 += v2 * b1; + t11 += v2 * b22; + t12 += v2 * b32; + t13 += v2 * b42; + t14 += v2 * b5; + t15 += v2 * b6; + t16 += v2 * b7; + t17 += v2 * b8; + t18 += v2 * b9; + t19 += v2 * b10; + t20 += v2 * b11; + t21 += v2 * b12; + t22 += v2 * b13; + t23 += v2 * b14; + t24 += v2 * b15; + v2 = a3[10]; + t10 += v2 * b0; + t11 += v2 * b1; + t12 += v2 * b22; + t13 += v2 * b32; + t14 += v2 * b42; + t15 += v2 * b5; + t16 += v2 * b6; + t17 += v2 * b7; + t18 += v2 * b8; + t19 += v2 * b9; + t20 += v2 * b10; + t21 += v2 * b11; + t22 += v2 * b12; + t23 += v2 * b13; + t24 += v2 * b14; + t25 += v2 * b15; + v2 = a3[11]; + t11 += v2 * b0; + t12 += v2 * b1; + t13 += v2 * b22; + t14 += v2 * b32; + t15 += v2 * b42; + t16 += v2 * b5; + t17 += v2 * b6; + t18 += v2 * b7; + t19 += v2 * b8; + t20 += v2 * b9; + t21 += v2 * b10; + t22 += v2 * b11; + t23 += v2 * b12; + t24 += v2 * b13; + t25 += v2 * b14; + t26 += v2 * b15; + v2 = a3[12]; + t12 += v2 * b0; + t13 += v2 * b1; + t14 += v2 * b22; + t15 += v2 * b32; + t16 += v2 * b42; + t17 += v2 * b5; + t18 += v2 * b6; + t19 += v2 * b7; + t20 += v2 * b8; + t21 += v2 * b9; + t22 += v2 * b10; + t23 += v2 * b11; + t24 += v2 * b12; + t25 += v2 * b13; + t26 += v2 * b14; + t27 += v2 * b15; + v2 = a3[13]; + t13 += v2 * b0; + t14 += v2 * b1; + t15 += v2 * b22; + t16 += v2 * b32; + t17 += v2 * b42; + t18 += v2 * b5; + t19 += v2 * b6; + t20 += v2 * b7; + t21 += v2 * b8; + t22 += v2 * b9; + t23 += v2 * b10; + t24 += v2 * b11; + t25 += v2 * b12; + t26 += v2 * b13; + t27 += v2 * b14; + t28 += v2 * b15; + v2 = a3[14]; + t14 += v2 * b0; + t15 += v2 * b1; + t16 += v2 * b22; + t17 += v2 * b32; + t18 += v2 * b42; + t19 += v2 * b5; + t20 += v2 * b6; + t21 += v2 * b7; + t22 += v2 * b8; + t23 += v2 * b9; + t24 += v2 * b10; + t25 += v2 * b11; + t26 += v2 * b12; + t27 += v2 * b13; + t28 += v2 * b14; + t29 += v2 * b15; + v2 = a3[15]; + t15 += v2 * b0; + t16 += v2 * b1; + t17 += v2 * b22; + t18 += v2 * b32; + t19 += v2 * b42; + t20 += v2 * b5; + t21 += v2 * b6; + t22 += v2 * b7; + t23 += v2 * b8; + t24 += v2 * b9; + t25 += v2 * b10; + t26 += v2 * b11; + t27 += v2 * b12; + t28 += v2 * b13; + t29 += v2 * b14; + t30 += v2 * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + o2[0] = t0; + o2[1] = t1; + o2[2] = t2; + o2[3] = t3; + o2[4] = t4; + o2[5] = t5; + o2[6] = t6; + o2[7] = t7; + o2[8] = t8; + o2[9] = t9; + o2[10] = t10; + o2[11] = t11; + o2[12] = t12; + o2[13] = t13; + o2[14] = t14; + o2[15] = t15; + } + function square(o2, a3) { + mul(o2, a3, a3); + } + function inv25519(o2, i2) { + const c4 = gf(); + let a3; + for (a3 = 0; a3 < 16; a3++) { + c4[a3] = i2[a3]; + } + for (a3 = 253; a3 >= 0; a3--) { + square(c4, c4); + if (a3 !== 2 && a3 !== 4) { + mul(c4, c4, i2); + } + } + for (a3 = 0; a3 < 16; a3++) { + o2[a3] = c4[a3]; + } + } + function pow2523(o2, i2) { + const c4 = gf(); + let a3; + for (a3 = 0; a3 < 16; a3++) { + c4[a3] = i2[a3]; + } + for (a3 = 250; a3 >= 0; a3--) { + square(c4, c4); + if (a3 !== 1) { + mul(c4, c4, i2); + } + } + for (a3 = 0; a3 < 16; a3++) { + o2[a3] = c4[a3]; + } + } + function edadd(p3, q2) { + const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(), g3 = gf(), h5 = gf(), t = gf(); + sub(a3, p3[1], p3[0]); + sub(t, q2[1], q2[0]); + mul(a3, a3, t); + add(b4, p3[0], p3[1]); + add(t, q2[0], q2[1]); + mul(b4, b4, t); + mul(c4, p3[3], q2[3]); + mul(c4, c4, D22); + mul(d3, p3[2], q2[2]); + add(d3, d3, d3); + sub(e2, b4, a3); + sub(f4, d3, c4); + add(g3, d3, c4); + add(h5, b4, a3); + mul(p3[0], e2, f4); + mul(p3[1], h5, g3); + mul(p3[2], g3, f4); + mul(p3[3], e2, h5); + } + function cswap(p3, q2, b4) { + for (let i2 = 0; i2 < 4; i2++) { + sel25519(p3[i2], q2[i2], b4); + } + } + function pack(r, p3) { + const tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p3[2]); + mul(tx, p3[0], zi); + mul(ty, p3[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; + } + function scalarmult(p3, q2, s2) { + set25519(p3[0], gf0); + set25519(p3[1], gf1); + set25519(p3[2], gf1); + set25519(p3[3], gf0); + for (let i2 = 255; i2 >= 0; --i2) { + const b4 = s2[i2 / 8 | 0] >> (i2 & 7) & 1; + cswap(p3, q2, b4); + edadd(q2, p3); + edadd(p3, p3); + cswap(p3, q2, b4); + } + } + function scalarbase(p3, s2) { + const q2 = [gf(), gf(), gf(), gf()]; + set25519(q2[0], X); + set25519(q2[1], Y); + set25519(q2[2], gf1); + mul(q2[3], X, Y); + scalarmult(p3, q2, s2); + } + function generateKeyPairFromSeed2(seed) { + if (seed.length !== exports2.SEED_LENGTH) { + throw new Error(`ed25519: seed must be ${exports2.SEED_LENGTH} bytes`); + } + const d3 = (0, sha512_1.hash)(seed); + d3[0] &= 248; + d3[31] &= 127; + d3[31] |= 64; + const publicKey = new Uint8Array(32); + const p3 = [gf(), gf(), gf(), gf()]; + scalarbase(p3, d3); + pack(publicKey, p3); + const secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, 32); + return { + publicKey, + secretKey + }; + } + exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; + function generateKeyPair2(prng) { + const seed = (0, random_1.randomBytes)(32, prng); + const result = generateKeyPairFromSeed2(seed); + (0, wipe_1.wipe)(seed); + return result; + } + exports2.generateKeyPair = generateKeyPair2; + function extractPublicKeyFromSecretKey(secretKey) { + if (secretKey.length !== exports2.SECRET_KEY_LENGTH) { + throw new Error(`ed25519: secret key must be ${exports2.SECRET_KEY_LENGTH} bytes`); + } + return new Uint8Array(secretKey.subarray(32)); + } + exports2.extractPublicKeyFromSecretKey = extractPublicKeyFromSecretKey; + var L2 = new Float64Array([ + 237, + 211, + 245, + 92, + 26, + 99, + 18, + 88, + 214, + 156, + 247, + 162, + 222, + 249, + 222, + 20, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 16 + ]); + function modL(r, x3) { + let carry; + let i2; + let j2; + let k4; + for (i2 = 63; i2 >= 32; --i2) { + carry = 0; + for (j2 = i2 - 32, k4 = i2 - 12; j2 < k4; ++j2) { + x3[j2] += carry - 16 * x3[i2] * L2[j2 - (i2 - 32)]; + carry = Math.floor((x3[j2] + 128) / 256); + x3[j2] -= carry * 256; + } + x3[j2] += carry; + x3[i2] = 0; + } + carry = 0; + for (j2 = 0; j2 < 32; j2++) { + x3[j2] += carry - (x3[31] >> 4) * L2[j2]; + carry = x3[j2] >> 8; + x3[j2] &= 255; + } + for (j2 = 0; j2 < 32; j2++) { + x3[j2] -= carry * L2[j2]; + } + for (i2 = 0; i2 < 32; i2++) { + x3[i2 + 1] += x3[i2] >> 8; + r[i2] = x3[i2] & 255; + } + } + function reduce(r) { + const x3 = new Float64Array(64); + for (let i2 = 0; i2 < 64; i2++) { + x3[i2] = r[i2]; + } + for (let i2 = 0; i2 < 64; i2++) { + r[i2] = 0; + } + modL(r, x3); + } + function sign2(secretKey, message) { + const x3 = new Float64Array(64); + const p3 = [gf(), gf(), gf(), gf()]; + const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); + d3[0] &= 248; + d3[31] &= 127; + d3[31] |= 64; + const signature = new Uint8Array(64); + signature.set(d3.subarray(32), 32); + const hs = new sha512_1.SHA512(); + hs.update(signature.subarray(32)); + hs.update(message); + const r = hs.digest(); + hs.clean(); + reduce(r); + scalarbase(p3, r); + pack(signature, p3); + hs.reset(); + hs.update(signature.subarray(0, 32)); + hs.update(secretKey.subarray(32)); + hs.update(message); + const h5 = hs.digest(); + reduce(h5); + for (let i2 = 0; i2 < 32; i2++) { + x3[i2] = r[i2]; + } + for (let i2 = 0; i2 < 32; i2++) { + for (let j2 = 0; j2 < 32; j2++) { + x3[i2 + j2] += h5[i2] * d3[j2]; + } + } + modL(signature.subarray(32), x3); + return signature; + } + exports2.sign = sign2; + function unpackneg(r, p3) { + const t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p3); + square(num, r[1]); + mul(den, num, D2); + sub(num, num, r[2]); + add(den, r[2], den); + square(den2, den); + square(den4, den2); + mul(den6, den4, den2); + mul(t, den6, num); + mul(t, t, den); + pow2523(t, t); + mul(t, t, num); + mul(t, t, den); + mul(t, t, den); + mul(r[0], t, den); + square(chk, r[0]); + mul(chk, chk, den); + if (neq25519(chk, num)) { + mul(r[0], r[0], I2); + } + square(chk, r[0]); + mul(chk, chk, den); + if (neq25519(chk, num)) { + return -1; + } + if (par25519(r[0]) === p3[31] >> 7) { + sub(r[0], gf0, r[0]); + } + mul(r[3], r[0], r[1]); + return 0; + } + function verify2(publicKey, message, signature) { + const t = new Uint8Array(32); + const p3 = [gf(), gf(), gf(), gf()]; + const q2 = [gf(), gf(), gf(), gf()]; + if (signature.length !== exports2.SIGNATURE_LENGTH) { + throw new Error(`ed25519: signature must be ${exports2.SIGNATURE_LENGTH} bytes`); + } + if (unpackneg(q2, publicKey)) { + return false; + } + const hs = new sha512_1.SHA512(); + hs.update(signature.subarray(0, 32)); + hs.update(publicKey); + hs.update(message); + const h5 = hs.digest(); + reduce(h5); + scalarmult(p3, q2, h5); + scalarbase(q2, signature.subarray(32)); + edadd(p3, q2); + pack(t, p3); + if (verify32(signature, t)) { + return false; + } + return true; + } + exports2.verify = verify2; + function convertPublicKeyToX25519(publicKey) { + let q2 = [gf(), gf(), gf(), gf()]; + if (unpackneg(q2, publicKey)) { + throw new Error("Ed25519: invalid public key"); + } + let a3 = gf(); + let b4 = gf(); + let y4 = q2[1]; + add(a3, gf1, y4); + sub(b4, gf1, y4); + inv25519(b4, b4); + mul(a3, a3, b4); + let z3 = new Uint8Array(32); + pack25519(z3, a3); + return z3; + } + exports2.convertPublicKeyToX25519 = convertPublicKeyToX25519; + function convertSecretKeyToX25519(secretKey) { + const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); + d3[0] &= 248; + d3[31] &= 127; + d3[31] |= 64; + const o2 = new Uint8Array(d3.subarray(0, 32)); + (0, wipe_1.wipe)(d3); + return o2; + } + exports2.convertSecretKeyToX25519 = convertSecretKeyToX25519; + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/constants.js +var JWT_IRIDIUM_ALG, JWT_IRIDIUM_TYP, JWT_DELIMITER, JWT_ENCODING, JSON_ENCODING, DATA_ENCODING, DID_DELIMITER, DID_PREFIX, DID_METHOD, MULTICODEC_ED25519_ENCODING, MULTICODEC_ED25519_BASE, MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_LENGTH, KEY_PAIR_SEED_LENGTH; +var init_constants = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/constants.js"() { + init_shim(); + JWT_IRIDIUM_ALG = "EdDSA"; + JWT_IRIDIUM_TYP = "JWT"; + JWT_DELIMITER = "."; + JWT_ENCODING = "base64url"; + JSON_ENCODING = "utf8"; + DATA_ENCODING = "utf8"; + DID_DELIMITER = ":"; + DID_PREFIX = "did"; + DID_METHOD = "key"; + MULTICODEC_ED25519_ENCODING = "base58btc"; + MULTICODEC_ED25519_BASE = "z"; + MULTICODEC_ED25519_HEADER = "K36"; + MULTICODEC_ED25519_LENGTH = 32; + KEY_PAIR_SEED_LENGTH = 32; + } +}); + +// node_modules/uint8arrays/esm/src/util/as-uint8array.js +function asUint8Array(buf) { + if (globalThis.Buffer != null) { + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + return buf; +} +var init_as_uint8array = __esm({ + "node_modules/uint8arrays/esm/src/util/as-uint8array.js"() { + init_shim(); + } +}); + +// node_modules/uint8arrays/esm/src/alloc.js +function allocUnsafe(size = 0) { + if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) { + return asUint8Array(globalThis.Buffer.allocUnsafe(size)); + } + return new Uint8Array(size); +} +var init_alloc = __esm({ + "node_modules/uint8arrays/esm/src/alloc.js"() { + init_shim(); + init_as_uint8array(); + } +}); + +// node_modules/uint8arrays/esm/src/concat.js +function concat(arrays, length2) { + if (!length2) { + length2 = arrays.reduce((acc, curr) => acc + curr.length, 0); + } + const output = allocUnsafe(length2); + let offset = 0; + for (const arr of arrays) { + output.set(arr, offset); + offset += arr.length; + } + return asUint8Array(output); +} +var init_concat = __esm({ + "node_modules/uint8arrays/esm/src/concat.js"() { + init_shim(); + init_alloc(); + init_as_uint8array(); + } +}); + +// node_modules/multiformats/esm/vendor/base-x.js +function base(ALPHABET, name2) { + if (ALPHABET.length >= 255) { + throw new TypeError("Alphabet too long"); + } + var BASE_MAP = new Uint8Array(256); + for (var j2 = 0; j2 < BASE_MAP.length; j2++) { + BASE_MAP[j2] = 255; + } + for (var i2 = 0; i2 < ALPHABET.length; i2++) { + var x3 = ALPHABET.charAt(i2); + var xc = x3.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { + throw new TypeError(x3 + " is ambiguous"); + } + BASE_MAP[xc] = i2; + } + var BASE2 = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE2) / Math.log(256); + var iFACTOR = Math.log(256) / Math.log(BASE2); + function encode5(source) { + if (source instanceof Uint8Array) + ; + else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + } else if (Array.isArray(source)) { + source = Uint8Array.from(source); + } + if (!(source instanceof Uint8Array)) { + throw new TypeError("Expected Uint8Array"); + } + if (source.length === 0) { + return ""; + } + var zeroes = 0; + var length2 = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); + while (pbegin !== pend) { + var carry = source[pbegin]; + var i3 = 0; + for (var it1 = size - 1; (carry !== 0 || i3 < length2) && it1 !== -1; it1--, i3++) { + carry += 256 * b58[it1] >>> 0; + b58[it1] = carry % BASE2 >>> 0; + carry = carry / BASE2 >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length2 = i3; + pbegin++; + } + var it2 = size - length2; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { + str += ALPHABET.charAt(b58[it2]); + } + return str; + } + function decodeUnsafe(source) { + if (typeof source !== "string") { + throw new TypeError("Expected String"); + } + if (source.length === 0) { + return new Uint8Array(); + } + var psz = 0; + if (source[psz] === " ") { + return; + } + var zeroes = 0; + var length2 = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + var size = (source.length - psz) * FACTOR + 1 >>> 0; + var b256 = new Uint8Array(size); + while (source[psz]) { + var carry = BASE_MAP[source.charCodeAt(psz)]; + if (carry === 255) { + return; + } + var i3 = 0; + for (var it3 = size - 1; (carry !== 0 || i3 < length2) && it3 !== -1; it3--, i3++) { + carry += BASE2 * b256[it3] >>> 0; + b256[it3] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length2 = i3; + psz++; + } + if (source[psz] === " ") { + return; + } + var it4 = size - length2; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = new Uint8Array(zeroes + (size - it4)); + var j3 = zeroes; + while (it4 !== size) { + vch[j3++] = b256[it4++]; + } + return vch; + } + function decode6(string2) { + var buffer = decodeUnsafe(string2); + if (buffer) { + return buffer; + } + throw new Error(`Non-${name2} character`); + } + return { + encode: encode5, + decodeUnsafe, + decode: decode6 + }; +} +var src, _brrp__multiformats_scope_baseX, base_x_default; +var init_base_x = __esm({ + "node_modules/multiformats/esm/vendor/base-x.js"() { + init_shim(); + src = base; + _brrp__multiformats_scope_baseX = src; + base_x_default = _brrp__multiformats_scope_baseX; + } +}); + +// node_modules/multiformats/esm/src/bytes.js +var empty, equals, coerce, fromString, toString; +var init_bytes = __esm({ + "node_modules/multiformats/esm/src/bytes.js"() { + init_shim(); + empty = new Uint8Array(0); + equals = (aa, bb) => { + if (aa === bb) + return true; + if (aa.byteLength !== bb.byteLength) { + return false; + } + for (let ii = 0; ii < aa.byteLength; ii++) { + if (aa[ii] !== bb[ii]) { + return false; + } + } + return true; + }; + coerce = (o2) => { + if (o2 instanceof Uint8Array && o2.constructor.name === "Uint8Array") + return o2; + if (o2 instanceof ArrayBuffer) + return new Uint8Array(o2); + if (ArrayBuffer.isView(o2)) { + return new Uint8Array(o2.buffer, o2.byteOffset, o2.byteLength); + } + throw new Error("Unknown type, must be binary type"); + }; + fromString = (str) => new TextEncoder().encode(str); + toString = (b4) => new TextDecoder().decode(b4); + } +}); + +// node_modules/multiformats/esm/src/bases/base.js +var Encoder, Decoder, ComposedDecoder, or, Codec, from, baseX, decode, encode, rfc4648; +var init_base = __esm({ + "node_modules/multiformats/esm/src/bases/base.js"() { + init_shim(); + init_base_x(); + init_bytes(); + Encoder = class { + constructor(name2, prefix, baseEncode) { + this.name = name2; + this.prefix = prefix; + this.baseEncode = baseEncode; + } + encode(bytes) { + if (bytes instanceof Uint8Array) { + return `${this.prefix}${this.baseEncode(bytes)}`; + } else { + throw Error("Unknown type, must be binary type"); + } + } + }; + Decoder = class { + constructor(name2, prefix, baseDecode) { + this.name = name2; + this.prefix = prefix; + if (prefix.codePointAt(0) === void 0) { + throw new Error("Invalid prefix character"); + } + this.prefixCodePoint = prefix.codePointAt(0); + this.baseDecode = baseDecode; + } + decode(text) { + if (typeof text === "string") { + if (text.codePointAt(0) !== this.prefixCodePoint) { + throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); + } + return this.baseDecode(text.slice(this.prefix.length)); + } else { + throw Error("Can only multibase decode strings"); + } + } + or(decoder) { + return or(this, decoder); + } + }; + ComposedDecoder = class { + constructor(decoders) { + this.decoders = decoders; + } + or(decoder) { + return or(this, decoder); + } + decode(input) { + const prefix = input[0]; + const decoder = this.decoders[prefix]; + if (decoder) { + return decoder.decode(input); + } else { + throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + } + } + }; + or = (left, right) => new ComposedDecoder({ + ...left.decoders || { [left.prefix]: left }, + ...right.decoders || { [right.prefix]: right } + }); + Codec = class { + constructor(name2, prefix, baseEncode, baseDecode) { + this.name = name2; + this.prefix = prefix; + this.baseEncode = baseEncode; + this.baseDecode = baseDecode; + this.encoder = new Encoder(name2, prefix, baseEncode); + this.decoder = new Decoder(name2, prefix, baseDecode); + } + encode(input) { + return this.encoder.encode(input); + } + decode(input) { + return this.decoder.decode(input); + } + }; + from = ({ name: name2, prefix, encode: encode5, decode: decode6 }) => new Codec(name2, prefix, encode5, decode6); + baseX = ({ prefix, name: name2, alphabet: alphabet2 }) => { + const { encode: encode5, decode: decode6 } = base_x_default(alphabet2, name2); + return from({ + prefix, + name: name2, + encode: encode5, + decode: (text) => coerce(decode6(text)) + }); + }; + decode = (string2, alphabet2, bitsPerChar, name2) => { + const codes = {}; + for (let i2 = 0; i2 < alphabet2.length; ++i2) { + codes[alphabet2[i2]] = i2; + } + let end = string2.length; + while (string2[end - 1] === "=") { + --end; + } + const out = new Uint8Array(end * bitsPerChar / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for (let i2 = 0; i2 < end; ++i2) { + const value = codes[string2[i2]]; + if (value === void 0) { + throw new SyntaxError(`Non-${name2} character`); + } + buffer = buffer << bitsPerChar | value; + bits += bitsPerChar; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; + }; + encode = (data, alphabet2, bitsPerChar) => { + const pad = alphabet2[alphabet2.length - 1] === "="; + const mask = (1 << bitsPerChar) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for (let i2 = 0; i2 < data.length; ++i2) { + buffer = buffer << 8 | data[i2]; + bits += 8; + while (bits > bitsPerChar) { + bits -= bitsPerChar; + out += alphabet2[mask & buffer >> bits]; + } + } + if (bits) { + out += alphabet2[mask & buffer << bitsPerChar - bits]; + } + if (pad) { + while (out.length * bitsPerChar & 7) { + out += "="; + } + } + return out; + }; + rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) => { + return from({ + prefix, + name: name2, + encode(input) { + return encode(input, alphabet2, bitsPerChar); + }, + decode(input) { + return decode(input, alphabet2, bitsPerChar, name2); + } + }); + }; + } +}); + +// node_modules/multiformats/esm/src/bases/identity.js +var identity_exports = {}; +__export(identity_exports, { + identity: () => identity +}); +var identity; +var init_identity = __esm({ + "node_modules/multiformats/esm/src/bases/identity.js"() { + init_shim(); + init_base(); + init_bytes(); + identity = from({ + prefix: "\0", + name: "identity", + encode: (buf) => toString(buf), + decode: (str) => fromString(str) + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base2.js +var base2_exports = {}; +__export(base2_exports, { + base2: () => base2 +}); +var base2; +var init_base2 = __esm({ + "node_modules/multiformats/esm/src/bases/base2.js"() { + init_shim(); + init_base(); + base2 = rfc4648({ + prefix: "0", + name: "base2", + alphabet: "01", + bitsPerChar: 1 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base8.js +var base8_exports = {}; +__export(base8_exports, { + base8: () => base8 +}); +var base8; +var init_base8 = __esm({ + "node_modules/multiformats/esm/src/bases/base8.js"() { + init_shim(); + init_base(); + base8 = rfc4648({ + prefix: "7", + name: "base8", + alphabet: "01234567", + bitsPerChar: 3 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base10.js +var base10_exports = {}; +__export(base10_exports, { + base10: () => base10 +}); +var base10; +var init_base10 = __esm({ + "node_modules/multiformats/esm/src/bases/base10.js"() { + init_shim(); + init_base(); + base10 = baseX({ + prefix: "9", + name: "base10", + alphabet: "0123456789" + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base16.js +var base16_exports = {}; +__export(base16_exports, { + base16: () => base16, + base16upper: () => base16upper +}); +var base16, base16upper; +var init_base16 = __esm({ + "node_modules/multiformats/esm/src/bases/base16.js"() { + init_shim(); + init_base(); + base16 = rfc4648({ + prefix: "f", + name: "base16", + alphabet: "0123456789abcdef", + bitsPerChar: 4 + }); + base16upper = rfc4648({ + prefix: "F", + name: "base16upper", + alphabet: "0123456789ABCDEF", + bitsPerChar: 4 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base32.js +var base32_exports = {}; +__export(base32_exports, { + base32: () => base32, + base32hex: () => base32hex, + base32hexpad: () => base32hexpad, + base32hexpadupper: () => base32hexpadupper, + base32hexupper: () => base32hexupper, + base32pad: () => base32pad, + base32padupper: () => base32padupper, + base32upper: () => base32upper, + base32z: () => base32z +}); +var base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z; +var init_base32 = __esm({ + "node_modules/multiformats/esm/src/bases/base32.js"() { + init_shim(); + init_base(); + base32 = rfc4648({ + prefix: "b", + name: "base32", + alphabet: "abcdefghijklmnopqrstuvwxyz234567", + bitsPerChar: 5 + }); + base32upper = rfc4648({ + prefix: "B", + name: "base32upper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + bitsPerChar: 5 + }); + base32pad = rfc4648({ + prefix: "c", + name: "base32pad", + alphabet: "abcdefghijklmnopqrstuvwxyz234567=", + bitsPerChar: 5 + }); + base32padupper = rfc4648({ + prefix: "C", + name: "base32padupper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", + bitsPerChar: 5 + }); + base32hex = rfc4648({ + prefix: "v", + name: "base32hex", + alphabet: "0123456789abcdefghijklmnopqrstuv", + bitsPerChar: 5 + }); + base32hexupper = rfc4648({ + prefix: "V", + name: "base32hexupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + bitsPerChar: 5 + }); + base32hexpad = rfc4648({ + prefix: "t", + name: "base32hexpad", + alphabet: "0123456789abcdefghijklmnopqrstuv=", + bitsPerChar: 5 + }); + base32hexpadupper = rfc4648({ + prefix: "T", + name: "base32hexpadupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", + bitsPerChar: 5 + }); + base32z = rfc4648({ + prefix: "h", + name: "base32z", + alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", + bitsPerChar: 5 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base36.js +var base36_exports = {}; +__export(base36_exports, { + base36: () => base36, + base36upper: () => base36upper +}); +var base36, base36upper; +var init_base36 = __esm({ + "node_modules/multiformats/esm/src/bases/base36.js"() { + init_shim(); + init_base(); + base36 = baseX({ + prefix: "k", + name: "base36", + alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" + }); + base36upper = baseX({ + prefix: "K", + name: "base36upper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base58.js +var base58_exports = {}; +__export(base58_exports, { + base58btc: () => base58btc, + base58flickr: () => base58flickr +}); +var base58btc, base58flickr; +var init_base58 = __esm({ + "node_modules/multiformats/esm/src/bases/base58.js"() { + init_shim(); + init_base(); + base58btc = baseX({ + name: "base58btc", + prefix: "z", + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + }); + base58flickr = baseX({ + name: "base58flickr", + prefix: "Z", + alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base64.js +var base64_exports = {}; +__export(base64_exports, { + base64: () => base64, + base64pad: () => base64pad, + base64url: () => base64url, + base64urlpad: () => base64urlpad +}); +var base64, base64pad, base64url, base64urlpad; +var init_base64 = __esm({ + "node_modules/multiformats/esm/src/bases/base64.js"() { + init_shim(); + init_base(); + base64 = rfc4648({ + prefix: "m", + name: "base64", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", + bitsPerChar: 6 + }); + base64pad = rfc4648({ + prefix: "M", + name: "base64pad", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + bitsPerChar: 6 + }); + base64url = rfc4648({ + prefix: "u", + name: "base64url", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + bitsPerChar: 6 + }); + base64urlpad = rfc4648({ + prefix: "U", + name: "base64urlpad", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", + bitsPerChar: 6 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base256emoji.js +var base256emoji_exports = {}; +__export(base256emoji_exports, { + base256emoji: () => base256emoji +}); +function encode2(data) { + return data.reduce((p3, c4) => { + p3 += alphabetBytesToChars[c4]; + return p3; + }, ""); +} +function decode2(str) { + const byts = []; + for (const char of str) { + const byt = alphabetCharsToBytes[char.codePointAt(0)]; + if (byt === void 0) { + throw new Error(`Non-base256emoji character: ${char}`); + } + byts.push(byt); + } + return new Uint8Array(byts); +} +var alphabet, alphabetBytesToChars, alphabetCharsToBytes, base256emoji; +var init_base256emoji = __esm({ + "node_modules/multiformats/esm/src/bases/base256emoji.js"() { + init_shim(); + init_base(); + alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); + alphabetBytesToChars = alphabet.reduce((p3, c4, i2) => { + p3[i2] = c4; + return p3; + }, []); + alphabetCharsToBytes = alphabet.reduce((p3, c4, i2) => { + p3[c4.codePointAt(0)] = i2; + return p3; + }, []); + base256emoji = from({ + prefix: "\u{1F680}", + name: "base256emoji", + encode: encode2, + decode: decode2 + }); + } +}); + +// node_modules/multiformats/esm/vendor/varint.js +function encode3(num, out, offset) { + out = out || []; + offset = offset || 0; + var oldOffset = offset; + while (num >= INT) { + out[offset++] = num & 255 | MSB; + num /= 128; + } + while (num & MSBALL) { + out[offset++] = num & 255 | MSB; + num >>>= 7; + } + out[offset] = num | 0; + encode3.bytes = offset - oldOffset + 1; + return out; +} +function read(buf, offset) { + var res = 0, offset = offset || 0, shift = 0, counter = offset, b4, l4 = buf.length; + do { + if (counter >= l4) { + read.bytes = 0; + throw new RangeError("Could not decode varint"); + } + b4 = buf[counter++]; + res += shift < 28 ? (b4 & REST$1) << shift : (b4 & REST$1) * Math.pow(2, shift); + shift += 7; + } while (b4 >= MSB$1); + read.bytes = counter - offset; + return res; +} +var encode_1, MSB, REST, MSBALL, INT, decode3, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default; +var init_varint = __esm({ + "node_modules/multiformats/esm/vendor/varint.js"() { + init_shim(); + encode_1 = encode3; + MSB = 128; + REST = 127; + MSBALL = ~REST; + INT = Math.pow(2, 31); + decode3 = read; + MSB$1 = 128; + REST$1 = 127; + N1 = Math.pow(2, 7); + N2 = Math.pow(2, 14); + N3 = Math.pow(2, 21); + N4 = Math.pow(2, 28); + N5 = Math.pow(2, 35); + N6 = Math.pow(2, 42); + N7 = Math.pow(2, 49); + N8 = Math.pow(2, 56); + N9 = Math.pow(2, 63); + length = function(value) { + return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; + }; + varint = { + encode: encode_1, + decode: decode3, + encodingLength: length + }; + _brrp_varint = varint; + varint_default = _brrp_varint; + } +}); + +// node_modules/multiformats/esm/src/varint.js +var decode4, encodeTo, encodingLength; +var init_varint2 = __esm({ + "node_modules/multiformats/esm/src/varint.js"() { + init_shim(); + init_varint(); + decode4 = (data, offset = 0) => { + const code2 = varint_default.decode(data, offset); + return [ + code2, + varint_default.decode.bytes + ]; + }; + encodeTo = (int, target, offset = 0) => { + varint_default.encode(int, target, offset); + return target; + }; + encodingLength = (int) => { + return varint_default.encodingLength(int); + }; + } +}); + +// node_modules/multiformats/esm/src/hashes/digest.js +var create, decode5, equals2, Digest; +var init_digest = __esm({ + "node_modules/multiformats/esm/src/hashes/digest.js"() { + init_shim(); + init_bytes(); + init_varint2(); + create = (code2, digest2) => { + const size = digest2.byteLength; + const sizeOffset = encodingLength(code2); + const digestOffset = sizeOffset + encodingLength(size); + const bytes = new Uint8Array(digestOffset + size); + encodeTo(code2, bytes, 0); + encodeTo(size, bytes, sizeOffset); + bytes.set(digest2, digestOffset); + return new Digest(code2, size, digest2, bytes); + }; + decode5 = (multihash) => { + const bytes = coerce(multihash); + const [code2, sizeOffset] = decode4(bytes); + const [size, digestOffset] = decode4(bytes.subarray(sizeOffset)); + const digest2 = bytes.subarray(sizeOffset + digestOffset); + if (digest2.byteLength !== size) { + throw new Error("Incorrect length"); + } + return new Digest(code2, size, digest2, bytes); + }; + equals2 = (a3, b4) => { + if (a3 === b4) { + return true; + } else { + return a3.code === b4.code && a3.size === b4.size && equals(a3.bytes, b4.bytes); + } + }; + Digest = class { + constructor(code2, size, digest2, bytes) { + this.code = code2; + this.size = size; + this.digest = digest2; + this.bytes = bytes; + } + }; + } +}); + +// node_modules/multiformats/esm/src/hashes/hasher.js +var from2, Hasher; +var init_hasher = __esm({ + "node_modules/multiformats/esm/src/hashes/hasher.js"() { + init_shim(); + init_digest(); + from2 = ({ name: name2, code: code2, encode: encode5 }) => new Hasher(name2, code2, encode5); + Hasher = class { + constructor(name2, code2, encode5) { + this.name = name2; + this.code = code2; + this.encode = encode5; + } + digest(input) { + if (input instanceof Uint8Array) { + const result = this.encode(input); + return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2)); + } else { + throw Error("Unknown type, must be binary type"); + } + } + }; + } +}); + +// node_modules/multiformats/esm/src/hashes/sha2-browser.js +var sha2_browser_exports = {}; +__export(sha2_browser_exports, { + sha256: () => sha256, + sha512: () => sha512 +}); +var sha, sha256, sha512; +var init_sha2_browser = __esm({ + "node_modules/multiformats/esm/src/hashes/sha2-browser.js"() { + init_shim(); + init_hasher(); + sha = (name2) => async (data) => new Uint8Array(await crypto.subtle.digest(name2, data)); + sha256 = from2({ + name: "sha2-256", + code: 18, + encode: sha("SHA-256") + }); + sha512 = from2({ + name: "sha2-512", + code: 19, + encode: sha("SHA-512") + }); + } +}); + +// node_modules/multiformats/esm/src/hashes/identity.js +var identity_exports2 = {}; +__export(identity_exports2, { + identity: () => identity2 +}); +var code, name, encode4, digest, identity2; +var init_identity2 = __esm({ + "node_modules/multiformats/esm/src/hashes/identity.js"() { + init_shim(); + init_bytes(); + init_digest(); + code = 0; + name = "identity"; + encode4 = coerce; + digest = (input) => create(code, encode4(input)); + identity2 = { + code, + name, + encode: encode4, + digest + }; + } +}); + +// node_modules/multiformats/esm/src/codecs/raw.js +var init_raw = __esm({ + "node_modules/multiformats/esm/src/codecs/raw.js"() { + init_shim(); + init_bytes(); + } +}); + +// node_modules/multiformats/esm/src/codecs/json.js +var textEncoder, textDecoder; +var init_json = __esm({ + "node_modules/multiformats/esm/src/codecs/json.js"() { + init_shim(); + textEncoder = new TextEncoder(); + textDecoder = new TextDecoder(); + } +}); + +// node_modules/multiformats/esm/src/cid.js +var CID, parseCIDtoBytes, toStringV0, toStringV1, DAG_PB_CODE, SHA_256_CODE, encodeCID, cidSymbol, readonly, hidden, version, deprecate, IS_CID_DEPRECATION; +var init_cid = __esm({ + "node_modules/multiformats/esm/src/cid.js"() { + init_shim(); + init_varint2(); + init_digest(); + init_base58(); + init_base32(); + init_bytes(); + CID = class _CID { + constructor(version2, code2, multihash, bytes) { + this.code = code2; + this.version = version2; + this.multihash = multihash; + this.bytes = bytes; + this.byteOffset = bytes.byteOffset; + this.byteLength = bytes.byteLength; + this.asCID = this; + this._baseCache = /* @__PURE__ */ new Map(); + Object.defineProperties(this, { + byteOffset: hidden, + byteLength: hidden, + code: readonly, + version: readonly, + multihash: readonly, + bytes: readonly, + _baseCache: hidden, + asCID: hidden + }); + } + toV0() { + switch (this.version) { + case 0: { + return this; + } + default: { + const { code: code2, multihash } = this; + if (code2 !== DAG_PB_CODE) { + throw new Error("Cannot convert a non dag-pb CID to CIDv0"); + } + if (multihash.code !== SHA_256_CODE) { + throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); + } + return _CID.createV0(multihash); + } + } + } + toV1() { + switch (this.version) { + case 0: { + const { code: code2, digest: digest2 } = this.multihash; + const multihash = create(code2, digest2); + return _CID.createV1(this.code, multihash); + } + case 1: { + return this; + } + default: { + throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); + } + } + } + equals(other) { + return other && this.code === other.code && this.version === other.version && equals2(this.multihash, other.multihash); + } + toString(base3) { + const { bytes, version: version2, _baseCache } = this; + switch (version2) { + case 0: + return toStringV0(bytes, _baseCache, base3 || base58btc.encoder); + default: + return toStringV1(bytes, _baseCache, base3 || base32.encoder); + } + } + toJSON() { + return { + code: this.code, + version: this.version, + hash: this.multihash.bytes + }; + } + get [Symbol.toStringTag]() { + return "CID"; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return "CID(" + this.toString() + ")"; + } + static isCID(value) { + deprecate(/^0\.0/, IS_CID_DEPRECATION); + return !!(value && (value[cidSymbol] || value.asCID === value)); + } + get toBaseEncodedString() { + throw new Error("Deprecated, use .toString()"); + } + get codec() { + throw new Error('"codec" property is deprecated, use integer "code" property instead'); + } + get buffer() { + throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); + } + get multibaseName() { + throw new Error('"multibaseName" property is deprecated'); + } + get prefix() { + throw new Error('"prefix" property is deprecated'); + } + static asCID(value) { + if (value instanceof _CID) { + return value; + } else if (value != null && value.asCID === value) { + const { version: version2, code: code2, multihash, bytes } = value; + return new _CID(version2, code2, multihash, bytes || encodeCID(version2, code2, multihash.bytes)); + } else if (value != null && value[cidSymbol] === true) { + const { version: version2, multihash, code: code2 } = value; + const digest2 = decode5(multihash); + return _CID.create(version2, code2, digest2); + } else { + return null; + } + } + static create(version2, code2, digest2) { + if (typeof code2 !== "number") { + throw new Error("String codecs are no longer supported"); + } + switch (version2) { + case 0: { + if (code2 !== DAG_PB_CODE) { + throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); + } else { + return new _CID(version2, code2, digest2, digest2.bytes); + } + } + case 1: { + const bytes = encodeCID(version2, code2, digest2.bytes); + return new _CID(version2, code2, digest2, bytes); + } + default: { + throw new Error("Invalid version"); + } + } + } + static createV0(digest2) { + return _CID.create(0, DAG_PB_CODE, digest2); + } + static createV1(code2, digest2) { + return _CID.create(1, code2, digest2); + } + static decode(bytes) { + const [cid, remainder] = _CID.decodeFirst(bytes); + if (remainder.length) { + throw new Error("Incorrect length"); + } + return cid; + } + static decodeFirst(bytes) { + const specs = _CID.inspectBytes(bytes); + const prefixSize = specs.size - specs.multihashSize; + const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); + if (multihashBytes.byteLength !== specs.multihashSize) { + throw new Error("Incorrect length"); + } + const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); + const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); + const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2); + return [ + cid, + bytes.subarray(specs.size) + ]; + } + static inspectBytes(initialBytes) { + let offset = 0; + const next = () => { + const [i2, length2] = decode4(initialBytes.subarray(offset)); + offset += length2; + return i2; + }; + let version2 = next(); + let codec = DAG_PB_CODE; + if (version2 === 18) { + version2 = 0; + offset = 0; + } else if (version2 === 1) { + codec = next(); + } + if (version2 !== 0 && version2 !== 1) { + throw new RangeError(`Invalid CID version ${version2}`); + } + const prefixSize = offset; + const multihashCode = next(); + const digestSize = next(); + const size = offset + digestSize; + const multihashSize = size - prefixSize; + return { + version: version2, + codec, + multihashCode, + digestSize, + multihashSize, + size + }; + } + static parse(source, base3) { + const [prefix, bytes] = parseCIDtoBytes(source, base3); + const cid = _CID.decode(bytes); + cid._baseCache.set(prefix, source); + return cid; + } + }; + parseCIDtoBytes = (source, base3) => { + switch (source[0]) { + case "Q": { + const decoder = base3 || base58btc; + return [ + base58btc.prefix, + decoder.decode(`${base58btc.prefix}${source}`) + ]; + } + case base58btc.prefix: { + const decoder = base3 || base58btc; + return [ + base58btc.prefix, + decoder.decode(source) + ]; + } + case base32.prefix: { + const decoder = base3 || base32; + return [ + base32.prefix, + decoder.decode(source) + ]; + } + default: { + if (base3 == null) { + throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); + } + return [ + source[0], + base3.decode(source) + ]; + } + } + }; + toStringV0 = (bytes, cache, base3) => { + const { prefix } = base3; + if (prefix !== base58btc.prefix) { + throw Error(`Cannot string encode V0 in ${base3.name} encoding`); + } + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base3.encode(bytes).slice(1); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } + }; + toStringV1 = (bytes, cache, base3) => { + const { prefix } = base3; + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base3.encode(bytes); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } + }; + DAG_PB_CODE = 112; + SHA_256_CODE = 18; + encodeCID = (version2, code2, multihash) => { + const codeOffset = encodingLength(version2); + const hashOffset = codeOffset + encodingLength(code2); + const bytes = new Uint8Array(hashOffset + multihash.byteLength); + encodeTo(version2, bytes, 0); + encodeTo(code2, bytes, codeOffset); + bytes.set(multihash, hashOffset); + return bytes; + }; + cidSymbol = Symbol.for("@ipld/js-cid/CID"); + readonly = { + writable: false, + configurable: false, + enumerable: true + }; + hidden = { + writable: false, + enumerable: false, + configurable: false + }; + version = "0.0.0-dev"; + deprecate = (range, message) => { + if (range.test(version)) { + console.warn(message); + } else { + throw new Error(message); + } + }; + IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: -if (CID.isCID(value)) { - doSomethingWithCID(value) +if (CID.isCID(value)) { + doSomethingWithCID(value) +} + +Is replaced with: + +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) +} +`; + } +}); + +// node_modules/multiformats/esm/src/index.js +var init_src = __esm({ + "node_modules/multiformats/esm/src/index.js"() { + init_shim(); + init_cid(); + init_varint2(); + init_bytes(); + init_hasher(); + init_digest(); + } +}); + +// node_modules/multiformats/esm/src/basics.js +var bases, hashes; +var init_basics = __esm({ + "node_modules/multiformats/esm/src/basics.js"() { + init_shim(); + init_identity(); + init_base2(); + init_base8(); + init_base10(); + init_base16(); + init_base32(); + init_base36(); + init_base58(); + init_base64(); + init_base256emoji(); + init_sha2_browser(); + init_identity2(); + init_raw(); + init_json(); + init_src(); + bases = { + ...identity_exports, + ...base2_exports, + ...base8_exports, + ...base10_exports, + ...base16_exports, + ...base32_exports, + ...base36_exports, + ...base58_exports, + ...base64_exports, + ...base256emoji_exports + }; + hashes = { + ...sha2_browser_exports, + ...identity_exports2 + }; + } +}); + +// node_modules/uint8arrays/esm/src/util/bases.js +function createCodec(name2, prefix, encode5, decode6) { + return { + name: name2, + prefix, + encoder: { + name: name2, + prefix, + encode: encode5 + }, + decoder: { decode: decode6 } + }; +} +var string, ascii, BASES, bases_default; +var init_bases = __esm({ + "node_modules/uint8arrays/esm/src/util/bases.js"() { + init_shim(); + init_basics(); + init_alloc(); + string = createCodec("utf8", "u", (buf) => { + const decoder = new TextDecoder("utf8"); + return "u" + decoder.decode(buf); + }, (str) => { + const encoder = new TextEncoder(); + return encoder.encode(str.substring(1)); + }); + ascii = createCodec("ascii", "a", (buf) => { + let string2 = "a"; + for (let i2 = 0; i2 < buf.length; i2++) { + string2 += String.fromCharCode(buf[i2]); + } + return string2; + }, (str) => { + str = str.substring(1); + const buf = allocUnsafe(str.length); + for (let i2 = 0; i2 < str.length; i2++) { + buf[i2] = str.charCodeAt(i2); + } + return buf; + }); + BASES = { + utf8: string, + "utf-8": string, + hex: bases.base16, + latin1: ascii, + ascii, + binary: ascii, + ...bases + }; + bases_default = BASES; + } +}); + +// node_modules/uint8arrays/esm/src/to-string.js +function toString2(array, encoding = "utf8") { + const base3 = bases_default[encoding]; + if (!base3) { + throw new Error(`Unsupported encoding "${encoding}"`); + } + if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { + return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); + } + return base3.encoder.encode(array).substring(1); +} +var init_to_string = __esm({ + "node_modules/uint8arrays/esm/src/to-string.js"() { + init_shim(); + init_bases(); + } +}); + +// node_modules/uint8arrays/esm/src/from-string.js +function fromString2(string2, encoding = "utf8") { + const base3 = bases_default[encoding]; + if (!base3) { + throw new Error(`Unsupported encoding "${encoding}"`); + } + if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { + return asUint8Array(globalThis.Buffer.from(string2, "utf-8")); + } + return base3.decoder.decode(`${base3.prefix}${string2}`); +} +var init_from_string = __esm({ + "node_modules/uint8arrays/esm/src/from-string.js"() { + init_shim(); + init_bases(); + init_as_uint8array(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/utils.js +function decodeJSON(str) { + return safeJsonParse(toString2(fromString2(str, JWT_ENCODING), JSON_ENCODING)); +} +function encodeJSON(val) { + return toString2(fromString2(safeJsonStringify(val), JSON_ENCODING), JWT_ENCODING); +} +function encodeIss(publicKey) { + const header = fromString2(MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_ENCODING); + const multicodec = MULTICODEC_ED25519_BASE + toString2(concat([header, publicKey]), MULTICODEC_ED25519_ENCODING); + return [DID_PREFIX, DID_METHOD, multicodec].join(DID_DELIMITER); +} +function decodeIss(issuer) { + const [prefix, method, multicodec] = issuer.split(DID_DELIMITER); + if (prefix !== DID_PREFIX || method !== DID_METHOD) { + throw new Error(`Issuer must be a DID with method "key"`); + } + const base3 = multicodec.slice(0, 1); + if (base3 !== MULTICODEC_ED25519_BASE) { + throw new Error(`Issuer must be a key in mulicodec format`); + } + const bytes = fromString2(multicodec.slice(1), MULTICODEC_ED25519_ENCODING); + const type = toString2(bytes.slice(0, 2), MULTICODEC_ED25519_ENCODING); + if (type !== MULTICODEC_ED25519_HEADER) { + throw new Error(`Issuer must be a public key with type "Ed25519"`); + } + const publicKey = bytes.slice(2); + if (publicKey.length !== MULTICODEC_ED25519_LENGTH) { + throw new Error(`Issuer must be a public key with length 32 bytes`); + } + return publicKey; +} +function encodeSig(bytes) { + return toString2(bytes, JWT_ENCODING); +} +function decodeSig(encoded) { + return fromString2(encoded, JWT_ENCODING); +} +function encodeData(params) { + return fromString2([encodeJSON(params.header), encodeJSON(params.payload)].join(JWT_DELIMITER), DATA_ENCODING); +} +function decodeData(data) { + const params = toString2(data, DATA_ENCODING).split(JWT_DELIMITER); + const header = decodeJSON(params[0]); + const payload = decodeJSON(params[1]); + return { header, payload }; +} +function encodeJWT(params) { + return [ + encodeJSON(params.header), + encodeJSON(params.payload), + encodeSig(params.signature) + ].join(JWT_DELIMITER); +} +function decodeJWT(jwt) { + const params = jwt.split(JWT_DELIMITER); + const header = decodeJSON(params[0]); + const payload = decodeJSON(params[1]); + const signature = decodeSig(params[2]); + const data = fromString2(params.slice(0, 2).join(JWT_DELIMITER), DATA_ENCODING); + return { header, payload, signature, data }; +} +var init_utils = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/utils.js"() { + init_shim(); + init_concat(); + init_to_string(); + init_from_string(); + init_esm(); + init_constants(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/api.js +function generateKeyPair(seed = (0, import_random.randomBytes)(KEY_PAIR_SEED_LENGTH)) { + return ed25519.generateKeyPairFromSeed(seed); +} +async function signJWT(sub, aud, ttl, keyPair, iat = (0, import_time.fromMiliseconds)(Date.now())) { + const header = { alg: JWT_IRIDIUM_ALG, typ: JWT_IRIDIUM_TYP }; + const iss = encodeIss(keyPair.publicKey); + const exp = iat + ttl; + const payload = { iss, sub, aud, iat, exp }; + const data = encodeData({ header, payload }); + const signature = ed25519.sign(keyPair.secretKey, data); + return encodeJWT({ header, payload, signature }); +} +async function verifyJWT(jwt) { + const { header, payload, data, signature } = decodeJWT(jwt); + if (header.alg !== JWT_IRIDIUM_ALG || header.typ !== JWT_IRIDIUM_TYP) { + throw new Error("JWT must use EdDSA algorithm"); + } + const publicKey = decodeIss(payload.iss); + return ed25519.verify(publicKey, data, signature); +} +var ed25519, import_random, import_time; +var init_api = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/api.js"() { + init_shim(); + ed25519 = __toESM(require_ed25519()); + import_random = __toESM(require_random()); + import_time = __toESM(require_cjs()); + init_constants(); + init_utils(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/types.js +var init_types = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/types.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/index.js +var esm_exports3 = {}; +__export(esm_exports3, { + DATA_ENCODING: () => DATA_ENCODING, + DID_DELIMITER: () => DID_DELIMITER, + DID_METHOD: () => DID_METHOD, + DID_PREFIX: () => DID_PREFIX, + JSON_ENCODING: () => JSON_ENCODING, + JWT_DELIMITER: () => JWT_DELIMITER, + JWT_ENCODING: () => JWT_ENCODING, + JWT_IRIDIUM_ALG: () => JWT_IRIDIUM_ALG, + JWT_IRIDIUM_TYP: () => JWT_IRIDIUM_TYP, + KEY_PAIR_SEED_LENGTH: () => KEY_PAIR_SEED_LENGTH, + MULTICODEC_ED25519_BASE: () => MULTICODEC_ED25519_BASE, + MULTICODEC_ED25519_ENCODING: () => MULTICODEC_ED25519_ENCODING, + MULTICODEC_ED25519_HEADER: () => MULTICODEC_ED25519_HEADER, + MULTICODEC_ED25519_LENGTH: () => MULTICODEC_ED25519_LENGTH, + decodeData: () => decodeData, + decodeIss: () => decodeIss, + decodeJSON: () => decodeJSON, + decodeJWT: () => decodeJWT, + decodeSig: () => decodeSig, + encodeData: () => encodeData, + encodeIss: () => encodeIss, + encodeJSON: () => encodeJSON, + encodeJWT: () => encodeJWT, + encodeSig: () => encodeSig, + generateKeyPair: () => generateKeyPair, + signJWT: () => signJWT, + verifyJWT: () => verifyJWT +}); +var init_esm3 = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/index.js"() { + init_shim(); + init_api(); + init_constants(); + init_types(); + init_utils(); + } +}); + +// node_modules/detect-browser/index.js +var require_detect_browser = __commonJS({ + "node_modules/detect-browser/index.js"(exports2) { + "use strict"; + init_shim(); + var __spreadArray = exports2 && exports2.__spreadArray || function(to, from3, pack) { + if (pack || arguments.length === 2) + for (var i2 = 0, l4 = from3.length, ar; i2 < l4; i2++) { + if (ar || !(i2 in from3)) { + if (!ar) + ar = Array.prototype.slice.call(from3, 0, i2); + ar[i2] = from3[i2]; + } + } + return to.concat(ar || Array.prototype.slice.call(from3)); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getNodeVersion = exports2.detectOS = exports2.parseUserAgent = exports2.browserName = exports2.detect = exports2.ReactNativeInfo = exports2.BotInfo = exports2.SearchBotDeviceInfo = exports2.NodeInfo = exports2.BrowserInfo = void 0; + var BrowserInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function BrowserInfo2(name2, version2, os) { + this.name = name2; + this.version = version2; + this.os = os; + this.type = "browser"; + } + return BrowserInfo2; + }() + ); + exports2.BrowserInfo = BrowserInfo; + var NodeInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function NodeInfo2(version2) { + this.version = version2; + this.type = "node"; + this.name = "node"; + this.os = import_process.default.platform; + } + return NodeInfo2; + }() + ); + exports2.NodeInfo = NodeInfo; + var SearchBotDeviceInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function SearchBotDeviceInfo2(name2, version2, os, bot) { + this.name = name2; + this.version = version2; + this.os = os; + this.bot = bot; + this.type = "bot-device"; + } + return SearchBotDeviceInfo2; + }() + ); + exports2.SearchBotDeviceInfo = SearchBotDeviceInfo; + var BotInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function BotInfo2() { + this.type = "bot"; + this.bot = true; + this.name = "bot"; + this.version = null; + this.os = null; + } + return BotInfo2; + }() + ); + exports2.BotInfo = BotInfo; + var ReactNativeInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function ReactNativeInfo2() { + this.type = "react-native"; + this.name = "react-native"; + this.version = null; + this.os = null; + } + return ReactNativeInfo2; + }() + ); + exports2.ReactNativeInfo = ReactNativeInfo; + var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/; + var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/; + var REQUIRED_VERSION_PARTS = 3; + var userAgentRules = [ + ["aol", /AOLShield\/([0-9\._]+)/], + ["edge", /Edge\/([0-9\._]+)/], + ["edge-ios", /EdgiOS\/([0-9\._]+)/], + ["yandexbrowser", /YaBrowser\/([0-9\._]+)/], + ["kakaotalk", /KAKAOTALK\s([0-9\.]+)/], + ["samsung", /SamsungBrowser\/([0-9\.]+)/], + ["silk", /\bSilk\/([0-9._-]+)\b/], + ["miui", /MiuiBrowser\/([0-9\.]+)$/], + ["beaker", /BeakerBrowser\/([0-9\.]+)/], + ["edge-chromium", /EdgA?\/([0-9\.]+)/], + [ + "chromium-webview", + /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ + ], + ["chrome", /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], + ["phantomjs", /PhantomJS\/([0-9\.]+)(:?\s|$)/], + ["crios", /CriOS\/([0-9\.]+)(:?\s|$)/], + ["firefox", /Firefox\/([0-9\.]+)(?:\s|$)/], + ["fxios", /FxiOS\/([0-9\.]+)/], + ["opera-mini", /Opera Mini.*Version\/([0-9\.]+)/], + ["opera", /Opera\/([0-9\.]+)(?:\s|$)/], + ["opera", /OPR\/([0-9\.]+)(:?\s|$)/], + ["pie", /^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/], + ["pie", /^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/], + ["netfront", /^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/], + ["ie", /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], + ["ie", /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], + ["ie", /MSIE\s(7\.0)/], + ["bb10", /BB10;\sTouch.*Version\/([0-9\.]+)/], + ["android", /Android\s([0-9\.]+)/], + ["ios", /Version\/([0-9\._]+).*Mobile.*Safari.*/], + ["safari", /Version\/([0-9\._]+).*Safari/], + ["facebook", /FB[AS]V\/([0-9\.]+)/], + ["instagram", /Instagram\s([0-9\.]+)/], + ["ios-webview", /AppleWebKit\/([0-9\.]+).*Mobile/], + ["ios-webview", /AppleWebKit\/([0-9\.]+).*Gecko\)$/], + ["curl", /^curl\/([0-9\.]+)$/], + ["searchbot", SEARCHBOX_UA_REGEX] + ]; + var operatingSystemRules = [ + ["iOS", /iP(hone|od|ad)/], + ["Android OS", /Android/], + ["BlackBerry OS", /BlackBerry|BB10/], + ["Windows Mobile", /IEMobile/], + ["Amazon OS", /Kindle/], + ["Windows 3.11", /Win16/], + ["Windows 95", /(Windows 95)|(Win95)|(Windows_95)/], + ["Windows 98", /(Windows 98)|(Win98)/], + ["Windows 2000", /(Windows NT 5.0)|(Windows 2000)/], + ["Windows XP", /(Windows NT 5.1)|(Windows XP)/], + ["Windows Server 2003", /(Windows NT 5.2)/], + ["Windows Vista", /(Windows NT 6.0)/], + ["Windows 7", /(Windows NT 6.1)/], + ["Windows 8", /(Windows NT 6.2)/], + ["Windows 8.1", /(Windows NT 6.3)/], + ["Windows 10", /(Windows NT 10.0)/], + ["Windows ME", /Windows ME/], + ["Windows CE", /Windows CE|WinCE|Microsoft Pocket Internet Explorer/], + ["Open BSD", /OpenBSD/], + ["Sun OS", /SunOS/], + ["Chrome OS", /CrOS/], + ["Linux", /(Linux)|(X11)/], + ["Mac OS", /(Mac_PowerPC)|(Macintosh)/], + ["QNX", /QNX/], + ["BeOS", /BeOS/], + ["OS/2", /OS\/2/] + ]; + function detect(userAgent) { + if (!!userAgent) { + return parseUserAgent(userAgent); + } + if (typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative") { + return new ReactNativeInfo(); + } + if (typeof navigator !== "undefined") { + return parseUserAgent(navigator.userAgent); + } + return getNodeVersion(); + } + exports2.detect = detect; + function matchUserAgent(ua) { + return ua !== "" && userAgentRules.reduce(function(matched, _a) { + var browser = _a[0], regex = _a[1]; + if (matched) { + return matched; + } + var uaMatch = regex.exec(ua); + return !!uaMatch && [browser, uaMatch]; + }, false); + } + function browserName(ua) { + var data = matchUserAgent(ua); + return data ? data[0] : null; + } + exports2.browserName = browserName; + function parseUserAgent(ua) { + var matchedRule = matchUserAgent(ua); + if (!matchedRule) { + return null; + } + var name2 = matchedRule[0], match = matchedRule[1]; + if (name2 === "searchbot") { + return new BotInfo(); + } + var versionParts = match[1] && match[1].split(".").join("_").split("_").slice(0, 3); + if (versionParts) { + if (versionParts.length < REQUIRED_VERSION_PARTS) { + versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true); + } + } else { + versionParts = []; + } + var version2 = versionParts.join("."); + var os = detectOS(ua); + var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua); + if (searchBotMatch && searchBotMatch[1]) { + return new SearchBotDeviceInfo(name2, version2, os, searchBotMatch[1]); + } + return new BrowserInfo(name2, version2, os); + } + exports2.parseUserAgent = parseUserAgent; + function detectOS(ua) { + for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) { + var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1]; + var match = regex.exec(ua); + if (match) { + return os; + } + } + return null; + } + exports2.detectOS = detectOS; + function getNodeVersion() { + var isNode2 = typeof import_process.default !== "undefined" && import_process.default.version; + return isNode2 ? new NodeInfo(import_process.default.version.slice(1)) : null; + } + exports2.getNodeVersion = getNodeVersion; + function createVersionParts(count) { + var output = []; + for (var ii = 0; ii < count; ii++) { + output.push("0"); + } + return output; + } + } +}); + +// node_modules/@walletconnect/window-getters/dist/cjs/index.js +var require_cjs3 = __commonJS({ + "node_modules/@walletconnect/window-getters/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getLocalStorage = exports2.getLocalStorageOrThrow = exports2.getCrypto = exports2.getCryptoOrThrow = exports2.getLocation = exports2.getLocationOrThrow = exports2.getNavigator = exports2.getNavigatorOrThrow = exports2.getDocument = exports2.getDocumentOrThrow = exports2.getFromWindowOrThrow = exports2.getFromWindow = void 0; + function getFromWindow(name2) { + let res = void 0; + if (typeof window !== "undefined" && typeof window[name2] !== "undefined") { + res = window[name2]; + } + return res; + } + exports2.getFromWindow = getFromWindow; + function getFromWindowOrThrow(name2) { + const res = getFromWindow(name2); + if (!res) { + throw new Error(`${name2} is not defined in Window`); + } + return res; + } + exports2.getFromWindowOrThrow = getFromWindowOrThrow; + function getDocumentOrThrow() { + return getFromWindowOrThrow("document"); + } + exports2.getDocumentOrThrow = getDocumentOrThrow; + function getDocument() { + return getFromWindow("document"); + } + exports2.getDocument = getDocument; + function getNavigatorOrThrow() { + return getFromWindowOrThrow("navigator"); + } + exports2.getNavigatorOrThrow = getNavigatorOrThrow; + function getNavigator() { + return getFromWindow("navigator"); + } + exports2.getNavigator = getNavigator; + function getLocationOrThrow() { + return getFromWindowOrThrow("location"); + } + exports2.getLocationOrThrow = getLocationOrThrow; + function getLocation() { + return getFromWindow("location"); + } + exports2.getLocation = getLocation; + function getCryptoOrThrow() { + return getFromWindowOrThrow("crypto"); + } + exports2.getCryptoOrThrow = getCryptoOrThrow; + function getCrypto() { + return getFromWindow("crypto"); + } + exports2.getCrypto = getCrypto; + function getLocalStorageOrThrow() { + return getFromWindowOrThrow("localStorage"); + } + exports2.getLocalStorageOrThrow = getLocalStorageOrThrow; + function getLocalStorage() { + return getFromWindow("localStorage"); + } + exports2.getLocalStorage = getLocalStorage; + } +}); + +// node_modules/@walletconnect/window-metadata/dist/cjs/index.js +var require_cjs4 = __commonJS({ + "node_modules/@walletconnect/window-metadata/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getWindowMetadata = void 0; + var window_getters_1 = require_cjs3(); + function getWindowMetadata() { + let doc; + let loc; + try { + doc = window_getters_1.getDocumentOrThrow(); + loc = window_getters_1.getLocationOrThrow(); + } catch (e2) { + return null; + } + function getIcons() { + const links = doc.getElementsByTagName("link"); + const icons2 = []; + for (let i2 = 0; i2 < links.length; i2++) { + const link = links[i2]; + const rel = link.getAttribute("rel"); + if (rel) { + if (rel.toLowerCase().indexOf("icon") > -1) { + const href = link.getAttribute("href"); + if (href) { + if (href.toLowerCase().indexOf("https:") === -1 && href.toLowerCase().indexOf("http:") === -1 && href.indexOf("//") !== 0) { + let absoluteHref = loc.protocol + "//" + loc.host; + if (href.indexOf("/") === 0) { + absoluteHref += href; + } else { + const path = loc.pathname.split("/"); + path.pop(); + const finalPath = path.join("/"); + absoluteHref += finalPath + "/" + href; + } + icons2.push(absoluteHref); + } else if (href.indexOf("//") === 0) { + const absoluteUrl = loc.protocol + href; + icons2.push(absoluteUrl); + } else { + icons2.push(href); + } + } + } + } + } + return icons2; + } + function getWindowMetadataOfAny(...args) { + const metaTags = doc.getElementsByTagName("meta"); + for (let i2 = 0; i2 < metaTags.length; i2++) { + const tag = metaTags[i2]; + const attributes = ["itemprop", "property", "name"].map((target) => tag.getAttribute(target)).filter((attr) => { + if (attr) { + return args.includes(attr); + } + return false; + }); + if (attributes.length && attributes) { + const content = tag.getAttribute("content"); + if (content) { + return content; + } + } + } + return ""; + } + function getName() { + let name3 = getWindowMetadataOfAny("name", "og:site_name", "og:title", "twitter:title"); + if (!name3) { + name3 = doc.title; + } + return name3; + } + function getDescription() { + const description2 = getWindowMetadataOfAny("description", "og:description", "twitter:description", "keywords"); + return description2; + } + const name2 = getName(); + const description = getDescription(); + const url = loc.origin; + const icons = getIcons(); + const meta = { + description, + url, + icons, + name: name2 + }; + return meta; + } + exports2.getWindowMetadata = getWindowMetadata; + } +}); + +// node_modules/strict-uri-encode/index.js +var require_strict_uri_encode = __commonJS({ + "node_modules/strict-uri-encode/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (x3) => `%${x3.charCodeAt(0).toString(16).toUpperCase()}`); + } +}); + +// node_modules/decode-uri-component/index.js +var require_decode_uri_component = __commonJS({ + "node_modules/decode-uri-component/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var token = "%[a-f0-9]{2}"; + var singleMatcher = new RegExp("(" + token + ")|([^%]+?)", "gi"); + var multiMatcher = new RegExp("(" + token + ")+", "gi"); + function decodeComponents(components, split) { + try { + return [decodeURIComponent(components.join(""))]; + } catch (err) { + } + if (components.length === 1) { + return components; + } + split = split || 1; + var left = components.slice(0, split); + var right = components.slice(split); + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); + } + function decode6(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher) || []; + for (var i2 = 1; i2 < tokens.length; i2++) { + input = decodeComponents(tokens, i2).join(""); + tokens = input.match(singleMatcher) || []; + } + return input; + } + } + function customDecodeURIComponent(input) { + var replaceMap = { + "%FE%FF": "\uFFFD\uFFFD", + "%FF%FE": "\uFFFD\uFFFD" + }; + var match = multiMatcher.exec(input); + while (match) { + try { + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode6(match[0]); + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } + match = multiMatcher.exec(input); + } + replaceMap["%C2"] = "\uFFFD"; + var entries = Object.keys(replaceMap); + for (var i2 = 0; i2 < entries.length; i2++) { + var key = entries[i2]; + input = input.replace(new RegExp(key, "g"), replaceMap[key]); + } + return input; + } + module2.exports = function(encodedURI) { + if (typeof encodedURI !== "string") { + throw new TypeError("Expected `encodedURI` to be of type `string`, got `" + typeof encodedURI + "`"); + } + try { + encodedURI = encodedURI.replace(/\+/g, " "); + return decodeURIComponent(encodedURI); + } catch (err) { + return customDecodeURIComponent(encodedURI); + } + }; + } +}); + +// node_modules/split-on-first/index.js +var require_split_on_first = __commonJS({ + "node_modules/split-on-first/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = (string2, separator) => { + if (!(typeof string2 === "string" && typeof separator === "string")) { + throw new TypeError("Expected the arguments to be of type `string`"); + } + if (separator === "") { + return [string2]; + } + const separatorIndex = string2.indexOf(separator); + if (separatorIndex === -1) { + return [string2]; + } + return [ + string2.slice(0, separatorIndex), + string2.slice(separatorIndex + separator.length) + ]; + }; + } +}); + +// node_modules/filter-obj/index.js +var require_filter_obj = __commonJS({ + "node_modules/filter-obj/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function(obj, predicate) { + var ret = {}; + var keys2 = Object.keys(obj); + var isArr = Array.isArray(predicate); + for (var i2 = 0; i2 < keys2.length; i2++) { + var key = keys2[i2]; + var val = obj[key]; + if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) { + ret[key] = val; + } + } + return ret; + }; + } +}); + +// node_modules/query-string/index.js +var require_query_string = __commonJS({ + "node_modules/query-string/index.js"(exports2) { + "use strict"; + init_shim(); + var strictUriEncode = require_strict_uri_encode(); + var decodeComponent = require_decode_uri_component(); + var splitOnFirst = require_split_on_first(); + var filterObject = require_filter_obj(); + var isNullOrUndefined = (value) => value === null || value === void 0; + var encodeFragmentIdentifier = Symbol("encodeFragmentIdentifier"); + function encoderForArrayFormat(options) { + switch (options.arrayFormat) { + case "index": + return (key) => (result, value) => { + const index = result.length; + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, [encode5(key, options), "[", index, "]"].join("")]; + } + return [ + ...result, + [encode5(key, options), "[", encode5(index, options), "]=", encode5(value, options)].join("") + ]; + }; + case "bracket": + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, [encode5(key, options), "[]"].join("")]; + } + return [...result, [encode5(key, options), "[]=", encode5(value, options)].join("")]; + }; + case "colon-list-separator": + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, [encode5(key, options), ":list="].join("")]; + } + return [...result, [encode5(key, options), ":list=", encode5(value, options)].join("")]; + }; + case "comma": + case "separator": + case "bracket-separator": { + const keyValueSep = options.arrayFormat === "bracket-separator" ? "[]=" : "="; + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + value = value === null ? "" : value; + if (result.length === 0) { + return [[encode5(key, options), keyValueSep, encode5(value, options)].join("")]; + } + return [[result, encode5(value, options)].join(options.arrayFormatSeparator)]; + }; + } + default: + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, encode5(key, options)]; + } + return [...result, [encode5(key, options), "=", encode5(value, options)].join("")]; + }; + } + } + function parserForArrayFormat(options) { + let result; + switch (options.arrayFormat) { + case "index": + return (key, value, accumulator) => { + result = /\[(\d*)\]$/.exec(key); + key = key.replace(/\[\d*\]$/, ""); + if (!result) { + accumulator[key] = value; + return; + } + if (accumulator[key] === void 0) { + accumulator[key] = {}; + } + accumulator[key][result[1]] = value; + }; + case "bracket": + return (key, value, accumulator) => { + result = /(\[\])$/.exec(key); + key = key.replace(/\[\]$/, ""); + if (!result) { + accumulator[key] = value; + return; + } + if (accumulator[key] === void 0) { + accumulator[key] = [value]; + return; + } + accumulator[key] = [].concat(accumulator[key], value); + }; + case "colon-list-separator": + return (key, value, accumulator) => { + result = /(:list)$/.exec(key); + key = key.replace(/:list$/, ""); + if (!result) { + accumulator[key] = value; + return; + } + if (accumulator[key] === void 0) { + accumulator[key] = [value]; + return; + } + accumulator[key] = [].concat(accumulator[key], value); + }; + case "comma": + case "separator": + return (key, value, accumulator) => { + const isArray = typeof value === "string" && value.includes(options.arrayFormatSeparator); + const isEncodedArray = typeof value === "string" && !isArray && decode6(value, options).includes(options.arrayFormatSeparator); + value = isEncodedArray ? decode6(value, options) : value; + const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)) : value === null ? value : decode6(value, options); + accumulator[key] = newValue; + }; + case "bracket-separator": + return (key, value, accumulator) => { + const isArray = /(\[\])$/.test(key); + key = key.replace(/\[\]$/, ""); + if (!isArray) { + accumulator[key] = value ? decode6(value, options) : value; + return; + } + const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)); + if (accumulator[key] === void 0) { + accumulator[key] = arrayValue; + return; + } + accumulator[key] = [].concat(accumulator[key], arrayValue); + }; + default: + return (key, value, accumulator) => { + if (accumulator[key] === void 0) { + accumulator[key] = value; + return; + } + accumulator[key] = [].concat(accumulator[key], value); + }; + } + } + function validateArrayFormatSeparator(value) { + if (typeof value !== "string" || value.length !== 1) { + throw new TypeError("arrayFormatSeparator must be single character string"); + } + } + function encode5(value, options) { + if (options.encode) { + return options.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + return value; + } + function decode6(value, options) { + if (options.decode) { + return decodeComponent(value); + } + return value; + } + function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } + if (typeof input === "object") { + return keysSorter(Object.keys(input)).sort((a3, b4) => Number(a3) - Number(b4)).map((key) => input[key]); + } + return input; + } + function removeHash(input) { + const hashStart = input.indexOf("#"); + if (hashStart !== -1) { + input = input.slice(0, hashStart); + } + return input; + } + function getHash(url) { + let hash = ""; + const hashStart = url.indexOf("#"); + if (hashStart !== -1) { + hash = url.slice(hashStart); + } + return hash; + } + function extract(input) { + input = removeHash(input); + const queryStart = input.indexOf("?"); + if (queryStart === -1) { + return ""; + } + return input.slice(queryStart + 1); + } + function parseValue(value, options) { + if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === "string" && value.trim() !== "")) { + value = Number(value); + } else if (options.parseBooleans && value !== null && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) { + value = value.toLowerCase() === "true"; + } + return value; + } + function parse(query, options) { + options = Object.assign({ + decode: true, + sort: true, + arrayFormat: "none", + arrayFormatSeparator: ",", + parseNumbers: false, + parseBooleans: false + }, options); + validateArrayFormatSeparator(options.arrayFormatSeparator); + const formatter = parserForArrayFormat(options); + const ret = /* @__PURE__ */ Object.create(null); + if (typeof query !== "string") { + return ret; + } + query = query.trim().replace(/^[?#&]/, ""); + if (!query) { + return ret; + } + for (const param of query.split("&")) { + if (param === "") { + continue; + } + let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, " ") : param, "="); + value = value === void 0 ? null : ["comma", "separator", "bracket-separator"].includes(options.arrayFormat) ? value : decode6(value, options); + formatter(decode6(key, options), value, ret); + } + for (const key of Object.keys(ret)) { + const value = ret[key]; + if (typeof value === "object" && value !== null) { + for (const k4 of Object.keys(value)) { + value[k4] = parseValue(value[k4], options); + } + } else { + ret[key] = parseValue(value, options); + } + } + if (options.sort === false) { + return ret; + } + return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { + const value = ret[key]; + if (Boolean(value) && typeof value === "object" && !Array.isArray(value)) { + result[key] = keysSorter(value); + } else { + result[key] = value; + } + return result; + }, /* @__PURE__ */ Object.create(null)); + } + exports2.extract = extract; + exports2.parse = parse; + exports2.stringify = (object, options) => { + if (!object) { + return ""; + } + options = Object.assign({ + encode: true, + strict: true, + arrayFormat: "none", + arrayFormatSeparator: "," + }, options); + validateArrayFormatSeparator(options.arrayFormatSeparator); + const shouldFilter = (key) => options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === ""; + const formatter = encoderForArrayFormat(options); + const objectCopy = {}; + for (const key of Object.keys(object)) { + if (!shouldFilter(key)) { + objectCopy[key] = object[key]; + } + } + const keys2 = Object.keys(objectCopy); + if (options.sort !== false) { + keys2.sort(options.sort); + } + return keys2.map((key) => { + const value = object[key]; + if (value === void 0) { + return ""; + } + if (value === null) { + return encode5(key, options); + } + if (Array.isArray(value)) { + if (value.length === 0 && options.arrayFormat === "bracket-separator") { + return encode5(key, options) + "[]"; + } + return value.reduce(formatter(key), []).join("&"); + } + return encode5(key, options) + "=" + encode5(value, options); + }).filter((x3) => x3.length > 0).join("&"); + }; + exports2.parseUrl = (url, options) => { + options = Object.assign({ + decode: true + }, options); + const [url_, hash] = splitOnFirst(url, "#"); + return Object.assign( + { + url: url_.split("?")[0] || "", + query: parse(extract(url), options) + }, + options && options.parseFragmentIdentifier && hash ? { fragmentIdentifier: decode6(hash, options) } : {} + ); + }; + exports2.stringifyUrl = (object, options) => { + options = Object.assign({ + encode: true, + strict: true, + [encodeFragmentIdentifier]: true + }, options); + const url = removeHash(object.url).split("?")[0] || ""; + const queryFromUrl = exports2.extract(object.url); + const parsedQueryFromUrl = exports2.parse(queryFromUrl, { sort: false }); + const query = Object.assign(parsedQueryFromUrl, object.query); + let queryString = exports2.stringify(query, options); + if (queryString) { + queryString = `?${queryString}`; + } + let hash = getHash(object.url); + if (object.fragmentIdentifier) { + hash = `#${options[encodeFragmentIdentifier] ? encode5(object.fragmentIdentifier, options) : object.fragmentIdentifier}`; + } + return `${url}${queryString}${hash}`; + }; + exports2.pick = (input, filter, options) => { + options = Object.assign({ + parseFragmentIdentifier: true, + [encodeFragmentIdentifier]: false + }, options); + const { url, query, fragmentIdentifier } = exports2.parseUrl(input, options); + return exports2.stringifyUrl({ + url, + query: filterObject(query, filter), + fragmentIdentifier + }, options); + }; + exports2.exclude = (input, filter, options) => { + const exclusionFilter = Array.isArray(filter) ? (key) => !filter.includes(key) : (key, value) => !filter(key, value); + return exports2.pick(input, exclusionFilter, options); + }; + } +}); + +// node_modules/@stablelib/chacha/lib/chacha.js +var require_chacha = __commonJS({ + "node_modules/@stablelib/chacha/lib/chacha.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + var ROUNDS = 20; + function core(out, input, key) { + var j0 = 1634760805; + var j1 = 857760878; + var j2 = 2036477234; + var j3 = 1797285236; + var j4 = key[3] << 24 | key[2] << 16 | key[1] << 8 | key[0]; + var j5 = key[7] << 24 | key[6] << 16 | key[5] << 8 | key[4]; + var j6 = key[11] << 24 | key[10] << 16 | key[9] << 8 | key[8]; + var j7 = key[15] << 24 | key[14] << 16 | key[13] << 8 | key[12]; + var j8 = key[19] << 24 | key[18] << 16 | key[17] << 8 | key[16]; + var j9 = key[23] << 24 | key[22] << 16 | key[21] << 8 | key[20]; + var j10 = key[27] << 24 | key[26] << 16 | key[25] << 8 | key[24]; + var j11 = key[31] << 24 | key[30] << 16 | key[29] << 8 | key[28]; + var j12 = input[3] << 24 | input[2] << 16 | input[1] << 8 | input[0]; + var j13 = input[7] << 24 | input[6] << 16 | input[5] << 8 | input[4]; + var j14 = input[11] << 24 | input[10] << 16 | input[9] << 8 | input[8]; + var j15 = input[15] << 24 | input[14] << 16 | input[13] << 8 | input[12]; + var x0 = j0; + var x1 = j1; + var x22 = j2; + var x3 = j3; + var x4 = j4; + var x5 = j5; + var x6 = j6; + var x7 = j7; + var x8 = j8; + var x9 = j9; + var x10 = j10; + var x11 = j11; + var x12 = j12; + var x13 = j13; + var x14 = j14; + var x15 = j15; + for (var i2 = 0; i2 < ROUNDS; i2 += 2) { + x0 = x0 + x4 | 0; + x12 ^= x0; + x12 = x12 >>> 32 - 16 | x12 << 16; + x8 = x8 + x12 | 0; + x4 ^= x8; + x4 = x4 >>> 32 - 12 | x4 << 12; + x1 = x1 + x5 | 0; + x13 ^= x1; + x13 = x13 >>> 32 - 16 | x13 << 16; + x9 = x9 + x13 | 0; + x5 ^= x9; + x5 = x5 >>> 32 - 12 | x5 << 12; + x22 = x22 + x6 | 0; + x14 ^= x22; + x14 = x14 >>> 32 - 16 | x14 << 16; + x10 = x10 + x14 | 0; + x6 ^= x10; + x6 = x6 >>> 32 - 12 | x6 << 12; + x3 = x3 + x7 | 0; + x15 ^= x3; + x15 = x15 >>> 32 - 16 | x15 << 16; + x11 = x11 + x15 | 0; + x7 ^= x11; + x7 = x7 >>> 32 - 12 | x7 << 12; + x22 = x22 + x6 | 0; + x14 ^= x22; + x14 = x14 >>> 32 - 8 | x14 << 8; + x10 = x10 + x14 | 0; + x6 ^= x10; + x6 = x6 >>> 32 - 7 | x6 << 7; + x3 = x3 + x7 | 0; + x15 ^= x3; + x15 = x15 >>> 32 - 8 | x15 << 8; + x11 = x11 + x15 | 0; + x7 ^= x11; + x7 = x7 >>> 32 - 7 | x7 << 7; + x1 = x1 + x5 | 0; + x13 ^= x1; + x13 = x13 >>> 32 - 8 | x13 << 8; + x9 = x9 + x13 | 0; + x5 ^= x9; + x5 = x5 >>> 32 - 7 | x5 << 7; + x0 = x0 + x4 | 0; + x12 ^= x0; + x12 = x12 >>> 32 - 8 | x12 << 8; + x8 = x8 + x12 | 0; + x4 ^= x8; + x4 = x4 >>> 32 - 7 | x4 << 7; + x0 = x0 + x5 | 0; + x15 ^= x0; + x15 = x15 >>> 32 - 16 | x15 << 16; + x10 = x10 + x15 | 0; + x5 ^= x10; + x5 = x5 >>> 32 - 12 | x5 << 12; + x1 = x1 + x6 | 0; + x12 ^= x1; + x12 = x12 >>> 32 - 16 | x12 << 16; + x11 = x11 + x12 | 0; + x6 ^= x11; + x6 = x6 >>> 32 - 12 | x6 << 12; + x22 = x22 + x7 | 0; + x13 ^= x22; + x13 = x13 >>> 32 - 16 | x13 << 16; + x8 = x8 + x13 | 0; + x7 ^= x8; + x7 = x7 >>> 32 - 12 | x7 << 12; + x3 = x3 + x4 | 0; + x14 ^= x3; + x14 = x14 >>> 32 - 16 | x14 << 16; + x9 = x9 + x14 | 0; + x4 ^= x9; + x4 = x4 >>> 32 - 12 | x4 << 12; + x22 = x22 + x7 | 0; + x13 ^= x22; + x13 = x13 >>> 32 - 8 | x13 << 8; + x8 = x8 + x13 | 0; + x7 ^= x8; + x7 = x7 >>> 32 - 7 | x7 << 7; + x3 = x3 + x4 | 0; + x14 ^= x3; + x14 = x14 >>> 32 - 8 | x14 << 8; + x9 = x9 + x14 | 0; + x4 ^= x9; + x4 = x4 >>> 32 - 7 | x4 << 7; + x1 = x1 + x6 | 0; + x12 ^= x1; + x12 = x12 >>> 32 - 8 | x12 << 8; + x11 = x11 + x12 | 0; + x6 ^= x11; + x6 = x6 >>> 32 - 7 | x6 << 7; + x0 = x0 + x5 | 0; + x15 ^= x0; + x15 = x15 >>> 32 - 8 | x15 << 8; + x10 = x10 + x15 | 0; + x5 ^= x10; + x5 = x5 >>> 32 - 7 | x5 << 7; + } + binary_1.writeUint32LE(x0 + j0 | 0, out, 0); + binary_1.writeUint32LE(x1 + j1 | 0, out, 4); + binary_1.writeUint32LE(x22 + j2 | 0, out, 8); + binary_1.writeUint32LE(x3 + j3 | 0, out, 12); + binary_1.writeUint32LE(x4 + j4 | 0, out, 16); + binary_1.writeUint32LE(x5 + j5 | 0, out, 20); + binary_1.writeUint32LE(x6 + j6 | 0, out, 24); + binary_1.writeUint32LE(x7 + j7 | 0, out, 28); + binary_1.writeUint32LE(x8 + j8 | 0, out, 32); + binary_1.writeUint32LE(x9 + j9 | 0, out, 36); + binary_1.writeUint32LE(x10 + j10 | 0, out, 40); + binary_1.writeUint32LE(x11 + j11 | 0, out, 44); + binary_1.writeUint32LE(x12 + j12 | 0, out, 48); + binary_1.writeUint32LE(x13 + j13 | 0, out, 52); + binary_1.writeUint32LE(x14 + j14 | 0, out, 56); + binary_1.writeUint32LE(x15 + j15 | 0, out, 60); + } + function streamXOR(key, nonce, src2, dst, nonceInplaceCounterLength) { + if (nonceInplaceCounterLength === void 0) { + nonceInplaceCounterLength = 0; + } + if (key.length !== 32) { + throw new Error("ChaCha: key size must be 32 bytes"); + } + if (dst.length < src2.length) { + throw new Error("ChaCha: destination is shorter than source"); + } + var nc; + var counterLength; + if (nonceInplaceCounterLength === 0) { + if (nonce.length !== 8 && nonce.length !== 12) { + throw new Error("ChaCha nonce must be 8 or 12 bytes"); + } + nc = new Uint8Array(16); + counterLength = nc.length - nonce.length; + nc.set(nonce, counterLength); + } else { + if (nonce.length !== 16) { + throw new Error("ChaCha nonce with counter must be 16 bytes"); + } + nc = nonce; + counterLength = nonceInplaceCounterLength; + } + var block = new Uint8Array(64); + for (var i2 = 0; i2 < src2.length; i2 += 64) { + core(block, nc, key); + for (var j2 = i2; j2 < i2 + 64 && j2 < src2.length; j2++) { + dst[j2] = src2[j2] ^ block[j2 - i2]; + } + incrementCounter(nc, 0, counterLength); + } + wipe_1.wipe(block); + if (nonceInplaceCounterLength === 0) { + wipe_1.wipe(nc); + } + return dst; + } + exports2.streamXOR = streamXOR; + function stream(key, nonce, dst, nonceInplaceCounterLength) { + if (nonceInplaceCounterLength === void 0) { + nonceInplaceCounterLength = 0; + } + wipe_1.wipe(dst); + return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength); + } + exports2.stream = stream; + function incrementCounter(counter, pos, len) { + var carry = 1; + while (len--) { + carry = carry + (counter[pos] & 255) | 0; + counter[pos] = carry & 255; + carry >>>= 8; + pos++; + } + if (carry > 0) { + throw new Error("ChaCha: counter overflow"); + } + } + } +}); + +// node_modules/@stablelib/constant-time/lib/constant-time.js +var require_constant_time = __commonJS({ + "node_modules/@stablelib/constant-time/lib/constant-time.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function select(subject, resultIfOne, resultIfZero) { + return ~(subject - 1) & resultIfOne | subject - 1 & resultIfZero; + } + exports2.select = select; + function lessOrEqual(a3, b4) { + return (a3 | 0) - (b4 | 0) - 1 >>> 31 & 1; + } + exports2.lessOrEqual = lessOrEqual; + function compare3(a3, b4) { + if (a3.length !== b4.length) { + return 0; + } + var result = 0; + for (var i2 = 0; i2 < a3.length; i2++) { + result |= a3[i2] ^ b4[i2]; + } + return 1 & result - 1 >>> 8; + } + exports2.compare = compare3; + function equal(a3, b4) { + if (a3.length === 0 || b4.length === 0) { + return false; + } + return compare3(a3, b4) !== 0; + } + exports2.equal = equal; + } +}); + +// node_modules/@stablelib/poly1305/lib/poly1305.js +var require_poly1305 = __commonJS({ + "node_modules/@stablelib/poly1305/lib/poly1305.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var constant_time_1 = require_constant_time(); + var wipe_1 = require_wipe(); + exports2.DIGEST_LENGTH = 16; + var Poly1305 = ( + /** @class */ + function() { + function Poly13052(key) { + this.digestLength = exports2.DIGEST_LENGTH; + this._buffer = new Uint8Array(16); + this._r = new Uint16Array(10); + this._h = new Uint16Array(10); + this._pad = new Uint16Array(8); + this._leftover = 0; + this._fin = 0; + this._finished = false; + var t0 = key[0] | key[1] << 8; + this._r[0] = t0 & 8191; + var t1 = key[2] | key[3] << 8; + this._r[1] = (t0 >>> 13 | t1 << 3) & 8191; + var t2 = key[4] | key[5] << 8; + this._r[2] = (t1 >>> 10 | t2 << 6) & 7939; + var t3 = key[6] | key[7] << 8; + this._r[3] = (t2 >>> 7 | t3 << 9) & 8191; + var t4 = key[8] | key[9] << 8; + this._r[4] = (t3 >>> 4 | t4 << 12) & 255; + this._r[5] = t4 >>> 1 & 8190; + var t5 = key[10] | key[11] << 8; + this._r[6] = (t4 >>> 14 | t5 << 2) & 8191; + var t6 = key[12] | key[13] << 8; + this._r[7] = (t5 >>> 11 | t6 << 5) & 8065; + var t7 = key[14] | key[15] << 8; + this._r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this._r[9] = t7 >>> 5 & 127; + this._pad[0] = key[16] | key[17] << 8; + this._pad[1] = key[18] | key[19] << 8; + this._pad[2] = key[20] | key[21] << 8; + this._pad[3] = key[22] | key[23] << 8; + this._pad[4] = key[24] | key[25] << 8; + this._pad[5] = key[26] | key[27] << 8; + this._pad[6] = key[28] | key[29] << 8; + this._pad[7] = key[30] | key[31] << 8; + } + Poly13052.prototype._blocks = function(m3, mpos, bytes) { + var hibit = this._fin ? 0 : 1 << 11; + var h0 = this._h[0], h1 = this._h[1], h22 = this._h[2], h32 = this._h[3], h42 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9]; + var r0 = this._r[0], r1 = this._r[1], r2 = this._r[2], r3 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9]; + while (bytes >= 16) { + var t0 = m3[mpos + 0] | m3[mpos + 1] << 8; + h0 += t0 & 8191; + var t1 = m3[mpos + 2] | m3[mpos + 3] << 8; + h1 += (t0 >>> 13 | t1 << 3) & 8191; + var t2 = m3[mpos + 4] | m3[mpos + 5] << 8; + h22 += (t1 >>> 10 | t2 << 6) & 8191; + var t3 = m3[mpos + 6] | m3[mpos + 7] << 8; + h32 += (t2 >>> 7 | t3 << 9) & 8191; + var t4 = m3[mpos + 8] | m3[mpos + 9] << 8; + h42 += (t3 >>> 4 | t4 << 12) & 8191; + h5 += t4 >>> 1 & 8191; + var t5 = m3[mpos + 10] | m3[mpos + 11] << 8; + h6 += (t4 >>> 14 | t5 << 2) & 8191; + var t6 = m3[mpos + 12] | m3[mpos + 13] << 8; + h7 += (t5 >>> 11 | t6 << 5) & 8191; + var t7 = m3[mpos + 14] | m3[mpos + 15] << 8; + h8 += (t6 >>> 8 | t7 << 8) & 8191; + h9 += t7 >>> 5 | hibit; + var c4 = 0; + var d0 = c4; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h22 * (5 * r8); + d0 += h32 * (5 * r7); + d0 += h42 * (5 * r6); + c4 = d0 >>> 13; + d0 &= 8191; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c4 += d0 >>> 13; + d0 &= 8191; + var d1 = c4; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h22 * (5 * r9); + d1 += h32 * (5 * r8); + d1 += h42 * (5 * r7); + c4 = d1 >>> 13; + d1 &= 8191; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c4 += d1 >>> 13; + d1 &= 8191; + var d22 = c4; + d22 += h0 * r2; + d22 += h1 * r1; + d22 += h22 * r0; + d22 += h32 * (5 * r9); + d22 += h42 * (5 * r8); + c4 = d22 >>> 13; + d22 &= 8191; + d22 += h5 * (5 * r7); + d22 += h6 * (5 * r6); + d22 += h7 * (5 * r5); + d22 += h8 * (5 * r4); + d22 += h9 * (5 * r3); + c4 += d22 >>> 13; + d22 &= 8191; + var d3 = c4; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h22 * r1; + d3 += h32 * r0; + d3 += h42 * (5 * r9); + c4 = d3 >>> 13; + d3 &= 8191; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c4 += d3 >>> 13; + d3 &= 8191; + var d4 = c4; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h22 * r2; + d4 += h32 * r1; + d4 += h42 * r0; + c4 = d4 >>> 13; + d4 &= 8191; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c4 += d4 >>> 13; + d4 &= 8191; + var d5 = c4; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h22 * r3; + d5 += h32 * r2; + d5 += h42 * r1; + c4 = d5 >>> 13; + d5 &= 8191; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c4 += d5 >>> 13; + d5 &= 8191; + var d6 = c4; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h22 * r4; + d6 += h32 * r3; + d6 += h42 * r2; + c4 = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c4 += d6 >>> 13; + d6 &= 8191; + var d7 = c4; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h22 * r5; + d7 += h32 * r4; + d7 += h42 * r3; + c4 = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c4 += d7 >>> 13; + d7 &= 8191; + var d8 = c4; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h22 * r6; + d8 += h32 * r5; + d8 += h42 * r4; + c4 = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c4 += d8 >>> 13; + d8 &= 8191; + var d9 = c4; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h22 * r7; + d9 += h32 * r6; + d9 += h42 * r5; + c4 = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c4 += d9 >>> 13; + d9 &= 8191; + c4 = (c4 << 2) + c4 | 0; + c4 = c4 + d0 | 0; + d0 = c4 & 8191; + c4 = c4 >>> 13; + d1 += c4; + h0 = d0; + h1 = d1; + h22 = d22; + h32 = d3; + h42 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + mpos += 16; + bytes -= 16; + } + this._h[0] = h0; + this._h[1] = h1; + this._h[2] = h22; + this._h[3] = h32; + this._h[4] = h42; + this._h[5] = h5; + this._h[6] = h6; + this._h[7] = h7; + this._h[8] = h8; + this._h[9] = h9; + }; + Poly13052.prototype.finish = function(mac, macpos) { + if (macpos === void 0) { + macpos = 0; + } + var g3 = new Uint16Array(10); + var c4; + var mask; + var f4; + var i2; + if (this._leftover) { + i2 = this._leftover; + this._buffer[i2++] = 1; + for (; i2 < 16; i2++) { + this._buffer[i2] = 0; + } + this._fin = 1; + this._blocks(this._buffer, 0, 16); + } + c4 = this._h[1] >>> 13; + this._h[1] &= 8191; + for (i2 = 2; i2 < 10; i2++) { + this._h[i2] += c4; + c4 = this._h[i2] >>> 13; + this._h[i2] &= 8191; + } + this._h[0] += c4 * 5; + c4 = this._h[0] >>> 13; + this._h[0] &= 8191; + this._h[1] += c4; + c4 = this._h[1] >>> 13; + this._h[1] &= 8191; + this._h[2] += c4; + g3[0] = this._h[0] + 5; + c4 = g3[0] >>> 13; + g3[0] &= 8191; + for (i2 = 1; i2 < 10; i2++) { + g3[i2] = this._h[i2] + c4; + c4 = g3[i2] >>> 13; + g3[i2] &= 8191; + } + g3[9] -= 1 << 13; + mask = (c4 ^ 1) - 1; + for (i2 = 0; i2 < 10; i2++) { + g3[i2] &= mask; + } + mask = ~mask; + for (i2 = 0; i2 < 10; i2++) { + this._h[i2] = this._h[i2] & mask | g3[i2]; + } + this._h[0] = (this._h[0] | this._h[1] << 13) & 65535; + this._h[1] = (this._h[1] >>> 3 | this._h[2] << 10) & 65535; + this._h[2] = (this._h[2] >>> 6 | this._h[3] << 7) & 65535; + this._h[3] = (this._h[3] >>> 9 | this._h[4] << 4) & 65535; + this._h[4] = (this._h[4] >>> 12 | this._h[5] << 1 | this._h[6] << 14) & 65535; + this._h[5] = (this._h[6] >>> 2 | this._h[7] << 11) & 65535; + this._h[6] = (this._h[7] >>> 5 | this._h[8] << 8) & 65535; + this._h[7] = (this._h[8] >>> 8 | this._h[9] << 5) & 65535; + f4 = this._h[0] + this._pad[0]; + this._h[0] = f4 & 65535; + for (i2 = 1; i2 < 8; i2++) { + f4 = (this._h[i2] + this._pad[i2] | 0) + (f4 >>> 16) | 0; + this._h[i2] = f4 & 65535; + } + mac[macpos + 0] = this._h[0] >>> 0; + mac[macpos + 1] = this._h[0] >>> 8; + mac[macpos + 2] = this._h[1] >>> 0; + mac[macpos + 3] = this._h[1] >>> 8; + mac[macpos + 4] = this._h[2] >>> 0; + mac[macpos + 5] = this._h[2] >>> 8; + mac[macpos + 6] = this._h[3] >>> 0; + mac[macpos + 7] = this._h[3] >>> 8; + mac[macpos + 8] = this._h[4] >>> 0; + mac[macpos + 9] = this._h[4] >>> 8; + mac[macpos + 10] = this._h[5] >>> 0; + mac[macpos + 11] = this._h[5] >>> 8; + mac[macpos + 12] = this._h[6] >>> 0; + mac[macpos + 13] = this._h[6] >>> 8; + mac[macpos + 14] = this._h[7] >>> 0; + mac[macpos + 15] = this._h[7] >>> 8; + this._finished = true; + return this; + }; + Poly13052.prototype.update = function(m3) { + var mpos = 0; + var bytes = m3.length; + var want; + if (this._leftover) { + want = 16 - this._leftover; + if (want > bytes) { + want = bytes; + } + for (var i2 = 0; i2 < want; i2++) { + this._buffer[this._leftover + i2] = m3[mpos + i2]; + } + bytes -= want; + mpos += want; + this._leftover += want; + if (this._leftover < 16) { + return this; + } + this._blocks(this._buffer, 0, 16); + this._leftover = 0; + } + if (bytes >= 16) { + want = bytes - bytes % 16; + this._blocks(m3, mpos, want); + mpos += want; + bytes -= want; + } + if (bytes) { + for (var i2 = 0; i2 < bytes; i2++) { + this._buffer[this._leftover + i2] = m3[mpos + i2]; + } + this._leftover += bytes; + } + return this; + }; + Poly13052.prototype.digest = function() { + if (this._finished) { + throw new Error("Poly1305 was finished"); + } + var mac = new Uint8Array(16); + this.finish(mac); + return mac; + }; + Poly13052.prototype.clean = function() { + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._r); + wipe_1.wipe(this._h); + wipe_1.wipe(this._pad); + this._leftover = 0; + this._fin = 0; + this._finished = true; + return this; + }; + return Poly13052; + }() + ); + exports2.Poly1305 = Poly1305; + function oneTimeAuth(key, data) { + var h5 = new Poly1305(key); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.oneTimeAuth = oneTimeAuth; + function equal(a3, b4) { + if (a3.length !== exports2.DIGEST_LENGTH || b4.length !== exports2.DIGEST_LENGTH) { + return false; + } + return constant_time_1.equal(a3, b4); + } + exports2.equal = equal; + } +}); + +// node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js +var require_chacha20poly1305 = __commonJS({ + "node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var chacha_1 = require_chacha(); + var poly1305_1 = require_poly1305(); + var wipe_1 = require_wipe(); + var binary_1 = require_binary2(); + var constant_time_1 = require_constant_time(); + exports2.KEY_LENGTH = 32; + exports2.NONCE_LENGTH = 12; + exports2.TAG_LENGTH = 16; + var ZEROS = new Uint8Array(16); + var ChaCha20Poly1305 = ( + /** @class */ + function() { + function ChaCha20Poly13052(key) { + this.nonceLength = exports2.NONCE_LENGTH; + this.tagLength = exports2.TAG_LENGTH; + if (key.length !== exports2.KEY_LENGTH) { + throw new Error("ChaCha20Poly1305 needs 32-byte key"); + } + this._key = new Uint8Array(key); + } + ChaCha20Poly13052.prototype.seal = function(nonce, plaintext, associatedData, dst) { + if (nonce.length > 16) { + throw new Error("ChaCha20Poly1305: incorrect nonce length"); + } + var counter = new Uint8Array(16); + counter.set(nonce, counter.length - nonce.length); + var authKey = new Uint8Array(32); + chacha_1.stream(this._key, counter, authKey, 4); + var resultLength = plaintext.length + this.tagLength; + var result; + if (dst) { + if (dst.length !== resultLength) { + throw new Error("ChaCha20Poly1305: incorrect destination length"); + } + result = dst; + } else { + result = new Uint8Array(resultLength); + } + chacha_1.streamXOR(this._key, counter, plaintext, result, 4); + this._authenticate(result.subarray(result.length - this.tagLength, result.length), authKey, result.subarray(0, result.length - this.tagLength), associatedData); + wipe_1.wipe(counter); + return result; + }; + ChaCha20Poly13052.prototype.open = function(nonce, sealed, associatedData, dst) { + if (nonce.length > 16) { + throw new Error("ChaCha20Poly1305: incorrect nonce length"); + } + if (sealed.length < this.tagLength) { + return null; + } + var counter = new Uint8Array(16); + counter.set(nonce, counter.length - nonce.length); + var authKey = new Uint8Array(32); + chacha_1.stream(this._key, counter, authKey, 4); + var calculatedTag = new Uint8Array(this.tagLength); + this._authenticate(calculatedTag, authKey, sealed.subarray(0, sealed.length - this.tagLength), associatedData); + if (!constant_time_1.equal(calculatedTag, sealed.subarray(sealed.length - this.tagLength, sealed.length))) { + return null; + } + var resultLength = sealed.length - this.tagLength; + var result; + if (dst) { + if (dst.length !== resultLength) { + throw new Error("ChaCha20Poly1305: incorrect destination length"); + } + result = dst; + } else { + result = new Uint8Array(resultLength); + } + chacha_1.streamXOR(this._key, counter, sealed.subarray(0, sealed.length - this.tagLength), result, 4); + wipe_1.wipe(counter); + return result; + }; + ChaCha20Poly13052.prototype.clean = function() { + wipe_1.wipe(this._key); + return this; + }; + ChaCha20Poly13052.prototype._authenticate = function(tagOut, authKey, ciphertext, associatedData) { + var h5 = new poly1305_1.Poly1305(authKey); + if (associatedData) { + h5.update(associatedData); + if (associatedData.length % 16 > 0) { + h5.update(ZEROS.subarray(associatedData.length % 16)); + } + } + h5.update(ciphertext); + if (ciphertext.length % 16 > 0) { + h5.update(ZEROS.subarray(ciphertext.length % 16)); + } + var length2 = new Uint8Array(8); + if (associatedData) { + binary_1.writeUint64LE(associatedData.length, length2); + } + h5.update(length2); + binary_1.writeUint64LE(ciphertext.length, length2); + h5.update(length2); + var tag = h5.digest(); + for (var i2 = 0; i2 < tag.length; i2++) { + tagOut[i2] = tag[i2]; + } + h5.clean(); + wipe_1.wipe(tag); + wipe_1.wipe(length2); + }; + return ChaCha20Poly13052; + }() + ); + exports2.ChaCha20Poly1305 = ChaCha20Poly1305; + } +}); + +// node_modules/@stablelib/hash/lib/hash.js +var require_hash2 = __commonJS({ + "node_modules/@stablelib/hash/lib/hash.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function isSerializableHash(h5) { + return typeof h5.saveState !== "undefined" && typeof h5.restoreState !== "undefined" && typeof h5.cleanSavedState !== "undefined"; + } + exports2.isSerializableHash = isSerializableHash; + } +}); + +// node_modules/@stablelib/hmac/lib/hmac.js +var require_hmac = __commonJS({ + "node_modules/@stablelib/hmac/lib/hmac.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var hash_1 = require_hash2(); + var constant_time_1 = require_constant_time(); + var wipe_1 = require_wipe(); + var HMAC = ( + /** @class */ + function() { + function HMAC2(hash, key) { + this._finished = false; + this._inner = new hash(); + this._outer = new hash(); + this.blockSize = this._outer.blockSize; + this.digestLength = this._outer.digestLength; + var pad = new Uint8Array(this.blockSize); + if (key.length > this.blockSize) { + this._inner.update(key).finish(pad).clean(); + } else { + pad.set(key); + } + for (var i2 = 0; i2 < pad.length; i2++) { + pad[i2] ^= 54; + } + this._inner.update(pad); + for (var i2 = 0; i2 < pad.length; i2++) { + pad[i2] ^= 54 ^ 92; + } + this._outer.update(pad); + if (hash_1.isSerializableHash(this._inner) && hash_1.isSerializableHash(this._outer)) { + this._innerKeyedState = this._inner.saveState(); + this._outerKeyedState = this._outer.saveState(); + } + wipe_1.wipe(pad); + } + HMAC2.prototype.reset = function() { + if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { + throw new Error("hmac: can't reset() because hash doesn't implement restoreState()"); + } + this._inner.restoreState(this._innerKeyedState); + this._outer.restoreState(this._outerKeyedState); + this._finished = false; + return this; + }; + HMAC2.prototype.clean = function() { + if (hash_1.isSerializableHash(this._inner)) { + this._inner.cleanSavedState(this._innerKeyedState); + } + if (hash_1.isSerializableHash(this._outer)) { + this._outer.cleanSavedState(this._outerKeyedState); + } + this._inner.clean(); + this._outer.clean(); + }; + HMAC2.prototype.update = function(data) { + this._inner.update(data); + return this; + }; + HMAC2.prototype.finish = function(out) { + if (this._finished) { + this._outer.finish(out); + return this; + } + this._inner.finish(out); + this._outer.update(out.subarray(0, this.digestLength)).finish(out); + this._finished = true; + return this; + }; + HMAC2.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + HMAC2.prototype.saveState = function() { + if (!hash_1.isSerializableHash(this._inner)) { + throw new Error("hmac: can't saveState() because hash doesn't implement it"); + } + return this._inner.saveState(); + }; + HMAC2.prototype.restoreState = function(savedState) { + if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { + throw new Error("hmac: can't restoreState() because hash doesn't implement it"); + } + this._inner.restoreState(savedState); + this._outer.restoreState(this._outerKeyedState); + this._finished = false; + return this; + }; + HMAC2.prototype.cleanSavedState = function(savedState) { + if (!hash_1.isSerializableHash(this._inner)) { + throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it"); + } + this._inner.cleanSavedState(savedState); + }; + return HMAC2; + }() + ); + exports2.HMAC = HMAC; + function hmac(hash, key, data) { + var h5 = new HMAC(hash, key); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.hmac = hmac; + exports2.equal = constant_time_1.equal; + } +}); + +// node_modules/@stablelib/hkdf/lib/hkdf.js +var require_hkdf = __commonJS({ + "node_modules/@stablelib/hkdf/lib/hkdf.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var hmac_1 = require_hmac(); + var wipe_1 = require_wipe(); + var HKDF = ( + /** @class */ + function() { + function HKDF2(hash, key, salt, info) { + if (salt === void 0) { + salt = new Uint8Array(0); + } + this._counter = new Uint8Array(1); + this._hash = hash; + this._info = info; + var okm = hmac_1.hmac(this._hash, salt, key); + this._hmac = new hmac_1.HMAC(hash, okm); + this._buffer = new Uint8Array(this._hmac.digestLength); + this._bufpos = this._buffer.length; + } + HKDF2.prototype._fillBuffer = function() { + this._counter[0]++; + var ctr = this._counter[0]; + if (ctr === 0) { + throw new Error("hkdf: cannot expand more"); + } + this._hmac.reset(); + if (ctr > 1) { + this._hmac.update(this._buffer); + } + if (this._info) { + this._hmac.update(this._info); + } + this._hmac.update(this._counter); + this._hmac.finish(this._buffer); + this._bufpos = 0; + }; + HKDF2.prototype.expand = function(length2) { + var out = new Uint8Array(length2); + for (var i2 = 0; i2 < out.length; i2++) { + if (this._bufpos === this._buffer.length) { + this._fillBuffer(); + } + out[i2] = this._buffer[this._bufpos++]; + } + return out; + }; + HKDF2.prototype.clean = function() { + this._hmac.clean(); + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._counter); + this._bufpos = 0; + }; + return HKDF2; + }() + ); + exports2.HKDF = HKDF; + } +}); + +// node_modules/@stablelib/sha256/lib/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@stablelib/sha256/lib/sha256.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + exports2.DIGEST_LENGTH = 32; + exports2.BLOCK_SIZE = 64; + var SHA256 = ( + /** @class */ + function() { + function SHA2562() { + this.digestLength = exports2.DIGEST_LENGTH; + this.blockSize = exports2.BLOCK_SIZE; + this._state = new Int32Array(8); + this._temp = new Int32Array(64); + this._buffer = new Uint8Array(128); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + this.reset(); + } + SHA2562.prototype._initState = function() { + this._state[0] = 1779033703; + this._state[1] = 3144134277; + this._state[2] = 1013904242; + this._state[3] = 2773480762; + this._state[4] = 1359893119; + this._state[5] = 2600822924; + this._state[6] = 528734635; + this._state[7] = 1541459225; + }; + SHA2562.prototype.reset = function() { + this._initState(); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + return this; + }; + SHA2562.prototype.clean = function() { + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._temp); + this.reset(); + }; + SHA2562.prototype.update = function(data, dataLength) { + if (dataLength === void 0) { + dataLength = data.length; + } + if (this._finished) { + throw new Error("SHA256: can't update because hash was finished."); + } + var dataPos = 0; + this._bytesHashed += dataLength; + if (this._bufferLength > 0) { + while (this._bufferLength < this.blockSize && dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + if (this._bufferLength === this.blockSize) { + hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize); + this._bufferLength = 0; + } + } + if (dataLength >= this.blockSize) { + dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength); + dataLength %= this.blockSize; + } + while (dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + return this; + }; + SHA2562.prototype.finish = function(out) { + if (!this._finished) { + var bytesHashed = this._bytesHashed; + var left = this._bufferLength; + var bitLenHi = bytesHashed / 536870912 | 0; + var bitLenLo = bytesHashed << 3; + var padLength = bytesHashed % 64 < 56 ? 64 : 128; + this._buffer[left] = 128; + for (var i2 = left + 1; i2 < padLength - 8; i2++) { + this._buffer[i2] = 0; + } + binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); + binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); + hashBlocks(this._temp, this._state, this._buffer, 0, padLength); + this._finished = true; + } + for (var i2 = 0; i2 < this.digestLength / 4; i2++) { + binary_1.writeUint32BE(this._state[i2], out, i2 * 4); + } + return this; + }; + SHA2562.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + SHA2562.prototype.saveState = function() { + if (this._finished) { + throw new Error("SHA256: cannot save finished state"); + } + return { + state: new Int32Array(this._state), + buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, + bufferLength: this._bufferLength, + bytesHashed: this._bytesHashed + }; + }; + SHA2562.prototype.restoreState = function(savedState) { + this._state.set(savedState.state); + this._bufferLength = savedState.bufferLength; + if (savedState.buffer) { + this._buffer.set(savedState.buffer); + } + this._bytesHashed = savedState.bytesHashed; + this._finished = false; + return this; + }; + SHA2562.prototype.cleanSavedState = function(savedState) { + wipe_1.wipe(savedState.state); + if (savedState.buffer) { + wipe_1.wipe(savedState.buffer); + } + savedState.bufferLength = 0; + savedState.bytesHashed = 0; + }; + return SHA2562; + }() + ); + exports2.SHA256 = SHA256; + var K2 = new Int32Array([ + 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 + ]); + function hashBlocks(w4, v2, p3, pos, len) { + while (len >= 64) { + var a3 = v2[0]; + var b4 = v2[1]; + var c4 = v2[2]; + var d3 = v2[3]; + var e2 = v2[4]; + var f4 = v2[5]; + var g3 = v2[6]; + var h5 = v2[7]; + for (var i2 = 0; i2 < 16; i2++) { + var j2 = pos + i2 * 4; + w4[i2] = binary_1.readUint32BE(p3, j2); + } + for (var i2 = 16; i2 < 64; i2++) { + var u3 = w4[i2 - 2]; + var t1 = (u3 >>> 17 | u3 << 32 - 17) ^ (u3 >>> 19 | u3 << 32 - 19) ^ u3 >>> 10; + u3 = w4[i2 - 15]; + var t2 = (u3 >>> 7 | u3 << 32 - 7) ^ (u3 >>> 18 | u3 << 32 - 18) ^ u3 >>> 3; + w4[i2] = (t1 + w4[i2 - 7] | 0) + (t2 + w4[i2 - 16] | 0); + } + for (var i2 = 0; i2 < 64; i2++) { + var t1 = (((e2 >>> 6 | e2 << 32 - 6) ^ (e2 >>> 11 | e2 << 32 - 11) ^ (e2 >>> 25 | e2 << 32 - 25)) + (e2 & f4 ^ ~e2 & g3) | 0) + (h5 + (K2[i2] + w4[i2] | 0) | 0) | 0; + var t2 = ((a3 >>> 2 | a3 << 32 - 2) ^ (a3 >>> 13 | a3 << 32 - 13) ^ (a3 >>> 22 | a3 << 32 - 22)) + (a3 & b4 ^ a3 & c4 ^ b4 & c4) | 0; + h5 = g3; + g3 = f4; + f4 = e2; + e2 = d3 + t1 | 0; + d3 = c4; + c4 = b4; + b4 = a3; + a3 = t1 + t2 | 0; + } + v2[0] += a3; + v2[1] += b4; + v2[2] += c4; + v2[3] += d3; + v2[4] += e2; + v2[5] += f4; + v2[6] += g3; + v2[7] += h5; + pos += 64; + len -= 64; + } + return pos; + } + function hash(data) { + var h5 = new SHA256(); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.hash = hash; + } +}); + +// node_modules/@stablelib/x25519/lib/x25519.js +var require_x25519 = __commonJS({ + "node_modules/@stablelib/x25519/lib/x25519.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.sharedKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.scalarMultBase = exports2.scalarMult = exports2.SHARED_KEY_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = void 0; + var random_1 = require_random(); + var wipe_1 = require_wipe(); + exports2.PUBLIC_KEY_LENGTH = 32; + exports2.SECRET_KEY_LENGTH = 32; + exports2.SHARED_KEY_LENGTH = 32; + function gf(init) { + const r = new Float64Array(16); + if (init) { + for (let i2 = 0; i2 < init.length; i2++) { + r[i2] = init[i2]; + } + } + return r; + } + var _9 = new Uint8Array(32); + _9[0] = 9; + var _121665 = gf([56129, 1]); + function car25519(o2) { + let c4 = 1; + for (let i2 = 0; i2 < 16; i2++) { + let v2 = o2[i2] + c4 + 65535; + c4 = Math.floor(v2 / 65536); + o2[i2] = v2 - c4 * 65536; + } + o2[0] += c4 - 1 + 37 * (c4 - 1); + } + function sel25519(p3, q2, b4) { + const c4 = ~(b4 - 1); + for (let i2 = 0; i2 < 16; i2++) { + const t = c4 & (p3[i2] ^ q2[i2]); + p3[i2] ^= t; + q2[i2] ^= t; + } + } + function pack25519(o2, n3) { + const m3 = gf(); + const t = gf(); + for (let i2 = 0; i2 < 16; i2++) { + t[i2] = n3[i2]; + } + car25519(t); + car25519(t); + car25519(t); + for (let j2 = 0; j2 < 2; j2++) { + m3[0] = t[0] - 65517; + for (let i2 = 1; i2 < 15; i2++) { + m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); + m3[i2 - 1] &= 65535; + } + m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); + const b4 = m3[15] >> 16 & 1; + m3[14] &= 65535; + sel25519(t, m3, 1 - b4); + } + for (let i2 = 0; i2 < 16; i2++) { + o2[2 * i2] = t[i2] & 255; + o2[2 * i2 + 1] = t[i2] >> 8; + } + } + function unpack25519(o2, n3) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); + } + o2[15] &= 32767; + } + function add(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] + b4[i2]; + } + } + function sub(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] - b4[i2]; + } + } + function mul(o2, a3, b4) { + let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; + v2 = a3[0]; + t0 += v2 * b0; + t1 += v2 * b1; + t2 += v2 * b22; + t3 += v2 * b32; + t4 += v2 * b42; + t5 += v2 * b5; + t6 += v2 * b6; + t7 += v2 * b7; + t8 += v2 * b8; + t9 += v2 * b9; + t10 += v2 * b10; + t11 += v2 * b11; + t12 += v2 * b12; + t13 += v2 * b13; + t14 += v2 * b14; + t15 += v2 * b15; + v2 = a3[1]; + t1 += v2 * b0; + t2 += v2 * b1; + t3 += v2 * b22; + t4 += v2 * b32; + t5 += v2 * b42; + t6 += v2 * b5; + t7 += v2 * b6; + t8 += v2 * b7; + t9 += v2 * b8; + t10 += v2 * b9; + t11 += v2 * b10; + t12 += v2 * b11; + t13 += v2 * b12; + t14 += v2 * b13; + t15 += v2 * b14; + t16 += v2 * b15; + v2 = a3[2]; + t2 += v2 * b0; + t3 += v2 * b1; + t4 += v2 * b22; + t5 += v2 * b32; + t6 += v2 * b42; + t7 += v2 * b5; + t8 += v2 * b6; + t9 += v2 * b7; + t10 += v2 * b8; + t11 += v2 * b9; + t12 += v2 * b10; + t13 += v2 * b11; + t14 += v2 * b12; + t15 += v2 * b13; + t16 += v2 * b14; + t17 += v2 * b15; + v2 = a3[3]; + t3 += v2 * b0; + t4 += v2 * b1; + t5 += v2 * b22; + t6 += v2 * b32; + t7 += v2 * b42; + t8 += v2 * b5; + t9 += v2 * b6; + t10 += v2 * b7; + t11 += v2 * b8; + t12 += v2 * b9; + t13 += v2 * b10; + t14 += v2 * b11; + t15 += v2 * b12; + t16 += v2 * b13; + t17 += v2 * b14; + t18 += v2 * b15; + v2 = a3[4]; + t4 += v2 * b0; + t5 += v2 * b1; + t6 += v2 * b22; + t7 += v2 * b32; + t8 += v2 * b42; + t9 += v2 * b5; + t10 += v2 * b6; + t11 += v2 * b7; + t12 += v2 * b8; + t13 += v2 * b9; + t14 += v2 * b10; + t15 += v2 * b11; + t16 += v2 * b12; + t17 += v2 * b13; + t18 += v2 * b14; + t19 += v2 * b15; + v2 = a3[5]; + t5 += v2 * b0; + t6 += v2 * b1; + t7 += v2 * b22; + t8 += v2 * b32; + t9 += v2 * b42; + t10 += v2 * b5; + t11 += v2 * b6; + t12 += v2 * b7; + t13 += v2 * b8; + t14 += v2 * b9; + t15 += v2 * b10; + t16 += v2 * b11; + t17 += v2 * b12; + t18 += v2 * b13; + t19 += v2 * b14; + t20 += v2 * b15; + v2 = a3[6]; + t6 += v2 * b0; + t7 += v2 * b1; + t8 += v2 * b22; + t9 += v2 * b32; + t10 += v2 * b42; + t11 += v2 * b5; + t12 += v2 * b6; + t13 += v2 * b7; + t14 += v2 * b8; + t15 += v2 * b9; + t16 += v2 * b10; + t17 += v2 * b11; + t18 += v2 * b12; + t19 += v2 * b13; + t20 += v2 * b14; + t21 += v2 * b15; + v2 = a3[7]; + t7 += v2 * b0; + t8 += v2 * b1; + t9 += v2 * b22; + t10 += v2 * b32; + t11 += v2 * b42; + t12 += v2 * b5; + t13 += v2 * b6; + t14 += v2 * b7; + t15 += v2 * b8; + t16 += v2 * b9; + t17 += v2 * b10; + t18 += v2 * b11; + t19 += v2 * b12; + t20 += v2 * b13; + t21 += v2 * b14; + t22 += v2 * b15; + v2 = a3[8]; + t8 += v2 * b0; + t9 += v2 * b1; + t10 += v2 * b22; + t11 += v2 * b32; + t12 += v2 * b42; + t13 += v2 * b5; + t14 += v2 * b6; + t15 += v2 * b7; + t16 += v2 * b8; + t17 += v2 * b9; + t18 += v2 * b10; + t19 += v2 * b11; + t20 += v2 * b12; + t21 += v2 * b13; + t22 += v2 * b14; + t23 += v2 * b15; + v2 = a3[9]; + t9 += v2 * b0; + t10 += v2 * b1; + t11 += v2 * b22; + t12 += v2 * b32; + t13 += v2 * b42; + t14 += v2 * b5; + t15 += v2 * b6; + t16 += v2 * b7; + t17 += v2 * b8; + t18 += v2 * b9; + t19 += v2 * b10; + t20 += v2 * b11; + t21 += v2 * b12; + t22 += v2 * b13; + t23 += v2 * b14; + t24 += v2 * b15; + v2 = a3[10]; + t10 += v2 * b0; + t11 += v2 * b1; + t12 += v2 * b22; + t13 += v2 * b32; + t14 += v2 * b42; + t15 += v2 * b5; + t16 += v2 * b6; + t17 += v2 * b7; + t18 += v2 * b8; + t19 += v2 * b9; + t20 += v2 * b10; + t21 += v2 * b11; + t22 += v2 * b12; + t23 += v2 * b13; + t24 += v2 * b14; + t25 += v2 * b15; + v2 = a3[11]; + t11 += v2 * b0; + t12 += v2 * b1; + t13 += v2 * b22; + t14 += v2 * b32; + t15 += v2 * b42; + t16 += v2 * b5; + t17 += v2 * b6; + t18 += v2 * b7; + t19 += v2 * b8; + t20 += v2 * b9; + t21 += v2 * b10; + t22 += v2 * b11; + t23 += v2 * b12; + t24 += v2 * b13; + t25 += v2 * b14; + t26 += v2 * b15; + v2 = a3[12]; + t12 += v2 * b0; + t13 += v2 * b1; + t14 += v2 * b22; + t15 += v2 * b32; + t16 += v2 * b42; + t17 += v2 * b5; + t18 += v2 * b6; + t19 += v2 * b7; + t20 += v2 * b8; + t21 += v2 * b9; + t22 += v2 * b10; + t23 += v2 * b11; + t24 += v2 * b12; + t25 += v2 * b13; + t26 += v2 * b14; + t27 += v2 * b15; + v2 = a3[13]; + t13 += v2 * b0; + t14 += v2 * b1; + t15 += v2 * b22; + t16 += v2 * b32; + t17 += v2 * b42; + t18 += v2 * b5; + t19 += v2 * b6; + t20 += v2 * b7; + t21 += v2 * b8; + t22 += v2 * b9; + t23 += v2 * b10; + t24 += v2 * b11; + t25 += v2 * b12; + t26 += v2 * b13; + t27 += v2 * b14; + t28 += v2 * b15; + v2 = a3[14]; + t14 += v2 * b0; + t15 += v2 * b1; + t16 += v2 * b22; + t17 += v2 * b32; + t18 += v2 * b42; + t19 += v2 * b5; + t20 += v2 * b6; + t21 += v2 * b7; + t22 += v2 * b8; + t23 += v2 * b9; + t24 += v2 * b10; + t25 += v2 * b11; + t26 += v2 * b12; + t27 += v2 * b13; + t28 += v2 * b14; + t29 += v2 * b15; + v2 = a3[15]; + t15 += v2 * b0; + t16 += v2 * b1; + t17 += v2 * b22; + t18 += v2 * b32; + t19 += v2 * b42; + t20 += v2 * b5; + t21 += v2 * b6; + t22 += v2 * b7; + t23 += v2 * b8; + t24 += v2 * b9; + t25 += v2 * b10; + t26 += v2 * b11; + t27 += v2 * b12; + t28 += v2 * b13; + t29 += v2 * b14; + t30 += v2 * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + o2[0] = t0; + o2[1] = t1; + o2[2] = t2; + o2[3] = t3; + o2[4] = t4; + o2[5] = t5; + o2[6] = t6; + o2[7] = t7; + o2[8] = t8; + o2[9] = t9; + o2[10] = t10; + o2[11] = t11; + o2[12] = t12; + o2[13] = t13; + o2[14] = t14; + o2[15] = t15; + } + function square(o2, a3) { + mul(o2, a3, a3); + } + function inv25519(o2, inp) { + const c4 = gf(); + for (let i2 = 0; i2 < 16; i2++) { + c4[i2] = inp[i2]; + } + for (let i2 = 253; i2 >= 0; i2--) { + square(c4, c4); + if (i2 !== 2 && i2 !== 4) { + mul(c4, c4, inp); + } + } + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = c4[i2]; + } + } + function scalarMult(n3, p3) { + const z3 = new Uint8Array(32); + const x3 = new Float64Array(80); + const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(); + for (let i2 = 0; i2 < 31; i2++) { + z3[i2] = n3[i2]; + } + z3[31] = n3[31] & 127 | 64; + z3[0] &= 248; + unpack25519(x3, p3); + for (let i2 = 0; i2 < 16; i2++) { + b4[i2] = x3[i2]; + } + a3[0] = d3[0] = 1; + for (let i2 = 254; i2 >= 0; --i2) { + const r = z3[i2 >>> 3] >>> (i2 & 7) & 1; + sel25519(a3, b4, r); + sel25519(c4, d3, r); + add(e2, a3, c4); + sub(a3, a3, c4); + add(c4, b4, d3); + sub(b4, b4, d3); + square(d3, e2); + square(f4, a3); + mul(a3, c4, a3); + mul(c4, b4, e2); + add(e2, a3, c4); + sub(a3, a3, c4); + square(b4, a3); + sub(c4, d3, f4); + mul(a3, c4, _121665); + add(a3, a3, d3); + mul(c4, c4, a3); + mul(a3, d3, f4); + mul(d3, b4, x3); + square(b4, e2); + sel25519(a3, b4, r); + sel25519(c4, d3, r); + } + for (let i2 = 0; i2 < 16; i2++) { + x3[i2 + 16] = a3[i2]; + x3[i2 + 32] = c4[i2]; + x3[i2 + 48] = b4[i2]; + x3[i2 + 64] = d3[i2]; + } + const x32 = x3.subarray(32); + const x16 = x3.subarray(16); + inv25519(x32, x32); + mul(x16, x16, x32); + const q2 = new Uint8Array(32); + pack25519(q2, x16); + return q2; + } + exports2.scalarMult = scalarMult; + function scalarMultBase(n3) { + return scalarMult(n3, _9); + } + exports2.scalarMultBase = scalarMultBase; + function generateKeyPairFromSeed2(seed) { + if (seed.length !== exports2.SECRET_KEY_LENGTH) { + throw new Error(`x25519: seed must be ${exports2.SECRET_KEY_LENGTH} bytes`); + } + const secretKey = new Uint8Array(seed); + const publicKey = scalarMultBase(secretKey); + return { + publicKey, + secretKey + }; + } + exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; + function generateKeyPair2(prng) { + const seed = (0, random_1.randomBytes)(32, prng); + const result = generateKeyPairFromSeed2(seed); + (0, wipe_1.wipe)(seed); + return result; + } + exports2.generateKeyPair = generateKeyPair2; + function sharedKey(mySecretKey, theirPublicKey, rejectZero = false) { + if (mySecretKey.length !== exports2.PUBLIC_KEY_LENGTH) { + throw new Error("X25519: incorrect secret key length"); + } + if (theirPublicKey.length !== exports2.PUBLIC_KEY_LENGTH) { + throw new Error("X25519: incorrect public key length"); + } + const result = scalarMult(mySecretKey, theirPublicKey); + if (rejectZero) { + let zeros = 0; + for (let i2 = 0; i2 < result.length; i2++) { + zeros |= result[i2]; + } + if (zeros === 0) { + throw new Error("X25519: invalid shared key"); + } + } + return result; + } + exports2.sharedKey = sharedKey; + } +}); + +// node_modules/uint8arrays/esm/src/compare.js +function compare(a3, b4) { + for (let i2 = 0; i2 < a3.byteLength; i2++) { + if (a3[i2] < b4[i2]) { + return -1; + } + if (a3[i2] > b4[i2]) { + return 1; + } + } + if (a3.byteLength > b4.byteLength) { + return 1; + } + if (a3.byteLength < b4.byteLength) { + return -1; + } + return 0; } +var init_compare = __esm({ + "node_modules/uint8arrays/esm/src/compare.js"() { + init_shim(); + } +}); -Is replaced with: +// node_modules/uint8arrays/esm/src/equals.js +function equals3(a3, b4) { + if (a3 === b4) { + return true; + } + if (a3.byteLength !== b4.byteLength) { + return false; + } + for (let i2 = 0; i2 < a3.byteLength; i2++) { + if (a3[i2] !== b4[i2]) { + return false; + } + } + return true; +} +var init_equals = __esm({ + "node_modules/uint8arrays/esm/src/equals.js"() { + init_shim(); + } +}); -const cid = CID.asCID(value) -if (cid) { - // Make sure to use cid instead of value - doSomethingWithCID(cid) +// node_modules/uint8arrays/esm/src/xor.js +function xor(a3, b4) { + if (a3.length !== b4.length) { + throw new Error("Inputs should have the same length"); + } + const result = allocUnsafe(a3.length); + for (let i2 = 0; i2 < a3.length; i2++) { + result[i2] = a3[i2] ^ b4[i2]; + } + return asUint8Array(result); } -`});var NP=he(()=>{l();xP();Sp();$i();vA();ml()});var IA,ppe,OP=he(()=>{l();nP();iP();sP();oP();aP();fA();uP();pA();cP();fP();vP();IP();_P();SP();NP();IA={...sA,...oA,...aA,...uA,...cA,...lA,...dA,...hA,...gA,...yA},ppe={...AA,...bA}});function PP(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var DP,_A,sW,Np,SA=he(()=>{l();OP();bp();DP=PP("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),_A=PP("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=Qa(t.length);for(let r=0;r{l();SA()});function On(t,e="utf8"){let r=Np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Wi(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var CA=he(()=>{l();SA();hl()});function El(t){return ji(si(On(t,Ga),gp))}function vl(t){return si(On(Qi(t),gp),Ga)}function xA(t){let e=On(vp,ja),r=Ep+si(Ip([e,t]),ja);return[mp,wp,r].join(yp)}function NA(t){let[e,r,n]=t.split(yp);if(e!==mp||r!==wp)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==Ep)throw new Error("Issuer must be a key in mulicodec format");let s=On(n.slice(1),ja);if(si(s.slice(0,2),ja)!==vp)throw new Error('Issuer must be a public key with type "Ed25519"');let a=s.slice(2);if(a.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return a}function RP(t){return si(t,Ga)}function BP(t){return On(t,Ga)}function OA(t){return On([vl(t.header),vl(t.payload)].join(ro),dl)}function oW(t){let e=si(t,dl).split(ro),r=El(e[0]),n=El(e[1]);return{header:r,payload:n}}function DA(t){return[vl(t.header),vl(t.payload),RP(t.signature)].join(ro)}function PA(t){let e=t.split(ro),r=El(e[0]),n=El(e[1]),i=BP(e[2]),s=On(e.slice(0,2).join(ro),dl);return{header:r,payload:n,signature:i,data:s}}var RA=he(()=>{l();eA();TA();CA();nl();Ap()});function aW(t=(0,LP.randomBytes)(32)){return Ja.generateKeyPairFromSeed(t)}async function uW(t,e,r,n,i=(0,FP.fromMiliseconds)(Date.now())){let s={alg:hp,typ:pp},o=xA(n.publicKey),a=i+r,u={iss:o,sub:t,aud:e,iat:i,exp:a},c=OA({header:s,payload:u}),f=Ja.sign(n.secretKey,c);return DA({header:s,payload:u,signature:f})}async function cW(t){let{header:e,payload:r,data:n,signature:i}=PA(t);if(e.alg!==hp||e.typ!==pp)throw new Error("JWT must use EdDSA algorithm");let s=NA(r.iss);return Ja.verify(s,n,i)}var Ja,LP,FP,MP=he(()=>{l();Ja=be(WD()),LP=be(cl()),FP=be(Xs());Ap();RA()});var UP=he(()=>{l()});var qP={};ft(qP,{DATA_ENCODING:()=>dl,DID_DELIMITER:()=>yp,DID_METHOD:()=>wp,DID_PREFIX:()=>mp,JSON_ENCODING:()=>gp,JWT_DELIMITER:()=>ro,JWT_ENCODING:()=>Ga,JWT_IRIDIUM_ALG:()=>hp,JWT_IRIDIUM_TYP:()=>pp,KEY_PAIR_SEED_LENGTH:()=>KD,MULTICODEC_ED25519_BASE:()=>Ep,MULTICODEC_ED25519_ENCODING:()=>ja,MULTICODEC_ED25519_HEADER:()=>vp,MULTICODEC_ED25519_LENGTH:()=>$D,decodeData:()=>oW,decodeIss:()=>NA,decodeJSON:()=>El,decodeJWT:()=>PA,decodeSig:()=>BP,encodeData:()=>OA,encodeIss:()=>xA,encodeJSON:()=>vl,encodeJWT:()=>DA,encodeSig:()=>RP,generateKeyPair:()=>aW,signJWT:()=>uW,verifyJWT:()=>cW});var VP=he(()=>{l();MP();Ap();UP();RA()});var kP=v(Op=>{"use strict";l();Object.defineProperty(Op,"__esModule",{value:!0});var tr=qa(),BA=Hr(),lW=20;function fW(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,a=r[3]<<24|r[2]<<16|r[1]<<8|r[0],u=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],g=r[23]<<24|r[22]<<16|r[21]<<8|r[20],m=r[27]<<24|r[26]<<16|r[25]<<8|r[24],y=r[31]<<24|r[30]<<16|r[29]<<8|r[28],A=e[3]<<24|e[2]<<16|e[1]<<8|e[0],O=e[7]<<24|e[6]<<16|e[5]<<8|e[4],R=e[11]<<24|e[10]<<16|e[9]<<8|e[8],q=e[15]<<24|e[14]<<16|e[13]<<8|e[12],M=n,b=i,S=s,N=o,_=a,T=u,B=c,X=f,z=d,k=g,Q=m,K=y,ye=A,ce=O,ie=R,J=q,oe=0;oe>>16|ye<<16,z=z+ye|0,_^=z,_=_>>>20|_<<12,b=b+T|0,ce^=b,ce=ce>>>16|ce<<16,k=k+ce|0,T^=k,T=T>>>20|T<<12,S=S+B|0,ie^=S,ie=ie>>>16|ie<<16,Q=Q+ie|0,B^=Q,B=B>>>20|B<<12,N=N+X|0,J^=N,J=J>>>16|J<<16,K=K+J|0,X^=K,X=X>>>20|X<<12,S=S+B|0,ie^=S,ie=ie>>>24|ie<<8,Q=Q+ie|0,B^=Q,B=B>>>25|B<<7,N=N+X|0,J^=N,J=J>>>24|J<<8,K=K+J|0,X^=K,X=X>>>25|X<<7,b=b+T|0,ce^=b,ce=ce>>>24|ce<<8,k=k+ce|0,T^=k,T=T>>>25|T<<7,M=M+_|0,ye^=M,ye=ye>>>24|ye<<8,z=z+ye|0,_^=z,_=_>>>25|_<<7,M=M+T|0,J^=M,J=J>>>16|J<<16,Q=Q+J|0,T^=Q,T=T>>>20|T<<12,b=b+B|0,ye^=b,ye=ye>>>16|ye<<16,K=K+ye|0,B^=K,B=B>>>20|B<<12,S=S+X|0,ce^=S,ce=ce>>>16|ce<<16,z=z+ce|0,X^=z,X=X>>>20|X<<12,N=N+_|0,ie^=N,ie=ie>>>16|ie<<16,k=k+ie|0,_^=k,_=_>>>20|_<<12,S=S+X|0,ce^=S,ce=ce>>>24|ce<<8,z=z+ce|0,X^=z,X=X>>>25|X<<7,N=N+_|0,ie^=N,ie=ie>>>24|ie<<8,k=k+ie|0,_^=k,_=_>>>25|_<<7,b=b+B|0,ye^=b,ye=ye>>>24|ye<<8,K=K+ye|0,B^=K,B=B>>>25|B<<7,M=M+T|0,J^=M,J=J>>>24|J<<8,Q=Q+J|0,T^=Q,T=T>>>25|T<<7;tr.writeUint32LE(M+n|0,t,0),tr.writeUint32LE(b+i|0,t,4),tr.writeUint32LE(S+s|0,t,8),tr.writeUint32LE(N+o|0,t,12),tr.writeUint32LE(_+a|0,t,16),tr.writeUint32LE(T+u|0,t,20),tr.writeUint32LE(B+c|0,t,24),tr.writeUint32LE(X+f|0,t,28),tr.writeUint32LE(z+d|0,t,32),tr.writeUint32LE(k+g|0,t,36),tr.writeUint32LE(Q+m|0,t,40),tr.writeUint32LE(K+y|0,t,44),tr.writeUint32LE(ye+A|0,t,48),tr.writeUint32LE(ce+O|0,t,52),tr.writeUint32LE(ie+R|0,t,56),tr.writeUint32LE(J+q|0,t,60)}function HP(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Dp=v(Xa=>{"use strict";l();Object.defineProperty(Xa,"__esModule",{value:!0});function pW(t,e,r){return~(t-1)&e|t-1&r}Xa.select=pW;function gW(t,e){return(t|0)-(e|0)-1>>>31&1}Xa.lessOrEqual=gW;function GP(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xa.compare=GP;function yW(t,e){return t.length===0||e.length===0?!1:GP(t,e)!==0}Xa.equal=yW});var QP=v(oi=>{"use strict";l();Object.defineProperty(oi,"__esModule",{value:!0});var mW=Dp(),Pp=Hr();oi.DIGEST_LENGTH=16;var jP=function(){function t(e){this.digestLength=oi.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=(o>>>14|a<<2)&8191;var u=e[12]|e[13]<<8;this._r[7]=(a>>>11|u<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(u>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],a=this._h[2],u=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],g=this._h[7],m=this._h[8],y=this._h[9],A=this._r[0],O=this._r[1],R=this._r[2],q=this._r[3],M=this._r[4],b=this._r[5],S=this._r[6],N=this._r[7],_=this._r[8],T=this._r[9];n>=16;){var B=e[r+0]|e[r+1]<<8;s+=B&8191;var X=e[r+2]|e[r+3]<<8;o+=(B>>>13|X<<3)&8191;var z=e[r+4]|e[r+5]<<8;a+=(X>>>10|z<<6)&8191;var k=e[r+6]|e[r+7]<<8;u+=(z>>>7|k<<9)&8191;var Q=e[r+8]|e[r+9]<<8;c+=(k>>>4|Q<<12)&8191,f+=Q>>>1&8191;var K=e[r+10]|e[r+11]<<8;d+=(Q>>>14|K<<2)&8191;var ye=e[r+12]|e[r+13]<<8;g+=(K>>>11|ye<<5)&8191;var ce=e[r+14]|e[r+15]<<8;m+=(ye>>>8|ce<<8)&8191,y+=ce>>>5|i;var ie=0,J=ie;J+=s*A,J+=o*(5*T),J+=a*(5*_),J+=u*(5*N),J+=c*(5*S),ie=J>>>13,J&=8191,J+=f*(5*b),J+=d*(5*M),J+=g*(5*q),J+=m*(5*R),J+=y*(5*O),ie+=J>>>13,J&=8191;var oe=ie;oe+=s*O,oe+=o*A,oe+=a*(5*T),oe+=u*(5*_),oe+=c*(5*N),ie=oe>>>13,oe&=8191,oe+=f*(5*S),oe+=d*(5*b),oe+=g*(5*M),oe+=m*(5*q),oe+=y*(5*R),ie+=oe>>>13,oe&=8191;var re=ie;re+=s*R,re+=o*O,re+=a*A,re+=u*(5*T),re+=c*(5*_),ie=re>>>13,re&=8191,re+=f*(5*N),re+=d*(5*S),re+=g*(5*b),re+=m*(5*M),re+=y*(5*q),ie+=re>>>13,re&=8191;var se=ie;se+=s*q,se+=o*R,se+=a*O,se+=u*A,se+=c*(5*T),ie=se>>>13,se&=8191,se+=f*(5*_),se+=d*(5*N),se+=g*(5*S),se+=m*(5*b),se+=y*(5*M),ie+=se>>>13,se&=8191;var U=ie;U+=s*M,U+=o*q,U+=a*R,U+=u*O,U+=c*A,ie=U>>>13,U&=8191,U+=f*(5*T),U+=d*(5*_),U+=g*(5*N),U+=m*(5*S),U+=y*(5*b),ie+=U>>>13,U&=8191;var fe=ie;fe+=s*b,fe+=o*M,fe+=a*q,fe+=u*R,fe+=c*O,ie=fe>>>13,fe&=8191,fe+=f*A,fe+=d*(5*T),fe+=g*(5*_),fe+=m*(5*N),fe+=y*(5*S),ie+=fe>>>13,fe&=8191;var ue=ie;ue+=s*S,ue+=o*b,ue+=a*M,ue+=u*q,ue+=c*R,ie=ue>>>13,ue&=8191,ue+=f*O,ue+=d*A,ue+=g*(5*T),ue+=m*(5*_),ue+=y*(5*N),ie+=ue>>>13,ue&=8191;var de=ie;de+=s*N,de+=o*S,de+=a*b,de+=u*M,de+=c*q,ie=de>>>13,de&=8191,de+=f*R,de+=d*O,de+=g*A,de+=m*(5*T),de+=y*(5*_),ie+=de>>>13,de&=8191;var ae=ie;ae+=s*_,ae+=o*N,ae+=a*S,ae+=u*b,ae+=c*M,ie=ae>>>13,ae&=8191,ae+=f*q,ae+=d*R,ae+=g*O,ae+=m*A,ae+=y*(5*T),ie+=ae>>>13,ae&=8191;var le=ie;le+=s*T,le+=o*_,le+=a*N,le+=u*S,le+=c*b,ie=le>>>13,le&=8191,le+=f*M,le+=d*q,le+=g*R,le+=m*O,le+=y*A,ie+=le>>>13,le&=8191,ie=(ie<<2)+ie|0,ie=ie+J|0,J=ie&8191,ie=ie>>>13,oe+=ie,s=J,o=oe,a=re,u=se,c=U,f=fe,d=ue,g=de,m=ae,y=le,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=a,this._h[3]=u,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=g,this._h[8]=m,this._h[9]=y},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,a;if(this._leftover){for(a=this._leftover,this._buffer[a++]=1;a<16;a++)this._buffer[a]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,a=2;a<10;a++)this._h[a]+=i,i=this._h[a]>>>13,this._h[a]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,a=1;a<10;a++)n[a]=this._h[a]+i,i=n[a]>>>13,n[a]&=8191;for(n[9]-=8192,s=(i^1)-1,a=0;a<10;a++)n[a]&=s;for(s=~s,a=0;a<10;a++)this._h[a]=this._h[a]&s|n[a];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,a=1;a<8;a++)o=(this._h[a]+this._pad[a]|0)+(o>>>16)|0,this._h[a]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";l();Object.defineProperty(ai,"__esModule",{value:!0});var Rp=kP(),vW=QP(),Al=Hr(),zP=qa(),AW=Dp();ai.KEY_LENGTH=32;ai.NONCE_LENGTH=12;ai.TAG_LENGTH=16;var WP=new Uint8Array(16),bW=function(){function t(e){if(this.nonceLength=ai.NONCE_LENGTH,this.tagLength=ai.TAG_LENGTH,e.length!==ai.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Rp.stream(this._key,s,o,4);var a=r.length+this.tagLength,u;if(i){if(i.length!==a)throw new Error("ChaCha20Poly1305: incorrect destination length");u=i}else u=new Uint8Array(a);return Rp.streamXOR(this._key,s,r,u,4),this._authenticate(u.subarray(u.length-this.tagLength,u.length),o,u.subarray(0,u.length-this.tagLength),n),Al.wipe(s),u},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(WP.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(WP.subarray(n.length%16));var o=new Uint8Array(8);i&&zP.writeUint64LE(i.length,o),s.update(o),zP.writeUint64LE(n.length,o),s.update(o);for(var a=s.digest(),u=0;u{"use strict";l();Object.defineProperty(LA,"__esModule",{value:!0});function IW(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}LA.isSerializableHash=IW});var JP=v(bl=>{"use strict";l();Object.defineProperty(bl,"__esModule",{value:!0});var Dn=KP(),_W=Dp(),SW=Hr(),YP=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";l();Object.defineProperty(FA,"__esModule",{value:!0});var XP=JP(),ZP=Hr(),CW=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=XP.hmac(this._hash,n,r);this._hmac=new XP.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";l();Object.defineProperty(Yi,"__esModule",{value:!0});var Lp=qa(),Bp=Hr();Yi.DIGEST_LENGTH=32;Yi.BLOCK_SIZE=64;var tR=function(){function t(){this.digestLength=Yi.DIGEST_LENGTH,this.blockSize=Yi.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Bp.wipe(this._buffer),Bp.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(MA(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=MA(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Bp.wipe(e.state),e.buffer&&Bp.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Yi.SHA256=tR;var xW=new Int32Array([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]);function MA(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],a=e[2],u=e[3],c=e[4],f=e[5],d=e[6],g=e[7],m=0;m<16;m++){var y=n+m*4;t[m]=Lp.readUint32BE(r,y)}for(var m=16;m<64;m++){var A=t[m-2],O=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=t[m-15];var R=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;t[m]=(O+t[m-7]|0)+(R+t[m-16]|0)}for(var m=0;m<64;m++){var O=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(g+(xW[m]+t[m]|0)|0)|0,R=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&a^o&a)|0;g=d,d=f,f=c,c=u+O|0,u=a,a=o,o=s,s=O+R|0}e[0]+=s,e[1]+=o,e[2]+=a,e[3]+=u,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=g,n+=64,i-=64}return n}function NW(t){var e=new tR;e.update(t);var r=e.digest();return e.clean(),r}Yi.hash=NW});var oR=v(mt=>{"use strict";l();Object.defineProperty(mt,"__esModule",{value:!0});mt.sharedKey=mt.generateKeyPair=mt.generateKeyPairFromSeed=mt.scalarMultBase=mt.scalarMult=mt.SHARED_KEY_LENGTH=mt.SECRET_KEY_LENGTH=mt.PUBLIC_KEY_LENGTH=void 0;var OW=cl(),DW=Hr();mt.PUBLIC_KEY_LENGTH=32;mt.SECRET_KEY_LENGTH=32;mt.SHARED_KEY_LENGTH=32;function Pn(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Il(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function BW(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Fp(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Mp(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function ui(t,e,r){let n,i,s=0,o=0,a=0,u=0,c=0,f=0,d=0,g=0,m=0,y=0,A=0,O=0,R=0,q=0,M=0,b=0,S=0,N=0,_=0,T=0,B=0,X=0,z=0,k=0,Q=0,K=0,ye=0,ce=0,ie=0,J=0,oe=0,re=r[0],se=r[1],U=r[2],fe=r[3],ue=r[4],de=r[5],ae=r[6],le=r[7],w=r[8],E=r[9],I=r[10],P=r[11],C=r[12],D=r[13],L=r[14],x=r[15];n=e[0],s+=n*re,o+=n*se,a+=n*U,u+=n*fe,c+=n*ue,f+=n*de,d+=n*ae,g+=n*le,m+=n*w,y+=n*E,A+=n*I,O+=n*P,R+=n*C,q+=n*D,M+=n*L,b+=n*x,n=e[1],o+=n*re,a+=n*se,u+=n*U,c+=n*fe,f+=n*ue,d+=n*de,g+=n*ae,m+=n*le,y+=n*w,A+=n*E,O+=n*I,R+=n*P,q+=n*C,M+=n*D,b+=n*L,S+=n*x,n=e[2],a+=n*re,u+=n*se,c+=n*U,f+=n*fe,d+=n*ue,g+=n*de,m+=n*ae,y+=n*le,A+=n*w,O+=n*E,R+=n*I,q+=n*P,M+=n*C,b+=n*D,S+=n*L,N+=n*x,n=e[3],u+=n*re,c+=n*se,f+=n*U,d+=n*fe,g+=n*ue,m+=n*de,y+=n*ae,A+=n*le,O+=n*w,R+=n*E,q+=n*I,M+=n*P,b+=n*C,S+=n*D,N+=n*L,_+=n*x,n=e[4],c+=n*re,f+=n*se,d+=n*U,g+=n*fe,m+=n*ue,y+=n*de,A+=n*ae,O+=n*le,R+=n*w,q+=n*E,M+=n*I,b+=n*P,S+=n*C,N+=n*D,_+=n*L,T+=n*x,n=e[5],f+=n*re,d+=n*se,g+=n*U,m+=n*fe,y+=n*ue,A+=n*de,O+=n*ae,R+=n*le,q+=n*w,M+=n*E,b+=n*I,S+=n*P,N+=n*C,_+=n*D,T+=n*L,B+=n*x,n=e[6],d+=n*re,g+=n*se,m+=n*U,y+=n*fe,A+=n*ue,O+=n*de,R+=n*ae,q+=n*le,M+=n*w,b+=n*E,S+=n*I,N+=n*P,_+=n*C,T+=n*D,B+=n*L,X+=n*x,n=e[7],g+=n*re,m+=n*se,y+=n*U,A+=n*fe,O+=n*ue,R+=n*de,q+=n*ae,M+=n*le,b+=n*w,S+=n*E,N+=n*I,_+=n*P,T+=n*C,B+=n*D,X+=n*L,z+=n*x,n=e[8],m+=n*re,y+=n*se,A+=n*U,O+=n*fe,R+=n*ue,q+=n*de,M+=n*ae,b+=n*le,S+=n*w,N+=n*E,_+=n*I,T+=n*P,B+=n*C,X+=n*D,z+=n*L,k+=n*x,n=e[9],y+=n*re,A+=n*se,O+=n*U,R+=n*fe,q+=n*ue,M+=n*de,b+=n*ae,S+=n*le,N+=n*w,_+=n*E,T+=n*I,B+=n*P,X+=n*C,z+=n*D,k+=n*L,Q+=n*x,n=e[10],A+=n*re,O+=n*se,R+=n*U,q+=n*fe,M+=n*ue,b+=n*de,S+=n*ae,N+=n*le,_+=n*w,T+=n*E,B+=n*I,X+=n*P,z+=n*C,k+=n*D,Q+=n*L,K+=n*x,n=e[11],O+=n*re,R+=n*se,q+=n*U,M+=n*fe,b+=n*ue,S+=n*de,N+=n*ae,_+=n*le,T+=n*w,B+=n*E,X+=n*I,z+=n*P,k+=n*C,Q+=n*D,K+=n*L,ye+=n*x,n=e[12],R+=n*re,q+=n*se,M+=n*U,b+=n*fe,S+=n*ue,N+=n*de,_+=n*ae,T+=n*le,B+=n*w,X+=n*E,z+=n*I,k+=n*P,Q+=n*C,K+=n*D,ye+=n*L,ce+=n*x,n=e[13],q+=n*re,M+=n*se,b+=n*U,S+=n*fe,N+=n*ue,_+=n*de,T+=n*ae,B+=n*le,X+=n*w,z+=n*E,k+=n*I,Q+=n*P,K+=n*C,ye+=n*D,ce+=n*L,ie+=n*x,n=e[14],M+=n*re,b+=n*se,S+=n*U,N+=n*fe,_+=n*ue,T+=n*de,B+=n*ae,X+=n*le,z+=n*w,k+=n*E,Q+=n*I,K+=n*P,ye+=n*C,ce+=n*D,ie+=n*L,J+=n*x,n=e[15],b+=n*re,S+=n*se,N+=n*U,_+=n*fe,T+=n*ue,B+=n*de,X+=n*ae,z+=n*le,k+=n*w,Q+=n*E,K+=n*I,ye+=n*P,ce+=n*C,ie+=n*D,J+=n*L,oe+=n*x,s+=38*S,o+=38*N,a+=38*_,u+=38*T,c+=38*B,f+=38*X,d+=38*z,g+=38*k,m+=38*Q,y+=38*K,A+=38*ye,O+=38*ce,R+=38*ie,q+=38*J,M+=38*oe,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=a,t[3]=u,t[4]=c,t[5]=f,t[6]=d,t[7]=g,t[8]=m,t[9]=y,t[10]=A,t[11]=O,t[12]=R,t[13]=q,t[14]=M,t[15]=b}function _l(t,e){ui(t,e,e)}function LW(t,e){let r=Pn();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)_l(r,r),n!==2&&n!==4&&ui(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function qA(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=Pn(),s=Pn(),o=Pn(),a=Pn(),u=Pn(),c=Pn();for(let m=0;m<31;m++)r[m]=t[m];r[31]=t[31]&127|64,r[0]&=248,BW(n,e);for(let m=0;m<16;m++)s[m]=n[m];i[0]=a[0]=1;for(let m=254;m>=0;--m){let y=r[m>>>3]>>>(m&7)&1;Il(i,s,y),Il(o,a,y),Fp(u,i,o),Mp(i,i,o),Fp(o,s,a),Mp(s,s,a),_l(a,u),_l(c,i),ui(i,o,i),ui(o,s,u),Fp(u,i,o),Mp(i,i,o),_l(s,i),Mp(o,a,c),ui(i,o,PW),Fp(i,i,a),ui(o,o,i),ui(i,a,c),ui(a,s,n),_l(s,u),Il(i,s,y),Il(o,a,y)}for(let m=0;m<16;m++)n[m+16]=i[m],n[m+32]=o[m],n[m+48]=s[m],n[m+64]=a[m];let f=n.subarray(32),d=n.subarray(16);LW(f,f),ui(d,d,f);let g=new Uint8Array(32);return RW(g,d),g}mt.scalarMult=qA;function iR(t){return qA(t,nR)}mt.scalarMultBase=iR;function sR(t){if(t.length!==mt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${mt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:iR(e),secretKey:e}}mt.generateKeyPairFromSeed=sR;function FW(t){let e=(0,OW.randomBytes)(32,t),r=sR(e);return(0,DW.wipe)(e),r}mt.generateKeyPair=FW;function MW(t,e,r=!1){if(t.length!==mt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==mt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=qA(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{l()});function cR(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{l()});function fR(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=Qa(t.length);for(let n=0;n{l();bp();hl()});var VA={};ft(VA,{compare:()=>aR,concat:()=>Ip,equals:()=>cR,fromString:()=>On,toString:()=>si,xor:()=>fR});var HA=he(()=>{l();uR();eA();lR();CA();TA();dR()});var _R=v(ut=>{"use strict";l();var hR=ut&&ut.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new vR:typeof navigator<"u"?kA(navigator.userAgent):IR()}ut.detect=HW;function AR(t){return t!==""&&VW.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function kW(t){var e=AR(t);return e?e[0]:null}ut.browserName=kW;function kA(t){var e=AR(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new ER;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";l();Object.defineProperty(et,"__esModule",{value:!0});et.getLocalStorage=et.getLocalStorageOrThrow=et.getCrypto=et.getCryptoOrThrow=et.getLocation=et.getLocationOrThrow=et.getNavigator=et.getNavigatorOrThrow=et.getDocument=et.getDocumentOrThrow=et.getFromWindowOrThrow=et.getFromWindow=void 0;function io(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}et.getFromWindow=io;function Za(t){let e=io(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}et.getFromWindowOrThrow=Za;function jW(){return Za("document")}et.getDocumentOrThrow=jW;function QW(){return io("document")}et.getDocument=QW;function zW(){return Za("navigator")}et.getNavigatorOrThrow=zW;function WW(){return io("navigator")}et.getNavigator=WW;function $W(){return Za("location")}et.getLocationOrThrow=$W;function KW(){return io("location")}et.getLocation=KW;function YW(){return Za("crypto")}et.getCryptoOrThrow=YW;function JW(){return io("crypto")}et.getCrypto=JW;function XW(){return Za("localStorage")}et.getLocalStorageOrThrow=XW;function ZW(){return io("localStorage")}et.getLocalStorage=ZW});var TR=v(Up=>{"use strict";l();Object.defineProperty(Up,"__esModule",{value:!0});Up.getWindowMetadata=void 0;var SR=GA();function e$(){let t,e;try{t=SR.getDocumentOrThrow(),e=SR.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),g=[];for(let m=0;m-1){let O=y.getAttribute("href");if(O)if(O.toLowerCase().indexOf("https:")===-1&&O.toLowerCase().indexOf("http:")===-1&&O.indexOf("//")!==0){let R=e.protocol+"//"+e.host;if(O.indexOf("/")===0)R+=O;else{let q=e.pathname.split("/");q.pop();let M=q.join("/");R+=M+"/"+O}g.push(R)}else if(O.indexOf("//")===0){let R=e.protocol+O;g.push(R)}else g.push(O)}}return g}function n(...d){let g=t.getElementsByTagName("meta");for(let m=0;my.getAttribute(O)).filter(O=>O?d.includes(O):!1);if(A.length&&A){let O=y.getAttribute("content");if(O)return O}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),a=s(),u=e.origin,c=r();return{description:a,url:u,icons:c,name:o}}Up.getWindowMetadata=e$});var xR=v((Oge,CR)=>{"use strict";l();CR.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var RR=v((Pge,PR)=>{"use strict";l();var DR="%[a-f0-9]{2}",NR=new RegExp("("+DR+")|([^%]+?)","gi"),OR=new RegExp("("+DR+")+","gi");function jA(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],jA(r),jA(n))}function t$(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(NR)||[],r=1;r{"use strict";l();BR.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var MR=v((Fge,FR)=>{"use strict";l();FR.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";l();var n$=xR(),i$=RR(),qR=LR(),s$=MR(),o$=t=>t==null,QA=Symbol("encodeFragmentIdentifier");function a$(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[It(e,t),"[",i,"]"].join("")]:[...r,[It(e,t),"[",It(i,t),"]=",It(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[It(e,t),"[]"].join("")]:[...r,[It(e,t),"[]=",It(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[It(e,t),":list="].join("")]:[...r,[It(e,t),":list=",It(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[It(r,t),e,It(i,t)].join("")]:[[n,It(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,It(e,t)]:[...r,[It(e,t),"=",It(n,t)].join("")]}}function u$(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&ci(n,t).includes(t.arrayFormatSeparator);n=o?ci(n,t):n;let a=s||o?n.split(t.arrayFormatSeparator).map(u=>ci(u,t)):n===null?n:ci(n,t);i[r]=a};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&ci(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(a=>ci(a,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function VR(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function It(t,e){return e.encode?e.strict?n$(t):encodeURIComponent(t):t}function ci(t,e){return e.decode?i$(t):t}function HR(t){return Array.isArray(t)?t.sort():typeof t=="object"?HR(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function kR(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function c$(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function GR(t){t=kR(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function UR(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function jR(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),VR(e.arrayFormatSeparator);let r=u$(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=qR(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:ci(o,e),r(ci(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=UR(s[o],e);else n[i]=UR(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=HR(o):i[s]=o,i},Object.create(null))}wr.extract=GR;wr.parse=jR;wr.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),VR(e.arrayFormatSeparator);let r=o=>e.skipNull&&o$(t[o])||e.skipEmptyString&&t[o]==="",n=a$(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let a=t[o];return a===void 0?"":a===null?It(o,e):Array.isArray(a)?a.length===0&&e.arrayFormat==="bracket-separator"?It(o,e)+"[]":a.reduce(n(o),[]).join("&"):It(o,e)+"="+It(a,e)}).filter(o=>o.length>0).join("&")};wr.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=qR(t,"#");return Object.assign({url:r.split("?")[0]||"",query:jR(GR(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:ci(n,e)}:{})};wr.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[QA]:!0},e);let r=kR(t.url).split("?")[0]||"",n=wr.extract(t.url),i=wr.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=wr.stringify(s,e);o&&(o=`?${o}`);let a=c$(t.url);return t.fragmentIdentifier&&(a=`#${e[QA]?It(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${a}`};wr.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[QA]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=wr.parseUrl(t,r);return wr.stringifyUrl({url:n,query:s$(i,e),fragmentIdentifier:s},r)};wr.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return wr.pick(t,n,r)}});var zR=he(()=>{l()});function Ji(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function l$(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function f$(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function d$(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function Sl(t,e,r){return(!r.length?f$(t,e.length):d$(t,e.length))?l$(t,e):!1}function Tl(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}var zA=he(()=>{l()});function h$(t){return qp(t.method)&&Vp(t.params)}function qp(t){return Tl(t,"subscribe")}function Vp(t){return Sl(t,["topic"],[])}function p$(t){return Hp(t.method)&&kp(t.params)}function Hp(t){return Tl(t,"publish")}function kp(t){return Sl(t,["message","topic","ttl"],["prompt","tag"])}function g$(t){return Gp(t.method)&&jp(t.params)}function Gp(t){return Tl(t,"unsubscribe")}function jp(t){return Sl(t,["id","topic"],[])}function y$(t){return Qp(t.method)&&zp(t.params)}function Qp(t){return Tl(t,"subscription")}function zp(t){return Sl(t,["id","data"],[])}var WA=he(()=>{l();zA()});function m$(t){if(!qp(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!Vp(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Ji(e,"topic"),e}function w$(t){if(!Hp(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!kp(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Ji(e,"topic"),Ji(e,"message"),Ji(e,"ttl","number"),e}function E$(t){if(!Gp(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!jp(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Ji(e,"id"),e}function v$(t){if(!Qp(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!zp(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Ji(e,"id"),Ji(e,"data"),e}var WR=he(()=>{l();zA();WA()});var A$,$R=he(()=>{l();A$={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe"}}});var KR={};ft(KR,{RELAY_JSONRPC:()=>A$,isPublishMethod:()=>Hp,isPublishParams:()=>kp,isPublishRequest:()=>p$,isSubscribeMethod:()=>qp,isSubscribeParams:()=>Vp,isSubscribeRequest:()=>h$,isSubscriptionMethod:()=>Qp,isSubscriptionParams:()=>zp,isSubscriptionRequest:()=>y$,isUnsubscribeMethod:()=>Gp,isUnsubscribeParams:()=>jp,isUnsubscribeRequest:()=>g$,parsePublishRequest:()=>w$,parseSubscribeRequest:()=>m$,parseSubscriptionRequest:()=>v$,parseUnsubscribeRequest:()=>E$});var YR=he(()=>{l();zR();WR();$R();WA()});var Dl=v(H=>{"use strict";l();Object.defineProperty(H,"__esModule",{value:!0});var o3=$P(),b$=eR(),a3=cl(),ZA=rR(),I$=oR(),ct=(HA(),ht(VA)),_$=_R(),eu=Xs(),tu=GA(),S$=TR(),T$=QR(),C$=(YR(),ht(KR));function u3(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var c3=u3(I$),Wp=u3(T$),Yp=":";function l3(t){let[e,r]=t.split(Yp);return{namespace:e,reference:r}}function f3(t){let{namespace:e,reference:r}=t;return[e,r].join(Yp)}function eb(t){let[e,r,n]=t.split(Yp);return{namespace:e,reference:r,address:n}}function d3(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(Yp)}function tb(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function h3(t){let{address:e}=eb(t);return e}function p3(t){let{namespace:e,reference:r}=eb(t);return f3({namespace:e,reference:r})}function x$(t,e){let{namespace:r,reference:n}=l3(e);return d3({namespace:r,reference:n,address:t})}function N$(t){return tb(t,h3)}function g3(t){return tb(t,p3)}function O$(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function D$(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...g3(i.accounts))}),r}function P$(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...Jp(n,i))}),r}function Jp(t,e){return t.includes(":")?[t]:e.chains||[]}var Xp=t=>t?.split(":"),y3=t=>{let e=t&&Xp(t);if(e)return e[3]},R$=t=>{let e=t&&Xp(t);if(e)return e[2]+":"+e[3]},m3=t=>{let e=t&&Xp(t);if(e)return e.pop()},B$=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=m3(e),i=t.statement,s=`URI: ${t.aud}`,o=`Version: ${t.version}`,a=`Chain ID: ${y3(e)}`,u=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources&&t.resources.length>0?`Resources: -${t.resources.map(d=>`- ${d}`).join(` -`)}`:void 0;return[r,n,"",i,"",s,o,a,u,c,f].filter(d=>d!=null).join(` -`)},rb="base10",or="base16",$p="base64pad",Zp="utf8",nb=0,ru=1,L$=0,JR=1,KA=12,ib=32;function F$(){let t=c3.generateKeyPair();return{privateKey:ct.toString(t.secretKey,or),publicKey:ct.toString(t.publicKey,or)}}function M$(){let t=a3.randomBytes(ib);return ct.toString(t,or)}function U$(t,e){let r=c3.sharedKey(ct.fromString(t,or),ct.fromString(e,or),!0),n=new b$.HKDF(ZA.SHA256,r).expand(ib);return ct.toString(n,or)}function q$(t){let e=ZA.hash(ct.fromString(t,or));return ct.toString(e,or)}function V$(t){let e=ZA.hash(ct.fromString(t,Zp));return ct.toString(e,or)}function w3(t){return ct.fromString(`${t}`,rb)}function xl(t){return Number(ct.toString(t,rb))}function H$(t){let e=w3(typeof t.type<"u"?t.type:nb);if(xl(e)===ru&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?ct.fromString(t.senderPublicKey,or):void 0,n=typeof t.iv<"u"?ct.fromString(t.iv,or):a3.randomBytes(KA),i=new o3.ChaCha20Poly1305(ct.fromString(t.symKey,or)).seal(n,ct.fromString(t.message,Zp));return E3({type:e,sealed:i,iv:n,senderPublicKey:r})}function k$(t){let e=new o3.ChaCha20Poly1305(ct.fromString(t.symKey,or)),{sealed:r,iv:n}=sb(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return ct.toString(i,Zp)}function E3(t){if(xl(t.type)===ru){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ct.toString(ct.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),$p)}return ct.toString(ct.concat([t.type,t.iv,t.sealed]),$p)}function sb(t){let e=ct.fromString(t,$p),r=e.slice(L$,JR),n=JR;if(xl(r)===ru){let a=n+ib,u=a+KA,c=e.slice(n,a),f=e.slice(a,u),d=e.slice(u);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+KA,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function G$(t,e){let r=sb(t);return v3({type:xl(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?ct.toString(r.senderPublicKey,or):void 0,receiverPublicKey:e?.receiverPublicKey})}function v3(t){let e=t?.type||nb;if(e===ru){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function j$(t){return t.type===ru&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var Q$=Object.defineProperty,XR=Object.getOwnPropertySymbols,z$=Object.prototype.hasOwnProperty,W$=Object.prototype.propertyIsEnumerable,ZR=(t,e,r)=>e in t?Q$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,e3=(t,e)=>{for(var r in e||(e={}))z$.call(e,r)&&ZR(t,r,e[r]);if(XR)for(var r of XR(e))W$.call(e,r)&&ZR(t,r,e[r]);return t},A3="ReactNative",sr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Kp=" ",$$=":",b3="/",ob=2,K$=1e3,I3="js";function ab(){return typeof p.default<"u"&&typeof p.default.versions<"u"&&typeof p.default.versions.node<"u"}function nu(){return!tu.getDocument()&&!!tu.getNavigator()&&navigator.product===A3}function Nl(){return!ab()&&!!tu.getNavigator()&&!!tu.getDocument()}function oo(){return nu()?sr.reactNative:ab()?sr.node:Nl()?sr.browser:sr.unknown}function Y$(){var t;try{return nu()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function _3(t,e){let r=Wp.parse(t);return r=e3(e3({},r),e),t=Wp.stringify(r),t}function J$(){return S$.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function X$(t,e){var r;let n=oo(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=tu.getLocation())==null?void 0:r.host)||"unknown"),i}function S3(){if(oo()===sr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=_$.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function T3(){var t;let e=oo();return e===sr.browser?[e,((t=tu.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function C3(t,e,r){let n=S3(),i=T3();return[[t,e].join("-"),[I3,r].join("-"),n,i].join("/")}function Z$({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a}){let u=r.split("?"),c=C3(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:a||void 0},d=_3(u[1]||"",f);return u[0]+"?"+d}function eK(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function tK(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function x3(t,e=ob){return N3(t.split(b3),e)}function rK(t){return x3(t).join(Kp)}function Xi(t,e){return t.filter(r=>e.includes(r)).length===t.length}function N3(t,e=ob){return t.slice(Math.max(t.length-e,0))}function nK(t){return Object.fromEntries(t.entries())}function iK(t){return new Map(Object.entries(t))}function sK(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var oK=t=>t;function O3(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function aK(t){return t.split(Kp).map(e=>O3(e)).join(Kp)}function uK(t=eu.FIVE_MINUTES,e){let r=eu.toMiliseconds(t||eu.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,a)=>{s=setTimeout(()=>{a(new Error(e))},r),n=o,i=a})}}function cK(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function ub(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function lK(t){return ub("topic",t)}function fK(t){return ub("id",t)}function dK(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function hK(t,e){return eu.fromMiliseconds((e||Date.now())+eu.toMiliseconds(t))}function pK(t){return Date.now()>=eu.toMiliseconds(t)}function gK(t,e){return`${t}${e?`:${e}`:""}`}function Zi(t=[],e=[]){return[...new Set([...t,...e])]}async function yK({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=oo();o===sr.browser?s.startsWith("https://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===sr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function mK(t,e){try{return await t.getItem(e)||(Nl()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}var D3="irn";function wK(t){return t?.relay||{protocol:D3}}function EK(t){let e=C$.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var vK=Object.defineProperty,t3=Object.getOwnPropertySymbols,AK=Object.prototype.hasOwnProperty,bK=Object.prototype.propertyIsEnumerable,r3=(t,e,r)=>e in t?vK(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,IK=(t,e)=>{for(var r in e||(e={}))AK.call(e,r)&&r3(t,r,e[r]);if(t3)for(var r of t3(e))bK.call(e,r)&&r3(t,r,e[r]);return t};function P3(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function _K(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=Wp.parse(s);return{protocol:n,topic:R3(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:P3(o)}}function R3(t){return t.startsWith("//")?t.substring(2):t}function B3(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function SK(t){return`${t.protocol}:${t.topic}@${t.version}?`+Wp.stringify(IK({symKey:t.symKey},B3(t.relay)))}var TK=Object.defineProperty,CK=Object.defineProperties,xK=Object.getOwnPropertyDescriptors,n3=Object.getOwnPropertySymbols,NK=Object.prototype.hasOwnProperty,OK=Object.prototype.propertyIsEnumerable,i3=(t,e,r)=>e in t?TK(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,DK=(t,e)=>{for(var r in e||(e={}))NK.call(e,r)&&i3(t,r,e[r]);if(n3)for(var r of n3(e))OK.call(e,r)&&i3(t,r,e[r]);return t},PK=(t,e)=>CK(t,xK(e));function ao(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function L3(t){let e=[];return Object.values(t).forEach(r=>{e.push(...ao(r.accounts))}),e}function F3(t,e){let r=[];return Object.values(t).forEach(n=>{ao(n.accounts).includes(e)&&r.push(...n.methods)}),r}function M3(t,e){let r=[];return Object.values(t).forEach(n=>{ao(n.accounts).includes(e)&&r.push(...n.events)}),r}function RK(t,e){let r=W3(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function BK(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=YA(e),s=YA(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,g=n[c].events,m=n[c].accounts;f.forEach(y=>{if(!m.some(A=>A.includes(y)))throw new Error(`No accounts provided for chain ${y} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:g,accounts:m}});let a=K3(e,o,"approve()");if(a)throw new Error(a.message);let u={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(y=>{var A,O;return(O=(A=i[c])==null?void 0:A.chains)==null?void 0:O.includes(y)}),d=n[c].methods.filter(y=>{var A,O;return(O=(A=i[c])==null?void 0:A.methods)==null?void 0:O.includes(y)}),g=n[c].events.filter(y=>{var A,O;return(O=(A=i[c])==null?void 0:A.events)==null?void 0:O.includes(y)}),m=f.map(y=>n[c].accounts.filter(A=>A.includes(`${y}:`))).flat();u[c]={chains:f,methods:d,events:g,accounts:m}}),Object.keys(s).forEach(c=>{var f,d,g,m,y,A;if(!n[c])return;let O=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(b=>n[c].chains.includes(b)),R=n[c].methods.filter(b=>{var S,N;return(N=(S=s[c])==null?void 0:S.methods)==null?void 0:N.includes(b)}),q=n[c].events.filter(b=>{var S,N;return(N=(S=s[c])==null?void 0:S.events)==null?void 0:N.includes(b)}),M=O?.map(b=>n[c].accounts.filter(S=>S.includes(`${b}:`))).flat();u[c]={chains:Zi((g=u[c])==null?void 0:g.chains,O),methods:Zi((m=u[c])==null?void 0:m.methods,R),events:Zi((y=u[c])==null?void 0:y.events,q),accounts:Zi((A=u[c])==null?void 0:A.accounts,M)}}),u)}function cb(t){return t.includes(":")}function U3(t){return cb(t)?t.split(":")[0]:t}function YA(t){var e,r,n;let i={};if(!eg(t))return i;for(let[s,o]of Object.entries(t)){let a=cb(s)?[s]:o.chains,u=o.methods||[],c=o.events||[],f=U3(s);i[f]=PK(DK({},i[f]),{chains:Zi(a,(e=i[f])==null?void 0:e.chains),methods:Zi(u,(r=i[f])==null?void 0:r.methods),events:Zi(c,(n=i[f])==null?void 0:n.events)})}return i}var q3={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},V3={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function li(t,e){let{message:r,code:n}=V3[t];return{message:e?`${r} ${e}`:r,code:n}}function so(t,e){let{message:r,code:n}=q3[t];return{message:e?`${r} ${e}`:r,code:n}}function Ol(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function eg(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function es(t){return typeof t>"u"}function _r(t,e){return e&&es(t)?!0:typeof t=="string"&&!!t.trim().length}function tg(t,e){return e&&es(t)?!0:typeof t=="number"&&!isNaN(t)}function LK(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Xi(i,n)?(n.forEach(o=>{let{accounts:a,methods:u,events:c}=t.namespaces[o],f=ao(a),d=r[o];(!Xi(Jp(o,d),f)||!Xi(d.methods,u)||!Xi(d.events,c))&&(s=!1)}),s):!1}function Cl(t){return _r(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function H3(t){if(_r(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&Cl(r)}}return!1}function FK(t){if(_r(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function MK(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function UK(t){return t?.topic}function qK(t,e){let r=null;return _r(t?.publicKey,!1)||(r=li("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function JA(t){let e=!0;return Ol(t)?t.length&&(e=t.every(r=>_r(r,!1))):e=!1,e}function k3(t,e,r){let n=null;return Ol(e)&&e.length?e.forEach(i=>{n||Cl(i)||(n=so("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Cl(t)||(n=so("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function G3(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=k3(i,Jp(i,s),`${e} ${r}`);o&&(n=o)}),n}function j3(t,e){let r=null;return Ol(t)?t.forEach(n=>{r||H3(n)||(r=so("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=so("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function Q3(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=j3(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function z3(t,e){let r=null;return JA(t?.methods)?JA(t?.events)||(r=so("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=so("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function lb(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=z3(n,`${e}, namespace`);i&&(r=i)}),r}function VK(t,e,r){let n=null;if(t&&eg(t)){let i=lb(t,e);i&&(n=i);let s=G3(t,e,r);s&&(n=s)}else n=li("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function W3(t,e){let r=null;if(t&&eg(t)){let n=lb(t,e);n&&(r=n);let i=Q3(t,e);i&&(r=i)}else r=li("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function $3(t){return _r(t.protocol,!0)}function HK(t,e){let r=!1;return e&&!t?r=!0:t&&Ol(t)&&t.length&&t.forEach(n=>{r=$3(n)}),r}function kK(t){return typeof t=="number"}function GK(t){return typeof t<"u"&&typeof t!==null}function jK(t){return!(!t||typeof t!="object"||!t.code||!tg(t.code,!1)||!t.message||!_r(t.message,!1))}function QK(t){return!(es(t)||!_r(t.method,!1))}function zK(t){return!(es(t)||es(t.result)&&es(t.error)||!tg(t.id,!1)||!_r(t.jsonrpc,!1))}function WK(t){return!(es(t)||!_r(t.name,!1))}function $K(t,e){return!(!Cl(e)||!L3(t).includes(e))}function KK(t,e,r){return _r(r,!1)?F3(t,e).includes(r):!1}function YK(t,e,r){return _r(r,!1)?M3(t,e).includes(r):!1}function K3(t,e,r){let n=null,i=JK(t),s=XK(e),o=Object.keys(i),a=Object.keys(s),u=s3(Object.keys(t)),c=s3(Object.keys(e)),f=u.filter(d=>!c.includes(d));return f.length&&(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. - Required: ${f.toString()} - Received: ${Object.keys(e).toString()}`)),Xi(o,a)||(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. - Required: ${o.toString()} - Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let g=ao(e[d].accounts);g.includes(d)||(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} - Required: ${d} - Approved: ${g.toString()}`))}),o.forEach(d=>{n||(Xi(i[d].methods,s[d].methods)?Xi(i[d].events,s[d].events)||(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function JK(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function s3(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function XK(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:ao(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function ZK(t,e){return tg(t,!1)&&t<=e.max&&t>=e.min}function eY(){let t=oo();return new Promise(e=>{switch(t){case sr.browser:e(Y3());break;case sr.reactNative:e(J3());break;case sr.node:e(X3());break;default:e(!0)}})}function Y3(){return Nl()&&navigator?.onLine}async function J3(){return nu()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function X3(){return!0}function tY(t){switch(oo()){case sr.browser:Z3(t);break;case sr.reactNative:eB(t);break;case sr.node:break}}function Z3(t){!nu()&&Nl()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function eB(t){nu()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var $A={},XA=class{static get(e){return $A[e]}static set(e,r){$A[e]=r}static delete(e){delete $A[e]}};H.BASE10=rb,H.BASE16=or,H.BASE64=$p,H.COLON=$$,H.DEFAULT_DEPTH=ob,H.EMPTY_SPACE=Kp,H.ENV_MAP=sr,H.INTERNAL_ERRORS=V3,H.MemoryStore=XA,H.ONE_THOUSAND=K$,H.REACT_NATIVE_PRODUCT=A3,H.RELAYER_DEFAULT_PROTOCOL=D3,H.SDK_ERRORS=q3,H.SDK_TYPE=I3,H.SLASH=b3,H.TYPE_0=nb,H.TYPE_1=ru,H.UTF8=Zp,H.appendToQueryString=_3,H.assertType=tK,H.buildApprovedNamespaces=BK,H.calcExpiry=hK,H.capitalize=aK,H.capitalizeWord=O3,H.createDelayedPromise=uK,H.createExpiringPromise=cK,H.decodeTypeByte=xl,H.decrypt=k$,H.deriveSymKey=U$,H.deserialize=sb,H.encodeTypeByte=w3,H.encrypt=H$,H.engineEvent=gK,H.enumify=oK,H.formatAccountId=d3,H.formatAccountWithChain=x$,H.formatChainId=f3,H.formatExpirerTarget=ub,H.formatIdTarget=fK,H.formatMessage=B$,H.formatMessageContext=rK,H.formatRelayParams=B3,H.formatRelayRpcUrl=Z$,H.formatTopicTarget=lK,H.formatUA=C3,H.formatUri=SK,H.generateKeyPair=F$,H.generateRandomBytes32=M$,H.getAccountsChains=ao,H.getAccountsFromNamespaces=O$,H.getAddressFromAccount=h3,H.getAddressesFromAccounts=N$,H.getAppMetadata=J$,H.getBrowserOnlineStatus=Y3,H.getBundleId=Y$,H.getChainFromAccount=p3,H.getChainsFromAccounts=g3,H.getChainsFromNamespace=Jp,H.getChainsFromNamespaces=D$,H.getChainsFromRequiredNamespaces=P$,H.getDeepLink=mK,H.getDidAddress=m3,H.getDidAddressSegments=Xp,H.getDidChainId=y3,H.getEnvironment=oo,H.getHttpUrl=eK,H.getInternalError=li,H.getJavascriptID=T3,H.getJavascriptOS=S3,H.getLastItems=N3,H.getNamespacedDidChainId=R$,H.getNamespacesChains=L3,H.getNamespacesEventsForChainId=M3,H.getNamespacesMethodsForChainId=F3,H.getNodeOnlineStatus=X3,H.getReactNativeOnlineStatus=J3,H.getRelayClientMetadata=X$,H.getRelayProtocolApi=EK,H.getRelayProtocolName=wK,H.getRequiredNamespacesFromNamespaces=RK,H.getSdkError=so,H.getUniqueValues=tb,H.handleDeeplinkRedirect=yK,H.hasOverlap=Xi,H.hashKey=q$,H.hashMessage=V$,H.isBrowser=Nl,H.isCaipNamespace=cb,H.isConformingNamespaces=K3,H.isExpired=pK,H.isNode=ab,H.isOnline=eY,H.isProposalStruct=MK,H.isReactNative=nu,H.isSessionCompatible=LK,H.isSessionStruct=UK,H.isTypeOneEnvelope=j$,H.isUndefined=es,H.isValidAccountId=H3,H.isValidAccounts=j3,H.isValidActions=z3,H.isValidArray=Ol,H.isValidChainId=Cl,H.isValidChains=k3,H.isValidController=qK,H.isValidErrorReason=jK,H.isValidEvent=WK,H.isValidId=kK,H.isValidNamespaceAccounts=Q3,H.isValidNamespaceActions=lb,H.isValidNamespaceChains=G3,H.isValidNamespaceMethodsOrEvents=JA,H.isValidNamespaces=W3,H.isValidNamespacesChainId=$K,H.isValidNamespacesEvent=YK,H.isValidNamespacesRequest=KK,H.isValidNumber=tg,H.isValidObject=eg,H.isValidParams=GK,H.isValidRelay=$3,H.isValidRelays=HK,H.isValidRequest=QK,H.isValidRequestExpiry=ZK,H.isValidRequiredNamespaces=VK,H.isValidResponse=zK,H.isValidString=_r,H.isValidUrl=FK,H.mapEntries=sK,H.mapToObj=nK,H.mergeArrays=Zi,H.normalizeNamespaces=YA,H.objToMap=iK,H.parseAccountId=eb,H.parseChainId=l3,H.parseContextNames=x3,H.parseExpirerTarget=dK,H.parseNamespaceKey=U3,H.parseRelayParams=P3,H.parseTopic=R3,H.parseUri=_K,H.serialize=E3,H.subscribeToBrowserNetworkChange=Z3,H.subscribeToNetworkChange=tY,H.subscribeToReactNativeNetworkChange=eB,H.validateDecoding=G$,H.validateEncoding=v3});var tB,rB,nB,iB,rg,Pl,fb,ng,ts,Rl,ig=he(()=>{l();tB="PARSE_ERROR",rB="INVALID_REQUEST",nB="METHOD_NOT_FOUND",iB="INVALID_PARAMS",rg="INTERNAL_ERROR",Pl="SERVER_ERROR",fb=[-32700,-32600,-32601,-32602,-32603],ng=[-32e3,-32099],ts={[tB]:{code:-32700,message:"Parse error"},[rB]:{code:-32600,message:"Invalid Request"},[nB]:{code:-32601,message:"Method not found"},[iB]:{code:-32602,message:"Invalid params"},[rg]:{code:-32603,message:"Internal error"},[Pl]:{code:-32e3,message:"Server error"}},Rl=Pl});function rY(t){return t<=ng[0]&&t>=ng[1]}function sg(t){return fb.includes(t)}function sB(t){return typeof t=="number"}function og(t){return Object.keys(ts).includes(t)?ts[t]:ts[Rl]}function ag(t){let e=Object.values(ts).find(r=>r.code===t);return e||ts[Rl]}function nY(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!sB(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(sg(t.error.code)){let e=ag(t.error.code);if(e.message!==ts[Rl].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function db(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var hb=he(()=>{l();ig()});var aB=v(rs=>{"use strict";l();Object.defineProperty(rs,"__esModule",{value:!0});rs.isBrowserCryptoAvailable=rs.getSubtleCrypto=rs.getBrowerCrypto=void 0;function pb(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}rs.getBrowerCrypto=pb;function oB(){let t=pb();return t.subtle||t.webkitSubtle}rs.getSubtleCrypto=oB;function iY(){return!!pb()&&!!oB()}rs.isBrowserCryptoAvailable=iY});var lB=v(ns=>{"use strict";l();Object.defineProperty(ns,"__esModule",{value:!0});ns.isBrowser=ns.isNode=ns.isReactNative=void 0;function uB(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ns.isReactNative=uB;function cB(){return typeof p.default<"u"&&typeof p.default.versions<"u"&&typeof p.default.versions.node<"u"}ns.isNode=cB;function sY(){return!uB()&&!cB()}ns.isBrowser=sY});var gb=v(ug=>{"use strict";l();Object.defineProperty(ug,"__esModule",{value:!0});var fB=(en(),ht(Zr));fB.__exportStar(aB(),ug);fB.__exportStar(lB(),ug)});var kt={};ft(kt,{isNodeJs:()=>hB});var dB,hB,pB=he(()=>{l();dB=be(gb());Qt(kt,be(gb()));hB=dB.isNode});function yb(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function mb(t=6){return BigInt(yb(t))}function wb(t,e,r){return{id:r||yb(),jsonrpc:"2.0",method:t,params:e}}function oY(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Eb(t,e,r){return{id:t,jsonrpc:"2.0",error:gB(e,r)}}function gB(t,e){return typeof t>"u"?og(rg):(typeof t=="string"&&(t=Object.assign(Object.assign({},og(Pl)),{message:t})),typeof e<"u"&&(t.data=e),sg(t.code)&&(t=ag(t.code)),t)}var yB=he(()=>{l();hb();ig()});function aY(t){return t.includes("*")?lg(t):!/\W/g.test(t)}function cg(t){return t==="*"}function lg(t){return cg(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function uY(t){return!cg(t)&&lg(t)&&!t.split("*")[0].trim()}function cY(t){return!cg(t)&&lg(t)&&!t.split("*")[1].trim()}var mB=he(()=>{l()});var wB=he(()=>{l()});var iu,vb=he(()=>{l();iu=class{}});var Ab,fg,Bl,EB=he(()=>{l();vb();Ab=class extends iu{constructor(e){super()}},fg=class extends iu{constructor(){super()}},Bl=class extends fg{constructor(e){super()}}});var vB=he(()=>{l()});var AB=he(()=>{l();wB();vb();EB();vB()});var bB=he(()=>{l();AB()});function dY(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function IB(t,e){let r=dY(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function hY(t){return IB(t,lY)}function dg(t){return IB(t,fY)}function bb(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var lY,fY,_B=he(()=>{l();lY="^https?:",fY="^wss?:"});function Ib(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function pY(t){return Ib(t)&&"method"in t}function _b(t){return Ib(t)&&(SB(t)||hg(t))}function SB(t){return"result"in t}function hg(t){return"error"in t}function gY(t){return"error"in t&&t.valid===!1}var TB=he(()=>{l()});var rr={};ft(rr,{DEFAULT_ERROR:()=>Rl,IBaseJsonRpcProvider:()=>fg,IEvents:()=>iu,IJsonRpcConnection:()=>Ab,IJsonRpcProvider:()=>Bl,INTERNAL_ERROR:()=>rg,INVALID_PARAMS:()=>iB,INVALID_REQUEST:()=>rB,METHOD_NOT_FOUND:()=>nB,PARSE_ERROR:()=>tB,RESERVED_ERROR_CODES:()=>fb,SERVER_ERROR:()=>Pl,SERVER_ERROR_CODE_RANGE:()=>ng,STANDARD_ERROR_MAP:()=>ts,formatErrorMessage:()=>gB,formatJsonRpcError:()=>Eb,formatJsonRpcRequest:()=>wb,formatJsonRpcResult:()=>oY,getBigIntRpcId:()=>mb,getError:()=>og,getErrorByCode:()=>ag,isHttpUrl:()=>hY,isJsonRpcError:()=>hg,isJsonRpcPayload:()=>Ib,isJsonRpcRequest:()=>pY,isJsonRpcResponse:()=>_b,isJsonRpcResult:()=>SB,isJsonRpcValidationInvalid:()=>gY,isLocalhostUrl:()=>bb,isNodeJs:()=>hB,isReservedErrorCode:()=>sg,isServerErrorCode:()=>rY,isValidDefaultRoute:()=>cg,isValidErrorCode:()=>sB,isValidLeadingWildcardRoute:()=>uY,isValidRoute:()=>aY,isValidTrailingWildcardRoute:()=>cY,isValidWildcardRoute:()=>lg,isWsUrl:()=>dg,parseConnectionError:()=>db,payloadId:()=>yb,validateJsonRpcError:()=>nY});var Ll=he(()=>{l();ig();hb();pB();Qt(rr,kt);yB();mB();bB();_B();TB()});var CB,pg,xB,Sb=he(()=>{l();CB=be(ti());Ll();pg=class extends Bl{constructor(e){super(e),this.events=new CB.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(wb(e.method,e.params||[],e.id||mb().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{hg(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),_b(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},xB=pg});var NB={};ft(NB,{JsonRpcProvider:()=>pg,default:()=>yY});var yY,OB=he(()=>{l();Sb();Sb();yY=xB});var PB=v((s0e,DB)=>{"use strict";l();DB.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var FB={};ft(FB,{WsConnection:()=>Tb,default:()=>Tb});var LB,mY,wY,RB,BB,EY,Tb,MB=he(()=>{l();LB=be(ti());nl();Ll();mY=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:PB(),wY=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",RB=t=>t.split("?")[0],BB=10,EY=mY(),Tb=class{constructor(e){if(this.url=e,this.events=new LB.EventEmitter,this.registering=!1,!dg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Qi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!dg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,rr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!bb(e)},o=new EY(e,[],s);wY()?o.onerror=a=>{let u=a;n(this.emitError(u.error))}:o.on("error",a=>{n(this.emitError(a))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?ji(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=Eb(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return db(e,RB(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>BB&&this.events.setMaxListeners(BB)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${RB(this.url)}`));return this.events.emit("register_error",r),r}}});var w6=v((Fl,ou)=>{l();var vY=200,Mb="__lodash_hash_undefined__",bg=1,KB=2,YB=9007199254740991,gg="[object Arguments]",Ob="[object Array]",AY="[object AsyncFunction]",JB="[object Boolean]",XB="[object Date]",ZB="[object Error]",e6="[object Function]",bY="[object GeneratorFunction]",yg="[object Map]",t6="[object Number]",IY="[object Null]",su="[object Object]",UB="[object Promise]",_Y="[object Proxy]",r6="[object RegExp]",mg="[object Set]",n6="[object String]",SY="[object Symbol]",TY="[object Undefined]",Db="[object WeakMap]",i6="[object ArrayBuffer]",wg="[object DataView]",CY="[object Float32Array]",xY="[object Float64Array]",NY="[object Int8Array]",OY="[object Int16Array]",DY="[object Int32Array]",PY="[object Uint8Array]",RY="[object Uint8ClampedArray]",BY="[object Uint16Array]",LY="[object Uint32Array]",FY=/[\\^$.*+?()[\]{}|]/g,MY=/^\[object .+?Constructor\]$/,UY=/^(?:0|[1-9]\d*)$/,st={};st[CY]=st[xY]=st[NY]=st[OY]=st[DY]=st[PY]=st[RY]=st[BY]=st[LY]=!0;st[gg]=st[Ob]=st[i6]=st[JB]=st[wg]=st[XB]=st[ZB]=st[e6]=st[yg]=st[t6]=st[su]=st[r6]=st[mg]=st[n6]=st[Db]=!1;var s6=typeof global=="object"&&global&&global.Object===Object&&global,qY=typeof self=="object"&&self&&self.Object===Object&&self,fi=s6||qY||Function("return this")(),o6=typeof Fl=="object"&&Fl&&!Fl.nodeType&&Fl,qB=o6&&typeof ou=="object"&&ou&&!ou.nodeType&&ou,a6=qB&&qB.exports===o6,Cb=a6&&s6.process,VB=function(){try{return Cb&&Cb.binding&&Cb.binding("util")}catch{}}(),HB=VB&&VB.isTypedArray;function VY(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function yJ(t,e){var r=this.__data__,n=_g(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}di.prototype.clear=dJ;di.prototype.delete=hJ;di.prototype.get=pJ;di.prototype.has=gJ;di.prototype.set=yJ;function lo(t){var e=-1,r=t==null?0:t.length;for(this.clear();++ea))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,g=r&KB?new vg:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=YB}function y6(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ql(t){return t!=null&&typeof t=="object"}var m6=HB?jY(HB):RJ;function WJ(t){return QJ(t)?NJ(t):BJ(t)}function $J(){return[]}function KJ(){return!1}ou.exports=zJ});var Ub=v((f0e,E6)=>{l();E6.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},u=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:u,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return a[f.toLowerCase()]},has:function(f){return f.toLowerCase()in a}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,g){s.push(d=d.toLowerCase()),o.push([d,g]),a[d]=a[d]?a[d]+","+g:g}),r(u())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var A6=v((h0e,v6)=>{l();v6.exports=self.fetch||(self.fetch=Ub().default||Ub())});var x8=v(we=>{"use strict";l();Object.defineProperty(we,"__esModule",{value:!0});var ho=ti(),YJ=(V2(),ht(q2)),Gl=nD(),Qe=m1(),Ln=F1(),b6=(nl(),ht(M2)),JJ=(VP(),ht(qP)),te=Dl(),XJ=(HA(),ht(VA)),Ke=Xs(),ZJ=(OB(),ht(NB)),Sr=(Ll(),ht(rr)),eX=(MB(),ht(FB)),tX=w6(),rX=A6();function jl(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function nX(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var iX=jl(ho),sX=jl(YJ),Tg=nX(JJ),oX=jl(eX),aX=jl(tX),uX=jl(rX);function cX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,b=new Uint8Array(M);R!==q;){for(var S=y[R],N=0,_=M-1;(S!==0||N>>0,b[_]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");O=N,R++}for(var T=M-O;T!==M&&b[T]===0;)T++;for(var B=u.repeat(A);T>>0,M=new Uint8Array(q);y[A];){var b=r[y.charCodeAt(A)];if(b===255)return;for(var S=0,N=q-1;(b!==0||S>>0,M[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");R=S,A++}if(y[A]!==" "){for(var _=q-R;_!==q&&M[_]===0;)_++;for(var T=new Uint8Array(O+(q-_)),B=O;_!==q;)T[B++]=M[_++];return T}}}function m(y){var A=g(y);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:g,decode:m}}var lX=cX,fX=lX,q6=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},dX=t=>new TextEncoder().encode(t),hX=t=>new TextDecoder().decode(t),Hb=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},kb=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return V6(this,e)}},Gb=class{constructor(e){this.decoders=e}or(e){return V6(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},V6=(t,e)=>new Gb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),jb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Hb(e,r,n),this.decoder=new kb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Hg=({name:t,prefix:e,encode:r,decode:n})=>new jb(t,e,r,n),Ql=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=fX(r,e);return Hg({prefix:t,name:e,encode:n,decode:s=>q6(i(s))})},pX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(a-=8,o[c++]=255&u>>a)}if(a>=r||255&u<<8-a)throw new SyntaxError("Unexpected end of data");return o},gX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<Hg({prefix:e,name:t,encode(i){return gX(i,n,r)},decode(i){return pX(i,n,r,t)}}),yX=Hg({prefix:"\0",name:"identity",encode:t=>hX(t),decode:t=>dX(t)}),mX=Object.freeze({__proto__:null,identity:yX}),wX=zt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),EX=Object.freeze({__proto__:null,base2:wX}),vX=zt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),AX=Object.freeze({__proto__:null,base8:vX}),bX=Ql({prefix:"9",name:"base10",alphabet:"0123456789"}),IX=Object.freeze({__proto__:null,base10:bX}),_X=zt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),SX=zt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),TX=Object.freeze({__proto__:null,base16:_X,base16upper:SX}),CX=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xX=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),NX=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),OX=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),DX=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),PX=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),RX=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),BX=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),LX=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),FX=Object.freeze({__proto__:null,base32:CX,base32upper:xX,base32pad:NX,base32padupper:OX,base32hex:DX,base32hexupper:PX,base32hexpad:RX,base32hexpadupper:BX,base32z:LX}),MX=Ql({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),UX=Ql({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),qX=Object.freeze({__proto__:null,base36:MX,base36upper:UX}),VX=Ql({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),HX=Ql({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),kX=Object.freeze({__proto__:null,base58btc:VX,base58flickr:HX}),GX=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jX=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QX=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zX=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),WX=Object.freeze({__proto__:null,base64:GX,base64pad:jX,base64url:QX,base64urlpad:zX}),H6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$X=H6.reduce((t,e,r)=>(t[r]=e,t),[]),KX=H6.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function YX(t){return t.reduce((e,r)=>(e+=$X[r],e),"")}function JX(t){let e=[];for(let r of t){let n=KX[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var XX=Hg({prefix:"\u{1F680}",name:"base256emoji",encode:YX,decode:JX}),ZX=Object.freeze({__proto__:null,base256emoji:XX}),eZ=k6,I6=128,tZ=127,rZ=~tZ,nZ=Math.pow(2,31);function k6(t,e,r){e=e||[],r=r||0;for(var n=r;t>=nZ;)e[r++]=t&255|I6,t/=128;for(;t&rZ;)e[r++]=t&255|I6,t>>>=7;return e[r]=t|0,k6.bytes=r-n+1,e}var iZ=Qb,sZ=128,_6=127;function Qb(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Qb.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&_6)<=sZ);return Qb.bytes=s-n,r}var oZ=Math.pow(2,7),aZ=Math.pow(2,14),uZ=Math.pow(2,21),cZ=Math.pow(2,28),lZ=Math.pow(2,35),fZ=Math.pow(2,42),dZ=Math.pow(2,49),hZ=Math.pow(2,56),pZ=Math.pow(2,63),gZ=function(t){return t(G6.encode(t,e,r),e),T6=t=>G6.encodingLength(t),zb=(t,e)=>{let r=e.byteLength,n=T6(t),i=n+T6(r),s=new Uint8Array(i+r);return S6(t,s,0),S6(r,s,n),s.set(e,i),new Wb(t,r,e,s)},Wb=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},j6=({name:t,code:e,encode:r})=>new $b(t,e,r),$b=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?zb(this.code,r):r.then(n=>zb(this.code,n))}else throw Error("Unknown type, must be binary type")}},Q6=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),mZ=j6({name:"sha2-256",code:18,encode:Q6("SHA-256")}),wZ=j6({name:"sha2-512",code:19,encode:Q6("SHA-512")}),EZ=Object.freeze({__proto__:null,sha256:mZ,sha512:wZ}),z6=0,vZ="identity",W6=q6,AZ=t=>zb(z6,W6(t)),bZ={code:z6,name:vZ,encode:W6,digest:AZ},IZ=Object.freeze({__proto__:null,identity:bZ});new TextEncoder,new TextDecoder;var C6={...mX,...EX,...AX,...IX,...TX,...FX,...qX,...kX,...WX,...ZX};({...EZ,...IZ});function $6(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function _Z(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?$6(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function K6(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var x6=K6("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),qb=K6("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=_Z(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=Qe.generateChildLogger(r,this.name)}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,te.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?te.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Og=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=Z6,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=Tg.generateKeyPair(i);return Tg.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=te.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=Tg.generateKeyPair(s),a=te.generateRandomBytes32(),u=e8;return await Tg.signJWT(a,i,u,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let a=this.getPrivateKey(i),u=te.deriveSymKey(a,s);return this.setSymKey(u,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||te.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let a=te.validateEncoding(o),u=b6.safeJsonStringify(s);if(te.isTypeOneEnvelope(a)){let g=a.senderPublicKey,m=a.receiverPublicKey;i=await this.generateSharedKey(g,m)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=a;return te.encrypt({type:f,symKey:c,message:u,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let a=te.validateDecoding(s,o);if(te.isTypeOneEnvelope(a)){let u=a.receiverPublicKey,c=a.senderPublicKey;i=await this.generateSharedKey(u,c)}try{let u=this.getSymKey(i),c=te.decrypt({symKey:u,encoded:s});return b6.safeJsonParse(c)}catch(u){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(u)}},this.getPayloadType=i=>{let s=te.deserialize(i);return te.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=te.deserialize(i);return s.senderPublicKey?XJ.toString(s.senderPublicKey,te.BASE16):void 0},this.core=e,this.logger=Qe.generateChildLogger(r,this.name),this.keychain=n||new Ng(this.core,this.logger)}get context(){return Qe.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Kb)}catch{e=te.generateRandomBytes32(),await this.keychain.set(Kb,e)}return TZ(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Dg=class extends Ln.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=n8,this.version=i8,this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=te.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=te.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=Qe.generateChildLogger(e,this.name),this.core=r}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,te.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?te.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Jb=class extends Ln.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new ho.EventEmitter,this.name=o8,this.queue=new Map,this.publishTimeout=Ke.toMiliseconds(Ke.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});try{let a=s?.ttl||s8,u=te.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||Sr.getBigIntRpcId().toString(),g={topic:n,message:i,opts:{ttl:a,relay:u,prompt:c,tag:f,id:d}},m=setTimeout(()=>this.queue.set(d,g),this.publishTimeout);try{await await te.createExpiringPromise(this.rpcPublish(n,i,a,u,c,f,d),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(d),this.relayer.events.emit(ar.publish,g)}catch(y){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(o=s?.internal)!=null&&o.throwOnFailedPublish)throw this.removeRequestFromQueue(d),y;return}finally{clearTimeout(m)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}})}catch(a){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(a),a}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=Qe.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return Qe.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,a){var u,c,f,d;let g={method:te.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:a};return te.isUndefined((u=g.params)==null?void 0:u.prompt)&&((c=g.params)==null||delete c.prompt),te.isUndefined((f=g.params)==null?void 0:f.tag)&&((d=g.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g}),this.relayer.request(g)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ar.connection_stalled);return}this.checkQueue()}),this.relayer.on(ar.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},Xb=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},DZ=Object.defineProperty,PZ=Object.defineProperties,RZ=Object.getOwnPropertyDescriptors,N6=Object.getOwnPropertySymbols,BZ=Object.prototype.hasOwnProperty,LZ=Object.prototype.propertyIsEnumerable,O6=(t,e,r)=>e in t?DZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hl=(t,e)=>{for(var r in e||(e={}))BZ.call(e,r)&&O6(t,r,e[r]);if(N6)for(var r of N6(e))LZ.call(e,r)&&O6(t,r,e[r]);return t},Vb=(t,e)=>PZ(t,RZ(e)),Pg=class extends Ln.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new Xb,this.events=new ho.EventEmitter,this.name=y8,this.version=m8,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hi,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=te.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let a=await this.rpcSubscribe(n,s);return this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,s)=>{let o=new Ke.Watch;o.start(this.pendingSubscriptionWatchLabel);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),i(!0)),o.elapsed(this.pendingSubscriptionWatchLabel)>=w8&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),s(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Qe.generateChildLogger(r,this.name),this.clientId=""}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=te.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=te.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:te.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await te.createExpiringPromise(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ar.connection_stalled)}return te.hashMessage(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:te.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await te.createExpiringPromise(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(ar.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:te.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Vb(Hl({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Hl({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,Hl({},r)),this.topicMap.set(r.topic,e),this.events.emit(Gr.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Gr.deleted,Vb(Hl({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Gr.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);te.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>Vb(Hl({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(ar.connect,async()=>{await this.onConnect()}),this.relayer.on(ar.disconnect,()=>{this.onDisconnect()}),this.events.on(Gr.created,async e=>{let r=Gr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Gr.deleted,async e=>{let r=Gr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},FZ=Object.defineProperty,D6=Object.getOwnPropertySymbols,MZ=Object.prototype.hasOwnProperty,UZ=Object.prototype.propertyIsEnumerable,P6=(t,e,r)=>e in t?FZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qZ=(t,e)=>{for(var r in e||(e={}))MZ.call(e,r)&&P6(t,r,e[r]);if(D6)for(var r of D6(e))UZ.call(e,r)&&P6(t,r,e[r]);return t},Rg=class extends Ln.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new ho.EventEmitter,this.name=c8,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async r=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(r)}catch(n){throw this.logger.debug("Failed to Publish Request"),this.logger.error(n),n}},this.onPayloadHandler=r=>{this.onProviderPayload(r)},this.onConnectHandler=()=>{this.events.emit(ar.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(ar.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Bn.payload,this.onPayloadHandler),this.provider.on(Bn.connect,this.onConnectHandler),this.provider.on(Bn.disconnect,this.onDisconnectHandler),this.provider.on(Bn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Qe.generateChildLogger(e.logger,this.name):Qe.pino(Qe.getDefaultLoggerOptions({level:e.logger||u8})),this.messages=new Dg(this.logger,e.core),this.subscriber=new Pg(this,this.logger),this.publisher=new Jb(this,this.logger),this.relayUrl=e?.relayUrl||eI,this.projectId=e.projectId,this.bundleId=te.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${Yb}...`),await this.restartTransport(Yb)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},h8)}get context(){return Qe.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";if(i)return i;let s,o=a=>{a.topic===e&&(this.subscriber.off(Gr.created,o),s())};return await Promise.all([new Promise(a=>{s=a,this.subscriber.on(Gr.created,o)}),new Promise(async a=>{i=await this.subscriber.subscribe(e,r),a()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await te.createExpiringPromise(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(r=>{if(!this.initialized)return r();this.subscriber.once(Gr.resubscribed,()=>{r()})}),new Promise(async(r,n)=>{try{await te.createExpiringPromise(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){n(i);return}r()})])}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r;this.provider.events.emit(Bn.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await te.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ZJ.JsonRpcProvider(new oX.default(te.formatRelayRpcUrl({sdkVersion:d8,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sr.isJsonRpcRequest(e)){if(!e.method.endsWith(l8))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(qZ({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else Sr.isJsonRpcResponse(e)&&this.events.emit(ar.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(ar.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=Sr.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Bn.payload,this.onPayloadHandler),this.provider.off(Bn.connect,this.onConnectHandler),this.provider.off(Bn.disconnect,this.onDisconnectHandler),this.provider.off(Bn.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(ar.connection_stalled,()=>{this.restartTransport().catch(r=>this.logger.error(r))});let e=await te.isOnline();te.subscribeToNetworkChange(async r=>{this.initialized&&e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(n=>this.logger.error(n))))})}onProviderDisconnect(){this.events.emit(ar.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},Ke.toMiliseconds(f8)))}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}},VZ=Object.defineProperty,R6=Object.getOwnPropertySymbols,HZ=Object.prototype.hasOwnProperty,kZ=Object.prototype.propertyIsEnumerable,B6=(t,e,r)=>e in t?VZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,L6=(t,e)=>{for(var r in e||(e={}))HZ.call(e,r)&&B6(t,r,e[r]);if(R6)for(var r of R6(e))kZ.call(e,r)&&B6(t,r,e[r]);return t},Bg=class extends Ln.IStore{constructor(e,r,n,i=hi,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=p8,this.cached=[],this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!te.isUndefined(o)?this.map.set(this.getKey(o),o):te.isProposalStruct(o)?this.map.set(o.id,o):te.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(u=>aX.default(a[u],o[u]))):this.values),this.update=async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});let u=L6(L6({},this.getData(o)),a);this.map.set(o,u),await this.persist()},this.delete=async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),await this.persist())},this.logger=Qe.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Lg=class{constructor(e,r){this.core=e,this.logger=r,this.name=E8,this.version=v8,this.events=new iX.default,this.initialized=!1,this.storagePrefix=hi,this.ignoredPayloadTypes=[te.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();let n=te.generateRandomBytes32(),i=await this.core.crypto.setSymKey(n),s=te.calcExpiry(Ke.FIVE_MINUTES),o={protocol:a8},a={topic:i,expiry:s,relay:o,active:!1},u=te.formatUri({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:o});return await this.pairings.set(i,a),await this.core.relayer.subscribe(i),this.core.expirer.set(i,s),{topic:i,uri:u}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o}=te.parseUri(n.uri),a;if(this.pairings.keys.includes(i)&&(a=this.pairings.get(i),a.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let u=te.calcExpiry(Ke.FIVE_MINUTES),c={topic:i,relay:o,expiry:u,active:!1};return await this.pairings.set(i,c),this.core.expirer.set(i,u),n.activatePairing&&await this.activate({topic:i}),this.events.emit(kl.create,c),this.core.crypto.keychain.has(i)||(await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o})),c},this.activate=async({topic:n})=>{this.isInitialized();let i=te.calcExpiry(Ke.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:u}=te.createDelayedPromise();this.events.once(te.engineEvent("pairing_ping",s),({error:c})=>{c?u(c):a()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",te.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=Sr.formatJsonRpcRequest(i,s),a=await this.core.crypto.encode(n,o),u=uu[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,u),o.id},this.sendResult=async(n,i,s)=>{let o=Sr.formatJsonRpcResult(n,s),a=await this.core.crypto.encode(i,o),u=await this.core.history.get(i,n),c=uu[u.request.method].res;await this.core.relayer.publish(i,a,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=Sr.formatJsonRpcError(n,s),a=await this.core.crypto.encode(i,o),u=await this.core.history.get(i,n),c=uu[u.request.method]?uu[u.request.method].res:uu.unregistered_method.res;await this.core.relayer.publish(i,a,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,te.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>te.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(kl.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{Sr.isJsonRpcResult(i)?this.events.emit(te.engineEvent("pairing_ping",s),{}):Sr.isJsonRpcError(i)&&this.events.emit(te.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(kl.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let a=te.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(te.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!te.isValidParams(n)){let{message:o}=te.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!te.isValidUrl(n.uri)){let{message:o}=te.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=te.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=te.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=te.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}},this.isValidPing=async n=>{if(!te.isValidParams(n)){let{message:s}=te.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!te.isValidParams(n)){let{message:s}=te.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!te.isValidString(n,!1)){let{message:i}=te.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=te.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(te.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=te.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=Qe.generateChildLogger(r,this.name),this.pairings=new Bg(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ar.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{Sr.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):Sr.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(kr.expired,async e=>{let{topic:r}=te.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(kl.expire,{topic:r}))})}},Fg=class extends Ln.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new ho.EventEmitter,this.name=A8,this.version=b8,this.cached=[],this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:te.calcExpiry(Ke.THIRTY_DAYS)};this.records.set(o.id,o),this.events.emit(rn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Sr.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(rn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(rn.deleted,s)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Qe.generateChildLogger(r,this.name)}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:Sr.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(rn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(rn.created,e=>{let r=rn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(rn.updated,e=>{let r=rn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(rn.deleted,e=>{let r=rn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{Ke.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Mg=class extends Ln.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new ho.EventEmitter,this.name=I8,this.version=_8,this.cached=[],this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(kr.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(kr.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Qe.generateChildLogger(r,this.name)}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return te.formatTopicTarget(e);if(typeof e=="number")return te.formatIdTarget(e);let{message:r}=te.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(kr.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Ke.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(kr.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(kr.created,e=>{let r=kr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(kr.expired,e=>{let r=kr.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(kr.deleted,e=>{let r=kr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ug=class extends Ln.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=Cg,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||te.isReactNative()||!te.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=xg;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,xg)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Ke.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{if(document.getElementById(Cg))return s();window.addEventListener("message",i);let o=document.createElement("iframe");o.id=Cg,o.src=`${this.verifyUrl}/${this.projectId}`,o.style.display="none",document.body.append(o),this.iframe=o,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Ke.toMiliseconds(Ke.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||cu;return S8.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${cu}`),i=cu),i},this.logger=Qe.generateChildLogger(r,this.name),this.verifyUrl=cu,this.abortController=new AbortController,this.isDevEnv=te.isNode()&&p.default.env.IS_VITEST}get context(){return Qe.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Ke.toMiliseconds(e))}},qg=class extends Ln.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=T8,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,u=`${C8}/${this.projectId}/clients`;await uX.default(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})},this.logger=Qe.generateChildLogger(r,this.context)}},GZ=Object.defineProperty,F6=Object.getOwnPropertySymbols,jZ=Object.prototype.hasOwnProperty,QZ=Object.prototype.propertyIsEnumerable,M6=(t,e,r)=>e in t?GZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,U6=(t,e)=>{for(var r in e||(e={}))jZ.call(e,r)&&M6(t,r,e[r]);if(F6)for(var r of F6(e))QZ.call(e,r)&&M6(t,r,e[r]);return t},Vg=class t extends Ln.ICore{constructor(e){super(e),this.protocol=Zb,this.version=Y6,this.name=kg,this.events=new ho.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||eI,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Qe.pino(Qe.getDefaultLoggerOptions({level:e?.logger||J6.logger}));this.logger=Qe.generateChildLogger(r,this.name),this.heartbeat=new Gl.HeartBeat,this.crypto=new Og(this,this.logger,e?.keychain),this.history=new Fg(this,this.logger),this.expirer=new Mg(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new sX.default(U6(U6({},X6),e?.storageOptions)),this.relayer=new Rg({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Lg(this,this.logger),this.verify=new Ug(this.projectId||"",this.logger),this.echoClient=new qg(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(g8,n),r}get context(){return Qe.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},zZ=Vg;we.CORE_CONTEXT=kg,we.CORE_DEFAULT=J6,we.CORE_PROTOCOL=Zb,we.CORE_STORAGE_OPTIONS=X6,we.CORE_STORAGE_PREFIX=hi,we.CORE_VERSION=Y6,we.CRYPTO_CLIENT_SEED=Kb,we.CRYPTO_CONTEXT=Z6,we.CRYPTO_JWT_TTL=e8,we.Core=zZ,we.Crypto=Og,we.ECHO_CONTEXT=T8,we.ECHO_URL=C8,we.EXPIRER_CONTEXT=I8,we.EXPIRER_DEFAULT_TTL=OZ,we.EXPIRER_EVENTS=kr,we.EXPIRER_STORAGE_VERSION=_8,we.EchoClient=qg,we.Expirer=Mg,we.HISTORY_CONTEXT=A8,we.HISTORY_EVENTS=rn,we.HISTORY_STORAGE_VERSION=b8,we.JsonRpcHistory=Fg,we.KEYCHAIN_CONTEXT=t8,we.KEYCHAIN_STORAGE_VERSION=r8,we.KeyChain=Ng,we.MESSAGES_CONTEXT=n8,we.MESSAGES_STORAGE_VERSION=i8,we.MessageTracker=Dg,we.PAIRING_CONTEXT=E8,we.PAIRING_DEFAULT_TTL=NZ,we.PAIRING_EVENTS=kl,we.PAIRING_RPC_OPTS=uu,we.PAIRING_STORAGE_VERSION=v8,we.PENDING_SUB_RESOLUTION_TIMEOUT=w8,we.PUBLISHER_CONTEXT=o8,we.PUBLISHER_DEFAULT_TTL=s8,we.Pairing=Lg,we.RELAYER_CONTEXT=c8,we.RELAYER_DEFAULT_LOGGER=u8,we.RELAYER_DEFAULT_PROTOCOL=a8,we.RELAYER_DEFAULT_RELAY_URL=eI,we.RELAYER_EVENTS=ar,we.RELAYER_FAILOVER_RELAY_URL=Yb,we.RELAYER_PROVIDER_EVENTS=Bn,we.RELAYER_RECONNECT_TIMEOUT=f8,we.RELAYER_SDK_VERSION=d8,we.RELAYER_STORAGE_OPTIONS=CZ,we.RELAYER_SUBSCRIBER_SUFFIX=l8,we.RELAYER_TRANSPORT_CUTOFF=h8,we.Relayer=Rg,we.STORE_STORAGE_VERSION=p8,we.SUBSCRIBER_CONTEXT=y8,we.SUBSCRIBER_DEFAULT_TTL=xZ,we.SUBSCRIBER_EVENTS=Gr,we.SUBSCRIBER_STORAGE_VERSION=m8,we.Store=Bg,we.Subscriber=Pg,we.TRUSTED_VERIFY_URLS=S8,we.VERIFY_CONTEXT=Cg,we.VERIFY_FALLBACK_SERVER=xg,we.VERIFY_SERVER=cu,we.Verify=Ug,we.WALLETCONNECT_CLIENT_ID=g8,we.default=Vg});var q8=v(Ye=>{"use strict";l();Object.defineProperty(Ye,"__esModule",{value:!0});var Mn=x8(),Gg=m1(),D8=F1(),j=Dl(),P8=ti(),tt=Xs(),wt=(Ll(),ht(rr));function WZ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var $Z=WZ(P8),sI="wc",oI=2,aI="client",$g=`${sI}@${oI}:${aI}:`,jg={name:aI,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},KZ={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire"},YZ={database:":memory:"},tI="WALLETCONNECT_DEEPLINK_CHOICE",JZ={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},XZ="history",ZZ="0.3",R8="proposal",eee=tt.THIRTY_DAYS,B8="Proposal expired",L8="session",Wl=tt.SEVEN_DAYS,F8="engine",lu={wc_sessionPropose:{req:{ttl:tt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:tt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:tt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:tt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:tt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:tt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:tt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:tt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:tt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:tt.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:tt.THIRTY_SECONDS,prompt:!1,tag:1115}}},Qg={min:tt.FIVE_MINUTES,max:tt.SEVEN_DAYS},Fn={idle:"IDLE",active:"ACTIVE"},M8="request",U8=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],tee=Object.defineProperty,ree=Object.defineProperties,nee=Object.getOwnPropertyDescriptors,N8=Object.getOwnPropertySymbols,iee=Object.prototype.hasOwnProperty,see=Object.prototype.propertyIsEnumerable,O8=(t,e,r)=>e in t?tee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Er=(t,e)=>{for(var r in e||(e={}))iee.call(e,r)&&O8(t,r,e[r]);if(N8)for(var r of N8(e))see.call(e,r)&&O8(t,r,e[r]);return t},zl=(t,e)=>ree(t,nee(e)),rI=class extends D8.IEngine{constructor(e){super(e),this.name=F8,this.events=new $Z.default,this.initialized=!1,this.ignoredPayloadTypes=[j.TYPE_1],this.requestQueue={state:Fn.idle,queue:[]},this.sessionRequestQueue={state:Fn.idle,queue:[]},this.requestQueueDelay=tt.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(lu)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},tt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=zl(Er({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:u}=n,c=i,f,d=!1;if(c&&(d=this.client.core.pairing.pairings.get(c).active),!c||!d){let{topic:M,uri:b}=await this.client.core.pairing.create();c=M,f=b}let g=await this.client.core.crypto.generateKeyPair(),m=Er({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:Mn.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:g,metadata:this.client.metadata}},a&&{sessionProperties:a}),{reject:y,resolve:A,done:O}=j.createDelayedPromise(tt.FIVE_MINUTES,B8);if(this.events.once(j.engineEvent("session_connect"),async({error:M,session:b})=>{if(M)y(M);else if(b){b.self.publicKey=g;let S=zl(Er({},b),{requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces});await this.client.session.set(b.topic,S),await this.setExpiry(b.topic,b.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:b.peer.metadata}),A(S)}}),!c){let{message:M}=j.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(M)}let R=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:m}),q=j.calcExpiry(tt.FIVE_MINUTES);return await this.setProposal(R,Er({id:R,expiry:q},m)),{uri:f,approval:O}},this.pair=async r=>(await this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{await this.isInitialized(),await this.isValidApprove(r);let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o}=r,a=this.client.proposal.get(n),{pairingTopic:u,proposer:c,requiredNamespaces:f,optionalNamespaces:d}=a;u=u||"",j.isValidObject(f)||(f=j.getRequiredNamespacesFromNamespaces(s,"approve()"));let g=await this.client.core.crypto.generateKeyPair(),m=c.publicKey,y=await this.client.core.crypto.generateSharedKey(g,m);u&&n&&(await this.client.core.pairing.updateMetadata({topic:u,metadata:c.metadata}),await this.sendResult({id:n,topic:u,result:{relay:{protocol:i??"irn"},responderPublicKey:g}}),await this.client.proposal.delete(n,j.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:u}));let A=Er({relay:{protocol:i??"irn"},namespaces:s,requiredNamespaces:f,optionalNamespaces:d,pairingTopic:u,controller:{publicKey:g,metadata:this.client.metadata},expiry:j.calcExpiry(Wl)},o&&{sessionProperties:o});await this.client.core.relayer.subscribe(y),await this.sendRequest({topic:y,method:"wc_sessionSettle",params:A,throwOnFailedPublish:!0});let O=zl(Er({},A),{topic:y,pairingTopic:u,acknowledged:!1,self:A.controller,peer:{publicKey:c.publicKey,metadata:c.metadata},controller:g});return await this.client.session.set(y,O),await this.setExpiry(y,j.calcExpiry(Wl)),{topic:y,acknowledged:()=>new Promise(R=>setTimeout(()=>R(this.client.session.get(y)),500))}},this.reject=async r=>{await this.isInitialized(),await this.isValidReject(r);let{id:n,reason:i}=r,{pairingTopic:s}=this.client.proposal.get(n);s&&(await this.sendError(n,s,i),await this.client.proposal.delete(n,j.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized(),await this.isValidUpdate(r);let{topic:n,namespaces:i}=r,s=await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:o,resolve:a,reject:u}=j.createDelayedPromise();return this.events.once(j.engineEvent("session_update",s),({error:c})=>{c?u(c):a()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:o}},this.extend=async r=>{await this.isInitialized(),await this.isValidExtend(r);let{topic:n}=r,i=await this.sendRequest({topic:n,method:"wc_sessionExtend",params:{}}),{done:s,resolve:o,reject:a}=j.createDelayedPromise();return this.events.once(j.engineEvent("session_extend",i),({error:u})=>{u?a(u):o()}),await this.setExpiry(n,j.calcExpiry(Wl)),{acknowledged:s}},this.request=async r=>{await this.isInitialized(),await this.isValidRequest(r);let{chainId:n,request:i,topic:s,expiry:o}=r,a=wt.payloadId(),{done:u,resolve:c,reject:f}=j.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(j.engineEvent("session_request",a),({error:d,result:g})=>{d?f(d):c(g)}),await Promise.all([new Promise(async d=>{await this.sendRequest({clientRpcId:a,topic:s,method:"wc_sessionRequest",params:{request:i,chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(g=>f(g)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),d()}),new Promise(async d=>{let g=await j.getDeepLink(this.client.core.storage,tI);j.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:g}),d()}),u()]).then(d=>d[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;wt.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):wt.isJsonRpcError(i)&&await this.sendError(s,n,i.error),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized(),await this.isValidPing(r);let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=await this.sendRequest({topic:n,method:"wc_sessionPing",params:{}}),{done:s,resolve:o,reject:a}=j.createDelayedPromise();this.events.once(j.engineEvent("session_ping",i),({error:u})=>{u?a(u):o()}),await s()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r;await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s}})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest({topic:n,method:"wc_sessionDelete",params:j.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>j.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{let{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,j.getSdkError("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(tI).catch(s=>this.client.logger.warn(s)),this.getPendingSessionRequests().forEach(s=>{s.topic===r&&this.deletePendingSessionRequest(s.id,j.getSdkError("USER_DISCONNECTED"))})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,j.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=Fn.idle)},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{let n=lu.wc_sessionRequest.req.ttl,{id:i,topic:s,params:o,verifyContext:a}=r;await this.client.pendingRequest.set(i,{id:i,topic:s,params:o,verifyContext:a}),n&&this.client.core.expirer.set(i,j.calcExpiry(n))},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:u,throwOnFailedPublish:c}=r,f=wt.formatJsonRpcRequest(i,s,u);if(j.isBrowser()&&U8.includes(i)){let m=j.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:m})}let d=await this.client.core.crypto.encode(n,f),g=lu[i].req;return o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(n,f),c?(g.internal=zl(Er({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,g)):this.client.core.relayer.publish(n,d,g).catch(m=>this.client.logger.error(m)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o}=r,a=wt.formatJsonRpcResult(n,s),u=await this.client.core.crypto.encode(i,a),c=await this.client.core.history.get(i,n),f=lu[c.request.method].res;o?(f.internal=zl(Er({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,f)):this.client.core.relayer.publish(i,u,f).catch(d=>this.client.logger.error(d)),await this.client.core.history.resolve(a)},this.sendError=async(r,n,i)=>{let s=wt.formatJsonRpcError(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),u=lu[a.request.method].res;this.client.core.relayer.publish(n,o,u),await this.client.core.history.resolve(s)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{j.isExpired(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{j.isExpired(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Fn.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Fn.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Fn.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=j.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(Er({},n.params));let o=j.calcExpiry(tt.FIVE_MINUTES),a=Er({id:s,pairingTopic:r,expiry:o},i);await this.setProposal(s,a);let u=j.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(u,a.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:a,verifyContext:c})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(wt.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let a=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});let u=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let c=await this.client.core.crypto.generateSharedKey(a,u);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else wt.isJsonRpcError(n)&&(await this.client.proposal.delete(i,j.getSdkError("USER_DISCONNECTED")),this.events.emit(j.engineEvent("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:a,expiry:u,namespaces:c,requiredNamespaces:f,optionalNamespaces:d,sessionProperties:g,pairingTopic:m}=n.params,y=Er({topic:r,relay:o,expiry:u,namespaces:c,acknowledged:!0,pairingTopic:m,requiredNamespaces:f,optionalNamespaces:d,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},g&&{sessionProperties:g});await this.sendResult({id:n.id,topic:r,result:!0}),this.events.emit(j.engineEvent("session_connect"),{session:y}),this.cleanupDuplicatePairings(y)}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(j.engineEvent("session_approve",i),{})):wt.isJsonRpcError(n)&&(await this.client.session.delete(r,j.getSdkError("USER_DISCONNECTED")),this.events.emit(j.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,a=j.MemoryStore.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidUpdate(Er({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0}),this.client.events.emit("session_update",{id:s,topic:r,params:i}),j.MemoryStore.set(o,s)}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_update",i),{}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,j.calcExpiry(Wl)),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_extend",i),{}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n;setTimeout(()=>{wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_ping",i),{}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(Mn.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession(r))})}),this.sendResult({id:i,topic:r,result:!0})]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidRequest(Er({topic:r},s));let o=j.hashMessage(JSON.stringify(wt.formatJsonRpcRequest("wc_sessionRequest",s,i))),a=this.client.session.get(r),u=await this.getVerifyContext(o,a.peer.metadata),c={id:i,topic:r,params:s,verifyContext:u};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_request",i),{result:n.result}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,a=j.MemoryStore.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Er({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),j.MemoryStore.set(o,i)}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Fn.idle,this.processSessionRequestQueue()},tt.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Fn.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Fn.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,wt.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!j.isValidParams(r)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if(j.isUndefined(n)||await this.isValidPairingTopic(n),!j.isValidRelays(a,!0)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(u)}!j.isUndefined(i)&&j.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!j.isUndefined(s)&&j.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),j.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=j.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!j.isValidParams(r))throw new Error(j.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;await this.isValidProposalId(n);let a=this.client.proposal.get(n),u=j.isValidNamespaces(i,"approve()");if(u)throw new Error(u.message);let c=j.isConformingNamespaces(a.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!j.isValidString(s,!0)){let{message:f}=j.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}j.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!j.isValidParams(r)){let{message:s}=j.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(await this.isValidProposalId(n),!j.isValidErrorReason(i)){let{message:s}=j.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!j.isValidParams(r)){let{message:c}=j.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!j.isValidRelay(n)){let{message:c}=j.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let a=j.isValidController(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);let u=j.isValidNamespaces(s,"onSessionSettleRequest()");if(u)throw new Error(u.message);if(j.isExpired(o)){let{message:c}=j.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!j.isValidParams(r)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(u)}let{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=j.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let a=j.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!j.isValidParams(r)){let{message:i}=j.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!j.isValidParams(r)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(u)}let{topic:n,request:i,chainId:s,expiry:o}=r;await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!j.isValidNamespacesChainId(a,s)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(u)}if(!j.isValidRequest(i)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(u)}if(!j.isValidNamespacesRequest(a,s,i.method)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(u)}if(o&&!j.isValidRequestExpiry(o,Qg)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Qg.min} and ${Qg.max}`);throw new Error(u)}},this.isValidRespond=async r=>{var n;if(!j.isValidParams(r)){let{message:o}=j.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!j.isValidResponse(s)){let{message:o}=j.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!j.isValidParams(r)){let{message:i}=j.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!j.isValidParams(r)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!j.isValidNamespacesChainId(o,s)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!j.isValidEvent(i)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!j.isValidNamespacesEvent(o,s,i.name)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!j.isValidParams(r)){let{message:i}=j.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||Mn.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!j.isValidString(i,!1)){let{message:s}=j.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})}}async isInitialized(){if(!this.initialized){let{message:e}=j.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mn.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;let i=await this.client.core.crypto.decode(r,n);try{wt.isJsonRpcRequest(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):wt.isJsonRpcResponse(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.client.core.history.delete(r,i.id)):this.onRelayEventUnknownPayload({topic:r,payload:i})}catch(s){this.client.logger.error(s)}})}registerExpirerEvents(){this.client.core.expirer.on(Mn.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=j.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,j.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Mn.PAIRING_EVENTS.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!j.isValidString(e,!1)){let{message:r}=j.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(j.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=j.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!j.isValidString(e,!1)){let{message:r}=j.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(j.isExpired(this.client.session.get(e).expiry)){await this.deleteSession(e);let{message:r}=j.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(j.isValidString(e,!1)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=j.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!j.isValidId(e)){let{message:r}=j.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(j.isExpired(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);let{message:r}=j.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},nI=class extends Mn.Store{constructor(e,r){super(e,r,R8,$g),this.core=e,this.logger=r}},zg=class extends Mn.Store{constructor(e,r){super(e,r,L8,$g),this.core=e,this.logger=r}},iI=class extends Mn.Store{constructor(e,r){super(e,r,M8,$g,n=>n.id),this.core=e,this.logger=r}},Wg=class t extends D8.ISignClient{constructor(e){super(e),this.protocol=sI,this.version=oI,this.name=jg.name,this.events=new P8.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||jg.name,this.metadata=e?.metadata||j.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gg.pino(Gg.getDefaultLoggerOptions({level:e?.logger||jg.logger}));this.core=e?.core||new Mn.Core(e),this.logger=Gg.generateChildLogger(r,this.name),this.session=new zg(this.core,this.logger),this.proposal=new nI(this.core,this.logger),this.pendingRequest=new iI(this.core,this.logger),this.engine=new rI(this)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Gg.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},oee=zg,aee=Wg;Ye.ENGINE_CONTEXT=F8,Ye.ENGINE_QUEUE_STATES=Fn,Ye.ENGINE_RPC_OPTS=lu,Ye.HISTORY_CONTEXT=XZ,Ye.HISTORY_EVENTS=JZ,Ye.HISTORY_STORAGE_VERSION=ZZ,Ye.METHODS_TO_VERIFY=U8,Ye.PROPOSAL_CONTEXT=R8,Ye.PROPOSAL_EXPIRY=eee,Ye.PROPOSAL_EXPIRY_MESSAGE=B8,Ye.REQUEST_CONTEXT=M8,Ye.SESSION_CONTEXT=L8,Ye.SESSION_EXPIRY=Wl,Ye.SESSION_REQUEST_EXPIRY_BOUNDARIES=Qg,Ye.SIGN_CLIENT_CONTEXT=aI,Ye.SIGN_CLIENT_DEFAULT=jg,Ye.SIGN_CLIENT_EVENTS=KZ,Ye.SIGN_CLIENT_PROTOCOL=sI,Ye.SIGN_CLIENT_STORAGE_OPTIONS=YZ,Ye.SIGN_CLIENT_STORAGE_PREFIX=$g,Ye.SIGN_CLIENT_VERSION=oI,Ye.SessionStore=oee,Ye.SignClient=aee,Ye.WALLETCONNECT_DEEPLINK_CHOICE=tI,Ye.default=Wg});var Kg=v(os=>{"use strict";l();Object.defineProperty(os,"__esModule",{value:!0});os.OptionalOperation=os.Operation=void 0;var uee;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(uee=os.Operation||(os.Operation={}));var cee;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(cee=os.OptionalOperation||(os.OptionalOperation={}))});var uI=v(Un=>{"use strict";l();Object.defineProperty(Un,"__esModule",{value:!0});Un.WALLETCONNECT_SIGN_LOGIN_DELAY=Un.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Un.WALLETCONNECT_MULTIVERSX_METHODS=Un.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var V8=Kg();Un.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";Un.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(V8.Operation);Un.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(V8.OptionalOperation);Un.WALLETCONNECT_SIGN_LOGIN_DELAY=200});var fI=v(nn=>{"use strict";l();Object.defineProperty(nn,"__esModule",{value:!0});nn.WalletConnectV2ProviderErrorMessagesEnum=nn.ErrBadAddress=nn.ErrNotImplemented=nn.Err=void 0;var $l=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};nn.Err=$l;var cI=class extends $l{constructor(){super("Method not yet implemented")}};nn.ErrNotImplemented=cI;var lI=class extends $l{constructor(e,r){super(`Bad address: ${e}`,r)}};nn.ErrBadAddress=lI;var lee;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(lee=nn.WalletConnectV2ProviderErrorMessagesEnum||(nn.WalletConnectV2ProviderErrorMessagesEnum={}))});var hI=v(Yg=>{"use strict";l();Object.defineProperty(Yg,"__esModule",{value:!0});Yg.Logger=void 0;var dI=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};Yg.Logger=dI});var H8=v(()=>{"use strict";l();global.Buffer||(global.Buffer=qs().Buffer)});var G8=v(k8=>{"use strict";l();Object.defineProperty(k8,"__esModule",{value:!0})});var Q8=v(j8=>{"use strict";l();Object.defineProperty(j8,"__esModule",{value:!0})});var z8=v(fu=>{"use strict";l();var fee=fu&&fu.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(fu,"__esModule",{value:!0});fu.RelayedTransactionV1Builder=void 0;var dee=fee(Yt()),pI=pt(),hee=Le(),pee=Yr(),gee=Yn(),gI=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new hee.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${h.Buffer.from(e).toString("hex")}`,n=new gee.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new pee.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new pI.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new pI.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:new dee.default(this.innerTransaction.getValue().toString(),10).toNumber(),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:h.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new pI.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?h.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?h.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return JSON.stringify(e)}};fu.RelayedTransactionV1Builder=gI});var W8=v(Jg=>{"use strict";l();Object.defineProperty(Jg,"__esModule",{value:!0});Jg.Code=void 0;var yee=gE(),mee=32,yI=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return h.Buffer.from(this.hex,"hex")}computeHash(){let e=yee(mee).update(this.valueOf()).digest();return h.Buffer.from(e)}};Jg.Code=yI});var J8=v(hu=>{"use strict";l();Object.defineProperty(hu,"__esModule",{value:!0});hu.bech32m=hu.bech32=void 0;var Xg="qpzry9x8gf2tvdw0s3jn54khce6mua7l",K8={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function $8(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=du(e)^n>>5}e=du(e);for(let r=0;r=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<=e)return"Excess padding";if(i<u)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=$8(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=du(c)^g,f+=Xg.charAt(g)}for(let d=0;d<6;++d)c=du(c);c^=e;for(let d=0;d<6;++d){let g=c>>(5-d)*5&31;f+=Xg.charAt(g)}return f}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";let u=o.toLowerCase(),c=o.toUpperCase();if(o!==u&&o!==c)return"Mixed-case string "+o;o=u;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),g=o.slice(f+1);if(g.length<6)return"Data too short";let m=$8(d);if(typeof m=="string")return m;let y=[];for(let A=0;A=g.length)&&y.push(R)}return m!==e?"Invalid checksum for "+o:{prefix:d,words:y}}function i(o,a){let u=n(o,a);if(typeof u=="object")return u}function s(o,a){let u=n(o,a);if(typeof u=="object")return u;throw new Error(u)}return{decodeUnsafe:i,decode:s,encode:r,toWords:wee,fromWordsUnsafe:Eee,fromWords:vee}}hu.bech32=Y8("bech32");hu.bech32m=Y8("bech32m")});var Z8=v(jr=>{"use strict";l();Object.defineProperty(jr,"__esModule",{value:!0});jr.TokenTransferProperties=jr.TransactionMetadataTransfer=jr.TransactionMetadata=jr.TransactionToDecode=jr.TransactionDecoder=void 0;var X8=J8(),wI=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new po;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new Zg;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new po;s.transfers||(s.transfers=[]);let o=2;for(let a=0;ao&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),a=new po;return a.sender=e.sender,a.receiver=o,a.value=s,r.length>4&&(a.functionName=this.hexToString(r[4]),a.functionArgs=r.slice(5)),a.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],a}base64Encode(e){return h.Buffer.from(e).toString("base64")}base64Decode(e){return h.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new po;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=h.Buffer.from(e,"hex"),n=X8.bech32.toWords(r);return X8.bech32.encode("erd",n)}isAddressValid(e){return h.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return h.Buffer.from(e,"base64").toString("hex")}hexToString(e){return h.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};jr.TransactionDecoder=wI;var Zg=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};jr.TransactionToDecode=Zg;var po=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};jr.TransactionMetadata=po;var EI=class{constructor(){this.value=BigInt(0)}};jr.TransactionMetadataTransfer=EI;var vI=class{};jr.TokenTransferProperties=vI});var AI=v(ey=>{"use strict";l();Object.defineProperty(ey,"__esModule",{value:!0});ey.ReturnCode=void 0;var ze=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};ey.ReturnCode=ze;ze.None=new ze("");ze.Ok=new ze("ok");ze.FunctionNotFound=new ze("function not found");ze.FunctionWrongSignature=new ze("wrong signature for function");ze.ContractNotFound=new ze("contract not found");ze.UserError=new ze("user error");ze.OutOfGas=new ze("out of gas");ze.AccountCollision=new ze("account collision");ze.OutOfFunds=new ze("out of funds");ze.CallStackOverFlow=new ze("call stack overflow");ze.ContractInvalid=new ze("contract invalid");ze.ExecutionFailed=new ze("execution failed");ze.Unknown=new ze("unknown")});var rL=v(ty=>{"use strict";l();Object.defineProperty(ty,"__esModule",{value:!0});ty.ResultsParser=void 0;var Aee=Z8(),eL=pt(),tL=Le(),as=pa(),bee=na(),pu=AI(),gu;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(gu||(gu={}));var bI;(function(t){t.TooMuchGas="@too much gas provided for processing"})(bI||(bI={}));var Iee={argsSerializer:new bee.ArgSerializer},II=class{constructor(e){e=Object.assign(Object.assign({},Iee),e),this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new pu.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new pu.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e),i=this.argsSerializer.buffersToValues(n.values,r.output);return{returnCode:n.returnCode,returnMessage:n.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return as.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return as.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return as.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return as.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return as.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return as.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return as.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return as.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new tL.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new Aee.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:pu.ReturnCode.None,returnMessage:pu.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:pu.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(gu.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.getLastTopic(),o=s?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(gu.OnWriteLog,a=>a.findFirstOrNoneTopic(u=>u.toString().startsWith(bI.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.getLastTopic(),o=s?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new eL.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(gu.OnWriteLog,u=>u.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),a=s.toString();return{returnCode:s,returnMessage:a,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new eL.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(gu.OnWriteLog,o=>{var a;let u=o.address.bech32()==e.sender.bech32(),c=((a=o.topics[0])===null||a===void 0?void 0:a.hex())==n.hex();return u&&c});if(s){let{returnCode:o,returnDataParts:a}=this.sliceDataFieldInParts(s.data),u=o.toString();return{returnCode:o,returnMessage:u,values:a}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||h.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new tL.ErrCannotParseContractResults("no return code");return{returnCode:pu.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){var n,i;let s={},o=e.topics.map(m=>h.Buffer.from(m.valueOf())).slice(1),a=((n=e.dataPayload)===null||n===void 0?void 0:n.valueOf())||h.Buffer.from([]),u=((i=e.additionalData)===null||i===void 0?void 0:i.map(m=>h.Buffer.from(m.valueOf())))||[];u.length==0&&a.length>0&&u.push(h.Buffer.from(a));let c=r.inputs.filter(m=>m.indexed),f=this.argsSerializer.buffersToValues(o,c);for(let m=0;m!m.indexed),g=this.argsSerializer.buffersToValues(u,d);for(let m=0;m{"use strict";l();var _ee=_t&&_t.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ur=_t&&_t.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_ee(e,t,r)};Object.defineProperty(_t,"__esModule",{value:!0});ur(na(),_t);ur(W8(),_t);ur(Bw(),_t);ur(NE(),_t);ur(qc(),_t);ur(UE(),_t);ur(RE(),_t);ur(Rv(),_t);ur(HE(),_t);ur(Vc(),_t);ur(rL(),_t);ur(AI(),_t);ur(Dv(),_t);ur($E(),_t);ur(xt(),_t)});var iL=v(ry=>{"use strict";l();Object.defineProperty(ry,"__esModule",{value:!0});ry.RelayedTransactionV2Builder=void 0;var nL=Le(),Kl=_I(),See=Yr(),Tee=Yn(),SI=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new nL.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new nL.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new Kl.ArgSerializer().valuesToString([new Kl.AddressValue(this.innerTransaction.getReceiver()),new Kl.U64Value(this.innerTransaction.getNonce().valueOf()),new Kl.BytesValue(this.innerTransaction.getData().valueOf()),new Kl.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Tee.TransactionPayload(r),i=new See.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};ry.RelayedTransactionV2Builder=SI});var CI=v(lt=>{"use strict";l();var Cee=lt&<.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xee=lt&<.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sL=lt&<.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cee(e,t,r);return xee(e,t),e},Nee=lt&<.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lt,"__esModule",{value:!0});lt.addressToHex=lt.bufferToHex=lt.utf8ToHex=lt.bigIntToHex=lt.bigIntToBuffer=lt.bufferToBigInt=lt.stringToBuffer=void 0;var Oee=Nee(Yt()),Dee=pt(),TI=sL(Tc()),oL=sL(Md());function Pee(t){return h.Buffer.from(t)}lt.stringToBuffer=Pee;function Ree(t){return t.length==0?new Oee.default(0):TI.bufferToBigInt(t)}lt.bufferToBigInt=Ree;function Bee(t){return t==0?h.Buffer.from([]):TI.bigIntToBuffer(t)}lt.bigIntToBuffer=Bee;function Lee(t){return t==0?"":TI.getHexMagnitudeOfBigInt(t)}lt.bigIntToHex=Lee;function Fee(t){let e=h.Buffer.from(t).toString("hex");return oL.zeroPadStringIfOddLength(e)}lt.utf8ToHex=Fee;function Mee(t){let e=t.toString("hex");return oL.zeroPadStringIfOddLength(e)}lt.bufferToHex=Mee;function Uee(t){return Dee.Address.fromBech32(t.toString()).pubkey().toString("hex")}lt.addressToHex=Uee});var uL=v(ny=>{"use strict";l();Object.defineProperty(ny,"__esModule",{value:!0});ny.TokenOperationsFactory=void 0;var xI=Ns(),qee=pa(),aL=xc(),Vee=Yr(),Hee=Yn(),ne=CI(),NI=class{constructor(e){this.config=e,this.trueAsHex=ne.utf8ToHex("true"),this.falseAsHex=ne.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.bigIntToHex(e.initialSupply),ne.bigIntToHex(e.numDecimals),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){qee.Logger.info(` -========== -IMPORTANT! -========== -You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.bigIntToHex(e.numDecimals),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.utf8ToHex(e.tokenType),ne.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user),...e.addRoleLocalMint?[ne.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ne.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user),...e.addRoleNFTCreate?[ne.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ne.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ne.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ne.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user),...e.addRoleNFTCreate?[ne.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ne.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ne.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ne.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ne.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.initialQuantity),ne.utf8ToHex(e.name),ne.bigIntToHex(e.royalties),ne.utf8ToHex(e.hash),ne.bufferToHex(e.attributes),...e.uris.map(ne.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.tokenNonce),ne.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.tokenNonce),ne.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.tokenNonce),ne.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:a,dataParts:u}){let c=this.buildTransactionPayload(u),f=o||this.computeGasLimit(c,a),d=new aL.TransactionVersion(xI.TRANSACTION_VERSION_DEFAULT),g=new aL.TransactionOptions(xI.TRANSACTION_OPTIONS_DEFAULT);return new Vee.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:g})}buildTransactionPayload(e){let r=e.join(xI.ARGUMENTS_SEPARATOR);return new Hee.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};ny.TokenOperationsFactory=NI});var cL=v(iy=>{"use strict";l();Object.defineProperty(iy,"__esModule",{value:!0});iy.TokenOperationsFactoryConfig=void 0;var kee=pt(),OI=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=kee.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};iy.TokenOperationsFactoryConfig=OI});var fL=v(sy=>{"use strict";l();Object.defineProperty(sy,"__esModule",{value:!0});sy.TokenOperationsOutcomeParser=void 0;var Gee=pt(),DI=Le(),lL=CI(),PI=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){var r;this.ensureNoError(e);let n=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),i=this.extractTokenIdentifier(n),s=this.extractNonce(n),o=(r=n.topics[3])===null||r===void 0?void 0:r.valueOf();return{tokenIdentifier:i,nonce:s,attributes:o}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){var r;for(let n of e.logs.events)if(n.identifier=="signalError"){let i=h.Buffer.from(n.data.substring(1),"hex").toString(),s=(r=n.topics[1])===null||r===void 0?void 0:r.valueOf().toString();throw new DI.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${s} (${i})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new DI.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new DI.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){var r;return(r=e.topics[0])===null||r===void 0?void 0:r.valueOf().toString()}extractNonce(e){var r;return lL.bufferToBigInt((r=e.topics[1])===null||r===void 0?void 0:r.valueOf()).toFixed(0)}extractAmount(e){var r;return lL.bufferToBigInt((r=e.topics[2])===null||r===void 0?void 0:r.valueOf()).toFixed(0)}extractAddress(e){var r;return Gee.Address.fromBuffer((r=e.topics[3])===null||r===void 0?void 0:r.valueOf()).toString()}};sy.TokenOperationsOutcomeParser=PI});var dL=v(pi=>{"use strict";l();var jee=pi&&pi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RI=pi&&pi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&jee(e,t,r)};Object.defineProperty(pi,"__esModule",{value:!0});RI(uL(),pi);RI(cL(),pi);RI(fL(),pi)});var hL=v(rt=>{"use strict";l();var Qee=rt&&rt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dt=rt&&rt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Qee(e,t,r)};Object.defineProperty(rt,"__esModule",{value:!0});H8();Dt(ha(),rt);Dt(pt(),rt);Dt(TE(),rt);Dt(Le(),rt);Dt(bE(),rt);Dt(G8(),rt);Dt(Q8(),rt);Dt(pa(),rt);Dt(xc(),rt);Dt(z8(),rt);Dt(iL(),rt);Dt(Wh(),rt);Dt(_I(),rt);Dt(dL(),rt);Dt(Vm(),rt);Dt(Yr(),rt);Dt(Yn(),rt);Dt(Ih(),rt);Dt(vE(),rt);Dt(br(),rt)});var EL=v(Pt=>{"use strict";l();var zee=Pt&&Pt.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.sleep=Pt.getMetadata=Pt.applyTransactionSignature=Pt.getAddressFromSession=Pt.addressIsValid=Pt.getConnectionParams=Pt.getCurrentTopic=Pt.getCurrentSession=void 0;var yL=hL(),pL=Rc(),Wee=Dl(),oy=uI(),gi=fI(),BI=hI(),gL=Kg();function mL(t,e){if(!e)throw new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find(wL(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw BI.Logger.error(gi.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}Pt.getCurrentSession=mL;function $ee(t,e){if(!e)throw new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=mL(t,e);if(!r?.topic)throw new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}Pt.getCurrentTopic=$ee;function wL(t,e){var r,n,i;let s=[...oy.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(gL.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(gL.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${oy.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],a=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[oy.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:a}}}}Pt.getConnectionParams=wL;function Kee(t){try{return!yL.Address.fromBech32(t).isEmpty()}catch{return!1}}Pt.addressIsValid=Kee;function Yee(t){let e=t.namespaces[oy.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}Pt.getAddressFromSession=Yee;function Jee({transaction:t,response:e}){if(!e)throw BI.Logger.error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,a=t.getGuardian().bech32();if(a&&a!==o)throw BI.Logger.error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(yL.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new pL.Signature(r)),n&&t.applyGuardianSignature(new pL.Signature(n)),t}Pt.applyTransactionSignature=Jee;function Xee(t){if(t)return Object.assign(Object.assign({},t),{url:Wee.getAppMetadata().url})}Pt.getMetadata=Xee;function Zee(t){return zee(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}Pt.sleep=Zee});var Yl=v(vr=>{"use strict";l();var St=vr&&vr.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})},ete=vr&&vr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vr,"__esModule",{value:!0});vr.WalletConnectV2Provider=vr.OptionalOperation=vr.Operation=vr.WalletConnectV2ProviderErrorMessagesEnum=void 0;var tte=Rc(),rte=ete(q8()),LI=Dl(),go=uI(),me=fI();Object.defineProperty(vr,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return me.WalletConnectV2ProviderErrorMessagesEnum}});var Fe=hI(),us=Kg();Object.defineProperty(vr,"Operation",{enumerable:!0,get:function(){return us.Operation}});Object.defineProperty(vr,"OptionalOperation",{enumerable:!0,get:function(){return us.OptionalOperation}});var Wt=EL(),FI=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return St(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:Wt.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield rte.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=Wt.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Fe.Logger.error(e?.topic?me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return St(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield Wt.sleep(go.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=Wt.getAddressFromSession(n),o=n.namespaces[go.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(us.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?us.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:us.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:a}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!a)throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:a})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||Wt.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:LI.getSdkError("USER_DISCONNECTED")});else{let r=Wt.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:LI.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:{method:us.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new tte.Signature(n))}catch{throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:{method:us.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return Wt.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:{method:us.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];Wt.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=Wt.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return St(this,void 0,void 0,function*(){return e?Wt.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Fe.Logger.error(`${me.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return St(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=Wt.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&Wt.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return St(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:a})=>{var u;if(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)return;let{namespaces:c}=a,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>St(this,void 0,void 0,function*(){var a;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)&&(Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>St(this,void 0,void 0,function*(){var a;!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o||(Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return St(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=Wt.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,a,u,c;return St(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!LI.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(u=(a=this.walletConnector.core)===null||a===void 0?void 0:a.relayer)===null||u===void 0?void 0:u.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};vr.WalletConnectV2Provider=FI});var AL=v((dme,vL)=>{"use strict";l();vL.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var _L=v((pme,IL)=>{"use strict";l();var bL=typeof Symbol<"u"&&Symbol,nte=AL();IL.exports=function(){return typeof bL!="function"||typeof Symbol!="function"||typeof bL("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:nte()}});var CL=v((yme,TL)=>{"use strict";l();var SL={foo:{}},ite=Object;TL.exports=function(){return{__proto__:SL}.foo===SL.foo&&!({__proto__:null}instanceof ite)}});var OL=v((wme,NL)=>{"use strict";l();var ste="Function.prototype.bind called on incompatible ",ote=Object.prototype.toString,ate=Math.max,ute="[object Function]",xL=function(e,r){for(var n=[],i=0;i{"use strict";l();var fte=OL();DL.exports=Function.prototype.bind||fte});var RL=v((bme,PL)=>{"use strict";l();var dte=Function.prototype.call,hte=Object.prototype.hasOwnProperty,pte=ay();PL.exports=pte.call(dte,hte)});var cs=v((_me,UL)=>{"use strict";l();var Re,Eu=SyntaxError,ML=Function,wu=TypeError,MI=function(t){try{return ML('"use strict"; return ('+t+").constructor;")()}catch{}},yo=Object.getOwnPropertyDescriptor;if(yo)try{yo({},"")}catch{yo=null}var UI=function(){throw new wu},gte=yo?function(){try{return arguments.callee,UI}catch{try{return yo(arguments,"callee").get}catch{return UI}}}():UI,yu=_L()(),yte=CL()(),Gt=Object.getPrototypeOf||(yte?function(t){return t.__proto__}:null),mu={},mte=typeof Uint8Array>"u"||!Gt?Re:Gt(Uint8Array),mo={"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":yu&&Gt?Gt([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":mu,"%AsyncGenerator%":mu,"%AsyncGeneratorFunction%":mu,"%AsyncIteratorPrototype%":mu,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":ML,"%GeneratorFunction%":mu,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":yu&&Gt?Gt(Gt([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!yu||!Gt?Re:Gt(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!yu||!Gt?Re:Gt(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":yu&&Gt?Gt(""[Symbol.iterator]()):Re,"%Symbol%":yu?Symbol:Re,"%SyntaxError%":Eu,"%ThrowTypeError%":gte,"%TypedArray%":mte,"%TypeError%":wu,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Gt)try{null.error}catch(t){BL=Gt(Gt(t)),mo["%Error.prototype%"]=BL}var BL,wte=function t(e){var r;if(e==="%AsyncFunction%")r=MI("async function () {}");else if(e==="%GeneratorFunction%")r=MI("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=MI("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Gt&&(r=Gt(i.prototype))}return mo[e]=r,r},LL={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Jl=ay(),uy=RL(),Ete=Jl.call(Function.call,Array.prototype.concat),vte=Jl.call(Function.apply,Array.prototype.splice),FL=Jl.call(Function.call,String.prototype.replace),cy=Jl.call(Function.call,String.prototype.slice),Ate=Jl.call(Function.call,RegExp.prototype.exec),bte=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Ite=/\\(\\)?/g,_te=function(e){var r=cy(e,0,1),n=cy(e,-1);if(r==="%"&&n!=="%")throw new Eu("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Eu("invalid intrinsic syntax, expected opening `%`");var i=[];return FL(e,bte,function(s,o,a,u){i[i.length]=a?FL(u,Ite,"$1"):o||s}),i},Ste=function(e,r){var n=e,i;if(uy(LL,n)&&(i=LL[n],n="%"+i[0]+"%"),uy(mo,n)){var s=mo[n];if(s===mu&&(s=wte(n)),typeof s>"u"&&!r)throw new wu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Eu("intrinsic "+e+" does not exist!")};UL.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new wu("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new wu('"allowMissing" argument must be a boolean');if(Ate(/^%?[^%]*%?$/,e)===null)throw new Eu("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=_te(e),i=n.length>0?n[0]:"",s=Ste("%"+i+"%",r),o=s.name,a=s.value,u=!1,c=s.alias;c&&(i=c[0],vte(n,Ete([0,1],c)));for(var f=1,d=!0;f=n.length){var A=yo(a,g);d=!!A,d&&"get"in A&&!("originalValue"in A.get)?a=A.get:a=a[g]}else d=uy(a,g),a=a[g];d&&!u&&(mo[o]=a)}}return a}});var HI=v((Tme,qL)=>{"use strict";l();var Tte=cs(),qI=Tte("%Object.defineProperty%",!0),VI=function(){if(qI)try{return qI({},"a",{value:1}),!0}catch{return!1}return!1};VI.hasArrayLengthDefineBug=function(){if(!VI())return null;try{return qI([],"length",{value:1}).length!==1}catch{return!0}};qL.exports=VI});var kI=v((xme,VL)=>{"use strict";l();var Cte=cs(),ly=Cte("%Object.getOwnPropertyDescriptor%",!0);if(ly)try{ly([],"length")}catch{ly=null}VL.exports=ly});var GL=v((Ome,kL)=>{"use strict";l();var xte=HI()(),GI=cs(),Xl=xte&&GI("%Object.defineProperty%",!0);if(Xl)try{Xl({},"a",{value:1})}catch{Xl=!1}var Nte=GI("%SyntaxError%"),vu=GI("%TypeError%"),HL=kI();kL.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new vu("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new vu("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new vu("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new vu("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new vu("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new vu("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,u=!!HL&&HL(e,r);if(Xl)Xl(e,r,{configurable:o===null&&u?u.configurable:!o,enumerable:i===null&&u?u.enumerable:!i,value:n,writable:s===null&&u?u.writable:!s});else if(a||!i&&!s&&!o)e[r]=n;else throw new Nte("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var KL=v((Pme,$L)=>{"use strict";l();var WL=cs(),jL=GL(),Ote=HI()(),QL=kI(),zL=WL("%TypeError%"),Dte=WL("%Math.floor%");$L.exports=function(e,r){if(typeof e!="function")throw new zL("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Dte(r)!==r)throw new zL("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&QL){var o=QL(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(Ote?jL(e,"length",r,!0,!0):jL(e,"length",r)),e}});var eF=v((Bme,fy)=>{"use strict";l();var jI=ay(),Au=cs(),Pte=KL(),Rte=Au("%TypeError%"),JL=Au("%Function.prototype.apply%"),XL=Au("%Function.prototype.call%"),ZL=Au("%Reflect.apply%",!0)||jI.call(XL,JL),Zl=Au("%Object.defineProperty%",!0),Bte=Au("%Math.max%");if(Zl)try{Zl({},"a",{value:1})}catch{Zl=null}fy.exports=function(e){if(typeof e!="function")throw new Rte("a function is required");var r=ZL(jI,XL,arguments);return Pte(r,1+Bte(0,e.length-(arguments.length-1)),!0)};var YL=function(){return ZL(jI,JL,arguments)};Zl?Zl(fy.exports,"apply",{value:YL}):fy.exports.apply=YL});var iF=v((Fme,nF)=>{"use strict";l();var tF=cs(),rF=eF(),Lte=rF(tF("String.prototype.indexOf"));nF.exports=function(e,r){var n=tF(e,!!r);return typeof n=="function"&&Lte(e,".prototype.")>-1?rF(n):n}});var sF=v(()=>{l()});var SF=v((Hme,_F)=>{l();var e_=typeof Map=="function"&&Map.prototype,QI=Object.getOwnPropertyDescriptor&&e_?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,hy=e_&&QI&&typeof QI.get=="function"?QI.get:null,oF=e_&&Map.prototype.forEach,t_=typeof Set=="function"&&Set.prototype,zI=Object.getOwnPropertyDescriptor&&t_?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,py=t_&&zI&&typeof zI.get=="function"?zI.get:null,aF=t_&&Set.prototype.forEach,Fte=typeof WeakMap=="function"&&WeakMap.prototype,tf=Fte?WeakMap.prototype.has:null,Mte=typeof WeakSet=="function"&&WeakSet.prototype,rf=Mte?WeakSet.prototype.has:null,Ute=typeof WeakRef=="function"&&WeakRef.prototype,uF=Ute?WeakRef.prototype.deref:null,qte=Boolean.prototype.valueOf,Vte=Object.prototype.toString,Hte=Function.prototype.toString,kte=String.prototype.match,r_=String.prototype.slice,fs=String.prototype.replace,Gte=String.prototype.toUpperCase,cF=String.prototype.toLowerCase,wF=RegExp.prototype.test,lF=Array.prototype.concat,qn=Array.prototype.join,jte=Array.prototype.slice,fF=Math.floor,KI=typeof BigInt=="function"?BigInt.prototype.valueOf:null,WI=Object.getOwnPropertySymbols,YI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,bu=typeof Symbol=="function"&&typeof Symbol.iterator=="object",nr=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===bu||!0)?Symbol.toStringTag:null,EF=Object.prototype.propertyIsEnumerable,dF=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function hF(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||wF.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-fF(-t):fF(t);if(n!==t){var i=String(n),s=r_.call(e,i.length+1);return fs.call(i,r,"$&_")+"."+fs.call(fs.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fs.call(e,r,"$&_")}var JI=sF(),pF=JI.custom,gF=AF(pF)?pF:null;_F.exports=function t(e,r,n,i){var s=r||{};if(ls(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(ls(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=ls(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(ls(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(ls(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return IF(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var u=String(e);return a?hF(e,u):u}if(typeof e=="bigint"){var c=String(e)+"n";return a?hF(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return XI(e)?"[Array]":"[Object]";var d=ure(s,n);if(typeof i>"u")i=[];else if(bF(i,e)>=0)return"[Circular]";function g(Q,K,ye){if(K&&(i=jte.call(i),i.push(K)),ye){var ce={depth:s.depth};return ls(s,"quoteStyle")&&(ce.quoteStyle=s.quoteStyle),t(Q,ce,n+1,i)}return t(Q,s,n+1,i)}if(typeof e=="function"&&!yF(e)){var m=Zte(e),y=dy(e,g);return"[Function"+(m?": "+m:" (anonymous)")+"]"+(y.length>0?" { "+qn.call(y,", ")+" }":"")}if(AF(e)){var A=bu?fs.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):YI.call(e);return typeof e=="object"&&!bu?ef(A):A}if(sre(e)){for(var O="<"+cF.call(String(e.nodeName)),R=e.attributes||[],q=0;q",O}if(XI(e)){if(e.length===0)return"[]";var M=dy(e,g);return d&&!are(M)?"["+ZI(M,d)+"]":"[ "+qn.call(M,", ")+" ]"}if(Wte(e)){var b=dy(e,g);return!("cause"in Error.prototype)&&"cause"in e&&!EF.call(e,"cause")?"{ ["+String(e)+"] "+qn.call(lF.call("[cause]: "+g(e.cause),b),", ")+" }":b.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+qn.call(b,", ")+" }"}if(typeof e=="object"&&o){if(gF&&typeof e[gF]=="function"&&JI)return JI(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(ere(e)){var S=[];return oF&&oF.call(e,function(Q,K){S.push(g(K,e,!0)+" => "+g(Q,e))}),mF("Map",hy.call(e),S,d)}if(nre(e)){var N=[];return aF&&aF.call(e,function(Q){N.push(g(Q,e))}),mF("Set",py.call(e),N,d)}if(tre(e))return $I("WeakMap");if(ire(e))return $I("WeakSet");if(rre(e))return $I("WeakRef");if(Kte(e))return ef(g(Number(e)));if(Jte(e))return ef(g(KI.call(e)));if(Yte(e))return ef(qte.call(e));if($te(e))return ef(g(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!zte(e)&&!yF(e)){var _=dy(e,g),T=dF?dF(e)===Object.prototype:e instanceof Object||e.constructor===Object,B=e instanceof Object?"":"null prototype",X=!T&&nr&&Object(e)===e&&nr in e?r_.call(ds(e),8,-1):B?"Object":"",z=T||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",k=z+(X||B?"["+qn.call(lF.call([],X||[],B||[]),": ")+"] ":"");return _.length===0?k+"{}":d?k+"{"+ZI(_,d)+"}":k+"{ "+qn.call(_,", ")+" }"}return String(e)};function vF(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function Qte(t){return fs.call(String(t),/"/g,""")}function XI(t){return ds(t)==="[object Array]"&&(!nr||!(typeof t=="object"&&nr in t))}function zte(t){return ds(t)==="[object Date]"&&(!nr||!(typeof t=="object"&&nr in t))}function yF(t){return ds(t)==="[object RegExp]"&&(!nr||!(typeof t=="object"&&nr in t))}function Wte(t){return ds(t)==="[object Error]"&&(!nr||!(typeof t=="object"&&nr in t))}function $te(t){return ds(t)==="[object String]"&&(!nr||!(typeof t=="object"&&nr in t))}function Kte(t){return ds(t)==="[object Number]"&&(!nr||!(typeof t=="object"&&nr in t))}function Yte(t){return ds(t)==="[object Boolean]"&&(!nr||!(typeof t=="object"&&nr in t))}function AF(t){if(bu)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!YI)return!1;try{return YI.call(t),!0}catch{}return!1}function Jte(t){if(!t||typeof t!="object"||!KI)return!1;try{return KI.call(t),!0}catch{}return!1}var Xte=Object.prototype.hasOwnProperty||function(t){return t in this};function ls(t,e){return Xte.call(t,e)}function ds(t){return Vte.call(t)}function Zte(t){if(t.name)return t.name;var e=kte.call(Hte.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function bF(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return IF(r_.call(t,0,e.maxStringLength),e)+n}var i=fs.call(fs.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,ore);return vF(i,"single",e)}function ore(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+Gte.call(e.toString(16))}function ef(t){return"Object("+t+")"}function $I(t){return t+" { ? }"}function mF(t,e,r,n){var i=n?ZI(r,n):qn.call(r,", ");return t+" ("+e+") {"+i+"}"}function are(t){for(var e=0;e=0)return!1;return!0}function ure(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=qn.call(Array(t.indent+1)," ");else return null;return{base:r,prev:qn.call(Array(e+1),r)}}function ZI(t,e){if(t.length===0)return"";var r=` -`+e.prev+e.base;return r+qn.call(t,","+r)+` -`+e.prev}function dy(t,e){var r=XI(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";l();var n_=cs(),Iu=iF(),cre=SF(),lre=n_("%TypeError%"),gy=n_("%WeakMap%",!0),yy=n_("%Map%",!0),fre=Iu("WeakMap.prototype.get",!0),dre=Iu("WeakMap.prototype.set",!0),hre=Iu("WeakMap.prototype.has",!0),pre=Iu("Map.prototype.get",!0),gre=Iu("Map.prototype.set",!0),yre=Iu("Map.prototype.has",!0),i_=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},mre=function(t,e){var r=i_(t,e);return r&&r.value},wre=function(t,e,r){var n=i_(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},Ere=function(t,e){return!!i_(t,e)};TF.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new lre("Side channel does not contain "+cre(s))},get:function(s){if(gy&&s&&(typeof s=="object"||typeof s=="function")){if(e)return fre(e,s)}else if(yy){if(r)return pre(r,s)}else if(n)return mre(n,s)},has:function(s){if(gy&&s&&(typeof s=="object"||typeof s=="function")){if(e)return hre(e,s)}else if(yy){if(r)return yre(r,s)}else if(n)return Ere(n,s);return!1},set:function(s,o){gy&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new gy),dre(e,s,o)):yy?(r||(r=new yy),gre(r,s,o)):(n||(n={key:{},next:null}),wre(n,s,o))}};return i}});var my=v((Qme,xF)=>{"use strict";l();var vre=String.prototype.replace,Are=/%20/g,s_={RFC1738:"RFC1738",RFC3986:"RFC3986"};xF.exports={default:s_.RFC3986,formatters:{RFC1738:function(t){return vre.call(t,Are,"+")},RFC3986:function(t){return String(t)}},RFC1738:s_.RFC1738,RFC3986:s_.RFC3986}});var a_=v((Wme,OF)=>{"use strict";l();var bre=my(),o_=Object.prototype.hasOwnProperty,wo=Array.isArray,Vn=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),Ire=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(wo(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===bre.RFC1738&&(c===40||c===41)){a+=o.charAt(u);continue}if(c<128){a=a+Vn[c];continue}if(c<2048){a=a+(Vn[192|c>>6]+Vn[128|c&63]);continue}if(c<55296||c>=57344){a=a+(Vn[224|c>>12]+Vn[128|c>>6&63]+Vn[128|c&63]);continue}u+=1,c=65536+((c&1023)<<10|o.charCodeAt(u)&1023),a+=Vn[240|c>>18]+Vn[128|c>>12&63]+Vn[128|c>>6&63]+Vn[128|c&63]}return a},xre=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";l();var RF=CF(),c_=a_(),nf=my(),Rre=Object.prototype.hasOwnProperty,DF={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},Eo=Array.isArray,Bre=String.prototype.split,Lre=Array.prototype.push,BF=function(t,e){Lre.apply(t,Eo(e)?e:[e])},Fre=Date.prototype.toISOString,PF=nf.default,$t={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:c_.encode,encodeValuesOnly:!1,format:PF,formatter:nf.formatters[PF],indices:!1,serializeDate:function(e){return Fre.call(e)},skipNulls:!1,strictNullHandling:!1},Mre=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},u_={},Ure=function t(e,r,n,i,s,o,a,u,c,f,d,g,m,y,A){for(var O=e,R=A,q=0,M=!1;(R=R.get(u_))!==void 0&&!M;){var b=R.get(e);if(q+=1,typeof b<"u"){if(b===q)throw new RangeError("Cyclic object value");M=!0}typeof R.get(u_)>"u"&&(q=0)}if(typeof a=="function"?O=a(r,O):O instanceof Date?O=f(O):n==="comma"&&Eo(O)&&(O=c_.maybeMap(O,function(ie){return ie instanceof Date?f(ie):ie})),O===null){if(i)return o&&!m?o(r,$t.encoder,y,"key",d):r;O=""}if(Mre(O)||c_.isBuffer(O)){if(o){var S=m?r:o(r,$t.encoder,y,"key",d);if(n==="comma"&&m){for(var N=Bre.call(String(O),","),_="",T=0;T"u")return B;var X;if(n==="comma"&&Eo(O))X=[{value:O.length>0?O.join(",")||null:void 0}];else if(Eo(a))X=a;else{var z=Object.keys(O);X=u?z.sort(u):z}for(var k=0;k"u"?$t.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:$t.charsetSentinel,delimiter:typeof e.delimiter>"u"?$t.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:$t.encode,encoder:typeof e.encoder=="function"?e.encoder:$t.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:$t.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:$t.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:$t.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:$t.strictNullHandling}};LF.exports=function(t,e){var r=t,n=qre(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Eo(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var a;e&&e.arrayFormat in DF?a=e.arrayFormat:e&&"indices"in e?a=e.indices?"indices":"repeat":a="indices";var u=DF[a];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=RF(),f=0;f0?m+g:""}});var qF=v((Jme,UF)=>{"use strict";l();var _u=a_(),l_=Object.prototype.hasOwnProperty,Vre=Array.isArray,jt={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:_u.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Hre=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},MF=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},kre="utf8=%26%2310003%3B",Gre="utf8=%E2%9C%93",jre=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),a=-1,u,c=r.charset;if(r.charsetSentinel)for(u=0;u-1&&(y=Vre(y)?[y]:y),l_.call(n,m)?n[m]=_u.combine(n[m],y):n[m]=y}return n},Qre=function(t,e,r,n){for(var i=n?e:MF(e,r),s=t.length-1;s>=0;--s){var o,a=t[s];if(a==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var u=a.charAt(0)==="["&&a.charAt(a.length-1)==="]"?a.slice(1,-1):a,c=parseInt(u,10);!r.parseArrays&&u===""?o={0:i}:!isNaN(c)&&a!==u&&String(c)===u&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):u!=="__proto__"&&(o[u]=i)}i=o}return i},zre=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,a=/(\[[^[\]]*])/g,u=n.depth>0&&o.exec(s),c=u?s.slice(0,u.index):s,f=[];if(c){if(!n.plainObjects&&l_.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(u=a.exec(s))!==null&&d"u"?jt.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?jt.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:jt.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:jt.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:jt.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:jt.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:jt.comma,decoder:typeof e.decoder=="function"?e.decoder:jt.decoder,delimiter:typeof e.delimiter=="string"||_u.isRegExp(e.delimiter)?e.delimiter:jt.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:jt.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:jt.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:jt.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:jt.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:jt.strictNullHandling}};UF.exports=function(t,e){var r=Wre(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?jre(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";l();var $re=FF(),Kre=qF(),Yre=my();VF.exports={formats:Yre,parse:Kre,stringify:$re}});var f_=v(Ge=>{"use strict";l();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=Ge.WALLET_PROVIDER_CALLBACK_PARAM=Ge.WALLET_PROVIDER_SIGN_MESSAGE_URL=Ge.WALLET_PROVIDER_GUARD_TRANSACTION_URL=Ge.WALLET_PROVIDER_SIGN_TRANSACTION_URL=Ge.WALLET_PROVIDER_SEND_TRANSACTION_URL=Ge.WALLET_PROVIDER_DISCONNECT_URL=Ge.WALLET_PROVIDER_CONNECT_URL=Ge.XALIAS_PROVIDER_TESTNET=Ge.XALIAS_PROVIDER_DEVNET=Ge.XALIAS_PROVIDER_MAINNET=Ge.WALLET_PROVIDER_TESTNET=Ge.WALLET_PROVIDER_DEVNET=Ge.WALLET_PROVIDER_MAINNET=void 0;Ge.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";Ge.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";Ge.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";Ge.XALIAS_PROVIDER_MAINNET="https://xalias.com";Ge.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";Ge.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";Ge.WALLET_PROVIDER_CONNECT_URL="hook/login";Ge.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";Ge.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";Ge.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";Ge.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";Ge.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";Ge.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";Ge.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var kF=v(Su=>{"use strict";l();Object.defineProperty(Su,"__esModule",{value:!0});Su.ErrCannotSignedMessage=Su.ErrCannotGetSignedTransactions=void 0;var d_=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Su.ErrCannotGetSignedTransactions=d_;var h_=class extends Error{constructor(){super("Cannot get signed message")}};Su.ErrCannotSignedMessage=h_});var GF=v(wy=>{"use strict";l();Object.defineProperty(wy,"__esModule",{value:!0});wy.PlainSignedTransaction=void 0;var p_=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};wy.PlainSignedTransaction=p_});var Tu=v(gs=>{"use strict";l();var hs=gs&&gs.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})},Jre=gs&&gs.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gs,"__esModule",{value:!0});gs.WalletProvider=void 0;var g_=Jre(HF()),ps=f_(),y_=kF(),Xre=GF(),m_=class t{constructor(e){this.walletUrl=e}login(e){return hs(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ps.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return hs(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return hs(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return hs(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ps.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return hs(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:ps.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=g_.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new y_.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return hs(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ps.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return hs(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ps.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return hs(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(){let e=g_.default.parse(window.location.search.slice(1));return t.isTxSignReturnSuccess(e)?this.getTxSignReturnValue(e):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(ps.WALLET_PROVIDER_CALLBACK_PARAM)&&e[ps.WALLET_PROVIDER_CALLBACK_PARAM]===ps.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new y_.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new y_.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let a=t.prepareWalletTransaction(o);for(let u in a)a.hasOwnProperty(u)&&!i.hasOwnProperty(u)&&(i[u]=[]),i[u].push(a[u])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};gs.WalletProvider=m_});var IM=v((cwe,bM)=>{"use strict";l();function tM(t,e){return function(){return t.apply(e,arguments)}}var{toString:Zre}=Object.prototype,{getPrototypeOf:N_}=Object,by=(t=>e=>{let r=Zre.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kn=t=>(t=t.toLowerCase(),e=>by(e)===t),Iy=t=>e=>typeof e===t,{isArray:Ou}=Array,of=Iy("undefined");function ene(t){return t!==null&&!of(t)&&t.constructor!==null&&!of(t.constructor)&&Qr(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var rM=kn("ArrayBuffer");function tne(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&rM(t.buffer),e}var rne=Iy("string"),Qr=Iy("function"),nM=Iy("number"),_y=t=>t!==null&&typeof t=="object",nne=t=>t===!0||t===!1,Ey=t=>{if(by(t)!=="object")return!1;let e=N_(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ine=kn("Date"),sne=kn("File"),one=kn("Blob"),ane=kn("FileList"),une=t=>_y(t)&&Qr(t.pipe),cne=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Qr(t.append)&&((e=by(t))==="formdata"||e==="object"&&Qr(t.toString)&&t.toString()==="[object FormData]"))},lne=kn("URLSearchParams"),fne=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function af(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ou(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var sM=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,oM=t=>!of(t)&&t!==sM;function b_(){let{caseless:t}=oM(this)&&this||{},e={},r=(n,i)=>{let s=t&&iM(e,i)||i;Ey(e[s])&&Ey(n)?e[s]=b_(e[s],n):Ey(n)?e[s]=b_({},n):Ou(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(af(e,(i,s)=>{r&&Qr(i)?t[s]=tM(i,r):t[s]=i},{allOwnKeys:n}),t),hne=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),pne=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},gne=(t,e,r,n)=>{let i,s,o,a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=r!==!1&&N_(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},yne=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},mne=t=>{if(!t)return null;if(Ou(t))return t;let e=t.length;if(!nM(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},wne=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&N_(Uint8Array)),Ene=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},vne=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Ane=kn("HTMLFormElement"),bne=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),jF=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Ine=kn("RegExp"),aM=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};af(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},_ne=t=>{aM(t,(e,r)=>{if(Qr(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(Qr(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Sne=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ou(t)?n(t):n(String(t).split(e)),r},Tne=()=>{},Cne=(t,e)=>(t=+t,Number.isFinite(t)?t:e),w_="abcdefghijklmnopqrstuvwxyz",QF="0123456789",uM={DIGIT:QF,ALPHA:w_,ALPHA_DIGIT:w_+w_.toUpperCase()+QF},xne=(t=16,e=uM.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function Nne(t){return!!(t&&Qr(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var One=t=>{let e=new Array(10),r=(n,i)=>{if(_y(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ou(n)?[]:{};return af(n,(o,a)=>{let u=r(o,i+1);!of(u)&&(s[a]=u)}),e[i]=void 0,s}}return n};return r(t,0)},Dne=kn("AsyncFunction"),Pne=t=>t&&(_y(t)||Qr(t))&&Qr(t.then)&&Qr(t.catch),Y={isArray:Ou,isArrayBuffer:rM,isBuffer:ene,isFormData:cne,isArrayBufferView:tne,isString:rne,isNumber:nM,isBoolean:nne,isObject:_y,isPlainObject:Ey,isUndefined:of,isDate:ine,isFile:sne,isBlob:one,isRegExp:Ine,isFunction:Qr,isStream:une,isURLSearchParams:lne,isTypedArray:wne,isFileList:ane,forEach:af,merge:b_,extend:dne,trim:fne,stripBOM:hne,inherits:pne,toFlatObject:gne,kindOf:by,kindOfTest:kn,endsWith:yne,toArray:mne,forEachEntry:Ene,matchAll:vne,isHTMLForm:Ane,hasOwnProperty:jF,hasOwnProp:jF,reduceDescriptors:aM,freezeMethods:_ne,toObjectSet:Sne,toCamelCase:bne,noop:Tne,toFiniteNumber:Cne,findKey:iM,global:sM,isContextDefined:oM,ALPHABET:uM,generateString:xne,isSpecCompliantForm:Nne,toJSONObject:One,isAsyncFn:Dne,isThenable:Pne};function Me(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}Y.inherits(Me,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:Y.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var cM=Me.prototype,lM={};["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(t=>{lM[t]={value:t}});Object.defineProperties(Me,lM);Object.defineProperty(cM,"isAxiosError",{value:!0});Me.from=(t,e,r,n,i,s)=>{let o=Object.create(cM);return Y.toFlatObject(t,o,function(u){return u!==Error.prototype},a=>a!=="isAxiosError"),Me.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var Rne=null;function I_(t){return Y.isPlainObject(t)||Y.isArray(t)}function fM(t){return Y.endsWith(t,"[]")?t.slice(0,-2):t}function zF(t,e,r){return t?t.concat(e).map(function(i,s){return i=fM(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Bne(t){return Y.isArray(t)&&!t.some(I_)}var Lne=Y.toFlatObject(Y,{},null,function(e){return/^is[A-Z]/.test(e)});function Sy(t,e,r){if(!Y.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=Y.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(A,O){return!Y.isUndefined(O[A])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,u=(r.Blob||typeof Blob<"u"&&Blob)&&Y.isSpecCompliantForm(e);if(!Y.isFunction(i))throw new TypeError("visitor must be a function");function c(y){if(y===null)return"";if(Y.isDate(y))return y.toISOString();if(!u&&Y.isBlob(y))throw new Me("Blob is not supported. Use a Buffer instead.");return Y.isArrayBuffer(y)||Y.isTypedArray(y)?u&&typeof Blob=="function"?new Blob([y]):h.Buffer.from(y):y}function f(y,A,O){let R=y;if(y&&!O&&typeof y=="object"){if(Y.endsWith(A,"{}"))A=n?A:A.slice(0,-2),y=JSON.stringify(y);else if(Y.isArray(y)&&Bne(y)||(Y.isFileList(y)||Y.endsWith(A,"[]"))&&(R=Y.toArray(y)))return A=fM(A),R.forEach(function(M,b){!(Y.isUndefined(M)||M===null)&&e.append(o===!0?zF([A],b,s):o===null?A:A+"[]",c(M))}),!1}return I_(y)?!0:(e.append(zF(O,A,s),c(y)),!1)}let d=[],g=Object.assign(Lne,{defaultVisitor:f,convertValue:c,isVisitable:I_});function m(y,A){if(!Y.isUndefined(y)){if(d.indexOf(y)!==-1)throw Error("Circular reference detected in "+A.join("."));d.push(y),Y.forEach(y,function(R,q){(!(Y.isUndefined(R)||R===null)&&i.call(e,R,Y.isString(q)?q.trim():q,A,g))===!0&&m(R,A?A.concat(q):[q])}),d.pop()}}if(!Y.isObject(t))throw new TypeError("data must be an object");return m(t),e}function WF(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function O_(t,e){this._pairs=[],t&&Sy(t,this,e)}var dM=O_.prototype;dM.append=function(e,r){this._pairs.push([e,r])};dM.toString=function(e){let r=e?function(n){return e.call(this,n,WF)}:WF;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Fne(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function hM(t,e,r){if(!e)return t;let n=r&&r.encode||Fne,i=r&&r.serialize,s;if(i?s=i(e,r):s=Y.isURLSearchParams(e)?e.toString():new O_(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var __=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Y.forEach(this.handlers,function(n){n!==null&&e(n)})}},$F=__,pM={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Mne=typeof URLSearchParams<"u"?URLSearchParams:O_,Une=typeof FormData<"u"?FormData:null,qne=typeof Blob<"u"?Blob:null,Vne={isBrowser:!0,classes:{URLSearchParams:Mne,FormData:Une,Blob:qne},protocols:["http","https","file","blob","url","data"]},gM=typeof window<"u"&&typeof document<"u",Hne=(t=>gM&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),kne=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Gne=Object.freeze({__proto__:null,hasBrowserEnv:gM,hasStandardBrowserWebWorkerEnv:kne,hasStandardBrowserEnv:Hne}),Hn={...Gne,...Vne};function jne(t,e){return Sy(t,new Hn.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Hn.isNode&&Y.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function Qne(t){return Y.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function zne(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&Y.isArray(i)?i.length:o,u?(Y.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!a):((!i[o]||!Y.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&Y.isArray(i[o])&&(i[o]=zne(i[o])),!a)}if(Y.isFormData(t)&&Y.isFunction(t.entries)){let r={};return Y.forEachEntry(t,(n,i)=>{e(Qne(n),i,r,0)}),r}return null}function Wne(t,e,r){if(Y.isString(t))try{return(e||JSON.parse)(t),Y.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var D_={transitional:pM,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=Y.isObject(e);if(s&&Y.isHTMLForm(e)&&(e=new FormData(e)),Y.isFormData(e))return i?JSON.stringify(yM(e)):e;if(Y.isArrayBuffer(e)||Y.isBuffer(e)||Y.isStream(e)||Y.isFile(e)||Y.isBlob(e))return e;if(Y.isArrayBufferView(e))return e.buffer;if(Y.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return jne(e,this.formSerializer).toString();if((a=Y.isFileList(e))||n.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return Sy(a?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Wne(e)):e}],transformResponse:[function(e){let r=this.transitional||D_.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&Y.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?Me.from(a,Me.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Hn.classes.FormData,Blob:Hn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Y.forEach(["delete","get","head","post","put","patch"],t=>{D_.headers[t]={}});var P_=D_,$ne=Y.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"]),Kne=t=>{let e={},r,n,i;return t&&t.split(` -`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&$ne[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},KF=Symbol("internals");function sf(t){return t&&String(t).trim().toLowerCase()}function vy(t){return t===!1||t==null?t:Y.isArray(t)?t.map(vy):String(t)}function Yne(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Jne=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function E_(t,e,r,n,i){if(Y.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!Y.isString(e)){if(Y.isString(n))return e.indexOf(n)!==-1;if(Y.isRegExp(n))return n.test(e)}}function Xne(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function Zne(t,e){let r=Y.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Cu=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(a,u,c){let f=sf(u);if(!f)throw new Error("header name must be a non-empty string");let d=Y.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||u]=vy(a))}let o=(a,u)=>Y.forEach(a,(c,f)=>s(c,f,u));return Y.isPlainObject(e)||e instanceof this.constructor?o(e,r):Y.isString(e)&&(e=e.trim())&&!Jne(e)?o(Kne(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=sf(e),e){let n=Y.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Yne(i);if(Y.isFunction(r))return r.call(this,i,n);if(Y.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=sf(e),e){let n=Y.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||E_(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=sf(o),o){let a=Y.findKey(n,o);a&&(!r||E_(n,n[a],a,r))&&(delete n[a],i=!0)}}return Y.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||E_(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return Y.forEach(this,(i,s)=>{let o=Y.findKey(n,s);if(o){r[o]=vy(i),delete r[s];return}let a=e?Xne(s):String(s).trim();a!==s&&delete r[s],r[a]=vy(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return Y.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&Y.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[KF]=this[KF]={accessors:{}}).accessors,i=this.prototype;function s(o){let a=sf(o);n[a]||(Zne(i,o),n[a]=!0)}return Y.isArray(e)?e.forEach(s):s(e),this}};Cu.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Y.reduceDescriptors(Cu.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});Y.freezeMethods(Cu);var yi=Cu;function v_(t,e){let r=this||P_,n=e||r,i=yi.from(n.headers),s=n.data;return Y.forEach(t,function(a){s=a.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function mM(t){return!!(t&&t.__CANCEL__)}function uf(t,e,r){Me.call(this,t??"canceled",Me.ERR_CANCELED,e,r),this.name="CanceledError"}Y.inherits(uf,Me,{__CANCEL__:!0});function eie(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Me("Request failed with status code "+r.status,[Me.ERR_BAD_REQUEST,Me.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var tie=Hn.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];Y.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Y.isString(n)&&o.push("path="+n),Y.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function rie(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function nie(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function wM(t,e){return t&&!rie(e)?nie(t,e):e}var iie=Hn.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let a=Y.isString(o)?i(o):o;return a.protocol===n.protocol&&a.host===n.host}}():function(){return function(){return!0}}();function sie(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function oie(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(u){let c=Date.now(),f=n[s];o||(o=c),r[i]=u,n[i]=c;let d=s,g=0;for(;d!==i;)g+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,a=s-r,u=n(a),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:u||void 0,estimated:u&&o&&c?(o-s)/u:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var aie=typeof XMLHttpRequest<"u",uie=aie&&function(t){return new Promise(function(r,n){let i=t.data,s=yi.from(t.headers).normalize(),{responseType:o,withXSRFToken:a}=t,u;function c(){t.cancelToken&&t.cancelToken.unsubscribe(u),t.signal&&t.signal.removeEventListener("abort",u)}let f;if(Y.isFormData(i)){if(Hn.hasStandardBrowserEnv||Hn.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[A,...O]=f?f.split(";").map(R=>R.trim()).filter(Boolean):[];s.setContentType([A||"multipart/form-data",...O].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let A=t.auth.username||"",O=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(A+":"+O))}let g=wM(t.baseURL,t.url);d.open(t.method.toUpperCase(),hM(g,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function m(){if(!d)return;let A=yi.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),R={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:A,config:t,request:d};eie(function(M){r(M),c()},function(M){n(M),c()},R),d=null}if("onloadend"in d?d.onloadend=m:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(m)},d.onabort=function(){d&&(n(new Me("Request aborted",Me.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Me("Network Error",Me.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let O=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",R=t.transitional||pM;t.timeoutErrorMessage&&(O=t.timeoutErrorMessage),n(new Me(O,R.clarifyTimeoutError?Me.ETIMEDOUT:Me.ECONNABORTED,t,d)),d=null},Hn.hasStandardBrowserEnv&&(a&&Y.isFunction(a)&&(a=a(t)),a||a!==!1&&iie(g))){let A=t.xsrfHeaderName&&t.xsrfCookieName&&tie.read(t.xsrfCookieName);A&&s.set(t.xsrfHeaderName,A)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&Y.forEach(s.toJSON(),function(O,R){d.setRequestHeader(R,O)}),Y.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",YF(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",YF(t.onUploadProgress)),(t.cancelToken||t.signal)&&(u=A=>{d&&(n(!A||A.type?new uf(null,t,d):A),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(u),t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u)));let y=sie(g);if(y&&Hn.protocols.indexOf(y)===-1){n(new Me("Unsupported protocol "+y+":",Me.ERR_BAD_REQUEST,t));return}d.send(i||null)})},S_={http:Rne,xhr:uie};Y.forEach(S_,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var JF=t=>`- ${t}`,cie=t=>Y.isFunction(t)||t===null||t===!1,EM={getAdapter:t=>{t=Y.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${a} `+(u===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : -`+s.map(JF).join(` -`):" "+JF(s[0]):"as no adapter specified";throw new Me("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:S_};function A_(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new uf(null,t)}function XF(t){return A_(t),t.headers=yi.from(t.headers),t.data=v_.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),EM.getAdapter(t.adapter||P_.adapter)(t).then(function(n){return A_(t),n.data=v_.call(t,t.transformResponse,n),n.headers=yi.from(n.headers),n},function(n){return mM(n)||(A_(t),n&&n.response&&(n.response.data=v_.call(t,t.transformResponse,n.response),n.response.headers=yi.from(n.response.headers))),Promise.reject(n)})}var ZF=t=>t instanceof yi?t.toJSON():t;function xu(t,e){e=e||{};let r={};function n(c,f,d){return Y.isPlainObject(c)&&Y.isPlainObject(f)?Y.merge.call({caseless:d},c,f):Y.isPlainObject(f)?Y.merge({},f):Y.isArray(f)?f.slice():f}function i(c,f,d){if(Y.isUndefined(f)){if(!Y.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!Y.isUndefined(f))return n(void 0,f)}function o(c,f){if(Y.isUndefined(f)){if(!Y.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function a(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let u={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:a,headers:(c,f)=>i(ZF(c),ZF(f),!0)};return Y.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=u[f]||i,g=d(t[f],e[f],f);Y.isUndefined(g)&&d!==a||(r[f]=g)}),r}var vM="1.6.7",R_={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{R_[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var eM={};R_.transitional=function(e,r,n){function i(s,o){return"[Axios v"+vM+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,a)=>{if(e===!1)throw new Me(i(o," has been removed"+(r?" in "+r:"")),Me.ERR_DEPRECATED);return r&&!eM[o]&&(eM[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,a):!0}};function lie(t,e,r){if(typeof t!="object")throw new Me("options must be an object",Me.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let a=t[s],u=a===void 0||o(a,s,t);if(u!==!0)throw new Me("option "+s+" must be "+u,Me.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Me("Unknown option "+s,Me.ERR_BAD_OPTION)}}var T_={assertOptions:lie,validators:R_},ys=T_.validators,Nu=class{constructor(e){this.defaults=e,this.interceptors={request:new $F,response:new $F}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` -`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=xu(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&T_.assertOptions(n,{silentJSONParsing:ys.transitional(ys.boolean),forcedJSONParsing:ys.transitional(ys.boolean),clarifyTimeoutError:ys.transitional(ys.boolean)},!1),i!=null&&(Y.isFunction(i)?r.paramsSerializer={serialize:i}:T_.assertOptions(i,{encode:ys.function,serialize:ys.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&Y.merge(s.common,s[r.method]);s&&Y.forEach(["delete","get","head","post","put","patch","common"],y=>{delete s[y]}),r.headers=yi.concat(o,s);let a=[],u=!0;this.interceptors.request.forEach(function(A){typeof A.runWhen=="function"&&A.runWhen(r)===!1||(u=u&&A.synchronous,a.unshift(A.fulfilled,A.rejected))});let c=[];this.interceptors.response.forEach(function(A){c.push(A.fulfilled,A.rejected)});let f,d=0,g;if(!u){let y=[XF.bind(this),void 0];for(y.unshift.apply(y,a),y.push.apply(y,c),g=y.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(a=>{n.subscribe(a),s=a}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,a){n.reason||(n.reason=new uf(s,o,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},fie=C_;function die(t){return function(r){return t.apply(null,r)}}function hie(t){return Y.isObject(t)&&t.isAxiosError===!0}var x_={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(x_).forEach(([t,e])=>{x_[e]=t});var pie=x_;function AM(t){let e=new Ay(t),r=tM(Ay.prototype.request,e);return Y.extend(r,Ay.prototype,e,{allOwnKeys:!0}),Y.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return AM(xu(t,i))},r}var Rt=AM(P_);Rt.Axios=Ay;Rt.CanceledError=uf;Rt.CancelToken=fie;Rt.isCancel=mM;Rt.VERSION=vM;Rt.toFormData=Sy;Rt.AxiosError=Me;Rt.Cancel=Rt.CanceledError;Rt.all=function(e){return Promise.all(e)};Rt.spread=die;Rt.isAxiosError=hie;Rt.mergeConfig=xu;Rt.AxiosHeaders=yi;Rt.formToJSON=t=>yM(Y.isHTMLForm(t)?new FormData(t):t);Rt.getAdapter=EM.getAdapter;Rt.HttpStatusCode=pie;Rt.default=Rt;bM.exports=Rt});var _M=v(Ty=>{"use strict";l();Object.defineProperty(Ty,"__esModule",{value:!0});Ty.NativeAuthClientConfig=void 0;var B_=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};Ty.NativeAuthClientConfig=B_});var F_=v(Du=>{"use strict";l();var vo=Du&&Du.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Du,"__esModule",{value:!0});Du.NativeAuthClient=void 0;var gie=IM(),yie=_M(),L_=class{constructor(e){this.config=Object.assign(new yie.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vo(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vo(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vo(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vo(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vo(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vo(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(h.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vo(this,void 0,void 0,function*(){return yield gie.default.get(e,{headers:this.config.extraRequestHeaders})})}};Du.NativeAuthClient=L_});var xM=v(xy=>{"use strict";l();Object.defineProperty(xy,"__esModule",{value:!0});xy.TransactionStatus=void 0;var U_=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};xy.TransactionStatus=U_});var OM=v(Ny=>{"use strict";l();Object.defineProperty(Ny,"__esModule",{value:!0});Ny.TransactionReceipt=void 0;var NM=Ta(),q_=class t{constructor(){this.value="",this.sender=new NM.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new NM.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};Ny.TransactionReceipt=q_});var DM=v(Gn=>{"use strict";l();Object.defineProperty(Gn,"__esModule",{value:!0});Gn.ErrContractQuery=Gn.ErrNetworkProvider=Gn.ErrUnexpectedCondition=Gn.Err=void 0;var Ru=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Gn.Err=Ru;var V_=class extends Ru{constructor(e){super(`Unexpected condition: [${e}]`)}};Gn.ErrUnexpectedCondition=V_;var H_=class extends Ru{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Gn.ErrNetworkProvider=H_;var k_=class extends Ru{constructor(e){super(e.message.replace("executeQuery:",""))}};Gn.ErrContractQuery=k_});var RM=v(ms=>{"use strict";l();Object.defineProperty(ms,"__esModule",{value:!0});ms.TransactionEventTopic=ms.TransactionEventData=ms.TransactionEvent=void 0;var PM=Ta(),G_=class t{constructor(e){this.address=new PM.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new Bu(h.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new PM.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new Oy(n)),r.dataPayload=Bu.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(Bu.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};ms.TransactionEvent=G_;var Bu=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(h.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};ms.TransactionEventData=Bu;var Oy=class{constructor(e){this.raw=h.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};ms.TransactionEventTopic=Oy});var Q_=v(Dy=>{"use strict";l();Object.defineProperty(Dy,"__esModule",{value:!0});Dy.TransactionLogs=void 0;var Eie=DM(),BM=Ta(),vie=RM(),j_=class t{constructor(e){this.address=new BM.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new BM.Address(e.address),r.events=(e.events||[]).map(n=>vie.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new Eie.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};Dy.TransactionLogs=j_});var FM=v(Lu=>{"use strict";l();Object.defineProperty(Lu,"__esModule",{value:!0});Lu.ContractResultItem=Lu.ContractResults=void 0;var LM=Q_(),Py=Ta(),z_=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>cf.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>cf.fromApiHttpResponse(n));return new t(r)}};Lu.ContractResults=z_;var cf=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new Py.Address(""),this.sender=new Py.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new LM.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=h.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new Py.Address(e.receiver),r.sender=new Py.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=LM.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Lu.ContractResultItem=cf});var MM=v(Ry=>{"use strict";l();Object.defineProperty(Ry,"__esModule",{value:!0});Ry.ContractQueryRequest=void 0;var W_=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};Ry.ContractQueryRequest=W_});var KM=v((dEe,$M)=>{l();$M.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ws=v(bo=>{l();var $_,Aie=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];bo.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};bo.getSymbolTotalCodewords=function(e){return Aie[e]};bo.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};bo.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');$_=e};bo.isKanjiModeEnabled=function(){return typeof $_<"u"};bo.toSJIS=function(e){return $_(e)}});var My=v(zr=>{l();zr.L={bit:1};zr.M={bit:0};zr.Q={bit:3};zr.H={bit:2};function bie(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return zr.L;case"m":case"medium":return zr.M;case"q":case"quartile":return zr.Q;case"h":case"high":return zr.H;default:throw new Error("Unknown EC Level: "+t)}}zr.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};zr.from=function(e,r){if(zr.isValid(e))return e;try{return bie(e)}catch{return r}}});var XM=v((wEe,JM)=>{l();function YM(){this.buffer=[],this.length=0}YM.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};JM.exports=YM});var eU=v((vEe,ZM)=>{l();function lf(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}lf.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};lf.prototype.get=function(t,e){return this.data[t*this.size+e]};lf.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};lf.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ZM.exports=lf});var tU=v(Uy=>{l();var Iie=ws().getSymbolSize;Uy.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=Iie(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{l();var _ie=ws().getSymbolSize,rU=7;nU.getPositions=function(e){let r=_ie(e);return[[0,0],[r-rU,0],[0,r-rU]]}});var sU=v(nt=>{l();nt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Io={N1:3,N2:3,N3:40,N4:10};nt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};nt.from=function(e){return nt.isValid(e)?parseInt(e,10):void 0};nt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,a=null;for(let u=0;u=5&&(n+=Io.N1+(i-5)),o=f,i=1),f=e.get(c,u),f===a?s++:(s>=5&&(n+=Io.N1+(s-5)),a=f,s=1)}i>=5&&(n+=Io.N1+(i-5)),s>=5&&(n+=Io.N1+(s-5))}return n};nt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&n++}return n*Io.N3};nt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{l();var Es=My(),qy=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Vy=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];K_.getBlocksCount=function(e,r){switch(r){case Es.L:return qy[(e-1)*4+0];case Es.M:return qy[(e-1)*4+1];case Es.Q:return qy[(e-1)*4+2];case Es.H:return qy[(e-1)*4+3];default:return}};K_.getTotalCodewordsCount=function(e,r){switch(r){case Es.L:return Vy[(e-1)*4+0];case Es.M:return Vy[(e-1)*4+1];case Es.Q:return Vy[(e-1)*4+2];case Es.H:return Vy[(e-1)*4+3];default:return}}});var oU=v(ky=>{l();var ff=new Uint8Array(512),Hy=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)ff[r]=e,Hy[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)ff[r]=ff[r-255]})();ky.log=function(e){if(e<1)throw new Error("log("+e+")");return Hy[e]};ky.exp=function(e){return ff[e]};ky.mul=function(e,r){return e===0||r===0?0:ff[Hy[e]+Hy[r]]}});var aU=v(df=>{l();var J_=oU();df.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{l();var uU=aU();function X_(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}X_.prototype.initialize=function(e){this.degree=e,this.genPoly=uU.generateECPolynomial(this.degree)};X_.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=uU.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};cU.exports=X_});var Z_=v(fU=>{l();fU.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var eS=v(mi=>{l();var dU="[0-9]+",Tie="[A-Z $%*+\\-./:]+",hf="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";hf=hf.replace(/u/g,"\\u");var Cie="(?:(?![A-Z0-9 $%*+\\-./:]|"+hf+`)(?:.|[\r -]))+`;mi.KANJI=new RegExp(hf,"g");mi.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");mi.BYTE=new RegExp(Cie,"g");mi.NUMERIC=new RegExp(dU,"g");mi.ALPHANUMERIC=new RegExp(Tie,"g");var xie=new RegExp("^"+hf+"$"),Nie=new RegExp("^"+dU+"$"),Oie=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");mi.testKanji=function(e){return xie.test(e)};mi.testNumeric=function(e){return Nie.test(e)};mi.testAlphanumeric=function(e){return Oie.test(e)}});var vs=v(Bt=>{l();var Die=Z_(),tS=eS();Bt.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};Bt.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};Bt.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};Bt.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};Bt.MIXED={bit:-1};Bt.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Die.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};Bt.getBestModeForData=function(e){return tS.testNumeric(e)?Bt.NUMERIC:tS.testAlphanumeric(e)?Bt.ALPHANUMERIC:tS.testKanji(e)?Bt.KANJI:Bt.BYTE};Bt.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};Bt.isValid=function(e){return e&&e.bit&&e.ccBits};function Pie(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return Bt.NUMERIC;case"alphanumeric":return Bt.ALPHANUMERIC;case"kanji":return Bt.KANJI;case"byte":return Bt.BYTE;default:throw new Error("Unknown mode: "+t)}}Bt.from=function(e,r){if(Bt.isValid(e))return e;try{return Pie(e)}catch{return r}}});var mU=v(_o=>{l();var Gy=ws(),Rie=Y_(),hU=My(),As=vs(),rS=Z_(),gU=7973,pU=Gy.getBCHDigit(gU);function Bie(t,e,r){for(let n=1;n<=40;n++)if(e<=_o.getCapacity(n,r,t))return n}function yU(t,e){return As.getCharCountIndicator(t,e)+4}function Lie(t,e){let r=0;return t.forEach(function(n){let i=yU(n.mode,e);r+=i+n.getBitsLength()}),r}function Fie(t,e){for(let r=1;r<=40;r++)if(Lie(t,r)<=_o.getCapacity(r,e,As.MIXED))return r}_o.from=function(e,r){return rS.isValid(e)?parseInt(e,10):r};_o.getCapacity=function(e,r,n){if(!rS.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=As.BYTE);let i=Gy.getSymbolTotalCodewords(e),s=Rie.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===As.MIXED)return o;let a=o-yU(n,e);switch(n){case As.NUMERIC:return Math.floor(a/10*3);case As.ALPHANUMERIC:return Math.floor(a/11*2);case As.KANJI:return Math.floor(a/13);case As.BYTE:default:return Math.floor(a/8)}};_o.getBestVersionForData=function(e,r){let n,i=hU.from(r,hU.M);if(Array.isArray(e)){if(e.length>1)return Fie(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Bie(n.mode,n.getLength(),i)};_o.getEncodedBits=function(e){if(!rS.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Gy.getBCHDigit(r)-pU>=0;)r^=gU<{l();var nS=ws(),EU=1335,Mie=21522,wU=nS.getBCHDigit(EU);vU.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;nS.getBCHDigit(i)-wU>=0;)i^=EU<{l();var Uie=vs();function Mu(t){this.mode=Uie.NUMERIC,this.data=t.toString()}Mu.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Mu.prototype.getLength=function(){return this.data.length};Mu.prototype.getBitsLength=function(){return Mu.getBitsLength(this.data.length)};Mu.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};bU.exports=Mu});var SU=v(($Ee,_U)=>{l();var qie=vs(),iS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Uu(t){this.mode=qie.ALPHANUMERIC,this.data=t}Uu.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Uu.prototype.getLength=function(){return this.data.length};Uu.prototype.getBitsLength=function(){return Uu.getBitsLength(this.data.length)};Uu.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=iS.indexOf(this.data[r])*45;n+=iS.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(iS.indexOf(this.data[r]),6)};_U.exports=Uu});var CU=v((YEe,TU)=>{"use strict";l();TU.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var NU=v((XEe,xU)=>{l();var Vie=CU(),Hie=vs();function qu(t){this.mode=Hie.BYTE,typeof t=="string"&&(t=Vie(t)),this.data=new Uint8Array(t)}qu.getBitsLength=function(e){return e*8};qu.prototype.getLength=function(){return this.data.length};qu.prototype.getBitsLength=function(){return qu.getBitsLength(this.data.length)};qu.prototype.write=function(t){for(let e=0,r=this.data.length;e{l();var kie=vs(),Gie=ws();function Vu(t){this.mode=kie.KANJI,this.data=t}Vu.getBitsLength=function(e){return e*13};Vu.prototype.getLength=function(){return this.data.length};Vu.prototype.getBitsLength=function(){return Vu.getBitsLength(this.data.length)};Vu.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` -Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};OU.exports=Vu});var PU=v((rve,sS)=>{"use strict";l();var pf={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=pf.PriorityQueue.make();s.push(e,0);for(var o,a,u,c,f,d,g,m,y;!s.empty();){o=s.pop(),a=o.value,c=o.cost,f=t[a]||{};for(u in f)f.hasOwnProperty(u)&&(d=f[u],g=c+d,m=i[u],y=typeof i[u]>"u",(y||m>g)&&(i[u]=g,s.push(u,g),n[u]=a))}if(typeof r<"u"&&typeof i[r]>"u"){var A=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(A)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=pf.single_source_shortest_paths(t,e,r);return pf.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=pf.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof sS<"u"&&(sS.exports=pf)});var VU=v(Hu=>{l();var je=vs(),LU=IU(),FU=SU(),MU=NU(),UU=DU(),gf=eS(),jy=ws(),jie=PU();function RU(t){return unescape(encodeURIComponent(t)).length}function yf(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function qU(t){let e=yf(gf.NUMERIC,je.NUMERIC,t),r=yf(gf.ALPHANUMERIC,je.ALPHANUMERIC,t),n,i;return jy.isKanjiModeEnabled()?(n=yf(gf.BYTE,je.BYTE,t),i=yf(gf.KANJI,je.KANJI,t)):(n=yf(gf.BYTE_KANJI,je.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function oS(t,e){switch(e){case je.NUMERIC:return LU.getBitsLength(t);case je.ALPHANUMERIC:return FU.getBitsLength(t);case je.KANJI:return UU.getBitsLength(t);case je.BYTE:return MU.getBitsLength(t)}}function Qie(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function zie(t){let e=[];for(let r=0;r{l();var zy=ws(),aS=My(),$ie=XM(),Kie=eU(),Yie=tU(),Jie=iU(),lS=sU(),fS=Y_(),Xie=lU(),Qy=mU(),Zie=AU(),ese=vs(),uS=VU();function tse(t,e){let r=t.size,n=Jie.getPositions(e);for(let i=0;i=0&&a<=6&&(u===0||u===6)||u>=0&&u<=6&&(a===0||a===6)||a>=2&&a<=4&&u>=2&&u<=4?t.set(s+a,o+u,!0,!0):t.set(s+a,o+u,!1,!0))}}function rse(t){let e=t.size;for(let r=8;r>a&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function cS(t,e,r){let n=t.size,i=Zie.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function sse(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let u=0;u<2;u++)if(!t.isReserved(i,a-u)){let c=!1;o>>s&1)===1),t.set(i,a-u,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function ose(t,e,r){let n=new $ie;r.forEach(function(u){n.put(u.mode.bit,4),n.put(u.getLength(),ese.getCharCountIndicator(u.mode,t)),u.write(n)});let i=zy.getSymbolTotalCodewords(t),s=fS.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let u=0;u=7&&ise(u,e),sse(u,o),isNaN(n)&&(n=lS.getBestMask(u,cS.bind(null,u,r))),lS.applyMask(n,u),cS(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}HU.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=aS.M,i,s;return typeof r<"u"&&(n=aS.from(r.errorCorrectionLevel,aS.M),i=Qy.from(r.version),s=lS.from(r.maskPattern),r.toSJISFunc&&zy.setToSJISFunction(r.toSJISFunc)),use(e,i,n,s)}});var dS=v(So=>{l();function GU(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}So.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:GU(e.color.dark||"#000000ff"),light:GU(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};So.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};So.getImageWidth=function(e,r){let n=So.getScale(e,r);return Math.floor((e+r.margin*2)*n)};So.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=So.getScale(i,n),a=Math.floor((i+n.margin*2)*o),u=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=u&&d>=u&&f{l();var hS=dS();function cse(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function lse(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Wy.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=lse()),i=hS.getOptions(i);let o=hS.getImageWidth(e.modules.size,i),a=s.getContext("2d"),u=a.createImageData(o,o);return hS.qrToImageData(u.data,e,i),cse(a,s,o),a.putImageData(u,0,0),s};Wy.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Wy.render(e,r,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var WU=v(zU=>{l();var fse=dS();function QU(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function pS(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function dse(t,e,r){let n="",i=0,s=!1,o=0;for(let a=0;a0&&u>0&&t[a-1]||(n+=s?pS("M",u+r,.5+c+r):pS("m",i,0),i=0,s=!1),u+1':"",c="',f='viewBox="0 0 '+a+" "+a+'"',g=''+u+c+` -`;return typeof n=="function"&&n(null,g),g}});var KU=v(mf=>{l();var hse=KM(),gS=kU(),$U=jU(),pse=WU();function yS(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!hse())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(u,c){try{let f=gS.create(r,n);u(t(f,e,n))}catch(f){c(f)}})}try{let u=gS.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}mf.create=gS.create;mf.toCanvas=yS.bind(null,$U.render);mf.toDataURL=yS.bind(null,$U.renderToDataURL);mf.toString=yS.bind(null,function(t,e,r){return pse.render(t,r)})});var o4=v(bs=>{"use strict";l();var Sse=bs&&bs.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),s4=bs&&bs.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Sse(e,t,r)};Object.defineProperty(bs,"__esModule",{value:!0});s4(Tu(),bs);s4(f_(),bs)});l();var xse=be(Vm(),1),Nse=be(vE(),1),Ose=be(bE(),1),Dse=be(pt(),1),Pse=be(ha(),1),Rse=be(Yr(),1),Bse=be(Yn(),1),Lse=be(Ih(),1),Fse=be(Dv(),1),Mse=be(qc(),1),Use=be(Wh(),1),x4=be(Ii(),1),jn=be(Ec(),1),N4=be(tc(),1),O4=be(ko(),1),qse=be(Rv(),1),Vse=be(Mv(),1);l();l();var A2=be(Vv(),1);l();l();var $h="elvenjs_state",w2="https://devnet-api.multiversx.com";var Gi="/dapp/init",Kh="devnet",E2="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",v2=["wss://relay.walletconnect.com"],Zt={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var ve={get(t){let e=localStorage.getItem($h);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem($h,JSON.stringify(r))},clear(){localStorage.removeItem($h)}};var Yh=async()=>{let t=A2.ExtensionProvider.getInstance();try{let e=await t.init(),r=ve.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var bS=be(Vv(),1),IS=be(Yl(),1),_S=be(Tu(),1),C4=be(F_(),1),i0=be(Wh(),1);l();var TM=be(Yl(),1);l();l();var Ee=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};l();var SM=(q=>(q.onLoginStart="onLoginStart",q.onLoginSuccess="onLoginSuccess",q.onLoginFailure="onLoginFailure",q.onLogoutStart="onLogoutStart",q.onLogoutSuccess="onLogoutSuccess",q.onLogoutFailure="onLogoutFailure",q.onQrPending="onQrPending",q.onQrLoaded="onQrLoaded",q.onTxStart="onTxStart",q.onTxSent="onTxSent",q.onTxFinalized="onTxFinalized",q.onTxFailure="onTxFailure",q.onSignMsgStart="onSignMsgStart",q.onSignMsgFinalized="onSignMsgFinalized",q.onSignMsgFailure="onSignMsgFailure",q.onQueryStart="onQueryStart",q.onQueryFinalized="onQueryFinalized",q.onQueryFailure="onQueryFailure",q))(SM||{}),M_=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(M_||{}),mie=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(mie||{}),wie=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(wie||{});l();var Et=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Pu=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");Ee.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(ve.clear(),Ee.run("onLogoutSuccess")),e}catch(e){let r=Et(e);console.warn(`Something went wrong trying to logout the user: ${r}`),Ee.run("onLogoutFailure",r)}};l();function Cy(t){return t[Math.floor(Math.random()*t.length)]}var CM=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Pu(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=Cy(t.initOptions.walletConnectV2RelayAddresses),n=new TM.WalletConnectV2Provider(e,Zt[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};l();var By=be(pt(),1),UM=be(xM(),1),qM=be(OM(),1),VM=be(Q_(),1),HM=be(FM(),1),kM=be(Mv(),1),GM=be(MM(),1),jM=be(Vc(),1);var Ly=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||Kh,this.apiUrl=e||Zt[this.chainType]?.apiAddress,this.apiTimeout=n||Zt[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),a=await o.json();if(!o.ok){let u=a?.error||o.status;return clearTimeout(i),Promise.reject(u)}return clearTimeout(i),a}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let a=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),u=await a.json();if(!a.ok){let c=u?.error||a.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),u}catch(a){this.handleApiError(a,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new By.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new UM.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new By.Address(r.sender),receiver:new By.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:h.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:qM.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:VM.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:HM.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new jM.Query({address:e,func:r,args:n,value:i,caller:s}),a=new GM.ContractQueryRequest(o).toHttpRequest(),u=await this.apiPost("query",a);return kM.ContractQueryResponse.fromHttpResponse(u)}catch(o){this.handleApiError(o,"query")}}};l();l();var Fu=()=>new Date().setHours(new Date().getHours()+24),Fy=t=>Date.now()>t;l();var QM=be(pt(),1),zM=be(ha(),1);var Ao=async t=>{let e=ve.get("address"),r=ve.get("expires");if(!(r&&Fy(r))&&e&&t.networkProvider){let i=new QM.Address(e),s=new zM.Account(i);try{let o=await t.networkProvider.getAccount(i),a=await t.networkProvider.getGuardianData(i);ve.set("address",e),ve.set("activeGuardian",a.guarded&&a.activeGuardian?.address?a.activeGuardian.address:""),ve.set("nonce",o.nonce.valueOf()),ve.set("balance",o.balance.toString()),s.update(o)}catch(o){let a=Et(o);console.warn(`Something went wrong trying to synchronize the user account: ${a}`)}}};var WM=async(t,e,r,n="/")=>{let i=await Yh(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(u){let c=Et(u);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:a}=i.account;if(ve.set("loginToken",e),a&&ve.set("signature",a),t.networkProvider&&a)try{let u=await i.getAddress();if(!u)throw new Error("Canceled!");ve.set("address",u),ve.set("loginMethod","browser-extension"),ve.set("expires",Fu()),await Ao(t);let c=r.getToken(u,e,a);return ve.set("accessToken",c),Ee.run("onLoginSuccess"),i}catch(u){throw new Error(`Something went wrong trying to synchronize the user account: ${u?.message}`)}};l();l();var YU=be(KU(),1),JU=be(Yl(),1);var gse=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},yse=t=>{let e=`${E2}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},mse=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},wse=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},mS={},Ese=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",mS[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:mS[t.topic].signal}),r},$y={},vse=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=Ese(t,e);return n.appendChild(s),$y[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:$y[t.topic].signal}),n},Ase=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},bse=t=>{if(!t)return;document.getElementById(t)?.remove()},Ise=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),_se=async t=>t?await YU.default.toString(t,{type:"svg"}):void 0,XU=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await _se(e),o;if(s&&(o=gse(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),Ise()&&i.appendChild(yse(e))),i&&r instanceof JU.WalletConnectV2Provider){let a=r.pairings,u=async f=>{try{f&&(await r.logout({topic:f}),bse(f))}catch(d){let g=Et(d);console.warn(`Something went wrong trying to remove the existing pairing: ${g}`)}finally{$y[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(Ase()),await r.login({approval:d,token:n})}catch(d){let g=Et(d);console.warn(`Something went wrong trying to login the user: ${g}`)}finally{for(let d of Object.values($y))d?.abort();for(let d of Object.values(mS))d?.abort()}};if(a&&a.length>0){let f=mse();i.appendChild(f);let d=wse();f.appendChild(d);for(let g of a){let m=vse(g,u,c);f.appendChild(m)}}}return i};var Ky=be(Yl(),1);var ZU=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=Cy(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof Ky.WalletConnectV2Provider){let u=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();ve.set("address",u),ve.set("loginMethod","mobile"),ve.set("expires",Fu()),await Ao(t),c&&ve.set("signature",c),ve.set("loginToken",e);let f=r.getToken(u,e,c);ve.set("accessToken",f),Ee.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof Ky.WalletConnectV2Provider&&await Pu(t)},onClientEvent:u=>{console.log("wc2 session event: ",u)}},a=new Ky.WalletConnectV2Provider(o,Zt[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(a){t.dappProvider=a,Ee.run("onQrPending"),await a.init();let{uri:u,approval:c}=await a.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${u}&token=${e}`:u;return n&&f&&(s=await XU(n,f,a,e),Ee.run("onQrLoaded")),await a.login({approval:c,token:e}),a}}catch(u){let c=Et(u);console.warn(`Something went wrong trying to login the user: ${c}`),Ee.run("onLoginFailure",c)}};l();var e4=be(Tu(),1);var wS=async(t,e,r,n)=>{let i=new e4.WalletProvider(`${t}${Gi}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return ve.set("loginMethod",Zt[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),ve.set("expires",Fu()),ve.set("loginToken",e),i}catch(a){let u=Et(a);console.warn(`Something went wrong trying to login the user: ${u}`),ve.set("loginMethod",""),Ee.run("onLoginFailure",u)}};l();var Ar=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};l();var t4=be(Tu(),1);var r4=be(F_(),1),ES=async(t,e)=>{let r=Ar("signature"),n=Ar("address"),i=ve.get("address"),s=ve.get("loginToken");if(r&&ve.set("signature",r),n||i){n&&(ve.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new t4.WalletProvider(`${t}${Gi}`);if(r&&e&&n){let u=new r4.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);ve.set("accessToken",u)}return o}};l();var n4=be(ha(),1),i4=be(Ih(),1);var Yy=async(t,e)=>{Ee.run("onTxSent",t),await new i4.TransactionWatcher(e).awaitCompleted(t);let n=t.getSender(),i=new n4.Account(n),s=await e.getAccount(n);i.update(s),ve.set("address",i.address.bech32()),ve.set("balance",i.balance.toString()),Ee.run("onTxFinalized",t)};l();var ku=be(o4(),1),u4=be(Yr(),1);l();var a4=be(ha(),1);var Jy=t=>{let e=t.getSender(),r=new a4.Account(e),n=t.getNonce().valueOf();r.incrementNonce(),ve.set("nonce",n+1)};var c4=async(t,e,r,n)=>{if(Ar(ku.WALLET_PROVIDER_CALLBACK_PARAM)===ku.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=ve.get("activeGuardian"),o=ve.get("loginMethod"),a=Ar("hasWebWalletGuardianSign"),u;if("getTransactionsFromWalletUrl"in t){if(u=t.getTransactionsFromWalletUrl()?.[0],!u)return;o==="web-wallet"&&(u.data=h.Buffer.from(u.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&a&&(u=new ku.WalletProvider(`${r}${Gi}`).getTransactionsFromWalletUrl()?.[0]);if(u){let c=u4.Transaction.fromPlainObject(u);c.setNonce(n),Jy(c);try{Ee.run("onTxStart",c),await e.sendTransaction(c),await Yy(c,e)}catch(f){let g=`Getting transaction information failed! ${Et(f)}`;throw Ee.run("onTxFailure",c,g),new Error(g)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};l();var Xy=be(xc(),1),l4=be(pt(),1),f4=be(Tu(),1);var d4=t=>{let e=ve.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(Xy.TransactionVersion.withTxOptions()),t.setOptions(Xy.TransactionOptions.withOptions(r)),t.setGuardian(l4.Address.fromBech32(e))}return t},h4=async(t,e)=>{let r=new f4.WalletProvider(`${e}${Gi}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},p4=t=>{let e=ve.get("activeGuardian");return!(!ve.get("address")||!e||t.isGuardedTransaction())};l();var g4=()=>{let t=!Ar("walletProviderStatus"),e=Ar("status")==="signed",r=Ar("message"),n=Ar("signature");t&&e&&r&&n&&(Ee.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};l();var AS=be(Yr(),1);l();var y4=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(y4||{}),m4=(a=>(a.handshakeResponse="HANDSHAKE_RESPONSE",a.loginResponse="LOGIN_RESPONSE",a.disconnectResponse="DISCONNECT_RESPONSE",a.cancelResponse="CANCEL_RESPONSE",a.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",a.signMessageResponse="SIGN_MESSAGE_RESPONSE",a.noneResponse="NONE_RESPONSE",a))(m4||{}),vS={...m4,...y4},w4=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))(w4||{}),E4=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(E4||{}),To={...E4,...w4};l();var v4=typeof window<"u"?window:{},A4=()=>v4.ReactNativeWebView?"reactNative":v4.webkit?"ios":"web",Co=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",Zy=t=>Object.prototype.toString.call(t)==="[object String]";l();var e0={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,Co()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:To.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:To.signTransactionsRequest,message:t}),Co())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:To.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:To.signMessageRequest,message:t}),Co())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:To.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:To.logoutRequest}),Co())}};var t0=A4(),r0="message",b4=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=Co()&&t0!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(r0,e),window&&window.addEventListener(r0,e)},Is=class{constructor(){}async logout(){return e0.logout[t0](),new Promise(e=>{e(!0)})}async signMessage(e){try{return e0.signMessage[t0](e),await new Promise((n,i)=>{window.signMessageResponse=(o,a)=>{if(a){i(a),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:a,type:u}=o;if(u===vS.signMessageResponse&&a!=null){let{signedMessage:c,error:f}=a;f?i(f):n(c)}document?.removeEventListener(r0,s)}b4(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return e0.signTransactions[t0](r),await new Promise((i,s)=>{window.transactionsSigned=(a,u)=>{if(a=JSON.parse(a),u){s(u),window.transactionsSigned=null;return}i(a.map(c=>AS.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(a){let{message:u,type:c}=a;if(c===vS.signTransactionsResponse){let{transactions:f,error:d}=u;try{d?s(d):i(f.map(g=>AS.Transaction.fromPlainObject(g)))}catch{s("Unable to sign")}}document&&document.removeEventListener(r0,o)}b4(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};l();l();l();function Cse(t){try{let e=atob(t),r=btoa(e),n=h.Buffer.from(t,"base64").toString(),i=h.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Gu(t){return Cse(t)?atob(t):t}l();var I4=t=>{if(!t||!Zy(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Gu(s)),a=Gu(r);return{ttl:Number(i),extraInfo:o,origin:a,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var _4=t=>{if(!t||!Zy(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Gu(r),o=Gu(n),a=I4(o);if(!a)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let u={...a,address:s,body:o,signature:i};return a.extraInfo?.timestamp||delete u.extraInfo,u}catch{return null}};function S4(t,e){let r=_4(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(ve.set("loginToken",s),ve.set("accessToken",t),ve.set("signature",n),ve.set("address",i),ve.set("loginMethod","x-portal-hub"),e.dappProvider=new Is)}l();var T4=t=>{t.onLoginStart&&Ee.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&Ee.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&Ee.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&Ee.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&Ee.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&Ee.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&Ee.set("onQrPending",t.onQrPending),t.onQrLoaded&&Ee.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&Ee.set("onTxStart",t.onTxStart),t.onTxSent&&Ee.set("onTxSent",t.onTxSent),t.onTxFinalized&&Ee.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&Ee.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&Ee.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&Ee.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&Ee.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&Ee.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&Ee.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&Ee.set("onQueryFailure",t.onQueryFailure)};l();var n0=async t=>{Ee.run("onLoginStart");try{await t(()=>{Ee.run("onLoginSuccess")})}catch(e){let r=Et(e);console.warn(`Something went wrong trying to login the user: ${r}`),Ee.run("onLoginFailure",r)}};var SS=class{static async init(e){let r=ve.get();if(r.expires&&Fy(r.expires)){ve.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:Kh,apiUrl:w2,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:v2,...e},this.networkProvider=new Ly(this.initOptions),T4(this.initOptions);let n=Ar("accessToken");n&&await n0(async s=>{S4(n,this),await Ao(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&Ar("address"))&&r?.loginMethod&&(await n0(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await Yh()),r.loginMethod==="mobile"&&(this.dappProvider=await CM(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new Is),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await ES(Zt[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await ES(Zt[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Ao(this),s()}),this.initOptions?.chainType&&(await c4(this.dappProvider,this.networkProvider,Zt[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),g4()))}static async login(e,r){if(!Object.values(M_).includes(e)){let i="Wrong login method!";throw Ee.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw Ee.run("onLoginFailure",i),new Error(i)}await n0(async()=>{let i=new C4.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await WM(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await ZU(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await wS(Zt[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await wS(Zt[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Pu(this);return this.dappProvider=void 0,e}catch(e){let r=Et(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw Ee.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw Ee.run("onTxFailure",e,n),new Error(n)}let r=d4(e);try{Ee.run("onTxStart",e);let n=ve.get();if(e.setNonce(n.nonce),this.dappProvider instanceof bS.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof IS.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof Is&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof _S.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=p4(r);if(i||Jy(r),i&&this.initOptions?.chainType){await h4(r,Zt[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await Yy(r,this.networkProvider)}}catch(n){let i=Et(n);throw Ee.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw Ee.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw Ee.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(Ee.run("onSignMsgStart",e),this.dappProvider instanceof bS.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new i0.SignableMessage({message:h.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof IS.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new i0.SignableMessage({message:h.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof Is&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof _S.WalletProvider){let s=a=>encodeURIComponent(a).replace(/[!'()*]/g,u=>`%${u.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new i0.SignableMessage({message:h.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=ve.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&Ee.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Et(i);throw Ee.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{Ee.run("onQueryStart",o);let a=await this.networkProvider.queryContract(o);return Ee.run("onQueryFinalized",a),a}catch(a){let u=Et(a);throw Ee.run("onQueryFinalized",o,u),new Error(`Smart contract query failed! ${u}`)}}static{this.storage=ve}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,Ee.clear()}}};var export_Account=Pse.Account;var export_Address=Dse.Address;var export_AddressType=O4.AddressType;var export_AddressValue=O4.AddressValue;var export_BigUIntType=jn.BigUIntType;var export_BigUIntValue=jn.BigUIntValue;var export_BooleanType=N4.BooleanType;var export_BooleanValue=N4.BooleanValue;var export_BytesType=x4.BytesType;var export_BytesValue=x4.BytesValue;var export_ContractFunction=Mse.ContractFunction;var export_ContractQueryResponse=Vse.ContractQueryResponse;var export_GasEstimator=Ose.GasEstimator;var export_QueryArguments=qse.QueryArguments;var export_SignableMessage=Use.SignableMessage;var export_SmartContract=Fse.SmartContract;var export_TokenTransfer=xse.TokenTransfer;var export_Transaction=Rse.Transaction;var export_TransactionPayload=Bse.TransactionPayload;var export_TransactionWatcher=Lse.TransactionWatcher;var export_TransferTransactionsFactory=Nse.TransferTransactionsFactory;var export_U16Type=jn.U16Type;var export_U16Value=jn.U16Value;var export_U32Type=jn.U32Type;var export_U32Value=jn.U32Value;var export_U64Type=jn.U64Type;var export_U64Value=jn.U64Value;var export_U8Type=jn.U8Type;var export_U8Value=jn.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractFunction as ContractFunction,export_ContractQueryResponse as ContractQueryResponse,mie as DappCoreWCV2CustomMethodsEnum,SS as ElvenJS,SM as EventStoreEvents,export_GasEstimator as GasEstimator,M_ as LoginMethodsEnum,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContract as SmartContract,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionPayload as TransactionPayload,export_TransactionWatcher as TransactionWatcher,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,wie as WebWalletUrlParamsEnum}; +var init_xor = __esm({ + "node_modules/uint8arrays/esm/src/xor.js"() { + init_shim(); + init_alloc(); + init_as_uint8array(); + } +}); + +// node_modules/uint8arrays/esm/src/index.js +var src_exports = {}; +__export(src_exports, { + compare: () => compare, + concat: () => concat, + equals: () => equals3, + fromString: () => fromString2, + toString: () => toString2, + xor: () => xor +}); +var init_src2 = __esm({ + "node_modules/uint8arrays/esm/src/index.js"() { + init_shim(); + init_compare(); + init_concat(); + init_equals(); + init_from_string(); + init_to_string(); + init_xor(); + } +}); + +// node_modules/@walletconnect/relay-api/dist/index.es.js +var index_es_exports3 = {}; +__export(index_es_exports3, { + RELAY_JSONRPC: () => C2, + isPublishMethod: () => c3, + isPublishParams: () => h3, + isPublishRequest: () => P, + isSubscribeMethod: () => b2, + isSubscribeParams: () => a, + isSubscribeRequest: () => R, + isSubscriptionMethod: () => m2, + isSubscriptionParams: () => d2, + isSubscriptionRequest: () => S2, + isUnsubscribeMethod: () => o, + isUnsubscribeParams: () => p2, + isUnsubscribeRequest: () => _3, + parsePublishRequest: () => q, + parseSubscribeRequest: () => g2, + parseSubscriptionRequest: () => k3, + parseUnsubscribeRequest: () => E3 +}); +function e(s2, r, i2 = "string") { + if (!s2[r] || typeof s2[r] !== i2) + throw new Error(`Missing or invalid "${r}" param`); +} +function l3(s2, r) { + let i2 = true; + return r.forEach((t) => { + t in s2 || (i2 = false); + }), i2; +} +function f2(s2, r) { + return Array.isArray(s2) ? s2.length === r : Object.keys(s2).length === r; +} +function w2(s2, r) { + return Array.isArray(s2) ? s2.length >= r : Object.keys(s2).length >= r; +} +function u(s2, r, i2) { + return (i2.length ? w2(s2, r.length) : f2(s2, r.length)) ? l3(s2, r) : false; +} +function n2(s2, r, i2 = "_") { + const t = s2.split(i2); + return t[t.length - 1].trim().toLowerCase() === r.trim().toLowerCase(); +} +function R(s2) { + return b2(s2.method) && a(s2.params); +} +function b2(s2) { + return n2(s2, "subscribe"); +} +function a(s2) { + return u(s2, ["topic"], []); +} +function P(s2) { + return c3(s2.method) && h3(s2.params); +} +function c3(s2) { + return n2(s2, "publish"); +} +function h3(s2) { + return u(s2, ["message", "topic", "ttl"], ["prompt", "tag"]); +} +function _3(s2) { + return o(s2.method) && p2(s2.params); +} +function o(s2) { + return n2(s2, "unsubscribe"); +} +function p2(s2) { + return u(s2, ["id", "topic"], []); +} +function S2(s2) { + return m2(s2.method) && d2(s2.params); +} +function m2(s2) { + return n2(s2, "subscription"); +} +function d2(s2) { + return u(s2, ["id", "data"], []); +} +function g2(s2) { + if (!b2(s2.method)) + throw new Error("JSON-RPC Request has invalid subscribe method"); + if (!a(s2.params)) + throw new Error("JSON-RPC Request has invalid subscribe params"); + const r = s2.params; + return e(r, "topic"), r; +} +function q(s2) { + if (!c3(s2.method)) + throw new Error("JSON-RPC Request has invalid publish method"); + if (!h3(s2.params)) + throw new Error("JSON-RPC Request has invalid publish params"); + const r = s2.params; + return e(r, "topic"), e(r, "message"), e(r, "ttl", "number"), r; +} +function E3(s2) { + if (!o(s2.method)) + throw new Error("JSON-RPC Request has invalid unsubscribe method"); + if (!p2(s2.params)) + throw new Error("JSON-RPC Request has invalid unsubscribe params"); + const r = s2.params; + return e(r, "id"), r; +} +function k3(s2) { + if (!m2(s2.method)) + throw new Error("JSON-RPC Request has invalid subscription method"); + if (!d2(s2.params)) + throw new Error("JSON-RPC Request has invalid subscription params"); + const r = s2.params; + return e(r, "id"), e(r, "data"), r; +} +var C2; +var init_index_es3 = __esm({ + "node_modules/@walletconnect/relay-api/dist/index.es.js"() { + init_shim(); + C2 = { waku: { publish: "waku_publish", batchPublish: "waku_batchPublish", subscribe: "waku_subscribe", batchSubscribe: "waku_batchSubscribe", subscription: "waku_subscription", unsubscribe: "waku_unsubscribe", batchUnsubscribe: "waku_batchUnsubscribe", batchFetchMessages: "waku_batchFetchMessages" }, irn: { publish: "irn_publish", batchPublish: "irn_batchPublish", subscribe: "irn_subscribe", batchSubscribe: "irn_batchSubscribe", subscription: "irn_subscription", unsubscribe: "irn_unsubscribe", batchUnsubscribe: "irn_batchUnsubscribe", batchFetchMessages: "irn_batchFetchMessages" }, iridium: { publish: "iridium_publish", batchPublish: "iridium_batchPublish", subscribe: "iridium_subscribe", batchSubscribe: "iridium_batchSubscribe", subscription: "iridium_subscription", unsubscribe: "iridium_unsubscribe", batchUnsubscribe: "iridium_batchUnsubscribe", batchFetchMessages: "iridium_batchFetchMessages" } }; + } +}); + +// node_modules/@walletconnect/utils/dist/index.cjs.js +var require_index_cjs2 = __commonJS({ + "node_modules/@walletconnect/utils/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var Ro = require_detect_browser(); + var tr = require_cjs(); + var er = require_cjs3(); + var Co = require_cjs4(); + var Oo = require_query_string(); + var fn = require_chacha20poly1305(); + var Po = require_hkdf(); + var on = require_random(); + var ci = require_sha256(); + var To = require_x25519(); + var Rt = (init_src2(), __toCommonJS(src_exports)); + var Fo = (init_index_es3(), __toCommonJS(index_es_exports3)); + function sn(e2) { + if (e2 && e2.__esModule) + return e2; + var t = /* @__PURE__ */ Object.create(null); + return e2 && Object.keys(e2).forEach(function(r) { + if (r !== "default") { + var i2 = Object.getOwnPropertyDescriptor(e2, r); + Object.defineProperty(t, r, i2.get ? i2 : { enumerable: true, get: function() { + return e2[r]; + } }); + } + }), t.default = e2, Object.freeze(t); + } + var Ir = sn(Oo); + var an = sn(To); + var _r = ":"; + function un(e2) { + const [t, r] = e2.split(_r); + return { namespace: t, reference: r }; + } + function hn(e2) { + const { namespace: t, reference: r } = e2; + return [t, r].join(_r); + } + function li(e2) { + const [t, r, i2] = e2.split(_r); + return { namespace: t, reference: r, address: i2 }; + } + function cn(e2) { + const { namespace: t, reference: r, address: i2 } = e2; + return [t, r, i2].join(_r); + } + function di(e2, t) { + const r = []; + return e2.forEach((i2) => { + const n3 = t(i2); + r.includes(n3) || r.push(n3); + }), r; + } + function ln(e2) { + const { address: t } = li(e2); + return t; + } + function dn(e2) { + const { namespace: t, reference: r } = li(e2); + return hn({ namespace: t, reference: r }); + } + function Do(e2, t) { + const { namespace: r, reference: i2 } = un(t); + return cn({ namespace: r, reference: i2, address: e2 }); + } + function Uo(e2) { + return di(e2, ln); + } + function pn(e2) { + return di(e2, dn); + } + function ko(e2, t = []) { + const r = []; + return Object.keys(e2).forEach((i2) => { + if (t.length && !t.includes(i2)) + return; + const n3 = e2[i2]; + r.push(...n3.accounts); + }), r; + } + function qo(e2, t = []) { + const r = []; + return Object.keys(e2).forEach((i2) => { + if (t.length && !t.includes(i2)) + return; + const n3 = e2[i2]; + r.push(...pn(n3.accounts)); + }), r; + } + function Ko(e2, t = []) { + const r = []; + return Object.keys(e2).forEach((i2) => { + if (t.length && !t.includes(i2)) + return; + const n3 = e2[i2]; + r.push(...Br(i2, n3)); + }), r; + } + function Br(e2, t) { + return e2.includes(":") ? [e2] : t.chains || []; + } + var Ho = Object.defineProperty; + var vn = Object.getOwnPropertySymbols; + var Lo = Object.prototype.hasOwnProperty; + var zo = Object.prototype.propertyIsEnumerable; + var gn = (e2, t, r) => t in e2 ? Ho(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var mn = (e2, t) => { + for (var r in t || (t = {})) + Lo.call(t, r) && gn(e2, r, t[r]); + if (vn) + for (var r of vn(t)) + zo.call(t, r) && gn(e2, r, t[r]); + return e2; + }; + var An = "ReactNative"; + var Kt = { reactNative: "react-native", node: "node", browser: "browser", unknown: "unknown" }; + var Rr = " "; + var jo = ":"; + var bn = "/"; + var pi = 2; + var Vo = 1e3; + var yn = "js"; + function vi() { + return typeof import_process.default < "u" && typeof import_process.default.versions < "u" && typeof import_process.default.versions.node < "u"; + } + function rr() { + return !er.getDocument() && !!er.getNavigator() && navigator.product === An; + } + function vr() { + return !vi() && !!er.getNavigator() && !!er.getDocument(); + } + function Ge() { + return rr() ? Kt.reactNative : vi() ? Kt.node : vr() ? Kt.browser : Kt.unknown; + } + function Qo() { + var e2; + try { + return rr() && typeof global < "u" && typeof (global == null ? void 0 : global.Application) < "u" ? (e2 = global.Application) == null ? void 0 : e2.applicationId : void 0; + } catch { + return; + } + } + function wn(e2, t) { + let r = Ir.parse(e2); + return r = mn(mn({}, r), t), e2 = Ir.stringify(r), e2; + } + function Jo() { + return Co.getWindowMetadata() || { name: "", description: "", url: "", icons: [""] }; + } + function Yo(e2, t) { + var r; + const i2 = Ge(), n3 = { protocol: e2, version: t, env: i2 }; + return i2 === "browser" && (n3.host = ((r = er.getLocation()) == null ? void 0 : r.host) || "unknown"), n3; + } + function xn() { + if (Ge() === Kt.reactNative && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u") { + const { OS: r, Version: i2 } = global.Platform; + return [r, i2].join("-"); + } + const e2 = Ro.detect(); + if (e2 === null) + return "unknown"; + const t = e2.os ? e2.os.replace(" ", "").toLowerCase() : "unknown"; + return e2.type === "browser" ? [t, e2.name, e2.version].join("-") : [t, e2.version].join("-"); + } + function Mn() { + var e2; + const t = Ge(); + return t === Kt.browser ? [t, ((e2 = er.getLocation()) == null ? void 0 : e2.host) || "unknown"].join(":") : t; + } + function En(e2, t, r) { + const i2 = xn(), n3 = Mn(); + return [[e2, t].join("-"), [yn, r].join("-"), i2, n3].join("/"); + } + function Go({ protocol: e2, version: t, relayUrl: r, sdkVersion: i2, auth: n3, projectId: o2, useOnCloseEvent: h5, bundleId: p3 }) { + const b4 = r.split("?"), g3 = En(e2, t, i2), w4 = { auth: n3, ua: g3, projectId: o2, useOnCloseEvent: h5 || void 0, origin: p3 || void 0 }, y4 = wn(b4[1] || "", w4); + return b4[0] + "?" + y4; + } + function Wo(e2) { + let t = (e2.match(/^[^:]+(?=:\/\/)/gi) || [])[0]; + const r = typeof t < "u" ? e2.split("://")[1] : e2; + return t = t === "wss" ? "https" : "http", [t, r].join("://"); + } + function Xo(e2, t, r) { + if (!e2[t] || typeof e2[t] !== r) + throw new Error(`Missing or invalid "${t}" param`); + } + function Sn(e2, t = pi) { + return Nn(e2.split(bn), t); + } + function Zo(e2) { + return Sn(e2).join(Rr); + } + function Ie(e2, t) { + return e2.filter((r) => t.includes(r)).length === e2.length; + } + function Nn(e2, t = pi) { + return e2.slice(Math.max(e2.length - t, 0)); + } + function $o(e2) { + return Object.fromEntries(e2.entries()); + } + function ts(e2) { + return new Map(Object.entries(e2)); + } + function es(e2, t) { + const r = {}; + return Object.keys(e2).forEach((i2) => { + r[i2] = t(e2[i2]); + }), r; + } + var rs = (e2) => e2; + function In(e2) { + return e2.trim().replace(/^\w/, (t) => t.toUpperCase()); + } + function is(e2) { + return e2.split(Rr).map((t) => In(t)).join(Rr); + } + function ns(e2 = tr.FIVE_MINUTES, t) { + const r = tr.toMiliseconds(e2 || tr.FIVE_MINUTES); + let i2, n3, o2; + return { resolve: (h5) => { + o2 && i2 && (clearTimeout(o2), i2(h5)); + }, reject: (h5) => { + o2 && n3 && (clearTimeout(o2), n3(h5)); + }, done: () => new Promise((h5, p3) => { + o2 = setTimeout(() => { + p3(new Error(t)); + }, r), i2 = h5, n3 = p3; + }) }; + } + function fs(e2, t, r) { + return new Promise(async (i2, n3) => { + const o2 = setTimeout(() => n3(new Error(r)), t); + try { + const h5 = await e2; + i2(h5); + } catch (h5) { + n3(h5); + } + clearTimeout(o2); + }); + } + function gi(e2, t) { + if (typeof t == "string" && t.startsWith(`${e2}:`)) + return t; + if (e2.toLowerCase() === "topic") { + if (typeof t != "string") + throw new Error('Value must be "string" for expirer target type: topic'); + return `topic:${t}`; + } else if (e2.toLowerCase() === "id") { + if (typeof t != "number") + throw new Error('Value must be "number" for expirer target type: id'); + return `id:${t}`; + } + throw new Error(`Unknown expirer target type: ${e2}`); + } + function os(e2) { + return gi("topic", e2); + } + function ss(e2) { + return gi("id", e2); + } + function as(e2) { + const [t, r] = e2.split(":"), i2 = { id: void 0, topic: void 0 }; + if (t === "topic" && typeof r == "string") + i2.topic = r; + else if (t === "id" && Number.isInteger(Number(r))) + i2.id = Number(r); + else + throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`); + return i2; + } + function us(e2, t) { + return tr.fromMiliseconds((t || Date.now()) + tr.toMiliseconds(e2)); + } + function hs(e2) { + return Date.now() >= tr.toMiliseconds(e2); + } + function cs(e2, t) { + return `${e2}${t ? `:${t}` : ""}`; + } + function ge(e2 = [], t = []) { + return [.../* @__PURE__ */ new Set([...e2, ...t])]; + } + async function ls2({ id: e2, topic: t, wcDeepLink: r }) { + try { + if (!r) + return; + const i2 = typeof r == "string" ? JSON.parse(r) : r; + let n3 = i2?.href; + if (typeof n3 != "string") + return; + n3.endsWith("/") && (n3 = n3.slice(0, -1)); + const o2 = `${n3}/wc?requestId=${e2}&sessionTopic=${t}`, h5 = Ge(); + h5 === Kt.browser ? o2.startsWith("https://") || o2.startsWith("http://") ? window.open(o2, "_blank", "noreferrer noopener") : window.open(o2, "_self", "noreferrer noopener") : h5 === Kt.reactNative && typeof (global == null ? void 0 : global.Linking) < "u" && await global.Linking.openURL(o2); + } catch (i2) { + console.error(i2); + } + } + async function ds(e2, t) { + try { + return await e2.getItem(t) || (vr() ? localStorage.getItem(t) : void 0); + } catch (r) { + console.error(r); + } + } + function mi(e2, t) { + return e2.filter((r) => t.includes(r)); + } + var _n = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; + function ps(e2) { + var t = e2.default; + if (typeof t == "function") { + var r = function() { + return t.apply(this, arguments); + }; + r.prototype = t.prototype; + } else + r = {}; + return Object.defineProperty(r, "__esModule", { value: true }), Object.keys(e2).forEach(function(i2) { + var n3 = Object.getOwnPropertyDescriptor(e2, i2); + Object.defineProperty(r, i2, n3.get ? n3 : { enumerable: true, get: function() { + return e2[i2]; + } }); + }), r; + } + var Bn = { exports: {} }; + (function(e2) { + (function() { + var t = "input is invalid type", r = "finalize already called", i2 = typeof window == "object", n3 = i2 ? window : {}; + n3.JS_SHA3_NO_WINDOW && (i2 = false); + var o2 = !i2 && typeof self == "object", h5 = !n3.JS_SHA3_NO_NODE_JS && typeof import_process.default == "object" && import_process.default.versions && import_process.default.versions.node; + h5 ? n3 = _n : o2 && (n3 = self); + var p3 = !n3.JS_SHA3_NO_COMMON_JS && true && e2.exports, b4 = !n3.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer < "u", g3 = "0123456789abcdef".split(""), w4 = [31, 7936, 2031616, 520093696], y4 = [4, 1024, 262144, 67108864], S4 = [1, 256, 65536, 16777216], I2 = [6, 1536, 393216, 100663296], N10 = [0, 8, 16, 24], R2 = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648], F = [224, 256, 384, 512], U2 = [128, 256], Q = ["hex", "buffer", "arrayBuffer", "array", "digest"], Bt = { 128: 168, 256: 136 }; + (n3.JS_SHA3_NO_NODE_JS || !Array.isArray) && (Array.isArray = function(u3) { + return Object.prototype.toString.call(u3) === "[object Array]"; + }), b4 && (n3.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView) && (ArrayBuffer.isView = function(u3) { + return typeof u3 == "object" && u3.buffer && u3.buffer.constructor === ArrayBuffer; + }); + for (var J = function(u3, E4, _4) { + return function(B2) { + return new s2(u3, E4, u3).update(B2)[_4](); + }; + }, H = function(u3, E4, _4) { + return function(B2, C3) { + return new s2(u3, E4, C3).update(B2)[_4](); + }; + }, L2 = function(u3, E4, _4) { + return function(B2, C3, D2, P2) { + return f4["cshake" + u3].update(B2, C3, D2, P2)[_4](); + }; + }, Tt = function(u3, E4, _4) { + return function(B2, C3, D2, P2) { + return f4["kmac" + u3].update(B2, C3, D2, P2)[_4](); + }; + }, W = function(u3, E4, _4, B2) { + for (var C3 = 0; C3 < Q.length; ++C3) { + var D2 = Q[C3]; + u3[D2] = E4(_4, B2, D2); + } + return u3; + }, Ot = function(u3, E4) { + var _4 = J(u3, E4, "hex"); + return _4.create = function() { + return new s2(u3, E4, u3); + }, _4.update = function(B2) { + return _4.create().update(B2); + }, W(_4, J, u3, E4); + }, Gt = function(u3, E4) { + var _4 = H(u3, E4, "hex"); + return _4.create = function(B2) { + return new s2(u3, E4, B2); + }, _4.update = function(B2, C3) { + return _4.create(C3).update(B2); + }, W(_4, H, u3, E4); + }, Y = function(u3, E4) { + var _4 = Bt[u3], B2 = L2(u3, E4, "hex"); + return B2.create = function(C3, D2, P2) { + return !D2 && !P2 ? f4["shake" + u3].create(C3) : new s2(u3, E4, C3).bytepad([D2, P2], _4); + }, B2.update = function(C3, D2, P2, O3) { + return B2.create(D2, P2, O3).update(C3); + }, W(B2, L2, u3, E4); + }, Wt = function(u3, E4) { + var _4 = Bt[u3], B2 = Tt(u3, E4, "hex"); + return B2.create = function(C3, D2, P2) { + return new v2(u3, E4, D2).bytepad(["KMAC", P2], _4).bytepad([C3], _4); + }, B2.update = function(C3, D2, P2, O3) { + return B2.create(C3, P2, O3).update(D2); + }, W(B2, Tt, u3, E4); + }, A2 = [{ name: "keccak", padding: S4, bits: F, createMethod: Ot }, { name: "sha3", padding: I2, bits: F, createMethod: Ot }, { name: "shake", padding: w4, bits: U2, createMethod: Gt }, { name: "cshake", padding: y4, bits: U2, createMethod: Y }, { name: "kmac", padding: y4, bits: U2, createMethod: Wt }], f4 = {}, a3 = [], c4 = 0; c4 < A2.length; ++c4) + for (var d3 = A2[c4], m3 = d3.bits, x3 = 0; x3 < m3.length; ++x3) { + var M = d3.name + "_" + m3[x3]; + if (a3.push(M), f4[M] = d3.createMethod(m3[x3], d3.padding), d3.name !== "sha3") { + var l4 = d3.name + m3[x3]; + a3.push(l4), f4[l4] = f4[M]; + } + } + function s2(u3, E4, _4) { + this.blocks = [], this.s = [], this.padding = E4, this.outputBits = _4, this.reset = true, this.finalized = false, this.block = 0, this.start = 0, this.blockCount = 1600 - (u3 << 1) >> 5, this.byteCount = this.blockCount << 2, this.outputBlocks = _4 >> 5, this.extraBytes = (_4 & 31) >> 3; + for (var B2 = 0; B2 < 50; ++B2) + this.s[B2] = 0; + } + s2.prototype.update = function(u3) { + if (this.finalized) + throw new Error(r); + var E4, _4 = typeof u3; + if (_4 !== "string") { + if (_4 === "object") { + if (u3 === null) + throw new Error(t); + if (b4 && u3.constructor === ArrayBuffer) + u3 = new Uint8Array(u3); + else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) + throw new Error(t); + } else + throw new Error(t); + E4 = true; + } + for (var B2 = this.blocks, C3 = this.byteCount, D2 = u3.length, P2 = this.blockCount, O3 = 0, Ct = this.s, T2, q2; O3 < D2; ) { + if (this.reset) + for (this.reset = false, B2[0] = this.block, T2 = 1; T2 < P2 + 1; ++T2) + B2[T2] = 0; + if (E4) + for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) + B2[T2 >> 2] |= u3[O3] << N10[T2++ & 3]; + else + for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) + q2 = u3.charCodeAt(O3), q2 < 128 ? B2[T2 >> 2] |= q2 << N10[T2++ & 3] : q2 < 2048 ? (B2[T2 >> 2] |= (192 | q2 >> 6) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : q2 < 55296 || q2 >= 57344 ? (B2[T2 >> 2] |= (224 | q2 >> 12) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : (q2 = 65536 + ((q2 & 1023) << 10 | u3.charCodeAt(++O3) & 1023), B2[T2 >> 2] |= (240 | q2 >> 18) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 12 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]); + if (this.lastByteIndex = T2, T2 >= C3) { + for (this.start = T2 - C3, this.block = B2[P2], T2 = 0; T2 < P2; ++T2) + Ct[T2] ^= B2[T2]; + k4(Ct), this.reset = true; + } else + this.start = T2; + } + return this; + }, s2.prototype.encode = function(u3, E4) { + var _4 = u3 & 255, B2 = 1, C3 = [_4]; + for (u3 = u3 >> 8, _4 = u3 & 255; _4 > 0; ) + C3.unshift(_4), u3 = u3 >> 8, _4 = u3 & 255, ++B2; + return E4 ? C3.push(B2) : C3.unshift(B2), this.update(C3), C3.length; + }, s2.prototype.encodeString = function(u3) { + var E4, _4 = typeof u3; + if (_4 !== "string") { + if (_4 === "object") { + if (u3 === null) + throw new Error(t); + if (b4 && u3.constructor === ArrayBuffer) + u3 = new Uint8Array(u3); + else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) + throw new Error(t); + } else + throw new Error(t); + E4 = true; + } + var B2 = 0, C3 = u3.length; + if (E4) + B2 = C3; + else + for (var D2 = 0; D2 < u3.length; ++D2) { + var P2 = u3.charCodeAt(D2); + P2 < 128 ? B2 += 1 : P2 < 2048 ? B2 += 2 : P2 < 55296 || P2 >= 57344 ? B2 += 3 : (P2 = 65536 + ((P2 & 1023) << 10 | u3.charCodeAt(++D2) & 1023), B2 += 4); + } + return B2 += this.encode(B2 * 8), this.update(u3), B2; + }, s2.prototype.bytepad = function(u3, E4) { + for (var _4 = this.encode(E4), B2 = 0; B2 < u3.length; ++B2) + _4 += this.encodeString(u3[B2]); + var C3 = E4 - _4 % E4, D2 = []; + return D2.length = C3, this.update(D2), this; + }, s2.prototype.finalize = function() { + if (!this.finalized) { + this.finalized = true; + var u3 = this.blocks, E4 = this.lastByteIndex, _4 = this.blockCount, B2 = this.s; + if (u3[E4 >> 2] |= this.padding[E4 & 3], this.lastByteIndex === this.byteCount) + for (u3[0] = u3[_4], E4 = 1; E4 < _4 + 1; ++E4) + u3[E4] = 0; + for (u3[_4 - 1] |= 2147483648, E4 = 0; E4 < _4; ++E4) + B2[E4] ^= u3[E4]; + k4(B2); + } + }, s2.prototype.toString = s2.prototype.hex = function() { + this.finalize(); + for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = "", O3; D2 < _4; ) { + for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) + O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15] + g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15] + g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15] + g3[O3 >> 28 & 15] + g3[O3 >> 24 & 15]; + D2 % u3 === 0 && (k4(E4), C3 = 0); + } + return B2 && (O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15], B2 > 1 && (P2 += g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15]), B2 > 2 && (P2 += g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15])), P2; + }, s2.prototype.arrayBuffer = function() { + this.finalize(); + var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = this.outputBits >> 3, O3; + B2 ? O3 = new ArrayBuffer(_4 + 1 << 2) : O3 = new ArrayBuffer(P2); + for (var Ct = new Uint32Array(O3); D2 < _4; ) { + for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) + Ct[D2] = E4[C3]; + D2 % u3 === 0 && k4(E4); + } + return B2 && (Ct[C3] = E4[C3], O3 = O3.slice(0, P2)), O3; + }, s2.prototype.buffer = s2.prototype.arrayBuffer, s2.prototype.digest = s2.prototype.array = function() { + this.finalize(); + for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = [], O3, Ct; D2 < _4; ) { + for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) + O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, P2[O3 + 1] = Ct >> 8 & 255, P2[O3 + 2] = Ct >> 16 & 255, P2[O3 + 3] = Ct >> 24 & 255; + D2 % u3 === 0 && k4(E4); + } + return B2 && (O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, B2 > 1 && (P2[O3 + 1] = Ct >> 8 & 255), B2 > 2 && (P2[O3 + 2] = Ct >> 16 & 255)), P2; + }; + function v2(u3, E4, _4) { + s2.call(this, u3, E4, _4); + } + v2.prototype = new s2(), v2.prototype.finalize = function() { + return this.encode(this.outputBits, true), s2.prototype.finalize.call(this); + }; + var k4 = function(u3) { + var E4, _4, B2, C3, D2, P2, O3, Ct, T2, q2, Pe, X, Z, Te, $, tt, Fe, et, rt, De, it, nt, Ue, ft, ot, ke, st, at, qe, ut, ht, Ke, ct, lt, He, dt, pt, Le, vt, gt, ze, mt, At, je, bt, yt, Ve, wt, xt, Qe, Mt, Et, Je, St, Nt, Ye, It, _t, xe, Me, Ee, Se, Ne; + for (B2 = 0; B2 < 48; B2 += 2) + C3 = u3[0] ^ u3[10] ^ u3[20] ^ u3[30] ^ u3[40], D2 = u3[1] ^ u3[11] ^ u3[21] ^ u3[31] ^ u3[41], P2 = u3[2] ^ u3[12] ^ u3[22] ^ u3[32] ^ u3[42], O3 = u3[3] ^ u3[13] ^ u3[23] ^ u3[33] ^ u3[43], Ct = u3[4] ^ u3[14] ^ u3[24] ^ u3[34] ^ u3[44], T2 = u3[5] ^ u3[15] ^ u3[25] ^ u3[35] ^ u3[45], q2 = u3[6] ^ u3[16] ^ u3[26] ^ u3[36] ^ u3[46], Pe = u3[7] ^ u3[17] ^ u3[27] ^ u3[37] ^ u3[47], X = u3[8] ^ u3[18] ^ u3[28] ^ u3[38] ^ u3[48], Z = u3[9] ^ u3[19] ^ u3[29] ^ u3[39] ^ u3[49], E4 = X ^ (P2 << 1 | O3 >>> 31), _4 = Z ^ (O3 << 1 | P2 >>> 31), u3[0] ^= E4, u3[1] ^= _4, u3[10] ^= E4, u3[11] ^= _4, u3[20] ^= E4, u3[21] ^= _4, u3[30] ^= E4, u3[31] ^= _4, u3[40] ^= E4, u3[41] ^= _4, E4 = C3 ^ (Ct << 1 | T2 >>> 31), _4 = D2 ^ (T2 << 1 | Ct >>> 31), u3[2] ^= E4, u3[3] ^= _4, u3[12] ^= E4, u3[13] ^= _4, u3[22] ^= E4, u3[23] ^= _4, u3[32] ^= E4, u3[33] ^= _4, u3[42] ^= E4, u3[43] ^= _4, E4 = P2 ^ (q2 << 1 | Pe >>> 31), _4 = O3 ^ (Pe << 1 | q2 >>> 31), u3[4] ^= E4, u3[5] ^= _4, u3[14] ^= E4, u3[15] ^= _4, u3[24] ^= E4, u3[25] ^= _4, u3[34] ^= E4, u3[35] ^= _4, u3[44] ^= E4, u3[45] ^= _4, E4 = Ct ^ (X << 1 | Z >>> 31), _4 = T2 ^ (Z << 1 | X >>> 31), u3[6] ^= E4, u3[7] ^= _4, u3[16] ^= E4, u3[17] ^= _4, u3[26] ^= E4, u3[27] ^= _4, u3[36] ^= E4, u3[37] ^= _4, u3[46] ^= E4, u3[47] ^= _4, E4 = q2 ^ (C3 << 1 | D2 >>> 31), _4 = Pe ^ (D2 << 1 | C3 >>> 31), u3[8] ^= E4, u3[9] ^= _4, u3[18] ^= E4, u3[19] ^= _4, u3[28] ^= E4, u3[29] ^= _4, u3[38] ^= E4, u3[39] ^= _4, u3[48] ^= E4, u3[49] ^= _4, Te = u3[0], $ = u3[1], yt = u3[11] << 4 | u3[10] >>> 28, Ve = u3[10] << 4 | u3[11] >>> 28, at = u3[20] << 3 | u3[21] >>> 29, qe = u3[21] << 3 | u3[20] >>> 29, Me = u3[31] << 9 | u3[30] >>> 23, Ee = u3[30] << 9 | u3[31] >>> 23, mt = u3[40] << 18 | u3[41] >>> 14, At = u3[41] << 18 | u3[40] >>> 14, lt = u3[2] << 1 | u3[3] >>> 31, He = u3[3] << 1 | u3[2] >>> 31, tt = u3[13] << 12 | u3[12] >>> 20, Fe = u3[12] << 12 | u3[13] >>> 20, wt = u3[22] << 10 | u3[23] >>> 22, xt = u3[23] << 10 | u3[22] >>> 22, ut = u3[33] << 13 | u3[32] >>> 19, ht = u3[32] << 13 | u3[33] >>> 19, Se = u3[42] << 2 | u3[43] >>> 30, Ne = u3[43] << 2 | u3[42] >>> 30, St = u3[5] << 30 | u3[4] >>> 2, Nt = u3[4] << 30 | u3[5] >>> 2, dt = u3[14] << 6 | u3[15] >>> 26, pt = u3[15] << 6 | u3[14] >>> 26, et = u3[25] << 11 | u3[24] >>> 21, rt = u3[24] << 11 | u3[25] >>> 21, Qe = u3[34] << 15 | u3[35] >>> 17, Mt = u3[35] << 15 | u3[34] >>> 17, Ke = u3[45] << 29 | u3[44] >>> 3, ct = u3[44] << 29 | u3[45] >>> 3, ft = u3[6] << 28 | u3[7] >>> 4, ot = u3[7] << 28 | u3[6] >>> 4, Ye = u3[17] << 23 | u3[16] >>> 9, It = u3[16] << 23 | u3[17] >>> 9, Le = u3[26] << 25 | u3[27] >>> 7, vt = u3[27] << 25 | u3[26] >>> 7, De = u3[36] << 21 | u3[37] >>> 11, it = u3[37] << 21 | u3[36] >>> 11, Et = u3[47] << 24 | u3[46] >>> 8, Je = u3[46] << 24 | u3[47] >>> 8, je = u3[8] << 27 | u3[9] >>> 5, bt = u3[9] << 27 | u3[8] >>> 5, ke = u3[18] << 20 | u3[19] >>> 12, st = u3[19] << 20 | u3[18] >>> 12, _t = u3[29] << 7 | u3[28] >>> 25, xe = u3[28] << 7 | u3[29] >>> 25, gt = u3[38] << 8 | u3[39] >>> 24, ze = u3[39] << 8 | u3[38] >>> 24, nt = u3[48] << 14 | u3[49] >>> 18, Ue = u3[49] << 14 | u3[48] >>> 18, u3[0] = Te ^ ~tt & et, u3[1] = $ ^ ~Fe & rt, u3[10] = ft ^ ~ke & at, u3[11] = ot ^ ~st & qe, u3[20] = lt ^ ~dt & Le, u3[21] = He ^ ~pt & vt, u3[30] = je ^ ~yt & wt, u3[31] = bt ^ ~Ve & xt, u3[40] = St ^ ~Ye & _t, u3[41] = Nt ^ ~It & xe, u3[2] = tt ^ ~et & De, u3[3] = Fe ^ ~rt & it, u3[12] = ke ^ ~at & ut, u3[13] = st ^ ~qe & ht, u3[22] = dt ^ ~Le & gt, u3[23] = pt ^ ~vt & ze, u3[32] = yt ^ ~wt & Qe, u3[33] = Ve ^ ~xt & Mt, u3[42] = Ye ^ ~_t & Me, u3[43] = It ^ ~xe & Ee, u3[4] = et ^ ~De & nt, u3[5] = rt ^ ~it & Ue, u3[14] = at ^ ~ut & Ke, u3[15] = qe ^ ~ht & ct, u3[24] = Le ^ ~gt & mt, u3[25] = vt ^ ~ze & At, u3[34] = wt ^ ~Qe & Et, u3[35] = xt ^ ~Mt & Je, u3[44] = _t ^ ~Me & Se, u3[45] = xe ^ ~Ee & Ne, u3[6] = De ^ ~nt & Te, u3[7] = it ^ ~Ue & $, u3[16] = ut ^ ~Ke & ft, u3[17] = ht ^ ~ct & ot, u3[26] = gt ^ ~mt & lt, u3[27] = ze ^ ~At & He, u3[36] = Qe ^ ~Et & je, u3[37] = Mt ^ ~Je & bt, u3[46] = Me ^ ~Se & St, u3[47] = Ee ^ ~Ne & Nt, u3[8] = nt ^ ~Te & tt, u3[9] = Ue ^ ~$ & Fe, u3[18] = Ke ^ ~ft & ke, u3[19] = ct ^ ~ot & st, u3[28] = mt ^ ~lt & dt, u3[29] = At ^ ~He & pt, u3[38] = Et ^ ~je & yt, u3[39] = Je ^ ~bt & Ve, u3[48] = Se ^ ~St & Ye, u3[49] = Ne ^ ~Nt & It, u3[0] ^= R2[B2], u3[1] ^= R2[B2 + 1]; + }; + if (p3) + e2.exports = f4; + else + for (c4 = 0; c4 < a3.length; ++c4) + n3[a3[c4]] = f4[a3[c4]]; + })(); + })(Bn); + var vs = Bn.exports; + var gs = "logger/5.7.0"; + var Rn = false; + var Cn = false; + var Cr = { debug: 1, default: 2, info: 2, warning: 3, error: 4, off: 5 }; + var On = Cr.default; + var Ai = null; + function ms() { + try { + const e2 = []; + if (["NFD", "NFC", "NFKD", "NFKC"].forEach((t) => { + try { + if ("test".normalize(t) !== "test") + throw new Error("bad normalize"); + } catch { + e2.push(t); + } + }), e2.length) + throw new Error("missing " + e2.join(", ")); + if (String.fromCharCode(233).normalize("NFD") !== String.fromCharCode(101, 769)) + throw new Error("broken implementation"); + } catch (e2) { + return e2.message; + } + return null; + } + var Pn = ms(); + var bi; + (function(e2) { + e2.DEBUG = "DEBUG", e2.INFO = "INFO", e2.WARNING = "WARNING", e2.ERROR = "ERROR", e2.OFF = "OFF"; + })(bi || (bi = {})); + var ee; + (function(e2) { + e2.UNKNOWN_ERROR = "UNKNOWN_ERROR", e2.NOT_IMPLEMENTED = "NOT_IMPLEMENTED", e2.UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION", e2.NETWORK_ERROR = "NETWORK_ERROR", e2.SERVER_ERROR = "SERVER_ERROR", e2.TIMEOUT = "TIMEOUT", e2.BUFFER_OVERRUN = "BUFFER_OVERRUN", e2.NUMERIC_FAULT = "NUMERIC_FAULT", e2.MISSING_NEW = "MISSING_NEW", e2.INVALID_ARGUMENT = "INVALID_ARGUMENT", e2.MISSING_ARGUMENT = "MISSING_ARGUMENT", e2.UNEXPECTED_ARGUMENT = "UNEXPECTED_ARGUMENT", e2.CALL_EXCEPTION = "CALL_EXCEPTION", e2.INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS", e2.NONCE_EXPIRED = "NONCE_EXPIRED", e2.REPLACEMENT_UNDERPRICED = "REPLACEMENT_UNDERPRICED", e2.UNPREDICTABLE_GAS_LIMIT = "UNPREDICTABLE_GAS_LIMIT", e2.TRANSACTION_REPLACED = "TRANSACTION_REPLACED", e2.ACTION_REJECTED = "ACTION_REJECTED"; + })(ee || (ee = {})); + var Tn = "0123456789abcdef"; + var z3 = class _z { + constructor(t) { + Object.defineProperty(this, "version", { enumerable: true, value: t, writable: false }); + } + _log(t, r) { + const i2 = t.toLowerCase(); + Cr[i2] == null && this.throwArgumentError("invalid log level name", "logLevel", t), !(On > Cr[i2]) && console.log.apply(console, r); + } + debug(...t) { + this._log(_z.levels.DEBUG, t); + } + info(...t) { + this._log(_z.levels.INFO, t); + } + warn(...t) { + this._log(_z.levels.WARNING, t); + } + makeError(t, r, i2) { + if (Cn) + return this.makeError("censored error", r, {}); + r || (r = _z.errors.UNKNOWN_ERROR), i2 || (i2 = {}); + const n3 = []; + Object.keys(i2).forEach((b4) => { + const g3 = i2[b4]; + try { + if (g3 instanceof Uint8Array) { + let w4 = ""; + for (let y4 = 0; y4 < g3.length; y4++) + w4 += Tn[g3[y4] >> 4], w4 += Tn[g3[y4] & 15]; + n3.push(b4 + "=Uint8Array(0x" + w4 + ")"); + } else + n3.push(b4 + "=" + JSON.stringify(g3)); + } catch { + n3.push(b4 + "=" + JSON.stringify(i2[b4].toString())); + } + }), n3.push(`code=${r}`), n3.push(`version=${this.version}`); + const o2 = t; + let h5 = ""; + switch (r) { + case ee.NUMERIC_FAULT: { + h5 = "NUMERIC_FAULT"; + const b4 = t; + switch (b4) { + case "overflow": + case "underflow": + case "division-by-zero": + h5 += "-" + b4; + break; + case "negative-power": + case "negative-width": + h5 += "-unsupported"; + break; + case "unbound-bitwise-result": + h5 += "-unbound-result"; + break; + } + break; + } + case ee.CALL_EXCEPTION: + case ee.INSUFFICIENT_FUNDS: + case ee.MISSING_NEW: + case ee.NONCE_EXPIRED: + case ee.REPLACEMENT_UNDERPRICED: + case ee.TRANSACTION_REPLACED: + case ee.UNPREDICTABLE_GAS_LIMIT: + h5 = r; + break; + } + h5 && (t += " [ See: https://links.ethers.org/v5-errors-" + h5 + " ]"), n3.length && (t += " (" + n3.join(", ") + ")"); + const p3 = new Error(t); + return p3.reason = o2, p3.code = r, Object.keys(i2).forEach(function(b4) { + p3[b4] = i2[b4]; + }), p3; + } + throwError(t, r, i2) { + throw this.makeError(t, r, i2); + } + throwArgumentError(t, r, i2) { + return this.throwError(t, _z.errors.INVALID_ARGUMENT, { argument: r, value: i2 }); + } + assert(t, r, i2, n3) { + t || this.throwError(r, i2, n3); + } + assertArgument(t, r, i2, n3) { + t || this.throwArgumentError(r, i2, n3); + } + checkNormalize(t) { + Pn && this.throwError("platform missing String.prototype.normalize", _z.errors.UNSUPPORTED_OPERATION, { operation: "String.prototype.normalize", form: Pn }); + } + checkSafeUint53(t, r) { + typeof t == "number" && (r == null && (r = "value not safe"), (t < 0 || t >= 9007199254740991) && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "out-of-safe-range", value: t }), t % 1 && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "non-integer", value: t })); + } + checkArgumentCount(t, r, i2) { + i2 ? i2 = ": " + i2 : i2 = "", t < r && this.throwError("missing argument" + i2, _z.errors.MISSING_ARGUMENT, { count: t, expectedCount: r }), t > r && this.throwError("too many arguments" + i2, _z.errors.UNEXPECTED_ARGUMENT, { count: t, expectedCount: r }); + } + checkNew(t, r) { + (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); + } + checkAbstract(t, r) { + t === r ? this.throwError("cannot instantiate abstract class " + JSON.stringify(r.name) + " directly; use a sub-class", _z.errors.UNSUPPORTED_OPERATION, { name: t.name, operation: "new" }) : (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); + } + static globalLogger() { + return Ai || (Ai = new _z(gs)), Ai; + } + static setCensorship(t, r) { + if (!t && r && this.globalLogger().throwError("cannot permanently disable censorship", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }), Rn) { + if (!t) + return; + this.globalLogger().throwError("error censorship permanent", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); + } + Cn = !!t, Rn = !!r; + } + static setLogLevel(t) { + const r = Cr[t.toLowerCase()]; + if (r == null) { + _z.globalLogger().warn("invalid log level - " + t); + return; + } + On = r; + } + static from(t) { + return new _z(t); + } + }; + z3.errors = ee, z3.levels = bi; + var As = "bytes/5.7.0"; + var Ft = new z3(As); + function Fn(e2) { + return !!e2.toHexString; + } + function ir(e2) { + return e2.slice || (e2.slice = function() { + const t = Array.prototype.slice.call(arguments); + return ir(new Uint8Array(Array.prototype.slice.apply(e2, t))); + }), e2; + } + function bs(e2) { + return Qt(e2) && !(e2.length % 2) || nr(e2); + } + function Dn(e2) { + return typeof e2 == "number" && e2 == e2 && e2 % 1 === 0; + } + function nr(e2) { + if (e2 == null) + return false; + if (e2.constructor === Uint8Array) + return true; + if (typeof e2 == "string" || !Dn(e2.length) || e2.length < 0) + return false; + for (let t = 0; t < e2.length; t++) { + const r = e2[t]; + if (!Dn(r) || r < 0 || r >= 256) + return false; + } + return true; + } + function Pt(e2, t) { + if (t || (t = {}), typeof e2 == "number") { + Ft.checkSafeUint53(e2, "invalid arrayify value"); + const r = []; + for (; e2; ) + r.unshift(e2 & 255), e2 = parseInt(String(e2 / 256)); + return r.length === 0 && r.push(0), ir(new Uint8Array(r)); + } + if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2) && (e2 = e2.toHexString()), Qt(e2)) { + let r = e2.substring(2); + r.length % 2 && (t.hexPad === "left" ? r = "0" + r : t.hexPad === "right" ? r += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)); + const i2 = []; + for (let n3 = 0; n3 < r.length; n3 += 2) + i2.push(parseInt(r.substring(n3, n3 + 2), 16)); + return ir(new Uint8Array(i2)); + } + return nr(e2) ? ir(new Uint8Array(e2)) : Ft.throwArgumentError("invalid arrayify value", "value", e2); + } + function ys(e2) { + const t = e2.map((n3) => Pt(n3)), r = t.reduce((n3, o2) => n3 + o2.length, 0), i2 = new Uint8Array(r); + return t.reduce((n3, o2) => (i2.set(o2, n3), n3 + o2.length), 0), ir(i2); + } + function ws(e2, t) { + e2 = Pt(e2), e2.length > t && Ft.throwArgumentError("value out of range", "value", arguments[0]); + const r = new Uint8Array(t); + return r.set(e2, t - e2.length), ir(r); + } + function Qt(e2, t) { + return !(typeof e2 != "string" || !e2.match(/^0x[0-9A-Fa-f]*$/) || t && e2.length !== 2 + 2 * t); + } + var yi = "0123456789abcdef"; + function Ht(e2, t) { + if (t || (t = {}), typeof e2 == "number") { + Ft.checkSafeUint53(e2, "invalid hexlify value"); + let r = ""; + for (; e2; ) + r = yi[e2 & 15] + r, e2 = Math.floor(e2 / 16); + return r.length ? (r.length % 2 && (r = "0" + r), "0x" + r) : "0x00"; + } + if (typeof e2 == "bigint") + return e2 = e2.toString(16), e2.length % 2 ? "0x0" + e2 : "0x" + e2; + if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2)) + return e2.toHexString(); + if (Qt(e2)) + return e2.length % 2 && (t.hexPad === "left" ? e2 = "0x0" + e2.substring(2) : t.hexPad === "right" ? e2 += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)), e2.toLowerCase(); + if (nr(e2)) { + let r = "0x"; + for (let i2 = 0; i2 < e2.length; i2++) { + let n3 = e2[i2]; + r += yi[(n3 & 240) >> 4] + yi[n3 & 15]; + } + return r; + } + return Ft.throwArgumentError("invalid hexlify value", "value", e2); + } + function xs(e2) { + if (typeof e2 != "string") + e2 = Ht(e2); + else if (!Qt(e2) || e2.length % 2) + return null; + return (e2.length - 2) / 2; + } + function Un(e2, t, r) { + return typeof e2 != "string" ? e2 = Ht(e2) : (!Qt(e2) || e2.length % 2) && Ft.throwArgumentError("invalid hexData", "value", e2), t = 2 + 2 * t, r != null ? "0x" + e2.substring(t, 2 + 2 * r) : "0x" + e2.substring(t); + } + function fe(e2, t) { + for (typeof e2 != "string" ? e2 = Ht(e2) : Qt(e2) || Ft.throwArgumentError("invalid hex string", "value", e2), e2.length > 2 * t + 2 && Ft.throwArgumentError("value out of range", "value", arguments[1]); e2.length < 2 * t + 2; ) + e2 = "0x0" + e2.substring(2); + return e2; + } + function kn(e2) { + const t = { r: "0x", s: "0x", _vs: "0x", recoveryParam: 0, v: 0, yParityAndS: "0x", compact: "0x" }; + if (bs(e2)) { + let r = Pt(e2); + r.length === 64 ? (t.v = 27 + (r[32] >> 7), r[32] &= 127, t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64))) : r.length === 65 ? (t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64)), t.v = r[64]) : Ft.throwArgumentError("invalid signature string", "signature", e2), t.v < 27 && (t.v === 0 || t.v === 1 ? t.v += 27 : Ft.throwArgumentError("signature invalid v byte", "signature", e2)), t.recoveryParam = 1 - t.v % 2, t.recoveryParam && (r[32] |= 128), t._vs = Ht(r.slice(32, 64)); + } else { + if (t.r = e2.r, t.s = e2.s, t.v = e2.v, t.recoveryParam = e2.recoveryParam, t._vs = e2._vs, t._vs != null) { + const n3 = ws(Pt(t._vs), 32); + t._vs = Ht(n3); + const o2 = n3[0] >= 128 ? 1 : 0; + t.recoveryParam == null ? t.recoveryParam = o2 : t.recoveryParam !== o2 && Ft.throwArgumentError("signature recoveryParam mismatch _vs", "signature", e2), n3[0] &= 127; + const h5 = Ht(n3); + t.s == null ? t.s = h5 : t.s !== h5 && Ft.throwArgumentError("signature v mismatch _vs", "signature", e2); + } + if (t.recoveryParam == null) + t.v == null ? Ft.throwArgumentError("signature missing v and recoveryParam", "signature", e2) : t.v === 0 || t.v === 1 ? t.recoveryParam = t.v : t.recoveryParam = 1 - t.v % 2; + else if (t.v == null) + t.v = 27 + t.recoveryParam; + else { + const n3 = t.v === 0 || t.v === 1 ? t.v : 1 - t.v % 2; + t.recoveryParam !== n3 && Ft.throwArgumentError("signature recoveryParam mismatch v", "signature", e2); + } + t.r == null || !Qt(t.r) ? Ft.throwArgumentError("signature missing or invalid r", "signature", e2) : t.r = fe(t.r, 32), t.s == null || !Qt(t.s) ? Ft.throwArgumentError("signature missing or invalid s", "signature", e2) : t.s = fe(t.s, 32); + const r = Pt(t.s); + r[0] >= 128 && Ft.throwArgumentError("signature s out of range", "signature", e2), t.recoveryParam && (r[0] |= 128); + const i2 = Ht(r); + t._vs && (Qt(t._vs) || Ft.throwArgumentError("signature invalid _vs", "signature", e2), t._vs = fe(t._vs, 32)), t._vs == null ? t._vs = i2 : t._vs !== i2 && Ft.throwArgumentError("signature _vs mismatch v and s", "signature", e2); + } + return t.yParityAndS = t._vs, t.compact = t.r + t.yParityAndS.substring(2), t; + } + function wi(e2) { + return "0x" + vs.keccak_256(Pt(e2)); + } + var qn = { exports: {} }; + var Ms = {}; + var Es = Object.freeze({ __proto__: null, default: Ms }); + var Ss = ps(Es); + (function(e2) { + (function(t, r) { + function i2(A2, f4) { + if (!A2) + throw new Error(f4 || "Assertion failed"); + } + function n3(A2, f4) { + A2.super_ = f4; + var a3 = function() { + }; + a3.prototype = f4.prototype, A2.prototype = new a3(), A2.prototype.constructor = A2; + } + function o2(A2, f4, a3) { + if (o2.isBN(A2)) + return A2; + this.negative = 0, this.words = null, this.length = 0, this.red = null, A2 !== null && ((f4 === "le" || f4 === "be") && (a3 = f4, f4 = 10), this._init(A2 || 0, f4 || 10, a3 || "be")); + } + typeof t == "object" ? t.exports = o2 : r.BN = o2, o2.BN = o2, o2.wordSize = 26; + var h5; + try { + typeof window < "u" && typeof window.Buffer < "u" ? h5 = window.Buffer : h5 = Ss.Buffer; + } catch { + } + o2.isBN = function(f4) { + return f4 instanceof o2 ? true : f4 !== null && typeof f4 == "object" && f4.constructor.wordSize === o2.wordSize && Array.isArray(f4.words); + }, o2.max = function(f4, a3) { + return f4.cmp(a3) > 0 ? f4 : a3; + }, o2.min = function(f4, a3) { + return f4.cmp(a3) < 0 ? f4 : a3; + }, o2.prototype._init = function(f4, a3, c4) { + if (typeof f4 == "number") + return this._initNumber(f4, a3, c4); + if (typeof f4 == "object") + return this._initArray(f4, a3, c4); + a3 === "hex" && (a3 = 16), i2(a3 === (a3 | 0) && a3 >= 2 && a3 <= 36), f4 = f4.toString().replace(/\s+/g, ""); + var d3 = 0; + f4[0] === "-" && (d3++, this.negative = 1), d3 < f4.length && (a3 === 16 ? this._parseHex(f4, d3, c4) : (this._parseBase(f4, a3, d3), c4 === "le" && this._initArray(this.toArray(), a3, c4))); + }, o2.prototype._initNumber = function(f4, a3, c4) { + f4 < 0 && (this.negative = 1, f4 = -f4), f4 < 67108864 ? (this.words = [f4 & 67108863], this.length = 1) : f4 < 4503599627370496 ? (this.words = [f4 & 67108863, f4 / 67108864 & 67108863], this.length = 2) : (i2(f4 < 9007199254740992), this.words = [f4 & 67108863, f4 / 67108864 & 67108863, 1], this.length = 3), c4 === "le" && this._initArray(this.toArray(), a3, c4); + }, o2.prototype._initArray = function(f4, a3, c4) { + if (i2(typeof f4.length == "number"), f4.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(f4.length / 3), this.words = new Array(this.length); + for (var d3 = 0; d3 < this.length; d3++) + this.words[d3] = 0; + var m3, x3, M = 0; + if (c4 === "be") + for (d3 = f4.length - 1, m3 = 0; d3 >= 0; d3 -= 3) + x3 = f4[d3] | f4[d3 - 1] << 8 | f4[d3 - 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); + else if (c4 === "le") + for (d3 = 0, m3 = 0; d3 < f4.length; d3 += 3) + x3 = f4[d3] | f4[d3 + 1] << 8 | f4[d3 + 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); + return this._strip(); + }; + function p3(A2, f4) { + var a3 = A2.charCodeAt(f4); + if (a3 >= 48 && a3 <= 57) + return a3 - 48; + if (a3 >= 65 && a3 <= 70) + return a3 - 55; + if (a3 >= 97 && a3 <= 102) + return a3 - 87; + i2(false, "Invalid character in " + A2); + } + function b4(A2, f4, a3) { + var c4 = p3(A2, a3); + return a3 - 1 >= f4 && (c4 |= p3(A2, a3 - 1) << 4), c4; + } + o2.prototype._parseHex = function(f4, a3, c4) { + this.length = Math.ceil((f4.length - a3) / 6), this.words = new Array(this.length); + for (var d3 = 0; d3 < this.length; d3++) + this.words[d3] = 0; + var m3 = 0, x3 = 0, M; + if (c4 === "be") + for (d3 = f4.length - 1; d3 >= a3; d3 -= 2) + M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; + else { + var l4 = f4.length - a3; + for (d3 = l4 % 2 === 0 ? a3 + 1 : a3; d3 < f4.length; d3 += 2) + M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; + } + this._strip(); + }; + function g3(A2, f4, a3, c4) { + for (var d3 = 0, m3 = 0, x3 = Math.min(A2.length, a3), M = f4; M < x3; M++) { + var l4 = A2.charCodeAt(M) - 48; + d3 *= c4, l4 >= 49 ? m3 = l4 - 49 + 10 : l4 >= 17 ? m3 = l4 - 17 + 10 : m3 = l4, i2(l4 >= 0 && m3 < c4, "Invalid character"), d3 += m3; + } + return d3; + } + o2.prototype._parseBase = function(f4, a3, c4) { + this.words = [0], this.length = 1; + for (var d3 = 0, m3 = 1; m3 <= 67108863; m3 *= a3) + d3++; + d3--, m3 = m3 / a3 | 0; + for (var x3 = f4.length - c4, M = x3 % d3, l4 = Math.min(x3, x3 - M) + c4, s2 = 0, v2 = c4; v2 < l4; v2 += d3) + s2 = g3(f4, v2, v2 + d3, a3), this.imuln(m3), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); + if (M !== 0) { + var k4 = 1; + for (s2 = g3(f4, v2, f4.length, a3), v2 = 0; v2 < M; v2++) + k4 *= a3; + this.imuln(k4), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); + } + this._strip(); + }, o2.prototype.copy = function(f4) { + f4.words = new Array(this.length); + for (var a3 = 0; a3 < this.length; a3++) + f4.words[a3] = this.words[a3]; + f4.length = this.length, f4.negative = this.negative, f4.red = this.red; + }; + function w4(A2, f4) { + A2.words = f4.words, A2.length = f4.length, A2.negative = f4.negative, A2.red = f4.red; + } + if (o2.prototype._move = function(f4) { + w4(f4, this); + }, o2.prototype.clone = function() { + var f4 = new o2(null); + return this.copy(f4), f4; + }, o2.prototype._expand = function(f4) { + for (; this.length < f4; ) + this.words[this.length++] = 0; + return this; + }, o2.prototype._strip = function() { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, o2.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, typeof Symbol < "u" && typeof Symbol.for == "function") + try { + o2.prototype[Symbol.for("nodejs.util.inspect.custom")] = y4; + } catch { + o2.prototype.inspect = y4; + } + else + o2.prototype.inspect = y4; + function y4() { + return (this.red ? ""; + } + var S4 = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], I2 = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], N10 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + o2.prototype.toString = function(f4, a3) { + f4 = f4 || 10, a3 = a3 | 0 || 1; + var c4; + if (f4 === 16 || f4 === "hex") { + c4 = ""; + for (var d3 = 0, m3 = 0, x3 = 0; x3 < this.length; x3++) { + var M = this.words[x3], l4 = ((M << d3 | m3) & 16777215).toString(16); + m3 = M >>> 24 - d3 & 16777215, d3 += 2, d3 >= 26 && (d3 -= 26, x3--), m3 !== 0 || x3 !== this.length - 1 ? c4 = S4[6 - l4.length] + l4 + c4 : c4 = l4 + c4; + } + for (m3 !== 0 && (c4 = m3.toString(16) + c4); c4.length % a3 !== 0; ) + c4 = "0" + c4; + return this.negative !== 0 && (c4 = "-" + c4), c4; + } + if (f4 === (f4 | 0) && f4 >= 2 && f4 <= 36) { + var s2 = I2[f4], v2 = N10[f4]; + c4 = ""; + var k4 = this.clone(); + for (k4.negative = 0; !k4.isZero(); ) { + var u3 = k4.modrn(v2).toString(f4); + k4 = k4.idivn(v2), k4.isZero() ? c4 = u3 + c4 : c4 = S4[s2 - u3.length] + u3 + c4; + } + for (this.isZero() && (c4 = "0" + c4); c4.length % a3 !== 0; ) + c4 = "0" + c4; + return this.negative !== 0 && (c4 = "-" + c4), c4; + } + i2(false, "Base should be between 2 and 36"); + }, o2.prototype.toNumber = function() { + var f4 = this.words[0]; + return this.length === 2 ? f4 += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? f4 += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && i2(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -f4 : f4; + }, o2.prototype.toJSON = function() { + return this.toString(16, 2); + }, h5 && (o2.prototype.toBuffer = function(f4, a3) { + return this.toArrayLike(h5, f4, a3); + }), o2.prototype.toArray = function(f4, a3) { + return this.toArrayLike(Array, f4, a3); + }; + var R2 = function(f4, a3) { + return f4.allocUnsafe ? f4.allocUnsafe(a3) : new f4(a3); + }; + o2.prototype.toArrayLike = function(f4, a3, c4) { + this._strip(); + var d3 = this.byteLength(), m3 = c4 || Math.max(1, d3); + i2(d3 <= m3, "byte array longer than desired length"), i2(m3 > 0, "Requested array length <= 0"); + var x3 = R2(f4, m3), M = a3 === "le" ? "LE" : "BE"; + return this["_toArrayLike" + M](x3, d3), x3; + }, o2.prototype._toArrayLikeLE = function(f4, a3) { + for (var c4 = 0, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { + var M = this.words[m3] << x3 | d3; + f4[c4++] = M & 255, c4 < f4.length && (f4[c4++] = M >> 8 & 255), c4 < f4.length && (f4[c4++] = M >> 16 & 255), x3 === 6 ? (c4 < f4.length && (f4[c4++] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); + } + if (c4 < f4.length) + for (f4[c4++] = d3; c4 < f4.length; ) + f4[c4++] = 0; + }, o2.prototype._toArrayLikeBE = function(f4, a3) { + for (var c4 = f4.length - 1, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { + var M = this.words[m3] << x3 | d3; + f4[c4--] = M & 255, c4 >= 0 && (f4[c4--] = M >> 8 & 255), c4 >= 0 && (f4[c4--] = M >> 16 & 255), x3 === 6 ? (c4 >= 0 && (f4[c4--] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); + } + if (c4 >= 0) + for (f4[c4--] = d3; c4 >= 0; ) + f4[c4--] = 0; + }, Math.clz32 ? o2.prototype._countBits = function(f4) { + return 32 - Math.clz32(f4); + } : o2.prototype._countBits = function(f4) { + var a3 = f4, c4 = 0; + return a3 >= 4096 && (c4 += 13, a3 >>>= 13), a3 >= 64 && (c4 += 7, a3 >>>= 7), a3 >= 8 && (c4 += 4, a3 >>>= 4), a3 >= 2 && (c4 += 2, a3 >>>= 2), c4 + a3; + }, o2.prototype._zeroBits = function(f4) { + if (f4 === 0) + return 26; + var a3 = f4, c4 = 0; + return a3 & 8191 || (c4 += 13, a3 >>>= 13), a3 & 127 || (c4 += 7, a3 >>>= 7), a3 & 15 || (c4 += 4, a3 >>>= 4), a3 & 3 || (c4 += 2, a3 >>>= 2), a3 & 1 || c4++, c4; + }, o2.prototype.bitLength = function() { + var f4 = this.words[this.length - 1], a3 = this._countBits(f4); + return (this.length - 1) * 26 + a3; + }; + function F(A2) { + for (var f4 = new Array(A2.bitLength()), a3 = 0; a3 < f4.length; a3++) { + var c4 = a3 / 26 | 0, d3 = a3 % 26; + f4[a3] = A2.words[c4] >>> d3 & 1; + } + return f4; + } + o2.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var f4 = 0, a3 = 0; a3 < this.length; a3++) { + var c4 = this._zeroBits(this.words[a3]); + if (f4 += c4, c4 !== 26) + break; + } + return f4; + }, o2.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, o2.prototype.toTwos = function(f4) { + return this.negative !== 0 ? this.abs().inotn(f4).iaddn(1) : this.clone(); + }, o2.prototype.fromTwos = function(f4) { + return this.testn(f4 - 1) ? this.notn(f4).iaddn(1).ineg() : this.clone(); + }, o2.prototype.isNeg = function() { + return this.negative !== 0; + }, o2.prototype.neg = function() { + return this.clone().ineg(); + }, o2.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, o2.prototype.iuor = function(f4) { + for (; this.length < f4.length; ) + this.words[this.length++] = 0; + for (var a3 = 0; a3 < f4.length; a3++) + this.words[a3] = this.words[a3] | f4.words[a3]; + return this._strip(); + }, o2.prototype.ior = function(f4) { + return i2((this.negative | f4.negative) === 0), this.iuor(f4); + }, o2.prototype.or = function(f4) { + return this.length > f4.length ? this.clone().ior(f4) : f4.clone().ior(this); + }, o2.prototype.uor = function(f4) { + return this.length > f4.length ? this.clone().iuor(f4) : f4.clone().iuor(this); + }, o2.prototype.iuand = function(f4) { + var a3; + this.length > f4.length ? a3 = f4 : a3 = this; + for (var c4 = 0; c4 < a3.length; c4++) + this.words[c4] = this.words[c4] & f4.words[c4]; + return this.length = a3.length, this._strip(); + }, o2.prototype.iand = function(f4) { + return i2((this.negative | f4.negative) === 0), this.iuand(f4); + }, o2.prototype.and = function(f4) { + return this.length > f4.length ? this.clone().iand(f4) : f4.clone().iand(this); + }, o2.prototype.uand = function(f4) { + return this.length > f4.length ? this.clone().iuand(f4) : f4.clone().iuand(this); + }, o2.prototype.iuxor = function(f4) { + var a3, c4; + this.length > f4.length ? (a3 = this, c4 = f4) : (a3 = f4, c4 = this); + for (var d3 = 0; d3 < c4.length; d3++) + this.words[d3] = a3.words[d3] ^ c4.words[d3]; + if (this !== a3) + for (; d3 < a3.length; d3++) + this.words[d3] = a3.words[d3]; + return this.length = a3.length, this._strip(); + }, o2.prototype.ixor = function(f4) { + return i2((this.negative | f4.negative) === 0), this.iuxor(f4); + }, o2.prototype.xor = function(f4) { + return this.length > f4.length ? this.clone().ixor(f4) : f4.clone().ixor(this); + }, o2.prototype.uxor = function(f4) { + return this.length > f4.length ? this.clone().iuxor(f4) : f4.clone().iuxor(this); + }, o2.prototype.inotn = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = Math.ceil(f4 / 26) | 0, c4 = f4 % 26; + this._expand(a3), c4 > 0 && a3--; + for (var d3 = 0; d3 < a3; d3++) + this.words[d3] = ~this.words[d3] & 67108863; + return c4 > 0 && (this.words[d3] = ~this.words[d3] & 67108863 >> 26 - c4), this._strip(); + }, o2.prototype.notn = function(f4) { + return this.clone().inotn(f4); + }, o2.prototype.setn = function(f4, a3) { + i2(typeof f4 == "number" && f4 >= 0); + var c4 = f4 / 26 | 0, d3 = f4 % 26; + return this._expand(c4 + 1), a3 ? this.words[c4] = this.words[c4] | 1 << d3 : this.words[c4] = this.words[c4] & ~(1 << d3), this._strip(); + }, o2.prototype.iadd = function(f4) { + var a3; + if (this.negative !== 0 && f4.negative === 0) + return this.negative = 0, a3 = this.isub(f4), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && f4.negative !== 0) + return f4.negative = 0, a3 = this.isub(f4), f4.negative = 1, a3._normSign(); + var c4, d3; + this.length > f4.length ? (c4 = this, d3 = f4) : (c4 = f4, d3 = this); + for (var m3 = 0, x3 = 0; x3 < d3.length; x3++) + a3 = (c4.words[x3] | 0) + (d3.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; + for (; m3 !== 0 && x3 < c4.length; x3++) + a3 = (c4.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; + if (this.length = c4.length, m3 !== 0) + this.words[this.length] = m3, this.length++; + else if (c4 !== this) + for (; x3 < c4.length; x3++) + this.words[x3] = c4.words[x3]; + return this; + }, o2.prototype.add = function(f4) { + var a3; + return f4.negative !== 0 && this.negative === 0 ? (f4.negative = 0, a3 = this.sub(f4), f4.negative ^= 1, a3) : f4.negative === 0 && this.negative !== 0 ? (this.negative = 0, a3 = f4.sub(this), this.negative = 1, a3) : this.length > f4.length ? this.clone().iadd(f4) : f4.clone().iadd(this); + }, o2.prototype.isub = function(f4) { + if (f4.negative !== 0) { + f4.negative = 0; + var a3 = this.iadd(f4); + return f4.negative = 1, a3._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(f4), this.negative = 1, this._normSign(); + var c4 = this.cmp(f4); + if (c4 === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var d3, m3; + c4 > 0 ? (d3 = this, m3 = f4) : (d3 = f4, m3 = this); + for (var x3 = 0, M = 0; M < m3.length; M++) + a3 = (d3.words[M] | 0) - (m3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; + for (; x3 !== 0 && M < d3.length; M++) + a3 = (d3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; + if (x3 === 0 && M < d3.length && d3 !== this) + for (; M < d3.length; M++) + this.words[M] = d3.words[M]; + return this.length = Math.max(this.length, M), d3 !== this && (this.negative = 1), this._strip(); + }, o2.prototype.sub = function(f4) { + return this.clone().isub(f4); + }; + function U2(A2, f4, a3) { + a3.negative = f4.negative ^ A2.negative; + var c4 = A2.length + f4.length | 0; + a3.length = c4, c4 = c4 - 1 | 0; + var d3 = A2.words[0] | 0, m3 = f4.words[0] | 0, x3 = d3 * m3, M = x3 & 67108863, l4 = x3 / 67108864 | 0; + a3.words[0] = M; + for (var s2 = 1; s2 < c4; s2++) { + for (var v2 = l4 >>> 26, k4 = l4 & 67108863, u3 = Math.min(s2, f4.length - 1), E4 = Math.max(0, s2 - A2.length + 1); E4 <= u3; E4++) { + var _4 = s2 - E4 | 0; + d3 = A2.words[_4] | 0, m3 = f4.words[E4] | 0, x3 = d3 * m3 + k4, v2 += x3 / 67108864 | 0, k4 = x3 & 67108863; + } + a3.words[s2] = k4 | 0, l4 = v2 | 0; + } + return l4 !== 0 ? a3.words[s2] = l4 | 0 : a3.length--, a3._strip(); + } + var Q = function(f4, a3, c4) { + var d3 = f4.words, m3 = a3.words, x3 = c4.words, M = 0, l4, s2, v2, k4 = d3[0] | 0, u3 = k4 & 8191, E4 = k4 >>> 13, _4 = d3[1] | 0, B2 = _4 & 8191, C3 = _4 >>> 13, D2 = d3[2] | 0, P2 = D2 & 8191, O3 = D2 >>> 13, Ct = d3[3] | 0, T2 = Ct & 8191, q2 = Ct >>> 13, Pe = d3[4] | 0, X = Pe & 8191, Z = Pe >>> 13, Te = d3[5] | 0, $ = Te & 8191, tt = Te >>> 13, Fe = d3[6] | 0, et = Fe & 8191, rt = Fe >>> 13, De = d3[7] | 0, it = De & 8191, nt = De >>> 13, Ue = d3[8] | 0, ft = Ue & 8191, ot = Ue >>> 13, ke = d3[9] | 0, st = ke & 8191, at = ke >>> 13, qe = m3[0] | 0, ut = qe & 8191, ht = qe >>> 13, Ke = m3[1] | 0, ct = Ke & 8191, lt = Ke >>> 13, He = m3[2] | 0, dt = He & 8191, pt = He >>> 13, Le = m3[3] | 0, vt = Le & 8191, gt = Le >>> 13, ze = m3[4] | 0, mt = ze & 8191, At = ze >>> 13, je = m3[5] | 0, bt = je & 8191, yt = je >>> 13, Ve = m3[6] | 0, wt = Ve & 8191, xt = Ve >>> 13, Qe = m3[7] | 0, Mt = Qe & 8191, Et = Qe >>> 13, Je = m3[8] | 0, St = Je & 8191, Nt = Je >>> 13, Ye = m3[9] | 0, It = Ye & 8191, _t = Ye >>> 13; + c4.negative = f4.negative ^ a3.negative, c4.length = 19, l4 = Math.imul(u3, ut), s2 = Math.imul(u3, ht), s2 = s2 + Math.imul(E4, ut) | 0, v2 = Math.imul(E4, ht); + var xe = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (xe >>> 26) | 0, xe &= 67108863, l4 = Math.imul(B2, ut), s2 = Math.imul(B2, ht), s2 = s2 + Math.imul(C3, ut) | 0, v2 = Math.imul(C3, ht), l4 = l4 + Math.imul(u3, ct) | 0, s2 = s2 + Math.imul(u3, lt) | 0, s2 = s2 + Math.imul(E4, ct) | 0, v2 = v2 + Math.imul(E4, lt) | 0; + var Me = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Me >>> 26) | 0, Me &= 67108863, l4 = Math.imul(P2, ut), s2 = Math.imul(P2, ht), s2 = s2 + Math.imul(O3, ut) | 0, v2 = Math.imul(O3, ht), l4 = l4 + Math.imul(B2, ct) | 0, s2 = s2 + Math.imul(B2, lt) | 0, s2 = s2 + Math.imul(C3, ct) | 0, v2 = v2 + Math.imul(C3, lt) | 0, l4 = l4 + Math.imul(u3, dt) | 0, s2 = s2 + Math.imul(u3, pt) | 0, s2 = s2 + Math.imul(E4, dt) | 0, v2 = v2 + Math.imul(E4, pt) | 0; + var Ee = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Ee >>> 26) | 0, Ee &= 67108863, l4 = Math.imul(T2, ut), s2 = Math.imul(T2, ht), s2 = s2 + Math.imul(q2, ut) | 0, v2 = Math.imul(q2, ht), l4 = l4 + Math.imul(P2, ct) | 0, s2 = s2 + Math.imul(P2, lt) | 0, s2 = s2 + Math.imul(O3, ct) | 0, v2 = v2 + Math.imul(O3, lt) | 0, l4 = l4 + Math.imul(B2, dt) | 0, s2 = s2 + Math.imul(B2, pt) | 0, s2 = s2 + Math.imul(C3, dt) | 0, v2 = v2 + Math.imul(C3, pt) | 0, l4 = l4 + Math.imul(u3, vt) | 0, s2 = s2 + Math.imul(u3, gt) | 0, s2 = s2 + Math.imul(E4, vt) | 0, v2 = v2 + Math.imul(E4, gt) | 0; + var Se = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Se >>> 26) | 0, Se &= 67108863, l4 = Math.imul(X, ut), s2 = Math.imul(X, ht), s2 = s2 + Math.imul(Z, ut) | 0, v2 = Math.imul(Z, ht), l4 = l4 + Math.imul(T2, ct) | 0, s2 = s2 + Math.imul(T2, lt) | 0, s2 = s2 + Math.imul(q2, ct) | 0, v2 = v2 + Math.imul(q2, lt) | 0, l4 = l4 + Math.imul(P2, dt) | 0, s2 = s2 + Math.imul(P2, pt) | 0, s2 = s2 + Math.imul(O3, dt) | 0, v2 = v2 + Math.imul(O3, pt) | 0, l4 = l4 + Math.imul(B2, vt) | 0, s2 = s2 + Math.imul(B2, gt) | 0, s2 = s2 + Math.imul(C3, vt) | 0, v2 = v2 + Math.imul(C3, gt) | 0, l4 = l4 + Math.imul(u3, mt) | 0, s2 = s2 + Math.imul(u3, At) | 0, s2 = s2 + Math.imul(E4, mt) | 0, v2 = v2 + Math.imul(E4, At) | 0; + var Ne = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Ne >>> 26) | 0, Ne &= 67108863, l4 = Math.imul($, ut), s2 = Math.imul($, ht), s2 = s2 + Math.imul(tt, ut) | 0, v2 = Math.imul(tt, ht), l4 = l4 + Math.imul(X, ct) | 0, s2 = s2 + Math.imul(X, lt) | 0, s2 = s2 + Math.imul(Z, ct) | 0, v2 = v2 + Math.imul(Z, lt) | 0, l4 = l4 + Math.imul(T2, dt) | 0, s2 = s2 + Math.imul(T2, pt) | 0, s2 = s2 + Math.imul(q2, dt) | 0, v2 = v2 + Math.imul(q2, pt) | 0, l4 = l4 + Math.imul(P2, vt) | 0, s2 = s2 + Math.imul(P2, gt) | 0, s2 = s2 + Math.imul(O3, vt) | 0, v2 = v2 + Math.imul(O3, gt) | 0, l4 = l4 + Math.imul(B2, mt) | 0, s2 = s2 + Math.imul(B2, At) | 0, s2 = s2 + Math.imul(C3, mt) | 0, v2 = v2 + Math.imul(C3, At) | 0, l4 = l4 + Math.imul(u3, bt) | 0, s2 = s2 + Math.imul(u3, yt) | 0, s2 = s2 + Math.imul(E4, bt) | 0, v2 = v2 + Math.imul(E4, yt) | 0; + var Xr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Xr >>> 26) | 0, Xr &= 67108863, l4 = Math.imul(et, ut), s2 = Math.imul(et, ht), s2 = s2 + Math.imul(rt, ut) | 0, v2 = Math.imul(rt, ht), l4 = l4 + Math.imul($, ct) | 0, s2 = s2 + Math.imul($, lt) | 0, s2 = s2 + Math.imul(tt, ct) | 0, v2 = v2 + Math.imul(tt, lt) | 0, l4 = l4 + Math.imul(X, dt) | 0, s2 = s2 + Math.imul(X, pt) | 0, s2 = s2 + Math.imul(Z, dt) | 0, v2 = v2 + Math.imul(Z, pt) | 0, l4 = l4 + Math.imul(T2, vt) | 0, s2 = s2 + Math.imul(T2, gt) | 0, s2 = s2 + Math.imul(q2, vt) | 0, v2 = v2 + Math.imul(q2, gt) | 0, l4 = l4 + Math.imul(P2, mt) | 0, s2 = s2 + Math.imul(P2, At) | 0, s2 = s2 + Math.imul(O3, mt) | 0, v2 = v2 + Math.imul(O3, At) | 0, l4 = l4 + Math.imul(B2, bt) | 0, s2 = s2 + Math.imul(B2, yt) | 0, s2 = s2 + Math.imul(C3, bt) | 0, v2 = v2 + Math.imul(C3, yt) | 0, l4 = l4 + Math.imul(u3, wt) | 0, s2 = s2 + Math.imul(u3, xt) | 0, s2 = s2 + Math.imul(E4, wt) | 0, v2 = v2 + Math.imul(E4, xt) | 0; + var Zr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Zr >>> 26) | 0, Zr &= 67108863, l4 = Math.imul(it, ut), s2 = Math.imul(it, ht), s2 = s2 + Math.imul(nt, ut) | 0, v2 = Math.imul(nt, ht), l4 = l4 + Math.imul(et, ct) | 0, s2 = s2 + Math.imul(et, lt) | 0, s2 = s2 + Math.imul(rt, ct) | 0, v2 = v2 + Math.imul(rt, lt) | 0, l4 = l4 + Math.imul($, dt) | 0, s2 = s2 + Math.imul($, pt) | 0, s2 = s2 + Math.imul(tt, dt) | 0, v2 = v2 + Math.imul(tt, pt) | 0, l4 = l4 + Math.imul(X, vt) | 0, s2 = s2 + Math.imul(X, gt) | 0, s2 = s2 + Math.imul(Z, vt) | 0, v2 = v2 + Math.imul(Z, gt) | 0, l4 = l4 + Math.imul(T2, mt) | 0, s2 = s2 + Math.imul(T2, At) | 0, s2 = s2 + Math.imul(q2, mt) | 0, v2 = v2 + Math.imul(q2, At) | 0, l4 = l4 + Math.imul(P2, bt) | 0, s2 = s2 + Math.imul(P2, yt) | 0, s2 = s2 + Math.imul(O3, bt) | 0, v2 = v2 + Math.imul(O3, yt) | 0, l4 = l4 + Math.imul(B2, wt) | 0, s2 = s2 + Math.imul(B2, xt) | 0, s2 = s2 + Math.imul(C3, wt) | 0, v2 = v2 + Math.imul(C3, xt) | 0, l4 = l4 + Math.imul(u3, Mt) | 0, s2 = s2 + Math.imul(u3, Et) | 0, s2 = s2 + Math.imul(E4, Mt) | 0, v2 = v2 + Math.imul(E4, Et) | 0; + var $r = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + ($r >>> 26) | 0, $r &= 67108863, l4 = Math.imul(ft, ut), s2 = Math.imul(ft, ht), s2 = s2 + Math.imul(ot, ut) | 0, v2 = Math.imul(ot, ht), l4 = l4 + Math.imul(it, ct) | 0, s2 = s2 + Math.imul(it, lt) | 0, s2 = s2 + Math.imul(nt, ct) | 0, v2 = v2 + Math.imul(nt, lt) | 0, l4 = l4 + Math.imul(et, dt) | 0, s2 = s2 + Math.imul(et, pt) | 0, s2 = s2 + Math.imul(rt, dt) | 0, v2 = v2 + Math.imul(rt, pt) | 0, l4 = l4 + Math.imul($, vt) | 0, s2 = s2 + Math.imul($, gt) | 0, s2 = s2 + Math.imul(tt, vt) | 0, v2 = v2 + Math.imul(tt, gt) | 0, l4 = l4 + Math.imul(X, mt) | 0, s2 = s2 + Math.imul(X, At) | 0, s2 = s2 + Math.imul(Z, mt) | 0, v2 = v2 + Math.imul(Z, At) | 0, l4 = l4 + Math.imul(T2, bt) | 0, s2 = s2 + Math.imul(T2, yt) | 0, s2 = s2 + Math.imul(q2, bt) | 0, v2 = v2 + Math.imul(q2, yt) | 0, l4 = l4 + Math.imul(P2, wt) | 0, s2 = s2 + Math.imul(P2, xt) | 0, s2 = s2 + Math.imul(O3, wt) | 0, v2 = v2 + Math.imul(O3, xt) | 0, l4 = l4 + Math.imul(B2, Mt) | 0, s2 = s2 + Math.imul(B2, Et) | 0, s2 = s2 + Math.imul(C3, Mt) | 0, v2 = v2 + Math.imul(C3, Et) | 0, l4 = l4 + Math.imul(u3, St) | 0, s2 = s2 + Math.imul(u3, Nt) | 0, s2 = s2 + Math.imul(E4, St) | 0, v2 = v2 + Math.imul(E4, Nt) | 0; + var ti = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ti >>> 26) | 0, ti &= 67108863, l4 = Math.imul(st, ut), s2 = Math.imul(st, ht), s2 = s2 + Math.imul(at, ut) | 0, v2 = Math.imul(at, ht), l4 = l4 + Math.imul(ft, ct) | 0, s2 = s2 + Math.imul(ft, lt) | 0, s2 = s2 + Math.imul(ot, ct) | 0, v2 = v2 + Math.imul(ot, lt) | 0, l4 = l4 + Math.imul(it, dt) | 0, s2 = s2 + Math.imul(it, pt) | 0, s2 = s2 + Math.imul(nt, dt) | 0, v2 = v2 + Math.imul(nt, pt) | 0, l4 = l4 + Math.imul(et, vt) | 0, s2 = s2 + Math.imul(et, gt) | 0, s2 = s2 + Math.imul(rt, vt) | 0, v2 = v2 + Math.imul(rt, gt) | 0, l4 = l4 + Math.imul($, mt) | 0, s2 = s2 + Math.imul($, At) | 0, s2 = s2 + Math.imul(tt, mt) | 0, v2 = v2 + Math.imul(tt, At) | 0, l4 = l4 + Math.imul(X, bt) | 0, s2 = s2 + Math.imul(X, yt) | 0, s2 = s2 + Math.imul(Z, bt) | 0, v2 = v2 + Math.imul(Z, yt) | 0, l4 = l4 + Math.imul(T2, wt) | 0, s2 = s2 + Math.imul(T2, xt) | 0, s2 = s2 + Math.imul(q2, wt) | 0, v2 = v2 + Math.imul(q2, xt) | 0, l4 = l4 + Math.imul(P2, Mt) | 0, s2 = s2 + Math.imul(P2, Et) | 0, s2 = s2 + Math.imul(O3, Mt) | 0, v2 = v2 + Math.imul(O3, Et) | 0, l4 = l4 + Math.imul(B2, St) | 0, s2 = s2 + Math.imul(B2, Nt) | 0, s2 = s2 + Math.imul(C3, St) | 0, v2 = v2 + Math.imul(C3, Nt) | 0, l4 = l4 + Math.imul(u3, It) | 0, s2 = s2 + Math.imul(u3, _t) | 0, s2 = s2 + Math.imul(E4, It) | 0, v2 = v2 + Math.imul(E4, _t) | 0; + var ei = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ei >>> 26) | 0, ei &= 67108863, l4 = Math.imul(st, ct), s2 = Math.imul(st, lt), s2 = s2 + Math.imul(at, ct) | 0, v2 = Math.imul(at, lt), l4 = l4 + Math.imul(ft, dt) | 0, s2 = s2 + Math.imul(ft, pt) | 0, s2 = s2 + Math.imul(ot, dt) | 0, v2 = v2 + Math.imul(ot, pt) | 0, l4 = l4 + Math.imul(it, vt) | 0, s2 = s2 + Math.imul(it, gt) | 0, s2 = s2 + Math.imul(nt, vt) | 0, v2 = v2 + Math.imul(nt, gt) | 0, l4 = l4 + Math.imul(et, mt) | 0, s2 = s2 + Math.imul(et, At) | 0, s2 = s2 + Math.imul(rt, mt) | 0, v2 = v2 + Math.imul(rt, At) | 0, l4 = l4 + Math.imul($, bt) | 0, s2 = s2 + Math.imul($, yt) | 0, s2 = s2 + Math.imul(tt, bt) | 0, v2 = v2 + Math.imul(tt, yt) | 0, l4 = l4 + Math.imul(X, wt) | 0, s2 = s2 + Math.imul(X, xt) | 0, s2 = s2 + Math.imul(Z, wt) | 0, v2 = v2 + Math.imul(Z, xt) | 0, l4 = l4 + Math.imul(T2, Mt) | 0, s2 = s2 + Math.imul(T2, Et) | 0, s2 = s2 + Math.imul(q2, Mt) | 0, v2 = v2 + Math.imul(q2, Et) | 0, l4 = l4 + Math.imul(P2, St) | 0, s2 = s2 + Math.imul(P2, Nt) | 0, s2 = s2 + Math.imul(O3, St) | 0, v2 = v2 + Math.imul(O3, Nt) | 0, l4 = l4 + Math.imul(B2, It) | 0, s2 = s2 + Math.imul(B2, _t) | 0, s2 = s2 + Math.imul(C3, It) | 0, v2 = v2 + Math.imul(C3, _t) | 0; + var ri = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ri >>> 26) | 0, ri &= 67108863, l4 = Math.imul(st, dt), s2 = Math.imul(st, pt), s2 = s2 + Math.imul(at, dt) | 0, v2 = Math.imul(at, pt), l4 = l4 + Math.imul(ft, vt) | 0, s2 = s2 + Math.imul(ft, gt) | 0, s2 = s2 + Math.imul(ot, vt) | 0, v2 = v2 + Math.imul(ot, gt) | 0, l4 = l4 + Math.imul(it, mt) | 0, s2 = s2 + Math.imul(it, At) | 0, s2 = s2 + Math.imul(nt, mt) | 0, v2 = v2 + Math.imul(nt, At) | 0, l4 = l4 + Math.imul(et, bt) | 0, s2 = s2 + Math.imul(et, yt) | 0, s2 = s2 + Math.imul(rt, bt) | 0, v2 = v2 + Math.imul(rt, yt) | 0, l4 = l4 + Math.imul($, wt) | 0, s2 = s2 + Math.imul($, xt) | 0, s2 = s2 + Math.imul(tt, wt) | 0, v2 = v2 + Math.imul(tt, xt) | 0, l4 = l4 + Math.imul(X, Mt) | 0, s2 = s2 + Math.imul(X, Et) | 0, s2 = s2 + Math.imul(Z, Mt) | 0, v2 = v2 + Math.imul(Z, Et) | 0, l4 = l4 + Math.imul(T2, St) | 0, s2 = s2 + Math.imul(T2, Nt) | 0, s2 = s2 + Math.imul(q2, St) | 0, v2 = v2 + Math.imul(q2, Nt) | 0, l4 = l4 + Math.imul(P2, It) | 0, s2 = s2 + Math.imul(P2, _t) | 0, s2 = s2 + Math.imul(O3, It) | 0, v2 = v2 + Math.imul(O3, _t) | 0; + var ii = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ii >>> 26) | 0, ii &= 67108863, l4 = Math.imul(st, vt), s2 = Math.imul(st, gt), s2 = s2 + Math.imul(at, vt) | 0, v2 = Math.imul(at, gt), l4 = l4 + Math.imul(ft, mt) | 0, s2 = s2 + Math.imul(ft, At) | 0, s2 = s2 + Math.imul(ot, mt) | 0, v2 = v2 + Math.imul(ot, At) | 0, l4 = l4 + Math.imul(it, bt) | 0, s2 = s2 + Math.imul(it, yt) | 0, s2 = s2 + Math.imul(nt, bt) | 0, v2 = v2 + Math.imul(nt, yt) | 0, l4 = l4 + Math.imul(et, wt) | 0, s2 = s2 + Math.imul(et, xt) | 0, s2 = s2 + Math.imul(rt, wt) | 0, v2 = v2 + Math.imul(rt, xt) | 0, l4 = l4 + Math.imul($, Mt) | 0, s2 = s2 + Math.imul($, Et) | 0, s2 = s2 + Math.imul(tt, Mt) | 0, v2 = v2 + Math.imul(tt, Et) | 0, l4 = l4 + Math.imul(X, St) | 0, s2 = s2 + Math.imul(X, Nt) | 0, s2 = s2 + Math.imul(Z, St) | 0, v2 = v2 + Math.imul(Z, Nt) | 0, l4 = l4 + Math.imul(T2, It) | 0, s2 = s2 + Math.imul(T2, _t) | 0, s2 = s2 + Math.imul(q2, It) | 0, v2 = v2 + Math.imul(q2, _t) | 0; + var ni = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ni >>> 26) | 0, ni &= 67108863, l4 = Math.imul(st, mt), s2 = Math.imul(st, At), s2 = s2 + Math.imul(at, mt) | 0, v2 = Math.imul(at, At), l4 = l4 + Math.imul(ft, bt) | 0, s2 = s2 + Math.imul(ft, yt) | 0, s2 = s2 + Math.imul(ot, bt) | 0, v2 = v2 + Math.imul(ot, yt) | 0, l4 = l4 + Math.imul(it, wt) | 0, s2 = s2 + Math.imul(it, xt) | 0, s2 = s2 + Math.imul(nt, wt) | 0, v2 = v2 + Math.imul(nt, xt) | 0, l4 = l4 + Math.imul(et, Mt) | 0, s2 = s2 + Math.imul(et, Et) | 0, s2 = s2 + Math.imul(rt, Mt) | 0, v2 = v2 + Math.imul(rt, Et) | 0, l4 = l4 + Math.imul($, St) | 0, s2 = s2 + Math.imul($, Nt) | 0, s2 = s2 + Math.imul(tt, St) | 0, v2 = v2 + Math.imul(tt, Nt) | 0, l4 = l4 + Math.imul(X, It) | 0, s2 = s2 + Math.imul(X, _t) | 0, s2 = s2 + Math.imul(Z, It) | 0, v2 = v2 + Math.imul(Z, _t) | 0; + var fi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (fi >>> 26) | 0, fi &= 67108863, l4 = Math.imul(st, bt), s2 = Math.imul(st, yt), s2 = s2 + Math.imul(at, bt) | 0, v2 = Math.imul(at, yt), l4 = l4 + Math.imul(ft, wt) | 0, s2 = s2 + Math.imul(ft, xt) | 0, s2 = s2 + Math.imul(ot, wt) | 0, v2 = v2 + Math.imul(ot, xt) | 0, l4 = l4 + Math.imul(it, Mt) | 0, s2 = s2 + Math.imul(it, Et) | 0, s2 = s2 + Math.imul(nt, Mt) | 0, v2 = v2 + Math.imul(nt, Et) | 0, l4 = l4 + Math.imul(et, St) | 0, s2 = s2 + Math.imul(et, Nt) | 0, s2 = s2 + Math.imul(rt, St) | 0, v2 = v2 + Math.imul(rt, Nt) | 0, l4 = l4 + Math.imul($, It) | 0, s2 = s2 + Math.imul($, _t) | 0, s2 = s2 + Math.imul(tt, It) | 0, v2 = v2 + Math.imul(tt, _t) | 0; + var oi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (oi >>> 26) | 0, oi &= 67108863, l4 = Math.imul(st, wt), s2 = Math.imul(st, xt), s2 = s2 + Math.imul(at, wt) | 0, v2 = Math.imul(at, xt), l4 = l4 + Math.imul(ft, Mt) | 0, s2 = s2 + Math.imul(ft, Et) | 0, s2 = s2 + Math.imul(ot, Mt) | 0, v2 = v2 + Math.imul(ot, Et) | 0, l4 = l4 + Math.imul(it, St) | 0, s2 = s2 + Math.imul(it, Nt) | 0, s2 = s2 + Math.imul(nt, St) | 0, v2 = v2 + Math.imul(nt, Nt) | 0, l4 = l4 + Math.imul(et, It) | 0, s2 = s2 + Math.imul(et, _t) | 0, s2 = s2 + Math.imul(rt, It) | 0, v2 = v2 + Math.imul(rt, _t) | 0; + var si = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (si >>> 26) | 0, si &= 67108863, l4 = Math.imul(st, Mt), s2 = Math.imul(st, Et), s2 = s2 + Math.imul(at, Mt) | 0, v2 = Math.imul(at, Et), l4 = l4 + Math.imul(ft, St) | 0, s2 = s2 + Math.imul(ft, Nt) | 0, s2 = s2 + Math.imul(ot, St) | 0, v2 = v2 + Math.imul(ot, Nt) | 0, l4 = l4 + Math.imul(it, It) | 0, s2 = s2 + Math.imul(it, _t) | 0, s2 = s2 + Math.imul(nt, It) | 0, v2 = v2 + Math.imul(nt, _t) | 0; + var ai = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ai >>> 26) | 0, ai &= 67108863, l4 = Math.imul(st, St), s2 = Math.imul(st, Nt), s2 = s2 + Math.imul(at, St) | 0, v2 = Math.imul(at, Nt), l4 = l4 + Math.imul(ft, It) | 0, s2 = s2 + Math.imul(ft, _t) | 0, s2 = s2 + Math.imul(ot, It) | 0, v2 = v2 + Math.imul(ot, _t) | 0; + var ui = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ui >>> 26) | 0, ui &= 67108863, l4 = Math.imul(st, It), s2 = Math.imul(st, _t), s2 = s2 + Math.imul(at, It) | 0, v2 = Math.imul(at, _t); + var hi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + return M = (v2 + (s2 >>> 13) | 0) + (hi >>> 26) | 0, hi &= 67108863, x3[0] = xe, x3[1] = Me, x3[2] = Ee, x3[3] = Se, x3[4] = Ne, x3[5] = Xr, x3[6] = Zr, x3[7] = $r, x3[8] = ti, x3[9] = ei, x3[10] = ri, x3[11] = ii, x3[12] = ni, x3[13] = fi, x3[14] = oi, x3[15] = si, x3[16] = ai, x3[17] = ui, x3[18] = hi, M !== 0 && (x3[19] = M, c4.length++), c4; + }; + Math.imul || (Q = U2); + function Bt(A2, f4, a3) { + a3.negative = f4.negative ^ A2.negative, a3.length = A2.length + f4.length; + for (var c4 = 0, d3 = 0, m3 = 0; m3 < a3.length - 1; m3++) { + var x3 = d3; + d3 = 0; + for (var M = c4 & 67108863, l4 = Math.min(m3, f4.length - 1), s2 = Math.max(0, m3 - A2.length + 1); s2 <= l4; s2++) { + var v2 = m3 - s2, k4 = A2.words[v2] | 0, u3 = f4.words[s2] | 0, E4 = k4 * u3, _4 = E4 & 67108863; + x3 = x3 + (E4 / 67108864 | 0) | 0, _4 = _4 + M | 0, M = _4 & 67108863, x3 = x3 + (_4 >>> 26) | 0, d3 += x3 >>> 26, x3 &= 67108863; + } + a3.words[m3] = M, c4 = x3, x3 = d3; + } + return c4 !== 0 ? a3.words[m3] = c4 : a3.length--, a3._strip(); + } + function J(A2, f4, a3) { + return Bt(A2, f4, a3); + } + o2.prototype.mulTo = function(f4, a3) { + var c4, d3 = this.length + f4.length; + return this.length === 10 && f4.length === 10 ? c4 = Q(this, f4, a3) : d3 < 63 ? c4 = U2(this, f4, a3) : d3 < 1024 ? c4 = Bt(this, f4, a3) : c4 = J(this, f4, a3), c4; + }, o2.prototype.mul = function(f4) { + var a3 = new o2(null); + return a3.words = new Array(this.length + f4.length), this.mulTo(f4, a3); + }, o2.prototype.mulf = function(f4) { + var a3 = new o2(null); + return a3.words = new Array(this.length + f4.length), J(this, f4, a3); + }, o2.prototype.imul = function(f4) { + return this.clone().mulTo(f4, this); + }, o2.prototype.imuln = function(f4) { + var a3 = f4 < 0; + a3 && (f4 = -f4), i2(typeof f4 == "number"), i2(f4 < 67108864); + for (var c4 = 0, d3 = 0; d3 < this.length; d3++) { + var m3 = (this.words[d3] | 0) * f4, x3 = (m3 & 67108863) + (c4 & 67108863); + c4 >>= 26, c4 += m3 / 67108864 | 0, c4 += x3 >>> 26, this.words[d3] = x3 & 67108863; + } + return c4 !== 0 && (this.words[d3] = c4, this.length++), a3 ? this.ineg() : this; + }, o2.prototype.muln = function(f4) { + return this.clone().imuln(f4); + }, o2.prototype.sqr = function() { + return this.mul(this); + }, o2.prototype.isqr = function() { + return this.imul(this.clone()); + }, o2.prototype.pow = function(f4) { + var a3 = F(f4); + if (a3.length === 0) + return new o2(1); + for (var c4 = this, d3 = 0; d3 < a3.length && a3[d3] === 0; d3++, c4 = c4.sqr()) + ; + if (++d3 < a3.length) + for (var m3 = c4.sqr(); d3 < a3.length; d3++, m3 = m3.sqr()) + a3[d3] !== 0 && (c4 = c4.mul(m3)); + return c4; + }, o2.prototype.iushln = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 67108863 >>> 26 - a3 << 26 - a3, m3; + if (a3 !== 0) { + var x3 = 0; + for (m3 = 0; m3 < this.length; m3++) { + var M = this.words[m3] & d3, l4 = (this.words[m3] | 0) - M << a3; + this.words[m3] = l4 | x3, x3 = M >>> 26 - a3; + } + x3 && (this.words[m3] = x3, this.length++); + } + if (c4 !== 0) { + for (m3 = this.length - 1; m3 >= 0; m3--) + this.words[m3 + c4] = this.words[m3]; + for (m3 = 0; m3 < c4; m3++) + this.words[m3] = 0; + this.length += c4; + } + return this._strip(); + }, o2.prototype.ishln = function(f4) { + return i2(this.negative === 0), this.iushln(f4); + }, o2.prototype.iushrn = function(f4, a3, c4) { + i2(typeof f4 == "number" && f4 >= 0); + var d3; + a3 ? d3 = (a3 - a3 % 26) / 26 : d3 = 0; + var m3 = f4 % 26, x3 = Math.min((f4 - m3) / 26, this.length), M = 67108863 ^ 67108863 >>> m3 << m3, l4 = c4; + if (d3 -= x3, d3 = Math.max(0, d3), l4) { + for (var s2 = 0; s2 < x3; s2++) + l4.words[s2] = this.words[s2]; + l4.length = x3; + } + if (x3 !== 0) + if (this.length > x3) + for (this.length -= x3, s2 = 0; s2 < this.length; s2++) + this.words[s2] = this.words[s2 + x3]; + else + this.words[0] = 0, this.length = 1; + var v2 = 0; + for (s2 = this.length - 1; s2 >= 0 && (v2 !== 0 || s2 >= d3); s2--) { + var k4 = this.words[s2] | 0; + this.words[s2] = v2 << 26 - m3 | k4 >>> m3, v2 = k4 & M; + } + return l4 && v2 !== 0 && (l4.words[l4.length++] = v2), this.length === 0 && (this.words[0] = 0, this.length = 1), this._strip(); + }, o2.prototype.ishrn = function(f4, a3, c4) { + return i2(this.negative === 0), this.iushrn(f4, a3, c4); + }, o2.prototype.shln = function(f4) { + return this.clone().ishln(f4); + }, o2.prototype.ushln = function(f4) { + return this.clone().iushln(f4); + }, o2.prototype.shrn = function(f4) { + return this.clone().ishrn(f4); + }, o2.prototype.ushrn = function(f4) { + return this.clone().iushrn(f4); + }, o2.prototype.testn = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; + if (this.length <= c4) + return false; + var m3 = this.words[c4]; + return !!(m3 & d3); + }, o2.prototype.imaskn = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = f4 % 26, c4 = (f4 - a3) / 26; + if (i2(this.negative === 0, "imaskn works only with positive numbers"), this.length <= c4) + return this; + if (a3 !== 0 && c4++, this.length = Math.min(c4, this.length), a3 !== 0) { + var d3 = 67108863 ^ 67108863 >>> a3 << a3; + this.words[this.length - 1] &= d3; + } + return this._strip(); + }, o2.prototype.maskn = function(f4) { + return this.clone().imaskn(f4); + }, o2.prototype.iaddn = function(f4) { + return i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0 ? this.isubn(-f4) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) <= f4 ? (this.words[0] = f4 - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(f4), this.negative = 1, this) : this._iaddn(f4); + }, o2.prototype._iaddn = function(f4) { + this.words[0] += f4; + for (var a3 = 0; a3 < this.length && this.words[a3] >= 67108864; a3++) + this.words[a3] -= 67108864, a3 === this.length - 1 ? this.words[a3 + 1] = 1 : this.words[a3 + 1]++; + return this.length = Math.max(this.length, a3 + 1), this; + }, o2.prototype.isubn = function(f4) { + if (i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0) + return this.iaddn(-f4); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(f4), this.negative = 1, this; + if (this.words[0] -= f4, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a3 = 0; a3 < this.length && this.words[a3] < 0; a3++) + this.words[a3] += 67108864, this.words[a3 + 1] -= 1; + return this._strip(); + }, o2.prototype.addn = function(f4) { + return this.clone().iaddn(f4); + }, o2.prototype.subn = function(f4) { + return this.clone().isubn(f4); + }, o2.prototype.iabs = function() { + return this.negative = 0, this; + }, o2.prototype.abs = function() { + return this.clone().iabs(); + }, o2.prototype._ishlnsubmul = function(f4, a3, c4) { + var d3 = f4.length + c4, m3; + this._expand(d3); + var x3, M = 0; + for (m3 = 0; m3 < f4.length; m3++) { + x3 = (this.words[m3 + c4] | 0) + M; + var l4 = (f4.words[m3] | 0) * a3; + x3 -= l4 & 67108863, M = (x3 >> 26) - (l4 / 67108864 | 0), this.words[m3 + c4] = x3 & 67108863; + } + for (; m3 < this.length - c4; m3++) + x3 = (this.words[m3 + c4] | 0) + M, M = x3 >> 26, this.words[m3 + c4] = x3 & 67108863; + if (M === 0) + return this._strip(); + for (i2(M === -1), M = 0, m3 = 0; m3 < this.length; m3++) + x3 = -(this.words[m3] | 0) + M, M = x3 >> 26, this.words[m3] = x3 & 67108863; + return this.negative = 1, this._strip(); + }, o2.prototype._wordDiv = function(f4, a3) { + var c4 = this.length - f4.length, d3 = this.clone(), m3 = f4, x3 = m3.words[m3.length - 1] | 0, M = this._countBits(x3); + c4 = 26 - M, c4 !== 0 && (m3 = m3.ushln(c4), d3.iushln(c4), x3 = m3.words[m3.length - 1] | 0); + var l4 = d3.length - m3.length, s2; + if (a3 !== "mod") { + s2 = new o2(null), s2.length = l4 + 1, s2.words = new Array(s2.length); + for (var v2 = 0; v2 < s2.length; v2++) + s2.words[v2] = 0; + } + var k4 = d3.clone()._ishlnsubmul(m3, 1, l4); + k4.negative === 0 && (d3 = k4, s2 && (s2.words[l4] = 1)); + for (var u3 = l4 - 1; u3 >= 0; u3--) { + var E4 = (d3.words[m3.length + u3] | 0) * 67108864 + (d3.words[m3.length + u3 - 1] | 0); + for (E4 = Math.min(E4 / x3 | 0, 67108863), d3._ishlnsubmul(m3, E4, u3); d3.negative !== 0; ) + E4--, d3.negative = 0, d3._ishlnsubmul(m3, 1, u3), d3.isZero() || (d3.negative ^= 1); + s2 && (s2.words[u3] = E4); + } + return s2 && s2._strip(), d3._strip(), a3 !== "div" && c4 !== 0 && d3.iushrn(c4), { div: s2 || null, mod: d3 }; + }, o2.prototype.divmod = function(f4, a3, c4) { + if (i2(!f4.isZero()), this.isZero()) + return { div: new o2(0), mod: new o2(0) }; + var d3, m3, x3; + return this.negative !== 0 && f4.negative === 0 ? (x3 = this.neg().divmod(f4, a3), a3 !== "mod" && (d3 = x3.div.neg()), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.iadd(f4)), { div: d3, mod: m3 }) : this.negative === 0 && f4.negative !== 0 ? (x3 = this.divmod(f4.neg(), a3), a3 !== "mod" && (d3 = x3.div.neg()), { div: d3, mod: x3.mod }) : this.negative & f4.negative ? (x3 = this.neg().divmod(f4.neg(), a3), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.isub(f4)), { div: x3.div, mod: m3 }) : f4.length > this.length || this.cmp(f4) < 0 ? { div: new o2(0), mod: this } : f4.length === 1 ? a3 === "div" ? { div: this.divn(f4.words[0]), mod: null } : a3 === "mod" ? { div: null, mod: new o2(this.modrn(f4.words[0])) } : { div: this.divn(f4.words[0]), mod: new o2(this.modrn(f4.words[0])) } : this._wordDiv(f4, a3); + }, o2.prototype.div = function(f4) { + return this.divmod(f4, "div", false).div; + }, o2.prototype.mod = function(f4) { + return this.divmod(f4, "mod", false).mod; + }, o2.prototype.umod = function(f4) { + return this.divmod(f4, "mod", true).mod; + }, o2.prototype.divRound = function(f4) { + var a3 = this.divmod(f4); + if (a3.mod.isZero()) + return a3.div; + var c4 = a3.div.negative !== 0 ? a3.mod.isub(f4) : a3.mod, d3 = f4.ushrn(1), m3 = f4.andln(1), x3 = c4.cmp(d3); + return x3 < 0 || m3 === 1 && x3 === 0 ? a3.div : a3.div.negative !== 0 ? a3.div.isubn(1) : a3.div.iaddn(1); + }, o2.prototype.modrn = function(f4) { + var a3 = f4 < 0; + a3 && (f4 = -f4), i2(f4 <= 67108863); + for (var c4 = (1 << 26) % f4, d3 = 0, m3 = this.length - 1; m3 >= 0; m3--) + d3 = (c4 * d3 + (this.words[m3] | 0)) % f4; + return a3 ? -d3 : d3; + }, o2.prototype.modn = function(f4) { + return this.modrn(f4); + }, o2.prototype.idivn = function(f4) { + var a3 = f4 < 0; + a3 && (f4 = -f4), i2(f4 <= 67108863); + for (var c4 = 0, d3 = this.length - 1; d3 >= 0; d3--) { + var m3 = (this.words[d3] | 0) + c4 * 67108864; + this.words[d3] = m3 / f4 | 0, c4 = m3 % f4; + } + return this._strip(), a3 ? this.ineg() : this; + }, o2.prototype.divn = function(f4) { + return this.clone().idivn(f4); + }, o2.prototype.egcd = function(f4) { + i2(f4.negative === 0), i2(!f4.isZero()); + var a3 = this, c4 = f4.clone(); + a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); + for (var d3 = new o2(1), m3 = new o2(0), x3 = new o2(0), M = new o2(1), l4 = 0; a3.isEven() && c4.isEven(); ) + a3.iushrn(1), c4.iushrn(1), ++l4; + for (var s2 = c4.clone(), v2 = a3.clone(); !a3.isZero(); ) { + for (var k4 = 0, u3 = 1; !(a3.words[0] & u3) && k4 < 26; ++k4, u3 <<= 1) + ; + if (k4 > 0) + for (a3.iushrn(k4); k4-- > 0; ) + (d3.isOdd() || m3.isOdd()) && (d3.iadd(s2), m3.isub(v2)), d3.iushrn(1), m3.iushrn(1); + for (var E4 = 0, _4 = 1; !(c4.words[0] & _4) && E4 < 26; ++E4, _4 <<= 1) + ; + if (E4 > 0) + for (c4.iushrn(E4); E4-- > 0; ) + (x3.isOdd() || M.isOdd()) && (x3.iadd(s2), M.isub(v2)), x3.iushrn(1), M.iushrn(1); + a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(x3), m3.isub(M)) : (c4.isub(a3), x3.isub(d3), M.isub(m3)); + } + return { a: x3, b: M, gcd: c4.iushln(l4) }; + }, o2.prototype._invmp = function(f4) { + i2(f4.negative === 0), i2(!f4.isZero()); + var a3 = this, c4 = f4.clone(); + a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); + for (var d3 = new o2(1), m3 = new o2(0), x3 = c4.clone(); a3.cmpn(1) > 0 && c4.cmpn(1) > 0; ) { + for (var M = 0, l4 = 1; !(a3.words[0] & l4) && M < 26; ++M, l4 <<= 1) + ; + if (M > 0) + for (a3.iushrn(M); M-- > 0; ) + d3.isOdd() && d3.iadd(x3), d3.iushrn(1); + for (var s2 = 0, v2 = 1; !(c4.words[0] & v2) && s2 < 26; ++s2, v2 <<= 1) + ; + if (s2 > 0) + for (c4.iushrn(s2); s2-- > 0; ) + m3.isOdd() && m3.iadd(x3), m3.iushrn(1); + a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(m3)) : (c4.isub(a3), m3.isub(d3)); + } + var k4; + return a3.cmpn(1) === 0 ? k4 = d3 : k4 = m3, k4.cmpn(0) < 0 && k4.iadd(f4), k4; + }, o2.prototype.gcd = function(f4) { + if (this.isZero()) + return f4.abs(); + if (f4.isZero()) + return this.abs(); + var a3 = this.clone(), c4 = f4.clone(); + a3.negative = 0, c4.negative = 0; + for (var d3 = 0; a3.isEven() && c4.isEven(); d3++) + a3.iushrn(1), c4.iushrn(1); + do { + for (; a3.isEven(); ) + a3.iushrn(1); + for (; c4.isEven(); ) + c4.iushrn(1); + var m3 = a3.cmp(c4); + if (m3 < 0) { + var x3 = a3; + a3 = c4, c4 = x3; + } else if (m3 === 0 || c4.cmpn(1) === 0) + break; + a3.isub(c4); + } while (true); + return c4.iushln(d3); + }, o2.prototype.invm = function(f4) { + return this.egcd(f4).a.umod(f4); + }, o2.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, o2.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, o2.prototype.andln = function(f4) { + return this.words[0] & f4; + }, o2.prototype.bincn = function(f4) { + i2(typeof f4 == "number"); + var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; + if (this.length <= c4) + return this._expand(c4 + 1), this.words[c4] |= d3, this; + for (var m3 = d3, x3 = c4; m3 !== 0 && x3 < this.length; x3++) { + var M = this.words[x3] | 0; + M += m3, m3 = M >>> 26, M &= 67108863, this.words[x3] = M; + } + return m3 !== 0 && (this.words[x3] = m3, this.length++), this; + }, o2.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, o2.prototype.cmpn = function(f4) { + var a3 = f4 < 0; + if (this.negative !== 0 && !a3) + return -1; + if (this.negative === 0 && a3) + return 1; + this._strip(); + var c4; + if (this.length > 1) + c4 = 1; + else { + a3 && (f4 = -f4), i2(f4 <= 67108863, "Number is too big"); + var d3 = this.words[0] | 0; + c4 = d3 === f4 ? 0 : d3 < f4 ? -1 : 1; + } + return this.negative !== 0 ? -c4 | 0 : c4; + }, o2.prototype.cmp = function(f4) { + if (this.negative !== 0 && f4.negative === 0) + return -1; + if (this.negative === 0 && f4.negative !== 0) + return 1; + var a3 = this.ucmp(f4); + return this.negative !== 0 ? -a3 | 0 : a3; + }, o2.prototype.ucmp = function(f4) { + if (this.length > f4.length) + return 1; + if (this.length < f4.length) + return -1; + for (var a3 = 0, c4 = this.length - 1; c4 >= 0; c4--) { + var d3 = this.words[c4] | 0, m3 = f4.words[c4] | 0; + if (d3 !== m3) { + d3 < m3 ? a3 = -1 : d3 > m3 && (a3 = 1); + break; + } + } + return a3; + }, o2.prototype.gtn = function(f4) { + return this.cmpn(f4) === 1; + }, o2.prototype.gt = function(f4) { + return this.cmp(f4) === 1; + }, o2.prototype.gten = function(f4) { + return this.cmpn(f4) >= 0; + }, o2.prototype.gte = function(f4) { + return this.cmp(f4) >= 0; + }, o2.prototype.ltn = function(f4) { + return this.cmpn(f4) === -1; + }, o2.prototype.lt = function(f4) { + return this.cmp(f4) === -1; + }, o2.prototype.lten = function(f4) { + return this.cmpn(f4) <= 0; + }, o2.prototype.lte = function(f4) { + return this.cmp(f4) <= 0; + }, o2.prototype.eqn = function(f4) { + return this.cmpn(f4) === 0; + }, o2.prototype.eq = function(f4) { + return this.cmp(f4) === 0; + }, o2.red = function(f4) { + return new Y(f4); + }, o2.prototype.toRed = function(f4) { + return i2(!this.red, "Already a number in reduction context"), i2(this.negative === 0, "red works only with positives"), f4.convertTo(this)._forceRed(f4); + }, o2.prototype.fromRed = function() { + return i2(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, o2.prototype._forceRed = function(f4) { + return this.red = f4, this; + }, o2.prototype.forceRed = function(f4) { + return i2(!this.red, "Already a number in reduction context"), this._forceRed(f4); + }, o2.prototype.redAdd = function(f4) { + return i2(this.red, "redAdd works only with red numbers"), this.red.add(this, f4); + }, o2.prototype.redIAdd = function(f4) { + return i2(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, f4); + }, o2.prototype.redSub = function(f4) { + return i2(this.red, "redSub works only with red numbers"), this.red.sub(this, f4); + }, o2.prototype.redISub = function(f4) { + return i2(this.red, "redISub works only with red numbers"), this.red.isub(this, f4); + }, o2.prototype.redShl = function(f4) { + return i2(this.red, "redShl works only with red numbers"), this.red.shl(this, f4); + }, o2.prototype.redMul = function(f4) { + return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.mul(this, f4); + }, o2.prototype.redIMul = function(f4) { + return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.imul(this, f4); + }, o2.prototype.redSqr = function() { + return i2(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, o2.prototype.redISqr = function() { + return i2(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, o2.prototype.redSqrt = function() { + return i2(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, o2.prototype.redInvm = function() { + return i2(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, o2.prototype.redNeg = function() { + return i2(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, o2.prototype.redPow = function(f4) { + return i2(this.red && !f4.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, f4); + }; + var H = { k256: null, p224: null, p192: null, p25519: null }; + function L2(A2, f4) { + this.name = A2, this.p = new o2(f4, 16), this.n = this.p.bitLength(), this.k = new o2(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + L2.prototype._tmp = function() { + var f4 = new o2(null); + return f4.words = new Array(Math.ceil(this.n / 13)), f4; + }, L2.prototype.ireduce = function(f4) { + var a3 = f4, c4; + do + this.split(a3, this.tmp), a3 = this.imulK(a3), a3 = a3.iadd(this.tmp), c4 = a3.bitLength(); + while (c4 > this.n); + var d3 = c4 < this.n ? -1 : a3.ucmp(this.p); + return d3 === 0 ? (a3.words[0] = 0, a3.length = 1) : d3 > 0 ? a3.isub(this.p) : a3.strip !== void 0 ? a3.strip() : a3._strip(), a3; + }, L2.prototype.split = function(f4, a3) { + f4.iushrn(this.n, 0, a3); + }, L2.prototype.imulK = function(f4) { + return f4.imul(this.k); + }; + function Tt() { + L2.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + n3(Tt, L2), Tt.prototype.split = function(f4, a3) { + for (var c4 = 4194303, d3 = Math.min(f4.length, 9), m3 = 0; m3 < d3; m3++) + a3.words[m3] = f4.words[m3]; + if (a3.length = d3, f4.length <= 9) { + f4.words[0] = 0, f4.length = 1; + return; + } + var x3 = f4.words[9]; + for (a3.words[a3.length++] = x3 & c4, m3 = 10; m3 < f4.length; m3++) { + var M = f4.words[m3] | 0; + f4.words[m3 - 10] = (M & c4) << 4 | x3 >>> 22, x3 = M; + } + x3 >>>= 22, f4.words[m3 - 10] = x3, x3 === 0 && f4.length > 10 ? f4.length -= 10 : f4.length -= 9; + }, Tt.prototype.imulK = function(f4) { + f4.words[f4.length] = 0, f4.words[f4.length + 1] = 0, f4.length += 2; + for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { + var d3 = f4.words[c4] | 0; + a3 += d3 * 977, f4.words[c4] = a3 & 67108863, a3 = d3 * 64 + (a3 / 67108864 | 0); + } + return f4.words[f4.length - 1] === 0 && (f4.length--, f4.words[f4.length - 1] === 0 && f4.length--), f4; + }; + function W() { + L2.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + n3(W, L2); + function Ot() { + L2.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + n3(Ot, L2); + function Gt() { + L2.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + n3(Gt, L2), Gt.prototype.imulK = function(f4) { + for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { + var d3 = (f4.words[c4] | 0) * 19 + a3, m3 = d3 & 67108863; + d3 >>>= 26, f4.words[c4] = m3, a3 = d3; + } + return a3 !== 0 && (f4.words[f4.length++] = a3), f4; + }, o2._prime = function(f4) { + if (H[f4]) + return H[f4]; + var a3; + if (f4 === "k256") + a3 = new Tt(); + else if (f4 === "p224") + a3 = new W(); + else if (f4 === "p192") + a3 = new Ot(); + else if (f4 === "p25519") + a3 = new Gt(); + else + throw new Error("Unknown prime " + f4); + return H[f4] = a3, a3; + }; + function Y(A2) { + if (typeof A2 == "string") { + var f4 = o2._prime(A2); + this.m = f4.p, this.prime = f4; + } else + i2(A2.gtn(1), "modulus must be greater than 1"), this.m = A2, this.prime = null; + } + Y.prototype._verify1 = function(f4) { + i2(f4.negative === 0, "red works only with positives"), i2(f4.red, "red works only with red numbers"); + }, Y.prototype._verify2 = function(f4, a3) { + i2((f4.negative | a3.negative) === 0, "red works only with positives"), i2(f4.red && f4.red === a3.red, "red works only with red numbers"); + }, Y.prototype.imod = function(f4) { + return this.prime ? this.prime.ireduce(f4)._forceRed(this) : (w4(f4, f4.umod(this.m)._forceRed(this)), f4); + }, Y.prototype.neg = function(f4) { + return f4.isZero() ? f4.clone() : this.m.sub(f4)._forceRed(this); + }, Y.prototype.add = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.add(a3); + return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4._forceRed(this); + }, Y.prototype.iadd = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.iadd(a3); + return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4; + }, Y.prototype.sub = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.sub(a3); + return c4.cmpn(0) < 0 && c4.iadd(this.m), c4._forceRed(this); + }, Y.prototype.isub = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.isub(a3); + return c4.cmpn(0) < 0 && c4.iadd(this.m), c4; + }, Y.prototype.shl = function(f4, a3) { + return this._verify1(f4), this.imod(f4.ushln(a3)); + }, Y.prototype.imul = function(f4, a3) { + return this._verify2(f4, a3), this.imod(f4.imul(a3)); + }, Y.prototype.mul = function(f4, a3) { + return this._verify2(f4, a3), this.imod(f4.mul(a3)); + }, Y.prototype.isqr = function(f4) { + return this.imul(f4, f4.clone()); + }, Y.prototype.sqr = function(f4) { + return this.mul(f4, f4); + }, Y.prototype.sqrt = function(f4) { + if (f4.isZero()) + return f4.clone(); + var a3 = this.m.andln(3); + if (i2(a3 % 2 === 1), a3 === 3) { + var c4 = this.m.add(new o2(1)).iushrn(2); + return this.pow(f4, c4); + } + for (var d3 = this.m.subn(1), m3 = 0; !d3.isZero() && d3.andln(1) === 0; ) + m3++, d3.iushrn(1); + i2(!d3.isZero()); + var x3 = new o2(1).toRed(this), M = x3.redNeg(), l4 = this.m.subn(1).iushrn(1), s2 = this.m.bitLength(); + for (s2 = new o2(2 * s2 * s2).toRed(this); this.pow(s2, l4).cmp(M) !== 0; ) + s2.redIAdd(M); + for (var v2 = this.pow(s2, d3), k4 = this.pow(f4, d3.addn(1).iushrn(1)), u3 = this.pow(f4, d3), E4 = m3; u3.cmp(x3) !== 0; ) { + for (var _4 = u3, B2 = 0; _4.cmp(x3) !== 0; B2++) + _4 = _4.redSqr(); + i2(B2 < E4); + var C3 = this.pow(v2, new o2(1).iushln(E4 - B2 - 1)); + k4 = k4.redMul(C3), v2 = C3.redSqr(), u3 = u3.redMul(v2), E4 = B2; + } + return k4; + }, Y.prototype.invm = function(f4) { + var a3 = f4._invmp(this.m); + return a3.negative !== 0 ? (a3.negative = 0, this.imod(a3).redNeg()) : this.imod(a3); + }, Y.prototype.pow = function(f4, a3) { + if (a3.isZero()) + return new o2(1).toRed(this); + if (a3.cmpn(1) === 0) + return f4.clone(); + var c4 = 4, d3 = new Array(1 << c4); + d3[0] = new o2(1).toRed(this), d3[1] = f4; + for (var m3 = 2; m3 < d3.length; m3++) + d3[m3] = this.mul(d3[m3 - 1], f4); + var x3 = d3[0], M = 0, l4 = 0, s2 = a3.bitLength() % 26; + for (s2 === 0 && (s2 = 26), m3 = a3.length - 1; m3 >= 0; m3--) { + for (var v2 = a3.words[m3], k4 = s2 - 1; k4 >= 0; k4--) { + var u3 = v2 >> k4 & 1; + if (x3 !== d3[0] && (x3 = this.sqr(x3)), u3 === 0 && M === 0) { + l4 = 0; + continue; + } + M <<= 1, M |= u3, l4++, !(l4 !== c4 && (m3 !== 0 || k4 !== 0)) && (x3 = this.mul(x3, d3[M]), l4 = 0, M = 0); + } + s2 = 26; + } + return x3; + }, Y.prototype.convertTo = function(f4) { + var a3 = f4.umod(this.m); + return a3 === f4 ? a3.clone() : a3; + }, Y.prototype.convertFrom = function(f4) { + var a3 = f4.clone(); + return a3.red = null, a3; + }, o2.mont = function(f4) { + return new Wt(f4); + }; + function Wt(A2) { + Y.call(this, A2), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new o2(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + n3(Wt, Y), Wt.prototype.convertTo = function(f4) { + return this.imod(f4.ushln(this.shift)); + }, Wt.prototype.convertFrom = function(f4) { + var a3 = this.imod(f4.mul(this.rinv)); + return a3.red = null, a3; + }, Wt.prototype.imul = function(f4, a3) { + if (f4.isZero() || a3.isZero()) + return f4.words[0] = 0, f4.length = 1, f4; + var c4 = f4.imul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; + return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); + }, Wt.prototype.mul = function(f4, a3) { + if (f4.isZero() || a3.isZero()) + return new o2(0)._forceRed(this); + var c4 = f4.mul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; + return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); + }, Wt.prototype.invm = function(f4) { + var a3 = this.imod(f4._invmp(this.m).mul(this.r2)); + return a3._forceRed(this); + }; + })(e2, _n); + })(qn); + var K2 = qn.exports; + var Kn = "bignumber/5.7.0"; + var Or = K2.BN; + var me = new z3(Kn); + var xi = {}; + var Hn = 9007199254740991; + function Ns(e2) { + return e2 != null && (G.isBigNumber(e2) || typeof e2 == "number" && e2 % 1 === 0 || typeof e2 == "string" && !!e2.match(/^-?[0-9]+$/) || Qt(e2) || typeof e2 == "bigint" || nr(e2)); + } + var Ln = false; + var G = class _G { + constructor(t, r) { + t !== xi && me.throwError("cannot call constructor directly; use BigNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new (BigNumber)" }), this._hex = r, this._isBigNumber = true, Object.freeze(this); + } + fromTwos(t) { + return jt(j2(this).fromTwos(t)); + } + toTwos(t) { + return jt(j2(this).toTwos(t)); + } + abs() { + return this._hex[0] === "-" ? _G.from(this._hex.substring(1)) : this; + } + add(t) { + return jt(j2(this).add(j2(t))); + } + sub(t) { + return jt(j2(this).sub(j2(t))); + } + div(t) { + return _G.from(t).isZero() && Xt("division-by-zero", "div"), jt(j2(this).div(j2(t))); + } + mul(t) { + return jt(j2(this).mul(j2(t))); + } + mod(t) { + const r = j2(t); + return r.isNeg() && Xt("division-by-zero", "mod"), jt(j2(this).umod(r)); + } + pow(t) { + const r = j2(t); + return r.isNeg() && Xt("negative-power", "pow"), jt(j2(this).pow(r)); + } + and(t) { + const r = j2(t); + return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "and"), jt(j2(this).and(r)); + } + or(t) { + const r = j2(t); + return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "or"), jt(j2(this).or(r)); + } + xor(t) { + const r = j2(t); + return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "xor"), jt(j2(this).xor(r)); + } + mask(t) { + return (this.isNegative() || t < 0) && Xt("negative-width", "mask"), jt(j2(this).maskn(t)); + } + shl(t) { + return (this.isNegative() || t < 0) && Xt("negative-width", "shl"), jt(j2(this).shln(t)); + } + shr(t) { + return (this.isNegative() || t < 0) && Xt("negative-width", "shr"), jt(j2(this).shrn(t)); + } + eq(t) { + return j2(this).eq(j2(t)); + } + lt(t) { + return j2(this).lt(j2(t)); + } + lte(t) { + return j2(this).lte(j2(t)); + } + gt(t) { + return j2(this).gt(j2(t)); + } + gte(t) { + return j2(this).gte(j2(t)); + } + isNegative() { + return this._hex[0] === "-"; + } + isZero() { + return j2(this).isZero(); + } + toNumber() { + try { + return j2(this).toNumber(); + } catch { + Xt("overflow", "toNumber", this.toString()); + } + return null; + } + toBigInt() { + try { + return BigInt(this.toString()); + } catch { + } + return me.throwError("this platform does not support BigInt", z3.errors.UNSUPPORTED_OPERATION, { value: this.toString() }); + } + toString() { + return arguments.length > 0 && (arguments[0] === 10 ? Ln || (Ln = true, me.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")) : arguments[0] === 16 ? me.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", z3.errors.UNEXPECTED_ARGUMENT, {}) : me.throwError("BigNumber.toString does not accept parameters", z3.errors.UNEXPECTED_ARGUMENT, {})), j2(this).toString(10); + } + toHexString() { + return this._hex; + } + toJSON(t) { + return { type: "BigNumber", hex: this.toHexString() }; + } + static from(t) { + if (t instanceof _G) + return t; + if (typeof t == "string") + return t.match(/^-?0x[0-9a-f]+$/i) ? new _G(xi, gr(t)) : t.match(/^-?[0-9]+$/) ? new _G(xi, gr(new Or(t))) : me.throwArgumentError("invalid BigNumber string", "value", t); + if (typeof t == "number") + return t % 1 && Xt("underflow", "BigNumber.from", t), (t >= Hn || t <= -Hn) && Xt("overflow", "BigNumber.from", t), _G.from(String(t)); + const r = t; + if (typeof r == "bigint") + return _G.from(r.toString()); + if (nr(r)) + return _G.from(Ht(r)); + if (r) + if (r.toHexString) { + const i2 = r.toHexString(); + if (typeof i2 == "string") + return _G.from(i2); + } else { + let i2 = r._hex; + if (i2 == null && r.type === "BigNumber" && (i2 = r.hex), typeof i2 == "string" && (Qt(i2) || i2[0] === "-" && Qt(i2.substring(1)))) + return _G.from(i2); + } + return me.throwArgumentError("invalid BigNumber value", "value", t); + } + static isBigNumber(t) { + return !!(t && t._isBigNumber); + } + }; + function gr(e2) { + if (typeof e2 != "string") + return gr(e2.toString(16)); + if (e2[0] === "-") + return e2 = e2.substring(1), e2[0] === "-" && me.throwArgumentError("invalid hex", "value", e2), e2 = gr(e2), e2 === "0x00" ? e2 : "-" + e2; + if (e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), e2 === "0x") + return "0x00"; + for (e2.length % 2 && (e2 = "0x0" + e2.substring(2)); e2.length > 4 && e2.substring(0, 4) === "0x00"; ) + e2 = "0x" + e2.substring(4); + return e2; + } + function jt(e2) { + return G.from(gr(e2)); + } + function j2(e2) { + const t = G.from(e2).toHexString(); + return t[0] === "-" ? new Or("-" + t.substring(3), 16) : new Or(t.substring(2), 16); + } + function Xt(e2, t, r) { + const i2 = { fault: e2, operation: t }; + return r != null && (i2.value = r), me.throwError(e2, z3.errors.NUMERIC_FAULT, i2); + } + function Is(e2) { + return new Or(e2, 36).toString(16); + } + var Lt = new z3(Kn); + var mr = {}; + var zn = G.from(0); + var jn = G.from(-1); + function Vn(e2, t, r, i2) { + const n3 = { fault: t, operation: r }; + return i2 !== void 0 && (n3.value = i2), Lt.throwError(e2, z3.errors.NUMERIC_FAULT, n3); + } + var Ar = "0"; + for (; Ar.length < 256; ) + Ar += Ar; + function Mi(e2) { + if (typeof e2 != "number") + try { + e2 = G.from(e2).toNumber(); + } catch { + } + return typeof e2 == "number" && e2 >= 0 && e2 <= 256 && !(e2 % 1) ? "1" + Ar.substring(0, e2) : Lt.throwArgumentError("invalid decimal size", "decimals", e2); + } + function Ei(e2, t) { + t == null && (t = 0); + const r = Mi(t); + e2 = G.from(e2); + const i2 = e2.lt(zn); + i2 && (e2 = e2.mul(jn)); + let n3 = e2.mod(r).toString(); + for (; n3.length < r.length - 1; ) + n3 = "0" + n3; + n3 = n3.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + const o2 = e2.div(r).toString(); + return r.length === 1 ? e2 = o2 : e2 = o2 + "." + n3, i2 && (e2 = "-" + e2), e2; + } + function Ae(e2, t) { + t == null && (t = 0); + const r = Mi(t); + (typeof e2 != "string" || !e2.match(/^-?[0-9.]+$/)) && Lt.throwArgumentError("invalid decimal value", "value", e2); + const i2 = e2.substring(0, 1) === "-"; + i2 && (e2 = e2.substring(1)), e2 === "." && Lt.throwArgumentError("missing value", "value", e2); + const n3 = e2.split("."); + n3.length > 2 && Lt.throwArgumentError("too many decimal points", "value", e2); + let o2 = n3[0], h5 = n3[1]; + for (o2 || (o2 = "0"), h5 || (h5 = "0"); h5[h5.length - 1] === "0"; ) + h5 = h5.substring(0, h5.length - 1); + for (h5.length > r.length - 1 && Vn("fractional component exceeds decimals", "underflow", "parseFixed"), h5 === "" && (h5 = "0"); h5.length < r.length - 1; ) + h5 += "0"; + const p3 = G.from(o2), b4 = G.from(h5); + let g3 = p3.mul(r).add(b4); + return i2 && (g3 = g3.mul(jn)), g3; + } + var pr = class _pr { + constructor(t, r, i2, n3) { + t !== mr && Lt.throwError("cannot use FixedFormat constructor; use FixedFormat.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.signed = r, this.width = i2, this.decimals = n3, this.name = (r ? "" : "u") + "fixed" + String(i2) + "x" + String(n3), this._multiplier = Mi(n3), Object.freeze(this); + } + static from(t) { + if (t instanceof _pr) + return t; + typeof t == "number" && (t = `fixed128x${t}`); + let r = true, i2 = 128, n3 = 18; + if (typeof t == "string") { + if (t !== "fixed") + if (t === "ufixed") + r = false; + else { + const o2 = t.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + o2 || Lt.throwArgumentError("invalid fixed format", "format", t), r = o2[1] !== "u", i2 = parseInt(o2[2]), n3 = parseInt(o2[3]); + } + } else if (t) { + const o2 = (h5, p3, b4) => t[h5] == null ? b4 : (typeof t[h5] !== p3 && Lt.throwArgumentError("invalid fixed format (" + h5 + " not " + p3 + ")", "format." + h5, t[h5]), t[h5]); + r = o2("signed", "boolean", r), i2 = o2("width", "number", i2), n3 = o2("decimals", "number", n3); + } + return i2 % 8 && Lt.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", i2), n3 > 80 && Lt.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", n3), new _pr(mr, r, i2, n3); + } + }; + var kt = class _kt { + constructor(t, r, i2, n3) { + t !== mr && Lt.throwError("cannot use FixedNumber constructor; use FixedNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.format = n3, this._hex = r, this._value = i2, this._isFixedNumber = true, Object.freeze(this); + } + _checkFormat(t) { + this.format.name !== t.format.name && Lt.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", t); + } + addUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.add(i2), this.format.decimals, this.format); + } + subUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.sub(i2), this.format.decimals, this.format); + } + mulUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.mul(i2).div(this.format._multiplier), this.format.decimals, this.format); + } + divUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.mul(this.format._multiplier).div(i2), this.format.decimals, this.format); + } + floor() { + const t = this.toString().split("."); + t.length === 1 && t.push("0"); + let r = _kt.from(t[0], this.format); + const i2 = !t[1].match(/^(0*)$/); + return this.isNegative() && i2 && (r = r.subUnsafe(Qn.toFormat(r.format))), r; + } + ceiling() { + const t = this.toString().split("."); + t.length === 1 && t.push("0"); + let r = _kt.from(t[0], this.format); + const i2 = !t[1].match(/^(0*)$/); + return !this.isNegative() && i2 && (r = r.addUnsafe(Qn.toFormat(r.format))), r; + } + round(t) { + t == null && (t = 0); + const r = this.toString().split("."); + if (r.length === 1 && r.push("0"), (t < 0 || t > 80 || t % 1) && Lt.throwArgumentError("invalid decimal count", "decimals", t), r[1].length <= t) + return this; + const i2 = _kt.from("1" + Ar.substring(0, t), this.format), n3 = _s.toFormat(this.format); + return this.mulUnsafe(i2).addUnsafe(n3).floor().divUnsafe(i2); + } + isZero() { + return this._value === "0.0" || this._value === "0"; + } + isNegative() { + return this._value[0] === "-"; + } + toString() { + return this._value; + } + toHexString(t) { + if (t == null) + return this._hex; + t % 8 && Lt.throwArgumentError("invalid byte width", "width", t); + const r = G.from(this._hex).fromTwos(this.format.width).toTwos(t).toHexString(); + return fe(r, t / 8); + } + toUnsafeFloat() { + return parseFloat(this.toString()); + } + toFormat(t) { + return _kt.fromString(this._value, t); + } + static fromValue(t, r, i2) { + return i2 == null && r != null && !Ns(r) && (i2 = r, r = null), r == null && (r = 0), i2 == null && (i2 = "fixed"), _kt.fromString(Ei(t, r), pr.from(i2)); + } + static fromString(t, r) { + r == null && (r = "fixed"); + const i2 = pr.from(r), n3 = Ae(t, i2.decimals); + !i2.signed && n3.lt(zn) && Vn("unsigned value cannot be negative", "overflow", "value", t); + let o2 = null; + i2.signed ? o2 = n3.toTwos(i2.width).toHexString() : (o2 = n3.toHexString(), o2 = fe(o2, i2.width / 8)); + const h5 = Ei(n3, i2.decimals); + return new _kt(mr, o2, h5, i2); + } + static fromBytes(t, r) { + r == null && (r = "fixed"); + const i2 = pr.from(r); + if (Pt(t).length > i2.width / 8) + throw new Error("overflow"); + let n3 = G.from(t); + i2.signed && (n3 = n3.fromTwos(i2.width)); + const o2 = n3.toTwos((i2.signed ? 0 : 1) + i2.width).toHexString(), h5 = Ei(n3, i2.decimals); + return new _kt(mr, o2, h5, i2); + } + static from(t, r) { + if (typeof t == "string") + return _kt.fromString(t, r); + if (nr(t)) + return _kt.fromBytes(t, r); + try { + return _kt.fromValue(t, 0, r); + } catch (i2) { + if (i2.code !== z3.errors.INVALID_ARGUMENT) + throw i2; + } + return Lt.throwArgumentError("invalid FixedNumber value", "value", t); + } + static isFixedNumber(t) { + return !!(t && t._isFixedNumber); + } + }; + var Qn = kt.from(1); + var _s = kt.from("0.5"); + var Bs = "strings/5.7.0"; + var Jn = new z3(Bs); + var Pr; + (function(e2) { + e2.current = "", e2.NFC = "NFC", e2.NFD = "NFD", e2.NFKC = "NFKC", e2.NFKD = "NFKD"; + })(Pr || (Pr = {})); + var fr; + (function(e2) { + e2.UNEXPECTED_CONTINUE = "unexpected continuation byte", e2.BAD_PREFIX = "bad codepoint prefix", e2.OVERRUN = "string overrun", e2.MISSING_CONTINUE = "missing continuation byte", e2.OUT_OF_RANGE = "out of UTF-8 range", e2.UTF16_SURROGATE = "UTF-16 surrogate", e2.OVERLONG = "overlong representation"; + })(fr || (fr = {})); + function Rs(e2, t, r, i2, n3) { + return Jn.throwArgumentError(`invalid codepoint at offset ${t}; ${e2}`, "bytes", r); + } + function Yn(e2, t, r, i2, n3) { + if (e2 === fr.BAD_PREFIX || e2 === fr.UNEXPECTED_CONTINUE) { + let o2 = 0; + for (let h5 = t + 1; h5 < r.length && r[h5] >> 6 === 2; h5++) + o2++; + return o2; + } + return e2 === fr.OVERRUN ? r.length - t - 1 : 0; + } + function Cs(e2, t, r, i2, n3) { + return e2 === fr.OVERLONG ? (i2.push(n3), 0) : (i2.push(65533), Yn(e2, t, r)); + } + Object.freeze({ error: Rs, ignore: Yn, replace: Cs }); + function Si(e2, t = Pr.current) { + t != Pr.current && (Jn.checkNormalize(), e2 = e2.normalize(t)); + let r = []; + for (let i2 = 0; i2 < e2.length; i2++) { + const n3 = e2.charCodeAt(i2); + if (n3 < 128) + r.push(n3); + else if (n3 < 2048) + r.push(n3 >> 6 | 192), r.push(n3 & 63 | 128); + else if ((n3 & 64512) == 55296) { + i2++; + const o2 = e2.charCodeAt(i2); + if (i2 >= e2.length || (o2 & 64512) !== 56320) + throw new Error("invalid utf-8 string"); + const h5 = 65536 + ((n3 & 1023) << 10) + (o2 & 1023); + r.push(h5 >> 18 | 240), r.push(h5 >> 12 & 63 | 128), r.push(h5 >> 6 & 63 | 128), r.push(h5 & 63 | 128); + } else + r.push(n3 >> 12 | 224), r.push(n3 >> 6 & 63 | 128), r.push(n3 & 63 | 128); + } + return Pt(r); + } + function Os(e2) { + if (e2.length % 4 !== 0) + throw new Error("bad data"); + let t = []; + for (let r = 0; r < e2.length; r += 4) + t.push(parseInt(e2.substring(r, r + 4), 16)); + return t; + } + function Ni(e2, t) { + t || (t = function(n3) { + return [parseInt(n3, 16)]; + }); + let r = 0, i2 = {}; + return e2.split(",").forEach((n3) => { + let o2 = n3.split(":"); + r += parseInt(o2[0], 16), i2[r] = t(o2[1]); + }), i2; + } + function Gn(e2) { + let t = 0; + return e2.split(",").map((r) => { + let i2 = r.split("-"); + i2.length === 1 ? i2[1] = "0" : i2[1] === "" && (i2[1] = "1"); + let n3 = t + parseInt(i2[0], 16); + return t = parseInt(i2[1], 16), { l: n3, h: t }; + }); + } + Gn("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"), "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((e2) => parseInt(e2, 16)), Ni("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"), Ni("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"), Ni("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", Os), Gn("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); + var Wn = "hash/5.7.0"; + function Ps(e2) { + e2 = atob(e2); + const t = []; + for (let r = 0; r < e2.length; r++) + t.push(e2.charCodeAt(r)); + return Pt(t); + } + function Xn(e2, t) { + t == null && (t = 1); + const r = [], i2 = r.forEach, n3 = function(o2, h5) { + i2.call(o2, function(p3) { + h5 > 0 && Array.isArray(p3) ? n3(p3, h5 - 1) : r.push(p3); + }); + }; + return n3(e2, t), r; + } + function Ts(e2) { + const t = {}; + for (let r = 0; r < e2.length; r++) { + const i2 = e2[r]; + t[i2[0]] = i2[1]; + } + return t; + } + function Fs(e2) { + let t = 0; + function r() { + return e2[t++] << 8 | e2[t++]; + } + let i2 = r(), n3 = 1, o2 = [0, 1]; + for (let H = 1; H < i2; H++) + o2.push(n3 += r()); + let h5 = r(), p3 = t; + t += h5; + let b4 = 0, g3 = 0; + function w4() { + return b4 == 0 && (g3 = g3 << 8 | e2[t++], b4 = 8), g3 >> --b4 & 1; + } + const y4 = 31, S4 = Math.pow(2, y4), I2 = S4 >>> 1, N10 = I2 >> 1, R2 = S4 - 1; + let F = 0; + for (let H = 0; H < y4; H++) + F = F << 1 | w4(); + let U2 = [], Q = 0, Bt = S4; + for (; ; ) { + let H = Math.floor(((F - Q + 1) * n3 - 1) / Bt), L2 = 0, Tt = i2; + for (; Tt - L2 > 1; ) { + let Gt = L2 + Tt >>> 1; + H < o2[Gt] ? Tt = Gt : L2 = Gt; + } + if (L2 == 0) + break; + U2.push(L2); + let W = Q + Math.floor(Bt * o2[L2] / n3), Ot = Q + Math.floor(Bt * o2[L2 + 1] / n3) - 1; + for (; !((W ^ Ot) & I2); ) + F = F << 1 & R2 | w4(), W = W << 1 & R2, Ot = Ot << 1 & R2 | 1; + for (; W & ~Ot & N10; ) + F = F & I2 | F << 1 & R2 >>> 1 | w4(), W = W << 1 ^ I2, Ot = (Ot ^ I2) << 1 | I2 | 1; + Q = W, Bt = 1 + Ot - W; + } + let J = i2 - 4; + return U2.map((H) => { + switch (H - J) { + case 3: + return J + 65792 + (e2[p3++] << 16 | e2[p3++] << 8 | e2[p3++]); + case 2: + return J + 256 + (e2[p3++] << 8 | e2[p3++]); + case 1: + return J + e2[p3++]; + default: + return H - 1; + } + }); + } + function Ds(e2) { + let t = 0; + return () => e2[t++]; + } + function Us(e2) { + return Ds(Fs(e2)); + } + function ks(e2) { + return e2 & 1 ? ~e2 >> 1 : e2 >> 1; + } + function qs(e2, t) { + let r = Array(e2); + for (let i2 = 0; i2 < e2; i2++) + r[i2] = 1 + t(); + return r; + } + function Zn(e2, t) { + let r = Array(e2); + for (let i2 = 0, n3 = -1; i2 < e2; i2++) + r[i2] = n3 += 1 + t(); + return r; + } + function Ks(e2, t) { + let r = Array(e2); + for (let i2 = 0, n3 = 0; i2 < e2; i2++) + r[i2] = n3 += ks(t()); + return r; + } + function Tr(e2, t) { + let r = Zn(e2(), e2), i2 = e2(), n3 = Zn(i2, e2), o2 = qs(i2, e2); + for (let h5 = 0; h5 < i2; h5++) + for (let p3 = 0; p3 < o2[h5]; p3++) + r.push(n3[h5] + p3); + return t ? r.map((h5) => t[h5]) : r; + } + function Hs(e2) { + let t = []; + for (; ; ) { + let r = e2(); + if (r == 0) + break; + t.push(zs(r, e2)); + } + for (; ; ) { + let r = e2() - 1; + if (r < 0) + break; + t.push(js(r, e2)); + } + return Ts(Xn(t)); + } + function Ls(e2) { + let t = []; + for (; ; ) { + let r = e2(); + if (r == 0) + break; + t.push(r); + } + return t; + } + function $n(e2, t, r) { + let i2 = Array(e2).fill(void 0).map(() => []); + for (let n3 = 0; n3 < t; n3++) + Ks(e2, r).forEach((o2, h5) => i2[h5].push(o2)); + return i2; + } + function zs(e2, t) { + let r = 1 + t(), i2 = t(), n3 = Ls(t), o2 = $n(n3.length, 1 + e2, t); + return Xn(o2.map((h5, p3) => { + const b4 = h5[0], g3 = h5.slice(1); + return Array(n3[p3]).fill(void 0).map((w4, y4) => { + let S4 = y4 * i2; + return [b4 + y4 * r, g3.map((I2) => I2 + S4)]; + }); + })); + } + function js(e2, t) { + let r = 1 + t(); + return $n(r, 1 + e2, t).map((n3) => [n3[0], n3.slice(1)]); + } + function Vs(e2) { + let t = Tr(e2).sort((i2, n3) => i2 - n3); + return r(); + function r() { + let i2 = []; + for (; ; ) { + let g3 = Tr(e2, t); + if (g3.length == 0) + break; + i2.push({ set: new Set(g3), node: r() }); + } + i2.sort((g3, w4) => w4.set.size - g3.set.size); + let n3 = e2(), o2 = n3 % 3; + n3 = n3 / 3 | 0; + let h5 = !!(n3 & 1); + n3 >>= 1; + let p3 = n3 == 1, b4 = n3 == 2; + return { branches: i2, valid: o2, fe0f: h5, save: p3, check: b4 }; + } + } + function Qs() { + return Us(Ps("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); + } + var Fr = Qs(); + new Set(Tr(Fr)), new Set(Tr(Fr)), Hs(Fr), Vs(Fr), new z3(Wn); + var Js = new Uint8Array(32); + Js.fill(0); + var Ys = `Ethereum Signed Message: +`; + function tf(e2) { + return typeof e2 == "string" && (e2 = Si(e2)), wi(ys([Si(Ys), Si(String(e2.length)), e2])); + } + var Gs = "rlp/5.7.0"; + new z3(Gs); + var Ws = "address/5.7.0"; + var br = new z3(Ws); + function ef(e2) { + Qt(e2, 20) || br.throwArgumentError("invalid address", "address", e2), e2 = e2.toLowerCase(); + const t = e2.substring(2).split(""), r = new Uint8Array(40); + for (let n3 = 0; n3 < 40; n3++) + r[n3] = t[n3].charCodeAt(0); + const i2 = Pt(wi(r)); + for (let n3 = 0; n3 < 40; n3 += 2) + i2[n3 >> 1] >> 4 >= 8 && (t[n3] = t[n3].toUpperCase()), (i2[n3 >> 1] & 15) >= 8 && (t[n3 + 1] = t[n3 + 1].toUpperCase()); + return "0x" + t.join(""); + } + var Xs = 9007199254740991; + function Zs(e2) { + return Math.log10 ? Math.log10(e2) : Math.log(e2) / Math.LN10; + } + var Ii = {}; + for (let e2 = 0; e2 < 10; e2++) + Ii[String(e2)] = String(e2); + for (let e2 = 0; e2 < 26; e2++) + Ii[String.fromCharCode(65 + e2)] = String(10 + e2); + var rf = Math.floor(Zs(Xs)); + function $s(e2) { + e2 = e2.toUpperCase(), e2 = e2.substring(4) + e2.substring(0, 2) + "00"; + let t = e2.split("").map((i2) => Ii[i2]).join(""); + for (; t.length >= rf; ) { + let i2 = t.substring(0, rf); + t = parseInt(i2, 10) % 97 + t.substring(i2.length); + } + let r = String(98 - parseInt(t, 10) % 97); + for (; r.length < 2; ) + r = "0" + r; + return r; + } + function ta(e2) { + let t = null; + if (typeof e2 != "string" && br.throwArgumentError("invalid address", "address", e2), e2.match(/^(0x)?[0-9a-fA-F]{40}$/)) + e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), t = ef(e2), e2.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && t !== e2 && br.throwArgumentError("bad address checksum", "address", e2); + else if (e2.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + for (e2.substring(2, 4) !== $s(e2) && br.throwArgumentError("bad icap checksum", "address", e2), t = Is(e2.substring(4)); t.length < 40; ) + t = "0" + t; + t = ef("0x" + t); + } else + br.throwArgumentError("invalid address", "address", e2); + return t; + } + var ea = "properties/5.7.0"; + new z3(ea); + function yr(e2, t, r) { + Object.defineProperty(e2, t, { enumerable: true, value: r, writable: false }); + } + new z3(Wn); + var ra = new Uint8Array(32); + ra.fill(0), G.from(-1); + var ia = G.from(0); + var na = G.from(1); + G.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), fe(na.toHexString(), 32), fe(ia.toHexString(), 32); + var oe = {}; + var V = {}; + var wr = nf; + function nf(e2, t) { + if (!e2) + throw new Error(t || "Assertion failed"); + } + nf.equal = function(t, r, i2) { + if (t != r) + throw new Error(i2 || "Assertion failed: " + t + " != " + r); + }; + var _i = { exports: {} }; + typeof Object.create == "function" ? _i.exports = function(t, r) { + r && (t.super_ = r, t.prototype = Object.create(r.prototype, { constructor: { value: t, enumerable: false, writable: true, configurable: true } })); + } : _i.exports = function(t, r) { + if (r) { + t.super_ = r; + var i2 = function() { + }; + i2.prototype = r.prototype, t.prototype = new i2(), t.prototype.constructor = t; + } + }; + var fa = wr; + var oa = _i.exports; + V.inherits = oa; + function sa(e2, t) { + return (e2.charCodeAt(t) & 64512) !== 55296 || t < 0 || t + 1 >= e2.length ? false : (e2.charCodeAt(t + 1) & 64512) === 56320; + } + function aa(e2, t) { + if (Array.isArray(e2)) + return e2.slice(); + if (!e2) + return []; + var r = []; + if (typeof e2 == "string") + if (t) { + if (t === "hex") + for (e2 = e2.replace(/[^a-z0-9]+/ig, ""), e2.length % 2 !== 0 && (e2 = "0" + e2), n3 = 0; n3 < e2.length; n3 += 2) + r.push(parseInt(e2[n3] + e2[n3 + 1], 16)); + } else + for (var i2 = 0, n3 = 0; n3 < e2.length; n3++) { + var o2 = e2.charCodeAt(n3); + o2 < 128 ? r[i2++] = o2 : o2 < 2048 ? (r[i2++] = o2 >> 6 | 192, r[i2++] = o2 & 63 | 128) : sa(e2, n3) ? (o2 = 65536 + ((o2 & 1023) << 10) + (e2.charCodeAt(++n3) & 1023), r[i2++] = o2 >> 18 | 240, r[i2++] = o2 >> 12 & 63 | 128, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128) : (r[i2++] = o2 >> 12 | 224, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128); + } + else + for (n3 = 0; n3 < e2.length; n3++) + r[n3] = e2[n3] | 0; + return r; + } + V.toArray = aa; + function ua(e2) { + for (var t = "", r = 0; r < e2.length; r++) + t += of(e2[r].toString(16)); + return t; + } + V.toHex = ua; + function ff(e2) { + var t = e2 >>> 24 | e2 >>> 8 & 65280 | e2 << 8 & 16711680 | (e2 & 255) << 24; + return t >>> 0; + } + V.htonl = ff; + function ha(e2, t) { + for (var r = "", i2 = 0; i2 < e2.length; i2++) { + var n3 = e2[i2]; + t === "little" && (n3 = ff(n3)), r += sf(n3.toString(16)); + } + return r; + } + V.toHex32 = ha; + function of(e2) { + return e2.length === 1 ? "0" + e2 : e2; + } + V.zero2 = of; + function sf(e2) { + return e2.length === 7 ? "0" + e2 : e2.length === 6 ? "00" + e2 : e2.length === 5 ? "000" + e2 : e2.length === 4 ? "0000" + e2 : e2.length === 3 ? "00000" + e2 : e2.length === 2 ? "000000" + e2 : e2.length === 1 ? "0000000" + e2 : e2; + } + V.zero8 = sf; + function ca(e2, t, r, i2) { + var n3 = r - t; + fa(n3 % 4 === 0); + for (var o2 = new Array(n3 / 4), h5 = 0, p3 = t; h5 < o2.length; h5++, p3 += 4) { + var b4; + i2 === "big" ? b4 = e2[p3] << 24 | e2[p3 + 1] << 16 | e2[p3 + 2] << 8 | e2[p3 + 3] : b4 = e2[p3 + 3] << 24 | e2[p3 + 2] << 16 | e2[p3 + 1] << 8 | e2[p3], o2[h5] = b4 >>> 0; + } + return o2; + } + V.join32 = ca; + function la(e2, t) { + for (var r = new Array(e2.length * 4), i2 = 0, n3 = 0; i2 < e2.length; i2++, n3 += 4) { + var o2 = e2[i2]; + t === "big" ? (r[n3] = o2 >>> 24, r[n3 + 1] = o2 >>> 16 & 255, r[n3 + 2] = o2 >>> 8 & 255, r[n3 + 3] = o2 & 255) : (r[n3 + 3] = o2 >>> 24, r[n3 + 2] = o2 >>> 16 & 255, r[n3 + 1] = o2 >>> 8 & 255, r[n3] = o2 & 255); + } + return r; + } + V.split32 = la; + function da(e2, t) { + return e2 >>> t | e2 << 32 - t; + } + V.rotr32 = da; + function pa(e2, t) { + return e2 << t | e2 >>> 32 - t; + } + V.rotl32 = pa; + function va(e2, t) { + return e2 + t >>> 0; + } + V.sum32 = va; + function ga(e2, t, r) { + return e2 + t + r >>> 0; + } + V.sum32_3 = ga; + function ma(e2, t, r, i2) { + return e2 + t + r + i2 >>> 0; + } + V.sum32_4 = ma; + function Aa(e2, t, r, i2, n3) { + return e2 + t + r + i2 + n3 >>> 0; + } + V.sum32_5 = Aa; + function ba(e2, t, r, i2) { + var n3 = e2[t], o2 = e2[t + 1], h5 = i2 + o2 >>> 0, p3 = (h5 < i2 ? 1 : 0) + r + n3; + e2[t] = p3 >>> 0, e2[t + 1] = h5; + } + V.sum64 = ba; + function ya(e2, t, r, i2) { + var n3 = t + i2 >>> 0, o2 = (n3 < t ? 1 : 0) + e2 + r; + return o2 >>> 0; + } + V.sum64_hi = ya; + function wa(e2, t, r, i2) { + var n3 = t + i2; + return n3 >>> 0; + } + V.sum64_lo = wa; + function xa(e2, t, r, i2, n3, o2, h5, p3) { + var b4 = 0, g3 = t; + g3 = g3 + i2 >>> 0, b4 += g3 < t ? 1 : 0, g3 = g3 + o2 >>> 0, b4 += g3 < o2 ? 1 : 0, g3 = g3 + p3 >>> 0, b4 += g3 < p3 ? 1 : 0; + var w4 = e2 + r + n3 + h5 + b4; + return w4 >>> 0; + } + V.sum64_4_hi = xa; + function Ma(e2, t, r, i2, n3, o2, h5, p3) { + var b4 = t + i2 + o2 + p3; + return b4 >>> 0; + } + V.sum64_4_lo = Ma; + function Ea(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { + var w4 = 0, y4 = t; + y4 = y4 + i2 >>> 0, w4 += y4 < t ? 1 : 0, y4 = y4 + o2 >>> 0, w4 += y4 < o2 ? 1 : 0, y4 = y4 + p3 >>> 0, w4 += y4 < p3 ? 1 : 0, y4 = y4 + g3 >>> 0, w4 += y4 < g3 ? 1 : 0; + var S4 = e2 + r + n3 + h5 + b4 + w4; + return S4 >>> 0; + } + V.sum64_5_hi = Ea; + function Sa(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { + var w4 = t + i2 + o2 + p3 + g3; + return w4 >>> 0; + } + V.sum64_5_lo = Sa; + function Na(e2, t, r) { + var i2 = t << 32 - r | e2 >>> r; + return i2 >>> 0; + } + V.rotr64_hi = Na; + function Ia(e2, t, r) { + var i2 = e2 << 32 - r | t >>> r; + return i2 >>> 0; + } + V.rotr64_lo = Ia; + function _a(e2, t, r) { + return e2 >>> r; + } + V.shr64_hi = _a; + function Ba(e2, t, r) { + var i2 = e2 << 32 - r | t >>> r; + return i2 >>> 0; + } + V.shr64_lo = Ba; + var or2 = {}; + var af = V; + var Ra = wr; + function Dr() { + this.pending = null, this.pendingTotal = 0, this.blockSize = this.constructor.blockSize, this.outSize = this.constructor.outSize, this.hmacStrength = this.constructor.hmacStrength, this.padLength = this.constructor.padLength / 8, this.endian = "big", this._delta8 = this.blockSize / 8, this._delta32 = this.blockSize / 32; + } + or2.BlockHash = Dr, Dr.prototype.update = function(t, r) { + if (t = af.toArray(t, r), this.pending ? this.pending = this.pending.concat(t) : this.pending = t, this.pendingTotal += t.length, this.pending.length >= this._delta8) { + t = this.pending; + var i2 = t.length % this._delta8; + this.pending = t.slice(t.length - i2, t.length), this.pending.length === 0 && (this.pending = null), t = af.join32(t, 0, t.length - i2, this.endian); + for (var n3 = 0; n3 < t.length; n3 += this._delta32) + this._update(t, n3, n3 + this._delta32); + } + return this; + }, Dr.prototype.digest = function(t) { + return this.update(this._pad()), Ra(this.pending === null), this._digest(t); + }, Dr.prototype._pad = function() { + var t = this.pendingTotal, r = this._delta8, i2 = r - (t + this.padLength) % r, n3 = new Array(i2 + this.padLength); + n3[0] = 128; + for (var o2 = 1; o2 < i2; o2++) + n3[o2] = 0; + if (t <<= 3, this.endian === "big") { + for (var h5 = 8; h5 < this.padLength; h5++) + n3[o2++] = 0; + n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = t >>> 24 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t & 255; + } else + for (n3[o2++] = t & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 24 & 255, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, h5 = 8; h5 < this.padLength; h5++) + n3[o2++] = 0; + return n3; + }; + var sr = {}; + var se = {}; + var Ca = V; + var ae = Ca.rotr32; + function Oa(e2, t, r, i2) { + if (e2 === 0) + return uf(t, r, i2); + if (e2 === 1 || e2 === 3) + return cf(t, r, i2); + if (e2 === 2) + return hf(t, r, i2); + } + se.ft_1 = Oa; + function uf(e2, t, r) { + return e2 & t ^ ~e2 & r; + } + se.ch32 = uf; + function hf(e2, t, r) { + return e2 & t ^ e2 & r ^ t & r; + } + se.maj32 = hf; + function cf(e2, t, r) { + return e2 ^ t ^ r; + } + se.p32 = cf; + function Pa(e2) { + return ae(e2, 2) ^ ae(e2, 13) ^ ae(e2, 22); + } + se.s0_256 = Pa; + function Ta(e2) { + return ae(e2, 6) ^ ae(e2, 11) ^ ae(e2, 25); + } + se.s1_256 = Ta; + function Fa(e2) { + return ae(e2, 7) ^ ae(e2, 18) ^ e2 >>> 3; + } + se.g0_256 = Fa; + function Da(e2) { + return ae(e2, 17) ^ ae(e2, 19) ^ e2 >>> 10; + } + se.g1_256 = Da; + var ar = V; + var Ua = or2; + var ka = se; + var Bi = ar.rotl32; + var xr = ar.sum32; + var qa = ar.sum32_5; + var Ka = ka.ft_1; + var lf = Ua.BlockHash; + var Ha = [1518500249, 1859775393, 2400959708, 3395469782]; + function ue() { + if (!(this instanceof ue)) + return new ue(); + lf.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.W = new Array(80); + } + ar.inherits(ue, lf); + var La = ue; + ue.blockSize = 512, ue.outSize = 160, ue.hmacStrength = 80, ue.padLength = 64, ue.prototype._update = function(t, r) { + for (var i2 = this.W, n3 = 0; n3 < 16; n3++) + i2[n3] = t[r + n3]; + for (; n3 < i2.length; n3++) + i2[n3] = Bi(i2[n3 - 3] ^ i2[n3 - 8] ^ i2[n3 - 14] ^ i2[n3 - 16], 1); + var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4]; + for (n3 = 0; n3 < i2.length; n3++) { + var w4 = ~~(n3 / 20), y4 = qa(Bi(o2, 5), Ka(w4, h5, p3, b4), g3, i2[n3], Ha[w4]); + g3 = b4, b4 = p3, p3 = Bi(h5, 30), h5 = o2, o2 = y4; + } + this.h[0] = xr(this.h[0], o2), this.h[1] = xr(this.h[1], h5), this.h[2] = xr(this.h[2], p3), this.h[3] = xr(this.h[3], b4), this.h[4] = xr(this.h[4], g3); + }, ue.prototype._digest = function(t) { + return t === "hex" ? ar.toHex32(this.h, "big") : ar.split32(this.h, "big"); + }; + var ur = V; + var za = or2; + var hr = se; + var ja = wr; + var re = ur.sum32; + var Va = ur.sum32_4; + var Qa = ur.sum32_5; + var Ja = hr.ch32; + var Ya = hr.maj32; + var Ga = hr.s0_256; + var Wa = hr.s1_256; + var Xa = hr.g0_256; + var Za = hr.g1_256; + var df = za.BlockHash; + var $a = [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]; + function he() { + if (!(this instanceof he)) + return new he(); + df.call(this), this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.k = $a, this.W = new Array(64); + } + ur.inherits(he, df); + var pf = he; + he.blockSize = 512, he.outSize = 256, he.hmacStrength = 192, he.padLength = 64, he.prototype._update = function(t, r) { + for (var i2 = this.W, n3 = 0; n3 < 16; n3++) + i2[n3] = t[r + n3]; + for (; n3 < i2.length; n3++) + i2[n3] = Va(Za(i2[n3 - 2]), i2[n3 - 7], Xa(i2[n3 - 15]), i2[n3 - 16]); + var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4], w4 = this.h[5], y4 = this.h[6], S4 = this.h[7]; + for (ja(this.k.length === i2.length), n3 = 0; n3 < i2.length; n3++) { + var I2 = Qa(S4, Wa(g3), Ja(g3, w4, y4), this.k[n3], i2[n3]), N10 = re(Ga(o2), Ya(o2, h5, p3)); + S4 = y4, y4 = w4, w4 = g3, g3 = re(b4, I2), b4 = p3, p3 = h5, h5 = o2, o2 = re(I2, N10); + } + this.h[0] = re(this.h[0], o2), this.h[1] = re(this.h[1], h5), this.h[2] = re(this.h[2], p3), this.h[3] = re(this.h[3], b4), this.h[4] = re(this.h[4], g3), this.h[5] = re(this.h[5], w4), this.h[6] = re(this.h[6], y4), this.h[7] = re(this.h[7], S4); + }, he.prototype._digest = function(t) { + return t === "hex" ? ur.toHex32(this.h, "big") : ur.split32(this.h, "big"); + }; + var Ri = V; + var vf = pf; + function be() { + if (!(this instanceof be)) + return new be(); + vf.call(this), this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]; + } + Ri.inherits(be, vf); + var t0 = be; + be.blockSize = 512, be.outSize = 224, be.hmacStrength = 192, be.padLength = 64, be.prototype._digest = function(t) { + return t === "hex" ? Ri.toHex32(this.h.slice(0, 7), "big") : Ri.split32(this.h.slice(0, 7), "big"); + }; + var Vt = V; + var e0 = or2; + var r0 = wr; + var ce = Vt.rotr64_hi; + var le = Vt.rotr64_lo; + var gf = Vt.shr64_hi; + var mf = Vt.shr64_lo; + var _e = Vt.sum64; + var Ci = Vt.sum64_hi; + var Oi = Vt.sum64_lo; + var i0 = Vt.sum64_4_hi; + var n0 = Vt.sum64_4_lo; + var f0 = Vt.sum64_5_hi; + var o0 = Vt.sum64_5_lo; + var Af = e0.BlockHash; + var s0 = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591]; + function ie() { + if (!(this instanceof ie)) + return new ie(); + Af.call(this), this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209], this.k = s0, this.W = new Array(160); + } + Vt.inherits(ie, Af); + var bf = ie; + ie.blockSize = 1024, ie.outSize = 512, ie.hmacStrength = 192, ie.padLength = 128, ie.prototype._prepareBlock = function(t, r) { + for (var i2 = this.W, n3 = 0; n3 < 32; n3++) + i2[n3] = t[r + n3]; + for (; n3 < i2.length; n3 += 2) { + var o2 = A0(i2[n3 - 4], i2[n3 - 3]), h5 = b0(i2[n3 - 4], i2[n3 - 3]), p3 = i2[n3 - 14], b4 = i2[n3 - 13], g3 = g0(i2[n3 - 30], i2[n3 - 29]), w4 = m0(i2[n3 - 30], i2[n3 - 29]), y4 = i2[n3 - 32], S4 = i2[n3 - 31]; + i2[n3] = i0(o2, h5, p3, b4, g3, w4, y4, S4), i2[n3 + 1] = n0(o2, h5, p3, b4, g3, w4, y4, S4); + } + }, ie.prototype._update = function(t, r) { + this._prepareBlock(t, r); + var i2 = this.W, n3 = this.h[0], o2 = this.h[1], h5 = this.h[2], p3 = this.h[3], b4 = this.h[4], g3 = this.h[5], w4 = this.h[6], y4 = this.h[7], S4 = this.h[8], I2 = this.h[9], N10 = this.h[10], R2 = this.h[11], F = this.h[12], U2 = this.h[13], Q = this.h[14], Bt = this.h[15]; + r0(this.k.length === i2.length); + for (var J = 0; J < i2.length; J += 2) { + var H = Q, L2 = Bt, Tt = p0(S4, I2), W = v0(S4, I2), Ot = a0(S4, I2, N10, R2, F), Gt = u0(S4, I2, N10, R2, F, U2), Y = this.k[J], Wt = this.k[J + 1], A2 = i2[J], f4 = i2[J + 1], a3 = f0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4), c4 = o0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4); + H = l0(n3, o2), L2 = d0(n3, o2), Tt = h0(n3, o2, h5, p3, b4), W = c0(n3, o2, h5, p3, b4, g3); + var d3 = Ci(H, L2, Tt, W), m3 = Oi(H, L2, Tt, W); + Q = F, Bt = U2, F = N10, U2 = R2, N10 = S4, R2 = I2, S4 = Ci(w4, y4, a3, c4), I2 = Oi(y4, y4, a3, c4), w4 = b4, y4 = g3, b4 = h5, g3 = p3, h5 = n3, p3 = o2, n3 = Ci(a3, c4, d3, m3), o2 = Oi(a3, c4, d3, m3); + } + _e(this.h, 0, n3, o2), _e(this.h, 2, h5, p3), _e(this.h, 4, b4, g3), _e(this.h, 6, w4, y4), _e(this.h, 8, S4, I2), _e(this.h, 10, N10, R2), _e(this.h, 12, F, U2), _e(this.h, 14, Q, Bt); + }, ie.prototype._digest = function(t) { + return t === "hex" ? Vt.toHex32(this.h, "big") : Vt.split32(this.h, "big"); + }; + function a0(e2, t, r, i2, n3) { + var o2 = e2 & r ^ ~e2 & n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function u0(e2, t, r, i2, n3, o2) { + var h5 = t & i2 ^ ~t & o2; + return h5 < 0 && (h5 += 4294967296), h5; + } + function h0(e2, t, r, i2, n3) { + var o2 = e2 & r ^ e2 & n3 ^ r & n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function c0(e2, t, r, i2, n3, o2) { + var h5 = t & i2 ^ t & o2 ^ i2 & o2; + return h5 < 0 && (h5 += 4294967296), h5; + } + function l0(e2, t) { + var r = ce(e2, t, 28), i2 = ce(t, e2, 2), n3 = ce(t, e2, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function d0(e2, t) { + var r = le(e2, t, 28), i2 = le(t, e2, 2), n3 = le(t, e2, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function p0(e2, t) { + var r = ce(e2, t, 14), i2 = ce(e2, t, 18), n3 = ce(t, e2, 9), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function v0(e2, t) { + var r = le(e2, t, 14), i2 = le(e2, t, 18), n3 = le(t, e2, 9), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function g0(e2, t) { + var r = ce(e2, t, 1), i2 = ce(e2, t, 8), n3 = gf(e2, t, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function m0(e2, t) { + var r = le(e2, t, 1), i2 = le(e2, t, 8), n3 = mf(e2, t, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function A0(e2, t) { + var r = ce(e2, t, 19), i2 = ce(t, e2, 29), n3 = gf(e2, t, 6), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function b0(e2, t) { + var r = le(e2, t, 19), i2 = le(t, e2, 29), n3 = mf(e2, t, 6), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + var Pi = V; + var yf = bf; + function ye() { + if (!(this instanceof ye)) + return new ye(); + yf.call(this), this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]; + } + Pi.inherits(ye, yf); + var y0 = ye; + ye.blockSize = 1024, ye.outSize = 384, ye.hmacStrength = 192, ye.padLength = 128, ye.prototype._digest = function(t) { + return t === "hex" ? Pi.toHex32(this.h.slice(0, 12), "big") : Pi.split32(this.h.slice(0, 12), "big"); + }, sr.sha1 = La, sr.sha224 = t0, sr.sha256 = pf, sr.sha384 = y0, sr.sha512 = bf; + var wf = {}; + var We = V; + var w0 = or2; + var Ur = We.rotl32; + var xf = We.sum32; + var Mr = We.sum32_3; + var Mf = We.sum32_4; + var Ef = w0.BlockHash; + function de() { + if (!(this instanceof de)) + return new de(); + Ef.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.endian = "little"; + } + We.inherits(de, Ef), wf.ripemd160 = de, de.blockSize = 512, de.outSize = 160, de.hmacStrength = 192, de.padLength = 64, de.prototype._update = function(t, r) { + for (var i2 = this.h[0], n3 = this.h[1], o2 = this.h[2], h5 = this.h[3], p3 = this.h[4], b4 = i2, g3 = n3, w4 = o2, y4 = h5, S4 = p3, I2 = 0; I2 < 80; I2++) { + var N10 = xf(Ur(Mf(i2, Sf(I2, n3, o2, h5), t[E0[I2] + r], x0(I2)), N0[I2]), p3); + i2 = p3, p3 = h5, h5 = Ur(o2, 10), o2 = n3, n3 = N10, N10 = xf(Ur(Mf(b4, Sf(79 - I2, g3, w4, y4), t[S0[I2] + r], M0(I2)), I0[I2]), S4), b4 = S4, S4 = y4, y4 = Ur(w4, 10), w4 = g3, g3 = N10; + } + N10 = Mr(this.h[1], o2, y4), this.h[1] = Mr(this.h[2], h5, S4), this.h[2] = Mr(this.h[3], p3, b4), this.h[3] = Mr(this.h[4], i2, g3), this.h[4] = Mr(this.h[0], n3, w4), this.h[0] = N10; + }, de.prototype._digest = function(t) { + return t === "hex" ? We.toHex32(this.h, "little") : We.split32(this.h, "little"); + }; + function Sf(e2, t, r, i2) { + return e2 <= 15 ? t ^ r ^ i2 : e2 <= 31 ? t & r | ~t & i2 : e2 <= 47 ? (t | ~r) ^ i2 : e2 <= 63 ? t & i2 | r & ~i2 : t ^ (r | ~i2); + } + function x0(e2) { + return e2 <= 15 ? 0 : e2 <= 31 ? 1518500249 : e2 <= 47 ? 1859775393 : e2 <= 63 ? 2400959708 : 2840853838; + } + function M0(e2) { + return e2 <= 15 ? 1352829926 : e2 <= 31 ? 1548603684 : e2 <= 47 ? 1836072691 : e2 <= 63 ? 2053994217 : 0; + } + var E0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; + var S0 = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; + var N0 = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]; + var I0 = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; + var _0 = V; + var B0 = wr; + function cr(e2, t, r) { + if (!(this instanceof cr)) + return new cr(e2, t, r); + this.Hash = e2, this.blockSize = e2.blockSize / 8, this.outSize = e2.outSize / 8, this.inner = null, this.outer = null, this._init(_0.toArray(t, r)); + } + var R0 = cr; + cr.prototype._init = function(t) { + t.length > this.blockSize && (t = new this.Hash().update(t).digest()), B0(t.length <= this.blockSize); + for (var r = t.length; r < this.blockSize; r++) + t.push(0); + for (r = 0; r < t.length; r++) + t[r] ^= 54; + for (this.inner = new this.Hash().update(t), r = 0; r < t.length; r++) + t[r] ^= 106; + this.outer = new this.Hash().update(t); + }, cr.prototype.update = function(t, r) { + return this.inner.update(t, r), this; + }, cr.prototype.digest = function(t) { + return this.outer.update(this.inner.digest()), this.outer.digest(t); + }, function(e2) { + var t = e2; + t.utils = V, t.common = or2, t.sha = sr, t.ripemd = wf, t.hmac = R0, t.sha1 = t.sha.sha1, t.sha256 = t.sha.sha256, t.sha224 = t.sha.sha224, t.sha384 = t.sha.sha384, t.sha512 = t.sha.sha512, t.ripemd160 = t.ripemd.ripemd160; + }(oe); + function lr(e2, t, r) { + return r = { path: t, exports: {}, require: function(i2, n3) { + return C0(i2, n3 ?? r.path); + } }, e2(r, r.exports), r.exports; + } + function C0() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); + } + var Ti = Nf; + function Nf(e2, t) { + if (!e2) + throw new Error(t || "Assertion failed"); + } + Nf.equal = function(t, r, i2) { + if (t != r) + throw new Error(i2 || "Assertion failed: " + t + " != " + r); + }; + var ne = lr(function(e2, t) { + var r = t; + function i2(h5, p3) { + if (Array.isArray(h5)) + return h5.slice(); + if (!h5) + return []; + var b4 = []; + if (typeof h5 != "string") { + for (var g3 = 0; g3 < h5.length; g3++) + b4[g3] = h5[g3] | 0; + return b4; + } + if (p3 === "hex") { + h5 = h5.replace(/[^a-z0-9]+/ig, ""), h5.length % 2 !== 0 && (h5 = "0" + h5); + for (var g3 = 0; g3 < h5.length; g3 += 2) + b4.push(parseInt(h5[g3] + h5[g3 + 1], 16)); + } else + for (var g3 = 0; g3 < h5.length; g3++) { + var w4 = h5.charCodeAt(g3), y4 = w4 >> 8, S4 = w4 & 255; + y4 ? b4.push(y4, S4) : b4.push(S4); + } + return b4; + } + r.toArray = i2; + function n3(h5) { + return h5.length === 1 ? "0" + h5 : h5; + } + r.zero2 = n3; + function o2(h5) { + for (var p3 = "", b4 = 0; b4 < h5.length; b4++) + p3 += n3(h5[b4].toString(16)); + return p3; + } + r.toHex = o2, r.encode = function(p3, b4) { + return b4 === "hex" ? o2(p3) : p3; + }; + }); + var Jt = lr(function(e2, t) { + var r = t; + r.assert = Ti, r.toArray = ne.toArray, r.zero2 = ne.zero2, r.toHex = ne.toHex, r.encode = ne.encode; + function i2(b4, g3, w4) { + var y4 = new Array(Math.max(b4.bitLength(), w4) + 1); + y4.fill(0); + for (var S4 = 1 << g3 + 1, I2 = b4.clone(), N10 = 0; N10 < y4.length; N10++) { + var R2, F = I2.andln(S4 - 1); + I2.isOdd() ? (F > (S4 >> 1) - 1 ? R2 = (S4 >> 1) - F : R2 = F, I2.isubn(R2)) : R2 = 0, y4[N10] = R2, I2.iushrn(1); + } + return y4; + } + r.getNAF = i2; + function n3(b4, g3) { + var w4 = [[], []]; + b4 = b4.clone(), g3 = g3.clone(); + for (var y4 = 0, S4 = 0, I2; b4.cmpn(-y4) > 0 || g3.cmpn(-S4) > 0; ) { + var N10 = b4.andln(3) + y4 & 3, R2 = g3.andln(3) + S4 & 3; + N10 === 3 && (N10 = -1), R2 === 3 && (R2 = -1); + var F; + N10 & 1 ? (I2 = b4.andln(7) + y4 & 7, (I2 === 3 || I2 === 5) && R2 === 2 ? F = -N10 : F = N10) : F = 0, w4[0].push(F); + var U2; + R2 & 1 ? (I2 = g3.andln(7) + S4 & 7, (I2 === 3 || I2 === 5) && N10 === 2 ? U2 = -R2 : U2 = R2) : U2 = 0, w4[1].push(U2), 2 * y4 === F + 1 && (y4 = 1 - y4), 2 * S4 === U2 + 1 && (S4 = 1 - S4), b4.iushrn(1), g3.iushrn(1); + } + return w4; + } + r.getJSF = n3; + function o2(b4, g3, w4) { + var y4 = "_" + g3; + b4.prototype[g3] = function() { + return this[y4] !== void 0 ? this[y4] : this[y4] = w4.call(this); + }; + } + r.cachedProperty = o2; + function h5(b4) { + return typeof b4 == "string" ? r.toArray(b4, "hex") : b4; + } + r.parseBytes = h5; + function p3(b4) { + return new K2(b4, "hex", "le"); + } + r.intFromLE = p3; + }); + var kr = Jt.getNAF; + var O0 = Jt.getJSF; + var qr = Jt.assert; + function Be(e2, t) { + this.type = e2, this.p = new K2(t.p, 16), this.red = t.prime ? K2.red(t.prime) : K2.mont(this.p), this.zero = new K2(0).toRed(this.red), this.one = new K2(1).toRed(this.red), this.two = new K2(2).toRed(this.red), this.n = t.n && new K2(t.n, 16), this.g = t.g && this.pointFromJSON(t.g, t.gRed), this._wnafT1 = new Array(4), this._wnafT2 = new Array(4), this._wnafT3 = new Array(4), this._wnafT4 = new Array(4), this._bitLength = this.n ? this.n.bitLength() : 0; + var r = this.n && this.p.div(this.n); + !r || r.cmpn(100) > 0 ? this.redN = null : (this._maxwellTrick = true, this.redN = this.n.toRed(this.red)); + } + var Xe = Be; + Be.prototype.point = function() { + throw new Error("Not implemented"); + }, Be.prototype.validate = function() { + throw new Error("Not implemented"); + }, Be.prototype._fixedNafMul = function(t, r) { + qr(t.precomputed); + var i2 = t._getDoubles(), n3 = kr(r, 1, this._bitLength), o2 = (1 << i2.step + 1) - (i2.step % 2 === 0 ? 2 : 1); + o2 /= 3; + var h5 = [], p3, b4; + for (p3 = 0; p3 < n3.length; p3 += i2.step) { + b4 = 0; + for (var g3 = p3 + i2.step - 1; g3 >= p3; g3--) + b4 = (b4 << 1) + n3[g3]; + h5.push(b4); + } + for (var w4 = this.jpoint(null, null, null), y4 = this.jpoint(null, null, null), S4 = o2; S4 > 0; S4--) { + for (p3 = 0; p3 < h5.length; p3++) + b4 = h5[p3], b4 === S4 ? y4 = y4.mixedAdd(i2.points[p3]) : b4 === -S4 && (y4 = y4.mixedAdd(i2.points[p3].neg())); + w4 = w4.add(y4); + } + return w4.toP(); + }, Be.prototype._wnafMul = function(t, r) { + var i2 = 4, n3 = t._getNAFPoints(i2); + i2 = n3.wnd; + for (var o2 = n3.points, h5 = kr(r, i2, this._bitLength), p3 = this.jpoint(null, null, null), b4 = h5.length - 1; b4 >= 0; b4--) { + for (var g3 = 0; b4 >= 0 && h5[b4] === 0; b4--) + g3++; + if (b4 >= 0 && g3++, p3 = p3.dblp(g3), b4 < 0) + break; + var w4 = h5[b4]; + qr(w4 !== 0), t.type === "affine" ? w4 > 0 ? p3 = p3.mixedAdd(o2[w4 - 1 >> 1]) : p3 = p3.mixedAdd(o2[-w4 - 1 >> 1].neg()) : w4 > 0 ? p3 = p3.add(o2[w4 - 1 >> 1]) : p3 = p3.add(o2[-w4 - 1 >> 1].neg()); + } + return t.type === "affine" ? p3.toP() : p3; + }, Be.prototype._wnafMulAdd = function(t, r, i2, n3, o2) { + var h5 = this._wnafT1, p3 = this._wnafT2, b4 = this._wnafT3, g3 = 0, w4, y4, S4; + for (w4 = 0; w4 < n3; w4++) { + S4 = r[w4]; + var I2 = S4._getNAFPoints(t); + h5[w4] = I2.wnd, p3[w4] = I2.points; + } + for (w4 = n3 - 1; w4 >= 1; w4 -= 2) { + var N10 = w4 - 1, R2 = w4; + if (h5[N10] !== 1 || h5[R2] !== 1) { + b4[N10] = kr(i2[N10], h5[N10], this._bitLength), b4[R2] = kr(i2[R2], h5[R2], this._bitLength), g3 = Math.max(b4[N10].length, g3), g3 = Math.max(b4[R2].length, g3); + continue; + } + var F = [r[N10], null, null, r[R2]]; + r[N10].y.cmp(r[R2].y) === 0 ? (F[1] = r[N10].add(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())) : r[N10].y.cmp(r[R2].y.redNeg()) === 0 ? (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].add(r[R2].neg())) : (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())); + var U2 = [-3, -1, -5, -7, 0, 7, 5, 1, 3], Q = O0(i2[N10], i2[R2]); + for (g3 = Math.max(Q[0].length, g3), b4[N10] = new Array(g3), b4[R2] = new Array(g3), y4 = 0; y4 < g3; y4++) { + var Bt = Q[0][y4] | 0, J = Q[1][y4] | 0; + b4[N10][y4] = U2[(Bt + 1) * 3 + (J + 1)], b4[R2][y4] = 0, p3[N10] = F; + } + } + var H = this.jpoint(null, null, null), L2 = this._wnafT4; + for (w4 = g3; w4 >= 0; w4--) { + for (var Tt = 0; w4 >= 0; ) { + var W = true; + for (y4 = 0; y4 < n3; y4++) + L2[y4] = b4[y4][w4] | 0, L2[y4] !== 0 && (W = false); + if (!W) + break; + Tt++, w4--; + } + if (w4 >= 0 && Tt++, H = H.dblp(Tt), w4 < 0) + break; + for (y4 = 0; y4 < n3; y4++) { + var Ot = L2[y4]; + Ot !== 0 && (Ot > 0 ? S4 = p3[y4][Ot - 1 >> 1] : Ot < 0 && (S4 = p3[y4][-Ot - 1 >> 1].neg()), S4.type === "affine" ? H = H.mixedAdd(S4) : H = H.add(S4)); + } + } + for (w4 = 0; w4 < n3; w4++) + p3[w4] = null; + return o2 ? H : H.toP(); + }; + function Zt(e2, t) { + this.curve = e2, this.type = t, this.precomputed = null; + } + Be.BasePoint = Zt, Zt.prototype.eq = function() { + throw new Error("Not implemented"); + }, Zt.prototype.validate = function() { + return this.curve.validate(this); + }, Be.prototype.decodePoint = function(t, r) { + t = Jt.toArray(t, r); + var i2 = this.p.byteLength(); + if ((t[0] === 4 || t[0] === 6 || t[0] === 7) && t.length - 1 === 2 * i2) { + t[0] === 6 ? qr(t[t.length - 1] % 2 === 0) : t[0] === 7 && qr(t[t.length - 1] % 2 === 1); + var n3 = this.point(t.slice(1, 1 + i2), t.slice(1 + i2, 1 + 2 * i2)); + return n3; + } else if ((t[0] === 2 || t[0] === 3) && t.length - 1 === i2) + return this.pointFromX(t.slice(1, 1 + i2), t[0] === 3); + throw new Error("Unknown point format"); + }, Zt.prototype.encodeCompressed = function(t) { + return this.encode(t, true); + }, Zt.prototype._encode = function(t) { + var r = this.curve.p.byteLength(), i2 = this.getX().toArray("be", r); + return t ? [this.getY().isEven() ? 2 : 3].concat(i2) : [4].concat(i2, this.getY().toArray("be", r)); + }, Zt.prototype.encode = function(t, r) { + return Jt.encode(this._encode(r), t); + }, Zt.prototype.precompute = function(t) { + if (this.precomputed) + return this; + var r = { doubles: null, naf: null, beta: null }; + return r.naf = this._getNAFPoints(8), r.doubles = this._getDoubles(4, t), r.beta = this._getBeta(), this.precomputed = r, this; + }, Zt.prototype._hasDoubles = function(t) { + if (!this.precomputed) + return false; + var r = this.precomputed.doubles; + return r ? r.points.length >= Math.ceil((t.bitLength() + 1) / r.step) : false; + }, Zt.prototype._getDoubles = function(t, r) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + for (var i2 = [this], n3 = this, o2 = 0; o2 < r; o2 += t) { + for (var h5 = 0; h5 < t; h5++) + n3 = n3.dbl(); + i2.push(n3); + } + return { step: t, points: i2 }; + }, Zt.prototype._getNAFPoints = function(t) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + for (var r = [this], i2 = (1 << t) - 1, n3 = i2 === 1 ? null : this.dbl(), o2 = 1; o2 < i2; o2++) + r[o2] = r[o2 - 1].add(n3); + return { wnd: t, points: r }; + }, Zt.prototype._getBeta = function() { + return null; + }, Zt.prototype.dblp = function(t) { + for (var r = this, i2 = 0; i2 < t; i2++) + r = r.dbl(); + return r; + }; + var Fi = lr(function(e2) { + typeof Object.create == "function" ? e2.exports = function(r, i2) { + i2 && (r.super_ = i2, r.prototype = Object.create(i2.prototype, { constructor: { value: r, enumerable: false, writable: true, configurable: true } })); + } : e2.exports = function(r, i2) { + if (i2) { + r.super_ = i2; + var n3 = function() { + }; + n3.prototype = i2.prototype, r.prototype = new n3(), r.prototype.constructor = r; + } + }; + }); + var P0 = Jt.assert; + function $t(e2) { + Xe.call(this, "short", e2), this.a = new K2(e2.a, 16).toRed(this.red), this.b = new K2(e2.b, 16).toRed(this.red), this.tinv = this.two.redInvm(), this.zeroA = this.a.fromRed().cmpn(0) === 0, this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0, this.endo = this._getEndomorphism(e2), this._endoWnafT1 = new Array(4), this._endoWnafT2 = new Array(4); + } + Fi($t, Xe); + var T0 = $t; + $t.prototype._getEndomorphism = function(t) { + if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { + var r, i2; + if (t.beta) + r = new K2(t.beta, 16).toRed(this.red); + else { + var n3 = this._getEndoRoots(this.p); + r = n3[0].cmp(n3[1]) < 0 ? n3[0] : n3[1], r = r.toRed(this.red); + } + if (t.lambda) + i2 = new K2(t.lambda, 16); + else { + var o2 = this._getEndoRoots(this.n); + this.g.mul(o2[0]).x.cmp(this.g.x.redMul(r)) === 0 ? i2 = o2[0] : (i2 = o2[1], P0(this.g.mul(i2).x.cmp(this.g.x.redMul(r)) === 0)); + } + var h5; + return t.basis ? h5 = t.basis.map(function(p3) { + return { a: new K2(p3.a, 16), b: new K2(p3.b, 16) }; + }) : h5 = this._getEndoBasis(i2), { beta: r, lambda: i2, basis: h5 }; + } + }, $t.prototype._getEndoRoots = function(t) { + var r = t === this.p ? this.red : K2.mont(t), i2 = new K2(2).toRed(r).redInvm(), n3 = i2.redNeg(), o2 = new K2(3).toRed(r).redNeg().redSqrt().redMul(i2), h5 = n3.redAdd(o2).fromRed(), p3 = n3.redSub(o2).fromRed(); + return [h5, p3]; + }, $t.prototype._getEndoBasis = function(t) { + for (var r = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), i2 = t, n3 = this.n.clone(), o2 = new K2(1), h5 = new K2(0), p3 = new K2(0), b4 = new K2(1), g3, w4, y4, S4, I2, N10, R2, F = 0, U2, Q; i2.cmpn(0) !== 0; ) { + var Bt = n3.div(i2); + U2 = n3.sub(Bt.mul(i2)), Q = p3.sub(Bt.mul(o2)); + var J = b4.sub(Bt.mul(h5)); + if (!y4 && U2.cmp(r) < 0) + g3 = R2.neg(), w4 = o2, y4 = U2.neg(), S4 = Q; + else if (y4 && ++F === 2) + break; + R2 = U2, n3 = i2, i2 = U2, p3 = o2, o2 = Q, b4 = h5, h5 = J; + } + I2 = U2.neg(), N10 = Q; + var H = y4.sqr().add(S4.sqr()), L2 = I2.sqr().add(N10.sqr()); + return L2.cmp(H) >= 0 && (I2 = g3, N10 = w4), y4.negative && (y4 = y4.neg(), S4 = S4.neg()), I2.negative && (I2 = I2.neg(), N10 = N10.neg()), [{ a: y4, b: S4 }, { a: I2, b: N10 }]; + }, $t.prototype._endoSplit = function(t) { + var r = this.endo.basis, i2 = r[0], n3 = r[1], o2 = n3.b.mul(t).divRound(this.n), h5 = i2.b.neg().mul(t).divRound(this.n), p3 = o2.mul(i2.a), b4 = h5.mul(n3.a), g3 = o2.mul(i2.b), w4 = h5.mul(n3.b), y4 = t.sub(p3).sub(b4), S4 = g3.add(w4).neg(); + return { k1: y4, k2: S4 }; + }, $t.prototype.pointFromX = function(t, r) { + t = new K2(t, 16), t.red || (t = t.toRed(this.red)); + var i2 = t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b), n3 = i2.redSqrt(); + if (n3.redSqr().redSub(i2).cmp(this.zero) !== 0) + throw new Error("invalid point"); + var o2 = n3.fromRed().isOdd(); + return (r && !o2 || !r && o2) && (n3 = n3.redNeg()), this.point(t, n3); + }, $t.prototype.validate = function(t) { + if (t.inf) + return true; + var r = t.x, i2 = t.y, n3 = this.a.redMul(r), o2 = r.redSqr().redMul(r).redIAdd(n3).redIAdd(this.b); + return i2.redSqr().redISub(o2).cmpn(0) === 0; + }, $t.prototype._endoWnafMulAdd = function(t, r, i2) { + for (var n3 = this._endoWnafT1, o2 = this._endoWnafT2, h5 = 0; h5 < t.length; h5++) { + var p3 = this._endoSplit(r[h5]), b4 = t[h5], g3 = b4._getBeta(); + p3.k1.negative && (p3.k1.ineg(), b4 = b4.neg(true)), p3.k2.negative && (p3.k2.ineg(), g3 = g3.neg(true)), n3[h5 * 2] = b4, n3[h5 * 2 + 1] = g3, o2[h5 * 2] = p3.k1, o2[h5 * 2 + 1] = p3.k2; + } + for (var w4 = this._wnafMulAdd(1, n3, o2, h5 * 2, i2), y4 = 0; y4 < h5 * 2; y4++) + n3[y4] = null, o2[y4] = null; + return w4; + }; + function Dt(e2, t, r, i2) { + Xe.BasePoint.call(this, e2, "affine"), t === null && r === null ? (this.x = null, this.y = null, this.inf = true) : (this.x = new K2(t, 16), this.y = new K2(r, 16), i2 && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.inf = false); + } + Fi(Dt, Xe.BasePoint), $t.prototype.point = function(t, r, i2) { + return new Dt(this, t, r, i2); + }, $t.prototype.pointFromJSON = function(t, r) { + return Dt.fromJSON(this, t, r); + }, Dt.prototype._getBeta = function() { + if (this.curve.endo) { + var t = this.precomputed; + if (t && t.beta) + return t.beta; + var r = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (t) { + var i2 = this.curve, n3 = function(o2) { + return i2.point(o2.x.redMul(i2.endo.beta), o2.y); + }; + t.beta = r, r.precomputed = { beta: null, naf: t.naf && { wnd: t.naf.wnd, points: t.naf.points.map(n3) }, doubles: t.doubles && { step: t.doubles.step, points: t.doubles.points.map(n3) } }; + } + return r; + } + }, Dt.prototype.toJSON = function() { + return this.precomputed ? [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }] : [this.x, this.y]; + }, Dt.fromJSON = function(t, r, i2) { + typeof r == "string" && (r = JSON.parse(r)); + var n3 = t.point(r[0], r[1], i2); + if (!r[2]) + return n3; + function o2(p3) { + return t.point(p3[0], p3[1], i2); + } + var h5 = r[2]; + return n3.precomputed = { beta: null, doubles: h5.doubles && { step: h5.doubles.step, points: [n3].concat(h5.doubles.points.map(o2)) }, naf: h5.naf && { wnd: h5.naf.wnd, points: [n3].concat(h5.naf.points.map(o2)) } }, n3; + }, Dt.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }, Dt.prototype.isInfinity = function() { + return this.inf; + }, Dt.prototype.add = function(t) { + if (this.inf) + return t; + if (t.inf) + return this; + if (this.eq(t)) + return this.dbl(); + if (this.neg().eq(t)) + return this.curve.point(null, null); + if (this.x.cmp(t.x) === 0) + return this.curve.point(null, null); + var r = this.y.redSub(t.y); + r.cmpn(0) !== 0 && (r = r.redMul(this.x.redSub(t.x).redInvm())); + var i2 = r.redSqr().redISub(this.x).redISub(t.x), n3 = r.redMul(this.x.redSub(i2)).redISub(this.y); + return this.curve.point(i2, n3); + }, Dt.prototype.dbl = function() { + if (this.inf) + return this; + var t = this.y.redAdd(this.y); + if (t.cmpn(0) === 0) + return this.curve.point(null, null); + var r = this.curve.a, i2 = this.x.redSqr(), n3 = t.redInvm(), o2 = i2.redAdd(i2).redIAdd(i2).redIAdd(r).redMul(n3), h5 = o2.redSqr().redISub(this.x.redAdd(this.x)), p3 = o2.redMul(this.x.redSub(h5)).redISub(this.y); + return this.curve.point(h5, p3); + }, Dt.prototype.getX = function() { + return this.x.fromRed(); + }, Dt.prototype.getY = function() { + return this.y.fromRed(); + }, Dt.prototype.mul = function(t) { + return t = new K2(t, 16), this.isInfinity() ? this : this._hasDoubles(t) ? this.curve._fixedNafMul(this, t) : this.curve.endo ? this.curve._endoWnafMulAdd([this], [t]) : this.curve._wnafMul(this, t); + }, Dt.prototype.mulAdd = function(t, r, i2) { + var n3 = [this, r], o2 = [t, i2]; + return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2) : this.curve._wnafMulAdd(1, n3, o2, 2); + }, Dt.prototype.jmulAdd = function(t, r, i2) { + var n3 = [this, r], o2 = [t, i2]; + return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2, true) : this.curve._wnafMulAdd(1, n3, o2, 2, true); + }, Dt.prototype.eq = function(t) { + return this === t || this.inf === t.inf && (this.inf || this.x.cmp(t.x) === 0 && this.y.cmp(t.y) === 0); + }, Dt.prototype.neg = function(t) { + if (this.inf) + return this; + var r = this.curve.point(this.x, this.y.redNeg()); + if (t && this.precomputed) { + var i2 = this.precomputed, n3 = function(o2) { + return o2.neg(); + }; + r.precomputed = { naf: i2.naf && { wnd: i2.naf.wnd, points: i2.naf.points.map(n3) }, doubles: i2.doubles && { step: i2.doubles.step, points: i2.doubles.points.map(n3) } }; + } + return r; + }, Dt.prototype.toJ = function() { + if (this.inf) + return this.curve.jpoint(null, null, null); + var t = this.curve.jpoint(this.x, this.y, this.curve.one); + return t; + }; + function Ut(e2, t, r, i2) { + Xe.BasePoint.call(this, e2, "jacobian"), t === null && r === null && i2 === null ? (this.x = this.curve.one, this.y = this.curve.one, this.z = new K2(0)) : (this.x = new K2(t, 16), this.y = new K2(r, 16), this.z = new K2(i2, 16)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red)), this.zOne = this.z === this.curve.one; + } + Fi(Ut, Xe.BasePoint), $t.prototype.jpoint = function(t, r, i2) { + return new Ut(this, t, r, i2); + }, Ut.prototype.toP = function() { + if (this.isInfinity()) + return this.curve.point(null, null); + var t = this.z.redInvm(), r = t.redSqr(), i2 = this.x.redMul(r), n3 = this.y.redMul(r).redMul(t); + return this.curve.point(i2, n3); + }, Ut.prototype.neg = function() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }, Ut.prototype.add = function(t) { + if (this.isInfinity()) + return t; + if (t.isInfinity()) + return this; + var r = t.z.redSqr(), i2 = this.z.redSqr(), n3 = this.x.redMul(r), o2 = t.x.redMul(i2), h5 = this.y.redMul(r.redMul(t.z)), p3 = t.y.redMul(i2.redMul(this.z)), b4 = n3.redSub(o2), g3 = h5.redSub(p3); + if (b4.cmpn(0) === 0) + return g3.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var w4 = b4.redSqr(), y4 = w4.redMul(b4), S4 = n3.redMul(w4), I2 = g3.redSqr().redIAdd(y4).redISub(S4).redISub(S4), N10 = g3.redMul(S4.redISub(I2)).redISub(h5.redMul(y4)), R2 = this.z.redMul(t.z).redMul(b4); + return this.curve.jpoint(I2, N10, R2); + }, Ut.prototype.mixedAdd = function(t) { + if (this.isInfinity()) + return t.toJ(); + if (t.isInfinity()) + return this; + var r = this.z.redSqr(), i2 = this.x, n3 = t.x.redMul(r), o2 = this.y, h5 = t.y.redMul(r).redMul(this.z), p3 = i2.redSub(n3), b4 = o2.redSub(h5); + if (p3.cmpn(0) === 0) + return b4.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var g3 = p3.redSqr(), w4 = g3.redMul(p3), y4 = i2.redMul(g3), S4 = b4.redSqr().redIAdd(w4).redISub(y4).redISub(y4), I2 = b4.redMul(y4.redISub(S4)).redISub(o2.redMul(w4)), N10 = this.z.redMul(p3); + return this.curve.jpoint(S4, I2, N10); + }, Ut.prototype.dblp = function(t) { + if (t === 0) + return this; + if (this.isInfinity()) + return this; + if (!t) + return this.dbl(); + var r; + if (this.curve.zeroA || this.curve.threeA) { + var i2 = this; + for (r = 0; r < t; r++) + i2 = i2.dbl(); + return i2; + } + var n3 = this.curve.a, o2 = this.curve.tinv, h5 = this.x, p3 = this.y, b4 = this.z, g3 = b4.redSqr().redSqr(), w4 = p3.redAdd(p3); + for (r = 0; r < t; r++) { + var y4 = h5.redSqr(), S4 = w4.redSqr(), I2 = S4.redSqr(), N10 = y4.redAdd(y4).redIAdd(y4).redIAdd(n3.redMul(g3)), R2 = h5.redMul(S4), F = N10.redSqr().redISub(R2.redAdd(R2)), U2 = R2.redISub(F), Q = N10.redMul(U2); + Q = Q.redIAdd(Q).redISub(I2); + var Bt = w4.redMul(b4); + r + 1 < t && (g3 = g3.redMul(I2)), h5 = F, b4 = Bt, w4 = Q; + } + return this.curve.jpoint(h5, w4.redMul(o2), b4); + }, Ut.prototype.dbl = function() { + return this.isInfinity() ? this : this.curve.zeroA ? this._zeroDbl() : this.curve.threeA ? this._threeDbl() : this._dbl(); + }, Ut.prototype._zeroDbl = function() { + var t, r, i2; + if (this.zOne) { + var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); + p3 = p3.redIAdd(p3); + var b4 = n3.redAdd(n3).redIAdd(n3), g3 = b4.redSqr().redISub(p3).redISub(p3), w4 = h5.redIAdd(h5); + w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), t = g3, r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); + } else { + var y4 = this.x.redSqr(), S4 = this.y.redSqr(), I2 = S4.redSqr(), N10 = this.x.redAdd(S4).redSqr().redISub(y4).redISub(I2); + N10 = N10.redIAdd(N10); + var R2 = y4.redAdd(y4).redIAdd(y4), F = R2.redSqr(), U2 = I2.redIAdd(I2); + U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), t = F.redISub(N10).redISub(N10), r = R2.redMul(N10.redISub(t)).redISub(U2), i2 = this.y.redMul(this.z), i2 = i2.redIAdd(i2); + } + return this.curve.jpoint(t, r, i2); + }, Ut.prototype._threeDbl = function() { + var t, r, i2; + if (this.zOne) { + var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); + p3 = p3.redIAdd(p3); + var b4 = n3.redAdd(n3).redIAdd(n3).redIAdd(this.curve.a), g3 = b4.redSqr().redISub(p3).redISub(p3); + t = g3; + var w4 = h5.redIAdd(h5); + w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); + } else { + var y4 = this.z.redSqr(), S4 = this.y.redSqr(), I2 = this.x.redMul(S4), N10 = this.x.redSub(y4).redMul(this.x.redAdd(y4)); + N10 = N10.redAdd(N10).redIAdd(N10); + var R2 = I2.redIAdd(I2); + R2 = R2.redIAdd(R2); + var F = R2.redAdd(R2); + t = N10.redSqr().redISub(F), i2 = this.y.redAdd(this.z).redSqr().redISub(S4).redISub(y4); + var U2 = S4.redSqr(); + U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), r = N10.redMul(R2.redISub(t)).redISub(U2); + } + return this.curve.jpoint(t, r, i2); + }, Ut.prototype._dbl = function() { + var t = this.curve.a, r = this.x, i2 = this.y, n3 = this.z, o2 = n3.redSqr().redSqr(), h5 = r.redSqr(), p3 = i2.redSqr(), b4 = h5.redAdd(h5).redIAdd(h5).redIAdd(t.redMul(o2)), g3 = r.redAdd(r); + g3 = g3.redIAdd(g3); + var w4 = g3.redMul(p3), y4 = b4.redSqr().redISub(w4.redAdd(w4)), S4 = w4.redISub(y4), I2 = p3.redSqr(); + I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); + var N10 = b4.redMul(S4).redISub(I2), R2 = i2.redAdd(i2).redMul(n3); + return this.curve.jpoint(y4, N10, R2); + }, Ut.prototype.trpl = function() { + if (!this.curve.zeroA) + return this.dbl().add(this); + var t = this.x.redSqr(), r = this.y.redSqr(), i2 = this.z.redSqr(), n3 = r.redSqr(), o2 = t.redAdd(t).redIAdd(t), h5 = o2.redSqr(), p3 = this.x.redAdd(r).redSqr().redISub(t).redISub(n3); + p3 = p3.redIAdd(p3), p3 = p3.redAdd(p3).redIAdd(p3), p3 = p3.redISub(h5); + var b4 = p3.redSqr(), g3 = n3.redIAdd(n3); + g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3); + var w4 = o2.redIAdd(p3).redSqr().redISub(h5).redISub(b4).redISub(g3), y4 = r.redMul(w4); + y4 = y4.redIAdd(y4), y4 = y4.redIAdd(y4); + var S4 = this.x.redMul(b4).redISub(y4); + S4 = S4.redIAdd(S4), S4 = S4.redIAdd(S4); + var I2 = this.y.redMul(w4.redMul(g3.redISub(w4)).redISub(p3.redMul(b4))); + I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); + var N10 = this.z.redAdd(p3).redSqr().redISub(i2).redISub(b4); + return this.curve.jpoint(S4, I2, N10); + }, Ut.prototype.mul = function(t, r) { + return t = new K2(t, r), this.curve._wnafMul(this, t); + }, Ut.prototype.eq = function(t) { + if (t.type === "affine") + return this.eq(t.toJ()); + if (this === t) + return true; + var r = this.z.redSqr(), i2 = t.z.redSqr(); + if (this.x.redMul(i2).redISub(t.x.redMul(r)).cmpn(0) !== 0) + return false; + var n3 = r.redMul(this.z), o2 = i2.redMul(t.z); + return this.y.redMul(o2).redISub(t.y.redMul(n3)).cmpn(0) === 0; + }, Ut.prototype.eqXToP = function(t) { + var r = this.z.redSqr(), i2 = t.toRed(this.curve.red).redMul(r); + if (this.x.cmp(i2) === 0) + return true; + for (var n3 = t.clone(), o2 = this.curve.redN.redMul(r); ; ) { + if (n3.iadd(this.curve.n), n3.cmp(this.curve.p) >= 0) + return false; + if (i2.redIAdd(o2), this.x.cmp(i2) === 0) + return true; + } + }, Ut.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }, Ut.prototype.isInfinity = function() { + return this.z.cmpn(0) === 0; + }; + var Kr = lr(function(e2, t) { + var r = t; + r.base = Xe, r.short = T0, r.mont = null, r.edwards = null; + }); + var Hr = lr(function(e2, t) { + var r = t, i2 = Jt.assert; + function n3(p3) { + p3.type === "short" ? this.curve = new Kr.short(p3) : p3.type === "edwards" ? this.curve = new Kr.edwards(p3) : this.curve = new Kr.mont(p3), this.g = this.curve.g, this.n = this.curve.n, this.hash = p3.hash, i2(this.g.validate(), "Invalid curve"), i2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); + } + r.PresetCurve = n3; + function o2(p3, b4) { + Object.defineProperty(r, p3, { configurable: true, enumerable: true, get: function() { + var g3 = new n3(b4); + return Object.defineProperty(r, p3, { configurable: true, enumerable: true, value: g3 }), g3; + } }); + } + o2("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: oe.sha256, gRed: false, g: ["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"] }), o2("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: oe.sha256, gRed: false, g: ["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"] }), o2("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: oe.sha256, gRed: false, g: ["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"] }), o2("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: oe.sha384, gRed: false, g: ["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"] }), o2("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: oe.sha512, gRed: false, g: ["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"] }), o2("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["9"] }), o2("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", "6666666666666666666666666666666666666666666666666666666666666658"] }); + var h5; + try { + h5 = null.crash(); + } catch { + h5 = void 0; + } + o2("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: oe.sha256, beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [{ a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" }], gRed: false, g: ["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", h5] }); + }); + function Re(e2) { + if (!(this instanceof Re)) + return new Re(e2); + this.hash = e2.hash, this.predResist = !!e2.predResist, this.outLen = this.hash.outSize, this.minEntropy = e2.minEntropy || this.hash.hmacStrength, this._reseed = null, this.reseedInterval = null, this.K = null, this.V = null; + var t = ne.toArray(e2.entropy, e2.entropyEnc || "hex"), r = ne.toArray(e2.nonce, e2.nonceEnc || "hex"), i2 = ne.toArray(e2.pers, e2.persEnc || "hex"); + Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._init(t, r, i2); + } + var If = Re; + Re.prototype._init = function(t, r, i2) { + var n3 = t.concat(r).concat(i2); + this.K = new Array(this.outLen / 8), this.V = new Array(this.outLen / 8); + for (var o2 = 0; o2 < this.V.length; o2++) + this.K[o2] = 0, this.V[o2] = 1; + this._update(n3), this._reseed = 1, this.reseedInterval = 281474976710656; + }, Re.prototype._hmac = function() { + return new oe.hmac(this.hash, this.K); + }, Re.prototype._update = function(t) { + var r = this._hmac().update(this.V).update([0]); + t && (r = r.update(t)), this.K = r.digest(), this.V = this._hmac().update(this.V).digest(), t && (this.K = this._hmac().update(this.V).update([1]).update(t).digest(), this.V = this._hmac().update(this.V).digest()); + }, Re.prototype.reseed = function(t, r, i2, n3) { + typeof r != "string" && (n3 = i2, i2 = r, r = null), t = ne.toArray(t, r), i2 = ne.toArray(i2, n3), Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._update(t.concat(i2 || [])), this._reseed = 1; + }, Re.prototype.generate = function(t, r, i2, n3) { + if (this._reseed > this.reseedInterval) + throw new Error("Reseed is required"); + typeof r != "string" && (n3 = i2, i2 = r, r = null), i2 && (i2 = ne.toArray(i2, n3 || "hex"), this._update(i2)); + for (var o2 = []; o2.length < t; ) + this.V = this._hmac().update(this.V).digest(), o2 = o2.concat(this.V); + var h5 = o2.slice(0, t); + return this._update(i2), this._reseed++, ne.encode(h5, r); + }; + var Di = Jt.assert; + function qt(e2, t) { + this.ec = e2, this.priv = null, this.pub = null, t.priv && this._importPrivate(t.priv, t.privEnc), t.pub && this._importPublic(t.pub, t.pubEnc); + } + var Ui = qt; + qt.fromPublic = function(t, r, i2) { + return r instanceof qt ? r : new qt(t, { pub: r, pubEnc: i2 }); + }, qt.fromPrivate = function(t, r, i2) { + return r instanceof qt ? r : new qt(t, { priv: r, privEnc: i2 }); + }, qt.prototype.validate = function() { + var t = this.getPublic(); + return t.isInfinity() ? { result: false, reason: "Invalid public key" } : t.validate() ? t.mul(this.ec.curve.n).isInfinity() ? { result: true, reason: null } : { result: false, reason: "Public key * N != O" } : { result: false, reason: "Public key is not a point" }; + }, qt.prototype.getPublic = function(t, r) { + return typeof t == "string" && (r = t, t = null), this.pub || (this.pub = this.ec.g.mul(this.priv)), r ? this.pub.encode(r, t) : this.pub; + }, qt.prototype.getPrivate = function(t) { + return t === "hex" ? this.priv.toString(16, 2) : this.priv; + }, qt.prototype._importPrivate = function(t, r) { + this.priv = new K2(t, r || 16), this.priv = this.priv.umod(this.ec.curve.n); + }, qt.prototype._importPublic = function(t, r) { + if (t.x || t.y) { + this.ec.curve.type === "mont" ? Di(t.x, "Need x coordinate") : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && Di(t.x && t.y, "Need both x and y coordinate"), this.pub = this.ec.curve.point(t.x, t.y); + return; + } + this.pub = this.ec.curve.decodePoint(t, r); + }, qt.prototype.derive = function(t) { + return t.validate() || Di(t.validate(), "public point not validated"), t.mul(this.priv).getX(); + }, qt.prototype.sign = function(t, r, i2) { + return this.ec.sign(t, this, r, i2); + }, qt.prototype.verify = function(t, r) { + return this.ec.verify(t, r, this); + }, qt.prototype.inspect = function() { + return ""; + }; + var F0 = Jt.assert; + function Lr(e2, t) { + if (e2 instanceof Lr) + return e2; + this._importDER(e2, t) || (F0(e2.r && e2.s, "Signature without r or s"), this.r = new K2(e2.r, 16), this.s = new K2(e2.s, 16), e2.recoveryParam === void 0 ? this.recoveryParam = null : this.recoveryParam = e2.recoveryParam); + } + var zr = Lr; + function D0() { + this.place = 0; + } + function ki(e2, t) { + var r = e2[t.place++]; + if (!(r & 128)) + return r; + var i2 = r & 15; + if (i2 === 0 || i2 > 4) + return false; + for (var n3 = 0, o2 = 0, h5 = t.place; o2 < i2; o2++, h5++) + n3 <<= 8, n3 |= e2[h5], n3 >>>= 0; + return n3 <= 127 ? false : (t.place = h5, n3); + } + function _f(e2) { + for (var t = 0, r = e2.length - 1; !e2[t] && !(e2[t + 1] & 128) && t < r; ) + t++; + return t === 0 ? e2 : e2.slice(t); + } + Lr.prototype._importDER = function(t, r) { + t = Jt.toArray(t, r); + var i2 = new D0(); + if (t[i2.place++] !== 48) + return false; + var n3 = ki(t, i2); + if (n3 === false || n3 + i2.place !== t.length || t[i2.place++] !== 2) + return false; + var o2 = ki(t, i2); + if (o2 === false) + return false; + var h5 = t.slice(i2.place, o2 + i2.place); + if (i2.place += o2, t[i2.place++] !== 2) + return false; + var p3 = ki(t, i2); + if (p3 === false || t.length !== p3 + i2.place) + return false; + var b4 = t.slice(i2.place, p3 + i2.place); + if (h5[0] === 0) + if (h5[1] & 128) + h5 = h5.slice(1); + else + return false; + if (b4[0] === 0) + if (b4[1] & 128) + b4 = b4.slice(1); + else + return false; + return this.r = new K2(h5), this.s = new K2(b4), this.recoveryParam = null, true; + }; + function qi(e2, t) { + if (t < 128) { + e2.push(t); + return; + } + var r = 1 + (Math.log(t) / Math.LN2 >>> 3); + for (e2.push(r | 128); --r; ) + e2.push(t >>> (r << 3) & 255); + e2.push(t); + } + Lr.prototype.toDER = function(t) { + var r = this.r.toArray(), i2 = this.s.toArray(); + for (r[0] & 128 && (r = [0].concat(r)), i2[0] & 128 && (i2 = [0].concat(i2)), r = _f(r), i2 = _f(i2); !i2[0] && !(i2[1] & 128); ) + i2 = i2.slice(1); + var n3 = [2]; + qi(n3, r.length), n3 = n3.concat(r), n3.push(2), qi(n3, i2.length); + var o2 = n3.concat(i2), h5 = [48]; + return qi(h5, o2.length), h5 = h5.concat(o2), Jt.encode(h5, t); + }; + var U0 = function() { + throw new Error("unsupported"); + }; + var Bf = Jt.assert; + function te(e2) { + if (!(this instanceof te)) + return new te(e2); + typeof e2 == "string" && (Bf(Object.prototype.hasOwnProperty.call(Hr, e2), "Unknown curve " + e2), e2 = Hr[e2]), e2 instanceof Hr.PresetCurve && (e2 = { curve: e2 }), this.curve = e2.curve.curve, this.n = this.curve.n, this.nh = this.n.ushrn(1), this.g = this.curve.g, this.g = e2.curve.g, this.g.precompute(e2.curve.n.bitLength() + 1), this.hash = e2.hash || e2.curve.hash; + } + var k0 = te; + te.prototype.keyPair = function(t) { + return new Ui(this, t); + }, te.prototype.keyFromPrivate = function(t, r) { + return Ui.fromPrivate(this, t, r); + }, te.prototype.keyFromPublic = function(t, r) { + return Ui.fromPublic(this, t, r); + }, te.prototype.genKeyPair = function(t) { + t || (t = {}); + for (var r = new If({ hash: this.hash, pers: t.pers, persEnc: t.persEnc || "utf8", entropy: t.entropy || U0(this.hash.hmacStrength), entropyEnc: t.entropy && t.entropyEnc || "utf8", nonce: this.n.toArray() }), i2 = this.n.byteLength(), n3 = this.n.sub(new K2(2)); ; ) { + var o2 = new K2(r.generate(i2)); + if (!(o2.cmp(n3) > 0)) + return o2.iaddn(1), this.keyFromPrivate(o2); + } + }, te.prototype._truncateToN = function(t, r) { + var i2 = t.byteLength() * 8 - this.n.bitLength(); + return i2 > 0 && (t = t.ushrn(i2)), !r && t.cmp(this.n) >= 0 ? t.sub(this.n) : t; + }, te.prototype.sign = function(t, r, i2, n3) { + typeof i2 == "object" && (n3 = i2, i2 = null), n3 || (n3 = {}), r = this.keyFromPrivate(r, i2), t = this._truncateToN(new K2(t, 16)); + for (var o2 = this.n.byteLength(), h5 = r.getPrivate().toArray("be", o2), p3 = t.toArray("be", o2), b4 = new If({ hash: this.hash, entropy: h5, nonce: p3, pers: n3.pers, persEnc: n3.persEnc || "utf8" }), g3 = this.n.sub(new K2(1)), w4 = 0; ; w4++) { + var y4 = n3.k ? n3.k(w4) : new K2(b4.generate(this.n.byteLength())); + if (y4 = this._truncateToN(y4, true), !(y4.cmpn(1) <= 0 || y4.cmp(g3) >= 0)) { + var S4 = this.g.mul(y4); + if (!S4.isInfinity()) { + var I2 = S4.getX(), N10 = I2.umod(this.n); + if (N10.cmpn(0) !== 0) { + var R2 = y4.invm(this.n).mul(N10.mul(r.getPrivate()).iadd(t)); + if (R2 = R2.umod(this.n), R2.cmpn(0) !== 0) { + var F = (S4.getY().isOdd() ? 1 : 0) | (I2.cmp(N10) !== 0 ? 2 : 0); + return n3.canonical && R2.cmp(this.nh) > 0 && (R2 = this.n.sub(R2), F ^= 1), new zr({ r: N10, s: R2, recoveryParam: F }); + } + } + } + } + } + }, te.prototype.verify = function(t, r, i2, n3) { + t = this._truncateToN(new K2(t, 16)), i2 = this.keyFromPublic(i2, n3), r = new zr(r, "hex"); + var o2 = r.r, h5 = r.s; + if (o2.cmpn(1) < 0 || o2.cmp(this.n) >= 0 || h5.cmpn(1) < 0 || h5.cmp(this.n) >= 0) + return false; + var p3 = h5.invm(this.n), b4 = p3.mul(t).umod(this.n), g3 = p3.mul(o2).umod(this.n), w4; + return this.curve._maxwellTrick ? (w4 = this.g.jmulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.eqXToP(o2)) : (w4 = this.g.mulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.getX().umod(this.n).cmp(o2) === 0); + }, te.prototype.recoverPubKey = function(e2, t, r, i2) { + Bf((3 & r) === r, "The recovery param is more than two bits"), t = new zr(t, i2); + var n3 = this.n, o2 = new K2(e2), h5 = t.r, p3 = t.s, b4 = r & 1, g3 = r >> 1; + if (h5.cmp(this.curve.p.umod(this.curve.n)) >= 0 && g3) + throw new Error("Unable to find sencond key candinate"); + g3 ? h5 = this.curve.pointFromX(h5.add(this.curve.n), b4) : h5 = this.curve.pointFromX(h5, b4); + var w4 = t.r.invm(n3), y4 = n3.sub(o2).mul(w4).umod(n3), S4 = p3.mul(w4).umod(n3); + return this.g.mulAdd(y4, h5, S4); + }, te.prototype.getKeyRecoveryParam = function(e2, t, r, i2) { + if (t = new zr(t, i2), t.recoveryParam !== null) + return t.recoveryParam; + for (var n3 = 0; n3 < 4; n3++) { + var o2; + try { + o2 = this.recoverPubKey(e2, t, n3); + } catch { + continue; + } + if (o2.eq(r)) + return n3; + } + throw new Error("Unable to find valid recovery factor"); + }; + var q0 = lr(function(e2, t) { + var r = t; + r.version = "6.5.4", r.utils = Jt, r.rand = function() { + throw new Error("unsupported"); + }, r.curve = Kr, r.curves = Hr, r.ec = k0, r.eddsa = null; + }); + var K0 = q0.ec; + var H0 = "signing-key/5.7.0"; + var Ki = new z3(H0); + var Hi = null; + function pe() { + return Hi || (Hi = new K0("secp256k1")), Hi; + } + var L0 = class { + constructor(t) { + yr(this, "curve", "secp256k1"), yr(this, "privateKey", Ht(t)), xs(this.privateKey) !== 32 && Ki.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); + const r = pe().keyFromPrivate(Pt(this.privateKey)); + yr(this, "publicKey", "0x" + r.getPublic(false, "hex")), yr(this, "compressedPublicKey", "0x" + r.getPublic(true, "hex")), yr(this, "_isSigningKey", true); + } + _addPoint(t) { + const r = pe().keyFromPublic(Pt(this.publicKey)), i2 = pe().keyFromPublic(Pt(t)); + return "0x" + r.pub.add(i2.pub).encodeCompressed("hex"); + } + signDigest(t) { + const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = Pt(t); + i2.length !== 32 && Ki.throwArgumentError("bad digest length", "digest", t); + const n3 = r.sign(i2, { canonical: true }); + return kn({ recoveryParam: n3.recoveryParam, r: fe("0x" + n3.r.toString(16), 32), s: fe("0x" + n3.s.toString(16), 32) }); + } + computeSharedSecret(t) { + const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = pe().keyFromPublic(Pt(Rf(t))); + return fe("0x" + r.derive(i2.getPublic()).toString(16), 32); + } + static isSigningKey(t) { + return !!(t && t._isSigningKey); + } + }; + function z0(e2, t) { + const r = kn(t), i2 = { r: Pt(r.r), s: Pt(r.s) }; + return "0x" + pe().recoverPubKey(Pt(e2), i2, r.recoveryParam).encode("hex", false); + } + function Rf(e2, t) { + const r = Pt(e2); + if (r.length === 32) { + const i2 = new L0(r); + return t ? "0x" + pe().keyFromPrivate(r).getPublic(true, "hex") : i2.publicKey; + } else { + if (r.length === 33) + return t ? Ht(r) : "0x" + pe().keyFromPublic(r).getPublic(false, "hex"); + if (r.length === 65) + return t ? "0x" + pe().keyFromPublic(r).getPublic(true, "hex") : Ht(r); + } + return Ki.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); + } + var j0 = "transactions/5.7.0"; + new z3(j0); + var Cf; + (function(e2) { + e2[e2.legacy = 0] = "legacy", e2[e2.eip2930 = 1] = "eip2930", e2[e2.eip1559 = 2] = "eip1559"; + })(Cf || (Cf = {})); + function V0(e2) { + const t = Rf(e2); + return ta(Un(wi(Un(t, 1)), 12)); + } + function Q0(e2, t) { + return V0(z0(Pt(e2), t)); + } + var J0 = "https://rpc.walletconnect.com/v1"; + async function Of(e2, t, r, i2, n3, o2) { + switch (r.t) { + case "eip191": + return Pf(e2, t, r.s); + case "eip1271": + return await Tf(e2, t, r.s, i2, n3, o2); + default: + throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`); + } + } + function Pf(e2, t, r) { + return Q0(tf(t), r).toLowerCase() === e2.toLowerCase(); + } + async function Tf(e2, t, r, i2, n3, o2) { + try { + const h5 = "0x1626ba7e", p3 = "0000000000000000000000000000000000000000000000000000000000000040", b4 = "0000000000000000000000000000000000000000000000000000000000000041", g3 = r.substring(2), w4 = tf(t).substring(2), y4 = h5 + w4 + p3 + b4 + g3, S4 = await fetch(`${o2 || J0}/?chainId=${i2}&projectId=${n3}`, { method: "POST", body: JSON.stringify({ id: Y0(), jsonrpc: "2.0", method: "eth_call", params: [{ to: e2, data: y4 }, "latest"] }) }), { result: I2 } = await S4.json(); + return I2 ? I2.slice(0, h5.length).toLowerCase() === h5.toLowerCase() : false; + } catch (h5) { + return console.error("isValidEip1271Signature: ", h5), false; + } + } + function Y0() { + return Date.now() + Math.floor(Math.random() * 1e3); + } + var G0 = Object.defineProperty; + var W0 = Object.defineProperties; + var X0 = Object.getOwnPropertyDescriptors; + var Ff = Object.getOwnPropertySymbols; + var Z0 = Object.prototype.hasOwnProperty; + var $0 = Object.prototype.propertyIsEnumerable; + var Df = (e2, t, r) => t in e2 ? G0(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var Li = (e2, t) => { + for (var r in t || (t = {})) + Z0.call(t, r) && Df(e2, r, t[r]); + if (Ff) + for (var r of Ff(t)) + $0.call(t, r) && Df(e2, r, t[r]); + return e2; + }; + var Uf = (e2, t) => W0(e2, X0(t)); + var tu = "did:pkh:"; + var jr = (e2) => e2?.split(":"); + var zi = (e2) => { + const t = e2 && jr(e2); + if (t) + return e2.includes(tu) ? t[3] : t[1]; + }; + var eu = (e2) => { + const t = e2 && jr(e2); + if (t) + return t[2] + ":" + t[3]; + }; + var ji = (e2) => { + const t = e2 && jr(e2); + if (t) + return t.pop(); + }; + async function ru(e2) { + const { cacao: t, projectId: r } = e2, { s: i2, p: n3 } = t, o2 = kf(n3, n3.iss), h5 = ji(n3.iss); + return await Of(h5, o2, i2, zi(n3.iss), r); + } + var kf = (e2, t) => { + const r = `${e2.domain} wants you to sign in with your Ethereum account:`, i2 = ji(t); + if (!e2.aud && !e2.uri) + throw new Error("Either `aud` or `uri` is required to construct the message"); + let n3 = e2.statement || void 0; + const o2 = `URI: ${e2.aud || e2.uri}`, h5 = `Version: ${e2.version}`, p3 = `Chain ID: ${zi(t)}`, b4 = `Nonce: ${e2.nonce}`, g3 = `Issued At: ${e2.iat}`, w4 = e2.resources ? `Resources:${e2.resources.map((S4) => ` +- ${S4}`).join("")}` : void 0, y4 = Qr(e2.resources); + if (y4) { + const S4 = Ce(y4); + n3 = Ji(n3, S4); + } + return [r, i2, "", n3, "", o2, h5, p3, b4, g3, w4].filter((S4) => S4 != null).join(` +`); + }; + function iu(e2, t, r) { + return r.includes("did:pkh:") || (r = `did:pkh:${r}`), { h: { t: "caip122" }, p: { iss: r, domain: e2.domain, aud: e2.aud, version: e2.version, nonce: e2.nonce, iat: e2.iat, statement: e2.statement, requestId: e2.requestId, resources: e2.resources, nbf: e2.nbf, exp: e2.exp }, s: t }; + } + function nu(e2) { + var t; + const { authPayload: r, chains: i2, methods: n3 } = e2, o2 = r.statement || ""; + if (!(i2 != null && i2.length)) + return r; + const h5 = r.chains, p3 = mi(h5, i2); + if (!(p3 != null && p3.length)) + throw new Error("No supported chains"); + const b4 = qf(r.resources); + if (!b4) + return r; + ve(b4); + const g3 = Kf(b4, "eip155"); + let w4 = r?.resources || []; + if (g3 != null && g3.length) { + const y4 = Hf(g3), S4 = mi(y4, n3); + if (!(S4 != null && S4.length)) + throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(y4)}, supported: ${JSON.stringify(n3)}`); + const I2 = Vi("request", S4, { chains: p3 }), N10 = Vf(b4, "eip155", I2); + w4 = ((t = r?.resources) == null ? void 0 : t.slice(0, -1)) || [], w4.push(Vr(N10)); + } + return Uf(Li({}, r), { statement: Jf(o2, Qr(w4)), chains: p3, resources: r != null && r.resources || w4.length > 0 ? w4 : void 0 }); + } + function qf(e2) { + const t = Qr(e2); + if (t && Qi(t)) + return Ce(t); + } + function fu(e2, t) { + var r; + return (r = e2?.att) == null ? void 0 : r.hasOwnProperty(t); + } + function Kf(e2, t) { + var r, i2; + return (r = e2?.att) != null && r[t] ? Object.keys((i2 = e2?.att) == null ? void 0 : i2[t]) : []; + } + function ou(e2) { + return e2?.map((t) => Object.keys(t)) || []; + } + function Hf(e2) { + return e2?.map((t) => { + var r; + return (r = t.split("/")) == null ? void 0 : r[1]; + }) || []; + } + function Lf(e2) { + return import_buffer.Buffer.from(JSON.stringify(e2)).toString("base64"); + } + function zf(e2) { + return JSON.parse(import_buffer.Buffer.from(e2, "base64").toString("utf-8")); + } + function ve(e2) { + if (!e2) + throw new Error("No recap provided, value is undefined"); + if (!e2.att) + throw new Error("No `att` property found"); + const t = Object.keys(e2.att); + if (!(t != null && t.length)) + throw new Error("No resources found in `att` property"); + t.forEach((r) => { + const i2 = e2.att[r]; + if (Array.isArray(i2)) + throw new Error(`Resource must be an object: ${r}`); + if (typeof i2 != "object") + throw new Error(`Resource must be an object: ${r}`); + if (!Object.keys(i2).length) + throw new Error(`Resource object is empty: ${r}`); + Object.keys(i2).forEach((n3) => { + const o2 = i2[n3]; + if (!Array.isArray(o2)) + throw new Error(`Ability limits ${n3} must be an array of objects, found: ${o2}`); + if (!o2.length) + throw new Error(`Value of ${n3} is empty array, must be an array with objects`); + o2.forEach((h5) => { + if (typeof h5 != "object") + throw new Error(`Ability limits (${n3}) must be an array of objects, found: ${h5}`); + }); + }); + }); + } + function jf(e2, t, r, i2 = {}) { + return r?.sort((n3, o2) => n3.localeCompare(o2)), { att: { [e2]: Vi(t, r, i2) } }; + } + function Vf(e2, t, r) { + var i2; + return e2.att[t] = Li({}, r), ((i2 = Object.keys(e2.att)) == null ? void 0 : i2.sort((n3, o2) => n3.localeCompare(o2))).reduce((n3, o2) => (n3.att[o2] = e2.att[o2], n3), { att: {} }); + } + function Vi(e2, t, r = {}) { + t = t?.sort((n3, o2) => n3.localeCompare(o2)); + const i2 = t.map((n3) => ({ [`${e2}/${n3}`]: [r] })); + return Object.assign({}, ...i2); + } + function Vr(e2) { + return ve(e2), `urn:recap:${Lf(e2).replace(/=/g, "")}`; + } + function Ce(e2) { + const t = zf(e2.replace("urn:recap:", "")); + return ve(t), t; + } + function su(e2, t, r) { + const i2 = jf(e2, t, r); + return Vr(i2); + } + function Qi(e2) { + return e2 && e2.includes("urn:recap:"); + } + function au(e2, t) { + const r = Ce(e2), i2 = Ce(t), n3 = Qf(r, i2); + return Vr(n3); + } + function Qf(e2, t) { + ve(e2), ve(t); + const r = Object.keys(e2.att).concat(Object.keys(t.att)).sort((n3, o2) => n3.localeCompare(o2)), i2 = { att: {} }; + return r.forEach((n3) => { + var o2, h5; + Object.keys(((o2 = e2.att) == null ? void 0 : o2[n3]) || {}).concat(Object.keys(((h5 = t.att) == null ? void 0 : h5[n3]) || {})).sort((p3, b4) => p3.localeCompare(b4)).forEach((p3) => { + var b4, g3; + i2.att[n3] = Uf(Li({}, i2.att[n3]), { [p3]: ((b4 = e2.att[n3]) == null ? void 0 : b4[p3]) || ((g3 = t.att[n3]) == null ? void 0 : g3[p3]) }); + }); + }), i2; + } + function Ji(e2 = "", t) { + ve(t); + const r = "I further authorize the stated URI to perform the following actions on my behalf: "; + if (e2.includes(r)) + return e2; + const i2 = []; + let n3 = 0; + Object.keys(t.att).forEach((p3) => { + const b4 = Object.keys(t.att[p3]).map((y4) => ({ ability: y4.split("/")[0], action: y4.split("/")[1] })); + b4.sort((y4, S4) => y4.action.localeCompare(S4.action)); + const g3 = {}; + b4.forEach((y4) => { + g3[y4.ability] || (g3[y4.ability] = []), g3[y4.ability].push(y4.action); + }); + const w4 = Object.keys(g3).map((y4) => (n3++, `(${n3}) '${y4}': '${g3[y4].join("', '")}' for '${p3}'.`)); + i2.push(w4.join(", ").replace(".,", ".")); + }); + const o2 = i2.join(" "), h5 = `${r}${o2}`; + return `${e2 ? e2 + " " : ""}${h5}`; + } + function uu(e2) { + var t; + const r = Ce(e2); + ve(r); + const i2 = (t = r.att) == null ? void 0 : t.eip155; + return i2 ? Object.keys(i2).map((n3) => n3.split("/")[1]) : []; + } + function hu(e2) { + const t = Ce(e2); + ve(t); + const r = []; + return Object.values(t.att).forEach((i2) => { + Object.values(i2).forEach((n3) => { + var o2; + (o2 = n3?.[0]) != null && o2.chains && r.push(n3[0].chains); + }); + }), [...new Set(r.flat())]; + } + function Jf(e2, t) { + if (!t) + return e2; + const r = Ce(t); + return ve(r), Ji(e2, r); + } + function Qr(e2) { + if (!e2) + return; + const t = e2?.[e2.length - 1]; + return Qi(t) ? t : void 0; + } + var Yi = "base10"; + var zt = "base16"; + var Jr = "base64pad"; + var Yr = "utf8"; + var Gi = 0; + var dr = 1; + var cu = 0; + var Yf = 1; + var Wi = 12; + var Xi = 32; + function lu() { + const e2 = an.generateKeyPair(); + return { privateKey: Rt.toString(e2.secretKey, zt), publicKey: Rt.toString(e2.publicKey, zt) }; + } + function du() { + const e2 = on.randomBytes(Xi); + return Rt.toString(e2, zt); + } + function pu(e2, t) { + const r = an.sharedKey(Rt.fromString(e2, zt), Rt.fromString(t, zt), true), i2 = new Po.HKDF(ci.SHA256, r).expand(Xi); + return Rt.toString(i2, zt); + } + function vu(e2) { + const t = ci.hash(Rt.fromString(e2, zt)); + return Rt.toString(t, zt); + } + function gu(e2) { + const t = ci.hash(Rt.fromString(e2, Yr)); + return Rt.toString(t, zt); + } + function Gf(e2) { + return Rt.fromString(`${e2}`, Yi); + } + function Er(e2) { + return Number(Rt.toString(e2, Yi)); + } + function mu(e2) { + const t = Gf(typeof e2.type < "u" ? e2.type : Gi); + if (Er(t) === dr && typeof e2.senderPublicKey > "u") + throw new Error("Missing sender public key for type 1 envelope"); + const r = typeof e2.senderPublicKey < "u" ? Rt.fromString(e2.senderPublicKey, zt) : void 0, i2 = typeof e2.iv < "u" ? Rt.fromString(e2.iv, zt) : on.randomBytes(Wi), n3 = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)).seal(i2, Rt.fromString(e2.message, Yr)); + return Wf({ type: t, sealed: n3, iv: i2, senderPublicKey: r }); + } + function Au(e2) { + const t = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)), { sealed: r, iv: i2 } = Zi(e2.encoded), n3 = t.open(i2, r); + if (n3 === null) + throw new Error("Failed to decrypt"); + return Rt.toString(n3, Yr); + } + function Wf(e2) { + if (Er(e2.type) === dr) { + if (typeof e2.senderPublicKey > "u") + throw new Error("Missing sender public key for type 1 envelope"); + return Rt.toString(Rt.concat([e2.type, e2.senderPublicKey, e2.iv, e2.sealed]), Jr); + } + return Rt.toString(Rt.concat([e2.type, e2.iv, e2.sealed]), Jr); + } + function Zi(e2) { + const t = Rt.fromString(e2, Jr), r = t.slice(cu, Yf), i2 = Yf; + if (Er(r) === dr) { + const p3 = i2 + Xi, b4 = p3 + Wi, g3 = t.slice(i2, p3), w4 = t.slice(p3, b4), y4 = t.slice(b4); + return { type: r, sealed: y4, iv: w4, senderPublicKey: g3 }; + } + const n3 = i2 + Wi, o2 = t.slice(i2, n3), h5 = t.slice(n3); + return { type: r, sealed: h5, iv: o2 }; + } + function bu(e2, t) { + const r = Zi(e2); + return Xf({ type: Er(r.type), senderPublicKey: typeof r.senderPublicKey < "u" ? Rt.toString(r.senderPublicKey, zt) : void 0, receiverPublicKey: t?.receiverPublicKey }); + } + function Xf(e2) { + const t = e2?.type || Gi; + if (t === dr) { + if (typeof e2?.senderPublicKey > "u") + throw new Error("missing sender public key"); + if (typeof e2?.receiverPublicKey > "u") + throw new Error("missing receiver public key"); + } + return { type: t, senderPublicKey: e2?.senderPublicKey, receiverPublicKey: e2?.receiverPublicKey }; + } + function yu(e2) { + return e2.type === dr && typeof e2.senderPublicKey == "string" && typeof e2.receiverPublicKey == "string"; + } + var Zf = "irn"; + function wu(e2) { + return e2?.relay || { protocol: Zf }; + } + function xu(e2) { + const t = Fo.RELAY_JSONRPC[e2]; + if (typeof t > "u") + throw new Error(`Relay Protocol not supported: ${e2}`); + return t; + } + var Mu = Object.defineProperty; + var Eu = Object.defineProperties; + var Su = Object.getOwnPropertyDescriptors; + var $f = Object.getOwnPropertySymbols; + var Nu = Object.prototype.hasOwnProperty; + var Iu = Object.prototype.propertyIsEnumerable; + var to = (e2, t, r) => t in e2 ? Mu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var eo = (e2, t) => { + for (var r in t || (t = {})) + Nu.call(t, r) && to(e2, r, t[r]); + if ($f) + for (var r of $f(t)) + Iu.call(t, r) && to(e2, r, t[r]); + return e2; + }; + var _u = (e2, t) => Eu(e2, Su(t)); + function ro(e2, t = "-") { + const r = {}, i2 = "relay" + t; + return Object.keys(e2).forEach((n3) => { + if (n3.startsWith(i2)) { + const o2 = n3.replace(i2, ""), h5 = e2[n3]; + r[o2] = h5; + } + }), r; + } + function Bu(e2) { + e2 = e2.includes("wc://") ? e2.replace("wc://", "") : e2, e2 = e2.includes("wc:") ? e2.replace("wc:", "") : e2; + const t = e2.indexOf(":"), r = e2.indexOf("?") !== -1 ? e2.indexOf("?") : void 0, i2 = e2.substring(0, t), n3 = e2.substring(t + 1, r).split("@"), o2 = typeof r < "u" ? e2.substring(r) : "", h5 = Ir.parse(o2), p3 = typeof h5.methods == "string" ? h5.methods.split(",") : void 0; + return { protocol: i2, topic: io(n3[0]), version: parseInt(n3[1], 10), symKey: h5.symKey, relay: ro(h5), methods: p3, expiryTimestamp: h5.expiryTimestamp ? parseInt(h5.expiryTimestamp, 10) : void 0 }; + } + function io(e2) { + return e2.startsWith("//") ? e2.substring(2) : e2; + } + function no(e2, t = "-") { + const r = "relay", i2 = {}; + return Object.keys(e2).forEach((n3) => { + const o2 = r + t + n3; + e2[n3] && (i2[o2] = e2[n3]); + }), i2; + } + function Ru(e2) { + return `${e2.protocol}:${e2.topic}@${e2.version}?` + Ir.stringify(eo(_u(eo({ symKey: e2.symKey }, no(e2.relay)), { expiryTimestamp: e2.expiryTimestamp }), e2.methods ? { methods: e2.methods.join(",") } : {})); + } + var Cu = Object.defineProperty; + var Ou = Object.defineProperties; + var Pu = Object.getOwnPropertyDescriptors; + var fo = Object.getOwnPropertySymbols; + var Tu = Object.prototype.hasOwnProperty; + var Fu = Object.prototype.propertyIsEnumerable; + var oo = (e2, t, r) => t in e2 ? Cu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var Du = (e2, t) => { + for (var r in t || (t = {})) + Tu.call(t, r) && oo(e2, r, t[r]); + if (fo) + for (var r of fo(t)) + Fu.call(t, r) && oo(e2, r, t[r]); + return e2; + }; + var Uu = (e2, t) => Ou(e2, Pu(t)); + function Ze(e2) { + const t = []; + return e2.forEach((r) => { + const [i2, n3] = r.split(":"); + t.push(`${i2}:${n3}`); + }), t; + } + function so(e2) { + const t = []; + return Object.values(e2).forEach((r) => { + t.push(...Ze(r.accounts)); + }), t; + } + function ao(e2, t) { + const r = []; + return Object.values(e2).forEach((i2) => { + Ze(i2.accounts).includes(t) && r.push(...i2.methods); + }), r; + } + function uo(e2, t) { + const r = []; + return Object.values(e2).forEach((i2) => { + Ze(i2.accounts).includes(t) && r.push(...i2.events); + }), r; + } + function ku(e2, t) { + const r = wo(e2, t); + if (r) + throw new Error(r.message); + const i2 = {}; + for (const [n3, o2] of Object.entries(e2)) + i2[n3] = { methods: o2.methods, events: o2.events, chains: o2.accounts.map((h5) => `${h5.split(":")[0]}:${h5.split(":")[1]}`) }; + return i2; + } + function qu(e2) { + const { proposal: { requiredNamespaces: t, optionalNamespaces: r = {} }, supportedNamespaces: i2 } = e2, n3 = tn(t), o2 = tn(r), h5 = {}; + Object.keys(i2).forEach((g3) => { + const w4 = i2[g3].chains, y4 = i2[g3].methods, S4 = i2[g3].events, I2 = i2[g3].accounts; + w4.forEach((N10) => { + if (!I2.some((R2) => R2.includes(N10))) + throw new Error(`No accounts provided for chain ${N10} in namespace ${g3}`); + }), h5[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; + }); + const p3 = Mo(t, h5, "approve()"); + if (p3) + throw new Error(p3.message); + const b4 = {}; + return !Object.keys(t).length && !Object.keys(r).length ? h5 : (Object.keys(n3).forEach((g3) => { + const w4 = i2[g3].chains.filter((N10) => { + var R2, F; + return (F = (R2 = n3[g3]) == null ? void 0 : R2.chains) == null ? void 0 : F.includes(N10); + }), y4 = i2[g3].methods.filter((N10) => { + var R2, F; + return (F = (R2 = n3[g3]) == null ? void 0 : R2.methods) == null ? void 0 : F.includes(N10); + }), S4 = i2[g3].events.filter((N10) => { + var R2, F; + return (F = (R2 = n3[g3]) == null ? void 0 : R2.events) == null ? void 0 : F.includes(N10); + }), I2 = w4.map((N10) => i2[g3].accounts.filter((R2) => R2.includes(`${N10}:`))).flat(); + b4[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; + }), Object.keys(o2).forEach((g3) => { + var w4, y4, S4, I2, N10, R2; + if (!i2[g3]) + return; + const F = (y4 = (w4 = o2[g3]) == null ? void 0 : w4.chains) == null ? void 0 : y4.filter((J) => i2[g3].chains.includes(J)), U2 = i2[g3].methods.filter((J) => { + var H, L2; + return (L2 = (H = o2[g3]) == null ? void 0 : H.methods) == null ? void 0 : L2.includes(J); + }), Q = i2[g3].events.filter((J) => { + var H, L2; + return (L2 = (H = o2[g3]) == null ? void 0 : H.events) == null ? void 0 : L2.includes(J); + }), Bt = F?.map((J) => i2[g3].accounts.filter((H) => H.includes(`${J}:`))).flat(); + b4[g3] = { chains: ge((S4 = b4[g3]) == null ? void 0 : S4.chains, F), methods: ge((I2 = b4[g3]) == null ? void 0 : I2.methods, U2), events: ge((N10 = b4[g3]) == null ? void 0 : N10.events, Q), accounts: ge((R2 = b4[g3]) == null ? void 0 : R2.accounts, Bt) }; + }), b4); + } + function $i(e2) { + return e2.includes(":"); + } + function ho(e2) { + return $i(e2) ? e2.split(":")[0] : e2; + } + function tn(e2) { + var t, r, i2; + const n3 = {}; + if (!Gr(e2)) + return n3; + for (const [o2, h5] of Object.entries(e2)) { + const p3 = $i(o2) ? [o2] : h5.chains, b4 = h5.methods || [], g3 = h5.events || [], w4 = ho(o2); + n3[w4] = Uu(Du({}, n3[w4]), { chains: ge(p3, (t = n3[w4]) == null ? void 0 : t.chains), methods: ge(b4, (r = n3[w4]) == null ? void 0 : r.methods), events: ge(g3, (i2 = n3[w4]) == null ? void 0 : i2.events) }); + } + return n3; + } + function co(e2) { + const t = {}; + return e2?.forEach((r) => { + const [i2, n3] = r.split(":"); + t[i2] || (t[i2] = { accounts: [], chains: [], events: [] }), t[i2].accounts.push(r), t[i2].chains.push(`${i2}:${n3}`); + }), t; + } + function Ku(e2, t) { + t = t.map((i2) => i2.replace("did:pkh:", "")); + const r = co(t); + for (const [i2, n3] of Object.entries(r)) + n3.methods ? n3.methods = ge(n3.methods, e2) : n3.methods = e2, n3.events = ["chainChanged", "accountsChanged"]; + return r; + } + var lo = { INVALID_METHOD: { message: "Invalid method.", code: 1001 }, INVALID_EVENT: { message: "Invalid event.", code: 1002 }, INVALID_UPDATE_REQUEST: { message: "Invalid update request.", code: 1003 }, INVALID_EXTEND_REQUEST: { message: "Invalid extend request.", code: 1004 }, INVALID_SESSION_SETTLE_REQUEST: { message: "Invalid session settle request.", code: 1005 }, UNAUTHORIZED_METHOD: { message: "Unauthorized method.", code: 3001 }, UNAUTHORIZED_EVENT: { message: "Unauthorized event.", code: 3002 }, UNAUTHORIZED_UPDATE_REQUEST: { message: "Unauthorized update request.", code: 3003 }, UNAUTHORIZED_EXTEND_REQUEST: { message: "Unauthorized extend request.", code: 3004 }, USER_REJECTED: { message: "User rejected.", code: 5e3 }, USER_REJECTED_CHAINS: { message: "User rejected chains.", code: 5001 }, USER_REJECTED_METHODS: { message: "User rejected methods.", code: 5002 }, USER_REJECTED_EVENTS: { message: "User rejected events.", code: 5003 }, UNSUPPORTED_CHAINS: { message: "Unsupported chains.", code: 5100 }, UNSUPPORTED_METHODS: { message: "Unsupported methods.", code: 5101 }, UNSUPPORTED_EVENTS: { message: "Unsupported events.", code: 5102 }, UNSUPPORTED_ACCOUNTS: { message: "Unsupported accounts.", code: 5103 }, UNSUPPORTED_NAMESPACE_KEY: { message: "Unsupported namespace key.", code: 5104 }, USER_DISCONNECTED: { message: "User disconnected.", code: 6e3 }, SESSION_SETTLEMENT_FAILED: { message: "Session settlement failed.", code: 7e3 }, WC_METHOD_UNSUPPORTED: { message: "Unsupported wc_ method.", code: 10001 } }; + var po = { NOT_INITIALIZED: { message: "Not initialized.", code: 1 }, NO_MATCHING_KEY: { message: "No matching key.", code: 2 }, RESTORE_WILL_OVERRIDE: { message: "Restore will override.", code: 3 }, RESUBSCRIBED: { message: "Resubscribed.", code: 4 }, MISSING_OR_INVALID: { message: "Missing or invalid.", code: 5 }, EXPIRED: { message: "Expired.", code: 6 }, UNKNOWN_TYPE: { message: "Unknown type.", code: 7 }, MISMATCHED_TOPIC: { message: "Mismatched topic.", code: 8 }, NON_CONFORMING_NAMESPACES: { message: "Non conforming namespaces.", code: 9 } }; + function we(e2, t) { + const { message: r, code: i2 } = po[e2]; + return { message: t ? `${r} ${t}` : r, code: i2 }; + } + function $e(e2, t) { + const { message: r, code: i2 } = lo[e2]; + return { message: t ? `${r} ${t}` : r, code: i2 }; + } + function Sr(e2, t) { + return Array.isArray(e2) ? typeof t < "u" && e2.length ? e2.every(t) : true : false; + } + function Gr(e2) { + return Object.getPrototypeOf(e2) === Object.prototype && Object.keys(e2).length; + } + function Oe(e2) { + return typeof e2 > "u"; + } + function Yt(e2, t) { + return t && Oe(e2) ? true : typeof e2 == "string" && !!e2.trim().length; + } + function Wr(e2, t) { + return t && Oe(e2) ? true : typeof e2 == "number" && !isNaN(e2); + } + function Hu(e2, t) { + const { requiredNamespaces: r } = t, i2 = Object.keys(e2.namespaces), n3 = Object.keys(r); + let o2 = true; + return Ie(n3, i2) ? (i2.forEach((h5) => { + const { accounts: p3, methods: b4, events: g3 } = e2.namespaces[h5], w4 = Ze(p3), y4 = r[h5]; + (!Ie(Br(h5, y4), w4) || !Ie(y4.methods, b4) || !Ie(y4.events, g3)) && (o2 = false); + }), o2) : false; + } + function Nr(e2) { + return Yt(e2, false) && e2.includes(":") ? e2.split(":").length === 2 : false; + } + function vo(e2) { + if (Yt(e2, false) && e2.includes(":")) { + const t = e2.split(":"); + if (t.length === 3) { + const r = t[0] + ":" + t[1]; + return !!t[2] && Nr(r); + } + } + return false; + } + function Lu(e2) { + if (Yt(e2, false)) + try { + return typeof new URL(e2) < "u"; + } catch { + return false; + } + return false; + } + function zu(e2) { + var t; + return (t = e2?.proposer) == null ? void 0 : t.publicKey; + } + function ju(e2) { + return e2?.topic; + } + function Vu(e2, t) { + let r = null; + return Yt(e2?.publicKey, false) || (r = we("MISSING_OR_INVALID", `${t} controller public key should be a string`)), r; + } + function en(e2) { + let t = true; + return Sr(e2) ? e2.length && (t = e2.every((r) => Yt(r, false))) : t = false, t; + } + function go(e2, t, r) { + let i2 = null; + return Sr(t) && t.length ? t.forEach((n3) => { + i2 || Nr(n3) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chain ${n3} should be a string and conform to "namespace:chainId" format`)); + }) : Nr(e2) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)), i2; + } + function mo(e2, t, r) { + let i2 = null; + return Object.entries(e2).forEach(([n3, o2]) => { + if (i2) + return; + const h5 = go(n3, Br(n3, o2), `${t} ${r}`); + h5 && (i2 = h5); + }), i2; + } + function Ao(e2, t) { + let r = null; + return Sr(e2) ? e2.forEach((i2) => { + r || vo(i2) || (r = $e("UNSUPPORTED_ACCOUNTS", `${t}, account ${i2} should be a string and conform to "namespace:chainId:address" format`)); + }) : r = $e("UNSUPPORTED_ACCOUNTS", `${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`), r; + } + function bo(e2, t) { + let r = null; + return Object.values(e2).forEach((i2) => { + if (r) + return; + const n3 = Ao(i2?.accounts, `${t} namespace`); + n3 && (r = n3); + }), r; + } + function yo(e2, t) { + let r = null; + return en(e2?.methods) ? en(e2?.events) || (r = $e("UNSUPPORTED_EVENTS", `${t}, events should be an array of strings or empty array for no events`)) : r = $e("UNSUPPORTED_METHODS", `${t}, methods should be an array of strings or empty array for no methods`), r; + } + function rn(e2, t) { + let r = null; + return Object.values(e2).forEach((i2) => { + if (r) + return; + const n3 = yo(i2, `${t}, namespace`); + n3 && (r = n3); + }), r; + } + function Qu(e2, t, r) { + let i2 = null; + if (e2 && Gr(e2)) { + const n3 = rn(e2, t); + n3 && (i2 = n3); + const o2 = mo(e2, t, r); + o2 && (i2 = o2); + } else + i2 = we("MISSING_OR_INVALID", `${t}, ${r} should be an object with data`); + return i2; + } + function wo(e2, t) { + let r = null; + if (e2 && Gr(e2)) { + const i2 = rn(e2, t); + i2 && (r = i2); + const n3 = bo(e2, t); + n3 && (r = n3); + } else + r = we("MISSING_OR_INVALID", `${t}, namespaces should be an object with data`); + return r; + } + function xo(e2) { + return Yt(e2.protocol, true); + } + function Ju(e2, t) { + let r = false; + return t && !e2 ? r = true : e2 && Sr(e2) && e2.length && e2.forEach((i2) => { + r = xo(i2); + }), r; + } + function Yu(e2) { + return typeof e2 == "number"; + } + function Gu(e2) { + return typeof e2 < "u" && typeof e2 !== null; + } + function Wu(e2) { + return !(!e2 || typeof e2 != "object" || !e2.code || !Wr(e2.code, false) || !e2.message || !Yt(e2.message, false)); + } + function Xu(e2) { + return !(Oe(e2) || !Yt(e2.method, false)); + } + function Zu(e2) { + return !(Oe(e2) || Oe(e2.result) && Oe(e2.error) || !Wr(e2.id, false) || !Yt(e2.jsonrpc, false)); + } + function $u(e2) { + return !(Oe(e2) || !Yt(e2.name, false)); + } + function th(e2, t) { + return !(!Nr(t) || !so(e2).includes(t)); + } + function eh(e2, t, r) { + return Yt(r, false) ? ao(e2, t).includes(r) : false; + } + function rh(e2, t, r) { + return Yt(r, false) ? uo(e2, t).includes(r) : false; + } + function Mo(e2, t, r) { + let i2 = null; + const n3 = ih(e2), o2 = nh(t), h5 = Object.keys(n3), p3 = Object.keys(o2), b4 = Eo(Object.keys(e2)), g3 = Eo(Object.keys(t)), w4 = b4.filter((y4) => !g3.includes(y4)); + return w4.length && (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces keys don't satisfy requiredNamespaces. + Required: ${w4.toString()} + Received: ${Object.keys(t).toString()}`)), Ie(h5, p3) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces chains don't satisfy required namespaces. + Required: ${h5.toString()} + Approved: ${p3.toString()}`)), Object.keys(t).forEach((y4) => { + if (!y4.includes(":") || i2) + return; + const S4 = Ze(t[y4].accounts); + S4.includes(y4) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces accounts don't satisfy namespace accounts for ${y4} + Required: ${y4} + Approved: ${S4.toString()}`)); + }), h5.forEach((y4) => { + i2 || (Ie(n3[y4].methods, o2[y4].methods) ? Ie(n3[y4].events, o2[y4].events) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces events don't satisfy namespace events for ${y4}`)) : i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces methods don't satisfy namespace methods for ${y4}`)); + }), i2; + } + function ih(e2) { + const t = {}; + return Object.keys(e2).forEach((r) => { + var i2; + r.includes(":") ? t[r] = e2[r] : (i2 = e2[r].chains) == null || i2.forEach((n3) => { + t[n3] = { methods: e2[r].methods, events: e2[r].events }; + }); + }), t; + } + function Eo(e2) { + return [...new Set(e2.map((t) => t.includes(":") ? t.split(":")[0] : t))]; + } + function nh(e2) { + const t = {}; + return Object.keys(e2).forEach((r) => { + if (r.includes(":")) + t[r] = e2[r]; + else { + const i2 = Ze(e2[r].accounts); + i2?.forEach((n3) => { + t[n3] = { accounts: e2[r].accounts.filter((o2) => o2.includes(`${n3}:`)), methods: e2[r].methods, events: e2[r].events }; + }); + } + }), t; + } + function fh(e2, t) { + return Wr(e2, false) && e2 <= t.max && e2 >= t.min; + } + function oh() { + const e2 = Ge(); + return new Promise((t) => { + switch (e2) { + case Kt.browser: + t(So()); + break; + case Kt.reactNative: + t(No()); + break; + case Kt.node: + t(Io()); + break; + default: + t(true); + } + }); + } + function So() { + return vr() && navigator?.onLine; + } + async function No() { + if (rr() && typeof global < "u" && global != null && global.NetInfo) { + const e2 = await (global == null ? void 0 : global.NetInfo.fetch()); + return e2?.isConnected; + } + return true; + } + function Io() { + return true; + } + function sh(e2) { + switch (Ge()) { + case Kt.browser: + _o(e2); + break; + case Kt.reactNative: + Bo(e2); + break; + case Kt.node: + break; + } + } + function _o(e2) { + !rr() && vr() && (window.addEventListener("online", () => e2(true)), window.addEventListener("offline", () => e2(false))); + } + function Bo(e2) { + rr() && typeof global < "u" && global != null && global.NetInfo && global?.NetInfo.addEventListener((t) => e2(t?.isConnected)); + } + var nn = {}; + var ah = class { + static get(t) { + return nn[t]; + } + static set(t, r) { + nn[t] = r; + } + static delete(t) { + delete nn[t]; + } + }; + exports2.BASE10 = Yi, exports2.BASE16 = zt, exports2.BASE64 = Jr, exports2.COLON = jo, exports2.DEFAULT_DEPTH = pi, exports2.EMPTY_SPACE = Rr, exports2.ENV_MAP = Kt, exports2.INTERNAL_ERRORS = po, exports2.MemoryStore = ah, exports2.ONE_THOUSAND = Vo, exports2.REACT_NATIVE_PRODUCT = An, exports2.RELAYER_DEFAULT_PROTOCOL = Zf, exports2.SDK_ERRORS = lo, exports2.SDK_TYPE = yn, exports2.SLASH = bn, exports2.TYPE_0 = Gi, exports2.TYPE_1 = dr, exports2.UTF8 = Yr, exports2.addResourceToRecap = Vf, exports2.appendToQueryString = wn, exports2.assertType = Xo, exports2.assignAbilityToActions = Vi, exports2.base64Decode = zf, exports2.base64Encode = Lf, exports2.buildApprovedNamespaces = qu, exports2.buildAuthObject = iu, exports2.buildNamespacesFromAuth = Ku, exports2.buildRecapStatement = Jf, exports2.calcExpiry = us, exports2.capitalize = is, exports2.capitalizeWord = In, exports2.createDelayedPromise = ns, exports2.createEncodedRecap = su, exports2.createExpiringPromise = fs, exports2.createRecap = jf, exports2.decodeRecap = Ce, exports2.decodeTypeByte = Er, exports2.decrypt = Au, exports2.deriveSymKey = pu, exports2.deserialize = Zi, exports2.encodeRecap = Vr, exports2.encodeTypeByte = Gf, exports2.encrypt = mu, exports2.engineEvent = cs, exports2.enumify = rs, exports2.formatAccountId = cn, exports2.formatAccountWithChain = Do, exports2.formatChainId = hn, exports2.formatExpirerTarget = gi, exports2.formatIdTarget = ss, exports2.formatMessage = kf, exports2.formatMessageContext = Zo, exports2.formatRelayParams = no, exports2.formatRelayRpcUrl = Go, exports2.formatStatementFromRecap = Ji, exports2.formatTopicTarget = os, exports2.formatUA = En, exports2.formatUri = Ru, exports2.generateKeyPair = lu, exports2.generateRandomBytes32 = du, exports2.getAccountsChains = Ze, exports2.getAccountsFromNamespaces = ko, exports2.getAddressFromAccount = ln, exports2.getAddressesFromAccounts = Uo, exports2.getAppMetadata = Jo, exports2.getBrowserOnlineStatus = So, exports2.getBundleId = Qo, exports2.getChainFromAccount = dn, exports2.getChainsFromAccounts = pn, exports2.getChainsFromNamespace = Br, exports2.getChainsFromNamespaces = qo, exports2.getChainsFromRecap = hu, exports2.getChainsFromRequiredNamespaces = Ko, exports2.getCommonValuesInArrays = mi, exports2.getDecodedRecapFromResources = qf, exports2.getDeepLink = ds, exports2.getDidAddress = ji, exports2.getDidAddressSegments = jr, exports2.getDidChainId = zi, exports2.getEnvironment = Ge, exports2.getHttpUrl = Wo, exports2.getInternalError = we, exports2.getJavascriptID = Mn, exports2.getJavascriptOS = xn, exports2.getLastItems = Nn, exports2.getMethodsFromRecap = uu, exports2.getNamespacedDidChainId = eu, exports2.getNamespacesChains = so, exports2.getNamespacesEventsForChainId = uo, exports2.getNamespacesFromAccounts = co, exports2.getNamespacesMethodsForChainId = ao, exports2.getNodeOnlineStatus = Io, exports2.getReCapActions = Hf, exports2.getReactNativeOnlineStatus = No, exports2.getRecapAbilitiesFromResource = ou, exports2.getRecapFromResources = Qr, exports2.getRecapResource = Kf, exports2.getRelayClientMetadata = Yo, exports2.getRelayProtocolApi = xu, exports2.getRelayProtocolName = wu, exports2.getRequiredNamespacesFromNamespaces = ku, exports2.getSdkError = $e, exports2.getUniqueValues = di, exports2.handleDeeplinkRedirect = ls2, exports2.hasOverlap = Ie, exports2.hashKey = vu, exports2.hashMessage = gu, exports2.isBrowser = vr, exports2.isCaipNamespace = $i, exports2.isConformingNamespaces = Mo, exports2.isExpired = hs, exports2.isNode = vi, exports2.isOnline = oh, exports2.isProposalStruct = zu, exports2.isReactNative = rr, exports2.isRecap = Qi, exports2.isSessionCompatible = Hu, exports2.isSessionStruct = ju, exports2.isTypeOneEnvelope = yu, exports2.isUndefined = Oe, exports2.isValidAccountId = vo, exports2.isValidAccounts = Ao, exports2.isValidActions = yo, exports2.isValidArray = Sr, exports2.isValidChainId = Nr, exports2.isValidChains = go, exports2.isValidController = Vu, exports2.isValidEip1271Signature = Tf, exports2.isValidEip191Signature = Pf, exports2.isValidErrorReason = Wu, exports2.isValidEvent = $u, exports2.isValidId = Yu, exports2.isValidNamespaceAccounts = bo, exports2.isValidNamespaceActions = rn, exports2.isValidNamespaceChains = mo, exports2.isValidNamespaceMethodsOrEvents = en, exports2.isValidNamespaces = wo, exports2.isValidNamespacesChainId = th, exports2.isValidNamespacesEvent = rh, exports2.isValidNamespacesRequest = eh, exports2.isValidNumber = Wr, exports2.isValidObject = Gr, exports2.isValidParams = Gu, exports2.isValidRecap = ve, exports2.isValidRelay = xo, exports2.isValidRelays = Ju, exports2.isValidRequest = Xu, exports2.isValidRequestExpiry = fh, exports2.isValidRequiredNamespaces = Qu, exports2.isValidResponse = Zu, exports2.isValidString = Yt, exports2.isValidUrl = Lu, exports2.mapEntries = es, exports2.mapToObj = $o, exports2.mergeArrays = ge, exports2.mergeEncodedRecaps = au, exports2.mergeRecaps = Qf, exports2.normalizeNamespaces = tn, exports2.objToMap = ts, exports2.parseAccountId = li, exports2.parseChainId = un, exports2.parseContextNames = Sn, exports2.parseExpirerTarget = as, exports2.parseNamespaceKey = ho, exports2.parseRelayParams = ro, exports2.parseTopic = io, exports2.parseUri = Bu, exports2.populateAuthPayload = nu, exports2.recapHasResource = fu, exports2.serialize = Wf, exports2.subscribeToBrowserNetworkChange = _o, exports2.subscribeToNetworkChange = sh, exports2.subscribeToReactNativeNetworkChange = Bo, exports2.validateDecoding = bu, exports2.validateEncoding = Xf, exports2.validateSignedCacao = ru, exports2.verifySignature = Of; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js +var PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, SERVER_ERROR, RESERVED_ERROR_CODES, SERVER_ERROR_CODE_RANGE, STANDARD_ERROR_MAP, DEFAULT_ERROR; +var init_constants2 = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js"() { + init_shim(); + PARSE_ERROR = "PARSE_ERROR"; + INVALID_REQUEST = "INVALID_REQUEST"; + METHOD_NOT_FOUND = "METHOD_NOT_FOUND"; + INVALID_PARAMS = "INVALID_PARAMS"; + INTERNAL_ERROR = "INTERNAL_ERROR"; + SERVER_ERROR = "SERVER_ERROR"; + RESERVED_ERROR_CODES = [-32700, -32600, -32601, -32602, -32603]; + SERVER_ERROR_CODE_RANGE = [-32e3, -32099]; + STANDARD_ERROR_MAP = { + [PARSE_ERROR]: { code: -32700, message: "Parse error" }, + [INVALID_REQUEST]: { code: -32600, message: "Invalid Request" }, + [METHOD_NOT_FOUND]: { code: -32601, message: "Method not found" }, + [INVALID_PARAMS]: { code: -32602, message: "Invalid params" }, + [INTERNAL_ERROR]: { code: -32603, message: "Internal error" }, + [SERVER_ERROR]: { code: -32e3, message: "Server error" } + }; + DEFAULT_ERROR = SERVER_ERROR; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js +function isServerErrorCode(code2) { + return code2 <= SERVER_ERROR_CODE_RANGE[0] && code2 >= SERVER_ERROR_CODE_RANGE[1]; +} +function isReservedErrorCode(code2) { + return RESERVED_ERROR_CODES.includes(code2); +} +function isValidErrorCode(code2) { + return typeof code2 === "number"; +} +function getError(type) { + if (!Object.keys(STANDARD_ERROR_MAP).includes(type)) { + return STANDARD_ERROR_MAP[DEFAULT_ERROR]; + } + return STANDARD_ERROR_MAP[type]; +} +function getErrorByCode(code2) { + const match = Object.values(STANDARD_ERROR_MAP).find((e2) => e2.code === code2); + if (!match) { + return STANDARD_ERROR_MAP[DEFAULT_ERROR]; + } + return match; +} +function validateJsonRpcError(response) { + if (typeof response.error.code === "undefined") { + return { valid: false, error: "Missing code for JSON-RPC error" }; + } + if (typeof response.error.message === "undefined") { + return { valid: false, error: "Missing message for JSON-RPC error" }; + } + if (!isValidErrorCode(response.error.code)) { + return { + valid: false, + error: `Invalid error code type for JSON-RPC: ${response.error.code}` + }; + } + if (isReservedErrorCode(response.error.code)) { + const error = getErrorByCode(response.error.code); + if (error.message !== STANDARD_ERROR_MAP[DEFAULT_ERROR].message && response.error.message === error.message) { + return { + valid: false, + error: `Invalid error code message for JSON-RPC: ${response.error.code}` + }; + } + } + return { valid: true }; +} +function parseConnectionError(e2, url, type) { + return e2.message.includes("getaddrinfo ENOTFOUND") || e2.message.includes("connect ECONNREFUSED") ? new Error(`Unavailable ${type} RPC url at ${url}`) : e2; +} +var init_error = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js"() { + init_shim(); + init_constants2(); + } +}); + +// node_modules/@walletconnect/environment/dist/cjs/crypto.js +var require_crypto2 = __commonJS({ + "node_modules/@walletconnect/environment/dist/cjs/crypto.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isBrowserCryptoAvailable = exports2.getSubtleCrypto = exports2.getBrowerCrypto = void 0; + function getBrowerCrypto() { + return (global === null || global === void 0 ? void 0 : global.crypto) || (global === null || global === void 0 ? void 0 : global.msCrypto) || {}; + } + exports2.getBrowerCrypto = getBrowerCrypto; + function getSubtleCrypto() { + const browserCrypto = getBrowerCrypto(); + return browserCrypto.subtle || browserCrypto.webkitSubtle; + } + exports2.getSubtleCrypto = getSubtleCrypto; + function isBrowserCryptoAvailable() { + return !!getBrowerCrypto() && !!getSubtleCrypto(); + } + exports2.isBrowserCryptoAvailable = isBrowserCryptoAvailable; + } +}); + +// node_modules/@walletconnect/environment/dist/cjs/env.js +var require_env = __commonJS({ + "node_modules/@walletconnect/environment/dist/cjs/env.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isBrowser = exports2.isNode = exports2.isReactNative = void 0; + function isReactNative() { + return typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative"; + } + exports2.isReactNative = isReactNative; + function isNode2() { + return typeof import_process.default !== "undefined" && typeof import_process.default.versions !== "undefined" && typeof import_process.default.versions.node !== "undefined"; + } + exports2.isNode = isNode2; + function isBrowser() { + return !isReactNative() && !isNode2(); + } + exports2.isBrowser = isBrowser; + } +}); + +// node_modules/@walletconnect/environment/dist/cjs/index.js +var require_cjs5 = __commonJS({ + "node_modules/@walletconnect/environment/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_crypto2(), exports2); + tslib_1.__exportStar(require_env(), exports2); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js +var env_exports = {}; +__export(env_exports, { + isNodeJs: () => isNodeJs +}); +var import_environment, isNodeJs; +var init_env = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js"() { + init_shim(); + import_environment = __toESM(require_cjs5()); + __reExport(env_exports, __toESM(require_cjs5())); + isNodeJs = import_environment.isNode; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js +function payloadId(entropy = 3) { + const date = Date.now() * Math.pow(10, entropy); + const extra = Math.floor(Math.random() * Math.pow(10, entropy)); + return date + extra; +} +function getBigIntRpcId(entropy = 6) { + return BigInt(payloadId(entropy)); +} +function formatJsonRpcRequest(method, params, id) { + return { + id: id || payloadId(), + jsonrpc: "2.0", + method, + params + }; +} +function formatJsonRpcResult(id, result) { + return { + id, + jsonrpc: "2.0", + result + }; +} +function formatJsonRpcError(id, error, data) { + return { + id, + jsonrpc: "2.0", + error: formatErrorMessage(error, data) + }; +} +function formatErrorMessage(error, data) { + if (typeof error === "undefined") { + return getError(INTERNAL_ERROR); + } + if (typeof error === "string") { + error = Object.assign(Object.assign({}, getError(SERVER_ERROR)), { message: error }); + } + if (typeof data !== "undefined") { + error.data = data; + } + if (isReservedErrorCode(error.code)) { + error = getErrorByCode(error.code); + } + return error; +} +var init_format = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js"() { + init_shim(); + init_error(); + init_constants2(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js +function isValidRoute(route) { + if (route.includes("*")) { + return isValidWildcardRoute(route); + } + if (/\W/g.test(route)) { + return false; + } + return true; +} +function isValidDefaultRoute(route) { + return route === "*"; +} +function isValidWildcardRoute(route) { + if (isValidDefaultRoute(route)) { + return true; + } + if (!route.includes("*")) { + return false; + } + if (route.split("*").length !== 2) { + return false; + } + if (route.split("*").filter((x3) => x3.trim() === "").length !== 1) { + return false; + } + return true; +} +function isValidLeadingWildcardRoute(route) { + return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[0].trim(); +} +function isValidTrailingWildcardRoute(route) { + return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[1].trim(); +} +var init_routing = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js +var init_jsonrpc = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js +var IEvents2; +var init_misc = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js"() { + init_shim(); + IEvents2 = class { + }; + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js +var IJsonRpcConnection, IBaseJsonRpcProvider, IJsonRpcProvider; +var init_provider = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js"() { + init_shim(); + init_misc(); + IJsonRpcConnection = class extends IEvents2 { + constructor(opts) { + super(); + } + }; + IBaseJsonRpcProvider = class extends IEvents2 { + constructor() { + super(); + } + }; + IJsonRpcProvider = class extends IBaseJsonRpcProvider { + constructor(connection) { + super(); + } + }; + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js +var init_validator = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js +var init_esm4 = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js"() { + init_shim(); + init_jsonrpc(); + init_misc(); + init_provider(); + init_validator(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js +var init_types2 = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js"() { + init_shim(); + init_esm4(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js +function getUrlProtocol(url) { + const matches = url.match(new RegExp(/^\w+:/, "gi")); + if (!matches || !matches.length) + return; + return matches[0]; +} +function matchRegexProtocol(url, regex) { + const protocol = getUrlProtocol(url); + if (typeof protocol === "undefined") + return false; + return new RegExp(regex).test(protocol); +} +function isHttpUrl(url) { + return matchRegexProtocol(url, HTTP_REGEX); +} +function isWsUrl(url) { + return matchRegexProtocol(url, WS_REGEX); +} +function isLocalhostUrl(url) { + return new RegExp("wss?://localhost(:d{2,5})?").test(url); +} +var HTTP_REGEX, WS_REGEX; +var init_url = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js"() { + init_shim(); + HTTP_REGEX = "^https?:"; + WS_REGEX = "^wss?:"; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js +function isJsonRpcPayload(payload) { + return typeof payload === "object" && "id" in payload && "jsonrpc" in payload && payload.jsonrpc === "2.0"; +} +function isJsonRpcRequest(payload) { + return isJsonRpcPayload(payload) && "method" in payload; +} +function isJsonRpcResponse(payload) { + return isJsonRpcPayload(payload) && (isJsonRpcResult(payload) || isJsonRpcError(payload)); +} +function isJsonRpcResult(payload) { + return "result" in payload; +} +function isJsonRpcError(payload) { + return "error" in payload; +} +function isJsonRpcValidationInvalid(validation) { + return "error" in validation && validation.valid === false; +} +var init_validators = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js +var esm_exports4 = {}; +__export(esm_exports4, { + DEFAULT_ERROR: () => DEFAULT_ERROR, + IBaseJsonRpcProvider: () => IBaseJsonRpcProvider, + IEvents: () => IEvents2, + IJsonRpcConnection: () => IJsonRpcConnection, + IJsonRpcProvider: () => IJsonRpcProvider, + INTERNAL_ERROR: () => INTERNAL_ERROR, + INVALID_PARAMS: () => INVALID_PARAMS, + INVALID_REQUEST: () => INVALID_REQUEST, + METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, + PARSE_ERROR: () => PARSE_ERROR, + RESERVED_ERROR_CODES: () => RESERVED_ERROR_CODES, + SERVER_ERROR: () => SERVER_ERROR, + SERVER_ERROR_CODE_RANGE: () => SERVER_ERROR_CODE_RANGE, + STANDARD_ERROR_MAP: () => STANDARD_ERROR_MAP, + formatErrorMessage: () => formatErrorMessage, + formatJsonRpcError: () => formatJsonRpcError, + formatJsonRpcRequest: () => formatJsonRpcRequest, + formatJsonRpcResult: () => formatJsonRpcResult, + getBigIntRpcId: () => getBigIntRpcId, + getError: () => getError, + getErrorByCode: () => getErrorByCode, + isHttpUrl: () => isHttpUrl, + isJsonRpcError: () => isJsonRpcError, + isJsonRpcPayload: () => isJsonRpcPayload, + isJsonRpcRequest: () => isJsonRpcRequest, + isJsonRpcResponse: () => isJsonRpcResponse, + isJsonRpcResult: () => isJsonRpcResult, + isJsonRpcValidationInvalid: () => isJsonRpcValidationInvalid, + isLocalhostUrl: () => isLocalhostUrl, + isNodeJs: () => isNodeJs, + isReservedErrorCode: () => isReservedErrorCode, + isServerErrorCode: () => isServerErrorCode, + isValidDefaultRoute: () => isValidDefaultRoute, + isValidErrorCode: () => isValidErrorCode, + isValidLeadingWildcardRoute: () => isValidLeadingWildcardRoute, + isValidRoute: () => isValidRoute, + isValidTrailingWildcardRoute: () => isValidTrailingWildcardRoute, + isValidWildcardRoute: () => isValidWildcardRoute, + isWsUrl: () => isWsUrl, + parseConnectionError: () => parseConnectionError, + payloadId: () => payloadId, + validateJsonRpcError: () => validateJsonRpcError +}); +var init_esm5 = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js"() { + init_shim(); + init_constants2(); + init_error(); + init_env(); + __reExport(esm_exports4, env_exports); + init_format(); + init_routing(); + init_types2(); + init_url(); + init_validators(); + } +}); + +// node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js +var import_events, JsonRpcProvider, provider_default; +var init_provider2 = __esm({ + "node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js"() { + init_shim(); + import_events = __toESM(require_events()); + init_esm5(); + JsonRpcProvider = class extends IJsonRpcProvider { + constructor(connection) { + super(connection); + this.events = new import_events.EventEmitter(); + this.hasRegisteredEventListeners = false; + this.connection = this.setConnection(connection); + if (this.connection.connected) { + this.registerEventListeners(); + } + } + async connect(connection = this.connection) { + await this.open(connection); + } + async disconnect() { + await this.close(); + } + on(event, listener) { + this.events.on(event, listener); + } + once(event, listener) { + this.events.once(event, listener); + } + off(event, listener) { + this.events.off(event, listener); + } + removeListener(event, listener) { + this.events.removeListener(event, listener); + } + async request(request, context) { + return this.requestStrict(formatJsonRpcRequest(request.method, request.params || [], request.id || getBigIntRpcId().toString()), context); + } + async requestStrict(request, context) { + return new Promise(async (resolve, reject) => { + if (!this.connection.connected) { + try { + await this.open(); + } catch (e2) { + reject(e2); + } + } + this.events.on(`${request.id}`, (response) => { + if (isJsonRpcError(response)) { + reject(response.error); + } else { + resolve(response.result); + } + }); + try { + await this.connection.send(request, context); + } catch (e2) { + reject(e2); + } + }); + } + setConnection(connection = this.connection) { + return connection; + } + onPayload(payload) { + this.events.emit("payload", payload); + if (isJsonRpcResponse(payload)) { + this.events.emit(`${payload.id}`, payload); + } else { + this.events.emit("message", { + type: payload.method, + data: payload.params + }); + } + } + onClose(event) { + if (event && event.code === 3e3) { + this.events.emit("error", new Error(`WebSocket connection closed abnormally with code: ${event.code} ${event.reason ? `(${event.reason})` : ""}`)); + } + this.events.emit("disconnect"); + } + async open(connection = this.connection) { + if (this.connection === connection && this.connection.connected) + return; + if (this.connection.connected) + this.close(); + if (typeof connection === "string") { + await this.connection.open(connection); + connection = this.connection; + } + this.connection = this.setConnection(connection); + await this.connection.open(); + this.registerEventListeners(); + this.events.emit("connect"); + } + async close() { + await this.connection.close(); + } + registerEventListeners() { + if (this.hasRegisteredEventListeners) + return; + this.connection.on("payload", (payload) => this.onPayload(payload)); + this.connection.on("close", (event) => this.onClose(event)); + this.connection.on("error", (error) => this.events.emit("error", error)); + this.connection.on("register_error", (error) => this.onClose()); + this.hasRegisteredEventListeners = true; + } + }; + provider_default = JsonRpcProvider; + } +}); + +// node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js +var esm_exports5 = {}; +__export(esm_exports5, { + JsonRpcProvider: () => JsonRpcProvider, + default: () => esm_default +}); +var esm_default; +var init_esm6 = __esm({ + "node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js"() { + init_shim(); + init_provider2(); + init_provider2(); + esm_default = provider_default; + } +}); + +// node_modules/ws/browser.js +var require_browser5 = __commonJS({ + "node_modules/ws/browser.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function() { + throw new Error( + "ws does not work in the browser. Browser clients must use the native WebSocket object" + ); + }; + } +}); + +// node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js +var index_es_exports4 = {}; +__export(index_es_exports4, { + WsConnection: () => f3, + default: () => f3 +}); +var import_events2, w3, b3, a2, h4, S3, f3; +var init_index_es4 = __esm({ + "node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js"() { + init_shim(); + import_events2 = __toESM(require_events()); + init_esm(); + init_esm5(); + w3 = () => typeof WebSocket < "u" ? WebSocket : typeof global < "u" && typeof global.WebSocket < "u" ? global.WebSocket : typeof window < "u" && typeof window.WebSocket < "u" ? window.WebSocket : typeof self < "u" && typeof self.WebSocket < "u" ? self.WebSocket : require_browser5(); + b3 = () => typeof WebSocket < "u" || typeof global < "u" && typeof global.WebSocket < "u" || typeof window < "u" && typeof window.WebSocket < "u" || typeof self < "u" && typeof self.WebSocket < "u"; + a2 = (c4) => c4.split("?")[0]; + h4 = 10; + S3 = w3(); + f3 = class { + constructor(e2) { + if (this.url = e2, this.events = new import_events2.EventEmitter(), this.registering = false, !isWsUrl(e2)) + throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); + this.url = e2; + } + get connected() { + return typeof this.socket < "u"; + } + get connecting() { + return this.registering; + } + on(e2, t) { + this.events.on(e2, t); + } + once(e2, t) { + this.events.once(e2, t); + } + off(e2, t) { + this.events.off(e2, t); + } + removeListener(e2, t) { + this.events.removeListener(e2, t); + } + async open(e2 = this.url) { + await this.register(e2); + } + async close() { + return new Promise((e2, t) => { + if (typeof this.socket > "u") { + t(new Error("Connection already closed")); + return; + } + this.socket.onclose = (n3) => { + this.onClose(n3), e2(); + }, this.socket.close(); + }); + } + async send(e2) { + typeof this.socket > "u" && (this.socket = await this.register()); + try { + this.socket.send(safeJsonStringify(e2)); + } catch (t) { + this.onError(e2.id, t); + } + } + register(e2 = this.url) { + if (!isWsUrl(e2)) + throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); + if (this.registering) { + const t = this.events.getMaxListeners(); + return (this.events.listenerCount("register_error") >= t || this.events.listenerCount("open") >= t) && this.events.setMaxListeners(t + 1), new Promise((n3, o2) => { + this.events.once("register_error", (s2) => { + this.resetMaxListeners(), o2(s2); + }), this.events.once("open", () => { + if (this.resetMaxListeners(), typeof this.socket > "u") + return o2(new Error("WebSocket connection is missing or invalid")); + n3(this.socket); + }); + }); + } + return this.url = e2, this.registering = true, new Promise((t, n3) => { + const o2 = new URLSearchParams(e2).get("origin"), s2 = (0, esm_exports4.isReactNative)() ? { headers: { origin: o2 } } : { rejectUnauthorized: !isLocalhostUrl(e2) }, i2 = new S3(e2, [], s2); + b3() ? i2.onerror = (r) => { + const l4 = r; + n3(this.emitError(l4.error)); + } : i2.on("error", (r) => { + n3(this.emitError(r)); + }), i2.onopen = () => { + this.onOpen(i2), t(i2); + }; + }); + } + onOpen(e2) { + e2.onmessage = (t) => this.onPayload(t), e2.onclose = (t) => this.onClose(t), this.socket = e2, this.registering = false, this.events.emit("open"); + } + onClose(e2) { + this.socket = void 0, this.registering = false, this.events.emit("close", e2); + } + onPayload(e2) { + if (typeof e2.data > "u") + return; + const t = typeof e2.data == "string" ? safeJsonParse(e2.data) : e2.data; + this.events.emit("payload", t); + } + onError(e2, t) { + const n3 = this.parseError(t), o2 = n3.message || n3.toString(), s2 = formatJsonRpcError(e2, o2); + this.events.emit("payload", s2); + } + parseError(e2, t = this.url) { + return parseConnectionError(e2, a2(t), "WS"); + } + resetMaxListeners() { + this.events.getMaxListeners() > h4 && this.events.setMaxListeners(h4); + } + emitError(e2) { + const t = this.parseError(new Error(e2?.message || `WebSocket connection failed for host: ${a2(this.url)}`)); + return this.events.emit("register_error", t), t; + } + }; + } +}); + +// node_modules/lodash.isequal/index.js +var require_lodash = __commonJS({ + "node_modules/lodash.isequal/index.js"(exports2, module2) { + init_shim(); + var LARGE_ARRAY_SIZE = 200; + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var COMPARE_PARTIAL_FLAG = 1; + var COMPARE_UNORDERED_FLAG = 2; + var MAX_SAFE_INTEGER2 = 9007199254740991; + var argsTag = "[object Arguments]"; + var arrayTag = "[object Array]"; + var asyncTag = "[object AsyncFunction]"; + var boolTag = "[object Boolean]"; + var dateTag = "[object Date]"; + var errorTag = "[object Error]"; + var funcTag = "[object Function]"; + var genTag = "[object GeneratorFunction]"; + var mapTag = "[object Map]"; + var numberTag = "[object Number]"; + var nullTag = "[object Null]"; + var objectTag = "[object Object]"; + var promiseTag = "[object Promise]"; + var proxyTag = "[object Proxy]"; + var regexpTag = "[object RegExp]"; + var setTag = "[object Set]"; + var stringTag = "[object String]"; + var symbolTag = "[object Symbol]"; + var undefinedTag = "[object Undefined]"; + var weakMapTag = "[object WeakMap]"; + var arrayBufferTag = "[object ArrayBuffer]"; + var dataViewTag = "[object DataView]"; + var float32Tag = "[object Float32Array]"; + var float64Tag = "[object Float64Array]"; + var int8Tag = "[object Int8Array]"; + var int16Tag = "[object Int16Array]"; + var int32Tag = "[object Int32Array]"; + var uint8Tag = "[object Uint8Array]"; + var uint8ClampedTag = "[object Uint8ClampedArray]"; + var uint16Tag = "[object Uint16Array]"; + var uint32Tag = "[object Uint32Array]"; + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; + var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding("util"); + } catch (e2) { + } + }(); + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + function arrayFilter(array, predicate) { + var index = -1, length2 = array == null ? 0 : array.length, resIndex = 0, result = []; + while (++index < length2) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + function arrayPush(array, values) { + var index = -1, length2 = values.length, offset = array.length; + while (++index < length2) { + array[offset + index] = values[index]; + } + return array; + } + function arraySome(array, predicate) { + var index = -1, length2 = array == null ? 0 : array.length; + while (++index < length2) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + function baseTimes(n3, iteratee) { + var index = -1, result = Array(n3); + while (++index < n3) { + result[index] = iteratee(index); + } + return result; + } + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + function cacheHas(cache, key) { + return cache.has(key); + } + function getValue(object, key) { + return object == null ? void 0 : object[key]; + } + function mapToArray(map) { + var index = -1, result = Array(map.size); + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + function setToArray(set2) { + var index = -1, result = Array(set2.size); + set2.forEach(function(value) { + result[++index] = value; + }); + return result; + } + var arrayProto = Array.prototype; + var funcProto = Function.prototype; + var objectProto = Object.prototype; + var coreJsData = root["__core-js_shared__"]; + var funcToString = funcProto.toString; + var hasOwnProperty = objectProto.hasOwnProperty; + var maskSrcKey = function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); + return uid ? "Symbol(src)_1." + uid : ""; + }(); + var nativeObjectToString = objectProto.toString; + var reIsNative = RegExp( + "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" + ); + var Buffer2 = moduleExports ? root.Buffer : void 0; + var Symbol2 = root.Symbol; + var Uint8Array2 = root.Uint8Array; + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + var splice = arrayProto.splice; + var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; + var nativeGetSymbols = Object.getOwnPropertySymbols; + var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; + var nativeKeys = overArg(Object.keys, Object); + var DataView2 = getNative(root, "DataView"); + var Map2 = getNative(root, "Map"); + var Promise2 = getNative(root, "Promise"); + var Set2 = getNative(root, "Set"); + var WeakMap2 = getNative(root, "WeakMap"); + var nativeCreate = getNative(Object, "create"); + var dataViewCtorString = toSource(DataView2); + var mapCtorString = toSource(Map2); + var promiseCtorString = toSource(Promise2); + var setCtorString = toSource(Set2); + var weakMapCtorString = toSource(WeakMap2); + var symbolProto = Symbol2 ? Symbol2.prototype : void 0; + var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; + function Hash(entries) { + var index = -1, length2 = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length2) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? void 0 : result; + } + return hasOwnProperty.call(data, key) ? data[key] : void 0; + } + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); + } + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; + return this; + } + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + function ListCache(entries) { + var index = -1, length2 = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length2) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? void 0 : data[index][1]; + } + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + function listCacheSet(key, value) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + function MapCache(entries) { + var index = -1, length2 = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length2) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function mapCacheClear() { + this.size = 0; + this.__data__ = { + "hash": new Hash(), + "map": new (Map2 || ListCache)(), + "string": new Hash() + }; + } + function mapCacheDelete(key) { + var result = getMapData(this, key)["delete"](key); + this.size -= result ? 1 : 0; + return result; + } + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + function mapCacheSet(key, value) { + var data = getMapData(this, key), size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + function SetCache(values) { + var index = -1, length2 = values == null ? 0 : values.length; + this.__data__ = new MapCache(); + while (++index < length2) { + this.add(values[index]); + } + } + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + function setCacheHas(value) { + return this.__data__.has(value); + } + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + function stackClear() { + this.__data__ = new ListCache(); + this.size = 0; + } + function stackDelete(key) { + var data = this.__data__, result = data["delete"](key); + this.size = data.size; + return result; + } + function stackGet(key) { + return this.__data__.get(key); + } + function stackHas(key) { + return this.__data__.has(key); + } + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + Stack.prototype.clear = stackClear; + Stack.prototype["delete"] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length2 = result.length; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. + (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. + isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. + isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. + isIndex(key, length2)))) { + result.push(key); + } + } + return result; + } + function assocIndexOf(array, key) { + var length2 = array.length; + while (length2--) { + if (eq(array[length2][0], key)) { + return length2; + } + } + return -1; + } + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + function baseGetTag(value) { + if (value == null) { + return value === void 0 ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); + } + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack()); + return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new Stack()); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack()); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + function baseIsTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != "constructor") { + result.push(key); + } + } + return result; + } + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0; + stack.set(array, other); + stack.set(other, array); + while (++index < arrLength) { + var arrValue = array[index], othValue = other[index]; + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== void 0) { + if (compared) { + continue; + } + result = false; + break; + } + if (seen) { + if (!arraySome(other, function(othValue2, othIndex) { + if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result = false; + break; + } + } + stack["delete"](array); + stack["delete"](other); + return result; + } + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + object = object.buffer; + other = other.buffer; + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { + return false; + } + return true; + case boolTag: + case dateTag: + case numberTag: + return eq(+object, +other); + case errorTag: + return object.name == other.name && object.message == other.message; + case regexpTag: + case stringTag: + return object == other + ""; + case mapTag: + var convert = mapToArray; + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + if (object.size != other.size && !isPartial) { + return false; + } + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack["delete"](object); + return result; + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], othValue = other[key]; + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } + if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { + result = false; + break; + } + skipCtor || (skipCtor = key == "constructor"); + } + if (result && !skipCtor) { + var objCtor = object.constructor, othCtor = other.constructor; + if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { + result = false; + } + } + stack["delete"](object); + stack["delete"](other); + return result; + } + function getAllKeys(object) { + return baseGetAllKeys(object, keys2, getSymbols); + } + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : void 0; + } + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + try { + value[symToStringTag] = void 0; + var unmasked = true; + } catch (e2) { + } + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + var getTag = baseGetTag; + if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) { + getTag = function(value) { + var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag; + case mapCtorString: + return mapTag; + case promiseCtorString: + return promiseTag; + case setCtorString: + return setTag; + case weakMapCtorString: + return weakMapTag; + } + } + return result; + }; + } + function isIndex(value, length2) { + length2 = length2 == null ? MAX_SAFE_INTEGER2 : length2; + return !!length2 && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length2); + } + function isKeyable(value) { + var type = typeof value; + return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; + } + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; + } + function isPrototype(value) { + var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value === proto; + } + function objectToString(value) { + return nativeObjectToString.call(value); + } + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e2) { + } + try { + return func + ""; + } catch (e2) { + } + } + return ""; + } + function eq(value, other) { + return value === other || value !== value && other !== other; + } + var isArguments = baseIsArguments(/* @__PURE__ */ function() { + return arguments; + }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + }; + var isArray = Array.isArray; + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + var isBuffer = nativeIsBuffer || stubFalse; + function isEqual(value, other) { + return baseIsEqual(value, other); + } + function isFunction(value) { + if (!isObject(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; + } + function isObject(value) { + var type = typeof value; + return value != null && (type == "object" || type == "function"); + } + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function keys2(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + function stubArray() { + return []; + } + function stubFalse() { + return false; + } + module2.exports = isEqual; + } +}); + +// node_modules/unfetch/dist/unfetch.js +var require_unfetch = __commonJS({ + "node_modules/unfetch/dist/unfetch.js"(exports2, module2) { + init_shim(); + module2.exports = function(e2, n3) { + return n3 = n3 || {}, new Promise(function(t, r) { + var s2 = new XMLHttpRequest(), o2 = [], u3 = [], i2 = {}, a3 = function() { + return { ok: 2 == (s2.status / 100 | 0), statusText: s2.statusText, status: s2.status, url: s2.responseURL, text: function() { + return Promise.resolve(s2.responseText); + }, json: function() { + return Promise.resolve(s2.responseText).then(JSON.parse); + }, blob: function() { + return Promise.resolve(new Blob([s2.response])); + }, clone: a3, headers: { keys: function() { + return o2; + }, entries: function() { + return u3; + }, get: function(e3) { + return i2[e3.toLowerCase()]; + }, has: function(e3) { + return e3.toLowerCase() in i2; + } } }; + }; + for (var l4 in s2.open(n3.method || "get", e2, true), s2.onload = function() { + s2.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function(e3, n4, t2) { + o2.push(n4 = n4.toLowerCase()), u3.push([n4, t2]), i2[n4] = i2[n4] ? i2[n4] + "," + t2 : t2; + }), t(a3()); + }, s2.onerror = r, s2.withCredentials = "include" == n3.credentials, n3.headers) + s2.setRequestHeader(l4, n3.headers[l4]); + s2.send(n3.body || null); + }); + }; + } +}); + +// node_modules/isomorphic-unfetch/browser.js +var require_browser6 = __commonJS({ + "node_modules/isomorphic-unfetch/browser.js"(exports2, module2) { + init_shim(); + module2.exports = self.fetch || (self.fetch = require_unfetch().default || require_unfetch()); + } +}); + +// node_modules/@walletconnect/core/dist/index.cjs.js +var require_index_cjs3 = __commonJS({ + "node_modules/@walletconnect/core/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var z3 = require_events(); + var It = (init_index_es(), __toCommonJS(index_es_exports)); + var $ = require_cjs2(); + var g3 = (init_index_es2(), __toCommonJS(index_es_exports2)); + var x3 = require_index_cjs(); + var oe = (init_esm(), __toCommonJS(esm_exports)); + var Rt = (init_esm3(), __toCommonJS(esm_exports3)); + var a3 = require_index_cjs2(); + var _t = (init_src2(), __toCommonJS(src_exports)); + var l4 = require_cjs(); + var Ct = (init_esm6(), __toCommonJS(esm_exports5)); + var f4 = (init_esm5(), __toCommonJS(esm_exports4)); + var Tt = (init_index_es4(), __toCommonJS(index_es_exports4)); + var St = require_lodash(); + var Ot = require_browser6(); + function k4(n3) { + return n3 && typeof n3 == "object" && "default" in n3 ? n3 : { default: n3 }; + } + function Pt(n3) { + if (n3 && n3.__esModule) + return n3; + var e2 = /* @__PURE__ */ Object.create(null); + return n3 && Object.keys(n3).forEach(function(t) { + if (t !== "default") { + var i2 = Object.getOwnPropertyDescriptor(n3, t); + Object.defineProperty(e2, t, i2.get ? i2 : { enumerable: true, get: function() { + return n3[t]; + } }); + } + }), e2.default = n3, Object.freeze(e2); + } + var At = k4(z3); + var xt = k4(It); + var j2 = Pt(Rt); + var Nt = k4(Tt); + var Lt = k4(St); + var Ut = k4(Ot); + function zt(n3, e2) { + if (n3.length >= 255) + throw new TypeError("Alphabet too long"); + for (var t = new Uint8Array(256), i2 = 0; i2 < t.length; i2++) + t[i2] = 255; + for (var s2 = 0; s2 < n3.length; s2++) { + var r = n3.charAt(s2), o2 = r.charCodeAt(0); + if (t[o2] !== 255) + throw new TypeError(r + " is ambiguous"); + t[o2] = s2; + } + var h5 = n3.length, c4 = n3.charAt(0), u3 = Math.log(h5) / Math.log(256), p3 = Math.log(256) / Math.log(h5); + function D2(d3) { + if (d3 instanceof Uint8Array || (ArrayBuffer.isView(d3) ? d3 = new Uint8Array(d3.buffer, d3.byteOffset, d3.byteLength) : Array.isArray(d3) && (d3 = Uint8Array.from(d3))), !(d3 instanceof Uint8Array)) + throw new TypeError("Expected Uint8Array"); + if (d3.length === 0) + return ""; + for (var y4 = 0, C3 = 0, E4 = 0, O3 = d3.length; E4 !== O3 && d3[E4] === 0; ) + E4++, y4++; + for (var P2 = (O3 - E4) * p3 + 1 >>> 0, v2 = new Uint8Array(P2); E4 !== O3; ) { + for (var A2 = d3[E4], U2 = 0, T2 = P2 - 1; (A2 !== 0 || U2 < C3) && T2 !== -1; T2--, U2++) + A2 += 256 * v2[T2] >>> 0, v2[T2] = A2 % h5 >>> 0, A2 = A2 / h5 >>> 0; + if (A2 !== 0) + throw new Error("Non-zero carry"); + C3 = U2, E4++; + } + for (var N10 = P2 - C3; N10 !== P2 && v2[N10] === 0; ) + N10++; + for (var Y = c4.repeat(y4); N10 < P2; ++N10) + Y += n3.charAt(v2[N10]); + return Y; + } + function b4(d3) { + if (typeof d3 != "string") + throw new TypeError("Expected String"); + if (d3.length === 0) + return new Uint8Array(); + var y4 = 0; + if (d3[y4] !== " ") { + for (var C3 = 0, E4 = 0; d3[y4] === c4; ) + C3++, y4++; + for (var O3 = (d3.length - y4) * u3 + 1 >>> 0, P2 = new Uint8Array(O3); d3[y4]; ) { + var v2 = t[d3.charCodeAt(y4)]; + if (v2 === 255) + return; + for (var A2 = 0, U2 = O3 - 1; (v2 !== 0 || A2 < E4) && U2 !== -1; U2--, A2++) + v2 += h5 * P2[U2] >>> 0, P2[U2] = v2 % 256 >>> 0, v2 = v2 / 256 >>> 0; + if (v2 !== 0) + throw new Error("Non-zero carry"); + E4 = A2, y4++; + } + if (d3[y4] !== " ") { + for (var T2 = O3 - E4; T2 !== O3 && P2[T2] === 0; ) + T2++; + for (var N10 = new Uint8Array(C3 + (O3 - T2)), Y = C3; T2 !== O3; ) + N10[Y++] = P2[T2++]; + return N10; + } + } + } + function F(d3) { + var y4 = b4(d3); + if (y4) + return y4; + throw new Error(`Non-${e2} character`); + } + return { encode: D2, decodeUnsafe: b4, decode: F }; + } + var Ft = zt; + var Mt = Ft; + var ae = (n3) => { + if (n3 instanceof Uint8Array && n3.constructor.name === "Uint8Array") + return n3; + if (n3 instanceof ArrayBuffer) + return new Uint8Array(n3); + if (ArrayBuffer.isView(n3)) + return new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength); + throw new Error("Unknown type, must be binary type"); + }; + var Bt = (n3) => new TextEncoder().encode(n3); + var $t = (n3) => new TextDecoder().decode(n3); + var kt = class { + constructor(e2, t, i2) { + this.name = e2, this.prefix = t, this.baseEncode = i2; + } + encode(e2) { + if (e2 instanceof Uint8Array) + return `${this.prefix}${this.baseEncode(e2)}`; + throw Error("Unknown type, must be binary type"); + } + }; + var Vt = class { + constructor(e2, t, i2) { + if (this.name = e2, this.prefix = t, t.codePointAt(0) === void 0) + throw new Error("Invalid prefix character"); + this.prefixCodePoint = t.codePointAt(0), this.baseDecode = i2; + } + decode(e2) { + if (typeof e2 == "string") { + if (e2.codePointAt(0) !== this.prefixCodePoint) + throw Error(`Unable to decode multibase string ${JSON.stringify(e2)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); + return this.baseDecode(e2.slice(this.prefix.length)); + } else + throw Error("Can only multibase decode strings"); + } + or(e2) { + return he(this, e2); + } + }; + var Kt = class { + constructor(e2) { + this.decoders = e2; + } + or(e2) { + return he(this, e2); + } + decode(e2) { + const t = e2[0], i2 = this.decoders[t]; + if (i2) + return i2.decode(e2); + throw RangeError(`Unable to decode multibase string ${JSON.stringify(e2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + } + }; + var he = (n3, e2) => new Kt({ ...n3.decoders || { [n3.prefix]: n3 }, ...e2.decoders || { [e2.prefix]: e2 } }); + var qt = class { + constructor(e2, t, i2, s2) { + this.name = e2, this.prefix = t, this.baseEncode = i2, this.baseDecode = s2, this.encoder = new kt(e2, t, i2), this.decoder = new Vt(e2, t, s2); + } + encode(e2) { + return this.encoder.encode(e2); + } + decode(e2) { + return this.decoder.decode(e2); + } + }; + var G = ({ name: n3, prefix: e2, encode: t, decode: i2 }) => new qt(n3, e2, t, i2); + var V = ({ prefix: n3, name: e2, alphabet: t }) => { + const { encode: i2, decode: s2 } = Mt(t, e2); + return G({ prefix: n3, name: e2, encode: i2, decode: (r) => ae(s2(r)) }); + }; + var Yt = (n3, e2, t, i2) => { + const s2 = {}; + for (let p3 = 0; p3 < e2.length; ++p3) + s2[e2[p3]] = p3; + let r = n3.length; + for (; n3[r - 1] === "="; ) + --r; + const o2 = new Uint8Array(r * t / 8 | 0); + let h5 = 0, c4 = 0, u3 = 0; + for (let p3 = 0; p3 < r; ++p3) { + const D2 = s2[n3[p3]]; + if (D2 === void 0) + throw new SyntaxError(`Non-${i2} character`); + c4 = c4 << t | D2, h5 += t, h5 >= 8 && (h5 -= 8, o2[u3++] = 255 & c4 >> h5); + } + if (h5 >= t || 255 & c4 << 8 - h5) + throw new SyntaxError("Unexpected end of data"); + return o2; + }; + var jt = (n3, e2, t) => { + const i2 = e2[e2.length - 1] === "=", s2 = (1 << t) - 1; + let r = "", o2 = 0, h5 = 0; + for (let c4 = 0; c4 < n3.length; ++c4) + for (h5 = h5 << 8 | n3[c4], o2 += 8; o2 > t; ) + o2 -= t, r += e2[s2 & h5 >> o2]; + if (o2 && (r += e2[s2 & h5 << t - o2]), i2) + for (; r.length * t & 7; ) + r += "="; + return r; + }; + var m3 = ({ name: n3, prefix: e2, bitsPerChar: t, alphabet: i2 }) => G({ prefix: e2, name: n3, encode(s2) { + return jt(s2, i2, t); + }, decode(s2) { + return Yt(s2, i2, t, n3); + } }); + var Gt = G({ prefix: "\0", name: "identity", encode: (n3) => $t(n3), decode: (n3) => Bt(n3) }); + var Ht = Object.freeze({ __proto__: null, identity: Gt }); + var Xt = m3({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); + var Jt = Object.freeze({ __proto__: null, base2: Xt }); + var Wt = m3({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); + var Qt = Object.freeze({ __proto__: null, base8: Wt }); + var Zt = V({ prefix: "9", name: "base10", alphabet: "0123456789" }); + var ei = Object.freeze({ __proto__: null, base10: Zt }); + var ti = m3({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); + var ii = m3({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); + var si = Object.freeze({ __proto__: null, base16: ti, base16upper: ii }); + var ri = m3({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); + var ni = m3({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); + var oi = m3({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); + var ai = m3({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); + var hi = m3({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); + var ci = m3({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); + var li = m3({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); + var ui = m3({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); + var gi = m3({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); + var di = Object.freeze({ __proto__: null, base32: ri, base32upper: ni, base32pad: oi, base32padupper: ai, base32hex: hi, base32hexupper: ci, base32hexpad: li, base32hexpadupper: ui, base32z: gi }); + var pi = V({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); + var Di = V({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); + var yi = Object.freeze({ __proto__: null, base36: pi, base36upper: Di }); + var Ei = V({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); + var mi = V({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); + var bi = Object.freeze({ __proto__: null, base58btc: Ei, base58flickr: mi }); + var fi = m3({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); + var wi = m3({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); + var vi = m3({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); + var Ii = m3({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); + var Ri = Object.freeze({ __proto__: null, base64: fi, base64pad: wi, base64url: vi, base64urlpad: Ii }); + var ce = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); + var _i = ce.reduce((n3, e2, t) => (n3[t] = e2, n3), []); + var Ci = ce.reduce((n3, e2, t) => (n3[e2.codePointAt(0)] = t, n3), []); + function Ti(n3) { + return n3.reduce((e2, t) => (e2 += _i[t], e2), ""); + } + function Si(n3) { + const e2 = []; + for (const t of n3) { + const i2 = Ci[t.codePointAt(0)]; + if (i2 === void 0) + throw new Error(`Non-base256emoji character: ${t}`); + e2.push(i2); + } + return new Uint8Array(e2); + } + var Oi = G({ prefix: "\u{1F680}", name: "base256emoji", encode: Ti, decode: Si }); + var Pi = Object.freeze({ __proto__: null, base256emoji: Oi }); + var Ai = ue; + var le = 128; + var xi = 127; + var Ni = ~xi; + var Li = Math.pow(2, 31); + function ue(n3, e2, t) { + e2 = e2 || [], t = t || 0; + for (var i2 = t; n3 >= Li; ) + e2[t++] = n3 & 255 | le, n3 /= 128; + for (; n3 & Ni; ) + e2[t++] = n3 & 255 | le, n3 >>>= 7; + return e2[t] = n3 | 0, ue.bytes = t - i2 + 1, e2; + } + var Ui = Q; + var zi = 128; + var ge = 127; + function Q(n3, i2) { + var t = 0, i2 = i2 || 0, s2 = 0, r = i2, o2, h5 = n3.length; + do { + if (r >= h5) + throw Q.bytes = 0, new RangeError("Could not decode varint"); + o2 = n3[r++], t += s2 < 28 ? (o2 & ge) << s2 : (o2 & ge) * Math.pow(2, s2), s2 += 7; + } while (o2 >= zi); + return Q.bytes = r - i2, t; + } + var Fi = Math.pow(2, 7); + var Mi = Math.pow(2, 14); + var Bi = Math.pow(2, 21); + var $i = Math.pow(2, 28); + var ki = Math.pow(2, 35); + var Vi = Math.pow(2, 42); + var Ki = Math.pow(2, 49); + var qi = Math.pow(2, 56); + var Yi = Math.pow(2, 63); + var ji = function(n3) { + return n3 < Fi ? 1 : n3 < Mi ? 2 : n3 < Bi ? 3 : n3 < $i ? 4 : n3 < ki ? 5 : n3 < Vi ? 6 : n3 < Ki ? 7 : n3 < qi ? 8 : n3 < Yi ? 9 : 10; + }; + var Gi = { encode: Ai, decode: Ui, encodingLength: ji }; + var de = Gi; + var pe = (n3, e2, t = 0) => (de.encode(n3, e2, t), e2); + var De = (n3) => de.encodingLength(n3); + var Z = (n3, e2) => { + const t = e2.byteLength, i2 = De(n3), s2 = i2 + De(t), r = new Uint8Array(s2 + t); + return pe(n3, r, 0), pe(t, r, i2), r.set(e2, s2), new Hi(n3, t, e2, r); + }; + var Hi = class { + constructor(e2, t, i2, s2) { + this.code = e2, this.size = t, this.digest = i2, this.bytes = s2; + } + }; + var ye = ({ name: n3, code: e2, encode: t }) => new Xi(n3, e2, t); + var Xi = class { + constructor(e2, t, i2) { + this.name = e2, this.code = t, this.encode = i2; + } + digest(e2) { + if (e2 instanceof Uint8Array) { + const t = this.encode(e2); + return t instanceof Uint8Array ? Z(this.code, t) : t.then((i2) => Z(this.code, i2)); + } else + throw Error("Unknown type, must be binary type"); + } + }; + var Ee = (n3) => async (e2) => new Uint8Array(await crypto.subtle.digest(n3, e2)); + var Ji = ye({ name: "sha2-256", code: 18, encode: Ee("SHA-256") }); + var Wi = ye({ name: "sha2-512", code: 19, encode: Ee("SHA-512") }); + var Qi = Object.freeze({ __proto__: null, sha256: Ji, sha512: Wi }); + var me = 0; + var Zi = "identity"; + var be = ae; + var es = (n3) => Z(me, be(n3)); + var ts = { code: me, name: Zi, encode: be, digest: es }; + var is = Object.freeze({ __proto__: null, identity: ts }); + new TextEncoder(), new TextDecoder(); + var fe = { ...Ht, ...Jt, ...Qt, ...ei, ...si, ...di, ...yi, ...bi, ...Ri, ...Pi }; + ({ ...Qi, ...is }); + function we(n3) { + return globalThis.Buffer != null ? new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength) : n3; + } + function ss(n3 = 0) { + return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? we(globalThis.Buffer.allocUnsafe(n3)) : new Uint8Array(n3); + } + function ve(n3, e2, t, i2) { + return { name: n3, prefix: e2, encoder: { name: n3, prefix: e2, encode: t }, decoder: { decode: i2 } }; + } + var Ie = ve("utf8", "u", (n3) => "u" + new TextDecoder("utf8").decode(n3), (n3) => new TextEncoder().encode(n3.substring(1))); + var ee = ve("ascii", "a", (n3) => { + let e2 = "a"; + for (let t = 0; t < n3.length; t++) + e2 += String.fromCharCode(n3[t]); + return e2; + }, (n3) => { + n3 = n3.substring(1); + const e2 = ss(n3.length); + for (let t = 0; t < n3.length; t++) + e2[t] = n3.charCodeAt(t); + return e2; + }); + var rs = { utf8: Ie, "utf-8": Ie, hex: fe.base16, latin1: ee, ascii: ee, binary: ee, ...fe }; + function ns(n3, e2 = "utf8") { + const t = rs[e2]; + if (!t) + throw new Error(`Unsupported encoding "${e2}"`); + return (e2 === "utf8" || e2 === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? we(globalThis.Buffer.from(n3, "utf-8")) : t.decoder.decode(`${t.prefix}${n3}`); + } + var te = "wc"; + var Re = 2; + var H = "core"; + var L2 = `${te}@2:${H}:`; + var _e = { name: H, logger: "error" }; + var Ce = { database: ":memory:" }; + var Te = "crypto"; + var ie = "client_ed25519_seed"; + var Se = l4.ONE_DAY; + var Oe = "keychain"; + var Pe = "0.3"; + var Ae = "messages"; + var xe = "0.3"; + var Ne = l4.SIX_HOURS; + var Le = "publisher"; + var Ue = "irn"; + var ze = "error"; + var se = "wss://relay.walletconnect.com"; + var re = "wss://relay.walletconnect.org"; + var Fe = "relayer"; + var I2 = { message: "relayer_message", message_ack: "relayer_message_ack", connect: "relayer_connect", disconnect: "relayer_disconnect", error: "relayer_error", connection_stalled: "relayer_connection_stalled", transport_closed: "relayer_transport_closed", publish: "relayer_publish" }; + var Me = "_subscription"; + var w4 = { payload: "payload", connect: "connect", disconnect: "disconnect", error: "error" }; + var Be = l4.ONE_SECOND; + var os = { database: ":memory:" }; + var $e = "2.12.2"; + var ke = 1e4; + var Ve = "0.3"; + var Ke = "WALLETCONNECT_CLIENT_ID"; + var S4 = { created: "subscription_created", deleted: "subscription_deleted", expired: "subscription_expired", disabled: "subscription_disabled", sync: "subscription_sync", resubscribed: "subscription_resubscribed" }; + var as = l4.THIRTY_DAYS; + var qe = "subscription"; + var Ye = "0.3"; + var je = l4.FIVE_SECONDS * 1e3; + var Ge = "pairing"; + var He = "0.3"; + var hs = l4.THIRTY_DAYS; + var M = { wc_pairingDelete: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 1e3 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 1001 } }, wc_pairingPing: { req: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1002 }, res: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1003 } }, unregistered_method: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 0 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 0 } } }; + var K2 = { create: "pairing_create", expire: "pairing_expire", delete: "pairing_delete", ping: "pairing_ping" }; + var R2 = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; + var Xe = "history"; + var Je = "0.3"; + var We = "expirer"; + var _4 = { created: "expirer_created", deleted: "expirer_deleted", expired: "expirer_expired", sync: "expirer_sync" }; + var Qe = "0.3"; + var cs = l4.ONE_DAY; + var X = "verify-api"; + var B2 = "https://verify.walletconnect.com"; + var J = "https://verify.walletconnect.org"; + var Ze = [B2, J]; + var et = "echo"; + var tt = "https://echo.walletconnect.com"; + var it = class { + constructor(e2, t) { + this.core = e2, this.logger = t, this.keychain = /* @__PURE__ */ new Map(), this.name = Oe, this.version = Pe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { + if (!this.initialized) { + const i2 = await this.getKeyChain(); + typeof i2 < "u" && (this.keychain = i2), this.initialized = true; + } + }, this.has = (i2) => (this.isInitialized(), this.keychain.has(i2)), this.set = async (i2, s2) => { + this.isInitialized(), this.keychain.set(i2, s2), await this.persist(); + }, this.get = (i2) => { + this.isInitialized(); + const s2 = this.keychain.get(i2); + if (typeof s2 > "u") { + const { message: r } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${i2}`); + throw new Error(r); + } + return s2; + }, this.del = async (i2) => { + this.isInitialized(), this.keychain.delete(i2), await this.persist(); + }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + async setKeyChain(e2) { + await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); + } + async getKeyChain() { + const e2 = await this.core.storage.getItem(this.storageKey); + return typeof e2 < "u" ? a3.objToMap(e2) : void 0; + } + async persist() { + await this.setKeyChain(this.keychain); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var st = class { + constructor(e2, t, i2) { + this.core = e2, this.logger = t, this.name = Te, this.initialized = false, this.init = async () => { + this.initialized || (await this.keychain.init(), this.initialized = true); + }, this.hasKeys = (s2) => (this.isInitialized(), this.keychain.has(s2)), this.getClientId = async () => { + this.isInitialized(); + const s2 = await this.getClientSeed(), r = j2.generateKeyPair(s2); + return j2.encodeIss(r.publicKey); + }, this.generateKeyPair = () => { + this.isInitialized(); + const s2 = a3.generateKeyPair(); + return this.setPrivateKey(s2.publicKey, s2.privateKey); + }, this.signJWT = async (s2) => { + this.isInitialized(); + const r = await this.getClientSeed(), o2 = j2.generateKeyPair(r), h5 = a3.generateRandomBytes32(), c4 = Se; + return await j2.signJWT(h5, s2, c4, o2); + }, this.generateSharedKey = (s2, r, o2) => { + this.isInitialized(); + const h5 = this.getPrivateKey(s2), c4 = a3.deriveSymKey(h5, r); + return this.setSymKey(c4, o2); + }, this.setSymKey = async (s2, r) => { + this.isInitialized(); + const o2 = r || a3.hashKey(s2); + return await this.keychain.set(o2, s2), o2; + }, this.deleteKeyPair = async (s2) => { + this.isInitialized(), await this.keychain.del(s2); + }, this.deleteSymKey = async (s2) => { + this.isInitialized(), await this.keychain.del(s2); + }, this.encode = async (s2, r, o2) => { + this.isInitialized(); + const h5 = a3.validateEncoding(o2), c4 = oe.safeJsonStringify(r); + if (a3.isTypeOneEnvelope(h5)) { + const b4 = h5.senderPublicKey, F = h5.receiverPublicKey; + s2 = await this.generateSharedKey(b4, F); + } + const u3 = this.getSymKey(s2), { type: p3, senderPublicKey: D2 } = h5; + return a3.encrypt({ type: p3, symKey: u3, message: c4, senderPublicKey: D2 }); + }, this.decode = async (s2, r, o2) => { + this.isInitialized(); + const h5 = a3.validateDecoding(r, o2); + if (a3.isTypeOneEnvelope(h5)) { + const c4 = h5.receiverPublicKey, u3 = h5.senderPublicKey; + s2 = await this.generateSharedKey(c4, u3); + } + try { + const c4 = this.getSymKey(s2), u3 = a3.decrypt({ symKey: c4, encoded: r }); + return oe.safeJsonParse(u3); + } catch (c4) { + this.logger.error(`Failed to decode message from topic: '${s2}', clientId: '${await this.getClientId()}'`), this.logger.error(c4); + } + }, this.getPayloadType = (s2) => { + const r = a3.deserialize(s2); + return a3.decodeTypeByte(r.type); + }, this.getPayloadSenderPublicKey = (s2) => { + const r = a3.deserialize(s2); + return r.senderPublicKey ? _t.toString(r.senderPublicKey, a3.BASE16) : void 0; + }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.keychain = i2 || new it(this.core, this.logger); + } + get context() { + return g3.getLoggerContext(this.logger); + } + async setPrivateKey(e2, t) { + return await this.keychain.set(e2, t), e2; + } + getPrivateKey(e2) { + return this.keychain.get(e2); + } + async getClientSeed() { + let e2 = ""; + try { + e2 = this.keychain.get(ie); + } catch { + e2 = a3.generateRandomBytes32(), await this.keychain.set(ie, e2); + } + return ns(e2, "base16"); + } + getSymKey(e2) { + return this.keychain.get(e2); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var rt = class extends x3.IMessageTracker { + constructor(e2, t) { + super(e2, t), this.logger = e2, this.core = t, this.messages = /* @__PURE__ */ new Map(), this.name = Ae, this.version = xe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { + if (!this.initialized) { + this.logger.trace("Initialized"); + try { + const i2 = await this.getRelayerMessages(); + typeof i2 < "u" && (this.messages = i2), this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", size: this.messages.size }); + } catch (i2) { + this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(i2); + } finally { + this.initialized = true; + } + } + }, this.set = async (i2, s2) => { + this.isInitialized(); + const r = a3.hashMessage(s2); + let o2 = this.messages.get(i2); + return typeof o2 > "u" && (o2 = {}), typeof o2[r] < "u" || (o2[r] = s2, this.messages.set(i2, o2), await this.persist()), r; + }, this.get = (i2) => { + this.isInitialized(); + let s2 = this.messages.get(i2); + return typeof s2 > "u" && (s2 = {}), s2; + }, this.has = (i2, s2) => { + this.isInitialized(); + const r = this.get(i2), o2 = a3.hashMessage(s2); + return typeof r[o2] < "u"; + }, this.del = async (i2) => { + this.isInitialized(), this.messages.delete(i2), await this.persist(); + }, this.logger = g3.generateChildLogger(e2, this.name), this.core = t; + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + async setRelayerMessages(e2) { + await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); + } + async getRelayerMessages() { + const e2 = await this.core.storage.getItem(this.storageKey); + return typeof e2 < "u" ? a3.objToMap(e2) : void 0; + } + async persist() { + await this.setRelayerMessages(this.messages); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var ls2 = class extends x3.IPublisher { + constructor(e2, t) { + super(e2, t), this.relayer = e2, this.logger = t, this.events = new z3.EventEmitter(), this.name = Le, this.queue = /* @__PURE__ */ new Map(), this.publishTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.failedPublishTimeout = l4.toMiliseconds(l4.ONE_SECOND), this.needsTransportRestart = false, this.publish = async (i2, s2, r) => { + var o2; + this.logger.debug("Publishing Payload"), this.logger.trace({ type: "method", method: "publish", params: { topic: i2, message: s2, opts: r } }); + const h5 = r?.ttl || Ne, c4 = a3.getRelayProtocolName(r), u3 = r?.prompt || false, p3 = r?.tag || 0, D2 = r?.id || f4.getBigIntRpcId().toString(), b4 = { topic: i2, message: s2, opts: { ttl: h5, relay: c4, prompt: u3, tag: p3, id: D2 } }, F = `Failed to publish payload, please try again. id:${D2} tag:${p3}`, d3 = Date.now(); + let y4, C3 = 1; + try { + for (; y4 === void 0; ) { + if (Date.now() - d3 > this.publishTimeout) + throw new Error(F); + this.logger.trace({ id: D2, attempts: C3 }, `publisher.publish - attempt ${C3}`), y4 = await await a3.createExpiringPromise(this.rpcPublish(i2, s2, h5, c4, u3, p3, D2).catch((E4) => this.logger.warn(E4)), this.publishTimeout, F), C3++, y4 || await new Promise((E4) => setTimeout(E4, this.failedPublishTimeout)); + } + this.relayer.events.emit(I2.publish, b4), this.logger.debug("Successfully Published Payload"), this.logger.trace({ type: "method", method: "publish", params: { id: D2, topic: i2, message: s2, opts: r } }); + } catch (E4) { + if (this.logger.debug("Failed to Publish Payload"), this.logger.error(E4), (o2 = r?.internal) != null && o2.throwOnFailedPublish) + throw E4; + this.queue.set(D2, b4); + } + }, this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.registerEventListeners(); + } + get context() { + return g3.getLoggerContext(this.logger); + } + rpcPublish(e2, t, i2, s2, r, o2, h5) { + var c4, u3, p3, D2; + const b4 = { method: a3.getRelayProtocolApi(s2.protocol).publish, params: { topic: e2, message: t, ttl: i2, prompt: r, tag: o2 }, id: h5 }; + return a3.isUndefined((c4 = b4.params) == null ? void 0 : c4.prompt) && ((u3 = b4.params) == null || delete u3.prompt), a3.isUndefined((p3 = b4.params) == null ? void 0 : p3.tag) && ((D2 = b4.params) == null || delete D2.tag), this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "message", direction: "outgoing", request: b4 }), this.relayer.request(b4); + } + removeRequestFromQueue(e2) { + this.queue.delete(e2); + } + checkQueue() { + this.queue.forEach(async (e2) => { + const { topic: t, message: i2, opts: s2 } = e2; + await this.publish(t, i2, s2); + }); + } + registerEventListeners() { + this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { + if (this.needsTransportRestart) { + this.needsTransportRestart = false, this.relayer.events.emit(I2.connection_stalled); + return; + } + this.checkQueue(); + }), this.relayer.on(I2.message_ack, (e2) => { + this.removeRequestFromQueue(e2.id.toString()); + }); + } + }; + var us = class { + constructor() { + this.map = /* @__PURE__ */ new Map(), this.set = (e2, t) => { + const i2 = this.get(e2); + this.exists(e2, t) || this.map.set(e2, [...i2, t]); + }, this.get = (e2) => this.map.get(e2) || [], this.exists = (e2, t) => this.get(e2).includes(t), this.delete = (e2, t) => { + if (typeof t > "u") { + this.map.delete(e2); + return; + } + if (!this.map.has(e2)) + return; + const i2 = this.get(e2); + if (!this.exists(e2, t)) + return; + const s2 = i2.filter((r) => r !== t); + if (!s2.length) { + this.map.delete(e2); + return; + } + this.map.set(e2, s2); + }, this.clear = () => { + this.map.clear(); + }; + } + get topics() { + return Array.from(this.map.keys()); + } + }; + var gs = Object.defineProperty; + var ds = Object.defineProperties; + var ps = Object.getOwnPropertyDescriptors; + var nt = Object.getOwnPropertySymbols; + var Ds = Object.prototype.hasOwnProperty; + var ys = Object.prototype.propertyIsEnumerable; + var ot = (n3, e2, t) => e2 in n3 ? gs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var q2 = (n3, e2) => { + for (var t in e2 || (e2 = {})) + Ds.call(e2, t) && ot(n3, t, e2[t]); + if (nt) + for (var t of nt(e2)) + ys.call(e2, t) && ot(n3, t, e2[t]); + return n3; + }; + var ne = (n3, e2) => ds(n3, ps(e2)); + var at = class extends x3.ISubscriber { + constructor(e2, t) { + super(e2, t), this.relayer = e2, this.logger = t, this.subscriptions = /* @__PURE__ */ new Map(), this.topicMap = new us(), this.events = new z3.EventEmitter(), this.name = qe, this.version = Ye, this.pending = /* @__PURE__ */ new Map(), this.cached = [], this.initialized = false, this.pendingSubscriptionWatchLabel = "pending_sub_watch_label", this.pollingInterval = 20, this.storagePrefix = L2, this.subscribeTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.restartInProgress = false, this.batchSubscribeTopicsLimit = 500, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), this.registerEventListeners(), this.clientId = await this.relayer.core.crypto.getClientId()); + }, this.subscribe = async (i2, s2) => { + await this.restartToComplete(), this.isInitialized(), this.logger.debug("Subscribing Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } }); + try { + const r = a3.getRelayProtocolName(s2), o2 = { topic: i2, relay: r }; + this.pending.set(i2, o2); + const h5 = await this.rpcSubscribe(i2, r); + return typeof h5 == "string" && (this.onSubscribe(h5, o2), this.logger.debug("Successfully Subscribed Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } })), h5; + } catch (r) { + throw this.logger.debug("Failed to Subscribe Topic"), this.logger.error(r), r; + } + }, this.unsubscribe = async (i2, s2) => { + await this.restartToComplete(), this.isInitialized(), typeof s2?.id < "u" ? await this.unsubscribeById(i2, s2.id, s2) : await this.unsubscribeByTopic(i2, s2); + }, this.isSubscribed = async (i2) => { + if (this.topics.includes(i2)) + return true; + const s2 = `${this.pendingSubscriptionWatchLabel}_${i2}`; + return await new Promise((r, o2) => { + const h5 = new l4.Watch(); + h5.start(s2); + const c4 = setInterval(() => { + !this.pending.has(i2) && this.topics.includes(i2) && (clearInterval(c4), h5.stop(s2), r(true)), h5.elapsed(s2) >= je && (clearInterval(c4), h5.stop(s2), o2(new Error("Subscription resolution timeout"))); + }, this.pollingInterval); + }).catch(() => false); + }, this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.start = async () => { + await this.onConnect(); + }, this.stop = async () => { + await this.onDisconnect(); + }, this.restart = async () => { + this.restartInProgress = true, await this.restore(), await this.reset(), this.restartInProgress = false; + }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.clientId = ""; + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.relayer.core.customStoragePrefix + "//" + this.name; + } + get length() { + return this.subscriptions.size; + } + get ids() { + return Array.from(this.subscriptions.keys()); + } + get values() { + return Array.from(this.subscriptions.values()); + } + get topics() { + return this.topicMap.topics; + } + hasSubscription(e2, t) { + let i2 = false; + try { + i2 = this.getSubscription(e2).topic === t; + } catch { + } + return i2; + } + onEnable() { + this.cached = [], this.initialized = true; + } + onDisable() { + this.cached = this.values, this.subscriptions.clear(), this.topicMap.clear(); + } + async unsubscribeByTopic(e2, t) { + const i2 = this.topicMap.get(e2); + await Promise.all(i2.map(async (s2) => await this.unsubscribeById(e2, s2, t))); + } + async unsubscribeById(e2, t, i2) { + this.logger.debug("Unsubscribing Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); + try { + const s2 = a3.getRelayProtocolName(i2); + await this.rpcUnsubscribe(e2, t, s2); + const r = a3.getSdkError("USER_DISCONNECTED", `${this.name}, ${e2}`); + await this.onUnsubscribe(e2, t, r), this.logger.debug("Successfully Unsubscribed Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); + } catch (s2) { + throw this.logger.debug("Failed to Unsubscribe Topic"), this.logger.error(s2), s2; + } + } + async rpcSubscribe(e2, t) { + const i2 = { method: a3.getRelayProtocolApi(t.protocol).subscribe, params: { topic: e2 } }; + this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); + try { + return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout) ? a3.hashMessage(e2 + this.clientId) : null; + } catch { + this.logger.debug("Outgoing Relay Subscribe Payload stalled"), this.relayer.events.emit(I2.connection_stalled); + } + return null; + } + async rpcBatchSubscribe(e2) { + if (!e2.length) + return; + const t = e2[0].relay, i2 = { method: a3.getRelayProtocolApi(t.protocol).batchSubscribe, params: { topics: e2.map((s2) => s2.topic) } }; + this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); + try { + return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout); + } catch { + this.relayer.events.emit(I2.connection_stalled); + } + } + rpcUnsubscribe(e2, t, i2) { + const s2 = { method: a3.getRelayProtocolApi(i2.protocol).unsubscribe, params: { topic: e2, id: t } }; + return this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s2 }), this.relayer.request(s2); + } + onSubscribe(e2, t) { + this.setSubscription(e2, ne(q2({}, t), { id: e2 })), this.pending.delete(t.topic); + } + onBatchSubscribe(e2) { + e2.length && e2.forEach((t) => { + this.setSubscription(t.id, q2({}, t)), this.pending.delete(t.topic); + }); + } + async onUnsubscribe(e2, t, i2) { + this.events.removeAllListeners(t), this.hasSubscription(t, e2) && this.deleteSubscription(t, i2), await this.relayer.messages.del(e2); + } + async setRelayerSubscriptions(e2) { + await this.relayer.core.storage.setItem(this.storageKey, e2); + } + async getRelayerSubscriptions() { + return await this.relayer.core.storage.getItem(this.storageKey); + } + setSubscription(e2, t) { + this.logger.debug("Setting subscription"), this.logger.trace({ type: "method", method: "setSubscription", id: e2, subscription: t }), this.addSubscription(e2, t); + } + addSubscription(e2, t) { + this.subscriptions.set(e2, q2({}, t)), this.topicMap.set(t.topic, e2), this.events.emit(S4.created, t); + } + getSubscription(e2) { + this.logger.debug("Getting subscription"), this.logger.trace({ type: "method", method: "getSubscription", id: e2 }); + const t = this.subscriptions.get(e2); + if (!t) { + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw new Error(i2); + } + return t; + } + deleteSubscription(e2, t) { + this.logger.debug("Deleting subscription"), this.logger.trace({ type: "method", method: "deleteSubscription", id: e2, reason: t }); + const i2 = this.getSubscription(e2); + this.subscriptions.delete(e2), this.topicMap.delete(i2.topic, e2), this.events.emit(S4.deleted, ne(q2({}, i2), { reason: t })); + } + async persist() { + await this.setRelayerSubscriptions(this.values), this.events.emit(S4.sync); + } + async reset() { + if (this.cached.length) { + const e2 = Math.ceil(this.cached.length / this.batchSubscribeTopicsLimit); + for (let t = 0; t < e2; t++) { + const i2 = this.cached.splice(0, this.batchSubscribeTopicsLimit); + await this.batchSubscribe(i2); + } + } + this.events.emit(S4.resubscribed); + } + async restore() { + try { + const e2 = await this.getRelayerSubscriptions(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.subscriptions.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored subscriptions for ${this.name}`), this.logger.trace({ type: "method", method: "restore", subscriptions: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore subscriptions for ${this.name}`), this.logger.error(e2); + } + } + async batchSubscribe(e2) { + if (!e2.length) + return; + const t = await this.rpcBatchSubscribe(e2); + a3.isValidArray(t) && this.onBatchSubscribe(t.map((i2, s2) => ne(q2({}, e2[s2]), { id: i2 }))); + } + async onConnect() { + await this.restart(), this.onEnable(); + } + onDisconnect() { + this.onDisable(); + } + async checkPending() { + if (!this.initialized || !this.relayer.connected) + return; + const e2 = []; + this.pending.forEach((t) => { + e2.push(t); + }), await this.batchSubscribe(e2); + } + registerEventListeners() { + this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, async () => { + await this.checkPending(); + }), this.events.on(S4.created, async (e2) => { + const t = S4.created; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); + }), this.events.on(S4.deleted, async (e2) => { + const t = S4.deleted; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); + }); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + async restartToComplete() { + this.restartInProgress && await new Promise((e2) => { + const t = setInterval(() => { + this.restartInProgress || (clearInterval(t), e2()); + }, this.pollingInterval); + }); + } + }; + var Es = Object.defineProperty; + var ht = Object.getOwnPropertySymbols; + var ms = Object.prototype.hasOwnProperty; + var bs = Object.prototype.propertyIsEnumerable; + var ct = (n3, e2, t) => e2 in n3 ? Es(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var fs = (n3, e2) => { + for (var t in e2 || (e2 = {})) + ms.call(e2, t) && ct(n3, t, e2[t]); + if (ht) + for (var t of ht(e2)) + bs.call(e2, t) && ct(n3, t, e2[t]); + return n3; + }; + var lt = class extends x3.IRelayer { + constructor(e2) { + super(e2), this.protocol = "wc", this.version = 2, this.events = new z3.EventEmitter(), this.name = Fe, this.transportExplicitlyClosed = false, this.initialized = false, this.connectionAttemptInProgress = false, this.connectionStatusPollingInterval = 20, this.staleConnectionErrors = ["socket hang up", "socket stalled", "interrupted"], this.hasExperiencedNetworkDisruption = false, this.requestsInFlight = /* @__PURE__ */ new Map(), this.heartBeatTimeout = l4.toMiliseconds(l4.THIRTY_SECONDS + l4.ONE_SECOND), this.request = async (t) => { + var i2, s2; + this.logger.debug("Publishing Request Payload"); + const r = t.id || f4.getBigIntRpcId().toString(); + await this.toEstablishConnection(); + try { + const o2 = this.provider.request(t); + this.requestsInFlight.set(r, { promise: o2, request: t }), this.logger.trace({ id: r, method: t.method, topic: (i2 = t.params) == null ? void 0 : i2.topic }, "relayer.request - attempt to publish..."); + const h5 = await new Promise(async (c4, u3) => { + const p3 = () => { + u3(new Error(`relayer.request - publish interrupted, id: ${r}`)); + }; + this.provider.on(w4.disconnect, p3); + const D2 = await o2; + this.provider.off(w4.disconnect, p3), c4(D2); + }); + return this.logger.trace({ id: r, method: t.method, topic: (s2 = t.params) == null ? void 0 : s2.topic }, "relayer.request - published"), h5; + } catch (o2) { + throw this.logger.debug(`Failed to Publish Request: ${r}`), o2; + } finally { + this.requestsInFlight.delete(r); + } + }, this.resetPingTimeout = () => { + if (a3.isNode()) + try { + clearTimeout(this.pingTimeout), this.pingTimeout = setTimeout(() => { + var t, i2, s2; + (s2 = (i2 = (t = this.provider) == null ? void 0 : t.connection) == null ? void 0 : i2.socket) == null || s2.terminate(); + }, this.heartBeatTimeout); + } catch (t) { + this.logger.warn(t); + } + }, this.onPayloadHandler = (t) => { + this.onProviderPayload(t), this.resetPingTimeout(); + }, this.onConnectHandler = () => { + this.startPingTimeout(), this.events.emit(I2.connect); + }, this.onDisconnectHandler = () => { + this.onProviderDisconnect(); + }, this.onProviderErrorHandler = (t) => { + this.logger.error(t), this.events.emit(I2.error, t), this.logger.info("Fatal socket error received, closing transport"), this.transportClose(); + }, this.registerProviderListeners = () => { + this.provider.on(w4.payload, this.onPayloadHandler), this.provider.on(w4.connect, this.onConnectHandler), this.provider.on(w4.disconnect, this.onDisconnectHandler), this.provider.on(w4.error, this.onProviderErrorHandler); + }, this.core = e2.core, this.logger = typeof e2.logger < "u" && typeof e2.logger != "string" ? g3.generateChildLogger(e2.logger, this.name) : g3.pino(g3.getDefaultLoggerOptions({ level: e2.logger || ze })), this.messages = new rt(this.logger, e2.core), this.subscriber = new at(this, this.logger), this.publisher = new ls2(this, this.logger), this.relayUrl = e2?.relayUrl || se, this.projectId = e2.projectId, this.bundleId = a3.getBundleId(), this.provider = {}; + } + async init() { + this.logger.trace("Initialized"), this.registerEventListeners(), await this.createProvider(), await Promise.all([this.messages.init(), this.subscriber.init()]); + try { + await this.transportOpen(); + } catch { + this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${re}...`), await this.restartTransport(re); + } + this.initialized = true, setTimeout(async () => { + this.subscriber.topics.length === 0 && this.subscriber.pending.size === 0 && (this.logger.info("No topics subscribed to after init, closing transport"), await this.transportClose(), this.transportExplicitlyClosed = false); + }, ke); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get connected() { + var e2, t, i2; + return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 1; + } + get connecting() { + var e2, t, i2; + return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 0; + } + async publish(e2, t, i2) { + this.isInitialized(), await this.publisher.publish(e2, t, i2), await this.recordMessageEvent({ topic: e2, message: t, publishedAt: Date.now() }); + } + async subscribe(e2, t) { + var i2; + this.isInitialized(); + let s2 = ((i2 = this.subscriber.topicMap.get(e2)) == null ? void 0 : i2[0]) || "", r; + const o2 = (h5) => { + h5.topic === e2 && (this.subscriber.off(S4.created, o2), r()); + }; + return await Promise.all([new Promise((h5) => { + r = h5, this.subscriber.on(S4.created, o2); + }), new Promise(async (h5) => { + s2 = await this.subscriber.subscribe(e2, t) || s2, h5(); + })]), s2; + } + async unsubscribe(e2, t) { + this.isInitialized(), await this.subscriber.unsubscribe(e2, t); + } + on(e2, t) { + this.events.on(e2, t); + } + once(e2, t) { + this.events.once(e2, t); + } + off(e2, t) { + this.events.off(e2, t); + } + removeListener(e2, t) { + this.events.removeListener(e2, t); + } + async transportDisconnect() { + if (!this.hasExperiencedNetworkDisruption && this.connected && this.requestsInFlight.size > 0) + try { + await Promise.all(Array.from(this.requestsInFlight.values()).map((e2) => e2.promise)); + } catch (e2) { + this.logger.warn(e2); + } + this.hasExperiencedNetworkDisruption || this.connected ? await a3.createExpiringPromise(this.provider.disconnect(), 2e3, "provider.disconnect()").catch(() => this.onProviderDisconnect()) : this.onProviderDisconnect(); + } + async transportClose() { + this.transportExplicitlyClosed = true, await this.transportDisconnect(); + } + async transportOpen(e2) { + await this.confirmOnlineStateOrThrow(), e2 && e2 !== this.relayUrl && (this.relayUrl = e2, await this.transportDisconnect(), await this.createProvider()), this.connectionAttemptInProgress = true, this.transportExplicitlyClosed = false; + try { + await new Promise(async (t, i2) => { + const s2 = () => { + this.provider.off(w4.disconnect, s2), i2(new Error("Connection interrupted while trying to subscribe")); + }; + this.provider.on(w4.disconnect, s2), await a3.createExpiringPromise(this.provider.connect(), l4.toMiliseconds(l4.ONE_MINUTE), `Socket stalled when trying to connect to ${this.relayUrl}`).catch((r) => { + i2(r); + }), await this.subscriber.start(), this.hasExperiencedNetworkDisruption = false, t(); + }); + } catch (t) { + this.logger.error(t); + const i2 = t; + if (!this.isConnectionStalled(i2.message)) + throw t; + } finally { + this.connectionAttemptInProgress = false; + } + } + async restartTransport(e2) { + this.connectionAttemptInProgress || (this.relayUrl = e2 || this.relayUrl, await this.confirmOnlineStateOrThrow(), await this.transportClose(), await this.createProvider(), await this.transportOpen()); + } + async confirmOnlineStateOrThrow() { + if (!await a3.isOnline()) + throw new Error("No internet connection detected. Please restart your network and try again."); + } + startPingTimeout() { + var e2, t, i2, s2, r; + if (a3.isNode()) + try { + (t = (e2 = this.provider) == null ? void 0 : e2.connection) != null && t.socket && ((r = (s2 = (i2 = this.provider) == null ? void 0 : i2.connection) == null ? void 0 : s2.socket) == null || r.once("ping", () => { + this.resetPingTimeout(); + })), this.resetPingTimeout(); + } catch (o2) { + this.logger.warn(o2); + } + } + isConnectionStalled(e2) { + return this.staleConnectionErrors.some((t) => e2.includes(t)); + } + async createProvider() { + this.provider.connection && this.unregisterProviderListeners(); + const e2 = await this.core.crypto.signJWT(this.relayUrl); + this.provider = new Ct.JsonRpcProvider(new Nt.default(a3.formatRelayRpcUrl({ sdkVersion: $e, protocol: this.protocol, version: this.version, relayUrl: this.relayUrl, projectId: this.projectId, auth: e2, useOnCloseEvent: true, bundleId: this.bundleId }))), this.registerProviderListeners(); + } + async recordMessageEvent(e2) { + const { topic: t, message: i2 } = e2; + await this.messages.set(t, i2); + } + async shouldIgnoreMessageEvent(e2) { + const { topic: t, message: i2 } = e2; + if (!i2 || i2.length === 0) + return this.logger.debug(`Ignoring invalid/empty message: ${i2}`), true; + if (!await this.subscriber.isSubscribed(t)) + return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`), true; + const s2 = this.messages.has(t, i2); + return s2 && this.logger.debug(`Ignoring duplicate message: ${i2}`), s2; + } + async onProviderPayload(e2) { + if (this.logger.debug("Incoming Relay Payload"), this.logger.trace({ type: "payload", direction: "incoming", payload: e2 }), f4.isJsonRpcRequest(e2)) { + if (!e2.method.endsWith(Me)) + return; + const t = e2.params, { topic: i2, message: s2, publishedAt: r } = t.data, o2 = { topic: i2, message: s2, publishedAt: r }; + this.logger.debug("Emitting Relayer Payload"), this.logger.trace(fs({ type: "event", event: t.id }, o2)), this.events.emit(t.id, o2), await this.acknowledgePayload(e2), await this.onMessageEvent(o2); + } else + f4.isJsonRpcResponse(e2) && this.events.emit(I2.message_ack, e2); + } + async onMessageEvent(e2) { + await this.shouldIgnoreMessageEvent(e2) || (this.events.emit(I2.message, e2), await this.recordMessageEvent(e2)); + } + async acknowledgePayload(e2) { + const t = f4.formatJsonRpcResult(e2.id, true); + await this.provider.connection.send(t); + } + unregisterProviderListeners() { + this.provider.off(w4.payload, this.onPayloadHandler), this.provider.off(w4.connect, this.onConnectHandler), this.provider.off(w4.disconnect, this.onDisconnectHandler), this.provider.off(w4.error, this.onProviderErrorHandler); + } + async registerEventListeners() { + let e2 = await a3.isOnline(); + a3.subscribeToNetworkChange(async (t) => { + e2 !== t && (e2 = t, t ? await this.restartTransport().catch((i2) => this.logger.error(i2)) : (this.hasExperiencedNetworkDisruption = true, await this.transportDisconnect(), this.transportExplicitlyClosed = false)); + }); + } + async onProviderDisconnect() { + await this.subscriber.stop(), this.events.emit(I2.disconnect), this.connectionAttemptInProgress = false, !this.transportExplicitlyClosed && setTimeout(async () => { + await this.transportOpen().catch((e2) => this.logger.error(e2)); + }, l4.toMiliseconds(Be)); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + async toEstablishConnection() { + await this.confirmOnlineStateOrThrow(), !this.connected && (this.connectionAttemptInProgress && await new Promise((e2) => { + const t = setInterval(() => { + this.connected && (clearInterval(t), e2()); + }, this.connectionStatusPollingInterval); + }), await this.transportOpen()); + } + }; + var ws = Object.defineProperty; + var ut = Object.getOwnPropertySymbols; + var vs = Object.prototype.hasOwnProperty; + var Is = Object.prototype.propertyIsEnumerable; + var gt = (n3, e2, t) => e2 in n3 ? ws(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var dt = (n3, e2) => { + for (var t in e2 || (e2 = {})) + vs.call(e2, t) && gt(n3, t, e2[t]); + if (ut) + for (var t of ut(e2)) + Is.call(e2, t) && gt(n3, t, e2[t]); + return n3; + }; + var pt = class extends x3.IStore { + constructor(e2, t, i2, s2 = L2, r = void 0) { + super(e2, t, i2, s2), this.core = e2, this.logger = t, this.name = i2, this.map = /* @__PURE__ */ new Map(), this.version = Ve, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.recentlyDeleted = [], this.recentlyDeletedLimit = 200, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((o2) => { + this.getKey && o2 !== null && !a3.isUndefined(o2) ? this.map.set(this.getKey(o2), o2) : a3.isProposalStruct(o2) ? this.map.set(o2.id, o2) : a3.isSessionStruct(o2) && this.map.set(o2.topic, o2); + }), this.cached = [], this.initialized = true); + }, this.set = async (o2, h5) => { + this.isInitialized(), this.map.has(o2) ? await this.update(o2, h5) : (this.logger.debug("Setting value"), this.logger.trace({ type: "method", method: "set", key: o2, value: h5 }), this.map.set(o2, h5), await this.persist()); + }, this.get = (o2) => (this.isInitialized(), this.logger.debug("Getting value"), this.logger.trace({ type: "method", method: "get", key: o2 }), this.getData(o2)), this.getAll = (o2) => (this.isInitialized(), o2 ? this.values.filter((h5) => Object.keys(o2).every((c4) => Lt.default(h5[c4], o2[c4]))) : this.values), this.update = async (o2, h5) => { + this.isInitialized(), this.logger.debug("Updating value"), this.logger.trace({ type: "method", method: "update", key: o2, update: h5 }); + const c4 = dt(dt({}, this.getData(o2)), h5); + this.map.set(o2, c4), await this.persist(); + }, this.delete = async (o2, h5) => { + this.isInitialized(), this.map.has(o2) && (this.logger.debug("Deleting value"), this.logger.trace({ type: "method", method: "delete", key: o2, reason: h5 }), this.map.delete(o2), this.addToRecentlyDeleted(o2), await this.persist()); + }, this.logger = g3.generateChildLogger(t, this.name), this.storagePrefix = s2, this.getKey = r; + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + get length() { + return this.map.size; + } + get keys() { + return Array.from(this.map.keys()); + } + get values() { + return Array.from(this.map.values()); + } + addToRecentlyDeleted(e2) { + this.recentlyDeleted.push(e2), this.recentlyDeleted.length >= this.recentlyDeletedLimit && this.recentlyDeleted.splice(0, this.recentlyDeletedLimit / 2); + } + async setDataStore(e2) { + await this.core.storage.setItem(this.storageKey, e2); + } + async getDataStore() { + return await this.core.storage.getItem(this.storageKey); + } + getData(e2) { + const t = this.map.get(e2); + if (!t) { + if (this.recentlyDeleted.includes(e2)) { + const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${this.name}: ${e2}`); + throw this.logger.error(s2), new Error(s2); + } + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw this.logger.error(i2), new Error(i2); + } + return t; + } + async persist() { + await this.setDataStore(this.values); + } + async restore() { + try { + const e2 = await this.getDataStore(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.map.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored value for ${this.name}`), this.logger.trace({ type: "method", method: "restore", value: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore value for ${this.name}`), this.logger.error(e2); + } + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var Dt = class { + constructor(e2, t) { + this.core = e2, this.logger = t, this.name = Ge, this.version = He, this.events = new At.default(), this.initialized = false, this.storagePrefix = L2, this.ignoredPayloadTypes = [a3.TYPE_1], this.registeredMethods = [], this.init = async () => { + this.initialized || (await this.pairings.init(), await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.initialized = true, this.logger.trace("Initialized")); + }, this.register = ({ methods: i2 }) => { + this.isInitialized(), this.registeredMethods = [.../* @__PURE__ */ new Set([...this.registeredMethods, ...i2])]; + }, this.create = async (i2) => { + this.isInitialized(); + const s2 = a3.generateRandomBytes32(), r = await this.core.crypto.setSymKey(s2), o2 = a3.calcExpiry(l4.FIVE_MINUTES), h5 = { protocol: Ue }, c4 = { topic: r, expiry: o2, relay: h5, active: false }, u3 = a3.formatUri({ protocol: this.core.protocol, version: this.core.version, topic: r, symKey: s2, relay: h5, expiryTimestamp: o2, methods: i2?.methods }); + return await this.pairings.set(r, c4), await this.core.relayer.subscribe(r), this.core.expirer.set(r, o2), { topic: r, uri: u3 }; + }, this.pair = async (i2) => { + this.isInitialized(), this.isValidPair(i2); + const { topic: s2, symKey: r, relay: o2, expiryTimestamp: h5, methods: c4 } = a3.parseUri(i2.uri); + let u3; + if (this.pairings.keys.includes(s2) && (u3 = this.pairings.get(s2), u3.active)) + throw new Error(`Pairing already exists: ${s2}. Please try again with a new connection URI.`); + const p3 = h5 || a3.calcExpiry(l4.FIVE_MINUTES), D2 = { topic: s2, relay: o2, expiry: p3, active: false, methods: c4 }; + return await this.pairings.set(s2, D2), this.core.expirer.set(s2, p3), i2.activatePairing && await this.activate({ topic: s2 }), this.events.emit(K2.create, D2), this.core.crypto.keychain.has(s2) || await this.core.crypto.setSymKey(r, s2), await this.core.relayer.subscribe(s2, { relay: o2 }), D2; + }, this.activate = async ({ topic: i2 }) => { + this.isInitialized(); + const s2 = a3.calcExpiry(l4.THIRTY_DAYS); + await this.pairings.update(i2, { active: true, expiry: s2 }), this.core.expirer.set(i2, s2); + }, this.ping = async (i2) => { + this.isInitialized(), await this.isValidPing(i2); + const { topic: s2 } = i2; + if (this.pairings.keys.includes(s2)) { + const r = await this.sendRequest(s2, "wc_pairingPing", {}), { done: o2, resolve: h5, reject: c4 } = a3.createDelayedPromise(); + this.events.once(a3.engineEvent("pairing_ping", r), ({ error: u3 }) => { + u3 ? c4(u3) : h5(); + }), await o2(); + } + }, this.updateExpiry = async ({ topic: i2, expiry: s2 }) => { + this.isInitialized(), await this.pairings.update(i2, { expiry: s2 }); + }, this.updateMetadata = async ({ topic: i2, metadata: s2 }) => { + this.isInitialized(), await this.pairings.update(i2, { peerMetadata: s2 }); + }, this.getPairings = () => (this.isInitialized(), this.pairings.values), this.disconnect = async (i2) => { + this.isInitialized(), await this.isValidDisconnect(i2); + const { topic: s2 } = i2; + this.pairings.keys.includes(s2) && (await this.sendRequest(s2, "wc_pairingDelete", a3.getSdkError("USER_DISCONNECTED")), await this.deletePairing(s2)); + }, this.sendRequest = async (i2, s2, r) => { + const o2 = f4.formatJsonRpcRequest(s2, r), h5 = await this.core.crypto.encode(i2, o2), c4 = M[s2].req; + return this.core.history.set(i2, o2), this.core.relayer.publish(i2, h5, c4), o2.id; + }, this.sendResult = async (i2, s2, r) => { + const o2 = f4.formatJsonRpcResult(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method].res; + await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); + }, this.sendError = async (i2, s2, r) => { + const o2 = f4.formatJsonRpcError(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method] ? M[c4.request.method].res : M.unregistered_method.res; + await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); + }, this.deletePairing = async (i2, s2) => { + await this.core.relayer.unsubscribe(i2), await Promise.all([this.pairings.delete(i2, a3.getSdkError("USER_DISCONNECTED")), this.core.crypto.deleteSymKey(i2), s2 ? Promise.resolve() : this.core.expirer.del(i2)]); + }, this.cleanup = async () => { + const i2 = this.pairings.getAll().filter((s2) => a3.isExpired(s2.expiry)); + await Promise.all(i2.map((s2) => this.deletePairing(s2.topic))); + }, this.onRelayEventRequest = (i2) => { + const { topic: s2, payload: r } = i2; + switch (r.method) { + case "wc_pairingPing": + return this.onPairingPingRequest(s2, r); + case "wc_pairingDelete": + return this.onPairingDeleteRequest(s2, r); + default: + return this.onUnknownRpcMethodRequest(s2, r); + } + }, this.onRelayEventResponse = async (i2) => { + const { topic: s2, payload: r } = i2, o2 = (await this.core.history.get(s2, r.id)).request.method; + switch (o2) { + case "wc_pairingPing": + return this.onPairingPingResponse(s2, r); + default: + return this.onUnknownRpcMethodResponse(o2); + } + }, this.onPairingPingRequest = async (i2, s2) => { + const { id: r } = s2; + try { + this.isValidPing({ topic: i2 }), await this.sendResult(r, i2, true), this.events.emit(K2.ping, { id: r, topic: i2 }); + } catch (o2) { + await this.sendError(r, i2, o2), this.logger.error(o2); + } + }, this.onPairingPingResponse = (i2, s2) => { + const { id: r } = s2; + setTimeout(() => { + f4.isJsonRpcResult(s2) ? this.events.emit(a3.engineEvent("pairing_ping", r), {}) : f4.isJsonRpcError(s2) && this.events.emit(a3.engineEvent("pairing_ping", r), { error: s2.error }); + }, 500); + }, this.onPairingDeleteRequest = async (i2, s2) => { + const { id: r } = s2; + try { + this.isValidDisconnect({ topic: i2 }), await this.deletePairing(i2), this.events.emit(K2.delete, { id: r, topic: i2 }); + } catch (o2) { + await this.sendError(r, i2, o2), this.logger.error(o2); + } + }, this.onUnknownRpcMethodRequest = async (i2, s2) => { + const { id: r, method: o2 } = s2; + try { + if (this.registeredMethods.includes(o2)) + return; + const h5 = a3.getSdkError("WC_METHOD_UNSUPPORTED", o2); + await this.sendError(r, i2, h5), this.logger.error(h5); + } catch (h5) { + await this.sendError(r, i2, h5), this.logger.error(h5); + } + }, this.onUnknownRpcMethodResponse = (i2) => { + this.registeredMethods.includes(i2) || this.logger.error(a3.getSdkError("WC_METHOD_UNSUPPORTED", i2)); + }, this.isValidPair = (i2) => { + var s2; + if (!a3.isValidParams(i2)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() params: ${i2}`); + throw new Error(o2); + } + if (!a3.isValidUrl(i2.uri)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() uri: ${i2.uri}`); + throw new Error(o2); + } + const r = a3.parseUri(i2.uri); + if (!((s2 = r?.relay) != null && s2.protocol)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#relay-protocol"); + throw new Error(o2); + } + if (!(r != null && r.symKey)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#symKey"); + throw new Error(o2); + } + if (r != null && r.expiryTimestamp && l4.toMiliseconds(r?.expiryTimestamp) < Date.now()) { + const { message: o2 } = a3.getInternalError("EXPIRED", "pair() URI has expired. Please try again with a new connection URI."); + throw new Error(o2); + } + }, this.isValidPing = async (i2) => { + if (!a3.isValidParams(i2)) { + const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `ping() params: ${i2}`); + throw new Error(r); + } + const { topic: s2 } = i2; + await this.isValidPairingTopic(s2); + }, this.isValidDisconnect = async (i2) => { + if (!a3.isValidParams(i2)) { + const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${i2}`); + throw new Error(r); + } + const { topic: s2 } = i2; + await this.isValidPairingTopic(s2); + }, this.isValidPairingTopic = async (i2) => { + if (!a3.isValidString(i2, false)) { + const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${i2}`); + throw new Error(s2); + } + if (!this.pairings.keys.includes(i2)) { + const { message: s2 } = a3.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${i2}`); + throw new Error(s2); + } + if (a3.isExpired(this.pairings.get(i2).expiry)) { + await this.deletePairing(i2); + const { message: s2 } = a3.getInternalError("EXPIRED", `pairing topic: ${i2}`); + throw new Error(s2); + } + }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.pairings = new pt(this.core, this.logger, this.name, this.storagePrefix); + } + get context() { + return g3.getLoggerContext(this.logger); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + registerRelayerEvents() { + this.core.relayer.on(I2.message, async (e2) => { + const { topic: t, message: i2 } = e2; + if (!this.pairings.keys.includes(t) || this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i2))) + return; + const s2 = await this.core.crypto.decode(t, i2); + try { + f4.isJsonRpcRequest(s2) ? (this.core.history.set(t, s2), this.onRelayEventRequest({ topic: t, payload: s2 })) : f4.isJsonRpcResponse(s2) && (await this.core.history.resolve(s2), await this.onRelayEventResponse({ topic: t, payload: s2 }), this.core.history.delete(t, s2.id)); + } catch (r) { + this.logger.error(r); + } + }); + } + registerExpirerEvents() { + this.core.expirer.on(_4.expired, async (e2) => { + const { topic: t } = a3.parseExpirerTarget(e2.target); + t && this.pairings.keys.includes(t) && (await this.deletePairing(t, true), this.events.emit(K2.expire, { topic: t })); + }); + } + }; + var yt = class extends x3.IJsonRpcHistory { + constructor(e2, t) { + super(e2, t), this.core = e2, this.logger = t, this.records = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = Xe, this.version = Je, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.records.set(i2.id, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); + }, this.set = (i2, s2, r) => { + if (this.isInitialized(), this.logger.debug("Setting JSON-RPC request history record"), this.logger.trace({ type: "method", method: "set", topic: i2, request: s2, chainId: r }), this.records.has(s2.id)) + return; + const o2 = { id: s2.id, topic: i2, request: { method: s2.method, params: s2.params || null }, chainId: r, expiry: a3.calcExpiry(l4.THIRTY_DAYS) }; + this.records.set(o2.id, o2), this.persist(), this.events.emit(R2.created, o2); + }, this.resolve = async (i2) => { + if (this.isInitialized(), this.logger.debug("Updating JSON-RPC response history record"), this.logger.trace({ type: "method", method: "update", response: i2 }), !this.records.has(i2.id)) + return; + const s2 = await this.getRecord(i2.id); + typeof s2.response > "u" && (s2.response = f4.isJsonRpcError(i2) ? { error: i2.error } : { result: i2.result }, this.records.set(s2.id, s2), this.persist(), this.events.emit(R2.updated, s2)); + }, this.get = async (i2, s2) => (this.isInitialized(), this.logger.debug("Getting record"), this.logger.trace({ type: "method", method: "get", topic: i2, id: s2 }), await this.getRecord(s2)), this.delete = (i2, s2) => { + this.isInitialized(), this.logger.debug("Deleting record"), this.logger.trace({ type: "method", method: "delete", id: s2 }), this.values.forEach((r) => { + if (r.topic === i2) { + if (typeof s2 < "u" && r.id !== s2) + return; + this.records.delete(r.id), this.events.emit(R2.deleted, r); + } + }), this.persist(); + }, this.exists = async (i2, s2) => (this.isInitialized(), this.records.has(s2) ? (await this.getRecord(s2)).topic === i2 : false), this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.logger = g3.generateChildLogger(t, this.name); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + get size() { + return this.records.size; + } + get keys() { + return Array.from(this.records.keys()); + } + get values() { + return Array.from(this.records.values()); + } + get pending() { + const e2 = []; + return this.values.forEach((t) => { + if (typeof t.response < "u") + return; + const i2 = { topic: t.topic, request: f4.formatJsonRpcRequest(t.request.method, t.request.params, t.id), chainId: t.chainId }; + return e2.push(i2); + }), e2; + } + async setJsonRpcRecords(e2) { + await this.core.storage.setItem(this.storageKey, e2); + } + async getJsonRpcRecords() { + return await this.core.storage.getItem(this.storageKey); + } + getRecord(e2) { + this.isInitialized(); + const t = this.records.get(e2); + if (!t) { + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw new Error(i2); + } + return t; + } + async persist() { + await this.setJsonRpcRecords(this.values), this.events.emit(R2.sync); + } + async restore() { + try { + const e2 = await this.getJsonRpcRecords(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.records.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", records: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(e2); + } + } + registerEventListeners() { + this.events.on(R2.created, (e2) => { + const t = R2.created; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); + }), this.events.on(R2.updated, (e2) => { + const t = R2.updated; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); + }), this.events.on(R2.deleted, (e2) => { + const t = R2.deleted; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); + }), this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { + this.cleanup(); + }); + } + cleanup() { + try { + this.isInitialized(); + let e2 = false; + this.records.forEach((t) => { + l4.toMiliseconds(t.expiry || 0) - Date.now() <= 0 && (this.logger.info(`Deleting expired history log: ${t.id}`), this.records.delete(t.id), this.events.emit(R2.deleted, t, false), e2 = true); + }), e2 && this.persist(); + } catch (e2) { + this.logger.warn(e2); + } + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var Et = class extends x3.IExpirer { + constructor(e2, t) { + super(e2, t), this.core = e2, this.logger = t, this.expirations = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = We, this.version = Qe, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.expirations.set(i2.target, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); + }, this.has = (i2) => { + try { + const s2 = this.formatTarget(i2); + return typeof this.getExpiration(s2) < "u"; + } catch { + return false; + } + }, this.set = (i2, s2) => { + this.isInitialized(); + const r = this.formatTarget(i2), o2 = { target: r, expiry: s2 }; + this.expirations.set(r, o2), this.checkExpiry(r, o2), this.events.emit(_4.created, { target: r, expiration: o2 }); + }, this.get = (i2) => { + this.isInitialized(); + const s2 = this.formatTarget(i2); + return this.getExpiration(s2); + }, this.del = (i2) => { + if (this.isInitialized(), this.has(i2)) { + const s2 = this.formatTarget(i2), r = this.getExpiration(s2); + this.expirations.delete(s2), this.events.emit(_4.deleted, { target: s2, expiration: r }); + } + }, this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.logger = g3.generateChildLogger(t, this.name); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + get length() { + return this.expirations.size; + } + get keys() { + return Array.from(this.expirations.keys()); + } + get values() { + return Array.from(this.expirations.values()); + } + formatTarget(e2) { + if (typeof e2 == "string") + return a3.formatTopicTarget(e2); + if (typeof e2 == "number") + return a3.formatIdTarget(e2); + const { message: t } = a3.getInternalError("UNKNOWN_TYPE", `Target type: ${typeof e2}`); + throw new Error(t); + } + async setExpirations(e2) { + await this.core.storage.setItem(this.storageKey, e2); + } + async getExpirations() { + return await this.core.storage.getItem(this.storageKey); + } + async persist() { + await this.setExpirations(this.values), this.events.emit(_4.sync); + } + async restore() { + try { + const e2 = await this.getExpirations(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.expirations.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored expirations for ${this.name}`), this.logger.trace({ type: "method", method: "restore", expirations: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore expirations for ${this.name}`), this.logger.error(e2); + } + } + getExpiration(e2) { + const t = this.expirations.get(e2); + if (!t) { + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw this.logger.warn(i2), new Error(i2); + } + return t; + } + checkExpiry(e2, t) { + const { expiry: i2 } = t; + l4.toMiliseconds(i2) - Date.now() <= 0 && this.expire(e2, t); + } + expire(e2, t) { + this.expirations.delete(e2), this.events.emit(_4.expired, { target: e2, expiration: t }); + } + checkExpirations() { + this.core.relayer.connected && this.expirations.forEach((e2, t) => this.checkExpiry(t, e2)); + } + registerEventListeners() { + this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => this.checkExpirations()), this.events.on(_4.created, (e2) => { + const t = _4.created; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); + }), this.events.on(_4.expired, (e2) => { + const t = _4.expired; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); + }), this.events.on(_4.deleted, (e2) => { + const t = _4.deleted; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); + }); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var mt = class extends x3.IVerify { + constructor(e2, t) { + super(e2, t), this.projectId = e2, this.logger = t, this.name = X, this.initialized = false, this.queue = [], this.verifyDisabled = false, this.init = async (i2) => { + if (this.verifyDisabled || a3.isReactNative() || !a3.isBrowser()) + return; + const s2 = this.getVerifyUrl(i2?.verifyUrl); + this.verifyUrl !== s2 && this.removeIframe(), this.verifyUrl = s2; + try { + await this.createIframe(); + } catch (r) { + this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r); + } + if (!this.initialized) { + this.removeIframe(), this.verifyUrl = J; + try { + await this.createIframe(); + } catch (r) { + this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r), this.verifyDisabled = true; + } + } + }, this.register = async (i2) => { + this.initialized ? this.sendPost(i2.attestationId) : (this.addToQueue(i2.attestationId), await this.init()); + }, this.resolve = async (i2) => { + if (this.isDevEnv) + return ""; + const s2 = this.getVerifyUrl(i2?.verifyUrl); + let r; + try { + r = await this.fetchAttestation(i2.attestationId, s2); + } catch (o2) { + this.logger.info(`failed to resolve attestation: ${i2.attestationId} from url: ${s2}`), this.logger.info(o2), r = await this.fetchAttestation(i2.attestationId, J); + } + return r; + }, this.fetchAttestation = async (i2, s2) => { + this.logger.info(`resolving attestation: ${i2} from url: ${s2}`); + const r = this.startAbortTimer(l4.ONE_SECOND * 2), o2 = await fetch(`${s2}/attestation/${i2}`, { signal: this.abortController.signal }); + return clearTimeout(r), o2.status === 200 ? await o2.json() : void 0; + }, this.addToQueue = (i2) => { + this.queue.push(i2); + }, this.processQueue = () => { + this.queue.length !== 0 && (this.queue.forEach((i2) => this.sendPost(i2)), this.queue = []); + }, this.sendPost = (i2) => { + var s2; + try { + if (!this.iframe) + return; + (s2 = this.iframe.contentWindow) == null || s2.postMessage(i2, "*"), this.logger.info(`postMessage sent: ${i2} ${this.verifyUrl}`); + } catch { + } + }, this.createIframe = async () => { + let i2; + const s2 = (r) => { + r.data === "verify_ready" && (this.onInit(), window.removeEventListener("message", s2), i2()); + }; + await Promise.race([new Promise((r) => { + const o2 = document.getElementById(X); + if (o2) + return this.iframe = o2, this.onInit(), r(); + window.addEventListener("message", s2); + const h5 = document.createElement("iframe"); + h5.id = X, h5.src = `${this.verifyUrl}/${this.projectId}`, h5.style.display = "none", document.body.append(h5), this.iframe = h5, i2 = r; + }), new Promise((r, o2) => setTimeout(() => { + window.removeEventListener("message", s2), o2("verify iframe load timeout"); + }, l4.toMiliseconds(l4.FIVE_SECONDS)))]); + }, this.onInit = () => { + this.initialized = true, this.processQueue(); + }, this.removeIframe = () => { + this.iframe && (this.iframe.remove(), this.iframe = void 0, this.initialized = false); + }, this.getVerifyUrl = (i2) => { + let s2 = i2 || B2; + return Ze.includes(s2) || (this.logger.info(`verify url: ${s2}, not included in trusted list, assigning default: ${B2}`), s2 = B2), s2; + }, this.logger = g3.generateChildLogger(t, this.name), this.verifyUrl = B2, this.abortController = new AbortController(), this.isDevEnv = a3.isNode() && import_process.default.env.IS_VITEST; + } + get context() { + return g3.getLoggerContext(this.logger); + } + startAbortTimer(e2) { + return this.abortController = new AbortController(), setTimeout(() => this.abortController.abort(), l4.toMiliseconds(e2)); + } + }; + var bt = class extends x3.IEchoClient { + constructor(e2, t) { + super(e2, t), this.projectId = e2, this.logger = t, this.context = et, this.registerDeviceToken = async (i2) => { + const { clientId: s2, token: r, notificationType: o2, enableEncrypted: h5 = false } = i2, c4 = `${tt}/${this.projectId}/clients`; + await Ut.default(c4, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: s2, type: o2, token: r, always_raw: h5 }) }); + }, this.logger = g3.generateChildLogger(t, this.context); + } + }; + var Rs = Object.defineProperty; + var ft = Object.getOwnPropertySymbols; + var _s = Object.prototype.hasOwnProperty; + var Cs = Object.prototype.propertyIsEnumerable; + var wt = (n3, e2, t) => e2 in n3 ? Rs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var vt = (n3, e2) => { + for (var t in e2 || (e2 = {})) + _s.call(e2, t) && wt(n3, t, e2[t]); + if (ft) + for (var t of ft(e2)) + Cs.call(e2, t) && wt(n3, t, e2[t]); + return n3; + }; + var W = class _W extends x3.ICore { + constructor(e2) { + var t; + super(e2), this.protocol = te, this.version = Re, this.name = H, this.events = new z3.EventEmitter(), this.initialized = false, this.on = (o2, h5) => this.events.on(o2, h5), this.once = (o2, h5) => this.events.once(o2, h5), this.off = (o2, h5) => this.events.off(o2, h5), this.removeListener = (o2, h5) => this.events.removeListener(o2, h5), this.projectId = e2?.projectId, this.relayUrl = e2?.relayUrl || se, this.customStoragePrefix = e2 != null && e2.customStoragePrefix ? `:${e2.customStoragePrefix}` : ""; + const i2 = g3.getDefaultLoggerOptions({ level: typeof e2?.logger == "string" && e2.logger ? e2.logger : _e.logger }), { logger: s2, chunkLoggerController: r } = g3.generatePlatformLogger({ opts: i2, maxSizeInBytes: e2?.maxLogBlobSizeInBytes, loggerOverride: e2?.logger }); + this.logChunkController = r, (t = this.logChunkController) != null && t.downloadLogsBlobInBrowser && (window.downloadLogsBlobInBrowser = async () => { + var o2, h5; + (o2 = this.logChunkController) != null && o2.downloadLogsBlobInBrowser && ((h5 = this.logChunkController) == null || h5.downloadLogsBlobInBrowser({ clientId: await this.crypto.getClientId() })); + }), this.logger = g3.generateChildLogger(s2, this.name), this.heartbeat = new $.HeartBeat(), this.crypto = new st(this, this.logger, e2?.keychain), this.history = new yt(this, this.logger), this.expirer = new Et(this, this.logger), this.storage = e2 != null && e2.storage ? e2.storage : new xt.default(vt(vt({}, Ce), e2?.storageOptions)), this.relayer = new lt({ core: this, logger: this.logger, relayUrl: this.relayUrl, projectId: this.projectId }), this.pairing = new Dt(this, this.logger), this.verify = new mt(this.projectId || "", this.logger), this.echoClient = new bt(this.projectId || "", this.logger); + } + static async init(e2) { + const t = new _W(e2); + await t.initialize(); + const i2 = await t.crypto.getClientId(); + return await t.storage.setItem(Ke, i2), t; + } + get context() { + return g3.getLoggerContext(this.logger); + } + async start() { + this.initialized || await this.initialize(); + } + async getLogsBlob() { + var e2; + return (e2 = this.logChunkController) == null ? void 0 : e2.logsToBlob({ clientId: await this.crypto.getClientId() }); + } + async initialize() { + this.logger.trace("Initialized"); + try { + await this.crypto.init(), await this.history.init(), await this.expirer.init(), await this.relayer.init(), await this.heartbeat.init(), await this.pairing.init(), this.initialized = true, this.logger.info("Core Initialization Success"); + } catch (e2) { + throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`, e2), this.logger.error(e2.message), e2; + } + } + }; + var Ts = W; + exports2.CORE_CONTEXT = H, exports2.CORE_DEFAULT = _e, exports2.CORE_PROTOCOL = te, exports2.CORE_STORAGE_OPTIONS = Ce, exports2.CORE_STORAGE_PREFIX = L2, exports2.CORE_VERSION = Re, exports2.CRYPTO_CLIENT_SEED = ie, exports2.CRYPTO_CONTEXT = Te, exports2.CRYPTO_JWT_TTL = Se, exports2.Core = Ts, exports2.Crypto = st, exports2.ECHO_CONTEXT = et, exports2.ECHO_URL = tt, exports2.EXPIRER_CONTEXT = We, exports2.EXPIRER_DEFAULT_TTL = cs, exports2.EXPIRER_EVENTS = _4, exports2.EXPIRER_STORAGE_VERSION = Qe, exports2.EchoClient = bt, exports2.Expirer = Et, exports2.HISTORY_CONTEXT = Xe, exports2.HISTORY_EVENTS = R2, exports2.HISTORY_STORAGE_VERSION = Je, exports2.JsonRpcHistory = yt, exports2.KEYCHAIN_CONTEXT = Oe, exports2.KEYCHAIN_STORAGE_VERSION = Pe, exports2.KeyChain = it, exports2.MESSAGES_CONTEXT = Ae, exports2.MESSAGES_STORAGE_VERSION = xe, exports2.MessageTracker = rt, exports2.PAIRING_CONTEXT = Ge, exports2.PAIRING_DEFAULT_TTL = hs, exports2.PAIRING_EVENTS = K2, exports2.PAIRING_RPC_OPTS = M, exports2.PAIRING_STORAGE_VERSION = He, exports2.PENDING_SUB_RESOLUTION_TIMEOUT = je, exports2.PUBLISHER_CONTEXT = Le, exports2.PUBLISHER_DEFAULT_TTL = Ne, exports2.Pairing = Dt, exports2.RELAYER_CONTEXT = Fe, exports2.RELAYER_DEFAULT_LOGGER = ze, exports2.RELAYER_DEFAULT_PROTOCOL = Ue, exports2.RELAYER_DEFAULT_RELAY_URL = se, exports2.RELAYER_EVENTS = I2, exports2.RELAYER_FAILOVER_RELAY_URL = re, exports2.RELAYER_PROVIDER_EVENTS = w4, exports2.RELAYER_RECONNECT_TIMEOUT = Be, exports2.RELAYER_SDK_VERSION = $e, exports2.RELAYER_STORAGE_OPTIONS = os, exports2.RELAYER_SUBSCRIBER_SUFFIX = Me, exports2.RELAYER_TRANSPORT_CUTOFF = ke, exports2.Relayer = lt, exports2.STORE_STORAGE_VERSION = Ve, exports2.SUBSCRIBER_CONTEXT = qe, exports2.SUBSCRIBER_DEFAULT_TTL = as, exports2.SUBSCRIBER_EVENTS = S4, exports2.SUBSCRIBER_STORAGE_VERSION = Ye, exports2.Store = pt, exports2.Subscriber = at, exports2.TRUSTED_VERIFY_URLS = Ze, exports2.VERIFY_CONTEXT = X, exports2.VERIFY_FALLBACK_SERVER = J, exports2.VERIFY_SERVER = B2, exports2.Verify = mt, exports2.WALLETCONNECT_CLIENT_ID = Ke, exports2.default = W; + } +}); + +// node_modules/@walletconnect/sign-client/dist/index.cjs.js +var require_index_cjs4 = __commonJS({ + "node_modules/@walletconnect/sign-client/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var N10 = require_index_cjs3(); + var k4 = (init_index_es2(), __toCommonJS(index_es_exports2)); + var oe = require_index_cjs(); + var s2 = require_index_cjs2(); + var ae = require_events(); + var w4 = require_cjs(); + var u3 = (init_esm5(), __toCommonJS(esm_exports4)); + function fe(y4) { + return y4 && typeof y4 == "object" && "default" in y4 ? y4 : { default: y4 }; + } + var qe = fe(ae); + var ee = "wc"; + var te = 2; + var ie = "client"; + var F = `${ee}@${te}:${ie}:`; + var Y = { name: ie, logger: "error", controller: false, relayUrl: "wss://relay.walletconnect.com" }; + var Pe = { session_proposal: "session_proposal", session_update: "session_update", session_extend: "session_extend", session_ping: "session_ping", session_delete: "session_delete", session_expire: "session_expire", session_request: "session_request", session_request_sent: "session_request_sent", session_event: "session_event", proposal_expire: "proposal_expire", session_authenticate: "session_authenticate", session_request_expire: "session_request_expire" }; + var Te = { database: ":memory:" }; + var se = "WALLETCONNECT_DEEPLINK_CHOICE"; + var ve = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; + var Oe = "history"; + var Ae = "0.3"; + var ce = "proposal"; + var Ve = w4.THIRTY_DAYS; + var le = "Proposal expired"; + var he = "session"; + var V = w4.SEVEN_DAYS; + var pe = "engine"; + var q2 = { wc_sessionPropose: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1100 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1101 } }, wc_sessionSettle: { req: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1102 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1103 } }, wc_sessionUpdate: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1104 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1105 } }, wc_sessionExtend: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1106 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1107 } }, wc_sessionRequest: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1108 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1109 } }, wc_sessionEvent: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1110 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1111 } }, wc_sessionDelete: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1112 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1113 } }, wc_sessionPing: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1114 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1115 } }, wc_sessionAuthenticate: { req: { ttl: w4.ONE_HOUR, prompt: true, tag: 1116 }, res: { ttl: w4.ONE_HOUR, prompt: false, tag: 1117 } } }; + var H = { min: w4.FIVE_MINUTES, max: w4.SEVEN_DAYS }; + var A2 = { idle: "IDLE", active: "ACTIVE" }; + var de = "request"; + var ue = ["wc_sessionPropose", "wc_sessionRequest", "wc_authRequest"]; + var ge = "wc"; + var De = 1.5; + var Ee = "auth"; + var we = "authKeys"; + var ye = "pairingTopics"; + var me = "requests"; + var L2 = `${ge}@${1.5}:${Ee}:`; + var U2 = `${L2}:PUB_KEY`; + var Ce = Object.defineProperty; + var xe = Object.defineProperties; + var be = Object.getOwnPropertyDescriptors; + var Se = Object.getOwnPropertySymbols; + var Me = Object.prototype.hasOwnProperty; + var Le = Object.prototype.propertyIsEnumerable; + var Ie = (y4, o2, t) => o2 in y4 ? Ce(y4, o2, { enumerable: true, configurable: true, writable: true, value: t }) : y4[o2] = t; + var S4 = (y4, o2) => { + for (var t in o2 || (o2 = {})) + Me.call(o2, t) && Ie(y4, t, o2[t]); + if (Se) + for (var t of Se(o2)) + Le.call(o2, t) && Ie(y4, t, o2[t]); + return y4; + }; + var C3 = (y4, o2) => xe(y4, be(o2)); + var Ue = class extends oe.IEngine { + constructor(o2) { + super(o2), this.name = pe, this.events = new qe.default(), this.initialized = false, this.requestQueue = { state: A2.idle, queue: [] }, this.sessionRequestQueue = { state: A2.idle, queue: [] }, this.requestQueueDelay = w4.ONE_SECOND, this.expectedPairingMethodMap = /* @__PURE__ */ new Map(), this.recentlyDeletedMap = /* @__PURE__ */ new Map(), this.recentlyDeletedLimit = 200, this.init = async () => { + this.initialized || (await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.registerPairingEvents(), this.client.core.pairing.register({ methods: Object.keys(q2) }), this.initialized = true, setTimeout(() => { + this.sessionRequestQueue.queue = this.getPendingSessionRequests(), this.processSessionRequestQueue(); + }, w4.toMiliseconds(this.requestQueueDelay))); + }, this.connect = async (t) => { + await this.isInitialized(); + const e2 = C3(S4({}, t), { requiredNamespaces: t.requiredNamespaces || {}, optionalNamespaces: t.optionalNamespaces || {} }); + await this.isValidConnect(e2); + const { pairingTopic: i2, requiredNamespaces: r, optionalNamespaces: n3, sessionProperties: a3, relays: c4 } = e2; + let l4 = i2, d3, p3 = false; + try { + l4 && (p3 = this.client.core.pairing.pairings.get(l4).active); + } catch (f4) { + throw this.client.logger.error(`connect() -> pairing.get(${l4}) failed`), f4; + } + if (!l4 || !p3) { + const { topic: f4, uri: T2 } = await this.client.core.pairing.create(); + l4 = f4, d3 = T2; + } + if (!l4) { + const { message: f4 } = s2.getInternalError("NO_MATCHING_KEY", `connect() pairing topic: ${l4}`); + throw new Error(f4); + } + const g3 = await this.client.core.crypto.generateKeyPair(), h5 = q2.wc_sessionPropose.req.ttl || w4.FIVE_MINUTES, m3 = s2.calcExpiry(h5), E4 = S4({ requiredNamespaces: r, optionalNamespaces: n3, relays: c4 ?? [{ protocol: N10.RELAYER_DEFAULT_PROTOCOL }], proposer: { publicKey: g3, metadata: this.client.metadata }, expiryTimestamp: m3 }, a3 && { sessionProperties: a3 }), { reject: R2, resolve: O3, done: I2 } = s2.createDelayedPromise(h5, le); + this.events.once(s2.engineEvent("session_connect"), async ({ error: f4, session: T2 }) => { + if (f4) + R2(f4); + else if (T2) { + T2.self.publicKey = g3; + const x3 = C3(S4({}, T2), { requiredNamespaces: E4.requiredNamespaces, optionalNamespaces: E4.optionalNamespaces }); + await this.client.session.set(T2.topic, x3), await this.setExpiry(T2.topic, T2.expiry), l4 && await this.client.core.pairing.updateMetadata({ topic: l4, metadata: T2.peer.metadata }), O3(x3); + } + }); + const P2 = await this.sendRequest({ topic: l4, method: "wc_sessionPropose", params: E4, throwOnFailedPublish: true }); + return await this.setProposal(P2, S4({ id: P2 }, E4)), { uri: d3, approval: I2 }; + }, this.pair = async (t) => { + await this.isInitialized(); + try { + return await this.client.core.pairing.pair(t); + } catch (e2) { + throw this.client.logger.error("pair() failed"), e2; + } + }, this.approve = async (t) => { + await this.isInitialized(); + try { + await this.isValidApprove(t); + } catch (I2) { + throw this.client.logger.error("approve() -> isValidApprove() failed"), I2; + } + const { id: e2, relayProtocol: i2, namespaces: r, sessionProperties: n3, sessionConfig: a3 } = t; + let c4; + try { + c4 = this.client.proposal.get(e2); + } catch (I2) { + throw this.client.logger.error(`approve() -> proposal.get(${e2}) failed`), I2; + } + let { pairingTopic: l4, proposer: d3, requiredNamespaces: p3, optionalNamespaces: g3 } = c4; + l4 = l4 || ""; + const h5 = await this.client.core.crypto.generateKeyPair(), m3 = d3.publicKey, E4 = await this.client.core.crypto.generateSharedKey(h5, m3), R2 = S4(S4({ relay: { protocol: i2 ?? "irn" }, namespaces: r, pairingTopic: l4, controller: { publicKey: h5, metadata: this.client.metadata }, expiry: s2.calcExpiry(V) }, n3 && { sessionProperties: n3 }), a3 && { sessionConfig: a3 }); + await this.client.core.relayer.subscribe(E4); + const O3 = C3(S4({}, R2), { topic: E4, requiredNamespaces: p3, optionalNamespaces: g3, pairingTopic: l4, acknowledged: false, self: R2.controller, peer: { publicKey: d3.publicKey, metadata: d3.metadata }, controller: h5 }); + await this.client.session.set(E4, O3); + try { + await this.sendResult({ id: e2, topic: l4, result: { relay: { protocol: i2 ?? "irn" }, responderPublicKey: h5 }, throwOnFailedPublish: true }), await this.sendRequest({ topic: E4, method: "wc_sessionSettle", params: R2, throwOnFailedPublish: true }); + } catch (I2) { + throw this.client.logger.error(I2), this.client.session.delete(E4, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.relayer.unsubscribe(E4), I2; + } + return await this.client.core.pairing.updateMetadata({ topic: l4, metadata: d3.metadata }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.pairing.activate({ topic: l4 }), await this.setExpiry(E4, s2.calcExpiry(V)), { topic: E4, acknowledged: () => new Promise((I2) => setTimeout(() => I2(this.client.session.get(E4)), 500)) }; + }, this.reject = async (t) => { + await this.isInitialized(); + try { + await this.isValidReject(t); + } catch (n3) { + throw this.client.logger.error("reject() -> isValidReject() failed"), n3; + } + const { id: e2, reason: i2 } = t; + let r; + try { + r = this.client.proposal.get(e2).pairingTopic; + } catch (n3) { + throw this.client.logger.error(`reject() -> proposal.get(${e2}) failed`), n3; + } + r && (await this.sendError({ id: e2, topic: r, error: i2 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED"))); + }, this.update = async (t) => { + await this.isInitialized(); + try { + await this.isValidUpdate(t); + } catch (p3) { + throw this.client.logger.error("update() -> isValidUpdate() failed"), p3; + } + const { topic: e2, namespaces: i2 } = t, { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), d3 = this.client.session.get(e2).namespaces; + return this.events.once(s2.engineEvent("session_update", c4), ({ error: p3 }) => { + p3 ? a3(p3) : n3(); + }), await this.client.session.update(e2, { namespaces: i2 }), this.sendRequest({ topic: e2, method: "wc_sessionUpdate", params: { namespaces: i2 }, throwOnFailedPublish: true, clientRpcId: c4, relayRpcId: l4 }).catch((p3) => { + this.client.logger.error(p3), this.client.session.update(e2, { namespaces: d3 }), a3(p3); + }), { acknowledged: r }; + }, this.extend = async (t) => { + await this.isInitialized(); + try { + await this.isValidExtend(t); + } catch (c4) { + throw this.client.logger.error("extend() -> isValidExtend() failed"), c4; + } + const { topic: e2 } = t, i2 = u3.payloadId(), { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(); + return this.events.once(s2.engineEvent("session_extend", i2), ({ error: c4 }) => { + c4 ? a3(c4) : n3(); + }), await this.setExpiry(e2, s2.calcExpiry(V)), this.sendRequest({ topic: e2, method: "wc_sessionExtend", params: {}, clientRpcId: i2, throwOnFailedPublish: true }).catch((c4) => { + a3(c4); + }), { acknowledged: r }; + }, this.request = async (t) => { + await this.isInitialized(); + try { + await this.isValidRequest(t); + } catch (h5) { + throw this.client.logger.error("request() -> isValidRequest() failed"), h5; + } + const { chainId: e2, request: i2, topic: r, expiry: n3 = q2.wc_sessionRequest.req.ttl } = t, a3 = this.client.session.get(r), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), { done: d3, resolve: p3, reject: g3 } = s2.createDelayedPromise(n3, "Request expired. Please try again."); + return this.events.once(s2.engineEvent("session_request", c4), ({ error: h5, result: m3 }) => { + h5 ? g3(h5) : p3(m3); + }), await Promise.all([new Promise(async (h5) => { + await this.sendRequest({ clientRpcId: c4, relayRpcId: l4, topic: r, method: "wc_sessionRequest", params: { request: C3(S4({}, i2), { expiryTimestamp: s2.calcExpiry(n3) }), chainId: e2 }, expiry: n3, throwOnFailedPublish: true }).catch((m3) => g3(m3)), this.client.events.emit("session_request_sent", { topic: r, request: i2, chainId: e2, id: c4 }), h5(); + }), new Promise(async (h5) => { + var m3; + if (!((m3 = a3.sessionConfig) != null && m3.disableDeepLink)) { + const E4 = await s2.getDeepLink(this.client.core.storage, se); + s2.handleDeeplinkRedirect({ id: c4, topic: r, wcDeepLink: E4 }); + } + h5(); + }), d3()]).then((h5) => h5[2]); + }, this.respond = async (t) => { + await this.isInitialized(), await this.isValidRespond(t); + const { topic: e2, response: i2 } = t, { id: r } = i2; + u3.isJsonRpcResult(i2) ? await this.sendResult({ id: r, topic: e2, result: i2.result, throwOnFailedPublish: true }) : u3.isJsonRpcError(i2) && await this.sendError({ id: r, topic: e2, error: i2.error }), this.cleanupAfterResponse(t); + }, this.ping = async (t) => { + await this.isInitialized(); + try { + await this.isValidPing(t); + } catch (i2) { + throw this.client.logger.error("ping() -> isValidPing() failed"), i2; + } + const { topic: e2 } = t; + if (this.client.session.keys.includes(e2)) { + const i2 = u3.payloadId(), r = u3.getBigIntRpcId().toString(), { done: n3, resolve: a3, reject: c4 } = s2.createDelayedPromise(); + this.events.once(s2.engineEvent("session_ping", i2), ({ error: l4 }) => { + l4 ? c4(l4) : a3(); + }), await Promise.all([this.sendRequest({ topic: e2, method: "wc_sessionPing", params: {}, throwOnFailedPublish: true, clientRpcId: i2, relayRpcId: r }), n3()]); + } else + this.client.core.pairing.pairings.keys.includes(e2) && await this.client.core.pairing.ping({ topic: e2 }); + }, this.emit = async (t) => { + await this.isInitialized(), await this.isValidEmit(t); + const { topic: e2, event: i2, chainId: r } = t, n3 = u3.getBigIntRpcId().toString(); + await this.sendRequest({ topic: e2, method: "wc_sessionEvent", params: { event: i2, chainId: r }, throwOnFailedPublish: true, relayRpcId: n3 }); + }, this.disconnect = async (t) => { + await this.isInitialized(), await this.isValidDisconnect(t); + const { topic: e2 } = t; + if (this.client.session.keys.includes(e2)) + await this.sendRequest({ topic: e2, method: "wc_sessionDelete", params: s2.getSdkError("USER_DISCONNECTED"), throwOnFailedPublish: true }), await this.deleteSession({ topic: e2, emitEvent: false }); + else if (this.client.core.pairing.pairings.keys.includes(e2)) + await this.client.core.pairing.disconnect({ topic: e2 }); + else { + const { message: i2 } = s2.getInternalError("MISMATCHED_TOPIC", `Session or pairing topic not found: ${e2}`); + throw new Error(i2); + } + }, this.find = (t) => (this.isInitialized(), this.client.session.getAll().filter((e2) => s2.isSessionCompatible(e2, t))), this.getPendingSessionRequests = () => this.client.pendingRequest.getAll(), this.authenticate = async (t) => { + this.isInitialized(), this.isValidAuthenticate(t); + const { chains: e2, statement: i2 = "", uri: r, domain: n3, nonce: a3, type: c4, exp: l4, nbf: d3, methods: p3 = [] } = t, g3 = [...t.resources || []], { topic: h5, uri: m3 } = await this.client.core.pairing.create({ methods: ["wc_sessionAuthenticate"] }); + this.client.logger.info({ message: "Generated new pairing", pairing: { topic: h5, uri: m3 } }); + const E4 = await this.client.core.crypto.generateKeyPair(), R2 = s2.hashKey(E4); + if (await Promise.all([this.client.auth.authKeys.set(U2, { responseTopic: R2, publicKey: E4 }), this.client.auth.pairingTopics.set(R2, { topic: R2, pairingTopic: h5 })]), await this.client.core.relayer.subscribe(R2), this.client.logger.info(`sending request to new pairing topic: ${h5}`), p3.length > 0) { + const { namespace: v2 } = s2.parseChainId(e2[0]); + let _4 = s2.createEncodedRecap(v2, "request", p3); + s2.getRecapFromResources(g3) && (_4 = s2.mergeEncodedRecaps(_4, g3.pop())), g3.push(_4); + } + const O3 = s2.calcExpiry(q2.wc_sessionPropose.req.ttl), I2 = { authPayload: { type: c4 ?? "caip122", chains: e2, statement: i2, aud: r, domain: n3, version: "1", nonce: a3, iat: (/* @__PURE__ */ new Date()).toISOString(), exp: l4, nbf: d3, resources: g3 }, requester: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, P2 = { eip155: { chains: e2, methods: [.../* @__PURE__ */ new Set(["personal_sign", ...p3])], events: ["chainChanged", "accountsChanged"] } }, f4 = { requiredNamespaces: {}, optionalNamespaces: P2, relays: [{ protocol: "irn" }], proposer: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, { done: T2, resolve: x3, reject: Q } = s2.createDelayedPromise(q2.wc_sessionAuthenticate.req.ttl, "Request expired"), $ = async ({ error: v2, session: _4 }) => { + if (this.events.off(s2.engineEvent("session_request", D2), X), v2) + Q(v2); + else if (_4) { + _4.self.publicKey = E4, await this.client.session.set(_4.topic, _4), await this.setExpiry(_4.topic, _4.expiry), h5 && await this.client.core.pairing.updateMetadata({ topic: h5, metadata: _4.peer.metadata }); + const b4 = this.client.session.get(_4.topic); + x3({ session: b4 }); + } + }, X = async (v2) => { + if (v2.error) { + const M = s2.getSdkError("WC_METHOD_UNSUPPORTED", "wc_sessionAuthenticate"); + return v2.error.code === M.code ? void 0 : (this.events.off(s2.engineEvent("session_connect"), $), Q(v2.error.message)); + } + this.events.off(s2.engineEvent("session_connect"), $); + const { cacaos: _4, responder: b4 } = v2.result, z3 = [], re = []; + for (const M of _4) { + await s2.validateSignedCacao({ cacao: M, projectId: this.client.core.projectId }) || (this.client.logger.error(M, "Signature verification failed"), Q(s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"))); + const { p: B2 } = M, W = s2.getRecapFromResources(B2.resources), ne = [s2.getNamespacedDidChainId(B2.iss)], Re = s2.getDidAddress(B2.iss); + if (W) { + const Z = s2.getMethodsFromRecap(W), Ne = s2.getChainsFromRecap(W); + z3.push(...Z), ne.push(...Ne); + } + for (const Z of ne) + re.push(`${Z}:${Re}`); + } + const G = await this.client.core.crypto.generateSharedKey(E4, b4.publicKey); + let K2; + z3.length > 0 && (K2 = { topic: G, acknowledged: true, self: { publicKey: E4, metadata: this.client.metadata }, peer: b4, controller: b4.publicKey, expiry: s2.calcExpiry(V), requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: h5, namespaces: s2.buildNamespacesFromAuth([...new Set(z3)], [...new Set(re)]) }, await this.client.core.relayer.subscribe(G), await this.client.session.set(G, K2), K2 = this.client.session.get(G)), x3({ auths: _4, session: K2 }); + }, D2 = u3.payloadId(), J = u3.payloadId(); + this.events.once(s2.engineEvent("session_connect"), $), this.events.once(s2.engineEvent("session_request", D2), X); + try { + await Promise.all([this.sendRequest({ topic: h5, method: "wc_sessionAuthenticate", params: I2, expiry: t.expiry, throwOnFailedPublish: true, clientRpcId: D2 }), this.sendRequest({ topic: h5, method: "wc_sessionPropose", params: f4, expiry: q2.wc_sessionPropose.req.ttl, throwOnFailedPublish: true, clientRpcId: J })]); + } catch (v2) { + throw this.events.off(s2.engineEvent("session_connect"), $), this.events.off(s2.engineEvent("session_request", D2), X), v2; + } + return await this.setProposal(J, S4({ id: J }, f4)), await this.client.auth.requests.set(D2, { authPayload: I2.authPayload, requester: I2.requester, expiryTimestamp: O3, id: D2, pairingTopic: h5, verifyContext: {} }), { uri: m3, response: T2 }; + }, this.approveSessionAuthenticate = async (t) => { + this.isInitialized(); + const { id: e2, auths: i2 } = t, r = this.getPendingAuthRequest(e2); + if (!r) + throw new Error(`Could not find pending auth request with id ${e2}`); + const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }, d3 = [], p3 = []; + for (const m3 of i2) { + if (!await s2.validateSignedCacao({ cacao: m3, projectId: this.client.core.projectId })) { + const P2 = s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"); + throw await this.sendError({ id: e2, topic: c4, error: P2, encodeOpts: l4 }), new Error(P2.message); + } + const { p: E4 } = m3, R2 = s2.getRecapFromResources(E4.resources), O3 = [s2.getNamespacedDidChainId(E4.iss)], I2 = s2.getDidAddress(E4.iss); + if (R2) { + const P2 = s2.getMethodsFromRecap(R2), f4 = s2.getChainsFromRecap(R2); + d3.push(...P2), O3.push(...f4); + } + for (const P2 of O3) + p3.push(`${P2}:${I2}`); + } + const g3 = await this.client.core.crypto.generateSharedKey(a3, n3); + let h5; + return d3?.length > 0 && (h5 = { topic: g3, acknowledged: true, self: { publicKey: a3, metadata: this.client.metadata }, peer: { publicKey: n3, metadata: r.requester.metadata }, controller: n3, expiry: s2.calcExpiry(V), authentication: i2, requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: "", namespaces: s2.buildNamespacesFromAuth([...new Set(d3)], [...new Set(p3)]) }, await this.client.core.relayer.subscribe(g3), await this.client.session.set(g3, h5)), await this.sendResult({ topic: c4, id: e2, result: { cacaos: i2, responder: { publicKey: a3, metadata: this.client.metadata } }, encodeOpts: l4, throwOnFailedPublish: true }), await this.client.auth.requests.delete(e2, { message: "fullfilled", code: 0 }), await this.client.core.pairing.activate({ topic: r.pairingTopic }), { session: h5 }; + }, this.rejectSessionAuthenticate = async (t) => { + await this.isInitialized(); + const { id: e2, reason: i2 } = t, r = this.getPendingAuthRequest(e2); + if (!r) + throw new Error(`Could not find pending auth request with id ${e2}`); + const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }; + await this.sendError({ id: e2, topic: c4, error: i2, encodeOpts: l4 }), await this.client.auth.requests.delete(e2, { message: "rejected", code: 0 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")); + }, this.formatAuthMessage = (t) => { + this.isInitialized(); + const { request: e2, iss: i2 } = t; + return s2.formatMessage(e2, i2); + }, this.cleanupDuplicatePairings = async (t) => { + if (t.pairingTopic) + try { + const e2 = this.client.core.pairing.pairings.get(t.pairingTopic), i2 = this.client.core.pairing.pairings.getAll().filter((r) => { + var n3, a3; + return ((n3 = r.peerMetadata) == null ? void 0 : n3.url) && ((a3 = r.peerMetadata) == null ? void 0 : a3.url) === t.peer.metadata.url && r.topic && r.topic !== e2.topic; + }); + if (i2.length === 0) + return; + this.client.logger.info(`Cleaning up ${i2.length} duplicate pairing(s)`), await Promise.all(i2.map((r) => this.client.core.pairing.disconnect({ topic: r.topic }))), this.client.logger.info("Duplicate pairings clean up finished"); + } catch (e2) { + this.client.logger.error(e2); + } + }, this.deleteSession = async (t) => { + const { topic: e2, expirerHasDeleted: i2 = false, emitEvent: r = true, id: n3 = 0 } = t, { self: a3 } = this.client.session.get(e2); + await this.client.core.relayer.unsubscribe(e2), await this.client.session.delete(e2, s2.getSdkError("USER_DISCONNECTED")), this.addToRecentlyDeleted(e2, "session"), this.client.core.crypto.keychain.has(a3.publicKey) && await this.client.core.crypto.deleteKeyPair(a3.publicKey), this.client.core.crypto.keychain.has(e2) && await this.client.core.crypto.deleteSymKey(e2), i2 || this.client.core.expirer.del(e2), this.client.core.storage.removeItem(se).catch((c4) => this.client.logger.warn(c4)), this.getPendingSessionRequests().forEach((c4) => { + c4.topic === e2 && this.deletePendingSessionRequest(c4.id, s2.getSdkError("USER_DISCONNECTED")); + }), r && this.client.events.emit("session_delete", { id: n3, topic: e2 }); + }, this.deleteProposal = async (t, e2) => { + await Promise.all([this.client.proposal.delete(t, s2.getSdkError("USER_DISCONNECTED")), e2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "proposal"); + }, this.deletePendingSessionRequest = async (t, e2, i2 = false) => { + await Promise.all([this.client.pendingRequest.delete(t, e2), i2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "request"), this.sessionRequestQueue.queue = this.sessionRequestQueue.queue.filter((r) => r.id !== t), i2 && (this.sessionRequestQueue.state = A2.idle, this.client.events.emit("session_request_expire", { id: t })); + }, this.setExpiry = async (t, e2) => { + this.client.session.keys.includes(t) && await this.client.session.update(t, { expiry: e2 }), this.client.core.expirer.set(t, e2); + }, this.setProposal = async (t, e2) => { + await this.client.proposal.set(t, e2), this.client.core.expirer.set(t, s2.calcExpiry(q2.wc_sessionPropose.req.ttl)); + }, this.setPendingSessionRequest = async (t) => { + const { id: e2, topic: i2, params: r, verifyContext: n3 } = t, a3 = r.request.expiryTimestamp || s2.calcExpiry(q2.wc_sessionRequest.req.ttl); + await this.client.pendingRequest.set(e2, { id: e2, topic: i2, params: r, verifyContext: n3 }), a3 && this.client.core.expirer.set(e2, a3); + }, this.sendRequest = async (t) => { + const { topic: e2, method: i2, params: r, expiry: n3, relayRpcId: a3, clientRpcId: c4, throwOnFailedPublish: l4 } = t, d3 = u3.formatJsonRpcRequest(i2, r, c4); + if (s2.isBrowser() && ue.includes(i2)) { + const h5 = s2.hashMessage(JSON.stringify(d3)); + this.client.core.verify.register({ attestationId: h5 }); + } + let p3; + try { + p3 = await this.client.core.crypto.encode(e2, d3); + } catch (h5) { + throw await this.cleanup(), this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${e2} failed`), h5; + } + const g3 = q2[i2].req; + return n3 && (g3.ttl = n3), a3 && (g3.id = a3), this.client.core.history.set(e2, d3), l4 ? (g3.internal = C3(S4({}, g3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(e2, p3, g3)) : this.client.core.relayer.publish(e2, p3, g3).catch((h5) => this.client.logger.error(h5)), d3.id; + }, this.sendResult = async (t) => { + const { id: e2, topic: i2, result: r, throwOnFailedPublish: n3, encodeOpts: a3 } = t, c4 = u3.formatJsonRpcResult(e2, r); + let l4; + try { + l4 = await this.client.core.crypto.encode(i2, c4, a3); + } catch (g3) { + throw await this.cleanup(), this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i2} failed`), g3; + } + let d3; + try { + d3 = await this.client.core.history.get(i2, e2); + } catch (g3) { + throw this.client.logger.error(`sendResult() -> history.get(${i2}, ${e2}) failed`), g3; + } + const p3 = q2[d3.request.method].res; + n3 ? (p3.internal = C3(S4({}, p3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(i2, l4, p3)) : this.client.core.relayer.publish(i2, l4, p3).catch((g3) => this.client.logger.error(g3)), await this.client.core.history.resolve(c4); + }, this.sendError = async (t) => { + const { id: e2, topic: i2, error: r, encodeOpts: n3 } = t, a3 = u3.formatJsonRpcError(e2, r); + let c4; + try { + c4 = await this.client.core.crypto.encode(i2, a3, n3); + } catch (p3) { + throw await this.cleanup(), this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i2} failed`), p3; + } + let l4; + try { + l4 = await this.client.core.history.get(i2, e2); + } catch (p3) { + throw this.client.logger.error(`sendError() -> history.get(${i2}, ${e2}) failed`), p3; + } + const d3 = q2[l4.request.method].res; + this.client.core.relayer.publish(i2, c4, d3), await this.client.core.history.resolve(a3); + }, this.cleanup = async () => { + const t = [], e2 = []; + this.client.session.getAll().forEach((i2) => { + let r = false; + s2.isExpired(i2.expiry) && (r = true), this.client.core.crypto.keychain.has(i2.topic) || (r = true), r && t.push(i2.topic); + }), this.client.proposal.getAll().forEach((i2) => { + s2.isExpired(i2.expiryTimestamp) && e2.push(i2.id); + }), await Promise.all([...t.map((i2) => this.deleteSession({ topic: i2 })), ...e2.map((i2) => this.deleteProposal(i2))]); + }, this.onRelayEventRequest = async (t) => { + this.requestQueue.queue.push(t), await this.processRequestsQueue(); + }, this.processRequestsQueue = async () => { + if (this.requestQueue.state === A2.active) { + this.client.logger.info("Request queue already active, skipping..."); + return; + } + for (this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`); this.requestQueue.queue.length > 0; ) { + this.requestQueue.state = A2.active; + const t = this.requestQueue.queue.shift(); + if (t) + try { + this.processRequest(t), await new Promise((e2) => setTimeout(e2, 300)); + } catch (e2) { + this.client.logger.warn(e2); + } + } + this.requestQueue.state = A2.idle; + }, this.processRequest = (t) => { + const { topic: e2, payload: i2 } = t, r = i2.method; + if (!this.shouldIgnorePairingRequest({ topic: e2, requestMethod: r })) + switch (r) { + case "wc_sessionPropose": + return this.onSessionProposeRequest(e2, i2); + case "wc_sessionSettle": + return this.onSessionSettleRequest(e2, i2); + case "wc_sessionUpdate": + return this.onSessionUpdateRequest(e2, i2); + case "wc_sessionExtend": + return this.onSessionExtendRequest(e2, i2); + case "wc_sessionPing": + return this.onSessionPingRequest(e2, i2); + case "wc_sessionDelete": + return this.onSessionDeleteRequest(e2, i2); + case "wc_sessionRequest": + return this.onSessionRequest(e2, i2); + case "wc_sessionEvent": + return this.onSessionEventRequest(e2, i2); + case "wc_sessionAuthenticate": + return this.onSessionAuthenticateRequest(e2, i2); + default: + return this.client.logger.info(`Unsupported request method ${r}`); + } + }, this.onRelayEventResponse = async (t) => { + const { topic: e2, payload: i2 } = t, r = (await this.client.core.history.get(e2, i2.id)).request.method; + switch (r) { + case "wc_sessionPropose": + return this.onSessionProposeResponse(e2, i2); + case "wc_sessionSettle": + return this.onSessionSettleResponse(e2, i2); + case "wc_sessionUpdate": + return this.onSessionUpdateResponse(e2, i2); + case "wc_sessionExtend": + return this.onSessionExtendResponse(e2, i2); + case "wc_sessionPing": + return this.onSessionPingResponse(e2, i2); + case "wc_sessionRequest": + return this.onSessionRequestResponse(e2, i2); + case "wc_sessionAuthenticate": + return this.onSessionAuthenticateResponse(e2, i2); + default: + return this.client.logger.info(`Unsupported response method ${r}`); + } + }, this.onRelayEventUnknownPayload = (t) => { + const { topic: e2 } = t, { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Decoded payload on topic ${e2} is not identifiable as a JSON-RPC request or a response.`); + throw new Error(i2); + }, this.shouldIgnorePairingRequest = (t) => { + const { topic: e2, requestMethod: i2 } = t, r = this.expectedPairingMethodMap.get(e2); + return !r || r.includes(i2) ? false : !!(r.includes("wc_sessionAuthenticate") && this.client.events.listenerCount("session_authenticate") > 0); + }, this.onSessionProposeRequest = async (t, e2) => { + const { params: i2, id: r } = e2; + try { + this.isValidConnect(S4({}, e2.params)); + const n3 = i2.expiryTimestamp || s2.calcExpiry(q2.wc_sessionPropose.req.ttl), a3 = S4({ id: r, pairingTopic: t, expiryTimestamp: n3 }, i2); + await this.setProposal(r, a3); + const c4 = s2.hashMessage(JSON.stringify(e2)), l4 = await this.getVerifyContext(c4, a3.proposer.metadata); + this.client.events.emit("session_proposal", { id: r, params: a3, verifyContext: l4 }); + } catch (n3) { + await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionProposeResponse = async (t, e2) => { + const { id: i2 } = e2; + if (u3.isJsonRpcResult(e2)) { + const { result: r } = e2; + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", result: r }); + const n3 = this.client.proposal.get(i2); + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", proposal: n3 }); + const a3 = n3.proposer.publicKey; + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", selfPublicKey: a3 }); + const c4 = r.responderPublicKey; + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", peerPublicKey: c4 }); + const l4 = await this.client.core.crypto.generateSharedKey(a3, c4); + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", sessionTopic: l4 }); + const d3 = await this.client.core.relayer.subscribe(l4); + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", subscriptionId: d3 }), await this.client.core.pairing.activate({ topic: t }); + } else if (u3.isJsonRpcError(e2)) { + await this.client.proposal.delete(i2, s2.getSdkError("USER_DISCONNECTED")); + const r = s2.engineEvent("session_connect"); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners, 954`); + this.events.emit(s2.engineEvent("session_connect"), { error: e2.error }); + } + }, this.onSessionSettleRequest = async (t, e2) => { + const { id: i2, params: r } = e2; + try { + this.isValidSessionSettleRequest(r); + const { relay: n3, controller: a3, expiry: c4, namespaces: l4, sessionProperties: d3, pairingTopic: p3, sessionConfig: g3 } = e2.params, h5 = S4(S4({ topic: t, relay: n3, expiry: c4, namespaces: l4, acknowledged: true, pairingTopic: p3, requiredNamespaces: {}, optionalNamespaces: {}, controller: a3.publicKey, self: { publicKey: "", metadata: this.client.metadata }, peer: { publicKey: a3.publicKey, metadata: a3.metadata } }, d3 && { sessionProperties: d3 }), g3 && { sessionConfig: g3 }); + await this.sendResult({ id: e2.id, topic: t, result: true, throwOnFailedPublish: true }); + const m3 = s2.engineEvent("session_connect"); + if (this.events.listenerCount(m3) === 0) + throw new Error(`emitting ${m3} without any listeners 997`); + this.events.emit(s2.engineEvent("session_connect"), { session: h5 }), this.cleanupDuplicatePairings(h5); + } catch (n3) { + await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionSettleResponse = async (t, e2) => { + const { id: i2 } = e2; + u3.isJsonRpcResult(e2) ? (await this.client.session.update(t, { acknowledged: true }), this.events.emit(s2.engineEvent("session_approve", i2), {})) : u3.isJsonRpcError(e2) && (await this.client.session.delete(t, s2.getSdkError("USER_DISCONNECTED")), this.events.emit(s2.engineEvent("session_approve", i2), { error: e2.error })); + }, this.onSessionUpdateRequest = async (t, e2) => { + const { params: i2, id: r } = e2; + try { + const n3 = `${t}_session_update`, a3 = s2.MemoryStore.get(n3); + if (a3 && this.isRequestOutOfSync(a3, r)) { + this.client.logger.info(`Discarding out of sync request - ${r}`), this.sendError({ id: r, topic: t, error: s2.getSdkError("INVALID_UPDATE_REQUEST") }); + return; + } + this.isValidUpdate(S4({ topic: t }, i2)); + try { + s2.MemoryStore.set(n3, r), await this.client.session.update(t, { namespaces: i2.namespaces }), await this.sendResult({ id: r, topic: t, result: true, throwOnFailedPublish: true }); + } catch (c4) { + throw s2.MemoryStore.delete(n3), c4; + } + this.client.events.emit("session_update", { id: r, topic: t, params: i2 }); + } catch (n3) { + await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.isRequestOutOfSync = (t, e2) => parseInt(e2.toString().slice(0, -3)) <= parseInt(t.toString().slice(0, -3)), this.onSessionUpdateResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_update", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_update", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_update", i2), { error: e2.error }); + }, this.onSessionExtendRequest = async (t, e2) => { + const { id: i2 } = e2; + try { + this.isValidExtend({ topic: t }), await this.setExpiry(t, s2.calcExpiry(V)), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_extend", { id: i2, topic: t }); + } catch (r) { + await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); + } + }, this.onSessionExtendResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_extend", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_extend", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_extend", i2), { error: e2.error }); + }, this.onSessionPingRequest = async (t, e2) => { + const { id: i2 } = e2; + try { + this.isValidPing({ topic: t }), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_ping", { id: i2, topic: t }); + } catch (r) { + await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); + } + }, this.onSessionPingResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_ping", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + setTimeout(() => { + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_ping", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_ping", i2), { error: e2.error }); + }, 500); + }, this.onSessionDeleteRequest = async (t, e2) => { + const { id: i2 } = e2; + try { + this.isValidDisconnect({ topic: t, reason: e2.params }), await Promise.all([new Promise((r) => { + this.client.core.relayer.once(N10.RELAYER_EVENTS.publish, async () => { + r(await this.deleteSession({ topic: t, id: i2 })); + }); + }), this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.cleanupPendingSentRequestsForTopic({ topic: t, error: s2.getSdkError("USER_DISCONNECTED") })]); + } catch (r) { + this.client.logger.error(r); + } + }, this.onSessionRequest = async (t, e2) => { + const { id: i2, params: r } = e2; + try { + await this.isValidRequest(S4({ topic: t }, r)); + const n3 = s2.hashMessage(JSON.stringify(u3.formatJsonRpcRequest("wc_sessionRequest", r, i2))), a3 = this.client.session.get(t), c4 = await this.getVerifyContext(n3, a3.peer.metadata), l4 = { id: i2, topic: t, params: r, verifyContext: c4 }; + await this.setPendingSessionRequest(l4), this.addSessionRequestToSessionRequestQueue(l4), this.processSessionRequestQueue(); + } catch (n3) { + await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionRequestResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_request", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); + }, this.onSessionEventRequest = async (t, e2) => { + const { id: i2, params: r } = e2; + try { + const n3 = `${t}_session_event_${r.event.name}`, a3 = s2.MemoryStore.get(n3); + if (a3 && this.isRequestOutOfSync(a3, i2)) { + this.client.logger.info(`Discarding out of sync request - ${i2}`); + return; + } + this.isValidEmit(S4({ topic: t }, r)), this.client.events.emit("session_event", { id: i2, topic: t, params: r }), s2.MemoryStore.set(n3, i2); + } catch (n3) { + await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionAuthenticateResponse = (t, e2) => { + const { id: i2 } = e2; + this.client.logger.trace({ type: "method", method: "onSessionAuthenticateResponse", topic: t, payload: e2 }), u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); + }, this.onSessionAuthenticateRequest = async (t, e2) => { + const { requester: i2, authPayload: r, expiryTimestamp: n3 } = e2.params, a3 = s2.hashMessage(JSON.stringify(e2)), c4 = await this.getVerifyContext(a3, this.client.metadata), l4 = { requester: i2, pairingTopic: t, id: e2.id, authPayload: r, verifyContext: c4, expiryTimestamp: n3 }; + await this.client.auth.requests.set(e2.id, l4), this.client.events.emit("session_authenticate", { topic: t, params: e2.params, id: e2.id }); + }, this.addSessionRequestToSessionRequestQueue = (t) => { + this.sessionRequestQueue.queue.push(t); + }, this.cleanupAfterResponse = (t) => { + this.deletePendingSessionRequest(t.response.id, { message: "fulfilled", code: 0 }), setTimeout(() => { + this.sessionRequestQueue.state = A2.idle, this.processSessionRequestQueue(); + }, w4.toMiliseconds(this.requestQueueDelay)); + }, this.cleanupPendingSentRequestsForTopic = ({ topic: t, error: e2 }) => { + const i2 = this.client.core.history.pending; + i2.length > 0 && i2.filter((r) => r.topic === t && r.request.method === "wc_sessionRequest").forEach((r) => { + const n3 = r.request.id, a3 = s2.engineEvent("session_request", n3); + if (this.events.listenerCount(a3) === 0) + throw new Error(`emitting ${a3} without any listeners`); + this.events.emit(s2.engineEvent("session_request", r.request.id), { error: e2 }); + }); + }, this.processSessionRequestQueue = () => { + if (this.sessionRequestQueue.state === A2.active) { + this.client.logger.info("session request queue is already active."); + return; + } + const t = this.sessionRequestQueue.queue[0]; + if (!t) { + this.client.logger.info("session request queue is empty."); + return; + } + try { + this.sessionRequestQueue.state = A2.active, this.client.events.emit("session_request", t); + } catch (e2) { + this.client.logger.error(e2); + } + }, this.onPairingCreated = (t) => { + if (t.methods && this.expectedPairingMethodMap.set(t.topic, t.methods), t.active) + return; + const e2 = this.client.proposal.getAll().find((i2) => i2.pairingTopic === t.topic); + e2 && this.onSessionProposeRequest(t.topic, u3.formatJsonRpcRequest("wc_sessionPropose", { requiredNamespaces: e2.requiredNamespaces, optionalNamespaces: e2.optionalNamespaces, relays: e2.relays, proposer: e2.proposer, sessionProperties: e2.sessionProperties }, e2.id)); + }, this.isValidConnect = async (t) => { + if (!s2.isValidParams(t)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() params: ${JSON.stringify(t)}`); + throw new Error(c4); + } + const { pairingTopic: e2, requiredNamespaces: i2, optionalNamespaces: r, sessionProperties: n3, relays: a3 } = t; + if (s2.isUndefined(e2) || await this.isValidPairingTopic(e2), !s2.isValidRelays(a3, true)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() relays: ${a3}`); + throw new Error(c4); + } + !s2.isUndefined(i2) && s2.isValidObject(i2) !== 0 && this.validateNamespaces(i2, "requiredNamespaces"), !s2.isUndefined(r) && s2.isValidObject(r) !== 0 && this.validateNamespaces(r, "optionalNamespaces"), s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); + }, this.validateNamespaces = (t, e2) => { + const i2 = s2.isValidRequiredNamespaces(t, "connect()", e2); + if (i2) + throw new Error(i2.message); + }, this.isValidApprove = async (t) => { + if (!s2.isValidParams(t)) + throw new Error(s2.getInternalError("MISSING_OR_INVALID", `approve() params: ${t}`).message); + const { id: e2, namespaces: i2, relayProtocol: r, sessionProperties: n3 } = t; + this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2); + const a3 = this.client.proposal.get(e2), c4 = s2.isValidNamespaces(i2, "approve()"); + if (c4) + throw new Error(c4.message); + const l4 = s2.isConformingNamespaces(a3.requiredNamespaces, i2, "approve()"); + if (l4) + throw new Error(l4.message); + if (!s2.isValidString(r, true)) { + const { message: d3 } = s2.getInternalError("MISSING_OR_INVALID", `approve() relayProtocol: ${r}`); + throw new Error(d3); + } + s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); + }, this.isValidReject = async (t) => { + if (!s2.isValidParams(t)) { + const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() params: ${t}`); + throw new Error(r); + } + const { id: e2, reason: i2 } = t; + if (this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2), !s2.isValidErrorReason(i2)) { + const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() reason: ${JSON.stringify(i2)}`); + throw new Error(r); + } + }, this.isValidSessionSettleRequest = (t) => { + if (!s2.isValidParams(t)) { + const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", `onSessionSettleRequest() params: ${t}`); + throw new Error(l4); + } + const { relay: e2, controller: i2, namespaces: r, expiry: n3 } = t; + if (!s2.isValidRelay(e2)) { + const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", "onSessionSettleRequest() relay protocol should be a string"); + throw new Error(l4); + } + const a3 = s2.isValidController(i2, "onSessionSettleRequest()"); + if (a3) + throw new Error(a3.message); + const c4 = s2.isValidNamespaces(r, "onSessionSettleRequest()"); + if (c4) + throw new Error(c4.message); + if (s2.isExpired(n3)) { + const { message: l4 } = s2.getInternalError("EXPIRED", "onSessionSettleRequest()"); + throw new Error(l4); + } + }, this.isValidUpdate = async (t) => { + if (!s2.isValidParams(t)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `update() params: ${t}`); + throw new Error(c4); + } + const { topic: e2, namespaces: i2 } = t; + this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); + const r = this.client.session.get(e2), n3 = s2.isValidNamespaces(i2, "update()"); + if (n3) + throw new Error(n3.message); + const a3 = s2.isConformingNamespaces(r.requiredNamespaces, i2, "update()"); + if (a3) + throw new Error(a3.message); + }, this.isValidExtend = async (t) => { + if (!s2.isValidParams(t)) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `extend() params: ${t}`); + throw new Error(i2); + } + const { topic: e2 } = t; + this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); + }, this.isValidRequest = async (t) => { + if (!s2.isValidParams(t)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() params: ${t}`); + throw new Error(c4); + } + const { topic: e2, request: i2, chainId: r, expiry: n3 } = t; + this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); + const { namespaces: a3 } = this.client.session.get(e2); + if (!s2.isValidNamespacesChainId(a3, r)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() chainId: ${r}`); + throw new Error(c4); + } + if (!s2.isValidRequest(i2)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() ${JSON.stringify(i2)}`); + throw new Error(c4); + } + if (!s2.isValidNamespacesRequest(a3, r, i2.method)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() method: ${i2.method}`); + throw new Error(c4); + } + if (n3 && !s2.isValidRequestExpiry(n3, H)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() expiry: ${n3}. Expiry must be a number (in seconds) between ${H.min} and ${H.max}`); + throw new Error(c4); + } + }, this.isValidRespond = async (t) => { + var e2; + if (!s2.isValidParams(t)) { + const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() params: ${t}`); + throw new Error(n3); + } + const { topic: i2, response: r } = t; + try { + await this.isValidSessionTopic(i2); + } catch (n3) { + throw (e2 = t?.response) != null && e2.id && this.cleanupAfterResponse(t), n3; + } + if (!s2.isValidResponse(r)) { + const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() response: ${JSON.stringify(r)}`); + throw new Error(n3); + } + }, this.isValidPing = async (t) => { + if (!s2.isValidParams(t)) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `ping() params: ${t}`); + throw new Error(i2); + } + const { topic: e2 } = t; + await this.isValidSessionOrPairingTopic(e2); + }, this.isValidEmit = async (t) => { + if (!s2.isValidParams(t)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() params: ${t}`); + throw new Error(a3); + } + const { topic: e2, event: i2, chainId: r } = t; + await this.isValidSessionTopic(e2); + const { namespaces: n3 } = this.client.session.get(e2); + if (!s2.isValidNamespacesChainId(n3, r)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() chainId: ${r}`); + throw new Error(a3); + } + if (!s2.isValidEvent(i2)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); + throw new Error(a3); + } + if (!s2.isValidNamespacesEvent(n3, r, i2.name)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); + throw new Error(a3); + } + }, this.isValidDisconnect = async (t) => { + if (!s2.isValidParams(t)) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${t}`); + throw new Error(i2); + } + const { topic: e2 } = t; + await this.isValidSessionOrPairingTopic(e2); + }, this.isValidAuthenticate = (t) => { + const { chains: e2, uri: i2, domain: r, nonce: n3 } = t; + if (!Array.isArray(e2) || e2.length === 0) + throw new Error("chains is required and must be a non-empty array"); + if (!s2.isValidString(i2, false)) + throw new Error("uri is required parameter"); + if (!s2.isValidString(r, false)) + throw new Error("domain is required parameter"); + if (!s2.isValidString(n3, false)) + throw new Error("nonce is required parameter"); + if ([...new Set(e2.map((c4) => s2.parseChainId(c4).namespace))].length > 1) + throw new Error("Multi-namespace requests are not supported. Please request single namespace only."); + const { namespace: a3 } = s2.parseChainId(e2[0]); + if (a3 !== "eip155") + throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains."); + }, this.getVerifyContext = async (t, e2) => { + const i2 = { verified: { verifyUrl: e2.verifyUrl || N10.VERIFY_SERVER, validation: "UNKNOWN", origin: e2.url || "" } }; + try { + const r = await this.client.core.verify.resolve({ attestationId: t, verifyUrl: e2.verifyUrl }); + r && (i2.verified.origin = r.origin, i2.verified.isScam = r.isScam, i2.verified.validation = r.origin === new URL(e2.url).origin ? "VALID" : "INVALID"); + } catch (r) { + this.client.logger.info(r); + } + return this.client.logger.info(`Verify context: ${JSON.stringify(i2)}`), i2; + }, this.validateSessionProps = (t, e2) => { + Object.values(t).forEach((i2) => { + if (!s2.isValidString(i2, false)) { + const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `${e2} must be in Record format. Received: ${JSON.stringify(i2)}`); + throw new Error(r); + } + }); + }, this.getPendingAuthRequest = (t) => { + const e2 = this.client.auth.requests.get(t); + return typeof e2 == "object" ? e2 : void 0; + }, this.addToRecentlyDeleted = (t, e2) => { + if (this.recentlyDeletedMap.set(t, e2), this.recentlyDeletedMap.size >= this.recentlyDeletedLimit) { + let i2 = 0; + const r = this.recentlyDeletedLimit / 2; + for (const n3 of this.recentlyDeletedMap.keys()) { + if (i2++ >= r) + break; + this.recentlyDeletedMap.delete(n3); + } + } + }, this.checkRecentlyDeleted = (t) => { + const e2 = this.recentlyDeletedMap.get(t); + if (e2) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${e2}: ${t}`); + throw new Error(i2); + } + }; + } + async isInitialized() { + if (!this.initialized) { + const { message: o2 } = s2.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(o2); + } + await this.client.core.relayer.confirmOnlineStateOrThrow(); + } + registerRelayerEvents() { + this.client.core.relayer.on(N10.RELAYER_EVENTS.message, async (o2) => { + const { topic: t, message: e2 } = o2, { publicKey: i2 } = this.client.auth.authKeys.keys.includes(U2) ? this.client.auth.authKeys.get(U2) : { responseTopic: void 0, publicKey: void 0 }, r = await this.client.core.crypto.decode(t, e2, { receiverPublicKey: i2 }); + try { + u3.isJsonRpcRequest(r) ? (this.client.core.history.set(t, r), this.onRelayEventRequest({ topic: t, payload: r })) : u3.isJsonRpcResponse(r) ? (await this.client.core.history.resolve(r), await this.onRelayEventResponse({ topic: t, payload: r }), this.client.core.history.delete(t, r.id)) : this.onRelayEventUnknownPayload({ topic: t, payload: r }); + } catch (n3) { + this.client.logger.error(n3); + } + }); + } + registerExpirerEvents() { + this.client.core.expirer.on(N10.EXPIRER_EVENTS.expired, async (o2) => { + const { topic: t, id: e2 } = s2.parseExpirerTarget(o2.target); + if (e2 && this.client.pendingRequest.keys.includes(e2)) + return await this.deletePendingSessionRequest(e2, s2.getInternalError("EXPIRED"), true); + t ? this.client.session.keys.includes(t) && (await this.deleteSession({ topic: t, expirerHasDeleted: true }), this.client.events.emit("session_expire", { topic: t })) : e2 && (await this.deleteProposal(e2, true), this.client.events.emit("proposal_expire", { id: e2 })); + }); + } + registerPairingEvents() { + this.client.core.pairing.events.on(N10.PAIRING_EVENTS.create, (o2) => this.onPairingCreated(o2)), this.client.core.pairing.events.on(N10.PAIRING_EVENTS.delete, (o2) => { + this.addToRecentlyDeleted(o2.topic, "pairing"); + }); + } + isValidPairingTopic(o2) { + if (!s2.isValidString(o2, false)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${o2}`); + throw new Error(t); + } + if (!this.client.core.pairing.pairings.keys.includes(o2)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${o2}`); + throw new Error(t); + } + if (s2.isExpired(this.client.core.pairing.pairings.get(o2).expiry)) { + const { message: t } = s2.getInternalError("EXPIRED", `pairing topic: ${o2}`); + throw new Error(t); + } + } + async isValidSessionTopic(o2) { + if (!s2.isValidString(o2, false)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic should be a string: ${o2}`); + throw new Error(t); + } + if (this.checkRecentlyDeleted(o2), !this.client.session.keys.includes(o2)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session topic doesn't exist: ${o2}`); + throw new Error(t); + } + if (s2.isExpired(this.client.session.get(o2).expiry)) { + await this.deleteSession({ topic: o2 }); + const { message: t } = s2.getInternalError("EXPIRED", `session topic: ${o2}`); + throw new Error(t); + } + if (!this.client.core.crypto.keychain.has(o2)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic does not exist in keychain: ${o2}`); + throw await this.deleteSession({ topic: o2 }), new Error(t); + } + } + async isValidSessionOrPairingTopic(o2) { + if (this.checkRecentlyDeleted(o2), this.client.session.keys.includes(o2)) + await this.isValidSessionTopic(o2); + else if (this.client.core.pairing.pairings.keys.includes(o2)) + this.isValidPairingTopic(o2); + else if (s2.isValidString(o2, false)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session or pairing topic doesn't exist: ${o2}`); + throw new Error(t); + } else { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session or pairing topic should be a string: ${o2}`); + throw new Error(t); + } + } + async isValidProposalId(o2) { + if (!s2.isValidId(o2)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `proposal id should be a number: ${o2}`); + throw new Error(t); + } + if (!this.client.proposal.keys.includes(o2)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `proposal id doesn't exist: ${o2}`); + throw new Error(t); + } + if (s2.isExpired(this.client.proposal.get(o2).expiryTimestamp)) { + await this.deleteProposal(o2); + const { message: t } = s2.getInternalError("EXPIRED", `proposal id: ${o2}`); + throw new Error(t); + } + } + }; + var $e = class extends N10.Store { + constructor(o2, t) { + super(o2, t, ce, F), this.core = o2, this.logger = t; + } + }; + var _e = class extends N10.Store { + constructor(o2, t) { + super(o2, t, he, F), this.core = o2, this.logger = t; + } + }; + var Ge = class extends N10.Store { + constructor(o2, t) { + super(o2, t, de, F, (e2) => e2.id), this.core = o2, this.logger = t; + } + }; + var Ke = class extends N10.Store { + constructor(o2, t) { + super(o2, t, we, L2, () => U2), this.core = o2, this.logger = t; + } + }; + var ke = class extends N10.Store { + constructor(o2, t) { + super(o2, t, ye, L2), this.core = o2, this.logger = t; + } + }; + var Fe = class extends N10.Store { + constructor(o2, t) { + super(o2, t, me, L2, (e2) => e2.id), this.core = o2, this.logger = t; + } + }; + var Ye = class { + constructor(o2, t) { + this.core = o2, this.logger = t, this.authKeys = new Ke(this.core, this.logger), this.pairingTopics = new ke(this.core, this.logger), this.requests = new Fe(this.core, this.logger); + } + async init() { + await this.authKeys.init(), await this.pairingTopics.init(), await this.requests.init(); + } + }; + var j2 = class _j extends oe.ISignClient { + constructor(o2) { + super(o2), this.protocol = ee, this.version = te, this.name = Y.name, this.events = new ae.EventEmitter(), this.on = (e2, i2) => this.events.on(e2, i2), this.once = (e2, i2) => this.events.once(e2, i2), this.off = (e2, i2) => this.events.off(e2, i2), this.removeListener = (e2, i2) => this.events.removeListener(e2, i2), this.removeAllListeners = (e2) => this.events.removeAllListeners(e2), this.connect = async (e2) => { + try { + return await this.engine.connect(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.pair = async (e2) => { + try { + return await this.engine.pair(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.approve = async (e2) => { + try { + return await this.engine.approve(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.reject = async (e2) => { + try { + return await this.engine.reject(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.update = async (e2) => { + try { + return await this.engine.update(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.extend = async (e2) => { + try { + return await this.engine.extend(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.request = async (e2) => { + try { + return await this.engine.request(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.respond = async (e2) => { + try { + return await this.engine.respond(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.ping = async (e2) => { + try { + return await this.engine.ping(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.emit = async (e2) => { + try { + return await this.engine.emit(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.disconnect = async (e2) => { + try { + return await this.engine.disconnect(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.find = (e2) => { + try { + return this.engine.find(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.getPendingSessionRequests = () => { + try { + return this.engine.getPendingSessionRequests(); + } catch (e2) { + throw this.logger.error(e2.message), e2; + } + }, this.authenticate = async (e2) => { + try { + return await this.engine.authenticate(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.formatAuthMessage = (e2) => { + try { + return this.engine.formatAuthMessage(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.approveSessionAuthenticate = async (e2) => { + try { + return await this.engine.approveSessionAuthenticate(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.rejectSessionAuthenticate = async (e2) => { + try { + return await this.engine.rejectSessionAuthenticate(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.name = o2?.name || Y.name, this.metadata = o2?.metadata || s2.getAppMetadata(); + const t = typeof o2?.logger < "u" && typeof o2?.logger != "string" ? o2.logger : k4.pino(k4.getDefaultLoggerOptions({ level: o2?.logger || Y.logger })); + this.core = o2?.core || new N10.Core(o2), this.logger = k4.generateChildLogger(t, this.name), this.session = new _e(this.core, this.logger), this.proposal = new $e(this.core, this.logger), this.pendingRequest = new Ge(this.core, this.logger), this.engine = new Ue(this), this.auth = new Ye(this.core, this.logger); + } + static async init(o2) { + const t = new _j(o2); + return await t.initialize(), t; + } + get context() { + return k4.getLoggerContext(this.logger); + } + get pairing() { + return this.core.pairing.pairings; + } + async initialize() { + this.logger.trace("Initialized"); + try { + await this.core.start(), await this.session.init(), await this.proposal.init(), await this.pendingRequest.init(), await this.engine.init(), await this.auth.init(), this.core.verify.init({ verifyUrl: this.metadata.verifyUrl }), this.logger.info("SignClient Initialization Success"); + } catch (o2) { + throw this.logger.info("SignClient Initialization Failure"), this.logger.error(o2.message), o2; + } + } + }; + var He = _e; + var je = j2; + exports2.AUTH_CONTEXT = Ee, exports2.AUTH_KEYS_CONTEXT = we, exports2.AUTH_PAIRING_TOPIC_CONTEXT = ye, exports2.AUTH_PROTOCOL = ge, exports2.AUTH_PUBLIC_KEY_NAME = U2, exports2.AUTH_REQUEST_CONTEXT = me, exports2.AUTH_STORAGE_PREFIX = L2, exports2.AUTH_VERSION = De, exports2.ENGINE_CONTEXT = pe, exports2.ENGINE_QUEUE_STATES = A2, exports2.ENGINE_RPC_OPTS = q2, exports2.HISTORY_CONTEXT = Oe, exports2.HISTORY_EVENTS = ve, exports2.HISTORY_STORAGE_VERSION = Ae, exports2.METHODS_TO_VERIFY = ue, exports2.PROPOSAL_CONTEXT = ce, exports2.PROPOSAL_EXPIRY = Ve, exports2.PROPOSAL_EXPIRY_MESSAGE = le, exports2.REQUEST_CONTEXT = de, exports2.SESSION_CONTEXT = he, exports2.SESSION_EXPIRY = V, exports2.SESSION_REQUEST_EXPIRY_BOUNDARIES = H, exports2.SIGN_CLIENT_CONTEXT = ie, exports2.SIGN_CLIENT_DEFAULT = Y, exports2.SIGN_CLIENT_EVENTS = Pe, exports2.SIGN_CLIENT_PROTOCOL = ee, exports2.SIGN_CLIENT_STORAGE_OPTIONS = Te, exports2.SIGN_CLIENT_STORAGE_PREFIX = F, exports2.SIGN_CLIENT_VERSION = te, exports2.SessionStore = He, exports2.SignClient = je, exports2.WALLETCONNECT_DEEPLINK_CHOICE = se, exports2.default = j2; + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js +var require_operation2 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OptionalOperation = exports2.Operation = void 0; + var Operation; + (function(Operation2) { + Operation2["SIGN_TRANSACTION"] = "mvx_signTransaction"; + Operation2["SIGN_TRANSACTIONS"] = "mvx_signTransactions"; + Operation2["SIGN_MESSAGE"] = "mvx_signMessage"; + })(Operation = exports2.Operation || (exports2.Operation = {})); + var OptionalOperation; + (function(OptionalOperation2) { + OptionalOperation2["SIGN_LOGIN_TOKEN"] = "mvx_signLoginToken"; + OptionalOperation2["SIGN_NATIVE_AUTH_TOKEN"] = "mvx_signNativeAuthToken"; + OptionalOperation2["CANCEL_ACTION"] = "mvx_cancelAction"; + })(OptionalOperation = exports2.OptionalOperation || (exports2.OptionalOperation = {})); + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js +var require_constants6 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = exports2.WALLETCONNECT_MULTIVERSX_METHODS = exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = void 0; + var operation_1 = require_operation2(); + exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = "mvx"; + exports2.WALLETCONNECT_MULTIVERSX_METHODS = Object.values(operation_1.Operation); + exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = Object.values(operation_1.OptionalOperation); + exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = 500; + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js +var require_errors3 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WalletConnectV2ProviderErrorMessagesEnum = exports2.ErrBadAddress = exports2.ErrNotImplemented = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + }; + exports2.Err = Err; + var ErrNotImplemented = class extends Err { + constructor() { + super("Method not yet implemented"); + } + }; + exports2.ErrNotImplemented = ErrNotImplemented; + var ErrBadAddress = class extends Err { + constructor(value, inner) { + super(`Bad address: ${value}`, inner); + } + }; + exports2.ErrBadAddress = ErrBadAddress; + var WalletConnectV2ProviderErrorMessagesEnum; + (function(WalletConnectV2ProviderErrorMessagesEnum2) { + WalletConnectV2ProviderErrorMessagesEnum2["unableToInit"] = "WalletConnect is unable to init"; + WalletConnectV2ProviderErrorMessagesEnum2["notInitialized"] = "WalletConnect is not initialized"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToConnect"] = "WalletConnect is unable to connect"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToConnectExisting"] = "WalletConnect is unable to connect to existing pairing"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToSignLoginToken"] = "WalletConnect could not sign login token"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToSign"] = "WalletConnect could not sign the message"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToLogin"] = "WalletConnect is unable to login"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleTopic"] = "WalletConnect: Unable to handle topic update"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleEvent"] = "WalletConnect: Unable to handle events"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleCleanup"] = "WalletConnect: Unable to handle cleanup"; + WalletConnectV2ProviderErrorMessagesEnum2["sessionNotConnected"] = "WalletConnect Session is not connected"; + WalletConnectV2ProviderErrorMessagesEnum2["sessionDeleted"] = "WalletConnect Session Deleted"; + WalletConnectV2ProviderErrorMessagesEnum2["sessionExpired"] = "WalletConnect Session Expired"; + WalletConnectV2ProviderErrorMessagesEnum2["alreadyLoggedOut"] = "WalletConnect: Already logged out"; + WalletConnectV2ProviderErrorMessagesEnum2["pingFailed"] = "WalletConnect Ping Failed"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidAddress"] = "WalletConnect: Invalid address"; + WalletConnectV2ProviderErrorMessagesEnum2["requestDifferentChain"] = "WalletConnect: Request Chain Id different than Connection Chain Id"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageResponse"] = "WalletConnect could not sign the message"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageSignature"] = "WalletConnect: Invalid message signature"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidTransactionResponse"] = "WalletConnect could not sign the transactions. Invalid signatures"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidCustomRequestResponse"] = "WalletConnect could not send the custom request"; + WalletConnectV2ProviderErrorMessagesEnum2["transactionError"] = "Transaction canceled"; + WalletConnectV2ProviderErrorMessagesEnum2["connectionError"] = "WalletConnect could not establish a connection"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidGuardian"] = "WalletConnect: Invalid Guardian"; + })(WalletConnectV2ProviderErrorMessagesEnum = exports2.WalletConnectV2ProviderErrorMessagesEnum || (exports2.WalletConnectV2ProviderErrorMessagesEnum = {})); + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js +var require_logger2 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Logger = void 0; + var Logger = class { + static error(message) { + console.error(message); + } + static trace(message) { + console.trace(message); + } + }; + exports2.Logger = Logger; + } +}); + +// node_modules/@multiversx/sdk-core/out/globals.js +var require_globals = __commonJS({ + "node_modules/@multiversx/sdk-core/out/globals.js"() { + "use strict"; + init_shim(); + if (!global.Buffer) { + global.Buffer = require_buffer2().Buffer; + } + } +}); + +// node_modules/@multiversx/sdk-core/out/smartContractQuery.js +var require_smartContractQuery = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartContractQuery.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractQueryResponse = exports2.SmartContractQuery = void 0; + var SmartContractQuery = class { + constructor(options) { + this.contract = options.contract; + this.caller = options.caller; + this.value = options.value; + this.function = options.function; + this.arguments = options.arguments; + } + }; + exports2.SmartContractQuery = SmartContractQuery; + var SmartContractQueryResponse = class { + constructor(obj) { + this.function = obj.function; + this.returnCode = obj.returnCode; + this.returnMessage = obj.returnMessage; + this.returnDataParts = obj.returnDataParts; + } + }; + exports2.SmartContractQueryResponse = SmartContractQueryResponse; + } +}); + +// node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js +var require_queryRunnerAdapter = __commonJS({ + "node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.QueryRunnerAdapter = void 0; + var address_1 = require_address(); + var smartContractQuery_1 = require_smartContractQuery(); + var QueryRunnerAdapter = class { + constructor(options) { + this.networkProvider = options.networkProvider; + } + async runQuery(query) { + const adaptedQuery = { + address: address_1.Address.fromBech32(query.contract), + caller: query.caller ? address_1.Address.fromBech32(query.caller) : void 0, + func: query.function, + value: query.value, + getEncodedArguments: () => query.arguments.map((arg) => import_buffer.Buffer.from(arg).toString("hex")) + }; + const adaptedQueryResponse = await this.networkProvider.queryContract(adaptedQuery); + return new smartContractQuery_1.SmartContractQueryResponse({ + function: query.function, + returnCode: adaptedQueryResponse.returnCode.toString(), + returnMessage: adaptedQueryResponse.returnMessage, + returnDataParts: adaptedQueryResponse.getReturnDataParts() + }); + } + }; + exports2.QueryRunnerAdapter = QueryRunnerAdapter; + } +}); + +// node_modules/@multiversx/sdk-core/out/adapters/index.js +var require_adapters = __commonJS({ + "node_modules/@multiversx/sdk-core/out/adapters/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_queryRunnerAdapter(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/converters/index.js +var require_converters = __commonJS({ + "node_modules/@multiversx/sdk-core/out/converters/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_transactionsConverter(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/gasEstimator.js +var require_gasEstimator = __commonJS({ + "node_modules/@multiversx/sdk-core/out/gasEstimator.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.GasEstimator = exports2.DefaultGasConfiguration = void 0; + exports2.DefaultGasConfiguration = { + minGasLimit: 5e4, + gasPerDataByte: 1500, + gasCostESDTTransfer: 2e5, + gasCostESDTNFTTransfer: 2e5, + gasCostESDTNFTMultiTransfer: 2e5 + }; + var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; + var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; + var GasEstimator = class { + constructor(gasConfiguration) { + this.gasConfiguration = gasConfiguration || exports2.DefaultGasConfiguration; + } + forEGLDTransfer(dataLength) { + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasPerDataByte * dataLength; + return gasLimit; + } + forESDTTransfer(dataLength) { + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_TRANSFER; + return gasLimit; + } + forESDTNFTTransfer(dataLength) { + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTNFTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER; + return gasLimit; + } + forMultiESDTNFTTransfer(dataLength, numTransfers) { + const gasLimit = this.gasConfiguration.minGasLimit + (this.gasConfiguration.gasCostESDTNFTMultiTransfer + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER) * numTransfers + this.gasConfiguration.gasPerDataByte * dataLength; + return gasLimit; + } + }; + exports2.GasEstimator = GasEstimator; + } +}); + +// node_modules/@multiversx/sdk-core/out/interface.js +var require_interface2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/interface.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js +var require_interfaceOfNetwork = __commonJS({ + "node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js +var require_relayedTransactionV1Builder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RelayedTransactionV1Builder = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var JSONbig = require_json_bigint(); + var RelayedTransactionV1Builder = class { + /** + * Sets the inner transaction to be used. It has to be already signed. + * + * @param {Transaction} transaction The inner transaction to be used + */ + setInnerTransaction(transaction) { + this.innerTransaction = transaction; + return this; + } + /** + * Sets the network config to be used for building the relayed v1 transaction + * + * @param {INetworkConfig} netConfig The network configuration to be used + */ + setNetworkConfig(netConfig) { + this.netConfig = netConfig; + return this; + } + /** + * Sets the address of the relayer (the one that will actually pay the fee) + * + * @param relayerAddress + */ + setRelayerAddress(relayerAddress) { + this.relayerAddress = relayerAddress; + return this; + } + /** + * (optional) Sets the nonce of the relayer + * + * @param relayerNonce + */ + setRelayerNonce(relayerNonce) { + this.relayerNonce = relayerNonce; + return this; + } + /** + * (optional) Sets the version of the relayed transaction + * + * @param relayedTxVersion + */ + setRelayedTransactionVersion(relayedTxVersion) { + this.relayedTransactionVersion = relayedTxVersion; + return this; + } + /** + * (optional) Sets the options of the relayed transaction + * + * @param relayedTxOptions + */ + setRelayedTransactionOptions(relayedTxOptions) { + this.relayedTransactionOptions = relayedTxOptions; + return this; + } + /** + * (optional) Sets the guardian of the relayed transaction + * + * @param relayedTxGuardian + */ + setRelayedTransactionGuardian(relayedTxGuardian) { + this.relayedTransactionGuardian = relayedTxGuardian; + return this; + } + /** + * Tries to build the relayed v1 transaction based on the previously set fields + * + * @throws ErrInvalidRelayedV1BuilderArguments + * @return Transaction + */ + build() { + if (!this.innerTransaction || !this.netConfig || !this.relayerAddress || !this.innerTransaction.getSignature()) { + throw new errors_1.ErrInvalidRelayedV1BuilderArguments(); + } + const serializedTransaction = this.prepareInnerTransaction(); + const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; + const payload = new transactionPayload_1.TransactionPayload(data); + const gasLimit = this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length() + this.innerTransaction.getGasLimit().valueOf(); + let relayedTransaction = new transaction_1.Transaction({ + nonce: this.relayerNonce, + sender: this.relayerAddress, + receiver: this.innerTransaction.getSender(), + value: 0, + gasLimit, + data: payload, + chainID: this.netConfig.ChainID, + version: this.relayedTransactionVersion, + options: this.relayedTransactionOptions, + guardian: this.relayedTransactionGuardian + }); + if (this.relayerNonce) { + relayedTransaction.setNonce(this.relayerNonce); + } + return relayedTransaction; + } + prepareInnerTransaction() { + if (!this.innerTransaction) { + return ""; + } + const txObject = { + nonce: this.innerTransaction.getNonce().valueOf(), + sender: new address_1.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"), + receiver: new address_1.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"), + value: BigInt(this.innerTransaction.getValue().toString()), + gasPrice: this.innerTransaction.getGasPrice().valueOf(), + gasLimit: this.innerTransaction.getGasLimit().valueOf(), + data: this.innerTransaction.getData().valueOf().toString("base64"), + signature: this.innerTransaction.getSignature().toString("base64"), + chainID: import_buffer.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"), + version: this.innerTransaction.getVersion().valueOf(), + options: this.innerTransaction.getOptions().valueOf() == 0 ? void 0 : this.innerTransaction.getOptions().valueOf(), + guardian: this.innerTransaction.getGuardian().bech32() ? new address_1.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64") : void 0, + guardianSignature: this.innerTransaction.getGuardianSignature().toString("hex") ? this.innerTransaction.getGuardianSignature().toString("base64") : void 0, + sndUserName: this.innerTransaction.getSenderUsername() ? import_buffer.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64") : void 0, + rcvUserName: this.innerTransaction.getReceiverUsername() ? import_buffer.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64") : void 0 + }; + return JSONbig.stringify(txObject); + } + }; + exports2.RelayedTransactionV1Builder = RelayedTransactionV1Builder; + } +}); + +// node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js +var require_relayedTransactionV2Builder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RelayedTransactionV2Builder = void 0; + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var RelayedTransactionV2Builder = class { + /** + * Sets the inner transaction to be used. It has to be already signed and with gasLimit set to 0. These checks + * are performed on the build() method + * + * @param {Transaction} transaction The inner transaction to be used + */ + setInnerTransaction(transaction) { + this.innerTransaction = transaction; + return this; + } + /** + * Sets the gas limit to be used for the SC Call inside the inner transaction + * + * @param {IGasLimit} gasLimit The gas limit to be used. The inner transaction needs to have the gas limit set to 0, + * so this field will specify the gas to be used for the SC call of the inner transaction + */ + setInnerTransactionGasLimit(gasLimit) { + this.innerTransactionGasLimit = gasLimit; + return this; + } + /** + * Sets the network config to be used for building the relayed v2 transaction + * + * @param {INetworkConfig} netConfig The network configuration to be used + */ + setNetworkConfig(netConfig) { + this.netConfig = netConfig; + return this; + } + /** + * Sets the address of the relayer (the one that will actually pay the fee) + * + * @param relayerAddress + */ + setRelayerAddress(relayerAddress) { + this.relayerAddress = relayerAddress; + return this; + } + /** + * (optional) Sets the nonce of the relayer + * + * @param relayerNonce + */ + setRelayerNonce(relayerNonce) { + this.relayerNonce = relayerNonce; + return this; + } + /** + * Tries to build the relayed v2 transaction based on the previously set fields. + * It returns a transaction that isn't signed + * + * @throws ErrInvalidRelayedV2BuilderArguments + * @throws ErrGasLimitShouldBe0ForInnerTransaction + * @return Transaction + */ + build() { + if (!this.innerTransaction || !this.innerTransactionGasLimit || !this.relayerAddress || !this.netConfig || !this.innerTransaction.getSignature()) { + throw new errors_1.ErrInvalidRelayedV2BuilderArguments(); + } + if (this.innerTransaction.getGasLimit() != 0) { + throw new errors_1.ErrGasLimitShouldBe0ForInnerTransaction(); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + new smartcontracts_1.AddressValue(this.innerTransaction.getReceiver()), + new smartcontracts_1.U64Value(this.innerTransaction.getNonce().valueOf()), + new smartcontracts_1.BytesValue(this.innerTransaction.getData().valueOf()), + new smartcontracts_1.BytesValue(this.innerTransaction.getSignature()) + ]); + const data = `relayedTxV2@${argumentsString}`; + const payload = new transactionPayload_1.TransactionPayload(data); + let relayedTransaction = new transaction_1.Transaction({ + sender: this.relayerAddress, + receiver: this.innerTransaction.getSender(), + value: 0, + gasLimit: this.innerTransactionGasLimit.valueOf() + this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length(), + data: payload, + chainID: this.netConfig.ChainID, + version: this.innerTransaction.getVersion(), + options: this.innerTransaction.getOptions() + }); + if (this.relayerNonce) { + relayedTransaction.setNonce(this.relayerNonce); + } + return relayedTransaction; + } + }; + exports2.RelayedTransactionV2Builder = RelayedTransactionV2Builder; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js +var require_smartContractQueriesController = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractQueriesController = void 0; + var errors_1 = require_errors(); + var smartContractQuery_1 = require_smartContractQuery(); + var smartcontracts_1 = require_smartcontracts(); + var SmartContractQueriesController = class { + constructor(options) { + this.abi = options.abi; + this.queryRunner = options.queryRunner; + this.legacyResultsParser = new smartcontracts_1.ResultsParser(); + } + createQuery(options) { + const preparedArguments = this.encodeArguments(options.function, options.arguments); + return new smartContractQuery_1.SmartContractQuery({ + contract: options.contract, + caller: options.caller, + function: options.function, + arguments: preparedArguments, + value: options.value + }); + } + encodeArguments(functionName, args) { + const endpoint = this.abi?.getEndpoint(functionName); + if (endpoint) { + const typedArgs = smartcontracts_1.NativeSerializer.nativeToTypedValues(args, endpoint); + return new smartcontracts_1.ArgSerializer().valuesToBuffers(typedArgs); + } + if (this.areArgsOfTypedValue(args)) { + return new smartcontracts_1.ArgSerializer().valuesToBuffers(args); + } + if (this.areArgsBuffers(args)) { + return args.map((arg) => import_buffer.Buffer.from(arg)); + } + throw new errors_1.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers"); + } + areArgsOfTypedValue(args) { + for (const arg of args) { + if (!arg.belongsToTypesystem) { + return false; + } + } + return true; + } + areArgsBuffers(args) { + for (const arg of args) { + if (!ArrayBuffer.isView(arg)) { + return false; + } + } + return true; + } + async runQuery(query) { + const queryResponse = await this.queryRunner.runQuery(query); + return queryResponse; + } + parseQueryResponse(response) { + if (!this.abi) { + return response.returnDataParts; + } + const legacyQueryResponse = { + returnCode: response.returnCode, + returnMessage: response.returnMessage, + getReturnDataParts: () => response.returnDataParts.map((part) => import_buffer.Buffer.from(part)) + }; + const functionName = response.function; + const endpoint = this.abi.getEndpoint(functionName); + const legacyBundle = this.legacyResultsParser.parseQueryResponse(legacyQueryResponse, endpoint); + const nativeValues = legacyBundle.values.map((value) => value.valueOf()); + return nativeValues; + } + }; + exports2.SmartContractQueriesController = SmartContractQueriesController; + } +}); + +// node_modules/@multiversx/sdk-core/out/index.js +var require_out = __commonJS({ + "node_modules/@multiversx/sdk-core/out/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + require_globals(); + __exportStar2(require_account(), exports2); + __exportStar2(require_adapters(), exports2); + __exportStar2(require_address(), exports2); + __exportStar2(require_asyncTimer(), exports2); + __exportStar2(require_converters(), exports2); + __exportStar2(require_errors(), exports2); + __exportStar2(require_gasEstimator(), exports2); + __exportStar2(require_interface2(), exports2); + __exportStar2(require_interfaceOfNetwork(), exports2); + __exportStar2(require_logger(), exports2); + __exportStar2(require_message(), exports2); + __exportStar2(require_networkParams(), exports2); + __exportStar2(require_relayedTransactionV1Builder(), exports2); + __exportStar2(require_relayedTransactionV2Builder(), exports2); + __exportStar2(require_signableMessage(), exports2); + __exportStar2(require_smartContractQueriesController(), exports2); + __exportStar2(require_smartcontracts(), exports2); + __exportStar2(require_tokenOperations(), exports2); + __exportStar2(require_tokens(), exports2); + __exportStar2(require_transaction(), exports2); + __exportStar2(require_transactionComputer(), exports2); + __exportStar2(require_transactionPayload(), exports2); + __exportStar2(require_transactionWatcher(), exports2); + __exportStar2(require_transactionsFactories(), exports2); + __exportStar2(require_transactionsOutcomeParsers(), exports2); + __exportStar2(require_utils2(), exports2); + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js +var require_utils4 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.sleep = exports2.getMetadata = exports2.applyTransactionSignature = exports2.getAddressFromSession = exports2.addressIsValid = exports2.getConnectionParams = exports2.getCurrentTopic = exports2.getCurrentSession = void 0; + var sdk_core_1 = require_out(); + var signature_1 = require_signature(); + var utils_1 = require_index_cjs2(); + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + var logger_1 = require_logger2(); + var operation_1 = require_operation2(); + function getCurrentSession(chainId, client) { + if (!client) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + const acknowledgedSessions = client.find(getConnectionParams(chainId)).filter((s2) => s2.acknowledged); + if (acknowledgedSessions.length > 0) { + const lastKeyIndex = acknowledgedSessions.length - 1; + const session = acknowledgedSessions[lastKeyIndex]; + return session; + } + if (client.session.length > 0) { + const lastKeyIndex = client.session.keys.length - 1; + const session = client.session.get(client.session.keys[lastKeyIndex]); + return session; + } + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + exports2.getCurrentSession = getCurrentSession; + function getCurrentTopic(chainId, client) { + if (!client) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + const session = getCurrentSession(chainId, client); + if (!(session === null || session === void 0 ? void 0 : session.topic)) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + return session.topic; + } + exports2.getCurrentTopic = getCurrentTopic; + function getConnectionParams(chainId, options) { + var _a, _b, _c; + const methods = [ + ...constants_1.WALLETCONNECT_MULTIVERSX_METHODS, + ...(_a = options === null || options === void 0 ? void 0 : options.methods) !== null && _a !== void 0 ? _a : [] + ]; + if (!((_b = options === null || options === void 0 ? void 0 : options.methods) === null || _b === void 0 ? void 0 : _b.includes(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN))) { + methods.push(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN); + } + const chains = [`${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${chainId}`]; + const events = (_c = options === null || options === void 0 ? void 0 : options.events) !== null && _c !== void 0 ? _c : []; + return { + requiredNamespaces: { + [constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]: { + methods, + chains, + events + } + } + }; + } + exports2.getConnectionParams = getConnectionParams; + function addressIsValid(destinationAddress) { + try { + const address = sdk_core_1.Address.fromBech32(destinationAddress); + return !address.isEmpty(); + } catch (_a) { + return false; + } + } + exports2.addressIsValid = addressIsValid; + function getAddressFromSession(session) { + const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; + if (selectedNamespace && selectedNamespace.accounts) { + const currentSession = selectedNamespace.accounts[0]; + const [namespace, reference, address] = currentSession.split(":"); + return address; + } + return ""; + } + exports2.getAddressFromSession = getAddressFromSession; + function applyTransactionSignature({ transaction, response }) { + if (!response) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + } + const { signature, guardianSignature, version: version2, options, guardian } = response; + const transactionGuardian = transaction.getGuardian().bech32(); + if (transactionGuardian && transactionGuardian !== guardian) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); + } + if (guardian) { + transaction.setGuardian(sdk_core_1.Address.fromBech32(guardian)); + } + if (version2) { + transaction.setVersion(version2); + } + if (options != null) { + transaction.setOptions(options); + } + transaction.applySignature(new signature_1.Signature(signature)); + if (guardianSignature) { + transaction.applyGuardianSignature(new signature_1.Signature(guardianSignature)); + } + return transaction; + } + exports2.applyTransactionSignature = applyTransactionSignature; + function getMetadata(metadata) { + if (metadata) { + return Object.assign(Object.assign({}, metadata), { url: utils_1.getAppMetadata().url }); + } + return; + } + exports2.getMetadata = getMetadata; + function sleep(timeout) { + return __awaiter2(this, void 0, void 0, function* () { + return yield new Promise((resolve) => setTimeout(() => { + resolve(); + }, timeout)); + }); + } + exports2.sleep = sleep; + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js +var require_walletConnectV2Provider = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WalletConnectV2Provider = exports2.OptionalOperation = exports2.Operation = exports2.WalletConnectV2ProviderErrorMessagesEnum = void 0; + var signature_1 = require_signature(); + var sign_client_1 = __importDefault2(require_index_cjs4()); + var utils_1 = require_index_cjs2(); + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + Object.defineProperty(exports2, "WalletConnectV2ProviderErrorMessagesEnum", { enumerable: true, get: function() { + return errors_1.WalletConnectV2ProviderErrorMessagesEnum; + } }); + var logger_1 = require_logger2(); + var operation_1 = require_operation2(); + Object.defineProperty(exports2, "Operation", { enumerable: true, get: function() { + return operation_1.Operation; + } }); + Object.defineProperty(exports2, "OptionalOperation", { enumerable: true, get: function() { + return operation_1.OptionalOperation; + } }); + var utils_2 = require_utils4(); + var WalletConnectV2Provider5 = class { + constructor(onClientConnect, chainId, walletConnectV2Relay, walletConnectV2ProjectId, options) { + this.chainId = ""; + this.address = ""; + this.signature = ""; + this.isInitializing = false; + this.processingTopic = ""; + this.options = {}; + this.onClientConnect = onClientConnect; + this.chainId = chainId; + this.walletConnectV2Relay = walletConnectV2Relay; + this.walletConnectV2ProjectId = walletConnectV2ProjectId; + this.options = options; + } + reset() { + this.address = ""; + this.signature = ""; + this.walletConnector = void 0; + this.session = void 0; + this.pairings = void 0; + } + /** + * Initiates WalletConnect client. + */ + init() { + var _a, _b; + return __awaiter2(this, void 0, void 0, function* () { + if (this.isInitialized()) { + return this.isInitialized(); + } else { + try { + if (!this.isInitializing) { + this.isInitializing = true; + this.reset(); + const metadata = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.metadata) ? { + metadata: utils_2.getMetadata((_b = this.options) === null || _b === void 0 ? void 0 : _b.metadata) + } : {}; + const client = yield sign_client_1.default.init(Object.assign(Object.assign(Object.assign({}, this.options), { relayUrl: this.walletConnectV2Relay, projectId: this.walletConnectV2ProjectId }), metadata)); + this.walletConnector = client; + this.isInitializing = false; + yield this.subscribeToEvents(client); + yield this.checkPersistedState(client); + } + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToInit); + } finally { + this.isInitializing = false; + return this.isInitialized(); + } + } + }); + } + /** + * Returns true if init() was previously called successfully + */ + isInitialized() { + return !!this.walletConnector && !this.isInitializing; + } + /** + * Returns true if provider is initialized and a valid session is set + */ + isConnected() { + return new Promise((resolve, _4) => resolve(Boolean(this.isInitialized() && typeof this.session !== "undefined"))); + } + connect(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + const connectParams = utils_2.getConnectionParams(this.chainId, options); + try { + const response = yield this.walletConnector.connect(Object.assign({ pairingTopic: options === null || options === void 0 ? void 0 : options.topic }, connectParams)); + return response; + } catch (error) { + this.reset(); + logger_1.Logger.error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); + throw new Error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); + } + }); + } + login(options) { + var _a; + return __awaiter2(this, void 0, void 0, function* () { + this.isInitializing = true; + if (typeof this.walletConnector === "undefined") { + yield this.connect(); + } + if (typeof this.walletConnector === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session !== "undefined") { + yield this.logout({ topic: (_a = this.session) === null || _a === void 0 ? void 0 : _a.topic }); + } + try { + if (options && options.approval) { + const session = yield options.approval(); + if (options.token) { + yield utils_2.sleep(constants_1.WALLETCONNECT_SIGN_LOGIN_DELAY); + const address = utils_2.getAddressFromSession(session); + const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; + const method = selectedNamespace.methods.includes(operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN) ? operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN : operation_1.OptionalOperation.SIGN_LOGIN_TOKEN; + const { signature } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: session.topic, + request: { + method, + params: { + token: options.token, + address + } + } + }); + if (!signature) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); + } + return yield this.onSessionConnected({ + session, + signature + }); + } + return yield this.onSessionConnected({ + session, + signature: "" + }); + } + } catch (error) { + this.reset(); + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); + } finally { + this.isInitializing = false; + } + return ""; + }); + } + /** + * Mocks a logout request by returning true + */ + logout(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + try { + if (this.processingTopic === ((options === null || options === void 0 ? void 0 : options.topic) || utils_2.getCurrentTopic(this.chainId, this.walletConnector))) { + return true; + } + if (options === null || options === void 0 ? void 0 : options.topic) { + this.processingTopic = options.topic; + yield this.walletConnector.disconnect({ + topic: options.topic, + reason: utils_1.getSdkError("USER_DISCONNECTED") + }); + } else { + const currentSessionTopic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); + this.processingTopic = currentSessionTopic; + yield this.walletConnector.disconnect({ + topic: currentSessionTopic, + reason: utils_1.getSdkError("USER_DISCONNECTED") + }); + this.reset(); + yield this.cleanupPendingPairings({ deletePairings: true }); + } + } catch (_a) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut); + } finally { + this.processingTopic = ""; + } + return true; + }); + } + /** + * Fetches the WalletConnect address + */ + getAddress() { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + return this.address; + }); + } + /** + * Fetches the WalletConnect signature + */ + getSignature() { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + return this.signature; + }); + } + /** + * Fetches the WalletConnect pairings + */ + getPairings() { + var _a, _b, _c, _d, _e; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + return (_e = (_d = (_c = (_b = (_a = this.walletConnector) === null || _a === void 0 ? void 0 : _a.core) === null || _b === void 0 ? void 0 : _b.pairing) === null || _c === void 0 ? void 0 : _c.pairings) === null || _d === void 0 ? void 0 : _d.getAll({ active: true })) !== null && _e !== void 0 ? _e : []; + }); + } + /** + * Signs a message and returns it signed + * @param message + */ + signMessage(message) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + try { + const address = yield this.getAddress(); + const { signature } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: { + method: operation_1.Operation.SIGN_MESSAGE, + params: { + address, + message: message.message.toString() + } + } + }); + if (!signature) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); + } + try { + message.applySignature(new signature_1.Signature(signature)); + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); + } + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSign); + } + return message; + }); + } + /** + * Signs a transaction and returns it signed + * @param transaction + */ + signTransaction(transaction) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + const plainTransaction = transaction.toPlainObject(); + if (this.chainId !== transaction.getChainID().valueOf()) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + } + try { + const response = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: { + method: operation_1.Operation.SIGN_TRANSACTION, + params: { + transaction: plainTransaction + } + } + }); + return utils_2.applyTransactionSignature({ transaction, response }); + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); + } + }); + } + /** + * Signs an array of transactions and returns it signed + * @param transactions + */ + signTransactions(transactions) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + const plainTransactions = transactions.map((transaction) => { + if (this.chainId !== transaction.getChainID().valueOf()) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + } + return transaction.toPlainObject(); + }); + try { + const { signatures } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: { + method: operation_1.Operation.SIGN_TRANSACTIONS, + params: { + transactions: plainTransactions + } + } + }); + if (!signatures) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + } + if (!Array.isArray(signatures) || transactions.length !== signatures.length) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + } + for (const [index, transaction] of transactions.entries()) { + const response = signatures[index]; + utils_2.applyTransactionSignature({ transaction, response }); + } + return transactions; + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); + } + }); + } + /** + * Sends a custom request + * @param request + */ + sendCustomRequest(options) { + var _a; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + if ((_a = options === null || options === void 0 ? void 0 : options.request) === null || _a === void 0 ? void 0 : _a.method) { + try { + const request = Object.assign({}, options.request); + let { method } = request; + const { response } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: Object.assign(Object.assign({}, request), { method }) + }); + if (!response) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); + } + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); + } + return; + } + }); + } + /** + * Ping helper + */ + ping() { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + try { + const topic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); + yield this.walletConnector.ping({ + topic + }); + return true; + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.pingFailed); + return false; + } + }); + } + loginAccount(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (!options) { + return ""; + } + if (utils_2.addressIsValid(options.address)) { + this.address = options.address; + if (options.signature) { + this.signature = options.signature; + } + this.onClientConnect.onClientLogin(); + return this.address; + } + logger_1.Logger.error(`${errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${options.address}`); + if (this.walletConnector) { + yield this.logout(); + } + return ""; + }); + } + onSessionConnected(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (!options) { + return ""; + } + this.session = options.session; + const address = utils_2.getAddressFromSession(options.session); + if (address) { + yield this.loginAccount({ address, signature: options.signature }); + return address; + } + return ""; + }); + } + handleTopicUpdateEvent({ topic }) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + return; + } + try { + const existingPairings = yield this.getPairings(); + if (this.address && !this.isInitializing && existingPairings) { + if ((existingPairings === null || existingPairings === void 0 ? void 0 : existingPairings.length) === 0) { + this.onClientConnect.onClientLogout(); + } else { + const lastActivePairing = existingPairings[existingPairings.length - 1]; + if ((lastActivePairing === null || lastActivePairing === void 0 ? void 0 : lastActivePairing.topic) === topic) { + this.onClientConnect.onClientLogout(); + } + } + } + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic); + } finally { + this.pairings = yield this.getPairings(); + } + }); + } + handleSessionEvents({ topic, params }) { + var _a; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (this.session && ((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) !== topic) { + return; + } + const { event } = params; + if ((event === null || event === void 0 ? void 0 : event.name) && utils_2.getCurrentTopic(this.chainId, this.walletConnector) === topic) { + const eventData = event.data; + this.onClientConnect.onClientEvent(eventData); + } + }); + } + subscribeToEvents(client) { + var _a, _b, _c, _d; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof client === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + try { + client.on("session_update", ({ topic, params }) => { + var _a2; + if (!this.session || ((_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.topic) !== topic) { + return; + } + const { namespaces } = params; + const _session = client.session.get(topic); + const updatedSession = Object.assign(Object.assign({}, _session), { namespaces }); + this.onSessionConnected({ session: updatedSession }); + }); + client.on("session_event", this.handleSessionEvents.bind(this)); + client.on("session_delete", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { + var _e; + if (this.isInitializing) { + this.onClientConnect.onClientLogout(); + this.reset(); + } + if (!this.session || ((_e = this.session) === null || _e === void 0 ? void 0 : _e.topic) !== topic) { + return; + } + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted); + this.onClientConnect.onClientLogout(); + this.reset(); + yield this.cleanupPendingPairings({ deletePairings: true }); + })); + client.on("session_expire", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { + var _f; + if (!this.session || ((_f = this.session) === null || _f === void 0 ? void 0 : _f.topic) !== topic) { + return; + } + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired); + this.onClientConnect.onClientLogout(); + this.reset(); + yield this.cleanupPendingPairings({ deletePairings: true }); + })); + (_b = (_a = client.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.events.on("pairing_delete", this.handleTopicUpdateEvent.bind(this)); + (_d = (_c = client.core) === null || _c === void 0 ? void 0 : _c.pairing) === null || _d === void 0 ? void 0 : _d.events.on("pairing_expire", this.handleTopicUpdateEvent.bind(this)); + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent); + } + }); + } + checkPersistedState(client) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof client === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + this.pairings = yield this.getPairings(); + if (typeof this.session !== "undefined") { + return; + } + if (client.session.length && !this.address && !this.isInitializing) { + const session = utils_2.getCurrentSession(this.chainId, client); + if (session) { + yield this.onSessionConnected({ session }); + return session; + } + } + return; + }); + } + cleanupPendingPairings(options = {}) { + var _a, _b, _c, _d, _e, _f, _g, _h; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + return; + } + try { + const inactivePairings = (_c = (_b = (_a = this.walletConnector.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.pairings) === null || _c === void 0 ? void 0 : _c.getAll({ active: false }); + if (!utils_1.isValidArray(inactivePairings)) { + return; + } + for (const pairing of inactivePairings) { + if (options.deletePairings) { + (_e = (_d = this.walletConnector.core) === null || _d === void 0 ? void 0 : _d.expirer) === null || _e === void 0 ? void 0 : _e.set(pairing.topic, 0); + } else { + try { + yield (_h = (_g = (_f = this.walletConnector.core) === null || _f === void 0 ? void 0 : _f.relayer) === null || _g === void 0 ? void 0 : _g.subscriber) === null || _h === void 0 ? void 0 : _h.unsubscribe(pairing.topic); + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); + } + } + } + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); + } + }); + } + }; + exports2.WalletConnectV2Provider = WalletConnectV2Provider5; + } +}); + +// node_modules/has-symbols/shams.js +var require_shams = __commonJS({ + "node_modules/has-symbols/shams.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function hasSymbols() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/has-symbols/index.js +var require_has_symbols = __commonJS({ + "node_modules/has-symbols/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = require_shams(); + module2.exports = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + } +}); + +// node_modules/has-proto/index.js +var require_has_proto = __commonJS({ + "node_modules/has-proto/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var test = { + foo: {} + }; + var $Object = Object; + module2.exports = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); + }; + } +}); + +// node_modules/function-bind/implementation.js +var require_implementation = __commonJS({ + "node_modules/function-bind/implementation.js"(exports2, module2) { + "use strict"; + init_shim(); + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a3, b4) { + var arr = []; + for (var i2 = 0; i2 < a3.length; i2 += 1) { + arr[i2] = a3[i2]; + } + for (var j2 = 0; j2 < b4.length; j2 += 1) { + arr[j2 + a3.length] = b4[j2]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i2 = offset || 0, j2 = 0; i2 < arrLike.length; i2 += 1, j2 += 1) { + arr[j2] = arrLike[i2]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i2 = 0; i2 < arr.length; i2 += 1) { + str += arr[i2]; + if (i2 + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + module2.exports = function bind(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i2 = 0; i2 < boundLength; i2++) { + boundArgs[i2] = "$" + i2; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + } +}); + +// node_modules/function-bind/index.js +var require_function_bind = __commonJS({ + "node_modules/function-bind/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var implementation = require_implementation(); + module2.exports = Function.prototype.bind || implementation; + } +}); + +// node_modules/hasown/index.js +var require_hasown = __commonJS({ + "node_modules/hasown/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind = require_function_bind(); + module2.exports = bind.call(call, $hasOwn); + } +}); + +// node_modules/get-intrinsic/index.js +var require_get_intrinsic = __commonJS({ + "node_modules/get-intrinsic/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var undefined2; + var $SyntaxError = SyntaxError; + var $Function = Function; + var $TypeError = TypeError; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e2) { + } + }; + var $gOPD = Object.getOwnPropertyDescriptor; + if ($gOPD) { + try { + $gOPD({}, ""); + } catch (e2) { + $gOPD = null; + } + } + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }() : throwTypeError; + var hasSymbols = require_has_symbols()(); + var hasProto = require_has_proto()(); + var getProto = Object.getPrototypeOf || (hasProto ? function(x3) { + return x3.__proto__; + } : null); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); + var INTRINSICS = { + "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, + "%AsyncFromSyncIteratorPrototype%": undefined2, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": EvalError, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, + "%JSON%": typeof JSON === "object" ? JSON : undefined2, + "%Map%": typeof Map === "undefined" ? undefined2 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": Object, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, + "%RangeError%": RangeError, + "%ReferenceError%": ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined2 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, + "%Symbol%": hasSymbols ? Symbol : undefined2, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, + "%URIError%": URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet + }; + if (getProto) { + try { + null.error; + } catch (e2) { + errorProto = getProto(getProto(e2)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var errorProto; + var doEval = function doEval2(name2) { + var value; + if (name2 === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name2 === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name2 === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name2 === "%AsyncGenerator%") { + var fn = doEval2("%AsyncGeneratorFunction%"); + if (fn) { + value = fn.prototype; + } + } else if (name2 === "%AsyncIteratorPrototype%") { + var gen = doEval2("%AsyncGenerator%"); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + INTRINSICS[name2] = value; + return value; + }; + var LEGACY_ALIASES = { + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind = require_function_bind(); + var hasOwn = require_hasown(); + var $concat = bind.call(Function.call, Array.prototype.concat); + var $spliceApply = bind.call(Function.apply, Array.prototype.splice); + var $replace = bind.call(Function.call, String.prototype.replace); + var $strSlice = bind.call(Function.call, String.prototype.slice); + var $exec = bind.call(Function.call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string2) { + var first = $strSlice(string2, 0, 1); + var last = $strSlice(string2, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string2, rePropName, function(match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) { + var intrinsicName = name2; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name2 + " does not exist!"); + }; + module2.exports = function GetIntrinsic(name2, allowMissing) { + if (typeof name2 !== "string" || name2.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name2) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name2); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i2 = 1, isOwn = true; i2 < parts.length; i2 += 1) { + var part = parts[i2]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available."); + } + return void 0; + } + if ($gOPD && i2 + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + } +}); + +// node_modules/has-property-descriptors/index.js +var require_has_property_descriptors = __commonJS({ + "node_modules/has-property-descriptors/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasPropertyDescriptors = function hasPropertyDescriptors2() { + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + return true; + } catch (e2) { + return false; + } + } + return false; + }; + hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + if (!hasPropertyDescriptors()) { + return null; + } + try { + return $defineProperty([], "length", { value: 1 }).length !== 1; + } catch (e2) { + return true; + } + }; + module2.exports = hasPropertyDescriptors; + } +}); + +// node_modules/gopd/index.js +var require_gopd = __commonJS({ + "node_modules/gopd/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e2) { + $gOPD = null; + } + } + module2.exports = $gOPD; + } +}); + +// node_modules/define-data-property/index.js +var require_define_data_property = __commonJS({ + "node_modules/define-data-property/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var hasPropertyDescriptors = require_has_property_descriptors()(); + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = hasPropertyDescriptors && GetIntrinsic("%Object.defineProperty%", true); + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e2) { + $defineProperty = false; + } + } + var $SyntaxError = GetIntrinsic("%SyntaxError%"); + var $TypeError = GetIntrinsic("%TypeError%"); + var gopd = require_gopd(); + module2.exports = function defineDataProperty(obj, property, value) { + if (!obj || typeof obj !== "object" && typeof obj !== "function") { + throw new $TypeError("`obj` must be an object or a function`"); + } + if (typeof property !== "string" && typeof property !== "symbol") { + throw new $TypeError("`property` must be a string or a symbol`"); + } + if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) { + throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null"); + } + if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) { + throw new $TypeError("`nonWritable`, if provided, must be a boolean or null"); + } + if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) { + throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null"); + } + if (arguments.length > 6 && typeof arguments[6] !== "boolean") { + throw new $TypeError("`loose`, if provided, must be a boolean"); + } + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + var desc = !!gopd && gopd(obj, property); + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) { + obj[property] = value; + } else { + throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable."); + } + }; + } +}); + +// node_modules/set-function-length/index.js +var require_set_function_length = __commonJS({ + "node_modules/set-function-length/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var define2 = require_define_data_property(); + var hasDescriptors = require_has_property_descriptors()(); + var gOPD = require_gopd(); + var $TypeError = GetIntrinsic("%TypeError%"); + var $floor = GetIntrinsic("%Math.floor%"); + module2.exports = function setFunctionLength(fn, length2) { + if (typeof fn !== "function") { + throw new $TypeError("`fn` is not a function"); + } + if (typeof length2 !== "number" || length2 < 0 || length2 > 4294967295 || $floor(length2) !== length2) { + throw new $TypeError("`length` must be a positive 32-bit integer"); + } + var loose = arguments.length > 2 && !!arguments[2]; + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ("length" in fn && gOPD) { + var desc = gOPD(fn, "length"); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define2( + /** @type {Parameters[0]} */ + fn, + "length", + length2, + true, + true + ); + } else { + define2( + /** @type {Parameters[0]} */ + fn, + "length", + length2 + ); + } + } + return fn; + }; + } +}); + +// node_modules/call-bind/index.js +var require_call_bind = __commonJS({ + "node_modules/call-bind/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var bind = require_function_bind(); + var GetIntrinsic = require_get_intrinsic(); + var setFunctionLength = require_set_function_length(); + var $TypeError = GetIntrinsic("%TypeError%"); + var $apply = GetIntrinsic("%Function.prototype.apply%"); + var $call = GetIntrinsic("%Function.prototype.call%"); + var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind.call($call, $apply); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var $max = GetIntrinsic("%Math.max%"); + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e2) { + $defineProperty = null; + } + } + module2.exports = function callBind(originalFunction) { + if (typeof originalFunction !== "function") { + throw new $TypeError("a function is required"); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); + }; + var applyBind = function applyBind2() { + return $reflectApply(bind, $apply, arguments); + }; + if ($defineProperty) { + $defineProperty(module2.exports, "apply", { value: applyBind }); + } else { + module2.exports.apply = applyBind; + } + } +}); + +// node_modules/call-bind/callBound.js +var require_callBound = __commonJS({ + "node_modules/call-bind/callBound.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var callBind = require_call_bind(); + var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf")); + module2.exports = function callBoundIntrinsic(name2, allowMissing) { + var intrinsic = GetIntrinsic(name2, !!allowMissing); + if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) { + return callBind(intrinsic); + } + return intrinsic; + }; + } +}); + +// (disabled):node_modules/object-inspect/util.inspect +var require_util2 = __commonJS({ + "(disabled):node_modules/object-inspect/util.inspect"() { + init_shim(); + } +}); + +// node_modules/object-inspect/index.js +var require_object_inspect = __commonJS({ + "node_modules/object-inspect/index.js"(exports2, module2) { + init_shim(); + var hasMap = typeof Map === "function" && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === "function" && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; + var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O3) { + return O3.__proto__; + } : null); + function addNumericSeparator(num, str) { + if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === "number") { + var int = num < 0 ? -$floor(-num) : $floor(num); + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); + } + } + return $replace.call(str, sepRegex, "$&_"); + } + var utilInspect = require_util2(); + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + module2.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, "customInspect") ? opts.customInspect : true; + if (typeof customInspect !== "boolean" && customInspect !== "symbol") { + throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); + } + if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + if (typeof obj === "boolean") { + return obj ? "true" : "false"; + } + if (typeof obj === "string") { + return inspectString(obj, opts); + } + if (typeof obj === "number") { + if (obj === 0) { + return Infinity / obj > 0 ? "0" : "-0"; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === "bigint") { + var bigIntStr = String(obj) + "n"; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; + if (typeof depth === "undefined") { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { + return isArray(obj) ? "[Array]" : "[Object]"; + } + var indent = getIndent(opts, depth); + if (typeof seen === "undefined") { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return "[Circular]"; + } + function inspect(value, from3, noIndent) { + if (from3) { + seen = $arrSlice.call(seen); + seen.push(from3); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, "quoteStyle")) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === "function" && !isRegExp(obj)) { + var name2 = nameOf(obj); + var keys2 = arrObjKeys(obj, inspect); + return "[Function" + (name2 ? ": " + name2 : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : ""); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); + return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s2 = "<" + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i2 = 0; i2 < attrs.length; i2++) { + s2 += " " + attrs[i2].name + "=" + wrapQuotes(quote(attrs[i2].value), "double", opts); + } + s2 += ">"; + if (obj.childNodes && obj.childNodes.length) { + s2 += "..."; + } + s2 += ""; + return s2; + } + if (isArray(obj)) { + if (obj.length === 0) { + return "[]"; + } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return "[" + indentedJoin(xs, indent) + "]"; + } + return "[ " + $join.call(xs, ", ") + " ]"; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { + return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; + } + if (parts.length === 0) { + return "[" + String(obj) + "]"; + } + return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; + } + if (typeof obj === "object" && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function(value, key) { + mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); + }); + } + return collectionOf("Map", mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function(value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf("Set", setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf("WeakMap"); + } + if (isWeakSet(obj)) { + return weakCollectionOf("WeakSet"); + } + if (isWeakRef(obj)) { + return weakCollectionOf("WeakRef"); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString2(obj)) { + return markBoxed(inspect(String(obj))); + } + if (typeof window !== "undefined" && obj === window) { + return "{ [object Window] }"; + } + if (obj === global) { + return "{ [object globalThis] }"; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? "" : "null prototype"; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; + var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; + var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); + if (ys.length === 0) { + return tag + "{}"; + } + if (indent) { + return tag + "{" + indentedJoin(ys, indent) + "}"; + } + return tag + "{ " + $join.call(ys, ", ") + " }"; + } + return String(obj); + }; + function wrapQuotes(s2, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'"; + return quoteChar + s2 + quoteChar; + } + function quote(s2) { + return $replace.call(String(s2), /"/g, """); + } + function isArray(obj) { + return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isDate(obj) { + return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isRegExp(obj) { + return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isError(obj) { + return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isString2(obj) { + return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isNumber(obj) { + return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isBoolean(obj) { + return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === "object" && obj instanceof Symbol; + } + if (typeof obj === "symbol") { + return true; + } + if (!obj || typeof obj !== "object" || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e2) { + } + return false; + } + function isBigInt(obj) { + if (!obj || typeof obj !== "object" || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e2) { + } + return false; + } + var hasOwn = Object.prototype.hasOwnProperty || function(key) { + return key in this; + }; + function has(obj, key) { + return hasOwn.call(obj, key); + } + function toStr(obj) { + return objectToString.call(obj); + } + function nameOf(f4) { + if (f4.name) { + return f4.name; + } + var m3 = $match.call(functionToString.call(f4), /^function\s*([\w$]+)/); + if (m3) { + return m3[1]; + } + return null; + } + function indexOf(xs, x3) { + if (xs.indexOf) { + return xs.indexOf(x3); + } + for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { + if (xs[i2] === x3) { + return i2; + } + } + return -1; + } + function isMap(x3) { + if (!mapSize || !x3 || typeof x3 !== "object") { + return false; + } + try { + mapSize.call(x3); + try { + setSize.call(x3); + } catch (s2) { + return true; + } + return x3 instanceof Map; + } catch (e2) { + } + return false; + } + function isWeakMap(x3) { + if (!weakMapHas || !x3 || typeof x3 !== "object") { + return false; + } + try { + weakMapHas.call(x3, weakMapHas); + try { + weakSetHas.call(x3, weakSetHas); + } catch (s2) { + return true; + } + return x3 instanceof WeakMap; + } catch (e2) { + } + return false; + } + function isWeakRef(x3) { + if (!weakRefDeref || !x3 || typeof x3 !== "object") { + return false; + } + try { + weakRefDeref.call(x3); + return true; + } catch (e2) { + } + return false; + } + function isSet(x3) { + if (!setSize || !x3 || typeof x3 !== "object") { + return false; + } + try { + setSize.call(x3); + try { + mapSize.call(x3); + } catch (m3) { + return true; + } + return x3 instanceof Set; + } catch (e2) { + } + return false; + } + function isWeakSet(x3) { + if (!weakSetHas || !x3 || typeof x3 !== "object") { + return false; + } + try { + weakSetHas.call(x3, weakSetHas); + try { + weakMapHas.call(x3, weakMapHas); + } catch (s2) { + return true; + } + return x3 instanceof WeakSet; + } catch (e2) { + } + return false; + } + function isElement(x3) { + if (!x3 || typeof x3 !== "object") { + return false; + } + if (typeof HTMLElement !== "undefined" && x3 instanceof HTMLElement) { + return true; + } + return typeof x3.nodeName === "string" && typeof x3.getAttribute === "function"; + } + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var s2 = $replace.call($replace.call(str, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s2, "single", opts); + } + function lowbyte(c4) { + var n3 = c4.charCodeAt(0); + var x3 = { + 8: "b", + 9: "t", + 10: "n", + 12: "f", + 13: "r" + }[n3]; + if (x3) { + return "\\" + x3; + } + return "\\x" + (n3 < 16 ? "0" : "") + $toUpperCase.call(n3.toString(16)); + } + function markBoxed(str) { + return "Object(" + str + ")"; + } + function weakCollectionOf(type) { + return type + " { ? }"; + } + function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); + return type + " (" + size + ") {" + joinedEntries + "}"; + } + function singleLineValues(xs) { + for (var i2 = 0; i2 < xs.length; i2++) { + if (indexOf(xs[i2], "\n") >= 0) { + return false; + } + } + return true; + } + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === " ") { + baseIndent = " "; + } else if (typeof opts.indent === "number" && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), " "); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + function indentedJoin(xs, indent) { + if (xs.length === 0) { + return ""; + } + var lineJoiner = "\n" + indent.prev + indent.base; + return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; + } + function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i2 = 0; i2 < obj.length; i2++) { + xs[i2] = has(obj, i2) ? inspect(obj[i2], obj) : ""; + } + } + var syms = typeof gOPS === "function" ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k4 = 0; k4 < syms.length; k4++) { + symMap["$" + syms[k4]] = syms[k4]; + } + } + for (var key in obj) { + if (!has(obj, key)) { + continue; + } + if (isArr && String(Number(key)) === key && key < obj.length) { + continue; + } + if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { + continue; + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); + } else { + xs.push(key + ": " + inspect(obj[key], obj)); + } + } + if (typeof gOPS === "function") { + for (var j2 = 0; j2 < syms.length; j2++) { + if (isEnumerable.call(obj, syms[j2])) { + xs.push("[" + inspect(syms[j2]) + "]: " + inspect(obj[syms[j2]], obj)); + } + } + } + return xs; + } + } +}); + +// node_modules/side-channel/index.js +var require_side_channel = __commonJS({ + "node_modules/side-channel/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var callBound = require_callBound(); + var inspect = require_object_inspect(); + var $TypeError = GetIntrinsic("%TypeError%"); + var $WeakMap = GetIntrinsic("%WeakMap%", true); + var $Map = GetIntrinsic("%Map%", true); + var $weakMapGet = callBound("WeakMap.prototype.get", true); + var $weakMapSet = callBound("WeakMap.prototype.set", true); + var $weakMapHas = callBound("WeakMap.prototype.has", true); + var $mapGet = callBound("Map.prototype.get", true); + var $mapSet = callBound("Map.prototype.set", true); + var $mapHas = callBound("Map.prototype.has", true); + var listGetNode = function(list, key) { + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; + return curr; + } + } + }; + var listGet = function(objects, key) { + var node = listGetNode(objects, key); + return node && node.value; + }; + var listSet = function(objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + objects.next = { + // eslint-disable-line no-param-reassign + key, + next: objects.next, + value + }; + } + }; + var listHas = function(objects, key) { + return !!listGetNode(objects, key); + }; + module2.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + get: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { + return listGet($o, key); + } + } + }, + has: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { + return listHas($o, key); + } + } + return false; + }, + set: function(key, value) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; + }; + } +}); + +// node_modules/qs/lib/formats.js +var require_formats = __commonJS({ + "node_modules/qs/lib/formats.js"(exports2, module2) { + "use strict"; + init_shim(); + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + var Format = { + RFC1738: "RFC1738", + RFC3986: "RFC3986" + }; + module2.exports = { + "default": Format.RFC3986, + formatters: { + RFC1738: function(value) { + return replace.call(value, percentTwenties, "+"); + }, + RFC3986: function(value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + } +}); + +// node_modules/qs/lib/utils.js +var require_utils5 = __commonJS({ + "node_modules/qs/lib/utils.js"(exports2, module2) { + "use strict"; + init_shim(); + var formats = require_formats(); + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + var hexTable = function() { + var array = []; + for (var i2 = 0; i2 < 256; ++i2) { + array.push("%" + ((i2 < 16 ? "0" : "") + i2.toString(16)).toUpperCase()); + } + return array; + }(); + var compactQueue = function compactQueue2(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + if (isArray(obj)) { + var compacted = []; + for (var j2 = 0; j2 < obj.length; ++j2) { + if (typeof obj[j2] !== "undefined") { + compacted.push(obj[j2]); + } + } + item.obj[item.prop] = compacted; + } + } + }; + var arrayToObject = function arrayToObject2(source, options) { + var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + for (var i2 = 0; i2 < source.length; ++i2) { + if (typeof source[i2] !== "undefined") { + obj[i2] = source[i2]; + } + } + return obj; + }; + var merge = function merge2(target, source, options) { + if (!source) { + return target; + } + if (typeof source !== "object") { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === "object") { + if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + return target; + } + if (!target || typeof target !== "object") { + return [target].concat(source); + } + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + if (isArray(target) && isArray(source)) { + source.forEach(function(item, i2) { + if (has.call(target, i2)) { + var targetItem = target[i2]; + if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { + target[i2] = merge2(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i2] = item; + } + }); + return target; + } + return Object.keys(source).reduce(function(acc, key) { + var value = source[key]; + if (has.call(acc, key)) { + acc[key] = merge2(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); + }; + var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function(acc, key) { + acc[key] = source[key]; + return acc; + }, target); + }; + var decode6 = function(str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, " "); + if (charset === "iso-8859-1") { + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + try { + return decodeURIComponent(strWithoutPlus); + } catch (e2) { + return strWithoutPlus; + } + }; + var encode5 = function encode6(str, defaultEncoder, charset, kind, format) { + if (str.length === 0) { + return str; + } + var string2 = str; + if (typeof str === "symbol") { + string2 = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string2 = String(str); + } + if (charset === "iso-8859-1") { + return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + var out = ""; + for (var i2 = 0; i2 < string2.length; ++i2) { + var c4 = string2.charCodeAt(i2); + if (c4 === 45 || c4 === 46 || c4 === 95 || c4 === 126 || c4 >= 48 && c4 <= 57 || c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122 || format === formats.RFC1738 && (c4 === 40 || c4 === 41)) { + out += string2.charAt(i2); + continue; + } + if (c4 < 128) { + out = out + hexTable[c4]; + continue; + } + if (c4 < 2048) { + out = out + (hexTable[192 | c4 >> 6] + hexTable[128 | c4 & 63]); + continue; + } + if (c4 < 55296 || c4 >= 57344) { + out = out + (hexTable[224 | c4 >> 12] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]); + continue; + } + i2 += 1; + c4 = 65536 + ((c4 & 1023) << 10 | string2.charCodeAt(i2) & 1023); + out += hexTable[240 | c4 >> 18] + hexTable[128 | c4 >> 12 & 63] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]; + } + return out; + }; + var compact = function compact2(value) { + var queue = [{ obj: { o: value }, prop: "o" }]; + var refs = []; + for (var i2 = 0; i2 < queue.length; ++i2) { + var item = queue[i2]; + var obj = item.obj[item.prop]; + var keys2 = Object.keys(obj); + for (var j2 = 0; j2 < keys2.length; ++j2) { + var key = keys2[j2]; + var val = obj[key]; + if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj, prop: key }); + refs.push(val); + } + } + } + compactQueue(queue); + return value; + }; + var isRegExp = function isRegExp2(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; + }; + var isBuffer = function isBuffer2(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + }; + var combine = function combine2(a3, b4) { + return [].concat(a3, b4); + }; + var maybeMap = function maybeMap2(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i2 = 0; i2 < val.length; i2 += 1) { + mapped.push(fn(val[i2])); + } + return mapped; + } + return fn(val); + }; + module2.exports = { + arrayToObject, + assign, + combine, + compact, + decode: decode6, + encode: encode5, + isBuffer, + isRegExp, + maybeMap, + merge + }; + } +}); + +// node_modules/qs/lib/stringify.js +var require_stringify2 = __commonJS({ + "node_modules/qs/lib/stringify.js"(exports2, module2) { + "use strict"; + init_shim(); + var getSideChannel = require_side_channel(); + var utils = require_utils5(); + var formats = require_formats(); + var has = Object.prototype.hasOwnProperty; + var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + "[]"; + }, + comma: "comma", + indices: function indices(prefix, key) { + return prefix + "[" + key + "]"; + }, + repeat: function repeat(prefix) { + return prefix; + } + }; + var isArray = Array.isArray; + var split = String.prototype.split; + var push = Array.prototype.push; + var pushToArray = function(arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); + }; + var toISO = Date.prototype.toISOString; + var defaultFormat = formats["default"]; + var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false + }; + var isNonNullishPrimitive = function isNonNullishPrimitive2(v2) { + return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean" || typeof v2 === "symbol" || typeof v2 === "bigint"; + }; + var sentinel = {}; + var stringify2 = function stringify3(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + var obj = object; + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + findFlag = true; + } + } + if (typeof tmpSc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = utils.maybeMap(obj, function(value2) { + if (value2 instanceof Date) { + return serializeDate(value2); + } + return value2; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; + } + obj = ""; + } + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + if (generateArrayPrefix === "comma" && encodeValuesOnly) { + var valuesArray = split.call(String(obj), ","); + var valuesJoined = ""; + for (var i2 = 0; i2 < valuesArray.length; ++i2) { + valuesJoined += (i2 === 0 ? "" : ",") + formatter(encoder(valuesArray[i2], defaults.encoder, charset, "value", format)); + } + return [formatter(keyValue) + "=" + valuesJoined]; + } + return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults.encoder, charset, "value", format))]; + } + return [formatter(prefix) + "=" + formatter(String(obj))]; + } + var values = []; + if (typeof obj === "undefined") { + return values; + } + var objKeys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys2 = Object.keys(obj); + objKeys = sort ? keys2.sort(sort) : keys2; + } + for (var j2 = 0; j2 < objKeys.length; ++j2) { + var key = objKeys[j2]; + var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; + } + var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? "." + key : "[" + key + "]"); + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify3( + value, + keyPrefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; + }; + var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { + if (!opts) { + return defaults; + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var format = formats["default"]; + if (typeof opts.format !== "undefined") { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + var filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + module2.exports = function(object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + var objKeys; + var filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + var keys2 = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && "indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = "indices"; + } + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (!objKeys) { + objKeys = Object.keys(obj); + } + if (options.sort) { + objKeys.sort(options.sort); + } + var sideChannel = getSideChannel(); + for (var i2 = 0; i2 < objKeys.length; ++i2) { + var key = objKeys[i2]; + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys2, stringify2( + obj[key], + key, + generateArrayPrefix, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + var joined = keys2.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; + }; + } +}); + +// node_modules/qs/lib/parse.js +var require_parse2 = __commonJS({ + "node_modules/qs/lib/parse.js"(exports2, module2) { + "use strict"; + init_shim(); + var utils = require_utils5(); + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: "utf-8", + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: "&", + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1e3, + parseArrays: true, + plainObjects: false, + strictNullHandling: false + }; + var interpretNumericEntities = function(str) { + return str.replace(/&#(\d+);/g, function($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); + }; + var parseArrayValue = function(val, options) { + if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { + return val.split(","); + } + return val; + }; + var isoSentinel = "utf8=%26%2310003%3B"; + var charsetSentinel = "utf8=%E2%9C%93"; + var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; + var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; + var i2; + var charset = options.charset; + if (options.charsetSentinel) { + for (i2 = 0; i2 < parts.length; ++i2) { + if (parts[i2].indexOf("utf8=") === 0) { + if (parts[i2] === charsetSentinel) { + charset = "utf-8"; + } else if (parts[i2] === isoSentinel) { + charset = "iso-8859-1"; + } + skipIndex = i2; + i2 = parts.length; + } + } + } + for (i2 = 0; i2 < parts.length; ++i2) { + if (i2 === skipIndex) { + continue; + } + var part = parts[i2]; + var bracketEqualsPos = part.indexOf("]="); + var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, "key"); + val = options.strictNullHandling ? null : ""; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function(encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, "value"); + } + ); + } + if (val && options.interpretNumericEntities && charset === "iso-8859-1") { + val = interpretNumericEntities(val); + } + if (part.indexOf("[]=") > -1) { + val = isArray(val) ? [val] : val; + } + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + return obj; + }; + var parseObject = function(chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + for (var i2 = chain.length - 1; i2 >= 0; --i2) { + var obj; + var root = chain[i2]; + if (root === "[]" && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === "") { + obj = { 0: leaf }; + } else if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== "__proto__") { + obj[cleanRoot] = leaf; + } + } + leaf = obj; + } + return leaf; + }; + var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + var keys2 = []; + if (parent) { + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + keys2.push(parent); + } + var i2 = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i2 < options.depth) { + i2 += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys2.push(segment[1]); + } + if (segment) { + keys2.push("[" + key.slice(segment.index) + "]"); + } + return parseObject(keys2, val, options, valuesParsed); + }; + var normalizeParseOptions = function normalizeParseOptions2(opts) { + if (!opts) { + return defaults; + } + if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") { + throw new TypeError("Decoder has to be a function."); + } + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; + return { + allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + module2.exports = function(str, opts) { + var options = normalizeParseOptions(opts); + if (str === "" || str === null || typeof str === "undefined") { + return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + } + var tempObj = typeof str === "string" ? parseValues(str, options) : str; + var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + var keys2 = Object.keys(tempObj); + for (var i2 = 0; i2 < keys2.length; ++i2) { + var key = keys2[i2]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); + obj = utils.merge(obj, newObj, options); + } + if (options.allowSparse === true) { + return obj; + } + return utils.compact(obj); + }; + } +}); + +// node_modules/qs/lib/index.js +var require_lib = __commonJS({ + "node_modules/qs/lib/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var stringify2 = require_stringify2(); + var parse = require_parse2(); + var formats = require_formats(); + module2.exports = { + formats, + parse, + stringify: stringify2 + }; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js +var require_constants7 = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = exports2.WALLET_PROVIDER_CALLBACK_PARAM = exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = exports2.WALLET_PROVIDER_DISCONNECT_URL = exports2.WALLET_PROVIDER_CONNECT_URL = exports2.XALIAS_PROVIDER_TESTNET = exports2.XALIAS_PROVIDER_DEVNET = exports2.XALIAS_PROVIDER_MAINNET = exports2.WALLET_PROVIDER_TESTNET = exports2.WALLET_PROVIDER_DEVNET = exports2.WALLET_PROVIDER_MAINNET = void 0; + exports2.WALLET_PROVIDER_MAINNET = "https://wallet.multiversx.com/dapp/init"; + exports2.WALLET_PROVIDER_DEVNET = "https://devnet-wallet.multiversx.com/dapp/init"; + exports2.WALLET_PROVIDER_TESTNET = "https://testnet-wallet.multiversx.com/dapp/init"; + exports2.XALIAS_PROVIDER_MAINNET = "https://xalias.com"; + exports2.XALIAS_PROVIDER_DEVNET = "https://devnet.xalias.com"; + exports2.XALIAS_PROVIDER_TESTNET = "https://testnet.xalias.com"; + exports2.WALLET_PROVIDER_CONNECT_URL = "hook/login"; + exports2.WALLET_PROVIDER_DISCONNECT_URL = "hook/logout"; + exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = "hook/transaction"; + exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = "hook/sign"; + exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = "hook/2fa"; + exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = "hook/sign-message"; + exports2.WALLET_PROVIDER_CALLBACK_PARAM = "walletProviderStatus"; + exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = "transactionsSigned"; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js +var require_errors4 = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrCannotSignedMessage = exports2.ErrCannotGetSignedTransactions = void 0; + var ErrCannotGetSignedTransactions = class extends Error { + constructor() { + super("Cannot get signed transaction(s)"); + } + }; + exports2.ErrCannotGetSignedTransactions = ErrCannotGetSignedTransactions; + var ErrCannotSignedMessage = class extends Error { + constructor() { + super("Cannot get signed message"); + } + }; + exports2.ErrCannotSignedMessage = ErrCannotSignedMessage; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js +var require_plainSignedTransaction = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PlainSignedTransaction = void 0; + var PlainSignedTransaction = class { + constructor(init) { + this.nonce = 0; + this.value = ""; + this.receiver = ""; + this.sender = ""; + this.gasPrice = 0; + this.gasLimit = 0; + this.data = ""; + this.chainID = ""; + this.version = 0; + this.signature = ""; + Object.assign(this, init); + } + }; + exports2.PlainSignedTransaction = PlainSignedTransaction; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js +var require_walletProvider = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WalletProvider = void 0; + var qs_1 = __importDefault2(require_lib()); + var constants_1 = require_constants7(); + var errors_1 = require_errors4(); + var plainSignedTransaction_1 = require_plainSignedTransaction(); + var WalletProvider6 = class _WalletProvider { + /** + * Creates a new WalletProvider + * @param walletURL + */ + constructor(walletURL) { + this.walletUrl = walletURL; + } + /** + * Fetches the login hook url and redirects the client to the wallet login. + */ + login(options) { + return __awaiter2(this, void 0, void 0, function* () { + const redirectUrl = this.buildWalletUrl({ + endpoint: constants_1.WALLET_PROVIDER_CONNECT_URL, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, + params: { + token: options === null || options === void 0 ? void 0 : options.token + } + }); + yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); + return redirectUrl; + }); + } + redirect(url, delayMilliseconds) { + return __awaiter2(this, void 0, void 0, function* () { + if (delayMilliseconds) { + yield this.redirectLater(url, delayMilliseconds); + } else { + this.redirectImmediately(url); + } + }); + } + redirectImmediately(url) { + window.location.href = url; + } + redirectLater(url, delayMilliseconds) { + return __awaiter2(this, void 0, void 0, function* () { + yield new Promise((resolve) => { + setTimeout(() => { + window.location.href = url; + resolve(true); + }, delayMilliseconds); + }); + }); + } + /** + * Fetches the logout hook url and redirects the client to the wallet logout. + */ + logout(options) { + return __awaiter2(this, void 0, void 0, function* () { + const redirectUrl = this.buildWalletUrl({ + endpoint: constants_1.WALLET_PROVIDER_DISCONNECT_URL, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl + }); + yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); + return true; + }); + } + /** + * Packs a {@link SignMessage} and fetches correct redirect URL from the wallet API. Then redirects + * the client to the sign message hook + * @param message + * @param options + */ + signMessage(message, options) { + return __awaiter2(this, void 0, void 0, function* () { + const redirectUrl = this.buildWalletUrl({ + endpoint: constants_1.WALLET_PROVIDER_SIGN_MESSAGE_URL, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, + params: { + message: message.message.toString() + } + }); + yield this.redirect(redirectUrl); + return redirectUrl; + }); + } + getMessageSignatureFromWalletUrl() { + var _a, _b; + const url = window.location.search.slice(1); + console.info("getMessageSignatureFromWalletUrl(), url:", url); + const urlParams = qs_1.default.parse(url); + const status = ((_a = urlParams.status) === null || _a === void 0 ? void 0 : _a.toString()) || ""; + const expectedStatus = "signed"; + if (status !== expectedStatus) { + throw new errors_1.ErrCannotSignedMessage(); + } + const signature = ((_b = urlParams.signature) === null || _b === void 0 ? void 0 : _b.toString()) || ""; + return signature; + } + /** + * Packs an array of {$link Transaction} and redirects to the 2fa hook + * + * @param transactions + * @param options + */ + guardTransactions(transactions, options) { + return __awaiter2(this, void 0, void 0, function* () { + this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_GUARD_TRANSACTION_URL, transactions, options); + }); + } + /** + * Packs an array of {$link Transaction} and redirects to the correct transaction sigining hook + * + * @param transactions + * @param options + */ + signTransactions(transactions, options) { + return __awaiter2(this, void 0, void 0, function* () { + this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_SIGN_TRANSACTION_URL, transactions, options); + }); + } + /** + * Packs a {@link Transaction} and fetches correct redirect URL from the wallet API. Then redirects + * the client to the sign transaction hook + * @param transaction + * @param options + */ + signTransaction(transaction, options) { + return __awaiter2(this, void 0, void 0, function* () { + yield this.signTransactions([transaction], options); + }); + } + getTransactionsFromWalletUrl(search = window.location.search) { + const urlParams = qs_1.default.parse(search.slice(1)); + if (!_WalletProvider.isTxSignReturnSuccess(urlParams)) { + return []; + } + return this.getTxSignReturnValue(urlParams); + } + static isTxSignReturnSuccess(urlParams) { + return urlParams.hasOwnProperty(constants_1.WALLET_PROVIDER_CALLBACK_PARAM) && urlParams[constants_1.WALLET_PROVIDER_CALLBACK_PARAM] === constants_1.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED; + } + getTxSignReturnValue(urlParams) { + console.info("getTxSignReturnValue(), urlParams:", urlParams); + const expectedProps = [ + "nonce", + "value", + "receiver", + "sender", + "gasPrice", + "gasLimit", + "chainID", + "version", + "signature" + ]; + for (let txProp of expectedProps) { + if (!urlParams[txProp] || !Array.isArray(urlParams[txProp])) { + throw new errors_1.ErrCannotGetSignedTransactions(); + } + } + const expectedLength = urlParams["nonce"].length; + for (let txProp of expectedProps) { + if (urlParams[txProp].length !== expectedLength) { + throw new errors_1.ErrCannotGetSignedTransactions(); + } + } + const transactions = []; + for (let i2 = 0; i2 < expectedLength; i2++) { + let plainSignedTransaction = new plainSignedTransaction_1.PlainSignedTransaction(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ + nonce: parseInt(urlParams["nonce"][i2]), + value: urlParams["value"][i2], + receiver: urlParams["receiver"][i2], + sender: urlParams["sender"][i2], + gasPrice: parseInt(urlParams["gasPrice"][i2]), + gasLimit: parseInt(urlParams["gasLimit"][i2]), + // Handle the optional "data" property. + data: urlParams["data"] && urlParams["data"][i2] ? urlParams["data"][i2] : "", + chainID: urlParams["chainID"][i2], + version: parseInt(urlParams["version"][i2]) + }, urlParams["guardian"] && urlParams["guardian"][i2] ? { guardian: urlParams["guardian"][i2] } : {}), urlParams["guardianSignature"] && urlParams["guardianSignature"][i2] ? { guardianSignature: urlParams["guardianSignature"][i2] } : {}), urlParams["options"] && urlParams["options"][i2] ? { + options: parseInt(urlParams["options"][i2]) + } : {}), urlParams["senderUsername"] && urlParams["senderUsername"][i2] ? { senderUsername: urlParams["senderUsername"][i2] } : {}), urlParams["receiverUsername"] && urlParams["receiverUsername"][i2] ? { receiverUsername: urlParams["receiverUsername"][i2] } : {}), { signature: urlParams["signature"][i2] })); + transactions.push(plainSignedTransaction); + } + return transactions; + } + static prepareWalletTransaction(transaction) { + let plainTransaction = transaction.toPlainObject(); + if (plainTransaction.data) { + plainTransaction.data = import_buffer.Buffer.from(plainTransaction.data, "base64").toString(); + } else { + plainTransaction.data = ""; + } + return plainTransaction; + } + buildWalletUrl(options) { + const callbackUrl = (options === null || options === void 0 ? void 0 : options.callbackUrl) || window.location.href; + const partialQueryString = qs_1.default.stringify(options.params || {}); + const fullQueryString = partialQueryString ? `${partialQueryString}&callbackUrl=${callbackUrl}` : `callbackUrl=${callbackUrl}`; + const url = `${this.baseWalletUrl()}/${options.endpoint}?${fullQueryString}`; + console.info(`Redirecting to Wallet URL: ${decodeURI(url)}`); + return url; + } + baseWalletUrl() { + const pathArray = this.walletUrl.split("/"); + const protocol = pathArray[0]; + const host = pathArray[2]; + return protocol + "//" + host; + } + /** + * Packs an array of {$link Transaction} and redirects to the specified wallet hook + * + * @param transactions + * @param options + */ + redirectTransactionsToEndpoint(endpoint, transactions, options) { + const jsonToSend = {}; + transactions.map((tx) => { + let plainTx = _WalletProvider.prepareWalletTransaction(tx); + for (let txProp in plainTx) { + if (plainTx.hasOwnProperty(txProp) && !jsonToSend.hasOwnProperty(txProp)) { + jsonToSend[txProp] = []; + } + jsonToSend[txProp].push(plainTx[txProp]); + } + }); + const redirectUrl = this.buildWalletUrl({ + endpoint, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, + params: jsonToSend + }); + window.location.href = redirectUrl; + } + }; + exports2.WalletProvider = WalletProvider6; + } +}); + +// node_modules/axios/dist/browser/axios.cjs +var require_axios = __commonJS({ + "node_modules/axios/dist/browser/axios.cjs"(exports2, module2) { + "use strict"; + init_shim(); + function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; + } + var { toString: toString3 } = Object.prototype; + var { getPrototypeOf } = Object; + var kindOf = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString3.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + })(/* @__PURE__ */ Object.create(null)); + var kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type; + }; + var typeOfTest = (type) => (thing) => typeof thing === type; + var { isArray } = Array; + var isUndefined = typeOfTest("undefined"); + function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); + } + var isArrayBuffer = kindOfTest("ArrayBuffer"); + function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; + } + var isString2 = typeOfTest("string"); + var isFunction = typeOfTest("function"); + var isNumber = typeOfTest("number"); + var isObject = (thing) => thing !== null && typeof thing === "object"; + var isBoolean = (thing) => thing === true || thing === false; + var isPlainObject = (val) => { + if (kindOf(val) !== "object") { + return false; + } + const prototype2 = getPrototypeOf(val); + return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); + }; + var isDate = kindOfTest("Date"); + var isFile = kindOfTest("File"); + var isBlob = kindOfTest("Blob"); + var isFileList = kindOfTest("FileList"); + var isStream = (val) => isObject(val) && isFunction(val.pipe); + var isFormData = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); + }; + var isURLSearchParams = kindOfTest("URLSearchParams"); + var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); + function forEach(obj, fn, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i2; + let l4; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray(obj)) { + for (i2 = 0, l4 = obj.length; i2 < l4; i2++) { + fn.call(null, obj[i2], i2, obj); + } + } else { + const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys2.length; + let key; + for (i2 = 0; i2 < len; i2++) { + key = keys2[i2]; + fn.call(null, obj[key], key, obj); + } + } + } + function findKey(obj, key) { + key = key.toLowerCase(); + const keys2 = Object.keys(obj); + let i2 = keys2.length; + let _key; + while (i2-- > 0) { + _key = keys2[i2]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; + } + var _global = (() => { + if (typeof globalThis !== "undefined") + return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; + })(); + var isContextDefined = (context) => !isUndefined(context) && context !== _global; + function merge() { + const { caseless } = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i2 = 0, l4 = arguments.length; i2 < l4; i2++) { + arguments[i2] && forEach(arguments[i2], assignValue); + } + return result; + } + var extend = (a3, b4, thisArg, { allOwnKeys } = {}) => { + forEach(b4, (val, key) => { + if (thisArg && isFunction(val)) { + a3[key] = bind(val, thisArg); + } else { + a3[key] = val; + } + }, { allOwnKeys }); + return a3; + }; + var stripBOM = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); + } + return content; + }; + var inherits = (constructor, superConstructor, props, descriptors2) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors2); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); + }; + var toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i2; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) + return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i2 = props.length; + while (i2-- > 0) { + prop = props[i2]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; + }; + var endsWith = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + var toArray = (thing) => { + if (!thing) + return null; + if (isArray(thing)) + return thing; + let i2 = thing.length; + if (!isNumber(i2)) + return null; + const arr = new Array(i2); + while (i2-- > 0) { + arr[i2] = thing[i2]; + } + return arr; + }; + var isTypedArray = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; + })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); + var forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + const iterator = generator.call(obj); + let result; + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } + }; + var matchAll = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; + }; + var isHTMLForm = kindOfTest("HTMLFormElement"); + var toCamelCase = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m3, p1, p22) { + return p1.toUpperCase() + p22; + } + ); + }; + var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); + var isRegExp = kindOfTest("RegExp"); + var reduceDescriptors = (obj, reducer) => { + const descriptors2 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach(descriptors2, (descriptor, name2) => { + let ret; + if ((ret = reducer(descriptor, name2, obj)) !== false) { + reducedDescriptors[name2] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); + }; + var freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name2) => { + if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) { + return false; + } + const value = obj[name2]; + if (!isFunction(value)) + return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name2 + "'"); + }; + } + }); + }; + var toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + const define2 = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); + return obj; + }; + var noop = () => { + }; + var toFiniteNumber = (value, defaultValue) => { + value = +value; + return Number.isFinite(value) ? value : defaultValue; + }; + var ALPHA = "abcdefghijklmnopqrstuvwxyz"; + var DIGIT = "0123456789"; + var ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + }; + var generateString = (size = 16, alphabet2 = ALPHABET.ALPHA_DIGIT) => { + let str = ""; + const { length: length2 } = alphabet2; + while (size--) { + str += alphabet2[Math.random() * length2 | 0]; + } + return str; + }; + function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); + } + var toJSONObject = (obj) => { + const stack = new Array(10); + const visit = (source, i2) => { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i2] = source; + const target = isArray(source) ? [] : {}; + forEach(source, (value, key) => { + const reducedValue = visit(value, i2 + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i2] = void 0; + return target; + } + } + return source; + }; + return visit(obj, 0); + }; + var isAsyncFn = kindOfTest("AsyncFunction"); + var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + var utils$1 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString: isString2, + isNumber, + isBoolean, + isObject, + isPlainObject, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable + }; + function AxiosError(message, code2, config, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = "AxiosError"; + code2 && (this.code = code2); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); + } + utils$1.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; + } + }); + var prototype$1 = AxiosError.prototype; + var descriptors = {}; + [ + "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" + // eslint-disable-next-line func-names + ].forEach((code2) => { + descriptors[code2] = { value: code2 }; + }); + Object.defineProperties(AxiosError, descriptors); + Object.defineProperty(prototype$1, "isAxiosError", { value: true }); + AxiosError.from = (error, code2, config, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError.call(axiosError, error.message, code2, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + }; + var httpAdapter = null; + function isVisitable(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + } + function removeBrackets(key) { + return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; + } + function renderKey(path, key, dots) { + if (!path) + return key; + return path.concat(key).map(function each(token, i2) { + token = removeBrackets(token); + return !dots && i2 ? "[" + token + "]" : token; + }).join(dots ? "." : ""); + } + function isFlatArray(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable); + } + var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); + }); + function toFormData(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new FormData(); + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils$1.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) + return ""; + if (utils$1.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError("Blob is not supported. Use a Buffer instead."); + } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : import_buffer.Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils$1.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { + key = removeBrackets(key); + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", + convertValue(el) + ); + }); + return false; + } + } + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils$1.isUndefined(value)) + return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils$1.forEach(value, function each(el, key) { + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, + el, + utils$1.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils$1.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; + } + function encode$1(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); + } + function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData(params, this, options); + } + var prototype = AxiosURLSearchParams.prototype; + prototype.append = function append(name2, value) { + this._pairs.push([name2, value]); + }; + prototype.toString = function toString4(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); + }; + function encode5(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + } + function buildURL(url, params, options) { + if (!params) { + return url; + } + const _encode = options && options.encode || encode5; + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url; + } + var InterceptorManager = class { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h5) { + if (h5 !== null) { + fn(h5); + } + }); + } + }; + var InterceptorManager$1 = InterceptorManager; + var transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }; + var URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams; + var FormData$1 = typeof FormData !== "undefined" ? FormData : null; + var Blob$1 = typeof Blob !== "undefined" ? Blob : null; + var platform$1 = { + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: Blob$1 + }, + protocols: ["http", "https", "file", "blob", "url", "data"] + }; + var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; + var hasStandardBrowserEnv = ((product) => { + return hasBrowserEnv && ["ReactNative", "NativeScript", "NS"].indexOf(product) < 0; + })(typeof navigator !== "undefined" && navigator.product); + var hasStandardBrowserWebWorkerEnv = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; + })(); + var utils = /* @__PURE__ */ Object.freeze({ + __proto__: null, + hasBrowserEnv, + hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv + }); + var platform = { + ...utils, + ...platform$1 + }; + function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); + } + function parsePropPath(name2) { + return utils$1.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); + } + function arrayToObject(arr) { + const obj = {}; + const keys2 = Object.keys(arr); + let i2; + const len = keys2.length; + let key; + for (i2 = 0; i2 < len; i2++) { + key = keys2[i2]; + obj[key] = arr[key]; + } + return obj; + } + function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name2 = path[index++]; + if (name2 === "__proto__") + return true; + const isNumericKey = Number.isFinite(+name2); + const isLast = index >= path.length; + name2 = !name2 && utils$1.isArray(target) ? target.length : name2; + if (isLast) { + if (utils$1.hasOwnProp(target, name2)) { + target[name2] = [target[name2], value]; + } else { + target[name2] = value; + } + return !isNumericKey; + } + if (!target[name2] || !utils$1.isObject(target[name2])) { + target[name2] = []; + } + const result = buildPath(path, value, target[name2], index); + if (result && utils$1.isArray(target[name2])) { + target[name2] = arrayToObject(target[name2]); + } + return !isNumericKey; + } + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + utils$1.forEachEntry(formData, (name2, value) => { + buildPath(parsePropPath(name2), value, obj, 0); + }); + return obj; + } + return null; + } + function stringifySafely(rawValue, parser, encoder) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e2) { + if (e2.name !== "SyntaxError") { + throw e2; + } + } + } + return (encoder || JSON.stringify)(rawValue); + } + var defaults = { + transitional: transitionalDefaults, + adapter: ["xhr", "http"], + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils$1.isObject(data); + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData2 = utils$1.isFormData(data); + if (isFormData2) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data)) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList2; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData( + isFileList2 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely(data); + } + return data; + }], + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e2) { + if (strictJSONParsing) { + if (e2.name === "SyntaxError") { + throw AxiosError.from(e2, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e2; + } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 + } + } + }; + utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults.headers[method] = {}; + }); + var defaults$1 = defaults; + var ignoreDuplicateOf = utils$1.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" + ]); + var parseHeaders = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i2; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i2 = line.indexOf(":"); + key = line.substring(0, i2).trim().toLowerCase(); + val = line.substring(i2 + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; + }; + var $internals = Symbol("internals"); + function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); + } + function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); + } + function parseTokens(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; + } + var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils$1.isString(value)) + return; + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } + } + function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w4, char, str) => { + return char.toUpperCase() + str; + }); + } + function buildAccessors(obj, header) { + const accessorName = utils$1.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); + } + var AxiosHeaders = class { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils$1.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue(_value); + } + } + const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader(header); + if (header) { + const key = utils$1.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); + } + } + } + has(header, matcher) { + header = normalizeHeader(header); + if (header) { + const key = utils$1.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + const key = utils$1.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys2 = Object.keys(this); + let i2 = keys2.length; + let deleted = false; + while (i2--) { + const key = keys2[i2]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + if (key) { + self2[key] = normalizeValue(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals] = this[$internals] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype2 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype2, _header); + accessors[lHeader] = true; + } + } + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } + }; + AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); + utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; + }); + utils$1.freezeMethods(AxiosHeaders); + var AxiosHeaders$1 = AxiosHeaders; + function transformData(fns, response) { + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; + } + function isCancel(value) { + return !!(value && value.__CANCEL__); + } + function CanceledError(message, config, request) { + AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request); + this.name = "CanceledError"; + } + utils$1.inherits(CanceledError, AxiosError, { + __CANCEL__: true + }); + function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + "Request failed with status code " + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } + } + var cookies = platform.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name2, value, expires, path, domain, secure) { + const cookie = [name2 + "=" + encodeURIComponent(value)]; + utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils$1.isString(path) && cookie.push("path=" + path); + utils$1.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name2) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name2 + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name2) { + this.write(name2, "", Date.now() - 864e5); + } + } + ) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } + ); + function isAbsoluteURL(url) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); + } + function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; + } + function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; + } + var isURLSameOrigin = platform.hasStandardBrowserEnv ? ( + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + function standardBrowserEnv() { + const msie = /(msie|trident)/i.test(navigator.userAgent); + const urlParsingNode = document.createElement("a"); + let originURL; + function resolveURL(url) { + let href = url; + if (msie) { + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } + urlParsingNode.setAttribute("href", href); + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname + }; + } + originURL = resolveURL(window.location.href); + return function isURLSameOrigin2(requestURL) { + const parsed = utils$1.isString(requestURL) ? resolveURL(requestURL) : requestURL; + return parsed.protocol === originURL.protocol && parsed.host === originURL.host; + }; + }() + ) : ( + // Non standard browser envs (web workers, react-native) lack needed support. + /* @__PURE__ */ function nonStandardBrowserEnv() { + return function isURLSameOrigin2() { + return true; + }; + }() + ); + function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ""; + } + function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i2 = tail; + let bytesCount = 0; + while (i2 !== head) { + bytesCount += bytes[i2++]; + i2 = i2 % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; + } + function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + return (e2) => { + const loaded = e2.loaded; + const total = e2.lengthComputable ? e2.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange ? (total - loaded) / rate : void 0, + event: e2 + }; + data[isDownloadStream ? "download" : "upload"] = true; + listener(data); + }; + } + var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; + var xhrAdapter = isXHRAdapterSupported && function(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + let requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + let { responseType, withXSRFToken } = config; + let onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + if (config.signal) { + config.signal.removeEventListener("abort", onCanceled); + } + } + let contentType; + if (utils$1.isFormData(requestData)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); + } else if ((contentType = requestHeaders.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + requestHeaders.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + let request = new XMLHttpRequest(); + if (config.auth) { + const username = config.auth.username || ""; + const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; + requestHeaders.set("Authorization", "Basic " + btoa(username + ":" + password)); + } + const fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + request.timeout = config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders$1.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request)); + request = null; + }; + request.onerror = function handleError() { + reject(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request)); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request + )); + request = null; + }; + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(fullPath)) { + const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); + if (xsrfValue) { + requestHeaders.set(config.xsrfHeaderName, xsrfValue); + } + } + } + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils$1.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = config.responseType; + } + if (typeof config.onDownloadProgress === "function") { + request.addEventListener("progress", progressEventReducer(config.onDownloadProgress, true)); + } + if (typeof config.onUploadProgress === "function" && request.upload) { + request.upload.addEventListener("progress", progressEventReducer(config.onUploadProgress)); + } + if (config.cancelToken || config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol(fullPath); + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config)); + return; + } + request.send(requestData || null); + }); + }; + var knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter + }; + utils$1.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, "name", { value }); + } catch (e2) { + } + Object.defineProperty(fn, "adapterName", { value }); + } + }); + var renderReason = (reason) => `- ${reason}`; + var isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + var adapters = { + getAdapter: (adapters2) => { + adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; + const { length: length2 } = adapters2; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i2 = 0; i2 < length2; i2++) { + nameOrAdapter = adapters2[i2]; + let id; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } + if (adapter) { + break; + } + rejectedReasons[id || "#" + i2] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s2 = length2 ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s2, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters + }; + function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } + } + function dispatchRequest(config) { + throwIfCancellationRequested(config); + config.headers = AxiosHeaders$1.from(config.headers); + config.data = transformData.call( + config, + config.transformRequest + ); + if (["post", "put", "patch"].indexOf(config.method) !== -1) { + config.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + response.data = transformData.call( + config, + config.transformResponse, + response + ); + response.headers = AxiosHeaders$1.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); + } + var headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + function mergeConfig(config1, config2) { + config2 = config2 || {}; + const config = {}; + function getMergedValue(target, source, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({ caseless }, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a3, b4, caseless) { + if (!utils$1.isUndefined(b4)) { + return getMergedValue(a3, b4, caseless); + } else if (!utils$1.isUndefined(a3)) { + return getMergedValue(void 0, a3, caseless); + } + } + function valueFromConfig2(a3, b4) { + if (!utils$1.isUndefined(b4)) { + return getMergedValue(void 0, b4); + } + } + function defaultToConfig2(a3, b4) { + if (!utils$1.isUndefined(b4)) { + return getMergedValue(void 0, b4); + } else if (!utils$1.isUndefined(a3)) { + return getMergedValue(void 0, a3); + } + } + function mergeDirectKeys(a3, b4, prop) { + if (prop in config2) { + return getMergedValue(a3, b4); + } else if (prop in config1) { + return getMergedValue(void 0, a3); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a3, b4) => mergeDeepProperties(headersToObject(a3), headersToObject(b4), true) + }; + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge2 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge2(config1[prop], config2[prop], prop); + utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); + }); + return config; + } + var VERSION = "1.6.8"; + var validators$1 = {}; + ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => { + validators$1[type] = function validator2(thing) { + return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type; + }; + }); + var deprecatedWarnings = {}; + validators$1.transitional = function transitional(validator2, version2, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator2 === false) { + throw new AxiosError( + formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")), + AxiosError.ERR_DEPRECATED + ); + } + if (version2 && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version2 + " and will be removed in the near future" + ) + ); + } + return validator2 ? validator2(value, opt, opts) : true; + }; + }; + function assertOptions(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys2 = Object.keys(options); + let i2 = keys2.length; + while (i2-- > 0) { + const opt = keys2[i2]; + const validator2 = schema[opt]; + if (validator2) { + const value = options[opt]; + const result = value === void 0 || validator2(value, opt, options); + if (result !== true) { + throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION); + } + } + } + var validator = { + assertOptions, + validators: validators$1 + }; + var validators = validator.validators; + var Axios = class { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy; + Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } + throw err; + } + } + _request(configOrUrl, config) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + config = mergeConfig(this.defaults, config); + const { transitional, paramsSerializer, headers } = config; + if (transitional !== void 0) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + config.method = (config.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config.method] + ); + headers && utils$1.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; + } + ); + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i2 = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config); + while (i2 < len) { + promise = promise.then(chain[i2++], chain[i2++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config; + i2 = 0; + while (i2 < len) { + const onFulfilled = requestInterceptorChain[i2++]; + const onRejected = requestInterceptorChain[i2++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i2 = 0; + len = responseInterceptorChain.length; + while (i2 < len) { + promise = promise.then(responseInterceptorChain[i2++], responseInterceptorChain[i2++]); + } + return promise; + } + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } + }; + utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; + }); + utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url, + data + })); + }; + } + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + "Form"] = generateHTTPMethod(true); + }); + var Axios$1 = Axios; + var CancelToken = class _CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) + return; + let i2 = token._listeners.length; + while (i2-- > 0) { + token._listeners[i2](cancel); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + /** + * Subscribe to the cancel signal + */ + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + /** + * Unsubscribe from the cancel signal + */ + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new _CancelToken(function executor(c4) { + cancel = c4; + }); + return { + token, + cancel + }; + } + }; + var CancelToken$1 = CancelToken; + function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + } + function isAxiosError(payload) { + return utils$1.isObject(payload) && payload.isAxiosError === true; + } + var HttpStatusCode = { + 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(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; + }); + var HttpStatusCode$1 = HttpStatusCode; + function createInstance(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); + utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); + utils$1.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create2(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + return instance; + } + var axios = createInstance(defaults$1); + axios.Axios = Axios$1; + axios.CanceledError = CanceledError; + axios.CancelToken = CancelToken$1; + axios.isCancel = isCancel; + axios.VERSION = VERSION; + axios.toFormData = toFormData; + axios.AxiosError = AxiosError; + axios.Cancel = axios.CanceledError; + axios.all = function all(promises) { + return Promise.all(promises); + }; + axios.spread = spread; + axios.isAxiosError = isAxiosError; + axios.mergeConfig = mergeConfig; + axios.AxiosHeaders = AxiosHeaders$1; + axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + axios.getAdapter = adapters.getAdapter; + axios.HttpStatusCode = HttpStatusCode$1; + axios.default = axios; + module2.exports = axios; + } +}); + +// node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js +var require_native_auth_client_config = __commonJS({ + "node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NativeAuthClientConfig = void 0; + var NativeAuthClientConfig = class { + constructor() { + this.origin = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.hostname : ""; + this.apiUrl = "https://api.multiversx.com"; + this.expirySeconds = 60 * 60 * 24; + } + }; + exports2.NativeAuthClientConfig = NativeAuthClientConfig; + } +}); + +// node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js +var require_native_auth_client = __commonJS({ + "node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NativeAuthClient = void 0; + var axios_1 = require_axios(); + var native_auth_client_config_1 = require_native_auth_client_config(); + var NativeAuthClient3 = class { + constructor(config) { + this.config = Object.assign(new native_auth_client_config_1.NativeAuthClientConfig(), config); + } + getToken(address, token, signature) { + const encodedAddress = this.encodeValue(address); + const encodedToken = this.encodeValue(token); + const accessToken = `${encodedAddress}.${encodedToken}.${signature}`; + return accessToken; + } + initialize(extraInfo = {}) { + return __awaiter2(this, void 0, void 0, function* () { + const blockHash = yield this.getCurrentBlockHash(); + const encodedExtraInfo = this.encodeValue(JSON.stringify(extraInfo)); + const origin = this.encodeValue(this.config.origin); + return `${origin}.${blockHash}.${this.config.expirySeconds}.${encodedExtraInfo}`; + }); + } + getCurrentBlockHash() { + return __awaiter2(this, void 0, void 0, function* () { + if (this.config.gatewayUrl) { + return yield this.getCurrentBlockHashWithGateway(); + } + return yield this.getCurrentBlockHashWithApi(); + }); + } + getCurrentBlockHashWithGateway() { + return __awaiter2(this, void 0, void 0, function* () { + const round = yield this.getCurrentRound(); + const url = `${this.config.gatewayUrl}/blocks/by-round/${round}`; + const response = yield this.get(url); + const blocks = response.data.data.blocks; + const block = blocks.filter((block2) => block2.shard === this.config.blockHashShard)[0]; + return block.hash; + }); + } + getCurrentRound() { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.config.gatewayUrl) { + throw new Error("Gateway URL not set"); + } + if (!this.config.blockHashShard) { + throw new Error("Blockhash shard not set"); + } + const url = `${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`; + const response = yield this.get(url); + const status = response.data.data.status; + return status.erd_current_round; + }); + } + getCurrentBlockHashWithApi() { + return __awaiter2(this, void 0, void 0, function* () { + try { + const url = `${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`; + const response = yield this.get(url); + if (response.data[0].hash !== void 0) { + return response.data[0].hash; + } + } catch (error) { + } + return this.getCurrentBlockHashWithApiFallback(); + }); + } + getCurrentBlockHashWithApiFallback() { + return __awaiter2(this, void 0, void 0, function* () { + let url = `${this.config.apiUrl}/blocks?size=1&fields=hash`; + if (this.config.blockHashShard !== void 0) { + url += `&shard=${this.config.blockHashShard}`; + } + const response = yield this.get(url); + return response.data[0].hash; + }); + } + encodeValue(str) { + return this.escape(import_buffer.Buffer.from(str, "utf8").toString("base64")); + } + escape(str) { + return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + } + get(url) { + return __awaiter2(this, void 0, void 0, function* () { + return yield axios_1.default.get(url, { headers: this.config.extraRequestHeaders }); + }); + } + }; + exports2.NativeAuthClient = NativeAuthClient3; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js +var require_transactionStatus = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionStatus = void 0; + var TransactionStatus2 = class _TransactionStatus { + /** + * Creates a new TransactionStatus object. + */ + constructor(status) { + this.status = (status || "").toLowerCase(); + } + /** + * Creates an unknown status. + */ + static createUnknown() { + return new _TransactionStatus("unknown"); + } + /** + * Returns whether the transaction is pending (e.g. in mempool). + */ + isPending() { + return this.status == "received" || this.status == "pending"; + } + /** + * Returns whether the transaction has been executed (not necessarily with success). + */ + isExecuted() { + return this.isSuccessful() || this.isFailed() || this.isInvalid(); + } + /** + * Returns whether the transaction has been executed successfully. + */ + isSuccessful() { + return this.status == "executed" || this.status == "success" || this.status == "successful"; + } + /** + * Returns whether the transaction has been executed, but with a failure. + */ + isFailed() { + return this.status == "fail" || this.status == "failed" || this.status == "unsuccessful" || this.isInvalid(); + } + /** + * Returns whether the transaction has been executed, but marked as invalid (e.g. due to "insufficient funds"). + */ + isInvalid() { + return this.status == "invalid"; + } + toString() { + return this.status; + } + valueOf() { + return this.status; + } + equals(other) { + if (!other) { + return false; + } + return this.status == other.status; + } + }; + exports2.TransactionStatus = TransactionStatus2; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js +var require_transactionReceipt = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionReceipt = void 0; + var primitives_1 = require_primitives(); + var TransactionReceipt2 = class _TransactionReceipt { + constructor() { + this.value = ""; + this.sender = new primitives_1.Address(""); + this.data = ""; + this.hash = ""; + } + static fromHttpResponse(response) { + let receipt = new _TransactionReceipt(); + receipt.value = (response.value || 0).toString(); + receipt.sender = new primitives_1.Address(response.sender); + receipt.data = response.data; + receipt.hash = response.txHash; + return receipt; + } + }; + exports2.TransactionReceipt = TransactionReceipt2; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/errors.js +var require_errors5 = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrContractQuery = exports2.ErrNetworkProvider = exports2.ErrUnexpectedCondition = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + }; + exports2.Err = Err; + var ErrUnexpectedCondition = class extends Err { + constructor(message) { + super(`Unexpected condition: [${message}]`); + } + }; + exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; + var ErrNetworkProvider = class extends Err { + constructor(url, error, inner) { + let message = `Request error on url [${url}]: [${error}]`; + super(message, inner); + } + }; + exports2.ErrNetworkProvider = ErrNetworkProvider; + var ErrContractQuery = class extends Err { + constructor(originalError) { + super(originalError.message.replace("executeQuery:", "")); + } + }; + exports2.ErrContractQuery = ErrContractQuery; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js +var require_transactionEvents = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionEventTopic = exports2.TransactionEventData = exports2.TransactionEvent = void 0; + var primitives_1 = require_primitives(); + var TransactionEvent = class _TransactionEvent { + constructor(init) { + this.address = new primitives_1.Address(""); + this.identifier = ""; + this.topics = []; + this.data = ""; + this.dataPayload = new TransactionEventData(import_buffer.Buffer.from("", "utf8")); + this.additionalData = []; + Object.assign(this, init); + } + static fromHttpResponse(responsePart) { + let result = new _TransactionEvent(); + result.address = new primitives_1.Address(responsePart.address); + result.identifier = responsePart.identifier || ""; + result.topics = (responsePart.topics || []).map((topic) => new TransactionEventTopic(topic)); + result.dataPayload = TransactionEventData.fromBase64(responsePart.data); + result.additionalData = (responsePart.additionalData || []).map(TransactionEventData.fromBase64); + result.data = result.dataPayload.toString(); + return result; + } + findFirstOrNoneTopic(predicate) { + return this.topics.filter((topic) => predicate(topic))[0]; + } + getLastTopic() { + return this.topics[this.topics.length - 1]; + } + }; + exports2.TransactionEvent = TransactionEvent; + var TransactionEventData = class _TransactionEventData { + constructor(data) { + this.raw = data; + } + static fromBase64(str) { + return new _TransactionEventData(import_buffer.Buffer.from(str || "", "base64")); + } + toString() { + return this.raw.toString("utf8"); + } + hex() { + return this.raw.toString("hex"); + } + valueOf() { + return this.raw; + } + }; + exports2.TransactionEventData = TransactionEventData; + var TransactionEventTopic = class { + constructor(topic) { + this.raw = import_buffer.Buffer.from(topic || "", "base64"); + } + toString() { + return this.raw.toString("utf8"); + } + hex() { + return this.raw.toString("hex"); + } + valueOf() { + return this.raw; + } + }; + exports2.TransactionEventTopic = TransactionEventTopic; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js +var require_transactionLogs = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionLogs = void 0; + var errors_1 = require_errors5(); + var primitives_1 = require_primitives(); + var transactionEvents_1 = require_transactionEvents(); + var TransactionLogs2 = class _TransactionLogs { + constructor(init) { + this.address = new primitives_1.Address(""); + this.events = []; + Object.assign(this, init); + } + static fromHttpResponse(logs) { + let result = new _TransactionLogs(); + result.address = new primitives_1.Address(logs.address); + result.events = (logs.events || []).map((event) => transactionEvents_1.TransactionEvent.fromHttpResponse(event)); + return result; + } + findSingleOrNoneEvent(identifier, predicate) { + let events = this.findEvents(identifier, predicate); + if (events.length > 1) { + throw new errors_1.ErrUnexpectedCondition(`more than one event of type ${identifier}`); + } + return events[0]; + } + findFirstOrNoneEvent(identifier, predicate) { + return this.findEvents(identifier, predicate)[0]; + } + findEvents(identifier, predicate) { + let events = this.events.filter((event) => event.identifier == identifier); + if (predicate) { + events = events.filter((event) => predicate(event)); + } + return events; + } + }; + exports2.TransactionLogs = TransactionLogs2; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/contractResults.js +var require_contractResults = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/contractResults.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractResultItem = exports2.ContractResults = void 0; + var transactionLogs_1 = require_transactionLogs(); + var primitives_1 = require_primitives(); + var ContractResults2 = class _ContractResults { + constructor(items) { + this.items = items; + this.items.sort(function(a3, b4) { + return a3.nonce.valueOf() - b4.nonce.valueOf(); + }); + } + static fromProxyHttpResponse(results) { + let items = results.map((item) => ContractResultItem.fromProxyHttpResponse(item)); + return new _ContractResults(items); + } + static fromApiHttpResponse(results) { + let items = results.map((item) => ContractResultItem.fromApiHttpResponse(item)); + return new _ContractResults(items); + } + }; + exports2.ContractResults = ContractResults2; + var ContractResultItem = class _ContractResultItem { + constructor(init) { + this.hash = ""; + this.nonce = 0; + this.value = ""; + this.receiver = new primitives_1.Address(""); + this.sender = new primitives_1.Address(""); + this.data = ""; + this.previousHash = ""; + this.originalHash = ""; + this.gasLimit = 0; + this.gasPrice = 0; + this.callType = 0; + this.returnMessage = ""; + this.logs = new transactionLogs_1.TransactionLogs(); + Object.assign(this, init); + } + static fromProxyHttpResponse(response) { + let item = _ContractResultItem.fromHttpResponse(response); + return item; + } + static fromApiHttpResponse(response) { + let item = _ContractResultItem.fromHttpResponse(response); + item.data = import_buffer.Buffer.from(item.data, "base64").toString(); + item.callType = Number(item.callType); + return item; + } + static fromHttpResponse(response) { + let item = new _ContractResultItem(); + item.hash = response.hash; + item.nonce = Number(response.nonce || 0); + item.value = (response.value || 0).toString(); + item.receiver = new primitives_1.Address(response.receiver); + item.sender = new primitives_1.Address(response.sender); + item.previousHash = response.prevTxHash; + item.originalHash = response.originalTxHash; + item.gasLimit = Number(response.gasLimit || 0); + item.gasPrice = Number(response.gasPrice || 0); + item.data = response.data || ""; + item.callType = response.callType; + item.returnMessage = response.returnMessage; + item.logs = transactionLogs_1.TransactionLogs.fromHttpResponse(response.logs || {}); + return item; + } + }; + exports2.ContractResultItem = ContractResultItem; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js +var require_contractQueryRequest = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractQueryRequest = void 0; + var ContractQueryRequest2 = class { + constructor(query) { + this.query = query; + } + toHttpRequest() { + var _a; + let request = {}; + let query = this.query; + request.scAddress = query.address.bech32(); + request.caller = ((_a = query.caller) === null || _a === void 0 ? void 0 : _a.bech32()) ? query.caller.bech32() : void 0; + request.funcName = query.func.toString(); + request.value = query.value ? query.value.toString() : void 0; + request.args = query.getEncodedArguments(); + return request; + } + }; + exports2.ContractQueryRequest = ContractQueryRequest2; + } +}); + +// node_modules/qrcode/lib/can-promise.js +var require_can_promise = __commonJS({ + "node_modules/qrcode/lib/can-promise.js"(exports2, module2) { + init_shim(); + module2.exports = function() { + return typeof Promise === "function" && Promise.prototype && Promise.prototype.then; + }; + } +}); + +// node_modules/qrcode/lib/core/utils.js +var require_utils6 = __commonJS({ + "node_modules/qrcode/lib/core/utils.js"(exports2) { + init_shim(); + var toSJISFunction; + var CODEWORDS_COUNT = [ + 0, + // Not used + 26, + 44, + 70, + 100, + 134, + 172, + 196, + 242, + 292, + 346, + 404, + 466, + 532, + 581, + 655, + 733, + 815, + 901, + 991, + 1085, + 1156, + 1258, + 1364, + 1474, + 1588, + 1706, + 1828, + 1921, + 2051, + 2185, + 2323, + 2465, + 2611, + 2761, + 2876, + 3034, + 3196, + 3362, + 3532, + 3706 + ]; + exports2.getSymbolSize = function getSymbolSize(version2) { + if (!version2) + throw new Error('"version" cannot be null or undefined'); + if (version2 < 1 || version2 > 40) + throw new Error('"version" should be in range from 1 to 40'); + return version2 * 4 + 17; + }; + exports2.getSymbolTotalCodewords = function getSymbolTotalCodewords(version2) { + return CODEWORDS_COUNT[version2]; + }; + exports2.getBCHDigit = function(data) { + let digit = 0; + while (data !== 0) { + digit++; + data >>>= 1; + } + return digit; + }; + exports2.setToSJISFunction = function setToSJISFunction(f4) { + if (typeof f4 !== "function") { + throw new Error('"toSJISFunc" is not a valid function.'); + } + toSJISFunction = f4; + }; + exports2.isKanjiModeEnabled = function() { + return typeof toSJISFunction !== "undefined"; + }; + exports2.toSJIS = function toSJIS(kanji) { + return toSJISFunction(kanji); + }; + } +}); + +// node_modules/qrcode/lib/core/error-correction-level.js +var require_error_correction_level = __commonJS({ + "node_modules/qrcode/lib/core/error-correction-level.js"(exports2) { + init_shim(); + exports2.L = { bit: 1 }; + exports2.M = { bit: 0 }; + exports2.Q = { bit: 3 }; + exports2.H = { bit: 2 }; + function fromString3(string2) { + if (typeof string2 !== "string") { + throw new Error("Param is not a string"); + } + const lcStr = string2.toLowerCase(); + switch (lcStr) { + case "l": + case "low": + return exports2.L; + case "m": + case "medium": + return exports2.M; + case "q": + case "quartile": + return exports2.Q; + case "h": + case "high": + return exports2.H; + default: + throw new Error("Unknown EC Level: " + string2); + } + } + exports2.isValid = function isValid(level) { + return level && typeof level.bit !== "undefined" && level.bit >= 0 && level.bit < 4; + }; + exports2.from = function from3(value, defaultValue) { + if (exports2.isValid(value)) { + return value; + } + try { + return fromString3(value); + } catch (e2) { + return defaultValue; + } + }; + } +}); + +// node_modules/qrcode/lib/core/bit-buffer.js +var require_bit_buffer = __commonJS({ + "node_modules/qrcode/lib/core/bit-buffer.js"(exports2, module2) { + init_shim(); + function BitBuffer() { + this.buffer = []; + this.length = 0; + } + BitBuffer.prototype = { + get: function(index) { + const bufIndex = Math.floor(index / 8); + return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1; + }, + put: function(num, length2) { + for (let i2 = 0; i2 < length2; i2++) { + this.putBit((num >>> length2 - i2 - 1 & 1) === 1); + } + }, + getLengthInBits: function() { + return this.length; + }, + putBit: function(bit) { + const bufIndex = Math.floor(this.length / 8); + if (this.buffer.length <= bufIndex) { + this.buffer.push(0); + } + if (bit) { + this.buffer[bufIndex] |= 128 >>> this.length % 8; + } + this.length++; + } + }; + module2.exports = BitBuffer; + } +}); + +// node_modules/qrcode/lib/core/bit-matrix.js +var require_bit_matrix = __commonJS({ + "node_modules/qrcode/lib/core/bit-matrix.js"(exports2, module2) { + init_shim(); + function BitMatrix(size) { + if (!size || size < 1) { + throw new Error("BitMatrix size must be defined and greater than 0"); + } + this.size = size; + this.data = new Uint8Array(size * size); + this.reservedBit = new Uint8Array(size * size); + } + BitMatrix.prototype.set = function(row, col, value, reserved) { + const index = row * this.size + col; + this.data[index] = value; + if (reserved) + this.reservedBit[index] = true; + }; + BitMatrix.prototype.get = function(row, col) { + return this.data[row * this.size + col]; + }; + BitMatrix.prototype.xor = function(row, col, value) { + this.data[row * this.size + col] ^= value; + }; + BitMatrix.prototype.isReserved = function(row, col) { + return this.reservedBit[row * this.size + col]; + }; + module2.exports = BitMatrix; + } +}); + +// node_modules/qrcode/lib/core/alignment-pattern.js +var require_alignment_pattern = __commonJS({ + "node_modules/qrcode/lib/core/alignment-pattern.js"(exports2) { + init_shim(); + var getSymbolSize = require_utils6().getSymbolSize; + exports2.getRowColCoords = function getRowColCoords(version2) { + if (version2 === 1) + return []; + const posCount = Math.floor(version2 / 7) + 2; + const size = getSymbolSize(version2); + const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2; + const positions = [size - 7]; + for (let i2 = 1; i2 < posCount - 1; i2++) { + positions[i2] = positions[i2 - 1] - intervals; + } + positions.push(6); + return positions.reverse(); + }; + exports2.getPositions = function getPositions(version2) { + const coords = []; + const pos = exports2.getRowColCoords(version2); + const posLength = pos.length; + for (let i2 = 0; i2 < posLength; i2++) { + for (let j2 = 0; j2 < posLength; j2++) { + if (i2 === 0 && j2 === 0 || // top-left + i2 === 0 && j2 === posLength - 1 || // bottom-left + i2 === posLength - 1 && j2 === 0) { + continue; + } + coords.push([pos[i2], pos[j2]]); + } + } + return coords; + }; + } +}); + +// node_modules/qrcode/lib/core/finder-pattern.js +var require_finder_pattern = __commonJS({ + "node_modules/qrcode/lib/core/finder-pattern.js"(exports2) { + init_shim(); + var getSymbolSize = require_utils6().getSymbolSize; + var FINDER_PATTERN_SIZE = 7; + exports2.getPositions = function getPositions(version2) { + const size = getSymbolSize(version2); + return [ + // top-left + [0, 0], + // top-right + [size - FINDER_PATTERN_SIZE, 0], + // bottom-left + [0, size - FINDER_PATTERN_SIZE] + ]; + }; + } +}); + +// node_modules/qrcode/lib/core/mask-pattern.js +var require_mask_pattern = __commonJS({ + "node_modules/qrcode/lib/core/mask-pattern.js"(exports2) { + init_shim(); + exports2.Patterns = { + PATTERN000: 0, + PATTERN001: 1, + PATTERN010: 2, + PATTERN011: 3, + PATTERN100: 4, + PATTERN101: 5, + PATTERN110: 6, + PATTERN111: 7 + }; + var PenaltyScores = { + N1: 3, + N2: 3, + N3: 40, + N4: 10 + }; + exports2.isValid = function isValid(mask) { + return mask != null && mask !== "" && !isNaN(mask) && mask >= 0 && mask <= 7; + }; + exports2.from = function from3(value) { + return exports2.isValid(value) ? parseInt(value, 10) : void 0; + }; + exports2.getPenaltyN1 = function getPenaltyN1(data) { + const size = data.size; + let points = 0; + let sameCountCol = 0; + let sameCountRow = 0; + let lastCol = null; + let lastRow = null; + for (let row = 0; row < size; row++) { + sameCountCol = sameCountRow = 0; + lastCol = lastRow = null; + for (let col = 0; col < size; col++) { + let module3 = data.get(row, col); + if (module3 === lastCol) { + sameCountCol++; + } else { + if (sameCountCol >= 5) + points += PenaltyScores.N1 + (sameCountCol - 5); + lastCol = module3; + sameCountCol = 1; + } + module3 = data.get(col, row); + if (module3 === lastRow) { + sameCountRow++; + } else { + if (sameCountRow >= 5) + points += PenaltyScores.N1 + (sameCountRow - 5); + lastRow = module3; + sameCountRow = 1; + } + } + if (sameCountCol >= 5) + points += PenaltyScores.N1 + (sameCountCol - 5); + if (sameCountRow >= 5) + points += PenaltyScores.N1 + (sameCountRow - 5); + } + return points; + }; + exports2.getPenaltyN2 = function getPenaltyN2(data) { + const size = data.size; + let points = 0; + for (let row = 0; row < size - 1; row++) { + for (let col = 0; col < size - 1; col++) { + const last = data.get(row, col) + data.get(row, col + 1) + data.get(row + 1, col) + data.get(row + 1, col + 1); + if (last === 4 || last === 0) + points++; + } + } + return points * PenaltyScores.N2; + }; + exports2.getPenaltyN3 = function getPenaltyN3(data) { + const size = data.size; + let points = 0; + let bitsCol = 0; + let bitsRow = 0; + for (let row = 0; row < size; row++) { + bitsCol = bitsRow = 0; + for (let col = 0; col < size; col++) { + bitsCol = bitsCol << 1 & 2047 | data.get(row, col); + if (col >= 10 && (bitsCol === 1488 || bitsCol === 93)) + points++; + bitsRow = bitsRow << 1 & 2047 | data.get(col, row); + if (col >= 10 && (bitsRow === 1488 || bitsRow === 93)) + points++; + } + } + return points * PenaltyScores.N3; + }; + exports2.getPenaltyN4 = function getPenaltyN4(data) { + let darkCount = 0; + const modulesCount = data.data.length; + for (let i2 = 0; i2 < modulesCount; i2++) + darkCount += data.data[i2]; + const k4 = Math.abs(Math.ceil(darkCount * 100 / modulesCount / 5) - 10); + return k4 * PenaltyScores.N4; + }; + function getMaskAt(maskPattern, i2, j2) { + switch (maskPattern) { + case exports2.Patterns.PATTERN000: + return (i2 + j2) % 2 === 0; + case exports2.Patterns.PATTERN001: + return i2 % 2 === 0; + case exports2.Patterns.PATTERN010: + return j2 % 3 === 0; + case exports2.Patterns.PATTERN011: + return (i2 + j2) % 3 === 0; + case exports2.Patterns.PATTERN100: + return (Math.floor(i2 / 2) + Math.floor(j2 / 3)) % 2 === 0; + case exports2.Patterns.PATTERN101: + return i2 * j2 % 2 + i2 * j2 % 3 === 0; + case exports2.Patterns.PATTERN110: + return (i2 * j2 % 2 + i2 * j2 % 3) % 2 === 0; + case exports2.Patterns.PATTERN111: + return (i2 * j2 % 3 + (i2 + j2) % 2) % 2 === 0; + default: + throw new Error("bad maskPattern:" + maskPattern); + } + } + exports2.applyMask = function applyMask(pattern, data) { + const size = data.size; + for (let col = 0; col < size; col++) { + for (let row = 0; row < size; row++) { + if (data.isReserved(row, col)) + continue; + data.xor(row, col, getMaskAt(pattern, row, col)); + } + } + }; + exports2.getBestMask = function getBestMask(data, setupFormatFunc) { + const numPatterns = Object.keys(exports2.Patterns).length; + let bestPattern = 0; + let lowerPenalty = Infinity; + for (let p3 = 0; p3 < numPatterns; p3++) { + setupFormatFunc(p3); + exports2.applyMask(p3, data); + const penalty = exports2.getPenaltyN1(data) + exports2.getPenaltyN2(data) + exports2.getPenaltyN3(data) + exports2.getPenaltyN4(data); + exports2.applyMask(p3, data); + if (penalty < lowerPenalty) { + lowerPenalty = penalty; + bestPattern = p3; + } + } + return bestPattern; + }; + } +}); + +// node_modules/qrcode/lib/core/error-correction-code.js +var require_error_correction_code = __commonJS({ + "node_modules/qrcode/lib/core/error-correction-code.js"(exports2) { + init_shim(); + var ECLevel = require_error_correction_level(); + var EC_BLOCKS_TABLE = [ + // L M Q H + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 1, + 2, + 2, + 4, + 1, + 2, + 4, + 4, + 2, + 4, + 4, + 4, + 2, + 4, + 6, + 5, + 2, + 4, + 6, + 6, + 2, + 5, + 8, + 8, + 4, + 5, + 8, + 8, + 4, + 5, + 8, + 11, + 4, + 8, + 10, + 11, + 4, + 9, + 12, + 16, + 4, + 9, + 16, + 16, + 6, + 10, + 12, + 18, + 6, + 10, + 17, + 16, + 6, + 11, + 16, + 19, + 6, + 13, + 18, + 21, + 7, + 14, + 21, + 25, + 8, + 16, + 20, + 25, + 8, + 17, + 23, + 25, + 9, + 17, + 23, + 34, + 9, + 18, + 25, + 30, + 10, + 20, + 27, + 32, + 12, + 21, + 29, + 35, + 12, + 23, + 34, + 37, + 12, + 25, + 34, + 40, + 13, + 26, + 35, + 42, + 14, + 28, + 38, + 45, + 15, + 29, + 40, + 48, + 16, + 31, + 43, + 51, + 17, + 33, + 45, + 54, + 18, + 35, + 48, + 57, + 19, + 37, + 51, + 60, + 19, + 38, + 53, + 63, + 20, + 40, + 56, + 66, + 21, + 43, + 59, + 70, + 22, + 45, + 62, + 74, + 24, + 47, + 65, + 77, + 25, + 49, + 68, + 81 + ]; + var EC_CODEWORDS_TABLE = [ + // L M Q H + 7, + 10, + 13, + 17, + 10, + 16, + 22, + 28, + 15, + 26, + 36, + 44, + 20, + 36, + 52, + 64, + 26, + 48, + 72, + 88, + 36, + 64, + 96, + 112, + 40, + 72, + 108, + 130, + 48, + 88, + 132, + 156, + 60, + 110, + 160, + 192, + 72, + 130, + 192, + 224, + 80, + 150, + 224, + 264, + 96, + 176, + 260, + 308, + 104, + 198, + 288, + 352, + 120, + 216, + 320, + 384, + 132, + 240, + 360, + 432, + 144, + 280, + 408, + 480, + 168, + 308, + 448, + 532, + 180, + 338, + 504, + 588, + 196, + 364, + 546, + 650, + 224, + 416, + 600, + 700, + 224, + 442, + 644, + 750, + 252, + 476, + 690, + 816, + 270, + 504, + 750, + 900, + 300, + 560, + 810, + 960, + 312, + 588, + 870, + 1050, + 336, + 644, + 952, + 1110, + 360, + 700, + 1020, + 1200, + 390, + 728, + 1050, + 1260, + 420, + 784, + 1140, + 1350, + 450, + 812, + 1200, + 1440, + 480, + 868, + 1290, + 1530, + 510, + 924, + 1350, + 1620, + 540, + 980, + 1440, + 1710, + 570, + 1036, + 1530, + 1800, + 570, + 1064, + 1590, + 1890, + 600, + 1120, + 1680, + 1980, + 630, + 1204, + 1770, + 2100, + 660, + 1260, + 1860, + 2220, + 720, + 1316, + 1950, + 2310, + 750, + 1372, + 2040, + 2430 + ]; + exports2.getBlocksCount = function getBlocksCount(version2, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 0]; + case ECLevel.M: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 1]; + case ECLevel.Q: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 2]; + case ECLevel.H: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 3]; + default: + return void 0; + } + }; + exports2.getTotalCodewordsCount = function getTotalCodewordsCount(version2, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 0]; + case ECLevel.M: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 1]; + case ECLevel.Q: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 2]; + case ECLevel.H: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 3]; + default: + return void 0; + } + }; + } +}); + +// node_modules/qrcode/lib/core/galois-field.js +var require_galois_field = __commonJS({ + "node_modules/qrcode/lib/core/galois-field.js"(exports2) { + init_shim(); + var EXP_TABLE = new Uint8Array(512); + var LOG_TABLE = new Uint8Array(256); + (function initTables() { + let x3 = 1; + for (let i2 = 0; i2 < 255; i2++) { + EXP_TABLE[i2] = x3; + LOG_TABLE[x3] = i2; + x3 <<= 1; + if (x3 & 256) { + x3 ^= 285; + } + } + for (let i2 = 255; i2 < 512; i2++) { + EXP_TABLE[i2] = EXP_TABLE[i2 - 255]; + } + })(); + exports2.log = function log(n3) { + if (n3 < 1) + throw new Error("log(" + n3 + ")"); + return LOG_TABLE[n3]; + }; + exports2.exp = function exp(n3) { + return EXP_TABLE[n3]; + }; + exports2.mul = function mul(x3, y4) { + if (x3 === 0 || y4 === 0) + return 0; + return EXP_TABLE[LOG_TABLE[x3] + LOG_TABLE[y4]]; + }; + } +}); + +// node_modules/qrcode/lib/core/polynomial.js +var require_polynomial = __commonJS({ + "node_modules/qrcode/lib/core/polynomial.js"(exports2) { + init_shim(); + var GF = require_galois_field(); + exports2.mul = function mul(p1, p22) { + const coeff = new Uint8Array(p1.length + p22.length - 1); + for (let i2 = 0; i2 < p1.length; i2++) { + for (let j2 = 0; j2 < p22.length; j2++) { + coeff[i2 + j2] ^= GF.mul(p1[i2], p22[j2]); + } + } + return coeff; + }; + exports2.mod = function mod2(divident, divisor) { + let result = new Uint8Array(divident); + while (result.length - divisor.length >= 0) { + const coeff = result[0]; + for (let i2 = 0; i2 < divisor.length; i2++) { + result[i2] ^= GF.mul(divisor[i2], coeff); + } + let offset = 0; + while (offset < result.length && result[offset] === 0) + offset++; + result = result.slice(offset); + } + return result; + }; + exports2.generateECPolynomial = function generateECPolynomial(degree) { + let poly = new Uint8Array([1]); + for (let i2 = 0; i2 < degree; i2++) { + poly = exports2.mul(poly, new Uint8Array([1, GF.exp(i2)])); + } + return poly; + }; + } +}); + +// node_modules/qrcode/lib/core/reed-solomon-encoder.js +var require_reed_solomon_encoder = __commonJS({ + "node_modules/qrcode/lib/core/reed-solomon-encoder.js"(exports2, module2) { + init_shim(); + var Polynomial = require_polynomial(); + function ReedSolomonEncoder(degree) { + this.genPoly = void 0; + this.degree = degree; + if (this.degree) + this.initialize(this.degree); + } + ReedSolomonEncoder.prototype.initialize = function initialize(degree) { + this.degree = degree; + this.genPoly = Polynomial.generateECPolynomial(this.degree); + }; + ReedSolomonEncoder.prototype.encode = function encode5(data) { + if (!this.genPoly) { + throw new Error("Encoder not initialized"); + } + const paddedData = new Uint8Array(data.length + this.degree); + paddedData.set(data); + const remainder = Polynomial.mod(paddedData, this.genPoly); + const start = this.degree - remainder.length; + if (start > 0) { + const buff = new Uint8Array(this.degree); + buff.set(remainder, start); + return buff; + } + return remainder; + }; + module2.exports = ReedSolomonEncoder; + } +}); + +// node_modules/qrcode/lib/core/version-check.js +var require_version_check = __commonJS({ + "node_modules/qrcode/lib/core/version-check.js"(exports2) { + init_shim(); + exports2.isValid = function isValid(version2) { + return !isNaN(version2) && version2 >= 1 && version2 <= 40; + }; + } +}); + +// node_modules/qrcode/lib/core/regex.js +var require_regex = __commonJS({ + "node_modules/qrcode/lib/core/regex.js"(exports2) { + init_shim(); + var numeric = "[0-9]+"; + var alphanumeric = "[A-Z $%*+\\-./:]+"; + var kanji = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+"; + kanji = kanji.replace(/u/g, "\\u"); + var byte = "(?:(?![A-Z0-9 $%*+\\-./:]|" + kanji + ")(?:.|[\r\n]))+"; + exports2.KANJI = new RegExp(kanji, "g"); + exports2.BYTE_KANJI = new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g"); + exports2.BYTE = new RegExp(byte, "g"); + exports2.NUMERIC = new RegExp(numeric, "g"); + exports2.ALPHANUMERIC = new RegExp(alphanumeric, "g"); + var TEST_KANJI = new RegExp("^" + kanji + "$"); + var TEST_NUMERIC = new RegExp("^" + numeric + "$"); + var TEST_ALPHANUMERIC = new RegExp("^[A-Z0-9 $%*+\\-./:]+$"); + exports2.testKanji = function testKanji(str) { + return TEST_KANJI.test(str); + }; + exports2.testNumeric = function testNumeric(str) { + return TEST_NUMERIC.test(str); + }; + exports2.testAlphanumeric = function testAlphanumeric(str) { + return TEST_ALPHANUMERIC.test(str); + }; + } +}); + +// node_modules/qrcode/lib/core/mode.js +var require_mode = __commonJS({ + "node_modules/qrcode/lib/core/mode.js"(exports2) { + init_shim(); + var VersionCheck = require_version_check(); + var Regex = require_regex(); + exports2.NUMERIC = { + id: "Numeric", + bit: 1 << 0, + ccBits: [10, 12, 14] + }; + exports2.ALPHANUMERIC = { + id: "Alphanumeric", + bit: 1 << 1, + ccBits: [9, 11, 13] + }; + exports2.BYTE = { + id: "Byte", + bit: 1 << 2, + ccBits: [8, 16, 16] + }; + exports2.KANJI = { + id: "Kanji", + bit: 1 << 3, + ccBits: [8, 10, 12] + }; + exports2.MIXED = { + bit: -1 + }; + exports2.getCharCountIndicator = function getCharCountIndicator(mode, version2) { + if (!mode.ccBits) + throw new Error("Invalid mode: " + mode); + if (!VersionCheck.isValid(version2)) { + throw new Error("Invalid version: " + version2); + } + if (version2 >= 1 && version2 < 10) + return mode.ccBits[0]; + else if (version2 < 27) + return mode.ccBits[1]; + return mode.ccBits[2]; + }; + exports2.getBestModeForData = function getBestModeForData(dataStr) { + if (Regex.testNumeric(dataStr)) + return exports2.NUMERIC; + else if (Regex.testAlphanumeric(dataStr)) + return exports2.ALPHANUMERIC; + else if (Regex.testKanji(dataStr)) + return exports2.KANJI; + else + return exports2.BYTE; + }; + exports2.toString = function toString3(mode) { + if (mode && mode.id) + return mode.id; + throw new Error("Invalid mode"); + }; + exports2.isValid = function isValid(mode) { + return mode && mode.bit && mode.ccBits; + }; + function fromString3(string2) { + if (typeof string2 !== "string") { + throw new Error("Param is not a string"); + } + const lcStr = string2.toLowerCase(); + switch (lcStr) { + case "numeric": + return exports2.NUMERIC; + case "alphanumeric": + return exports2.ALPHANUMERIC; + case "kanji": + return exports2.KANJI; + case "byte": + return exports2.BYTE; + default: + throw new Error("Unknown mode: " + string2); + } + } + exports2.from = function from3(value, defaultValue) { + if (exports2.isValid(value)) { + return value; + } + try { + return fromString3(value); + } catch (e2) { + return defaultValue; + } + }; + } +}); + +// node_modules/qrcode/lib/core/version.js +var require_version = __commonJS({ + "node_modules/qrcode/lib/core/version.js"(exports2) { + init_shim(); + var Utils = require_utils6(); + var ECCode = require_error_correction_code(); + var ECLevel = require_error_correction_level(); + var Mode = require_mode(); + var VersionCheck = require_version_check(); + var G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0; + var G18_BCH = Utils.getBCHDigit(G18); + function getBestVersionForDataLength(mode, length2, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, mode)) { + return currentVersion; + } + } + return void 0; + } + function getReservedBitsCount(mode, version2) { + return Mode.getCharCountIndicator(mode, version2) + 4; + } + function getTotalBitsFromDataArray(segments, version2) { + let totalBits = 0; + segments.forEach(function(data) { + const reservedBits = getReservedBitsCount(data.mode, version2); + totalBits += reservedBits + data.getBitsLength(); + }); + return totalBits; + } + function getBestVersionForMixedData(segments, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + const length2 = getTotalBitsFromDataArray(segments, currentVersion); + if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { + return currentVersion; + } + } + return void 0; + } + exports2.from = function from3(value, defaultValue) { + if (VersionCheck.isValid(value)) { + return parseInt(value, 10); + } + return defaultValue; + }; + exports2.getCapacity = function getCapacity(version2, errorCorrectionLevel, mode) { + if (!VersionCheck.isValid(version2)) { + throw new Error("Invalid QR Code version"); + } + if (typeof mode === "undefined") + mode = Mode.BYTE; + const totalCodewords = Utils.getSymbolTotalCodewords(version2); + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; + if (mode === Mode.MIXED) + return dataTotalCodewordsBits; + const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version2); + switch (mode) { + case Mode.NUMERIC: + return Math.floor(usableBits / 10 * 3); + case Mode.ALPHANUMERIC: + return Math.floor(usableBits / 11 * 2); + case Mode.KANJI: + return Math.floor(usableBits / 13); + case Mode.BYTE: + default: + return Math.floor(usableBits / 8); + } + }; + exports2.getBestVersionForData = function getBestVersionForData(data, errorCorrectionLevel) { + let seg; + const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M); + if (Array.isArray(data)) { + if (data.length > 1) { + return getBestVersionForMixedData(data, ecl); + } + if (data.length === 0) { + return 1; + } + seg = data[0]; + } else { + seg = data; + } + return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl); + }; + exports2.getEncodedBits = function getEncodedBits(version2) { + if (!VersionCheck.isValid(version2) || version2 < 7) { + throw new Error("Invalid QR Code version"); + } + let d3 = version2 << 12; + while (Utils.getBCHDigit(d3) - G18_BCH >= 0) { + d3 ^= G18 << Utils.getBCHDigit(d3) - G18_BCH; + } + return version2 << 12 | d3; + }; + } +}); + +// node_modules/qrcode/lib/core/format-info.js +var require_format_info = __commonJS({ + "node_modules/qrcode/lib/core/format-info.js"(exports2) { + init_shim(); + var Utils = require_utils6(); + var G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0; + var G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1; + var G15_BCH = Utils.getBCHDigit(G15); + exports2.getEncodedBits = function getEncodedBits(errorCorrectionLevel, mask) { + const data = errorCorrectionLevel.bit << 3 | mask; + let d3 = data << 10; + while (Utils.getBCHDigit(d3) - G15_BCH >= 0) { + d3 ^= G15 << Utils.getBCHDigit(d3) - G15_BCH; + } + return (data << 10 | d3) ^ G15_MASK; + }; + } +}); + +// node_modules/qrcode/lib/core/numeric-data.js +var require_numeric_data = __commonJS({ + "node_modules/qrcode/lib/core/numeric-data.js"(exports2, module2) { + init_shim(); + var Mode = require_mode(); + function NumericData(data) { + this.mode = Mode.NUMERIC; + this.data = data.toString(); + } + NumericData.getBitsLength = function getBitsLength(length2) { + return 10 * Math.floor(length2 / 3) + (length2 % 3 ? length2 % 3 * 3 + 1 : 0); + }; + NumericData.prototype.getLength = function getLength() { + return this.data.length; + }; + NumericData.prototype.getBitsLength = function getBitsLength() { + return NumericData.getBitsLength(this.data.length); + }; + NumericData.prototype.write = function write(bitBuffer) { + let i2, group, value; + for (i2 = 0; i2 + 3 <= this.data.length; i2 += 3) { + group = this.data.substr(i2, 3); + value = parseInt(group, 10); + bitBuffer.put(value, 10); + } + const remainingNum = this.data.length - i2; + if (remainingNum > 0) { + group = this.data.substr(i2); + value = parseInt(group, 10); + bitBuffer.put(value, remainingNum * 3 + 1); + } + }; + module2.exports = NumericData; + } +}); + +// node_modules/qrcode/lib/core/alphanumeric-data.js +var require_alphanumeric_data = __commonJS({ + "node_modules/qrcode/lib/core/alphanumeric-data.js"(exports2, module2) { + init_shim(); + var Mode = require_mode(); + var ALPHA_NUM_CHARS = [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + " ", + "$", + "%", + "*", + "+", + "-", + ".", + "/", + ":" + ]; + function AlphanumericData(data) { + this.mode = Mode.ALPHANUMERIC; + this.data = data; + } + AlphanumericData.getBitsLength = function getBitsLength(length2) { + return 11 * Math.floor(length2 / 2) + 6 * (length2 % 2); + }; + AlphanumericData.prototype.getLength = function getLength() { + return this.data.length; + }; + AlphanumericData.prototype.getBitsLength = function getBitsLength() { + return AlphanumericData.getBitsLength(this.data.length); + }; + AlphanumericData.prototype.write = function write(bitBuffer) { + let i2; + for (i2 = 0; i2 + 2 <= this.data.length; i2 += 2) { + let value = ALPHA_NUM_CHARS.indexOf(this.data[i2]) * 45; + value += ALPHA_NUM_CHARS.indexOf(this.data[i2 + 1]); + bitBuffer.put(value, 11); + } + if (this.data.length % 2) { + bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i2]), 6); + } + }; + module2.exports = AlphanumericData; + } +}); + +// node_modules/encode-utf8/index.js +var require_encode_utf8 = __commonJS({ + "node_modules/encode-utf8/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function encodeUtf8(input) { + var result = []; + var size = input.length; + for (var index = 0; index < size; index++) { + var point = input.charCodeAt(index); + if (point >= 55296 && point <= 56319 && size > index + 1) { + var second = input.charCodeAt(index + 1); + if (second >= 56320 && second <= 57343) { + point = (point - 55296) * 1024 + second - 56320 + 65536; + index += 1; + } + } + if (point < 128) { + result.push(point); + continue; + } + if (point < 2048) { + result.push(point >> 6 | 192); + result.push(point & 63 | 128); + continue; + } + if (point < 55296 || point >= 57344 && point < 65536) { + result.push(point >> 12 | 224); + result.push(point >> 6 & 63 | 128); + result.push(point & 63 | 128); + continue; + } + if (point >= 65536 && point <= 1114111) { + result.push(point >> 18 | 240); + result.push(point >> 12 & 63 | 128); + result.push(point >> 6 & 63 | 128); + result.push(point & 63 | 128); + continue; + } + result.push(239, 191, 189); + } + return new Uint8Array(result).buffer; + }; + } +}); + +// node_modules/qrcode/lib/core/byte-data.js +var require_byte_data = __commonJS({ + "node_modules/qrcode/lib/core/byte-data.js"(exports2, module2) { + init_shim(); + var encodeUtf8 = require_encode_utf8(); + var Mode = require_mode(); + function ByteData(data) { + this.mode = Mode.BYTE; + if (typeof data === "string") { + data = encodeUtf8(data); + } + this.data = new Uint8Array(data); + } + ByteData.getBitsLength = function getBitsLength(length2) { + return length2 * 8; + }; + ByteData.prototype.getLength = function getLength() { + return this.data.length; + }; + ByteData.prototype.getBitsLength = function getBitsLength() { + return ByteData.getBitsLength(this.data.length); + }; + ByteData.prototype.write = function(bitBuffer) { + for (let i2 = 0, l4 = this.data.length; i2 < l4; i2++) { + bitBuffer.put(this.data[i2], 8); + } + }; + module2.exports = ByteData; + } +}); + +// node_modules/qrcode/lib/core/kanji-data.js +var require_kanji_data = __commonJS({ + "node_modules/qrcode/lib/core/kanji-data.js"(exports2, module2) { + init_shim(); + var Mode = require_mode(); + var Utils = require_utils6(); + function KanjiData(data) { + this.mode = Mode.KANJI; + this.data = data; + } + KanjiData.getBitsLength = function getBitsLength(length2) { + return length2 * 13; + }; + KanjiData.prototype.getLength = function getLength() { + return this.data.length; + }; + KanjiData.prototype.getBitsLength = function getBitsLength() { + return KanjiData.getBitsLength(this.data.length); + }; + KanjiData.prototype.write = function(bitBuffer) { + let i2; + for (i2 = 0; i2 < this.data.length; i2++) { + let value = Utils.toSJIS(this.data[i2]); + if (value >= 33088 && value <= 40956) { + value -= 33088; + } else if (value >= 57408 && value <= 60351) { + value -= 49472; + } else { + throw new Error( + "Invalid SJIS character: " + this.data[i2] + "\nMake sure your charset is UTF-8" + ); + } + value = (value >>> 8 & 255) * 192 + (value & 255); + bitBuffer.put(value, 13); + } + }; + module2.exports = KanjiData; + } +}); + +// node_modules/dijkstrajs/dijkstra.js +var require_dijkstra = __commonJS({ + "node_modules/dijkstrajs/dijkstra.js"(exports2, module2) { + "use strict"; + init_shim(); + var dijkstra = { + single_source_shortest_paths: function(graph, s2, d3) { + var predecessors = {}; + var costs = {}; + costs[s2] = 0; + var open = dijkstra.PriorityQueue.make(); + open.push(s2, 0); + var closest, u3, v2, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit; + while (!open.empty()) { + closest = open.pop(); + u3 = closest.value; + cost_of_s_to_u = closest.cost; + adjacent_nodes = graph[u3] || {}; + for (v2 in adjacent_nodes) { + if (adjacent_nodes.hasOwnProperty(v2)) { + cost_of_e = adjacent_nodes[v2]; + cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; + cost_of_s_to_v = costs[v2]; + first_visit = typeof costs[v2] === "undefined"; + if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { + costs[v2] = cost_of_s_to_u_plus_cost_of_e; + open.push(v2, cost_of_s_to_u_plus_cost_of_e); + predecessors[v2] = u3; + } + } + } + } + if (typeof d3 !== "undefined" && typeof costs[d3] === "undefined") { + var msg = ["Could not find a path from ", s2, " to ", d3, "."].join(""); + throw new Error(msg); + } + return predecessors; + }, + extract_shortest_path_from_predecessor_list: function(predecessors, d3) { + var nodes = []; + var u3 = d3; + var predecessor; + while (u3) { + nodes.push(u3); + predecessor = predecessors[u3]; + u3 = predecessors[u3]; + } + nodes.reverse(); + return nodes; + }, + find_path: function(graph, s2, d3) { + var predecessors = dijkstra.single_source_shortest_paths(graph, s2, d3); + return dijkstra.extract_shortest_path_from_predecessor_list( + predecessors, + d3 + ); + }, + /** + * A very naive priority queue implementation. + */ + PriorityQueue: { + make: function(opts) { + var T2 = dijkstra.PriorityQueue, t = {}, key; + opts = opts || {}; + for (key in T2) { + if (T2.hasOwnProperty(key)) { + t[key] = T2[key]; + } + } + t.queue = []; + t.sorter = opts.sorter || T2.default_sorter; + return t; + }, + default_sorter: function(a3, b4) { + return a3.cost - b4.cost; + }, + /** + * Add a new item to the queue and ensure the highest priority element + * is at the front of the queue. + */ + push: function(value, cost) { + var item = { value, cost }; + this.queue.push(item); + this.queue.sort(this.sorter); + }, + /** + * Return the highest priority element in the queue. + */ + pop: function() { + return this.queue.shift(); + }, + empty: function() { + return this.queue.length === 0; + } + } + }; + if (typeof module2 !== "undefined") { + module2.exports = dijkstra; + } + } +}); + +// node_modules/qrcode/lib/core/segments.js +var require_segments = __commonJS({ + "node_modules/qrcode/lib/core/segments.js"(exports2) { + init_shim(); + var Mode = require_mode(); + var NumericData = require_numeric_data(); + var AlphanumericData = require_alphanumeric_data(); + var ByteData = require_byte_data(); + var KanjiData = require_kanji_data(); + var Regex = require_regex(); + var Utils = require_utils6(); + var dijkstra = require_dijkstra(); + function getStringByteLength(str) { + return unescape(encodeURIComponent(str)).length; + } + function getSegments(regex, mode, str) { + const segments = []; + let result; + while ((result = regex.exec(str)) !== null) { + segments.push({ + data: result[0], + index: result.index, + mode, + length: result[0].length + }); + } + return segments; + } + function getSegmentsFromString(dataStr) { + const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr); + const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr); + let byteSegs; + let kanjiSegs; + if (Utils.isKanjiModeEnabled()) { + byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr); + kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr); + } else { + byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr); + kanjiSegs = []; + } + const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs); + return segs.sort(function(s1, s2) { + return s1.index - s2.index; + }).map(function(obj) { + return { + data: obj.data, + mode: obj.mode, + length: obj.length + }; + }); + } + function getSegmentBitsLength(length2, mode) { + switch (mode) { + case Mode.NUMERIC: + return NumericData.getBitsLength(length2); + case Mode.ALPHANUMERIC: + return AlphanumericData.getBitsLength(length2); + case Mode.KANJI: + return KanjiData.getBitsLength(length2); + case Mode.BYTE: + return ByteData.getBitsLength(length2); + } + } + function mergeSegments(segs) { + return segs.reduce(function(acc, curr) { + const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null; + if (prevSeg && prevSeg.mode === curr.mode) { + acc[acc.length - 1].data += curr.data; + return acc; + } + acc.push(curr); + return acc; + }, []); + } + function buildNodes(segs) { + const nodes = []; + for (let i2 = 0; i2 < segs.length; i2++) { + const seg = segs[i2]; + switch (seg.mode) { + case Mode.NUMERIC: + nodes.push([ + seg, + { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]); + break; + case Mode.ALPHANUMERIC: + nodes.push([ + seg, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]); + break; + case Mode.KANJI: + nodes.push([ + seg, + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]); + break; + case Mode.BYTE: + nodes.push([ + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]); + } + } + return nodes; + } + function buildGraph(nodes, version2) { + const table = {}; + const graph = { start: {} }; + let prevNodeIds = ["start"]; + for (let i2 = 0; i2 < nodes.length; i2++) { + const nodeGroup = nodes[i2]; + const currentNodeIds = []; + for (let j2 = 0; j2 < nodeGroup.length; j2++) { + const node = nodeGroup[j2]; + const key = "" + i2 + j2; + currentNodeIds.push(key); + table[key] = { node, lastCount: 0 }; + graph[key] = {}; + for (let n3 = 0; n3 < prevNodeIds.length; n3++) { + const prevNodeId = prevNodeIds[n3]; + if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { + graph[prevNodeId][key] = getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - getSegmentBitsLength(table[prevNodeId].lastCount, node.mode); + table[prevNodeId].lastCount += node.length; + } else { + if (table[prevNodeId]) + table[prevNodeId].lastCount = node.length; + graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + 4 + Mode.getCharCountIndicator(node.mode, version2); + } + } + } + prevNodeIds = currentNodeIds; + } + for (let n3 = 0; n3 < prevNodeIds.length; n3++) { + graph[prevNodeIds[n3]].end = 0; + } + return { map: graph, table }; + } + function buildSingleSegment(data, modesHint) { + let mode; + const bestMode = Mode.getBestModeForData(data); + mode = Mode.from(modesHint, bestMode); + if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { + throw new Error('"' + data + '" cannot be encoded with mode ' + Mode.toString(mode) + ".\n Suggested mode is: " + Mode.toString(bestMode)); + } + if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { + mode = Mode.BYTE; + } + switch (mode) { + case Mode.NUMERIC: + return new NumericData(data); + case Mode.ALPHANUMERIC: + return new AlphanumericData(data); + case Mode.KANJI: + return new KanjiData(data); + case Mode.BYTE: + return new ByteData(data); + } + } + exports2.fromArray = function fromArray(array) { + return array.reduce(function(acc, seg) { + if (typeof seg === "string") { + acc.push(buildSingleSegment(seg, null)); + } else if (seg.data) { + acc.push(buildSingleSegment(seg.data, seg.mode)); + } + return acc; + }, []); + }; + exports2.fromString = function fromString3(data, version2) { + const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()); + const nodes = buildNodes(segs); + const graph = buildGraph(nodes, version2); + const path = dijkstra.find_path(graph.map, "start", "end"); + const optimizedSegs = []; + for (let i2 = 1; i2 < path.length - 1; i2++) { + optimizedSegs.push(graph.table[path[i2]].node); + } + return exports2.fromArray(mergeSegments(optimizedSegs)); + }; + exports2.rawSplit = function rawSplit(data) { + return exports2.fromArray( + getSegmentsFromString(data, Utils.isKanjiModeEnabled()) + ); + }; + } +}); + +// node_modules/qrcode/lib/core/qrcode.js +var require_qrcode = __commonJS({ + "node_modules/qrcode/lib/core/qrcode.js"(exports2) { + init_shim(); + var Utils = require_utils6(); + var ECLevel = require_error_correction_level(); + var BitBuffer = require_bit_buffer(); + var BitMatrix = require_bit_matrix(); + var AlignmentPattern = require_alignment_pattern(); + var FinderPattern = require_finder_pattern(); + var MaskPattern = require_mask_pattern(); + var ECCode = require_error_correction_code(); + var ReedSolomonEncoder = require_reed_solomon_encoder(); + var Version = require_version(); + var FormatInfo = require_format_info(); + var Mode = require_mode(); + var Segments = require_segments(); + function setupFinderPattern(matrix, version2) { + const size = matrix.size; + const pos = FinderPattern.getPositions(version2); + for (let i2 = 0; i2 < pos.length; i2++) { + const row = pos[i2][0]; + const col = pos[i2][1]; + for (let r = -1; r <= 7; r++) { + if (row + r <= -1 || size <= row + r) + continue; + for (let c4 = -1; c4 <= 7; c4++) { + if (col + c4 <= -1 || size <= col + c4) + continue; + if (r >= 0 && r <= 6 && (c4 === 0 || c4 === 6) || c4 >= 0 && c4 <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c4 >= 2 && c4 <= 4) { + matrix.set(row + r, col + c4, true, true); + } else { + matrix.set(row + r, col + c4, false, true); + } + } + } + } + } + function setupTimingPattern(matrix) { + const size = matrix.size; + for (let r = 8; r < size - 8; r++) { + const value = r % 2 === 0; + matrix.set(r, 6, value, true); + matrix.set(6, r, value, true); + } + } + function setupAlignmentPattern(matrix, version2) { + const pos = AlignmentPattern.getPositions(version2); + for (let i2 = 0; i2 < pos.length; i2++) { + const row = pos[i2][0]; + const col = pos[i2][1]; + for (let r = -2; r <= 2; r++) { + for (let c4 = -2; c4 <= 2; c4++) { + if (r === -2 || r === 2 || c4 === -2 || c4 === 2 || r === 0 && c4 === 0) { + matrix.set(row + r, col + c4, true, true); + } else { + matrix.set(row + r, col + c4, false, true); + } + } + } + } + } + function setupVersionInfo(matrix, version2) { + const size = matrix.size; + const bits = Version.getEncodedBits(version2); + let row, col, mod2; + for (let i2 = 0; i2 < 18; i2++) { + row = Math.floor(i2 / 3); + col = i2 % 3 + size - 8 - 3; + mod2 = (bits >> i2 & 1) === 1; + matrix.set(row, col, mod2, true); + matrix.set(col, row, mod2, true); + } + } + function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) { + const size = matrix.size; + const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern); + let i2, mod2; + for (i2 = 0; i2 < 15; i2++) { + mod2 = (bits >> i2 & 1) === 1; + if (i2 < 6) { + matrix.set(i2, 8, mod2, true); + } else if (i2 < 8) { + matrix.set(i2 + 1, 8, mod2, true); + } else { + matrix.set(size - 15 + i2, 8, mod2, true); + } + if (i2 < 8) { + matrix.set(8, size - i2 - 1, mod2, true); + } else if (i2 < 9) { + matrix.set(8, 15 - i2 - 1 + 1, mod2, true); + } else { + matrix.set(8, 15 - i2 - 1, mod2, true); + } + } + matrix.set(size - 8, 8, 1, true); + } + function setupData(matrix, data) { + const size = matrix.size; + let inc = -1; + let row = size - 1; + let bitIndex = 7; + let byteIndex = 0; + for (let col = size - 1; col > 0; col -= 2) { + if (col === 6) + col--; + while (true) { + for (let c4 = 0; c4 < 2; c4++) { + if (!matrix.isReserved(row, col - c4)) { + let dark = false; + if (byteIndex < data.length) { + dark = (data[byteIndex] >>> bitIndex & 1) === 1; + } + matrix.set(row, col - c4, dark); + bitIndex--; + if (bitIndex === -1) { + byteIndex++; + bitIndex = 7; + } + } + } + row += inc; + if (row < 0 || size <= row) { + row -= inc; + inc = -inc; + break; + } + } + } + } + function createData(version2, errorCorrectionLevel, segments) { + const buffer = new BitBuffer(); + segments.forEach(function(data) { + buffer.put(data.mode.bit, 4); + buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version2)); + data.write(buffer); + }); + const totalCodewords = Utils.getSymbolTotalCodewords(version2); + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; + if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) { + buffer.put(0, 4); + } + while (buffer.getLengthInBits() % 8 !== 0) { + buffer.putBit(0); + } + const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8; + for (let i2 = 0; i2 < remainingByte; i2++) { + buffer.put(i2 % 2 ? 17 : 236, 8); + } + return createCodewords(buffer, version2, errorCorrectionLevel); + } + function createCodewords(bitBuffer, version2, errorCorrectionLevel) { + const totalCodewords = Utils.getSymbolTotalCodewords(version2); + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); + const dataTotalCodewords = totalCodewords - ecTotalCodewords; + const ecTotalBlocks = ECCode.getBlocksCount(version2, errorCorrectionLevel); + const blocksInGroup2 = totalCodewords % ecTotalBlocks; + const blocksInGroup1 = ecTotalBlocks - blocksInGroup2; + const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks); + const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks); + const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1; + const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1; + const rs = new ReedSolomonEncoder(ecCount); + let offset = 0; + const dcData = new Array(ecTotalBlocks); + const ecData = new Array(ecTotalBlocks); + let maxDataSize = 0; + const buffer = new Uint8Array(bitBuffer.buffer); + for (let b4 = 0; b4 < ecTotalBlocks; b4++) { + const dataSize = b4 < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2; + dcData[b4] = buffer.slice(offset, offset + dataSize); + ecData[b4] = rs.encode(dcData[b4]); + offset += dataSize; + maxDataSize = Math.max(maxDataSize, dataSize); + } + const data = new Uint8Array(totalCodewords); + let index = 0; + let i2, r; + for (i2 = 0; i2 < maxDataSize; i2++) { + for (r = 0; r < ecTotalBlocks; r++) { + if (i2 < dcData[r].length) { + data[index++] = dcData[r][i2]; + } + } + } + for (i2 = 0; i2 < ecCount; i2++) { + for (r = 0; r < ecTotalBlocks; r++) { + data[index++] = ecData[r][i2]; + } + } + return data; + } + function createSymbol(data, version2, errorCorrectionLevel, maskPattern) { + let segments; + if (Array.isArray(data)) { + segments = Segments.fromArray(data); + } else if (typeof data === "string") { + let estimatedVersion = version2; + if (!estimatedVersion) { + const rawSegments = Segments.rawSplit(data); + estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel); + } + segments = Segments.fromString(data, estimatedVersion || 40); + } else { + throw new Error("Invalid data"); + } + const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel); + if (!bestVersion) { + throw new Error("The amount of data is too big to be stored in a QR Code"); + } + if (!version2) { + version2 = bestVersion; + } else if (version2 < bestVersion) { + throw new Error( + "\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: " + bestVersion + ".\n" + ); + } + const dataBits = createData(version2, errorCorrectionLevel, segments); + const moduleCount = Utils.getSymbolSize(version2); + const modules = new BitMatrix(moduleCount); + setupFinderPattern(modules, version2); + setupTimingPattern(modules); + setupAlignmentPattern(modules, version2); + setupFormatInfo(modules, errorCorrectionLevel, 0); + if (version2 >= 7) { + setupVersionInfo(modules, version2); + } + setupData(modules, dataBits); + if (isNaN(maskPattern)) { + maskPattern = MaskPattern.getBestMask( + modules, + setupFormatInfo.bind(null, modules, errorCorrectionLevel) + ); + } + MaskPattern.applyMask(maskPattern, modules); + setupFormatInfo(modules, errorCorrectionLevel, maskPattern); + return { + modules, + version: version2, + errorCorrectionLevel, + maskPattern, + segments + }; + } + exports2.create = function create2(data, options) { + if (typeof data === "undefined" || data === "") { + throw new Error("No input text"); + } + let errorCorrectionLevel = ECLevel.M; + let version2; + let mask; + if (typeof options !== "undefined") { + errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M); + version2 = Version.from(options.version); + mask = MaskPattern.from(options.maskPattern); + if (options.toSJISFunc) { + Utils.setToSJISFunction(options.toSJISFunc); + } + } + return createSymbol(data, version2, errorCorrectionLevel, mask); + }; + } +}); + +// node_modules/qrcode/lib/renderer/utils.js +var require_utils7 = __commonJS({ + "node_modules/qrcode/lib/renderer/utils.js"(exports2) { + init_shim(); + function hex2rgba(hex) { + if (typeof hex === "number") { + hex = hex.toString(); + } + if (typeof hex !== "string") { + throw new Error("Color should be defined as hex string"); + } + let hexCode = hex.slice().replace("#", "").split(""); + if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { + throw new Error("Invalid hex color: " + hex); + } + if (hexCode.length === 3 || hexCode.length === 4) { + hexCode = Array.prototype.concat.apply([], hexCode.map(function(c4) { + return [c4, c4]; + })); + } + if (hexCode.length === 6) + hexCode.push("F", "F"); + const hexValue = parseInt(hexCode.join(""), 16); + return { + r: hexValue >> 24 & 255, + g: hexValue >> 16 & 255, + b: hexValue >> 8 & 255, + a: hexValue & 255, + hex: "#" + hexCode.slice(0, 6).join("") + }; + } + exports2.getOptions = function getOptions(options) { + if (!options) + options = {}; + if (!options.color) + options.color = {}; + const margin = typeof options.margin === "undefined" || options.margin === null || options.margin < 0 ? 4 : options.margin; + const width = options.width && options.width >= 21 ? options.width : void 0; + const scale = options.scale || 4; + return { + width, + scale: width ? 4 : scale, + margin, + color: { + dark: hex2rgba(options.color.dark || "#000000ff"), + light: hex2rgba(options.color.light || "#ffffffff") + }, + type: options.type, + rendererOpts: options.rendererOpts || {} + }; + }; + exports2.getScale = function getScale(qrSize, opts) { + return opts.width && opts.width >= qrSize + opts.margin * 2 ? opts.width / (qrSize + opts.margin * 2) : opts.scale; + }; + exports2.getImageWidth = function getImageWidth(qrSize, opts) { + const scale = exports2.getScale(qrSize, opts); + return Math.floor((qrSize + opts.margin * 2) * scale); + }; + exports2.qrToImageData = function qrToImageData(imgData, qr, opts) { + const size = qr.modules.size; + const data = qr.modules.data; + const scale = exports2.getScale(size, opts); + const symbolSize = Math.floor((size + opts.margin * 2) * scale); + const scaledMargin = opts.margin * scale; + const palette = [opts.color.light, opts.color.dark]; + for (let i2 = 0; i2 < symbolSize; i2++) { + for (let j2 = 0; j2 < symbolSize; j2++) { + let posDst = (i2 * symbolSize + j2) * 4; + let pxColor = opts.color.light; + if (i2 >= scaledMargin && j2 >= scaledMargin && i2 < symbolSize - scaledMargin && j2 < symbolSize - scaledMargin) { + const iSrc = Math.floor((i2 - scaledMargin) / scale); + const jSrc = Math.floor((j2 - scaledMargin) / scale); + pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]; + } + imgData[posDst++] = pxColor.r; + imgData[posDst++] = pxColor.g; + imgData[posDst++] = pxColor.b; + imgData[posDst] = pxColor.a; + } + } + }; + } +}); + +// node_modules/qrcode/lib/renderer/canvas.js +var require_canvas = __commonJS({ + "node_modules/qrcode/lib/renderer/canvas.js"(exports2) { + init_shim(); + var Utils = require_utils7(); + function clearCanvas(ctx, canvas, size) { + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (!canvas.style) + canvas.style = {}; + canvas.height = size; + canvas.width = size; + canvas.style.height = size + "px"; + canvas.style.width = size + "px"; + } + function getCanvasElement() { + try { + return document.createElement("canvas"); + } catch (e2) { + throw new Error("You need to specify a canvas element"); + } + } + exports2.render = function render(qrData, canvas, options) { + let opts = options; + let canvasEl = canvas; + if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { + opts = canvas; + canvas = void 0; + } + if (!canvas) { + canvasEl = getCanvasElement(); + } + opts = Utils.getOptions(opts); + const size = Utils.getImageWidth(qrData.modules.size, opts); + const ctx = canvasEl.getContext("2d"); + const image = ctx.createImageData(size, size); + Utils.qrToImageData(image.data, qrData, opts); + clearCanvas(ctx, canvasEl, size); + ctx.putImageData(image, 0, 0); + return canvasEl; + }; + exports2.renderToDataURL = function renderToDataURL(qrData, canvas, options) { + let opts = options; + if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { + opts = canvas; + canvas = void 0; + } + if (!opts) + opts = {}; + const canvasEl = exports2.render(qrData, canvas, opts); + const type = opts.type || "image/png"; + const rendererOpts = opts.rendererOpts || {}; + return canvasEl.toDataURL(type, rendererOpts.quality); + }; + } +}); + +// node_modules/qrcode/lib/renderer/svg-tag.js +var require_svg_tag = __commonJS({ + "node_modules/qrcode/lib/renderer/svg-tag.js"(exports2) { + init_shim(); + var Utils = require_utils7(); + function getColorAttrib(color, attrib) { + const alpha = color.a / 255; + const str = attrib + '="' + color.hex + '"'; + return alpha < 1 ? str + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str; + } + function svgCmd(cmd, x3, y4) { + let str = cmd + x3; + if (typeof y4 !== "undefined") + str += " " + y4; + return str; + } + function qrToPath(data, size, margin) { + let path = ""; + let moveBy = 0; + let newRow = false; + let lineLength = 0; + for (let i2 = 0; i2 < data.length; i2++) { + const col = Math.floor(i2 % size); + const row = Math.floor(i2 / size); + if (!col && !newRow) + newRow = true; + if (data[i2]) { + lineLength++; + if (!(i2 > 0 && col > 0 && data[i2 - 1])) { + path += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0); + moveBy = 0; + newRow = false; + } + if (!(col + 1 < size && data[i2 + 1])) { + path += svgCmd("h", lineLength); + lineLength = 0; + } + } else { + moveBy++; + } + } + return path; + } + exports2.render = function render(qrData, options, cb) { + const opts = Utils.getOptions(options); + const size = qrData.modules.size; + const data = qrData.modules.data; + const qrcodesize = size + opts.margin * 2; + const bg = !opts.color.light.a ? "" : "'; + const path = "'; + const viewBox = 'viewBox="0 0 ' + qrcodesize + " " + qrcodesize + '"'; + const width = !opts.width ? "" : 'width="' + opts.width + '" height="' + opts.width + '" '; + const svgTag = '' + bg + path + "\n"; + if (typeof cb === "function") { + cb(null, svgTag); + } + return svgTag; + }; + } +}); + +// node_modules/qrcode/lib/browser.js +var require_browser7 = __commonJS({ + "node_modules/qrcode/lib/browser.js"(exports2) { + init_shim(); + var canPromise = require_can_promise(); + var QRCode2 = require_qrcode(); + var CanvasRenderer = require_canvas(); + var SvgRenderer = require_svg_tag(); + function renderCanvas(renderFunc, canvas, text, opts, cb) { + const args = [].slice.call(arguments, 1); + const argsNum = args.length; + const isLastArgCb = typeof args[argsNum - 1] === "function"; + if (!isLastArgCb && !canPromise()) { + throw new Error("Callback required as last argument"); + } + if (isLastArgCb) { + if (argsNum < 2) { + throw new Error("Too few arguments provided"); + } + if (argsNum === 2) { + cb = text; + text = canvas; + canvas = opts = void 0; + } else if (argsNum === 3) { + if (canvas.getContext && typeof cb === "undefined") { + cb = opts; + opts = void 0; + } else { + cb = opts; + opts = text; + text = canvas; + canvas = void 0; + } + } + } else { + if (argsNum < 1) { + throw new Error("Too few arguments provided"); + } + if (argsNum === 1) { + text = canvas; + canvas = opts = void 0; + } else if (argsNum === 2 && !canvas.getContext) { + opts = text; + text = canvas; + canvas = void 0; + } + return new Promise(function(resolve, reject) { + try { + const data = QRCode2.create(text, opts); + resolve(renderFunc(data, canvas, opts)); + } catch (e2) { + reject(e2); + } + }); + } + try { + const data = QRCode2.create(text, opts); + cb(null, renderFunc(data, canvas, opts)); + } catch (e2) { + cb(e2); + } + } + exports2.create = QRCode2.create; + exports2.toCanvas = renderCanvas.bind(null, CanvasRenderer.render); + exports2.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL); + exports2.toString = renderCanvas.bind(null, function(data, _4, opts) { + return SvgRenderer.render(data, opts); + }); + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/index.js +var require_out2 = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_walletProvider(), exports2); + __exportStar2(require_constants7(), exports2); + } +}); + +// src/elven.ts +init_shim(); +var import_tokens = __toESM(require_tokens(), 1); +var import_tokenOperations = __toESM(require_tokenOperations(), 1); +var import_transactionsFactories = __toESM(require_transactionsFactories(), 1); +var import_transactionsOutcomeParsers = __toESM(require_transactionsOutcomeParsers(), 1); +var import_address4 = __toESM(require_address(), 1); +var import_account4 = __toESM(require_account(), 1); +var import_transaction3 = __toESM(require_transaction(), 1); +var import_transactionComputer = __toESM(require_transactionComputer(), 1); +var import_message = __toESM(require_message(), 1); +var import_transactionWatcher2 = __toESM(require_transactionWatcher(), 1); +var import_signableMessage2 = __toESM(require_signableMessage(), 1); +var import_bytes7 = __toESM(require_bytes(), 1); +var import_numerical = __toESM(require_numerical(), 1); +var import_boolean = __toESM(require_boolean(), 1); +var import_address5 = __toESM(require_address2(), 1); +var import_interface = __toESM(require_interface(), 1); +var import_contractQueryResponse2 = __toESM(require_contractQueryResponse(), 1); + +// src/main.ts +init_shim(); + +// src/auth/init-extension-provider.ts +init_shim(); +var import_extensionProvider = __toESM(require_extensionProvider(), 1); + +// src/utils/ls-helpers.ts +init_shim(); + +// src/utils/constants.ts +init_shim(); +var LOCAL_STORAGE_KEY = "elvenjs_state"; +var defaultApiEndpoint = "https://devnet-api.multiversx.com"; +var DAPP_INIT_ROUTE = "/dapp/init"; +var defaultChainTypeConfig = "devnet"; +var walletConnectDeepLink = "https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/"; +var defaultWalletConnectV2RelayAddresses = [ + "wss://relay.walletconnect.com" +]; +var networkConfig = { + devnet: { + id: "devnet", + shortId: "D", + name: "Devnet", + egldLabel: "xEGLD", + egldDenomination: "18", + decimals: "4", + gasPerDataByte: "1500", + walletAddress: "https://devnet-wallet.multiversx.com", + xAliasAddress: "https://devnet.xalias.com", + apiAddress: "https://devnet-api.multiversx.com", + explorerAddress: "https://devnet-explorer.multiversx.com", + apiTimeout: 1e4 + }, + testnet: { + id: "testnet", + shortId: "T", + name: "Testnet", + egldLabel: "xEGLD", + egldDenomination: "18", + decimals: "4", + gasPerDataByte: "1500", + walletAddress: "https://testnet-wallet.multiversx.com", + xAliasAddress: "https://testnet.xalias.com", + apiAddress: "https://testnet-api.multiversx.com", + explorerAddress: "https://testnet-explorer.multiversx.com", + apiTimeout: 1e4 + }, + mainnet: { + id: "mainnet", + shortId: "1", + name: "Mainnet", + egldLabel: "EGLD", + egldDenomination: "18", + decimals: "4", + gasPerDataByte: "1500", + walletAddress: "https://wallet.multiversx.com", + xAliasAddress: "https://xalias.com", + apiAddress: "https://api.multiversx.com", + explorerAddress: "https://explorer.multiversx.com", + apiTimeout: 1e4 + } +}; + +// src/utils/ls-helpers.ts +var ls = { + get(key) { + const state = localStorage.getItem(LOCAL_STORAGE_KEY); + if (!state) + return {}; + const parsedState = JSON.parse(state); + if (key) { + return parsedState[key]; + } + return parsedState; + }, + set(key, value) { + const currentState = this.get(); + currentState[key] = value; + localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(currentState)); + }, + clear() { + localStorage.removeItem(LOCAL_STORAGE_KEY); + } +}; + +// src/auth/init-extension-provider.ts +var initExtensionProvider = async () => { + const dappProvider = import_extensionProvider.ExtensionProvider.getInstance(); + try { + const isSuccessfullyInitialized = await dappProvider.init(); + const currentState = ls.get(); + if (currentState?.address) { + dappProvider.setAddress(currentState.address); + } + if (!isSuccessfullyInitialized) { + console.warn( + "Something went wrong when trying to initialize the ExtensionProvider.." + ); + return; + } + return dappProvider; + } catch (e2) { + console.warn("Can't initialize the Dapp Provider!"); + } +}; + +// src/main.ts +var import_extensionProvider2 = __toESM(require_extensionProvider(), 1); +var import_walletConnectV2Provider4 = __toESM(require_walletConnectV2Provider(), 1); +var import_walletProvider4 = __toESM(require_walletProvider(), 1); +var import_native_auth2 = __toESM(require_native_auth_client(), 1); +var import_signableMessage = __toESM(require_signableMessage(), 1); + +// src/auth/init-mobile-provider.ts +init_shim(); +var import_walletConnectV2Provider = __toESM(require_walletConnectV2Provider(), 1); + +// src/auth/logout.ts +init_shim(); + +// src/events-store.ts +init_shim(); +var EventsStore = class { + static set(name2, fn) { + if (!name2) + return; + const eventsObj = { ...this.events, [name2]: fn }; + this.events = eventsObj; + } + static get(name2) { + if (!name2 || !this.events) + return; + return this.events[name2]; + } + static run(name2, ...args) { + if (!name2 || !this.events) + return; + this.events[name2]?.(...args); + } + static clear() { + this.events = void 0; + } +}; + +// src/types.ts +init_shim(); +var EventStoreEvents = /* @__PURE__ */ ((EventStoreEvents2) => { + EventStoreEvents2["onLoginStart"] = "onLoginStart"; + EventStoreEvents2["onLoginSuccess"] = "onLoginSuccess"; + EventStoreEvents2["onLoginFailure"] = "onLoginFailure"; + EventStoreEvents2["onLogoutStart"] = "onLogoutStart"; + EventStoreEvents2["onLogoutSuccess"] = "onLogoutSuccess"; + EventStoreEvents2["onLogoutFailure"] = "onLogoutFailure"; + EventStoreEvents2["onQrPending"] = "onQrPending"; + EventStoreEvents2["onQrLoaded"] = "onQrLoaded"; + EventStoreEvents2["onTxStart"] = "onTxStart"; + EventStoreEvents2["onTxSent"] = "onTxSent"; + EventStoreEvents2["onTxFinalized"] = "onTxFinalized"; + EventStoreEvents2["onTxFailure"] = "onTxFailure"; + EventStoreEvents2["onSignMsgStart"] = "onSignMsgStart"; + EventStoreEvents2["onSignMsgFinalized"] = "onSignMsgFinalized"; + EventStoreEvents2["onSignMsgFailure"] = "onSignMsgFailure"; + EventStoreEvents2["onQueryStart"] = "onQueryStart"; + EventStoreEvents2["onQueryFinalized"] = "onQueryFinalized"; + EventStoreEvents2["onQueryFailure"] = "onQueryFailure"; + return EventStoreEvents2; +})(EventStoreEvents || {}); +var LoginMethodsEnum = /* @__PURE__ */ ((LoginMethodsEnum2) => { + LoginMethodsEnum2["ledger"] = "ledger"; + LoginMethodsEnum2["mobile"] = "mobile"; + LoginMethodsEnum2["webWallet"] = "web-wallet"; + LoginMethodsEnum2["browserExtension"] = "browser-extension"; + LoginMethodsEnum2["xAlias"] = "x-alias"; + LoginMethodsEnum2["xPortalHub"] = "x-portal-hub"; + return LoginMethodsEnum2; +})(LoginMethodsEnum || {}); +var DappCoreWCV2CustomMethodsEnum = /* @__PURE__ */ ((DappCoreWCV2CustomMethodsEnum2) => { + DappCoreWCV2CustomMethodsEnum2["mvx_cancelAction"] = "mvx_cancelAction"; + DappCoreWCV2CustomMethodsEnum2["mvx_signNativeAuthToken"] = "mvx_signNativeAuthToken"; + return DappCoreWCV2CustomMethodsEnum2; +})(DappCoreWCV2CustomMethodsEnum || {}); +var WebWalletUrlParamsEnum = /* @__PURE__ */ ((WebWalletUrlParamsEnum2) => { + WebWalletUrlParamsEnum2["hasWebWalletGuardianSign"] = "hasWebWalletGuardianSign"; + return WebWalletUrlParamsEnum2; +})(WebWalletUrlParamsEnum || {}); + +// src/utils/error-parse.ts +init_shim(); +var errorParse = (err) => { + if (typeof err === "string") { + return err.toUpperCase(); + } else if (err instanceof Error) { + return err.message; + } + return JSON.stringify(err); +}; + +// src/auth/logout.ts +var logout = async (elven) => { + if (!elven.dappProvider) { + throw new Error("Logout failed: There is no active session!"); + } + EventsStore.run("onLogoutStart" /* onLogoutStart */); + try { + const isLoggedOut = await elven.dappProvider.logout(); + if (isLoggedOut) { + ls.clear(); + EventsStore.run("onLogoutSuccess" /* onLogoutSuccess */); + } + return isLoggedOut; + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to logout the user: ${err}`); + EventsStore.run("onLogoutFailure" /* onLogoutFailure */, err); + } +}; + +// src/utils/get-random-address-from-network.ts +init_shim(); +function getRandomAddressFromNetwork(addresses) { + return addresses[Math.floor(Math.random() * addresses.length)]; +} + +// src/auth/init-mobile-provider.ts +var initMobileProvider = async (elven) => { + if (!elven.initOptions.walletConnectV2ProjectId || !elven.initOptions.chainType) { + return void 0; + } + const providerHandlers = { + onClientLogin: () => { + }, + onClientLogout: () => logout(elven), + onClientEvent: (event) => { + console.log("wc2 session event: ", event); + } + }; + const relayAddress = getRandomAddressFromNetwork( + elven.initOptions.walletConnectV2RelayAddresses + ); + const dappProviderInstance = new import_walletConnectV2Provider.WalletConnectV2Provider( + providerHandlers, + networkConfig[elven.initOptions.chainType].shortId, + relayAddress, + elven.initOptions.walletConnectV2ProjectId + ); + try { + await dappProviderInstance.init(); + return dappProviderInstance; + } catch { + console.warn("Can't initialize the Dapp Provider!"); + } +}; + +// src/network-provider.ts +init_shim(); +var import_address = __toESM(require_address(), 1); +var import_transactionStatus = __toESM(require_transactionStatus(), 1); +var import_transactionReceipt = __toESM(require_transactionReceipt(), 1); +var import_transactionLogs = __toESM(require_transactionLogs(), 1); +var import_contractResults = __toESM(require_contractResults(), 1); +var import_contractQueryResponse = __toESM(require_contractQueryResponse(), 1); +var import_contractQueryRequest = __toESM(require_contractQueryRequest(), 1); +var import_query = __toESM(require_query(), 1); +var ApiNetworkProvider = class { + constructor({ apiUrl, chainType, apiTimeout }) { + this.chainType = chainType || defaultChainTypeConfig; + this.apiUrl = apiUrl || networkConfig[this.chainType]?.apiAddress; + this.apiTimeout = apiTimeout || networkConfig[this.chainType]?.apiTimeout; + } + async apiGet(endpoint, options) { + if (typeof fetch !== "undefined") { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); + const defaultOptions = { + method: "GET", + headers: { + "Content-Type": "application/json", + Accept: "application/json" + }, + signal: controller.signal + }; + try { + const response = await fetch( + this.apiUrl + "/" + endpoint, + Object.assign(defaultOptions, options || {}) + ); + const result = await response.json(); + if (!response.ok) { + const error = result?.error || response.status; + clearTimeout(timeoutId); + return Promise.reject(error); + } + clearTimeout(timeoutId); + return result; + } catch (e2) { + this.handleApiError(e2, endpoint); + } + } + } + async apiPost(endpoint, payload, options) { + if (typeof fetch !== "undefined") { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); + const defaultOptions = { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json" + }, + body: JSON.stringify(payload || {}), + signal: controller.signal + }; + try { + const response = await fetch( + this.apiUrl + "/" + endpoint, + Object.assign(defaultOptions, options || {}) + ); + const result = await response.json(); + if (!response.ok) { + const error = result?.error || response.status; + clearTimeout(timeoutId); + return Promise.reject(error); + } + clearTimeout(timeoutId); + return result; + } catch (e2) { + this.handleApiError(e2, endpoint); + } + } + } + handleApiError(error, resourceUrl) { + if (!error.response) { + throw new Error( + `Request error on url [${resourceUrl}]: [${error.toString()}]` + ); + } + const errorData = error.response.data; + const originalErrorMessage = errorData.error || errorData.message || JSON.stringify(errorData); + throw new Error(originalErrorMessage); + } + async sendTransaction(tx) { + const response = await this.apiPost("transactions", tx.toSendable()); + return response.txHash; + } + async getAccount(address) { + const responsePayload = await this.apiGet(`accounts/${address.bech32()}`); + const account = { + address: new import_address.Address(responsePayload?.address || ""), + nonce: Number(responsePayload?.nonce || 0), + balance: BigInt(responsePayload?.balance || 0), + code: responsePayload?.code || "", + userName: responsePayload?.username || "" + }; + return account; + } + async getGuardianData(address) { + const response = await this.apiGet( + `address/${address.bech32()}/guardian-data` + ); + const accountGuardian = { + guarded: response?.data?.guardianData?.guarded || false, + activeGuardian: response?.data?.guardianData?.activeGuardian, + pendingGuardian: response?.data?.guardianData?.pendingGuardian + }; + return accountGuardian; + } + async getTransaction(txHash) { + const payload = await this.apiGet(`transactions/${txHash}`); + const status = new import_transactionStatus.TransactionStatus(payload.status); + const transaction = { + hash: txHash, + type: payload.type || "", + nonce: payload.nonce || 0, + round: payload.round, + epoch: payload.epoch || 0, + value: (payload.value || 0).toString(), + sender: new import_address.Address(payload.sender), + receiver: new import_address.Address(payload.receiver), + gasPrice: payload.gasPrice || 0, + gasLimit: payload.gasLimit || 0, + data: import_buffer.Buffer.from(payload.data || "", "base64"), + status, + timestamp: payload.timestamp || 0, + blockNonce: payload.blockNonce || 0, + hyperblockNonce: payload.hyperblockNonce || 0, + hyperblockHash: payload.hyperblockHash || "", + receipt: import_transactionReceipt.TransactionReceipt.fromHttpResponse(payload.receipt || {}), + logs: import_transactionLogs.TransactionLogs.fromHttpResponse(payload.logs || {}), + contractResults: import_contractResults.ContractResults.fromApiHttpResponse( + payload.results || [] + ), + isCompleted: !status.isPending() + }; + return transaction; + } + async queryContract({ + address, + func, + args, + value, + caller + }) { + try { + const query = new import_query.Query({ + address, + func, + args, + value, + caller + }); + const request = new import_contractQueryRequest.ContractQueryRequest(query).toHttpRequest(); + const response = await this.apiPost("query", request); + return import_contractQueryResponse.ContractQueryResponse.fromHttpResponse(response); + } catch (e2) { + this.handleApiError(e2, "query"); + } + } +}; + +// src/auth/login-with-extension.ts +init_shim(); + +// src/auth/expires-at.ts +init_shim(); +var getNewLoginExpiresTimestamp = () => { + return (/* @__PURE__ */ new Date()).setHours((/* @__PURE__ */ new Date()).getHours() + 24); +}; +var isLoginExpired = (expirationTimestamp) => { + return Date.now() > expirationTimestamp; +}; + +// src/auth/account-sync.ts +init_shim(); +var import_address2 = __toESM(require_address(), 1); +var import_account = __toESM(require_account(), 1); +var accountSync = async (elven) => { + const address = ls.get("address"); + const loginExpires = ls.get("expires"); + const loginExpired = loginExpires && isLoginExpired(loginExpires); + if (!loginExpired && address && elven.networkProvider) { + const userAddressInstance = new import_address2.Address(address); + const userAccountInstance = new import_account.Account(userAddressInstance); + try { + const userAccountOnNetwork = await elven.networkProvider.getAccount(userAddressInstance); + const userGuardianOnNetwork = await elven.networkProvider.getGuardianData(userAddressInstance); + ls.set("address", address); + ls.set( + "activeGuardian", + userGuardianOnNetwork.guarded && userGuardianOnNetwork.activeGuardian?.address ? userGuardianOnNetwork.activeGuardian.address : "" + ); + ls.set("nonce", userAccountOnNetwork.nonce.valueOf()); + ls.set("balance", userAccountOnNetwork.balance.toString()); + userAccountInstance.update(userAccountOnNetwork); + } catch (e2) { + const err = errorParse(e2); + console.warn( + `Something went wrong trying to synchronize the user account: ${err}` + ); + } + } +}; + +// src/auth/login-with-extension.ts +var loginWithExtension = async (elven, loginToken, nativeAuthClient, callbackRoute = "/") => { + const dappProvider = await initExtensionProvider(); + const callbackUrl = encodeURIComponent( + `${window.location.origin}${callbackRoute}` + ); + const providerLoginData = { + callbackUrl, + token: loginToken + }; + try { + if (dappProvider) { + const address = await dappProvider.login(providerLoginData); + if (!address) { + throw new Error("There were problems while logging in!"); + } + } + } catch (e2) { + const err = errorParse(e2); + throw new Error(err); + } + if (!dappProvider) { + throw new Error("There were problems with auth provider initialization!"); + } + const { signature } = dappProvider.account; + ls.set("loginToken", loginToken); + if (signature) { + ls.set("signature", signature); + } + if (elven.networkProvider && signature) { + try { + const address = await dappProvider.getAddress(); + if (!address) { + throw new Error("Canceled!"); + } + ls.set("address", address); + ls.set("loginMethod", "browser-extension" /* browserExtension */); + ls.set("expires", getNewLoginExpiresTimestamp()); + await accountSync(elven); + const accessToken = nativeAuthClient.getToken( + address, + loginToken, + signature + ); + ls.set("accessToken", accessToken); + EventsStore.run("onLoginSuccess" /* onLoginSuccess */); + return dappProvider; + } catch (e2) { + throw new Error( + `Something went wrong trying to synchronize the user account: ${e2?.message}` + ); + } + } +}; + +// src/auth/login-with-mobile.ts +init_shim(); + +// src/auth/qr-code-and-pairings-builder.ts +init_shim(); +var import_qrcode = __toESM(require_browser7(), 1); +var import_walletConnectV2Provider2 = __toESM(require_walletConnectV2Provider(), 1); +var htmlStringToElement = (htmlString) => { + const template = document.createElement("template"); + template.innerHTML = htmlString.trim(); + return template.content.firstChild?.cloneNode(true); +}; +var buildDeepLink = (walletConnectUri) => { + const hrefVal = `${walletConnectDeepLink}?wallet-connect=${encodeURIComponent( + walletConnectUri + )}`; + const aElem = document.createElement("a"); + aElem.setAttribute("href", hrefVal); + aElem.setAttribute("rel", "noopener noreferrer nofollow"); + aElem.setAttribute("target", "_blank"); + aElem.textContent = "xPortal login"; + aElem.classList.add("elven-qr-code-deep-link"); + return aElem; +}; +var buildPairingsContainer = () => { + const container = document.createElement("div"); + container.classList.add("elven-wc-pairings"); + return container; +}; +var buildPairingsHeader = () => { + const headerElem = document.createElement("div"); + headerElem.textContent = "Existing WalletConnect pairings:"; + headerElem.classList.add("elven-wc-pairings-header"); + return headerElem; +}; +var pairingRemoveControllers = {}; +var buildPairingsRemoveButton = (pairing, removeExistingPairing) => { + const btn = document.createElement("button"); + btn.classList.add("elven-wc-pairings-remove-btn"); + btn.textContent = "\u2716"; + pairingRemoveControllers[pairing.topic] = new AbortController(); + btn.addEventListener( + "click", + (e2) => { + e2.stopImmediatePropagation(); + removeExistingPairing(pairing.topic); + }, + { + signal: pairingRemoveControllers[pairing.topic].signal + } + ); + return btn; +}; +var pairingLoginControllers = {}; +var buildPairingItem = (pairing, removeExistingPairing, loginThroughExistingPairing) => { + const itemElem = document.createElement("div"); + const itemTextWrapper = document.createElement("div"); + itemElem.classList.add("elven-wc-pairing-item"); + itemElem.setAttribute("id", pairing.topic); + itemTextWrapper.classList.add("elven-wc-pairing-item-description"); + itemTextWrapper.textContent = `${pairing.peerMetadata?.description} (${pairing.peerMetadata?.url})`; + itemElem.appendChild(itemTextWrapper); + const button = buildPairingsRemoveButton(pairing, removeExistingPairing); + itemElem.appendChild(button); + pairingLoginControllers[pairing.topic] = new AbortController(); + itemElem.addEventListener( + "click", + () => loginThroughExistingPairing(pairing.topic), + { signal: pairingLoginControllers[pairing.topic].signal } + ); + return itemElem; +}; +var buildPairingItemConfirmMessage = () => { + const itemElem = document.createElement("div"); + itemElem.classList.add("elven-wc-pairing-item-confirm-msessage"); + itemElem.setAttribute("id", "elven-wc-pairing-item-confirm-msessage"); + itemElem.innerText = "Confirm on xPortal app!"; + return itemElem; +}; +var removePairingItem = (topic) => { + if (!topic) + return; + const pairingElement = document.getElementById(topic); + pairingElement?.remove(); +}; +var isMobile = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent +); +var generateQRCode = async (walletConnectUri) => { + if (!walletConnectUri) { + return; + } + const svg = await import_qrcode.default.toString(walletConnectUri, { + type: "svg" + }); + return svg; +}; +var qrCodeAndPairingsBuilder = async (qrCodeContainer, walletConnectUri, dappProvider, token) => { + if (!qrCodeContainer) + throw new Error( + "Please provide the QR Code and WalletConnect Pairings container id!" + ); + let containerElem = null; + if (typeof qrCodeContainer === "string") { + containerElem = document.getElementById(qrCodeContainer); + } else if (qrCodeContainer instanceof HTMLElement) { + containerElem = qrCodeContainer; + } + const qrCodeElementString = await generateQRCode(walletConnectUri); + let qrCodeSvg; + if (qrCodeElementString) { + qrCodeSvg = htmlStringToElement(qrCodeElementString); + } + if (containerElem && qrCodeSvg) { + containerElem.replaceChildren(); + containerElem.appendChild(qrCodeSvg); + if (isMobile()) { + containerElem.appendChild(buildDeepLink(walletConnectUri)); + } + } + if (containerElem && dappProvider instanceof import_walletConnectV2Provider2.WalletConnectV2Provider) { + const wcPairings = dappProvider.pairings; + const removeExistingPairing = async (topic) => { + try { + if (topic) { + await dappProvider.logout({ + topic + }); + removePairingItem(topic); + } + } catch (e2) { + const err = errorParse(e2); + console.warn( + `Something went wrong trying to remove the existing pairing: ${err}` + ); + } finally { + pairingLoginControllers[topic].abort(); + } + }; + const loginThroughExistingPairing = async (topic) => { + try { + const { approval } = await dappProvider.connect({ + topic, + methods: [ + "mvx_cancelAction" /* mvx_cancelAction */, + "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ + ] + }); + const pairingItemConfirmation = document.getElementById( + "elven-wc-pairing-item-confirm-msessage" + ); + if (!pairingItemConfirmation) { + const pairingItemElement = document.getElementById(topic); + pairingItemElement?.after(buildPairingItemConfirmMessage()); + } + await dappProvider.login({ + approval, + token + }); + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + } finally { + for (const abortController of Object.values(pairingLoginControllers)) { + abortController?.abort(); + } + for (const abortController of Object.values(pairingRemoveControllers)) { + abortController?.abort(); + } + } + }; + if (wcPairings && wcPairings.length > 0) { + const container = buildPairingsContainer(); + containerElem.appendChild(container); + const headerElem = buildPairingsHeader(); + container.appendChild(headerElem); + for (const pairing of wcPairings) { + const itemElem = buildPairingItem( + pairing, + removeExistingPairing, + loginThroughExistingPairing + ); + container.appendChild(itemElem); + } + } + } + return containerElem; +}; + +// src/auth/login-with-mobile.ts +var import_walletConnectV2Provider3 = __toESM(require_walletConnectV2Provider(), 1); +var loginWithMobile = async (elven, loginToken, nativeAuthClient, qrCodeContainer) => { + if (!qrCodeContainer) { + throw new Error( + "You haven't provided the QR code container DOM element id" + ); + } + const relayAddress = getRandomAddressFromNetwork( + elven.initOptions.walletConnectV2RelayAddresses + ); + if (!relayAddress || !elven.networkProvider) { + throw new Error( + "Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!" + ); + } + if (!elven.initOptions.walletConnectV2ProjectId) { + throw new Error( + "Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)" + ); + } + if (!elven.initOptions.chainType) { + throw new Error("Please provide the chain type in ElvenJS.init function!"); + } + let qrCodeElement; + const providerHandlers = { + onClientLogin: async () => { + if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { + const address = await elven.dappProvider.getAddress(); + const signature = await elven.dappProvider.getSignature(); + ls.set("address", address); + ls.set("loginMethod", "mobile" /* mobile */); + ls.set("expires", getNewLoginExpiresTimestamp()); + await accountSync(elven); + if (signature) { + ls.set("signature", signature); + } + ls.set("loginToken", loginToken); + const accessToken = nativeAuthClient.getToken( + address, + loginToken, + signature + ); + ls.set("accessToken", accessToken); + EventsStore.run("onLoginSuccess" /* onLoginSuccess */); + qrCodeElement?.replaceChildren(); + } + }, + onClientLogout: async () => { + if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { + await logout(elven); + } + }, + onClientEvent: (event) => { + console.log("wc2 session event: ", event); + } + }; + const dappProvider = new import_walletConnectV2Provider3.WalletConnectV2Provider( + providerHandlers, + networkConfig[elven.initOptions.chainType].shortId, + relayAddress, + elven.initOptions.walletConnectV2ProjectId + ); + try { + if (dappProvider) { + elven.dappProvider = dappProvider; + EventsStore.run("onQrPending" /* onQrPending */); + await dappProvider.init(); + const { uri: walletConnectUri, approval } = await dappProvider.connect({ + methods: [ + "mvx_cancelAction" /* mvx_cancelAction */, + "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ + ] + }); + const wCUri = loginToken ? `${walletConnectUri}&token=${loginToken}` : walletConnectUri; + if (qrCodeContainer && wCUri) { + qrCodeElement = await qrCodeAndPairingsBuilder( + qrCodeContainer, + wCUri, + dappProvider, + loginToken + ); + EventsStore.run("onQrLoaded" /* onQrLoaded */); + } + await dappProvider.login({ + approval, + token: loginToken + }); + return dappProvider; + } + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + EventsStore.run("onLoginFailure" /* onLoginFailure */, err); + } +}; + +// src/auth/login-with-web-wallet.ts +init_shim(); +var import_walletProvider = __toESM(require_walletProvider(), 1); +var loginWithWebWallet = async (urlAddress, loginToken, chainType, callbackRoute) => { + const dappProvider = new import_walletProvider.WalletProvider(`${urlAddress}${DAPP_INIT_ROUTE}`); + const callbackUrl = typeof window !== "undefined" ? encodeURIComponent(`${window.location.origin}${callbackRoute || "/"}`) : "/"; + const providerLoginData = { + callbackUrl, + token: loginToken + }; + try { + ls.set( + "loginMethod", + networkConfig[chainType].xAliasAddress === urlAddress ? "x-alias" /* xAlias */ : "web-wallet" /* webWallet */ + ); + await dappProvider.login(providerLoginData); + ls.set("expires", getNewLoginExpiresTimestamp()); + ls.set("loginToken", loginToken); + return dappProvider; + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + ls.set("loginMethod", ""); + EventsStore.run("onLoginFailure" /* onLoginFailure */, err); + } +}; + +// src/utils/get-param-from-url.ts +init_shim(); +var getParamFromUrl = (paramName) => { + if (typeof window !== "undefined") { + const url = new URL(window.location.href); + const params = new URLSearchParams(url.search); + return params.get(paramName); + } +}; + +// src/auth/init-web-wallet-provider.ts +init_shim(); +var import_walletProvider2 = __toESM(require_walletProvider(), 1); +var import_native_auth = __toESM(require_native_auth_client(), 1); +var initWebWalletProvider = async (webWalletAddress, apiUrl) => { + const signature = getParamFromUrl("signature"); + const urlAddress = getParamFromUrl("address"); + const lsAddress = ls.get("address"); + const loginToken = ls.get("loginToken"); + if (signature) { + ls.set("signature", signature); + } + if (urlAddress || lsAddress) { + if (urlAddress) { + ls.set("address", urlAddress); + window.history.replaceState(null, "", window.location.pathname); + } + const dappProvider = new import_walletProvider2.WalletProvider( + `${webWalletAddress}${DAPP_INIT_ROUTE}` + ); + if (signature && apiUrl && urlAddress) { + const nativeAuthClient = new import_native_auth.NativeAuthClient({ + apiUrl, + origin: window.location.origin + }); + const accessToken = nativeAuthClient.getToken( + urlAddress, + loginToken, + signature + ); + ls.set("accessToken", accessToken); + } + return dappProvider; + } +}; + +// src/interaction/post-send-tx.ts +init_shim(); +var import_account2 = __toESM(require_account(), 1); +var import_transactionWatcher = __toESM(require_transactionWatcher(), 1); +var postSendTx = async (transaction, networkProvider) => { + EventsStore.run("onTxSent" /* onTxSent */, transaction); + const transactionWatcher = new import_transactionWatcher.TransactionWatcher(networkProvider); + const transactionOnNetwork = await transactionWatcher.awaitCompleted(transaction); + const sender = transactionOnNetwork.sender; + const senderAccount = new import_account2.Account(sender); + const userAccountOnNetwork = await networkProvider.getAccount(sender); + senderAccount.update(userAccountOnNetwork); + ls.set("address", senderAccount.address.bech32()); + ls.set("balance", senderAccount.balance.toString()); + EventsStore.run("onTxFinalized" /* onTxFinalized */, transactionOnNetwork); +}; + +// src/interaction/web-wallet-tx-finalize.ts +init_shim(); +var import_out = __toESM(require_out2(), 1); +var import_transaction = __toESM(require_transaction(), 1); + +// src/interaction/pre-send-tx.ts +init_shim(); +var import_account3 = __toESM(require_account(), 1); +var preSendTx = (tx) => { + const sender = tx.getSender(); + const senderAccount = new import_account3.Account(sender); + const currentNonce = tx.nonce.valueOf(); + senderAccount.incrementNonce(); + ls.set("nonce", (currentNonce + 1n).toString()); +}; + +// src/interaction/web-wallet-tx-finalize.ts +var webWalletTxFinalize = async (dappProvider, networkProvider, urlAddress, nonce) => { + const walletProviderStatus = getParamFromUrl(import_out.WALLET_PROVIDER_CALLBACK_PARAM); + if (walletProviderStatus === import_out.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED && dappProvider && networkProvider) { + const guardian = ls.get("activeGuardian"); + const loginMethod = ls.get("loginMethod"); + const hasWebWalletGuardianSign = getParamFromUrl( + "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */ + ); + let transactionObj; + if ("getTransactionsFromWalletUrl" in dappProvider) { + const txs = dappProvider.getTransactionsFromWalletUrl(); + transactionObj = txs?.[0]; + if (!transactionObj) + return; + if (loginMethod === "web-wallet" /* webWallet */) { + transactionObj.data = import_buffer.Buffer.from(transactionObj.data).toString( + "base64" + ); + } + } else if (guardian && loginMethod !== "web-wallet" /* webWallet */ && loginMethod !== "x-alias" /* xAlias */ && hasWebWalletGuardianSign) { + const webWalletProvider = new import_out.WalletProvider( + `${urlAddress}${DAPP_INIT_ROUTE}` + ); + const txs = webWalletProvider.getTransactionsFromWalletUrl(); + transactionObj = txs?.[0]; + } + if (transactionObj) { + const transaction = import_transaction.Transaction.fromPlainObject(transactionObj); + transaction.nonce = BigInt(nonce); + preSendTx(transaction); + try { + EventsStore.run("onTxStart" /* onTxStart */, transaction); + await networkProvider.sendTransaction(transaction); + await postSendTx(transaction, networkProvider); + } catch (e2) { + const err = errorParse(e2); + const errMsg = `Getting transaction information failed! ${err}`; + EventsStore.run("onTxFailure" /* onTxFailure */, transaction, errMsg); + throw new Error(errMsg); + } finally { + window.history.replaceState(null, "", window.location.pathname); + } + } + window.history.replaceState(null, "", window.location.pathname); + } +}; + +// src/interaction/guardian-operations.ts +init_shim(); +var import_networkParams = __toESM(require_networkParams(), 1); +var import_address3 = __toESM(require_address(), 1); +var import_walletProvider3 = __toESM(require_walletProvider(), 1); +var guardianPreSignTxOperations = (tx) => { + const guardian = ls.get("activeGuardian"); + if (guardian) { + const options = { + guarded: true + }; + tx.setVersion(import_networkParams.TransactionVersion.withTxOptions()); + tx.setOptions(import_networkParams.TransactionOptions.withOptions(options)); + tx.setGuardian(import_address3.Address.fromBech32(guardian)); + } + return tx; +}; +var sendTxToGuardian = async (signedTx, walletAddress) => { + const webWalletProvider = new import_walletProvider3.WalletProvider( + `${walletAddress}${DAPP_INIT_ROUTE}` + ); + const currentUrl = window?.location.href; + const alteredCallbackUrl = new URL(currentUrl); + alteredCallbackUrl.searchParams.set( + "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */, + "true" + ); + await webWalletProvider.guardTransactions([signedTx], { + callbackUrl: encodeURIComponent(alteredCallbackUrl.toString()) + }); +}; +var checkNeedsGuardianSigning = (signedTx) => { + const guardian = ls.get("activeGuardian"); + const address = ls.get("address"); + if (!address || !guardian) { + return false; + } + if (signedTx.isGuardedTransaction()) { + return false; + } + return true; +}; + +// src/interaction/web-wallet-sign-message-finalize.ts +init_shim(); +var webWalletSignMessageFinalize = () => { + const isNotTransaction = !getParamFromUrl("walletProviderStatus"); + const isSigned = getParamFromUrl("status") === "signed"; + const message = getParamFromUrl("message"); + const signature = getParamFromUrl("signature"); + if (isNotTransaction && isSigned && message && signature) { + EventsStore.run("onSignMsgFinalized" /* onSignMsgFinalized */, message, signature); + window.history.replaceState(null, "", window.location.pathname); + } +}; + +// src/webview-provider/webview-provider.ts +init_shim(); +var import_transaction2 = __toESM(require_transaction(), 1); + +// src/webview-provider/types.ts +init_shim(); +var WebViewProviderResponseBaseEnums = /* @__PURE__ */ ((WebViewProviderResponseBaseEnums2) => { + WebViewProviderResponseBaseEnums2["reloginResponse"] = "RELOGIN_RESPONSE"; + return WebViewProviderResponseBaseEnums2; +})(WebViewProviderResponseBaseEnums || {}); +var CrossWindowProviderResponseEnums = /* @__PURE__ */ ((CrossWindowProviderResponseEnums2) => { + CrossWindowProviderResponseEnums2["handshakeResponse"] = "HANDSHAKE_RESPONSE"; + CrossWindowProviderResponseEnums2["loginResponse"] = "LOGIN_RESPONSE"; + CrossWindowProviderResponseEnums2["disconnectResponse"] = "DISCONNECT_RESPONSE"; + CrossWindowProviderResponseEnums2["cancelResponse"] = "CANCEL_RESPONSE"; + CrossWindowProviderResponseEnums2["signTransactionsResponse"] = "SIGN_TRANSACTIONS_RESPONSE"; + CrossWindowProviderResponseEnums2["signMessageResponse"] = "SIGN_MESSAGE_RESPONSE"; + CrossWindowProviderResponseEnums2["noneResponse"] = "NONE_RESPONSE"; + return CrossWindowProviderResponseEnums2; +})(CrossWindowProviderResponseEnums || {}); +var WebViewProviderResponseEnums = { + ...CrossWindowProviderResponseEnums, + ...WebViewProviderResponseBaseEnums +}; +var WebViewProviderRequestBaseEnums = /* @__PURE__ */ ((WebViewProviderRequestBaseEnums2) => { + WebViewProviderRequestBaseEnums2["signTransactionsWithGuardianResponse"] = "SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE"; + WebViewProviderRequestBaseEnums2["reloginRequest"] = "RELOGIN_REQUEST"; + return WebViewProviderRequestBaseEnums2; +})(WebViewProviderRequestBaseEnums || {}); +var CrossWindowProviderRequestEnums = /* @__PURE__ */ ((CrossWindowProviderRequestEnums2) => { + CrossWindowProviderRequestEnums2["signTransactionsRequest"] = "SIGN_TRANSACTIONS_REQUEST"; + CrossWindowProviderRequestEnums2["signMessageRequest"] = "SIGN_MESSAGE_REQUEST"; + CrossWindowProviderRequestEnums2["loginRequest"] = "LOGIN_REQUEST"; + CrossWindowProviderRequestEnums2["logoutRequest"] = "LOGOUT_REQUEST"; + CrossWindowProviderRequestEnums2["cancelAction"] = "CANCEL_ACTION_REQUEST"; + CrossWindowProviderRequestEnums2["finalizeHandshakeRequest"] = "FINALIZE_HANDSHAKE_REQUEST"; + return CrossWindowProviderRequestEnums2; +})(CrossWindowProviderRequestEnums || {}); +var WebViewProviderRequestEnums = { + ...CrossWindowProviderRequestEnums, + ...WebViewProviderRequestBaseEnums +}; + +// src/webview-provider/utils.ts +init_shim(); +var safeWindow = typeof window !== "undefined" ? window : {}; +var detectCurrentPlatform = () => { + if (safeWindow.ReactNativeWebView) { + return "reactNative" /* reactNative */; + } + if (safeWindow.webkit) { + return "ios" /* ios */; + } + return "web" /* web */; +}; +var getTargetOrigin = () => { + return typeof window != "undefined" && typeof window?.location != "undefined" ? window?.parent?.origin ?? "*" : "*"; +}; +var isString = (x3) => { + return Object.prototype.toString.call(x3) === "[object String]"; +}; + +// src/webview-provider/request-methods.ts +init_shim(); +var requestMethods = { + signTransactions: { + ["ios" /* ios */]: (transactions) => window.webkit.messageHandlers.signTransactions.postMessage( + transactions, + getTargetOrigin() + ), + ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signTransactionsRequest, + message + }) + ), + ["web" /* web */]: (message) => window?.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signTransactionsRequest, + message + }), + getTargetOrigin() + ) + }, + signMessage: { + ["ios" /* ios */]: (message) => window.webkit.messageHandlers.signMessage.postMessage(message), + ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signMessageRequest, + message + }) + ), + ["web" /* web */]: (message) => window?.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signMessageRequest, + message + }), + getTargetOrigin() + ) + }, + logout: { + ["ios" /* ios */]: () => window.webkit.messageHandlers.logout.postMessage(), + ["reactNative" /* reactNative */]: () => window?.ReactNativeWebView.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.logoutRequest + }) + ), + ["web" /* web */]: () => window?.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.logoutRequest + }), + getTargetOrigin() + ) + } +}; + +// src/webview-provider/webview-provider.ts +var currentPlatform = detectCurrentPlatform(); +var messageType = "message"; +var handleWaitForMessage = (cb) => { + const handleMessageReceived = (event) => { + let eventData = event.data; + if (event.target.origin != getTargetOrigin() && currentPlatform != "reactNative" /* reactNative */) { + return; + } + try { + eventData = JSON.parse(eventData); + cb(eventData); + } catch (err) { + console.error("error parsing response"); + } + }; + if (document) { + document.addEventListener(messageType, handleMessageReceived); + } + if (window) { + window.addEventListener(messageType, handleMessageReceived); + } +}; +var WebviewProvider = class { + constructor() { + } + async logout() { + requestMethods.logout[currentPlatform](); + return new Promise((resolve) => { + resolve(true); + }); + } + async signMessage(message) { + try { + requestMethods.signMessage[currentPlatform](message); + const waitForSignedMessageResponse = new Promise( + (resolve, reject) => { + window.signMessageResponse = (signedMessage, error) => { + if (error) { + reject(error); + window.signMessageResponse = null; + return; + } + resolve(signedMessage); + window.signMessageResponse = null; + }; + function handleSignMessageResponse(eventData) { + const { message: message2, type } = eventData; + if (type === WebViewProviderResponseEnums.signMessageResponse && message2 != null) { + const { signedMessage, error } = message2; + if (!error) { + resolve(signedMessage); + } else { + reject(error); + } + } + document?.removeEventListener( + messageType, + handleSignMessageResponse + ); + } + handleWaitForMessage(handleSignMessageResponse); + } + ); + return await waitForSignedMessageResponse; + } catch (err) { + console.error("error sending transaction", err); + throw err; + } + } + async signTransactions(transactions) { + try { + const plainTransactions = transactions.map((tx) => tx.toPlainObject()); + requestMethods.signTransactions[currentPlatform](plainTransactions); + const waitForSignedTransactionsResponse = new Promise((resolve, reject) => { + window.transactionsSigned = (txs, error) => { + txs = JSON.parse(txs); + if (error) { + reject(error); + window.transactionsSigned = null; + return; + } + resolve(txs.map((tx) => import_transaction2.Transaction.fromPlainObject(tx))); + window.transactionsSigned = null; + }; + function handleSignTransactionResponse(eventData) { + const { message, type } = eventData; + if (type === WebViewProviderResponseEnums.signTransactionsResponse) { + const { transactions: transactions2, error } = message; + try { + if (!error) { + resolve( + transactions2.map( + (tx) => import_transaction2.Transaction.fromPlainObject(tx) + ) + ); + } else { + reject(error); + } + } catch (err) { + reject("Unable to sign"); + } + } + if (document) { + document.removeEventListener( + messageType, + handleSignTransactionResponse + ); + } + } + handleWaitForMessage(handleSignTransactionResponse); + }); + return await waitForSignedTransactionsResponse; + } catch (err) { + console.error("error sending transaction", err); + throw err; + } + } + async signTransaction(transaction) { + const response = await this.signTransactions([transaction]); + return response[0]; + } +}; + +// src/auth/login-with-native-auth-token.ts +init_shim(); + +// src/webview-provider/decode-native-auth-token.ts +init_shim(); + +// src/webview-provider/base64-utils.ts +init_shim(); +function isStringBase64(str) { + try { + const atobDecoded = atob(str); + const btoaEncoded = btoa(atobDecoded); + const bufferFromDecoded = import_buffer.Buffer.from(str, "base64").toString(); + const bufferFromEncoded = import_buffer.Buffer.from(bufferFromDecoded).toString("base64"); + const isEqualToInitialString = str === btoaEncoded && str === bufferFromEncoded; + const isAtobEqualToBufferFrom = atobDecoded === bufferFromDecoded; + if (isEqualToInitialString || isAtobEqualToBufferFrom) { + return true; + } + } catch (e2) { + return false; + } + return false; +} +function decodeBase64(string2) { + if (!isStringBase64(string2)) { + return string2; + } + return atob(string2); +} + +// src/webview-provider/decode-login-token.ts +init_shim(); +var decodeLoginToken = (loginToken) => { + if (!loginToken || !isString(loginToken)) { + return null; + } + const parts = loginToken.split("."); + if (parts.length !== 4) { + return null; + } + try { + const [origin, blockHash, ttl, extraInfo] = parts; + const parsedExtraInfo = JSON.parse(decodeBase64(extraInfo)); + const parsedOrigin = decodeBase64(origin); + return { + ttl: Number(ttl), + extraInfo: parsedExtraInfo, + origin: parsedOrigin, + blockHash + }; + } catch (e2) { + console.error(`Error trying to decode ${loginToken}:`, e2); + return null; + } +}; + +// src/webview-provider/decode-native-auth-token.ts +var decodeNativeAuthToken = (accessToken) => { + if (!accessToken || !isString(accessToken)) { + return null; + } + const parts = accessToken.split("."); + if (parts.length !== 3) { + console.error( + "Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead" + ); + return null; + } + try { + const [address, body, signature] = parts; + const parsedAddress = decodeBase64(address); + const parsedBody = decodeBase64(body); + const parsedInitToken = decodeLoginToken(parsedBody); + if (!parsedInitToken) { + return { + address: parsedAddress, + body: parsedBody, + signature, + blockHash: "", + origin: "", + ttl: 0 + }; + } + const result = { + ...parsedInitToken, + address: parsedAddress, + body: parsedBody, + signature + }; + if (!parsedInitToken.extraInfo?.timestamp) { + delete result.extraInfo; + } + return result; + } catch (err) { + return null; + } +}; + +// src/auth/login-with-native-auth-token.ts +function loginWithNativeAuthToken(token, elven) { + const nativeAuthInfo = decodeNativeAuthToken(token); + if (nativeAuthInfo == null) { + return; + } + const { signature, address, body } = nativeAuthInfo; + if (signature && token && address) { + ls.set("loginToken", body); + ls.set("accessToken", token); + ls.set("signature", signature); + ls.set("address", address); + ls.set("loginMethod", "x-portal-hub" /* xPortalHub */); + elven.dappProvider = new WebviewProvider(); + } +} + +// src/initialize-events-store.ts +init_shim(); +var initializeEventsStore = (initOptions) => { + if (initOptions.onLoginStart) { + EventsStore.set("onLoginStart" /* onLoginStart */, initOptions.onLoginStart); + } + if (initOptions.onLoginSuccess) { + EventsStore.set( + "onLoginSuccess" /* onLoginSuccess */, + initOptions.onLoginSuccess + ); + } + if (initOptions.onLoginFailure) { + EventsStore.set( + "onLoginFailure" /* onLoginFailure */, + initOptions.onLoginFailure + ); + } + if (initOptions.onLogoutStart) { + EventsStore.set("onLogoutStart" /* onLogoutStart */, initOptions.onLogoutStart); + } + if (initOptions.onLogoutSuccess) { + EventsStore.set( + "onLogoutSuccess" /* onLogoutSuccess */, + initOptions.onLogoutSuccess + ); + } + if (initOptions.onLogoutFailure) { + EventsStore.set( + "onLogoutFailure" /* onLogoutFailure */, + initOptions.onLogoutFailure + ); + } + if (initOptions.onQrPending) { + EventsStore.set("onQrPending" /* onQrPending */, initOptions.onQrPending); + } + if (initOptions.onQrLoaded) { + EventsStore.set("onQrLoaded" /* onQrLoaded */, initOptions.onQrLoaded); + } + if (initOptions.onTxStart) { + EventsStore.set("onTxStart" /* onTxStart */, initOptions.onTxStart); + } + if (initOptions.onTxSent) { + EventsStore.set("onTxSent" /* onTxSent */, initOptions.onTxSent); + } + if (initOptions.onTxFinalized) { + EventsStore.set("onTxFinalized" /* onTxFinalized */, initOptions.onTxFinalized); + } + if (initOptions.onTxFailure) { + EventsStore.set("onTxFailure" /* onTxFailure */, initOptions.onTxFailure); + } + if (initOptions.onSignMsgStart) { + EventsStore.set( + "onSignMsgStart" /* onSignMsgStart */, + initOptions.onSignMsgStart + ); + } + if (initOptions.onSignMsgFinalized) { + EventsStore.set( + "onSignMsgFinalized" /* onSignMsgFinalized */, + initOptions.onSignMsgFinalized + ); + } + if (initOptions.onSignMsgFailure) { + EventsStore.set( + "onSignMsgFailure" /* onSignMsgFailure */, + initOptions.onSignMsgFailure + ); + } + if (initOptions.onQueryStart) { + EventsStore.set("onQueryStart" /* onQueryStart */, initOptions.onQueryStart); + } + if (initOptions.onQueryFinalized) { + EventsStore.set( + "onQueryFinalized" /* onQueryFinalized */, + initOptions.onQueryFinalized + ); + } + if (initOptions.onQueryFailure) { + EventsStore.set( + "onQueryFailure" /* onQueryFailure */, + initOptions.onQueryFailure + ); + } +}; + +// src/utils/with-login-events.ts +init_shim(); +var withLoginEvents = async (fn) => { + EventsStore.run("onLoginStart" /* onLoginStart */); + try { + await fn(() => { + EventsStore.run("onLoginSuccess" /* onLoginSuccess */); + }); + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + EventsStore.run("onLoginFailure" /* onLoginFailure */, err); + } +}; + +// src/main.ts +var ElvenJS = class { + /** + * Initialization of the Elven.js + */ + static async init(options) { + const state = ls.get(); + if (state.expires && isLoginExpired(state.expires)) { + ls.clear(); + this.dappProvider = void 0; + return; + } + this.initOptions = { + chainType: defaultChainTypeConfig, + apiUrl: defaultApiEndpoint, + apiTimeout: 1e4, + walletConnectV2ProjectId: "", + walletConnectV2RelayAddresses: defaultWalletConnectV2RelayAddresses, + ...options + }; + this.networkProvider = new ApiNetworkProvider(this.initOptions); + initializeEventsStore(this.initOptions); + const nativeAuthTokenFromUrl = getParamFromUrl("accessToken"); + if (nativeAuthTokenFromUrl) { + await withLoginEvents(async (onLoginSuccess) => { + loginWithNativeAuthToken(nativeAuthTokenFromUrl, this); + await accountSync(this); + onLoginSuccess(); + }); + } + const isAddress = state?.address || (state.loginMethod === "web-wallet" /* webWallet */ || state.loginMethod === "x-alias" /* xAlias */) && getParamFromUrl("address"); + if (isAddress && state?.loginMethod) { + await withLoginEvents(async (onLoginSuccess) => { + if (state.loginMethod === "browser-extension" /* browserExtension */) { + this.dappProvider = await initExtensionProvider(); + } + if (state.loginMethod === "mobile" /* mobile */) { + this.dappProvider = await initMobileProvider(this); + } + if (state.loginMethod === "x-portal-hub" /* xPortalHub */) { + this.dappProvider = new WebviewProvider(); + } + if (state.loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { + this.dappProvider = await initWebWalletProvider( + networkConfig[this.initOptions.chainType].walletAddress, + this.initOptions.apiUrl + ); + } + if (state.loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { + this.dappProvider = await initWebWalletProvider( + networkConfig[this.initOptions.chainType].xAliasAddress, + this.initOptions.apiUrl + ); + } + await accountSync(this); + onLoginSuccess(); + }); + if (this.initOptions?.chainType) { + await webWalletTxFinalize( + this.dappProvider, + this.networkProvider, + networkConfig[this.initOptions.chainType][state.loginMethod === "x-alias" /* xAlias */ ? "xAliasAddress" : "walletAddress"], + state.nonce + ); + webWalletSignMessageFinalize(); + } + } + } + /** + * Login function + */ + static async login(loginMethod, options) { + const isProperLoginMethod = Object.values(LoginMethodsEnum).includes(loginMethod); + if (!isProperLoginMethod) { + const error = "Wrong login method!"; + EventsStore.run("onLoginFailure" /* onLoginFailure */, error); + throw new Error(error); + } + if (!this.networkProvider) { + const error = "Login failed: Use ElvenJs.init() first!"; + EventsStore.run("onLoginFailure" /* onLoginFailure */, error); + throw new Error(error); + } + await withLoginEvents(async () => { + const nativeAuthClient = new import_native_auth2.NativeAuthClient({ + apiUrl: this.initOptions?.apiUrl, + origin: window.location.origin + }); + const loginToken = await nativeAuthClient.initialize(); + if (loginMethod === "browser-extension" /* browserExtension */) { + const dappProvider = await loginWithExtension( + this, + loginToken, + nativeAuthClient, + options?.callbackRoute + ); + this.dappProvider = dappProvider; + } + if (loginMethod === "mobile" /* mobile */) { + const dappProvider = await loginWithMobile( + this, + loginToken, + nativeAuthClient, + options?.qrCodeContainer + ); + this.dappProvider = dappProvider; + } + if (loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { + const dappProvider = await loginWithWebWallet( + networkConfig[this.initOptions.chainType].walletAddress, + loginToken, + this.initOptions?.chainType, + options?.callbackRoute + ); + this.dappProvider = dappProvider; + } + if (loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { + const dappProvider = await loginWithWebWallet( + networkConfig[this.initOptions.chainType].xAliasAddress, + loginToken, + this.initOptions?.chainType, + options?.callbackRoute + ); + this.dappProvider = dappProvider; + } + }); + } + /** + * Logout function + */ + static async logout() { + try { + const isLoggedOut = await logout(this); + this.dappProvider = void 0; + return isLoggedOut; + } catch (e2) { + const err = errorParse(e2); + console.warn("Something went wrong when logging out: ", err); + } + } + /** + * Sign and send function + */ + static async signAndSendTransaction(transaction) { + if (!this.dappProvider) { + const error = "Transaction signing failed: There is no active session!"; + EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); + throw new Error(error); + } + if (!this.networkProvider) { + const error = "Transaction signing failed: There is no active network provider!"; + EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); + throw new Error(error); + } + let signedTx = guardianPreSignTxOperations(transaction); + try { + EventsStore.run("onTxStart" /* onTxStart */, transaction); + const currentState = ls.get(); + transaction.nonce = currentState.nonce; + if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { + signedTx = await this.dappProvider.signTransaction(transaction); + } + if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { + signedTx = await this.dappProvider.signTransaction(transaction); + } + if (this.dappProvider instanceof WebviewProvider) { + signedTx = await this.dappProvider.signTransaction(transaction); + } + if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { + await this.dappProvider.signTransaction(transaction); + } + if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { + const needsGuardianSign = checkNeedsGuardianSigning(signedTx); + if (!needsGuardianSign) { + preSendTx(signedTx); + } + if (needsGuardianSign && this.initOptions?.chainType) { + await sendTxToGuardian( + signedTx, + networkConfig[this.initOptions.chainType].walletAddress + ); + return; + } + await this.networkProvider.sendTransaction(signedTx); + await postSendTx(signedTx, this.networkProvider); + } + } catch (e2) { + const err = errorParse(e2); + EventsStore.run( + "onTxFailure" /* onTxFailure */, + signedTx, + `Getting transaction information failed! ${err}` + ); + throw new Error(`Getting transaction information failed! ${err}`); + } + return signedTx; + } + /** + * Sign a single message + */ + static async signMessage(message, options) { + if (!this.dappProvider) { + const error = "Message signing failed: There is no active session!"; + EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); + throw new Error(error); + } + if (!this.networkProvider) { + const error = "Message signing failed: There is no active network provider!"; + EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); + throw new Error(error); + } + let messageSignature = ""; + try { + EventsStore.run("onSignMsgStart" /* onSignMsgStart */, message); + if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { + const signedMessage = await this.dappProvider.signMessage( + new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) + ); + messageSignature = signedMessage.getSignature().toString("hex"); + } + if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { + const signedMessage = await this.dappProvider.signMessage( + new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) + ); + messageSignature = signedMessage.getSignature().toString("hex"); + } + if (this.dappProvider instanceof WebviewProvider) { + messageSignature = await this.dappProvider.signMessage(message); + } + if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { + const encodeRFC3986URIComponent = (str) => { + return encodeURIComponent(str).replace( + /[!'()*]/g, + (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}` + ); + }; + const url = options?.callbackUrl || window.location.origin; + await this.dappProvider.signMessage( + new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }), + { + callbackUrl: encodeURIComponent( + `${url}${url.includes("?") ? "&" : "?"}message=${encodeRFC3986URIComponent(message)}` + ) + } + ); + } + const currentState = ls.get(); + if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { + EventsStore.run( + "onSignMsgFinalized" /* onSignMsgFinalized */, + message, + messageSignature + ); + } + return { message, messageSignature }; + } catch (e2) { + const err = errorParse(e2); + EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, err); + throw new Error(`Message signing failed! ${err}`); + } + } + /** + * Query Smart Contracts + */ + static async queryContract({ + address, + func, + args = [], + value = 0, + caller + }) { + if (!this.networkProvider) { + throw new Error("Query failed: There is no active network provider!"); + } + if (!address || !func) { + throw new Error( + "Query failed: The Query arguments are not valid! Address and func required" + ); + } + const queryArgs = { + address, + func, + args, + value, + caller + }; + try { + EventsStore.run("onQueryStart" /* onQueryStart */, queryArgs); + const response = await this.networkProvider.queryContract(queryArgs); + EventsStore.run("onQueryFinalized" /* onQueryFinalized */, response); + return response; + } catch (e2) { + const err = errorParse(e2); + EventsStore.run("onQueryFinalized" /* onQueryFinalized */, queryArgs, err); + throw new Error(`Smart contract query failed! ${err}`); + } + } + static { + /** + * Main storage + */ + this.storage = ls; + } + static { + /** + * Destroy and cleanup if needed + */ + this.destroy = () => { + this.networkProvider = void 0; + this.dappProvider = void 0; + this.initOptions = void 0; + EventsStore.clear(); + }; + } +}; + +// src/utils/amount.ts +init_shim(); + +// node_modules/bignumber.js/bignumber.mjs +init_shim(); +var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; +var mathceil = Math.ceil; +var mathfloor = Math.floor; +var bignumberError = "[BigNumber Error] "; +var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; +var BASE = 1e14; +var LOG_BASE = 14; +var MAX_SAFE_INTEGER = 9007199254740991; +var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13]; +var SQRT_BASE = 1e7; +var MAX = 1e9; +function clone(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber2(v2, b4) { + var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber2)) + return new BigNumber2(v2, b4); + if (b4 == null) { + if (v2 && v2._isBigNumber === true) { + x3.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v2.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v2.e; + x3.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric.test(str = String(v2))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i2 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i2; + e2 += +str.slice(i2 + 1); + str = str.substring(0, i2); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck(b4, 2, ALPHABET.length, "Base"); + if (b4 == 10 && alphabetHasNormalDecimalDigits) { + x3 = new BigNumber2(v2); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric(x3, str, isNum, b4); + x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits + v2); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet2 = ALPHABET.slice(0, b4); + e2 = i2 = 0; + for (len = str.length; i2 < len; i2++) { + if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { + if (c4 == ".") { + if (i2 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i2 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v2), isNum, b4); + } + } + isNum = false; + str = convertBase(str, b4, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i2 = 0; str.charCodeAt(i2) === 48; i2++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i2, ++len)) { + len -= i2; + if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) { + throw Error(tooManyDigits + x3.s * v2); + } + if ((e2 = e2 - i2 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i2 = (e2 + 1) % LOG_BASE; + if (e2 < 0) + i2 += LOG_BASE; + if (i2 < len) { + if (i2) + x3.c.push(+str.slice(0, i2)); + for (len -= LOG_BASE; i2 < len; ) { + x3.c.push(+str.slice(i2, i2 += LOG_BASE)); + } + i2 = LOG_BASE - (str = str.slice(i2)).length; + } else { + i2 -= len; + } + for (; i2--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber2.clone = clone; + BigNumber2.ROUND_UP = 0; + BigNumber2.ROUND_DOWN = 1; + BigNumber2.ROUND_CEIL = 2; + BigNumber2.ROUND_FLOOR = 3; + BigNumber2.ROUND_HALF_UP = 4; + BigNumber2.ROUND_HALF_DOWN = 5; + BigNumber2.ROUND_HALF_EVEN = 6; + BigNumber2.ROUND_HALF_CEIL = 7; + BigNumber2.ROUND_HALF_FLOOR = 8; + BigNumber2.EUCLID = 9; + BigNumber2.config = BigNumber2.set = function(obj) { + var p3, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { + v2 = obj[p3]; + intCheck(v2, 0, MAX, p3); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { + v2 = obj[p3]; + intCheck(v2, 0, 8, p3); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck(v2[0], -MAX, 0, p3); + intCheck(v2[1], 0, MAX, p3); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck(v2, -MAX, MAX, p3); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p3 = "RANGE")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck(v2[0], -MAX, -1, p3); + intCheck(v2[1], 1, MAX, p3); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck(v2, -MAX, MAX, p3); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError + p3 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p3 = "CRYPTO")) { + v2 = obj[p3]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError + p3 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { + v2 = obj[p3]; + intCheck(v2, 0, 9, p3); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { + v2 = obj[p3]; + intCheck(v2, 0, MAX, p3); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p3 = "FORMAT")) { + v2 = obj[p3]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError + p3 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p3 = "ALPHABET")) { + v2 = obj[p3]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; + ALPHABET = v2; + } else { + throw Error(bignumberError + p3 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber2.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber2.DEBUG) + return true; + var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c4) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX && e2 <= MAX && e2 === mathfloor(e2)) { + if (c4[0] === 0) { + if (e2 === 0 && c4.length === 1) + return true; + break out; + } + i2 = (e2 + 1) % LOG_BASE; + if (i2 < 1) + i2 += LOG_BASE; + if (String(c4[0]).length == i2) { + for (i2 = 0; i2 < c4.length; i2++) { + n3 = c4[i2]; + if (n3 < 0 || n3 >= BASE || n3 !== mathfloor(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError + "Invalid BigNumber: " + v2); + }; + BigNumber2.maximum = BigNumber2.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber2.minimum = BigNumber2.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber2.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber2(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck(dp, 0, MAX); + k4 = mathceil(dp / LOG_BASE); + if (CRYPTO) { + if (crypto.getRandomValues) { + a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); + for (; i2 < k4; ) { + v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); + if (v2 >= 9e15) { + b4 = crypto.getRandomValues(new Uint32Array(2)); + a3[i2] = b4[0]; + a3[i2 + 1] = b4[1]; + } else { + c4.push(v2 % 1e14); + i2 += 2; + } + } + i2 = k4 / 2; + } else if (crypto.randomBytes) { + a3 = crypto.randomBytes(k4 *= 7); + for (; i2 < k4; ) { + v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a3, i2); + } else { + c4.push(v2 % 1e14); + i2 += 7; + } + } + i2 = k4 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i2 < k4; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c4[i2++] = v2 % 1e14; + } + } + k4 = c4[--i2]; + dp %= LOG_BASE; + if (k4 && dp) { + v2 = POWS_TEN[LOG_BASE - dp]; + c4[i2] = mathfloor(k4 / v2) * v2; + } + for (; c4[i2] === 0; c4.pop(), i2--) + ; + if (i2 < 0) { + c4 = [e2 = 0]; + } else { + for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE) + ; + for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) + ; + if (i2 < LOG_BASE) + e2 -= LOG_BASE - i2; + } + rand.e = e2; + rand.c = c4; + return rand; + }; + }(); + BigNumber2.sum = function() { + var i2 = 1, args = arguments, sum = new BigNumber2(args[0]); + for (; i2 < args.length; ) + sum = sum.plus(args[i2++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet2) { + var j2, arr = [0], arrL, i2 = 0, len = str.length; + for (; i2 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet2.indexOf(str.charAt(i2++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i2 >= 0) { + k4 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y4 = new BigNumber2(baseIn); + x3 = y4.pow(str.length - i2); + POW_PRECISION = k4; + y4.c = toBaseOut( + toFixedPoint(coeffToString(x3.c), x3.e, "0"), + 10, + baseOut, + decimal + ); + y4.e = y4.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); + e2 = k4 = xc.length; + for (; xc[--k4] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet2.charAt(0); + if (i2 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign2; + x3 = div(x3, y4, dp, rm, baseOut); + xc = x3.c; + r = x3.r; + e2 = x3.e; + } + d3 = e2 + dp + 1; + i2 = xc[d3]; + k4 = baseOut / 2; + r = r || d3 < 0 || xc[d3 + 1] != null; + r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (d3 < 1 || !xc[0]) { + str = r ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); + } else { + xc.length = d3; + if (r) { + for (--baseOut; ++xc[--d3] > baseOut; ) { + xc[d3] = 0; + if (!d3) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k4 = xc.length; !xc[--k4]; ) + ; + for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) + ; + str = toFixedPoint(str, e2, alphabet2.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x3, k4, base3) { + var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE, khi = k4 / SQRT_BASE | 0; + for (x3 = x3.slice(); i2--; ) { + xlo = x3[i2] % SQRT_BASE; + xhi = x3[i2] / SQRT_BASE | 0; + m3 = khi * xlo + xhi * klo; + temp = klo * xlo + m3 % SQRT_BASE * SQRT_BASE + carry; + carry = (temp / base3 | 0) + (m3 / SQRT_BASE | 0) + khi * xhi; + x3[i2] = temp % base3; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare3(a3, b4, aL, bL) { + var i2, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i2 = cmp = 0; i2 < aL; i2++) { + if (a3[i2] != b4[i2]) { + cmp = a3[i2] > b4[i2] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a3, b4, aL, base3) { + var i2 = 0; + for (; aL--; ) { + a3[aL] -= i2; + i2 = a3[aL] < b4[aL] ? 1 : 0; + a3[aL] = i2 * base3 + a3[aL] - b4[aL]; + } + for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) + ; + } + return function(x3, y4, dp, rm, base3) { + var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber2( + // Return NaN if either NaN, or both Infinity or 0. + !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber2(s2); + qc = q2.c = []; + e2 = x3.e - y4.e; + s2 = dp + e2 + 1; + if (!base3) { + base3 = BASE; + e2 = bitFloor(x3.e / LOG_BASE) - bitFloor(y4.e / LOG_BASE); + s2 = s2 / LOG_BASE | 0; + } + for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) + ; + if (yc[i2] > (xc[i2] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i2 = 0; + s2 += 2; + n3 = mathfloor(base3 / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base3); + xc = multiply(xc, n3, base3); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base3 / 2) + yc0++; + do { + n3 = 0; + cmp = compare3(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base3 + (rem[1] || 0); + n3 = mathfloor(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base3) + n3 = base3 - 1; + prod = multiply(yc, n3, base3); + prodL = prod.length; + remL = rem.length; + while (compare3(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base3); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base3); + remL = rem.length; + if (cmp == -1) { + while (compare3(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base3); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i2++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base3 == BASE) { + for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) + ; + round(q2, dp + (q2.e = i2 + e2 * LOG_BASE - 1) + 1, rm, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format(n3, i2, rm, id) { + var c0, e2, ne, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne = n3.e; + if (i2 == null) { + str = coeffToString(n3.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0"); + } else { + n3 = round(new BigNumber2(n3), i2, rm); + e2 = n3.e; + str = coeffToString(n3.c); + len = str.length; + if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { + for (; len < i2; str += "0", len++) + ; + str = toExponential(str, e2); + } else { + i2 -= ne; + str = toFixedPoint(str, e2, "0"); + if (e2 + 1 > len) { + if (--i2 > 0) + for (str += "."; i2--; str += "0") + ; + } else { + i2 += e2 - len; + if (i2 > 0) { + if (e2 + 1 == len) + str += "."; + for (; i2--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, n3) { + var k4, y4, i2 = 1, x3 = new BigNumber2(args[0]); + for (; i2 < args.length; i2++) { + y4 = new BigNumber2(args[i2]); + if (!y4.s || (k4 = compare2(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { + x3 = y4; + } + } + return x3; + } + function normalise(n3, c4, e2) { + var i2 = 1, j2 = c4.length; + for (; !c4[--j2]; c4.pop()) + ; + for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) + ; + if ((e2 = i2 + e2 * LOG_BASE - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e2 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e2; + n3.c = c4; + } + return n3; + } + parseNumeric = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b4) { + var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m3, p1, p22) { + base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; + return !b4 || b4 == base3 ? p1 : m3; + }); + if (b4) { + base3 = b4; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber2(s2, base3); + } + if (BigNumber2.DEBUG) { + throw Error(bignumberError + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm, r) { + var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN; + if (xc) { + out: { + for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) + ; + i2 = sd - d3; + if (i2 < 0) { + i2 += LOG_BASE; + j2 = sd; + n3 = xc[ni = 0]; + rd = mathfloor(n3 / pows10[d3 - j2 - 1] % 10); + } else { + ni = mathceil((i2 + 1) / LOG_BASE); + if (ni >= xc.length) { + if (r) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d3 = 1; + i2 %= LOG_BASE; + j2 = i2 - LOG_BASE + 1; + } else { + break out; + } + } else { + n3 = k4 = xc[ni]; + for (d3 = 1; k4 >= 10; k4 /= 10, d3++) + ; + i2 %= LOG_BASE; + j2 = i2 - LOG_BASE + d3; + rd = j2 < 0 ? 0 : mathfloor(n3 / pows10[d3 - j2 - 1] % 10); + } + } + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i2 == 0) { + xc.length = ni; + k4 = 1; + ni--; + } else { + xc.length = ni + 1; + k4 = pows10[LOG_BASE - i2]; + xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; + } + if (r) { + for (; ; ) { + if (ni == 0) { + for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) + ; + j2 = xc[0] += k4; + for (k4 = 1; j2 >= 10; j2 /= 10, k4++) + ; + if (i2 != k4) { + x3.e++; + if (xc[0] == BASE) + xc[0] = 1; + } + break; + } else { + xc[ni] += k4; + if (xc[ni] != BASE) + break; + xc[ni--] = 0; + k4 = 1; + } + } + } + for (i2 = xc.length; xc[--i2] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n3) { + var str, e2 = n3.e; + if (e2 === null) + return n3.toString(); + str = coeffToString(n3.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber2(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c4, n3, v2, x3 = this; + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber2(x3), dp + x3.e + 1, rm); + } + if (!(c4 = x3.c)) + return null; + n3 = ((v2 = c4.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + if (v2 = c4[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y4, b4) { + return div(this, new BigNumber2(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { + return div(this, new BigNumber2(y4, b4), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m3) { + var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; + n3 = new BigNumber2(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError + "Exponent not an integer: " + valueOf(n3)); + } + if (m3 != null) + m3 = new BigNumber2(m3); + nIsBig = n3.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { + y4 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd(n3)) : +valueOf(n3))); + return m3 ? y4.mod(m3) : y4; + } + nIsNeg = n3.s < 0; + if (m3) { + if (m3.c ? !m3.c[0] : !m3.s) + return new BigNumber2(NaN); + isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); + if (isModExp) + x3 = x3.mod(m3); + } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { + k4 = x3.s < 0 && isOdd(n3) ? -0 : 0; + if (x3.e > -1) + k4 = 1 / k4; + return new BigNumber2(nIsNeg ? 1 / k4 : k4); + } else if (POW_PRECISION) { + k4 = mathceil(POW_PRECISION / LOG_BASE + 2); + } + if (nIsBig) { + half = new BigNumber2(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd(n3); + } else { + i2 = Math.abs(+valueOf(n3)); + nIsOdd = i2 % 2; + } + y4 = new BigNumber2(ONE); + for (; ; ) { + if (nIsOdd) { + y4 = y4.times(x3); + if (!y4.c) + break; + if (k4) { + if (y4.c.length > k4) + y4.c.length = k4; + } else if (isModExp) { + y4 = y4.mod(m3); + } + } + if (i2) { + i2 = mathfloor(i2 / 2); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd(n3); + } else { + i2 = +valueOf(n3); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } + } + x3 = x3.times(x3); + if (k4) { + if (x3.c && x3.c.length > k4) + x3.c.length = k4; + } else if (isModExp) { + x3 = x3.mod(m3); + } + } + if (isModExp) + return y4; + if (nIsNeg) + y4 = ONE.div(y4); + return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber2(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { + return (b4 = compare2(this, new BigNumber2(y4, b4))) === 1 || b4 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { + return (b4 = compare2(this, new BigNumber2(y4, b4))) === -1 || b4 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y4, b4) { + var i2, j2, t, xLTy, x3 = this, a3 = x3.s; + y4 = new BigNumber2(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber2(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.plus(y4); + } + var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y4.s = -b4, y4) : new BigNumber2(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y4.s = -b4, y4) : new BigNumber2(xc[0] ? x3 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (xLTy = a3 < 0) { + a3 = -a3; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); + for (b4 = a3; b4--; t.push(0)) + ; + t.reverse(); + } else { + j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; + for (a3 = b4 = 0; b4 < j2; b4++) { + if (xc[b4] != yc[b4]) { + xLTy = xc[b4] < yc[b4]; + break; + } + } + } + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y4.s = -y4.s; + } + b4 = (j2 = yc.length) - (i2 = xc.length); + if (b4 > 0) + for (; b4--; xc[i2++] = 0) + ; + b4 = BASE - 1; + for (; j2 > a3; ) { + if (xc[--j2] < yc[j2]) { + for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) + ; + --xc[i2]; + xc[j2] += BASE; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y4.s = ROUNDING_MODE == 3 ? -1 : 1; + y4.c = [y4.e = 0]; + return y4; + } + return normalise(y4, xc, ye); + }; + P2.modulo = P2.mod = function(y4, b4) { + var q2, s2, x3 = this; + y4 = new BigNumber2(y4, b4); + if (!x3.c || !y4.s || y4.c && !y4.c[0]) { + return new BigNumber2(NaN); + } else if (!y4.c || x3.c && !x3.c[0]) { + return new BigNumber2(x3); + } + if (MODULO_MODE == 9) { + s2 = y4.s; + y4.s = 1; + q2 = div(x3, y4, 0, 3); + y4.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y4, 0, MODULO_MODE); + } + y4 = x3.minus(q2.times(y4)); + if (!y4.c[0] && MODULO_MODE == 1) + y4.s = x3.s; + return y4; + }; + P2.multipliedBy = P2.times = function(y4, b4) { + var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber2(y4, b4)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y4.c = y4.e = y4.s = null; + } else { + y4.s *= x3.s; + if (!xc || !yc) { + y4.c = y4.e = null; + } else { + y4.c = [0]; + y4.e = 0; + } + } + return y4; + } + e2 = bitFloor(x3.e / LOG_BASE) + bitFloor(y4.e / LOG_BASE); + y4.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i2 = xcL; + xcL = ycL; + ycL = i2; + } + for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) + ; + base3 = BASE; + sqrtBase = SQRT_BASE; + for (i2 = ycL; --i2 >= 0; ) { + c4 = 0; + ylo = yc[i2] % sqrtBase; + yhi = yc[i2] / sqrtBase | 0; + for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { + xlo = xc[--k4] % sqrtBase; + xhi = xc[k4] / sqrtBase | 0; + m3 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; + c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base3; + } + zc[j2] = c4; + } + if (c4) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y4, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber2(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y4, b4) { + var t, x3 = this, a3 = x3.s; + y4 = new BigNumber2(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber2(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.minus(y4); + } + var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber2(a3 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y4 : new BigNumber2(xc[0] ? x3 : a3 * 0); + } + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (a3 > 0) { + ye = xe; + t = yc; + } else { + a3 = -a3; + t = xc; + } + t.reverse(); + for (; a3--; t.push(0)) + ; + t.reverse(); + } + a3 = xc.length; + b4 = yc.length; + if (a3 - b4 < 0) { + t = yc; + yc = xc; + xc = t; + b4 = a3; + } + for (a3 = 0; b4; ) { + a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE | 0; + xc[b4] = BASE === xc[b4] ? 0 : xc[b4] % BASE; + } + if (a3) { + xc = [a3].concat(xc); + ++ye; + } + return normalise(y4, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm) { + var c4, n3, v2, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber2(x3), sd, rm); + } + if (!(c4 = x3.c)) + return null; + v2 = c4.length - 1; + n3 = v2 * LOG_BASE + 1; + if (v2 = c4[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x3.e + 1 > n3) + n3 = x3.e + 1; + return n3; + }; + P2.shiftedBy = function(k4) { + intCheck(k4, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times("1e" + k4); + }; + P2.squareRoot = P2.sqrt = function() { + var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); + if (s2 !== 1 || !c4 || !c4[0]) { + return new BigNumber2(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString(c4); + if ((n3.length + e2) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e2; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; + } + r = new BigNumber2(n3); + } else { + r = new BigNumber2(s2 + ""); + } + if (r.c[0]) { + e2 = r.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t = r; + r = half.times(t.plus(div(x3, t, dp, 1))); + if (coeffToString(t.c).slice(0, s2) === (n3 = coeffToString(r.c)).slice(0, s2)) { + if (r.e < e2) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + if (t.times(t).eq(x3)) { + r = t; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m3 = !r.times(r).eq(x3); + } + break; + } + } + } + } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format2) { + var str, x3 = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError + "Argument not an object: " + format2); + } + str = x3.toFixed(dp, rm); + if (x3.c) { + var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) { + i2 = g1; + g1 = g22; + g22 = i2; + len -= i2; + } + if (g1 > 0 && len > 0) { + i2 = len % g1 || g1; + intPart = intDigits.substr(0, i2); + for (; i2 < len; i2 += g1) + intPart += groupSeparator + intDigits.substr(i2, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i2); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format2.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P2.toFraction = function(md) { + var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; + if (md != null) { + n3 = new BigNumber2(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber2(x3); + d3 = new BigNumber2(ONE); + n1 = d0 = new BigNumber2(ONE); + d1 = n0 = new BigNumber2(ONE); + s2 = coeffToString(xc); + e2 = d3.e = s2.length - x3.e - 1; + d3.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber2(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d3, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d3 = n3.minus(q2.times(d22 = d3)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( + div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + P2.toString = function(b4) { + var str, n3 = this, s2 = n3.s, e2 = n3.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b4 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n3.c), e2) : toFixedPoint(coeffToString(n3.c), e2, "0"); + } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { + n3 = round(new BigNumber2(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n3.c), n3.e, "0"); + } else { + intCheck(b4, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint(coeffToString(n3.c), e2, "0"), 10, b4, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + P2[Symbol.toStringTag] = "BigNumber"; + P2[Symbol.for("nodejs.util.inspect.custom")] = P2.valueOf; + if (configObject != null) + BigNumber2.set(configObject); + return BigNumber2; +} +function bitFloor(n3) { + var i2 = n3 | 0; + return n3 > 0 || n3 === i2 ? i2 : i2 - 1; +} +function coeffToString(a3) { + var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; + for (; i2 < j2; ) { + s2 = a3[i2++] + ""; + z3 = LOG_BASE - s2.length; + for (; z3--; s2 = "0" + s2) + ; + r += s2; + } + for (j2 = r.length; r.charCodeAt(--j2) === 48; ) + ; + return r.slice(0, j2 + 1 || 1); +} +function compare2(x3, y4) { + var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; + if (!i2 || !j2) + return null; + a3 = xc && !xc[0]; + b4 = yc && !yc[0]; + if (a3 || b4) + return a3 ? b4 ? 0 : -j2 : i2; + if (i2 != j2) + return i2; + a3 = i2 < 0; + b4 = k4 == l4; + if (!xc || !yc) + return b4 ? 0 : !xc ^ a3 ? 1 : -1; + if (!b4) + return k4 > l4 ^ a3 ? 1 : -1; + j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; + for (i2 = 0; i2 < j2; i2++) + if (xc[i2] != yc[i2]) + return xc[i2] > yc[i2] ^ a3 ? 1 : -1; + return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; +} +function intCheck(n3, min, max, name2) { + if (n3 < min || n3 > max || n3 !== mathfloor(n3)) { + throw Error(bignumberError + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } +} +function isOdd(n3) { + var k4 = n3.c.length - 1; + return bitFloor(n3.e / LOG_BASE) == k4 && n3.c[k4] % 2 != 0; +} +function toExponential(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; +} +function toFixedPoint(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + "."; ++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len; --e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; +} +var BigNumber = clone(); +var bignumber_default = BigNumber; + +// src/utils/amount.ts +bignumber_default.config({ ROUNDING_MODE: bignumber_default.ROUND_FLOOR }); +var parseAmount = ({ + amount, + decimals +}) => { + if (decimals < 0) + throw new Error("Decimal places shouldn't be negative number!"); + return BigInt(new bignumber_default(amount).shiftedBy(decimals).toFixed()); +}; +var formatAmount = ({ + amount, + decimals, + rounding = decimals +}) => { + if (decimals < 0) + throw new Error("Decimal places shouldn't be negative number!"); + return new bignumber_default(amount).shiftedBy(-decimals).decimalPlaces(rounding).toFixed(); +}; +var export_Account = import_account4.Account; +var export_Address = import_address4.Address; +var export_AddressType = import_address5.AddressType; +var export_AddressValue = import_address5.AddressValue; +var export_BigUIntType = import_numerical.BigUIntType; +var export_BigUIntValue = import_numerical.BigUIntValue; +var export_BooleanType = import_boolean.BooleanType; +var export_BooleanValue = import_boolean.BooleanValue; +var export_BytesType = import_bytes7.BytesType; +var export_BytesValue = import_bytes7.BytesValue; +var export_ContractQueryResponse = import_contractQueryResponse2.ContractQueryResponse; +var export_Message = import_message.Message; +var export_MessageComputer = import_message.MessageComputer; +var export_QueryArguments = import_interface.QueryArguments; +var export_SignableMessage = import_signableMessage2.SignableMessage; +var export_SmartContractTransactionsFactory = import_transactionsFactories.SmartContractTransactionsFactory; +var export_SmartContractTransactionsOutcomeParser = import_transactionsOutcomeParsers.SmartContractTransactionsOutcomeParser; +var export_Token = import_tokens.Token; +var export_TokenComputer = import_tokens.TokenComputer; +var export_TokenManagementTransactionsFactory = import_transactionsFactories.TokenManagementTransactionsFactory; +var export_TokenManagementTransactionsOutcomeParser = import_transactionsOutcomeParsers.TokenManagementTransactionsOutcomeParser; +var export_TokenOperationsFactory = import_tokenOperations.TokenOperationsFactory; +var export_TokenOperationsFactoryConfig = import_tokenOperations.TokenOperationsFactoryConfig; +var export_TokenOperationsOutcomeParser = import_tokenOperations.TokenOperationsOutcomeParser; +var export_TokenTransfer = import_tokens.TokenTransfer; +var export_Transaction = import_transaction3.Transaction; +var export_TransactionComputer = import_transactionComputer.TransactionComputer; +var export_TransactionEventsParser = import_transactionsOutcomeParsers.TransactionEventsParser; +var export_TransactionWatcher = import_transactionWatcher2.TransactionWatcher; +var export_TransactionsFactoryConfig = import_transactionsFactories.TransactionsFactoryConfig; +var export_TransferTransactionsFactory = import_transactionsFactories.TransferTransactionsFactory; +var export_U16Type = import_numerical.U16Type; +var export_U16Value = import_numerical.U16Value; +var export_U32Type = import_numerical.U32Type; +var export_U32Value = import_numerical.U32Value; +var export_U64Type = import_numerical.U64Type; +var export_U64Value = import_numerical.U64Value; +var export_U8Type = import_numerical.U8Type; +var export_U8Value = import_numerical.U8Value; +export { + export_Account as Account, + export_Address as Address, + export_AddressType as AddressType, + export_AddressValue as AddressValue, + export_BigUIntType as BigUIntType, + export_BigUIntValue as BigUIntValue, + export_BooleanType as BooleanType, + export_BooleanValue as BooleanValue, + export_BytesType as BytesType, + export_BytesValue as BytesValue, + export_ContractQueryResponse as ContractQueryResponse, + DappCoreWCV2CustomMethodsEnum, + ElvenJS, + EventStoreEvents, + LoginMethodsEnum, + export_Message as Message, + export_MessageComputer as MessageComputer, + export_QueryArguments as QueryArguments, + export_SignableMessage as SignableMessage, + export_SmartContractTransactionsFactory as SmartContractTransactionsFactory, + export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser, + export_Token as Token, + export_TokenComputer as TokenComputer, + export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory, + export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser, + export_TokenOperationsFactory as TokenOperationsFactory, + export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig, + export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser, + export_TokenTransfer as TokenTransfer, + export_Transaction as Transaction, + export_TransactionComputer as TransactionComputer, + export_TransactionEventsParser as TransactionEventsParser, + export_TransactionWatcher as TransactionWatcher, + export_TransactionsFactoryConfig as TransactionsFactoryConfig, + export_TransferTransactionsFactory as TransferTransactionsFactory, + export_U16Type as U16Type, + export_U16Value as U16Value, + export_U32Type as U32Type, + export_U32Value as U32Value, + export_U64Type as U64Type, + export_U64Value as U64Value, + export_U8Type as U8Type, + export_U8Value as U8Value, + WebWalletUrlParamsEnum, + formatAmount, + parseAmount +}; /*! Bundled license information: ieee754/index.js: @@ -61,9 +54994,6 @@ buffer/index.js: * @license MIT *) -punycode/punycode.js: - (*! https://mths.be/punycode v1.4.1 by @mathias *) - buffer/index.js: (*! * The buffer module from node.js, for the browser. @@ -90,4 +55020,14 @@ tslib/tslib.es6.js: OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** *) + +@walletconnect/utils/dist/index.cjs.js: + (** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + *) */ diff --git a/build/types/elven.d.ts b/build/types/elven.d.ts index 573de0a..0a357f0 100644 --- a/build/types/elven.d.ts +++ b/build/types/elven.d.ts @@ -1,13 +1,13 @@ -export { TokenTransfer } from '@multiversx/sdk-core/out/tokenTransfer'; -export { TransferTransactionsFactory } from '@multiversx/sdk-core/out/transferTransactionsFactory'; -export { GasEstimator } from '@multiversx/sdk-core/out/gasEstimator'; +export { TokenTransfer, TokenComputer, Token, } from '@multiversx/sdk-core/out/tokens'; +export { TokenOperationsFactory, TokenOperationsFactoryConfig, TokenOperationsOutcomeParser, } from '@multiversx/sdk-core/out/tokenOperations'; +export { TransferTransactionsFactory, TransactionsFactoryConfig, SmartContractTransactionsFactory, TokenManagementTransactionsFactory, } from '@multiversx/sdk-core/out/transactionsFactories/'; +export { SmartContractTransactionsOutcomeParser, TokenManagementTransactionsOutcomeParser, TransactionEventsParser, } from '@multiversx/sdk-core/out/transactionsOutcomeParsers'; export { Address } from '@multiversx/sdk-core/out/address'; export { Account } from '@multiversx/sdk-core/out/account'; export { Transaction } from '@multiversx/sdk-core/out/transaction'; -export { TransactionPayload } from '@multiversx/sdk-core/out/transactionPayload'; +export { TransactionComputer } from '@multiversx/sdk-core/out/transactionComputer'; +export { Message, MessageComputer } from '@multiversx/sdk-core/out/message'; export { TransactionWatcher } from '@multiversx/sdk-core/out/transactionWatcher'; -export { SmartContract } from '@multiversx/sdk-core/out/smartcontracts/smartContract'; -export { ContractFunction } from '@multiversx/sdk-core/out/smartcontracts/function'; export { SignableMessage } from '@multiversx/sdk-core/out/signableMessage'; export { BytesType, BytesValue, } from '@multiversx/sdk-core/out/smartcontracts/typesystem/bytes'; export { U16Type, U16Value, U32Type, U32Value, U64Type, U64Value, U8Type, U8Value, BigUIntType, BigUIntValue, } from '@multiversx/sdk-core/out/smartcontracts/typesystem/numerical'; @@ -16,4 +16,5 @@ export { AddressType, AddressValue, } from '@multiversx/sdk-core/out/smartcontra export { QueryArguments } from '@multiversx/sdk-core/out/smartcontracts/interface'; export { ContractQueryResponse } from '@multiversx/sdk-network-providers/out/contractQueryResponse'; export { ElvenJS } from './main'; +export { parseAmount, formatAmount } from './utils/amount'; export * from './types'; diff --git a/build/types/utils/amount.d.ts b/build/types/utils/amount.d.ts new file mode 100644 index 0000000..0a5502d --- /dev/null +++ b/build/types/utils/amount.d.ts @@ -0,0 +1,21 @@ +type AmountArgs = { + amount: string; + decimals: number; + rounding?: number; +}; +/** + * Parses the amount from string + * @param amount + * @param decimals + * @returns bigInt + */ +export declare const parseAmount: ({ amount, decimals, }: Omit) => bigint; +/** + * Formats the amount from string (bigInt) + * @param amount + * @param decimals + * @param rounding + * @returns string + */ +export declare const formatAmount: ({ amount, decimals, rounding, }: AmountArgs) => string; +export {}; diff --git a/esbuild.config.cjs b/esbuild.config.cjs index 9853a86..b3f3a77 100644 --- a/esbuild.config.cjs +++ b/esbuild.config.cjs @@ -10,7 +10,7 @@ esbuild entryPoints: ['./src/elven.ts'], bundle: true, metafile: true, - minify: true, + minify: false, outdir: 'build', platform: 'browser', }) diff --git a/example/elven.js b/example/elven.js index 4a74182..aab57b0 100644 --- a/example/elven.js +++ b/example/elven.js @@ -1,53 +1,54986 @@ -var D4=Object.create;var Ef=Object.defineProperty;var P4=Object.getOwnPropertyDescriptor;var R4=Object.getOwnPropertyNames;var B4=Object.getPrototypeOf,L4=Object.prototype.hasOwnProperty;var TS=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var he=(t,e)=>()=>(t&&(e=t(t=0)),e);var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ft=(t,e)=>{for(var r in e)Ef(t,r,{get:e[r],enumerable:!0})},wf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of R4(e))!L4.call(t,i)&&i!==r&&Ef(t,i,{get:()=>e[i],enumerable:!(n=P4(e,i))||n.enumerable});return t},Qt=(t,e,r)=>(wf(t,e,"default"),r&&wf(r,e,"default")),be=(t,e,r)=>(r=t!=null?D4(B4(t)):{},wf(e||!t||!t.__esModule?Ef(r,"default",{value:t,enumerable:!0}):r,t)),ht=t=>wf(Ef({},"__esModule",{value:!0}),t);var $0=v(vf=>{"use strict";l();vf.byteLength=M4;vf.toByteArray=q4;vf.fromByteArray=k4;var sn=[],Tr=[],F4=typeof Uint8Array<"u"?Uint8Array:Array,W0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ts=0,CS=W0.length;Ts0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function M4(t){var e=xS(t),r=e[0],n=e[1];return(r+n)*3/4-n}function U4(t,e,r){return(e+r)*3/4-r}function q4(t){var e,r=xS(t),n=r[0],i=r[1],s=new F4(U4(t,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tr[t.charCodeAt(u)]<<2|Tr[t.charCodeAt(u+1)]>>4,s[o++]=e&255),i===1&&(e=Tr[t.charCodeAt(u)]<<10|Tr[t.charCodeAt(u+1)]<<4|Tr[t.charCodeAt(u+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function V4(t){return sn[t>>18&63]+sn[t>>12&63]+sn[t>>6&63]+sn[t&63]}function H4(t,e,r){for(var n,i=[],s=e;sa?a:o+s));return n===1?(e=t[r-1],i.push(sn[e>>2]+sn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(sn[e>>10]+sn[e>>4&63]+sn[e<<2&63]+"=")),i.join("")}});var Y0=v(K0=>{l();K0.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,u=(1<>1,f=-7,d=r?i-1:0,g=r?-1:1,m=t[e+d];for(d+=g,s=m&(1<<-f)-1,m>>=-f,f+=a;f>0;s=s*256+t[e+d],d+=g,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=g,f-=8);if(s===0)s=1-c;else{if(s===u)return o?NaN:(m?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(m?-1:1)*o*Math.pow(2,s-n)};K0.write=function(t,e,r,n,i,s){var o,a,u,c=s*8-i-1,f=(1<>1,g=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,m=n?0:s-1,y=n?1:-1,A=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+d>=1?e+=g/u:e+=g*Math.pow(2,1-d),e*u>=2&&(o++,u/=2),o+d>=f?(a=0,o=f):o+d>=1?(a=(e*u-1)*Math.pow(2,i),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+m]=a&255,m+=y,a/=256,i-=8);for(o=o<0;t[r+m]=o&255,m+=y,o/=256,c-=8);t[r+m-y]|=A*128}});var HS=v(No=>{"use strict";l();var J0=$0(),xo=Y0(),NS=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;No.Buffer=$;No.SlowBuffer=$4;No.INSPECT_MAX_BYTES=50;var Af=2147483647;No.kMaxLength=Af;$.TYPED_ARRAY_SUPPORT=G4();!$.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 G4(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty($.prototype,"parent",{enumerable:!0,get:function(){if($.isBuffer(this))return this.buffer}});Object.defineProperty($.prototype,"offset",{enumerable:!0,get:function(){if($.isBuffer(this))return this.byteOffset}});function zn(t){if(t>Af)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,$.prototype),e}function $(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return tm(t)}return PS(t,e,r)}$.poolSize=8192;function PS(t,e,r){if(typeof t=="string")return Q4(t,e);if(ArrayBuffer.isView(t))return z4(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(on(t,ArrayBuffer)||t&&on(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(on(t,SharedArrayBuffer)||t&&on(t.buffer,SharedArrayBuffer)))return Z0(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return $.from(n,e,r);var i=W4(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return $.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}$.from=function(t,e,r){return PS(t,e,r)};Object.setPrototypeOf($.prototype,Uint8Array.prototype);Object.setPrototypeOf($,Uint8Array);function RS(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function j4(t,e,r){return RS(t),t<=0?zn(t):e!==void 0?typeof r=="string"?zn(t).fill(e,r):zn(t).fill(e):zn(t)}$.alloc=function(t,e,r){return j4(t,e,r)};function tm(t){return RS(t),zn(t<0?0:rm(t)|0)}$.allocUnsafe=function(t){return tm(t)};$.allocUnsafeSlow=function(t){return tm(t)};function Q4(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!$.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=BS(t,e)|0,n=zn(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function X0(t){for(var e=t.length<0?0:rm(t.length)|0,r=zn(e),n=0;n=Af)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Af.toString(16)+" bytes");return t|0}function $4(t){return+t!=t&&(t=0),$.alloc(+t)}$.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==$.prototype};$.compare=function(e,r){if(on(e,Uint8Array)&&(e=$.from(e,e.offset,e.byteLength)),on(r,Uint8Array)&&(r=$.from(r,r.offset,r.byteLength)),!$.isBuffer(e)||!$.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?$.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if($.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function BS(t,e){if($.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||on(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return em(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return VS(t).length;default:if(i)return n?-1:em(t).length;e=(""+e).toLowerCase(),i=!0}}$.byteLength=BS;function K4(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return s5(this,e,r);case"utf8":case"utf-8":return FS(this,e,r);case"ascii":return n5(this,e,r);case"latin1":case"binary":return i5(this,e,r);case"base64":return t5(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return o5(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}$.prototype._isBuffer=!0;function Cs(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}$.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};NS&&($.prototype[NS]=$.prototype.inspect);$.prototype.compare=function(e,r,n,i,s){if(on(e,Uint8Array)&&(e=$.from(e,e.offset,e.byteLength)),!$.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,a=n-r,u=Math.min(o,a),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,nm(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=$.from(e,n)),$.isBuffer(e))return e.length===0?-1:OS(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):OS(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function OS(t,e,r,n,i){var s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function u(m,y){return s===1?m[y]:m.readUInt16BE(y*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-a),c=r;c>=0;c--){for(var d=!0,g=0;gi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Y4(this,e,r,n);case"utf8":case"utf-8":return J4(this,e,r,n);case"ascii":case"latin1":case"binary":return X4(this,e,r,n);case"base64":return Z4(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return e5(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};$.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function t5(t,e,r){return e===0&&r===t.length?J0.fromByteArray(t):J0.fromByteArray(t.slice(e,r))}function FS(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+a<=r){var u,c,f,d;switch(a){case 1:s<128&&(o=s);break;case 2:u=t[i+1],(u&192)===128&&(d=(s&31)<<6|u&63,d>127&&(o=d));break;case 3:u=t[i+1],c=t[i+2],(u&192)===128&&(c&192)===128&&(d=(s&15)<<12|(u&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:u=t[i+1],c=t[i+2],f=t[i+3],(u&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(u&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return r5(n)}var DS=4096;function r5(t){var e=t.length;if(e<=DS)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}$.prototype.readUintLE=$.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};$.prototype.readUint8=$.prototype.readUInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]};$.prototype.readUint16LE=$.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]|this[e+1]<<8};$.prototype.readUint16BE=$.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]<<8|this[e+1]};$.prototype.readUint32LE=$.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};$.prototype.readUint32BE=$.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};$.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};$.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};$.prototype.readInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};$.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};$.prototype.readInt16BE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};$.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};$.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};$.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),xo.read(this,e,!0,23,4)};$.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),xo.read(this,e,!1,23,4)};$.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),xo.read(this,e,!0,52,8)};$.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),xo.read(this,e,!1,52,8)};function lr(t,e,r,n,i,s){if(!$.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}$.prototype.writeUintLE=$.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;lr(this,e,r,n,s,0)}var o=1,a=0;for(this[r]=e&255;++a>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;lr(this,e,r,n,s,0)}var o=n-1,a=1;for(this[r+o]=e&255;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+n};$.prototype.writeUint8=$.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,1,255,0),this[r]=e&255,r+1};$.prototype.writeUint16LE=$.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};$.prototype.writeUint16BE=$.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};$.prototype.writeUint32LE=$.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};$.prototype.writeUint32BE=$.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};$.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);lr(this,e,r,n,s-1,-s)}var o=0,a=1,u=0;for(this[r]=e&255;++o>0)-u&255;return r+n};$.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);lr(this,e,r,n,s-1,-s)}var o=n-1,a=1,u=0;for(this[r+o]=e&255;--o>=0&&(a*=256);)e<0&&u===0&&this[r+o+1]!==0&&(u=1),this[r+o]=(e/a>>0)-u&255;return r+n};$.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};$.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};$.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};$.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};$.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||lr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function MS(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function US(t,e,r,n,i){return e=+e,r=r>>>0,i||MS(t,e,r,4,34028234663852886e22,-34028234663852886e22),xo.write(t,e,r,n,23,4),r+4}$.prototype.writeFloatLE=function(e,r,n){return US(this,e,r,!0,n)};$.prototype.writeFloatBE=function(e,r,n){return US(this,e,r,!1,n)};function qS(t,e,r,n,i){return e=+e,r=r>>>0,i||MS(t,e,r,8,17976931348623157e292,-17976931348623157e292),xo.write(t,e,r,n,52,8),r+8}$.prototype.writeDoubleLE=function(e,r,n){return qS(this,e,r,!0,n)};$.prototype.writeDoubleBE=function(e,r,n){return qS(this,e,r,!1,n)};$.prototype.copy=function(e,r,n,i){if(!$.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function c5(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function VS(t){return J0.toByteArray(u5(t))}function bf(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function on(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function nm(t){return t!==t}var f5=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var zS=v(($se,QS)=>{l();var vt=QS.exports={},an,un;function im(){throw new Error("setTimeout has not been defined")}function sm(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?an=setTimeout:an=im}catch{an=im}try{typeof clearTimeout=="function"?un=clearTimeout:un=sm}catch{un=sm}})();function kS(t){if(an===setTimeout)return setTimeout(t,0);if((an===im||!an)&&setTimeout)return an=setTimeout,setTimeout(t,0);try{return an(t,0)}catch{try{return an.call(null,t,0)}catch{return an.call(this,t,0)}}}function d5(t){if(un===clearTimeout)return clearTimeout(t);if((un===sm||!un)&&clearTimeout)return un=clearTimeout,clearTimeout(t);try{return un(t)}catch{try{return un.call(null,t)}catch{return un.call(this,t)}}}var Wn=[],Oo=!1,xs,If=-1;function h5(){!Oo||!xs||(Oo=!1,xs.length?Wn=xs.concat(Wn):If=-1,Wn.length&&GS())}function GS(){if(!Oo){var t=kS(h5);Oo=!0;for(var e=Wn.length;e;){for(xs=Wn,Wn=[];++If1)for(var r=1;r{h=be(HS()),p=be(zS()),p5=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=p5});var Yt=v((WS,_f)=>{l();(function(t){"use strict";var e,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,i=Math.floor,s="[BigNumber Error] ",o=s+"Number primitive has more than 15 significant digits: ",a=1e14,u=14,c=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],d=1e7,g=1e9;function m(S){var N,_,T,B=U.prototype={constructor:U,toString:null,valueOf:null},X=new U(1),z=20,k=4,Q=-7,K=21,ye=-1e7,ce=1e7,ie=!1,J=1,oe=0,re={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},se="0123456789abcdefghijklmnopqrstuvwxyz";function U(w,E){var I,P,C,D,L,x,F,G,V=this;if(!(V instanceof U))return new U(w,E);if(E==null){if(w&&w._isBigNumber===!0){V.s=w.s,!w.c||w.e>ce?V.c=V.e=null:w.e=10;L/=10,D++);D>ce?V.c=V.e=null:(V.e=D,V.c=[w]);return}G=String(w)}else{if(!r.test(G=String(w)))return T(V,G,x);V.s=G.charCodeAt(0)==45?(G=G.slice(1),-1):1}(D=G.indexOf("."))>-1&&(G=G.replace(".","")),(L=G.search(/e/i))>0?(D<0&&(D=L),D+=+G.slice(L+1),G=G.substring(0,L)):D<0&&(D=G.length)}else{if(R(E,2,se.length,"Base"),E==10)return V=new U(w),ae(V,z+V.e+1,k);if(G=String(w),x=typeof w=="number"){if(w*0!=0)return T(V,G,x,E);if(V.s=1/w<0?(G=G.slice(1),-1):1,U.DEBUG&&G.replace(/^0\.0*|\./,"").length>15)throw Error(o+w)}else V.s=G.charCodeAt(0)===45?(G=G.slice(1),-1):1;for(I=se.slice(0,E),D=L=0,F=G.length;LD){D=F;continue}}else if(!C&&(G==G.toUpperCase()&&(G=G.toLowerCase())||G==G.toLowerCase()&&(G=G.toUpperCase()))){C=!0,L=-1,D=0;continue}return T(V,String(w),x,E)}x=!1,G=_(G,E,10,V.s),(D=G.indexOf("."))>-1?G=G.replace(".",""):D=G.length}for(L=0;G.charCodeAt(L)===48;L++);for(F=G.length;G.charCodeAt(--F)===48;);if(G=G.slice(L,++F)){if(F-=L,x&&U.DEBUG&&F>15&&(w>c||w!==i(w)))throw Error(o+V.s*w);if((D=D-L-1)>ce)V.c=V.e=null;else if(D=-g&&C<=g&&C===i(C)){if(P[0]===0){if(C===0&&P.length===1)return!0;break e}if(E=(C+1)%u,E<1&&(E+=u),String(P[0]).length==E){for(E=0;E=a||I!==i(I))break e;if(I!==0)return!0}}}else if(P===null&&C===null&&(D===null||D===1||D===-1))return!0;throw Error(s+"Invalid BigNumber: "+w)},U.maximum=U.max=function(){return ue(arguments,B.lt)},U.minimum=U.min=function(){return ue(arguments,B.gt)},U.random=function(){var w=9007199254740992,E=Math.random()*w&2097151?function(){return i(Math.random()*w)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(I){var P,C,D,L,x,F=0,G=[],V=new U(X);if(I==null?I=z:R(I,0,g),L=n(I/u),ie)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(L*=2));F>>11),x>=9e15?(C=crypto.getRandomValues(new Uint32Array(2)),P[F]=C[0],P[F+1]=C[1]):(G.push(x%1e14),F+=2);F=L/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(L*=7);F=9e15?crypto.randomBytes(7).copy(P,F):(G.push(x%1e14),F+=7);F=L/7}else throw ie=!1,Error(s+"crypto unavailable");if(!ie)for(;F=10;x/=10,F++);FC-1&&(x[L+1]==null&&(x[L+1]=0),x[L+1]+=x[L]/C|0,x[L]%=C)}return x.reverse()}return function(I,P,C,D,L){var x,F,G,V,ee,Ae,Se,Be,it=I.indexOf("."),dt=z,De=k;for(it>=0&&(V=oe,oe=0,I=I.replace(".",""),Be=new U(P),Ae=Be.pow(I.length-it),oe=V,Be.c=E(b(A(Ae.c),Ae.e,"0"),10,C,w),Be.e=Be.c.length),Se=E(I,P,C,L?(x=se,w):(x=w,se)),G=V=Se.length;Se[--V]==0;Se.pop());if(!Se[0])return x.charAt(0);if(it<0?--G:(Ae.c=Se,Ae.e=G,Ae.s=D,Ae=N(Ae,Be,dt,De,C),Se=Ae.c,ee=Ae.r,G=Ae.e),F=G+dt+1,it=Se[F],V=C/2,ee=ee||F<0||Se[F+1]!=null,ee=De<4?(it!=null||ee)&&(De==0||De==(Ae.s<0?3:2)):it>V||it==V&&(De==4||ee||De==6&&Se[F-1]&1||De==(Ae.s<0?8:7)),F<1||!Se[0])I=ee?b(x.charAt(1),-dt,x.charAt(0)):x.charAt(0);else{if(Se.length=F,ee)for(--C;++Se[--F]>C;)Se[F]=0,F||(++G,Se=[1].concat(Se));for(V=Se.length;!Se[--V];);for(it=0,I="";it<=V;I+=x.charAt(Se[it++]));I=b(I,G,x.charAt(0))}return I}}(),N=function(){function w(P,C,D){var L,x,F,G,V=0,ee=P.length,Ae=C%d,Se=C/d|0;for(P=P.slice();ee--;)F=P[ee]%d,G=P[ee]/d|0,L=Se*F+G*Ae,x=Ae*F+L%d*d+V,V=(x/D|0)+(L/d|0)+Se*G,P[ee]=x%D;return V&&(P=[V].concat(P)),P}function E(P,C,D,L){var x,F;if(D!=L)F=D>L?1:-1;else for(x=F=0;xC[x]?1:-1;break}return F}function I(P,C,D,L){for(var x=0;D--;)P[D]-=x,x=P[D]1;P.splice(0,1));}return function(P,C,D,L,x){var F,G,V,ee,Ae,Se,Be,it,dt,De,Ve,Lt,wi,_s,Ss,cr,Qn,Kt=P.s==C.s?1:-1,Ft=P.c,Je=C.c;if(!Ft||!Ft[0]||!Je||!Je[0])return new U(!P.s||!C.s||(Ft?Je&&Ft[0]==Je[0]:!Je)?NaN:Ft&&Ft[0]==0||!Je?Kt*0:Kt/0);for(it=new U(Kt),dt=it.c=[],G=P.e-C.e,Kt=D+G+1,x||(x=a,G=y(P.e/u)-y(C.e/u),Kt=Kt/u|0),V=0;Je[V]==(Ft[V]||0);V++);if(Je[V]>(Ft[V]||0)&&G--,Kt<0)dt.push(1),ee=!0;else{for(_s=Ft.length,cr=Je.length,V=0,Kt+=2,Ae=i(x/(Je[0]+1)),Ae>1&&(Je=w(Je,Ae,x),Ft=w(Ft,Ae,x),cr=Je.length,_s=Ft.length),wi=cr,De=Ft.slice(0,cr),Ve=De.length;Ve=x/2&&Ss++;do{if(Ae=0,F=E(Je,De,cr,Ve),F<0){if(Lt=De[0],cr!=Ve&&(Lt=Lt*x+(De[1]||0)),Ae=i(Lt/Ss),Ae>1)for(Ae>=x&&(Ae=x-1),Se=w(Je,Ae,x),Be=Se.length,Ve=De.length;E(Se,De,Be,Ve)==1;)Ae--,I(Se,cr=10;Kt/=10,V++);ae(it,D+(it.e=V+G*u-1)+1,L,ee)}else it.e=G,it.r=+ee;return it}}();function fe(w,E,I,P){var C,D,L,x,F;if(I==null?I=k:R(I,0,8),!w.c)return w.toString();if(C=w.c[0],L=w.e,E==null)F=A(w.c),F=P==1||P==2&&(L<=Q||L>=K)?M(F,L):b(F,L,"0");else if(w=ae(new U(w),E,I),D=w.e,F=A(w.c),x=F.length,P==1||P==2&&(E<=D||D<=Q)){for(;xx){if(--E>0)for(F+=".";E--;F+="0");}else if(E+=D-x,E>0)for(D+1==x&&(F+=".");E--;F+="0");return w.s<0&&C?"-"+F:F}function ue(w,E){for(var I,P=1,C=new U(w[0]);P=10;C/=10,P++);return(I=P+I*u-1)>ce?w.c=w.e=null:I=10;x/=10,C++);if(D=E-C,D<0)D+=u,L=E,F=ee[G=0],V=F/Ae[C-L-1]%10|0;else if(G=n((D+1)/u),G>=ee.length)if(P){for(;ee.length<=G;ee.push(0));F=V=0,C=1,D%=u,L=D-u+1}else break e;else{for(F=x=ee[G],C=1;x>=10;x/=10,C++);D%=u,L=D-u+C,V=L<0?0:F/Ae[C-L-1]%10|0}if(P=P||E<0||ee[G+1]!=null||(L<0?F:F%Ae[C-L-1]),P=I<4?(V||P)&&(I==0||I==(w.s<0?3:2)):V>5||V==5&&(I==4||P||I==6&&(D>0?L>0?F/Ae[C-L]:0:ee[G-1])%10&1||I==(w.s<0?8:7)),E<1||!ee[0])return ee.length=0,P?(E-=w.e+1,ee[0]=Ae[(u-E%u)%u],w.e=-E||0):ee[0]=w.e=0,w;if(D==0?(ee.length=G,x=1,G--):(ee.length=G+1,x=Ae[u-D],ee[G]=L>0?i(F/Ae[C-L]%Ae[L])*x:0),P)for(;;)if(G==0){for(D=1,L=ee[0];L>=10;L/=10,D++);for(L=ee[0]+=x,x=1;L>=10;L/=10,x++);D!=x&&(w.e++,ee[0]==a&&(ee[0]=1));break}else{if(ee[G]+=x,ee[G]!=a)break;ee[G--]=0,x=1}for(D=ee.length;ee[--D]===0;ee.pop());}w.e>ce?w.c=w.e=null:w.e=K?M(E,I):b(E,I,"0"),w.s<0?"-"+E:E)}return B.absoluteValue=B.abs=function(){var w=new U(this);return w.s<0&&(w.s=1),w},B.comparedTo=function(w,E){return O(this,new U(w,E))},B.decimalPlaces=B.dp=function(w,E){var I,P,C,D=this;if(w!=null)return R(w,0,g),E==null?E=k:R(E,0,8),ae(new U(D),w+D.e+1,E);if(!(I=D.c))return null;if(P=((C=I.length-1)-y(this.e/u))*u,C=I[C])for(;C%10==0;C/=10,P--);return P<0&&(P=0),P},B.dividedBy=B.div=function(w,E){return N(this,new U(w,E),z,k)},B.dividedToIntegerBy=B.idiv=function(w,E){return N(this,new U(w,E),0,1)},B.exponentiatedBy=B.pow=function(w,E){var I,P,C,D,L,x,F,G,V,ee=this;if(w=new U(w),w.c&&!w.isInteger())throw Error(s+"Exponent not an integer: "+le(w));if(E!=null&&(E=new U(E)),x=w.e>14,!ee.c||!ee.c[0]||ee.c[0]==1&&!ee.e&&ee.c.length==1||!w.c||!w.c[0])return V=new U(Math.pow(+le(ee),x?2-q(w):+le(w))),E?V.mod(E):V;if(F=w.s<0,E){if(E.c?!E.c[0]:!E.s)return new U(NaN);P=!F&&ee.isInteger()&&E.isInteger(),P&&(ee=ee.mod(E))}else{if(w.e>9&&(ee.e>0||ee.e<-1||(ee.e==0?ee.c[0]>1||x&&ee.c[1]>=24e7:ee.c[0]<8e13||x&&ee.c[0]<=9999975e7)))return D=ee.s<0&&q(w)?-0:0,ee.e>-1&&(D=1/D),new U(F?1/D:D);oe&&(D=n(oe/u+2))}for(x?(I=new U(.5),F&&(w.s=1),G=q(w)):(C=Math.abs(+le(w)),G=C%2),V=new U(X);;){if(G){if(V=V.times(ee),!V.c)break;D?V.c.length>D&&(V.c.length=D):P&&(V=V.mod(E))}if(C){if(C=i(C/2),C===0)break;G=C%2}else if(w=w.times(I),ae(w,w.e+1,1),w.e>14)G=q(w);else{if(C=+le(w),C===0)break;G=C%2}ee=ee.times(ee),D?ee.c&&ee.c.length>D&&(ee.c.length=D):P&&(ee=ee.mod(E))}return P?V:(F&&(V=X.div(V)),E?V.mod(E):D?ae(V,oe,k,L):V)},B.integerValue=function(w){var E=new U(this);return w==null?w=k:R(w,0,8),ae(E,E.e+1,w)},B.isEqualTo=B.eq=function(w,E){return O(this,new U(w,E))===0},B.isFinite=function(){return!!this.c},B.isGreaterThan=B.gt=function(w,E){return O(this,new U(w,E))>0},B.isGreaterThanOrEqualTo=B.gte=function(w,E){return(E=O(this,new U(w,E)))===1||E===0},B.isInteger=function(){return!!this.c&&y(this.e/u)>this.c.length-2},B.isLessThan=B.lt=function(w,E){return O(this,new U(w,E))<0},B.isLessThanOrEqualTo=B.lte=function(w,E){return(E=O(this,new U(w,E)))===-1||E===0},B.isNaN=function(){return!this.s},B.isNegative=function(){return this.s<0},B.isPositive=function(){return this.s>0},B.isZero=function(){return!!this.c&&this.c[0]==0},B.minus=function(w,E){var I,P,C,D,L=this,x=L.s;if(w=new U(w,E),E=w.s,!x||!E)return new U(NaN);if(x!=E)return w.s=-E,L.plus(w);var F=L.e/u,G=w.e/u,V=L.c,ee=w.c;if(!F||!G){if(!V||!ee)return V?(w.s=-E,w):new U(ee?L:NaN);if(!V[0]||!ee[0])return ee[0]?(w.s=-E,w):new U(V[0]?L:k==3?-0:0)}if(F=y(F),G=y(G),V=V.slice(),x=F-G){for((D=x<0)?(x=-x,C=V):(G=F,C=ee),C.reverse(),E=x;E--;C.push(0));C.reverse()}else for(P=(D=(x=V.length)<(E=ee.length))?x:E,x=E=0;E0)for(;E--;V[I++]=0);for(E=a-1;P>x;){if(V[--P]=0;){for(I=0,Ae=Lt[C]%dt,Se=Lt[C]/dt|0,L=F,D=C+L;D>C;)G=Ve[--L]%dt,V=Ve[L]/dt|0,x=Se*G+V*Ae,G=Ae*G+x%dt*dt+Be[D]+I,I=(G/it|0)+(x/dt|0)+Se*V,Be[D--]=G%it;Be[D]=I}return I?++P:Be.splice(0,1),de(w,Be,P)},B.negated=function(){var w=new U(this);return w.s=-w.s||null,w},B.plus=function(w,E){var I,P=this,C=P.s;if(w=new U(w,E),E=w.s,!C||!E)return new U(NaN);if(C!=E)return w.s=-E,P.minus(w);var D=P.e/u,L=w.e/u,x=P.c,F=w.c;if(!D||!L){if(!x||!F)return new U(C/0);if(!x[0]||!F[0])return F[0]?w:new U(x[0]?P:C*0)}if(D=y(D),L=y(L),x=x.slice(),C=D-L){for(C>0?(L=D,I=F):(C=-C,I=x),I.reverse();C--;I.push(0));I.reverse()}for(C=x.length,E=F.length,C-E<0&&(I=F,F=x,x=I,E=C),C=0;E;)C=(x[--E]=x[E]+F[E]+C)/a|0,x[E]=a===x[E]?0:x[E]%a;return C&&(x=[C].concat(x),++L),de(w,x,L)},B.precision=B.sd=function(w,E){var I,P,C,D=this;if(w!=null&&w!==!!w)return R(w,1,g),E==null?E=k:R(E,0,8),ae(new U(D),w,E);if(!(I=D.c))return null;if(C=I.length-1,P=C*u+1,C=I[C]){for(;C%10==0;C/=10,P--);for(C=I[0];C>=10;C/=10,P++);}return w&&D.e+1>P&&(P=D.e+1),P},B.shiftedBy=function(w){return R(w,-c,c),this.times("1e"+w)},B.squareRoot=B.sqrt=function(){var w,E,I,P,C,D=this,L=D.c,x=D.s,F=D.e,G=z+4,V=new U("0.5");if(x!==1||!L||!L[0])return new U(!x||x<0&&(!L||L[0])?NaN:L?D:1/0);if(x=Math.sqrt(+le(D)),x==0||x==1/0?(E=A(L),(E.length+F)%2==0&&(E+="0"),x=Math.sqrt(+E),F=y((F+1)/2)-(F<0||F%2),x==1/0?E="5e"+F:(E=x.toExponential(),E=E.slice(0,E.indexOf("e")+1)+F),I=new U(E)):I=new U(x+""),I.c[0]){for(F=I.e,x=F+G,x<3&&(x=0);;)if(C=I,I=V.times(C.plus(N(D,C,G,1))),A(C.c).slice(0,x)===(E=A(I.c)).slice(0,x))if(I.e0&&Be>0){for(D=Be%x||x,V=Se.substr(0,D);D0&&(V+=G+Se.slice(D)),Ae&&(V="-"+V)}P=ee?V+(I.decimalSeparator||"")+((F=+I.fractionGroupSize)?ee.replace(new RegExp("\\d{"+F+"}\\B","g"),"$&"+(I.fractionGroupSeparator||"")):ee):V}return(I.prefix||"")+P+(I.suffix||"")},B.toFraction=function(w){var E,I,P,C,D,L,x,F,G,V,ee,Ae,Se=this,Be=Se.c;if(w!=null&&(x=new U(w),!x.isInteger()&&(x.c||x.s!==1)||x.lt(X)))throw Error(s+"Argument "+(x.isInteger()?"out of range: ":"not an integer: ")+le(x));if(!Be)return new U(Se);for(E=new U(X),G=I=new U(X),P=F=new U(X),Ae=A(Be),D=E.e=Ae.length-Se.e-1,E.c[0]=f[(L=D%u)<0?u+L:L],w=!w||x.comparedTo(E)>0?D>0?E:G:x,L=ce,ce=1/0,x=new U(Ae),F.c[0]=0;V=N(x,E,0,1),C=I.plus(V.times(P)),C.comparedTo(w)!=1;)I=P,P=C,G=F.plus(V.times(C=G)),F=C,E=x.minus(V.times(C=E)),x=C;return C=N(w.minus(I),P,0,1),F=F.plus(C.times(G)),I=I.plus(C.times(P)),F.s=G.s=Se.s,D=D*2,ee=N(G,P,D,k).minus(Se).abs().comparedTo(N(F,I,D,k).minus(Se).abs())<1?[G,P]:[F,I],ce=L,ee},B.toNumber=function(){return+le(this)},B.toPrecision=function(w,E){return w!=null&&R(w,1,g),fe(this,w,E,2)},B.toString=function(w){var E,I=this,P=I.s,C=I.e;return C===null?P?(E="Infinity",P<0&&(E="-"+E)):E="NaN":(w==null?E=C<=Q||C>=K?M(A(I.c),C):b(A(I.c),C,"0"):w===10?(I=ae(new U(I),z+C+1,k),E=b(A(I.c),I.e,"0")):(R(w,2,se.length,"Base"),E=_(b(A(I.c),C,"0"),10,w,P,!0)),P<0&&I.c[0]&&(E="-"+E)),E},B.valueOf=B.toJSON=function(){return le(this)},B._isBigNumber=!0,S!=null&&U.set(S),U}function y(S){var N=S|0;return S>0||S===N?N:N-1}function A(S){for(var N,_,T=1,B=S.length,X=S[0]+"";TK^_?1:-1;for(k=(Q=B.length)<(K=X.length)?Q:K,z=0;zX[z]^_?1:-1;return Q==K?0:Q>K^_?1:-1}function R(S,N,_,T){if(S_||S!==i(S))throw Error(s+(T||"Argument")+(typeof S=="number"?S_?" out of range: ":" not an integer: ":" not a primitive number: ")+String(S))}function q(S){var N=S.c.length-1;return y(S.e/u)==N&&S.c[N]%2!=0}function M(S,N){return(S.length>1?S.charAt(0)+"."+S.slice(1):S)+(N<0?"e":"e+")+N}function b(S,N,_){var T,B;if(N<0){for(B=_+".";++N;B+=_);S=B+S}else if(T=S.length,++N>T){for(B=_,N-=T;--N;B+=_);S+=B}else N{"use strict";l();Object.defineProperty(pe,"__esModule",{value:!0});pe.ErrIsCompletedFieldIsMissingOnTransaction=pe.ErrGasLimitShouldBe0ForInnerTransaction=pe.ErrInvalidRelayedV2BuilderArguments=pe.ErrInvalidRelayedV1BuilderArguments=pe.ErrNotImplemented=pe.ErrContractInteraction=pe.ErrCodec=pe.ErrCannotParseTransactionOutcome=pe.ErrCannotParseContractResults=pe.ErrMissingFieldOnEnum=pe.ErrMissingFieldOnStruct=pe.ErrTypingSystem=pe.ErrMock=pe.ErrContractHasNoAddress=pe.ErrContract=pe.ErrExpectedTransactionEventsNotFound=pe.ErrExpectedTransactionStatusNotReached=pe.ErrTransactionWatcherTimeout=pe.ErrAsyncTimerAborted=pe.ErrAsyncTimerAlreadyRunning=pe.ErrInvalidFunctionName=pe.ErrSignatureCannotCreate=pe.ErrTransactionOptionsInvalid=pe.ErrTransactionVersionInvalid=pe.ErrNonceInvalid=pe.ErrNotEnoughGas=pe.ErrAddressEmpty=pe.ErrAddressBadHrp=pe.ErrAddressCannotCreate=pe.ErrUnexpectedCondition=pe.ErrInvariantFailed=pe.ErrBadType=pe.ErrUnsupportedOperation=pe.ErrInvalidArgument=pe.Err=void 0;var Pe=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};pe.Err=Pe;var om=class extends Pe{constructor(e,r){super(`Invalid argument: ${e}`,r)}};pe.ErrInvalidArgument=om;var am=class extends Pe{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};pe.ErrUnsupportedOperation=am;var um=class extends Pe{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};pe.ErrBadType=um;var cm=class extends Pe{constructor(e){super(`Invariant failed: [${e}]`)}};pe.ErrInvariantFailed=cm;var lm=class extends Pe{constructor(e){super(`Unexpected condition: [${e}]`)}};pe.ErrUnexpectedCondition=lm;var fm=class extends Pe{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};pe.ErrAddressCannotCreate=fm;var dm=class extends Pe{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};pe.ErrAddressBadHrp=dm;var hm=class extends Pe{constructor(){super("Address is empty")}};pe.ErrAddressEmpty=hm;var pm=class extends Pe{constructor(e){super(`Not enough gas provided: ${e}`)}};pe.ErrNotEnoughGas=pm;var gm=class extends Pe{constructor(e){super(`Invalid nonce: ${e}`)}};pe.ErrNonceInvalid=gm;var ym=class extends Pe{constructor(e){super(`Invalid transaction version: ${e}`)}};pe.ErrTransactionVersionInvalid=ym;var mm=class extends Pe{constructor(e){super(`Invalid transaction options: ${e}`)}};pe.ErrTransactionOptionsInvalid=mm;var wm=class extends Pe{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};pe.ErrSignatureCannotCreate=wm;var Em=class extends Pe{constructor(){super("Invalid function name")}};pe.ErrInvalidFunctionName=Em;var vm=class extends Pe{constructor(){super("Async timer already running")}};pe.ErrAsyncTimerAlreadyRunning=vm;var Am=class extends Pe{constructor(){super("Async timer aborted")}};pe.ErrAsyncTimerAborted=Am;var bm=class extends Pe{constructor(){super("TransactionWatcher has timed out")}};pe.ErrTransactionWatcherTimeout=bm;var Im=class extends Pe{constructor(){super("Expected transaction status not reached")}};pe.ErrExpectedTransactionStatusNotReached=Im;var _m=class extends Pe{constructor(){super("Expected transaction events not found")}};pe.ErrExpectedTransactionEventsNotFound=_m;var Sf=class extends Pe{constructor(e){super(e)}};pe.ErrContract=Sf;var Sm=class extends Sf{constructor(){super(` +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, { + get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] +}) : x3)(function(x3) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x3 + '" is not supported'); +}); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod2) => function __require2() { + return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; +}; +var __export = (target, all) => { + for (var name2 in all) + __defProp(target, name2, { get: all[name2], enumerable: true }); +}; +var __copyProps = (to, from3, except, desc) => { + if (from3 && typeof from3 === "object" || typeof from3 === "function") { + for (let key of __getOwnPropNames(from3)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default")); +var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, + mod2 +)); +var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); + +// node_modules/base64-js/index.js +var require_base64_js = __commonJS({ + "node_modules/base64-js/index.js"(exports2) { + "use strict"; + init_shim(); + exports2.byteLength = byteLength; + exports2.toByteArray = toByteArray; + exports2.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i2 = 0, len = code2.length; i2 < len; ++i2) { + lookup[i2] = code2[i2]; + revLookup[code2.charCodeAt(i2)] = i2; + } + var i2; + var len; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) + validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i3; + for (i3 = 0; i3 < len2; i3 += 4) { + tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i3 = start; i3 < end; i3 += 3) { + tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) { + parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); + } + } +}); + +// node_modules/ieee754/index.js +var require_ieee754 = __commonJS({ + "node_modules/ieee754/index.js"(exports2) { + init_shim(); + exports2.read = function(buffer, offset, isLE, mLen, nBytes) { + var e2, m3; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i2 = isLE ? nBytes - 1 : 0; + var d3 = isLE ? -1 : 1; + var s2 = buffer[offset + i2]; + i2 += d3; + e2 = s2 & (1 << -nBits) - 1; + s2 >>= -nBits; + nBits += eLen; + for (; nBits > 0; e2 = e2 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { + } + m3 = e2 & (1 << -nBits) - 1; + e2 >>= -nBits; + nBits += mLen; + for (; nBits > 0; m3 = m3 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { + } + if (e2 === 0) { + e2 = 1 - eBias; + } else if (e2 === eMax) { + return m3 ? NaN : (s2 ? -1 : 1) * Infinity; + } else { + m3 = m3 + Math.pow(2, mLen); + e2 = e2 - eBias; + } + return (s2 ? -1 : 1) * m3 * Math.pow(2, e2 - mLen); + }; + exports2.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e2, m3, c4; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i2 = isLE ? 0 : nBytes - 1; + var d3 = isLE ? 1 : -1; + var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + if (isNaN(value) || value === Infinity) { + m3 = isNaN(value) ? 1 : 0; + e2 = eMax; + } else { + e2 = Math.floor(Math.log(value) / Math.LN2); + if (value * (c4 = Math.pow(2, -e2)) < 1) { + e2--; + c4 *= 2; + } + if (e2 + eBias >= 1) { + value += rt / c4; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c4 >= 2) { + e2++; + c4 /= 2; + } + if (e2 + eBias >= eMax) { + m3 = 0; + e2 = eMax; + } else if (e2 + eBias >= 1) { + m3 = (value * c4 - 1) * Math.pow(2, mLen); + e2 = e2 + eBias; + } else { + m3 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e2 = 0; + } + } + for (; mLen >= 8; buffer[offset + i2] = m3 & 255, i2 += d3, m3 /= 256, mLen -= 8) { + } + e2 = e2 << mLen | m3; + eLen += mLen; + for (; eLen > 0; buffer[offset + i2] = e2 & 255, i2 += d3, e2 /= 256, eLen -= 8) { + } + buffer[offset + i2 - d3] |= s2 * 128; + }; + } +}); + +// node_modules/node-stdlib-browser/node_modules/buffer/index.js +var require_buffer = __commonJS({ + "node_modules/node-stdlib-browser/node_modules/buffer/index.js"(exports2) { + "use strict"; + init_shim(); + var base642 = require_base64_js(); + var ieee754 = require_ieee754(); + var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports2.Buffer = Buffer2; + exports2.SlowBuffer = SlowBuffer; + exports2.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports2.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { + try { + var arr = new Uint8Array(1); + var proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e2) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.byteOffset; + } + }); + function createBuffer(length2) { + if (length2 > K_MAX_LENGTH) { + throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); + } + var buf = new Uint8Array(length2); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe2(arg); + } + return from3(arg, encodingOrOffset, length2); + } + Buffer2.poolSize = 8192; + function from3(value, encodingOrOffset, length2) { + if (typeof value === "string") { + return fromString3(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer2.from(valueOf, encodingOrOffset, length2); + } + var b4 = fromObject(value); + if (b4) + return b4; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer2.from( + value[Symbol.toPrimitive]("string"), + encodingOrOffset, + length2 + ); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + Buffer2.from = function(value, encodingOrOffset, length2) { + return from3(value, encodingOrOffset, length2); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe2(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe2(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe2(size); + }; + function fromString3(string2, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + var length2 = byteLength(string2, encoding) | 0; + var buf = createBuffer(length2); + var actual = buf.write(string2, encoding); + if (actual !== length2) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + var length2 = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length2); + for (var i2 = 0; i2 < length2; i2 += 1) { + buf[i2] = array[i2] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array, byteOffset, length2) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length2 || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + var buf; + if (byteOffset === void 0 && length2 === void 0) { + buf = new Uint8Array(array); + } else if (length2 === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length2); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length2) { + if (length2 >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length2 | 0; + } + function SlowBuffer(length2) { + if (+length2 != length2) { + length2 = 0; + } + return Buffer2.alloc(+length2); + } + Buffer2.isBuffer = function isBuffer(b4) { + return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; + }; + Buffer2.compare = function compare3(a3, b4) { + if (isInstance(a3, Uint8Array)) + a3 = Buffer2.from(a3, a3.offset, a3.byteLength); + if (isInstance(b4, Uint8Array)) + b4 = Buffer2.from(b4, b4.offset, b4.byteLength); + if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a3 === b4) + return 0; + var x3 = a3.length; + var y4 = b4.length; + for (var i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { + if (a3[i2] !== b4[i2]) { + x3 = a3[i2]; + y4 = b4[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding) { + switch (String(encoding).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 true; + default: + return false; + } + }; + Buffer2.concat = function concat2(list, length2) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + var i2; + if (length2 === void 0) { + length2 = 0; + for (i2 = 0; i2 < list.length; ++i2) { + length2 += list[i2].length; + } + } + var buffer = Buffer2.allocUnsafe(length2); + var pos = 0; + for (i2 = 0; i2 < list.length; ++i2) { + var buf = list[i2]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer2.from(buf).copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer; + }; + function byteLength(string2, encoding) { + if (Buffer2.isBuffer(string2)) { + return string2.length; + } + if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { + return string2.byteLength; + } + if (typeof string2 !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 + ); + } + var len = string2.length; + var mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) + return 0; + var loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string2).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string2).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string2).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength; + function slowToString(encoding, start, end) { + var loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) + encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b4, n3, m3) { + var i2 = b4[n3]; + b4[n3] = b4[m3]; + b4[m3] = i2; + } + Buffer2.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (var i2 = 0; i2 < len; i2 += 2) { + swap(this, i2, i2 + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (var i2 = 0; i2 < len; i2 += 4) { + swap(this, i2, i2 + 3); + swap(this, i2 + 1, i2 + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (var i2 = 0; i2 < len; i2 += 8) { + swap(this, i2, i2 + 7); + swap(this, i2 + 1, i2 + 6); + swap(this, i2 + 2, i2 + 5); + swap(this, i2 + 3, i2 + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString3() { + var length2 = this.length; + if (length2 === 0) + return ""; + if (arguments.length === 0) + return utf8Slice(this, 0, length2); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals4(b4) { + if (!Buffer2.isBuffer(b4)) + throw new TypeError("Argument must be a Buffer"); + if (this === b4) + return true; + return Buffer2.compare(this, b4) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + var str = ""; + var max = exports2.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) + str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) + return 0; + var x3 = thisEnd - thisStart; + var y4 = end - start; + var len = Math.min(x3, y4); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + for (var i2 = 0; i2 < len; ++i2) { + if (thisCopy[i2] !== targetCopy[i2]) { + x3 = thisCopy[i2]; + y4 = targetCopy[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + if (buffer.length === 0) + return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer.length - 1; + } + if (byteOffset < 0) + byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) + return -1; + else + byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) + byteOffset = 0; + else + return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read2(buf, i3) { + if (indexSize === 1) { + return buf[i3]; + } else { + return buf.readUInt16BE(i3 * indexSize); + } + } + var i2; + if (dir) { + var foundIndex = -1; + for (i2 = byteOffset; i2 < arrLength; i2++) { + if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { + if (foundIndex === -1) + foundIndex = i2; + if (i2 - foundIndex + 1 === valLength) + return foundIndex * indexSize; + } else { + if (foundIndex !== -1) + i2 -= i2 - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength; + for (i2 = byteOffset; i2 >= 0; i2--) { + var found = true; + for (var j2 = 0; j2 < valLength; j2++) { + if (read2(arr, i2 + j2) !== read2(val, j2)) { + found = false; + break; + } + } + if (found) + return i2; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string2, offset, length2) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length2) { + length2 = remaining; + } else { + length2 = Number(length2); + if (length2 > remaining) { + length2 = remaining; + } + } + var strLen = string2.length; + if (length2 > strLen / 2) { + length2 = strLen / 2; + } + for (var i2 = 0; i2 < length2; ++i2) { + var parsed = parseInt(string2.substr(i2 * 2, 2), 16); + if (numberIsNaN(parsed)) + return i2; + buf[offset + i2] = parsed; + } + return i2; + } + function utf8Write(buf, string2, offset, length2) { + return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); + } + function asciiWrite(buf, string2, offset, length2) { + return blitBuffer(asciiToBytes(string2), buf, offset, length2); + } + function base64Write(buf, string2, offset, length2) { + return blitBuffer(base64ToBytes(string2), buf, offset, length2); + } + function ucs2Write(buf, string2, offset, length2) { + return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); + } + Buffer2.prototype.write = function write(string2, offset, length2, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length2 = this.length; + offset = 0; + } else if (length2 === void 0 && typeof offset === "string") { + encoding = offset; + length2 = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length2)) { + length2 = length2 >>> 0; + if (encoding === void 0) + encoding = "utf8"; + } else { + encoding = length2; + length2 = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + var remaining = this.length - offset; + if (length2 === void 0 || length2 > remaining) + length2 = remaining; + if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) + encoding = "utf8"; + var loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string2, offset, length2); + case "utf8": + case "utf-8": + return utf8Write(this, string2, offset, length2); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string2, offset, length2); + case "base64": + return base64Write(this, string2, offset, length2); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string2, offset, length2); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base642.fromByteArray(buf); + } else { + return base642.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i2 = start; + while (i2 < end) { + var firstByte = buf[i2]; + var codePoint = null; + var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i2 + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i2 + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + fourthByte = buf[i2 + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i2 += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + var res = ""; + var i2 = 0; + while (i2 < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); + for (var i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); + for (var i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2]); + } + return ret; + } + function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) + start = 0; + if (!end || end < 0 || end > len) + end = len; + var out = ""; + for (var i2 = start; i2 < end; ++i2) { + out += hexSliceLookupTable[buf[i2]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ""; + for (var i2 = 0; i2 < bytes.length - 1; i2 += 2) { + res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) + start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) + end = 0; + } else if (end > len) { + end = len; + } + if (end < start) + end = start; + var newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset, ext, length2) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError("offset is not uint"); + if (offset + ext > length2) + throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + var val = this[offset]; + var mul = 1; + var i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength2, this.length); + } + var val = this[offset + --byteLength2]; + var mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset + --byteLength2] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + var val = this[offset]; + var mul = 1; + var i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + var i2 = byteLength2; + var mul = 1; + var val = this[offset + --i2]; + while (i2 > 0 && (mul *= 256)) { + val += this[offset + --i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) + return this[offset]; + return (255 - this[offset] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer2.isBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + var mul = 1; + var i2 = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + var i2 = byteLength2 - 1; + var mul = 1; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + var i2 = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + var i2 = byteLength2 - 1; + var mul = 1; + var sub = 0; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 127, -128); + if (value < 0) + value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + if (value < 0) + value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + if (offset < 0) + throw new RangeError("Index out of range"); + } + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + Buffer2.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) + throw new TypeError("argument should be a Buffer"); + if (!start) + start = 0; + if (!end && end !== 0) + end = this.length; + if (targetStart >= target.length) + targetStart = target.length; + if (!targetStart) + targetStart = 0; + if (end > 0 && end < start) + end = start; + if (end === start) + return 0; + if (target.length === 0 || this.length === 0) + return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) + throw new RangeError("Index out of range"); + if (end < 0) + throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) + end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + var len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + var code2 = val.charCodeAt(0); + if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { + val = code2; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) + val = 0; + var i2; + if (typeof val === "number") { + for (i2 = start; i2 < end; ++i2) { + this[i2] = val; + } + } else { + var bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); + var len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i2 = 0; i2 < end - start; ++i2) { + this[i2 + start] = bytes[i2 % len]; + } + } + return this; + }; + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) + return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + function utf8ToBytes(string2, units) { + units = units || Infinity; + var codePoint; + var length2 = string2.length; + var leadSurrogate = null; + var bytes = []; + for (var i2 = 0; i2 < length2; ++i2) { + codePoint = string2.charCodeAt(i2); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } else if (i2 + 1 === length2) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) + break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) + break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) + break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) + break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str) { + var byteArray = []; + for (var i2 = 0; i2 < str.length; ++i2) { + byteArray.push(str.charCodeAt(i2) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + var c4, hi, lo; + var byteArray = []; + for (var i2 = 0; i2 < str.length; ++i2) { + if ((units -= 2) < 0) + break; + c4 = str.charCodeAt(i2); + hi = c4 >> 8; + lo = c4 % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base642.toByteArray(base64clean(str)); + } + function blitBuffer(src2, dst, offset, length2) { + for (var i2 = 0; i2 < length2; ++i2) { + if (i2 + offset >= dst.length || i2 >= src2.length) + break; + dst[i2 + offset] = src2[i2]; + } + return i2; + } + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + var hexSliceLookupTable = function() { + var alphabet2 = "0123456789abcdef"; + var table = new Array(256); + for (var i2 = 0; i2 < 16; ++i2) { + var i16 = i2 * 16; + for (var j2 = 0; j2 < 16; ++j2) { + table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; + } + } + return table; + }(); + } +}); + +// node_modules/process/browser.js +var require_browser = __commonJS({ + "node_modules/process/browser.js"(exports2, module2) { + init_shim(); + var process2 = module2.exports = {}; + var cachedSetTimeout; + var cachedClearTimeout; + function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); + } + function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + if (typeof setTimeout === "function") { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e2) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === "function") { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e2) { + cachedClearTimeout = defaultClearTimeout; + } + })(); + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); + } + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + return cachedSetTimeout(fun, 0); + } catch (e2) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e3) { + return cachedSetTimeout.call(this, fun, 0); + } + } + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); + } + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + return cachedClearTimeout(marker); + } catch (e2) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e3) { + return cachedClearTimeout.call(this, marker); + } + } + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + process2.nextTick = function(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i2 = 1; i2 < arguments.length; i2++) { + args[i2 - 1] = arguments[i2]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function() { + this.fun.apply(null, this.array); + }; + process2.title = "browser"; + process2.browser = true; + process2.env = {}; + process2.argv = []; + process2.version = ""; + process2.versions = {}; + function noop() { + } + process2.on = noop; + process2.addListener = noop; + process2.once = noop; + process2.off = noop; + process2.removeListener = noop; + process2.removeAllListeners = noop; + process2.emit = noop; + process2.prependListener = noop; + process2.prependOnceListener = noop; + process2.listeners = function(name2) { + return []; + }; + process2.binding = function(name2) { + throw new Error("process.binding is not supported"); + }; + process2.cwd = function() { + return "/"; + }; + process2.chdir = function(dir) { + throw new Error("process.chdir is not supported"); + }; + process2.umask = function() { + return 0; + }; + } +}); + +// node_modules/node-stdlib-browser/helpers/esbuild/shim.js +var import_buffer, import_process, _globalThis, global; +var init_shim = __esm({ + "node_modules/node-stdlib-browser/helpers/esbuild/shim.js"() { + import_buffer = __toESM(require_buffer()); + import_process = __toESM(require_browser()); + _globalThis = function(Object2) { + function get2() { + var _global2 = this || self; + delete Object2.prototype.__magic__; + return _global2; + } + if (typeof globalThis === "object") { + return globalThis; + } + if (this) { + return get2(); + } else { + Object2.defineProperty(Object2.prototype, "__magic__", { + configurable: true, + get: get2 + }); + var _global = __magic__; + return _global; + } + }(Object); + global = _globalThis; + } +}); + +// node_modules/bignumber.js/bignumber.js +var require_bignumber = __commonJS({ + "node_modules/bignumber.js/bignumber.js"(exports2, module2) { + init_shim(); + (function(globalObject) { + "use strict"; + var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; + function clone2(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber3(v2, b4) { + var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber3)) + return new BigNumber3(v2, b4); + if (b4 == null) { + if (v2 && v2._isBigNumber === true) { + x3.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v2.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v2.e; + x3.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric2.test(str = String(v2))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i2 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i2; + e2 += +str.slice(i2 + 1); + str = str.substring(0, i2); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + if (b4 == 10 && alphabetHasNormalDecimalDigits) { + x3 = new BigNumber3(v2); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric(x3, str, isNum, b4); + x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits2 + v2); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet2 = ALPHABET.slice(0, b4); + e2 = i2 = 0; + for (len = str.length; i2 < len; i2++) { + if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { + if (c4 == ".") { + if (i2 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i2 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v2), isNum, b4); + } + } + isNum = false; + str = convertBase(str, b4, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i2 = 0; str.charCodeAt(i2) === 48; i2++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i2, ++len)) { + len -= i2; + if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { + throw Error(tooManyDigits2 + x3.s * v2); + } + if ((e2 = e2 - i2 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i2 = (e2 + 1) % LOG_BASE2; + if (e2 < 0) + i2 += LOG_BASE2; + if (i2 < len) { + if (i2) + x3.c.push(+str.slice(0, i2)); + for (len -= LOG_BASE2; i2 < len; ) { + x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); + } + i2 = LOG_BASE2 - (str = str.slice(i2)).length; + } else { + i2 -= len; + } + for (; i2--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber3.clone = clone2; + BigNumber3.ROUND_UP = 0; + BigNumber3.ROUND_DOWN = 1; + BigNumber3.ROUND_CEIL = 2; + BigNumber3.ROUND_FLOOR = 3; + BigNumber3.ROUND_HALF_UP = 4; + BigNumber3.ROUND_HALF_DOWN = 5; + BigNumber3.ROUND_HALF_EVEN = 6; + BigNumber3.ROUND_HALF_CEIL = 7; + BigNumber3.ROUND_HALF_FLOOR = 8; + BigNumber3.EUCLID = 9; + BigNumber3.config = BigNumber3.set = function(obj) { + var p3, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 8, p3); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, 0, p3); + intCheck2(v2[1], 0, MAX2, p3); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p3 = "RANGE")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, -1, p3); + intCheck2(v2[1], 1, MAX2, p3); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p3 = "CRYPTO")) { + v2 = obj[p3]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError2 + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError2 + p3 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 9, p3); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p3 = "FORMAT")) { + v2 = obj[p3]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError2 + p3 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p3 = "ALPHABET")) { + v2 = obj[p3]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; + ALPHABET = v2; + } else { + throw Error(bignumberError2 + p3 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError2 + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber3.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber3.DEBUG) + return true; + var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c4) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { + if (c4[0] === 0) { + if (e2 === 0 && c4.length === 1) + return true; + break out; + } + i2 = (e2 + 1) % LOG_BASE2; + if (i2 < 1) + i2 += LOG_BASE2; + if (String(c4[0]).length == i2) { + for (i2 = 0; i2 < c4.length; i2++) { + n3 = c4[i2]; + if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError2 + "Invalid BigNumber: " + v2); + }; + BigNumber3.maximum = BigNumber3.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber3.minimum = BigNumber3.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber3.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor2(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck2(dp, 0, MAX2); + k4 = mathceil2(dp / LOG_BASE2); + if (CRYPTO) { + if (crypto.getRandomValues) { + a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); + for (; i2 < k4; ) { + v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); + if (v2 >= 9e15) { + b4 = crypto.getRandomValues(new Uint32Array(2)); + a3[i2] = b4[0]; + a3[i2 + 1] = b4[1]; + } else { + c4.push(v2 % 1e14); + i2 += 2; + } + } + i2 = k4 / 2; + } else if (crypto.randomBytes) { + a3 = crypto.randomBytes(k4 *= 7); + for (; i2 < k4; ) { + v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a3, i2); + } else { + c4.push(v2 % 1e14); + i2 += 7; + } + } + i2 = k4 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError2 + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i2 < k4; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c4[i2++] = v2 % 1e14; + } + } + k4 = c4[--i2]; + dp %= LOG_BASE2; + if (k4 && dp) { + v2 = POWS_TEN2[LOG_BASE2 - dp]; + c4[i2] = mathfloor2(k4 / v2) * v2; + } + for (; c4[i2] === 0; c4.pop(), i2--) + ; + if (i2 < 0) { + c4 = [e2 = 0]; + } else { + for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) + ; + for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) + ; + if (i2 < LOG_BASE2) + e2 -= LOG_BASE2 - i2; + } + rand.e = e2; + rand.c = c4; + return rand; + }; + }(); + BigNumber3.sum = function() { + var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); + for (; i2 < args.length; ) + sum = sum.plus(args[i2++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet2) { + var j2, arr = [0], arrL, i2 = 0, len = str.length; + for (; i2 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet2.indexOf(str.charAt(i2++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i2 >= 0) { + k4 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y4 = new BigNumber3(baseIn); + x3 = y4.pow(str.length - i2); + POW_PRECISION = k4; + y4.c = toBaseOut( + toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), + 10, + baseOut, + decimal + ); + y4.e = y4.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); + e2 = k4 = xc.length; + for (; xc[--k4] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet2.charAt(0); + if (i2 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign2; + x3 = div(x3, y4, dp, rm, baseOut); + xc = x3.c; + r = x3.r; + e2 = x3.e; + } + d3 = e2 + dp + 1; + i2 = xc[d3]; + k4 = baseOut / 2; + r = r || d3 < 0 || xc[d3 + 1] != null; + r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (d3 < 1 || !xc[0]) { + str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); + } else { + xc.length = d3; + if (r) { + for (--baseOut; ++xc[--d3] > baseOut; ) { + xc[d3] = 0; + if (!d3) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k4 = xc.length; !xc[--k4]; ) + ; + for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) + ; + str = toFixedPoint2(str, e2, alphabet2.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x3, k4, base3) { + var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; + for (x3 = x3.slice(); i2--; ) { + xlo = x3[i2] % SQRT_BASE2; + xhi = x3[i2] / SQRT_BASE2 | 0; + m3 = khi * xlo + xhi * klo; + temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; + carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; + x3[i2] = temp % base3; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare4(a3, b4, aL, bL) { + var i2, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i2 = cmp = 0; i2 < aL; i2++) { + if (a3[i2] != b4[i2]) { + cmp = a3[i2] > b4[i2] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a3, b4, aL, base3) { + var i2 = 0; + for (; aL--; ) { + a3[aL] -= i2; + i2 = a3[aL] < b4[aL] ? 1 : 0; + a3[aL] = i2 * base3 + a3[aL] - b4[aL]; + } + for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) + ; + } + return function(x3, y4, dp, rm, base3) { + var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber3( + // Return NaN if either NaN, or both Infinity or 0. + !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber3(s2); + qc = q2.c = []; + e2 = x3.e - y4.e; + s2 = dp + e2 + 1; + if (!base3) { + base3 = BASE2; + e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); + s2 = s2 / LOG_BASE2 | 0; + } + for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) + ; + if (yc[i2] > (xc[i2] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i2 = 0; + s2 += 2; + n3 = mathfloor2(base3 / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base3); + xc = multiply(xc, n3, base3); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base3 / 2) + yc0++; + do { + n3 = 0; + cmp = compare4(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base3 + (rem[1] || 0); + n3 = mathfloor2(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base3) + n3 = base3 - 1; + prod = multiply(yc, n3, base3); + prodL = prod.length; + remL = rem.length; + while (compare4(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base3); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base3); + remL = rem.length; + if (cmp == -1) { + while (compare4(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base3); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i2++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base3 == BASE2) { + for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) + ; + round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format(n3, i2, rm, id) { + var c0, e2, ne, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne = n3.e; + if (i2 == null) { + str = coeffToString2(n3.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); + } else { + n3 = round(new BigNumber3(n3), i2, rm); + e2 = n3.e; + str = coeffToString2(n3.c); + len = str.length; + if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { + for (; len < i2; str += "0", len++) + ; + str = toExponential2(str, e2); + } else { + i2 -= ne; + str = toFixedPoint2(str, e2, "0"); + if (e2 + 1 > len) { + if (--i2 > 0) + for (str += "."; i2--; str += "0") + ; + } else { + i2 += e2 - len; + if (i2 > 0) { + if (e2 + 1 == len) + str += "."; + for (; i2--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, n3) { + var k4, y4, i2 = 1, x3 = new BigNumber3(args[0]); + for (; i2 < args.length; i2++) { + y4 = new BigNumber3(args[i2]); + if (!y4.s || (k4 = compare3(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { + x3 = y4; + } + } + return x3; + } + function normalise(n3, c4, e2) { + var i2 = 1, j2 = c4.length; + for (; !c4[--j2]; c4.pop()) + ; + for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) + ; + if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e2 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e2; + n3.c = c4; + } + return n3; + } + parseNumeric = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b4) { + var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m3, p1, p22) { + base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; + return !b4 || b4 == base3 ? p1 : m3; + }); + if (b4) { + base3 = b4; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber3(s2, base3); + } + if (BigNumber3.DEBUG) { + throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm, r) { + var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; + if (xc) { + out: { + for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) + ; + i2 = sd - d3; + if (i2 < 0) { + i2 += LOG_BASE2; + j2 = sd; + n3 = xc[ni = 0]; + rd = mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); + } else { + ni = mathceil2((i2 + 1) / LOG_BASE2); + if (ni >= xc.length) { + if (r) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d3 = 1; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + 1; + } else { + break out; + } + } else { + n3 = k4 = xc[ni]; + for (d3 = 1; k4 >= 10; k4 /= 10, d3++) + ; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + d3; + rd = j2 < 0 ? 0 : mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); + } + } + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i2 == 0) { + xc.length = ni; + k4 = 1; + ni--; + } else { + xc.length = ni + 1; + k4 = pows10[LOG_BASE2 - i2]; + xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; + } + if (r) { + for (; ; ) { + if (ni == 0) { + for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) + ; + j2 = xc[0] += k4; + for (k4 = 1; j2 >= 10; j2 /= 10, k4++) + ; + if (i2 != k4) { + x3.e++; + if (xc[0] == BASE2) + xc[0] = 1; + } + break; + } else { + xc[ni] += k4; + if (xc[ni] != BASE2) + break; + xc[ni--] = 0; + k4 = 1; + } + } + } + for (i2 = xc.length; xc[--i2] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n3) { + var str, e2 = n3.e; + if (e2 === null) + return n3.toString(); + str = coeffToString2(n3.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber3(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c4, n3, v2, x3 = this; + if (dp != null) { + intCheck2(dp, 0, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), dp + x3.e + 1, rm); + } + if (!(c4 = x3.c)) + return null; + n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; + if (v2 = c4[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m3) { + var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; + n3 = new BigNumber3(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); + } + if (m3 != null) + m3 = new BigNumber3(m3); + nIsBig = n3.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { + y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd2(n3)) : +valueOf(n3))); + return m3 ? y4.mod(m3) : y4; + } + nIsNeg = n3.s < 0; + if (m3) { + if (m3.c ? !m3.c[0] : !m3.s) + return new BigNumber3(NaN); + isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); + if (isModExp) + x3 = x3.mod(m3); + } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { + k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; + if (x3.e > -1) + k4 = 1 / k4; + return new BigNumber3(nIsNeg ? 1 / k4 : k4); + } else if (POW_PRECISION) { + k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); + } + if (nIsBig) { + half = new BigNumber3(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd2(n3); + } else { + i2 = Math.abs(+valueOf(n3)); + nIsOdd = i2 % 2; + } + y4 = new BigNumber3(ONE); + for (; ; ) { + if (nIsOdd) { + y4 = y4.times(x3); + if (!y4.c) + break; + if (k4) { + if (y4.c.length > k4) + y4.c.length = k4; + } else if (isModExp) { + y4 = y4.mod(m3); + } + } + if (i2) { + i2 = mathfloor2(i2 / 2); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd2(n3); + } else { + i2 = +valueOf(n3); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } + } + x3 = x3.times(x3); + if (k4) { + if (x3.c && x3.c.length > k4) + x3.c.length = k4; + } else if (isModExp) { + x3 = x3.mod(m3); + } + } + if (isModExp) + return y4; + if (nIsNeg) + y4 = ONE.div(y4); + return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber3(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y4, b4) { + var i2, j2, t, xLTy, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.plus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (xLTy = a3 < 0) { + a3 = -a3; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); + for (b4 = a3; b4--; t.push(0)) + ; + t.reverse(); + } else { + j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; + for (a3 = b4 = 0; b4 < j2; b4++) { + if (xc[b4] != yc[b4]) { + xLTy = xc[b4] < yc[b4]; + break; + } + } + } + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y4.s = -y4.s; + } + b4 = (j2 = yc.length) - (i2 = xc.length); + if (b4 > 0) + for (; b4--; xc[i2++] = 0) + ; + b4 = BASE2 - 1; + for (; j2 > a3; ) { + if (xc[--j2] < yc[j2]) { + for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) + ; + --xc[i2]; + xc[j2] += BASE2; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y4.s = ROUNDING_MODE == 3 ? -1 : 1; + y4.c = [y4.e = 0]; + return y4; + } + return normalise(y4, xc, ye); + }; + P2.modulo = P2.mod = function(y4, b4) { + var q2, s2, x3 = this; + y4 = new BigNumber3(y4, b4); + if (!x3.c || !y4.s || y4.c && !y4.c[0]) { + return new BigNumber3(NaN); + } else if (!y4.c || x3.c && !x3.c[0]) { + return new BigNumber3(x3); + } + if (MODULO_MODE == 9) { + s2 = y4.s; + y4.s = 1; + q2 = div(x3, y4, 0, 3); + y4.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y4, 0, MODULO_MODE); + } + y4 = x3.minus(q2.times(y4)); + if (!y4.c[0] && MODULO_MODE == 1) + y4.s = x3.s; + return y4; + }; + P2.multipliedBy = P2.times = function(y4, b4) { + var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y4.c = y4.e = y4.s = null; + } else { + y4.s *= x3.s; + if (!xc || !yc) { + y4.c = y4.e = null; + } else { + y4.c = [0]; + y4.e = 0; + } + } + return y4; + } + e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); + y4.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i2 = xcL; + xcL = ycL; + ycL = i2; + } + for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) + ; + base3 = BASE2; + sqrtBase = SQRT_BASE2; + for (i2 = ycL; --i2 >= 0; ) { + c4 = 0; + ylo = yc[i2] % sqrtBase; + yhi = yc[i2] / sqrtBase | 0; + for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { + xlo = xc[--k4] % sqrtBase; + xhi = xc[k4] / sqrtBase | 0; + m3 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; + c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base3; + } + zc[j2] = c4; + } + if (c4) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y4, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber3(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y4, b4) { + var t, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.minus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber3(a3 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (a3 > 0) { + ye = xe; + t = yc; + } else { + a3 = -a3; + t = xc; + } + t.reverse(); + for (; a3--; t.push(0)) + ; + t.reverse(); + } + a3 = xc.length; + b4 = yc.length; + if (a3 - b4 < 0) { + t = yc; + yc = xc; + xc = t; + b4 = a3; + } + for (a3 = 0; b4; ) { + a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; + xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; + } + if (a3) { + xc = [a3].concat(xc); + ++ye; + } + return normalise(y4, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm) { + var c4, n3, v2, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck2(sd, 1, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), sd, rm); + } + if (!(c4 = x3.c)) + return null; + v2 = c4.length - 1; + n3 = v2 * LOG_BASE2 + 1; + if (v2 = c4[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x3.e + 1 > n3) + n3 = x3.e + 1; + return n3; + }; + P2.shiftedBy = function(k4) { + intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); + return this.times("1e" + k4); + }; + P2.squareRoot = P2.sqrt = function() { + var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); + if (s2 !== 1 || !c4 || !c4[0]) { + return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString2(c4); + if ((n3.length + e2) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e2; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; + } + r = new BigNumber3(n3); + } else { + r = new BigNumber3(s2 + ""); + } + if (r.c[0]) { + e2 = r.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t = r; + r = half.times(t.plus(div(x3, t, dp, 1))); + if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { + if (r.e < e2) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + if (t.times(t).eq(x3)) { + r = t; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m3 = !r.times(r).eq(x3); + } + break; + } + } + } + } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp++; + } + return format(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format2) { + var str, x3 = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError2 + "Argument not an object: " + format2); + } + str = x3.toFixed(dp, rm); + if (x3.c) { + var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) { + i2 = g1; + g1 = g22; + g22 = i2; + len -= i2; + } + if (g1 > 0 && len > 0) { + i2 = len % g1 || g1; + intPart = intDigits.substr(0, i2); + for (; i2 < len; i2 += g1) + intPart += groupSeparator + intDigits.substr(i2, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i2); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format2.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P2.toFraction = function(md) { + var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; + if (md != null) { + n3 = new BigNumber3(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber3(x3); + d3 = new BigNumber3(ONE); + n1 = d0 = new BigNumber3(ONE); + d1 = n0 = new BigNumber3(ONE); + s2 = coeffToString2(xc); + e2 = d3.e = s2.length - x3.e - 1; + d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; + md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber3(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d3, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d3 = n3.minus(q2.times(d22 = d3)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( + div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck2(sd, 1, MAX2); + return format(this, sd, rm, 2); + }; + P2.toString = function(b4) { + var str, n3 = this, s2 = n3.s, e2 = n3.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b4 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); + } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { + n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + if (configObject != null) + BigNumber3.set(configObject); + return BigNumber3; + } + function bitFloor2(n3) { + var i2 = n3 | 0; + return n3 > 0 || n3 === i2 ? i2 : i2 - 1; + } + function coeffToString2(a3) { + var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; + for (; i2 < j2; ) { + s2 = a3[i2++] + ""; + z3 = LOG_BASE2 - s2.length; + for (; z3--; s2 = "0" + s2) + ; + r += s2; + } + for (j2 = r.length; r.charCodeAt(--j2) === 48; ) + ; + return r.slice(0, j2 + 1 || 1); + } + function compare3(x3, y4) { + var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; + if (!i2 || !j2) + return null; + a3 = xc && !xc[0]; + b4 = yc && !yc[0]; + if (a3 || b4) + return a3 ? b4 ? 0 : -j2 : i2; + if (i2 != j2) + return i2; + a3 = i2 < 0; + b4 = k4 == l4; + if (!xc || !yc) + return b4 ? 0 : !xc ^ a3 ? 1 : -1; + if (!b4) + return k4 > l4 ^ a3 ? 1 : -1; + j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; + for (i2 = 0; i2 < j2; i2++) + if (xc[i2] != yc[i2]) + return xc[i2] > yc[i2] ^ a3 ? 1 : -1; + return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; + } + function intCheck2(n3, min, max, name2) { + if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { + throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } + } + function isOdd2(n3) { + var k4 = n3.c.length - 1; + return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; + } + function toExponential2(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + function toFixedPoint2(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + "."; ++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len; --e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; + } + BigNumber2 = clone2(); + BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; + if (typeof define == "function" && define.amd) { + define(function() { + return BigNumber2; + }); + } else if (typeof module2 != "undefined" && module2.exports) { + module2.exports = BigNumber2; + } else { + if (!globalObject) { + globalObject = typeof self != "undefined" && self ? self : window; + } + globalObject.BigNumber = BigNumber2; + } + })(exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/errors.js +var require_errors = __commonJS({ + "node_modules/@multiversx/sdk-core/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrParseTransactionOutcome = exports2.ErrInvalidInnerTransaction = exports2.ErrBadUsage = exports2.ErrInvalidTokenIdentifier = exports2.ErrIsCompletedFieldIsMissingOnTransaction = exports2.ErrGasLimitShouldBe0ForInnerTransaction = exports2.ErrInvalidRelayedV2BuilderArguments = exports2.ErrInvalidRelayedV1BuilderArguments = exports2.ErrNotImplemented = exports2.ErrContractInteraction = exports2.ErrCodec = exports2.ErrCannotParseTransactionOutcome = exports2.ErrCannotParseContractResults = exports2.ErrMissingFieldOnEnum = exports2.ErrMissingFieldOnStruct = exports2.ErrTypingSystem = exports2.ErrMock = exports2.ErrContractHasNoAddress = exports2.ErrContract = exports2.ErrExpectedTransactionEventsNotFound = exports2.ErrExpectedTransactionStatusNotReached = exports2.ErrTransactionWatcherTimeout = exports2.ErrAsyncTimerAborted = exports2.ErrAsyncTimerAlreadyRunning = exports2.ErrInvalidFunctionName = exports2.ErrSignatureCannotCreate = exports2.ErrTransactionOptionsInvalid = exports2.ErrTransactionVersionInvalid = exports2.ErrNonceInvalid = exports2.ErrNotEnoughGas = exports2.ErrAddressEmpty = exports2.ErrAddressBadHrp = exports2.ErrAddressCannotCreate = exports2.ErrUnexpectedCondition = exports2.ErrInvariantFailed = exports2.ErrBadType = exports2.ErrUnsupportedOperation = exports2.ErrInvalidArgument = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + /** + * Returns a pretty, friendly summary for the error or for the chain of errros (if appropriate). + */ + summary() { + let result = []; + result.push({ name: this.name, message: this.message }); + let inner = this.inner; + while (inner) { + result.push({ name: inner.name, message: inner.message }); + inner = inner.inner; + } + return result; + } + }; + exports2.Err = Err; + var ErrInvalidArgument = class extends Err { + constructor(message, inner) { + super(`Invalid argument: ${message}`, inner); + } + }; + exports2.ErrInvalidArgument = ErrInvalidArgument; + var ErrUnsupportedOperation = class extends Err { + constructor(operation, reason = "not specified") { + super(`Operation "${operation}" not supported. Reason: ${reason}`); + } + }; + exports2.ErrUnsupportedOperation = ErrUnsupportedOperation; + var ErrBadType = class extends Err { + constructor(name2, type, value) { + super(`Bad type of "${name2}": ${value}. Expected type: ${type}`); + } + }; + exports2.ErrBadType = ErrBadType; + var ErrInvariantFailed = class extends Err { + constructor(message) { + super(`Invariant failed: [${message}]`); + } + }; + exports2.ErrInvariantFailed = ErrInvariantFailed; + var ErrUnexpectedCondition = class extends Err { + constructor(message) { + super(`Unexpected condition: [${message}]`); + } + }; + exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; + var ErrAddressCannotCreate = class extends Err { + constructor(input, inner) { + let message = `Cannot create address from: ${input}`; + super(message, inner); + } + }; + exports2.ErrAddressCannotCreate = ErrAddressCannotCreate; + var ErrAddressBadHrp = class extends Err { + constructor(expected, got) { + super(`Wrong address HRP. Expected: ${expected}, got ${got}`); + } + }; + exports2.ErrAddressBadHrp = ErrAddressBadHrp; + var ErrAddressEmpty = class extends Err { + constructor() { + super(`Address is empty`); + } + }; + exports2.ErrAddressEmpty = ErrAddressEmpty; + var ErrNotEnoughGas = class extends Err { + constructor(value) { + super(`Not enough gas provided: ${value}`); + } + }; + exports2.ErrNotEnoughGas = ErrNotEnoughGas; + var ErrNonceInvalid = class extends Err { + constructor(value) { + super(`Invalid nonce: ${value}`); + } + }; + exports2.ErrNonceInvalid = ErrNonceInvalid; + var ErrTransactionVersionInvalid = class extends Err { + constructor(value) { + super(`Invalid transaction version: ${value}`); + } + }; + exports2.ErrTransactionVersionInvalid = ErrTransactionVersionInvalid; + var ErrTransactionOptionsInvalid = class extends Err { + constructor(value) { + super(`Invalid transaction options: ${value}`); + } + }; + exports2.ErrTransactionOptionsInvalid = ErrTransactionOptionsInvalid; + var ErrSignatureCannotCreate = class extends Err { + constructor(input, inner) { + let message = `Cannot create signature from: ${input}`; + super(message, inner); + } + }; + exports2.ErrSignatureCannotCreate = ErrSignatureCannotCreate; + var ErrInvalidFunctionName = class extends Err { + constructor() { + super(`Invalid function name`); + } + }; + exports2.ErrInvalidFunctionName = ErrInvalidFunctionName; + var ErrAsyncTimerAlreadyRunning = class extends Err { + constructor() { + super("Async timer already running"); + } + }; + exports2.ErrAsyncTimerAlreadyRunning = ErrAsyncTimerAlreadyRunning; + var ErrAsyncTimerAborted = class extends Err { + constructor() { + super("Async timer aborted"); + } + }; + exports2.ErrAsyncTimerAborted = ErrAsyncTimerAborted; + var ErrTransactionWatcherTimeout = class extends Err { + constructor() { + super(`TransactionWatcher has timed out`); + } + }; + exports2.ErrTransactionWatcherTimeout = ErrTransactionWatcherTimeout; + var ErrExpectedTransactionStatusNotReached = class extends Err { + constructor() { + super(`Expected transaction status not reached`); + } + }; + exports2.ErrExpectedTransactionStatusNotReached = ErrExpectedTransactionStatusNotReached; + var ErrExpectedTransactionEventsNotFound = class extends Err { + constructor() { + super(`Expected transaction events not found`); + } + }; + exports2.ErrExpectedTransactionEventsNotFound = ErrExpectedTransactionEventsNotFound; + var ErrContract = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrContract = ErrContract; + var ErrContractHasNoAddress = class extends ErrContract { + constructor() { + super(` The smart contract has no address set. Make sure you provide the address in the constructor, or call setAddress() appropriately. If you need to recompute the address of the contract, make use of SmartContract.computeAddress() (static method). -`)}};pe.ErrContractHasNoAddress=Sm;var Tm=class extends Pe{constructor(e){super(e)}};pe.ErrMock=Tm;var Cm=class extends Pe{constructor(e){super(e)}};pe.ErrTypingSystem=Cm;var xm=class extends Pe{constructor(e,r){super(`field ${e} does not exist on struct ${r}`)}};pe.ErrMissingFieldOnStruct=xm;var Nm=class extends Pe{constructor(e,r){super(`field ${e} does not exist on enum ${r}`)}};pe.ErrMissingFieldOnEnum=Nm;var Om=class extends Pe{constructor(e){super(`cannot parse contract results: ${e}`)}};pe.ErrCannotParseContractResults=Om;var Dm=class extends Pe{constructor(e,r){super(`cannot parse outcome of transaction ${e}: ${r}`)}};pe.ErrCannotParseTransactionOutcome=Dm;var Pm=class extends Pe{constructor(e){super(e)}};pe.ErrCodec=Pm;var Rm=class extends Pe{constructor(e){super(e)}};pe.ErrContractInteraction=Rm;var Bm=class extends Pe{constructor(){super("Method not yet implemented")}};pe.ErrNotImplemented=Bm;var Lm=class extends Pe{constructor(){super("invalid arguments for relayed v1 builder")}};pe.ErrInvalidRelayedV1BuilderArguments=Lm;var Fm=class extends Pe{constructor(){super("invalid arguments for relayed v2 builder")}};pe.ErrInvalidRelayedV2BuilderArguments=Fm;var Mm=class extends Pe{constructor(){super("gas limit must be 0 for the inner transaction for relayed v2")}};pe.ErrGasLimitShouldBe0ForInnerTransaction=Mm;var Um=class extends Pe{constructor(){super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`.")}};pe.ErrIsCompletedFieldIsMissingOnTransaction=Um});var Vm=v(Ei=>{"use strict";l();var g5=Ei&&Ei.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ei,"__esModule",{value:!0});Ei.TokenPayment=Ei.TokenTransfer=void 0;var ju=g5(Yt()),y5=Le(),$S="EGLD",KS=18;ju.default.set({ROUNDING_MODE:1});var Tf=class t{constructor(e){let r=new ju.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new y5.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0}static egldFromAmount(e){let r=new ju.default(e).shiftedBy(KS).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:$S,nonce:0,amountAsBigInteger:e,numDecimals:KS})}static fungibleFromAmount(e,r,n){let i=new ju.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new ju.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amountAsBigInteger.toFixed(0)}valueOf(){return this.amountAsBigInteger}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.tokenIdentifier==$S}isFungible(){return this.nonce==0}};Ei.TokenTransfer=Tf;var qm=class extends Tf{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};Ei.TokenPayment=qm});var Ns=v(Xe=>{"use strict";l();Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ARGUMENTS_SEPARATOR=Xe.ESDT_TRANSFER_VALUE=Xe.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Xe.ESDTNFT_TRANSFER_FUNCTION_NAME=Xe.ESDT_TRANSFER_FUNCTION_NAME=Xe.ESDT_TRANSFER_GAS_LIMIT=Xe.TRANSACTION_VERSION_WITH_OPTIONS=Xe.TRANSACTION_VERSION_DEFAULT=Xe.TRANSACTION_OPTIONS_TX_GUARDED=Xe.TRANSACTION_OPTIONS_TX_HASH_SIGN=Xe.TRANSACTION_OPTIONS_DEFAULT=Xe.TRANSACTION_MIN_GAS_PRICE=void 0;Xe.TRANSACTION_MIN_GAS_PRICE=1e9;Xe.TRANSACTION_OPTIONS_DEFAULT=0;Xe.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Xe.TRANSACTION_OPTIONS_TX_GUARDED=2;Xe.TRANSACTION_VERSION_DEFAULT=1;Xe.TRANSACTION_VERSION_WITH_OPTIONS=2;Xe.ESDT_TRANSFER_GAS_LIMIT=5e5;Xe.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Xe.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Xe.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Xe.ESDT_TRANSFER_VALUE="0";Xe.ARGUMENTS_SEPARATOR="@"});var br=v(ot=>{"use strict";l();var m5=ot&&ot.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),w5=ot&&ot.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),E5=ot&&ot.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&m5(e,t,r);return w5(e,t),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.isEmpty=ot.guardEmpty=ot.guardNotEmpty=ot.guardLength=ot.guardSameLength=ot.guardValueIsSetWithMessage=ot.guardValueIsSet=ot.guardTrue=void 0;var Do=E5(Le());function v5(t,e){if(!t)throw new Do.ErrInvariantFailed(`[<${e}>] isn't true`)}ot.guardTrue=v5;function A5(t,e){YS(`${t} isn't set (null or undefined)`,e)}ot.guardValueIsSet=A5;function YS(t,e){if(e==null||e===void 0)throw new Do.ErrInvariantFailed(t)}ot.guardValueIsSetWithMessage=YS;function b5(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new Do.ErrInvariantFailed("arrays do not have the same length")}ot.guardSameLength=b5;function I5(t,e){let r=t.length||0;if(r!=e)throw new Do.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}ot.guardLength=I5;function _5(t,e){if(Hm(t))throw new Do.ErrInvariantFailed(`${e} is empty`)}ot.guardNotEmpty=_5;function S5(t,e){if(!Hm(t))throw new Do.ErrInvariantFailed(`${e} is not empty`)}ot.guardEmpty=S5;function Hm(t){return t.isEmpty?t.isEmpty():t.length===0}ot.isEmpty=Hm});var JS=v(Cf=>{"use strict";l();Object.defineProperty(Cf,"__esModule",{value:!0});Cf.getJavascriptPrototypesInHierarchy=void 0;function T5(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}Cf.getJavascriptPrototypesInHierarchy=T5});var Ct=v(Tt=>{"use strict";l();Object.defineProperty(Tt,"__esModule",{value:!0});Tt.NullType=Tt.TypePlaceholder=Tt.isTyped=Tt.PrimitiveValue=Tt.TypedValue=Tt.CustomType=Tt.PrimitiveType=Tt.TypeCardinality=Tt.Type=void 0;var km=JS(),XS=br(),vi=class t{constructor(e,r=[],n=Qu.fixed(1)){XS.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return km.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return XS.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return km.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};Tt.Type=vi;vi.ClassName="Type";var Qu=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};Tt.TypeCardinality=Qu;Qu.MaxCardinality=4096;var xf=class t extends vi{constructor(e){super(e)}getClassName(){return t.ClassName}};Tt.PrimitiveType=xf;xf.ClassName="PrimitiveType";var Nf=class t extends vi{getClassName(){return t.ClassName}};Tt.CustomType=Nf;Nf.ClassName="CustomType";var zu=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return km.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};Tt.TypedValue=zu;zu.ClassName="TypedValue";var Of=class t extends zu{constructor(e){super(e)}getClassName(){return t.ClassName}};Tt.PrimitiveValue=Of;Of.ClassName="PrimitiveValue";function C5(t){return t.belongsToTypesystem!==void 0}Tt.isTyped=C5;var Df=class t extends vi{constructor(){super("...")}getClassName(){return t.ClassName}};Tt.TypePlaceholder=Df;Df.ClassName="TypePlaceholder";var Pf=class t extends vi{constructor(){super("?")}getClassName(){return t.ClassName}};Tt.NullType=Pf;Pf.ClassName="NullType"});var ZS=v((Po,Ro)=>{l();(function(t){var e=typeof Po=="object"&&Po&&!Po.nodeType&&Po,r=typeof Ro=="object"&&Ro&&!Ro.nodeType&&Ro,n=typeof global=="object"&&global;(n.global===n||n.window===n||n.self===n)&&(t=n);var i,s=2147483647,o=36,a=1,u=26,c=38,f=700,d=72,g=128,m="-",y=/^xn--/,A=/[^\x20-\x7E]/,O=/[\x2E\u3002\uFF0E\uFF61]/g,R={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},q=o-a,M=Math.floor,b=String.fromCharCode,S;function N(J){throw new RangeError(R[J])}function _(J,oe){for(var re=J.length,se=[];re--;)se[re]=oe(J[re]);return se}function T(J,oe){var re=J.split("@"),se="";re.length>1&&(se=re[0]+"@",J=re[1]),J=J.replace(O,".");var U=J.split("."),fe=_(U,oe).join(".");return se+fe}function B(J){for(var oe=[],re=0,se=J.length,U,fe;re=55296&&U<=56319&&re65535&&(oe-=65536,re+=b(oe>>>10&1023|55296),oe=56320|oe&1023),re+=b(oe),re}).join("")}function z(J){return J-48<10?J-22:J-65<26?J-65:J-97<26?J-97:o}function k(J,oe){return J+22+75*(J<26)-((oe!=0)<<5)}function Q(J,oe,re){var se=0;for(J=re?M(J/f):J>>1,J+=M(J/oe);J>q*u>>1;se+=o)J=M(J/q);return M(se+(q+1)*J/(J+c))}function K(J){var oe=[],re=J.length,se,U=0,fe=g,ue=d,de,ae,le,w,E,I,P,C,D;for(de=J.lastIndexOf(m),de<0&&(de=0),ae=0;ae=128&&N("not-basic"),oe.push(J.charCodeAt(ae));for(le=de>0?de+1:0;le=re&&N("invalid-input"),P=z(J.charCodeAt(le++)),(P>=o||P>M((s-U)/E))&&N("overflow"),U+=P*E,C=I<=ue?a:I>=ue+u?u:I-ue,!(PM(s/D)&&N("overflow"),E*=D;se=oe.length+1,ue=Q(U-w,se,w==0),M(U/se)>s-fe&&N("overflow"),fe+=M(U/se),U%=se,oe.splice(U++,0,fe)}return X(oe)}function ye(J){var oe,re,se,U,fe,ue,de,ae,le,w,E,I=[],P,C,D,L;for(J=B(J),P=J.length,oe=g,re=0,fe=d,ue=0;ue=oe&&EM((s-re)/C)&&N("overflow"),re+=(de-oe)*C,oe=de,ue=0;ues&&N("overflow"),E==oe){for(ae=re,le=o;w=le<=fe?a:le>=fe+u?u:le-fe,!(ae{"use strict";l();var tT=ZS();function x5(t,e){this.__proto__=new Error(e),this.__proto__.name="BackslashError",this.offset=t}function Gm(t){return t>="0"&&t<="7"}function N5(t){return t>="0"&&t<="9"||t>="a"&&t<="f"||t>="A"&&t<="F"}function eT(t){return t=parseInt(t,16),tT.ucs2.encode([t])}function rT(t,e,r){var n=!1,i=[];function s(u){var c=t[u];if(!N5(c))throw new x5(u,"Unexpected token ILLEGAL");return c}for(;e{l();var oT=nT();cT.exports={validate:O5,parse:D5};function O5(t,e){var r;if(e=e||!1,typeof t!="string")r="Input must be a string";else try{Rf(t,0,e,!1)}catch(n){r=n.message}return r}function D5(t,e){if(typeof t!="string")throw new Error("Input must be a string");e=e||!1;var r=Rf(t,0,e,!0);return r.value}function aT(t,e){for(var r=t.length,n=e,i,s=e;s-1&&t[r]==="\\";)n++,r--;return n%2===0}function L5(t,e,r,n){for(var i=e,s=",",o=[],a=e;Os(t[a]);)a++;if(t[a]==="]")return{start:e,end:a,value:o};for(;s===",";){var u=Rf(t,i,r,n),c=aT(t,u.end);n&&o.push(u.value),i=c.end,s=c.value}return{start:e,end:i,value:o}}function F5(t,e){return t.substr(e,4)==="true"}function M5(t,e){return t.substr(e,5)==="false"}function U5(t,e){return t.substr(e,4)==="null"}var q5=new RegExp(/^\s$/);function Os(t){return q5.test(t)}var V5=new RegExp(/^\d$/);function iT(t){return V5.test(t)}function Kn(t,e,r){var n=10,i;t.length{"use strict";l();var H5=cn&&cn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),k5=cn&&cn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),G5=cn&&cn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H5(e,t,r);return k5(e,t),e};Object.defineProperty(cn,"__esModule",{value:!0});cn.TypeExpressionParser=void 0;var fT=G5(Le()),j5=Ct(),Q5=lT(),Qm=class{parse(e){let r=this.doParse(e),n=Object.keys(r);if(n.length!=1)throw new fT.ErrTypingSystem(`bad type expression: ${e}`);let i=n[0];return this.nodeToType(i,r[i])}doParse(e){let r=this.getJsonedString(e);try{return Q5.parse(r)}catch{throw new fT.ErrTypingSystem(`cannot parse type expression: ${e}. internal json: ${r}.`)}}getJsonedString(e){let r="";for(var n=0;n"?a!=">"?r+=": {} }":r+="}":o==","?u==">"||(a==">"?r+=",":r+=": {},"):r+=o}let i=/(:|\{|\}|,|\s)/,s=r.replace(/utf\-8\sstring/ig,"utf-8-string").split(i).filter(o=>o);return r=s.map(o=>i.test(o)?o:`"${o}"`).map(o=>o.replace(/utf\-8\-string/ig,"utf-8 string")).join(""),s.length==1?`{${r}: {}}`:`{${r}}`}nodeToType(e,r){e.charAt(e.length-1)==="1"&&(e=e.slice(0,-1));let n=Object.keys(r).map(i=>this.nodeToType(i,r[i]));return new j5.Type(e,n)}};cn.TypeExpressionParser=Qm});var Wm=v(Ai=>{"use strict";l();Object.defineProperty(Ai,"__esModule",{value:!0});Ai.EndpointParameterDefinition=Ai.EndpointModifiers=Ai.EndpointDefinition=void 0;var z5=Wu(),dT="?",W5="N / A",zm=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?dT:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>$u.fromJSON(s)),n=e.outputs.map(s=>$u.fromJSON(s)),i=new Bf(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};Ai.EndpointDefinition=zm;var Bf=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};Ai.EndpointModifiers=Bf;var $u=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new z5.TypeExpressionParser().parse(e.type);return new t(e.name||dT,e.description||W5,r)}};Ai.EndpointParameterDefinition=$u});var Bo=v(fr=>{"use strict";l();var $5=fr&&fr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),K5=fr&&fr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Y5=fr&&fr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$5(e,t,r);return K5(e,t),e};Object.defineProperty(fr,"__esModule",{value:!0});fr.Fields=fr.Field=fr.FieldDefinition=void 0;var $m=Y5(Le()),J5=Wu(),Km=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new J5.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};fr.FieldDefinition=Km;var Ym=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new $m.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new $m.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};fr.Field=Ym;var Jm=class{static checkTyping(e,r){if(e.length!=r.length)throw new $m.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";l();Object.defineProperty(bi,"__esModule",{value:!0});bi.EnumValue=bi.EnumVariantDefinition=bi.EnumType=void 0;var X5=Le(),Xm=br(),Lf=Bo(),pT=Ct(),hT=256,Ff=class t extends pT.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>Mf.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>Object.assign(Object.assign({},n),{discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return Xm.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return Xm.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};bi.EnumType=Ff;Ff.ClassName="EnumType";var Mf=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],Xm.guardTrue(rLf.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Lf.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};bi.EnumVariantDefinition=Mf;var Uf=class t extends pT.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();Lf.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=Lf.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new X5.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};bi.EnumValue=Uf;Uf.ClassName="EnumValue"});var yT=v(Lo=>{"use strict";l();Object.defineProperty(Lo,"__esModule",{value:!0});Lo.EventTopicDefinition=Lo.EventDefinition=void 0;var Z5=Wu(),gT="?",Zm=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?gT:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>qf.fromJSON(n));return new t(e.identifier,r)}};Lo.EventDefinition=Zm;var qf=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Z5.TypeExpressionParser().parse(e.type);return new t({name:e.name||gT,type:r,indexed:e.indexed})}};Lo.EventTopicDefinition=qf});var Mo=v(Fo=>{"use strict";l();Object.defineProperty(Fo,"__esModule",{value:!0});Fo.Struct=Fo.StructType=void 0;var eq=Le(),Vf=Bo(),mT=Ct(),Hf=class t extends mT.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>Vf.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Vf.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Fo.StructType=Hf;Hf.ClassName="StructType";var kf=class t extends mT.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();Vf.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new eq.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return Vf.Fields.equals(r,n)}};Fo.Struct=kf;kf.ClassName="Struct"});var tw=v((Coe,vT)=>{"use strict";l();var jf="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ew={};for(Yu=0;Yu>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function wT(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Uo(e)^n>>5}for(e=Uo(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=wT(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Uo(n)^o,i+=jf.charAt(o)}for(s=0;s<6;++s)n=Uo(n);for(n^=1,s=0;s<6;++s){var a=n>>(5-s)*5&31;i+=jf.charAt(a)}return i}function ET(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var a=wT(s);if(typeof a=="string")return a;for(var u=[],c=0;c=o.length)&&u.push(d)}return a!==1?"Invalid checksum for "+t:{prefix:s,words:u}}function rq(){var t=ET.apply(null,arguments);if(typeof t=="object")return t}function nq(t){var e=ET.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function Qf(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<=e)return"Excess padding";if(i<{"use strict";l();var uq=ln&&ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),cq=ln&&ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),AT=ln&&ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&uq(e,t,r);return cq(e,t),e};Object.defineProperty(ln,"__esModule",{value:!0});ln.Address=void 0;var qo=AT(tw()),Vo=AT(Le()),zf="erd",Wf=32,lq="0".repeat(16),rw=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(e instanceof h.Buffer)return t.fromBuffer(e);if(typeof e=="string")return t.fromString(e);throw new Vo.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=Wf)throw new Vo.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return h.Buffer.from(e,"hex").length==Wf}static fromHex(e){if(!t.isValidHex(e))throw new Vo.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t}static fromBech32(e){let r;try{r=qo.decode(e)}catch(s){throw new Vo.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=zf)throw new Vo.ErrAddressBadHrp(zf,n);let i=h.Buffer.from(qo.fromWords(r.words));if(i.length!=Wf)throw new Vo.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=qo.decodeUnsafe(e),n=r?.prefix,i=r?h.Buffer.from(qo.fromWords(r.words)):void 0;return!(n!==zf||i?.length!==Wf)}hex(){return this.isEmpty()?"":this.valueHex}bech32(){if(this.isEmpty())return"";let e=qo.toWords(this.pubkey());return qo.encode(zf,e)}pubkey(){return this.isEmpty()?h.Buffer.from([]):h.Buffer.from(this.valueHex,"hex")}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.bech32()}toJSON(){return{bech32:this.bech32(),pubkey:this.hex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.hex().startsWith(lq)}};ln.Address=rw});var ko=v(Ho=>{"use strict";l();Object.defineProperty(Ho,"__esModule",{value:!0});Ho.AddressValue=Ho.AddressType=void 0;var fq=pt(),bT=Ct(),Ju=class t extends bT.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};Ho.AddressType=Ju;Ju.ClassName="AddressType";var $f=class t extends bT.PrimitiveValue{constructor(e){super(new Ju),this.value=new fq.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};Ho.AddressValue=$f;$f.ClassName="AddressValue"});var Yf=v(Go=>{"use strict";l();Object.defineProperty(Go,"__esModule",{value:!0});Go.OptionalValue=Go.OptionalType=void 0;var dq=br(),Xu=Ct(),Zu=class t extends Xu.Type{constructor(e){super("Optional",[e],Xu.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Xu.NullType.ClassName);return r||n}};Go.OptionalType=Zu;Zu.ClassName="OptionalType";var Kf=class t extends Xu.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new Zu(new Xu.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return dq.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){var r;return((r=this.value)===null||r===void 0?void 0:r.equals(e.value))||!1}};Go.OptionalValue=Kf;Kf.ClassName="OptionalValue"});var tc=v(jo=>{"use strict";l();Object.defineProperty(jo,"__esModule",{value:!0});jo.BooleanValue=jo.BooleanType=void 0;var IT=Ct(),ec=class t extends IT.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};jo.BooleanType=ec;ec.ClassName="BooleanType";var Jf=class t extends IT.PrimitiveValue{constructor(e){super(new ec),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};jo.BooleanValue=Jf;Jf.ClassName="BooleanValue"});var Ii=v(Qo=>{"use strict";l();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.BytesValue=Qo.BytesType=void 0;var _T=Ct(),rc=class t extends _T.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Qo.BytesType=rc;rc.ClassName="BytesType";var Xf=class t extends _T.PrimitiveValue{constructor(e){super(new rc),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=h.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=h.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Qo.BytesValue=Xf;Xf.ClassName="BytesValue"});var TT=v(zo=>{"use strict";l();Object.defineProperty(zo,"__esModule",{value:!0});zo.CodeMetadataValue=zo.CodeMetadataType=void 0;var ST=Ct(),Zf=class extends ST.PrimitiveType{constructor(){super("CodeMetadata")}};zo.CodeMetadataType=Zf;var nw=class extends ST.PrimitiveValue{constructor(e){super(new Zf),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};zo.CodeMetadataValue=nw});var td=v(Wo=>{"use strict";l();Object.defineProperty(Wo,"__esModule",{value:!0});Wo.CompositeValue=Wo.CompositeType=void 0;var hq=br(),iw=Ct(),nc=class t extends iw.Type{constructor(...e){super("Composite",e,iw.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};Wo.CompositeType=nc;nc.ClassName="CompositeType";var ed=class t extends iw.TypedValue{constructor(e,r){super(e),hq.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new nc(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";l();Object.defineProperty(rd,"__esModule",{value:!0});rd.CollectionOfTypedValues=void 0;var sw=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";l();Object.defineProperty(fn,"__esModule",{value:!0});fn.List=fn.OptionValue=fn.ListType=fn.OptionType=void 0;var pq=br(),gq=ow(),Ps=Ct(),Ds=class t extends Ps.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Ps.NullType.ClassName);return r||n}};fn.OptionType=Ds;Ds.ClassName="OptionType";var ic=class t extends Ps.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};fn.ListType=ic;ic.ClassName="ListType";var nd=class t extends Ps.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new Ds(new Ps.NullType);return new t(e)}static newMissingTyped(e){return new t(new Ds(e))}static newProvided(e){let r=new Ds(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return pq.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){var r;return((r=this.value)===null||r===void 0?void 0:r.equals(e.value))||!1}};fn.OptionValue=nd;nd.ClassName="OptionValue";var id=class t extends Ps.TypedValue{constructor(e,r){super(e),this.backingCollection=new gq.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new Ps.TypePlaceholder,[]);let r=e[0].getType(),n=new ic(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};fn.List=id;id.ClassName="List"});var ad=v($o=>{"use strict";l();Object.defineProperty($o,"__esModule",{value:!0});$o.ArrayVec=$o.ArrayVecType=void 0;var CT=br(),yq=ow(),xT=Ct(),sd=class t extends xT.Type{constructor(e,r){super("Array",[r]),CT.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};$o.ArrayVecType=sd;sd.ClassName="ArrayVecType";var od=class t extends xT.TypedValue{constructor(e,r){super(e),CT.guardLength(r,e.length),this.backingCollection=new yq.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};$o.ArrayVec=od;od.ClassName="ArrayVec"});var ac=v(Ko=>{"use strict";l();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.H256Value=Ko.H256Type=void 0;var NT=Ct(),oc=class t extends NT.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};Ko.H256Type=oc;oc.ClassName="H256Type";var ud=class t extends NT.PrimitiveValue{constructor(e){super(new oc),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};Ko.H256Value=ud;ud.ClassName="H256Value"});var ld=v(Yo=>{"use strict";l();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.NothingValue=Yo.NothingType=void 0;var OT=Ct(),uc=class t extends OT.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};Yo.NothingType=uc;uc.ClassName="NothingType";var cd=class t extends OT.PrimitiveValue{constructor(){super(new uc)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};Yo.NothingValue=cd;cd.ClassName="NothingValue"});var Ec=v(Ce=>{"use strict";l();var mq=Ce&&Ce.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wq=Ce&&Ce.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Eq=Ce&&Ce.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mq(e,t,r);return wq(e,t),e},vq=Ce&&Ce.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ce,"__esModule",{value:!0});Ce.BigIntValue=Ce.BigUIntValue=Ce.I64Value=Ce.U64Value=Ce.I32Value=Ce.U32Value=Ce.I16Value=Ce.U16Value=Ce.I8Value=Ce.U8Value=Ce.NumericalValue=Ce.BigIntType=Ce.BigUIntType=Ce.I64Type=Ce.U64Type=Ce.I32Type=Ce.U32Type=Ce.I16Type=Ce.U16Type=Ce.I8Type=Ce.U8Type=Ce.NumericalType=void 0;var DT=Eq(Le()),PT=Ct(),Rs=vq(Yt()),dr=class t extends PT.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ce.NumericalType=dr;dr.ClassName="NumericalType";var cc=class t extends dr{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ce.U8Type=cc;cc.ClassName="U8Type";var lc=class t extends dr{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ce.I8Type=lc;lc.ClassName="I8Type";var fc=class t extends dr{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ce.U16Type=fc;fc.ClassName="U16Type";var dc=class t extends dr{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ce.I16Type=dc;dc.ClassName="I16Type";var hc=class t extends dr{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ce.U32Type=hc;hc.ClassName="U32Type";var pc=class t extends dr{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ce.I32Type=pc;pc.ClassName="I32Type";var gc=class t extends dr{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ce.U64Type=gc;gc.ClassName="U64Type";var yc=class t extends dr{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ce.I64Type=yc;yc.ClassName="I64Type";var mc=class t extends dr{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ce.BigUIntType=mc;mc.ClassName="BigUIntType";var wc=class t extends dr{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ce.BigIntType=wc;wc.ClassName="BigIntType";var hr=class t extends PT.PrimitiveValue{constructor(e,r){if(super(e),this.value=new Rs.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new DT.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new DT.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ce.NumericalValue=hr;hr.ClassName="NumericalValue";var fd=class t extends hr{constructor(e){super(new cc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.U8Value=fd;fd.ClassName="U8Value";var dd=class t extends hr{constructor(e){super(new lc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.I8Value=dd;dd.ClassName="I8Value";var hd=class t extends hr{constructor(e){super(new fc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.U16Value=hd;hd.ClassName="U16Value";var pd=class t extends hr{constructor(e){super(new dc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.I16Value=pd;pd.ClassName="I16Value";var gd=class t extends hr{constructor(e){super(new hc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.U32Value=gd;gd.ClassName="U32Value";var yd=class t extends hr{constructor(e){super(new pc,new Rs.default(e))}getClassName(){return t.ClassName}};Ce.I32Value=yd;yd.ClassName="I32Value";var md=class t extends hr{constructor(e){super(new gc,e)}getClassName(){return t.ClassName}};Ce.U64Value=md;md.ClassName="U64Value";var wd=class t extends hr{constructor(e){super(new yc,e)}getClassName(){return t.ClassName}};Ce.I64Value=wd;wd.ClassName="I64Value";var Ed=class t extends hr{constructor(e){super(new mc,e)}getClassName(){return t.ClassName}};Ce.BigUIntValue=Ed;Ed.ClassName="BigUIntValue";var vd=class t extends hr{constructor(e){super(new wc,e)}getClassName(){return t.ClassName}};Ce.BigIntValue=vd;vd.ClassName="BigIntValue"});var bd=v(Jo=>{"use strict";l();Object.defineProperty(Jo,"__esModule",{value:!0});Jo.StringValue=Jo.StringType=void 0;var RT=Ct(),vc=class t extends RT.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};Jo.StringType=vc;vc.ClassName="StringType";var Ad=class t extends RT.PrimitiveValue{constructor(e){super(new vc),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=h.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};Jo.StringValue=Ad;Ad.ClassName="StringValue"});var Zo=v(Xo=>{"use strict";l();Object.defineProperty(Xo,"__esModule",{value:!0});Xo.TokenIdentifierValue=Xo.TokenIdentifierType=void 0;var BT=Ct(),Aq="EGLD",Ac=class t extends BT.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};Xo.TokenIdentifierType=Ac;Ac.ClassName="TokenIdentifierType";var Id=class t extends BT.PrimitiveValue{constructor(e){super(new Ac),this.value=e}static egld(){return new t(Aq)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};Xo.TokenIdentifierValue=Id;Id.ClassName="TokenIdentifierValue"});var Sd=v(Cr=>{"use strict";l();var bq=Cr&&Cr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Iq=Cr&&Cr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_q=Cr&&Cr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&bq(e,t,r);return Iq(e,t),e};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.Tuple=Cr.TupleType=void 0;var Sq=_q(Le()),LT=Bo(),FT=Mo(),bc=class t extends FT.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new LT.FieldDefinition(MT(i),"anonymous tuple field",n))}};Cr.TupleType=bc;bc.ClassName="TupleType";function MT(t){return`field${t}`}var _d=class t extends FT.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Sq.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new bc(...r),i=e.map((s,o)=>new LT.Field(s,MT(o)));return new t(n,i)}};Cr.Tuple=_d;_d.ClassName="Tuple"});var xd=v(_i=>{"use strict";l();Object.defineProperty(_i,"__esModule",{value:!0});_i.VariadicValue=_i.CountedVariadicType=_i.VariadicType=void 0;var ea=Ct(),Bs=class t extends ea.Type{constructor(e,r=!1){super("Variadic",[e],ea.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};_i.VariadicType=Bs;Bs.ClassName="VariadicType";var Td=class extends ea.Type{constructor(e){super("Variadic",[e],ea.TypeCardinality.variable())}getClassName(){return Bs.ClassName}};_i.CountedVariadicType=Td;Td.ClassName="VariadicType";var Cd=class t extends ea.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Bs(new ea.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Bs(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";l();var Tq=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Cq=hn&&hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xq=hn&&hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Tq(e,t,r);return Cq(e,t),e};Object.defineProperty(hn,"__esModule",{value:!0});hn.TypeMapper=void 0;var UT=xq(Le()),Nq=ko(),aw=Yf(),Oq=tc(),Dq=Ii(),Pq=TT(),Nd=td(),uw=Ku(),Rq=Bo(),qT=sc(),dn=ad(),Bq=ac(),VT=ld(),xr=Ec(),Lq=bd(),HT=Mo(),kT=Zo(),Si=Sd(),Od=xd(),cw=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new qT.OptionType(r[0])],["List",(...r)=>new qT.ListType(r[0])],["VarArgs",(...r)=>new Od.VariadicType(r[0])],["MultiResultVec",(...r)=>new Od.VariadicType(r[0])],["variadic",(...r)=>new Od.VariadicType(r[0])],["counted-variadic",(...r)=>new Od.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new aw.OptionalType(r[0])],["optional",(...r)=>new aw.OptionalType(r[0])],["OptionalResult",(...r)=>new aw.OptionalType(r[0])],["multi",(...r)=>new Nd.CompositeType(...r)],["MultiArg",(...r)=>new Nd.CompositeType(...r)],["MultiResult",(...r)=>new Nd.CompositeType(...r)],["multi",(...r)=>new Nd.CompositeType(...r)],["tuple",(...r)=>new Si.TupleType(...r)],["tuple2",(...r)=>new Si.TupleType(...r)],["tuple3",(...r)=>new Si.TupleType(...r)],["tuple4",(...r)=>new Si.TupleType(...r)],["tuple5",(...r)=>new Si.TupleType(...r)],["tuple6",(...r)=>new Si.TupleType(...r)],["tuple7",(...r)=>new Si.TupleType(...r)],["tuple8",(...r)=>new Si.TupleType(...r)],["array2",(...r)=>new dn.ArrayVecType(2,r[0])],["array8",(...r)=>new dn.ArrayVecType(8,r[0])],["array16",(...r)=>new dn.ArrayVecType(16,r[0])],["array20",(...r)=>new dn.ArrayVecType(20,r[0])],["array32",(...r)=>new dn.ArrayVecType(32,r[0])],["array46",(...r)=>new dn.ArrayVecType(46,r[0])],["array48",(...r)=>new dn.ArrayVecType(48,r[0])],["array64",(...r)=>new dn.ArrayVecType(64,r[0])],["array128",(...r)=>new dn.ArrayVecType(128,r[0])],["array256",(...r)=>new dn.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new xr.U8Type],["u16",new xr.U16Type],["u32",new xr.U32Type],["u64",new xr.U64Type],["U64",new xr.U64Type],["BigUint",new xr.BigUIntType],["i8",new xr.I8Type],["i16",new xr.I16Type],["i32",new xr.I32Type],["i64",new xr.I64Type],["Bigint",new xr.BigIntType],["BigInt",new xr.BigIntType],["bool",new Oq.BooleanType],["bytes",new Dq.BytesType],["Address",new Nq.AddressType],["H256",new Bq.H256Type],["utf-8 string",new Lq.StringType],["TokenIdentifier",new kT.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new kT.TokenIdentifierType],["CodeMetadata",new Pq.CodeMetadataType],["nothing",new VT.NothingType],["AsyncCall",new VT.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new UT.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(uw.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(HT.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new HT.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new uw.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new uw.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new Rq.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new UT.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};hn.TypeMapper=cw});var WT=v(pn=>{"use strict";l();var Fq=pn&&pn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Mq=pn&&pn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Uq=pn&&pn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Fq(e,t,r);return Mq(e,t),e};Object.defineProperty(pn,"__esModule",{value:!0});pn.AbiRegistry=void 0;var GT=Uq(Le()),Ic=br(),_c=Wm(),jT=Ku(),fw=yT(),QT=Mo(),qq=lw(),Vq="?",dw=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||Vq,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],a=_c.EndpointDefinition.fromJSON(Object.assign({name:"constructor"},n)),u=i.map(m=>_c.EndpointDefinition.fromJSON(m)),c=[];for(let m in s){let y=s[m];if(y.type=="struct")c.push(QT.StructType.fromJSON({name:m,fields:y.fields}));else if(y.type=="enum"||y.type=="explicit-enum")c.push(jT.EnumType.fromJSON({name:m,variants:y.variants}));else throw new GT.ErrTypingSystem(`Cannot handle custom type: ${m}`)}let f=o.map(m=>fw.EventDefinition.fromJSON(m));return new t({name:r,constructorDefinition:a,endpoints:u,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return Ic.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(QT.StructType.ClassName));return Ic.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(jT.EnumType.ClassName));return Ic.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return Ic.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return Ic.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new qq.TypeMapper([]),r=[];for(let a of this.customTypes)this.mapCustomTypeDepthFirst(a,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new GT.ErrTypingSystem("Did not re-map all custom types");let n=zT(this.constructorDefinition,e),i=[];for(let a of this.endpoints)i.push(zT(a,e));let s=this.events.map(a=>Hq(a,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(a=>a.getName()==e.getName())>=0)return;for(let a of e.getNamesOfDependencies()){let u=r.find(c=>c.getName()==a);u&&this.mapCustomTypeDepthFirst(u,r,n,i)}let o=n.mapType(e);i.push(o)}};pn.AbiRegistry=dw;function zT(t,e){let r=t.input.map(i=>new _c.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new _c.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new _c.EndpointDefinition(t.name,r,n,t.modifiers)}function Hq(t,e){let r=t.inputs.map(n=>new fw.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new fw.EventDefinition(t.identifier,r)}});var KT=v(ta=>{"use strict";l();Object.defineProperty(ta,"__esModule",{value:!0});ta.createListOfTokenIdentifiers=ta.createListOfAddresses=void 0;var kq=ko(),$T=sc(),Gq=Zo();function jq(t){let e=t.map(n=>new kq.AddressValue(n));return $T.List.fromItems(e)}ta.createListOfAddresses=jq;function Qq(t){let e=t.map(n=>new Gq.TokenIdentifierValue(n));return $T.List.fromItems(e)}ta.createListOfTokenIdentifiers=Qq});var cC=v(Jt=>{"use strict";l();var zq=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Wq=Jt&&Jt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$q=Jt&&Jt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zq(e,t,r);return Wq(e,t),e};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.onPrimitiveTypeSelect=Jt.onPrimitiveValueSelect=Jt.onTypedValueSelect=Jt.onTypeSelect=void 0;var Pd=$q(Le()),YT=ko(),JT=tc(),XT=Ii(),ZT=Ku(),Dd=sc(),eC=ac(),tC=Ec(),rC=ld(),nC=Mo(),iC=Zo(),sC=Sd(),oC=Ct(),aC=ad(),uC=bd();function Kq(t,e){if(t.hasExactClass(Dd.OptionType.ClassName))return e.onOption();if(t.hasExactClass(Dd.ListType.ClassName))return e.onList();if(t.hasExactClass(aC.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(oC.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(nC.StructType.ClassName))return e.onStruct();if(t.hasExactClass(sC.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(ZT.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`type isn't known: ${t}`)}Jt.onTypeSelect=Kq;function Yq(t,e){if(t.hasClassOrSuperclass(oC.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(Dd.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(Dd.List.ClassName))return e.onList();if(t.hasExactClass(aC.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(nC.Struct.ClassName))return e.onStruct();if(t.hasExactClass(sC.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(ZT.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`value isn't typed: ${t}`)}Jt.onTypedValueSelect=Yq;function Jq(t,e){if(t.hasExactClass(JT.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(tC.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(YT.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(XT.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(uC.StringValue.ClassName))return e.onString();if(t.hasExactClass(eC.H256Value.ClassName))return e.onH256();if(t.hasExactClass(iC.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(rC.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Jt.onPrimitiveValueSelect=Jq;function Xq(t,e){if(t.hasExactClass(JT.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(tC.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(YT.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(XT.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(uC.StringType.ClassName))return e.onString();if(t.hasExactClass(eC.H256Type.ClassName))return e.onH256();if(t.hasExactClass(iC.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(rC.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new Pd.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Jt.onPrimitiveTypeSelect=Xq});var xt=v(He=>{"use strict";l();var Zq=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),at=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Zq(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});at(WT(),He);at(ko(),He);at(Yf(),He);at(tc(),He);at(Ii(),He);at(td(),He);at(Wm(),He);at(Ku(),He);at(KT(),He);at(Bo(),He);at(sc(),He);at(ad(),He);at(ac(),He);at(cC(),He);at(ld(),He);at(Ec(),He);at(bd(),He);at(Mo(),He);at(Zo(),He);at(Sd(),He);at(Wu(),He);at(lw(),He);at(Ct(),He);at(xd(),He)});var fC=v(gn=>{"use strict";l();var eV=gn&&gn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),tV=gn&&gn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),rV=gn&&gn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&eV(e,t,r);return tV(e,t),e};Object.defineProperty(gn,"__esModule",{value:!0});gn.OptionValueBinaryCodec=void 0;var lC=rV(Le()),Rd=xt(),hw=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[Rd.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new lC.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[Rd.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new Rd.OptionValue(r);if(e[0]!=1)throw new lC.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new Rd.OptionValue(r,n)}encodeNested(e){return e.isSet()?h.Buffer.concat([h.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):h.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?h.Buffer.concat([h.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):h.Buffer.from([])}};gn.OptionValueBinaryCodec=hw});var dC=v(Bd=>{"use strict";l();Object.defineProperty(Bd,"__esModule",{value:!0});Bd.AddressBinaryCodec=void 0;var nV=pt(),iV=xt(),pw=class{decodeNested(e){let r=e.slice(0,32),n=new nV.Address(r);return[new iV.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};Bd.AddressBinaryCodec=pw});var pC=v(yn=>{"use strict";l();var sV=yn&&yn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),oV=yn&&yn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),aV=yn&&yn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sV(e,t,r);return oV(e,t),e};Object.defineProperty(yn,"__esModule",{value:!0});yn.BooleanBinaryCodec=void 0;var uV=aV(Le()),hC=xt(),Sc=class t{decodeNested(e){let r=e.readUInt8(0);return[new hC.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new uV.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new hC.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?h.Buffer.from([t.TRUE]):h.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?h.Buffer.from([t.TRUE]):h.Buffer.from([])}};yn.BooleanBinaryCodec=Sc;Sc.TRUE=1;Sc.FALSE=0});var Fd=v(Ld=>{"use strict";l();Object.defineProperty(Ld,"__esModule",{value:!0});Ld.SizeOfU32=void 0;Ld.SizeOfU32=4});var Md=v(mn=>{"use strict";l();var cV=mn&&mn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(mn,"__esModule",{value:!0});mn.zeroPadStringIfOddLength=mn.isPaddedHex=mn.numberToPaddedHex=void 0;var lV=cV(Yt());function fV(t){let e=new lV.default(t).toString(16);return gC(e)}mn.numberToPaddedHex=fV;function dV(t){t=t||"";let e=h.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}mn.isPaddedHex=dV;function gC(t){return t=t||"",t.length%2==1?"0"+t:t}mn.zeroPadStringIfOddLength=gC});var Tc=v(Nt=>{"use strict";l();var hV=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.prependByteToBuffer=Nt.flipBufferBitsInPlace=Nt.getHexMagnitudeOfBigInt=Nt.bigIntToBuffer=Nt.bufferToBigInt=Nt.cloneBuffer=Nt.isMsbZero=Nt.isMsbOne=void 0;var gw=hV(Yt()),pV=Md();function yC(t,e=0){return t[e]>>7==1}Nt.isMsbOne=yC;function gV(t,e=0){return!yC(t,e)}Nt.isMsbZero=gV;function yV(t){let e=h.Buffer.alloc(t.length);return t.copy(e),e}Nt.cloneBuffer=yV;function mV(t){let e=t.toString("hex");return new gw.default(`0x${e}`,16)}Nt.bufferToBigInt=mV;function wV(t){let e=mC(t);return h.Buffer.from(e,"hex")}Nt.bigIntToBuffer=wV;function mC(t){return t=new gw.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new gw.default(-1))),pV.numberToPaddedHex(t)):""}Nt.getHexMagnitudeOfBigInt=mC;function EV(t){for(let e=0;e{"use strict";l();var AV=ra&&ra.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ra,"__esModule",{value:!0});ra.NumericalBinaryCodec=void 0;var Cc=AV(Yt()),yw=xt(),wC=Fd(),At=Tc(),mw=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=wC.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),a=i+n;return[o,a]}decodeTopLevel(e,r){let n=At.cloneBuffer(e);if(e.length==0)return new yw.NumericalValue(r,new Cc.default(0));if(!r.withSign||At.isMsbZero(n)){let c=At.bufferToBigInt(n);return new yw.NumericalValue(r,c)}At.flipBufferBitsInPlace(n);let u=At.bufferToBigInt(n).multipliedBy(new Cc.default(-1)).minus(new Cc.default(1));return new yw.NumericalValue(r,u)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=h.Buffer.alloc(wC.SizeOfU32);return n.writeUInt32BE(r.length),h.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return h.Buffer.alloc(r,0);if(!e.withSign){let o=At.bigIntToBuffer(e.value),a=h.Buffer.alloc(r-o.length,0);return h.Buffer.concat([a,o])}if(e.value.isPositive()){let o=At.bigIntToBuffer(e.value);At.isMsbOne(o)&&(o=At.prependByteToBuffer(o,0));let a=h.Buffer.alloc(r-o.length,0);return h.Buffer.concat([a,o])}let n=e.value.plus(new Cc.default(1)),i=At.bigIntToBuffer(n);At.flipBufferBitsInPlace(i),At.isMsbZero(i)&&(i=At.prependByteToBuffer(i,255));let s=h.Buffer.alloc(r-i.length,255);return h.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?h.Buffer.alloc(0):r?this.encodePrimitive(e):At.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=At.bigIntToBuffer(e.value);return At.isMsbOne(i)&&(i=At.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Cc.default(1)),n=At.bigIntToBuffer(r);return At.flipBufferBitsInPlace(n),At.isMsbZero(n)&&(n=At.prependByteToBuffer(n,255)),n}};ra.NumericalBinaryCodec=mw});var vC=v(Ud=>{"use strict";l();Object.defineProperty(Ud,"__esModule",{value:!0});Ud.H256BinaryCodec=void 0;var bV=ac(),ww=class{decodeNested(e){let r=e.slice(0,32);return[new bV.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Ud.H256BinaryCodec=ww});var Hd=v(Vd=>{"use strict";l();Object.defineProperty(Vd,"__esModule",{value:!0});Vd.BytesBinaryCodec=void 0;var AC=Ii(),qd=Fd(),Ew=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(qd.SizeOfU32,qd.SizeOfU32+r);return[new AC.BytesValue(n),qd.SizeOfU32+r]}decodeTopLevel(e){return new AC.BytesValue(e)}encodeNested(e){let r=h.Buffer.alloc(qd.SizeOfU32);return r.writeUInt32BE(e.getLength()),h.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Vd.BytesBinaryCodec=Ew});var IC=v(kd=>{"use strict";l();Object.defineProperty(kd,"__esModule",{value:!0});kd.TokenIdentifierCodec=void 0;var IV=Ii(),bC=Zo(),_V=Hd(),vw=class{constructor(){this.bytesCodec=new _V.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new bC.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new bC.TokenIdentifierValue(r.toString())}encodeNested(e){let r=IV.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return h.Buffer.from(e.valueOf())}};kd.TokenIdentifierCodec=vw});var SC=v(Gd=>{"use strict";l();Object.defineProperty(Gd,"__esModule",{value:!0});Gd.NothingCodec=void 0;var _C=xt(),Aw=class{decodeNested(){return[new _C.NothingValue,0]}decodeTopLevel(){return new _C.NothingValue}encodeNested(){return h.Buffer.from([])}encodeTopLevel(){return h.Buffer.from([])}};Gd.NothingCodec=Aw});var CC=v(jd=>{"use strict";l();Object.defineProperty(jd,"__esModule",{value:!0});jd.StringBinaryCodec=void 0;var TC=xt(),SV=Ii(),TV=Hd(),bw=class{constructor(){this.bytesBinaryCodec=new TV.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new TC.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new TC.StringValue(e.toString())}encodeNested(e){let r=SV.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return h.Buffer.from(e.valueOf())}};jd.StringBinaryCodec=bw});var xC=v(zd=>{"use strict";l();Object.defineProperty(zd,"__esModule",{value:!0});zd.PrimitiveBinaryCodec=void 0;var Qd=xt(),CV=dC(),xV=pC(),NV=EC(),OV=vC(),DV=Hd(),PV=IC(),RV=SC(),BV=CC(),Iw=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new xV.BooleanBinaryCodec,this.numericalCodec=new NV.NumericalBinaryCodec,this.addressCodec=new CV.AddressBinaryCodec,this.h256Codec=new OV.H256BinaryCodec,this.bytesCodec=new DV.BytesBinaryCodec,this.stringCodec=new BV.StringBinaryCodec,this.tokenIdentifierCodec=new PV.TokenIdentifierCodec,this.nothingCodec=new RV.NothingCodec}decodeNested(e,r){return Qd.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Qd.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Qd.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Qd.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};zd.PrimitiveBinaryCodec=Iw});var DC=v(Wd=>{"use strict";l();Object.defineProperty(Wd,"__esModule",{value:!0});Wd.ListBinaryCodec=void 0;var NC=xt(),OC=Fd(),_w=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,a=OC.SizeOfU32;e=o.slice(a);for(let u=0;u0;){let[a,u]=this.binaryCodec.decodeNested(e,n);i.push(a),o+=u,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new NC.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=h.Buffer.alloc(OC.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return h.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return h.Buffer.concat(r)}};Wd.ListBinaryCodec=_w});var Tw=v($d=>{"use strict";l();Object.defineProperty($d,"__esModule",{value:!0});$d.FieldsBinaryCodec=void 0;var LV=xt(),Sw=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,a]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(a),i+=a;let u=new LV.Field(o,s.name);n.push(u)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return h.Buffer.concat(r)}};$d.FieldsBinaryCodec=Sw});var xw=v(Kd=>{"use strict";l();Object.defineProperty(Kd,"__esModule",{value:!0});Kd.StructBinaryCodec=void 0;var FV=xt(),MV=Tw(),Cw=class{constructor(e){this.fieldsCodec=new MV.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new FV.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Kd.StructBinaryCodec=Cw});var PC=v(Jd=>{"use strict";l();Object.defineProperty(Jd,"__esModule",{value:!0});Jd.EnumBinaryCodec=void 0;var Yd=xt(),UV=Tw(),Nw=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new UV.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[a,u]=this.fieldsCodec.decodeNested(e,o);return[new Yd.EnumValue(r,s,a),i+u]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Yd.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Yd.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return h.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Yd.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return h.Buffer.concat([o,i])}};Jd.EnumBinaryCodec=Nw});var RC=v(Xd=>{"use strict";l();Object.defineProperty(Xd,"__esModule",{value:!0});Xd.TupleBinaryCodec=void 0;var qV=xw(),Ow=class{constructor(e){this.structCodec=new qV.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Xd.TupleBinaryCodec=Ow});var BC=v(Zd=>{"use strict";l();Object.defineProperty(Zd,"__esModule",{value:!0});Zd.ArrayVecBinaryCodec=void 0;var VV=xt(),Dw=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let a=0;a{"use strict";l();var HV=Nr&&Nr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),kV=Nr&&Nr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GV=Nr&&Nr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&HV(e,t,r);return kV(e,t),e};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.BinaryCodecConstraints=Nr.BinaryCodec=void 0;var LC=GV(Le()),eh=xt(),FC=br(),jV=fC(),QV=xC(),zV=DC(),WV=xw(),$V=PC(),KV=RC(),YV=BC(),Pw=class{constructor(e=null){this.constraints=e||new th,this.optionCodec=new jV.OptionValueBinaryCodec(this),this.listCodec=new zV.ListBinaryCodec(this),this.arrayCodec=new YV.ArrayVecBinaryCodec(this),this.primitiveCodec=new QV.PrimitiveBinaryCodec(this),this.structCodec=new WV.StructBinaryCodec(this),this.tupleCodec=new KV.TupleBinaryCodec(this),this.enumCodec=new $V.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),eh.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=eh.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return FC.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),eh.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return FC.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),eh.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Nr.BinaryCodec=Pw;var th=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new LC.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new LC.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Nr.BinaryCodecConstraints=th});var MC=v(Or=>{"use strict";l();var JV=Or&&Or.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Or,"__esModule",{value:!0});Or.decodeBigNumber=Or.decodeString=Or.decodeBool=Or.decodeUnsignedNumber=void 0;var XV=JV(Yt()),rh=xt(),ZV=Rw(),nh=new ZV.BinaryCodec;function eH(t){let e=nh.decodeTopLevel(t,new rh.BigUIntType);return Number(e.valueOf())}Or.decodeUnsignedNumber=eH;function tH(t){return!!nh.decodeTopLevel(t,new rh.BooleanType).valueOf()}Or.decodeBool=tH;function rH(t){let e=nh.decodeTopLevel(t,new rh.BytesType);return String(e.valueOf())}Or.decodeString=rH;function nH(t){let e=nh.decodeTopLevel(t,new rh.BigUIntType);return new XV.default(e.valueOf())}Or.decodeBigNumber=nH});var Bw=v(Ti=>{"use strict";l();var iH=Ti&&Ti.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),UC=Ti&&Ti.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&iH(e,t,r)};Object.defineProperty(Ti,"__esModule",{value:!0});UC(Rw(),Ti);UC(MC(),Ti)});var na=v(ih=>{"use strict";l();Object.defineProperty(ih,"__esModule",{value:!0});ih.ArgSerializer=void 0;var qC=Ns(),sH=Bw(),VC=xt(),Lw=Yf(),Fw=td(),Mw=xd(),oH={codec:new sH.BinaryCodec},Uw=class{constructor(e){e=Object.assign(Object.assign({},oH),e),this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split(qC.ARGUMENTS_SEPARATOR).map(r=>h.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join(qC.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(Lw.OptionalValue.ClassName)){let u=o;u.isSet()&&i(u.getTypedValue());return}if(o.hasExactClass(Mw.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(Fw.CompositeValue.ClassName)){let u=o;for(let c of u.getItems())i(c);return}let a=r.codec.encodeTopLevel(o);n.push(a)}function s(o){if(o.getType().isCounted){let u=new VC.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(u))}for(let u of o.getItems())i(u)}return n}};ih.ArgSerializer=Uw});var ah=v(oh=>{"use strict";l();Object.defineProperty(oh,"__esModule",{value:!0});oh.Compatibility=void 0;var aH=pt(),sh=class{static guardAddressIsSetAndNonZero(e,r,n){this.areWarningsEnabled&&(!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==aH.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`))}};oh.Compatibility=sh;sh.areWarningsEnabled=!0});var HC=v(wn=>{"use strict";l();var uH=wn&&wn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),cH=wn&&wn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),lH=wn&&wn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&uH(e,t,r);return cH(e,t),e};Object.defineProperty(wn,"__esModule",{value:!0});wn.Hash=void 0;var fH=lH(Le()),qw=class t{constructor(e){if(!e)this.hash=h.Buffer.from([]);else if(e instanceof h.Buffer)this.hash=e;else if(typeof e=="string")this.hash=h.Buffer.from(e,"hex");else throw new fH.ErrBadType("hash","buffer | string",e)}static empty(){return new t(h.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};wn.Hash=qw});var xc=v(Dr=>{"use strict";l();var dH=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),hH=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),pH=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&dH(e,t,r);return hH(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.TransactionOptions=Dr.TransactionVersion=void 0;var Wr=Ns(),kC=pH(Le()),Vw=class t{constructor(e){if(e=Number(e),e<1)throw new kC.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(Wr.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(Wr.TRANSACTION_VERSION_WITH_OPTIONS)}valueOf(){return this.value}};Dr.TransactionVersion=Vw;var Hw=class t{constructor(e){if(e=Number(e),e<0)throw new kC.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(Wr.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=Wr.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN)==Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&Wr.TRANSACTION_OPTIONS_TX_GUARDED)==Wr.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=Wr.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=Wr.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};Dr.TransactionOptions=Hw});var jC=v((mue,GC)=>{"use strict";l();GC.exports=gH;function gH(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";l();var uh=WC;uh.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var ia=new Array(64),zC=new Array(123);for($r=0;$r<64;)zC[ia[$r]=$r<26?$r+65:$r<52?$r+71:$r<62?$r-4:$r-59|43]=$r++;var $r;uh.encode=function(e,r,n){for(var i=null,s=[],o=0,a=0,u;r>2],u=(c&3)<<4,a=1;break;case 1:s[o++]=ia[u|c>>4],u=(c&15)<<2,a=2;break;case 2:s[o++]=ia[u|c>>6],s[o++]=ia[c&63],a=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return a&&(s[o++]=ia[u],s[o++]=61,a===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var QC="invalid encoding";uh.decode=function(e,r,n){for(var i=n,s=0,o,a=0;a1)break;if((u=zC[u])===void 0)throw Error(QC);switch(s){case 0:o=u,s=1;break;case 1:r[n++]=o<<2|(u&48)>>4,o=u,s=2;break;case 2:r[n++]=(o&15)<<4|(u&60)>>2,o=u,s=3;break;case 3:r[n++]=(o&3)<<6|u,s=0;break}}if(s===1)throw Error(QC);return n-i};uh.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var YC=v((Aue,KC)=>{"use strict";l();KC.exports=ch;function ch(){this._listeners={}}ch.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};ch.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";l();rx.exports=JC(JC);function JC(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(u,c,f){e[0]=u,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(u,c,f){e[0]=u,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(u,c){return r[0]=u[c],r[1]=u[c+1],r[2]=u[c+2],r[3]=u[c+3],e[0]}function a(u,c){return r[3]=u[c],r[2]=u[c+1],r[1]=u[c+2],r[0]=u[c+3],e[0]}t.readFloatLE=n?o:a,t.readFloatBE=n?a:o}():function(){function e(n,i,s,o){var a=i<0?1:0;if(a&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((a<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((a<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var u=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-u)*8388608)&8388607;n((a<<31|u+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,XC),t.writeFloatBE=e.bind(null,ZC);function r(n,i,s){var o=n(i,s),a=(o>>31)*2+1,u=o>>>23&255,c=o&8388607;return u===255?c?NaN:a*(1/0):u===0?a*1401298464324817e-60*c:a*Math.pow(2,u-150)*(c+8388608)}t.readFloatLE=r.bind(null,ex),t.readFloatBE=r.bind(null,tx)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(u,c,f){e[0]=u,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(u,c,f){e[0]=u,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(u,c){return r[0]=u[c],r[1]=u[c+1],r[2]=u[c+2],r[3]=u[c+3],r[4]=u[c+4],r[5]=u[c+5],r[6]=u[c+6],r[7]=u[c+7],e[0]}function a(u,c){return r[7]=u[c],r[6]=u[c+1],r[5]=u[c+2],r[4]=u[c+3],r[3]=u[c+4],r[2]=u[c+5],r[1]=u[c+6],r[0]=u[c+7],e[0]}t.readDoubleLE=n?o:a,t.readDoubleBE=n?a:o}():function(){function e(n,i,s,o,a,u){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,a,u+i),n(1/o>0?0:2147483648,a,u+s);else if(isNaN(o))n(0,a,u+i),n(2146959360,a,u+s);else if(o>17976931348623157e292)n(0,a,u+i),n((c<<31|2146435072)>>>0,a,u+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,a,u+i),n((c<<31|f/4294967296)>>>0,a,u+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,a,u+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,a,u+s)}}}t.writeDoubleLE=e.bind(null,XC,0,4),t.writeDoubleBE=e.bind(null,ZC,4,0);function r(n,i,s,o,a){var u=n(o,a+i),c=n(o,a+s),f=(c>>31)*2+1,d=c>>>20&2047,g=4294967296*(c&1048575)+u;return d===2047?g?NaN:f*(1/0):d===0?f*5e-324*g:f*Math.pow(2,d-1075)*(g+4503599627370496)}t.readDoubleLE=r.bind(null,ex,0,4),t.readDoubleBE=r.bind(null,tx,4,0)}(),t}function XC(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function ZC(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function ex(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function tx(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var ix=v((exports,module)=>{"use strict";l();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var ox=v(sx=>{"use strict";l();var kw=sx;kw.length=function(e){for(var r=0,n=0,i=0;i191&&u<224?o[a++]=(u&31)<<6|e[r++]&63:u>239&&u<365?(u=((u&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[a++]=55296+(u>>10),o[a++]=56320+(u&1023)):o[a++]=(u&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,o.slice(0,a))),s.join("")):String.fromCharCode.apply(String,o.slice(0,a))};kw.write=function(e,r,n){for(var i=n,s,o,a=0;a>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++a,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var ux=v((xue,ax)=>{"use strict";l();ax.exports=yH;function yH(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(u){if(u<1||u>i)return t(u);o+u>n&&(s=t(n),o=0);var c=e.call(s,o,o+=u);return o&7&&(o=(o|7)+1),c}}});var lx=v((Oue,cx)=>{"use strict";l();cx.exports=qt;var Nc=xi();function qt(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ls=qt.zero=new qt(0,0);Ls.toNumber=function(){return 0};Ls.zzEncode=Ls.zzDecode=function(){return this};Ls.length=function(){return 1};var mH=qt.zeroHash="\0\0\0\0\0\0\0\0";qt.fromNumber=function(e){if(e===0)return Ls;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new qt(n,i)};qt.from=function(e){if(typeof e=="number")return qt.fromNumber(e);if(Nc.isString(e))if(Nc.Long)e=Nc.Long.fromString(e);else return qt.fromNumber(parseInt(e,10));return e.low||e.high?new qt(e.low>>>0,e.high>>>0):Ls};qt.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};qt.prototype.toLong=function(e){return Nc.Long?new Nc.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Ci=String.prototype.charCodeAt;qt.fromHash=function(e){return e===mH?Ls:new qt((Ci.call(e,0)|Ci.call(e,1)<<8|Ci.call(e,2)<<16|Ci.call(e,3)<<24)>>>0,(Ci.call(e,4)|Ci.call(e,5)<<8|Ci.call(e,6)<<16|Ci.call(e,7)<<24)>>>0)};qt.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};qt.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};qt.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};qt.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var xi=v(Gw=>{"use strict";l();var Ie=Gw;Ie.asPromise=jC();Ie.base64=$C();Ie.EventEmitter=YC();Ie.float=nx();Ie.inquire=ix();Ie.utf8=ox();Ie.pool=ux();Ie.LongBits=lx();Ie.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);Ie.global=Ie.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||Gw;Ie.emptyArray=Object.freeze?Object.freeze([]):[];Ie.emptyObject=Object.freeze?Object.freeze({}):{};Ie.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};Ie.isString=function(e){return typeof e=="string"||e instanceof String};Ie.isObject=function(e){return e&&typeof e=="object"};Ie.isset=Ie.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};Ie.Buffer=function(){try{var t=Ie.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();Ie._Buffer_from=null;Ie._Buffer_allocUnsafe=null;Ie.newBuffer=function(e){return typeof e=="number"?Ie.Buffer?Ie._Buffer_allocUnsafe(e):new Ie.Array(e):Ie.Buffer?Ie._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};Ie.Array=typeof Uint8Array<"u"?Uint8Array:Array;Ie.Long=Ie.global.dcodeIO&&Ie.global.dcodeIO.Long||Ie.global.Long||Ie.inquire("long");Ie.key2Re=/^true|false|0|1$/;Ie.key32Re=/^-?(?:0|[1-9][0-9]*)$/;Ie.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;Ie.longToHash=function(e){return e?Ie.LongBits.from(e).toHash():Ie.LongBits.zeroHash};Ie.longFromHash=function(e,r){var n=Ie.LongBits.fromHash(e);return Ie.Long?Ie.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function fx(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};Ie.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";l();yx.exports=Ue;var Pr=xi(),jw,lh=Pr.LongBits,hx=Pr.base64,px=Pr.utf8;function Oc(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function zw(){}function wH(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Oc(zw,0,0),this.tail=this.head,this.states=null}var gx=function(){return Pr.Buffer?function(){return(Ue.create=function(){return new jw})()}:function(){return new Ue}};Ue.create=gx();Ue.alloc=function(e){return new Pr.Array(e)};Pr.Array!==Array&&(Ue.alloc=Pr.pool(Ue.alloc,Pr.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Oc(e,r,n),this.len+=r,this};function Ww(t,e,r){e[r]=t&255}function EH(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function $w(t,e){this.len=t,this.next=void 0,this.val=e}$w.prototype=Object.create(Oc.prototype);$w.prototype.fn=EH;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new $w((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(Kw,10,lh.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Kw(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=lh.from(e);return this._push(Kw,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=lh.from(e).zzEncode();return this._push(Kw,r.length(),r)};Ue.prototype.bool=function(e){return this._push(Ww,1,e?1:0)};function Qw(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(Qw,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=lh.from(e);return this._push(Qw,4,r.lo)._push(Qw,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Pr.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Pr.float.writeDoubleLE,8,e)};var vH=Pr.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(Ww,1,0);if(Pr.isString(e)){var n=Ue.alloc(r=hx.length(e));hx.decode(e,n,0),e=n}return this.uint32(r)._push(vH,r,e)};Ue.prototype.string=function(e){var r=px.length(e);return r?this.uint32(r)._push(px.write,r,e):this._push(Ww,1,0)};Ue.prototype.fork=function(){return this.states=new wH(this),this.head=this.tail=new Oc(zw,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Oc(zw,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){jw=t,Ue.create=gx(),jw._configure()}});var Ex=v((Fue,wx)=>{"use strict";l();wx.exports=En;var mx=Yw();(En.prototype=Object.create(mx.prototype)).constructor=En;var Ni=xi();function En(){mx.call(this)}En._configure=function(){En.alloc=Ni._Buffer_allocUnsafe,En.writeBytesBuffer=Ni.Buffer&&Ni.Buffer.prototype instanceof Uint8Array&&Ni.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(En.writeBytesBuffer,r,e),this};function AH(t,e,r){t.length<40?Ni.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}En.prototype.string=function(e){var r=Ni.Buffer.byteLength(e);return this.uint32(r),r&&this._push(AH,r,e),this};En._configure()});var Zw=v((Uue,_x)=>{"use strict";l();_x.exports=bt;var vn=xi(),Xw,bx=vn.LongBits,bH=vn.utf8;function Kr(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function bt(t){this.buf=t,this.pos=0,this.len=t.length}var vx=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new bt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new bt(e);throw Error("illegal buffer")},Ix=function(){return vn.Buffer?function(r){return(bt.create=function(i){return vn.Buffer.isBuffer(i)?new Xw(i):vx(i)})(r)}:vx};bt.create=Ix();bt.prototype._slice=vn.Array.prototype.subarray||vn.Array.prototype.slice;bt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Kr(this,10);return e}}();bt.prototype.int32=function(){return this.uint32()|0};bt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Jw(){var t=new bx(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Kr(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Kr(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}bt.prototype.bool=function(){return this.uint32()!==0};function fh(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}bt.prototype.fixed32=function(){if(this.pos+4>this.len)throw Kr(this,4);return fh(this.buf,this.pos+=4)};bt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Kr(this,4);return fh(this.buf,this.pos+=4)|0};function Ax(){if(this.pos+8>this.len)throw Kr(this,8);return new bx(fh(this.buf,this.pos+=4),fh(this.buf,this.pos+=4))}bt.prototype.float=function(){if(this.pos+4>this.len)throw Kr(this,4);var e=vn.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};bt.prototype.double=function(){if(this.pos+8>this.len)throw Kr(this,4);var e=vn.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};bt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Kr(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(r,n):r===n?new this.buf.constructor(0):this._slice.call(this.buf,r,n)};bt.prototype.string=function(){var e=this.bytes();return bH.read(e,0,e.length)};bt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Kr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Kr(this);while(this.buf[this.pos++]&128);return this};bt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};bt._configure=function(t){Xw=t,bt.create=Ix(),Xw._configure();var e=vn.Long?"toLong":"toNumber";vn.merge(bt.prototype,{int64:function(){return Jw.call(this)[e](!1)},uint64:function(){return Jw.call(this)[e](!0)},sint64:function(){return Jw.call(this).zzDecode()[e](!1)},fixed64:function(){return Ax.call(this)[e](!0)},sfixed64:function(){return Ax.call(this)[e](!1)}})}});var xx=v((Vue,Cx)=>{"use strict";l();Cx.exports=Fs;var Tx=Zw();(Fs.prototype=Object.create(Tx.prototype)).constructor=Fs;var Sx=xi();function Fs(t){Tx.call(this,t)}Fs._configure=function(){Sx.Buffer&&(Fs.prototype._slice=Sx.Buffer.prototype.slice)};Fs.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Fs._configure()});var Ox=v((kue,Nx)=>{"use strict";l();Nx.exports=Dc;var eE=xi();(Dc.prototype=Object.create(eE.EventEmitter.prototype)).constructor=Dc;function Dc(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");eE.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Dc.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return eE.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(u,c){if(u)return o.emit("error",u,e),s(u);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(a){o.emit("error",a,e),setTimeout(function(){s(a)},0);return}};Dc.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var Px=v(Dx=>{"use strict";l();var IH=Dx;IH.Service=Ox()});var Bx=v((zue,Rx)=>{"use strict";l();Rx.exports={}});var Mx=v(Fx=>{"use strict";l();var pr=Fx;pr.build="minimal";pr.Writer=Yw();pr.BufferWriter=Ex();pr.Reader=Zw();pr.BufferReader=xx();pr.util=xi();pr.rpc=Px();pr.roots=Bx();pr.configure=Lx;function Lx(){pr.util._configure(),pr.Writer._configure(pr.BufferWriter),pr.Reader._configure(pr.BufferReader)}Lx()});var qx=v((Yue,Ux)=>{"use strict";l();Ux.exports=Mx()});var Hx=v((Xue,Vx)=>{"use strict";l();var sa=qx(),dh=sa.Reader,_H=sa.Writer,Z=sa.util,Pc=sa.roots.default||(sa.roots.default={});Pc.proto=function(){var t={};return t.Transaction=function(){function e(r){if(r)for(var n=Object.keys(r),i=0;i>>3){case 1:o.Nonce=n.uint64();break;case 2:o.Value=n.bytes();break;case 3:o.RcvAddr=n.bytes();break;case 4:o.RcvUserName=n.bytes();break;case 5:o.SndAddr=n.bytes();break;case 6:o.SndUserName=n.bytes();break;case 7:o.GasPrice=n.uint64();break;case 8:o.GasLimit=n.uint64();break;case 9:o.Data=n.bytes();break;case 10:o.ChainID=n.bytes();break;case 11:o.Version=n.uint32();break;case 12:o.Signature=n.bytes();break;case 13:o.Options=n.uint32();break;case 14:o.GuardAddr=n.bytes();break;case 15:o.GuardSignature=n.bytes();break;default:n.skipType(a&7);break}}return o},e.decodeDelimited=function(n){return n instanceof dh||(n=new dh(n)),this.decode(n,n.uint32())},e.verify=function(n){return typeof n!="object"||n===null?"object expected":n.Nonce!=null&&n.hasOwnProperty("Nonce")&&!Z.isInteger(n.Nonce)&&!(n.Nonce&&Z.isInteger(n.Nonce.low)&&Z.isInteger(n.Nonce.high))?"Nonce: integer|Long expected":n.Value!=null&&n.hasOwnProperty("Value")&&!(n.Value&&typeof n.Value.length=="number"||Z.isString(n.Value))?"Value: buffer expected":n.RcvAddr!=null&&n.hasOwnProperty("RcvAddr")&&!(n.RcvAddr&&typeof n.RcvAddr.length=="number"||Z.isString(n.RcvAddr))?"RcvAddr: buffer expected":n.RcvUserName!=null&&n.hasOwnProperty("RcvUserName")&&!(n.RcvUserName&&typeof n.RcvUserName.length=="number"||Z.isString(n.RcvUserName))?"RcvUserName: buffer expected":n.SndAddr!=null&&n.hasOwnProperty("SndAddr")&&!(n.SndAddr&&typeof n.SndAddr.length=="number"||Z.isString(n.SndAddr))?"SndAddr: buffer expected":n.SndUserName!=null&&n.hasOwnProperty("SndUserName")&&!(n.SndUserName&&typeof n.SndUserName.length=="number"||Z.isString(n.SndUserName))?"SndUserName: buffer expected":n.GasPrice!=null&&n.hasOwnProperty("GasPrice")&&!Z.isInteger(n.GasPrice)&&!(n.GasPrice&&Z.isInteger(n.GasPrice.low)&&Z.isInteger(n.GasPrice.high))?"GasPrice: integer|Long expected":n.GasLimit!=null&&n.hasOwnProperty("GasLimit")&&!Z.isInteger(n.GasLimit)&&!(n.GasLimit&&Z.isInteger(n.GasLimit.low)&&Z.isInteger(n.GasLimit.high))?"GasLimit: integer|Long expected":n.Data!=null&&n.hasOwnProperty("Data")&&!(n.Data&&typeof n.Data.length=="number"||Z.isString(n.Data))?"Data: buffer expected":n.ChainID!=null&&n.hasOwnProperty("ChainID")&&!(n.ChainID&&typeof n.ChainID.length=="number"||Z.isString(n.ChainID))?"ChainID: buffer expected":n.Version!=null&&n.hasOwnProperty("Version")&&!Z.isInteger(n.Version)?"Version: integer expected":n.Signature!=null&&n.hasOwnProperty("Signature")&&!(n.Signature&&typeof n.Signature.length=="number"||Z.isString(n.Signature))?"Signature: buffer expected":n.Options!=null&&n.hasOwnProperty("Options")&&!Z.isInteger(n.Options)?"Options: integer expected":n.GuardAddr!=null&&n.hasOwnProperty("GuardAddr")&&!(n.GuardAddr&&typeof n.GuardAddr.length=="number"||Z.isString(n.GuardAddr))?"GuardAddr: buffer expected":n.GuardSignature!=null&&n.hasOwnProperty("GuardSignature")&&!(n.GuardSignature&&typeof n.GuardSignature.length=="number"||Z.isString(n.GuardSignature))?"GuardSignature: buffer expected":null},e.fromObject=function(n){if(n instanceof Pc.proto.Transaction)return n;var i=new Pc.proto.Transaction;return n.Nonce!=null&&(Z.Long?(i.Nonce=Z.Long.fromValue(n.Nonce)).unsigned=!0:typeof n.Nonce=="string"?i.Nonce=parseInt(n.Nonce,10):typeof n.Nonce=="number"?i.Nonce=n.Nonce:typeof n.Nonce=="object"&&(i.Nonce=new Z.LongBits(n.Nonce.low>>>0,n.Nonce.high>>>0).toNumber(!0))),n.Value!=null&&(typeof n.Value=="string"?Z.base64.decode(n.Value,i.Value=Z.newBuffer(Z.base64.length(n.Value)),0):n.Value.length&&(i.Value=n.Value)),n.RcvAddr!=null&&(typeof n.RcvAddr=="string"?Z.base64.decode(n.RcvAddr,i.RcvAddr=Z.newBuffer(Z.base64.length(n.RcvAddr)),0):n.RcvAddr.length&&(i.RcvAddr=n.RcvAddr)),n.RcvUserName!=null&&(typeof n.RcvUserName=="string"?Z.base64.decode(n.RcvUserName,i.RcvUserName=Z.newBuffer(Z.base64.length(n.RcvUserName)),0):n.RcvUserName.length&&(i.RcvUserName=n.RcvUserName)),n.SndAddr!=null&&(typeof n.SndAddr=="string"?Z.base64.decode(n.SndAddr,i.SndAddr=Z.newBuffer(Z.base64.length(n.SndAddr)),0):n.SndAddr.length&&(i.SndAddr=n.SndAddr)),n.SndUserName!=null&&(typeof n.SndUserName=="string"?Z.base64.decode(n.SndUserName,i.SndUserName=Z.newBuffer(Z.base64.length(n.SndUserName)),0):n.SndUserName.length&&(i.SndUserName=n.SndUserName)),n.GasPrice!=null&&(Z.Long?(i.GasPrice=Z.Long.fromValue(n.GasPrice)).unsigned=!0:typeof n.GasPrice=="string"?i.GasPrice=parseInt(n.GasPrice,10):typeof n.GasPrice=="number"?i.GasPrice=n.GasPrice:typeof n.GasPrice=="object"&&(i.GasPrice=new Z.LongBits(n.GasPrice.low>>>0,n.GasPrice.high>>>0).toNumber(!0))),n.GasLimit!=null&&(Z.Long?(i.GasLimit=Z.Long.fromValue(n.GasLimit)).unsigned=!0:typeof n.GasLimit=="string"?i.GasLimit=parseInt(n.GasLimit,10):typeof n.GasLimit=="number"?i.GasLimit=n.GasLimit:typeof n.GasLimit=="object"&&(i.GasLimit=new Z.LongBits(n.GasLimit.low>>>0,n.GasLimit.high>>>0).toNumber(!0))),n.Data!=null&&(typeof n.Data=="string"?Z.base64.decode(n.Data,i.Data=Z.newBuffer(Z.base64.length(n.Data)),0):n.Data.length&&(i.Data=n.Data)),n.ChainID!=null&&(typeof n.ChainID=="string"?Z.base64.decode(n.ChainID,i.ChainID=Z.newBuffer(Z.base64.length(n.ChainID)),0):n.ChainID.length&&(i.ChainID=n.ChainID)),n.Version!=null&&(i.Version=n.Version>>>0),n.Signature!=null&&(typeof n.Signature=="string"?Z.base64.decode(n.Signature,i.Signature=Z.newBuffer(Z.base64.length(n.Signature)),0):n.Signature.length&&(i.Signature=n.Signature)),n.Options!=null&&(i.Options=n.Options>>>0),n.GuardAddr!=null&&(typeof n.GuardAddr=="string"?Z.base64.decode(n.GuardAddr,i.GuardAddr=Z.newBuffer(Z.base64.length(n.GuardAddr)),0):n.GuardAddr.length&&(i.GuardAddr=n.GuardAddr)),n.GuardSignature!=null&&(typeof n.GuardSignature=="string"?Z.base64.decode(n.GuardSignature,i.GuardSignature=Z.newBuffer(Z.base64.length(n.GuardSignature)),0):n.GuardSignature.length&&(i.GuardSignature=n.GuardSignature)),i},e.toObject=function(n,i){i||(i={});var s={};if(i.defaults){if(Z.Long){var o=new Z.Long(0,0,!0);s.Nonce=i.longs===String?o.toString():i.longs===Number?o.toNumber():o}else s.Nonce=i.longs===String?"0":0;if(i.bytes===String?s.Value="":(s.Value=[],i.bytes!==Array&&(s.Value=Z.newBuffer(s.Value))),i.bytes===String?s.RcvAddr="":(s.RcvAddr=[],i.bytes!==Array&&(s.RcvAddr=Z.newBuffer(s.RcvAddr))),i.bytes===String?s.RcvUserName="":(s.RcvUserName=[],i.bytes!==Array&&(s.RcvUserName=Z.newBuffer(s.RcvUserName))),i.bytes===String?s.SndAddr="":(s.SndAddr=[],i.bytes!==Array&&(s.SndAddr=Z.newBuffer(s.SndAddr))),i.bytes===String?s.SndUserName="":(s.SndUserName=[],i.bytes!==Array&&(s.SndUserName=Z.newBuffer(s.SndUserName))),Z.Long){var o=new Z.Long(0,0,!0);s.GasPrice=i.longs===String?o.toString():i.longs===Number?o.toNumber():o}else s.GasPrice=i.longs===String?"0":0;if(Z.Long){var o=new Z.Long(0,0,!0);s.GasLimit=i.longs===String?o.toString():i.longs===Number?o.toNumber():o}else s.GasLimit=i.longs===String?"0":0;i.bytes===String?s.Data="":(s.Data=[],i.bytes!==Array&&(s.Data=Z.newBuffer(s.Data))),i.bytes===String?s.ChainID="":(s.ChainID=[],i.bytes!==Array&&(s.ChainID=Z.newBuffer(s.ChainID))),s.Version=0,i.bytes===String?s.Signature="":(s.Signature=[],i.bytes!==Array&&(s.Signature=Z.newBuffer(s.Signature))),s.Options=0,i.bytes===String?s.GuardAddr="":(s.GuardAddr=[],i.bytes!==Array&&(s.GuardAddr=Z.newBuffer(s.GuardAddr))),i.bytes===String?s.GuardSignature="":(s.GuardSignature=[],i.bytes!==Array&&(s.GuardSignature=Z.newBuffer(s.GuardSignature)))}return n.Nonce!=null&&n.hasOwnProperty("Nonce")&&(typeof n.Nonce=="number"?s.Nonce=i.longs===String?String(n.Nonce):n.Nonce:s.Nonce=i.longs===String?Z.Long.prototype.toString.call(n.Nonce):i.longs===Number?new Z.LongBits(n.Nonce.low>>>0,n.Nonce.high>>>0).toNumber(!0):n.Nonce),n.Value!=null&&n.hasOwnProperty("Value")&&(s.Value=i.bytes===String?Z.base64.encode(n.Value,0,n.Value.length):i.bytes===Array?Array.prototype.slice.call(n.Value):n.Value),n.RcvAddr!=null&&n.hasOwnProperty("RcvAddr")&&(s.RcvAddr=i.bytes===String?Z.base64.encode(n.RcvAddr,0,n.RcvAddr.length):i.bytes===Array?Array.prototype.slice.call(n.RcvAddr):n.RcvAddr),n.RcvUserName!=null&&n.hasOwnProperty("RcvUserName")&&(s.RcvUserName=i.bytes===String?Z.base64.encode(n.RcvUserName,0,n.RcvUserName.length):i.bytes===Array?Array.prototype.slice.call(n.RcvUserName):n.RcvUserName),n.SndAddr!=null&&n.hasOwnProperty("SndAddr")&&(s.SndAddr=i.bytes===String?Z.base64.encode(n.SndAddr,0,n.SndAddr.length):i.bytes===Array?Array.prototype.slice.call(n.SndAddr):n.SndAddr),n.SndUserName!=null&&n.hasOwnProperty("SndUserName")&&(s.SndUserName=i.bytes===String?Z.base64.encode(n.SndUserName,0,n.SndUserName.length):i.bytes===Array?Array.prototype.slice.call(n.SndUserName):n.SndUserName),n.GasPrice!=null&&n.hasOwnProperty("GasPrice")&&(typeof n.GasPrice=="number"?s.GasPrice=i.longs===String?String(n.GasPrice):n.GasPrice:s.GasPrice=i.longs===String?Z.Long.prototype.toString.call(n.GasPrice):i.longs===Number?new Z.LongBits(n.GasPrice.low>>>0,n.GasPrice.high>>>0).toNumber(!0):n.GasPrice),n.GasLimit!=null&&n.hasOwnProperty("GasLimit")&&(typeof n.GasLimit=="number"?s.GasLimit=i.longs===String?String(n.GasLimit):n.GasLimit:s.GasLimit=i.longs===String?Z.Long.prototype.toString.call(n.GasLimit):i.longs===Number?new Z.LongBits(n.GasLimit.low>>>0,n.GasLimit.high>>>0).toNumber(!0):n.GasLimit),n.Data!=null&&n.hasOwnProperty("Data")&&(s.Data=i.bytes===String?Z.base64.encode(n.Data,0,n.Data.length):i.bytes===Array?Array.prototype.slice.call(n.Data):n.Data),n.ChainID!=null&&n.hasOwnProperty("ChainID")&&(s.ChainID=i.bytes===String?Z.base64.encode(n.ChainID,0,n.ChainID.length):i.bytes===Array?Array.prototype.slice.call(n.ChainID):n.ChainID),n.Version!=null&&n.hasOwnProperty("Version")&&(s.Version=n.Version),n.Signature!=null&&n.hasOwnProperty("Signature")&&(s.Signature=i.bytes===String?Z.base64.encode(n.Signature,0,n.Signature.length):i.bytes===Array?Array.prototype.slice.call(n.Signature):n.Signature),n.Options!=null&&n.hasOwnProperty("Options")&&(s.Options=n.Options),n.GuardAddr!=null&&n.hasOwnProperty("GuardAddr")&&(s.GuardAddr=i.bytes===String?Z.base64.encode(n.GuardAddr,0,n.GuardAddr.length):i.bytes===Array?Array.prototype.slice.call(n.GuardAddr):n.GuardAddr),n.GuardSignature!=null&&n.hasOwnProperty("GuardSignature")&&(s.GuardSignature=i.bytes===String?Z.base64.encode(n.GuardSignature,0,n.GuardSignature.length):i.bytes===Array?Array.prototype.slice.call(n.GuardSignature):n.GuardSignature),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,sa.util.toJSONOptions)},e}(),t}();Vx.exports=Pc});var kx=v(Rr=>{"use strict";l();var SH=Rr&&Rr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),TH=Rr&&Rr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),CH=Rr&&Rr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&SH(e,t,r);return TH(e,t),e},xH=Rr&&Rr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Rr,"__esModule",{value:!0});Rr.ProtoSerializer=void 0;var NH=xH(Yt()),tE=pt(),OH=Ns(),DH=CH(Le()),PH=Tc(),rE=class{serializeTransaction(e){let r=Hx().proto,n=new tE.Address(e.getReceiver().bech32()).pubkey(),i=new tE.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?h.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?h.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:h.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==OH.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let u=e.getGuardian();s.GuardAddr=new tE.Address(u.bech32()).pubkey(),s.GuardSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return h.Buffer.from(o)}serializeTransactionValue(e){let r=new NH.default(e.toString());if(r.isZero())return h.Buffer.from([0,0]);let n=PH.bigIntToBuffer(r);return n=h.Buffer.concat([h.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new DH.ErrUnsupportedOperation("deserializeTransaction")}};Rr.ProtoSerializer=rE});var Gx=v(Ms=>{"use strict";l();var RH=Ms&&Ms.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),BH=Ms&&Ms.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&RH(e,t,r)};Object.defineProperty(Ms,"__esModule",{value:!0});BH(kx(),Ms)});var Rc=v(Br=>{"use strict";l();var LH=Br&&Br.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FH=Br&&Br.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),MH=Br&&Br.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LH(e,t,r);return FH(e,t),e};Object.defineProperty(Br,"__esModule",{value:!0});Br.interpretSignatureAsBuffer=Br.Signature=void 0;var jx=MH(Le()),Qx=64,nE=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof h.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new jx.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return h.Buffer.from(e,"hex").length==Qx}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=Qx)throw new jx.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Br.Signature=nE;function UH(t){if(ArrayBuffer.isView(t))return h.Buffer.from(t);if(t.hex!=null)return h.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Br.interpretSignatureAsBuffer=UH});var Yn=v(hh=>{"use strict";l();Object.defineProperty(hh,"__esModule",{value:!0});hh.TransactionPayload=void 0;var iE=class t{constructor(e){this.data=h.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=h.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>h.Buffer.from(e,"hex"))}length(){return h.Buffer.from(this.data).length}};hh.TransactionPayload=iE});var sE=v((uce,zx)=>{l();Jn.notEqual=VH;Jn.notOk=HH;Jn.equal=qH;Jn.ok=Jn;zx.exports=Jn;function qH(t,e,r){Jn(t==e,r)}function VH(t,e,r){Jn(t!=e,r)}function HH(t,e){Jn(!t,e)}function Jn(t,e){if(!t)throw new Error(e||"AssertionError")}});var qs=v(ca=>{"use strict";l();var oE=$0(),aa=Y0(),Wx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;ca.Buffer=W;ca.SlowBuffer=WH;ca.INSPECT_MAX_BYTES=50;var ph=2147483647;ca.kMaxLength=ph;W.TYPED_ARRAY_SUPPORT=kH();!W.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 kH(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(W.prototype,"parent",{enumerable:!0,get:function(){if(W.isBuffer(this))return this.buffer}});Object.defineProperty(W.prototype,"offset",{enumerable:!0,get:function(){if(W.isBuffer(this))return this.byteOffset}});function Xn(t){if(t>ph)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,W.prototype),e}function W(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return lE(t)}return Jx(t,e,r)}W.poolSize=8192;function Jx(t,e,r){if(typeof t=="string")return jH(t,e);if(ArrayBuffer.isView(t))return QH(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(An(t,ArrayBuffer)||t&&An(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(An(t,SharedArrayBuffer)||t&&An(t.buffer,SharedArrayBuffer)))return uE(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return W.from(n,e,r);let i=zH(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return W.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}W.from=function(t,e,r){return Jx(t,e,r)};Object.setPrototypeOf(W.prototype,Uint8Array.prototype);Object.setPrototypeOf(W,Uint8Array);function Xx(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function GH(t,e,r){return Xx(t),t<=0?Xn(t):e!==void 0?typeof r=="string"?Xn(t).fill(e,r):Xn(t).fill(e):Xn(t)}W.alloc=function(t,e,r){return GH(t,e,r)};function lE(t){return Xx(t),Xn(t<0?0:fE(t)|0)}W.allocUnsafe=function(t){return lE(t)};W.allocUnsafeSlow=function(t){return lE(t)};function jH(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!W.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=Zx(t,e)|0,n=Xn(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function aE(t){let e=t.length<0?0:fE(t.length)|0,r=Xn(e);for(let n=0;n=ph)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ph.toString(16)+" bytes");return t|0}function WH(t){return+t!=t&&(t=0),W.alloc(+t)}W.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==W.prototype};W.compare=function(e,r){if(An(e,Uint8Array)&&(e=W.from(e,e.offset,e.byteLength)),An(r,Uint8Array)&&(r=W.from(r,r.offset,r.byteLength)),!W.isBuffer(e)||!W.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let n=e.length,i=r.length;for(let s=0,o=Math.min(n,i);si.length?(W.isBuffer(o)||(o=W.from(o)),o.copy(i,s)):Uint8Array.prototype.set.call(i,o,s);else if(W.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function Zx(t,e){if(W.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||An(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return cE(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return uN(t).length;default:if(i)return n?-1:cE(t).length;e=(""+e).toLowerCase(),i=!0}}W.byteLength=Zx;function $H(t,e,r){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return ik(this,e,r);case"utf8":case"utf-8":return tN(this,e,r);case"ascii":return rk(this,e,r);case"latin1":case"binary":return nk(this,e,r);case"base64":return ek(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}W.prototype._isBuffer=!0;function Us(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}W.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;rr&&(e+=" ... "),""};Wx&&(W.prototype[Wx]=W.prototype.inspect);W.prototype.compare=function(e,r,n,i,s){if(An(e,Uint8Array)&&(e=W.from(e,e.offset,e.byteLength)),!W.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;let o=s-i,a=n-r,u=Math.min(o,a),c=this.slice(i,s),f=e.slice(r,n);for(let d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,hE(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=W.from(e,n)),W.isBuffer(e))return e.length===0?-1:$x(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):$x(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function $x(t,e,r,n,i){let s=1,o=t.length,a=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,a/=2,r/=2}function u(f,d){return s===1?f[d]:f.readUInt16BE(d*s)}let c;if(i){let f=-1;for(c=r;co&&(r=o-a),c=r;c>=0;c--){let f=!0;for(let d=0;di&&(n=i)):n=i;let s=e.length;n>s/2&&(n=s/2);let o;for(o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return KH(this,e,r,n);case"utf8":case"utf-8":return YH(this,e,r,n);case"ascii":case"latin1":case"binary":return JH(this,e,r,n);case"base64":return XH(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ZH(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};W.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ek(t,e,r){return e===0&&r===t.length?oE.fromByteArray(t):oE.fromByteArray(t.slice(e,r))}function tN(t,e,r){r=Math.min(t.length,r);let n=[],i=e;for(;i239?4:s>223?3:s>191?2:1;if(i+a<=r){let u,c,f,d;switch(a){case 1:s<128&&(o=s);break;case 2:u=t[i+1],(u&192)===128&&(d=(s&31)<<6|u&63,d>127&&(o=d));break;case 3:u=t[i+1],c=t[i+2],(u&192)===128&&(c&192)===128&&(d=(s&15)<<12|(u&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:u=t[i+1],c=t[i+2],f=t[i+3],(u&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(u&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=a}return tk(n)}var Kx=4096;function tk(t){let e=t.length;if(e<=Kx)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn)&&(r=n);let i="";for(let s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}W.prototype.readUintLE=W.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Vt(e,r,this.length);let i=this[e],s=1,o=0;for(;++o>>0,r=r>>>0,n||Vt(e,r,this.length);let i=this[e+--r],s=1;for(;r>0&&(s*=256);)i+=this[e+--r]*s;return i};W.prototype.readUint8=W.prototype.readUInt8=function(e,r){return e=e>>>0,r||Vt(e,1,this.length),this[e]};W.prototype.readUint16LE=W.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Vt(e,2,this.length),this[e]|this[e+1]<<8};W.prototype.readUint16BE=W.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Vt(e,2,this.length),this[e]<<8|this[e+1]};W.prototype.readUint32LE=W.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};W.prototype.readUint32BE=W.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};W.prototype.readBigUInt64LE=Oi(function(e){e=e>>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<>>0,r=r>>>0,n||Vt(e,r,this.length);let i=this[e],s=1,o=0;for(;++o=s&&(i-=Math.pow(2,8*r)),i};W.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Vt(e,r,this.length);let i=r,s=1,o=this[e+--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};W.prototype.readInt8=function(e,r){return e=e>>>0,r||Vt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};W.prototype.readInt16LE=function(e,r){e=e>>>0,r||Vt(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};W.prototype.readInt16BE=function(e,r){e=e>>>0,r||Vt(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};W.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};W.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};W.prototype.readBigInt64LE=Oi(function(e){e=e>>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<>>0,ua(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&Bc(e,this.length-8);let i=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,r||Vt(e,4,this.length),aa.read(this,e,!0,23,4)};W.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),aa.read(this,e,!1,23,4)};W.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Vt(e,8,this.length),aa.read(this,e,!0,52,8)};W.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Vt(e,8,this.length),aa.read(this,e,!1,52,8)};function gr(t,e,r,n,i,s){if(!W.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}W.prototype.writeUintLE=W.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;gr(this,e,r,n,a,0)}let s=1,o=0;for(this[r]=e&255;++o>>0,n=n>>>0,!i){let a=Math.pow(2,8*n)-1;gr(this,e,r,n,a,0)}let s=n-1,o=1;for(this[r+s]=e&255;--s>=0&&(o*=256);)this[r+s]=e/o&255;return r+n};W.prototype.writeUint8=W.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,1,255,0),this[r]=e&255,r+1};W.prototype.writeUint16LE=W.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};W.prototype.writeUint16BE=W.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};W.prototype.writeUint32LE=W.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};W.prototype.writeUint32BE=W.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function rN(t,e,r,n,i){aN(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,o=o>>8,t[r++]=o,r}function nN(t,e,r,n,i){aN(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=o,o=o>>8,t[r+2]=o,o=o>>8,t[r+1]=o,o=o>>8,t[r]=o,r+8}W.prototype.writeBigUInt64LE=Oi(function(e,r=0){return rN(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});W.prototype.writeBigUInt64BE=Oi(function(e,r=0){return nN(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});W.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let u=Math.pow(2,8*n-1);gr(this,e,r,n,u-1,-u)}let s=0,o=1,a=0;for(this[r]=e&255;++s>0)-a&255;return r+n};W.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let u=Math.pow(2,8*n-1);gr(this,e,r,n,u-1,-u)}let s=n-1,o=1,a=0;for(this[r+s]=e&255;--s>=0&&(o*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/o>>0)-a&255;return r+n};W.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};W.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};W.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};W.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};W.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||gr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};W.prototype.writeBigInt64LE=Oi(function(e,r=0){return rN(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});W.prototype.writeBigInt64BE=Oi(function(e,r=0){return nN(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function iN(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function sN(t,e,r,n,i){return e=+e,r=r>>>0,i||iN(t,e,r,4,34028234663852886e22,-34028234663852886e22),aa.write(t,e,r,n,23,4),r+4}W.prototype.writeFloatLE=function(e,r,n){return sN(this,e,r,!0,n)};W.prototype.writeFloatBE=function(e,r,n){return sN(this,e,r,!1,n)};function oN(t,e,r,n,i){return e=+e,r=r>>>0,i||iN(t,e,r,8,17976931348623157e292,-17976931348623157e292),aa.write(t,e,r,n,52,8),r+8}W.prototype.writeDoubleLE=function(e,r,n){return oN(this,e,r,!0,n)};W.prototype.writeDoubleBE=function(e,r,n){return oN(this,e,r,!1,n)};W.prototype.copy=function(e,r,n,i){if(!W.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s2**32?i=Yx(String(r)):typeof r=="bigint"&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=Yx(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function Yx(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function ok(t,e,r){ua(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&Bc(e,t.length-(r+1))}function aN(t,e,r,n,i,s){if(t>r||t3?e===0||e===BigInt(0)?a=`>= 0${o} and < 2${o} ** ${(s+1)*8}${o}`:a=`>= -(2${o} ** ${(s+1)*8-1}${o}) and < 2 ** ${(s+1)*8-1}${o}`:a=`>= ${e}${o} and <= ${r}${o}`,new oa.ERR_OUT_OF_RANGE("value",a,t)}ok(n,i,s)}function ua(t,e){if(typeof t!="number")throw new oa.ERR_INVALID_ARG_TYPE(e,"number",t)}function Bc(t,e,r){throw Math.floor(t)!==t?(ua(t,r),new oa.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new oa.ERR_BUFFER_OUT_OF_BOUNDS:new oa.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var ak=/[^+/0-9A-Za-z-_]/g;function uk(t){if(t=t.split("=")[0],t=t.trim().replace(ak,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function cE(t,e){e=e||1/0;let r,n=t.length,i=null,s=[];for(let o=0;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function ck(t){let e=[];for(let r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function uN(t){return oE.toByteArray(uk(t))}function gh(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function An(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function hE(t){return t!==t}var fk=function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let n=r*16;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Oi(t){return typeof BigInt>"u"?dk:t}function dk(){throw new Error("BigInt not supported")}});var lN=v((hce,cN)=>{l();cN.exports=pE;pE.supported=typeof WebAssembly<"u";function pE(t){if(!pE.supported)return null;var e=t&&t.imports,r=hk("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(u){i.exports.memory.grow(Math.ceil(Math.abs(u-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(u){if(i.exports)return u();if(n){n.then(u.bind(null,null)).catch(u);return}try{if(t&&t.async)throw new Error("async");a({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(a)}o(u)}function a(u){i.exports=u.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function hk(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(pk)):new(qs()).Buffer(t,"base64")}function pk(t){return t.charCodeAt(0)}});var mN=v((mce,In)=>{l();var bn=sE(),Ze=lN()(),Zn=64,yh=[];In.exports=Lr;var fN=In.exports.BYTES_MIN=16,dN=In.exports.BYTES_MAX=64,gce=In.exports.BYTES=32,hN=In.exports.KEYBYTES_MIN=16,pN=In.exports.KEYBYTES_MAX=64,yce=In.exports.KEYBYTES=32,gN=In.exports.SALTBYTES=16,yN=In.exports.PERSONALBYTES=16;function Lr(t,e,r,n,i){if(!(this instanceof Lr))return new Lr(t,e,r,n,i);if(!(Ze&&Ze.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(bn(t>=fN,"digestLength must be at least "+fN+", was given "+t),bn(t<=dN,"digestLength must be at most "+dN+", was given "+t),e!=null&&bn(e.length>=hN,"key must be at least "+hN+", was given "+e.length),e!=null&&bn(e.length<=pN,"key must be at least "+pN+", was given "+e.length),r!=null&&bn(r.length===gN,"salt must be exactly "+gN+", was given "+r.length),n!=null&&bn(n.length===yN,"personal must be exactly "+yN+", was given "+n.length)),yh.length||(yh.push(Zn),Zn+=216),this.digestLength=t,this.finalized=!1,this.pointer=yh.pop(),Ze.memory.fill(0,0,64),Ze.memory[0]=this.digestLength,Ze.memory[1]=e?e.length:0,Ze.memory[2]=1,Ze.memory[3]=1,r&&Ze.memory.set(r,32),n&&Ze.memory.set(n,48),this.pointer+216>Ze.memory.length&&Ze.realloc(this.pointer+216),Ze.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),Ze.memory.fill(0,Zn,Zn+e.length),Ze.memory[this.pointer+200]=128)}Lr.prototype.update=function(t){return bn(this.finalized===!1,"Hash instance finalized"),bn(t,"input must be TypedArray or Buffer"),Zn+t.length>Ze.memory.length&&Ze.realloc(Zn+t.length),Ze.memory.set(t,Zn),Ze.exports.blake2b_update(this.pointer,Zn,Zn+t.length),this};Lr.prototype.digest=function(t){if(bn(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,yh.push(this.pointer),Ze.exports.blake2b_final(this.pointer),!t||t==="binary")return Ze.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return yk(Ze.memory,this.pointer+128,this.digestLength);bn(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{l();var Ri=sE(),Fc=mN();function mh(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function wN(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function SN(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Di(t,e,r,n,i,s){var o=Lc[i],a=Lc[i+1],u=Lc[s],c=Lc[s+1];mh(xe,t,e),wN(xe,t,o,a);var f=xe[n]^xe[t],d=xe[n+1]^xe[t+1];xe[n]=d,xe[n+1]=f,mh(xe,r,n),f=xe[e]^xe[r],d=xe[e+1]^xe[r+1],xe[e]=f>>>24^d<<8,xe[e+1]=d>>>24^f<<8,mh(xe,t,e),wN(xe,t,u,c),f=xe[n]^xe[t],d=xe[n+1]^xe[t+1],xe[n]=f>>>16^d<<16,xe[n+1]=d>>>16^f<<16,mh(xe,r,n),f=xe[e]^xe[r],d=xe[e+1]^xe[r+1],xe[e]=d>>>31^f<<1,xe[e+1]=f>>>31^d<<1}var TN=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),wk=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Xt=new Uint8Array(wk.map(function(t){return t*2})),xe=new Uint32Array(32),Lc=new Uint32Array(32);function CN(t,e){var r=0;for(r=0;r<16;r++)xe[r]=t.h[r],xe[r+16]=TN[r];for(xe[24]=xe[24]^t.t,xe[25]=xe[25]^t.t/4294967296,e&&(xe[28]=~xe[28],xe[29]=~xe[29]),r=0;r<32;r++)Lc[r]=SN(t.b,4*r);for(r=0;r<12;r++)Di(0,8,16,24,Xt[r*16+0],Xt[r*16+1]),Di(2,10,18,26,Xt[r*16+2],Xt[r*16+3]),Di(4,12,20,28,Xt[r*16+4],Xt[r*16+5]),Di(6,14,22,30,Xt[r*16+6],Xt[r*16+7]),Di(0,10,20,30,Xt[r*16+8],Xt[r*16+9]),Di(2,12,22,24,Xt[r*16+10],Xt[r*16+11]),Di(4,14,16,26,Xt[r*16+12],Xt[r*16+13]),Di(6,8,18,28,Xt[r*16+14],Xt[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^xe[r]^xe[r+16]}var Pi=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function la(t,e,r,n){Pi.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Pi[0]=t,e&&(Pi[1]=e.length),Pi[2]=1,Pi[3]=1,r&&Pi.set(r,32),n&&Pi.set(n,48);for(var i=0;i<16;i++)this.h[i]=TN[i]^SN(Pi,i*4);e&&(xN(this,e),this.c=128)}la.prototype.update=function(t){return Ri(t!=null,"input must be Uint8Array or Buffer"),xN(this,t),this};la.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Ri(e.length>=this.outlen,"out must have at least outlen bytes of space"),Ek(this,e),t==="hex"?vk(e):e};la.prototype.final=la.prototype.digest;la.ready=function(t){Fc.ready(function(){t()})};function xN(t,e){for(var r=0;r>2]>>8*(r&3);return e}function vk(t){for(var e="",r=0;r=EN,"outlen must be at least "+EN+", was given "+e),Ri(e<=vN,"outlen must be at most "+vN+", was given "+e),r!=null&&Ri(r.length>=AN,"key must be at least "+AN+", was given "+r.length),r!=null&&Ri(r.length<=bN,"key must be at most "+bN+", was given "+r.length),n!=null&&Ri(n.length===IN,"salt must be exactly "+IN+", was given "+n.length),i!=null&&Ri(i.length===_N,"personal must be exactly "+_N+", was given "+i.length)),new NN(e,r,n,i)};yr.exports.ready=function(t){Fc.ready(function(){t()})};yr.exports.WASM_SUPPORTED=Fc.SUPPORTED;yr.exports.WASM_LOADED=!1;var EN=yr.exports.BYTES_MIN=16,vN=yr.exports.BYTES_MAX=64,Ece=yr.exports.BYTES=32,AN=yr.exports.KEYBYTES_MIN=16,bN=yr.exports.KEYBYTES_MAX=64,vce=yr.exports.KEYBYTES=32,IN=yr.exports.SALTBYTES=16,_N=yr.exports.PERSONALBYTES=16;Fc.ready(function(t){t||(yr.exports.WASM_LOADED=!0,NN=Fc)})});var Yr=v(Fr=>{"use strict";l();var bk=Fr&&Fr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ik=Fr&&Fr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_k=Fr&&Fr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&bk(e,t,r);return Ik(e,t),e};Object.defineProperty(Fr,"__esModule",{value:!0});Fr.TransactionHash=Fr.Transaction=void 0;var fa=Yt(),Mc=pt(),Sk=ah(),Tk=Ns(),Ck=_k(Le()),xk=HC(),ei=xc(),Nk=Gx(),wh=Rc(),ON=Yn(),Ok=br(),Dk=gE(),Pk=32,yE=class t{constructor({nonce:e,value:r,sender:n,receiver:i,senderUsername:s,receiverUsername:o,gasPrice:a,gasLimit:u,data:c,chainID:f,version:d,options:g,guardian:m}){this.nonce=e||0,this.value=r?new fa.BigNumber(r.toString()).toFixed(0):0,this.sender=n,this.receiver=i,this.senderUsername=s||"",this.receiverUsername=o||"",this.gasPrice=a||Tk.TRANSACTION_MIN_GAS_PRICE,this.gasLimit=u,this.data=c||new ON.TransactionPayload,this.chainID=f,this.version=d?new ei.TransactionVersion(d.valueOf()):ei.TransactionVersion.withDefaultVersion(),this.options=g?new ei.TransactionOptions(g.valueOf()):ei.TransactionOptions.withDefaultOptions(),this.guardian=m||Mc.Address.empty(),this.signature=h.Buffer.from([]),this.guardianSignature=h.Buffer.from([]),this.hash=da.empty()}getNonce(){return this.nonce}setNonce(e){this.nonce=e}getValue(){return this.value}setValue(e){this.value=e}getSender(){return this.sender}setSender(e){this.sender=e}getReceiver(){return this.receiver}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return this.guardian}getGasPrice(){return this.gasPrice}setGasPrice(e){this.gasPrice=e}getGasLimit(){return this.gasLimit}setGasLimit(e){this.gasLimit=e}getData(){return this.data}getChainID(){return this.chainID}setChainID(e){this.chainID=e}getVersion(){return this.version}setVersion(e){this.version=new ei.TransactionVersion(e.valueOf())}getOptions(){return new ei.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=new ei.TransactionOptions(e.valueOf())}getSignature(){return this.signature}getGuardianSignature(){return this.guardianSignature}setGuardian(e){this.guardian=e}getHash(){return Ok.guardNotEmpty(this.hash,"hash"),this.hash}serializeForSigning(){let e=this.toPlainObject();e.signature&&delete e.signature,e.guardianSignature&&delete e.guardianSignature,e.guardian||delete e.guardian;let r=JSON.stringify(e);return h.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.bech32().length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){var e;let r={nonce:this.nonce.valueOf(),value:this.value.toString(),receiver:this.receiver.bech32(),sender:this.sender.bech32(),senderUsername:this.senderUsername?h.Buffer.from(this.senderUsername).toString("base64"):void 0,receiverUsername:this.receiverUsername?h.Buffer.from(this.receiverUsername).toString("base64"):void 0,gasPrice:this.gasPrice.valueOf(),gasLimit:this.gasLimit.valueOf(),data:this.data.length()==0?void 0:this.data.encoded(),chainID:this.chainID.valueOf(),version:this.getVersion().valueOf(),options:this.getOptions().valueOf()==0?void 0:this.getOptions().valueOf(),guardian:!((e=this.guardian)===null||e===void 0)&&e.bech32()?this.guardian.bech32()==""?void 0:this.guardian.bech32():void 0,signature:this.signature.toString("hex")?this.signature.toString("hex"):void 0,guardianSignature:this.guardianSignature.toString("hex")?this.guardianSignature.toString("hex"):void 0};return Sk.Compatibility.guardAddressIsSetAndNonZero(new Mc.Address(r.sender),"'sender' of transaction","pass the actual sender to the Transaction constructor"),r}static fromPlainObject(e){let r=new t({nonce:Number(e.nonce),value:new fa.BigNumber(e.value).toFixed(0),receiver:Mc.Address.fromString(e.receiver),receiverUsername:e.receiverUsername?h.Buffer.from(e.receiverUsername,"base64").toString():void 0,sender:Mc.Address.fromString(e.sender),senderUsername:e.senderUsername?h.Buffer.from(e.senderUsername,"base64").toString():void 0,guardian:e.guardian?Mc.Address.fromString(e.guardian):void 0,gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:new ON.TransactionPayload(h.Buffer.from(e.data||"","base64")),chainID:String(e.chainID),version:new ei.TransactionVersion(e.version),options:e.options!=null?new ei.TransactionOptions(e.options):void 0});return e.signature&&r.applySignature(new wh.Signature(e.signature)),e.guardianSignature&&r.applyGuardianSignature(new wh.Signature(e.guardianSignature)),r}applySignature(e){this.signature=wh.interpretSignatureAsBuffer(e),this.hash=da.compute(this)}applyGuardianSignature(e){this.guardianSignature=wh.interpretSignatureAsBuffer(e),this.hash=da.compute(this)}toSendable(){return this.toPlainObject()}computeFee(e){let r=e.MinGasLimit.valueOf()+this.data.length()*e.GasPerDataByte.valueOf();if(r>this.gasLimit.valueOf())throw new Ck.ErrNotEnoughGas(this.gasLimit.valueOf());let n=new fa.BigNumber(this.gasPrice.valueOf()),i=new fa.BigNumber(r).multipliedBy(n);if(r===this.gasLimit.valueOf())return i;let s=new fa.BigNumber(this.gasLimit.valueOf()-r),o=n.multipliedBy(new fa.BigNumber(e.GasPriceModifier.valueOf())),a=s.multipliedBy(o);return i.plus(a)}};Fr.Transaction=yE;var da=class t extends xk.Hash{constructor(e){super(e)}static compute(e){let n=new Nk.ProtoSerializer().serializeTransaction(e),i=Dk(Pk).update(n).digest("hex");return new t(i)}};Fr.TransactionHash=da});var vE=v(vh=>{"use strict";l();Object.defineProperty(vh,"__esModule",{value:!0});vh.TransferTransactionsFactory=void 0;var mE=na(),Jr=xt(),Eh=Yr(),wE=Yn(),EE=class{constructor(e){this.gasEstimator=e}createEGLDTransfer(e){var r;let n=((r=e.data)===null||r===void 0?void 0:r.length())||0,i=this.gasEstimator.forEGLDTransfer(n);return new Eh.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||i,data:e.data,chainID:e.chainID})}createESDTTransfer(e){let{argumentsString:r}=new mE.ArgSerializer().valuesToString([Jr.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new Jr.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Eh.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){let{argumentsString:r}=new mE.ArgSerializer().valuesToString([Jr.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new Jr.U64Value(e.tokenTransfer.nonce),new Jr.BigUIntValue(e.tokenTransfer.valueOf()),new Jr.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Eh.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){let r=[new Jr.AddressValue(e.destination),new Jr.U16Value(e.tokenTransfers.length)];for(let u of e.tokenTransfers)r.push(Jr.BytesValue.fromUTF8(u.tokenIdentifier),new Jr.U64Value(u.nonce),new Jr.BigUIntValue(u.valueOf()));let{argumentsString:n}=new mE.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new wE.TransactionPayload(i),o=s.length()||0,a=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Eh.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||a,data:s,chainID:e.chainID})}};vh.TransferTransactionsFactory=EE});var bE=v(Vs=>{"use strict";l();Object.defineProperty(Vs,"__esModule",{value:!0});Vs.GasEstimator=Vs.DefaultGasConfiguration=void 0;Vs.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Rk=1e5,DN=8e5,AE=class{constructor(e){this.gasConfiguration=e||Vs.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Rk}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+DN}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+DN)*r+this.gasConfiguration.gasPerDataByte*e}};Vs.GasEstimator=AE});var ha=v(Ah=>{"use strict";l();Object.defineProperty(Ah,"__esModule",{value:!0});Ah.Account=void 0;var Bk=pt(),IE=class{constructor(e){this.address=new Bk.Address,this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};Ah.Account=IE});var pa=v(ks=>{"use strict";l();Object.defineProperty(ks,"__esModule",{value:!0});ks.Logger=ks.LogLevel=void 0;var Hs;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Hs=ks.LogLevel||(ks.LogLevel={}));var bh=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Hs.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Hs.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Hs.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Hs.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Hs.Error||console.error(e,r)}};ks.Logger=bh;bh.logLevel=Hs.Debug});var TE=v(_n=>{"use strict";l();var Lk=_n&&_n.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Fk=_n&&_n.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mk=_n&&_n.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lk(e,t,r);return Fk(e,t),e};Object.defineProperty(_n,"__esModule",{value:!0});_n.AsyncTimer=void 0;var Uk=Mk(Le()),qk=Le(),_E=pa(),SE=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new Uk.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,_E.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){_E.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new qk.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(_E.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};_n.AsyncTimer=SE});var Ih=v(ga=>{"use strict";l();var Mr=ga&&ga.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ga,"__esModule",{value:!0});ga.TransactionWatcher=void 0;var CE=TE(),Bi=Le(),PN=pa(),Li=class t{constructor(e,r={}){this.fetcher=new xE(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}awaitPending(e){return Mr(this,void 0,void 0,function*(){let r=s=>s.status.isPending(),n=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),i=()=>new Bi.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)})}awaitCompleted(e){return Mr(this,void 0,void 0,function*(){let r=s=>{if(s.isCompleted===void 0)throw new Bi.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),i=()=>new Bi.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)})}awaitAllEvents(e,r){return Mr(this,void 0,void 0,function*(){let n=o=>{let a=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>a.includes(c))},i=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),s=()=>new Bi.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)})}awaitAnyEvent(e,r){return Mr(this,void 0,void 0,function*(){let n=o=>{let a=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>a.includes(c))!=null},i=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),s=()=>new Bi.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)})}awaitOnCondition(e,r){return Mr(this,void 0,void 0,function*(){let n=()=>Mr(this,void 0,void 0,function*(){return yield this.fetcher.getTransaction(e.getHash().hex())}),i=()=>new Bi.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)})}awaitConditionally(e,r,n){return Mr(this,void 0,void 0,function*(){let i=new CE.AsyncTimer("watcher:periodic"),s=new CE.AsyncTimer("watcher:patience"),o=new CE.AsyncTimer("watcher:timeout"),a=!1,u,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),a=!0});!a;){yield i.start(this.pollingIntervalMilliseconds);try{if(u=yield r(),c=e(u),c||a)break}catch(f){if(PN.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Bi.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Bi.Err))throw f}}if(c&&(yield s.start(this.patienceMilliseconds)),o.isStopped()||o.stop(),!u||!c)throw n();return u})}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};ga.TransactionWatcher=Li;Li.DefaultPollingInterval=6e3;Li.DefaultTimeout=Li.DefaultPollingInterval*15;Li.DefaultPatience=0;Li.NoopOnStatusReceived=t=>{};var xE=class{constructor(e){this.fetcher=e}getTransaction(e){return Mr(this,void 0,void 0,function*(){return PN.Logger.debug(`transactionWatcher, getTransaction(${e})`),yield this.fetcher.getTransaction(e)})}}});var NE=v(_h=>{"use strict";l();Object.defineProperty(_h,"__esModule",{value:!0});_h.CodeMetadata=void 0;var Uc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBuffer(e){if(e.length<2)throw new Error("Buffer is too short.");let r=e[0],n=e[1],i=(r&t.ByteZero.Upgradeable)!==0,s=(r&t.ByteZero.Readable)!==0,o=(n&t.ByteOne.Payable)!==0,a=(n&t.ByteOne.PayableBySc)!==0;return new t(i,s,o,a)}toggleUpgradeable(e){this.upgradeable=e}toggleReadable(e){this.readable=e}togglePayable(e){this.payable=e}togglePayableBySc(e){this.payableBySc=e}toBuffer(){let e=0,r=0;return this.upgradeable&&(e|=t.ByteZero.Upgradeable),this.readable&&(e|=t.ByteZero.Readable),this.payable&&(r|=t.ByteOne.Payable),this.payableBySc&&(r|=t.ByteOne.PayableBySc),h.Buffer.from([e,r])}toString(){return this.toBuffer().toString("hex")}toJSON(){return{upgradeable:this.upgradeable,readable:this.readable,payable:this.payable,payableBySc:this.payableBySc}}equals(e){return this.upgradeable==e.upgradeable&&this.readable==e.readable&&this.payable==e.payable&&this.payableBySc==e.payableBySc}};_h.CodeMetadata=Uc;Uc.ByteZero={Upgradeable:1,Reserved2:2,Readable:4};Uc.ByteOne={Reserved1:1,Payable:2,PayableBySc:4}});var qc=v(Sn=>{"use strict";l();var Vk=Sn&&Sn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Hk=Sn&&Sn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),kk=Sn&&Sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Vk(e,t,r);return Hk(e,t),e};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.ContractFunction=void 0;var Gk=kk(Le()),OE=class t{constructor(e){if(this.name=e,e==null)throw new Gk.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Sn.ContractFunction=OE});var RE=v(Ur=>{"use strict";l();var jk=Ur&&Ur.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Qk=Ur&&Ur.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zk=Ur&&Ur.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&jk(e,t,r);return Qk(e,t),e},Wk=Ur&&Ur.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.InteractionChecker=void 0;var DE=zk(Le()),$k=Wk(Yt()),PE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new $k.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new DE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new DE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let a=0;a{"use strict";l();Object.defineProperty(Sh,"__esModule",{value:!0});Sh.Query=void 0;var Kk=pt(),Yk=na(),BE=class{constructor(e){this.caller=e.caller||new Kk.Address,this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new Yk.ArgSerializer().valuesToStrings(this.args)}};Sh.Query=BE});var UE=v(Th=>{"use strict";l();Object.defineProperty(Th,"__esModule",{value:!0});Th.Interaction=void 0;var RN=pt(),Jk=ah(),LE=Ns(),FE=qc(),Xk=RE(),Zk=Vc(),ya=xt(),ME=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=new RN.Address,this.sender=new RN.Address,this.isWithSingleESDTTransfer=!1,this.isWithSingleESDTNFTTransfer=!1,this.isWithMultiESDTNFTTransfer=!1,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=new ma([],this)}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers.getTransfers()}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){Jk.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=this.explicitReceiver||this.contract.getAddress(),r=this.function,n=this.args;this.isWithSingleESDTTransfer?(r=new FE.ContractFunction(LE.ESDT_TRANSFER_FUNCTION_NAME),n=this.tokenTransfers.buildArgsForSingleESDTTransfer()):this.isWithSingleESDTNFTTransfer?(e=this.sender,r=new FE.ContractFunction(LE.ESDTNFT_TRANSFER_FUNCTION_NAME),n=this.tokenTransfers.buildArgsForSingleESDTNFTTransfer()):this.isWithMultiESDTNFTTransfer&&(e=this.sender,r=new FE.ContractFunction(LE.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME),n=this.tokenTransfers.buildArgsForMultiESDTNFTTransfer());let i=this.contract.call({func:r,gasLimit:this.gasLimit,gasPrice:this.gasPrice,args:n,value:this.value,receiver:e,chainID:this.chainID,caller:this.sender});return i.setNonce(this.nonce),i}buildQuery(){return new Zk.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.isWithSingleESDTTransfer=!0,this.tokenTransfers=new ma([e],this),this}withSingleESDTNFTTransfer(e,r){return this.isWithSingleESDTNFTTransfer=!0,this.tokenTransfers=new ma([e],this),r&&(this.sender=r),this}withMultiESDTNFTTransfer(e,r){return this.isWithMultiESDTNFTTransfer=!0,this.tokenTransfers=new ma(e,this),r&&(this.sender=r),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new Xk.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};Th.Interaction=ME;var ma=class{constructor(e,r){this.transfers=e,this.interaction=r}getTransfers(){return this.transfers}buildArgsForSingleESDTTransfer(){let e=this.transfers[0];return[this.getTypedTokenIdentifier(e),this.getTypedTokenQuantity(e),this.getTypedInteractionFunction(),...this.getInteractionArguments()]}buildArgsForSingleESDTNFTTransfer(){let e=this.transfers[0];return[this.getTypedTokenIdentifier(e),this.getTypedTokenNonce(e),this.getTypedTokenQuantity(e),this.getTypedTokensReceiver(),this.getTypedInteractionFunction(),...this.getInteractionArguments()]}buildArgsForMultiESDTNFTTransfer(){let e=[];e.push(this.getTypedTokensReceiver()),e.push(this.getTypedNumberOfTransfers());for(let r of this.transfers)e.push(this.getTypedTokenIdentifier(r)),e.push(this.getTypedTokenNonce(r)),e.push(this.getTypedTokenQuantity(r));return e.push(this.getTypedInteractionFunction()),e.push(...this.getInteractionArguments()),e}getTypedNumberOfTransfers(){return new ya.U8Value(this.transfers.length)}getTypedTokenIdentifier(e){return ya.BytesValue.fromUTF8(e.tokenIdentifier)}getTypedTokenNonce(e){return new ya.U64Value(e.nonce)}getTypedTokenQuantity(e){return new ya.BigUIntValue(e.amountAsBigInteger)}getTypedTokensReceiver(){return new ya.AddressValue(this.interaction.getContractAddress())}getTypedInteractionFunction(){return ya.BytesValue.fromUTF8(this.interaction.getFunction().valueOf())}getInteractionArguments(){return this.interaction.getArguments()}}});var BN=v(Ch=>{"use strict";l();Object.defineProperty(Ch,"__esModule",{value:!0});Ch.ArgumentErrorContext=void 0;var eG=Le(),qE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new eG.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) -Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};Ch.ArgumentErrorContext=qE});var HE=v(Gs=>{"use strict";l();var tG=Gs&&Gs.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Gs,"__esModule",{value:!0});Gs.NativeSerializer=void 0;var rG=tG(Yt()),nG=pt(),VE=Le(),iG=Md(),sG=BN(),_e=xt(),oG;(function(t){function e(b,S){b=b||[],r(b,S),n(S)&&(b=i(b,S));let N=S.input,_=[];for(let T=0;T0&&S[0].type.getCardinality().isComposite()&&(_=1/0,T=!0);for(let B of S){if(B.type.getCardinality().isSingular())break;N-=1}return{min:N,max:_,variadic:T}}function o(b,S,N){if(b&&b.belongsToTypesystem)return b;if(S instanceof _e.OptionType)return a(b,S,N);if(S instanceof _e.OptionalType)return u(b,S,N);if(S instanceof _e.VariadicType)return c(b,S,N);if(S instanceof _e.CompositeType)return d(b,S,N);if(S instanceof _e.TupleType)return g(b,S,N);if(S instanceof _e.StructType)return m(b,S,N);if(S instanceof _e.ListType)return f(b,S,N);if(S instanceof _e.PrimitiveType)return y(b,S,N);if(S instanceof _e.EnumType)return A(b,S,N);N.throwError(`convertToTypedValue: unhandled type ${S}`)}function a(b,S,N){if(b==null)return _e.OptionValue.newMissing();let _=o(b,S.getFirstTypeParameter(),N);return _e.OptionValue.newProvided(_)}function u(b,S,N){if(b==null)return new _e.OptionalValue(S);let _=o(b,S.getFirstTypeParameter(),N);return new _e.OptionalValue(S,_)}function c(b,S,N){if(S.isCounted)throw new VE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');b==null&&(b=[]),b.map===void 0&&N.convertError(b,"Variadic");let _=b.map(function(T){return o(T,S.getFirstTypeParameter(),N)});return new _e.VariadicValue(S,_)}function f(b,S,N){b.map===void 0&&N.convertError(b,"List");let _=b.map(function(T){return o(T,S.getFirstTypeParameter(),N)});return new _e.List(S,_)}function d(b,S,N){let _=[],T=S.getTypeParameters();N.guardSameLength(b,T);for(let B=0;B{"use strict";l();Object.defineProperty(Xr,"__esModule",{value:!0});Xr.ContractCallPayloadBuilder=Xr.ContractUpgradePayloadBuilder=Xr.ContractDeployPayloadBuilder=Xr.ArwenVirtualMachine=void 0;var QE=Yn(),zE=br(),aG=na();Xr.ArwenVirtualMachine="0500";var kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${Xr.ArwenVirtualMachine}@${r}`;return n=WE(n,this.arguments),new QE.TransactionPayload(n)}};Xr.ContractDeployPayloadBuilder=kE;var GE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=WE(n,this.arguments),new QE.TransactionPayload(n)}};Xr.ContractUpgradePayloadBuilder=GE;var jE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=WE(e,this.arguments),new QE.TransactionPayload(e)}};Xr.ContractCallPayloadBuilder=jE;function WE(t,e){let{argumentsString:r,count:n}=new aG.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var ti=v((Zce,KE)=>{"use strict";l();var wa=typeof Reflect=="object"?Reflect:null,LN=wa&&typeof wa.apply=="function"?wa.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},xh;wa&&typeof wa.ownKeys=="function"?xh=wa.ownKeys:Object.getOwnPropertySymbols?xh=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:xh=function(e){return Object.getOwnPropertyNames(e)};function uG(t){console&&console.warn&&console.warn(t)}var MN=Number.isNaN||function(e){return e!==e};function We(){We.init.call(this)}KE.exports=We;KE.exports.once=dG;We.EventEmitter=We;We.prototype._events=void 0;We.prototype._eventsCount=0;We.prototype._maxListeners=void 0;var FN=10;function Nh(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(We,"defaultMaxListeners",{enumerable:!0,get:function(){return FN},set:function(t){if(typeof t!="number"||t<0||MN(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");FN=t}});We.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};We.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||MN(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function UN(t){return t._maxListeners===void 0?We.defaultMaxListeners:t._maxListeners}We.prototype.getMaxListeners=function(){return UN(this)};We.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=s[e];if(u===void 0)return!1;if(typeof u=="function")LN(u,this,r);else for(var c=u.length,f=GN(u,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,uG(a)}return t}We.prototype.addListener=function(e,r){return qN(this,e,r,!1)};We.prototype.on=We.prototype.addListener;We.prototype.prependListener=function(e,r){return qN(this,e,r,!0)};function cG(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function VN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=cG.bind(n);return i.listener=r,n.wrapFn=i,i}We.prototype.once=function(e,r){return Nh(r),this.on(e,VN(this,e,r)),this};We.prototype.prependOnceListener=function(e,r){return Nh(r),this.prependListener(e,VN(this,e,r)),this};We.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Nh(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():lG(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};We.prototype.off=We.prototype.removeListener;We.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function HN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?fG(i):GN(i,i.length)}We.prototype.listeners=function(e){return HN(this,e,!0)};We.prototype.rawListeners=function(e){return HN(this,e,!1)};We.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):kN.call(t,e)};We.prototype.listenerCount=kN;function kN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}We.prototype.eventNames=function(){return this._eventsCount>0?xh(this._events):[]};function GN(t,e){for(var r=new Array(e),n=0;n{l();QN.exports=ti().EventEmitter});var JE=v(()=>{l()});var JN=v((ole,YN)=>{"use strict";l();function zN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function WN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Oh.alloc(0);for(var n=Oh.allocUnsafe(r>>>0),i=this.head,s=0;i;)AG(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(a===o.length?s+=o:s+=o.slice(0,r),r-=a,r===0){a===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(a));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Oh.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,a=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,a),r-=a,r===0){a===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(a));break}++s}return this.length-=s,n}},{key:vG,value:function(r,n){return XE(this,WN(WN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var ev=v((ule,ZN)=>{"use strict";l();function bG(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,p.default.nextTick(ZE,this,t)):p.default.nextTick(ZE,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?p.default.nextTick(Dh,r):(r._writableState.errorEmitted=!0,p.default.nextTick(XN,r,s)):p.default.nextTick(XN,r,s):e?(p.default.nextTick(Dh,r),e(s)):p.default.nextTick(Dh,r)}),this)}function XN(t,e){ZE(t,e),Dh(t)}function Dh(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function IG(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function ZE(t,e){t.emit("error",e)}function _G(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}ZN.exports={destroy:bG,undestroy:IG,errorOrDestroy:_G}});var js=v((lle,rO)=>{"use strict";l();function SG(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var tO={};function qr(t,e,r){r||(r=Error);function n(s,o,a){return typeof e=="string"?e:e(s,o,a)}var i=function(s){SG(o,s);function o(a,u,c){return s.call(this,n(a,u,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,tO[t]=i}function eO(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function TG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function CG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function xG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}qr("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);qr("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&TG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(CG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(eO(e,"type"));else{var s=xG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(eO(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);qr("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");qr("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});qr("ERR_STREAM_PREMATURE_CLOSE","Premature close");qr("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});qr("ERR_MULTIPLE_CALLBACK","Callback called multiple times");qr("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");qr("ERR_STREAM_WRITE_AFTER_END","write after end");qr("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);qr("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);qr("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");rO.exports.codes=tO});var tv=v((dle,nO)=>{"use strict";l();var NG=js().codes.ERR_INVALID_OPT_VALUE;function OG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function DG(t,e,r,n){var i=OG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new NG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}nO.exports={getHighWaterMark:DG}});var Ea=v((ple,rv)=>{l();typeof Object.create=="function"?rv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:rv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var sO=v((yle,iO)=>{l();iO.exports=PG;function PG(t,e){if(nv("noDeprecation"))return t;var r=!1;function n(){if(!r){if(nv("throwDeprecation"))throw new Error(e);nv("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function nv(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var ov=v((wle,fO)=>{"use strict";l();fO.exports=gt;function aO(t){var e=this;this.next=null,this.entry=null,this.finish=function(){sj(e,t)}}var va;gt.WritableState=kc;var RG={deprecate:sO()},uO=YE(),Rh=qs().Buffer,BG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function LG(t){return Rh.from(t)}function FG(t){return Rh.isBuffer(t)||t instanceof BG}var sv=ev(),MG=tv(),UG=MG.getHighWaterMark,Fi=js().codes,qG=Fi.ERR_INVALID_ARG_TYPE,VG=Fi.ERR_METHOD_NOT_IMPLEMENTED,HG=Fi.ERR_MULTIPLE_CALLBACK,kG=Fi.ERR_STREAM_CANNOT_PIPE,GG=Fi.ERR_STREAM_DESTROYED,jG=Fi.ERR_STREAM_NULL_VALUES,QG=Fi.ERR_STREAM_WRITE_AFTER_END,zG=Fi.ERR_UNKNOWN_ENCODING,Aa=sv.errorOrDestroy;Ea()(gt,uO);function WG(){}function kc(t,e,r){va=va||Qs(),t=t||{},typeof r!="boolean"&&(r=e instanceof va),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=UG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){ej(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new aO(this)}kc.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(kc.prototype,"buffer",{get:RG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var Ph;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Ph=Function.prototype[Symbol.hasInstance],Object.defineProperty(gt,Symbol.hasInstance,{value:function(e){return Ph.call(this,e)?!0:this!==gt?!1:e&&e._writableState instanceof kc}})):Ph=function(e){return e instanceof this};function gt(t){va=va||Qs();var e=this instanceof va;if(!e&&!Ph.call(gt,this))return new gt(t);this._writableState=new kc(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),uO.call(this)}gt.prototype.pipe=function(){Aa(this,new kG)};function $G(t,e){var r=new QG;Aa(t,r),p.default.nextTick(e,r)}function KG(t,e,r,n){var i;return r===null?i=new jG:typeof r!="string"&&!e.objectMode&&(i=new qG("chunk",["string","Buffer"],r)),i?(Aa(t,i),p.default.nextTick(n,i),!1):!0}gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&FG(t);return s&&!Rh.isBuffer(t)&&(t=LG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=WG),n.ending?$G(this,r):(s||KG(this,n,t,r))&&(n.pendingcb++,i=JG(this,n,s,t,e,r)),i};gt.prototype.cork=function(){this._writableState.corked++};gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&cO(this,t))};gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new zG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function YG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=Rh.from(e,r)),e}Object.defineProperty(gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function JG(t,e,r,n,i,s){if(!r){var o=YG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var a=e.objectMode?1:n.length;e.length+=a;var u=e.length{"use strict";l();var oj=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};hO.exports=Tn;var dO=cv(),uv=ov();Ea()(Tn,dO);for(av=oj(uv.prototype),Bh=0;Bh{l();var Fh=qs(),Cn=Fh.Buffer;function pO(t,e){for(var r in t)e[r]=t[r]}Cn.from&&Cn.alloc&&Cn.allocUnsafe&&Cn.allocUnsafeSlow?gO.exports=Fh:(pO(Fh,lv),lv.Buffer=zs);function zs(t,e,r){return Cn(t,e,r)}zs.prototype=Object.create(Cn.prototype);pO(Cn,zs);zs.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Cn(t,e,r)};zs.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Cn(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};zs.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Cn(t)};zs.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fh.SlowBuffer(t)}});var hv=v(wO=>{"use strict";l();var dv=yO().Buffer,mO=dv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function cj(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function lj(t){var e=cj(t);if(typeof e!="string"&&(dv.isEncoding===mO||!mO(t)))throw new Error("Unknown encoding: "+t);return e||t}wO.StringDecoder=Gc;function Gc(t){this.encoding=lj(t);var e;switch(this.encoding){case"utf16le":this.text=yj,this.end=mj,e=4;break;case"utf8":this.fillLast=hj,e=4;break;case"base64":this.text=wj,this.end=Ej,e=3;break;default:this.write=vj,this.end=Aj;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=dv.allocUnsafe(e)}Gc.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function fj(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function dj(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function hj(t){var e=this.lastTotal-this.lastNeed,r=dj(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function pj(t,e){var r=fj(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function gj(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function yj(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function mj(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function wj(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Ej(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function vj(t){return t.toString(this.encoding)}function Aj(t){return t&&t.length?this.write(t):""}});var Mh=v((Sle,AO)=>{"use strict";l();var EO=js().codes.ERR_STREAM_PREMATURE_CLOSE;function bj(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";l();var Uh;function Mi(t,e,r){return e=Sj(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Sj(t){var e=Tj(t,"string");return typeof e=="symbol"?e:String(e)}function Tj(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Cj=Mh(),Ui=Symbol("lastResolve"),Ws=Symbol("lastReject"),jc=Symbol("error"),qh=Symbol("ended"),$s=Symbol("lastPromise"),pv=Symbol("handlePromise"),Ks=Symbol("stream");function qi(t,e){return{value:t,done:e}}function xj(t){var e=t[Ui];if(e!==null){var r=t[Ks].read();r!==null&&(t[$s]=null,t[Ui]=null,t[Ws]=null,e(qi(r,!1)))}}function Nj(t){p.default.nextTick(xj,t)}function Oj(t,e){return function(r,n){t.then(function(){if(e[qh]){r(qi(void 0,!0));return}e[pv](r,n)},n)}}var Dj=Object.getPrototypeOf(function(){}),Pj=Object.setPrototypeOf((Uh={get stream(){return this[Ks]},next:function(){var e=this,r=this[jc];if(r!==null)return Promise.reject(r);if(this[qh])return Promise.resolve(qi(void 0,!0));if(this[Ks].destroyed)return new Promise(function(o,a){p.default.nextTick(function(){e[jc]?a(e[jc]):o(qi(void 0,!0))})});var n=this[$s],i;if(n)i=new Promise(Oj(n,this));else{var s=this[Ks].read();if(s!==null)return Promise.resolve(qi(s,!1));i=new Promise(this[pv])}return this[$s]=i,i}},Mi(Uh,Symbol.asyncIterator,function(){return this}),Mi(Uh,"return",function(){var e=this;return new Promise(function(r,n){e[Ks].destroy(null,function(i){if(i){n(i);return}r(qi(void 0,!0))})})}),Uh),Dj),Rj=function(e){var r,n=Object.create(Pj,(r={},Mi(r,Ks,{value:e,writable:!0}),Mi(r,Ui,{value:null,writable:!0}),Mi(r,Ws,{value:null,writable:!0}),Mi(r,jc,{value:null,writable:!0}),Mi(r,qh,{value:e._readableState.endEmitted,writable:!0}),Mi(r,pv,{value:function(s,o){var a=n[Ks].read();a?(n[$s]=null,n[Ui]=null,n[Ws]=null,s(qi(a,!1))):(n[Ui]=s,n[Ws]=o)},writable:!0}),r));return n[$s]=null,Cj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Ws];s!==null&&(n[$s]=null,n[Ui]=null,n[Ws]=null,s(i)),n[jc]=i;return}var o=n[Ui];o!==null&&(n[$s]=null,n[Ui]=null,n[Ws]=null,o(qi(void 0,!0))),n[qh]=!0}),e.on("readable",Nj.bind(null,n)),n};bO.exports=Rj});var SO=v((Nle,_O)=>{l();_O.exports=function(){throw new Error("Readable.from is not available in the browser")}});var cv=v((Ple,LO)=>{"use strict";l();LO.exports=qe;var ba;qe.ReadableState=NO;var Dle=ti().EventEmitter,xO=function(e,r){return e.listeners(r).length},zc=YE(),Vh=qs().Buffer,Bj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function Lj(t){return Vh.from(t)}function Fj(t){return Vh.isBuffer(t)||t instanceof Bj}var gv=JE(),Ne;gv&&gv.debuglog?Ne=gv.debuglog("stream"):Ne=function(){};var Mj=JN(),bv=ev(),Uj=tv(),qj=Uj.getHighWaterMark,Hh=js().codes,Vj=Hh.ERR_INVALID_ARG_TYPE,Hj=Hh.ERR_STREAM_PUSH_AFTER_EOF,kj=Hh.ERR_METHOD_NOT_IMPLEMENTED,Gj=Hh.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Ia,yv,mv;Ea()(qe,zc);var Qc=bv.errorOrDestroy,wv=["error","close","destroy","pause","resume"];function jj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function NO(t,e,r){ba=ba||Qs(),t=t||{},typeof r!="boolean"&&(r=e instanceof ba),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=qj(this,t,"readableHighWaterMark",r),this.buffer=new Mj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Ia||(Ia=hv().StringDecoder),this.decoder=new Ia(t.encoding),this.encoding=t.encoding)}function qe(t){if(ba=ba||Qs(),!(this instanceof qe))return new qe(t);var e=this instanceof ba;this._readableState=new NO(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),zc.call(this)}Object.defineProperty(qe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});qe.prototype.destroy=bv.destroy;qe.prototype._undestroy=bv.undestroy;qe.prototype._destroy=function(t,e){e(t)};qe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=Vh.from(t,e),e=""),n=!0),OO(this,t,e,!1,n)};qe.prototype.unshift=function(t){return OO(this,t,null,!0,!1)};function OO(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Wj(t,s);else{var o;if(i||(o=Qj(s,e)),o)Qc(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==Vh.prototype&&(e=Lj(e)),n)s.endEmitted?Qc(t,new Gj):Ev(t,s,e,!0);else if(s.ended)Qc(t,new Hj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?Ev(t,s,e,!1):Av(t,s)):Ev(t,s,e,!1)}else n||(s.reading=!1,Av(t,s))}return!s.ended&&(s.length=TO?t=TO:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function CO(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=zj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}qe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?vv(this):kh(this),null;if(t=CO(t,e),t===0&&e.ended)return e.length===0&&vv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=RO(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&vv(this)),i!==null&&this.emit("data",i),i};function Wj(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?kh(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,DO(t)))}}function kh(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,p.default.nextTick(DO,t))}function DO(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,Iv(t)}function Av(t,e){e.readingMore||(e.readingMore=!0,p.default.nextTick($j,t,e))}function $j(t,e){for(;!e.reading&&!e.ended&&(e.length1&&BO(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function g(O){Ne("onerror",O),A(),t.removeListener("error",g),xO(t,"error")===0&&Qc(t,O)}jj(t,"error",g);function m(){t.removeListener("finish",y),A()}t.once("close",m);function y(){Ne("onfinish"),t.removeListener("close",m),A()}t.once("finish",y);function A(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Kj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&xO(t,"data")&&(r.flowing=!0,Iv(t))}}qe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?kh(this):n.reading||p.default.nextTick(Yj,this)),r};qe.prototype.addListener=qe.prototype.on;qe.prototype.removeListener=function(t,e){var r=zc.prototype.removeListener.call(this,t,e);return t==="readable"&&p.default.nextTick(PO,this),r};qe.prototype.removeAllListeners=function(t){var e=zc.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&p.default.nextTick(PO,this),e};function PO(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Yj(t){Ne("readable nexttick read 0"),t.read(0)}qe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Jj(this,t)),t.paused=!1,this};function Jj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,p.default.nextTick(Xj,t,e))}function Xj(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),Iv(t),e.flowing&&!e.reading&&t.read(0)}qe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Iv(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}qe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var a=e.push(o);a||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(a){return function(){return t[a].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function vv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,p.default.nextTick(Zj,e,t))}function Zj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(qe.from=function(t,e){return mv===void 0&&(mv=SO()),mv(qe,t,e)});function BO(t,e){for(var r=0,n=t.length;r{"use strict";l();MO.exports=ri;var Gh=js().codes,eQ=Gh.ERR_METHOD_NOT_IMPLEMENTED,tQ=Gh.ERR_MULTIPLE_CALLBACK,rQ=Gh.ERR_TRANSFORM_ALREADY_TRANSFORMING,nQ=Gh.ERR_TRANSFORM_WITH_LENGTH_0,jh=Qs();Ea()(ri,jh);function iQ(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new tQ);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";l();qO.exports=Wc;var UO=_v();Ea()(Wc,UO);function Wc(t){if(!(this instanceof Wc))return new Wc(t);UO.call(this,t)}Wc.prototype._transform=function(t,e,r){r(null,t)}});var QO=v((Ule,jO)=>{"use strict";l();var Sv;function oQ(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var GO=js().codes,aQ=GO.ERR_MISSING_ARGS,uQ=GO.ERR_STREAM_DESTROYED;function HO(t){if(t)throw t}function cQ(t){return t.setHeader&&typeof t.abort=="function"}function lQ(t,e,r,n){n=oQ(n);var i=!1;t.on("close",function(){i=!0}),Sv===void 0&&(Sv=Mh()),Sv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,cQ(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new uQ("pipe"))}}}function kO(t){t()}function fQ(t,e){return t.pipe(e)}function dQ(t){return!t.length||typeof t[t.length-1]!="function"?HO:t.pop()}function hQ(){for(var t=arguments.length,e=new Array(t),r=0;r0;return lQ(o,u,c,function(f){i||(i=f),f&&s.forEach(kO),!u&&(s.forEach(kO),n(i))})});return e.reduce(fQ)}jO.exports=hQ});var Tv=v((Vr,zO)=>{l();Vr=zO.exports=cv();Vr.Stream=Vr;Vr.Readable=Vr;Vr.Writable=ov();Vr.Duplex=Qs();Vr.Transform=_v();Vr.PassThrough=VO();Vr.finished=Mh();Vr.pipeline=QO()});var KO=v((Hle,$O)=>{l();var{Transform:pQ}=Tv();$O.exports=t=>class WO extends pQ{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!h.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return h.Buffer.isBuffer(r)||(r=h.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new WO(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var XO=v((Gle,JO)=>{l();var{Transform:gQ}=Tv();JO.exports=t=>class YO extends gQ{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!h.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return h.Buffer.isBuffer(r)||(r=h.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new YO(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var e2=v((Qle,ZO)=>{l();var yQ=KO(),mQ=XO();ZO.exports=function(t){let e=yQ(t),r=mQ(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var n2=v(r2=>{l();var t2=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];r2.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],a=t[5]^t[15]^t[25]^t[35]^t[45],u=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],g=f^(i<<1|s>>>31),m=d^(s<<1|i>>>31),y=t[0]^g,A=t[1]^m,O=t[10]^g,R=t[11]^m,q=t[20]^g,M=t[21]^m,b=t[30]^g,S=t[31]^m,N=t[40]^g,_=t[41]^m;g=r^(o<<1|a>>>31),m=n^(a<<1|o>>>31);let T=t[2]^g,B=t[3]^m,X=t[12]^g,z=t[13]^m,k=t[22]^g,Q=t[23]^m,K=t[32]^g,ye=t[33]^m,ce=t[42]^g,ie=t[43]^m;g=i^(u<<1|c>>>31),m=s^(c<<1|u>>>31);let J=t[4]^g,oe=t[5]^m,re=t[14]^g,se=t[15]^m,U=t[24]^g,fe=t[25]^m,ue=t[34]^g,de=t[35]^m,ae=t[44]^g,le=t[45]^m;g=o^(f<<1|d>>>31),m=a^(d<<1|f>>>31);let w=t[6]^g,E=t[7]^m,I=t[16]^g,P=t[17]^m,C=t[26]^g,D=t[27]^m,L=t[36]^g,x=t[37]^m,F=t[46]^g,G=t[47]^m;g=u^(r<<1|n>>>31),m=c^(n<<1|r>>>31);let V=t[8]^g,ee=t[9]^m,Ae=t[18]^g,Se=t[19]^m,Be=t[28]^g,it=t[29]^m,dt=t[38]^g,De=t[39]^m,Ve=t[48]^g,Lt=t[49]^m,wi=y,_s=A,Ss=R<<4|O>>>28,cr=O<<4|R>>>28,Qn=q<<3|M>>>29,Kt=M<<3|q>>>29,Ft=S<<9|b>>>23,Je=b<<9|S>>>23,s0=N<<18|_>>>14,o0=_<<18|N>>>14,a0=T<<1|B>>>31,u0=B<<1|T>>>31,c0=z<<12|X>>>20,l0=X<<12|z>>>20,f0=k<<10|Q>>>22,d0=Q<<10|k>>>22,h0=ye<<13|K>>>19,p0=K<<13|ye>>>19,g0=ce<<2|ie>>>30,y0=ie<<2|ce>>>30,m0=oe<<30|J>>>2,w0=J<<30|oe>>>2,E0=re<<6|se>>>26,v0=se<<6|re>>>26,A0=fe<<11|U>>>21,b0=U<<11|fe>>>21,I0=ue<<15|de>>>17,_0=de<<15|ue>>>17,S0=le<<29|ae>>>3,T0=ae<<29|le>>>3,C0=w<<28|E>>>4,x0=E<<28|w>>>4,N0=P<<23|I>>>9,O0=I<<23|P>>>9,D0=C<<25|D>>>7,P0=D<<25|C>>>7,R0=L<<21|x>>>11,B0=x<<21|L>>>11,L0=G<<24|F>>>8,F0=F<<24|G>>>8,M0=V<<27|ee>>>5,U0=ee<<27|V>>>5,q0=Ae<<20|Se>>>12,V0=Se<<20|Ae>>>12,H0=it<<7|Be>>>25,k0=Be<<7|it>>>25,G0=dt<<8|De>>>24,j0=De<<8|dt>>>24,Q0=Ve<<14|Lt>>>18,z0=Lt<<14|Ve>>>18;t[0]=wi^~c0&A0,t[1]=_s^~l0&b0,t[10]=C0^~q0&Qn,t[11]=x0^~V0&Kt,t[20]=a0^~E0&D0,t[21]=u0^~v0&P0,t[30]=M0^~Ss&f0,t[31]=U0^~cr&d0,t[40]=m0^~N0&H0,t[41]=w0^~O0&k0,t[2]=c0^~A0&R0,t[3]=l0^~b0&B0,t[12]=q0^~Qn&h0,t[13]=V0^~Kt&p0,t[22]=E0^~D0&G0,t[23]=v0^~P0&j0,t[32]=Ss^~f0&I0,t[33]=cr^~d0&_0,t[42]=N0^~H0&Ft,t[43]=O0^~k0&Je,t[4]=A0^~R0&Q0,t[5]=b0^~B0&z0,t[14]=Qn^~h0&S0,t[15]=Kt^~p0&T0,t[24]=D0^~G0&s0,t[25]=P0^~j0&o0,t[34]=f0^~I0&L0,t[35]=d0^~_0&F0,t[44]=H0^~Ft&g0,t[45]=k0^~Je&y0,t[6]=R0^~Q0&wi,t[7]=B0^~z0&_s,t[16]=h0^~S0&C0,t[17]=p0^~T0&x0,t[26]=G0^~s0&a0,t[27]=j0^~o0&u0,t[36]=I0^~L0&M0,t[37]=_0^~F0&U0,t[46]=Ft^~g0&m0,t[47]=Je^~y0&w0,t[8]=Q0^~wi&c0,t[9]=z0^~_s&l0,t[18]=S0^~C0&q0,t[19]=T0^~x0&V0,t[28]=s0^~a0&E0,t[29]=o0^~u0&v0,t[38]=L0^~M0&Ss,t[39]=F0^~U0&cr,t[48]=g0^~m0&N0,t[49]=y0^~w0&O0,t[0]^=t2[e*2],t[1]^=t2[e*2+1]}}});var s2=v((Kle,i2)=>{l();var Qh=n2();function _a(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}_a.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};_a.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(Qh.p1600(this.state),this.count=0);return e};_a.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};i2.exports=_a});var Cv=v((Jle,o2)=>{l();o2.exports=e2()(s2())});var Dv=v(Sa=>{"use strict";l();var wQ=Sa&&Sa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Sa,"__esModule",{value:!0});Sa.SmartContract=void 0;var EQ=wQ(Yt()),$c=pt(),xv=ah(),vQ=Le(),Nv=Yr(),AQ=br(),bQ=Tc(),a2=NE(),u2=qc(),c2=UE(),IQ=HE(),_Q=Vc(),zh=$E(),SQ=Cv(),Ov=class{constructor(e={}){this.address=new $c.Address,this.methodsExplicit={},this.methods={},this.address=e.address||new $c.Address,this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new u2.ContractFunction(i);return new c2.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new u2.ContractFunction(i),a=IQ.NativeSerializer.nativeToTypedValues(s||[],n);return new c2.Interaction(e,o,a||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return AQ.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:a,chainID:u}){xv.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()"),n=n||new a2.CodeMetadata,i=i||[],s=s||0;let c=new zh.ContractDeployPayloadBuilder().setCode(r).setCodeMetadata(n).setInitArgs(i).build();return new Nv.Transaction({receiver:$c.Address.Zero(),sender:e,value:s,gasLimit:o,gasPrice:a,data:c,chainID:u})}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:a,chainID:u}){xv.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress(),n=n||new a2.CodeMetadata,i=i||[],s=s||0;let c=new zh.ContractUpgradePayloadBuilder().setCode(r).setCodeMetadata(n).setInitArgs(i).build();return new Nv.Transaction({sender:e,receiver:this.getAddress(),value:s,gasLimit:o,gasPrice:a,data:c,chainID:u})}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:a,caller:u}){xv.Compatibility.guardAddressIsSetAndNonZero(u,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress(),r=r||[],n=n||0;let c=new zh.ContractCallPayloadBuilder().setFunction(e).setArgs(r).build();return new Nv.Transaction({sender:u,receiver:s||this.getAddress(),value:n,gasLimit:i,gasPrice:o,data:c,chainID:a})}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new _Q.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new vQ.ErrContractHasNoAddress}static computeAddress(e,r){let n=h.Buffer.alloc(8,0),i=new $c.Address(e.bech32()).pubkey(),s=i.slice(30),o=h.Buffer.alloc(8),a=new EQ.default(r.valueOf().toString(10)),u=bQ.bigIntToBuffer(a);o.write(u.reverse().toString("hex"),"hex");let c=h.Buffer.concat([i,o]),f=SQ("keccak256").update(c).digest(),d=h.Buffer.from(zh.ArwenVirtualMachine,"hex"),g=h.Buffer.concat([n,d,f.slice(10,30),s]);return new $c.Address(g)}};Sa.SmartContract=Ov});var Wh=v(Ys=>{"use strict";l();Object.defineProperty(Ys,"__esModule",{value:!0});Ys.SignableMessage=Ys.MESSAGE_PREFIX=void 0;var TQ=pt(),CQ=Rc(),xQ=Cv();Ys.MESSAGE_PREFIX=`Elrond Signed Message: -`;var Pv=class{constructor(e){this.message=h.Buffer.from([]),this.signature=h.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=new TQ.Address,Object.assign(this,e)}serializeForSigning(){let e=h.Buffer.from(this.message.length.toString()),r=h.Buffer.concat([e,this.message]),n=h.Buffer.concat([h.Buffer.from(Ys.MESSAGE_PREFIX),r]);return xQ("keccak256").update(n).digest()}serializeForSigningRaw(){return h.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=CQ.interpretSignatureAsBuffer(e)}getMessageSize(){let e=h.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};Ys.SignableMessage=Pv});var Rv=v(l2=>{"use strict";l();Object.defineProperty(l2,"__esModule",{value:!0})});var Ta=v(Ht=>{"use strict";l();var NQ=Ht&&Ht.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),OQ=Ht&&Ht.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),DQ=Ht&&Ht.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&NQ(e,t,r);return OQ(e,t),e};Object.defineProperty(Ht,"__esModule",{value:!0});Ht.zeroPadStringIfOddLength=Ht.isPaddedHex=Ht.numberToPaddedHex=Ht.Nonce=Ht.Address=void 0;var f2=DQ(tw()),PQ="erd",Bv=class t{constructor(e){this.value=e}static fromPubkey(e){let r=f2.toWords(e),n=f2.encode(PQ,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};Ht.Address=Bv;var Lv=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return d2(this.value)}};Ht.Nonce=Lv;function d2(t){let e=t.toString(16);return h2(e)}Ht.numberToPaddedHex=d2;function RQ(t){t=t||"";let e=h.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Ht.isPaddedHex=RQ;function h2(t){return t=t||"",t.length%2==1?"0"+t:t}Ht.zeroPadStringIfOddLength=h2});var p2=v(Vi=>{"use strict";l();var BQ=Vi&&Vi.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vi,"__esModule",{value:!0});Vi.EsdtContractAddress=Vi.MaxUint64AsBigNumber=void 0;var LQ=BQ(Yt()),FQ=Ta();Vi.MaxUint64AsBigNumber=new LQ.default("18446744073709551615");Vi.EsdtContractAddress=new FQ.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var Mv=v(Ca=>{"use strict";l();var MQ=Ca&&Ca.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ca,"__esModule",{value:!0});Ca.ContractQueryResponse=void 0;var UQ=MQ(Yt()),qQ=p2(),Fv=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new UQ.default(e.gasRemaining||e.GasRemaining||0),o=qQ.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>h.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Ca.ContractQueryResponse=Fv});var g2=v(Hi=>{"use strict";l();Object.defineProperty(Hi,"__esModule",{value:!0});Hi.ErrAccountNotConnected=Hi.ErrCannotSignSingleTransaction=Hi.Err=void 0;var Kc=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Hi.Err=Kc;var Uv=class extends Kc{constructor(){super("Cannot sign single transaction.")}};Hi.ErrCannotSignSingleTransaction=Uv;var qv=class extends Kc{constructor(){super("Account is not connected.")}};Hi.ErrAccountNotConnected=qv});var y2=v(Yc=>{"use strict";l();Object.defineProperty(Yc,"__esModule",{value:!0});Yc.Operation=void 0;var VQ;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(VQ=Yc.Operation||(Yc.Operation={}))});var Vv=v(xa=>{"use strict";l();var ki=xa&&xa.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(xa,"__esModule",{value:!0});xa.ExtensionProvider=void 0;var HQ=Yr(),m2=g2(),Jc=y2(),Xc=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return ki(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return ki(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(Jc.Operation.Connect,n),this.account.address})}logout(){return ki(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(Jc.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return ki(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return ki(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return ki(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new m2.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new m2.ErrAccountNotConnected}signTransactions(e){return ki(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(Jc.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>HQ.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return ki(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(Jc.Operation.SignMessage,r)).signature,s=h.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(Jc.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};xa.ExtensionProvider=Xc;Xc._instance=new Xc});function QQ(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){zQ(t);return}return e}function zQ(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Zc(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.at(-1)==='"'&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!jQ.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(kQ.test(t)||GQ.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,QQ)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var kQ,GQ,jQ,b2=he(()=>{l();kQ=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,GQ=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,jQ=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function WQ(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Mt(t,...e){try{return WQ(t(...e))}catch(r){return Promise.reject(r)}}function $Q(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function KQ(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function el(t){if($Q(t))return String(t);if(KQ(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return el(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function I2(){if(typeof h.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function _2(t){if(typeof t=="string")return t;I2();let e=h.Buffer.from(t).toString("base64");return Hv+e}function S2(t){return typeof t!="string"||!t.startsWith(Hv)?t:(I2(),h.Buffer.from(t.slice(Hv.length),"base64"))}function ir(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function T2(...t){return ir(t.join(":"))}function tl(t){return t=ir(t),t?t+":":""}var Hv,C2=he(()=>{l();Hv="base64:"});function O2(t={}){let e={mounts:{"":t.driver||JQ()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=ir(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await x2(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},a=(c,f,d)=>{let g=new Map,m=y=>{let A=g.get(y.base);return A||(A={driver:y.driver,base:y.base,items:[]},g.set(y.base,A)),A};for(let y of c){let A=typeof y=="string",O=ir(A?y:y.key),R=A?void 0:y.value,q=A||!y.options?f:{...f,...y.options},M=r(O);m(M).items.push({key:O,value:R,relativeKey:M.relativeKey,options:q})}return Promise.all([...g.values()].map(y=>d(y))).then(y=>y.flat())},u={hasItem(c,f={}){c=ir(c);let{relativeKey:d,driver:g}=r(c);return Mt(g.hasItem,d,f)},getItem(c,f={}){c=ir(c);let{relativeKey:d,driver:g}=r(c);return Mt(g.getItem,d,f).then(m=>Zc(m))},getItems(c,f){return a(c,f,d=>d.driver.getItems?Mt(d.driver.getItems,d.items.map(g=>({key:g.relativeKey,options:g.options})),f).then(g=>g.map(m=>({key:T2(d.base,m.key),value:Zc(m.value)}))):Promise.all(d.items.map(g=>Mt(d.driver.getItem,g.relativeKey,g.options).then(m=>({key:g.key,value:Zc(m)})))))},getItemRaw(c,f={}){c=ir(c);let{relativeKey:d,driver:g}=r(c);return g.getItemRaw?Mt(g.getItemRaw,d,f):Mt(g.getItem,d,f).then(m=>S2(m))},async setItem(c,f,d={}){if(f===void 0)return u.removeItem(c);c=ir(c);let{relativeKey:g,driver:m}=r(c);m.setItem&&(await Mt(m.setItem,g,el(f),d),m.watch||i("update",c))},async setItems(c,f){await a(c,f,async d=>{d.driver.setItems&&await Mt(d.driver.setItems,d.items.map(g=>({key:g.relativeKey,value:el(g.value),options:g.options})),f),d.driver.setItem&&await Promise.all(d.items.map(g=>Mt(d.driver.setItem,g.relativeKey,el(g.value),g.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return u.removeItem(c,d);c=ir(c);let{relativeKey:g,driver:m}=r(c);if(m.setItemRaw)await Mt(m.setItemRaw,g,f,d);else if(m.setItem)await Mt(m.setItem,g,_2(f),d);else return;m.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=ir(c);let{relativeKey:d,driver:g}=r(c);g.removeItem&&(await Mt(g.removeItem,d,f),(f.removeMeta||f.removeMata)&&await Mt(g.removeItem,d+"$",f),g.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=ir(c);let{relativeKey:d,driver:g}=r(c),m=Object.create(null);if(g.getMeta&&Object.assign(m,await Mt(g.getMeta,d,f)),!f.nativeOnly){let y=await Mt(g.getItem,d+"$",f).then(A=>Zc(A));y&&typeof y=="object"&&(typeof y.atime=="string"&&(y.atime=new Date(y.atime)),typeof y.mtime=="string"&&(y.mtime=new Date(y.mtime)),Object.assign(m,y))}return m},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=tl(c);let d=n(c,!0),g=[],m=[];for(let y of d){let O=(await Mt(y.driver.getKeys,y.relativeBase,f)).map(R=>y.mountpoint+ir(R)).filter(R=>!g.some(q=>R.startsWith(q)));m.push(...O),g=[y.mountpoint,...g.filter(R=>!R.startsWith(y.mountpoint))]}return c?m.filter(y=>y.startsWith(c)&&!y.endsWith("$")):m.filter(y=>!y.endsWith("$"))},async clear(c,f={}){c=tl(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return Mt(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let g=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(g.map(m=>d.driver.removeItem(m,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>N2(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=tl(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,g)=>g.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(x2(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),u},async unmount(c,f=!0){c=tl(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await N2(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=ir(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=ir(c),n(c,f.parents).map(g=>({driver:g.driver,base:g.mountpoint}))}};return u}function x2(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function N2(t){typeof t.dispose=="function"&&await Mt(t.dispose)}var YQ,JQ,D2=he(()=>{l();b2();C2();YQ="memory",JQ=()=>{let t=new Map;return{name:YQ,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function Js(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Gv(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=Js(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function rl(){return kv||(kv=Gv("keyval-store","keyval")),kv}function jv(t,e=rl()){return e("readonly",r=>Js(r.get(t)))}function P2(t,e,r=rl()){return r("readwrite",n=>(n.put(e,t),Js(n.transaction)))}function R2(t,e=rl()){return e("readwrite",r=>(r.delete(t),Js(r.transaction)))}function B2(t=rl()){return t("readwrite",e=>(e.clear(),Js(e.transaction)))}function XQ(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Js(t.transaction)}function L2(t=rl()){return t("readonly",e=>{if(e.getAllKeys)return Js(e.getAllKeys());let r=[];return XQ(e,n=>r.push(n.key)).then(()=>r)})}var kv,F2=he(()=>{l()});var M2={};ft(M2,{safeJsonParse:()=>ji,safeJsonStringify:()=>Qi});function ji(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return e7(t)}catch{return t}}function Qi(t){return typeof t=="string"?t:ZQ(t)||""}var ZQ,e7,nl=he(()=>{l();ZQ=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),e7=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var q2={};ft(q2,{KeyValueStorage:()=>$v,default:()=>$v});function s7(t){var e;return[t[0],ji((e=t[1])!=null?e:"")]}var t7,r7,n7,i7,zv,Qv,Jh,Wv,o7,U2,a7,u7,$v,V2=he(()=>{l();D2();F2();nl();t7="idb-keyval",r7=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Gv(t.dbName,t.storeName)),{name:t7,options:t,async hasItem(i){return!(typeof await jv(r(i),n)>"u")},async getItem(i){return await jv(r(i),n)??null},setItem(i,s){return P2(r(i),s,n)},removeItem(i){return R2(r(i),n)},getKeys(){return L2(n)},clear(){return B2(n)}}},n7="WALLET_CONNECT_V2_INDEXED_DB",i7="keyvaluestorage",zv=class{constructor(){this.indexedDb=O2({driver:r7({dbName:n7,storeName:i7})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Qi(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Qv=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Jh={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Qv<"u"&&Qv.localStorage?Jh.exports=Qv.localStorage:typeof window<"u"&&window.localStorage?Jh.exports=window.localStorage:Jh.exports=new e})();Wv=class{constructor(){this.localStorage=Jh.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(s7)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return ji(r)}async setItem(e,r){this.localStorage.setItem(e,Qi(r))}async removeItem(e){this.localStorage.removeItem(e)}},o7="wc_storage_version",U2=1,a7=async(t,e,r)=>{let n=o7,i=await e.getItem(n);if(i&&i>=U2){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let a=s.shift();if(!a)continue;let u=a.toLowerCase();if(u.includes("wc@")||u.includes("walletconnect")||u.includes("wc_")||u.includes("wallet_connect")){let c=await t.getItem(a);await e.setItem(a,c),o.push(a)}}await e.setItem(n,U2),r(e),u7(t,o)},u7=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},$v=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new Wv;this.storage=e;try{let r=new zv;a7(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zr={};ft(Zr,{__assign:()=>Yv,__asyncDelegator:()=>A7,__asyncGenerator:()=>v7,__asyncValues:()=>b7,__await:()=>il,__awaiter:()=>p7,__classPrivateFieldGet:()=>T7,__classPrivateFieldSet:()=>C7,__createBinding:()=>y7,__decorate:()=>f7,__exportStar:()=>m7,__extends:()=>c7,__generator:()=>g7,__importDefault:()=>S7,__importStar:()=>_7,__makeTemplateObject:()=>I7,__metadata:()=>h7,__param:()=>d7,__read:()=>H2,__rest:()=>l7,__spread:()=>w7,__spreadArrays:()=>E7,__values:()=>Jv});function c7(t,e){Kv(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function l7(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function d7(t,e){return function(r,n){e(r,n,t)}}function h7(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function p7(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})}function g7(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(f){return u([c,f])}}function u(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function H2(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function w7(){for(var t=[],e=0;e1||a(g,m)})})}function a(g,m){try{u(n[g](m))}catch(y){d(s[0][3],y)}}function u(g){g.value instanceof il?Promise.resolve(g.value.v).then(c,f):d(s[0][2],g)}function c(g){a("next",g)}function f(g){a("throw",g)}function d(g,m){g(m),s.shift(),s.length&&a(s[0][0],s[0][1])}}function A7(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:il(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function b7(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Jv=="function"?Jv(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,u){o=t[s](o),i(a,u,o.done,o.value)})}}function i(s,o,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a})},o)}}function I7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function _7(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function S7(t){return t&&t.__esModule?t:{default:t}}function T7(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function C7(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Kv,Yv,en=he(()=>{l();Kv=function(t,e){return Kv=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Kv(t,e)};Yv=function(){return Yv=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";l();Object.defineProperty(Xh,"__esModule",{value:!0});Xh.delay=void 0;function x7(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}Xh.delay=x7});var G2=v(Na=>{"use strict";l();Object.defineProperty(Na,"__esModule",{value:!0});Na.ONE_THOUSAND=Na.ONE_HUNDRED=void 0;Na.ONE_HUNDRED=100;Na.ONE_THOUSAND=1e3});var j2=v(ge=>{"use strict";l();Object.defineProperty(ge,"__esModule",{value:!0});ge.ONE_YEAR=ge.FOUR_WEEKS=ge.THREE_WEEKS=ge.TWO_WEEKS=ge.ONE_WEEK=ge.THIRTY_DAYS=ge.SEVEN_DAYS=ge.FIVE_DAYS=ge.THREE_DAYS=ge.ONE_DAY=ge.TWENTY_FOUR_HOURS=ge.TWELVE_HOURS=ge.SIX_HOURS=ge.THREE_HOURS=ge.ONE_HOUR=ge.SIXTY_MINUTES=ge.THIRTY_MINUTES=ge.TEN_MINUTES=ge.FIVE_MINUTES=ge.ONE_MINUTE=ge.SIXTY_SECONDS=ge.THIRTY_SECONDS=ge.TEN_SECONDS=ge.FIVE_SECONDS=ge.ONE_SECOND=void 0;ge.ONE_SECOND=1;ge.FIVE_SECONDS=5;ge.TEN_SECONDS=10;ge.THIRTY_SECONDS=30;ge.SIXTY_SECONDS=60;ge.ONE_MINUTE=ge.SIXTY_SECONDS;ge.FIVE_MINUTES=ge.ONE_MINUTE*5;ge.TEN_MINUTES=ge.ONE_MINUTE*10;ge.THIRTY_MINUTES=ge.ONE_MINUTE*30;ge.SIXTY_MINUTES=ge.ONE_MINUTE*60;ge.ONE_HOUR=ge.SIXTY_MINUTES;ge.THREE_HOURS=ge.ONE_HOUR*3;ge.SIX_HOURS=ge.ONE_HOUR*6;ge.TWELVE_HOURS=ge.ONE_HOUR*12;ge.TWENTY_FOUR_HOURS=ge.ONE_HOUR*24;ge.ONE_DAY=ge.TWENTY_FOUR_HOURS;ge.THREE_DAYS=ge.ONE_DAY*3;ge.FIVE_DAYS=ge.ONE_DAY*5;ge.SEVEN_DAYS=ge.ONE_DAY*7;ge.THIRTY_DAYS=ge.ONE_DAY*30;ge.ONE_WEEK=ge.SEVEN_DAYS;ge.TWO_WEEKS=ge.ONE_WEEK*2;ge.THREE_WEEKS=ge.ONE_WEEK*3;ge.FOUR_WEEKS=ge.ONE_WEEK*4;ge.ONE_YEAR=ge.ONE_DAY*365});var Xv=v(Zh=>{"use strict";l();Object.defineProperty(Zh,"__esModule",{value:!0});var Q2=(en(),ht(Zr));Q2.__exportStar(G2(),Zh);Q2.__exportStar(j2(),Zh)});var W2=v(Oa=>{"use strict";l();Object.defineProperty(Oa,"__esModule",{value:!0});Oa.fromMiliseconds=Oa.toMiliseconds=void 0;var z2=Xv();function N7(t){return t*z2.ONE_THOUSAND}Oa.toMiliseconds=N7;function O7(t){return Math.floor(t/z2.ONE_THOUSAND)}Oa.fromMiliseconds=O7});var K2=v(ep=>{"use strict";l();Object.defineProperty(ep,"__esModule",{value:!0});var $2=(en(),ht(Zr));$2.__exportStar(k2(),ep);$2.__exportStar(W2(),ep)});var Y2=v(sl=>{"use strict";l();Object.defineProperty(sl,"__esModule",{value:!0});sl.Watch=void 0;var tp=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};sl.Watch=tp;sl.default=tp});var J2=v(rp=>{"use strict";l();Object.defineProperty(rp,"__esModule",{value:!0});rp.IWatch=void 0;var Zv=class{};rp.IWatch=Zv});var X2=v(e1=>{"use strict";l();Object.defineProperty(e1,"__esModule",{value:!0});var D7=(en(),ht(Zr));D7.__exportStar(J2(),e1)});var Xs=v(Da=>{"use strict";l();Object.defineProperty(Da,"__esModule",{value:!0});var np=(en(),ht(Zr));np.__exportStar(K2(),Da);np.__exportStar(Y2(),Da);np.__exportStar(X2(),Da);np.__exportStar(Xv(),Da)});var t1,Z2=he(()=>{l();t1=class{}});var r1={};ft(r1,{IEvents:()=>t1});var n1=he(()=>{l();Z2()});var eD=v(ip=>{"use strict";l();Object.defineProperty(ip,"__esModule",{value:!0});ip.IHeartBeat=void 0;var P7=(n1(),ht(r1)),i1=class extends P7.IEvents{constructor(e){super()}};ip.IHeartBeat=i1});var o1=v(s1=>{"use strict";l();Object.defineProperty(s1,"__esModule",{value:!0});var R7=(en(),ht(Zr));R7.__exportStar(eD(),s1)});var tD=v(Pa=>{"use strict";l();Object.defineProperty(Pa,"__esModule",{value:!0});Pa.HEARTBEAT_EVENTS=Pa.HEARTBEAT_INTERVAL=void 0;var B7=Xs();Pa.HEARTBEAT_INTERVAL=B7.FIVE_SECONDS;Pa.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var u1=v(a1=>{"use strict";l();Object.defineProperty(a1,"__esModule",{value:!0});var L7=(en(),ht(Zr));L7.__exportStar(tD(),a1)});var rD=v(sp=>{"use strict";l();Object.defineProperty(sp,"__esModule",{value:!0});sp.HeartBeat=void 0;var c1=(en(),ht(Zr)),F7=ti(),M7=Xs(),U7=o1(),l1=u1(),f1=class t extends U7.IHeartBeat{constructor(e){super(e),this.events=new F7.EventEmitter,this.interval=l1.HEARTBEAT_INTERVAL,this.interval=e?.interval||l1.HEARTBEAT_INTERVAL}static init(e){return c1.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return c1.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return c1.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),M7.toMiliseconds(this.interval))})}pulse(){this.events.emit(l1.HEARTBEAT_EVENTS.pulse)}};sp.HeartBeat=f1});var nD=v(ol=>{"use strict";l();Object.defineProperty(ol,"__esModule",{value:!0});var d1=(en(),ht(Zr));d1.__exportStar(rD(),ol);d1.__exportStar(o1(),ol);d1.__exportStar(u1(),ol)});var sD=v((Ide,iD)=>{"use strict";l();function q7(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}iD.exports=V7;function V7(t,e,r){var n=r&&r.stringify||q7,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var a=1;a-1?d:0,t.charCodeAt(m+1)){case 100:case 102:if(f>=u||e[f]==null)break;d=u||e[f]==null)break;d=u||e[f]===void 0)break;d",d=m+2,m++;break}c+=n(e[f]),d=m+2,m++;break;case 115:if(f>=u)break;d{"use strict";l();var oD=sD();cD.exports=xn;var al=Y7().console||{},H7={mapHttpRequest:op,mapHttpResponse:op,wrapRequestSerializer:h1,wrapResponseSerializer:h1,wrapErrorSerializer:h1,req:op,res:op,err:z7};function k7(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function xn(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||al;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=k7(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let a=t.level||"info",u=Object.create(r);u.log||(u.log=ul),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:d,set:g});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:W7(t)};u.levels=xn.levels,u.level=a,u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=ul,u.serializers=n,u._serialize=i,u._stdErrSerialize=s,u.child=m,e&&(u._logEvent=p1());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function g(y){if(y!=="silent"&&!this.levels.values[y])throw Error("unknown level "+y);this._level=y,Ra(c,u,"error","log"),Ra(c,u,"fatal","error"),Ra(c,u,"warn","error"),Ra(c,u,"info","log"),Ra(c,u,"debug","log"),Ra(c,u,"trace","log")}function m(y,A){if(!y)throw new Error("missing bindings for child Pino");A=A||{},i&&y.serializers&&(A.serializers=y.serializers);let O=A.serializers;if(i&&O){var R=Object.assign({},n,O),q=t.browser.serialize===!0?Object.keys(R):i;delete y.serializers,ap([y],q,R,this._stdErrSerialize)}function M(b){this._childLevel=(b._childLevel|0)+1,this.error=Ba(b,y,"error"),this.fatal=Ba(b,y,"fatal"),this.warn=Ba(b,y,"warn"),this.info=Ba(b,y,"info"),this.debug=Ba(b,y,"debug"),this.trace=Ba(b,y,"trace"),R&&(this.serializers=R,this._serialize=q),e&&(this._logEvent=p1([].concat(b._logEvent.bindings,y)))}return M.prototype=this,new M(this)}return u}xn.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};xn.stdSerializers=H7;xn.stdTimeFunctions=Object.assign({},{nullTime:aD,epochTime:uD,unixTime:$7,isoTime:K7});function Ra(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?ul:i[r]?i[r]:al[r]||al[n]||ul,G7(t,e,r)}function G7(t,e,r){!t.transmit&&e[r]===ul||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===al?al:this;for(var u=0;u-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Ba(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;i{"use strict";l();Object.defineProperty(La,"__esModule",{value:!0});La.PINO_CUSTOM_CONTEXT_KEY=La.PINO_LOGGER_DEFAULTS=void 0;La.PINO_LOGGER_DEFAULTS={level:"info"};La.PINO_CUSTOM_CONTEXT_KEY="custom_context"});var gD=v(mr=>{"use strict";l();Object.defineProperty(mr,"__esModule",{value:!0});mr.generateChildLogger=mr.formatChildLoggerContext=mr.getLoggerContext=mr.setBrowserLoggerContext=mr.getBrowserLoggerContext=mr.getDefaultLoggerOptions=void 0;var Fa=g1();function J7(t){return Object.assign(Object.assign({},t),{level:t?.level||Fa.PINO_LOGGER_DEFAULTS.level})}mr.getDefaultLoggerOptions=J7;function fD(t,e=Fa.PINO_CUSTOM_CONTEXT_KEY){return t[e]||""}mr.getBrowserLoggerContext=fD;function dD(t,e,r=Fa.PINO_CUSTOM_CONTEXT_KEY){return t[r]=e,t}mr.setBrowserLoggerContext=dD;function hD(t,e=Fa.PINO_CUSTOM_CONTEXT_KEY){let r="";return typeof t.bindings>"u"?r=fD(t,e):r=t.bindings().context||"",r}mr.getLoggerContext=hD;function pD(t,e,r=Fa.PINO_CUSTOM_CONTEXT_KEY){let n=hD(t,r);return n.trim()?`${n}/${e}`:e}mr.formatChildLoggerContext=pD;function X7(t,e,r=Fa.PINO_CUSTOM_CONTEXT_KEY){let n=pD(t,e,r),i=t.child({context:n});return dD(i,n,r)}mr.generateChildLogger=X7});var m1=v(Ma=>{"use strict";l();Object.defineProperty(Ma,"__esModule",{value:!0});Ma.pino=void 0;var y1=(en(),ht(Zr)),Z7=y1.__importDefault(lD());Object.defineProperty(Ma,"pino",{enumerable:!0,get:function(){return Z7.default}});y1.__exportStar(g1(),Ma);y1.__exportStar(gD(),Ma)});var F1=v(Ot=>{"use strict";l();Object.defineProperty(Ot,"__esModule",{value:!0});var Ua=(n1(),ht(r1)),yD=ti();function e9(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var t9=e9(yD),w1=class extends Ua.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},E1=class{constructor(e,r,n){this.core=e,this.logger=r}},v1=class extends Ua.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},A1=class{constructor(e,r){this.logger=e,this.core=r}},b1=class extends Ua.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},I1=class extends Ua.IEvents{constructor(e){super()}},_1=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},S1=class{constructor(){this.map=new Map}},T1=class extends Ua.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},C1=class{constructor(e,r){this.core=e,this.logger=r}},x1=class extends Ua.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},N1=class{constructor(e,r){this.logger=e,this.core=r}},O1=class{constructor(e,r){this.projectId=e,this.logger=r}},D1=class{constructor(e,r){this.projectId=e,this.logger=r}},P1=class extends t9.default{constructor(){super()}},R1=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},B1=class extends yD.EventEmitter{constructor(){super()}},L1=class{constructor(e){this.client=e}};Ot.ICore=w1,Ot.ICrypto=E1,Ot.IEchoClient=D1,Ot.IEngine=L1,Ot.IEngineEvents=B1,Ot.IExpirer=x1,Ot.IJsonRpcHistory=v1,Ot.IKeyChain=C1,Ot.IMessageTracker=A1,Ot.IPairing=N1,Ot.IPublisher=b1,Ot.IRelayer=I1,Ot.ISignClient=R1,Ot.ISignClientEvents=P1,Ot.IStore=_1,Ot.ISubscriber=T1,Ot.ISubscriberTopicMap=S1,Ot.IVerify=O1});var wD=v(up=>{"use strict";l();Object.defineProperty(up,"__esModule",{value:!0});up.BrowserRandomSource=void 0;var mD=65536,M1=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";l();Object.defineProperty(U1,"__esModule",{value:!0});function r9(t){for(var e=0;e{l()});var vD=v(cp=>{"use strict";l();Object.defineProperty(cp,"__esModule",{value:!0});cp.NodeRandomSource=void 0;var n9=Hr(),q1=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof TS<"u"){let e=ED();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";l();Object.defineProperty(lp,"__esModule",{value:!0});lp.SystemRandomSource=void 0;var i9=wD(),s9=vD(),V1=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new i9.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new s9.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};lp.SystemRandomSource=V1});var bD=v(Ir=>{"use strict";l();Object.defineProperty(Ir,"__esModule",{value:!0});function o9(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}Ir.mul=Math.imul||o9;function a9(t,e){return t+e|0}Ir.add=a9;function u9(t,e){return t-e|0}Ir.sub=u9;function c9(t,e){return t<>>32-e}Ir.rotl=c9;function l9(t,e){return t<<32-e|t>>>e}Ir.rotr=l9;function f9(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}Ir.isInteger=Number.isInteger||f9;Ir.MAX_SAFE_INTEGER=9007199254740991;Ir.isSafeInteger=function(t){return Ir.isInteger(t)&&t>=-Ir.MAX_SAFE_INTEGER&&t<=Ir.MAX_SAFE_INTEGER}});var qa=v(Oe=>{"use strict";l();Object.defineProperty(Oe,"__esModule",{value:!0});var ID=bD();function d9(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}Oe.readInt16BE=d9;function h9(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}Oe.readUint16BE=h9;function p9(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}Oe.readInt16LE=p9;function g9(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}Oe.readUint16LE=g9;function _D(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}Oe.writeUint16BE=_D;Oe.writeInt16BE=_D;function SD(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}Oe.writeUint16LE=SD;Oe.writeInt16LE=SD;function H1(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}Oe.readInt32BE=H1;function k1(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}Oe.readUint32BE=k1;function G1(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}Oe.readInt32LE=G1;function j1(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}Oe.readUint32LE=j1;function fp(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}Oe.writeUint32BE=fp;Oe.writeInt32BE=fp;function dp(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}Oe.writeUint32LE=dp;Oe.writeInt32LE=dp;function y9(t,e){e===void 0&&(e=0);var r=H1(t,e),n=H1(t,e+4);return r*4294967296+n-(n>>31)*4294967296}Oe.readInt64BE=y9;function m9(t,e){e===void 0&&(e=0);var r=k1(t,e),n=k1(t,e+4);return r*4294967296+n}Oe.readUint64BE=m9;function w9(t,e){e===void 0&&(e=0);var r=G1(t,e),n=G1(t,e+4);return n*4294967296+r-(r>>31)*4294967296}Oe.readInt64LE=w9;function E9(t,e){e===void 0&&(e=0);var r=j1(t,e),n=j1(t,e+4);return n*4294967296+r}Oe.readUint64LE=E9;function TD(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),fp(t/4294967296>>>0,e,r),fp(t>>>0,e,r+4),e}Oe.writeUint64BE=TD;Oe.writeInt64BE=TD;function CD(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),dp(t>>>0,e,r),dp(t/4294967296>>>0,e,r+4),e}Oe.writeUint64LE=CD;Oe.writeInt64LE=CD;function v9(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}Oe.readUintBE=v9;function A9(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}Oe.writeUintBE=b9;function I9(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!ID.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";l();Object.defineProperty(er,"__esModule",{value:!0});er.randomStringForEntropy=er.randomString=er.randomUint32=er.randomBytes=er.defaultRandomSource=void 0;var P9=AD(),R9=qa(),xD=Hr();er.defaultRandomSource=new P9.SystemRandomSource;function Q1(t,e=er.defaultRandomSource){return e.randomBytes(t)}er.randomBytes=Q1;function B9(t=er.defaultRandomSource){let e=Q1(4,t),r=(0,R9.readUint32LE)(e);return(0,xD.wipe)(e),r}er.randomUint32=B9;var ND="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function OD(t,e=ND,r=er.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=Q1(Math.ceil(t*256/s),r);for(let a=0;a0;a++){let u=o[a];u{"use strict";l();Object.defineProperty(ni,"__esModule",{value:!0});var Ha=qa(),Va=Hr();ni.DIGEST_LENGTH=64;ni.BLOCK_SIZE=128;var PD=function(){function t(){this.digestLength=ni.DIGEST_LENGTH,this.blockSize=ni.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Va.wipe(this._buffer),Va.wipe(this._tempHi),Va.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(z1(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=z1(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var a=n+1;a0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Va.wipe(e.stateHi),Va.wipe(e.stateLo),e.buffer&&Va.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();ni.SHA512=PD;var DD=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function z1(t,e,r,n,i,s,o){for(var a=r[0],u=r[1],c=r[2],f=r[3],d=r[4],g=r[5],m=r[6],y=r[7],A=n[0],O=n[1],R=n[2],q=n[3],M=n[4],b=n[5],S=n[6],N=n[7],_,T,B,X,z,k,Q,K;o>=128;){for(var ye=0;ye<16;ye++){var ce=8*ye+s;t[ye]=Ha.readUint32BE(i,ce),e[ye]=Ha.readUint32BE(i,ce+4)}for(var ye=0;ye<80;ye++){var ie=a,J=u,oe=c,re=f,se=d,U=g,fe=m,ue=y,de=A,ae=O,le=R,w=q,E=M,I=b,P=S,C=N;if(_=y,T=N,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=(d>>>14|M<<18)^(d>>>18|M<<14)^(M>>>9|d<<23),T=(M>>>14|d<<18)^(M>>>18|d<<14)^(d>>>9|M<<23),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=d&g^~d&m,T=M&b^~M&S,z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=DD[ye*2],T=DD[ye*2+1],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=t[ye%16],T=e[ye%16],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,B=Q&65535|K<<16,X=z&65535|k<<16,_=B,T=X,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=(a>>>28|A<<4)^(A>>>2|a<<30)^(A>>>7|a<<25),T=(A>>>28|a<<4)^(a>>>2|A<<30)^(a>>>7|A<<25),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,_=a&u^a&c^u&c,T=A&O^A&R^O&R,z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,ue=Q&65535|K<<16,C=z&65535|k<<16,_=re,T=w,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=B,T=X,z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,re=Q&65535|K<<16,w=z&65535|k<<16,u=ie,c=J,f=oe,d=re,g=se,m=U,y=fe,a=ue,O=de,R=ae,q=le,M=w,b=E,S=I,N=P,A=C,ye%16===15)for(var ce=0;ce<16;ce++)_=t[ce],T=e[ce],z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=t[(ce+9)%16],T=e[(ce+9)%16],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,B=t[(ce+1)%16],X=e[(ce+1)%16],_=(B>>>1|X<<31)^(B>>>8|X<<24)^B>>>7,T=(X>>>1|B<<31)^(X>>>8|B<<24)^(X>>>7|B<<25),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,B=t[(ce+14)%16],X=e[(ce+14)%16],_=(B>>>19|X<<13)^(X>>>29|B<<3)^B>>>6,T=(X>>>19|B<<13)^(B>>>29|X<<3)^(X>>>6|B<<26),z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,t[ce]=Q&65535|K<<16,e[ce]=z&65535|k<<16}_=a,T=A,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[0],T=n[0],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[0]=a=Q&65535|K<<16,n[0]=A=z&65535|k<<16,_=u,T=O,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[1],T=n[1],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[1]=u=Q&65535|K<<16,n[1]=O=z&65535|k<<16,_=c,T=R,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[2],T=n[2],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[2]=c=Q&65535|K<<16,n[2]=R=z&65535|k<<16,_=f,T=q,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[3],T=n[3],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[3]=f=Q&65535|K<<16,n[3]=q=z&65535|k<<16,_=d,T=M,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[4],T=n[4],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[4]=d=Q&65535|K<<16,n[4]=M=z&65535|k<<16,_=g,T=b,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[5],T=n[5],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[5]=g=Q&65535|K<<16,n[5]=b=z&65535|k<<16,_=m,T=S,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[6],T=n[6],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[6]=m=Q&65535|K<<16,n[6]=S=z&65535|k<<16,_=y,T=N,z=T&65535,k=T>>>16,Q=_&65535,K=_>>>16,_=r[7],T=n[7],z+=T&65535,k+=T>>>16,Q+=_&65535,K+=_>>>16,k+=z>>>16,Q+=k>>>16,K+=Q>>>16,r[7]=y=Q&65535|K<<16,n[7]=N=z&65535|k<<16,s+=128,o-=128}return s}function F9(t){var e=new PD;e.update(t);var r=e.digest();return e.clean(),r}ni.hash=F9});var WD=v(ke=>{"use strict";l();Object.defineProperty(ke,"__esModule",{value:!0});ke.convertSecretKeyToX25519=ke.convertPublicKeyToX25519=ke.verify=ke.sign=ke.extractPublicKeyFromSecretKey=ke.generateKeyPair=ke.generateKeyPairFromSeed=ke.SEED_LENGTH=ke.SECRET_KEY_LENGTH=ke.PUBLIC_KEY_LENGTH=ke.SIGNATURE_LENGTH=void 0;var M9=cl(),ll=RD(),UD=Hr();ke.SIGNATURE_LENGTH=64;ke.PUBLIC_KEY_LENGTH=32;ke.SECRET_KEY_LENGTH=64;ke.SEED_LENGTH=32;function Te(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,qD(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function VD(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function FD(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return fl(r,t),fl(n,e),VD(r,n)}function HD(t){let e=new Uint8Array(32);return fl(e,t),e[0]&1}function k9(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Zs(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function to(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function $e(t,e,r){let n,i,s=0,o=0,a=0,u=0,c=0,f=0,d=0,g=0,m=0,y=0,A=0,O=0,R=0,q=0,M=0,b=0,S=0,N=0,_=0,T=0,B=0,X=0,z=0,k=0,Q=0,K=0,ye=0,ce=0,ie=0,J=0,oe=0,re=r[0],se=r[1],U=r[2],fe=r[3],ue=r[4],de=r[5],ae=r[6],le=r[7],w=r[8],E=r[9],I=r[10],P=r[11],C=r[12],D=r[13],L=r[14],x=r[15];n=e[0],s+=n*re,o+=n*se,a+=n*U,u+=n*fe,c+=n*ue,f+=n*de,d+=n*ae,g+=n*le,m+=n*w,y+=n*E,A+=n*I,O+=n*P,R+=n*C,q+=n*D,M+=n*L,b+=n*x,n=e[1],o+=n*re,a+=n*se,u+=n*U,c+=n*fe,f+=n*ue,d+=n*de,g+=n*ae,m+=n*le,y+=n*w,A+=n*E,O+=n*I,R+=n*P,q+=n*C,M+=n*D,b+=n*L,S+=n*x,n=e[2],a+=n*re,u+=n*se,c+=n*U,f+=n*fe,d+=n*ue,g+=n*de,m+=n*ae,y+=n*le,A+=n*w,O+=n*E,R+=n*I,q+=n*P,M+=n*C,b+=n*D,S+=n*L,N+=n*x,n=e[3],u+=n*re,c+=n*se,f+=n*U,d+=n*fe,g+=n*ue,m+=n*de,y+=n*ae,A+=n*le,O+=n*w,R+=n*E,q+=n*I,M+=n*P,b+=n*C,S+=n*D,N+=n*L,_+=n*x,n=e[4],c+=n*re,f+=n*se,d+=n*U,g+=n*fe,m+=n*ue,y+=n*de,A+=n*ae,O+=n*le,R+=n*w,q+=n*E,M+=n*I,b+=n*P,S+=n*C,N+=n*D,_+=n*L,T+=n*x,n=e[5],f+=n*re,d+=n*se,g+=n*U,m+=n*fe,y+=n*ue,A+=n*de,O+=n*ae,R+=n*le,q+=n*w,M+=n*E,b+=n*I,S+=n*P,N+=n*C,_+=n*D,T+=n*L,B+=n*x,n=e[6],d+=n*re,g+=n*se,m+=n*U,y+=n*fe,A+=n*ue,O+=n*de,R+=n*ae,q+=n*le,M+=n*w,b+=n*E,S+=n*I,N+=n*P,_+=n*C,T+=n*D,B+=n*L,X+=n*x,n=e[7],g+=n*re,m+=n*se,y+=n*U,A+=n*fe,O+=n*ue,R+=n*de,q+=n*ae,M+=n*le,b+=n*w,S+=n*E,N+=n*I,_+=n*P,T+=n*C,B+=n*D,X+=n*L,z+=n*x,n=e[8],m+=n*re,y+=n*se,A+=n*U,O+=n*fe,R+=n*ue,q+=n*de,M+=n*ae,b+=n*le,S+=n*w,N+=n*E,_+=n*I,T+=n*P,B+=n*C,X+=n*D,z+=n*L,k+=n*x,n=e[9],y+=n*re,A+=n*se,O+=n*U,R+=n*fe,q+=n*ue,M+=n*de,b+=n*ae,S+=n*le,N+=n*w,_+=n*E,T+=n*I,B+=n*P,X+=n*C,z+=n*D,k+=n*L,Q+=n*x,n=e[10],A+=n*re,O+=n*se,R+=n*U,q+=n*fe,M+=n*ue,b+=n*de,S+=n*ae,N+=n*le,_+=n*w,T+=n*E,B+=n*I,X+=n*P,z+=n*C,k+=n*D,Q+=n*L,K+=n*x,n=e[11],O+=n*re,R+=n*se,q+=n*U,M+=n*fe,b+=n*ue,S+=n*de,N+=n*ae,_+=n*le,T+=n*w,B+=n*E,X+=n*I,z+=n*P,k+=n*C,Q+=n*D,K+=n*L,ye+=n*x,n=e[12],R+=n*re,q+=n*se,M+=n*U,b+=n*fe,S+=n*ue,N+=n*de,_+=n*ae,T+=n*le,B+=n*w,X+=n*E,z+=n*I,k+=n*P,Q+=n*C,K+=n*D,ye+=n*L,ce+=n*x,n=e[13],q+=n*re,M+=n*se,b+=n*U,S+=n*fe,N+=n*ue,_+=n*de,T+=n*ae,B+=n*le,X+=n*w,z+=n*E,k+=n*I,Q+=n*P,K+=n*C,ye+=n*D,ce+=n*L,ie+=n*x,n=e[14],M+=n*re,b+=n*se,S+=n*U,N+=n*fe,_+=n*ue,T+=n*de,B+=n*ae,X+=n*le,z+=n*w,k+=n*E,Q+=n*I,K+=n*P,ye+=n*C,ce+=n*D,ie+=n*L,J+=n*x,n=e[15],b+=n*re,S+=n*se,N+=n*U,_+=n*fe,T+=n*ue,B+=n*de,X+=n*ae,z+=n*le,k+=n*w,Q+=n*E,K+=n*I,ye+=n*P,ce+=n*C,ie+=n*D,J+=n*L,oe+=n*x,s+=38*S,o+=38*N,a+=38*_,u+=38*T,c+=38*B,f+=38*X,d+=38*z,g+=38*k,m+=38*Q,y+=38*K,A+=38*ye,O+=38*ce,R+=38*ie,q+=38*J,M+=38*oe,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=a,t[3]=u,t[4]=c,t[5]=f,t[6]=d,t[7]=g,t[8]=m,t[9]=y,t[10]=A,t[11]=O,t[12]=R,t[13]=q,t[14]=M,t[15]=b}function eo(t,e){$e(t,e,e)}function kD(t,e){let r=Te(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)eo(r,r),n!==2&&n!==4&&$e(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function G9(t,e){let r=Te(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)eo(r,r),n!==1&&$e(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function Y1(t,e){let r=Te(),n=Te(),i=Te(),s=Te(),o=Te(),a=Te(),u=Te(),c=Te(),f=Te();to(r,t[1],t[0]),to(f,e[1],e[0]),$e(r,r,f),Zs(n,t[0],t[1]),Zs(f,e[0],e[1]),$e(n,n,f),$e(i,t[3],e[3]),$e(i,i,V9),$e(s,t[2],e[2]),Zs(s,s,s),to(o,n,r),to(a,s,i),Zs(u,s,i),Zs(c,n,r),$e(t[0],o,a),$e(t[1],c,u),$e(t[2],u,a),$e(t[3],o,c)}function MD(t,e,r){for(let n=0;n<4;n++)qD(t[n],e[n],r)}function X1(t,e){let r=Te(),n=Te(),i=Te();kD(i,e[2]),$e(r,e[0],i),$e(n,e[1],i),fl(t,n),t[31]^=HD(r)<<7}function GD(t,e,r){zi(t[0],K1),zi(t[1],ka),zi(t[2],ka),zi(t[3],K1);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;MD(t,e,i),Y1(e,t),Y1(t,t),MD(t,e,i)}}function Z1(t,e){let r=[Te(),Te(),Te(),Te()];zi(r[0],BD),zi(r[1],LD),zi(r[2],ka),$e(r[3],BD,LD),GD(t,r,e)}function jD(t){if(t.length!==ke.SEED_LENGTH)throw new Error(`ed25519: seed must be ${ke.SEED_LENGTH} bytes`);let e=(0,ll.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[Te(),Te(),Te(),Te()];Z1(n,e),X1(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}ke.generateKeyPairFromSeed=jD;function j9(t){let e=(0,M9.randomBytes)(32,t),r=jD(e);return(0,UD.wipe)(e),r}ke.generateKeyPair=j9;function Q9(t){if(t.length!==ke.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${ke.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}ke.extractPublicKeyFromSecretKey=Q9;var $1=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function QD(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*$1[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*$1[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function J1(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;QD(t,e)}function z9(t,e){let r=new Float64Array(64),n=[Te(),Te(),Te(),Te()],i=(0,ll.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new ll.SHA512;o.update(s.subarray(32)),o.update(e);let a=o.digest();o.clean(),J1(a),Z1(n,a),X1(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let u=o.digest();J1(u);for(let c=0;c<32;c++)r[c]=a[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=u[c]*i[f];return QD(s.subarray(32),r),s}ke.sign=z9;function zD(t,e){let r=Te(),n=Te(),i=Te(),s=Te(),o=Te(),a=Te(),u=Te();return zi(t[2],ka),k9(t[1],e),eo(i,t[1]),$e(s,i,q9),to(i,i,t[2]),Zs(s,t[2],s),eo(o,s),eo(a,o),$e(u,a,o),$e(r,u,i),$e(r,r,s),G9(r,r),$e(r,r,i),$e(r,r,s),$e(r,r,s),$e(t[0],r,s),eo(n,t[0]),$e(n,n,s),FD(n,i)&&$e(t[0],t[0],H9),eo(n,t[0]),$e(n,n,s),FD(n,i)?-1:(HD(t[0])===e[31]>>7&&to(t[0],K1,t[0]),$e(t[3],t[0],t[1]),0)}function W9(t,e,r){let n=new Uint8Array(32),i=[Te(),Te(),Te(),Te()],s=[Te(),Te(),Te(),Te()];if(r.length!==ke.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${ke.SIGNATURE_LENGTH} bytes`);if(zD(s,t))return!1;let o=new ll.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let a=o.digest();return J1(a),GD(i,s,a),Z1(s,r.subarray(32)),Y1(i,s),X1(n,i),!VD(r,n)}ke.verify=W9;function $9(t){let e=[Te(),Te(),Te(),Te()];if(zD(e,t))throw new Error("Ed25519: invalid public key");let r=Te(),n=Te(),i=e[1];Zs(r,ka,i),to(n,ka,i),kD(n,n),$e(r,r,n);let s=new Uint8Array(32);return fl(s,r),s}ke.convertPublicKeyToX25519=$9;function K9(t){let e=(0,ll.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,UD.wipe)(e),r}ke.convertSecretKeyToX25519=K9});var hp,pp,ro,Ga,gp,dl,yp,mp,wp,ja,Ep,vp,$D,KD,Ap=he(()=>{l();hp="EdDSA",pp="JWT",ro=".",Ga="base64url",gp="utf8",dl="utf8",yp=":",mp="did",wp="key",ja="base58btc",Ep="z",vp="K36",$D=32,KD=32});function Wi(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var hl=he(()=>{l()});function Qa(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Wi(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var bp=he(()=>{l();hl()});function Ip(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=Qa(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Wi(r)}var eA=he(()=>{l();bp();hl()});function Y9(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,b=new Uint8Array(M);R!==q;){for(var S=y[R],N=0,_=M-1;(S!==0||N>>0,b[_]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");O=N,R++}for(var T=M-O;T!==M&&b[T]===0;)T++;for(var B=u.repeat(A);T>>0,M=new Uint8Array(q);y[A];){var b=r[y.charCodeAt(A)];if(b===255)return;for(var S=0,N=q-1;(b!==0||S>>0,M[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");R=S,A++}if(y[A]!==" "){for(var _=q-R;_!==q&&M[_]===0;)_++;for(var T=new Uint8Array(O+(q-_)),B=O;_!==q;)T[B++]=M[_++];return T}}}function m(y){var A=g(y);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:g,decode:m}}var J9,X9,YD,JD=he(()=>{l();J9=Y9,X9=J9,YD=X9});var yhe,XD,ii,ZD,eP,$i=he(()=>{l();yhe=new Uint8Array(0),XD=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},ZD=t=>new TextEncoder().encode(t),eP=t=>new TextDecoder().decode(t)});var tA,rA,nA,rP,iA,za,Ki,Z9,ez,yt,tn=he(()=>{l();JD();$i();tA=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},rA=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rP(this,e)}},nA=class{constructor(e){this.decoders=e}or(e){return rP(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},rP=(t,e)=>new nA({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),iA=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new tA(e,r,n),this.decoder=new rA(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},za=({name:t,prefix:e,encode:r,decode:n})=>new iA(t,e,r,n),Ki=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=YD(r,e);return za({prefix:t,name:e,encode:n,decode:s=>ii(i(s))})},Z9=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(a-=8,o[c++]=255&u>>a)}if(a>=r||255&u<<8-a)throw new SyntaxError("Unexpected end of data");return o},ez=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<za({prefix:e,name:t,encode(i){return ez(i,n,r)},decode(i){return Z9(i,n,r,t)}})});var sA={};ft(sA,{identity:()=>tz});var tz,nP=he(()=>{l();tn();$i();tz=za({prefix:"\0",name:"identity",encode:t=>eP(t),decode:t=>ZD(t)})});var oA={};ft(oA,{base2:()=>rz});var rz,iP=he(()=>{l();tn();rz=yt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var aA={};ft(aA,{base8:()=>nz});var nz,sP=he(()=>{l();tn();nz=yt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var uA={};ft(uA,{base10:()=>iz});var iz,oP=he(()=>{l();tn();iz=Ki({prefix:"9",name:"base10",alphabet:"0123456789"})});var cA={};ft(cA,{base16:()=>sz,base16upper:()=>oz});var sz,oz,aP=he(()=>{l();tn();sz=yt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oz=yt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var lA={};ft(lA,{base32:()=>Wa,base32hex:()=>lz,base32hexpad:()=>dz,base32hexpadupper:()=>hz,base32hexupper:()=>fz,base32pad:()=>uz,base32padupper:()=>cz,base32upper:()=>az,base32z:()=>pz});var Wa,az,uz,cz,lz,fz,dz,hz,pz,fA=he(()=>{l();tn();Wa=yt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),az=yt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),uz=yt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cz=yt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lz=yt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fz=yt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dz=yt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hz=yt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pz=yt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var dA={};ft(dA,{base36:()=>gz,base36upper:()=>yz});var gz,yz,uP=he(()=>{l();tn();gz=Ki({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yz=Ki({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var hA={};ft(hA,{base58btc:()=>Nn,base58flickr:()=>mz});var Nn,mz,pA=he(()=>{l();tn();Nn=Ki({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mz=Ki({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var gA={};ft(gA,{base64:()=>wz,base64pad:()=>Ez,base64url:()=>vz,base64urlpad:()=>Az});var wz,Ez,vz,Az,cP=he(()=>{l();tn();wz=yt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ez=yt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vz=yt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Az=yt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var yA={};ft(yA,{base256emoji:()=>Tz});function _z(t){return t.reduce((e,r)=>(e+=bz[r],e),"")}function Sz(t){let e=[];for(let r of t){let n=Iz[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var lP,bz,Iz,Tz,fP=he(()=>{l();tn();lP=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),bz=lP.reduce((t,e,r)=>(t[r]=e,t),[]),Iz=lP.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);Tz=za({prefix:"\u{1F680}",name:"base256emoji",encode:_z,decode:Sz})});function pP(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Oz;)e[r++]=t&255|dP,t/=128;for(;t&Nz;)e[r++]=t&255|dP,t>>>=7;return e[r]=t|0,pP.bytes=r-n+1,e}function mA(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw mA.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&hP)<=Pz);return mA.bytes=s-n,r}var Cz,dP,xz,Nz,Oz,Dz,Pz,hP,Rz,Bz,Lz,Fz,Mz,Uz,qz,Vz,Hz,kz,Gz,jz,pl,gP=he(()=>{l();Cz=pP,dP=128,xz=127,Nz=~xz,Oz=Math.pow(2,31);Dz=mA,Pz=128,hP=127;Rz=Math.pow(2,7),Bz=Math.pow(2,14),Lz=Math.pow(2,21),Fz=Math.pow(2,28),Mz=Math.pow(2,35),Uz=Math.pow(2,42),qz=Math.pow(2,49),Vz=Math.pow(2,56),Hz=Math.pow(2,63),kz=function(t){return t{l();gP();gl=(t,e=0)=>[pl.decode(t,e),pl.decode.bytes],$a=(t,e,r=0)=>(pl.encode(t,e,r),e),Ka=t=>pl.encodingLength(t)});var no,yP,mP,Ya,ml=he(()=>{l();$i();Sp();no=(t,e)=>{let r=e.byteLength,n=Ka(t),i=n+Ka(r),s=new Uint8Array(i+r);return $a(t,s,0),$a(r,s,n),s.set(e,i),new Ya(t,r,e,s)},yP=t=>{let e=ii(t),[r,n]=gl(e),[i,s]=gl(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Ya(r,i,o,e)},mP=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&XD(t.bytes,e.bytes),Ya=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var EA,wA,vA=he(()=>{l();ml();EA=({name:t,code:e,encode:r})=>new wA(t,e,r),wA=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?no(this.code,r):r.then(n=>no(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var AA={};ft(AA,{sha256:()=>Qz,sha512:()=>zz});var EP,Qz,zz,vP=he(()=>{l();vA();EP=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Qz=EA({name:"sha2-256",code:18,encode:EP("SHA-256")}),zz=EA({name:"sha2-512",code:19,encode:EP("SHA-512")})});var bA={};ft(bA,{identity:()=>Kz});var AP,Wz,bP,$z,Kz,IP=he(()=>{l();$i();ml();AP=0,Wz="identity",bP=ii,$z=t=>no(AP,bP(t)),Kz={code:AP,name:Wz,encode:bP,digest:$z}});var _P=he(()=>{l();$i()});var rpe,npe,SP=he(()=>{l();rpe=new TextEncoder,npe=new TextDecoder});var xp,Xz,Zz,eW,wl,tW,TP,CP,Tp,Cp,rW,nW,iW,xP=he(()=>{l();Sp();ml();pA();fA();$i();xp=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Cp,byteLength:Cp,code:Tp,version:Tp,multihash:Tp,bytes:Tp,_baseCache:Cp,asCID:Cp})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==wl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==tW)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=no(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&mP(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return Zz(r,i,e||Nn.encoder);default:return eW(r,i,e||Wa.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return nW(/^0\.0/,iW),!!(e&&(e[CP]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||TP(r,n,i.bytes))}else if(e!=null&&e[CP]===!0){let{version:r,multihash:n,code:i}=e,s=yP(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==wl)throw new Error(`Version 0 CID must use dag-pb (code: ${wl}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=TP(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,wl,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=ii(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new Ya(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,g]=gl(e.subarray(r));return r+=g,d},i=n(),s=wl;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),u=n(),c=r+u,f=c-o;return{version:i,codec:s,multihashCode:a,digestSize:u,multihashSize:f,size:c}}static parse(e,r){let[n,i]=Xz(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},Xz=(t,e)=>{switch(t[0]){case"Q":{let r=e||Nn;return[Nn.prefix,r.decode(`${Nn.prefix}${t}`)]}case Nn.prefix:{let r=e||Nn;return[Nn.prefix,r.decode(t)]}case Wa.prefix:{let r=e||Wa;return[Wa.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Zz=(t,e,r)=>{let{prefix:n}=r;if(n!==Nn.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},eW=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},wl=112,tW=18,TP=(t,e,r)=>{let n=Ka(t),i=n+Ka(e),s=new Uint8Array(i+r.byteLength);return $a(t,s,0),$a(e,s,n),s.set(r,i),s},CP=Symbol.for("@ipld/js-cid/CID"),Tp={writable:!1,configurable:!1,enumerable:!0},Cp={writable:!1,enumerable:!1,configurable:!1},rW="0.0.0-dev",nW=(t,e)=>{if(t.test(rW))console.warn(e);else throw new Error(e)},iW=`CID.isCID(v) is deprecated and will be removed in the next major release. +`); + } + }; + exports2.ErrContractHasNoAddress = ErrContractHasNoAddress; + var ErrMock = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrMock = ErrMock; + var ErrTypingSystem = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrTypingSystem = ErrTypingSystem; + var ErrMissingFieldOnStruct = class extends Err { + constructor(fieldName, structName) { + super(`field ${fieldName} does not exist on struct ${structName}`); + } + }; + exports2.ErrMissingFieldOnStruct = ErrMissingFieldOnStruct; + var ErrMissingFieldOnEnum = class extends Err { + constructor(fieldName, enumName) { + super(`field ${fieldName} does not exist on enum ${enumName}`); + } + }; + exports2.ErrMissingFieldOnEnum = ErrMissingFieldOnEnum; + var ErrCannotParseContractResults = class extends Err { + constructor(details) { + super(`cannot parse contract results: ${details}`); + } + }; + exports2.ErrCannotParseContractResults = ErrCannotParseContractResults; + var ErrCannotParseTransactionOutcome = class extends Err { + constructor(transactionHash, message) { + super(`cannot parse outcome of transaction ${transactionHash}: ${message}`); + } + }; + exports2.ErrCannotParseTransactionOutcome = ErrCannotParseTransactionOutcome; + var ErrCodec = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrCodec = ErrCodec; + var ErrContractInteraction = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrContractInteraction = ErrContractInteraction; + var ErrNotImplemented = class extends Err { + constructor() { + super("Method not yet implemented"); + } + }; + exports2.ErrNotImplemented = ErrNotImplemented; + var ErrInvalidRelayedV1BuilderArguments = class extends Err { + constructor() { + super("invalid arguments for relayed v1 builder"); + } + }; + exports2.ErrInvalidRelayedV1BuilderArguments = ErrInvalidRelayedV1BuilderArguments; + var ErrInvalidRelayedV2BuilderArguments = class extends Err { + constructor() { + super("invalid arguments for relayed v2 builder"); + } + }; + exports2.ErrInvalidRelayedV2BuilderArguments = ErrInvalidRelayedV2BuilderArguments; + var ErrGasLimitShouldBe0ForInnerTransaction = class extends Err { + constructor() { + super("gas limit must be 0 for the inner transaction for relayed v2"); + } + }; + exports2.ErrGasLimitShouldBe0ForInnerTransaction = ErrGasLimitShouldBe0ForInnerTransaction; + var ErrIsCompletedFieldIsMissingOnTransaction = class extends Err { + constructor() { + super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`."); + } + }; + exports2.ErrIsCompletedFieldIsMissingOnTransaction = ErrIsCompletedFieldIsMissingOnTransaction; + var ErrInvalidTokenIdentifier = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrInvalidTokenIdentifier = ErrInvalidTokenIdentifier; + var ErrBadUsage = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrBadUsage = ErrBadUsage; + var ErrInvalidInnerTransaction = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrInvalidInnerTransaction = ErrInvalidInnerTransaction; + var ErrParseTransactionOutcome = class extends Err { + constructor(message) { + super(message); + } + }; + exports2.ErrParseTransactionOutcome = ErrParseTransactionOutcome; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokens.js +var require_tokens = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokens.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenPayment = exports2.TokenComputer = exports2.TokenTransfer = exports2.Token = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var errors_1 = require_errors(); + var EGLDTokenIdentifier = "EGLD"; + var EGLDNumDecimals = 18; + bignumber_js_1.default.set({ ROUNDING_MODE: 1 }); + var Token2 = class { + constructor(options) { + this.identifier = options.identifier; + this.nonce = options.nonce || 0n; + } + }; + exports2.Token = Token2; + var TokenTransfer2 = class _TokenTransfer { + constructor(options) { + if (this.isLegacyTokenTransferOptions(options)) { + const amount = new bignumber_js_1.default(options.amountAsBigInteger); + if (!amount.isInteger() || amount.isNegative()) { + throw new errors_1.ErrInvalidArgument(`bad amountAsBigInteger: ${options.amountAsBigInteger}`); + } + this.tokenIdentifier = options.tokenIdentifier; + this.nonce = options.nonce; + this.amountAsBigInteger = amount; + this.numDecimals = options.numDecimals || 0; + this.token = new Token2({ + identifier: options.tokenIdentifier, + nonce: BigInt(options.nonce) + }); + this.amount = BigInt(this.amountAsBigInteger.toFixed(0)); + } else { + this.token = options.token; + this.amount = options.amount; + this.tokenIdentifier = options.token.identifier; + this.nonce = Number(options.token.nonce); + this.amountAsBigInteger = new bignumber_js_1.default(this.amount.toString()); + this.numDecimals = 0; + } + } + isLegacyTokenTransferOptions(options) { + return options.tokenIdentifier !== void 0; + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static egldFromAmount(amount) { + const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(EGLDNumDecimals).decimalPlaces(0); + return this.egldFromBigInteger(amountAsBigInteger); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static egldFromBigInteger(amountAsBigInteger) { + return new _TokenTransfer({ + tokenIdentifier: EGLDTokenIdentifier, + nonce: 0, + amountAsBigInteger, + numDecimals: EGLDNumDecimals + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static fungibleFromAmount(tokenIdentifier, amount, numDecimals) { + const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); + return this.fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals = 0) { + return new _TokenTransfer({ + tokenIdentifier, + nonce: 0, + amountAsBigInteger, + numDecimals + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static nonFungible(tokenIdentifier, nonce) { + return new _TokenTransfer({ + tokenIdentifier, + nonce, + amountAsBigInteger: 1, + numDecimals: 0 + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static semiFungible(tokenIdentifier, nonce, quantity) { + return new _TokenTransfer({ + tokenIdentifier, + nonce, + amountAsBigInteger: quantity, + numDecimals: 0 + }); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static metaEsdtFromAmount(tokenIdentifier, nonce, amount, numDecimals) { + const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); + return this.metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals); + } + /** + * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); + */ + static metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals = 0) { + return new _TokenTransfer({ + tokenIdentifier, + nonce, + amountAsBigInteger, + numDecimals + }); + } + toString() { + return this.amount.toString(); + } + /** + * Legacy function. Use the "amount" field instead. + */ + valueOf() { + return new bignumber_js_1.default(this.amount.toString()); + } + /** + * Legacy function. For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. + */ + toPrettyString() { + return `${this.toAmount()} ${this.tokenIdentifier}`; + } + toAmount() { + return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals); + } + /** + * Legacy function. Within your code, don't mix native values (EGLD) and custom (ESDT) tokens. + * See "TransferTransactionsFactory.createTransactionForNativeTokenTransfer()" vs. "TransferTransactionsFactory.createTransactionForESDTTokenTransfer()". + */ + isEgld() { + return this.token.identifier == EGLDTokenIdentifier; + } + /** + * Legacy function. Use "TokenComputer.isFungible(token)" instead. + */ + isFungible() { + return this.token.nonce == 0n; + } + }; + exports2.TokenTransfer = TokenTransfer2; + var TokenComputer2 = class { + constructor() { + } + isFungible(token) { + return token.nonce === 0n; + } + extractNonceFromExtendedIdentifier(identifier) { + const parts = identifier.split("-"); + this.checkIfExtendedIdentifierWasProvided(parts); + this.checkLengthOfRandomSequence(parts[1]); + if (parts.length == 2) { + return 0; + } + const hexNonce = import_buffer.Buffer.from(parts[2], "hex"); + return decodeUnsignedNumber(hexNonce); + } + extractIdentifierFromExtendedIdentifier(identifier) { + const parts = identifier.split("-"); + this.checkIfExtendedIdentifierWasProvided(parts); + this.ensureTokenTickerValidity(parts[0]); + this.checkLengthOfRandomSequence(parts[1]); + return parts[0] + "-" + parts[1]; + } + checkIfExtendedIdentifierWasProvided(tokenParts) { + const MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 2; + const MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 3; + if (tokenParts.length < MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED || tokenParts.length > MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED) { + throw new errors_1.ErrInvalidTokenIdentifier("Invalid extended token identifier provided"); + } + } + checkLengthOfRandomSequence(randomSequence) { + const TOKEN_RANDOM_SEQUENCE_LENGTH = 6; + if (randomSequence.length !== TOKEN_RANDOM_SEQUENCE_LENGTH) { + throw new errors_1.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length"); + } + } + ensureTokenTickerValidity(ticker) { + const MIN_TICKER_LENGTH = 3; + const MAX_TICKER_LENGTH = 10; + if (ticker.length < MIN_TICKER_LENGTH || ticker.length > MAX_TICKER_LENGTH) { + throw new errors_1.ErrInvalidTokenIdentifier(`The token ticker should be between ${MIN_TICKER_LENGTH} and ${MAX_TICKER_LENGTH} characters`); + } + if (!ticker.match(/^[a-zA-Z0-9]+$/)) { + throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters"); + } + if (!(ticker == ticker.toUpperCase())) { + throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should be upper case"); + } + } + }; + exports2.TokenComputer = TokenComputer2; + function decodeUnsignedNumber(arg) { + return arg.readUIntBE(0, arg.length); + } + var TokenPayment = class extends TokenTransfer2 { + constructor(tokenIdentifier, nonce, amountAsBigInteger, numDecimals) { + super({ + tokenIdentifier, + nonce, + amountAsBigInteger, + numDecimals + }); + } + }; + exports2.TokenPayment = TokenPayment; + } +}); + +// node_modules/@multiversx/sdk-core/out/constants.js +var require_constants = __commonJS({ + "node_modules/@multiversx/sdk-core/out/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.UNKNOWN_SIGNER = exports2.SDK_JS_SIGNER = exports2.METACHAIN_ID = exports2.WasmVirtualMachine = exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = exports2.BECH32_ADDRESS_LENGTH = exports2.HEX_TRANSACTION_HASH_LENGTH = exports2.MESSAGE_PREFIX = exports2.DEFAULT_MESSAGE_VERSION = exports2.ESDT_CONTRACT_ADDRESS = exports2.DEFAULT_HRP = exports2.DELEGATION_MANAGER_SC_ADDRESS = exports2.CONTRACT_DEPLOY_ADDRESS = exports2.VM_TYPE_WASM_VM = exports2.ARGUMENTS_SEPARATOR = exports2.ESDT_TRANSFER_VALUE = exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_GAS_LIMIT = exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = exports2.TRANSACTION_VERSION_DEFAULT = exports2.TRANSACTION_OPTIONS_TX_GUARDED = exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = exports2.TRANSACTION_OPTIONS_DEFAULT = exports2.TRANSACTION_MIN_GAS_PRICE = void 0; + exports2.TRANSACTION_MIN_GAS_PRICE = 1e9; + exports2.TRANSACTION_OPTIONS_DEFAULT = 0; + exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = 1; + exports2.TRANSACTION_OPTIONS_TX_GUARDED = 2; + exports2.TRANSACTION_VERSION_DEFAULT = 2; + exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = 2; + exports2.ESDT_TRANSFER_GAS_LIMIT = 5e5; + exports2.ESDT_TRANSFER_FUNCTION_NAME = "ESDTTransfer"; + exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = "ESDTNFTTransfer"; + exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = "MultiESDTNFTTransfer"; + exports2.ESDT_TRANSFER_VALUE = "0"; + exports2.ARGUMENTS_SEPARATOR = "@"; + exports2.VM_TYPE_WASM_VM = new Uint8Array([5, 0]); + exports2.CONTRACT_DEPLOY_ADDRESS = "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"; + exports2.DELEGATION_MANAGER_SC_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"; + exports2.DEFAULT_HRP = "erd"; + exports2.ESDT_CONTRACT_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"; + exports2.DEFAULT_MESSAGE_VERSION = 1; + exports2.MESSAGE_PREFIX = "Elrond Signed Message:\n"; + exports2.HEX_TRANSACTION_HASH_LENGTH = 64; + exports2.BECH32_ADDRESS_LENGTH = 62; + exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = 3; + exports2.WasmVirtualMachine = "0500"; + exports2.METACHAIN_ID = 4294967295; + exports2.SDK_JS_SIGNER = "sdk-js"; + exports2.UNKNOWN_SIGNER = "unknown"; + } +}); + +// node_modules/@multiversx/sdk-core/out/logger.js +var require_logger = __commonJS({ + "node_modules/@multiversx/sdk-core/out/logger.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Logger = exports2.LogLevel = void 0; + var LogLevel; + (function(LogLevel2) { + LogLevel2[LogLevel2["Trace"] = 0] = "Trace"; + LogLevel2[LogLevel2["Debug"] = 1] = "Debug"; + LogLevel2[LogLevel2["Info"] = 2] = "Info"; + LogLevel2[LogLevel2["Warn"] = 3] = "Warn"; + LogLevel2[LogLevel2["Error"] = 4] = "Error"; + LogLevel2[LogLevel2["None"] = 5] = "None"; + })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); + var Logger = class _Logger { + static setLevel(logLevel) { + _Logger.logLevel = logLevel; + } + static trace(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Debug) { + return; + } + console.debug(message, optionalParams); + } + static debug(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Debug) { + return; + } + console.debug(message, optionalParams); + } + static info(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Info) { + return; + } + console.log(message, optionalParams); + } + static warn(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Warn) { + return; + } + console.warn(message, optionalParams); + } + static error(message, ...optionalParams) { + if (_Logger.logLevel >= LogLevel.Error) { + return; + } + console.error(message, optionalParams); + } + }; + exports2.Logger = Logger; + Logger.logLevel = LogLevel.Debug; + } +}); + +// node_modules/@multiversx/sdk-core/out/networkParams.js +var require_networkParams = __commonJS({ + "node_modules/@multiversx/sdk-core/out/networkParams.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionOptions = exports2.TransactionVersion = void 0; + var constants_1 = require_constants(); + var errors = __importStar2(require_errors()); + var TransactionVersion2 = class _TransactionVersion { + /** + * Creates a TransactionVersion object given a value. + */ + constructor(value) { + value = Number(value); + if (value < 1) { + throw new errors.ErrTransactionVersionInvalid(value); + } + this.value = value; + } + /** + * Creates a TransactionVersion object with the default version setting + */ + static withDefaultVersion() { + return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); + } + /** + * Creates a TransactionVersion object with the VERSION setting for enabling options + */ + static withTxOptions() { + return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); + } + valueOf() { + return this.value; + } + }; + exports2.TransactionVersion = TransactionVersion2; + var TransactionOptions2 = class _TransactionOptions { + /** + * Creates a TransactionOptions from a numeric value. + */ + constructor(value) { + value = Number(value); + if (value < 0) { + throw new errors.ErrTransactionOptionsInvalid(value); + } + this.value = value; + } + /** + * Creates a TransactionOptions object with the default options. + */ + static withDefaultOptions() { + return new _TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); + } + /** + * Creates a TransactionOptions object from a set of options. + */ + static withOptions(options) { + let value = 0; + if (options.hashSign) { + value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + if (options.guarded) { + value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + return new _TransactionOptions(value); + } + /** + * Returns true if the "hash sign" option is set. + */ + isWithHashSign() { + return (this.value & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + /** + * Returns true if the "guarded transaction" option is set. + */ + isWithGuardian() { + return (this.value & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + /** + * Sets the "hash sign" option. + */ + setWithHashSign() { + this.value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + /** + * Sets the "guarded transaction" option. + */ + setWithGuardian() { + this.value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + valueOf() { + return this.value; + } + }; + exports2.TransactionOptions = TransactionOptions2; + } +}); + +// node_modules/bech32/index.js +var require_bech32 = __commonJS({ + "node_modules/bech32/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + var ALPHABET_MAP = {}; + for (z3 = 0; z3 < ALPHABET.length; z3++) { + x3 = ALPHABET.charAt(z3); + if (ALPHABET_MAP[x3] !== void 0) + throw new TypeError(x3 + " is ambiguous"); + ALPHABET_MAP[x3] = z3; + } + var x3; + var z3; + function polymodStep(pre) { + var b4 = pre >> 25; + return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; + } + function prefixChk(prefix) { + var chk = 1; + for (var i2 = 0; i2 < prefix.length; ++i2) { + var c4 = prefix.charCodeAt(i2); + if (c4 < 33 || c4 > 126) + return "Invalid prefix (" + prefix + ")"; + chk = polymodStep(chk) ^ c4 >> 5; + } + chk = polymodStep(chk); + for (i2 = 0; i2 < prefix.length; ++i2) { + var v2 = prefix.charCodeAt(i2); + chk = polymodStep(chk) ^ v2 & 31; + } + return chk; + } + function encode5(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) + throw new TypeError("Exceeds length limit"); + prefix = prefix.toLowerCase(); + var chk = prefixChk(prefix); + if (typeof chk === "string") + throw new Error(chk); + var result = prefix + "1"; + for (var i2 = 0; i2 < words.length; ++i2) { + var x4 = words[i2]; + if (x4 >> 5 !== 0) + throw new Error("Non 5-bit word"); + chk = polymodStep(chk) ^ x4; + result += ALPHABET.charAt(x4); + } + for (i2 = 0; i2 < 6; ++i2) { + chk = polymodStep(chk); + } + chk ^= 1; + for (i2 = 0; i2 < 6; ++i2) { + var v2 = chk >> (5 - i2) * 5 & 31; + result += ALPHABET.charAt(v2); + } + return result; + } + function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) + return str + " too short"; + if (str.length > LIMIT) + return "Exceeds length limit"; + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) + return "Mixed-case string " + str; + str = lowered; + var split = str.lastIndexOf("1"); + if (split === -1) + return "No separator character for " + str; + if (split === 0) + return "Missing prefix for " + str; + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) + return "Data too short"; + var chk = prefixChk(prefix); + if (typeof chk === "string") + return chk; + var words = []; + for (var i2 = 0; i2 < wordChars.length; ++i2) { + var c4 = wordChars.charAt(i2); + var v2 = ALPHABET_MAP[c4]; + if (v2 === void 0) + return "Unknown character " + c4; + chk = polymodStep(chk) ^ v2; + if (i2 + 6 >= wordChars.length) + continue; + words.push(v2); + } + if (chk !== 1) + return "Invalid checksum for " + str; + return { prefix, words }; + } + function decodeUnsafe() { + var res = __decode.apply(null, arguments); + if (typeof res === "object") + return res; + } + function decode6(str) { + var res = __decode.apply(null, arguments); + if (typeof res === "object") + return res; + throw new Error(res); + } + function convert(data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + var result = []; + for (var i2 = 0; i2 < data.length; ++i2) { + value = value << inBits | data[i2]; + bits += inBits; + while (bits >= outBits) { + bits -= outBits; + result.push(value >> bits & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push(value << outBits - bits & maxV); + } + } else { + if (bits >= inBits) + return "Excess padding"; + if (value << outBits - bits & maxV) + return "Non-zero padding"; + } + return result; + } + function toWordsUnsafe(bytes) { + var res = convert(bytes, 8, 5, true); + if (Array.isArray(res)) + return res; + } + function toWords(bytes) { + var res = convert(bytes, 8, 5, true); + if (Array.isArray(res)) + return res; + throw new Error(res); + } + function fromWordsUnsafe(words) { + var res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + } + function fromWords(words) { + var res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + throw new Error(res); + } + module2.exports = { + decodeUnsafe, + decode: decode6, + encode: encode5, + toWordsUnsafe, + toWords, + fromWordsUnsafe, + fromWords + }; + } +}); + +// node_modules/@multiversx/sdk-core/out/utils.codec.js +var require_utils_codec = __commonJS({ + "node_modules/@multiversx/sdk-core/out/utils.codec.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addressToHex = exports2.bigIntToHex = exports2.byteArrayToHex = exports2.boolToHex = exports2.utf8ToHex = exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var contractsCodecUtils = __importStar2(require_utils()); + function numberToPaddedHex(value) { + let hexableNumber; + if (typeof value === "bigint" || typeof value === "number") { + hexableNumber = value; + } else { + hexableNumber = new bignumber_js_1.default(value); + } + const hex = hexableNumber.toString(16); + return zeroPadStringIfOddLength(hex); + } + exports2.numberToPaddedHex = numberToPaddedHex; + function isPaddedHex(input) { + input = input || ""; + let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); + return input.toUpperCase() == decodedThenEncoded.toUpperCase(); + } + exports2.isPaddedHex = isPaddedHex; + function zeroPadStringIfOddLength(input) { + input = input || ""; + if (input.length % 2 == 1) { + return "0" + input; + } + return input; + } + exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; + function utf8ToHex(value) { + const hex = import_buffer.Buffer.from(value).toString("hex"); + return zeroPadStringIfOddLength(hex); + } + exports2.utf8ToHex = utf8ToHex; + function boolToHex(value) { + return utf8ToHex(value.toString()); + } + exports2.boolToHex = boolToHex; + function byteArrayToHex(byteArray) { + const hexString = import_buffer.Buffer.from(byteArray).toString("hex"); + return zeroPadStringIfOddLength(hexString); + } + exports2.byteArrayToHex = byteArrayToHex; + function bigIntToHex(value) { + if (value == 0) { + return ""; + } + return contractsCodecUtils.getHexMagnitudeOfBigInt(value); + } + exports2.bigIntToHex = bigIntToHex; + function addressToHex(address) { + const buffer = address_1.Address.fromBech32(address.toString()).pubkey(); + return buffer.toString("hex"); + } + exports2.addressToHex = addressToHex; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js +var require_utils = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.prependByteToBuffer = exports2.flipBufferBitsInPlace = exports2.getHexMagnitudeOfBigInt = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.cloneBuffer = exports2.isMsbZero = exports2.isMsbOne = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var utils_codec_1 = require_utils_codec(); + function isMsbOne(buffer, byteIndex = 0) { + let byte = buffer[byteIndex]; + let bit = byte >> 7; + let isSet = bit == 1; + return isSet; + } + exports2.isMsbOne = isMsbOne; + function isMsbZero(buffer, byteIndex = 0) { + return !isMsbOne(buffer, byteIndex); + } + exports2.isMsbZero = isMsbZero; + function cloneBuffer(buffer) { + let clone2 = import_buffer.Buffer.alloc(buffer.length); + buffer.copy(clone2); + return clone2; + } + exports2.cloneBuffer = cloneBuffer; + function bufferToBigInt(buffer) { + let hex = buffer.toString("hex"); + return new bignumber_js_1.default(`0x${hex}`, 16); + } + exports2.bufferToBigInt = bufferToBigInt; + function bigIntToBuffer(value) { + let hex = getHexMagnitudeOfBigInt(value); + return import_buffer.Buffer.from(hex, "hex"); + } + exports2.bigIntToBuffer = bigIntToBuffer; + function getHexMagnitudeOfBigInt(value) { + value = new bignumber_js_1.default(value); + if (!value) { + return ""; + } + if (value.isNegative()) { + value = value.multipliedBy(new bignumber_js_1.default(-1)); + } + return utils_codec_1.numberToPaddedHex(value); + } + exports2.getHexMagnitudeOfBigInt = getHexMagnitudeOfBigInt; + function flipBufferBitsInPlace(buffer) { + for (let i2 = 0; i2 < buffer.length; i2++) { + buffer[i2] = ~buffer[i2]; + } + } + exports2.flipBufferBitsInPlace = flipBufferBitsInPlace; + function prependByteToBuffer(buffer, byte) { + return import_buffer.Buffer.concat([import_buffer.Buffer.from([byte]), buffer]); + } + exports2.prependByteToBuffer = prependByteToBuffer; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js +var require_codec = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bufferToHex = exports2.addressToHex = exports2.bigIntToHex = exports2.utf8ToHex = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.stringToBuffer = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var contractsCodecUtils = __importStar2(require_utils()); + var codecUtils = __importStar2(require_utils_codec()); + function stringToBuffer(value) { + return import_buffer.Buffer.from(value); + } + exports2.stringToBuffer = stringToBuffer; + function bufferToBigInt(buffer) { + if (buffer.length == 0) { + return new bignumber_js_1.default(0); + } + return contractsCodecUtils.bufferToBigInt(buffer); + } + exports2.bufferToBigInt = bufferToBigInt; + function bigIntToBuffer(value) { + if (value == 0) { + return import_buffer.Buffer.from([]); + } + return contractsCodecUtils.bigIntToBuffer(value); + } + exports2.bigIntToBuffer = bigIntToBuffer; + var utils_codec_1 = require_utils_codec(); + Object.defineProperty(exports2, "utf8ToHex", { enumerable: true, get: function() { + return utils_codec_1.utf8ToHex; + } }); + Object.defineProperty(exports2, "bigIntToHex", { enumerable: true, get: function() { + return utils_codec_1.bigIntToHex; + } }); + Object.defineProperty(exports2, "addressToHex", { enumerable: true, get: function() { + return utils_codec_1.addressToHex; + } }); + function bufferToHex(value) { + const hex = value.toString("hex"); + return codecUtils.zeroPadStringIfOddLength(hex); + } + exports2.bufferToHex = bufferToHex; + } +}); + +// node_modules/events/events.js +var require_events = __commonJS({ + "node_modules/events/events.js"(exports2, module2) { + "use strict"; + init_shim(); + var R2 = typeof Reflect === "object" ? Reflect : null; + var ReflectApply = R2 && typeof R2.apply === "function" ? R2.apply : function ReflectApply2(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }; + var ReflectOwnKeys; + if (R2 && typeof R2.ownKeys === "function") { + ReflectOwnKeys = R2.ownKeys; + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target); + }; + } + function ProcessEmitWarning(warning) { + if (console && console.warn) + console.warn(warning); + } + var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { + return value !== value; + }; + function EventEmitter2() { + EventEmitter2.init.call(this); + } + module2.exports = EventEmitter2; + module2.exports.once = once; + EventEmitter2.EventEmitter = EventEmitter2; + EventEmitter2.prototype._events = void 0; + EventEmitter2.prototype._eventsCount = 0; + EventEmitter2.prototype._maxListeners = void 0; + var defaultMaxListeners = 10; + function checkListener(listener) { + if (typeof listener !== "function") { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + } + Object.defineProperty(EventEmitter2, "defaultMaxListeners", { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); + } + defaultMaxListeners = arg; + } + }); + EventEmitter2.init = function() { + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + }; + EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n3) { + if (typeof n3 !== "number" || n3 < 0 || NumberIsNaN(n3)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n3 + "."); + } + this._maxListeners = n3; + return this; + }; + function _getMaxListeners(that) { + if (that._maxListeners === void 0) + return EventEmitter2.defaultMaxListeners; + return that._maxListeners; + } + EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; + EventEmitter2.prototype.emit = function emit(type) { + var args = []; + for (var i2 = 1; i2 < arguments.length; i2++) + args.push(arguments[i2]); + var doError = type === "error"; + var events = this._events; + if (events !== void 0) + doError = doError && events.error === void 0; + else if (!doError) + return false; + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + throw er; + } + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); + err.context = er; + throw err; + } + var handler = events[type]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i2 = 0; i2 < len; ++i2) + ReflectApply(listeners[i2], this, args); + } + return true; + }; + function _addListener(target, type, listener, prepend) { + var m3; + var events; + var existing; + checkListener(listener); + events = target._events; + if (events === void 0) { + events = target._events = /* @__PURE__ */ Object.create(null); + target._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + target.emit( + "newListener", + type, + listener.listener ? listener.listener : listener + ); + events = target._events; + } + existing = events[type]; + } + if (existing === void 0) { + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m3 = _getMaxListeners(target); + if (m3 > 0 && existing.length > m3 && !existing.warned) { + existing.warned = true; + var w4 = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w4.name = "MaxListenersExceededWarning"; + w4.emitter = target; + w4.type = type; + w4.count = existing.length; + ProcessEmitWarning(w4); + } + } + return target; + } + EventEmitter2.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; + EventEmitter2.prototype.prependListener = function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } + } + function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: void 0, target, type, listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + EventEmitter2.prototype.once = function once2(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + EventEmitter2.prototype.removeListener = function removeListener(type, listener) { + var list, events, position, i2, originalListener; + checkListener(listener); + events = this._events; + if (events === void 0) + return this; + list = events[type]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit("removeListener", type, list.listener || listener); + } + } else if (typeof list !== "function") { + position = -1; + for (i2 = list.length - 1; i2 >= 0; i2--) { + if (list[i2] === listener || list[i2].listener === listener) { + originalListener = list[i2].listener; + position = i2; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events[type] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type, originalListener || listener); + } + return this; + }; + EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; + EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { + var listeners, events, i2; + events = this._events; + if (events === void 0) + return this; + if (events.removeListener === void 0) { + if (arguments.length === 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type]; + } + return this; + } + if (arguments.length === 0) { + var keys2 = Object.keys(events); + var key; + for (i2 = 0; i2 < keys2.length; ++i2) { + key = keys2[i2]; + if (key === "removeListener") + continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return this; + } + listeners = events[type]; + if (typeof listeners === "function") { + this.removeListener(type, listeners); + } else if (listeners !== void 0) { + for (i2 = listeners.length - 1; i2 >= 0; i2--) { + this.removeListener(type, listeners[i2]); + } + } + return this; + }; + function _listeners(target, type, unwrap) { + var events = target._events; + if (events === void 0) + return []; + var evlistener = events[type]; + if (evlistener === void 0) + return []; + if (typeof evlistener === "function") + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + } + EventEmitter2.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; + EventEmitter2.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; + EventEmitter2.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } + }; + EventEmitter2.prototype.listenerCount = listenerCount; + function listenerCount(type) { + var events = this._events; + if (events !== void 0) { + var evlistener = events[type]; + if (typeof evlistener === "function") { + return 1; + } else if (evlistener !== void 0) { + return evlistener.length; + } + } + return 0; + } + EventEmitter2.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; + function arrayClone(arr, n3) { + var copy = new Array(n3); + for (var i2 = 0; i2 < n3; ++i2) + copy[i2] = arr[i2]; + return copy; + } + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i2 = 0; i2 < ret.length; ++i2) { + ret[i2] = arr[i2].listener || arr[i2]; + } + return ret; + } + function once(emitter, name2) { + return new Promise(function(resolve, reject) { + function errorListener(err) { + emitter.removeListener(name2, resolver); + reject(err); + } + function resolver() { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + resolve([].slice.call(arguments)); + } + ; + eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); + if (name2 !== "error") { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); + } + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === "function") { + eventTargetAgnosticAddListener(emitter, "error", handler, flags); + } + } + function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { + if (typeof emitter.on === "function") { + if (flags.once) { + emitter.once(name2, listener); + } else { + emitter.on(name2, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name2, function wrapListener(arg) { + if (flags.once) { + emitter.removeEventListener(name2, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/stream-browser.js +var require_stream_browser = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/stream-browser.js"(exports2, module2) { + init_shim(); + module2.exports = require_events().EventEmitter; + } +}); + +// node_modules/buffer/index.js +var require_buffer2 = __commonJS({ + "node_modules/buffer/index.js"(exports2) { + "use strict"; + init_shim(); + var base642 = require_base64_js(); + var ieee754 = require_ieee754(); + var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports2.Buffer = Buffer2; + exports2.SlowBuffer = SlowBuffer; + exports2.INSPECT_MAX_BYTES = 50; + var K_MAX_LENGTH = 2147483647; + exports2.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42; + } catch (e2) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) + return void 0; + return this.byteOffset; + } + }); + function createBuffer(length2) { + if (length2 > K_MAX_LENGTH) { + throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); + } + const buf = new Uint8Array(length2); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe2(arg); + } + return from3(arg, encodingOrOffset, length2); + } + Buffer2.poolSize = 8192; + function from3(value, encodingOrOffset, length2) { + if (typeof value === "string") { + return fromString3(value, encodingOrOffset); + } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value); + } + if (value == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length2); + } + if (typeof value === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer2.from(valueOf, encodingOrOffset, length2); + } + const b4 = fromObject(value); + if (b4) + return b4; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { + return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length2); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value + ); + } + Buffer2.from = function(value, encodingOrOffset, length2) { + return from3(value, encodingOrOffset, length2); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe2(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe2(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe2(size); + }; + function fromString3(string2, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length2 = byteLength(string2, encoding) | 0; + let buf = createBuffer(length2); + const actual = buf.write(string2, encoding); + if (actual !== length2) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array) { + const length2 = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length2); + for (let i2 = 0; i2 < length2; i2 += 1) { + buf[i2] = array[i2] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array, byteOffset, length2) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array.byteLength < byteOffset + (length2 || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length2 === void 0) { + buf = new Uint8Array(array); + } else if (length2 === void 0) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length2); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length2) { + if (length2 >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length2 | 0; + } + function SlowBuffer(length2) { + if (+length2 != length2) { + length2 = 0; + } + return Buffer2.alloc(+length2); + } + Buffer2.isBuffer = function isBuffer(b4) { + return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; + }; + Buffer2.compare = function compare3(a3, b4) { + if (isInstance(a3, Uint8Array)) + a3 = Buffer2.from(a3, a3.offset, a3.byteLength); + if (isInstance(b4, Uint8Array)) + b4 = Buffer2.from(b4, b4.offset, b4.byteLength); + if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a3 === b4) + return 0; + let x3 = a3.length; + let y4 = b4.length; + for (let i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { + if (a3[i2] !== b4[i2]) { + x3 = a3[i2]; + y4 = b4[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding) { + switch (String(encoding).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 true; + default: + return false; + } + }; + Buffer2.concat = function concat2(list, length2) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + let i2; + if (length2 === void 0) { + length2 = 0; + for (i2 = 0; i2 < list.length; ++i2) { + length2 += list[i2].length; + } + } + const buffer = Buffer2.allocUnsafe(length2); + let pos = 0; + for (i2 = 0; i2 < list.length; ++i2) { + let buf = list[i2]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer2.isBuffer(buf)) + buf = Buffer2.from(buf); + buf.copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer; + }; + function byteLength(string2, encoding) { + if (Buffer2.isBuffer(string2)) { + return string2.length; + } + if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { + return string2.byteLength; + } + if (typeof string2 !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 + ); + } + const len = string2.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) + return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string2).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string2).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string2).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength; + function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) + encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b4, n3, m3) { + const i2 = b4[n3]; + b4[n3] = b4[m3]; + b4[m3] = i2; + } + Buffer2.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i2 = 0; i2 < len; i2 += 2) { + swap(this, i2, i2 + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i2 = 0; i2 < len; i2 += 4) { + swap(this, i2, i2 + 3); + swap(this, i2 + 1, i2 + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i2 = 0; i2 < len; i2 += 8) { + swap(this, i2, i2 + 7); + swap(this, i2 + 1, i2 + 6); + swap(this, i2 + 2, i2 + 5); + swap(this, i2 + 3, i2 + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString3() { + const length2 = this.length; + if (length2 === 0) + return ""; + if (arguments.length === 0) + return utf8Slice(this, 0, length2); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals4(b4) { + if (!Buffer2.isBuffer(b4)) + throw new TypeError("Argument must be a Buffer"); + if (this === b4) + return true; + return Buffer2.compare(this, b4) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + let str = ""; + const max = exports2.INSPECT_MAX_BYTES; + str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) + str += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) + return 0; + let x3 = thisEnd - thisStart; + let y4 = end - start; + const len = Math.min(x3, y4); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i2 = 0; i2 < len; ++i2) { + if (thisCopy[i2] !== targetCopy[i2]) { + x3 = thisCopy[i2]; + y4 = targetCopy[i2]; + break; + } + } + if (x3 < y4) + return -1; + if (y4 < x3) + return 1; + return 0; + }; + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + if (buffer.length === 0) + return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer.length - 1; + } + if (byteOffset < 0) + byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) + return -1; + else + byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) + byteOffset = 0; + else + return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read2(buf, i3) { + if (indexSize === 1) { + return buf[i3]; + } else { + return buf.readUInt16BE(i3 * indexSize); + } + } + let i2; + if (dir) { + let foundIndex = -1; + for (i2 = byteOffset; i2 < arrLength; i2++) { + if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { + if (foundIndex === -1) + foundIndex = i2; + if (i2 - foundIndex + 1 === valLength) + return foundIndex * indexSize; + } else { + if (foundIndex !== -1) + i2 -= i2 - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength; + for (i2 = byteOffset; i2 >= 0; i2--) { + let found = true; + for (let j2 = 0; j2 < valLength; j2++) { + if (read2(arr, i2 + j2) !== read2(val, j2)) { + found = false; + break; + } + } + if (found) + return i2; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string2, offset, length2) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (!length2) { + length2 = remaining; + } else { + length2 = Number(length2); + if (length2 > remaining) { + length2 = remaining; + } + } + const strLen = string2.length; + if (length2 > strLen / 2) { + length2 = strLen / 2; + } + let i2; + for (i2 = 0; i2 < length2; ++i2) { + const parsed = parseInt(string2.substr(i2 * 2, 2), 16); + if (numberIsNaN(parsed)) + return i2; + buf[offset + i2] = parsed; + } + return i2; + } + function utf8Write(buf, string2, offset, length2) { + return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); + } + function asciiWrite(buf, string2, offset, length2) { + return blitBuffer(asciiToBytes(string2), buf, offset, length2); + } + function base64Write(buf, string2, offset, length2) { + return blitBuffer(base64ToBytes(string2), buf, offset, length2); + } + function ucs2Write(buf, string2, offset, length2) { + return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); + } + Buffer2.prototype.write = function write(string2, offset, length2, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length2 = this.length; + offset = 0; + } else if (length2 === void 0 && typeof offset === "string") { + encoding = offset; + length2 = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length2)) { + length2 = length2 >>> 0; + if (encoding === void 0) + encoding = "utf8"; + } else { + encoding = length2; + length2 = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset; + if (length2 === void 0 || length2 > remaining) + length2 = remaining; + if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) + encoding = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string2, offset, length2); + case "utf8": + case "utf-8": + return utf8Write(this, string2, offset, length2); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string2, offset, length2); + case "base64": + return base64Write(this, string2, offset, length2); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string2, offset, length2); + default: + if (loweredCase) + throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base642.fromByteArray(buf); + } else { + return base642.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i2 = start; + while (i2 < end) { + const firstByte = buf[i2]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i2 + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i2 + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i2 + 1]; + thirdByte = buf[i2 + 2]; + fourthByte = buf[i2 + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i2 += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + var MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i2 = 0; + while (i2 < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i2 = start; i2 < end; ++i2) { + ret += String.fromCharCode(buf[i2]); + } + return ret; + } + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) + start = 0; + if (!end || end < 0 || end > len) + end = len; + let out = ""; + for (let i2 = start; i2 < end; ++i2) { + out += hexSliceLookupTable[buf[i2]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i2 = 0; i2 < bytes.length - 1; i2 += 2) { + res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) + start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) + end = 0; + } else if (end > len) { + end = len; + } + if (end < start) + end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset, ext, length2) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError("offset is not uint"); + if (offset + ext > length2) + throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength2, this.length); + } + let val = this[offset + --byteLength2]; + let mul = 1; + while (byteLength2 > 0 && (mul *= 256)) { + val += this[offset + --byteLength2] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; + const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); + }); + Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }); + Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let val = this[offset]; + let mul = 1; + let i2 = 0; + while (++i2 < byteLength2 && (mul *= 256)) { + val += this[offset + i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) + checkOffset(offset, byteLength2, this.length); + let i2 = byteLength2; + let mul = 1; + let val = this[offset + --i2]; + while (i2 > 0 && (mul *= 256)) { + val += this[offset + --i2] * mul; + } + mul *= 128; + if (val >= mul) + val -= Math.pow(2, 8 * byteLength2); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) + return this[offset]; + return (255 - this[offset] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + const val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 2, this.length); + const val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); + }); + Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); + }); + Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 4, this.length); + return ieee754.read(this, offset, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) + checkOffset(offset, 8, this.length); + return ieee754.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value, offset, ext, max, min) { + if (!Buffer2.isBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let mul = 1; + let i2 = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength2 = byteLength2 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength2) - 1; + checkInt(this, value, offset, byteLength2, maxBytes, 0); + } + let i2 = byteLength2 - 1; + let mul = 1; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + this[offset + i2] = value / mul & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 255, 0); + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 65535, 0); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 4294967295, 0); + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + function wrtBigUInt64LE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset; + } + function wrtBigUInt64BE(buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + let lo = Number(value & BigInt(4294967295)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(4294967295)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8; + } + Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i2 = 0; + let mul = 1; + let sub = 0; + this[offset] = value & 255; + while (++i2 < byteLength2 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength2 - 1); + checkInt(this, value, offset, byteLength2, limit - 1, -limit); + } + let i2 = byteLength2 - 1; + let mul = 1; + let sub = 0; + this[offset + i2] = value & 255; + while (--i2 >= 0 && (mul *= 256)) { + if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { + sub = 1; + } + this[offset + i2] = (value / mul >> 0) - sub & 255; + } + return offset + byteLength2; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 1, 127, -128); + if (value < 0) + value = 255 + value + 1; + this[offset] = value & 255; + return offset + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 2, 32767, -32768); + this[offset] = value >>> 8; + this[offset + 1] = value & 255; + return offset + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + this[offset] = value & 255; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + return offset + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) + checkInt(this, value, offset, 4, 2147483647, -2147483648); + if (value < 0) + value = 4294967295 + value + 1; + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 255; + return offset + 4; + }; + Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) + throw new RangeError("Index out of range"); + if (offset < 0) + throw new RangeError("Index out of range"); + } + function writeFloat(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); + } + ieee754.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + function writeDouble(buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); + } + ieee754.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + Buffer2.prototype.copy = function copy(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) + throw new TypeError("argument should be a Buffer"); + if (!start) + start = 0; + if (!end && end !== 0) + end = this.length; + if (targetStart >= target.length) + targetStart = target.length; + if (!targetStart) + targetStart = 0; + if (end > 0 && end < start) + end = start; + if (end === start) + return 0; + if (target.length === 0 || this.length === 0) + return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) + throw new RangeError("Index out of range"); + if (end < 0) + throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) + end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code2 = val.charCodeAt(0); + if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { + val = code2; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) + val = 0; + let i2; + if (typeof val === "number") { + for (i2 = start; i2 < end; ++i2) { + this[i2] = val; + } + } else { + const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i2 = 0; i2 < end - start; ++i2) { + this[i2 + start] = bytes[i2 % len]; + } + } + return this; + }; + var errors = {}; + function E4(sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; + } + E4( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name2) { + if (name2) { + return `${name2} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E4( + "ERR_INVALID_ARG_TYPE", + function(name2, actual) { + return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E4( + "ERR_OUT_OF_RANGE", + function(str, range, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg += ` It must be ${range}. Received ${received}`; + return msg; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i2 = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i2 >= start + 4; i2 -= 3) { + res = `_${val.slice(i2 - 3, i2)}${res}`; + } + return `${val.slice(0, i2)}${res}`; + } + function checkBounds(buf, offset, byteLength2) { + validateNumber(offset, "offset"); + if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { + boundsError(offset, buf.length - (byteLength2 + 1)); + } + } + function checkIntBI(value, min, max, buf, offset, byteLength2) { + if (value > max || value < min) { + const n3 = typeof min === "bigint" ? "n" : ""; + let range; + if (byteLength2 > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n3} and < 2${n3} ** ${(byteLength2 + 1) * 8}${n3}`; + } else { + range = `>= -(2${n3} ** ${(byteLength2 + 1) * 8 - 1}${n3}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n3}`; + } + } else { + range = `>= ${min}${n3} and <= ${max}${n3}`; + } + throw new errors.ERR_OUT_OF_RANGE("value", range, value); + } + checkBounds(buf, offset, byteLength2); + } + function validateNumber(value, name2) { + if (typeof value !== "number") { + throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value); + } + } + function boundsError(value, length2, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); + } + if (length2 < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors.ERR_OUT_OF_RANGE( + type || "offset", + `>= ${type ? 1 : 0} and <= ${length2}`, + value + ); + } + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str) { + str = str.split("=")[0]; + str = str.trim().replace(INVALID_BASE64_RE, ""); + if (str.length < 2) + return ""; + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + function utf8ToBytes(string2, units) { + units = units || Infinity; + let codePoint; + const length2 = string2.length; + let leadSurrogate = null; + const bytes = []; + for (let i2 = 0; i2 < length2; ++i2) { + codePoint = string2.charCodeAt(i2); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } else if (i2 + 1 === length2) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) + bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) + break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) + break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) + break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) + break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str) { + const byteArray = []; + for (let i2 = 0; i2 < str.length; ++i2) { + byteArray.push(str.charCodeAt(i2) & 255); + } + return byteArray; + } + function utf16leToBytes(str, units) { + let c4, hi, lo; + const byteArray = []; + for (let i2 = 0; i2 < str.length; ++i2) { + if ((units -= 2) < 0) + break; + c4 = str.charCodeAt(i2); + hi = c4 >> 8; + lo = c4 % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str) { + return base642.toByteArray(base64clean(str)); + } + function blitBuffer(src2, dst, offset, length2) { + let i2; + for (i2 = 0; i2 < length2; ++i2) { + if (i2 + offset >= dst.length || i2 >= src2.length) + break; + dst[i2 + offset] = src2[i2]; + } + return i2; + } + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + var hexSliceLookupTable = function() { + const alphabet2 = "0123456789abcdef"; + const table = new Array(256); + for (let i2 = 0; i2 < 16; ++i2) { + const i16 = i2 * 16; + for (let j2 = 0; j2 < 16; ++j2) { + table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; + } + } + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; + } + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); + } + } +}); + +// (disabled):node_modules/util/util.js +var require_util = __commonJS({ + "(disabled):node_modules/util/util.js"() { + init_shim(); + } +}); + +// node_modules/readable-stream/lib/internal/streams/buffer_list.js +var require_buffer_list = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { + "use strict"; + init_shim(); + function ownKeys(object, enumerableOnly) { + var keys2 = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys2.push.apply(keys2, symbols); + } + return keys2; + } + function _objectSpread(target) { + for (var i2 = 1; i2 < arguments.length; i2++) { + var source = null != arguments[i2] ? arguments[i2] : {}; + i2 % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i2 = 0; i2 < props.length; i2++) { + var descriptor = props[i2]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) + return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") + return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var _require = require_buffer2(); + var Buffer2 = _require.Buffer; + var _require2 = require_util(); + var inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src2, target, offset) { + Buffer2.prototype.copy.call(src2, target, offset); + } + module2.exports = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v2) { + var entry = { + data: v2, + next: null + }; + if (this.length > 0) + this.tail.next = entry; + else + this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v2) { + var entry = { + data: v2, + next: this.head + }; + if (this.length === 0) + this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) + return; + var ret = this.head.data; + if (this.length === 1) + this.head = this.tail = null; + else + this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear2() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s2) { + if (this.length === 0) + return ""; + var p3 = this.head; + var ret = "" + p3.data; + while (p3 = p3.next) + ret += s2 + p3.data; + return ret; + } + }, { + key: "concat", + value: function concat2(n3) { + if (this.length === 0) + return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n3 >>> 0); + var p3 = this.head; + var i2 = 0; + while (p3) { + copyBuffer(p3.data, ret, i2); + i2 += p3.data.length; + p3 = p3.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n3, hasStrings) { + var ret; + if (n3 < this.head.data.length) { + ret = this.head.data.slice(0, n3); + this.head.data = this.head.data.slice(n3); + } else if (n3 === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n3) : this._getBuffer(n3); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n3) { + var p3 = this.head; + var c4 = 1; + var ret = p3.data; + n3 -= ret.length; + while (p3 = p3.next) { + var str = p3.data; + var nb = n3 > str.length ? str.length : n3; + if (nb === str.length) + ret += str; + else + ret += str.slice(0, n3); + n3 -= nb; + if (n3 === 0) { + if (nb === str.length) { + ++c4; + if (p3.next) + this.head = p3.next; + else + this.head = this.tail = null; + } else { + this.head = p3; + p3.data = str.slice(nb); + } + break; + } + ++c4; + } + this.length -= c4; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n3) { + var ret = Buffer2.allocUnsafe(n3); + var p3 = this.head; + var c4 = 1; + p3.data.copy(ret); + n3 -= p3.data.length; + while (p3 = p3.next) { + var buf = p3.data; + var nb = n3 > buf.length ? buf.length : n3; + buf.copy(ret, ret.length - n3, 0, nb); + n3 -= nb; + if (n3 === 0) { + if (nb === buf.length) { + ++c4; + if (p3.next) + this.head = p3.next; + else + this.head = this.tail = null; + } else { + this.head = p3; + p3.data = buf.slice(nb); + } + break; + } + ++c4; + } + this.length -= c4; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_4, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + } +}); + +// node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { + "use strict"; + init_shim(); + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + import_process.default.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + import_process.default.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + import_process.default.nextTick(emitCloseNT, _this); + } + } else if (cb) { + import_process.default.nextTick(emitCloseNT, _this); + cb(err2); + } else { + import_process.default.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) + return; + if (self2._readableState && !self2._readableState.emitClose) + return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream, err) { + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) + stream.destroy(err); + else + stream.emit("error", err); + } + module2.exports = { + destroy, + undestroy, + errorOrDestroy + }; + } +}); + +// node_modules/readable-stream/errors-browser.js +var require_errors_browser = __commonJS({ + "node_modules/readable-stream/errors-browser.js"(exports2, module2) { + "use strict"; + init_shim(); + function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; + } + var codes = {}; + function createErrorType(code2, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = /* @__PURE__ */ function(_Base) { + _inheritsLoose(NodeError2, _Base); + function NodeError2(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + return NodeError2; + }(Base); + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code2; + codes[code2] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function(i2) { + return String(i2); + }); + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name2, value) { + return 'The value "' + value + '" is invalid for option "' + name2 + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) { + var determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + var msg; + if (endsWith(name2, " argument")) { + msg = "The ".concat(name2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } else { + var type = includes(name2, ".") ? "property" : "argument"; + msg = 'The "'.concat(name2, '" ').concat(type, " ").concat(determiner, " ").concat(oneOf(expected, "type")); + } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name2) { + return "The " + name2 + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name2) { + return "Cannot call " + name2 + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + module2.exports.codes = codes; + } +}); + +// node_modules/readable-stream/lib/internal/streams/state.js +var require_state = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { + "use strict"; + init_shim(); + var ERR_INVALID_OPT_VALUE = require_errors_browser().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name2 = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name2, hwm); + } + return Math.floor(hwm); + } + return state.objectMode ? 16 : 16 * 1024; + } + module2.exports = { + getHighWaterMark + }; + } +}); + +// node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/inherits/inherits_browser.js"(exports2, module2) { + init_shim(); + if (typeof Object.create === "function") { + module2.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module2.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + } +}); + +// node_modules/util-deprecate/browser.js +var require_browser2 = __commonJS({ + "node_modules/util-deprecate/browser.js"(exports2, module2) { + init_shim(); + module2.exports = deprecate2; + function deprecate2(fn, msg) { + if (config("noDeprecation")) { + return fn; + } + var warned = false; + function deprecated() { + if (!warned) { + if (config("throwDeprecation")) { + throw new Error(msg); + } else if (config("traceDeprecation")) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + return deprecated; + } + function config(name2) { + try { + if (!global.localStorage) + return false; + } catch (_4) { + return false; + } + var val = global.localStorage[name2]; + if (null == val) + return false; + return String(val).toLowerCase() === "true"; + } + } +}); + +// node_modules/readable-stream/lib/_stream_writable.js +var require_stream_writable = __commonJS({ + "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Writable; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: require_browser2() + }; + var Stream = require_stream_browser(); + var Buffer2 = require_buffer2().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors_browser().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; + var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; + var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + require_inherits_browser()(Writable, Stream); + function nop() { + } + function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") + isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_4) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) + return true; + if (this !== Writable) + return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) + return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + this.writable = true; + if (options) { + if (typeof options.write === "function") + this._write = options.write; + if (typeof options.writev === "function") + this._writev = options.writev; + if (typeof options.destroy === "function") + this._destroy = options.destroy; + if (typeof options.final === "function") + this._final = options.final; + } + Stream.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream, er); + import_process.default.nextTick(cb, er); + } + function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream, er); + import_process.default.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (isBuf) + encoding = "buffer"; + else if (!encoding) + encoding = state.defaultEncoding; + if (typeof cb !== "function") + cb = nop; + if (state.ending) + writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) + clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") + encoding = encoding.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) + throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + if (!ret) + state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) + state.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + import_process.default.nextTick(cb, er); + import_process.default.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + finishMaybe(stream, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== "function") + throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) + onwriteError(stream, state, sync, er, cb); + else { + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + import_process.default.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit("drain"); + } + } + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + var l4 = state.bufferedRequestCount; + var buffer = new Array(l4); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) + allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, "", holder.finish); + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + if (state.writing) { + break; + } + } + if (entry === null) + state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) + this.write(chunk, encoding); + if (state.corked) { + state.corked = 1; + this.uncork(); + } + if (!state.ending) + endWritable(this, state, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function(err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit("prefinish"); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === "function" && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + import_process.default.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit("prefinish"); + } + } + } + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit("finish"); + if (state.autoDestroy) { + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; + } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + import_process.default.nextTick(cb); + else + stream.once("finish", cb); + } + state.ended = true; + stream.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set2(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + } +}); + +// node_modules/readable-stream/lib/_stream_duplex.js +var require_stream_duplex = __commonJS({ + "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { + "use strict"; + init_shim(); + var objectKeys = Object.keys || function(obj) { + var keys3 = []; + for (var key in obj) + keys3.push(key); + return keys3; + }; + module2.exports = Duplex; + var Readable = require_stream_readable(); + var Writable = require_stream_writable(); + require_inherits_browser()(Duplex, Readable); + { + keys2 = objectKeys(Writable.prototype); + for (v2 = 0; v2 < keys2.length; v2++) { + method = keys2[v2]; + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; + } + } + var keys2; + var method; + var v2; + function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) + this.readable = false; + if (options.writable === false) + this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) + return; + import_process.default.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set2(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + } +}); + +// node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/safe-buffer/index.js"(exports2, module2) { + init_shim(); + var buffer = require_buffer2(); + var Buffer2 = buffer.Buffer; + function copyProps(src2, dst) { + for (var key in src2) { + dst[key] = src2[key]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module2.exports = buffer; + } else { + copyProps(buffer, exports2); + exports2.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length2) { + return Buffer2(arg, encodingOrOffset, length2); + } + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length2); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer.SlowBuffer(size); + }; + } +}); + +// node_modules/string_decoder/lib/string_decoder.js +var require_string_decoder = __commonJS({ + "node_modules/string_decoder/lib/string_decoder.js"(exports2) { + "use strict"; + init_shim(); + var Buffer2 = require_safe_buffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _normalizeEncoding(enc) { + if (!enc) + return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) + return; + enc = ("" + enc).toLowerCase(); + retried = true; + } + } + } + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) + throw new Error("Unknown encoding: " + enc); + return nenc || enc; + } + exports2.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); + } + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) + return ""; + var r; + var i2; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === void 0) + return ""; + i2 = this.lastNeed; + this.lastNeed = 0; + } else { + i2 = 0; + } + if (i2 < buf.length) + return r ? r + this.text(buf, i2) : this.text(buf, i2); + return r || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + function utf8CheckByte(byte) { + if (byte <= 127) + return 0; + else if (byte >> 5 === 6) + return 2; + else if (byte >> 4 === 14) + return 3; + else if (byte >> 3 === 30) + return 4; + return byte >> 6 === 2 ? -1 : -2; + } + function utf8CheckIncomplete(self2, buf, i2) { + var j2 = buf.length - 1; + if (j2 < i2) + return 0; + var nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) + self2.lastNeed = nb - 1; + return nb; + } + if (--j2 < i2 || nb === -2) + return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) + self2.lastNeed = nb - 2; + return nb; + } + if (--j2 < i2 || nb === -2) + return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) + nb = 0; + else + self2.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + function utf8CheckExtraBytes(self2, buf, p3) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "\uFFFD"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "\uFFFD"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "\uFFFD"; + } + } + } + } + function utf8FillLast(buf) { + var p3 = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p3); + if (r !== void 0) + return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p3, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p3, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i2) { + var total = utf8CheckIncomplete(this, buf, i2); + if (!this.lastNeed) + return buf.toString("utf8", i2); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i2, end); + } + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) + return r + "\uFFFD"; + return r; + } + function utf16Text(buf, i2) { + if ((buf.length - i2) % 2 === 0) { + var r = buf.toString("utf16le", i2); + if (r) { + var c4 = r.charCodeAt(r.length - 1); + if (c4 >= 55296 && c4 <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i2, buf.length - 1); + } + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); + } + return r; + } + function base64Text(buf, i2) { + var n3 = (buf.length - i2) % 3; + if (n3 === 0) + return buf.toString("base64", i2); + this.lastNeed = 3 - n3; + this.lastTotal = 3; + if (n3 === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i2, buf.length - n3); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) + return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/end-of-stream.js +var require_end_of_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { + "use strict"; + init_shim(); + var ERR_STREAM_PREMATURE_CLOSE = require_errors_browser().codes.ERR_STREAM_PREMATURE_CLOSE; + function once(callback) { + var called = false; + return function() { + if (called) + return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop() { + } + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + function eos(stream, opts, callback) { + if (typeof opts === "function") + return eos(stream, null, opts); + if (!opts) + opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream.writable) + onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish2() { + writable = false; + writableEnded = true; + if (!readable) + callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend2() { + readable = false; + readableEnded = true; + if (!writable) + callback.call(stream); + }; + var onerror = function onerror2(err) { + callback.call(stream, err); + }; + var onclose = function onclose2() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) + err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) + err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest2() { + stream.req.on("finish", onfinish); + }; + if (isRequest(stream)) { + stream.on("complete", onfinish); + stream.on("abort", onclose); + if (stream.req) + onrequest(); + else + stream.on("request", onrequest); + } else if (writable && !stream._writableState) { + stream.on("end", onlegacyfinish); + stream.on("close", onlegacyfinish); + } + stream.on("end", onend); + stream.on("finish", onfinish); + if (opts.error !== false) + stream.on("error", onerror); + stream.on("close", onclose); + return function() { + stream.removeListener("complete", onfinish); + stream.removeListener("abort", onclose); + stream.removeListener("request", onrequest); + if (stream.req) + stream.req.removeListener("finish", onfinish); + stream.removeListener("end", onlegacyfinish); + stream.removeListener("close", onlegacyfinish); + stream.removeListener("finish", onfinish); + stream.removeListener("end", onend); + stream.removeListener("error", onerror); + stream.removeListener("close", onclose); + }; + } + module2.exports = eos; + } +}); + +// node_modules/readable-stream/lib/internal/streams/async_iterator.js +var require_async_iterator = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { + "use strict"; + init_shim(); + var _Object$setPrototypeO; + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) + return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") + return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = require_end_of_stream(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + function onReadable(iter) { + import_process.default.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + import_process.default.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator[kLastReject]; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(void 0, true)); + } + iterator[kEnded] = true; + }); + stream.on("readable", onReadable.bind(null, iterator)); + return iterator; + }; + module2.exports = createReadableStreamAsyncIterator; + } +}); + +// node_modules/readable-stream/lib/internal/streams/from-browser.js +var require_from_browser = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/from-browser.js"(exports2, module2) { + init_shim(); + module2.exports = function() { + throw new Error("Readable.from is not available in the browser"); + }; + } +}); + +// node_modules/readable-stream/lib/_stream_readable.js +var require_stream_readable = __commonJS({ + "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Readable; + var Duplex; + Readable.ReadableState = ReadableState; + var EE = require_events().EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type) { + return emitter.listeners(type).length; + }; + var Stream = require_stream_browser(); + var Buffer2 = require_buffer2().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = require_util(); + var debug; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function debug2() { + }; + } + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors_browser().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from3; + require_inherits_browser()(Readable, Stream); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") + return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") + isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require_string_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable)) + return new Readable(options); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + this.readable = true; + if (options) { + if (typeof options.read === "function") + this._read = options.read; + if (typeof options.destroy === "function") + this._destroy = options.destroy; + } + Stream.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set2(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug("readableAddChunk", chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) + er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) + errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else + addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) + addChunk(stream, state, chunk, false); + else + maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit("data", chunk); + } else { + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) + state.buffer.unshift(chunk); + else + state.buffer.push(chunk); + if (state.needReadable) + emitReadable(stream); + } + maybeReadMore(stream, state); + } + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require_string_decoder().StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + this._readableState.encoding = this._readableState.decoder.encoding; + var p3 = this._readableState.buffer.head; + var content = ""; + while (p3 !== null) { + content += decoder.write(p3.data); + p3 = p3.next; + } + this._readableState.buffer.clear(); + if (content !== "") + this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n3) { + if (n3 >= MAX_HWM) { + n3 = MAX_HWM; + } else { + n3--; + n3 |= n3 >>> 1; + n3 |= n3 >>> 2; + n3 |= n3 >>> 4; + n3 |= n3 >>> 8; + n3 |= n3 >>> 16; + n3++; + } + return n3; + } + function howMuchToRead(n3, state) { + if (n3 <= 0 || state.length === 0 && state.ended) + return 0; + if (state.objectMode) + return 1; + if (n3 !== n3) { + if (state.flowing && state.length) + return state.buffer.head.data.length; + else + return state.length; + } + if (n3 > state.highWaterMark) + state.highWaterMark = computeNewHighWaterMark(n3); + if (n3 <= state.length) + return n3; + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + Readable.prototype.read = function(n3) { + debug("read", n3); + n3 = parseInt(n3, 10); + var state = this._readableState; + var nOrig = n3; + if (n3 !== 0) + state.emittedReadable = false; + if (n3 === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) + endReadable(this); + else + emitReadable(this); + return null; + } + n3 = howMuchToRead(n3, state); + if (n3 === 0 && state.ended) { + if (state.length === 0) + endReadable(this); + return null; + } + var doRead = state.needReadable; + debug("need readable", doRead); + if (state.length === 0 || state.length - n3 < state.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + if (state.length === 0) + state.needReadable = true; + this._read(state.highWaterMark); + state.sync = false; + if (!state.reading) + n3 = howMuchToRead(nOrig, state); + } + var ret; + if (n3 > 0) + ret = fromList(n3, state); + else + ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n3 = 0; + } else { + state.length -= n3; + state.awaitDrain = 0; + } + if (state.length === 0) { + if (!state.ended) + state.needReadable = true; + if (nOrig !== n3 && state.ended) + endReadable(this); + } + if (ret !== null) + this.emit("data", ret); + return ret; + }; + function onEofChunk(stream, state) { + debug("onEofChunk"); + if (state.ended) + return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + emitReadable(stream); + } else { + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } + function emitReadable(stream) { + var state = stream._readableState; + debug("emitReadable", state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + import_process.default.nextTick(emitReadable_, stream); + } + } + function emitReadable_(stream) { + var state = stream._readableState; + debug("emitReadable_", state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit("readable"); + state.emittedReadable = false; + } + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + import_process.default.nextTick(maybeReadMore_, stream, state); + } + } + function maybeReadMore_(stream, state) { + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug("maybeReadMore read 0"); + stream.read(0); + if (len === state.length) + break; + } + state.readingMore = false; + } + Readable.prototype._read = function(n3) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src2 = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== import_process.default.stdout && dest !== import_process.default.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) + import_process.default.nextTick(endFn); + else + src2.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src2) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src2); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src2.removeListener("end", onend); + src2.removeListener("end", unpipe); + src2.removeListener("data", ondata); + cleanedUp = true; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) + ondrain(); + } + src2.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + var ret = dest.write(chunk); + debug("dest.write", ret); + if (ret === false) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state.awaitDrain); + state.awaitDrain++; + } + src2.pause(); + } + } + function onerror(er) { + debug("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) + errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src2.unpipe(dest); + } + dest.emit("pipe", src2); + if (!state.flowing) { + debug("pipe resume"); + src2.resume(); + } + return dest; + }; + function pipeOnDrain(src2) { + return function pipeOnDrainFunctionResult() { + var state = src2._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src2, "data")) { + state.flowing = true; + flow(src2); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state.pipesCount === 0) + return this; + if (state.pipesCount === 1) { + if (dest && dest !== state.pipes) + return this; + if (!dest) + dest = state.pipes; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) + dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i2 = 0; i2 < len; i2++) + dests[i2].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index = indexOf(state.pipes, dest); + if (index === -1) + return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === "data") { + state.readableListening = this.listenerCount("readable") > 0; + if (state.flowing !== false) + this.resume(); + } else if (ev === "readable") { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug("on readable", state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + import_process.default.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function(ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + import_process.default.nextTick(updateReadableListening, this); + } + return res; + }; + Readable.prototype.removeAllListeners = function(ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + import_process.default.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state = self2._readableState; + state.readableListening = self2.listenerCount("readable") > 0; + if (state.resumeScheduled && !state.paused) { + state.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug("readable nexttick read 0"); + self2.read(0); + } + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + import_process.default.nextTick(resume_, stream, state); + } + } + function resume_(stream, state) { + debug("resume", state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit("resume"); + flow(stream); + if (state.flowing && !state.reading) + stream.read(0); + } + Readable.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream) { + var state = stream._readableState; + debug("flow", state.flowing); + while (state.flowing && stream.read() !== null) + ; + } + Readable.prototype.wrap = function(stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + _this.push(chunk); + } + _this.push(null); + }); + stream.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (state.objectMode && (chunk === null || chunk === void 0)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + for (var i2 in stream) { + if (this[i2] === void 0 && typeof stream[i2] === "function") { + this[i2] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i2); + } + } + for (var n3 = 0; n3 < kProxyEvents.length; n3++) { + stream.on(kProxyEvents[n3], this.emit.bind(this, kProxyEvents[n3])); + } + this._read = function(n4) { + debug("wrapped _read", n4); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = require_async_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.flowing; + }, + set: function set2(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.length; + } + }); + function fromList(n3, state) { + if (state.length === 0) + return null; + var ret; + if (state.objectMode) + ret = state.buffer.shift(); + else if (!n3 || n3 >= state.length) { + if (state.decoder) + ret = state.buffer.join(""); + else if (state.buffer.length === 1) + ret = state.buffer.first(); + else + ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + ret = state.buffer.consume(n3, state.decoder); + } + return ret; + } + function endReadable(stream) { + var state = stream._readableState; + debug("endReadable", state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + import_process.default.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + debug("endReadableNT", state.endEmitted, state.length); + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit("end"); + if (state.autoDestroy) { + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable.from = function(iterable, opts) { + if (from3 === void 0) { + from3 = require_from_browser(); + } + return from3(Readable, iterable, opts); + }; + } + function indexOf(xs, x3) { + for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { + if (xs[i2] === x3) + return i2; + } + return -1; + } + } +}); + +// node_modules/readable-stream/lib/_stream_transform.js +var require_stream_transform = __commonJS({ + "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Transform; + var _require$codes = require_errors_browser().codes; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; + var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + require_inherits_browser()(Transform, Duplex); + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") + this._transform = options.transform; + if (typeof options.flush === "function") + this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n3) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream, er, data) { + if (er) + return stream.emit("error", er); + if (data != null) + stream.push(data); + if (stream._writableState.length) + throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) + throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + } +}); + +// node_modules/readable-stream/lib/_stream_passthrough.js +var require_stream_passthrough = __commonJS({ + "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = PassThrough; + var Transform = require_stream_transform(); + require_inherits_browser()(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { + "use strict"; + init_shim(); + var eos; + function once(callback) { + var called = false; + return function() { + if (called) + return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = require_errors_browser().codes; + var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop(err) { + if (err) + throw err; + } + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on("close", function() { + closed = true; + }); + if (eos === void 0) + eos = require_end_of_stream(); + eos(stream, { + readable: reading, + writable: writing + }, function(err) { + if (err) + return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) + return; + if (destroyed) + return; + destroyed = true; + if (isRequest(stream)) + return stream.abort(); + if (typeof stream.destroy === "function") + return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe(from3, to) { + return from3.pipe(to); + } + function popCallback(streams) { + if (!streams.length) + return noop; + if (typeof streams[streams.length - 1] !== "function") + return noop; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) + streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error; + var destroys = streams.map(function(stream, i2) { + var reading = i2 < streams.length - 1; + var writing = i2 > 0; + return destroyer(stream, reading, writing, function(err) { + if (!error) + error = err; + if (err) + destroys.forEach(call); + if (reading) + return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + module2.exports = pipeline; + } +}); + +// node_modules/readable-stream/readable-browser.js +var require_readable_browser = __commonJS({ + "node_modules/readable-stream/readable-browser.js"(exports2, module2) { + init_shim(); + exports2 = module2.exports = require_stream_readable(); + exports2.Stream = exports2; + exports2.Readable = exports2; + exports2.Writable = require_stream_writable(); + exports2.Duplex = require_stream_duplex(); + exports2.Transform = require_stream_transform(); + exports2.PassThrough = require_stream_passthrough(); + exports2.finished = require_end_of_stream(); + exports2.pipeline = require_pipeline(); + } +}); + +// node_modules/keccak/lib/api/keccak.js +var require_keccak = __commonJS({ + "node_modules/keccak/lib/api/keccak.js"(exports2, module2) { + init_shim(); + var { Transform } = require_readable_browser(); + module2.exports = (KeccakState) => class Keccak extends Transform { + constructor(rate, capacity, delimitedSuffix, hashBitLength, options) { + super(options); + this._rate = rate; + this._capacity = capacity; + this._delimitedSuffix = delimitedSuffix; + this._hashBitLength = hashBitLength; + this._options = options; + this._state = new KeccakState(); + this._state.initialize(rate, capacity); + this._finalized = false; + } + _transform(chunk, encoding, callback) { + let error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + callback(error); + } + _flush(callback) { + let error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } + callback(error); + } + update(data, encoding) { + if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") + throw new TypeError("Data must be a string or a buffer"); + if (this._finalized) + throw new Error("Digest already called"); + if (!import_buffer.Buffer.isBuffer(data)) + data = import_buffer.Buffer.from(data, encoding); + this._state.absorb(data); + return this; + } + digest(encoding) { + if (this._finalized) + throw new Error("Digest already called"); + this._finalized = true; + if (this._delimitedSuffix) + this._state.absorbLastFewBits(this._delimitedSuffix); + let digest2 = this._state.squeeze(this._hashBitLength / 8); + if (encoding !== void 0) + digest2 = digest2.toString(encoding); + this._resetState(); + return digest2; + } + // remove result from memory + _resetState() { + this._state.initialize(this._rate, this._capacity); + return this; + } + // because sometimes we need hash right now and little later + _clone() { + const clone2 = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options); + this._state.copy(clone2._state); + clone2._finalized = this._finalized; + return clone2; + } + }; + } +}); + +// node_modules/keccak/lib/api/shake.js +var require_shake = __commonJS({ + "node_modules/keccak/lib/api/shake.js"(exports2, module2) { + init_shim(); + var { Transform } = require_readable_browser(); + module2.exports = (KeccakState) => class Shake extends Transform { + constructor(rate, capacity, delimitedSuffix, options) { + super(options); + this._rate = rate; + this._capacity = capacity; + this._delimitedSuffix = delimitedSuffix; + this._options = options; + this._state = new KeccakState(); + this._state.initialize(rate, capacity); + this._finalized = false; + } + _transform(chunk, encoding, callback) { + let error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + callback(error); + } + _flush() { + } + _read(size) { + this.push(this.squeeze(size)); + } + update(data, encoding) { + if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") + throw new TypeError("Data must be a string or a buffer"); + if (this._finalized) + throw new Error("Squeeze already called"); + if (!import_buffer.Buffer.isBuffer(data)) + data = import_buffer.Buffer.from(data, encoding); + this._state.absorb(data); + return this; + } + squeeze(dataByteLength, encoding) { + if (!this._finalized) { + this._finalized = true; + this._state.absorbLastFewBits(this._delimitedSuffix); + } + let data = this._state.squeeze(dataByteLength); + if (encoding !== void 0) + data = data.toString(encoding); + return data; + } + _resetState() { + this._state.initialize(this._rate, this._capacity); + return this; + } + _clone() { + const clone2 = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options); + this._state.copy(clone2._state); + clone2._finalized = this._finalized; + return clone2; + } + }; + } +}); + +// node_modules/keccak/lib/api/index.js +var require_api = __commonJS({ + "node_modules/keccak/lib/api/index.js"(exports2, module2) { + init_shim(); + var createKeccak = require_keccak(); + var createShake = require_shake(); + module2.exports = function(KeccakState) { + const Keccak = createKeccak(KeccakState); + const Shake = createShake(KeccakState); + return function(algorithm, options) { + const hash = typeof algorithm === "string" ? algorithm.toLowerCase() : algorithm; + switch (hash) { + case "keccak224": + return new Keccak(1152, 448, null, 224, options); + case "keccak256": + return new Keccak(1088, 512, null, 256, options); + case "keccak384": + return new Keccak(832, 768, null, 384, options); + case "keccak512": + return new Keccak(576, 1024, null, 512, options); + case "sha3-224": + return new Keccak(1152, 448, 6, 224, options); + case "sha3-256": + return new Keccak(1088, 512, 6, 256, options); + case "sha3-384": + return new Keccak(832, 768, 6, 384, options); + case "sha3-512": + return new Keccak(576, 1024, 6, 512, options); + case "shake128": + return new Shake(1344, 256, 31, options); + case "shake256": + return new Shake(1088, 512, 31, options); + default: + throw new Error("Invald algorithm: " + algorithm); + } + }; + }; + } +}); + +// node_modules/keccak/lib/keccak-state-unroll.js +var require_keccak_state_unroll = __commonJS({ + "node_modules/keccak/lib/keccak-state-unroll.js"(exports2) { + init_shim(); + var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + exports2.p1600 = function(s2) { + for (let round = 0; round < 24; ++round) { + const lo0 = s2[0] ^ s2[10] ^ s2[20] ^ s2[30] ^ s2[40]; + const hi0 = s2[1] ^ s2[11] ^ s2[21] ^ s2[31] ^ s2[41]; + const lo1 = s2[2] ^ s2[12] ^ s2[22] ^ s2[32] ^ s2[42]; + const hi1 = s2[3] ^ s2[13] ^ s2[23] ^ s2[33] ^ s2[43]; + const lo2 = s2[4] ^ s2[14] ^ s2[24] ^ s2[34] ^ s2[44]; + const hi2 = s2[5] ^ s2[15] ^ s2[25] ^ s2[35] ^ s2[45]; + const lo3 = s2[6] ^ s2[16] ^ s2[26] ^ s2[36] ^ s2[46]; + const hi3 = s2[7] ^ s2[17] ^ s2[27] ^ s2[37] ^ s2[47]; + const lo4 = s2[8] ^ s2[18] ^ s2[28] ^ s2[38] ^ s2[48]; + const hi4 = s2[9] ^ s2[19] ^ s2[29] ^ s2[39] ^ s2[49]; + let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31); + let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31); + const t1slo0 = s2[0] ^ lo; + const t1shi0 = s2[1] ^ hi; + const t1slo5 = s2[10] ^ lo; + const t1shi5 = s2[11] ^ hi; + const t1slo10 = s2[20] ^ lo; + const t1shi10 = s2[21] ^ hi; + const t1slo15 = s2[30] ^ lo; + const t1shi15 = s2[31] ^ hi; + const t1slo20 = s2[40] ^ lo; + const t1shi20 = s2[41] ^ hi; + lo = lo0 ^ (lo2 << 1 | hi2 >>> 31); + hi = hi0 ^ (hi2 << 1 | lo2 >>> 31); + const t1slo1 = s2[2] ^ lo; + const t1shi1 = s2[3] ^ hi; + const t1slo6 = s2[12] ^ lo; + const t1shi6 = s2[13] ^ hi; + const t1slo11 = s2[22] ^ lo; + const t1shi11 = s2[23] ^ hi; + const t1slo16 = s2[32] ^ lo; + const t1shi16 = s2[33] ^ hi; + const t1slo21 = s2[42] ^ lo; + const t1shi21 = s2[43] ^ hi; + lo = lo1 ^ (lo3 << 1 | hi3 >>> 31); + hi = hi1 ^ (hi3 << 1 | lo3 >>> 31); + const t1slo2 = s2[4] ^ lo; + const t1shi2 = s2[5] ^ hi; + const t1slo7 = s2[14] ^ lo; + const t1shi7 = s2[15] ^ hi; + const t1slo12 = s2[24] ^ lo; + const t1shi12 = s2[25] ^ hi; + const t1slo17 = s2[34] ^ lo; + const t1shi17 = s2[35] ^ hi; + const t1slo22 = s2[44] ^ lo; + const t1shi22 = s2[45] ^ hi; + lo = lo2 ^ (lo4 << 1 | hi4 >>> 31); + hi = hi2 ^ (hi4 << 1 | lo4 >>> 31); + const t1slo3 = s2[6] ^ lo; + const t1shi3 = s2[7] ^ hi; + const t1slo8 = s2[16] ^ lo; + const t1shi8 = s2[17] ^ hi; + const t1slo13 = s2[26] ^ lo; + const t1shi13 = s2[27] ^ hi; + const t1slo18 = s2[36] ^ lo; + const t1shi18 = s2[37] ^ hi; + const t1slo23 = s2[46] ^ lo; + const t1shi23 = s2[47] ^ hi; + lo = lo3 ^ (lo0 << 1 | hi0 >>> 31); + hi = hi3 ^ (hi0 << 1 | lo0 >>> 31); + const t1slo4 = s2[8] ^ lo; + const t1shi4 = s2[9] ^ hi; + const t1slo9 = s2[18] ^ lo; + const t1shi9 = s2[19] ^ hi; + const t1slo14 = s2[28] ^ lo; + const t1shi14 = s2[29] ^ hi; + const t1slo19 = s2[38] ^ lo; + const t1shi19 = s2[39] ^ hi; + const t1slo24 = s2[48] ^ lo; + const t1shi24 = s2[49] ^ hi; + const t2slo0 = t1slo0; + const t2shi0 = t1shi0; + const t2slo16 = t1shi5 << 4 | t1slo5 >>> 28; + const t2shi16 = t1slo5 << 4 | t1shi5 >>> 28; + const t2slo7 = t1slo10 << 3 | t1shi10 >>> 29; + const t2shi7 = t1shi10 << 3 | t1slo10 >>> 29; + const t2slo23 = t1shi15 << 9 | t1slo15 >>> 23; + const t2shi23 = t1slo15 << 9 | t1shi15 >>> 23; + const t2slo14 = t1slo20 << 18 | t1shi20 >>> 14; + const t2shi14 = t1shi20 << 18 | t1slo20 >>> 14; + const t2slo10 = t1slo1 << 1 | t1shi1 >>> 31; + const t2shi10 = t1shi1 << 1 | t1slo1 >>> 31; + const t2slo1 = t1shi6 << 12 | t1slo6 >>> 20; + const t2shi1 = t1slo6 << 12 | t1shi6 >>> 20; + const t2slo17 = t1slo11 << 10 | t1shi11 >>> 22; + const t2shi17 = t1shi11 << 10 | t1slo11 >>> 22; + const t2slo8 = t1shi16 << 13 | t1slo16 >>> 19; + const t2shi8 = t1slo16 << 13 | t1shi16 >>> 19; + const t2slo24 = t1slo21 << 2 | t1shi21 >>> 30; + const t2shi24 = t1shi21 << 2 | t1slo21 >>> 30; + const t2slo20 = t1shi2 << 30 | t1slo2 >>> 2; + const t2shi20 = t1slo2 << 30 | t1shi2 >>> 2; + const t2slo11 = t1slo7 << 6 | t1shi7 >>> 26; + const t2shi11 = t1shi7 << 6 | t1slo7 >>> 26; + const t2slo2 = t1shi12 << 11 | t1slo12 >>> 21; + const t2shi2 = t1slo12 << 11 | t1shi12 >>> 21; + const t2slo18 = t1slo17 << 15 | t1shi17 >>> 17; + const t2shi18 = t1shi17 << 15 | t1slo17 >>> 17; + const t2slo9 = t1shi22 << 29 | t1slo22 >>> 3; + const t2shi9 = t1slo22 << 29 | t1shi22 >>> 3; + const t2slo5 = t1slo3 << 28 | t1shi3 >>> 4; + const t2shi5 = t1shi3 << 28 | t1slo3 >>> 4; + const t2slo21 = t1shi8 << 23 | t1slo8 >>> 9; + const t2shi21 = t1slo8 << 23 | t1shi8 >>> 9; + const t2slo12 = t1slo13 << 25 | t1shi13 >>> 7; + const t2shi12 = t1shi13 << 25 | t1slo13 >>> 7; + const t2slo3 = t1slo18 << 21 | t1shi18 >>> 11; + const t2shi3 = t1shi18 << 21 | t1slo18 >>> 11; + const t2slo19 = t1shi23 << 24 | t1slo23 >>> 8; + const t2shi19 = t1slo23 << 24 | t1shi23 >>> 8; + const t2slo15 = t1slo4 << 27 | t1shi4 >>> 5; + const t2shi15 = t1shi4 << 27 | t1slo4 >>> 5; + const t2slo6 = t1slo9 << 20 | t1shi9 >>> 12; + const t2shi6 = t1shi9 << 20 | t1slo9 >>> 12; + const t2slo22 = t1shi14 << 7 | t1slo14 >>> 25; + const t2shi22 = t1slo14 << 7 | t1shi14 >>> 25; + const t2slo13 = t1slo19 << 8 | t1shi19 >>> 24; + const t2shi13 = t1shi19 << 8 | t1slo19 >>> 24; + const t2slo4 = t1slo24 << 14 | t1shi24 >>> 18; + const t2shi4 = t1shi24 << 14 | t1slo24 >>> 18; + s2[0] = t2slo0 ^ ~t2slo1 & t2slo2; + s2[1] = t2shi0 ^ ~t2shi1 & t2shi2; + s2[10] = t2slo5 ^ ~t2slo6 & t2slo7; + s2[11] = t2shi5 ^ ~t2shi6 & t2shi7; + s2[20] = t2slo10 ^ ~t2slo11 & t2slo12; + s2[21] = t2shi10 ^ ~t2shi11 & t2shi12; + s2[30] = t2slo15 ^ ~t2slo16 & t2slo17; + s2[31] = t2shi15 ^ ~t2shi16 & t2shi17; + s2[40] = t2slo20 ^ ~t2slo21 & t2slo22; + s2[41] = t2shi20 ^ ~t2shi21 & t2shi22; + s2[2] = t2slo1 ^ ~t2slo2 & t2slo3; + s2[3] = t2shi1 ^ ~t2shi2 & t2shi3; + s2[12] = t2slo6 ^ ~t2slo7 & t2slo8; + s2[13] = t2shi6 ^ ~t2shi7 & t2shi8; + s2[22] = t2slo11 ^ ~t2slo12 & t2slo13; + s2[23] = t2shi11 ^ ~t2shi12 & t2shi13; + s2[32] = t2slo16 ^ ~t2slo17 & t2slo18; + s2[33] = t2shi16 ^ ~t2shi17 & t2shi18; + s2[42] = t2slo21 ^ ~t2slo22 & t2slo23; + s2[43] = t2shi21 ^ ~t2shi22 & t2shi23; + s2[4] = t2slo2 ^ ~t2slo3 & t2slo4; + s2[5] = t2shi2 ^ ~t2shi3 & t2shi4; + s2[14] = t2slo7 ^ ~t2slo8 & t2slo9; + s2[15] = t2shi7 ^ ~t2shi8 & t2shi9; + s2[24] = t2slo12 ^ ~t2slo13 & t2slo14; + s2[25] = t2shi12 ^ ~t2shi13 & t2shi14; + s2[34] = t2slo17 ^ ~t2slo18 & t2slo19; + s2[35] = t2shi17 ^ ~t2shi18 & t2shi19; + s2[44] = t2slo22 ^ ~t2slo23 & t2slo24; + s2[45] = t2shi22 ^ ~t2shi23 & t2shi24; + s2[6] = t2slo3 ^ ~t2slo4 & t2slo0; + s2[7] = t2shi3 ^ ~t2shi4 & t2shi0; + s2[16] = t2slo8 ^ ~t2slo9 & t2slo5; + s2[17] = t2shi8 ^ ~t2shi9 & t2shi5; + s2[26] = t2slo13 ^ ~t2slo14 & t2slo10; + s2[27] = t2shi13 ^ ~t2shi14 & t2shi10; + s2[36] = t2slo18 ^ ~t2slo19 & t2slo15; + s2[37] = t2shi18 ^ ~t2shi19 & t2shi15; + s2[46] = t2slo23 ^ ~t2slo24 & t2slo20; + s2[47] = t2shi23 ^ ~t2shi24 & t2shi20; + s2[8] = t2slo4 ^ ~t2slo0 & t2slo1; + s2[9] = t2shi4 ^ ~t2shi0 & t2shi1; + s2[18] = t2slo9 ^ ~t2slo5 & t2slo6; + s2[19] = t2shi9 ^ ~t2shi5 & t2shi6; + s2[28] = t2slo14 ^ ~t2slo10 & t2slo11; + s2[29] = t2shi14 ^ ~t2shi10 & t2shi11; + s2[38] = t2slo19 ^ ~t2slo15 & t2slo16; + s2[39] = t2shi19 ^ ~t2shi15 & t2shi16; + s2[48] = t2slo24 ^ ~t2slo20 & t2slo21; + s2[49] = t2shi24 ^ ~t2shi20 & t2shi21; + s2[0] ^= P1600_ROUND_CONSTANTS[round * 2]; + s2[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]; + } + }; + } +}); + +// node_modules/keccak/lib/keccak.js +var require_keccak2 = __commonJS({ + "node_modules/keccak/lib/keccak.js"(exports2, module2) { + init_shim(); + var keccakState = require_keccak_state_unroll(); + function Keccak() { + this.state = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + this.blockSize = null; + this.count = 0; + this.squeezing = false; + } + Keccak.prototype.initialize = function(rate, capacity) { + for (let i2 = 0; i2 < 50; ++i2) + this.state[i2] = 0; + this.blockSize = rate / 8; + this.count = 0; + this.squeezing = false; + }; + Keccak.prototype.absorb = function(data) { + for (let i2 = 0; i2 < data.length; ++i2) { + this.state[~~(this.count / 4)] ^= data[i2] << 8 * (this.count % 4); + this.count += 1; + if (this.count === this.blockSize) { + keccakState.p1600(this.state); + this.count = 0; + } + } + }; + Keccak.prototype.absorbLastFewBits = function(bits) { + this.state[~~(this.count / 4)] ^= bits << 8 * (this.count % 4); + if ((bits & 128) !== 0 && this.count === this.blockSize - 1) + keccakState.p1600(this.state); + this.state[~~((this.blockSize - 1) / 4)] ^= 128 << 8 * ((this.blockSize - 1) % 4); + keccakState.p1600(this.state); + this.count = 0; + this.squeezing = true; + }; + Keccak.prototype.squeeze = function(length2) { + if (!this.squeezing) + this.absorbLastFewBits(1); + const output = import_buffer.Buffer.alloc(length2); + for (let i2 = 0; i2 < length2; ++i2) { + output[i2] = this.state[~~(this.count / 4)] >>> 8 * (this.count % 4) & 255; + this.count += 1; + if (this.count === this.blockSize) { + keccakState.p1600(this.state); + this.count = 0; + } + } + return output; + }; + Keccak.prototype.copy = function(dest) { + for (let i2 = 0; i2 < 50; ++i2) + dest.state[i2] = this.state[i2]; + dest.blockSize = this.blockSize; + dest.count = this.count; + dest.squeezing = this.squeezing; + }; + module2.exports = Keccak; + } +}); + +// node_modules/keccak/js.js +var require_js = __commonJS({ + "node_modules/keccak/js.js"(exports2, module2) { + init_shim(); + module2.exports = require_api()(require_keccak2()); + } +}); + +// node_modules/@multiversx/sdk-core/out/address.js +var require_address = __commonJS({ + "node_modules/@multiversx/sdk-core/out/address.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AddressComputer = exports2.Address = void 0; + var bech32 = __importStar2(require_bech32()); + var bignumber_js_1 = __importDefault2(require_bignumber()); + var constants_1 = require_constants(); + var errors = __importStar2(require_errors()); + var codec_1 = require_codec(); + var createKeccakHash = require_js(); + var HRP = "erd"; + var PUBKEY_LENGTH = 32; + var SMART_CONTRACT_HEX_PUBKEY_PREFIX = "0".repeat(16); + var Address5 = class _Address { + /** + * Creates an address object, given a raw string (whether a hex pubkey or a Bech32 address), a sequence of bytes, or another Address object. + */ + constructor(value) { + this.valueHex = ""; + if (!value) { + return; + } + if (value instanceof _Address) { + return _Address.fromAddress(value); + } + if (ArrayBuffer.isView(value)) { + return _Address.fromBuffer(import_buffer.Buffer.from(value)); + } + if (typeof value === "string") { + return _Address.fromString(value); + } + throw new errors.ErrAddressCannotCreate(value); + } + /** + * Creates an address object from another address object + */ + static fromAddress(address) { + return _Address.fromValidHex(address.valueHex); + } + static fromValidHex(value) { + let result = _Address.empty(); + result.valueHex = value; + return result; + } + /** + * Creates an address object from a Buffer + */ + static fromBuffer(buffer) { + if (buffer.length != PUBKEY_LENGTH) { + throw new errors.ErrAddressCannotCreate(buffer); + } + return _Address.fromValidHex(buffer.toString("hex")); + } + /** + * Creates an address object from a string (hex or bech32) + */ + static fromString(value) { + if (_Address.isValidHex(value)) { + return _Address.fromValidHex(value); + } + return _Address.fromBech32(value); + } + static isValidHex(value) { + return import_buffer.Buffer.from(value, "hex").length == PUBKEY_LENGTH; + } + /** + * Creates an address object from a hex-encoded string + */ + static fromHex(value) { + if (!_Address.isValidHex(value)) { + throw new errors.ErrAddressCannotCreate(value); + } + return _Address.fromValidHex(value); + } + /** + * Creates an empty address object. + * Generally speaking, this should not be used by client code (internal use only). + */ + static empty() { + return new _Address(""); + } + /** + * Creates an address object from a bech32-encoded string + */ + static fromBech32(value) { + let decoded; + try { + decoded = bech32.decode(value); + } catch (err) { + throw new errors.ErrAddressCannotCreate(value, err); + } + const prefix = decoded.prefix; + if (prefix != HRP) { + throw new errors.ErrAddressBadHrp(HRP, prefix); + } + const pubkey = import_buffer.Buffer.from(bech32.fromWords(decoded.words)); + if (pubkey.length != PUBKEY_LENGTH) { + throw new errors.ErrAddressCannotCreate(value); + } + return _Address.fromValidHex(pubkey.toString("hex")); + } + /** + * Performs address validation without throwing errors + */ + static isValid(value) { + const decoded = bech32.decodeUnsafe(value); + const prefix = decoded?.prefix; + const pubkey = decoded ? import_buffer.Buffer.from(bech32.fromWords(decoded.words)) : void 0; + if (prefix !== HRP || pubkey?.length !== PUBKEY_LENGTH) { + return false; + } + return true; + } + /** + * Use {@link toHex} instead. + */ + hex() { + return this.toHex(); + } + /** + * Returns the hex representation of the address (pubkey) + */ + toHex() { + if (this.isEmpty()) { + return ""; + } + return this.valueHex; + } + /** + * Use {@link toBech32} instead. + */ + bech32() { + return this.toBech32(); + } + /** + * Returns the bech32 representation of the address + */ + toBech32() { + if (this.isEmpty()) { + return ""; + } + let words = bech32.toWords(this.pubkey()); + let address = bech32.encode(HRP, words); + return address; + } + /** + * Use {@link getPublicKey} instead. + */ + pubkey() { + return this.getPublicKey(); + } + /** + * Returns the pubkey as raw bytes (buffer) + */ + getPublicKey() { + if (this.isEmpty()) { + return import_buffer.Buffer.from([]); + } + return import_buffer.Buffer.from(this.valueHex, "hex"); + } + /** + * Returns the human-readable-part of the bech32 addresses. + * The HRP is currently hardcoded to "erd". + */ + getHrp() { + return HRP; + } + /** + * Returns whether the address is empty. + */ + isEmpty() { + return !this.valueHex; + } + /** + * Compares the address to another address + */ + equals(other) { + if (!other) { + return false; + } + return this.valueHex == other.valueHex; + } + /** + * Returns the bech32 representation of the address + */ + toString() { + return this.toBech32(); + } + /** + * Converts the address to a pretty, plain JavaScript object. + */ + toJSON() { + return { + bech32: this.toBech32(), + pubkey: this.toHex() + }; + } + /** + * Creates the Zero address (the one that should be used when deploying smart contracts). + * Generally speaking, this should not be used by client code (internal use only). + */ + static Zero() { + return new _Address("0".repeat(64)); + } + /** + * Use {@link isSmartContract} instead. + */ + isContractAddress() { + return this.isSmartContract(); + } + /** + * Returns whether the address is a smart contract address. + */ + isSmartContract() { + return this.toHex().startsWith(SMART_CONTRACT_HEX_PUBKEY_PREFIX); + } + }; + exports2.Address = Address5; + var AddressComputer = class { + constructor(numberOfShardsWithoutMeta) { + this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || constants_1.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; + } + computeContractAddress(deployer, deploymentNonce) { + const initialPadding = import_buffer.Buffer.alloc(8, 0); + const ownerPubkey = deployer.getPublicKey(); + const shardSelector = ownerPubkey.slice(30); + const ownerNonceBytes = import_buffer.Buffer.alloc(8); + const bigNonce = new bignumber_js_1.default(deploymentNonce.toString()); + const bigNonceBuffer = codec_1.bigIntToBuffer(bigNonce); + ownerNonceBytes.write(bigNonceBuffer.reverse().toString("hex"), "hex"); + const bytesToHash = import_buffer.Buffer.concat([ownerPubkey, ownerNonceBytes]); + const hash = createKeccakHash("keccak256").update(bytesToHash).digest(); + const vmTypeBytes = import_buffer.Buffer.from(constants_1.WasmVirtualMachine, "hex"); + const addressBytes = import_buffer.Buffer.concat([initialPadding, vmTypeBytes, hash.slice(10, 30), shardSelector]); + return new Address5(addressBytes); + } + getShardOfAddress(address) { + return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); + } + getShardOfPubkey(pubkey, numberOfShards) { + const maskHigh = parseInt("11", 2); + const maskLow = parseInt("01", 2); + const lastByteOfPubkey = pubkey[31]; + if (this.isPubkeyOfMetachain(pubkey)) { + return constants_1.METACHAIN_ID; + } + let shard = lastByteOfPubkey & maskHigh; + if (shard > numberOfShards - 1) { + shard = lastByteOfPubkey & maskLow; + } + return shard; + } + isPubkeyOfMetachain(pubkey) { + const metachainPrefix = import_buffer.Buffer.from([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]); + const pubkeyPrefix = import_buffer.Buffer.from(pubkey).slice(0, metachainPrefix.length); + if (metachainPrefix.equals(pubkeyPrefix)) { + return true; + } + const zeroAddress = import_buffer.Buffer.alloc(32); + if (zeroAddress.equals(import_buffer.Buffer.from(pubkey))) { + return true; + } + return false; + } + }; + exports2.AddressComputer = AddressComputer; + } +}); + +// node_modules/@multiversx/sdk-core/out/utils.js +var require_utils2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/utils.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isEmpty = exports2.guardEmpty = exports2.guardNotEmpty = exports2.guardLength = exports2.guardSameLength = exports2.guardValueIsSetWithMessage = exports2.guardValueIsSet = exports2.guardTrue = void 0; + var errors = __importStar2(require_errors()); + function guardTrue(value, what) { + if (!value) { + throw new errors.ErrInvariantFailed(`[<${what}>] isn't true`); + } + } + exports2.guardTrue = guardTrue; + function guardValueIsSet(name2, value) { + guardValueIsSetWithMessage(`${name2} isn't set (null or undefined)`, value); + } + exports2.guardValueIsSet = guardValueIsSet; + function guardValueIsSetWithMessage(message, value) { + if (value == null || value === void 0) { + throw new errors.ErrInvariantFailed(message); + } + } + exports2.guardValueIsSetWithMessage = guardValueIsSetWithMessage; + function guardSameLength(a3, b4) { + a3 = a3 || []; + b4 = b4 || []; + if (a3.length != b4.length) { + throw new errors.ErrInvariantFailed("arrays do not have the same length"); + } + } + exports2.guardSameLength = guardSameLength; + function guardLength(withLength, expectedLength) { + let actualLength = withLength.length || 0; + if (actualLength != expectedLength) { + throw new errors.ErrInvariantFailed(`wrong length, expected: ${expectedLength}, actual: ${actualLength}`); + } + } + exports2.guardLength = guardLength; + function guardNotEmpty(value, what) { + if (isEmpty(value)) { + throw new errors.ErrInvariantFailed(`${what} is empty`); + } + } + exports2.guardNotEmpty = guardNotEmpty; + function guardEmpty(value, what) { + if (!isEmpty(value)) { + throw new errors.ErrInvariantFailed(`${what} is not empty`); + } + } + exports2.guardEmpty = guardEmpty; + function isEmpty(value) { + if (value.isEmpty) { + return value.isEmpty(); + } + return value.length === 0; + } + exports2.isEmpty = isEmpty; + } +}); + +// node_modules/@multiversx/sdk-core/out/abi/typeFormula.js +var require_typeFormula = __commonJS({ + "node_modules/@multiversx/sdk-core/out/abi/typeFormula.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeFormula = void 0; + var TypeFormula = class { + constructor(name2, typeParameters) { + this.name = name2; + this.typeParameters = typeParameters; + } + toString() { + if (this.typeParameters.length > 0) { + const typeParameters = this.typeParameters.map((typeParameter) => typeParameter.toString()).join(", "); + return `${this.name}<${typeParameters}>`; + } else { + return this.name; + } + } + }; + exports2.TypeFormula = TypeFormula; + } +}); + +// node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js +var require_typeFormulaParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeFormulaParser = void 0; + var typeFormula_1 = require_typeFormula(); + var TypeFormulaParser = class _TypeFormulaParser { + parseExpression(expression) { + expression = expression.trim(); + const tokens = this.tokenizeExpression(expression).filter((token) => token !== _TypeFormulaParser.COMMA); + const stack = []; + for (const token of tokens) { + if (this.isPunctuation(token)) { + if (this.isEndOfTypeParameters(token)) { + const typeFormula = this.acquireTypeWithParameters(stack); + stack.push(typeFormula); + } else if (this.isBeginningOfTypeParameters(token)) { + stack.push(token); + } else { + throw new Error(`Unexpected token (punctuation): ${token}`); + } + } else { + stack.push(token); + } + } + if (stack.length !== 1) { + throw new Error(`Unexpected stack length at end of parsing: ${stack.length}`); + } + if (_TypeFormulaParser.PUNCTUATION.includes(stack[0])) { + throw new Error("Unexpected root element."); + } + const item = stack[0]; + if (item instanceof typeFormula_1.TypeFormula) { + return item; + } else if (typeof item === "string") { + return new typeFormula_1.TypeFormula(item, []); + } else { + throw new Error(`Unexpected item on stack: ${item}`); + } + } + tokenizeExpression(expression) { + const tokens = []; + let currentToken = ""; + for (const character of expression) { + if (this.isPunctuation(character)) { + if (currentToken) { + tokens.push(currentToken.trim()); + currentToken = ""; + } + tokens.push(character); + } else { + currentToken += character; + } + } + if (currentToken) { + tokens.push(currentToken.trim()); + } + return tokens; + } + acquireTypeWithParameters(stack) { + const typeParameters = this.acquireTypeParameters(stack); + const typeName = stack.pop(); + const typeFormula = new typeFormula_1.TypeFormula(typeName, typeParameters.reverse()); + return typeFormula; + } + acquireTypeParameters(stack) { + const typeParameters = []; + while (true) { + const item = stack.pop(); + if (item === void 0) { + throw new Error("Badly specified type parameters"); + } + if (this.isBeginningOfTypeParameters(item)) { + break; + } + if (item instanceof typeFormula_1.TypeFormula) { + typeParameters.push(item); + } else if (typeof item === "string") { + typeParameters.push(new typeFormula_1.TypeFormula(item, [])); + } else { + throw new Error(`Unexpected type parameter object in stack: ${item}`); + } + } + return typeParameters; + } + isPunctuation(token) { + return _TypeFormulaParser.PUNCTUATION.includes(token); + } + isEndOfTypeParameters(token) { + return token === _TypeFormulaParser.END_TYPE_PARAMETERS; + } + isBeginningOfTypeParameters(token) { + return token === _TypeFormulaParser.BEGIN_TYPE_PARAMETERS; + } + }; + exports2.TypeFormulaParser = TypeFormulaParser; + TypeFormulaParser.BEGIN_TYPE_PARAMETERS = "<"; + TypeFormulaParser.END_TYPE_PARAMETERS = ">"; + TypeFormulaParser.COMMA = ","; + TypeFormulaParser.PUNCTUATION = [ + TypeFormulaParser.COMMA, + TypeFormulaParser.BEGIN_TYPE_PARAMETERS, + TypeFormulaParser.END_TYPE_PARAMETERS + ]; + } +}); + +// node_modules/@multiversx/sdk-core/out/reflection.js +var require_reflection = __commonJS({ + "node_modules/@multiversx/sdk-core/out/reflection.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getJavascriptPrototypesInHierarchy = void 0; + function getJavascriptPrototypesInHierarchy(obj, filter) { + let prototypes = []; + let prototype = Object.getPrototypeOf(obj); + while (prototype && filter(prototype)) { + prototypes.push(prototype); + prototype = Object.getPrototypeOf(prototype); + } + return prototypes; + } + exports2.getJavascriptPrototypesInHierarchy = getJavascriptPrototypesInHierarchy; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js +var require_types = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NullType = exports2.TypePlaceholder = exports2.isTyped = exports2.PrimitiveValue = exports2.TypedValue = exports2.CustomType = exports2.PrimitiveType = exports2.TypeCardinality = exports2.Type = void 0; + var reflection_1 = require_reflection(); + var utils_1 = require_utils2(); + var Type = class _Type { + constructor(name2, typeParameters = [], cardinality = TypeCardinality.fixed(1)) { + utils_1.guardValueIsSet("name", name2); + this.name = name2; + this.typeParameters = typeParameters; + this.cardinality = cardinality; + } + getName() { + return this.name; + } + getClassName() { + return _Type.ClassName; + } + getClassHierarchy() { + let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); + let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); + return classNames; + } + /** + * Gets the fully qualified name of the type, to allow for better (efficient and non-ambiguous) type comparison within the custom typesystem. + */ + getFullyQualifiedName() { + let joinedTypeParameters = this.getTypeParameters().map((type) => type.getFullyQualifiedName()).join(", "); + return this.isGenericType() ? `multiversx:types:${this.getName()}<${joinedTypeParameters}>` : `multiversx:types:${this.getName()}`; + } + hasExactClass(className) { + return this.getClassName() == className; + } + hasClassOrSuperclass(className) { + let hierarchy = this.getClassHierarchy(); + return hierarchy.includes(className); + } + getTypeParameters() { + return this.typeParameters; + } + isGenericType() { + return this.typeParameters.length > 0; + } + getFirstTypeParameter() { + utils_1.guardTrue(this.typeParameters.length > 0, "type parameters length > 0"); + return this.typeParameters[0]; + } + /** + * Generates type expressions similar to mx-sdk-rs. + */ + toString() { + let typeParameters = this.getTypeParameters().map((type) => type.toString()).join(", "); + let typeParametersExpression = typeParameters ? `<${typeParameters}>` : ""; + return `${this.name}${typeParametersExpression}`; + } + equals(other) { + return _Type.equals(this, other); + } + static equals(a3, b4) { + return a3.getFullyQualifiedName() == b4.getFullyQualifiedName(); + } + static equalsMany(a3, b4) { + return a3.every((type, i2) => type.equals(b4[i2])); + } + static isAssignableFromMany(a3, b4) { + return a3.every((type, i2) => type.isAssignableFrom(b4[i2])); + } + differs(other) { + return !this.equals(other); + } + valueOf() { + return this.name; + } + /** + * Inspired from: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom + * For (most) generics, type invariance is expected (assumed) - neither covariance, nor contravariance are supported yet (will be supported in a next release). + * + * One exception though: for {@link OptionType}, we simulate covariance for missing (not provided) values. + * For example, Option is assignable from Option. + * For more details, see the implementation of {@link OptionType} and @{@link OptionalType}. + * + * Also see: + * - https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) + * - https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance + */ + isAssignableFrom(other) { + let invariantTypeParameters = _Type.equalsMany(this.getTypeParameters(), other.getTypeParameters()); + if (!invariantTypeParameters) { + return false; + } + let fullyQualifiedNameOfThis = this.getFullyQualifiedName(); + let fullyQualifiedNamesInHierarchyOfOther = _Type.getFullyQualifiedNamesInHierarchy(other); + if (fullyQualifiedNamesInHierarchyOfOther.includes(fullyQualifiedNameOfThis)) { + return true; + } + return other.hasClassOrSuperclass(this.getClassName()); + } + static getFullyQualifiedNamesInHierarchy(type) { + let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(type, (prototype) => prototype.belongsToTypesystem); + let fullyQualifiedNames = prototypes.map((prototype) => prototype.getFullyQualifiedName.call(type)); + return fullyQualifiedNames; + } + getNamesOfDependencies() { + const dependencies = []; + for (const type of this.typeParameters) { + dependencies.push(type.getName()); + dependencies.push(...type.getNamesOfDependencies()); + } + return [...new Set(dependencies)]; + } + /** + * Converts the account to a pretty, plain JavaScript object. + */ + toJSON() { + return { + name: this.name, + typeParameters: this.typeParameters.map((item) => item.toJSON()) + }; + } + getCardinality() { + return this.cardinality; + } + /** + * A special marker for types within the custom typesystem. + */ + belongsToTypesystem() { + } + }; + exports2.Type = Type; + Type.ClassName = "Type"; + var TypeCardinality = class _TypeCardinality { + constructor(lowerBound, upperBound) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + } + static fixed(value) { + return new _TypeCardinality(value, value); + } + static variable(value) { + return new _TypeCardinality(0, value); + } + isSingular() { + return this.lowerBound == 1 && this.upperBound == 1; + } + isSingularOrNone() { + return this.lowerBound == 0 && this.upperBound == 1; + } + isComposite() { + return this.upperBound != 1; + } + isFixed() { + return this.lowerBound == this.upperBound; + } + getLowerBound() { + return this.lowerBound; + } + getUpperBound() { + return this.upperBound || _TypeCardinality.MaxCardinality; + } + }; + exports2.TypeCardinality = TypeCardinality; + TypeCardinality.MaxCardinality = 4096; + var PrimitiveType = class _PrimitiveType extends Type { + constructor(name2) { + super(name2); + } + getClassName() { + return _PrimitiveType.ClassName; + } + }; + exports2.PrimitiveType = PrimitiveType; + PrimitiveType.ClassName = "PrimitiveType"; + var CustomType = class _CustomType extends Type { + getClassName() { + return _CustomType.ClassName; + } + }; + exports2.CustomType = CustomType; + CustomType.ClassName = "CustomType"; + var TypedValue = class _TypedValue { + constructor(type) { + this.type = type; + } + getClassName() { + return _TypedValue.ClassName; + } + getClassHierarchy() { + let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); + let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); + return classNames; + } + getType() { + return this.type; + } + hasExactClass(className) { + return this.getClassName() == className; + } + hasClassOrSuperclass(className) { + let hierarchy = this.getClassHierarchy(); + return hierarchy.includes(className); + } + /** + * A special marker for values within the custom typesystem. + */ + belongsToTypesystem() { + } + }; + exports2.TypedValue = TypedValue; + TypedValue.ClassName = "TypedValue"; + var PrimitiveValue = class _PrimitiveValue extends TypedValue { + constructor(type) { + super(type); + } + getClassName() { + return _PrimitiveValue.ClassName; + } + }; + exports2.PrimitiveValue = PrimitiveValue; + PrimitiveValue.ClassName = "PrimitiveValue"; + function isTyped(value) { + return value.belongsToTypesystem !== void 0; + } + exports2.isTyped = isTyped; + var TypePlaceholder = class _TypePlaceholder extends Type { + constructor() { + super("..."); + } + getClassName() { + return _TypePlaceholder.ClassName; + } + }; + exports2.TypePlaceholder = TypePlaceholder; + TypePlaceholder.ClassName = "TypePlaceholder"; + var NullType = class _NullType extends Type { + constructor() { + super("?"); + } + getClassName() { + return _NullType.ClassName; + } + }; + exports2.NullType = NullType; + NullType.ClassName = "NullType"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js +var require_typeExpressionParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeExpressionParser = void 0; + var typeFormulaParser_1 = require_typeFormulaParser(); + var errors_1 = require_errors(); + var types_1 = require_types(); + var TypeExpressionParser = class { + constructor() { + this.backingTypeFormulaParser = new typeFormulaParser_1.TypeFormulaParser(); + } + parse(expression) { + try { + return this.doParse(expression); + } catch (e2) { + throw new errors_1.ErrTypingSystem(`Failed to parse type expression: ${expression}. Error: ${e2}`); + } + } + doParse(expression) { + const typeFormula = this.backingTypeFormulaParser.parseExpression(expression); + const type = this.typeFormulaToType(typeFormula); + return type; + } + typeFormulaToType(typeFormula) { + const typeParameters = typeFormula.typeParameters.map((typeFormula2) => this.typeFormulaToType(typeFormula2)); + return new types_1.Type(typeFormula.name, typeParameters); + } + }; + exports2.TypeExpressionParser = TypeExpressionParser; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js +var require_endpoint = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EndpointParameterDefinition = exports2.EndpointModifiers = exports2.EndpointDefinition = void 0; + var typeExpressionParser_1 = require_typeExpressionParser(); + var NamePlaceholder = "?"; + var DescriptionPlaceholder = "N / A"; + var EndpointDefinition = class _EndpointDefinition { + constructor(name2, input, output, modifiers) { + this.input = []; + this.output = []; + this.name = name2; + this.input = input || []; + this.output = output || []; + this.modifiers = modifiers; + } + isConstructor() { + return this.name == "constructor"; + } + static fromJSON(json) { + json.name = json.name == null ? NamePlaceholder : json.name; + json.onlyOwner = json.onlyOwner || false; + json.payableInTokens = json.payableInTokens || []; + json.inputs = json.inputs || []; + json.outputs = json.outputs || []; + let input = json.inputs.map((param) => EndpointParameterDefinition.fromJSON(param)); + let output = json.outputs.map((param) => EndpointParameterDefinition.fromJSON(param)); + let modifiers = new EndpointModifiers(json.mutability, json.payableInTokens, json.onlyOwner); + return new _EndpointDefinition(json.name, input, output, modifiers); + } + }; + exports2.EndpointDefinition = EndpointDefinition; + var EndpointModifiers = class { + constructor(mutability, payableInTokens, onlyOwner) { + this.mutability = mutability || ""; + this.payableInTokens = payableInTokens || []; + this.onlyOwner = onlyOwner || false; + } + isPayableInEGLD() { + return this.isPayableInToken("EGLD"); + } + isPayableInToken(token) { + if (this.payableInTokens.includes(token)) { + return true; + } + if (this.payableInTokens.includes(`!${token}`)) { + return false; + } + if (this.payableInTokens.includes("*")) { + return true; + } + return false; + } + isPayable() { + return this.payableInTokens.length != 0; + } + isReadonly() { + return this.mutability == "readonly"; + } + isOnlyOwner() { + return this.onlyOwner; + } + }; + exports2.EndpointModifiers = EndpointModifiers; + var EndpointParameterDefinition = class _EndpointParameterDefinition { + constructor(name2, description, type) { + this.name = name2; + this.description = description; + this.type = type; + } + static fromJSON(json) { + let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); + return new _EndpointParameterDefinition(json.name || NamePlaceholder, json.description || DescriptionPlaceholder, parsedType); + } + }; + exports2.EndpointParameterDefinition = EndpointParameterDefinition; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js +var require_fields = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Fields = exports2.Field = exports2.FieldDefinition = void 0; + var errors = __importStar2(require_errors()); + var typeExpressionParser_1 = require_typeExpressionParser(); + var FieldDefinition = class _FieldDefinition { + constructor(name2, description, type) { + this.name = name2; + this.description = description; + this.type = type; + } + static fromJSON(json) { + let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); + return new _FieldDefinition(json.name, json.description, parsedType); + } + }; + exports2.FieldDefinition = FieldDefinition; + var Field = class { + constructor(value, name2 = "") { + this.value = value; + this.name = name2; + } + checkTyping(expectedDefinition) { + const actualType = this.value.getType(); + if (!actualType.equals(expectedDefinition.type)) { + throw new errors.ErrTypingSystem(`check type of field "${expectedDefinition.name}; expected: ${expectedDefinition.type}, actual: ${actualType}"`); + } + if (this.name != expectedDefinition.name) { + throw new errors.ErrTypingSystem(`check name of field "${expectedDefinition.name}"`); + } + } + equals(other) { + return this.name == other.name && this.value.equals(other.value); + } + }; + exports2.Field = Field; + var Fields = class { + static checkTyping(fields, definitions) { + if (fields.length != definitions.length) { + throw new errors.ErrTypingSystem("fields length vs. field definitions length"); + } + for (let i2 = 0; i2 < fields.length; i2++) { + let field = fields[i2]; + let definition = definitions[i2]; + field.checkTyping(definition); + } + } + static equals(actual, expected) { + if (actual.length != expected.length) { + return false; + } + for (let i2 = 0; i2 < actual.length; i2++) { + let selfField = actual[i2]; + let otherField = expected[i2]; + if (!selfField.equals(otherField)) { + return false; + } + } + return true; + } + static getNamesOfTypeDependencies(definitions) { + const dependencies = []; + for (const definition of definitions) { + dependencies.push(definition.type.getName()); + dependencies.push(...definition.type.getNamesOfDependencies()); + } + return [...new Set(dependencies)]; + } + }; + exports2.Fields = Fields; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js +var require_enum = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EnumValue = exports2.EnumVariantDefinition = exports2.EnumType = void 0; + var errors_1 = require_errors(); + var utils_1 = require_utils2(); + var fields_1 = require_fields(); + var types_1 = require_types(); + var SimpleEnumMaxDiscriminant = 256; + var EnumType = class _EnumType extends types_1.CustomType { + constructor(name2, variants) { + super(name2); + this.variants = []; + this.variants = variants; + } + getClassName() { + return _EnumType.ClassName; + } + static fromJSON(json) { + const rawVariants = _EnumType.assignMissingDiscriminants(json.variants || []); + const variants = rawVariants.map((variant) => EnumVariantDefinition.fromJSON(variant)); + return new _EnumType(json.name, variants); + } + // For some enums (e.g. some "explicit-enum" types), the discriminants are missing. + static assignMissingDiscriminants(variants) { + const allDiscriminantsAreMissing = variants.every((variant) => variant.discriminant == void 0); + if (!allDiscriminantsAreMissing) { + return variants; + } + return variants.map((variant, index) => { + return { + ...variant, + discriminant: index + }; + }); + } + getVariantByDiscriminant(discriminant) { + let result = this.variants.find((e2) => e2.discriminant == discriminant); + utils_1.guardValueIsSet(`variant by discriminant (${discriminant})`, result); + return result; + } + getVariantByName(name2) { + let result = this.variants.find((e2) => e2.name == name2); + utils_1.guardValueIsSet(`variant by name (${name2})`, result); + return result; + } + getNamesOfDependencies() { + const dependencies = []; + for (const variant of this.variants) { + dependencies.push(...variant.getNamesOfDependencies()); + } + return [...new Set(dependencies)]; + } + }; + exports2.EnumType = EnumType; + EnumType.ClassName = "EnumType"; + var EnumVariantDefinition = class _EnumVariantDefinition { + constructor(name2, discriminant, fieldsDefinitions = []) { + this.fieldsDefinitions = []; + utils_1.guardTrue(discriminant < SimpleEnumMaxDiscriminant, `discriminant for simple enum should be less than ${SimpleEnumMaxDiscriminant}`); + this.name = name2; + this.discriminant = discriminant; + this.fieldsDefinitions = fieldsDefinitions; + } + static fromJSON(json) { + let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); + return new _EnumVariantDefinition(json.name, json.discriminant, definitions); + } + getFieldsDefinitions() { + return this.fieldsDefinitions; + } + getFieldDefinition(name2) { + return this.fieldsDefinitions.find((item) => item.name == name2); + } + getNamesOfDependencies() { + return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); + } + }; + exports2.EnumVariantDefinition = EnumVariantDefinition; + var EnumValue = class _EnumValue extends types_1.TypedValue { + constructor(type, variant, fields) { + super(type); + this.fields = []; + this.name = variant.name; + this.discriminant = variant.discriminant; + this.fields = fields; + this.fieldsByName = new Map(fields.map((field) => [field.name, field])); + let definitions = variant.getFieldsDefinitions(); + fields_1.Fields.checkTyping(this.fields, definitions); + } + getClassName() { + return _EnumValue.ClassName; + } + /** + * Utility (named constructor) to create a simple (i.e. without fields) enum value. + */ + static fromName(type, name2) { + let variant = type.getVariantByName(name2); + return new _EnumValue(type, variant, []); + } + /** + * Utility (named constructor) to create a simple (i.e. without fields) enum value. + */ + static fromDiscriminant(type, discriminant) { + let variant = type.getVariantByDiscriminant(discriminant); + return new _EnumValue(type, variant, []); + } + equals(other) { + if (!this.getType().equals(other.getType())) { + return false; + } + let selfFields = this.getFields(); + let otherFields = other.getFields(); + const nameIsSame = this.name == other.name; + const discriminantIsSame = this.discriminant == other.discriminant; + const fieldsAreSame = fields_1.Fields.equals(selfFields, otherFields); + return nameIsSame && discriminantIsSame && fieldsAreSame; + } + getFields() { + return this.fields; + } + getFieldValue(name2) { + let field = this.fieldsByName.get(name2); + if (field) { + return field.value.valueOf(); + } + throw new errors_1.ErrMissingFieldOnEnum(name2, this.getType().getName()); + } + valueOf() { + let result = { name: this.name, fields: [] }; + this.fields.forEach((field, index) => result.fields[index] = field.value.valueOf()); + return result; + } + }; + exports2.EnumValue = EnumValue; + EnumValue.ClassName = "EnumValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js +var require_event = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EventTopicDefinition = exports2.EventDefinition = void 0; + var typeExpressionParser_1 = require_typeExpressionParser(); + var NamePlaceholder = "?"; + var EventDefinition = class _EventDefinition { + constructor(identifier, inputs) { + this.inputs = []; + this.identifier = identifier; + this.inputs = inputs || []; + } + static fromJSON(json) { + json.identifier = json.identifier == null ? NamePlaceholder : json.identifier; + json.inputs = json.inputs || []; + const inputs = json.inputs.map((param) => EventTopicDefinition.fromJSON(param)); + return new _EventDefinition(json.identifier, inputs); + } + }; + exports2.EventDefinition = EventDefinition; + var EventTopicDefinition = class _EventTopicDefinition { + constructor(options) { + this.name = options.name; + this.type = options.type; + this.indexed = options.indexed; + } + static fromJSON(json) { + const parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); + return new _EventTopicDefinition({ + name: json.name || NamePlaceholder, + type: parsedType, + indexed: json.indexed + }); + } + }; + exports2.EventTopicDefinition = EventTopicDefinition; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js +var require_struct = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Struct = exports2.StructType = void 0; + var errors_1 = require_errors(); + var fields_1 = require_fields(); + var types_1 = require_types(); + var StructType = class _StructType extends types_1.CustomType { + constructor(name2, fieldsDefinitions) { + super(name2); + this.fieldsDefinitions = []; + this.fieldsDefinitions = fieldsDefinitions; + } + getClassName() { + return _StructType.ClassName; + } + static fromJSON(json) { + let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); + return new _StructType(json.name, definitions); + } + getFieldsDefinitions() { + return this.fieldsDefinitions; + } + getFieldDefinition(name2) { + return this.fieldsDefinitions.find((item) => item.name == name2); + } + getNamesOfDependencies() { + return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); + } + }; + exports2.StructType = StructType; + StructType.ClassName = "StructType"; + var Struct = class _Struct extends types_1.TypedValue { + /** + * One can only set fields at initialization time. + */ + constructor(type, fields) { + super(type); + this.fields = fields; + this.fieldsByName = new Map(fields.map((field) => [field.name, field])); + this.checkTyping(); + } + getClassName() { + return _Struct.ClassName; + } + checkTyping() { + let type = this.getType(); + let definitions = type.getFieldsDefinitions(); + fields_1.Fields.checkTyping(this.fields, definitions); + } + getFields() { + return this.fields; + } + getFieldValue(name2) { + let field = this.fieldsByName.get(name2); + if (field) { + return field.value.valueOf(); + } + throw new errors_1.ErrMissingFieldOnStruct(name2, this.getType().getName()); + } + valueOf() { + let result = {}; + for (const field of this.fields) { + result[field.name] = field.value.valueOf(); + } + return result; + } + equals(other) { + if (!this.getType().equals(other.getType())) { + return false; + } + let selfFields = this.getFields(); + let otherFields = other.getFields(); + return fields_1.Fields.equals(selfFields, otherFields); + } + }; + exports2.Struct = Struct; + Struct.ClassName = "Struct"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js +var require_address2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AddressValue = exports2.AddressType = void 0; + var address_1 = require_address(); + var types_1 = require_types(); + var AddressType2 = class _AddressType extends types_1.PrimitiveType { + constructor() { + super("Address"); + } + getClassName() { + return _AddressType.ClassName; + } + }; + exports2.AddressType = AddressType2; + AddressType2.ClassName = "AddressType"; + var AddressValue2 = class _AddressValue extends types_1.PrimitiveValue { + constructor(value) { + super(new AddressType2()); + this.value = new address_1.Address(value.bech32()); + } + getClassName() { + return _AddressValue.ClassName; + } + /** + * Returns whether two objects have the same value. + * + * @param other another AddressValue + */ + equals(other) { + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + }; + exports2.AddressValue = AddressValue2; + AddressValue2.ClassName = "AddressValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js +var require_algebraic = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OptionalValue = exports2.OptionalType = void 0; + var utils_1 = require_utils2(); + var types_1 = require_types(); + var OptionalType = class _OptionalType extends types_1.Type { + constructor(typeParameter) { + super("Optional", [typeParameter], types_1.TypeCardinality.variable(1)); + } + getClassName() { + return _OptionalType.ClassName; + } + isAssignableFrom(type) { + if (!type.hasExactClass(_OptionalType.ClassName)) { + return false; + } + let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); + let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); + return invariantTypeParameters || fakeCovarianceToNull; + } + }; + exports2.OptionalType = OptionalType; + OptionalType.ClassName = "OptionalType"; + var OptionalValue = class _OptionalValue extends types_1.TypedValue { + constructor(type, value = null) { + super(type); + this.value = value; + } + getClassName() { + return _OptionalValue.ClassName; + } + /** + * Creates an OptionalValue, as not provided (missing). + */ + static newMissing() { + let type = new OptionalType(new types_1.NullType()); + return new _OptionalValue(type); + } + isSet() { + return this.value ? true : false; + } + getTypedValue() { + utils_1.guardValueIsSet("value", this.value); + return this.value; + } + valueOf() { + return this.value ? this.value.valueOf() : null; + } + equals(other) { + return this.value?.equals(other.value) || false; + } + }; + exports2.OptionalValue = OptionalValue; + OptionalValue.ClassName = "OptionalValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js +var require_boolean = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BooleanValue = exports2.BooleanType = void 0; + var types_1 = require_types(); + var BooleanType2 = class _BooleanType extends types_1.PrimitiveType { + constructor() { + super("bool"); + } + getClassName() { + return _BooleanType.ClassName; + } + }; + exports2.BooleanType = BooleanType2; + BooleanType2.ClassName = "BooleanType"; + var BooleanValue2 = class _BooleanValue extends types_1.PrimitiveValue { + constructor(value) { + super(new BooleanType2()); + this.value = value; + } + getClassName() { + return _BooleanValue.ClassName; + } + /** + * Returns whether two objects have the same value. + * + * @param other another BooleanValue + */ + equals(other) { + return this.value === other.value; + } + isTrue() { + return this.value === true; + } + isFalse() { + return !this.isTrue(); + } + valueOf() { + return this.value; + } + }; + exports2.BooleanValue = BooleanValue2; + BooleanValue2.ClassName = "BooleanValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js +var require_bytes = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesValue = exports2.BytesType = void 0; + var types_1 = require_types(); + var BytesType2 = class _BytesType extends types_1.PrimitiveType { + constructor() { + super("bytes"); + } + getClassName() { + return _BytesType.ClassName; + } + }; + exports2.BytesType = BytesType2; + BytesType2.ClassName = "BytesType"; + var BytesValue2 = class _BytesValue extends types_1.PrimitiveValue { + constructor(value) { + super(new BytesType2()); + this.value = value; + } + getClassName() { + return _BytesValue.ClassName; + } + /** + * Creates a BytesValue from a utf-8 string. + */ + static fromUTF8(value) { + let buffer = import_buffer.Buffer.from(value, "utf-8"); + return new _BytesValue(buffer); + } + /** + * Creates a BytesValue from a hex-encoded string. + */ + static fromHex(value) { + let buffer = import_buffer.Buffer.from(value, "hex"); + return new _BytesValue(buffer); + } + getLength() { + return this.value.length; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + if (this.getLength() != other.getLength()) { + return false; + } + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + toString() { + return this.value.toString(); + } + }; + exports2.BytesValue = BytesValue2; + BytesValue2.ClassName = "BytesValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js +var require_codeMetadata = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CodeMetadataValue = exports2.CodeMetadataType = void 0; + var types_1 = require_types(); + var CodeMetadataType = class extends types_1.PrimitiveType { + constructor() { + super("CodeMetadata"); + } + }; + exports2.CodeMetadataType = CodeMetadataType; + var CodeMetadataValue = class extends types_1.PrimitiveValue { + constructor(value) { + super(new CodeMetadataType()); + this.value = value; + } + equals(other) { + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + }; + exports2.CodeMetadataValue = CodeMetadataValue; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js +var require_composite = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CompositeValue = exports2.CompositeType = void 0; + var utils_1 = require_utils2(); + var types_1 = require_types(); + var CompositeType = class _CompositeType extends types_1.Type { + constructor(...typeParameters) { + super("Composite", typeParameters, types_1.TypeCardinality.variable(typeParameters.length)); + } + getClassName() { + return _CompositeType.ClassName; + } + }; + exports2.CompositeType = CompositeType; + CompositeType.ClassName = "CompositeType"; + var CompositeValue = class _CompositeValue extends types_1.TypedValue { + constructor(type, items) { + super(type); + utils_1.guardLength(items, type.getTypeParameters().length); + this.items = items; + } + getClassName() { + return _CompositeValue.ClassName; + } + static fromItems(...items) { + let typeParameters = items.map((value) => value.getType()); + let type = new CompositeType(...typeParameters); + return new _CompositeValue(type, items); + } + getItems() { + return this.items; + } + valueOf() { + return this.items.map((item) => item?.valueOf()); + } + equals(other) { + if (this.getType().differs(other.getType())) { + return false; + } + for (let i2 = 0; i2 < this.items.length; i2++) { + let selfItem = this.items[i2]; + let otherItem = other.items[i2]; + if (!selfItem.equals(otherItem)) { + return false; + } + } + return true; + } + }; + exports2.CompositeValue = CompositeValue; + CompositeValue.ClassName = "CompositeValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js +var require_collections = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CollectionOfTypedValues = void 0; + var CollectionOfTypedValues = class { + constructor(items) { + this.items = items; + } + getLength() { + return this.items.length; + } + getItems() { + return this.items; + } + valueOf() { + return this.items.map((item) => item.valueOf()); + } + equals(other) { + if (this.getLength() != other.getLength()) { + return false; + } + for (let i2 = 0; i2 < this.getLength(); i2++) { + let selfItem = this.items[i2]; + let otherItem = other.items[i2]; + if (!selfItem.equals(otherItem)) { + return false; + } + } + return true; + } + }; + exports2.CollectionOfTypedValues = CollectionOfTypedValues; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js +var require_generic = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.List = exports2.OptionValue = exports2.ListType = exports2.OptionType = void 0; + var utils_1 = require_utils2(); + var collections_1 = require_collections(); + var types_1 = require_types(); + var OptionType = class _OptionType extends types_1.Type { + constructor(typeParameter) { + super("Option", [typeParameter]); + } + getClassName() { + return _OptionType.ClassName; + } + isAssignableFrom(type) { + if (!type.hasExactClass(_OptionType.ClassName)) { + return false; + } + let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); + let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); + return invariantTypeParameters || fakeCovarianceToNull; + } + }; + exports2.OptionType = OptionType; + OptionType.ClassName = "OptionType"; + var ListType = class _ListType extends types_1.Type { + constructor(typeParameter) { + super("List", [typeParameter]); + } + getClassName() { + return _ListType.ClassName; + } + }; + exports2.ListType = ListType; + ListType.ClassName = "ListType"; + var OptionValue = class _OptionValue extends types_1.TypedValue { + constructor(type, value = null) { + super(type); + this.value = value; + } + getClassName() { + return _OptionValue.ClassName; + } + /** + * Creates an OptionValue, as a missing option argument. + */ + static newMissing() { + let type = new OptionType(new types_1.NullType()); + return new _OptionValue(type); + } + static newMissingTyped(type) { + return new _OptionValue(new OptionType(type)); + } + /** + * Creates an OptionValue, as a provided option argument. + */ + static newProvided(typedValue) { + let type = new OptionType(typedValue.getType()); + return new _OptionValue(type, typedValue); + } + isSet() { + return this.value ? true : false; + } + getTypedValue() { + utils_1.guardValueIsSet("value", this.value); + return this.value; + } + valueOf() { + return this.value ? this.value.valueOf() : null; + } + equals(other) { + return this.value?.equals(other.value) || false; + } + }; + exports2.OptionValue = OptionValue; + OptionValue.ClassName = "OptionValue"; + var List = class _List extends types_1.TypedValue { + /** + * + * @param type the type of this TypedValue (an instance of ListType), not the type parameter of the ListType + * @param items the items, having the type type.getFirstTypeParameter() + */ + constructor(type, items) { + super(type); + this.backingCollection = new collections_1.CollectionOfTypedValues(items); + } + getClassName() { + return _List.ClassName; + } + static fromItems(items) { + if (items.length == 0) { + return new _List(new types_1.TypePlaceholder(), []); + } + let typeParameter = items[0].getType(); + let listType = new ListType(typeParameter); + return new _List(listType, items); + } + getLength() { + return this.backingCollection.getLength(); + } + getItems() { + return this.backingCollection.getItems(); + } + valueOf() { + return this.backingCollection.valueOf(); + } + equals(other) { + return this.backingCollection.equals(other.backingCollection); + } + }; + exports2.List = List; + List.ClassName = "List"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js +var require_genericArray = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArrayVec = exports2.ArrayVecType = void 0; + var utils_1 = require_utils2(); + var collections_1 = require_collections(); + var types_1 = require_types(); + var ArrayVecType = class _ArrayVecType extends types_1.Type { + constructor(length2, typeParameter) { + super("Array", [typeParameter]); + utils_1.guardTrue(length2 > 0, "array length > 0"); + this.length = length2; + } + getClassName() { + return _ArrayVecType.ClassName; + } + }; + exports2.ArrayVecType = ArrayVecType; + ArrayVecType.ClassName = "ArrayVecType"; + var ArrayVec = class _ArrayVec extends types_1.TypedValue { + constructor(type, items) { + super(type); + utils_1.guardLength(items, type.length); + this.backingCollection = new collections_1.CollectionOfTypedValues(items); + } + getClassName() { + return _ArrayVec.ClassName; + } + getLength() { + return this.backingCollection.getLength(); + } + getItems() { + return this.backingCollection.getItems(); + } + valueOf() { + return this.backingCollection.valueOf(); + } + equals(other) { + return this.backingCollection.equals(other.backingCollection); + } + }; + exports2.ArrayVec = ArrayVec; + ArrayVec.ClassName = "ArrayVec"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js +var require_h256 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.H256Value = exports2.H256Type = void 0; + var types_1 = require_types(); + var H256Type = class _H256Type extends types_1.PrimitiveType { + constructor() { + super("H256"); + } + getClassName() { + return _H256Type.ClassName; + } + }; + exports2.H256Type = H256Type; + H256Type.ClassName = "H256Type"; + var H256Value = class _H256Value extends types_1.PrimitiveValue { + constructor(value) { + super(new H256Type()); + this.value = value; + } + getClassName() { + return _H256Value.ClassName; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + return this.value.equals(other.value); + } + valueOf() { + return this.value; + } + }; + exports2.H256Value = H256Value; + H256Value.ClassName = "H256Value"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js +var require_nothing = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NothingValue = exports2.NothingType = void 0; + var types_1 = require_types(); + var NothingType = class _NothingType extends types_1.PrimitiveType { + constructor() { + super("nothing"); + } + getClassName() { + return _NothingType.ClassName; + } + }; + exports2.NothingType = NothingType; + NothingType.ClassName = "NothingType"; + var NothingValue = class _NothingValue extends types_1.PrimitiveValue { + constructor() { + super(new NothingType()); + } + getClassName() { + return _NothingValue.ClassName; + } + equals(_other) { + return false; + } + valueOf() { + return {}; + } + }; + exports2.NothingValue = NothingValue; + NothingValue.ClassName = "NothingValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js +var require_numerical = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BigIntValue = exports2.BigUIntValue = exports2.I64Value = exports2.U64Value = exports2.I32Value = exports2.U32Value = exports2.I16Value = exports2.U16Value = exports2.I8Value = exports2.U8Value = exports2.NumericalValue = exports2.BigIntType = exports2.BigUIntType = exports2.I64Type = exports2.U64Type = exports2.I32Type = exports2.U32Type = exports2.I16Type = exports2.U16Type = exports2.I8Type = exports2.U8Type = exports2.NumericalType = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var errors = __importStar2(require_errors()); + var types_1 = require_types(); + var NumericalType = class _NumericalType extends types_1.PrimitiveType { + constructor(name2, sizeInBytes, withSign) { + super(name2); + this.sizeInBytes = sizeInBytes; + this.withSign = withSign; + } + getClassName() { + return _NumericalType.ClassName; + } + hasFixedSize() { + return this.sizeInBytes ? true : false; + } + hasArbitrarySize() { + return !this.hasFixedSize(); + } + }; + exports2.NumericalType = NumericalType; + NumericalType.ClassName = "NumericalType"; + var U8Type2 = class _U8Type extends NumericalType { + constructor() { + super("u8", 1, false); + } + getClassName() { + return _U8Type.ClassName; + } + }; + exports2.U8Type = U8Type2; + U8Type2.ClassName = "U8Type"; + var I8Type = class _I8Type extends NumericalType { + constructor() { + super("i8", 1, true); + } + getClassName() { + return _I8Type.ClassName; + } + }; + exports2.I8Type = I8Type; + I8Type.ClassName = "I8Type"; + var U16Type2 = class _U16Type extends NumericalType { + constructor() { + super("u16", 2, false); + } + getClassName() { + return _U16Type.ClassName; + } + }; + exports2.U16Type = U16Type2; + U16Type2.ClassName = "U16Type"; + var I16Type = class _I16Type extends NumericalType { + constructor() { + super("i16", 2, true); + } + getClassName() { + return _I16Type.ClassName; + } + }; + exports2.I16Type = I16Type; + I16Type.ClassName = "I16Type"; + var U32Type2 = class _U32Type extends NumericalType { + constructor() { + super("u32", 4, false); + } + getClassName() { + return _U32Type.ClassName; + } + }; + exports2.U32Type = U32Type2; + U32Type2.ClassName = "U32Type"; + var I32Type = class _I32Type extends NumericalType { + constructor() { + super("i32", 4, true); + } + getClassName() { + return _I32Type.ClassName; + } + }; + exports2.I32Type = I32Type; + I32Type.ClassName = "I32Type"; + var U64Type2 = class _U64Type extends NumericalType { + constructor() { + super("u64", 8, false); + } + getClassName() { + return _U64Type.ClassName; + } + }; + exports2.U64Type = U64Type2; + U64Type2.ClassName = "U64Type"; + var I64Type = class _I64Type extends NumericalType { + constructor() { + super("i64", 8, true); + } + getClassName() { + return _I64Type.ClassName; + } + }; + exports2.I64Type = I64Type; + I64Type.ClassName = "I64Type"; + var BigUIntType2 = class _BigUIntType extends NumericalType { + constructor() { + super("BigUint", 0, false); + } + getClassName() { + return _BigUIntType.ClassName; + } + }; + exports2.BigUIntType = BigUIntType2; + BigUIntType2.ClassName = "BigUIntType"; + var BigIntType = class _BigIntType extends NumericalType { + constructor() { + super("Bigint", 0, true); + } + getClassName() { + return _BigIntType.ClassName; + } + }; + exports2.BigIntType = BigIntType; + BigIntType.ClassName = "BigIntType"; + var NumericalValue = class _NumericalValue extends types_1.PrimitiveValue { + constructor(type, value) { + super(type); + if (typeof value === "bigint") { + value = value.toString(); + } + this.value = new bignumber_js_1.default(value); + this.sizeInBytes = type.sizeInBytes; + this.withSign = type.withSign; + if (this.value.isNaN()) { + throw new errors.ErrInvalidArgument(`not a number: ${value}`); + } + if (!this.withSign && this.value.isNegative()) { + throw new errors.ErrInvalidArgument(`negative, but type is unsigned: ${value}`); + } + } + getClassName() { + return _NumericalValue.ClassName; + } + /** + * Returns whether two objects have the same value. + * + * @param other another NumericalValue + */ + equals(other) { + return this.value.isEqualTo(other.value); + } + valueOf() { + return this.value; + } + toString() { + return this.value.toString(); + } + }; + exports2.NumericalValue = NumericalValue; + NumericalValue.ClassName = "NumericalValue"; + var U8Value2 = class _U8Value extends NumericalValue { + constructor(value) { + super(new U8Type2(), value); + } + getClassName() { + return _U8Value.ClassName; + } + }; + exports2.U8Value = U8Value2; + U8Value2.ClassName = "U8Value"; + var I8Value = class _I8Value extends NumericalValue { + constructor(value) { + super(new I8Type(), value); + } + getClassName() { + return _I8Value.ClassName; + } + }; + exports2.I8Value = I8Value; + I8Value.ClassName = "I8Value"; + var U16Value2 = class _U16Value extends NumericalValue { + constructor(value) { + super(new U16Type2(), value); + } + getClassName() { + return _U16Value.ClassName; + } + }; + exports2.U16Value = U16Value2; + U16Value2.ClassName = "U16Value"; + var I16Value = class _I16Value extends NumericalValue { + constructor(value) { + super(new I16Type(), value); + } + getClassName() { + return _I16Value.ClassName; + } + }; + exports2.I16Value = I16Value; + I16Value.ClassName = "I16Value"; + var U32Value2 = class _U32Value extends NumericalValue { + constructor(value) { + super(new U32Type2(), value); + } + getClassName() { + return _U32Value.ClassName; + } + }; + exports2.U32Value = U32Value2; + U32Value2.ClassName = "U32Value"; + var I32Value = class _I32Value extends NumericalValue { + constructor(value) { + super(new I32Type(), value); + } + getClassName() { + return _I32Value.ClassName; + } + }; + exports2.I32Value = I32Value; + I32Value.ClassName = "I32Value"; + var U64Value2 = class _U64Value extends NumericalValue { + constructor(value) { + super(new U64Type2(), value); + } + getClassName() { + return _U64Value.ClassName; + } + }; + exports2.U64Value = U64Value2; + U64Value2.ClassName = "U64Value"; + var I64Value = class _I64Value extends NumericalValue { + constructor(value) { + super(new I64Type(), value); + } + getClassName() { + return _I64Value.ClassName; + } + }; + exports2.I64Value = I64Value; + I64Value.ClassName = "I64Value"; + var BigUIntValue2 = class _BigUIntValue extends NumericalValue { + constructor(value) { + super(new BigUIntType2(), value); + } + getClassName() { + return _BigUIntValue.ClassName; + } + }; + exports2.BigUIntValue = BigUIntValue2; + BigUIntValue2.ClassName = "BigUIntValue"; + var BigIntValue = class _BigIntValue extends NumericalValue { + constructor(value) { + super(new BigIntType(), value); + } + getClassName() { + return _BigIntValue.ClassName; + } + }; + exports2.BigIntValue = BigIntValue; + BigIntValue.ClassName = "BigIntValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js +var require_string = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StringValue = exports2.StringType = void 0; + var types_1 = require_types(); + var StringType = class _StringType extends types_1.PrimitiveType { + constructor() { + super("utf-8 string"); + } + getClassName() { + return _StringType.ClassName; + } + }; + exports2.StringType = StringType; + StringType.ClassName = "StringType"; + var StringValue = class _StringValue extends types_1.PrimitiveValue { + constructor(value) { + super(new StringType()); + this.value = value; + } + getClassName() { + return _StringValue.ClassName; + } + /** + * Creates a StringValue from a utf-8 string. + */ + static fromUTF8(value) { + return new _StringValue(value); + } + /** + * Creates a StringValue from a hex-encoded string. + */ + static fromHex(value) { + let decodedValue = import_buffer.Buffer.from(value, "hex").toString(); + return new _StringValue(decodedValue); + } + getLength() { + return this.value.length; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + return this.value === other.value; + } + valueOf() { + return this.value; + } + }; + exports2.StringValue = StringValue; + StringValue.ClassName = "StringValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js +var require_tokenIdentifier = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenIdentifierValue = exports2.TokenIdentifierType = void 0; + var types_1 = require_types(); + var EGLDTokenIdentifier = "EGLD"; + var TokenIdentifierType = class _TokenIdentifierType extends types_1.PrimitiveType { + constructor() { + super("TokenIdentifier"); + } + getClassName() { + return _TokenIdentifierType.ClassName; + } + }; + exports2.TokenIdentifierType = TokenIdentifierType; + TokenIdentifierType.ClassName = "TokenIdentifierType"; + var TokenIdentifierValue = class _TokenIdentifierValue extends types_1.PrimitiveValue { + constructor(value) { + super(new TokenIdentifierType()); + this.value = value; + } + static egld() { + return new _TokenIdentifierValue(EGLDTokenIdentifier); + } + static esdtTokenIdentifier(identifier) { + return new _TokenIdentifierValue(identifier); + } + getClassName() { + return _TokenIdentifierValue.ClassName; + } + getLength() { + return this.value.length; + } + /** + * Returns whether two objects have the same value. + */ + equals(other) { + if (this.getLength() != other.getLength()) { + return false; + } + return this.value == other.value; + } + valueOf() { + return this.value; + } + toString() { + return this.value.toString(); + } + }; + exports2.TokenIdentifierValue = TokenIdentifierValue; + TokenIdentifierValue.ClassName = "TokenIdentifierValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js +var require_tuple = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Tuple = exports2.TupleType = void 0; + var errors = __importStar2(require_errors()); + var fields_1 = require_fields(); + var struct_1 = require_struct(); + var TupleType = class _TupleType extends struct_1.StructType { + constructor(...typeParameters) { + super(_TupleType.prepareName(typeParameters), _TupleType.prepareFieldDefinitions(typeParameters)); + } + getClassName() { + return _TupleType.ClassName; + } + static prepareName(typeParameters) { + let fields = typeParameters.map((type) => type.toString()).join(", "); + let result = `tuple<${fields}>`; + return result; + } + static prepareFieldDefinitions(typeParameters) { + let result = typeParameters.map((type, i2) => new fields_1.FieldDefinition(prepareFieldName(i2), "anonymous tuple field", type)); + return result; + } + }; + exports2.TupleType = TupleType; + TupleType.ClassName = "TupleType"; + function prepareFieldName(fieldIndex) { + return `field${fieldIndex}`; + } + var Tuple = class _Tuple extends struct_1.Struct { + constructor(type, fields) { + super(type, fields); + } + getClassName() { + return _Tuple.ClassName; + } + static fromItems(items) { + if (items.length < 1) { + throw new errors.ErrTypingSystem("bad tuple items"); + } + let fieldsTypes = items.map((item) => item.getType()); + let tupleType = new TupleType(...fieldsTypes); + let fields = items.map((item, i2) => new fields_1.Field(item, prepareFieldName(i2))); + return new _Tuple(tupleType, fields); + } + }; + exports2.Tuple = Tuple; + Tuple.ClassName = "Tuple"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js +var require_variadic = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.VariadicValue = exports2.CountedVariadicType = exports2.VariadicType = void 0; + var types_1 = require_types(); + var VariadicType = class _VariadicType extends types_1.Type { + constructor(typeParameter, isCounted = false) { + super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); + this.isCounted = isCounted; + } + getClassName() { + return _VariadicType.ClassName; + } + }; + exports2.VariadicType = VariadicType; + VariadicType.ClassName = "VariadicType"; + var CountedVariadicType = class extends types_1.Type { + constructor(typeParameter) { + super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); + } + getClassName() { + return VariadicType.ClassName; + } + }; + exports2.CountedVariadicType = CountedVariadicType; + CountedVariadicType.ClassName = "VariadicType"; + var VariadicValue = class _VariadicValue extends types_1.TypedValue { + /** + * + * @param type the type of this TypedValue (an instance of VariadicType), not the type parameter of the VariadicType + * @param items the items, having the type type.getFirstTypeParameter() + */ + constructor(type, items) { + super(type); + this.items = items; + } + getClassName() { + return _VariadicValue.ClassName; + } + static fromItems(...items) { + return this.createFromItems(items, false); + } + static fromItemsCounted(...items) { + return this.createFromItems(items, true); + } + static createFromItems(items, isCounted) { + if (items.length == 0) { + return new _VariadicValue(new VariadicType(new types_1.TypePlaceholder(), isCounted), []); + } + const typeParameter = items[0].getType(); + return new _VariadicValue(new VariadicType(typeParameter, isCounted), items); + } + getItems() { + return this.items; + } + valueOf() { + return this.items.map((item) => item.valueOf()); + } + equals(other) { + if (this.getType().differs(other.getType())) { + return false; + } + for (let i2 = 0; i2 < this.items.length; i2++) { + let selfItem = this.items[i2]; + let otherItem = other.items[i2]; + if (!selfItem.equals(otherItem)) { + return false; + } + } + return true; + } + }; + exports2.VariadicValue = VariadicValue; + VariadicValue.ClassName = "VariadicValue"; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js +var require_typeMapper = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TypeMapper = void 0; + var errors = __importStar2(require_errors()); + var address_1 = require_address2(); + var algebraic_1 = require_algebraic(); + var boolean_1 = require_boolean(); + var bytes_1 = require_bytes(); + var codeMetadata_1 = require_codeMetadata(); + var composite_1 = require_composite(); + var enum_1 = require_enum(); + var fields_1 = require_fields(); + var generic_1 = require_generic(); + var genericArray_1 = require_genericArray(); + var h256_1 = require_h256(); + var nothing_1 = require_nothing(); + var numerical_1 = require_numerical(); + var string_1 = require_string(); + var struct_1 = require_struct(); + var tokenIdentifier_1 = require_tokenIdentifier(); + var tuple_1 = require_tuple(); + var variadic_1 = require_variadic(); + var TypeMapper = class { + constructor(learnedTypes = []) { + this.openTypesFactories = /* @__PURE__ */ new Map([ + ["Option", (...typeParameters) => new generic_1.OptionType(typeParameters[0])], + ["List", (...typeParameters) => new generic_1.ListType(typeParameters[0])], + // For the following open generics, we use a slightly different typing than the one defined by mx-sdk-rs (temporary workaround). + ["VarArgs", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], + ["MultiResultVec", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], + ["variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], + ["counted-variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0], true)], + ["OptionalArg", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], + ["optional", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], + ["OptionalResult", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], + ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + ["MultiArg", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + ["MultiResult", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], + // Perhaps we can adjust the ABI generator to only output "tuple", instead of "tupleN"? + ["tuple", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple2", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple3", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple4", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple5", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple6", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple7", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + ["tuple8", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], + // Known-length arrays. + // TODO: Handle these in typeExpressionParser! + ["array2", (...typeParameters) => new genericArray_1.ArrayVecType(2, typeParameters[0])], + ["array8", (...typeParameters) => new genericArray_1.ArrayVecType(8, typeParameters[0])], + ["array16", (...typeParameters) => new genericArray_1.ArrayVecType(16, typeParameters[0])], + ["array20", (...typeParameters) => new genericArray_1.ArrayVecType(20, typeParameters[0])], + ["array32", (...typeParameters) => new genericArray_1.ArrayVecType(32, typeParameters[0])], + ["array46", (...typeParameters) => new genericArray_1.ArrayVecType(46, typeParameters[0])], + ["array48", (...typeParameters) => new genericArray_1.ArrayVecType(48, typeParameters[0])], + ["array64", (...typeParameters) => new genericArray_1.ArrayVecType(64, typeParameters[0])], + ["array128", (...typeParameters) => new genericArray_1.ArrayVecType(128, typeParameters[0])], + ["array256", (...typeParameters) => new genericArray_1.ArrayVecType(256, typeParameters[0])] + ]); + this.closedTypesMap = /* @__PURE__ */ new Map([ + ["u8", new numerical_1.U8Type()], + ["u16", new numerical_1.U16Type()], + ["u32", new numerical_1.U32Type()], + ["u64", new numerical_1.U64Type()], + ["U64", new numerical_1.U64Type()], + ["BigUint", new numerical_1.BigUIntType()], + ["i8", new numerical_1.I8Type()], + ["i16", new numerical_1.I16Type()], + ["i32", new numerical_1.I32Type()], + ["i64", new numerical_1.I64Type()], + ["Bigint", new numerical_1.BigIntType()], + ["BigInt", new numerical_1.BigIntType()], + ["bool", new boolean_1.BooleanType()], + ["bytes", new bytes_1.BytesType()], + ["Address", new address_1.AddressType()], + ["H256", new h256_1.H256Type()], + ["utf-8 string", new string_1.StringType()], + ["TokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], + ["EgldOrEsdtTokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], + ["CodeMetadata", new codeMetadata_1.CodeMetadataType()], + ["nothing", new nothing_1.NothingType()], + ["AsyncCall", new nothing_1.NothingType()] + ]); + this.learnedTypesMap = /* @__PURE__ */ new Map(); + for (const type of learnedTypes) { + this.learnedTypesMap.set(type.getName(), type); + } + } + /** + * Maps a "raw type" object to a "known (specific) type" object. + * In the process, it also learns the new type. + * Can only map types if their dependencies were previously learned (through mapping). + */ + mapType(type) { + let mappedType = this.mapTypeRecursively(type); + if (mappedType) { + if (!mappedType.isGenericType()) { + this.learnType(mappedType); + } + return mappedType; + } + throw new errors.ErrTypingSystem(`Cannot map the type "${type.getName()}" to a known type`); + } + mapTypeRecursively(type) { + let isGeneric = type.isGenericType(); + let previouslyLearnedType = this.learnedTypesMap.get(type.getName()); + if (previouslyLearnedType) { + return previouslyLearnedType; + } + let knownClosedType = this.closedTypesMap.get(type.getName()); + if (knownClosedType) { + return knownClosedType; + } + if (type.hasExactClass(enum_1.EnumType.ClassName)) { + return this.mapEnumType(type); + } + if (type.hasExactClass(struct_1.StructType.ClassName)) { + return this.mapStructType(type); + } + if (isGeneric) { + return this.mapGenericType(type); + } + return null; + } + learnType(type) { + this.learnedTypesMap.delete(type.getName()); + this.learnedTypesMap.set(type.getName(), type); + } + mapStructType(type) { + let mappedFields = this.mappedFields(type.getFieldsDefinitions()); + let mappedStruct = new struct_1.StructType(type.getName(), mappedFields); + return mappedStruct; + } + mapEnumType(type) { + let variants = type.variants.map((variant) => new enum_1.EnumVariantDefinition(variant.name, variant.discriminant, this.mappedFields(variant.getFieldsDefinitions()))); + let mappedEnum = new enum_1.EnumType(type.getName(), variants); + return mappedEnum; + } + mappedFields(definitions) { + return definitions.map((definition) => new fields_1.FieldDefinition(definition.name, definition.description, this.mapType(definition.type))); + } + mapGenericType(type) { + let typeParameters = type.getTypeParameters(); + let mappedTypeParameters = typeParameters.map((item) => this.mapType(item)); + let factory = this.openTypesFactories.get(type.getName()); + if (!factory) { + throw new errors.ErrTypingSystem(`Cannot map the generic type "${type.getName()}" to a known type`); + } + return factory(...mappedTypeParameters); + } + }; + exports2.TypeMapper = TypeMapper; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js +var require_abiRegistry = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AbiRegistry = void 0; + var errors = __importStar2(require_errors()); + var utils_1 = require_utils2(); + var endpoint_1 = require_endpoint(); + var enum_1 = require_enum(); + var event_1 = require_event(); + var struct_1 = require_struct(); + var typeMapper_1 = require_typeMapper(); + var interfaceNamePlaceholder = "?"; + var AbiRegistry = class _AbiRegistry { + constructor(options) { + this.endpoints = []; + this.customTypes = []; + this.events = []; + this.name = options.name; + this.constructorDefinition = options.constructorDefinition; + this.endpoints = options.endpoints; + this.customTypes = options.customTypes; + this.events = options.events || []; + } + static create(options) { + const name2 = options.name || interfaceNamePlaceholder; + const constructor = options.constructor || {}; + const endpoints = options.endpoints || []; + const types = options.types || {}; + const events = options.events || []; + const constructorDefinition = endpoint_1.EndpointDefinition.fromJSON({ name: "constructor", ...constructor }); + const endpointDefinitions = endpoints.map((item) => endpoint_1.EndpointDefinition.fromJSON(item)); + const customTypes = []; + for (const customTypeName in types) { + const typeDefinition = types[customTypeName]; + if (typeDefinition.type == "struct") { + customTypes.push(struct_1.StructType.fromJSON({ name: customTypeName, fields: typeDefinition.fields })); + } else if (typeDefinition.type == "enum" || typeDefinition.type == "explicit-enum") { + customTypes.push(enum_1.EnumType.fromJSON({ name: customTypeName, variants: typeDefinition.variants })); + } else { + throw new errors.ErrTypingSystem(`Cannot handle custom type: ${customTypeName}`); + } + } + const eventDefinitions = events.map((item) => event_1.EventDefinition.fromJSON(item)); + const registry = new _AbiRegistry({ + name: name2, + constructorDefinition, + endpoints: endpointDefinitions, + customTypes, + events: eventDefinitions + }); + const remappedRegistry = registry.remapToKnownTypes(); + return remappedRegistry; + } + getCustomType(name2) { + const result = this.customTypes.find((e2) => e2.getName() == name2); + utils_1.guardValueIsSetWithMessage(`custom type [${name2}] not found`, result); + return result; + } + getStruct(name2) { + const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(struct_1.StructType.ClassName)); + utils_1.guardValueIsSetWithMessage(`struct [${name2}] not found`, result); + return result; + } + getStructs(names) { + return names.map((name2) => this.getStruct(name2)); + } + getEnum(name2) { + const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(enum_1.EnumType.ClassName)); + utils_1.guardValueIsSetWithMessage(`enum [${name2}] not found`, result); + return result; + } + getEnums(names) { + return names.map((name2) => this.getEnum(name2)); + } + getEndpoints() { + return this.endpoints; + } + getEndpoint(name2) { + const result = this.endpoints.find((e2) => e2.name == name2); + utils_1.guardValueIsSetWithMessage(`endpoint [${name2}] not found`, result); + return result; + } + getEvent(name2) { + const result = this.events.find((e2) => e2.identifier == name2); + utils_1.guardValueIsSetWithMessage(`event [${name2}] not found`, result); + return result; + } + /** + * Right after loading ABI definitions into a registry, the endpoints and the custom types (structs, enums) + * use raw types for their I/O parameters (in the case of endpoints), or for their fields (in the case of structs). + * + * A raw type is merely an instance of {@link Type}, with a given name and type parameters (if it's a generic type). + * + * Though, for most (development) purposes, we'd like to operate using known, specific types (e.g. {@link List}, {@link U8Type} etc.). + * This function increases the specificity of the types used by parameter / field definitions within a registry (on best-efforts basis). + * The result is an equivalent, more explicit ABI registry. + */ + remapToKnownTypes() { + const mapper = new typeMapper_1.TypeMapper([]); + const newCustomTypes = []; + for (const type of this.customTypes) { + this.mapCustomTypeDepthFirst(type, this.customTypes, mapper, newCustomTypes); + } + if (this.customTypes.length != newCustomTypes.length) { + throw new errors.ErrTypingSystem("Did not re-map all custom types"); + } + const newConstructor = mapEndpoint(this.constructorDefinition, mapper); + const newEndpoints = []; + for (const endpoint of this.endpoints) { + newEndpoints.push(mapEndpoint(endpoint, mapper)); + } + const newEvents = this.events.map((event) => mapEvent(event, mapper)); + const newRegistry = new _AbiRegistry({ + name: this.name, + constructorDefinition: newConstructor, + endpoints: newEndpoints, + customTypes: newCustomTypes, + events: newEvents + }); + return newRegistry; + } + mapCustomTypeDepthFirst(typeToMap, allTypesToMap, mapper, mappedTypes) { + const hasBeenMapped = mappedTypes.findIndex((type) => type.getName() == typeToMap.getName()) >= 0; + if (hasBeenMapped) { + return; + } + for (const typeName of typeToMap.getNamesOfDependencies()) { + const dependencyType = allTypesToMap.find((type) => type.getName() == typeName); + if (!dependencyType) { + continue; + } + this.mapCustomTypeDepthFirst(dependencyType, allTypesToMap, mapper, mappedTypes); + } + const mappedType = mapper.mapType(typeToMap); + mappedTypes.push(mappedType); + } + }; + exports2.AbiRegistry = AbiRegistry; + function mapEndpoint(endpoint, mapper) { + const newInput = endpoint.input.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); + const newOutput = endpoint.output.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); + return new endpoint_1.EndpointDefinition(endpoint.name, newInput, newOutput, endpoint.modifiers); + } + function mapEvent(event, mapper) { + const newInputs = event.inputs.map((e2) => new event_1.EventTopicDefinition({ + name: e2.name, + type: mapper.mapType(e2.type), + indexed: e2.indexed + })); + return new event_1.EventDefinition(event.identifier, newInputs); + } + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js +var require_factory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.createListOfTokenIdentifiers = exports2.createListOfAddresses = void 0; + var address_1 = require_address2(); + var generic_1 = require_generic(); + var tokenIdentifier_1 = require_tokenIdentifier(); + function createListOfAddresses(addresses) { + let addressesTyped = addresses.map((address) => new address_1.AddressValue(address)); + let list = generic_1.List.fromItems(addressesTyped); + return list; + } + exports2.createListOfAddresses = createListOfAddresses; + function createListOfTokenIdentifiers(identifiers) { + let identifiersTyped = identifiers.map((identifier) => new tokenIdentifier_1.TokenIdentifierValue(identifier)); + let list = generic_1.List.fromItems(identifiersTyped); + return list; + } + exports2.createListOfTokenIdentifiers = createListOfTokenIdentifiers; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js +var require_matchers = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.onPrimitiveTypeSelect = exports2.onPrimitiveValueSelect = exports2.onTypedValueSelect = exports2.onTypeSelect = void 0; + var errors = __importStar2(require_errors()); + var address_1 = require_address2(); + var boolean_1 = require_boolean(); + var bytes_1 = require_bytes(); + var enum_1 = require_enum(); + var generic_1 = require_generic(); + var h256_1 = require_h256(); + var numerical_1 = require_numerical(); + var nothing_1 = require_nothing(); + var struct_1 = require_struct(); + var tokenIdentifier_1 = require_tokenIdentifier(); + var tuple_1 = require_tuple(); + var types_1 = require_types(); + var genericArray_1 = require_genericArray(); + var string_1 = require_string(); + function onTypeSelect(type, selectors) { + if (type.hasExactClass(generic_1.OptionType.ClassName)) { + return selectors.onOption(); + } + if (type.hasExactClass(generic_1.ListType.ClassName)) { + return selectors.onList(); + } + if (type.hasExactClass(genericArray_1.ArrayVecType.ClassName)) { + return selectors.onArray(); + } + if (type.hasClassOrSuperclass(types_1.PrimitiveType.ClassName)) { + return selectors.onPrimitive(); + } + if (type.hasExactClass(struct_1.StructType.ClassName)) { + return selectors.onStruct(); + } + if (type.hasExactClass(tuple_1.TupleType.ClassName)) { + return selectors.onTuple(); + } + if (type.hasExactClass(enum_1.EnumType.ClassName)) { + return selectors.onEnum(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`type isn't known: ${type}`); + } + exports2.onTypeSelect = onTypeSelect; + function onTypedValueSelect(value, selectors) { + if (value.hasClassOrSuperclass(types_1.PrimitiveValue.ClassName)) { + return selectors.onPrimitive(); + } + if (value.hasExactClass(generic_1.OptionValue.ClassName)) { + return selectors.onOption(); + } + if (value.hasExactClass(generic_1.List.ClassName)) { + return selectors.onList(); + } + if (value.hasExactClass(genericArray_1.ArrayVec.ClassName)) { + return selectors.onArray(); + } + if (value.hasExactClass(struct_1.Struct.ClassName)) { + return selectors.onStruct(); + } + if (value.hasExactClass(tuple_1.Tuple.ClassName)) { + return selectors.onTuple(); + } + if (value.hasExactClass(enum_1.EnumValue.ClassName)) { + return selectors.onEnum(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`value isn't typed: ${value}`); + } + exports2.onTypedValueSelect = onTypedValueSelect; + function onPrimitiveValueSelect(value, selectors) { + if (value.hasExactClass(boolean_1.BooleanValue.ClassName)) { + return selectors.onBoolean(); + } + if (value.hasClassOrSuperclass(numerical_1.NumericalValue.ClassName)) { + return selectors.onNumerical(); + } + if (value.hasExactClass(address_1.AddressValue.ClassName)) { + return selectors.onAddress(); + } + if (value.hasExactClass(bytes_1.BytesValue.ClassName)) { + return selectors.onBytes(); + } + if (value.hasExactClass(string_1.StringValue.ClassName)) { + return selectors.onString(); + } + if (value.hasExactClass(h256_1.H256Value.ClassName)) { + return selectors.onH256(); + } + if (value.hasExactClass(tokenIdentifier_1.TokenIdentifierValue.ClassName)) { + return selectors.onTypeIdentifier(); + } + if (value.hasExactClass(nothing_1.NothingValue.ClassName)) { + return selectors.onNothing(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`value isn't a primitive: ${value.getType()}`); + } + exports2.onPrimitiveValueSelect = onPrimitiveValueSelect; + function onPrimitiveTypeSelect(type, selectors) { + if (type.hasExactClass(boolean_1.BooleanType.ClassName)) { + return selectors.onBoolean(); + } + if (type.hasClassOrSuperclass(numerical_1.NumericalType.ClassName)) { + return selectors.onNumerical(); + } + if (type.hasExactClass(address_1.AddressType.ClassName)) { + return selectors.onAddress(); + } + if (type.hasExactClass(bytes_1.BytesType.ClassName)) { + return selectors.onBytes(); + } + if (type.hasExactClass(string_1.StringType.ClassName)) { + return selectors.onString(); + } + if (type.hasExactClass(h256_1.H256Type.ClassName)) { + return selectors.onH256(); + } + if (type.hasExactClass(tokenIdentifier_1.TokenIdentifierType.ClassName)) { + return selectors.onTokenIndetifier(); + } + if (type.hasExactClass(nothing_1.NothingType.ClassName)) { + return selectors.onNothing(); + } + if (selectors.onOther) { + return selectors.onOther(); + } + throw new errors.ErrTypingSystem(`type isn't a known primitive: ${type}`); + } + exports2.onPrimitiveTypeSelect = onPrimitiveTypeSelect; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js +var require_typesystem = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_abiRegistry(), exports2); + __exportStar2(require_address2(), exports2); + __exportStar2(require_algebraic(), exports2); + __exportStar2(require_boolean(), exports2); + __exportStar2(require_bytes(), exports2); + __exportStar2(require_composite(), exports2); + __exportStar2(require_endpoint(), exports2); + __exportStar2(require_enum(), exports2); + __exportStar2(require_factory(), exports2); + __exportStar2(require_fields(), exports2); + __exportStar2(require_generic(), exports2); + __exportStar2(require_genericArray(), exports2); + __exportStar2(require_h256(), exports2); + __exportStar2(require_matchers(), exports2); + __exportStar2(require_nothing(), exports2); + __exportStar2(require_numerical(), exports2); + __exportStar2(require_string(), exports2); + __exportStar2(require_struct(), exports2); + __exportStar2(require_tokenIdentifier(), exports2); + __exportStar2(require_tuple(), exports2); + __exportStar2(require_typeExpressionParser(), exports2); + __exportStar2(require_typeMapper(), exports2); + __exportStar2(require_types(), exports2); + __exportStar2(require_variadic(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js +var require_option = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OptionValueBinaryCodec = void 0; + var errors = __importStar2(require_errors()); + var typesystem_1 = require_typesystem(); + var OptionValueBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, type) { + if (buffer[0] == 0) { + return [typesystem_1.OptionValue.newMissingTyped(type), 1]; + } + if (buffer[0] != 1) { + throw new errors.ErrCodec("invalid buffer for optional value"); + } + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); + return [typesystem_1.OptionValue.newProvided(decoded), decodedLength + 1]; + } + decodeTopLevel(buffer, type) { + if (buffer.length == 0) { + return new typesystem_1.OptionValue(type); + } + if (buffer[0] != 1) { + throw new errors.ErrCodec("invalid buffer for optional value"); + } + let [decoded, _decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); + return new typesystem_1.OptionValue(type, decoded); + } + encodeNested(optionValue) { + if (optionValue.isSet()) { + return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); + } + return import_buffer.Buffer.from([0]); + } + encodeTopLevel(optionValue) { + if (optionValue.isSet()) { + return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); + } + return import_buffer.Buffer.from([]); + } + }; + exports2.OptionValueBinaryCodec = OptionValueBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js +var require_address3 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AddressBinaryCodec = void 0; + var address_1 = require_address(); + var typesystem_1 = require_typesystem(); + var AddressBinaryCodec = class { + /** + * Reads and decodes an AddressValue from a given buffer. + * + * @param buffer the input buffer + */ + decodeNested(buffer) { + let slice = buffer.slice(0, 32); + let value = new address_1.Address(slice); + return [new typesystem_1.AddressValue(value), 32]; + } + /** + * Reads and decodes an AddressValue from a given buffer. + * + * @param buffer the input buffer + */ + decodeTopLevel(buffer) { + let [decoded, _length] = this.decodeNested(buffer); + return decoded; + } + /** + * Encodes an AddressValue to a buffer. + */ + encodeNested(primitive) { + return primitive.valueOf().pubkey(); + } + /** + * Encodes an AddressValue to a buffer. + */ + encodeTopLevel(primitive) { + return primitive.valueOf().pubkey(); + } + }; + exports2.AddressBinaryCodec = AddressBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js +var require_boolean2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BooleanBinaryCodec = void 0; + var errors = __importStar2(require_errors()); + var typesystem_1 = require_typesystem(); + var BooleanBinaryCodec = class _BooleanBinaryCodec { + decodeNested(buffer) { + let byte = buffer.readUInt8(0); + return [new typesystem_1.BooleanValue(byte == _BooleanBinaryCodec.TRUE), 1]; + } + decodeTopLevel(buffer) { + if (buffer.length > 1) { + throw new errors.ErrInvalidArgument("buffer should be of size <= 1"); + } + let firstByte = buffer[0]; + return new typesystem_1.BooleanValue(firstByte == _BooleanBinaryCodec.TRUE); + } + encodeNested(primitive) { + if (primitive.isTrue()) { + return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); + } + return import_buffer.Buffer.from([_BooleanBinaryCodec.FALSE]); + } + encodeTopLevel(primitive) { + if (primitive.isTrue()) { + return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); + } + return import_buffer.Buffer.from([]); + } + }; + exports2.BooleanBinaryCodec = BooleanBinaryCodec; + BooleanBinaryCodec.TRUE = 1; + BooleanBinaryCodec.FALSE = 0; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js +var require_constants2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SizeOfU32 = void 0; + exports2.SizeOfU32 = 4; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js +var require_numerical2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NumericalBinaryCodec = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var typesystem_1 = require_typesystem(); + var constants_1 = require_constants2(); + var utils_1 = require_utils(); + var NumericalBinaryCodec = class { + decodeNested(buffer, type) { + let offset = 0; + let length2 = type.sizeInBytes; + if (!length2) { + offset = constants_1.SizeOfU32; + length2 = buffer.readUInt32BE(0); + } + let payload = buffer.slice(offset, offset + length2); + let result = this.decodeTopLevel(payload, type); + let decodedLength = length2 + offset; + return [result, decodedLength]; + } + decodeTopLevel(buffer, type) { + let payload = utils_1.cloneBuffer(buffer); + let empty2 = buffer.length == 0; + if (empty2) { + return new typesystem_1.NumericalValue(type, new bignumber_js_1.default(0)); + } + let isPositive = !type.withSign || utils_1.isMsbZero(payload); + if (isPositive) { + let value2 = utils_1.bufferToBigInt(payload); + return new typesystem_1.NumericalValue(type, value2); + } + utils_1.flipBufferBitsInPlace(payload); + let value = utils_1.bufferToBigInt(payload); + let negativeValue = value.multipliedBy(new bignumber_js_1.default(-1)); + let negativeValueMinusOne = negativeValue.minus(new bignumber_js_1.default(1)); + return new typesystem_1.NumericalValue(type, negativeValueMinusOne); + } + encodeNested(primitive) { + if (primitive.sizeInBytes) { + return this.encodeNestedFixedSize(primitive, primitive.sizeInBytes); + } + let buffer = this.encodeTopLevel(primitive); + let length2 = import_buffer.Buffer.alloc(constants_1.SizeOfU32); + length2.writeUInt32BE(buffer.length); + return import_buffer.Buffer.concat([length2, buffer]); + } + encodeNestedFixedSize(primitive, size) { + if (primitive.value.isZero()) { + return import_buffer.Buffer.alloc(size, 0); + } + if (!primitive.withSign) { + const buffer2 = utils_1.bigIntToBuffer(primitive.value); + const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); + return import_buffer.Buffer.concat([paddingBytes2, buffer2]); + } + if (primitive.value.isPositive()) { + let buffer2 = utils_1.bigIntToBuffer(primitive.value); + if (utils_1.isMsbOne(buffer2)) { + buffer2 = utils_1.prependByteToBuffer(buffer2, 0); + } + const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); + return import_buffer.Buffer.concat([paddingBytes2, buffer2]); + } + let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); + let buffer = utils_1.bigIntToBuffer(valuePlusOne); + utils_1.flipBufferBitsInPlace(buffer); + if (utils_1.isMsbZero(buffer)) { + buffer = utils_1.prependByteToBuffer(buffer, 255); + } + const paddingBytes = import_buffer.Buffer.alloc(size - buffer.length, 255); + return import_buffer.Buffer.concat([paddingBytes, buffer]); + } + encodeTopLevel(primitive) { + let withSign = primitive.withSign; + if (primitive.value.isZero()) { + return import_buffer.Buffer.alloc(0); + } + if (!withSign) { + return utils_1.bigIntToBuffer(primitive.value); + } + return this.encodePrimitive(primitive); + } + encodePrimitive(primitive) { + if (primitive.value.isPositive()) { + let buffer2 = utils_1.bigIntToBuffer(primitive.value); + if (utils_1.isMsbOne(buffer2)) { + buffer2 = utils_1.prependByteToBuffer(buffer2, 0); + } + return buffer2; + } + let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); + let buffer = utils_1.bigIntToBuffer(valuePlusOne); + utils_1.flipBufferBitsInPlace(buffer); + if (utils_1.isMsbZero(buffer)) { + buffer = utils_1.prependByteToBuffer(buffer, 255); + } + return buffer; + } + }; + exports2.NumericalBinaryCodec = NumericalBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js +var require_h2562 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.H256BinaryCodec = void 0; + var h256_1 = require_h256(); + var H256BinaryCodec = class { + /** + * Reads and decodes a H256Value from a given buffer. + * + * @param buffer the input buffer + */ + decodeNested(buffer) { + let slice = buffer.slice(0, 32); + return [new h256_1.H256Value(slice), 32]; + } + /** + * Reads and decodes a H256Value from a given buffer. + * + * @param buffer the input buffer + */ + decodeTopLevel(buffer) { + let [decoded, _length] = this.decodeNested(buffer); + return decoded; + } + /** + * Encodes a H256Value to a buffer. + */ + encodeNested(primitive) { + return primitive.valueOf(); + } + /** + * Encodes a H256Value to a buffer. + */ + encodeTopLevel(primitive) { + return primitive.valueOf(); + } + }; + exports2.H256BinaryCodec = H256BinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js +var require_bytes2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BytesBinaryCodec = void 0; + var bytes_1 = require_bytes(); + var constants_1 = require_constants2(); + var BytesBinaryCodec = class { + decodeNested(buffer) { + let length2 = buffer.readUInt32BE(0); + let payload = buffer.slice(constants_1.SizeOfU32, constants_1.SizeOfU32 + length2); + let result = new bytes_1.BytesValue(payload); + return [result, constants_1.SizeOfU32 + length2]; + } + decodeTopLevel(buffer) { + return new bytes_1.BytesValue(buffer); + } + encodeNested(bytes) { + let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); + lengthBuffer.writeUInt32BE(bytes.getLength()); + let buffer = import_buffer.Buffer.concat([lengthBuffer, bytes.valueOf()]); + return buffer; + } + encodeTopLevel(bytes) { + return bytes.valueOf(); + } + }; + exports2.BytesBinaryCodec = BytesBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js +var require_tokenIdentifier2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenIdentifierCodec = void 0; + var bytes_1 = require_bytes(); + var tokenIdentifier_1 = require_tokenIdentifier(); + var bytes_2 = require_bytes2(); + var TokenIdentifierCodec = class { + constructor() { + this.bytesCodec = new bytes_2.BytesBinaryCodec(); + } + decodeNested(buffer) { + let [bytesValue, length2] = this.bytesCodec.decodeNested(buffer); + return [new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()), length2]; + } + decodeTopLevel(buffer) { + let bytesValue = this.bytesCodec.decodeTopLevel(buffer); + return new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()); + } + encodeNested(tokenIdentifier) { + let bytesValue = bytes_1.BytesValue.fromUTF8(tokenIdentifier.valueOf()); + return this.bytesCodec.encodeNested(bytesValue); + } + encodeTopLevel(tokenIdentifier) { + return import_buffer.Buffer.from(tokenIdentifier.valueOf()); + } + }; + exports2.TokenIdentifierCodec = TokenIdentifierCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js +var require_nothing2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NothingCodec = void 0; + var typesystem_1 = require_typesystem(); + var NothingCodec = class { + decodeNested() { + return [new typesystem_1.NothingValue(), 0]; + } + decodeTopLevel() { + return new typesystem_1.NothingValue(); + } + encodeNested() { + return import_buffer.Buffer.from([]); + } + encodeTopLevel() { + return import_buffer.Buffer.from([]); + } + }; + exports2.NothingCodec = NothingCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js +var require_string2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StringBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var bytes_1 = require_bytes(); + var bytes_2 = require_bytes2(); + var StringBinaryCodec = class { + constructor() { + this.bytesBinaryCodec = new bytes_2.BytesBinaryCodec(); + } + decodeNested(buffer) { + let [decoded, length2] = this.bytesBinaryCodec.decodeNested(buffer); + let decodedAsString = new typesystem_1.StringValue(decoded.valueOf().toString()); + return [decodedAsString, length2]; + } + decodeTopLevel(buffer) { + return new typesystem_1.StringValue(buffer.toString()); + } + encodeNested(value) { + let valueAsBytes = bytes_1.BytesValue.fromUTF8(value.valueOf()); + return this.bytesBinaryCodec.encodeNested(valueAsBytes); + } + encodeTopLevel(value) { + return import_buffer.Buffer.from(value.valueOf()); + } + }; + exports2.StringBinaryCodec = StringBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js +var require_primitive = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PrimitiveBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var address_1 = require_address3(); + var boolean_1 = require_boolean2(); + var numerical_1 = require_numerical2(); + var h256_1 = require_h2562(); + var bytes_1 = require_bytes2(); + var tokenIdentifier_1 = require_tokenIdentifier2(); + var nothing_1 = require_nothing2(); + var string_1 = require_string2(); + var PrimitiveBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + this.booleanCodec = new boolean_1.BooleanBinaryCodec(); + this.numericalCodec = new numerical_1.NumericalBinaryCodec(); + this.addressCodec = new address_1.AddressBinaryCodec(); + this.h256Codec = new h256_1.H256BinaryCodec(); + this.bytesCodec = new bytes_1.BytesBinaryCodec(); + this.stringCodec = new string_1.StringBinaryCodec(); + this.tokenIdentifierCodec = new tokenIdentifier_1.TokenIdentifierCodec(); + this.nothingCodec = new nothing_1.NothingCodec(); + } + decodeNested(buffer, type) { + return typesystem_1.onPrimitiveTypeSelect(type, { + onBoolean: () => this.booleanCodec.decodeNested(buffer), + onNumerical: () => this.numericalCodec.decodeNested(buffer, type), + onAddress: () => this.addressCodec.decodeNested(buffer), + onBytes: () => this.bytesCodec.decodeNested(buffer), + onString: () => this.stringCodec.decodeNested(buffer), + onH256: () => this.h256Codec.decodeNested(buffer), + onTokenIndetifier: () => this.tokenIdentifierCodec.decodeNested(buffer), + onNothing: () => this.nothingCodec.decodeNested() + }); + } + decodeTopLevel(buffer, type) { + return typesystem_1.onPrimitiveTypeSelect(type, { + onBoolean: () => this.booleanCodec.decodeTopLevel(buffer), + onNumerical: () => this.numericalCodec.decodeTopLevel(buffer, type), + onAddress: () => this.addressCodec.decodeTopLevel(buffer), + onBytes: () => this.bytesCodec.decodeTopLevel(buffer), + onString: () => this.stringCodec.decodeTopLevel(buffer), + onH256: () => this.h256Codec.decodeTopLevel(buffer), + onTokenIndetifier: () => this.tokenIdentifierCodec.decodeTopLevel(buffer), + onNothing: () => this.nothingCodec.decodeTopLevel() + }); + } + encodeNested(value) { + return typesystem_1.onPrimitiveValueSelect(value, { + onBoolean: () => this.booleanCodec.encodeNested(value), + onNumerical: () => this.numericalCodec.encodeNested(value), + onAddress: () => this.addressCodec.encodeNested(value), + onBytes: () => this.bytesCodec.encodeNested(value), + onString: () => this.stringCodec.encodeNested(value), + onH256: () => this.h256Codec.encodeNested(value), + onTypeIdentifier: () => this.tokenIdentifierCodec.encodeNested(value), + onNothing: () => this.nothingCodec.encodeNested() + }); + } + encodeTopLevel(value) { + return typesystem_1.onPrimitiveValueSelect(value, { + onBoolean: () => this.booleanCodec.encodeTopLevel(value), + onNumerical: () => this.numericalCodec.encodeTopLevel(value), + onAddress: () => this.addressCodec.encodeTopLevel(value), + onBytes: () => this.bytesCodec.encodeTopLevel(value), + onString: () => this.stringCodec.encodeTopLevel(value), + onH256: () => this.h256Codec.encodeTopLevel(value), + onTypeIdentifier: () => this.tokenIdentifierCodec.encodeTopLevel(value), + onNothing: () => this.nothingCodec.encodeTopLevel() + }); + } + }; + exports2.PrimitiveBinaryCodec = PrimitiveBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js +var require_list = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ListBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var constants_1 = require_constants2(); + var ListBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, type) { + let typeParameter = type.getFirstTypeParameter(); + let result = []; + let numItems = buffer.readUInt32BE(0); + this.binaryCodec.constraints.checkListLength(numItems); + let originalBuffer = buffer; + let offset = constants_1.SizeOfU32; + buffer = originalBuffer.slice(offset); + for (let i2 = 0; i2 < numItems; i2++) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); + result.push(decoded); + offset += decodedLength; + buffer = originalBuffer.slice(offset); + } + return [new typesystem_1.List(type, result), offset]; + } + decodeTopLevel(buffer, type) { + let typeParameter = type.getFirstTypeParameter(); + let result = []; + let originalBuffer = buffer; + let offset = 0; + while (buffer.length > 0) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); + result.push(decoded); + offset += decodedLength; + buffer = originalBuffer.slice(offset); + this.binaryCodec.constraints.checkListLength(result.length); + } + return new typesystem_1.List(type, result); + } + encodeNested(list) { + this.binaryCodec.constraints.checkListLength(list.getLength()); + let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); + lengthBuffer.writeUInt32BE(list.getLength()); + let itemsBuffers = []; + for (const item of list.getItems()) { + let itemBuffer = this.binaryCodec.encodeNested(item); + itemsBuffers.push(itemBuffer); + } + let buffer = import_buffer.Buffer.concat([lengthBuffer, ...itemsBuffers]); + return buffer; + } + encodeTopLevel(list) { + this.binaryCodec.constraints.checkListLength(list.getLength()); + let itemsBuffers = []; + for (const item of list.getItems()) { + let itemBuffer = this.binaryCodec.encodeNested(item); + itemsBuffers.push(itemBuffer); + } + let buffer = import_buffer.Buffer.concat(itemsBuffers); + return buffer; + } + }; + exports2.ListBinaryCodec = ListBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js +var require_fields2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.FieldsBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var FieldsBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, fieldDefinitions) { + let fields = []; + let totalLength = 0; + for (const fieldDefinition of fieldDefinitions) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, fieldDefinition.type); + buffer = buffer.slice(decodedLength); + totalLength += decodedLength; + let field = new typesystem_1.Field(decoded, fieldDefinition.name); + fields.push(field); + } + return [fields, totalLength]; + } + encodeNested(fields) { + let buffers = []; + for (const field of fields) { + let fieldBuffer = this.binaryCodec.encodeNested(field.value); + buffers.push(fieldBuffer); + } + return import_buffer.Buffer.concat(buffers); + } + }; + exports2.FieldsBinaryCodec = FieldsBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js +var require_struct2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.StructBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var fields_1 = require_fields2(); + var StructBinaryCodec = class { + constructor(binaryCodec) { + this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); + } + decodeTopLevel(buffer, type) { + let [decoded] = this.decodeNested(buffer, type); + return decoded; + } + decodeNested(buffer, type) { + let fieldDefinitions = type.getFieldsDefinitions(); + let [fields, offset] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); + let struct = new typesystem_1.Struct(type, fields); + return [struct, offset]; + } + encodeNested(struct) { + let fields = struct.getFields(); + let buffer = this.fieldsCodec.encodeNested(fields); + return buffer; + } + encodeTopLevel(struct) { + return this.encodeNested(struct); + } + }; + exports2.StructBinaryCodec = StructBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js +var require_enum2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EnumBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var fields_1 = require_fields2(); + var EnumBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); + } + decodeTopLevel(buffer, type) { + let [enumValue] = this.decodeNested(buffer, type); + return enumValue; + } + decodeNested(buffer, type) { + let [discriminant, lengthOfDiscriminant] = this.readDiscriminant(buffer); + buffer = buffer.slice(lengthOfDiscriminant); + let variant = type.getVariantByDiscriminant(discriminant); + let fieldDefinitions = variant.getFieldsDefinitions(); + let [fields, lengthOfFields] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); + let enumValue = new typesystem_1.EnumValue(type, variant, fields); + return [enumValue, lengthOfDiscriminant + lengthOfFields]; + } + readDiscriminant(buffer) { + let [value, length2] = this.binaryCodec.decodeNested(buffer, new typesystem_1.U8Type()); + let discriminant = value.valueOf(); + return [discriminant, length2]; + } + encodeNested(enumValue) { + let discriminant = new typesystem_1.U8Value(enumValue.discriminant); + let discriminantBuffer = this.binaryCodec.encodeNested(discriminant); + let fields = enumValue.getFields(); + let fieldsBuffer = this.fieldsCodec.encodeNested(fields); + return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); + } + encodeTopLevel(enumValue) { + let fields = enumValue.getFields(); + let hasFields = fields.length > 0; + let fieldsBuffer = this.fieldsCodec.encodeNested(fields); + let discriminant = new typesystem_1.U8Value(enumValue.discriminant); + let discriminantBuffer = hasFields ? this.binaryCodec.encodeNested(discriminant) : this.binaryCodec.encodeTopLevel(discriminant); + return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); + } + }; + exports2.EnumBinaryCodec = EnumBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js +var require_tuple2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TupleBinaryCodec = void 0; + var struct_1 = require_struct2(); + var TupleBinaryCodec = class { + constructor(binaryCodec) { + this.structCodec = new struct_1.StructBinaryCodec(binaryCodec); + } + decodeTopLevel(buffer, type) { + return this.structCodec.decodeTopLevel(buffer, type); + } + decodeNested(buffer, type) { + return this.structCodec.decodeNested(buffer, type); + } + encodeNested(struct) { + return this.structCodec.encodeNested(struct); + } + encodeTopLevel(struct) { + return this.structCodec.encodeTopLevel(struct); + } + }; + exports2.TupleBinaryCodec = TupleBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js +var require_arrayVec = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArrayVecBinaryCodec = void 0; + var typesystem_1 = require_typesystem(); + var ArrayVecBinaryCodec = class { + constructor(binaryCodec) { + this.binaryCodec = binaryCodec; + } + decodeNested(buffer, type) { + let arrayLength = type.length; + let typeParameter = type.getFirstTypeParameter(); + let result = []; + let totalLength = 0; + for (let i2 = 0; i2 < arrayLength; i2++) { + let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); + result.push(decoded); + totalLength += decodedLength; + buffer = buffer.slice(decodedLength); + } + return [new typesystem_1.ArrayVec(type, result), totalLength]; + } + decodeTopLevel(buffer, type) { + let [result, _4] = this.decodeNested(buffer, type); + return result; + } + encodeNested(array) { + let itemsBuffers = []; + for (const item of array.getItems()) { + let itemBuffer = this.binaryCodec.encodeNested(item); + itemsBuffers.push(itemBuffer); + } + return import_buffer.Buffer.concat(itemsBuffers); + } + encodeTopLevel(array) { + return this.encodeNested(array); + } + }; + exports2.ArrayVecBinaryCodec = ArrayVecBinaryCodec; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js +var require_binary = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BinaryCodecConstraints = exports2.BinaryCodec = void 0; + var errors = __importStar2(require_errors()); + var typesystem_1 = require_typesystem(); + var utils_1 = require_utils2(); + var option_1 = require_option(); + var primitive_1 = require_primitive(); + var list_1 = require_list(); + var struct_1 = require_struct2(); + var enum_1 = require_enum2(); + var tuple_1 = require_tuple2(); + var arrayVec_1 = require_arrayVec(); + var BinaryCodec = class { + constructor(constraints = null) { + this.constraints = constraints || new BinaryCodecConstraints(); + this.optionCodec = new option_1.OptionValueBinaryCodec(this); + this.listCodec = new list_1.ListBinaryCodec(this); + this.arrayCodec = new arrayVec_1.ArrayVecBinaryCodec(this); + this.primitiveCodec = new primitive_1.PrimitiveBinaryCodec(this); + this.structCodec = new struct_1.StructBinaryCodec(this); + this.tupleCodec = new tuple_1.TupleBinaryCodec(this); + this.enumCodec = new enum_1.EnumBinaryCodec(this); + } + decodeTopLevel(buffer, type) { + this.constraints.checkBufferLength(buffer); + let typedValue = typesystem_1.onTypeSelect(type, { + onOption: () => this.optionCodec.decodeTopLevel(buffer, type.getFirstTypeParameter()), + onList: () => this.listCodec.decodeTopLevel(buffer, type), + onArray: () => this.arrayCodec.decodeTopLevel(buffer, type), + onPrimitive: () => this.primitiveCodec.decodeTopLevel(buffer, type), + onStruct: () => this.structCodec.decodeTopLevel(buffer, type), + onTuple: () => this.tupleCodec.decodeTopLevel(buffer, type), + onEnum: () => this.enumCodec.decodeTopLevel(buffer, type) + }); + return typedValue; + } + decodeNested(buffer, type) { + this.constraints.checkBufferLength(buffer); + let [typedResult, decodedLength] = typesystem_1.onTypeSelect(type, { + onOption: () => this.optionCodec.decodeNested(buffer, type.getFirstTypeParameter()), + onList: () => this.listCodec.decodeNested(buffer, type), + onArray: () => this.arrayCodec.decodeNested(buffer, type), + onPrimitive: () => this.primitiveCodec.decodeNested(buffer, type), + onStruct: () => this.structCodec.decodeNested(buffer, type), + onTuple: () => this.tupleCodec.decodeNested(buffer, type), + onEnum: () => this.enumCodec.decodeNested(buffer, type) + }); + return [typedResult, decodedLength]; + } + encodeNested(typedValue) { + utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); + return typesystem_1.onTypedValueSelect(typedValue, { + onPrimitive: () => this.primitiveCodec.encodeNested(typedValue), + onOption: () => this.optionCodec.encodeNested(typedValue), + onList: () => this.listCodec.encodeNested(typedValue), + onArray: () => this.arrayCodec.encodeNested(typedValue), + onStruct: () => this.structCodec.encodeNested(typedValue), + onTuple: () => this.tupleCodec.encodeNested(typedValue), + onEnum: () => this.enumCodec.encodeNested(typedValue) + }); + } + encodeTopLevel(typedValue) { + utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); + return typesystem_1.onTypedValueSelect(typedValue, { + onPrimitive: () => this.primitiveCodec.encodeTopLevel(typedValue), + onOption: () => this.optionCodec.encodeTopLevel(typedValue), + onList: () => this.listCodec.encodeTopLevel(typedValue), + onArray: () => this.arrayCodec.encodeTopLevel(typedValue), + onStruct: () => this.structCodec.encodeTopLevel(typedValue), + onTuple: () => this.tupleCodec.encodeTopLevel(typedValue), + onEnum: () => this.enumCodec.encodeTopLevel(typedValue) + }); + } + }; + exports2.BinaryCodec = BinaryCodec; + var BinaryCodecConstraints = class { + constructor(init) { + this.maxBufferLength = init?.maxBufferLength || 256e3; + this.maxListLength = init?.maxListLength || 128e3; + } + checkBufferLength(buffer) { + if (buffer.length > this.maxBufferLength) { + throw new errors.ErrCodec(`Buffer too large: ${buffer.length} > ${this.maxBufferLength}`); + } + } + /** + * This constraint avoids computer-freezing decode bugs (e.g. due to invalid ABI or struct definitions). + */ + checkListLength(length2) { + if (length2 > this.maxListLength) { + throw new errors.ErrCodec(`List too large: ${length2} > ${this.maxListLength}`); + } + } + }; + exports2.BinaryCodecConstraints = BinaryCodecConstraints; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js +var require_binaryCodecUtils = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.decodeBigNumber = exports2.decodeString = exports2.decodeBool = exports2.decodeUnsignedNumber = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var typesystem_1 = require_typesystem(); + var binary_1 = require_binary(); + var Codec2 = new binary_1.BinaryCodec(); + function decodeUnsignedNumber(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); + let raw = Number(value.valueOf()); + return raw; + } + exports2.decodeUnsignedNumber = decodeUnsignedNumber; + function decodeBool(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BooleanType()); + let raw = Boolean(value.valueOf()); + return raw; + } + exports2.decodeBool = decodeBool; + function decodeString(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BytesType()); + let raw = String(value.valueOf()); + return raw; + } + exports2.decodeString = decodeString; + function decodeBigNumber(buffer) { + let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); + let raw = new bignumber_js_1.default(value.valueOf()); + return raw; + } + exports2.decodeBigNumber = decodeBigNumber; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js +var require_codec2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_binary(), exports2); + __exportStar2(require_binaryCodecUtils(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js +var require_argSerializer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArgSerializer = void 0; + var constants_1 = require_constants(); + var codec_1 = require_codec2(); + var typesystem_1 = require_typesystem(); + var algebraic_1 = require_algebraic(); + var composite_1 = require_composite(); + var variadic_1 = require_variadic(); + var defaultArgSerializerOptions = { + codec: new codec_1.BinaryCodec() + }; + var ArgSerializer = class { + constructor(options) { + options = { ...defaultArgSerializerOptions, ...options }; + this.codec = options.codec; + } + /** + * Reads typed values from an arguments string (e.g. aa@bb@@cc), given parameter definitions. + */ + stringToValues(joinedString, parameters) { + let buffers = this.stringToBuffers(joinedString); + let values = this.buffersToValues(buffers, parameters); + return values; + } + /** + * Reads raw buffers from an arguments string (e.g. aa@bb@@cc). + */ + stringToBuffers(joinedString) { + return joinedString.split(constants_1.ARGUMENTS_SEPARATOR).map((item) => import_buffer.Buffer.from(item, "hex")); + } + /** + * Decodes a set of buffers into a set of typed values, given parameter definitions. + */ + buffersToValues(buffers, parameters) { + const self2 = this; + buffers = buffers || []; + let values = []; + let bufferIndex = 0; + let numBuffers = buffers.length; + for (let i2 = 0; i2 < parameters.length; i2++) { + let parameter = parameters[i2]; + let type = parameter.type; + let value = readValue(type); + values.push(value); + } + function readValue(type) { + if (type.hasExactClass(algebraic_1.OptionalType.ClassName)) { + const typedValue2 = readValue(type.getFirstTypeParameter()); + return new algebraic_1.OptionalValue(type, typedValue2); + } + if (type.hasExactClass(variadic_1.VariadicType.ClassName)) { + return readVariadicValue(type); + } + if (type.hasExactClass(composite_1.CompositeType.ClassName)) { + const typedValues = []; + for (const typeParameter of type.getTypeParameters()) { + typedValues.push(readValue(typeParameter)); + } + return new composite_1.CompositeValue(type, typedValues); + } + const typedValue = decodeNextBuffer(type); + return typedValue; + } + function readVariadicValue(type) { + const variadicType = type; + const typedValues = []; + if (variadicType.isCounted) { + const count = readValue(new typesystem_1.U32Type()).valueOf().toNumber(); + for (let i2 = 0; i2 < count; i2++) { + typedValues.push(readValue(type.getFirstTypeParameter())); + } + } else { + while (!hasReachedTheEnd()) { + typedValues.push(readValue(type.getFirstTypeParameter())); + } + } + return new variadic_1.VariadicValue(variadicType, typedValues); + } + function decodeNextBuffer(type) { + if (hasReachedTheEnd()) { + return null; + } + let buffer = buffers[bufferIndex++]; + let decodedValue = self2.codec.decodeTopLevel(buffer, type); + return decodedValue; + } + function hasReachedTheEnd() { + return bufferIndex >= numBuffers; + } + return values; + } + /** + * Serializes a set of typed values into an arguments string (e.g. aa@bb@@cc). + */ + valuesToString(values) { + let strings = this.valuesToStrings(values); + let argumentsString = strings.join(constants_1.ARGUMENTS_SEPARATOR); + let count = strings.length; + return { argumentsString, count }; + } + /** + * Serializes a set of typed values into a set of strings. + */ + valuesToStrings(values) { + let buffers = this.valuesToBuffers(values); + let strings = buffers.map((buffer) => buffer.toString("hex")); + return strings; + } + /** + * Serializes a set of typed values into a set of strings buffers. + * Variadic types and composite types might result into none, one or more buffers. + */ + valuesToBuffers(values) { + const self2 = this; + const buffers = []; + for (const value of values) { + handleValue(value); + } + function handleValue(value) { + if (value.hasExactClass(algebraic_1.OptionalValue.ClassName)) { + const valueAsOptional = value; + if (valueAsOptional.isSet()) { + handleValue(valueAsOptional.getTypedValue()); + } + return; + } + if (value.hasExactClass(variadic_1.VariadicValue.ClassName)) { + handleVariadicValue(value); + return; + } + if (value.hasExactClass(composite_1.CompositeValue.ClassName)) { + const valueAsComposite = value; + for (const item of valueAsComposite.getItems()) { + handleValue(item); + } + return; + } + const buffer = self2.codec.encodeTopLevel(value); + buffers.push(buffer); + } + function handleVariadicValue(value) { + const variadicType = value.getType(); + if (variadicType.isCounted) { + const countValue = new typesystem_1.U32Value(value.getItems().length); + buffers.push(self2.codec.encodeTopLevel(countValue)); + } + for (const item of value.getItems()) { + handleValue(item); + } + } + return buffers; + } + }; + exports2.ArgSerializer = ArgSerializer; + } +}); + +// node_modules/nanoassert/index.js +var require_nanoassert = __commonJS({ + "node_modules/nanoassert/index.js"(exports2, module2) { + init_shim(); + assert.notEqual = notEqual; + assert.notOk = notOk; + assert.equal = equal; + assert.ok = assert; + module2.exports = assert; + function equal(a3, b4, m3) { + assert(a3 == b4, m3); + } + function notEqual(a3, b4, m3) { + assert(a3 != b4, m3); + } + function notOk(t, m3) { + assert(!t, m3); + } + function assert(t, m3) { + if (!t) + throw new Error(m3 || "AssertionError"); + } + } +}); + +// node_modules/blake2b-wasm/blake2b.js +var require_blake2b = __commonJS({ + "node_modules/blake2b-wasm/blake2b.js"(exports2, module2) { + init_shim(); + module2.exports = loadWebAssembly; + loadWebAssembly.supported = typeof WebAssembly !== "undefined"; + function loadWebAssembly(opts) { + if (!loadWebAssembly.supported) + return null; + var imp = opts && opts.imports; + var wasm = toUint8Array("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"); + var ready = null; + var mod2 = { + buffer: wasm, + memory: null, + exports: null, + realloc, + onload + }; + onload(function() { + }); + return mod2; + function realloc(size) { + mod2.exports.memory.grow(Math.ceil(Math.abs(size - mod2.memory.length) / 65536)); + mod2.memory = new Uint8Array(mod2.exports.memory.buffer); + } + function onload(cb) { + if (mod2.exports) + return cb(); + if (ready) { + ready.then(cb.bind(null, null)).catch(cb); + return; + } + try { + if (opts && opts.async) + throw new Error("async"); + setup({ instance: new WebAssembly.Instance(new WebAssembly.Module(wasm), imp) }); + } catch (err) { + ready = WebAssembly.instantiate(wasm, imp).then(setup); + } + onload(cb); + } + function setup(w4) { + mod2.exports = w4.instance.exports; + mod2.memory = mod2.exports.memory && mod2.exports.memory.buffer && new Uint8Array(mod2.exports.memory.buffer); + } + } + function toUint8Array(s2) { + if (typeof atob === "function") + return new Uint8Array(atob(s2).split("").map(charCodeAt)); + return new (require_buffer2()).Buffer(s2, "base64"); + } + function charCodeAt(c4) { + return c4.charCodeAt(0); + } + } +}); + +// node_modules/blake2b-wasm/index.js +var require_blake2b_wasm = __commonJS({ + "node_modules/blake2b-wasm/index.js"(exports2, module2) { + init_shim(); + var assert = require_nanoassert(); + var wasm = require_blake2b()(); + var head = 64; + var freeList = []; + module2.exports = Blake2b; + var BYTES_MIN = module2.exports.BYTES_MIN = 16; + var BYTES_MAX = module2.exports.BYTES_MAX = 64; + var BYTES = module2.exports.BYTES = 32; + var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; + var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; + var KEYBYTES = module2.exports.KEYBYTES = 32; + var SALTBYTES = module2.exports.SALTBYTES = 16; + var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; + function Blake2b(digestLength, key, salt, personal, noAssert) { + if (!(this instanceof Blake2b)) + return new Blake2b(digestLength, key, salt, personal, noAssert); + if (!(wasm && wasm.exports)) + throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)"); + if (!digestLength) + digestLength = 32; + if (noAssert !== true) { + assert(digestLength >= BYTES_MIN, "digestLength must be at least " + BYTES_MIN + ", was given " + digestLength); + assert(digestLength <= BYTES_MAX, "digestLength must be at most " + BYTES_MAX + ", was given " + digestLength); + if (key != null) + assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); + if (key != null) + assert(key.length <= KEYBYTES_MAX, "key must be at least " + KEYBYTES_MAX + ", was given " + key.length); + if (salt != null) + assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); + if (personal != null) + assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); + } + if (!freeList.length) { + freeList.push(head); + head += 216; + } + this.digestLength = digestLength; + this.finalized = false; + this.pointer = freeList.pop(); + wasm.memory.fill(0, 0, 64); + wasm.memory[0] = this.digestLength; + wasm.memory[1] = key ? key.length : 0; + wasm.memory[2] = 1; + wasm.memory[3] = 1; + if (salt) + wasm.memory.set(salt, 32); + if (personal) + wasm.memory.set(personal, 48); + if (this.pointer + 216 > wasm.memory.length) + wasm.realloc(this.pointer + 216); + wasm.exports.blake2b_init(this.pointer, this.digestLength); + if (key) { + this.update(key); + wasm.memory.fill(0, head, head + key.length); + wasm.memory[this.pointer + 200] = 128; + } + } + Blake2b.prototype.update = function(input) { + assert(this.finalized === false, "Hash instance finalized"); + assert(input, "input must be TypedArray or Buffer"); + if (head + input.length > wasm.memory.length) + wasm.realloc(head + input.length); + wasm.memory.set(input, head); + wasm.exports.blake2b_update(this.pointer, head, head + input.length); + return this; + }; + Blake2b.prototype.digest = function(enc) { + assert(this.finalized === false, "Hash instance finalized"); + this.finalized = true; + freeList.push(this.pointer); + wasm.exports.blake2b_final(this.pointer); + if (!enc || enc === "binary") { + return wasm.memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength); + } + if (enc === "hex") { + return hexSlice(wasm.memory, this.pointer + 128, this.digestLength); + } + assert(enc.length >= this.digestLength, "input must be TypedArray or Buffer"); + for (var i2 = 0; i2 < this.digestLength; i2++) { + enc[i2] = wasm.memory[this.pointer + 128 + i2]; + } + return enc; + }; + Blake2b.prototype.final = Blake2b.prototype.digest; + Blake2b.WASM = wasm && wasm.buffer; + Blake2b.SUPPORTED = typeof WebAssembly !== "undefined"; + Blake2b.ready = function(cb) { + if (!cb) + cb = noop; + if (!wasm) + return cb(new Error("WebAssembly not supported")); + var p3 = new Promise(function(reject, resolve) { + wasm.onload(function(err) { + if (err) + resolve(); + else + reject(); + cb(err); + }); + }); + return p3; + }; + Blake2b.prototype.ready = Blake2b.ready; + function noop() { + } + function hexSlice(buf, start, len) { + var str = ""; + for (var i2 = 0; i2 < len; i2++) + str += toHex(buf[start + i2]); + return str; + } + function toHex(n3) { + if (n3 < 16) + return "0" + n3.toString(16); + return n3.toString(16); + } + } +}); + +// node_modules/blake2b/index.js +var require_blake2b2 = __commonJS({ + "node_modules/blake2b/index.js"(exports2, module2) { + init_shim(); + var assert = require_nanoassert(); + var b2wasm = require_blake2b_wasm(); + function ADD64AA(v3, a3, b4) { + var o0 = v3[a3] + v3[b4]; + var o1 = v3[a3 + 1] + v3[b4 + 1]; + if (o0 >= 4294967296) { + o1++; + } + v3[a3] = o0; + v3[a3 + 1] = o1; + } + function ADD64AC(v3, a3, b0, b1) { + var o0 = v3[a3] + b0; + if (b0 < 0) { + o0 += 4294967296; + } + var o1 = v3[a3 + 1] + b1; + if (o0 >= 4294967296) { + o1++; + } + v3[a3] = o0; + v3[a3 + 1] = o1; + } + function B2B_GET32(arr, i2) { + return arr[i2] ^ arr[i2 + 1] << 8 ^ arr[i2 + 2] << 16 ^ arr[i2 + 3] << 24; + } + function B2B_G(a3, b4, c4, d3, ix, iy) { + var x0 = m3[ix]; + var x1 = m3[ix + 1]; + var y0 = m3[iy]; + var y1 = m3[iy + 1]; + ADD64AA(v2, a3, b4); + ADD64AC(v2, a3, x0, x1); + var xor0 = v2[d3] ^ v2[a3]; + var xor1 = v2[d3 + 1] ^ v2[a3 + 1]; + v2[d3] = xor1; + v2[d3 + 1] = xor0; + ADD64AA(v2, c4, d3); + xor0 = v2[b4] ^ v2[c4]; + xor1 = v2[b4 + 1] ^ v2[c4 + 1]; + v2[b4] = xor0 >>> 24 ^ xor1 << 8; + v2[b4 + 1] = xor1 >>> 24 ^ xor0 << 8; + ADD64AA(v2, a3, b4); + ADD64AC(v2, a3, y0, y1); + xor0 = v2[d3] ^ v2[a3]; + xor1 = v2[d3 + 1] ^ v2[a3 + 1]; + v2[d3] = xor0 >>> 16 ^ xor1 << 16; + v2[d3 + 1] = xor1 >>> 16 ^ xor0 << 16; + ADD64AA(v2, c4, d3); + xor0 = v2[b4] ^ v2[c4]; + xor1 = v2[b4 + 1] ^ v2[c4 + 1]; + v2[b4] = xor1 >>> 31 ^ xor0 << 1; + v2[b4 + 1] = xor0 >>> 31 ^ xor1 << 1; + } + var BLAKE2B_IV32 = new Uint32Array([ + 4089235720, + 1779033703, + 2227873595, + 3144134277, + 4271175723, + 1013904242, + 1595750129, + 2773480762, + 2917565137, + 1359893119, + 725511199, + 2600822924, + 4215389547, + 528734635, + 327033209, + 1541459225 + ]); + var SIGMA8 = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + 11, + 8, + 12, + 0, + 5, + 2, + 15, + 13, + 10, + 14, + 3, + 6, + 7, + 1, + 9, + 4, + 7, + 9, + 3, + 1, + 13, + 12, + 11, + 14, + 2, + 6, + 5, + 10, + 4, + 0, + 15, + 8, + 9, + 0, + 5, + 7, + 2, + 4, + 10, + 15, + 14, + 1, + 11, + 12, + 6, + 8, + 3, + 13, + 2, + 12, + 6, + 10, + 0, + 11, + 8, + 3, + 4, + 13, + 7, + 5, + 15, + 14, + 1, + 9, + 12, + 5, + 1, + 15, + 14, + 13, + 4, + 10, + 0, + 7, + 6, + 3, + 9, + 2, + 8, + 11, + 13, + 11, + 7, + 14, + 12, + 1, + 3, + 9, + 5, + 0, + 15, + 4, + 8, + 6, + 2, + 10, + 6, + 15, + 14, + 9, + 11, + 3, + 0, + 8, + 12, + 2, + 13, + 7, + 1, + 4, + 10, + 5, + 10, + 2, + 8, + 4, + 7, + 6, + 1, + 5, + 15, + 11, + 9, + 14, + 3, + 12, + 13, + 0, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3 + ]; + var SIGMA82 = new Uint8Array(SIGMA8.map(function(x3) { + return x3 * 2; + })); + var v2 = new Uint32Array(32); + var m3 = new Uint32Array(32); + function blake2bCompress(ctx, last) { + var i2 = 0; + for (i2 = 0; i2 < 16; i2++) { + v2[i2] = ctx.h[i2]; + v2[i2 + 16] = BLAKE2B_IV32[i2]; + } + v2[24] = v2[24] ^ ctx.t; + v2[25] = v2[25] ^ ctx.t / 4294967296; + if (last) { + v2[28] = ~v2[28]; + v2[29] = ~v2[29]; + } + for (i2 = 0; i2 < 32; i2++) { + m3[i2] = B2B_GET32(ctx.b, 4 * i2); + } + for (i2 = 0; i2 < 12; i2++) { + B2B_G(0, 8, 16, 24, SIGMA82[i2 * 16 + 0], SIGMA82[i2 * 16 + 1]); + B2B_G(2, 10, 18, 26, SIGMA82[i2 * 16 + 2], SIGMA82[i2 * 16 + 3]); + B2B_G(4, 12, 20, 28, SIGMA82[i2 * 16 + 4], SIGMA82[i2 * 16 + 5]); + B2B_G(6, 14, 22, 30, SIGMA82[i2 * 16 + 6], SIGMA82[i2 * 16 + 7]); + B2B_G(0, 10, 20, 30, SIGMA82[i2 * 16 + 8], SIGMA82[i2 * 16 + 9]); + B2B_G(2, 12, 22, 24, SIGMA82[i2 * 16 + 10], SIGMA82[i2 * 16 + 11]); + B2B_G(4, 14, 16, 26, SIGMA82[i2 * 16 + 12], SIGMA82[i2 * 16 + 13]); + B2B_G(6, 8, 18, 28, SIGMA82[i2 * 16 + 14], SIGMA82[i2 * 16 + 15]); + } + for (i2 = 0; i2 < 16; i2++) { + ctx.h[i2] = ctx.h[i2] ^ v2[i2] ^ v2[i2 + 16]; + } + } + var parameter_block = new Uint8Array([ + 0, + 0, + 0, + 0, + // 0: outlen, keylen, fanout, depth + 0, + 0, + 0, + 0, + // 4: leaf length, sequential mode + 0, + 0, + 0, + 0, + // 8: node offset + 0, + 0, + 0, + 0, + // 12: node offset + 0, + 0, + 0, + 0, + // 16: node depth, inner length, rfu + 0, + 0, + 0, + 0, + // 20: rfu + 0, + 0, + 0, + 0, + // 24: rfu + 0, + 0, + 0, + 0, + // 28: rfu + 0, + 0, + 0, + 0, + // 32: salt + 0, + 0, + 0, + 0, + // 36: salt + 0, + 0, + 0, + 0, + // 40: salt + 0, + 0, + 0, + 0, + // 44: salt + 0, + 0, + 0, + 0, + // 48: personal + 0, + 0, + 0, + 0, + // 52: personal + 0, + 0, + 0, + 0, + // 56: personal + 0, + 0, + 0, + 0 + // 60: personal + ]); + function Blake2b(outlen, key, salt, personal) { + parameter_block.fill(0); + this.b = new Uint8Array(128); + this.h = new Uint32Array(16); + this.t = 0; + this.c = 0; + this.outlen = outlen; + parameter_block[0] = outlen; + if (key) + parameter_block[1] = key.length; + parameter_block[2] = 1; + parameter_block[3] = 1; + if (salt) + parameter_block.set(salt, 32); + if (personal) + parameter_block.set(personal, 48); + for (var i2 = 0; i2 < 16; i2++) { + this.h[i2] = BLAKE2B_IV32[i2] ^ B2B_GET32(parameter_block, i2 * 4); + } + if (key) { + blake2bUpdate(this, key); + this.c = 128; + } + } + Blake2b.prototype.update = function(input) { + assert(input != null, "input must be Uint8Array or Buffer"); + blake2bUpdate(this, input); + return this; + }; + Blake2b.prototype.digest = function(out) { + var buf = !out || out === "binary" || out === "hex" ? new Uint8Array(this.outlen) : out; + assert(buf.length >= this.outlen, "out must have at least outlen bytes of space"); + blake2bFinal(this, buf); + if (out === "hex") + return hexSlice(buf); + return buf; + }; + Blake2b.prototype.final = Blake2b.prototype.digest; + Blake2b.ready = function(cb) { + b2wasm.ready(function() { + cb(); + }); + }; + function blake2bUpdate(ctx, input) { + for (var i2 = 0; i2 < input.length; i2++) { + if (ctx.c === 128) { + ctx.t += ctx.c; + blake2bCompress(ctx, false); + ctx.c = 0; + } + ctx.b[ctx.c++] = input[i2]; + } + } + function blake2bFinal(ctx, out) { + ctx.t += ctx.c; + while (ctx.c < 128) { + ctx.b[ctx.c++] = 0; + } + blake2bCompress(ctx, true); + for (var i2 = 0; i2 < ctx.outlen; i2++) { + out[i2] = ctx.h[i2 >> 2] >> 8 * (i2 & 3); + } + return out; + } + function hexSlice(buf) { + var str = ""; + for (var i2 = 0; i2 < buf.length; i2++) + str += toHex(buf[i2]); + return str; + } + function toHex(n3) { + if (n3 < 16) + return "0" + n3.toString(16); + return n3.toString(16); + } + var Proto = Blake2b; + module2.exports = function createHash(outlen, key, salt, personal, noAssert) { + if (noAssert !== true) { + assert(outlen >= BYTES_MIN, "outlen must be at least " + BYTES_MIN + ", was given " + outlen); + assert(outlen <= BYTES_MAX, "outlen must be at most " + BYTES_MAX + ", was given " + outlen); + if (key != null) + assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); + if (key != null) + assert(key.length <= KEYBYTES_MAX, "key must be at most " + KEYBYTES_MAX + ", was given " + key.length); + if (salt != null) + assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); + if (personal != null) + assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); + } + return new Proto(outlen, key, salt, personal); + }; + module2.exports.ready = function(cb) { + b2wasm.ready(function() { + cb(); + }); + }; + module2.exports.WASM_SUPPORTED = b2wasm.SUPPORTED; + module2.exports.WASM_LOADED = false; + var BYTES_MIN = module2.exports.BYTES_MIN = 16; + var BYTES_MAX = module2.exports.BYTES_MAX = 64; + var BYTES = module2.exports.BYTES = 32; + var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; + var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; + var KEYBYTES = module2.exports.KEYBYTES = 32; + var SALTBYTES = module2.exports.SALTBYTES = 16; + var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; + b2wasm.ready(function(err) { + if (!err) { + module2.exports.WASM_LOADED = true; + Proto = b2wasm; + } + }); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/code.js +var require_code = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/code.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Code = void 0; + var createHasher = require_blake2b2(); + var CODE_HASH_LENGTH = 32; + var Code = class _Code { + constructor(hex) { + this.hex = hex; + } + /** + * Creates a Code object from a buffer (sequence of bytes). + */ + static fromBuffer(code2) { + return new _Code(code2.toString("hex")); + } + /** + * Creates a Code object from a hex-encoded string. + */ + static fromHex(hex) { + return new _Code(hex); + } + /** + * Returns the bytecode as a hex-encoded string. + */ + toString() { + return this.hex; + } + valueOf() { + return import_buffer.Buffer.from(this.hex, "hex"); + } + computeHash() { + const hash = createHasher(CODE_HASH_LENGTH).update(this.valueOf()).digest(); + return import_buffer.Buffer.from(hash); + } + }; + exports2.Code = Code; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js +var require_codeMetadata2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.CodeMetadata = void 0; + var CodeMetadata = class _CodeMetadata { + /** + * Creates a metadata object. By default, set the `upgradeable` attribute, and uset all others. + * + * @param upgradeable Whether the contract is upgradeable + * @param readable Whether other contracts can read this contract's data (without calling one of its pure functions) + * @param payable Whether the contract is payable + * @param payableBySc Whether the contract is payable by other smart contracts + */ + constructor(upgradeable = true, readable = false, payable = false, payableBySc = false) { + this.upgradeable = upgradeable; + this.readable = readable; + this.payable = payable; + this.payableBySc = payableBySc; + } + static fromBytes(bytes) { + return _CodeMetadata.fromBuffer(import_buffer.Buffer.from(bytes)); + } + /** + * Creates a metadata object from a buffer. + */ + static fromBuffer(buffer) { + if (buffer.length < this.codeMetadataLength) { + throw new Error("Buffer is too short."); + } + const byteZero = buffer[0]; + const byteOne = buffer[1]; + const upgradeable = (byteZero & _CodeMetadata.ByteZero.Upgradeable) !== 0; + const readable = (byteZero & _CodeMetadata.ByteZero.Readable) !== 0; + const payable = (byteOne & _CodeMetadata.ByteOne.Payable) !== 0; + const payableBySc = (byteOne & _CodeMetadata.ByteOne.PayableBySc) !== 0; + return new _CodeMetadata(upgradeable, readable, payable, payableBySc); + } + /** + * Adjust the metadata (the `upgradeable` attribute), when preparing the deployment transaction. + */ + toggleUpgradeable(value) { + this.upgradeable = value; + } + /** + * Adjust the metadata (the `readable` attribute), when preparing the deployment transaction. + */ + toggleReadable(value) { + this.readable = value; + } + /** + * Adjust the metadata (the `payable` attribute), when preparing the deployment transaction. + */ + togglePayable(value) { + this.payable = value; + } + /** + * Adjust the metadata (the `payableBySc` attribute), when preparing the deployment transaction. + */ + togglePayableBySc(value) { + this.payableBySc = value; + } + /** + * Converts the metadata to the protocol-friendly representation. + */ + toBuffer() { + let byteZero = 0; + let byteOne = 0; + if (this.upgradeable) { + byteZero |= _CodeMetadata.ByteZero.Upgradeable; + } + if (this.readable) { + byteZero |= _CodeMetadata.ByteZero.Readable; + } + if (this.payable) { + byteOne |= _CodeMetadata.ByteOne.Payable; + } + if (this.payableBySc) { + byteOne |= _CodeMetadata.ByteOne.PayableBySc; + } + return import_buffer.Buffer.from([byteZero, byteOne]); + } + /** + * Converts the metadata to a hex-encoded string. + */ + toString() { + return this.toBuffer().toString("hex"); + } + /** + * Converts the metadata to a pretty, plain JavaScript object. + */ + toJSON() { + return { + upgradeable: this.upgradeable, + readable: this.readable, + payable: this.payable, + payableBySc: this.payableBySc + }; + } + equals(other) { + return this.upgradeable == other.upgradeable && this.readable == other.readable && this.payable == other.payable && this.payableBySc == other.payableBySc; + } + }; + exports2.CodeMetadata = CodeMetadata; + CodeMetadata.codeMetadataLength = 2; + CodeMetadata.ByteZero = { + Upgradeable: 1, + Reserved2: 2, + Readable: 4 + }; + CodeMetadata.ByteOne = { + Reserved1: 1, + Payable: 2, + PayableBySc: 4 + }; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/function.js +var require_function = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/function.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractFunction = void 0; + var errors = __importStar2(require_errors()); + var ContractFunction = class _ContractFunction { + /** + * Creates a ContractFunction object, given its name. + * + * @param name the name of the function + */ + constructor(name2) { + this.name = name2; + if (name2 == null) { + throw new errors.ErrInvalidFunctionName(); + } + } + /** + * Null-object pattern: creates an empty ContractFunction object. + */ + static none() { + return new _ContractFunction("untitled"); + } + /** + * Returns the name of the function. + */ + toString() { + return this.name; + } + valueOf() { + return this.name; + } + }; + exports2.ContractFunction = ContractFunction; + } +}); + +// node_modules/@multiversx/sdk-core/out/compatibility.js +var require_compatibility = __commonJS({ + "node_modules/@multiversx/sdk-core/out/compatibility.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Compatibility = void 0; + var address_1 = require_address(); + var Compatibility = class { + /** + * For internal use only. + */ + static guardAddressIsSetAndNonZero(address, context, resolution) { + if (!address || address.bech32() == "") { + console.warn(`${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); + } else if (address.bech32() == address_1.Address.Zero().bech32()) { + console.warn(`${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); + } + } + }; + exports2.Compatibility = Compatibility; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionPayload.js +var require_transactionPayload = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionPayload.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionPayload = void 0; + var TransactionPayload = class _TransactionPayload { + /** + * Creates a TransactionPayload from a utf-8 string or from a buffer. + */ + constructor(data) { + this.data = import_buffer.Buffer.from(data || []); + } + /** + * Creates a TransactionPayload from a base-64 encoded string. + */ + static fromEncoded(encoded) { + if (!encoded) { + return new _TransactionPayload(""); + } + let decoded = import_buffer.Buffer.from(encoded, "base64").toString(); + return new _TransactionPayload(decoded); + } + /** + * Returns whether the "data" is void. + */ + isEmpty() { + return this.data.length == 0; + } + /** + * Returns the base-64 representation of the data. + */ + encoded() { + return this.data.toString("base64"); + } + /** + * Returns the data as a buffer. + */ + valueOf() { + return this.data; + } + toString() { + return this.data.toString(); + } + getEncodedArguments() { + return this.toString().split("@"); + } + getRawArguments() { + return this.getEncodedArguments().map((argument) => import_buffer.Buffer.from(argument, "hex")); + } + /** + * Returns the length of the data. + */ + length() { + return import_buffer.Buffer.from(this.data).length; + } + }; + exports2.TransactionPayload = TransactionPayload; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js +var require_transactionBuilder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionBuilder = void 0; + var constants_1 = require_constants(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var TransactionBuilder = class { + constructor(options) { + this.config = options.config; + this.sender = options.sender; + this.receiver = options.receiver; + this.dataParts = options.dataParts; + this.providedGasLimit = options.gasLimit; + this.addDataMovementGas = options.addDataMovementGas; + this.amount = options.amount; + } + computeGasLimit(payload) { + if (!this.addDataMovementGas) { + return this.providedGasLimit; + } + const dataMovementGas = this.config.minGasLimit + this.config.gasLimitPerByte * BigInt(payload.length()); + const gasLimit = dataMovementGas + this.providedGasLimit; + return gasLimit; + } + buildTransactionPayload() { + const data = this.dataParts.join(constants_1.ARGUMENTS_SEPARATOR); + return new transactionPayload_1.TransactionPayload(data); + } + build() { + const data = this.buildTransactionPayload(); + const gasLimit = this.computeGasLimit(data); + return new transaction_1.Transaction({ + sender: this.sender.bech32(), + receiver: this.receiver.bech32(), + gasLimit, + value: this.amount || 0n, + data: data.valueOf(), + chainID: this.config.chainID + }); + } + }; + exports2.TransactionBuilder = TransactionBuilder; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js +var require_delegationTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DelegationTransactionsFactory = void 0; + var address_1 = require_address(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var transactionBuilder_1 = require_transactionBuilder(); + var DelegationTransactionsFactory = class { + constructor(options) { + this.config = options.config; + this.argSerializer = new smartcontracts_1.ArgSerializer(); + } + createTransactionForNewDelegationContract(options) { + const dataParts = [ + "createNewDelegationContract", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.BigUIntValue(options.totalDelegationCap), + new smartcontracts_1.BigUIntValue(options.serviceFee) + ]) + ]; + const executionGasLimit = this.config.gasLimitCreateDelegationContract + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.DELEGATION_MANAGER_SC_ADDRESS), + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true, + amount: options.amount + }).build(); + } + createTransactionForAddingNodes(options) { + if (options.publicKeys.length !== options.signedMessages.length) { + throw new errors_1.Err("The number of public keys should match the number of signed messages"); + } + const signedMessagesAsTypedValues = options.signedMessages.map((message) => new smartcontracts_1.BytesValue(import_buffer.Buffer.from(message))); + const messagesAsStrings = this.argSerializer.valuesToStrings(signedMessagesAsTypedValues); + const numNodes = options.publicKeys.length; + const dataParts = ["addNodes"]; + for (let i2 = 0; i2 < numNodes; i2++) { + dataParts.push(...[options.publicKeys[i2].hex(), messagesAsStrings[i2]]); + } + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), + addDataMovementGas: true + }).build(); + } + createTransactionForRemovingNodes(options) { + const dataParts = ["removeNodes"]; + for (const key of options.publicKeys) { + dataParts.push(key.hex()); + } + const numNodes = options.publicKeys.length; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), + addDataMovementGas: true + }).build(); + } + createTransactionForStakingNodes(options) { + let dataParts = ["stakeNodes"]; + for (const key of options.publicKeys) { + dataParts = dataParts.concat(key.hex()); + } + const numNodes = options.publicKeys.length; + const additionalGasForAllNodes = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode; + const executionGasLimit = additionalGasForAllNodes + this.config.gasLimitStake + this.config.gasLimitDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnbondingNodes(options) { + let dataParts = ["unBondNodes"]; + for (const key of options.publicKeys) { + dataParts = dataParts.concat(key.hex()); + } + const numNodes = options.publicKeys.length; + const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnbond + this.config.gasLimitDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnstakingNodes(options) { + let dataParts = ["unStakeNodes"]; + for (const key of options.publicKeys) { + dataParts = dataParts.concat(key.hex()); + } + const numNodes = options.publicKeys.length; + const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnstake + this.config.gasLimitDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: executionGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnjailingNodes(options) { + const dataParts = ["unJailNodes"]; + for (const key of options.publicKeys) { + dataParts.push(key.hex()); + } + const numNodes = options.publicKeys.length; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), + addDataMovementGas: true + }).build(); + } + createTransactionForChangingServiceFee(options) { + const dataParts = [ + "changeServiceFee", + this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.serviceFee)])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForModifyingDelegationCap(options) { + const dataParts = [ + "modifyTotalDelegationCap", + this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.delegationCap)])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingAutomaticActivation(options) { + const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0]]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnsettingAutomaticActivation(options) { + const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0]]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingCapCheckOnRedelegateRewards(options) { + const dataParts = [ + "setCheckCapOnReDelegateRewards", + this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForUnsettingCapCheckOnRedelegateRewards(options) { + const dataParts = [ + "setCheckCapOnReDelegateRewards", + this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0] + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingMetadata(options) { + const dataParts = [ + "setMetaData", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.name), + new smartcontracts_1.StringValue(options.website), + new smartcontracts_1.StringValue(options.identifier) + ]) + ]; + const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.delegationContract, + dataParts, + gasLimit, + addDataMovementGas: true + }).build(); + } + computeExecutionGasLimitForNodesManagement(numNodes) { + const additionalGasForAllNodes = this.config.additionalGasLimitPerValidatorNode * BigInt(numNodes); + return this.config.gasLimitDelegationOperations + additionalGasForAllNodes; + } + }; + exports2.DelegationTransactionsFactory = DelegationTransactionsFactory; + } +}); + +// node_modules/json-bigint/lib/stringify.js +var require_stringify = __commonJS({ + "node_modules/json-bigint/lib/stringify.js"(exports2, module2) { + init_shim(); + var BigNumber2 = require_bignumber(); + var JSON2 = module2.exports; + (function() { + "use strict"; + function f4(n3) { + return n3 < 10 ? "0" + n3 : n3; + } + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { + // table of character substitutions + "\b": "\\b", + " ": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\" + }, rep; + function quote(string2) { + escapable.lastIndex = 0; + return escapable.test(string2) ? '"' + string2.replace(escapable, function(a3) { + var c4 = meta[a3]; + return typeof c4 === "string" ? c4 : "\\u" + ("0000" + a3.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string2 + '"'; + } + function str(key, holder) { + var i2, k4, v2, length2, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber2 || BigNumber2.isBigNumber(value)); + if (value && typeof value === "object" && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + if (typeof rep === "function") { + value = rep.call(holder, key, value); + } + switch (typeof value) { + case "string": + if (isBigNumber) { + return value; + } else { + return quote(value); + } + case "number": + return isFinite(value) ? String(value) : "null"; + case "boolean": + case "null": + case "bigint": + return String(value); + case "object": + if (!value) { + return "null"; + } + gap += indent; + partial = []; + if (Object.prototype.toString.apply(value) === "[object Array]") { + length2 = value.length; + for (i2 = 0; i2 < length2; i2 += 1) { + partial[i2] = str(i2, value) || "null"; + } + v2 = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]"; + gap = mind; + return v2; + } + if (rep && typeof rep === "object") { + length2 = rep.length; + for (i2 = 0; i2 < length2; i2 += 1) { + if (typeof rep[i2] === "string") { + k4 = rep[i2]; + v2 = str(k4, value); + if (v2) { + partial.push(quote(k4) + (gap ? ": " : ":") + v2); + } + } + } + } else { + Object.keys(value).forEach(function(k5) { + var v3 = str(k5, value); + if (v3) { + partial.push(quote(k5) + (gap ? ": " : ":") + v3); + } + }); + } + v2 = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; + gap = mind; + return v2; + } + } + if (typeof JSON2.stringify !== "function") { + JSON2.stringify = function(value, replacer, space) { + var i2; + gap = ""; + indent = ""; + if (typeof space === "number") { + for (i2 = 0; i2 < space; i2 += 1) { + indent += " "; + } + } else if (typeof space === "string") { + indent = space; + } + rep = replacer; + if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { + throw new Error("JSON.stringify"); + } + return str("", { "": value }); + }; + } + })(); + } +}); + +// node_modules/json-bigint/lib/parse.js +var require_parse = __commonJS({ + "node_modules/json-bigint/lib/parse.js"(exports2, module2) { + init_shim(); + var BigNumber2 = null; + var suspectProtoRx2 = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; + var suspectConstructorRx2 = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; + var json_parse = function(options) { + "use strict"; + var _options = { + strict: false, + // not being strict means do not generate syntax errors for "duplicate key" + storeAsString: false, + // toggles whether the values should be stored as BigNumber (default) or a string + alwaysParseAsBig: false, + // toggles whether all numbers should be Big + useNativeBigInt: false, + // toggles whether to use native BigInt instead of bignumber.js + protoAction: "error", + constructorAction: "error" + }; + if (options !== void 0 && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; + _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; + if (typeof options.constructorAction !== "undefined") { + if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { + _options.constructorAction = options.constructorAction; + } else { + throw new Error( + `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` + ); + } + } + if (typeof options.protoAction !== "undefined") { + if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { + _options.protoAction = options.protoAction; + } else { + throw new Error( + `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` + ); + } + } + } + var at, ch, escapee = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: " " + }, text, error = function(m3) { + throw { + name: "SyntaxError", + message: m3, + at, + text + }; + }, next = function(c4) { + if (c4 && c4 !== ch) { + error("Expected '" + c4 + "' instead of '" + ch + "'"); + } + ch = text.charAt(at); + at += 1; + return ch; + }, number = function() { + var number2, string3 = ""; + if (ch === "-") { + string3 = "-"; + next("-"); + } + while (ch >= "0" && ch <= "9") { + string3 += ch; + next(); + } + if (ch === ".") { + string3 += "."; + while (next() && ch >= "0" && ch <= "9") { + string3 += ch; + } + } + if (ch === "e" || ch === "E") { + string3 += ch; + next(); + if (ch === "-" || ch === "+") { + string3 += ch; + next(); + } + while (ch >= "0" && ch <= "9") { + string3 += ch; + next(); + } + } + number2 = +string3; + if (!isFinite(number2)) { + error("Bad number"); + } else { + if (BigNumber2 == null) + BigNumber2 = require_bignumber(); + if (string3.length > 15) + return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber2(string3); + else + return !_options.alwaysParseAsBig ? number2 : _options.useNativeBigInt ? BigInt(number2) : new BigNumber2(number2); + } + }, string2 = function() { + var hex, i2, string3 = "", uffff; + if (ch === '"') { + var startAt = at; + while (next()) { + if (ch === '"') { + if (at - 1 > startAt) + string3 += text.substring(startAt, at - 1); + next(); + return string3; + } + if (ch === "\\") { + if (at - 1 > startAt) + string3 += text.substring(startAt, at - 1); + next(); + if (ch === "u") { + uffff = 0; + for (i2 = 0; i2 < 4; i2 += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string3 += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === "string") { + string3 += escapee[ch]; + } else { + break; + } + startAt = at; + } + } + } + error("Bad string"); + }, white = function() { + while (ch && ch <= " ") { + next(); + } + }, word = function() { + switch (ch) { + case "t": + next("t"); + next("r"); + next("u"); + next("e"); + return true; + case "f": + next("f"); + next("a"); + next("l"); + next("s"); + next("e"); + return false; + case "n": + next("n"); + next("u"); + next("l"); + next("l"); + return null; + } + error("Unexpected '" + ch + "'"); + }, value, array = function() { + var array2 = []; + if (ch === "[") { + next("["); + white(); + if (ch === "]") { + next("]"); + return array2; + } + while (ch) { + array2.push(value()); + white(); + if (ch === "]") { + next("]"); + return array2; + } + next(","); + white(); + } + } + error("Bad array"); + }, object = function() { + var key, object2 = /* @__PURE__ */ Object.create(null); + if (ch === "{") { + next("{"); + white(); + if (ch === "}") { + next("}"); + return object2; + } + while (ch) { + key = string2(); + white(); + next(":"); + if (_options.strict === true && Object.hasOwnProperty.call(object2, key)) { + error('Duplicate key "' + key + '"'); + } + if (suspectProtoRx2.test(key) === true) { + if (_options.protoAction === "error") { + error("Object contains forbidden prototype property"); + } else if (_options.protoAction === "ignore") { + value(); + } else { + object2[key] = value(); + } + } else if (suspectConstructorRx2.test(key) === true) { + if (_options.constructorAction === "error") { + error("Object contains forbidden constructor property"); + } else if (_options.constructorAction === "ignore") { + value(); + } else { + object2[key] = value(); + } + } else { + object2[key] = value(); + } + white(); + if (ch === "}") { + next("}"); + return object2; + } + next(","); + white(); + } + } + error("Bad object"); + }; + value = function() { + white(); + switch (ch) { + case "{": + return object(); + case "[": + return array(); + case '"': + return string2(); + case "-": + return number(); + default: + return ch >= "0" && ch <= "9" ? number() : word(); + } + }; + return function(source, reviver) { + var result; + text = source + ""; + at = 0; + ch = " "; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + return typeof reviver === "function" ? function walk(holder, key) { + var k4, v2, value2 = holder[key]; + if (value2 && typeof value2 === "object") { + Object.keys(value2).forEach(function(k5) { + v2 = walk(value2, k5); + if (v2 !== void 0) { + value2[k5] = v2; + } else { + delete value2[k5]; + } + }); + } + return reviver.call(holder, key, value2); + }({ "": result }, "") : result; + }; + }; + module2.exports = json_parse; + } +}); + +// node_modules/json-bigint/index.js +var require_json_bigint = __commonJS({ + "node_modules/json-bigint/index.js"(exports2, module2) { + init_shim(); + var json_stringify = require_stringify().stringify; + var json_parse = require_parse(); + module2.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + }; + }; + module2.exports.parse = json_parse(); + module2.exports.stringify = json_stringify; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js +var require_relayedTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RelayedTransactionsFactory = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var transaction_1 = require_transaction(); + var JSONbig = require_json_bigint(); + var RelayedTransactionsFactory = class { + constructor(options) { + this.config = options.config; + } + createRelayedV1Transaction(options) { + if (!options.innerTransaction.gasLimit) { + throw new errors_1.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); + } + if (!options.innerTransaction.signature.length) { + throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); + } + const serializedTransaction = this.prepareInnerTransactionForRelayedV1(options.innerTransaction); + const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; + const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); + const gasLimit = this.config.minGasLimit + additionalGasForDataLength + options.innerTransaction.gasLimit; + return new transaction_1.Transaction({ + chainID: this.config.chainID, + sender: options.relayerAddress.bech32(), + receiver: options.innerTransaction.sender, + gasLimit, + data: import_buffer.Buffer.from(data) + }); + } + createRelayedV2Transaction(options) { + if (options.innerTransaction.gasLimit) { + throw new errors_1.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction"); + } + if (!options.innerTransaction.signature.length) { + throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + new smartcontracts_1.AddressValue(address_1.Address.fromBech32(options.innerTransaction.receiver)), + new smartcontracts_1.U64Value(new bignumber_js_1.default(options.innerTransaction.nonce.toString())), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.data)), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.signature)) + ]); + const data = `relayedTxV2@${argumentsString}`; + const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); + const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; + return new transaction_1.Transaction({ + sender: options.relayerAddress.bech32(), + receiver: options.innerTransaction.sender, + value: 0n, + gasLimit, + chainID: this.config.chainID, + data: import_buffer.Buffer.from(data), + version: options.innerTransaction.version, + options: options.innerTransaction.options + }); + } + prepareInnerTransactionForRelayedV1(innerTransaction) { + const txObject = { + nonce: innerTransaction.nonce, + sender: address_1.Address.fromBech32(innerTransaction.sender).pubkey().toString("base64"), + receiver: address_1.Address.fromBech32(innerTransaction.receiver).pubkey().toString("base64"), + value: innerTransaction.value, + gasPrice: innerTransaction.gasPrice, + gasLimit: innerTransaction.gasLimit, + data: import_buffer.Buffer.from(innerTransaction.data).toString("base64"), + signature: import_buffer.Buffer.from(innerTransaction.signature).toString("base64"), + chainID: import_buffer.Buffer.from(innerTransaction.chainID).toString("base64"), + version: innerTransaction.version, + options: innerTransaction.options.valueOf() == 0 ? void 0 : innerTransaction.options, + guardian: innerTransaction.guardian ? address_1.Address.fromBech32(innerTransaction.guardian).pubkey().toString("base64") : void 0, + guardianSignature: innerTransaction.guardianSignature.length ? import_buffer.Buffer.from(innerTransaction.guardianSignature).toString("base64") : void 0, + sndUserName: innerTransaction.senderUsername ? import_buffer.Buffer.from(innerTransaction.senderUsername).toString("base64") : void 0, + rcvUserName: innerTransaction.receiverUsername ? import_buffer.Buffer.from(innerTransaction.receiverUsername).toString("base64") : void 0 + }; + return JSONbig.stringify(txObject); + } + }; + exports2.RelayedTransactionsFactory = RelayedTransactionsFactory; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js +var require_argumentErrorContext = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ArgumentErrorContext = void 0; + var errors_1 = require_errors(); + var ArgumentErrorContext = class { + constructor(endpointName, argumentIndex, parameterDefinition) { + this.endpointName = endpointName; + this.argumentIndex = argumentIndex; + this.parameterDefinition = parameterDefinition; + } + throwError(specificError) { + throw new errors_1.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) +Nested error: ${specificError}`); + } + convertError(native, typeName) { + this.throwError(`Can't convert argument (argument: ${native}, type ${typeof native}), wanted type: ${typeName})`); + } + unhandledType(functionName, type) { + this.throwError(`Unhandled type (function: ${functionName}, type: ${type})`); + } + guardSameLength(native, valueTypes) { + native = native || []; + if (native.length != valueTypes.length) { + this.throwError(`Incorrect composite type length: have ${native.length}, expected ${valueTypes.length} (argument: ${native})`); + } + } + guardHasField(native, fieldName) { + native = native || {}; + if (!(fieldName in native)) { + this.throwError(`Struct argument does not contain a field named "${fieldName}" (argument: ${JSON.stringify(native)})`); + } + } + }; + exports2.ArgumentErrorContext = ArgumentErrorContext; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js +var require_nativeSerializer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NativeSerializer = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var errors_1 = require_errors(); + var utils_codec_1 = require_utils_codec(); + var argumentErrorContext_1 = require_argumentErrorContext(); + var typesystem_1 = require_typesystem(); + var NativeSerializer; + (function(NativeSerializer2) { + function nativeToTypedValues(args, endpoint) { + args = args || []; + checkArgumentsCardinality(args, endpoint); + if (hasNonCountedVariadicParameter(endpoint)) { + args = repackNonCountedVariadicParameters(args, endpoint); + } else { + } + let parameters = endpoint.input; + let values = []; + for (let i2 = 0; i2 < parameters.length; i2++) { + let parameter = parameters[i2]; + let errorContext = new argumentErrorContext_1.ArgumentErrorContext(endpoint.name, i2, parameter); + let value = convertToTypedValue(args[i2], parameter.type, errorContext); + values.push(value); + } + return values; + } + NativeSerializer2.nativeToTypedValues = nativeToTypedValues; + function checkArgumentsCardinality(args, endpoint) { + const { min, max } = getArgumentsCardinality(endpoint.input); + if (!(min <= args.length && args.length <= max)) { + throw new errors_1.ErrInvalidArgument(`Wrong number of arguments for endpoint ${endpoint.name}: expected between ${min} and ${max} arguments, have ${args.length}`); + } + } + function hasNonCountedVariadicParameter(endpoint) { + const lastParameter = endpoint.input[endpoint.input.length - 1]; + return lastParameter?.type instanceof typesystem_1.VariadicType && !lastParameter.type.isCounted; + } + function repackNonCountedVariadicParameters(args, endpoint) { + const lastEndpointParamIndex = endpoint.input.length - 1; + const argAtIndex = args[lastEndpointParamIndex]; + if (argAtIndex?.belongsToTypesystem) { + const isVariadicValue = argAtIndex.hasClassOrSuperclass(typesystem_1.VariadicValue.ClassName); + if (!isVariadicValue) { + throw new errors_1.ErrInvalidArgument(`Wrong argument type for endpoint ${endpoint.name}: typed value provided; expected variadic type, have ${argAtIndex.getClassName()}`); + } + } else { + args[lastEndpointParamIndex] = args.slice(lastEndpointParamIndex); + } + return args; + } + function getArgumentsCardinality(parameters) { + let reversed = [...parameters].reverse(); + let min = parameters.length; + let max = parameters.length; + let variadic = false; + if (reversed.length > 0 && reversed[0].type.getCardinality().isComposite()) { + max = Infinity; + variadic = true; + } + for (let parameter of reversed) { + if (parameter.type.getCardinality().isSingular()) { + break; + } + min -= 1; + } + return { min, max, variadic }; + } + NativeSerializer2.getArgumentsCardinality = getArgumentsCardinality; + function convertToTypedValue(value, type, errorContext) { + if (value && value.belongsToTypesystem) { + return value; + } + if (type instanceof typesystem_1.OptionType) { + return toOptionValue(value, type, errorContext); + } + if (type instanceof typesystem_1.OptionalType) { + return toOptionalValue(value, type, errorContext); + } + if (type instanceof typesystem_1.VariadicType) { + return toVariadicValue(value, type, errorContext); + } + if (type instanceof typesystem_1.CompositeType) { + return toCompositeValue(value, type, errorContext); + } + if (type instanceof typesystem_1.TupleType) { + return toTupleValue(value, type, errorContext); + } + if (type instanceof typesystem_1.StructType) { + return toStructValue(value, type, errorContext); + } + if (type instanceof typesystem_1.ListType) { + return toListValue(value, type, errorContext); + } + if (type instanceof typesystem_1.PrimitiveType) { + return toPrimitive(value, type, errorContext); + } + if (type instanceof typesystem_1.EnumType) { + return toEnumValue(value, type, errorContext); + } + errorContext.throwError(`convertToTypedValue: unhandled type ${type}`); + } + function toOptionValue(native, type, errorContext) { + if (native == null) { + return typesystem_1.OptionValue.newMissing(); + } + let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); + return typesystem_1.OptionValue.newProvided(converted); + } + function toOptionalValue(native, type, errorContext) { + if (native == null) { + return new typesystem_1.OptionalValue(type); + } + let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); + return new typesystem_1.OptionalValue(type, converted); + } + function toVariadicValue(native, type, errorContext) { + if (type.isCounted) { + throw new errors_1.ErrInvalidArgument(`Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"`); + } + if (native == null) { + native = []; + } + if (native.map === void 0) { + errorContext.convertError(native, "Variadic"); + } + let converted = native.map(function(item) { + return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); + }); + return new typesystem_1.VariadicValue(type, converted); + } + function toListValue(native, type, errorContext) { + if (native.map === void 0) { + errorContext.convertError(native, "List"); + } + let converted = native.map(function(item) { + return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); + }); + return new typesystem_1.List(type, converted); + } + function toCompositeValue(native, type, errorContext) { + let typedValues = []; + let typeParameters = type.getTypeParameters(); + errorContext.guardSameLength(native, typeParameters); + for (let i2 = 0; i2 < typeParameters.length; i2++) { + typedValues.push(convertToTypedValue(native[i2], typeParameters[i2], errorContext)); + } + return new typesystem_1.CompositeValue(type, typedValues); + } + function toTupleValue(native, type, errorContext) { + let typedValues = []; + const fields = type.getFieldsDefinitions(); + errorContext.guardSameLength(native, fields); + for (let i2 = 0; i2 < fields.length; i2++) { + typedValues.push(convertToTypedValue(native[i2], fields[i2].type, errorContext)); + } + return typesystem_1.Tuple.fromItems(typedValues); + } + function toStructValue(native, type, errorContext) { + let structFieldValues = []; + const fields = type.getFieldsDefinitions(); + for (let i2 = 0; i2 < fields.length; i2++) { + const fieldName = fields[i2].name; + errorContext.guardHasField(native, fieldName); + const fieldNativeValue = native[fieldName]; + const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); + structFieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); + } + return new typesystem_1.Struct(type, structFieldValues); + } + function toPrimitive(native, type, errorContext) { + if (type instanceof typesystem_1.NumericalType) { + let number = new bignumber_js_1.default(native); + return convertNumericalType(number, type, errorContext); + } + if (type instanceof typesystem_1.BytesType) { + return convertNativeToBytesValue(native, errorContext); + } + if (type instanceof typesystem_1.AddressType) { + return new typesystem_1.AddressValue(convertNativeToAddress(native, errorContext)); + } + if (type instanceof typesystem_1.BooleanType) { + return new typesystem_1.BooleanValue(native); + } + if (type instanceof typesystem_1.TokenIdentifierType) { + return new typesystem_1.TokenIdentifierValue(convertNativeToString(native, errorContext)); + } + errorContext.throwError(`(function: toPrimitive) unsupported type ${type}`); + } + function toEnumValue(native, type, errorContext) { + if (typeof native === "number") { + return typesystem_1.EnumValue.fromDiscriminant(type, native); + } + if (typeof native === "string") { + return typesystem_1.EnumValue.fromName(type, native); + } + if (typeof native === "object") { + errorContext.guardHasField(native, "name"); + const variant = type.getVariantByName(native.name); + errorContext.guardHasField(native, "fields"); + const nativeFields = native.fields; + const fieldValues = []; + const fields = variant.getFieldsDefinitions(); + for (let i2 = 0; i2 < fields.length; i2++) { + const fieldName = fields[i2].name; + errorContext.guardHasField(nativeFields, fieldName); + const fieldNativeValue = nativeFields[fieldName]; + const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); + fieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); + } + return new typesystem_1.EnumValue(type, variant, fieldValues); + } + errorContext.throwError(`(function: toEnumValue) unsupported native type ${typeof native}`); + } + function convertNativeToBytesValue(native, errorContext) { + const innerValue = native.valueOf(); + if (native === void 0) { + errorContext.convertError(native, "BytesValue"); + } + if (native instanceof import_buffer.Buffer) { + return new typesystem_1.BytesValue(native); + } + if (typeof native === "string") { + return typesystem_1.BytesValue.fromUTF8(native); + } + if (innerValue instanceof import_buffer.Buffer) { + return new typesystem_1.BytesValue(innerValue); + } + if (typeof innerValue === "number") { + return typesystem_1.BytesValue.fromHex(utils_codec_1.numberToPaddedHex(innerValue)); + } + errorContext.convertError(native, "BytesValue"); + } + function convertNativeToString(native, errorContext) { + if (native === void 0) { + errorContext.convertError(native, "Buffer"); + } + if (native instanceof import_buffer.Buffer) { + return native.toString(); + } + if (typeof native === "string") { + return native; + } + errorContext.convertError(native, "Buffer"); + } + function convertNativeToAddress(native, errorContext) { + if (native.bech32) { + return native; + } + if (native.getAddress) { + return native.getAddress(); + } + switch (native.constructor) { + case import_buffer.Buffer: + case String: + return new address_1.Address(native); + default: + errorContext.convertError(native, "Address"); + } + } + NativeSerializer2.convertNativeToAddress = convertNativeToAddress; + function convertNumericalType(number, type, errorContext) { + switch (type.constructor) { + case typesystem_1.U8Type: + return new typesystem_1.U8Value(number); + case typesystem_1.I8Type: + return new typesystem_1.I8Value(number); + case typesystem_1.U16Type: + return new typesystem_1.U16Value(number); + case typesystem_1.I16Type: + return new typesystem_1.I16Value(number); + case typesystem_1.U32Type: + return new typesystem_1.U32Value(number); + case typesystem_1.I32Type: + return new typesystem_1.I32Value(number); + case typesystem_1.U64Type: + return new typesystem_1.U64Value(number); + case typesystem_1.I64Type: + return new typesystem_1.I64Value(number); + case typesystem_1.BigUIntType: + return new typesystem_1.BigUIntValue(number); + case typesystem_1.BigIntType: + return new typesystem_1.BigIntValue(number); + default: + errorContext.unhandledType("convertNumericalType", type); + } + } + })(NativeSerializer = exports2.NativeSerializer || (exports2.NativeSerializer = {})); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js +var require_tokenTransfersDataBuilder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenTransfersDataBuilder = void 0; + var argSerializer_1 = require_argSerializer(); + var typesystem_1 = require_typesystem(); + var tokens_1 = require_tokens(); + var TokenTransfersDataBuilder = class { + constructor() { + this.tokenComputer = new tokens_1.TokenComputer(); + this.argsSerializer = new argSerializer_1.ArgSerializer(); + } + buildDataPartsForESDTTransfer(transfer) { + const args = this.argsSerializer.valuesToStrings([ + new typesystem_1.TokenIdentifierValue(transfer.token.identifier), + new typesystem_1.BigUIntValue(transfer.amount) + ]); + return ["ESDTTransfer", ...args]; + } + buildDataPartsForSingleESDTNFTTransfer(transfer, receiver) { + const token = transfer.token; + const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(token.identifier); + const args = this.argsSerializer.valuesToStrings([ + new typesystem_1.TokenIdentifierValue(identifier), + new typesystem_1.BigUIntValue(token.nonce), + new typesystem_1.BigUIntValue(transfer.amount), + new typesystem_1.AddressValue(receiver) + ]); + return ["ESDTNFTTransfer", ...args]; + } + buildDataPartsForMultiESDTNFTTransfer(receiver, transfers) { + const argsTyped = [new typesystem_1.AddressValue(receiver), new typesystem_1.U32Value(transfers.length)]; + for (const transfer of transfers) { + const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(transfer.token.identifier); + argsTyped.push(...[ + new typesystem_1.TokenIdentifierValue(identifier), + new typesystem_1.BigUIntValue(transfer.token.nonce), + new typesystem_1.BigUIntValue(transfer.amount) + ]); + } + const args = this.argsSerializer.valuesToStrings(argsTyped); + return ["MultiESDTNFTTransfer", ...args]; + } + }; + exports2.TokenTransfersDataBuilder = TokenTransfersDataBuilder; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js +var require_smartContractTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractTransactionsFactory = void 0; + var address_1 = require_address(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var smartcontracts_1 = require_smartcontracts(); + var nativeSerializer_1 = require_nativeSerializer(); + var tokens_1 = require_tokens(); + var utils_codec_1 = require_utils_codec(); + var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); + var transactionBuilder_1 = require_transactionBuilder(); + var SmartContractTransactionsFactory2 = class { + constructor(options) { + this.config = options.config; + this.abi = options.abi; + this.tokenComputer = new tokens_1.TokenComputer(); + this.dataArgsBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); + } + createTransactionForDeploy(options) { + const nativeTransferAmount = options.nativeTransferAmount ?? 0n; + const isUpgradeable = options.isUpgradeable ?? true; + const isReadable = options.isReadable ?? true; + const isPayable = options.isPayable ?? false; + const isPayableBySmartContract = options.isPayableBySmartContract ?? true; + const args = options.arguments || []; + const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); + const dataParts = [utils_codec_1.byteArrayToHex(options.bytecode), utils_codec_1.byteArrayToHex(constants_1.VM_TYPE_WASM_VM), metadata.toString()]; + const endpoint = this.abi?.constructorDefinition; + const preparedArgs = this.argsToDataParts(args, endpoint); + dataParts.push(...preparedArgs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.CONTRACT_DEPLOY_ADDRESS), + dataParts, + gasLimit: options.gasLimit, + addDataMovementGas: false, + amount: nativeTransferAmount + }).build(); + } + createTransactionForExecute(options) { + const args = options.arguments || []; + const tokenTransfer = options.tokenTransfers || []; + const nativeTransferAmount = options.nativeTransferAmount ?? 0n; + const numberOfTokens = tokenTransfer.length; + if (nativeTransferAmount && numberOfTokens) { + throw new errors_1.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)"); + } + let receiver = options.contract; + let dataParts = []; + if (numberOfTokens === 1) { + const transfer = tokenTransfer[0]; + if (this.tokenComputer.isFungible(transfer.token)) { + dataParts = this.dataArgsBuilder.buildDataPartsForESDTTransfer(transfer); + } else { + dataParts = this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); + receiver = options.sender; + } + } else if (numberOfTokens > 1) { + dataParts = this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(receiver, tokenTransfer); + receiver = options.sender; + } + dataParts.push(dataParts.length ? utils_codec_1.utf8ToHex(options.function) : options.function); + const endpoint = this.abi?.getEndpoint(options.function); + const preparedArgs = this.argsToDataParts(args, endpoint); + dataParts.push(...preparedArgs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver, + dataParts, + gasLimit: options.gasLimit, + addDataMovementGas: false, + amount: nativeTransferAmount + }).build(); + } + createTransactionForUpgrade(options) { + const nativeTransferAmount = options.nativeTransferAmount ?? 0n; + const isUpgradeable = options.isUpgradeable ?? true; + const isReadable = options.isReadable ?? true; + const isPayable = options.isPayable ?? false; + const isPayableBySmartContract = options.isPayableBySmartContract ?? true; + const args = options.arguments || []; + const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); + const dataParts = ["upgradeContract", utils_codec_1.byteArrayToHex(options.bytecode), metadata.toString()]; + const endpoint = this.getEndpointForUpgrade(); + const preparedArgs = this.argsToDataParts(args, endpoint); + dataParts.push(...preparedArgs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.contract, + dataParts, + gasLimit: options.gasLimit, + addDataMovementGas: false, + amount: nativeTransferAmount + }).build(); + } + getEndpointForUpgrade() { + if (!this.abi) { + return void 0; + } + try { + return this.abi.getEndpoint("upgrade"); + } catch (error) { + logger_1.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."); + return this.abi.constructorDefinition; + } + } + createTransactionForClaimingDeveloperRewards(options) { + const dataParts = ["ClaimDeveloperRewards"]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.contract, + dataParts, + gasLimit: this.config.gasLimitClaimDeveloperRewards, + addDataMovementGas: false + }).build(); + } + createTransactionForChangingOwnerAddress(options) { + const dataParts = ["ChangeOwnerAddress", address_1.Address.fromBech32(options.newOwner.bech32()).toHex()]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.contract, + dataParts, + gasLimit: this.config.gasLimitChangeOwnerAddress, + addDataMovementGas: false + }).build(); + } + argsToDataParts(args, endpoint) { + if (endpoint) { + const typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args, endpoint); + return new smartcontracts_1.ArgSerializer().valuesToStrings(typedArgs); + } + if (this.areArgsOfTypedValue(args)) { + return new smartcontracts_1.ArgSerializer().valuesToStrings(args); + } + throw new errors_1.Err("Can't convert args to TypedValues"); + } + areArgsOfTypedValue(args) { + for (const arg of args) { + if (!arg.belongsToTypesystem) { + return false; + } + } + return true; + } + }; + exports2.SmartContractTransactionsFactory = SmartContractTransactionsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js +var require_tokenManagementTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenManagementTransactionsFactory = void 0; + var address_1 = require_address(); + var constants_1 = require_constants(); + var logger_1 = require_logger(); + var smartcontracts_1 = require_smartcontracts(); + var transactionBuilder_1 = require_transactionBuilder(); + var TokenManagementTransactionsFactory2 = class { + constructor(options) { + this.config = options.config; + this.argSerializer = new smartcontracts_1.ArgSerializer(); + this.trueAsString = "true"; + this.falseAsString = "false"; + } + createTransactionForIssuingFungible(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.BigUIntValue(options.initialSupply), + new smartcontracts_1.BigUIntValue(options.numDecimals), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["issue", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForIssuingSemiFungible(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canTransferNFTCreateRole"), + new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["issueSemiFungible", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForIssuingNonFungible(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canTransferNFTCreateRole"), + new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["issueNonFungible", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForRegisteringMetaESDT(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const args = [ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.BigUIntValue(options.numDecimals), + new smartcontracts_1.StringValue("canFreeze"), + new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), + new smartcontracts_1.StringValue("canWipe"), + new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), + new smartcontracts_1.StringValue("canPause"), + new smartcontracts_1.StringValue(this.boolToString(options.canPause)), + new smartcontracts_1.StringValue("canTransferNFTCreateRole"), + new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), + new smartcontracts_1.StringValue("canChangeOwner"), + new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), + new smartcontracts_1.StringValue("canUpgrade"), + new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), + new smartcontracts_1.StringValue("canAddSpecialRoles"), + new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) + ]; + const dataParts = ["registerMetaESDT", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForRegisteringAndSettingRoles(options) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const dataParts = [ + "registerAndSetAllRoles", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenName), + new smartcontracts_1.StringValue(options.tokenTicker), + new smartcontracts_1.StringValue(options.tokenType), + new smartcontracts_1.BigUIntValue(options.numDecimals) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitIssue, + addDataMovementGas: true, + amount: this.config.issueCost + }).build(); + } + createTransactionForSettingBurnRoleGlobally(options) { + const dataParts = [ + "setBurnRoleGlobally", + ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitToggleBurnRoleGlobally, + addDataMovementGas: true + }).build(); + } + createTransactionForUnsettingBurnRoleGlobally(options) { + const dataParts = [ + "unsetBurnRoleGlobally", + ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitToggleBurnRoleGlobally, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingSpecialRoleOnFungibleToken(options) { + const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; + options.addRoleLocalMint ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalMint")) : 0; + options.addRoleLocalBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalBurn")) : 0; + options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; + const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingSpecialRoleOnSemiFungibleToken(options) { + const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; + options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; + options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; + options.addRoleNFTAddQuantity ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddQuantity")) : 0; + options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; + const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true + }).build(); + } + createTransactionForSettingSpecialRoleOnMetaESDT(options) { + return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(options); + } + createTransactionForSettingSpecialRoleOnNonFungibleToken(options) { + const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; + options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; + options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; + options.addRoleNFTUpdateAttributes ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTUpdateAttributes")) : 0; + options.addRoleNFTAddURI ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddURI")) : 0; + options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; + const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), + dataParts, + gasLimit: this.config.gasLimitSetSpecialRole, + addDataMovementGas: true + }).build(); + } + createTransactionForCreatingNFT(options) { + const dataParts = [ + "ESDTNFTCreate", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.initialQuantity), + new smartcontracts_1.StringValue(options.name), + new smartcontracts_1.BigUIntValue(options.royalties), + new smartcontracts_1.StringValue(options.hash), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)), + ...options.uris.map((uri) => new smartcontracts_1.StringValue(uri)) + ]) + ]; + const nftData = options.name + options.hash + options.attributes + options.uris.join(""); + const storageGasLimit = this.config.gasLimitStorePerByte + BigInt(nftData.length); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftCreate + storageGasLimit, + addDataMovementGas: true + }).build(); + } + createTransactionForPausing(options) { + const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)])]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitPausing, + addDataMovementGas: true + }).build(); + } + createTransactionForUnpausing(options) { + const dataParts = [ + "unPause", + ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitPausing, + addDataMovementGas: true + }).build(); + } + createTransactionForFreezing(options) { + const dataParts = [ + "freeze", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.AddressValue(options.user) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitFreezing, + addDataMovementGas: true + }).build(); + } + createTransactionForUnfreezing(options) { + const dataParts = [ + "UnFreeze", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.AddressValue(options.user) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitFreezing, + addDataMovementGas: true + }).build(); + } + createTransactionForWiping(options) { + const dataParts = [ + "wipe", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.AddressValue(options.user) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitWiping, + addDataMovementGas: true + }).build(); + } + createTransactionForLocalMint(options) { + const dataParts = [ + "ESDTLocalMint", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.supplyToMint) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtLocalMint, + addDataMovementGas: true + }).build(); + } + createTransactionForLocalBurning(options) { + const dataParts = [ + "ESDTLocalBurn", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.supplyToBurn) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtLocalBurn, + addDataMovementGas: true + }).build(); + } + createTransactionForUpdatingAttributes(options) { + const dataParts = [ + "ESDTNFTUpdateAttributes", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.tokenNonce), + new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftUpdateAttributes, + addDataMovementGas: true + }).build(); + } + createTransactionForAddingQuantity(options) { + const dataParts = [ + "ESDTNFTAddQuantity", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.tokenNonce), + new smartcontracts_1.BigUIntValue(options.quantityToAdd) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftAddQuantity, + addDataMovementGas: true + }).build(); + } + createTransactionForBurningQuantity(options) { + const dataParts = [ + "ESDTNFTBurn", + ...this.argSerializer.valuesToStrings([ + new smartcontracts_1.StringValue(options.tokenIdentifier), + new smartcontracts_1.BigUIntValue(options.tokenNonce), + new smartcontracts_1.BigUIntValue(options.quantityToBurn) + ]) + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitEsdtNftBurn, + addDataMovementGas: true + }).build(); + } + notifyAboutUnsettingBurnRoleGlobally() { + logger_1.Logger.info(` +========== +IMPORTANT! +========== +You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); + } + boolToString(value) { + if (value) { + return this.trueAsString; + } + return this.falseAsString; + } + }; + exports2.TokenManagementTransactionsFactory = TokenManagementTransactionsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js +var require_transactionsFactoryConfig = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionsFactoryConfig = void 0; + var constants_1 = require_constants(); + var TransactionsFactoryConfig2 = class { + constructor(options) { + this.chainID = options.chainID; + this.addressHrp = constants_1.DEFAULT_HRP; + this.minGasLimit = 50000n; + this.gasLimitPerByte = 1500n; + this.gasLimitIssue = 60000000n; + this.gasLimitToggleBurnRoleGlobally = 60000000n; + this.gasLimitEsdtLocalMint = 300000n; + this.gasLimitEsdtLocalBurn = 300000n; + this.gasLimitSetSpecialRole = 60000000n; + this.gasLimitPausing = 60000000n; + this.gasLimitFreezing = 60000000n; + this.gasLimitWiping = 60000000n; + this.gasLimitEsdtNftCreate = 3000000n; + this.gasLimitEsdtNftUpdateAttributes = 1000000n; + this.gasLimitEsdtNftAddQuantity = 1000000n; + this.gasLimitEsdtNftBurn = 1000000n; + this.gasLimitStorePerByte = 10000n; + this.issueCost = 50000000000000000n; + this.gasLimitStake = 5000000n; + this.gasLimitUnstake = 5000000n; + this.gasLimitUnbond = 5000000n; + this.gasLimitCreateDelegationContract = 50000000n; + this.gasLimitDelegationOperations = 1000000n; + this.additionalGasLimitPerValidatorNode = 6000000n; + this.additionalGasLimitForDelegationOperations = 10000000n; + this.gasLimitSaveKeyValue = 100000n; + this.gasLimitPersistPerByte = 1000n; + this.gasLimitSetGuardian = 250000n; + this.gasLimitGuardAccount = 250000n; + this.gasLimitUnguardAccount = 250000n; + this.gasLimitESDTTransfer = 200000n; + this.gasLimitESDTNFTTransfer = 200000n; + this.gasLimitMultiESDTNFTTransfer = 200000n; + this.gasLimitClaimDeveloperRewards = 6000000n; + this.gasLimitChangeOwnerAddress = 6000000n; + } + }; + exports2.TransactionsFactoryConfig = TransactionsFactoryConfig2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js +var require_transferTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransferTransactionsFactory = void 0; + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var tokens_1 = require_tokens(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); + var transactionBuilder_1 = require_transactionBuilder(); + var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; + var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; + var TransferTransactionsFactory2 = class { + /** + * Should be instantiated using `Config` and `TokenComputer`. + * Instantiating this class using GasEstimator represents the legacy version of this class. + * The legacy version contains methods like `createEGLDTransfer`, `createESDTTransfer`, `createESDTNFTTransfer` and `createMultiESDTNFTTransfer`. + * This was done in order to minimize breaking changes in client code. + */ + constructor(options) { + if (this.isGasEstimator(options)) { + this.gasEstimator = options; + } else { + this.config = options.config; + this.tokenComputer = new tokens_1.TokenComputer(); + this.tokenTransfersDataBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); + } + } + isGasEstimator(options) { + return typeof options === "object" && typeof options.forEGLDTransfer === "function" && typeof options.forESDTTransfer === "function" && typeof options.forESDTNFTTransfer === "function" && typeof options.forMultiESDTNFTTransfer === "function"; + } + isGasEstimatorDefined() { + return this.gasEstimator !== void 0; + } + ensureMembersAreDefined() { + if (this.config === void 0) { + throw new errors_1.Err("'config' is not defined"); + } + if (this.tokenTransfersDataBuilder === void 0) { + throw new errors_1.Err("`dataArgsBuilder is not defined`"); + } + if (this.tokenComputer === void 0) { + throw new errors_1.Err("`tokenComputer is not defined`"); + } + } + createTransactionForNativeTokenTransfer(options) { + this.ensureMembersAreDefined(); + const data = options.data || new Uint8Array(); + return new transaction_1.Transaction({ + sender: options.sender.bech32(), + receiver: options.receiver.bech32(), + chainID: this.config.chainID, + gasLimit: this.computeGasForMoveBalance(this.config, data), + data, + value: options.nativeAmount + }); + } + createTransactionForESDTTokenTransfer(options) { + this.ensureMembersAreDefined(); + const numberOfTransfers = options.tokenTransfers.length; + if (numberOfTransfers === 0) { + throw new errors_1.ErrBadUsage("No token transfer has been provided"); + } + if (numberOfTransfers === 1) { + return this.createSingleESDTTransferTransaction(options); + } + const dataParts = this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(options.receiver, options.tokenTransfers); + const extraGasForTransfer = this.config.gasLimitMultiESDTNFTTransfer * BigInt(numberOfTransfers) + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: extraGasForTransfer, + addDataMovementGas: true + }).build(); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForNativeTokenTransfer} instead. + */ + createEGLDTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method."); + } + const dataLength = args.data?.length() || 0; + const estimatedGasLimit = this.gasEstimator.forEGLDTransfer(dataLength); + return new transaction_1.Transaction({ + nonce: args.nonce, + value: args.value, + receiver: args.receiver, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: args.data, + chainID: args.chainID + }); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForESDTTokenTransfer} instead. + */ + createESDTTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + // The token identifier + smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), + // The transfered amount + new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()) + ]); + const data = `ESDTTransfer@${argumentsString}`; + const transactionPayload = new transactionPayload_1.TransactionPayload(data); + const dataLength = transactionPayload.length() || 0; + const estimatedGasLimit = this.gasEstimator.forESDTTransfer(dataLength); + return new transaction_1.Transaction({ + nonce: args.nonce, + receiver: args.receiver, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: transactionPayload, + chainID: args.chainID + }); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForESDTTokenTransfer} instead. + */ + createESDTNFTTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + // The token identifier + smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), + // The nonce of the token + new smartcontracts_1.U64Value(args.tokenTransfer.nonce), + // The transferred quantity + new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()), + // The destination address + new smartcontracts_1.AddressValue(args.destination) + ]); + const data = `ESDTNFTTransfer@${argumentsString}`; + const transactionPayload = new transactionPayload_1.TransactionPayload(data); + const dataLength = transactionPayload.length() || 0; + const estimatedGasLimit = this.gasEstimator.forESDTNFTTransfer(dataLength); + return new transaction_1.Transaction({ + nonce: args.nonce, + receiver: args.sender, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: transactionPayload, + chainID: args.chainID + }); + } + /** + * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. + * Use {@link createTransactionForESDTTokenTransfer} instead. + */ + createMultiESDTNFTTransfer(args) { + if (!this.isGasEstimatorDefined()) { + throw new errors_1.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); + } + const parts = [ + // The destination address + new smartcontracts_1.AddressValue(args.destination), + // Number of tokens + new smartcontracts_1.U16Value(args.tokenTransfers.length) + ]; + for (const payment of args.tokenTransfers) { + parts.push(...[ + // The token identifier + smartcontracts_1.BytesValue.fromUTF8(payment.tokenIdentifier), + // The nonce of the token + new smartcontracts_1.U64Value(payment.nonce), + // The transfered quantity + new smartcontracts_1.BigUIntValue(payment.valueOf()) + ]); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString(parts); + const data = `MultiESDTNFTTransfer@${argumentsString}`; + const transactionPayload = new transactionPayload_1.TransactionPayload(data); + const dataLength = transactionPayload.length() || 0; + const estimatedGasLimit = this.gasEstimator.forMultiESDTNFTTransfer(dataLength, args.tokenTransfers.length); + return new transaction_1.Transaction({ + nonce: args.nonce, + receiver: args.sender, + sender: args.sender, + gasPrice: args.gasPrice, + gasLimit: args.gasLimit || estimatedGasLimit, + data: transactionPayload, + chainID: args.chainID + }); + } + createSingleESDTTransferTransaction(options) { + this.ensureMembersAreDefined(); + let dataParts = []; + const transfer = options.tokenTransfers[0]; + let extraGasForTransfer = 0n; + let receiver = options.receiver; + if (this.tokenComputer.isFungible(transfer.token)) { + dataParts = this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(transfer); + extraGasForTransfer = this.config.gasLimitESDTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_TRANSFER); + } else { + dataParts = this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); + extraGasForTransfer = this.config.gasLimitESDTNFTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); + receiver = options.sender; + } + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver, + dataParts, + gasLimit: extraGasForTransfer, + addDataMovementGas: true + }).build(); + } + computeGasForMoveBalance(config, data) { + return config.minGasLimit + config.gasLimitPerByte * BigInt(data.length); + } + }; + exports2.TransferTransactionsFactory = TransferTransactionsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js +var require_accountTransactionsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AccountTransactionsFactory = void 0; + var address_1 = require_address(); + var transactionBuilder_1 = require_transactionBuilder(); + var AccountTransactionsFactory = class { + constructor(options) { + this.config = options.config; + } + createTransactionForSavingKeyValue(options) { + const functionName = "SaveKeyValue"; + const keyValueParts = this.computeDataPartsForSavingKeyValue(options.keyValuePairs); + const dataParts = [functionName, ...keyValueParts]; + const extraGas = this.computeExtraGasForSavingKeyValue(options.keyValuePairs); + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: extraGas, + addDataMovementGas: true + }).build(); + } + computeExtraGasForSavingKeyValue(keyValuePairs) { + let extraGas = 0n; + keyValuePairs.forEach((value, key) => { + extraGas += this.config.gasLimitPersistPerByte * BigInt(key.length + value.length) + this.config.gasLimitStorePerByte * BigInt(value.length); + }); + return extraGas + this.config.gasLimitSaveKeyValue; + } + computeDataPartsForSavingKeyValue(keyValuePairs) { + const dataParts = []; + keyValuePairs.forEach((value, key) => { + dataParts.push(...[import_buffer.Buffer.from(key).toString("hex"), import_buffer.Buffer.from(value).toString("hex")]); + }); + return dataParts; + } + createTransactionForSettingGuardian(options) { + const dataParts = [ + "SetGuardian", + address_1.Address.fromBech32(options.guardianAddress.bech32()).toHex(), + import_buffer.Buffer.from(options.serviceID).toString("hex") + ]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitSetGuardian, + addDataMovementGas: true + }).build(); + } + createTransactionForGuardingAccount(options) { + const dataParts = ["GuardAccount"]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitGuardAccount, + addDataMovementGas: true + }).build(); + } + createTransactionForUnguardingAccount(options) { + const dataParts = ["UnGuardAccount"]; + return new transactionBuilder_1.TransactionBuilder({ + config: this.config, + sender: options.sender, + receiver: options.sender, + dataParts, + gasLimit: this.config.gasLimitUnguardAccount, + addDataMovementGas: true + }).build(); + } + }; + exports2.AccountTransactionsFactory = AccountTransactionsFactory; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js +var require_transactionsFactories = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_delegationTransactionsFactory(), exports2); + __exportStar2(require_relayedTransactionsFactory(), exports2); + __exportStar2(require_smartContractTransactionsFactory(), exports2); + __exportStar2(require_tokenManagementTransactionsFactory(), exports2); + __exportStar2(require_transactionsFactoryConfig(), exports2); + __exportStar2(require_transferTransactionsFactory(), exports2); + __exportStar2(require_accountTransactionsFactory(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js +var require_interactionChecker = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.InteractionChecker = void 0; + var errors = __importStar2(require_errors()); + var bignumber_js_1 = __importDefault2(require_bignumber()); + var InteractionChecker = class { + checkInteraction(interaction, definition) { + this.checkPayable(interaction, definition); + this.checkArguments(interaction, definition); + } + checkPayable(interaction, definition) { + let hasValue = !new bignumber_js_1.default(interaction.getValue().toString()).isZero(); + let isPayableInEGLD = definition.modifiers.isPayableInEGLD(); + if (hasValue && !isPayableInEGLD) { + throw new errors.ErrContractInteraction("cannot send EGLD value to non-payable"); + } + } + checkArguments(interaction, definition) { + let formalArguments = definition.input; + let actualArguments = interaction.getArguments(); + let numFormalArguments = formalArguments.length; + let numActualArguments = actualArguments.length; + if (numFormalArguments != numActualArguments) { + throw new errors.ErrContractInteraction(`bad arguments, expected: ${numFormalArguments}, got: ${numActualArguments}`); + } + for (let i2 = 0; i2 < numFormalArguments; i2++) { + let expectedType = formalArguments[i2].type; + let argument = actualArguments[i2]; + let actualType = argument.getType(); + let ok = expectedType.isAssignableFrom(actualType); + if (!ok) { + throw new errors.ErrContractInteraction(`type mismatch at index ${i2}, expected: ${expectedType}, got: ${actualType}`); + } + } + } + }; + exports2.InteractionChecker = InteractionChecker; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/query.js +var require_query = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/query.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Query = void 0; + var address_1 = require_address(); + var argSerializer_1 = require_argSerializer(); + var Query2 = class { + constructor(obj) { + this.caller = obj.caller || address_1.Address.empty(); + this.address = obj.address; + this.func = obj.func; + this.args = obj.args || []; + this.value = obj.value || 0; + } + getEncodedArguments() { + return new argSerializer_1.ArgSerializer().valuesToStrings(this.args); + } + }; + exports2.Query = Query2; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js +var require_interaction = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Interaction = void 0; + var address_1 = require_address(); + var compatibility_1 = require_compatibility(); + var constants_1 = require_constants(); + var tokens_1 = require_tokens(); + var transactionsFactories_1 = require_transactionsFactories(); + var interactionChecker_1 = require_interactionChecker(); + var query_1 = require_query(); + var Interaction = class { + constructor(contract, func, args) { + this.nonce = 0; + this.value = "0"; + this.gasLimit = 0; + this.gasPrice = void 0; + this.chainID = ""; + this.querent = address_1.Address.empty(); + this.sender = address_1.Address.empty(); + this.version = constants_1.TRANSACTION_VERSION_DEFAULT; + this.contract = contract; + this.function = func; + this.args = args; + this.tokenTransfers = []; + } + getContractAddress() { + return this.contract.getAddress(); + } + getFunction() { + return this.function; + } + getEndpoint() { + return this.contract.getEndpoint(this.function); + } + getArguments() { + return this.args; + } + getValue() { + return this.value; + } + getTokenTransfers() { + return this.tokenTransfers; + } + getGasLimit() { + return this.gasLimit; + } + getExplicitReceiver() { + return this.explicitReceiver; + } + buildTransaction() { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(this.sender, "'sender' of interaction", "use interaction.withSender()"); + const factoryConfig = new transactionsFactories_1.TransactionsFactoryConfig({ chainID: this.chainID.valueOf() }); + const factory = new transactionsFactories_1.SmartContractTransactionsFactory({ + config: factoryConfig + }); + const transaction = factory.createTransactionForExecute({ + sender: this.sender, + contract: this.contract.getAddress(), + function: this.function.valueOf(), + gasLimit: BigInt(this.gasLimit.valueOf()), + arguments: this.args, + nativeTransferAmount: BigInt(this.value.toString()), + tokenTransfers: this.tokenTransfers + }); + transaction.chainID = this.chainID.valueOf(); + transaction.nonce = BigInt(this.nonce.valueOf()); + transaction.version = this.version; + if (this.gasPrice) { + transaction.gasPrice = BigInt(this.gasPrice.valueOf()); + } + return transaction; + } + buildQuery() { + return new query_1.Query({ + address: this.contract.getAddress(), + func: this.function, + args: this.args, + // Value will be set using "withValue()". + value: this.value, + caller: this.querent + }); + } + withValue(value) { + this.value = value; + return this; + } + withSingleESDTTransfer(transfer) { + this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); + return this; + } + withSingleESDTNFTTransfer(transfer) { + this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); + return this; + } + withMultiESDTNFTTransfer(transfers) { + this.tokenTransfers = transfers.map((transfer) => new tokens_1.TokenTransfer(transfer)); + return this; + } + withGasLimit(gasLimit) { + this.gasLimit = gasLimit; + return this; + } + withGasPrice(gasPrice) { + this.gasPrice = gasPrice; + return this; + } + withNonce(nonce) { + this.nonce = nonce; + return this; + } + useThenIncrementNonceOf(account) { + return this.withNonce(account.getNonceThenIncrement()); + } + withChainID(chainID) { + this.chainID = chainID; + return this; + } + withSender(sender) { + this.sender = sender; + return this; + } + withVersion(version2) { + this.version = version2; + return this; + } + /** + * Sets the "caller" field on contract queries. + */ + withQuerent(querent) { + this.querent = querent; + return this; + } + withExplicitReceiver(receiver) { + this.explicitReceiver = receiver; + return this; + } + /** + * To perform custom checking, extend {@link Interaction} and override this method. + */ + check() { + new interactionChecker_1.InteractionChecker().checkInteraction(this, this.getEndpoint()); + return this; + } + }; + exports2.Interaction = Interaction; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js +var require_interface = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js +var require_dist = __commonJS({ + "node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.bech32m = exports2.bech32 = void 0; + var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + var ALPHABET_MAP = {}; + for (let z3 = 0; z3 < ALPHABET.length; z3++) { + const x3 = ALPHABET.charAt(z3); + ALPHABET_MAP[x3] = z3; + } + function polymodStep(pre) { + const b4 = pre >> 25; + return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; + } + function prefixChk(prefix) { + let chk = 1; + for (let i2 = 0; i2 < prefix.length; ++i2) { + const c4 = prefix.charCodeAt(i2); + if (c4 < 33 || c4 > 126) + return "Invalid prefix (" + prefix + ")"; + chk = polymodStep(chk) ^ c4 >> 5; + } + chk = polymodStep(chk); + for (let i2 = 0; i2 < prefix.length; ++i2) { + const v2 = prefix.charCodeAt(i2); + chk = polymodStep(chk) ^ v2 & 31; + } + return chk; + } + function convert(data, inBits, outBits, pad) { + let value = 0; + let bits = 0; + const maxV = (1 << outBits) - 1; + const result = []; + for (let i2 = 0; i2 < data.length; ++i2) { + value = value << inBits | data[i2]; + bits += inBits; + while (bits >= outBits) { + bits -= outBits; + result.push(value >> bits & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push(value << outBits - bits & maxV); + } + } else { + if (bits >= inBits) + return "Excess padding"; + if (value << outBits - bits & maxV) + return "Non-zero padding"; + } + return result; + } + function toWords(bytes) { + return convert(bytes, 8, 5, true); + } + function fromWordsUnsafe(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + } + function fromWords(words) { + const res = convert(words, 5, 8, false); + if (Array.isArray(res)) + return res; + throw new Error(res); + } + function getLibraryFromEncoding(encoding) { + let ENCODING_CONST; + if (encoding === "bech32") { + ENCODING_CONST = 1; + } else { + ENCODING_CONST = 734539939; + } + function encode5(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) + throw new TypeError("Exceeds length limit"); + prefix = prefix.toLowerCase(); + let chk = prefixChk(prefix); + if (typeof chk === "string") + throw new Error(chk); + let result = prefix + "1"; + for (let i2 = 0; i2 < words.length; ++i2) { + const x3 = words[i2]; + if (x3 >> 5 !== 0) + throw new Error("Non 5-bit word"); + chk = polymodStep(chk) ^ x3; + result += ALPHABET.charAt(x3); + } + for (let i2 = 0; i2 < 6; ++i2) { + chk = polymodStep(chk); + } + chk ^= ENCODING_CONST; + for (let i2 = 0; i2 < 6; ++i2) { + const v2 = chk >> (5 - i2) * 5 & 31; + result += ALPHABET.charAt(v2); + } + return result; + } + function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) + return str + " too short"; + if (str.length > LIMIT) + return "Exceeds length limit"; + const lowered = str.toLowerCase(); + const uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) + return "Mixed-case string " + str; + str = lowered; + const split = str.lastIndexOf("1"); + if (split === -1) + return "No separator character for " + str; + if (split === 0) + return "Missing prefix for " + str; + const prefix = str.slice(0, split); + const wordChars = str.slice(split + 1); + if (wordChars.length < 6) + return "Data too short"; + let chk = prefixChk(prefix); + if (typeof chk === "string") + return chk; + const words = []; + for (let i2 = 0; i2 < wordChars.length; ++i2) { + const c4 = wordChars.charAt(i2); + const v2 = ALPHABET_MAP[c4]; + if (v2 === void 0) + return "Unknown character " + c4; + chk = polymodStep(chk) ^ v2; + if (i2 + 6 >= wordChars.length) + continue; + words.push(v2); + } + if (chk !== ENCODING_CONST) + return "Invalid checksum for " + str; + return { prefix, words }; + } + function decodeUnsafe(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === "object") + return res; + } + function decode6(str, LIMIT) { + const res = __decode(str, LIMIT); + if (typeof res === "object") + return res; + throw new Error(res); + } + return { + decodeUnsafe, + decode: decode6, + encode: encode5, + toWords, + fromWordsUnsafe, + fromWords + }; + } + exports2.bech32 = getLibraryFromEncoding("bech32"); + exports2.bech32m = getLibraryFromEncoding("bech32m"); + } +}); + +// node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js +var require_transaction_decoder = __commonJS({ + "node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenTransferProperties = exports2.TransactionMetadataTransfer = exports2.TransactionMetadata = exports2.TransactionToDecode = exports2.TransactionDecoder = void 0; + var bech32_1 = require_dist(); + var TransactionDecoder = class { + getTransactionMetadata(transaction) { + const metadata = this.getNormalTransactionMetadata(transaction); + const esdtMetadata = this.getEsdtTransactionMetadata(metadata); + if (esdtMetadata) { + return esdtMetadata; + } + const nftMetadata = this.getNftTransferMetadata(metadata); + if (nftMetadata) { + return nftMetadata; + } + const multiMetadata = this.getMultiTransferMetadata(metadata); + if (multiMetadata) { + return multiMetadata; + } + return metadata; + } + getNormalTransactionMetadata(transaction) { + const metadata = new TransactionMetadata(); + metadata.sender = transaction.sender; + metadata.receiver = transaction.receiver; + metadata.value = BigInt(transaction.value); + if (transaction.data) { + const decodedData = this.base64Decode(transaction.data); + const dataComponents = decodedData.split("@"); + const args = dataComponents.slice(1); + if (args.every((x3) => this.isSmartContractArgument(x3))) { + metadata.functionName = dataComponents[0]; + metadata.functionArgs = args; + } + if (metadata.functionName === "relayedTx" && metadata.functionArgs && metadata.functionArgs.length === 1) { + try { + const relayedTransaction = JSON.parse(this.hexToString(metadata.functionArgs[0])); + relayedTransaction.value = relayedTransaction.value.toString(); + relayedTransaction.sender = this.bech32Encode(this.base64ToHex(relayedTransaction.sender)); + relayedTransaction.receiver = this.bech32Encode(this.base64ToHex(relayedTransaction.receiver)); + return this.getNormalTransactionMetadata(relayedTransaction); + } catch (error) { + } + } + if (metadata.functionName === "relayedTxV2" && metadata.functionArgs && metadata.functionArgs.length === 4) { + try { + const relayedTransaction = new TransactionToDecode(); + relayedTransaction.sender = transaction.receiver; + relayedTransaction.receiver = this.bech32Encode(metadata.functionArgs[0]); + relayedTransaction.data = this.base64Encode(this.hexToString(metadata.functionArgs[2])); + relayedTransaction.value = "0"; + return this.getNormalTransactionMetadata(relayedTransaction); + } catch (error) { + } + } + } + return metadata; + } + getMultiTransferMetadata(metadata) { + if (metadata.sender !== metadata.receiver) { + return void 0; + } + if (metadata.functionName !== "MultiESDTNFTTransfer") { + return void 0; + } + const args = metadata.functionArgs; + if (!args) { + return void 0; + } + if (args.length < 3) { + return void 0; + } + if (!this.isAddressValid(args[0])) { + return void 0; + } + const receiver = this.bech32Encode(args[0]); + const transferCount = this.hexToNumber(args[1]); + const result = new TransactionMetadata(); + if (!result.transfers) { + result.transfers = []; + } + let index = 2; + for (let i2 = 0; i2 < transferCount; i2++) { + const identifier = this.hexToString(args[index++]); + const nonce = args[index++]; + const value = this.hexToBigInt(args[index++]); + if (nonce) { + result.transfers.push({ + value, + properties: { + collection: identifier, + identifier: `${identifier}-${nonce}` + } + }); + } else { + result.transfers.push({ + value, + properties: { + token: identifier + } + }); + } + } + result.sender = metadata.sender; + result.receiver = receiver; + if (args.length > index) { + result.functionName = this.hexToString(args[index++]); + result.functionArgs = args.slice(index++); + } + return result; + } + getNftTransferMetadata(metadata) { + if (metadata.sender !== metadata.receiver) { + return void 0; + } + if (metadata.functionName !== "ESDTNFTTransfer") { + return void 0; + } + const args = metadata.functionArgs; + if (!args) { + return void 0; + } + if (args.length < 4) { + return void 0; + } + if (!this.isAddressValid(args[3])) { + return void 0; + } + const collectionIdentifier = this.hexToString(args[0]); + const nonce = args[1]; + const value = this.hexToBigInt(args[2]); + const receiver = this.bech32Encode(args[3]); + const result = new TransactionMetadata(); + result.sender = metadata.sender; + result.receiver = receiver; + result.value = value; + if (args.length > 4) { + result.functionName = this.hexToString(args[4]); + result.functionArgs = args.slice(5); + } + result.transfers = [{ + value, + properties: { + collection: collectionIdentifier, + identifier: `${collectionIdentifier}-${nonce}` + } + }]; + return result; + } + base64Encode(str) { + return import_buffer.Buffer.from(str).toString("base64"); + } + base64Decode(str) { + return import_buffer.Buffer.from(str, "base64").toString("binary"); + } + hexToNumber(hex) { + return parseInt(hex, 16); + } + getEsdtTransactionMetadata(metadata) { + if (metadata.functionName !== "ESDTTransfer") { + return void 0; + } + const args = metadata.functionArgs; + if (!args) { + return void 0; + } + if (args.length < 2) { + return void 0; + } + const tokenIdentifier = this.hexToString(args[0]); + const value = this.hexToBigInt(args[1]); + const result = new TransactionMetadata(); + result.sender = metadata.sender; + result.receiver = metadata.receiver; + if (args.length > 2) { + result.functionName = this.hexToString(args[2]); + result.functionArgs = args.slice(3); + } + result.transfers = [{ + value, + properties: { + identifier: tokenIdentifier + } + }]; + result.value = value; + return result; + } + bech32Encode(address) { + const pubKey = import_buffer.Buffer.from(address, "hex"); + const words = bech32_1.bech32.toWords(pubKey); + return bech32_1.bech32.encode("erd", words); + } + isAddressValid(address) { + return import_buffer.Buffer.from(address, "hex").length == 32; + } + isSmartContractArgument(arg) { + if (!this.isHex(arg)) { + return false; + } + if (arg.length % 2 !== 0) { + return false; + } + return true; + } + isHex(value) { + return new RegExp(/[^a-f0-9]/gi).test(value) === false; + } + base64ToHex(str) { + return import_buffer.Buffer.from(str, "base64").toString("hex"); + } + hexToString(hex) { + return import_buffer.Buffer.from(hex, "hex").toString("ascii"); + } + hexToBigInt(hex) { + if (!hex) { + return BigInt(0); + } + return BigInt("0x" + hex); + } + }; + exports2.TransactionDecoder = TransactionDecoder; + var TransactionToDecode = class { + constructor() { + this.sender = ""; + this.receiver = ""; + this.data = ""; + this.value = "0"; + } + }; + exports2.TransactionToDecode = TransactionToDecode; + var TransactionMetadata = class { + constructor() { + this.sender = ""; + this.receiver = ""; + this.value = BigInt(0); + } + }; + exports2.TransactionMetadata = TransactionMetadata; + var TransactionMetadataTransfer = class { + constructor() { + this.value = BigInt(0); + } + }; + exports2.TransactionMetadataTransfer = TransactionMetadataTransfer; + var TokenTransferProperties = class { + }; + exports2.TokenTransferProperties = TokenTransferProperties; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js +var require_returnCode = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ReturnCode = void 0; + var ReturnCode = class _ReturnCode { + constructor(text) { + this.text = text; + } + static fromBuffer(buffer) { + let text = buffer.toString(); + return new _ReturnCode(text); + } + toString() { + return this.text; + } + valueOf() { + return this.text; + } + equals(other) { + if (!other) { + return false; + } + return this.text == other.text; + } + isSuccess() { + return this.equals(_ReturnCode.Ok) || this.equals(_ReturnCode.None); + } + }; + exports2.ReturnCode = ReturnCode; + ReturnCode.None = new ReturnCode(""); + ReturnCode.Ok = new ReturnCode("ok"); + ReturnCode.FunctionNotFound = new ReturnCode("function not found"); + ReturnCode.FunctionWrongSignature = new ReturnCode("wrong signature for function"); + ReturnCode.ContractNotFound = new ReturnCode("contract not found"); + ReturnCode.UserError = new ReturnCode("user error"); + ReturnCode.OutOfGas = new ReturnCode("out of gas"); + ReturnCode.AccountCollision = new ReturnCode("account collision"); + ReturnCode.OutOfFunds = new ReturnCode("out of funds"); + ReturnCode.CallStackOverFlow = new ReturnCode("call stack overflow"); + ReturnCode.ContractInvalid = new ReturnCode("contract invalid"); + ReturnCode.ExecutionFailed = new ReturnCode("execution failed"); + ReturnCode.Unknown = new ReturnCode("unknown"); + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js +var require_resultsParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ResultsParser = void 0; + var transaction_decoder_1 = require_transaction_decoder(); + var address_1 = require_address(); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var argSerializer_1 = require_argSerializer(); + var returnCode_1 = require_returnCode(); + var WellKnownEvents; + (function(WellKnownEvents2) { + WellKnownEvents2["OnTransactionCompleted"] = "completedTxEvent"; + WellKnownEvents2["OnSignalError"] = "signalError"; + WellKnownEvents2["OnWriteLog"] = "writeLog"; + })(WellKnownEvents || (WellKnownEvents = {})); + var WellKnownTopics; + (function(WellKnownTopics2) { + WellKnownTopics2["TooMuchGas"] = "@too much gas provided for processing"; + })(WellKnownTopics || (WellKnownTopics = {})); + var defaultResultsParserOptions = { + argsSerializer: new argSerializer_1.ArgSerializer() + }; + var ResultsParser = class { + constructor(options) { + options = { ...defaultResultsParserOptions, ...options }; + this.argsSerializer = options.argsSerializer; + } + /** + * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. + */ + parseQueryResponse(queryResponse, endpoint) { + let parts = queryResponse.getReturnDataParts(); + let values = this.argsSerializer.buffersToValues(parts, endpoint.output); + let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); + return { + returnCode, + returnMessage: queryResponse.returnMessage, + values, + firstValue: values[0], + secondValue: values[1], + thirdValue: values[2], + lastValue: values[values.length - 1] + }; + } + /** + * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. + */ + parseUntypedQueryResponse(queryResponse) { + let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); + return { + returnCode, + returnMessage: queryResponse.returnMessage, + values: queryResponse.getReturnDataParts() + }; + } + /** + * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. + */ + parseOutcome(transaction, endpoint) { + const untypedBundle = this.parseUntypedOutcome(transaction); + const typedBundle = this.parseOutcomeFromUntypedBundle(untypedBundle, endpoint); + return typedBundle; + } + /** + * @internal + * For internal use only. + */ + parseOutcomeFromUntypedBundle(bundle, endpoint) { + const values = this.argsSerializer.buffersToValues(bundle.values, endpoint.output); + return { + returnCode: bundle.returnCode, + returnMessage: bundle.returnMessage, + values, + firstValue: values[0], + secondValue: values[1], + thirdValue: values[2], + lastValue: values[values.length - 1] + }; + } + /** + * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. + */ + parseUntypedOutcome(transaction) { + let bundle; + let transactionMetadata = this.parseTransactionMetadata(transaction); + bundle = this.createBundleOnSimpleMoveBalance(transaction); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on simple move balance"); + return bundle; + } + bundle = this.createBundleOnInvalidTransaction(transaction); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on invalid transaction"); + return bundle; + } + bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.contractResults); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on easily found result with return data"); + return bundle; + } + bundle = this.createBundleOnSignalError(transaction.logs); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on signal error"); + return bundle; + } + bundle = this.createBundleOnTooMuchGasWarning(transaction.logs); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"); + return bundle; + } + bundle = this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(transaction.logs, transaction.sender); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"); + return bundle; + } + bundle = this.createBundleWithCustomHeuristics(transaction, transactionMetadata); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): with custom heuristics"); + return bundle; + } + bundle = this.createBundleWithFallbackHeuristics(transaction, transactionMetadata); + if (bundle) { + logger_1.Logger.trace("parseUntypedOutcome(): with fallback heuristics"); + return bundle; + } + throw new errors_1.ErrCannotParseContractResults(`transaction ${transaction.hash.toString()}`); + } + parseTransactionMetadata(transaction) { + return new transaction_decoder_1.TransactionDecoder().getTransactionMetadata({ + sender: transaction.sender.bech32(), + receiver: transaction.receiver.bech32(), + data: transaction.data.toString("base64"), + value: transaction.value.toString() + }); + } + createBundleOnSimpleMoveBalance(transaction) { + let noResults = transaction.contractResults.items.length == 0; + let noLogs = transaction.logs.events.length == 0; + if (noResults && noLogs) { + return { + returnCode: returnCode_1.ReturnCode.None, + returnMessage: returnCode_1.ReturnCode.None.toString(), + values: [] + }; + } + return null; + } + createBundleOnInvalidTransaction(transaction) { + if (transaction.status.isInvalid()) { + if (transaction.receipt.data) { + return { + returnCode: returnCode_1.ReturnCode.OutOfFunds, + returnMessage: transaction.receipt.data, + values: [] + }; + } + } + return null; + } + createBundleOnEasilyFoundResultWithReturnData(results) { + let resultItemWithReturnData = results.items.find((item) => item.nonce.valueOf() != 0 && item.data.startsWith("@")); + if (!resultItemWithReturnData) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data); + let returnMessage = resultItemWithReturnData.returnMessage || returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + createBundleOnSignalError(logs) { + let eventSignalError = logs.findSingleOrNoneEvent(WellKnownEvents.OnSignalError); + if (!eventSignalError) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventSignalError.data); + let lastTopic = eventSignalError.getLastTopic(); + let returnMessage = lastTopic?.toString() || returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + createBundleOnTooMuchGasWarning(logs) { + let eventTooMuchGas = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.toString().startsWith(WellKnownTopics.TooMuchGas)) != void 0); + if (!eventTooMuchGas) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data); + let lastTopic = eventTooMuchGas.getLastTopic(); + let returnMessage = lastTopic?.toString() || returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + createBundleOnWriteLogWhereFirstTopicEqualsAddress(logs, address) { + let hexAddress = new address_1.Address(address.bech32()).hex(); + let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.hex() == hexAddress) != void 0); + if (!eventWriteLogWhereTopicIsSender) { + return null; + } + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventWriteLogWhereTopicIsSender.data); + let returnMessage = returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + /** + * Override this method (in a subclass of {@link ResultsParser}) if the basic heuristics of the parser are not sufficient. + */ + createBundleWithCustomHeuristics(_transaction, _transactionMetadata) { + return null; + } + createBundleWithFallbackHeuristics(transaction, transactionMetadata) { + let contractAddress = new address_1.Address(transactionMetadata.receiver); + for (const resultItem of transaction.contractResults.items) { + let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { + let addressIsSender = event.address.bech32() == transaction.sender.bech32(); + let firstTopicIsContract = event.topics[0]?.hex() == contractAddress.hex(); + return addressIsSender && firstTopicIsContract; + }); + if (writeLogWithReturnData) { + let { returnCode, returnDataParts } = this.sliceDataFieldInParts(writeLogWithReturnData.data); + let returnMessage = returnCode.toString(); + return { + returnCode, + returnMessage, + values: returnDataParts + }; + } + } + return null; + } + sliceDataFieldInParts(data) { + let startingIndex = 1; + if (data.startsWith("ESDTTransfer")) { + startingIndex = 3; + } else { + } + let parts = this.argsSerializer.stringToBuffers(data); + let returnCodePart = parts[startingIndex] || import_buffer.Buffer.from([]); + let returnDataParts = parts.slice(startingIndex + 1); + if (returnCodePart.length == 0) { + throw new errors_1.ErrCannotParseContractResults("no return code"); + } + let returnCode = returnCode_1.ReturnCode.fromBuffer(returnCodePart); + return { returnCode, returnDataParts }; + } + /** + * Legacy method, use "TransactionEventsParser.parseEvent()" instead. + */ + parseEvent(transactionEvent, eventDefinition) { + const topics = transactionEvent.topics.map((topic) => import_buffer.Buffer.from(topic.valueOf())).slice(1); + const legacyData = transactionEvent.dataPayload?.valueOf() || import_buffer.Buffer.from([]); + const dataItems = transactionEvent.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; + if (dataItems.length === 0) { + if (legacyData.length) { + dataItems.push(import_buffer.Buffer.from(legacyData)); + } + } + return this.doParseEvent({ topics, dataItems, eventDefinition }); + } + /** + * @internal + * For internal use only. + * + * Once the legacy "ResultParser" is deprecated & removed, this logic will be absorbed into "TransactionEventsParser". + */ + doParseEvent(options) { + const result = {}; + const indexedInputs = options.eventDefinition.inputs.filter((input) => input.indexed); + const decodedTopics = this.argsSerializer.buffersToValues(options.topics, indexedInputs); + for (let i2 = 0; i2 < indexedInputs.length; i2++) { + result[indexedInputs[i2].name] = decodedTopics[i2].valueOf(); + } + const nonIndexedInputs = options.eventDefinition.inputs.filter((input) => !input.indexed); + const decodedDataParts = this.argsSerializer.buffersToValues(options.dataItems, nonIndexedInputs); + for (let i2 = 0; i2 < nonIndexedInputs.length; i2++) { + result[nonIndexedInputs[i2].name] = decodedDataParts[i2].valueOf(); + } + return result; + } + }; + exports2.ResultsParser = ResultsParser; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js +var require_smartContract = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContract = void 0; + var address_1 = require_address(); + var compatibility_1 = require_compatibility(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var smartContractTransactionsFactory_1 = require_smartContractTransactionsFactory(); + var transactionsFactoryConfig_1 = require_transactionsFactoryConfig(); + var utils_1 = require_utils2(); + var codeMetadata_1 = require_codeMetadata2(); + var function_1 = require_function(); + var interaction_1 = require_interaction(); + var nativeSerializer_1 = require_nativeSerializer(); + var query_1 = require_query(); + var SmartContract = class { + /** + * Create a SmartContract object by providing its address on the Network. + */ + constructor(options = {}) { + this.address = address_1.Address.empty(); + this.methodsExplicit = {}; + this.methods = {}; + this.address = options.address || address_1.Address.empty(); + this.abi = options.abi; + if (this.abi) { + this.setupMethods(); + } + } + setupMethods() { + let contract = this; + let abi = this.getAbi(); + for (const definition of abi.getEndpoints()) { + let functionName = definition.name; + this.methodsExplicit[functionName] = function(args) { + let func = new function_1.ContractFunction(functionName); + let interaction = new interaction_1.Interaction(contract, func, args || []); + return interaction; + }; + this.methods[functionName] = function(args) { + let func = new function_1.ContractFunction(functionName); + let typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args || [], definition); + let interaction = new interaction_1.Interaction(contract, func, typedArgs || []); + return interaction; + }; + } + } + /** + * Sets the address, as on Network. + */ + setAddress(address) { + this.address = address; + } + /** + * Gets the address, as on Network. + */ + getAddress() { + return this.address; + } + getAbi() { + utils_1.guardValueIsSet("abi", this.abi); + return this.abi; + } + getEndpoint(name2) { + return this.getAbi().getEndpoint(name2); + } + /** + * Creates a {@link Transaction} for deploying the Smart Contract to the Network. + */ + deploy({ deployer, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(deployer, "'deployer' of SmartContract.deploy()", "pass the actual address to deploy()"); + const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); + const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ + config, + abi: this.abi + }); + const bytecode = import_buffer.Buffer.from(code2.toString(), "hex"); + const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); + const transaction = factory.createTransactionForDeploy({ + sender: deployer, + bytecode, + gasLimit: BigInt(gasLimit.valueOf()), + arguments: initArguments, + isUpgradeable: metadataAsJson.upgradeable, + isReadable: metadataAsJson.readable, + isPayable: metadataAsJson.payable, + isPayableBySmartContract: metadataAsJson.payableBySc + }); + transaction.setChainID(chainID); + transaction.setValue(value ?? 0); + transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); + return transaction; + } + getMetadataPropertiesAsObject(codeMetadata) { + let metadata; + if (codeMetadata) { + metadata = codeMetadata_1.CodeMetadata.fromBytes(import_buffer.Buffer.from(codeMetadata.toString(), "hex")); + } else { + metadata = new codeMetadata_1.CodeMetadata(); + } + const metadataAsJson = metadata.toJSON(); + return metadataAsJson; + } + /** + * Creates a {@link Transaction} for upgrading the Smart Contract on the Network. + */ + upgrade({ caller, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.upgrade()", "pass the actual address to upgrade()"); + this.ensureHasAddress(); + const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); + const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ + config, + abi: this.abi + }); + const bytecode = Uint8Array.from(import_buffer.Buffer.from(code2.toString(), "hex")); + const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); + const transaction = factory.createTransactionForUpgrade({ + sender: caller, + contract: this.getAddress(), + bytecode, + gasLimit: BigInt(gasLimit.valueOf()), + arguments: initArguments, + isUpgradeable: metadataAsJson.upgradeable, + isReadable: metadataAsJson.readable, + isPayable: metadataAsJson.payable, + isPayableBySmartContract: metadataAsJson.payableBySc + }); + transaction.setChainID(chainID); + transaction.setValue(value ?? 0); + transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); + return transaction; + } + /** + * Creates a {@link Transaction} for calling (a function of) the Smart Contract. + */ + call({ func, args, value, gasLimit, receiver, gasPrice, chainID, caller }) { + compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.call()", "pass the actual address to call()"); + this.ensureHasAddress(); + const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); + const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ + config, + abi: this.abi + }); + args = args || []; + value = value || 0; + const transaction = factory.createTransactionForExecute({ + sender: caller, + contract: receiver ? receiver : this.getAddress(), + function: func.toString(), + gasLimit: BigInt(gasLimit.valueOf()), + arguments: args + }); + transaction.setChainID(chainID); + transaction.setValue(value); + transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); + return transaction; + } + createQuery({ func, args, value, caller }) { + this.ensureHasAddress(); + return new query_1.Query({ + address: this.getAddress(), + func, + args, + value, + caller + }); + } + ensureHasAddress() { + if (!this.getAddress().bech32()) { + throw new errors_1.ErrContractHasNoAddress(); + } + } + /** + * Computes the address of a Smart Contract. + * The address is computed deterministically, from the address of the owner and the nonce of the deployment transaction. + * + * @param owner The owner of the Smart Contract + * @param nonce The owner nonce used for the deployment transaction + */ + static computeAddress(owner, nonce) { + const deployer = address_1.Address.fromBech32(owner.bech32()); + const addressComputer = new address_1.AddressComputer(); + return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); + } + }; + exports2.SmartContract = SmartContract; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js +var require_transactionPayloadBuilders = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractCallPayloadBuilder = exports2.ContractUpgradePayloadBuilder = exports2.ContractDeployPayloadBuilder = void 0; + var constants_1 = require_constants(); + var transactionPayload_1 = require_transactionPayload(); + var utils_1 = require_utils2(); + var argSerializer_1 = require_argSerializer(); + var ContractDeployPayloadBuilder = class { + constructor() { + this.code = null; + this.codeMetadata = ""; + this.arguments = []; + } + /** + * Sets the code of the Smart Contract. + */ + setCode(code2) { + this.code = code2; + return this; + } + /** + * Sets the code metadata of the Smart Contract. + */ + setCodeMetadata(codeMetadata) { + this.codeMetadata = codeMetadata; + return this; + } + /** + * Adds constructor (`init`) arguments. + */ + addInitArg(arg) { + this.arguments.push(arg); + return this; + } + /** + * Sets constructor (`init`) arguments. + */ + setInitArgs(args) { + this.arguments = args; + return this; + } + /** + * Builds the {@link TransactionPayload}. + */ + build() { + utils_1.guardValueIsSet("code", this.code); + let code2 = this.code.toString(); + let codeMetadata = this.codeMetadata.toString(); + let data = `${code2}@${constants_1.WasmVirtualMachine}@${codeMetadata}`; + data = appendArgumentsToString(data, this.arguments); + return new transactionPayload_1.TransactionPayload(data); + } + }; + exports2.ContractDeployPayloadBuilder = ContractDeployPayloadBuilder; + var ContractUpgradePayloadBuilder = class { + constructor() { + this.code = null; + this.codeMetadata = ""; + this.arguments = []; + } + /** + * Sets the code of the Smart Contract. + */ + setCode(code2) { + this.code = code2; + return this; + } + /** + * Sets the code metadata of the Smart Contract. + */ + setCodeMetadata(codeMetadata) { + this.codeMetadata = codeMetadata; + return this; + } + /** + * Adds upgrade (`init`) arguments. + */ + addInitArg(arg) { + this.arguments.push(arg); + return this; + } + /** + * Sets upgrade (`init`) arguments. + */ + setInitArgs(args) { + this.arguments = args; + return this; + } + /** + * Builds the {@link TransactionPayload}. + */ + build() { + utils_1.guardValueIsSet("code", this.code); + let code2 = this.code.toString(); + let codeMetadata = this.codeMetadata.toString(); + let data = `upgradeContract@${code2}@${codeMetadata}`; + data = appendArgumentsToString(data, this.arguments); + return new transactionPayload_1.TransactionPayload(data); + } + }; + exports2.ContractUpgradePayloadBuilder = ContractUpgradePayloadBuilder; + var ContractCallPayloadBuilder = class { + constructor() { + this.contractFunction = null; + this.arguments = []; + } + /** + * Sets the function to be called (executed). + */ + setFunction(contractFunction) { + this.contractFunction = contractFunction; + return this; + } + /** + * Adds a function argument. + */ + addArg(arg) { + this.arguments.push(arg); + return this; + } + /** + * Sets the function arguments. + */ + setArgs(args) { + this.arguments = args; + return this; + } + /** + * Builds the {@link TransactionPayload}. + */ + build() { + utils_1.guardValueIsSet("calledFunction", this.contractFunction); + let data = this.contractFunction.toString(); + data = appendArgumentsToString(data, this.arguments); + return new transactionPayload_1.TransactionPayload(data); + } + }; + exports2.ContractCallPayloadBuilder = ContractCallPayloadBuilder; + function appendArgumentsToString(to, values) { + let { argumentsString, count } = new argSerializer_1.ArgSerializer().valuesToString(values); + if (count == 0) { + return to; + } + return `${to}@${argumentsString}`; + } + } +}); + +// node_modules/@multiversx/sdk-core/out/smartcontracts/index.js +var require_smartcontracts = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartcontracts/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_argSerializer(), exports2); + __exportStar2(require_code(), exports2); + __exportStar2(require_codec2(), exports2); + __exportStar2(require_codeMetadata2(), exports2); + __exportStar2(require_function(), exports2); + __exportStar2(require_interaction(), exports2); + __exportStar2(require_interactionChecker(), exports2); + __exportStar2(require_interface(), exports2); + __exportStar2(require_nativeSerializer(), exports2); + __exportStar2(require_query(), exports2); + __exportStar2(require_resultsParser(), exports2); + __exportStar2(require_returnCode(), exports2); + __exportStar2(require_smartContract(), exports2); + __exportStar2(require_transactionPayloadBuilders(), exports2); + __exportStar2(require_typesystem(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js +var require_resources = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.gatherAllEvents = exports2.findEventsByFirstTopic = exports2.findEventsByIdentifier = exports2.findEventsByPredicate = exports2.SmartContractCallOutcome = exports2.TransactionOutcome = exports2.SmartContractResult = exports2.TransactionLogs = exports2.TransactionEvent = void 0; + var TransactionEvent = class { + constructor(init) { + this.address = ""; + this.identifier = ""; + this.topics = []; + this.dataItems = []; + Object.assign(this, init); + } + }; + exports2.TransactionEvent = TransactionEvent; + var TransactionLogs2 = class { + constructor(init) { + this.address = ""; + this.events = []; + Object.assign(this, init); + } + }; + exports2.TransactionLogs = TransactionLogs2; + var SmartContractResult = class { + constructor(init) { + this.sender = ""; + this.receiver = ""; + this.data = new Uint8Array(); + this.logs = new TransactionLogs2({}); + Object.assign(this, init); + } + }; + exports2.SmartContractResult = SmartContractResult; + var TransactionOutcome = class { + constructor(init) { + this.directSmartContractCallOutcome = new SmartContractCallOutcome({}); + this.smartContractResults = []; + this.logs = new TransactionLogs2({}); + Object.assign(this, init); + } + }; + exports2.TransactionOutcome = TransactionOutcome; + var SmartContractCallOutcome = class { + constructor(init) { + this.function = ""; + this.returnDataParts = []; + this.returnMessage = ""; + this.returnCode = ""; + Object.assign(this, init); + } + }; + exports2.SmartContractCallOutcome = SmartContractCallOutcome; + function findEventsByPredicate(transactionOutcome, predicate) { + return gatherAllEvents(transactionOutcome).filter(predicate); + } + exports2.findEventsByPredicate = findEventsByPredicate; + function findEventsByIdentifier(transactionOutcome, identifier) { + return findEventsByPredicate(transactionOutcome, (event) => event.identifier == identifier); + } + exports2.findEventsByIdentifier = findEventsByIdentifier; + function findEventsByFirstTopic(transactionOutcome, topic) { + return findEventsByPredicate(transactionOutcome, (event) => event.topics[0]?.toString() == topic); + } + exports2.findEventsByFirstTopic = findEventsByFirstTopic; + function gatherAllEvents(transactionOutcome) { + const allEvents = []; + allEvents.push(...transactionOutcome.logs.events); + for (const item of transactionOutcome.smartContractResults) { + allEvents.push(...item.logs.events); + } + return allEvents; + } + exports2.gatherAllEvents = gatherAllEvents; + } +}); + +// node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js +var require_transactionsConverter = __commonJS({ + "node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionsConverter = void 0; + var smartcontracts_1 = require_smartcontracts(); + var transaction_1 = require_transaction(); + var resources_1 = require_resources(); + var TransactionsConverter = class { + transactionToPlainObject(transaction) { + const plainObject = { + nonce: Number(transaction.nonce), + value: transaction.value.toString(), + receiver: transaction.receiver, + sender: transaction.sender, + senderUsername: this.toBase64OrUndefined(transaction.senderUsername), + receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), + gasPrice: Number(transaction.gasPrice), + gasLimit: Number(transaction.gasLimit), + data: this.toBase64OrUndefined(transaction.data), + chainID: transaction.chainID.valueOf(), + version: transaction.version, + options: transaction.options == 0 ? void 0 : transaction.options, + guardian: transaction.guardian ? transaction.guardian : void 0, + signature: this.toHexOrUndefined(transaction.signature), + guardianSignature: this.toHexOrUndefined(transaction.guardianSignature) + }; + return plainObject; + } + toBase64OrUndefined(value) { + return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; + } + toHexOrUndefined(value) { + return value && value.length ? import_buffer.Buffer.from(value).toString("hex") : void 0; + } + plainObjectToTransaction(object) { + const transaction = new transaction_1.Transaction({ + nonce: BigInt(object.nonce), + value: BigInt(object.value || ""), + receiver: object.receiver, + receiverUsername: this.bufferFromBase64(object.receiverUsername).toString(), + sender: object.sender, + senderUsername: this.bufferFromBase64(object.senderUsername).toString(), + guardian: object.guardian, + gasPrice: BigInt(object.gasPrice), + gasLimit: BigInt(object.gasLimit), + data: this.bufferFromBase64(object.data), + chainID: String(object.chainID), + version: Number(object.version), + options: Number(object.options), + signature: this.bufferFromHex(object.signature), + guardianSignature: this.bufferFromHex(object.guardianSignature) + }); + return transaction; + } + bufferFromBase64(value) { + return import_buffer.Buffer.from(value || "", "base64"); + } + bufferFromHex(value) { + return import_buffer.Buffer.from(value || "", "hex"); + } + transactionOnNetworkToOutcome(transactionOnNetwork) { + const legacyResultsParser = new smartcontracts_1.ResultsParser(); + const callOutcomeBundle = legacyResultsParser.parseUntypedOutcome(transactionOnNetwork); + const callOutcome = new resources_1.SmartContractCallOutcome({ + function: transactionOnNetwork.function, + returnCode: callOutcomeBundle.returnCode.toString(), + returnMessage: callOutcomeBundle.returnMessage, + returnDataParts: callOutcomeBundle.values + }); + const contractResults = transactionOnNetwork.contractResults.items.map((result) => this.smartContractResultOnNetworkToSmartContractResult(result)); + const logs = new resources_1.TransactionLogs({ + address: transactionOnNetwork.logs.address.bech32(), + events: transactionOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) + }); + return new resources_1.TransactionOutcome({ + logs, + smartContractResults: contractResults, + directSmartContractCallOutcome: callOutcome + }); + } + smartContractResultOnNetworkToSmartContractResult(resultOnNetwork) { + return new resources_1.SmartContractResult({ + sender: resultOnNetwork.sender.bech32(), + receiver: resultOnNetwork.receiver.bech32(), + data: import_buffer.Buffer.from(resultOnNetwork.data), + logs: new resources_1.TransactionLogs({ + address: resultOnNetwork.logs.address.bech32(), + events: resultOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) + }) + }); + } + eventOnNetworkToEvent(eventOnNetwork) { + const legacyData = eventOnNetwork.dataPayload?.valueOf() || import_buffer.Buffer.from(eventOnNetwork.data || ""); + const dataItems = eventOnNetwork.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; + if (dataItems.length === 0) { + if (legacyData.length) { + dataItems.push(import_buffer.Buffer.from(legacyData)); + } + } + return new resources_1.TransactionEvent({ + address: eventOnNetwork.address.bech32(), + identifier: eventOnNetwork.identifier, + topics: eventOnNetwork.topics.map((topic) => import_buffer.Buffer.from(topic.hex(), "hex")), + dataItems + }); + } + }; + exports2.TransactionsConverter = TransactionsConverter; + } +}); + +// node_modules/@multiversx/sdk-core/out/hash.js +var require_hash = __commonJS({ + "node_modules/@multiversx/sdk-core/out/hash.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Hash = void 0; + var errors = __importStar2(require_errors()); + var Hash = class _Hash { + /** + * Creates a new Hash object. + * + * @param hash The hash, as a Buffer or a hex-encoded string. + */ + constructor(hash) { + if (!hash) { + this.hash = import_buffer.Buffer.from([]); + } else if (hash instanceof import_buffer.Buffer) { + this.hash = hash; + } else if (typeof hash === "string") { + this.hash = import_buffer.Buffer.from(hash, "hex"); + } else { + throw new errors.ErrBadType("hash", "buffer | string", hash); + } + } + static empty() { + return new _Hash(import_buffer.Buffer.from([])); + } + /** + * Returns whether the hash is empty (not computed). + */ + isEmpty() { + return this.hash.length == 0; + } + toString() { + return this.hex(); + } + hex() { + return this.hash.toString("hex"); + } + valueOf() { + return this.hash; + } + }; + exports2.Hash = Hash; + } +}); + +// node_modules/@multiversx/sdk-core/out/signature.js +var require_signature = __commonJS({ + "node_modules/@multiversx/sdk-core/out/signature.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.interpretSignatureAsBuffer = exports2.Signature = void 0; + var errors = __importStar2(require_errors()); + var SIGNATURE_LENGTH = 64; + var Signature = class _Signature { + constructor(value) { + this.valueHex = ""; + if (!value) { + return; + } + if (typeof value === "string") { + return _Signature.fromHex(value); + } + if (value instanceof import_buffer.Buffer) { + return _Signature.fromBuffer(value); + } + } + static empty() { + return new _Signature(); + } + static fromHex(value) { + if (value.startsWith("0x")) { + value = value.slice(2); + } + if (!_Signature.isValidHex(value)) { + throw new errors.ErrSignatureCannotCreate(value); + } + return _Signature.fromValidHex(value); + } + static isValidHex(value) { + return import_buffer.Buffer.from(value, "hex").length == SIGNATURE_LENGTH; + } + static fromValidHex(value) { + let result = new _Signature(); + result.valueHex = value; + return result; + } + static fromBuffer(buffer) { + if (buffer.length != SIGNATURE_LENGTH) { + throw new errors.ErrSignatureCannotCreate(buffer); + } + return _Signature.fromValidHex(buffer.toString("hex")); + } + hex() { + return this.valueHex; + } + }; + exports2.Signature = Signature; + function interpretSignatureAsBuffer(signature) { + if (ArrayBuffer.isView(signature)) { + return import_buffer.Buffer.from(signature); + } else if (signature.hex != null) { + return import_buffer.Buffer.from(signature.hex(), "hex"); + } + throw new Error(`Object cannot be interpreted as a signature: ${signature}`); + } + exports2.interpretSignatureAsBuffer = interpretSignatureAsBuffer; + } +}); + +// node_modules/@protobufjs/aspromise/index.js +var require_aspromise = __commonJS({ + "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = asPromise; + function asPromise(fn, ctx) { + var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params2 = new Array(arguments.length - 1), offset2 = 0; + while (offset2 < params2.length) + params2[offset2++] = arguments[offset2]; + resolve.apply(null, params2); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); + } + } +}); + +// node_modules/@protobufjs/base64/index.js +var require_base64 = __commonJS({ + "node_modules/@protobufjs/base64/index.js"(exports2) { + "use strict"; + init_shim(); + var base642 = exports2; + base642.length = function length2(string2) { + var p3 = string2.length; + if (!p3) + return 0; + var n3 = 0; + while (--p3 % 4 > 1 && string2.charAt(p3) === "=") + ++n3; + return Math.ceil(string2.length * 3) / 4 - n3; + }; + var b64 = new Array(64); + var s64 = new Array(123); + for (i2 = 0; i2 < 64; ) + s64[b64[i2] = i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 - 59 | 43] = i2++; + var i2; + base642.encode = function encode5(buffer, start, end) { + var parts = null, chunk = []; + var i3 = 0, j2 = 0, t; + while (start < end) { + var b4 = buffer[start++]; + switch (j2) { + case 0: + chunk[i3++] = b64[b4 >> 2]; + t = (b4 & 3) << 4; + j2 = 1; + break; + case 1: + chunk[i3++] = b64[t | b4 >> 4]; + t = (b4 & 15) << 2; + j2 = 2; + break; + case 2: + chunk[i3++] = b64[t | b4 >> 6]; + chunk[i3++] = b64[b4 & 63]; + j2 = 0; + break; + } + if (i3 > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i3 = 0; + } + } + if (j2) { + chunk[i3++] = b64[t]; + chunk[i3++] = 61; + if (j2 === 1) + chunk[i3++] = 61; + } + if (parts) { + if (i3) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i3))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i3)); + }; + var invalidEncoding = "invalid encoding"; + base642.decode = function decode6(string2, buffer, offset) { + var start = offset; + var j2 = 0, t; + for (var i3 = 0; i3 < string2.length; ) { + var c4 = string2.charCodeAt(i3++); + if (c4 === 61 && j2 > 1) + break; + if ((c4 = s64[c4]) === void 0) + throw Error(invalidEncoding); + switch (j2) { + case 0: + t = c4; + j2 = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c4 & 48) >> 4; + t = c4; + j2 = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c4 & 60) >> 2; + t = c4; + j2 = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c4; + j2 = 0; + break; + } + } + if (j2 === 1) + throw Error(invalidEncoding); + return offset - start; + }; + base642.test = function test(string2) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string2); + }; + } +}); + +// node_modules/@protobufjs/eventemitter/index.js +var require_eventemitter = __commonJS({ + "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = EventEmitter2; + function EventEmitter2() { + this._listeners = {}; + } + EventEmitter2.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn, + ctx: ctx || this + }); + return this; + }; + EventEmitter2.prototype.off = function off(evt, fn) { + if (evt === void 0) + this._listeners = {}; + else { + if (fn === void 0) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i2 = 0; i2 < listeners.length; ) + if (listeners[i2].fn === fn) + listeners.splice(i2, 1); + else + ++i2; + } + } + return this; + }; + EventEmitter2.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], i2 = 1; + for (; i2 < arguments.length; ) + args.push(arguments[i2++]); + for (i2 = 0; i2 < listeners.length; ) + listeners[i2].fn.apply(listeners[i2++].ctx, args); + } + return this; + }; + } +}); + +// node_modules/@protobufjs/float/index.js +var require_float = __commonJS({ + "node_modules/@protobufjs/float/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = factory(factory); + function factory(exports3) { + if (typeof Float32Array !== "undefined") + (function() { + var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + })(); + else + (function() { + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign2 = val < 0 ? 1 : 0; + if (sign2) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? ( + /* positive */ + 0 + ) : ( + /* negative 0 */ + 2147483648 + ), buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 34028234663852886e22) + writeUint((sign2 << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 11754943508222875e-54) + writeUint((sign2 << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign2 << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), sign2 = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; + return exponent === 255 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 1401298464324817e-60 * mantissa : sign2 * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + })(); + if (typeof Float64Array !== "undefined") + (function() { + var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + })(); + else + (function() { + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign2 = val < 0 ? 1 : 0; + if (sign2) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? ( + /* positive */ + 0 + ) : ( + /* negative 0 */ + 2147483648 + ), buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 17976931348623157e292) { + writeUint(0, buf, pos + off0); + writeUint((sign2 << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 22250738585072014e-324) { + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign2 << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign2 << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); + var sign2 = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 5e-324 * mantissa : sign2 * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + })(); + return exports3; + } + function writeUintLE(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + function writeUintBE(val, buf, pos) { + buf[pos] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; + } + function readUintLE(buf, pos) { + return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; + } + function readUintBE(buf, pos) { + return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; + } + } +}); + +// node_modules/@protobufjs/inquire/index.js +var require_inquire = __commonJS({ + "node_modules/@protobufjs/inquire/index.js"(exports, module) { + "use strict"; + init_shim(); + module.exports = inquire; + function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/, "re"))(moduleName); + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e2) { + } + return null; + } + } +}); + +// node_modules/@protobufjs/utf8/index.js +var require_utf8 = __commonJS({ + "node_modules/@protobufjs/utf8/index.js"(exports2) { + "use strict"; + init_shim(); + var utf8 = exports2; + utf8.length = function utf8_length(string2) { + var len = 0, c4 = 0; + for (var i2 = 0; i2 < string2.length; ++i2) { + c4 = string2.charCodeAt(i2); + if (c4 < 128) + len += 1; + else if (c4 < 2048) + len += 2; + else if ((c4 & 64512) === 55296 && (string2.charCodeAt(i2 + 1) & 64512) === 56320) { + ++i2; + len += 4; + } else + len += 3; + } + return len; + }; + utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, chunk = [], i2 = 0, t; + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i2++] = t; + else if (t > 191 && t < 224) + chunk[i2++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536; + chunk[i2++] = 55296 + (t >> 10); + chunk[i2++] = 56320 + (t & 1023); + } else + chunk[i2++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i2 > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i2 = 0; + } + } + if (parts) { + if (i2) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i2)); + }; + utf8.write = function utf8_write(string2, buffer, offset) { + var start = offset, c1, c22; + for (var i2 = 0; i2 < string2.length; ++i2) { + c1 = string2.charCodeAt(i2); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 64512) === 55296 && ((c22 = string2.charCodeAt(i2 + 1)) & 64512) === 56320) { + c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023); + ++i2; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; + }; + } +}); + +// node_modules/@protobufjs/pool/index.js +var require_pool = __commonJS({ + "node_modules/@protobufjs/pool/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = pool; + function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX2 = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size2) { + if (size2 < 1 || size2 > MAX2) + return alloc(size2); + if (offset + size2 > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size2); + if (offset & 7) + offset = (offset | 7) + 1; + return buf; + }; + } + } +}); + +// node_modules/protobufjs/src/util/longbits.js +var require_longbits = __commonJS({ + "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = LongBits; + var util = require_minimal(); + function LongBits(lo, hi) { + this.lo = lo >>> 0; + this.hi = hi >>> 0; + } + var zero = LongBits.zero = new LongBits(0, 0); + zero.toNumber = function() { + return 0; + }; + zero.zzEncode = zero.zzDecode = function() { + return this; + }; + zero.length = function() { + return 1; + }; + var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign2 = value < 0; + if (sign2) + value = -value; + var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; + if (sign2) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); + }; + LongBits.from = function from3(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; + }; + LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; + }; + LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; + }; + var charCodeAt = String.prototype.charCodeAt; + LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, + (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 + ); + }; + LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24, + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); + }; + LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = (this.lo << 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = (this.hi >>> 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.length = function length2() { + var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; + return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; + }; + } +}); + +// node_modules/protobufjs/src/util/minimal.js +var require_minimal = __commonJS({ + "node_modules/protobufjs/src/util/minimal.js"(exports2) { + "use strict"; + init_shim(); + var util = exports2; + util.asPromise = require_aspromise(); + util.base64 = require_base64(); + util.EventEmitter = require_eventemitter(); + util.float = require_float(); + util.inquire = require_inquire(); + util.utf8 = require_utf8(); + util.pool = require_pool(); + util.LongBits = require_longbits(); + util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); + util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; + util.emptyArray = Object.freeze ? Object.freeze([]) : ( + /* istanbul ignore next */ + [] + ); + util.emptyObject = Object.freeze ? Object.freeze({}) : ( + /* istanbul ignore next */ + {} + ); + util.isInteger = Number.isInteger || /* istanbul ignore next */ + function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; + }; + util.isString = function isString2(value) { + return typeof value === "string" || value instanceof String; + }; + util.isObject = function isObject(value) { + return value && typeof value === "object"; + }; + util.isset = /** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ + util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; + }; + util.Buffer = function() { + try { + var Buffer2 = util.inquire("buffer").Buffer; + return Buffer2.prototype.utf8Write ? Buffer2 : ( + /* istanbul ignore next */ + null + ); + } catch (e2) { + return null; + } + }(); + util._Buffer_from = null; + util._Buffer_allocUnsafe = null; + util.newBuffer = function newBuffer(sizeOrArray) { + return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); + }; + util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + util.Long = /* istanbul ignore next */ + util.global.dcodeIO && /* istanbul ignore next */ + util.global.dcodeIO.Long || /* istanbul ignore next */ + util.global.Long || util.inquire("long"); + util.key2Re = /^true|false|0|1$/; + util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + util.longToHash = function longToHash(value) { + return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; + }; + util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); + }; + function merge(dst, src2, ifNotSet) { + for (var keys2 = Object.keys(src2), i2 = 0; i2 < keys2.length; ++i2) + if (dst[keys2[i2]] === void 0 || !ifNotSet) + dst[keys2[i2]] = src2[keys2[i2]]; + return dst; + } + util.merge = merge; + util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); + }; + function newError(name2) { + function CustomError(message, properties) { + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + Object.defineProperty(this, "message", { get: function() { + return message; + } }); + if (Error.captureStackTrace) + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + if (properties) + merge(this, properties); + } + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true + }, + name: { + get: function get2() { + return name2; + }, + set: void 0, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true + }, + toString: { + value: function value() { + return this.name + ": " + this.message; + }, + writable: true, + enumerable: false, + configurable: true + } + }); + return CustomError; + } + util.newError = newError; + util.ProtocolError = newError("ProtocolError"); + util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i2 = 0; i2 < fieldNames.length; ++i2) + fieldMap[fieldNames[i2]] = 1; + return function() { + for (var keys2 = Object.keys(this), i3 = keys2.length - 1; i3 > -1; --i3) + if (fieldMap[keys2[i3]] === 1 && this[keys2[i3]] !== void 0 && this[keys2[i3]] !== null) + return keys2[i3]; + }; + }; + util.oneOfSetter = function setOneOf(fieldNames) { + return function(name2) { + for (var i2 = 0; i2 < fieldNames.length; ++i2) + if (fieldNames[i2] !== name2) + delete this[fieldNames[i2]]; + }; + }; + util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true + }; + util._configure = function() { + var Buffer2 = util.Buffer; + if (!Buffer2) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer2(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer2(size); + }; + }; + } +}); + +// node_modules/protobufjs/src/writer.js +var require_writer = __commonJS({ + "node_modules/protobufjs/src/writer.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Writer; + var util = require_minimal(); + var BufferWriter; + var LongBits = util.LongBits; + var base642 = util.base64; + var utf8 = util.utf8; + function Op(fn, len, val) { + this.fn = fn; + this.len = len; + this.next = void 0; + this.val = val; + } + function noop() { + } + function State(writer) { + this.head = writer.head; + this.tail = writer.tail; + this.len = writer.len; + this.next = writer.states; + } + function Writer() { + this.len = 0; + this.head = new Op(noop, 0, 0); + this.tail = this.head; + this.states = null; + } + var create2 = function create3() { + return util.Buffer ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } : function create_array() { + return new Writer(); + }; + }; + Writer.create = create2(); + Writer.alloc = function alloc(size) { + return new util.Array(size); + }; + if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; + }; + function writeByte(val, buf, pos) { + buf[pos] = val & 255; + } + function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; + } + function VarintOp(len, val) { + this.len = len; + this.next = void 0; + this.val = val; + } + VarintOp.prototype = Object.create(Op.prototype); + VarintOp.prototype.fn = writeVarint32; + Writer.prototype.uint32 = function write_uint32(value) { + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, + value + )).len; + return this; + }; + Writer.prototype.int32 = function write_int32(value) { + return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); + }; + Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); + }; + function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; + } + Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.int64 = Writer.prototype.uint64; + Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); + }; + function writeFixed32(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); + }; + Writer.prototype.sfixed32 = Writer.prototype.fixed32; + Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); + }; + Writer.prototype.sfixed64 = Writer.prototype.fixed64; + Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); + }; + Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); + }; + var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytes_for(val, buf, pos) { + for (var i2 = 0; i2 < val.length; ++i2) + buf[pos + i2] = val[i2]; + }; + Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base642.length(value)); + base642.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); + }; + Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); + }; + Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; + }; + Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; + }; + Writer.prototype.ldelim = function ldelim() { + var head = this.head, tail = this.tail, len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; + this.tail = tail; + this.len += len; + } + return this; + }; + Writer.prototype.finish = function finish() { + var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + return buf; + }; + Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create2(); + BufferWriter._configure(); + }; + } +}); + +// node_modules/protobufjs/src/writer_buffer.js +var require_writer_buffer = __commonJS({ + "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = BufferWriter; + var Writer = require_writer(); + (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + var util = require_minimal(); + function BufferWriter() { + Writer.call(this); + } + BufferWriter._configure = function() { + BufferWriter.alloc = util._Buffer_allocUnsafe; + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) + val.copy(buf, pos, 0, val.length); + else + for (var i2 = 0; i2 < val.length; ) + buf[pos++] = val[i2++]; + }; + }; + BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; + }; + function writeStringBuffer(val, buf, pos) { + if (val.length < 40) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); + } + BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; + }; + BufferWriter._configure(); + } +}); + +// node_modules/protobufjs/src/reader.js +var require_reader = __commonJS({ + "node_modules/protobufjs/src/reader.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Reader; + var util = require_minimal(); + var BufferReader; + var LongBits = util.LongBits; + var utf8 = util.utf8; + function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); + } + function Reader(buffer) { + this.buf = buffer; + this.pos = 0; + this.len = buffer.length; + } + var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } : function create_array2(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + var create2 = function create3() { + return util.Buffer ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer2) { + return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); + })(buffer); + } : create_array; + }; + Reader.create = create2(); + Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ + util.Array.prototype.slice; + Reader.prototype.uint32 = /* @__PURE__ */ function read_uint32_setup() { + var value = 4294967295; + return function read_uint32() { + value = (this.buf[this.pos] & 127) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; + }(); + Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; + }; + Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; + }; + function readLongVarint() { + var bits = new LongBits(0, 0); + var i2 = 0; + if (this.len - this.pos > 4) { + for (; i2 < 4; ++i2) { + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i2 = 0; + } else { + for (; i2 < 3; ++i2) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i2 * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { + for (; i2 < 5; ++i2) { + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i2 < 5; ++i2) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + throw Error("invalid varint encoding"); + } + Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; + }; + function readFixed32_end(buf, end) { + return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; + } + Reader.prototype.fixed32 = function read_fixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4); + }; + Reader.prototype.sfixed32 = function read_sfixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4) | 0; + }; + function readFixed64() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); + } + Reader.prototype.float = function read_float() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; + }; + Reader.prototype.double = function read_double() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; + }; + Reader.prototype.bytes = function read_bytes() { + var length2 = this.uint32(), start = this.pos, end = this.pos + length2; + if (end > this.len) + throw indexOutOfRange(this, length2); + this.pos += length2; + if (Array.isArray(this.buf)) + return this.buf.slice(start, end); + if (start === end) { + var nativeBuffer = util.Buffer; + return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); + }; + Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); + }; + Reader.prototype.skip = function skip(length2) { + if (typeof length2 === "number") { + if (this.pos + length2 > this.len) + throw indexOutOfRange(this, length2); + this.pos += length2; + } else { + do { + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; + }; + Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; + }; + Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create2(); + BufferReader._configure(); + var fn = util.Long ? "toLong" : ( + /* istanbul ignore next */ + "toNumber" + ); + util.merge(Reader.prototype, { + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + }); + }; + } +}); + +// node_modules/protobufjs/src/reader_buffer.js +var require_reader_buffer = __commonJS({ + "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = BufferReader; + var Reader = require_reader(); + (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + var util = require_minimal(); + function BufferReader(buffer) { + Reader.call(this, buffer); + } + BufferReader._configure = function() { + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; + }; + BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); + return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); + }; + BufferReader._configure(); + } +}); + +// node_modules/protobufjs/src/rpc/service.js +var require_service = __commonJS({ + "node_modules/protobufjs/src/rpc/service.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = Service; + var util = require_minimal(); + (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + function Service(rpcImpl, requestDelimited, responseDelimited) { + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + util.EventEmitter.call(this); + this.rpcImpl = rpcImpl; + this.requestDelimited = Boolean(requestDelimited); + this.responseDelimited = Boolean(responseDelimited); + } + Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + if (!request) + throw TypeError("request must be specified"); + var self2 = this; + if (!callback) + return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request); + if (!self2.rpcImpl) { + setTimeout(function() { + callback(Error("already ended")); + }, 0); + return void 0; + } + try { + return self2.rpcImpl( + method, + requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + if (err) { + self2.emit("error", err, method); + return callback(err); + } + if (response === null) { + self2.end( + /* endedByRPC */ + true + ); + return void 0; + } + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err2) { + self2.emit("error", err2, method); + return callback(err2); + } + } + self2.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self2.emit("error", err, method); + setTimeout(function() { + callback(err); + }, 0); + return void 0; + } + }; + Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; + }; + } +}); + +// node_modules/protobufjs/src/rpc.js +var require_rpc = __commonJS({ + "node_modules/protobufjs/src/rpc.js"(exports2) { + "use strict"; + init_shim(); + var rpc = exports2; + rpc.Service = require_service(); + } +}); + +// node_modules/protobufjs/src/roots.js +var require_roots = __commonJS({ + "node_modules/protobufjs/src/roots.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = {}; + } +}); + +// node_modules/protobufjs/src/index-minimal.js +var require_index_minimal = __commonJS({ + "node_modules/protobufjs/src/index-minimal.js"(exports2) { + "use strict"; + init_shim(); + var protobuf = exports2; + protobuf.build = "minimal"; + protobuf.Writer = require_writer(); + protobuf.BufferWriter = require_writer_buffer(); + protobuf.Reader = require_reader(); + protobuf.BufferReader = require_reader_buffer(); + protobuf.util = require_minimal(); + protobuf.rpc = require_rpc(); + protobuf.roots = require_roots(); + protobuf.configure = configure; + function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); + } + configure(); + } +}); + +// node_modules/protobufjs/minimal.js +var require_minimal2 = __commonJS({ + "node_modules/protobufjs/minimal.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = require_index_minimal(); + } +}); + +// node_modules/@multiversx/sdk-core/out/proto/compiled.js +var require_compiled = __commonJS({ + "node_modules/@multiversx/sdk-core/out/proto/compiled.js"(exports2, module2) { + "use strict"; + init_shim(); + (function(global2, factory) { + if (typeof define === "function" && define.amd) + define(["protobufjs/minimal"], factory); + else if (typeof __require === "function" && typeof module2 === "object" && module2 && module2.exports) + module2.exports = factory(require_minimal2()); + })(exports2, function($protobuf) { + "use strict"; + var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; + var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); + $root.proto = function() { + var proto = {}; + proto.Transaction = function() { + function Transaction4(properties) { + if (properties) { + for (var keys2 = Object.keys(properties), i2 = 0; i2 < keys2.length; ++i2) + if (properties[keys2[i2]] != null) + this[keys2[i2]] = properties[keys2[i2]]; + } + } + Transaction4.prototype.Nonce = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; + Transaction4.prototype.Value = $util.newBuffer([]); + Transaction4.prototype.RcvAddr = $util.newBuffer([]); + Transaction4.prototype.RcvUserName = $util.newBuffer([]); + Transaction4.prototype.SndAddr = $util.newBuffer([]); + Transaction4.prototype.SndUserName = $util.newBuffer([]); + Transaction4.prototype.GasPrice = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; + Transaction4.prototype.GasLimit = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; + Transaction4.prototype.Data = $util.newBuffer([]); + Transaction4.prototype.ChainID = $util.newBuffer([]); + Transaction4.prototype.Version = 0; + Transaction4.prototype.Signature = $util.newBuffer([]); + Transaction4.prototype.Options = 0; + Transaction4.prototype.GuardianAddr = $util.newBuffer([]); + Transaction4.prototype.GuardianSignature = $util.newBuffer([]); + Transaction4.create = function create2(properties) { + return new Transaction4(properties); + }; + Transaction4.encode = function encode5(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.Nonce != null && Object.hasOwnProperty.call(message, "Nonce")) + writer.uint32( + /* id 1, wireType 0 =*/ + 8 + ).uint64(message.Nonce); + if (message.Value != null && Object.hasOwnProperty.call(message, "Value")) + writer.uint32( + /* id 2, wireType 2 =*/ + 18 + ).bytes(message.Value); + if (message.RcvAddr != null && Object.hasOwnProperty.call(message, "RcvAddr")) + writer.uint32( + /* id 3, wireType 2 =*/ + 26 + ).bytes(message.RcvAddr); + if (message.RcvUserName != null && Object.hasOwnProperty.call(message, "RcvUserName")) + writer.uint32( + /* id 4, wireType 2 =*/ + 34 + ).bytes(message.RcvUserName); + if (message.SndAddr != null && Object.hasOwnProperty.call(message, "SndAddr")) + writer.uint32( + /* id 5, wireType 2 =*/ + 42 + ).bytes(message.SndAddr); + if (message.SndUserName != null && Object.hasOwnProperty.call(message, "SndUserName")) + writer.uint32( + /* id 6, wireType 2 =*/ + 50 + ).bytes(message.SndUserName); + if (message.GasPrice != null && Object.hasOwnProperty.call(message, "GasPrice")) + writer.uint32( + /* id 7, wireType 0 =*/ + 56 + ).uint64(message.GasPrice); + if (message.GasLimit != null && Object.hasOwnProperty.call(message, "GasLimit")) + writer.uint32( + /* id 8, wireType 0 =*/ + 64 + ).uint64(message.GasLimit); + if (message.Data != null && Object.hasOwnProperty.call(message, "Data")) + writer.uint32( + /* id 9, wireType 2 =*/ + 74 + ).bytes(message.Data); + if (message.ChainID != null && Object.hasOwnProperty.call(message, "ChainID")) + writer.uint32( + /* id 10, wireType 2 =*/ + 82 + ).bytes(message.ChainID); + if (message.Version != null && Object.hasOwnProperty.call(message, "Version")) + writer.uint32( + /* id 11, wireType 0 =*/ + 88 + ).uint32(message.Version); + if (message.Signature != null && Object.hasOwnProperty.call(message, "Signature")) + writer.uint32( + /* id 12, wireType 2 =*/ + 98 + ).bytes(message.Signature); + if (message.Options != null && Object.hasOwnProperty.call(message, "Options")) + writer.uint32( + /* id 13, wireType 0 =*/ + 104 + ).uint32(message.Options); + if (message.GuardianAddr != null && Object.hasOwnProperty.call(message, "GuardianAddr")) + writer.uint32( + /* id 14, wireType 2 =*/ + 114 + ).bytes(message.GuardianAddr); + if (message.GuardianSignature != null && Object.hasOwnProperty.call(message, "GuardianSignature")) + writer.uint32( + /* id 15, wireType 2 =*/ + 122 + ).bytes(message.GuardianSignature); + return writer; + }; + Transaction4.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + Transaction4.decode = function decode6(reader, length2) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length2 === void 0 ? reader.len : reader.pos + length2, message = new $root.proto.Transaction(); + while (reader.pos < end) { + var tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + message.Nonce = reader.uint64(); + break; + } + case 2: { + message.Value = reader.bytes(); + break; + } + case 3: { + message.RcvAddr = reader.bytes(); + break; + } + case 4: { + message.RcvUserName = reader.bytes(); + break; + } + case 5: { + message.SndAddr = reader.bytes(); + break; + } + case 6: { + message.SndUserName = reader.bytes(); + break; + } + case 7: { + message.GasPrice = reader.uint64(); + break; + } + case 8: { + message.GasLimit = reader.uint64(); + break; + } + case 9: { + message.Data = reader.bytes(); + break; + } + case 10: { + message.ChainID = reader.bytes(); + break; + } + case 11: { + message.Version = reader.uint32(); + break; + } + case 12: { + message.Signature = reader.bytes(); + break; + } + case 13: { + message.Options = reader.uint32(); + break; + } + case 14: { + message.GuardianAddr = reader.bytes(); + break; + } + case 15: { + message.GuardianSignature = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + Transaction4.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + Transaction4.verify = function verify2(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.Nonce != null && message.hasOwnProperty("Nonce")) { + if (!$util.isInteger(message.Nonce) && !(message.Nonce && $util.isInteger(message.Nonce.low) && $util.isInteger(message.Nonce.high))) + return "Nonce: integer|Long expected"; + } + if (message.Value != null && message.hasOwnProperty("Value")) { + if (!(message.Value && typeof message.Value.length === "number" || $util.isString(message.Value))) + return "Value: buffer expected"; + } + if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) { + if (!(message.RcvAddr && typeof message.RcvAddr.length === "number" || $util.isString(message.RcvAddr))) + return "RcvAddr: buffer expected"; + } + if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) { + if (!(message.RcvUserName && typeof message.RcvUserName.length === "number" || $util.isString(message.RcvUserName))) + return "RcvUserName: buffer expected"; + } + if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) { + if (!(message.SndAddr && typeof message.SndAddr.length === "number" || $util.isString(message.SndAddr))) + return "SndAddr: buffer expected"; + } + if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) { + if (!(message.SndUserName && typeof message.SndUserName.length === "number" || $util.isString(message.SndUserName))) + return "SndUserName: buffer expected"; + } + if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) { + if (!$util.isInteger(message.GasPrice) && !(message.GasPrice && $util.isInteger(message.GasPrice.low) && $util.isInteger(message.GasPrice.high))) + return "GasPrice: integer|Long expected"; + } + if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) { + if (!$util.isInteger(message.GasLimit) && !(message.GasLimit && $util.isInteger(message.GasLimit.low) && $util.isInteger(message.GasLimit.high))) + return "GasLimit: integer|Long expected"; + } + if (message.Data != null && message.hasOwnProperty("Data")) { + if (!(message.Data && typeof message.Data.length === "number" || $util.isString(message.Data))) + return "Data: buffer expected"; + } + if (message.ChainID != null && message.hasOwnProperty("ChainID")) { + if (!(message.ChainID && typeof message.ChainID.length === "number" || $util.isString(message.ChainID))) + return "ChainID: buffer expected"; + } + if (message.Version != null && message.hasOwnProperty("Version")) { + if (!$util.isInteger(message.Version)) + return "Version: integer expected"; + } + if (message.Signature != null && message.hasOwnProperty("Signature")) { + if (!(message.Signature && typeof message.Signature.length === "number" || $util.isString(message.Signature))) + return "Signature: buffer expected"; + } + if (message.Options != null && message.hasOwnProperty("Options")) { + if (!$util.isInteger(message.Options)) + return "Options: integer expected"; + } + if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) { + if (!(message.GuardianAddr && typeof message.GuardianAddr.length === "number" || $util.isString(message.GuardianAddr))) + return "GuardianAddr: buffer expected"; + } + if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) { + if (!(message.GuardianSignature && typeof message.GuardianSignature.length === "number" || $util.isString(message.GuardianSignature))) + return "GuardianSignature: buffer expected"; + } + return null; + }; + Transaction4.fromObject = function fromObject(object) { + if (object instanceof $root.proto.Transaction) + return object; + var message = new $root.proto.Transaction(); + if (object.Nonce != null) { + if ($util.Long) + (message.Nonce = $util.Long.fromValue(object.Nonce)).unsigned = true; + else if (typeof object.Nonce === "string") + message.Nonce = parseInt(object.Nonce, 10); + else if (typeof object.Nonce === "number") + message.Nonce = object.Nonce; + else if (typeof object.Nonce === "object") + message.Nonce = new $util.LongBits(object.Nonce.low >>> 0, object.Nonce.high >>> 0).toNumber(true); + } + if (object.Value != null) { + if (typeof object.Value === "string") + $util.base64.decode(object.Value, message.Value = $util.newBuffer($util.base64.length(object.Value)), 0); + else if (object.Value.length >= 0) + message.Value = object.Value; + } + if (object.RcvAddr != null) { + if (typeof object.RcvAddr === "string") + $util.base64.decode(object.RcvAddr, message.RcvAddr = $util.newBuffer($util.base64.length(object.RcvAddr)), 0); + else if (object.RcvAddr.length >= 0) + message.RcvAddr = object.RcvAddr; + } + if (object.RcvUserName != null) { + if (typeof object.RcvUserName === "string") + $util.base64.decode(object.RcvUserName, message.RcvUserName = $util.newBuffer($util.base64.length(object.RcvUserName)), 0); + else if (object.RcvUserName.length >= 0) + message.RcvUserName = object.RcvUserName; + } + if (object.SndAddr != null) { + if (typeof object.SndAddr === "string") + $util.base64.decode(object.SndAddr, message.SndAddr = $util.newBuffer($util.base64.length(object.SndAddr)), 0); + else if (object.SndAddr.length >= 0) + message.SndAddr = object.SndAddr; + } + if (object.SndUserName != null) { + if (typeof object.SndUserName === "string") + $util.base64.decode(object.SndUserName, message.SndUserName = $util.newBuffer($util.base64.length(object.SndUserName)), 0); + else if (object.SndUserName.length >= 0) + message.SndUserName = object.SndUserName; + } + if (object.GasPrice != null) { + if ($util.Long) + (message.GasPrice = $util.Long.fromValue(object.GasPrice)).unsigned = true; + else if (typeof object.GasPrice === "string") + message.GasPrice = parseInt(object.GasPrice, 10); + else if (typeof object.GasPrice === "number") + message.GasPrice = object.GasPrice; + else if (typeof object.GasPrice === "object") + message.GasPrice = new $util.LongBits(object.GasPrice.low >>> 0, object.GasPrice.high >>> 0).toNumber(true); + } + if (object.GasLimit != null) { + if ($util.Long) + (message.GasLimit = $util.Long.fromValue(object.GasLimit)).unsigned = true; + else if (typeof object.GasLimit === "string") + message.GasLimit = parseInt(object.GasLimit, 10); + else if (typeof object.GasLimit === "number") + message.GasLimit = object.GasLimit; + else if (typeof object.GasLimit === "object") + message.GasLimit = new $util.LongBits(object.GasLimit.low >>> 0, object.GasLimit.high >>> 0).toNumber(true); + } + if (object.Data != null) { + if (typeof object.Data === "string") + $util.base64.decode(object.Data, message.Data = $util.newBuffer($util.base64.length(object.Data)), 0); + else if (object.Data.length >= 0) + message.Data = object.Data; + } + if (object.ChainID != null) { + if (typeof object.ChainID === "string") + $util.base64.decode(object.ChainID, message.ChainID = $util.newBuffer($util.base64.length(object.ChainID)), 0); + else if (object.ChainID.length >= 0) + message.ChainID = object.ChainID; + } + if (object.Version != null) + message.Version = object.Version >>> 0; + if (object.Signature != null) { + if (typeof object.Signature === "string") + $util.base64.decode(object.Signature, message.Signature = $util.newBuffer($util.base64.length(object.Signature)), 0); + else if (object.Signature.length >= 0) + message.Signature = object.Signature; + } + if (object.Options != null) + message.Options = object.Options >>> 0; + if (object.GuardianAddr != null) { + if (typeof object.GuardianAddr === "string") + $util.base64.decode(object.GuardianAddr, message.GuardianAddr = $util.newBuffer($util.base64.length(object.GuardianAddr)), 0); + else if (object.GuardianAddr.length >= 0) + message.GuardianAddr = object.GuardianAddr; + } + if (object.GuardianSignature != null) { + if (typeof object.GuardianSignature === "string") + $util.base64.decode(object.GuardianSignature, message.GuardianSignature = $util.newBuffer($util.base64.length(object.GuardianSignature)), 0); + else if (object.GuardianSignature.length >= 0) + message.GuardianSignature = object.GuardianSignature; + } + return message; + }; + Transaction4.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.Nonce = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.Nonce = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.Value = ""; + else { + object.Value = []; + if (options.bytes !== Array) + object.Value = $util.newBuffer(object.Value); + } + if (options.bytes === String) + object.RcvAddr = ""; + else { + object.RcvAddr = []; + if (options.bytes !== Array) + object.RcvAddr = $util.newBuffer(object.RcvAddr); + } + if (options.bytes === String) + object.RcvUserName = ""; + else { + object.RcvUserName = []; + if (options.bytes !== Array) + object.RcvUserName = $util.newBuffer(object.RcvUserName); + } + if (options.bytes === String) + object.SndAddr = ""; + else { + object.SndAddr = []; + if (options.bytes !== Array) + object.SndAddr = $util.newBuffer(object.SndAddr); + } + if (options.bytes === String) + object.SndUserName = ""; + else { + object.SndUserName = []; + if (options.bytes !== Array) + object.SndUserName = $util.newBuffer(object.SndUserName); + } + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.GasPrice = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.GasPrice = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.GasLimit = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.GasLimit = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.Data = ""; + else { + object.Data = []; + if (options.bytes !== Array) + object.Data = $util.newBuffer(object.Data); + } + if (options.bytes === String) + object.ChainID = ""; + else { + object.ChainID = []; + if (options.bytes !== Array) + object.ChainID = $util.newBuffer(object.ChainID); + } + object.Version = 0; + if (options.bytes === String) + object.Signature = ""; + else { + object.Signature = []; + if (options.bytes !== Array) + object.Signature = $util.newBuffer(object.Signature); + } + object.Options = 0; + if (options.bytes === String) + object.GuardianAddr = ""; + else { + object.GuardianAddr = []; + if (options.bytes !== Array) + object.GuardianAddr = $util.newBuffer(object.GuardianAddr); + } + if (options.bytes === String) + object.GuardianSignature = ""; + else { + object.GuardianSignature = []; + if (options.bytes !== Array) + object.GuardianSignature = $util.newBuffer(object.GuardianSignature); + } + } + if (message.Nonce != null && message.hasOwnProperty("Nonce")) + if (typeof message.Nonce === "number") + object.Nonce = options.longs === String ? String(message.Nonce) : message.Nonce; + else + object.Nonce = options.longs === String ? $util.Long.prototype.toString.call(message.Nonce) : options.longs === Number ? new $util.LongBits(message.Nonce.low >>> 0, message.Nonce.high >>> 0).toNumber(true) : message.Nonce; + if (message.Value != null && message.hasOwnProperty("Value")) + object.Value = options.bytes === String ? $util.base64.encode(message.Value, 0, message.Value.length) : options.bytes === Array ? Array.prototype.slice.call(message.Value) : message.Value; + if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) + object.RcvAddr = options.bytes === String ? $util.base64.encode(message.RcvAddr, 0, message.RcvAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvAddr) : message.RcvAddr; + if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) + object.RcvUserName = options.bytes === String ? $util.base64.encode(message.RcvUserName, 0, message.RcvUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvUserName) : message.RcvUserName; + if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) + object.SndAddr = options.bytes === String ? $util.base64.encode(message.SndAddr, 0, message.SndAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndAddr) : message.SndAddr; + if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) + object.SndUserName = options.bytes === String ? $util.base64.encode(message.SndUserName, 0, message.SndUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndUserName) : message.SndUserName; + if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) + if (typeof message.GasPrice === "number") + object.GasPrice = options.longs === String ? String(message.GasPrice) : message.GasPrice; + else + object.GasPrice = options.longs === String ? $util.Long.prototype.toString.call(message.GasPrice) : options.longs === Number ? new $util.LongBits(message.GasPrice.low >>> 0, message.GasPrice.high >>> 0).toNumber(true) : message.GasPrice; + if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) + if (typeof message.GasLimit === "number") + object.GasLimit = options.longs === String ? String(message.GasLimit) : message.GasLimit; + else + object.GasLimit = options.longs === String ? $util.Long.prototype.toString.call(message.GasLimit) : options.longs === Number ? new $util.LongBits(message.GasLimit.low >>> 0, message.GasLimit.high >>> 0).toNumber(true) : message.GasLimit; + if (message.Data != null && message.hasOwnProperty("Data")) + object.Data = options.bytes === String ? $util.base64.encode(message.Data, 0, message.Data.length) : options.bytes === Array ? Array.prototype.slice.call(message.Data) : message.Data; + if (message.ChainID != null && message.hasOwnProperty("ChainID")) + object.ChainID = options.bytes === String ? $util.base64.encode(message.ChainID, 0, message.ChainID.length) : options.bytes === Array ? Array.prototype.slice.call(message.ChainID) : message.ChainID; + if (message.Version != null && message.hasOwnProperty("Version")) + object.Version = message.Version; + if (message.Signature != null && message.hasOwnProperty("Signature")) + object.Signature = options.bytes === String ? $util.base64.encode(message.Signature, 0, message.Signature.length) : options.bytes === Array ? Array.prototype.slice.call(message.Signature) : message.Signature; + if (message.Options != null && message.hasOwnProperty("Options")) + object.Options = message.Options; + if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) + object.GuardianAddr = options.bytes === String ? $util.base64.encode(message.GuardianAddr, 0, message.GuardianAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianAddr) : message.GuardianAddr; + if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) + object.GuardianSignature = options.bytes === String ? $util.base64.encode(message.GuardianSignature, 0, message.GuardianSignature.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianSignature) : message.GuardianSignature; + return object; + }; + Transaction4.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + Transaction4.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === void 0) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/proto.Transaction"; + }; + return Transaction4; + }(); + return proto; + }(); + return $root; + }); + } +}); + +// node_modules/@multiversx/sdk-core/out/proto/serializer.js +var require_serializer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/proto/serializer.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ProtoSerializer = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber()); + var address_1 = require_address(); + var constants_1 = require_constants(); + var errors = __importStar2(require_errors()); + var utils_1 = require_utils(); + var ProtoSerializer = class { + /** + * Serializes a Transaction object to a Buffer. Handles low-level conversion logic and field-mappings as well. + */ + serializeTransaction(transaction) { + const proto = require_compiled().proto; + const receiverPubkey = new address_1.Address(transaction.getReceiver().bech32()).pubkey(); + const senderPubkey = new address_1.Address(transaction.getSender().bech32()).pubkey(); + let protoTransaction = new proto.Transaction({ + // mx-chain-go's serializer handles nonce == 0 differently, thus we treat 0 as "undefined". + Nonce: transaction.getNonce().valueOf() ? transaction.getNonce().valueOf() : void 0, + Value: this.serializeTransactionValue(transaction.getValue()), + RcvAddr: receiverPubkey, + RcvUserName: transaction.getReceiverUsername() ? import_buffer.Buffer.from(transaction.getReceiverUsername()).toString("base64") : void 0, + SndAddr: senderPubkey, + SndUserName: transaction.getSenderUsername() ? import_buffer.Buffer.from(transaction.getSenderUsername()).toString("base64") : void 0, + GasPrice: transaction.getGasPrice().valueOf(), + GasLimit: transaction.getGasLimit().valueOf(), + Data: transaction.getData().length() == 0 ? null : transaction.getData().valueOf(), + ChainID: import_buffer.Buffer.from(transaction.getChainID().valueOf()), + Version: transaction.getVersion().valueOf(), + Signature: transaction.getSignature() + }); + if (transaction.getOptions().valueOf() !== constants_1.TRANSACTION_OPTIONS_DEFAULT) { + protoTransaction.Options = transaction.getOptions().valueOf(); + } + if (transaction.isGuardedTransaction()) { + const guardianAddress = transaction.getGuardian(); + protoTransaction.GuardianAddr = new address_1.Address(guardianAddress.bech32()).pubkey(); + protoTransaction.GuardianSignature = transaction.getGuardianSignature(); + } + const encoded = proto.Transaction.encode(protoTransaction).finish(); + const buffer = import_buffer.Buffer.from(encoded); + return buffer; + } + /** + * Custom serialization, compatible with mx-chain-go. + */ + serializeTransactionValue(transactionValue) { + let value = new bignumber_js_1.default(transactionValue.toString()); + if (value.isZero()) { + return import_buffer.Buffer.from([0, 0]); + } + let buffer = utils_1.bigIntToBuffer(value); + buffer = import_buffer.Buffer.concat([import_buffer.Buffer.from([0]), buffer]); + return buffer; + } + deserializeTransaction(_buffer) { + throw new errors.ErrUnsupportedOperation("deserializeTransaction"); + } + }; + exports2.ProtoSerializer = ProtoSerializer; + } +}); + +// node_modules/@multiversx/sdk-core/out/proto/index.js +var require_proto = __commonJS({ + "node_modules/@multiversx/sdk-core/out/proto/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_serializer(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionComputer.js +var require_transactionComputer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionComputer.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionComputer = void 0; + var errors = __importStar2(require_errors()); + var bignumber_js_1 = __importDefault2(require_bignumber()); + var proto_1 = require_proto(); + var transaction_1 = require_transaction(); + var constants_1 = require_constants(); + var createTransactionHasher = require_blake2b2(); + var createKeccakHash = require_js(); + var TRANSACTION_HASH_LENGTH = 32; + var TransactionComputer2 = class { + constructor() { + } + computeTransactionFee(transaction, networkConfig2) { + const moveBalanceGas = BigInt(networkConfig2.MinGasLimit + transaction.data.length * networkConfig2.GasPerDataByte); + if (moveBalanceGas > transaction.gasLimit) { + throw new errors.ErrNotEnoughGas(parseInt(transaction.gasLimit.toString(), 10)); + } + const gasPrice = transaction.gasPrice; + const feeForMove = moveBalanceGas * gasPrice; + if (moveBalanceGas === transaction.gasLimit) { + return feeForMove; + } + const diff = transaction.gasLimit - moveBalanceGas; + const modifiedGasPrice = BigInt(new bignumber_js_1.default(gasPrice.toString()).multipliedBy(new bignumber_js_1.default(networkConfig2.GasPriceModifier)).toFixed(0)); + const processingFee = diff * modifiedGasPrice; + return feeForMove + processingFee; + } + computeBytesForSigning(transaction) { + this.ensureValidTransactionFields(transaction); + const plainTransaction = this.toPlainObjectForSigning(transaction); + const serialized = JSON.stringify(plainTransaction); + return new Uint8Array(import_buffer.Buffer.from(serialized)); + } + computeBytesForVerifying(transaction) { + const isTxSignedByHash = this.hasOptionsSetForHashSigning(transaction); + if (isTxSignedByHash) { + return this.computeHashForSigning(transaction); + } + return this.computeBytesForSigning(transaction); + } + computeHashForSigning(transaction) { + const plainTransaction = this.toPlainObjectForSigning(transaction); + const signable = import_buffer.Buffer.from(JSON.stringify(plainTransaction)); + return createKeccakHash("keccak256").update(signable).digest(); + } + computeTransactionHash(transaction) { + const serializer = new proto_1.ProtoSerializer(); + const buffer = serializer.serializeTransaction(new transaction_1.Transaction(transaction)); + const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); + return import_buffer.Buffer.from(hash, "hex"); + } + hasOptionsSetForGuardedTransaction(transaction) { + return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + } + hasOptionsSetForHashSigning(transaction) { + return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + applyGuardian(transaction, guardian) { + if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { + transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; + } + transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_GUARDED; + transaction.guardian = guardian; + } + applyOptionsForHashSigning(transaction) { + if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { + transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; + } + transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; + } + toPlainObjectForSigning(transaction) { + return { + nonce: Number(transaction.nonce), + value: transaction.value.toString(), + receiver: transaction.receiver, + sender: transaction.sender, + senderUsername: this.toBase64OrUndefined(transaction.senderUsername), + receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), + gasPrice: Number(transaction.gasPrice), + gasLimit: Number(transaction.gasLimit), + data: this.toBase64OrUndefined(transaction.data), + chainID: transaction.chainID, + version: transaction.version, + options: transaction.options ? transaction.options : void 0, + guardian: transaction.guardian ? transaction.guardian : void 0 + }; + } + toBase64OrUndefined(value) { + return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; + } + ensureValidTransactionFields(transaction) { + if (transaction.sender.length !== constants_1.BECH32_ADDRESS_LENGTH) { + throw new errors.ErrBadUsage("Invalid `sender` field. Should be the bech32 address of the sender."); + } + if (transaction.receiver.length !== constants_1.BECH32_ADDRESS_LENGTH) { + throw new errors.ErrBadUsage("Invalid `receiver` field. Should be the bech32 address of the receiver."); + } + if (!transaction.chainID.length) { + throw new errors.ErrBadUsage("The `chainID` field is not set"); + } + if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { + if (this.hasOptionsSetForGuardedTransaction(transaction) || this.hasOptionsSetForHashSigning(transaction)) { + throw new errors.ErrBadUsage(`Non-empty transaction options requires transaction version >= ${constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`); + } + } + } + }; + exports2.TransactionComputer = TransactionComputer2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transaction.js +var require_transaction = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transaction.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionHash = exports2.Transaction = void 0; + var bignumber_js_1 = require_bignumber(); + var address_1 = require_address(); + var constants_1 = require_constants(); + var transactionsConverter_1 = require_transactionsConverter(); + var hash_1 = require_hash(); + var networkParams_1 = require_networkParams(); + var signature_1 = require_signature(); + var transactionPayload_1 = require_transactionPayload(); + var transactionComputer_1 = require_transactionComputer(); + var Transaction4 = class { + /** + * Creates a new Transaction object. + */ + constructor(options) { + this.nonce = BigInt(options.nonce?.valueOf() || 0n); + this.value = options.value ? BigInt(new bignumber_js_1.BigNumber(options.value.toString()).toFixed(0)) : 0n; + this.sender = this.addressAsBech32(options.sender); + this.receiver = this.addressAsBech32(options.receiver); + this.senderUsername = options.senderUsername || ""; + this.receiverUsername = options.receiverUsername || ""; + this.gasPrice = BigInt(options.gasPrice?.valueOf() || constants_1.TRANSACTION_MIN_GAS_PRICE); + this.gasLimit = BigInt(options.gasLimit.valueOf()); + this.data = options.data?.valueOf() || new Uint8Array(); + this.chainID = options.chainID.valueOf(); + this.version = Number(options.version?.valueOf() || constants_1.TRANSACTION_VERSION_DEFAULT); + this.options = Number(options.options?.valueOf() || constants_1.TRANSACTION_OPTIONS_DEFAULT); + this.guardian = options.guardian ? this.addressAsBech32(options.guardian) : ""; + this.signature = options.signature || import_buffer.Buffer.from([]); + this.guardianSignature = options.guardianSignature || import_buffer.Buffer.from([]); + } + addressAsBech32(address) { + return typeof address === "string" ? address : address.bech32(); + } + /** + * Legacy method, use the "nonce" property instead. + */ + getNonce() { + return Number(this.nonce); + } + /** + * Legacy method, use the "nonce" property instead. + * Sets the account sequence number of the sender. Must be done prior signing. + */ + setNonce(nonce) { + this.nonce = BigInt(nonce.valueOf()); + } + /** + * Legacy method, use the "value" property instead. + */ + getValue() { + return this.value; + } + /** + * Legacy method, use the "value" property instead. + */ + setValue(value) { + this.value = BigInt(value.toString()); + } + /** + * Legacy method, use the "sender" property instead. + */ + getSender() { + return address_1.Address.fromBech32(this.sender); + } + /** + * Legacy method, use the "sender" property instead. + */ + setSender(sender) { + this.sender = typeof sender === "string" ? sender : sender.bech32(); + } + /** + * Legacy method, use the "receiver" property instead. + */ + getReceiver() { + return address_1.Address.fromBech32(this.receiver); + } + /** + * Legacy method, use the "senderUsername" property instead. + */ + getSenderUsername() { + return this.senderUsername; + } + /** + * Legacy method, use the "senderUsername" property instead. + */ + setSenderUsername(senderUsername) { + this.senderUsername = senderUsername; + } + /** + * Legacy method, use the "receiverUsername" property instead. + */ + getReceiverUsername() { + return this.receiverUsername; + } + /** + * Legacy method, use the "receiverUsername" property instead. + */ + setReceiverUsername(receiverUsername) { + this.receiverUsername = receiverUsername; + } + /** + * Legacy method, use the "guardian" property instead. + */ + getGuardian() { + return new address_1.Address(this.guardian); + } + /** + * Legacy method, use the "gasPrice" property instead. + */ + getGasPrice() { + return Number(this.gasPrice); + } + /** + * Legacy method, use the "gasPrice" property instead. + */ + setGasPrice(gasPrice) { + this.gasPrice = BigInt(gasPrice.valueOf()); + } + /** + * Legacy method, use the "gasLimit" property instead. + */ + getGasLimit() { + return Number(this.gasLimit); + } + /** + * Legacy method, use the "gasLimit" property instead. + */ + setGasLimit(gasLimit) { + this.gasLimit = BigInt(gasLimit.valueOf()); + } + /** + * Legacy method, use the "data" property instead. + */ + getData() { + return new transactionPayload_1.TransactionPayload(import_buffer.Buffer.from(this.data)); + } + /** + * Legacy method, use the "chainID" property instead. + */ + getChainID() { + return this.chainID; + } + /** + * Legacy method, use the "chainID" property instead. + */ + setChainID(chainID) { + this.chainID = chainID.valueOf(); + } + /** + * Legacy method, use the "version" property instead. + */ + getVersion() { + return new networkParams_1.TransactionVersion(this.version); + } + /** + * Legacy method, use the "version" property instead. + */ + setVersion(version2) { + this.version = version2.valueOf(); + } + /** + * Legacy method, use the "options" property instead. + */ + getOptions() { + return new networkParams_1.TransactionOptions(this.options.valueOf()); + } + /** + * Legacy method, use the "options" property instead. + * + * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. + */ + setOptions(options) { + this.options = options.valueOf(); + } + /** + * Legacy method, use the "signature" property instead. + */ + getSignature() { + return import_buffer.Buffer.from(this.signature); + } + /** + * Legacy method, use the "guardianSignature" property instead. + */ + getGuardianSignature() { + return import_buffer.Buffer.from(this.guardianSignature); + } + /** + * Legacy method, use the "guardian" property instead. + */ + setGuardian(guardian) { + this.guardian = typeof guardian === "string" ? guardian : guardian.bech32(); + } + /** + * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. + */ + getHash() { + return TransactionHash.compute(this); + } + /** + * Legacy method, use "TransactionComputer.computeBytesForSigning()" instead. + * Serializes a transaction to a sequence of bytes, ready to be signed. + * This function is called internally by signers. + */ + serializeForSigning() { + const computer = new transactionComputer_1.TransactionComputer(); + const bytes = computer.computeBytesForSigning(this); + return import_buffer.Buffer.from(bytes); + } + /** + * Checks the integrity of the guarded transaction + */ + isGuardedTransaction() { + const hasGuardian = this.guardian.length > 0; + const hasGuardianSignature = this.guardianSignature.length > 0; + return this.getOptions().isWithGuardian() && hasGuardian && hasGuardianSignature; + } + /** + * Legacy method, use "TransactionsConverter.transactionToPlainObject()" instead. + * + * Converts the transaction object into a ready-to-serialize, plain JavaScript object. + * This function is called internally within the signing procedure. + */ + toPlainObject() { + const converter = new transactionsConverter_1.TransactionsConverter(); + return converter.transactionToPlainObject(this); + } + /** + * Legacy method, use "TransactionsConverter.plainObjectToTransaction()" instead. + * Converts a plain object transaction into a Transaction Object. + * + * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() + */ + static fromPlainObject(plainObjectTransaction) { + const converter = new transactionsConverter_1.TransactionsConverter(); + return converter.plainObjectToTransaction(plainObjectTransaction); + } + /** + * Legacy method, use the "signature" property instead. + * Applies the signature on the transaction. + * + * @param signature The signature, as computed by a signer. + */ + applySignature(signature) { + this.signature = signature_1.interpretSignatureAsBuffer(signature); + } + /** + * Legacy method, use the "guardianSignature" property instead. + * Applies the guardian signature on the transaction. + * + * @param guardianSignature The signature, as computed by a signer. + */ + applyGuardianSignature(guardianSignature) { + this.guardianSignature = signature_1.interpretSignatureAsBuffer(guardianSignature); + } + /** + * Converts a transaction to a ready-to-broadcast object. + * Called internally by the network provider. + */ + toSendable() { + return this.toPlainObject(); + } + /** + * Legacy method, use "TransactionComputer.computeTransactionFee()" instead. + * + * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties + * @param networkConfig {@link NetworkConfig} + */ + computeFee(networkConfig2) { + const computer = new transactionComputer_1.TransactionComputer(); + const fee = computer.computeTransactionFee(this, networkConfig2); + return new bignumber_js_1.BigNumber(fee.toString()); + } + }; + exports2.Transaction = Transaction4; + var TransactionHash = class _TransactionHash extends hash_1.Hash { + constructor(hash) { + super(hash); + } + /** + * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. + * Computes the hash of a transaction. + */ + static compute(transaction) { + const computer = new transactionComputer_1.TransactionComputer(); + const hash = computer.computeTransactionHash(transaction); + return new _TransactionHash(import_buffer.Buffer.from(hash).toString("hex")); + } + }; + exports2.TransactionHash = TransactionHash; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js +var require_tokenOperationsFactory = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenOperationsFactory = void 0; + var constants_1 = require_constants(); + var logger_1 = require_logger(); + var networkParams_1 = require_networkParams(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var codec_1 = require_codec(); + var TokenOperationsFactory2 = class { + constructor(config) { + this.config = config; + this.trueAsHex = codec_1.utf8ToHex("true"); + this.falseAsHex = codec_1.utf8ToHex("false"); + } + issueFungible(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "issue", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.bigIntToHex(args.initialSupply), + codec_1.bigIntToHex(args.numDecimals), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + notifyAboutUnsettingBurnRoleGlobally() { + logger_1.Logger.info(` +========== +IMPORTANT! +========== +You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); + } + issueSemiFungible(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "issueSemiFungible", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canTransferNFTCreateRole"), + args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + issueNonFungible(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "issueNonFungible", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canTransferNFTCreateRole"), + args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + registerMetaESDT(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "registerMetaESDT", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.bigIntToHex(args.numDecimals), + codec_1.utf8ToHex("canFreeze"), + args.canFreeze ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canWipe"), + args.canWipe ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canPause"), + args.canPause ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canTransferNFTCreateRole"), + args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canChangeOwner"), + args.canChangeOwner ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canUpgrade"), + args.canUpgrade ? this.trueAsHex : this.falseAsHex, + codec_1.utf8ToHex("canAddSpecialRoles"), + args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + registerAndSetAllRoles(args) { + this.notifyAboutUnsettingBurnRoleGlobally(); + const parts = [ + "registerAndSetAllRoles", + codec_1.utf8ToHex(args.tokenName), + codec_1.utf8ToHex(args.tokenTicker), + codec_1.utf8ToHex(args.tokenType), + codec_1.bigIntToHex(args.numDecimals) + ]; + return this.createTransaction({ + sender: args.issuer, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + value: this.config.issueCost, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitIssue, + dataParts: parts + }); + } + setBurnRoleGlobally(args) { + const parts = ["setBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, + dataParts: parts + }); + } + unsetBurnRoleGlobally(args) { + const parts = ["unsetBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, + dataParts: parts + }); + } + setSpecialRoleOnFungible(args) { + const parts = [ + "setSpecialRole", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.addressToHex(args.user), + ...args.addRoleLocalMint ? [codec_1.utf8ToHex("ESDTRoleLocalMint")] : [], + ...args.addRoleLocalBurn ? [codec_1.utf8ToHex("ESDTRoleLocalBurn")] : [] + ]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitSetSpecialRole, + dataParts: parts + }); + } + setSpecialRoleOnSemiFungible(args) { + const parts = [ + "setSpecialRole", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.addressToHex(args.user), + ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], + ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], + ...args.addRoleNFTAddQuantity ? [codec_1.utf8ToHex("ESDTRoleNFTAddQuantity")] : [], + ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] + ]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitSetSpecialRole, + dataParts: parts + }); + } + setSpecialRoleOnMetaESDT(args) { + return this.setSpecialRoleOnSemiFungible(args); + } + setSpecialRoleOnNonFungible(args) { + const parts = [ + "setSpecialRole", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.addressToHex(args.user), + ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], + ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], + ...args.addRoleNFTUpdateAttributes ? [codec_1.utf8ToHex("ESDTRoleNFTUpdateAttributes")] : [], + ...args.addRoleNFTAddURI ? [codec_1.utf8ToHex("ESDTRoleNFTAddURI")] : [], + ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] + ]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitSetSpecialRole, + dataParts: parts + }); + } + nftCreate(args) { + const parts = [ + "ESDTNFTCreate", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.initialQuantity), + codec_1.utf8ToHex(args.name), + codec_1.bigIntToHex(args.royalties), + codec_1.utf8ToHex(args.hash), + codec_1.bufferToHex(args.attributes), + ...args.uris.map(codec_1.utf8ToHex) + ]; + const nftData = args.name + args.hash + args.attributes + args.uris.join(""); + const storageGasLimit = nftData.length * this.config.gasLimitStorePerByte.valueOf(); + return this.createTransaction({ + sender: args.creator, + receiver: args.creator, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTCreate.valueOf() + storageGasLimit.valueOf(), + dataParts: parts + }); + } + pause(args) { + const parts = ["pause", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitPausing, + dataParts: parts + }); + } + unpause(args) { + const parts = ["unPause", codec_1.utf8ToHex(args.tokenIdentifier)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitPausing, + dataParts: parts + }); + } + freeze(args) { + const parts = ["freeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitFreezing, + dataParts: parts + }); + } + unfreeze(args) { + const parts = ["unFreeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitFreezing, + dataParts: parts + }); + } + wipe(args) { + const parts = ["wipe", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; + return this.createTransaction({ + sender: args.manager, + receiver: this.config.esdtContractAddress, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitWiping, + dataParts: parts + }); + } + localMint(args) { + const parts = ["ESDTLocalMint", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToMint)]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTLocalMint, + dataParts: parts + }); + } + localBurn(args) { + const parts = ["ESDTLocalBurn", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToBurn)]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTLocalBurn, + dataParts: parts + }); + } + updateAttributes(args) { + const parts = [ + "ESDTNFTUpdateAttributes", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.tokenNonce), + codec_1.bufferToHex(args.attributes) + ]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTUpdateAttributes, + dataParts: parts + }); + } + addQuantity(args) { + const parts = [ + "ESDTNFTAddQuantity", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.tokenNonce), + codec_1.bigIntToHex(args.quantityToAdd) + ]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTAddQuantity, + dataParts: parts + }); + } + burnQuantity(args) { + const parts = [ + "ESDTNFTBurn", + codec_1.utf8ToHex(args.tokenIdentifier), + codec_1.bigIntToHex(args.tokenNonce), + codec_1.bigIntToHex(args.quantityToBurn) + ]; + return this.createTransaction({ + sender: args.manager, + receiver: args.manager, + nonce: args.transactionNonce, + gasPrice: args.gasPrice, + gasLimitHint: args.gasLimit, + executionGasLimit: this.config.gasLimitESDTNFTBurn, + dataParts: parts + }); + } + createTransaction({ sender, receiver, nonce, value, gasPrice, gasLimitHint, executionGasLimit, dataParts }) { + const payload = this.buildTransactionPayload(dataParts); + const gasLimit = gasLimitHint || this.computeGasLimit(payload, executionGasLimit); + const version2 = new networkParams_1.TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); + const options = new networkParams_1.TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); + return new transaction_1.Transaction({ + chainID: this.config.chainID, + sender, + receiver, + gasLimit, + gasPrice, + nonce: nonce || 0, + value: value || 0, + data: payload, + version: version2, + options + }); + } + buildTransactionPayload(parts) { + const data = parts.join(constants_1.ARGUMENTS_SEPARATOR); + return new transactionPayload_1.TransactionPayload(data); + } + computeGasLimit(payload, executionGas) { + const dataMovementGas = this.config.minGasLimit.valueOf() + this.config.gasLimitPerByte.valueOf() * payload.length(); + return dataMovementGas + executionGas.valueOf(); + } + }; + exports2.TokenOperationsFactory = TokenOperationsFactory2; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js +var require_tokenOperationsFactoryConfig = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenOperationsFactoryConfig = void 0; + var address_1 = require_address(); + var TokenOperationsFactoryConfig2 = class { + constructor(chainID) { + this.minGasPrice = 1e9; + this.minGasLimit = 5e4; + this.gasLimitPerByte = 1500; + this.gasLimitIssue = 6e7; + this.gasLimitToggleBurnRoleGlobally = 6e7; + this.gasLimitESDTLocalMint = 3e5; + this.gasLimitESDTLocalBurn = 3e5; + this.gasLimitSetSpecialRole = 6e7; + this.gasLimitPausing = 6e7; + this.gasLimitFreezing = 6e7; + this.gasLimitWiping = 6e7; + this.gasLimitESDTNFTCreate = 3e6; + this.gasLimitESDTNFTUpdateAttributes = 1e6; + this.gasLimitESDTNFTAddQuantity = 1e6; + this.gasLimitESDTNFTBurn = 1e6; + this.gasLimitStorePerByte = 5e4; + this.issueCost = "50000000000000000"; + this.esdtContractAddress = address_1.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); + this.chainID = chainID; + } + }; + exports2.TokenOperationsFactoryConfig = TokenOperationsFactoryConfig2; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js +var require_tokenOperationsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenOperationsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var codec_1 = require_codec(); + var TokenOperationsOutcomeParser2 = class { + parseIssueFungible(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "issue"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseIssueNonFungible(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "issueNonFungible"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseIssueSemiFungible(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "issueSemiFungible"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseRegisterMetaESDT(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "registerMetaESDT"); + const tokenIdentifier = this.extractTokenIdentifier(event); + return { tokenIdentifier }; + } + parseRegisterAndSetAllRoles(transaction) { + this.ensureNoError(transaction); + const eventRegister = this.findSingleEventByIdentifier(transaction, "registerAndSetAllRoles"); + const tokenIdentifier = this.extractTokenIdentifier(eventRegister); + const eventSetRole = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); + const roles = eventSetRole.topics.slice(3).map((topic) => topic.valueOf().toString()); + return { tokenIdentifier, roles }; + } + parseSetBurnRoleGlobally(transaction) { + this.ensureNoError(transaction); + return {}; + } + parseUnsetBurnRoleGlobally(transaction) { + this.ensureNoError(transaction); + return {}; + } + parseSetSpecialRole(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); + const userAddress = event.address.toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const roles = event.topics.slice(3).map((topic) => topic.valueOf().toString()); + return { userAddress, tokenIdentifier, roles }; + } + parseNFTCreate(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTCreate"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const initialQuantity = this.extractAmount(event); + return { tokenIdentifier, nonce, initialQuantity }; + } + parseLocalMint(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalMint"); + const userAddress = event.address.toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const mintedSupply = this.extractAmount(event); + return { userAddress, tokenIdentifier, nonce, mintedSupply }; + } + parseLocalBurn(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalBurn"); + const userAddress = event.address.toString(); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntSupply = this.extractAmount(event); + return { userAddress, tokenIdentifier, nonce, burntSupply }; + } + parsePause(transaction) { + this.ensureNoError(transaction); + const _4 = this.findSingleEventByIdentifier(transaction, "ESDTPause"); + return {}; + } + parseUnpause(transaction) { + this.ensureNoError(transaction); + const _4 = this.findSingleEventByIdentifier(transaction, "ESDTUnPause"); + return {}; + } + parseFreeze(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTFreeze"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + const userAddress = this.extractAddress(event); + return { userAddress, tokenIdentifier, nonce, balance }; + } + parseUnfreeze(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTUnFreeze"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + const userAddress = this.extractAddress(event); + return { userAddress, tokenIdentifier, nonce, balance }; + } + parseWipe(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTWipe"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + const userAddress = this.extractAddress(event); + return { userAddress, tokenIdentifier, nonce, balance }; + } + parseUpdateAttributes(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTUpdateAttributes"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const attributes = event.topics[3]?.valueOf(); + return { tokenIdentifier, nonce, attributes }; + } + parseAddQuantity(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTAddQuantity"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const addedQuantity = this.extractAmount(event); + return { tokenIdentifier, nonce, addedQuantity }; + } + parseBurnQuantity(transaction) { + this.ensureNoError(transaction); + const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTBurn"); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntQuantity = this.extractAmount(event); + return { tokenIdentifier, nonce, burntQuantity }; + } + ensureNoError(transaction) { + for (const event of transaction.logs.events) { + if (event.identifier == "signalError") { + const data = import_buffer.Buffer.from(event.data.substring(1), "hex").toString(); + const message = event.topics[1]?.valueOf().toString(); + throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `encountered signalError: ${message} (${data})`); + } + } + } + findSingleEventByIdentifier(transaction, identifier) { + const events = this.gatherAllEvents(transaction).filter((event) => event.identifier == identifier); + if (events.length == 0) { + throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `cannot find event of type ${identifier}`); + } + if (events.length > 1) { + throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `more than one event of type ${identifier}`); + } + return events[0]; + } + gatherAllEvents(transaction) { + const allEvents = []; + allEvents.push(...transaction.logs.events); + for (const item of transaction.contractResults.items) { + allEvents.push(...item.logs.events); + } + return allEvents; + } + extractTokenIdentifier(event) { + return event.topics[0]?.valueOf().toString(); + } + extractNonce(event) { + return codec_1.bufferToBigInt(event.topics[1]?.valueOf()).toFixed(0); + } + extractAmount(event) { + return codec_1.bufferToBigInt(event.topics[2]?.valueOf()).toFixed(0); + } + extractAddress(event) { + return address_1.Address.fromBuffer(event.topics[3]?.valueOf()).toString(); + } + }; + exports2.TokenOperationsOutcomeParser = TokenOperationsOutcomeParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/tokenOperations/index.js +var require_tokenOperations = __commonJS({ + "node_modules/@multiversx/sdk-core/out/tokenOperations/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_tokenOperationsFactory(), exports2); + __exportStar2(require_tokenOperationsFactoryConfig(), exports2); + __exportStar2(require_tokenOperationsOutcomeParser(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js +var require_delegationTransactionsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.DelegationTransactionsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var resources_1 = require_resources(); + var DelegationTransactionsOutcomeParser = class { + constructor() { + } + parseCreateNewDelegationContract(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "SCDeploy"); + return events.map((event) => ({ contractAddress: this.extractContractAddress(event) })); + } + ensureNoError(transactionEvents) { + for (const event of transactionEvents) { + if (event.identifier == "signalError") { + const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; + const message = this.decodeTopicAsString(event.topics[1]); + throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); + } + } + } + extractContractAddress(event) { + if (!event.topics[0]?.length) { + return ""; + } + const address = import_buffer.Buffer.from(event.topics[0]); + return address_1.Address.fromBuffer(address).bech32(); + } + decodeTopicAsString(topic) { + return import_buffer.Buffer.from(topic).toString(); + } + }; + exports2.DelegationTransactionsOutcomeParser = DelegationTransactionsOutcomeParser; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js +var require_smartContractTransactionsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractTransactionsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var resources_1 = require_resources(); + var SmartContractTransactionsOutcomeParser2 = class { + constructor(options) { + this.abi = options?.abi; + this.legacyResultsParser = options?.legacyResultsParser || new smartcontracts_1.ResultsParser(); + } + parseDeploy(options) { + const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; + const events = resources_1.findEventsByIdentifier(options.transactionOutcome, "SCDeploy"); + const contracts = events.map((event) => this.parseScDeployEvent(event)); + return { + returnCode: directCallOutcome.returnCode, + returnMessage: directCallOutcome.returnMessage, + contracts + }; + } + parseScDeployEvent(event) { + const topicForAddress = event.topics[0]; + const topicForOwnerAddress = event.topics[1]; + const topicForCodeHash = event.topics[2]; + const address = topicForAddress?.length ? new address_1.Address(topicForAddress).toBech32() : ""; + const ownerAddress = topicForOwnerAddress?.length ? new address_1.Address(topicForOwnerAddress).toBech32() : ""; + const codeHash = topicForCodeHash; + return { + address, + ownerAddress, + codeHash + }; + } + parseExecute(options) { + const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; + if (!this.abi) { + return { + values: directCallOutcome.returnDataParts, + returnCode: directCallOutcome.returnCode, + returnMessage: directCallOutcome.returnMessage + }; + } + const functionName = options.function || directCallOutcome.function; + if (!functionName) { + throw new errors_1.Err(`Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?`); + } + const endpoint = this.abi.getEndpoint(functionName); + const legacyUntypedBundle = { + returnCode: new smartcontracts_1.ReturnCode(directCallOutcome.returnCode), + returnMessage: directCallOutcome.returnMessage, + values: directCallOutcome.returnDataParts.map((part) => import_buffer.Buffer.from(part)) + }; + const legacyTypedBundle = this.legacyResultsParser.parseOutcomeFromUntypedBundle(legacyUntypedBundle, endpoint); + return { + values: legacyTypedBundle.values.map((value) => value.valueOf()), + returnCode: legacyTypedBundle.returnCode.toString(), + returnMessage: legacyTypedBundle.returnMessage + }; + } + }; + exports2.SmartContractTransactionsOutcomeParser = SmartContractTransactionsOutcomeParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js +var require_tokenManagementTransactionsOutcomeParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TokenManagementTransactionsOutcomeParser = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var utils_1 = require_utils(); + var resources_1 = require_resources(); + var TokenManagementTransactionsOutcomeParser2 = class { + constructor() { + } + parseIssueFungible(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "issue"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseIssueNonFungible(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueNonFungible"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseIssueSemiFungible(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueSemiFungible"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseRegisterMetaEsdt(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "registerMetaESDT"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseRegisterAndSetAllRoles(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const registerEvents = resources_1.findEventsByIdentifier(transactionOutcome, "registerAndSetAllRoles"); + const setRoleEvents = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); + if (registerEvents.length !== setRoleEvents.length) { + throw new errors_1.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events."); + } + return registerEvents.map((registerEvent, index) => { + const tokenIdentifier = this.extractTokenIdentifier(registerEvent); + const encodedRoles = setRoleEvents[index].topics.slice(3); + const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); + return { tokenIdentifier, roles }; + }); + } + parseSetBurnRoleGlobally(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + } + parseUnsetBurnRoleGlobally(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + } + parseSetSpecialRole(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); + return events.map((event) => this.getOutputForSetSpecialRoleEvent(event)); + } + getOutputForSetSpecialRoleEvent(event) { + const userAddress = event.address; + const tokenIdentifier = this.extractTokenIdentifier(event); + const encodedRoles = event.topics.slice(3); + const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); + return { userAddress, tokenIdentifier, roles }; + } + parseNftCreate(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTCreate"); + return events.map((event) => this.getOutputForNftCreateEvent(event)); + } + getOutputForNftCreateEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const amount = this.extractAmount(event); + return { tokenIdentifier, nonce, initialQuantity: amount }; + } + parseLocalMint(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalMint"); + return events.map((event) => this.getOutputForLocalMintEvent(event)); + } + getOutputForLocalMintEvent(event) { + const userAddress = event.address; + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const mintedSupply = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + mintedSupply + }; + } + parseLocalBurn(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalBurn"); + return events.map((event) => this.getOutputForLocalBurnEvent(event)); + } + getOutputForLocalBurnEvent(event) { + const userAddress = event.address; + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntSupply = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + burntSupply + }; + } + parsePause(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTPause"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseUnpause(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnPause"); + return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); + } + parseFreeze(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTFreeze"); + return events.map((event) => this.getOutputForFreezeEvent(event)); + } + getOutputForFreezeEvent(event) { + const userAddress = this.extractAddress(event); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + balance + }; + } + parseUnfreeze(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnFreeze"); + return events.map((event) => this.getOutputForUnfreezeEvent(event)); + } + getOutputForUnfreezeEvent(event) { + const userAddress = this.extractAddress(event); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + balance + }; + } + parseWipe(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTWipe"); + return events.map((event) => this.getOutputForWipeEvent(event)); + } + getOutputForWipeEvent(event) { + const userAddress = this.extractAddress(event); + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const balance = this.extractAmount(event); + return { + userAddress, + tokenIdentifier, + nonce, + balance + }; + } + parseUpdateAttributes(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTUpdateAttributes"); + return events.map((event) => this.getOutputForUpdateAttributesEvent(event)); + } + getOutputForUpdateAttributesEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const attributes = event.topics[3] ? event.topics[3] : new Uint8Array(); + return { + tokenIdentifier, + nonce, + attributes + }; + } + parseAddQuantity(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTAddQuantity"); + return events.map((event) => this.getOutputForAddQuantityEvent(event)); + } + getOutputForAddQuantityEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const addedQuantity = this.extractAmount(event); + return { + tokenIdentifier, + nonce, + addedQuantity + }; + } + parseBurnQuantity(transactionOutcome) { + this.ensureNoError(transactionOutcome.logs.events); + const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTBurn"); + return events.map((event) => this.getOutputForBurnQuantityEvent(event)); + } + getOutputForBurnQuantityEvent(event) { + const tokenIdentifier = this.extractTokenIdentifier(event); + const nonce = this.extractNonce(event); + const burntQuantity = this.extractAmount(event); + return { + tokenIdentifier, + nonce, + burntQuantity + }; + } + ensureNoError(transactionEvents) { + for (const event of transactionEvents) { + if (event.identifier == "signalError") { + const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; + const message = this.decodeTopicAsString(event.topics[1]); + throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); + } + } + } + extractTokenIdentifier(event) { + if (!event.topics[0]?.length) { + return ""; + } + return this.decodeTopicAsString(event.topics[0]); + } + extractNonce(event) { + if (!event.topics[1]?.length) { + return BigInt(0); + } + const nonce = import_buffer.Buffer.from(event.topics[1]); + return BigInt(utils_1.bufferToBigInt(nonce).toFixed(0)); + } + extractAmount(event) { + if (!event.topics[2]?.length) { + return BigInt(0); + } + const amount = import_buffer.Buffer.from(event.topics[2]); + return BigInt(utils_1.bufferToBigInt(amount).toFixed(0)); + } + extractAddress(event) { + if (!event.topics[3]?.length) { + return ""; + } + const address = import_buffer.Buffer.from(event.topics[3]); + return address_1.Address.fromBuffer(address).bech32(); + } + decodeTopicAsString(topic) { + return import_buffer.Buffer.from(topic).toString(); + } + }; + exports2.TokenManagementTransactionsOutcomeParser = TokenManagementTransactionsOutcomeParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js +var require_transactionEventsParser = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionEventsParser = void 0; + var smartcontracts_1 = require_smartcontracts(); + var TransactionEventsParser2 = class { + constructor(options) { + this.legacyResultsParser = new smartcontracts_1.ResultsParser(); + this.abi = options.abi; + this.firstTopicIsIdentifier = options.firstTopicIsIdentifier ?? true; + } + parseEvents(options) { + const results = []; + for (const event of options.events) { + const parsedEvent = this.parseEvent({ event }); + results.push(parsedEvent); + } + return results; + } + parseEvent(options) { + const topics = options.event.topics.map((topic) => import_buffer.Buffer.from(topic)); + const abiIdentifier = this.firstTopicIsIdentifier ? topics[0]?.toString() : options.event.identifier; + if (this.firstTopicIsIdentifier) { + topics.shift(); + } + const dataItems = options.event.dataItems.map((dataItem) => import_buffer.Buffer.from(dataItem)); + const eventDefinition = this.abi.getEvent(abiIdentifier); + const parsedEvent = this.legacyResultsParser.doParseEvent({ + topics, + dataItems, + eventDefinition + }); + return parsedEvent; + } + }; + exports2.TransactionEventsParser = TransactionEventsParser2; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js +var require_transactionsOutcomeParsers = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_delegationTransactionsOutcomeParser(), exports2); + __exportStar2(require_resources(), exports2); + __exportStar2(require_smartContractTransactionsOutcomeParser(), exports2); + __exportStar2(require_tokenManagementTransactionsOutcomeParser(), exports2); + __exportStar2(require_transactionEventsParser(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/account.js +var require_account = __commonJS({ + "node_modules/@multiversx/sdk-core/out/account.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Account = void 0; + var address_1 = require_address(); + var Account5 = class { + /** + * Creates an account object from an address + */ + constructor(address) { + this.address = address_1.Address.empty(); + this.nonce = 0; + this.balance = "0"; + this.address = address; + } + /** + * Updates account properties (such as nonce, balance). + */ + update(obj) { + this.nonce = obj.nonce; + this.balance = obj.balance; + } + /** + * Increments (locally) the nonce (the account sequence number). + */ + incrementNonce() { + this.nonce = this.nonce.valueOf() + 1; + } + /** + * Gets then increments (locally) the nonce (the account sequence number). + */ + getNonceThenIncrement() { + let nonce = this.nonce; + this.nonce = this.nonce.valueOf() + 1; + return nonce; + } + /** + * Converts the account to a pretty, plain JavaScript object. + */ + toJSON() { + return { + address: this.address.bech32(), + nonce: this.nonce.valueOf(), + balance: this.balance.toString() + }; + } + }; + exports2.Account = Account5; + } +}); + +// node_modules/@multiversx/sdk-core/out/message.js +var require_message = __commonJS({ + "node_modules/@multiversx/sdk-core/out/message.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.MessageComputer = exports2.Message = void 0; + var constants_1 = require_constants(); + var address_1 = require_address(); + var createKeccakHash = require_js(); + var Message2 = class { + constructor(options) { + this.data = options.data; + this.signature = options.signature; + this.address = options.address; + this.version = options.version || constants_1.DEFAULT_MESSAGE_VERSION; + this.signer = options.signer || constants_1.SDK_JS_SIGNER; + } + }; + exports2.Message = Message2; + var MessageComputer2 = class { + constructor() { + } + computeBytesForSigning(message) { + const messageSize = import_buffer.Buffer.from(message.data.length.toString()); + const signableMessage = import_buffer.Buffer.concat([messageSize, message.data]); + let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); + return createKeccakHash("keccak256").update(bytesToHash).digest(); + } + computeBytesForVerifying(message) { + return this.computeBytesForSigning(message); + } + packMessage(message) { + return { + message: import_buffer.Buffer.from(message.data).toString("hex"), + signature: message.signature ? import_buffer.Buffer.from(message.signature).toString("hex") : "", + address: message.address ? message.address.bech32() : "", + version: message.version, + signer: message.signer + }; + } + unpackMessage(packedMessage) { + const dataHex = this.trimHexPrefix(packedMessage.message); + const data = import_buffer.Buffer.from(dataHex, "hex"); + const signatureHex = this.trimHexPrefix(packedMessage.signature || ""); + const signature = import_buffer.Buffer.from(signatureHex, "hex"); + let address = void 0; + if (packedMessage.address) { + address = address_1.Address.fromBech32(packedMessage.address); + } + const version2 = packedMessage.version || constants_1.DEFAULT_MESSAGE_VERSION; + const signer = packedMessage.signer || constants_1.UNKNOWN_SIGNER; + return new Message2({ + data, + signature, + address, + version: version2, + signer + }); + } + trimHexPrefix(data) { + if (data.startsWith("0x") || data.startsWith("0X")) { + return data.slice(2); + } + return data; + } + }; + exports2.MessageComputer = MessageComputer2; + } +}); + +// node_modules/@multiversx/sdk-core/out/asyncTimer.js +var require_asyncTimer = __commonJS({ + "node_modules/@multiversx/sdk-core/out/asyncTimer.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.AsyncTimer = void 0; + var errors = __importStar2(require_errors()); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var AsyncTimer = class { + /** + * Creates an AsyncTimer. + */ + constructor(name2) { + this.timeoutHandle = null; + this.rejectionFunc = null; + this.name = name2; + this.correlationTag = 0; + } + /** + * Starts the timer. + * @param timeout The time (in milliseconds) to wait until resolving the promise. + */ + start(timeout) { + if (this.timeoutHandle) { + throw new errors.ErrAsyncTimerAlreadyRunning(); + } + this.correlationTag++; + logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`); + return new Promise((resolve, reject) => { + this.rejectionFunc = reject; + let timeoutCallback = () => { + this.rejectionFunc = null; + this.stop(); + resolve(); + }; + this.timeoutHandle = setTimeout(timeoutCallback, timeout); + }); + } + /** + * Aborts the timer: rejects the promise (if any) and stops the timer. + */ + abort() { + logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`); + if (this.rejectionFunc) { + this.rejectionFunc(new errors_1.ErrAsyncTimerAborted()); + this.rejectionFunc = null; + } + this.stop(); + } + /** + * Stops the timer. + */ + stop() { + if (this.isStopped()) { + return; + } + logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`); + if (this.timeoutHandle) { + clearTimeout(this.timeoutHandle); + this.timeoutHandle = null; + } + } + /** + * Returns whether the timer is stopped. + */ + isStopped() { + return this.timeoutHandle ? false : true; + } + }; + exports2.AsyncTimer = AsyncTimer; + } +}); + +// node_modules/@multiversx/sdk-core/out/transactionWatcher.js +var require_transactionWatcher = __commonJS({ + "node_modules/@multiversx/sdk-core/out/transactionWatcher.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionWatcher = void 0; + var asyncTimer_1 = require_asyncTimer(); + var constants_1 = require_constants(); + var errors_1 = require_errors(); + var logger_1 = require_logger(); + var TransactionWatcher3 = class _TransactionWatcher { + /** + * A transaction watcher (awaiter). + * + * @param fetcher The transaction fetcher + * @param options The options + * @param options.pollingIntervalMilliseconds The polling interval, in milliseconds + * @param options.timeoutMilliseconds The timeout, in milliseconds + * @param options.patienceMilliseconds The patience: an extra time (in milliseconds) to wait, after the transaction has reached its desired status. Currently there's a delay between the moment a transaction is marked as "completed" and the moment its outcome (contract results, events and logs) is available. + */ + constructor(fetcher, options = {}) { + this.fetcher = new TransactionFetcherWithTracing(fetcher); + this.pollingIntervalMilliseconds = options.pollingIntervalMilliseconds || _TransactionWatcher.DefaultPollingInterval; + this.timeoutMilliseconds = options.timeoutMilliseconds || _TransactionWatcher.DefaultTimeout; + this.patienceMilliseconds = options.patienceMilliseconds || _TransactionWatcher.DefaultPatience; + } + /** + * Waits until the transaction reaches the "pending" status. + * @param txHash The hex-encoded transaction hash + */ + async awaitPending(transactionOrTxHash) { + const isPending = (transaction) => transaction.status.isPending(); + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); + return this.awaitConditionally(isPending, doFetch, errorProvider); + } + /** + * Waits until the transaction is completely processed. + * @param txHash The hex-encoded transaction hash + */ + async awaitCompleted(transactionOrTxHash) { + const isCompleted = (transactionOnNetwork) => { + if (transactionOnNetwork.isCompleted === void 0) { + throw new errors_1.ErrIsCompletedFieldIsMissingOnTransaction(); + } + return transactionOnNetwork.isCompleted; + }; + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); + return this.awaitConditionally(isCompleted, doFetch, errorProvider); + } + async awaitAllEvents(transactionOrTxHash, events) { + const foundAllEvents = (transactionOnNetwork) => { + const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); + const allAreFound = events.every((event) => allEventIdentifiers.includes(event)); + return allAreFound; + }; + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); + return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); + } + async awaitAnyEvent(transactionOrTxHash, events) { + const foundAnyEvent = (transactionOnNetwork) => { + const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); + const anyIsFound = events.find((event) => allEventIdentifiers.includes(event)) != void 0; + return anyIsFound; + }; + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); + return this.awaitConditionally(foundAnyEvent, doFetch, errorProvider); + } + async awaitOnCondition(transactionOrTxHash, condition) { + const doFetch = async () => { + const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); + return await this.fetcher.getTransaction(hash); + }; + const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); + return this.awaitConditionally(condition, doFetch, errorProvider); + } + transactionOrTxHashToTxHash(transactionOrTxHash) { + const hash = typeof transactionOrTxHash === "string" ? transactionOrTxHash : transactionOrTxHash.getHash().hex(); + if (hash.length !== constants_1.HEX_TRANSACTION_HASH_LENGTH) { + throw new errors_1.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${constants_1.HEX_TRANSACTION_HASH_LENGTH}.`); + } + return hash; + } + async awaitConditionally(isSatisfied, doFetch, createError) { + const periodicTimer = new asyncTimer_1.AsyncTimer("watcher:periodic"); + const patienceTimer = new asyncTimer_1.AsyncTimer("watcher:patience"); + const timeoutTimer = new asyncTimer_1.AsyncTimer("watcher:timeout"); + let stop = false; + let fetchedData = void 0; + let satisfied = false; + timeoutTimer.start(this.timeoutMilliseconds).finally(() => { + timeoutTimer.stop(); + stop = true; + }); + while (!stop) { + await periodicTimer.start(this.pollingIntervalMilliseconds); + try { + fetchedData = await doFetch(); + satisfied = isSatisfied(fetchedData); + if (satisfied || stop) { + break; + } + } catch (error) { + logger_1.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."); + if (error instanceof errors_1.ErrIsCompletedFieldIsMissingOnTransaction) { + throw error; + } + if (!(error instanceof errors_1.Err)) { + throw error; + } + } + } + if (satisfied) { + await patienceTimer.start(this.patienceMilliseconds); + } + if (!timeoutTimer.isStopped()) { + timeoutTimer.stop(); + } + if (!fetchedData || !satisfied) { + throw createError(); + } + return fetchedData; + } + getAllTransactionEvents(transaction) { + const result = [...transaction.logs.events]; + for (const resultItem of transaction.contractResults.items) { + result.push(...resultItem.logs.events); + } + return result; + } + }; + exports2.TransactionWatcher = TransactionWatcher3; + TransactionWatcher3.DefaultPollingInterval = 6e3; + TransactionWatcher3.DefaultTimeout = TransactionWatcher3.DefaultPollingInterval * 15; + TransactionWatcher3.DefaultPatience = 0; + TransactionWatcher3.NoopOnStatusReceived = (_4) => { + }; + var TransactionFetcherWithTracing = class { + constructor(fetcher) { + this.fetcher = fetcher; + } + async getTransaction(txHash) { + logger_1.Logger.debug(`transactionWatcher, getTransaction(${txHash})`); + return await this.fetcher.getTransaction(txHash); + } + }; + } +}); + +// node_modules/@multiversx/sdk-core/out/signableMessage.js +var require_signableMessage = __commonJS({ + "node_modules/@multiversx/sdk-core/out/signableMessage.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SignableMessage = void 0; + var address_1 = require_address(); + var signature_1 = require_signature(); + var constants_1 = require_constants(); + var createKeccakHash = require_js(); + var SignableMessage3 = class { + constructor(init) { + this.message = import_buffer.Buffer.from([]); + this.signature = import_buffer.Buffer.from([]); + this.version = 1; + this.signer = "ErdJS"; + this.address = address_1.Address.empty(); + Object.assign(this, init); + } + serializeForSigning() { + const messageSize = import_buffer.Buffer.from(this.message.length.toString()); + const signableMessage = import_buffer.Buffer.concat([messageSize, this.message]); + let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); + return createKeccakHash("keccak256").update(bytesToHash).digest(); + } + serializeForSigningRaw() { + return import_buffer.Buffer.concat([this.getMessageSize(), this.message]); + } + getSignature() { + return this.signature; + } + applySignature(signature) { + this.signature = signature_1.interpretSignatureAsBuffer(signature); + } + getMessageSize() { + const messageSize = import_buffer.Buffer.alloc(4); + messageSize.writeUInt32BE(this.message.length, 0); + return messageSize; + } + toJSON() { + return { + address: this.address.bech32(), + message: "0x" + this.message.toString("hex"), + signature: "0x" + this.signature.toString("hex"), + version: this.version, + signer: this.signer + }; + } + }; + exports2.SignableMessage = SignableMessage3; + } +}); + +// node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js +var require_bignumber2 = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js"(exports2, module2) { + init_shim(); + (function(globalObject) { + "use strict"; + var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; + function clone2(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + function BigNumber3(v2, b4) { + var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber3)) + return new BigNumber3(v2, b4); + if (b4 == null) { + if (v2 && v2._isBigNumber === true) { + x3.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v2.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v2.e; + x3.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric2.test(str = String(v2))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i2 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i2; + e2 += +str.slice(i2 + 1); + str = str.substring(0, i2); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + if (b4 == 10) { + x3 = new BigNumber3(v2); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric(x3, str, isNum, b4); + x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits2 + v2); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet2 = ALPHABET.slice(0, b4); + e2 = i2 = 0; + for (len = str.length; i2 < len; i2++) { + if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { + if (c4 == ".") { + if (i2 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i2 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v2), isNum, b4); + } + } + isNum = false; + str = convertBase(str, b4, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i2 = 0; str.charCodeAt(i2) === 48; i2++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i2, ++len)) { + len -= i2; + if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { + throw Error(tooManyDigits2 + x3.s * v2); + } + if ((e2 = e2 - i2 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i2 = (e2 + 1) % LOG_BASE2; + if (e2 < 0) + i2 += LOG_BASE2; + if (i2 < len) { + if (i2) + x3.c.push(+str.slice(0, i2)); + for (len -= LOG_BASE2; i2 < len; ) { + x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); + } + i2 = LOG_BASE2 - (str = str.slice(i2)).length; + } else { + i2 -= len; + } + for (; i2--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber3.clone = clone2; + BigNumber3.ROUND_UP = 0; + BigNumber3.ROUND_DOWN = 1; + BigNumber3.ROUND_CEIL = 2; + BigNumber3.ROUND_FLOOR = 3; + BigNumber3.ROUND_HALF_UP = 4; + BigNumber3.ROUND_HALF_DOWN = 5; + BigNumber3.ROUND_HALF_EVEN = 6; + BigNumber3.ROUND_HALF_CEIL = 7; + BigNumber3.ROUND_HALF_FLOOR = 8; + BigNumber3.EUCLID = 9; + BigNumber3.config = BigNumber3.set = function(obj) { + var p3, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 8, p3); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, 0, p3); + intCheck2(v2[1], 0, MAX2, p3); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p3 = "RANGE")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck2(v2[0], -MAX2, -1, p3); + intCheck2(v2[1], 1, MAX2, p3); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck2(v2, -MAX2, MAX2, p3); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p3 = "CRYPTO")) { + v2 = obj[p3]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError2 + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError2 + p3 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { + v2 = obj[p3]; + intCheck2(v2, 0, 9, p3); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { + v2 = obj[p3]; + intCheck2(v2, 0, MAX2, p3); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p3 = "FORMAT")) { + v2 = obj[p3]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError2 + p3 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p3 = "ALPHABET")) { + v2 = obj[p3]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + ALPHABET = v2; + } else { + throw Error(bignumberError2 + p3 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError2 + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber3.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber3.DEBUG) + return true; + var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c4) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { + if (c4[0] === 0) { + if (e2 === 0 && c4.length === 1) + return true; + break out; + } + i2 = (e2 + 1) % LOG_BASE2; + if (i2 < 1) + i2 += LOG_BASE2; + if (String(c4[0]).length == i2) { + for (i2 = 0; i2 < c4.length; i2++) { + n3 = c4[i2]; + if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError2 + "Invalid BigNumber: " + v2); + }; + BigNumber3.maximum = BigNumber3.max = function() { + return maxOrMin(arguments, P2.lt); + }; + BigNumber3.minimum = BigNumber3.min = function() { + return maxOrMin(arguments, P2.gt); + }; + BigNumber3.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor2(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck2(dp, 0, MAX2); + k4 = mathceil2(dp / LOG_BASE2); + if (CRYPTO) { + if (crypto.getRandomValues) { + a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); + for (; i2 < k4; ) { + v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); + if (v2 >= 9e15) { + b4 = crypto.getRandomValues(new Uint32Array(2)); + a3[i2] = b4[0]; + a3[i2 + 1] = b4[1]; + } else { + c4.push(v2 % 1e14); + i2 += 2; + } + } + i2 = k4 / 2; + } else if (crypto.randomBytes) { + a3 = crypto.randomBytes(k4 *= 7); + for (; i2 < k4; ) { + v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a3, i2); + } else { + c4.push(v2 % 1e14); + i2 += 7; + } + } + i2 = k4 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError2 + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i2 < k4; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c4[i2++] = v2 % 1e14; + } + } + k4 = c4[--i2]; + dp %= LOG_BASE2; + if (k4 && dp) { + v2 = POWS_TEN2[LOG_BASE2 - dp]; + c4[i2] = mathfloor2(k4 / v2) * v2; + } + for (; c4[i2] === 0; c4.pop(), i2--) + ; + if (i2 < 0) { + c4 = [e2 = 0]; + } else { + for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) + ; + for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) + ; + if (i2 < LOG_BASE2) + e2 -= LOG_BASE2 - i2; + } + rand.e = e2; + rand.c = c4; + return rand; + }; + }(); + BigNumber3.sum = function() { + var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); + for (; i2 < args.length; ) + sum = sum.plus(args[i2++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet2) { + var j2, arr = [0], arrL, i2 = 0, len = str.length; + for (; i2 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet2.indexOf(str.charAt(i2++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i2 >= 0) { + k4 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y4 = new BigNumber3(baseIn); + x3 = y4.pow(str.length - i2); + POW_PRECISION = k4; + y4.c = toBaseOut( + toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), + 10, + baseOut, + decimal + ); + y4.e = y4.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); + e2 = k4 = xc.length; + for (; xc[--k4] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet2.charAt(0); + if (i2 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign2; + x3 = div(x3, y4, dp, rm, baseOut); + xc = x3.c; + r = x3.r; + e2 = x3.e; + } + d3 = e2 + dp + 1; + i2 = xc[d3]; + k4 = baseOut / 2; + r = r || d3 < 0 || xc[d3 + 1] != null; + r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (d3 < 1 || !xc[0]) { + str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); + } else { + xc.length = d3; + if (r) { + for (--baseOut; ++xc[--d3] > baseOut; ) { + xc[d3] = 0; + if (!d3) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k4 = xc.length; !xc[--k4]; ) + ; + for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) + ; + str = toFixedPoint2(str, e2, alphabet2.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x3, k4, base3) { + var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; + for (x3 = x3.slice(); i2--; ) { + xlo = x3[i2] % SQRT_BASE2; + xhi = x3[i2] / SQRT_BASE2 | 0; + m3 = khi * xlo + xhi * klo; + temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; + carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; + x3[i2] = temp % base3; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare4(a3, b4, aL, bL) { + var i2, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i2 = cmp = 0; i2 < aL; i2++) { + if (a3[i2] != b4[i2]) { + cmp = a3[i2] > b4[i2] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a3, b4, aL, base3) { + var i2 = 0; + for (; aL--; ) { + a3[aL] -= i2; + i2 = a3[aL] < b4[aL] ? 1 : 0; + a3[aL] = i2 * base3 + a3[aL] - b4[aL]; + } + for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) + ; + } + return function(x3, y4, dp, rm, base3) { + var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber3( + // Return NaN if either NaN, or both Infinity or 0. + !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber3(s2); + qc = q2.c = []; + e2 = x3.e - y4.e; + s2 = dp + e2 + 1; + if (!base3) { + base3 = BASE2; + e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); + s2 = s2 / LOG_BASE2 | 0; + } + for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) + ; + if (yc[i2] > (xc[i2] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i2 = 0; + s2 += 2; + n3 = mathfloor2(base3 / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base3); + xc = multiply(xc, n3, base3); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base3 / 2) + yc0++; + do { + n3 = 0; + cmp = compare4(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base3 + (rem[1] || 0); + n3 = mathfloor2(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base3) + n3 = base3 - 1; + prod = multiply(yc, n3, base3); + prodL = prod.length; + remL = rem.length; + while (compare4(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base3); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base3); + remL = rem.length; + if (cmp == -1) { + while (compare4(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base3); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i2++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base3 == BASE2) { + for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) + ; + round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format(n3, i2, rm, id) { + var c0, e2, ne, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne = n3.e; + if (i2 == null) { + str = coeffToString2(n3.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); + } else { + n3 = round(new BigNumber3(n3), i2, rm); + e2 = n3.e; + str = coeffToString2(n3.c); + len = str.length; + if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { + for (; len < i2; str += "0", len++) + ; + str = toExponential2(str, e2); + } else { + i2 -= ne; + str = toFixedPoint2(str, e2, "0"); + if (e2 + 1 > len) { + if (--i2 > 0) + for (str += "."; i2--; str += "0") + ; + } else { + i2 += e2 - len; + if (i2 > 0) { + if (e2 + 1 == len) + str += "."; + for (; i2--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, method) { + var n3, i2 = 1, m3 = new BigNumber3(args[0]); + for (; i2 < args.length; i2++) { + n3 = new BigNumber3(args[i2]); + if (!n3.s) { + m3 = n3; + break; + } else if (method.call(m3, n3)) { + m3 = n3; + } + } + return m3; + } + function normalise(n3, c4, e2) { + var i2 = 1, j2 = c4.length; + for (; !c4[--j2]; c4.pop()) + ; + for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) + ; + if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e2 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e2; + n3.c = c4; + } + return n3; + } + parseNumeric = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b4) { + var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m3, p1, p22) { + base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; + return !b4 || b4 == base3 ? p1 : m3; + }); + if (b4) { + base3 = b4; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber3(s2, base3); + } + if (BigNumber3.DEBUG) { + throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm, r) { + var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; + if (xc) { + out: { + for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) + ; + i2 = sd - d3; + if (i2 < 0) { + i2 += LOG_BASE2; + j2 = sd; + n3 = xc[ni = 0]; + rd = n3 / pows10[d3 - j2 - 1] % 10 | 0; + } else { + ni = mathceil2((i2 + 1) / LOG_BASE2); + if (ni >= xc.length) { + if (r) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d3 = 1; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + 1; + } else { + break out; + } + } else { + n3 = k4 = xc[ni]; + for (d3 = 1; k4 >= 10; k4 /= 10, d3++) + ; + i2 %= LOG_BASE2; + j2 = i2 - LOG_BASE2 + d3; + rd = j2 < 0 ? 0 : n3 / pows10[d3 - j2 - 1] % 10 | 0; + } + } + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i2 == 0) { + xc.length = ni; + k4 = 1; + ni--; + } else { + xc.length = ni + 1; + k4 = pows10[LOG_BASE2 - i2]; + xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; + } + if (r) { + for (; ; ) { + if (ni == 0) { + for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) + ; + j2 = xc[0] += k4; + for (k4 = 1; j2 >= 10; j2 /= 10, k4++) + ; + if (i2 != k4) { + x3.e++; + if (xc[0] == BASE2) + xc[0] = 1; + } + break; + } else { + xc[ni] += k4; + if (xc[ni] != BASE2) + break; + xc[ni--] = 0; + k4 = 1; + } + } + } + for (i2 = xc.length; xc[--i2] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n3) { + var str, e2 = n3.e; + if (e2 === null) + return n3.toString(); + str = coeffToString2(n3.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber3(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c4, n3, v2, x3 = this; + if (dp != null) { + intCheck2(dp, 0, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), dp + x3.e + 1, rm); + } + if (!(c4 = x3.c)) + return null; + n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; + if (v2 = c4[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { + return div(this, new BigNumber3(y4, b4), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m3) { + var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; + n3 = new BigNumber3(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); + } + if (m3 != null) + m3 = new BigNumber3(m3); + nIsBig = n3.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { + y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? 2 - isOdd2(n3) : +valueOf(n3))); + return m3 ? y4.mod(m3) : y4; + } + nIsNeg = n3.s < 0; + if (m3) { + if (m3.c ? !m3.c[0] : !m3.s) + return new BigNumber3(NaN); + isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); + if (isModExp) + x3 = x3.mod(m3); + } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { + k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; + if (x3.e > -1) + k4 = 1 / k4; + return new BigNumber3(nIsNeg ? 1 / k4 : k4); + } else if (POW_PRECISION) { + k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); + } + if (nIsBig) { + half = new BigNumber3(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd2(n3); + } else { + i2 = Math.abs(+valueOf(n3)); + nIsOdd = i2 % 2; + } + y4 = new BigNumber3(ONE); + for (; ; ) { + if (nIsOdd) { + y4 = y4.times(x3); + if (!y4.c) + break; + if (k4) { + if (y4.c.length > k4) + y4.c.length = k4; + } else if (isModExp) { + y4 = y4.mod(m3); + } + } + if (i2) { + i2 = mathfloor2(i2 / 2); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd2(n3); + } else { + i2 = +valueOf(n3); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } + } + x3 = x3.times(x3); + if (k4) { + if (x3.c && x3.c.length > k4) + x3.c.length = k4; + } else if (isModExp) { + x3 = x3.mod(m3); + } + } + if (isModExp) + return y4; + if (nIsNeg) + y4 = ONE.div(y4); + return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber3(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y4, b4) { + return compare3(this, new BigNumber3(y4, b4)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { + return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y4, b4) { + var i2, j2, t, xLTy, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.plus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (xLTy = a3 < 0) { + a3 = -a3; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); + for (b4 = a3; b4--; t.push(0)) + ; + t.reverse(); + } else { + j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; + for (a3 = b4 = 0; b4 < j2; b4++) { + if (xc[b4] != yc[b4]) { + xLTy = xc[b4] < yc[b4]; + break; + } + } + } + if (xLTy) + t = xc, xc = yc, yc = t, y4.s = -y4.s; + b4 = (j2 = yc.length) - (i2 = xc.length); + if (b4 > 0) + for (; b4--; xc[i2++] = 0) + ; + b4 = BASE2 - 1; + for (; j2 > a3; ) { + if (xc[--j2] < yc[j2]) { + for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) + ; + --xc[i2]; + xc[j2] += BASE2; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y4.s = ROUNDING_MODE == 3 ? -1 : 1; + y4.c = [y4.e = 0]; + return y4; + } + return normalise(y4, xc, ye); + }; + P2.modulo = P2.mod = function(y4, b4) { + var q2, s2, x3 = this; + y4 = new BigNumber3(y4, b4); + if (!x3.c || !y4.s || y4.c && !y4.c[0]) { + return new BigNumber3(NaN); + } else if (!y4.c || x3.c && !x3.c[0]) { + return new BigNumber3(x3); + } + if (MODULO_MODE == 9) { + s2 = y4.s; + y4.s = 1; + q2 = div(x3, y4, 0, 3); + y4.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y4, 0, MODULO_MODE); + } + y4 = x3.minus(q2.times(y4)); + if (!y4.c[0] && MODULO_MODE == 1) + y4.s = x3.s; + return y4; + }; + P2.multipliedBy = P2.times = function(y4, b4) { + var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y4.c = y4.e = y4.s = null; + } else { + y4.s *= x3.s; + if (!xc || !yc) { + y4.c = y4.e = null; + } else { + y4.c = [0]; + y4.e = 0; + } + } + return y4; + } + e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); + y4.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) + zc = xc, xc = yc, yc = zc, i2 = xcL, xcL = ycL, ycL = i2; + for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) + ; + base3 = BASE2; + sqrtBase = SQRT_BASE2; + for (i2 = ycL; --i2 >= 0; ) { + c4 = 0; + ylo = yc[i2] % sqrtBase; + yhi = yc[i2] / sqrtBase | 0; + for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { + xlo = xc[--k4] % sqrtBase; + xhi = xc[k4] / sqrtBase | 0; + m3 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; + c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base3; + } + zc[j2] = c4; + } + if (c4) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y4, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber3(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y4, b4) { + var t, x3 = this, a3 = x3.s; + y4 = new BigNumber3(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber3(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.minus(y4); + } + var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber3(a3 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); + } + xe = bitFloor2(xe); + ye = bitFloor2(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (a3 > 0) { + ye = xe; + t = yc; + } else { + a3 = -a3; + t = xc; + } + t.reverse(); + for (; a3--; t.push(0)) + ; + t.reverse(); + } + a3 = xc.length; + b4 = yc.length; + if (a3 - b4 < 0) + t = yc, yc = xc, xc = t, b4 = a3; + for (a3 = 0; b4; ) { + a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; + xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; + } + if (a3) { + xc = [a3].concat(xc); + ++ye; + } + return normalise(y4, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm) { + var c4, n3, v2, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck2(sd, 1, MAX2); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck2(rm, 0, 8); + return round(new BigNumber3(x3), sd, rm); + } + if (!(c4 = x3.c)) + return null; + v2 = c4.length - 1; + n3 = v2 * LOG_BASE2 + 1; + if (v2 = c4[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x3.e + 1 > n3) + n3 = x3.e + 1; + return n3; + }; + P2.shiftedBy = function(k4) { + intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); + return this.times("1e" + k4); + }; + P2.squareRoot = P2.sqrt = function() { + var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); + if (s2 !== 1 || !c4 || !c4[0]) { + return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString2(c4); + if ((n3.length + e2) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e2; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; + } + r = new BigNumber3(n3); + } else { + r = new BigNumber3(s2 + ""); + } + if (r.c[0]) { + e2 = r.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t = r; + r = half.times(t.plus(div(x3, t, dp, 1))); + if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { + if (r.e < e2) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + if (t.times(t).eq(x3)) { + r = t; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m3 = !r.times(r).eq(x3); + } + break; + } + } + } + } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp++; + } + return format(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck2(dp, 0, MAX2); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format2) { + var str, x3 = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError2 + "Argument not an object: " + format2); + } + str = x3.toFixed(dp, rm); + if (x3.c) { + var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) + i2 = g1, g1 = g22, g22 = i2, len -= i2; + if (g1 > 0 && len > 0) { + i2 = len % g1 || g1; + intPart = intDigits.substr(0, i2); + for (; i2 < len; i2 += g1) + intPart += groupSeparator + intDigits.substr(i2, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i2); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format2.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P2.toFraction = function(md) { + var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; + if (md != null) { + n3 = new BigNumber3(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber3(x3); + d3 = new BigNumber3(ONE); + n1 = d0 = new BigNumber3(ONE); + d1 = n0 = new BigNumber3(ONE); + s2 = coeffToString2(xc); + e2 = d3.e = s2.length - x3.e - 1; + d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; + md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber3(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d3, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d3 = n3.minus(q2.times(d22 = d3)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( + div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck2(sd, 1, MAX2); + return format(this, sd, rm, 2); + }; + P2.toString = function(b4) { + var str, n3 = this, s2 = n3.s, e2 = n3.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b4 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); + } else if (b4 === 10) { + n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); + } else { + intCheck2(b4, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + if (configObject != null) + BigNumber3.set(configObject); + return BigNumber3; + } + function bitFloor2(n3) { + var i2 = n3 | 0; + return n3 > 0 || n3 === i2 ? i2 : i2 - 1; + } + function coeffToString2(a3) { + var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; + for (; i2 < j2; ) { + s2 = a3[i2++] + ""; + z3 = LOG_BASE2 - s2.length; + for (; z3--; s2 = "0" + s2) + ; + r += s2; + } + for (j2 = r.length; r.charCodeAt(--j2) === 48; ) + ; + return r.slice(0, j2 + 1 || 1); + } + function compare3(x3, y4) { + var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; + if (!i2 || !j2) + return null; + a3 = xc && !xc[0]; + b4 = yc && !yc[0]; + if (a3 || b4) + return a3 ? b4 ? 0 : -j2 : i2; + if (i2 != j2) + return i2; + a3 = i2 < 0; + b4 = k4 == l4; + if (!xc || !yc) + return b4 ? 0 : !xc ^ a3 ? 1 : -1; + if (!b4) + return k4 > l4 ^ a3 ? 1 : -1; + j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; + for (i2 = 0; i2 < j2; i2++) + if (xc[i2] != yc[i2]) + return xc[i2] > yc[i2] ^ a3 ? 1 : -1; + return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; + } + function intCheck2(n3, min, max, name2) { + if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { + throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } + } + function isOdd2(n3) { + var k4 = n3.c.length - 1; + return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; + } + function toExponential2(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + function toFixedPoint2(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + "."; ++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len; --e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; + } + BigNumber2 = clone2(); + BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; + if (typeof define == "function" && define.amd) { + define(function() { + return BigNumber2; + }); + } else if (typeof module2 != "undefined" && module2.exports) { + module2.exports = BigNumber2; + } else { + if (!globalObject) { + globalObject = typeof self != "undefined" && self ? self : window; + } + globalObject.BigNumber = BigNumber2; + } + })(exports2); + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/primitives.js +var require_primitives = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/primitives.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { + Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); + } : function(o2, v2) { + o2["default"] = v2; + }); + var __importStar2 = exports2 && exports2.__importStar || function(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) + __createBinding2(result, mod2, k4); + } + __setModuleDefault(result, mod2); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = exports2.Nonce = exports2.Address = void 0; + var bech32 = __importStar2(require_bech32()); + var HRP = "erd"; + var Address5 = class _Address { + constructor(value) { + this.value = value; + } + static fromPubkey(pubkey) { + let words = bech32.toWords(pubkey); + let address = bech32.encode(HRP, words); + return new _Address(address); + } + bech32() { + return this.value; + } + toString() { + return this.bech32(); + } + }; + exports2.Address = Address5; + var Nonce = class { + constructor(value) { + this.value = value; + } + valueOf() { + return this.value; + } + hex() { + return numberToPaddedHex(this.value); + } + }; + exports2.Nonce = Nonce; + function numberToPaddedHex(value) { + let hex = value.toString(16); + return zeroPadStringIfOddLength(hex); + } + exports2.numberToPaddedHex = numberToPaddedHex; + function isPaddedHex(input) { + input = input || ""; + let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); + return input.toUpperCase() == decodedThenEncoded.toUpperCase(); + } + exports2.isPaddedHex = isPaddedHex; + function zeroPadStringIfOddLength(input) { + input = input || ""; + if (input.length % 2 == 1) { + return "0" + input; + } + return input; + } + exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/constants.js +var require_constants3 = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/constants.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.EsdtContractAddress = exports2.MaxUint64AsBigNumber = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber2()); + var primitives_1 = require_primitives(); + exports2.MaxUint64AsBigNumber = new bignumber_js_1.default("18446744073709551615"); + exports2.EsdtContractAddress = new primitives_1.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js +var require_contractQueryResponse = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js"(exports2) { + "use strict"; + init_shim(); + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractQueryResponse = void 0; + var bignumber_js_1 = __importDefault2(require_bignumber2()); + var constants_1 = require_constants3(); + var ContractQueryResponse3 = class _ContractQueryResponse { + constructor(init) { + this.returnData = (init === null || init === void 0 ? void 0 : init.returnData) || []; + this.returnCode = (init === null || init === void 0 ? void 0 : init.returnCode) || ""; + this.returnMessage = (init === null || init === void 0 ? void 0 : init.returnMessage) || ""; + this.gasUsed = (init === null || init === void 0 ? void 0 : init.gasUsed) || 0; + } + /** + * Constructs a QueryResponse object from a HTTP response (as returned by the provider). + */ + static fromHttpResponse(payload) { + let returnData = payload["returnData"] || payload["ReturnData"]; + let returnCode = payload["returnCode"] || payload["ReturnCode"]; + let returnMessage = payload["returnMessage"] || payload["ReturnMessage"]; + let gasRemaining = new bignumber_js_1.default(payload["gasRemaining"] || payload["GasRemaining"] || 0); + let gasUsed = constants_1.MaxUint64AsBigNumber.minus(gasRemaining).toNumber(); + return new _ContractQueryResponse({ + returnData, + returnCode, + returnMessage, + gasUsed + }); + } + getReturnDataParts() { + return this.returnData.map((item) => import_buffer.Buffer.from(item || "", "base64")); + } + /** + * Converts the object to a pretty, plain JavaScript object. + */ + toJSON() { + return { + returnData: this.returnData, + returnCode: this.returnCode, + returnMessage: this.returnMessage, + gasUsed: this.gasUsed.valueOf() + }; + } + }; + exports2.ContractQueryResponse = ContractQueryResponse3; + } +}); + +// node_modules/@multiversx/sdk-extension-provider/out/errors.js +var require_errors2 = __commonJS({ + "node_modules/@multiversx/sdk-extension-provider/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrAccountNotConnected = exports2.ErrCannotSignSingleTransaction = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + }; + exports2.Err = Err; + var ErrCannotSignSingleTransaction = class extends Err { + constructor() { + super("Cannot sign single transaction."); + } + }; + exports2.ErrCannotSignSingleTransaction = ErrCannotSignSingleTransaction; + var ErrAccountNotConnected = class extends Err { + constructor() { + super("Account is not connected."); + } + }; + exports2.ErrAccountNotConnected = ErrAccountNotConnected; + } +}); + +// node_modules/@multiversx/sdk-extension-provider/out/operation.js +var require_operation = __commonJS({ + "node_modules/@multiversx/sdk-extension-provider/out/operation.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Operation = void 0; + var Operation; + (function(Operation2) { + Operation2["Connect"] = "connect"; + Operation2["Logout"] = "logout"; + Operation2["SignTransactions"] = "signTransactions"; + Operation2["SignMessage"] = "signMessage"; + Operation2["CancelAction"] = "cancelAction"; + })(Operation = exports2.Operation || (exports2.Operation = {})); + } +}); + +// node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js +var require_extensionProvider = __commonJS({ + "node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ExtensionProvider = void 0; + var transaction_1 = require_transaction(); + var errors_1 = require_errors2(); + var operation_1 = require_operation(); + var ExtensionProvider3 = class _ExtensionProvider { + constructor() { + this.account = { address: "" }; + this.initialized = false; + if (_ExtensionProvider._instance) { + throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new."); + } + _ExtensionProvider._instance = this; + } + static getInstance() { + return _ExtensionProvider._instance; + } + setAddress(address) { + this.account.address = address; + return _ExtensionProvider._instance; + } + init() { + return __awaiter2(this, void 0, void 0, function* () { + if (window && window.elrondWallet) { + this.initialized = true; + } + return this.initialized; + }); + } + login(options = {}) { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.initialized) { + throw new Error("Extension provider is not initialised, call init() first"); + } + const { token } = options; + const data = token ? token : ""; + yield this.startBgrMsgChannel(operation_1.Operation.Connect, data); + return this.account.address; + }); + } + logout() { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.initialized) { + throw new Error("Extension provider is not initialised, call init() first"); + } + try { + yield this.startBgrMsgChannel(operation_1.Operation.Logout, this.account.address); + this.disconnect(); + } catch (error) { + console.warn("Extension origin url is already cleared!", error); + } + return true; + }); + } + disconnect() { + this.account = { address: "" }; + } + getAddress() { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.initialized) { + throw new Error("Extension provider is not initialised, call init() first"); + } + return this.account ? this.account.address : ""; + }); + } + isInitialized() { + return this.initialized; + } + // TODO: In V3, this will not be an async function anymore. + isConnected() { + return __awaiter2(this, void 0, void 0, function* () { + return Boolean(this.account.address); + }); + } + signTransaction(transaction) { + return __awaiter2(this, void 0, void 0, function* () { + this.ensureConnected(); + const signedTransactions = yield this.signTransactions([transaction]); + if (signedTransactions.length != 1) { + throw new errors_1.ErrCannotSignSingleTransaction(); + } + return signedTransactions[0]; + }); + } + ensureConnected() { + if (!this.account.address) { + throw new errors_1.ErrAccountNotConnected(); + } + } + signTransactions(transactions) { + return __awaiter2(this, void 0, void 0, function* () { + this.ensureConnected(); + const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignTransactions, { + from: this.account.address, + transactions: transactions.map((transaction) => transaction.toPlainObject()) + }); + try { + const transactionsResponse = extensionResponse.map((transaction) => transaction_1.Transaction.fromPlainObject(transaction)); + return transactionsResponse; + } catch (error) { + throw new Error(`Transaction canceled: ${error.message}.`); + } + }); + } + signMessage(message) { + return __awaiter2(this, void 0, void 0, function* () { + this.ensureConnected(); + const data = { + account: this.account.address, + message: message.message.toString() + }; + const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignMessage, data); + const signatureHex = extensionResponse.signature; + const signature = import_buffer.Buffer.from(signatureHex, "hex"); + message.applySignature(signature); + return message; + }); + } + cancelAction() { + return this.startBgrMsgChannel(operation_1.Operation.CancelAction, {}); + } + startBgrMsgChannel(operation, connectData) { + return new Promise((resolve) => { + window.postMessage({ + target: "erdw-inpage", + type: operation, + data: connectData + }, window.origin); + const eventHandler = (event) => { + if (event.isTrusted && event.data.target === "erdw-contentScript") { + if (event.data.type === "connectResponse") { + if (event.data.data && Boolean(event.data.data.address)) { + this.account = event.data.data; + } + window.removeEventListener("message", eventHandler); + resolve(event.data.data); + } else { + window.removeEventListener("message", eventHandler); + resolve(event.data.data); + } + } + }; + window.addEventListener("message", eventHandler, false); + }); + } + }; + exports2.ExtensionProvider = ExtensionProvider3; + ExtensionProvider3._instance = new ExtensionProvider3(); + } +}); + +// node_modules/destr/dist/index.mjs +function jsonParseTransform(key, value) { + if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) { + warnKeyDropped(key); + return; + } + return value; +} +function warnKeyDropped(key) { + console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`); +} +function destr(value, options = {}) { + if (typeof value !== "string") { + return value; + } + const _value = value.trim(); + if ( + // eslint-disable-next-line unicorn/prefer-at + value[0] === '"' && value.endsWith('"') && !value.includes("\\") + ) { + return _value.slice(1, -1); + } + if (_value.length <= 9) { + const _lval = _value.toLowerCase(); + if (_lval === "true") { + return true; + } + if (_lval === "false") { + return false; + } + if (_lval === "undefined") { + return void 0; + } + if (_lval === "null") { + return null; + } + if (_lval === "nan") { + return Number.NaN; + } + if (_lval === "infinity") { + return Number.POSITIVE_INFINITY; + } + if (_lval === "-infinity") { + return Number.NEGATIVE_INFINITY; + } + } + if (!JsonSigRx.test(value)) { + if (options.strict) { + throw new SyntaxError("[destr] Invalid JSON"); + } + return value; + } + try { + if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) { + if (options.strict) { + throw new Error("[destr] Possible prototype pollution"); + } + return JSON.parse(value, jsonParseTransform); + } + return JSON.parse(value); + } catch (error) { + if (options.strict) { + throw error; + } + return value; + } +} +var suspectProtoRx, suspectConstructorRx, JsonSigRx; +var init_dist = __esm({ + "node_modules/destr/dist/index.mjs"() { + init_shim(); + suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/; + suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; + JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; + } +}); + +// node_modules/unstorage/dist/shared/unstorage.8581f561.mjs +function wrapToPromise(value) { + if (!value || typeof value.then !== "function") { + return Promise.resolve(value); + } + return value; +} +function asyncCall(function_, ...arguments_) { + try { + return wrapToPromise(function_(...arguments_)); + } catch (error) { + return Promise.reject(error); + } +} +function isPrimitive(value) { + const type = typeof value; + return value === null || type !== "object" && type !== "function"; +} +function isPureObject(value) { + const proto = Object.getPrototypeOf(value); + return !proto || proto.isPrototypeOf(Object); +} +function stringify(value) { + if (isPrimitive(value)) { + return String(value); + } + if (isPureObject(value) || Array.isArray(value)) { + return JSON.stringify(value); + } + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + throw new Error("[unstorage] Cannot stringify value!"); +} +function checkBufferSupport() { + if (typeof import_buffer.Buffer === void 0) { + throw new TypeError("[unstorage] Buffer is not supported!"); + } +} +function serializeRaw(value) { + if (typeof value === "string") { + return value; + } + checkBufferSupport(); + const base642 = import_buffer.Buffer.from(value).toString("base64"); + return BASE64_PREFIX + base642; +} +function deserializeRaw(value) { + if (typeof value !== "string") { + return value; + } + if (!value.startsWith(BASE64_PREFIX)) { + return value; + } + checkBufferSupport(); + return import_buffer.Buffer.from(value.slice(BASE64_PREFIX.length), "base64"); +} +function normalizeKey(key) { + if (!key) { + return ""; + } + return key.split("?")[0].replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, ""); +} +function joinKeys(...keys2) { + return normalizeKey(keys2.join(":")); +} +function normalizeBaseKey(base3) { + base3 = normalizeKey(base3); + return base3 ? base3 + ":" : ""; +} +var BASE64_PREFIX; +var init_unstorage_8581f561 = __esm({ + "node_modules/unstorage/dist/shared/unstorage.8581f561.mjs"() { + init_shim(); + BASE64_PREFIX = "base64:"; + } +}); + +// node_modules/unstorage/dist/index.mjs +function defineDriver(factory) { + return factory; +} +function createStorage(options = {}) { + const context = { + mounts: { "": options.driver || memory() }, + mountpoints: [""], + watching: false, + watchListeners: [], + unwatch: {} + }; + const getMount = (key) => { + for (const base3 of context.mountpoints) { + if (key.startsWith(base3)) { + return { + base: base3, + relativeKey: key.slice(base3.length), + driver: context.mounts[base3] + }; + } + } + return { + base: "", + relativeKey: key, + driver: context.mounts[""] + }; + }; + const getMounts = (base3, includeParent) => { + return context.mountpoints.filter( + (mountpoint) => mountpoint.startsWith(base3) || includeParent && base3.startsWith(mountpoint) + ).map((mountpoint) => ({ + relativeBase: base3.length > mountpoint.length ? base3.slice(mountpoint.length) : void 0, + mountpoint, + driver: context.mounts[mountpoint] + })); + }; + const onChange = (event, key) => { + if (!context.watching) { + return; + } + key = normalizeKey(key); + for (const listener of context.watchListeners) { + listener(event, key); + } + }; + const startWatch = async () => { + if (context.watching) { + return; + } + context.watching = true; + for (const mountpoint in context.mounts) { + context.unwatch[mountpoint] = await watch( + context.mounts[mountpoint], + onChange, + mountpoint + ); + } + }; + const stopWatch = async () => { + if (!context.watching) { + return; + } + for (const mountpoint in context.unwatch) { + await context.unwatch[mountpoint](); + } + context.unwatch = {}; + context.watching = false; + }; + const runBatch = (items, commonOptions, cb) => { + const batches = /* @__PURE__ */ new Map(); + const getBatch = (mount) => { + let batch = batches.get(mount.base); + if (!batch) { + batch = { + driver: mount.driver, + base: mount.base, + items: [] + }; + batches.set(mount.base, batch); + } + return batch; + }; + for (const item of items) { + const isStringItem = typeof item === "string"; + const key = normalizeKey(isStringItem ? item : item.key); + const value = isStringItem ? void 0 : item.value; + const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options }; + const mount = getMount(key); + getBatch(mount).items.push({ + key, + value, + relativeKey: mount.relativeKey, + options: options2 + }); + } + return Promise.all([...batches.values()].map((batch) => cb(batch))).then( + (r) => r.flat() + ); + }; + const storage = { + // Item + hasItem(key, opts = {}) { + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + return asyncCall(driver.hasItem, relativeKey, opts); + }, + getItem(key, opts = {}) { + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + return asyncCall(driver.getItem, relativeKey, opts).then( + (value) => destr(value) + ); + }, + getItems(items, commonOptions) { + return runBatch(items, commonOptions, (batch) => { + if (batch.driver.getItems) { + return asyncCall( + batch.driver.getItems, + batch.items.map((item) => ({ + key: item.relativeKey, + options: item.options + })), + commonOptions + ).then( + (r) => r.map((item) => ({ + key: joinKeys(batch.base, item.key), + value: destr(item.value) + })) + ); + } + return Promise.all( + batch.items.map((item) => { + return asyncCall( + batch.driver.getItem, + item.relativeKey, + item.options + ).then((value) => ({ + key: item.key, + value: destr(value) + })); + }) + ); + }); + }, + getItemRaw(key, opts = {}) { + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (driver.getItemRaw) { + return asyncCall(driver.getItemRaw, relativeKey, opts); + } + return asyncCall(driver.getItem, relativeKey, opts).then( + (value) => deserializeRaw(value) + ); + }, + async setItem(key, value, opts = {}) { + if (value === void 0) { + return storage.removeItem(key); + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (!driver.setItem) { + return; + } + await asyncCall(driver.setItem, relativeKey, stringify(value), opts); + if (!driver.watch) { + onChange("update", key); + } + }, + async setItems(items, commonOptions) { + await runBatch(items, commonOptions, async (batch) => { + if (batch.driver.setItems) { + return asyncCall( + batch.driver.setItems, + batch.items.map((item) => ({ + key: item.relativeKey, + value: stringify(item.value), + options: item.options + })), + commonOptions + ); + } + if (!batch.driver.setItem) { + return; + } + await Promise.all( + batch.items.map((item) => { + return asyncCall( + batch.driver.setItem, + item.relativeKey, + stringify(item.value), + item.options + ); + }) + ); + }); + }, + async setItemRaw(key, value, opts = {}) { + if (value === void 0) { + return storage.removeItem(key, opts); + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (driver.setItemRaw) { + await asyncCall(driver.setItemRaw, relativeKey, value, opts); + } else if (driver.setItem) { + await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts); + } else { + return; + } + if (!driver.watch) { + onChange("update", key); + } + }, + async removeItem(key, opts = {}) { + if (typeof opts === "boolean") { + opts = { removeMeta: opts }; + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + if (!driver.removeItem) { + return; + } + await asyncCall(driver.removeItem, relativeKey, opts); + if (opts.removeMeta || opts.removeMata) { + await asyncCall(driver.removeItem, relativeKey + "$", opts); + } + if (!driver.watch) { + onChange("remove", key); + } + }, + // Meta + async getMeta(key, opts = {}) { + if (typeof opts === "boolean") { + opts = { nativeOnly: opts }; + } + key = normalizeKey(key); + const { relativeKey, driver } = getMount(key); + const meta = /* @__PURE__ */ Object.create(null); + if (driver.getMeta) { + Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts)); + } + if (!opts.nativeOnly) { + const value = await asyncCall( + driver.getItem, + relativeKey + "$", + opts + ).then((value_) => destr(value_)); + if (value && typeof value === "object") { + if (typeof value.atime === "string") { + value.atime = new Date(value.atime); + } + if (typeof value.mtime === "string") { + value.mtime = new Date(value.mtime); + } + Object.assign(meta, value); + } + } + return meta; + }, + setMeta(key, value, opts = {}) { + return this.setItem(key + "$", value, opts); + }, + removeMeta(key, opts = {}) { + return this.removeItem(key + "$", opts); + }, + // Keys + async getKeys(base3, opts = {}) { + base3 = normalizeBaseKey(base3); + const mounts = getMounts(base3, true); + let maskedMounts = []; + const allKeys = []; + for (const mount of mounts) { + const rawKeys = await asyncCall( + mount.driver.getKeys, + mount.relativeBase, + opts + ); + const keys2 = rawKeys.map((key) => mount.mountpoint + normalizeKey(key)).filter((key) => !maskedMounts.some((p3) => key.startsWith(p3))); + allKeys.push(...keys2); + maskedMounts = [ + mount.mountpoint, + ...maskedMounts.filter((p3) => !p3.startsWith(mount.mountpoint)) + ]; + } + return base3 ? allKeys.filter((key) => key.startsWith(base3) && !key.endsWith("$")) : allKeys.filter((key) => !key.endsWith("$")); + }, + // Utils + async clear(base3, opts = {}) { + base3 = normalizeBaseKey(base3); + await Promise.all( + getMounts(base3, false).map(async (m3) => { + if (m3.driver.clear) { + return asyncCall(m3.driver.clear, m3.relativeBase, opts); + } + if (m3.driver.removeItem) { + const keys2 = await m3.driver.getKeys(m3.relativeBase || "", opts); + return Promise.all( + keys2.map((key) => m3.driver.removeItem(key, opts)) + ); + } + }) + ); + }, + async dispose() { + await Promise.all( + Object.values(context.mounts).map((driver) => dispose(driver)) + ); + }, + async watch(callback) { + await startWatch(); + context.watchListeners.push(callback); + return async () => { + context.watchListeners = context.watchListeners.filter( + (listener) => listener !== callback + ); + if (context.watchListeners.length === 0) { + await stopWatch(); + } + }; + }, + async unwatch() { + context.watchListeners = []; + await stopWatch(); + }, + // Mount + mount(base3, driver) { + base3 = normalizeBaseKey(base3); + if (base3 && context.mounts[base3]) { + throw new Error(`already mounted at ${base3}`); + } + if (base3) { + context.mountpoints.push(base3); + context.mountpoints.sort((a3, b4) => b4.length - a3.length); + } + context.mounts[base3] = driver; + if (context.watching) { + Promise.resolve(watch(driver, onChange, base3)).then((unwatcher) => { + context.unwatch[base3] = unwatcher; + }).catch(console.error); + } + return storage; + }, + async unmount(base3, _dispose = true) { + base3 = normalizeBaseKey(base3); + if (!base3 || !context.mounts[base3]) { + return; + } + if (context.watching && base3 in context.unwatch) { + context.unwatch[base3](); + delete context.unwatch[base3]; + } + if (_dispose) { + await dispose(context.mounts[base3]); + } + context.mountpoints = context.mountpoints.filter((key) => key !== base3); + delete context.mounts[base3]; + }, + getMount(key = "") { + key = normalizeKey(key) + ":"; + const m3 = getMount(key); + return { + driver: m3.driver, + base: m3.base + }; + }, + getMounts(base3 = "", opts = {}) { + base3 = normalizeKey(base3); + const mounts = getMounts(base3, opts.parents); + return mounts.map((m3) => ({ + driver: m3.driver, + base: m3.mountpoint + })); + } + }; + return storage; +} +function watch(driver, onChange, base3) { + return driver.watch ? driver.watch((event, key) => onChange(event, base3 + key)) : () => { + }; +} +async function dispose(driver) { + if (typeof driver.dispose === "function") { + await asyncCall(driver.dispose); + } +} +var DRIVER_NAME, memory; +var init_dist2 = __esm({ + "node_modules/unstorage/dist/index.mjs"() { + init_shim(); + init_dist(); + init_unstorage_8581f561(); + DRIVER_NAME = "memory"; + memory = defineDriver(() => { + const data = /* @__PURE__ */ new Map(); + return { + name: DRIVER_NAME, + options: {}, + hasItem(key) { + return data.has(key); + }, + getItem(key) { + return data.get(key) ?? null; + }, + getItemRaw(key) { + return data.get(key) ?? null; + }, + setItem(key, value) { + data.set(key, value); + }, + setItemRaw(key, value) { + data.set(key, value); + }, + removeItem(key) { + data.delete(key); + }, + getKeys() { + return Array.from(data.keys()); + }, + clear() { + data.clear(); + }, + dispose() { + data.clear(); + } + }; + }); + } +}); + +// node_modules/idb-keyval/dist/index.js +function promisifyRequest(request) { + return new Promise((resolve, reject) => { + request.oncomplete = request.onsuccess = () => resolve(request.result); + request.onabort = request.onerror = () => reject(request.error); + }); +} +function createStore(dbName, storeName) { + const request = indexedDB.open(dbName); + request.onupgradeneeded = () => request.result.createObjectStore(storeName); + const dbp = promisifyRequest(request); + return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName))); +} +function defaultGetStore() { + if (!defaultGetStoreFunc) { + defaultGetStoreFunc = createStore("keyval-store", "keyval"); + } + return defaultGetStoreFunc; +} +function get(key, customStore = defaultGetStore()) { + return customStore("readonly", (store) => promisifyRequest(store.get(key))); +} +function set(key, value, customStore = defaultGetStore()) { + return customStore("readwrite", (store) => { + store.put(value, key); + return promisifyRequest(store.transaction); + }); +} +function del(key, customStore = defaultGetStore()) { + return customStore("readwrite", (store) => { + store.delete(key); + return promisifyRequest(store.transaction); + }); +} +function clear(customStore = defaultGetStore()) { + return customStore("readwrite", (store) => { + store.clear(); + return promisifyRequest(store.transaction); + }); +} +function eachCursor(store, callback) { + store.openCursor().onsuccess = function() { + if (!this.result) + return; + callback(this.result); + this.result.continue(); + }; + return promisifyRequest(store.transaction); +} +function keys(customStore = defaultGetStore()) { + return customStore("readonly", (store) => { + if (store.getAllKeys) { + return promisifyRequest(store.getAllKeys()); + } + const items = []; + return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items); + }); +} +var defaultGetStoreFunc; +var init_dist3 = __esm({ + "node_modules/idb-keyval/dist/index.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/safe-json/dist/esm/index.js +var esm_exports = {}; +__export(esm_exports, { + safeJsonParse: () => safeJsonParse, + safeJsonStringify: () => safeJsonStringify +}); +function safeJsonParse(value) { + if (typeof value !== "string") { + throw new Error(`Cannot safe json parse value of type ${typeof value}`); + } + try { + return JSONParse(value); + } catch (_a) { + return value; + } +} +function safeJsonStringify(value) { + return typeof value === "string" ? value : JSONStringify(value) || ""; +} +var JSONStringify, JSONParse; +var init_esm = __esm({ + "node_modules/@walletconnect/safe-json/dist/esm/index.js"() { + init_shim(); + JSONStringify = (data) => JSON.stringify(data, (_4, value) => typeof value === "bigint" ? value.toString() + "n" : value); + JSONParse = (json) => { + const numbersBiggerThanMaxInt = /([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g; + const serializedData = json.replace(numbersBiggerThanMaxInt, '$1"$2n"$3'); + return JSON.parse(serializedData, (_4, value) => { + const isCustomFormatBigInt = typeof value === "string" && value.match(/^\d+n$/); + if (isCustomFormatBigInt) + return BigInt(value.substring(0, value.length - 1)); + return value; + }); + }; + } +}); + +// node_modules/@walletconnect/keyvaluestorage/dist/index.es.js +var index_es_exports = {}; +__export(index_es_exports, { + KeyValueStorage: () => h, + default: () => h +}); +function k(i2) { + var t; + return [i2[0], safeJsonParse((t = i2[1]) != null ? t : "")]; +} +var x, z, D, E, _, l, c, K, N, y, O, j, h; +var init_index_es = __esm({ + "node_modules/@walletconnect/keyvaluestorage/dist/index.es.js"() { + init_shim(); + init_dist2(); + init_dist3(); + init_esm(); + x = "idb-keyval"; + z = (i2 = {}) => { + const t = i2.base && i2.base.length > 0 ? `${i2.base}:` : "", e2 = (s2) => t + s2; + let n3; + return i2.dbName && i2.storeName && (n3 = createStore(i2.dbName, i2.storeName)), { name: x, options: i2, async hasItem(s2) { + return !(typeof await get(e2(s2), n3) > "u"); + }, async getItem(s2) { + return await get(e2(s2), n3) ?? null; + }, setItem(s2, a3) { + return set(e2(s2), a3, n3); + }, removeItem(s2) { + return del(e2(s2), n3); + }, getKeys() { + return keys(n3); + }, clear() { + return clear(n3); + } }; + }; + D = "WALLET_CONNECT_V2_INDEXED_DB"; + E = "keyvaluestorage"; + _ = class { + constructor() { + this.indexedDb = createStorage({ driver: z({ dbName: D, storeName: E }) }); + } + async getKeys() { + return this.indexedDb.getKeys(); + } + async getEntries() { + return (await this.indexedDb.getItems(await this.indexedDb.getKeys())).map((t) => [t.key, t.value]); + } + async getItem(t) { + const e2 = await this.indexedDb.getItem(t); + if (e2 !== null) + return e2; + } + async setItem(t, e2) { + await this.indexedDb.setItem(t, safeJsonStringify(e2)); + } + async removeItem(t) { + await this.indexedDb.removeItem(t); + } + }; + l = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; + c = { exports: {} }; + (function() { + let i2; + function t() { + } + i2 = t, i2.prototype.getItem = function(e2) { + return this.hasOwnProperty(e2) ? String(this[e2]) : null; + }, i2.prototype.setItem = function(e2, n3) { + this[e2] = String(n3); + }, i2.prototype.removeItem = function(e2) { + delete this[e2]; + }, i2.prototype.clear = function() { + const e2 = this; + Object.keys(e2).forEach(function(n3) { + e2[n3] = void 0, delete e2[n3]; + }); + }, i2.prototype.key = function(e2) { + return e2 = e2 || 0, Object.keys(this)[e2]; + }, i2.prototype.__defineGetter__("length", function() { + return Object.keys(this).length; + }), typeof l < "u" && l.localStorage ? c.exports = l.localStorage : typeof window < "u" && window.localStorage ? c.exports = window.localStorage : c.exports = new t(); + })(); + K = class { + constructor() { + this.localStorage = c.exports; + } + async getKeys() { + return Object.keys(this.localStorage); + } + async getEntries() { + return Object.entries(this.localStorage).map(k); + } + async getItem(t) { + const e2 = this.localStorage.getItem(t); + if (e2 !== null) + return safeJsonParse(e2); + } + async setItem(t, e2) { + this.localStorage.setItem(t, safeJsonStringify(e2)); + } + async removeItem(t) { + this.localStorage.removeItem(t); + } + }; + N = "wc_storage_version"; + y = 1; + O = async (i2, t, e2) => { + const n3 = N, s2 = await t.getItem(n3); + if (s2 && s2 >= y) { + e2(t); + return; + } + const a3 = await i2.getKeys(); + if (!a3.length) { + e2(t); + return; + } + const m3 = []; + for (; a3.length; ) { + const r = a3.shift(); + if (!r) + continue; + const o2 = r.toLowerCase(); + if (o2.includes("wc@") || o2.includes("walletconnect") || o2.includes("wc_") || o2.includes("wallet_connect")) { + const f4 = await i2.getItem(r); + await t.setItem(r, f4), m3.push(r); + } + } + await t.setItem(n3, y), e2(t), j(i2, m3); + }; + j = async (i2, t) => { + t.length && t.forEach(async (e2) => { + await i2.removeItem(e2); + }); + }; + h = class { + constructor() { + this.initialized = false, this.setInitialized = (e2) => { + this.storage = e2, this.initialized = true; + }; + const t = new K(); + this.storage = t; + try { + const e2 = new _(); + O(t, e2, this.setInitialized); + } catch { + this.initialized = true; + } + } + async getKeys() { + return await this.initialize(), this.storage.getKeys(); + } + async getEntries() { + return await this.initialize(), this.storage.getEntries(); + } + async getItem(t) { + return await this.initialize(), this.storage.getItem(t); + } + async setItem(t, e2) { + return await this.initialize(), this.storage.setItem(t, e2); + } + async removeItem(t) { + return await this.initialize(), this.storage.removeItem(t); + } + async initialize() { + this.initialized || await new Promise((t) => { + const e2 = setInterval(() => { + this.initialized && (clearInterval(e2), t()); + }, 20); + }); + } + }; + } +}); + +// node_modules/tslib/tslib.es6.js +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __read: () => __read, + __rest: () => __rest, + __spread: () => __spread, + __spreadArrays: () => __spreadArrays, + __values: () => __values +}); +function __extends(d3, b4) { + extendStatics(d3, b4); + function __() { + this.constructor = d3; + } + d3.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); +} +function __rest(s2, e2) { + var t = {}; + for (var p3 in s2) + if (Object.prototype.hasOwnProperty.call(s2, p3) && e2.indexOf(p3) < 0) + t[p3] = s2[p3]; + if (s2 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i2 = 0, p3 = Object.getOwnPropertySymbols(s2); i2 < p3.length; i2++) { + if (e2.indexOf(p3[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p3[i2])) + t[p3[i2]] = s2[p3[i2]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c4 = arguments.length, r = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i2 = decorators.length - 1; i2 >= 0; i2--) + if (d3 = decorators[i2]) + r = (c4 < 3 ? d3(r) : c4 > 3 ? d3(target, key, r) : d3(target, key)) || r; + return c4 > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _4 = { label: 0, sent: function() { + if (t[0] & 1) + throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f4, y4, t, g3; + return g3 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() { + return this; + }), g3; + function verb(n3) { + return function(v2) { + return step([n3, v2]); + }; + } + function step(op) { + if (f4) + throw new TypeError("Generator is already executing."); + while (_4) + try { + if (f4 = 1, y4 && (t = op[0] & 2 ? y4["return"] : op[0] ? y4["throw"] || ((t = y4["return"]) && t.call(y4), 0) : y4.next) && !(t = t.call(y4, op[1])).done) + return t; + if (y4 = 0, t) + op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _4.label++; + return { value: op[1], done: false }; + case 5: + _4.label++; + y4 = op[1]; + op = [0]; + continue; + case 7: + op = _4.ops.pop(); + _4.trys.pop(); + continue; + default: + if (!(t = _4.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _4 = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _4.label = op[1]; + break; + } + if (op[0] === 6 && _4.label < t[1]) { + _4.label = t[1]; + t = op; + break; + } + if (t && _4.label < t[2]) { + _4.label = t[2]; + _4.ops.push(op); + break; + } + if (t[2]) + _4.ops.pop(); + _4.trys.pop(); + continue; + } + op = body.call(thisArg, _4); + } catch (e2) { + op = [6, e2]; + y4 = 0; + } finally { + f4 = t = 0; + } + if (op[0] & 5) + throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __createBinding(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; +} +function __exportStar(m3, exports2) { + for (var p3 in m3) + if (p3 !== "default" && !exports2.hasOwnProperty(p3)) + exports2[p3] = m3[p3]; +} +function __values(o2) { + var s2 = typeof Symbol === "function" && Symbol.iterator, m3 = s2 && o2[s2], i2 = 0; + if (m3) + return m3.call(o2); + if (o2 && typeof o2.length === "number") + return { + next: function() { + if (o2 && i2 >= o2.length) + o2 = void 0; + return { value: o2 && o2[i2++], done: !o2 }; + } + }; + throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o2, n3) { + var m3 = typeof Symbol === "function" && o2[Symbol.iterator]; + if (!m3) + return o2; + var i2 = m3.call(o2), r, ar = [], e2; + try { + while ((n3 === void 0 || n3-- > 0) && !(r = i2.next()).done) + ar.push(r.value); + } catch (error) { + e2 = { error }; + } finally { + try { + if (r && !r.done && (m3 = i2["return"])) + m3.call(i2); + } finally { + if (e2) + throw e2.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i2 = 0; i2 < arguments.length; i2++) + ar = ar.concat(__read(arguments[i2])); + return ar; +} +function __spreadArrays() { + for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) + s2 += arguments[i2].length; + for (var r = Array(s2), k4 = 0, i2 = 0; i2 < il; i2++) + for (var a3 = arguments[i2], j2 = 0, jl = a3.length; j2 < jl; j2++, k4++) + r[k4] = a3[j2]; + return r; +} +function __await(v2) { + return this instanceof __await ? (this.v = v2, this) : new __await(v2); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g3 = generator.apply(thisArg, _arguments || []), i2, q2 = []; + return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2; + function verb(n3) { + if (g3[n3]) + i2[n3] = function(v2) { + return new Promise(function(a3, b4) { + q2.push([n3, v2, a3, b4]) > 1 || resume(n3, v2); + }); + }; + } + function resume(n3, v2) { + try { + step(g3[n3](v2)); + } catch (e2) { + settle(q2[0][3], e2); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f4, v2) { + if (f4(v2), q2.shift(), q2.length) + resume(q2[0][0], q2[0][1]); + } +} +function __asyncDelegator(o2) { + var i2, p3; + return i2 = {}, verb("next"), verb("throw", function(e2) { + throw e2; + }), verb("return"), i2[Symbol.iterator] = function() { + return this; + }, i2; + function verb(n3, f4) { + i2[n3] = o2[n3] ? function(v2) { + return (p3 = !p3) ? { value: __await(o2[n3](v2)), done: n3 === "return" } : f4 ? f4(v2) : v2; + } : f4; + } +} +function __asyncValues(o2) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m3 = o2[Symbol.asyncIterator], i2; + return m3 ? m3.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2); + function verb(n3) { + i2[n3] = o2[n3] && function(v2) { + return new Promise(function(resolve, reject) { + v2 = o2[n3](v2), settle(resolve, reject, v2.done, v2.value); + }); + }; + } + function settle(resolve, reject, d3, v2) { + Promise.resolve(v2).then(function(v3) { + resolve({ value: v3, done: d3 }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod2) { + if (mod2 && mod2.__esModule) + return mod2; + var result = {}; + if (mod2 != null) { + for (var k4 in mod2) + if (Object.hasOwnProperty.call(mod2, k4)) + result[k4] = mod2[k4]; + } + result.default = mod2; + return result; +} +function __importDefault(mod2) { + return mod2 && mod2.__esModule ? mod2 : { default: mod2 }; +} +function __classPrivateFieldGet(receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); +} +function __classPrivateFieldSet(receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; +} +var extendStatics, __assign; +var init_tslib_es6 = __esm({ + "node_modules/tslib/tslib.es6.js"() { + init_shim(); + extendStatics = function(d3, b4) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b5) { + d4.__proto__ = b5; + } || function(d4, b5) { + for (var p3 in b5) + if (b5.hasOwnProperty(p3)) + d4[p3] = b5[p3]; + }; + return extendStatics(d3, b4); + }; + __assign = function() { + __assign = Object.assign || function __assign2(t) { + for (var s2, i2 = 1, n3 = arguments.length; i2 < n3; i2++) { + s2 = arguments[i2]; + for (var p3 in s2) + if (Object.prototype.hasOwnProperty.call(s2, p3)) + t[p3] = s2[p3]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/utils/delay.js +var require_delay = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/utils/delay.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.delay = void 0; + function delay(timeout) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(true); + }, timeout); + }); + } + exports2.delay = delay; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/constants/misc.js +var require_misc = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/constants/misc.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ONE_THOUSAND = exports2.ONE_HUNDRED = void 0; + exports2.ONE_HUNDRED = 100; + exports2.ONE_THOUSAND = 1e3; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/constants/time.js +var require_time = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/constants/time.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ONE_YEAR = exports2.FOUR_WEEKS = exports2.THREE_WEEKS = exports2.TWO_WEEKS = exports2.ONE_WEEK = exports2.THIRTY_DAYS = exports2.SEVEN_DAYS = exports2.FIVE_DAYS = exports2.THREE_DAYS = exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS = exports2.TWELVE_HOURS = exports2.SIX_HOURS = exports2.THREE_HOURS = exports2.ONE_HOUR = exports2.SIXTY_MINUTES = exports2.THIRTY_MINUTES = exports2.TEN_MINUTES = exports2.FIVE_MINUTES = exports2.ONE_MINUTE = exports2.SIXTY_SECONDS = exports2.THIRTY_SECONDS = exports2.TEN_SECONDS = exports2.FIVE_SECONDS = exports2.ONE_SECOND = void 0; + exports2.ONE_SECOND = 1; + exports2.FIVE_SECONDS = 5; + exports2.TEN_SECONDS = 10; + exports2.THIRTY_SECONDS = 30; + exports2.SIXTY_SECONDS = 60; + exports2.ONE_MINUTE = exports2.SIXTY_SECONDS; + exports2.FIVE_MINUTES = exports2.ONE_MINUTE * 5; + exports2.TEN_MINUTES = exports2.ONE_MINUTE * 10; + exports2.THIRTY_MINUTES = exports2.ONE_MINUTE * 30; + exports2.SIXTY_MINUTES = exports2.ONE_MINUTE * 60; + exports2.ONE_HOUR = exports2.SIXTY_MINUTES; + exports2.THREE_HOURS = exports2.ONE_HOUR * 3; + exports2.SIX_HOURS = exports2.ONE_HOUR * 6; + exports2.TWELVE_HOURS = exports2.ONE_HOUR * 12; + exports2.TWENTY_FOUR_HOURS = exports2.ONE_HOUR * 24; + exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS; + exports2.THREE_DAYS = exports2.ONE_DAY * 3; + exports2.FIVE_DAYS = exports2.ONE_DAY * 5; + exports2.SEVEN_DAYS = exports2.ONE_DAY * 7; + exports2.THIRTY_DAYS = exports2.ONE_DAY * 30; + exports2.ONE_WEEK = exports2.SEVEN_DAYS; + exports2.TWO_WEEKS = exports2.ONE_WEEK * 2; + exports2.THREE_WEEKS = exports2.ONE_WEEK * 3; + exports2.FOUR_WEEKS = exports2.ONE_WEEK * 4; + exports2.ONE_YEAR = exports2.ONE_DAY * 365; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/constants/index.js +var require_constants4 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/constants/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_misc(), exports2); + tslib_1.__exportStar(require_time(), exports2); + } +}); + +// node_modules/@walletconnect/time/dist/cjs/utils/convert.js +var require_convert = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/utils/convert.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.fromMiliseconds = exports2.toMiliseconds = void 0; + var constants_1 = require_constants4(); + function toMiliseconds(seconds) { + return seconds * constants_1.ONE_THOUSAND; + } + exports2.toMiliseconds = toMiliseconds; + function fromMiliseconds2(miliseconds) { + return Math.floor(miliseconds / constants_1.ONE_THOUSAND); + } + exports2.fromMiliseconds = fromMiliseconds2; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/utils/index.js +var require_utils3 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/utils/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_delay(), exports2); + tslib_1.__exportStar(require_convert(), exports2); + } +}); + +// node_modules/@walletconnect/time/dist/cjs/watch.js +var require_watch = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/watch.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Watch = void 0; + var Watch = class { + constructor() { + this.timestamps = /* @__PURE__ */ new Map(); + } + start(label) { + if (this.timestamps.has(label)) { + throw new Error(`Watch already started for label: ${label}`); + } + this.timestamps.set(label, { started: Date.now() }); + } + stop(label) { + const timestamp = this.get(label); + if (typeof timestamp.elapsed !== "undefined") { + throw new Error(`Watch already stopped for label: ${label}`); + } + const elapsed = Date.now() - timestamp.started; + this.timestamps.set(label, { started: timestamp.started, elapsed }); + } + get(label) { + const timestamp = this.timestamps.get(label); + if (typeof timestamp === "undefined") { + throw new Error(`No timestamp found for label: ${label}`); + } + return timestamp; + } + elapsed(label) { + const timestamp = this.get(label); + const elapsed = timestamp.elapsed || Date.now() - timestamp.started; + return elapsed; + } + }; + exports2.Watch = Watch; + exports2.default = Watch; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/types/watch.js +var require_watch2 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/types/watch.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.IWatch = void 0; + var IWatch = class { + }; + exports2.IWatch = IWatch; + } +}); + +// node_modules/@walletconnect/time/dist/cjs/types/index.js +var require_types2 = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/types/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_watch2(), exports2); + } +}); + +// node_modules/@walletconnect/time/dist/cjs/index.js +var require_cjs = __commonJS({ + "node_modules/@walletconnect/time/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_utils3(), exports2); + tslib_1.__exportStar(require_watch(), exports2); + tslib_1.__exportStar(require_types2(), exports2); + tslib_1.__exportStar(require_constants4(), exports2); + } +}); + +// node_modules/@walletconnect/events/dist/esm/events.js +var IEvents; +var init_events = __esm({ + "node_modules/@walletconnect/events/dist/esm/events.js"() { + init_shim(); + IEvents = class { + }; + } +}); + +// node_modules/@walletconnect/events/dist/esm/index.js +var esm_exports2 = {}; +__export(esm_exports2, { + IEvents: () => IEvents +}); +var init_esm2 = __esm({ + "node_modules/@walletconnect/events/dist/esm/index.js"() { + init_shim(); + init_events(); + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js +var require_heartbeat = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.IHeartBeat = void 0; + var events_1 = (init_esm2(), __toCommonJS(esm_exports2)); + var IHeartBeat = class extends events_1.IEvents { + constructor(opts) { + super(); + } + }; + exports2.IHeartBeat = IHeartBeat; + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js +var require_types3 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_heartbeat(), exports2); + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js +var require_heartbeat2 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HEARTBEAT_EVENTS = exports2.HEARTBEAT_INTERVAL = void 0; + var time_1 = require_cjs(); + exports2.HEARTBEAT_INTERVAL = time_1.FIVE_SECONDS; + exports2.HEARTBEAT_EVENTS = { + pulse: "heartbeat_pulse" + }; + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js +var require_constants5 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_heartbeat2(), exports2); + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js +var require_heartbeat3 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HeartBeat = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var events_1 = require_events(); + var time_1 = require_cjs(); + var types_1 = require_types3(); + var constants_1 = require_constants5(); + var HeartBeat = class _HeartBeat extends types_1.IHeartBeat { + constructor(opts) { + super(opts); + this.events = new events_1.EventEmitter(); + this.interval = constants_1.HEARTBEAT_INTERVAL; + this.interval = (opts === null || opts === void 0 ? void 0 : opts.interval) || constants_1.HEARTBEAT_INTERVAL; + } + static init(opts) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const heartbeat = new _HeartBeat(opts); + yield heartbeat.init(); + return heartbeat; + }); + } + init() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + yield this.initialize(); + }); + } + stop() { + clearInterval(this.intervalRef); + } + on(event, listener) { + this.events.on(event, listener); + } + once(event, listener) { + this.events.once(event, listener); + } + off(event, listener) { + this.events.off(event, listener); + } + removeListener(event, listener) { + this.events.removeListener(event, listener); + } + initialize() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + this.intervalRef = setInterval(() => this.pulse(), time_1.toMiliseconds(this.interval)); + }); + } + pulse() { + this.events.emit(constants_1.HEARTBEAT_EVENTS.pulse); + } + }; + exports2.HeartBeat = HeartBeat; + } +}); + +// node_modules/@walletconnect/heartbeat/dist/cjs/index.js +var require_cjs2 = __commonJS({ + "node_modules/@walletconnect/heartbeat/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_heartbeat3(), exports2); + tslib_1.__exportStar(require_types3(), exports2); + tslib_1.__exportStar(require_constants5(), exports2); + } +}); + +// node_modules/quick-format-unescaped/index.js +var require_quick_format_unescaped = __commonJS({ + "node_modules/quick-format-unescaped/index.js"(exports2, module2) { + "use strict"; + init_shim(); + function tryStringify(o2) { + try { + return JSON.stringify(o2); + } catch (e2) { + return '"[Circular]"'; + } + } + module2.exports = format; + function format(f4, args, opts) { + var ss = opts && opts.stringify || tryStringify; + var offset = 1; + if (typeof f4 === "object" && f4 !== null) { + var len = args.length + offset; + if (len === 1) + return f4; + var objects = new Array(len); + objects[0] = ss(f4); + for (var index = 1; index < len; index++) { + objects[index] = ss(args[index]); + } + return objects.join(" "); + } + if (typeof f4 !== "string") { + return f4; + } + var argLen = args.length; + if (argLen === 0) + return f4; + var str = ""; + var a3 = 1 - offset; + var lastPos = -1; + var flen = f4 && f4.length || 0; + for (var i2 = 0; i2 < flen; ) { + if (f4.charCodeAt(i2) === 37 && i2 + 1 < flen) { + lastPos = lastPos > -1 ? lastPos : 0; + switch (f4.charCodeAt(i2 + 1)) { + case 100: + case 102: + if (a3 >= argLen) + break; + if (args[a3] == null) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += Number(args[a3]); + lastPos = i2 + 2; + i2++; + break; + case 105: + if (a3 >= argLen) + break; + if (args[a3] == null) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += Math.floor(Number(args[a3])); + lastPos = i2 + 2; + i2++; + break; + case 79: + case 111: + case 106: + if (a3 >= argLen) + break; + if (args[a3] === void 0) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + var type = typeof args[a3]; + if (type === "string") { + str += "'" + args[a3] + "'"; + lastPos = i2 + 2; + i2++; + break; + } + if (type === "function") { + str += args[a3].name || ""; + lastPos = i2 + 2; + i2++; + break; + } + str += ss(args[a3]); + lastPos = i2 + 2; + i2++; + break; + case 115: + if (a3 >= argLen) + break; + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += String(args[a3]); + lastPos = i2 + 2; + i2++; + break; + case 37: + if (lastPos < i2) + str += f4.slice(lastPos, i2); + str += "%"; + lastPos = i2 + 2; + i2++; + a3--; + break; + } + ++a3; + } + ++i2; + } + if (lastPos === -1) + return f4; + else if (lastPos < flen) { + str += f4.slice(lastPos); + } + return str; + } + } +}); + +// node_modules/pino/browser.js +var require_browser3 = __commonJS({ + "node_modules/pino/browser.js"(exports2, module2) { + "use strict"; + init_shim(); + var format = require_quick_format_unescaped(); + module2.exports = pino; + var _console = pfGlobalThisOrFallback().console || {}; + var stdSerializers = { + mapHttpRequest: mock, + mapHttpResponse: mock, + wrapRequestSerializer: passthrough, + wrapResponseSerializer: passthrough, + wrapErrorSerializer: passthrough, + req: mock, + res: mock, + err: asErrValue + }; + function shouldSerialize(serialize, serializers) { + if (Array.isArray(serialize)) { + const hasToFilter = serialize.filter(function(k4) { + return k4 !== "!stdSerializers.err"; + }); + return hasToFilter; + } else if (serialize === true) { + return Object.keys(serializers); + } + return false; + } + function pino(opts) { + opts = opts || {}; + opts.browser = opts.browser || {}; + const transmit2 = opts.browser.transmit; + if (transmit2 && typeof transmit2.send !== "function") { + throw Error("pino: transmit option must have a send function"); + } + const proto = opts.browser.write || _console; + if (opts.browser.write) + opts.browser.asObject = true; + const serializers = opts.serializers || {}; + const serialize = shouldSerialize(opts.browser.serialize, serializers); + let stdErrSerialize = opts.browser.serialize; + if (Array.isArray(opts.browser.serialize) && opts.browser.serialize.indexOf("!stdSerializers.err") > -1) + stdErrSerialize = false; + const levels = ["error", "fatal", "warn", "info", "debug", "trace"]; + if (typeof proto === "function") { + proto.error = proto.fatal = proto.warn = proto.info = proto.debug = proto.trace = proto; + } + if (opts.enabled === false) + opts.level = "silent"; + const level = opts.level || "info"; + const logger = Object.create(proto); + if (!logger.log) + logger.log = noop; + Object.defineProperty(logger, "levelVal", { + get: getLevelVal + }); + Object.defineProperty(logger, "level", { + get: getLevel, + set: setLevel + }); + const setOpts = { + transmit: transmit2, + serialize, + asObject: opts.browser.asObject, + levels, + timestamp: getTimeFunction(opts) + }; + logger.levels = pino.levels; + logger.level = level; + logger.setMaxListeners = logger.getMaxListeners = logger.emit = logger.addListener = logger.on = logger.prependListener = logger.once = logger.prependOnceListener = logger.removeListener = logger.removeAllListeners = logger.listeners = logger.listenerCount = logger.eventNames = logger.write = logger.flush = noop; + logger.serializers = serializers; + logger._serialize = serialize; + logger._stdErrSerialize = stdErrSerialize; + logger.child = child; + if (transmit2) + logger._logEvent = createLogEventShape(); + function getLevelVal() { + return this.level === "silent" ? Infinity : this.levels.values[this.level]; + } + function getLevel() { + return this._level; + } + function setLevel(level2) { + if (level2 !== "silent" && !this.levels.values[level2]) { + throw Error("unknown level " + level2); + } + this._level = level2; + set2(setOpts, logger, "error", "log"); + set2(setOpts, logger, "fatal", "error"); + set2(setOpts, logger, "warn", "error"); + set2(setOpts, logger, "info", "log"); + set2(setOpts, logger, "debug", "log"); + set2(setOpts, logger, "trace", "log"); + } + function child(bindings, childOptions) { + if (!bindings) { + throw new Error("missing bindings for child Pino"); + } + childOptions = childOptions || {}; + if (serialize && bindings.serializers) { + childOptions.serializers = bindings.serializers; + } + const childOptionsSerializers = childOptions.serializers; + if (serialize && childOptionsSerializers) { + var childSerializers = Object.assign({}, serializers, childOptionsSerializers); + var childSerialize = opts.browser.serialize === true ? Object.keys(childSerializers) : serialize; + delete bindings.serializers; + applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize); + } + function Child(parent) { + this._childLevel = (parent._childLevel | 0) + 1; + this.error = bind(parent, bindings, "error"); + this.fatal = bind(parent, bindings, "fatal"); + this.warn = bind(parent, bindings, "warn"); + this.info = bind(parent, bindings, "info"); + this.debug = bind(parent, bindings, "debug"); + this.trace = bind(parent, bindings, "trace"); + if (childSerializers) { + this.serializers = childSerializers; + this._serialize = childSerialize; + } + if (transmit2) { + this._logEvent = createLogEventShape( + [].concat(parent._logEvent.bindings, bindings) + ); + } + } + Child.prototype = this; + return new Child(this); + } + return logger; + } + pino.levels = { + values: { + fatal: 60, + error: 50, + warn: 40, + info: 30, + debug: 20, + trace: 10 + }, + labels: { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal" + } + }; + pino.stdSerializers = stdSerializers; + pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime }); + function set2(opts, logger, level, fallback) { + const proto = Object.getPrototypeOf(logger); + logger[level] = logger.levelVal > logger.levels.values[level] ? noop : proto[level] ? proto[level] : _console[level] || _console[fallback] || noop; + wrap(opts, logger, level); + } + function wrap(opts, logger, level) { + if (!opts.transmit && logger[level] === noop) + return; + logger[level] = /* @__PURE__ */ function(write) { + return function LOG() { + const ts = opts.timestamp(); + const args = new Array(arguments.length); + const proto = Object.getPrototypeOf && Object.getPrototypeOf(this) === _console ? _console : this; + for (var i2 = 0; i2 < args.length; i2++) + args[i2] = arguments[i2]; + if (opts.serialize && !opts.asObject) { + applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize); + } + if (opts.asObject) + write.call(proto, asObject(this, level, args, ts)); + else + write.apply(proto, args); + if (opts.transmit) { + const transmitLevel = opts.transmit.level || logger.level; + const transmitValue = pino.levels.values[transmitLevel]; + const methodValue = pino.levels.values[level]; + if (methodValue < transmitValue) + return; + transmit(this, { + ts, + methodLevel: level, + methodValue, + transmitLevel, + transmitValue: pino.levels.values[opts.transmit.level || logger.level], + send: opts.transmit.send, + val: logger.levelVal + }, args); + } + }; + }(logger[level]); + } + function asObject(logger, level, args, ts) { + if (logger._serialize) + applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize); + const argsCloned = args.slice(); + let msg = argsCloned[0]; + const o2 = {}; + if (ts) { + o2.time = ts; + } + o2.level = pino.levels.values[level]; + let lvl = (logger._childLevel | 0) + 1; + if (lvl < 1) + lvl = 1; + if (msg !== null && typeof msg === "object") { + while (lvl-- && typeof argsCloned[0] === "object") { + Object.assign(o2, argsCloned.shift()); + } + msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : void 0; + } else if (typeof msg === "string") + msg = format(argsCloned.shift(), argsCloned); + if (msg !== void 0) + o2.msg = msg; + return o2; + } + function applySerializers(args, serialize, serializers, stdErrSerialize) { + for (const i2 in args) { + if (stdErrSerialize && args[i2] instanceof Error) { + args[i2] = pino.stdSerializers.err(args[i2]); + } else if (typeof args[i2] === "object" && !Array.isArray(args[i2])) { + for (const k4 in args[i2]) { + if (serialize && serialize.indexOf(k4) > -1 && k4 in serializers) { + args[i2][k4] = serializers[k4](args[i2][k4]); + } + } + } + } + } + function bind(parent, bindings, level) { + return function() { + const args = new Array(1 + arguments.length); + args[0] = bindings; + for (var i2 = 1; i2 < args.length; i2++) { + args[i2] = arguments[i2 - 1]; + } + return parent[level].apply(this, args); + }; + } + function transmit(logger, opts, args) { + const send = opts.send; + const ts = opts.ts; + const methodLevel = opts.methodLevel; + const methodValue = opts.methodValue; + const val = opts.val; + const bindings = logger._logEvent.bindings; + applySerializers( + args, + logger._serialize || Object.keys(logger.serializers), + logger.serializers, + logger._stdErrSerialize === void 0 ? true : logger._stdErrSerialize + ); + logger._logEvent.ts = ts; + logger._logEvent.messages = args.filter(function(arg) { + return bindings.indexOf(arg) === -1; + }); + logger._logEvent.level.label = methodLevel; + logger._logEvent.level.value = methodValue; + send(methodLevel, logger._logEvent, val); + logger._logEvent = createLogEventShape(bindings); + } + function createLogEventShape(bindings) { + return { + ts: 0, + messages: [], + bindings: bindings || [], + level: { label: "", value: 0 } + }; + } + function asErrValue(err) { + const obj = { + type: err.constructor.name, + msg: err.message, + stack: err.stack + }; + for (const key in err) { + if (obj[key] === void 0) { + obj[key] = err[key]; + } + } + return obj; + } + function getTimeFunction(opts) { + if (typeof opts.timestamp === "function") { + return opts.timestamp; + } + if (opts.timestamp === false) { + return nullTime; + } + return epochTime; + } + function mock() { + return {}; + } + function passthrough(a3) { + return a3; + } + function noop() { + } + function nullTime() { + return false; + } + function epochTime() { + return Date.now(); + } + function unixTime() { + return Math.round(Date.now() / 1e3); + } + function isoTime() { + return new Date(Date.now()).toISOString(); + } + function pfGlobalThisOrFallback() { + function defd(o2) { + return typeof o2 !== "undefined" && o2; + } + try { + if (typeof globalThis !== "undefined") + return globalThis; + Object.defineProperty(Object.prototype, "globalThis", { + get: function() { + delete Object.prototype.globalThis; + return this.globalThis = this; + }, + configurable: true + }); + return globalThis; + } catch (e2) { + return defd(self) || defd(window) || defd(this) || {}; + } + } + } +}); + +// node_modules/@walletconnect/logger/dist/index.es.js +var index_es_exports2 = {}; +__export(index_es_exports2, { + MAX_LOG_SIZE_IN_BYTES_DEFAULT: () => l2, + PINO_CUSTOM_CONTEXT_KEY: () => n, + PINO_LOGGER_DEFAULTS: () => c2, + formatChildLoggerContext: () => w, + generateChildLogger: () => E2, + generateClientLogger: () => C, + generatePlatformLogger: () => A, + generateServerLogger: () => I, + getBrowserLoggerContext: () => v, + getDefaultLoggerOptions: () => k2, + getLoggerContext: () => y2, + pino: () => import_pino2.default, + setBrowserLoggerContext: () => b +}); +function k2(r) { + return g(i({}, r), { level: r?.level || c2.level }); +} +function v(r, e2 = n) { + return r[e2] || ""; +} +function b(r, e2, t = n) { + return r[t] = e2, r; +} +function y2(r, e2 = n) { + let t = ""; + return typeof r.bindings > "u" ? t = v(r, e2) : t = r.bindings().context || "", t; +} +function w(r, e2, t = n) { + const o2 = y2(r, t); + return o2.trim() ? `${o2}/${e2}` : e2; +} +function E2(r, e2, t = n) { + const o2 = w(r, e2, t), a3 = r.child({ context: o2 }); + return b(a3, o2, t); +} +function C(r) { + var e2, t; + const o2 = new m((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); + return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace", browser: g(i({}, (t = r.opts) == null ? void 0 : t.browser), { write: (a3) => o2.write(a3) }) })), chunkLoggerController: o2 }; +} +function I(r) { + var e2; + const t = new B((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); + return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace" }), t), chunkLoggerController: t }; +} +function A(r) { + return typeof r.loggerOverride < "u" && typeof r.loggerOverride != "string" ? { logger: r.loggerOverride, chunkLoggerController: null } : typeof window < "u" ? C(r) : I(r); +} +var import_pino, import_pino2, c2, n, l2, O2, d, L, m, B, x2, S, _2, p, T, z2, f, i, g; +var init_index_es2 = __esm({ + "node_modules/@walletconnect/logger/dist/index.es.js"() { + init_shim(); + import_pino = __toESM(require_browser3()); + import_pino2 = __toESM(require_browser3()); + init_esm(); + c2 = { level: "info" }; + n = "custom_context"; + l2 = 1e3 * 1024; + O2 = class { + constructor(e2) { + this.nodeValue = e2, this.sizeInBytes = new TextEncoder().encode(this.nodeValue).length, this.next = null; + } + get value() { + return this.nodeValue; + } + get size() { + return this.sizeInBytes; + } + }; + d = class { + constructor(e2) { + this.head = null, this.tail = null, this.lengthInNodes = 0, this.maxSizeInBytes = e2, this.sizeInBytes = 0; + } + append(e2) { + const t = new O2(e2); + if (t.size > this.maxSizeInBytes) + throw new Error(`[LinkedList] Value too big to insert into list: ${e2} with size ${t.size}`); + for (; this.size + t.size > this.maxSizeInBytes; ) + this.shift(); + this.head ? (this.tail && (this.tail.next = t), this.tail = t) : (this.head = t, this.tail = t), this.lengthInNodes++, this.sizeInBytes += t.size; + } + shift() { + if (!this.head) + return; + const e2 = this.head; + this.head = this.head.next, this.head || (this.tail = null), this.lengthInNodes--, this.sizeInBytes -= e2.size; + } + toArray() { + const e2 = []; + let t = this.head; + for (; t !== null; ) + e2.push(t.value), t = t.next; + return e2; + } + get length() { + return this.lengthInNodes; + } + get size() { + return this.sizeInBytes; + } + toOrderedArray() { + return Array.from(this); + } + [Symbol.iterator]() { + let e2 = this.head; + return { next: () => { + if (!e2) + return { done: true, value: null }; + const t = e2.value; + return e2 = e2.next, { done: false, value: t }; + } }; + } + }; + L = class { + constructor(e2, t = l2) { + this.level = e2 ?? "error", this.levelValue = import_pino.levels.values[this.level], this.MAX_LOG_SIZE_IN_BYTES = t, this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); + } + forwardToConsole(e2, t) { + t === import_pino.levels.values.error ? console.error(e2) : t === import_pino.levels.values.warn ? console.warn(e2) : t === import_pino.levels.values.debug ? console.debug(e2) : t === import_pino.levels.values.trace ? console.trace(e2) : console.log(e2); + } + appendToLogs(e2) { + this.logs.append(safeJsonStringify({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), log: e2 })); + const t = typeof e2 == "string" ? JSON.parse(e2).level : e2.level; + t >= this.levelValue && this.forwardToConsole(e2, t); + } + getLogs() { + return this.logs; + } + clearLogs() { + this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); + } + getLogArray() { + return Array.from(this.logs); + } + logsToBlob(e2) { + const t = this.getLogArray(); + return t.push(safeJsonStringify({ extraMetadata: e2 })), new Blob(t, { type: "application/json" }); + } + }; + m = class { + constructor(e2, t = l2) { + this.baseChunkLogger = new L(e2, t); + } + write(e2) { + this.baseChunkLogger.appendToLogs(e2); + } + getLogs() { + return this.baseChunkLogger.getLogs(); + } + clearLogs() { + this.baseChunkLogger.clearLogs(); + } + getLogArray() { + return this.baseChunkLogger.getLogArray(); + } + logsToBlob(e2) { + return this.baseChunkLogger.logsToBlob(e2); + } + downloadLogsBlobInBrowser(e2) { + const t = URL.createObjectURL(this.logsToBlob(e2)), o2 = document.createElement("a"); + o2.href = t, o2.download = `walletconnect-logs-${(/* @__PURE__ */ new Date()).toISOString()}.txt`, document.body.appendChild(o2), o2.click(), document.body.removeChild(o2), URL.revokeObjectURL(t); + } + }; + B = class { + constructor(e2, t = l2) { + this.baseChunkLogger = new L(e2, t); + } + write(e2) { + this.baseChunkLogger.appendToLogs(e2); + } + getLogs() { + return this.baseChunkLogger.getLogs(); + } + clearLogs() { + this.baseChunkLogger.clearLogs(); + } + getLogArray() { + return this.baseChunkLogger.getLogArray(); + } + logsToBlob(e2) { + return this.baseChunkLogger.logsToBlob(e2); + } + }; + x2 = Object.defineProperty; + S = Object.defineProperties; + _2 = Object.getOwnPropertyDescriptors; + p = Object.getOwnPropertySymbols; + T = Object.prototype.hasOwnProperty; + z2 = Object.prototype.propertyIsEnumerable; + f = (r, e2, t) => e2 in r ? x2(r, e2, { enumerable: true, configurable: true, writable: true, value: t }) : r[e2] = t; + i = (r, e2) => { + for (var t in e2 || (e2 = {})) + T.call(e2, t) && f(r, t, e2[t]); + if (p) + for (var t of p(e2)) + z2.call(e2, t) && f(r, t, e2[t]); + return r; + }; + g = (r, e2) => S(r, _2(e2)); + } +}); + +// node_modules/@walletconnect/types/dist/index.cjs.js +var require_index_cjs = __commonJS({ + "node_modules/@walletconnect/types/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var r = (init_esm2(), __toCommonJS(esm_exports2)); + var c4 = require_events(); + function i2(t) { + return t && typeof t == "object" && "default" in t ? t : { default: t }; + } + var n3 = i2(c4); + var l4 = class extends r.IEvents { + constructor(s2) { + super(), this.opts = s2, this.protocol = "wc", this.version = 2; + } + }; + var a3 = class { + constructor(s2, e2, o2) { + this.core = s2, this.logger = e2; + } + }; + var u3 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.core = s2, this.logger = e2, this.records = /* @__PURE__ */ new Map(); + } + }; + var I2 = class { + constructor(s2, e2) { + this.logger = s2, this.core = e2; + } + }; + var h5 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.relayer = s2, this.logger = e2; + } + }; + var g3 = class extends r.IEvents { + constructor(s2) { + super(); + } + }; + var p3 = class { + constructor(s2, e2, o2, _4) { + this.core = s2, this.logger = e2, this.name = o2; + } + }; + var E4 = class { + constructor() { + this.map = /* @__PURE__ */ new Map(); + } + }; + var v2 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.relayer = s2, this.logger = e2; + } + }; + var d3 = class { + constructor(s2, e2) { + this.core = s2, this.logger = e2; + } + }; + var y4 = class extends r.IEvents { + constructor(s2, e2) { + super(), this.core = s2, this.logger = e2; + } + }; + var b4 = class { + constructor(s2, e2) { + this.logger = s2, this.core = e2; + } + }; + var C3 = class { + constructor(s2, e2) { + this.projectId = s2, this.logger = e2; + } + }; + var f4 = class { + constructor(s2, e2) { + this.projectId = s2, this.logger = e2; + } + }; + var x3 = class extends n3.default { + constructor() { + super(); + } + }; + var S4 = class { + constructor(s2) { + this.opts = s2, this.protocol = "wc", this.version = 2; + } + }; + var M = class extends c4.EventEmitter { + constructor() { + super(); + } + }; + var P2 = class { + constructor(s2) { + this.client = s2; + } + }; + exports2.ICore = l4, exports2.ICrypto = a3, exports2.IEchoClient = f4, exports2.IEngine = P2, exports2.IEngineEvents = M, exports2.IExpirer = y4, exports2.IJsonRpcHistory = u3, exports2.IKeyChain = d3, exports2.IMessageTracker = I2, exports2.IPairing = b4, exports2.IPublisher = h5, exports2.IRelayer = g3, exports2.ISignClient = S4, exports2.ISignClientEvents = x3, exports2.IStore = p3, exports2.ISubscriber = v2, exports2.ISubscriberTopicMap = E4, exports2.IVerify = C3; + } +}); + +// node_modules/@stablelib/random/lib/source/browser.js +var require_browser4 = __commonJS({ + "node_modules/@stablelib/random/lib/source/browser.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.BrowserRandomSource = void 0; + var QUOTA = 65536; + var BrowserRandomSource = class { + constructor() { + this.isAvailable = false; + this.isInstantiated = false; + const browserCrypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; + if (browserCrypto && browserCrypto.getRandomValues !== void 0) { + this._crypto = browserCrypto; + this.isAvailable = true; + this.isInstantiated = true; + } + } + randomBytes(length2) { + if (!this.isAvailable || !this._crypto) { + throw new Error("Browser random byte generator is not available."); + } + const out = new Uint8Array(length2); + for (let i2 = 0; i2 < out.length; i2 += QUOTA) { + this._crypto.getRandomValues(out.subarray(i2, i2 + Math.min(out.length - i2, QUOTA))); + } + return out; + } + }; + exports2.BrowserRandomSource = BrowserRandomSource; + } +}); + +// node_modules/@stablelib/wipe/lib/wipe.js +var require_wipe = __commonJS({ + "node_modules/@stablelib/wipe/lib/wipe.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function wipe(array) { + for (var i2 = 0; i2 < array.length; i2++) { + array[i2] = 0; + } + return array; + } + exports2.wipe = wipe; + } +}); + +// (disabled):crypto +var require_crypto = __commonJS({ + "(disabled):crypto"() { + init_shim(); + } +}); + +// node_modules/@stablelib/random/lib/source/node.js +var require_node = __commonJS({ + "node_modules/@stablelib/random/lib/source/node.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NodeRandomSource = void 0; + var wipe_1 = require_wipe(); + var NodeRandomSource = class { + constructor() { + this.isAvailable = false; + this.isInstantiated = false; + if (typeof __require !== "undefined") { + const nodeCrypto = require_crypto(); + if (nodeCrypto && nodeCrypto.randomBytes) { + this._crypto = nodeCrypto; + this.isAvailable = true; + this.isInstantiated = true; + } + } + } + randomBytes(length2) { + if (!this.isAvailable || !this._crypto) { + throw new Error("Node.js random byte generator is not available."); + } + let buffer = this._crypto.randomBytes(length2); + if (buffer.length !== length2) { + throw new Error("NodeRandomSource: got fewer bytes than requested"); + } + const out = new Uint8Array(length2); + for (let i2 = 0; i2 < out.length; i2++) { + out[i2] = buffer[i2]; + } + (0, wipe_1.wipe)(buffer); + return out; + } + }; + exports2.NodeRandomSource = NodeRandomSource; + } +}); + +// node_modules/@stablelib/random/lib/source/system.js +var require_system = __commonJS({ + "node_modules/@stablelib/random/lib/source/system.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SystemRandomSource = void 0; + var browser_1 = require_browser4(); + var node_1 = require_node(); + var SystemRandomSource = class { + constructor() { + this.isAvailable = false; + this.name = ""; + this._source = new browser_1.BrowserRandomSource(); + if (this._source.isAvailable) { + this.isAvailable = true; + this.name = "Browser"; + return; + } + this._source = new node_1.NodeRandomSource(); + if (this._source.isAvailable) { + this.isAvailable = true; + this.name = "Node"; + return; + } + } + randomBytes(length2) { + if (!this.isAvailable) { + throw new Error("System random byte generator is not available."); + } + return this._source.randomBytes(length2); + } + }; + exports2.SystemRandomSource = SystemRandomSource; + } +}); + +// node_modules/@stablelib/int/lib/int.js +var require_int = __commonJS({ + "node_modules/@stablelib/int/lib/int.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function imulShim(a3, b4) { + var ah = a3 >>> 16 & 65535, al = a3 & 65535; + var bh = b4 >>> 16 & 65535, bl = b4 & 65535; + return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; + } + exports2.mul = Math.imul || imulShim; + function add(a3, b4) { + return a3 + b4 | 0; + } + exports2.add = add; + function sub(a3, b4) { + return a3 - b4 | 0; + } + exports2.sub = sub; + function rotl(x3, n3) { + return x3 << n3 | x3 >>> 32 - n3; + } + exports2.rotl = rotl; + function rotr(x3, n3) { + return x3 << 32 - n3 | x3 >>> n3; + } + exports2.rotr = rotr; + function isIntegerShim(n3) { + return typeof n3 === "number" && isFinite(n3) && Math.floor(n3) === n3; + } + exports2.isInteger = Number.isInteger || isIntegerShim; + exports2.MAX_SAFE_INTEGER = 9007199254740991; + exports2.isSafeInteger = function(n3) { + return exports2.isInteger(n3) && (n3 >= -exports2.MAX_SAFE_INTEGER && n3 <= exports2.MAX_SAFE_INTEGER); + }; + } +}); + +// node_modules/@stablelib/binary/lib/binary.js +var require_binary2 = __commonJS({ + "node_modules/@stablelib/binary/lib/binary.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var int_1 = require_int(); + function readInt16BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 0] << 8 | array[offset + 1]) << 16 >> 16; + } + exports2.readInt16BE = readInt16BE; + function readUint16BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 0] << 8 | array[offset + 1]) >>> 0; + } + exports2.readUint16BE = readUint16BE; + function readInt16LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 1] << 8 | array[offset]) << 16 >> 16; + } + exports2.readInt16LE = readInt16LE; + function readUint16LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 1] << 8 | array[offset]) >>> 0; + } + exports2.readUint16LE = readUint16LE; + function writeUint16BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(2); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 8; + out[offset + 1] = value >>> 0; + return out; + } + exports2.writeUint16BE = writeUint16BE; + exports2.writeInt16BE = writeUint16BE; + function writeUint16LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(2); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 0; + out[offset + 1] = value >>> 8; + return out; + } + exports2.writeUint16LE = writeUint16LE; + exports2.writeInt16LE = writeUint16LE; + function readInt32BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]; + } + exports2.readInt32BE = readInt32BE; + function readUint32BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]) >>> 0; + } + exports2.readUint32BE = readUint32BE; + function readInt32LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]; + } + exports2.readInt32LE = readInt32LE; + function readUint32LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + return (array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]) >>> 0; + } + exports2.readUint32LE = readUint32LE; + function writeUint32BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 24; + out[offset + 1] = value >>> 16; + out[offset + 2] = value >>> 8; + out[offset + 3] = value >>> 0; + return out; + } + exports2.writeUint32BE = writeUint32BE; + exports2.writeInt32BE = writeUint32BE; + function writeUint32LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + out[offset + 0] = value >>> 0; + out[offset + 1] = value >>> 8; + out[offset + 2] = value >>> 16; + out[offset + 3] = value >>> 24; + return out; + } + exports2.writeUint32LE = writeUint32LE; + exports2.writeInt32LE = writeUint32LE; + function readInt64BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var hi = readInt32BE(array, offset); + var lo = readInt32BE(array, offset + 4); + return hi * 4294967296 + lo - (lo >> 31) * 4294967296; + } + exports2.readInt64BE = readInt64BE; + function readUint64BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var hi = readUint32BE(array, offset); + var lo = readUint32BE(array, offset + 4); + return hi * 4294967296 + lo; + } + exports2.readUint64BE = readUint64BE; + function readInt64LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var lo = readInt32LE(array, offset); + var hi = readInt32LE(array, offset + 4); + return hi * 4294967296 + lo - (lo >> 31) * 4294967296; + } + exports2.readInt64LE = readInt64LE; + function readUint64LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var lo = readUint32LE(array, offset); + var hi = readUint32LE(array, offset + 4); + return hi * 4294967296 + lo; + } + exports2.readUint64LE = readUint64LE; + function writeUint64BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + writeUint32BE(value / 4294967296 >>> 0, out, offset); + writeUint32BE(value >>> 0, out, offset + 4); + return out; + } + exports2.writeUint64BE = writeUint64BE; + exports2.writeInt64BE = writeUint64BE; + function writeUint64LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + writeUint32LE(value >>> 0, out, offset); + writeUint32LE(value / 4294967296 >>> 0, out, offset + 4); + return out; + } + exports2.writeUint64LE = writeUint64LE; + exports2.writeInt64LE = writeUint64LE; + function readUintBE(bitLength, array, offset) { + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("readUintBE supports only bitLengths divisible by 8"); + } + if (bitLength / 8 > array.length - offset) { + throw new Error("readUintBE: array is too short for the given bitLength"); + } + var result = 0; + var mul = 1; + for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { + result += array[i2] * mul; + mul *= 256; + } + return result; + } + exports2.readUintBE = readUintBE; + function readUintLE(bitLength, array, offset) { + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("readUintLE supports only bitLengths divisible by 8"); + } + if (bitLength / 8 > array.length - offset) { + throw new Error("readUintLE: array is too short for the given bitLength"); + } + var result = 0; + var mul = 1; + for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { + result += array[i2] * mul; + mul *= 256; + } + return result; + } + exports2.readUintLE = readUintLE; + function writeUintBE(bitLength, value, out, offset) { + if (out === void 0) { + out = new Uint8Array(bitLength / 8); + } + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("writeUintBE supports only bitLengths divisible by 8"); + } + if (!int_1.isSafeInteger(value)) { + throw new Error("writeUintBE value must be an integer"); + } + var div = 1; + for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { + out[i2] = value / div & 255; + div *= 256; + } + return out; + } + exports2.writeUintBE = writeUintBE; + function writeUintLE(bitLength, value, out, offset) { + if (out === void 0) { + out = new Uint8Array(bitLength / 8); + } + if (offset === void 0) { + offset = 0; + } + if (bitLength % 8 !== 0) { + throw new Error("writeUintLE supports only bitLengths divisible by 8"); + } + if (!int_1.isSafeInteger(value)) { + throw new Error("writeUintLE value must be an integer"); + } + var div = 1; + for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { + out[i2] = value / div & 255; + div *= 256; + } + return out; + } + exports2.writeUintLE = writeUintLE; + function readFloat32BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat32(offset); + } + exports2.readFloat32BE = readFloat32BE; + function readFloat32LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat32(offset, true); + } + exports2.readFloat32LE = readFloat32LE; + function readFloat64BE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat64(offset); + } + exports2.readFloat64BE = readFloat64BE; + function readFloat64LE(array, offset) { + if (offset === void 0) { + offset = 0; + } + var view = new DataView(array.buffer, array.byteOffset, array.byteLength); + return view.getFloat64(offset, true); + } + exports2.readFloat64LE = readFloat64LE; + function writeFloat32BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat32(offset, value); + return out; + } + exports2.writeFloat32BE = writeFloat32BE; + function writeFloat32LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(4); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat32(offset, value, true); + return out; + } + exports2.writeFloat32LE = writeFloat32LE; + function writeFloat64BE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat64(offset, value); + return out; + } + exports2.writeFloat64BE = writeFloat64BE; + function writeFloat64LE(value, out, offset) { + if (out === void 0) { + out = new Uint8Array(8); + } + if (offset === void 0) { + offset = 0; + } + var view = new DataView(out.buffer, out.byteOffset, out.byteLength); + view.setFloat64(offset, value, true); + return out; + } + exports2.writeFloat64LE = writeFloat64LE; + } +}); + +// node_modules/@stablelib/random/lib/random.js +var require_random = __commonJS({ + "node_modules/@stablelib/random/lib/random.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.randomStringForEntropy = exports2.randomString = exports2.randomUint32 = exports2.randomBytes = exports2.defaultRandomSource = void 0; + var system_1 = require_system(); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + exports2.defaultRandomSource = new system_1.SystemRandomSource(); + function randomBytes2(length2, prng = exports2.defaultRandomSource) { + return prng.randomBytes(length2); + } + exports2.randomBytes = randomBytes2; + function randomUint32(prng = exports2.defaultRandomSource) { + const buf = randomBytes2(4, prng); + const result = (0, binary_1.readUint32LE)(buf); + (0, wipe_1.wipe)(buf); + return result; + } + exports2.randomUint32 = randomUint32; + var ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + function randomString(length2, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { + if (charset.length < 2) { + throw new Error("randomString charset is too short"); + } + if (charset.length > 256) { + throw new Error("randomString charset is too long"); + } + let out = ""; + const charsLen = charset.length; + const maxByte = 256 - 256 % charsLen; + while (length2 > 0) { + const buf = randomBytes2(Math.ceil(length2 * 256 / maxByte), prng); + for (let i2 = 0; i2 < buf.length && length2 > 0; i2++) { + const randomByte = buf[i2]; + if (randomByte < maxByte) { + out += charset.charAt(randomByte % charsLen); + length2--; + } + } + (0, wipe_1.wipe)(buf); + } + return out; + } + exports2.randomString = randomString; + function randomStringForEntropy(bits, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { + const length2 = Math.ceil(bits / (Math.log(charset.length) / Math.LN2)); + return randomString(length2, charset, prng); + } + exports2.randomStringForEntropy = randomStringForEntropy; + } +}); + +// node_modules/@stablelib/sha512/lib/sha512.js +var require_sha512 = __commonJS({ + "node_modules/@stablelib/sha512/lib/sha512.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + exports2.DIGEST_LENGTH = 64; + exports2.BLOCK_SIZE = 128; + var SHA512 = ( + /** @class */ + function() { + function SHA5122() { + this.digestLength = exports2.DIGEST_LENGTH; + this.blockSize = exports2.BLOCK_SIZE; + this._stateHi = new Int32Array(8); + this._stateLo = new Int32Array(8); + this._tempHi = new Int32Array(16); + this._tempLo = new Int32Array(16); + this._buffer = new Uint8Array(256); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + this.reset(); + } + SHA5122.prototype._initState = function() { + this._stateHi[0] = 1779033703; + this._stateHi[1] = 3144134277; + this._stateHi[2] = 1013904242; + this._stateHi[3] = 2773480762; + this._stateHi[4] = 1359893119; + this._stateHi[5] = 2600822924; + this._stateHi[6] = 528734635; + this._stateHi[7] = 1541459225; + this._stateLo[0] = 4089235720; + this._stateLo[1] = 2227873595; + this._stateLo[2] = 4271175723; + this._stateLo[3] = 1595750129; + this._stateLo[4] = 2917565137; + this._stateLo[5] = 725511199; + this._stateLo[6] = 4215389547; + this._stateLo[7] = 327033209; + }; + SHA5122.prototype.reset = function() { + this._initState(); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + return this; + }; + SHA5122.prototype.clean = function() { + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._tempHi); + wipe_1.wipe(this._tempLo); + this.reset(); + }; + SHA5122.prototype.update = function(data, dataLength) { + if (dataLength === void 0) { + dataLength = data.length; + } + if (this._finished) { + throw new Error("SHA512: can't update because hash was finished."); + } + var dataPos = 0; + this._bytesHashed += dataLength; + if (this._bufferLength > 0) { + while (this._bufferLength < exports2.BLOCK_SIZE && dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + if (this._bufferLength === this.blockSize) { + hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize); + this._bufferLength = 0; + } + } + if (dataLength >= this.blockSize) { + dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength); + dataLength %= this.blockSize; + } + while (dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + return this; + }; + SHA5122.prototype.finish = function(out) { + if (!this._finished) { + var bytesHashed = this._bytesHashed; + var left = this._bufferLength; + var bitLenHi = bytesHashed / 536870912 | 0; + var bitLenLo = bytesHashed << 3; + var padLength = bytesHashed % 128 < 112 ? 128 : 256; + this._buffer[left] = 128; + for (var i2 = left + 1; i2 < padLength - 8; i2++) { + this._buffer[i2] = 0; + } + binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); + binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); + hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength); + this._finished = true; + } + for (var i2 = 0; i2 < this.digestLength / 8; i2++) { + binary_1.writeUint32BE(this._stateHi[i2], out, i2 * 8); + binary_1.writeUint32BE(this._stateLo[i2], out, i2 * 8 + 4); + } + return this; + }; + SHA5122.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + SHA5122.prototype.saveState = function() { + if (this._finished) { + throw new Error("SHA256: cannot save finished state"); + } + return { + stateHi: new Int32Array(this._stateHi), + stateLo: new Int32Array(this._stateLo), + buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, + bufferLength: this._bufferLength, + bytesHashed: this._bytesHashed + }; + }; + SHA5122.prototype.restoreState = function(savedState) { + this._stateHi.set(savedState.stateHi); + this._stateLo.set(savedState.stateLo); + this._bufferLength = savedState.bufferLength; + if (savedState.buffer) { + this._buffer.set(savedState.buffer); + } + this._bytesHashed = savedState.bytesHashed; + this._finished = false; + return this; + }; + SHA5122.prototype.cleanSavedState = function(savedState) { + wipe_1.wipe(savedState.stateHi); + wipe_1.wipe(savedState.stateLo); + if (savedState.buffer) { + wipe_1.wipe(savedState.buffer); + } + savedState.bufferLength = 0; + savedState.bytesHashed = 0; + }; + return SHA5122; + }() + ); + exports2.SHA512 = SHA512; + var K2 = new Int32Array([ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 + ]); + function hashBlocks(wh, wl, hh, hl, m3, pos, len) { + var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; + var h5, l4; + var th, tl; + var a3, b4, c4, d3; + while (len >= 128) { + for (var i2 = 0; i2 < 16; i2++) { + var j2 = 8 * i2 + pos; + wh[i2] = binary_1.readUint32BE(m3, j2); + wl[i2] = binary_1.readUint32BE(m3, j2 + 4); + } + for (var i2 = 0; i2 < 80; i2++) { + var bh0 = ah0; + var bh1 = ah1; + var bh2 = ah2; + var bh3 = ah3; + var bh4 = ah4; + var bh5 = ah5; + var bh6 = ah6; + var bh7 = ah7; + var bl0 = al0; + var bl1 = al1; + var bl2 = al2; + var bl3 = al3; + var bl4 = al4; + var bl5 = al5; + var bl6 = al6; + var bl7 = al7; + h5 = ah7; + l4 = al7; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); + l4 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = ah4 & ah5 ^ ~ah4 & ah6; + l4 = al4 & al5 ^ ~al4 & al6; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = K2[i2 * 2]; + l4 = K2[i2 * 2 + 1]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = wh[i2 % 16]; + l4 = wl[i2 % 16]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + th = c4 & 65535 | d3 << 16; + tl = a3 & 65535 | b4 << 16; + h5 = th; + l4 = tl; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); + l4 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + h5 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; + l4 = al0 & al1 ^ al0 & al2 ^ al1 & al2; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + bh7 = c4 & 65535 | d3 << 16; + bl7 = a3 & 65535 | b4 << 16; + h5 = bh3; + l4 = bl3; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = th; + l4 = tl; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + bh3 = c4 & 65535 | d3 << 16; + bl3 = a3 & 65535 | b4 << 16; + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + if (i2 % 16 === 15) { + for (var j2 = 0; j2 < 16; j2++) { + h5 = wh[j2]; + l4 = wl[j2]; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = wh[(j2 + 9) % 16]; + l4 = wl[(j2 + 9) % 16]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + th = wh[(j2 + 1) % 16]; + tl = wl[(j2 + 1) % 16]; + h5 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; + l4 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + th = wh[(j2 + 14) % 16]; + tl = wl[(j2 + 14) % 16]; + h5 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; + l4 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + wh[j2] = c4 & 65535 | d3 << 16; + wl[j2] = a3 & 65535 | b4 << 16; + } + } + } + h5 = ah0; + l4 = al0; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[0]; + l4 = hl[0]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[0] = ah0 = c4 & 65535 | d3 << 16; + hl[0] = al0 = a3 & 65535 | b4 << 16; + h5 = ah1; + l4 = al1; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[1]; + l4 = hl[1]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[1] = ah1 = c4 & 65535 | d3 << 16; + hl[1] = al1 = a3 & 65535 | b4 << 16; + h5 = ah2; + l4 = al2; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[2]; + l4 = hl[2]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[2] = ah2 = c4 & 65535 | d3 << 16; + hl[2] = al2 = a3 & 65535 | b4 << 16; + h5 = ah3; + l4 = al3; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[3]; + l4 = hl[3]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[3] = ah3 = c4 & 65535 | d3 << 16; + hl[3] = al3 = a3 & 65535 | b4 << 16; + h5 = ah4; + l4 = al4; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[4]; + l4 = hl[4]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[4] = ah4 = c4 & 65535 | d3 << 16; + hl[4] = al4 = a3 & 65535 | b4 << 16; + h5 = ah5; + l4 = al5; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[5]; + l4 = hl[5]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[5] = ah5 = c4 & 65535 | d3 << 16; + hl[5] = al5 = a3 & 65535 | b4 << 16; + h5 = ah6; + l4 = al6; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[6]; + l4 = hl[6]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[6] = ah6 = c4 & 65535 | d3 << 16; + hl[6] = al6 = a3 & 65535 | b4 << 16; + h5 = ah7; + l4 = al7; + a3 = l4 & 65535; + b4 = l4 >>> 16; + c4 = h5 & 65535; + d3 = h5 >>> 16; + h5 = hh[7]; + l4 = hl[7]; + a3 += l4 & 65535; + b4 += l4 >>> 16; + c4 += h5 & 65535; + d3 += h5 >>> 16; + b4 += a3 >>> 16; + c4 += b4 >>> 16; + d3 += c4 >>> 16; + hh[7] = ah7 = c4 & 65535 | d3 << 16; + hl[7] = al7 = a3 & 65535 | b4 << 16; + pos += 128; + len -= 128; + } + return pos; + } + function hash(data) { + var h5 = new SHA512(); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.hash = hash; + } +}); + +// node_modules/@stablelib/ed25519/lib/ed25519.js +var require_ed25519 = __commonJS({ + "node_modules/@stablelib/ed25519/lib/ed25519.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.convertSecretKeyToX25519 = exports2.convertPublicKeyToX25519 = exports2.verify = exports2.sign = exports2.extractPublicKeyFromSecretKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.SEED_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = exports2.SIGNATURE_LENGTH = void 0; + var random_1 = require_random(); + var sha512_1 = require_sha512(); + var wipe_1 = require_wipe(); + exports2.SIGNATURE_LENGTH = 64; + exports2.PUBLIC_KEY_LENGTH = 32; + exports2.SECRET_KEY_LENGTH = 64; + exports2.SEED_LENGTH = 32; + function gf(init) { + const r = new Float64Array(16); + if (init) { + for (let i2 = 0; i2 < init.length; i2++) { + r[i2] = init[i2]; + } + } + return r; + } + var _9 = new Uint8Array(32); + _9[0] = 9; + var gf0 = gf(); + var gf1 = gf([1]); + var D2 = gf([ + 30883, + 4953, + 19914, + 30187, + 55467, + 16705, + 2637, + 112, + 59544, + 30585, + 16505, + 36039, + 65139, + 11119, + 27886, + 20995 + ]); + var D22 = gf([ + 61785, + 9906, + 39828, + 60374, + 45398, + 33411, + 5274, + 224, + 53552, + 61171, + 33010, + 6542, + 64743, + 22239, + 55772, + 9222 + ]); + var X = gf([ + 54554, + 36645, + 11616, + 51542, + 42930, + 38181, + 51040, + 26924, + 56412, + 64982, + 57905, + 49316, + 21502, + 52590, + 14035, + 8553 + ]); + var Y = gf([ + 26200, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214, + 26214 + ]); + var I2 = gf([ + 41136, + 18958, + 6951, + 50414, + 58488, + 44335, + 6150, + 12099, + 55207, + 15867, + 153, + 11085, + 57099, + 20417, + 9344, + 11139 + ]); + function set25519(r, a3) { + for (let i2 = 0; i2 < 16; i2++) { + r[i2] = a3[i2] | 0; + } + } + function car25519(o2) { + let c4 = 1; + for (let i2 = 0; i2 < 16; i2++) { + let v2 = o2[i2] + c4 + 65535; + c4 = Math.floor(v2 / 65536); + o2[i2] = v2 - c4 * 65536; + } + o2[0] += c4 - 1 + 37 * (c4 - 1); + } + function sel25519(p3, q2, b4) { + const c4 = ~(b4 - 1); + for (let i2 = 0; i2 < 16; i2++) { + const t = c4 & (p3[i2] ^ q2[i2]); + p3[i2] ^= t; + q2[i2] ^= t; + } + } + function pack25519(o2, n3) { + const m3 = gf(); + const t = gf(); + for (let i2 = 0; i2 < 16; i2++) { + t[i2] = n3[i2]; + } + car25519(t); + car25519(t); + car25519(t); + for (let j2 = 0; j2 < 2; j2++) { + m3[0] = t[0] - 65517; + for (let i2 = 1; i2 < 15; i2++) { + m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); + m3[i2 - 1] &= 65535; + } + m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); + const b4 = m3[15] >> 16 & 1; + m3[14] &= 65535; + sel25519(t, m3, 1 - b4); + } + for (let i2 = 0; i2 < 16; i2++) { + o2[2 * i2] = t[i2] & 255; + o2[2 * i2 + 1] = t[i2] >> 8; + } + } + function verify32(x3, y4) { + let d3 = 0; + for (let i2 = 0; i2 < 32; i2++) { + d3 |= x3[i2] ^ y4[i2]; + } + return (1 & d3 - 1 >>> 8) - 1; + } + function neq25519(a3, b4) { + const c4 = new Uint8Array(32); + const d3 = new Uint8Array(32); + pack25519(c4, a3); + pack25519(d3, b4); + return verify32(c4, d3); + } + function par25519(a3) { + const d3 = new Uint8Array(32); + pack25519(d3, a3); + return d3[0] & 1; + } + function unpack25519(o2, n3) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); + } + o2[15] &= 32767; + } + function add(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] + b4[i2]; + } + } + function sub(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] - b4[i2]; + } + } + function mul(o2, a3, b4) { + let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; + v2 = a3[0]; + t0 += v2 * b0; + t1 += v2 * b1; + t2 += v2 * b22; + t3 += v2 * b32; + t4 += v2 * b42; + t5 += v2 * b5; + t6 += v2 * b6; + t7 += v2 * b7; + t8 += v2 * b8; + t9 += v2 * b9; + t10 += v2 * b10; + t11 += v2 * b11; + t12 += v2 * b12; + t13 += v2 * b13; + t14 += v2 * b14; + t15 += v2 * b15; + v2 = a3[1]; + t1 += v2 * b0; + t2 += v2 * b1; + t3 += v2 * b22; + t4 += v2 * b32; + t5 += v2 * b42; + t6 += v2 * b5; + t7 += v2 * b6; + t8 += v2 * b7; + t9 += v2 * b8; + t10 += v2 * b9; + t11 += v2 * b10; + t12 += v2 * b11; + t13 += v2 * b12; + t14 += v2 * b13; + t15 += v2 * b14; + t16 += v2 * b15; + v2 = a3[2]; + t2 += v2 * b0; + t3 += v2 * b1; + t4 += v2 * b22; + t5 += v2 * b32; + t6 += v2 * b42; + t7 += v2 * b5; + t8 += v2 * b6; + t9 += v2 * b7; + t10 += v2 * b8; + t11 += v2 * b9; + t12 += v2 * b10; + t13 += v2 * b11; + t14 += v2 * b12; + t15 += v2 * b13; + t16 += v2 * b14; + t17 += v2 * b15; + v2 = a3[3]; + t3 += v2 * b0; + t4 += v2 * b1; + t5 += v2 * b22; + t6 += v2 * b32; + t7 += v2 * b42; + t8 += v2 * b5; + t9 += v2 * b6; + t10 += v2 * b7; + t11 += v2 * b8; + t12 += v2 * b9; + t13 += v2 * b10; + t14 += v2 * b11; + t15 += v2 * b12; + t16 += v2 * b13; + t17 += v2 * b14; + t18 += v2 * b15; + v2 = a3[4]; + t4 += v2 * b0; + t5 += v2 * b1; + t6 += v2 * b22; + t7 += v2 * b32; + t8 += v2 * b42; + t9 += v2 * b5; + t10 += v2 * b6; + t11 += v2 * b7; + t12 += v2 * b8; + t13 += v2 * b9; + t14 += v2 * b10; + t15 += v2 * b11; + t16 += v2 * b12; + t17 += v2 * b13; + t18 += v2 * b14; + t19 += v2 * b15; + v2 = a3[5]; + t5 += v2 * b0; + t6 += v2 * b1; + t7 += v2 * b22; + t8 += v2 * b32; + t9 += v2 * b42; + t10 += v2 * b5; + t11 += v2 * b6; + t12 += v2 * b7; + t13 += v2 * b8; + t14 += v2 * b9; + t15 += v2 * b10; + t16 += v2 * b11; + t17 += v2 * b12; + t18 += v2 * b13; + t19 += v2 * b14; + t20 += v2 * b15; + v2 = a3[6]; + t6 += v2 * b0; + t7 += v2 * b1; + t8 += v2 * b22; + t9 += v2 * b32; + t10 += v2 * b42; + t11 += v2 * b5; + t12 += v2 * b6; + t13 += v2 * b7; + t14 += v2 * b8; + t15 += v2 * b9; + t16 += v2 * b10; + t17 += v2 * b11; + t18 += v2 * b12; + t19 += v2 * b13; + t20 += v2 * b14; + t21 += v2 * b15; + v2 = a3[7]; + t7 += v2 * b0; + t8 += v2 * b1; + t9 += v2 * b22; + t10 += v2 * b32; + t11 += v2 * b42; + t12 += v2 * b5; + t13 += v2 * b6; + t14 += v2 * b7; + t15 += v2 * b8; + t16 += v2 * b9; + t17 += v2 * b10; + t18 += v2 * b11; + t19 += v2 * b12; + t20 += v2 * b13; + t21 += v2 * b14; + t22 += v2 * b15; + v2 = a3[8]; + t8 += v2 * b0; + t9 += v2 * b1; + t10 += v2 * b22; + t11 += v2 * b32; + t12 += v2 * b42; + t13 += v2 * b5; + t14 += v2 * b6; + t15 += v2 * b7; + t16 += v2 * b8; + t17 += v2 * b9; + t18 += v2 * b10; + t19 += v2 * b11; + t20 += v2 * b12; + t21 += v2 * b13; + t22 += v2 * b14; + t23 += v2 * b15; + v2 = a3[9]; + t9 += v2 * b0; + t10 += v2 * b1; + t11 += v2 * b22; + t12 += v2 * b32; + t13 += v2 * b42; + t14 += v2 * b5; + t15 += v2 * b6; + t16 += v2 * b7; + t17 += v2 * b8; + t18 += v2 * b9; + t19 += v2 * b10; + t20 += v2 * b11; + t21 += v2 * b12; + t22 += v2 * b13; + t23 += v2 * b14; + t24 += v2 * b15; + v2 = a3[10]; + t10 += v2 * b0; + t11 += v2 * b1; + t12 += v2 * b22; + t13 += v2 * b32; + t14 += v2 * b42; + t15 += v2 * b5; + t16 += v2 * b6; + t17 += v2 * b7; + t18 += v2 * b8; + t19 += v2 * b9; + t20 += v2 * b10; + t21 += v2 * b11; + t22 += v2 * b12; + t23 += v2 * b13; + t24 += v2 * b14; + t25 += v2 * b15; + v2 = a3[11]; + t11 += v2 * b0; + t12 += v2 * b1; + t13 += v2 * b22; + t14 += v2 * b32; + t15 += v2 * b42; + t16 += v2 * b5; + t17 += v2 * b6; + t18 += v2 * b7; + t19 += v2 * b8; + t20 += v2 * b9; + t21 += v2 * b10; + t22 += v2 * b11; + t23 += v2 * b12; + t24 += v2 * b13; + t25 += v2 * b14; + t26 += v2 * b15; + v2 = a3[12]; + t12 += v2 * b0; + t13 += v2 * b1; + t14 += v2 * b22; + t15 += v2 * b32; + t16 += v2 * b42; + t17 += v2 * b5; + t18 += v2 * b6; + t19 += v2 * b7; + t20 += v2 * b8; + t21 += v2 * b9; + t22 += v2 * b10; + t23 += v2 * b11; + t24 += v2 * b12; + t25 += v2 * b13; + t26 += v2 * b14; + t27 += v2 * b15; + v2 = a3[13]; + t13 += v2 * b0; + t14 += v2 * b1; + t15 += v2 * b22; + t16 += v2 * b32; + t17 += v2 * b42; + t18 += v2 * b5; + t19 += v2 * b6; + t20 += v2 * b7; + t21 += v2 * b8; + t22 += v2 * b9; + t23 += v2 * b10; + t24 += v2 * b11; + t25 += v2 * b12; + t26 += v2 * b13; + t27 += v2 * b14; + t28 += v2 * b15; + v2 = a3[14]; + t14 += v2 * b0; + t15 += v2 * b1; + t16 += v2 * b22; + t17 += v2 * b32; + t18 += v2 * b42; + t19 += v2 * b5; + t20 += v2 * b6; + t21 += v2 * b7; + t22 += v2 * b8; + t23 += v2 * b9; + t24 += v2 * b10; + t25 += v2 * b11; + t26 += v2 * b12; + t27 += v2 * b13; + t28 += v2 * b14; + t29 += v2 * b15; + v2 = a3[15]; + t15 += v2 * b0; + t16 += v2 * b1; + t17 += v2 * b22; + t18 += v2 * b32; + t19 += v2 * b42; + t20 += v2 * b5; + t21 += v2 * b6; + t22 += v2 * b7; + t23 += v2 * b8; + t24 += v2 * b9; + t25 += v2 * b10; + t26 += v2 * b11; + t27 += v2 * b12; + t28 += v2 * b13; + t29 += v2 * b14; + t30 += v2 * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + o2[0] = t0; + o2[1] = t1; + o2[2] = t2; + o2[3] = t3; + o2[4] = t4; + o2[5] = t5; + o2[6] = t6; + o2[7] = t7; + o2[8] = t8; + o2[9] = t9; + o2[10] = t10; + o2[11] = t11; + o2[12] = t12; + o2[13] = t13; + o2[14] = t14; + o2[15] = t15; + } + function square(o2, a3) { + mul(o2, a3, a3); + } + function inv25519(o2, i2) { + const c4 = gf(); + let a3; + for (a3 = 0; a3 < 16; a3++) { + c4[a3] = i2[a3]; + } + for (a3 = 253; a3 >= 0; a3--) { + square(c4, c4); + if (a3 !== 2 && a3 !== 4) { + mul(c4, c4, i2); + } + } + for (a3 = 0; a3 < 16; a3++) { + o2[a3] = c4[a3]; + } + } + function pow2523(o2, i2) { + const c4 = gf(); + let a3; + for (a3 = 0; a3 < 16; a3++) { + c4[a3] = i2[a3]; + } + for (a3 = 250; a3 >= 0; a3--) { + square(c4, c4); + if (a3 !== 1) { + mul(c4, c4, i2); + } + } + for (a3 = 0; a3 < 16; a3++) { + o2[a3] = c4[a3]; + } + } + function edadd(p3, q2) { + const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(), g3 = gf(), h5 = gf(), t = gf(); + sub(a3, p3[1], p3[0]); + sub(t, q2[1], q2[0]); + mul(a3, a3, t); + add(b4, p3[0], p3[1]); + add(t, q2[0], q2[1]); + mul(b4, b4, t); + mul(c4, p3[3], q2[3]); + mul(c4, c4, D22); + mul(d3, p3[2], q2[2]); + add(d3, d3, d3); + sub(e2, b4, a3); + sub(f4, d3, c4); + add(g3, d3, c4); + add(h5, b4, a3); + mul(p3[0], e2, f4); + mul(p3[1], h5, g3); + mul(p3[2], g3, f4); + mul(p3[3], e2, h5); + } + function cswap(p3, q2, b4) { + for (let i2 = 0; i2 < 4; i2++) { + sel25519(p3[i2], q2[i2], b4); + } + } + function pack(r, p3) { + const tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p3[2]); + mul(tx, p3[0], zi); + mul(ty, p3[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; + } + function scalarmult(p3, q2, s2) { + set25519(p3[0], gf0); + set25519(p3[1], gf1); + set25519(p3[2], gf1); + set25519(p3[3], gf0); + for (let i2 = 255; i2 >= 0; --i2) { + const b4 = s2[i2 / 8 | 0] >> (i2 & 7) & 1; + cswap(p3, q2, b4); + edadd(q2, p3); + edadd(p3, p3); + cswap(p3, q2, b4); + } + } + function scalarbase(p3, s2) { + const q2 = [gf(), gf(), gf(), gf()]; + set25519(q2[0], X); + set25519(q2[1], Y); + set25519(q2[2], gf1); + mul(q2[3], X, Y); + scalarmult(p3, q2, s2); + } + function generateKeyPairFromSeed2(seed) { + if (seed.length !== exports2.SEED_LENGTH) { + throw new Error(`ed25519: seed must be ${exports2.SEED_LENGTH} bytes`); + } + const d3 = (0, sha512_1.hash)(seed); + d3[0] &= 248; + d3[31] &= 127; + d3[31] |= 64; + const publicKey = new Uint8Array(32); + const p3 = [gf(), gf(), gf(), gf()]; + scalarbase(p3, d3); + pack(publicKey, p3); + const secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, 32); + return { + publicKey, + secretKey + }; + } + exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; + function generateKeyPair2(prng) { + const seed = (0, random_1.randomBytes)(32, prng); + const result = generateKeyPairFromSeed2(seed); + (0, wipe_1.wipe)(seed); + return result; + } + exports2.generateKeyPair = generateKeyPair2; + function extractPublicKeyFromSecretKey(secretKey) { + if (secretKey.length !== exports2.SECRET_KEY_LENGTH) { + throw new Error(`ed25519: secret key must be ${exports2.SECRET_KEY_LENGTH} bytes`); + } + return new Uint8Array(secretKey.subarray(32)); + } + exports2.extractPublicKeyFromSecretKey = extractPublicKeyFromSecretKey; + var L2 = new Float64Array([ + 237, + 211, + 245, + 92, + 26, + 99, + 18, + 88, + 214, + 156, + 247, + 162, + 222, + 249, + 222, + 20, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 16 + ]); + function modL(r, x3) { + let carry; + let i2; + let j2; + let k4; + for (i2 = 63; i2 >= 32; --i2) { + carry = 0; + for (j2 = i2 - 32, k4 = i2 - 12; j2 < k4; ++j2) { + x3[j2] += carry - 16 * x3[i2] * L2[j2 - (i2 - 32)]; + carry = Math.floor((x3[j2] + 128) / 256); + x3[j2] -= carry * 256; + } + x3[j2] += carry; + x3[i2] = 0; + } + carry = 0; + for (j2 = 0; j2 < 32; j2++) { + x3[j2] += carry - (x3[31] >> 4) * L2[j2]; + carry = x3[j2] >> 8; + x3[j2] &= 255; + } + for (j2 = 0; j2 < 32; j2++) { + x3[j2] -= carry * L2[j2]; + } + for (i2 = 0; i2 < 32; i2++) { + x3[i2 + 1] += x3[i2] >> 8; + r[i2] = x3[i2] & 255; + } + } + function reduce(r) { + const x3 = new Float64Array(64); + for (let i2 = 0; i2 < 64; i2++) { + x3[i2] = r[i2]; + } + for (let i2 = 0; i2 < 64; i2++) { + r[i2] = 0; + } + modL(r, x3); + } + function sign2(secretKey, message) { + const x3 = new Float64Array(64); + const p3 = [gf(), gf(), gf(), gf()]; + const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); + d3[0] &= 248; + d3[31] &= 127; + d3[31] |= 64; + const signature = new Uint8Array(64); + signature.set(d3.subarray(32), 32); + const hs = new sha512_1.SHA512(); + hs.update(signature.subarray(32)); + hs.update(message); + const r = hs.digest(); + hs.clean(); + reduce(r); + scalarbase(p3, r); + pack(signature, p3); + hs.reset(); + hs.update(signature.subarray(0, 32)); + hs.update(secretKey.subarray(32)); + hs.update(message); + const h5 = hs.digest(); + reduce(h5); + for (let i2 = 0; i2 < 32; i2++) { + x3[i2] = r[i2]; + } + for (let i2 = 0; i2 < 32; i2++) { + for (let j2 = 0; j2 < 32; j2++) { + x3[i2 + j2] += h5[i2] * d3[j2]; + } + } + modL(signature.subarray(32), x3); + return signature; + } + exports2.sign = sign2; + function unpackneg(r, p3) { + const t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); + set25519(r[2], gf1); + unpack25519(r[1], p3); + square(num, r[1]); + mul(den, num, D2); + sub(num, num, r[2]); + add(den, r[2], den); + square(den2, den); + square(den4, den2); + mul(den6, den4, den2); + mul(t, den6, num); + mul(t, t, den); + pow2523(t, t); + mul(t, t, num); + mul(t, t, den); + mul(t, t, den); + mul(r[0], t, den); + square(chk, r[0]); + mul(chk, chk, den); + if (neq25519(chk, num)) { + mul(r[0], r[0], I2); + } + square(chk, r[0]); + mul(chk, chk, den); + if (neq25519(chk, num)) { + return -1; + } + if (par25519(r[0]) === p3[31] >> 7) { + sub(r[0], gf0, r[0]); + } + mul(r[3], r[0], r[1]); + return 0; + } + function verify2(publicKey, message, signature) { + const t = new Uint8Array(32); + const p3 = [gf(), gf(), gf(), gf()]; + const q2 = [gf(), gf(), gf(), gf()]; + if (signature.length !== exports2.SIGNATURE_LENGTH) { + throw new Error(`ed25519: signature must be ${exports2.SIGNATURE_LENGTH} bytes`); + } + if (unpackneg(q2, publicKey)) { + return false; + } + const hs = new sha512_1.SHA512(); + hs.update(signature.subarray(0, 32)); + hs.update(publicKey); + hs.update(message); + const h5 = hs.digest(); + reduce(h5); + scalarmult(p3, q2, h5); + scalarbase(q2, signature.subarray(32)); + edadd(p3, q2); + pack(t, p3); + if (verify32(signature, t)) { + return false; + } + return true; + } + exports2.verify = verify2; + function convertPublicKeyToX25519(publicKey) { + let q2 = [gf(), gf(), gf(), gf()]; + if (unpackneg(q2, publicKey)) { + throw new Error("Ed25519: invalid public key"); + } + let a3 = gf(); + let b4 = gf(); + let y4 = q2[1]; + add(a3, gf1, y4); + sub(b4, gf1, y4); + inv25519(b4, b4); + mul(a3, a3, b4); + let z3 = new Uint8Array(32); + pack25519(z3, a3); + return z3; + } + exports2.convertPublicKeyToX25519 = convertPublicKeyToX25519; + function convertSecretKeyToX25519(secretKey) { + const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); + d3[0] &= 248; + d3[31] &= 127; + d3[31] |= 64; + const o2 = new Uint8Array(d3.subarray(0, 32)); + (0, wipe_1.wipe)(d3); + return o2; + } + exports2.convertSecretKeyToX25519 = convertSecretKeyToX25519; + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/constants.js +var JWT_IRIDIUM_ALG, JWT_IRIDIUM_TYP, JWT_DELIMITER, JWT_ENCODING, JSON_ENCODING, DATA_ENCODING, DID_DELIMITER, DID_PREFIX, DID_METHOD, MULTICODEC_ED25519_ENCODING, MULTICODEC_ED25519_BASE, MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_LENGTH, KEY_PAIR_SEED_LENGTH; +var init_constants = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/constants.js"() { + init_shim(); + JWT_IRIDIUM_ALG = "EdDSA"; + JWT_IRIDIUM_TYP = "JWT"; + JWT_DELIMITER = "."; + JWT_ENCODING = "base64url"; + JSON_ENCODING = "utf8"; + DATA_ENCODING = "utf8"; + DID_DELIMITER = ":"; + DID_PREFIX = "did"; + DID_METHOD = "key"; + MULTICODEC_ED25519_ENCODING = "base58btc"; + MULTICODEC_ED25519_BASE = "z"; + MULTICODEC_ED25519_HEADER = "K36"; + MULTICODEC_ED25519_LENGTH = 32; + KEY_PAIR_SEED_LENGTH = 32; + } +}); + +// node_modules/uint8arrays/esm/src/util/as-uint8array.js +function asUint8Array(buf) { + if (globalThis.Buffer != null) { + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + return buf; +} +var init_as_uint8array = __esm({ + "node_modules/uint8arrays/esm/src/util/as-uint8array.js"() { + init_shim(); + } +}); + +// node_modules/uint8arrays/esm/src/alloc.js +function allocUnsafe(size = 0) { + if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) { + return asUint8Array(globalThis.Buffer.allocUnsafe(size)); + } + return new Uint8Array(size); +} +var init_alloc = __esm({ + "node_modules/uint8arrays/esm/src/alloc.js"() { + init_shim(); + init_as_uint8array(); + } +}); + +// node_modules/uint8arrays/esm/src/concat.js +function concat(arrays, length2) { + if (!length2) { + length2 = arrays.reduce((acc, curr) => acc + curr.length, 0); + } + const output = allocUnsafe(length2); + let offset = 0; + for (const arr of arrays) { + output.set(arr, offset); + offset += arr.length; + } + return asUint8Array(output); +} +var init_concat = __esm({ + "node_modules/uint8arrays/esm/src/concat.js"() { + init_shim(); + init_alloc(); + init_as_uint8array(); + } +}); + +// node_modules/multiformats/esm/vendor/base-x.js +function base(ALPHABET, name2) { + if (ALPHABET.length >= 255) { + throw new TypeError("Alphabet too long"); + } + var BASE_MAP = new Uint8Array(256); + for (var j2 = 0; j2 < BASE_MAP.length; j2++) { + BASE_MAP[j2] = 255; + } + for (var i2 = 0; i2 < ALPHABET.length; i2++) { + var x3 = ALPHABET.charAt(i2); + var xc = x3.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { + throw new TypeError(x3 + " is ambiguous"); + } + BASE_MAP[xc] = i2; + } + var BASE2 = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE2) / Math.log(256); + var iFACTOR = Math.log(256) / Math.log(BASE2); + function encode5(source) { + if (source instanceof Uint8Array) + ; + else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + } else if (Array.isArray(source)) { + source = Uint8Array.from(source); + } + if (!(source instanceof Uint8Array)) { + throw new TypeError("Expected Uint8Array"); + } + if (source.length === 0) { + return ""; + } + var zeroes = 0; + var length2 = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); + while (pbegin !== pend) { + var carry = source[pbegin]; + var i3 = 0; + for (var it1 = size - 1; (carry !== 0 || i3 < length2) && it1 !== -1; it1--, i3++) { + carry += 256 * b58[it1] >>> 0; + b58[it1] = carry % BASE2 >>> 0; + carry = carry / BASE2 >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length2 = i3; + pbegin++; + } + var it2 = size - length2; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { + str += ALPHABET.charAt(b58[it2]); + } + return str; + } + function decodeUnsafe(source) { + if (typeof source !== "string") { + throw new TypeError("Expected String"); + } + if (source.length === 0) { + return new Uint8Array(); + } + var psz = 0; + if (source[psz] === " ") { + return; + } + var zeroes = 0; + var length2 = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + var size = (source.length - psz) * FACTOR + 1 >>> 0; + var b256 = new Uint8Array(size); + while (source[psz]) { + var carry = BASE_MAP[source.charCodeAt(psz)]; + if (carry === 255) { + return; + } + var i3 = 0; + for (var it3 = size - 1; (carry !== 0 || i3 < length2) && it3 !== -1; it3--, i3++) { + carry += BASE2 * b256[it3] >>> 0; + b256[it3] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length2 = i3; + psz++; + } + if (source[psz] === " ") { + return; + } + var it4 = size - length2; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = new Uint8Array(zeroes + (size - it4)); + var j3 = zeroes; + while (it4 !== size) { + vch[j3++] = b256[it4++]; + } + return vch; + } + function decode6(string2) { + var buffer = decodeUnsafe(string2); + if (buffer) { + return buffer; + } + throw new Error(`Non-${name2} character`); + } + return { + encode: encode5, + decodeUnsafe, + decode: decode6 + }; +} +var src, _brrp__multiformats_scope_baseX, base_x_default; +var init_base_x = __esm({ + "node_modules/multiformats/esm/vendor/base-x.js"() { + init_shim(); + src = base; + _brrp__multiformats_scope_baseX = src; + base_x_default = _brrp__multiformats_scope_baseX; + } +}); + +// node_modules/multiformats/esm/src/bytes.js +var empty, equals, coerce, fromString, toString; +var init_bytes = __esm({ + "node_modules/multiformats/esm/src/bytes.js"() { + init_shim(); + empty = new Uint8Array(0); + equals = (aa, bb) => { + if (aa === bb) + return true; + if (aa.byteLength !== bb.byteLength) { + return false; + } + for (let ii = 0; ii < aa.byteLength; ii++) { + if (aa[ii] !== bb[ii]) { + return false; + } + } + return true; + }; + coerce = (o2) => { + if (o2 instanceof Uint8Array && o2.constructor.name === "Uint8Array") + return o2; + if (o2 instanceof ArrayBuffer) + return new Uint8Array(o2); + if (ArrayBuffer.isView(o2)) { + return new Uint8Array(o2.buffer, o2.byteOffset, o2.byteLength); + } + throw new Error("Unknown type, must be binary type"); + }; + fromString = (str) => new TextEncoder().encode(str); + toString = (b4) => new TextDecoder().decode(b4); + } +}); + +// node_modules/multiformats/esm/src/bases/base.js +var Encoder, Decoder, ComposedDecoder, or, Codec, from, baseX, decode, encode, rfc4648; +var init_base = __esm({ + "node_modules/multiformats/esm/src/bases/base.js"() { + init_shim(); + init_base_x(); + init_bytes(); + Encoder = class { + constructor(name2, prefix, baseEncode) { + this.name = name2; + this.prefix = prefix; + this.baseEncode = baseEncode; + } + encode(bytes) { + if (bytes instanceof Uint8Array) { + return `${this.prefix}${this.baseEncode(bytes)}`; + } else { + throw Error("Unknown type, must be binary type"); + } + } + }; + Decoder = class { + constructor(name2, prefix, baseDecode) { + this.name = name2; + this.prefix = prefix; + if (prefix.codePointAt(0) === void 0) { + throw new Error("Invalid prefix character"); + } + this.prefixCodePoint = prefix.codePointAt(0); + this.baseDecode = baseDecode; + } + decode(text) { + if (typeof text === "string") { + if (text.codePointAt(0) !== this.prefixCodePoint) { + throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); + } + return this.baseDecode(text.slice(this.prefix.length)); + } else { + throw Error("Can only multibase decode strings"); + } + } + or(decoder) { + return or(this, decoder); + } + }; + ComposedDecoder = class { + constructor(decoders) { + this.decoders = decoders; + } + or(decoder) { + return or(this, decoder); + } + decode(input) { + const prefix = input[0]; + const decoder = this.decoders[prefix]; + if (decoder) { + return decoder.decode(input); + } else { + throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + } + } + }; + or = (left, right) => new ComposedDecoder({ + ...left.decoders || { [left.prefix]: left }, + ...right.decoders || { [right.prefix]: right } + }); + Codec = class { + constructor(name2, prefix, baseEncode, baseDecode) { + this.name = name2; + this.prefix = prefix; + this.baseEncode = baseEncode; + this.baseDecode = baseDecode; + this.encoder = new Encoder(name2, prefix, baseEncode); + this.decoder = new Decoder(name2, prefix, baseDecode); + } + encode(input) { + return this.encoder.encode(input); + } + decode(input) { + return this.decoder.decode(input); + } + }; + from = ({ name: name2, prefix, encode: encode5, decode: decode6 }) => new Codec(name2, prefix, encode5, decode6); + baseX = ({ prefix, name: name2, alphabet: alphabet2 }) => { + const { encode: encode5, decode: decode6 } = base_x_default(alphabet2, name2); + return from({ + prefix, + name: name2, + encode: encode5, + decode: (text) => coerce(decode6(text)) + }); + }; + decode = (string2, alphabet2, bitsPerChar, name2) => { + const codes = {}; + for (let i2 = 0; i2 < alphabet2.length; ++i2) { + codes[alphabet2[i2]] = i2; + } + let end = string2.length; + while (string2[end - 1] === "=") { + --end; + } + const out = new Uint8Array(end * bitsPerChar / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for (let i2 = 0; i2 < end; ++i2) { + const value = codes[string2[i2]]; + if (value === void 0) { + throw new SyntaxError(`Non-${name2} character`); + } + buffer = buffer << bitsPerChar | value; + bits += bitsPerChar; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; + }; + encode = (data, alphabet2, bitsPerChar) => { + const pad = alphabet2[alphabet2.length - 1] === "="; + const mask = (1 << bitsPerChar) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for (let i2 = 0; i2 < data.length; ++i2) { + buffer = buffer << 8 | data[i2]; + bits += 8; + while (bits > bitsPerChar) { + bits -= bitsPerChar; + out += alphabet2[mask & buffer >> bits]; + } + } + if (bits) { + out += alphabet2[mask & buffer << bitsPerChar - bits]; + } + if (pad) { + while (out.length * bitsPerChar & 7) { + out += "="; + } + } + return out; + }; + rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) => { + return from({ + prefix, + name: name2, + encode(input) { + return encode(input, alphabet2, bitsPerChar); + }, + decode(input) { + return decode(input, alphabet2, bitsPerChar, name2); + } + }); + }; + } +}); + +// node_modules/multiformats/esm/src/bases/identity.js +var identity_exports = {}; +__export(identity_exports, { + identity: () => identity +}); +var identity; +var init_identity = __esm({ + "node_modules/multiformats/esm/src/bases/identity.js"() { + init_shim(); + init_base(); + init_bytes(); + identity = from({ + prefix: "\0", + name: "identity", + encode: (buf) => toString(buf), + decode: (str) => fromString(str) + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base2.js +var base2_exports = {}; +__export(base2_exports, { + base2: () => base2 +}); +var base2; +var init_base2 = __esm({ + "node_modules/multiformats/esm/src/bases/base2.js"() { + init_shim(); + init_base(); + base2 = rfc4648({ + prefix: "0", + name: "base2", + alphabet: "01", + bitsPerChar: 1 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base8.js +var base8_exports = {}; +__export(base8_exports, { + base8: () => base8 +}); +var base8; +var init_base8 = __esm({ + "node_modules/multiformats/esm/src/bases/base8.js"() { + init_shim(); + init_base(); + base8 = rfc4648({ + prefix: "7", + name: "base8", + alphabet: "01234567", + bitsPerChar: 3 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base10.js +var base10_exports = {}; +__export(base10_exports, { + base10: () => base10 +}); +var base10; +var init_base10 = __esm({ + "node_modules/multiformats/esm/src/bases/base10.js"() { + init_shim(); + init_base(); + base10 = baseX({ + prefix: "9", + name: "base10", + alphabet: "0123456789" + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base16.js +var base16_exports = {}; +__export(base16_exports, { + base16: () => base16, + base16upper: () => base16upper +}); +var base16, base16upper; +var init_base16 = __esm({ + "node_modules/multiformats/esm/src/bases/base16.js"() { + init_shim(); + init_base(); + base16 = rfc4648({ + prefix: "f", + name: "base16", + alphabet: "0123456789abcdef", + bitsPerChar: 4 + }); + base16upper = rfc4648({ + prefix: "F", + name: "base16upper", + alphabet: "0123456789ABCDEF", + bitsPerChar: 4 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base32.js +var base32_exports = {}; +__export(base32_exports, { + base32: () => base32, + base32hex: () => base32hex, + base32hexpad: () => base32hexpad, + base32hexpadupper: () => base32hexpadupper, + base32hexupper: () => base32hexupper, + base32pad: () => base32pad, + base32padupper: () => base32padupper, + base32upper: () => base32upper, + base32z: () => base32z +}); +var base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z; +var init_base32 = __esm({ + "node_modules/multiformats/esm/src/bases/base32.js"() { + init_shim(); + init_base(); + base32 = rfc4648({ + prefix: "b", + name: "base32", + alphabet: "abcdefghijklmnopqrstuvwxyz234567", + bitsPerChar: 5 + }); + base32upper = rfc4648({ + prefix: "B", + name: "base32upper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + bitsPerChar: 5 + }); + base32pad = rfc4648({ + prefix: "c", + name: "base32pad", + alphabet: "abcdefghijklmnopqrstuvwxyz234567=", + bitsPerChar: 5 + }); + base32padupper = rfc4648({ + prefix: "C", + name: "base32padupper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", + bitsPerChar: 5 + }); + base32hex = rfc4648({ + prefix: "v", + name: "base32hex", + alphabet: "0123456789abcdefghijklmnopqrstuv", + bitsPerChar: 5 + }); + base32hexupper = rfc4648({ + prefix: "V", + name: "base32hexupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + bitsPerChar: 5 + }); + base32hexpad = rfc4648({ + prefix: "t", + name: "base32hexpad", + alphabet: "0123456789abcdefghijklmnopqrstuv=", + bitsPerChar: 5 + }); + base32hexpadupper = rfc4648({ + prefix: "T", + name: "base32hexpadupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", + bitsPerChar: 5 + }); + base32z = rfc4648({ + prefix: "h", + name: "base32z", + alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", + bitsPerChar: 5 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base36.js +var base36_exports = {}; +__export(base36_exports, { + base36: () => base36, + base36upper: () => base36upper +}); +var base36, base36upper; +var init_base36 = __esm({ + "node_modules/multiformats/esm/src/bases/base36.js"() { + init_shim(); + init_base(); + base36 = baseX({ + prefix: "k", + name: "base36", + alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" + }); + base36upper = baseX({ + prefix: "K", + name: "base36upper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base58.js +var base58_exports = {}; +__export(base58_exports, { + base58btc: () => base58btc, + base58flickr: () => base58flickr +}); +var base58btc, base58flickr; +var init_base58 = __esm({ + "node_modules/multiformats/esm/src/bases/base58.js"() { + init_shim(); + init_base(); + base58btc = baseX({ + name: "base58btc", + prefix: "z", + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + }); + base58flickr = baseX({ + name: "base58flickr", + prefix: "Z", + alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base64.js +var base64_exports = {}; +__export(base64_exports, { + base64: () => base64, + base64pad: () => base64pad, + base64url: () => base64url, + base64urlpad: () => base64urlpad +}); +var base64, base64pad, base64url, base64urlpad; +var init_base64 = __esm({ + "node_modules/multiformats/esm/src/bases/base64.js"() { + init_shim(); + init_base(); + base64 = rfc4648({ + prefix: "m", + name: "base64", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", + bitsPerChar: 6 + }); + base64pad = rfc4648({ + prefix: "M", + name: "base64pad", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + bitsPerChar: 6 + }); + base64url = rfc4648({ + prefix: "u", + name: "base64url", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", + bitsPerChar: 6 + }); + base64urlpad = rfc4648({ + prefix: "U", + name: "base64urlpad", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", + bitsPerChar: 6 + }); + } +}); + +// node_modules/multiformats/esm/src/bases/base256emoji.js +var base256emoji_exports = {}; +__export(base256emoji_exports, { + base256emoji: () => base256emoji +}); +function encode2(data) { + return data.reduce((p3, c4) => { + p3 += alphabetBytesToChars[c4]; + return p3; + }, ""); +} +function decode2(str) { + const byts = []; + for (const char of str) { + const byt = alphabetCharsToBytes[char.codePointAt(0)]; + if (byt === void 0) { + throw new Error(`Non-base256emoji character: ${char}`); + } + byts.push(byt); + } + return new Uint8Array(byts); +} +var alphabet, alphabetBytesToChars, alphabetCharsToBytes, base256emoji; +var init_base256emoji = __esm({ + "node_modules/multiformats/esm/src/bases/base256emoji.js"() { + init_shim(); + init_base(); + alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); + alphabetBytesToChars = alphabet.reduce((p3, c4, i2) => { + p3[i2] = c4; + return p3; + }, []); + alphabetCharsToBytes = alphabet.reduce((p3, c4, i2) => { + p3[c4.codePointAt(0)] = i2; + return p3; + }, []); + base256emoji = from({ + prefix: "\u{1F680}", + name: "base256emoji", + encode: encode2, + decode: decode2 + }); + } +}); + +// node_modules/multiformats/esm/vendor/varint.js +function encode3(num, out, offset) { + out = out || []; + offset = offset || 0; + var oldOffset = offset; + while (num >= INT) { + out[offset++] = num & 255 | MSB; + num /= 128; + } + while (num & MSBALL) { + out[offset++] = num & 255 | MSB; + num >>>= 7; + } + out[offset] = num | 0; + encode3.bytes = offset - oldOffset + 1; + return out; +} +function read(buf, offset) { + var res = 0, offset = offset || 0, shift = 0, counter = offset, b4, l4 = buf.length; + do { + if (counter >= l4) { + read.bytes = 0; + throw new RangeError("Could not decode varint"); + } + b4 = buf[counter++]; + res += shift < 28 ? (b4 & REST$1) << shift : (b4 & REST$1) * Math.pow(2, shift); + shift += 7; + } while (b4 >= MSB$1); + read.bytes = counter - offset; + return res; +} +var encode_1, MSB, REST, MSBALL, INT, decode3, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default; +var init_varint = __esm({ + "node_modules/multiformats/esm/vendor/varint.js"() { + init_shim(); + encode_1 = encode3; + MSB = 128; + REST = 127; + MSBALL = ~REST; + INT = Math.pow(2, 31); + decode3 = read; + MSB$1 = 128; + REST$1 = 127; + N1 = Math.pow(2, 7); + N2 = Math.pow(2, 14); + N3 = Math.pow(2, 21); + N4 = Math.pow(2, 28); + N5 = Math.pow(2, 35); + N6 = Math.pow(2, 42); + N7 = Math.pow(2, 49); + N8 = Math.pow(2, 56); + N9 = Math.pow(2, 63); + length = function(value) { + return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; + }; + varint = { + encode: encode_1, + decode: decode3, + encodingLength: length + }; + _brrp_varint = varint; + varint_default = _brrp_varint; + } +}); + +// node_modules/multiformats/esm/src/varint.js +var decode4, encodeTo, encodingLength; +var init_varint2 = __esm({ + "node_modules/multiformats/esm/src/varint.js"() { + init_shim(); + init_varint(); + decode4 = (data, offset = 0) => { + const code2 = varint_default.decode(data, offset); + return [ + code2, + varint_default.decode.bytes + ]; + }; + encodeTo = (int, target, offset = 0) => { + varint_default.encode(int, target, offset); + return target; + }; + encodingLength = (int) => { + return varint_default.encodingLength(int); + }; + } +}); + +// node_modules/multiformats/esm/src/hashes/digest.js +var create, decode5, equals2, Digest; +var init_digest = __esm({ + "node_modules/multiformats/esm/src/hashes/digest.js"() { + init_shim(); + init_bytes(); + init_varint2(); + create = (code2, digest2) => { + const size = digest2.byteLength; + const sizeOffset = encodingLength(code2); + const digestOffset = sizeOffset + encodingLength(size); + const bytes = new Uint8Array(digestOffset + size); + encodeTo(code2, bytes, 0); + encodeTo(size, bytes, sizeOffset); + bytes.set(digest2, digestOffset); + return new Digest(code2, size, digest2, bytes); + }; + decode5 = (multihash) => { + const bytes = coerce(multihash); + const [code2, sizeOffset] = decode4(bytes); + const [size, digestOffset] = decode4(bytes.subarray(sizeOffset)); + const digest2 = bytes.subarray(sizeOffset + digestOffset); + if (digest2.byteLength !== size) { + throw new Error("Incorrect length"); + } + return new Digest(code2, size, digest2, bytes); + }; + equals2 = (a3, b4) => { + if (a3 === b4) { + return true; + } else { + return a3.code === b4.code && a3.size === b4.size && equals(a3.bytes, b4.bytes); + } + }; + Digest = class { + constructor(code2, size, digest2, bytes) { + this.code = code2; + this.size = size; + this.digest = digest2; + this.bytes = bytes; + } + }; + } +}); + +// node_modules/multiformats/esm/src/hashes/hasher.js +var from2, Hasher; +var init_hasher = __esm({ + "node_modules/multiformats/esm/src/hashes/hasher.js"() { + init_shim(); + init_digest(); + from2 = ({ name: name2, code: code2, encode: encode5 }) => new Hasher(name2, code2, encode5); + Hasher = class { + constructor(name2, code2, encode5) { + this.name = name2; + this.code = code2; + this.encode = encode5; + } + digest(input) { + if (input instanceof Uint8Array) { + const result = this.encode(input); + return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2)); + } else { + throw Error("Unknown type, must be binary type"); + } + } + }; + } +}); + +// node_modules/multiformats/esm/src/hashes/sha2-browser.js +var sha2_browser_exports = {}; +__export(sha2_browser_exports, { + sha256: () => sha256, + sha512: () => sha512 +}); +var sha, sha256, sha512; +var init_sha2_browser = __esm({ + "node_modules/multiformats/esm/src/hashes/sha2-browser.js"() { + init_shim(); + init_hasher(); + sha = (name2) => async (data) => new Uint8Array(await crypto.subtle.digest(name2, data)); + sha256 = from2({ + name: "sha2-256", + code: 18, + encode: sha("SHA-256") + }); + sha512 = from2({ + name: "sha2-512", + code: 19, + encode: sha("SHA-512") + }); + } +}); + +// node_modules/multiformats/esm/src/hashes/identity.js +var identity_exports2 = {}; +__export(identity_exports2, { + identity: () => identity2 +}); +var code, name, encode4, digest, identity2; +var init_identity2 = __esm({ + "node_modules/multiformats/esm/src/hashes/identity.js"() { + init_shim(); + init_bytes(); + init_digest(); + code = 0; + name = "identity"; + encode4 = coerce; + digest = (input) => create(code, encode4(input)); + identity2 = { + code, + name, + encode: encode4, + digest + }; + } +}); + +// node_modules/multiformats/esm/src/codecs/raw.js +var init_raw = __esm({ + "node_modules/multiformats/esm/src/codecs/raw.js"() { + init_shim(); + init_bytes(); + } +}); + +// node_modules/multiformats/esm/src/codecs/json.js +var textEncoder, textDecoder; +var init_json = __esm({ + "node_modules/multiformats/esm/src/codecs/json.js"() { + init_shim(); + textEncoder = new TextEncoder(); + textDecoder = new TextDecoder(); + } +}); + +// node_modules/multiformats/esm/src/cid.js +var CID, parseCIDtoBytes, toStringV0, toStringV1, DAG_PB_CODE, SHA_256_CODE, encodeCID, cidSymbol, readonly, hidden, version, deprecate, IS_CID_DEPRECATION; +var init_cid = __esm({ + "node_modules/multiformats/esm/src/cid.js"() { + init_shim(); + init_varint2(); + init_digest(); + init_base58(); + init_base32(); + init_bytes(); + CID = class _CID { + constructor(version2, code2, multihash, bytes) { + this.code = code2; + this.version = version2; + this.multihash = multihash; + this.bytes = bytes; + this.byteOffset = bytes.byteOffset; + this.byteLength = bytes.byteLength; + this.asCID = this; + this._baseCache = /* @__PURE__ */ new Map(); + Object.defineProperties(this, { + byteOffset: hidden, + byteLength: hidden, + code: readonly, + version: readonly, + multihash: readonly, + bytes: readonly, + _baseCache: hidden, + asCID: hidden + }); + } + toV0() { + switch (this.version) { + case 0: { + return this; + } + default: { + const { code: code2, multihash } = this; + if (code2 !== DAG_PB_CODE) { + throw new Error("Cannot convert a non dag-pb CID to CIDv0"); + } + if (multihash.code !== SHA_256_CODE) { + throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); + } + return _CID.createV0(multihash); + } + } + } + toV1() { + switch (this.version) { + case 0: { + const { code: code2, digest: digest2 } = this.multihash; + const multihash = create(code2, digest2); + return _CID.createV1(this.code, multihash); + } + case 1: { + return this; + } + default: { + throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); + } + } + } + equals(other) { + return other && this.code === other.code && this.version === other.version && equals2(this.multihash, other.multihash); + } + toString(base3) { + const { bytes, version: version2, _baseCache } = this; + switch (version2) { + case 0: + return toStringV0(bytes, _baseCache, base3 || base58btc.encoder); + default: + return toStringV1(bytes, _baseCache, base3 || base32.encoder); + } + } + toJSON() { + return { + code: this.code, + version: this.version, + hash: this.multihash.bytes + }; + } + get [Symbol.toStringTag]() { + return "CID"; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return "CID(" + this.toString() + ")"; + } + static isCID(value) { + deprecate(/^0\.0/, IS_CID_DEPRECATION); + return !!(value && (value[cidSymbol] || value.asCID === value)); + } + get toBaseEncodedString() { + throw new Error("Deprecated, use .toString()"); + } + get codec() { + throw new Error('"codec" property is deprecated, use integer "code" property instead'); + } + get buffer() { + throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); + } + get multibaseName() { + throw new Error('"multibaseName" property is deprecated'); + } + get prefix() { + throw new Error('"prefix" property is deprecated'); + } + static asCID(value) { + if (value instanceof _CID) { + return value; + } else if (value != null && value.asCID === value) { + const { version: version2, code: code2, multihash, bytes } = value; + return new _CID(version2, code2, multihash, bytes || encodeCID(version2, code2, multihash.bytes)); + } else if (value != null && value[cidSymbol] === true) { + const { version: version2, multihash, code: code2 } = value; + const digest2 = decode5(multihash); + return _CID.create(version2, code2, digest2); + } else { + return null; + } + } + static create(version2, code2, digest2) { + if (typeof code2 !== "number") { + throw new Error("String codecs are no longer supported"); + } + switch (version2) { + case 0: { + if (code2 !== DAG_PB_CODE) { + throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); + } else { + return new _CID(version2, code2, digest2, digest2.bytes); + } + } + case 1: { + const bytes = encodeCID(version2, code2, digest2.bytes); + return new _CID(version2, code2, digest2, bytes); + } + default: { + throw new Error("Invalid version"); + } + } + } + static createV0(digest2) { + return _CID.create(0, DAG_PB_CODE, digest2); + } + static createV1(code2, digest2) { + return _CID.create(1, code2, digest2); + } + static decode(bytes) { + const [cid, remainder] = _CID.decodeFirst(bytes); + if (remainder.length) { + throw new Error("Incorrect length"); + } + return cid; + } + static decodeFirst(bytes) { + const specs = _CID.inspectBytes(bytes); + const prefixSize = specs.size - specs.multihashSize; + const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); + if (multihashBytes.byteLength !== specs.multihashSize) { + throw new Error("Incorrect length"); + } + const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); + const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); + const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2); + return [ + cid, + bytes.subarray(specs.size) + ]; + } + static inspectBytes(initialBytes) { + let offset = 0; + const next = () => { + const [i2, length2] = decode4(initialBytes.subarray(offset)); + offset += length2; + return i2; + }; + let version2 = next(); + let codec = DAG_PB_CODE; + if (version2 === 18) { + version2 = 0; + offset = 0; + } else if (version2 === 1) { + codec = next(); + } + if (version2 !== 0 && version2 !== 1) { + throw new RangeError(`Invalid CID version ${version2}`); + } + const prefixSize = offset; + const multihashCode = next(); + const digestSize = next(); + const size = offset + digestSize; + const multihashSize = size - prefixSize; + return { + version: version2, + codec, + multihashCode, + digestSize, + multihashSize, + size + }; + } + static parse(source, base3) { + const [prefix, bytes] = parseCIDtoBytes(source, base3); + const cid = _CID.decode(bytes); + cid._baseCache.set(prefix, source); + return cid; + } + }; + parseCIDtoBytes = (source, base3) => { + switch (source[0]) { + case "Q": { + const decoder = base3 || base58btc; + return [ + base58btc.prefix, + decoder.decode(`${base58btc.prefix}${source}`) + ]; + } + case base58btc.prefix: { + const decoder = base3 || base58btc; + return [ + base58btc.prefix, + decoder.decode(source) + ]; + } + case base32.prefix: { + const decoder = base3 || base32; + return [ + base32.prefix, + decoder.decode(source) + ]; + } + default: { + if (base3 == null) { + throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); + } + return [ + source[0], + base3.decode(source) + ]; + } + } + }; + toStringV0 = (bytes, cache, base3) => { + const { prefix } = base3; + if (prefix !== base58btc.prefix) { + throw Error(`Cannot string encode V0 in ${base3.name} encoding`); + } + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base3.encode(bytes).slice(1); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } + }; + toStringV1 = (bytes, cache, base3) => { + const { prefix } = base3; + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base3.encode(bytes); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } + }; + DAG_PB_CODE = 112; + SHA_256_CODE = 18; + encodeCID = (version2, code2, multihash) => { + const codeOffset = encodingLength(version2); + const hashOffset = codeOffset + encodingLength(code2); + const bytes = new Uint8Array(hashOffset + multihash.byteLength); + encodeTo(version2, bytes, 0); + encodeTo(code2, bytes, codeOffset); + bytes.set(multihash, hashOffset); + return bytes; + }; + cidSymbol = Symbol.for("@ipld/js-cid/CID"); + readonly = { + writable: false, + configurable: false, + enumerable: true + }; + hidden = { + writable: false, + enumerable: false, + configurable: false + }; + version = "0.0.0-dev"; + deprecate = (range, message) => { + if (range.test(version)) { + console.warn(message); + } else { + throw new Error(message); + } + }; + IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: -if (CID.isCID(value)) { - doSomethingWithCID(value) +if (CID.isCID(value)) { + doSomethingWithCID(value) +} + +Is replaced with: + +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) +} +`; + } +}); + +// node_modules/multiformats/esm/src/index.js +var init_src = __esm({ + "node_modules/multiformats/esm/src/index.js"() { + init_shim(); + init_cid(); + init_varint2(); + init_bytes(); + init_hasher(); + init_digest(); + } +}); + +// node_modules/multiformats/esm/src/basics.js +var bases, hashes; +var init_basics = __esm({ + "node_modules/multiformats/esm/src/basics.js"() { + init_shim(); + init_identity(); + init_base2(); + init_base8(); + init_base10(); + init_base16(); + init_base32(); + init_base36(); + init_base58(); + init_base64(); + init_base256emoji(); + init_sha2_browser(); + init_identity2(); + init_raw(); + init_json(); + init_src(); + bases = { + ...identity_exports, + ...base2_exports, + ...base8_exports, + ...base10_exports, + ...base16_exports, + ...base32_exports, + ...base36_exports, + ...base58_exports, + ...base64_exports, + ...base256emoji_exports + }; + hashes = { + ...sha2_browser_exports, + ...identity_exports2 + }; + } +}); + +// node_modules/uint8arrays/esm/src/util/bases.js +function createCodec(name2, prefix, encode5, decode6) { + return { + name: name2, + prefix, + encoder: { + name: name2, + prefix, + encode: encode5 + }, + decoder: { decode: decode6 } + }; +} +var string, ascii, BASES, bases_default; +var init_bases = __esm({ + "node_modules/uint8arrays/esm/src/util/bases.js"() { + init_shim(); + init_basics(); + init_alloc(); + string = createCodec("utf8", "u", (buf) => { + const decoder = new TextDecoder("utf8"); + return "u" + decoder.decode(buf); + }, (str) => { + const encoder = new TextEncoder(); + return encoder.encode(str.substring(1)); + }); + ascii = createCodec("ascii", "a", (buf) => { + let string2 = "a"; + for (let i2 = 0; i2 < buf.length; i2++) { + string2 += String.fromCharCode(buf[i2]); + } + return string2; + }, (str) => { + str = str.substring(1); + const buf = allocUnsafe(str.length); + for (let i2 = 0; i2 < str.length; i2++) { + buf[i2] = str.charCodeAt(i2); + } + return buf; + }); + BASES = { + utf8: string, + "utf-8": string, + hex: bases.base16, + latin1: ascii, + ascii, + binary: ascii, + ...bases + }; + bases_default = BASES; + } +}); + +// node_modules/uint8arrays/esm/src/to-string.js +function toString2(array, encoding = "utf8") { + const base3 = bases_default[encoding]; + if (!base3) { + throw new Error(`Unsupported encoding "${encoding}"`); + } + if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { + return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); + } + return base3.encoder.encode(array).substring(1); +} +var init_to_string = __esm({ + "node_modules/uint8arrays/esm/src/to-string.js"() { + init_shim(); + init_bases(); + } +}); + +// node_modules/uint8arrays/esm/src/from-string.js +function fromString2(string2, encoding = "utf8") { + const base3 = bases_default[encoding]; + if (!base3) { + throw new Error(`Unsupported encoding "${encoding}"`); + } + if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { + return asUint8Array(globalThis.Buffer.from(string2, "utf-8")); + } + return base3.decoder.decode(`${base3.prefix}${string2}`); +} +var init_from_string = __esm({ + "node_modules/uint8arrays/esm/src/from-string.js"() { + init_shim(); + init_bases(); + init_as_uint8array(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/utils.js +function decodeJSON(str) { + return safeJsonParse(toString2(fromString2(str, JWT_ENCODING), JSON_ENCODING)); +} +function encodeJSON(val) { + return toString2(fromString2(safeJsonStringify(val), JSON_ENCODING), JWT_ENCODING); +} +function encodeIss(publicKey) { + const header = fromString2(MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_ENCODING); + const multicodec = MULTICODEC_ED25519_BASE + toString2(concat([header, publicKey]), MULTICODEC_ED25519_ENCODING); + return [DID_PREFIX, DID_METHOD, multicodec].join(DID_DELIMITER); +} +function decodeIss(issuer) { + const [prefix, method, multicodec] = issuer.split(DID_DELIMITER); + if (prefix !== DID_PREFIX || method !== DID_METHOD) { + throw new Error(`Issuer must be a DID with method "key"`); + } + const base3 = multicodec.slice(0, 1); + if (base3 !== MULTICODEC_ED25519_BASE) { + throw new Error(`Issuer must be a key in mulicodec format`); + } + const bytes = fromString2(multicodec.slice(1), MULTICODEC_ED25519_ENCODING); + const type = toString2(bytes.slice(0, 2), MULTICODEC_ED25519_ENCODING); + if (type !== MULTICODEC_ED25519_HEADER) { + throw new Error(`Issuer must be a public key with type "Ed25519"`); + } + const publicKey = bytes.slice(2); + if (publicKey.length !== MULTICODEC_ED25519_LENGTH) { + throw new Error(`Issuer must be a public key with length 32 bytes`); + } + return publicKey; +} +function encodeSig(bytes) { + return toString2(bytes, JWT_ENCODING); +} +function decodeSig(encoded) { + return fromString2(encoded, JWT_ENCODING); +} +function encodeData(params) { + return fromString2([encodeJSON(params.header), encodeJSON(params.payload)].join(JWT_DELIMITER), DATA_ENCODING); +} +function decodeData(data) { + const params = toString2(data, DATA_ENCODING).split(JWT_DELIMITER); + const header = decodeJSON(params[0]); + const payload = decodeJSON(params[1]); + return { header, payload }; +} +function encodeJWT(params) { + return [ + encodeJSON(params.header), + encodeJSON(params.payload), + encodeSig(params.signature) + ].join(JWT_DELIMITER); +} +function decodeJWT(jwt) { + const params = jwt.split(JWT_DELIMITER); + const header = decodeJSON(params[0]); + const payload = decodeJSON(params[1]); + const signature = decodeSig(params[2]); + const data = fromString2(params.slice(0, 2).join(JWT_DELIMITER), DATA_ENCODING); + return { header, payload, signature, data }; +} +var init_utils = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/utils.js"() { + init_shim(); + init_concat(); + init_to_string(); + init_from_string(); + init_esm(); + init_constants(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/api.js +function generateKeyPair(seed = (0, import_random.randomBytes)(KEY_PAIR_SEED_LENGTH)) { + return ed25519.generateKeyPairFromSeed(seed); +} +async function signJWT(sub, aud, ttl, keyPair, iat = (0, import_time.fromMiliseconds)(Date.now())) { + const header = { alg: JWT_IRIDIUM_ALG, typ: JWT_IRIDIUM_TYP }; + const iss = encodeIss(keyPair.publicKey); + const exp = iat + ttl; + const payload = { iss, sub, aud, iat, exp }; + const data = encodeData({ header, payload }); + const signature = ed25519.sign(keyPair.secretKey, data); + return encodeJWT({ header, payload, signature }); +} +async function verifyJWT(jwt) { + const { header, payload, data, signature } = decodeJWT(jwt); + if (header.alg !== JWT_IRIDIUM_ALG || header.typ !== JWT_IRIDIUM_TYP) { + throw new Error("JWT must use EdDSA algorithm"); + } + const publicKey = decodeIss(payload.iss); + return ed25519.verify(publicKey, data, signature); +} +var ed25519, import_random, import_time; +var init_api = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/api.js"() { + init_shim(); + ed25519 = __toESM(require_ed25519()); + import_random = __toESM(require_random()); + import_time = __toESM(require_cjs()); + init_constants(); + init_utils(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/types.js +var init_types = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/types.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/relay-auth/dist/esm/index.js +var esm_exports3 = {}; +__export(esm_exports3, { + DATA_ENCODING: () => DATA_ENCODING, + DID_DELIMITER: () => DID_DELIMITER, + DID_METHOD: () => DID_METHOD, + DID_PREFIX: () => DID_PREFIX, + JSON_ENCODING: () => JSON_ENCODING, + JWT_DELIMITER: () => JWT_DELIMITER, + JWT_ENCODING: () => JWT_ENCODING, + JWT_IRIDIUM_ALG: () => JWT_IRIDIUM_ALG, + JWT_IRIDIUM_TYP: () => JWT_IRIDIUM_TYP, + KEY_PAIR_SEED_LENGTH: () => KEY_PAIR_SEED_LENGTH, + MULTICODEC_ED25519_BASE: () => MULTICODEC_ED25519_BASE, + MULTICODEC_ED25519_ENCODING: () => MULTICODEC_ED25519_ENCODING, + MULTICODEC_ED25519_HEADER: () => MULTICODEC_ED25519_HEADER, + MULTICODEC_ED25519_LENGTH: () => MULTICODEC_ED25519_LENGTH, + decodeData: () => decodeData, + decodeIss: () => decodeIss, + decodeJSON: () => decodeJSON, + decodeJWT: () => decodeJWT, + decodeSig: () => decodeSig, + encodeData: () => encodeData, + encodeIss: () => encodeIss, + encodeJSON: () => encodeJSON, + encodeJWT: () => encodeJWT, + encodeSig: () => encodeSig, + generateKeyPair: () => generateKeyPair, + signJWT: () => signJWT, + verifyJWT: () => verifyJWT +}); +var init_esm3 = __esm({ + "node_modules/@walletconnect/relay-auth/dist/esm/index.js"() { + init_shim(); + init_api(); + init_constants(); + init_types(); + init_utils(); + } +}); + +// node_modules/detect-browser/index.js +var require_detect_browser = __commonJS({ + "node_modules/detect-browser/index.js"(exports2) { + "use strict"; + init_shim(); + var __spreadArray = exports2 && exports2.__spreadArray || function(to, from3, pack) { + if (pack || arguments.length === 2) + for (var i2 = 0, l4 = from3.length, ar; i2 < l4; i2++) { + if (ar || !(i2 in from3)) { + if (!ar) + ar = Array.prototype.slice.call(from3, 0, i2); + ar[i2] = from3[i2]; + } + } + return to.concat(ar || Array.prototype.slice.call(from3)); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getNodeVersion = exports2.detectOS = exports2.parseUserAgent = exports2.browserName = exports2.detect = exports2.ReactNativeInfo = exports2.BotInfo = exports2.SearchBotDeviceInfo = exports2.NodeInfo = exports2.BrowserInfo = void 0; + var BrowserInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function BrowserInfo2(name2, version2, os) { + this.name = name2; + this.version = version2; + this.os = os; + this.type = "browser"; + } + return BrowserInfo2; + }() + ); + exports2.BrowserInfo = BrowserInfo; + var NodeInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function NodeInfo2(version2) { + this.version = version2; + this.type = "node"; + this.name = "node"; + this.os = import_process.default.platform; + } + return NodeInfo2; + }() + ); + exports2.NodeInfo = NodeInfo; + var SearchBotDeviceInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function SearchBotDeviceInfo2(name2, version2, os, bot) { + this.name = name2; + this.version = version2; + this.os = os; + this.bot = bot; + this.type = "bot-device"; + } + return SearchBotDeviceInfo2; + }() + ); + exports2.SearchBotDeviceInfo = SearchBotDeviceInfo; + var BotInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function BotInfo2() { + this.type = "bot"; + this.bot = true; + this.name = "bot"; + this.version = null; + this.os = null; + } + return BotInfo2; + }() + ); + exports2.BotInfo = BotInfo; + var ReactNativeInfo = ( + /** @class */ + /* @__PURE__ */ function() { + function ReactNativeInfo2() { + this.type = "react-native"; + this.name = "react-native"; + this.version = null; + this.os = null; + } + return ReactNativeInfo2; + }() + ); + exports2.ReactNativeInfo = ReactNativeInfo; + var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/; + var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/; + var REQUIRED_VERSION_PARTS = 3; + var userAgentRules = [ + ["aol", /AOLShield\/([0-9\._]+)/], + ["edge", /Edge\/([0-9\._]+)/], + ["edge-ios", /EdgiOS\/([0-9\._]+)/], + ["yandexbrowser", /YaBrowser\/([0-9\._]+)/], + ["kakaotalk", /KAKAOTALK\s([0-9\.]+)/], + ["samsung", /SamsungBrowser\/([0-9\.]+)/], + ["silk", /\bSilk\/([0-9._-]+)\b/], + ["miui", /MiuiBrowser\/([0-9\.]+)$/], + ["beaker", /BeakerBrowser\/([0-9\.]+)/], + ["edge-chromium", /EdgA?\/([0-9\.]+)/], + [ + "chromium-webview", + /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ + ], + ["chrome", /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], + ["phantomjs", /PhantomJS\/([0-9\.]+)(:?\s|$)/], + ["crios", /CriOS\/([0-9\.]+)(:?\s|$)/], + ["firefox", /Firefox\/([0-9\.]+)(?:\s|$)/], + ["fxios", /FxiOS\/([0-9\.]+)/], + ["opera-mini", /Opera Mini.*Version\/([0-9\.]+)/], + ["opera", /Opera\/([0-9\.]+)(?:\s|$)/], + ["opera", /OPR\/([0-9\.]+)(:?\s|$)/], + ["pie", /^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/], + ["pie", /^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/], + ["netfront", /^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/], + ["ie", /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], + ["ie", /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], + ["ie", /MSIE\s(7\.0)/], + ["bb10", /BB10;\sTouch.*Version\/([0-9\.]+)/], + ["android", /Android\s([0-9\.]+)/], + ["ios", /Version\/([0-9\._]+).*Mobile.*Safari.*/], + ["safari", /Version\/([0-9\._]+).*Safari/], + ["facebook", /FB[AS]V\/([0-9\.]+)/], + ["instagram", /Instagram\s([0-9\.]+)/], + ["ios-webview", /AppleWebKit\/([0-9\.]+).*Mobile/], + ["ios-webview", /AppleWebKit\/([0-9\.]+).*Gecko\)$/], + ["curl", /^curl\/([0-9\.]+)$/], + ["searchbot", SEARCHBOX_UA_REGEX] + ]; + var operatingSystemRules = [ + ["iOS", /iP(hone|od|ad)/], + ["Android OS", /Android/], + ["BlackBerry OS", /BlackBerry|BB10/], + ["Windows Mobile", /IEMobile/], + ["Amazon OS", /Kindle/], + ["Windows 3.11", /Win16/], + ["Windows 95", /(Windows 95)|(Win95)|(Windows_95)/], + ["Windows 98", /(Windows 98)|(Win98)/], + ["Windows 2000", /(Windows NT 5.0)|(Windows 2000)/], + ["Windows XP", /(Windows NT 5.1)|(Windows XP)/], + ["Windows Server 2003", /(Windows NT 5.2)/], + ["Windows Vista", /(Windows NT 6.0)/], + ["Windows 7", /(Windows NT 6.1)/], + ["Windows 8", /(Windows NT 6.2)/], + ["Windows 8.1", /(Windows NT 6.3)/], + ["Windows 10", /(Windows NT 10.0)/], + ["Windows ME", /Windows ME/], + ["Windows CE", /Windows CE|WinCE|Microsoft Pocket Internet Explorer/], + ["Open BSD", /OpenBSD/], + ["Sun OS", /SunOS/], + ["Chrome OS", /CrOS/], + ["Linux", /(Linux)|(X11)/], + ["Mac OS", /(Mac_PowerPC)|(Macintosh)/], + ["QNX", /QNX/], + ["BeOS", /BeOS/], + ["OS/2", /OS\/2/] + ]; + function detect(userAgent) { + if (!!userAgent) { + return parseUserAgent(userAgent); + } + if (typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative") { + return new ReactNativeInfo(); + } + if (typeof navigator !== "undefined") { + return parseUserAgent(navigator.userAgent); + } + return getNodeVersion(); + } + exports2.detect = detect; + function matchUserAgent(ua) { + return ua !== "" && userAgentRules.reduce(function(matched, _a) { + var browser = _a[0], regex = _a[1]; + if (matched) { + return matched; + } + var uaMatch = regex.exec(ua); + return !!uaMatch && [browser, uaMatch]; + }, false); + } + function browserName(ua) { + var data = matchUserAgent(ua); + return data ? data[0] : null; + } + exports2.browserName = browserName; + function parseUserAgent(ua) { + var matchedRule = matchUserAgent(ua); + if (!matchedRule) { + return null; + } + var name2 = matchedRule[0], match = matchedRule[1]; + if (name2 === "searchbot") { + return new BotInfo(); + } + var versionParts = match[1] && match[1].split(".").join("_").split("_").slice(0, 3); + if (versionParts) { + if (versionParts.length < REQUIRED_VERSION_PARTS) { + versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true); + } + } else { + versionParts = []; + } + var version2 = versionParts.join("."); + var os = detectOS(ua); + var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua); + if (searchBotMatch && searchBotMatch[1]) { + return new SearchBotDeviceInfo(name2, version2, os, searchBotMatch[1]); + } + return new BrowserInfo(name2, version2, os); + } + exports2.parseUserAgent = parseUserAgent; + function detectOS(ua) { + for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) { + var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1]; + var match = regex.exec(ua); + if (match) { + return os; + } + } + return null; + } + exports2.detectOS = detectOS; + function getNodeVersion() { + var isNode2 = typeof import_process.default !== "undefined" && import_process.default.version; + return isNode2 ? new NodeInfo(import_process.default.version.slice(1)) : null; + } + exports2.getNodeVersion = getNodeVersion; + function createVersionParts(count) { + var output = []; + for (var ii = 0; ii < count; ii++) { + output.push("0"); + } + return output; + } + } +}); + +// node_modules/@walletconnect/window-getters/dist/cjs/index.js +var require_cjs3 = __commonJS({ + "node_modules/@walletconnect/window-getters/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getLocalStorage = exports2.getLocalStorageOrThrow = exports2.getCrypto = exports2.getCryptoOrThrow = exports2.getLocation = exports2.getLocationOrThrow = exports2.getNavigator = exports2.getNavigatorOrThrow = exports2.getDocument = exports2.getDocumentOrThrow = exports2.getFromWindowOrThrow = exports2.getFromWindow = void 0; + function getFromWindow(name2) { + let res = void 0; + if (typeof window !== "undefined" && typeof window[name2] !== "undefined") { + res = window[name2]; + } + return res; + } + exports2.getFromWindow = getFromWindow; + function getFromWindowOrThrow(name2) { + const res = getFromWindow(name2); + if (!res) { + throw new Error(`${name2} is not defined in Window`); + } + return res; + } + exports2.getFromWindowOrThrow = getFromWindowOrThrow; + function getDocumentOrThrow() { + return getFromWindowOrThrow("document"); + } + exports2.getDocumentOrThrow = getDocumentOrThrow; + function getDocument() { + return getFromWindow("document"); + } + exports2.getDocument = getDocument; + function getNavigatorOrThrow() { + return getFromWindowOrThrow("navigator"); + } + exports2.getNavigatorOrThrow = getNavigatorOrThrow; + function getNavigator() { + return getFromWindow("navigator"); + } + exports2.getNavigator = getNavigator; + function getLocationOrThrow() { + return getFromWindowOrThrow("location"); + } + exports2.getLocationOrThrow = getLocationOrThrow; + function getLocation() { + return getFromWindow("location"); + } + exports2.getLocation = getLocation; + function getCryptoOrThrow() { + return getFromWindowOrThrow("crypto"); + } + exports2.getCryptoOrThrow = getCryptoOrThrow; + function getCrypto() { + return getFromWindow("crypto"); + } + exports2.getCrypto = getCrypto; + function getLocalStorageOrThrow() { + return getFromWindowOrThrow("localStorage"); + } + exports2.getLocalStorageOrThrow = getLocalStorageOrThrow; + function getLocalStorage() { + return getFromWindow("localStorage"); + } + exports2.getLocalStorage = getLocalStorage; + } +}); + +// node_modules/@walletconnect/window-metadata/dist/cjs/index.js +var require_cjs4 = __commonJS({ + "node_modules/@walletconnect/window-metadata/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getWindowMetadata = void 0; + var window_getters_1 = require_cjs3(); + function getWindowMetadata() { + let doc; + let loc; + try { + doc = window_getters_1.getDocumentOrThrow(); + loc = window_getters_1.getLocationOrThrow(); + } catch (e2) { + return null; + } + function getIcons() { + const links = doc.getElementsByTagName("link"); + const icons2 = []; + for (let i2 = 0; i2 < links.length; i2++) { + const link = links[i2]; + const rel = link.getAttribute("rel"); + if (rel) { + if (rel.toLowerCase().indexOf("icon") > -1) { + const href = link.getAttribute("href"); + if (href) { + if (href.toLowerCase().indexOf("https:") === -1 && href.toLowerCase().indexOf("http:") === -1 && href.indexOf("//") !== 0) { + let absoluteHref = loc.protocol + "//" + loc.host; + if (href.indexOf("/") === 0) { + absoluteHref += href; + } else { + const path = loc.pathname.split("/"); + path.pop(); + const finalPath = path.join("/"); + absoluteHref += finalPath + "/" + href; + } + icons2.push(absoluteHref); + } else if (href.indexOf("//") === 0) { + const absoluteUrl = loc.protocol + href; + icons2.push(absoluteUrl); + } else { + icons2.push(href); + } + } + } + } + } + return icons2; + } + function getWindowMetadataOfAny(...args) { + const metaTags = doc.getElementsByTagName("meta"); + for (let i2 = 0; i2 < metaTags.length; i2++) { + const tag = metaTags[i2]; + const attributes = ["itemprop", "property", "name"].map((target) => tag.getAttribute(target)).filter((attr) => { + if (attr) { + return args.includes(attr); + } + return false; + }); + if (attributes.length && attributes) { + const content = tag.getAttribute("content"); + if (content) { + return content; + } + } + } + return ""; + } + function getName() { + let name3 = getWindowMetadataOfAny("name", "og:site_name", "og:title", "twitter:title"); + if (!name3) { + name3 = doc.title; + } + return name3; + } + function getDescription() { + const description2 = getWindowMetadataOfAny("description", "og:description", "twitter:description", "keywords"); + return description2; + } + const name2 = getName(); + const description = getDescription(); + const url = loc.origin; + const icons = getIcons(); + const meta = { + description, + url, + icons, + name: name2 + }; + return meta; + } + exports2.getWindowMetadata = getWindowMetadata; + } +}); + +// node_modules/strict-uri-encode/index.js +var require_strict_uri_encode = __commonJS({ + "node_modules/strict-uri-encode/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (x3) => `%${x3.charCodeAt(0).toString(16).toUpperCase()}`); + } +}); + +// node_modules/decode-uri-component/index.js +var require_decode_uri_component = __commonJS({ + "node_modules/decode-uri-component/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var token = "%[a-f0-9]{2}"; + var singleMatcher = new RegExp("(" + token + ")|([^%]+?)", "gi"); + var multiMatcher = new RegExp("(" + token + ")+", "gi"); + function decodeComponents(components, split) { + try { + return [decodeURIComponent(components.join(""))]; + } catch (err) { + } + if (components.length === 1) { + return components; + } + split = split || 1; + var left = components.slice(0, split); + var right = components.slice(split); + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); + } + function decode6(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher) || []; + for (var i2 = 1; i2 < tokens.length; i2++) { + input = decodeComponents(tokens, i2).join(""); + tokens = input.match(singleMatcher) || []; + } + return input; + } + } + function customDecodeURIComponent(input) { + var replaceMap = { + "%FE%FF": "\uFFFD\uFFFD", + "%FF%FE": "\uFFFD\uFFFD" + }; + var match = multiMatcher.exec(input); + while (match) { + try { + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode6(match[0]); + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } + match = multiMatcher.exec(input); + } + replaceMap["%C2"] = "\uFFFD"; + var entries = Object.keys(replaceMap); + for (var i2 = 0; i2 < entries.length; i2++) { + var key = entries[i2]; + input = input.replace(new RegExp(key, "g"), replaceMap[key]); + } + return input; + } + module2.exports = function(encodedURI) { + if (typeof encodedURI !== "string") { + throw new TypeError("Expected `encodedURI` to be of type `string`, got `" + typeof encodedURI + "`"); + } + try { + encodedURI = encodedURI.replace(/\+/g, " "); + return decodeURIComponent(encodedURI); + } catch (err) { + return customDecodeURIComponent(encodedURI); + } + }; + } +}); + +// node_modules/split-on-first/index.js +var require_split_on_first = __commonJS({ + "node_modules/split-on-first/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = (string2, separator) => { + if (!(typeof string2 === "string" && typeof separator === "string")) { + throw new TypeError("Expected the arguments to be of type `string`"); + } + if (separator === "") { + return [string2]; + } + const separatorIndex = string2.indexOf(separator); + if (separatorIndex === -1) { + return [string2]; + } + return [ + string2.slice(0, separatorIndex), + string2.slice(separatorIndex + separator.length) + ]; + }; + } +}); + +// node_modules/filter-obj/index.js +var require_filter_obj = __commonJS({ + "node_modules/filter-obj/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function(obj, predicate) { + var ret = {}; + var keys2 = Object.keys(obj); + var isArr = Array.isArray(predicate); + for (var i2 = 0; i2 < keys2.length; i2++) { + var key = keys2[i2]; + var val = obj[key]; + if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) { + ret[key] = val; + } + } + return ret; + }; + } +}); + +// node_modules/query-string/index.js +var require_query_string = __commonJS({ + "node_modules/query-string/index.js"(exports2) { + "use strict"; + init_shim(); + var strictUriEncode = require_strict_uri_encode(); + var decodeComponent = require_decode_uri_component(); + var splitOnFirst = require_split_on_first(); + var filterObject = require_filter_obj(); + var isNullOrUndefined = (value) => value === null || value === void 0; + var encodeFragmentIdentifier = Symbol("encodeFragmentIdentifier"); + function encoderForArrayFormat(options) { + switch (options.arrayFormat) { + case "index": + return (key) => (result, value) => { + const index = result.length; + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, [encode5(key, options), "[", index, "]"].join("")]; + } + return [ + ...result, + [encode5(key, options), "[", encode5(index, options), "]=", encode5(value, options)].join("") + ]; + }; + case "bracket": + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, [encode5(key, options), "[]"].join("")]; + } + return [...result, [encode5(key, options), "[]=", encode5(value, options)].join("")]; + }; + case "colon-list-separator": + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, [encode5(key, options), ":list="].join("")]; + } + return [...result, [encode5(key, options), ":list=", encode5(value, options)].join("")]; + }; + case "comma": + case "separator": + case "bracket-separator": { + const keyValueSep = options.arrayFormat === "bracket-separator" ? "[]=" : "="; + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + value = value === null ? "" : value; + if (result.length === 0) { + return [[encode5(key, options), keyValueSep, encode5(value, options)].join("")]; + } + return [[result, encode5(value, options)].join(options.arrayFormatSeparator)]; + }; + } + default: + return (key) => (result, value) => { + if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { + return result; + } + if (value === null) { + return [...result, encode5(key, options)]; + } + return [...result, [encode5(key, options), "=", encode5(value, options)].join("")]; + }; + } + } + function parserForArrayFormat(options) { + let result; + switch (options.arrayFormat) { + case "index": + return (key, value, accumulator) => { + result = /\[(\d*)\]$/.exec(key); + key = key.replace(/\[\d*\]$/, ""); + if (!result) { + accumulator[key] = value; + return; + } + if (accumulator[key] === void 0) { + accumulator[key] = {}; + } + accumulator[key][result[1]] = value; + }; + case "bracket": + return (key, value, accumulator) => { + result = /(\[\])$/.exec(key); + key = key.replace(/\[\]$/, ""); + if (!result) { + accumulator[key] = value; + return; + } + if (accumulator[key] === void 0) { + accumulator[key] = [value]; + return; + } + accumulator[key] = [].concat(accumulator[key], value); + }; + case "colon-list-separator": + return (key, value, accumulator) => { + result = /(:list)$/.exec(key); + key = key.replace(/:list$/, ""); + if (!result) { + accumulator[key] = value; + return; + } + if (accumulator[key] === void 0) { + accumulator[key] = [value]; + return; + } + accumulator[key] = [].concat(accumulator[key], value); + }; + case "comma": + case "separator": + return (key, value, accumulator) => { + const isArray = typeof value === "string" && value.includes(options.arrayFormatSeparator); + const isEncodedArray = typeof value === "string" && !isArray && decode6(value, options).includes(options.arrayFormatSeparator); + value = isEncodedArray ? decode6(value, options) : value; + const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)) : value === null ? value : decode6(value, options); + accumulator[key] = newValue; + }; + case "bracket-separator": + return (key, value, accumulator) => { + const isArray = /(\[\])$/.test(key); + key = key.replace(/\[\]$/, ""); + if (!isArray) { + accumulator[key] = value ? decode6(value, options) : value; + return; + } + const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)); + if (accumulator[key] === void 0) { + accumulator[key] = arrayValue; + return; + } + accumulator[key] = [].concat(accumulator[key], arrayValue); + }; + default: + return (key, value, accumulator) => { + if (accumulator[key] === void 0) { + accumulator[key] = value; + return; + } + accumulator[key] = [].concat(accumulator[key], value); + }; + } + } + function validateArrayFormatSeparator(value) { + if (typeof value !== "string" || value.length !== 1) { + throw new TypeError("arrayFormatSeparator must be single character string"); + } + } + function encode5(value, options) { + if (options.encode) { + return options.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + return value; + } + function decode6(value, options) { + if (options.decode) { + return decodeComponent(value); + } + return value; + } + function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } + if (typeof input === "object") { + return keysSorter(Object.keys(input)).sort((a3, b4) => Number(a3) - Number(b4)).map((key) => input[key]); + } + return input; + } + function removeHash(input) { + const hashStart = input.indexOf("#"); + if (hashStart !== -1) { + input = input.slice(0, hashStart); + } + return input; + } + function getHash(url) { + let hash = ""; + const hashStart = url.indexOf("#"); + if (hashStart !== -1) { + hash = url.slice(hashStart); + } + return hash; + } + function extract(input) { + input = removeHash(input); + const queryStart = input.indexOf("?"); + if (queryStart === -1) { + return ""; + } + return input.slice(queryStart + 1); + } + function parseValue(value, options) { + if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === "string" && value.trim() !== "")) { + value = Number(value); + } else if (options.parseBooleans && value !== null && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) { + value = value.toLowerCase() === "true"; + } + return value; + } + function parse(query, options) { + options = Object.assign({ + decode: true, + sort: true, + arrayFormat: "none", + arrayFormatSeparator: ",", + parseNumbers: false, + parseBooleans: false + }, options); + validateArrayFormatSeparator(options.arrayFormatSeparator); + const formatter = parserForArrayFormat(options); + const ret = /* @__PURE__ */ Object.create(null); + if (typeof query !== "string") { + return ret; + } + query = query.trim().replace(/^[?#&]/, ""); + if (!query) { + return ret; + } + for (const param of query.split("&")) { + if (param === "") { + continue; + } + let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, " ") : param, "="); + value = value === void 0 ? null : ["comma", "separator", "bracket-separator"].includes(options.arrayFormat) ? value : decode6(value, options); + formatter(decode6(key, options), value, ret); + } + for (const key of Object.keys(ret)) { + const value = ret[key]; + if (typeof value === "object" && value !== null) { + for (const k4 of Object.keys(value)) { + value[k4] = parseValue(value[k4], options); + } + } else { + ret[key] = parseValue(value, options); + } + } + if (options.sort === false) { + return ret; + } + return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { + const value = ret[key]; + if (Boolean(value) && typeof value === "object" && !Array.isArray(value)) { + result[key] = keysSorter(value); + } else { + result[key] = value; + } + return result; + }, /* @__PURE__ */ Object.create(null)); + } + exports2.extract = extract; + exports2.parse = parse; + exports2.stringify = (object, options) => { + if (!object) { + return ""; + } + options = Object.assign({ + encode: true, + strict: true, + arrayFormat: "none", + arrayFormatSeparator: "," + }, options); + validateArrayFormatSeparator(options.arrayFormatSeparator); + const shouldFilter = (key) => options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === ""; + const formatter = encoderForArrayFormat(options); + const objectCopy = {}; + for (const key of Object.keys(object)) { + if (!shouldFilter(key)) { + objectCopy[key] = object[key]; + } + } + const keys2 = Object.keys(objectCopy); + if (options.sort !== false) { + keys2.sort(options.sort); + } + return keys2.map((key) => { + const value = object[key]; + if (value === void 0) { + return ""; + } + if (value === null) { + return encode5(key, options); + } + if (Array.isArray(value)) { + if (value.length === 0 && options.arrayFormat === "bracket-separator") { + return encode5(key, options) + "[]"; + } + return value.reduce(formatter(key), []).join("&"); + } + return encode5(key, options) + "=" + encode5(value, options); + }).filter((x3) => x3.length > 0).join("&"); + }; + exports2.parseUrl = (url, options) => { + options = Object.assign({ + decode: true + }, options); + const [url_, hash] = splitOnFirst(url, "#"); + return Object.assign( + { + url: url_.split("?")[0] || "", + query: parse(extract(url), options) + }, + options && options.parseFragmentIdentifier && hash ? { fragmentIdentifier: decode6(hash, options) } : {} + ); + }; + exports2.stringifyUrl = (object, options) => { + options = Object.assign({ + encode: true, + strict: true, + [encodeFragmentIdentifier]: true + }, options); + const url = removeHash(object.url).split("?")[0] || ""; + const queryFromUrl = exports2.extract(object.url); + const parsedQueryFromUrl = exports2.parse(queryFromUrl, { sort: false }); + const query = Object.assign(parsedQueryFromUrl, object.query); + let queryString = exports2.stringify(query, options); + if (queryString) { + queryString = `?${queryString}`; + } + let hash = getHash(object.url); + if (object.fragmentIdentifier) { + hash = `#${options[encodeFragmentIdentifier] ? encode5(object.fragmentIdentifier, options) : object.fragmentIdentifier}`; + } + return `${url}${queryString}${hash}`; + }; + exports2.pick = (input, filter, options) => { + options = Object.assign({ + parseFragmentIdentifier: true, + [encodeFragmentIdentifier]: false + }, options); + const { url, query, fragmentIdentifier } = exports2.parseUrl(input, options); + return exports2.stringifyUrl({ + url, + query: filterObject(query, filter), + fragmentIdentifier + }, options); + }; + exports2.exclude = (input, filter, options) => { + const exclusionFilter = Array.isArray(filter) ? (key) => !filter.includes(key) : (key, value) => !filter(key, value); + return exports2.pick(input, exclusionFilter, options); + }; + } +}); + +// node_modules/@stablelib/chacha/lib/chacha.js +var require_chacha = __commonJS({ + "node_modules/@stablelib/chacha/lib/chacha.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + var ROUNDS = 20; + function core(out, input, key) { + var j0 = 1634760805; + var j1 = 857760878; + var j2 = 2036477234; + var j3 = 1797285236; + var j4 = key[3] << 24 | key[2] << 16 | key[1] << 8 | key[0]; + var j5 = key[7] << 24 | key[6] << 16 | key[5] << 8 | key[4]; + var j6 = key[11] << 24 | key[10] << 16 | key[9] << 8 | key[8]; + var j7 = key[15] << 24 | key[14] << 16 | key[13] << 8 | key[12]; + var j8 = key[19] << 24 | key[18] << 16 | key[17] << 8 | key[16]; + var j9 = key[23] << 24 | key[22] << 16 | key[21] << 8 | key[20]; + var j10 = key[27] << 24 | key[26] << 16 | key[25] << 8 | key[24]; + var j11 = key[31] << 24 | key[30] << 16 | key[29] << 8 | key[28]; + var j12 = input[3] << 24 | input[2] << 16 | input[1] << 8 | input[0]; + var j13 = input[7] << 24 | input[6] << 16 | input[5] << 8 | input[4]; + var j14 = input[11] << 24 | input[10] << 16 | input[9] << 8 | input[8]; + var j15 = input[15] << 24 | input[14] << 16 | input[13] << 8 | input[12]; + var x0 = j0; + var x1 = j1; + var x22 = j2; + var x3 = j3; + var x4 = j4; + var x5 = j5; + var x6 = j6; + var x7 = j7; + var x8 = j8; + var x9 = j9; + var x10 = j10; + var x11 = j11; + var x12 = j12; + var x13 = j13; + var x14 = j14; + var x15 = j15; + for (var i2 = 0; i2 < ROUNDS; i2 += 2) { + x0 = x0 + x4 | 0; + x12 ^= x0; + x12 = x12 >>> 32 - 16 | x12 << 16; + x8 = x8 + x12 | 0; + x4 ^= x8; + x4 = x4 >>> 32 - 12 | x4 << 12; + x1 = x1 + x5 | 0; + x13 ^= x1; + x13 = x13 >>> 32 - 16 | x13 << 16; + x9 = x9 + x13 | 0; + x5 ^= x9; + x5 = x5 >>> 32 - 12 | x5 << 12; + x22 = x22 + x6 | 0; + x14 ^= x22; + x14 = x14 >>> 32 - 16 | x14 << 16; + x10 = x10 + x14 | 0; + x6 ^= x10; + x6 = x6 >>> 32 - 12 | x6 << 12; + x3 = x3 + x7 | 0; + x15 ^= x3; + x15 = x15 >>> 32 - 16 | x15 << 16; + x11 = x11 + x15 | 0; + x7 ^= x11; + x7 = x7 >>> 32 - 12 | x7 << 12; + x22 = x22 + x6 | 0; + x14 ^= x22; + x14 = x14 >>> 32 - 8 | x14 << 8; + x10 = x10 + x14 | 0; + x6 ^= x10; + x6 = x6 >>> 32 - 7 | x6 << 7; + x3 = x3 + x7 | 0; + x15 ^= x3; + x15 = x15 >>> 32 - 8 | x15 << 8; + x11 = x11 + x15 | 0; + x7 ^= x11; + x7 = x7 >>> 32 - 7 | x7 << 7; + x1 = x1 + x5 | 0; + x13 ^= x1; + x13 = x13 >>> 32 - 8 | x13 << 8; + x9 = x9 + x13 | 0; + x5 ^= x9; + x5 = x5 >>> 32 - 7 | x5 << 7; + x0 = x0 + x4 | 0; + x12 ^= x0; + x12 = x12 >>> 32 - 8 | x12 << 8; + x8 = x8 + x12 | 0; + x4 ^= x8; + x4 = x4 >>> 32 - 7 | x4 << 7; + x0 = x0 + x5 | 0; + x15 ^= x0; + x15 = x15 >>> 32 - 16 | x15 << 16; + x10 = x10 + x15 | 0; + x5 ^= x10; + x5 = x5 >>> 32 - 12 | x5 << 12; + x1 = x1 + x6 | 0; + x12 ^= x1; + x12 = x12 >>> 32 - 16 | x12 << 16; + x11 = x11 + x12 | 0; + x6 ^= x11; + x6 = x6 >>> 32 - 12 | x6 << 12; + x22 = x22 + x7 | 0; + x13 ^= x22; + x13 = x13 >>> 32 - 16 | x13 << 16; + x8 = x8 + x13 | 0; + x7 ^= x8; + x7 = x7 >>> 32 - 12 | x7 << 12; + x3 = x3 + x4 | 0; + x14 ^= x3; + x14 = x14 >>> 32 - 16 | x14 << 16; + x9 = x9 + x14 | 0; + x4 ^= x9; + x4 = x4 >>> 32 - 12 | x4 << 12; + x22 = x22 + x7 | 0; + x13 ^= x22; + x13 = x13 >>> 32 - 8 | x13 << 8; + x8 = x8 + x13 | 0; + x7 ^= x8; + x7 = x7 >>> 32 - 7 | x7 << 7; + x3 = x3 + x4 | 0; + x14 ^= x3; + x14 = x14 >>> 32 - 8 | x14 << 8; + x9 = x9 + x14 | 0; + x4 ^= x9; + x4 = x4 >>> 32 - 7 | x4 << 7; + x1 = x1 + x6 | 0; + x12 ^= x1; + x12 = x12 >>> 32 - 8 | x12 << 8; + x11 = x11 + x12 | 0; + x6 ^= x11; + x6 = x6 >>> 32 - 7 | x6 << 7; + x0 = x0 + x5 | 0; + x15 ^= x0; + x15 = x15 >>> 32 - 8 | x15 << 8; + x10 = x10 + x15 | 0; + x5 ^= x10; + x5 = x5 >>> 32 - 7 | x5 << 7; + } + binary_1.writeUint32LE(x0 + j0 | 0, out, 0); + binary_1.writeUint32LE(x1 + j1 | 0, out, 4); + binary_1.writeUint32LE(x22 + j2 | 0, out, 8); + binary_1.writeUint32LE(x3 + j3 | 0, out, 12); + binary_1.writeUint32LE(x4 + j4 | 0, out, 16); + binary_1.writeUint32LE(x5 + j5 | 0, out, 20); + binary_1.writeUint32LE(x6 + j6 | 0, out, 24); + binary_1.writeUint32LE(x7 + j7 | 0, out, 28); + binary_1.writeUint32LE(x8 + j8 | 0, out, 32); + binary_1.writeUint32LE(x9 + j9 | 0, out, 36); + binary_1.writeUint32LE(x10 + j10 | 0, out, 40); + binary_1.writeUint32LE(x11 + j11 | 0, out, 44); + binary_1.writeUint32LE(x12 + j12 | 0, out, 48); + binary_1.writeUint32LE(x13 + j13 | 0, out, 52); + binary_1.writeUint32LE(x14 + j14 | 0, out, 56); + binary_1.writeUint32LE(x15 + j15 | 0, out, 60); + } + function streamXOR(key, nonce, src2, dst, nonceInplaceCounterLength) { + if (nonceInplaceCounterLength === void 0) { + nonceInplaceCounterLength = 0; + } + if (key.length !== 32) { + throw new Error("ChaCha: key size must be 32 bytes"); + } + if (dst.length < src2.length) { + throw new Error("ChaCha: destination is shorter than source"); + } + var nc; + var counterLength; + if (nonceInplaceCounterLength === 0) { + if (nonce.length !== 8 && nonce.length !== 12) { + throw new Error("ChaCha nonce must be 8 or 12 bytes"); + } + nc = new Uint8Array(16); + counterLength = nc.length - nonce.length; + nc.set(nonce, counterLength); + } else { + if (nonce.length !== 16) { + throw new Error("ChaCha nonce with counter must be 16 bytes"); + } + nc = nonce; + counterLength = nonceInplaceCounterLength; + } + var block = new Uint8Array(64); + for (var i2 = 0; i2 < src2.length; i2 += 64) { + core(block, nc, key); + for (var j2 = i2; j2 < i2 + 64 && j2 < src2.length; j2++) { + dst[j2] = src2[j2] ^ block[j2 - i2]; + } + incrementCounter(nc, 0, counterLength); + } + wipe_1.wipe(block); + if (nonceInplaceCounterLength === 0) { + wipe_1.wipe(nc); + } + return dst; + } + exports2.streamXOR = streamXOR; + function stream(key, nonce, dst, nonceInplaceCounterLength) { + if (nonceInplaceCounterLength === void 0) { + nonceInplaceCounterLength = 0; + } + wipe_1.wipe(dst); + return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength); + } + exports2.stream = stream; + function incrementCounter(counter, pos, len) { + var carry = 1; + while (len--) { + carry = carry + (counter[pos] & 255) | 0; + counter[pos] = carry & 255; + carry >>>= 8; + pos++; + } + if (carry > 0) { + throw new Error("ChaCha: counter overflow"); + } + } + } +}); + +// node_modules/@stablelib/constant-time/lib/constant-time.js +var require_constant_time = __commonJS({ + "node_modules/@stablelib/constant-time/lib/constant-time.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function select(subject, resultIfOne, resultIfZero) { + return ~(subject - 1) & resultIfOne | subject - 1 & resultIfZero; + } + exports2.select = select; + function lessOrEqual(a3, b4) { + return (a3 | 0) - (b4 | 0) - 1 >>> 31 & 1; + } + exports2.lessOrEqual = lessOrEqual; + function compare3(a3, b4) { + if (a3.length !== b4.length) { + return 0; + } + var result = 0; + for (var i2 = 0; i2 < a3.length; i2++) { + result |= a3[i2] ^ b4[i2]; + } + return 1 & result - 1 >>> 8; + } + exports2.compare = compare3; + function equal(a3, b4) { + if (a3.length === 0 || b4.length === 0) { + return false; + } + return compare3(a3, b4) !== 0; + } + exports2.equal = equal; + } +}); + +// node_modules/@stablelib/poly1305/lib/poly1305.js +var require_poly1305 = __commonJS({ + "node_modules/@stablelib/poly1305/lib/poly1305.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var constant_time_1 = require_constant_time(); + var wipe_1 = require_wipe(); + exports2.DIGEST_LENGTH = 16; + var Poly1305 = ( + /** @class */ + function() { + function Poly13052(key) { + this.digestLength = exports2.DIGEST_LENGTH; + this._buffer = new Uint8Array(16); + this._r = new Uint16Array(10); + this._h = new Uint16Array(10); + this._pad = new Uint16Array(8); + this._leftover = 0; + this._fin = 0; + this._finished = false; + var t0 = key[0] | key[1] << 8; + this._r[0] = t0 & 8191; + var t1 = key[2] | key[3] << 8; + this._r[1] = (t0 >>> 13 | t1 << 3) & 8191; + var t2 = key[4] | key[5] << 8; + this._r[2] = (t1 >>> 10 | t2 << 6) & 7939; + var t3 = key[6] | key[7] << 8; + this._r[3] = (t2 >>> 7 | t3 << 9) & 8191; + var t4 = key[8] | key[9] << 8; + this._r[4] = (t3 >>> 4 | t4 << 12) & 255; + this._r[5] = t4 >>> 1 & 8190; + var t5 = key[10] | key[11] << 8; + this._r[6] = (t4 >>> 14 | t5 << 2) & 8191; + var t6 = key[12] | key[13] << 8; + this._r[7] = (t5 >>> 11 | t6 << 5) & 8065; + var t7 = key[14] | key[15] << 8; + this._r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this._r[9] = t7 >>> 5 & 127; + this._pad[0] = key[16] | key[17] << 8; + this._pad[1] = key[18] | key[19] << 8; + this._pad[2] = key[20] | key[21] << 8; + this._pad[3] = key[22] | key[23] << 8; + this._pad[4] = key[24] | key[25] << 8; + this._pad[5] = key[26] | key[27] << 8; + this._pad[6] = key[28] | key[29] << 8; + this._pad[7] = key[30] | key[31] << 8; + } + Poly13052.prototype._blocks = function(m3, mpos, bytes) { + var hibit = this._fin ? 0 : 1 << 11; + var h0 = this._h[0], h1 = this._h[1], h22 = this._h[2], h32 = this._h[3], h42 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9]; + var r0 = this._r[0], r1 = this._r[1], r2 = this._r[2], r3 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9]; + while (bytes >= 16) { + var t0 = m3[mpos + 0] | m3[mpos + 1] << 8; + h0 += t0 & 8191; + var t1 = m3[mpos + 2] | m3[mpos + 3] << 8; + h1 += (t0 >>> 13 | t1 << 3) & 8191; + var t2 = m3[mpos + 4] | m3[mpos + 5] << 8; + h22 += (t1 >>> 10 | t2 << 6) & 8191; + var t3 = m3[mpos + 6] | m3[mpos + 7] << 8; + h32 += (t2 >>> 7 | t3 << 9) & 8191; + var t4 = m3[mpos + 8] | m3[mpos + 9] << 8; + h42 += (t3 >>> 4 | t4 << 12) & 8191; + h5 += t4 >>> 1 & 8191; + var t5 = m3[mpos + 10] | m3[mpos + 11] << 8; + h6 += (t4 >>> 14 | t5 << 2) & 8191; + var t6 = m3[mpos + 12] | m3[mpos + 13] << 8; + h7 += (t5 >>> 11 | t6 << 5) & 8191; + var t7 = m3[mpos + 14] | m3[mpos + 15] << 8; + h8 += (t6 >>> 8 | t7 << 8) & 8191; + h9 += t7 >>> 5 | hibit; + var c4 = 0; + var d0 = c4; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h22 * (5 * r8); + d0 += h32 * (5 * r7); + d0 += h42 * (5 * r6); + c4 = d0 >>> 13; + d0 &= 8191; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c4 += d0 >>> 13; + d0 &= 8191; + var d1 = c4; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h22 * (5 * r9); + d1 += h32 * (5 * r8); + d1 += h42 * (5 * r7); + c4 = d1 >>> 13; + d1 &= 8191; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c4 += d1 >>> 13; + d1 &= 8191; + var d22 = c4; + d22 += h0 * r2; + d22 += h1 * r1; + d22 += h22 * r0; + d22 += h32 * (5 * r9); + d22 += h42 * (5 * r8); + c4 = d22 >>> 13; + d22 &= 8191; + d22 += h5 * (5 * r7); + d22 += h6 * (5 * r6); + d22 += h7 * (5 * r5); + d22 += h8 * (5 * r4); + d22 += h9 * (5 * r3); + c4 += d22 >>> 13; + d22 &= 8191; + var d3 = c4; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h22 * r1; + d3 += h32 * r0; + d3 += h42 * (5 * r9); + c4 = d3 >>> 13; + d3 &= 8191; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c4 += d3 >>> 13; + d3 &= 8191; + var d4 = c4; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h22 * r2; + d4 += h32 * r1; + d4 += h42 * r0; + c4 = d4 >>> 13; + d4 &= 8191; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c4 += d4 >>> 13; + d4 &= 8191; + var d5 = c4; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h22 * r3; + d5 += h32 * r2; + d5 += h42 * r1; + c4 = d5 >>> 13; + d5 &= 8191; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c4 += d5 >>> 13; + d5 &= 8191; + var d6 = c4; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h22 * r4; + d6 += h32 * r3; + d6 += h42 * r2; + c4 = d6 >>> 13; + d6 &= 8191; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c4 += d6 >>> 13; + d6 &= 8191; + var d7 = c4; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h22 * r5; + d7 += h32 * r4; + d7 += h42 * r3; + c4 = d7 >>> 13; + d7 &= 8191; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c4 += d7 >>> 13; + d7 &= 8191; + var d8 = c4; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h22 * r6; + d8 += h32 * r5; + d8 += h42 * r4; + c4 = d8 >>> 13; + d8 &= 8191; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c4 += d8 >>> 13; + d8 &= 8191; + var d9 = c4; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h22 * r7; + d9 += h32 * r6; + d9 += h42 * r5; + c4 = d9 >>> 13; + d9 &= 8191; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c4 += d9 >>> 13; + d9 &= 8191; + c4 = (c4 << 2) + c4 | 0; + c4 = c4 + d0 | 0; + d0 = c4 & 8191; + c4 = c4 >>> 13; + d1 += c4; + h0 = d0; + h1 = d1; + h22 = d22; + h32 = d3; + h42 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + mpos += 16; + bytes -= 16; + } + this._h[0] = h0; + this._h[1] = h1; + this._h[2] = h22; + this._h[3] = h32; + this._h[4] = h42; + this._h[5] = h5; + this._h[6] = h6; + this._h[7] = h7; + this._h[8] = h8; + this._h[9] = h9; + }; + Poly13052.prototype.finish = function(mac, macpos) { + if (macpos === void 0) { + macpos = 0; + } + var g3 = new Uint16Array(10); + var c4; + var mask; + var f4; + var i2; + if (this._leftover) { + i2 = this._leftover; + this._buffer[i2++] = 1; + for (; i2 < 16; i2++) { + this._buffer[i2] = 0; + } + this._fin = 1; + this._blocks(this._buffer, 0, 16); + } + c4 = this._h[1] >>> 13; + this._h[1] &= 8191; + for (i2 = 2; i2 < 10; i2++) { + this._h[i2] += c4; + c4 = this._h[i2] >>> 13; + this._h[i2] &= 8191; + } + this._h[0] += c4 * 5; + c4 = this._h[0] >>> 13; + this._h[0] &= 8191; + this._h[1] += c4; + c4 = this._h[1] >>> 13; + this._h[1] &= 8191; + this._h[2] += c4; + g3[0] = this._h[0] + 5; + c4 = g3[0] >>> 13; + g3[0] &= 8191; + for (i2 = 1; i2 < 10; i2++) { + g3[i2] = this._h[i2] + c4; + c4 = g3[i2] >>> 13; + g3[i2] &= 8191; + } + g3[9] -= 1 << 13; + mask = (c4 ^ 1) - 1; + for (i2 = 0; i2 < 10; i2++) { + g3[i2] &= mask; + } + mask = ~mask; + for (i2 = 0; i2 < 10; i2++) { + this._h[i2] = this._h[i2] & mask | g3[i2]; + } + this._h[0] = (this._h[0] | this._h[1] << 13) & 65535; + this._h[1] = (this._h[1] >>> 3 | this._h[2] << 10) & 65535; + this._h[2] = (this._h[2] >>> 6 | this._h[3] << 7) & 65535; + this._h[3] = (this._h[3] >>> 9 | this._h[4] << 4) & 65535; + this._h[4] = (this._h[4] >>> 12 | this._h[5] << 1 | this._h[6] << 14) & 65535; + this._h[5] = (this._h[6] >>> 2 | this._h[7] << 11) & 65535; + this._h[6] = (this._h[7] >>> 5 | this._h[8] << 8) & 65535; + this._h[7] = (this._h[8] >>> 8 | this._h[9] << 5) & 65535; + f4 = this._h[0] + this._pad[0]; + this._h[0] = f4 & 65535; + for (i2 = 1; i2 < 8; i2++) { + f4 = (this._h[i2] + this._pad[i2] | 0) + (f4 >>> 16) | 0; + this._h[i2] = f4 & 65535; + } + mac[macpos + 0] = this._h[0] >>> 0; + mac[macpos + 1] = this._h[0] >>> 8; + mac[macpos + 2] = this._h[1] >>> 0; + mac[macpos + 3] = this._h[1] >>> 8; + mac[macpos + 4] = this._h[2] >>> 0; + mac[macpos + 5] = this._h[2] >>> 8; + mac[macpos + 6] = this._h[3] >>> 0; + mac[macpos + 7] = this._h[3] >>> 8; + mac[macpos + 8] = this._h[4] >>> 0; + mac[macpos + 9] = this._h[4] >>> 8; + mac[macpos + 10] = this._h[5] >>> 0; + mac[macpos + 11] = this._h[5] >>> 8; + mac[macpos + 12] = this._h[6] >>> 0; + mac[macpos + 13] = this._h[6] >>> 8; + mac[macpos + 14] = this._h[7] >>> 0; + mac[macpos + 15] = this._h[7] >>> 8; + this._finished = true; + return this; + }; + Poly13052.prototype.update = function(m3) { + var mpos = 0; + var bytes = m3.length; + var want; + if (this._leftover) { + want = 16 - this._leftover; + if (want > bytes) { + want = bytes; + } + for (var i2 = 0; i2 < want; i2++) { + this._buffer[this._leftover + i2] = m3[mpos + i2]; + } + bytes -= want; + mpos += want; + this._leftover += want; + if (this._leftover < 16) { + return this; + } + this._blocks(this._buffer, 0, 16); + this._leftover = 0; + } + if (bytes >= 16) { + want = bytes - bytes % 16; + this._blocks(m3, mpos, want); + mpos += want; + bytes -= want; + } + if (bytes) { + for (var i2 = 0; i2 < bytes; i2++) { + this._buffer[this._leftover + i2] = m3[mpos + i2]; + } + this._leftover += bytes; + } + return this; + }; + Poly13052.prototype.digest = function() { + if (this._finished) { + throw new Error("Poly1305 was finished"); + } + var mac = new Uint8Array(16); + this.finish(mac); + return mac; + }; + Poly13052.prototype.clean = function() { + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._r); + wipe_1.wipe(this._h); + wipe_1.wipe(this._pad); + this._leftover = 0; + this._fin = 0; + this._finished = true; + return this; + }; + return Poly13052; + }() + ); + exports2.Poly1305 = Poly1305; + function oneTimeAuth(key, data) { + var h5 = new Poly1305(key); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.oneTimeAuth = oneTimeAuth; + function equal(a3, b4) { + if (a3.length !== exports2.DIGEST_LENGTH || b4.length !== exports2.DIGEST_LENGTH) { + return false; + } + return constant_time_1.equal(a3, b4); + } + exports2.equal = equal; + } +}); + +// node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js +var require_chacha20poly1305 = __commonJS({ + "node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var chacha_1 = require_chacha(); + var poly1305_1 = require_poly1305(); + var wipe_1 = require_wipe(); + var binary_1 = require_binary2(); + var constant_time_1 = require_constant_time(); + exports2.KEY_LENGTH = 32; + exports2.NONCE_LENGTH = 12; + exports2.TAG_LENGTH = 16; + var ZEROS = new Uint8Array(16); + var ChaCha20Poly1305 = ( + /** @class */ + function() { + function ChaCha20Poly13052(key) { + this.nonceLength = exports2.NONCE_LENGTH; + this.tagLength = exports2.TAG_LENGTH; + if (key.length !== exports2.KEY_LENGTH) { + throw new Error("ChaCha20Poly1305 needs 32-byte key"); + } + this._key = new Uint8Array(key); + } + ChaCha20Poly13052.prototype.seal = function(nonce, plaintext, associatedData, dst) { + if (nonce.length > 16) { + throw new Error("ChaCha20Poly1305: incorrect nonce length"); + } + var counter = new Uint8Array(16); + counter.set(nonce, counter.length - nonce.length); + var authKey = new Uint8Array(32); + chacha_1.stream(this._key, counter, authKey, 4); + var resultLength = plaintext.length + this.tagLength; + var result; + if (dst) { + if (dst.length !== resultLength) { + throw new Error("ChaCha20Poly1305: incorrect destination length"); + } + result = dst; + } else { + result = new Uint8Array(resultLength); + } + chacha_1.streamXOR(this._key, counter, plaintext, result, 4); + this._authenticate(result.subarray(result.length - this.tagLength, result.length), authKey, result.subarray(0, result.length - this.tagLength), associatedData); + wipe_1.wipe(counter); + return result; + }; + ChaCha20Poly13052.prototype.open = function(nonce, sealed, associatedData, dst) { + if (nonce.length > 16) { + throw new Error("ChaCha20Poly1305: incorrect nonce length"); + } + if (sealed.length < this.tagLength) { + return null; + } + var counter = new Uint8Array(16); + counter.set(nonce, counter.length - nonce.length); + var authKey = new Uint8Array(32); + chacha_1.stream(this._key, counter, authKey, 4); + var calculatedTag = new Uint8Array(this.tagLength); + this._authenticate(calculatedTag, authKey, sealed.subarray(0, sealed.length - this.tagLength), associatedData); + if (!constant_time_1.equal(calculatedTag, sealed.subarray(sealed.length - this.tagLength, sealed.length))) { + return null; + } + var resultLength = sealed.length - this.tagLength; + var result; + if (dst) { + if (dst.length !== resultLength) { + throw new Error("ChaCha20Poly1305: incorrect destination length"); + } + result = dst; + } else { + result = new Uint8Array(resultLength); + } + chacha_1.streamXOR(this._key, counter, sealed.subarray(0, sealed.length - this.tagLength), result, 4); + wipe_1.wipe(counter); + return result; + }; + ChaCha20Poly13052.prototype.clean = function() { + wipe_1.wipe(this._key); + return this; + }; + ChaCha20Poly13052.prototype._authenticate = function(tagOut, authKey, ciphertext, associatedData) { + var h5 = new poly1305_1.Poly1305(authKey); + if (associatedData) { + h5.update(associatedData); + if (associatedData.length % 16 > 0) { + h5.update(ZEROS.subarray(associatedData.length % 16)); + } + } + h5.update(ciphertext); + if (ciphertext.length % 16 > 0) { + h5.update(ZEROS.subarray(ciphertext.length % 16)); + } + var length2 = new Uint8Array(8); + if (associatedData) { + binary_1.writeUint64LE(associatedData.length, length2); + } + h5.update(length2); + binary_1.writeUint64LE(ciphertext.length, length2); + h5.update(length2); + var tag = h5.digest(); + for (var i2 = 0; i2 < tag.length; i2++) { + tagOut[i2] = tag[i2]; + } + h5.clean(); + wipe_1.wipe(tag); + wipe_1.wipe(length2); + }; + return ChaCha20Poly13052; + }() + ); + exports2.ChaCha20Poly1305 = ChaCha20Poly1305; + } +}); + +// node_modules/@stablelib/hash/lib/hash.js +var require_hash2 = __commonJS({ + "node_modules/@stablelib/hash/lib/hash.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + function isSerializableHash(h5) { + return typeof h5.saveState !== "undefined" && typeof h5.restoreState !== "undefined" && typeof h5.cleanSavedState !== "undefined"; + } + exports2.isSerializableHash = isSerializableHash; + } +}); + +// node_modules/@stablelib/hmac/lib/hmac.js +var require_hmac = __commonJS({ + "node_modules/@stablelib/hmac/lib/hmac.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var hash_1 = require_hash2(); + var constant_time_1 = require_constant_time(); + var wipe_1 = require_wipe(); + var HMAC = ( + /** @class */ + function() { + function HMAC2(hash, key) { + this._finished = false; + this._inner = new hash(); + this._outer = new hash(); + this.blockSize = this._outer.blockSize; + this.digestLength = this._outer.digestLength; + var pad = new Uint8Array(this.blockSize); + if (key.length > this.blockSize) { + this._inner.update(key).finish(pad).clean(); + } else { + pad.set(key); + } + for (var i2 = 0; i2 < pad.length; i2++) { + pad[i2] ^= 54; + } + this._inner.update(pad); + for (var i2 = 0; i2 < pad.length; i2++) { + pad[i2] ^= 54 ^ 92; + } + this._outer.update(pad); + if (hash_1.isSerializableHash(this._inner) && hash_1.isSerializableHash(this._outer)) { + this._innerKeyedState = this._inner.saveState(); + this._outerKeyedState = this._outer.saveState(); + } + wipe_1.wipe(pad); + } + HMAC2.prototype.reset = function() { + if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { + throw new Error("hmac: can't reset() because hash doesn't implement restoreState()"); + } + this._inner.restoreState(this._innerKeyedState); + this._outer.restoreState(this._outerKeyedState); + this._finished = false; + return this; + }; + HMAC2.prototype.clean = function() { + if (hash_1.isSerializableHash(this._inner)) { + this._inner.cleanSavedState(this._innerKeyedState); + } + if (hash_1.isSerializableHash(this._outer)) { + this._outer.cleanSavedState(this._outerKeyedState); + } + this._inner.clean(); + this._outer.clean(); + }; + HMAC2.prototype.update = function(data) { + this._inner.update(data); + return this; + }; + HMAC2.prototype.finish = function(out) { + if (this._finished) { + this._outer.finish(out); + return this; + } + this._inner.finish(out); + this._outer.update(out.subarray(0, this.digestLength)).finish(out); + this._finished = true; + return this; + }; + HMAC2.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + HMAC2.prototype.saveState = function() { + if (!hash_1.isSerializableHash(this._inner)) { + throw new Error("hmac: can't saveState() because hash doesn't implement it"); + } + return this._inner.saveState(); + }; + HMAC2.prototype.restoreState = function(savedState) { + if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { + throw new Error("hmac: can't restoreState() because hash doesn't implement it"); + } + this._inner.restoreState(savedState); + this._outer.restoreState(this._outerKeyedState); + this._finished = false; + return this; + }; + HMAC2.prototype.cleanSavedState = function(savedState) { + if (!hash_1.isSerializableHash(this._inner)) { + throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it"); + } + this._inner.cleanSavedState(savedState); + }; + return HMAC2; + }() + ); + exports2.HMAC = HMAC; + function hmac(hash, key, data) { + var h5 = new HMAC(hash, key); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.hmac = hmac; + exports2.equal = constant_time_1.equal; + } +}); + +// node_modules/@stablelib/hkdf/lib/hkdf.js +var require_hkdf = __commonJS({ + "node_modules/@stablelib/hkdf/lib/hkdf.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var hmac_1 = require_hmac(); + var wipe_1 = require_wipe(); + var HKDF = ( + /** @class */ + function() { + function HKDF2(hash, key, salt, info) { + if (salt === void 0) { + salt = new Uint8Array(0); + } + this._counter = new Uint8Array(1); + this._hash = hash; + this._info = info; + var okm = hmac_1.hmac(this._hash, salt, key); + this._hmac = new hmac_1.HMAC(hash, okm); + this._buffer = new Uint8Array(this._hmac.digestLength); + this._bufpos = this._buffer.length; + } + HKDF2.prototype._fillBuffer = function() { + this._counter[0]++; + var ctr = this._counter[0]; + if (ctr === 0) { + throw new Error("hkdf: cannot expand more"); + } + this._hmac.reset(); + if (ctr > 1) { + this._hmac.update(this._buffer); + } + if (this._info) { + this._hmac.update(this._info); + } + this._hmac.update(this._counter); + this._hmac.finish(this._buffer); + this._bufpos = 0; + }; + HKDF2.prototype.expand = function(length2) { + var out = new Uint8Array(length2); + for (var i2 = 0; i2 < out.length; i2++) { + if (this._bufpos === this._buffer.length) { + this._fillBuffer(); + } + out[i2] = this._buffer[this._bufpos++]; + } + return out; + }; + HKDF2.prototype.clean = function() { + this._hmac.clean(); + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._counter); + this._bufpos = 0; + }; + return HKDF2; + }() + ); + exports2.HKDF = HKDF; + } +}); + +// node_modules/@stablelib/sha256/lib/sha256.js +var require_sha256 = __commonJS({ + "node_modules/@stablelib/sha256/lib/sha256.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var binary_1 = require_binary2(); + var wipe_1 = require_wipe(); + exports2.DIGEST_LENGTH = 32; + exports2.BLOCK_SIZE = 64; + var SHA256 = ( + /** @class */ + function() { + function SHA2562() { + this.digestLength = exports2.DIGEST_LENGTH; + this.blockSize = exports2.BLOCK_SIZE; + this._state = new Int32Array(8); + this._temp = new Int32Array(64); + this._buffer = new Uint8Array(128); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + this.reset(); + } + SHA2562.prototype._initState = function() { + this._state[0] = 1779033703; + this._state[1] = 3144134277; + this._state[2] = 1013904242; + this._state[3] = 2773480762; + this._state[4] = 1359893119; + this._state[5] = 2600822924; + this._state[6] = 528734635; + this._state[7] = 1541459225; + }; + SHA2562.prototype.reset = function() { + this._initState(); + this._bufferLength = 0; + this._bytesHashed = 0; + this._finished = false; + return this; + }; + SHA2562.prototype.clean = function() { + wipe_1.wipe(this._buffer); + wipe_1.wipe(this._temp); + this.reset(); + }; + SHA2562.prototype.update = function(data, dataLength) { + if (dataLength === void 0) { + dataLength = data.length; + } + if (this._finished) { + throw new Error("SHA256: can't update because hash was finished."); + } + var dataPos = 0; + this._bytesHashed += dataLength; + if (this._bufferLength > 0) { + while (this._bufferLength < this.blockSize && dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + if (this._bufferLength === this.blockSize) { + hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize); + this._bufferLength = 0; + } + } + if (dataLength >= this.blockSize) { + dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength); + dataLength %= this.blockSize; + } + while (dataLength > 0) { + this._buffer[this._bufferLength++] = data[dataPos++]; + dataLength--; + } + return this; + }; + SHA2562.prototype.finish = function(out) { + if (!this._finished) { + var bytesHashed = this._bytesHashed; + var left = this._bufferLength; + var bitLenHi = bytesHashed / 536870912 | 0; + var bitLenLo = bytesHashed << 3; + var padLength = bytesHashed % 64 < 56 ? 64 : 128; + this._buffer[left] = 128; + for (var i2 = left + 1; i2 < padLength - 8; i2++) { + this._buffer[i2] = 0; + } + binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); + binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); + hashBlocks(this._temp, this._state, this._buffer, 0, padLength); + this._finished = true; + } + for (var i2 = 0; i2 < this.digestLength / 4; i2++) { + binary_1.writeUint32BE(this._state[i2], out, i2 * 4); + } + return this; + }; + SHA2562.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + SHA2562.prototype.saveState = function() { + if (this._finished) { + throw new Error("SHA256: cannot save finished state"); + } + return { + state: new Int32Array(this._state), + buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, + bufferLength: this._bufferLength, + bytesHashed: this._bytesHashed + }; + }; + SHA2562.prototype.restoreState = function(savedState) { + this._state.set(savedState.state); + this._bufferLength = savedState.bufferLength; + if (savedState.buffer) { + this._buffer.set(savedState.buffer); + } + this._bytesHashed = savedState.bytesHashed; + this._finished = false; + return this; + }; + SHA2562.prototype.cleanSavedState = function(savedState) { + wipe_1.wipe(savedState.state); + if (savedState.buffer) { + wipe_1.wipe(savedState.buffer); + } + savedState.bufferLength = 0; + savedState.bytesHashed = 0; + }; + return SHA2562; + }() + ); + exports2.SHA256 = SHA256; + var K2 = new Int32Array([ + 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 + ]); + function hashBlocks(w4, v2, p3, pos, len) { + while (len >= 64) { + var a3 = v2[0]; + var b4 = v2[1]; + var c4 = v2[2]; + var d3 = v2[3]; + var e2 = v2[4]; + var f4 = v2[5]; + var g3 = v2[6]; + var h5 = v2[7]; + for (var i2 = 0; i2 < 16; i2++) { + var j2 = pos + i2 * 4; + w4[i2] = binary_1.readUint32BE(p3, j2); + } + for (var i2 = 16; i2 < 64; i2++) { + var u3 = w4[i2 - 2]; + var t1 = (u3 >>> 17 | u3 << 32 - 17) ^ (u3 >>> 19 | u3 << 32 - 19) ^ u3 >>> 10; + u3 = w4[i2 - 15]; + var t2 = (u3 >>> 7 | u3 << 32 - 7) ^ (u3 >>> 18 | u3 << 32 - 18) ^ u3 >>> 3; + w4[i2] = (t1 + w4[i2 - 7] | 0) + (t2 + w4[i2 - 16] | 0); + } + for (var i2 = 0; i2 < 64; i2++) { + var t1 = (((e2 >>> 6 | e2 << 32 - 6) ^ (e2 >>> 11 | e2 << 32 - 11) ^ (e2 >>> 25 | e2 << 32 - 25)) + (e2 & f4 ^ ~e2 & g3) | 0) + (h5 + (K2[i2] + w4[i2] | 0) | 0) | 0; + var t2 = ((a3 >>> 2 | a3 << 32 - 2) ^ (a3 >>> 13 | a3 << 32 - 13) ^ (a3 >>> 22 | a3 << 32 - 22)) + (a3 & b4 ^ a3 & c4 ^ b4 & c4) | 0; + h5 = g3; + g3 = f4; + f4 = e2; + e2 = d3 + t1 | 0; + d3 = c4; + c4 = b4; + b4 = a3; + a3 = t1 + t2 | 0; + } + v2[0] += a3; + v2[1] += b4; + v2[2] += c4; + v2[3] += d3; + v2[4] += e2; + v2[5] += f4; + v2[6] += g3; + v2[7] += h5; + pos += 64; + len -= 64; + } + return pos; + } + function hash(data) { + var h5 = new SHA256(); + h5.update(data); + var digest2 = h5.digest(); + h5.clean(); + return digest2; + } + exports2.hash = hash; + } +}); + +// node_modules/@stablelib/x25519/lib/x25519.js +var require_x25519 = __commonJS({ + "node_modules/@stablelib/x25519/lib/x25519.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.sharedKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.scalarMultBase = exports2.scalarMult = exports2.SHARED_KEY_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = void 0; + var random_1 = require_random(); + var wipe_1 = require_wipe(); + exports2.PUBLIC_KEY_LENGTH = 32; + exports2.SECRET_KEY_LENGTH = 32; + exports2.SHARED_KEY_LENGTH = 32; + function gf(init) { + const r = new Float64Array(16); + if (init) { + for (let i2 = 0; i2 < init.length; i2++) { + r[i2] = init[i2]; + } + } + return r; + } + var _9 = new Uint8Array(32); + _9[0] = 9; + var _121665 = gf([56129, 1]); + function car25519(o2) { + let c4 = 1; + for (let i2 = 0; i2 < 16; i2++) { + let v2 = o2[i2] + c4 + 65535; + c4 = Math.floor(v2 / 65536); + o2[i2] = v2 - c4 * 65536; + } + o2[0] += c4 - 1 + 37 * (c4 - 1); + } + function sel25519(p3, q2, b4) { + const c4 = ~(b4 - 1); + for (let i2 = 0; i2 < 16; i2++) { + const t = c4 & (p3[i2] ^ q2[i2]); + p3[i2] ^= t; + q2[i2] ^= t; + } + } + function pack25519(o2, n3) { + const m3 = gf(); + const t = gf(); + for (let i2 = 0; i2 < 16; i2++) { + t[i2] = n3[i2]; + } + car25519(t); + car25519(t); + car25519(t); + for (let j2 = 0; j2 < 2; j2++) { + m3[0] = t[0] - 65517; + for (let i2 = 1; i2 < 15; i2++) { + m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); + m3[i2 - 1] &= 65535; + } + m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); + const b4 = m3[15] >> 16 & 1; + m3[14] &= 65535; + sel25519(t, m3, 1 - b4); + } + for (let i2 = 0; i2 < 16; i2++) { + o2[2 * i2] = t[i2] & 255; + o2[2 * i2 + 1] = t[i2] >> 8; + } + } + function unpack25519(o2, n3) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); + } + o2[15] &= 32767; + } + function add(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] + b4[i2]; + } + } + function sub(o2, a3, b4) { + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = a3[i2] - b4[i2]; + } + } + function mul(o2, a3, b4) { + let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; + v2 = a3[0]; + t0 += v2 * b0; + t1 += v2 * b1; + t2 += v2 * b22; + t3 += v2 * b32; + t4 += v2 * b42; + t5 += v2 * b5; + t6 += v2 * b6; + t7 += v2 * b7; + t8 += v2 * b8; + t9 += v2 * b9; + t10 += v2 * b10; + t11 += v2 * b11; + t12 += v2 * b12; + t13 += v2 * b13; + t14 += v2 * b14; + t15 += v2 * b15; + v2 = a3[1]; + t1 += v2 * b0; + t2 += v2 * b1; + t3 += v2 * b22; + t4 += v2 * b32; + t5 += v2 * b42; + t6 += v2 * b5; + t7 += v2 * b6; + t8 += v2 * b7; + t9 += v2 * b8; + t10 += v2 * b9; + t11 += v2 * b10; + t12 += v2 * b11; + t13 += v2 * b12; + t14 += v2 * b13; + t15 += v2 * b14; + t16 += v2 * b15; + v2 = a3[2]; + t2 += v2 * b0; + t3 += v2 * b1; + t4 += v2 * b22; + t5 += v2 * b32; + t6 += v2 * b42; + t7 += v2 * b5; + t8 += v2 * b6; + t9 += v2 * b7; + t10 += v2 * b8; + t11 += v2 * b9; + t12 += v2 * b10; + t13 += v2 * b11; + t14 += v2 * b12; + t15 += v2 * b13; + t16 += v2 * b14; + t17 += v2 * b15; + v2 = a3[3]; + t3 += v2 * b0; + t4 += v2 * b1; + t5 += v2 * b22; + t6 += v2 * b32; + t7 += v2 * b42; + t8 += v2 * b5; + t9 += v2 * b6; + t10 += v2 * b7; + t11 += v2 * b8; + t12 += v2 * b9; + t13 += v2 * b10; + t14 += v2 * b11; + t15 += v2 * b12; + t16 += v2 * b13; + t17 += v2 * b14; + t18 += v2 * b15; + v2 = a3[4]; + t4 += v2 * b0; + t5 += v2 * b1; + t6 += v2 * b22; + t7 += v2 * b32; + t8 += v2 * b42; + t9 += v2 * b5; + t10 += v2 * b6; + t11 += v2 * b7; + t12 += v2 * b8; + t13 += v2 * b9; + t14 += v2 * b10; + t15 += v2 * b11; + t16 += v2 * b12; + t17 += v2 * b13; + t18 += v2 * b14; + t19 += v2 * b15; + v2 = a3[5]; + t5 += v2 * b0; + t6 += v2 * b1; + t7 += v2 * b22; + t8 += v2 * b32; + t9 += v2 * b42; + t10 += v2 * b5; + t11 += v2 * b6; + t12 += v2 * b7; + t13 += v2 * b8; + t14 += v2 * b9; + t15 += v2 * b10; + t16 += v2 * b11; + t17 += v2 * b12; + t18 += v2 * b13; + t19 += v2 * b14; + t20 += v2 * b15; + v2 = a3[6]; + t6 += v2 * b0; + t7 += v2 * b1; + t8 += v2 * b22; + t9 += v2 * b32; + t10 += v2 * b42; + t11 += v2 * b5; + t12 += v2 * b6; + t13 += v2 * b7; + t14 += v2 * b8; + t15 += v2 * b9; + t16 += v2 * b10; + t17 += v2 * b11; + t18 += v2 * b12; + t19 += v2 * b13; + t20 += v2 * b14; + t21 += v2 * b15; + v2 = a3[7]; + t7 += v2 * b0; + t8 += v2 * b1; + t9 += v2 * b22; + t10 += v2 * b32; + t11 += v2 * b42; + t12 += v2 * b5; + t13 += v2 * b6; + t14 += v2 * b7; + t15 += v2 * b8; + t16 += v2 * b9; + t17 += v2 * b10; + t18 += v2 * b11; + t19 += v2 * b12; + t20 += v2 * b13; + t21 += v2 * b14; + t22 += v2 * b15; + v2 = a3[8]; + t8 += v2 * b0; + t9 += v2 * b1; + t10 += v2 * b22; + t11 += v2 * b32; + t12 += v2 * b42; + t13 += v2 * b5; + t14 += v2 * b6; + t15 += v2 * b7; + t16 += v2 * b8; + t17 += v2 * b9; + t18 += v2 * b10; + t19 += v2 * b11; + t20 += v2 * b12; + t21 += v2 * b13; + t22 += v2 * b14; + t23 += v2 * b15; + v2 = a3[9]; + t9 += v2 * b0; + t10 += v2 * b1; + t11 += v2 * b22; + t12 += v2 * b32; + t13 += v2 * b42; + t14 += v2 * b5; + t15 += v2 * b6; + t16 += v2 * b7; + t17 += v2 * b8; + t18 += v2 * b9; + t19 += v2 * b10; + t20 += v2 * b11; + t21 += v2 * b12; + t22 += v2 * b13; + t23 += v2 * b14; + t24 += v2 * b15; + v2 = a3[10]; + t10 += v2 * b0; + t11 += v2 * b1; + t12 += v2 * b22; + t13 += v2 * b32; + t14 += v2 * b42; + t15 += v2 * b5; + t16 += v2 * b6; + t17 += v2 * b7; + t18 += v2 * b8; + t19 += v2 * b9; + t20 += v2 * b10; + t21 += v2 * b11; + t22 += v2 * b12; + t23 += v2 * b13; + t24 += v2 * b14; + t25 += v2 * b15; + v2 = a3[11]; + t11 += v2 * b0; + t12 += v2 * b1; + t13 += v2 * b22; + t14 += v2 * b32; + t15 += v2 * b42; + t16 += v2 * b5; + t17 += v2 * b6; + t18 += v2 * b7; + t19 += v2 * b8; + t20 += v2 * b9; + t21 += v2 * b10; + t22 += v2 * b11; + t23 += v2 * b12; + t24 += v2 * b13; + t25 += v2 * b14; + t26 += v2 * b15; + v2 = a3[12]; + t12 += v2 * b0; + t13 += v2 * b1; + t14 += v2 * b22; + t15 += v2 * b32; + t16 += v2 * b42; + t17 += v2 * b5; + t18 += v2 * b6; + t19 += v2 * b7; + t20 += v2 * b8; + t21 += v2 * b9; + t22 += v2 * b10; + t23 += v2 * b11; + t24 += v2 * b12; + t25 += v2 * b13; + t26 += v2 * b14; + t27 += v2 * b15; + v2 = a3[13]; + t13 += v2 * b0; + t14 += v2 * b1; + t15 += v2 * b22; + t16 += v2 * b32; + t17 += v2 * b42; + t18 += v2 * b5; + t19 += v2 * b6; + t20 += v2 * b7; + t21 += v2 * b8; + t22 += v2 * b9; + t23 += v2 * b10; + t24 += v2 * b11; + t25 += v2 * b12; + t26 += v2 * b13; + t27 += v2 * b14; + t28 += v2 * b15; + v2 = a3[14]; + t14 += v2 * b0; + t15 += v2 * b1; + t16 += v2 * b22; + t17 += v2 * b32; + t18 += v2 * b42; + t19 += v2 * b5; + t20 += v2 * b6; + t21 += v2 * b7; + t22 += v2 * b8; + t23 += v2 * b9; + t24 += v2 * b10; + t25 += v2 * b11; + t26 += v2 * b12; + t27 += v2 * b13; + t28 += v2 * b14; + t29 += v2 * b15; + v2 = a3[15]; + t15 += v2 * b0; + t16 += v2 * b1; + t17 += v2 * b22; + t18 += v2 * b32; + t19 += v2 * b42; + t20 += v2 * b5; + t21 += v2 * b6; + t22 += v2 * b7; + t23 += v2 * b8; + t24 += v2 * b9; + t25 += v2 * b10; + t26 += v2 * b11; + t27 += v2 * b12; + t28 += v2 * b13; + t29 += v2 * b14; + t30 += v2 * b15; + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + c4 = 1; + v2 = t0 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t0 = v2 - c4 * 65536; + v2 = t1 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t1 = v2 - c4 * 65536; + v2 = t2 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t2 = v2 - c4 * 65536; + v2 = t3 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t3 = v2 - c4 * 65536; + v2 = t4 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t4 = v2 - c4 * 65536; + v2 = t5 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t5 = v2 - c4 * 65536; + v2 = t6 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t6 = v2 - c4 * 65536; + v2 = t7 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t7 = v2 - c4 * 65536; + v2 = t8 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t8 = v2 - c4 * 65536; + v2 = t9 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t9 = v2 - c4 * 65536; + v2 = t10 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t10 = v2 - c4 * 65536; + v2 = t11 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t11 = v2 - c4 * 65536; + v2 = t12 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t12 = v2 - c4 * 65536; + v2 = t13 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t13 = v2 - c4 * 65536; + v2 = t14 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t14 = v2 - c4 * 65536; + v2 = t15 + c4 + 65535; + c4 = Math.floor(v2 / 65536); + t15 = v2 - c4 * 65536; + t0 += c4 - 1 + 37 * (c4 - 1); + o2[0] = t0; + o2[1] = t1; + o2[2] = t2; + o2[3] = t3; + o2[4] = t4; + o2[5] = t5; + o2[6] = t6; + o2[7] = t7; + o2[8] = t8; + o2[9] = t9; + o2[10] = t10; + o2[11] = t11; + o2[12] = t12; + o2[13] = t13; + o2[14] = t14; + o2[15] = t15; + } + function square(o2, a3) { + mul(o2, a3, a3); + } + function inv25519(o2, inp) { + const c4 = gf(); + for (let i2 = 0; i2 < 16; i2++) { + c4[i2] = inp[i2]; + } + for (let i2 = 253; i2 >= 0; i2--) { + square(c4, c4); + if (i2 !== 2 && i2 !== 4) { + mul(c4, c4, inp); + } + } + for (let i2 = 0; i2 < 16; i2++) { + o2[i2] = c4[i2]; + } + } + function scalarMult(n3, p3) { + const z3 = new Uint8Array(32); + const x3 = new Float64Array(80); + const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(); + for (let i2 = 0; i2 < 31; i2++) { + z3[i2] = n3[i2]; + } + z3[31] = n3[31] & 127 | 64; + z3[0] &= 248; + unpack25519(x3, p3); + for (let i2 = 0; i2 < 16; i2++) { + b4[i2] = x3[i2]; + } + a3[0] = d3[0] = 1; + for (let i2 = 254; i2 >= 0; --i2) { + const r = z3[i2 >>> 3] >>> (i2 & 7) & 1; + sel25519(a3, b4, r); + sel25519(c4, d3, r); + add(e2, a3, c4); + sub(a3, a3, c4); + add(c4, b4, d3); + sub(b4, b4, d3); + square(d3, e2); + square(f4, a3); + mul(a3, c4, a3); + mul(c4, b4, e2); + add(e2, a3, c4); + sub(a3, a3, c4); + square(b4, a3); + sub(c4, d3, f4); + mul(a3, c4, _121665); + add(a3, a3, d3); + mul(c4, c4, a3); + mul(a3, d3, f4); + mul(d3, b4, x3); + square(b4, e2); + sel25519(a3, b4, r); + sel25519(c4, d3, r); + } + for (let i2 = 0; i2 < 16; i2++) { + x3[i2 + 16] = a3[i2]; + x3[i2 + 32] = c4[i2]; + x3[i2 + 48] = b4[i2]; + x3[i2 + 64] = d3[i2]; + } + const x32 = x3.subarray(32); + const x16 = x3.subarray(16); + inv25519(x32, x32); + mul(x16, x16, x32); + const q2 = new Uint8Array(32); + pack25519(q2, x16); + return q2; + } + exports2.scalarMult = scalarMult; + function scalarMultBase(n3) { + return scalarMult(n3, _9); + } + exports2.scalarMultBase = scalarMultBase; + function generateKeyPairFromSeed2(seed) { + if (seed.length !== exports2.SECRET_KEY_LENGTH) { + throw new Error(`x25519: seed must be ${exports2.SECRET_KEY_LENGTH} bytes`); + } + const secretKey = new Uint8Array(seed); + const publicKey = scalarMultBase(secretKey); + return { + publicKey, + secretKey + }; + } + exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; + function generateKeyPair2(prng) { + const seed = (0, random_1.randomBytes)(32, prng); + const result = generateKeyPairFromSeed2(seed); + (0, wipe_1.wipe)(seed); + return result; + } + exports2.generateKeyPair = generateKeyPair2; + function sharedKey(mySecretKey, theirPublicKey, rejectZero = false) { + if (mySecretKey.length !== exports2.PUBLIC_KEY_LENGTH) { + throw new Error("X25519: incorrect secret key length"); + } + if (theirPublicKey.length !== exports2.PUBLIC_KEY_LENGTH) { + throw new Error("X25519: incorrect public key length"); + } + const result = scalarMult(mySecretKey, theirPublicKey); + if (rejectZero) { + let zeros = 0; + for (let i2 = 0; i2 < result.length; i2++) { + zeros |= result[i2]; + } + if (zeros === 0) { + throw new Error("X25519: invalid shared key"); + } + } + return result; + } + exports2.sharedKey = sharedKey; + } +}); + +// node_modules/uint8arrays/esm/src/compare.js +function compare(a3, b4) { + for (let i2 = 0; i2 < a3.byteLength; i2++) { + if (a3[i2] < b4[i2]) { + return -1; + } + if (a3[i2] > b4[i2]) { + return 1; + } + } + if (a3.byteLength > b4.byteLength) { + return 1; + } + if (a3.byteLength < b4.byteLength) { + return -1; + } + return 0; } +var init_compare = __esm({ + "node_modules/uint8arrays/esm/src/compare.js"() { + init_shim(); + } +}); -Is replaced with: +// node_modules/uint8arrays/esm/src/equals.js +function equals3(a3, b4) { + if (a3 === b4) { + return true; + } + if (a3.byteLength !== b4.byteLength) { + return false; + } + for (let i2 = 0; i2 < a3.byteLength; i2++) { + if (a3[i2] !== b4[i2]) { + return false; + } + } + return true; +} +var init_equals = __esm({ + "node_modules/uint8arrays/esm/src/equals.js"() { + init_shim(); + } +}); -const cid = CID.asCID(value) -if (cid) { - // Make sure to use cid instead of value - doSomethingWithCID(cid) +// node_modules/uint8arrays/esm/src/xor.js +function xor(a3, b4) { + if (a3.length !== b4.length) { + throw new Error("Inputs should have the same length"); + } + const result = allocUnsafe(a3.length); + for (let i2 = 0; i2 < a3.length; i2++) { + result[i2] = a3[i2] ^ b4[i2]; + } + return asUint8Array(result); } -`});var NP=he(()=>{l();xP();Sp();$i();vA();ml()});var IA,ppe,OP=he(()=>{l();nP();iP();sP();oP();aP();fA();uP();pA();cP();fP();vP();IP();_P();SP();NP();IA={...sA,...oA,...aA,...uA,...cA,...lA,...dA,...hA,...gA,...yA},ppe={...AA,...bA}});function PP(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var DP,_A,sW,Np,SA=he(()=>{l();OP();bp();DP=PP("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),_A=PP("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=Qa(t.length);for(let r=0;r{l();SA()});function On(t,e="utf8"){let r=Np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Wi(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var CA=he(()=>{l();SA();hl()});function El(t){return ji(si(On(t,Ga),gp))}function vl(t){return si(On(Qi(t),gp),Ga)}function xA(t){let e=On(vp,ja),r=Ep+si(Ip([e,t]),ja);return[mp,wp,r].join(yp)}function NA(t){let[e,r,n]=t.split(yp);if(e!==mp||r!==wp)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==Ep)throw new Error("Issuer must be a key in mulicodec format");let s=On(n.slice(1),ja);if(si(s.slice(0,2),ja)!==vp)throw new Error('Issuer must be a public key with type "Ed25519"');let a=s.slice(2);if(a.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return a}function RP(t){return si(t,Ga)}function BP(t){return On(t,Ga)}function OA(t){return On([vl(t.header),vl(t.payload)].join(ro),dl)}function oW(t){let e=si(t,dl).split(ro),r=El(e[0]),n=El(e[1]);return{header:r,payload:n}}function DA(t){return[vl(t.header),vl(t.payload),RP(t.signature)].join(ro)}function PA(t){let e=t.split(ro),r=El(e[0]),n=El(e[1]),i=BP(e[2]),s=On(e.slice(0,2).join(ro),dl);return{header:r,payload:n,signature:i,data:s}}var RA=he(()=>{l();eA();TA();CA();nl();Ap()});function aW(t=(0,LP.randomBytes)(32)){return Ja.generateKeyPairFromSeed(t)}async function uW(t,e,r,n,i=(0,FP.fromMiliseconds)(Date.now())){let s={alg:hp,typ:pp},o=xA(n.publicKey),a=i+r,u={iss:o,sub:t,aud:e,iat:i,exp:a},c=OA({header:s,payload:u}),f=Ja.sign(n.secretKey,c);return DA({header:s,payload:u,signature:f})}async function cW(t){let{header:e,payload:r,data:n,signature:i}=PA(t);if(e.alg!==hp||e.typ!==pp)throw new Error("JWT must use EdDSA algorithm");let s=NA(r.iss);return Ja.verify(s,n,i)}var Ja,LP,FP,MP=he(()=>{l();Ja=be(WD()),LP=be(cl()),FP=be(Xs());Ap();RA()});var UP=he(()=>{l()});var qP={};ft(qP,{DATA_ENCODING:()=>dl,DID_DELIMITER:()=>yp,DID_METHOD:()=>wp,DID_PREFIX:()=>mp,JSON_ENCODING:()=>gp,JWT_DELIMITER:()=>ro,JWT_ENCODING:()=>Ga,JWT_IRIDIUM_ALG:()=>hp,JWT_IRIDIUM_TYP:()=>pp,KEY_PAIR_SEED_LENGTH:()=>KD,MULTICODEC_ED25519_BASE:()=>Ep,MULTICODEC_ED25519_ENCODING:()=>ja,MULTICODEC_ED25519_HEADER:()=>vp,MULTICODEC_ED25519_LENGTH:()=>$D,decodeData:()=>oW,decodeIss:()=>NA,decodeJSON:()=>El,decodeJWT:()=>PA,decodeSig:()=>BP,encodeData:()=>OA,encodeIss:()=>xA,encodeJSON:()=>vl,encodeJWT:()=>DA,encodeSig:()=>RP,generateKeyPair:()=>aW,signJWT:()=>uW,verifyJWT:()=>cW});var VP=he(()=>{l();MP();Ap();UP();RA()});var kP=v(Op=>{"use strict";l();Object.defineProperty(Op,"__esModule",{value:!0});var tr=qa(),BA=Hr(),lW=20;function fW(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,a=r[3]<<24|r[2]<<16|r[1]<<8|r[0],u=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],g=r[23]<<24|r[22]<<16|r[21]<<8|r[20],m=r[27]<<24|r[26]<<16|r[25]<<8|r[24],y=r[31]<<24|r[30]<<16|r[29]<<8|r[28],A=e[3]<<24|e[2]<<16|e[1]<<8|e[0],O=e[7]<<24|e[6]<<16|e[5]<<8|e[4],R=e[11]<<24|e[10]<<16|e[9]<<8|e[8],q=e[15]<<24|e[14]<<16|e[13]<<8|e[12],M=n,b=i,S=s,N=o,_=a,T=u,B=c,X=f,z=d,k=g,Q=m,K=y,ye=A,ce=O,ie=R,J=q,oe=0;oe>>16|ye<<16,z=z+ye|0,_^=z,_=_>>>20|_<<12,b=b+T|0,ce^=b,ce=ce>>>16|ce<<16,k=k+ce|0,T^=k,T=T>>>20|T<<12,S=S+B|0,ie^=S,ie=ie>>>16|ie<<16,Q=Q+ie|0,B^=Q,B=B>>>20|B<<12,N=N+X|0,J^=N,J=J>>>16|J<<16,K=K+J|0,X^=K,X=X>>>20|X<<12,S=S+B|0,ie^=S,ie=ie>>>24|ie<<8,Q=Q+ie|0,B^=Q,B=B>>>25|B<<7,N=N+X|0,J^=N,J=J>>>24|J<<8,K=K+J|0,X^=K,X=X>>>25|X<<7,b=b+T|0,ce^=b,ce=ce>>>24|ce<<8,k=k+ce|0,T^=k,T=T>>>25|T<<7,M=M+_|0,ye^=M,ye=ye>>>24|ye<<8,z=z+ye|0,_^=z,_=_>>>25|_<<7,M=M+T|0,J^=M,J=J>>>16|J<<16,Q=Q+J|0,T^=Q,T=T>>>20|T<<12,b=b+B|0,ye^=b,ye=ye>>>16|ye<<16,K=K+ye|0,B^=K,B=B>>>20|B<<12,S=S+X|0,ce^=S,ce=ce>>>16|ce<<16,z=z+ce|0,X^=z,X=X>>>20|X<<12,N=N+_|0,ie^=N,ie=ie>>>16|ie<<16,k=k+ie|0,_^=k,_=_>>>20|_<<12,S=S+X|0,ce^=S,ce=ce>>>24|ce<<8,z=z+ce|0,X^=z,X=X>>>25|X<<7,N=N+_|0,ie^=N,ie=ie>>>24|ie<<8,k=k+ie|0,_^=k,_=_>>>25|_<<7,b=b+B|0,ye^=b,ye=ye>>>24|ye<<8,K=K+ye|0,B^=K,B=B>>>25|B<<7,M=M+T|0,J^=M,J=J>>>24|J<<8,Q=Q+J|0,T^=Q,T=T>>>25|T<<7;tr.writeUint32LE(M+n|0,t,0),tr.writeUint32LE(b+i|0,t,4),tr.writeUint32LE(S+s|0,t,8),tr.writeUint32LE(N+o|0,t,12),tr.writeUint32LE(_+a|0,t,16),tr.writeUint32LE(T+u|0,t,20),tr.writeUint32LE(B+c|0,t,24),tr.writeUint32LE(X+f|0,t,28),tr.writeUint32LE(z+d|0,t,32),tr.writeUint32LE(k+g|0,t,36),tr.writeUint32LE(Q+m|0,t,40),tr.writeUint32LE(K+y|0,t,44),tr.writeUint32LE(ye+A|0,t,48),tr.writeUint32LE(ce+O|0,t,52),tr.writeUint32LE(ie+R|0,t,56),tr.writeUint32LE(J+q|0,t,60)}function HP(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Dp=v(Xa=>{"use strict";l();Object.defineProperty(Xa,"__esModule",{value:!0});function pW(t,e,r){return~(t-1)&e|t-1&r}Xa.select=pW;function gW(t,e){return(t|0)-(e|0)-1>>>31&1}Xa.lessOrEqual=gW;function GP(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xa.compare=GP;function yW(t,e){return t.length===0||e.length===0?!1:GP(t,e)!==0}Xa.equal=yW});var QP=v(oi=>{"use strict";l();Object.defineProperty(oi,"__esModule",{value:!0});var mW=Dp(),Pp=Hr();oi.DIGEST_LENGTH=16;var jP=function(){function t(e){this.digestLength=oi.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var a=e[10]|e[11]<<8;this._r[6]=(o>>>14|a<<2)&8191;var u=e[12]|e[13]<<8;this._r[7]=(a>>>11|u<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(u>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],a=this._h[2],u=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],g=this._h[7],m=this._h[8],y=this._h[9],A=this._r[0],O=this._r[1],R=this._r[2],q=this._r[3],M=this._r[4],b=this._r[5],S=this._r[6],N=this._r[7],_=this._r[8],T=this._r[9];n>=16;){var B=e[r+0]|e[r+1]<<8;s+=B&8191;var X=e[r+2]|e[r+3]<<8;o+=(B>>>13|X<<3)&8191;var z=e[r+4]|e[r+5]<<8;a+=(X>>>10|z<<6)&8191;var k=e[r+6]|e[r+7]<<8;u+=(z>>>7|k<<9)&8191;var Q=e[r+8]|e[r+9]<<8;c+=(k>>>4|Q<<12)&8191,f+=Q>>>1&8191;var K=e[r+10]|e[r+11]<<8;d+=(Q>>>14|K<<2)&8191;var ye=e[r+12]|e[r+13]<<8;g+=(K>>>11|ye<<5)&8191;var ce=e[r+14]|e[r+15]<<8;m+=(ye>>>8|ce<<8)&8191,y+=ce>>>5|i;var ie=0,J=ie;J+=s*A,J+=o*(5*T),J+=a*(5*_),J+=u*(5*N),J+=c*(5*S),ie=J>>>13,J&=8191,J+=f*(5*b),J+=d*(5*M),J+=g*(5*q),J+=m*(5*R),J+=y*(5*O),ie+=J>>>13,J&=8191;var oe=ie;oe+=s*O,oe+=o*A,oe+=a*(5*T),oe+=u*(5*_),oe+=c*(5*N),ie=oe>>>13,oe&=8191,oe+=f*(5*S),oe+=d*(5*b),oe+=g*(5*M),oe+=m*(5*q),oe+=y*(5*R),ie+=oe>>>13,oe&=8191;var re=ie;re+=s*R,re+=o*O,re+=a*A,re+=u*(5*T),re+=c*(5*_),ie=re>>>13,re&=8191,re+=f*(5*N),re+=d*(5*S),re+=g*(5*b),re+=m*(5*M),re+=y*(5*q),ie+=re>>>13,re&=8191;var se=ie;se+=s*q,se+=o*R,se+=a*O,se+=u*A,se+=c*(5*T),ie=se>>>13,se&=8191,se+=f*(5*_),se+=d*(5*N),se+=g*(5*S),se+=m*(5*b),se+=y*(5*M),ie+=se>>>13,se&=8191;var U=ie;U+=s*M,U+=o*q,U+=a*R,U+=u*O,U+=c*A,ie=U>>>13,U&=8191,U+=f*(5*T),U+=d*(5*_),U+=g*(5*N),U+=m*(5*S),U+=y*(5*b),ie+=U>>>13,U&=8191;var fe=ie;fe+=s*b,fe+=o*M,fe+=a*q,fe+=u*R,fe+=c*O,ie=fe>>>13,fe&=8191,fe+=f*A,fe+=d*(5*T),fe+=g*(5*_),fe+=m*(5*N),fe+=y*(5*S),ie+=fe>>>13,fe&=8191;var ue=ie;ue+=s*S,ue+=o*b,ue+=a*M,ue+=u*q,ue+=c*R,ie=ue>>>13,ue&=8191,ue+=f*O,ue+=d*A,ue+=g*(5*T),ue+=m*(5*_),ue+=y*(5*N),ie+=ue>>>13,ue&=8191;var de=ie;de+=s*N,de+=o*S,de+=a*b,de+=u*M,de+=c*q,ie=de>>>13,de&=8191,de+=f*R,de+=d*O,de+=g*A,de+=m*(5*T),de+=y*(5*_),ie+=de>>>13,de&=8191;var ae=ie;ae+=s*_,ae+=o*N,ae+=a*S,ae+=u*b,ae+=c*M,ie=ae>>>13,ae&=8191,ae+=f*q,ae+=d*R,ae+=g*O,ae+=m*A,ae+=y*(5*T),ie+=ae>>>13,ae&=8191;var le=ie;le+=s*T,le+=o*_,le+=a*N,le+=u*S,le+=c*b,ie=le>>>13,le&=8191,le+=f*M,le+=d*q,le+=g*R,le+=m*O,le+=y*A,ie+=le>>>13,le&=8191,ie=(ie<<2)+ie|0,ie=ie+J|0,J=ie&8191,ie=ie>>>13,oe+=ie,s=J,o=oe,a=re,u=se,c=U,f=fe,d=ue,g=de,m=ae,y=le,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=a,this._h[3]=u,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=g,this._h[8]=m,this._h[9]=y},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,a;if(this._leftover){for(a=this._leftover,this._buffer[a++]=1;a<16;a++)this._buffer[a]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,a=2;a<10;a++)this._h[a]+=i,i=this._h[a]>>>13,this._h[a]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,a=1;a<10;a++)n[a]=this._h[a]+i,i=n[a]>>>13,n[a]&=8191;for(n[9]-=8192,s=(i^1)-1,a=0;a<10;a++)n[a]&=s;for(s=~s,a=0;a<10;a++)this._h[a]=this._h[a]&s|n[a];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,a=1;a<8;a++)o=(this._h[a]+this._pad[a]|0)+(o>>>16)|0,this._h[a]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";l();Object.defineProperty(ai,"__esModule",{value:!0});var Rp=kP(),vW=QP(),Al=Hr(),zP=qa(),AW=Dp();ai.KEY_LENGTH=32;ai.NONCE_LENGTH=12;ai.TAG_LENGTH=16;var WP=new Uint8Array(16),bW=function(){function t(e){if(this.nonceLength=ai.NONCE_LENGTH,this.tagLength=ai.TAG_LENGTH,e.length!==ai.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Rp.stream(this._key,s,o,4);var a=r.length+this.tagLength,u;if(i){if(i.length!==a)throw new Error("ChaCha20Poly1305: incorrect destination length");u=i}else u=new Uint8Array(a);return Rp.streamXOR(this._key,s,r,u,4),this._authenticate(u.subarray(u.length-this.tagLength,u.length),o,u.subarray(0,u.length-this.tagLength),n),Al.wipe(s),u},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(WP.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(WP.subarray(n.length%16));var o=new Uint8Array(8);i&&zP.writeUint64LE(i.length,o),s.update(o),zP.writeUint64LE(n.length,o),s.update(o);for(var a=s.digest(),u=0;u{"use strict";l();Object.defineProperty(LA,"__esModule",{value:!0});function IW(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}LA.isSerializableHash=IW});var JP=v(bl=>{"use strict";l();Object.defineProperty(bl,"__esModule",{value:!0});var Dn=KP(),_W=Dp(),SW=Hr(),YP=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";l();Object.defineProperty(FA,"__esModule",{value:!0});var XP=JP(),ZP=Hr(),CW=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=XP.hmac(this._hash,n,r);this._hmac=new XP.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";l();Object.defineProperty(Yi,"__esModule",{value:!0});var Lp=qa(),Bp=Hr();Yi.DIGEST_LENGTH=32;Yi.BLOCK_SIZE=64;var tR=function(){function t(){this.digestLength=Yi.DIGEST_LENGTH,this.blockSize=Yi.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Bp.wipe(this._buffer),Bp.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(MA(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=MA(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var a=n+1;a0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Bp.wipe(e.state),e.buffer&&Bp.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Yi.SHA256=tR;var xW=new Int32Array([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]);function MA(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],a=e[2],u=e[3],c=e[4],f=e[5],d=e[6],g=e[7],m=0;m<16;m++){var y=n+m*4;t[m]=Lp.readUint32BE(r,y)}for(var m=16;m<64;m++){var A=t[m-2],O=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=t[m-15];var R=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;t[m]=(O+t[m-7]|0)+(R+t[m-16]|0)}for(var m=0;m<64;m++){var O=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(g+(xW[m]+t[m]|0)|0)|0,R=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&a^o&a)|0;g=d,d=f,f=c,c=u+O|0,u=a,a=o,o=s,s=O+R|0}e[0]+=s,e[1]+=o,e[2]+=a,e[3]+=u,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=g,n+=64,i-=64}return n}function NW(t){var e=new tR;e.update(t);var r=e.digest();return e.clean(),r}Yi.hash=NW});var oR=v(mt=>{"use strict";l();Object.defineProperty(mt,"__esModule",{value:!0});mt.sharedKey=mt.generateKeyPair=mt.generateKeyPairFromSeed=mt.scalarMultBase=mt.scalarMult=mt.SHARED_KEY_LENGTH=mt.SECRET_KEY_LENGTH=mt.PUBLIC_KEY_LENGTH=void 0;var OW=cl(),DW=Hr();mt.PUBLIC_KEY_LENGTH=32;mt.SECRET_KEY_LENGTH=32;mt.SHARED_KEY_LENGTH=32;function Pn(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Il(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function BW(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Fp(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Mp(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function ui(t,e,r){let n,i,s=0,o=0,a=0,u=0,c=0,f=0,d=0,g=0,m=0,y=0,A=0,O=0,R=0,q=0,M=0,b=0,S=0,N=0,_=0,T=0,B=0,X=0,z=0,k=0,Q=0,K=0,ye=0,ce=0,ie=0,J=0,oe=0,re=r[0],se=r[1],U=r[2],fe=r[3],ue=r[4],de=r[5],ae=r[6],le=r[7],w=r[8],E=r[9],I=r[10],P=r[11],C=r[12],D=r[13],L=r[14],x=r[15];n=e[0],s+=n*re,o+=n*se,a+=n*U,u+=n*fe,c+=n*ue,f+=n*de,d+=n*ae,g+=n*le,m+=n*w,y+=n*E,A+=n*I,O+=n*P,R+=n*C,q+=n*D,M+=n*L,b+=n*x,n=e[1],o+=n*re,a+=n*se,u+=n*U,c+=n*fe,f+=n*ue,d+=n*de,g+=n*ae,m+=n*le,y+=n*w,A+=n*E,O+=n*I,R+=n*P,q+=n*C,M+=n*D,b+=n*L,S+=n*x,n=e[2],a+=n*re,u+=n*se,c+=n*U,f+=n*fe,d+=n*ue,g+=n*de,m+=n*ae,y+=n*le,A+=n*w,O+=n*E,R+=n*I,q+=n*P,M+=n*C,b+=n*D,S+=n*L,N+=n*x,n=e[3],u+=n*re,c+=n*se,f+=n*U,d+=n*fe,g+=n*ue,m+=n*de,y+=n*ae,A+=n*le,O+=n*w,R+=n*E,q+=n*I,M+=n*P,b+=n*C,S+=n*D,N+=n*L,_+=n*x,n=e[4],c+=n*re,f+=n*se,d+=n*U,g+=n*fe,m+=n*ue,y+=n*de,A+=n*ae,O+=n*le,R+=n*w,q+=n*E,M+=n*I,b+=n*P,S+=n*C,N+=n*D,_+=n*L,T+=n*x,n=e[5],f+=n*re,d+=n*se,g+=n*U,m+=n*fe,y+=n*ue,A+=n*de,O+=n*ae,R+=n*le,q+=n*w,M+=n*E,b+=n*I,S+=n*P,N+=n*C,_+=n*D,T+=n*L,B+=n*x,n=e[6],d+=n*re,g+=n*se,m+=n*U,y+=n*fe,A+=n*ue,O+=n*de,R+=n*ae,q+=n*le,M+=n*w,b+=n*E,S+=n*I,N+=n*P,_+=n*C,T+=n*D,B+=n*L,X+=n*x,n=e[7],g+=n*re,m+=n*se,y+=n*U,A+=n*fe,O+=n*ue,R+=n*de,q+=n*ae,M+=n*le,b+=n*w,S+=n*E,N+=n*I,_+=n*P,T+=n*C,B+=n*D,X+=n*L,z+=n*x,n=e[8],m+=n*re,y+=n*se,A+=n*U,O+=n*fe,R+=n*ue,q+=n*de,M+=n*ae,b+=n*le,S+=n*w,N+=n*E,_+=n*I,T+=n*P,B+=n*C,X+=n*D,z+=n*L,k+=n*x,n=e[9],y+=n*re,A+=n*se,O+=n*U,R+=n*fe,q+=n*ue,M+=n*de,b+=n*ae,S+=n*le,N+=n*w,_+=n*E,T+=n*I,B+=n*P,X+=n*C,z+=n*D,k+=n*L,Q+=n*x,n=e[10],A+=n*re,O+=n*se,R+=n*U,q+=n*fe,M+=n*ue,b+=n*de,S+=n*ae,N+=n*le,_+=n*w,T+=n*E,B+=n*I,X+=n*P,z+=n*C,k+=n*D,Q+=n*L,K+=n*x,n=e[11],O+=n*re,R+=n*se,q+=n*U,M+=n*fe,b+=n*ue,S+=n*de,N+=n*ae,_+=n*le,T+=n*w,B+=n*E,X+=n*I,z+=n*P,k+=n*C,Q+=n*D,K+=n*L,ye+=n*x,n=e[12],R+=n*re,q+=n*se,M+=n*U,b+=n*fe,S+=n*ue,N+=n*de,_+=n*ae,T+=n*le,B+=n*w,X+=n*E,z+=n*I,k+=n*P,Q+=n*C,K+=n*D,ye+=n*L,ce+=n*x,n=e[13],q+=n*re,M+=n*se,b+=n*U,S+=n*fe,N+=n*ue,_+=n*de,T+=n*ae,B+=n*le,X+=n*w,z+=n*E,k+=n*I,Q+=n*P,K+=n*C,ye+=n*D,ce+=n*L,ie+=n*x,n=e[14],M+=n*re,b+=n*se,S+=n*U,N+=n*fe,_+=n*ue,T+=n*de,B+=n*ae,X+=n*le,z+=n*w,k+=n*E,Q+=n*I,K+=n*P,ye+=n*C,ce+=n*D,ie+=n*L,J+=n*x,n=e[15],b+=n*re,S+=n*se,N+=n*U,_+=n*fe,T+=n*ue,B+=n*de,X+=n*ae,z+=n*le,k+=n*w,Q+=n*E,K+=n*I,ye+=n*P,ce+=n*C,ie+=n*D,J+=n*L,oe+=n*x,s+=38*S,o+=38*N,a+=38*_,u+=38*T,c+=38*B,f+=38*X,d+=38*z,g+=38*k,m+=38*Q,y+=38*K,A+=38*ye,O+=38*ce,R+=38*ie,q+=38*J,M+=38*oe,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=g+i+65535,i=Math.floor(n/65536),g=n-i*65536,n=m+i+65535,i=Math.floor(n/65536),m=n-i*65536,n=y+i+65535,i=Math.floor(n/65536),y=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=O+i+65535,i=Math.floor(n/65536),O=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=q+i+65535,i=Math.floor(n/65536),q=n-i*65536,n=M+i+65535,i=Math.floor(n/65536),M=n-i*65536,n=b+i+65535,i=Math.floor(n/65536),b=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=a,t[3]=u,t[4]=c,t[5]=f,t[6]=d,t[7]=g,t[8]=m,t[9]=y,t[10]=A,t[11]=O,t[12]=R,t[13]=q,t[14]=M,t[15]=b}function _l(t,e){ui(t,e,e)}function LW(t,e){let r=Pn();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)_l(r,r),n!==2&&n!==4&&ui(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function qA(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=Pn(),s=Pn(),o=Pn(),a=Pn(),u=Pn(),c=Pn();for(let m=0;m<31;m++)r[m]=t[m];r[31]=t[31]&127|64,r[0]&=248,BW(n,e);for(let m=0;m<16;m++)s[m]=n[m];i[0]=a[0]=1;for(let m=254;m>=0;--m){let y=r[m>>>3]>>>(m&7)&1;Il(i,s,y),Il(o,a,y),Fp(u,i,o),Mp(i,i,o),Fp(o,s,a),Mp(s,s,a),_l(a,u),_l(c,i),ui(i,o,i),ui(o,s,u),Fp(u,i,o),Mp(i,i,o),_l(s,i),Mp(o,a,c),ui(i,o,PW),Fp(i,i,a),ui(o,o,i),ui(i,a,c),ui(a,s,n),_l(s,u),Il(i,s,y),Il(o,a,y)}for(let m=0;m<16;m++)n[m+16]=i[m],n[m+32]=o[m],n[m+48]=s[m],n[m+64]=a[m];let f=n.subarray(32),d=n.subarray(16);LW(f,f),ui(d,d,f);let g=new Uint8Array(32);return RW(g,d),g}mt.scalarMult=qA;function iR(t){return qA(t,nR)}mt.scalarMultBase=iR;function sR(t){if(t.length!==mt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${mt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:iR(e),secretKey:e}}mt.generateKeyPairFromSeed=sR;function FW(t){let e=(0,OW.randomBytes)(32,t),r=sR(e);return(0,DW.wipe)(e),r}mt.generateKeyPair=FW;function MW(t,e,r=!1){if(t.length!==mt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==mt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=qA(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{l()});function cR(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{l()});function fR(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=Qa(t.length);for(let n=0;n{l();bp();hl()});var VA={};ft(VA,{compare:()=>aR,concat:()=>Ip,equals:()=>cR,fromString:()=>On,toString:()=>si,xor:()=>fR});var HA=he(()=>{l();uR();eA();lR();CA();TA();dR()});var _R=v(ut=>{"use strict";l();var hR=ut&&ut.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new vR:typeof navigator<"u"?kA(navigator.userAgent):IR()}ut.detect=HW;function AR(t){return t!==""&&VW.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function kW(t){var e=AR(t);return e?e[0]:null}ut.browserName=kW;function kA(t){var e=AR(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new ER;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";l();Object.defineProperty(et,"__esModule",{value:!0});et.getLocalStorage=et.getLocalStorageOrThrow=et.getCrypto=et.getCryptoOrThrow=et.getLocation=et.getLocationOrThrow=et.getNavigator=et.getNavigatorOrThrow=et.getDocument=et.getDocumentOrThrow=et.getFromWindowOrThrow=et.getFromWindow=void 0;function io(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}et.getFromWindow=io;function Za(t){let e=io(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}et.getFromWindowOrThrow=Za;function jW(){return Za("document")}et.getDocumentOrThrow=jW;function QW(){return io("document")}et.getDocument=QW;function zW(){return Za("navigator")}et.getNavigatorOrThrow=zW;function WW(){return io("navigator")}et.getNavigator=WW;function $W(){return Za("location")}et.getLocationOrThrow=$W;function KW(){return io("location")}et.getLocation=KW;function YW(){return Za("crypto")}et.getCryptoOrThrow=YW;function JW(){return io("crypto")}et.getCrypto=JW;function XW(){return Za("localStorage")}et.getLocalStorageOrThrow=XW;function ZW(){return io("localStorage")}et.getLocalStorage=ZW});var TR=v(Up=>{"use strict";l();Object.defineProperty(Up,"__esModule",{value:!0});Up.getWindowMetadata=void 0;var SR=GA();function e$(){let t,e;try{t=SR.getDocumentOrThrow(),e=SR.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),g=[];for(let m=0;m-1){let O=y.getAttribute("href");if(O)if(O.toLowerCase().indexOf("https:")===-1&&O.toLowerCase().indexOf("http:")===-1&&O.indexOf("//")!==0){let R=e.protocol+"//"+e.host;if(O.indexOf("/")===0)R+=O;else{let q=e.pathname.split("/");q.pop();let M=q.join("/");R+=M+"/"+O}g.push(R)}else if(O.indexOf("//")===0){let R=e.protocol+O;g.push(R)}else g.push(O)}}return g}function n(...d){let g=t.getElementsByTagName("meta");for(let m=0;my.getAttribute(O)).filter(O=>O?d.includes(O):!1);if(A.length&&A){let O=y.getAttribute("content");if(O)return O}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),a=s(),u=e.origin,c=r();return{description:a,url:u,icons:c,name:o}}Up.getWindowMetadata=e$});var xR=v((Oge,CR)=>{"use strict";l();CR.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var RR=v((Pge,PR)=>{"use strict";l();var DR="%[a-f0-9]{2}",NR=new RegExp("("+DR+")|([^%]+?)","gi"),OR=new RegExp("("+DR+")+","gi");function jA(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],jA(r),jA(n))}function t$(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(NR)||[],r=1;r{"use strict";l();BR.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var MR=v((Fge,FR)=>{"use strict";l();FR.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";l();var n$=xR(),i$=RR(),qR=LR(),s$=MR(),o$=t=>t==null,QA=Symbol("encodeFragmentIdentifier");function a$(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[It(e,t),"[",i,"]"].join("")]:[...r,[It(e,t),"[",It(i,t),"]=",It(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[It(e,t),"[]"].join("")]:[...r,[It(e,t),"[]=",It(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[It(e,t),":list="].join("")]:[...r,[It(e,t),":list=",It(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[It(r,t),e,It(i,t)].join("")]:[[n,It(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,It(e,t)]:[...r,[It(e,t),"=",It(n,t)].join("")]}}function u$(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&ci(n,t).includes(t.arrayFormatSeparator);n=o?ci(n,t):n;let a=s||o?n.split(t.arrayFormatSeparator).map(u=>ci(u,t)):n===null?n:ci(n,t);i[r]=a};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&ci(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(a=>ci(a,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function VR(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function It(t,e){return e.encode?e.strict?n$(t):encodeURIComponent(t):t}function ci(t,e){return e.decode?i$(t):t}function HR(t){return Array.isArray(t)?t.sort():typeof t=="object"?HR(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function kR(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function c$(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function GR(t){t=kR(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function UR(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function jR(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),VR(e.arrayFormatSeparator);let r=u$(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=qR(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:ci(o,e),r(ci(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=UR(s[o],e);else n[i]=UR(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=HR(o):i[s]=o,i},Object.create(null))}wr.extract=GR;wr.parse=jR;wr.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),VR(e.arrayFormatSeparator);let r=o=>e.skipNull&&o$(t[o])||e.skipEmptyString&&t[o]==="",n=a$(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let a=t[o];return a===void 0?"":a===null?It(o,e):Array.isArray(a)?a.length===0&&e.arrayFormat==="bracket-separator"?It(o,e)+"[]":a.reduce(n(o),[]).join("&"):It(o,e)+"="+It(a,e)}).filter(o=>o.length>0).join("&")};wr.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=qR(t,"#");return Object.assign({url:r.split("?")[0]||"",query:jR(GR(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:ci(n,e)}:{})};wr.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[QA]:!0},e);let r=kR(t.url).split("?")[0]||"",n=wr.extract(t.url),i=wr.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=wr.stringify(s,e);o&&(o=`?${o}`);let a=c$(t.url);return t.fragmentIdentifier&&(a=`#${e[QA]?It(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${a}`};wr.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[QA]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=wr.parseUrl(t,r);return wr.stringifyUrl({url:n,query:s$(i,e),fragmentIdentifier:s},r)};wr.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return wr.pick(t,n,r)}});var zR=he(()=>{l()});function Ji(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function l$(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function f$(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function d$(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function Sl(t,e,r){return(!r.length?f$(t,e.length):d$(t,e.length))?l$(t,e):!1}function Tl(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}var zA=he(()=>{l()});function h$(t){return qp(t.method)&&Vp(t.params)}function qp(t){return Tl(t,"subscribe")}function Vp(t){return Sl(t,["topic"],[])}function p$(t){return Hp(t.method)&&kp(t.params)}function Hp(t){return Tl(t,"publish")}function kp(t){return Sl(t,["message","topic","ttl"],["prompt","tag"])}function g$(t){return Gp(t.method)&&jp(t.params)}function Gp(t){return Tl(t,"unsubscribe")}function jp(t){return Sl(t,["id","topic"],[])}function y$(t){return Qp(t.method)&&zp(t.params)}function Qp(t){return Tl(t,"subscription")}function zp(t){return Sl(t,["id","data"],[])}var WA=he(()=>{l();zA()});function m$(t){if(!qp(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!Vp(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Ji(e,"topic"),e}function w$(t){if(!Hp(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!kp(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Ji(e,"topic"),Ji(e,"message"),Ji(e,"ttl","number"),e}function E$(t){if(!Gp(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!jp(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Ji(e,"id"),e}function v$(t){if(!Qp(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!zp(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Ji(e,"id"),Ji(e,"data"),e}var WR=he(()=>{l();zA();WA()});var A$,$R=he(()=>{l();A$={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe"}}});var KR={};ft(KR,{RELAY_JSONRPC:()=>A$,isPublishMethod:()=>Hp,isPublishParams:()=>kp,isPublishRequest:()=>p$,isSubscribeMethod:()=>qp,isSubscribeParams:()=>Vp,isSubscribeRequest:()=>h$,isSubscriptionMethod:()=>Qp,isSubscriptionParams:()=>zp,isSubscriptionRequest:()=>y$,isUnsubscribeMethod:()=>Gp,isUnsubscribeParams:()=>jp,isUnsubscribeRequest:()=>g$,parsePublishRequest:()=>w$,parseSubscribeRequest:()=>m$,parseSubscriptionRequest:()=>v$,parseUnsubscribeRequest:()=>E$});var YR=he(()=>{l();zR();WR();$R();WA()});var Dl=v(H=>{"use strict";l();Object.defineProperty(H,"__esModule",{value:!0});var o3=$P(),b$=eR(),a3=cl(),ZA=rR(),I$=oR(),ct=(HA(),ht(VA)),_$=_R(),eu=Xs(),tu=GA(),S$=TR(),T$=QR(),C$=(YR(),ht(KR));function u3(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var c3=u3(I$),Wp=u3(T$),Yp=":";function l3(t){let[e,r]=t.split(Yp);return{namespace:e,reference:r}}function f3(t){let{namespace:e,reference:r}=t;return[e,r].join(Yp)}function eb(t){let[e,r,n]=t.split(Yp);return{namespace:e,reference:r,address:n}}function d3(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(Yp)}function tb(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function h3(t){let{address:e}=eb(t);return e}function p3(t){let{namespace:e,reference:r}=eb(t);return f3({namespace:e,reference:r})}function x$(t,e){let{namespace:r,reference:n}=l3(e);return d3({namespace:r,reference:n,address:t})}function N$(t){return tb(t,h3)}function g3(t){return tb(t,p3)}function O$(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function D$(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...g3(i.accounts))}),r}function P$(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...Jp(n,i))}),r}function Jp(t,e){return t.includes(":")?[t]:e.chains||[]}var Xp=t=>t?.split(":"),y3=t=>{let e=t&&Xp(t);if(e)return e[3]},R$=t=>{let e=t&&Xp(t);if(e)return e[2]+":"+e[3]},m3=t=>{let e=t&&Xp(t);if(e)return e.pop()},B$=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=m3(e),i=t.statement,s=`URI: ${t.aud}`,o=`Version: ${t.version}`,a=`Chain ID: ${y3(e)}`,u=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources&&t.resources.length>0?`Resources: -${t.resources.map(d=>`- ${d}`).join(` -`)}`:void 0;return[r,n,"",i,"",s,o,a,u,c,f].filter(d=>d!=null).join(` -`)},rb="base10",or="base16",$p="base64pad",Zp="utf8",nb=0,ru=1,L$=0,JR=1,KA=12,ib=32;function F$(){let t=c3.generateKeyPair();return{privateKey:ct.toString(t.secretKey,or),publicKey:ct.toString(t.publicKey,or)}}function M$(){let t=a3.randomBytes(ib);return ct.toString(t,or)}function U$(t,e){let r=c3.sharedKey(ct.fromString(t,or),ct.fromString(e,or),!0),n=new b$.HKDF(ZA.SHA256,r).expand(ib);return ct.toString(n,or)}function q$(t){let e=ZA.hash(ct.fromString(t,or));return ct.toString(e,or)}function V$(t){let e=ZA.hash(ct.fromString(t,Zp));return ct.toString(e,or)}function w3(t){return ct.fromString(`${t}`,rb)}function xl(t){return Number(ct.toString(t,rb))}function H$(t){let e=w3(typeof t.type<"u"?t.type:nb);if(xl(e)===ru&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?ct.fromString(t.senderPublicKey,or):void 0,n=typeof t.iv<"u"?ct.fromString(t.iv,or):a3.randomBytes(KA),i=new o3.ChaCha20Poly1305(ct.fromString(t.symKey,or)).seal(n,ct.fromString(t.message,Zp));return E3({type:e,sealed:i,iv:n,senderPublicKey:r})}function k$(t){let e=new o3.ChaCha20Poly1305(ct.fromString(t.symKey,or)),{sealed:r,iv:n}=sb(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return ct.toString(i,Zp)}function E3(t){if(xl(t.type)===ru){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ct.toString(ct.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),$p)}return ct.toString(ct.concat([t.type,t.iv,t.sealed]),$p)}function sb(t){let e=ct.fromString(t,$p),r=e.slice(L$,JR),n=JR;if(xl(r)===ru){let a=n+ib,u=a+KA,c=e.slice(n,a),f=e.slice(a,u),d=e.slice(u);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+KA,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function G$(t,e){let r=sb(t);return v3({type:xl(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?ct.toString(r.senderPublicKey,or):void 0,receiverPublicKey:e?.receiverPublicKey})}function v3(t){let e=t?.type||nb;if(e===ru){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function j$(t){return t.type===ru&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var Q$=Object.defineProperty,XR=Object.getOwnPropertySymbols,z$=Object.prototype.hasOwnProperty,W$=Object.prototype.propertyIsEnumerable,ZR=(t,e,r)=>e in t?Q$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,e3=(t,e)=>{for(var r in e||(e={}))z$.call(e,r)&&ZR(t,r,e[r]);if(XR)for(var r of XR(e))W$.call(e,r)&&ZR(t,r,e[r]);return t},A3="ReactNative",sr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Kp=" ",$$=":",b3="/",ob=2,K$=1e3,I3="js";function ab(){return typeof p.default<"u"&&typeof p.default.versions<"u"&&typeof p.default.versions.node<"u"}function nu(){return!tu.getDocument()&&!!tu.getNavigator()&&navigator.product===A3}function Nl(){return!ab()&&!!tu.getNavigator()&&!!tu.getDocument()}function oo(){return nu()?sr.reactNative:ab()?sr.node:Nl()?sr.browser:sr.unknown}function Y$(){var t;try{return nu()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function _3(t,e){let r=Wp.parse(t);return r=e3(e3({},r),e),t=Wp.stringify(r),t}function J$(){return S$.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function X$(t,e){var r;let n=oo(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=tu.getLocation())==null?void 0:r.host)||"unknown"),i}function S3(){if(oo()===sr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=_$.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function T3(){var t;let e=oo();return e===sr.browser?[e,((t=tu.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function C3(t,e,r){let n=S3(),i=T3();return[[t,e].join("-"),[I3,r].join("-"),n,i].join("/")}function Z$({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a}){let u=r.split("?"),c=C3(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:a||void 0},d=_3(u[1]||"",f);return u[0]+"?"+d}function eK(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function tK(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function x3(t,e=ob){return N3(t.split(b3),e)}function rK(t){return x3(t).join(Kp)}function Xi(t,e){return t.filter(r=>e.includes(r)).length===t.length}function N3(t,e=ob){return t.slice(Math.max(t.length-e,0))}function nK(t){return Object.fromEntries(t.entries())}function iK(t){return new Map(Object.entries(t))}function sK(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var oK=t=>t;function O3(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function aK(t){return t.split(Kp).map(e=>O3(e)).join(Kp)}function uK(t=eu.FIVE_MINUTES,e){let r=eu.toMiliseconds(t||eu.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,a)=>{s=setTimeout(()=>{a(new Error(e))},r),n=o,i=a})}}function cK(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function ub(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function lK(t){return ub("topic",t)}function fK(t){return ub("id",t)}function dK(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function hK(t,e){return eu.fromMiliseconds((e||Date.now())+eu.toMiliseconds(t))}function pK(t){return Date.now()>=eu.toMiliseconds(t)}function gK(t,e){return`${t}${e?`:${e}`:""}`}function Zi(t=[],e=[]){return[...new Set([...t,...e])]}async function yK({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=oo();o===sr.browser?s.startsWith("https://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===sr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function mK(t,e){try{return await t.getItem(e)||(Nl()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}var D3="irn";function wK(t){return t?.relay||{protocol:D3}}function EK(t){let e=C$.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var vK=Object.defineProperty,t3=Object.getOwnPropertySymbols,AK=Object.prototype.hasOwnProperty,bK=Object.prototype.propertyIsEnumerable,r3=(t,e,r)=>e in t?vK(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,IK=(t,e)=>{for(var r in e||(e={}))AK.call(e,r)&&r3(t,r,e[r]);if(t3)for(var r of t3(e))bK.call(e,r)&&r3(t,r,e[r]);return t};function P3(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function _K(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=Wp.parse(s);return{protocol:n,topic:R3(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:P3(o)}}function R3(t){return t.startsWith("//")?t.substring(2):t}function B3(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function SK(t){return`${t.protocol}:${t.topic}@${t.version}?`+Wp.stringify(IK({symKey:t.symKey},B3(t.relay)))}var TK=Object.defineProperty,CK=Object.defineProperties,xK=Object.getOwnPropertyDescriptors,n3=Object.getOwnPropertySymbols,NK=Object.prototype.hasOwnProperty,OK=Object.prototype.propertyIsEnumerable,i3=(t,e,r)=>e in t?TK(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,DK=(t,e)=>{for(var r in e||(e={}))NK.call(e,r)&&i3(t,r,e[r]);if(n3)for(var r of n3(e))OK.call(e,r)&&i3(t,r,e[r]);return t},PK=(t,e)=>CK(t,xK(e));function ao(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function L3(t){let e=[];return Object.values(t).forEach(r=>{e.push(...ao(r.accounts))}),e}function F3(t,e){let r=[];return Object.values(t).forEach(n=>{ao(n.accounts).includes(e)&&r.push(...n.methods)}),r}function M3(t,e){let r=[];return Object.values(t).forEach(n=>{ao(n.accounts).includes(e)&&r.push(...n.events)}),r}function RK(t,e){let r=W3(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function BK(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=YA(e),s=YA(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,g=n[c].events,m=n[c].accounts;f.forEach(y=>{if(!m.some(A=>A.includes(y)))throw new Error(`No accounts provided for chain ${y} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:g,accounts:m}});let a=K3(e,o,"approve()");if(a)throw new Error(a.message);let u={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(y=>{var A,O;return(O=(A=i[c])==null?void 0:A.chains)==null?void 0:O.includes(y)}),d=n[c].methods.filter(y=>{var A,O;return(O=(A=i[c])==null?void 0:A.methods)==null?void 0:O.includes(y)}),g=n[c].events.filter(y=>{var A,O;return(O=(A=i[c])==null?void 0:A.events)==null?void 0:O.includes(y)}),m=f.map(y=>n[c].accounts.filter(A=>A.includes(`${y}:`))).flat();u[c]={chains:f,methods:d,events:g,accounts:m}}),Object.keys(s).forEach(c=>{var f,d,g,m,y,A;if(!n[c])return;let O=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(b=>n[c].chains.includes(b)),R=n[c].methods.filter(b=>{var S,N;return(N=(S=s[c])==null?void 0:S.methods)==null?void 0:N.includes(b)}),q=n[c].events.filter(b=>{var S,N;return(N=(S=s[c])==null?void 0:S.events)==null?void 0:N.includes(b)}),M=O?.map(b=>n[c].accounts.filter(S=>S.includes(`${b}:`))).flat();u[c]={chains:Zi((g=u[c])==null?void 0:g.chains,O),methods:Zi((m=u[c])==null?void 0:m.methods,R),events:Zi((y=u[c])==null?void 0:y.events,q),accounts:Zi((A=u[c])==null?void 0:A.accounts,M)}}),u)}function cb(t){return t.includes(":")}function U3(t){return cb(t)?t.split(":")[0]:t}function YA(t){var e,r,n;let i={};if(!eg(t))return i;for(let[s,o]of Object.entries(t)){let a=cb(s)?[s]:o.chains,u=o.methods||[],c=o.events||[],f=U3(s);i[f]=PK(DK({},i[f]),{chains:Zi(a,(e=i[f])==null?void 0:e.chains),methods:Zi(u,(r=i[f])==null?void 0:r.methods),events:Zi(c,(n=i[f])==null?void 0:n.events)})}return i}var q3={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},V3={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function li(t,e){let{message:r,code:n}=V3[t];return{message:e?`${r} ${e}`:r,code:n}}function so(t,e){let{message:r,code:n}=q3[t];return{message:e?`${r} ${e}`:r,code:n}}function Ol(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function eg(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function es(t){return typeof t>"u"}function _r(t,e){return e&&es(t)?!0:typeof t=="string"&&!!t.trim().length}function tg(t,e){return e&&es(t)?!0:typeof t=="number"&&!isNaN(t)}function LK(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Xi(i,n)?(n.forEach(o=>{let{accounts:a,methods:u,events:c}=t.namespaces[o],f=ao(a),d=r[o];(!Xi(Jp(o,d),f)||!Xi(d.methods,u)||!Xi(d.events,c))&&(s=!1)}),s):!1}function Cl(t){return _r(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function H3(t){if(_r(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&Cl(r)}}return!1}function FK(t){if(_r(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function MK(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function UK(t){return t?.topic}function qK(t,e){let r=null;return _r(t?.publicKey,!1)||(r=li("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function JA(t){let e=!0;return Ol(t)?t.length&&(e=t.every(r=>_r(r,!1))):e=!1,e}function k3(t,e,r){let n=null;return Ol(e)&&e.length?e.forEach(i=>{n||Cl(i)||(n=so("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Cl(t)||(n=so("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function G3(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=k3(i,Jp(i,s),`${e} ${r}`);o&&(n=o)}),n}function j3(t,e){let r=null;return Ol(t)?t.forEach(n=>{r||H3(n)||(r=so("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=so("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function Q3(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=j3(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function z3(t,e){let r=null;return JA(t?.methods)?JA(t?.events)||(r=so("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=so("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function lb(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=z3(n,`${e}, namespace`);i&&(r=i)}),r}function VK(t,e,r){let n=null;if(t&&eg(t)){let i=lb(t,e);i&&(n=i);let s=G3(t,e,r);s&&(n=s)}else n=li("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function W3(t,e){let r=null;if(t&&eg(t)){let n=lb(t,e);n&&(r=n);let i=Q3(t,e);i&&(r=i)}else r=li("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function $3(t){return _r(t.protocol,!0)}function HK(t,e){let r=!1;return e&&!t?r=!0:t&&Ol(t)&&t.length&&t.forEach(n=>{r=$3(n)}),r}function kK(t){return typeof t=="number"}function GK(t){return typeof t<"u"&&typeof t!==null}function jK(t){return!(!t||typeof t!="object"||!t.code||!tg(t.code,!1)||!t.message||!_r(t.message,!1))}function QK(t){return!(es(t)||!_r(t.method,!1))}function zK(t){return!(es(t)||es(t.result)&&es(t.error)||!tg(t.id,!1)||!_r(t.jsonrpc,!1))}function WK(t){return!(es(t)||!_r(t.name,!1))}function $K(t,e){return!(!Cl(e)||!L3(t).includes(e))}function KK(t,e,r){return _r(r,!1)?F3(t,e).includes(r):!1}function YK(t,e,r){return _r(r,!1)?M3(t,e).includes(r):!1}function K3(t,e,r){let n=null,i=JK(t),s=XK(e),o=Object.keys(i),a=Object.keys(s),u=s3(Object.keys(t)),c=s3(Object.keys(e)),f=u.filter(d=>!c.includes(d));return f.length&&(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. - Required: ${f.toString()} - Received: ${Object.keys(e).toString()}`)),Xi(o,a)||(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. - Required: ${o.toString()} - Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let g=ao(e[d].accounts);g.includes(d)||(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} - Required: ${d} - Approved: ${g.toString()}`))}),o.forEach(d=>{n||(Xi(i[d].methods,s[d].methods)?Xi(i[d].events,s[d].events)||(n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=li("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function JK(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function s3(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function XK(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:ao(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function ZK(t,e){return tg(t,!1)&&t<=e.max&&t>=e.min}function eY(){let t=oo();return new Promise(e=>{switch(t){case sr.browser:e(Y3());break;case sr.reactNative:e(J3());break;case sr.node:e(X3());break;default:e(!0)}})}function Y3(){return Nl()&&navigator?.onLine}async function J3(){return nu()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function X3(){return!0}function tY(t){switch(oo()){case sr.browser:Z3(t);break;case sr.reactNative:eB(t);break;case sr.node:break}}function Z3(t){!nu()&&Nl()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function eB(t){nu()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var $A={},XA=class{static get(e){return $A[e]}static set(e,r){$A[e]=r}static delete(e){delete $A[e]}};H.BASE10=rb,H.BASE16=or,H.BASE64=$p,H.COLON=$$,H.DEFAULT_DEPTH=ob,H.EMPTY_SPACE=Kp,H.ENV_MAP=sr,H.INTERNAL_ERRORS=V3,H.MemoryStore=XA,H.ONE_THOUSAND=K$,H.REACT_NATIVE_PRODUCT=A3,H.RELAYER_DEFAULT_PROTOCOL=D3,H.SDK_ERRORS=q3,H.SDK_TYPE=I3,H.SLASH=b3,H.TYPE_0=nb,H.TYPE_1=ru,H.UTF8=Zp,H.appendToQueryString=_3,H.assertType=tK,H.buildApprovedNamespaces=BK,H.calcExpiry=hK,H.capitalize=aK,H.capitalizeWord=O3,H.createDelayedPromise=uK,H.createExpiringPromise=cK,H.decodeTypeByte=xl,H.decrypt=k$,H.deriveSymKey=U$,H.deserialize=sb,H.encodeTypeByte=w3,H.encrypt=H$,H.engineEvent=gK,H.enumify=oK,H.formatAccountId=d3,H.formatAccountWithChain=x$,H.formatChainId=f3,H.formatExpirerTarget=ub,H.formatIdTarget=fK,H.formatMessage=B$,H.formatMessageContext=rK,H.formatRelayParams=B3,H.formatRelayRpcUrl=Z$,H.formatTopicTarget=lK,H.formatUA=C3,H.formatUri=SK,H.generateKeyPair=F$,H.generateRandomBytes32=M$,H.getAccountsChains=ao,H.getAccountsFromNamespaces=O$,H.getAddressFromAccount=h3,H.getAddressesFromAccounts=N$,H.getAppMetadata=J$,H.getBrowserOnlineStatus=Y3,H.getBundleId=Y$,H.getChainFromAccount=p3,H.getChainsFromAccounts=g3,H.getChainsFromNamespace=Jp,H.getChainsFromNamespaces=D$,H.getChainsFromRequiredNamespaces=P$,H.getDeepLink=mK,H.getDidAddress=m3,H.getDidAddressSegments=Xp,H.getDidChainId=y3,H.getEnvironment=oo,H.getHttpUrl=eK,H.getInternalError=li,H.getJavascriptID=T3,H.getJavascriptOS=S3,H.getLastItems=N3,H.getNamespacedDidChainId=R$,H.getNamespacesChains=L3,H.getNamespacesEventsForChainId=M3,H.getNamespacesMethodsForChainId=F3,H.getNodeOnlineStatus=X3,H.getReactNativeOnlineStatus=J3,H.getRelayClientMetadata=X$,H.getRelayProtocolApi=EK,H.getRelayProtocolName=wK,H.getRequiredNamespacesFromNamespaces=RK,H.getSdkError=so,H.getUniqueValues=tb,H.handleDeeplinkRedirect=yK,H.hasOverlap=Xi,H.hashKey=q$,H.hashMessage=V$,H.isBrowser=Nl,H.isCaipNamespace=cb,H.isConformingNamespaces=K3,H.isExpired=pK,H.isNode=ab,H.isOnline=eY,H.isProposalStruct=MK,H.isReactNative=nu,H.isSessionCompatible=LK,H.isSessionStruct=UK,H.isTypeOneEnvelope=j$,H.isUndefined=es,H.isValidAccountId=H3,H.isValidAccounts=j3,H.isValidActions=z3,H.isValidArray=Ol,H.isValidChainId=Cl,H.isValidChains=k3,H.isValidController=qK,H.isValidErrorReason=jK,H.isValidEvent=WK,H.isValidId=kK,H.isValidNamespaceAccounts=Q3,H.isValidNamespaceActions=lb,H.isValidNamespaceChains=G3,H.isValidNamespaceMethodsOrEvents=JA,H.isValidNamespaces=W3,H.isValidNamespacesChainId=$K,H.isValidNamespacesEvent=YK,H.isValidNamespacesRequest=KK,H.isValidNumber=tg,H.isValidObject=eg,H.isValidParams=GK,H.isValidRelay=$3,H.isValidRelays=HK,H.isValidRequest=QK,H.isValidRequestExpiry=ZK,H.isValidRequiredNamespaces=VK,H.isValidResponse=zK,H.isValidString=_r,H.isValidUrl=FK,H.mapEntries=sK,H.mapToObj=nK,H.mergeArrays=Zi,H.normalizeNamespaces=YA,H.objToMap=iK,H.parseAccountId=eb,H.parseChainId=l3,H.parseContextNames=x3,H.parseExpirerTarget=dK,H.parseNamespaceKey=U3,H.parseRelayParams=P3,H.parseTopic=R3,H.parseUri=_K,H.serialize=E3,H.subscribeToBrowserNetworkChange=Z3,H.subscribeToNetworkChange=tY,H.subscribeToReactNativeNetworkChange=eB,H.validateDecoding=G$,H.validateEncoding=v3});var tB,rB,nB,iB,rg,Pl,fb,ng,ts,Rl,ig=he(()=>{l();tB="PARSE_ERROR",rB="INVALID_REQUEST",nB="METHOD_NOT_FOUND",iB="INVALID_PARAMS",rg="INTERNAL_ERROR",Pl="SERVER_ERROR",fb=[-32700,-32600,-32601,-32602,-32603],ng=[-32e3,-32099],ts={[tB]:{code:-32700,message:"Parse error"},[rB]:{code:-32600,message:"Invalid Request"},[nB]:{code:-32601,message:"Method not found"},[iB]:{code:-32602,message:"Invalid params"},[rg]:{code:-32603,message:"Internal error"},[Pl]:{code:-32e3,message:"Server error"}},Rl=Pl});function rY(t){return t<=ng[0]&&t>=ng[1]}function sg(t){return fb.includes(t)}function sB(t){return typeof t=="number"}function og(t){return Object.keys(ts).includes(t)?ts[t]:ts[Rl]}function ag(t){let e=Object.values(ts).find(r=>r.code===t);return e||ts[Rl]}function nY(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!sB(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(sg(t.error.code)){let e=ag(t.error.code);if(e.message!==ts[Rl].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function db(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var hb=he(()=>{l();ig()});var aB=v(rs=>{"use strict";l();Object.defineProperty(rs,"__esModule",{value:!0});rs.isBrowserCryptoAvailable=rs.getSubtleCrypto=rs.getBrowerCrypto=void 0;function pb(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}rs.getBrowerCrypto=pb;function oB(){let t=pb();return t.subtle||t.webkitSubtle}rs.getSubtleCrypto=oB;function iY(){return!!pb()&&!!oB()}rs.isBrowserCryptoAvailable=iY});var lB=v(ns=>{"use strict";l();Object.defineProperty(ns,"__esModule",{value:!0});ns.isBrowser=ns.isNode=ns.isReactNative=void 0;function uB(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ns.isReactNative=uB;function cB(){return typeof p.default<"u"&&typeof p.default.versions<"u"&&typeof p.default.versions.node<"u"}ns.isNode=cB;function sY(){return!uB()&&!cB()}ns.isBrowser=sY});var gb=v(ug=>{"use strict";l();Object.defineProperty(ug,"__esModule",{value:!0});var fB=(en(),ht(Zr));fB.__exportStar(aB(),ug);fB.__exportStar(lB(),ug)});var kt={};ft(kt,{isNodeJs:()=>hB});var dB,hB,pB=he(()=>{l();dB=be(gb());Qt(kt,be(gb()));hB=dB.isNode});function yb(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function mb(t=6){return BigInt(yb(t))}function wb(t,e,r){return{id:r||yb(),jsonrpc:"2.0",method:t,params:e}}function oY(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Eb(t,e,r){return{id:t,jsonrpc:"2.0",error:gB(e,r)}}function gB(t,e){return typeof t>"u"?og(rg):(typeof t=="string"&&(t=Object.assign(Object.assign({},og(Pl)),{message:t})),typeof e<"u"&&(t.data=e),sg(t.code)&&(t=ag(t.code)),t)}var yB=he(()=>{l();hb();ig()});function aY(t){return t.includes("*")?lg(t):!/\W/g.test(t)}function cg(t){return t==="*"}function lg(t){return cg(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function uY(t){return!cg(t)&&lg(t)&&!t.split("*")[0].trim()}function cY(t){return!cg(t)&&lg(t)&&!t.split("*")[1].trim()}var mB=he(()=>{l()});var wB=he(()=>{l()});var iu,vb=he(()=>{l();iu=class{}});var Ab,fg,Bl,EB=he(()=>{l();vb();Ab=class extends iu{constructor(e){super()}},fg=class extends iu{constructor(){super()}},Bl=class extends fg{constructor(e){super()}}});var vB=he(()=>{l()});var AB=he(()=>{l();wB();vb();EB();vB()});var bB=he(()=>{l();AB()});function dY(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function IB(t,e){let r=dY(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function hY(t){return IB(t,lY)}function dg(t){return IB(t,fY)}function bb(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var lY,fY,_B=he(()=>{l();lY="^https?:",fY="^wss?:"});function Ib(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function pY(t){return Ib(t)&&"method"in t}function _b(t){return Ib(t)&&(SB(t)||hg(t))}function SB(t){return"result"in t}function hg(t){return"error"in t}function gY(t){return"error"in t&&t.valid===!1}var TB=he(()=>{l()});var rr={};ft(rr,{DEFAULT_ERROR:()=>Rl,IBaseJsonRpcProvider:()=>fg,IEvents:()=>iu,IJsonRpcConnection:()=>Ab,IJsonRpcProvider:()=>Bl,INTERNAL_ERROR:()=>rg,INVALID_PARAMS:()=>iB,INVALID_REQUEST:()=>rB,METHOD_NOT_FOUND:()=>nB,PARSE_ERROR:()=>tB,RESERVED_ERROR_CODES:()=>fb,SERVER_ERROR:()=>Pl,SERVER_ERROR_CODE_RANGE:()=>ng,STANDARD_ERROR_MAP:()=>ts,formatErrorMessage:()=>gB,formatJsonRpcError:()=>Eb,formatJsonRpcRequest:()=>wb,formatJsonRpcResult:()=>oY,getBigIntRpcId:()=>mb,getError:()=>og,getErrorByCode:()=>ag,isHttpUrl:()=>hY,isJsonRpcError:()=>hg,isJsonRpcPayload:()=>Ib,isJsonRpcRequest:()=>pY,isJsonRpcResponse:()=>_b,isJsonRpcResult:()=>SB,isJsonRpcValidationInvalid:()=>gY,isLocalhostUrl:()=>bb,isNodeJs:()=>hB,isReservedErrorCode:()=>sg,isServerErrorCode:()=>rY,isValidDefaultRoute:()=>cg,isValidErrorCode:()=>sB,isValidLeadingWildcardRoute:()=>uY,isValidRoute:()=>aY,isValidTrailingWildcardRoute:()=>cY,isValidWildcardRoute:()=>lg,isWsUrl:()=>dg,parseConnectionError:()=>db,payloadId:()=>yb,validateJsonRpcError:()=>nY});var Ll=he(()=>{l();ig();hb();pB();Qt(rr,kt);yB();mB();bB();_B();TB()});var CB,pg,xB,Sb=he(()=>{l();CB=be(ti());Ll();pg=class extends Bl{constructor(e){super(e),this.events=new CB.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(wb(e.method,e.params||[],e.id||mb().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{hg(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),_b(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},xB=pg});var NB={};ft(NB,{JsonRpcProvider:()=>pg,default:()=>yY});var yY,OB=he(()=>{l();Sb();Sb();yY=xB});var PB=v((s0e,DB)=>{"use strict";l();DB.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var FB={};ft(FB,{WsConnection:()=>Tb,default:()=>Tb});var LB,mY,wY,RB,BB,EY,Tb,MB=he(()=>{l();LB=be(ti());nl();Ll();mY=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:PB(),wY=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",RB=t=>t.split("?")[0],BB=10,EY=mY(),Tb=class{constructor(e){if(this.url=e,this.events=new LB.EventEmitter,this.registering=!1,!dg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Qi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!dg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,rr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!bb(e)},o=new EY(e,[],s);wY()?o.onerror=a=>{let u=a;n(this.emitError(u.error))}:o.on("error",a=>{n(this.emitError(a))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?ji(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=Eb(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return db(e,RB(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>BB&&this.events.setMaxListeners(BB)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${RB(this.url)}`));return this.events.emit("register_error",r),r}}});var w6=v((Fl,ou)=>{l();var vY=200,Mb="__lodash_hash_undefined__",bg=1,KB=2,YB=9007199254740991,gg="[object Arguments]",Ob="[object Array]",AY="[object AsyncFunction]",JB="[object Boolean]",XB="[object Date]",ZB="[object Error]",e6="[object Function]",bY="[object GeneratorFunction]",yg="[object Map]",t6="[object Number]",IY="[object Null]",su="[object Object]",UB="[object Promise]",_Y="[object Proxy]",r6="[object RegExp]",mg="[object Set]",n6="[object String]",SY="[object Symbol]",TY="[object Undefined]",Db="[object WeakMap]",i6="[object ArrayBuffer]",wg="[object DataView]",CY="[object Float32Array]",xY="[object Float64Array]",NY="[object Int8Array]",OY="[object Int16Array]",DY="[object Int32Array]",PY="[object Uint8Array]",RY="[object Uint8ClampedArray]",BY="[object Uint16Array]",LY="[object Uint32Array]",FY=/[\\^$.*+?()[\]{}|]/g,MY=/^\[object .+?Constructor\]$/,UY=/^(?:0|[1-9]\d*)$/,st={};st[CY]=st[xY]=st[NY]=st[OY]=st[DY]=st[PY]=st[RY]=st[BY]=st[LY]=!0;st[gg]=st[Ob]=st[i6]=st[JB]=st[wg]=st[XB]=st[ZB]=st[e6]=st[yg]=st[t6]=st[su]=st[r6]=st[mg]=st[n6]=st[Db]=!1;var s6=typeof global=="object"&&global&&global.Object===Object&&global,qY=typeof self=="object"&&self&&self.Object===Object&&self,fi=s6||qY||Function("return this")(),o6=typeof Fl=="object"&&Fl&&!Fl.nodeType&&Fl,qB=o6&&typeof ou=="object"&&ou&&!ou.nodeType&&ou,a6=qB&&qB.exports===o6,Cb=a6&&s6.process,VB=function(){try{return Cb&&Cb.binding&&Cb.binding("util")}catch{}}(),HB=VB&&VB.isTypedArray;function VY(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function yJ(t,e){var r=this.__data__,n=_g(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}di.prototype.clear=dJ;di.prototype.delete=hJ;di.prototype.get=pJ;di.prototype.has=gJ;di.prototype.set=yJ;function lo(t){var e=-1,r=t==null?0:t.length;for(this.clear();++ea))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,g=r&KB?new vg:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=YB}function y6(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ql(t){return t!=null&&typeof t=="object"}var m6=HB?jY(HB):RJ;function WJ(t){return QJ(t)?NJ(t):BJ(t)}function $J(){return[]}function KJ(){return!1}ou.exports=zJ});var Ub=v((f0e,E6)=>{l();E6.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],a={},u=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:u,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return a[f.toLowerCase()]},has:function(f){return f.toLowerCase()in a}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,g){s.push(d=d.toLowerCase()),o.push([d,g]),a[d]=a[d]?a[d]+","+g:g}),r(u())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var A6=v((h0e,v6)=>{l();v6.exports=self.fetch||(self.fetch=Ub().default||Ub())});var x8=v(we=>{"use strict";l();Object.defineProperty(we,"__esModule",{value:!0});var ho=ti(),YJ=(V2(),ht(q2)),Gl=nD(),Qe=m1(),Ln=F1(),b6=(nl(),ht(M2)),JJ=(VP(),ht(qP)),te=Dl(),XJ=(HA(),ht(VA)),Ke=Xs(),ZJ=(OB(),ht(NB)),Sr=(Ll(),ht(rr)),eX=(MB(),ht(FB)),tX=w6(),rX=A6();function jl(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function nX(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var iX=jl(ho),sX=jl(YJ),Tg=nX(JJ),oX=jl(eX),aX=jl(tX),uX=jl(rX);function cX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,b=new Uint8Array(M);R!==q;){for(var S=y[R],N=0,_=M-1;(S!==0||N>>0,b[_]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");O=N,R++}for(var T=M-O;T!==M&&b[T]===0;)T++;for(var B=u.repeat(A);T>>0,M=new Uint8Array(q);y[A];){var b=r[y.charCodeAt(A)];if(b===255)return;for(var S=0,N=q-1;(b!==0||S>>0,M[N]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");R=S,A++}if(y[A]!==" "){for(var _=q-R;_!==q&&M[_]===0;)_++;for(var T=new Uint8Array(O+(q-_)),B=O;_!==q;)T[B++]=M[_++];return T}}}function m(y){var A=g(y);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:g,decode:m}}var lX=cX,fX=lX,q6=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},dX=t=>new TextEncoder().encode(t),hX=t=>new TextDecoder().decode(t),Hb=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},kb=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return V6(this,e)}},Gb=class{constructor(e){this.decoders=e}or(e){return V6(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},V6=(t,e)=>new Gb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),jb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Hb(e,r,n),this.decoder=new kb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Hg=({name:t,prefix:e,encode:r,decode:n})=>new jb(t,e,r,n),Ql=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=fX(r,e);return Hg({prefix:t,name:e,encode:n,decode:s=>q6(i(s))})},pX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(a-=8,o[c++]=255&u>>a)}if(a>=r||255&u<<8-a)throw new SyntaxError("Unexpected end of data");return o},gX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<Hg({prefix:e,name:t,encode(i){return gX(i,n,r)},decode(i){return pX(i,n,r,t)}}),yX=Hg({prefix:"\0",name:"identity",encode:t=>hX(t),decode:t=>dX(t)}),mX=Object.freeze({__proto__:null,identity:yX}),wX=zt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),EX=Object.freeze({__proto__:null,base2:wX}),vX=zt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),AX=Object.freeze({__proto__:null,base8:vX}),bX=Ql({prefix:"9",name:"base10",alphabet:"0123456789"}),IX=Object.freeze({__proto__:null,base10:bX}),_X=zt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),SX=zt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),TX=Object.freeze({__proto__:null,base16:_X,base16upper:SX}),CX=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xX=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),NX=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),OX=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),DX=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),PX=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),RX=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),BX=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),LX=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),FX=Object.freeze({__proto__:null,base32:CX,base32upper:xX,base32pad:NX,base32padupper:OX,base32hex:DX,base32hexupper:PX,base32hexpad:RX,base32hexpadupper:BX,base32z:LX}),MX=Ql({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),UX=Ql({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),qX=Object.freeze({__proto__:null,base36:MX,base36upper:UX}),VX=Ql({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),HX=Ql({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),kX=Object.freeze({__proto__:null,base58btc:VX,base58flickr:HX}),GX=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jX=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QX=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zX=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),WX=Object.freeze({__proto__:null,base64:GX,base64pad:jX,base64url:QX,base64urlpad:zX}),H6=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$X=H6.reduce((t,e,r)=>(t[r]=e,t),[]),KX=H6.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function YX(t){return t.reduce((e,r)=>(e+=$X[r],e),"")}function JX(t){let e=[];for(let r of t){let n=KX[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var XX=Hg({prefix:"\u{1F680}",name:"base256emoji",encode:YX,decode:JX}),ZX=Object.freeze({__proto__:null,base256emoji:XX}),eZ=k6,I6=128,tZ=127,rZ=~tZ,nZ=Math.pow(2,31);function k6(t,e,r){e=e||[],r=r||0;for(var n=r;t>=nZ;)e[r++]=t&255|I6,t/=128;for(;t&rZ;)e[r++]=t&255|I6,t>>>=7;return e[r]=t|0,k6.bytes=r-n+1,e}var iZ=Qb,sZ=128,_6=127;function Qb(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Qb.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&_6)<=sZ);return Qb.bytes=s-n,r}var oZ=Math.pow(2,7),aZ=Math.pow(2,14),uZ=Math.pow(2,21),cZ=Math.pow(2,28),lZ=Math.pow(2,35),fZ=Math.pow(2,42),dZ=Math.pow(2,49),hZ=Math.pow(2,56),pZ=Math.pow(2,63),gZ=function(t){return t(G6.encode(t,e,r),e),T6=t=>G6.encodingLength(t),zb=(t,e)=>{let r=e.byteLength,n=T6(t),i=n+T6(r),s=new Uint8Array(i+r);return S6(t,s,0),S6(r,s,n),s.set(e,i),new Wb(t,r,e,s)},Wb=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},j6=({name:t,code:e,encode:r})=>new $b(t,e,r),$b=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?zb(this.code,r):r.then(n=>zb(this.code,n))}else throw Error("Unknown type, must be binary type")}},Q6=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),mZ=j6({name:"sha2-256",code:18,encode:Q6("SHA-256")}),wZ=j6({name:"sha2-512",code:19,encode:Q6("SHA-512")}),EZ=Object.freeze({__proto__:null,sha256:mZ,sha512:wZ}),z6=0,vZ="identity",W6=q6,AZ=t=>zb(z6,W6(t)),bZ={code:z6,name:vZ,encode:W6,digest:AZ},IZ=Object.freeze({__proto__:null,identity:bZ});new TextEncoder,new TextDecoder;var C6={...mX,...EX,...AX,...IX,...TX,...FX,...qX,...kX,...WX,...ZX};({...EZ,...IZ});function $6(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function _Z(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?$6(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function K6(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var x6=K6("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),qb=K6("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=_Z(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=Qe.generateChildLogger(r,this.name)}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,te.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?te.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Og=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=Z6,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=Tg.generateKeyPair(i);return Tg.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=te.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=Tg.generateKeyPair(s),a=te.generateRandomBytes32(),u=e8;return await Tg.signJWT(a,i,u,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let a=this.getPrivateKey(i),u=te.deriveSymKey(a,s);return this.setSymKey(u,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||te.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let a=te.validateEncoding(o),u=b6.safeJsonStringify(s);if(te.isTypeOneEnvelope(a)){let g=a.senderPublicKey,m=a.receiverPublicKey;i=await this.generateSharedKey(g,m)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=a;return te.encrypt({type:f,symKey:c,message:u,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let a=te.validateDecoding(s,o);if(te.isTypeOneEnvelope(a)){let u=a.receiverPublicKey,c=a.senderPublicKey;i=await this.generateSharedKey(u,c)}try{let u=this.getSymKey(i),c=te.decrypt({symKey:u,encoded:s});return b6.safeJsonParse(c)}catch(u){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(u)}},this.getPayloadType=i=>{let s=te.deserialize(i);return te.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=te.deserialize(i);return s.senderPublicKey?XJ.toString(s.senderPublicKey,te.BASE16):void 0},this.core=e,this.logger=Qe.generateChildLogger(r,this.name),this.keychain=n||new Ng(this.core,this.logger)}get context(){return Qe.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Kb)}catch{e=te.generateRandomBytes32(),await this.keychain.set(Kb,e)}return TZ(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Dg=class extends Ln.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=n8,this.version=i8,this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=te.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=te.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=Qe.generateChildLogger(e,this.name),this.core=r}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,te.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?te.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Jb=class extends Ln.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new ho.EventEmitter,this.name=o8,this.queue=new Map,this.publishTimeout=Ke.toMiliseconds(Ke.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});try{let a=s?.ttl||s8,u=te.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||Sr.getBigIntRpcId().toString(),g={topic:n,message:i,opts:{ttl:a,relay:u,prompt:c,tag:f,id:d}},m=setTimeout(()=>this.queue.set(d,g),this.publishTimeout);try{await await te.createExpiringPromise(this.rpcPublish(n,i,a,u,c,f,d),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(d),this.relayer.events.emit(ar.publish,g)}catch(y){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(o=s?.internal)!=null&&o.throwOnFailedPublish)throw this.removeRequestFromQueue(d),y;return}finally{clearTimeout(m)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}})}catch(a){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(a),a}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=Qe.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return Qe.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,a){var u,c,f,d;let g={method:te.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:a};return te.isUndefined((u=g.params)==null?void 0:u.prompt)&&((c=g.params)==null||delete c.prompt),te.isUndefined((f=g.params)==null?void 0:f.tag)&&((d=g.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g}),this.relayer.request(g)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ar.connection_stalled);return}this.checkQueue()}),this.relayer.on(ar.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},Xb=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},DZ=Object.defineProperty,PZ=Object.defineProperties,RZ=Object.getOwnPropertyDescriptors,N6=Object.getOwnPropertySymbols,BZ=Object.prototype.hasOwnProperty,LZ=Object.prototype.propertyIsEnumerable,O6=(t,e,r)=>e in t?DZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hl=(t,e)=>{for(var r in e||(e={}))BZ.call(e,r)&&O6(t,r,e[r]);if(N6)for(var r of N6(e))LZ.call(e,r)&&O6(t,r,e[r]);return t},Vb=(t,e)=>PZ(t,RZ(e)),Pg=class extends Ln.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new Xb,this.events=new ho.EventEmitter,this.name=y8,this.version=m8,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hi,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=te.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let a=await this.rpcSubscribe(n,s);return this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,s)=>{let o=new Ke.Watch;o.start(this.pendingSubscriptionWatchLabel);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),i(!0)),o.elapsed(this.pendingSubscriptionWatchLabel)>=w8&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),s(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Qe.generateChildLogger(r,this.name),this.clientId=""}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=te.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=te.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:te.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await te.createExpiringPromise(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ar.connection_stalled)}return te.hashMessage(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:te.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await te.createExpiringPromise(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(ar.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:te.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Vb(Hl({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Hl({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,Hl({},r)),this.topicMap.set(r.topic,e),this.events.emit(Gr.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Gr.deleted,Vb(Hl({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Gr.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);te.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>Vb(Hl({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(ar.connect,async()=>{await this.onConnect()}),this.relayer.on(ar.disconnect,()=>{this.onDisconnect()}),this.events.on(Gr.created,async e=>{let r=Gr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Gr.deleted,async e=>{let r=Gr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},FZ=Object.defineProperty,D6=Object.getOwnPropertySymbols,MZ=Object.prototype.hasOwnProperty,UZ=Object.prototype.propertyIsEnumerable,P6=(t,e,r)=>e in t?FZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qZ=(t,e)=>{for(var r in e||(e={}))MZ.call(e,r)&&P6(t,r,e[r]);if(D6)for(var r of D6(e))UZ.call(e,r)&&P6(t,r,e[r]);return t},Rg=class extends Ln.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new ho.EventEmitter,this.name=c8,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async r=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(r)}catch(n){throw this.logger.debug("Failed to Publish Request"),this.logger.error(n),n}},this.onPayloadHandler=r=>{this.onProviderPayload(r)},this.onConnectHandler=()=>{this.events.emit(ar.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(ar.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Bn.payload,this.onPayloadHandler),this.provider.on(Bn.connect,this.onConnectHandler),this.provider.on(Bn.disconnect,this.onDisconnectHandler),this.provider.on(Bn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Qe.generateChildLogger(e.logger,this.name):Qe.pino(Qe.getDefaultLoggerOptions({level:e.logger||u8})),this.messages=new Dg(this.logger,e.core),this.subscriber=new Pg(this,this.logger),this.publisher=new Jb(this,this.logger),this.relayUrl=e?.relayUrl||eI,this.projectId=e.projectId,this.bundleId=te.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${Yb}...`),await this.restartTransport(Yb)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},h8)}get context(){return Qe.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";if(i)return i;let s,o=a=>{a.topic===e&&(this.subscriber.off(Gr.created,o),s())};return await Promise.all([new Promise(a=>{s=a,this.subscriber.on(Gr.created,o)}),new Promise(async a=>{i=await this.subscriber.subscribe(e,r),a()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await te.createExpiringPromise(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(r=>{if(!this.initialized)return r();this.subscriber.once(Gr.resubscribed,()=>{r()})}),new Promise(async(r,n)=>{try{await te.createExpiringPromise(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){n(i);return}r()})])}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r;this.provider.events.emit(Bn.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await te.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ZJ.JsonRpcProvider(new oX.default(te.formatRelayRpcUrl({sdkVersion:d8,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sr.isJsonRpcRequest(e)){if(!e.method.endsWith(l8))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(qZ({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else Sr.isJsonRpcResponse(e)&&this.events.emit(ar.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(ar.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=Sr.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Bn.payload,this.onPayloadHandler),this.provider.off(Bn.connect,this.onConnectHandler),this.provider.off(Bn.disconnect,this.onDisconnectHandler),this.provider.off(Bn.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(ar.connection_stalled,()=>{this.restartTransport().catch(r=>this.logger.error(r))});let e=await te.isOnline();te.subscribeToNetworkChange(async r=>{this.initialized&&e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(n=>this.logger.error(n))))})}onProviderDisconnect(){this.events.emit(ar.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},Ke.toMiliseconds(f8)))}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}},VZ=Object.defineProperty,R6=Object.getOwnPropertySymbols,HZ=Object.prototype.hasOwnProperty,kZ=Object.prototype.propertyIsEnumerable,B6=(t,e,r)=>e in t?VZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,L6=(t,e)=>{for(var r in e||(e={}))HZ.call(e,r)&&B6(t,r,e[r]);if(R6)for(var r of R6(e))kZ.call(e,r)&&B6(t,r,e[r]);return t},Bg=class extends Ln.IStore{constructor(e,r,n,i=hi,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=p8,this.cached=[],this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!te.isUndefined(o)?this.map.set(this.getKey(o),o):te.isProposalStruct(o)?this.map.set(o.id,o):te.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(u=>aX.default(a[u],o[u]))):this.values),this.update=async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});let u=L6(L6({},this.getData(o)),a);this.map.set(o,u),await this.persist()},this.delete=async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),await this.persist())},this.logger=Qe.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Lg=class{constructor(e,r){this.core=e,this.logger=r,this.name=E8,this.version=v8,this.events=new iX.default,this.initialized=!1,this.storagePrefix=hi,this.ignoredPayloadTypes=[te.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();let n=te.generateRandomBytes32(),i=await this.core.crypto.setSymKey(n),s=te.calcExpiry(Ke.FIVE_MINUTES),o={protocol:a8},a={topic:i,expiry:s,relay:o,active:!1},u=te.formatUri({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:o});return await this.pairings.set(i,a),await this.core.relayer.subscribe(i),this.core.expirer.set(i,s),{topic:i,uri:u}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o}=te.parseUri(n.uri),a;if(this.pairings.keys.includes(i)&&(a=this.pairings.get(i),a.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let u=te.calcExpiry(Ke.FIVE_MINUTES),c={topic:i,relay:o,expiry:u,active:!1};return await this.pairings.set(i,c),this.core.expirer.set(i,u),n.activatePairing&&await this.activate({topic:i}),this.events.emit(kl.create,c),this.core.crypto.keychain.has(i)||(await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o})),c},this.activate=async({topic:n})=>{this.isInitialized();let i=te.calcExpiry(Ke.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:u}=te.createDelayedPromise();this.events.once(te.engineEvent("pairing_ping",s),({error:c})=>{c?u(c):a()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",te.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=Sr.formatJsonRpcRequest(i,s),a=await this.core.crypto.encode(n,o),u=uu[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,u),o.id},this.sendResult=async(n,i,s)=>{let o=Sr.formatJsonRpcResult(n,s),a=await this.core.crypto.encode(i,o),u=await this.core.history.get(i,n),c=uu[u.request.method].res;await this.core.relayer.publish(i,a,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=Sr.formatJsonRpcError(n,s),a=await this.core.crypto.encode(i,o),u=await this.core.history.get(i,n),c=uu[u.request.method]?uu[u.request.method].res:uu.unregistered_method.res;await this.core.relayer.publish(i,a,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,te.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>te.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(kl.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{Sr.isJsonRpcResult(i)?this.events.emit(te.engineEvent("pairing_ping",s),{}):Sr.isJsonRpcError(i)&&this.events.emit(te.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(kl.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let a=te.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(te.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!te.isValidParams(n)){let{message:o}=te.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!te.isValidUrl(n.uri)){let{message:o}=te.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=te.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=te.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=te.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}},this.isValidPing=async n=>{if(!te.isValidParams(n)){let{message:s}=te.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!te.isValidParams(n)){let{message:s}=te.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!te.isValidString(n,!1)){let{message:i}=te.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=te.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(te.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=te.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=Qe.generateChildLogger(r,this.name),this.pairings=new Bg(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ar.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{Sr.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):Sr.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(kr.expired,async e=>{let{topic:r}=te.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(kl.expire,{topic:r}))})}},Fg=class extends Ln.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new ho.EventEmitter,this.name=A8,this.version=b8,this.cached=[],this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:te.calcExpiry(Ke.THIRTY_DAYS)};this.records.set(o.id,o),this.events.emit(rn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Sr.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(rn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(rn.deleted,s)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Qe.generateChildLogger(r,this.name)}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:Sr.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(rn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(rn.created,e=>{let r=rn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(rn.updated,e=>{let r=rn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(rn.deleted,e=>{let r=rn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{Ke.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Mg=class extends Ln.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new ho.EventEmitter,this.name=I8,this.version=_8,this.cached=[],this.initialized=!1,this.storagePrefix=hi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(kr.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(kr.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=Qe.generateChildLogger(r,this.name)}get context(){return Qe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return te.formatTopicTarget(e);if(typeof e=="number")return te.formatIdTarget(e);let{message:r}=te.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(kr.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=te.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=te.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Ke.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(kr.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Gl.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(kr.created,e=>{let r=kr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(kr.expired,e=>{let r=kr.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(kr.deleted,e=>{let r=kr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=te.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ug=class extends Ln.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=Cg,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||te.isReactNative()||!te.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=xg;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,xg)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Ke.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{if(document.getElementById(Cg))return s();window.addEventListener("message",i);let o=document.createElement("iframe");o.id=Cg,o.src=`${this.verifyUrl}/${this.projectId}`,o.style.display="none",document.body.append(o),this.iframe=o,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Ke.toMiliseconds(Ke.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||cu;return S8.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${cu}`),i=cu),i},this.logger=Qe.generateChildLogger(r,this.name),this.verifyUrl=cu,this.abortController=new AbortController,this.isDevEnv=te.isNode()&&p.default.env.IS_VITEST}get context(){return Qe.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Ke.toMiliseconds(e))}},qg=class extends Ln.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=T8,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,u=`${C8}/${this.projectId}/clients`;await uX.default(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})},this.logger=Qe.generateChildLogger(r,this.context)}},GZ=Object.defineProperty,F6=Object.getOwnPropertySymbols,jZ=Object.prototype.hasOwnProperty,QZ=Object.prototype.propertyIsEnumerable,M6=(t,e,r)=>e in t?GZ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,U6=(t,e)=>{for(var r in e||(e={}))jZ.call(e,r)&&M6(t,r,e[r]);if(F6)for(var r of F6(e))QZ.call(e,r)&&M6(t,r,e[r]);return t},Vg=class t extends Ln.ICore{constructor(e){super(e),this.protocol=Zb,this.version=Y6,this.name=kg,this.events=new ho.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||eI,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Qe.pino(Qe.getDefaultLoggerOptions({level:e?.logger||J6.logger}));this.logger=Qe.generateChildLogger(r,this.name),this.heartbeat=new Gl.HeartBeat,this.crypto=new Og(this,this.logger,e?.keychain),this.history=new Fg(this,this.logger),this.expirer=new Mg(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new sX.default(U6(U6({},X6),e?.storageOptions)),this.relayer=new Rg({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Lg(this,this.logger),this.verify=new Ug(this.projectId||"",this.logger),this.echoClient=new qg(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(g8,n),r}get context(){return Qe.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},zZ=Vg;we.CORE_CONTEXT=kg,we.CORE_DEFAULT=J6,we.CORE_PROTOCOL=Zb,we.CORE_STORAGE_OPTIONS=X6,we.CORE_STORAGE_PREFIX=hi,we.CORE_VERSION=Y6,we.CRYPTO_CLIENT_SEED=Kb,we.CRYPTO_CONTEXT=Z6,we.CRYPTO_JWT_TTL=e8,we.Core=zZ,we.Crypto=Og,we.ECHO_CONTEXT=T8,we.ECHO_URL=C8,we.EXPIRER_CONTEXT=I8,we.EXPIRER_DEFAULT_TTL=OZ,we.EXPIRER_EVENTS=kr,we.EXPIRER_STORAGE_VERSION=_8,we.EchoClient=qg,we.Expirer=Mg,we.HISTORY_CONTEXT=A8,we.HISTORY_EVENTS=rn,we.HISTORY_STORAGE_VERSION=b8,we.JsonRpcHistory=Fg,we.KEYCHAIN_CONTEXT=t8,we.KEYCHAIN_STORAGE_VERSION=r8,we.KeyChain=Ng,we.MESSAGES_CONTEXT=n8,we.MESSAGES_STORAGE_VERSION=i8,we.MessageTracker=Dg,we.PAIRING_CONTEXT=E8,we.PAIRING_DEFAULT_TTL=NZ,we.PAIRING_EVENTS=kl,we.PAIRING_RPC_OPTS=uu,we.PAIRING_STORAGE_VERSION=v8,we.PENDING_SUB_RESOLUTION_TIMEOUT=w8,we.PUBLISHER_CONTEXT=o8,we.PUBLISHER_DEFAULT_TTL=s8,we.Pairing=Lg,we.RELAYER_CONTEXT=c8,we.RELAYER_DEFAULT_LOGGER=u8,we.RELAYER_DEFAULT_PROTOCOL=a8,we.RELAYER_DEFAULT_RELAY_URL=eI,we.RELAYER_EVENTS=ar,we.RELAYER_FAILOVER_RELAY_URL=Yb,we.RELAYER_PROVIDER_EVENTS=Bn,we.RELAYER_RECONNECT_TIMEOUT=f8,we.RELAYER_SDK_VERSION=d8,we.RELAYER_STORAGE_OPTIONS=CZ,we.RELAYER_SUBSCRIBER_SUFFIX=l8,we.RELAYER_TRANSPORT_CUTOFF=h8,we.Relayer=Rg,we.STORE_STORAGE_VERSION=p8,we.SUBSCRIBER_CONTEXT=y8,we.SUBSCRIBER_DEFAULT_TTL=xZ,we.SUBSCRIBER_EVENTS=Gr,we.SUBSCRIBER_STORAGE_VERSION=m8,we.Store=Bg,we.Subscriber=Pg,we.TRUSTED_VERIFY_URLS=S8,we.VERIFY_CONTEXT=Cg,we.VERIFY_FALLBACK_SERVER=xg,we.VERIFY_SERVER=cu,we.Verify=Ug,we.WALLETCONNECT_CLIENT_ID=g8,we.default=Vg});var q8=v(Ye=>{"use strict";l();Object.defineProperty(Ye,"__esModule",{value:!0});var Mn=x8(),Gg=m1(),D8=F1(),j=Dl(),P8=ti(),tt=Xs(),wt=(Ll(),ht(rr));function WZ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var $Z=WZ(P8),sI="wc",oI=2,aI="client",$g=`${sI}@${oI}:${aI}:`,jg={name:aI,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},KZ={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire"},YZ={database:":memory:"},tI="WALLETCONNECT_DEEPLINK_CHOICE",JZ={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},XZ="history",ZZ="0.3",R8="proposal",eee=tt.THIRTY_DAYS,B8="Proposal expired",L8="session",Wl=tt.SEVEN_DAYS,F8="engine",lu={wc_sessionPropose:{req:{ttl:tt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:tt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:tt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:tt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:tt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:tt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:tt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:tt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:tt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:tt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:tt.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:tt.THIRTY_SECONDS,prompt:!1,tag:1115}}},Qg={min:tt.FIVE_MINUTES,max:tt.SEVEN_DAYS},Fn={idle:"IDLE",active:"ACTIVE"},M8="request",U8=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],tee=Object.defineProperty,ree=Object.defineProperties,nee=Object.getOwnPropertyDescriptors,N8=Object.getOwnPropertySymbols,iee=Object.prototype.hasOwnProperty,see=Object.prototype.propertyIsEnumerable,O8=(t,e,r)=>e in t?tee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Er=(t,e)=>{for(var r in e||(e={}))iee.call(e,r)&&O8(t,r,e[r]);if(N8)for(var r of N8(e))see.call(e,r)&&O8(t,r,e[r]);return t},zl=(t,e)=>ree(t,nee(e)),rI=class extends D8.IEngine{constructor(e){super(e),this.name=F8,this.events=new $Z.default,this.initialized=!1,this.ignoredPayloadTypes=[j.TYPE_1],this.requestQueue={state:Fn.idle,queue:[]},this.sessionRequestQueue={state:Fn.idle,queue:[]},this.requestQueueDelay=tt.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(lu)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},tt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=zl(Er({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:u}=n,c=i,f,d=!1;if(c&&(d=this.client.core.pairing.pairings.get(c).active),!c||!d){let{topic:M,uri:b}=await this.client.core.pairing.create();c=M,f=b}let g=await this.client.core.crypto.generateKeyPair(),m=Er({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:Mn.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:g,metadata:this.client.metadata}},a&&{sessionProperties:a}),{reject:y,resolve:A,done:O}=j.createDelayedPromise(tt.FIVE_MINUTES,B8);if(this.events.once(j.engineEvent("session_connect"),async({error:M,session:b})=>{if(M)y(M);else if(b){b.self.publicKey=g;let S=zl(Er({},b),{requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces});await this.client.session.set(b.topic,S),await this.setExpiry(b.topic,b.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:b.peer.metadata}),A(S)}}),!c){let{message:M}=j.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(M)}let R=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:m}),q=j.calcExpiry(tt.FIVE_MINUTES);return await this.setProposal(R,Er({id:R,expiry:q},m)),{uri:f,approval:O}},this.pair=async r=>(await this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{await this.isInitialized(),await this.isValidApprove(r);let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o}=r,a=this.client.proposal.get(n),{pairingTopic:u,proposer:c,requiredNamespaces:f,optionalNamespaces:d}=a;u=u||"",j.isValidObject(f)||(f=j.getRequiredNamespacesFromNamespaces(s,"approve()"));let g=await this.client.core.crypto.generateKeyPair(),m=c.publicKey,y=await this.client.core.crypto.generateSharedKey(g,m);u&&n&&(await this.client.core.pairing.updateMetadata({topic:u,metadata:c.metadata}),await this.sendResult({id:n,topic:u,result:{relay:{protocol:i??"irn"},responderPublicKey:g}}),await this.client.proposal.delete(n,j.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:u}));let A=Er({relay:{protocol:i??"irn"},namespaces:s,requiredNamespaces:f,optionalNamespaces:d,pairingTopic:u,controller:{publicKey:g,metadata:this.client.metadata},expiry:j.calcExpiry(Wl)},o&&{sessionProperties:o});await this.client.core.relayer.subscribe(y),await this.sendRequest({topic:y,method:"wc_sessionSettle",params:A,throwOnFailedPublish:!0});let O=zl(Er({},A),{topic:y,pairingTopic:u,acknowledged:!1,self:A.controller,peer:{publicKey:c.publicKey,metadata:c.metadata},controller:g});return await this.client.session.set(y,O),await this.setExpiry(y,j.calcExpiry(Wl)),{topic:y,acknowledged:()=>new Promise(R=>setTimeout(()=>R(this.client.session.get(y)),500))}},this.reject=async r=>{await this.isInitialized(),await this.isValidReject(r);let{id:n,reason:i}=r,{pairingTopic:s}=this.client.proposal.get(n);s&&(await this.sendError(n,s,i),await this.client.proposal.delete(n,j.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized(),await this.isValidUpdate(r);let{topic:n,namespaces:i}=r,s=await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:o,resolve:a,reject:u}=j.createDelayedPromise();return this.events.once(j.engineEvent("session_update",s),({error:c})=>{c?u(c):a()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:o}},this.extend=async r=>{await this.isInitialized(),await this.isValidExtend(r);let{topic:n}=r,i=await this.sendRequest({topic:n,method:"wc_sessionExtend",params:{}}),{done:s,resolve:o,reject:a}=j.createDelayedPromise();return this.events.once(j.engineEvent("session_extend",i),({error:u})=>{u?a(u):o()}),await this.setExpiry(n,j.calcExpiry(Wl)),{acknowledged:s}},this.request=async r=>{await this.isInitialized(),await this.isValidRequest(r);let{chainId:n,request:i,topic:s,expiry:o}=r,a=wt.payloadId(),{done:u,resolve:c,reject:f}=j.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(j.engineEvent("session_request",a),({error:d,result:g})=>{d?f(d):c(g)}),await Promise.all([new Promise(async d=>{await this.sendRequest({clientRpcId:a,topic:s,method:"wc_sessionRequest",params:{request:i,chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(g=>f(g)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),d()}),new Promise(async d=>{let g=await j.getDeepLink(this.client.core.storage,tI);j.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:g}),d()}),u()]).then(d=>d[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;wt.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):wt.isJsonRpcError(i)&&await this.sendError(s,n,i.error),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized(),await this.isValidPing(r);let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=await this.sendRequest({topic:n,method:"wc_sessionPing",params:{}}),{done:s,resolve:o,reject:a}=j.createDelayedPromise();this.events.once(j.engineEvent("session_ping",i),({error:u})=>{u?a(u):o()}),await s()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r;await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s}})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest({topic:n,method:"wc_sessionDelete",params:j.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>j.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{let{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,j.getSdkError("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(tI).catch(s=>this.client.logger.warn(s)),this.getPendingSessionRequests().forEach(s=>{s.topic===r&&this.deletePendingSessionRequest(s.id,j.getSdkError("USER_DISCONNECTED"))})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,j.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=Fn.idle)},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{let n=lu.wc_sessionRequest.req.ttl,{id:i,topic:s,params:o,verifyContext:a}=r;await this.client.pendingRequest.set(i,{id:i,topic:s,params:o,verifyContext:a}),n&&this.client.core.expirer.set(i,j.calcExpiry(n))},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:u,throwOnFailedPublish:c}=r,f=wt.formatJsonRpcRequest(i,s,u);if(j.isBrowser()&&U8.includes(i)){let m=j.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:m})}let d=await this.client.core.crypto.encode(n,f),g=lu[i].req;return o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(n,f),c?(g.internal=zl(Er({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,g)):this.client.core.relayer.publish(n,d,g).catch(m=>this.client.logger.error(m)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o}=r,a=wt.formatJsonRpcResult(n,s),u=await this.client.core.crypto.encode(i,a),c=await this.client.core.history.get(i,n),f=lu[c.request.method].res;o?(f.internal=zl(Er({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,f)):this.client.core.relayer.publish(i,u,f).catch(d=>this.client.logger.error(d)),await this.client.core.history.resolve(a)},this.sendError=async(r,n,i)=>{let s=wt.formatJsonRpcError(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),u=lu[a.request.method].res;this.client.core.relayer.publish(n,o,u),await this.client.core.history.resolve(s)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{j.isExpired(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{j.isExpired(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Fn.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Fn.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Fn.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=j.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(Er({},n.params));let o=j.calcExpiry(tt.FIVE_MINUTES),a=Er({id:s,pairingTopic:r,expiry:o},i);await this.setProposal(s,a);let u=j.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(u,a.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:a,verifyContext:c})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(wt.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let a=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});let u=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let c=await this.client.core.crypto.generateSharedKey(a,u);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else wt.isJsonRpcError(n)&&(await this.client.proposal.delete(i,j.getSdkError("USER_DISCONNECTED")),this.events.emit(j.engineEvent("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:a,expiry:u,namespaces:c,requiredNamespaces:f,optionalNamespaces:d,sessionProperties:g,pairingTopic:m}=n.params,y=Er({topic:r,relay:o,expiry:u,namespaces:c,acknowledged:!0,pairingTopic:m,requiredNamespaces:f,optionalNamespaces:d,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},g&&{sessionProperties:g});await this.sendResult({id:n.id,topic:r,result:!0}),this.events.emit(j.engineEvent("session_connect"),{session:y}),this.cleanupDuplicatePairings(y)}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(j.engineEvent("session_approve",i),{})):wt.isJsonRpcError(n)&&(await this.client.session.delete(r,j.getSdkError("USER_DISCONNECTED")),this.events.emit(j.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,a=j.MemoryStore.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidUpdate(Er({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0}),this.client.events.emit("session_update",{id:s,topic:r,params:i}),j.MemoryStore.set(o,s)}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_update",i),{}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,j.calcExpiry(Wl)),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_extend",i),{}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n;setTimeout(()=>{wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_ping",i),{}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(Mn.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession(r))})}),this.sendResult({id:i,topic:r,result:!0})]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidRequest(Er({topic:r},s));let o=j.hashMessage(JSON.stringify(wt.formatJsonRpcRequest("wc_sessionRequest",s,i))),a=this.client.session.get(r),u=await this.getVerifyContext(o,a.peer.metadata),c={id:i,topic:r,params:s,verifyContext:u};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n;wt.isJsonRpcResult(n)?this.events.emit(j.engineEvent("session_request",i),{result:n.result}):wt.isJsonRpcError(n)&&this.events.emit(j.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,a=j.MemoryStore.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Er({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),j.MemoryStore.set(o,i)}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Fn.idle,this.processSessionRequestQueue()},tt.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Fn.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Fn.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,wt.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!j.isValidParams(r)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if(j.isUndefined(n)||await this.isValidPairingTopic(n),!j.isValidRelays(a,!0)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(u)}!j.isUndefined(i)&&j.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!j.isUndefined(s)&&j.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),j.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=j.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!j.isValidParams(r))throw new Error(j.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;await this.isValidProposalId(n);let a=this.client.proposal.get(n),u=j.isValidNamespaces(i,"approve()");if(u)throw new Error(u.message);let c=j.isConformingNamespaces(a.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!j.isValidString(s,!0)){let{message:f}=j.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}j.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!j.isValidParams(r)){let{message:s}=j.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(await this.isValidProposalId(n),!j.isValidErrorReason(i)){let{message:s}=j.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!j.isValidParams(r)){let{message:c}=j.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!j.isValidRelay(n)){let{message:c}=j.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let a=j.isValidController(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);let u=j.isValidNamespaces(s,"onSessionSettleRequest()");if(u)throw new Error(u.message);if(j.isExpired(o)){let{message:c}=j.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!j.isValidParams(r)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(u)}let{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=j.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let a=j.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!j.isValidParams(r)){let{message:i}=j.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!j.isValidParams(r)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(u)}let{topic:n,request:i,chainId:s,expiry:o}=r;await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!j.isValidNamespacesChainId(a,s)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(u)}if(!j.isValidRequest(i)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(u)}if(!j.isValidNamespacesRequest(a,s,i.method)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(u)}if(o&&!j.isValidRequestExpiry(o,Qg)){let{message:u}=j.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Qg.min} and ${Qg.max}`);throw new Error(u)}},this.isValidRespond=async r=>{var n;if(!j.isValidParams(r)){let{message:o}=j.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!j.isValidResponse(s)){let{message:o}=j.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!j.isValidParams(r)){let{message:i}=j.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!j.isValidParams(r)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!j.isValidNamespacesChainId(o,s)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!j.isValidEvent(i)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!j.isValidNamespacesEvent(o,s,i.name)){let{message:a}=j.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!j.isValidParams(r)){let{message:i}=j.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||Mn.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!j.isValidString(i,!1)){let{message:s}=j.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})}}async isInitialized(){if(!this.initialized){let{message:e}=j.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mn.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;let i=await this.client.core.crypto.decode(r,n);try{wt.isJsonRpcRequest(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):wt.isJsonRpcResponse(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.client.core.history.delete(r,i.id)):this.onRelayEventUnknownPayload({topic:r,payload:i})}catch(s){this.client.logger.error(s)}})}registerExpirerEvents(){this.client.core.expirer.on(Mn.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=j.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,j.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Mn.PAIRING_EVENTS.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!j.isValidString(e,!1)){let{message:r}=j.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(j.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=j.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!j.isValidString(e,!1)){let{message:r}=j.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(j.isExpired(this.client.session.get(e).expiry)){await this.deleteSession(e);let{message:r}=j.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(j.isValidString(e,!1)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=j.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!j.isValidId(e)){let{message:r}=j.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=j.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(j.isExpired(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);let{message:r}=j.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},nI=class extends Mn.Store{constructor(e,r){super(e,r,R8,$g),this.core=e,this.logger=r}},zg=class extends Mn.Store{constructor(e,r){super(e,r,L8,$g),this.core=e,this.logger=r}},iI=class extends Mn.Store{constructor(e,r){super(e,r,M8,$g,n=>n.id),this.core=e,this.logger=r}},Wg=class t extends D8.ISignClient{constructor(e){super(e),this.protocol=sI,this.version=oI,this.name=jg.name,this.events=new P8.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||jg.name,this.metadata=e?.metadata||j.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gg.pino(Gg.getDefaultLoggerOptions({level:e?.logger||jg.logger}));this.core=e?.core||new Mn.Core(e),this.logger=Gg.generateChildLogger(r,this.name),this.session=new zg(this.core,this.logger),this.proposal=new nI(this.core,this.logger),this.pendingRequest=new iI(this.core,this.logger),this.engine=new rI(this)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Gg.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},oee=zg,aee=Wg;Ye.ENGINE_CONTEXT=F8,Ye.ENGINE_QUEUE_STATES=Fn,Ye.ENGINE_RPC_OPTS=lu,Ye.HISTORY_CONTEXT=XZ,Ye.HISTORY_EVENTS=JZ,Ye.HISTORY_STORAGE_VERSION=ZZ,Ye.METHODS_TO_VERIFY=U8,Ye.PROPOSAL_CONTEXT=R8,Ye.PROPOSAL_EXPIRY=eee,Ye.PROPOSAL_EXPIRY_MESSAGE=B8,Ye.REQUEST_CONTEXT=M8,Ye.SESSION_CONTEXT=L8,Ye.SESSION_EXPIRY=Wl,Ye.SESSION_REQUEST_EXPIRY_BOUNDARIES=Qg,Ye.SIGN_CLIENT_CONTEXT=aI,Ye.SIGN_CLIENT_DEFAULT=jg,Ye.SIGN_CLIENT_EVENTS=KZ,Ye.SIGN_CLIENT_PROTOCOL=sI,Ye.SIGN_CLIENT_STORAGE_OPTIONS=YZ,Ye.SIGN_CLIENT_STORAGE_PREFIX=$g,Ye.SIGN_CLIENT_VERSION=oI,Ye.SessionStore=oee,Ye.SignClient=aee,Ye.WALLETCONNECT_DEEPLINK_CHOICE=tI,Ye.default=Wg});var Kg=v(os=>{"use strict";l();Object.defineProperty(os,"__esModule",{value:!0});os.OptionalOperation=os.Operation=void 0;var uee;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(uee=os.Operation||(os.Operation={}));var cee;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(cee=os.OptionalOperation||(os.OptionalOperation={}))});var uI=v(Un=>{"use strict";l();Object.defineProperty(Un,"__esModule",{value:!0});Un.WALLETCONNECT_SIGN_LOGIN_DELAY=Un.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Un.WALLETCONNECT_MULTIVERSX_METHODS=Un.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var V8=Kg();Un.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";Un.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(V8.Operation);Un.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(V8.OptionalOperation);Un.WALLETCONNECT_SIGN_LOGIN_DELAY=200});var fI=v(nn=>{"use strict";l();Object.defineProperty(nn,"__esModule",{value:!0});nn.WalletConnectV2ProviderErrorMessagesEnum=nn.ErrBadAddress=nn.ErrNotImplemented=nn.Err=void 0;var $l=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};nn.Err=$l;var cI=class extends $l{constructor(){super("Method not yet implemented")}};nn.ErrNotImplemented=cI;var lI=class extends $l{constructor(e,r){super(`Bad address: ${e}`,r)}};nn.ErrBadAddress=lI;var lee;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(lee=nn.WalletConnectV2ProviderErrorMessagesEnum||(nn.WalletConnectV2ProviderErrorMessagesEnum={}))});var hI=v(Yg=>{"use strict";l();Object.defineProperty(Yg,"__esModule",{value:!0});Yg.Logger=void 0;var dI=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};Yg.Logger=dI});var H8=v(()=>{"use strict";l();global.Buffer||(global.Buffer=qs().Buffer)});var G8=v(k8=>{"use strict";l();Object.defineProperty(k8,"__esModule",{value:!0})});var Q8=v(j8=>{"use strict";l();Object.defineProperty(j8,"__esModule",{value:!0})});var z8=v(fu=>{"use strict";l();var fee=fu&&fu.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(fu,"__esModule",{value:!0});fu.RelayedTransactionV1Builder=void 0;var dee=fee(Yt()),pI=pt(),hee=Le(),pee=Yr(),gee=Yn(),gI=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new hee.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${h.Buffer.from(e).toString("hex")}`,n=new gee.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new pee.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new pI.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new pI.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:new dee.default(this.innerTransaction.getValue().toString(),10).toNumber(),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:h.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new pI.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?h.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?h.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return JSON.stringify(e)}};fu.RelayedTransactionV1Builder=gI});var W8=v(Jg=>{"use strict";l();Object.defineProperty(Jg,"__esModule",{value:!0});Jg.Code=void 0;var yee=gE(),mee=32,yI=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return h.Buffer.from(this.hex,"hex")}computeHash(){let e=yee(mee).update(this.valueOf()).digest();return h.Buffer.from(e)}};Jg.Code=yI});var J8=v(hu=>{"use strict";l();Object.defineProperty(hu,"__esModule",{value:!0});hu.bech32m=hu.bech32=void 0;var Xg="qpzry9x8gf2tvdw0s3jn54khce6mua7l",K8={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function $8(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=du(e)^n>>5}e=du(e);for(let r=0;r=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<=e)return"Excess padding";if(i<u)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=$8(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=du(c)^g,f+=Xg.charAt(g)}for(let d=0;d<6;++d)c=du(c);c^=e;for(let d=0;d<6;++d){let g=c>>(5-d)*5&31;f+=Xg.charAt(g)}return f}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";let u=o.toLowerCase(),c=o.toUpperCase();if(o!==u&&o!==c)return"Mixed-case string "+o;o=u;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),g=o.slice(f+1);if(g.length<6)return"Data too short";let m=$8(d);if(typeof m=="string")return m;let y=[];for(let A=0;A=g.length)&&y.push(R)}return m!==e?"Invalid checksum for "+o:{prefix:d,words:y}}function i(o,a){let u=n(o,a);if(typeof u=="object")return u}function s(o,a){let u=n(o,a);if(typeof u=="object")return u;throw new Error(u)}return{decodeUnsafe:i,decode:s,encode:r,toWords:wee,fromWordsUnsafe:Eee,fromWords:vee}}hu.bech32=Y8("bech32");hu.bech32m=Y8("bech32m")});var Z8=v(jr=>{"use strict";l();Object.defineProperty(jr,"__esModule",{value:!0});jr.TokenTransferProperties=jr.TransactionMetadataTransfer=jr.TransactionMetadata=jr.TransactionToDecode=jr.TransactionDecoder=void 0;var X8=J8(),wI=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new po;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new Zg;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new po;s.transfers||(s.transfers=[]);let o=2;for(let a=0;ao&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),a=new po;return a.sender=e.sender,a.receiver=o,a.value=s,r.length>4&&(a.functionName=this.hexToString(r[4]),a.functionArgs=r.slice(5)),a.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],a}base64Encode(e){return h.Buffer.from(e).toString("base64")}base64Decode(e){return h.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new po;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=h.Buffer.from(e,"hex"),n=X8.bech32.toWords(r);return X8.bech32.encode("erd",n)}isAddressValid(e){return h.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return h.Buffer.from(e,"base64").toString("hex")}hexToString(e){return h.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};jr.TransactionDecoder=wI;var Zg=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};jr.TransactionToDecode=Zg;var po=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};jr.TransactionMetadata=po;var EI=class{constructor(){this.value=BigInt(0)}};jr.TransactionMetadataTransfer=EI;var vI=class{};jr.TokenTransferProperties=vI});var AI=v(ey=>{"use strict";l();Object.defineProperty(ey,"__esModule",{value:!0});ey.ReturnCode=void 0;var ze=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};ey.ReturnCode=ze;ze.None=new ze("");ze.Ok=new ze("ok");ze.FunctionNotFound=new ze("function not found");ze.FunctionWrongSignature=new ze("wrong signature for function");ze.ContractNotFound=new ze("contract not found");ze.UserError=new ze("user error");ze.OutOfGas=new ze("out of gas");ze.AccountCollision=new ze("account collision");ze.OutOfFunds=new ze("out of funds");ze.CallStackOverFlow=new ze("call stack overflow");ze.ContractInvalid=new ze("contract invalid");ze.ExecutionFailed=new ze("execution failed");ze.Unknown=new ze("unknown")});var rL=v(ty=>{"use strict";l();Object.defineProperty(ty,"__esModule",{value:!0});ty.ResultsParser=void 0;var Aee=Z8(),eL=pt(),tL=Le(),as=pa(),bee=na(),pu=AI(),gu;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(gu||(gu={}));var bI;(function(t){t.TooMuchGas="@too much gas provided for processing"})(bI||(bI={}));var Iee={argsSerializer:new bee.ArgSerializer},II=class{constructor(e){e=Object.assign(Object.assign({},Iee),e),this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new pu.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new pu.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e),i=this.argsSerializer.buffersToValues(n.values,r.output);return{returnCode:n.returnCode,returnMessage:n.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return as.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return as.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return as.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return as.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return as.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return as.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return as.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return as.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new tL.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new Aee.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:pu.ReturnCode.None,returnMessage:pu.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:pu.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(gu.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.getLastTopic(),o=s?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(gu.OnWriteLog,a=>a.findFirstOrNoneTopic(u=>u.toString().startsWith(bI.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.getLastTopic(),o=s?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new eL.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(gu.OnWriteLog,u=>u.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),a=s.toString();return{returnCode:s,returnMessage:a,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new eL.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(gu.OnWriteLog,o=>{var a;let u=o.address.bech32()==e.sender.bech32(),c=((a=o.topics[0])===null||a===void 0?void 0:a.hex())==n.hex();return u&&c});if(s){let{returnCode:o,returnDataParts:a}=this.sliceDataFieldInParts(s.data),u=o.toString();return{returnCode:o,returnMessage:u,values:a}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||h.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new tL.ErrCannotParseContractResults("no return code");return{returnCode:pu.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){var n,i;let s={},o=e.topics.map(m=>h.Buffer.from(m.valueOf())).slice(1),a=((n=e.dataPayload)===null||n===void 0?void 0:n.valueOf())||h.Buffer.from([]),u=((i=e.additionalData)===null||i===void 0?void 0:i.map(m=>h.Buffer.from(m.valueOf())))||[];u.length==0&&a.length>0&&u.push(h.Buffer.from(a));let c=r.inputs.filter(m=>m.indexed),f=this.argsSerializer.buffersToValues(o,c);for(let m=0;m!m.indexed),g=this.argsSerializer.buffersToValues(u,d);for(let m=0;m{"use strict";l();var _ee=_t&&_t.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ur=_t&&_t.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_ee(e,t,r)};Object.defineProperty(_t,"__esModule",{value:!0});ur(na(),_t);ur(W8(),_t);ur(Bw(),_t);ur(NE(),_t);ur(qc(),_t);ur(UE(),_t);ur(RE(),_t);ur(Rv(),_t);ur(HE(),_t);ur(Vc(),_t);ur(rL(),_t);ur(AI(),_t);ur(Dv(),_t);ur($E(),_t);ur(xt(),_t)});var iL=v(ry=>{"use strict";l();Object.defineProperty(ry,"__esModule",{value:!0});ry.RelayedTransactionV2Builder=void 0;var nL=Le(),Kl=_I(),See=Yr(),Tee=Yn(),SI=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new nL.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new nL.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new Kl.ArgSerializer().valuesToString([new Kl.AddressValue(this.innerTransaction.getReceiver()),new Kl.U64Value(this.innerTransaction.getNonce().valueOf()),new Kl.BytesValue(this.innerTransaction.getData().valueOf()),new Kl.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Tee.TransactionPayload(r),i=new See.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};ry.RelayedTransactionV2Builder=SI});var CI=v(lt=>{"use strict";l();var Cee=lt&<.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xee=lt&<.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sL=lt&<.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cee(e,t,r);return xee(e,t),e},Nee=lt&<.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lt,"__esModule",{value:!0});lt.addressToHex=lt.bufferToHex=lt.utf8ToHex=lt.bigIntToHex=lt.bigIntToBuffer=lt.bufferToBigInt=lt.stringToBuffer=void 0;var Oee=Nee(Yt()),Dee=pt(),TI=sL(Tc()),oL=sL(Md());function Pee(t){return h.Buffer.from(t)}lt.stringToBuffer=Pee;function Ree(t){return t.length==0?new Oee.default(0):TI.bufferToBigInt(t)}lt.bufferToBigInt=Ree;function Bee(t){return t==0?h.Buffer.from([]):TI.bigIntToBuffer(t)}lt.bigIntToBuffer=Bee;function Lee(t){return t==0?"":TI.getHexMagnitudeOfBigInt(t)}lt.bigIntToHex=Lee;function Fee(t){let e=h.Buffer.from(t).toString("hex");return oL.zeroPadStringIfOddLength(e)}lt.utf8ToHex=Fee;function Mee(t){let e=t.toString("hex");return oL.zeroPadStringIfOddLength(e)}lt.bufferToHex=Mee;function Uee(t){return Dee.Address.fromBech32(t.toString()).pubkey().toString("hex")}lt.addressToHex=Uee});var uL=v(ny=>{"use strict";l();Object.defineProperty(ny,"__esModule",{value:!0});ny.TokenOperationsFactory=void 0;var xI=Ns(),qee=pa(),aL=xc(),Vee=Yr(),Hee=Yn(),ne=CI(),NI=class{constructor(e){this.config=e,this.trueAsHex=ne.utf8ToHex("true"),this.falseAsHex=ne.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.bigIntToHex(e.initialSupply),ne.bigIntToHex(e.numDecimals),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){qee.Logger.info(` -========== -IMPORTANT! -========== -You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.bigIntToHex(e.numDecimals),ne.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ne.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ne.utf8ToHex(e.tokenName),ne.utf8ToHex(e.tokenTicker),ne.utf8ToHex(e.tokenType),ne.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user),...e.addRoleLocalMint?[ne.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ne.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user),...e.addRoleNFTCreate?[ne.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ne.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ne.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ne.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user),...e.addRoleNFTCreate?[ne.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ne.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ne.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ne.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ne.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.initialQuantity),ne.utf8ToHex(e.name),ne.bigIntToHex(e.royalties),ne.utf8ToHex(e.hash),ne.bufferToHex(e.attributes),...e.uris.map(ne.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ne.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ne.utf8ToHex(e.tokenIdentifier),ne.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.tokenNonce),ne.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.tokenNonce),ne.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ne.utf8ToHex(e.tokenIdentifier),ne.bigIntToHex(e.tokenNonce),ne.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:a,dataParts:u}){let c=this.buildTransactionPayload(u),f=o||this.computeGasLimit(c,a),d=new aL.TransactionVersion(xI.TRANSACTION_VERSION_DEFAULT),g=new aL.TransactionOptions(xI.TRANSACTION_OPTIONS_DEFAULT);return new Vee.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:g})}buildTransactionPayload(e){let r=e.join(xI.ARGUMENTS_SEPARATOR);return new Hee.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};ny.TokenOperationsFactory=NI});var cL=v(iy=>{"use strict";l();Object.defineProperty(iy,"__esModule",{value:!0});iy.TokenOperationsFactoryConfig=void 0;var kee=pt(),OI=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=kee.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};iy.TokenOperationsFactoryConfig=OI});var fL=v(sy=>{"use strict";l();Object.defineProperty(sy,"__esModule",{value:!0});sy.TokenOperationsOutcomeParser=void 0;var Gee=pt(),DI=Le(),lL=CI(),PI=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){var r;this.ensureNoError(e);let n=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),i=this.extractTokenIdentifier(n),s=this.extractNonce(n),o=(r=n.topics[3])===null||r===void 0?void 0:r.valueOf();return{tokenIdentifier:i,nonce:s,attributes:o}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){var r;for(let n of e.logs.events)if(n.identifier=="signalError"){let i=h.Buffer.from(n.data.substring(1),"hex").toString(),s=(r=n.topics[1])===null||r===void 0?void 0:r.valueOf().toString();throw new DI.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${s} (${i})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new DI.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new DI.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){var r;return(r=e.topics[0])===null||r===void 0?void 0:r.valueOf().toString()}extractNonce(e){var r;return lL.bufferToBigInt((r=e.topics[1])===null||r===void 0?void 0:r.valueOf()).toFixed(0)}extractAmount(e){var r;return lL.bufferToBigInt((r=e.topics[2])===null||r===void 0?void 0:r.valueOf()).toFixed(0)}extractAddress(e){var r;return Gee.Address.fromBuffer((r=e.topics[3])===null||r===void 0?void 0:r.valueOf()).toString()}};sy.TokenOperationsOutcomeParser=PI});var dL=v(pi=>{"use strict";l();var jee=pi&&pi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RI=pi&&pi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&jee(e,t,r)};Object.defineProperty(pi,"__esModule",{value:!0});RI(uL(),pi);RI(cL(),pi);RI(fL(),pi)});var hL=v(rt=>{"use strict";l();var Qee=rt&&rt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dt=rt&&rt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Qee(e,t,r)};Object.defineProperty(rt,"__esModule",{value:!0});H8();Dt(ha(),rt);Dt(pt(),rt);Dt(TE(),rt);Dt(Le(),rt);Dt(bE(),rt);Dt(G8(),rt);Dt(Q8(),rt);Dt(pa(),rt);Dt(xc(),rt);Dt(z8(),rt);Dt(iL(),rt);Dt(Wh(),rt);Dt(_I(),rt);Dt(dL(),rt);Dt(Vm(),rt);Dt(Yr(),rt);Dt(Yn(),rt);Dt(Ih(),rt);Dt(vE(),rt);Dt(br(),rt)});var EL=v(Pt=>{"use strict";l();var zee=Pt&&Pt.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.sleep=Pt.getMetadata=Pt.applyTransactionSignature=Pt.getAddressFromSession=Pt.addressIsValid=Pt.getConnectionParams=Pt.getCurrentTopic=Pt.getCurrentSession=void 0;var yL=hL(),pL=Rc(),Wee=Dl(),oy=uI(),gi=fI(),BI=hI(),gL=Kg();function mL(t,e){if(!e)throw new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find(wL(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw BI.Logger.error(gi.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}Pt.getCurrentSession=mL;function $ee(t,e){if(!e)throw new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=mL(t,e);if(!r?.topic)throw new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}Pt.getCurrentTopic=$ee;function wL(t,e){var r,n,i;let s=[...oy.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(gL.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(gL.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${oy.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],a=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[oy.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:a}}}}Pt.getConnectionParams=wL;function Kee(t){try{return!yL.Address.fromBech32(t).isEmpty()}catch{return!1}}Pt.addressIsValid=Kee;function Yee(t){let e=t.namespaces[oy.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}Pt.getAddressFromSession=Yee;function Jee({transaction:t,response:e}){if(!e)throw BI.Logger.error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,a=t.getGuardian().bech32();if(a&&a!==o)throw BI.Logger.error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(gi.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(yL.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new pL.Signature(r)),n&&t.applyGuardianSignature(new pL.Signature(n)),t}Pt.applyTransactionSignature=Jee;function Xee(t){if(t)return Object.assign(Object.assign({},t),{url:Wee.getAppMetadata().url})}Pt.getMetadata=Xee;function Zee(t){return zee(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}Pt.sleep=Zee});var Yl=v(vr=>{"use strict";l();var St=vr&&vr.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})},ete=vr&&vr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vr,"__esModule",{value:!0});vr.WalletConnectV2Provider=vr.OptionalOperation=vr.Operation=vr.WalletConnectV2ProviderErrorMessagesEnum=void 0;var tte=Rc(),rte=ete(q8()),LI=Dl(),go=uI(),me=fI();Object.defineProperty(vr,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return me.WalletConnectV2ProviderErrorMessagesEnum}});var Fe=hI(),us=Kg();Object.defineProperty(vr,"Operation",{enumerable:!0,get:function(){return us.Operation}});Object.defineProperty(vr,"OptionalOperation",{enumerable:!0,get:function(){return us.OptionalOperation}});var Wt=EL(),FI=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return St(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:Wt.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield rte.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=Wt.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Fe.Logger.error(e?.topic?me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:me.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return St(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield Wt.sleep(go.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=Wt.getAddressFromSession(n),o=n.namespaces[go.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(us.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?us.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:us.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:a}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!a)throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:a})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||Wt.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:LI.getSdkError("USER_DISCONNECTED")});else{let r=Wt.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:LI.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:{method:us.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new tte.Signature(n))}catch{throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:{method:us.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return Wt.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:{method:us.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];Wt.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${go.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:Wt.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=Wt.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return St(this,void 0,void 0,function*(){return e?Wt.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Fe.Logger.error(`${me.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return St(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=Wt.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return St(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&Wt.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return St(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:a})=>{var u;if(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)return;let{namespaces:c}=a,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>St(this,void 0,void 0,function*(){var a;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)&&(Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>St(this,void 0,void 0,function*(){var a;!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o||(Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return St(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(me.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=Wt.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,a,u,c;return St(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!LI.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(u=(a=this.walletConnector.core)===null||a===void 0?void 0:a.relayer)===null||u===void 0?void 0:u.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Fe.Logger.error(me.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};vr.WalletConnectV2Provider=FI});var AL=v((dme,vL)=>{"use strict";l();vL.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var _L=v((pme,IL)=>{"use strict";l();var bL=typeof Symbol<"u"&&Symbol,nte=AL();IL.exports=function(){return typeof bL!="function"||typeof Symbol!="function"||typeof bL("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:nte()}});var CL=v((yme,TL)=>{"use strict";l();var SL={foo:{}},ite=Object;TL.exports=function(){return{__proto__:SL}.foo===SL.foo&&!({__proto__:null}instanceof ite)}});var OL=v((wme,NL)=>{"use strict";l();var ste="Function.prototype.bind called on incompatible ",ote=Object.prototype.toString,ate=Math.max,ute="[object Function]",xL=function(e,r){for(var n=[],i=0;i{"use strict";l();var fte=OL();DL.exports=Function.prototype.bind||fte});var RL=v((bme,PL)=>{"use strict";l();var dte=Function.prototype.call,hte=Object.prototype.hasOwnProperty,pte=ay();PL.exports=pte.call(dte,hte)});var cs=v((_me,UL)=>{"use strict";l();var Re,Eu=SyntaxError,ML=Function,wu=TypeError,MI=function(t){try{return ML('"use strict"; return ('+t+").constructor;")()}catch{}},yo=Object.getOwnPropertyDescriptor;if(yo)try{yo({},"")}catch{yo=null}var UI=function(){throw new wu},gte=yo?function(){try{return arguments.callee,UI}catch{try{return yo(arguments,"callee").get}catch{return UI}}}():UI,yu=_L()(),yte=CL()(),Gt=Object.getPrototypeOf||(yte?function(t){return t.__proto__}:null),mu={},mte=typeof Uint8Array>"u"||!Gt?Re:Gt(Uint8Array),mo={"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":yu&&Gt?Gt([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":mu,"%AsyncGenerator%":mu,"%AsyncGeneratorFunction%":mu,"%AsyncIteratorPrototype%":mu,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":ML,"%GeneratorFunction%":mu,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":yu&&Gt?Gt(Gt([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!yu||!Gt?Re:Gt(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!yu||!Gt?Re:Gt(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":yu&&Gt?Gt(""[Symbol.iterator]()):Re,"%Symbol%":yu?Symbol:Re,"%SyntaxError%":Eu,"%ThrowTypeError%":gte,"%TypedArray%":mte,"%TypeError%":wu,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Gt)try{null.error}catch(t){BL=Gt(Gt(t)),mo["%Error.prototype%"]=BL}var BL,wte=function t(e){var r;if(e==="%AsyncFunction%")r=MI("async function () {}");else if(e==="%GeneratorFunction%")r=MI("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=MI("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Gt&&(r=Gt(i.prototype))}return mo[e]=r,r},LL={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Jl=ay(),uy=RL(),Ete=Jl.call(Function.call,Array.prototype.concat),vte=Jl.call(Function.apply,Array.prototype.splice),FL=Jl.call(Function.call,String.prototype.replace),cy=Jl.call(Function.call,String.prototype.slice),Ate=Jl.call(Function.call,RegExp.prototype.exec),bte=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Ite=/\\(\\)?/g,_te=function(e){var r=cy(e,0,1),n=cy(e,-1);if(r==="%"&&n!=="%")throw new Eu("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Eu("invalid intrinsic syntax, expected opening `%`");var i=[];return FL(e,bte,function(s,o,a,u){i[i.length]=a?FL(u,Ite,"$1"):o||s}),i},Ste=function(e,r){var n=e,i;if(uy(LL,n)&&(i=LL[n],n="%"+i[0]+"%"),uy(mo,n)){var s=mo[n];if(s===mu&&(s=wte(n)),typeof s>"u"&&!r)throw new wu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Eu("intrinsic "+e+" does not exist!")};UL.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new wu("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new wu('"allowMissing" argument must be a boolean');if(Ate(/^%?[^%]*%?$/,e)===null)throw new Eu("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=_te(e),i=n.length>0?n[0]:"",s=Ste("%"+i+"%",r),o=s.name,a=s.value,u=!1,c=s.alias;c&&(i=c[0],vte(n,Ete([0,1],c)));for(var f=1,d=!0;f=n.length){var A=yo(a,g);d=!!A,d&&"get"in A&&!("originalValue"in A.get)?a=A.get:a=a[g]}else d=uy(a,g),a=a[g];d&&!u&&(mo[o]=a)}}return a}});var HI=v((Tme,qL)=>{"use strict";l();var Tte=cs(),qI=Tte("%Object.defineProperty%",!0),VI=function(){if(qI)try{return qI({},"a",{value:1}),!0}catch{return!1}return!1};VI.hasArrayLengthDefineBug=function(){if(!VI())return null;try{return qI([],"length",{value:1}).length!==1}catch{return!0}};qL.exports=VI});var kI=v((xme,VL)=>{"use strict";l();var Cte=cs(),ly=Cte("%Object.getOwnPropertyDescriptor%",!0);if(ly)try{ly([],"length")}catch{ly=null}VL.exports=ly});var GL=v((Ome,kL)=>{"use strict";l();var xte=HI()(),GI=cs(),Xl=xte&&GI("%Object.defineProperty%",!0);if(Xl)try{Xl({},"a",{value:1})}catch{Xl=!1}var Nte=GI("%SyntaxError%"),vu=GI("%TypeError%"),HL=kI();kL.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new vu("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new vu("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new vu("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new vu("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new vu("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new vu("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,u=!!HL&&HL(e,r);if(Xl)Xl(e,r,{configurable:o===null&&u?u.configurable:!o,enumerable:i===null&&u?u.enumerable:!i,value:n,writable:s===null&&u?u.writable:!s});else if(a||!i&&!s&&!o)e[r]=n;else throw new Nte("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var KL=v((Pme,$L)=>{"use strict";l();var WL=cs(),jL=GL(),Ote=HI()(),QL=kI(),zL=WL("%TypeError%"),Dte=WL("%Math.floor%");$L.exports=function(e,r){if(typeof e!="function")throw new zL("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Dte(r)!==r)throw new zL("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&QL){var o=QL(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(Ote?jL(e,"length",r,!0,!0):jL(e,"length",r)),e}});var eF=v((Bme,fy)=>{"use strict";l();var jI=ay(),Au=cs(),Pte=KL(),Rte=Au("%TypeError%"),JL=Au("%Function.prototype.apply%"),XL=Au("%Function.prototype.call%"),ZL=Au("%Reflect.apply%",!0)||jI.call(XL,JL),Zl=Au("%Object.defineProperty%",!0),Bte=Au("%Math.max%");if(Zl)try{Zl({},"a",{value:1})}catch{Zl=null}fy.exports=function(e){if(typeof e!="function")throw new Rte("a function is required");var r=ZL(jI,XL,arguments);return Pte(r,1+Bte(0,e.length-(arguments.length-1)),!0)};var YL=function(){return ZL(jI,JL,arguments)};Zl?Zl(fy.exports,"apply",{value:YL}):fy.exports.apply=YL});var iF=v((Fme,nF)=>{"use strict";l();var tF=cs(),rF=eF(),Lte=rF(tF("String.prototype.indexOf"));nF.exports=function(e,r){var n=tF(e,!!r);return typeof n=="function"&&Lte(e,".prototype.")>-1?rF(n):n}});var sF=v(()=>{l()});var SF=v((Hme,_F)=>{l();var e_=typeof Map=="function"&&Map.prototype,QI=Object.getOwnPropertyDescriptor&&e_?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,hy=e_&&QI&&typeof QI.get=="function"?QI.get:null,oF=e_&&Map.prototype.forEach,t_=typeof Set=="function"&&Set.prototype,zI=Object.getOwnPropertyDescriptor&&t_?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,py=t_&&zI&&typeof zI.get=="function"?zI.get:null,aF=t_&&Set.prototype.forEach,Fte=typeof WeakMap=="function"&&WeakMap.prototype,tf=Fte?WeakMap.prototype.has:null,Mte=typeof WeakSet=="function"&&WeakSet.prototype,rf=Mte?WeakSet.prototype.has:null,Ute=typeof WeakRef=="function"&&WeakRef.prototype,uF=Ute?WeakRef.prototype.deref:null,qte=Boolean.prototype.valueOf,Vte=Object.prototype.toString,Hte=Function.prototype.toString,kte=String.prototype.match,r_=String.prototype.slice,fs=String.prototype.replace,Gte=String.prototype.toUpperCase,cF=String.prototype.toLowerCase,wF=RegExp.prototype.test,lF=Array.prototype.concat,qn=Array.prototype.join,jte=Array.prototype.slice,fF=Math.floor,KI=typeof BigInt=="function"?BigInt.prototype.valueOf:null,WI=Object.getOwnPropertySymbols,YI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,bu=typeof Symbol=="function"&&typeof Symbol.iterator=="object",nr=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===bu||!0)?Symbol.toStringTag:null,EF=Object.prototype.propertyIsEnumerable,dF=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function hF(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||wF.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-fF(-t):fF(t);if(n!==t){var i=String(n),s=r_.call(e,i.length+1);return fs.call(i,r,"$&_")+"."+fs.call(fs.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return fs.call(e,r,"$&_")}var JI=sF(),pF=JI.custom,gF=AF(pF)?pF:null;_F.exports=function t(e,r,n,i){var s=r||{};if(ls(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(ls(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=ls(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(ls(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(ls(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return IF(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var u=String(e);return a?hF(e,u):u}if(typeof e=="bigint"){var c=String(e)+"n";return a?hF(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return XI(e)?"[Array]":"[Object]";var d=ure(s,n);if(typeof i>"u")i=[];else if(bF(i,e)>=0)return"[Circular]";function g(Q,K,ye){if(K&&(i=jte.call(i),i.push(K)),ye){var ce={depth:s.depth};return ls(s,"quoteStyle")&&(ce.quoteStyle=s.quoteStyle),t(Q,ce,n+1,i)}return t(Q,s,n+1,i)}if(typeof e=="function"&&!yF(e)){var m=Zte(e),y=dy(e,g);return"[Function"+(m?": "+m:" (anonymous)")+"]"+(y.length>0?" { "+qn.call(y,", ")+" }":"")}if(AF(e)){var A=bu?fs.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):YI.call(e);return typeof e=="object"&&!bu?ef(A):A}if(sre(e)){for(var O="<"+cF.call(String(e.nodeName)),R=e.attributes||[],q=0;q",O}if(XI(e)){if(e.length===0)return"[]";var M=dy(e,g);return d&&!are(M)?"["+ZI(M,d)+"]":"[ "+qn.call(M,", ")+" ]"}if(Wte(e)){var b=dy(e,g);return!("cause"in Error.prototype)&&"cause"in e&&!EF.call(e,"cause")?"{ ["+String(e)+"] "+qn.call(lF.call("[cause]: "+g(e.cause),b),", ")+" }":b.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+qn.call(b,", ")+" }"}if(typeof e=="object"&&o){if(gF&&typeof e[gF]=="function"&&JI)return JI(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(ere(e)){var S=[];return oF&&oF.call(e,function(Q,K){S.push(g(K,e,!0)+" => "+g(Q,e))}),mF("Map",hy.call(e),S,d)}if(nre(e)){var N=[];return aF&&aF.call(e,function(Q){N.push(g(Q,e))}),mF("Set",py.call(e),N,d)}if(tre(e))return $I("WeakMap");if(ire(e))return $I("WeakSet");if(rre(e))return $I("WeakRef");if(Kte(e))return ef(g(Number(e)));if(Jte(e))return ef(g(KI.call(e)));if(Yte(e))return ef(qte.call(e));if($te(e))return ef(g(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!zte(e)&&!yF(e)){var _=dy(e,g),T=dF?dF(e)===Object.prototype:e instanceof Object||e.constructor===Object,B=e instanceof Object?"":"null prototype",X=!T&&nr&&Object(e)===e&&nr in e?r_.call(ds(e),8,-1):B?"Object":"",z=T||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",k=z+(X||B?"["+qn.call(lF.call([],X||[],B||[]),": ")+"] ":"");return _.length===0?k+"{}":d?k+"{"+ZI(_,d)+"}":k+"{ "+qn.call(_,", ")+" }"}return String(e)};function vF(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function Qte(t){return fs.call(String(t),/"/g,""")}function XI(t){return ds(t)==="[object Array]"&&(!nr||!(typeof t=="object"&&nr in t))}function zte(t){return ds(t)==="[object Date]"&&(!nr||!(typeof t=="object"&&nr in t))}function yF(t){return ds(t)==="[object RegExp]"&&(!nr||!(typeof t=="object"&&nr in t))}function Wte(t){return ds(t)==="[object Error]"&&(!nr||!(typeof t=="object"&&nr in t))}function $te(t){return ds(t)==="[object String]"&&(!nr||!(typeof t=="object"&&nr in t))}function Kte(t){return ds(t)==="[object Number]"&&(!nr||!(typeof t=="object"&&nr in t))}function Yte(t){return ds(t)==="[object Boolean]"&&(!nr||!(typeof t=="object"&&nr in t))}function AF(t){if(bu)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!YI)return!1;try{return YI.call(t),!0}catch{}return!1}function Jte(t){if(!t||typeof t!="object"||!KI)return!1;try{return KI.call(t),!0}catch{}return!1}var Xte=Object.prototype.hasOwnProperty||function(t){return t in this};function ls(t,e){return Xte.call(t,e)}function ds(t){return Vte.call(t)}function Zte(t){if(t.name)return t.name;var e=kte.call(Hte.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function bF(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return IF(r_.call(t,0,e.maxStringLength),e)+n}var i=fs.call(fs.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,ore);return vF(i,"single",e)}function ore(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+Gte.call(e.toString(16))}function ef(t){return"Object("+t+")"}function $I(t){return t+" { ? }"}function mF(t,e,r,n){var i=n?ZI(r,n):qn.call(r,", ");return t+" ("+e+") {"+i+"}"}function are(t){for(var e=0;e=0)return!1;return!0}function ure(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=qn.call(Array(t.indent+1)," ");else return null;return{base:r,prev:qn.call(Array(e+1),r)}}function ZI(t,e){if(t.length===0)return"";var r=` -`+e.prev+e.base;return r+qn.call(t,","+r)+` -`+e.prev}function dy(t,e){var r=XI(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";l();var n_=cs(),Iu=iF(),cre=SF(),lre=n_("%TypeError%"),gy=n_("%WeakMap%",!0),yy=n_("%Map%",!0),fre=Iu("WeakMap.prototype.get",!0),dre=Iu("WeakMap.prototype.set",!0),hre=Iu("WeakMap.prototype.has",!0),pre=Iu("Map.prototype.get",!0),gre=Iu("Map.prototype.set",!0),yre=Iu("Map.prototype.has",!0),i_=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},mre=function(t,e){var r=i_(t,e);return r&&r.value},wre=function(t,e,r){var n=i_(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},Ere=function(t,e){return!!i_(t,e)};TF.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new lre("Side channel does not contain "+cre(s))},get:function(s){if(gy&&s&&(typeof s=="object"||typeof s=="function")){if(e)return fre(e,s)}else if(yy){if(r)return pre(r,s)}else if(n)return mre(n,s)},has:function(s){if(gy&&s&&(typeof s=="object"||typeof s=="function")){if(e)return hre(e,s)}else if(yy){if(r)return yre(r,s)}else if(n)return Ere(n,s);return!1},set:function(s,o){gy&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new gy),dre(e,s,o)):yy?(r||(r=new yy),gre(r,s,o)):(n||(n={key:{},next:null}),wre(n,s,o))}};return i}});var my=v((Qme,xF)=>{"use strict";l();var vre=String.prototype.replace,Are=/%20/g,s_={RFC1738:"RFC1738",RFC3986:"RFC3986"};xF.exports={default:s_.RFC3986,formatters:{RFC1738:function(t){return vre.call(t,Are,"+")},RFC3986:function(t){return String(t)}},RFC1738:s_.RFC1738,RFC3986:s_.RFC3986}});var a_=v((Wme,OF)=>{"use strict";l();var bre=my(),o_=Object.prototype.hasOwnProperty,wo=Array.isArray,Vn=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),Ire=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(wo(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===bre.RFC1738&&(c===40||c===41)){a+=o.charAt(u);continue}if(c<128){a=a+Vn[c];continue}if(c<2048){a=a+(Vn[192|c>>6]+Vn[128|c&63]);continue}if(c<55296||c>=57344){a=a+(Vn[224|c>>12]+Vn[128|c>>6&63]+Vn[128|c&63]);continue}u+=1,c=65536+((c&1023)<<10|o.charCodeAt(u)&1023),a+=Vn[240|c>>18]+Vn[128|c>>12&63]+Vn[128|c>>6&63]+Vn[128|c&63]}return a},xre=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";l();var RF=CF(),c_=a_(),nf=my(),Rre=Object.prototype.hasOwnProperty,DF={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},Eo=Array.isArray,Bre=String.prototype.split,Lre=Array.prototype.push,BF=function(t,e){Lre.apply(t,Eo(e)?e:[e])},Fre=Date.prototype.toISOString,PF=nf.default,$t={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:c_.encode,encodeValuesOnly:!1,format:PF,formatter:nf.formatters[PF],indices:!1,serializeDate:function(e){return Fre.call(e)},skipNulls:!1,strictNullHandling:!1},Mre=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},u_={},Ure=function t(e,r,n,i,s,o,a,u,c,f,d,g,m,y,A){for(var O=e,R=A,q=0,M=!1;(R=R.get(u_))!==void 0&&!M;){var b=R.get(e);if(q+=1,typeof b<"u"){if(b===q)throw new RangeError("Cyclic object value");M=!0}typeof R.get(u_)>"u"&&(q=0)}if(typeof a=="function"?O=a(r,O):O instanceof Date?O=f(O):n==="comma"&&Eo(O)&&(O=c_.maybeMap(O,function(ie){return ie instanceof Date?f(ie):ie})),O===null){if(i)return o&&!m?o(r,$t.encoder,y,"key",d):r;O=""}if(Mre(O)||c_.isBuffer(O)){if(o){var S=m?r:o(r,$t.encoder,y,"key",d);if(n==="comma"&&m){for(var N=Bre.call(String(O),","),_="",T=0;T"u")return B;var X;if(n==="comma"&&Eo(O))X=[{value:O.length>0?O.join(",")||null:void 0}];else if(Eo(a))X=a;else{var z=Object.keys(O);X=u?z.sort(u):z}for(var k=0;k"u"?$t.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:$t.charsetSentinel,delimiter:typeof e.delimiter>"u"?$t.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:$t.encode,encoder:typeof e.encoder=="function"?e.encoder:$t.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:$t.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:$t.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:$t.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:$t.strictNullHandling}};LF.exports=function(t,e){var r=t,n=qre(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Eo(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var a;e&&e.arrayFormat in DF?a=e.arrayFormat:e&&"indices"in e?a=e.indices?"indices":"repeat":a="indices";var u=DF[a];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=RF(),f=0;f0?m+g:""}});var qF=v((Jme,UF)=>{"use strict";l();var _u=a_(),l_=Object.prototype.hasOwnProperty,Vre=Array.isArray,jt={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:_u.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Hre=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},MF=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},kre="utf8=%26%2310003%3B",Gre="utf8=%E2%9C%93",jre=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),a=-1,u,c=r.charset;if(r.charsetSentinel)for(u=0;u-1&&(y=Vre(y)?[y]:y),l_.call(n,m)?n[m]=_u.combine(n[m],y):n[m]=y}return n},Qre=function(t,e,r,n){for(var i=n?e:MF(e,r),s=t.length-1;s>=0;--s){var o,a=t[s];if(a==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var u=a.charAt(0)==="["&&a.charAt(a.length-1)==="]"?a.slice(1,-1):a,c=parseInt(u,10);!r.parseArrays&&u===""?o={0:i}:!isNaN(c)&&a!==u&&String(c)===u&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):u!=="__proto__"&&(o[u]=i)}i=o}return i},zre=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,a=/(\[[^[\]]*])/g,u=n.depth>0&&o.exec(s),c=u?s.slice(0,u.index):s,f=[];if(c){if(!n.plainObjects&&l_.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(u=a.exec(s))!==null&&d"u"?jt.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?jt.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:jt.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:jt.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:jt.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:jt.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:jt.comma,decoder:typeof e.decoder=="function"?e.decoder:jt.decoder,delimiter:typeof e.delimiter=="string"||_u.isRegExp(e.delimiter)?e.delimiter:jt.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:jt.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:jt.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:jt.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:jt.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:jt.strictNullHandling}};UF.exports=function(t,e){var r=Wre(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?jre(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";l();var $re=FF(),Kre=qF(),Yre=my();VF.exports={formats:Yre,parse:Kre,stringify:$re}});var f_=v(Ge=>{"use strict";l();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=Ge.WALLET_PROVIDER_CALLBACK_PARAM=Ge.WALLET_PROVIDER_SIGN_MESSAGE_URL=Ge.WALLET_PROVIDER_GUARD_TRANSACTION_URL=Ge.WALLET_PROVIDER_SIGN_TRANSACTION_URL=Ge.WALLET_PROVIDER_SEND_TRANSACTION_URL=Ge.WALLET_PROVIDER_DISCONNECT_URL=Ge.WALLET_PROVIDER_CONNECT_URL=Ge.XALIAS_PROVIDER_TESTNET=Ge.XALIAS_PROVIDER_DEVNET=Ge.XALIAS_PROVIDER_MAINNET=Ge.WALLET_PROVIDER_TESTNET=Ge.WALLET_PROVIDER_DEVNET=Ge.WALLET_PROVIDER_MAINNET=void 0;Ge.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";Ge.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";Ge.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";Ge.XALIAS_PROVIDER_MAINNET="https://xalias.com";Ge.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";Ge.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";Ge.WALLET_PROVIDER_CONNECT_URL="hook/login";Ge.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";Ge.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";Ge.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";Ge.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";Ge.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";Ge.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";Ge.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var kF=v(Su=>{"use strict";l();Object.defineProperty(Su,"__esModule",{value:!0});Su.ErrCannotSignedMessage=Su.ErrCannotGetSignedTransactions=void 0;var d_=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Su.ErrCannotGetSignedTransactions=d_;var h_=class extends Error{constructor(){super("Cannot get signed message")}};Su.ErrCannotSignedMessage=h_});var GF=v(wy=>{"use strict";l();Object.defineProperty(wy,"__esModule",{value:!0});wy.PlainSignedTransaction=void 0;var p_=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};wy.PlainSignedTransaction=p_});var Tu=v(gs=>{"use strict";l();var hs=gs&&gs.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})},Jre=gs&&gs.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gs,"__esModule",{value:!0});gs.WalletProvider=void 0;var g_=Jre(HF()),ps=f_(),y_=kF(),Xre=GF(),m_=class t{constructor(e){this.walletUrl=e}login(e){return hs(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ps.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return hs(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return hs(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return hs(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ps.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return hs(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:ps.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=g_.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new y_.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return hs(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ps.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return hs(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ps.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return hs(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(){let e=g_.default.parse(window.location.search.slice(1));return t.isTxSignReturnSuccess(e)?this.getTxSignReturnValue(e):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(ps.WALLET_PROVIDER_CALLBACK_PARAM)&&e[ps.WALLET_PROVIDER_CALLBACK_PARAM]===ps.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new y_.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new y_.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let a=t.prepareWalletTransaction(o);for(let u in a)a.hasOwnProperty(u)&&!i.hasOwnProperty(u)&&(i[u]=[]),i[u].push(a[u])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};gs.WalletProvider=m_});var IM=v((cwe,bM)=>{"use strict";l();function tM(t,e){return function(){return t.apply(e,arguments)}}var{toString:Zre}=Object.prototype,{getPrototypeOf:N_}=Object,by=(t=>e=>{let r=Zre.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kn=t=>(t=t.toLowerCase(),e=>by(e)===t),Iy=t=>e=>typeof e===t,{isArray:Ou}=Array,of=Iy("undefined");function ene(t){return t!==null&&!of(t)&&t.constructor!==null&&!of(t.constructor)&&Qr(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var rM=kn("ArrayBuffer");function tne(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&rM(t.buffer),e}var rne=Iy("string"),Qr=Iy("function"),nM=Iy("number"),_y=t=>t!==null&&typeof t=="object",nne=t=>t===!0||t===!1,Ey=t=>{if(by(t)!=="object")return!1;let e=N_(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ine=kn("Date"),sne=kn("File"),one=kn("Blob"),ane=kn("FileList"),une=t=>_y(t)&&Qr(t.pipe),cne=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Qr(t.append)&&((e=by(t))==="formdata"||e==="object"&&Qr(t.toString)&&t.toString()==="[object FormData]"))},lne=kn("URLSearchParams"),fne=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function af(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ou(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var sM=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,oM=t=>!of(t)&&t!==sM;function b_(){let{caseless:t}=oM(this)&&this||{},e={},r=(n,i)=>{let s=t&&iM(e,i)||i;Ey(e[s])&&Ey(n)?e[s]=b_(e[s],n):Ey(n)?e[s]=b_({},n):Ou(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(af(e,(i,s)=>{r&&Qr(i)?t[s]=tM(i,r):t[s]=i},{allOwnKeys:n}),t),hne=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),pne=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},gne=(t,e,r,n)=>{let i,s,o,a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=r!==!1&&N_(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},yne=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},mne=t=>{if(!t)return null;if(Ou(t))return t;let e=t.length;if(!nM(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},wne=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&N_(Uint8Array)),Ene=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},vne=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Ane=kn("HTMLFormElement"),bne=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),jF=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Ine=kn("RegExp"),aM=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};af(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},_ne=t=>{aM(t,(e,r)=>{if(Qr(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(Qr(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Sne=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ou(t)?n(t):n(String(t).split(e)),r},Tne=()=>{},Cne=(t,e)=>(t=+t,Number.isFinite(t)?t:e),w_="abcdefghijklmnopqrstuvwxyz",QF="0123456789",uM={DIGIT:QF,ALPHA:w_,ALPHA_DIGIT:w_+w_.toUpperCase()+QF},xne=(t=16,e=uM.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function Nne(t){return!!(t&&Qr(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var One=t=>{let e=new Array(10),r=(n,i)=>{if(_y(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ou(n)?[]:{};return af(n,(o,a)=>{let u=r(o,i+1);!of(u)&&(s[a]=u)}),e[i]=void 0,s}}return n};return r(t,0)},Dne=kn("AsyncFunction"),Pne=t=>t&&(_y(t)||Qr(t))&&Qr(t.then)&&Qr(t.catch),Y={isArray:Ou,isArrayBuffer:rM,isBuffer:ene,isFormData:cne,isArrayBufferView:tne,isString:rne,isNumber:nM,isBoolean:nne,isObject:_y,isPlainObject:Ey,isUndefined:of,isDate:ine,isFile:sne,isBlob:one,isRegExp:Ine,isFunction:Qr,isStream:une,isURLSearchParams:lne,isTypedArray:wne,isFileList:ane,forEach:af,merge:b_,extend:dne,trim:fne,stripBOM:hne,inherits:pne,toFlatObject:gne,kindOf:by,kindOfTest:kn,endsWith:yne,toArray:mne,forEachEntry:Ene,matchAll:vne,isHTMLForm:Ane,hasOwnProperty:jF,hasOwnProp:jF,reduceDescriptors:aM,freezeMethods:_ne,toObjectSet:Sne,toCamelCase:bne,noop:Tne,toFiniteNumber:Cne,findKey:iM,global:sM,isContextDefined:oM,ALPHABET:uM,generateString:xne,isSpecCompliantForm:Nne,toJSONObject:One,isAsyncFn:Dne,isThenable:Pne};function Me(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}Y.inherits(Me,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:Y.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var cM=Me.prototype,lM={};["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(t=>{lM[t]={value:t}});Object.defineProperties(Me,lM);Object.defineProperty(cM,"isAxiosError",{value:!0});Me.from=(t,e,r,n,i,s)=>{let o=Object.create(cM);return Y.toFlatObject(t,o,function(u){return u!==Error.prototype},a=>a!=="isAxiosError"),Me.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var Rne=null;function I_(t){return Y.isPlainObject(t)||Y.isArray(t)}function fM(t){return Y.endsWith(t,"[]")?t.slice(0,-2):t}function zF(t,e,r){return t?t.concat(e).map(function(i,s){return i=fM(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Bne(t){return Y.isArray(t)&&!t.some(I_)}var Lne=Y.toFlatObject(Y,{},null,function(e){return/^is[A-Z]/.test(e)});function Sy(t,e,r){if(!Y.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=Y.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(A,O){return!Y.isUndefined(O[A])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,u=(r.Blob||typeof Blob<"u"&&Blob)&&Y.isSpecCompliantForm(e);if(!Y.isFunction(i))throw new TypeError("visitor must be a function");function c(y){if(y===null)return"";if(Y.isDate(y))return y.toISOString();if(!u&&Y.isBlob(y))throw new Me("Blob is not supported. Use a Buffer instead.");return Y.isArrayBuffer(y)||Y.isTypedArray(y)?u&&typeof Blob=="function"?new Blob([y]):h.Buffer.from(y):y}function f(y,A,O){let R=y;if(y&&!O&&typeof y=="object"){if(Y.endsWith(A,"{}"))A=n?A:A.slice(0,-2),y=JSON.stringify(y);else if(Y.isArray(y)&&Bne(y)||(Y.isFileList(y)||Y.endsWith(A,"[]"))&&(R=Y.toArray(y)))return A=fM(A),R.forEach(function(M,b){!(Y.isUndefined(M)||M===null)&&e.append(o===!0?zF([A],b,s):o===null?A:A+"[]",c(M))}),!1}return I_(y)?!0:(e.append(zF(O,A,s),c(y)),!1)}let d=[],g=Object.assign(Lne,{defaultVisitor:f,convertValue:c,isVisitable:I_});function m(y,A){if(!Y.isUndefined(y)){if(d.indexOf(y)!==-1)throw Error("Circular reference detected in "+A.join("."));d.push(y),Y.forEach(y,function(R,q){(!(Y.isUndefined(R)||R===null)&&i.call(e,R,Y.isString(q)?q.trim():q,A,g))===!0&&m(R,A?A.concat(q):[q])}),d.pop()}}if(!Y.isObject(t))throw new TypeError("data must be an object");return m(t),e}function WF(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function O_(t,e){this._pairs=[],t&&Sy(t,this,e)}var dM=O_.prototype;dM.append=function(e,r){this._pairs.push([e,r])};dM.toString=function(e){let r=e?function(n){return e.call(this,n,WF)}:WF;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Fne(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function hM(t,e,r){if(!e)return t;let n=r&&r.encode||Fne,i=r&&r.serialize,s;if(i?s=i(e,r):s=Y.isURLSearchParams(e)?e.toString():new O_(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var __=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Y.forEach(this.handlers,function(n){n!==null&&e(n)})}},$F=__,pM={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Mne=typeof URLSearchParams<"u"?URLSearchParams:O_,Une=typeof FormData<"u"?FormData:null,qne=typeof Blob<"u"?Blob:null,Vne={isBrowser:!0,classes:{URLSearchParams:Mne,FormData:Une,Blob:qne},protocols:["http","https","file","blob","url","data"]},gM=typeof window<"u"&&typeof document<"u",Hne=(t=>gM&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),kne=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Gne=Object.freeze({__proto__:null,hasBrowserEnv:gM,hasStandardBrowserWebWorkerEnv:kne,hasStandardBrowserEnv:Hne}),Hn={...Gne,...Vne};function jne(t,e){return Sy(t,new Hn.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Hn.isNode&&Y.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function Qne(t){return Y.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function zne(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&Y.isArray(i)?i.length:o,u?(Y.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!a):((!i[o]||!Y.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&Y.isArray(i[o])&&(i[o]=zne(i[o])),!a)}if(Y.isFormData(t)&&Y.isFunction(t.entries)){let r={};return Y.forEachEntry(t,(n,i)=>{e(Qne(n),i,r,0)}),r}return null}function Wne(t,e,r){if(Y.isString(t))try{return(e||JSON.parse)(t),Y.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var D_={transitional:pM,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=Y.isObject(e);if(s&&Y.isHTMLForm(e)&&(e=new FormData(e)),Y.isFormData(e))return i?JSON.stringify(yM(e)):e;if(Y.isArrayBuffer(e)||Y.isBuffer(e)||Y.isStream(e)||Y.isFile(e)||Y.isBlob(e))return e;if(Y.isArrayBufferView(e))return e.buffer;if(Y.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return jne(e,this.formSerializer).toString();if((a=Y.isFileList(e))||n.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return Sy(a?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Wne(e)):e}],transformResponse:[function(e){let r=this.transitional||D_.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&Y.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?Me.from(a,Me.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Hn.classes.FormData,Blob:Hn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Y.forEach(["delete","get","head","post","put","patch"],t=>{D_.headers[t]={}});var P_=D_,$ne=Y.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"]),Kne=t=>{let e={},r,n,i;return t&&t.split(` -`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&$ne[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},KF=Symbol("internals");function sf(t){return t&&String(t).trim().toLowerCase()}function vy(t){return t===!1||t==null?t:Y.isArray(t)?t.map(vy):String(t)}function Yne(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Jne=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function E_(t,e,r,n,i){if(Y.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!Y.isString(e)){if(Y.isString(n))return e.indexOf(n)!==-1;if(Y.isRegExp(n))return n.test(e)}}function Xne(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function Zne(t,e){let r=Y.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Cu=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(a,u,c){let f=sf(u);if(!f)throw new Error("header name must be a non-empty string");let d=Y.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||u]=vy(a))}let o=(a,u)=>Y.forEach(a,(c,f)=>s(c,f,u));return Y.isPlainObject(e)||e instanceof this.constructor?o(e,r):Y.isString(e)&&(e=e.trim())&&!Jne(e)?o(Kne(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=sf(e),e){let n=Y.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Yne(i);if(Y.isFunction(r))return r.call(this,i,n);if(Y.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=sf(e),e){let n=Y.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||E_(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=sf(o),o){let a=Y.findKey(n,o);a&&(!r||E_(n,n[a],a,r))&&(delete n[a],i=!0)}}return Y.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||E_(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return Y.forEach(this,(i,s)=>{let o=Y.findKey(n,s);if(o){r[o]=vy(i),delete r[s];return}let a=e?Xne(s):String(s).trim();a!==s&&delete r[s],r[a]=vy(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return Y.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&Y.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[KF]=this[KF]={accessors:{}}).accessors,i=this.prototype;function s(o){let a=sf(o);n[a]||(Zne(i,o),n[a]=!0)}return Y.isArray(e)?e.forEach(s):s(e),this}};Cu.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);Y.reduceDescriptors(Cu.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});Y.freezeMethods(Cu);var yi=Cu;function v_(t,e){let r=this||P_,n=e||r,i=yi.from(n.headers),s=n.data;return Y.forEach(t,function(a){s=a.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function mM(t){return!!(t&&t.__CANCEL__)}function uf(t,e,r){Me.call(this,t??"canceled",Me.ERR_CANCELED,e,r),this.name="CanceledError"}Y.inherits(uf,Me,{__CANCEL__:!0});function eie(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Me("Request failed with status code "+r.status,[Me.ERR_BAD_REQUEST,Me.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var tie=Hn.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];Y.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Y.isString(n)&&o.push("path="+n),Y.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function rie(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function nie(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function wM(t,e){return t&&!rie(e)?nie(t,e):e}var iie=Hn.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let a=Y.isString(o)?i(o):o;return a.protocol===n.protocol&&a.host===n.host}}():function(){return function(){return!0}}();function sie(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function oie(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(u){let c=Date.now(),f=n[s];o||(o=c),r[i]=u,n[i]=c;let d=s,g=0;for(;d!==i;)g+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,a=s-r,u=n(a),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:u||void 0,estimated:u&&o&&c?(o-s)/u:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var aie=typeof XMLHttpRequest<"u",uie=aie&&function(t){return new Promise(function(r,n){let i=t.data,s=yi.from(t.headers).normalize(),{responseType:o,withXSRFToken:a}=t,u;function c(){t.cancelToken&&t.cancelToken.unsubscribe(u),t.signal&&t.signal.removeEventListener("abort",u)}let f;if(Y.isFormData(i)){if(Hn.hasStandardBrowserEnv||Hn.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[A,...O]=f?f.split(";").map(R=>R.trim()).filter(Boolean):[];s.setContentType([A||"multipart/form-data",...O].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let A=t.auth.username||"",O=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(A+":"+O))}let g=wM(t.baseURL,t.url);d.open(t.method.toUpperCase(),hM(g,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function m(){if(!d)return;let A=yi.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),R={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:A,config:t,request:d};eie(function(M){r(M),c()},function(M){n(M),c()},R),d=null}if("onloadend"in d?d.onloadend=m:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(m)},d.onabort=function(){d&&(n(new Me("Request aborted",Me.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Me("Network Error",Me.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let O=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",R=t.transitional||pM;t.timeoutErrorMessage&&(O=t.timeoutErrorMessage),n(new Me(O,R.clarifyTimeoutError?Me.ETIMEDOUT:Me.ECONNABORTED,t,d)),d=null},Hn.hasStandardBrowserEnv&&(a&&Y.isFunction(a)&&(a=a(t)),a||a!==!1&&iie(g))){let A=t.xsrfHeaderName&&t.xsrfCookieName&&tie.read(t.xsrfCookieName);A&&s.set(t.xsrfHeaderName,A)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&Y.forEach(s.toJSON(),function(O,R){d.setRequestHeader(R,O)}),Y.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",YF(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",YF(t.onUploadProgress)),(t.cancelToken||t.signal)&&(u=A=>{d&&(n(!A||A.type?new uf(null,t,d):A),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(u),t.signal&&(t.signal.aborted?u():t.signal.addEventListener("abort",u)));let y=sie(g);if(y&&Hn.protocols.indexOf(y)===-1){n(new Me("Unsupported protocol "+y+":",Me.ERR_BAD_REQUEST,t));return}d.send(i||null)})},S_={http:Rne,xhr:uie};Y.forEach(S_,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var JF=t=>`- ${t}`,cie=t=>Y.isFunction(t)||t===null||t===!1,EM={getAdapter:t=>{t=Y.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${a} `+(u===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : -`+s.map(JF).join(` -`):" "+JF(s[0]):"as no adapter specified";throw new Me("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:S_};function A_(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new uf(null,t)}function XF(t){return A_(t),t.headers=yi.from(t.headers),t.data=v_.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),EM.getAdapter(t.adapter||P_.adapter)(t).then(function(n){return A_(t),n.data=v_.call(t,t.transformResponse,n),n.headers=yi.from(n.headers),n},function(n){return mM(n)||(A_(t),n&&n.response&&(n.response.data=v_.call(t,t.transformResponse,n.response),n.response.headers=yi.from(n.response.headers))),Promise.reject(n)})}var ZF=t=>t instanceof yi?t.toJSON():t;function xu(t,e){e=e||{};let r={};function n(c,f,d){return Y.isPlainObject(c)&&Y.isPlainObject(f)?Y.merge.call({caseless:d},c,f):Y.isPlainObject(f)?Y.merge({},f):Y.isArray(f)?f.slice():f}function i(c,f,d){if(Y.isUndefined(f)){if(!Y.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!Y.isUndefined(f))return n(void 0,f)}function o(c,f){if(Y.isUndefined(f)){if(!Y.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function a(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let u={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:a,headers:(c,f)=>i(ZF(c),ZF(f),!0)};return Y.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=u[f]||i,g=d(t[f],e[f],f);Y.isUndefined(g)&&d!==a||(r[f]=g)}),r}var vM="1.6.7",R_={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{R_[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var eM={};R_.transitional=function(e,r,n){function i(s,o){return"[Axios v"+vM+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,a)=>{if(e===!1)throw new Me(i(o," has been removed"+(r?" in "+r:"")),Me.ERR_DEPRECATED);return r&&!eM[o]&&(eM[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,a):!0}};function lie(t,e,r){if(typeof t!="object")throw new Me("options must be an object",Me.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let a=t[s],u=a===void 0||o(a,s,t);if(u!==!0)throw new Me("option "+s+" must be "+u,Me.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Me("Unknown option "+s,Me.ERR_BAD_OPTION)}}var T_={assertOptions:lie,validators:R_},ys=T_.validators,Nu=class{constructor(e){this.defaults=e,this.interceptors={request:new $F,response:new $F}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` -`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=xu(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&T_.assertOptions(n,{silentJSONParsing:ys.transitional(ys.boolean),forcedJSONParsing:ys.transitional(ys.boolean),clarifyTimeoutError:ys.transitional(ys.boolean)},!1),i!=null&&(Y.isFunction(i)?r.paramsSerializer={serialize:i}:T_.assertOptions(i,{encode:ys.function,serialize:ys.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&Y.merge(s.common,s[r.method]);s&&Y.forEach(["delete","get","head","post","put","patch","common"],y=>{delete s[y]}),r.headers=yi.concat(o,s);let a=[],u=!0;this.interceptors.request.forEach(function(A){typeof A.runWhen=="function"&&A.runWhen(r)===!1||(u=u&&A.synchronous,a.unshift(A.fulfilled,A.rejected))});let c=[];this.interceptors.response.forEach(function(A){c.push(A.fulfilled,A.rejected)});let f,d=0,g;if(!u){let y=[XF.bind(this),void 0];for(y.unshift.apply(y,a),y.push.apply(y,c),g=y.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(a=>{n.subscribe(a),s=a}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,a){n.reason||(n.reason=new uf(s,o,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},fie=C_;function die(t){return function(r){return t.apply(null,r)}}function hie(t){return Y.isObject(t)&&t.isAxiosError===!0}var x_={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(x_).forEach(([t,e])=>{x_[e]=t});var pie=x_;function AM(t){let e=new Ay(t),r=tM(Ay.prototype.request,e);return Y.extend(r,Ay.prototype,e,{allOwnKeys:!0}),Y.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return AM(xu(t,i))},r}var Rt=AM(P_);Rt.Axios=Ay;Rt.CanceledError=uf;Rt.CancelToken=fie;Rt.isCancel=mM;Rt.VERSION=vM;Rt.toFormData=Sy;Rt.AxiosError=Me;Rt.Cancel=Rt.CanceledError;Rt.all=function(e){return Promise.all(e)};Rt.spread=die;Rt.isAxiosError=hie;Rt.mergeConfig=xu;Rt.AxiosHeaders=yi;Rt.formToJSON=t=>yM(Y.isHTMLForm(t)?new FormData(t):t);Rt.getAdapter=EM.getAdapter;Rt.HttpStatusCode=pie;Rt.default=Rt;bM.exports=Rt});var _M=v(Ty=>{"use strict";l();Object.defineProperty(Ty,"__esModule",{value:!0});Ty.NativeAuthClientConfig=void 0;var B_=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};Ty.NativeAuthClientConfig=B_});var F_=v(Du=>{"use strict";l();var vo=Du&&Du.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(f){try{c(n.next(f))}catch(d){o(d)}}function u(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(a,u)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Du,"__esModule",{value:!0});Du.NativeAuthClient=void 0;var gie=IM(),yie=_M(),L_=class{constructor(e){this.config=Object.assign(new yie.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vo(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vo(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vo(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vo(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vo(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vo(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(h.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vo(this,void 0,void 0,function*(){return yield gie.default.get(e,{headers:this.config.extraRequestHeaders})})}};Du.NativeAuthClient=L_});var xM=v(xy=>{"use strict";l();Object.defineProperty(xy,"__esModule",{value:!0});xy.TransactionStatus=void 0;var U_=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};xy.TransactionStatus=U_});var OM=v(Ny=>{"use strict";l();Object.defineProperty(Ny,"__esModule",{value:!0});Ny.TransactionReceipt=void 0;var NM=Ta(),q_=class t{constructor(){this.value="",this.sender=new NM.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new NM.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};Ny.TransactionReceipt=q_});var DM=v(Gn=>{"use strict";l();Object.defineProperty(Gn,"__esModule",{value:!0});Gn.ErrContractQuery=Gn.ErrNetworkProvider=Gn.ErrUnexpectedCondition=Gn.Err=void 0;var Ru=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Gn.Err=Ru;var V_=class extends Ru{constructor(e){super(`Unexpected condition: [${e}]`)}};Gn.ErrUnexpectedCondition=V_;var H_=class extends Ru{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Gn.ErrNetworkProvider=H_;var k_=class extends Ru{constructor(e){super(e.message.replace("executeQuery:",""))}};Gn.ErrContractQuery=k_});var RM=v(ms=>{"use strict";l();Object.defineProperty(ms,"__esModule",{value:!0});ms.TransactionEventTopic=ms.TransactionEventData=ms.TransactionEvent=void 0;var PM=Ta(),G_=class t{constructor(e){this.address=new PM.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new Bu(h.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new PM.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new Oy(n)),r.dataPayload=Bu.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(Bu.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};ms.TransactionEvent=G_;var Bu=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(h.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};ms.TransactionEventData=Bu;var Oy=class{constructor(e){this.raw=h.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};ms.TransactionEventTopic=Oy});var Q_=v(Dy=>{"use strict";l();Object.defineProperty(Dy,"__esModule",{value:!0});Dy.TransactionLogs=void 0;var Eie=DM(),BM=Ta(),vie=RM(),j_=class t{constructor(e){this.address=new BM.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new BM.Address(e.address),r.events=(e.events||[]).map(n=>vie.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new Eie.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};Dy.TransactionLogs=j_});var FM=v(Lu=>{"use strict";l();Object.defineProperty(Lu,"__esModule",{value:!0});Lu.ContractResultItem=Lu.ContractResults=void 0;var LM=Q_(),Py=Ta(),z_=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>cf.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>cf.fromApiHttpResponse(n));return new t(r)}};Lu.ContractResults=z_;var cf=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new Py.Address(""),this.sender=new Py.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new LM.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=h.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new Py.Address(e.receiver),r.sender=new Py.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=LM.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Lu.ContractResultItem=cf});var MM=v(Ry=>{"use strict";l();Object.defineProperty(Ry,"__esModule",{value:!0});Ry.ContractQueryRequest=void 0;var W_=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};Ry.ContractQueryRequest=W_});var KM=v((dEe,$M)=>{l();$M.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ws=v(bo=>{l();var $_,Aie=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];bo.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};bo.getSymbolTotalCodewords=function(e){return Aie[e]};bo.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};bo.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');$_=e};bo.isKanjiModeEnabled=function(){return typeof $_<"u"};bo.toSJIS=function(e){return $_(e)}});var My=v(zr=>{l();zr.L={bit:1};zr.M={bit:0};zr.Q={bit:3};zr.H={bit:2};function bie(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return zr.L;case"m":case"medium":return zr.M;case"q":case"quartile":return zr.Q;case"h":case"high":return zr.H;default:throw new Error("Unknown EC Level: "+t)}}zr.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};zr.from=function(e,r){if(zr.isValid(e))return e;try{return bie(e)}catch{return r}}});var XM=v((wEe,JM)=>{l();function YM(){this.buffer=[],this.length=0}YM.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};JM.exports=YM});var eU=v((vEe,ZM)=>{l();function lf(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}lf.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};lf.prototype.get=function(t,e){return this.data[t*this.size+e]};lf.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};lf.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ZM.exports=lf});var tU=v(Uy=>{l();var Iie=ws().getSymbolSize;Uy.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=Iie(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{l();var _ie=ws().getSymbolSize,rU=7;nU.getPositions=function(e){let r=_ie(e);return[[0,0],[r-rU,0],[0,r-rU]]}});var sU=v(nt=>{l();nt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Io={N1:3,N2:3,N3:40,N4:10};nt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};nt.from=function(e){return nt.isValid(e)?parseInt(e,10):void 0};nt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,a=null;for(let u=0;u=5&&(n+=Io.N1+(i-5)),o=f,i=1),f=e.get(c,u),f===a?s++:(s>=5&&(n+=Io.N1+(s-5)),a=f,s=1)}i>=5&&(n+=Io.N1+(i-5)),s>=5&&(n+=Io.N1+(s-5))}return n};nt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&n++}return n*Io.N3};nt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{l();var Es=My(),qy=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Vy=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];K_.getBlocksCount=function(e,r){switch(r){case Es.L:return qy[(e-1)*4+0];case Es.M:return qy[(e-1)*4+1];case Es.Q:return qy[(e-1)*4+2];case Es.H:return qy[(e-1)*4+3];default:return}};K_.getTotalCodewordsCount=function(e,r){switch(r){case Es.L:return Vy[(e-1)*4+0];case Es.M:return Vy[(e-1)*4+1];case Es.Q:return Vy[(e-1)*4+2];case Es.H:return Vy[(e-1)*4+3];default:return}}});var oU=v(ky=>{l();var ff=new Uint8Array(512),Hy=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)ff[r]=e,Hy[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)ff[r]=ff[r-255]})();ky.log=function(e){if(e<1)throw new Error("log("+e+")");return Hy[e]};ky.exp=function(e){return ff[e]};ky.mul=function(e,r){return e===0||r===0?0:ff[Hy[e]+Hy[r]]}});var aU=v(df=>{l();var J_=oU();df.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{l();var uU=aU();function X_(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}X_.prototype.initialize=function(e){this.degree=e,this.genPoly=uU.generateECPolynomial(this.degree)};X_.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=uU.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};cU.exports=X_});var Z_=v(fU=>{l();fU.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var eS=v(mi=>{l();var dU="[0-9]+",Tie="[A-Z $%*+\\-./:]+",hf="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";hf=hf.replace(/u/g,"\\u");var Cie="(?:(?![A-Z0-9 $%*+\\-./:]|"+hf+`)(?:.|[\r -]))+`;mi.KANJI=new RegExp(hf,"g");mi.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");mi.BYTE=new RegExp(Cie,"g");mi.NUMERIC=new RegExp(dU,"g");mi.ALPHANUMERIC=new RegExp(Tie,"g");var xie=new RegExp("^"+hf+"$"),Nie=new RegExp("^"+dU+"$"),Oie=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");mi.testKanji=function(e){return xie.test(e)};mi.testNumeric=function(e){return Nie.test(e)};mi.testAlphanumeric=function(e){return Oie.test(e)}});var vs=v(Bt=>{l();var Die=Z_(),tS=eS();Bt.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};Bt.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};Bt.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};Bt.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};Bt.MIXED={bit:-1};Bt.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Die.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};Bt.getBestModeForData=function(e){return tS.testNumeric(e)?Bt.NUMERIC:tS.testAlphanumeric(e)?Bt.ALPHANUMERIC:tS.testKanji(e)?Bt.KANJI:Bt.BYTE};Bt.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};Bt.isValid=function(e){return e&&e.bit&&e.ccBits};function Pie(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return Bt.NUMERIC;case"alphanumeric":return Bt.ALPHANUMERIC;case"kanji":return Bt.KANJI;case"byte":return Bt.BYTE;default:throw new Error("Unknown mode: "+t)}}Bt.from=function(e,r){if(Bt.isValid(e))return e;try{return Pie(e)}catch{return r}}});var mU=v(_o=>{l();var Gy=ws(),Rie=Y_(),hU=My(),As=vs(),rS=Z_(),gU=7973,pU=Gy.getBCHDigit(gU);function Bie(t,e,r){for(let n=1;n<=40;n++)if(e<=_o.getCapacity(n,r,t))return n}function yU(t,e){return As.getCharCountIndicator(t,e)+4}function Lie(t,e){let r=0;return t.forEach(function(n){let i=yU(n.mode,e);r+=i+n.getBitsLength()}),r}function Fie(t,e){for(let r=1;r<=40;r++)if(Lie(t,r)<=_o.getCapacity(r,e,As.MIXED))return r}_o.from=function(e,r){return rS.isValid(e)?parseInt(e,10):r};_o.getCapacity=function(e,r,n){if(!rS.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=As.BYTE);let i=Gy.getSymbolTotalCodewords(e),s=Rie.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===As.MIXED)return o;let a=o-yU(n,e);switch(n){case As.NUMERIC:return Math.floor(a/10*3);case As.ALPHANUMERIC:return Math.floor(a/11*2);case As.KANJI:return Math.floor(a/13);case As.BYTE:default:return Math.floor(a/8)}};_o.getBestVersionForData=function(e,r){let n,i=hU.from(r,hU.M);if(Array.isArray(e)){if(e.length>1)return Fie(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Bie(n.mode,n.getLength(),i)};_o.getEncodedBits=function(e){if(!rS.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Gy.getBCHDigit(r)-pU>=0;)r^=gU<{l();var nS=ws(),EU=1335,Mie=21522,wU=nS.getBCHDigit(EU);vU.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;nS.getBCHDigit(i)-wU>=0;)i^=EU<{l();var Uie=vs();function Mu(t){this.mode=Uie.NUMERIC,this.data=t.toString()}Mu.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Mu.prototype.getLength=function(){return this.data.length};Mu.prototype.getBitsLength=function(){return Mu.getBitsLength(this.data.length)};Mu.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};bU.exports=Mu});var SU=v(($Ee,_U)=>{l();var qie=vs(),iS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Uu(t){this.mode=qie.ALPHANUMERIC,this.data=t}Uu.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Uu.prototype.getLength=function(){return this.data.length};Uu.prototype.getBitsLength=function(){return Uu.getBitsLength(this.data.length)};Uu.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=iS.indexOf(this.data[r])*45;n+=iS.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(iS.indexOf(this.data[r]),6)};_U.exports=Uu});var CU=v((YEe,TU)=>{"use strict";l();TU.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var NU=v((XEe,xU)=>{l();var Vie=CU(),Hie=vs();function qu(t){this.mode=Hie.BYTE,typeof t=="string"&&(t=Vie(t)),this.data=new Uint8Array(t)}qu.getBitsLength=function(e){return e*8};qu.prototype.getLength=function(){return this.data.length};qu.prototype.getBitsLength=function(){return qu.getBitsLength(this.data.length)};qu.prototype.write=function(t){for(let e=0,r=this.data.length;e{l();var kie=vs(),Gie=ws();function Vu(t){this.mode=kie.KANJI,this.data=t}Vu.getBitsLength=function(e){return e*13};Vu.prototype.getLength=function(){return this.data.length};Vu.prototype.getBitsLength=function(){return Vu.getBitsLength(this.data.length)};Vu.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` -Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};OU.exports=Vu});var PU=v((rve,sS)=>{"use strict";l();var pf={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=pf.PriorityQueue.make();s.push(e,0);for(var o,a,u,c,f,d,g,m,y;!s.empty();){o=s.pop(),a=o.value,c=o.cost,f=t[a]||{};for(u in f)f.hasOwnProperty(u)&&(d=f[u],g=c+d,m=i[u],y=typeof i[u]>"u",(y||m>g)&&(i[u]=g,s.push(u,g),n[u]=a))}if(typeof r<"u"&&typeof i[r]>"u"){var A=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(A)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=pf.single_source_shortest_paths(t,e,r);return pf.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=pf.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof sS<"u"&&(sS.exports=pf)});var VU=v(Hu=>{l();var je=vs(),LU=IU(),FU=SU(),MU=NU(),UU=DU(),gf=eS(),jy=ws(),jie=PU();function RU(t){return unescape(encodeURIComponent(t)).length}function yf(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function qU(t){let e=yf(gf.NUMERIC,je.NUMERIC,t),r=yf(gf.ALPHANUMERIC,je.ALPHANUMERIC,t),n,i;return jy.isKanjiModeEnabled()?(n=yf(gf.BYTE,je.BYTE,t),i=yf(gf.KANJI,je.KANJI,t)):(n=yf(gf.BYTE_KANJI,je.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function oS(t,e){switch(e){case je.NUMERIC:return LU.getBitsLength(t);case je.ALPHANUMERIC:return FU.getBitsLength(t);case je.KANJI:return UU.getBitsLength(t);case je.BYTE:return MU.getBitsLength(t)}}function Qie(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function zie(t){let e=[];for(let r=0;r{l();var zy=ws(),aS=My(),$ie=XM(),Kie=eU(),Yie=tU(),Jie=iU(),lS=sU(),fS=Y_(),Xie=lU(),Qy=mU(),Zie=AU(),ese=vs(),uS=VU();function tse(t,e){let r=t.size,n=Jie.getPositions(e);for(let i=0;i=0&&a<=6&&(u===0||u===6)||u>=0&&u<=6&&(a===0||a===6)||a>=2&&a<=4&&u>=2&&u<=4?t.set(s+a,o+u,!0,!0):t.set(s+a,o+u,!1,!0))}}function rse(t){let e=t.size;for(let r=8;r>a&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function cS(t,e,r){let n=t.size,i=Zie.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function sse(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let u=0;u<2;u++)if(!t.isReserved(i,a-u)){let c=!1;o>>s&1)===1),t.set(i,a-u,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function ose(t,e,r){let n=new $ie;r.forEach(function(u){n.put(u.mode.bit,4),n.put(u.getLength(),ese.getCharCountIndicator(u.mode,t)),u.write(n)});let i=zy.getSymbolTotalCodewords(t),s=fS.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let u=0;u=7&&ise(u,e),sse(u,o),isNaN(n)&&(n=lS.getBestMask(u,cS.bind(null,u,r))),lS.applyMask(n,u),cS(u,r,n),{modules:u,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}HU.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=aS.M,i,s;return typeof r<"u"&&(n=aS.from(r.errorCorrectionLevel,aS.M),i=Qy.from(r.version),s=lS.from(r.maskPattern),r.toSJISFunc&&zy.setToSJISFunction(r.toSJISFunc)),use(e,i,n,s)}});var dS=v(So=>{l();function GU(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}So.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:GU(e.color.dark||"#000000ff"),light:GU(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};So.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};So.getImageWidth=function(e,r){let n=So.getScale(e,r);return Math.floor((e+r.margin*2)*n)};So.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=So.getScale(i,n),a=Math.floor((i+n.margin*2)*o),u=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=u&&d>=u&&f{l();var hS=dS();function cse(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function lse(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Wy.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=lse()),i=hS.getOptions(i);let o=hS.getImageWidth(e.modules.size,i),a=s.getContext("2d"),u=a.createImageData(o,o);return hS.qrToImageData(u.data,e,i),cse(a,s,o),a.putImageData(u,0,0),s};Wy.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Wy.render(e,r,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var WU=v(zU=>{l();var fse=dS();function QU(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function pS(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function dse(t,e,r){let n="",i=0,s=!1,o=0;for(let a=0;a0&&u>0&&t[a-1]||(n+=s?pS("M",u+r,.5+c+r):pS("m",i,0),i=0,s=!1),u+1':"",c="',f='viewBox="0 0 '+a+" "+a+'"',g=''+u+c+` -`;return typeof n=="function"&&n(null,g),g}});var KU=v(mf=>{l();var hse=KM(),gS=kU(),$U=jU(),pse=WU();function yS(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!hse())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(u,c){try{let f=gS.create(r,n);u(t(f,e,n))}catch(f){c(f)}})}try{let u=gS.create(r,n);i(null,t(u,e,n))}catch(u){i(u)}}mf.create=gS.create;mf.toCanvas=yS.bind(null,$U.render);mf.toDataURL=yS.bind(null,$U.renderToDataURL);mf.toString=yS.bind(null,function(t,e,r){return pse.render(t,r)})});var o4=v(bs=>{"use strict";l();var Sse=bs&&bs.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),s4=bs&&bs.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Sse(e,t,r)};Object.defineProperty(bs,"__esModule",{value:!0});s4(Tu(),bs);s4(f_(),bs)});l();var xse=be(Vm(),1),Nse=be(vE(),1),Ose=be(bE(),1),Dse=be(pt(),1),Pse=be(ha(),1),Rse=be(Yr(),1),Bse=be(Yn(),1),Lse=be(Ih(),1),Fse=be(Dv(),1),Mse=be(qc(),1),Use=be(Wh(),1),x4=be(Ii(),1),jn=be(Ec(),1),N4=be(tc(),1),O4=be(ko(),1),qse=be(Rv(),1),Vse=be(Mv(),1);l();l();var A2=be(Vv(),1);l();l();var $h="elvenjs_state",w2="https://devnet-api.multiversx.com";var Gi="/dapp/init",Kh="devnet",E2="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",v2=["wss://relay.walletconnect.com"],Zt={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var ve={get(t){let e=localStorage.getItem($h);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem($h,JSON.stringify(r))},clear(){localStorage.removeItem($h)}};var Yh=async()=>{let t=A2.ExtensionProvider.getInstance();try{let e=await t.init(),r=ve.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var bS=be(Vv(),1),IS=be(Yl(),1),_S=be(Tu(),1),C4=be(F_(),1),i0=be(Wh(),1);l();var TM=be(Yl(),1);l();l();var Ee=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};l();var SM=(q=>(q.onLoginStart="onLoginStart",q.onLoginSuccess="onLoginSuccess",q.onLoginFailure="onLoginFailure",q.onLogoutStart="onLogoutStart",q.onLogoutSuccess="onLogoutSuccess",q.onLogoutFailure="onLogoutFailure",q.onQrPending="onQrPending",q.onQrLoaded="onQrLoaded",q.onTxStart="onTxStart",q.onTxSent="onTxSent",q.onTxFinalized="onTxFinalized",q.onTxFailure="onTxFailure",q.onSignMsgStart="onSignMsgStart",q.onSignMsgFinalized="onSignMsgFinalized",q.onSignMsgFailure="onSignMsgFailure",q.onQueryStart="onQueryStart",q.onQueryFinalized="onQueryFinalized",q.onQueryFailure="onQueryFailure",q))(SM||{}),M_=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(M_||{}),mie=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(mie||{}),wie=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(wie||{});l();var Et=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Pu=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");Ee.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(ve.clear(),Ee.run("onLogoutSuccess")),e}catch(e){let r=Et(e);console.warn(`Something went wrong trying to logout the user: ${r}`),Ee.run("onLogoutFailure",r)}};l();function Cy(t){return t[Math.floor(Math.random()*t.length)]}var CM=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Pu(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=Cy(t.initOptions.walletConnectV2RelayAddresses),n=new TM.WalletConnectV2Provider(e,Zt[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};l();var By=be(pt(),1),UM=be(xM(),1),qM=be(OM(),1),VM=be(Q_(),1),HM=be(FM(),1),kM=be(Mv(),1),GM=be(MM(),1),jM=be(Vc(),1);var Ly=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||Kh,this.apiUrl=e||Zt[this.chainType]?.apiAddress,this.apiTimeout=n||Zt[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),a=await o.json();if(!o.ok){let u=a?.error||o.status;return clearTimeout(i),Promise.reject(u)}return clearTimeout(i),a}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let a=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),u=await a.json();if(!a.ok){let c=u?.error||a.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),u}catch(a){this.handleApiError(a,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new By.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new UM.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new By.Address(r.sender),receiver:new By.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:h.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:qM.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:VM.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:HM.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new jM.Query({address:e,func:r,args:n,value:i,caller:s}),a=new GM.ContractQueryRequest(o).toHttpRequest(),u=await this.apiPost("query",a);return kM.ContractQueryResponse.fromHttpResponse(u)}catch(o){this.handleApiError(o,"query")}}};l();l();var Fu=()=>new Date().setHours(new Date().getHours()+24),Fy=t=>Date.now()>t;l();var QM=be(pt(),1),zM=be(ha(),1);var Ao=async t=>{let e=ve.get("address"),r=ve.get("expires");if(!(r&&Fy(r))&&e&&t.networkProvider){let i=new QM.Address(e),s=new zM.Account(i);try{let o=await t.networkProvider.getAccount(i),a=await t.networkProvider.getGuardianData(i);ve.set("address",e),ve.set("activeGuardian",a.guarded&&a.activeGuardian?.address?a.activeGuardian.address:""),ve.set("nonce",o.nonce.valueOf()),ve.set("balance",o.balance.toString()),s.update(o)}catch(o){let a=Et(o);console.warn(`Something went wrong trying to synchronize the user account: ${a}`)}}};var WM=async(t,e,r,n="/")=>{let i=await Yh(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(u){let c=Et(u);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:a}=i.account;if(ve.set("loginToken",e),a&&ve.set("signature",a),t.networkProvider&&a)try{let u=await i.getAddress();if(!u)throw new Error("Canceled!");ve.set("address",u),ve.set("loginMethod","browser-extension"),ve.set("expires",Fu()),await Ao(t);let c=r.getToken(u,e,a);return ve.set("accessToken",c),Ee.run("onLoginSuccess"),i}catch(u){throw new Error(`Something went wrong trying to synchronize the user account: ${u?.message}`)}};l();l();var YU=be(KU(),1),JU=be(Yl(),1);var gse=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},yse=t=>{let e=`${E2}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},mse=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},wse=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},mS={},Ese=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",mS[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:mS[t.topic].signal}),r},$y={},vse=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=Ese(t,e);return n.appendChild(s),$y[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:$y[t.topic].signal}),n},Ase=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},bse=t=>{if(!t)return;document.getElementById(t)?.remove()},Ise=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),_se=async t=>t?await YU.default.toString(t,{type:"svg"}):void 0,XU=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await _se(e),o;if(s&&(o=gse(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),Ise()&&i.appendChild(yse(e))),i&&r instanceof JU.WalletConnectV2Provider){let a=r.pairings,u=async f=>{try{f&&(await r.logout({topic:f}),bse(f))}catch(d){let g=Et(d);console.warn(`Something went wrong trying to remove the existing pairing: ${g}`)}finally{$y[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(Ase()),await r.login({approval:d,token:n})}catch(d){let g=Et(d);console.warn(`Something went wrong trying to login the user: ${g}`)}finally{for(let d of Object.values($y))d?.abort();for(let d of Object.values(mS))d?.abort()}};if(a&&a.length>0){let f=mse();i.appendChild(f);let d=wse();f.appendChild(d);for(let g of a){let m=vse(g,u,c);f.appendChild(m)}}}return i};var Ky=be(Yl(),1);var ZU=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=Cy(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof Ky.WalletConnectV2Provider){let u=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();ve.set("address",u),ve.set("loginMethod","mobile"),ve.set("expires",Fu()),await Ao(t),c&&ve.set("signature",c),ve.set("loginToken",e);let f=r.getToken(u,e,c);ve.set("accessToken",f),Ee.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof Ky.WalletConnectV2Provider&&await Pu(t)},onClientEvent:u=>{console.log("wc2 session event: ",u)}},a=new Ky.WalletConnectV2Provider(o,Zt[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(a){t.dappProvider=a,Ee.run("onQrPending"),await a.init();let{uri:u,approval:c}=await a.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${u}&token=${e}`:u;return n&&f&&(s=await XU(n,f,a,e),Ee.run("onQrLoaded")),await a.login({approval:c,token:e}),a}}catch(u){let c=Et(u);console.warn(`Something went wrong trying to login the user: ${c}`),Ee.run("onLoginFailure",c)}};l();var e4=be(Tu(),1);var wS=async(t,e,r,n)=>{let i=new e4.WalletProvider(`${t}${Gi}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return ve.set("loginMethod",Zt[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),ve.set("expires",Fu()),ve.set("loginToken",e),i}catch(a){let u=Et(a);console.warn(`Something went wrong trying to login the user: ${u}`),ve.set("loginMethod",""),Ee.run("onLoginFailure",u)}};l();var Ar=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};l();var t4=be(Tu(),1);var r4=be(F_(),1),ES=async(t,e)=>{let r=Ar("signature"),n=Ar("address"),i=ve.get("address"),s=ve.get("loginToken");if(r&&ve.set("signature",r),n||i){n&&(ve.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new t4.WalletProvider(`${t}${Gi}`);if(r&&e&&n){let u=new r4.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);ve.set("accessToken",u)}return o}};l();var n4=be(ha(),1),i4=be(Ih(),1);var Yy=async(t,e)=>{Ee.run("onTxSent",t),await new i4.TransactionWatcher(e).awaitCompleted(t);let n=t.getSender(),i=new n4.Account(n),s=await e.getAccount(n);i.update(s),ve.set("address",i.address.bech32()),ve.set("balance",i.balance.toString()),Ee.run("onTxFinalized",t)};l();var ku=be(o4(),1),u4=be(Yr(),1);l();var a4=be(ha(),1);var Jy=t=>{let e=t.getSender(),r=new a4.Account(e),n=t.getNonce().valueOf();r.incrementNonce(),ve.set("nonce",n+1)};var c4=async(t,e,r,n)=>{if(Ar(ku.WALLET_PROVIDER_CALLBACK_PARAM)===ku.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=ve.get("activeGuardian"),o=ve.get("loginMethod"),a=Ar("hasWebWalletGuardianSign"),u;if("getTransactionsFromWalletUrl"in t){if(u=t.getTransactionsFromWalletUrl()?.[0],!u)return;o==="web-wallet"&&(u.data=h.Buffer.from(u.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&a&&(u=new ku.WalletProvider(`${r}${Gi}`).getTransactionsFromWalletUrl()?.[0]);if(u){let c=u4.Transaction.fromPlainObject(u);c.setNonce(n),Jy(c);try{Ee.run("onTxStart",c),await e.sendTransaction(c),await Yy(c,e)}catch(f){let g=`Getting transaction information failed! ${Et(f)}`;throw Ee.run("onTxFailure",c,g),new Error(g)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};l();var Xy=be(xc(),1),l4=be(pt(),1),f4=be(Tu(),1);var d4=t=>{let e=ve.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(Xy.TransactionVersion.withTxOptions()),t.setOptions(Xy.TransactionOptions.withOptions(r)),t.setGuardian(l4.Address.fromBech32(e))}return t},h4=async(t,e)=>{let r=new f4.WalletProvider(`${e}${Gi}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},p4=t=>{let e=ve.get("activeGuardian");return!(!ve.get("address")||!e||t.isGuardedTransaction())};l();var g4=()=>{let t=!Ar("walletProviderStatus"),e=Ar("status")==="signed",r=Ar("message"),n=Ar("signature");t&&e&&r&&n&&(Ee.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};l();var AS=be(Yr(),1);l();var y4=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(y4||{}),m4=(a=>(a.handshakeResponse="HANDSHAKE_RESPONSE",a.loginResponse="LOGIN_RESPONSE",a.disconnectResponse="DISCONNECT_RESPONSE",a.cancelResponse="CANCEL_RESPONSE",a.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",a.signMessageResponse="SIGN_MESSAGE_RESPONSE",a.noneResponse="NONE_RESPONSE",a))(m4||{}),vS={...m4,...y4},w4=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))(w4||{}),E4=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(E4||{}),To={...E4,...w4};l();var v4=typeof window<"u"?window:{},A4=()=>v4.ReactNativeWebView?"reactNative":v4.webkit?"ios":"web",Co=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",Zy=t=>Object.prototype.toString.call(t)==="[object String]";l();var e0={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,Co()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:To.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:To.signTransactionsRequest,message:t}),Co())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:To.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:To.signMessageRequest,message:t}),Co())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:To.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:To.logoutRequest}),Co())}};var t0=A4(),r0="message",b4=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=Co()&&t0!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(r0,e),window&&window.addEventListener(r0,e)},Is=class{constructor(){}async logout(){return e0.logout[t0](),new Promise(e=>{e(!0)})}async signMessage(e){try{return e0.signMessage[t0](e),await new Promise((n,i)=>{window.signMessageResponse=(o,a)=>{if(a){i(a),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:a,type:u}=o;if(u===vS.signMessageResponse&&a!=null){let{signedMessage:c,error:f}=a;f?i(f):n(c)}document?.removeEventListener(r0,s)}b4(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return e0.signTransactions[t0](r),await new Promise((i,s)=>{window.transactionsSigned=(a,u)=>{if(a=JSON.parse(a),u){s(u),window.transactionsSigned=null;return}i(a.map(c=>AS.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(a){let{message:u,type:c}=a;if(c===vS.signTransactionsResponse){let{transactions:f,error:d}=u;try{d?s(d):i(f.map(g=>AS.Transaction.fromPlainObject(g)))}catch{s("Unable to sign")}}document&&document.removeEventListener(r0,o)}b4(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};l();l();l();function Cse(t){try{let e=atob(t),r=btoa(e),n=h.Buffer.from(t,"base64").toString(),i=h.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Gu(t){return Cse(t)?atob(t):t}l();var I4=t=>{if(!t||!Zy(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Gu(s)),a=Gu(r);return{ttl:Number(i),extraInfo:o,origin:a,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var _4=t=>{if(!t||!Zy(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Gu(r),o=Gu(n),a=I4(o);if(!a)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let u={...a,address:s,body:o,signature:i};return a.extraInfo?.timestamp||delete u.extraInfo,u}catch{return null}};function S4(t,e){let r=_4(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(ve.set("loginToken",s),ve.set("accessToken",t),ve.set("signature",n),ve.set("address",i),ve.set("loginMethod","x-portal-hub"),e.dappProvider=new Is)}l();var T4=t=>{t.onLoginStart&&Ee.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&Ee.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&Ee.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&Ee.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&Ee.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&Ee.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&Ee.set("onQrPending",t.onQrPending),t.onQrLoaded&&Ee.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&Ee.set("onTxStart",t.onTxStart),t.onTxSent&&Ee.set("onTxSent",t.onTxSent),t.onTxFinalized&&Ee.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&Ee.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&Ee.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&Ee.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&Ee.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&Ee.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&Ee.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&Ee.set("onQueryFailure",t.onQueryFailure)};l();var n0=async t=>{Ee.run("onLoginStart");try{await t(()=>{Ee.run("onLoginSuccess")})}catch(e){let r=Et(e);console.warn(`Something went wrong trying to login the user: ${r}`),Ee.run("onLoginFailure",r)}};var SS=class{static async init(e){let r=ve.get();if(r.expires&&Fy(r.expires)){ve.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:Kh,apiUrl:w2,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:v2,...e},this.networkProvider=new Ly(this.initOptions),T4(this.initOptions);let n=Ar("accessToken");n&&await n0(async s=>{S4(n,this),await Ao(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&Ar("address"))&&r?.loginMethod&&(await n0(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await Yh()),r.loginMethod==="mobile"&&(this.dappProvider=await CM(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new Is),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await ES(Zt[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await ES(Zt[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Ao(this),s()}),this.initOptions?.chainType&&(await c4(this.dappProvider,this.networkProvider,Zt[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),g4()))}static async login(e,r){if(!Object.values(M_).includes(e)){let i="Wrong login method!";throw Ee.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw Ee.run("onLoginFailure",i),new Error(i)}await n0(async()=>{let i=new C4.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await WM(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await ZU(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await wS(Zt[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await wS(Zt[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Pu(this);return this.dappProvider=void 0,e}catch(e){let r=Et(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw Ee.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw Ee.run("onTxFailure",e,n),new Error(n)}let r=d4(e);try{Ee.run("onTxStart",e);let n=ve.get();if(e.setNonce(n.nonce),this.dappProvider instanceof bS.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof IS.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof Is&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof _S.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=p4(r);if(i||Jy(r),i&&this.initOptions?.chainType){await h4(r,Zt[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await Yy(r,this.networkProvider)}}catch(n){let i=Et(n);throw Ee.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw Ee.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw Ee.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(Ee.run("onSignMsgStart",e),this.dappProvider instanceof bS.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new i0.SignableMessage({message:h.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof IS.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new i0.SignableMessage({message:h.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof Is&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof _S.WalletProvider){let s=a=>encodeURIComponent(a).replace(/[!'()*]/g,u=>`%${u.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new i0.SignableMessage({message:h.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=ve.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&Ee.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Et(i);throw Ee.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{Ee.run("onQueryStart",o);let a=await this.networkProvider.queryContract(o);return Ee.run("onQueryFinalized",a),a}catch(a){let u=Et(a);throw Ee.run("onQueryFinalized",o,u),new Error(`Smart contract query failed! ${u}`)}}static{this.storage=ve}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,Ee.clear()}}};var export_Account=Pse.Account;var export_Address=Dse.Address;var export_AddressType=O4.AddressType;var export_AddressValue=O4.AddressValue;var export_BigUIntType=jn.BigUIntType;var export_BigUIntValue=jn.BigUIntValue;var export_BooleanType=N4.BooleanType;var export_BooleanValue=N4.BooleanValue;var export_BytesType=x4.BytesType;var export_BytesValue=x4.BytesValue;var export_ContractFunction=Mse.ContractFunction;var export_ContractQueryResponse=Vse.ContractQueryResponse;var export_GasEstimator=Ose.GasEstimator;var export_QueryArguments=qse.QueryArguments;var export_SignableMessage=Use.SignableMessage;var export_SmartContract=Fse.SmartContract;var export_TokenTransfer=xse.TokenTransfer;var export_Transaction=Rse.Transaction;var export_TransactionPayload=Bse.TransactionPayload;var export_TransactionWatcher=Lse.TransactionWatcher;var export_TransferTransactionsFactory=Nse.TransferTransactionsFactory;var export_U16Type=jn.U16Type;var export_U16Value=jn.U16Value;var export_U32Type=jn.U32Type;var export_U32Value=jn.U32Value;var export_U64Type=jn.U64Type;var export_U64Value=jn.U64Value;var export_U8Type=jn.U8Type;var export_U8Value=jn.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractFunction as ContractFunction,export_ContractQueryResponse as ContractQueryResponse,mie as DappCoreWCV2CustomMethodsEnum,SS as ElvenJS,SM as EventStoreEvents,export_GasEstimator as GasEstimator,M_ as LoginMethodsEnum,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContract as SmartContract,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionPayload as TransactionPayload,export_TransactionWatcher as TransactionWatcher,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,wie as WebWalletUrlParamsEnum}; +var init_xor = __esm({ + "node_modules/uint8arrays/esm/src/xor.js"() { + init_shim(); + init_alloc(); + init_as_uint8array(); + } +}); + +// node_modules/uint8arrays/esm/src/index.js +var src_exports = {}; +__export(src_exports, { + compare: () => compare, + concat: () => concat, + equals: () => equals3, + fromString: () => fromString2, + toString: () => toString2, + xor: () => xor +}); +var init_src2 = __esm({ + "node_modules/uint8arrays/esm/src/index.js"() { + init_shim(); + init_compare(); + init_concat(); + init_equals(); + init_from_string(); + init_to_string(); + init_xor(); + } +}); + +// node_modules/@walletconnect/relay-api/dist/index.es.js +var index_es_exports3 = {}; +__export(index_es_exports3, { + RELAY_JSONRPC: () => C2, + isPublishMethod: () => c3, + isPublishParams: () => h3, + isPublishRequest: () => P, + isSubscribeMethod: () => b2, + isSubscribeParams: () => a, + isSubscribeRequest: () => R, + isSubscriptionMethod: () => m2, + isSubscriptionParams: () => d2, + isSubscriptionRequest: () => S2, + isUnsubscribeMethod: () => o, + isUnsubscribeParams: () => p2, + isUnsubscribeRequest: () => _3, + parsePublishRequest: () => q, + parseSubscribeRequest: () => g2, + parseSubscriptionRequest: () => k3, + parseUnsubscribeRequest: () => E3 +}); +function e(s2, r, i2 = "string") { + if (!s2[r] || typeof s2[r] !== i2) + throw new Error(`Missing or invalid "${r}" param`); +} +function l3(s2, r) { + let i2 = true; + return r.forEach((t) => { + t in s2 || (i2 = false); + }), i2; +} +function f2(s2, r) { + return Array.isArray(s2) ? s2.length === r : Object.keys(s2).length === r; +} +function w2(s2, r) { + return Array.isArray(s2) ? s2.length >= r : Object.keys(s2).length >= r; +} +function u(s2, r, i2) { + return (i2.length ? w2(s2, r.length) : f2(s2, r.length)) ? l3(s2, r) : false; +} +function n2(s2, r, i2 = "_") { + const t = s2.split(i2); + return t[t.length - 1].trim().toLowerCase() === r.trim().toLowerCase(); +} +function R(s2) { + return b2(s2.method) && a(s2.params); +} +function b2(s2) { + return n2(s2, "subscribe"); +} +function a(s2) { + return u(s2, ["topic"], []); +} +function P(s2) { + return c3(s2.method) && h3(s2.params); +} +function c3(s2) { + return n2(s2, "publish"); +} +function h3(s2) { + return u(s2, ["message", "topic", "ttl"], ["prompt", "tag"]); +} +function _3(s2) { + return o(s2.method) && p2(s2.params); +} +function o(s2) { + return n2(s2, "unsubscribe"); +} +function p2(s2) { + return u(s2, ["id", "topic"], []); +} +function S2(s2) { + return m2(s2.method) && d2(s2.params); +} +function m2(s2) { + return n2(s2, "subscription"); +} +function d2(s2) { + return u(s2, ["id", "data"], []); +} +function g2(s2) { + if (!b2(s2.method)) + throw new Error("JSON-RPC Request has invalid subscribe method"); + if (!a(s2.params)) + throw new Error("JSON-RPC Request has invalid subscribe params"); + const r = s2.params; + return e(r, "topic"), r; +} +function q(s2) { + if (!c3(s2.method)) + throw new Error("JSON-RPC Request has invalid publish method"); + if (!h3(s2.params)) + throw new Error("JSON-RPC Request has invalid publish params"); + const r = s2.params; + return e(r, "topic"), e(r, "message"), e(r, "ttl", "number"), r; +} +function E3(s2) { + if (!o(s2.method)) + throw new Error("JSON-RPC Request has invalid unsubscribe method"); + if (!p2(s2.params)) + throw new Error("JSON-RPC Request has invalid unsubscribe params"); + const r = s2.params; + return e(r, "id"), r; +} +function k3(s2) { + if (!m2(s2.method)) + throw new Error("JSON-RPC Request has invalid subscription method"); + if (!d2(s2.params)) + throw new Error("JSON-RPC Request has invalid subscription params"); + const r = s2.params; + return e(r, "id"), e(r, "data"), r; +} +var C2; +var init_index_es3 = __esm({ + "node_modules/@walletconnect/relay-api/dist/index.es.js"() { + init_shim(); + C2 = { waku: { publish: "waku_publish", batchPublish: "waku_batchPublish", subscribe: "waku_subscribe", batchSubscribe: "waku_batchSubscribe", subscription: "waku_subscription", unsubscribe: "waku_unsubscribe", batchUnsubscribe: "waku_batchUnsubscribe", batchFetchMessages: "waku_batchFetchMessages" }, irn: { publish: "irn_publish", batchPublish: "irn_batchPublish", subscribe: "irn_subscribe", batchSubscribe: "irn_batchSubscribe", subscription: "irn_subscription", unsubscribe: "irn_unsubscribe", batchUnsubscribe: "irn_batchUnsubscribe", batchFetchMessages: "irn_batchFetchMessages" }, iridium: { publish: "iridium_publish", batchPublish: "iridium_batchPublish", subscribe: "iridium_subscribe", batchSubscribe: "iridium_batchSubscribe", subscription: "iridium_subscription", unsubscribe: "iridium_unsubscribe", batchUnsubscribe: "iridium_batchUnsubscribe", batchFetchMessages: "iridium_batchFetchMessages" } }; + } +}); + +// node_modules/@walletconnect/utils/dist/index.cjs.js +var require_index_cjs2 = __commonJS({ + "node_modules/@walletconnect/utils/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var Ro = require_detect_browser(); + var tr = require_cjs(); + var er = require_cjs3(); + var Co = require_cjs4(); + var Oo = require_query_string(); + var fn = require_chacha20poly1305(); + var Po = require_hkdf(); + var on = require_random(); + var ci = require_sha256(); + var To = require_x25519(); + var Rt = (init_src2(), __toCommonJS(src_exports)); + var Fo = (init_index_es3(), __toCommonJS(index_es_exports3)); + function sn(e2) { + if (e2 && e2.__esModule) + return e2; + var t = /* @__PURE__ */ Object.create(null); + return e2 && Object.keys(e2).forEach(function(r) { + if (r !== "default") { + var i2 = Object.getOwnPropertyDescriptor(e2, r); + Object.defineProperty(t, r, i2.get ? i2 : { enumerable: true, get: function() { + return e2[r]; + } }); + } + }), t.default = e2, Object.freeze(t); + } + var Ir = sn(Oo); + var an = sn(To); + var _r = ":"; + function un(e2) { + const [t, r] = e2.split(_r); + return { namespace: t, reference: r }; + } + function hn(e2) { + const { namespace: t, reference: r } = e2; + return [t, r].join(_r); + } + function li(e2) { + const [t, r, i2] = e2.split(_r); + return { namespace: t, reference: r, address: i2 }; + } + function cn(e2) { + const { namespace: t, reference: r, address: i2 } = e2; + return [t, r, i2].join(_r); + } + function di(e2, t) { + const r = []; + return e2.forEach((i2) => { + const n3 = t(i2); + r.includes(n3) || r.push(n3); + }), r; + } + function ln(e2) { + const { address: t } = li(e2); + return t; + } + function dn(e2) { + const { namespace: t, reference: r } = li(e2); + return hn({ namespace: t, reference: r }); + } + function Do(e2, t) { + const { namespace: r, reference: i2 } = un(t); + return cn({ namespace: r, reference: i2, address: e2 }); + } + function Uo(e2) { + return di(e2, ln); + } + function pn(e2) { + return di(e2, dn); + } + function ko(e2, t = []) { + const r = []; + return Object.keys(e2).forEach((i2) => { + if (t.length && !t.includes(i2)) + return; + const n3 = e2[i2]; + r.push(...n3.accounts); + }), r; + } + function qo(e2, t = []) { + const r = []; + return Object.keys(e2).forEach((i2) => { + if (t.length && !t.includes(i2)) + return; + const n3 = e2[i2]; + r.push(...pn(n3.accounts)); + }), r; + } + function Ko(e2, t = []) { + const r = []; + return Object.keys(e2).forEach((i2) => { + if (t.length && !t.includes(i2)) + return; + const n3 = e2[i2]; + r.push(...Br(i2, n3)); + }), r; + } + function Br(e2, t) { + return e2.includes(":") ? [e2] : t.chains || []; + } + var Ho = Object.defineProperty; + var vn = Object.getOwnPropertySymbols; + var Lo = Object.prototype.hasOwnProperty; + var zo = Object.prototype.propertyIsEnumerable; + var gn = (e2, t, r) => t in e2 ? Ho(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var mn = (e2, t) => { + for (var r in t || (t = {})) + Lo.call(t, r) && gn(e2, r, t[r]); + if (vn) + for (var r of vn(t)) + zo.call(t, r) && gn(e2, r, t[r]); + return e2; + }; + var An = "ReactNative"; + var Kt = { reactNative: "react-native", node: "node", browser: "browser", unknown: "unknown" }; + var Rr = " "; + var jo = ":"; + var bn = "/"; + var pi = 2; + var Vo = 1e3; + var yn = "js"; + function vi() { + return typeof import_process.default < "u" && typeof import_process.default.versions < "u" && typeof import_process.default.versions.node < "u"; + } + function rr() { + return !er.getDocument() && !!er.getNavigator() && navigator.product === An; + } + function vr() { + return !vi() && !!er.getNavigator() && !!er.getDocument(); + } + function Ge() { + return rr() ? Kt.reactNative : vi() ? Kt.node : vr() ? Kt.browser : Kt.unknown; + } + function Qo() { + var e2; + try { + return rr() && typeof global < "u" && typeof (global == null ? void 0 : global.Application) < "u" ? (e2 = global.Application) == null ? void 0 : e2.applicationId : void 0; + } catch { + return; + } + } + function wn(e2, t) { + let r = Ir.parse(e2); + return r = mn(mn({}, r), t), e2 = Ir.stringify(r), e2; + } + function Jo() { + return Co.getWindowMetadata() || { name: "", description: "", url: "", icons: [""] }; + } + function Yo(e2, t) { + var r; + const i2 = Ge(), n3 = { protocol: e2, version: t, env: i2 }; + return i2 === "browser" && (n3.host = ((r = er.getLocation()) == null ? void 0 : r.host) || "unknown"), n3; + } + function xn() { + if (Ge() === Kt.reactNative && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u") { + const { OS: r, Version: i2 } = global.Platform; + return [r, i2].join("-"); + } + const e2 = Ro.detect(); + if (e2 === null) + return "unknown"; + const t = e2.os ? e2.os.replace(" ", "").toLowerCase() : "unknown"; + return e2.type === "browser" ? [t, e2.name, e2.version].join("-") : [t, e2.version].join("-"); + } + function Mn() { + var e2; + const t = Ge(); + return t === Kt.browser ? [t, ((e2 = er.getLocation()) == null ? void 0 : e2.host) || "unknown"].join(":") : t; + } + function En(e2, t, r) { + const i2 = xn(), n3 = Mn(); + return [[e2, t].join("-"), [yn, r].join("-"), i2, n3].join("/"); + } + function Go({ protocol: e2, version: t, relayUrl: r, sdkVersion: i2, auth: n3, projectId: o2, useOnCloseEvent: h5, bundleId: p3 }) { + const b4 = r.split("?"), g3 = En(e2, t, i2), w4 = { auth: n3, ua: g3, projectId: o2, useOnCloseEvent: h5 || void 0, origin: p3 || void 0 }, y4 = wn(b4[1] || "", w4); + return b4[0] + "?" + y4; + } + function Wo(e2) { + let t = (e2.match(/^[^:]+(?=:\/\/)/gi) || [])[0]; + const r = typeof t < "u" ? e2.split("://")[1] : e2; + return t = t === "wss" ? "https" : "http", [t, r].join("://"); + } + function Xo(e2, t, r) { + if (!e2[t] || typeof e2[t] !== r) + throw new Error(`Missing or invalid "${t}" param`); + } + function Sn(e2, t = pi) { + return Nn(e2.split(bn), t); + } + function Zo(e2) { + return Sn(e2).join(Rr); + } + function Ie(e2, t) { + return e2.filter((r) => t.includes(r)).length === e2.length; + } + function Nn(e2, t = pi) { + return e2.slice(Math.max(e2.length - t, 0)); + } + function $o(e2) { + return Object.fromEntries(e2.entries()); + } + function ts(e2) { + return new Map(Object.entries(e2)); + } + function es(e2, t) { + const r = {}; + return Object.keys(e2).forEach((i2) => { + r[i2] = t(e2[i2]); + }), r; + } + var rs = (e2) => e2; + function In(e2) { + return e2.trim().replace(/^\w/, (t) => t.toUpperCase()); + } + function is(e2) { + return e2.split(Rr).map((t) => In(t)).join(Rr); + } + function ns(e2 = tr.FIVE_MINUTES, t) { + const r = tr.toMiliseconds(e2 || tr.FIVE_MINUTES); + let i2, n3, o2; + return { resolve: (h5) => { + o2 && i2 && (clearTimeout(o2), i2(h5)); + }, reject: (h5) => { + o2 && n3 && (clearTimeout(o2), n3(h5)); + }, done: () => new Promise((h5, p3) => { + o2 = setTimeout(() => { + p3(new Error(t)); + }, r), i2 = h5, n3 = p3; + }) }; + } + function fs(e2, t, r) { + return new Promise(async (i2, n3) => { + const o2 = setTimeout(() => n3(new Error(r)), t); + try { + const h5 = await e2; + i2(h5); + } catch (h5) { + n3(h5); + } + clearTimeout(o2); + }); + } + function gi(e2, t) { + if (typeof t == "string" && t.startsWith(`${e2}:`)) + return t; + if (e2.toLowerCase() === "topic") { + if (typeof t != "string") + throw new Error('Value must be "string" for expirer target type: topic'); + return `topic:${t}`; + } else if (e2.toLowerCase() === "id") { + if (typeof t != "number") + throw new Error('Value must be "number" for expirer target type: id'); + return `id:${t}`; + } + throw new Error(`Unknown expirer target type: ${e2}`); + } + function os(e2) { + return gi("topic", e2); + } + function ss(e2) { + return gi("id", e2); + } + function as(e2) { + const [t, r] = e2.split(":"), i2 = { id: void 0, topic: void 0 }; + if (t === "topic" && typeof r == "string") + i2.topic = r; + else if (t === "id" && Number.isInteger(Number(r))) + i2.id = Number(r); + else + throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`); + return i2; + } + function us(e2, t) { + return tr.fromMiliseconds((t || Date.now()) + tr.toMiliseconds(e2)); + } + function hs(e2) { + return Date.now() >= tr.toMiliseconds(e2); + } + function cs(e2, t) { + return `${e2}${t ? `:${t}` : ""}`; + } + function ge(e2 = [], t = []) { + return [.../* @__PURE__ */ new Set([...e2, ...t])]; + } + async function ls2({ id: e2, topic: t, wcDeepLink: r }) { + try { + if (!r) + return; + const i2 = typeof r == "string" ? JSON.parse(r) : r; + let n3 = i2?.href; + if (typeof n3 != "string") + return; + n3.endsWith("/") && (n3 = n3.slice(0, -1)); + const o2 = `${n3}/wc?requestId=${e2}&sessionTopic=${t}`, h5 = Ge(); + h5 === Kt.browser ? o2.startsWith("https://") || o2.startsWith("http://") ? window.open(o2, "_blank", "noreferrer noopener") : window.open(o2, "_self", "noreferrer noopener") : h5 === Kt.reactNative && typeof (global == null ? void 0 : global.Linking) < "u" && await global.Linking.openURL(o2); + } catch (i2) { + console.error(i2); + } + } + async function ds(e2, t) { + try { + return await e2.getItem(t) || (vr() ? localStorage.getItem(t) : void 0); + } catch (r) { + console.error(r); + } + } + function mi(e2, t) { + return e2.filter((r) => t.includes(r)); + } + var _n = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; + function ps(e2) { + var t = e2.default; + if (typeof t == "function") { + var r = function() { + return t.apply(this, arguments); + }; + r.prototype = t.prototype; + } else + r = {}; + return Object.defineProperty(r, "__esModule", { value: true }), Object.keys(e2).forEach(function(i2) { + var n3 = Object.getOwnPropertyDescriptor(e2, i2); + Object.defineProperty(r, i2, n3.get ? n3 : { enumerable: true, get: function() { + return e2[i2]; + } }); + }), r; + } + var Bn = { exports: {} }; + (function(e2) { + (function() { + var t = "input is invalid type", r = "finalize already called", i2 = typeof window == "object", n3 = i2 ? window : {}; + n3.JS_SHA3_NO_WINDOW && (i2 = false); + var o2 = !i2 && typeof self == "object", h5 = !n3.JS_SHA3_NO_NODE_JS && typeof import_process.default == "object" && import_process.default.versions && import_process.default.versions.node; + h5 ? n3 = _n : o2 && (n3 = self); + var p3 = !n3.JS_SHA3_NO_COMMON_JS && true && e2.exports, b4 = !n3.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer < "u", g3 = "0123456789abcdef".split(""), w4 = [31, 7936, 2031616, 520093696], y4 = [4, 1024, 262144, 67108864], S4 = [1, 256, 65536, 16777216], I2 = [6, 1536, 393216, 100663296], N10 = [0, 8, 16, 24], R2 = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648], F = [224, 256, 384, 512], U2 = [128, 256], Q = ["hex", "buffer", "arrayBuffer", "array", "digest"], Bt = { 128: 168, 256: 136 }; + (n3.JS_SHA3_NO_NODE_JS || !Array.isArray) && (Array.isArray = function(u3) { + return Object.prototype.toString.call(u3) === "[object Array]"; + }), b4 && (n3.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView) && (ArrayBuffer.isView = function(u3) { + return typeof u3 == "object" && u3.buffer && u3.buffer.constructor === ArrayBuffer; + }); + for (var J = function(u3, E4, _4) { + return function(B2) { + return new s2(u3, E4, u3).update(B2)[_4](); + }; + }, H = function(u3, E4, _4) { + return function(B2, C3) { + return new s2(u3, E4, C3).update(B2)[_4](); + }; + }, L2 = function(u3, E4, _4) { + return function(B2, C3, D2, P2) { + return f4["cshake" + u3].update(B2, C3, D2, P2)[_4](); + }; + }, Tt = function(u3, E4, _4) { + return function(B2, C3, D2, P2) { + return f4["kmac" + u3].update(B2, C3, D2, P2)[_4](); + }; + }, W = function(u3, E4, _4, B2) { + for (var C3 = 0; C3 < Q.length; ++C3) { + var D2 = Q[C3]; + u3[D2] = E4(_4, B2, D2); + } + return u3; + }, Ot = function(u3, E4) { + var _4 = J(u3, E4, "hex"); + return _4.create = function() { + return new s2(u3, E4, u3); + }, _4.update = function(B2) { + return _4.create().update(B2); + }, W(_4, J, u3, E4); + }, Gt = function(u3, E4) { + var _4 = H(u3, E4, "hex"); + return _4.create = function(B2) { + return new s2(u3, E4, B2); + }, _4.update = function(B2, C3) { + return _4.create(C3).update(B2); + }, W(_4, H, u3, E4); + }, Y = function(u3, E4) { + var _4 = Bt[u3], B2 = L2(u3, E4, "hex"); + return B2.create = function(C3, D2, P2) { + return !D2 && !P2 ? f4["shake" + u3].create(C3) : new s2(u3, E4, C3).bytepad([D2, P2], _4); + }, B2.update = function(C3, D2, P2, O3) { + return B2.create(D2, P2, O3).update(C3); + }, W(B2, L2, u3, E4); + }, Wt = function(u3, E4) { + var _4 = Bt[u3], B2 = Tt(u3, E4, "hex"); + return B2.create = function(C3, D2, P2) { + return new v2(u3, E4, D2).bytepad(["KMAC", P2], _4).bytepad([C3], _4); + }, B2.update = function(C3, D2, P2, O3) { + return B2.create(C3, P2, O3).update(D2); + }, W(B2, Tt, u3, E4); + }, A2 = [{ name: "keccak", padding: S4, bits: F, createMethod: Ot }, { name: "sha3", padding: I2, bits: F, createMethod: Ot }, { name: "shake", padding: w4, bits: U2, createMethod: Gt }, { name: "cshake", padding: y4, bits: U2, createMethod: Y }, { name: "kmac", padding: y4, bits: U2, createMethod: Wt }], f4 = {}, a3 = [], c4 = 0; c4 < A2.length; ++c4) + for (var d3 = A2[c4], m3 = d3.bits, x3 = 0; x3 < m3.length; ++x3) { + var M = d3.name + "_" + m3[x3]; + if (a3.push(M), f4[M] = d3.createMethod(m3[x3], d3.padding), d3.name !== "sha3") { + var l4 = d3.name + m3[x3]; + a3.push(l4), f4[l4] = f4[M]; + } + } + function s2(u3, E4, _4) { + this.blocks = [], this.s = [], this.padding = E4, this.outputBits = _4, this.reset = true, this.finalized = false, this.block = 0, this.start = 0, this.blockCount = 1600 - (u3 << 1) >> 5, this.byteCount = this.blockCount << 2, this.outputBlocks = _4 >> 5, this.extraBytes = (_4 & 31) >> 3; + for (var B2 = 0; B2 < 50; ++B2) + this.s[B2] = 0; + } + s2.prototype.update = function(u3) { + if (this.finalized) + throw new Error(r); + var E4, _4 = typeof u3; + if (_4 !== "string") { + if (_4 === "object") { + if (u3 === null) + throw new Error(t); + if (b4 && u3.constructor === ArrayBuffer) + u3 = new Uint8Array(u3); + else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) + throw new Error(t); + } else + throw new Error(t); + E4 = true; + } + for (var B2 = this.blocks, C3 = this.byteCount, D2 = u3.length, P2 = this.blockCount, O3 = 0, Ct = this.s, T2, q2; O3 < D2; ) { + if (this.reset) + for (this.reset = false, B2[0] = this.block, T2 = 1; T2 < P2 + 1; ++T2) + B2[T2] = 0; + if (E4) + for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) + B2[T2 >> 2] |= u3[O3] << N10[T2++ & 3]; + else + for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) + q2 = u3.charCodeAt(O3), q2 < 128 ? B2[T2 >> 2] |= q2 << N10[T2++ & 3] : q2 < 2048 ? (B2[T2 >> 2] |= (192 | q2 >> 6) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : q2 < 55296 || q2 >= 57344 ? (B2[T2 >> 2] |= (224 | q2 >> 12) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : (q2 = 65536 + ((q2 & 1023) << 10 | u3.charCodeAt(++O3) & 1023), B2[T2 >> 2] |= (240 | q2 >> 18) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 12 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]); + if (this.lastByteIndex = T2, T2 >= C3) { + for (this.start = T2 - C3, this.block = B2[P2], T2 = 0; T2 < P2; ++T2) + Ct[T2] ^= B2[T2]; + k4(Ct), this.reset = true; + } else + this.start = T2; + } + return this; + }, s2.prototype.encode = function(u3, E4) { + var _4 = u3 & 255, B2 = 1, C3 = [_4]; + for (u3 = u3 >> 8, _4 = u3 & 255; _4 > 0; ) + C3.unshift(_4), u3 = u3 >> 8, _4 = u3 & 255, ++B2; + return E4 ? C3.push(B2) : C3.unshift(B2), this.update(C3), C3.length; + }, s2.prototype.encodeString = function(u3) { + var E4, _4 = typeof u3; + if (_4 !== "string") { + if (_4 === "object") { + if (u3 === null) + throw new Error(t); + if (b4 && u3.constructor === ArrayBuffer) + u3 = new Uint8Array(u3); + else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) + throw new Error(t); + } else + throw new Error(t); + E4 = true; + } + var B2 = 0, C3 = u3.length; + if (E4) + B2 = C3; + else + for (var D2 = 0; D2 < u3.length; ++D2) { + var P2 = u3.charCodeAt(D2); + P2 < 128 ? B2 += 1 : P2 < 2048 ? B2 += 2 : P2 < 55296 || P2 >= 57344 ? B2 += 3 : (P2 = 65536 + ((P2 & 1023) << 10 | u3.charCodeAt(++D2) & 1023), B2 += 4); + } + return B2 += this.encode(B2 * 8), this.update(u3), B2; + }, s2.prototype.bytepad = function(u3, E4) { + for (var _4 = this.encode(E4), B2 = 0; B2 < u3.length; ++B2) + _4 += this.encodeString(u3[B2]); + var C3 = E4 - _4 % E4, D2 = []; + return D2.length = C3, this.update(D2), this; + }, s2.prototype.finalize = function() { + if (!this.finalized) { + this.finalized = true; + var u3 = this.blocks, E4 = this.lastByteIndex, _4 = this.blockCount, B2 = this.s; + if (u3[E4 >> 2] |= this.padding[E4 & 3], this.lastByteIndex === this.byteCount) + for (u3[0] = u3[_4], E4 = 1; E4 < _4 + 1; ++E4) + u3[E4] = 0; + for (u3[_4 - 1] |= 2147483648, E4 = 0; E4 < _4; ++E4) + B2[E4] ^= u3[E4]; + k4(B2); + } + }, s2.prototype.toString = s2.prototype.hex = function() { + this.finalize(); + for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = "", O3; D2 < _4; ) { + for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) + O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15] + g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15] + g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15] + g3[O3 >> 28 & 15] + g3[O3 >> 24 & 15]; + D2 % u3 === 0 && (k4(E4), C3 = 0); + } + return B2 && (O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15], B2 > 1 && (P2 += g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15]), B2 > 2 && (P2 += g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15])), P2; + }, s2.prototype.arrayBuffer = function() { + this.finalize(); + var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = this.outputBits >> 3, O3; + B2 ? O3 = new ArrayBuffer(_4 + 1 << 2) : O3 = new ArrayBuffer(P2); + for (var Ct = new Uint32Array(O3); D2 < _4; ) { + for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) + Ct[D2] = E4[C3]; + D2 % u3 === 0 && k4(E4); + } + return B2 && (Ct[C3] = E4[C3], O3 = O3.slice(0, P2)), O3; + }, s2.prototype.buffer = s2.prototype.arrayBuffer, s2.prototype.digest = s2.prototype.array = function() { + this.finalize(); + for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = [], O3, Ct; D2 < _4; ) { + for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) + O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, P2[O3 + 1] = Ct >> 8 & 255, P2[O3 + 2] = Ct >> 16 & 255, P2[O3 + 3] = Ct >> 24 & 255; + D2 % u3 === 0 && k4(E4); + } + return B2 && (O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, B2 > 1 && (P2[O3 + 1] = Ct >> 8 & 255), B2 > 2 && (P2[O3 + 2] = Ct >> 16 & 255)), P2; + }; + function v2(u3, E4, _4) { + s2.call(this, u3, E4, _4); + } + v2.prototype = new s2(), v2.prototype.finalize = function() { + return this.encode(this.outputBits, true), s2.prototype.finalize.call(this); + }; + var k4 = function(u3) { + var E4, _4, B2, C3, D2, P2, O3, Ct, T2, q2, Pe, X, Z, Te, $, tt, Fe, et, rt, De, it, nt, Ue, ft, ot, ke, st, at, qe, ut, ht, Ke, ct, lt, He, dt, pt, Le, vt, gt, ze, mt, At, je, bt, yt, Ve, wt, xt, Qe, Mt, Et, Je, St, Nt, Ye, It, _t, xe, Me, Ee, Se, Ne; + for (B2 = 0; B2 < 48; B2 += 2) + C3 = u3[0] ^ u3[10] ^ u3[20] ^ u3[30] ^ u3[40], D2 = u3[1] ^ u3[11] ^ u3[21] ^ u3[31] ^ u3[41], P2 = u3[2] ^ u3[12] ^ u3[22] ^ u3[32] ^ u3[42], O3 = u3[3] ^ u3[13] ^ u3[23] ^ u3[33] ^ u3[43], Ct = u3[4] ^ u3[14] ^ u3[24] ^ u3[34] ^ u3[44], T2 = u3[5] ^ u3[15] ^ u3[25] ^ u3[35] ^ u3[45], q2 = u3[6] ^ u3[16] ^ u3[26] ^ u3[36] ^ u3[46], Pe = u3[7] ^ u3[17] ^ u3[27] ^ u3[37] ^ u3[47], X = u3[8] ^ u3[18] ^ u3[28] ^ u3[38] ^ u3[48], Z = u3[9] ^ u3[19] ^ u3[29] ^ u3[39] ^ u3[49], E4 = X ^ (P2 << 1 | O3 >>> 31), _4 = Z ^ (O3 << 1 | P2 >>> 31), u3[0] ^= E4, u3[1] ^= _4, u3[10] ^= E4, u3[11] ^= _4, u3[20] ^= E4, u3[21] ^= _4, u3[30] ^= E4, u3[31] ^= _4, u3[40] ^= E4, u3[41] ^= _4, E4 = C3 ^ (Ct << 1 | T2 >>> 31), _4 = D2 ^ (T2 << 1 | Ct >>> 31), u3[2] ^= E4, u3[3] ^= _4, u3[12] ^= E4, u3[13] ^= _4, u3[22] ^= E4, u3[23] ^= _4, u3[32] ^= E4, u3[33] ^= _4, u3[42] ^= E4, u3[43] ^= _4, E4 = P2 ^ (q2 << 1 | Pe >>> 31), _4 = O3 ^ (Pe << 1 | q2 >>> 31), u3[4] ^= E4, u3[5] ^= _4, u3[14] ^= E4, u3[15] ^= _4, u3[24] ^= E4, u3[25] ^= _4, u3[34] ^= E4, u3[35] ^= _4, u3[44] ^= E4, u3[45] ^= _4, E4 = Ct ^ (X << 1 | Z >>> 31), _4 = T2 ^ (Z << 1 | X >>> 31), u3[6] ^= E4, u3[7] ^= _4, u3[16] ^= E4, u3[17] ^= _4, u3[26] ^= E4, u3[27] ^= _4, u3[36] ^= E4, u3[37] ^= _4, u3[46] ^= E4, u3[47] ^= _4, E4 = q2 ^ (C3 << 1 | D2 >>> 31), _4 = Pe ^ (D2 << 1 | C3 >>> 31), u3[8] ^= E4, u3[9] ^= _4, u3[18] ^= E4, u3[19] ^= _4, u3[28] ^= E4, u3[29] ^= _4, u3[38] ^= E4, u3[39] ^= _4, u3[48] ^= E4, u3[49] ^= _4, Te = u3[0], $ = u3[1], yt = u3[11] << 4 | u3[10] >>> 28, Ve = u3[10] << 4 | u3[11] >>> 28, at = u3[20] << 3 | u3[21] >>> 29, qe = u3[21] << 3 | u3[20] >>> 29, Me = u3[31] << 9 | u3[30] >>> 23, Ee = u3[30] << 9 | u3[31] >>> 23, mt = u3[40] << 18 | u3[41] >>> 14, At = u3[41] << 18 | u3[40] >>> 14, lt = u3[2] << 1 | u3[3] >>> 31, He = u3[3] << 1 | u3[2] >>> 31, tt = u3[13] << 12 | u3[12] >>> 20, Fe = u3[12] << 12 | u3[13] >>> 20, wt = u3[22] << 10 | u3[23] >>> 22, xt = u3[23] << 10 | u3[22] >>> 22, ut = u3[33] << 13 | u3[32] >>> 19, ht = u3[32] << 13 | u3[33] >>> 19, Se = u3[42] << 2 | u3[43] >>> 30, Ne = u3[43] << 2 | u3[42] >>> 30, St = u3[5] << 30 | u3[4] >>> 2, Nt = u3[4] << 30 | u3[5] >>> 2, dt = u3[14] << 6 | u3[15] >>> 26, pt = u3[15] << 6 | u3[14] >>> 26, et = u3[25] << 11 | u3[24] >>> 21, rt = u3[24] << 11 | u3[25] >>> 21, Qe = u3[34] << 15 | u3[35] >>> 17, Mt = u3[35] << 15 | u3[34] >>> 17, Ke = u3[45] << 29 | u3[44] >>> 3, ct = u3[44] << 29 | u3[45] >>> 3, ft = u3[6] << 28 | u3[7] >>> 4, ot = u3[7] << 28 | u3[6] >>> 4, Ye = u3[17] << 23 | u3[16] >>> 9, It = u3[16] << 23 | u3[17] >>> 9, Le = u3[26] << 25 | u3[27] >>> 7, vt = u3[27] << 25 | u3[26] >>> 7, De = u3[36] << 21 | u3[37] >>> 11, it = u3[37] << 21 | u3[36] >>> 11, Et = u3[47] << 24 | u3[46] >>> 8, Je = u3[46] << 24 | u3[47] >>> 8, je = u3[8] << 27 | u3[9] >>> 5, bt = u3[9] << 27 | u3[8] >>> 5, ke = u3[18] << 20 | u3[19] >>> 12, st = u3[19] << 20 | u3[18] >>> 12, _t = u3[29] << 7 | u3[28] >>> 25, xe = u3[28] << 7 | u3[29] >>> 25, gt = u3[38] << 8 | u3[39] >>> 24, ze = u3[39] << 8 | u3[38] >>> 24, nt = u3[48] << 14 | u3[49] >>> 18, Ue = u3[49] << 14 | u3[48] >>> 18, u3[0] = Te ^ ~tt & et, u3[1] = $ ^ ~Fe & rt, u3[10] = ft ^ ~ke & at, u3[11] = ot ^ ~st & qe, u3[20] = lt ^ ~dt & Le, u3[21] = He ^ ~pt & vt, u3[30] = je ^ ~yt & wt, u3[31] = bt ^ ~Ve & xt, u3[40] = St ^ ~Ye & _t, u3[41] = Nt ^ ~It & xe, u3[2] = tt ^ ~et & De, u3[3] = Fe ^ ~rt & it, u3[12] = ke ^ ~at & ut, u3[13] = st ^ ~qe & ht, u3[22] = dt ^ ~Le & gt, u3[23] = pt ^ ~vt & ze, u3[32] = yt ^ ~wt & Qe, u3[33] = Ve ^ ~xt & Mt, u3[42] = Ye ^ ~_t & Me, u3[43] = It ^ ~xe & Ee, u3[4] = et ^ ~De & nt, u3[5] = rt ^ ~it & Ue, u3[14] = at ^ ~ut & Ke, u3[15] = qe ^ ~ht & ct, u3[24] = Le ^ ~gt & mt, u3[25] = vt ^ ~ze & At, u3[34] = wt ^ ~Qe & Et, u3[35] = xt ^ ~Mt & Je, u3[44] = _t ^ ~Me & Se, u3[45] = xe ^ ~Ee & Ne, u3[6] = De ^ ~nt & Te, u3[7] = it ^ ~Ue & $, u3[16] = ut ^ ~Ke & ft, u3[17] = ht ^ ~ct & ot, u3[26] = gt ^ ~mt & lt, u3[27] = ze ^ ~At & He, u3[36] = Qe ^ ~Et & je, u3[37] = Mt ^ ~Je & bt, u3[46] = Me ^ ~Se & St, u3[47] = Ee ^ ~Ne & Nt, u3[8] = nt ^ ~Te & tt, u3[9] = Ue ^ ~$ & Fe, u3[18] = Ke ^ ~ft & ke, u3[19] = ct ^ ~ot & st, u3[28] = mt ^ ~lt & dt, u3[29] = At ^ ~He & pt, u3[38] = Et ^ ~je & yt, u3[39] = Je ^ ~bt & Ve, u3[48] = Se ^ ~St & Ye, u3[49] = Ne ^ ~Nt & It, u3[0] ^= R2[B2], u3[1] ^= R2[B2 + 1]; + }; + if (p3) + e2.exports = f4; + else + for (c4 = 0; c4 < a3.length; ++c4) + n3[a3[c4]] = f4[a3[c4]]; + })(); + })(Bn); + var vs = Bn.exports; + var gs = "logger/5.7.0"; + var Rn = false; + var Cn = false; + var Cr = { debug: 1, default: 2, info: 2, warning: 3, error: 4, off: 5 }; + var On = Cr.default; + var Ai = null; + function ms() { + try { + const e2 = []; + if (["NFD", "NFC", "NFKD", "NFKC"].forEach((t) => { + try { + if ("test".normalize(t) !== "test") + throw new Error("bad normalize"); + } catch { + e2.push(t); + } + }), e2.length) + throw new Error("missing " + e2.join(", ")); + if (String.fromCharCode(233).normalize("NFD") !== String.fromCharCode(101, 769)) + throw new Error("broken implementation"); + } catch (e2) { + return e2.message; + } + return null; + } + var Pn = ms(); + var bi; + (function(e2) { + e2.DEBUG = "DEBUG", e2.INFO = "INFO", e2.WARNING = "WARNING", e2.ERROR = "ERROR", e2.OFF = "OFF"; + })(bi || (bi = {})); + var ee; + (function(e2) { + e2.UNKNOWN_ERROR = "UNKNOWN_ERROR", e2.NOT_IMPLEMENTED = "NOT_IMPLEMENTED", e2.UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION", e2.NETWORK_ERROR = "NETWORK_ERROR", e2.SERVER_ERROR = "SERVER_ERROR", e2.TIMEOUT = "TIMEOUT", e2.BUFFER_OVERRUN = "BUFFER_OVERRUN", e2.NUMERIC_FAULT = "NUMERIC_FAULT", e2.MISSING_NEW = "MISSING_NEW", e2.INVALID_ARGUMENT = "INVALID_ARGUMENT", e2.MISSING_ARGUMENT = "MISSING_ARGUMENT", e2.UNEXPECTED_ARGUMENT = "UNEXPECTED_ARGUMENT", e2.CALL_EXCEPTION = "CALL_EXCEPTION", e2.INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS", e2.NONCE_EXPIRED = "NONCE_EXPIRED", e2.REPLACEMENT_UNDERPRICED = "REPLACEMENT_UNDERPRICED", e2.UNPREDICTABLE_GAS_LIMIT = "UNPREDICTABLE_GAS_LIMIT", e2.TRANSACTION_REPLACED = "TRANSACTION_REPLACED", e2.ACTION_REJECTED = "ACTION_REJECTED"; + })(ee || (ee = {})); + var Tn = "0123456789abcdef"; + var z3 = class _z { + constructor(t) { + Object.defineProperty(this, "version", { enumerable: true, value: t, writable: false }); + } + _log(t, r) { + const i2 = t.toLowerCase(); + Cr[i2] == null && this.throwArgumentError("invalid log level name", "logLevel", t), !(On > Cr[i2]) && console.log.apply(console, r); + } + debug(...t) { + this._log(_z.levels.DEBUG, t); + } + info(...t) { + this._log(_z.levels.INFO, t); + } + warn(...t) { + this._log(_z.levels.WARNING, t); + } + makeError(t, r, i2) { + if (Cn) + return this.makeError("censored error", r, {}); + r || (r = _z.errors.UNKNOWN_ERROR), i2 || (i2 = {}); + const n3 = []; + Object.keys(i2).forEach((b4) => { + const g3 = i2[b4]; + try { + if (g3 instanceof Uint8Array) { + let w4 = ""; + for (let y4 = 0; y4 < g3.length; y4++) + w4 += Tn[g3[y4] >> 4], w4 += Tn[g3[y4] & 15]; + n3.push(b4 + "=Uint8Array(0x" + w4 + ")"); + } else + n3.push(b4 + "=" + JSON.stringify(g3)); + } catch { + n3.push(b4 + "=" + JSON.stringify(i2[b4].toString())); + } + }), n3.push(`code=${r}`), n3.push(`version=${this.version}`); + const o2 = t; + let h5 = ""; + switch (r) { + case ee.NUMERIC_FAULT: { + h5 = "NUMERIC_FAULT"; + const b4 = t; + switch (b4) { + case "overflow": + case "underflow": + case "division-by-zero": + h5 += "-" + b4; + break; + case "negative-power": + case "negative-width": + h5 += "-unsupported"; + break; + case "unbound-bitwise-result": + h5 += "-unbound-result"; + break; + } + break; + } + case ee.CALL_EXCEPTION: + case ee.INSUFFICIENT_FUNDS: + case ee.MISSING_NEW: + case ee.NONCE_EXPIRED: + case ee.REPLACEMENT_UNDERPRICED: + case ee.TRANSACTION_REPLACED: + case ee.UNPREDICTABLE_GAS_LIMIT: + h5 = r; + break; + } + h5 && (t += " [ See: https://links.ethers.org/v5-errors-" + h5 + " ]"), n3.length && (t += " (" + n3.join(", ") + ")"); + const p3 = new Error(t); + return p3.reason = o2, p3.code = r, Object.keys(i2).forEach(function(b4) { + p3[b4] = i2[b4]; + }), p3; + } + throwError(t, r, i2) { + throw this.makeError(t, r, i2); + } + throwArgumentError(t, r, i2) { + return this.throwError(t, _z.errors.INVALID_ARGUMENT, { argument: r, value: i2 }); + } + assert(t, r, i2, n3) { + t || this.throwError(r, i2, n3); + } + assertArgument(t, r, i2, n3) { + t || this.throwArgumentError(r, i2, n3); + } + checkNormalize(t) { + Pn && this.throwError("platform missing String.prototype.normalize", _z.errors.UNSUPPORTED_OPERATION, { operation: "String.prototype.normalize", form: Pn }); + } + checkSafeUint53(t, r) { + typeof t == "number" && (r == null && (r = "value not safe"), (t < 0 || t >= 9007199254740991) && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "out-of-safe-range", value: t }), t % 1 && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "non-integer", value: t })); + } + checkArgumentCount(t, r, i2) { + i2 ? i2 = ": " + i2 : i2 = "", t < r && this.throwError("missing argument" + i2, _z.errors.MISSING_ARGUMENT, { count: t, expectedCount: r }), t > r && this.throwError("too many arguments" + i2, _z.errors.UNEXPECTED_ARGUMENT, { count: t, expectedCount: r }); + } + checkNew(t, r) { + (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); + } + checkAbstract(t, r) { + t === r ? this.throwError("cannot instantiate abstract class " + JSON.stringify(r.name) + " directly; use a sub-class", _z.errors.UNSUPPORTED_OPERATION, { name: t.name, operation: "new" }) : (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); + } + static globalLogger() { + return Ai || (Ai = new _z(gs)), Ai; + } + static setCensorship(t, r) { + if (!t && r && this.globalLogger().throwError("cannot permanently disable censorship", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }), Rn) { + if (!t) + return; + this.globalLogger().throwError("error censorship permanent", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); + } + Cn = !!t, Rn = !!r; + } + static setLogLevel(t) { + const r = Cr[t.toLowerCase()]; + if (r == null) { + _z.globalLogger().warn("invalid log level - " + t); + return; + } + On = r; + } + static from(t) { + return new _z(t); + } + }; + z3.errors = ee, z3.levels = bi; + var As = "bytes/5.7.0"; + var Ft = new z3(As); + function Fn(e2) { + return !!e2.toHexString; + } + function ir(e2) { + return e2.slice || (e2.slice = function() { + const t = Array.prototype.slice.call(arguments); + return ir(new Uint8Array(Array.prototype.slice.apply(e2, t))); + }), e2; + } + function bs(e2) { + return Qt(e2) && !(e2.length % 2) || nr(e2); + } + function Dn(e2) { + return typeof e2 == "number" && e2 == e2 && e2 % 1 === 0; + } + function nr(e2) { + if (e2 == null) + return false; + if (e2.constructor === Uint8Array) + return true; + if (typeof e2 == "string" || !Dn(e2.length) || e2.length < 0) + return false; + for (let t = 0; t < e2.length; t++) { + const r = e2[t]; + if (!Dn(r) || r < 0 || r >= 256) + return false; + } + return true; + } + function Pt(e2, t) { + if (t || (t = {}), typeof e2 == "number") { + Ft.checkSafeUint53(e2, "invalid arrayify value"); + const r = []; + for (; e2; ) + r.unshift(e2 & 255), e2 = parseInt(String(e2 / 256)); + return r.length === 0 && r.push(0), ir(new Uint8Array(r)); + } + if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2) && (e2 = e2.toHexString()), Qt(e2)) { + let r = e2.substring(2); + r.length % 2 && (t.hexPad === "left" ? r = "0" + r : t.hexPad === "right" ? r += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)); + const i2 = []; + for (let n3 = 0; n3 < r.length; n3 += 2) + i2.push(parseInt(r.substring(n3, n3 + 2), 16)); + return ir(new Uint8Array(i2)); + } + return nr(e2) ? ir(new Uint8Array(e2)) : Ft.throwArgumentError("invalid arrayify value", "value", e2); + } + function ys(e2) { + const t = e2.map((n3) => Pt(n3)), r = t.reduce((n3, o2) => n3 + o2.length, 0), i2 = new Uint8Array(r); + return t.reduce((n3, o2) => (i2.set(o2, n3), n3 + o2.length), 0), ir(i2); + } + function ws(e2, t) { + e2 = Pt(e2), e2.length > t && Ft.throwArgumentError("value out of range", "value", arguments[0]); + const r = new Uint8Array(t); + return r.set(e2, t - e2.length), ir(r); + } + function Qt(e2, t) { + return !(typeof e2 != "string" || !e2.match(/^0x[0-9A-Fa-f]*$/) || t && e2.length !== 2 + 2 * t); + } + var yi = "0123456789abcdef"; + function Ht(e2, t) { + if (t || (t = {}), typeof e2 == "number") { + Ft.checkSafeUint53(e2, "invalid hexlify value"); + let r = ""; + for (; e2; ) + r = yi[e2 & 15] + r, e2 = Math.floor(e2 / 16); + return r.length ? (r.length % 2 && (r = "0" + r), "0x" + r) : "0x00"; + } + if (typeof e2 == "bigint") + return e2 = e2.toString(16), e2.length % 2 ? "0x0" + e2 : "0x" + e2; + if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2)) + return e2.toHexString(); + if (Qt(e2)) + return e2.length % 2 && (t.hexPad === "left" ? e2 = "0x0" + e2.substring(2) : t.hexPad === "right" ? e2 += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)), e2.toLowerCase(); + if (nr(e2)) { + let r = "0x"; + for (let i2 = 0; i2 < e2.length; i2++) { + let n3 = e2[i2]; + r += yi[(n3 & 240) >> 4] + yi[n3 & 15]; + } + return r; + } + return Ft.throwArgumentError("invalid hexlify value", "value", e2); + } + function xs(e2) { + if (typeof e2 != "string") + e2 = Ht(e2); + else if (!Qt(e2) || e2.length % 2) + return null; + return (e2.length - 2) / 2; + } + function Un(e2, t, r) { + return typeof e2 != "string" ? e2 = Ht(e2) : (!Qt(e2) || e2.length % 2) && Ft.throwArgumentError("invalid hexData", "value", e2), t = 2 + 2 * t, r != null ? "0x" + e2.substring(t, 2 + 2 * r) : "0x" + e2.substring(t); + } + function fe(e2, t) { + for (typeof e2 != "string" ? e2 = Ht(e2) : Qt(e2) || Ft.throwArgumentError("invalid hex string", "value", e2), e2.length > 2 * t + 2 && Ft.throwArgumentError("value out of range", "value", arguments[1]); e2.length < 2 * t + 2; ) + e2 = "0x0" + e2.substring(2); + return e2; + } + function kn(e2) { + const t = { r: "0x", s: "0x", _vs: "0x", recoveryParam: 0, v: 0, yParityAndS: "0x", compact: "0x" }; + if (bs(e2)) { + let r = Pt(e2); + r.length === 64 ? (t.v = 27 + (r[32] >> 7), r[32] &= 127, t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64))) : r.length === 65 ? (t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64)), t.v = r[64]) : Ft.throwArgumentError("invalid signature string", "signature", e2), t.v < 27 && (t.v === 0 || t.v === 1 ? t.v += 27 : Ft.throwArgumentError("signature invalid v byte", "signature", e2)), t.recoveryParam = 1 - t.v % 2, t.recoveryParam && (r[32] |= 128), t._vs = Ht(r.slice(32, 64)); + } else { + if (t.r = e2.r, t.s = e2.s, t.v = e2.v, t.recoveryParam = e2.recoveryParam, t._vs = e2._vs, t._vs != null) { + const n3 = ws(Pt(t._vs), 32); + t._vs = Ht(n3); + const o2 = n3[0] >= 128 ? 1 : 0; + t.recoveryParam == null ? t.recoveryParam = o2 : t.recoveryParam !== o2 && Ft.throwArgumentError("signature recoveryParam mismatch _vs", "signature", e2), n3[0] &= 127; + const h5 = Ht(n3); + t.s == null ? t.s = h5 : t.s !== h5 && Ft.throwArgumentError("signature v mismatch _vs", "signature", e2); + } + if (t.recoveryParam == null) + t.v == null ? Ft.throwArgumentError("signature missing v and recoveryParam", "signature", e2) : t.v === 0 || t.v === 1 ? t.recoveryParam = t.v : t.recoveryParam = 1 - t.v % 2; + else if (t.v == null) + t.v = 27 + t.recoveryParam; + else { + const n3 = t.v === 0 || t.v === 1 ? t.v : 1 - t.v % 2; + t.recoveryParam !== n3 && Ft.throwArgumentError("signature recoveryParam mismatch v", "signature", e2); + } + t.r == null || !Qt(t.r) ? Ft.throwArgumentError("signature missing or invalid r", "signature", e2) : t.r = fe(t.r, 32), t.s == null || !Qt(t.s) ? Ft.throwArgumentError("signature missing or invalid s", "signature", e2) : t.s = fe(t.s, 32); + const r = Pt(t.s); + r[0] >= 128 && Ft.throwArgumentError("signature s out of range", "signature", e2), t.recoveryParam && (r[0] |= 128); + const i2 = Ht(r); + t._vs && (Qt(t._vs) || Ft.throwArgumentError("signature invalid _vs", "signature", e2), t._vs = fe(t._vs, 32)), t._vs == null ? t._vs = i2 : t._vs !== i2 && Ft.throwArgumentError("signature _vs mismatch v and s", "signature", e2); + } + return t.yParityAndS = t._vs, t.compact = t.r + t.yParityAndS.substring(2), t; + } + function wi(e2) { + return "0x" + vs.keccak_256(Pt(e2)); + } + var qn = { exports: {} }; + var Ms = {}; + var Es = Object.freeze({ __proto__: null, default: Ms }); + var Ss = ps(Es); + (function(e2) { + (function(t, r) { + function i2(A2, f4) { + if (!A2) + throw new Error(f4 || "Assertion failed"); + } + function n3(A2, f4) { + A2.super_ = f4; + var a3 = function() { + }; + a3.prototype = f4.prototype, A2.prototype = new a3(), A2.prototype.constructor = A2; + } + function o2(A2, f4, a3) { + if (o2.isBN(A2)) + return A2; + this.negative = 0, this.words = null, this.length = 0, this.red = null, A2 !== null && ((f4 === "le" || f4 === "be") && (a3 = f4, f4 = 10), this._init(A2 || 0, f4 || 10, a3 || "be")); + } + typeof t == "object" ? t.exports = o2 : r.BN = o2, o2.BN = o2, o2.wordSize = 26; + var h5; + try { + typeof window < "u" && typeof window.Buffer < "u" ? h5 = window.Buffer : h5 = Ss.Buffer; + } catch { + } + o2.isBN = function(f4) { + return f4 instanceof o2 ? true : f4 !== null && typeof f4 == "object" && f4.constructor.wordSize === o2.wordSize && Array.isArray(f4.words); + }, o2.max = function(f4, a3) { + return f4.cmp(a3) > 0 ? f4 : a3; + }, o2.min = function(f4, a3) { + return f4.cmp(a3) < 0 ? f4 : a3; + }, o2.prototype._init = function(f4, a3, c4) { + if (typeof f4 == "number") + return this._initNumber(f4, a3, c4); + if (typeof f4 == "object") + return this._initArray(f4, a3, c4); + a3 === "hex" && (a3 = 16), i2(a3 === (a3 | 0) && a3 >= 2 && a3 <= 36), f4 = f4.toString().replace(/\s+/g, ""); + var d3 = 0; + f4[0] === "-" && (d3++, this.negative = 1), d3 < f4.length && (a3 === 16 ? this._parseHex(f4, d3, c4) : (this._parseBase(f4, a3, d3), c4 === "le" && this._initArray(this.toArray(), a3, c4))); + }, o2.prototype._initNumber = function(f4, a3, c4) { + f4 < 0 && (this.negative = 1, f4 = -f4), f4 < 67108864 ? (this.words = [f4 & 67108863], this.length = 1) : f4 < 4503599627370496 ? (this.words = [f4 & 67108863, f4 / 67108864 & 67108863], this.length = 2) : (i2(f4 < 9007199254740992), this.words = [f4 & 67108863, f4 / 67108864 & 67108863, 1], this.length = 3), c4 === "le" && this._initArray(this.toArray(), a3, c4); + }, o2.prototype._initArray = function(f4, a3, c4) { + if (i2(typeof f4.length == "number"), f4.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(f4.length / 3), this.words = new Array(this.length); + for (var d3 = 0; d3 < this.length; d3++) + this.words[d3] = 0; + var m3, x3, M = 0; + if (c4 === "be") + for (d3 = f4.length - 1, m3 = 0; d3 >= 0; d3 -= 3) + x3 = f4[d3] | f4[d3 - 1] << 8 | f4[d3 - 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); + else if (c4 === "le") + for (d3 = 0, m3 = 0; d3 < f4.length; d3 += 3) + x3 = f4[d3] | f4[d3 + 1] << 8 | f4[d3 + 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); + return this._strip(); + }; + function p3(A2, f4) { + var a3 = A2.charCodeAt(f4); + if (a3 >= 48 && a3 <= 57) + return a3 - 48; + if (a3 >= 65 && a3 <= 70) + return a3 - 55; + if (a3 >= 97 && a3 <= 102) + return a3 - 87; + i2(false, "Invalid character in " + A2); + } + function b4(A2, f4, a3) { + var c4 = p3(A2, a3); + return a3 - 1 >= f4 && (c4 |= p3(A2, a3 - 1) << 4), c4; + } + o2.prototype._parseHex = function(f4, a3, c4) { + this.length = Math.ceil((f4.length - a3) / 6), this.words = new Array(this.length); + for (var d3 = 0; d3 < this.length; d3++) + this.words[d3] = 0; + var m3 = 0, x3 = 0, M; + if (c4 === "be") + for (d3 = f4.length - 1; d3 >= a3; d3 -= 2) + M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; + else { + var l4 = f4.length - a3; + for (d3 = l4 % 2 === 0 ? a3 + 1 : a3; d3 < f4.length; d3 += 2) + M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; + } + this._strip(); + }; + function g3(A2, f4, a3, c4) { + for (var d3 = 0, m3 = 0, x3 = Math.min(A2.length, a3), M = f4; M < x3; M++) { + var l4 = A2.charCodeAt(M) - 48; + d3 *= c4, l4 >= 49 ? m3 = l4 - 49 + 10 : l4 >= 17 ? m3 = l4 - 17 + 10 : m3 = l4, i2(l4 >= 0 && m3 < c4, "Invalid character"), d3 += m3; + } + return d3; + } + o2.prototype._parseBase = function(f4, a3, c4) { + this.words = [0], this.length = 1; + for (var d3 = 0, m3 = 1; m3 <= 67108863; m3 *= a3) + d3++; + d3--, m3 = m3 / a3 | 0; + for (var x3 = f4.length - c4, M = x3 % d3, l4 = Math.min(x3, x3 - M) + c4, s2 = 0, v2 = c4; v2 < l4; v2 += d3) + s2 = g3(f4, v2, v2 + d3, a3), this.imuln(m3), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); + if (M !== 0) { + var k4 = 1; + for (s2 = g3(f4, v2, f4.length, a3), v2 = 0; v2 < M; v2++) + k4 *= a3; + this.imuln(k4), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); + } + this._strip(); + }, o2.prototype.copy = function(f4) { + f4.words = new Array(this.length); + for (var a3 = 0; a3 < this.length; a3++) + f4.words[a3] = this.words[a3]; + f4.length = this.length, f4.negative = this.negative, f4.red = this.red; + }; + function w4(A2, f4) { + A2.words = f4.words, A2.length = f4.length, A2.negative = f4.negative, A2.red = f4.red; + } + if (o2.prototype._move = function(f4) { + w4(f4, this); + }, o2.prototype.clone = function() { + var f4 = new o2(null); + return this.copy(f4), f4; + }, o2.prototype._expand = function(f4) { + for (; this.length < f4; ) + this.words[this.length++] = 0; + return this; + }, o2.prototype._strip = function() { + for (; this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, o2.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, typeof Symbol < "u" && typeof Symbol.for == "function") + try { + o2.prototype[Symbol.for("nodejs.util.inspect.custom")] = y4; + } catch { + o2.prototype.inspect = y4; + } + else + o2.prototype.inspect = y4; + function y4() { + return (this.red ? ""; + } + var S4 = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], I2 = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], N10 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + o2.prototype.toString = function(f4, a3) { + f4 = f4 || 10, a3 = a3 | 0 || 1; + var c4; + if (f4 === 16 || f4 === "hex") { + c4 = ""; + for (var d3 = 0, m3 = 0, x3 = 0; x3 < this.length; x3++) { + var M = this.words[x3], l4 = ((M << d3 | m3) & 16777215).toString(16); + m3 = M >>> 24 - d3 & 16777215, d3 += 2, d3 >= 26 && (d3 -= 26, x3--), m3 !== 0 || x3 !== this.length - 1 ? c4 = S4[6 - l4.length] + l4 + c4 : c4 = l4 + c4; + } + for (m3 !== 0 && (c4 = m3.toString(16) + c4); c4.length % a3 !== 0; ) + c4 = "0" + c4; + return this.negative !== 0 && (c4 = "-" + c4), c4; + } + if (f4 === (f4 | 0) && f4 >= 2 && f4 <= 36) { + var s2 = I2[f4], v2 = N10[f4]; + c4 = ""; + var k4 = this.clone(); + for (k4.negative = 0; !k4.isZero(); ) { + var u3 = k4.modrn(v2).toString(f4); + k4 = k4.idivn(v2), k4.isZero() ? c4 = u3 + c4 : c4 = S4[s2 - u3.length] + u3 + c4; + } + for (this.isZero() && (c4 = "0" + c4); c4.length % a3 !== 0; ) + c4 = "0" + c4; + return this.negative !== 0 && (c4 = "-" + c4), c4; + } + i2(false, "Base should be between 2 and 36"); + }, o2.prototype.toNumber = function() { + var f4 = this.words[0]; + return this.length === 2 ? f4 += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? f4 += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && i2(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -f4 : f4; + }, o2.prototype.toJSON = function() { + return this.toString(16, 2); + }, h5 && (o2.prototype.toBuffer = function(f4, a3) { + return this.toArrayLike(h5, f4, a3); + }), o2.prototype.toArray = function(f4, a3) { + return this.toArrayLike(Array, f4, a3); + }; + var R2 = function(f4, a3) { + return f4.allocUnsafe ? f4.allocUnsafe(a3) : new f4(a3); + }; + o2.prototype.toArrayLike = function(f4, a3, c4) { + this._strip(); + var d3 = this.byteLength(), m3 = c4 || Math.max(1, d3); + i2(d3 <= m3, "byte array longer than desired length"), i2(m3 > 0, "Requested array length <= 0"); + var x3 = R2(f4, m3), M = a3 === "le" ? "LE" : "BE"; + return this["_toArrayLike" + M](x3, d3), x3; + }, o2.prototype._toArrayLikeLE = function(f4, a3) { + for (var c4 = 0, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { + var M = this.words[m3] << x3 | d3; + f4[c4++] = M & 255, c4 < f4.length && (f4[c4++] = M >> 8 & 255), c4 < f4.length && (f4[c4++] = M >> 16 & 255), x3 === 6 ? (c4 < f4.length && (f4[c4++] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); + } + if (c4 < f4.length) + for (f4[c4++] = d3; c4 < f4.length; ) + f4[c4++] = 0; + }, o2.prototype._toArrayLikeBE = function(f4, a3) { + for (var c4 = f4.length - 1, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { + var M = this.words[m3] << x3 | d3; + f4[c4--] = M & 255, c4 >= 0 && (f4[c4--] = M >> 8 & 255), c4 >= 0 && (f4[c4--] = M >> 16 & 255), x3 === 6 ? (c4 >= 0 && (f4[c4--] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); + } + if (c4 >= 0) + for (f4[c4--] = d3; c4 >= 0; ) + f4[c4--] = 0; + }, Math.clz32 ? o2.prototype._countBits = function(f4) { + return 32 - Math.clz32(f4); + } : o2.prototype._countBits = function(f4) { + var a3 = f4, c4 = 0; + return a3 >= 4096 && (c4 += 13, a3 >>>= 13), a3 >= 64 && (c4 += 7, a3 >>>= 7), a3 >= 8 && (c4 += 4, a3 >>>= 4), a3 >= 2 && (c4 += 2, a3 >>>= 2), c4 + a3; + }, o2.prototype._zeroBits = function(f4) { + if (f4 === 0) + return 26; + var a3 = f4, c4 = 0; + return a3 & 8191 || (c4 += 13, a3 >>>= 13), a3 & 127 || (c4 += 7, a3 >>>= 7), a3 & 15 || (c4 += 4, a3 >>>= 4), a3 & 3 || (c4 += 2, a3 >>>= 2), a3 & 1 || c4++, c4; + }, o2.prototype.bitLength = function() { + var f4 = this.words[this.length - 1], a3 = this._countBits(f4); + return (this.length - 1) * 26 + a3; + }; + function F(A2) { + for (var f4 = new Array(A2.bitLength()), a3 = 0; a3 < f4.length; a3++) { + var c4 = a3 / 26 | 0, d3 = a3 % 26; + f4[a3] = A2.words[c4] >>> d3 & 1; + } + return f4; + } + o2.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var f4 = 0, a3 = 0; a3 < this.length; a3++) { + var c4 = this._zeroBits(this.words[a3]); + if (f4 += c4, c4 !== 26) + break; + } + return f4; + }, o2.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, o2.prototype.toTwos = function(f4) { + return this.negative !== 0 ? this.abs().inotn(f4).iaddn(1) : this.clone(); + }, o2.prototype.fromTwos = function(f4) { + return this.testn(f4 - 1) ? this.notn(f4).iaddn(1).ineg() : this.clone(); + }, o2.prototype.isNeg = function() { + return this.negative !== 0; + }, o2.prototype.neg = function() { + return this.clone().ineg(); + }, o2.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, o2.prototype.iuor = function(f4) { + for (; this.length < f4.length; ) + this.words[this.length++] = 0; + for (var a3 = 0; a3 < f4.length; a3++) + this.words[a3] = this.words[a3] | f4.words[a3]; + return this._strip(); + }, o2.prototype.ior = function(f4) { + return i2((this.negative | f4.negative) === 0), this.iuor(f4); + }, o2.prototype.or = function(f4) { + return this.length > f4.length ? this.clone().ior(f4) : f4.clone().ior(this); + }, o2.prototype.uor = function(f4) { + return this.length > f4.length ? this.clone().iuor(f4) : f4.clone().iuor(this); + }, o2.prototype.iuand = function(f4) { + var a3; + this.length > f4.length ? a3 = f4 : a3 = this; + for (var c4 = 0; c4 < a3.length; c4++) + this.words[c4] = this.words[c4] & f4.words[c4]; + return this.length = a3.length, this._strip(); + }, o2.prototype.iand = function(f4) { + return i2((this.negative | f4.negative) === 0), this.iuand(f4); + }, o2.prototype.and = function(f4) { + return this.length > f4.length ? this.clone().iand(f4) : f4.clone().iand(this); + }, o2.prototype.uand = function(f4) { + return this.length > f4.length ? this.clone().iuand(f4) : f4.clone().iuand(this); + }, o2.prototype.iuxor = function(f4) { + var a3, c4; + this.length > f4.length ? (a3 = this, c4 = f4) : (a3 = f4, c4 = this); + for (var d3 = 0; d3 < c4.length; d3++) + this.words[d3] = a3.words[d3] ^ c4.words[d3]; + if (this !== a3) + for (; d3 < a3.length; d3++) + this.words[d3] = a3.words[d3]; + return this.length = a3.length, this._strip(); + }, o2.prototype.ixor = function(f4) { + return i2((this.negative | f4.negative) === 0), this.iuxor(f4); + }, o2.prototype.xor = function(f4) { + return this.length > f4.length ? this.clone().ixor(f4) : f4.clone().ixor(this); + }, o2.prototype.uxor = function(f4) { + return this.length > f4.length ? this.clone().iuxor(f4) : f4.clone().iuxor(this); + }, o2.prototype.inotn = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = Math.ceil(f4 / 26) | 0, c4 = f4 % 26; + this._expand(a3), c4 > 0 && a3--; + for (var d3 = 0; d3 < a3; d3++) + this.words[d3] = ~this.words[d3] & 67108863; + return c4 > 0 && (this.words[d3] = ~this.words[d3] & 67108863 >> 26 - c4), this._strip(); + }, o2.prototype.notn = function(f4) { + return this.clone().inotn(f4); + }, o2.prototype.setn = function(f4, a3) { + i2(typeof f4 == "number" && f4 >= 0); + var c4 = f4 / 26 | 0, d3 = f4 % 26; + return this._expand(c4 + 1), a3 ? this.words[c4] = this.words[c4] | 1 << d3 : this.words[c4] = this.words[c4] & ~(1 << d3), this._strip(); + }, o2.prototype.iadd = function(f4) { + var a3; + if (this.negative !== 0 && f4.negative === 0) + return this.negative = 0, a3 = this.isub(f4), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && f4.negative !== 0) + return f4.negative = 0, a3 = this.isub(f4), f4.negative = 1, a3._normSign(); + var c4, d3; + this.length > f4.length ? (c4 = this, d3 = f4) : (c4 = f4, d3 = this); + for (var m3 = 0, x3 = 0; x3 < d3.length; x3++) + a3 = (c4.words[x3] | 0) + (d3.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; + for (; m3 !== 0 && x3 < c4.length; x3++) + a3 = (c4.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; + if (this.length = c4.length, m3 !== 0) + this.words[this.length] = m3, this.length++; + else if (c4 !== this) + for (; x3 < c4.length; x3++) + this.words[x3] = c4.words[x3]; + return this; + }, o2.prototype.add = function(f4) { + var a3; + return f4.negative !== 0 && this.negative === 0 ? (f4.negative = 0, a3 = this.sub(f4), f4.negative ^= 1, a3) : f4.negative === 0 && this.negative !== 0 ? (this.negative = 0, a3 = f4.sub(this), this.negative = 1, a3) : this.length > f4.length ? this.clone().iadd(f4) : f4.clone().iadd(this); + }, o2.prototype.isub = function(f4) { + if (f4.negative !== 0) { + f4.negative = 0; + var a3 = this.iadd(f4); + return f4.negative = 1, a3._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(f4), this.negative = 1, this._normSign(); + var c4 = this.cmp(f4); + if (c4 === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var d3, m3; + c4 > 0 ? (d3 = this, m3 = f4) : (d3 = f4, m3 = this); + for (var x3 = 0, M = 0; M < m3.length; M++) + a3 = (d3.words[M] | 0) - (m3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; + for (; x3 !== 0 && M < d3.length; M++) + a3 = (d3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; + if (x3 === 0 && M < d3.length && d3 !== this) + for (; M < d3.length; M++) + this.words[M] = d3.words[M]; + return this.length = Math.max(this.length, M), d3 !== this && (this.negative = 1), this._strip(); + }, o2.prototype.sub = function(f4) { + return this.clone().isub(f4); + }; + function U2(A2, f4, a3) { + a3.negative = f4.negative ^ A2.negative; + var c4 = A2.length + f4.length | 0; + a3.length = c4, c4 = c4 - 1 | 0; + var d3 = A2.words[0] | 0, m3 = f4.words[0] | 0, x3 = d3 * m3, M = x3 & 67108863, l4 = x3 / 67108864 | 0; + a3.words[0] = M; + for (var s2 = 1; s2 < c4; s2++) { + for (var v2 = l4 >>> 26, k4 = l4 & 67108863, u3 = Math.min(s2, f4.length - 1), E4 = Math.max(0, s2 - A2.length + 1); E4 <= u3; E4++) { + var _4 = s2 - E4 | 0; + d3 = A2.words[_4] | 0, m3 = f4.words[E4] | 0, x3 = d3 * m3 + k4, v2 += x3 / 67108864 | 0, k4 = x3 & 67108863; + } + a3.words[s2] = k4 | 0, l4 = v2 | 0; + } + return l4 !== 0 ? a3.words[s2] = l4 | 0 : a3.length--, a3._strip(); + } + var Q = function(f4, a3, c4) { + var d3 = f4.words, m3 = a3.words, x3 = c4.words, M = 0, l4, s2, v2, k4 = d3[0] | 0, u3 = k4 & 8191, E4 = k4 >>> 13, _4 = d3[1] | 0, B2 = _4 & 8191, C3 = _4 >>> 13, D2 = d3[2] | 0, P2 = D2 & 8191, O3 = D2 >>> 13, Ct = d3[3] | 0, T2 = Ct & 8191, q2 = Ct >>> 13, Pe = d3[4] | 0, X = Pe & 8191, Z = Pe >>> 13, Te = d3[5] | 0, $ = Te & 8191, tt = Te >>> 13, Fe = d3[6] | 0, et = Fe & 8191, rt = Fe >>> 13, De = d3[7] | 0, it = De & 8191, nt = De >>> 13, Ue = d3[8] | 0, ft = Ue & 8191, ot = Ue >>> 13, ke = d3[9] | 0, st = ke & 8191, at = ke >>> 13, qe = m3[0] | 0, ut = qe & 8191, ht = qe >>> 13, Ke = m3[1] | 0, ct = Ke & 8191, lt = Ke >>> 13, He = m3[2] | 0, dt = He & 8191, pt = He >>> 13, Le = m3[3] | 0, vt = Le & 8191, gt = Le >>> 13, ze = m3[4] | 0, mt = ze & 8191, At = ze >>> 13, je = m3[5] | 0, bt = je & 8191, yt = je >>> 13, Ve = m3[6] | 0, wt = Ve & 8191, xt = Ve >>> 13, Qe = m3[7] | 0, Mt = Qe & 8191, Et = Qe >>> 13, Je = m3[8] | 0, St = Je & 8191, Nt = Je >>> 13, Ye = m3[9] | 0, It = Ye & 8191, _t = Ye >>> 13; + c4.negative = f4.negative ^ a3.negative, c4.length = 19, l4 = Math.imul(u3, ut), s2 = Math.imul(u3, ht), s2 = s2 + Math.imul(E4, ut) | 0, v2 = Math.imul(E4, ht); + var xe = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (xe >>> 26) | 0, xe &= 67108863, l4 = Math.imul(B2, ut), s2 = Math.imul(B2, ht), s2 = s2 + Math.imul(C3, ut) | 0, v2 = Math.imul(C3, ht), l4 = l4 + Math.imul(u3, ct) | 0, s2 = s2 + Math.imul(u3, lt) | 0, s2 = s2 + Math.imul(E4, ct) | 0, v2 = v2 + Math.imul(E4, lt) | 0; + var Me = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Me >>> 26) | 0, Me &= 67108863, l4 = Math.imul(P2, ut), s2 = Math.imul(P2, ht), s2 = s2 + Math.imul(O3, ut) | 0, v2 = Math.imul(O3, ht), l4 = l4 + Math.imul(B2, ct) | 0, s2 = s2 + Math.imul(B2, lt) | 0, s2 = s2 + Math.imul(C3, ct) | 0, v2 = v2 + Math.imul(C3, lt) | 0, l4 = l4 + Math.imul(u3, dt) | 0, s2 = s2 + Math.imul(u3, pt) | 0, s2 = s2 + Math.imul(E4, dt) | 0, v2 = v2 + Math.imul(E4, pt) | 0; + var Ee = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Ee >>> 26) | 0, Ee &= 67108863, l4 = Math.imul(T2, ut), s2 = Math.imul(T2, ht), s2 = s2 + Math.imul(q2, ut) | 0, v2 = Math.imul(q2, ht), l4 = l4 + Math.imul(P2, ct) | 0, s2 = s2 + Math.imul(P2, lt) | 0, s2 = s2 + Math.imul(O3, ct) | 0, v2 = v2 + Math.imul(O3, lt) | 0, l4 = l4 + Math.imul(B2, dt) | 0, s2 = s2 + Math.imul(B2, pt) | 0, s2 = s2 + Math.imul(C3, dt) | 0, v2 = v2 + Math.imul(C3, pt) | 0, l4 = l4 + Math.imul(u3, vt) | 0, s2 = s2 + Math.imul(u3, gt) | 0, s2 = s2 + Math.imul(E4, vt) | 0, v2 = v2 + Math.imul(E4, gt) | 0; + var Se = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Se >>> 26) | 0, Se &= 67108863, l4 = Math.imul(X, ut), s2 = Math.imul(X, ht), s2 = s2 + Math.imul(Z, ut) | 0, v2 = Math.imul(Z, ht), l4 = l4 + Math.imul(T2, ct) | 0, s2 = s2 + Math.imul(T2, lt) | 0, s2 = s2 + Math.imul(q2, ct) | 0, v2 = v2 + Math.imul(q2, lt) | 0, l4 = l4 + Math.imul(P2, dt) | 0, s2 = s2 + Math.imul(P2, pt) | 0, s2 = s2 + Math.imul(O3, dt) | 0, v2 = v2 + Math.imul(O3, pt) | 0, l4 = l4 + Math.imul(B2, vt) | 0, s2 = s2 + Math.imul(B2, gt) | 0, s2 = s2 + Math.imul(C3, vt) | 0, v2 = v2 + Math.imul(C3, gt) | 0, l4 = l4 + Math.imul(u3, mt) | 0, s2 = s2 + Math.imul(u3, At) | 0, s2 = s2 + Math.imul(E4, mt) | 0, v2 = v2 + Math.imul(E4, At) | 0; + var Ne = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Ne >>> 26) | 0, Ne &= 67108863, l4 = Math.imul($, ut), s2 = Math.imul($, ht), s2 = s2 + Math.imul(tt, ut) | 0, v2 = Math.imul(tt, ht), l4 = l4 + Math.imul(X, ct) | 0, s2 = s2 + Math.imul(X, lt) | 0, s2 = s2 + Math.imul(Z, ct) | 0, v2 = v2 + Math.imul(Z, lt) | 0, l4 = l4 + Math.imul(T2, dt) | 0, s2 = s2 + Math.imul(T2, pt) | 0, s2 = s2 + Math.imul(q2, dt) | 0, v2 = v2 + Math.imul(q2, pt) | 0, l4 = l4 + Math.imul(P2, vt) | 0, s2 = s2 + Math.imul(P2, gt) | 0, s2 = s2 + Math.imul(O3, vt) | 0, v2 = v2 + Math.imul(O3, gt) | 0, l4 = l4 + Math.imul(B2, mt) | 0, s2 = s2 + Math.imul(B2, At) | 0, s2 = s2 + Math.imul(C3, mt) | 0, v2 = v2 + Math.imul(C3, At) | 0, l4 = l4 + Math.imul(u3, bt) | 0, s2 = s2 + Math.imul(u3, yt) | 0, s2 = s2 + Math.imul(E4, bt) | 0, v2 = v2 + Math.imul(E4, yt) | 0; + var Xr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Xr >>> 26) | 0, Xr &= 67108863, l4 = Math.imul(et, ut), s2 = Math.imul(et, ht), s2 = s2 + Math.imul(rt, ut) | 0, v2 = Math.imul(rt, ht), l4 = l4 + Math.imul($, ct) | 0, s2 = s2 + Math.imul($, lt) | 0, s2 = s2 + Math.imul(tt, ct) | 0, v2 = v2 + Math.imul(tt, lt) | 0, l4 = l4 + Math.imul(X, dt) | 0, s2 = s2 + Math.imul(X, pt) | 0, s2 = s2 + Math.imul(Z, dt) | 0, v2 = v2 + Math.imul(Z, pt) | 0, l4 = l4 + Math.imul(T2, vt) | 0, s2 = s2 + Math.imul(T2, gt) | 0, s2 = s2 + Math.imul(q2, vt) | 0, v2 = v2 + Math.imul(q2, gt) | 0, l4 = l4 + Math.imul(P2, mt) | 0, s2 = s2 + Math.imul(P2, At) | 0, s2 = s2 + Math.imul(O3, mt) | 0, v2 = v2 + Math.imul(O3, At) | 0, l4 = l4 + Math.imul(B2, bt) | 0, s2 = s2 + Math.imul(B2, yt) | 0, s2 = s2 + Math.imul(C3, bt) | 0, v2 = v2 + Math.imul(C3, yt) | 0, l4 = l4 + Math.imul(u3, wt) | 0, s2 = s2 + Math.imul(u3, xt) | 0, s2 = s2 + Math.imul(E4, wt) | 0, v2 = v2 + Math.imul(E4, xt) | 0; + var Zr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (Zr >>> 26) | 0, Zr &= 67108863, l4 = Math.imul(it, ut), s2 = Math.imul(it, ht), s2 = s2 + Math.imul(nt, ut) | 0, v2 = Math.imul(nt, ht), l4 = l4 + Math.imul(et, ct) | 0, s2 = s2 + Math.imul(et, lt) | 0, s2 = s2 + Math.imul(rt, ct) | 0, v2 = v2 + Math.imul(rt, lt) | 0, l4 = l4 + Math.imul($, dt) | 0, s2 = s2 + Math.imul($, pt) | 0, s2 = s2 + Math.imul(tt, dt) | 0, v2 = v2 + Math.imul(tt, pt) | 0, l4 = l4 + Math.imul(X, vt) | 0, s2 = s2 + Math.imul(X, gt) | 0, s2 = s2 + Math.imul(Z, vt) | 0, v2 = v2 + Math.imul(Z, gt) | 0, l4 = l4 + Math.imul(T2, mt) | 0, s2 = s2 + Math.imul(T2, At) | 0, s2 = s2 + Math.imul(q2, mt) | 0, v2 = v2 + Math.imul(q2, At) | 0, l4 = l4 + Math.imul(P2, bt) | 0, s2 = s2 + Math.imul(P2, yt) | 0, s2 = s2 + Math.imul(O3, bt) | 0, v2 = v2 + Math.imul(O3, yt) | 0, l4 = l4 + Math.imul(B2, wt) | 0, s2 = s2 + Math.imul(B2, xt) | 0, s2 = s2 + Math.imul(C3, wt) | 0, v2 = v2 + Math.imul(C3, xt) | 0, l4 = l4 + Math.imul(u3, Mt) | 0, s2 = s2 + Math.imul(u3, Et) | 0, s2 = s2 + Math.imul(E4, Mt) | 0, v2 = v2 + Math.imul(E4, Et) | 0; + var $r = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + ($r >>> 26) | 0, $r &= 67108863, l4 = Math.imul(ft, ut), s2 = Math.imul(ft, ht), s2 = s2 + Math.imul(ot, ut) | 0, v2 = Math.imul(ot, ht), l4 = l4 + Math.imul(it, ct) | 0, s2 = s2 + Math.imul(it, lt) | 0, s2 = s2 + Math.imul(nt, ct) | 0, v2 = v2 + Math.imul(nt, lt) | 0, l4 = l4 + Math.imul(et, dt) | 0, s2 = s2 + Math.imul(et, pt) | 0, s2 = s2 + Math.imul(rt, dt) | 0, v2 = v2 + Math.imul(rt, pt) | 0, l4 = l4 + Math.imul($, vt) | 0, s2 = s2 + Math.imul($, gt) | 0, s2 = s2 + Math.imul(tt, vt) | 0, v2 = v2 + Math.imul(tt, gt) | 0, l4 = l4 + Math.imul(X, mt) | 0, s2 = s2 + Math.imul(X, At) | 0, s2 = s2 + Math.imul(Z, mt) | 0, v2 = v2 + Math.imul(Z, At) | 0, l4 = l4 + Math.imul(T2, bt) | 0, s2 = s2 + Math.imul(T2, yt) | 0, s2 = s2 + Math.imul(q2, bt) | 0, v2 = v2 + Math.imul(q2, yt) | 0, l4 = l4 + Math.imul(P2, wt) | 0, s2 = s2 + Math.imul(P2, xt) | 0, s2 = s2 + Math.imul(O3, wt) | 0, v2 = v2 + Math.imul(O3, xt) | 0, l4 = l4 + Math.imul(B2, Mt) | 0, s2 = s2 + Math.imul(B2, Et) | 0, s2 = s2 + Math.imul(C3, Mt) | 0, v2 = v2 + Math.imul(C3, Et) | 0, l4 = l4 + Math.imul(u3, St) | 0, s2 = s2 + Math.imul(u3, Nt) | 0, s2 = s2 + Math.imul(E4, St) | 0, v2 = v2 + Math.imul(E4, Nt) | 0; + var ti = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ti >>> 26) | 0, ti &= 67108863, l4 = Math.imul(st, ut), s2 = Math.imul(st, ht), s2 = s2 + Math.imul(at, ut) | 0, v2 = Math.imul(at, ht), l4 = l4 + Math.imul(ft, ct) | 0, s2 = s2 + Math.imul(ft, lt) | 0, s2 = s2 + Math.imul(ot, ct) | 0, v2 = v2 + Math.imul(ot, lt) | 0, l4 = l4 + Math.imul(it, dt) | 0, s2 = s2 + Math.imul(it, pt) | 0, s2 = s2 + Math.imul(nt, dt) | 0, v2 = v2 + Math.imul(nt, pt) | 0, l4 = l4 + Math.imul(et, vt) | 0, s2 = s2 + Math.imul(et, gt) | 0, s2 = s2 + Math.imul(rt, vt) | 0, v2 = v2 + Math.imul(rt, gt) | 0, l4 = l4 + Math.imul($, mt) | 0, s2 = s2 + Math.imul($, At) | 0, s2 = s2 + Math.imul(tt, mt) | 0, v2 = v2 + Math.imul(tt, At) | 0, l4 = l4 + Math.imul(X, bt) | 0, s2 = s2 + Math.imul(X, yt) | 0, s2 = s2 + Math.imul(Z, bt) | 0, v2 = v2 + Math.imul(Z, yt) | 0, l4 = l4 + Math.imul(T2, wt) | 0, s2 = s2 + Math.imul(T2, xt) | 0, s2 = s2 + Math.imul(q2, wt) | 0, v2 = v2 + Math.imul(q2, xt) | 0, l4 = l4 + Math.imul(P2, Mt) | 0, s2 = s2 + Math.imul(P2, Et) | 0, s2 = s2 + Math.imul(O3, Mt) | 0, v2 = v2 + Math.imul(O3, Et) | 0, l4 = l4 + Math.imul(B2, St) | 0, s2 = s2 + Math.imul(B2, Nt) | 0, s2 = s2 + Math.imul(C3, St) | 0, v2 = v2 + Math.imul(C3, Nt) | 0, l4 = l4 + Math.imul(u3, It) | 0, s2 = s2 + Math.imul(u3, _t) | 0, s2 = s2 + Math.imul(E4, It) | 0, v2 = v2 + Math.imul(E4, _t) | 0; + var ei = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ei >>> 26) | 0, ei &= 67108863, l4 = Math.imul(st, ct), s2 = Math.imul(st, lt), s2 = s2 + Math.imul(at, ct) | 0, v2 = Math.imul(at, lt), l4 = l4 + Math.imul(ft, dt) | 0, s2 = s2 + Math.imul(ft, pt) | 0, s2 = s2 + Math.imul(ot, dt) | 0, v2 = v2 + Math.imul(ot, pt) | 0, l4 = l4 + Math.imul(it, vt) | 0, s2 = s2 + Math.imul(it, gt) | 0, s2 = s2 + Math.imul(nt, vt) | 0, v2 = v2 + Math.imul(nt, gt) | 0, l4 = l4 + Math.imul(et, mt) | 0, s2 = s2 + Math.imul(et, At) | 0, s2 = s2 + Math.imul(rt, mt) | 0, v2 = v2 + Math.imul(rt, At) | 0, l4 = l4 + Math.imul($, bt) | 0, s2 = s2 + Math.imul($, yt) | 0, s2 = s2 + Math.imul(tt, bt) | 0, v2 = v2 + Math.imul(tt, yt) | 0, l4 = l4 + Math.imul(X, wt) | 0, s2 = s2 + Math.imul(X, xt) | 0, s2 = s2 + Math.imul(Z, wt) | 0, v2 = v2 + Math.imul(Z, xt) | 0, l4 = l4 + Math.imul(T2, Mt) | 0, s2 = s2 + Math.imul(T2, Et) | 0, s2 = s2 + Math.imul(q2, Mt) | 0, v2 = v2 + Math.imul(q2, Et) | 0, l4 = l4 + Math.imul(P2, St) | 0, s2 = s2 + Math.imul(P2, Nt) | 0, s2 = s2 + Math.imul(O3, St) | 0, v2 = v2 + Math.imul(O3, Nt) | 0, l4 = l4 + Math.imul(B2, It) | 0, s2 = s2 + Math.imul(B2, _t) | 0, s2 = s2 + Math.imul(C3, It) | 0, v2 = v2 + Math.imul(C3, _t) | 0; + var ri = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ri >>> 26) | 0, ri &= 67108863, l4 = Math.imul(st, dt), s2 = Math.imul(st, pt), s2 = s2 + Math.imul(at, dt) | 0, v2 = Math.imul(at, pt), l4 = l4 + Math.imul(ft, vt) | 0, s2 = s2 + Math.imul(ft, gt) | 0, s2 = s2 + Math.imul(ot, vt) | 0, v2 = v2 + Math.imul(ot, gt) | 0, l4 = l4 + Math.imul(it, mt) | 0, s2 = s2 + Math.imul(it, At) | 0, s2 = s2 + Math.imul(nt, mt) | 0, v2 = v2 + Math.imul(nt, At) | 0, l4 = l4 + Math.imul(et, bt) | 0, s2 = s2 + Math.imul(et, yt) | 0, s2 = s2 + Math.imul(rt, bt) | 0, v2 = v2 + Math.imul(rt, yt) | 0, l4 = l4 + Math.imul($, wt) | 0, s2 = s2 + Math.imul($, xt) | 0, s2 = s2 + Math.imul(tt, wt) | 0, v2 = v2 + Math.imul(tt, xt) | 0, l4 = l4 + Math.imul(X, Mt) | 0, s2 = s2 + Math.imul(X, Et) | 0, s2 = s2 + Math.imul(Z, Mt) | 0, v2 = v2 + Math.imul(Z, Et) | 0, l4 = l4 + Math.imul(T2, St) | 0, s2 = s2 + Math.imul(T2, Nt) | 0, s2 = s2 + Math.imul(q2, St) | 0, v2 = v2 + Math.imul(q2, Nt) | 0, l4 = l4 + Math.imul(P2, It) | 0, s2 = s2 + Math.imul(P2, _t) | 0, s2 = s2 + Math.imul(O3, It) | 0, v2 = v2 + Math.imul(O3, _t) | 0; + var ii = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ii >>> 26) | 0, ii &= 67108863, l4 = Math.imul(st, vt), s2 = Math.imul(st, gt), s2 = s2 + Math.imul(at, vt) | 0, v2 = Math.imul(at, gt), l4 = l4 + Math.imul(ft, mt) | 0, s2 = s2 + Math.imul(ft, At) | 0, s2 = s2 + Math.imul(ot, mt) | 0, v2 = v2 + Math.imul(ot, At) | 0, l4 = l4 + Math.imul(it, bt) | 0, s2 = s2 + Math.imul(it, yt) | 0, s2 = s2 + Math.imul(nt, bt) | 0, v2 = v2 + Math.imul(nt, yt) | 0, l4 = l4 + Math.imul(et, wt) | 0, s2 = s2 + Math.imul(et, xt) | 0, s2 = s2 + Math.imul(rt, wt) | 0, v2 = v2 + Math.imul(rt, xt) | 0, l4 = l4 + Math.imul($, Mt) | 0, s2 = s2 + Math.imul($, Et) | 0, s2 = s2 + Math.imul(tt, Mt) | 0, v2 = v2 + Math.imul(tt, Et) | 0, l4 = l4 + Math.imul(X, St) | 0, s2 = s2 + Math.imul(X, Nt) | 0, s2 = s2 + Math.imul(Z, St) | 0, v2 = v2 + Math.imul(Z, Nt) | 0, l4 = l4 + Math.imul(T2, It) | 0, s2 = s2 + Math.imul(T2, _t) | 0, s2 = s2 + Math.imul(q2, It) | 0, v2 = v2 + Math.imul(q2, _t) | 0; + var ni = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ni >>> 26) | 0, ni &= 67108863, l4 = Math.imul(st, mt), s2 = Math.imul(st, At), s2 = s2 + Math.imul(at, mt) | 0, v2 = Math.imul(at, At), l4 = l4 + Math.imul(ft, bt) | 0, s2 = s2 + Math.imul(ft, yt) | 0, s2 = s2 + Math.imul(ot, bt) | 0, v2 = v2 + Math.imul(ot, yt) | 0, l4 = l4 + Math.imul(it, wt) | 0, s2 = s2 + Math.imul(it, xt) | 0, s2 = s2 + Math.imul(nt, wt) | 0, v2 = v2 + Math.imul(nt, xt) | 0, l4 = l4 + Math.imul(et, Mt) | 0, s2 = s2 + Math.imul(et, Et) | 0, s2 = s2 + Math.imul(rt, Mt) | 0, v2 = v2 + Math.imul(rt, Et) | 0, l4 = l4 + Math.imul($, St) | 0, s2 = s2 + Math.imul($, Nt) | 0, s2 = s2 + Math.imul(tt, St) | 0, v2 = v2 + Math.imul(tt, Nt) | 0, l4 = l4 + Math.imul(X, It) | 0, s2 = s2 + Math.imul(X, _t) | 0, s2 = s2 + Math.imul(Z, It) | 0, v2 = v2 + Math.imul(Z, _t) | 0; + var fi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (fi >>> 26) | 0, fi &= 67108863, l4 = Math.imul(st, bt), s2 = Math.imul(st, yt), s2 = s2 + Math.imul(at, bt) | 0, v2 = Math.imul(at, yt), l4 = l4 + Math.imul(ft, wt) | 0, s2 = s2 + Math.imul(ft, xt) | 0, s2 = s2 + Math.imul(ot, wt) | 0, v2 = v2 + Math.imul(ot, xt) | 0, l4 = l4 + Math.imul(it, Mt) | 0, s2 = s2 + Math.imul(it, Et) | 0, s2 = s2 + Math.imul(nt, Mt) | 0, v2 = v2 + Math.imul(nt, Et) | 0, l4 = l4 + Math.imul(et, St) | 0, s2 = s2 + Math.imul(et, Nt) | 0, s2 = s2 + Math.imul(rt, St) | 0, v2 = v2 + Math.imul(rt, Nt) | 0, l4 = l4 + Math.imul($, It) | 0, s2 = s2 + Math.imul($, _t) | 0, s2 = s2 + Math.imul(tt, It) | 0, v2 = v2 + Math.imul(tt, _t) | 0; + var oi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (oi >>> 26) | 0, oi &= 67108863, l4 = Math.imul(st, wt), s2 = Math.imul(st, xt), s2 = s2 + Math.imul(at, wt) | 0, v2 = Math.imul(at, xt), l4 = l4 + Math.imul(ft, Mt) | 0, s2 = s2 + Math.imul(ft, Et) | 0, s2 = s2 + Math.imul(ot, Mt) | 0, v2 = v2 + Math.imul(ot, Et) | 0, l4 = l4 + Math.imul(it, St) | 0, s2 = s2 + Math.imul(it, Nt) | 0, s2 = s2 + Math.imul(nt, St) | 0, v2 = v2 + Math.imul(nt, Nt) | 0, l4 = l4 + Math.imul(et, It) | 0, s2 = s2 + Math.imul(et, _t) | 0, s2 = s2 + Math.imul(rt, It) | 0, v2 = v2 + Math.imul(rt, _t) | 0; + var si = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (si >>> 26) | 0, si &= 67108863, l4 = Math.imul(st, Mt), s2 = Math.imul(st, Et), s2 = s2 + Math.imul(at, Mt) | 0, v2 = Math.imul(at, Et), l4 = l4 + Math.imul(ft, St) | 0, s2 = s2 + Math.imul(ft, Nt) | 0, s2 = s2 + Math.imul(ot, St) | 0, v2 = v2 + Math.imul(ot, Nt) | 0, l4 = l4 + Math.imul(it, It) | 0, s2 = s2 + Math.imul(it, _t) | 0, s2 = s2 + Math.imul(nt, It) | 0, v2 = v2 + Math.imul(nt, _t) | 0; + var ai = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ai >>> 26) | 0, ai &= 67108863, l4 = Math.imul(st, St), s2 = Math.imul(st, Nt), s2 = s2 + Math.imul(at, St) | 0, v2 = Math.imul(at, Nt), l4 = l4 + Math.imul(ft, It) | 0, s2 = s2 + Math.imul(ft, _t) | 0, s2 = s2 + Math.imul(ot, It) | 0, v2 = v2 + Math.imul(ot, _t) | 0; + var ui = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + M = (v2 + (s2 >>> 13) | 0) + (ui >>> 26) | 0, ui &= 67108863, l4 = Math.imul(st, It), s2 = Math.imul(st, _t), s2 = s2 + Math.imul(at, It) | 0, v2 = Math.imul(at, _t); + var hi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; + return M = (v2 + (s2 >>> 13) | 0) + (hi >>> 26) | 0, hi &= 67108863, x3[0] = xe, x3[1] = Me, x3[2] = Ee, x3[3] = Se, x3[4] = Ne, x3[5] = Xr, x3[6] = Zr, x3[7] = $r, x3[8] = ti, x3[9] = ei, x3[10] = ri, x3[11] = ii, x3[12] = ni, x3[13] = fi, x3[14] = oi, x3[15] = si, x3[16] = ai, x3[17] = ui, x3[18] = hi, M !== 0 && (x3[19] = M, c4.length++), c4; + }; + Math.imul || (Q = U2); + function Bt(A2, f4, a3) { + a3.negative = f4.negative ^ A2.negative, a3.length = A2.length + f4.length; + for (var c4 = 0, d3 = 0, m3 = 0; m3 < a3.length - 1; m3++) { + var x3 = d3; + d3 = 0; + for (var M = c4 & 67108863, l4 = Math.min(m3, f4.length - 1), s2 = Math.max(0, m3 - A2.length + 1); s2 <= l4; s2++) { + var v2 = m3 - s2, k4 = A2.words[v2] | 0, u3 = f4.words[s2] | 0, E4 = k4 * u3, _4 = E4 & 67108863; + x3 = x3 + (E4 / 67108864 | 0) | 0, _4 = _4 + M | 0, M = _4 & 67108863, x3 = x3 + (_4 >>> 26) | 0, d3 += x3 >>> 26, x3 &= 67108863; + } + a3.words[m3] = M, c4 = x3, x3 = d3; + } + return c4 !== 0 ? a3.words[m3] = c4 : a3.length--, a3._strip(); + } + function J(A2, f4, a3) { + return Bt(A2, f4, a3); + } + o2.prototype.mulTo = function(f4, a3) { + var c4, d3 = this.length + f4.length; + return this.length === 10 && f4.length === 10 ? c4 = Q(this, f4, a3) : d3 < 63 ? c4 = U2(this, f4, a3) : d3 < 1024 ? c4 = Bt(this, f4, a3) : c4 = J(this, f4, a3), c4; + }, o2.prototype.mul = function(f4) { + var a3 = new o2(null); + return a3.words = new Array(this.length + f4.length), this.mulTo(f4, a3); + }, o2.prototype.mulf = function(f4) { + var a3 = new o2(null); + return a3.words = new Array(this.length + f4.length), J(this, f4, a3); + }, o2.prototype.imul = function(f4) { + return this.clone().mulTo(f4, this); + }, o2.prototype.imuln = function(f4) { + var a3 = f4 < 0; + a3 && (f4 = -f4), i2(typeof f4 == "number"), i2(f4 < 67108864); + for (var c4 = 0, d3 = 0; d3 < this.length; d3++) { + var m3 = (this.words[d3] | 0) * f4, x3 = (m3 & 67108863) + (c4 & 67108863); + c4 >>= 26, c4 += m3 / 67108864 | 0, c4 += x3 >>> 26, this.words[d3] = x3 & 67108863; + } + return c4 !== 0 && (this.words[d3] = c4, this.length++), a3 ? this.ineg() : this; + }, o2.prototype.muln = function(f4) { + return this.clone().imuln(f4); + }, o2.prototype.sqr = function() { + return this.mul(this); + }, o2.prototype.isqr = function() { + return this.imul(this.clone()); + }, o2.prototype.pow = function(f4) { + var a3 = F(f4); + if (a3.length === 0) + return new o2(1); + for (var c4 = this, d3 = 0; d3 < a3.length && a3[d3] === 0; d3++, c4 = c4.sqr()) + ; + if (++d3 < a3.length) + for (var m3 = c4.sqr(); d3 < a3.length; d3++, m3 = m3.sqr()) + a3[d3] !== 0 && (c4 = c4.mul(m3)); + return c4; + }, o2.prototype.iushln = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 67108863 >>> 26 - a3 << 26 - a3, m3; + if (a3 !== 0) { + var x3 = 0; + for (m3 = 0; m3 < this.length; m3++) { + var M = this.words[m3] & d3, l4 = (this.words[m3] | 0) - M << a3; + this.words[m3] = l4 | x3, x3 = M >>> 26 - a3; + } + x3 && (this.words[m3] = x3, this.length++); + } + if (c4 !== 0) { + for (m3 = this.length - 1; m3 >= 0; m3--) + this.words[m3 + c4] = this.words[m3]; + for (m3 = 0; m3 < c4; m3++) + this.words[m3] = 0; + this.length += c4; + } + return this._strip(); + }, o2.prototype.ishln = function(f4) { + return i2(this.negative === 0), this.iushln(f4); + }, o2.prototype.iushrn = function(f4, a3, c4) { + i2(typeof f4 == "number" && f4 >= 0); + var d3; + a3 ? d3 = (a3 - a3 % 26) / 26 : d3 = 0; + var m3 = f4 % 26, x3 = Math.min((f4 - m3) / 26, this.length), M = 67108863 ^ 67108863 >>> m3 << m3, l4 = c4; + if (d3 -= x3, d3 = Math.max(0, d3), l4) { + for (var s2 = 0; s2 < x3; s2++) + l4.words[s2] = this.words[s2]; + l4.length = x3; + } + if (x3 !== 0) + if (this.length > x3) + for (this.length -= x3, s2 = 0; s2 < this.length; s2++) + this.words[s2] = this.words[s2 + x3]; + else + this.words[0] = 0, this.length = 1; + var v2 = 0; + for (s2 = this.length - 1; s2 >= 0 && (v2 !== 0 || s2 >= d3); s2--) { + var k4 = this.words[s2] | 0; + this.words[s2] = v2 << 26 - m3 | k4 >>> m3, v2 = k4 & M; + } + return l4 && v2 !== 0 && (l4.words[l4.length++] = v2), this.length === 0 && (this.words[0] = 0, this.length = 1), this._strip(); + }, o2.prototype.ishrn = function(f4, a3, c4) { + return i2(this.negative === 0), this.iushrn(f4, a3, c4); + }, o2.prototype.shln = function(f4) { + return this.clone().ishln(f4); + }, o2.prototype.ushln = function(f4) { + return this.clone().iushln(f4); + }, o2.prototype.shrn = function(f4) { + return this.clone().ishrn(f4); + }, o2.prototype.ushrn = function(f4) { + return this.clone().iushrn(f4); + }, o2.prototype.testn = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; + if (this.length <= c4) + return false; + var m3 = this.words[c4]; + return !!(m3 & d3); + }, o2.prototype.imaskn = function(f4) { + i2(typeof f4 == "number" && f4 >= 0); + var a3 = f4 % 26, c4 = (f4 - a3) / 26; + if (i2(this.negative === 0, "imaskn works only with positive numbers"), this.length <= c4) + return this; + if (a3 !== 0 && c4++, this.length = Math.min(c4, this.length), a3 !== 0) { + var d3 = 67108863 ^ 67108863 >>> a3 << a3; + this.words[this.length - 1] &= d3; + } + return this._strip(); + }, o2.prototype.maskn = function(f4) { + return this.clone().imaskn(f4); + }, o2.prototype.iaddn = function(f4) { + return i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0 ? this.isubn(-f4) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) <= f4 ? (this.words[0] = f4 - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(f4), this.negative = 1, this) : this._iaddn(f4); + }, o2.prototype._iaddn = function(f4) { + this.words[0] += f4; + for (var a3 = 0; a3 < this.length && this.words[a3] >= 67108864; a3++) + this.words[a3] -= 67108864, a3 === this.length - 1 ? this.words[a3 + 1] = 1 : this.words[a3 + 1]++; + return this.length = Math.max(this.length, a3 + 1), this; + }, o2.prototype.isubn = function(f4) { + if (i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0) + return this.iaddn(-f4); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(f4), this.negative = 1, this; + if (this.words[0] -= f4, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a3 = 0; a3 < this.length && this.words[a3] < 0; a3++) + this.words[a3] += 67108864, this.words[a3 + 1] -= 1; + return this._strip(); + }, o2.prototype.addn = function(f4) { + return this.clone().iaddn(f4); + }, o2.prototype.subn = function(f4) { + return this.clone().isubn(f4); + }, o2.prototype.iabs = function() { + return this.negative = 0, this; + }, o2.prototype.abs = function() { + return this.clone().iabs(); + }, o2.prototype._ishlnsubmul = function(f4, a3, c4) { + var d3 = f4.length + c4, m3; + this._expand(d3); + var x3, M = 0; + for (m3 = 0; m3 < f4.length; m3++) { + x3 = (this.words[m3 + c4] | 0) + M; + var l4 = (f4.words[m3] | 0) * a3; + x3 -= l4 & 67108863, M = (x3 >> 26) - (l4 / 67108864 | 0), this.words[m3 + c4] = x3 & 67108863; + } + for (; m3 < this.length - c4; m3++) + x3 = (this.words[m3 + c4] | 0) + M, M = x3 >> 26, this.words[m3 + c4] = x3 & 67108863; + if (M === 0) + return this._strip(); + for (i2(M === -1), M = 0, m3 = 0; m3 < this.length; m3++) + x3 = -(this.words[m3] | 0) + M, M = x3 >> 26, this.words[m3] = x3 & 67108863; + return this.negative = 1, this._strip(); + }, o2.prototype._wordDiv = function(f4, a3) { + var c4 = this.length - f4.length, d3 = this.clone(), m3 = f4, x3 = m3.words[m3.length - 1] | 0, M = this._countBits(x3); + c4 = 26 - M, c4 !== 0 && (m3 = m3.ushln(c4), d3.iushln(c4), x3 = m3.words[m3.length - 1] | 0); + var l4 = d3.length - m3.length, s2; + if (a3 !== "mod") { + s2 = new o2(null), s2.length = l4 + 1, s2.words = new Array(s2.length); + for (var v2 = 0; v2 < s2.length; v2++) + s2.words[v2] = 0; + } + var k4 = d3.clone()._ishlnsubmul(m3, 1, l4); + k4.negative === 0 && (d3 = k4, s2 && (s2.words[l4] = 1)); + for (var u3 = l4 - 1; u3 >= 0; u3--) { + var E4 = (d3.words[m3.length + u3] | 0) * 67108864 + (d3.words[m3.length + u3 - 1] | 0); + for (E4 = Math.min(E4 / x3 | 0, 67108863), d3._ishlnsubmul(m3, E4, u3); d3.negative !== 0; ) + E4--, d3.negative = 0, d3._ishlnsubmul(m3, 1, u3), d3.isZero() || (d3.negative ^= 1); + s2 && (s2.words[u3] = E4); + } + return s2 && s2._strip(), d3._strip(), a3 !== "div" && c4 !== 0 && d3.iushrn(c4), { div: s2 || null, mod: d3 }; + }, o2.prototype.divmod = function(f4, a3, c4) { + if (i2(!f4.isZero()), this.isZero()) + return { div: new o2(0), mod: new o2(0) }; + var d3, m3, x3; + return this.negative !== 0 && f4.negative === 0 ? (x3 = this.neg().divmod(f4, a3), a3 !== "mod" && (d3 = x3.div.neg()), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.iadd(f4)), { div: d3, mod: m3 }) : this.negative === 0 && f4.negative !== 0 ? (x3 = this.divmod(f4.neg(), a3), a3 !== "mod" && (d3 = x3.div.neg()), { div: d3, mod: x3.mod }) : this.negative & f4.negative ? (x3 = this.neg().divmod(f4.neg(), a3), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.isub(f4)), { div: x3.div, mod: m3 }) : f4.length > this.length || this.cmp(f4) < 0 ? { div: new o2(0), mod: this } : f4.length === 1 ? a3 === "div" ? { div: this.divn(f4.words[0]), mod: null } : a3 === "mod" ? { div: null, mod: new o2(this.modrn(f4.words[0])) } : { div: this.divn(f4.words[0]), mod: new o2(this.modrn(f4.words[0])) } : this._wordDiv(f4, a3); + }, o2.prototype.div = function(f4) { + return this.divmod(f4, "div", false).div; + }, o2.prototype.mod = function(f4) { + return this.divmod(f4, "mod", false).mod; + }, o2.prototype.umod = function(f4) { + return this.divmod(f4, "mod", true).mod; + }, o2.prototype.divRound = function(f4) { + var a3 = this.divmod(f4); + if (a3.mod.isZero()) + return a3.div; + var c4 = a3.div.negative !== 0 ? a3.mod.isub(f4) : a3.mod, d3 = f4.ushrn(1), m3 = f4.andln(1), x3 = c4.cmp(d3); + return x3 < 0 || m3 === 1 && x3 === 0 ? a3.div : a3.div.negative !== 0 ? a3.div.isubn(1) : a3.div.iaddn(1); + }, o2.prototype.modrn = function(f4) { + var a3 = f4 < 0; + a3 && (f4 = -f4), i2(f4 <= 67108863); + for (var c4 = (1 << 26) % f4, d3 = 0, m3 = this.length - 1; m3 >= 0; m3--) + d3 = (c4 * d3 + (this.words[m3] | 0)) % f4; + return a3 ? -d3 : d3; + }, o2.prototype.modn = function(f4) { + return this.modrn(f4); + }, o2.prototype.idivn = function(f4) { + var a3 = f4 < 0; + a3 && (f4 = -f4), i2(f4 <= 67108863); + for (var c4 = 0, d3 = this.length - 1; d3 >= 0; d3--) { + var m3 = (this.words[d3] | 0) + c4 * 67108864; + this.words[d3] = m3 / f4 | 0, c4 = m3 % f4; + } + return this._strip(), a3 ? this.ineg() : this; + }, o2.prototype.divn = function(f4) { + return this.clone().idivn(f4); + }, o2.prototype.egcd = function(f4) { + i2(f4.negative === 0), i2(!f4.isZero()); + var a3 = this, c4 = f4.clone(); + a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); + for (var d3 = new o2(1), m3 = new o2(0), x3 = new o2(0), M = new o2(1), l4 = 0; a3.isEven() && c4.isEven(); ) + a3.iushrn(1), c4.iushrn(1), ++l4; + for (var s2 = c4.clone(), v2 = a3.clone(); !a3.isZero(); ) { + for (var k4 = 0, u3 = 1; !(a3.words[0] & u3) && k4 < 26; ++k4, u3 <<= 1) + ; + if (k4 > 0) + for (a3.iushrn(k4); k4-- > 0; ) + (d3.isOdd() || m3.isOdd()) && (d3.iadd(s2), m3.isub(v2)), d3.iushrn(1), m3.iushrn(1); + for (var E4 = 0, _4 = 1; !(c4.words[0] & _4) && E4 < 26; ++E4, _4 <<= 1) + ; + if (E4 > 0) + for (c4.iushrn(E4); E4-- > 0; ) + (x3.isOdd() || M.isOdd()) && (x3.iadd(s2), M.isub(v2)), x3.iushrn(1), M.iushrn(1); + a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(x3), m3.isub(M)) : (c4.isub(a3), x3.isub(d3), M.isub(m3)); + } + return { a: x3, b: M, gcd: c4.iushln(l4) }; + }, o2.prototype._invmp = function(f4) { + i2(f4.negative === 0), i2(!f4.isZero()); + var a3 = this, c4 = f4.clone(); + a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); + for (var d3 = new o2(1), m3 = new o2(0), x3 = c4.clone(); a3.cmpn(1) > 0 && c4.cmpn(1) > 0; ) { + for (var M = 0, l4 = 1; !(a3.words[0] & l4) && M < 26; ++M, l4 <<= 1) + ; + if (M > 0) + for (a3.iushrn(M); M-- > 0; ) + d3.isOdd() && d3.iadd(x3), d3.iushrn(1); + for (var s2 = 0, v2 = 1; !(c4.words[0] & v2) && s2 < 26; ++s2, v2 <<= 1) + ; + if (s2 > 0) + for (c4.iushrn(s2); s2-- > 0; ) + m3.isOdd() && m3.iadd(x3), m3.iushrn(1); + a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(m3)) : (c4.isub(a3), m3.isub(d3)); + } + var k4; + return a3.cmpn(1) === 0 ? k4 = d3 : k4 = m3, k4.cmpn(0) < 0 && k4.iadd(f4), k4; + }, o2.prototype.gcd = function(f4) { + if (this.isZero()) + return f4.abs(); + if (f4.isZero()) + return this.abs(); + var a3 = this.clone(), c4 = f4.clone(); + a3.negative = 0, c4.negative = 0; + for (var d3 = 0; a3.isEven() && c4.isEven(); d3++) + a3.iushrn(1), c4.iushrn(1); + do { + for (; a3.isEven(); ) + a3.iushrn(1); + for (; c4.isEven(); ) + c4.iushrn(1); + var m3 = a3.cmp(c4); + if (m3 < 0) { + var x3 = a3; + a3 = c4, c4 = x3; + } else if (m3 === 0 || c4.cmpn(1) === 0) + break; + a3.isub(c4); + } while (true); + return c4.iushln(d3); + }, o2.prototype.invm = function(f4) { + return this.egcd(f4).a.umod(f4); + }, o2.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, o2.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, o2.prototype.andln = function(f4) { + return this.words[0] & f4; + }, o2.prototype.bincn = function(f4) { + i2(typeof f4 == "number"); + var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; + if (this.length <= c4) + return this._expand(c4 + 1), this.words[c4] |= d3, this; + for (var m3 = d3, x3 = c4; m3 !== 0 && x3 < this.length; x3++) { + var M = this.words[x3] | 0; + M += m3, m3 = M >>> 26, M &= 67108863, this.words[x3] = M; + } + return m3 !== 0 && (this.words[x3] = m3, this.length++), this; + }, o2.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, o2.prototype.cmpn = function(f4) { + var a3 = f4 < 0; + if (this.negative !== 0 && !a3) + return -1; + if (this.negative === 0 && a3) + return 1; + this._strip(); + var c4; + if (this.length > 1) + c4 = 1; + else { + a3 && (f4 = -f4), i2(f4 <= 67108863, "Number is too big"); + var d3 = this.words[0] | 0; + c4 = d3 === f4 ? 0 : d3 < f4 ? -1 : 1; + } + return this.negative !== 0 ? -c4 | 0 : c4; + }, o2.prototype.cmp = function(f4) { + if (this.negative !== 0 && f4.negative === 0) + return -1; + if (this.negative === 0 && f4.negative !== 0) + return 1; + var a3 = this.ucmp(f4); + return this.negative !== 0 ? -a3 | 0 : a3; + }, o2.prototype.ucmp = function(f4) { + if (this.length > f4.length) + return 1; + if (this.length < f4.length) + return -1; + for (var a3 = 0, c4 = this.length - 1; c4 >= 0; c4--) { + var d3 = this.words[c4] | 0, m3 = f4.words[c4] | 0; + if (d3 !== m3) { + d3 < m3 ? a3 = -1 : d3 > m3 && (a3 = 1); + break; + } + } + return a3; + }, o2.prototype.gtn = function(f4) { + return this.cmpn(f4) === 1; + }, o2.prototype.gt = function(f4) { + return this.cmp(f4) === 1; + }, o2.prototype.gten = function(f4) { + return this.cmpn(f4) >= 0; + }, o2.prototype.gte = function(f4) { + return this.cmp(f4) >= 0; + }, o2.prototype.ltn = function(f4) { + return this.cmpn(f4) === -1; + }, o2.prototype.lt = function(f4) { + return this.cmp(f4) === -1; + }, o2.prototype.lten = function(f4) { + return this.cmpn(f4) <= 0; + }, o2.prototype.lte = function(f4) { + return this.cmp(f4) <= 0; + }, o2.prototype.eqn = function(f4) { + return this.cmpn(f4) === 0; + }, o2.prototype.eq = function(f4) { + return this.cmp(f4) === 0; + }, o2.red = function(f4) { + return new Y(f4); + }, o2.prototype.toRed = function(f4) { + return i2(!this.red, "Already a number in reduction context"), i2(this.negative === 0, "red works only with positives"), f4.convertTo(this)._forceRed(f4); + }, o2.prototype.fromRed = function() { + return i2(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, o2.prototype._forceRed = function(f4) { + return this.red = f4, this; + }, o2.prototype.forceRed = function(f4) { + return i2(!this.red, "Already a number in reduction context"), this._forceRed(f4); + }, o2.prototype.redAdd = function(f4) { + return i2(this.red, "redAdd works only with red numbers"), this.red.add(this, f4); + }, o2.prototype.redIAdd = function(f4) { + return i2(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, f4); + }, o2.prototype.redSub = function(f4) { + return i2(this.red, "redSub works only with red numbers"), this.red.sub(this, f4); + }, o2.prototype.redISub = function(f4) { + return i2(this.red, "redISub works only with red numbers"), this.red.isub(this, f4); + }, o2.prototype.redShl = function(f4) { + return i2(this.red, "redShl works only with red numbers"), this.red.shl(this, f4); + }, o2.prototype.redMul = function(f4) { + return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.mul(this, f4); + }, o2.prototype.redIMul = function(f4) { + return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.imul(this, f4); + }, o2.prototype.redSqr = function() { + return i2(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, o2.prototype.redISqr = function() { + return i2(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, o2.prototype.redSqrt = function() { + return i2(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, o2.prototype.redInvm = function() { + return i2(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, o2.prototype.redNeg = function() { + return i2(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, o2.prototype.redPow = function(f4) { + return i2(this.red && !f4.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, f4); + }; + var H = { k256: null, p224: null, p192: null, p25519: null }; + function L2(A2, f4) { + this.name = A2, this.p = new o2(f4, 16), this.n = this.p.bitLength(), this.k = new o2(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + L2.prototype._tmp = function() { + var f4 = new o2(null); + return f4.words = new Array(Math.ceil(this.n / 13)), f4; + }, L2.prototype.ireduce = function(f4) { + var a3 = f4, c4; + do + this.split(a3, this.tmp), a3 = this.imulK(a3), a3 = a3.iadd(this.tmp), c4 = a3.bitLength(); + while (c4 > this.n); + var d3 = c4 < this.n ? -1 : a3.ucmp(this.p); + return d3 === 0 ? (a3.words[0] = 0, a3.length = 1) : d3 > 0 ? a3.isub(this.p) : a3.strip !== void 0 ? a3.strip() : a3._strip(), a3; + }, L2.prototype.split = function(f4, a3) { + f4.iushrn(this.n, 0, a3); + }, L2.prototype.imulK = function(f4) { + return f4.imul(this.k); + }; + function Tt() { + L2.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + n3(Tt, L2), Tt.prototype.split = function(f4, a3) { + for (var c4 = 4194303, d3 = Math.min(f4.length, 9), m3 = 0; m3 < d3; m3++) + a3.words[m3] = f4.words[m3]; + if (a3.length = d3, f4.length <= 9) { + f4.words[0] = 0, f4.length = 1; + return; + } + var x3 = f4.words[9]; + for (a3.words[a3.length++] = x3 & c4, m3 = 10; m3 < f4.length; m3++) { + var M = f4.words[m3] | 0; + f4.words[m3 - 10] = (M & c4) << 4 | x3 >>> 22, x3 = M; + } + x3 >>>= 22, f4.words[m3 - 10] = x3, x3 === 0 && f4.length > 10 ? f4.length -= 10 : f4.length -= 9; + }, Tt.prototype.imulK = function(f4) { + f4.words[f4.length] = 0, f4.words[f4.length + 1] = 0, f4.length += 2; + for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { + var d3 = f4.words[c4] | 0; + a3 += d3 * 977, f4.words[c4] = a3 & 67108863, a3 = d3 * 64 + (a3 / 67108864 | 0); + } + return f4.words[f4.length - 1] === 0 && (f4.length--, f4.words[f4.length - 1] === 0 && f4.length--), f4; + }; + function W() { + L2.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + n3(W, L2); + function Ot() { + L2.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + n3(Ot, L2); + function Gt() { + L2.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + n3(Gt, L2), Gt.prototype.imulK = function(f4) { + for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { + var d3 = (f4.words[c4] | 0) * 19 + a3, m3 = d3 & 67108863; + d3 >>>= 26, f4.words[c4] = m3, a3 = d3; + } + return a3 !== 0 && (f4.words[f4.length++] = a3), f4; + }, o2._prime = function(f4) { + if (H[f4]) + return H[f4]; + var a3; + if (f4 === "k256") + a3 = new Tt(); + else if (f4 === "p224") + a3 = new W(); + else if (f4 === "p192") + a3 = new Ot(); + else if (f4 === "p25519") + a3 = new Gt(); + else + throw new Error("Unknown prime " + f4); + return H[f4] = a3, a3; + }; + function Y(A2) { + if (typeof A2 == "string") { + var f4 = o2._prime(A2); + this.m = f4.p, this.prime = f4; + } else + i2(A2.gtn(1), "modulus must be greater than 1"), this.m = A2, this.prime = null; + } + Y.prototype._verify1 = function(f4) { + i2(f4.negative === 0, "red works only with positives"), i2(f4.red, "red works only with red numbers"); + }, Y.prototype._verify2 = function(f4, a3) { + i2((f4.negative | a3.negative) === 0, "red works only with positives"), i2(f4.red && f4.red === a3.red, "red works only with red numbers"); + }, Y.prototype.imod = function(f4) { + return this.prime ? this.prime.ireduce(f4)._forceRed(this) : (w4(f4, f4.umod(this.m)._forceRed(this)), f4); + }, Y.prototype.neg = function(f4) { + return f4.isZero() ? f4.clone() : this.m.sub(f4)._forceRed(this); + }, Y.prototype.add = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.add(a3); + return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4._forceRed(this); + }, Y.prototype.iadd = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.iadd(a3); + return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4; + }, Y.prototype.sub = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.sub(a3); + return c4.cmpn(0) < 0 && c4.iadd(this.m), c4._forceRed(this); + }, Y.prototype.isub = function(f4, a3) { + this._verify2(f4, a3); + var c4 = f4.isub(a3); + return c4.cmpn(0) < 0 && c4.iadd(this.m), c4; + }, Y.prototype.shl = function(f4, a3) { + return this._verify1(f4), this.imod(f4.ushln(a3)); + }, Y.prototype.imul = function(f4, a3) { + return this._verify2(f4, a3), this.imod(f4.imul(a3)); + }, Y.prototype.mul = function(f4, a3) { + return this._verify2(f4, a3), this.imod(f4.mul(a3)); + }, Y.prototype.isqr = function(f4) { + return this.imul(f4, f4.clone()); + }, Y.prototype.sqr = function(f4) { + return this.mul(f4, f4); + }, Y.prototype.sqrt = function(f4) { + if (f4.isZero()) + return f4.clone(); + var a3 = this.m.andln(3); + if (i2(a3 % 2 === 1), a3 === 3) { + var c4 = this.m.add(new o2(1)).iushrn(2); + return this.pow(f4, c4); + } + for (var d3 = this.m.subn(1), m3 = 0; !d3.isZero() && d3.andln(1) === 0; ) + m3++, d3.iushrn(1); + i2(!d3.isZero()); + var x3 = new o2(1).toRed(this), M = x3.redNeg(), l4 = this.m.subn(1).iushrn(1), s2 = this.m.bitLength(); + for (s2 = new o2(2 * s2 * s2).toRed(this); this.pow(s2, l4).cmp(M) !== 0; ) + s2.redIAdd(M); + for (var v2 = this.pow(s2, d3), k4 = this.pow(f4, d3.addn(1).iushrn(1)), u3 = this.pow(f4, d3), E4 = m3; u3.cmp(x3) !== 0; ) { + for (var _4 = u3, B2 = 0; _4.cmp(x3) !== 0; B2++) + _4 = _4.redSqr(); + i2(B2 < E4); + var C3 = this.pow(v2, new o2(1).iushln(E4 - B2 - 1)); + k4 = k4.redMul(C3), v2 = C3.redSqr(), u3 = u3.redMul(v2), E4 = B2; + } + return k4; + }, Y.prototype.invm = function(f4) { + var a3 = f4._invmp(this.m); + return a3.negative !== 0 ? (a3.negative = 0, this.imod(a3).redNeg()) : this.imod(a3); + }, Y.prototype.pow = function(f4, a3) { + if (a3.isZero()) + return new o2(1).toRed(this); + if (a3.cmpn(1) === 0) + return f4.clone(); + var c4 = 4, d3 = new Array(1 << c4); + d3[0] = new o2(1).toRed(this), d3[1] = f4; + for (var m3 = 2; m3 < d3.length; m3++) + d3[m3] = this.mul(d3[m3 - 1], f4); + var x3 = d3[0], M = 0, l4 = 0, s2 = a3.bitLength() % 26; + for (s2 === 0 && (s2 = 26), m3 = a3.length - 1; m3 >= 0; m3--) { + for (var v2 = a3.words[m3], k4 = s2 - 1; k4 >= 0; k4--) { + var u3 = v2 >> k4 & 1; + if (x3 !== d3[0] && (x3 = this.sqr(x3)), u3 === 0 && M === 0) { + l4 = 0; + continue; + } + M <<= 1, M |= u3, l4++, !(l4 !== c4 && (m3 !== 0 || k4 !== 0)) && (x3 = this.mul(x3, d3[M]), l4 = 0, M = 0); + } + s2 = 26; + } + return x3; + }, Y.prototype.convertTo = function(f4) { + var a3 = f4.umod(this.m); + return a3 === f4 ? a3.clone() : a3; + }, Y.prototype.convertFrom = function(f4) { + var a3 = f4.clone(); + return a3.red = null, a3; + }, o2.mont = function(f4) { + return new Wt(f4); + }; + function Wt(A2) { + Y.call(this, A2), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new o2(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + n3(Wt, Y), Wt.prototype.convertTo = function(f4) { + return this.imod(f4.ushln(this.shift)); + }, Wt.prototype.convertFrom = function(f4) { + var a3 = this.imod(f4.mul(this.rinv)); + return a3.red = null, a3; + }, Wt.prototype.imul = function(f4, a3) { + if (f4.isZero() || a3.isZero()) + return f4.words[0] = 0, f4.length = 1, f4; + var c4 = f4.imul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; + return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); + }, Wt.prototype.mul = function(f4, a3) { + if (f4.isZero() || a3.isZero()) + return new o2(0)._forceRed(this); + var c4 = f4.mul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; + return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); + }, Wt.prototype.invm = function(f4) { + var a3 = this.imod(f4._invmp(this.m).mul(this.r2)); + return a3._forceRed(this); + }; + })(e2, _n); + })(qn); + var K2 = qn.exports; + var Kn = "bignumber/5.7.0"; + var Or = K2.BN; + var me = new z3(Kn); + var xi = {}; + var Hn = 9007199254740991; + function Ns(e2) { + return e2 != null && (G.isBigNumber(e2) || typeof e2 == "number" && e2 % 1 === 0 || typeof e2 == "string" && !!e2.match(/^-?[0-9]+$/) || Qt(e2) || typeof e2 == "bigint" || nr(e2)); + } + var Ln = false; + var G = class _G { + constructor(t, r) { + t !== xi && me.throwError("cannot call constructor directly; use BigNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new (BigNumber)" }), this._hex = r, this._isBigNumber = true, Object.freeze(this); + } + fromTwos(t) { + return jt(j2(this).fromTwos(t)); + } + toTwos(t) { + return jt(j2(this).toTwos(t)); + } + abs() { + return this._hex[0] === "-" ? _G.from(this._hex.substring(1)) : this; + } + add(t) { + return jt(j2(this).add(j2(t))); + } + sub(t) { + return jt(j2(this).sub(j2(t))); + } + div(t) { + return _G.from(t).isZero() && Xt("division-by-zero", "div"), jt(j2(this).div(j2(t))); + } + mul(t) { + return jt(j2(this).mul(j2(t))); + } + mod(t) { + const r = j2(t); + return r.isNeg() && Xt("division-by-zero", "mod"), jt(j2(this).umod(r)); + } + pow(t) { + const r = j2(t); + return r.isNeg() && Xt("negative-power", "pow"), jt(j2(this).pow(r)); + } + and(t) { + const r = j2(t); + return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "and"), jt(j2(this).and(r)); + } + or(t) { + const r = j2(t); + return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "or"), jt(j2(this).or(r)); + } + xor(t) { + const r = j2(t); + return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "xor"), jt(j2(this).xor(r)); + } + mask(t) { + return (this.isNegative() || t < 0) && Xt("negative-width", "mask"), jt(j2(this).maskn(t)); + } + shl(t) { + return (this.isNegative() || t < 0) && Xt("negative-width", "shl"), jt(j2(this).shln(t)); + } + shr(t) { + return (this.isNegative() || t < 0) && Xt("negative-width", "shr"), jt(j2(this).shrn(t)); + } + eq(t) { + return j2(this).eq(j2(t)); + } + lt(t) { + return j2(this).lt(j2(t)); + } + lte(t) { + return j2(this).lte(j2(t)); + } + gt(t) { + return j2(this).gt(j2(t)); + } + gte(t) { + return j2(this).gte(j2(t)); + } + isNegative() { + return this._hex[0] === "-"; + } + isZero() { + return j2(this).isZero(); + } + toNumber() { + try { + return j2(this).toNumber(); + } catch { + Xt("overflow", "toNumber", this.toString()); + } + return null; + } + toBigInt() { + try { + return BigInt(this.toString()); + } catch { + } + return me.throwError("this platform does not support BigInt", z3.errors.UNSUPPORTED_OPERATION, { value: this.toString() }); + } + toString() { + return arguments.length > 0 && (arguments[0] === 10 ? Ln || (Ln = true, me.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")) : arguments[0] === 16 ? me.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", z3.errors.UNEXPECTED_ARGUMENT, {}) : me.throwError("BigNumber.toString does not accept parameters", z3.errors.UNEXPECTED_ARGUMENT, {})), j2(this).toString(10); + } + toHexString() { + return this._hex; + } + toJSON(t) { + return { type: "BigNumber", hex: this.toHexString() }; + } + static from(t) { + if (t instanceof _G) + return t; + if (typeof t == "string") + return t.match(/^-?0x[0-9a-f]+$/i) ? new _G(xi, gr(t)) : t.match(/^-?[0-9]+$/) ? new _G(xi, gr(new Or(t))) : me.throwArgumentError("invalid BigNumber string", "value", t); + if (typeof t == "number") + return t % 1 && Xt("underflow", "BigNumber.from", t), (t >= Hn || t <= -Hn) && Xt("overflow", "BigNumber.from", t), _G.from(String(t)); + const r = t; + if (typeof r == "bigint") + return _G.from(r.toString()); + if (nr(r)) + return _G.from(Ht(r)); + if (r) + if (r.toHexString) { + const i2 = r.toHexString(); + if (typeof i2 == "string") + return _G.from(i2); + } else { + let i2 = r._hex; + if (i2 == null && r.type === "BigNumber" && (i2 = r.hex), typeof i2 == "string" && (Qt(i2) || i2[0] === "-" && Qt(i2.substring(1)))) + return _G.from(i2); + } + return me.throwArgumentError("invalid BigNumber value", "value", t); + } + static isBigNumber(t) { + return !!(t && t._isBigNumber); + } + }; + function gr(e2) { + if (typeof e2 != "string") + return gr(e2.toString(16)); + if (e2[0] === "-") + return e2 = e2.substring(1), e2[0] === "-" && me.throwArgumentError("invalid hex", "value", e2), e2 = gr(e2), e2 === "0x00" ? e2 : "-" + e2; + if (e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), e2 === "0x") + return "0x00"; + for (e2.length % 2 && (e2 = "0x0" + e2.substring(2)); e2.length > 4 && e2.substring(0, 4) === "0x00"; ) + e2 = "0x" + e2.substring(4); + return e2; + } + function jt(e2) { + return G.from(gr(e2)); + } + function j2(e2) { + const t = G.from(e2).toHexString(); + return t[0] === "-" ? new Or("-" + t.substring(3), 16) : new Or(t.substring(2), 16); + } + function Xt(e2, t, r) { + const i2 = { fault: e2, operation: t }; + return r != null && (i2.value = r), me.throwError(e2, z3.errors.NUMERIC_FAULT, i2); + } + function Is(e2) { + return new Or(e2, 36).toString(16); + } + var Lt = new z3(Kn); + var mr = {}; + var zn = G.from(0); + var jn = G.from(-1); + function Vn(e2, t, r, i2) { + const n3 = { fault: t, operation: r }; + return i2 !== void 0 && (n3.value = i2), Lt.throwError(e2, z3.errors.NUMERIC_FAULT, n3); + } + var Ar = "0"; + for (; Ar.length < 256; ) + Ar += Ar; + function Mi(e2) { + if (typeof e2 != "number") + try { + e2 = G.from(e2).toNumber(); + } catch { + } + return typeof e2 == "number" && e2 >= 0 && e2 <= 256 && !(e2 % 1) ? "1" + Ar.substring(0, e2) : Lt.throwArgumentError("invalid decimal size", "decimals", e2); + } + function Ei(e2, t) { + t == null && (t = 0); + const r = Mi(t); + e2 = G.from(e2); + const i2 = e2.lt(zn); + i2 && (e2 = e2.mul(jn)); + let n3 = e2.mod(r).toString(); + for (; n3.length < r.length - 1; ) + n3 = "0" + n3; + n3 = n3.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + const o2 = e2.div(r).toString(); + return r.length === 1 ? e2 = o2 : e2 = o2 + "." + n3, i2 && (e2 = "-" + e2), e2; + } + function Ae(e2, t) { + t == null && (t = 0); + const r = Mi(t); + (typeof e2 != "string" || !e2.match(/^-?[0-9.]+$/)) && Lt.throwArgumentError("invalid decimal value", "value", e2); + const i2 = e2.substring(0, 1) === "-"; + i2 && (e2 = e2.substring(1)), e2 === "." && Lt.throwArgumentError("missing value", "value", e2); + const n3 = e2.split("."); + n3.length > 2 && Lt.throwArgumentError("too many decimal points", "value", e2); + let o2 = n3[0], h5 = n3[1]; + for (o2 || (o2 = "0"), h5 || (h5 = "0"); h5[h5.length - 1] === "0"; ) + h5 = h5.substring(0, h5.length - 1); + for (h5.length > r.length - 1 && Vn("fractional component exceeds decimals", "underflow", "parseFixed"), h5 === "" && (h5 = "0"); h5.length < r.length - 1; ) + h5 += "0"; + const p3 = G.from(o2), b4 = G.from(h5); + let g3 = p3.mul(r).add(b4); + return i2 && (g3 = g3.mul(jn)), g3; + } + var pr = class _pr { + constructor(t, r, i2, n3) { + t !== mr && Lt.throwError("cannot use FixedFormat constructor; use FixedFormat.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.signed = r, this.width = i2, this.decimals = n3, this.name = (r ? "" : "u") + "fixed" + String(i2) + "x" + String(n3), this._multiplier = Mi(n3), Object.freeze(this); + } + static from(t) { + if (t instanceof _pr) + return t; + typeof t == "number" && (t = `fixed128x${t}`); + let r = true, i2 = 128, n3 = 18; + if (typeof t == "string") { + if (t !== "fixed") + if (t === "ufixed") + r = false; + else { + const o2 = t.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + o2 || Lt.throwArgumentError("invalid fixed format", "format", t), r = o2[1] !== "u", i2 = parseInt(o2[2]), n3 = parseInt(o2[3]); + } + } else if (t) { + const o2 = (h5, p3, b4) => t[h5] == null ? b4 : (typeof t[h5] !== p3 && Lt.throwArgumentError("invalid fixed format (" + h5 + " not " + p3 + ")", "format." + h5, t[h5]), t[h5]); + r = o2("signed", "boolean", r), i2 = o2("width", "number", i2), n3 = o2("decimals", "number", n3); + } + return i2 % 8 && Lt.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", i2), n3 > 80 && Lt.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", n3), new _pr(mr, r, i2, n3); + } + }; + var kt = class _kt { + constructor(t, r, i2, n3) { + t !== mr && Lt.throwError("cannot use FixedNumber constructor; use FixedNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.format = n3, this._hex = r, this._value = i2, this._isFixedNumber = true, Object.freeze(this); + } + _checkFormat(t) { + this.format.name !== t.format.name && Lt.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", t); + } + addUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.add(i2), this.format.decimals, this.format); + } + subUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.sub(i2), this.format.decimals, this.format); + } + mulUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.mul(i2).div(this.format._multiplier), this.format.decimals, this.format); + } + divUnsafe(t) { + this._checkFormat(t); + const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); + return _kt.fromValue(r.mul(this.format._multiplier).div(i2), this.format.decimals, this.format); + } + floor() { + const t = this.toString().split("."); + t.length === 1 && t.push("0"); + let r = _kt.from(t[0], this.format); + const i2 = !t[1].match(/^(0*)$/); + return this.isNegative() && i2 && (r = r.subUnsafe(Qn.toFormat(r.format))), r; + } + ceiling() { + const t = this.toString().split("."); + t.length === 1 && t.push("0"); + let r = _kt.from(t[0], this.format); + const i2 = !t[1].match(/^(0*)$/); + return !this.isNegative() && i2 && (r = r.addUnsafe(Qn.toFormat(r.format))), r; + } + round(t) { + t == null && (t = 0); + const r = this.toString().split("."); + if (r.length === 1 && r.push("0"), (t < 0 || t > 80 || t % 1) && Lt.throwArgumentError("invalid decimal count", "decimals", t), r[1].length <= t) + return this; + const i2 = _kt.from("1" + Ar.substring(0, t), this.format), n3 = _s.toFormat(this.format); + return this.mulUnsafe(i2).addUnsafe(n3).floor().divUnsafe(i2); + } + isZero() { + return this._value === "0.0" || this._value === "0"; + } + isNegative() { + return this._value[0] === "-"; + } + toString() { + return this._value; + } + toHexString(t) { + if (t == null) + return this._hex; + t % 8 && Lt.throwArgumentError("invalid byte width", "width", t); + const r = G.from(this._hex).fromTwos(this.format.width).toTwos(t).toHexString(); + return fe(r, t / 8); + } + toUnsafeFloat() { + return parseFloat(this.toString()); + } + toFormat(t) { + return _kt.fromString(this._value, t); + } + static fromValue(t, r, i2) { + return i2 == null && r != null && !Ns(r) && (i2 = r, r = null), r == null && (r = 0), i2 == null && (i2 = "fixed"), _kt.fromString(Ei(t, r), pr.from(i2)); + } + static fromString(t, r) { + r == null && (r = "fixed"); + const i2 = pr.from(r), n3 = Ae(t, i2.decimals); + !i2.signed && n3.lt(zn) && Vn("unsigned value cannot be negative", "overflow", "value", t); + let o2 = null; + i2.signed ? o2 = n3.toTwos(i2.width).toHexString() : (o2 = n3.toHexString(), o2 = fe(o2, i2.width / 8)); + const h5 = Ei(n3, i2.decimals); + return new _kt(mr, o2, h5, i2); + } + static fromBytes(t, r) { + r == null && (r = "fixed"); + const i2 = pr.from(r); + if (Pt(t).length > i2.width / 8) + throw new Error("overflow"); + let n3 = G.from(t); + i2.signed && (n3 = n3.fromTwos(i2.width)); + const o2 = n3.toTwos((i2.signed ? 0 : 1) + i2.width).toHexString(), h5 = Ei(n3, i2.decimals); + return new _kt(mr, o2, h5, i2); + } + static from(t, r) { + if (typeof t == "string") + return _kt.fromString(t, r); + if (nr(t)) + return _kt.fromBytes(t, r); + try { + return _kt.fromValue(t, 0, r); + } catch (i2) { + if (i2.code !== z3.errors.INVALID_ARGUMENT) + throw i2; + } + return Lt.throwArgumentError("invalid FixedNumber value", "value", t); + } + static isFixedNumber(t) { + return !!(t && t._isFixedNumber); + } + }; + var Qn = kt.from(1); + var _s = kt.from("0.5"); + var Bs = "strings/5.7.0"; + var Jn = new z3(Bs); + var Pr; + (function(e2) { + e2.current = "", e2.NFC = "NFC", e2.NFD = "NFD", e2.NFKC = "NFKC", e2.NFKD = "NFKD"; + })(Pr || (Pr = {})); + var fr; + (function(e2) { + e2.UNEXPECTED_CONTINUE = "unexpected continuation byte", e2.BAD_PREFIX = "bad codepoint prefix", e2.OVERRUN = "string overrun", e2.MISSING_CONTINUE = "missing continuation byte", e2.OUT_OF_RANGE = "out of UTF-8 range", e2.UTF16_SURROGATE = "UTF-16 surrogate", e2.OVERLONG = "overlong representation"; + })(fr || (fr = {})); + function Rs(e2, t, r, i2, n3) { + return Jn.throwArgumentError(`invalid codepoint at offset ${t}; ${e2}`, "bytes", r); + } + function Yn(e2, t, r, i2, n3) { + if (e2 === fr.BAD_PREFIX || e2 === fr.UNEXPECTED_CONTINUE) { + let o2 = 0; + for (let h5 = t + 1; h5 < r.length && r[h5] >> 6 === 2; h5++) + o2++; + return o2; + } + return e2 === fr.OVERRUN ? r.length - t - 1 : 0; + } + function Cs(e2, t, r, i2, n3) { + return e2 === fr.OVERLONG ? (i2.push(n3), 0) : (i2.push(65533), Yn(e2, t, r)); + } + Object.freeze({ error: Rs, ignore: Yn, replace: Cs }); + function Si(e2, t = Pr.current) { + t != Pr.current && (Jn.checkNormalize(), e2 = e2.normalize(t)); + let r = []; + for (let i2 = 0; i2 < e2.length; i2++) { + const n3 = e2.charCodeAt(i2); + if (n3 < 128) + r.push(n3); + else if (n3 < 2048) + r.push(n3 >> 6 | 192), r.push(n3 & 63 | 128); + else if ((n3 & 64512) == 55296) { + i2++; + const o2 = e2.charCodeAt(i2); + if (i2 >= e2.length || (o2 & 64512) !== 56320) + throw new Error("invalid utf-8 string"); + const h5 = 65536 + ((n3 & 1023) << 10) + (o2 & 1023); + r.push(h5 >> 18 | 240), r.push(h5 >> 12 & 63 | 128), r.push(h5 >> 6 & 63 | 128), r.push(h5 & 63 | 128); + } else + r.push(n3 >> 12 | 224), r.push(n3 >> 6 & 63 | 128), r.push(n3 & 63 | 128); + } + return Pt(r); + } + function Os(e2) { + if (e2.length % 4 !== 0) + throw new Error("bad data"); + let t = []; + for (let r = 0; r < e2.length; r += 4) + t.push(parseInt(e2.substring(r, r + 4), 16)); + return t; + } + function Ni(e2, t) { + t || (t = function(n3) { + return [parseInt(n3, 16)]; + }); + let r = 0, i2 = {}; + return e2.split(",").forEach((n3) => { + let o2 = n3.split(":"); + r += parseInt(o2[0], 16), i2[r] = t(o2[1]); + }), i2; + } + function Gn(e2) { + let t = 0; + return e2.split(",").map((r) => { + let i2 = r.split("-"); + i2.length === 1 ? i2[1] = "0" : i2[1] === "" && (i2[1] = "1"); + let n3 = t + parseInt(i2[0], 16); + return t = parseInt(i2[1], 16), { l: n3, h: t }; + }); + } + Gn("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"), "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((e2) => parseInt(e2, 16)), Ni("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"), Ni("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"), Ni("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", Os), Gn("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); + var Wn = "hash/5.7.0"; + function Ps(e2) { + e2 = atob(e2); + const t = []; + for (let r = 0; r < e2.length; r++) + t.push(e2.charCodeAt(r)); + return Pt(t); + } + function Xn(e2, t) { + t == null && (t = 1); + const r = [], i2 = r.forEach, n3 = function(o2, h5) { + i2.call(o2, function(p3) { + h5 > 0 && Array.isArray(p3) ? n3(p3, h5 - 1) : r.push(p3); + }); + }; + return n3(e2, t), r; + } + function Ts(e2) { + const t = {}; + for (let r = 0; r < e2.length; r++) { + const i2 = e2[r]; + t[i2[0]] = i2[1]; + } + return t; + } + function Fs(e2) { + let t = 0; + function r() { + return e2[t++] << 8 | e2[t++]; + } + let i2 = r(), n3 = 1, o2 = [0, 1]; + for (let H = 1; H < i2; H++) + o2.push(n3 += r()); + let h5 = r(), p3 = t; + t += h5; + let b4 = 0, g3 = 0; + function w4() { + return b4 == 0 && (g3 = g3 << 8 | e2[t++], b4 = 8), g3 >> --b4 & 1; + } + const y4 = 31, S4 = Math.pow(2, y4), I2 = S4 >>> 1, N10 = I2 >> 1, R2 = S4 - 1; + let F = 0; + for (let H = 0; H < y4; H++) + F = F << 1 | w4(); + let U2 = [], Q = 0, Bt = S4; + for (; ; ) { + let H = Math.floor(((F - Q + 1) * n3 - 1) / Bt), L2 = 0, Tt = i2; + for (; Tt - L2 > 1; ) { + let Gt = L2 + Tt >>> 1; + H < o2[Gt] ? Tt = Gt : L2 = Gt; + } + if (L2 == 0) + break; + U2.push(L2); + let W = Q + Math.floor(Bt * o2[L2] / n3), Ot = Q + Math.floor(Bt * o2[L2 + 1] / n3) - 1; + for (; !((W ^ Ot) & I2); ) + F = F << 1 & R2 | w4(), W = W << 1 & R2, Ot = Ot << 1 & R2 | 1; + for (; W & ~Ot & N10; ) + F = F & I2 | F << 1 & R2 >>> 1 | w4(), W = W << 1 ^ I2, Ot = (Ot ^ I2) << 1 | I2 | 1; + Q = W, Bt = 1 + Ot - W; + } + let J = i2 - 4; + return U2.map((H) => { + switch (H - J) { + case 3: + return J + 65792 + (e2[p3++] << 16 | e2[p3++] << 8 | e2[p3++]); + case 2: + return J + 256 + (e2[p3++] << 8 | e2[p3++]); + case 1: + return J + e2[p3++]; + default: + return H - 1; + } + }); + } + function Ds(e2) { + let t = 0; + return () => e2[t++]; + } + function Us(e2) { + return Ds(Fs(e2)); + } + function ks(e2) { + return e2 & 1 ? ~e2 >> 1 : e2 >> 1; + } + function qs(e2, t) { + let r = Array(e2); + for (let i2 = 0; i2 < e2; i2++) + r[i2] = 1 + t(); + return r; + } + function Zn(e2, t) { + let r = Array(e2); + for (let i2 = 0, n3 = -1; i2 < e2; i2++) + r[i2] = n3 += 1 + t(); + return r; + } + function Ks(e2, t) { + let r = Array(e2); + for (let i2 = 0, n3 = 0; i2 < e2; i2++) + r[i2] = n3 += ks(t()); + return r; + } + function Tr(e2, t) { + let r = Zn(e2(), e2), i2 = e2(), n3 = Zn(i2, e2), o2 = qs(i2, e2); + for (let h5 = 0; h5 < i2; h5++) + for (let p3 = 0; p3 < o2[h5]; p3++) + r.push(n3[h5] + p3); + return t ? r.map((h5) => t[h5]) : r; + } + function Hs(e2) { + let t = []; + for (; ; ) { + let r = e2(); + if (r == 0) + break; + t.push(zs(r, e2)); + } + for (; ; ) { + let r = e2() - 1; + if (r < 0) + break; + t.push(js(r, e2)); + } + return Ts(Xn(t)); + } + function Ls(e2) { + let t = []; + for (; ; ) { + let r = e2(); + if (r == 0) + break; + t.push(r); + } + return t; + } + function $n(e2, t, r) { + let i2 = Array(e2).fill(void 0).map(() => []); + for (let n3 = 0; n3 < t; n3++) + Ks(e2, r).forEach((o2, h5) => i2[h5].push(o2)); + return i2; + } + function zs(e2, t) { + let r = 1 + t(), i2 = t(), n3 = Ls(t), o2 = $n(n3.length, 1 + e2, t); + return Xn(o2.map((h5, p3) => { + const b4 = h5[0], g3 = h5.slice(1); + return Array(n3[p3]).fill(void 0).map((w4, y4) => { + let S4 = y4 * i2; + return [b4 + y4 * r, g3.map((I2) => I2 + S4)]; + }); + })); + } + function js(e2, t) { + let r = 1 + t(); + return $n(r, 1 + e2, t).map((n3) => [n3[0], n3.slice(1)]); + } + function Vs(e2) { + let t = Tr(e2).sort((i2, n3) => i2 - n3); + return r(); + function r() { + let i2 = []; + for (; ; ) { + let g3 = Tr(e2, t); + if (g3.length == 0) + break; + i2.push({ set: new Set(g3), node: r() }); + } + i2.sort((g3, w4) => w4.set.size - g3.set.size); + let n3 = e2(), o2 = n3 % 3; + n3 = n3 / 3 | 0; + let h5 = !!(n3 & 1); + n3 >>= 1; + let p3 = n3 == 1, b4 = n3 == 2; + return { branches: i2, valid: o2, fe0f: h5, save: p3, check: b4 }; + } + } + function Qs() { + return Us(Ps("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); + } + var Fr = Qs(); + new Set(Tr(Fr)), new Set(Tr(Fr)), Hs(Fr), Vs(Fr), new z3(Wn); + var Js = new Uint8Array(32); + Js.fill(0); + var Ys = `Ethereum Signed Message: +`; + function tf(e2) { + return typeof e2 == "string" && (e2 = Si(e2)), wi(ys([Si(Ys), Si(String(e2.length)), e2])); + } + var Gs = "rlp/5.7.0"; + new z3(Gs); + var Ws = "address/5.7.0"; + var br = new z3(Ws); + function ef(e2) { + Qt(e2, 20) || br.throwArgumentError("invalid address", "address", e2), e2 = e2.toLowerCase(); + const t = e2.substring(2).split(""), r = new Uint8Array(40); + for (let n3 = 0; n3 < 40; n3++) + r[n3] = t[n3].charCodeAt(0); + const i2 = Pt(wi(r)); + for (let n3 = 0; n3 < 40; n3 += 2) + i2[n3 >> 1] >> 4 >= 8 && (t[n3] = t[n3].toUpperCase()), (i2[n3 >> 1] & 15) >= 8 && (t[n3 + 1] = t[n3 + 1].toUpperCase()); + return "0x" + t.join(""); + } + var Xs = 9007199254740991; + function Zs(e2) { + return Math.log10 ? Math.log10(e2) : Math.log(e2) / Math.LN10; + } + var Ii = {}; + for (let e2 = 0; e2 < 10; e2++) + Ii[String(e2)] = String(e2); + for (let e2 = 0; e2 < 26; e2++) + Ii[String.fromCharCode(65 + e2)] = String(10 + e2); + var rf = Math.floor(Zs(Xs)); + function $s(e2) { + e2 = e2.toUpperCase(), e2 = e2.substring(4) + e2.substring(0, 2) + "00"; + let t = e2.split("").map((i2) => Ii[i2]).join(""); + for (; t.length >= rf; ) { + let i2 = t.substring(0, rf); + t = parseInt(i2, 10) % 97 + t.substring(i2.length); + } + let r = String(98 - parseInt(t, 10) % 97); + for (; r.length < 2; ) + r = "0" + r; + return r; + } + function ta(e2) { + let t = null; + if (typeof e2 != "string" && br.throwArgumentError("invalid address", "address", e2), e2.match(/^(0x)?[0-9a-fA-F]{40}$/)) + e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), t = ef(e2), e2.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && t !== e2 && br.throwArgumentError("bad address checksum", "address", e2); + else if (e2.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + for (e2.substring(2, 4) !== $s(e2) && br.throwArgumentError("bad icap checksum", "address", e2), t = Is(e2.substring(4)); t.length < 40; ) + t = "0" + t; + t = ef("0x" + t); + } else + br.throwArgumentError("invalid address", "address", e2); + return t; + } + var ea = "properties/5.7.0"; + new z3(ea); + function yr(e2, t, r) { + Object.defineProperty(e2, t, { enumerable: true, value: r, writable: false }); + } + new z3(Wn); + var ra = new Uint8Array(32); + ra.fill(0), G.from(-1); + var ia = G.from(0); + var na = G.from(1); + G.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), fe(na.toHexString(), 32), fe(ia.toHexString(), 32); + var oe = {}; + var V = {}; + var wr = nf; + function nf(e2, t) { + if (!e2) + throw new Error(t || "Assertion failed"); + } + nf.equal = function(t, r, i2) { + if (t != r) + throw new Error(i2 || "Assertion failed: " + t + " != " + r); + }; + var _i = { exports: {} }; + typeof Object.create == "function" ? _i.exports = function(t, r) { + r && (t.super_ = r, t.prototype = Object.create(r.prototype, { constructor: { value: t, enumerable: false, writable: true, configurable: true } })); + } : _i.exports = function(t, r) { + if (r) { + t.super_ = r; + var i2 = function() { + }; + i2.prototype = r.prototype, t.prototype = new i2(), t.prototype.constructor = t; + } + }; + var fa = wr; + var oa = _i.exports; + V.inherits = oa; + function sa(e2, t) { + return (e2.charCodeAt(t) & 64512) !== 55296 || t < 0 || t + 1 >= e2.length ? false : (e2.charCodeAt(t + 1) & 64512) === 56320; + } + function aa(e2, t) { + if (Array.isArray(e2)) + return e2.slice(); + if (!e2) + return []; + var r = []; + if (typeof e2 == "string") + if (t) { + if (t === "hex") + for (e2 = e2.replace(/[^a-z0-9]+/ig, ""), e2.length % 2 !== 0 && (e2 = "0" + e2), n3 = 0; n3 < e2.length; n3 += 2) + r.push(parseInt(e2[n3] + e2[n3 + 1], 16)); + } else + for (var i2 = 0, n3 = 0; n3 < e2.length; n3++) { + var o2 = e2.charCodeAt(n3); + o2 < 128 ? r[i2++] = o2 : o2 < 2048 ? (r[i2++] = o2 >> 6 | 192, r[i2++] = o2 & 63 | 128) : sa(e2, n3) ? (o2 = 65536 + ((o2 & 1023) << 10) + (e2.charCodeAt(++n3) & 1023), r[i2++] = o2 >> 18 | 240, r[i2++] = o2 >> 12 & 63 | 128, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128) : (r[i2++] = o2 >> 12 | 224, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128); + } + else + for (n3 = 0; n3 < e2.length; n3++) + r[n3] = e2[n3] | 0; + return r; + } + V.toArray = aa; + function ua(e2) { + for (var t = "", r = 0; r < e2.length; r++) + t += of(e2[r].toString(16)); + return t; + } + V.toHex = ua; + function ff(e2) { + var t = e2 >>> 24 | e2 >>> 8 & 65280 | e2 << 8 & 16711680 | (e2 & 255) << 24; + return t >>> 0; + } + V.htonl = ff; + function ha(e2, t) { + for (var r = "", i2 = 0; i2 < e2.length; i2++) { + var n3 = e2[i2]; + t === "little" && (n3 = ff(n3)), r += sf(n3.toString(16)); + } + return r; + } + V.toHex32 = ha; + function of(e2) { + return e2.length === 1 ? "0" + e2 : e2; + } + V.zero2 = of; + function sf(e2) { + return e2.length === 7 ? "0" + e2 : e2.length === 6 ? "00" + e2 : e2.length === 5 ? "000" + e2 : e2.length === 4 ? "0000" + e2 : e2.length === 3 ? "00000" + e2 : e2.length === 2 ? "000000" + e2 : e2.length === 1 ? "0000000" + e2 : e2; + } + V.zero8 = sf; + function ca(e2, t, r, i2) { + var n3 = r - t; + fa(n3 % 4 === 0); + for (var o2 = new Array(n3 / 4), h5 = 0, p3 = t; h5 < o2.length; h5++, p3 += 4) { + var b4; + i2 === "big" ? b4 = e2[p3] << 24 | e2[p3 + 1] << 16 | e2[p3 + 2] << 8 | e2[p3 + 3] : b4 = e2[p3 + 3] << 24 | e2[p3 + 2] << 16 | e2[p3 + 1] << 8 | e2[p3], o2[h5] = b4 >>> 0; + } + return o2; + } + V.join32 = ca; + function la(e2, t) { + for (var r = new Array(e2.length * 4), i2 = 0, n3 = 0; i2 < e2.length; i2++, n3 += 4) { + var o2 = e2[i2]; + t === "big" ? (r[n3] = o2 >>> 24, r[n3 + 1] = o2 >>> 16 & 255, r[n3 + 2] = o2 >>> 8 & 255, r[n3 + 3] = o2 & 255) : (r[n3 + 3] = o2 >>> 24, r[n3 + 2] = o2 >>> 16 & 255, r[n3 + 1] = o2 >>> 8 & 255, r[n3] = o2 & 255); + } + return r; + } + V.split32 = la; + function da(e2, t) { + return e2 >>> t | e2 << 32 - t; + } + V.rotr32 = da; + function pa(e2, t) { + return e2 << t | e2 >>> 32 - t; + } + V.rotl32 = pa; + function va(e2, t) { + return e2 + t >>> 0; + } + V.sum32 = va; + function ga(e2, t, r) { + return e2 + t + r >>> 0; + } + V.sum32_3 = ga; + function ma(e2, t, r, i2) { + return e2 + t + r + i2 >>> 0; + } + V.sum32_4 = ma; + function Aa(e2, t, r, i2, n3) { + return e2 + t + r + i2 + n3 >>> 0; + } + V.sum32_5 = Aa; + function ba(e2, t, r, i2) { + var n3 = e2[t], o2 = e2[t + 1], h5 = i2 + o2 >>> 0, p3 = (h5 < i2 ? 1 : 0) + r + n3; + e2[t] = p3 >>> 0, e2[t + 1] = h5; + } + V.sum64 = ba; + function ya(e2, t, r, i2) { + var n3 = t + i2 >>> 0, o2 = (n3 < t ? 1 : 0) + e2 + r; + return o2 >>> 0; + } + V.sum64_hi = ya; + function wa(e2, t, r, i2) { + var n3 = t + i2; + return n3 >>> 0; + } + V.sum64_lo = wa; + function xa(e2, t, r, i2, n3, o2, h5, p3) { + var b4 = 0, g3 = t; + g3 = g3 + i2 >>> 0, b4 += g3 < t ? 1 : 0, g3 = g3 + o2 >>> 0, b4 += g3 < o2 ? 1 : 0, g3 = g3 + p3 >>> 0, b4 += g3 < p3 ? 1 : 0; + var w4 = e2 + r + n3 + h5 + b4; + return w4 >>> 0; + } + V.sum64_4_hi = xa; + function Ma(e2, t, r, i2, n3, o2, h5, p3) { + var b4 = t + i2 + o2 + p3; + return b4 >>> 0; + } + V.sum64_4_lo = Ma; + function Ea(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { + var w4 = 0, y4 = t; + y4 = y4 + i2 >>> 0, w4 += y4 < t ? 1 : 0, y4 = y4 + o2 >>> 0, w4 += y4 < o2 ? 1 : 0, y4 = y4 + p3 >>> 0, w4 += y4 < p3 ? 1 : 0, y4 = y4 + g3 >>> 0, w4 += y4 < g3 ? 1 : 0; + var S4 = e2 + r + n3 + h5 + b4 + w4; + return S4 >>> 0; + } + V.sum64_5_hi = Ea; + function Sa(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { + var w4 = t + i2 + o2 + p3 + g3; + return w4 >>> 0; + } + V.sum64_5_lo = Sa; + function Na(e2, t, r) { + var i2 = t << 32 - r | e2 >>> r; + return i2 >>> 0; + } + V.rotr64_hi = Na; + function Ia(e2, t, r) { + var i2 = e2 << 32 - r | t >>> r; + return i2 >>> 0; + } + V.rotr64_lo = Ia; + function _a(e2, t, r) { + return e2 >>> r; + } + V.shr64_hi = _a; + function Ba(e2, t, r) { + var i2 = e2 << 32 - r | t >>> r; + return i2 >>> 0; + } + V.shr64_lo = Ba; + var or2 = {}; + var af = V; + var Ra = wr; + function Dr() { + this.pending = null, this.pendingTotal = 0, this.blockSize = this.constructor.blockSize, this.outSize = this.constructor.outSize, this.hmacStrength = this.constructor.hmacStrength, this.padLength = this.constructor.padLength / 8, this.endian = "big", this._delta8 = this.blockSize / 8, this._delta32 = this.blockSize / 32; + } + or2.BlockHash = Dr, Dr.prototype.update = function(t, r) { + if (t = af.toArray(t, r), this.pending ? this.pending = this.pending.concat(t) : this.pending = t, this.pendingTotal += t.length, this.pending.length >= this._delta8) { + t = this.pending; + var i2 = t.length % this._delta8; + this.pending = t.slice(t.length - i2, t.length), this.pending.length === 0 && (this.pending = null), t = af.join32(t, 0, t.length - i2, this.endian); + for (var n3 = 0; n3 < t.length; n3 += this._delta32) + this._update(t, n3, n3 + this._delta32); + } + return this; + }, Dr.prototype.digest = function(t) { + return this.update(this._pad()), Ra(this.pending === null), this._digest(t); + }, Dr.prototype._pad = function() { + var t = this.pendingTotal, r = this._delta8, i2 = r - (t + this.padLength) % r, n3 = new Array(i2 + this.padLength); + n3[0] = 128; + for (var o2 = 1; o2 < i2; o2++) + n3[o2] = 0; + if (t <<= 3, this.endian === "big") { + for (var h5 = 8; h5 < this.padLength; h5++) + n3[o2++] = 0; + n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = t >>> 24 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t & 255; + } else + for (n3[o2++] = t & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 24 & 255, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, h5 = 8; h5 < this.padLength; h5++) + n3[o2++] = 0; + return n3; + }; + var sr = {}; + var se = {}; + var Ca = V; + var ae = Ca.rotr32; + function Oa(e2, t, r, i2) { + if (e2 === 0) + return uf(t, r, i2); + if (e2 === 1 || e2 === 3) + return cf(t, r, i2); + if (e2 === 2) + return hf(t, r, i2); + } + se.ft_1 = Oa; + function uf(e2, t, r) { + return e2 & t ^ ~e2 & r; + } + se.ch32 = uf; + function hf(e2, t, r) { + return e2 & t ^ e2 & r ^ t & r; + } + se.maj32 = hf; + function cf(e2, t, r) { + return e2 ^ t ^ r; + } + se.p32 = cf; + function Pa(e2) { + return ae(e2, 2) ^ ae(e2, 13) ^ ae(e2, 22); + } + se.s0_256 = Pa; + function Ta(e2) { + return ae(e2, 6) ^ ae(e2, 11) ^ ae(e2, 25); + } + se.s1_256 = Ta; + function Fa(e2) { + return ae(e2, 7) ^ ae(e2, 18) ^ e2 >>> 3; + } + se.g0_256 = Fa; + function Da(e2) { + return ae(e2, 17) ^ ae(e2, 19) ^ e2 >>> 10; + } + se.g1_256 = Da; + var ar = V; + var Ua = or2; + var ka = se; + var Bi = ar.rotl32; + var xr = ar.sum32; + var qa = ar.sum32_5; + var Ka = ka.ft_1; + var lf = Ua.BlockHash; + var Ha = [1518500249, 1859775393, 2400959708, 3395469782]; + function ue() { + if (!(this instanceof ue)) + return new ue(); + lf.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.W = new Array(80); + } + ar.inherits(ue, lf); + var La = ue; + ue.blockSize = 512, ue.outSize = 160, ue.hmacStrength = 80, ue.padLength = 64, ue.prototype._update = function(t, r) { + for (var i2 = this.W, n3 = 0; n3 < 16; n3++) + i2[n3] = t[r + n3]; + for (; n3 < i2.length; n3++) + i2[n3] = Bi(i2[n3 - 3] ^ i2[n3 - 8] ^ i2[n3 - 14] ^ i2[n3 - 16], 1); + var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4]; + for (n3 = 0; n3 < i2.length; n3++) { + var w4 = ~~(n3 / 20), y4 = qa(Bi(o2, 5), Ka(w4, h5, p3, b4), g3, i2[n3], Ha[w4]); + g3 = b4, b4 = p3, p3 = Bi(h5, 30), h5 = o2, o2 = y4; + } + this.h[0] = xr(this.h[0], o2), this.h[1] = xr(this.h[1], h5), this.h[2] = xr(this.h[2], p3), this.h[3] = xr(this.h[3], b4), this.h[4] = xr(this.h[4], g3); + }, ue.prototype._digest = function(t) { + return t === "hex" ? ar.toHex32(this.h, "big") : ar.split32(this.h, "big"); + }; + var ur = V; + var za = or2; + var hr = se; + var ja = wr; + var re = ur.sum32; + var Va = ur.sum32_4; + var Qa = ur.sum32_5; + var Ja = hr.ch32; + var Ya = hr.maj32; + var Ga = hr.s0_256; + var Wa = hr.s1_256; + var Xa = hr.g0_256; + var Za = hr.g1_256; + var df = za.BlockHash; + var $a = [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]; + function he() { + if (!(this instanceof he)) + return new he(); + df.call(this), this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.k = $a, this.W = new Array(64); + } + ur.inherits(he, df); + var pf = he; + he.blockSize = 512, he.outSize = 256, he.hmacStrength = 192, he.padLength = 64, he.prototype._update = function(t, r) { + for (var i2 = this.W, n3 = 0; n3 < 16; n3++) + i2[n3] = t[r + n3]; + for (; n3 < i2.length; n3++) + i2[n3] = Va(Za(i2[n3 - 2]), i2[n3 - 7], Xa(i2[n3 - 15]), i2[n3 - 16]); + var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4], w4 = this.h[5], y4 = this.h[6], S4 = this.h[7]; + for (ja(this.k.length === i2.length), n3 = 0; n3 < i2.length; n3++) { + var I2 = Qa(S4, Wa(g3), Ja(g3, w4, y4), this.k[n3], i2[n3]), N10 = re(Ga(o2), Ya(o2, h5, p3)); + S4 = y4, y4 = w4, w4 = g3, g3 = re(b4, I2), b4 = p3, p3 = h5, h5 = o2, o2 = re(I2, N10); + } + this.h[0] = re(this.h[0], o2), this.h[1] = re(this.h[1], h5), this.h[2] = re(this.h[2], p3), this.h[3] = re(this.h[3], b4), this.h[4] = re(this.h[4], g3), this.h[5] = re(this.h[5], w4), this.h[6] = re(this.h[6], y4), this.h[7] = re(this.h[7], S4); + }, he.prototype._digest = function(t) { + return t === "hex" ? ur.toHex32(this.h, "big") : ur.split32(this.h, "big"); + }; + var Ri = V; + var vf = pf; + function be() { + if (!(this instanceof be)) + return new be(); + vf.call(this), this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]; + } + Ri.inherits(be, vf); + var t0 = be; + be.blockSize = 512, be.outSize = 224, be.hmacStrength = 192, be.padLength = 64, be.prototype._digest = function(t) { + return t === "hex" ? Ri.toHex32(this.h.slice(0, 7), "big") : Ri.split32(this.h.slice(0, 7), "big"); + }; + var Vt = V; + var e0 = or2; + var r0 = wr; + var ce = Vt.rotr64_hi; + var le = Vt.rotr64_lo; + var gf = Vt.shr64_hi; + var mf = Vt.shr64_lo; + var _e = Vt.sum64; + var Ci = Vt.sum64_hi; + var Oi = Vt.sum64_lo; + var i0 = Vt.sum64_4_hi; + var n0 = Vt.sum64_4_lo; + var f0 = Vt.sum64_5_hi; + var o0 = Vt.sum64_5_lo; + var Af = e0.BlockHash; + var s0 = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591]; + function ie() { + if (!(this instanceof ie)) + return new ie(); + Af.call(this), this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209], this.k = s0, this.W = new Array(160); + } + Vt.inherits(ie, Af); + var bf = ie; + ie.blockSize = 1024, ie.outSize = 512, ie.hmacStrength = 192, ie.padLength = 128, ie.prototype._prepareBlock = function(t, r) { + for (var i2 = this.W, n3 = 0; n3 < 32; n3++) + i2[n3] = t[r + n3]; + for (; n3 < i2.length; n3 += 2) { + var o2 = A0(i2[n3 - 4], i2[n3 - 3]), h5 = b0(i2[n3 - 4], i2[n3 - 3]), p3 = i2[n3 - 14], b4 = i2[n3 - 13], g3 = g0(i2[n3 - 30], i2[n3 - 29]), w4 = m0(i2[n3 - 30], i2[n3 - 29]), y4 = i2[n3 - 32], S4 = i2[n3 - 31]; + i2[n3] = i0(o2, h5, p3, b4, g3, w4, y4, S4), i2[n3 + 1] = n0(o2, h5, p3, b4, g3, w4, y4, S4); + } + }, ie.prototype._update = function(t, r) { + this._prepareBlock(t, r); + var i2 = this.W, n3 = this.h[0], o2 = this.h[1], h5 = this.h[2], p3 = this.h[3], b4 = this.h[4], g3 = this.h[5], w4 = this.h[6], y4 = this.h[7], S4 = this.h[8], I2 = this.h[9], N10 = this.h[10], R2 = this.h[11], F = this.h[12], U2 = this.h[13], Q = this.h[14], Bt = this.h[15]; + r0(this.k.length === i2.length); + for (var J = 0; J < i2.length; J += 2) { + var H = Q, L2 = Bt, Tt = p0(S4, I2), W = v0(S4, I2), Ot = a0(S4, I2, N10, R2, F), Gt = u0(S4, I2, N10, R2, F, U2), Y = this.k[J], Wt = this.k[J + 1], A2 = i2[J], f4 = i2[J + 1], a3 = f0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4), c4 = o0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4); + H = l0(n3, o2), L2 = d0(n3, o2), Tt = h0(n3, o2, h5, p3, b4), W = c0(n3, o2, h5, p3, b4, g3); + var d3 = Ci(H, L2, Tt, W), m3 = Oi(H, L2, Tt, W); + Q = F, Bt = U2, F = N10, U2 = R2, N10 = S4, R2 = I2, S4 = Ci(w4, y4, a3, c4), I2 = Oi(y4, y4, a3, c4), w4 = b4, y4 = g3, b4 = h5, g3 = p3, h5 = n3, p3 = o2, n3 = Ci(a3, c4, d3, m3), o2 = Oi(a3, c4, d3, m3); + } + _e(this.h, 0, n3, o2), _e(this.h, 2, h5, p3), _e(this.h, 4, b4, g3), _e(this.h, 6, w4, y4), _e(this.h, 8, S4, I2), _e(this.h, 10, N10, R2), _e(this.h, 12, F, U2), _e(this.h, 14, Q, Bt); + }, ie.prototype._digest = function(t) { + return t === "hex" ? Vt.toHex32(this.h, "big") : Vt.split32(this.h, "big"); + }; + function a0(e2, t, r, i2, n3) { + var o2 = e2 & r ^ ~e2 & n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function u0(e2, t, r, i2, n3, o2) { + var h5 = t & i2 ^ ~t & o2; + return h5 < 0 && (h5 += 4294967296), h5; + } + function h0(e2, t, r, i2, n3) { + var o2 = e2 & r ^ e2 & n3 ^ r & n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function c0(e2, t, r, i2, n3, o2) { + var h5 = t & i2 ^ t & o2 ^ i2 & o2; + return h5 < 0 && (h5 += 4294967296), h5; + } + function l0(e2, t) { + var r = ce(e2, t, 28), i2 = ce(t, e2, 2), n3 = ce(t, e2, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function d0(e2, t) { + var r = le(e2, t, 28), i2 = le(t, e2, 2), n3 = le(t, e2, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function p0(e2, t) { + var r = ce(e2, t, 14), i2 = ce(e2, t, 18), n3 = ce(t, e2, 9), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function v0(e2, t) { + var r = le(e2, t, 14), i2 = le(e2, t, 18), n3 = le(t, e2, 9), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function g0(e2, t) { + var r = ce(e2, t, 1), i2 = ce(e2, t, 8), n3 = gf(e2, t, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function m0(e2, t) { + var r = le(e2, t, 1), i2 = le(e2, t, 8), n3 = mf(e2, t, 7), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function A0(e2, t) { + var r = ce(e2, t, 19), i2 = ce(t, e2, 29), n3 = gf(e2, t, 6), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + function b0(e2, t) { + var r = le(e2, t, 19), i2 = le(t, e2, 29), n3 = mf(e2, t, 6), o2 = r ^ i2 ^ n3; + return o2 < 0 && (o2 += 4294967296), o2; + } + var Pi = V; + var yf = bf; + function ye() { + if (!(this instanceof ye)) + return new ye(); + yf.call(this), this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]; + } + Pi.inherits(ye, yf); + var y0 = ye; + ye.blockSize = 1024, ye.outSize = 384, ye.hmacStrength = 192, ye.padLength = 128, ye.prototype._digest = function(t) { + return t === "hex" ? Pi.toHex32(this.h.slice(0, 12), "big") : Pi.split32(this.h.slice(0, 12), "big"); + }, sr.sha1 = La, sr.sha224 = t0, sr.sha256 = pf, sr.sha384 = y0, sr.sha512 = bf; + var wf = {}; + var We = V; + var w0 = or2; + var Ur = We.rotl32; + var xf = We.sum32; + var Mr = We.sum32_3; + var Mf = We.sum32_4; + var Ef = w0.BlockHash; + function de() { + if (!(this instanceof de)) + return new de(); + Ef.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.endian = "little"; + } + We.inherits(de, Ef), wf.ripemd160 = de, de.blockSize = 512, de.outSize = 160, de.hmacStrength = 192, de.padLength = 64, de.prototype._update = function(t, r) { + for (var i2 = this.h[0], n3 = this.h[1], o2 = this.h[2], h5 = this.h[3], p3 = this.h[4], b4 = i2, g3 = n3, w4 = o2, y4 = h5, S4 = p3, I2 = 0; I2 < 80; I2++) { + var N10 = xf(Ur(Mf(i2, Sf(I2, n3, o2, h5), t[E0[I2] + r], x0(I2)), N0[I2]), p3); + i2 = p3, p3 = h5, h5 = Ur(o2, 10), o2 = n3, n3 = N10, N10 = xf(Ur(Mf(b4, Sf(79 - I2, g3, w4, y4), t[S0[I2] + r], M0(I2)), I0[I2]), S4), b4 = S4, S4 = y4, y4 = Ur(w4, 10), w4 = g3, g3 = N10; + } + N10 = Mr(this.h[1], o2, y4), this.h[1] = Mr(this.h[2], h5, S4), this.h[2] = Mr(this.h[3], p3, b4), this.h[3] = Mr(this.h[4], i2, g3), this.h[4] = Mr(this.h[0], n3, w4), this.h[0] = N10; + }, de.prototype._digest = function(t) { + return t === "hex" ? We.toHex32(this.h, "little") : We.split32(this.h, "little"); + }; + function Sf(e2, t, r, i2) { + return e2 <= 15 ? t ^ r ^ i2 : e2 <= 31 ? t & r | ~t & i2 : e2 <= 47 ? (t | ~r) ^ i2 : e2 <= 63 ? t & i2 | r & ~i2 : t ^ (r | ~i2); + } + function x0(e2) { + return e2 <= 15 ? 0 : e2 <= 31 ? 1518500249 : e2 <= 47 ? 1859775393 : e2 <= 63 ? 2400959708 : 2840853838; + } + function M0(e2) { + return e2 <= 15 ? 1352829926 : e2 <= 31 ? 1548603684 : e2 <= 47 ? 1836072691 : e2 <= 63 ? 2053994217 : 0; + } + var E0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; + var S0 = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; + var N0 = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]; + var I0 = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; + var _0 = V; + var B0 = wr; + function cr(e2, t, r) { + if (!(this instanceof cr)) + return new cr(e2, t, r); + this.Hash = e2, this.blockSize = e2.blockSize / 8, this.outSize = e2.outSize / 8, this.inner = null, this.outer = null, this._init(_0.toArray(t, r)); + } + var R0 = cr; + cr.prototype._init = function(t) { + t.length > this.blockSize && (t = new this.Hash().update(t).digest()), B0(t.length <= this.blockSize); + for (var r = t.length; r < this.blockSize; r++) + t.push(0); + for (r = 0; r < t.length; r++) + t[r] ^= 54; + for (this.inner = new this.Hash().update(t), r = 0; r < t.length; r++) + t[r] ^= 106; + this.outer = new this.Hash().update(t); + }, cr.prototype.update = function(t, r) { + return this.inner.update(t, r), this; + }, cr.prototype.digest = function(t) { + return this.outer.update(this.inner.digest()), this.outer.digest(t); + }, function(e2) { + var t = e2; + t.utils = V, t.common = or2, t.sha = sr, t.ripemd = wf, t.hmac = R0, t.sha1 = t.sha.sha1, t.sha256 = t.sha.sha256, t.sha224 = t.sha.sha224, t.sha384 = t.sha.sha384, t.sha512 = t.sha.sha512, t.ripemd160 = t.ripemd.ripemd160; + }(oe); + function lr(e2, t, r) { + return r = { path: t, exports: {}, require: function(i2, n3) { + return C0(i2, n3 ?? r.path); + } }, e2(r, r.exports), r.exports; + } + function C0() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); + } + var Ti = Nf; + function Nf(e2, t) { + if (!e2) + throw new Error(t || "Assertion failed"); + } + Nf.equal = function(t, r, i2) { + if (t != r) + throw new Error(i2 || "Assertion failed: " + t + " != " + r); + }; + var ne = lr(function(e2, t) { + var r = t; + function i2(h5, p3) { + if (Array.isArray(h5)) + return h5.slice(); + if (!h5) + return []; + var b4 = []; + if (typeof h5 != "string") { + for (var g3 = 0; g3 < h5.length; g3++) + b4[g3] = h5[g3] | 0; + return b4; + } + if (p3 === "hex") { + h5 = h5.replace(/[^a-z0-9]+/ig, ""), h5.length % 2 !== 0 && (h5 = "0" + h5); + for (var g3 = 0; g3 < h5.length; g3 += 2) + b4.push(parseInt(h5[g3] + h5[g3 + 1], 16)); + } else + for (var g3 = 0; g3 < h5.length; g3++) { + var w4 = h5.charCodeAt(g3), y4 = w4 >> 8, S4 = w4 & 255; + y4 ? b4.push(y4, S4) : b4.push(S4); + } + return b4; + } + r.toArray = i2; + function n3(h5) { + return h5.length === 1 ? "0" + h5 : h5; + } + r.zero2 = n3; + function o2(h5) { + for (var p3 = "", b4 = 0; b4 < h5.length; b4++) + p3 += n3(h5[b4].toString(16)); + return p3; + } + r.toHex = o2, r.encode = function(p3, b4) { + return b4 === "hex" ? o2(p3) : p3; + }; + }); + var Jt = lr(function(e2, t) { + var r = t; + r.assert = Ti, r.toArray = ne.toArray, r.zero2 = ne.zero2, r.toHex = ne.toHex, r.encode = ne.encode; + function i2(b4, g3, w4) { + var y4 = new Array(Math.max(b4.bitLength(), w4) + 1); + y4.fill(0); + for (var S4 = 1 << g3 + 1, I2 = b4.clone(), N10 = 0; N10 < y4.length; N10++) { + var R2, F = I2.andln(S4 - 1); + I2.isOdd() ? (F > (S4 >> 1) - 1 ? R2 = (S4 >> 1) - F : R2 = F, I2.isubn(R2)) : R2 = 0, y4[N10] = R2, I2.iushrn(1); + } + return y4; + } + r.getNAF = i2; + function n3(b4, g3) { + var w4 = [[], []]; + b4 = b4.clone(), g3 = g3.clone(); + for (var y4 = 0, S4 = 0, I2; b4.cmpn(-y4) > 0 || g3.cmpn(-S4) > 0; ) { + var N10 = b4.andln(3) + y4 & 3, R2 = g3.andln(3) + S4 & 3; + N10 === 3 && (N10 = -1), R2 === 3 && (R2 = -1); + var F; + N10 & 1 ? (I2 = b4.andln(7) + y4 & 7, (I2 === 3 || I2 === 5) && R2 === 2 ? F = -N10 : F = N10) : F = 0, w4[0].push(F); + var U2; + R2 & 1 ? (I2 = g3.andln(7) + S4 & 7, (I2 === 3 || I2 === 5) && N10 === 2 ? U2 = -R2 : U2 = R2) : U2 = 0, w4[1].push(U2), 2 * y4 === F + 1 && (y4 = 1 - y4), 2 * S4 === U2 + 1 && (S4 = 1 - S4), b4.iushrn(1), g3.iushrn(1); + } + return w4; + } + r.getJSF = n3; + function o2(b4, g3, w4) { + var y4 = "_" + g3; + b4.prototype[g3] = function() { + return this[y4] !== void 0 ? this[y4] : this[y4] = w4.call(this); + }; + } + r.cachedProperty = o2; + function h5(b4) { + return typeof b4 == "string" ? r.toArray(b4, "hex") : b4; + } + r.parseBytes = h5; + function p3(b4) { + return new K2(b4, "hex", "le"); + } + r.intFromLE = p3; + }); + var kr = Jt.getNAF; + var O0 = Jt.getJSF; + var qr = Jt.assert; + function Be(e2, t) { + this.type = e2, this.p = new K2(t.p, 16), this.red = t.prime ? K2.red(t.prime) : K2.mont(this.p), this.zero = new K2(0).toRed(this.red), this.one = new K2(1).toRed(this.red), this.two = new K2(2).toRed(this.red), this.n = t.n && new K2(t.n, 16), this.g = t.g && this.pointFromJSON(t.g, t.gRed), this._wnafT1 = new Array(4), this._wnafT2 = new Array(4), this._wnafT3 = new Array(4), this._wnafT4 = new Array(4), this._bitLength = this.n ? this.n.bitLength() : 0; + var r = this.n && this.p.div(this.n); + !r || r.cmpn(100) > 0 ? this.redN = null : (this._maxwellTrick = true, this.redN = this.n.toRed(this.red)); + } + var Xe = Be; + Be.prototype.point = function() { + throw new Error("Not implemented"); + }, Be.prototype.validate = function() { + throw new Error("Not implemented"); + }, Be.prototype._fixedNafMul = function(t, r) { + qr(t.precomputed); + var i2 = t._getDoubles(), n3 = kr(r, 1, this._bitLength), o2 = (1 << i2.step + 1) - (i2.step % 2 === 0 ? 2 : 1); + o2 /= 3; + var h5 = [], p3, b4; + for (p3 = 0; p3 < n3.length; p3 += i2.step) { + b4 = 0; + for (var g3 = p3 + i2.step - 1; g3 >= p3; g3--) + b4 = (b4 << 1) + n3[g3]; + h5.push(b4); + } + for (var w4 = this.jpoint(null, null, null), y4 = this.jpoint(null, null, null), S4 = o2; S4 > 0; S4--) { + for (p3 = 0; p3 < h5.length; p3++) + b4 = h5[p3], b4 === S4 ? y4 = y4.mixedAdd(i2.points[p3]) : b4 === -S4 && (y4 = y4.mixedAdd(i2.points[p3].neg())); + w4 = w4.add(y4); + } + return w4.toP(); + }, Be.prototype._wnafMul = function(t, r) { + var i2 = 4, n3 = t._getNAFPoints(i2); + i2 = n3.wnd; + for (var o2 = n3.points, h5 = kr(r, i2, this._bitLength), p3 = this.jpoint(null, null, null), b4 = h5.length - 1; b4 >= 0; b4--) { + for (var g3 = 0; b4 >= 0 && h5[b4] === 0; b4--) + g3++; + if (b4 >= 0 && g3++, p3 = p3.dblp(g3), b4 < 0) + break; + var w4 = h5[b4]; + qr(w4 !== 0), t.type === "affine" ? w4 > 0 ? p3 = p3.mixedAdd(o2[w4 - 1 >> 1]) : p3 = p3.mixedAdd(o2[-w4 - 1 >> 1].neg()) : w4 > 0 ? p3 = p3.add(o2[w4 - 1 >> 1]) : p3 = p3.add(o2[-w4 - 1 >> 1].neg()); + } + return t.type === "affine" ? p3.toP() : p3; + }, Be.prototype._wnafMulAdd = function(t, r, i2, n3, o2) { + var h5 = this._wnafT1, p3 = this._wnafT2, b4 = this._wnafT3, g3 = 0, w4, y4, S4; + for (w4 = 0; w4 < n3; w4++) { + S4 = r[w4]; + var I2 = S4._getNAFPoints(t); + h5[w4] = I2.wnd, p3[w4] = I2.points; + } + for (w4 = n3 - 1; w4 >= 1; w4 -= 2) { + var N10 = w4 - 1, R2 = w4; + if (h5[N10] !== 1 || h5[R2] !== 1) { + b4[N10] = kr(i2[N10], h5[N10], this._bitLength), b4[R2] = kr(i2[R2], h5[R2], this._bitLength), g3 = Math.max(b4[N10].length, g3), g3 = Math.max(b4[R2].length, g3); + continue; + } + var F = [r[N10], null, null, r[R2]]; + r[N10].y.cmp(r[R2].y) === 0 ? (F[1] = r[N10].add(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())) : r[N10].y.cmp(r[R2].y.redNeg()) === 0 ? (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].add(r[R2].neg())) : (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())); + var U2 = [-3, -1, -5, -7, 0, 7, 5, 1, 3], Q = O0(i2[N10], i2[R2]); + for (g3 = Math.max(Q[0].length, g3), b4[N10] = new Array(g3), b4[R2] = new Array(g3), y4 = 0; y4 < g3; y4++) { + var Bt = Q[0][y4] | 0, J = Q[1][y4] | 0; + b4[N10][y4] = U2[(Bt + 1) * 3 + (J + 1)], b4[R2][y4] = 0, p3[N10] = F; + } + } + var H = this.jpoint(null, null, null), L2 = this._wnafT4; + for (w4 = g3; w4 >= 0; w4--) { + for (var Tt = 0; w4 >= 0; ) { + var W = true; + for (y4 = 0; y4 < n3; y4++) + L2[y4] = b4[y4][w4] | 0, L2[y4] !== 0 && (W = false); + if (!W) + break; + Tt++, w4--; + } + if (w4 >= 0 && Tt++, H = H.dblp(Tt), w4 < 0) + break; + for (y4 = 0; y4 < n3; y4++) { + var Ot = L2[y4]; + Ot !== 0 && (Ot > 0 ? S4 = p3[y4][Ot - 1 >> 1] : Ot < 0 && (S4 = p3[y4][-Ot - 1 >> 1].neg()), S4.type === "affine" ? H = H.mixedAdd(S4) : H = H.add(S4)); + } + } + for (w4 = 0; w4 < n3; w4++) + p3[w4] = null; + return o2 ? H : H.toP(); + }; + function Zt(e2, t) { + this.curve = e2, this.type = t, this.precomputed = null; + } + Be.BasePoint = Zt, Zt.prototype.eq = function() { + throw new Error("Not implemented"); + }, Zt.prototype.validate = function() { + return this.curve.validate(this); + }, Be.prototype.decodePoint = function(t, r) { + t = Jt.toArray(t, r); + var i2 = this.p.byteLength(); + if ((t[0] === 4 || t[0] === 6 || t[0] === 7) && t.length - 1 === 2 * i2) { + t[0] === 6 ? qr(t[t.length - 1] % 2 === 0) : t[0] === 7 && qr(t[t.length - 1] % 2 === 1); + var n3 = this.point(t.slice(1, 1 + i2), t.slice(1 + i2, 1 + 2 * i2)); + return n3; + } else if ((t[0] === 2 || t[0] === 3) && t.length - 1 === i2) + return this.pointFromX(t.slice(1, 1 + i2), t[0] === 3); + throw new Error("Unknown point format"); + }, Zt.prototype.encodeCompressed = function(t) { + return this.encode(t, true); + }, Zt.prototype._encode = function(t) { + var r = this.curve.p.byteLength(), i2 = this.getX().toArray("be", r); + return t ? [this.getY().isEven() ? 2 : 3].concat(i2) : [4].concat(i2, this.getY().toArray("be", r)); + }, Zt.prototype.encode = function(t, r) { + return Jt.encode(this._encode(r), t); + }, Zt.prototype.precompute = function(t) { + if (this.precomputed) + return this; + var r = { doubles: null, naf: null, beta: null }; + return r.naf = this._getNAFPoints(8), r.doubles = this._getDoubles(4, t), r.beta = this._getBeta(), this.precomputed = r, this; + }, Zt.prototype._hasDoubles = function(t) { + if (!this.precomputed) + return false; + var r = this.precomputed.doubles; + return r ? r.points.length >= Math.ceil((t.bitLength() + 1) / r.step) : false; + }, Zt.prototype._getDoubles = function(t, r) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + for (var i2 = [this], n3 = this, o2 = 0; o2 < r; o2 += t) { + for (var h5 = 0; h5 < t; h5++) + n3 = n3.dbl(); + i2.push(n3); + } + return { step: t, points: i2 }; + }, Zt.prototype._getNAFPoints = function(t) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + for (var r = [this], i2 = (1 << t) - 1, n3 = i2 === 1 ? null : this.dbl(), o2 = 1; o2 < i2; o2++) + r[o2] = r[o2 - 1].add(n3); + return { wnd: t, points: r }; + }, Zt.prototype._getBeta = function() { + return null; + }, Zt.prototype.dblp = function(t) { + for (var r = this, i2 = 0; i2 < t; i2++) + r = r.dbl(); + return r; + }; + var Fi = lr(function(e2) { + typeof Object.create == "function" ? e2.exports = function(r, i2) { + i2 && (r.super_ = i2, r.prototype = Object.create(i2.prototype, { constructor: { value: r, enumerable: false, writable: true, configurable: true } })); + } : e2.exports = function(r, i2) { + if (i2) { + r.super_ = i2; + var n3 = function() { + }; + n3.prototype = i2.prototype, r.prototype = new n3(), r.prototype.constructor = r; + } + }; + }); + var P0 = Jt.assert; + function $t(e2) { + Xe.call(this, "short", e2), this.a = new K2(e2.a, 16).toRed(this.red), this.b = new K2(e2.b, 16).toRed(this.red), this.tinv = this.two.redInvm(), this.zeroA = this.a.fromRed().cmpn(0) === 0, this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0, this.endo = this._getEndomorphism(e2), this._endoWnafT1 = new Array(4), this._endoWnafT2 = new Array(4); + } + Fi($t, Xe); + var T0 = $t; + $t.prototype._getEndomorphism = function(t) { + if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { + var r, i2; + if (t.beta) + r = new K2(t.beta, 16).toRed(this.red); + else { + var n3 = this._getEndoRoots(this.p); + r = n3[0].cmp(n3[1]) < 0 ? n3[0] : n3[1], r = r.toRed(this.red); + } + if (t.lambda) + i2 = new K2(t.lambda, 16); + else { + var o2 = this._getEndoRoots(this.n); + this.g.mul(o2[0]).x.cmp(this.g.x.redMul(r)) === 0 ? i2 = o2[0] : (i2 = o2[1], P0(this.g.mul(i2).x.cmp(this.g.x.redMul(r)) === 0)); + } + var h5; + return t.basis ? h5 = t.basis.map(function(p3) { + return { a: new K2(p3.a, 16), b: new K2(p3.b, 16) }; + }) : h5 = this._getEndoBasis(i2), { beta: r, lambda: i2, basis: h5 }; + } + }, $t.prototype._getEndoRoots = function(t) { + var r = t === this.p ? this.red : K2.mont(t), i2 = new K2(2).toRed(r).redInvm(), n3 = i2.redNeg(), o2 = new K2(3).toRed(r).redNeg().redSqrt().redMul(i2), h5 = n3.redAdd(o2).fromRed(), p3 = n3.redSub(o2).fromRed(); + return [h5, p3]; + }, $t.prototype._getEndoBasis = function(t) { + for (var r = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), i2 = t, n3 = this.n.clone(), o2 = new K2(1), h5 = new K2(0), p3 = new K2(0), b4 = new K2(1), g3, w4, y4, S4, I2, N10, R2, F = 0, U2, Q; i2.cmpn(0) !== 0; ) { + var Bt = n3.div(i2); + U2 = n3.sub(Bt.mul(i2)), Q = p3.sub(Bt.mul(o2)); + var J = b4.sub(Bt.mul(h5)); + if (!y4 && U2.cmp(r) < 0) + g3 = R2.neg(), w4 = o2, y4 = U2.neg(), S4 = Q; + else if (y4 && ++F === 2) + break; + R2 = U2, n3 = i2, i2 = U2, p3 = o2, o2 = Q, b4 = h5, h5 = J; + } + I2 = U2.neg(), N10 = Q; + var H = y4.sqr().add(S4.sqr()), L2 = I2.sqr().add(N10.sqr()); + return L2.cmp(H) >= 0 && (I2 = g3, N10 = w4), y4.negative && (y4 = y4.neg(), S4 = S4.neg()), I2.negative && (I2 = I2.neg(), N10 = N10.neg()), [{ a: y4, b: S4 }, { a: I2, b: N10 }]; + }, $t.prototype._endoSplit = function(t) { + var r = this.endo.basis, i2 = r[0], n3 = r[1], o2 = n3.b.mul(t).divRound(this.n), h5 = i2.b.neg().mul(t).divRound(this.n), p3 = o2.mul(i2.a), b4 = h5.mul(n3.a), g3 = o2.mul(i2.b), w4 = h5.mul(n3.b), y4 = t.sub(p3).sub(b4), S4 = g3.add(w4).neg(); + return { k1: y4, k2: S4 }; + }, $t.prototype.pointFromX = function(t, r) { + t = new K2(t, 16), t.red || (t = t.toRed(this.red)); + var i2 = t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b), n3 = i2.redSqrt(); + if (n3.redSqr().redSub(i2).cmp(this.zero) !== 0) + throw new Error("invalid point"); + var o2 = n3.fromRed().isOdd(); + return (r && !o2 || !r && o2) && (n3 = n3.redNeg()), this.point(t, n3); + }, $t.prototype.validate = function(t) { + if (t.inf) + return true; + var r = t.x, i2 = t.y, n3 = this.a.redMul(r), o2 = r.redSqr().redMul(r).redIAdd(n3).redIAdd(this.b); + return i2.redSqr().redISub(o2).cmpn(0) === 0; + }, $t.prototype._endoWnafMulAdd = function(t, r, i2) { + for (var n3 = this._endoWnafT1, o2 = this._endoWnafT2, h5 = 0; h5 < t.length; h5++) { + var p3 = this._endoSplit(r[h5]), b4 = t[h5], g3 = b4._getBeta(); + p3.k1.negative && (p3.k1.ineg(), b4 = b4.neg(true)), p3.k2.negative && (p3.k2.ineg(), g3 = g3.neg(true)), n3[h5 * 2] = b4, n3[h5 * 2 + 1] = g3, o2[h5 * 2] = p3.k1, o2[h5 * 2 + 1] = p3.k2; + } + for (var w4 = this._wnafMulAdd(1, n3, o2, h5 * 2, i2), y4 = 0; y4 < h5 * 2; y4++) + n3[y4] = null, o2[y4] = null; + return w4; + }; + function Dt(e2, t, r, i2) { + Xe.BasePoint.call(this, e2, "affine"), t === null && r === null ? (this.x = null, this.y = null, this.inf = true) : (this.x = new K2(t, 16), this.y = new K2(r, 16), i2 && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.inf = false); + } + Fi(Dt, Xe.BasePoint), $t.prototype.point = function(t, r, i2) { + return new Dt(this, t, r, i2); + }, $t.prototype.pointFromJSON = function(t, r) { + return Dt.fromJSON(this, t, r); + }, Dt.prototype._getBeta = function() { + if (this.curve.endo) { + var t = this.precomputed; + if (t && t.beta) + return t.beta; + var r = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (t) { + var i2 = this.curve, n3 = function(o2) { + return i2.point(o2.x.redMul(i2.endo.beta), o2.y); + }; + t.beta = r, r.precomputed = { beta: null, naf: t.naf && { wnd: t.naf.wnd, points: t.naf.points.map(n3) }, doubles: t.doubles && { step: t.doubles.step, points: t.doubles.points.map(n3) } }; + } + return r; + } + }, Dt.prototype.toJSON = function() { + return this.precomputed ? [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }] : [this.x, this.y]; + }, Dt.fromJSON = function(t, r, i2) { + typeof r == "string" && (r = JSON.parse(r)); + var n3 = t.point(r[0], r[1], i2); + if (!r[2]) + return n3; + function o2(p3) { + return t.point(p3[0], p3[1], i2); + } + var h5 = r[2]; + return n3.precomputed = { beta: null, doubles: h5.doubles && { step: h5.doubles.step, points: [n3].concat(h5.doubles.points.map(o2)) }, naf: h5.naf && { wnd: h5.naf.wnd, points: [n3].concat(h5.naf.points.map(o2)) } }, n3; + }, Dt.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }, Dt.prototype.isInfinity = function() { + return this.inf; + }, Dt.prototype.add = function(t) { + if (this.inf) + return t; + if (t.inf) + return this; + if (this.eq(t)) + return this.dbl(); + if (this.neg().eq(t)) + return this.curve.point(null, null); + if (this.x.cmp(t.x) === 0) + return this.curve.point(null, null); + var r = this.y.redSub(t.y); + r.cmpn(0) !== 0 && (r = r.redMul(this.x.redSub(t.x).redInvm())); + var i2 = r.redSqr().redISub(this.x).redISub(t.x), n3 = r.redMul(this.x.redSub(i2)).redISub(this.y); + return this.curve.point(i2, n3); + }, Dt.prototype.dbl = function() { + if (this.inf) + return this; + var t = this.y.redAdd(this.y); + if (t.cmpn(0) === 0) + return this.curve.point(null, null); + var r = this.curve.a, i2 = this.x.redSqr(), n3 = t.redInvm(), o2 = i2.redAdd(i2).redIAdd(i2).redIAdd(r).redMul(n3), h5 = o2.redSqr().redISub(this.x.redAdd(this.x)), p3 = o2.redMul(this.x.redSub(h5)).redISub(this.y); + return this.curve.point(h5, p3); + }, Dt.prototype.getX = function() { + return this.x.fromRed(); + }, Dt.prototype.getY = function() { + return this.y.fromRed(); + }, Dt.prototype.mul = function(t) { + return t = new K2(t, 16), this.isInfinity() ? this : this._hasDoubles(t) ? this.curve._fixedNafMul(this, t) : this.curve.endo ? this.curve._endoWnafMulAdd([this], [t]) : this.curve._wnafMul(this, t); + }, Dt.prototype.mulAdd = function(t, r, i2) { + var n3 = [this, r], o2 = [t, i2]; + return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2) : this.curve._wnafMulAdd(1, n3, o2, 2); + }, Dt.prototype.jmulAdd = function(t, r, i2) { + var n3 = [this, r], o2 = [t, i2]; + return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2, true) : this.curve._wnafMulAdd(1, n3, o2, 2, true); + }, Dt.prototype.eq = function(t) { + return this === t || this.inf === t.inf && (this.inf || this.x.cmp(t.x) === 0 && this.y.cmp(t.y) === 0); + }, Dt.prototype.neg = function(t) { + if (this.inf) + return this; + var r = this.curve.point(this.x, this.y.redNeg()); + if (t && this.precomputed) { + var i2 = this.precomputed, n3 = function(o2) { + return o2.neg(); + }; + r.precomputed = { naf: i2.naf && { wnd: i2.naf.wnd, points: i2.naf.points.map(n3) }, doubles: i2.doubles && { step: i2.doubles.step, points: i2.doubles.points.map(n3) } }; + } + return r; + }, Dt.prototype.toJ = function() { + if (this.inf) + return this.curve.jpoint(null, null, null); + var t = this.curve.jpoint(this.x, this.y, this.curve.one); + return t; + }; + function Ut(e2, t, r, i2) { + Xe.BasePoint.call(this, e2, "jacobian"), t === null && r === null && i2 === null ? (this.x = this.curve.one, this.y = this.curve.one, this.z = new K2(0)) : (this.x = new K2(t, 16), this.y = new K2(r, 16), this.z = new K2(i2, 16)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red)), this.zOne = this.z === this.curve.one; + } + Fi(Ut, Xe.BasePoint), $t.prototype.jpoint = function(t, r, i2) { + return new Ut(this, t, r, i2); + }, Ut.prototype.toP = function() { + if (this.isInfinity()) + return this.curve.point(null, null); + var t = this.z.redInvm(), r = t.redSqr(), i2 = this.x.redMul(r), n3 = this.y.redMul(r).redMul(t); + return this.curve.point(i2, n3); + }, Ut.prototype.neg = function() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }, Ut.prototype.add = function(t) { + if (this.isInfinity()) + return t; + if (t.isInfinity()) + return this; + var r = t.z.redSqr(), i2 = this.z.redSqr(), n3 = this.x.redMul(r), o2 = t.x.redMul(i2), h5 = this.y.redMul(r.redMul(t.z)), p3 = t.y.redMul(i2.redMul(this.z)), b4 = n3.redSub(o2), g3 = h5.redSub(p3); + if (b4.cmpn(0) === 0) + return g3.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var w4 = b4.redSqr(), y4 = w4.redMul(b4), S4 = n3.redMul(w4), I2 = g3.redSqr().redIAdd(y4).redISub(S4).redISub(S4), N10 = g3.redMul(S4.redISub(I2)).redISub(h5.redMul(y4)), R2 = this.z.redMul(t.z).redMul(b4); + return this.curve.jpoint(I2, N10, R2); + }, Ut.prototype.mixedAdd = function(t) { + if (this.isInfinity()) + return t.toJ(); + if (t.isInfinity()) + return this; + var r = this.z.redSqr(), i2 = this.x, n3 = t.x.redMul(r), o2 = this.y, h5 = t.y.redMul(r).redMul(this.z), p3 = i2.redSub(n3), b4 = o2.redSub(h5); + if (p3.cmpn(0) === 0) + return b4.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var g3 = p3.redSqr(), w4 = g3.redMul(p3), y4 = i2.redMul(g3), S4 = b4.redSqr().redIAdd(w4).redISub(y4).redISub(y4), I2 = b4.redMul(y4.redISub(S4)).redISub(o2.redMul(w4)), N10 = this.z.redMul(p3); + return this.curve.jpoint(S4, I2, N10); + }, Ut.prototype.dblp = function(t) { + if (t === 0) + return this; + if (this.isInfinity()) + return this; + if (!t) + return this.dbl(); + var r; + if (this.curve.zeroA || this.curve.threeA) { + var i2 = this; + for (r = 0; r < t; r++) + i2 = i2.dbl(); + return i2; + } + var n3 = this.curve.a, o2 = this.curve.tinv, h5 = this.x, p3 = this.y, b4 = this.z, g3 = b4.redSqr().redSqr(), w4 = p3.redAdd(p3); + for (r = 0; r < t; r++) { + var y4 = h5.redSqr(), S4 = w4.redSqr(), I2 = S4.redSqr(), N10 = y4.redAdd(y4).redIAdd(y4).redIAdd(n3.redMul(g3)), R2 = h5.redMul(S4), F = N10.redSqr().redISub(R2.redAdd(R2)), U2 = R2.redISub(F), Q = N10.redMul(U2); + Q = Q.redIAdd(Q).redISub(I2); + var Bt = w4.redMul(b4); + r + 1 < t && (g3 = g3.redMul(I2)), h5 = F, b4 = Bt, w4 = Q; + } + return this.curve.jpoint(h5, w4.redMul(o2), b4); + }, Ut.prototype.dbl = function() { + return this.isInfinity() ? this : this.curve.zeroA ? this._zeroDbl() : this.curve.threeA ? this._threeDbl() : this._dbl(); + }, Ut.prototype._zeroDbl = function() { + var t, r, i2; + if (this.zOne) { + var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); + p3 = p3.redIAdd(p3); + var b4 = n3.redAdd(n3).redIAdd(n3), g3 = b4.redSqr().redISub(p3).redISub(p3), w4 = h5.redIAdd(h5); + w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), t = g3, r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); + } else { + var y4 = this.x.redSqr(), S4 = this.y.redSqr(), I2 = S4.redSqr(), N10 = this.x.redAdd(S4).redSqr().redISub(y4).redISub(I2); + N10 = N10.redIAdd(N10); + var R2 = y4.redAdd(y4).redIAdd(y4), F = R2.redSqr(), U2 = I2.redIAdd(I2); + U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), t = F.redISub(N10).redISub(N10), r = R2.redMul(N10.redISub(t)).redISub(U2), i2 = this.y.redMul(this.z), i2 = i2.redIAdd(i2); + } + return this.curve.jpoint(t, r, i2); + }, Ut.prototype._threeDbl = function() { + var t, r, i2; + if (this.zOne) { + var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); + p3 = p3.redIAdd(p3); + var b4 = n3.redAdd(n3).redIAdd(n3).redIAdd(this.curve.a), g3 = b4.redSqr().redISub(p3).redISub(p3); + t = g3; + var w4 = h5.redIAdd(h5); + w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); + } else { + var y4 = this.z.redSqr(), S4 = this.y.redSqr(), I2 = this.x.redMul(S4), N10 = this.x.redSub(y4).redMul(this.x.redAdd(y4)); + N10 = N10.redAdd(N10).redIAdd(N10); + var R2 = I2.redIAdd(I2); + R2 = R2.redIAdd(R2); + var F = R2.redAdd(R2); + t = N10.redSqr().redISub(F), i2 = this.y.redAdd(this.z).redSqr().redISub(S4).redISub(y4); + var U2 = S4.redSqr(); + U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), r = N10.redMul(R2.redISub(t)).redISub(U2); + } + return this.curve.jpoint(t, r, i2); + }, Ut.prototype._dbl = function() { + var t = this.curve.a, r = this.x, i2 = this.y, n3 = this.z, o2 = n3.redSqr().redSqr(), h5 = r.redSqr(), p3 = i2.redSqr(), b4 = h5.redAdd(h5).redIAdd(h5).redIAdd(t.redMul(o2)), g3 = r.redAdd(r); + g3 = g3.redIAdd(g3); + var w4 = g3.redMul(p3), y4 = b4.redSqr().redISub(w4.redAdd(w4)), S4 = w4.redISub(y4), I2 = p3.redSqr(); + I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); + var N10 = b4.redMul(S4).redISub(I2), R2 = i2.redAdd(i2).redMul(n3); + return this.curve.jpoint(y4, N10, R2); + }, Ut.prototype.trpl = function() { + if (!this.curve.zeroA) + return this.dbl().add(this); + var t = this.x.redSqr(), r = this.y.redSqr(), i2 = this.z.redSqr(), n3 = r.redSqr(), o2 = t.redAdd(t).redIAdd(t), h5 = o2.redSqr(), p3 = this.x.redAdd(r).redSqr().redISub(t).redISub(n3); + p3 = p3.redIAdd(p3), p3 = p3.redAdd(p3).redIAdd(p3), p3 = p3.redISub(h5); + var b4 = p3.redSqr(), g3 = n3.redIAdd(n3); + g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3); + var w4 = o2.redIAdd(p3).redSqr().redISub(h5).redISub(b4).redISub(g3), y4 = r.redMul(w4); + y4 = y4.redIAdd(y4), y4 = y4.redIAdd(y4); + var S4 = this.x.redMul(b4).redISub(y4); + S4 = S4.redIAdd(S4), S4 = S4.redIAdd(S4); + var I2 = this.y.redMul(w4.redMul(g3.redISub(w4)).redISub(p3.redMul(b4))); + I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); + var N10 = this.z.redAdd(p3).redSqr().redISub(i2).redISub(b4); + return this.curve.jpoint(S4, I2, N10); + }, Ut.prototype.mul = function(t, r) { + return t = new K2(t, r), this.curve._wnafMul(this, t); + }, Ut.prototype.eq = function(t) { + if (t.type === "affine") + return this.eq(t.toJ()); + if (this === t) + return true; + var r = this.z.redSqr(), i2 = t.z.redSqr(); + if (this.x.redMul(i2).redISub(t.x.redMul(r)).cmpn(0) !== 0) + return false; + var n3 = r.redMul(this.z), o2 = i2.redMul(t.z); + return this.y.redMul(o2).redISub(t.y.redMul(n3)).cmpn(0) === 0; + }, Ut.prototype.eqXToP = function(t) { + var r = this.z.redSqr(), i2 = t.toRed(this.curve.red).redMul(r); + if (this.x.cmp(i2) === 0) + return true; + for (var n3 = t.clone(), o2 = this.curve.redN.redMul(r); ; ) { + if (n3.iadd(this.curve.n), n3.cmp(this.curve.p) >= 0) + return false; + if (i2.redIAdd(o2), this.x.cmp(i2) === 0) + return true; + } + }, Ut.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }, Ut.prototype.isInfinity = function() { + return this.z.cmpn(0) === 0; + }; + var Kr = lr(function(e2, t) { + var r = t; + r.base = Xe, r.short = T0, r.mont = null, r.edwards = null; + }); + var Hr = lr(function(e2, t) { + var r = t, i2 = Jt.assert; + function n3(p3) { + p3.type === "short" ? this.curve = new Kr.short(p3) : p3.type === "edwards" ? this.curve = new Kr.edwards(p3) : this.curve = new Kr.mont(p3), this.g = this.curve.g, this.n = this.curve.n, this.hash = p3.hash, i2(this.g.validate(), "Invalid curve"), i2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); + } + r.PresetCurve = n3; + function o2(p3, b4) { + Object.defineProperty(r, p3, { configurable: true, enumerable: true, get: function() { + var g3 = new n3(b4); + return Object.defineProperty(r, p3, { configurable: true, enumerable: true, value: g3 }), g3; + } }); + } + o2("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: oe.sha256, gRed: false, g: ["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"] }), o2("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: oe.sha256, gRed: false, g: ["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"] }), o2("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: oe.sha256, gRed: false, g: ["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"] }), o2("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: oe.sha384, gRed: false, g: ["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"] }), o2("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: oe.sha512, gRed: false, g: ["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"] }), o2("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["9"] }), o2("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", "6666666666666666666666666666666666666666666666666666666666666658"] }); + var h5; + try { + h5 = null.crash(); + } catch { + h5 = void 0; + } + o2("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: oe.sha256, beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [{ a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" }], gRed: false, g: ["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", h5] }); + }); + function Re(e2) { + if (!(this instanceof Re)) + return new Re(e2); + this.hash = e2.hash, this.predResist = !!e2.predResist, this.outLen = this.hash.outSize, this.minEntropy = e2.minEntropy || this.hash.hmacStrength, this._reseed = null, this.reseedInterval = null, this.K = null, this.V = null; + var t = ne.toArray(e2.entropy, e2.entropyEnc || "hex"), r = ne.toArray(e2.nonce, e2.nonceEnc || "hex"), i2 = ne.toArray(e2.pers, e2.persEnc || "hex"); + Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._init(t, r, i2); + } + var If = Re; + Re.prototype._init = function(t, r, i2) { + var n3 = t.concat(r).concat(i2); + this.K = new Array(this.outLen / 8), this.V = new Array(this.outLen / 8); + for (var o2 = 0; o2 < this.V.length; o2++) + this.K[o2] = 0, this.V[o2] = 1; + this._update(n3), this._reseed = 1, this.reseedInterval = 281474976710656; + }, Re.prototype._hmac = function() { + return new oe.hmac(this.hash, this.K); + }, Re.prototype._update = function(t) { + var r = this._hmac().update(this.V).update([0]); + t && (r = r.update(t)), this.K = r.digest(), this.V = this._hmac().update(this.V).digest(), t && (this.K = this._hmac().update(this.V).update([1]).update(t).digest(), this.V = this._hmac().update(this.V).digest()); + }, Re.prototype.reseed = function(t, r, i2, n3) { + typeof r != "string" && (n3 = i2, i2 = r, r = null), t = ne.toArray(t, r), i2 = ne.toArray(i2, n3), Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._update(t.concat(i2 || [])), this._reseed = 1; + }, Re.prototype.generate = function(t, r, i2, n3) { + if (this._reseed > this.reseedInterval) + throw new Error("Reseed is required"); + typeof r != "string" && (n3 = i2, i2 = r, r = null), i2 && (i2 = ne.toArray(i2, n3 || "hex"), this._update(i2)); + for (var o2 = []; o2.length < t; ) + this.V = this._hmac().update(this.V).digest(), o2 = o2.concat(this.V); + var h5 = o2.slice(0, t); + return this._update(i2), this._reseed++, ne.encode(h5, r); + }; + var Di = Jt.assert; + function qt(e2, t) { + this.ec = e2, this.priv = null, this.pub = null, t.priv && this._importPrivate(t.priv, t.privEnc), t.pub && this._importPublic(t.pub, t.pubEnc); + } + var Ui = qt; + qt.fromPublic = function(t, r, i2) { + return r instanceof qt ? r : new qt(t, { pub: r, pubEnc: i2 }); + }, qt.fromPrivate = function(t, r, i2) { + return r instanceof qt ? r : new qt(t, { priv: r, privEnc: i2 }); + }, qt.prototype.validate = function() { + var t = this.getPublic(); + return t.isInfinity() ? { result: false, reason: "Invalid public key" } : t.validate() ? t.mul(this.ec.curve.n).isInfinity() ? { result: true, reason: null } : { result: false, reason: "Public key * N != O" } : { result: false, reason: "Public key is not a point" }; + }, qt.prototype.getPublic = function(t, r) { + return typeof t == "string" && (r = t, t = null), this.pub || (this.pub = this.ec.g.mul(this.priv)), r ? this.pub.encode(r, t) : this.pub; + }, qt.prototype.getPrivate = function(t) { + return t === "hex" ? this.priv.toString(16, 2) : this.priv; + }, qt.prototype._importPrivate = function(t, r) { + this.priv = new K2(t, r || 16), this.priv = this.priv.umod(this.ec.curve.n); + }, qt.prototype._importPublic = function(t, r) { + if (t.x || t.y) { + this.ec.curve.type === "mont" ? Di(t.x, "Need x coordinate") : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && Di(t.x && t.y, "Need both x and y coordinate"), this.pub = this.ec.curve.point(t.x, t.y); + return; + } + this.pub = this.ec.curve.decodePoint(t, r); + }, qt.prototype.derive = function(t) { + return t.validate() || Di(t.validate(), "public point not validated"), t.mul(this.priv).getX(); + }, qt.prototype.sign = function(t, r, i2) { + return this.ec.sign(t, this, r, i2); + }, qt.prototype.verify = function(t, r) { + return this.ec.verify(t, r, this); + }, qt.prototype.inspect = function() { + return ""; + }; + var F0 = Jt.assert; + function Lr(e2, t) { + if (e2 instanceof Lr) + return e2; + this._importDER(e2, t) || (F0(e2.r && e2.s, "Signature without r or s"), this.r = new K2(e2.r, 16), this.s = new K2(e2.s, 16), e2.recoveryParam === void 0 ? this.recoveryParam = null : this.recoveryParam = e2.recoveryParam); + } + var zr = Lr; + function D0() { + this.place = 0; + } + function ki(e2, t) { + var r = e2[t.place++]; + if (!(r & 128)) + return r; + var i2 = r & 15; + if (i2 === 0 || i2 > 4) + return false; + for (var n3 = 0, o2 = 0, h5 = t.place; o2 < i2; o2++, h5++) + n3 <<= 8, n3 |= e2[h5], n3 >>>= 0; + return n3 <= 127 ? false : (t.place = h5, n3); + } + function _f(e2) { + for (var t = 0, r = e2.length - 1; !e2[t] && !(e2[t + 1] & 128) && t < r; ) + t++; + return t === 0 ? e2 : e2.slice(t); + } + Lr.prototype._importDER = function(t, r) { + t = Jt.toArray(t, r); + var i2 = new D0(); + if (t[i2.place++] !== 48) + return false; + var n3 = ki(t, i2); + if (n3 === false || n3 + i2.place !== t.length || t[i2.place++] !== 2) + return false; + var o2 = ki(t, i2); + if (o2 === false) + return false; + var h5 = t.slice(i2.place, o2 + i2.place); + if (i2.place += o2, t[i2.place++] !== 2) + return false; + var p3 = ki(t, i2); + if (p3 === false || t.length !== p3 + i2.place) + return false; + var b4 = t.slice(i2.place, p3 + i2.place); + if (h5[0] === 0) + if (h5[1] & 128) + h5 = h5.slice(1); + else + return false; + if (b4[0] === 0) + if (b4[1] & 128) + b4 = b4.slice(1); + else + return false; + return this.r = new K2(h5), this.s = new K2(b4), this.recoveryParam = null, true; + }; + function qi(e2, t) { + if (t < 128) { + e2.push(t); + return; + } + var r = 1 + (Math.log(t) / Math.LN2 >>> 3); + for (e2.push(r | 128); --r; ) + e2.push(t >>> (r << 3) & 255); + e2.push(t); + } + Lr.prototype.toDER = function(t) { + var r = this.r.toArray(), i2 = this.s.toArray(); + for (r[0] & 128 && (r = [0].concat(r)), i2[0] & 128 && (i2 = [0].concat(i2)), r = _f(r), i2 = _f(i2); !i2[0] && !(i2[1] & 128); ) + i2 = i2.slice(1); + var n3 = [2]; + qi(n3, r.length), n3 = n3.concat(r), n3.push(2), qi(n3, i2.length); + var o2 = n3.concat(i2), h5 = [48]; + return qi(h5, o2.length), h5 = h5.concat(o2), Jt.encode(h5, t); + }; + var U0 = function() { + throw new Error("unsupported"); + }; + var Bf = Jt.assert; + function te(e2) { + if (!(this instanceof te)) + return new te(e2); + typeof e2 == "string" && (Bf(Object.prototype.hasOwnProperty.call(Hr, e2), "Unknown curve " + e2), e2 = Hr[e2]), e2 instanceof Hr.PresetCurve && (e2 = { curve: e2 }), this.curve = e2.curve.curve, this.n = this.curve.n, this.nh = this.n.ushrn(1), this.g = this.curve.g, this.g = e2.curve.g, this.g.precompute(e2.curve.n.bitLength() + 1), this.hash = e2.hash || e2.curve.hash; + } + var k0 = te; + te.prototype.keyPair = function(t) { + return new Ui(this, t); + }, te.prototype.keyFromPrivate = function(t, r) { + return Ui.fromPrivate(this, t, r); + }, te.prototype.keyFromPublic = function(t, r) { + return Ui.fromPublic(this, t, r); + }, te.prototype.genKeyPair = function(t) { + t || (t = {}); + for (var r = new If({ hash: this.hash, pers: t.pers, persEnc: t.persEnc || "utf8", entropy: t.entropy || U0(this.hash.hmacStrength), entropyEnc: t.entropy && t.entropyEnc || "utf8", nonce: this.n.toArray() }), i2 = this.n.byteLength(), n3 = this.n.sub(new K2(2)); ; ) { + var o2 = new K2(r.generate(i2)); + if (!(o2.cmp(n3) > 0)) + return o2.iaddn(1), this.keyFromPrivate(o2); + } + }, te.prototype._truncateToN = function(t, r) { + var i2 = t.byteLength() * 8 - this.n.bitLength(); + return i2 > 0 && (t = t.ushrn(i2)), !r && t.cmp(this.n) >= 0 ? t.sub(this.n) : t; + }, te.prototype.sign = function(t, r, i2, n3) { + typeof i2 == "object" && (n3 = i2, i2 = null), n3 || (n3 = {}), r = this.keyFromPrivate(r, i2), t = this._truncateToN(new K2(t, 16)); + for (var o2 = this.n.byteLength(), h5 = r.getPrivate().toArray("be", o2), p3 = t.toArray("be", o2), b4 = new If({ hash: this.hash, entropy: h5, nonce: p3, pers: n3.pers, persEnc: n3.persEnc || "utf8" }), g3 = this.n.sub(new K2(1)), w4 = 0; ; w4++) { + var y4 = n3.k ? n3.k(w4) : new K2(b4.generate(this.n.byteLength())); + if (y4 = this._truncateToN(y4, true), !(y4.cmpn(1) <= 0 || y4.cmp(g3) >= 0)) { + var S4 = this.g.mul(y4); + if (!S4.isInfinity()) { + var I2 = S4.getX(), N10 = I2.umod(this.n); + if (N10.cmpn(0) !== 0) { + var R2 = y4.invm(this.n).mul(N10.mul(r.getPrivate()).iadd(t)); + if (R2 = R2.umod(this.n), R2.cmpn(0) !== 0) { + var F = (S4.getY().isOdd() ? 1 : 0) | (I2.cmp(N10) !== 0 ? 2 : 0); + return n3.canonical && R2.cmp(this.nh) > 0 && (R2 = this.n.sub(R2), F ^= 1), new zr({ r: N10, s: R2, recoveryParam: F }); + } + } + } + } + } + }, te.prototype.verify = function(t, r, i2, n3) { + t = this._truncateToN(new K2(t, 16)), i2 = this.keyFromPublic(i2, n3), r = new zr(r, "hex"); + var o2 = r.r, h5 = r.s; + if (o2.cmpn(1) < 0 || o2.cmp(this.n) >= 0 || h5.cmpn(1) < 0 || h5.cmp(this.n) >= 0) + return false; + var p3 = h5.invm(this.n), b4 = p3.mul(t).umod(this.n), g3 = p3.mul(o2).umod(this.n), w4; + return this.curve._maxwellTrick ? (w4 = this.g.jmulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.eqXToP(o2)) : (w4 = this.g.mulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.getX().umod(this.n).cmp(o2) === 0); + }, te.prototype.recoverPubKey = function(e2, t, r, i2) { + Bf((3 & r) === r, "The recovery param is more than two bits"), t = new zr(t, i2); + var n3 = this.n, o2 = new K2(e2), h5 = t.r, p3 = t.s, b4 = r & 1, g3 = r >> 1; + if (h5.cmp(this.curve.p.umod(this.curve.n)) >= 0 && g3) + throw new Error("Unable to find sencond key candinate"); + g3 ? h5 = this.curve.pointFromX(h5.add(this.curve.n), b4) : h5 = this.curve.pointFromX(h5, b4); + var w4 = t.r.invm(n3), y4 = n3.sub(o2).mul(w4).umod(n3), S4 = p3.mul(w4).umod(n3); + return this.g.mulAdd(y4, h5, S4); + }, te.prototype.getKeyRecoveryParam = function(e2, t, r, i2) { + if (t = new zr(t, i2), t.recoveryParam !== null) + return t.recoveryParam; + for (var n3 = 0; n3 < 4; n3++) { + var o2; + try { + o2 = this.recoverPubKey(e2, t, n3); + } catch { + continue; + } + if (o2.eq(r)) + return n3; + } + throw new Error("Unable to find valid recovery factor"); + }; + var q0 = lr(function(e2, t) { + var r = t; + r.version = "6.5.4", r.utils = Jt, r.rand = function() { + throw new Error("unsupported"); + }, r.curve = Kr, r.curves = Hr, r.ec = k0, r.eddsa = null; + }); + var K0 = q0.ec; + var H0 = "signing-key/5.7.0"; + var Ki = new z3(H0); + var Hi = null; + function pe() { + return Hi || (Hi = new K0("secp256k1")), Hi; + } + var L0 = class { + constructor(t) { + yr(this, "curve", "secp256k1"), yr(this, "privateKey", Ht(t)), xs(this.privateKey) !== 32 && Ki.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); + const r = pe().keyFromPrivate(Pt(this.privateKey)); + yr(this, "publicKey", "0x" + r.getPublic(false, "hex")), yr(this, "compressedPublicKey", "0x" + r.getPublic(true, "hex")), yr(this, "_isSigningKey", true); + } + _addPoint(t) { + const r = pe().keyFromPublic(Pt(this.publicKey)), i2 = pe().keyFromPublic(Pt(t)); + return "0x" + r.pub.add(i2.pub).encodeCompressed("hex"); + } + signDigest(t) { + const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = Pt(t); + i2.length !== 32 && Ki.throwArgumentError("bad digest length", "digest", t); + const n3 = r.sign(i2, { canonical: true }); + return kn({ recoveryParam: n3.recoveryParam, r: fe("0x" + n3.r.toString(16), 32), s: fe("0x" + n3.s.toString(16), 32) }); + } + computeSharedSecret(t) { + const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = pe().keyFromPublic(Pt(Rf(t))); + return fe("0x" + r.derive(i2.getPublic()).toString(16), 32); + } + static isSigningKey(t) { + return !!(t && t._isSigningKey); + } + }; + function z0(e2, t) { + const r = kn(t), i2 = { r: Pt(r.r), s: Pt(r.s) }; + return "0x" + pe().recoverPubKey(Pt(e2), i2, r.recoveryParam).encode("hex", false); + } + function Rf(e2, t) { + const r = Pt(e2); + if (r.length === 32) { + const i2 = new L0(r); + return t ? "0x" + pe().keyFromPrivate(r).getPublic(true, "hex") : i2.publicKey; + } else { + if (r.length === 33) + return t ? Ht(r) : "0x" + pe().keyFromPublic(r).getPublic(false, "hex"); + if (r.length === 65) + return t ? "0x" + pe().keyFromPublic(r).getPublic(true, "hex") : Ht(r); + } + return Ki.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); + } + var j0 = "transactions/5.7.0"; + new z3(j0); + var Cf; + (function(e2) { + e2[e2.legacy = 0] = "legacy", e2[e2.eip2930 = 1] = "eip2930", e2[e2.eip1559 = 2] = "eip1559"; + })(Cf || (Cf = {})); + function V0(e2) { + const t = Rf(e2); + return ta(Un(wi(Un(t, 1)), 12)); + } + function Q0(e2, t) { + return V0(z0(Pt(e2), t)); + } + var J0 = "https://rpc.walletconnect.com/v1"; + async function Of(e2, t, r, i2, n3, o2) { + switch (r.t) { + case "eip191": + return Pf(e2, t, r.s); + case "eip1271": + return await Tf(e2, t, r.s, i2, n3, o2); + default: + throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`); + } + } + function Pf(e2, t, r) { + return Q0(tf(t), r).toLowerCase() === e2.toLowerCase(); + } + async function Tf(e2, t, r, i2, n3, o2) { + try { + const h5 = "0x1626ba7e", p3 = "0000000000000000000000000000000000000000000000000000000000000040", b4 = "0000000000000000000000000000000000000000000000000000000000000041", g3 = r.substring(2), w4 = tf(t).substring(2), y4 = h5 + w4 + p3 + b4 + g3, S4 = await fetch(`${o2 || J0}/?chainId=${i2}&projectId=${n3}`, { method: "POST", body: JSON.stringify({ id: Y0(), jsonrpc: "2.0", method: "eth_call", params: [{ to: e2, data: y4 }, "latest"] }) }), { result: I2 } = await S4.json(); + return I2 ? I2.slice(0, h5.length).toLowerCase() === h5.toLowerCase() : false; + } catch (h5) { + return console.error("isValidEip1271Signature: ", h5), false; + } + } + function Y0() { + return Date.now() + Math.floor(Math.random() * 1e3); + } + var G0 = Object.defineProperty; + var W0 = Object.defineProperties; + var X0 = Object.getOwnPropertyDescriptors; + var Ff = Object.getOwnPropertySymbols; + var Z0 = Object.prototype.hasOwnProperty; + var $0 = Object.prototype.propertyIsEnumerable; + var Df = (e2, t, r) => t in e2 ? G0(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var Li = (e2, t) => { + for (var r in t || (t = {})) + Z0.call(t, r) && Df(e2, r, t[r]); + if (Ff) + for (var r of Ff(t)) + $0.call(t, r) && Df(e2, r, t[r]); + return e2; + }; + var Uf = (e2, t) => W0(e2, X0(t)); + var tu = "did:pkh:"; + var jr = (e2) => e2?.split(":"); + var zi = (e2) => { + const t = e2 && jr(e2); + if (t) + return e2.includes(tu) ? t[3] : t[1]; + }; + var eu = (e2) => { + const t = e2 && jr(e2); + if (t) + return t[2] + ":" + t[3]; + }; + var ji = (e2) => { + const t = e2 && jr(e2); + if (t) + return t.pop(); + }; + async function ru(e2) { + const { cacao: t, projectId: r } = e2, { s: i2, p: n3 } = t, o2 = kf(n3, n3.iss), h5 = ji(n3.iss); + return await Of(h5, o2, i2, zi(n3.iss), r); + } + var kf = (e2, t) => { + const r = `${e2.domain} wants you to sign in with your Ethereum account:`, i2 = ji(t); + if (!e2.aud && !e2.uri) + throw new Error("Either `aud` or `uri` is required to construct the message"); + let n3 = e2.statement || void 0; + const o2 = `URI: ${e2.aud || e2.uri}`, h5 = `Version: ${e2.version}`, p3 = `Chain ID: ${zi(t)}`, b4 = `Nonce: ${e2.nonce}`, g3 = `Issued At: ${e2.iat}`, w4 = e2.resources ? `Resources:${e2.resources.map((S4) => ` +- ${S4}`).join("")}` : void 0, y4 = Qr(e2.resources); + if (y4) { + const S4 = Ce(y4); + n3 = Ji(n3, S4); + } + return [r, i2, "", n3, "", o2, h5, p3, b4, g3, w4].filter((S4) => S4 != null).join(` +`); + }; + function iu(e2, t, r) { + return r.includes("did:pkh:") || (r = `did:pkh:${r}`), { h: { t: "caip122" }, p: { iss: r, domain: e2.domain, aud: e2.aud, version: e2.version, nonce: e2.nonce, iat: e2.iat, statement: e2.statement, requestId: e2.requestId, resources: e2.resources, nbf: e2.nbf, exp: e2.exp }, s: t }; + } + function nu(e2) { + var t; + const { authPayload: r, chains: i2, methods: n3 } = e2, o2 = r.statement || ""; + if (!(i2 != null && i2.length)) + return r; + const h5 = r.chains, p3 = mi(h5, i2); + if (!(p3 != null && p3.length)) + throw new Error("No supported chains"); + const b4 = qf(r.resources); + if (!b4) + return r; + ve(b4); + const g3 = Kf(b4, "eip155"); + let w4 = r?.resources || []; + if (g3 != null && g3.length) { + const y4 = Hf(g3), S4 = mi(y4, n3); + if (!(S4 != null && S4.length)) + throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(y4)}, supported: ${JSON.stringify(n3)}`); + const I2 = Vi("request", S4, { chains: p3 }), N10 = Vf(b4, "eip155", I2); + w4 = ((t = r?.resources) == null ? void 0 : t.slice(0, -1)) || [], w4.push(Vr(N10)); + } + return Uf(Li({}, r), { statement: Jf(o2, Qr(w4)), chains: p3, resources: r != null && r.resources || w4.length > 0 ? w4 : void 0 }); + } + function qf(e2) { + const t = Qr(e2); + if (t && Qi(t)) + return Ce(t); + } + function fu(e2, t) { + var r; + return (r = e2?.att) == null ? void 0 : r.hasOwnProperty(t); + } + function Kf(e2, t) { + var r, i2; + return (r = e2?.att) != null && r[t] ? Object.keys((i2 = e2?.att) == null ? void 0 : i2[t]) : []; + } + function ou(e2) { + return e2?.map((t) => Object.keys(t)) || []; + } + function Hf(e2) { + return e2?.map((t) => { + var r; + return (r = t.split("/")) == null ? void 0 : r[1]; + }) || []; + } + function Lf(e2) { + return import_buffer.Buffer.from(JSON.stringify(e2)).toString("base64"); + } + function zf(e2) { + return JSON.parse(import_buffer.Buffer.from(e2, "base64").toString("utf-8")); + } + function ve(e2) { + if (!e2) + throw new Error("No recap provided, value is undefined"); + if (!e2.att) + throw new Error("No `att` property found"); + const t = Object.keys(e2.att); + if (!(t != null && t.length)) + throw new Error("No resources found in `att` property"); + t.forEach((r) => { + const i2 = e2.att[r]; + if (Array.isArray(i2)) + throw new Error(`Resource must be an object: ${r}`); + if (typeof i2 != "object") + throw new Error(`Resource must be an object: ${r}`); + if (!Object.keys(i2).length) + throw new Error(`Resource object is empty: ${r}`); + Object.keys(i2).forEach((n3) => { + const o2 = i2[n3]; + if (!Array.isArray(o2)) + throw new Error(`Ability limits ${n3} must be an array of objects, found: ${o2}`); + if (!o2.length) + throw new Error(`Value of ${n3} is empty array, must be an array with objects`); + o2.forEach((h5) => { + if (typeof h5 != "object") + throw new Error(`Ability limits (${n3}) must be an array of objects, found: ${h5}`); + }); + }); + }); + } + function jf(e2, t, r, i2 = {}) { + return r?.sort((n3, o2) => n3.localeCompare(o2)), { att: { [e2]: Vi(t, r, i2) } }; + } + function Vf(e2, t, r) { + var i2; + return e2.att[t] = Li({}, r), ((i2 = Object.keys(e2.att)) == null ? void 0 : i2.sort((n3, o2) => n3.localeCompare(o2))).reduce((n3, o2) => (n3.att[o2] = e2.att[o2], n3), { att: {} }); + } + function Vi(e2, t, r = {}) { + t = t?.sort((n3, o2) => n3.localeCompare(o2)); + const i2 = t.map((n3) => ({ [`${e2}/${n3}`]: [r] })); + return Object.assign({}, ...i2); + } + function Vr(e2) { + return ve(e2), `urn:recap:${Lf(e2).replace(/=/g, "")}`; + } + function Ce(e2) { + const t = zf(e2.replace("urn:recap:", "")); + return ve(t), t; + } + function su(e2, t, r) { + const i2 = jf(e2, t, r); + return Vr(i2); + } + function Qi(e2) { + return e2 && e2.includes("urn:recap:"); + } + function au(e2, t) { + const r = Ce(e2), i2 = Ce(t), n3 = Qf(r, i2); + return Vr(n3); + } + function Qf(e2, t) { + ve(e2), ve(t); + const r = Object.keys(e2.att).concat(Object.keys(t.att)).sort((n3, o2) => n3.localeCompare(o2)), i2 = { att: {} }; + return r.forEach((n3) => { + var o2, h5; + Object.keys(((o2 = e2.att) == null ? void 0 : o2[n3]) || {}).concat(Object.keys(((h5 = t.att) == null ? void 0 : h5[n3]) || {})).sort((p3, b4) => p3.localeCompare(b4)).forEach((p3) => { + var b4, g3; + i2.att[n3] = Uf(Li({}, i2.att[n3]), { [p3]: ((b4 = e2.att[n3]) == null ? void 0 : b4[p3]) || ((g3 = t.att[n3]) == null ? void 0 : g3[p3]) }); + }); + }), i2; + } + function Ji(e2 = "", t) { + ve(t); + const r = "I further authorize the stated URI to perform the following actions on my behalf: "; + if (e2.includes(r)) + return e2; + const i2 = []; + let n3 = 0; + Object.keys(t.att).forEach((p3) => { + const b4 = Object.keys(t.att[p3]).map((y4) => ({ ability: y4.split("/")[0], action: y4.split("/")[1] })); + b4.sort((y4, S4) => y4.action.localeCompare(S4.action)); + const g3 = {}; + b4.forEach((y4) => { + g3[y4.ability] || (g3[y4.ability] = []), g3[y4.ability].push(y4.action); + }); + const w4 = Object.keys(g3).map((y4) => (n3++, `(${n3}) '${y4}': '${g3[y4].join("', '")}' for '${p3}'.`)); + i2.push(w4.join(", ").replace(".,", ".")); + }); + const o2 = i2.join(" "), h5 = `${r}${o2}`; + return `${e2 ? e2 + " " : ""}${h5}`; + } + function uu(e2) { + var t; + const r = Ce(e2); + ve(r); + const i2 = (t = r.att) == null ? void 0 : t.eip155; + return i2 ? Object.keys(i2).map((n3) => n3.split("/")[1]) : []; + } + function hu(e2) { + const t = Ce(e2); + ve(t); + const r = []; + return Object.values(t.att).forEach((i2) => { + Object.values(i2).forEach((n3) => { + var o2; + (o2 = n3?.[0]) != null && o2.chains && r.push(n3[0].chains); + }); + }), [...new Set(r.flat())]; + } + function Jf(e2, t) { + if (!t) + return e2; + const r = Ce(t); + return ve(r), Ji(e2, r); + } + function Qr(e2) { + if (!e2) + return; + const t = e2?.[e2.length - 1]; + return Qi(t) ? t : void 0; + } + var Yi = "base10"; + var zt = "base16"; + var Jr = "base64pad"; + var Yr = "utf8"; + var Gi = 0; + var dr = 1; + var cu = 0; + var Yf = 1; + var Wi = 12; + var Xi = 32; + function lu() { + const e2 = an.generateKeyPair(); + return { privateKey: Rt.toString(e2.secretKey, zt), publicKey: Rt.toString(e2.publicKey, zt) }; + } + function du() { + const e2 = on.randomBytes(Xi); + return Rt.toString(e2, zt); + } + function pu(e2, t) { + const r = an.sharedKey(Rt.fromString(e2, zt), Rt.fromString(t, zt), true), i2 = new Po.HKDF(ci.SHA256, r).expand(Xi); + return Rt.toString(i2, zt); + } + function vu(e2) { + const t = ci.hash(Rt.fromString(e2, zt)); + return Rt.toString(t, zt); + } + function gu(e2) { + const t = ci.hash(Rt.fromString(e2, Yr)); + return Rt.toString(t, zt); + } + function Gf(e2) { + return Rt.fromString(`${e2}`, Yi); + } + function Er(e2) { + return Number(Rt.toString(e2, Yi)); + } + function mu(e2) { + const t = Gf(typeof e2.type < "u" ? e2.type : Gi); + if (Er(t) === dr && typeof e2.senderPublicKey > "u") + throw new Error("Missing sender public key for type 1 envelope"); + const r = typeof e2.senderPublicKey < "u" ? Rt.fromString(e2.senderPublicKey, zt) : void 0, i2 = typeof e2.iv < "u" ? Rt.fromString(e2.iv, zt) : on.randomBytes(Wi), n3 = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)).seal(i2, Rt.fromString(e2.message, Yr)); + return Wf({ type: t, sealed: n3, iv: i2, senderPublicKey: r }); + } + function Au(e2) { + const t = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)), { sealed: r, iv: i2 } = Zi(e2.encoded), n3 = t.open(i2, r); + if (n3 === null) + throw new Error("Failed to decrypt"); + return Rt.toString(n3, Yr); + } + function Wf(e2) { + if (Er(e2.type) === dr) { + if (typeof e2.senderPublicKey > "u") + throw new Error("Missing sender public key for type 1 envelope"); + return Rt.toString(Rt.concat([e2.type, e2.senderPublicKey, e2.iv, e2.sealed]), Jr); + } + return Rt.toString(Rt.concat([e2.type, e2.iv, e2.sealed]), Jr); + } + function Zi(e2) { + const t = Rt.fromString(e2, Jr), r = t.slice(cu, Yf), i2 = Yf; + if (Er(r) === dr) { + const p3 = i2 + Xi, b4 = p3 + Wi, g3 = t.slice(i2, p3), w4 = t.slice(p3, b4), y4 = t.slice(b4); + return { type: r, sealed: y4, iv: w4, senderPublicKey: g3 }; + } + const n3 = i2 + Wi, o2 = t.slice(i2, n3), h5 = t.slice(n3); + return { type: r, sealed: h5, iv: o2 }; + } + function bu(e2, t) { + const r = Zi(e2); + return Xf({ type: Er(r.type), senderPublicKey: typeof r.senderPublicKey < "u" ? Rt.toString(r.senderPublicKey, zt) : void 0, receiverPublicKey: t?.receiverPublicKey }); + } + function Xf(e2) { + const t = e2?.type || Gi; + if (t === dr) { + if (typeof e2?.senderPublicKey > "u") + throw new Error("missing sender public key"); + if (typeof e2?.receiverPublicKey > "u") + throw new Error("missing receiver public key"); + } + return { type: t, senderPublicKey: e2?.senderPublicKey, receiverPublicKey: e2?.receiverPublicKey }; + } + function yu(e2) { + return e2.type === dr && typeof e2.senderPublicKey == "string" && typeof e2.receiverPublicKey == "string"; + } + var Zf = "irn"; + function wu(e2) { + return e2?.relay || { protocol: Zf }; + } + function xu(e2) { + const t = Fo.RELAY_JSONRPC[e2]; + if (typeof t > "u") + throw new Error(`Relay Protocol not supported: ${e2}`); + return t; + } + var Mu = Object.defineProperty; + var Eu = Object.defineProperties; + var Su = Object.getOwnPropertyDescriptors; + var $f = Object.getOwnPropertySymbols; + var Nu = Object.prototype.hasOwnProperty; + var Iu = Object.prototype.propertyIsEnumerable; + var to = (e2, t, r) => t in e2 ? Mu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var eo = (e2, t) => { + for (var r in t || (t = {})) + Nu.call(t, r) && to(e2, r, t[r]); + if ($f) + for (var r of $f(t)) + Iu.call(t, r) && to(e2, r, t[r]); + return e2; + }; + var _u = (e2, t) => Eu(e2, Su(t)); + function ro(e2, t = "-") { + const r = {}, i2 = "relay" + t; + return Object.keys(e2).forEach((n3) => { + if (n3.startsWith(i2)) { + const o2 = n3.replace(i2, ""), h5 = e2[n3]; + r[o2] = h5; + } + }), r; + } + function Bu(e2) { + e2 = e2.includes("wc://") ? e2.replace("wc://", "") : e2, e2 = e2.includes("wc:") ? e2.replace("wc:", "") : e2; + const t = e2.indexOf(":"), r = e2.indexOf("?") !== -1 ? e2.indexOf("?") : void 0, i2 = e2.substring(0, t), n3 = e2.substring(t + 1, r).split("@"), o2 = typeof r < "u" ? e2.substring(r) : "", h5 = Ir.parse(o2), p3 = typeof h5.methods == "string" ? h5.methods.split(",") : void 0; + return { protocol: i2, topic: io(n3[0]), version: parseInt(n3[1], 10), symKey: h5.symKey, relay: ro(h5), methods: p3, expiryTimestamp: h5.expiryTimestamp ? parseInt(h5.expiryTimestamp, 10) : void 0 }; + } + function io(e2) { + return e2.startsWith("//") ? e2.substring(2) : e2; + } + function no(e2, t = "-") { + const r = "relay", i2 = {}; + return Object.keys(e2).forEach((n3) => { + const o2 = r + t + n3; + e2[n3] && (i2[o2] = e2[n3]); + }), i2; + } + function Ru(e2) { + return `${e2.protocol}:${e2.topic}@${e2.version}?` + Ir.stringify(eo(_u(eo({ symKey: e2.symKey }, no(e2.relay)), { expiryTimestamp: e2.expiryTimestamp }), e2.methods ? { methods: e2.methods.join(",") } : {})); + } + var Cu = Object.defineProperty; + var Ou = Object.defineProperties; + var Pu = Object.getOwnPropertyDescriptors; + var fo = Object.getOwnPropertySymbols; + var Tu = Object.prototype.hasOwnProperty; + var Fu = Object.prototype.propertyIsEnumerable; + var oo = (e2, t, r) => t in e2 ? Cu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; + var Du = (e2, t) => { + for (var r in t || (t = {})) + Tu.call(t, r) && oo(e2, r, t[r]); + if (fo) + for (var r of fo(t)) + Fu.call(t, r) && oo(e2, r, t[r]); + return e2; + }; + var Uu = (e2, t) => Ou(e2, Pu(t)); + function Ze(e2) { + const t = []; + return e2.forEach((r) => { + const [i2, n3] = r.split(":"); + t.push(`${i2}:${n3}`); + }), t; + } + function so(e2) { + const t = []; + return Object.values(e2).forEach((r) => { + t.push(...Ze(r.accounts)); + }), t; + } + function ao(e2, t) { + const r = []; + return Object.values(e2).forEach((i2) => { + Ze(i2.accounts).includes(t) && r.push(...i2.methods); + }), r; + } + function uo(e2, t) { + const r = []; + return Object.values(e2).forEach((i2) => { + Ze(i2.accounts).includes(t) && r.push(...i2.events); + }), r; + } + function ku(e2, t) { + const r = wo(e2, t); + if (r) + throw new Error(r.message); + const i2 = {}; + for (const [n3, o2] of Object.entries(e2)) + i2[n3] = { methods: o2.methods, events: o2.events, chains: o2.accounts.map((h5) => `${h5.split(":")[0]}:${h5.split(":")[1]}`) }; + return i2; + } + function qu(e2) { + const { proposal: { requiredNamespaces: t, optionalNamespaces: r = {} }, supportedNamespaces: i2 } = e2, n3 = tn(t), o2 = tn(r), h5 = {}; + Object.keys(i2).forEach((g3) => { + const w4 = i2[g3].chains, y4 = i2[g3].methods, S4 = i2[g3].events, I2 = i2[g3].accounts; + w4.forEach((N10) => { + if (!I2.some((R2) => R2.includes(N10))) + throw new Error(`No accounts provided for chain ${N10} in namespace ${g3}`); + }), h5[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; + }); + const p3 = Mo(t, h5, "approve()"); + if (p3) + throw new Error(p3.message); + const b4 = {}; + return !Object.keys(t).length && !Object.keys(r).length ? h5 : (Object.keys(n3).forEach((g3) => { + const w4 = i2[g3].chains.filter((N10) => { + var R2, F; + return (F = (R2 = n3[g3]) == null ? void 0 : R2.chains) == null ? void 0 : F.includes(N10); + }), y4 = i2[g3].methods.filter((N10) => { + var R2, F; + return (F = (R2 = n3[g3]) == null ? void 0 : R2.methods) == null ? void 0 : F.includes(N10); + }), S4 = i2[g3].events.filter((N10) => { + var R2, F; + return (F = (R2 = n3[g3]) == null ? void 0 : R2.events) == null ? void 0 : F.includes(N10); + }), I2 = w4.map((N10) => i2[g3].accounts.filter((R2) => R2.includes(`${N10}:`))).flat(); + b4[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; + }), Object.keys(o2).forEach((g3) => { + var w4, y4, S4, I2, N10, R2; + if (!i2[g3]) + return; + const F = (y4 = (w4 = o2[g3]) == null ? void 0 : w4.chains) == null ? void 0 : y4.filter((J) => i2[g3].chains.includes(J)), U2 = i2[g3].methods.filter((J) => { + var H, L2; + return (L2 = (H = o2[g3]) == null ? void 0 : H.methods) == null ? void 0 : L2.includes(J); + }), Q = i2[g3].events.filter((J) => { + var H, L2; + return (L2 = (H = o2[g3]) == null ? void 0 : H.events) == null ? void 0 : L2.includes(J); + }), Bt = F?.map((J) => i2[g3].accounts.filter((H) => H.includes(`${J}:`))).flat(); + b4[g3] = { chains: ge((S4 = b4[g3]) == null ? void 0 : S4.chains, F), methods: ge((I2 = b4[g3]) == null ? void 0 : I2.methods, U2), events: ge((N10 = b4[g3]) == null ? void 0 : N10.events, Q), accounts: ge((R2 = b4[g3]) == null ? void 0 : R2.accounts, Bt) }; + }), b4); + } + function $i(e2) { + return e2.includes(":"); + } + function ho(e2) { + return $i(e2) ? e2.split(":")[0] : e2; + } + function tn(e2) { + var t, r, i2; + const n3 = {}; + if (!Gr(e2)) + return n3; + for (const [o2, h5] of Object.entries(e2)) { + const p3 = $i(o2) ? [o2] : h5.chains, b4 = h5.methods || [], g3 = h5.events || [], w4 = ho(o2); + n3[w4] = Uu(Du({}, n3[w4]), { chains: ge(p3, (t = n3[w4]) == null ? void 0 : t.chains), methods: ge(b4, (r = n3[w4]) == null ? void 0 : r.methods), events: ge(g3, (i2 = n3[w4]) == null ? void 0 : i2.events) }); + } + return n3; + } + function co(e2) { + const t = {}; + return e2?.forEach((r) => { + const [i2, n3] = r.split(":"); + t[i2] || (t[i2] = { accounts: [], chains: [], events: [] }), t[i2].accounts.push(r), t[i2].chains.push(`${i2}:${n3}`); + }), t; + } + function Ku(e2, t) { + t = t.map((i2) => i2.replace("did:pkh:", "")); + const r = co(t); + for (const [i2, n3] of Object.entries(r)) + n3.methods ? n3.methods = ge(n3.methods, e2) : n3.methods = e2, n3.events = ["chainChanged", "accountsChanged"]; + return r; + } + var lo = { INVALID_METHOD: { message: "Invalid method.", code: 1001 }, INVALID_EVENT: { message: "Invalid event.", code: 1002 }, INVALID_UPDATE_REQUEST: { message: "Invalid update request.", code: 1003 }, INVALID_EXTEND_REQUEST: { message: "Invalid extend request.", code: 1004 }, INVALID_SESSION_SETTLE_REQUEST: { message: "Invalid session settle request.", code: 1005 }, UNAUTHORIZED_METHOD: { message: "Unauthorized method.", code: 3001 }, UNAUTHORIZED_EVENT: { message: "Unauthorized event.", code: 3002 }, UNAUTHORIZED_UPDATE_REQUEST: { message: "Unauthorized update request.", code: 3003 }, UNAUTHORIZED_EXTEND_REQUEST: { message: "Unauthorized extend request.", code: 3004 }, USER_REJECTED: { message: "User rejected.", code: 5e3 }, USER_REJECTED_CHAINS: { message: "User rejected chains.", code: 5001 }, USER_REJECTED_METHODS: { message: "User rejected methods.", code: 5002 }, USER_REJECTED_EVENTS: { message: "User rejected events.", code: 5003 }, UNSUPPORTED_CHAINS: { message: "Unsupported chains.", code: 5100 }, UNSUPPORTED_METHODS: { message: "Unsupported methods.", code: 5101 }, UNSUPPORTED_EVENTS: { message: "Unsupported events.", code: 5102 }, UNSUPPORTED_ACCOUNTS: { message: "Unsupported accounts.", code: 5103 }, UNSUPPORTED_NAMESPACE_KEY: { message: "Unsupported namespace key.", code: 5104 }, USER_DISCONNECTED: { message: "User disconnected.", code: 6e3 }, SESSION_SETTLEMENT_FAILED: { message: "Session settlement failed.", code: 7e3 }, WC_METHOD_UNSUPPORTED: { message: "Unsupported wc_ method.", code: 10001 } }; + var po = { NOT_INITIALIZED: { message: "Not initialized.", code: 1 }, NO_MATCHING_KEY: { message: "No matching key.", code: 2 }, RESTORE_WILL_OVERRIDE: { message: "Restore will override.", code: 3 }, RESUBSCRIBED: { message: "Resubscribed.", code: 4 }, MISSING_OR_INVALID: { message: "Missing or invalid.", code: 5 }, EXPIRED: { message: "Expired.", code: 6 }, UNKNOWN_TYPE: { message: "Unknown type.", code: 7 }, MISMATCHED_TOPIC: { message: "Mismatched topic.", code: 8 }, NON_CONFORMING_NAMESPACES: { message: "Non conforming namespaces.", code: 9 } }; + function we(e2, t) { + const { message: r, code: i2 } = po[e2]; + return { message: t ? `${r} ${t}` : r, code: i2 }; + } + function $e(e2, t) { + const { message: r, code: i2 } = lo[e2]; + return { message: t ? `${r} ${t}` : r, code: i2 }; + } + function Sr(e2, t) { + return Array.isArray(e2) ? typeof t < "u" && e2.length ? e2.every(t) : true : false; + } + function Gr(e2) { + return Object.getPrototypeOf(e2) === Object.prototype && Object.keys(e2).length; + } + function Oe(e2) { + return typeof e2 > "u"; + } + function Yt(e2, t) { + return t && Oe(e2) ? true : typeof e2 == "string" && !!e2.trim().length; + } + function Wr(e2, t) { + return t && Oe(e2) ? true : typeof e2 == "number" && !isNaN(e2); + } + function Hu(e2, t) { + const { requiredNamespaces: r } = t, i2 = Object.keys(e2.namespaces), n3 = Object.keys(r); + let o2 = true; + return Ie(n3, i2) ? (i2.forEach((h5) => { + const { accounts: p3, methods: b4, events: g3 } = e2.namespaces[h5], w4 = Ze(p3), y4 = r[h5]; + (!Ie(Br(h5, y4), w4) || !Ie(y4.methods, b4) || !Ie(y4.events, g3)) && (o2 = false); + }), o2) : false; + } + function Nr(e2) { + return Yt(e2, false) && e2.includes(":") ? e2.split(":").length === 2 : false; + } + function vo(e2) { + if (Yt(e2, false) && e2.includes(":")) { + const t = e2.split(":"); + if (t.length === 3) { + const r = t[0] + ":" + t[1]; + return !!t[2] && Nr(r); + } + } + return false; + } + function Lu(e2) { + if (Yt(e2, false)) + try { + return typeof new URL(e2) < "u"; + } catch { + return false; + } + return false; + } + function zu(e2) { + var t; + return (t = e2?.proposer) == null ? void 0 : t.publicKey; + } + function ju(e2) { + return e2?.topic; + } + function Vu(e2, t) { + let r = null; + return Yt(e2?.publicKey, false) || (r = we("MISSING_OR_INVALID", `${t} controller public key should be a string`)), r; + } + function en(e2) { + let t = true; + return Sr(e2) ? e2.length && (t = e2.every((r) => Yt(r, false))) : t = false, t; + } + function go(e2, t, r) { + let i2 = null; + return Sr(t) && t.length ? t.forEach((n3) => { + i2 || Nr(n3) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chain ${n3} should be a string and conform to "namespace:chainId" format`)); + }) : Nr(e2) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)), i2; + } + function mo(e2, t, r) { + let i2 = null; + return Object.entries(e2).forEach(([n3, o2]) => { + if (i2) + return; + const h5 = go(n3, Br(n3, o2), `${t} ${r}`); + h5 && (i2 = h5); + }), i2; + } + function Ao(e2, t) { + let r = null; + return Sr(e2) ? e2.forEach((i2) => { + r || vo(i2) || (r = $e("UNSUPPORTED_ACCOUNTS", `${t}, account ${i2} should be a string and conform to "namespace:chainId:address" format`)); + }) : r = $e("UNSUPPORTED_ACCOUNTS", `${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`), r; + } + function bo(e2, t) { + let r = null; + return Object.values(e2).forEach((i2) => { + if (r) + return; + const n3 = Ao(i2?.accounts, `${t} namespace`); + n3 && (r = n3); + }), r; + } + function yo(e2, t) { + let r = null; + return en(e2?.methods) ? en(e2?.events) || (r = $e("UNSUPPORTED_EVENTS", `${t}, events should be an array of strings or empty array for no events`)) : r = $e("UNSUPPORTED_METHODS", `${t}, methods should be an array of strings or empty array for no methods`), r; + } + function rn(e2, t) { + let r = null; + return Object.values(e2).forEach((i2) => { + if (r) + return; + const n3 = yo(i2, `${t}, namespace`); + n3 && (r = n3); + }), r; + } + function Qu(e2, t, r) { + let i2 = null; + if (e2 && Gr(e2)) { + const n3 = rn(e2, t); + n3 && (i2 = n3); + const o2 = mo(e2, t, r); + o2 && (i2 = o2); + } else + i2 = we("MISSING_OR_INVALID", `${t}, ${r} should be an object with data`); + return i2; + } + function wo(e2, t) { + let r = null; + if (e2 && Gr(e2)) { + const i2 = rn(e2, t); + i2 && (r = i2); + const n3 = bo(e2, t); + n3 && (r = n3); + } else + r = we("MISSING_OR_INVALID", `${t}, namespaces should be an object with data`); + return r; + } + function xo(e2) { + return Yt(e2.protocol, true); + } + function Ju(e2, t) { + let r = false; + return t && !e2 ? r = true : e2 && Sr(e2) && e2.length && e2.forEach((i2) => { + r = xo(i2); + }), r; + } + function Yu(e2) { + return typeof e2 == "number"; + } + function Gu(e2) { + return typeof e2 < "u" && typeof e2 !== null; + } + function Wu(e2) { + return !(!e2 || typeof e2 != "object" || !e2.code || !Wr(e2.code, false) || !e2.message || !Yt(e2.message, false)); + } + function Xu(e2) { + return !(Oe(e2) || !Yt(e2.method, false)); + } + function Zu(e2) { + return !(Oe(e2) || Oe(e2.result) && Oe(e2.error) || !Wr(e2.id, false) || !Yt(e2.jsonrpc, false)); + } + function $u(e2) { + return !(Oe(e2) || !Yt(e2.name, false)); + } + function th(e2, t) { + return !(!Nr(t) || !so(e2).includes(t)); + } + function eh(e2, t, r) { + return Yt(r, false) ? ao(e2, t).includes(r) : false; + } + function rh(e2, t, r) { + return Yt(r, false) ? uo(e2, t).includes(r) : false; + } + function Mo(e2, t, r) { + let i2 = null; + const n3 = ih(e2), o2 = nh(t), h5 = Object.keys(n3), p3 = Object.keys(o2), b4 = Eo(Object.keys(e2)), g3 = Eo(Object.keys(t)), w4 = b4.filter((y4) => !g3.includes(y4)); + return w4.length && (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces keys don't satisfy requiredNamespaces. + Required: ${w4.toString()} + Received: ${Object.keys(t).toString()}`)), Ie(h5, p3) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces chains don't satisfy required namespaces. + Required: ${h5.toString()} + Approved: ${p3.toString()}`)), Object.keys(t).forEach((y4) => { + if (!y4.includes(":") || i2) + return; + const S4 = Ze(t[y4].accounts); + S4.includes(y4) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces accounts don't satisfy namespace accounts for ${y4} + Required: ${y4} + Approved: ${S4.toString()}`)); + }), h5.forEach((y4) => { + i2 || (Ie(n3[y4].methods, o2[y4].methods) ? Ie(n3[y4].events, o2[y4].events) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces events don't satisfy namespace events for ${y4}`)) : i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces methods don't satisfy namespace methods for ${y4}`)); + }), i2; + } + function ih(e2) { + const t = {}; + return Object.keys(e2).forEach((r) => { + var i2; + r.includes(":") ? t[r] = e2[r] : (i2 = e2[r].chains) == null || i2.forEach((n3) => { + t[n3] = { methods: e2[r].methods, events: e2[r].events }; + }); + }), t; + } + function Eo(e2) { + return [...new Set(e2.map((t) => t.includes(":") ? t.split(":")[0] : t))]; + } + function nh(e2) { + const t = {}; + return Object.keys(e2).forEach((r) => { + if (r.includes(":")) + t[r] = e2[r]; + else { + const i2 = Ze(e2[r].accounts); + i2?.forEach((n3) => { + t[n3] = { accounts: e2[r].accounts.filter((o2) => o2.includes(`${n3}:`)), methods: e2[r].methods, events: e2[r].events }; + }); + } + }), t; + } + function fh(e2, t) { + return Wr(e2, false) && e2 <= t.max && e2 >= t.min; + } + function oh() { + const e2 = Ge(); + return new Promise((t) => { + switch (e2) { + case Kt.browser: + t(So()); + break; + case Kt.reactNative: + t(No()); + break; + case Kt.node: + t(Io()); + break; + default: + t(true); + } + }); + } + function So() { + return vr() && navigator?.onLine; + } + async function No() { + if (rr() && typeof global < "u" && global != null && global.NetInfo) { + const e2 = await (global == null ? void 0 : global.NetInfo.fetch()); + return e2?.isConnected; + } + return true; + } + function Io() { + return true; + } + function sh(e2) { + switch (Ge()) { + case Kt.browser: + _o(e2); + break; + case Kt.reactNative: + Bo(e2); + break; + case Kt.node: + break; + } + } + function _o(e2) { + !rr() && vr() && (window.addEventListener("online", () => e2(true)), window.addEventListener("offline", () => e2(false))); + } + function Bo(e2) { + rr() && typeof global < "u" && global != null && global.NetInfo && global?.NetInfo.addEventListener((t) => e2(t?.isConnected)); + } + var nn = {}; + var ah = class { + static get(t) { + return nn[t]; + } + static set(t, r) { + nn[t] = r; + } + static delete(t) { + delete nn[t]; + } + }; + exports2.BASE10 = Yi, exports2.BASE16 = zt, exports2.BASE64 = Jr, exports2.COLON = jo, exports2.DEFAULT_DEPTH = pi, exports2.EMPTY_SPACE = Rr, exports2.ENV_MAP = Kt, exports2.INTERNAL_ERRORS = po, exports2.MemoryStore = ah, exports2.ONE_THOUSAND = Vo, exports2.REACT_NATIVE_PRODUCT = An, exports2.RELAYER_DEFAULT_PROTOCOL = Zf, exports2.SDK_ERRORS = lo, exports2.SDK_TYPE = yn, exports2.SLASH = bn, exports2.TYPE_0 = Gi, exports2.TYPE_1 = dr, exports2.UTF8 = Yr, exports2.addResourceToRecap = Vf, exports2.appendToQueryString = wn, exports2.assertType = Xo, exports2.assignAbilityToActions = Vi, exports2.base64Decode = zf, exports2.base64Encode = Lf, exports2.buildApprovedNamespaces = qu, exports2.buildAuthObject = iu, exports2.buildNamespacesFromAuth = Ku, exports2.buildRecapStatement = Jf, exports2.calcExpiry = us, exports2.capitalize = is, exports2.capitalizeWord = In, exports2.createDelayedPromise = ns, exports2.createEncodedRecap = su, exports2.createExpiringPromise = fs, exports2.createRecap = jf, exports2.decodeRecap = Ce, exports2.decodeTypeByte = Er, exports2.decrypt = Au, exports2.deriveSymKey = pu, exports2.deserialize = Zi, exports2.encodeRecap = Vr, exports2.encodeTypeByte = Gf, exports2.encrypt = mu, exports2.engineEvent = cs, exports2.enumify = rs, exports2.formatAccountId = cn, exports2.formatAccountWithChain = Do, exports2.formatChainId = hn, exports2.formatExpirerTarget = gi, exports2.formatIdTarget = ss, exports2.formatMessage = kf, exports2.formatMessageContext = Zo, exports2.formatRelayParams = no, exports2.formatRelayRpcUrl = Go, exports2.formatStatementFromRecap = Ji, exports2.formatTopicTarget = os, exports2.formatUA = En, exports2.formatUri = Ru, exports2.generateKeyPair = lu, exports2.generateRandomBytes32 = du, exports2.getAccountsChains = Ze, exports2.getAccountsFromNamespaces = ko, exports2.getAddressFromAccount = ln, exports2.getAddressesFromAccounts = Uo, exports2.getAppMetadata = Jo, exports2.getBrowserOnlineStatus = So, exports2.getBundleId = Qo, exports2.getChainFromAccount = dn, exports2.getChainsFromAccounts = pn, exports2.getChainsFromNamespace = Br, exports2.getChainsFromNamespaces = qo, exports2.getChainsFromRecap = hu, exports2.getChainsFromRequiredNamespaces = Ko, exports2.getCommonValuesInArrays = mi, exports2.getDecodedRecapFromResources = qf, exports2.getDeepLink = ds, exports2.getDidAddress = ji, exports2.getDidAddressSegments = jr, exports2.getDidChainId = zi, exports2.getEnvironment = Ge, exports2.getHttpUrl = Wo, exports2.getInternalError = we, exports2.getJavascriptID = Mn, exports2.getJavascriptOS = xn, exports2.getLastItems = Nn, exports2.getMethodsFromRecap = uu, exports2.getNamespacedDidChainId = eu, exports2.getNamespacesChains = so, exports2.getNamespacesEventsForChainId = uo, exports2.getNamespacesFromAccounts = co, exports2.getNamespacesMethodsForChainId = ao, exports2.getNodeOnlineStatus = Io, exports2.getReCapActions = Hf, exports2.getReactNativeOnlineStatus = No, exports2.getRecapAbilitiesFromResource = ou, exports2.getRecapFromResources = Qr, exports2.getRecapResource = Kf, exports2.getRelayClientMetadata = Yo, exports2.getRelayProtocolApi = xu, exports2.getRelayProtocolName = wu, exports2.getRequiredNamespacesFromNamespaces = ku, exports2.getSdkError = $e, exports2.getUniqueValues = di, exports2.handleDeeplinkRedirect = ls2, exports2.hasOverlap = Ie, exports2.hashKey = vu, exports2.hashMessage = gu, exports2.isBrowser = vr, exports2.isCaipNamespace = $i, exports2.isConformingNamespaces = Mo, exports2.isExpired = hs, exports2.isNode = vi, exports2.isOnline = oh, exports2.isProposalStruct = zu, exports2.isReactNative = rr, exports2.isRecap = Qi, exports2.isSessionCompatible = Hu, exports2.isSessionStruct = ju, exports2.isTypeOneEnvelope = yu, exports2.isUndefined = Oe, exports2.isValidAccountId = vo, exports2.isValidAccounts = Ao, exports2.isValidActions = yo, exports2.isValidArray = Sr, exports2.isValidChainId = Nr, exports2.isValidChains = go, exports2.isValidController = Vu, exports2.isValidEip1271Signature = Tf, exports2.isValidEip191Signature = Pf, exports2.isValidErrorReason = Wu, exports2.isValidEvent = $u, exports2.isValidId = Yu, exports2.isValidNamespaceAccounts = bo, exports2.isValidNamespaceActions = rn, exports2.isValidNamespaceChains = mo, exports2.isValidNamespaceMethodsOrEvents = en, exports2.isValidNamespaces = wo, exports2.isValidNamespacesChainId = th, exports2.isValidNamespacesEvent = rh, exports2.isValidNamespacesRequest = eh, exports2.isValidNumber = Wr, exports2.isValidObject = Gr, exports2.isValidParams = Gu, exports2.isValidRecap = ve, exports2.isValidRelay = xo, exports2.isValidRelays = Ju, exports2.isValidRequest = Xu, exports2.isValidRequestExpiry = fh, exports2.isValidRequiredNamespaces = Qu, exports2.isValidResponse = Zu, exports2.isValidString = Yt, exports2.isValidUrl = Lu, exports2.mapEntries = es, exports2.mapToObj = $o, exports2.mergeArrays = ge, exports2.mergeEncodedRecaps = au, exports2.mergeRecaps = Qf, exports2.normalizeNamespaces = tn, exports2.objToMap = ts, exports2.parseAccountId = li, exports2.parseChainId = un, exports2.parseContextNames = Sn, exports2.parseExpirerTarget = as, exports2.parseNamespaceKey = ho, exports2.parseRelayParams = ro, exports2.parseTopic = io, exports2.parseUri = Bu, exports2.populateAuthPayload = nu, exports2.recapHasResource = fu, exports2.serialize = Wf, exports2.subscribeToBrowserNetworkChange = _o, exports2.subscribeToNetworkChange = sh, exports2.subscribeToReactNativeNetworkChange = Bo, exports2.validateDecoding = bu, exports2.validateEncoding = Xf, exports2.validateSignedCacao = ru, exports2.verifySignature = Of; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js +var PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, SERVER_ERROR, RESERVED_ERROR_CODES, SERVER_ERROR_CODE_RANGE, STANDARD_ERROR_MAP, DEFAULT_ERROR; +var init_constants2 = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js"() { + init_shim(); + PARSE_ERROR = "PARSE_ERROR"; + INVALID_REQUEST = "INVALID_REQUEST"; + METHOD_NOT_FOUND = "METHOD_NOT_FOUND"; + INVALID_PARAMS = "INVALID_PARAMS"; + INTERNAL_ERROR = "INTERNAL_ERROR"; + SERVER_ERROR = "SERVER_ERROR"; + RESERVED_ERROR_CODES = [-32700, -32600, -32601, -32602, -32603]; + SERVER_ERROR_CODE_RANGE = [-32e3, -32099]; + STANDARD_ERROR_MAP = { + [PARSE_ERROR]: { code: -32700, message: "Parse error" }, + [INVALID_REQUEST]: { code: -32600, message: "Invalid Request" }, + [METHOD_NOT_FOUND]: { code: -32601, message: "Method not found" }, + [INVALID_PARAMS]: { code: -32602, message: "Invalid params" }, + [INTERNAL_ERROR]: { code: -32603, message: "Internal error" }, + [SERVER_ERROR]: { code: -32e3, message: "Server error" } + }; + DEFAULT_ERROR = SERVER_ERROR; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js +function isServerErrorCode(code2) { + return code2 <= SERVER_ERROR_CODE_RANGE[0] && code2 >= SERVER_ERROR_CODE_RANGE[1]; +} +function isReservedErrorCode(code2) { + return RESERVED_ERROR_CODES.includes(code2); +} +function isValidErrorCode(code2) { + return typeof code2 === "number"; +} +function getError(type) { + if (!Object.keys(STANDARD_ERROR_MAP).includes(type)) { + return STANDARD_ERROR_MAP[DEFAULT_ERROR]; + } + return STANDARD_ERROR_MAP[type]; +} +function getErrorByCode(code2) { + const match = Object.values(STANDARD_ERROR_MAP).find((e2) => e2.code === code2); + if (!match) { + return STANDARD_ERROR_MAP[DEFAULT_ERROR]; + } + return match; +} +function validateJsonRpcError(response) { + if (typeof response.error.code === "undefined") { + return { valid: false, error: "Missing code for JSON-RPC error" }; + } + if (typeof response.error.message === "undefined") { + return { valid: false, error: "Missing message for JSON-RPC error" }; + } + if (!isValidErrorCode(response.error.code)) { + return { + valid: false, + error: `Invalid error code type for JSON-RPC: ${response.error.code}` + }; + } + if (isReservedErrorCode(response.error.code)) { + const error = getErrorByCode(response.error.code); + if (error.message !== STANDARD_ERROR_MAP[DEFAULT_ERROR].message && response.error.message === error.message) { + return { + valid: false, + error: `Invalid error code message for JSON-RPC: ${response.error.code}` + }; + } + } + return { valid: true }; +} +function parseConnectionError(e2, url, type) { + return e2.message.includes("getaddrinfo ENOTFOUND") || e2.message.includes("connect ECONNREFUSED") ? new Error(`Unavailable ${type} RPC url at ${url}`) : e2; +} +var init_error = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js"() { + init_shim(); + init_constants2(); + } +}); + +// node_modules/@walletconnect/environment/dist/cjs/crypto.js +var require_crypto2 = __commonJS({ + "node_modules/@walletconnect/environment/dist/cjs/crypto.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isBrowserCryptoAvailable = exports2.getSubtleCrypto = exports2.getBrowerCrypto = void 0; + function getBrowerCrypto() { + return (global === null || global === void 0 ? void 0 : global.crypto) || (global === null || global === void 0 ? void 0 : global.msCrypto) || {}; + } + exports2.getBrowerCrypto = getBrowerCrypto; + function getSubtleCrypto() { + const browserCrypto = getBrowerCrypto(); + return browserCrypto.subtle || browserCrypto.webkitSubtle; + } + exports2.getSubtleCrypto = getSubtleCrypto; + function isBrowserCryptoAvailable() { + return !!getBrowerCrypto() && !!getSubtleCrypto(); + } + exports2.isBrowserCryptoAvailable = isBrowserCryptoAvailable; + } +}); + +// node_modules/@walletconnect/environment/dist/cjs/env.js +var require_env = __commonJS({ + "node_modules/@walletconnect/environment/dist/cjs/env.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.isBrowser = exports2.isNode = exports2.isReactNative = void 0; + function isReactNative() { + return typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative"; + } + exports2.isReactNative = isReactNative; + function isNode2() { + return typeof import_process.default !== "undefined" && typeof import_process.default.versions !== "undefined" && typeof import_process.default.versions.node !== "undefined"; + } + exports2.isNode = isNode2; + function isBrowser() { + return !isReactNative() && !isNode2(); + } + exports2.isBrowser = isBrowser; + } +}); + +// node_modules/@walletconnect/environment/dist/cjs/index.js +var require_cjs5 = __commonJS({ + "node_modules/@walletconnect/environment/dist/cjs/index.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_crypto2(), exports2); + tslib_1.__exportStar(require_env(), exports2); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js +var env_exports = {}; +__export(env_exports, { + isNodeJs: () => isNodeJs +}); +var import_environment, isNodeJs; +var init_env = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js"() { + init_shim(); + import_environment = __toESM(require_cjs5()); + __reExport(env_exports, __toESM(require_cjs5())); + isNodeJs = import_environment.isNode; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js +function payloadId(entropy = 3) { + const date = Date.now() * Math.pow(10, entropy); + const extra = Math.floor(Math.random() * Math.pow(10, entropy)); + return date + extra; +} +function getBigIntRpcId(entropy = 6) { + return BigInt(payloadId(entropy)); +} +function formatJsonRpcRequest(method, params, id) { + return { + id: id || payloadId(), + jsonrpc: "2.0", + method, + params + }; +} +function formatJsonRpcResult(id, result) { + return { + id, + jsonrpc: "2.0", + result + }; +} +function formatJsonRpcError(id, error, data) { + return { + id, + jsonrpc: "2.0", + error: formatErrorMessage(error, data) + }; +} +function formatErrorMessage(error, data) { + if (typeof error === "undefined") { + return getError(INTERNAL_ERROR); + } + if (typeof error === "string") { + error = Object.assign(Object.assign({}, getError(SERVER_ERROR)), { message: error }); + } + if (typeof data !== "undefined") { + error.data = data; + } + if (isReservedErrorCode(error.code)) { + error = getErrorByCode(error.code); + } + return error; +} +var init_format = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js"() { + init_shim(); + init_error(); + init_constants2(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js +function isValidRoute(route) { + if (route.includes("*")) { + return isValidWildcardRoute(route); + } + if (/\W/g.test(route)) { + return false; + } + return true; +} +function isValidDefaultRoute(route) { + return route === "*"; +} +function isValidWildcardRoute(route) { + if (isValidDefaultRoute(route)) { + return true; + } + if (!route.includes("*")) { + return false; + } + if (route.split("*").length !== 2) { + return false; + } + if (route.split("*").filter((x3) => x3.trim() === "").length !== 1) { + return false; + } + return true; +} +function isValidLeadingWildcardRoute(route) { + return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[0].trim(); +} +function isValidTrailingWildcardRoute(route) { + return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[1].trim(); +} +var init_routing = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js +var init_jsonrpc = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js +var IEvents2; +var init_misc = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js"() { + init_shim(); + IEvents2 = class { + }; + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js +var IJsonRpcConnection, IBaseJsonRpcProvider, IJsonRpcProvider; +var init_provider = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js"() { + init_shim(); + init_misc(); + IJsonRpcConnection = class extends IEvents2 { + constructor(opts) { + super(); + } + }; + IBaseJsonRpcProvider = class extends IEvents2 { + constructor() { + super(); + } + }; + IJsonRpcProvider = class extends IBaseJsonRpcProvider { + constructor(connection) { + super(); + } + }; + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js +var init_validator = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js +var init_esm4 = __esm({ + "node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js"() { + init_shim(); + init_jsonrpc(); + init_misc(); + init_provider(); + init_validator(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js +var init_types2 = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js"() { + init_shim(); + init_esm4(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js +function getUrlProtocol(url) { + const matches = url.match(new RegExp(/^\w+:/, "gi")); + if (!matches || !matches.length) + return; + return matches[0]; +} +function matchRegexProtocol(url, regex) { + const protocol = getUrlProtocol(url); + if (typeof protocol === "undefined") + return false; + return new RegExp(regex).test(protocol); +} +function isHttpUrl(url) { + return matchRegexProtocol(url, HTTP_REGEX); +} +function isWsUrl(url) { + return matchRegexProtocol(url, WS_REGEX); +} +function isLocalhostUrl(url) { + return new RegExp("wss?://localhost(:d{2,5})?").test(url); +} +var HTTP_REGEX, WS_REGEX; +var init_url = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js"() { + init_shim(); + HTTP_REGEX = "^https?:"; + WS_REGEX = "^wss?:"; + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js +function isJsonRpcPayload(payload) { + return typeof payload === "object" && "id" in payload && "jsonrpc" in payload && payload.jsonrpc === "2.0"; +} +function isJsonRpcRequest(payload) { + return isJsonRpcPayload(payload) && "method" in payload; +} +function isJsonRpcResponse(payload) { + return isJsonRpcPayload(payload) && (isJsonRpcResult(payload) || isJsonRpcError(payload)); +} +function isJsonRpcResult(payload) { + return "result" in payload; +} +function isJsonRpcError(payload) { + return "error" in payload; +} +function isJsonRpcValidationInvalid(validation) { + return "error" in validation && validation.valid === false; +} +var init_validators = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js"() { + init_shim(); + } +}); + +// node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js +var esm_exports4 = {}; +__export(esm_exports4, { + DEFAULT_ERROR: () => DEFAULT_ERROR, + IBaseJsonRpcProvider: () => IBaseJsonRpcProvider, + IEvents: () => IEvents2, + IJsonRpcConnection: () => IJsonRpcConnection, + IJsonRpcProvider: () => IJsonRpcProvider, + INTERNAL_ERROR: () => INTERNAL_ERROR, + INVALID_PARAMS: () => INVALID_PARAMS, + INVALID_REQUEST: () => INVALID_REQUEST, + METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, + PARSE_ERROR: () => PARSE_ERROR, + RESERVED_ERROR_CODES: () => RESERVED_ERROR_CODES, + SERVER_ERROR: () => SERVER_ERROR, + SERVER_ERROR_CODE_RANGE: () => SERVER_ERROR_CODE_RANGE, + STANDARD_ERROR_MAP: () => STANDARD_ERROR_MAP, + formatErrorMessage: () => formatErrorMessage, + formatJsonRpcError: () => formatJsonRpcError, + formatJsonRpcRequest: () => formatJsonRpcRequest, + formatJsonRpcResult: () => formatJsonRpcResult, + getBigIntRpcId: () => getBigIntRpcId, + getError: () => getError, + getErrorByCode: () => getErrorByCode, + isHttpUrl: () => isHttpUrl, + isJsonRpcError: () => isJsonRpcError, + isJsonRpcPayload: () => isJsonRpcPayload, + isJsonRpcRequest: () => isJsonRpcRequest, + isJsonRpcResponse: () => isJsonRpcResponse, + isJsonRpcResult: () => isJsonRpcResult, + isJsonRpcValidationInvalid: () => isJsonRpcValidationInvalid, + isLocalhostUrl: () => isLocalhostUrl, + isNodeJs: () => isNodeJs, + isReservedErrorCode: () => isReservedErrorCode, + isServerErrorCode: () => isServerErrorCode, + isValidDefaultRoute: () => isValidDefaultRoute, + isValidErrorCode: () => isValidErrorCode, + isValidLeadingWildcardRoute: () => isValidLeadingWildcardRoute, + isValidRoute: () => isValidRoute, + isValidTrailingWildcardRoute: () => isValidTrailingWildcardRoute, + isValidWildcardRoute: () => isValidWildcardRoute, + isWsUrl: () => isWsUrl, + parseConnectionError: () => parseConnectionError, + payloadId: () => payloadId, + validateJsonRpcError: () => validateJsonRpcError +}); +var init_esm5 = __esm({ + "node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js"() { + init_shim(); + init_constants2(); + init_error(); + init_env(); + __reExport(esm_exports4, env_exports); + init_format(); + init_routing(); + init_types2(); + init_url(); + init_validators(); + } +}); + +// node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js +var import_events, JsonRpcProvider, provider_default; +var init_provider2 = __esm({ + "node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js"() { + init_shim(); + import_events = __toESM(require_events()); + init_esm5(); + JsonRpcProvider = class extends IJsonRpcProvider { + constructor(connection) { + super(connection); + this.events = new import_events.EventEmitter(); + this.hasRegisteredEventListeners = false; + this.connection = this.setConnection(connection); + if (this.connection.connected) { + this.registerEventListeners(); + } + } + async connect(connection = this.connection) { + await this.open(connection); + } + async disconnect() { + await this.close(); + } + on(event, listener) { + this.events.on(event, listener); + } + once(event, listener) { + this.events.once(event, listener); + } + off(event, listener) { + this.events.off(event, listener); + } + removeListener(event, listener) { + this.events.removeListener(event, listener); + } + async request(request, context) { + return this.requestStrict(formatJsonRpcRequest(request.method, request.params || [], request.id || getBigIntRpcId().toString()), context); + } + async requestStrict(request, context) { + return new Promise(async (resolve, reject) => { + if (!this.connection.connected) { + try { + await this.open(); + } catch (e2) { + reject(e2); + } + } + this.events.on(`${request.id}`, (response) => { + if (isJsonRpcError(response)) { + reject(response.error); + } else { + resolve(response.result); + } + }); + try { + await this.connection.send(request, context); + } catch (e2) { + reject(e2); + } + }); + } + setConnection(connection = this.connection) { + return connection; + } + onPayload(payload) { + this.events.emit("payload", payload); + if (isJsonRpcResponse(payload)) { + this.events.emit(`${payload.id}`, payload); + } else { + this.events.emit("message", { + type: payload.method, + data: payload.params + }); + } + } + onClose(event) { + if (event && event.code === 3e3) { + this.events.emit("error", new Error(`WebSocket connection closed abnormally with code: ${event.code} ${event.reason ? `(${event.reason})` : ""}`)); + } + this.events.emit("disconnect"); + } + async open(connection = this.connection) { + if (this.connection === connection && this.connection.connected) + return; + if (this.connection.connected) + this.close(); + if (typeof connection === "string") { + await this.connection.open(connection); + connection = this.connection; + } + this.connection = this.setConnection(connection); + await this.connection.open(); + this.registerEventListeners(); + this.events.emit("connect"); + } + async close() { + await this.connection.close(); + } + registerEventListeners() { + if (this.hasRegisteredEventListeners) + return; + this.connection.on("payload", (payload) => this.onPayload(payload)); + this.connection.on("close", (event) => this.onClose(event)); + this.connection.on("error", (error) => this.events.emit("error", error)); + this.connection.on("register_error", (error) => this.onClose()); + this.hasRegisteredEventListeners = true; + } + }; + provider_default = JsonRpcProvider; + } +}); + +// node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js +var esm_exports5 = {}; +__export(esm_exports5, { + JsonRpcProvider: () => JsonRpcProvider, + default: () => esm_default +}); +var esm_default; +var init_esm6 = __esm({ + "node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js"() { + init_shim(); + init_provider2(); + init_provider2(); + esm_default = provider_default; + } +}); + +// node_modules/ws/browser.js +var require_browser5 = __commonJS({ + "node_modules/ws/browser.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function() { + throw new Error( + "ws does not work in the browser. Browser clients must use the native WebSocket object" + ); + }; + } +}); + +// node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js +var index_es_exports4 = {}; +__export(index_es_exports4, { + WsConnection: () => f3, + default: () => f3 +}); +var import_events2, w3, b3, a2, h4, S3, f3; +var init_index_es4 = __esm({ + "node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js"() { + init_shim(); + import_events2 = __toESM(require_events()); + init_esm(); + init_esm5(); + w3 = () => typeof WebSocket < "u" ? WebSocket : typeof global < "u" && typeof global.WebSocket < "u" ? global.WebSocket : typeof window < "u" && typeof window.WebSocket < "u" ? window.WebSocket : typeof self < "u" && typeof self.WebSocket < "u" ? self.WebSocket : require_browser5(); + b3 = () => typeof WebSocket < "u" || typeof global < "u" && typeof global.WebSocket < "u" || typeof window < "u" && typeof window.WebSocket < "u" || typeof self < "u" && typeof self.WebSocket < "u"; + a2 = (c4) => c4.split("?")[0]; + h4 = 10; + S3 = w3(); + f3 = class { + constructor(e2) { + if (this.url = e2, this.events = new import_events2.EventEmitter(), this.registering = false, !isWsUrl(e2)) + throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); + this.url = e2; + } + get connected() { + return typeof this.socket < "u"; + } + get connecting() { + return this.registering; + } + on(e2, t) { + this.events.on(e2, t); + } + once(e2, t) { + this.events.once(e2, t); + } + off(e2, t) { + this.events.off(e2, t); + } + removeListener(e2, t) { + this.events.removeListener(e2, t); + } + async open(e2 = this.url) { + await this.register(e2); + } + async close() { + return new Promise((e2, t) => { + if (typeof this.socket > "u") { + t(new Error("Connection already closed")); + return; + } + this.socket.onclose = (n3) => { + this.onClose(n3), e2(); + }, this.socket.close(); + }); + } + async send(e2) { + typeof this.socket > "u" && (this.socket = await this.register()); + try { + this.socket.send(safeJsonStringify(e2)); + } catch (t) { + this.onError(e2.id, t); + } + } + register(e2 = this.url) { + if (!isWsUrl(e2)) + throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); + if (this.registering) { + const t = this.events.getMaxListeners(); + return (this.events.listenerCount("register_error") >= t || this.events.listenerCount("open") >= t) && this.events.setMaxListeners(t + 1), new Promise((n3, o2) => { + this.events.once("register_error", (s2) => { + this.resetMaxListeners(), o2(s2); + }), this.events.once("open", () => { + if (this.resetMaxListeners(), typeof this.socket > "u") + return o2(new Error("WebSocket connection is missing or invalid")); + n3(this.socket); + }); + }); + } + return this.url = e2, this.registering = true, new Promise((t, n3) => { + const o2 = new URLSearchParams(e2).get("origin"), s2 = (0, esm_exports4.isReactNative)() ? { headers: { origin: o2 } } : { rejectUnauthorized: !isLocalhostUrl(e2) }, i2 = new S3(e2, [], s2); + b3() ? i2.onerror = (r) => { + const l4 = r; + n3(this.emitError(l4.error)); + } : i2.on("error", (r) => { + n3(this.emitError(r)); + }), i2.onopen = () => { + this.onOpen(i2), t(i2); + }; + }); + } + onOpen(e2) { + e2.onmessage = (t) => this.onPayload(t), e2.onclose = (t) => this.onClose(t), this.socket = e2, this.registering = false, this.events.emit("open"); + } + onClose(e2) { + this.socket = void 0, this.registering = false, this.events.emit("close", e2); + } + onPayload(e2) { + if (typeof e2.data > "u") + return; + const t = typeof e2.data == "string" ? safeJsonParse(e2.data) : e2.data; + this.events.emit("payload", t); + } + onError(e2, t) { + const n3 = this.parseError(t), o2 = n3.message || n3.toString(), s2 = formatJsonRpcError(e2, o2); + this.events.emit("payload", s2); + } + parseError(e2, t = this.url) { + return parseConnectionError(e2, a2(t), "WS"); + } + resetMaxListeners() { + this.events.getMaxListeners() > h4 && this.events.setMaxListeners(h4); + } + emitError(e2) { + const t = this.parseError(new Error(e2?.message || `WebSocket connection failed for host: ${a2(this.url)}`)); + return this.events.emit("register_error", t), t; + } + }; + } +}); + +// node_modules/lodash.isequal/index.js +var require_lodash = __commonJS({ + "node_modules/lodash.isequal/index.js"(exports2, module2) { + init_shim(); + var LARGE_ARRAY_SIZE = 200; + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var COMPARE_PARTIAL_FLAG = 1; + var COMPARE_UNORDERED_FLAG = 2; + var MAX_SAFE_INTEGER2 = 9007199254740991; + var argsTag = "[object Arguments]"; + var arrayTag = "[object Array]"; + var asyncTag = "[object AsyncFunction]"; + var boolTag = "[object Boolean]"; + var dateTag = "[object Date]"; + var errorTag = "[object Error]"; + var funcTag = "[object Function]"; + var genTag = "[object GeneratorFunction]"; + var mapTag = "[object Map]"; + var numberTag = "[object Number]"; + var nullTag = "[object Null]"; + var objectTag = "[object Object]"; + var promiseTag = "[object Promise]"; + var proxyTag = "[object Proxy]"; + var regexpTag = "[object RegExp]"; + var setTag = "[object Set]"; + var stringTag = "[object String]"; + var symbolTag = "[object Symbol]"; + var undefinedTag = "[object Undefined]"; + var weakMapTag = "[object WeakMap]"; + var arrayBufferTag = "[object ArrayBuffer]"; + var dataViewTag = "[object DataView]"; + var float32Tag = "[object Float32Array]"; + var float64Tag = "[object Float64Array]"; + var int8Tag = "[object Int8Array]"; + var int16Tag = "[object Int16Array]"; + var int32Tag = "[object Int32Array]"; + var uint8Tag = "[object Uint8Array]"; + var uint8ClampedTag = "[object Uint8ClampedArray]"; + var uint16Tag = "[object Uint16Array]"; + var uint32Tag = "[object Uint32Array]"; + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; + var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding("util"); + } catch (e2) { + } + }(); + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + function arrayFilter(array, predicate) { + var index = -1, length2 = array == null ? 0 : array.length, resIndex = 0, result = []; + while (++index < length2) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + function arrayPush(array, values) { + var index = -1, length2 = values.length, offset = array.length; + while (++index < length2) { + array[offset + index] = values[index]; + } + return array; + } + function arraySome(array, predicate) { + var index = -1, length2 = array == null ? 0 : array.length; + while (++index < length2) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + function baseTimes(n3, iteratee) { + var index = -1, result = Array(n3); + while (++index < n3) { + result[index] = iteratee(index); + } + return result; + } + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + function cacheHas(cache, key) { + return cache.has(key); + } + function getValue(object, key) { + return object == null ? void 0 : object[key]; + } + function mapToArray(map) { + var index = -1, result = Array(map.size); + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + function setToArray(set2) { + var index = -1, result = Array(set2.size); + set2.forEach(function(value) { + result[++index] = value; + }); + return result; + } + var arrayProto = Array.prototype; + var funcProto = Function.prototype; + var objectProto = Object.prototype; + var coreJsData = root["__core-js_shared__"]; + var funcToString = funcProto.toString; + var hasOwnProperty = objectProto.hasOwnProperty; + var maskSrcKey = function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); + return uid ? "Symbol(src)_1." + uid : ""; + }(); + var nativeObjectToString = objectProto.toString; + var reIsNative = RegExp( + "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" + ); + var Buffer2 = moduleExports ? root.Buffer : void 0; + var Symbol2 = root.Symbol; + var Uint8Array2 = root.Uint8Array; + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + var splice = arrayProto.splice; + var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; + var nativeGetSymbols = Object.getOwnPropertySymbols; + var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; + var nativeKeys = overArg(Object.keys, Object); + var DataView2 = getNative(root, "DataView"); + var Map2 = getNative(root, "Map"); + var Promise2 = getNative(root, "Promise"); + var Set2 = getNative(root, "Set"); + var WeakMap2 = getNative(root, "WeakMap"); + var nativeCreate = getNative(Object, "create"); + var dataViewCtorString = toSource(DataView2); + var mapCtorString = toSource(Map2); + var promiseCtorString = toSource(Promise2); + var setCtorString = toSource(Set2); + var weakMapCtorString = toSource(WeakMap2); + var symbolProto = Symbol2 ? Symbol2.prototype : void 0; + var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; + function Hash(entries) { + var index = -1, length2 = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length2) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? void 0 : result; + } + return hasOwnProperty.call(data, key) ? data[key] : void 0; + } + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); + } + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; + return this; + } + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + function ListCache(entries) { + var index = -1, length2 = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length2) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? void 0 : data[index][1]; + } + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + function listCacheSet(key, value) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + function MapCache(entries) { + var index = -1, length2 = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length2) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function mapCacheClear() { + this.size = 0; + this.__data__ = { + "hash": new Hash(), + "map": new (Map2 || ListCache)(), + "string": new Hash() + }; + } + function mapCacheDelete(key) { + var result = getMapData(this, key)["delete"](key); + this.size -= result ? 1 : 0; + return result; + } + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + function mapCacheSet(key, value) { + var data = getMapData(this, key), size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + function SetCache(values) { + var index = -1, length2 = values == null ? 0 : values.length; + this.__data__ = new MapCache(); + while (++index < length2) { + this.add(values[index]); + } + } + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + function setCacheHas(value) { + return this.__data__.has(value); + } + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + function stackClear() { + this.__data__ = new ListCache(); + this.size = 0; + } + function stackDelete(key) { + var data = this.__data__, result = data["delete"](key); + this.size = data.size; + return result; + } + function stackGet(key) { + return this.__data__.get(key); + } + function stackHas(key) { + return this.__data__.has(key); + } + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + Stack.prototype.clear = stackClear; + Stack.prototype["delete"] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length2 = result.length; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. + (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. + isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. + isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. + isIndex(key, length2)))) { + result.push(key); + } + } + return result; + } + function assocIndexOf(array, key) { + var length2 = array.length; + while (length2--) { + if (eq(array[length2][0], key)) { + return length2; + } + } + return -1; + } + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + function baseGetTag(value) { + if (value == null) { + return value === void 0 ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); + } + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack()); + return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new Stack()); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack()); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + function baseIsTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != "constructor") { + result.push(key); + } + } + return result; + } + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0; + stack.set(array, other); + stack.set(other, array); + while (++index < arrLength) { + var arrValue = array[index], othValue = other[index]; + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== void 0) { + if (compared) { + continue; + } + result = false; + break; + } + if (seen) { + if (!arraySome(other, function(othValue2, othIndex) { + if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result = false; + break; + } + } + stack["delete"](array); + stack["delete"](other); + return result; + } + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + object = object.buffer; + other = other.buffer; + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { + return false; + } + return true; + case boolTag: + case dateTag: + case numberTag: + return eq(+object, +other); + case errorTag: + return object.name == other.name && object.message == other.message; + case regexpTag: + case stringTag: + return object == other + ""; + case mapTag: + var convert = mapToArray; + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + if (object.size != other.size && !isPartial) { + return false; + } + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack["delete"](object); + return result; + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], othValue = other[key]; + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } + if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { + result = false; + break; + } + skipCtor || (skipCtor = key == "constructor"); + } + if (result && !skipCtor) { + var objCtor = object.constructor, othCtor = other.constructor; + if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { + result = false; + } + } + stack["delete"](object); + stack["delete"](other); + return result; + } + function getAllKeys(object) { + return baseGetAllKeys(object, keys2, getSymbols); + } + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : void 0; + } + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + try { + value[symToStringTag] = void 0; + var unmasked = true; + } catch (e2) { + } + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + var getTag = baseGetTag; + if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) { + getTag = function(value) { + var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag; + case mapCtorString: + return mapTag; + case promiseCtorString: + return promiseTag; + case setCtorString: + return setTag; + case weakMapCtorString: + return weakMapTag; + } + } + return result; + }; + } + function isIndex(value, length2) { + length2 = length2 == null ? MAX_SAFE_INTEGER2 : length2; + return !!length2 && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length2); + } + function isKeyable(value) { + var type = typeof value; + return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; + } + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; + } + function isPrototype(value) { + var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value === proto; + } + function objectToString(value) { + return nativeObjectToString.call(value); + } + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e2) { + } + try { + return func + ""; + } catch (e2) { + } + } + return ""; + } + function eq(value, other) { + return value === other || value !== value && other !== other; + } + var isArguments = baseIsArguments(/* @__PURE__ */ function() { + return arguments; + }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); + }; + var isArray = Array.isArray; + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + var isBuffer = nativeIsBuffer || stubFalse; + function isEqual(value, other) { + return baseIsEqual(value, other); + } + function isFunction(value) { + if (!isObject(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; + } + function isObject(value) { + var type = typeof value; + return value != null && (type == "object" || type == "function"); + } + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function keys2(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + function stubArray() { + return []; + } + function stubFalse() { + return false; + } + module2.exports = isEqual; + } +}); + +// node_modules/unfetch/dist/unfetch.js +var require_unfetch = __commonJS({ + "node_modules/unfetch/dist/unfetch.js"(exports2, module2) { + init_shim(); + module2.exports = function(e2, n3) { + return n3 = n3 || {}, new Promise(function(t, r) { + var s2 = new XMLHttpRequest(), o2 = [], u3 = [], i2 = {}, a3 = function() { + return { ok: 2 == (s2.status / 100 | 0), statusText: s2.statusText, status: s2.status, url: s2.responseURL, text: function() { + return Promise.resolve(s2.responseText); + }, json: function() { + return Promise.resolve(s2.responseText).then(JSON.parse); + }, blob: function() { + return Promise.resolve(new Blob([s2.response])); + }, clone: a3, headers: { keys: function() { + return o2; + }, entries: function() { + return u3; + }, get: function(e3) { + return i2[e3.toLowerCase()]; + }, has: function(e3) { + return e3.toLowerCase() in i2; + } } }; + }; + for (var l4 in s2.open(n3.method || "get", e2, true), s2.onload = function() { + s2.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function(e3, n4, t2) { + o2.push(n4 = n4.toLowerCase()), u3.push([n4, t2]), i2[n4] = i2[n4] ? i2[n4] + "," + t2 : t2; + }), t(a3()); + }, s2.onerror = r, s2.withCredentials = "include" == n3.credentials, n3.headers) + s2.setRequestHeader(l4, n3.headers[l4]); + s2.send(n3.body || null); + }); + }; + } +}); + +// node_modules/isomorphic-unfetch/browser.js +var require_browser6 = __commonJS({ + "node_modules/isomorphic-unfetch/browser.js"(exports2, module2) { + init_shim(); + module2.exports = self.fetch || (self.fetch = require_unfetch().default || require_unfetch()); + } +}); + +// node_modules/@walletconnect/core/dist/index.cjs.js +var require_index_cjs3 = __commonJS({ + "node_modules/@walletconnect/core/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var z3 = require_events(); + var It = (init_index_es(), __toCommonJS(index_es_exports)); + var $ = require_cjs2(); + var g3 = (init_index_es2(), __toCommonJS(index_es_exports2)); + var x3 = require_index_cjs(); + var oe = (init_esm(), __toCommonJS(esm_exports)); + var Rt = (init_esm3(), __toCommonJS(esm_exports3)); + var a3 = require_index_cjs2(); + var _t = (init_src2(), __toCommonJS(src_exports)); + var l4 = require_cjs(); + var Ct = (init_esm6(), __toCommonJS(esm_exports5)); + var f4 = (init_esm5(), __toCommonJS(esm_exports4)); + var Tt = (init_index_es4(), __toCommonJS(index_es_exports4)); + var St = require_lodash(); + var Ot = require_browser6(); + function k4(n3) { + return n3 && typeof n3 == "object" && "default" in n3 ? n3 : { default: n3 }; + } + function Pt(n3) { + if (n3 && n3.__esModule) + return n3; + var e2 = /* @__PURE__ */ Object.create(null); + return n3 && Object.keys(n3).forEach(function(t) { + if (t !== "default") { + var i2 = Object.getOwnPropertyDescriptor(n3, t); + Object.defineProperty(e2, t, i2.get ? i2 : { enumerable: true, get: function() { + return n3[t]; + } }); + } + }), e2.default = n3, Object.freeze(e2); + } + var At = k4(z3); + var xt = k4(It); + var j2 = Pt(Rt); + var Nt = k4(Tt); + var Lt = k4(St); + var Ut = k4(Ot); + function zt(n3, e2) { + if (n3.length >= 255) + throw new TypeError("Alphabet too long"); + for (var t = new Uint8Array(256), i2 = 0; i2 < t.length; i2++) + t[i2] = 255; + for (var s2 = 0; s2 < n3.length; s2++) { + var r = n3.charAt(s2), o2 = r.charCodeAt(0); + if (t[o2] !== 255) + throw new TypeError(r + " is ambiguous"); + t[o2] = s2; + } + var h5 = n3.length, c4 = n3.charAt(0), u3 = Math.log(h5) / Math.log(256), p3 = Math.log(256) / Math.log(h5); + function D2(d3) { + if (d3 instanceof Uint8Array || (ArrayBuffer.isView(d3) ? d3 = new Uint8Array(d3.buffer, d3.byteOffset, d3.byteLength) : Array.isArray(d3) && (d3 = Uint8Array.from(d3))), !(d3 instanceof Uint8Array)) + throw new TypeError("Expected Uint8Array"); + if (d3.length === 0) + return ""; + for (var y4 = 0, C3 = 0, E4 = 0, O3 = d3.length; E4 !== O3 && d3[E4] === 0; ) + E4++, y4++; + for (var P2 = (O3 - E4) * p3 + 1 >>> 0, v2 = new Uint8Array(P2); E4 !== O3; ) { + for (var A2 = d3[E4], U2 = 0, T2 = P2 - 1; (A2 !== 0 || U2 < C3) && T2 !== -1; T2--, U2++) + A2 += 256 * v2[T2] >>> 0, v2[T2] = A2 % h5 >>> 0, A2 = A2 / h5 >>> 0; + if (A2 !== 0) + throw new Error("Non-zero carry"); + C3 = U2, E4++; + } + for (var N10 = P2 - C3; N10 !== P2 && v2[N10] === 0; ) + N10++; + for (var Y = c4.repeat(y4); N10 < P2; ++N10) + Y += n3.charAt(v2[N10]); + return Y; + } + function b4(d3) { + if (typeof d3 != "string") + throw new TypeError("Expected String"); + if (d3.length === 0) + return new Uint8Array(); + var y4 = 0; + if (d3[y4] !== " ") { + for (var C3 = 0, E4 = 0; d3[y4] === c4; ) + C3++, y4++; + for (var O3 = (d3.length - y4) * u3 + 1 >>> 0, P2 = new Uint8Array(O3); d3[y4]; ) { + var v2 = t[d3.charCodeAt(y4)]; + if (v2 === 255) + return; + for (var A2 = 0, U2 = O3 - 1; (v2 !== 0 || A2 < E4) && U2 !== -1; U2--, A2++) + v2 += h5 * P2[U2] >>> 0, P2[U2] = v2 % 256 >>> 0, v2 = v2 / 256 >>> 0; + if (v2 !== 0) + throw new Error("Non-zero carry"); + E4 = A2, y4++; + } + if (d3[y4] !== " ") { + for (var T2 = O3 - E4; T2 !== O3 && P2[T2] === 0; ) + T2++; + for (var N10 = new Uint8Array(C3 + (O3 - T2)), Y = C3; T2 !== O3; ) + N10[Y++] = P2[T2++]; + return N10; + } + } + } + function F(d3) { + var y4 = b4(d3); + if (y4) + return y4; + throw new Error(`Non-${e2} character`); + } + return { encode: D2, decodeUnsafe: b4, decode: F }; + } + var Ft = zt; + var Mt = Ft; + var ae = (n3) => { + if (n3 instanceof Uint8Array && n3.constructor.name === "Uint8Array") + return n3; + if (n3 instanceof ArrayBuffer) + return new Uint8Array(n3); + if (ArrayBuffer.isView(n3)) + return new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength); + throw new Error("Unknown type, must be binary type"); + }; + var Bt = (n3) => new TextEncoder().encode(n3); + var $t = (n3) => new TextDecoder().decode(n3); + var kt = class { + constructor(e2, t, i2) { + this.name = e2, this.prefix = t, this.baseEncode = i2; + } + encode(e2) { + if (e2 instanceof Uint8Array) + return `${this.prefix}${this.baseEncode(e2)}`; + throw Error("Unknown type, must be binary type"); + } + }; + var Vt = class { + constructor(e2, t, i2) { + if (this.name = e2, this.prefix = t, t.codePointAt(0) === void 0) + throw new Error("Invalid prefix character"); + this.prefixCodePoint = t.codePointAt(0), this.baseDecode = i2; + } + decode(e2) { + if (typeof e2 == "string") { + if (e2.codePointAt(0) !== this.prefixCodePoint) + throw Error(`Unable to decode multibase string ${JSON.stringify(e2)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); + return this.baseDecode(e2.slice(this.prefix.length)); + } else + throw Error("Can only multibase decode strings"); + } + or(e2) { + return he(this, e2); + } + }; + var Kt = class { + constructor(e2) { + this.decoders = e2; + } + or(e2) { + return he(this, e2); + } + decode(e2) { + const t = e2[0], i2 = this.decoders[t]; + if (i2) + return i2.decode(e2); + throw RangeError(`Unable to decode multibase string ${JSON.stringify(e2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + } + }; + var he = (n3, e2) => new Kt({ ...n3.decoders || { [n3.prefix]: n3 }, ...e2.decoders || { [e2.prefix]: e2 } }); + var qt = class { + constructor(e2, t, i2, s2) { + this.name = e2, this.prefix = t, this.baseEncode = i2, this.baseDecode = s2, this.encoder = new kt(e2, t, i2), this.decoder = new Vt(e2, t, s2); + } + encode(e2) { + return this.encoder.encode(e2); + } + decode(e2) { + return this.decoder.decode(e2); + } + }; + var G = ({ name: n3, prefix: e2, encode: t, decode: i2 }) => new qt(n3, e2, t, i2); + var V = ({ prefix: n3, name: e2, alphabet: t }) => { + const { encode: i2, decode: s2 } = Mt(t, e2); + return G({ prefix: n3, name: e2, encode: i2, decode: (r) => ae(s2(r)) }); + }; + var Yt = (n3, e2, t, i2) => { + const s2 = {}; + for (let p3 = 0; p3 < e2.length; ++p3) + s2[e2[p3]] = p3; + let r = n3.length; + for (; n3[r - 1] === "="; ) + --r; + const o2 = new Uint8Array(r * t / 8 | 0); + let h5 = 0, c4 = 0, u3 = 0; + for (let p3 = 0; p3 < r; ++p3) { + const D2 = s2[n3[p3]]; + if (D2 === void 0) + throw new SyntaxError(`Non-${i2} character`); + c4 = c4 << t | D2, h5 += t, h5 >= 8 && (h5 -= 8, o2[u3++] = 255 & c4 >> h5); + } + if (h5 >= t || 255 & c4 << 8 - h5) + throw new SyntaxError("Unexpected end of data"); + return o2; + }; + var jt = (n3, e2, t) => { + const i2 = e2[e2.length - 1] === "=", s2 = (1 << t) - 1; + let r = "", o2 = 0, h5 = 0; + for (let c4 = 0; c4 < n3.length; ++c4) + for (h5 = h5 << 8 | n3[c4], o2 += 8; o2 > t; ) + o2 -= t, r += e2[s2 & h5 >> o2]; + if (o2 && (r += e2[s2 & h5 << t - o2]), i2) + for (; r.length * t & 7; ) + r += "="; + return r; + }; + var m3 = ({ name: n3, prefix: e2, bitsPerChar: t, alphabet: i2 }) => G({ prefix: e2, name: n3, encode(s2) { + return jt(s2, i2, t); + }, decode(s2) { + return Yt(s2, i2, t, n3); + } }); + var Gt = G({ prefix: "\0", name: "identity", encode: (n3) => $t(n3), decode: (n3) => Bt(n3) }); + var Ht = Object.freeze({ __proto__: null, identity: Gt }); + var Xt = m3({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); + var Jt = Object.freeze({ __proto__: null, base2: Xt }); + var Wt = m3({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); + var Qt = Object.freeze({ __proto__: null, base8: Wt }); + var Zt = V({ prefix: "9", name: "base10", alphabet: "0123456789" }); + var ei = Object.freeze({ __proto__: null, base10: Zt }); + var ti = m3({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); + var ii = m3({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); + var si = Object.freeze({ __proto__: null, base16: ti, base16upper: ii }); + var ri = m3({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); + var ni = m3({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); + var oi = m3({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); + var ai = m3({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); + var hi = m3({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); + var ci = m3({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); + var li = m3({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); + var ui = m3({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); + var gi = m3({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); + var di = Object.freeze({ __proto__: null, base32: ri, base32upper: ni, base32pad: oi, base32padupper: ai, base32hex: hi, base32hexupper: ci, base32hexpad: li, base32hexpadupper: ui, base32z: gi }); + var pi = V({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); + var Di = V({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); + var yi = Object.freeze({ __proto__: null, base36: pi, base36upper: Di }); + var Ei = V({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); + var mi = V({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); + var bi = Object.freeze({ __proto__: null, base58btc: Ei, base58flickr: mi }); + var fi = m3({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); + var wi = m3({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); + var vi = m3({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); + var Ii = m3({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); + var Ri = Object.freeze({ __proto__: null, base64: fi, base64pad: wi, base64url: vi, base64urlpad: Ii }); + var ce = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); + var _i = ce.reduce((n3, e2, t) => (n3[t] = e2, n3), []); + var Ci = ce.reduce((n3, e2, t) => (n3[e2.codePointAt(0)] = t, n3), []); + function Ti(n3) { + return n3.reduce((e2, t) => (e2 += _i[t], e2), ""); + } + function Si(n3) { + const e2 = []; + for (const t of n3) { + const i2 = Ci[t.codePointAt(0)]; + if (i2 === void 0) + throw new Error(`Non-base256emoji character: ${t}`); + e2.push(i2); + } + return new Uint8Array(e2); + } + var Oi = G({ prefix: "\u{1F680}", name: "base256emoji", encode: Ti, decode: Si }); + var Pi = Object.freeze({ __proto__: null, base256emoji: Oi }); + var Ai = ue; + var le = 128; + var xi = 127; + var Ni = ~xi; + var Li = Math.pow(2, 31); + function ue(n3, e2, t) { + e2 = e2 || [], t = t || 0; + for (var i2 = t; n3 >= Li; ) + e2[t++] = n3 & 255 | le, n3 /= 128; + for (; n3 & Ni; ) + e2[t++] = n3 & 255 | le, n3 >>>= 7; + return e2[t] = n3 | 0, ue.bytes = t - i2 + 1, e2; + } + var Ui = Q; + var zi = 128; + var ge = 127; + function Q(n3, i2) { + var t = 0, i2 = i2 || 0, s2 = 0, r = i2, o2, h5 = n3.length; + do { + if (r >= h5) + throw Q.bytes = 0, new RangeError("Could not decode varint"); + o2 = n3[r++], t += s2 < 28 ? (o2 & ge) << s2 : (o2 & ge) * Math.pow(2, s2), s2 += 7; + } while (o2 >= zi); + return Q.bytes = r - i2, t; + } + var Fi = Math.pow(2, 7); + var Mi = Math.pow(2, 14); + var Bi = Math.pow(2, 21); + var $i = Math.pow(2, 28); + var ki = Math.pow(2, 35); + var Vi = Math.pow(2, 42); + var Ki = Math.pow(2, 49); + var qi = Math.pow(2, 56); + var Yi = Math.pow(2, 63); + var ji = function(n3) { + return n3 < Fi ? 1 : n3 < Mi ? 2 : n3 < Bi ? 3 : n3 < $i ? 4 : n3 < ki ? 5 : n3 < Vi ? 6 : n3 < Ki ? 7 : n3 < qi ? 8 : n3 < Yi ? 9 : 10; + }; + var Gi = { encode: Ai, decode: Ui, encodingLength: ji }; + var de = Gi; + var pe = (n3, e2, t = 0) => (de.encode(n3, e2, t), e2); + var De = (n3) => de.encodingLength(n3); + var Z = (n3, e2) => { + const t = e2.byteLength, i2 = De(n3), s2 = i2 + De(t), r = new Uint8Array(s2 + t); + return pe(n3, r, 0), pe(t, r, i2), r.set(e2, s2), new Hi(n3, t, e2, r); + }; + var Hi = class { + constructor(e2, t, i2, s2) { + this.code = e2, this.size = t, this.digest = i2, this.bytes = s2; + } + }; + var ye = ({ name: n3, code: e2, encode: t }) => new Xi(n3, e2, t); + var Xi = class { + constructor(e2, t, i2) { + this.name = e2, this.code = t, this.encode = i2; + } + digest(e2) { + if (e2 instanceof Uint8Array) { + const t = this.encode(e2); + return t instanceof Uint8Array ? Z(this.code, t) : t.then((i2) => Z(this.code, i2)); + } else + throw Error("Unknown type, must be binary type"); + } + }; + var Ee = (n3) => async (e2) => new Uint8Array(await crypto.subtle.digest(n3, e2)); + var Ji = ye({ name: "sha2-256", code: 18, encode: Ee("SHA-256") }); + var Wi = ye({ name: "sha2-512", code: 19, encode: Ee("SHA-512") }); + var Qi = Object.freeze({ __proto__: null, sha256: Ji, sha512: Wi }); + var me = 0; + var Zi = "identity"; + var be = ae; + var es = (n3) => Z(me, be(n3)); + var ts = { code: me, name: Zi, encode: be, digest: es }; + var is = Object.freeze({ __proto__: null, identity: ts }); + new TextEncoder(), new TextDecoder(); + var fe = { ...Ht, ...Jt, ...Qt, ...ei, ...si, ...di, ...yi, ...bi, ...Ri, ...Pi }; + ({ ...Qi, ...is }); + function we(n3) { + return globalThis.Buffer != null ? new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength) : n3; + } + function ss(n3 = 0) { + return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? we(globalThis.Buffer.allocUnsafe(n3)) : new Uint8Array(n3); + } + function ve(n3, e2, t, i2) { + return { name: n3, prefix: e2, encoder: { name: n3, prefix: e2, encode: t }, decoder: { decode: i2 } }; + } + var Ie = ve("utf8", "u", (n3) => "u" + new TextDecoder("utf8").decode(n3), (n3) => new TextEncoder().encode(n3.substring(1))); + var ee = ve("ascii", "a", (n3) => { + let e2 = "a"; + for (let t = 0; t < n3.length; t++) + e2 += String.fromCharCode(n3[t]); + return e2; + }, (n3) => { + n3 = n3.substring(1); + const e2 = ss(n3.length); + for (let t = 0; t < n3.length; t++) + e2[t] = n3.charCodeAt(t); + return e2; + }); + var rs = { utf8: Ie, "utf-8": Ie, hex: fe.base16, latin1: ee, ascii: ee, binary: ee, ...fe }; + function ns(n3, e2 = "utf8") { + const t = rs[e2]; + if (!t) + throw new Error(`Unsupported encoding "${e2}"`); + return (e2 === "utf8" || e2 === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? we(globalThis.Buffer.from(n3, "utf-8")) : t.decoder.decode(`${t.prefix}${n3}`); + } + var te = "wc"; + var Re = 2; + var H = "core"; + var L2 = `${te}@2:${H}:`; + var _e = { name: H, logger: "error" }; + var Ce = { database: ":memory:" }; + var Te = "crypto"; + var ie = "client_ed25519_seed"; + var Se = l4.ONE_DAY; + var Oe = "keychain"; + var Pe = "0.3"; + var Ae = "messages"; + var xe = "0.3"; + var Ne = l4.SIX_HOURS; + var Le = "publisher"; + var Ue = "irn"; + var ze = "error"; + var se = "wss://relay.walletconnect.com"; + var re = "wss://relay.walletconnect.org"; + var Fe = "relayer"; + var I2 = { message: "relayer_message", message_ack: "relayer_message_ack", connect: "relayer_connect", disconnect: "relayer_disconnect", error: "relayer_error", connection_stalled: "relayer_connection_stalled", transport_closed: "relayer_transport_closed", publish: "relayer_publish" }; + var Me = "_subscription"; + var w4 = { payload: "payload", connect: "connect", disconnect: "disconnect", error: "error" }; + var Be = l4.ONE_SECOND; + var os = { database: ":memory:" }; + var $e = "2.12.2"; + var ke = 1e4; + var Ve = "0.3"; + var Ke = "WALLETCONNECT_CLIENT_ID"; + var S4 = { created: "subscription_created", deleted: "subscription_deleted", expired: "subscription_expired", disabled: "subscription_disabled", sync: "subscription_sync", resubscribed: "subscription_resubscribed" }; + var as = l4.THIRTY_DAYS; + var qe = "subscription"; + var Ye = "0.3"; + var je = l4.FIVE_SECONDS * 1e3; + var Ge = "pairing"; + var He = "0.3"; + var hs = l4.THIRTY_DAYS; + var M = { wc_pairingDelete: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 1e3 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 1001 } }, wc_pairingPing: { req: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1002 }, res: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1003 } }, unregistered_method: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 0 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 0 } } }; + var K2 = { create: "pairing_create", expire: "pairing_expire", delete: "pairing_delete", ping: "pairing_ping" }; + var R2 = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; + var Xe = "history"; + var Je = "0.3"; + var We = "expirer"; + var _4 = { created: "expirer_created", deleted: "expirer_deleted", expired: "expirer_expired", sync: "expirer_sync" }; + var Qe = "0.3"; + var cs = l4.ONE_DAY; + var X = "verify-api"; + var B2 = "https://verify.walletconnect.com"; + var J = "https://verify.walletconnect.org"; + var Ze = [B2, J]; + var et = "echo"; + var tt = "https://echo.walletconnect.com"; + var it = class { + constructor(e2, t) { + this.core = e2, this.logger = t, this.keychain = /* @__PURE__ */ new Map(), this.name = Oe, this.version = Pe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { + if (!this.initialized) { + const i2 = await this.getKeyChain(); + typeof i2 < "u" && (this.keychain = i2), this.initialized = true; + } + }, this.has = (i2) => (this.isInitialized(), this.keychain.has(i2)), this.set = async (i2, s2) => { + this.isInitialized(), this.keychain.set(i2, s2), await this.persist(); + }, this.get = (i2) => { + this.isInitialized(); + const s2 = this.keychain.get(i2); + if (typeof s2 > "u") { + const { message: r } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${i2}`); + throw new Error(r); + } + return s2; + }, this.del = async (i2) => { + this.isInitialized(), this.keychain.delete(i2), await this.persist(); + }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + async setKeyChain(e2) { + await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); + } + async getKeyChain() { + const e2 = await this.core.storage.getItem(this.storageKey); + return typeof e2 < "u" ? a3.objToMap(e2) : void 0; + } + async persist() { + await this.setKeyChain(this.keychain); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var st = class { + constructor(e2, t, i2) { + this.core = e2, this.logger = t, this.name = Te, this.initialized = false, this.init = async () => { + this.initialized || (await this.keychain.init(), this.initialized = true); + }, this.hasKeys = (s2) => (this.isInitialized(), this.keychain.has(s2)), this.getClientId = async () => { + this.isInitialized(); + const s2 = await this.getClientSeed(), r = j2.generateKeyPair(s2); + return j2.encodeIss(r.publicKey); + }, this.generateKeyPair = () => { + this.isInitialized(); + const s2 = a3.generateKeyPair(); + return this.setPrivateKey(s2.publicKey, s2.privateKey); + }, this.signJWT = async (s2) => { + this.isInitialized(); + const r = await this.getClientSeed(), o2 = j2.generateKeyPair(r), h5 = a3.generateRandomBytes32(), c4 = Se; + return await j2.signJWT(h5, s2, c4, o2); + }, this.generateSharedKey = (s2, r, o2) => { + this.isInitialized(); + const h5 = this.getPrivateKey(s2), c4 = a3.deriveSymKey(h5, r); + return this.setSymKey(c4, o2); + }, this.setSymKey = async (s2, r) => { + this.isInitialized(); + const o2 = r || a3.hashKey(s2); + return await this.keychain.set(o2, s2), o2; + }, this.deleteKeyPair = async (s2) => { + this.isInitialized(), await this.keychain.del(s2); + }, this.deleteSymKey = async (s2) => { + this.isInitialized(), await this.keychain.del(s2); + }, this.encode = async (s2, r, o2) => { + this.isInitialized(); + const h5 = a3.validateEncoding(o2), c4 = oe.safeJsonStringify(r); + if (a3.isTypeOneEnvelope(h5)) { + const b4 = h5.senderPublicKey, F = h5.receiverPublicKey; + s2 = await this.generateSharedKey(b4, F); + } + const u3 = this.getSymKey(s2), { type: p3, senderPublicKey: D2 } = h5; + return a3.encrypt({ type: p3, symKey: u3, message: c4, senderPublicKey: D2 }); + }, this.decode = async (s2, r, o2) => { + this.isInitialized(); + const h5 = a3.validateDecoding(r, o2); + if (a3.isTypeOneEnvelope(h5)) { + const c4 = h5.receiverPublicKey, u3 = h5.senderPublicKey; + s2 = await this.generateSharedKey(c4, u3); + } + try { + const c4 = this.getSymKey(s2), u3 = a3.decrypt({ symKey: c4, encoded: r }); + return oe.safeJsonParse(u3); + } catch (c4) { + this.logger.error(`Failed to decode message from topic: '${s2}', clientId: '${await this.getClientId()}'`), this.logger.error(c4); + } + }, this.getPayloadType = (s2) => { + const r = a3.deserialize(s2); + return a3.decodeTypeByte(r.type); + }, this.getPayloadSenderPublicKey = (s2) => { + const r = a3.deserialize(s2); + return r.senderPublicKey ? _t.toString(r.senderPublicKey, a3.BASE16) : void 0; + }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.keychain = i2 || new it(this.core, this.logger); + } + get context() { + return g3.getLoggerContext(this.logger); + } + async setPrivateKey(e2, t) { + return await this.keychain.set(e2, t), e2; + } + getPrivateKey(e2) { + return this.keychain.get(e2); + } + async getClientSeed() { + let e2 = ""; + try { + e2 = this.keychain.get(ie); + } catch { + e2 = a3.generateRandomBytes32(), await this.keychain.set(ie, e2); + } + return ns(e2, "base16"); + } + getSymKey(e2) { + return this.keychain.get(e2); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var rt = class extends x3.IMessageTracker { + constructor(e2, t) { + super(e2, t), this.logger = e2, this.core = t, this.messages = /* @__PURE__ */ new Map(), this.name = Ae, this.version = xe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { + if (!this.initialized) { + this.logger.trace("Initialized"); + try { + const i2 = await this.getRelayerMessages(); + typeof i2 < "u" && (this.messages = i2), this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", size: this.messages.size }); + } catch (i2) { + this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(i2); + } finally { + this.initialized = true; + } + } + }, this.set = async (i2, s2) => { + this.isInitialized(); + const r = a3.hashMessage(s2); + let o2 = this.messages.get(i2); + return typeof o2 > "u" && (o2 = {}), typeof o2[r] < "u" || (o2[r] = s2, this.messages.set(i2, o2), await this.persist()), r; + }, this.get = (i2) => { + this.isInitialized(); + let s2 = this.messages.get(i2); + return typeof s2 > "u" && (s2 = {}), s2; + }, this.has = (i2, s2) => { + this.isInitialized(); + const r = this.get(i2), o2 = a3.hashMessage(s2); + return typeof r[o2] < "u"; + }, this.del = async (i2) => { + this.isInitialized(), this.messages.delete(i2), await this.persist(); + }, this.logger = g3.generateChildLogger(e2, this.name), this.core = t; + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + async setRelayerMessages(e2) { + await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); + } + async getRelayerMessages() { + const e2 = await this.core.storage.getItem(this.storageKey); + return typeof e2 < "u" ? a3.objToMap(e2) : void 0; + } + async persist() { + await this.setRelayerMessages(this.messages); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var ls2 = class extends x3.IPublisher { + constructor(e2, t) { + super(e2, t), this.relayer = e2, this.logger = t, this.events = new z3.EventEmitter(), this.name = Le, this.queue = /* @__PURE__ */ new Map(), this.publishTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.failedPublishTimeout = l4.toMiliseconds(l4.ONE_SECOND), this.needsTransportRestart = false, this.publish = async (i2, s2, r) => { + var o2; + this.logger.debug("Publishing Payload"), this.logger.trace({ type: "method", method: "publish", params: { topic: i2, message: s2, opts: r } }); + const h5 = r?.ttl || Ne, c4 = a3.getRelayProtocolName(r), u3 = r?.prompt || false, p3 = r?.tag || 0, D2 = r?.id || f4.getBigIntRpcId().toString(), b4 = { topic: i2, message: s2, opts: { ttl: h5, relay: c4, prompt: u3, tag: p3, id: D2 } }, F = `Failed to publish payload, please try again. id:${D2} tag:${p3}`, d3 = Date.now(); + let y4, C3 = 1; + try { + for (; y4 === void 0; ) { + if (Date.now() - d3 > this.publishTimeout) + throw new Error(F); + this.logger.trace({ id: D2, attempts: C3 }, `publisher.publish - attempt ${C3}`), y4 = await await a3.createExpiringPromise(this.rpcPublish(i2, s2, h5, c4, u3, p3, D2).catch((E4) => this.logger.warn(E4)), this.publishTimeout, F), C3++, y4 || await new Promise((E4) => setTimeout(E4, this.failedPublishTimeout)); + } + this.relayer.events.emit(I2.publish, b4), this.logger.debug("Successfully Published Payload"), this.logger.trace({ type: "method", method: "publish", params: { id: D2, topic: i2, message: s2, opts: r } }); + } catch (E4) { + if (this.logger.debug("Failed to Publish Payload"), this.logger.error(E4), (o2 = r?.internal) != null && o2.throwOnFailedPublish) + throw E4; + this.queue.set(D2, b4); + } + }, this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.registerEventListeners(); + } + get context() { + return g3.getLoggerContext(this.logger); + } + rpcPublish(e2, t, i2, s2, r, o2, h5) { + var c4, u3, p3, D2; + const b4 = { method: a3.getRelayProtocolApi(s2.protocol).publish, params: { topic: e2, message: t, ttl: i2, prompt: r, tag: o2 }, id: h5 }; + return a3.isUndefined((c4 = b4.params) == null ? void 0 : c4.prompt) && ((u3 = b4.params) == null || delete u3.prompt), a3.isUndefined((p3 = b4.params) == null ? void 0 : p3.tag) && ((D2 = b4.params) == null || delete D2.tag), this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "message", direction: "outgoing", request: b4 }), this.relayer.request(b4); + } + removeRequestFromQueue(e2) { + this.queue.delete(e2); + } + checkQueue() { + this.queue.forEach(async (e2) => { + const { topic: t, message: i2, opts: s2 } = e2; + await this.publish(t, i2, s2); + }); + } + registerEventListeners() { + this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { + if (this.needsTransportRestart) { + this.needsTransportRestart = false, this.relayer.events.emit(I2.connection_stalled); + return; + } + this.checkQueue(); + }), this.relayer.on(I2.message_ack, (e2) => { + this.removeRequestFromQueue(e2.id.toString()); + }); + } + }; + var us = class { + constructor() { + this.map = /* @__PURE__ */ new Map(), this.set = (e2, t) => { + const i2 = this.get(e2); + this.exists(e2, t) || this.map.set(e2, [...i2, t]); + }, this.get = (e2) => this.map.get(e2) || [], this.exists = (e2, t) => this.get(e2).includes(t), this.delete = (e2, t) => { + if (typeof t > "u") { + this.map.delete(e2); + return; + } + if (!this.map.has(e2)) + return; + const i2 = this.get(e2); + if (!this.exists(e2, t)) + return; + const s2 = i2.filter((r) => r !== t); + if (!s2.length) { + this.map.delete(e2); + return; + } + this.map.set(e2, s2); + }, this.clear = () => { + this.map.clear(); + }; + } + get topics() { + return Array.from(this.map.keys()); + } + }; + var gs = Object.defineProperty; + var ds = Object.defineProperties; + var ps = Object.getOwnPropertyDescriptors; + var nt = Object.getOwnPropertySymbols; + var Ds = Object.prototype.hasOwnProperty; + var ys = Object.prototype.propertyIsEnumerable; + var ot = (n3, e2, t) => e2 in n3 ? gs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var q2 = (n3, e2) => { + for (var t in e2 || (e2 = {})) + Ds.call(e2, t) && ot(n3, t, e2[t]); + if (nt) + for (var t of nt(e2)) + ys.call(e2, t) && ot(n3, t, e2[t]); + return n3; + }; + var ne = (n3, e2) => ds(n3, ps(e2)); + var at = class extends x3.ISubscriber { + constructor(e2, t) { + super(e2, t), this.relayer = e2, this.logger = t, this.subscriptions = /* @__PURE__ */ new Map(), this.topicMap = new us(), this.events = new z3.EventEmitter(), this.name = qe, this.version = Ye, this.pending = /* @__PURE__ */ new Map(), this.cached = [], this.initialized = false, this.pendingSubscriptionWatchLabel = "pending_sub_watch_label", this.pollingInterval = 20, this.storagePrefix = L2, this.subscribeTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.restartInProgress = false, this.batchSubscribeTopicsLimit = 500, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), this.registerEventListeners(), this.clientId = await this.relayer.core.crypto.getClientId()); + }, this.subscribe = async (i2, s2) => { + await this.restartToComplete(), this.isInitialized(), this.logger.debug("Subscribing Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } }); + try { + const r = a3.getRelayProtocolName(s2), o2 = { topic: i2, relay: r }; + this.pending.set(i2, o2); + const h5 = await this.rpcSubscribe(i2, r); + return typeof h5 == "string" && (this.onSubscribe(h5, o2), this.logger.debug("Successfully Subscribed Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } })), h5; + } catch (r) { + throw this.logger.debug("Failed to Subscribe Topic"), this.logger.error(r), r; + } + }, this.unsubscribe = async (i2, s2) => { + await this.restartToComplete(), this.isInitialized(), typeof s2?.id < "u" ? await this.unsubscribeById(i2, s2.id, s2) : await this.unsubscribeByTopic(i2, s2); + }, this.isSubscribed = async (i2) => { + if (this.topics.includes(i2)) + return true; + const s2 = `${this.pendingSubscriptionWatchLabel}_${i2}`; + return await new Promise((r, o2) => { + const h5 = new l4.Watch(); + h5.start(s2); + const c4 = setInterval(() => { + !this.pending.has(i2) && this.topics.includes(i2) && (clearInterval(c4), h5.stop(s2), r(true)), h5.elapsed(s2) >= je && (clearInterval(c4), h5.stop(s2), o2(new Error("Subscription resolution timeout"))); + }, this.pollingInterval); + }).catch(() => false); + }, this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.start = async () => { + await this.onConnect(); + }, this.stop = async () => { + await this.onDisconnect(); + }, this.restart = async () => { + this.restartInProgress = true, await this.restore(), await this.reset(), this.restartInProgress = false; + }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.clientId = ""; + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.relayer.core.customStoragePrefix + "//" + this.name; + } + get length() { + return this.subscriptions.size; + } + get ids() { + return Array.from(this.subscriptions.keys()); + } + get values() { + return Array.from(this.subscriptions.values()); + } + get topics() { + return this.topicMap.topics; + } + hasSubscription(e2, t) { + let i2 = false; + try { + i2 = this.getSubscription(e2).topic === t; + } catch { + } + return i2; + } + onEnable() { + this.cached = [], this.initialized = true; + } + onDisable() { + this.cached = this.values, this.subscriptions.clear(), this.topicMap.clear(); + } + async unsubscribeByTopic(e2, t) { + const i2 = this.topicMap.get(e2); + await Promise.all(i2.map(async (s2) => await this.unsubscribeById(e2, s2, t))); + } + async unsubscribeById(e2, t, i2) { + this.logger.debug("Unsubscribing Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); + try { + const s2 = a3.getRelayProtocolName(i2); + await this.rpcUnsubscribe(e2, t, s2); + const r = a3.getSdkError("USER_DISCONNECTED", `${this.name}, ${e2}`); + await this.onUnsubscribe(e2, t, r), this.logger.debug("Successfully Unsubscribed Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); + } catch (s2) { + throw this.logger.debug("Failed to Unsubscribe Topic"), this.logger.error(s2), s2; + } + } + async rpcSubscribe(e2, t) { + const i2 = { method: a3.getRelayProtocolApi(t.protocol).subscribe, params: { topic: e2 } }; + this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); + try { + return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout) ? a3.hashMessage(e2 + this.clientId) : null; + } catch { + this.logger.debug("Outgoing Relay Subscribe Payload stalled"), this.relayer.events.emit(I2.connection_stalled); + } + return null; + } + async rpcBatchSubscribe(e2) { + if (!e2.length) + return; + const t = e2[0].relay, i2 = { method: a3.getRelayProtocolApi(t.protocol).batchSubscribe, params: { topics: e2.map((s2) => s2.topic) } }; + this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); + try { + return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout); + } catch { + this.relayer.events.emit(I2.connection_stalled); + } + } + rpcUnsubscribe(e2, t, i2) { + const s2 = { method: a3.getRelayProtocolApi(i2.protocol).unsubscribe, params: { topic: e2, id: t } }; + return this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s2 }), this.relayer.request(s2); + } + onSubscribe(e2, t) { + this.setSubscription(e2, ne(q2({}, t), { id: e2 })), this.pending.delete(t.topic); + } + onBatchSubscribe(e2) { + e2.length && e2.forEach((t) => { + this.setSubscription(t.id, q2({}, t)), this.pending.delete(t.topic); + }); + } + async onUnsubscribe(e2, t, i2) { + this.events.removeAllListeners(t), this.hasSubscription(t, e2) && this.deleteSubscription(t, i2), await this.relayer.messages.del(e2); + } + async setRelayerSubscriptions(e2) { + await this.relayer.core.storage.setItem(this.storageKey, e2); + } + async getRelayerSubscriptions() { + return await this.relayer.core.storage.getItem(this.storageKey); + } + setSubscription(e2, t) { + this.logger.debug("Setting subscription"), this.logger.trace({ type: "method", method: "setSubscription", id: e2, subscription: t }), this.addSubscription(e2, t); + } + addSubscription(e2, t) { + this.subscriptions.set(e2, q2({}, t)), this.topicMap.set(t.topic, e2), this.events.emit(S4.created, t); + } + getSubscription(e2) { + this.logger.debug("Getting subscription"), this.logger.trace({ type: "method", method: "getSubscription", id: e2 }); + const t = this.subscriptions.get(e2); + if (!t) { + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw new Error(i2); + } + return t; + } + deleteSubscription(e2, t) { + this.logger.debug("Deleting subscription"), this.logger.trace({ type: "method", method: "deleteSubscription", id: e2, reason: t }); + const i2 = this.getSubscription(e2); + this.subscriptions.delete(e2), this.topicMap.delete(i2.topic, e2), this.events.emit(S4.deleted, ne(q2({}, i2), { reason: t })); + } + async persist() { + await this.setRelayerSubscriptions(this.values), this.events.emit(S4.sync); + } + async reset() { + if (this.cached.length) { + const e2 = Math.ceil(this.cached.length / this.batchSubscribeTopicsLimit); + for (let t = 0; t < e2; t++) { + const i2 = this.cached.splice(0, this.batchSubscribeTopicsLimit); + await this.batchSubscribe(i2); + } + } + this.events.emit(S4.resubscribed); + } + async restore() { + try { + const e2 = await this.getRelayerSubscriptions(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.subscriptions.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored subscriptions for ${this.name}`), this.logger.trace({ type: "method", method: "restore", subscriptions: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore subscriptions for ${this.name}`), this.logger.error(e2); + } + } + async batchSubscribe(e2) { + if (!e2.length) + return; + const t = await this.rpcBatchSubscribe(e2); + a3.isValidArray(t) && this.onBatchSubscribe(t.map((i2, s2) => ne(q2({}, e2[s2]), { id: i2 }))); + } + async onConnect() { + await this.restart(), this.onEnable(); + } + onDisconnect() { + this.onDisable(); + } + async checkPending() { + if (!this.initialized || !this.relayer.connected) + return; + const e2 = []; + this.pending.forEach((t) => { + e2.push(t); + }), await this.batchSubscribe(e2); + } + registerEventListeners() { + this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, async () => { + await this.checkPending(); + }), this.events.on(S4.created, async (e2) => { + const t = S4.created; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); + }), this.events.on(S4.deleted, async (e2) => { + const t = S4.deleted; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); + }); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + async restartToComplete() { + this.restartInProgress && await new Promise((e2) => { + const t = setInterval(() => { + this.restartInProgress || (clearInterval(t), e2()); + }, this.pollingInterval); + }); + } + }; + var Es = Object.defineProperty; + var ht = Object.getOwnPropertySymbols; + var ms = Object.prototype.hasOwnProperty; + var bs = Object.prototype.propertyIsEnumerable; + var ct = (n3, e2, t) => e2 in n3 ? Es(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var fs = (n3, e2) => { + for (var t in e2 || (e2 = {})) + ms.call(e2, t) && ct(n3, t, e2[t]); + if (ht) + for (var t of ht(e2)) + bs.call(e2, t) && ct(n3, t, e2[t]); + return n3; + }; + var lt = class extends x3.IRelayer { + constructor(e2) { + super(e2), this.protocol = "wc", this.version = 2, this.events = new z3.EventEmitter(), this.name = Fe, this.transportExplicitlyClosed = false, this.initialized = false, this.connectionAttemptInProgress = false, this.connectionStatusPollingInterval = 20, this.staleConnectionErrors = ["socket hang up", "socket stalled", "interrupted"], this.hasExperiencedNetworkDisruption = false, this.requestsInFlight = /* @__PURE__ */ new Map(), this.heartBeatTimeout = l4.toMiliseconds(l4.THIRTY_SECONDS + l4.ONE_SECOND), this.request = async (t) => { + var i2, s2; + this.logger.debug("Publishing Request Payload"); + const r = t.id || f4.getBigIntRpcId().toString(); + await this.toEstablishConnection(); + try { + const o2 = this.provider.request(t); + this.requestsInFlight.set(r, { promise: o2, request: t }), this.logger.trace({ id: r, method: t.method, topic: (i2 = t.params) == null ? void 0 : i2.topic }, "relayer.request - attempt to publish..."); + const h5 = await new Promise(async (c4, u3) => { + const p3 = () => { + u3(new Error(`relayer.request - publish interrupted, id: ${r}`)); + }; + this.provider.on(w4.disconnect, p3); + const D2 = await o2; + this.provider.off(w4.disconnect, p3), c4(D2); + }); + return this.logger.trace({ id: r, method: t.method, topic: (s2 = t.params) == null ? void 0 : s2.topic }, "relayer.request - published"), h5; + } catch (o2) { + throw this.logger.debug(`Failed to Publish Request: ${r}`), o2; + } finally { + this.requestsInFlight.delete(r); + } + }, this.resetPingTimeout = () => { + if (a3.isNode()) + try { + clearTimeout(this.pingTimeout), this.pingTimeout = setTimeout(() => { + var t, i2, s2; + (s2 = (i2 = (t = this.provider) == null ? void 0 : t.connection) == null ? void 0 : i2.socket) == null || s2.terminate(); + }, this.heartBeatTimeout); + } catch (t) { + this.logger.warn(t); + } + }, this.onPayloadHandler = (t) => { + this.onProviderPayload(t), this.resetPingTimeout(); + }, this.onConnectHandler = () => { + this.startPingTimeout(), this.events.emit(I2.connect); + }, this.onDisconnectHandler = () => { + this.onProviderDisconnect(); + }, this.onProviderErrorHandler = (t) => { + this.logger.error(t), this.events.emit(I2.error, t), this.logger.info("Fatal socket error received, closing transport"), this.transportClose(); + }, this.registerProviderListeners = () => { + this.provider.on(w4.payload, this.onPayloadHandler), this.provider.on(w4.connect, this.onConnectHandler), this.provider.on(w4.disconnect, this.onDisconnectHandler), this.provider.on(w4.error, this.onProviderErrorHandler); + }, this.core = e2.core, this.logger = typeof e2.logger < "u" && typeof e2.logger != "string" ? g3.generateChildLogger(e2.logger, this.name) : g3.pino(g3.getDefaultLoggerOptions({ level: e2.logger || ze })), this.messages = new rt(this.logger, e2.core), this.subscriber = new at(this, this.logger), this.publisher = new ls2(this, this.logger), this.relayUrl = e2?.relayUrl || se, this.projectId = e2.projectId, this.bundleId = a3.getBundleId(), this.provider = {}; + } + async init() { + this.logger.trace("Initialized"), this.registerEventListeners(), await this.createProvider(), await Promise.all([this.messages.init(), this.subscriber.init()]); + try { + await this.transportOpen(); + } catch { + this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${re}...`), await this.restartTransport(re); + } + this.initialized = true, setTimeout(async () => { + this.subscriber.topics.length === 0 && this.subscriber.pending.size === 0 && (this.logger.info("No topics subscribed to after init, closing transport"), await this.transportClose(), this.transportExplicitlyClosed = false); + }, ke); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get connected() { + var e2, t, i2; + return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 1; + } + get connecting() { + var e2, t, i2; + return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 0; + } + async publish(e2, t, i2) { + this.isInitialized(), await this.publisher.publish(e2, t, i2), await this.recordMessageEvent({ topic: e2, message: t, publishedAt: Date.now() }); + } + async subscribe(e2, t) { + var i2; + this.isInitialized(); + let s2 = ((i2 = this.subscriber.topicMap.get(e2)) == null ? void 0 : i2[0]) || "", r; + const o2 = (h5) => { + h5.topic === e2 && (this.subscriber.off(S4.created, o2), r()); + }; + return await Promise.all([new Promise((h5) => { + r = h5, this.subscriber.on(S4.created, o2); + }), new Promise(async (h5) => { + s2 = await this.subscriber.subscribe(e2, t) || s2, h5(); + })]), s2; + } + async unsubscribe(e2, t) { + this.isInitialized(), await this.subscriber.unsubscribe(e2, t); + } + on(e2, t) { + this.events.on(e2, t); + } + once(e2, t) { + this.events.once(e2, t); + } + off(e2, t) { + this.events.off(e2, t); + } + removeListener(e2, t) { + this.events.removeListener(e2, t); + } + async transportDisconnect() { + if (!this.hasExperiencedNetworkDisruption && this.connected && this.requestsInFlight.size > 0) + try { + await Promise.all(Array.from(this.requestsInFlight.values()).map((e2) => e2.promise)); + } catch (e2) { + this.logger.warn(e2); + } + this.hasExperiencedNetworkDisruption || this.connected ? await a3.createExpiringPromise(this.provider.disconnect(), 2e3, "provider.disconnect()").catch(() => this.onProviderDisconnect()) : this.onProviderDisconnect(); + } + async transportClose() { + this.transportExplicitlyClosed = true, await this.transportDisconnect(); + } + async transportOpen(e2) { + await this.confirmOnlineStateOrThrow(), e2 && e2 !== this.relayUrl && (this.relayUrl = e2, await this.transportDisconnect(), await this.createProvider()), this.connectionAttemptInProgress = true, this.transportExplicitlyClosed = false; + try { + await new Promise(async (t, i2) => { + const s2 = () => { + this.provider.off(w4.disconnect, s2), i2(new Error("Connection interrupted while trying to subscribe")); + }; + this.provider.on(w4.disconnect, s2), await a3.createExpiringPromise(this.provider.connect(), l4.toMiliseconds(l4.ONE_MINUTE), `Socket stalled when trying to connect to ${this.relayUrl}`).catch((r) => { + i2(r); + }), await this.subscriber.start(), this.hasExperiencedNetworkDisruption = false, t(); + }); + } catch (t) { + this.logger.error(t); + const i2 = t; + if (!this.isConnectionStalled(i2.message)) + throw t; + } finally { + this.connectionAttemptInProgress = false; + } + } + async restartTransport(e2) { + this.connectionAttemptInProgress || (this.relayUrl = e2 || this.relayUrl, await this.confirmOnlineStateOrThrow(), await this.transportClose(), await this.createProvider(), await this.transportOpen()); + } + async confirmOnlineStateOrThrow() { + if (!await a3.isOnline()) + throw new Error("No internet connection detected. Please restart your network and try again."); + } + startPingTimeout() { + var e2, t, i2, s2, r; + if (a3.isNode()) + try { + (t = (e2 = this.provider) == null ? void 0 : e2.connection) != null && t.socket && ((r = (s2 = (i2 = this.provider) == null ? void 0 : i2.connection) == null ? void 0 : s2.socket) == null || r.once("ping", () => { + this.resetPingTimeout(); + })), this.resetPingTimeout(); + } catch (o2) { + this.logger.warn(o2); + } + } + isConnectionStalled(e2) { + return this.staleConnectionErrors.some((t) => e2.includes(t)); + } + async createProvider() { + this.provider.connection && this.unregisterProviderListeners(); + const e2 = await this.core.crypto.signJWT(this.relayUrl); + this.provider = new Ct.JsonRpcProvider(new Nt.default(a3.formatRelayRpcUrl({ sdkVersion: $e, protocol: this.protocol, version: this.version, relayUrl: this.relayUrl, projectId: this.projectId, auth: e2, useOnCloseEvent: true, bundleId: this.bundleId }))), this.registerProviderListeners(); + } + async recordMessageEvent(e2) { + const { topic: t, message: i2 } = e2; + await this.messages.set(t, i2); + } + async shouldIgnoreMessageEvent(e2) { + const { topic: t, message: i2 } = e2; + if (!i2 || i2.length === 0) + return this.logger.debug(`Ignoring invalid/empty message: ${i2}`), true; + if (!await this.subscriber.isSubscribed(t)) + return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`), true; + const s2 = this.messages.has(t, i2); + return s2 && this.logger.debug(`Ignoring duplicate message: ${i2}`), s2; + } + async onProviderPayload(e2) { + if (this.logger.debug("Incoming Relay Payload"), this.logger.trace({ type: "payload", direction: "incoming", payload: e2 }), f4.isJsonRpcRequest(e2)) { + if (!e2.method.endsWith(Me)) + return; + const t = e2.params, { topic: i2, message: s2, publishedAt: r } = t.data, o2 = { topic: i2, message: s2, publishedAt: r }; + this.logger.debug("Emitting Relayer Payload"), this.logger.trace(fs({ type: "event", event: t.id }, o2)), this.events.emit(t.id, o2), await this.acknowledgePayload(e2), await this.onMessageEvent(o2); + } else + f4.isJsonRpcResponse(e2) && this.events.emit(I2.message_ack, e2); + } + async onMessageEvent(e2) { + await this.shouldIgnoreMessageEvent(e2) || (this.events.emit(I2.message, e2), await this.recordMessageEvent(e2)); + } + async acknowledgePayload(e2) { + const t = f4.formatJsonRpcResult(e2.id, true); + await this.provider.connection.send(t); + } + unregisterProviderListeners() { + this.provider.off(w4.payload, this.onPayloadHandler), this.provider.off(w4.connect, this.onConnectHandler), this.provider.off(w4.disconnect, this.onDisconnectHandler), this.provider.off(w4.error, this.onProviderErrorHandler); + } + async registerEventListeners() { + let e2 = await a3.isOnline(); + a3.subscribeToNetworkChange(async (t) => { + e2 !== t && (e2 = t, t ? await this.restartTransport().catch((i2) => this.logger.error(i2)) : (this.hasExperiencedNetworkDisruption = true, await this.transportDisconnect(), this.transportExplicitlyClosed = false)); + }); + } + async onProviderDisconnect() { + await this.subscriber.stop(), this.events.emit(I2.disconnect), this.connectionAttemptInProgress = false, !this.transportExplicitlyClosed && setTimeout(async () => { + await this.transportOpen().catch((e2) => this.logger.error(e2)); + }, l4.toMiliseconds(Be)); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + async toEstablishConnection() { + await this.confirmOnlineStateOrThrow(), !this.connected && (this.connectionAttemptInProgress && await new Promise((e2) => { + const t = setInterval(() => { + this.connected && (clearInterval(t), e2()); + }, this.connectionStatusPollingInterval); + }), await this.transportOpen()); + } + }; + var ws = Object.defineProperty; + var ut = Object.getOwnPropertySymbols; + var vs = Object.prototype.hasOwnProperty; + var Is = Object.prototype.propertyIsEnumerable; + var gt = (n3, e2, t) => e2 in n3 ? ws(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var dt = (n3, e2) => { + for (var t in e2 || (e2 = {})) + vs.call(e2, t) && gt(n3, t, e2[t]); + if (ut) + for (var t of ut(e2)) + Is.call(e2, t) && gt(n3, t, e2[t]); + return n3; + }; + var pt = class extends x3.IStore { + constructor(e2, t, i2, s2 = L2, r = void 0) { + super(e2, t, i2, s2), this.core = e2, this.logger = t, this.name = i2, this.map = /* @__PURE__ */ new Map(), this.version = Ve, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.recentlyDeleted = [], this.recentlyDeletedLimit = 200, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((o2) => { + this.getKey && o2 !== null && !a3.isUndefined(o2) ? this.map.set(this.getKey(o2), o2) : a3.isProposalStruct(o2) ? this.map.set(o2.id, o2) : a3.isSessionStruct(o2) && this.map.set(o2.topic, o2); + }), this.cached = [], this.initialized = true); + }, this.set = async (o2, h5) => { + this.isInitialized(), this.map.has(o2) ? await this.update(o2, h5) : (this.logger.debug("Setting value"), this.logger.trace({ type: "method", method: "set", key: o2, value: h5 }), this.map.set(o2, h5), await this.persist()); + }, this.get = (o2) => (this.isInitialized(), this.logger.debug("Getting value"), this.logger.trace({ type: "method", method: "get", key: o2 }), this.getData(o2)), this.getAll = (o2) => (this.isInitialized(), o2 ? this.values.filter((h5) => Object.keys(o2).every((c4) => Lt.default(h5[c4], o2[c4]))) : this.values), this.update = async (o2, h5) => { + this.isInitialized(), this.logger.debug("Updating value"), this.logger.trace({ type: "method", method: "update", key: o2, update: h5 }); + const c4 = dt(dt({}, this.getData(o2)), h5); + this.map.set(o2, c4), await this.persist(); + }, this.delete = async (o2, h5) => { + this.isInitialized(), this.map.has(o2) && (this.logger.debug("Deleting value"), this.logger.trace({ type: "method", method: "delete", key: o2, reason: h5 }), this.map.delete(o2), this.addToRecentlyDeleted(o2), await this.persist()); + }, this.logger = g3.generateChildLogger(t, this.name), this.storagePrefix = s2, this.getKey = r; + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + get length() { + return this.map.size; + } + get keys() { + return Array.from(this.map.keys()); + } + get values() { + return Array.from(this.map.values()); + } + addToRecentlyDeleted(e2) { + this.recentlyDeleted.push(e2), this.recentlyDeleted.length >= this.recentlyDeletedLimit && this.recentlyDeleted.splice(0, this.recentlyDeletedLimit / 2); + } + async setDataStore(e2) { + await this.core.storage.setItem(this.storageKey, e2); + } + async getDataStore() { + return await this.core.storage.getItem(this.storageKey); + } + getData(e2) { + const t = this.map.get(e2); + if (!t) { + if (this.recentlyDeleted.includes(e2)) { + const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${this.name}: ${e2}`); + throw this.logger.error(s2), new Error(s2); + } + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw this.logger.error(i2), new Error(i2); + } + return t; + } + async persist() { + await this.setDataStore(this.values); + } + async restore() { + try { + const e2 = await this.getDataStore(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.map.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored value for ${this.name}`), this.logger.trace({ type: "method", method: "restore", value: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore value for ${this.name}`), this.logger.error(e2); + } + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var Dt = class { + constructor(e2, t) { + this.core = e2, this.logger = t, this.name = Ge, this.version = He, this.events = new At.default(), this.initialized = false, this.storagePrefix = L2, this.ignoredPayloadTypes = [a3.TYPE_1], this.registeredMethods = [], this.init = async () => { + this.initialized || (await this.pairings.init(), await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.initialized = true, this.logger.trace("Initialized")); + }, this.register = ({ methods: i2 }) => { + this.isInitialized(), this.registeredMethods = [.../* @__PURE__ */ new Set([...this.registeredMethods, ...i2])]; + }, this.create = async (i2) => { + this.isInitialized(); + const s2 = a3.generateRandomBytes32(), r = await this.core.crypto.setSymKey(s2), o2 = a3.calcExpiry(l4.FIVE_MINUTES), h5 = { protocol: Ue }, c4 = { topic: r, expiry: o2, relay: h5, active: false }, u3 = a3.formatUri({ protocol: this.core.protocol, version: this.core.version, topic: r, symKey: s2, relay: h5, expiryTimestamp: o2, methods: i2?.methods }); + return await this.pairings.set(r, c4), await this.core.relayer.subscribe(r), this.core.expirer.set(r, o2), { topic: r, uri: u3 }; + }, this.pair = async (i2) => { + this.isInitialized(), this.isValidPair(i2); + const { topic: s2, symKey: r, relay: o2, expiryTimestamp: h5, methods: c4 } = a3.parseUri(i2.uri); + let u3; + if (this.pairings.keys.includes(s2) && (u3 = this.pairings.get(s2), u3.active)) + throw new Error(`Pairing already exists: ${s2}. Please try again with a new connection URI.`); + const p3 = h5 || a3.calcExpiry(l4.FIVE_MINUTES), D2 = { topic: s2, relay: o2, expiry: p3, active: false, methods: c4 }; + return await this.pairings.set(s2, D2), this.core.expirer.set(s2, p3), i2.activatePairing && await this.activate({ topic: s2 }), this.events.emit(K2.create, D2), this.core.crypto.keychain.has(s2) || await this.core.crypto.setSymKey(r, s2), await this.core.relayer.subscribe(s2, { relay: o2 }), D2; + }, this.activate = async ({ topic: i2 }) => { + this.isInitialized(); + const s2 = a3.calcExpiry(l4.THIRTY_DAYS); + await this.pairings.update(i2, { active: true, expiry: s2 }), this.core.expirer.set(i2, s2); + }, this.ping = async (i2) => { + this.isInitialized(), await this.isValidPing(i2); + const { topic: s2 } = i2; + if (this.pairings.keys.includes(s2)) { + const r = await this.sendRequest(s2, "wc_pairingPing", {}), { done: o2, resolve: h5, reject: c4 } = a3.createDelayedPromise(); + this.events.once(a3.engineEvent("pairing_ping", r), ({ error: u3 }) => { + u3 ? c4(u3) : h5(); + }), await o2(); + } + }, this.updateExpiry = async ({ topic: i2, expiry: s2 }) => { + this.isInitialized(), await this.pairings.update(i2, { expiry: s2 }); + }, this.updateMetadata = async ({ topic: i2, metadata: s2 }) => { + this.isInitialized(), await this.pairings.update(i2, { peerMetadata: s2 }); + }, this.getPairings = () => (this.isInitialized(), this.pairings.values), this.disconnect = async (i2) => { + this.isInitialized(), await this.isValidDisconnect(i2); + const { topic: s2 } = i2; + this.pairings.keys.includes(s2) && (await this.sendRequest(s2, "wc_pairingDelete", a3.getSdkError("USER_DISCONNECTED")), await this.deletePairing(s2)); + }, this.sendRequest = async (i2, s2, r) => { + const o2 = f4.formatJsonRpcRequest(s2, r), h5 = await this.core.crypto.encode(i2, o2), c4 = M[s2].req; + return this.core.history.set(i2, o2), this.core.relayer.publish(i2, h5, c4), o2.id; + }, this.sendResult = async (i2, s2, r) => { + const o2 = f4.formatJsonRpcResult(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method].res; + await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); + }, this.sendError = async (i2, s2, r) => { + const o2 = f4.formatJsonRpcError(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method] ? M[c4.request.method].res : M.unregistered_method.res; + await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); + }, this.deletePairing = async (i2, s2) => { + await this.core.relayer.unsubscribe(i2), await Promise.all([this.pairings.delete(i2, a3.getSdkError("USER_DISCONNECTED")), this.core.crypto.deleteSymKey(i2), s2 ? Promise.resolve() : this.core.expirer.del(i2)]); + }, this.cleanup = async () => { + const i2 = this.pairings.getAll().filter((s2) => a3.isExpired(s2.expiry)); + await Promise.all(i2.map((s2) => this.deletePairing(s2.topic))); + }, this.onRelayEventRequest = (i2) => { + const { topic: s2, payload: r } = i2; + switch (r.method) { + case "wc_pairingPing": + return this.onPairingPingRequest(s2, r); + case "wc_pairingDelete": + return this.onPairingDeleteRequest(s2, r); + default: + return this.onUnknownRpcMethodRequest(s2, r); + } + }, this.onRelayEventResponse = async (i2) => { + const { topic: s2, payload: r } = i2, o2 = (await this.core.history.get(s2, r.id)).request.method; + switch (o2) { + case "wc_pairingPing": + return this.onPairingPingResponse(s2, r); + default: + return this.onUnknownRpcMethodResponse(o2); + } + }, this.onPairingPingRequest = async (i2, s2) => { + const { id: r } = s2; + try { + this.isValidPing({ topic: i2 }), await this.sendResult(r, i2, true), this.events.emit(K2.ping, { id: r, topic: i2 }); + } catch (o2) { + await this.sendError(r, i2, o2), this.logger.error(o2); + } + }, this.onPairingPingResponse = (i2, s2) => { + const { id: r } = s2; + setTimeout(() => { + f4.isJsonRpcResult(s2) ? this.events.emit(a3.engineEvent("pairing_ping", r), {}) : f4.isJsonRpcError(s2) && this.events.emit(a3.engineEvent("pairing_ping", r), { error: s2.error }); + }, 500); + }, this.onPairingDeleteRequest = async (i2, s2) => { + const { id: r } = s2; + try { + this.isValidDisconnect({ topic: i2 }), await this.deletePairing(i2), this.events.emit(K2.delete, { id: r, topic: i2 }); + } catch (o2) { + await this.sendError(r, i2, o2), this.logger.error(o2); + } + }, this.onUnknownRpcMethodRequest = async (i2, s2) => { + const { id: r, method: o2 } = s2; + try { + if (this.registeredMethods.includes(o2)) + return; + const h5 = a3.getSdkError("WC_METHOD_UNSUPPORTED", o2); + await this.sendError(r, i2, h5), this.logger.error(h5); + } catch (h5) { + await this.sendError(r, i2, h5), this.logger.error(h5); + } + }, this.onUnknownRpcMethodResponse = (i2) => { + this.registeredMethods.includes(i2) || this.logger.error(a3.getSdkError("WC_METHOD_UNSUPPORTED", i2)); + }, this.isValidPair = (i2) => { + var s2; + if (!a3.isValidParams(i2)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() params: ${i2}`); + throw new Error(o2); + } + if (!a3.isValidUrl(i2.uri)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() uri: ${i2.uri}`); + throw new Error(o2); + } + const r = a3.parseUri(i2.uri); + if (!((s2 = r?.relay) != null && s2.protocol)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#relay-protocol"); + throw new Error(o2); + } + if (!(r != null && r.symKey)) { + const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#symKey"); + throw new Error(o2); + } + if (r != null && r.expiryTimestamp && l4.toMiliseconds(r?.expiryTimestamp) < Date.now()) { + const { message: o2 } = a3.getInternalError("EXPIRED", "pair() URI has expired. Please try again with a new connection URI."); + throw new Error(o2); + } + }, this.isValidPing = async (i2) => { + if (!a3.isValidParams(i2)) { + const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `ping() params: ${i2}`); + throw new Error(r); + } + const { topic: s2 } = i2; + await this.isValidPairingTopic(s2); + }, this.isValidDisconnect = async (i2) => { + if (!a3.isValidParams(i2)) { + const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${i2}`); + throw new Error(r); + } + const { topic: s2 } = i2; + await this.isValidPairingTopic(s2); + }, this.isValidPairingTopic = async (i2) => { + if (!a3.isValidString(i2, false)) { + const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${i2}`); + throw new Error(s2); + } + if (!this.pairings.keys.includes(i2)) { + const { message: s2 } = a3.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${i2}`); + throw new Error(s2); + } + if (a3.isExpired(this.pairings.get(i2).expiry)) { + await this.deletePairing(i2); + const { message: s2 } = a3.getInternalError("EXPIRED", `pairing topic: ${i2}`); + throw new Error(s2); + } + }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.pairings = new pt(this.core, this.logger, this.name, this.storagePrefix); + } + get context() { + return g3.getLoggerContext(this.logger); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + registerRelayerEvents() { + this.core.relayer.on(I2.message, async (e2) => { + const { topic: t, message: i2 } = e2; + if (!this.pairings.keys.includes(t) || this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i2))) + return; + const s2 = await this.core.crypto.decode(t, i2); + try { + f4.isJsonRpcRequest(s2) ? (this.core.history.set(t, s2), this.onRelayEventRequest({ topic: t, payload: s2 })) : f4.isJsonRpcResponse(s2) && (await this.core.history.resolve(s2), await this.onRelayEventResponse({ topic: t, payload: s2 }), this.core.history.delete(t, s2.id)); + } catch (r) { + this.logger.error(r); + } + }); + } + registerExpirerEvents() { + this.core.expirer.on(_4.expired, async (e2) => { + const { topic: t } = a3.parseExpirerTarget(e2.target); + t && this.pairings.keys.includes(t) && (await this.deletePairing(t, true), this.events.emit(K2.expire, { topic: t })); + }); + } + }; + var yt = class extends x3.IJsonRpcHistory { + constructor(e2, t) { + super(e2, t), this.core = e2, this.logger = t, this.records = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = Xe, this.version = Je, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.records.set(i2.id, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); + }, this.set = (i2, s2, r) => { + if (this.isInitialized(), this.logger.debug("Setting JSON-RPC request history record"), this.logger.trace({ type: "method", method: "set", topic: i2, request: s2, chainId: r }), this.records.has(s2.id)) + return; + const o2 = { id: s2.id, topic: i2, request: { method: s2.method, params: s2.params || null }, chainId: r, expiry: a3.calcExpiry(l4.THIRTY_DAYS) }; + this.records.set(o2.id, o2), this.persist(), this.events.emit(R2.created, o2); + }, this.resolve = async (i2) => { + if (this.isInitialized(), this.logger.debug("Updating JSON-RPC response history record"), this.logger.trace({ type: "method", method: "update", response: i2 }), !this.records.has(i2.id)) + return; + const s2 = await this.getRecord(i2.id); + typeof s2.response > "u" && (s2.response = f4.isJsonRpcError(i2) ? { error: i2.error } : { result: i2.result }, this.records.set(s2.id, s2), this.persist(), this.events.emit(R2.updated, s2)); + }, this.get = async (i2, s2) => (this.isInitialized(), this.logger.debug("Getting record"), this.logger.trace({ type: "method", method: "get", topic: i2, id: s2 }), await this.getRecord(s2)), this.delete = (i2, s2) => { + this.isInitialized(), this.logger.debug("Deleting record"), this.logger.trace({ type: "method", method: "delete", id: s2 }), this.values.forEach((r) => { + if (r.topic === i2) { + if (typeof s2 < "u" && r.id !== s2) + return; + this.records.delete(r.id), this.events.emit(R2.deleted, r); + } + }), this.persist(); + }, this.exists = async (i2, s2) => (this.isInitialized(), this.records.has(s2) ? (await this.getRecord(s2)).topic === i2 : false), this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.logger = g3.generateChildLogger(t, this.name); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + get size() { + return this.records.size; + } + get keys() { + return Array.from(this.records.keys()); + } + get values() { + return Array.from(this.records.values()); + } + get pending() { + const e2 = []; + return this.values.forEach((t) => { + if (typeof t.response < "u") + return; + const i2 = { topic: t.topic, request: f4.formatJsonRpcRequest(t.request.method, t.request.params, t.id), chainId: t.chainId }; + return e2.push(i2); + }), e2; + } + async setJsonRpcRecords(e2) { + await this.core.storage.setItem(this.storageKey, e2); + } + async getJsonRpcRecords() { + return await this.core.storage.getItem(this.storageKey); + } + getRecord(e2) { + this.isInitialized(); + const t = this.records.get(e2); + if (!t) { + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw new Error(i2); + } + return t; + } + async persist() { + await this.setJsonRpcRecords(this.values), this.events.emit(R2.sync); + } + async restore() { + try { + const e2 = await this.getJsonRpcRecords(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.records.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", records: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(e2); + } + } + registerEventListeners() { + this.events.on(R2.created, (e2) => { + const t = R2.created; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); + }), this.events.on(R2.updated, (e2) => { + const t = R2.updated; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); + }), this.events.on(R2.deleted, (e2) => { + const t = R2.deleted; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); + }), this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { + this.cleanup(); + }); + } + cleanup() { + try { + this.isInitialized(); + let e2 = false; + this.records.forEach((t) => { + l4.toMiliseconds(t.expiry || 0) - Date.now() <= 0 && (this.logger.info(`Deleting expired history log: ${t.id}`), this.records.delete(t.id), this.events.emit(R2.deleted, t, false), e2 = true); + }), e2 && this.persist(); + } catch (e2) { + this.logger.warn(e2); + } + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var Et = class extends x3.IExpirer { + constructor(e2, t) { + super(e2, t), this.core = e2, this.logger = t, this.expirations = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = We, this.version = Qe, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { + this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.expirations.set(i2.target, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); + }, this.has = (i2) => { + try { + const s2 = this.formatTarget(i2); + return typeof this.getExpiration(s2) < "u"; + } catch { + return false; + } + }, this.set = (i2, s2) => { + this.isInitialized(); + const r = this.formatTarget(i2), o2 = { target: r, expiry: s2 }; + this.expirations.set(r, o2), this.checkExpiry(r, o2), this.events.emit(_4.created, { target: r, expiration: o2 }); + }, this.get = (i2) => { + this.isInitialized(); + const s2 = this.formatTarget(i2); + return this.getExpiration(s2); + }, this.del = (i2) => { + if (this.isInitialized(), this.has(i2)) { + const s2 = this.formatTarget(i2), r = this.getExpiration(s2); + this.expirations.delete(s2), this.events.emit(_4.deleted, { target: s2, expiration: r }); + } + }, this.on = (i2, s2) => { + this.events.on(i2, s2); + }, this.once = (i2, s2) => { + this.events.once(i2, s2); + }, this.off = (i2, s2) => { + this.events.off(i2, s2); + }, this.removeListener = (i2, s2) => { + this.events.removeListener(i2, s2); + }, this.logger = g3.generateChildLogger(t, this.name); + } + get context() { + return g3.getLoggerContext(this.logger); + } + get storageKey() { + return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; + } + get length() { + return this.expirations.size; + } + get keys() { + return Array.from(this.expirations.keys()); + } + get values() { + return Array.from(this.expirations.values()); + } + formatTarget(e2) { + if (typeof e2 == "string") + return a3.formatTopicTarget(e2); + if (typeof e2 == "number") + return a3.formatIdTarget(e2); + const { message: t } = a3.getInternalError("UNKNOWN_TYPE", `Target type: ${typeof e2}`); + throw new Error(t); + } + async setExpirations(e2) { + await this.core.storage.setItem(this.storageKey, e2); + } + async getExpirations() { + return await this.core.storage.getItem(this.storageKey); + } + async persist() { + await this.setExpirations(this.values), this.events.emit(_4.sync); + } + async restore() { + try { + const e2 = await this.getExpirations(); + if (typeof e2 > "u" || !e2.length) + return; + if (this.expirations.size) { + const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); + throw this.logger.error(t), new Error(t); + } + this.cached = e2, this.logger.debug(`Successfully Restored expirations for ${this.name}`), this.logger.trace({ type: "method", method: "restore", expirations: this.values }); + } catch (e2) { + this.logger.debug(`Failed to Restore expirations for ${this.name}`), this.logger.error(e2); + } + } + getExpiration(e2) { + const t = this.expirations.get(e2); + if (!t) { + const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); + throw this.logger.warn(i2), new Error(i2); + } + return t; + } + checkExpiry(e2, t) { + const { expiry: i2 } = t; + l4.toMiliseconds(i2) - Date.now() <= 0 && this.expire(e2, t); + } + expire(e2, t) { + this.expirations.delete(e2), this.events.emit(_4.expired, { target: e2, expiration: t }); + } + checkExpirations() { + this.core.relayer.connected && this.expirations.forEach((e2, t) => this.checkExpiry(t, e2)); + } + registerEventListeners() { + this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => this.checkExpirations()), this.events.on(_4.created, (e2) => { + const t = _4.created; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); + }), this.events.on(_4.expired, (e2) => { + const t = _4.expired; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); + }), this.events.on(_4.deleted, (e2) => { + const t = _4.deleted; + this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); + }); + } + isInitialized() { + if (!this.initialized) { + const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(e2); + } + } + }; + var mt = class extends x3.IVerify { + constructor(e2, t) { + super(e2, t), this.projectId = e2, this.logger = t, this.name = X, this.initialized = false, this.queue = [], this.verifyDisabled = false, this.init = async (i2) => { + if (this.verifyDisabled || a3.isReactNative() || !a3.isBrowser()) + return; + const s2 = this.getVerifyUrl(i2?.verifyUrl); + this.verifyUrl !== s2 && this.removeIframe(), this.verifyUrl = s2; + try { + await this.createIframe(); + } catch (r) { + this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r); + } + if (!this.initialized) { + this.removeIframe(), this.verifyUrl = J; + try { + await this.createIframe(); + } catch (r) { + this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r), this.verifyDisabled = true; + } + } + }, this.register = async (i2) => { + this.initialized ? this.sendPost(i2.attestationId) : (this.addToQueue(i2.attestationId), await this.init()); + }, this.resolve = async (i2) => { + if (this.isDevEnv) + return ""; + const s2 = this.getVerifyUrl(i2?.verifyUrl); + let r; + try { + r = await this.fetchAttestation(i2.attestationId, s2); + } catch (o2) { + this.logger.info(`failed to resolve attestation: ${i2.attestationId} from url: ${s2}`), this.logger.info(o2), r = await this.fetchAttestation(i2.attestationId, J); + } + return r; + }, this.fetchAttestation = async (i2, s2) => { + this.logger.info(`resolving attestation: ${i2} from url: ${s2}`); + const r = this.startAbortTimer(l4.ONE_SECOND * 2), o2 = await fetch(`${s2}/attestation/${i2}`, { signal: this.abortController.signal }); + return clearTimeout(r), o2.status === 200 ? await o2.json() : void 0; + }, this.addToQueue = (i2) => { + this.queue.push(i2); + }, this.processQueue = () => { + this.queue.length !== 0 && (this.queue.forEach((i2) => this.sendPost(i2)), this.queue = []); + }, this.sendPost = (i2) => { + var s2; + try { + if (!this.iframe) + return; + (s2 = this.iframe.contentWindow) == null || s2.postMessage(i2, "*"), this.logger.info(`postMessage sent: ${i2} ${this.verifyUrl}`); + } catch { + } + }, this.createIframe = async () => { + let i2; + const s2 = (r) => { + r.data === "verify_ready" && (this.onInit(), window.removeEventListener("message", s2), i2()); + }; + await Promise.race([new Promise((r) => { + const o2 = document.getElementById(X); + if (o2) + return this.iframe = o2, this.onInit(), r(); + window.addEventListener("message", s2); + const h5 = document.createElement("iframe"); + h5.id = X, h5.src = `${this.verifyUrl}/${this.projectId}`, h5.style.display = "none", document.body.append(h5), this.iframe = h5, i2 = r; + }), new Promise((r, o2) => setTimeout(() => { + window.removeEventListener("message", s2), o2("verify iframe load timeout"); + }, l4.toMiliseconds(l4.FIVE_SECONDS)))]); + }, this.onInit = () => { + this.initialized = true, this.processQueue(); + }, this.removeIframe = () => { + this.iframe && (this.iframe.remove(), this.iframe = void 0, this.initialized = false); + }, this.getVerifyUrl = (i2) => { + let s2 = i2 || B2; + return Ze.includes(s2) || (this.logger.info(`verify url: ${s2}, not included in trusted list, assigning default: ${B2}`), s2 = B2), s2; + }, this.logger = g3.generateChildLogger(t, this.name), this.verifyUrl = B2, this.abortController = new AbortController(), this.isDevEnv = a3.isNode() && import_process.default.env.IS_VITEST; + } + get context() { + return g3.getLoggerContext(this.logger); + } + startAbortTimer(e2) { + return this.abortController = new AbortController(), setTimeout(() => this.abortController.abort(), l4.toMiliseconds(e2)); + } + }; + var bt = class extends x3.IEchoClient { + constructor(e2, t) { + super(e2, t), this.projectId = e2, this.logger = t, this.context = et, this.registerDeviceToken = async (i2) => { + const { clientId: s2, token: r, notificationType: o2, enableEncrypted: h5 = false } = i2, c4 = `${tt}/${this.projectId}/clients`; + await Ut.default(c4, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: s2, type: o2, token: r, always_raw: h5 }) }); + }, this.logger = g3.generateChildLogger(t, this.context); + } + }; + var Rs = Object.defineProperty; + var ft = Object.getOwnPropertySymbols; + var _s = Object.prototype.hasOwnProperty; + var Cs = Object.prototype.propertyIsEnumerable; + var wt = (n3, e2, t) => e2 in n3 ? Rs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; + var vt = (n3, e2) => { + for (var t in e2 || (e2 = {})) + _s.call(e2, t) && wt(n3, t, e2[t]); + if (ft) + for (var t of ft(e2)) + Cs.call(e2, t) && wt(n3, t, e2[t]); + return n3; + }; + var W = class _W extends x3.ICore { + constructor(e2) { + var t; + super(e2), this.protocol = te, this.version = Re, this.name = H, this.events = new z3.EventEmitter(), this.initialized = false, this.on = (o2, h5) => this.events.on(o2, h5), this.once = (o2, h5) => this.events.once(o2, h5), this.off = (o2, h5) => this.events.off(o2, h5), this.removeListener = (o2, h5) => this.events.removeListener(o2, h5), this.projectId = e2?.projectId, this.relayUrl = e2?.relayUrl || se, this.customStoragePrefix = e2 != null && e2.customStoragePrefix ? `:${e2.customStoragePrefix}` : ""; + const i2 = g3.getDefaultLoggerOptions({ level: typeof e2?.logger == "string" && e2.logger ? e2.logger : _e.logger }), { logger: s2, chunkLoggerController: r } = g3.generatePlatformLogger({ opts: i2, maxSizeInBytes: e2?.maxLogBlobSizeInBytes, loggerOverride: e2?.logger }); + this.logChunkController = r, (t = this.logChunkController) != null && t.downloadLogsBlobInBrowser && (window.downloadLogsBlobInBrowser = async () => { + var o2, h5; + (o2 = this.logChunkController) != null && o2.downloadLogsBlobInBrowser && ((h5 = this.logChunkController) == null || h5.downloadLogsBlobInBrowser({ clientId: await this.crypto.getClientId() })); + }), this.logger = g3.generateChildLogger(s2, this.name), this.heartbeat = new $.HeartBeat(), this.crypto = new st(this, this.logger, e2?.keychain), this.history = new yt(this, this.logger), this.expirer = new Et(this, this.logger), this.storage = e2 != null && e2.storage ? e2.storage : new xt.default(vt(vt({}, Ce), e2?.storageOptions)), this.relayer = new lt({ core: this, logger: this.logger, relayUrl: this.relayUrl, projectId: this.projectId }), this.pairing = new Dt(this, this.logger), this.verify = new mt(this.projectId || "", this.logger), this.echoClient = new bt(this.projectId || "", this.logger); + } + static async init(e2) { + const t = new _W(e2); + await t.initialize(); + const i2 = await t.crypto.getClientId(); + return await t.storage.setItem(Ke, i2), t; + } + get context() { + return g3.getLoggerContext(this.logger); + } + async start() { + this.initialized || await this.initialize(); + } + async getLogsBlob() { + var e2; + return (e2 = this.logChunkController) == null ? void 0 : e2.logsToBlob({ clientId: await this.crypto.getClientId() }); + } + async initialize() { + this.logger.trace("Initialized"); + try { + await this.crypto.init(), await this.history.init(), await this.expirer.init(), await this.relayer.init(), await this.heartbeat.init(), await this.pairing.init(), this.initialized = true, this.logger.info("Core Initialization Success"); + } catch (e2) { + throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`, e2), this.logger.error(e2.message), e2; + } + } + }; + var Ts = W; + exports2.CORE_CONTEXT = H, exports2.CORE_DEFAULT = _e, exports2.CORE_PROTOCOL = te, exports2.CORE_STORAGE_OPTIONS = Ce, exports2.CORE_STORAGE_PREFIX = L2, exports2.CORE_VERSION = Re, exports2.CRYPTO_CLIENT_SEED = ie, exports2.CRYPTO_CONTEXT = Te, exports2.CRYPTO_JWT_TTL = Se, exports2.Core = Ts, exports2.Crypto = st, exports2.ECHO_CONTEXT = et, exports2.ECHO_URL = tt, exports2.EXPIRER_CONTEXT = We, exports2.EXPIRER_DEFAULT_TTL = cs, exports2.EXPIRER_EVENTS = _4, exports2.EXPIRER_STORAGE_VERSION = Qe, exports2.EchoClient = bt, exports2.Expirer = Et, exports2.HISTORY_CONTEXT = Xe, exports2.HISTORY_EVENTS = R2, exports2.HISTORY_STORAGE_VERSION = Je, exports2.JsonRpcHistory = yt, exports2.KEYCHAIN_CONTEXT = Oe, exports2.KEYCHAIN_STORAGE_VERSION = Pe, exports2.KeyChain = it, exports2.MESSAGES_CONTEXT = Ae, exports2.MESSAGES_STORAGE_VERSION = xe, exports2.MessageTracker = rt, exports2.PAIRING_CONTEXT = Ge, exports2.PAIRING_DEFAULT_TTL = hs, exports2.PAIRING_EVENTS = K2, exports2.PAIRING_RPC_OPTS = M, exports2.PAIRING_STORAGE_VERSION = He, exports2.PENDING_SUB_RESOLUTION_TIMEOUT = je, exports2.PUBLISHER_CONTEXT = Le, exports2.PUBLISHER_DEFAULT_TTL = Ne, exports2.Pairing = Dt, exports2.RELAYER_CONTEXT = Fe, exports2.RELAYER_DEFAULT_LOGGER = ze, exports2.RELAYER_DEFAULT_PROTOCOL = Ue, exports2.RELAYER_DEFAULT_RELAY_URL = se, exports2.RELAYER_EVENTS = I2, exports2.RELAYER_FAILOVER_RELAY_URL = re, exports2.RELAYER_PROVIDER_EVENTS = w4, exports2.RELAYER_RECONNECT_TIMEOUT = Be, exports2.RELAYER_SDK_VERSION = $e, exports2.RELAYER_STORAGE_OPTIONS = os, exports2.RELAYER_SUBSCRIBER_SUFFIX = Me, exports2.RELAYER_TRANSPORT_CUTOFF = ke, exports2.Relayer = lt, exports2.STORE_STORAGE_VERSION = Ve, exports2.SUBSCRIBER_CONTEXT = qe, exports2.SUBSCRIBER_DEFAULT_TTL = as, exports2.SUBSCRIBER_EVENTS = S4, exports2.SUBSCRIBER_STORAGE_VERSION = Ye, exports2.Store = pt, exports2.Subscriber = at, exports2.TRUSTED_VERIFY_URLS = Ze, exports2.VERIFY_CONTEXT = X, exports2.VERIFY_FALLBACK_SERVER = J, exports2.VERIFY_SERVER = B2, exports2.Verify = mt, exports2.WALLETCONNECT_CLIENT_ID = Ke, exports2.default = W; + } +}); + +// node_modules/@walletconnect/sign-client/dist/index.cjs.js +var require_index_cjs4 = __commonJS({ + "node_modules/@walletconnect/sign-client/dist/index.cjs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + var N10 = require_index_cjs3(); + var k4 = (init_index_es2(), __toCommonJS(index_es_exports2)); + var oe = require_index_cjs(); + var s2 = require_index_cjs2(); + var ae = require_events(); + var w4 = require_cjs(); + var u3 = (init_esm5(), __toCommonJS(esm_exports4)); + function fe(y4) { + return y4 && typeof y4 == "object" && "default" in y4 ? y4 : { default: y4 }; + } + var qe = fe(ae); + var ee = "wc"; + var te = 2; + var ie = "client"; + var F = `${ee}@${te}:${ie}:`; + var Y = { name: ie, logger: "error", controller: false, relayUrl: "wss://relay.walletconnect.com" }; + var Pe = { session_proposal: "session_proposal", session_update: "session_update", session_extend: "session_extend", session_ping: "session_ping", session_delete: "session_delete", session_expire: "session_expire", session_request: "session_request", session_request_sent: "session_request_sent", session_event: "session_event", proposal_expire: "proposal_expire", session_authenticate: "session_authenticate", session_request_expire: "session_request_expire" }; + var Te = { database: ":memory:" }; + var se = "WALLETCONNECT_DEEPLINK_CHOICE"; + var ve = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; + var Oe = "history"; + var Ae = "0.3"; + var ce = "proposal"; + var Ve = w4.THIRTY_DAYS; + var le = "Proposal expired"; + var he = "session"; + var V = w4.SEVEN_DAYS; + var pe = "engine"; + var q2 = { wc_sessionPropose: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1100 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1101 } }, wc_sessionSettle: { req: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1102 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1103 } }, wc_sessionUpdate: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1104 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1105 } }, wc_sessionExtend: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1106 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1107 } }, wc_sessionRequest: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1108 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1109 } }, wc_sessionEvent: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1110 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1111 } }, wc_sessionDelete: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1112 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1113 } }, wc_sessionPing: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1114 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1115 } }, wc_sessionAuthenticate: { req: { ttl: w4.ONE_HOUR, prompt: true, tag: 1116 }, res: { ttl: w4.ONE_HOUR, prompt: false, tag: 1117 } } }; + var H = { min: w4.FIVE_MINUTES, max: w4.SEVEN_DAYS }; + var A2 = { idle: "IDLE", active: "ACTIVE" }; + var de = "request"; + var ue = ["wc_sessionPropose", "wc_sessionRequest", "wc_authRequest"]; + var ge = "wc"; + var De = 1.5; + var Ee = "auth"; + var we = "authKeys"; + var ye = "pairingTopics"; + var me = "requests"; + var L2 = `${ge}@${1.5}:${Ee}:`; + var U2 = `${L2}:PUB_KEY`; + var Ce = Object.defineProperty; + var xe = Object.defineProperties; + var be = Object.getOwnPropertyDescriptors; + var Se = Object.getOwnPropertySymbols; + var Me = Object.prototype.hasOwnProperty; + var Le = Object.prototype.propertyIsEnumerable; + var Ie = (y4, o2, t) => o2 in y4 ? Ce(y4, o2, { enumerable: true, configurable: true, writable: true, value: t }) : y4[o2] = t; + var S4 = (y4, o2) => { + for (var t in o2 || (o2 = {})) + Me.call(o2, t) && Ie(y4, t, o2[t]); + if (Se) + for (var t of Se(o2)) + Le.call(o2, t) && Ie(y4, t, o2[t]); + return y4; + }; + var C3 = (y4, o2) => xe(y4, be(o2)); + var Ue = class extends oe.IEngine { + constructor(o2) { + super(o2), this.name = pe, this.events = new qe.default(), this.initialized = false, this.requestQueue = { state: A2.idle, queue: [] }, this.sessionRequestQueue = { state: A2.idle, queue: [] }, this.requestQueueDelay = w4.ONE_SECOND, this.expectedPairingMethodMap = /* @__PURE__ */ new Map(), this.recentlyDeletedMap = /* @__PURE__ */ new Map(), this.recentlyDeletedLimit = 200, this.init = async () => { + this.initialized || (await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.registerPairingEvents(), this.client.core.pairing.register({ methods: Object.keys(q2) }), this.initialized = true, setTimeout(() => { + this.sessionRequestQueue.queue = this.getPendingSessionRequests(), this.processSessionRequestQueue(); + }, w4.toMiliseconds(this.requestQueueDelay))); + }, this.connect = async (t) => { + await this.isInitialized(); + const e2 = C3(S4({}, t), { requiredNamespaces: t.requiredNamespaces || {}, optionalNamespaces: t.optionalNamespaces || {} }); + await this.isValidConnect(e2); + const { pairingTopic: i2, requiredNamespaces: r, optionalNamespaces: n3, sessionProperties: a3, relays: c4 } = e2; + let l4 = i2, d3, p3 = false; + try { + l4 && (p3 = this.client.core.pairing.pairings.get(l4).active); + } catch (f4) { + throw this.client.logger.error(`connect() -> pairing.get(${l4}) failed`), f4; + } + if (!l4 || !p3) { + const { topic: f4, uri: T2 } = await this.client.core.pairing.create(); + l4 = f4, d3 = T2; + } + if (!l4) { + const { message: f4 } = s2.getInternalError("NO_MATCHING_KEY", `connect() pairing topic: ${l4}`); + throw new Error(f4); + } + const g3 = await this.client.core.crypto.generateKeyPair(), h5 = q2.wc_sessionPropose.req.ttl || w4.FIVE_MINUTES, m3 = s2.calcExpiry(h5), E4 = S4({ requiredNamespaces: r, optionalNamespaces: n3, relays: c4 ?? [{ protocol: N10.RELAYER_DEFAULT_PROTOCOL }], proposer: { publicKey: g3, metadata: this.client.metadata }, expiryTimestamp: m3 }, a3 && { sessionProperties: a3 }), { reject: R2, resolve: O3, done: I2 } = s2.createDelayedPromise(h5, le); + this.events.once(s2.engineEvent("session_connect"), async ({ error: f4, session: T2 }) => { + if (f4) + R2(f4); + else if (T2) { + T2.self.publicKey = g3; + const x3 = C3(S4({}, T2), { requiredNamespaces: E4.requiredNamespaces, optionalNamespaces: E4.optionalNamespaces }); + await this.client.session.set(T2.topic, x3), await this.setExpiry(T2.topic, T2.expiry), l4 && await this.client.core.pairing.updateMetadata({ topic: l4, metadata: T2.peer.metadata }), O3(x3); + } + }); + const P2 = await this.sendRequest({ topic: l4, method: "wc_sessionPropose", params: E4, throwOnFailedPublish: true }); + return await this.setProposal(P2, S4({ id: P2 }, E4)), { uri: d3, approval: I2 }; + }, this.pair = async (t) => { + await this.isInitialized(); + try { + return await this.client.core.pairing.pair(t); + } catch (e2) { + throw this.client.logger.error("pair() failed"), e2; + } + }, this.approve = async (t) => { + await this.isInitialized(); + try { + await this.isValidApprove(t); + } catch (I2) { + throw this.client.logger.error("approve() -> isValidApprove() failed"), I2; + } + const { id: e2, relayProtocol: i2, namespaces: r, sessionProperties: n3, sessionConfig: a3 } = t; + let c4; + try { + c4 = this.client.proposal.get(e2); + } catch (I2) { + throw this.client.logger.error(`approve() -> proposal.get(${e2}) failed`), I2; + } + let { pairingTopic: l4, proposer: d3, requiredNamespaces: p3, optionalNamespaces: g3 } = c4; + l4 = l4 || ""; + const h5 = await this.client.core.crypto.generateKeyPair(), m3 = d3.publicKey, E4 = await this.client.core.crypto.generateSharedKey(h5, m3), R2 = S4(S4({ relay: { protocol: i2 ?? "irn" }, namespaces: r, pairingTopic: l4, controller: { publicKey: h5, metadata: this.client.metadata }, expiry: s2.calcExpiry(V) }, n3 && { sessionProperties: n3 }), a3 && { sessionConfig: a3 }); + await this.client.core.relayer.subscribe(E4); + const O3 = C3(S4({}, R2), { topic: E4, requiredNamespaces: p3, optionalNamespaces: g3, pairingTopic: l4, acknowledged: false, self: R2.controller, peer: { publicKey: d3.publicKey, metadata: d3.metadata }, controller: h5 }); + await this.client.session.set(E4, O3); + try { + await this.sendResult({ id: e2, topic: l4, result: { relay: { protocol: i2 ?? "irn" }, responderPublicKey: h5 }, throwOnFailedPublish: true }), await this.sendRequest({ topic: E4, method: "wc_sessionSettle", params: R2, throwOnFailedPublish: true }); + } catch (I2) { + throw this.client.logger.error(I2), this.client.session.delete(E4, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.relayer.unsubscribe(E4), I2; + } + return await this.client.core.pairing.updateMetadata({ topic: l4, metadata: d3.metadata }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.pairing.activate({ topic: l4 }), await this.setExpiry(E4, s2.calcExpiry(V)), { topic: E4, acknowledged: () => new Promise((I2) => setTimeout(() => I2(this.client.session.get(E4)), 500)) }; + }, this.reject = async (t) => { + await this.isInitialized(); + try { + await this.isValidReject(t); + } catch (n3) { + throw this.client.logger.error("reject() -> isValidReject() failed"), n3; + } + const { id: e2, reason: i2 } = t; + let r; + try { + r = this.client.proposal.get(e2).pairingTopic; + } catch (n3) { + throw this.client.logger.error(`reject() -> proposal.get(${e2}) failed`), n3; + } + r && (await this.sendError({ id: e2, topic: r, error: i2 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED"))); + }, this.update = async (t) => { + await this.isInitialized(); + try { + await this.isValidUpdate(t); + } catch (p3) { + throw this.client.logger.error("update() -> isValidUpdate() failed"), p3; + } + const { topic: e2, namespaces: i2 } = t, { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), d3 = this.client.session.get(e2).namespaces; + return this.events.once(s2.engineEvent("session_update", c4), ({ error: p3 }) => { + p3 ? a3(p3) : n3(); + }), await this.client.session.update(e2, { namespaces: i2 }), this.sendRequest({ topic: e2, method: "wc_sessionUpdate", params: { namespaces: i2 }, throwOnFailedPublish: true, clientRpcId: c4, relayRpcId: l4 }).catch((p3) => { + this.client.logger.error(p3), this.client.session.update(e2, { namespaces: d3 }), a3(p3); + }), { acknowledged: r }; + }, this.extend = async (t) => { + await this.isInitialized(); + try { + await this.isValidExtend(t); + } catch (c4) { + throw this.client.logger.error("extend() -> isValidExtend() failed"), c4; + } + const { topic: e2 } = t, i2 = u3.payloadId(), { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(); + return this.events.once(s2.engineEvent("session_extend", i2), ({ error: c4 }) => { + c4 ? a3(c4) : n3(); + }), await this.setExpiry(e2, s2.calcExpiry(V)), this.sendRequest({ topic: e2, method: "wc_sessionExtend", params: {}, clientRpcId: i2, throwOnFailedPublish: true }).catch((c4) => { + a3(c4); + }), { acknowledged: r }; + }, this.request = async (t) => { + await this.isInitialized(); + try { + await this.isValidRequest(t); + } catch (h5) { + throw this.client.logger.error("request() -> isValidRequest() failed"), h5; + } + const { chainId: e2, request: i2, topic: r, expiry: n3 = q2.wc_sessionRequest.req.ttl } = t, a3 = this.client.session.get(r), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), { done: d3, resolve: p3, reject: g3 } = s2.createDelayedPromise(n3, "Request expired. Please try again."); + return this.events.once(s2.engineEvent("session_request", c4), ({ error: h5, result: m3 }) => { + h5 ? g3(h5) : p3(m3); + }), await Promise.all([new Promise(async (h5) => { + await this.sendRequest({ clientRpcId: c4, relayRpcId: l4, topic: r, method: "wc_sessionRequest", params: { request: C3(S4({}, i2), { expiryTimestamp: s2.calcExpiry(n3) }), chainId: e2 }, expiry: n3, throwOnFailedPublish: true }).catch((m3) => g3(m3)), this.client.events.emit("session_request_sent", { topic: r, request: i2, chainId: e2, id: c4 }), h5(); + }), new Promise(async (h5) => { + var m3; + if (!((m3 = a3.sessionConfig) != null && m3.disableDeepLink)) { + const E4 = await s2.getDeepLink(this.client.core.storage, se); + s2.handleDeeplinkRedirect({ id: c4, topic: r, wcDeepLink: E4 }); + } + h5(); + }), d3()]).then((h5) => h5[2]); + }, this.respond = async (t) => { + await this.isInitialized(), await this.isValidRespond(t); + const { topic: e2, response: i2 } = t, { id: r } = i2; + u3.isJsonRpcResult(i2) ? await this.sendResult({ id: r, topic: e2, result: i2.result, throwOnFailedPublish: true }) : u3.isJsonRpcError(i2) && await this.sendError({ id: r, topic: e2, error: i2.error }), this.cleanupAfterResponse(t); + }, this.ping = async (t) => { + await this.isInitialized(); + try { + await this.isValidPing(t); + } catch (i2) { + throw this.client.logger.error("ping() -> isValidPing() failed"), i2; + } + const { topic: e2 } = t; + if (this.client.session.keys.includes(e2)) { + const i2 = u3.payloadId(), r = u3.getBigIntRpcId().toString(), { done: n3, resolve: a3, reject: c4 } = s2.createDelayedPromise(); + this.events.once(s2.engineEvent("session_ping", i2), ({ error: l4 }) => { + l4 ? c4(l4) : a3(); + }), await Promise.all([this.sendRequest({ topic: e2, method: "wc_sessionPing", params: {}, throwOnFailedPublish: true, clientRpcId: i2, relayRpcId: r }), n3()]); + } else + this.client.core.pairing.pairings.keys.includes(e2) && await this.client.core.pairing.ping({ topic: e2 }); + }, this.emit = async (t) => { + await this.isInitialized(), await this.isValidEmit(t); + const { topic: e2, event: i2, chainId: r } = t, n3 = u3.getBigIntRpcId().toString(); + await this.sendRequest({ topic: e2, method: "wc_sessionEvent", params: { event: i2, chainId: r }, throwOnFailedPublish: true, relayRpcId: n3 }); + }, this.disconnect = async (t) => { + await this.isInitialized(), await this.isValidDisconnect(t); + const { topic: e2 } = t; + if (this.client.session.keys.includes(e2)) + await this.sendRequest({ topic: e2, method: "wc_sessionDelete", params: s2.getSdkError("USER_DISCONNECTED"), throwOnFailedPublish: true }), await this.deleteSession({ topic: e2, emitEvent: false }); + else if (this.client.core.pairing.pairings.keys.includes(e2)) + await this.client.core.pairing.disconnect({ topic: e2 }); + else { + const { message: i2 } = s2.getInternalError("MISMATCHED_TOPIC", `Session or pairing topic not found: ${e2}`); + throw new Error(i2); + } + }, this.find = (t) => (this.isInitialized(), this.client.session.getAll().filter((e2) => s2.isSessionCompatible(e2, t))), this.getPendingSessionRequests = () => this.client.pendingRequest.getAll(), this.authenticate = async (t) => { + this.isInitialized(), this.isValidAuthenticate(t); + const { chains: e2, statement: i2 = "", uri: r, domain: n3, nonce: a3, type: c4, exp: l4, nbf: d3, methods: p3 = [] } = t, g3 = [...t.resources || []], { topic: h5, uri: m3 } = await this.client.core.pairing.create({ methods: ["wc_sessionAuthenticate"] }); + this.client.logger.info({ message: "Generated new pairing", pairing: { topic: h5, uri: m3 } }); + const E4 = await this.client.core.crypto.generateKeyPair(), R2 = s2.hashKey(E4); + if (await Promise.all([this.client.auth.authKeys.set(U2, { responseTopic: R2, publicKey: E4 }), this.client.auth.pairingTopics.set(R2, { topic: R2, pairingTopic: h5 })]), await this.client.core.relayer.subscribe(R2), this.client.logger.info(`sending request to new pairing topic: ${h5}`), p3.length > 0) { + const { namespace: v2 } = s2.parseChainId(e2[0]); + let _4 = s2.createEncodedRecap(v2, "request", p3); + s2.getRecapFromResources(g3) && (_4 = s2.mergeEncodedRecaps(_4, g3.pop())), g3.push(_4); + } + const O3 = s2.calcExpiry(q2.wc_sessionPropose.req.ttl), I2 = { authPayload: { type: c4 ?? "caip122", chains: e2, statement: i2, aud: r, domain: n3, version: "1", nonce: a3, iat: (/* @__PURE__ */ new Date()).toISOString(), exp: l4, nbf: d3, resources: g3 }, requester: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, P2 = { eip155: { chains: e2, methods: [.../* @__PURE__ */ new Set(["personal_sign", ...p3])], events: ["chainChanged", "accountsChanged"] } }, f4 = { requiredNamespaces: {}, optionalNamespaces: P2, relays: [{ protocol: "irn" }], proposer: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, { done: T2, resolve: x3, reject: Q } = s2.createDelayedPromise(q2.wc_sessionAuthenticate.req.ttl, "Request expired"), $ = async ({ error: v2, session: _4 }) => { + if (this.events.off(s2.engineEvent("session_request", D2), X), v2) + Q(v2); + else if (_4) { + _4.self.publicKey = E4, await this.client.session.set(_4.topic, _4), await this.setExpiry(_4.topic, _4.expiry), h5 && await this.client.core.pairing.updateMetadata({ topic: h5, metadata: _4.peer.metadata }); + const b4 = this.client.session.get(_4.topic); + x3({ session: b4 }); + } + }, X = async (v2) => { + if (v2.error) { + const M = s2.getSdkError("WC_METHOD_UNSUPPORTED", "wc_sessionAuthenticate"); + return v2.error.code === M.code ? void 0 : (this.events.off(s2.engineEvent("session_connect"), $), Q(v2.error.message)); + } + this.events.off(s2.engineEvent("session_connect"), $); + const { cacaos: _4, responder: b4 } = v2.result, z3 = [], re = []; + for (const M of _4) { + await s2.validateSignedCacao({ cacao: M, projectId: this.client.core.projectId }) || (this.client.logger.error(M, "Signature verification failed"), Q(s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"))); + const { p: B2 } = M, W = s2.getRecapFromResources(B2.resources), ne = [s2.getNamespacedDidChainId(B2.iss)], Re = s2.getDidAddress(B2.iss); + if (W) { + const Z = s2.getMethodsFromRecap(W), Ne = s2.getChainsFromRecap(W); + z3.push(...Z), ne.push(...Ne); + } + for (const Z of ne) + re.push(`${Z}:${Re}`); + } + const G = await this.client.core.crypto.generateSharedKey(E4, b4.publicKey); + let K2; + z3.length > 0 && (K2 = { topic: G, acknowledged: true, self: { publicKey: E4, metadata: this.client.metadata }, peer: b4, controller: b4.publicKey, expiry: s2.calcExpiry(V), requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: h5, namespaces: s2.buildNamespacesFromAuth([...new Set(z3)], [...new Set(re)]) }, await this.client.core.relayer.subscribe(G), await this.client.session.set(G, K2), K2 = this.client.session.get(G)), x3({ auths: _4, session: K2 }); + }, D2 = u3.payloadId(), J = u3.payloadId(); + this.events.once(s2.engineEvent("session_connect"), $), this.events.once(s2.engineEvent("session_request", D2), X); + try { + await Promise.all([this.sendRequest({ topic: h5, method: "wc_sessionAuthenticate", params: I2, expiry: t.expiry, throwOnFailedPublish: true, clientRpcId: D2 }), this.sendRequest({ topic: h5, method: "wc_sessionPropose", params: f4, expiry: q2.wc_sessionPropose.req.ttl, throwOnFailedPublish: true, clientRpcId: J })]); + } catch (v2) { + throw this.events.off(s2.engineEvent("session_connect"), $), this.events.off(s2.engineEvent("session_request", D2), X), v2; + } + return await this.setProposal(J, S4({ id: J }, f4)), await this.client.auth.requests.set(D2, { authPayload: I2.authPayload, requester: I2.requester, expiryTimestamp: O3, id: D2, pairingTopic: h5, verifyContext: {} }), { uri: m3, response: T2 }; + }, this.approveSessionAuthenticate = async (t) => { + this.isInitialized(); + const { id: e2, auths: i2 } = t, r = this.getPendingAuthRequest(e2); + if (!r) + throw new Error(`Could not find pending auth request with id ${e2}`); + const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }, d3 = [], p3 = []; + for (const m3 of i2) { + if (!await s2.validateSignedCacao({ cacao: m3, projectId: this.client.core.projectId })) { + const P2 = s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"); + throw await this.sendError({ id: e2, topic: c4, error: P2, encodeOpts: l4 }), new Error(P2.message); + } + const { p: E4 } = m3, R2 = s2.getRecapFromResources(E4.resources), O3 = [s2.getNamespacedDidChainId(E4.iss)], I2 = s2.getDidAddress(E4.iss); + if (R2) { + const P2 = s2.getMethodsFromRecap(R2), f4 = s2.getChainsFromRecap(R2); + d3.push(...P2), O3.push(...f4); + } + for (const P2 of O3) + p3.push(`${P2}:${I2}`); + } + const g3 = await this.client.core.crypto.generateSharedKey(a3, n3); + let h5; + return d3?.length > 0 && (h5 = { topic: g3, acknowledged: true, self: { publicKey: a3, metadata: this.client.metadata }, peer: { publicKey: n3, metadata: r.requester.metadata }, controller: n3, expiry: s2.calcExpiry(V), authentication: i2, requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: "", namespaces: s2.buildNamespacesFromAuth([...new Set(d3)], [...new Set(p3)]) }, await this.client.core.relayer.subscribe(g3), await this.client.session.set(g3, h5)), await this.sendResult({ topic: c4, id: e2, result: { cacaos: i2, responder: { publicKey: a3, metadata: this.client.metadata } }, encodeOpts: l4, throwOnFailedPublish: true }), await this.client.auth.requests.delete(e2, { message: "fullfilled", code: 0 }), await this.client.core.pairing.activate({ topic: r.pairingTopic }), { session: h5 }; + }, this.rejectSessionAuthenticate = async (t) => { + await this.isInitialized(); + const { id: e2, reason: i2 } = t, r = this.getPendingAuthRequest(e2); + if (!r) + throw new Error(`Could not find pending auth request with id ${e2}`); + const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }; + await this.sendError({ id: e2, topic: c4, error: i2, encodeOpts: l4 }), await this.client.auth.requests.delete(e2, { message: "rejected", code: 0 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")); + }, this.formatAuthMessage = (t) => { + this.isInitialized(); + const { request: e2, iss: i2 } = t; + return s2.formatMessage(e2, i2); + }, this.cleanupDuplicatePairings = async (t) => { + if (t.pairingTopic) + try { + const e2 = this.client.core.pairing.pairings.get(t.pairingTopic), i2 = this.client.core.pairing.pairings.getAll().filter((r) => { + var n3, a3; + return ((n3 = r.peerMetadata) == null ? void 0 : n3.url) && ((a3 = r.peerMetadata) == null ? void 0 : a3.url) === t.peer.metadata.url && r.topic && r.topic !== e2.topic; + }); + if (i2.length === 0) + return; + this.client.logger.info(`Cleaning up ${i2.length} duplicate pairing(s)`), await Promise.all(i2.map((r) => this.client.core.pairing.disconnect({ topic: r.topic }))), this.client.logger.info("Duplicate pairings clean up finished"); + } catch (e2) { + this.client.logger.error(e2); + } + }, this.deleteSession = async (t) => { + const { topic: e2, expirerHasDeleted: i2 = false, emitEvent: r = true, id: n3 = 0 } = t, { self: a3 } = this.client.session.get(e2); + await this.client.core.relayer.unsubscribe(e2), await this.client.session.delete(e2, s2.getSdkError("USER_DISCONNECTED")), this.addToRecentlyDeleted(e2, "session"), this.client.core.crypto.keychain.has(a3.publicKey) && await this.client.core.crypto.deleteKeyPair(a3.publicKey), this.client.core.crypto.keychain.has(e2) && await this.client.core.crypto.deleteSymKey(e2), i2 || this.client.core.expirer.del(e2), this.client.core.storage.removeItem(se).catch((c4) => this.client.logger.warn(c4)), this.getPendingSessionRequests().forEach((c4) => { + c4.topic === e2 && this.deletePendingSessionRequest(c4.id, s2.getSdkError("USER_DISCONNECTED")); + }), r && this.client.events.emit("session_delete", { id: n3, topic: e2 }); + }, this.deleteProposal = async (t, e2) => { + await Promise.all([this.client.proposal.delete(t, s2.getSdkError("USER_DISCONNECTED")), e2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "proposal"); + }, this.deletePendingSessionRequest = async (t, e2, i2 = false) => { + await Promise.all([this.client.pendingRequest.delete(t, e2), i2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "request"), this.sessionRequestQueue.queue = this.sessionRequestQueue.queue.filter((r) => r.id !== t), i2 && (this.sessionRequestQueue.state = A2.idle, this.client.events.emit("session_request_expire", { id: t })); + }, this.setExpiry = async (t, e2) => { + this.client.session.keys.includes(t) && await this.client.session.update(t, { expiry: e2 }), this.client.core.expirer.set(t, e2); + }, this.setProposal = async (t, e2) => { + await this.client.proposal.set(t, e2), this.client.core.expirer.set(t, s2.calcExpiry(q2.wc_sessionPropose.req.ttl)); + }, this.setPendingSessionRequest = async (t) => { + const { id: e2, topic: i2, params: r, verifyContext: n3 } = t, a3 = r.request.expiryTimestamp || s2.calcExpiry(q2.wc_sessionRequest.req.ttl); + await this.client.pendingRequest.set(e2, { id: e2, topic: i2, params: r, verifyContext: n3 }), a3 && this.client.core.expirer.set(e2, a3); + }, this.sendRequest = async (t) => { + const { topic: e2, method: i2, params: r, expiry: n3, relayRpcId: a3, clientRpcId: c4, throwOnFailedPublish: l4 } = t, d3 = u3.formatJsonRpcRequest(i2, r, c4); + if (s2.isBrowser() && ue.includes(i2)) { + const h5 = s2.hashMessage(JSON.stringify(d3)); + this.client.core.verify.register({ attestationId: h5 }); + } + let p3; + try { + p3 = await this.client.core.crypto.encode(e2, d3); + } catch (h5) { + throw await this.cleanup(), this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${e2} failed`), h5; + } + const g3 = q2[i2].req; + return n3 && (g3.ttl = n3), a3 && (g3.id = a3), this.client.core.history.set(e2, d3), l4 ? (g3.internal = C3(S4({}, g3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(e2, p3, g3)) : this.client.core.relayer.publish(e2, p3, g3).catch((h5) => this.client.logger.error(h5)), d3.id; + }, this.sendResult = async (t) => { + const { id: e2, topic: i2, result: r, throwOnFailedPublish: n3, encodeOpts: a3 } = t, c4 = u3.formatJsonRpcResult(e2, r); + let l4; + try { + l4 = await this.client.core.crypto.encode(i2, c4, a3); + } catch (g3) { + throw await this.cleanup(), this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i2} failed`), g3; + } + let d3; + try { + d3 = await this.client.core.history.get(i2, e2); + } catch (g3) { + throw this.client.logger.error(`sendResult() -> history.get(${i2}, ${e2}) failed`), g3; + } + const p3 = q2[d3.request.method].res; + n3 ? (p3.internal = C3(S4({}, p3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(i2, l4, p3)) : this.client.core.relayer.publish(i2, l4, p3).catch((g3) => this.client.logger.error(g3)), await this.client.core.history.resolve(c4); + }, this.sendError = async (t) => { + const { id: e2, topic: i2, error: r, encodeOpts: n3 } = t, a3 = u3.formatJsonRpcError(e2, r); + let c4; + try { + c4 = await this.client.core.crypto.encode(i2, a3, n3); + } catch (p3) { + throw await this.cleanup(), this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i2} failed`), p3; + } + let l4; + try { + l4 = await this.client.core.history.get(i2, e2); + } catch (p3) { + throw this.client.logger.error(`sendError() -> history.get(${i2}, ${e2}) failed`), p3; + } + const d3 = q2[l4.request.method].res; + this.client.core.relayer.publish(i2, c4, d3), await this.client.core.history.resolve(a3); + }, this.cleanup = async () => { + const t = [], e2 = []; + this.client.session.getAll().forEach((i2) => { + let r = false; + s2.isExpired(i2.expiry) && (r = true), this.client.core.crypto.keychain.has(i2.topic) || (r = true), r && t.push(i2.topic); + }), this.client.proposal.getAll().forEach((i2) => { + s2.isExpired(i2.expiryTimestamp) && e2.push(i2.id); + }), await Promise.all([...t.map((i2) => this.deleteSession({ topic: i2 })), ...e2.map((i2) => this.deleteProposal(i2))]); + }, this.onRelayEventRequest = async (t) => { + this.requestQueue.queue.push(t), await this.processRequestsQueue(); + }, this.processRequestsQueue = async () => { + if (this.requestQueue.state === A2.active) { + this.client.logger.info("Request queue already active, skipping..."); + return; + } + for (this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`); this.requestQueue.queue.length > 0; ) { + this.requestQueue.state = A2.active; + const t = this.requestQueue.queue.shift(); + if (t) + try { + this.processRequest(t), await new Promise((e2) => setTimeout(e2, 300)); + } catch (e2) { + this.client.logger.warn(e2); + } + } + this.requestQueue.state = A2.idle; + }, this.processRequest = (t) => { + const { topic: e2, payload: i2 } = t, r = i2.method; + if (!this.shouldIgnorePairingRequest({ topic: e2, requestMethod: r })) + switch (r) { + case "wc_sessionPropose": + return this.onSessionProposeRequest(e2, i2); + case "wc_sessionSettle": + return this.onSessionSettleRequest(e2, i2); + case "wc_sessionUpdate": + return this.onSessionUpdateRequest(e2, i2); + case "wc_sessionExtend": + return this.onSessionExtendRequest(e2, i2); + case "wc_sessionPing": + return this.onSessionPingRequest(e2, i2); + case "wc_sessionDelete": + return this.onSessionDeleteRequest(e2, i2); + case "wc_sessionRequest": + return this.onSessionRequest(e2, i2); + case "wc_sessionEvent": + return this.onSessionEventRequest(e2, i2); + case "wc_sessionAuthenticate": + return this.onSessionAuthenticateRequest(e2, i2); + default: + return this.client.logger.info(`Unsupported request method ${r}`); + } + }, this.onRelayEventResponse = async (t) => { + const { topic: e2, payload: i2 } = t, r = (await this.client.core.history.get(e2, i2.id)).request.method; + switch (r) { + case "wc_sessionPropose": + return this.onSessionProposeResponse(e2, i2); + case "wc_sessionSettle": + return this.onSessionSettleResponse(e2, i2); + case "wc_sessionUpdate": + return this.onSessionUpdateResponse(e2, i2); + case "wc_sessionExtend": + return this.onSessionExtendResponse(e2, i2); + case "wc_sessionPing": + return this.onSessionPingResponse(e2, i2); + case "wc_sessionRequest": + return this.onSessionRequestResponse(e2, i2); + case "wc_sessionAuthenticate": + return this.onSessionAuthenticateResponse(e2, i2); + default: + return this.client.logger.info(`Unsupported response method ${r}`); + } + }, this.onRelayEventUnknownPayload = (t) => { + const { topic: e2 } = t, { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Decoded payload on topic ${e2} is not identifiable as a JSON-RPC request or a response.`); + throw new Error(i2); + }, this.shouldIgnorePairingRequest = (t) => { + const { topic: e2, requestMethod: i2 } = t, r = this.expectedPairingMethodMap.get(e2); + return !r || r.includes(i2) ? false : !!(r.includes("wc_sessionAuthenticate") && this.client.events.listenerCount("session_authenticate") > 0); + }, this.onSessionProposeRequest = async (t, e2) => { + const { params: i2, id: r } = e2; + try { + this.isValidConnect(S4({}, e2.params)); + const n3 = i2.expiryTimestamp || s2.calcExpiry(q2.wc_sessionPropose.req.ttl), a3 = S4({ id: r, pairingTopic: t, expiryTimestamp: n3 }, i2); + await this.setProposal(r, a3); + const c4 = s2.hashMessage(JSON.stringify(e2)), l4 = await this.getVerifyContext(c4, a3.proposer.metadata); + this.client.events.emit("session_proposal", { id: r, params: a3, verifyContext: l4 }); + } catch (n3) { + await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionProposeResponse = async (t, e2) => { + const { id: i2 } = e2; + if (u3.isJsonRpcResult(e2)) { + const { result: r } = e2; + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", result: r }); + const n3 = this.client.proposal.get(i2); + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", proposal: n3 }); + const a3 = n3.proposer.publicKey; + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", selfPublicKey: a3 }); + const c4 = r.responderPublicKey; + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", peerPublicKey: c4 }); + const l4 = await this.client.core.crypto.generateSharedKey(a3, c4); + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", sessionTopic: l4 }); + const d3 = await this.client.core.relayer.subscribe(l4); + this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", subscriptionId: d3 }), await this.client.core.pairing.activate({ topic: t }); + } else if (u3.isJsonRpcError(e2)) { + await this.client.proposal.delete(i2, s2.getSdkError("USER_DISCONNECTED")); + const r = s2.engineEvent("session_connect"); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners, 954`); + this.events.emit(s2.engineEvent("session_connect"), { error: e2.error }); + } + }, this.onSessionSettleRequest = async (t, e2) => { + const { id: i2, params: r } = e2; + try { + this.isValidSessionSettleRequest(r); + const { relay: n3, controller: a3, expiry: c4, namespaces: l4, sessionProperties: d3, pairingTopic: p3, sessionConfig: g3 } = e2.params, h5 = S4(S4({ topic: t, relay: n3, expiry: c4, namespaces: l4, acknowledged: true, pairingTopic: p3, requiredNamespaces: {}, optionalNamespaces: {}, controller: a3.publicKey, self: { publicKey: "", metadata: this.client.metadata }, peer: { publicKey: a3.publicKey, metadata: a3.metadata } }, d3 && { sessionProperties: d3 }), g3 && { sessionConfig: g3 }); + await this.sendResult({ id: e2.id, topic: t, result: true, throwOnFailedPublish: true }); + const m3 = s2.engineEvent("session_connect"); + if (this.events.listenerCount(m3) === 0) + throw new Error(`emitting ${m3} without any listeners 997`); + this.events.emit(s2.engineEvent("session_connect"), { session: h5 }), this.cleanupDuplicatePairings(h5); + } catch (n3) { + await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionSettleResponse = async (t, e2) => { + const { id: i2 } = e2; + u3.isJsonRpcResult(e2) ? (await this.client.session.update(t, { acknowledged: true }), this.events.emit(s2.engineEvent("session_approve", i2), {})) : u3.isJsonRpcError(e2) && (await this.client.session.delete(t, s2.getSdkError("USER_DISCONNECTED")), this.events.emit(s2.engineEvent("session_approve", i2), { error: e2.error })); + }, this.onSessionUpdateRequest = async (t, e2) => { + const { params: i2, id: r } = e2; + try { + const n3 = `${t}_session_update`, a3 = s2.MemoryStore.get(n3); + if (a3 && this.isRequestOutOfSync(a3, r)) { + this.client.logger.info(`Discarding out of sync request - ${r}`), this.sendError({ id: r, topic: t, error: s2.getSdkError("INVALID_UPDATE_REQUEST") }); + return; + } + this.isValidUpdate(S4({ topic: t }, i2)); + try { + s2.MemoryStore.set(n3, r), await this.client.session.update(t, { namespaces: i2.namespaces }), await this.sendResult({ id: r, topic: t, result: true, throwOnFailedPublish: true }); + } catch (c4) { + throw s2.MemoryStore.delete(n3), c4; + } + this.client.events.emit("session_update", { id: r, topic: t, params: i2 }); + } catch (n3) { + await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.isRequestOutOfSync = (t, e2) => parseInt(e2.toString().slice(0, -3)) <= parseInt(t.toString().slice(0, -3)), this.onSessionUpdateResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_update", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_update", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_update", i2), { error: e2.error }); + }, this.onSessionExtendRequest = async (t, e2) => { + const { id: i2 } = e2; + try { + this.isValidExtend({ topic: t }), await this.setExpiry(t, s2.calcExpiry(V)), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_extend", { id: i2, topic: t }); + } catch (r) { + await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); + } + }, this.onSessionExtendResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_extend", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_extend", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_extend", i2), { error: e2.error }); + }, this.onSessionPingRequest = async (t, e2) => { + const { id: i2 } = e2; + try { + this.isValidPing({ topic: t }), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_ping", { id: i2, topic: t }); + } catch (r) { + await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); + } + }, this.onSessionPingResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_ping", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + setTimeout(() => { + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_ping", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_ping", i2), { error: e2.error }); + }, 500); + }, this.onSessionDeleteRequest = async (t, e2) => { + const { id: i2 } = e2; + try { + this.isValidDisconnect({ topic: t, reason: e2.params }), await Promise.all([new Promise((r) => { + this.client.core.relayer.once(N10.RELAYER_EVENTS.publish, async () => { + r(await this.deleteSession({ topic: t, id: i2 })); + }); + }), this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.cleanupPendingSentRequestsForTopic({ topic: t, error: s2.getSdkError("USER_DISCONNECTED") })]); + } catch (r) { + this.client.logger.error(r); + } + }, this.onSessionRequest = async (t, e2) => { + const { id: i2, params: r } = e2; + try { + await this.isValidRequest(S4({ topic: t }, r)); + const n3 = s2.hashMessage(JSON.stringify(u3.formatJsonRpcRequest("wc_sessionRequest", r, i2))), a3 = this.client.session.get(t), c4 = await this.getVerifyContext(n3, a3.peer.metadata), l4 = { id: i2, topic: t, params: r, verifyContext: c4 }; + await this.setPendingSessionRequest(l4), this.addSessionRequestToSessionRequestQueue(l4), this.processSessionRequestQueue(); + } catch (n3) { + await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionRequestResponse = (t, e2) => { + const { id: i2 } = e2, r = s2.engineEvent("session_request", i2); + if (this.events.listenerCount(r) === 0) + throw new Error(`emitting ${r} without any listeners`); + u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); + }, this.onSessionEventRequest = async (t, e2) => { + const { id: i2, params: r } = e2; + try { + const n3 = `${t}_session_event_${r.event.name}`, a3 = s2.MemoryStore.get(n3); + if (a3 && this.isRequestOutOfSync(a3, i2)) { + this.client.logger.info(`Discarding out of sync request - ${i2}`); + return; + } + this.isValidEmit(S4({ topic: t }, r)), this.client.events.emit("session_event", { id: i2, topic: t, params: r }), s2.MemoryStore.set(n3, i2); + } catch (n3) { + await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); + } + }, this.onSessionAuthenticateResponse = (t, e2) => { + const { id: i2 } = e2; + this.client.logger.trace({ type: "method", method: "onSessionAuthenticateResponse", topic: t, payload: e2 }), u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); + }, this.onSessionAuthenticateRequest = async (t, e2) => { + const { requester: i2, authPayload: r, expiryTimestamp: n3 } = e2.params, a3 = s2.hashMessage(JSON.stringify(e2)), c4 = await this.getVerifyContext(a3, this.client.metadata), l4 = { requester: i2, pairingTopic: t, id: e2.id, authPayload: r, verifyContext: c4, expiryTimestamp: n3 }; + await this.client.auth.requests.set(e2.id, l4), this.client.events.emit("session_authenticate", { topic: t, params: e2.params, id: e2.id }); + }, this.addSessionRequestToSessionRequestQueue = (t) => { + this.sessionRequestQueue.queue.push(t); + }, this.cleanupAfterResponse = (t) => { + this.deletePendingSessionRequest(t.response.id, { message: "fulfilled", code: 0 }), setTimeout(() => { + this.sessionRequestQueue.state = A2.idle, this.processSessionRequestQueue(); + }, w4.toMiliseconds(this.requestQueueDelay)); + }, this.cleanupPendingSentRequestsForTopic = ({ topic: t, error: e2 }) => { + const i2 = this.client.core.history.pending; + i2.length > 0 && i2.filter((r) => r.topic === t && r.request.method === "wc_sessionRequest").forEach((r) => { + const n3 = r.request.id, a3 = s2.engineEvent("session_request", n3); + if (this.events.listenerCount(a3) === 0) + throw new Error(`emitting ${a3} without any listeners`); + this.events.emit(s2.engineEvent("session_request", r.request.id), { error: e2 }); + }); + }, this.processSessionRequestQueue = () => { + if (this.sessionRequestQueue.state === A2.active) { + this.client.logger.info("session request queue is already active."); + return; + } + const t = this.sessionRequestQueue.queue[0]; + if (!t) { + this.client.logger.info("session request queue is empty."); + return; + } + try { + this.sessionRequestQueue.state = A2.active, this.client.events.emit("session_request", t); + } catch (e2) { + this.client.logger.error(e2); + } + }, this.onPairingCreated = (t) => { + if (t.methods && this.expectedPairingMethodMap.set(t.topic, t.methods), t.active) + return; + const e2 = this.client.proposal.getAll().find((i2) => i2.pairingTopic === t.topic); + e2 && this.onSessionProposeRequest(t.topic, u3.formatJsonRpcRequest("wc_sessionPropose", { requiredNamespaces: e2.requiredNamespaces, optionalNamespaces: e2.optionalNamespaces, relays: e2.relays, proposer: e2.proposer, sessionProperties: e2.sessionProperties }, e2.id)); + }, this.isValidConnect = async (t) => { + if (!s2.isValidParams(t)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() params: ${JSON.stringify(t)}`); + throw new Error(c4); + } + const { pairingTopic: e2, requiredNamespaces: i2, optionalNamespaces: r, sessionProperties: n3, relays: a3 } = t; + if (s2.isUndefined(e2) || await this.isValidPairingTopic(e2), !s2.isValidRelays(a3, true)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() relays: ${a3}`); + throw new Error(c4); + } + !s2.isUndefined(i2) && s2.isValidObject(i2) !== 0 && this.validateNamespaces(i2, "requiredNamespaces"), !s2.isUndefined(r) && s2.isValidObject(r) !== 0 && this.validateNamespaces(r, "optionalNamespaces"), s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); + }, this.validateNamespaces = (t, e2) => { + const i2 = s2.isValidRequiredNamespaces(t, "connect()", e2); + if (i2) + throw new Error(i2.message); + }, this.isValidApprove = async (t) => { + if (!s2.isValidParams(t)) + throw new Error(s2.getInternalError("MISSING_OR_INVALID", `approve() params: ${t}`).message); + const { id: e2, namespaces: i2, relayProtocol: r, sessionProperties: n3 } = t; + this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2); + const a3 = this.client.proposal.get(e2), c4 = s2.isValidNamespaces(i2, "approve()"); + if (c4) + throw new Error(c4.message); + const l4 = s2.isConformingNamespaces(a3.requiredNamespaces, i2, "approve()"); + if (l4) + throw new Error(l4.message); + if (!s2.isValidString(r, true)) { + const { message: d3 } = s2.getInternalError("MISSING_OR_INVALID", `approve() relayProtocol: ${r}`); + throw new Error(d3); + } + s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); + }, this.isValidReject = async (t) => { + if (!s2.isValidParams(t)) { + const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() params: ${t}`); + throw new Error(r); + } + const { id: e2, reason: i2 } = t; + if (this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2), !s2.isValidErrorReason(i2)) { + const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() reason: ${JSON.stringify(i2)}`); + throw new Error(r); + } + }, this.isValidSessionSettleRequest = (t) => { + if (!s2.isValidParams(t)) { + const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", `onSessionSettleRequest() params: ${t}`); + throw new Error(l4); + } + const { relay: e2, controller: i2, namespaces: r, expiry: n3 } = t; + if (!s2.isValidRelay(e2)) { + const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", "onSessionSettleRequest() relay protocol should be a string"); + throw new Error(l4); + } + const a3 = s2.isValidController(i2, "onSessionSettleRequest()"); + if (a3) + throw new Error(a3.message); + const c4 = s2.isValidNamespaces(r, "onSessionSettleRequest()"); + if (c4) + throw new Error(c4.message); + if (s2.isExpired(n3)) { + const { message: l4 } = s2.getInternalError("EXPIRED", "onSessionSettleRequest()"); + throw new Error(l4); + } + }, this.isValidUpdate = async (t) => { + if (!s2.isValidParams(t)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `update() params: ${t}`); + throw new Error(c4); + } + const { topic: e2, namespaces: i2 } = t; + this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); + const r = this.client.session.get(e2), n3 = s2.isValidNamespaces(i2, "update()"); + if (n3) + throw new Error(n3.message); + const a3 = s2.isConformingNamespaces(r.requiredNamespaces, i2, "update()"); + if (a3) + throw new Error(a3.message); + }, this.isValidExtend = async (t) => { + if (!s2.isValidParams(t)) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `extend() params: ${t}`); + throw new Error(i2); + } + const { topic: e2 } = t; + this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); + }, this.isValidRequest = async (t) => { + if (!s2.isValidParams(t)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() params: ${t}`); + throw new Error(c4); + } + const { topic: e2, request: i2, chainId: r, expiry: n3 } = t; + this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); + const { namespaces: a3 } = this.client.session.get(e2); + if (!s2.isValidNamespacesChainId(a3, r)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() chainId: ${r}`); + throw new Error(c4); + } + if (!s2.isValidRequest(i2)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() ${JSON.stringify(i2)}`); + throw new Error(c4); + } + if (!s2.isValidNamespacesRequest(a3, r, i2.method)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() method: ${i2.method}`); + throw new Error(c4); + } + if (n3 && !s2.isValidRequestExpiry(n3, H)) { + const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() expiry: ${n3}. Expiry must be a number (in seconds) between ${H.min} and ${H.max}`); + throw new Error(c4); + } + }, this.isValidRespond = async (t) => { + var e2; + if (!s2.isValidParams(t)) { + const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() params: ${t}`); + throw new Error(n3); + } + const { topic: i2, response: r } = t; + try { + await this.isValidSessionTopic(i2); + } catch (n3) { + throw (e2 = t?.response) != null && e2.id && this.cleanupAfterResponse(t), n3; + } + if (!s2.isValidResponse(r)) { + const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() response: ${JSON.stringify(r)}`); + throw new Error(n3); + } + }, this.isValidPing = async (t) => { + if (!s2.isValidParams(t)) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `ping() params: ${t}`); + throw new Error(i2); + } + const { topic: e2 } = t; + await this.isValidSessionOrPairingTopic(e2); + }, this.isValidEmit = async (t) => { + if (!s2.isValidParams(t)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() params: ${t}`); + throw new Error(a3); + } + const { topic: e2, event: i2, chainId: r } = t; + await this.isValidSessionTopic(e2); + const { namespaces: n3 } = this.client.session.get(e2); + if (!s2.isValidNamespacesChainId(n3, r)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() chainId: ${r}`); + throw new Error(a3); + } + if (!s2.isValidEvent(i2)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); + throw new Error(a3); + } + if (!s2.isValidNamespacesEvent(n3, r, i2.name)) { + const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); + throw new Error(a3); + } + }, this.isValidDisconnect = async (t) => { + if (!s2.isValidParams(t)) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${t}`); + throw new Error(i2); + } + const { topic: e2 } = t; + await this.isValidSessionOrPairingTopic(e2); + }, this.isValidAuthenticate = (t) => { + const { chains: e2, uri: i2, domain: r, nonce: n3 } = t; + if (!Array.isArray(e2) || e2.length === 0) + throw new Error("chains is required and must be a non-empty array"); + if (!s2.isValidString(i2, false)) + throw new Error("uri is required parameter"); + if (!s2.isValidString(r, false)) + throw new Error("domain is required parameter"); + if (!s2.isValidString(n3, false)) + throw new Error("nonce is required parameter"); + if ([...new Set(e2.map((c4) => s2.parseChainId(c4).namespace))].length > 1) + throw new Error("Multi-namespace requests are not supported. Please request single namespace only."); + const { namespace: a3 } = s2.parseChainId(e2[0]); + if (a3 !== "eip155") + throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains."); + }, this.getVerifyContext = async (t, e2) => { + const i2 = { verified: { verifyUrl: e2.verifyUrl || N10.VERIFY_SERVER, validation: "UNKNOWN", origin: e2.url || "" } }; + try { + const r = await this.client.core.verify.resolve({ attestationId: t, verifyUrl: e2.verifyUrl }); + r && (i2.verified.origin = r.origin, i2.verified.isScam = r.isScam, i2.verified.validation = r.origin === new URL(e2.url).origin ? "VALID" : "INVALID"); + } catch (r) { + this.client.logger.info(r); + } + return this.client.logger.info(`Verify context: ${JSON.stringify(i2)}`), i2; + }, this.validateSessionProps = (t, e2) => { + Object.values(t).forEach((i2) => { + if (!s2.isValidString(i2, false)) { + const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `${e2} must be in Record format. Received: ${JSON.stringify(i2)}`); + throw new Error(r); + } + }); + }, this.getPendingAuthRequest = (t) => { + const e2 = this.client.auth.requests.get(t); + return typeof e2 == "object" ? e2 : void 0; + }, this.addToRecentlyDeleted = (t, e2) => { + if (this.recentlyDeletedMap.set(t, e2), this.recentlyDeletedMap.size >= this.recentlyDeletedLimit) { + let i2 = 0; + const r = this.recentlyDeletedLimit / 2; + for (const n3 of this.recentlyDeletedMap.keys()) { + if (i2++ >= r) + break; + this.recentlyDeletedMap.delete(n3); + } + } + }, this.checkRecentlyDeleted = (t) => { + const e2 = this.recentlyDeletedMap.get(t); + if (e2) { + const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${e2}: ${t}`); + throw new Error(i2); + } + }; + } + async isInitialized() { + if (!this.initialized) { + const { message: o2 } = s2.getInternalError("NOT_INITIALIZED", this.name); + throw new Error(o2); + } + await this.client.core.relayer.confirmOnlineStateOrThrow(); + } + registerRelayerEvents() { + this.client.core.relayer.on(N10.RELAYER_EVENTS.message, async (o2) => { + const { topic: t, message: e2 } = o2, { publicKey: i2 } = this.client.auth.authKeys.keys.includes(U2) ? this.client.auth.authKeys.get(U2) : { responseTopic: void 0, publicKey: void 0 }, r = await this.client.core.crypto.decode(t, e2, { receiverPublicKey: i2 }); + try { + u3.isJsonRpcRequest(r) ? (this.client.core.history.set(t, r), this.onRelayEventRequest({ topic: t, payload: r })) : u3.isJsonRpcResponse(r) ? (await this.client.core.history.resolve(r), await this.onRelayEventResponse({ topic: t, payload: r }), this.client.core.history.delete(t, r.id)) : this.onRelayEventUnknownPayload({ topic: t, payload: r }); + } catch (n3) { + this.client.logger.error(n3); + } + }); + } + registerExpirerEvents() { + this.client.core.expirer.on(N10.EXPIRER_EVENTS.expired, async (o2) => { + const { topic: t, id: e2 } = s2.parseExpirerTarget(o2.target); + if (e2 && this.client.pendingRequest.keys.includes(e2)) + return await this.deletePendingSessionRequest(e2, s2.getInternalError("EXPIRED"), true); + t ? this.client.session.keys.includes(t) && (await this.deleteSession({ topic: t, expirerHasDeleted: true }), this.client.events.emit("session_expire", { topic: t })) : e2 && (await this.deleteProposal(e2, true), this.client.events.emit("proposal_expire", { id: e2 })); + }); + } + registerPairingEvents() { + this.client.core.pairing.events.on(N10.PAIRING_EVENTS.create, (o2) => this.onPairingCreated(o2)), this.client.core.pairing.events.on(N10.PAIRING_EVENTS.delete, (o2) => { + this.addToRecentlyDeleted(o2.topic, "pairing"); + }); + } + isValidPairingTopic(o2) { + if (!s2.isValidString(o2, false)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${o2}`); + throw new Error(t); + } + if (!this.client.core.pairing.pairings.keys.includes(o2)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${o2}`); + throw new Error(t); + } + if (s2.isExpired(this.client.core.pairing.pairings.get(o2).expiry)) { + const { message: t } = s2.getInternalError("EXPIRED", `pairing topic: ${o2}`); + throw new Error(t); + } + } + async isValidSessionTopic(o2) { + if (!s2.isValidString(o2, false)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic should be a string: ${o2}`); + throw new Error(t); + } + if (this.checkRecentlyDeleted(o2), !this.client.session.keys.includes(o2)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session topic doesn't exist: ${o2}`); + throw new Error(t); + } + if (s2.isExpired(this.client.session.get(o2).expiry)) { + await this.deleteSession({ topic: o2 }); + const { message: t } = s2.getInternalError("EXPIRED", `session topic: ${o2}`); + throw new Error(t); + } + if (!this.client.core.crypto.keychain.has(o2)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic does not exist in keychain: ${o2}`); + throw await this.deleteSession({ topic: o2 }), new Error(t); + } + } + async isValidSessionOrPairingTopic(o2) { + if (this.checkRecentlyDeleted(o2), this.client.session.keys.includes(o2)) + await this.isValidSessionTopic(o2); + else if (this.client.core.pairing.pairings.keys.includes(o2)) + this.isValidPairingTopic(o2); + else if (s2.isValidString(o2, false)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session or pairing topic doesn't exist: ${o2}`); + throw new Error(t); + } else { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session or pairing topic should be a string: ${o2}`); + throw new Error(t); + } + } + async isValidProposalId(o2) { + if (!s2.isValidId(o2)) { + const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `proposal id should be a number: ${o2}`); + throw new Error(t); + } + if (!this.client.proposal.keys.includes(o2)) { + const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `proposal id doesn't exist: ${o2}`); + throw new Error(t); + } + if (s2.isExpired(this.client.proposal.get(o2).expiryTimestamp)) { + await this.deleteProposal(o2); + const { message: t } = s2.getInternalError("EXPIRED", `proposal id: ${o2}`); + throw new Error(t); + } + } + }; + var $e = class extends N10.Store { + constructor(o2, t) { + super(o2, t, ce, F), this.core = o2, this.logger = t; + } + }; + var _e = class extends N10.Store { + constructor(o2, t) { + super(o2, t, he, F), this.core = o2, this.logger = t; + } + }; + var Ge = class extends N10.Store { + constructor(o2, t) { + super(o2, t, de, F, (e2) => e2.id), this.core = o2, this.logger = t; + } + }; + var Ke = class extends N10.Store { + constructor(o2, t) { + super(o2, t, we, L2, () => U2), this.core = o2, this.logger = t; + } + }; + var ke = class extends N10.Store { + constructor(o2, t) { + super(o2, t, ye, L2), this.core = o2, this.logger = t; + } + }; + var Fe = class extends N10.Store { + constructor(o2, t) { + super(o2, t, me, L2, (e2) => e2.id), this.core = o2, this.logger = t; + } + }; + var Ye = class { + constructor(o2, t) { + this.core = o2, this.logger = t, this.authKeys = new Ke(this.core, this.logger), this.pairingTopics = new ke(this.core, this.logger), this.requests = new Fe(this.core, this.logger); + } + async init() { + await this.authKeys.init(), await this.pairingTopics.init(), await this.requests.init(); + } + }; + var j2 = class _j extends oe.ISignClient { + constructor(o2) { + super(o2), this.protocol = ee, this.version = te, this.name = Y.name, this.events = new ae.EventEmitter(), this.on = (e2, i2) => this.events.on(e2, i2), this.once = (e2, i2) => this.events.once(e2, i2), this.off = (e2, i2) => this.events.off(e2, i2), this.removeListener = (e2, i2) => this.events.removeListener(e2, i2), this.removeAllListeners = (e2) => this.events.removeAllListeners(e2), this.connect = async (e2) => { + try { + return await this.engine.connect(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.pair = async (e2) => { + try { + return await this.engine.pair(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.approve = async (e2) => { + try { + return await this.engine.approve(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.reject = async (e2) => { + try { + return await this.engine.reject(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.update = async (e2) => { + try { + return await this.engine.update(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.extend = async (e2) => { + try { + return await this.engine.extend(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.request = async (e2) => { + try { + return await this.engine.request(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.respond = async (e2) => { + try { + return await this.engine.respond(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.ping = async (e2) => { + try { + return await this.engine.ping(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.emit = async (e2) => { + try { + return await this.engine.emit(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.disconnect = async (e2) => { + try { + return await this.engine.disconnect(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.find = (e2) => { + try { + return this.engine.find(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.getPendingSessionRequests = () => { + try { + return this.engine.getPendingSessionRequests(); + } catch (e2) { + throw this.logger.error(e2.message), e2; + } + }, this.authenticate = async (e2) => { + try { + return await this.engine.authenticate(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.formatAuthMessage = (e2) => { + try { + return this.engine.formatAuthMessage(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.approveSessionAuthenticate = async (e2) => { + try { + return await this.engine.approveSessionAuthenticate(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.rejectSessionAuthenticate = async (e2) => { + try { + return await this.engine.rejectSessionAuthenticate(e2); + } catch (i2) { + throw this.logger.error(i2.message), i2; + } + }, this.name = o2?.name || Y.name, this.metadata = o2?.metadata || s2.getAppMetadata(); + const t = typeof o2?.logger < "u" && typeof o2?.logger != "string" ? o2.logger : k4.pino(k4.getDefaultLoggerOptions({ level: o2?.logger || Y.logger })); + this.core = o2?.core || new N10.Core(o2), this.logger = k4.generateChildLogger(t, this.name), this.session = new _e(this.core, this.logger), this.proposal = new $e(this.core, this.logger), this.pendingRequest = new Ge(this.core, this.logger), this.engine = new Ue(this), this.auth = new Ye(this.core, this.logger); + } + static async init(o2) { + const t = new _j(o2); + return await t.initialize(), t; + } + get context() { + return k4.getLoggerContext(this.logger); + } + get pairing() { + return this.core.pairing.pairings; + } + async initialize() { + this.logger.trace("Initialized"); + try { + await this.core.start(), await this.session.init(), await this.proposal.init(), await this.pendingRequest.init(), await this.engine.init(), await this.auth.init(), this.core.verify.init({ verifyUrl: this.metadata.verifyUrl }), this.logger.info("SignClient Initialization Success"); + } catch (o2) { + throw this.logger.info("SignClient Initialization Failure"), this.logger.error(o2.message), o2; + } + } + }; + var He = _e; + var je = j2; + exports2.AUTH_CONTEXT = Ee, exports2.AUTH_KEYS_CONTEXT = we, exports2.AUTH_PAIRING_TOPIC_CONTEXT = ye, exports2.AUTH_PROTOCOL = ge, exports2.AUTH_PUBLIC_KEY_NAME = U2, exports2.AUTH_REQUEST_CONTEXT = me, exports2.AUTH_STORAGE_PREFIX = L2, exports2.AUTH_VERSION = De, exports2.ENGINE_CONTEXT = pe, exports2.ENGINE_QUEUE_STATES = A2, exports2.ENGINE_RPC_OPTS = q2, exports2.HISTORY_CONTEXT = Oe, exports2.HISTORY_EVENTS = ve, exports2.HISTORY_STORAGE_VERSION = Ae, exports2.METHODS_TO_VERIFY = ue, exports2.PROPOSAL_CONTEXT = ce, exports2.PROPOSAL_EXPIRY = Ve, exports2.PROPOSAL_EXPIRY_MESSAGE = le, exports2.REQUEST_CONTEXT = de, exports2.SESSION_CONTEXT = he, exports2.SESSION_EXPIRY = V, exports2.SESSION_REQUEST_EXPIRY_BOUNDARIES = H, exports2.SIGN_CLIENT_CONTEXT = ie, exports2.SIGN_CLIENT_DEFAULT = Y, exports2.SIGN_CLIENT_EVENTS = Pe, exports2.SIGN_CLIENT_PROTOCOL = ee, exports2.SIGN_CLIENT_STORAGE_OPTIONS = Te, exports2.SIGN_CLIENT_STORAGE_PREFIX = F, exports2.SIGN_CLIENT_VERSION = te, exports2.SessionStore = He, exports2.SignClient = je, exports2.WALLETCONNECT_DEEPLINK_CHOICE = se, exports2.default = j2; + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js +var require_operation2 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.OptionalOperation = exports2.Operation = void 0; + var Operation; + (function(Operation2) { + Operation2["SIGN_TRANSACTION"] = "mvx_signTransaction"; + Operation2["SIGN_TRANSACTIONS"] = "mvx_signTransactions"; + Operation2["SIGN_MESSAGE"] = "mvx_signMessage"; + })(Operation = exports2.Operation || (exports2.Operation = {})); + var OptionalOperation; + (function(OptionalOperation2) { + OptionalOperation2["SIGN_LOGIN_TOKEN"] = "mvx_signLoginToken"; + OptionalOperation2["SIGN_NATIVE_AUTH_TOKEN"] = "mvx_signNativeAuthToken"; + OptionalOperation2["CANCEL_ACTION"] = "mvx_cancelAction"; + })(OptionalOperation = exports2.OptionalOperation || (exports2.OptionalOperation = {})); + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js +var require_constants6 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = exports2.WALLETCONNECT_MULTIVERSX_METHODS = exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = void 0; + var operation_1 = require_operation2(); + exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = "mvx"; + exports2.WALLETCONNECT_MULTIVERSX_METHODS = Object.values(operation_1.Operation); + exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = Object.values(operation_1.OptionalOperation); + exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = 500; + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js +var require_errors3 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WalletConnectV2ProviderErrorMessagesEnum = exports2.ErrBadAddress = exports2.ErrNotImplemented = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + }; + exports2.Err = Err; + var ErrNotImplemented = class extends Err { + constructor() { + super("Method not yet implemented"); + } + }; + exports2.ErrNotImplemented = ErrNotImplemented; + var ErrBadAddress = class extends Err { + constructor(value, inner) { + super(`Bad address: ${value}`, inner); + } + }; + exports2.ErrBadAddress = ErrBadAddress; + var WalletConnectV2ProviderErrorMessagesEnum; + (function(WalletConnectV2ProviderErrorMessagesEnum2) { + WalletConnectV2ProviderErrorMessagesEnum2["unableToInit"] = "WalletConnect is unable to init"; + WalletConnectV2ProviderErrorMessagesEnum2["notInitialized"] = "WalletConnect is not initialized"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToConnect"] = "WalletConnect is unable to connect"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToConnectExisting"] = "WalletConnect is unable to connect to existing pairing"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToSignLoginToken"] = "WalletConnect could not sign login token"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToSign"] = "WalletConnect could not sign the message"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToLogin"] = "WalletConnect is unable to login"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleTopic"] = "WalletConnect: Unable to handle topic update"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleEvent"] = "WalletConnect: Unable to handle events"; + WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleCleanup"] = "WalletConnect: Unable to handle cleanup"; + WalletConnectV2ProviderErrorMessagesEnum2["sessionNotConnected"] = "WalletConnect Session is not connected"; + WalletConnectV2ProviderErrorMessagesEnum2["sessionDeleted"] = "WalletConnect Session Deleted"; + WalletConnectV2ProviderErrorMessagesEnum2["sessionExpired"] = "WalletConnect Session Expired"; + WalletConnectV2ProviderErrorMessagesEnum2["alreadyLoggedOut"] = "WalletConnect: Already logged out"; + WalletConnectV2ProviderErrorMessagesEnum2["pingFailed"] = "WalletConnect Ping Failed"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidAddress"] = "WalletConnect: Invalid address"; + WalletConnectV2ProviderErrorMessagesEnum2["requestDifferentChain"] = "WalletConnect: Request Chain Id different than Connection Chain Id"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageResponse"] = "WalletConnect could not sign the message"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageSignature"] = "WalletConnect: Invalid message signature"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidTransactionResponse"] = "WalletConnect could not sign the transactions. Invalid signatures"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidCustomRequestResponse"] = "WalletConnect could not send the custom request"; + WalletConnectV2ProviderErrorMessagesEnum2["transactionError"] = "Transaction canceled"; + WalletConnectV2ProviderErrorMessagesEnum2["connectionError"] = "WalletConnect could not establish a connection"; + WalletConnectV2ProviderErrorMessagesEnum2["invalidGuardian"] = "WalletConnect: Invalid Guardian"; + })(WalletConnectV2ProviderErrorMessagesEnum = exports2.WalletConnectV2ProviderErrorMessagesEnum || (exports2.WalletConnectV2ProviderErrorMessagesEnum = {})); + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js +var require_logger2 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Logger = void 0; + var Logger = class { + static error(message) { + console.error(message); + } + static trace(message) { + console.trace(message); + } + }; + exports2.Logger = Logger; + } +}); + +// node_modules/@multiversx/sdk-core/out/globals.js +var require_globals = __commonJS({ + "node_modules/@multiversx/sdk-core/out/globals.js"() { + "use strict"; + init_shim(); + if (!global.Buffer) { + global.Buffer = require_buffer2().Buffer; + } + } +}); + +// node_modules/@multiversx/sdk-core/out/smartContractQuery.js +var require_smartContractQuery = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartContractQuery.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractQueryResponse = exports2.SmartContractQuery = void 0; + var SmartContractQuery = class { + constructor(options) { + this.contract = options.contract; + this.caller = options.caller; + this.value = options.value; + this.function = options.function; + this.arguments = options.arguments; + } + }; + exports2.SmartContractQuery = SmartContractQuery; + var SmartContractQueryResponse = class { + constructor(obj) { + this.function = obj.function; + this.returnCode = obj.returnCode; + this.returnMessage = obj.returnMessage; + this.returnDataParts = obj.returnDataParts; + } + }; + exports2.SmartContractQueryResponse = SmartContractQueryResponse; + } +}); + +// node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js +var require_queryRunnerAdapter = __commonJS({ + "node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.QueryRunnerAdapter = void 0; + var address_1 = require_address(); + var smartContractQuery_1 = require_smartContractQuery(); + var QueryRunnerAdapter = class { + constructor(options) { + this.networkProvider = options.networkProvider; + } + async runQuery(query) { + const adaptedQuery = { + address: address_1.Address.fromBech32(query.contract), + caller: query.caller ? address_1.Address.fromBech32(query.caller) : void 0, + func: query.function, + value: query.value, + getEncodedArguments: () => query.arguments.map((arg) => import_buffer.Buffer.from(arg).toString("hex")) + }; + const adaptedQueryResponse = await this.networkProvider.queryContract(adaptedQuery); + return new smartContractQuery_1.SmartContractQueryResponse({ + function: query.function, + returnCode: adaptedQueryResponse.returnCode.toString(), + returnMessage: adaptedQueryResponse.returnMessage, + returnDataParts: adaptedQueryResponse.getReturnDataParts() + }); + } + }; + exports2.QueryRunnerAdapter = QueryRunnerAdapter; + } +}); + +// node_modules/@multiversx/sdk-core/out/adapters/index.js +var require_adapters = __commonJS({ + "node_modules/@multiversx/sdk-core/out/adapters/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_queryRunnerAdapter(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/converters/index.js +var require_converters = __commonJS({ + "node_modules/@multiversx/sdk-core/out/converters/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_transactionsConverter(), exports2); + } +}); + +// node_modules/@multiversx/sdk-core/out/gasEstimator.js +var require_gasEstimator = __commonJS({ + "node_modules/@multiversx/sdk-core/out/gasEstimator.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.GasEstimator = exports2.DefaultGasConfiguration = void 0; + exports2.DefaultGasConfiguration = { + minGasLimit: 5e4, + gasPerDataByte: 1500, + gasCostESDTTransfer: 2e5, + gasCostESDTNFTTransfer: 2e5, + gasCostESDTNFTMultiTransfer: 2e5 + }; + var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; + var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; + var GasEstimator = class { + constructor(gasConfiguration) { + this.gasConfiguration = gasConfiguration || exports2.DefaultGasConfiguration; + } + forEGLDTransfer(dataLength) { + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasPerDataByte * dataLength; + return gasLimit; + } + forESDTTransfer(dataLength) { + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_TRANSFER; + return gasLimit; + } + forESDTNFTTransfer(dataLength) { + const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTNFTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER; + return gasLimit; + } + forMultiESDTNFTTransfer(dataLength, numTransfers) { + const gasLimit = this.gasConfiguration.minGasLimit + (this.gasConfiguration.gasCostESDTNFTMultiTransfer + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER) * numTransfers + this.gasConfiguration.gasPerDataByte * dataLength; + return gasLimit; + } + }; + exports2.GasEstimator = GasEstimator; + } +}); + +// node_modules/@multiversx/sdk-core/out/interface.js +var require_interface2 = __commonJS({ + "node_modules/@multiversx/sdk-core/out/interface.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js +var require_interfaceOfNetwork = __commonJS({ + "node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js +var require_relayedTransactionV1Builder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RelayedTransactionV1Builder = void 0; + var address_1 = require_address(); + var errors_1 = require_errors(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var JSONbig = require_json_bigint(); + var RelayedTransactionV1Builder = class { + /** + * Sets the inner transaction to be used. It has to be already signed. + * + * @param {Transaction} transaction The inner transaction to be used + */ + setInnerTransaction(transaction) { + this.innerTransaction = transaction; + return this; + } + /** + * Sets the network config to be used for building the relayed v1 transaction + * + * @param {INetworkConfig} netConfig The network configuration to be used + */ + setNetworkConfig(netConfig) { + this.netConfig = netConfig; + return this; + } + /** + * Sets the address of the relayer (the one that will actually pay the fee) + * + * @param relayerAddress + */ + setRelayerAddress(relayerAddress) { + this.relayerAddress = relayerAddress; + return this; + } + /** + * (optional) Sets the nonce of the relayer + * + * @param relayerNonce + */ + setRelayerNonce(relayerNonce) { + this.relayerNonce = relayerNonce; + return this; + } + /** + * (optional) Sets the version of the relayed transaction + * + * @param relayedTxVersion + */ + setRelayedTransactionVersion(relayedTxVersion) { + this.relayedTransactionVersion = relayedTxVersion; + return this; + } + /** + * (optional) Sets the options of the relayed transaction + * + * @param relayedTxOptions + */ + setRelayedTransactionOptions(relayedTxOptions) { + this.relayedTransactionOptions = relayedTxOptions; + return this; + } + /** + * (optional) Sets the guardian of the relayed transaction + * + * @param relayedTxGuardian + */ + setRelayedTransactionGuardian(relayedTxGuardian) { + this.relayedTransactionGuardian = relayedTxGuardian; + return this; + } + /** + * Tries to build the relayed v1 transaction based on the previously set fields + * + * @throws ErrInvalidRelayedV1BuilderArguments + * @return Transaction + */ + build() { + if (!this.innerTransaction || !this.netConfig || !this.relayerAddress || !this.innerTransaction.getSignature()) { + throw new errors_1.ErrInvalidRelayedV1BuilderArguments(); + } + const serializedTransaction = this.prepareInnerTransaction(); + const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; + const payload = new transactionPayload_1.TransactionPayload(data); + const gasLimit = this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length() + this.innerTransaction.getGasLimit().valueOf(); + let relayedTransaction = new transaction_1.Transaction({ + nonce: this.relayerNonce, + sender: this.relayerAddress, + receiver: this.innerTransaction.getSender(), + value: 0, + gasLimit, + data: payload, + chainID: this.netConfig.ChainID, + version: this.relayedTransactionVersion, + options: this.relayedTransactionOptions, + guardian: this.relayedTransactionGuardian + }); + if (this.relayerNonce) { + relayedTransaction.setNonce(this.relayerNonce); + } + return relayedTransaction; + } + prepareInnerTransaction() { + if (!this.innerTransaction) { + return ""; + } + const txObject = { + nonce: this.innerTransaction.getNonce().valueOf(), + sender: new address_1.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"), + receiver: new address_1.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"), + value: BigInt(this.innerTransaction.getValue().toString()), + gasPrice: this.innerTransaction.getGasPrice().valueOf(), + gasLimit: this.innerTransaction.getGasLimit().valueOf(), + data: this.innerTransaction.getData().valueOf().toString("base64"), + signature: this.innerTransaction.getSignature().toString("base64"), + chainID: import_buffer.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"), + version: this.innerTransaction.getVersion().valueOf(), + options: this.innerTransaction.getOptions().valueOf() == 0 ? void 0 : this.innerTransaction.getOptions().valueOf(), + guardian: this.innerTransaction.getGuardian().bech32() ? new address_1.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64") : void 0, + guardianSignature: this.innerTransaction.getGuardianSignature().toString("hex") ? this.innerTransaction.getGuardianSignature().toString("base64") : void 0, + sndUserName: this.innerTransaction.getSenderUsername() ? import_buffer.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64") : void 0, + rcvUserName: this.innerTransaction.getReceiverUsername() ? import_buffer.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64") : void 0 + }; + return JSONbig.stringify(txObject); + } + }; + exports2.RelayedTransactionV1Builder = RelayedTransactionV1Builder; + } +}); + +// node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js +var require_relayedTransactionV2Builder = __commonJS({ + "node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.RelayedTransactionV2Builder = void 0; + var errors_1 = require_errors(); + var smartcontracts_1 = require_smartcontracts(); + var transaction_1 = require_transaction(); + var transactionPayload_1 = require_transactionPayload(); + var RelayedTransactionV2Builder = class { + /** + * Sets the inner transaction to be used. It has to be already signed and with gasLimit set to 0. These checks + * are performed on the build() method + * + * @param {Transaction} transaction The inner transaction to be used + */ + setInnerTransaction(transaction) { + this.innerTransaction = transaction; + return this; + } + /** + * Sets the gas limit to be used for the SC Call inside the inner transaction + * + * @param {IGasLimit} gasLimit The gas limit to be used. The inner transaction needs to have the gas limit set to 0, + * so this field will specify the gas to be used for the SC call of the inner transaction + */ + setInnerTransactionGasLimit(gasLimit) { + this.innerTransactionGasLimit = gasLimit; + return this; + } + /** + * Sets the network config to be used for building the relayed v2 transaction + * + * @param {INetworkConfig} netConfig The network configuration to be used + */ + setNetworkConfig(netConfig) { + this.netConfig = netConfig; + return this; + } + /** + * Sets the address of the relayer (the one that will actually pay the fee) + * + * @param relayerAddress + */ + setRelayerAddress(relayerAddress) { + this.relayerAddress = relayerAddress; + return this; + } + /** + * (optional) Sets the nonce of the relayer + * + * @param relayerNonce + */ + setRelayerNonce(relayerNonce) { + this.relayerNonce = relayerNonce; + return this; + } + /** + * Tries to build the relayed v2 transaction based on the previously set fields. + * It returns a transaction that isn't signed + * + * @throws ErrInvalidRelayedV2BuilderArguments + * @throws ErrGasLimitShouldBe0ForInnerTransaction + * @return Transaction + */ + build() { + if (!this.innerTransaction || !this.innerTransactionGasLimit || !this.relayerAddress || !this.netConfig || !this.innerTransaction.getSignature()) { + throw new errors_1.ErrInvalidRelayedV2BuilderArguments(); + } + if (this.innerTransaction.getGasLimit() != 0) { + throw new errors_1.ErrGasLimitShouldBe0ForInnerTransaction(); + } + const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ + new smartcontracts_1.AddressValue(this.innerTransaction.getReceiver()), + new smartcontracts_1.U64Value(this.innerTransaction.getNonce().valueOf()), + new smartcontracts_1.BytesValue(this.innerTransaction.getData().valueOf()), + new smartcontracts_1.BytesValue(this.innerTransaction.getSignature()) + ]); + const data = `relayedTxV2@${argumentsString}`; + const payload = new transactionPayload_1.TransactionPayload(data); + let relayedTransaction = new transaction_1.Transaction({ + sender: this.relayerAddress, + receiver: this.innerTransaction.getSender(), + value: 0, + gasLimit: this.innerTransactionGasLimit.valueOf() + this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length(), + data: payload, + chainID: this.netConfig.ChainID, + version: this.innerTransaction.getVersion(), + options: this.innerTransaction.getOptions() + }); + if (this.relayerNonce) { + relayedTransaction.setNonce(this.relayerNonce); + } + return relayedTransaction; + } + }; + exports2.RelayedTransactionV2Builder = RelayedTransactionV2Builder; + } +}); + +// node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js +var require_smartContractQueriesController = __commonJS({ + "node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.SmartContractQueriesController = void 0; + var errors_1 = require_errors(); + var smartContractQuery_1 = require_smartContractQuery(); + var smartcontracts_1 = require_smartcontracts(); + var SmartContractQueriesController = class { + constructor(options) { + this.abi = options.abi; + this.queryRunner = options.queryRunner; + this.legacyResultsParser = new smartcontracts_1.ResultsParser(); + } + createQuery(options) { + const preparedArguments = this.encodeArguments(options.function, options.arguments); + return new smartContractQuery_1.SmartContractQuery({ + contract: options.contract, + caller: options.caller, + function: options.function, + arguments: preparedArguments, + value: options.value + }); + } + encodeArguments(functionName, args) { + const endpoint = this.abi?.getEndpoint(functionName); + if (endpoint) { + const typedArgs = smartcontracts_1.NativeSerializer.nativeToTypedValues(args, endpoint); + return new smartcontracts_1.ArgSerializer().valuesToBuffers(typedArgs); + } + if (this.areArgsOfTypedValue(args)) { + return new smartcontracts_1.ArgSerializer().valuesToBuffers(args); + } + if (this.areArgsBuffers(args)) { + return args.map((arg) => import_buffer.Buffer.from(arg)); + } + throw new errors_1.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers"); + } + areArgsOfTypedValue(args) { + for (const arg of args) { + if (!arg.belongsToTypesystem) { + return false; + } + } + return true; + } + areArgsBuffers(args) { + for (const arg of args) { + if (!ArrayBuffer.isView(arg)) { + return false; + } + } + return true; + } + async runQuery(query) { + const queryResponse = await this.queryRunner.runQuery(query); + return queryResponse; + } + parseQueryResponse(response) { + if (!this.abi) { + return response.returnDataParts; + } + const legacyQueryResponse = { + returnCode: response.returnCode, + returnMessage: response.returnMessage, + getReturnDataParts: () => response.returnDataParts.map((part) => import_buffer.Buffer.from(part)) + }; + const functionName = response.function; + const endpoint = this.abi.getEndpoint(functionName); + const legacyBundle = this.legacyResultsParser.parseQueryResponse(legacyQueryResponse, endpoint); + const nativeValues = legacyBundle.values.map((value) => value.valueOf()); + return nativeValues; + } + }; + exports2.SmartContractQueriesController = SmartContractQueriesController; + } +}); + +// node_modules/@multiversx/sdk-core/out/index.js +var require_out = __commonJS({ + "node_modules/@multiversx/sdk-core/out/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + require_globals(); + __exportStar2(require_account(), exports2); + __exportStar2(require_adapters(), exports2); + __exportStar2(require_address(), exports2); + __exportStar2(require_asyncTimer(), exports2); + __exportStar2(require_converters(), exports2); + __exportStar2(require_errors(), exports2); + __exportStar2(require_gasEstimator(), exports2); + __exportStar2(require_interface2(), exports2); + __exportStar2(require_interfaceOfNetwork(), exports2); + __exportStar2(require_logger(), exports2); + __exportStar2(require_message(), exports2); + __exportStar2(require_networkParams(), exports2); + __exportStar2(require_relayedTransactionV1Builder(), exports2); + __exportStar2(require_relayedTransactionV2Builder(), exports2); + __exportStar2(require_signableMessage(), exports2); + __exportStar2(require_smartContractQueriesController(), exports2); + __exportStar2(require_smartcontracts(), exports2); + __exportStar2(require_tokenOperations(), exports2); + __exportStar2(require_tokens(), exports2); + __exportStar2(require_transaction(), exports2); + __exportStar2(require_transactionComputer(), exports2); + __exportStar2(require_transactionPayload(), exports2); + __exportStar2(require_transactionWatcher(), exports2); + __exportStar2(require_transactionsFactories(), exports2); + __exportStar2(require_transactionsOutcomeParsers(), exports2); + __exportStar2(require_utils2(), exports2); + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js +var require_utils4 = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.sleep = exports2.getMetadata = exports2.applyTransactionSignature = exports2.getAddressFromSession = exports2.addressIsValid = exports2.getConnectionParams = exports2.getCurrentTopic = exports2.getCurrentSession = void 0; + var sdk_core_1 = require_out(); + var signature_1 = require_signature(); + var utils_1 = require_index_cjs2(); + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + var logger_1 = require_logger2(); + var operation_1 = require_operation2(); + function getCurrentSession(chainId, client) { + if (!client) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + const acknowledgedSessions = client.find(getConnectionParams(chainId)).filter((s2) => s2.acknowledged); + if (acknowledgedSessions.length > 0) { + const lastKeyIndex = acknowledgedSessions.length - 1; + const session = acknowledgedSessions[lastKeyIndex]; + return session; + } + if (client.session.length > 0) { + const lastKeyIndex = client.session.keys.length - 1; + const session = client.session.get(client.session.keys[lastKeyIndex]); + return session; + } + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + exports2.getCurrentSession = getCurrentSession; + function getCurrentTopic(chainId, client) { + if (!client) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + const session = getCurrentSession(chainId, client); + if (!(session === null || session === void 0 ? void 0 : session.topic)) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + return session.topic; + } + exports2.getCurrentTopic = getCurrentTopic; + function getConnectionParams(chainId, options) { + var _a, _b, _c; + const methods = [ + ...constants_1.WALLETCONNECT_MULTIVERSX_METHODS, + ...(_a = options === null || options === void 0 ? void 0 : options.methods) !== null && _a !== void 0 ? _a : [] + ]; + if (!((_b = options === null || options === void 0 ? void 0 : options.methods) === null || _b === void 0 ? void 0 : _b.includes(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN))) { + methods.push(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN); + } + const chains = [`${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${chainId}`]; + const events = (_c = options === null || options === void 0 ? void 0 : options.events) !== null && _c !== void 0 ? _c : []; + return { + requiredNamespaces: { + [constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]: { + methods, + chains, + events + } + } + }; + } + exports2.getConnectionParams = getConnectionParams; + function addressIsValid(destinationAddress) { + try { + const address = sdk_core_1.Address.fromBech32(destinationAddress); + return !address.isEmpty(); + } catch (_a) { + return false; + } + } + exports2.addressIsValid = addressIsValid; + function getAddressFromSession(session) { + const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; + if (selectedNamespace && selectedNamespace.accounts) { + const currentSession = selectedNamespace.accounts[0]; + const [namespace, reference, address] = currentSession.split(":"); + return address; + } + return ""; + } + exports2.getAddressFromSession = getAddressFromSession; + function applyTransactionSignature({ transaction, response }) { + if (!response) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + } + const { signature, guardianSignature, version: version2, options, guardian } = response; + const transactionGuardian = transaction.getGuardian().bech32(); + if (transactionGuardian && transactionGuardian !== guardian) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); + } + if (guardian) { + transaction.setGuardian(sdk_core_1.Address.fromBech32(guardian)); + } + if (version2) { + transaction.setVersion(version2); + } + if (options != null) { + transaction.setOptions(options); + } + transaction.applySignature(new signature_1.Signature(signature)); + if (guardianSignature) { + transaction.applyGuardianSignature(new signature_1.Signature(guardianSignature)); + } + return transaction; + } + exports2.applyTransactionSignature = applyTransactionSignature; + function getMetadata(metadata) { + if (metadata) { + return Object.assign(Object.assign({}, metadata), { url: utils_1.getAppMetadata().url }); + } + return; + } + exports2.getMetadata = getMetadata; + function sleep(timeout) { + return __awaiter2(this, void 0, void 0, function* () { + return yield new Promise((resolve) => setTimeout(() => { + resolve(); + }, timeout)); + }); + } + exports2.sleep = sleep; + } +}); + +// node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js +var require_walletConnectV2Provider = __commonJS({ + "node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WalletConnectV2Provider = exports2.OptionalOperation = exports2.Operation = exports2.WalletConnectV2ProviderErrorMessagesEnum = void 0; + var signature_1 = require_signature(); + var sign_client_1 = __importDefault2(require_index_cjs4()); + var utils_1 = require_index_cjs2(); + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + Object.defineProperty(exports2, "WalletConnectV2ProviderErrorMessagesEnum", { enumerable: true, get: function() { + return errors_1.WalletConnectV2ProviderErrorMessagesEnum; + } }); + var logger_1 = require_logger2(); + var operation_1 = require_operation2(); + Object.defineProperty(exports2, "Operation", { enumerable: true, get: function() { + return operation_1.Operation; + } }); + Object.defineProperty(exports2, "OptionalOperation", { enumerable: true, get: function() { + return operation_1.OptionalOperation; + } }); + var utils_2 = require_utils4(); + var WalletConnectV2Provider5 = class { + constructor(onClientConnect, chainId, walletConnectV2Relay, walletConnectV2ProjectId, options) { + this.chainId = ""; + this.address = ""; + this.signature = ""; + this.isInitializing = false; + this.processingTopic = ""; + this.options = {}; + this.onClientConnect = onClientConnect; + this.chainId = chainId; + this.walletConnectV2Relay = walletConnectV2Relay; + this.walletConnectV2ProjectId = walletConnectV2ProjectId; + this.options = options; + } + reset() { + this.address = ""; + this.signature = ""; + this.walletConnector = void 0; + this.session = void 0; + this.pairings = void 0; + } + /** + * Initiates WalletConnect client. + */ + init() { + var _a, _b; + return __awaiter2(this, void 0, void 0, function* () { + if (this.isInitialized()) { + return this.isInitialized(); + } else { + try { + if (!this.isInitializing) { + this.isInitializing = true; + this.reset(); + const metadata = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.metadata) ? { + metadata: utils_2.getMetadata((_b = this.options) === null || _b === void 0 ? void 0 : _b.metadata) + } : {}; + const client = yield sign_client_1.default.init(Object.assign(Object.assign(Object.assign({}, this.options), { relayUrl: this.walletConnectV2Relay, projectId: this.walletConnectV2ProjectId }), metadata)); + this.walletConnector = client; + this.isInitializing = false; + yield this.subscribeToEvents(client); + yield this.checkPersistedState(client); + } + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToInit); + } finally { + this.isInitializing = false; + return this.isInitialized(); + } + } + }); + } + /** + * Returns true if init() was previously called successfully + */ + isInitialized() { + return !!this.walletConnector && !this.isInitializing; + } + /** + * Returns true if provider is initialized and a valid session is set + */ + isConnected() { + return new Promise((resolve, _4) => resolve(Boolean(this.isInitialized() && typeof this.session !== "undefined"))); + } + connect(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + const connectParams = utils_2.getConnectionParams(this.chainId, options); + try { + const response = yield this.walletConnector.connect(Object.assign({ pairingTopic: options === null || options === void 0 ? void 0 : options.topic }, connectParams)); + return response; + } catch (error) { + this.reset(); + logger_1.Logger.error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); + throw new Error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); + } + }); + } + login(options) { + var _a; + return __awaiter2(this, void 0, void 0, function* () { + this.isInitializing = true; + if (typeof this.walletConnector === "undefined") { + yield this.connect(); + } + if (typeof this.walletConnector === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session !== "undefined") { + yield this.logout({ topic: (_a = this.session) === null || _a === void 0 ? void 0 : _a.topic }); + } + try { + if (options && options.approval) { + const session = yield options.approval(); + if (options.token) { + yield utils_2.sleep(constants_1.WALLETCONNECT_SIGN_LOGIN_DELAY); + const address = utils_2.getAddressFromSession(session); + const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; + const method = selectedNamespace.methods.includes(operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN) ? operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN : operation_1.OptionalOperation.SIGN_LOGIN_TOKEN; + const { signature } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: session.topic, + request: { + method, + params: { + token: options.token, + address + } + } + }); + if (!signature) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); + } + return yield this.onSessionConnected({ + session, + signature + }); + } + return yield this.onSessionConnected({ + session, + signature: "" + }); + } + } catch (error) { + this.reset(); + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); + } finally { + this.isInitializing = false; + } + return ""; + }); + } + /** + * Mocks a logout request by returning true + */ + logout(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + try { + if (this.processingTopic === ((options === null || options === void 0 ? void 0 : options.topic) || utils_2.getCurrentTopic(this.chainId, this.walletConnector))) { + return true; + } + if (options === null || options === void 0 ? void 0 : options.topic) { + this.processingTopic = options.topic; + yield this.walletConnector.disconnect({ + topic: options.topic, + reason: utils_1.getSdkError("USER_DISCONNECTED") + }); + } else { + const currentSessionTopic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); + this.processingTopic = currentSessionTopic; + yield this.walletConnector.disconnect({ + topic: currentSessionTopic, + reason: utils_1.getSdkError("USER_DISCONNECTED") + }); + this.reset(); + yield this.cleanupPendingPairings({ deletePairings: true }); + } + } catch (_a) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut); + } finally { + this.processingTopic = ""; + } + return true; + }); + } + /** + * Fetches the WalletConnect address + */ + getAddress() { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + return this.address; + }); + } + /** + * Fetches the WalletConnect signature + */ + getSignature() { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + return this.signature; + }); + } + /** + * Fetches the WalletConnect pairings + */ + getPairings() { + var _a, _b, _c, _d, _e; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + return (_e = (_d = (_c = (_b = (_a = this.walletConnector) === null || _a === void 0 ? void 0 : _a.core) === null || _b === void 0 ? void 0 : _b.pairing) === null || _c === void 0 ? void 0 : _c.pairings) === null || _d === void 0 ? void 0 : _d.getAll({ active: true })) !== null && _e !== void 0 ? _e : []; + }); + } + /** + * Signs a message and returns it signed + * @param message + */ + signMessage(message) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + try { + const address = yield this.getAddress(); + const { signature } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: { + method: operation_1.Operation.SIGN_MESSAGE, + params: { + address, + message: message.message.toString() + } + } + }); + if (!signature) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); + } + try { + message.applySignature(new signature_1.Signature(signature)); + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); + } + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSign); + } + return message; + }); + } + /** + * Signs a transaction and returns it signed + * @param transaction + */ + signTransaction(transaction) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + const plainTransaction = transaction.toPlainObject(); + if (this.chainId !== transaction.getChainID().valueOf()) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + } + try { + const response = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: { + method: operation_1.Operation.SIGN_TRANSACTION, + params: { + transaction: plainTransaction + } + } + }); + return utils_2.applyTransactionSignature({ transaction, response }); + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); + } + }); + } + /** + * Signs an array of transactions and returns it signed + * @param transactions + */ + signTransactions(transactions) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + const plainTransactions = transactions.map((transaction) => { + if (this.chainId !== transaction.getChainID().valueOf()) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); + } + return transaction.toPlainObject(); + }); + try { + const { signatures } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: { + method: operation_1.Operation.SIGN_TRANSACTIONS, + params: { + transactions: plainTransactions + } + } + }); + if (!signatures) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + } + if (!Array.isArray(signatures) || transactions.length !== signatures.length) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); + } + for (const [index, transaction] of transactions.entries()) { + const response = signatures[index]; + utils_2.applyTransactionSignature({ transaction, response }); + } + return transactions; + } catch (error) { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); + } + }); + } + /** + * Sends a custom request + * @param request + */ + sendCustomRequest(options) { + var _a; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + this.onClientConnect.onClientLogout(); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + if ((_a = options === null || options === void 0 ? void 0 : options.request) === null || _a === void 0 ? void 0 : _a.method) { + try { + const request = Object.assign({}, options.request); + let { method } = request; + const { response } = yield this.walletConnector.request({ + chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, + topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), + request: Object.assign(Object.assign({}, request), { method }) + }); + if (!response) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); + } + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); + } + return; + } + }); + } + /** + * Ping helper + */ + ping() { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (typeof this.session === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); + } + try { + const topic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); + yield this.walletConnector.ping({ + topic + }); + return true; + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.pingFailed); + return false; + } + }); + } + loginAccount(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (!options) { + return ""; + } + if (utils_2.addressIsValid(options.address)) { + this.address = options.address; + if (options.signature) { + this.signature = options.signature; + } + this.onClientConnect.onClientLogin(); + return this.address; + } + logger_1.Logger.error(`${errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${options.address}`); + if (this.walletConnector) { + yield this.logout(); + } + return ""; + }); + } + onSessionConnected(options) { + return __awaiter2(this, void 0, void 0, function* () { + if (!options) { + return ""; + } + this.session = options.session; + const address = utils_2.getAddressFromSession(options.session); + if (address) { + yield this.loginAccount({ address, signature: options.signature }); + return address; + } + return ""; + }); + } + handleTopicUpdateEvent({ topic }) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + return; + } + try { + const existingPairings = yield this.getPairings(); + if (this.address && !this.isInitializing && existingPairings) { + if ((existingPairings === null || existingPairings === void 0 ? void 0 : existingPairings.length) === 0) { + this.onClientConnect.onClientLogout(); + } else { + const lastActivePairing = existingPairings[existingPairings.length - 1]; + if ((lastActivePairing === null || lastActivePairing === void 0 ? void 0 : lastActivePairing.topic) === topic) { + this.onClientConnect.onClientLogout(); + } + } + } + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic); + } finally { + this.pairings = yield this.getPairings(); + } + }); + } + handleSessionEvents({ topic, params }) { + var _a; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + if (this.session && ((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) !== topic) { + return; + } + const { event } = params; + if ((event === null || event === void 0 ? void 0 : event.name) && utils_2.getCurrentTopic(this.chainId, this.walletConnector) === topic) { + const eventData = event.data; + this.onClientConnect.onClientEvent(eventData); + } + }); + } + subscribeToEvents(client) { + var _a, _b, _c, _d; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof client === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + try { + client.on("session_update", ({ topic, params }) => { + var _a2; + if (!this.session || ((_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.topic) !== topic) { + return; + } + const { namespaces } = params; + const _session = client.session.get(topic); + const updatedSession = Object.assign(Object.assign({}, _session), { namespaces }); + this.onSessionConnected({ session: updatedSession }); + }); + client.on("session_event", this.handleSessionEvents.bind(this)); + client.on("session_delete", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { + var _e; + if (this.isInitializing) { + this.onClientConnect.onClientLogout(); + this.reset(); + } + if (!this.session || ((_e = this.session) === null || _e === void 0 ? void 0 : _e.topic) !== topic) { + return; + } + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted); + this.onClientConnect.onClientLogout(); + this.reset(); + yield this.cleanupPendingPairings({ deletePairings: true }); + })); + client.on("session_expire", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { + var _f; + if (!this.session || ((_f = this.session) === null || _f === void 0 ? void 0 : _f.topic) !== topic) { + return; + } + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired); + this.onClientConnect.onClientLogout(); + this.reset(); + yield this.cleanupPendingPairings({ deletePairings: true }); + })); + (_b = (_a = client.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.events.on("pairing_delete", this.handleTopicUpdateEvent.bind(this)); + (_d = (_c = client.core) === null || _c === void 0 ? void 0 : _c.pairing) === null || _d === void 0 ? void 0 : _d.events.on("pairing_expire", this.handleTopicUpdateEvent.bind(this)); + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent); + } + }); + } + checkPersistedState(client) { + return __awaiter2(this, void 0, void 0, function* () { + if (typeof client === "undefined") { + throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); + } + this.pairings = yield this.getPairings(); + if (typeof this.session !== "undefined") { + return; + } + if (client.session.length && !this.address && !this.isInitializing) { + const session = utils_2.getCurrentSession(this.chainId, client); + if (session) { + yield this.onSessionConnected({ session }); + return session; + } + } + return; + }); + } + cleanupPendingPairings(options = {}) { + var _a, _b, _c, _d, _e, _f, _g, _h; + return __awaiter2(this, void 0, void 0, function* () { + if (typeof this.walletConnector === "undefined") { + return; + } + try { + const inactivePairings = (_c = (_b = (_a = this.walletConnector.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.pairings) === null || _c === void 0 ? void 0 : _c.getAll({ active: false }); + if (!utils_1.isValidArray(inactivePairings)) { + return; + } + for (const pairing of inactivePairings) { + if (options.deletePairings) { + (_e = (_d = this.walletConnector.core) === null || _d === void 0 ? void 0 : _d.expirer) === null || _e === void 0 ? void 0 : _e.set(pairing.topic, 0); + } else { + try { + yield (_h = (_g = (_f = this.walletConnector.core) === null || _f === void 0 ? void 0 : _f.relayer) === null || _g === void 0 ? void 0 : _g.subscriber) === null || _h === void 0 ? void 0 : _h.unsubscribe(pairing.topic); + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); + } + } + } + } catch (error) { + logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); + } + }); + } + }; + exports2.WalletConnectV2Provider = WalletConnectV2Provider5; + } +}); + +// node_modules/has-symbols/shams.js +var require_shams = __commonJS({ + "node_modules/has-symbols/shams.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function hasSymbols() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/has-symbols/index.js +var require_has_symbols = __commonJS({ + "node_modules/has-symbols/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = require_shams(); + module2.exports = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + } +}); + +// node_modules/has-proto/index.js +var require_has_proto = __commonJS({ + "node_modules/has-proto/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var test = { + foo: {} + }; + var $Object = Object; + module2.exports = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); + }; + } +}); + +// node_modules/function-bind/implementation.js +var require_implementation = __commonJS({ + "node_modules/function-bind/implementation.js"(exports2, module2) { + "use strict"; + init_shim(); + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a3, b4) { + var arr = []; + for (var i2 = 0; i2 < a3.length; i2 += 1) { + arr[i2] = a3[i2]; + } + for (var j2 = 0; j2 < b4.length; j2 += 1) { + arr[j2 + a3.length] = b4[j2]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i2 = offset || 0, j2 = 0; i2 < arrLike.length; i2 += 1, j2 += 1) { + arr[j2] = arrLike[i2]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i2 = 0; i2 < arr.length; i2 += 1) { + str += arr[i2]; + if (i2 + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + module2.exports = function bind(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i2 = 0; i2 < boundLength; i2++) { + boundArgs[i2] = "$" + i2; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + } +}); + +// node_modules/function-bind/index.js +var require_function_bind = __commonJS({ + "node_modules/function-bind/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var implementation = require_implementation(); + module2.exports = Function.prototype.bind || implementation; + } +}); + +// node_modules/hasown/index.js +var require_hasown = __commonJS({ + "node_modules/hasown/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind = require_function_bind(); + module2.exports = bind.call(call, $hasOwn); + } +}); + +// node_modules/get-intrinsic/index.js +var require_get_intrinsic = __commonJS({ + "node_modules/get-intrinsic/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var undefined2; + var $SyntaxError = SyntaxError; + var $Function = Function; + var $TypeError = TypeError; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e2) { + } + }; + var $gOPD = Object.getOwnPropertyDescriptor; + if ($gOPD) { + try { + $gOPD({}, ""); + } catch (e2) { + $gOPD = null; + } + } + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }() : throwTypeError; + var hasSymbols = require_has_symbols()(); + var hasProto = require_has_proto()(); + var getProto = Object.getPrototypeOf || (hasProto ? function(x3) { + return x3.__proto__; + } : null); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); + var INTRINSICS = { + "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, + "%AsyncFromSyncIteratorPrototype%": undefined2, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": EvalError, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, + "%JSON%": typeof JSON === "object" ? JSON : undefined2, + "%Map%": typeof Map === "undefined" ? undefined2 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": Object, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, + "%RangeError%": RangeError, + "%ReferenceError%": ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined2 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, + "%Symbol%": hasSymbols ? Symbol : undefined2, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, + "%URIError%": URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet + }; + if (getProto) { + try { + null.error; + } catch (e2) { + errorProto = getProto(getProto(e2)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var errorProto; + var doEval = function doEval2(name2) { + var value; + if (name2 === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name2 === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name2 === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name2 === "%AsyncGenerator%") { + var fn = doEval2("%AsyncGeneratorFunction%"); + if (fn) { + value = fn.prototype; + } + } else if (name2 === "%AsyncIteratorPrototype%") { + var gen = doEval2("%AsyncGenerator%"); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + INTRINSICS[name2] = value; + return value; + }; + var LEGACY_ALIASES = { + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind = require_function_bind(); + var hasOwn = require_hasown(); + var $concat = bind.call(Function.call, Array.prototype.concat); + var $spliceApply = bind.call(Function.apply, Array.prototype.splice); + var $replace = bind.call(Function.call, String.prototype.replace); + var $strSlice = bind.call(Function.call, String.prototype.slice); + var $exec = bind.call(Function.call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string2) { + var first = $strSlice(string2, 0, 1); + var last = $strSlice(string2, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string2, rePropName, function(match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) { + var intrinsicName = name2; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name2 + " does not exist!"); + }; + module2.exports = function GetIntrinsic(name2, allowMissing) { + if (typeof name2 !== "string" || name2.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name2) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name2); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i2 = 1, isOwn = true; i2 < parts.length; i2 += 1) { + var part = parts[i2]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available."); + } + return void 0; + } + if ($gOPD && i2 + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + } +}); + +// node_modules/has-property-descriptors/index.js +var require_has_property_descriptors = __commonJS({ + "node_modules/has-property-descriptors/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasPropertyDescriptors = function hasPropertyDescriptors2() { + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + return true; + } catch (e2) { + return false; + } + } + return false; + }; + hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + if (!hasPropertyDescriptors()) { + return null; + } + try { + return $defineProperty([], "length", { value: 1 }).length !== 1; + } catch (e2) { + return true; + } + }; + module2.exports = hasPropertyDescriptors; + } +}); + +// node_modules/gopd/index.js +var require_gopd = __commonJS({ + "node_modules/gopd/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e2) { + $gOPD = null; + } + } + module2.exports = $gOPD; + } +}); + +// node_modules/define-data-property/index.js +var require_define_data_property = __commonJS({ + "node_modules/define-data-property/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var hasPropertyDescriptors = require_has_property_descriptors()(); + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = hasPropertyDescriptors && GetIntrinsic("%Object.defineProperty%", true); + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e2) { + $defineProperty = false; + } + } + var $SyntaxError = GetIntrinsic("%SyntaxError%"); + var $TypeError = GetIntrinsic("%TypeError%"); + var gopd = require_gopd(); + module2.exports = function defineDataProperty(obj, property, value) { + if (!obj || typeof obj !== "object" && typeof obj !== "function") { + throw new $TypeError("`obj` must be an object or a function`"); + } + if (typeof property !== "string" && typeof property !== "symbol") { + throw new $TypeError("`property` must be a string or a symbol`"); + } + if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) { + throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null"); + } + if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) { + throw new $TypeError("`nonWritable`, if provided, must be a boolean or null"); + } + if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) { + throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null"); + } + if (arguments.length > 6 && typeof arguments[6] !== "boolean") { + throw new $TypeError("`loose`, if provided, must be a boolean"); + } + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + var desc = !!gopd && gopd(obj, property); + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) { + obj[property] = value; + } else { + throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable."); + } + }; + } +}); + +// node_modules/set-function-length/index.js +var require_set_function_length = __commonJS({ + "node_modules/set-function-length/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var define2 = require_define_data_property(); + var hasDescriptors = require_has_property_descriptors()(); + var gOPD = require_gopd(); + var $TypeError = GetIntrinsic("%TypeError%"); + var $floor = GetIntrinsic("%Math.floor%"); + module2.exports = function setFunctionLength(fn, length2) { + if (typeof fn !== "function") { + throw new $TypeError("`fn` is not a function"); + } + if (typeof length2 !== "number" || length2 < 0 || length2 > 4294967295 || $floor(length2) !== length2) { + throw new $TypeError("`length` must be a positive 32-bit integer"); + } + var loose = arguments.length > 2 && !!arguments[2]; + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ("length" in fn && gOPD) { + var desc = gOPD(fn, "length"); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define2( + /** @type {Parameters[0]} */ + fn, + "length", + length2, + true, + true + ); + } else { + define2( + /** @type {Parameters[0]} */ + fn, + "length", + length2 + ); + } + } + return fn; + }; + } +}); + +// node_modules/call-bind/index.js +var require_call_bind = __commonJS({ + "node_modules/call-bind/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var bind = require_function_bind(); + var GetIntrinsic = require_get_intrinsic(); + var setFunctionLength = require_set_function_length(); + var $TypeError = GetIntrinsic("%TypeError%"); + var $apply = GetIntrinsic("%Function.prototype.apply%"); + var $call = GetIntrinsic("%Function.prototype.call%"); + var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind.call($call, $apply); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var $max = GetIntrinsic("%Math.max%"); + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e2) { + $defineProperty = null; + } + } + module2.exports = function callBind(originalFunction) { + if (typeof originalFunction !== "function") { + throw new $TypeError("a function is required"); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); + }; + var applyBind = function applyBind2() { + return $reflectApply(bind, $apply, arguments); + }; + if ($defineProperty) { + $defineProperty(module2.exports, "apply", { value: applyBind }); + } else { + module2.exports.apply = applyBind; + } + } +}); + +// node_modules/call-bind/callBound.js +var require_callBound = __commonJS({ + "node_modules/call-bind/callBound.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var callBind = require_call_bind(); + var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf")); + module2.exports = function callBoundIntrinsic(name2, allowMissing) { + var intrinsic = GetIntrinsic(name2, !!allowMissing); + if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) { + return callBind(intrinsic); + } + return intrinsic; + }; + } +}); + +// (disabled):node_modules/object-inspect/util.inspect +var require_util2 = __commonJS({ + "(disabled):node_modules/object-inspect/util.inspect"() { + init_shim(); + } +}); + +// node_modules/object-inspect/index.js +var require_object_inspect = __commonJS({ + "node_modules/object-inspect/index.js"(exports2, module2) { + init_shim(); + var hasMap = typeof Map === "function" && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === "function" && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; + var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O3) { + return O3.__proto__; + } : null); + function addNumericSeparator(num, str) { + if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === "number") { + var int = num < 0 ? -$floor(-num) : $floor(num); + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); + } + } + return $replace.call(str, sepRegex, "$&_"); + } + var utilInspect = require_util2(); + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + module2.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, "customInspect") ? opts.customInspect : true; + if (typeof customInspect !== "boolean" && customInspect !== "symbol") { + throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); + } + if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + if (typeof obj === "boolean") { + return obj ? "true" : "false"; + } + if (typeof obj === "string") { + return inspectString(obj, opts); + } + if (typeof obj === "number") { + if (obj === 0) { + return Infinity / obj > 0 ? "0" : "-0"; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === "bigint") { + var bigIntStr = String(obj) + "n"; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; + if (typeof depth === "undefined") { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { + return isArray(obj) ? "[Array]" : "[Object]"; + } + var indent = getIndent(opts, depth); + if (typeof seen === "undefined") { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return "[Circular]"; + } + function inspect(value, from3, noIndent) { + if (from3) { + seen = $arrSlice.call(seen); + seen.push(from3); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, "quoteStyle")) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === "function" && !isRegExp(obj)) { + var name2 = nameOf(obj); + var keys2 = arrObjKeys(obj, inspect); + return "[Function" + (name2 ? ": " + name2 : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : ""); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); + return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s2 = "<" + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i2 = 0; i2 < attrs.length; i2++) { + s2 += " " + attrs[i2].name + "=" + wrapQuotes(quote(attrs[i2].value), "double", opts); + } + s2 += ">"; + if (obj.childNodes && obj.childNodes.length) { + s2 += "..."; + } + s2 += ""; + return s2; + } + if (isArray(obj)) { + if (obj.length === 0) { + return "[]"; + } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return "[" + indentedJoin(xs, indent) + "]"; + } + return "[ " + $join.call(xs, ", ") + " ]"; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { + return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; + } + if (parts.length === 0) { + return "[" + String(obj) + "]"; + } + return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; + } + if (typeof obj === "object" && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function(value, key) { + mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); + }); + } + return collectionOf("Map", mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function(value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf("Set", setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf("WeakMap"); + } + if (isWeakSet(obj)) { + return weakCollectionOf("WeakSet"); + } + if (isWeakRef(obj)) { + return weakCollectionOf("WeakRef"); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString2(obj)) { + return markBoxed(inspect(String(obj))); + } + if (typeof window !== "undefined" && obj === window) { + return "{ [object Window] }"; + } + if (obj === global) { + return "{ [object globalThis] }"; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? "" : "null prototype"; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; + var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; + var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); + if (ys.length === 0) { + return tag + "{}"; + } + if (indent) { + return tag + "{" + indentedJoin(ys, indent) + "}"; + } + return tag + "{ " + $join.call(ys, ", ") + " }"; + } + return String(obj); + }; + function wrapQuotes(s2, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'"; + return quoteChar + s2 + quoteChar; + } + function quote(s2) { + return $replace.call(String(s2), /"/g, """); + } + function isArray(obj) { + return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isDate(obj) { + return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isRegExp(obj) { + return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isError(obj) { + return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isString2(obj) { + return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isNumber(obj) { + return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isBoolean(obj) { + return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); + } + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === "object" && obj instanceof Symbol; + } + if (typeof obj === "symbol") { + return true; + } + if (!obj || typeof obj !== "object" || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e2) { + } + return false; + } + function isBigInt(obj) { + if (!obj || typeof obj !== "object" || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e2) { + } + return false; + } + var hasOwn = Object.prototype.hasOwnProperty || function(key) { + return key in this; + }; + function has(obj, key) { + return hasOwn.call(obj, key); + } + function toStr(obj) { + return objectToString.call(obj); + } + function nameOf(f4) { + if (f4.name) { + return f4.name; + } + var m3 = $match.call(functionToString.call(f4), /^function\s*([\w$]+)/); + if (m3) { + return m3[1]; + } + return null; + } + function indexOf(xs, x3) { + if (xs.indexOf) { + return xs.indexOf(x3); + } + for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { + if (xs[i2] === x3) { + return i2; + } + } + return -1; + } + function isMap(x3) { + if (!mapSize || !x3 || typeof x3 !== "object") { + return false; + } + try { + mapSize.call(x3); + try { + setSize.call(x3); + } catch (s2) { + return true; + } + return x3 instanceof Map; + } catch (e2) { + } + return false; + } + function isWeakMap(x3) { + if (!weakMapHas || !x3 || typeof x3 !== "object") { + return false; + } + try { + weakMapHas.call(x3, weakMapHas); + try { + weakSetHas.call(x3, weakSetHas); + } catch (s2) { + return true; + } + return x3 instanceof WeakMap; + } catch (e2) { + } + return false; + } + function isWeakRef(x3) { + if (!weakRefDeref || !x3 || typeof x3 !== "object") { + return false; + } + try { + weakRefDeref.call(x3); + return true; + } catch (e2) { + } + return false; + } + function isSet(x3) { + if (!setSize || !x3 || typeof x3 !== "object") { + return false; + } + try { + setSize.call(x3); + try { + mapSize.call(x3); + } catch (m3) { + return true; + } + return x3 instanceof Set; + } catch (e2) { + } + return false; + } + function isWeakSet(x3) { + if (!weakSetHas || !x3 || typeof x3 !== "object") { + return false; + } + try { + weakSetHas.call(x3, weakSetHas); + try { + weakMapHas.call(x3, weakMapHas); + } catch (s2) { + return true; + } + return x3 instanceof WeakSet; + } catch (e2) { + } + return false; + } + function isElement(x3) { + if (!x3 || typeof x3 !== "object") { + return false; + } + if (typeof HTMLElement !== "undefined" && x3 instanceof HTMLElement) { + return true; + } + return typeof x3.nodeName === "string" && typeof x3.getAttribute === "function"; + } + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var s2 = $replace.call($replace.call(str, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s2, "single", opts); + } + function lowbyte(c4) { + var n3 = c4.charCodeAt(0); + var x3 = { + 8: "b", + 9: "t", + 10: "n", + 12: "f", + 13: "r" + }[n3]; + if (x3) { + return "\\" + x3; + } + return "\\x" + (n3 < 16 ? "0" : "") + $toUpperCase.call(n3.toString(16)); + } + function markBoxed(str) { + return "Object(" + str + ")"; + } + function weakCollectionOf(type) { + return type + " { ? }"; + } + function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); + return type + " (" + size + ") {" + joinedEntries + "}"; + } + function singleLineValues(xs) { + for (var i2 = 0; i2 < xs.length; i2++) { + if (indexOf(xs[i2], "\n") >= 0) { + return false; + } + } + return true; + } + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === " ") { + baseIndent = " "; + } else if (typeof opts.indent === "number" && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), " "); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + function indentedJoin(xs, indent) { + if (xs.length === 0) { + return ""; + } + var lineJoiner = "\n" + indent.prev + indent.base; + return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; + } + function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i2 = 0; i2 < obj.length; i2++) { + xs[i2] = has(obj, i2) ? inspect(obj[i2], obj) : ""; + } + } + var syms = typeof gOPS === "function" ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k4 = 0; k4 < syms.length; k4++) { + symMap["$" + syms[k4]] = syms[k4]; + } + } + for (var key in obj) { + if (!has(obj, key)) { + continue; + } + if (isArr && String(Number(key)) === key && key < obj.length) { + continue; + } + if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { + continue; + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); + } else { + xs.push(key + ": " + inspect(obj[key], obj)); + } + } + if (typeof gOPS === "function") { + for (var j2 = 0; j2 < syms.length; j2++) { + if (isEnumerable.call(obj, syms[j2])) { + xs.push("[" + inspect(syms[j2]) + "]: " + inspect(obj[syms[j2]], obj)); + } + } + } + return xs; + } + } +}); + +// node_modules/side-channel/index.js +var require_side_channel = __commonJS({ + "node_modules/side-channel/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var GetIntrinsic = require_get_intrinsic(); + var callBound = require_callBound(); + var inspect = require_object_inspect(); + var $TypeError = GetIntrinsic("%TypeError%"); + var $WeakMap = GetIntrinsic("%WeakMap%", true); + var $Map = GetIntrinsic("%Map%", true); + var $weakMapGet = callBound("WeakMap.prototype.get", true); + var $weakMapSet = callBound("WeakMap.prototype.set", true); + var $weakMapHas = callBound("WeakMap.prototype.has", true); + var $mapGet = callBound("Map.prototype.get", true); + var $mapSet = callBound("Map.prototype.set", true); + var $mapHas = callBound("Map.prototype.has", true); + var listGetNode = function(list, key) { + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; + return curr; + } + } + }; + var listGet = function(objects, key) { + var node = listGetNode(objects, key); + return node && node.value; + }; + var listSet = function(objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + objects.next = { + // eslint-disable-line no-param-reassign + key, + next: objects.next, + value + }; + } + }; + var listHas = function(objects, key) { + return !!listGetNode(objects, key); + }; + module2.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + get: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { + return listGet($o, key); + } + } + }, + has: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { + return listHas($o, key); + } + } + return false; + }, + set: function(key, value) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; + }; + } +}); + +// node_modules/qs/lib/formats.js +var require_formats = __commonJS({ + "node_modules/qs/lib/formats.js"(exports2, module2) { + "use strict"; + init_shim(); + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + var Format = { + RFC1738: "RFC1738", + RFC3986: "RFC3986" + }; + module2.exports = { + "default": Format.RFC3986, + formatters: { + RFC1738: function(value) { + return replace.call(value, percentTwenties, "+"); + }, + RFC3986: function(value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + } +}); + +// node_modules/qs/lib/utils.js +var require_utils5 = __commonJS({ + "node_modules/qs/lib/utils.js"(exports2, module2) { + "use strict"; + init_shim(); + var formats = require_formats(); + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + var hexTable = function() { + var array = []; + for (var i2 = 0; i2 < 256; ++i2) { + array.push("%" + ((i2 < 16 ? "0" : "") + i2.toString(16)).toUpperCase()); + } + return array; + }(); + var compactQueue = function compactQueue2(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + if (isArray(obj)) { + var compacted = []; + for (var j2 = 0; j2 < obj.length; ++j2) { + if (typeof obj[j2] !== "undefined") { + compacted.push(obj[j2]); + } + } + item.obj[item.prop] = compacted; + } + } + }; + var arrayToObject = function arrayToObject2(source, options) { + var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + for (var i2 = 0; i2 < source.length; ++i2) { + if (typeof source[i2] !== "undefined") { + obj[i2] = source[i2]; + } + } + return obj; + }; + var merge = function merge2(target, source, options) { + if (!source) { + return target; + } + if (typeof source !== "object") { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === "object") { + if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + return target; + } + if (!target || typeof target !== "object") { + return [target].concat(source); + } + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + if (isArray(target) && isArray(source)) { + source.forEach(function(item, i2) { + if (has.call(target, i2)) { + var targetItem = target[i2]; + if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { + target[i2] = merge2(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i2] = item; + } + }); + return target; + } + return Object.keys(source).reduce(function(acc, key) { + var value = source[key]; + if (has.call(acc, key)) { + acc[key] = merge2(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); + }; + var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function(acc, key) { + acc[key] = source[key]; + return acc; + }, target); + }; + var decode6 = function(str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, " "); + if (charset === "iso-8859-1") { + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + try { + return decodeURIComponent(strWithoutPlus); + } catch (e2) { + return strWithoutPlus; + } + }; + var encode5 = function encode6(str, defaultEncoder, charset, kind, format) { + if (str.length === 0) { + return str; + } + var string2 = str; + if (typeof str === "symbol") { + string2 = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string2 = String(str); + } + if (charset === "iso-8859-1") { + return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + var out = ""; + for (var i2 = 0; i2 < string2.length; ++i2) { + var c4 = string2.charCodeAt(i2); + if (c4 === 45 || c4 === 46 || c4 === 95 || c4 === 126 || c4 >= 48 && c4 <= 57 || c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122 || format === formats.RFC1738 && (c4 === 40 || c4 === 41)) { + out += string2.charAt(i2); + continue; + } + if (c4 < 128) { + out = out + hexTable[c4]; + continue; + } + if (c4 < 2048) { + out = out + (hexTable[192 | c4 >> 6] + hexTable[128 | c4 & 63]); + continue; + } + if (c4 < 55296 || c4 >= 57344) { + out = out + (hexTable[224 | c4 >> 12] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]); + continue; + } + i2 += 1; + c4 = 65536 + ((c4 & 1023) << 10 | string2.charCodeAt(i2) & 1023); + out += hexTable[240 | c4 >> 18] + hexTable[128 | c4 >> 12 & 63] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]; + } + return out; + }; + var compact = function compact2(value) { + var queue = [{ obj: { o: value }, prop: "o" }]; + var refs = []; + for (var i2 = 0; i2 < queue.length; ++i2) { + var item = queue[i2]; + var obj = item.obj[item.prop]; + var keys2 = Object.keys(obj); + for (var j2 = 0; j2 < keys2.length; ++j2) { + var key = keys2[j2]; + var val = obj[key]; + if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj, prop: key }); + refs.push(val); + } + } + } + compactQueue(queue); + return value; + }; + var isRegExp = function isRegExp2(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; + }; + var isBuffer = function isBuffer2(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + }; + var combine = function combine2(a3, b4) { + return [].concat(a3, b4); + }; + var maybeMap = function maybeMap2(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i2 = 0; i2 < val.length; i2 += 1) { + mapped.push(fn(val[i2])); + } + return mapped; + } + return fn(val); + }; + module2.exports = { + arrayToObject, + assign, + combine, + compact, + decode: decode6, + encode: encode5, + isBuffer, + isRegExp, + maybeMap, + merge + }; + } +}); + +// node_modules/qs/lib/stringify.js +var require_stringify2 = __commonJS({ + "node_modules/qs/lib/stringify.js"(exports2, module2) { + "use strict"; + init_shim(); + var getSideChannel = require_side_channel(); + var utils = require_utils5(); + var formats = require_formats(); + var has = Object.prototype.hasOwnProperty; + var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + "[]"; + }, + comma: "comma", + indices: function indices(prefix, key) { + return prefix + "[" + key + "]"; + }, + repeat: function repeat(prefix) { + return prefix; + } + }; + var isArray = Array.isArray; + var split = String.prototype.split; + var push = Array.prototype.push; + var pushToArray = function(arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); + }; + var toISO = Date.prototype.toISOString; + var defaultFormat = formats["default"]; + var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false + }; + var isNonNullishPrimitive = function isNonNullishPrimitive2(v2) { + return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean" || typeof v2 === "symbol" || typeof v2 === "bigint"; + }; + var sentinel = {}; + var stringify2 = function stringify3(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + var obj = object; + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + findFlag = true; + } + } + if (typeof tmpSc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = utils.maybeMap(obj, function(value2) { + if (value2 instanceof Date) { + return serializeDate(value2); + } + return value2; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; + } + obj = ""; + } + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + if (generateArrayPrefix === "comma" && encodeValuesOnly) { + var valuesArray = split.call(String(obj), ","); + var valuesJoined = ""; + for (var i2 = 0; i2 < valuesArray.length; ++i2) { + valuesJoined += (i2 === 0 ? "" : ",") + formatter(encoder(valuesArray[i2], defaults.encoder, charset, "value", format)); + } + return [formatter(keyValue) + "=" + valuesJoined]; + } + return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults.encoder, charset, "value", format))]; + } + return [formatter(prefix) + "=" + formatter(String(obj))]; + } + var values = []; + if (typeof obj === "undefined") { + return values; + } + var objKeys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys2 = Object.keys(obj); + objKeys = sort ? keys2.sort(sort) : keys2; + } + for (var j2 = 0; j2 < objKeys.length; ++j2) { + var key = objKeys[j2]; + var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; + } + var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? "." + key : "[" + key + "]"); + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify3( + value, + keyPrefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values; + }; + var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { + if (!opts) { + return defaults; + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var format = formats["default"]; + if (typeof opts.format !== "undefined") { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + var filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + module2.exports = function(object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + var objKeys; + var filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + var keys2 = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && "indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = "indices"; + } + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (!objKeys) { + objKeys = Object.keys(obj); + } + if (options.sort) { + objKeys.sort(options.sort); + } + var sideChannel = getSideChannel(); + for (var i2 = 0; i2 < objKeys.length; ++i2) { + var key = objKeys[i2]; + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys2, stringify2( + obj[key], + key, + generateArrayPrefix, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + var joined = keys2.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; + }; + } +}); + +// node_modules/qs/lib/parse.js +var require_parse2 = __commonJS({ + "node_modules/qs/lib/parse.js"(exports2, module2) { + "use strict"; + init_shim(); + var utils = require_utils5(); + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: "utf-8", + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: "&", + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1e3, + parseArrays: true, + plainObjects: false, + strictNullHandling: false + }; + var interpretNumericEntities = function(str) { + return str.replace(/&#(\d+);/g, function($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); + }; + var parseArrayValue = function(val, options) { + if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { + return val.split(","); + } + return val; + }; + var isoSentinel = "utf8=%26%2310003%3B"; + var charsetSentinel = "utf8=%E2%9C%93"; + var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; + var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; + var i2; + var charset = options.charset; + if (options.charsetSentinel) { + for (i2 = 0; i2 < parts.length; ++i2) { + if (parts[i2].indexOf("utf8=") === 0) { + if (parts[i2] === charsetSentinel) { + charset = "utf-8"; + } else if (parts[i2] === isoSentinel) { + charset = "iso-8859-1"; + } + skipIndex = i2; + i2 = parts.length; + } + } + } + for (i2 = 0; i2 < parts.length; ++i2) { + if (i2 === skipIndex) { + continue; + } + var part = parts[i2]; + var bracketEqualsPos = part.indexOf("]="); + var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, "key"); + val = options.strictNullHandling ? null : ""; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function(encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, "value"); + } + ); + } + if (val && options.interpretNumericEntities && charset === "iso-8859-1") { + val = interpretNumericEntities(val); + } + if (part.indexOf("[]=") > -1) { + val = isArray(val) ? [val] : val; + } + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + return obj; + }; + var parseObject = function(chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + for (var i2 = chain.length - 1; i2 >= 0; --i2) { + var obj; + var root = chain[i2]; + if (root === "[]" && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === "") { + obj = { 0: leaf }; + } else if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== "__proto__") { + obj[cleanRoot] = leaf; + } + } + leaf = obj; + } + return leaf; + }; + var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + var keys2 = []; + if (parent) { + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + keys2.push(parent); + } + var i2 = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i2 < options.depth) { + i2 += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys2.push(segment[1]); + } + if (segment) { + keys2.push("[" + key.slice(segment.index) + "]"); + } + return parseObject(keys2, val, options, valuesParsed); + }; + var normalizeParseOptions = function normalizeParseOptions2(opts) { + if (!opts) { + return defaults; + } + if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") { + throw new TypeError("Decoder has to be a function."); + } + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; + return { + allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + module2.exports = function(str, opts) { + var options = normalizeParseOptions(opts); + if (str === "" || str === null || typeof str === "undefined") { + return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + } + var tempObj = typeof str === "string" ? parseValues(str, options) : str; + var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; + var keys2 = Object.keys(tempObj); + for (var i2 = 0; i2 < keys2.length; ++i2) { + var key = keys2[i2]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); + obj = utils.merge(obj, newObj, options); + } + if (options.allowSparse === true) { + return obj; + } + return utils.compact(obj); + }; + } +}); + +// node_modules/qs/lib/index.js +var require_lib = __commonJS({ + "node_modules/qs/lib/index.js"(exports2, module2) { + "use strict"; + init_shim(); + var stringify2 = require_stringify2(); + var parse = require_parse2(); + var formats = require_formats(); + module2.exports = { + formats, + parse, + stringify: stringify2 + }; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js +var require_constants7 = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = exports2.WALLET_PROVIDER_CALLBACK_PARAM = exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = exports2.WALLET_PROVIDER_DISCONNECT_URL = exports2.WALLET_PROVIDER_CONNECT_URL = exports2.XALIAS_PROVIDER_TESTNET = exports2.XALIAS_PROVIDER_DEVNET = exports2.XALIAS_PROVIDER_MAINNET = exports2.WALLET_PROVIDER_TESTNET = exports2.WALLET_PROVIDER_DEVNET = exports2.WALLET_PROVIDER_MAINNET = void 0; + exports2.WALLET_PROVIDER_MAINNET = "https://wallet.multiversx.com/dapp/init"; + exports2.WALLET_PROVIDER_DEVNET = "https://devnet-wallet.multiversx.com/dapp/init"; + exports2.WALLET_PROVIDER_TESTNET = "https://testnet-wallet.multiversx.com/dapp/init"; + exports2.XALIAS_PROVIDER_MAINNET = "https://xalias.com"; + exports2.XALIAS_PROVIDER_DEVNET = "https://devnet.xalias.com"; + exports2.XALIAS_PROVIDER_TESTNET = "https://testnet.xalias.com"; + exports2.WALLET_PROVIDER_CONNECT_URL = "hook/login"; + exports2.WALLET_PROVIDER_DISCONNECT_URL = "hook/logout"; + exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = "hook/transaction"; + exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = "hook/sign"; + exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = "hook/2fa"; + exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = "hook/sign-message"; + exports2.WALLET_PROVIDER_CALLBACK_PARAM = "walletProviderStatus"; + exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = "transactionsSigned"; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js +var require_errors4 = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrCannotSignedMessage = exports2.ErrCannotGetSignedTransactions = void 0; + var ErrCannotGetSignedTransactions = class extends Error { + constructor() { + super("Cannot get signed transaction(s)"); + } + }; + exports2.ErrCannotGetSignedTransactions = ErrCannotGetSignedTransactions; + var ErrCannotSignedMessage = class extends Error { + constructor() { + super("Cannot get signed message"); + } + }; + exports2.ErrCannotSignedMessage = ErrCannotSignedMessage; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js +var require_plainSignedTransaction = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.PlainSignedTransaction = void 0; + var PlainSignedTransaction = class { + constructor(init) { + this.nonce = 0; + this.value = ""; + this.receiver = ""; + this.sender = ""; + this.gasPrice = 0; + this.gasLimit = 0; + this.data = ""; + this.chainID = ""; + this.version = 0; + this.signature = ""; + Object.assign(this, init); + } + }; + exports2.PlainSignedTransaction = PlainSignedTransaction; + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js +var require_walletProvider = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WalletProvider = void 0; + var qs_1 = __importDefault2(require_lib()); + var constants_1 = require_constants7(); + var errors_1 = require_errors4(); + var plainSignedTransaction_1 = require_plainSignedTransaction(); + var WalletProvider6 = class _WalletProvider { + /** + * Creates a new WalletProvider + * @param walletURL + */ + constructor(walletURL) { + this.walletUrl = walletURL; + } + /** + * Fetches the login hook url and redirects the client to the wallet login. + */ + login(options) { + return __awaiter2(this, void 0, void 0, function* () { + const redirectUrl = this.buildWalletUrl({ + endpoint: constants_1.WALLET_PROVIDER_CONNECT_URL, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, + params: { + token: options === null || options === void 0 ? void 0 : options.token + } + }); + yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); + return redirectUrl; + }); + } + redirect(url, delayMilliseconds) { + return __awaiter2(this, void 0, void 0, function* () { + if (delayMilliseconds) { + yield this.redirectLater(url, delayMilliseconds); + } else { + this.redirectImmediately(url); + } + }); + } + redirectImmediately(url) { + window.location.href = url; + } + redirectLater(url, delayMilliseconds) { + return __awaiter2(this, void 0, void 0, function* () { + yield new Promise((resolve) => { + setTimeout(() => { + window.location.href = url; + resolve(true); + }, delayMilliseconds); + }); + }); + } + /** + * Fetches the logout hook url and redirects the client to the wallet logout. + */ + logout(options) { + return __awaiter2(this, void 0, void 0, function* () { + const redirectUrl = this.buildWalletUrl({ + endpoint: constants_1.WALLET_PROVIDER_DISCONNECT_URL, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl + }); + yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); + return true; + }); + } + /** + * Packs a {@link SignMessage} and fetches correct redirect URL from the wallet API. Then redirects + * the client to the sign message hook + * @param message + * @param options + */ + signMessage(message, options) { + return __awaiter2(this, void 0, void 0, function* () { + const redirectUrl = this.buildWalletUrl({ + endpoint: constants_1.WALLET_PROVIDER_SIGN_MESSAGE_URL, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, + params: { + message: message.message.toString() + } + }); + yield this.redirect(redirectUrl); + return redirectUrl; + }); + } + getMessageSignatureFromWalletUrl() { + var _a, _b; + const url = window.location.search.slice(1); + console.info("getMessageSignatureFromWalletUrl(), url:", url); + const urlParams = qs_1.default.parse(url); + const status = ((_a = urlParams.status) === null || _a === void 0 ? void 0 : _a.toString()) || ""; + const expectedStatus = "signed"; + if (status !== expectedStatus) { + throw new errors_1.ErrCannotSignedMessage(); + } + const signature = ((_b = urlParams.signature) === null || _b === void 0 ? void 0 : _b.toString()) || ""; + return signature; + } + /** + * Packs an array of {$link Transaction} and redirects to the 2fa hook + * + * @param transactions + * @param options + */ + guardTransactions(transactions, options) { + return __awaiter2(this, void 0, void 0, function* () { + this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_GUARD_TRANSACTION_URL, transactions, options); + }); + } + /** + * Packs an array of {$link Transaction} and redirects to the correct transaction sigining hook + * + * @param transactions + * @param options + */ + signTransactions(transactions, options) { + return __awaiter2(this, void 0, void 0, function* () { + this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_SIGN_TRANSACTION_URL, transactions, options); + }); + } + /** + * Packs a {@link Transaction} and fetches correct redirect URL from the wallet API. Then redirects + * the client to the sign transaction hook + * @param transaction + * @param options + */ + signTransaction(transaction, options) { + return __awaiter2(this, void 0, void 0, function* () { + yield this.signTransactions([transaction], options); + }); + } + getTransactionsFromWalletUrl(search = window.location.search) { + const urlParams = qs_1.default.parse(search.slice(1)); + if (!_WalletProvider.isTxSignReturnSuccess(urlParams)) { + return []; + } + return this.getTxSignReturnValue(urlParams); + } + static isTxSignReturnSuccess(urlParams) { + return urlParams.hasOwnProperty(constants_1.WALLET_PROVIDER_CALLBACK_PARAM) && urlParams[constants_1.WALLET_PROVIDER_CALLBACK_PARAM] === constants_1.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED; + } + getTxSignReturnValue(urlParams) { + console.info("getTxSignReturnValue(), urlParams:", urlParams); + const expectedProps = [ + "nonce", + "value", + "receiver", + "sender", + "gasPrice", + "gasLimit", + "chainID", + "version", + "signature" + ]; + for (let txProp of expectedProps) { + if (!urlParams[txProp] || !Array.isArray(urlParams[txProp])) { + throw new errors_1.ErrCannotGetSignedTransactions(); + } + } + const expectedLength = urlParams["nonce"].length; + for (let txProp of expectedProps) { + if (urlParams[txProp].length !== expectedLength) { + throw new errors_1.ErrCannotGetSignedTransactions(); + } + } + const transactions = []; + for (let i2 = 0; i2 < expectedLength; i2++) { + let plainSignedTransaction = new plainSignedTransaction_1.PlainSignedTransaction(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ + nonce: parseInt(urlParams["nonce"][i2]), + value: urlParams["value"][i2], + receiver: urlParams["receiver"][i2], + sender: urlParams["sender"][i2], + gasPrice: parseInt(urlParams["gasPrice"][i2]), + gasLimit: parseInt(urlParams["gasLimit"][i2]), + // Handle the optional "data" property. + data: urlParams["data"] && urlParams["data"][i2] ? urlParams["data"][i2] : "", + chainID: urlParams["chainID"][i2], + version: parseInt(urlParams["version"][i2]) + }, urlParams["guardian"] && urlParams["guardian"][i2] ? { guardian: urlParams["guardian"][i2] } : {}), urlParams["guardianSignature"] && urlParams["guardianSignature"][i2] ? { guardianSignature: urlParams["guardianSignature"][i2] } : {}), urlParams["options"] && urlParams["options"][i2] ? { + options: parseInt(urlParams["options"][i2]) + } : {}), urlParams["senderUsername"] && urlParams["senderUsername"][i2] ? { senderUsername: urlParams["senderUsername"][i2] } : {}), urlParams["receiverUsername"] && urlParams["receiverUsername"][i2] ? { receiverUsername: urlParams["receiverUsername"][i2] } : {}), { signature: urlParams["signature"][i2] })); + transactions.push(plainSignedTransaction); + } + return transactions; + } + static prepareWalletTransaction(transaction) { + let plainTransaction = transaction.toPlainObject(); + if (plainTransaction.data) { + plainTransaction.data = import_buffer.Buffer.from(plainTransaction.data, "base64").toString(); + } else { + plainTransaction.data = ""; + } + return plainTransaction; + } + buildWalletUrl(options) { + const callbackUrl = (options === null || options === void 0 ? void 0 : options.callbackUrl) || window.location.href; + const partialQueryString = qs_1.default.stringify(options.params || {}); + const fullQueryString = partialQueryString ? `${partialQueryString}&callbackUrl=${callbackUrl}` : `callbackUrl=${callbackUrl}`; + const url = `${this.baseWalletUrl()}/${options.endpoint}?${fullQueryString}`; + console.info(`Redirecting to Wallet URL: ${decodeURI(url)}`); + return url; + } + baseWalletUrl() { + const pathArray = this.walletUrl.split("/"); + const protocol = pathArray[0]; + const host = pathArray[2]; + return protocol + "//" + host; + } + /** + * Packs an array of {$link Transaction} and redirects to the specified wallet hook + * + * @param transactions + * @param options + */ + redirectTransactionsToEndpoint(endpoint, transactions, options) { + const jsonToSend = {}; + transactions.map((tx) => { + let plainTx = _WalletProvider.prepareWalletTransaction(tx); + for (let txProp in plainTx) { + if (plainTx.hasOwnProperty(txProp) && !jsonToSend.hasOwnProperty(txProp)) { + jsonToSend[txProp] = []; + } + jsonToSend[txProp].push(plainTx[txProp]); + } + }); + const redirectUrl = this.buildWalletUrl({ + endpoint, + callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, + params: jsonToSend + }); + window.location.href = redirectUrl; + } + }; + exports2.WalletProvider = WalletProvider6; + } +}); + +// node_modules/axios/dist/browser/axios.cjs +var require_axios = __commonJS({ + "node_modules/axios/dist/browser/axios.cjs"(exports2, module2) { + "use strict"; + init_shim(); + function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; + } + var { toString: toString3 } = Object.prototype; + var { getPrototypeOf } = Object; + var kindOf = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString3.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + })(/* @__PURE__ */ Object.create(null)); + var kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type; + }; + var typeOfTest = (type) => (thing) => typeof thing === type; + var { isArray } = Array; + var isUndefined = typeOfTest("undefined"); + function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); + } + var isArrayBuffer = kindOfTest("ArrayBuffer"); + function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; + } + var isString2 = typeOfTest("string"); + var isFunction = typeOfTest("function"); + var isNumber = typeOfTest("number"); + var isObject = (thing) => thing !== null && typeof thing === "object"; + var isBoolean = (thing) => thing === true || thing === false; + var isPlainObject = (val) => { + if (kindOf(val) !== "object") { + return false; + } + const prototype2 = getPrototypeOf(val); + return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); + }; + var isDate = kindOfTest("Date"); + var isFile = kindOfTest("File"); + var isBlob = kindOfTest("Blob"); + var isFileList = kindOfTest("FileList"); + var isStream = (val) => isObject(val) && isFunction(val.pipe); + var isFormData = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); + }; + var isURLSearchParams = kindOfTest("URLSearchParams"); + var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); + function forEach(obj, fn, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i2; + let l4; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray(obj)) { + for (i2 = 0, l4 = obj.length; i2 < l4; i2++) { + fn.call(null, obj[i2], i2, obj); + } + } else { + const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys2.length; + let key; + for (i2 = 0; i2 < len; i2++) { + key = keys2[i2]; + fn.call(null, obj[key], key, obj); + } + } + } + function findKey(obj, key) { + key = key.toLowerCase(); + const keys2 = Object.keys(obj); + let i2 = keys2.length; + let _key; + while (i2-- > 0) { + _key = keys2[i2]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; + } + var _global = (() => { + if (typeof globalThis !== "undefined") + return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; + })(); + var isContextDefined = (context) => !isUndefined(context) && context !== _global; + function merge() { + const { caseless } = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i2 = 0, l4 = arguments.length; i2 < l4; i2++) { + arguments[i2] && forEach(arguments[i2], assignValue); + } + return result; + } + var extend = (a3, b4, thisArg, { allOwnKeys } = {}) => { + forEach(b4, (val, key) => { + if (thisArg && isFunction(val)) { + a3[key] = bind(val, thisArg); + } else { + a3[key] = val; + } + }, { allOwnKeys }); + return a3; + }; + var stripBOM = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); + } + return content; + }; + var inherits = (constructor, superConstructor, props, descriptors2) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors2); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); + }; + var toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i2; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) + return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i2 = props.length; + while (i2-- > 0) { + prop = props[i2]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; + }; + var endsWith = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + var toArray = (thing) => { + if (!thing) + return null; + if (isArray(thing)) + return thing; + let i2 = thing.length; + if (!isNumber(i2)) + return null; + const arr = new Array(i2); + while (i2-- > 0) { + arr[i2] = thing[i2]; + } + return arr; + }; + var isTypedArray = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; + })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); + var forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + const iterator = generator.call(obj); + let result; + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } + }; + var matchAll = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; + }; + var isHTMLForm = kindOfTest("HTMLFormElement"); + var toCamelCase = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m3, p1, p22) { + return p1.toUpperCase() + p22; + } + ); + }; + var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); + var isRegExp = kindOfTest("RegExp"); + var reduceDescriptors = (obj, reducer) => { + const descriptors2 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach(descriptors2, (descriptor, name2) => { + let ret; + if ((ret = reducer(descriptor, name2, obj)) !== false) { + reducedDescriptors[name2] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); + }; + var freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name2) => { + if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) { + return false; + } + const value = obj[name2]; + if (!isFunction(value)) + return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name2 + "'"); + }; + } + }); + }; + var toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + const define2 = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); + return obj; + }; + var noop = () => { + }; + var toFiniteNumber = (value, defaultValue) => { + value = +value; + return Number.isFinite(value) ? value : defaultValue; + }; + var ALPHA = "abcdefghijklmnopqrstuvwxyz"; + var DIGIT = "0123456789"; + var ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT + }; + var generateString = (size = 16, alphabet2 = ALPHABET.ALPHA_DIGIT) => { + let str = ""; + const { length: length2 } = alphabet2; + while (size--) { + str += alphabet2[Math.random() * length2 | 0]; + } + return str; + }; + function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); + } + var toJSONObject = (obj) => { + const stack = new Array(10); + const visit = (source, i2) => { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i2] = source; + const target = isArray(source) ? [] : {}; + forEach(source, (value, key) => { + const reducedValue = visit(value, i2 + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i2] = void 0; + return target; + } + } + return source; + }; + return visit(obj, 0); + }; + var isAsyncFn = kindOfTest("AsyncFunction"); + var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + var utils$1 = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString: isString2, + isNumber, + isBoolean, + isObject, + isPlainObject, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable + }; + function AxiosError(message, code2, config, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = "AxiosError"; + code2 && (this.code = code2); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); + } + utils$1.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; + } + }); + var prototype$1 = AxiosError.prototype; + var descriptors = {}; + [ + "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" + // eslint-disable-next-line func-names + ].forEach((code2) => { + descriptors[code2] = { value: code2 }; + }); + Object.defineProperties(AxiosError, descriptors); + Object.defineProperty(prototype$1, "isAxiosError", { value: true }); + AxiosError.from = (error, code2, config, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + utils$1.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError.call(axiosError, error.message, code2, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + }; + var httpAdapter = null; + function isVisitable(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + } + function removeBrackets(key) { + return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; + } + function renderKey(path, key, dots) { + if (!path) + return key; + return path.concat(key).map(function each(token, i2) { + token = removeBrackets(token); + return !dots && i2 ? "[" + token + "]" : token; + }).join(dots ? "." : ""); + } + function isFlatArray(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable); + } + var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); + }); + function toFormData(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new FormData(); + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils$1.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) + return ""; + if (utils$1.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError("Blob is not supported. Use a Buffer instead."); + } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : import_buffer.Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils$1.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { + key = removeBrackets(key); + arr.forEach(function each(el, index) { + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", + convertValue(el) + ); + }); + return false; + } + } + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils$1.isUndefined(value)) + return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils$1.forEach(value, function each(el, key) { + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, + el, + utils$1.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils$1.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; + } + function encode$1(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); + } + function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData(params, this, options); + } + var prototype = AxiosURLSearchParams.prototype; + prototype.append = function append(name2, value) { + this._pairs.push([name2, value]); + }; + prototype.toString = function toString4(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); + }; + function encode5(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + } + function buildURL(url, params, options) { + if (!params) { + return url; + } + const _encode = options && options.encode || encode5; + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url; + } + var InterceptorManager = class { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } + } + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils$1.forEach(this.handlers, function forEachHandler(h5) { + if (h5 !== null) { + fn(h5); + } + }); + } + }; + var InterceptorManager$1 = InterceptorManager; + var transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }; + var URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams; + var FormData$1 = typeof FormData !== "undefined" ? FormData : null; + var Blob$1 = typeof Blob !== "undefined" ? Blob : null; + var platform$1 = { + isBrowser: true, + classes: { + URLSearchParams: URLSearchParams$1, + FormData: FormData$1, + Blob: Blob$1 + }, + protocols: ["http", "https", "file", "blob", "url", "data"] + }; + var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; + var hasStandardBrowserEnv = ((product) => { + return hasBrowserEnv && ["ReactNative", "NativeScript", "NS"].indexOf(product) < 0; + })(typeof navigator !== "undefined" && navigator.product); + var hasStandardBrowserWebWorkerEnv = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; + })(); + var utils = /* @__PURE__ */ Object.freeze({ + __proto__: null, + hasBrowserEnv, + hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv + }); + var platform = { + ...utils, + ...platform$1 + }; + function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); + } + function parsePropPath(name2) { + return utils$1.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); + } + function arrayToObject(arr) { + const obj = {}; + const keys2 = Object.keys(arr); + let i2; + const len = keys2.length; + let key; + for (i2 = 0; i2 < len; i2++) { + key = keys2[i2]; + obj[key] = arr[key]; + } + return obj; + } + function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name2 = path[index++]; + if (name2 === "__proto__") + return true; + const isNumericKey = Number.isFinite(+name2); + const isLast = index >= path.length; + name2 = !name2 && utils$1.isArray(target) ? target.length : name2; + if (isLast) { + if (utils$1.hasOwnProp(target, name2)) { + target[name2] = [target[name2], value]; + } else { + target[name2] = value; + } + return !isNumericKey; + } + if (!target[name2] || !utils$1.isObject(target[name2])) { + target[name2] = []; + } + const result = buildPath(path, value, target[name2], index); + if (result && utils$1.isArray(target[name2])) { + target[name2] = arrayToObject(target[name2]); + } + return !isNumericKey; + } + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + utils$1.forEachEntry(formData, (name2, value) => { + buildPath(parsePropPath(name2), value, obj, 0); + }); + return obj; + } + return null; + } + function stringifySafely(rawValue, parser, encoder) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e2) { + if (e2.name !== "SyntaxError") { + throw e2; + } + } + } + return (encoder || JSON.stringify)(rawValue); + } + var defaults = { + transitional: transitionalDefaults, + adapter: ["xhr", "http"], + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils$1.isObject(data); + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData2 = utils$1.isFormData(data); + if (isFormData2) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; + } + if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data)) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList2; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData( + isFileList2 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely(data); + } + return data; + }], + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e2) { + if (strictJSONParsing) { + if (e2.name === "SyntaxError") { + throw AxiosError.from(e2, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e2; + } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 + } + } + }; + utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults.headers[method] = {}; + }); + var defaults$1 = defaults; + var ignoreDuplicateOf = utils$1.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" + ]); + var parseHeaders = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i2; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i2 = line.indexOf(":"); + key = line.substring(0, i2).trim().toLowerCase(); + val = line.substring(i2 + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; + }; + var $internals = Symbol("internals"); + function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); + } + function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); + } + function parseTokens(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; + } + var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils$1.isFunction(filter)) { + return filter.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils$1.isString(value)) + return; + if (utils$1.isString(filter)) { + return value.indexOf(filter) !== -1; + } + if (utils$1.isRegExp(filter)) { + return filter.test(value); + } + } + function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w4, char, str) => { + return char.toUpperCase() + str; + }); + } + function buildAccessors(obj, header) { + const accessorName = utils$1.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); + } + var AxiosHeaders = class { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils$1.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue(_value); + } + } + const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader(header); + if (header) { + const key = utils$1.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); + } + } + } + has(header, matcher) { + header = normalizeHeader(header); + if (header) { + const key = utils$1.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + const key = utils$1.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys2 = Object.keys(this); + let i2 = keys2.length; + let deleted = false; + while (i2--) { + const key = keys2[i2]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + if (key) { + self2[key] = normalizeValue(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals] = this[$internals] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype2 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype2, _header); + accessors[lHeader] = true; + } + } + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } + }; + AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); + utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; + }); + utils$1.freezeMethods(AxiosHeaders); + var AxiosHeaders$1 = AxiosHeaders; + function transformData(fns, response) { + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + utils$1.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; + } + function isCancel(value) { + return !!(value && value.__CANCEL__); + } + function CanceledError(message, config, request) { + AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request); + this.name = "CanceledError"; + } + utils$1.inherits(CanceledError, AxiosError, { + __CANCEL__: true + }); + function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + "Request failed with status code " + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } + } + var cookies = platform.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name2, value, expires, path, domain, secure) { + const cookie = [name2 + "=" + encodeURIComponent(value)]; + utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils$1.isString(path) && cookie.push("path=" + path); + utils$1.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name2) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name2 + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name2) { + this.write(name2, "", Date.now() - 864e5); + } + } + ) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } + ); + function isAbsoluteURL(url) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); + } + function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; + } + function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; + } + var isURLSameOrigin = platform.hasStandardBrowserEnv ? ( + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + function standardBrowserEnv() { + const msie = /(msie|trident)/i.test(navigator.userAgent); + const urlParsingNode = document.createElement("a"); + let originURL; + function resolveURL(url) { + let href = url; + if (msie) { + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } + urlParsingNode.setAttribute("href", href); + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname + }; + } + originURL = resolveURL(window.location.href); + return function isURLSameOrigin2(requestURL) { + const parsed = utils$1.isString(requestURL) ? resolveURL(requestURL) : requestURL; + return parsed.protocol === originURL.protocol && parsed.host === originURL.host; + }; + }() + ) : ( + // Non standard browser envs (web workers, react-native) lack needed support. + /* @__PURE__ */ function nonStandardBrowserEnv() { + return function isURLSameOrigin2() { + return true; + }; + }() + ); + function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ""; + } + function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i2 = tail; + let bytesCount = 0; + while (i2 !== head) { + bytesCount += bytes[i2++]; + i2 = i2 % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; + } + function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + return (e2) => { + const loaded = e2.loaded; + const total = e2.lengthComputable ? e2.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange ? (total - loaded) / rate : void 0, + event: e2 + }; + data[isDownloadStream ? "download" : "upload"] = true; + listener(data); + }; + } + var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; + var xhrAdapter = isXHRAdapterSupported && function(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + let requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + let { responseType, withXSRFToken } = config; + let onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + if (config.signal) { + config.signal.removeEventListener("abort", onCanceled); + } + } + let contentType; + if (utils$1.isFormData(requestData)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); + } else if ((contentType = requestHeaders.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + requestHeaders.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + let request = new XMLHttpRequest(); + if (config.auth) { + const username = config.auth.username || ""; + const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; + requestHeaders.set("Authorization", "Basic " + btoa(username + ":" + password)); + } + const fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + request.timeout = config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders$1.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request)); + request = null; + }; + request.onerror = function handleError() { + reject(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request)); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request + )); + request = null; + }; + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(fullPath)) { + const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); + if (xsrfValue) { + requestHeaders.set(config.xsrfHeaderName, xsrfValue); + } + } + } + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils$1.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = config.responseType; + } + if (typeof config.onDownloadProgress === "function") { + request.addEventListener("progress", progressEventReducer(config.onDownloadProgress, true)); + } + if (typeof config.onUploadProgress === "function" && request.upload) { + request.upload.addEventListener("progress", progressEventReducer(config.onUploadProgress)); + } + if (config.cancelToken || config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol(fullPath); + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config)); + return; + } + request.send(requestData || null); + }); + }; + var knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter + }; + utils$1.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, "name", { value }); + } catch (e2) { + } + Object.defineProperty(fn, "adapterName", { value }); + } + }); + var renderReason = (reason) => `- ${reason}`; + var isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + var adapters = { + getAdapter: (adapters2) => { + adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; + const { length: length2 } = adapters2; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i2 = 0; i2 < length2; i2++) { + nameOrAdapter = adapters2[i2]; + let id; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError(`Unknown adapter '${id}'`); + } + } + if (adapter) { + break; + } + rejectedReasons[id || "#" + i2] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s2 = length2 ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s2, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters + }; + function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); + } + } + function dispatchRequest(config) { + throwIfCancellationRequested(config); + config.headers = AxiosHeaders$1.from(config.headers); + config.data = transformData.call( + config, + config.transformRequest + ); + if (["post", "put", "patch"].indexOf(config.method) !== -1) { + config.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + response.data = transformData.call( + config, + config.transformResponse, + response + ); + response.headers = AxiosHeaders$1.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); + } + var headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + function mergeConfig(config1, config2) { + config2 = config2 || {}; + const config = {}; + function getMergedValue(target, source, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({ caseless }, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a3, b4, caseless) { + if (!utils$1.isUndefined(b4)) { + return getMergedValue(a3, b4, caseless); + } else if (!utils$1.isUndefined(a3)) { + return getMergedValue(void 0, a3, caseless); + } + } + function valueFromConfig2(a3, b4) { + if (!utils$1.isUndefined(b4)) { + return getMergedValue(void 0, b4); + } + } + function defaultToConfig2(a3, b4) { + if (!utils$1.isUndefined(b4)) { + return getMergedValue(void 0, b4); + } else if (!utils$1.isUndefined(a3)) { + return getMergedValue(void 0, a3); + } + } + function mergeDirectKeys(a3, b4, prop) { + if (prop in config2) { + return getMergedValue(a3, b4); + } else if (prop in config1) { + return getMergedValue(void 0, a3); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a3, b4) => mergeDeepProperties(headersToObject(a3), headersToObject(b4), true) + }; + utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge2 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge2(config1[prop], config2[prop], prop); + utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); + }); + return config; + } + var VERSION = "1.6.8"; + var validators$1 = {}; + ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => { + validators$1[type] = function validator2(thing) { + return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type; + }; + }); + var deprecatedWarnings = {}; + validators$1.transitional = function transitional(validator2, version2, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator2 === false) { + throw new AxiosError( + formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")), + AxiosError.ERR_DEPRECATED + ); + } + if (version2 && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version2 + " and will be removed in the near future" + ) + ); + } + return validator2 ? validator2(value, opt, opts) : true; + }; + }; + function assertOptions(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE); + } + const keys2 = Object.keys(options); + let i2 = keys2.length; + while (i2-- > 0) { + const opt = keys2[i2]; + const validator2 = schema[opt]; + if (validator2) { + const value = options[opt]; + const result = value === void 0 || validator2(value, opt, options); + if (result !== true) { + throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION); + } + } + } + var validator = { + assertOptions, + validators: validators$1 + }; + var validators = validator.validators; + var Axios = class { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config) { + try { + return await this._request(configOrUrl, config); + } catch (err) { + if (err instanceof Error) { + let dummy; + Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } + throw err; + } + } + _request(configOrUrl, config) { + if (typeof configOrUrl === "string") { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + config = mergeConfig(this.defaults, config); + const { transitional, paramsSerializer, headers } = config; + if (transitional !== void 0) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + config.method = (config.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config.method] + ); + headers && utils$1.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; + } + ); + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i2 = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config); + while (i2 < len) { + promise = promise.then(chain[i2++], chain[i2++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config; + i2 = 0; + while (i2 < len) { + const onFulfilled = requestInterceptorChain[i2++]; + const onRejected = requestInterceptorChain[i2++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i2 = 0; + len = responseInterceptorChain.length; + while (i2 < len) { + promise = promise.then(responseInterceptorChain[i2++], responseInterceptorChain[i2++]); + } + return promise; + } + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); + } + }; + utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; + }); + utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url, + data + })); + }; + } + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + "Form"] = generateHTTPMethod(true); + }); + var Axios$1 = Axios; + var CancelToken = class _CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) + return; + let i2 = token._listeners.length; + while (i2-- > 0) { + token._listeners[i2](cancel); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); + } + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + /** + * Subscribe to the cancel signal + */ + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + /** + * Unsubscribe from the cancel signal + */ + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } + } + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new _CancelToken(function executor(c4) { + cancel = c4; + }); + return { + token, + cancel + }; + } + }; + var CancelToken$1 = CancelToken; + function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + } + function isAxiosError(payload) { + return utils$1.isObject(payload) && payload.isAxiosError === true; + } + var HttpStatusCode = { + 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(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; + }); + var HttpStatusCode$1 = HttpStatusCode; + function createInstance(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); + utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); + utils$1.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create2(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + return instance; + } + var axios = createInstance(defaults$1); + axios.Axios = Axios$1; + axios.CanceledError = CanceledError; + axios.CancelToken = CancelToken$1; + axios.isCancel = isCancel; + axios.VERSION = VERSION; + axios.toFormData = toFormData; + axios.AxiosError = AxiosError; + axios.Cancel = axios.CanceledError; + axios.all = function all(promises) { + return Promise.all(promises); + }; + axios.spread = spread; + axios.isAxiosError = isAxiosError; + axios.mergeConfig = mergeConfig; + axios.AxiosHeaders = AxiosHeaders$1; + axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + axios.getAdapter = adapters.getAdapter; + axios.HttpStatusCode = HttpStatusCode$1; + axios.default = axios; + module2.exports = axios; + } +}); + +// node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js +var require_native_auth_client_config = __commonJS({ + "node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NativeAuthClientConfig = void 0; + var NativeAuthClientConfig = class { + constructor() { + this.origin = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.hostname : ""; + this.apiUrl = "https://api.multiversx.com"; + this.expirySeconds = 60 * 60 * 24; + } + }; + exports2.NativeAuthClientConfig = NativeAuthClientConfig; + } +}); + +// node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js +var require_native_auth_client = __commonJS({ + "node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js"(exports2) { + "use strict"; + init_shim(); + var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.NativeAuthClient = void 0; + var axios_1 = require_axios(); + var native_auth_client_config_1 = require_native_auth_client_config(); + var NativeAuthClient3 = class { + constructor(config) { + this.config = Object.assign(new native_auth_client_config_1.NativeAuthClientConfig(), config); + } + getToken(address, token, signature) { + const encodedAddress = this.encodeValue(address); + const encodedToken = this.encodeValue(token); + const accessToken = `${encodedAddress}.${encodedToken}.${signature}`; + return accessToken; + } + initialize(extraInfo = {}) { + return __awaiter2(this, void 0, void 0, function* () { + const blockHash = yield this.getCurrentBlockHash(); + const encodedExtraInfo = this.encodeValue(JSON.stringify(extraInfo)); + const origin = this.encodeValue(this.config.origin); + return `${origin}.${blockHash}.${this.config.expirySeconds}.${encodedExtraInfo}`; + }); + } + getCurrentBlockHash() { + return __awaiter2(this, void 0, void 0, function* () { + if (this.config.gatewayUrl) { + return yield this.getCurrentBlockHashWithGateway(); + } + return yield this.getCurrentBlockHashWithApi(); + }); + } + getCurrentBlockHashWithGateway() { + return __awaiter2(this, void 0, void 0, function* () { + const round = yield this.getCurrentRound(); + const url = `${this.config.gatewayUrl}/blocks/by-round/${round}`; + const response = yield this.get(url); + const blocks = response.data.data.blocks; + const block = blocks.filter((block2) => block2.shard === this.config.blockHashShard)[0]; + return block.hash; + }); + } + getCurrentRound() { + return __awaiter2(this, void 0, void 0, function* () { + if (!this.config.gatewayUrl) { + throw new Error("Gateway URL not set"); + } + if (!this.config.blockHashShard) { + throw new Error("Blockhash shard not set"); + } + const url = `${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`; + const response = yield this.get(url); + const status = response.data.data.status; + return status.erd_current_round; + }); + } + getCurrentBlockHashWithApi() { + return __awaiter2(this, void 0, void 0, function* () { + try { + const url = `${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`; + const response = yield this.get(url); + if (response.data[0].hash !== void 0) { + return response.data[0].hash; + } + } catch (error) { + } + return this.getCurrentBlockHashWithApiFallback(); + }); + } + getCurrentBlockHashWithApiFallback() { + return __awaiter2(this, void 0, void 0, function* () { + let url = `${this.config.apiUrl}/blocks?size=1&fields=hash`; + if (this.config.blockHashShard !== void 0) { + url += `&shard=${this.config.blockHashShard}`; + } + const response = yield this.get(url); + return response.data[0].hash; + }); + } + encodeValue(str) { + return this.escape(import_buffer.Buffer.from(str, "utf8").toString("base64")); + } + escape(str) { + return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + } + get(url) { + return __awaiter2(this, void 0, void 0, function* () { + return yield axios_1.default.get(url, { headers: this.config.extraRequestHeaders }); + }); + } + }; + exports2.NativeAuthClient = NativeAuthClient3; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js +var require_transactionStatus = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionStatus = void 0; + var TransactionStatus2 = class _TransactionStatus { + /** + * Creates a new TransactionStatus object. + */ + constructor(status) { + this.status = (status || "").toLowerCase(); + } + /** + * Creates an unknown status. + */ + static createUnknown() { + return new _TransactionStatus("unknown"); + } + /** + * Returns whether the transaction is pending (e.g. in mempool). + */ + isPending() { + return this.status == "received" || this.status == "pending"; + } + /** + * Returns whether the transaction has been executed (not necessarily with success). + */ + isExecuted() { + return this.isSuccessful() || this.isFailed() || this.isInvalid(); + } + /** + * Returns whether the transaction has been executed successfully. + */ + isSuccessful() { + return this.status == "executed" || this.status == "success" || this.status == "successful"; + } + /** + * Returns whether the transaction has been executed, but with a failure. + */ + isFailed() { + return this.status == "fail" || this.status == "failed" || this.status == "unsuccessful" || this.isInvalid(); + } + /** + * Returns whether the transaction has been executed, but marked as invalid (e.g. due to "insufficient funds"). + */ + isInvalid() { + return this.status == "invalid"; + } + toString() { + return this.status; + } + valueOf() { + return this.status; + } + equals(other) { + if (!other) { + return false; + } + return this.status == other.status; + } + }; + exports2.TransactionStatus = TransactionStatus2; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js +var require_transactionReceipt = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionReceipt = void 0; + var primitives_1 = require_primitives(); + var TransactionReceipt2 = class _TransactionReceipt { + constructor() { + this.value = ""; + this.sender = new primitives_1.Address(""); + this.data = ""; + this.hash = ""; + } + static fromHttpResponse(response) { + let receipt = new _TransactionReceipt(); + receipt.value = (response.value || 0).toString(); + receipt.sender = new primitives_1.Address(response.sender); + receipt.data = response.data; + receipt.hash = response.txHash; + return receipt; + } + }; + exports2.TransactionReceipt = TransactionReceipt2; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/errors.js +var require_errors5 = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/errors.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrContractQuery = exports2.ErrNetworkProvider = exports2.ErrUnexpectedCondition = exports2.Err = void 0; + var Err = class extends Error { + constructor(message, inner) { + super(message); + this.inner = void 0; + this.inner = inner; + } + }; + exports2.Err = Err; + var ErrUnexpectedCondition = class extends Err { + constructor(message) { + super(`Unexpected condition: [${message}]`); + } + }; + exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; + var ErrNetworkProvider = class extends Err { + constructor(url, error, inner) { + let message = `Request error on url [${url}]: [${error}]`; + super(message, inner); + } + }; + exports2.ErrNetworkProvider = ErrNetworkProvider; + var ErrContractQuery = class extends Err { + constructor(originalError) { + super(originalError.message.replace("executeQuery:", "")); + } + }; + exports2.ErrContractQuery = ErrContractQuery; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js +var require_transactionEvents = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionEventTopic = exports2.TransactionEventData = exports2.TransactionEvent = void 0; + var primitives_1 = require_primitives(); + var TransactionEvent = class _TransactionEvent { + constructor(init) { + this.address = new primitives_1.Address(""); + this.identifier = ""; + this.topics = []; + this.data = ""; + this.dataPayload = new TransactionEventData(import_buffer.Buffer.from("", "utf8")); + this.additionalData = []; + Object.assign(this, init); + } + static fromHttpResponse(responsePart) { + let result = new _TransactionEvent(); + result.address = new primitives_1.Address(responsePart.address); + result.identifier = responsePart.identifier || ""; + result.topics = (responsePart.topics || []).map((topic) => new TransactionEventTopic(topic)); + result.dataPayload = TransactionEventData.fromBase64(responsePart.data); + result.additionalData = (responsePart.additionalData || []).map(TransactionEventData.fromBase64); + result.data = result.dataPayload.toString(); + return result; + } + findFirstOrNoneTopic(predicate) { + return this.topics.filter((topic) => predicate(topic))[0]; + } + getLastTopic() { + return this.topics[this.topics.length - 1]; + } + }; + exports2.TransactionEvent = TransactionEvent; + var TransactionEventData = class _TransactionEventData { + constructor(data) { + this.raw = data; + } + static fromBase64(str) { + return new _TransactionEventData(import_buffer.Buffer.from(str || "", "base64")); + } + toString() { + return this.raw.toString("utf8"); + } + hex() { + return this.raw.toString("hex"); + } + valueOf() { + return this.raw; + } + }; + exports2.TransactionEventData = TransactionEventData; + var TransactionEventTopic = class { + constructor(topic) { + this.raw = import_buffer.Buffer.from(topic || "", "base64"); + } + toString() { + return this.raw.toString("utf8"); + } + hex() { + return this.raw.toString("hex"); + } + valueOf() { + return this.raw; + } + }; + exports2.TransactionEventTopic = TransactionEventTopic; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js +var require_transactionLogs = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.TransactionLogs = void 0; + var errors_1 = require_errors5(); + var primitives_1 = require_primitives(); + var transactionEvents_1 = require_transactionEvents(); + var TransactionLogs2 = class _TransactionLogs { + constructor(init) { + this.address = new primitives_1.Address(""); + this.events = []; + Object.assign(this, init); + } + static fromHttpResponse(logs) { + let result = new _TransactionLogs(); + result.address = new primitives_1.Address(logs.address); + result.events = (logs.events || []).map((event) => transactionEvents_1.TransactionEvent.fromHttpResponse(event)); + return result; + } + findSingleOrNoneEvent(identifier, predicate) { + let events = this.findEvents(identifier, predicate); + if (events.length > 1) { + throw new errors_1.ErrUnexpectedCondition(`more than one event of type ${identifier}`); + } + return events[0]; + } + findFirstOrNoneEvent(identifier, predicate) { + return this.findEvents(identifier, predicate)[0]; + } + findEvents(identifier, predicate) { + let events = this.events.filter((event) => event.identifier == identifier); + if (predicate) { + events = events.filter((event) => predicate(event)); + } + return events; + } + }; + exports2.TransactionLogs = TransactionLogs2; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/contractResults.js +var require_contractResults = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/contractResults.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractResultItem = exports2.ContractResults = void 0; + var transactionLogs_1 = require_transactionLogs(); + var primitives_1 = require_primitives(); + var ContractResults2 = class _ContractResults { + constructor(items) { + this.items = items; + this.items.sort(function(a3, b4) { + return a3.nonce.valueOf() - b4.nonce.valueOf(); + }); + } + static fromProxyHttpResponse(results) { + let items = results.map((item) => ContractResultItem.fromProxyHttpResponse(item)); + return new _ContractResults(items); + } + static fromApiHttpResponse(results) { + let items = results.map((item) => ContractResultItem.fromApiHttpResponse(item)); + return new _ContractResults(items); + } + }; + exports2.ContractResults = ContractResults2; + var ContractResultItem = class _ContractResultItem { + constructor(init) { + this.hash = ""; + this.nonce = 0; + this.value = ""; + this.receiver = new primitives_1.Address(""); + this.sender = new primitives_1.Address(""); + this.data = ""; + this.previousHash = ""; + this.originalHash = ""; + this.gasLimit = 0; + this.gasPrice = 0; + this.callType = 0; + this.returnMessage = ""; + this.logs = new transactionLogs_1.TransactionLogs(); + Object.assign(this, init); + } + static fromProxyHttpResponse(response) { + let item = _ContractResultItem.fromHttpResponse(response); + return item; + } + static fromApiHttpResponse(response) { + let item = _ContractResultItem.fromHttpResponse(response); + item.data = import_buffer.Buffer.from(item.data, "base64").toString(); + item.callType = Number(item.callType); + return item; + } + static fromHttpResponse(response) { + let item = new _ContractResultItem(); + item.hash = response.hash; + item.nonce = Number(response.nonce || 0); + item.value = (response.value || 0).toString(); + item.receiver = new primitives_1.Address(response.receiver); + item.sender = new primitives_1.Address(response.sender); + item.previousHash = response.prevTxHash; + item.originalHash = response.originalTxHash; + item.gasLimit = Number(response.gasLimit || 0); + item.gasPrice = Number(response.gasPrice || 0); + item.data = response.data || ""; + item.callType = response.callType; + item.returnMessage = response.returnMessage; + item.logs = transactionLogs_1.TransactionLogs.fromHttpResponse(response.logs || {}); + return item; + } + }; + exports2.ContractResultItem = ContractResultItem; + } +}); + +// node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js +var require_contractQueryRequest = __commonJS({ + "node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js"(exports2) { + "use strict"; + init_shim(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ContractQueryRequest = void 0; + var ContractQueryRequest2 = class { + constructor(query) { + this.query = query; + } + toHttpRequest() { + var _a; + let request = {}; + let query = this.query; + request.scAddress = query.address.bech32(); + request.caller = ((_a = query.caller) === null || _a === void 0 ? void 0 : _a.bech32()) ? query.caller.bech32() : void 0; + request.funcName = query.func.toString(); + request.value = query.value ? query.value.toString() : void 0; + request.args = query.getEncodedArguments(); + return request; + } + }; + exports2.ContractQueryRequest = ContractQueryRequest2; + } +}); + +// node_modules/qrcode/lib/can-promise.js +var require_can_promise = __commonJS({ + "node_modules/qrcode/lib/can-promise.js"(exports2, module2) { + init_shim(); + module2.exports = function() { + return typeof Promise === "function" && Promise.prototype && Promise.prototype.then; + }; + } +}); + +// node_modules/qrcode/lib/core/utils.js +var require_utils6 = __commonJS({ + "node_modules/qrcode/lib/core/utils.js"(exports2) { + init_shim(); + var toSJISFunction; + var CODEWORDS_COUNT = [ + 0, + // Not used + 26, + 44, + 70, + 100, + 134, + 172, + 196, + 242, + 292, + 346, + 404, + 466, + 532, + 581, + 655, + 733, + 815, + 901, + 991, + 1085, + 1156, + 1258, + 1364, + 1474, + 1588, + 1706, + 1828, + 1921, + 2051, + 2185, + 2323, + 2465, + 2611, + 2761, + 2876, + 3034, + 3196, + 3362, + 3532, + 3706 + ]; + exports2.getSymbolSize = function getSymbolSize(version2) { + if (!version2) + throw new Error('"version" cannot be null or undefined'); + if (version2 < 1 || version2 > 40) + throw new Error('"version" should be in range from 1 to 40'); + return version2 * 4 + 17; + }; + exports2.getSymbolTotalCodewords = function getSymbolTotalCodewords(version2) { + return CODEWORDS_COUNT[version2]; + }; + exports2.getBCHDigit = function(data) { + let digit = 0; + while (data !== 0) { + digit++; + data >>>= 1; + } + return digit; + }; + exports2.setToSJISFunction = function setToSJISFunction(f4) { + if (typeof f4 !== "function") { + throw new Error('"toSJISFunc" is not a valid function.'); + } + toSJISFunction = f4; + }; + exports2.isKanjiModeEnabled = function() { + return typeof toSJISFunction !== "undefined"; + }; + exports2.toSJIS = function toSJIS(kanji) { + return toSJISFunction(kanji); + }; + } +}); + +// node_modules/qrcode/lib/core/error-correction-level.js +var require_error_correction_level = __commonJS({ + "node_modules/qrcode/lib/core/error-correction-level.js"(exports2) { + init_shim(); + exports2.L = { bit: 1 }; + exports2.M = { bit: 0 }; + exports2.Q = { bit: 3 }; + exports2.H = { bit: 2 }; + function fromString3(string2) { + if (typeof string2 !== "string") { + throw new Error("Param is not a string"); + } + const lcStr = string2.toLowerCase(); + switch (lcStr) { + case "l": + case "low": + return exports2.L; + case "m": + case "medium": + return exports2.M; + case "q": + case "quartile": + return exports2.Q; + case "h": + case "high": + return exports2.H; + default: + throw new Error("Unknown EC Level: " + string2); + } + } + exports2.isValid = function isValid(level) { + return level && typeof level.bit !== "undefined" && level.bit >= 0 && level.bit < 4; + }; + exports2.from = function from3(value, defaultValue) { + if (exports2.isValid(value)) { + return value; + } + try { + return fromString3(value); + } catch (e2) { + return defaultValue; + } + }; + } +}); + +// node_modules/qrcode/lib/core/bit-buffer.js +var require_bit_buffer = __commonJS({ + "node_modules/qrcode/lib/core/bit-buffer.js"(exports2, module2) { + init_shim(); + function BitBuffer() { + this.buffer = []; + this.length = 0; + } + BitBuffer.prototype = { + get: function(index) { + const bufIndex = Math.floor(index / 8); + return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1; + }, + put: function(num, length2) { + for (let i2 = 0; i2 < length2; i2++) { + this.putBit((num >>> length2 - i2 - 1 & 1) === 1); + } + }, + getLengthInBits: function() { + return this.length; + }, + putBit: function(bit) { + const bufIndex = Math.floor(this.length / 8); + if (this.buffer.length <= bufIndex) { + this.buffer.push(0); + } + if (bit) { + this.buffer[bufIndex] |= 128 >>> this.length % 8; + } + this.length++; + } + }; + module2.exports = BitBuffer; + } +}); + +// node_modules/qrcode/lib/core/bit-matrix.js +var require_bit_matrix = __commonJS({ + "node_modules/qrcode/lib/core/bit-matrix.js"(exports2, module2) { + init_shim(); + function BitMatrix(size) { + if (!size || size < 1) { + throw new Error("BitMatrix size must be defined and greater than 0"); + } + this.size = size; + this.data = new Uint8Array(size * size); + this.reservedBit = new Uint8Array(size * size); + } + BitMatrix.prototype.set = function(row, col, value, reserved) { + const index = row * this.size + col; + this.data[index] = value; + if (reserved) + this.reservedBit[index] = true; + }; + BitMatrix.prototype.get = function(row, col) { + return this.data[row * this.size + col]; + }; + BitMatrix.prototype.xor = function(row, col, value) { + this.data[row * this.size + col] ^= value; + }; + BitMatrix.prototype.isReserved = function(row, col) { + return this.reservedBit[row * this.size + col]; + }; + module2.exports = BitMatrix; + } +}); + +// node_modules/qrcode/lib/core/alignment-pattern.js +var require_alignment_pattern = __commonJS({ + "node_modules/qrcode/lib/core/alignment-pattern.js"(exports2) { + init_shim(); + var getSymbolSize = require_utils6().getSymbolSize; + exports2.getRowColCoords = function getRowColCoords(version2) { + if (version2 === 1) + return []; + const posCount = Math.floor(version2 / 7) + 2; + const size = getSymbolSize(version2); + const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2; + const positions = [size - 7]; + for (let i2 = 1; i2 < posCount - 1; i2++) { + positions[i2] = positions[i2 - 1] - intervals; + } + positions.push(6); + return positions.reverse(); + }; + exports2.getPositions = function getPositions(version2) { + const coords = []; + const pos = exports2.getRowColCoords(version2); + const posLength = pos.length; + for (let i2 = 0; i2 < posLength; i2++) { + for (let j2 = 0; j2 < posLength; j2++) { + if (i2 === 0 && j2 === 0 || // top-left + i2 === 0 && j2 === posLength - 1 || // bottom-left + i2 === posLength - 1 && j2 === 0) { + continue; + } + coords.push([pos[i2], pos[j2]]); + } + } + return coords; + }; + } +}); + +// node_modules/qrcode/lib/core/finder-pattern.js +var require_finder_pattern = __commonJS({ + "node_modules/qrcode/lib/core/finder-pattern.js"(exports2) { + init_shim(); + var getSymbolSize = require_utils6().getSymbolSize; + var FINDER_PATTERN_SIZE = 7; + exports2.getPositions = function getPositions(version2) { + const size = getSymbolSize(version2); + return [ + // top-left + [0, 0], + // top-right + [size - FINDER_PATTERN_SIZE, 0], + // bottom-left + [0, size - FINDER_PATTERN_SIZE] + ]; + }; + } +}); + +// node_modules/qrcode/lib/core/mask-pattern.js +var require_mask_pattern = __commonJS({ + "node_modules/qrcode/lib/core/mask-pattern.js"(exports2) { + init_shim(); + exports2.Patterns = { + PATTERN000: 0, + PATTERN001: 1, + PATTERN010: 2, + PATTERN011: 3, + PATTERN100: 4, + PATTERN101: 5, + PATTERN110: 6, + PATTERN111: 7 + }; + var PenaltyScores = { + N1: 3, + N2: 3, + N3: 40, + N4: 10 + }; + exports2.isValid = function isValid(mask) { + return mask != null && mask !== "" && !isNaN(mask) && mask >= 0 && mask <= 7; + }; + exports2.from = function from3(value) { + return exports2.isValid(value) ? parseInt(value, 10) : void 0; + }; + exports2.getPenaltyN1 = function getPenaltyN1(data) { + const size = data.size; + let points = 0; + let sameCountCol = 0; + let sameCountRow = 0; + let lastCol = null; + let lastRow = null; + for (let row = 0; row < size; row++) { + sameCountCol = sameCountRow = 0; + lastCol = lastRow = null; + for (let col = 0; col < size; col++) { + let module3 = data.get(row, col); + if (module3 === lastCol) { + sameCountCol++; + } else { + if (sameCountCol >= 5) + points += PenaltyScores.N1 + (sameCountCol - 5); + lastCol = module3; + sameCountCol = 1; + } + module3 = data.get(col, row); + if (module3 === lastRow) { + sameCountRow++; + } else { + if (sameCountRow >= 5) + points += PenaltyScores.N1 + (sameCountRow - 5); + lastRow = module3; + sameCountRow = 1; + } + } + if (sameCountCol >= 5) + points += PenaltyScores.N1 + (sameCountCol - 5); + if (sameCountRow >= 5) + points += PenaltyScores.N1 + (sameCountRow - 5); + } + return points; + }; + exports2.getPenaltyN2 = function getPenaltyN2(data) { + const size = data.size; + let points = 0; + for (let row = 0; row < size - 1; row++) { + for (let col = 0; col < size - 1; col++) { + const last = data.get(row, col) + data.get(row, col + 1) + data.get(row + 1, col) + data.get(row + 1, col + 1); + if (last === 4 || last === 0) + points++; + } + } + return points * PenaltyScores.N2; + }; + exports2.getPenaltyN3 = function getPenaltyN3(data) { + const size = data.size; + let points = 0; + let bitsCol = 0; + let bitsRow = 0; + for (let row = 0; row < size; row++) { + bitsCol = bitsRow = 0; + for (let col = 0; col < size; col++) { + bitsCol = bitsCol << 1 & 2047 | data.get(row, col); + if (col >= 10 && (bitsCol === 1488 || bitsCol === 93)) + points++; + bitsRow = bitsRow << 1 & 2047 | data.get(col, row); + if (col >= 10 && (bitsRow === 1488 || bitsRow === 93)) + points++; + } + } + return points * PenaltyScores.N3; + }; + exports2.getPenaltyN4 = function getPenaltyN4(data) { + let darkCount = 0; + const modulesCount = data.data.length; + for (let i2 = 0; i2 < modulesCount; i2++) + darkCount += data.data[i2]; + const k4 = Math.abs(Math.ceil(darkCount * 100 / modulesCount / 5) - 10); + return k4 * PenaltyScores.N4; + }; + function getMaskAt(maskPattern, i2, j2) { + switch (maskPattern) { + case exports2.Patterns.PATTERN000: + return (i2 + j2) % 2 === 0; + case exports2.Patterns.PATTERN001: + return i2 % 2 === 0; + case exports2.Patterns.PATTERN010: + return j2 % 3 === 0; + case exports2.Patterns.PATTERN011: + return (i2 + j2) % 3 === 0; + case exports2.Patterns.PATTERN100: + return (Math.floor(i2 / 2) + Math.floor(j2 / 3)) % 2 === 0; + case exports2.Patterns.PATTERN101: + return i2 * j2 % 2 + i2 * j2 % 3 === 0; + case exports2.Patterns.PATTERN110: + return (i2 * j2 % 2 + i2 * j2 % 3) % 2 === 0; + case exports2.Patterns.PATTERN111: + return (i2 * j2 % 3 + (i2 + j2) % 2) % 2 === 0; + default: + throw new Error("bad maskPattern:" + maskPattern); + } + } + exports2.applyMask = function applyMask(pattern, data) { + const size = data.size; + for (let col = 0; col < size; col++) { + for (let row = 0; row < size; row++) { + if (data.isReserved(row, col)) + continue; + data.xor(row, col, getMaskAt(pattern, row, col)); + } + } + }; + exports2.getBestMask = function getBestMask(data, setupFormatFunc) { + const numPatterns = Object.keys(exports2.Patterns).length; + let bestPattern = 0; + let lowerPenalty = Infinity; + for (let p3 = 0; p3 < numPatterns; p3++) { + setupFormatFunc(p3); + exports2.applyMask(p3, data); + const penalty = exports2.getPenaltyN1(data) + exports2.getPenaltyN2(data) + exports2.getPenaltyN3(data) + exports2.getPenaltyN4(data); + exports2.applyMask(p3, data); + if (penalty < lowerPenalty) { + lowerPenalty = penalty; + bestPattern = p3; + } + } + return bestPattern; + }; + } +}); + +// node_modules/qrcode/lib/core/error-correction-code.js +var require_error_correction_code = __commonJS({ + "node_modules/qrcode/lib/core/error-correction-code.js"(exports2) { + init_shim(); + var ECLevel = require_error_correction_level(); + var EC_BLOCKS_TABLE = [ + // L M Q H + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 1, + 2, + 2, + 4, + 1, + 2, + 4, + 4, + 2, + 4, + 4, + 4, + 2, + 4, + 6, + 5, + 2, + 4, + 6, + 6, + 2, + 5, + 8, + 8, + 4, + 5, + 8, + 8, + 4, + 5, + 8, + 11, + 4, + 8, + 10, + 11, + 4, + 9, + 12, + 16, + 4, + 9, + 16, + 16, + 6, + 10, + 12, + 18, + 6, + 10, + 17, + 16, + 6, + 11, + 16, + 19, + 6, + 13, + 18, + 21, + 7, + 14, + 21, + 25, + 8, + 16, + 20, + 25, + 8, + 17, + 23, + 25, + 9, + 17, + 23, + 34, + 9, + 18, + 25, + 30, + 10, + 20, + 27, + 32, + 12, + 21, + 29, + 35, + 12, + 23, + 34, + 37, + 12, + 25, + 34, + 40, + 13, + 26, + 35, + 42, + 14, + 28, + 38, + 45, + 15, + 29, + 40, + 48, + 16, + 31, + 43, + 51, + 17, + 33, + 45, + 54, + 18, + 35, + 48, + 57, + 19, + 37, + 51, + 60, + 19, + 38, + 53, + 63, + 20, + 40, + 56, + 66, + 21, + 43, + 59, + 70, + 22, + 45, + 62, + 74, + 24, + 47, + 65, + 77, + 25, + 49, + 68, + 81 + ]; + var EC_CODEWORDS_TABLE = [ + // L M Q H + 7, + 10, + 13, + 17, + 10, + 16, + 22, + 28, + 15, + 26, + 36, + 44, + 20, + 36, + 52, + 64, + 26, + 48, + 72, + 88, + 36, + 64, + 96, + 112, + 40, + 72, + 108, + 130, + 48, + 88, + 132, + 156, + 60, + 110, + 160, + 192, + 72, + 130, + 192, + 224, + 80, + 150, + 224, + 264, + 96, + 176, + 260, + 308, + 104, + 198, + 288, + 352, + 120, + 216, + 320, + 384, + 132, + 240, + 360, + 432, + 144, + 280, + 408, + 480, + 168, + 308, + 448, + 532, + 180, + 338, + 504, + 588, + 196, + 364, + 546, + 650, + 224, + 416, + 600, + 700, + 224, + 442, + 644, + 750, + 252, + 476, + 690, + 816, + 270, + 504, + 750, + 900, + 300, + 560, + 810, + 960, + 312, + 588, + 870, + 1050, + 336, + 644, + 952, + 1110, + 360, + 700, + 1020, + 1200, + 390, + 728, + 1050, + 1260, + 420, + 784, + 1140, + 1350, + 450, + 812, + 1200, + 1440, + 480, + 868, + 1290, + 1530, + 510, + 924, + 1350, + 1620, + 540, + 980, + 1440, + 1710, + 570, + 1036, + 1530, + 1800, + 570, + 1064, + 1590, + 1890, + 600, + 1120, + 1680, + 1980, + 630, + 1204, + 1770, + 2100, + 660, + 1260, + 1860, + 2220, + 720, + 1316, + 1950, + 2310, + 750, + 1372, + 2040, + 2430 + ]; + exports2.getBlocksCount = function getBlocksCount(version2, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 0]; + case ECLevel.M: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 1]; + case ECLevel.Q: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 2]; + case ECLevel.H: + return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 3]; + default: + return void 0; + } + }; + exports2.getTotalCodewordsCount = function getTotalCodewordsCount(version2, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 0]; + case ECLevel.M: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 1]; + case ECLevel.Q: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 2]; + case ECLevel.H: + return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 3]; + default: + return void 0; + } + }; + } +}); + +// node_modules/qrcode/lib/core/galois-field.js +var require_galois_field = __commonJS({ + "node_modules/qrcode/lib/core/galois-field.js"(exports2) { + init_shim(); + var EXP_TABLE = new Uint8Array(512); + var LOG_TABLE = new Uint8Array(256); + (function initTables() { + let x3 = 1; + for (let i2 = 0; i2 < 255; i2++) { + EXP_TABLE[i2] = x3; + LOG_TABLE[x3] = i2; + x3 <<= 1; + if (x3 & 256) { + x3 ^= 285; + } + } + for (let i2 = 255; i2 < 512; i2++) { + EXP_TABLE[i2] = EXP_TABLE[i2 - 255]; + } + })(); + exports2.log = function log(n3) { + if (n3 < 1) + throw new Error("log(" + n3 + ")"); + return LOG_TABLE[n3]; + }; + exports2.exp = function exp(n3) { + return EXP_TABLE[n3]; + }; + exports2.mul = function mul(x3, y4) { + if (x3 === 0 || y4 === 0) + return 0; + return EXP_TABLE[LOG_TABLE[x3] + LOG_TABLE[y4]]; + }; + } +}); + +// node_modules/qrcode/lib/core/polynomial.js +var require_polynomial = __commonJS({ + "node_modules/qrcode/lib/core/polynomial.js"(exports2) { + init_shim(); + var GF = require_galois_field(); + exports2.mul = function mul(p1, p22) { + const coeff = new Uint8Array(p1.length + p22.length - 1); + for (let i2 = 0; i2 < p1.length; i2++) { + for (let j2 = 0; j2 < p22.length; j2++) { + coeff[i2 + j2] ^= GF.mul(p1[i2], p22[j2]); + } + } + return coeff; + }; + exports2.mod = function mod2(divident, divisor) { + let result = new Uint8Array(divident); + while (result.length - divisor.length >= 0) { + const coeff = result[0]; + for (let i2 = 0; i2 < divisor.length; i2++) { + result[i2] ^= GF.mul(divisor[i2], coeff); + } + let offset = 0; + while (offset < result.length && result[offset] === 0) + offset++; + result = result.slice(offset); + } + return result; + }; + exports2.generateECPolynomial = function generateECPolynomial(degree) { + let poly = new Uint8Array([1]); + for (let i2 = 0; i2 < degree; i2++) { + poly = exports2.mul(poly, new Uint8Array([1, GF.exp(i2)])); + } + return poly; + }; + } +}); + +// node_modules/qrcode/lib/core/reed-solomon-encoder.js +var require_reed_solomon_encoder = __commonJS({ + "node_modules/qrcode/lib/core/reed-solomon-encoder.js"(exports2, module2) { + init_shim(); + var Polynomial = require_polynomial(); + function ReedSolomonEncoder(degree) { + this.genPoly = void 0; + this.degree = degree; + if (this.degree) + this.initialize(this.degree); + } + ReedSolomonEncoder.prototype.initialize = function initialize(degree) { + this.degree = degree; + this.genPoly = Polynomial.generateECPolynomial(this.degree); + }; + ReedSolomonEncoder.prototype.encode = function encode5(data) { + if (!this.genPoly) { + throw new Error("Encoder not initialized"); + } + const paddedData = new Uint8Array(data.length + this.degree); + paddedData.set(data); + const remainder = Polynomial.mod(paddedData, this.genPoly); + const start = this.degree - remainder.length; + if (start > 0) { + const buff = new Uint8Array(this.degree); + buff.set(remainder, start); + return buff; + } + return remainder; + }; + module2.exports = ReedSolomonEncoder; + } +}); + +// node_modules/qrcode/lib/core/version-check.js +var require_version_check = __commonJS({ + "node_modules/qrcode/lib/core/version-check.js"(exports2) { + init_shim(); + exports2.isValid = function isValid(version2) { + return !isNaN(version2) && version2 >= 1 && version2 <= 40; + }; + } +}); + +// node_modules/qrcode/lib/core/regex.js +var require_regex = __commonJS({ + "node_modules/qrcode/lib/core/regex.js"(exports2) { + init_shim(); + var numeric = "[0-9]+"; + var alphanumeric = "[A-Z $%*+\\-./:]+"; + var kanji = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+"; + kanji = kanji.replace(/u/g, "\\u"); + var byte = "(?:(?![A-Z0-9 $%*+\\-./:]|" + kanji + ")(?:.|[\r\n]))+"; + exports2.KANJI = new RegExp(kanji, "g"); + exports2.BYTE_KANJI = new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g"); + exports2.BYTE = new RegExp(byte, "g"); + exports2.NUMERIC = new RegExp(numeric, "g"); + exports2.ALPHANUMERIC = new RegExp(alphanumeric, "g"); + var TEST_KANJI = new RegExp("^" + kanji + "$"); + var TEST_NUMERIC = new RegExp("^" + numeric + "$"); + var TEST_ALPHANUMERIC = new RegExp("^[A-Z0-9 $%*+\\-./:]+$"); + exports2.testKanji = function testKanji(str) { + return TEST_KANJI.test(str); + }; + exports2.testNumeric = function testNumeric(str) { + return TEST_NUMERIC.test(str); + }; + exports2.testAlphanumeric = function testAlphanumeric(str) { + return TEST_ALPHANUMERIC.test(str); + }; + } +}); + +// node_modules/qrcode/lib/core/mode.js +var require_mode = __commonJS({ + "node_modules/qrcode/lib/core/mode.js"(exports2) { + init_shim(); + var VersionCheck = require_version_check(); + var Regex = require_regex(); + exports2.NUMERIC = { + id: "Numeric", + bit: 1 << 0, + ccBits: [10, 12, 14] + }; + exports2.ALPHANUMERIC = { + id: "Alphanumeric", + bit: 1 << 1, + ccBits: [9, 11, 13] + }; + exports2.BYTE = { + id: "Byte", + bit: 1 << 2, + ccBits: [8, 16, 16] + }; + exports2.KANJI = { + id: "Kanji", + bit: 1 << 3, + ccBits: [8, 10, 12] + }; + exports2.MIXED = { + bit: -1 + }; + exports2.getCharCountIndicator = function getCharCountIndicator(mode, version2) { + if (!mode.ccBits) + throw new Error("Invalid mode: " + mode); + if (!VersionCheck.isValid(version2)) { + throw new Error("Invalid version: " + version2); + } + if (version2 >= 1 && version2 < 10) + return mode.ccBits[0]; + else if (version2 < 27) + return mode.ccBits[1]; + return mode.ccBits[2]; + }; + exports2.getBestModeForData = function getBestModeForData(dataStr) { + if (Regex.testNumeric(dataStr)) + return exports2.NUMERIC; + else if (Regex.testAlphanumeric(dataStr)) + return exports2.ALPHANUMERIC; + else if (Regex.testKanji(dataStr)) + return exports2.KANJI; + else + return exports2.BYTE; + }; + exports2.toString = function toString3(mode) { + if (mode && mode.id) + return mode.id; + throw new Error("Invalid mode"); + }; + exports2.isValid = function isValid(mode) { + return mode && mode.bit && mode.ccBits; + }; + function fromString3(string2) { + if (typeof string2 !== "string") { + throw new Error("Param is not a string"); + } + const lcStr = string2.toLowerCase(); + switch (lcStr) { + case "numeric": + return exports2.NUMERIC; + case "alphanumeric": + return exports2.ALPHANUMERIC; + case "kanji": + return exports2.KANJI; + case "byte": + return exports2.BYTE; + default: + throw new Error("Unknown mode: " + string2); + } + } + exports2.from = function from3(value, defaultValue) { + if (exports2.isValid(value)) { + return value; + } + try { + return fromString3(value); + } catch (e2) { + return defaultValue; + } + }; + } +}); + +// node_modules/qrcode/lib/core/version.js +var require_version = __commonJS({ + "node_modules/qrcode/lib/core/version.js"(exports2) { + init_shim(); + var Utils = require_utils6(); + var ECCode = require_error_correction_code(); + var ECLevel = require_error_correction_level(); + var Mode = require_mode(); + var VersionCheck = require_version_check(); + var G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0; + var G18_BCH = Utils.getBCHDigit(G18); + function getBestVersionForDataLength(mode, length2, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, mode)) { + return currentVersion; + } + } + return void 0; + } + function getReservedBitsCount(mode, version2) { + return Mode.getCharCountIndicator(mode, version2) + 4; + } + function getTotalBitsFromDataArray(segments, version2) { + let totalBits = 0; + segments.forEach(function(data) { + const reservedBits = getReservedBitsCount(data.mode, version2); + totalBits += reservedBits + data.getBitsLength(); + }); + return totalBits; + } + function getBestVersionForMixedData(segments, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + const length2 = getTotalBitsFromDataArray(segments, currentVersion); + if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { + return currentVersion; + } + } + return void 0; + } + exports2.from = function from3(value, defaultValue) { + if (VersionCheck.isValid(value)) { + return parseInt(value, 10); + } + return defaultValue; + }; + exports2.getCapacity = function getCapacity(version2, errorCorrectionLevel, mode) { + if (!VersionCheck.isValid(version2)) { + throw new Error("Invalid QR Code version"); + } + if (typeof mode === "undefined") + mode = Mode.BYTE; + const totalCodewords = Utils.getSymbolTotalCodewords(version2); + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; + if (mode === Mode.MIXED) + return dataTotalCodewordsBits; + const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version2); + switch (mode) { + case Mode.NUMERIC: + return Math.floor(usableBits / 10 * 3); + case Mode.ALPHANUMERIC: + return Math.floor(usableBits / 11 * 2); + case Mode.KANJI: + return Math.floor(usableBits / 13); + case Mode.BYTE: + default: + return Math.floor(usableBits / 8); + } + }; + exports2.getBestVersionForData = function getBestVersionForData(data, errorCorrectionLevel) { + let seg; + const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M); + if (Array.isArray(data)) { + if (data.length > 1) { + return getBestVersionForMixedData(data, ecl); + } + if (data.length === 0) { + return 1; + } + seg = data[0]; + } else { + seg = data; + } + return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl); + }; + exports2.getEncodedBits = function getEncodedBits(version2) { + if (!VersionCheck.isValid(version2) || version2 < 7) { + throw new Error("Invalid QR Code version"); + } + let d3 = version2 << 12; + while (Utils.getBCHDigit(d3) - G18_BCH >= 0) { + d3 ^= G18 << Utils.getBCHDigit(d3) - G18_BCH; + } + return version2 << 12 | d3; + }; + } +}); + +// node_modules/qrcode/lib/core/format-info.js +var require_format_info = __commonJS({ + "node_modules/qrcode/lib/core/format-info.js"(exports2) { + init_shim(); + var Utils = require_utils6(); + var G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0; + var G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1; + var G15_BCH = Utils.getBCHDigit(G15); + exports2.getEncodedBits = function getEncodedBits(errorCorrectionLevel, mask) { + const data = errorCorrectionLevel.bit << 3 | mask; + let d3 = data << 10; + while (Utils.getBCHDigit(d3) - G15_BCH >= 0) { + d3 ^= G15 << Utils.getBCHDigit(d3) - G15_BCH; + } + return (data << 10 | d3) ^ G15_MASK; + }; + } +}); + +// node_modules/qrcode/lib/core/numeric-data.js +var require_numeric_data = __commonJS({ + "node_modules/qrcode/lib/core/numeric-data.js"(exports2, module2) { + init_shim(); + var Mode = require_mode(); + function NumericData(data) { + this.mode = Mode.NUMERIC; + this.data = data.toString(); + } + NumericData.getBitsLength = function getBitsLength(length2) { + return 10 * Math.floor(length2 / 3) + (length2 % 3 ? length2 % 3 * 3 + 1 : 0); + }; + NumericData.prototype.getLength = function getLength() { + return this.data.length; + }; + NumericData.prototype.getBitsLength = function getBitsLength() { + return NumericData.getBitsLength(this.data.length); + }; + NumericData.prototype.write = function write(bitBuffer) { + let i2, group, value; + for (i2 = 0; i2 + 3 <= this.data.length; i2 += 3) { + group = this.data.substr(i2, 3); + value = parseInt(group, 10); + bitBuffer.put(value, 10); + } + const remainingNum = this.data.length - i2; + if (remainingNum > 0) { + group = this.data.substr(i2); + value = parseInt(group, 10); + bitBuffer.put(value, remainingNum * 3 + 1); + } + }; + module2.exports = NumericData; + } +}); + +// node_modules/qrcode/lib/core/alphanumeric-data.js +var require_alphanumeric_data = __commonJS({ + "node_modules/qrcode/lib/core/alphanumeric-data.js"(exports2, module2) { + init_shim(); + var Mode = require_mode(); + var ALPHA_NUM_CHARS = [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + " ", + "$", + "%", + "*", + "+", + "-", + ".", + "/", + ":" + ]; + function AlphanumericData(data) { + this.mode = Mode.ALPHANUMERIC; + this.data = data; + } + AlphanumericData.getBitsLength = function getBitsLength(length2) { + return 11 * Math.floor(length2 / 2) + 6 * (length2 % 2); + }; + AlphanumericData.prototype.getLength = function getLength() { + return this.data.length; + }; + AlphanumericData.prototype.getBitsLength = function getBitsLength() { + return AlphanumericData.getBitsLength(this.data.length); + }; + AlphanumericData.prototype.write = function write(bitBuffer) { + let i2; + for (i2 = 0; i2 + 2 <= this.data.length; i2 += 2) { + let value = ALPHA_NUM_CHARS.indexOf(this.data[i2]) * 45; + value += ALPHA_NUM_CHARS.indexOf(this.data[i2 + 1]); + bitBuffer.put(value, 11); + } + if (this.data.length % 2) { + bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i2]), 6); + } + }; + module2.exports = AlphanumericData; + } +}); + +// node_modules/encode-utf8/index.js +var require_encode_utf8 = __commonJS({ + "node_modules/encode-utf8/index.js"(exports2, module2) { + "use strict"; + init_shim(); + module2.exports = function encodeUtf8(input) { + var result = []; + var size = input.length; + for (var index = 0; index < size; index++) { + var point = input.charCodeAt(index); + if (point >= 55296 && point <= 56319 && size > index + 1) { + var second = input.charCodeAt(index + 1); + if (second >= 56320 && second <= 57343) { + point = (point - 55296) * 1024 + second - 56320 + 65536; + index += 1; + } + } + if (point < 128) { + result.push(point); + continue; + } + if (point < 2048) { + result.push(point >> 6 | 192); + result.push(point & 63 | 128); + continue; + } + if (point < 55296 || point >= 57344 && point < 65536) { + result.push(point >> 12 | 224); + result.push(point >> 6 & 63 | 128); + result.push(point & 63 | 128); + continue; + } + if (point >= 65536 && point <= 1114111) { + result.push(point >> 18 | 240); + result.push(point >> 12 & 63 | 128); + result.push(point >> 6 & 63 | 128); + result.push(point & 63 | 128); + continue; + } + result.push(239, 191, 189); + } + return new Uint8Array(result).buffer; + }; + } +}); + +// node_modules/qrcode/lib/core/byte-data.js +var require_byte_data = __commonJS({ + "node_modules/qrcode/lib/core/byte-data.js"(exports2, module2) { + init_shim(); + var encodeUtf8 = require_encode_utf8(); + var Mode = require_mode(); + function ByteData(data) { + this.mode = Mode.BYTE; + if (typeof data === "string") { + data = encodeUtf8(data); + } + this.data = new Uint8Array(data); + } + ByteData.getBitsLength = function getBitsLength(length2) { + return length2 * 8; + }; + ByteData.prototype.getLength = function getLength() { + return this.data.length; + }; + ByteData.prototype.getBitsLength = function getBitsLength() { + return ByteData.getBitsLength(this.data.length); + }; + ByteData.prototype.write = function(bitBuffer) { + for (let i2 = 0, l4 = this.data.length; i2 < l4; i2++) { + bitBuffer.put(this.data[i2], 8); + } + }; + module2.exports = ByteData; + } +}); + +// node_modules/qrcode/lib/core/kanji-data.js +var require_kanji_data = __commonJS({ + "node_modules/qrcode/lib/core/kanji-data.js"(exports2, module2) { + init_shim(); + var Mode = require_mode(); + var Utils = require_utils6(); + function KanjiData(data) { + this.mode = Mode.KANJI; + this.data = data; + } + KanjiData.getBitsLength = function getBitsLength(length2) { + return length2 * 13; + }; + KanjiData.prototype.getLength = function getLength() { + return this.data.length; + }; + KanjiData.prototype.getBitsLength = function getBitsLength() { + return KanjiData.getBitsLength(this.data.length); + }; + KanjiData.prototype.write = function(bitBuffer) { + let i2; + for (i2 = 0; i2 < this.data.length; i2++) { + let value = Utils.toSJIS(this.data[i2]); + if (value >= 33088 && value <= 40956) { + value -= 33088; + } else if (value >= 57408 && value <= 60351) { + value -= 49472; + } else { + throw new Error( + "Invalid SJIS character: " + this.data[i2] + "\nMake sure your charset is UTF-8" + ); + } + value = (value >>> 8 & 255) * 192 + (value & 255); + bitBuffer.put(value, 13); + } + }; + module2.exports = KanjiData; + } +}); + +// node_modules/dijkstrajs/dijkstra.js +var require_dijkstra = __commonJS({ + "node_modules/dijkstrajs/dijkstra.js"(exports2, module2) { + "use strict"; + init_shim(); + var dijkstra = { + single_source_shortest_paths: function(graph, s2, d3) { + var predecessors = {}; + var costs = {}; + costs[s2] = 0; + var open = dijkstra.PriorityQueue.make(); + open.push(s2, 0); + var closest, u3, v2, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit; + while (!open.empty()) { + closest = open.pop(); + u3 = closest.value; + cost_of_s_to_u = closest.cost; + adjacent_nodes = graph[u3] || {}; + for (v2 in adjacent_nodes) { + if (adjacent_nodes.hasOwnProperty(v2)) { + cost_of_e = adjacent_nodes[v2]; + cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; + cost_of_s_to_v = costs[v2]; + first_visit = typeof costs[v2] === "undefined"; + if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { + costs[v2] = cost_of_s_to_u_plus_cost_of_e; + open.push(v2, cost_of_s_to_u_plus_cost_of_e); + predecessors[v2] = u3; + } + } + } + } + if (typeof d3 !== "undefined" && typeof costs[d3] === "undefined") { + var msg = ["Could not find a path from ", s2, " to ", d3, "."].join(""); + throw new Error(msg); + } + return predecessors; + }, + extract_shortest_path_from_predecessor_list: function(predecessors, d3) { + var nodes = []; + var u3 = d3; + var predecessor; + while (u3) { + nodes.push(u3); + predecessor = predecessors[u3]; + u3 = predecessors[u3]; + } + nodes.reverse(); + return nodes; + }, + find_path: function(graph, s2, d3) { + var predecessors = dijkstra.single_source_shortest_paths(graph, s2, d3); + return dijkstra.extract_shortest_path_from_predecessor_list( + predecessors, + d3 + ); + }, + /** + * A very naive priority queue implementation. + */ + PriorityQueue: { + make: function(opts) { + var T2 = dijkstra.PriorityQueue, t = {}, key; + opts = opts || {}; + for (key in T2) { + if (T2.hasOwnProperty(key)) { + t[key] = T2[key]; + } + } + t.queue = []; + t.sorter = opts.sorter || T2.default_sorter; + return t; + }, + default_sorter: function(a3, b4) { + return a3.cost - b4.cost; + }, + /** + * Add a new item to the queue and ensure the highest priority element + * is at the front of the queue. + */ + push: function(value, cost) { + var item = { value, cost }; + this.queue.push(item); + this.queue.sort(this.sorter); + }, + /** + * Return the highest priority element in the queue. + */ + pop: function() { + return this.queue.shift(); + }, + empty: function() { + return this.queue.length === 0; + } + } + }; + if (typeof module2 !== "undefined") { + module2.exports = dijkstra; + } + } +}); + +// node_modules/qrcode/lib/core/segments.js +var require_segments = __commonJS({ + "node_modules/qrcode/lib/core/segments.js"(exports2) { + init_shim(); + var Mode = require_mode(); + var NumericData = require_numeric_data(); + var AlphanumericData = require_alphanumeric_data(); + var ByteData = require_byte_data(); + var KanjiData = require_kanji_data(); + var Regex = require_regex(); + var Utils = require_utils6(); + var dijkstra = require_dijkstra(); + function getStringByteLength(str) { + return unescape(encodeURIComponent(str)).length; + } + function getSegments(regex, mode, str) { + const segments = []; + let result; + while ((result = regex.exec(str)) !== null) { + segments.push({ + data: result[0], + index: result.index, + mode, + length: result[0].length + }); + } + return segments; + } + function getSegmentsFromString(dataStr) { + const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr); + const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr); + let byteSegs; + let kanjiSegs; + if (Utils.isKanjiModeEnabled()) { + byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr); + kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr); + } else { + byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr); + kanjiSegs = []; + } + const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs); + return segs.sort(function(s1, s2) { + return s1.index - s2.index; + }).map(function(obj) { + return { + data: obj.data, + mode: obj.mode, + length: obj.length + }; + }); + } + function getSegmentBitsLength(length2, mode) { + switch (mode) { + case Mode.NUMERIC: + return NumericData.getBitsLength(length2); + case Mode.ALPHANUMERIC: + return AlphanumericData.getBitsLength(length2); + case Mode.KANJI: + return KanjiData.getBitsLength(length2); + case Mode.BYTE: + return ByteData.getBitsLength(length2); + } + } + function mergeSegments(segs) { + return segs.reduce(function(acc, curr) { + const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null; + if (prevSeg && prevSeg.mode === curr.mode) { + acc[acc.length - 1].data += curr.data; + return acc; + } + acc.push(curr); + return acc; + }, []); + } + function buildNodes(segs) { + const nodes = []; + for (let i2 = 0; i2 < segs.length; i2++) { + const seg = segs[i2]; + switch (seg.mode) { + case Mode.NUMERIC: + nodes.push([ + seg, + { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]); + break; + case Mode.ALPHANUMERIC: + nodes.push([ + seg, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]); + break; + case Mode.KANJI: + nodes.push([ + seg, + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]); + break; + case Mode.BYTE: + nodes.push([ + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]); + } + } + return nodes; + } + function buildGraph(nodes, version2) { + const table = {}; + const graph = { start: {} }; + let prevNodeIds = ["start"]; + for (let i2 = 0; i2 < nodes.length; i2++) { + const nodeGroup = nodes[i2]; + const currentNodeIds = []; + for (let j2 = 0; j2 < nodeGroup.length; j2++) { + const node = nodeGroup[j2]; + const key = "" + i2 + j2; + currentNodeIds.push(key); + table[key] = { node, lastCount: 0 }; + graph[key] = {}; + for (let n3 = 0; n3 < prevNodeIds.length; n3++) { + const prevNodeId = prevNodeIds[n3]; + if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { + graph[prevNodeId][key] = getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - getSegmentBitsLength(table[prevNodeId].lastCount, node.mode); + table[prevNodeId].lastCount += node.length; + } else { + if (table[prevNodeId]) + table[prevNodeId].lastCount = node.length; + graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + 4 + Mode.getCharCountIndicator(node.mode, version2); + } + } + } + prevNodeIds = currentNodeIds; + } + for (let n3 = 0; n3 < prevNodeIds.length; n3++) { + graph[prevNodeIds[n3]].end = 0; + } + return { map: graph, table }; + } + function buildSingleSegment(data, modesHint) { + let mode; + const bestMode = Mode.getBestModeForData(data); + mode = Mode.from(modesHint, bestMode); + if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { + throw new Error('"' + data + '" cannot be encoded with mode ' + Mode.toString(mode) + ".\n Suggested mode is: " + Mode.toString(bestMode)); + } + if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { + mode = Mode.BYTE; + } + switch (mode) { + case Mode.NUMERIC: + return new NumericData(data); + case Mode.ALPHANUMERIC: + return new AlphanumericData(data); + case Mode.KANJI: + return new KanjiData(data); + case Mode.BYTE: + return new ByteData(data); + } + } + exports2.fromArray = function fromArray(array) { + return array.reduce(function(acc, seg) { + if (typeof seg === "string") { + acc.push(buildSingleSegment(seg, null)); + } else if (seg.data) { + acc.push(buildSingleSegment(seg.data, seg.mode)); + } + return acc; + }, []); + }; + exports2.fromString = function fromString3(data, version2) { + const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()); + const nodes = buildNodes(segs); + const graph = buildGraph(nodes, version2); + const path = dijkstra.find_path(graph.map, "start", "end"); + const optimizedSegs = []; + for (let i2 = 1; i2 < path.length - 1; i2++) { + optimizedSegs.push(graph.table[path[i2]].node); + } + return exports2.fromArray(mergeSegments(optimizedSegs)); + }; + exports2.rawSplit = function rawSplit(data) { + return exports2.fromArray( + getSegmentsFromString(data, Utils.isKanjiModeEnabled()) + ); + }; + } +}); + +// node_modules/qrcode/lib/core/qrcode.js +var require_qrcode = __commonJS({ + "node_modules/qrcode/lib/core/qrcode.js"(exports2) { + init_shim(); + var Utils = require_utils6(); + var ECLevel = require_error_correction_level(); + var BitBuffer = require_bit_buffer(); + var BitMatrix = require_bit_matrix(); + var AlignmentPattern = require_alignment_pattern(); + var FinderPattern = require_finder_pattern(); + var MaskPattern = require_mask_pattern(); + var ECCode = require_error_correction_code(); + var ReedSolomonEncoder = require_reed_solomon_encoder(); + var Version = require_version(); + var FormatInfo = require_format_info(); + var Mode = require_mode(); + var Segments = require_segments(); + function setupFinderPattern(matrix, version2) { + const size = matrix.size; + const pos = FinderPattern.getPositions(version2); + for (let i2 = 0; i2 < pos.length; i2++) { + const row = pos[i2][0]; + const col = pos[i2][1]; + for (let r = -1; r <= 7; r++) { + if (row + r <= -1 || size <= row + r) + continue; + for (let c4 = -1; c4 <= 7; c4++) { + if (col + c4 <= -1 || size <= col + c4) + continue; + if (r >= 0 && r <= 6 && (c4 === 0 || c4 === 6) || c4 >= 0 && c4 <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c4 >= 2 && c4 <= 4) { + matrix.set(row + r, col + c4, true, true); + } else { + matrix.set(row + r, col + c4, false, true); + } + } + } + } + } + function setupTimingPattern(matrix) { + const size = matrix.size; + for (let r = 8; r < size - 8; r++) { + const value = r % 2 === 0; + matrix.set(r, 6, value, true); + matrix.set(6, r, value, true); + } + } + function setupAlignmentPattern(matrix, version2) { + const pos = AlignmentPattern.getPositions(version2); + for (let i2 = 0; i2 < pos.length; i2++) { + const row = pos[i2][0]; + const col = pos[i2][1]; + for (let r = -2; r <= 2; r++) { + for (let c4 = -2; c4 <= 2; c4++) { + if (r === -2 || r === 2 || c4 === -2 || c4 === 2 || r === 0 && c4 === 0) { + matrix.set(row + r, col + c4, true, true); + } else { + matrix.set(row + r, col + c4, false, true); + } + } + } + } + } + function setupVersionInfo(matrix, version2) { + const size = matrix.size; + const bits = Version.getEncodedBits(version2); + let row, col, mod2; + for (let i2 = 0; i2 < 18; i2++) { + row = Math.floor(i2 / 3); + col = i2 % 3 + size - 8 - 3; + mod2 = (bits >> i2 & 1) === 1; + matrix.set(row, col, mod2, true); + matrix.set(col, row, mod2, true); + } + } + function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) { + const size = matrix.size; + const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern); + let i2, mod2; + for (i2 = 0; i2 < 15; i2++) { + mod2 = (bits >> i2 & 1) === 1; + if (i2 < 6) { + matrix.set(i2, 8, mod2, true); + } else if (i2 < 8) { + matrix.set(i2 + 1, 8, mod2, true); + } else { + matrix.set(size - 15 + i2, 8, mod2, true); + } + if (i2 < 8) { + matrix.set(8, size - i2 - 1, mod2, true); + } else if (i2 < 9) { + matrix.set(8, 15 - i2 - 1 + 1, mod2, true); + } else { + matrix.set(8, 15 - i2 - 1, mod2, true); + } + } + matrix.set(size - 8, 8, 1, true); + } + function setupData(matrix, data) { + const size = matrix.size; + let inc = -1; + let row = size - 1; + let bitIndex = 7; + let byteIndex = 0; + for (let col = size - 1; col > 0; col -= 2) { + if (col === 6) + col--; + while (true) { + for (let c4 = 0; c4 < 2; c4++) { + if (!matrix.isReserved(row, col - c4)) { + let dark = false; + if (byteIndex < data.length) { + dark = (data[byteIndex] >>> bitIndex & 1) === 1; + } + matrix.set(row, col - c4, dark); + bitIndex--; + if (bitIndex === -1) { + byteIndex++; + bitIndex = 7; + } + } + } + row += inc; + if (row < 0 || size <= row) { + row -= inc; + inc = -inc; + break; + } + } + } + } + function createData(version2, errorCorrectionLevel, segments) { + const buffer = new BitBuffer(); + segments.forEach(function(data) { + buffer.put(data.mode.bit, 4); + buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version2)); + data.write(buffer); + }); + const totalCodewords = Utils.getSymbolTotalCodewords(version2); + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; + if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) { + buffer.put(0, 4); + } + while (buffer.getLengthInBits() % 8 !== 0) { + buffer.putBit(0); + } + const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8; + for (let i2 = 0; i2 < remainingByte; i2++) { + buffer.put(i2 % 2 ? 17 : 236, 8); + } + return createCodewords(buffer, version2, errorCorrectionLevel); + } + function createCodewords(bitBuffer, version2, errorCorrectionLevel) { + const totalCodewords = Utils.getSymbolTotalCodewords(version2); + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); + const dataTotalCodewords = totalCodewords - ecTotalCodewords; + const ecTotalBlocks = ECCode.getBlocksCount(version2, errorCorrectionLevel); + const blocksInGroup2 = totalCodewords % ecTotalBlocks; + const blocksInGroup1 = ecTotalBlocks - blocksInGroup2; + const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks); + const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks); + const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1; + const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1; + const rs = new ReedSolomonEncoder(ecCount); + let offset = 0; + const dcData = new Array(ecTotalBlocks); + const ecData = new Array(ecTotalBlocks); + let maxDataSize = 0; + const buffer = new Uint8Array(bitBuffer.buffer); + for (let b4 = 0; b4 < ecTotalBlocks; b4++) { + const dataSize = b4 < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2; + dcData[b4] = buffer.slice(offset, offset + dataSize); + ecData[b4] = rs.encode(dcData[b4]); + offset += dataSize; + maxDataSize = Math.max(maxDataSize, dataSize); + } + const data = new Uint8Array(totalCodewords); + let index = 0; + let i2, r; + for (i2 = 0; i2 < maxDataSize; i2++) { + for (r = 0; r < ecTotalBlocks; r++) { + if (i2 < dcData[r].length) { + data[index++] = dcData[r][i2]; + } + } + } + for (i2 = 0; i2 < ecCount; i2++) { + for (r = 0; r < ecTotalBlocks; r++) { + data[index++] = ecData[r][i2]; + } + } + return data; + } + function createSymbol(data, version2, errorCorrectionLevel, maskPattern) { + let segments; + if (Array.isArray(data)) { + segments = Segments.fromArray(data); + } else if (typeof data === "string") { + let estimatedVersion = version2; + if (!estimatedVersion) { + const rawSegments = Segments.rawSplit(data); + estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel); + } + segments = Segments.fromString(data, estimatedVersion || 40); + } else { + throw new Error("Invalid data"); + } + const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel); + if (!bestVersion) { + throw new Error("The amount of data is too big to be stored in a QR Code"); + } + if (!version2) { + version2 = bestVersion; + } else if (version2 < bestVersion) { + throw new Error( + "\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: " + bestVersion + ".\n" + ); + } + const dataBits = createData(version2, errorCorrectionLevel, segments); + const moduleCount = Utils.getSymbolSize(version2); + const modules = new BitMatrix(moduleCount); + setupFinderPattern(modules, version2); + setupTimingPattern(modules); + setupAlignmentPattern(modules, version2); + setupFormatInfo(modules, errorCorrectionLevel, 0); + if (version2 >= 7) { + setupVersionInfo(modules, version2); + } + setupData(modules, dataBits); + if (isNaN(maskPattern)) { + maskPattern = MaskPattern.getBestMask( + modules, + setupFormatInfo.bind(null, modules, errorCorrectionLevel) + ); + } + MaskPattern.applyMask(maskPattern, modules); + setupFormatInfo(modules, errorCorrectionLevel, maskPattern); + return { + modules, + version: version2, + errorCorrectionLevel, + maskPattern, + segments + }; + } + exports2.create = function create2(data, options) { + if (typeof data === "undefined" || data === "") { + throw new Error("No input text"); + } + let errorCorrectionLevel = ECLevel.M; + let version2; + let mask; + if (typeof options !== "undefined") { + errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M); + version2 = Version.from(options.version); + mask = MaskPattern.from(options.maskPattern); + if (options.toSJISFunc) { + Utils.setToSJISFunction(options.toSJISFunc); + } + } + return createSymbol(data, version2, errorCorrectionLevel, mask); + }; + } +}); + +// node_modules/qrcode/lib/renderer/utils.js +var require_utils7 = __commonJS({ + "node_modules/qrcode/lib/renderer/utils.js"(exports2) { + init_shim(); + function hex2rgba(hex) { + if (typeof hex === "number") { + hex = hex.toString(); + } + if (typeof hex !== "string") { + throw new Error("Color should be defined as hex string"); + } + let hexCode = hex.slice().replace("#", "").split(""); + if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { + throw new Error("Invalid hex color: " + hex); + } + if (hexCode.length === 3 || hexCode.length === 4) { + hexCode = Array.prototype.concat.apply([], hexCode.map(function(c4) { + return [c4, c4]; + })); + } + if (hexCode.length === 6) + hexCode.push("F", "F"); + const hexValue = parseInt(hexCode.join(""), 16); + return { + r: hexValue >> 24 & 255, + g: hexValue >> 16 & 255, + b: hexValue >> 8 & 255, + a: hexValue & 255, + hex: "#" + hexCode.slice(0, 6).join("") + }; + } + exports2.getOptions = function getOptions(options) { + if (!options) + options = {}; + if (!options.color) + options.color = {}; + const margin = typeof options.margin === "undefined" || options.margin === null || options.margin < 0 ? 4 : options.margin; + const width = options.width && options.width >= 21 ? options.width : void 0; + const scale = options.scale || 4; + return { + width, + scale: width ? 4 : scale, + margin, + color: { + dark: hex2rgba(options.color.dark || "#000000ff"), + light: hex2rgba(options.color.light || "#ffffffff") + }, + type: options.type, + rendererOpts: options.rendererOpts || {} + }; + }; + exports2.getScale = function getScale(qrSize, opts) { + return opts.width && opts.width >= qrSize + opts.margin * 2 ? opts.width / (qrSize + opts.margin * 2) : opts.scale; + }; + exports2.getImageWidth = function getImageWidth(qrSize, opts) { + const scale = exports2.getScale(qrSize, opts); + return Math.floor((qrSize + opts.margin * 2) * scale); + }; + exports2.qrToImageData = function qrToImageData(imgData, qr, opts) { + const size = qr.modules.size; + const data = qr.modules.data; + const scale = exports2.getScale(size, opts); + const symbolSize = Math.floor((size + opts.margin * 2) * scale); + const scaledMargin = opts.margin * scale; + const palette = [opts.color.light, opts.color.dark]; + for (let i2 = 0; i2 < symbolSize; i2++) { + for (let j2 = 0; j2 < symbolSize; j2++) { + let posDst = (i2 * symbolSize + j2) * 4; + let pxColor = opts.color.light; + if (i2 >= scaledMargin && j2 >= scaledMargin && i2 < symbolSize - scaledMargin && j2 < symbolSize - scaledMargin) { + const iSrc = Math.floor((i2 - scaledMargin) / scale); + const jSrc = Math.floor((j2 - scaledMargin) / scale); + pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]; + } + imgData[posDst++] = pxColor.r; + imgData[posDst++] = pxColor.g; + imgData[posDst++] = pxColor.b; + imgData[posDst] = pxColor.a; + } + } + }; + } +}); + +// node_modules/qrcode/lib/renderer/canvas.js +var require_canvas = __commonJS({ + "node_modules/qrcode/lib/renderer/canvas.js"(exports2) { + init_shim(); + var Utils = require_utils7(); + function clearCanvas(ctx, canvas, size) { + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (!canvas.style) + canvas.style = {}; + canvas.height = size; + canvas.width = size; + canvas.style.height = size + "px"; + canvas.style.width = size + "px"; + } + function getCanvasElement() { + try { + return document.createElement("canvas"); + } catch (e2) { + throw new Error("You need to specify a canvas element"); + } + } + exports2.render = function render(qrData, canvas, options) { + let opts = options; + let canvasEl = canvas; + if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { + opts = canvas; + canvas = void 0; + } + if (!canvas) { + canvasEl = getCanvasElement(); + } + opts = Utils.getOptions(opts); + const size = Utils.getImageWidth(qrData.modules.size, opts); + const ctx = canvasEl.getContext("2d"); + const image = ctx.createImageData(size, size); + Utils.qrToImageData(image.data, qrData, opts); + clearCanvas(ctx, canvasEl, size); + ctx.putImageData(image, 0, 0); + return canvasEl; + }; + exports2.renderToDataURL = function renderToDataURL(qrData, canvas, options) { + let opts = options; + if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { + opts = canvas; + canvas = void 0; + } + if (!opts) + opts = {}; + const canvasEl = exports2.render(qrData, canvas, opts); + const type = opts.type || "image/png"; + const rendererOpts = opts.rendererOpts || {}; + return canvasEl.toDataURL(type, rendererOpts.quality); + }; + } +}); + +// node_modules/qrcode/lib/renderer/svg-tag.js +var require_svg_tag = __commonJS({ + "node_modules/qrcode/lib/renderer/svg-tag.js"(exports2) { + init_shim(); + var Utils = require_utils7(); + function getColorAttrib(color, attrib) { + const alpha = color.a / 255; + const str = attrib + '="' + color.hex + '"'; + return alpha < 1 ? str + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str; + } + function svgCmd(cmd, x3, y4) { + let str = cmd + x3; + if (typeof y4 !== "undefined") + str += " " + y4; + return str; + } + function qrToPath(data, size, margin) { + let path = ""; + let moveBy = 0; + let newRow = false; + let lineLength = 0; + for (let i2 = 0; i2 < data.length; i2++) { + const col = Math.floor(i2 % size); + const row = Math.floor(i2 / size); + if (!col && !newRow) + newRow = true; + if (data[i2]) { + lineLength++; + if (!(i2 > 0 && col > 0 && data[i2 - 1])) { + path += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0); + moveBy = 0; + newRow = false; + } + if (!(col + 1 < size && data[i2 + 1])) { + path += svgCmd("h", lineLength); + lineLength = 0; + } + } else { + moveBy++; + } + } + return path; + } + exports2.render = function render(qrData, options, cb) { + const opts = Utils.getOptions(options); + const size = qrData.modules.size; + const data = qrData.modules.data; + const qrcodesize = size + opts.margin * 2; + const bg = !opts.color.light.a ? "" : "'; + const path = "'; + const viewBox = 'viewBox="0 0 ' + qrcodesize + " " + qrcodesize + '"'; + const width = !opts.width ? "" : 'width="' + opts.width + '" height="' + opts.width + '" '; + const svgTag = '' + bg + path + "\n"; + if (typeof cb === "function") { + cb(null, svgTag); + } + return svgTag; + }; + } +}); + +// node_modules/qrcode/lib/browser.js +var require_browser7 = __commonJS({ + "node_modules/qrcode/lib/browser.js"(exports2) { + init_shim(); + var canPromise = require_can_promise(); + var QRCode2 = require_qrcode(); + var CanvasRenderer = require_canvas(); + var SvgRenderer = require_svg_tag(); + function renderCanvas(renderFunc, canvas, text, opts, cb) { + const args = [].slice.call(arguments, 1); + const argsNum = args.length; + const isLastArgCb = typeof args[argsNum - 1] === "function"; + if (!isLastArgCb && !canPromise()) { + throw new Error("Callback required as last argument"); + } + if (isLastArgCb) { + if (argsNum < 2) { + throw new Error("Too few arguments provided"); + } + if (argsNum === 2) { + cb = text; + text = canvas; + canvas = opts = void 0; + } else if (argsNum === 3) { + if (canvas.getContext && typeof cb === "undefined") { + cb = opts; + opts = void 0; + } else { + cb = opts; + opts = text; + text = canvas; + canvas = void 0; + } + } + } else { + if (argsNum < 1) { + throw new Error("Too few arguments provided"); + } + if (argsNum === 1) { + text = canvas; + canvas = opts = void 0; + } else if (argsNum === 2 && !canvas.getContext) { + opts = text; + text = canvas; + canvas = void 0; + } + return new Promise(function(resolve, reject) { + try { + const data = QRCode2.create(text, opts); + resolve(renderFunc(data, canvas, opts)); + } catch (e2) { + reject(e2); + } + }); + } + try { + const data = QRCode2.create(text, opts); + cb(null, renderFunc(data, canvas, opts)); + } catch (e2) { + cb(e2); + } + } + exports2.create = QRCode2.create; + exports2.toCanvas = renderCanvas.bind(null, CanvasRenderer.render); + exports2.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL); + exports2.toString = renderCanvas.bind(null, function(data, _4, opts) { + return SvgRenderer.render(data, opts); + }); + } +}); + +// node_modules/@multiversx/sdk-web-wallet-provider/out/index.js +var require_out2 = __commonJS({ + "node_modules/@multiversx/sdk-web-wallet-provider/out/index.js"(exports2) { + "use strict"; + init_shim(); + var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + Object.defineProperty(o2, k22, { enumerable: true, get: function() { + return m3[k4]; + } }); + } : function(o2, m3, k4, k22) { + if (k22 === void 0) + k22 = k4; + o2[k22] = m3[k4]; + }); + var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { + for (var p3 in m3) + if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) + __createBinding2(exports3, m3, p3); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar2(require_walletProvider(), exports2); + __exportStar2(require_constants7(), exports2); + } +}); + +// src/elven.ts +init_shim(); +var import_tokens = __toESM(require_tokens(), 1); +var import_tokenOperations = __toESM(require_tokenOperations(), 1); +var import_transactionsFactories = __toESM(require_transactionsFactories(), 1); +var import_transactionsOutcomeParsers = __toESM(require_transactionsOutcomeParsers(), 1); +var import_address4 = __toESM(require_address(), 1); +var import_account4 = __toESM(require_account(), 1); +var import_transaction3 = __toESM(require_transaction(), 1); +var import_transactionComputer = __toESM(require_transactionComputer(), 1); +var import_message = __toESM(require_message(), 1); +var import_transactionWatcher2 = __toESM(require_transactionWatcher(), 1); +var import_signableMessage2 = __toESM(require_signableMessage(), 1); +var import_bytes7 = __toESM(require_bytes(), 1); +var import_numerical = __toESM(require_numerical(), 1); +var import_boolean = __toESM(require_boolean(), 1); +var import_address5 = __toESM(require_address2(), 1); +var import_interface = __toESM(require_interface(), 1); +var import_contractQueryResponse2 = __toESM(require_contractQueryResponse(), 1); + +// src/main.ts +init_shim(); + +// src/auth/init-extension-provider.ts +init_shim(); +var import_extensionProvider = __toESM(require_extensionProvider(), 1); + +// src/utils/ls-helpers.ts +init_shim(); + +// src/utils/constants.ts +init_shim(); +var LOCAL_STORAGE_KEY = "elvenjs_state"; +var defaultApiEndpoint = "https://devnet-api.multiversx.com"; +var DAPP_INIT_ROUTE = "/dapp/init"; +var defaultChainTypeConfig = "devnet"; +var walletConnectDeepLink = "https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/"; +var defaultWalletConnectV2RelayAddresses = [ + "wss://relay.walletconnect.com" +]; +var networkConfig = { + devnet: { + id: "devnet", + shortId: "D", + name: "Devnet", + egldLabel: "xEGLD", + egldDenomination: "18", + decimals: "4", + gasPerDataByte: "1500", + walletAddress: "https://devnet-wallet.multiversx.com", + xAliasAddress: "https://devnet.xalias.com", + apiAddress: "https://devnet-api.multiversx.com", + explorerAddress: "https://devnet-explorer.multiversx.com", + apiTimeout: 1e4 + }, + testnet: { + id: "testnet", + shortId: "T", + name: "Testnet", + egldLabel: "xEGLD", + egldDenomination: "18", + decimals: "4", + gasPerDataByte: "1500", + walletAddress: "https://testnet-wallet.multiversx.com", + xAliasAddress: "https://testnet.xalias.com", + apiAddress: "https://testnet-api.multiversx.com", + explorerAddress: "https://testnet-explorer.multiversx.com", + apiTimeout: 1e4 + }, + mainnet: { + id: "mainnet", + shortId: "1", + name: "Mainnet", + egldLabel: "EGLD", + egldDenomination: "18", + decimals: "4", + gasPerDataByte: "1500", + walletAddress: "https://wallet.multiversx.com", + xAliasAddress: "https://xalias.com", + apiAddress: "https://api.multiversx.com", + explorerAddress: "https://explorer.multiversx.com", + apiTimeout: 1e4 + } +}; + +// src/utils/ls-helpers.ts +var ls = { + get(key) { + const state = localStorage.getItem(LOCAL_STORAGE_KEY); + if (!state) + return {}; + const parsedState = JSON.parse(state); + if (key) { + return parsedState[key]; + } + return parsedState; + }, + set(key, value) { + const currentState = this.get(); + currentState[key] = value; + localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(currentState)); + }, + clear() { + localStorage.removeItem(LOCAL_STORAGE_KEY); + } +}; + +// src/auth/init-extension-provider.ts +var initExtensionProvider = async () => { + const dappProvider = import_extensionProvider.ExtensionProvider.getInstance(); + try { + const isSuccessfullyInitialized = await dappProvider.init(); + const currentState = ls.get(); + if (currentState?.address) { + dappProvider.setAddress(currentState.address); + } + if (!isSuccessfullyInitialized) { + console.warn( + "Something went wrong when trying to initialize the ExtensionProvider.." + ); + return; + } + return dappProvider; + } catch (e2) { + console.warn("Can't initialize the Dapp Provider!"); + } +}; + +// src/main.ts +var import_extensionProvider2 = __toESM(require_extensionProvider(), 1); +var import_walletConnectV2Provider4 = __toESM(require_walletConnectV2Provider(), 1); +var import_walletProvider4 = __toESM(require_walletProvider(), 1); +var import_native_auth2 = __toESM(require_native_auth_client(), 1); +var import_signableMessage = __toESM(require_signableMessage(), 1); + +// src/auth/init-mobile-provider.ts +init_shim(); +var import_walletConnectV2Provider = __toESM(require_walletConnectV2Provider(), 1); + +// src/auth/logout.ts +init_shim(); + +// src/events-store.ts +init_shim(); +var EventsStore = class { + static set(name2, fn) { + if (!name2) + return; + const eventsObj = { ...this.events, [name2]: fn }; + this.events = eventsObj; + } + static get(name2) { + if (!name2 || !this.events) + return; + return this.events[name2]; + } + static run(name2, ...args) { + if (!name2 || !this.events) + return; + this.events[name2]?.(...args); + } + static clear() { + this.events = void 0; + } +}; + +// src/types.ts +init_shim(); +var EventStoreEvents = /* @__PURE__ */ ((EventStoreEvents2) => { + EventStoreEvents2["onLoginStart"] = "onLoginStart"; + EventStoreEvents2["onLoginSuccess"] = "onLoginSuccess"; + EventStoreEvents2["onLoginFailure"] = "onLoginFailure"; + EventStoreEvents2["onLogoutStart"] = "onLogoutStart"; + EventStoreEvents2["onLogoutSuccess"] = "onLogoutSuccess"; + EventStoreEvents2["onLogoutFailure"] = "onLogoutFailure"; + EventStoreEvents2["onQrPending"] = "onQrPending"; + EventStoreEvents2["onQrLoaded"] = "onQrLoaded"; + EventStoreEvents2["onTxStart"] = "onTxStart"; + EventStoreEvents2["onTxSent"] = "onTxSent"; + EventStoreEvents2["onTxFinalized"] = "onTxFinalized"; + EventStoreEvents2["onTxFailure"] = "onTxFailure"; + EventStoreEvents2["onSignMsgStart"] = "onSignMsgStart"; + EventStoreEvents2["onSignMsgFinalized"] = "onSignMsgFinalized"; + EventStoreEvents2["onSignMsgFailure"] = "onSignMsgFailure"; + EventStoreEvents2["onQueryStart"] = "onQueryStart"; + EventStoreEvents2["onQueryFinalized"] = "onQueryFinalized"; + EventStoreEvents2["onQueryFailure"] = "onQueryFailure"; + return EventStoreEvents2; +})(EventStoreEvents || {}); +var LoginMethodsEnum = /* @__PURE__ */ ((LoginMethodsEnum2) => { + LoginMethodsEnum2["ledger"] = "ledger"; + LoginMethodsEnum2["mobile"] = "mobile"; + LoginMethodsEnum2["webWallet"] = "web-wallet"; + LoginMethodsEnum2["browserExtension"] = "browser-extension"; + LoginMethodsEnum2["xAlias"] = "x-alias"; + LoginMethodsEnum2["xPortalHub"] = "x-portal-hub"; + return LoginMethodsEnum2; +})(LoginMethodsEnum || {}); +var DappCoreWCV2CustomMethodsEnum = /* @__PURE__ */ ((DappCoreWCV2CustomMethodsEnum2) => { + DappCoreWCV2CustomMethodsEnum2["mvx_cancelAction"] = "mvx_cancelAction"; + DappCoreWCV2CustomMethodsEnum2["mvx_signNativeAuthToken"] = "mvx_signNativeAuthToken"; + return DappCoreWCV2CustomMethodsEnum2; +})(DappCoreWCV2CustomMethodsEnum || {}); +var WebWalletUrlParamsEnum = /* @__PURE__ */ ((WebWalletUrlParamsEnum2) => { + WebWalletUrlParamsEnum2["hasWebWalletGuardianSign"] = "hasWebWalletGuardianSign"; + return WebWalletUrlParamsEnum2; +})(WebWalletUrlParamsEnum || {}); + +// src/utils/error-parse.ts +init_shim(); +var errorParse = (err) => { + if (typeof err === "string") { + return err.toUpperCase(); + } else if (err instanceof Error) { + return err.message; + } + return JSON.stringify(err); +}; + +// src/auth/logout.ts +var logout = async (elven) => { + if (!elven.dappProvider) { + throw new Error("Logout failed: There is no active session!"); + } + EventsStore.run("onLogoutStart" /* onLogoutStart */); + try { + const isLoggedOut = await elven.dappProvider.logout(); + if (isLoggedOut) { + ls.clear(); + EventsStore.run("onLogoutSuccess" /* onLogoutSuccess */); + } + return isLoggedOut; + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to logout the user: ${err}`); + EventsStore.run("onLogoutFailure" /* onLogoutFailure */, err); + } +}; + +// src/utils/get-random-address-from-network.ts +init_shim(); +function getRandomAddressFromNetwork(addresses) { + return addresses[Math.floor(Math.random() * addresses.length)]; +} + +// src/auth/init-mobile-provider.ts +var initMobileProvider = async (elven) => { + if (!elven.initOptions.walletConnectV2ProjectId || !elven.initOptions.chainType) { + return void 0; + } + const providerHandlers = { + onClientLogin: () => { + }, + onClientLogout: () => logout(elven), + onClientEvent: (event) => { + console.log("wc2 session event: ", event); + } + }; + const relayAddress = getRandomAddressFromNetwork( + elven.initOptions.walletConnectV2RelayAddresses + ); + const dappProviderInstance = new import_walletConnectV2Provider.WalletConnectV2Provider( + providerHandlers, + networkConfig[elven.initOptions.chainType].shortId, + relayAddress, + elven.initOptions.walletConnectV2ProjectId + ); + try { + await dappProviderInstance.init(); + return dappProviderInstance; + } catch { + console.warn("Can't initialize the Dapp Provider!"); + } +}; + +// src/network-provider.ts +init_shim(); +var import_address = __toESM(require_address(), 1); +var import_transactionStatus = __toESM(require_transactionStatus(), 1); +var import_transactionReceipt = __toESM(require_transactionReceipt(), 1); +var import_transactionLogs = __toESM(require_transactionLogs(), 1); +var import_contractResults = __toESM(require_contractResults(), 1); +var import_contractQueryResponse = __toESM(require_contractQueryResponse(), 1); +var import_contractQueryRequest = __toESM(require_contractQueryRequest(), 1); +var import_query = __toESM(require_query(), 1); +var ApiNetworkProvider = class { + constructor({ apiUrl, chainType, apiTimeout }) { + this.chainType = chainType || defaultChainTypeConfig; + this.apiUrl = apiUrl || networkConfig[this.chainType]?.apiAddress; + this.apiTimeout = apiTimeout || networkConfig[this.chainType]?.apiTimeout; + } + async apiGet(endpoint, options) { + if (typeof fetch !== "undefined") { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); + const defaultOptions = { + method: "GET", + headers: { + "Content-Type": "application/json", + Accept: "application/json" + }, + signal: controller.signal + }; + try { + const response = await fetch( + this.apiUrl + "/" + endpoint, + Object.assign(defaultOptions, options || {}) + ); + const result = await response.json(); + if (!response.ok) { + const error = result?.error || response.status; + clearTimeout(timeoutId); + return Promise.reject(error); + } + clearTimeout(timeoutId); + return result; + } catch (e2) { + this.handleApiError(e2, endpoint); + } + } + } + async apiPost(endpoint, payload, options) { + if (typeof fetch !== "undefined") { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); + const defaultOptions = { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json" + }, + body: JSON.stringify(payload || {}), + signal: controller.signal + }; + try { + const response = await fetch( + this.apiUrl + "/" + endpoint, + Object.assign(defaultOptions, options || {}) + ); + const result = await response.json(); + if (!response.ok) { + const error = result?.error || response.status; + clearTimeout(timeoutId); + return Promise.reject(error); + } + clearTimeout(timeoutId); + return result; + } catch (e2) { + this.handleApiError(e2, endpoint); + } + } + } + handleApiError(error, resourceUrl) { + if (!error.response) { + throw new Error( + `Request error on url [${resourceUrl}]: [${error.toString()}]` + ); + } + const errorData = error.response.data; + const originalErrorMessage = errorData.error || errorData.message || JSON.stringify(errorData); + throw new Error(originalErrorMessage); + } + async sendTransaction(tx) { + const response = await this.apiPost("transactions", tx.toSendable()); + return response.txHash; + } + async getAccount(address) { + const responsePayload = await this.apiGet(`accounts/${address.bech32()}`); + const account = { + address: new import_address.Address(responsePayload?.address || ""), + nonce: Number(responsePayload?.nonce || 0), + balance: BigInt(responsePayload?.balance || 0), + code: responsePayload?.code || "", + userName: responsePayload?.username || "" + }; + return account; + } + async getGuardianData(address) { + const response = await this.apiGet( + `address/${address.bech32()}/guardian-data` + ); + const accountGuardian = { + guarded: response?.data?.guardianData?.guarded || false, + activeGuardian: response?.data?.guardianData?.activeGuardian, + pendingGuardian: response?.data?.guardianData?.pendingGuardian + }; + return accountGuardian; + } + async getTransaction(txHash) { + const payload = await this.apiGet(`transactions/${txHash}`); + const status = new import_transactionStatus.TransactionStatus(payload.status); + const transaction = { + hash: txHash, + type: payload.type || "", + nonce: payload.nonce || 0, + round: payload.round, + epoch: payload.epoch || 0, + value: (payload.value || 0).toString(), + sender: new import_address.Address(payload.sender), + receiver: new import_address.Address(payload.receiver), + gasPrice: payload.gasPrice || 0, + gasLimit: payload.gasLimit || 0, + data: import_buffer.Buffer.from(payload.data || "", "base64"), + status, + timestamp: payload.timestamp || 0, + blockNonce: payload.blockNonce || 0, + hyperblockNonce: payload.hyperblockNonce || 0, + hyperblockHash: payload.hyperblockHash || "", + receipt: import_transactionReceipt.TransactionReceipt.fromHttpResponse(payload.receipt || {}), + logs: import_transactionLogs.TransactionLogs.fromHttpResponse(payload.logs || {}), + contractResults: import_contractResults.ContractResults.fromApiHttpResponse( + payload.results || [] + ), + isCompleted: !status.isPending() + }; + return transaction; + } + async queryContract({ + address, + func, + args, + value, + caller + }) { + try { + const query = new import_query.Query({ + address, + func, + args, + value, + caller + }); + const request = new import_contractQueryRequest.ContractQueryRequest(query).toHttpRequest(); + const response = await this.apiPost("query", request); + return import_contractQueryResponse.ContractQueryResponse.fromHttpResponse(response); + } catch (e2) { + this.handleApiError(e2, "query"); + } + } +}; + +// src/auth/login-with-extension.ts +init_shim(); + +// src/auth/expires-at.ts +init_shim(); +var getNewLoginExpiresTimestamp = () => { + return (/* @__PURE__ */ new Date()).setHours((/* @__PURE__ */ new Date()).getHours() + 24); +}; +var isLoginExpired = (expirationTimestamp) => { + return Date.now() > expirationTimestamp; +}; + +// src/auth/account-sync.ts +init_shim(); +var import_address2 = __toESM(require_address(), 1); +var import_account = __toESM(require_account(), 1); +var accountSync = async (elven) => { + const address = ls.get("address"); + const loginExpires = ls.get("expires"); + const loginExpired = loginExpires && isLoginExpired(loginExpires); + if (!loginExpired && address && elven.networkProvider) { + const userAddressInstance = new import_address2.Address(address); + const userAccountInstance = new import_account.Account(userAddressInstance); + try { + const userAccountOnNetwork = await elven.networkProvider.getAccount(userAddressInstance); + const userGuardianOnNetwork = await elven.networkProvider.getGuardianData(userAddressInstance); + ls.set("address", address); + ls.set( + "activeGuardian", + userGuardianOnNetwork.guarded && userGuardianOnNetwork.activeGuardian?.address ? userGuardianOnNetwork.activeGuardian.address : "" + ); + ls.set("nonce", userAccountOnNetwork.nonce.valueOf()); + ls.set("balance", userAccountOnNetwork.balance.toString()); + userAccountInstance.update(userAccountOnNetwork); + } catch (e2) { + const err = errorParse(e2); + console.warn( + `Something went wrong trying to synchronize the user account: ${err}` + ); + } + } +}; + +// src/auth/login-with-extension.ts +var loginWithExtension = async (elven, loginToken, nativeAuthClient, callbackRoute = "/") => { + const dappProvider = await initExtensionProvider(); + const callbackUrl = encodeURIComponent( + `${window.location.origin}${callbackRoute}` + ); + const providerLoginData = { + callbackUrl, + token: loginToken + }; + try { + if (dappProvider) { + const address = await dappProvider.login(providerLoginData); + if (!address) { + throw new Error("There were problems while logging in!"); + } + } + } catch (e2) { + const err = errorParse(e2); + throw new Error(err); + } + if (!dappProvider) { + throw new Error("There were problems with auth provider initialization!"); + } + const { signature } = dappProvider.account; + ls.set("loginToken", loginToken); + if (signature) { + ls.set("signature", signature); + } + if (elven.networkProvider && signature) { + try { + const address = await dappProvider.getAddress(); + if (!address) { + throw new Error("Canceled!"); + } + ls.set("address", address); + ls.set("loginMethod", "browser-extension" /* browserExtension */); + ls.set("expires", getNewLoginExpiresTimestamp()); + await accountSync(elven); + const accessToken = nativeAuthClient.getToken( + address, + loginToken, + signature + ); + ls.set("accessToken", accessToken); + EventsStore.run("onLoginSuccess" /* onLoginSuccess */); + return dappProvider; + } catch (e2) { + throw new Error( + `Something went wrong trying to synchronize the user account: ${e2?.message}` + ); + } + } +}; + +// src/auth/login-with-mobile.ts +init_shim(); + +// src/auth/qr-code-and-pairings-builder.ts +init_shim(); +var import_qrcode = __toESM(require_browser7(), 1); +var import_walletConnectV2Provider2 = __toESM(require_walletConnectV2Provider(), 1); +var htmlStringToElement = (htmlString) => { + const template = document.createElement("template"); + template.innerHTML = htmlString.trim(); + return template.content.firstChild?.cloneNode(true); +}; +var buildDeepLink = (walletConnectUri) => { + const hrefVal = `${walletConnectDeepLink}?wallet-connect=${encodeURIComponent( + walletConnectUri + )}`; + const aElem = document.createElement("a"); + aElem.setAttribute("href", hrefVal); + aElem.setAttribute("rel", "noopener noreferrer nofollow"); + aElem.setAttribute("target", "_blank"); + aElem.textContent = "xPortal login"; + aElem.classList.add("elven-qr-code-deep-link"); + return aElem; +}; +var buildPairingsContainer = () => { + const container = document.createElement("div"); + container.classList.add("elven-wc-pairings"); + return container; +}; +var buildPairingsHeader = () => { + const headerElem = document.createElement("div"); + headerElem.textContent = "Existing WalletConnect pairings:"; + headerElem.classList.add("elven-wc-pairings-header"); + return headerElem; +}; +var pairingRemoveControllers = {}; +var buildPairingsRemoveButton = (pairing, removeExistingPairing) => { + const btn = document.createElement("button"); + btn.classList.add("elven-wc-pairings-remove-btn"); + btn.textContent = "\u2716"; + pairingRemoveControllers[pairing.topic] = new AbortController(); + btn.addEventListener( + "click", + (e2) => { + e2.stopImmediatePropagation(); + removeExistingPairing(pairing.topic); + }, + { + signal: pairingRemoveControllers[pairing.topic].signal + } + ); + return btn; +}; +var pairingLoginControllers = {}; +var buildPairingItem = (pairing, removeExistingPairing, loginThroughExistingPairing) => { + const itemElem = document.createElement("div"); + const itemTextWrapper = document.createElement("div"); + itemElem.classList.add("elven-wc-pairing-item"); + itemElem.setAttribute("id", pairing.topic); + itemTextWrapper.classList.add("elven-wc-pairing-item-description"); + itemTextWrapper.textContent = `${pairing.peerMetadata?.description} (${pairing.peerMetadata?.url})`; + itemElem.appendChild(itemTextWrapper); + const button = buildPairingsRemoveButton(pairing, removeExistingPairing); + itemElem.appendChild(button); + pairingLoginControllers[pairing.topic] = new AbortController(); + itemElem.addEventListener( + "click", + () => loginThroughExistingPairing(pairing.topic), + { signal: pairingLoginControllers[pairing.topic].signal } + ); + return itemElem; +}; +var buildPairingItemConfirmMessage = () => { + const itemElem = document.createElement("div"); + itemElem.classList.add("elven-wc-pairing-item-confirm-msessage"); + itemElem.setAttribute("id", "elven-wc-pairing-item-confirm-msessage"); + itemElem.innerText = "Confirm on xPortal app!"; + return itemElem; +}; +var removePairingItem = (topic) => { + if (!topic) + return; + const pairingElement = document.getElementById(topic); + pairingElement?.remove(); +}; +var isMobile = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent +); +var generateQRCode = async (walletConnectUri) => { + if (!walletConnectUri) { + return; + } + const svg = await import_qrcode.default.toString(walletConnectUri, { + type: "svg" + }); + return svg; +}; +var qrCodeAndPairingsBuilder = async (qrCodeContainer, walletConnectUri, dappProvider, token) => { + if (!qrCodeContainer) + throw new Error( + "Please provide the QR Code and WalletConnect Pairings container id!" + ); + let containerElem = null; + if (typeof qrCodeContainer === "string") { + containerElem = document.getElementById(qrCodeContainer); + } else if (qrCodeContainer instanceof HTMLElement) { + containerElem = qrCodeContainer; + } + const qrCodeElementString = await generateQRCode(walletConnectUri); + let qrCodeSvg; + if (qrCodeElementString) { + qrCodeSvg = htmlStringToElement(qrCodeElementString); + } + if (containerElem && qrCodeSvg) { + containerElem.replaceChildren(); + containerElem.appendChild(qrCodeSvg); + if (isMobile()) { + containerElem.appendChild(buildDeepLink(walletConnectUri)); + } + } + if (containerElem && dappProvider instanceof import_walletConnectV2Provider2.WalletConnectV2Provider) { + const wcPairings = dappProvider.pairings; + const removeExistingPairing = async (topic) => { + try { + if (topic) { + await dappProvider.logout({ + topic + }); + removePairingItem(topic); + } + } catch (e2) { + const err = errorParse(e2); + console.warn( + `Something went wrong trying to remove the existing pairing: ${err}` + ); + } finally { + pairingLoginControllers[topic].abort(); + } + }; + const loginThroughExistingPairing = async (topic) => { + try { + const { approval } = await dappProvider.connect({ + topic, + methods: [ + "mvx_cancelAction" /* mvx_cancelAction */, + "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ + ] + }); + const pairingItemConfirmation = document.getElementById( + "elven-wc-pairing-item-confirm-msessage" + ); + if (!pairingItemConfirmation) { + const pairingItemElement = document.getElementById(topic); + pairingItemElement?.after(buildPairingItemConfirmMessage()); + } + await dappProvider.login({ + approval, + token + }); + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + } finally { + for (const abortController of Object.values(pairingLoginControllers)) { + abortController?.abort(); + } + for (const abortController of Object.values(pairingRemoveControllers)) { + abortController?.abort(); + } + } + }; + if (wcPairings && wcPairings.length > 0) { + const container = buildPairingsContainer(); + containerElem.appendChild(container); + const headerElem = buildPairingsHeader(); + container.appendChild(headerElem); + for (const pairing of wcPairings) { + const itemElem = buildPairingItem( + pairing, + removeExistingPairing, + loginThroughExistingPairing + ); + container.appendChild(itemElem); + } + } + } + return containerElem; +}; + +// src/auth/login-with-mobile.ts +var import_walletConnectV2Provider3 = __toESM(require_walletConnectV2Provider(), 1); +var loginWithMobile = async (elven, loginToken, nativeAuthClient, qrCodeContainer) => { + if (!qrCodeContainer) { + throw new Error( + "You haven't provided the QR code container DOM element id" + ); + } + const relayAddress = getRandomAddressFromNetwork( + elven.initOptions.walletConnectV2RelayAddresses + ); + if (!relayAddress || !elven.networkProvider) { + throw new Error( + "Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!" + ); + } + if (!elven.initOptions.walletConnectV2ProjectId) { + throw new Error( + "Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)" + ); + } + if (!elven.initOptions.chainType) { + throw new Error("Please provide the chain type in ElvenJS.init function!"); + } + let qrCodeElement; + const providerHandlers = { + onClientLogin: async () => { + if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { + const address = await elven.dappProvider.getAddress(); + const signature = await elven.dappProvider.getSignature(); + ls.set("address", address); + ls.set("loginMethod", "mobile" /* mobile */); + ls.set("expires", getNewLoginExpiresTimestamp()); + await accountSync(elven); + if (signature) { + ls.set("signature", signature); + } + ls.set("loginToken", loginToken); + const accessToken = nativeAuthClient.getToken( + address, + loginToken, + signature + ); + ls.set("accessToken", accessToken); + EventsStore.run("onLoginSuccess" /* onLoginSuccess */); + qrCodeElement?.replaceChildren(); + } + }, + onClientLogout: async () => { + if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { + await logout(elven); + } + }, + onClientEvent: (event) => { + console.log("wc2 session event: ", event); + } + }; + const dappProvider = new import_walletConnectV2Provider3.WalletConnectV2Provider( + providerHandlers, + networkConfig[elven.initOptions.chainType].shortId, + relayAddress, + elven.initOptions.walletConnectV2ProjectId + ); + try { + if (dappProvider) { + elven.dappProvider = dappProvider; + EventsStore.run("onQrPending" /* onQrPending */); + await dappProvider.init(); + const { uri: walletConnectUri, approval } = await dappProvider.connect({ + methods: [ + "mvx_cancelAction" /* mvx_cancelAction */, + "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ + ] + }); + const wCUri = loginToken ? `${walletConnectUri}&token=${loginToken}` : walletConnectUri; + if (qrCodeContainer && wCUri) { + qrCodeElement = await qrCodeAndPairingsBuilder( + qrCodeContainer, + wCUri, + dappProvider, + loginToken + ); + EventsStore.run("onQrLoaded" /* onQrLoaded */); + } + await dappProvider.login({ + approval, + token: loginToken + }); + return dappProvider; + } + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + EventsStore.run("onLoginFailure" /* onLoginFailure */, err); + } +}; + +// src/auth/login-with-web-wallet.ts +init_shim(); +var import_walletProvider = __toESM(require_walletProvider(), 1); +var loginWithWebWallet = async (urlAddress, loginToken, chainType, callbackRoute) => { + const dappProvider = new import_walletProvider.WalletProvider(`${urlAddress}${DAPP_INIT_ROUTE}`); + const callbackUrl = typeof window !== "undefined" ? encodeURIComponent(`${window.location.origin}${callbackRoute || "/"}`) : "/"; + const providerLoginData = { + callbackUrl, + token: loginToken + }; + try { + ls.set( + "loginMethod", + networkConfig[chainType].xAliasAddress === urlAddress ? "x-alias" /* xAlias */ : "web-wallet" /* webWallet */ + ); + await dappProvider.login(providerLoginData); + ls.set("expires", getNewLoginExpiresTimestamp()); + ls.set("loginToken", loginToken); + return dappProvider; + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + ls.set("loginMethod", ""); + EventsStore.run("onLoginFailure" /* onLoginFailure */, err); + } +}; + +// src/utils/get-param-from-url.ts +init_shim(); +var getParamFromUrl = (paramName) => { + if (typeof window !== "undefined") { + const url = new URL(window.location.href); + const params = new URLSearchParams(url.search); + return params.get(paramName); + } +}; + +// src/auth/init-web-wallet-provider.ts +init_shim(); +var import_walletProvider2 = __toESM(require_walletProvider(), 1); +var import_native_auth = __toESM(require_native_auth_client(), 1); +var initWebWalletProvider = async (webWalletAddress, apiUrl) => { + const signature = getParamFromUrl("signature"); + const urlAddress = getParamFromUrl("address"); + const lsAddress = ls.get("address"); + const loginToken = ls.get("loginToken"); + if (signature) { + ls.set("signature", signature); + } + if (urlAddress || lsAddress) { + if (urlAddress) { + ls.set("address", urlAddress); + window.history.replaceState(null, "", window.location.pathname); + } + const dappProvider = new import_walletProvider2.WalletProvider( + `${webWalletAddress}${DAPP_INIT_ROUTE}` + ); + if (signature && apiUrl && urlAddress) { + const nativeAuthClient = new import_native_auth.NativeAuthClient({ + apiUrl, + origin: window.location.origin + }); + const accessToken = nativeAuthClient.getToken( + urlAddress, + loginToken, + signature + ); + ls.set("accessToken", accessToken); + } + return dappProvider; + } +}; + +// src/interaction/post-send-tx.ts +init_shim(); +var import_account2 = __toESM(require_account(), 1); +var import_transactionWatcher = __toESM(require_transactionWatcher(), 1); +var postSendTx = async (transaction, networkProvider) => { + EventsStore.run("onTxSent" /* onTxSent */, transaction); + const transactionWatcher = new import_transactionWatcher.TransactionWatcher(networkProvider); + const transactionOnNetwork = await transactionWatcher.awaitCompleted(transaction); + const sender = transactionOnNetwork.sender; + const senderAccount = new import_account2.Account(sender); + const userAccountOnNetwork = await networkProvider.getAccount(sender); + senderAccount.update(userAccountOnNetwork); + ls.set("address", senderAccount.address.bech32()); + ls.set("balance", senderAccount.balance.toString()); + EventsStore.run("onTxFinalized" /* onTxFinalized */, transactionOnNetwork); +}; + +// src/interaction/web-wallet-tx-finalize.ts +init_shim(); +var import_out = __toESM(require_out2(), 1); +var import_transaction = __toESM(require_transaction(), 1); + +// src/interaction/pre-send-tx.ts +init_shim(); +var import_account3 = __toESM(require_account(), 1); +var preSendTx = (tx) => { + const sender = tx.getSender(); + const senderAccount = new import_account3.Account(sender); + const currentNonce = tx.nonce.valueOf(); + senderAccount.incrementNonce(); + ls.set("nonce", (currentNonce + 1n).toString()); +}; + +// src/interaction/web-wallet-tx-finalize.ts +var webWalletTxFinalize = async (dappProvider, networkProvider, urlAddress, nonce) => { + const walletProviderStatus = getParamFromUrl(import_out.WALLET_PROVIDER_CALLBACK_PARAM); + if (walletProviderStatus === import_out.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED && dappProvider && networkProvider) { + const guardian = ls.get("activeGuardian"); + const loginMethod = ls.get("loginMethod"); + const hasWebWalletGuardianSign = getParamFromUrl( + "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */ + ); + let transactionObj; + if ("getTransactionsFromWalletUrl" in dappProvider) { + const txs = dappProvider.getTransactionsFromWalletUrl(); + transactionObj = txs?.[0]; + if (!transactionObj) + return; + if (loginMethod === "web-wallet" /* webWallet */) { + transactionObj.data = import_buffer.Buffer.from(transactionObj.data).toString( + "base64" + ); + } + } else if (guardian && loginMethod !== "web-wallet" /* webWallet */ && loginMethod !== "x-alias" /* xAlias */ && hasWebWalletGuardianSign) { + const webWalletProvider = new import_out.WalletProvider( + `${urlAddress}${DAPP_INIT_ROUTE}` + ); + const txs = webWalletProvider.getTransactionsFromWalletUrl(); + transactionObj = txs?.[0]; + } + if (transactionObj) { + const transaction = import_transaction.Transaction.fromPlainObject(transactionObj); + transaction.nonce = BigInt(nonce); + preSendTx(transaction); + try { + EventsStore.run("onTxStart" /* onTxStart */, transaction); + await networkProvider.sendTransaction(transaction); + await postSendTx(transaction, networkProvider); + } catch (e2) { + const err = errorParse(e2); + const errMsg = `Getting transaction information failed! ${err}`; + EventsStore.run("onTxFailure" /* onTxFailure */, transaction, errMsg); + throw new Error(errMsg); + } finally { + window.history.replaceState(null, "", window.location.pathname); + } + } + window.history.replaceState(null, "", window.location.pathname); + } +}; + +// src/interaction/guardian-operations.ts +init_shim(); +var import_networkParams = __toESM(require_networkParams(), 1); +var import_address3 = __toESM(require_address(), 1); +var import_walletProvider3 = __toESM(require_walletProvider(), 1); +var guardianPreSignTxOperations = (tx) => { + const guardian = ls.get("activeGuardian"); + if (guardian) { + const options = { + guarded: true + }; + tx.setVersion(import_networkParams.TransactionVersion.withTxOptions()); + tx.setOptions(import_networkParams.TransactionOptions.withOptions(options)); + tx.setGuardian(import_address3.Address.fromBech32(guardian)); + } + return tx; +}; +var sendTxToGuardian = async (signedTx, walletAddress) => { + const webWalletProvider = new import_walletProvider3.WalletProvider( + `${walletAddress}${DAPP_INIT_ROUTE}` + ); + const currentUrl = window?.location.href; + const alteredCallbackUrl = new URL(currentUrl); + alteredCallbackUrl.searchParams.set( + "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */, + "true" + ); + await webWalletProvider.guardTransactions([signedTx], { + callbackUrl: encodeURIComponent(alteredCallbackUrl.toString()) + }); +}; +var checkNeedsGuardianSigning = (signedTx) => { + const guardian = ls.get("activeGuardian"); + const address = ls.get("address"); + if (!address || !guardian) { + return false; + } + if (signedTx.isGuardedTransaction()) { + return false; + } + return true; +}; + +// src/interaction/web-wallet-sign-message-finalize.ts +init_shim(); +var webWalletSignMessageFinalize = () => { + const isNotTransaction = !getParamFromUrl("walletProviderStatus"); + const isSigned = getParamFromUrl("status") === "signed"; + const message = getParamFromUrl("message"); + const signature = getParamFromUrl("signature"); + if (isNotTransaction && isSigned && message && signature) { + EventsStore.run("onSignMsgFinalized" /* onSignMsgFinalized */, message, signature); + window.history.replaceState(null, "", window.location.pathname); + } +}; + +// src/webview-provider/webview-provider.ts +init_shim(); +var import_transaction2 = __toESM(require_transaction(), 1); + +// src/webview-provider/types.ts +init_shim(); +var WebViewProviderResponseBaseEnums = /* @__PURE__ */ ((WebViewProviderResponseBaseEnums2) => { + WebViewProviderResponseBaseEnums2["reloginResponse"] = "RELOGIN_RESPONSE"; + return WebViewProviderResponseBaseEnums2; +})(WebViewProviderResponseBaseEnums || {}); +var CrossWindowProviderResponseEnums = /* @__PURE__ */ ((CrossWindowProviderResponseEnums2) => { + CrossWindowProviderResponseEnums2["handshakeResponse"] = "HANDSHAKE_RESPONSE"; + CrossWindowProviderResponseEnums2["loginResponse"] = "LOGIN_RESPONSE"; + CrossWindowProviderResponseEnums2["disconnectResponse"] = "DISCONNECT_RESPONSE"; + CrossWindowProviderResponseEnums2["cancelResponse"] = "CANCEL_RESPONSE"; + CrossWindowProviderResponseEnums2["signTransactionsResponse"] = "SIGN_TRANSACTIONS_RESPONSE"; + CrossWindowProviderResponseEnums2["signMessageResponse"] = "SIGN_MESSAGE_RESPONSE"; + CrossWindowProviderResponseEnums2["noneResponse"] = "NONE_RESPONSE"; + return CrossWindowProviderResponseEnums2; +})(CrossWindowProviderResponseEnums || {}); +var WebViewProviderResponseEnums = { + ...CrossWindowProviderResponseEnums, + ...WebViewProviderResponseBaseEnums +}; +var WebViewProviderRequestBaseEnums = /* @__PURE__ */ ((WebViewProviderRequestBaseEnums2) => { + WebViewProviderRequestBaseEnums2["signTransactionsWithGuardianResponse"] = "SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE"; + WebViewProviderRequestBaseEnums2["reloginRequest"] = "RELOGIN_REQUEST"; + return WebViewProviderRequestBaseEnums2; +})(WebViewProviderRequestBaseEnums || {}); +var CrossWindowProviderRequestEnums = /* @__PURE__ */ ((CrossWindowProviderRequestEnums2) => { + CrossWindowProviderRequestEnums2["signTransactionsRequest"] = "SIGN_TRANSACTIONS_REQUEST"; + CrossWindowProviderRequestEnums2["signMessageRequest"] = "SIGN_MESSAGE_REQUEST"; + CrossWindowProviderRequestEnums2["loginRequest"] = "LOGIN_REQUEST"; + CrossWindowProviderRequestEnums2["logoutRequest"] = "LOGOUT_REQUEST"; + CrossWindowProviderRequestEnums2["cancelAction"] = "CANCEL_ACTION_REQUEST"; + CrossWindowProviderRequestEnums2["finalizeHandshakeRequest"] = "FINALIZE_HANDSHAKE_REQUEST"; + return CrossWindowProviderRequestEnums2; +})(CrossWindowProviderRequestEnums || {}); +var WebViewProviderRequestEnums = { + ...CrossWindowProviderRequestEnums, + ...WebViewProviderRequestBaseEnums +}; + +// src/webview-provider/utils.ts +init_shim(); +var safeWindow = typeof window !== "undefined" ? window : {}; +var detectCurrentPlatform = () => { + if (safeWindow.ReactNativeWebView) { + return "reactNative" /* reactNative */; + } + if (safeWindow.webkit) { + return "ios" /* ios */; + } + return "web" /* web */; +}; +var getTargetOrigin = () => { + return typeof window != "undefined" && typeof window?.location != "undefined" ? window?.parent?.origin ?? "*" : "*"; +}; +var isString = (x3) => { + return Object.prototype.toString.call(x3) === "[object String]"; +}; + +// src/webview-provider/request-methods.ts +init_shim(); +var requestMethods = { + signTransactions: { + ["ios" /* ios */]: (transactions) => window.webkit.messageHandlers.signTransactions.postMessage( + transactions, + getTargetOrigin() + ), + ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signTransactionsRequest, + message + }) + ), + ["web" /* web */]: (message) => window?.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signTransactionsRequest, + message + }), + getTargetOrigin() + ) + }, + signMessage: { + ["ios" /* ios */]: (message) => window.webkit.messageHandlers.signMessage.postMessage(message), + ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signMessageRequest, + message + }) + ), + ["web" /* web */]: (message) => window?.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.signMessageRequest, + message + }), + getTargetOrigin() + ) + }, + logout: { + ["ios" /* ios */]: () => window.webkit.messageHandlers.logout.postMessage(), + ["reactNative" /* reactNative */]: () => window?.ReactNativeWebView.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.logoutRequest + }) + ), + ["web" /* web */]: () => window?.postMessage( + JSON.stringify({ + type: WebViewProviderRequestEnums.logoutRequest + }), + getTargetOrigin() + ) + } +}; + +// src/webview-provider/webview-provider.ts +var currentPlatform = detectCurrentPlatform(); +var messageType = "message"; +var handleWaitForMessage = (cb) => { + const handleMessageReceived = (event) => { + let eventData = event.data; + if (event.target.origin != getTargetOrigin() && currentPlatform != "reactNative" /* reactNative */) { + return; + } + try { + eventData = JSON.parse(eventData); + cb(eventData); + } catch (err) { + console.error("error parsing response"); + } + }; + if (document) { + document.addEventListener(messageType, handleMessageReceived); + } + if (window) { + window.addEventListener(messageType, handleMessageReceived); + } +}; +var WebviewProvider = class { + constructor() { + } + async logout() { + requestMethods.logout[currentPlatform](); + return new Promise((resolve) => { + resolve(true); + }); + } + async signMessage(message) { + try { + requestMethods.signMessage[currentPlatform](message); + const waitForSignedMessageResponse = new Promise( + (resolve, reject) => { + window.signMessageResponse = (signedMessage, error) => { + if (error) { + reject(error); + window.signMessageResponse = null; + return; + } + resolve(signedMessage); + window.signMessageResponse = null; + }; + function handleSignMessageResponse(eventData) { + const { message: message2, type } = eventData; + if (type === WebViewProviderResponseEnums.signMessageResponse && message2 != null) { + const { signedMessage, error } = message2; + if (!error) { + resolve(signedMessage); + } else { + reject(error); + } + } + document?.removeEventListener( + messageType, + handleSignMessageResponse + ); + } + handleWaitForMessage(handleSignMessageResponse); + } + ); + return await waitForSignedMessageResponse; + } catch (err) { + console.error("error sending transaction", err); + throw err; + } + } + async signTransactions(transactions) { + try { + const plainTransactions = transactions.map((tx) => tx.toPlainObject()); + requestMethods.signTransactions[currentPlatform](plainTransactions); + const waitForSignedTransactionsResponse = new Promise((resolve, reject) => { + window.transactionsSigned = (txs, error) => { + txs = JSON.parse(txs); + if (error) { + reject(error); + window.transactionsSigned = null; + return; + } + resolve(txs.map((tx) => import_transaction2.Transaction.fromPlainObject(tx))); + window.transactionsSigned = null; + }; + function handleSignTransactionResponse(eventData) { + const { message, type } = eventData; + if (type === WebViewProviderResponseEnums.signTransactionsResponse) { + const { transactions: transactions2, error } = message; + try { + if (!error) { + resolve( + transactions2.map( + (tx) => import_transaction2.Transaction.fromPlainObject(tx) + ) + ); + } else { + reject(error); + } + } catch (err) { + reject("Unable to sign"); + } + } + if (document) { + document.removeEventListener( + messageType, + handleSignTransactionResponse + ); + } + } + handleWaitForMessage(handleSignTransactionResponse); + }); + return await waitForSignedTransactionsResponse; + } catch (err) { + console.error("error sending transaction", err); + throw err; + } + } + async signTransaction(transaction) { + const response = await this.signTransactions([transaction]); + return response[0]; + } +}; + +// src/auth/login-with-native-auth-token.ts +init_shim(); + +// src/webview-provider/decode-native-auth-token.ts +init_shim(); + +// src/webview-provider/base64-utils.ts +init_shim(); +function isStringBase64(str) { + try { + const atobDecoded = atob(str); + const btoaEncoded = btoa(atobDecoded); + const bufferFromDecoded = import_buffer.Buffer.from(str, "base64").toString(); + const bufferFromEncoded = import_buffer.Buffer.from(bufferFromDecoded).toString("base64"); + const isEqualToInitialString = str === btoaEncoded && str === bufferFromEncoded; + const isAtobEqualToBufferFrom = atobDecoded === bufferFromDecoded; + if (isEqualToInitialString || isAtobEqualToBufferFrom) { + return true; + } + } catch (e2) { + return false; + } + return false; +} +function decodeBase64(string2) { + if (!isStringBase64(string2)) { + return string2; + } + return atob(string2); +} + +// src/webview-provider/decode-login-token.ts +init_shim(); +var decodeLoginToken = (loginToken) => { + if (!loginToken || !isString(loginToken)) { + return null; + } + const parts = loginToken.split("."); + if (parts.length !== 4) { + return null; + } + try { + const [origin, blockHash, ttl, extraInfo] = parts; + const parsedExtraInfo = JSON.parse(decodeBase64(extraInfo)); + const parsedOrigin = decodeBase64(origin); + return { + ttl: Number(ttl), + extraInfo: parsedExtraInfo, + origin: parsedOrigin, + blockHash + }; + } catch (e2) { + console.error(`Error trying to decode ${loginToken}:`, e2); + return null; + } +}; + +// src/webview-provider/decode-native-auth-token.ts +var decodeNativeAuthToken = (accessToken) => { + if (!accessToken || !isString(accessToken)) { + return null; + } + const parts = accessToken.split("."); + if (parts.length !== 3) { + console.error( + "Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead" + ); + return null; + } + try { + const [address, body, signature] = parts; + const parsedAddress = decodeBase64(address); + const parsedBody = decodeBase64(body); + const parsedInitToken = decodeLoginToken(parsedBody); + if (!parsedInitToken) { + return { + address: parsedAddress, + body: parsedBody, + signature, + blockHash: "", + origin: "", + ttl: 0 + }; + } + const result = { + ...parsedInitToken, + address: parsedAddress, + body: parsedBody, + signature + }; + if (!parsedInitToken.extraInfo?.timestamp) { + delete result.extraInfo; + } + return result; + } catch (err) { + return null; + } +}; + +// src/auth/login-with-native-auth-token.ts +function loginWithNativeAuthToken(token, elven) { + const nativeAuthInfo = decodeNativeAuthToken(token); + if (nativeAuthInfo == null) { + return; + } + const { signature, address, body } = nativeAuthInfo; + if (signature && token && address) { + ls.set("loginToken", body); + ls.set("accessToken", token); + ls.set("signature", signature); + ls.set("address", address); + ls.set("loginMethod", "x-portal-hub" /* xPortalHub */); + elven.dappProvider = new WebviewProvider(); + } +} + +// src/initialize-events-store.ts +init_shim(); +var initializeEventsStore = (initOptions) => { + if (initOptions.onLoginStart) { + EventsStore.set("onLoginStart" /* onLoginStart */, initOptions.onLoginStart); + } + if (initOptions.onLoginSuccess) { + EventsStore.set( + "onLoginSuccess" /* onLoginSuccess */, + initOptions.onLoginSuccess + ); + } + if (initOptions.onLoginFailure) { + EventsStore.set( + "onLoginFailure" /* onLoginFailure */, + initOptions.onLoginFailure + ); + } + if (initOptions.onLogoutStart) { + EventsStore.set("onLogoutStart" /* onLogoutStart */, initOptions.onLogoutStart); + } + if (initOptions.onLogoutSuccess) { + EventsStore.set( + "onLogoutSuccess" /* onLogoutSuccess */, + initOptions.onLogoutSuccess + ); + } + if (initOptions.onLogoutFailure) { + EventsStore.set( + "onLogoutFailure" /* onLogoutFailure */, + initOptions.onLogoutFailure + ); + } + if (initOptions.onQrPending) { + EventsStore.set("onQrPending" /* onQrPending */, initOptions.onQrPending); + } + if (initOptions.onQrLoaded) { + EventsStore.set("onQrLoaded" /* onQrLoaded */, initOptions.onQrLoaded); + } + if (initOptions.onTxStart) { + EventsStore.set("onTxStart" /* onTxStart */, initOptions.onTxStart); + } + if (initOptions.onTxSent) { + EventsStore.set("onTxSent" /* onTxSent */, initOptions.onTxSent); + } + if (initOptions.onTxFinalized) { + EventsStore.set("onTxFinalized" /* onTxFinalized */, initOptions.onTxFinalized); + } + if (initOptions.onTxFailure) { + EventsStore.set("onTxFailure" /* onTxFailure */, initOptions.onTxFailure); + } + if (initOptions.onSignMsgStart) { + EventsStore.set( + "onSignMsgStart" /* onSignMsgStart */, + initOptions.onSignMsgStart + ); + } + if (initOptions.onSignMsgFinalized) { + EventsStore.set( + "onSignMsgFinalized" /* onSignMsgFinalized */, + initOptions.onSignMsgFinalized + ); + } + if (initOptions.onSignMsgFailure) { + EventsStore.set( + "onSignMsgFailure" /* onSignMsgFailure */, + initOptions.onSignMsgFailure + ); + } + if (initOptions.onQueryStart) { + EventsStore.set("onQueryStart" /* onQueryStart */, initOptions.onQueryStart); + } + if (initOptions.onQueryFinalized) { + EventsStore.set( + "onQueryFinalized" /* onQueryFinalized */, + initOptions.onQueryFinalized + ); + } + if (initOptions.onQueryFailure) { + EventsStore.set( + "onQueryFailure" /* onQueryFailure */, + initOptions.onQueryFailure + ); + } +}; + +// src/utils/with-login-events.ts +init_shim(); +var withLoginEvents = async (fn) => { + EventsStore.run("onLoginStart" /* onLoginStart */); + try { + await fn(() => { + EventsStore.run("onLoginSuccess" /* onLoginSuccess */); + }); + } catch (e2) { + const err = errorParse(e2); + console.warn(`Something went wrong trying to login the user: ${err}`); + EventsStore.run("onLoginFailure" /* onLoginFailure */, err); + } +}; + +// src/main.ts +var ElvenJS = class { + /** + * Initialization of the Elven.js + */ + static async init(options) { + const state = ls.get(); + if (state.expires && isLoginExpired(state.expires)) { + ls.clear(); + this.dappProvider = void 0; + return; + } + this.initOptions = { + chainType: defaultChainTypeConfig, + apiUrl: defaultApiEndpoint, + apiTimeout: 1e4, + walletConnectV2ProjectId: "", + walletConnectV2RelayAddresses: defaultWalletConnectV2RelayAddresses, + ...options + }; + this.networkProvider = new ApiNetworkProvider(this.initOptions); + initializeEventsStore(this.initOptions); + const nativeAuthTokenFromUrl = getParamFromUrl("accessToken"); + if (nativeAuthTokenFromUrl) { + await withLoginEvents(async (onLoginSuccess) => { + loginWithNativeAuthToken(nativeAuthTokenFromUrl, this); + await accountSync(this); + onLoginSuccess(); + }); + } + const isAddress = state?.address || (state.loginMethod === "web-wallet" /* webWallet */ || state.loginMethod === "x-alias" /* xAlias */) && getParamFromUrl("address"); + if (isAddress && state?.loginMethod) { + await withLoginEvents(async (onLoginSuccess) => { + if (state.loginMethod === "browser-extension" /* browserExtension */) { + this.dappProvider = await initExtensionProvider(); + } + if (state.loginMethod === "mobile" /* mobile */) { + this.dappProvider = await initMobileProvider(this); + } + if (state.loginMethod === "x-portal-hub" /* xPortalHub */) { + this.dappProvider = new WebviewProvider(); + } + if (state.loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { + this.dappProvider = await initWebWalletProvider( + networkConfig[this.initOptions.chainType].walletAddress, + this.initOptions.apiUrl + ); + } + if (state.loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { + this.dappProvider = await initWebWalletProvider( + networkConfig[this.initOptions.chainType].xAliasAddress, + this.initOptions.apiUrl + ); + } + await accountSync(this); + onLoginSuccess(); + }); + if (this.initOptions?.chainType) { + await webWalletTxFinalize( + this.dappProvider, + this.networkProvider, + networkConfig[this.initOptions.chainType][state.loginMethod === "x-alias" /* xAlias */ ? "xAliasAddress" : "walletAddress"], + state.nonce + ); + webWalletSignMessageFinalize(); + } + } + } + /** + * Login function + */ + static async login(loginMethod, options) { + const isProperLoginMethod = Object.values(LoginMethodsEnum).includes(loginMethod); + if (!isProperLoginMethod) { + const error = "Wrong login method!"; + EventsStore.run("onLoginFailure" /* onLoginFailure */, error); + throw new Error(error); + } + if (!this.networkProvider) { + const error = "Login failed: Use ElvenJs.init() first!"; + EventsStore.run("onLoginFailure" /* onLoginFailure */, error); + throw new Error(error); + } + await withLoginEvents(async () => { + const nativeAuthClient = new import_native_auth2.NativeAuthClient({ + apiUrl: this.initOptions?.apiUrl, + origin: window.location.origin + }); + const loginToken = await nativeAuthClient.initialize(); + if (loginMethod === "browser-extension" /* browserExtension */) { + const dappProvider = await loginWithExtension( + this, + loginToken, + nativeAuthClient, + options?.callbackRoute + ); + this.dappProvider = dappProvider; + } + if (loginMethod === "mobile" /* mobile */) { + const dappProvider = await loginWithMobile( + this, + loginToken, + nativeAuthClient, + options?.qrCodeContainer + ); + this.dappProvider = dappProvider; + } + if (loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { + const dappProvider = await loginWithWebWallet( + networkConfig[this.initOptions.chainType].walletAddress, + loginToken, + this.initOptions?.chainType, + options?.callbackRoute + ); + this.dappProvider = dappProvider; + } + if (loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { + const dappProvider = await loginWithWebWallet( + networkConfig[this.initOptions.chainType].xAliasAddress, + loginToken, + this.initOptions?.chainType, + options?.callbackRoute + ); + this.dappProvider = dappProvider; + } + }); + } + /** + * Logout function + */ + static async logout() { + try { + const isLoggedOut = await logout(this); + this.dappProvider = void 0; + return isLoggedOut; + } catch (e2) { + const err = errorParse(e2); + console.warn("Something went wrong when logging out: ", err); + } + } + /** + * Sign and send function + */ + static async signAndSendTransaction(transaction) { + if (!this.dappProvider) { + const error = "Transaction signing failed: There is no active session!"; + EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); + throw new Error(error); + } + if (!this.networkProvider) { + const error = "Transaction signing failed: There is no active network provider!"; + EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); + throw new Error(error); + } + let signedTx = guardianPreSignTxOperations(transaction); + try { + EventsStore.run("onTxStart" /* onTxStart */, transaction); + const currentState = ls.get(); + transaction.nonce = currentState.nonce; + if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { + signedTx = await this.dappProvider.signTransaction(transaction); + } + if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { + signedTx = await this.dappProvider.signTransaction(transaction); + } + if (this.dappProvider instanceof WebviewProvider) { + signedTx = await this.dappProvider.signTransaction(transaction); + } + if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { + await this.dappProvider.signTransaction(transaction); + } + if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { + const needsGuardianSign = checkNeedsGuardianSigning(signedTx); + if (!needsGuardianSign) { + preSendTx(signedTx); + } + if (needsGuardianSign && this.initOptions?.chainType) { + await sendTxToGuardian( + signedTx, + networkConfig[this.initOptions.chainType].walletAddress + ); + return; + } + await this.networkProvider.sendTransaction(signedTx); + await postSendTx(signedTx, this.networkProvider); + } + } catch (e2) { + const err = errorParse(e2); + EventsStore.run( + "onTxFailure" /* onTxFailure */, + signedTx, + `Getting transaction information failed! ${err}` + ); + throw new Error(`Getting transaction information failed! ${err}`); + } + return signedTx; + } + /** + * Sign a single message + */ + static async signMessage(message, options) { + if (!this.dappProvider) { + const error = "Message signing failed: There is no active session!"; + EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); + throw new Error(error); + } + if (!this.networkProvider) { + const error = "Message signing failed: There is no active network provider!"; + EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); + throw new Error(error); + } + let messageSignature = ""; + try { + EventsStore.run("onSignMsgStart" /* onSignMsgStart */, message); + if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { + const signedMessage = await this.dappProvider.signMessage( + new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) + ); + messageSignature = signedMessage.getSignature().toString("hex"); + } + if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { + const signedMessage = await this.dappProvider.signMessage( + new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) + ); + messageSignature = signedMessage.getSignature().toString("hex"); + } + if (this.dappProvider instanceof WebviewProvider) { + messageSignature = await this.dappProvider.signMessage(message); + } + if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { + const encodeRFC3986URIComponent = (str) => { + return encodeURIComponent(str).replace( + /[!'()*]/g, + (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}` + ); + }; + const url = options?.callbackUrl || window.location.origin; + await this.dappProvider.signMessage( + new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }), + { + callbackUrl: encodeURIComponent( + `${url}${url.includes("?") ? "&" : "?"}message=${encodeRFC3986URIComponent(message)}` + ) + } + ); + } + const currentState = ls.get(); + if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { + EventsStore.run( + "onSignMsgFinalized" /* onSignMsgFinalized */, + message, + messageSignature + ); + } + return { message, messageSignature }; + } catch (e2) { + const err = errorParse(e2); + EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, err); + throw new Error(`Message signing failed! ${err}`); + } + } + /** + * Query Smart Contracts + */ + static async queryContract({ + address, + func, + args = [], + value = 0, + caller + }) { + if (!this.networkProvider) { + throw new Error("Query failed: There is no active network provider!"); + } + if (!address || !func) { + throw new Error( + "Query failed: The Query arguments are not valid! Address and func required" + ); + } + const queryArgs = { + address, + func, + args, + value, + caller + }; + try { + EventsStore.run("onQueryStart" /* onQueryStart */, queryArgs); + const response = await this.networkProvider.queryContract(queryArgs); + EventsStore.run("onQueryFinalized" /* onQueryFinalized */, response); + return response; + } catch (e2) { + const err = errorParse(e2); + EventsStore.run("onQueryFinalized" /* onQueryFinalized */, queryArgs, err); + throw new Error(`Smart contract query failed! ${err}`); + } + } + static { + /** + * Main storage + */ + this.storage = ls; + } + static { + /** + * Destroy and cleanup if needed + */ + this.destroy = () => { + this.networkProvider = void 0; + this.dappProvider = void 0; + this.initOptions = void 0; + EventsStore.clear(); + }; + } +}; + +// src/utils/amount.ts +init_shim(); + +// node_modules/bignumber.js/bignumber.mjs +init_shim(); +var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; +var mathceil = Math.ceil; +var mathfloor = Math.floor; +var bignumberError = "[BigNumber Error] "; +var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; +var BASE = 1e14; +var LOG_BASE = 14; +var MAX_SAFE_INTEGER = 9007199254740991; +var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13]; +var SQRT_BASE = 1e7; +var MAX = 1e9; +function clone(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + // non-breaking space + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber2(v2, b4) { + var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber2)) + return new BigNumber2(v2, b4); + if (b4 == null) { + if (v2 && v2._isBigNumber === true) { + x3.s = v2.s; + if (!v2.c || v2.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v2.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v2.e; + x3.c = v2.c.slice(); + } + return; + } + if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { + x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; + if (v2 === ~~v2) { + for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v2]; + } + return; + } + str = String(v2); + } else { + if (!isNumeric.test(str = String(v2))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i2 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i2; + e2 += +str.slice(i2 + 1); + str = str.substring(0, i2); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck(b4, 2, ALPHABET.length, "Base"); + if (b4 == 10 && alphabetHasNormalDecimalDigits) { + x3 = new BigNumber2(v2); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v2); + if (isNum = typeof v2 == "number") { + if (v2 * 0 != 0) + return parseNumeric(x3, str, isNum, b4); + x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits + v2); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet2 = ALPHABET.slice(0, b4); + e2 = i2 = 0; + for (len = str.length; i2 < len; i2++) { + if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { + if (c4 == ".") { + if (i2 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i2 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v2), isNum, b4); + } + } + isNum = false; + str = convertBase(str, b4, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i2 = 0; str.charCodeAt(i2) === 48; i2++) + ; + for (len = str.length; str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i2, ++len)) { + len -= i2; + if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) { + throw Error(tooManyDigits + x3.s * v2); + } + if ((e2 = e2 - i2 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i2 = (e2 + 1) % LOG_BASE; + if (e2 < 0) + i2 += LOG_BASE; + if (i2 < len) { + if (i2) + x3.c.push(+str.slice(0, i2)); + for (len -= LOG_BASE; i2 < len; ) { + x3.c.push(+str.slice(i2, i2 += LOG_BASE)); + } + i2 = LOG_BASE - (str = str.slice(i2)).length; + } else { + i2 -= len; + } + for (; i2--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber2.clone = clone; + BigNumber2.ROUND_UP = 0; + BigNumber2.ROUND_DOWN = 1; + BigNumber2.ROUND_CEIL = 2; + BigNumber2.ROUND_FLOOR = 3; + BigNumber2.ROUND_HALF_UP = 4; + BigNumber2.ROUND_HALF_DOWN = 5; + BigNumber2.ROUND_HALF_EVEN = 6; + BigNumber2.ROUND_HALF_CEIL = 7; + BigNumber2.ROUND_HALF_FLOOR = 8; + BigNumber2.EUCLID = 9; + BigNumber2.config = BigNumber2.set = function(obj) { + var p3, v2; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { + v2 = obj[p3]; + intCheck(v2, 0, MAX, p3); + DECIMAL_PLACES = v2; + } + if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { + v2 = obj[p3]; + intCheck(v2, 0, 8, p3); + ROUNDING_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck(v2[0], -MAX, 0, p3); + intCheck(v2[1], 0, MAX, p3); + TO_EXP_NEG = v2[0]; + TO_EXP_POS = v2[1]; + } else { + intCheck(v2, -MAX, MAX, p3); + TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); + } + } + if (obj.hasOwnProperty(p3 = "RANGE")) { + v2 = obj[p3]; + if (v2 && v2.pop) { + intCheck(v2[0], -MAX, -1, p3); + intCheck(v2[1], 1, MAX, p3); + MIN_EXP = v2[0]; + MAX_EXP = v2[1]; + } else { + intCheck(v2, -MAX, MAX, p3); + if (v2) { + MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); + } else { + throw Error(bignumberError + p3 + " cannot be zero: " + v2); + } + } + } + if (obj.hasOwnProperty(p3 = "CRYPTO")) { + v2 = obj[p3]; + if (v2 === !!v2) { + if (v2) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v2; + } else { + CRYPTO = !v2; + throw Error(bignumberError + "crypto unavailable"); + } + } else { + CRYPTO = v2; + } + } else { + throw Error(bignumberError + p3 + " not true or false: " + v2); + } + } + if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { + v2 = obj[p3]; + intCheck(v2, 0, 9, p3); + MODULO_MODE = v2; + } + if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { + v2 = obj[p3]; + intCheck(v2, 0, MAX, p3); + POW_PRECISION = v2; + } + if (obj.hasOwnProperty(p3 = "FORMAT")) { + v2 = obj[p3]; + if (typeof v2 == "object") + FORMAT = v2; + else + throw Error(bignumberError + p3 + " not an object: " + v2); + } + if (obj.hasOwnProperty(p3 = "ALPHABET")) { + v2 = obj[p3]; + if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { + alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; + ALPHABET = v2; + } else { + throw Error(bignumberError + p3 + " invalid: " + v2); + } + } + } else { + throw Error(bignumberError + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber2.isBigNumber = function(v2) { + if (!v2 || v2._isBigNumber !== true) + return false; + if (!BigNumber2.DEBUG) + return true; + var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; + out: + if ({}.toString.call(c4) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX && e2 <= MAX && e2 === mathfloor(e2)) { + if (c4[0] === 0) { + if (e2 === 0 && c4.length === 1) + return true; + break out; + } + i2 = (e2 + 1) % LOG_BASE; + if (i2 < 1) + i2 += LOG_BASE; + if (String(c4[0]).length == i2) { + for (i2 = 0; i2 < c4.length; i2++) { + n3 = c4[i2]; + if (n3 < 0 || n3 >= BASE || n3 !== mathfloor(n3)) + break out; + } + if (n3 !== 0) + return true; + } + } + } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError + "Invalid BigNumber: " + v2); + }; + BigNumber2.maximum = BigNumber2.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber2.minimum = BigNumber2.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber2.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber2(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck(dp, 0, MAX); + k4 = mathceil(dp / LOG_BASE); + if (CRYPTO) { + if (crypto.getRandomValues) { + a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); + for (; i2 < k4; ) { + v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); + if (v2 >= 9e15) { + b4 = crypto.getRandomValues(new Uint32Array(2)); + a3[i2] = b4[0]; + a3[i2 + 1] = b4[1]; + } else { + c4.push(v2 % 1e14); + i2 += 2; + } + } + i2 = k4 / 2; + } else if (crypto.randomBytes) { + a3 = crypto.randomBytes(k4 *= 7); + for (; i2 < k4; ) { + v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; + if (v2 >= 9e15) { + crypto.randomBytes(7).copy(a3, i2); + } else { + c4.push(v2 % 1e14); + i2 += 7; + } + } + i2 = k4 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (; i2 < k4; ) { + v2 = random53bitInt(); + if (v2 < 9e15) + c4[i2++] = v2 % 1e14; + } + } + k4 = c4[--i2]; + dp %= LOG_BASE; + if (k4 && dp) { + v2 = POWS_TEN[LOG_BASE - dp]; + c4[i2] = mathfloor(k4 / v2) * v2; + } + for (; c4[i2] === 0; c4.pop(), i2--) + ; + if (i2 < 0) { + c4 = [e2 = 0]; + } else { + for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE) + ; + for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) + ; + if (i2 < LOG_BASE) + e2 -= LOG_BASE - i2; + } + rand.e = e2; + rand.c = c4; + return rand; + }; + }(); + BigNumber2.sum = function() { + var i2 = 1, args = arguments, sum = new BigNumber2(args[0]); + for (; i2 < args.length; ) + sum = sum.plus(args[i2++]); + return sum; + }; + convertBase = /* @__PURE__ */ function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet2) { + var j2, arr = [0], arrL, i2 = 0, len = str.length; + for (; i2 < len; ) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet2.indexOf(str.charAt(i2++)); + for (j2 = 0; j2 < arr.length; j2++) { + if (arr[j2] > baseOut - 1) { + if (arr[j2 + 1] == null) + arr[j2 + 1] = 0; + arr[j2 + 1] += arr[j2] / baseOut | 0; + arr[j2] %= baseOut; + } + } + } + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign2, callerIsToString) { + var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i2 >= 0) { + k4 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y4 = new BigNumber2(baseIn); + x3 = y4.pow(str.length - i2); + POW_PRECISION = k4; + y4.c = toBaseOut( + toFixedPoint(coeffToString(x3.c), x3.e, "0"), + 10, + baseOut, + decimal + ); + y4.e = y4.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); + e2 = k4 = xc.length; + for (; xc[--k4] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet2.charAt(0); + if (i2 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign2; + x3 = div(x3, y4, dp, rm, baseOut); + xc = x3.c; + r = x3.r; + e2 = x3.e; + } + d3 = e2 + dp + 1; + i2 = xc[d3]; + k4 = baseOut / 2; + r = r || d3 < 0 || xc[d3 + 1] != null; + r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (d3 < 1 || !xc[0]) { + str = r ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); + } else { + xc.length = d3; + if (r) { + for (--baseOut; ++xc[--d3] > baseOut; ) { + xc[d3] = 0; + if (!d3) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k4 = xc.length; !xc[--k4]; ) + ; + for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) + ; + str = toFixedPoint(str, e2, alphabet2.charAt(0)); + } + return str; + }; + }(); + div = /* @__PURE__ */ function() { + function multiply(x3, k4, base3) { + var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE, khi = k4 / SQRT_BASE | 0; + for (x3 = x3.slice(); i2--; ) { + xlo = x3[i2] % SQRT_BASE; + xhi = x3[i2] / SQRT_BASE | 0; + m3 = khi * xlo + xhi * klo; + temp = klo * xlo + m3 % SQRT_BASE * SQRT_BASE + carry; + carry = (temp / base3 | 0) + (m3 / SQRT_BASE | 0) + khi * xhi; + x3[i2] = temp % base3; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare3(a3, b4, aL, bL) { + var i2, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i2 = cmp = 0; i2 < aL; i2++) { + if (a3[i2] != b4[i2]) { + cmp = a3[i2] > b4[i2] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a3, b4, aL, base3) { + var i2 = 0; + for (; aL--; ) { + a3[aL] -= i2; + i2 = a3[aL] < b4[aL] ? 1 : 0; + a3[aL] = i2 * base3 + a3[aL] - b4[aL]; + } + for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) + ; + } + return function(x3, y4, dp, rm, base3) { + var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber2( + // Return NaN if either NaN, or both Infinity or 0. + !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 + ) + ); + } + q2 = new BigNumber2(s2); + qc = q2.c = []; + e2 = x3.e - y4.e; + s2 = dp + e2 + 1; + if (!base3) { + base3 = BASE; + e2 = bitFloor(x3.e / LOG_BASE) - bitFloor(y4.e / LOG_BASE); + s2 = s2 / LOG_BASE | 0; + } + for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) + ; + if (yc[i2] > (xc[i2] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i2 = 0; + s2 += 2; + n3 = mathfloor(base3 / (yc[0] + 1)); + if (n3 > 1) { + yc = multiply(yc, n3, base3); + xc = multiply(xc, n3, base3); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (; remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base3 / 2) + yc0++; + do { + n3 = 0; + cmp = compare3(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base3 + (rem[1] || 0); + n3 = mathfloor(rem0 / yc0); + if (n3 > 1) { + if (n3 >= base3) + n3 = base3 - 1; + prod = multiply(yc, n3, base3); + prodL = prod.length; + remL = rem.length; + while (compare3(prod, rem, prodL, remL) == 1) { + n3--; + subtract(prod, yL < prodL ? yz : yc, prodL, base3); + prodL = prod.length; + cmp = 1; + } + } else { + if (n3 == 0) { + cmp = n3 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base3); + remL = rem.length; + if (cmp == -1) { + while (compare3(yc, rem, yL, remL) < 1) { + n3++; + subtract(rem, yL < remL ? yz : yc, remL, base3); + remL = rem.length; + } + } + } else if (cmp === 0) { + n3++; + rem = [0]; + } + qc[i2++] = n3; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base3 == BASE) { + for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) + ; + round(q2, dp + (q2.e = i2 + e2 * LOG_BASE - 1) + 1, rm, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format(n3, i2, rm, id) { + var c0, e2, ne, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + if (!n3.c) + return n3.toString(); + c0 = n3.c[0]; + ne = n3.e; + if (i2 == null) { + str = coeffToString(n3.c); + str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0"); + } else { + n3 = round(new BigNumber2(n3), i2, rm); + e2 = n3.e; + str = coeffToString(n3.c); + len = str.length; + if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { + for (; len < i2; str += "0", len++) + ; + str = toExponential(str, e2); + } else { + i2 -= ne; + str = toFixedPoint(str, e2, "0"); + if (e2 + 1 > len) { + if (--i2 > 0) + for (str += "."; i2--; str += "0") + ; + } else { + i2 += e2 - len; + if (i2 > 0) { + if (e2 + 1 == len) + str += "."; + for (; i2--; str += "0") + ; + } + } + } + } + return n3.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, n3) { + var k4, y4, i2 = 1, x3 = new BigNumber2(args[0]); + for (; i2 < args.length; i2++) { + y4 = new BigNumber2(args[i2]); + if (!y4.s || (k4 = compare2(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { + x3 = y4; + } + } + return x3; + } + function normalise(n3, c4, e2) { + var i2 = 1, j2 = c4.length; + for (; !c4[--j2]; c4.pop()) + ; + for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) + ; + if ((e2 = i2 + e2 * LOG_BASE - 1) > MAX_EXP) { + n3.c = n3.e = null; + } else if (e2 < MIN_EXP) { + n3.c = [n3.e = 0]; + } else { + n3.e = e2; + n3.c = c4; + } + return n3; + } + parseNumeric = /* @__PURE__ */ function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b4) { + var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m3, p1, p22) { + base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; + return !b4 || b4 == base3 ? p1 : m3; + }); + if (b4) { + base3 = b4; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber2(s2, base3); + } + if (BigNumber2.DEBUG) { + throw Error(bignumberError + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm, r) { + var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN; + if (xc) { + out: { + for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) + ; + i2 = sd - d3; + if (i2 < 0) { + i2 += LOG_BASE; + j2 = sd; + n3 = xc[ni = 0]; + rd = mathfloor(n3 / pows10[d3 - j2 - 1] % 10); + } else { + ni = mathceil((i2 + 1) / LOG_BASE); + if (ni >= xc.length) { + if (r) { + for (; xc.length <= ni; xc.push(0)) + ; + n3 = rd = 0; + d3 = 1; + i2 %= LOG_BASE; + j2 = i2 - LOG_BASE + 1; + } else { + break out; + } + } else { + n3 = k4 = xc[ni]; + for (d3 = 1; k4 >= 10; k4 /= 10, d3++) + ; + i2 %= LOG_BASE; + j2 = i2 - LOG_BASE + d3; + rd = j2 < 0 ? 0 : mathfloor(n3 / pows10[d3 - j2 - 1] % 10); + } + } + r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. + (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i2 == 0) { + xc.length = ni; + k4 = 1; + ni--; + } else { + xc.length = ni + 1; + k4 = pows10[LOG_BASE - i2]; + xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; + } + if (r) { + for (; ; ) { + if (ni == 0) { + for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) + ; + j2 = xc[0] += k4; + for (k4 = 1; j2 >= 10; j2 /= 10, k4++) + ; + if (i2 != k4) { + x3.e++; + if (xc[0] == BASE) + xc[0] = 1; + } + break; + } else { + xc[ni] += k4; + if (xc[ni] != BASE) + break; + xc[ni--] = 0; + k4 = 1; + } + } + } + for (i2 = xc.length; xc[--i2] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n3) { + var str, e2 = n3.e; + if (e2 === null) + return n3.toString(); + str = coeffToString(n3.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); + return n3.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber2(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm) { + var c4, n3, v2, x3 = this; + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber2(x3), dp + x3.e + 1, rm); + } + if (!(c4 = x3.c)) + return null; + n3 = ((v2 = c4.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + if (v2 = c4[v2]) + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + if (n3 < 0) + n3 = 0; + return n3; + }; + P2.dividedBy = P2.div = function(y4, b4) { + return div(this, new BigNumber2(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { + return div(this, new BigNumber2(y4, b4), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n3, m3) { + var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; + n3 = new BigNumber2(n3); + if (n3.c && !n3.isInteger()) { + throw Error(bignumberError + "Exponent not an integer: " + valueOf(n3)); + } + if (m3 != null) + m3 = new BigNumber2(m3); + nIsBig = n3.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { + y4 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd(n3)) : +valueOf(n3))); + return m3 ? y4.mod(m3) : y4; + } + nIsNeg = n3.s < 0; + if (m3) { + if (m3.c ? !m3.c[0] : !m3.s) + return new BigNumber2(NaN); + isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); + if (isModExp) + x3 = x3.mod(m3); + } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { + k4 = x3.s < 0 && isOdd(n3) ? -0 : 0; + if (x3.e > -1) + k4 = 1 / k4; + return new BigNumber2(nIsNeg ? 1 / k4 : k4); + } else if (POW_PRECISION) { + k4 = mathceil(POW_PRECISION / LOG_BASE + 2); + } + if (nIsBig) { + half = new BigNumber2(0.5); + if (nIsNeg) + n3.s = 1; + nIsOdd = isOdd(n3); + } else { + i2 = Math.abs(+valueOf(n3)); + nIsOdd = i2 % 2; + } + y4 = new BigNumber2(ONE); + for (; ; ) { + if (nIsOdd) { + y4 = y4.times(x3); + if (!y4.c) + break; + if (k4) { + if (y4.c.length > k4) + y4.c.length = k4; + } else if (isModExp) { + y4 = y4.mod(m3); + } + } + if (i2) { + i2 = mathfloor(i2 / 2); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } else { + n3 = n3.times(half); + round(n3, n3.e + 1, 1); + if (n3.e > 14) { + nIsOdd = isOdd(n3); + } else { + i2 = +valueOf(n3); + if (i2 === 0) + break; + nIsOdd = i2 % 2; + } + } + x3 = x3.times(x3); + if (k4) { + if (x3.c && x3.c.length > k4) + x3.c.length = k4; + } else if (isModExp) { + x3 = x3.mod(m3); + } + } + if (isModExp) + return y4; + if (nIsNeg) + y4 = ONE.div(y4); + return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; + }; + P2.integerValue = function(rm) { + var n3 = new BigNumber2(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(n3, n3.e + 1, rm); + }; + P2.isEqualTo = P2.eq = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { + return (b4 = compare2(this, new BigNumber2(y4, b4))) === 1 || b4 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y4, b4) { + return compare2(this, new BigNumber2(y4, b4)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { + return (b4 = compare2(this, new BigNumber2(y4, b4))) === -1 || b4 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y4, b4) { + var i2, j2, t, xLTy, x3 = this, a3 = x3.s; + y4 = new BigNumber2(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber2(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.plus(y4); + } + var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y4.s = -b4, y4) : new BigNumber2(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y4.s = -b4, y4) : new BigNumber2(xc[0] ? x3 : ( + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 + )); + } + } + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (xLTy = a3 < 0) { + a3 = -a3; + t = xc; + } else { + ye = xe; + t = yc; + } + t.reverse(); + for (b4 = a3; b4--; t.push(0)) + ; + t.reverse(); + } else { + j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; + for (a3 = b4 = 0; b4 < j2; b4++) { + if (xc[b4] != yc[b4]) { + xLTy = xc[b4] < yc[b4]; + break; + } + } + } + if (xLTy) { + t = xc; + xc = yc; + yc = t; + y4.s = -y4.s; + } + b4 = (j2 = yc.length) - (i2 = xc.length); + if (b4 > 0) + for (; b4--; xc[i2++] = 0) + ; + b4 = BASE - 1; + for (; j2 > a3; ) { + if (xc[--j2] < yc[j2]) { + for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) + ; + --xc[i2]; + xc[j2] += BASE; + } + xc[j2] -= yc[j2]; + } + for (; xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y4.s = ROUNDING_MODE == 3 ? -1 : 1; + y4.c = [y4.e = 0]; + return y4; + } + return normalise(y4, xc, ye); + }; + P2.modulo = P2.mod = function(y4, b4) { + var q2, s2, x3 = this; + y4 = new BigNumber2(y4, b4); + if (!x3.c || !y4.s || y4.c && !y4.c[0]) { + return new BigNumber2(NaN); + } else if (!y4.c || x3.c && !x3.c[0]) { + return new BigNumber2(x3); + } + if (MODULO_MODE == 9) { + s2 = y4.s; + y4.s = 1; + q2 = div(x3, y4, 0, 3); + y4.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y4, 0, MODULO_MODE); + } + y4 = x3.minus(q2.times(y4)); + if (!y4.c[0] && MODULO_MODE == 1) + y4.s = x3.s; + return y4; + }; + P2.multipliedBy = P2.times = function(y4, b4) { + var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber2(y4, b4)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y4.c = y4.e = y4.s = null; + } else { + y4.s *= x3.s; + if (!xc || !yc) { + y4.c = y4.e = null; + } else { + y4.c = [0]; + y4.e = 0; + } + } + return y4; + } + e2 = bitFloor(x3.e / LOG_BASE) + bitFloor(y4.e / LOG_BASE); + y4.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i2 = xcL; + xcL = ycL; + ycL = i2; + } + for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) + ; + base3 = BASE; + sqrtBase = SQRT_BASE; + for (i2 = ycL; --i2 >= 0; ) { + c4 = 0; + ylo = yc[i2] % sqrtBase; + yhi = yc[i2] / sqrtBase | 0; + for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { + xlo = xc[--k4] % sqrtBase; + xhi = xc[k4] / sqrtBase | 0; + m3 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; + c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base3; + } + zc[j2] = c4; + } + if (c4) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y4, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber2(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y4, b4) { + var t, x3 = this, a3 = x3.s; + y4 = new BigNumber2(y4, b4); + b4 = y4.s; + if (!a3 || !b4) + return new BigNumber2(NaN); + if (a3 != b4) { + y4.s = -b4; + return x3.minus(y4); + } + var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber2(a3 / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y4 : new BigNumber2(xc[0] ? x3 : a3 * 0); + } + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a3 = xe - ye) { + if (a3 > 0) { + ye = xe; + t = yc; + } else { + a3 = -a3; + t = xc; + } + t.reverse(); + for (; a3--; t.push(0)) + ; + t.reverse(); + } + a3 = xc.length; + b4 = yc.length; + if (a3 - b4 < 0) { + t = yc; + yc = xc; + xc = t; + b4 = a3; + } + for (a3 = 0; b4; ) { + a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE | 0; + xc[b4] = BASE === xc[b4] ? 0 : xc[b4] % BASE; + } + if (a3) { + xc = [a3].concat(xc); + ++ye; + } + return normalise(y4, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm) { + var c4, n3, v2, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber2(x3), sd, rm); + } + if (!(c4 = x3.c)) + return null; + v2 = c4.length - 1; + n3 = v2 * LOG_BASE + 1; + if (v2 = c4[v2]) { + for (; v2 % 10 == 0; v2 /= 10, n3--) + ; + for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) + ; + } + if (sd && x3.e + 1 > n3) + n3 = x3.e + 1; + return n3; + }; + P2.shiftedBy = function(k4) { + intCheck(k4, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times("1e" + k4); + }; + P2.squareRoot = P2.sqrt = function() { + var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); + if (s2 !== 1 || !c4 || !c4[0]) { + return new BigNumber2(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n3 = coeffToString(c4); + if ((n3.length + e2) % 2 == 0) + n3 += "0"; + s2 = Math.sqrt(+n3); + e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n3 = "5e" + e2; + } else { + n3 = s2.toExponential(); + n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; + } + r = new BigNumber2(n3); + } else { + r = new BigNumber2(s2 + ""); + } + if (r.c[0]) { + e2 = r.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (; ; ) { + t = r; + r = half.times(t.plus(div(x3, t, dp, 1))); + if (coeffToString(t.c).slice(0, s2) === (n3 = coeffToString(r.c)).slice(0, s2)) { + if (r.e < e2) + --s2; + n3 = n3.slice(s2 - 3, s2 + 1); + if (n3 == "9999" || !rep && n3 == "4999") { + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + if (t.times(t).eq(x3)) { + r = t; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m3 = !r.times(r).eq(x3); + } + break; + } + } + } + } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); + }; + P2.toExponential = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + P2.toFixed = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P2.toFormat = function(dp, rm, format2) { + var str, x3 = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError + "Argument not an object: " + format2); + } + str = x3.toFixed(dp, rm); + if (x3.c) { + var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g22) { + i2 = g1; + g1 = g22; + g22 = i2; + len -= i2; + } + if (g1 > 0 && len > 0) { + i2 = len % g1 || g1; + intPart = intDigits.substr(0, i2); + for (; i2 < len; i2 += g1) + intPart += groupSeparator + intDigits.substr(i2, g1); + if (g22 > 0) + intPart += groupSeparator + intDigits.slice(i2); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( + new RegExp("\\d{" + g22 + "}\\B", "g"), + "$&" + (format2.fractionGroupSeparator || "") + ) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P2.toFraction = function(md) { + var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; + if (md != null) { + n3 = new BigNumber2(md); + if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { + throw Error(bignumberError + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); + } + } + if (!xc) + return new BigNumber2(x3); + d3 = new BigNumber2(ONE); + n1 = d0 = new BigNumber2(ONE); + d1 = n0 = new BigNumber2(ONE); + s2 = coeffToString(xc); + e2 = d3.e = s2.length - x3.e - 1; + d3.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n3 = new BigNumber2(s2); + n0.c[0] = 0; + for (; ; ) { + q2 = div(n3, d3, 0, 1); + d22 = d0.plus(q2.times(d1)); + if (d22.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d22; + n1 = n0.plus(q2.times(d22 = n1)); + n0 = d22; + d3 = n3.minus(q2.times(d22 = d3)); + n3 = d22; + } + d22 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d22.times(n1)); + d0 = d0.plus(d22.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( + div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() + ) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm) { + if (sd != null) + intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + P2.toString = function(b4) { + var str, n3 = this, s2 = n3.s, e2 = n3.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b4 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n3.c), e2) : toFixedPoint(coeffToString(n3.c), e2, "0"); + } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { + n3 = round(new BigNumber2(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n3.c), n3.e, "0"); + } else { + intCheck(b4, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint(coeffToString(n3.c), e2, "0"), 10, b4, s2, true); + } + if (s2 < 0 && n3.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + P2[Symbol.toStringTag] = "BigNumber"; + P2[Symbol.for("nodejs.util.inspect.custom")] = P2.valueOf; + if (configObject != null) + BigNumber2.set(configObject); + return BigNumber2; +} +function bitFloor(n3) { + var i2 = n3 | 0; + return n3 > 0 || n3 === i2 ? i2 : i2 - 1; +} +function coeffToString(a3) { + var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; + for (; i2 < j2; ) { + s2 = a3[i2++] + ""; + z3 = LOG_BASE - s2.length; + for (; z3--; s2 = "0" + s2) + ; + r += s2; + } + for (j2 = r.length; r.charCodeAt(--j2) === 48; ) + ; + return r.slice(0, j2 + 1 || 1); +} +function compare2(x3, y4) { + var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; + if (!i2 || !j2) + return null; + a3 = xc && !xc[0]; + b4 = yc && !yc[0]; + if (a3 || b4) + return a3 ? b4 ? 0 : -j2 : i2; + if (i2 != j2) + return i2; + a3 = i2 < 0; + b4 = k4 == l4; + if (!xc || !yc) + return b4 ? 0 : !xc ^ a3 ? 1 : -1; + if (!b4) + return k4 > l4 ^ a3 ? 1 : -1; + j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; + for (i2 = 0; i2 < j2; i2++) + if (xc[i2] != yc[i2]) + return xc[i2] > yc[i2] ^ a3 ? 1 : -1; + return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; +} +function intCheck(n3, min, max, name2) { + if (n3 < min || n3 > max || n3 !== mathfloor(n3)) { + throw Error(bignumberError + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); + } +} +function isOdd(n3) { + var k4 = n3.c.length - 1; + return bitFloor(n3.e / LOG_BASE) == k4 && n3.c[k4] % 2 != 0; +} +function toExponential(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; +} +function toFixedPoint(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + "."; ++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len; --e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; +} +var BigNumber = clone(); +var bignumber_default = BigNumber; + +// src/utils/amount.ts +bignumber_default.config({ ROUNDING_MODE: bignumber_default.ROUND_FLOOR }); +var parseAmount = ({ + amount, + decimals +}) => { + if (decimals < 0) + throw new Error("Decimal places shouldn't be negative number!"); + return BigInt(new bignumber_default(amount).shiftedBy(decimals).toFixed()); +}; +var formatAmount = ({ + amount, + decimals, + rounding = decimals +}) => { + if (decimals < 0) + throw new Error("Decimal places shouldn't be negative number!"); + return new bignumber_default(amount).shiftedBy(-decimals).decimalPlaces(rounding).toFixed(); +}; +var export_Account = import_account4.Account; +var export_Address = import_address4.Address; +var export_AddressType = import_address5.AddressType; +var export_AddressValue = import_address5.AddressValue; +var export_BigUIntType = import_numerical.BigUIntType; +var export_BigUIntValue = import_numerical.BigUIntValue; +var export_BooleanType = import_boolean.BooleanType; +var export_BooleanValue = import_boolean.BooleanValue; +var export_BytesType = import_bytes7.BytesType; +var export_BytesValue = import_bytes7.BytesValue; +var export_ContractQueryResponse = import_contractQueryResponse2.ContractQueryResponse; +var export_Message = import_message.Message; +var export_MessageComputer = import_message.MessageComputer; +var export_QueryArguments = import_interface.QueryArguments; +var export_SignableMessage = import_signableMessage2.SignableMessage; +var export_SmartContractTransactionsFactory = import_transactionsFactories.SmartContractTransactionsFactory; +var export_SmartContractTransactionsOutcomeParser = import_transactionsOutcomeParsers.SmartContractTransactionsOutcomeParser; +var export_Token = import_tokens.Token; +var export_TokenComputer = import_tokens.TokenComputer; +var export_TokenManagementTransactionsFactory = import_transactionsFactories.TokenManagementTransactionsFactory; +var export_TokenManagementTransactionsOutcomeParser = import_transactionsOutcomeParsers.TokenManagementTransactionsOutcomeParser; +var export_TokenOperationsFactory = import_tokenOperations.TokenOperationsFactory; +var export_TokenOperationsFactoryConfig = import_tokenOperations.TokenOperationsFactoryConfig; +var export_TokenOperationsOutcomeParser = import_tokenOperations.TokenOperationsOutcomeParser; +var export_TokenTransfer = import_tokens.TokenTransfer; +var export_Transaction = import_transaction3.Transaction; +var export_TransactionComputer = import_transactionComputer.TransactionComputer; +var export_TransactionEventsParser = import_transactionsOutcomeParsers.TransactionEventsParser; +var export_TransactionWatcher = import_transactionWatcher2.TransactionWatcher; +var export_TransactionsFactoryConfig = import_transactionsFactories.TransactionsFactoryConfig; +var export_TransferTransactionsFactory = import_transactionsFactories.TransferTransactionsFactory; +var export_U16Type = import_numerical.U16Type; +var export_U16Value = import_numerical.U16Value; +var export_U32Type = import_numerical.U32Type; +var export_U32Value = import_numerical.U32Value; +var export_U64Type = import_numerical.U64Type; +var export_U64Value = import_numerical.U64Value; +var export_U8Type = import_numerical.U8Type; +var export_U8Value = import_numerical.U8Value; +export { + export_Account as Account, + export_Address as Address, + export_AddressType as AddressType, + export_AddressValue as AddressValue, + export_BigUIntType as BigUIntType, + export_BigUIntValue as BigUIntValue, + export_BooleanType as BooleanType, + export_BooleanValue as BooleanValue, + export_BytesType as BytesType, + export_BytesValue as BytesValue, + export_ContractQueryResponse as ContractQueryResponse, + DappCoreWCV2CustomMethodsEnum, + ElvenJS, + EventStoreEvents, + LoginMethodsEnum, + export_Message as Message, + export_MessageComputer as MessageComputer, + export_QueryArguments as QueryArguments, + export_SignableMessage as SignableMessage, + export_SmartContractTransactionsFactory as SmartContractTransactionsFactory, + export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser, + export_Token as Token, + export_TokenComputer as TokenComputer, + export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory, + export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser, + export_TokenOperationsFactory as TokenOperationsFactory, + export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig, + export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser, + export_TokenTransfer as TokenTransfer, + export_Transaction as Transaction, + export_TransactionComputer as TransactionComputer, + export_TransactionEventsParser as TransactionEventsParser, + export_TransactionWatcher as TransactionWatcher, + export_TransactionsFactoryConfig as TransactionsFactoryConfig, + export_TransferTransactionsFactory as TransferTransactionsFactory, + export_U16Type as U16Type, + export_U16Value as U16Value, + export_U32Type as U32Type, + export_U32Value as U32Value, + export_U64Type as U64Type, + export_U64Value as U64Value, + export_U8Type as U8Type, + export_U8Value as U8Value, + WebWalletUrlParamsEnum, + formatAmount, + parseAmount +}; /*! Bundled license information: ieee754/index.js: @@ -61,9 +54994,6 @@ buffer/index.js: * @license MIT *) -punycode/punycode.js: - (*! https://mths.be/punycode v1.4.1 by @mathias *) - buffer/index.js: (*! * The buffer module from node.js, for the browser. @@ -90,4 +55020,14 @@ tslib/tslib.es6.js: OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** *) + +@walletconnect/utils/dist/index.cjs.js: + (** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.8.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2018 + * @license MIT + *) */ diff --git a/example/index.html b/example/index.html index 22d6b12..8a8baf1 100644 --- a/example/index.html +++ b/example/index.html @@ -166,14 +166,15 @@

Other demos:

ElvenJS, Transaction, Address, - TransactionPayload, TokenTransfer, + Token, TransferTransactionsFactory, + TransactionsFactoryConfig, + TokenComputer, U32Value, AddressValue, - SmartContract, - GasEstimator, - ContractFunction + SmartContractTransactionsFactory, + parseAmount, } from './elven.js'; // Options are the defaults and here only to show all of them @@ -201,7 +202,7 @@

Other demos:

// Transaction callbacks onTxStart: (tx) => { uiPending(true); }, onTxSent: (tx) => { const hash = tx.getHash().toString(); hash && updateTxHashContainer(hash, true); }, - onTxFinalized: (tx) => { tx?.hash && updateTxHashContainer(tx.hash); uiPending(false); }, + onTxFinalized: (tx) => { console.log(tx); tx?.hash && updateTxHashContainer(tx.hash); uiPending(false); }, onTxFailure: (tx, error) => { displayError(error); uiPending(false); }, // Qr code callbacks: onQrPending: () => { uiPending(true); }, @@ -295,12 +296,14 @@

Other demos:

// See more about gas limit calculation here: https://docs.multiversx.com/developers/gas-and-fees/overview/ const gasLimit = ((isGuardian || isXalias) ? 100000 : 50000) + 1500 * demoMessage.length; + const textEncoder = new TextEncoder(); + const tx = new Transaction({ nonce: ElvenJS.storage.get('nonce'), receiver: new Address(egldTransferAddress), gasLimit, chainID: 'D', - data: new TransactionPayload(demoMessage), + data: textEncoder.encode(demoMessage), value: TokenTransfer.egldFromAmount(0.001), sender: new Address(ElvenJS.storage.get('address')), }); @@ -320,19 +323,19 @@

Other demos:

// You need to know its ticker and how many decimals places it has // In this case, the token has 18 decimal places. You can check it in the MultiversX devnet explorer // You can use the community-based faucet to get the BUILDO-22c0a5 token: https://r3d4.fr/faucet - const transfer = TokenTransfer.fungibleFromAmount( - 'BUILDO-22c0a5', - '1', - 18 - ); + const tokenTransfer = new TokenTransfer({ + token: new Token({ identifier: 'BUILDO-22c0a5' }), + amount: 1000000000000000000n, + }); - const factory = new TransferTransactionsFactory(new GasEstimator()); + const factory = new TransferTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: 'D' }), + }); - const tx = factory.createESDTTransfer({ - tokenTransfer: transfer, + const tx = factory.createTransactionForESDTTokenTransfer({ receiver: new Address(esdtTransferAddress), sender: new Address(ElvenJS.storage.get('address')), - chainID: 'D', + tokenTransfers: [tokenTransfer] }); try { @@ -347,21 +350,25 @@

Other demos:

const nftMinterSmartContract = 'erd1qqqqqqqqqqqqqpgqufmyqvy3kvda2uywqgx809lglxftq9t667es3956pv'; document.getElementById('button-mint').addEventListener('click', async () => { const contractAddress = new Address(nftMinterSmartContract); - const contract = new SmartContract({ address: contractAddress }); const isGuardian = ElvenJS.storage.get('activeGuardian'); // Additional 50000 when there is an active guardian // See more about gas limit calculation here: https://docs.multiversx.com/developers/gas-and-fees/overview/ const gasLimit = isGuardian ? 14050000 : 14000000; - const tx = contract.call({ - caller: new Address(ElvenJS.storage.get('address')), - value: TokenTransfer.egldFromAmount(0.01), - func: new ContractFunction("mint"), - gasLimit, - args: [new U32Value(1)], - chainID: "D" - }) + const factory = new SmartContractTransactionsFactory({ + config: new TransactionsFactoryConfig({ chainID: 'D' }), + }); + + const tx = factory.createTransactionForExecute({ + sender: new Address(ElvenJS.storage.get('address')), + contract: new Address(contractAddress), + function: 'mint', + nativeTransferAmount: parseAmount({ amount: '0.01', decimals: 18 }), + gasLimit: BigInt(gasLimit), + arguments: [new U32Value(1)], + }); + try { await ElvenJS.signAndSendTransaction(tx); } catch (e) { @@ -379,7 +386,7 @@

Other demos:

try { await ElvenJS.queryContract({ address: new Address(nftMinterSmartContract), - func: new ContractFunction('getMintedPerAddressTotal'), + func: 'getMintedPerAddressTotal', args: [new AddressValue(new Address(ElvenJS.storage.get('address')))] }); } catch (e) { diff --git a/package-lock.json b/package-lock.json index 9ef693e..a56bc3b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,34 +1,35 @@ { "name": "elven.js", - "version": "0.17.0", + "version": "0.18.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "elven.js", - "version": "0.17.0", + "version": "0.18.0", "license": "MIT", "devDependencies": { - "@multiversx/sdk-core": "12.18.0", + "@multiversx/sdk-core": "13.1.0", "@multiversx/sdk-extension-provider": "3.0.0", - "@multiversx/sdk-native-auth-client": "1.0.7", - "@multiversx/sdk-network-providers": "2.2.1", - "@multiversx/sdk-wallet-connect-provider": "4.1.0", - "@multiversx/sdk-web-wallet-provider": "3.2.0", + "@multiversx/sdk-native-auth-client": "1.0.8", + "@multiversx/sdk-network-providers": "2.4.3", + "@multiversx/sdk-wallet-connect-provider": "4.1.2", + "@multiversx/sdk-web-wallet-provider": "3.2.1", "@types/qrcode": "1.5.5", "@types/serve-handler": "6.1.4", - "@typescript-eslint/eslint-plugin": "6.20.0", - "@typescript-eslint/parser": "6.20.0", - "esbuild": "0.20.0", - "eslint": "8.56.0", + "@typescript-eslint/eslint-plugin": "7.7.0", + "@typescript-eslint/parser": "7.7.0", + "bignumber.js": "^9.1.2", + "esbuild": "0.20.2", + "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", "eslint-plugin-prettier": "5.1.3", "node-stdlib-browser": "1.2.0", - "prettier": "3.2.4", + "prettier": "3.2.5", "qrcode": "1.5.3", "rimraf": "5.0.5", "serve-handler": "6.1.5", - "typescript": "5.3.3" + "typescript": "5.4.5" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -41,9 +42,9 @@ } }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.0.tgz", - "integrity": "sha512-fGFDEctNh0CcSwsiRPxiaqX0P5rq+AqE0SRhYGZ4PX46Lg1FNR6oCxJghf8YgY0WQEgQuh3lErUFE4KxLeRmmw==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz", + "integrity": "sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==", "cpu": [ "ppc64" ], @@ -57,9 +58,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.20.0.tgz", - "integrity": "sha512-3bMAfInvByLHfJwYPJRlpTeaQA75n8C/QKpEaiS4HrFWFiJlNI0vzq/zCjBrhAYcPyVPG7Eo9dMrcQXuqmNk5g==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.20.2.tgz", + "integrity": "sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==", "cpu": [ "arm" ], @@ -73,9 +74,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.20.0.tgz", - "integrity": "sha512-aVpnM4lURNkp0D3qPoAzSG92VXStYmoVPOgXveAUoQBWRSuQzt51yvSju29J6AHPmwY1BjH49uR29oyfH1ra8Q==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.20.2.tgz", + "integrity": "sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==", "cpu": [ "arm64" ], @@ -89,9 +90,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.20.0.tgz", - "integrity": "sha512-uK7wAnlRvjkCPzh8jJ+QejFyrP8ObKuR5cBIsQZ+qbMunwR8sbd8krmMbxTLSrDhiPZaJYKQAU5Y3iMDcZPhyQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.20.2.tgz", + "integrity": "sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==", "cpu": [ "x64" ], @@ -105,9 +106,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.20.0.tgz", - "integrity": "sha512-AjEcivGAlPs3UAcJedMa9qYg9eSfU6FnGHJjT8s346HSKkrcWlYezGE8VaO2xKfvvlZkgAhyvl06OJOxiMgOYQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.20.2.tgz", + "integrity": "sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==", "cpu": [ "arm64" ], @@ -121,9 +122,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.20.0.tgz", - "integrity": "sha512-bsgTPoyYDnPv8ER0HqnJggXK6RyFy4PH4rtsId0V7Efa90u2+EifxytE9pZnsDgExgkARy24WUQGv9irVbTvIw==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.20.2.tgz", + "integrity": "sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==", "cpu": [ "x64" ], @@ -137,9 +138,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.0.tgz", - "integrity": "sha512-kQ7jYdlKS335mpGbMW5tEe3IrQFIok9r84EM3PXB8qBFJPSc6dpWfrtsC/y1pyrz82xfUIn5ZrnSHQQsd6jebQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.2.tgz", + "integrity": "sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==", "cpu": [ "arm64" ], @@ -153,9 +154,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.20.0.tgz", - "integrity": "sha512-uG8B0WSepMRsBNVXAQcHf9+Ko/Tr+XqmK7Ptel9HVmnykupXdS4J7ovSQUIi0tQGIndhbqWLaIL/qO/cWhXKyQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.20.2.tgz", + "integrity": "sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==", "cpu": [ "x64" ], @@ -169,9 +170,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.20.0.tgz", - "integrity": "sha512-2ezuhdiZw8vuHf1HKSf4TIk80naTbP9At7sOqZmdVwvvMyuoDiZB49YZKLsLOfKIr77+I40dWpHVeY5JHpIEIg==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.20.2.tgz", + "integrity": "sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==", "cpu": [ "arm" ], @@ -185,9 +186,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.20.0.tgz", - "integrity": "sha512-uTtyYAP5veqi2z9b6Gr0NUoNv9F/rOzI8tOD5jKcCvRUn7T60Bb+42NDBCWNhMjkQzI0qqwXkQGo1SY41G52nw==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.20.2.tgz", + "integrity": "sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==", "cpu": [ "arm64" ], @@ -201,9 +202,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.20.0.tgz", - "integrity": "sha512-c88wwtfs8tTffPaoJ+SQn3y+lKtgTzyjkD8NgsyCtCmtoIC8RDL7PrJU05an/e9VuAke6eJqGkoMhJK1RY6z4w==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.20.2.tgz", + "integrity": "sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==", "cpu": [ "ia32" ], @@ -217,9 +218,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.20.0.tgz", - "integrity": "sha512-lR2rr/128/6svngnVta6JN4gxSXle/yZEZL3o4XZ6esOqhyR4wsKyfu6qXAL04S4S5CgGfG+GYZnjFd4YiG3Aw==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.20.2.tgz", + "integrity": "sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==", "cpu": [ "loong64" ], @@ -233,9 +234,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.20.0.tgz", - "integrity": "sha512-9Sycc+1uUsDnJCelDf6ZNqgZQoK1mJvFtqf2MUz4ujTxGhvCWw+4chYfDLPepMEvVL9PDwn6HrXad5yOrNzIsQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.20.2.tgz", + "integrity": "sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==", "cpu": [ "mips64el" ], @@ -249,9 +250,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.20.0.tgz", - "integrity": "sha512-CoWSaaAXOZd+CjbUTdXIJE/t7Oz+4g90A3VBCHLbfuc5yUQU/nFDLOzQsN0cdxgXd97lYW/psIIBdjzQIwTBGw==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.20.2.tgz", + "integrity": "sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==", "cpu": [ "ppc64" ], @@ -265,9 +266,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.20.0.tgz", - "integrity": "sha512-mlb1hg/eYRJUpv8h/x+4ShgoNLL8wgZ64SUr26KwglTYnwAWjkhR2GpoKftDbPOCnodA9t4Y/b68H4J9XmmPzA==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.20.2.tgz", + "integrity": "sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==", "cpu": [ "riscv64" ], @@ -281,9 +282,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.20.0.tgz", - "integrity": "sha512-fgf9ubb53xSnOBqyvWEY6ukBNRl1mVX1srPNu06B6mNsNK20JfH6xV6jECzrQ69/VMiTLvHMicQR/PgTOgqJUQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.20.2.tgz", + "integrity": "sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==", "cpu": [ "s390x" ], @@ -297,9 +298,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.20.0.tgz", - "integrity": "sha512-H9Eu6MGse++204XZcYsse1yFHmRXEWgadk2N58O/xd50P9EvFMLJTQLg+lB4E1cF2xhLZU5luSWtGTb0l9UeSg==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.20.2.tgz", + "integrity": "sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==", "cpu": [ "x64" ], @@ -313,9 +314,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.20.0.tgz", - "integrity": "sha512-lCT675rTN1v8Fo+RGrE5KjSnfY0x9Og4RN7t7lVrN3vMSjy34/+3na0q7RIfWDAj0e0rCh0OL+P88lu3Rt21MQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.20.2.tgz", + "integrity": "sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==", "cpu": [ "x64" ], @@ -329,9 +330,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.20.0.tgz", - "integrity": "sha512-HKoUGXz/TOVXKQ+67NhxyHv+aDSZf44QpWLa3I1lLvAwGq8x1k0T+e2HHSRvxWhfJrFxaaqre1+YyzQ99KixoA==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.20.2.tgz", + "integrity": "sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==", "cpu": [ "x64" ], @@ -345,9 +346,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.20.0.tgz", - "integrity": "sha512-GDwAqgHQm1mVoPppGsoq4WJwT3vhnz/2N62CzhvApFD1eJyTroob30FPpOZabN+FgCjhG+AgcZyOPIkR8dfD7g==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.20.2.tgz", + "integrity": "sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==", "cpu": [ "x64" ], @@ -361,9 +362,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.20.0.tgz", - "integrity": "sha512-0vYsP8aC4TvMlOQYozoksiaxjlvUcQrac+muDqj1Fxy6jh9l9CZJzj7zmh8JGfiV49cYLTorFLxg7593pGldwQ==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.20.2.tgz", + "integrity": "sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==", "cpu": [ "arm64" ], @@ -377,9 +378,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.20.0.tgz", - "integrity": "sha512-p98u4rIgfh4gdpV00IqknBD5pC84LCub+4a3MO+zjqvU5MVXOc3hqR2UgT2jI2nh3h8s9EQxmOsVI3tyzv1iFg==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.20.2.tgz", + "integrity": "sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==", "cpu": [ "ia32" ], @@ -393,9 +394,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.20.0.tgz", - "integrity": "sha512-NgJnesu1RtWihtTtXGFMU5YSE6JyyHPMxCwBZK7a6/8d31GuSo9l0Ss7w1Jw5QnKUawG6UEehs883kcXf5fYwg==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.20.2.tgz", + "integrity": "sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==", "cpu": [ "x64" ], @@ -478,9 +479,9 @@ } }, "node_modules/@eslint/js": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.56.0.tgz", - "integrity": "sha512-gMsVel9D7f2HLkBma9VbtzZRehRogVRfbr++f06nL2vnCGCNlzOD+/MUov/F4p8myyAHspEhVobgjpX64q5m6A==", + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", + "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -541,12 +542,6 @@ "integrity": "sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw==", "dev": true }, - "node_modules/@ioredis/commands": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.2.0.tgz", - "integrity": "sha512-Sx1pU8EM64o2BrqNpEO1CNLtKQwyhuXuqyfH7oGKCk+1a33d2r5saW8zNwm3j6BTExtjrv2BxTgzzkMwts6vGg==", - "dev": true - }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -592,19 +587,21 @@ } }, "node_modules/@multiversx/sdk-core": { - "version": "12.18.0", - "resolved": "https://registry.npmjs.org/@multiversx/sdk-core/-/sdk-core-12.18.0.tgz", - "integrity": "sha512-F+xGslPMkkZ0S/Q8UJZsMYl0mgHIuK/GdVsNFPiMKxQsKkxA2LTjNdPxVxjwgvRmN7WfdsTtQvmlsA5O1NYhBg==", + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/@multiversx/sdk-core/-/sdk-core-13.1.0.tgz", + "integrity": "sha512-Z8lDPX4mKKD0QUtAqRzM0bf8zex3xCWRd5yYRLCxjW1F+jYg+9LjIQjkyvDSWGYJHY4IJeYqkORoS3gQG8NDbA==", "dev": true, "dependencies": { "@multiversx/sdk-transaction-decoder": "1.0.2", "bech32": "1.1.4", - "bignumber.js": "9.0.1", "blake2b": "2.1.3", "buffer": "6.0.3", - "json-duplicate-key-handle": "1.0.0", - "keccak": "3.0.2", - "protobufjs": "7.2.4" + "json-bigint": "1.0.0", + "keccak": "3.0.2" + }, + "peerDependencies": { + "bignumber.js": "^9.0.1", + "protobufjs": "^7.2.6" } }, "node_modules/@multiversx/sdk-extension-provider": { @@ -617,36 +614,34 @@ } }, "node_modules/@multiversx/sdk-native-auth-client": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@multiversx/sdk-native-auth-client/-/sdk-native-auth-client-1.0.7.tgz", - "integrity": "sha512-Fl/4DcM8tJ4dULIu03lMfi875qatGMe8DLg6HglQRB+2s5YoW3NrWkqKNrIbG0CbYCaCH9Sk5nOZkZse8FwNQg==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@multiversx/sdk-native-auth-client/-/sdk-native-auth-client-1.0.8.tgz", + "integrity": "sha512-anXcQplVp3/m2rBH4oGQZNIhk0m/J45SomubNMCgSzepJ2PU5E5eQLYletvSDObhTGfRnNCF8edAldkDP9a4Kw==", "dev": true, "dependencies": { - "axios": "^1.6.5" + "axios": "^1.6.8" } }, "node_modules/@multiversx/sdk-network-providers": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@multiversx/sdk-network-providers/-/sdk-network-providers-2.2.1.tgz", - "integrity": "sha512-JsGznvyZSIBLpQ9bRjyv0EWfstaqDyFRBzokNZSbwk5z+3LjQFZxPTU3iv95BvW/rPQh8L0zD8Xwjw05pjTLyA==", + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@multiversx/sdk-network-providers/-/sdk-network-providers-2.4.3.tgz", + "integrity": "sha512-tJmJuxU+BjtC2q29PuzQOM4Qr6aiXujKwQXgIAPHTiuNbMc3Yi6Q4B0DC1PfI3iG+M4DONwfXknvM1uwqnY2zA==", "dev": true, "dependencies": { - "axios": "1.6.5", + "axios": "1.6.8", "bech32": "1.1.4", "bignumber.js": "9.0.1", "buffer": "6.0.3", "json-bigint": "1.0.0" } }, - "node_modules/@multiversx/sdk-network-providers/node_modules/axios": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.5.tgz", - "integrity": "sha512-Ii012v05KEVuUoFWmMW/UQv9aRIc3ZwkWDcM+h5Il8izZCtRVpDUfwpoFf7eOtajT3QiGR4yDUx7lPqHJULgbg==", + "node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.1.tgz", + "integrity": "sha512-IdZR9mh6ahOBv/hYGiXyVuyCetmGJhtYkqLBpTStdhEGjegpPlUawydyaF3pbIOFynJTpllEs+NP+CS9jKFLjA==", "dev": true, - "dependencies": { - "follow-redirects": "^1.15.4", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" + "engines": { + "node": "*" } }, "node_modules/@multiversx/sdk-transaction-decoder": { @@ -665,13 +660,13 @@ "dev": true }, "node_modules/@multiversx/sdk-wallet-connect-provider": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@multiversx/sdk-wallet-connect-provider/-/sdk-wallet-connect-provider-4.1.0.tgz", - "integrity": "sha512-gvgZ2q+boliQHRiYDkJ+OOYCbsbrhoavqx01wwECs41EPn7TCIFKVcA5ljtK9OSiX8Htis7ckpTaZFWSr5wkCg==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/@multiversx/sdk-wallet-connect-provider/-/sdk-wallet-connect-provider-4.1.2.tgz", + "integrity": "sha512-zdJna8ZNhEtNQYL4xjoPDbsKlAaruvLdAKVn6sxyyd90ME1+5T5Owp5ITMZdihOLPaGjmvjRKNgy777iADyqTQ==", "dev": true, "dependencies": { - "@walletconnect/sign-client": "2.11.0", - "@walletconnect/utils": "2.11.0", + "@walletconnect/sign-client": "2.12.2", + "@walletconnect/utils": "2.12.2", "bech32": "1.1.4" }, "peerDependencies": { @@ -679,9 +674,9 @@ } }, "node_modules/@multiversx/sdk-web-wallet-provider": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@multiversx/sdk-web-wallet-provider/-/sdk-web-wallet-provider-3.2.0.tgz", - "integrity": "sha512-nY84LTk5TvbSznkWuGLOhccAfRJyftCTnCRTJzMHIc5hGEWK/XkzTZOUIs+5Z7/ZqBTvOnZ+wOlMJdvUDogkEQ==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@multiversx/sdk-web-wallet-provider/-/sdk-web-wallet-provider-3.2.1.tgz", + "integrity": "sha512-f0CHVsBephFhoQtCAx9y2WhiIZEaNgn0oVa+sZNkgILcXU53Gm8Rj8wMfM0SDimHBYcXCcBDedyLCU3MioOjoQ==", "dev": true, "dependencies": { "qs": "6.10.3" @@ -726,11 +721,10 @@ } }, "node_modules/@parcel/watcher": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.4.0.tgz", - "integrity": "sha512-XJLGVL0DEclX5pcWa2N9SX1jCGTDd8l972biNooLFtjneuGqodupPQh6XseXIBBeVIMaaJ7bTcs3qGvXwsp4vg==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.4.1.tgz", + "integrity": "sha512-HNjmfLQEVRZmHRET336f20H/8kOozUGwk7yajvsonjNxbj2wBTK1WsQuHkD5yYh9RxFGL2EyDHryOihOwUoKDA==", "dev": true, - "hasInstallScript": true, "dependencies": { "detect-libc": "^1.0.3", "is-glob": "^4.0.3", @@ -745,24 +739,24 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "@parcel/watcher-android-arm64": "2.4.0", - "@parcel/watcher-darwin-arm64": "2.4.0", - "@parcel/watcher-darwin-x64": "2.4.0", - "@parcel/watcher-freebsd-x64": "2.4.0", - "@parcel/watcher-linux-arm-glibc": "2.4.0", - "@parcel/watcher-linux-arm64-glibc": "2.4.0", - "@parcel/watcher-linux-arm64-musl": "2.4.0", - "@parcel/watcher-linux-x64-glibc": "2.4.0", - "@parcel/watcher-linux-x64-musl": "2.4.0", - "@parcel/watcher-win32-arm64": "2.4.0", - "@parcel/watcher-win32-ia32": "2.4.0", - "@parcel/watcher-win32-x64": "2.4.0" + "@parcel/watcher-android-arm64": "2.4.1", + "@parcel/watcher-darwin-arm64": "2.4.1", + "@parcel/watcher-darwin-x64": "2.4.1", + "@parcel/watcher-freebsd-x64": "2.4.1", + "@parcel/watcher-linux-arm-glibc": "2.4.1", + "@parcel/watcher-linux-arm64-glibc": "2.4.1", + "@parcel/watcher-linux-arm64-musl": "2.4.1", + "@parcel/watcher-linux-x64-glibc": "2.4.1", + "@parcel/watcher-linux-x64-musl": "2.4.1", + "@parcel/watcher-win32-arm64": "2.4.1", + "@parcel/watcher-win32-ia32": "2.4.1", + "@parcel/watcher-win32-x64": "2.4.1" } }, "node_modules/@parcel/watcher-android-arm64": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.4.0.tgz", - "integrity": "sha512-+fPtO/GsbYX1LJnCYCaDVT3EOBjvSFdQN9Mrzh9zWAOOfvidPWyScTrHIZHHfJBvlHzNA0Gy0U3NXFA/M7PHUA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.4.1.tgz", + "integrity": "sha512-LOi/WTbbh3aTn2RYddrO8pnapixAziFl6SMxHM69r3tvdSm94JtCenaKgk1GRg5FJ5wpMCpHeW+7yqPlvZv7kg==", "cpu": [ "arm64" ], @@ -780,9 +774,9 @@ } }, "node_modules/@parcel/watcher-darwin-arm64": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.4.0.tgz", - "integrity": "sha512-T/At5pansFuQ8VJLRx0C6C87cgfqIYhW2N/kBfLCUvDhCah0EnLLwaD/6MW3ux+rpgkpQAnMELOCTKlbwncwiA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.4.1.tgz", + "integrity": "sha512-ln41eihm5YXIY043vBrrHfn94SIBlqOWmoROhsMVTSXGh0QahKGy77tfEywQ7v3NywyxBBkGIfrWRHm0hsKtzA==", "cpu": [ "arm64" ], @@ -800,9 +794,9 @@ } }, "node_modules/@parcel/watcher-darwin-x64": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.4.0.tgz", - "integrity": "sha512-vZMv9jl+szz5YLsSqEGCMSllBl1gU1snfbRL5ysJU03MEa6gkVy9OMcvXV1j4g0++jHEcvzhs3Z3LpeEbVmY6Q==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.4.1.tgz", + "integrity": "sha512-yrw81BRLjjtHyDu7J61oPuSoeYWR3lDElcPGJyOvIXmor6DEo7/G2u1o7I38cwlcoBHQFULqF6nesIX3tsEXMg==", "cpu": [ "x64" ], @@ -820,9 +814,9 @@ } }, "node_modules/@parcel/watcher-freebsd-x64": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.4.0.tgz", - "integrity": "sha512-dHTRMIplPDT1M0+BkXjtMN+qLtqq24sLDUhmU+UxxLP2TEY2k8GIoqIJiVrGWGomdWsy5IO27aDV1vWyQ6gfHA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.4.1.tgz", + "integrity": "sha512-TJa3Pex/gX3CWIx/Co8k+ykNdDCLx+TuZj3f3h7eOjgpdKM+Mnix37RYsYU4LHhiYJz3DK5nFCCra81p6g050w==", "cpu": [ "x64" ], @@ -840,9 +834,9 @@ } }, "node_modules/@parcel/watcher-linux-arm-glibc": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.4.0.tgz", - "integrity": "sha512-9NQXD+qk46RwATNC3/UB7HWurscY18CnAPMTFcI9Y8CTbtm63/eex1SNt+BHFinEQuLBjaZwR2Lp+n7pmEJPpQ==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.4.1.tgz", + "integrity": "sha512-4rVYDlsMEYfa537BRXxJ5UF4ddNwnr2/1O4MHM5PjI9cvV2qymvhwZSFgXqbS8YoTk5i/JR0L0JDs69BUn45YA==", "cpu": [ "arm" ], @@ -860,9 +854,9 @@ } }, "node_modules/@parcel/watcher-linux-arm64-glibc": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.4.0.tgz", - "integrity": "sha512-QuJTAQdsd7PFW9jNGaV9Pw+ZMWV9wKThEzzlY3Lhnnwy7iW23qtQFPql8iEaSFMCVI5StNNmONUopk+MFKpiKg==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.4.1.tgz", + "integrity": "sha512-BJ7mH985OADVLpbrzCLgrJ3TOpiZggE9FMblfO65PlOCdG++xJpKUJ0Aol74ZUIYfb8WsRlUdgrZxKkz3zXWYA==", "cpu": [ "arm64" ], @@ -880,9 +874,9 @@ } }, "node_modules/@parcel/watcher-linux-arm64-musl": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.4.0.tgz", - "integrity": "sha512-oyN+uA9xcTDo/45bwsd6TFHa7Lc7hKujyMlvwrCLvSckvWogndCEoVYFNfZ6JJ2KNL/6fFiGPcbjp8jJmEh5Ng==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.4.1.tgz", + "integrity": "sha512-p4Xb7JGq3MLgAfYhslU2SjoV9G0kI0Xry0kuxeG/41UfpjHGOhv7UoUDAz/jb1u2elbhazy4rRBL8PegPJFBhA==", "cpu": [ "arm64" ], @@ -900,9 +894,9 @@ } }, "node_modules/@parcel/watcher-linux-x64-glibc": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.4.0.tgz", - "integrity": "sha512-KphV8awJmxU3q52JQvJot0QMu07CIyEjV+2Tb2ZtbucEgqyRcxOBDMsqp1JNq5nuDXtcCC0uHQICeiEz38dPBQ==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.4.1.tgz", + "integrity": "sha512-s9O3fByZ/2pyYDPoLM6zt92yu6P4E39a03zvO0qCHOTjxmt3GHRMLuRZEWhWLASTMSrrnVNWdVI/+pUElJBBBg==", "cpu": [ "x64" ], @@ -920,9 +914,9 @@ } }, "node_modules/@parcel/watcher-linux-x64-musl": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.4.0.tgz", - "integrity": "sha512-7jzcOonpXNWcSijPpKD5IbC6xC7yTibjJw9jviVzZostYLGxbz8LDJLUnLzLzhASPlPGgpeKLtFUMjAAzM+gSA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.4.1.tgz", + "integrity": "sha512-L2nZTYR1myLNST0O632g0Dx9LyMNHrn6TOt76sYxWLdff3cB22/GZX2UPtJnaqQPdCRoszoY5rcOj4oMTtp5fQ==", "cpu": [ "x64" ], @@ -940,9 +934,9 @@ } }, "node_modules/@parcel/watcher-wasm": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-wasm/-/watcher-wasm-2.3.0.tgz", - "integrity": "sha512-ejBAX8H0ZGsD8lSICDNyMbSEtPMWgDL0WFCt/0z7hyf5v8Imz4rAM8xY379mBsECkq/Wdqa5WEDLqtjZ+6NxfA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-wasm/-/watcher-wasm-2.4.1.tgz", + "integrity": "sha512-/ZR0RxqxU/xxDGzbzosMjh4W6NdYFMqq2nvo2b8SLi7rsl/4jkL8S5stIikorNkdR50oVDvqb/3JT05WM+CRRA==", "bundleDependencies": [ "napi-wasm" ], @@ -967,9 +961,9 @@ "license": "MIT" }, "node_modules/@parcel/watcher-win32-arm64": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.4.0.tgz", - "integrity": "sha512-NOej2lqlq8bQNYhUMnOD0nwvNql8ToQF+1Zhi9ULZoG+XTtJ9hNnCFfyICxoZLXor4bBPTOnzs/aVVoefYnjIg==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.4.1.tgz", + "integrity": "sha512-Uq2BPp5GWhrq/lcuItCHoqxjULU1QYEcyjSO5jqqOK8RNFDBQnenMMx4gAl3v8GiWa59E9+uDM7yZ6LxwUIfRg==", "cpu": [ "arm64" ], @@ -987,9 +981,9 @@ } }, "node_modules/@parcel/watcher-win32-ia32": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.4.0.tgz", - "integrity": "sha512-IO/nM+K2YD/iwjWAfHFMBPz4Zqn6qBDqZxY4j2n9s+4+OuTSRM/y/irksnuqcspom5DjkSeF9d0YbO+qpys+JA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.4.1.tgz", + "integrity": "sha512-maNRit5QQV2kgHFSYwftmPBxiuK5u4DXjbXx7q6eKjq5dsLXZ4FJiVvlcw35QXzk0KrUecJmuVFbj4uV9oYrcw==", "cpu": [ "ia32" ], @@ -1007,9 +1001,9 @@ } }, "node_modules/@parcel/watcher-win32-x64": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.4.0.tgz", - "integrity": "sha512-pAUyUVjfFjWaf/pShmJpJmNxZhbMvJASUpdes9jL6bTEJ+gDxPRSpXTIemNyNsb9AtbiGXs9XduP1reThmd+dA==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.4.1.tgz", + "integrity": "sha512-+DvS92F9ezicfswqrvIRM2njcYJbd5mb9CUgtrHCHmvn7pPPa+nMDRu1o1bYYz/l5IB2NVGNJWiH7h1E58IF2A==", "cpu": [ "x64" ], @@ -1061,31 +1055,36 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/base64": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/codegen": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/eventemitter": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/fetch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", "dev": true, + "peer": true, "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" @@ -1095,31 +1094,36 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/inquire": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/path": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/pool": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@protobufjs/utf8": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@stablelib/aead": { "version": "1.0.1", @@ -1310,9 +1314,9 @@ } }, "node_modules/@types/semver": { - "version": "7.5.6", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.6.tgz", - "integrity": "sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==", + "version": "7.5.8", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.8.tgz", + "integrity": "sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==", "dev": true }, "node_modules/@types/serve-handler": { @@ -1325,33 +1329,33 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.20.0.tgz", - "integrity": "sha512-fTwGQUnjhoYHeSF6m5pWNkzmDDdsKELYrOBxhjMrofPqCkoC2k3B2wvGHFxa1CTIqkEn88nlW1HVMztjo2K8Hg==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.7.0.tgz", + "integrity": "sha512-GJWR0YnfrKnsRoluVO3PRb9r5aMZriiMMM/RHj5nnTrBy1/wIgk76XCtCKcnXGjpZQJQRFtGV9/0JJ6n30uwpQ==", "dev": true, "dependencies": { - "@eslint-community/regexpp": "^4.5.1", - "@typescript-eslint/scope-manager": "6.20.0", - "@typescript-eslint/type-utils": "6.20.0", - "@typescript-eslint/utils": "6.20.0", - "@typescript-eslint/visitor-keys": "6.20.0", + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "7.7.0", + "@typescript-eslint/type-utils": "7.7.0", + "@typescript-eslint/utils": "7.7.0", + "@typescript-eslint/visitor-keys": "7.7.0", "debug": "^4.3.4", "graphemer": "^1.4.0", - "ignore": "^5.2.4", + "ignore": "^5.3.1", "natural-compare": "^1.4.0", - "semver": "^7.5.4", - "ts-api-utils": "^1.0.1" + "semver": "^7.6.0", + "ts-api-utils": "^1.3.0" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^6.0.0 || ^6.0.0-alpha", - "eslint": "^7.0.0 || ^8.0.0" + "@typescript-eslint/parser": "^7.0.0", + "eslint": "^8.56.0" }, "peerDependenciesMeta": { "typescript": { @@ -1360,26 +1364,26 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.20.0.tgz", - "integrity": "sha512-bYerPDF/H5v6V76MdMYhjwmwgMA+jlPVqjSDq2cRqMi8bP5sR3Z+RLOiOMad3nsnmDVmn2gAFCyNgh/dIrfP/w==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.7.0.tgz", + "integrity": "sha512-fNcDm3wSwVM8QYL4HKVBggdIPAy9Q41vcvC/GtDobw3c4ndVT3K6cqudUmjHPw8EAp4ufax0o58/xvWaP2FmTg==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "6.20.0", - "@typescript-eslint/types": "6.20.0", - "@typescript-eslint/typescript-estree": "6.20.0", - "@typescript-eslint/visitor-keys": "6.20.0", + "@typescript-eslint/scope-manager": "7.7.0", + "@typescript-eslint/types": "7.7.0", + "@typescript-eslint/typescript-estree": "7.7.0", + "@typescript-eslint/visitor-keys": "7.7.0", "debug": "^4.3.4" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^7.0.0 || ^8.0.0" + "eslint": "^8.56.0" }, "peerDependenciesMeta": { "typescript": { @@ -1388,16 +1392,16 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.20.0.tgz", - "integrity": "sha512-p4rvHQRDTI1tGGMDFQm+GtxP1ZHyAh64WANVoyEcNMpaTFn3ox/3CcgtIlELnRfKzSs/DwYlDccJEtr3O6qBvA==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.7.0.tgz", + "integrity": "sha512-/8INDn0YLInbe9Wt7dK4cXLDYp0fNHP5xKLHvZl3mOT5X17rK/YShXaiNmorl+/U4VKCVIjJnx4Ri5b0y+HClw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.20.0", - "@typescript-eslint/visitor-keys": "6.20.0" + "@typescript-eslint/types": "7.7.0", + "@typescript-eslint/visitor-keys": "7.7.0" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", @@ -1405,25 +1409,25 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.20.0.tgz", - "integrity": "sha512-qnSobiJQb1F5JjN0YDRPHruQTrX7ICsmltXhkV536mp4idGAYrIyr47zF/JmkJtEcAVnIz4gUYJ7gOZa6SmN4g==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.7.0.tgz", + "integrity": "sha512-bOp3ejoRYrhAlnT/bozNQi3nio9tIgv3U5C0mVDdZC7cpcQEDZXvq8inrHYghLVwuNABRqrMW5tzAv88Vy77Sg==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "6.20.0", - "@typescript-eslint/utils": "6.20.0", + "@typescript-eslint/typescript-estree": "7.7.0", + "@typescript-eslint/utils": "7.7.0", "debug": "^4.3.4", - "ts-api-utils": "^1.0.1" + "ts-api-utils": "^1.3.0" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^7.0.0 || ^8.0.0" + "eslint": "^8.56.0" }, "peerDependenciesMeta": { "typescript": { @@ -1432,12 +1436,12 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.20.0.tgz", - "integrity": "sha512-MM9mfZMAhiN4cOEcUOEx+0HmuaW3WBfukBZPCfwSqFnQy0grXYtngKCqpQN339X3RrwtzspWJrpbrupKYUSBXQ==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.7.0.tgz", + "integrity": "sha512-G01YPZ1Bd2hn+KPpIbrAhEWOn5lQBrjxkzHkWvP6NucMXFtfXoevK82hzQdpfuQYuhkvFDeQYbzXCjR1z9Z03w==", "dev": true, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", @@ -1445,22 +1449,22 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.20.0.tgz", - "integrity": "sha512-RnRya9q5m6YYSpBN7IzKu9FmLcYtErkDkc8/dKv81I9QiLLtVBHrjz+Ev/crAqgMNW2FCsoZF4g2QUylMnJz+g==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.7.0.tgz", + "integrity": "sha512-8p71HQPE6CbxIBy2kWHqM1KGrC07pk6RJn40n0DSc6bMOBBREZxSDJ+BmRzc8B5OdaMh1ty3mkuWRg4sCFiDQQ==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.20.0", - "@typescript-eslint/visitor-keys": "6.20.0", + "@typescript-eslint/types": "7.7.0", + "@typescript-eslint/visitor-keys": "7.7.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", - "minimatch": "9.0.3", - "semver": "^7.5.4", - "ts-api-utils": "^1.0.1" + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^1.3.0" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", @@ -1473,41 +1477,41 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.20.0.tgz", - "integrity": "sha512-/EKuw+kRu2vAqCoDwDCBtDRU6CTKbUmwwI7SH7AashZ+W+7o8eiyy6V2cdOqN49KsTcASWsC5QeghYuRDTyOOg==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.7.0.tgz", + "integrity": "sha512-LKGAXMPQs8U/zMRFXDZOzmMKgFv3COlxUQ+2NMPhbqgVm6R1w+nU1i4836Pmxu9jZAuIeyySNrN/6Rc657ggig==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", - "@types/json-schema": "^7.0.12", - "@types/semver": "^7.5.0", - "@typescript-eslint/scope-manager": "6.20.0", - "@typescript-eslint/types": "6.20.0", - "@typescript-eslint/typescript-estree": "6.20.0", - "semver": "^7.5.4" + "@types/json-schema": "^7.0.15", + "@types/semver": "^7.5.8", + "@typescript-eslint/scope-manager": "7.7.0", + "@typescript-eslint/types": "7.7.0", + "@typescript-eslint/typescript-estree": "7.7.0", + "semver": "^7.6.0" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^7.0.0 || ^8.0.0" + "eslint": "^8.56.0" } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.20.0.tgz", - "integrity": "sha512-E8Cp98kRe4gKHjJD4NExXKz/zOJ1A2hhZc+IMVD6i7w4yjIvh6VyuRI0gRtxAsXtoC35uGMaQ9rjI2zJaXDEAw==", + "version": "7.7.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.7.0.tgz", + "integrity": "sha512-h0WHOj8MhdhY8YWkzIF30R379y0NqyOHExI9N9KCzvmu05EgG4FumeYa3ccfKUSphyWkWQE1ybVrgz/Pbam6YA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.20.0", - "eslint-visitor-keys": "^3.4.1" + "@typescript-eslint/types": "7.7.0", + "eslint-visitor-keys": "^3.4.3" }, "engines": { - "node": "^16.0.0 || >=18.0.0" + "node": "^18.18.0 || >=20.0.0" }, "funding": { "type": "opencollective", @@ -1521,9 +1525,9 @@ "dev": true }, "node_modules/@walletconnect/core": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.11.0.tgz", - "integrity": "sha512-2Tjp5BCevI7dbmqo/OrCjX4tqgMqwJNQLlQAlphqPfvwlF9+tIu6pGcVbSN3U9zyXzWIZCeleqEaWUeSeET4Ew==", + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.12.2.tgz", + "integrity": "sha512-7Adv/b3pp9F42BkvReaaM4KS8NEvlkS7AMtwO3uF/o6aRMKtcfTJq9/jgWdKJh4RP8pPRTRFjCw6XQ/RZtT4aQ==", "dev": true, "dependencies": { "@walletconnect/heartbeat": "1.2.1", @@ -1532,13 +1536,13 @@ "@walletconnect/jsonrpc-utils": "1.0.8", "@walletconnect/jsonrpc-ws-connection": "1.0.14", "@walletconnect/keyvaluestorage": "^1.1.1", - "@walletconnect/logger": "^2.0.1", + "@walletconnect/logger": "^2.1.2", "@walletconnect/relay-api": "^1.0.9", "@walletconnect/relay-auth": "^1.0.4", "@walletconnect/safe-json": "^1.0.2", "@walletconnect/time": "^1.0.2", - "@walletconnect/types": "2.11.0", - "@walletconnect/utils": "2.11.0", + "@walletconnect/types": "2.12.2", + "@walletconnect/utils": "2.12.2", "events": "^3.3.0", "isomorphic-unfetch": "3.1.0", "lodash.isequal": "4.5.0", @@ -1639,23 +1643,22 @@ } }, "node_modules/@walletconnect/logger": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@walletconnect/logger/-/logger-2.0.1.tgz", - "integrity": "sha512-SsTKdsgWm+oDTBeNE/zHxxr5eJfZmE9/5yp/Ku+zJtcTAjELb3DXueWkDXmE9h8uHIbJzIb5wj5lPdzyrjT6hQ==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@walletconnect/logger/-/logger-2.1.2.tgz", + "integrity": "sha512-aAb28I3S6pYXZHQm5ESB+V6rDqIYfsnHaQyzFbwUUBFY4H0OXx/YtTl8lvhUNhMMfb9UxbwEBS253TlXUYJWSw==", "dev": true, "dependencies": { - "pino": "7.11.0", - "tslib": "1.14.1" + "@walletconnect/safe-json": "^1.0.2", + "pino": "7.11.0" } }, "node_modules/@walletconnect/relay-api": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@walletconnect/relay-api/-/relay-api-1.0.9.tgz", - "integrity": "sha512-Q3+rylJOqRkO1D9Su0DPE3mmznbAalYapJ9qmzDgK28mYF9alcP3UwG/og5V7l7CFOqzCLi7B8BvcBUrpDj0Rg==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@walletconnect/relay-api/-/relay-api-1.0.10.tgz", + "integrity": "sha512-tqrdd4zU9VBNqUaXXQASaexklv6A54yEyQQEXYOCr+Jz8Ket0dmPBDyg19LVSNUN2cipAghQc45/KVmfFJ0cYw==", "dev": true, "dependencies": { - "@walletconnect/jsonrpc-types": "^1.0.2", - "tslib": "1.14.1" + "@walletconnect/jsonrpc-types": "^1.0.2" } }, "node_modules/@walletconnect/relay-auth": { @@ -1682,19 +1685,19 @@ } }, "node_modules/@walletconnect/sign-client": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.11.0.tgz", - "integrity": "sha512-H2ukscibBS+6WrzQWh+WyVBqO5z4F5et12JcwobdwgHnJSlqIoZxqnUYYWNCI5rUR5UKsKWaUyto4AE9N5dw4Q==", + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.12.2.tgz", + "integrity": "sha512-cM0ualXj6nVvLqS4BDNRk+ZWR+lubcsz/IHreH+3wYrQ2sV+C0fN6ctrd7MMGZss0C0qacWCx0pm62ZBuoKvqA==", "dev": true, "dependencies": { - "@walletconnect/core": "2.11.0", + "@walletconnect/core": "2.12.2", "@walletconnect/events": "^1.0.1", "@walletconnect/heartbeat": "1.2.1", "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/logger": "^2.0.1", + "@walletconnect/logger": "^2.1.2", "@walletconnect/time": "^1.0.2", - "@walletconnect/types": "2.11.0", - "@walletconnect/utils": "2.11.0", + "@walletconnect/types": "2.12.2", + "@walletconnect/utils": "2.12.2", "events": "^3.3.0" } }, @@ -1708,9 +1711,9 @@ } }, "node_modules/@walletconnect/types": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.11.0.tgz", - "integrity": "sha512-AB5b1lrEbCGHxqS2vqfCkIoODieH+ZAUp9rA1O2ftrhnqDJiJK983Df87JhYhECsQUBHHfALphA8ydER0q+9sw==", + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.12.2.tgz", + "integrity": "sha512-9CmwTlPbrFTzayTL9q7xM7s3KTJkS6kYFtH2m1/fHFgALs6pIUjf1qAx1TF2E4tv7SEzLAIzU4NqgYUt2vWXTg==", "dev": true, "dependencies": { "@walletconnect/events": "^1.0.1", @@ -1722,9 +1725,9 @@ } }, "node_modules/@walletconnect/utils": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.11.0.tgz", - "integrity": "sha512-hxkHPlTlDQILHfIKXlmzgNJau/YcSBC3XHUSuZuKZbNEw3duFT6h6pm3HT/1+j1a22IG05WDsNBuTCRkwss+BQ==", + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.12.2.tgz", + "integrity": "sha512-zf50HeS3SfoLv1N9GPl2IXTZ9TsXfet4usVAsZmX9P6/Xzq7d/7QakjVQCHH/Wk1O9XkcsfeoZoUhRxoMJ5uJw==", "dev": true, "dependencies": { "@stablelib/chacha20poly1305": "1.0.1", @@ -1735,7 +1738,7 @@ "@walletconnect/relay-api": "^1.0.9", "@walletconnect/safe-json": "^1.0.2", "@walletconnect/time": "^1.0.2", - "@walletconnect/types": "2.11.0", + "@walletconnect/types": "2.12.2", "@walletconnect/window-getters": "^1.0.1", "@walletconnect/window-metadata": "^1.0.1", "detect-browser": "5.3.0", @@ -1910,22 +1913,16 @@ } }, "node_modules/axios": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", - "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", + "version": "1.6.8", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz", + "integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==", "dev": true, "dependencies": { - "follow-redirects": "^1.15.4", + "follow-redirects": "^1.15.6", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } }, - "node_modules/backslash": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/backslash/-/backslash-0.2.0.tgz", - "integrity": "sha512-Avs+8FUZ1HF/VFP4YWwHQZSGzRPm37ukU1JQYQWijuHhtXdOuAzcZ8PcAzfIw898a8PyBzdn+RtnKA6MzW0X2A==", - "dev": true - }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1959,21 +1956,24 @@ "dev": true }, "node_modules/bignumber.js": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.1.tgz", - "integrity": "sha512-IdZR9mh6ahOBv/hYGiXyVuyCetmGJhtYkqLBpTStdhEGjegpPlUawydyaF3pbIOFynJTpllEs+NP+CS9jKFLjA==", + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.1.2.tgz", + "integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==", "dev": true, "engines": { "node": "*" } }, "node_modules/binary-extensions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", "dev": true, "engines": { "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/blake2b": { @@ -2207,16 +2207,10 @@ } }, "node_modules/chokidar": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ], "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -2229,6 +2223,9 @@ "engines": { "node": ">= 8.10.0" }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, "optionalDependencies": { "fsevents": "~2.3.2" } @@ -2256,9 +2253,9 @@ } }, "node_modules/citty": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.5.tgz", - "integrity": "sha512-AS7n5NSc0OQVMV9v6wt3ByujNIrne0/cTjiC2MYqhvao57VNfiuVksTSr2p17nVOhEr2KtqiAkGwHcgMC/qUuQ==", + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz", + "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==", "dev": true, "dependencies": { "consola": "^3.2.3" @@ -2326,15 +2323,6 @@ "node": ">=8" } }, - "node_modules/cluster-key-slot": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", - "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -2371,6 +2359,12 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true }, + "node_modules/confbox": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.7.tgz", + "integrity": "sha512-uJcB/FKZtBMCJpK8MQji6bJHgu1tixKPxRLeGkNzBoOZzpnZUJm0jm2/sBDWcuBx1dYgxV4JU+g5hmNxCyAmdA==", + "dev": true + }, "node_modules/consola": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/consola/-/consola-3.2.3.tgz", @@ -2402,9 +2396,9 @@ } }, "node_modules/cookie-es": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-1.0.0.tgz", - "integrity": "sha512-mWYvfOLrfEc996hlKcdABeIiPHUPC6DM2QYZdGGOvhOTbA3tjm2eBwqlJpoFdjC89NI4Qt6h0Pu06Mp+1Pj5OQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-1.1.0.tgz", + "integrity": "sha512-L2rLOcK0wzWSfSDA33YR+PUHDG10a8px7rUHKWbGLP4YfbsMed2KFUw5fczvDPbT98DDe3LEzviswl810apTEw==", "dev": true }, "node_modules/create-ecdh": { @@ -2470,6 +2464,20 @@ "node": ">= 8" } }, + "node_modules/crossws": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/crossws/-/crossws-0.2.4.tgz", + "integrity": "sha512-DAxroI2uSOgUKLz00NX6A8U/8EE3SZHmIND+10jkVSaypvyt57J5JEOxAQOL6lQxyzi/wZbTIwssU1uy69h5Vg==", + "dev": true, + "peerDependencies": { + "uWebSockets.js": "*" + }, + "peerDependenciesMeta": { + "uWebSockets.js": { + "optional": true + } + } + }, "node_modules/crypto-browserify": { "version": "3.12.0", "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", @@ -2579,15 +2587,6 @@ "node": ">=0.4.0" } }, - "node_modules/denque": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", - "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", - "dev": true, - "engines": { - "node": ">=0.10" - } - }, "node_modules/des.js": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.1.0.tgz", @@ -2599,9 +2598,9 @@ } }, "node_modules/destr": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.2.tgz", - "integrity": "sha512-65AlobnZMiCET00KaFFjUefxDX0khFA/E4myqZ7a6Sq1yZtR8+FVIvilVX66vF2uobSumxooYZChiRPCKNqhmg==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.3.tgz", + "integrity": "sha512-2N3BOUU4gYMpTP24s5rF5iP7BDr7uNTCs4ozw3kf/eKfvWSIu93GEBi5m427YoyJoeOzQ5smuu4nNAPGb8idSQ==", "dev": true }, "node_modules/detect-browser": { @@ -2682,15 +2681,15 @@ } }, "node_modules/duplexify": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.2.tgz", - "integrity": "sha512-fz3OjcNCHmRP12MJoZMPglx8m4rrFP8rovnk4vT8Fs+aonZoCwGg10dSsQsfP/E62eZcPTMSMP6686fu9Qlqtw==", + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz", + "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==", "dev": true, "dependencies": { "end-of-stream": "^1.4.1", "inherits": "^2.0.3", "readable-stream": "^3.1.1", - "stream-shift": "^1.0.0" + "stream-shift": "^1.0.2" } }, "node_modules/eastasianwidth": { @@ -2742,9 +2741,9 @@ } }, "node_modules/esbuild": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.0.tgz", - "integrity": "sha512-6iwE3Y2RVYCME1jLpBqq7LQWK3MW6vjV2bZy6gt/WrqkY+WE74Spyc0ThAOYpMtITvnjX09CrC6ym7A/m9mebA==", + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.2.tgz", + "integrity": "sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==", "dev": true, "hasInstallScript": true, "bin": { @@ -2754,29 +2753,29 @@ "node": ">=12" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.20.0", - "@esbuild/android-arm": "0.20.0", - "@esbuild/android-arm64": "0.20.0", - "@esbuild/android-x64": "0.20.0", - "@esbuild/darwin-arm64": "0.20.0", - "@esbuild/darwin-x64": "0.20.0", - "@esbuild/freebsd-arm64": "0.20.0", - "@esbuild/freebsd-x64": "0.20.0", - "@esbuild/linux-arm": "0.20.0", - "@esbuild/linux-arm64": "0.20.0", - "@esbuild/linux-ia32": "0.20.0", - "@esbuild/linux-loong64": "0.20.0", - "@esbuild/linux-mips64el": "0.20.0", - "@esbuild/linux-ppc64": "0.20.0", - "@esbuild/linux-riscv64": "0.20.0", - "@esbuild/linux-s390x": "0.20.0", - "@esbuild/linux-x64": "0.20.0", - "@esbuild/netbsd-x64": "0.20.0", - "@esbuild/openbsd-x64": "0.20.0", - "@esbuild/sunos-x64": "0.20.0", - "@esbuild/win32-arm64": "0.20.0", - "@esbuild/win32-ia32": "0.20.0", - "@esbuild/win32-x64": "0.20.0" + "@esbuild/aix-ppc64": "0.20.2", + "@esbuild/android-arm": "0.20.2", + "@esbuild/android-arm64": "0.20.2", + "@esbuild/android-x64": "0.20.2", + "@esbuild/darwin-arm64": "0.20.2", + "@esbuild/darwin-x64": "0.20.2", + "@esbuild/freebsd-arm64": "0.20.2", + "@esbuild/freebsd-x64": "0.20.2", + "@esbuild/linux-arm": "0.20.2", + "@esbuild/linux-arm64": "0.20.2", + "@esbuild/linux-ia32": "0.20.2", + "@esbuild/linux-loong64": "0.20.2", + "@esbuild/linux-mips64el": "0.20.2", + "@esbuild/linux-ppc64": "0.20.2", + "@esbuild/linux-riscv64": "0.20.2", + "@esbuild/linux-s390x": "0.20.2", + "@esbuild/linux-x64": "0.20.2", + "@esbuild/netbsd-x64": "0.20.2", + "@esbuild/openbsd-x64": "0.20.2", + "@esbuild/sunos-x64": "0.20.2", + "@esbuild/win32-arm64": "0.20.2", + "@esbuild/win32-ia32": "0.20.2", + "@esbuild/win32-x64": "0.20.2" } }, "node_modules/escape-string-regexp": { @@ -2792,16 +2791,16 @@ } }, "node_modules/eslint": { - "version": "8.56.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz", - "integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==", + "version": "8.57.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", + "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.56.0", - "@humanwhocodes/config-array": "^0.11.13", + "@eslint/js": "8.57.0", + "@humanwhocodes/config-array": "^0.11.14", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", "@ungap/structured-clone": "^1.2.0", @@ -3092,9 +3091,9 @@ "dev": true }, "node_modules/fast-redact": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.3.0.tgz", - "integrity": "sha512-6T5V1QK1u4oF+ATxs1lWUmlEk6P2T9HqJG3e2DnHOdVgZy2rFJBoEnrIedcTXlkAHU/zKC+7KETJ+KGGKwxgMQ==", + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz", + "integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==", "dev": true, "engines": { "node": ">=6" @@ -3245,9 +3244,9 @@ "dev": true }, "node_modules/follow-redirects": { - "version": "1.15.5", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", - "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "version": "1.15.6", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz", + "integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==", "dev": true, "funding": [ { @@ -3462,18 +3461,19 @@ "dev": true }, "node_modules/h3": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/h3/-/h3-1.10.1.tgz", - "integrity": "sha512-UBAUp47hmm4BB5/njB4LrEa9gpuvZj4/Qf/ynSMzO6Ku2RXaouxEfiG2E2IFnv6fxbhAkzjasDxmo6DFdEeXRg==", + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/h3/-/h3-1.11.1.tgz", + "integrity": "sha512-AbaH6IDnZN6nmbnJOH72y3c5Wwh9P97soSVdGSBbcDACRdkC0FEWf25pzx4f/NuOCK6quHmW18yF2Wx+G4Zi1A==", "dev": true, "dependencies": { "cookie-es": "^1.0.0", + "crossws": "^0.2.2", "defu": "^6.1.4", - "destr": "^2.0.2", + "destr": "^2.0.3", "iron-webcrypto": "^1.0.0", "ohash": "^1.1.3", "radix3": "^1.1.0", - "ufo": "^1.3.2", + "ufo": "^1.4.0", "uncrypto": "^0.1.3", "unenv": "^1.9.0" } @@ -3637,9 +3637,9 @@ ] }, "node_modules/ignore": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz", - "integrity": "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz", + "integrity": "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==", "dev": true, "engines": { "node": ">= 4" @@ -3686,34 +3686,10 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, - "node_modules/ioredis": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.3.2.tgz", - "integrity": "sha512-1DKMMzlIHM02eBBVOFQ1+AolGjs6+xEcM4PDL7NqOS6szq7H9jSaEkIUH6/a5Hl241LzW6JLSiAbNvTQjUupUA==", - "dev": true, - "dependencies": { - "@ioredis/commands": "^1.1.1", - "cluster-key-slot": "^1.1.0", - "debug": "^4.3.4", - "denque": "^2.1.0", - "lodash.defaults": "^4.2.0", - "lodash.isarguments": "^3.1.0", - "redis-errors": "^1.2.0", - "redis-parser": "^3.0.0", - "standard-as-callback": "^2.1.0" - }, - "engines": { - "node": ">=12.22.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/ioredis" - } - }, "node_modules/iron-webcrypto": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.0.0.tgz", - "integrity": "sha512-anOK1Mktt8U1Xi7fCM3RELTuYbnFikQY5VtrDj7kPgpejV7d43tWKhzgioO0zpkazLEL/j/iayRqnJhrGfqUsg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.1.1.tgz", + "integrity": "sha512-5xGwQUWHQSy039rFr+5q/zOmj7GP0Ypzvo34Ep+61bPIhaLduEDp/PvLGlU3awD2mzWUR0weN2vJ1mILydFPEg==", "dev": true, "funding": { "url": "https://github.com/sponsors/brc-dd" @@ -4019,15 +3995,6 @@ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", "dev": true }, - "node_modules/json-duplicate-key-handle": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-duplicate-key-handle/-/json-duplicate-key-handle-1.0.0.tgz", - "integrity": "sha512-OLIxL+UpfwUsqcLX3i6Z51ChTou/Vje+6bSeGUSubj96dF/SfjObDprLy++ZXYH07KITuEzsXS7PX7e/BGf4jw==", - "dev": true, - "dependencies": { - "backslash": "^0.2.0" - } - }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -4040,12 +4007,6 @@ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", "dev": true }, - "node_modules/jsonc-parser": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.1.tgz", - "integrity": "sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA==", - "dev": true - }, "node_modules/keccak": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/keccak/-/keccak-3.0.2.tgz", @@ -4090,26 +4051,27 @@ } }, "node_modules/listhen": { - "version": "1.5.6", - "resolved": "https://registry.npmjs.org/listhen/-/listhen-1.5.6.tgz", - "integrity": "sha512-gTpEJhT5L85L0bFgmu+Boqu5rP4DwDtEb4Exq5gdQUxWRwx4jbzdInZkmyLONo5EwIcQB0k7ZpWlpCDPdL77EQ==", + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/listhen/-/listhen-1.7.2.tgz", + "integrity": "sha512-7/HamOm5YD9Wb7CFgAZkKgVPA96WwhcTQoqtm2VTZGVbVVn3IWKRBTgrU7cchA3Q8k9iCsG8Osoi9GX4JsGM9g==", "dev": true, "dependencies": { - "@parcel/watcher": "^2.3.0", - "@parcel/watcher-wasm": "2.3.0", - "citty": "^0.1.5", + "@parcel/watcher": "^2.4.1", + "@parcel/watcher-wasm": "^2.4.1", + "citty": "^0.1.6", "clipboardy": "^4.0.0", "consola": "^3.2.3", + "crossws": "^0.2.0", "defu": "^6.1.4", "get-port-please": "^3.1.2", - "h3": "^1.10.0", + "h3": "^1.10.2", "http-shutdown": "^1.2.2", "jiti": "^1.21.0", - "mlly": "^1.4.2", + "mlly": "^1.6.1", "node-forge": "^1.3.1", - "pathe": "^1.1.1", + "pathe": "^1.1.2", "std-env": "^3.7.0", - "ufo": "^1.3.2", + "ufo": "^1.4.0", "untun": "^0.1.3", "uqr": "^0.1.2" }, @@ -4133,18 +4095,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash.defaults": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", - "dev": true - }, - "node_modules/lodash.isarguments": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", - "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", - "dev": true - }, "node_modules/lodash.isequal": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", @@ -4161,7 +4111,8 @@ "version": "5.2.3", "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==", - "dev": true + "dev": true, + "peer": true }, "node_modules/lru-cache": { "version": "10.2.0", @@ -4288,9 +4239,9 @@ "dev": true }, "node_modules/minimatch": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", - "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", + "version": "9.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.4.tgz", + "integrity": "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw==", "dev": true, "dependencies": { "brace-expansion": "^2.0.1" @@ -4312,9 +4263,9 @@ } }, "node_modules/mlly": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.5.0.tgz", - "integrity": "sha512-NPVQvAY1xr1QoVeG0cy8yUYC7FQcOx6evl/RjT1wL5FvzPnzOysoqB/jmx/DhssT2dYa8nxECLAaFI/+gVLhDQ==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.6.1.tgz", + "integrity": "sha512-vLgaHvaeunuOXHSmEbZ9izxPx3USsk8KCQ8iC+aTlp5sKRSoZvwhHh5L9VbKSaVC6sJDqbyohIS76E2VmHIPAA==", "dev": true, "dependencies": { "acorn": "^8.11.3", @@ -4383,9 +4334,9 @@ } }, "node_modules/node-fetch-native": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.1.tgz", - "integrity": "sha512-bW9T/uJDPAJB2YNYEpWzE54U5O3MQidXsOyTfnbKYtTtFexRvGzb1waphBN4ZwP6EcIvYYEOwW0b72BpAqydTw==", + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.4.tgz", + "integrity": "sha512-IhOigYzAKHd244OC0JIMIUrjzctirCmPkaIfhDeGcEETWof5zKYUW7e7MYvChGWh/4CJeXEgsRyGzuF334rOOQ==", "dev": true }, "node_modules/node-forge": { @@ -4480,9 +4431,9 @@ } }, "node_modules/npm-run-path": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.2.0.tgz", - "integrity": "sha512-W4/tgAXFqFA0iL7fk0+uQ3g7wkL8xJmx3XdK0VGb4cHW//eZTtKGvFBBoRKVTpY7n6ze4NL9ly7rgXcHufqXKg==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", "dev": true, "dependencies": { "path-key": "^4.0.0" @@ -4559,14 +4510,14 @@ } }, "node_modules/ofetch": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/ofetch/-/ofetch-1.3.3.tgz", - "integrity": "sha512-s1ZCMmQWXy4b5K/TW9i/DtiN8Ku+xCiHcjQ6/J/nDdssirrQNOoB165Zu8EqLMA2lln1JUth9a0aW9Ap2ctrUg==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/ofetch/-/ofetch-1.3.4.tgz", + "integrity": "sha512-KLIET85ik3vhEfS+3fDlc/BAZiAp+43QEC/yCo5zkNoY2YaKvNkOaFr/6wCFgFH1kuYQM5pMNi0Tg8koiIemtw==", "dev": true, "dependencies": { - "destr": "^2.0.1", - "node-fetch-native": "^1.4.0", - "ufo": "^1.3.0" + "destr": "^2.0.3", + "node-fetch-native": "^1.6.3", + "ufo": "^1.5.3" } }, "node_modules/ohash": { @@ -4859,14 +4810,14 @@ } }, "node_modules/pkg-types": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.3.tgz", - "integrity": "sha512-nN7pYi0AQqJnoLPC9eHFQ8AcyaixBUOwvqc5TDnIKCMEE6I0y8P7OKA7fPexsXGCGxQDl/cmrLAp26LhcwxZ4A==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.1.0.tgz", + "integrity": "sha512-/RpmvKdxKf8uILTtoOhAgf30wYbP2Qw+L9p3Rvshx1JZVX+XQNZQFjlbmGHEGIm4CkVPlSn+NXmIM8+9oWQaSA==", "dev": true, "dependencies": { - "jsonc-parser": "^3.2.0", - "mlly": "^1.2.0", - "pathe": "^1.1.0" + "confbox": "^0.1.7", + "mlly": "^1.6.1", + "pathe": "^1.1.2" } }, "node_modules/pngjs": { @@ -4888,9 +4839,9 @@ } }, "node_modules/prettier": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.4.tgz", - "integrity": "sha512-FWu1oLHKCrtpO1ypU6J0SbK2d9Ckwysq6bHj/uaCP26DxrPpppCLQRGVuqAxSTvhF00AcvDRyYrLNW7ocBhFFQ==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", "dev": true, "bin": { "prettier": "bin/prettier.cjs" @@ -4930,11 +4881,12 @@ "dev": true }, "node_modules/protobufjs": { - "version": "7.2.4", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.2.4.tgz", - "integrity": "sha512-AT+RJgD2sH8phPmCf7OUZR8xGdcJRga4+1cOaXJ64hvcSkVhNcRHOwIxUatPH15+nj59WAGTDv3LSGZPEQbJaQ==", + "version": "7.2.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.2.6.tgz", + "integrity": "sha512-dgJaEDDL6x8ASUZ1YqWciTRrdOuYNzoOf27oHNfdyvKqHr5i0FV7FSLU+aIeFjyFgVxrpTOtQUi0BLLBymZaBw==", "dev": true, "hasInstallScript": true, + "peer": true, "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", @@ -5072,9 +5024,9 @@ "dev": true }, "node_modules/radix3": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.0.tgz", - "integrity": "sha512-pNsHDxbGORSvuSScqNJ+3Km6QAVqk8CfsCBIEoDgpqLrkD2f3QM4I7d1ozJJ172OmIcoUcerZaNWqtLkRXTV3A==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.2.tgz", + "integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==", "dev": true }, "node_modules/randombytes": { @@ -5140,27 +5092,6 @@ "node": ">= 12.13.0" } }, - "node_modules/redis-errors": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", - "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/redis-parser": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", - "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", - "dev": true, - "dependencies": { - "redis-errors": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -5299,9 +5230,9 @@ "dev": true }, "node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", + "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" @@ -5508,12 +5439,6 @@ "node": ">= 10.x" } }, - "node_modules/standard-as-callback": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", - "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", - "dev": true - }, "node_modules/std-env": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.7.0.tgz", @@ -5784,12 +5709,12 @@ "dev": true }, "node_modules/ts-api-utils": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.3.tgz", - "integrity": "sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.3.0.tgz", + "integrity": "sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==", "dev": true, "engines": { - "node": ">=16.13.0" + "node": ">=16" }, "peerDependencies": { "typescript": ">=4.2.0" @@ -5832,9 +5757,9 @@ } }, "node_modules/typescript": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", - "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", "dev": true, "bin": { "tsc": "bin/tsc", @@ -5845,9 +5770,9 @@ } }, "node_modules/ufo": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.3.2.tgz", - "integrity": "sha512-o+ORpgGwaYQXgqGDwd+hkS4PuZ3QnmqMMxRuajK/a38L6fTpcE5GPIfrf+L/KemFzfUpeUQc1rRS1iDBozvnFA==", + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.5.3.tgz", + "integrity": "sha512-Y7HYmWaFwPUmkoQCUIAYpKqkOf+SbVj/2fJJZ4RJMCfZp0rTGwRbzQD+HghfnhKOjL9E01okqz+ncJskGYfBNw==", "dev": true }, "node_modules/uint8arrays": { @@ -5891,36 +5816,36 @@ "dev": true }, "node_modules/unstorage": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/unstorage/-/unstorage-1.10.1.tgz", - "integrity": "sha512-rWQvLRfZNBpF+x8D3/gda5nUCQL2PgXy2jNG4U7/Rc9BGEv9+CAJd0YyGCROUBKs9v49Hg8huw3aih5Bf5TAVw==", + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/unstorage/-/unstorage-1.10.2.tgz", + "integrity": "sha512-cULBcwDqrS8UhlIysUJs2Dk0Mmt8h7B0E6mtR+relW9nZvsf/u4SkAYyNliPiPW7XtFNb5u3IUMkxGxFTTRTgQ==", "dev": true, "dependencies": { "anymatch": "^3.1.3", - "chokidar": "^3.5.3", - "destr": "^2.0.2", - "h3": "^1.8.2", - "ioredis": "^5.3.2", - "listhen": "^1.5.5", - "lru-cache": "^10.0.2", + "chokidar": "^3.6.0", + "destr": "^2.0.3", + "h3": "^1.11.1", + "listhen": "^1.7.2", + "lru-cache": "^10.2.0", "mri": "^1.2.0", - "node-fetch-native": "^1.4.1", + "node-fetch-native": "^1.6.2", "ofetch": "^1.3.3", - "ufo": "^1.3.1" + "ufo": "^1.4.0" }, "peerDependencies": { - "@azure/app-configuration": "^1.4.1", + "@azure/app-configuration": "^1.5.0", "@azure/cosmos": "^4.0.0", "@azure/data-tables": "^13.2.2", - "@azure/identity": "^3.3.2", - "@azure/keyvault-secrets": "^4.7.0", - "@azure/storage-blob": "^12.16.0", - "@capacitor/preferences": "^5.0.6", - "@netlify/blobs": "^6.2.0", - "@planetscale/database": "^1.11.0", - "@upstash/redis": "^1.23.4", - "@vercel/kv": "^0.2.3", - "idb-keyval": "^6.2.1" + "@azure/identity": "^4.0.1", + "@azure/keyvault-secrets": "^4.8.0", + "@azure/storage-blob": "^12.17.0", + "@capacitor/preferences": "^5.0.7", + "@netlify/blobs": "^6.5.0 || ^7.0.0", + "@planetscale/database": "^1.16.0", + "@upstash/redis": "^1.28.4", + "@vercel/kv": "^1.0.1", + "idb-keyval": "^6.2.1", + "ioredis": "^5.3.2" }, "peerDependenciesMeta": { "@azure/app-configuration": { @@ -5958,6 +5883,9 @@ }, "idb-keyval": { "optional": true + }, + "ioredis": { + "optional": true } } }, diff --git a/package.json b/package.json index 2fad4c4..6341fc0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "elven.js", - "version": "0.17.0", + "version": "0.18.0", "description": "Authenticate, sign and send transactions on the MultiversX blockchain in the browser.", "type": "module", "module": "build/elven.js", @@ -41,25 +41,26 @@ "prepublishOnly": "npm run build" }, "devDependencies": { - "@multiversx/sdk-core": "12.18.0", + "@multiversx/sdk-core": "13.1.0", "@multiversx/sdk-extension-provider": "3.0.0", - "@multiversx/sdk-native-auth-client": "1.0.7", - "@multiversx/sdk-network-providers": "2.2.1", - "@multiversx/sdk-wallet-connect-provider": "4.1.0", - "@multiversx/sdk-web-wallet-provider": "3.2.0", + "@multiversx/sdk-native-auth-client": "1.0.8", + "@multiversx/sdk-network-providers": "2.4.3", + "@multiversx/sdk-wallet-connect-provider": "4.1.2", + "@multiversx/sdk-web-wallet-provider": "3.2.1", "@types/qrcode": "1.5.5", "@types/serve-handler": "6.1.4", - "@typescript-eslint/eslint-plugin": "6.20.0", - "@typescript-eslint/parser": "6.20.0", - "esbuild": "0.20.0", - "eslint": "8.56.0", + "@typescript-eslint/eslint-plugin": "7.7.0", + "@typescript-eslint/parser": "7.7.0", + "bignumber.js": "9.1.2", + "esbuild": "0.20.2", + "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", "eslint-plugin-prettier": "5.1.3", "node-stdlib-browser": "1.2.0", - "prettier": "3.2.4", + "prettier": "3.2.5", "qrcode": "1.5.3", "rimraf": "5.0.5", "serve-handler": "6.1.5", - "typescript": "5.3.3" + "typescript": "5.4.5" } } diff --git a/src/elven.ts b/src/elven.ts index 1d4d0ad..570ce89 100644 --- a/src/elven.ts +++ b/src/elven.ts @@ -1,13 +1,30 @@ -export { TokenTransfer } from '@multiversx/sdk-core/out/tokenTransfer'; -export { TransferTransactionsFactory } from '@multiversx/sdk-core/out/transferTransactionsFactory'; -export { GasEstimator } from '@multiversx/sdk-core/out/gasEstimator'; +export { + TokenTransfer, + TokenComputer, + Token, +} from '@multiversx/sdk-core/out/tokens'; +export { + TokenOperationsFactory, + TokenOperationsFactoryConfig, + TokenOperationsOutcomeParser, +} from '@multiversx/sdk-core/out/tokenOperations'; +export { + TransferTransactionsFactory, + TransactionsFactoryConfig, + SmartContractTransactionsFactory, + TokenManagementTransactionsFactory, +} from '@multiversx/sdk-core/out/transactionsFactories/'; +export { + SmartContractTransactionsOutcomeParser, + TokenManagementTransactionsOutcomeParser, + TransactionEventsParser, +} from '@multiversx/sdk-core/out/transactionsOutcomeParsers'; export { Address } from '@multiversx/sdk-core/out/address'; export { Account } from '@multiversx/sdk-core/out/account'; export { Transaction } from '@multiversx/sdk-core/out/transaction'; -export { TransactionPayload } from '@multiversx/sdk-core/out/transactionPayload'; +export { TransactionComputer } from '@multiversx/sdk-core/out/transactionComputer'; +export { Message, MessageComputer } from '@multiversx/sdk-core/out/message'; export { TransactionWatcher } from '@multiversx/sdk-core/out/transactionWatcher'; -export { SmartContract } from '@multiversx/sdk-core/out/smartcontracts/smartContract'; -export { ContractFunction } from '@multiversx/sdk-core/out/smartcontracts/function'; export { SignableMessage } from '@multiversx/sdk-core/out/signableMessage'; export { BytesType, @@ -37,4 +54,5 @@ export { QueryArguments } from '@multiversx/sdk-core/out/smartcontracts/interfac export { ContractQueryResponse } from '@multiversx/sdk-network-providers/out/contractQueryResponse'; export { ElvenJS } from './main'; +export { parseAmount, formatAmount } from './utils/amount'; export * from './types'; diff --git a/src/interaction/post-send-tx.ts b/src/interaction/post-send-tx.ts index 74067e7..9465daa 100644 --- a/src/interaction/post-send-tx.ts +++ b/src/interaction/post-send-tx.ts @@ -12,12 +12,13 @@ export const postSendTx = async ( ) => { EventsStore.run(EventStoreEvents.onTxSent, transaction); const transactionWatcher = new TransactionWatcher(networkProvider); - await transactionWatcher.awaitCompleted(transaction); - const sender = transaction.getSender(); + const transactionOnNetwork = + await transactionWatcher.awaitCompleted(transaction); + const sender = transactionOnNetwork.sender; const senderAccount = new Account(sender); const userAccountOnNetwork = await networkProvider.getAccount(sender); senderAccount.update(userAccountOnNetwork); ls.set('address', senderAccount.address.bech32()); ls.set('balance', senderAccount.balance.toString()); - EventsStore.run(EventStoreEvents.onTxFinalized, transaction); + EventsStore.run(EventStoreEvents.onTxFinalized, transactionOnNetwork); }; diff --git a/src/interaction/pre-send-tx.ts b/src/interaction/pre-send-tx.ts index 71620ff..360f804 100644 --- a/src/interaction/pre-send-tx.ts +++ b/src/interaction/pre-send-tx.ts @@ -5,7 +5,7 @@ import { ls } from '../utils/ls-helpers'; export const preSendTx = (tx: Transaction) => { const sender = tx.getSender(); const senderAccount = new Account(sender); - const currentNonce = tx.getNonce().valueOf(); + const currentNonce = tx.nonce.valueOf(); senderAccount.incrementNonce(); - ls.set('nonce', currentNonce + 1); + ls.set('nonce', (currentNonce + 1n).toString()); }; diff --git a/src/interaction/web-wallet-tx-finalize.ts b/src/interaction/web-wallet-tx-finalize.ts index 1798c15..fd70767 100644 --- a/src/interaction/web-wallet-tx-finalize.ts +++ b/src/interaction/web-wallet-tx-finalize.ts @@ -71,7 +71,7 @@ export const webWalletTxFinalize = async ( if (transactionObj) { const transaction = Transaction.fromPlainObject(transactionObj); - transaction.setNonce(nonce); + transaction.nonce = BigInt(nonce); preSendTx(transaction); diff --git a/src/main.ts b/src/main.ts index 4144717..8df958f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -261,7 +261,7 @@ export class ElvenJS { const currentState = ls.get(); - transaction.setNonce(currentState.nonce); + transaction.nonce = currentState.nonce; if (this.dappProvider instanceof ExtensionProvider) { signedTx = await this.dappProvider.signTransaction(transaction); diff --git a/src/utils/amount.ts b/src/utils/amount.ts new file mode 100644 index 0000000..f99be6c --- /dev/null +++ b/src/utils/amount.ts @@ -0,0 +1,46 @@ +import BigNumber from 'bignumber.js'; + +BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_FLOOR }); + +type AmountArgs = { + amount: string; + decimals: number; + rounding?: number; +}; + +/** + * Parses the amount from string + * @param amount + * @param decimals + * @returns bigInt + */ +export const parseAmount = ({ + amount, + decimals, +}: Omit) => { + if (decimals < 0) + throw new Error("Decimal places shouldn't be negative number!"); + + return BigInt(new BigNumber(amount).shiftedBy(decimals).toFixed()); +}; + +/** + * Formats the amount from string (bigInt) + * @param amount + * @param decimals + * @param rounding + * @returns string + */ +export const formatAmount = ({ + amount, + decimals, + rounding = decimals, +}: AmountArgs) => { + if (decimals < 0) + throw new Error("Decimal places shouldn't be negative number!"); + + return new BigNumber(amount) + .shiftedBy(-decimals) + .decimalPlaces(rounding) + .toFixed(); +}; diff --git a/tsconfig.json b/tsconfig.json index 35bd15f..22e8b9c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "include": ["src/**/*"], "compilerOptions": { "strict": true, - "target": "ES2015", + "target": "ES2020", "module": "ES2020", "declaration": true, "declarationDir": "build/types", From 0a28135418c0c2cbbbddbe37dcd8975ff4d029c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20=C4=86wirko?= Date: Sun, 28 Apr 2024 15:38:32 +0200 Subject: [PATCH 2/5] improve bundle size --- .gitignore | 1 + CHANGELOG.md | 2 +- build/elven.js | 55024 +------------------------------------------ esbuild.config.cjs | 26 +- example/elven.js | 55024 +------------------------------------------ package-lock.json | 9 +- package.json | 1 + 7 files changed, 130 insertions(+), 109957 deletions(-) diff --git a/.gitignore b/.gitignore index 6baa20c..8bc0f7a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules meta.txt meta.json +stats.html diff --git a/CHANGELOG.md b/CHANGELOG.md index dbfc1e6..5188bf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -### [0.18.0](https://github.com/elven-js/elven.js/releases/tag/v0.18.0) (2024-04-21) +### [0.18.0](https://github.com/elven-js/elven.js/releases/tag/v0.18.0) (2024-04-28) - switch to SDK v13 - breaking: `SmartContract` is no longer exported, use `SmartContractTransactionsFactory` - breaking: `GasEstimator` removed diff --git a/build/elven.js b/build/elven.js index aab57b0..ec95d64 100644 --- a/build/elven.js +++ b/build/elven.js @@ -1,54987 +1,65 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, { - get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] -}) : x3)(function(x3) { - if (typeof require !== "undefined") - return require.apply(this, arguments); - throw Error('Dynamic require of "' + x3 + '" is not supported'); -}); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod2) => function __require2() { - return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; -}; -var __export = (target, all) => { - for (var name2 in all) - __defProp(target, name2, { get: all[name2], enumerable: true }); -}; -var __copyProps = (to, from3, except, desc) => { - if (from3 && typeof from3 === "object" || typeof from3 === "function") { - for (let key of __getOwnPropNames(from3)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default")); -var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, - mod2 -)); -var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); - -// node_modules/base64-js/index.js -var require_base64_js = __commonJS({ - "node_modules/base64-js/index.js"(exports2) { - "use strict"; - init_shim(); - exports2.byteLength = byteLength; - exports2.toByteArray = toByteArray; - exports2.fromByteArray = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i2 = 0, len = code2.length; i2 < len; ++i2) { - lookup[i2] = code2[i2]; - revLookup[code2.charCodeAt(i2)] = i2; - } - var i2; - var len; - revLookup["-".charCodeAt(0)] = 62; - revLookup["_".charCodeAt(0)] = 63; - function getLens(b64) { - var len2 = b64.length; - if (len2 % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) - validLen = len2; - var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } - function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i3; - for (i3 = 0; i3 < len2; i3 += 4) { - tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - return arr; - } - function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; - } - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i3 = start; i3 < end; i3 += 3) { - tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255); - output.push(tripletToBase64(tmp)); - } - return output.join(""); - } - function fromByteArray(uint8) { - var tmp; - var len2 = uint8.length; - var extraBytes = len2 % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) { - parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength)); - } - if (extraBytes === 1) { - tmp = uint8[len2 - 1]; - parts.push( - lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" - ); - } else if (extraBytes === 2) { - tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; - parts.push( - lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" - ); - } - return parts.join(""); - } - } -}); - -// node_modules/ieee754/index.js -var require_ieee754 = __commonJS({ - "node_modules/ieee754/index.js"(exports2) { - init_shim(); - exports2.read = function(buffer, offset, isLE, mLen, nBytes) { - var e2, m3; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i2 = isLE ? nBytes - 1 : 0; - var d3 = isLE ? -1 : 1; - var s2 = buffer[offset + i2]; - i2 += d3; - e2 = s2 & (1 << -nBits) - 1; - s2 >>= -nBits; - nBits += eLen; - for (; nBits > 0; e2 = e2 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { - } - m3 = e2 & (1 << -nBits) - 1; - e2 >>= -nBits; - nBits += mLen; - for (; nBits > 0; m3 = m3 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { - } - if (e2 === 0) { - e2 = 1 - eBias; - } else if (e2 === eMax) { - return m3 ? NaN : (s2 ? -1 : 1) * Infinity; - } else { - m3 = m3 + Math.pow(2, mLen); - e2 = e2 - eBias; - } - return (s2 ? -1 : 1) * m3 * Math.pow(2, e2 - mLen); - }; - exports2.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e2, m3, c4; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i2 = isLE ? 0 : nBytes - 1; - var d3 = isLE ? 1 : -1; - var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m3 = isNaN(value) ? 1 : 0; - e2 = eMax; - } else { - e2 = Math.floor(Math.log(value) / Math.LN2); - if (value * (c4 = Math.pow(2, -e2)) < 1) { - e2--; - c4 *= 2; - } - if (e2 + eBias >= 1) { - value += rt / c4; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c4 >= 2) { - e2++; - c4 /= 2; - } - if (e2 + eBias >= eMax) { - m3 = 0; - e2 = eMax; - } else if (e2 + eBias >= 1) { - m3 = (value * c4 - 1) * Math.pow(2, mLen); - e2 = e2 + eBias; - } else { - m3 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e2 = 0; - } - } - for (; mLen >= 8; buffer[offset + i2] = m3 & 255, i2 += d3, m3 /= 256, mLen -= 8) { - } - e2 = e2 << mLen | m3; - eLen += mLen; - for (; eLen > 0; buffer[offset + i2] = e2 & 255, i2 += d3, e2 /= 256, eLen -= 8) { - } - buffer[offset + i2 - d3] |= s2 * 128; - }; - } -}); - -// node_modules/node-stdlib-browser/node_modules/buffer/index.js -var require_buffer = __commonJS({ - "node_modules/node-stdlib-browser/node_modules/buffer/index.js"(exports2) { - "use strict"; - init_shim(); - var base642 = require_base64_js(); - var ieee754 = require_ieee754(); - var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports2.Buffer = Buffer2; - exports2.SlowBuffer = SlowBuffer; - exports2.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 2147483647; - exports2.kMaxLength = K_MAX_LENGTH; - Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { - try { - var arr = new Uint8Array(1); - var proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e2) { - return false; - } - } - Object.defineProperty(Buffer2.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer2.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.byteOffset; - } - }); - function createBuffer(length2) { - if (length2 > K_MAX_LENGTH) { - throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); - } - var buf = new Uint8Array(length2); - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function Buffer2(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe2(arg); - } - return from3(arg, encodingOrOffset, length2); - } - Buffer2.poolSize = 8192; - function from3(value, encodingOrOffset, length2) { - if (typeof value === "string") { - return fromString3(value, encodingOrOffset); - } - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof value === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - var valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer2.from(valueOf, encodingOrOffset, length2); - } - var b4 = fromObject(value); - if (b4) - return b4; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer2.from( - value[Symbol.toPrimitive]("string"), - encodingOrOffset, - length2 - ); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - Buffer2.from = function(value, encodingOrOffset, length2) { - return from3(value, encodingOrOffset, length2); - }; - Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer2, Uint8Array); - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } - } - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); - } - Buffer2.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; - function allocUnsafe2(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - Buffer2.allocUnsafe = function(size) { - return allocUnsafe2(size); - }; - Buffer2.allocUnsafeSlow = function(size) { - return allocUnsafe2(size); - }; - function fromString3(string2, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - var length2 = byteLength(string2, encoding) | 0; - var buf = createBuffer(length2); - var actual = buf.write(string2, encoding); - if (actual !== length2) { - buf = buf.slice(0, actual); - } - return buf; - } - function fromArrayLike(array) { - var length2 = array.length < 0 ? 0 : checked(array.length) | 0; - var buf = createBuffer(length2); - for (var i2 = 0; i2 < length2; i2 += 1) { - buf[i2] = array[i2] & 255; - } - return buf; - } - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - return fromArrayLike(arrayView); - } - function fromArrayBuffer(array, byteOffset, length2) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length2 || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - var buf; - if (byteOffset === void 0 && length2 === void 0) { - buf = new Uint8Array(array); - } else if (length2 === void 0) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length2); - } - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function fromObject(obj) { - if (Buffer2.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - function checked(length2) { - if (length2 >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length2 | 0; - } - function SlowBuffer(length2) { - if (+length2 != length2) { - length2 = 0; - } - return Buffer2.alloc(+length2); - } - Buffer2.isBuffer = function isBuffer(b4) { - return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; - }; - Buffer2.compare = function compare3(a3, b4) { - if (isInstance(a3, Uint8Array)) - a3 = Buffer2.from(a3, a3.offset, a3.byteLength); - if (isInstance(b4, Uint8Array)) - b4 = Buffer2.from(b4, b4.offset, b4.byteLength); - if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a3 === b4) - return 0; - var x3 = a3.length; - var y4 = b4.length; - for (var i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { - if (a3[i2] !== b4[i2]) { - x3 = a3[i2]; - y4 = b4[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - Buffer2.isEncoding = function isEncoding(encoding) { - switch (String(encoding).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 true; - default: - return false; - } - }; - Buffer2.concat = function concat2(list, length2) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer2.alloc(0); - } - var i2; - if (length2 === void 0) { - length2 = 0; - for (i2 = 0; i2 < list.length; ++i2) { - length2 += list[i2].length; - } - } - var buffer = Buffer2.allocUnsafe(length2); - var pos = 0; - for (i2 = 0; i2 < list.length; ++i2) { - var buf = list[i2]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer2.from(buf).copy(buffer, pos); - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ); - } - } else if (!Buffer2.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - pos += buf.length; - } - return buffer; - }; - function byteLength(string2, encoding) { - if (Buffer2.isBuffer(string2)) { - return string2.length; - } - if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { - return string2.byteLength; - } - if (typeof string2 !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 - ); - } - var len = string2.length; - var mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) - return 0; - var loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes(string2).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string2).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string2).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.byteLength = byteLength; - function slowToString(encoding, start, end) { - var loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) - encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.prototype._isBuffer = true; - function swap(b4, n3, m3) { - var i2 = b4[n3]; - b4[n3] = b4[m3]; - b4[m3] = i2; - } - Buffer2.prototype.swap16 = function swap16() { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (var i2 = 0; i2 < len; i2 += 2) { - swap(this, i2, i2 + 1); - } - return this; - }; - Buffer2.prototype.swap32 = function swap32() { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (var i2 = 0; i2 < len; i2 += 4) { - swap(this, i2, i2 + 3); - swap(this, i2 + 1, i2 + 2); - } - return this; - }; - Buffer2.prototype.swap64 = function swap64() { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (var i2 = 0; i2 < len; i2 += 8) { - swap(this, i2, i2 + 7); - swap(this, i2 + 1, i2 + 6); - swap(this, i2 + 2, i2 + 5); - swap(this, i2 + 3, i2 + 4); - } - return this; - }; - Buffer2.prototype.toString = function toString3() { - var length2 = this.length; - if (length2 === 0) - return ""; - if (arguments.length === 0) - return utf8Slice(this, 0, length2); - return slowToString.apply(this, arguments); - }; - Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; - Buffer2.prototype.equals = function equals4(b4) { - if (!Buffer2.isBuffer(b4)) - throw new TypeError("Argument must be a Buffer"); - if (this === b4) - return true; - return Buffer2.compare(this, b4) === 0; - }; - Buffer2.prototype.inspect = function inspect() { - var str = ""; - var max = exports2.INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) - str += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; - } - Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer2.from(target, target.offset, target.byteLength); - } - if (!Buffer2.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) - return 0; - var x3 = thisEnd - thisStart; - var y4 = end - start; - var len = Math.min(x3, y4); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - for (var i2 = 0; i2 < len; ++i2) { - if (thisCopy[i2] !== targetCopy[i2]) { - x3 = thisCopy[i2]; - y4 = targetCopy[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - if (buffer.length === 0) - return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length - 1; - } - if (byteOffset < 0) - byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) - return -1; - else - byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) - byteOffset = 0; - else - return -1; - } - if (typeof val === "string") { - val = Buffer2.from(val, encoding); - } - if (Buffer2.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); - } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read2(buf, i3) { - if (indexSize === 1) { - return buf[i3]; - } else { - return buf.readUInt16BE(i3 * indexSize); - } - } - var i2; - if (dir) { - var foundIndex = -1; - for (i2 = byteOffset; i2 < arrLength; i2++) { - if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { - if (foundIndex === -1) - foundIndex = i2; - if (i2 - foundIndex + 1 === valLength) - return foundIndex * indexSize; - } else { - if (foundIndex !== -1) - i2 -= i2 - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) - byteOffset = arrLength - valLength; - for (i2 = byteOffset; i2 >= 0; i2--) { - var found = true; - for (var j2 = 0; j2 < valLength; j2++) { - if (read2(arr, i2 + j2) !== read2(val, j2)) { - found = false; - break; - } - } - if (found) - return i2; - } - } - return -1; - } - Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string2, offset, length2) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length2) { - length2 = remaining; - } else { - length2 = Number(length2); - if (length2 > remaining) { - length2 = remaining; - } - } - var strLen = string2.length; - if (length2 > strLen / 2) { - length2 = strLen / 2; - } - for (var i2 = 0; i2 < length2; ++i2) { - var parsed = parseInt(string2.substr(i2 * 2, 2), 16); - if (numberIsNaN(parsed)) - return i2; - buf[offset + i2] = parsed; - } - return i2; - } - function utf8Write(buf, string2, offset, length2) { - return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); - } - function asciiWrite(buf, string2, offset, length2) { - return blitBuffer(asciiToBytes(string2), buf, offset, length2); - } - function base64Write(buf, string2, offset, length2) { - return blitBuffer(base64ToBytes(string2), buf, offset, length2); - } - function ucs2Write(buf, string2, offset, length2) { - return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); - } - Buffer2.prototype.write = function write(string2, offset, length2, encoding) { - if (offset === void 0) { - encoding = "utf8"; - length2 = this.length; - offset = 0; - } else if (length2 === void 0 && typeof offset === "string") { - encoding = offset; - length2 = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length2)) { - length2 = length2 >>> 0; - if (encoding === void 0) - encoding = "utf8"; - } else { - encoding = length2; - length2 = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - var remaining = this.length - offset; - if (length2 === void 0 || length2 > remaining) - length2 = remaining; - if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) - encoding = "utf8"; - var loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string2, offset, length2); - case "utf8": - case "utf-8": - return utf8Write(this, string2, offset, length2); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string2, offset, length2); - case "base64": - return base64Write(this, string2, offset, length2); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string2, offset, length2); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - Buffer2.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base642.fromByteArray(buf); - } else { - return base642.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i2 = start; - while (i2 < end) { - var firstByte = buf[i2]; - var codePoint = null; - var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i2 + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i2 + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - fourthByte = buf[i2 + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i2 += bytesPerSequence; - } - return decodeCodePointsArray(res); - } - var MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - var res = ""; - var i2 = 0; - while (i2 < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) - ); - } - return res; - } - function asciiSlice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); - for (var i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2] & 127); - } - return ret; - } - function latin1Slice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); - for (var i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2]); - } - return ret; - } - function hexSlice(buf, start, end) { - var len = buf.length; - if (!start || start < 0) - start = 0; - if (!end || end < 0 || end > len) - end = len; - var out = ""; - for (var i2 = start; i2 < end; ++i2) { - out += hexSliceLookupTable[buf[i2]]; - } - return out; - } - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ""; - for (var i2 = 0; i2 < bytes.length - 1; i2 += 2) { - res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); - } - return res; - } - Buffer2.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) - start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) - end = 0; - } else if (end > len) { - end = len; - } - if (end < start) - end = start; - var newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer2.prototype); - return newBuf; - }; - function checkOffset(offset, ext, length2) { - if (offset % 1 !== 0 || offset < 0) - throw new RangeError("offset is not uint"); - if (offset + ext > length2) - throw new RangeError("Trying to access beyond buffer length"); - } - Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - var val = this[offset]; - var mul = 1; - var i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - return val; - }; - Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength2, this.length); - } - var val = this[offset + --byteLength2]; - var mul = 1; - while (byteLength2 > 0 && (mul *= 256)) { - val += this[offset + --byteLength2] * mul; - } - return val; - }; - Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - return this[offset]; - }; - Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; - }; - Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - var val = this[offset]; - var mul = 1; - var i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - var i2 = byteLength2; - var mul = 1; - var val = this[offset + --i2]; - while (i2 > 0 && (mul *= 256)) { - val += this[offset + --i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) - return this[offset]; - return (255 - this[offset] + 1) * -1; - }; - Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - var val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - var val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); - }; - Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); - }; - Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); - }; - Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); - }; - function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer2.isBuffer(buf)) - throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) - throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - } - Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - var mul = 1; - var i2 = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - var i2 = byteLength2 - 1; - var mul = 1; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 255, 0); - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - var i2 = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - var i2 = byteLength2 - 1; - var mul = 1; - var sub = 0; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 127, -128); - if (value < 0) - value = 255 + value + 1; - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; - }; - Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - if (value < 0) - value = 4294967295 + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - if (offset < 0) - throw new RangeError("Index out of range"); - } - function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); - }; - function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; - Buffer2.prototype.copy = function copy(target, targetStart, start, end) { - if (!Buffer2.isBuffer(target)) - throw new TypeError("argument should be a Buffer"); - if (!start) - start = 0; - if (!end && end !== 0) - end = this.length; - if (targetStart >= target.length) - targetStart = target.length; - if (!targetStart) - targetStart = 0; - if (end > 0 && end < start) - end = start; - if (end === start) - return 0; - if (target.length === 0 || this.length === 0) - return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) - throw new RangeError("Index out of range"); - if (end < 0) - throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) - end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - var len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); - } - return len; - }; - Buffer2.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - var code2 = val.charCodeAt(0); - if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { - val = code2; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) - val = 0; - var i2; - if (typeof val === "number") { - for (i2 = start; i2 < end; ++i2) { - this[i2] = val; - } - } else { - var bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); - var len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i2 = 0; i2 < end - start; ++i2) { - this[i2 + start] = bytes[i2 % len]; - } - } - return this; - }; - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) - return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } - function utf8ToBytes(string2, units) { - units = units || Infinity; - var codePoint; - var length2 = string2.length; - var leadSurrogate = null; - var bytes = []; - for (var i2 = 0; i2 < length2; ++i2) { - codePoint = string2.charCodeAt(i2); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } else if (i2 + 1 === length2) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) - break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) - break; - bytes.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) - break; - bytes.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) - break; - bytes.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; - } - function asciiToBytes(str) { - var byteArray = []; - for (var i2 = 0; i2 < str.length; ++i2) { - byteArray.push(str.charCodeAt(i2) & 255); - } - return byteArray; - } - function utf16leToBytes(str, units) { - var c4, hi, lo; - var byteArray = []; - for (var i2 = 0; i2 < str.length; ++i2) { - if ((units -= 2) < 0) - break; - c4 = str.charCodeAt(i2); - hi = c4 >> 8; - lo = c4 % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; - } - function base64ToBytes(str) { - return base642.toByteArray(base64clean(str)); - } - function blitBuffer(src2, dst, offset, length2) { - for (var i2 = 0; i2 < length2; ++i2) { - if (i2 + offset >= dst.length || i2 >= src2.length) - break; - dst[i2 + offset] = src2[i2]; - } - return i2; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - var hexSliceLookupTable = function() { - var alphabet2 = "0123456789abcdef"; - var table = new Array(256); - for (var i2 = 0; i2 < 16; ++i2) { - var i16 = i2 * 16; - for (var j2 = 0; j2 < 16; ++j2) { - table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; - } - } - return table; - }(); - } -}); - -// node_modules/process/browser.js -var require_browser = __commonJS({ - "node_modules/process/browser.js"(exports2, module2) { - init_shim(); - var process2 = module2.exports = {}; - var cachedSetTimeout; - var cachedClearTimeout; - function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); - } - function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); - } - (function() { - try { - if (typeof setTimeout === "function") { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e2) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === "function") { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e2) { - cachedClearTimeout = defaultClearTimeout; - } - })(); - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - return setTimeout(fun, 0); - } - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - return cachedSetTimeout(fun, 0); - } catch (e2) { - try { - return cachedSetTimeout.call(null, fun, 0); - } catch (e3) { - return cachedSetTimeout.call(this, fun, 0); - } - } - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - return clearTimeout(marker); - } - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - return cachedClearTimeout(marker); - } catch (e2) { - try { - return cachedClearTimeout.call(null, marker); - } catch (e3) { - return cachedClearTimeout.call(this, marker); - } - } - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - process2.nextTick = function(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i2 = 1; i2 < arguments.length; i2++) { - args[i2 - 1] = arguments[i2]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function() { - this.fun.apply(null, this.array); - }; - process2.title = "browser"; - process2.browser = true; - process2.env = {}; - process2.argv = []; - process2.version = ""; - process2.versions = {}; - function noop() { - } - process2.on = noop; - process2.addListener = noop; - process2.once = noop; - process2.off = noop; - process2.removeListener = noop; - process2.removeAllListeners = noop; - process2.emit = noop; - process2.prependListener = noop; - process2.prependOnceListener = noop; - process2.listeners = function(name2) { - return []; - }; - process2.binding = function(name2) { - throw new Error("process.binding is not supported"); - }; - process2.cwd = function() { - return "/"; - }; - process2.chdir = function(dir) { - throw new Error("process.chdir is not supported"); - }; - process2.umask = function() { - return 0; - }; - } -}); - -// node_modules/node-stdlib-browser/helpers/esbuild/shim.js -var import_buffer, import_process, _globalThis, global; -var init_shim = __esm({ - "node_modules/node-stdlib-browser/helpers/esbuild/shim.js"() { - import_buffer = __toESM(require_buffer()); - import_process = __toESM(require_browser()); - _globalThis = function(Object2) { - function get2() { - var _global2 = this || self; - delete Object2.prototype.__magic__; - return _global2; - } - if (typeof globalThis === "object") { - return globalThis; - } - if (this) { - return get2(); - } else { - Object2.defineProperty(Object2.prototype, "__magic__", { - configurable: true, - get: get2 - }); - var _global = __magic__; - return _global; - } - }(Object); - global = _globalThis; - } -}); - -// node_modules/bignumber.js/bignumber.js -var require_bignumber = __commonJS({ - "node_modules/bignumber.js/bignumber.js"(exports2, module2) { - init_shim(); - (function(globalObject) { - "use strict"; - var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; - function clone2(configObject) { - var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber3(v2, b4) { - var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; - if (!(x3 instanceof BigNumber3)) - return new BigNumber3(v2, b4); - if (b4 == null) { - if (v2 && v2._isBigNumber === true) { - x3.s = v2.s; - if (!v2.c || v2.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (v2.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = v2.e; - x3.c = v2.c.slice(); - } - return; - } - if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { - x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; - if (v2 === ~~v2) { - for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x3.c = x3.e = null; - } else { - x3.e = e2; - x3.c = [v2]; - } - return; - } - str = String(v2); - } else { - if (!isNumeric2.test(str = String(v2))) - return parseNumeric(x3, str, isNum); - x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i2 = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i2; - e2 += +str.slice(i2 + 1); - str = str.substring(0, i2); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - if (b4 == 10 && alphabetHasNormalDecimalDigits) { - x3 = new BigNumber3(v2); - return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); - } - str = String(v2); - if (isNum = typeof v2 == "number") { - if (v2 * 0 != 0) - return parseNumeric(x3, str, isNum, b4); - x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits2 + v2); - } - } else { - x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b4); - e2 = i2 = 0; - for (len = str.length; i2 < len; i2++) { - if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { - if (c4 == ".") { - if (i2 > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i2 = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x3, String(v2), isNum, b4); - } - } - isNum = false; - str = convertBase(str, b4, 10, x3.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i2 = 0; str.charCodeAt(i2) === 48; i2++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i2, ++len)) { - len -= i2; - if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { - throw Error(tooManyDigits2 + x3.s * v2); - } - if ((e2 = e2 - i2 - 1) > MAX_EXP) { - x3.c = x3.e = null; - } else if (e2 < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = e2; - x3.c = []; - i2 = (e2 + 1) % LOG_BASE2; - if (e2 < 0) - i2 += LOG_BASE2; - if (i2 < len) { - if (i2) - x3.c.push(+str.slice(0, i2)); - for (len -= LOG_BASE2; i2 < len; ) { - x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); - } - i2 = LOG_BASE2 - (str = str.slice(i2)).length; - } else { - i2 -= len; - } - for (; i2--; str += "0") - ; - x3.c.push(+str); - } - } else { - x3.c = [x3.e = 0]; - } - } - BigNumber3.clone = clone2; - BigNumber3.ROUND_UP = 0; - BigNumber3.ROUND_DOWN = 1; - BigNumber3.ROUND_CEIL = 2; - BigNumber3.ROUND_FLOOR = 3; - BigNumber3.ROUND_HALF_UP = 4; - BigNumber3.ROUND_HALF_DOWN = 5; - BigNumber3.ROUND_HALF_EVEN = 6; - BigNumber3.ROUND_HALF_CEIL = 7; - BigNumber3.ROUND_HALF_FLOOR = 8; - BigNumber3.EUCLID = 9; - BigNumber3.config = BigNumber3.set = function(obj) { - var p3, v2; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - DECIMAL_PLACES = v2; - } - if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 8, p3); - ROUNDING_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, 0, p3); - intCheck2(v2[1], 0, MAX2, p3); - TO_EXP_NEG = v2[0]; - TO_EXP_POS = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); - } - } - if (obj.hasOwnProperty(p3 = "RANGE")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, -1, p3); - intCheck2(v2[1], 1, MAX2, p3); - MIN_EXP = v2[0]; - MAX_EXP = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - if (v2) { - MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); - } else { - throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); - } - } - } - if (obj.hasOwnProperty(p3 = "CRYPTO")) { - v2 = obj[p3]; - if (v2 === !!v2) { - if (v2) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v2; - } else { - CRYPTO = !v2; - throw Error(bignumberError2 + "crypto unavailable"); - } - } else { - CRYPTO = v2; - } - } else { - throw Error(bignumberError2 + p3 + " not true or false: " + v2); - } - } - if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 9, p3); - MODULO_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - POW_PRECISION = v2; - } - if (obj.hasOwnProperty(p3 = "FORMAT")) { - v2 = obj[p3]; - if (typeof v2 == "object") - FORMAT = v2; - else - throw Error(bignumberError2 + p3 + " not an object: " + v2); - } - if (obj.hasOwnProperty(p3 = "ALPHABET")) { - v2 = obj[p3]; - if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { - alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; - ALPHABET = v2; - } else { - throw Error(bignumberError2 + p3 + " invalid: " + v2); - } - } - } else { - throw Error(bignumberError2 + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber3.isBigNumber = function(v2) { - if (!v2 || v2._isBigNumber !== true) - return false; - if (!BigNumber3.DEBUG) - return true; - var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; - out: - if ({}.toString.call(c4) == "[object Array]") { - if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { - if (c4[0] === 0) { - if (e2 === 0 && c4.length === 1) - return true; - break out; - } - i2 = (e2 + 1) % LOG_BASE2; - if (i2 < 1) - i2 += LOG_BASE2; - if (String(c4[0]).length == i2) { - for (i2 = 0; i2 < c4.length; i2++) { - n3 = c4[i2]; - if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) - break out; - } - if (n3 !== 0) - return true; - } - } - } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { - return true; - } - throw Error(bignumberError2 + "Invalid BigNumber: " + v2); - }; - BigNumber3.maximum = BigNumber3.max = function() { - return maxOrMin(arguments, -1); - }; - BigNumber3.minimum = BigNumber3.min = function() { - return maxOrMin(arguments, 1); - }; - BigNumber3.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor2(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck2(dp, 0, MAX2); - k4 = mathceil2(dp / LOG_BASE2); - if (CRYPTO) { - if (crypto.getRandomValues) { - a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); - for (; i2 < k4; ) { - v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); - if (v2 >= 9e15) { - b4 = crypto.getRandomValues(new Uint32Array(2)); - a3[i2] = b4[0]; - a3[i2 + 1] = b4[1]; - } else { - c4.push(v2 % 1e14); - i2 += 2; - } - } - i2 = k4 / 2; - } else if (crypto.randomBytes) { - a3 = crypto.randomBytes(k4 *= 7); - for (; i2 < k4; ) { - v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; - if (v2 >= 9e15) { - crypto.randomBytes(7).copy(a3, i2); - } else { - c4.push(v2 % 1e14); - i2 += 7; - } - } - i2 = k4 / 7; - } else { - CRYPTO = false; - throw Error(bignumberError2 + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (; i2 < k4; ) { - v2 = random53bitInt(); - if (v2 < 9e15) - c4[i2++] = v2 % 1e14; - } - } - k4 = c4[--i2]; - dp %= LOG_BASE2; - if (k4 && dp) { - v2 = POWS_TEN2[LOG_BASE2 - dp]; - c4[i2] = mathfloor2(k4 / v2) * v2; - } - for (; c4[i2] === 0; c4.pop(), i2--) - ; - if (i2 < 0) { - c4 = [e2 = 0]; - } else { - for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) - ; - for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) - ; - if (i2 < LOG_BASE2) - e2 -= LOG_BASE2 - i2; - } - rand.e = e2; - rand.c = c4; - return rand; - }; - }(); - BigNumber3.sum = function() { - var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); - for (; i2 < args.length; ) - sum = sum.plus(args[i2++]); - return sum; - }; - convertBase = /* @__PURE__ */ function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j2, arr = [0], arrL, i2 = 0, len = str.length; - for (; i2 < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i2++)); - for (j2 = 0; j2 < arr.length; j2++) { - if (arr[j2] > baseOut - 1) { - if (arr[j2 + 1] == null) - arr[j2 + 1] = 0; - arr[j2 + 1] += arr[j2] / baseOut | 0; - arr[j2] %= baseOut; - } - } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign2, callerIsToString) { - var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i2 >= 0) { - k4 = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y4 = new BigNumber3(baseIn); - x3 = y4.pow(str.length - i2); - POW_PRECISION = k4; - y4.c = toBaseOut( - toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), - 10, - baseOut, - decimal - ); - y4.e = y4.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k4 = xc.length; - for (; xc[--k4] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i2 < 0) { - --e2; - } else { - x3.c = xc; - x3.e = e2; - x3.s = sign2; - x3 = div(x3, y4, dp, rm, baseOut); - xc = x3.c; - r = x3.r; - e2 = x3.e; - } - d3 = e2 + dp + 1; - i2 = xc[d3]; - k4 = baseOut / 2; - r = r || d3 < 0 || xc[d3 + 1] != null; - r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (d3 < 1 || !xc[0]) { - str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d3; - if (r) { - for (--baseOut; ++xc[--d3] > baseOut; ) { - xc[d3] = 0; - if (!d3) { - ++e2; - xc = [1].concat(xc); - } - } - } - for (k4 = xc.length; !xc[--k4]; ) - ; - for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) - ; - str = toFixedPoint2(str, e2, alphabet2.charAt(0)); - } - return str; - }; - }(); - div = /* @__PURE__ */ function() { - function multiply(x3, k4, base3) { - var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; - for (x3 = x3.slice(); i2--; ) { - xlo = x3[i2] % SQRT_BASE2; - xhi = x3[i2] / SQRT_BASE2 | 0; - m3 = khi * xlo + xhi * klo; - temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; - carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; - x3[i2] = temp % base3; - } - if (carry) - x3 = [carry].concat(x3); - return x3; - } - function compare4(a3, b4, aL, bL) { - var i2, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i2 = cmp = 0; i2 < aL; i2++) { - if (a3[i2] != b4[i2]) { - cmp = a3[i2] > b4[i2] ? 1 : -1; - break; - } - } - } - return cmp; - } - function subtract(a3, b4, aL, base3) { - var i2 = 0; - for (; aL--; ) { - a3[aL] -= i2; - i2 = a3[aL] < b4[aL] ? 1 : 0; - a3[aL] = i2 * base3 + a3[aL] - b4[aL]; - } - for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) - ; - } - return function(x3, y4, dp, rm, base3) { - var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber3( - // Return NaN if either NaN, or both Infinity or 0. - !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 - ) - ); - } - q2 = new BigNumber3(s2); - qc = q2.c = []; - e2 = x3.e - y4.e; - s2 = dp + e2 + 1; - if (!base3) { - base3 = BASE2; - e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); - s2 = s2 / LOG_BASE2 | 0; - } - for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) - ; - if (yc[i2] > (xc[i2] || 0)) - e2--; - if (s2 < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i2 = 0; - s2 += 2; - n3 = mathfloor2(base3 / (yc[0] + 1)); - if (n3 > 1) { - yc = multiply(yc, n3, base3); - xc = multiply(xc, n3, base3); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base3 / 2) - yc0++; - do { - n3 = 0; - cmp = compare4(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base3 + (rem[1] || 0); - n3 = mathfloor2(rem0 / yc0); - if (n3 > 1) { - if (n3 >= base3) - n3 = base3 - 1; - prod = multiply(yc, n3, base3); - prodL = prod.length; - remL = rem.length; - while (compare4(prod, rem, prodL, remL) == 1) { - n3--; - subtract(prod, yL < prodL ? yz : yc, prodL, base3); - prodL = prod.length; - cmp = 1; - } - } else { - if (n3 == 0) { - cmp = n3 = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base3); - remL = rem.length; - if (cmp == -1) { - while (compare4(yc, rem, yL, remL) < 1) { - n3++; - subtract(rem, yL < remL ? yz : yc, remL, base3); - remL = rem.length; - } - } - } else if (cmp === 0) { - n3++; - rem = [0]; - } - qc[i2++] = n3; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s2--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base3 == BASE2) { - for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) - ; - round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); - } else { - q2.e = e2; - q2.r = +more; - } - return q2; - }; - }(); - function format(n3, i2, rm, id) { - var c0, e2, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - if (!n3.c) - return n3.toString(); - c0 = n3.c[0]; - ne = n3.e; - if (i2 == null) { - str = coeffToString2(n3.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); - } else { - n3 = round(new BigNumber3(n3), i2, rm); - e2 = n3.e; - str = coeffToString2(n3.c); - len = str.length; - if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { - for (; len < i2; str += "0", len++) - ; - str = toExponential2(str, e2); - } else { - i2 -= ne; - str = toFixedPoint2(str, e2, "0"); - if (e2 + 1 > len) { - if (--i2 > 0) - for (str += "."; i2--; str += "0") - ; - } else { - i2 += e2 - len; - if (i2 > 0) { - if (e2 + 1 == len) - str += "."; - for (; i2--; str += "0") - ; - } - } - } - } - return n3.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, n3) { - var k4, y4, i2 = 1, x3 = new BigNumber3(args[0]); - for (; i2 < args.length; i2++) { - y4 = new BigNumber3(args[i2]); - if (!y4.s || (k4 = compare3(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { - x3 = y4; - } - } - return x3; - } - function normalise(n3, c4, e2) { - var i2 = 1, j2 = c4.length; - for (; !c4[--j2]; c4.pop()) - ; - for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) - ; - if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { - n3.c = n3.e = null; - } else if (e2 < MIN_EXP) { - n3.c = [n3.e = 0]; - } else { - n3.e = e2; - n3.c = c4; - } - return n3; - } - parseNumeric = /* @__PURE__ */ function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x3, str, isNum, b4) { - var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s2)) { - x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; - } else { - if (!isNum) { - s2 = s2.replace(basePrefix, function(m3, p1, p22) { - base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; - return !b4 || b4 == base3 ? p1 : m3; - }); - if (b4) { - base3 = b4; - s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s2) - return new BigNumber3(s2, base3); - } - if (BigNumber3.DEBUG) { - throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); - } - x3.s = null; - } - x3.c = x3.e = null; - }; - }(); - function round(x3, sd, rm, r) { - var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; - if (xc) { - out: { - for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) - ; - i2 = sd - d3; - if (i2 < 0) { - i2 += LOG_BASE2; - j2 = sd; - n3 = xc[ni = 0]; - rd = mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); - } else { - ni = mathceil2((i2 + 1) / LOG_BASE2); - if (ni >= xc.length) { - if (r) { - for (; xc.length <= ni; xc.push(0)) - ; - n3 = rd = 0; - d3 = 1; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + 1; - } else { - break out; - } - } else { - n3 = k4 = xc[ni]; - for (d3 = 1; k4 >= 10; k4 /= 10, d3++) - ; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + d3; - rd = j2 < 0 ? 0 : mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); - } - } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x3.e + 1; - xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; - x3.e = -sd || 0; - } else { - xc[0] = x3.e = 0; - } - return x3; - } - if (i2 == 0) { - xc.length = ni; - k4 = 1; - ni--; - } else { - xc.length = ni + 1; - k4 = pows10[LOG_BASE2 - i2]; - xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; - } - if (r) { - for (; ; ) { - if (ni == 0) { - for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) - ; - j2 = xc[0] += k4; - for (k4 = 1; j2 >= 10; j2 /= 10, k4++) - ; - if (i2 != k4) { - x3.e++; - if (xc[0] == BASE2) - xc[0] = 1; - } - break; - } else { - xc[ni] += k4; - if (xc[ni] != BASE2) - break; - xc[ni--] = 0; - k4 = 1; - } - } - } - for (i2 = xc.length; xc[--i2] === 0; xc.pop()) - ; - } - if (x3.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (x3.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } - } - return x3; - } - function valueOf(n3) { - var str, e2 = n3.e; - if (e2 === null) - return n3.toString(); - str = coeffToString2(n3.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); - return n3.s < 0 ? "-" + str : str; - } - P2.absoluteValue = P2.abs = function() { - var x3 = new BigNumber3(this); - if (x3.s < 0) - x3.s = 1; - return x3; - }; - P2.comparedTo = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)); - }; - P2.decimalPlaces = P2.dp = function(dp, rm) { - var c4, n3, v2, x3 = this; - if (dp != null) { - intCheck2(dp, 0, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), dp + x3.e + 1, rm); - } - if (!(c4 = x3.c)) - return null; - n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; - if (v2 = c4[v2]) - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - if (n3 < 0) - n3 = 0; - return n3; - }; - P2.dividedBy = P2.div = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); - }; - P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), 0, 1); - }; - P2.exponentiatedBy = P2.pow = function(n3, m3) { - var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; - n3 = new BigNumber3(n3); - if (n3.c && !n3.isInteger()) { - throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); - } - if (m3 != null) - m3 = new BigNumber3(m3); - nIsBig = n3.e > 14; - if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { - y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd2(n3)) : +valueOf(n3))); - return m3 ? y4.mod(m3) : y4; - } - nIsNeg = n3.s < 0; - if (m3) { - if (m3.c ? !m3.c[0] : !m3.s) - return new BigNumber3(NaN); - isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); - if (isModExp) - x3 = x3.mod(m3); - } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { - k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; - if (x3.e > -1) - k4 = 1 / k4; - return new BigNumber3(nIsNeg ? 1 / k4 : k4); - } else if (POW_PRECISION) { - k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); - } - if (nIsBig) { - half = new BigNumber3(0.5); - if (nIsNeg) - n3.s = 1; - nIsOdd = isOdd2(n3); - } else { - i2 = Math.abs(+valueOf(n3)); - nIsOdd = i2 % 2; - } - y4 = new BigNumber3(ONE); - for (; ; ) { - if (nIsOdd) { - y4 = y4.times(x3); - if (!y4.c) - break; - if (k4) { - if (y4.c.length > k4) - y4.c.length = k4; - } else if (isModExp) { - y4 = y4.mod(m3); - } - } - if (i2) { - i2 = mathfloor2(i2 / 2); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } else { - n3 = n3.times(half); - round(n3, n3.e + 1, 1); - if (n3.e > 14) { - nIsOdd = isOdd2(n3); - } else { - i2 = +valueOf(n3); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } - } - x3 = x3.times(x3); - if (k4) { - if (x3.c && x3.c.length > k4) - x3.c.length = k4; - } else if (isModExp) { - x3 = x3.mod(m3); - } - } - if (isModExp) - return y4; - if (nIsNeg) - y4 = ONE.div(y4); - return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; - }; - P2.integerValue = function(rm) { - var n3 = new BigNumber3(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(n3, n3.e + 1, rm); - }; - P2.isEqualTo = P2.eq = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) === 0; - }; - P2.isFinite = function() { - return !!this.c; - }; - P2.isGreaterThan = P2.gt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) > 0; - }; - P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; - }; - P2.isInteger = function() { - return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; - }; - P2.isLessThan = P2.lt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) < 0; - }; - P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; - }; - P2.isNaN = function() { - return !this.s; - }; - P2.isNegative = function() { - return this.s < 0; - }; - P2.isPositive = function() { - return this.s > 0; - }; - P2.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P2.minus = function(y4, b4) { - var i2, j2, t, xLTy, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.plus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); - } - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (xLTy = a3 < 0) { - a3 = -a3; - t = xc; - } else { - ye = xe; - t = yc; - } - t.reverse(); - for (b4 = a3; b4--; t.push(0)) - ; - t.reverse(); - } else { - j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; - for (a3 = b4 = 0; b4 < j2; b4++) { - if (xc[b4] != yc[b4]) { - xLTy = xc[b4] < yc[b4]; - break; - } - } - } - if (xLTy) { - t = xc; - xc = yc; - yc = t; - y4.s = -y4.s; - } - b4 = (j2 = yc.length) - (i2 = xc.length); - if (b4 > 0) - for (; b4--; xc[i2++] = 0) - ; - b4 = BASE2 - 1; - for (; j2 > a3; ) { - if (xc[--j2] < yc[j2]) { - for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) - ; - --xc[i2]; - xc[j2] += BASE2; - } - xc[j2] -= yc[j2]; - } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y4.s = ROUNDING_MODE == 3 ? -1 : 1; - y4.c = [y4.e = 0]; - return y4; - } - return normalise(y4, xc, ye); - }; - P2.modulo = P2.mod = function(y4, b4) { - var q2, s2, x3 = this; - y4 = new BigNumber3(y4, b4); - if (!x3.c || !y4.s || y4.c && !y4.c[0]) { - return new BigNumber3(NaN); - } else if (!y4.c || x3.c && !x3.c[0]) { - return new BigNumber3(x3); - } - if (MODULO_MODE == 9) { - s2 = y4.s; - y4.s = 1; - q2 = div(x3, y4, 0, 3); - y4.s = s2; - q2.s *= s2; - } else { - q2 = div(x3, y4, 0, MODULO_MODE); - } - y4 = x3.minus(q2.times(y4)); - if (!y4.c[0] && MODULO_MODE == 1) - y4.s = x3.s; - return y4; - }; - P2.multipliedBy = P2.times = function(y4, b4) { - var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y4.c = y4.e = y4.s = null; - } else { - y4.s *= x3.s; - if (!xc || !yc) { - y4.c = y4.e = null; - } else { - y4.c = [0]; - y4.e = 0; - } - } - return y4; - } - e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); - y4.s *= x3.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) { - zc = xc; - xc = yc; - yc = zc; - i2 = xcL; - xcL = ycL; - ycL = i2; - } - for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) - ; - base3 = BASE2; - sqrtBase = SQRT_BASE2; - for (i2 = ycL; --i2 >= 0; ) { - c4 = 0; - ylo = yc[i2] % sqrtBase; - yhi = yc[i2] / sqrtBase | 0; - for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { - xlo = xc[--k4] % sqrtBase; - xhi = xc[k4] / sqrtBase | 0; - m3 = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; - c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; - zc[j2--] = xlo % base3; - } - zc[j2] = c4; - } - if (c4) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y4, zc, e2); - }; - P2.negated = function() { - var x3 = new BigNumber3(this); - x3.s = -x3.s || null; - return x3; - }; - P2.plus = function(y4, b4) { - var t, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.minus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber3(a3 / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (a3 > 0) { - ye = xe; - t = yc; - } else { - a3 = -a3; - t = xc; - } - t.reverse(); - for (; a3--; t.push(0)) - ; - t.reverse(); - } - a3 = xc.length; - b4 = yc.length; - if (a3 - b4 < 0) { - t = yc; - yc = xc; - xc = t; - b4 = a3; - } - for (a3 = 0; b4; ) { - a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; - xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; - } - if (a3) { - xc = [a3].concat(xc); - ++ye; - } - return normalise(y4, xc, ye); - }; - P2.precision = P2.sd = function(sd, rm) { - var c4, n3, v2, x3 = this; - if (sd != null && sd !== !!sd) { - intCheck2(sd, 1, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), sd, rm); - } - if (!(c4 = x3.c)) - return null; - v2 = c4.length - 1; - n3 = v2 * LOG_BASE2 + 1; - if (v2 = c4[v2]) { - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) - ; - } - if (sd && x3.e + 1 > n3) - n3 = x3.e + 1; - return n3; - }; - P2.shiftedBy = function(k4) { - intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); - return this.times("1e" + k4); - }; - P2.squareRoot = P2.sqrt = function() { - var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); - if (s2 !== 1 || !c4 || !c4[0]) { - return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); - } - s2 = Math.sqrt(+valueOf(x3)); - if (s2 == 0 || s2 == 1 / 0) { - n3 = coeffToString2(c4); - if ((n3.length + e2) % 2 == 0) - n3 += "0"; - s2 = Math.sqrt(+n3); - e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s2 == 1 / 0) { - n3 = "5e" + e2; - } else { - n3 = s2.toExponential(); - n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; - } - r = new BigNumber3(n3); - } else { - r = new BigNumber3(s2 + ""); - } - if (r.c[0]) { - e2 = r.e; - s2 = e2 + dp; - if (s2 < 3) - s2 = 0; - for (; ; ) { - t = r; - r = half.times(t.plus(div(x3, t, dp, 1))); - if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { - if (r.e < e2) - --s2; - n3 = n3.slice(s2 - 3, s2 + 1); - if (n3 == "9999" || !rep && n3 == "4999") { - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - if (t.times(t).eq(x3)) { - r = t; - break; - } - } - dp += 4; - s2 += 4; - rep = 1; - } else { - if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m3 = !r.times(r).eq(x3); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); - }; - P2.toExponential = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp++; - } - return format(this, dp, rm, 1); - }; - P2.toFixed = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P2.toFormat = function(dp, rm, format2) { - var str, x3 = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError2 + "Argument not an object: " + format2); - } - str = x3.toFixed(dp, rm); - if (x3.c) { - var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g22) { - i2 = g1; - g1 = g22; - g22 = i2; - len -= i2; - } - if (g1 > 0 && len > 0) { - i2 = len % g1 || g1; - intPart = intDigits.substr(0, i2); - for (; i2 < len; i2 += g1) - intPart += groupSeparator + intDigits.substr(i2, g1); - if (g22 > 0) - intPart += groupSeparator + intDigits.slice(i2); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g22 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P2.toFraction = function(md) { - var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; - if (md != null) { - n3 = new BigNumber3(md); - if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { - throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); - } - } - if (!xc) - return new BigNumber3(x3); - d3 = new BigNumber3(ONE); - n1 = d0 = new BigNumber3(ONE); - d1 = n0 = new BigNumber3(ONE); - s2 = coeffToString2(xc); - e2 = d3.e = s2.length - x3.e - 1; - d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; - md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n3 = new BigNumber3(s2); - n0.c[0] = 0; - for (; ; ) { - q2 = div(n3, d3, 0, 1); - d22 = d0.plus(q2.times(d1)); - if (d22.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d22; - n1 = n0.plus(q2.times(d22 = n1)); - n0 = d22; - d3 = n3.minus(q2.times(d22 = d3)); - n3 = d22; - } - d22 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d22.times(n1)); - d0 = d0.plus(d22.times(d1)); - n0.s = n1.s = x3.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( - div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() - ) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P2.toNumber = function() { - return +valueOf(this); - }; - P2.toPrecision = function(sd, rm) { - if (sd != null) - intCheck2(sd, 1, MAX2); - return format(this, sd, rm, 2); - }; - P2.toString = function(b4) { - var str, n3 = this, s2 = n3.s, e2 = n3.e; - if (e2 === null) { - if (s2) { - str = "Infinity"; - if (s2 < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b4 == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); - } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { - n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); - } - if (s2 < 0 && n3.c[0]) - str = "-" + str; - } - return str; - }; - P2.valueOf = P2.toJSON = function() { - return valueOf(this); - }; - P2._isBigNumber = true; - if (configObject != null) - BigNumber3.set(configObject); - return BigNumber3; - } - function bitFloor2(n3) { - var i2 = n3 | 0; - return n3 > 0 || n3 === i2 ? i2 : i2 - 1; - } - function coeffToString2(a3) { - var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; - for (; i2 < j2; ) { - s2 = a3[i2++] + ""; - z3 = LOG_BASE2 - s2.length; - for (; z3--; s2 = "0" + s2) - ; - r += s2; - } - for (j2 = r.length; r.charCodeAt(--j2) === 48; ) - ; - return r.slice(0, j2 + 1 || 1); - } - function compare3(x3, y4) { - var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; - if (!i2 || !j2) - return null; - a3 = xc && !xc[0]; - b4 = yc && !yc[0]; - if (a3 || b4) - return a3 ? b4 ? 0 : -j2 : i2; - if (i2 != j2) - return i2; - a3 = i2 < 0; - b4 = k4 == l4; - if (!xc || !yc) - return b4 ? 0 : !xc ^ a3 ? 1 : -1; - if (!b4) - return k4 > l4 ^ a3 ? 1 : -1; - j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; - for (i2 = 0; i2 < j2; i2++) - if (xc[i2] != yc[i2]) - return xc[i2] > yc[i2] ^ a3 ? 1 : -1; - return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; - } - function intCheck2(n3, min, max, name2) { - if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { - throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); - } - } - function isOdd2(n3) { - var k4 = n3.c.length - 1; - return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; - } - function toExponential2(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; - } - function toFixedPoint2(str, e2, z3) { - var len, zs; - if (e2 < 0) { - for (zs = z3 + "."; ++e2; zs += z3) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z3, e2 -= len; --e2; zs += z3) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } - } - return str; - } - BigNumber2 = clone2(); - BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; - if (typeof define == "function" && define.amd) { - define(function() { - return BigNumber2; - }); - } else if (typeof module2 != "undefined" && module2.exports) { - module2.exports = BigNumber2; - } else { - if (!globalObject) { - globalObject = typeof self != "undefined" && self ? self : window; - } - globalObject.BigNumber = BigNumber2; - } - })(exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/errors.js -var require_errors = __commonJS({ - "node_modules/@multiversx/sdk-core/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrParseTransactionOutcome = exports2.ErrInvalidInnerTransaction = exports2.ErrBadUsage = exports2.ErrInvalidTokenIdentifier = exports2.ErrIsCompletedFieldIsMissingOnTransaction = exports2.ErrGasLimitShouldBe0ForInnerTransaction = exports2.ErrInvalidRelayedV2BuilderArguments = exports2.ErrInvalidRelayedV1BuilderArguments = exports2.ErrNotImplemented = exports2.ErrContractInteraction = exports2.ErrCodec = exports2.ErrCannotParseTransactionOutcome = exports2.ErrCannotParseContractResults = exports2.ErrMissingFieldOnEnum = exports2.ErrMissingFieldOnStruct = exports2.ErrTypingSystem = exports2.ErrMock = exports2.ErrContractHasNoAddress = exports2.ErrContract = exports2.ErrExpectedTransactionEventsNotFound = exports2.ErrExpectedTransactionStatusNotReached = exports2.ErrTransactionWatcherTimeout = exports2.ErrAsyncTimerAborted = exports2.ErrAsyncTimerAlreadyRunning = exports2.ErrInvalidFunctionName = exports2.ErrSignatureCannotCreate = exports2.ErrTransactionOptionsInvalid = exports2.ErrTransactionVersionInvalid = exports2.ErrNonceInvalid = exports2.ErrNotEnoughGas = exports2.ErrAddressEmpty = exports2.ErrAddressBadHrp = exports2.ErrAddressCannotCreate = exports2.ErrUnexpectedCondition = exports2.ErrInvariantFailed = exports2.ErrBadType = exports2.ErrUnsupportedOperation = exports2.ErrInvalidArgument = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - /** - * Returns a pretty, friendly summary for the error or for the chain of errros (if appropriate). - */ - summary() { - let result = []; - result.push({ name: this.name, message: this.message }); - let inner = this.inner; - while (inner) { - result.push({ name: inner.name, message: inner.message }); - inner = inner.inner; - } - return result; - } - }; - exports2.Err = Err; - var ErrInvalidArgument = class extends Err { - constructor(message, inner) { - super(`Invalid argument: ${message}`, inner); - } - }; - exports2.ErrInvalidArgument = ErrInvalidArgument; - var ErrUnsupportedOperation = class extends Err { - constructor(operation, reason = "not specified") { - super(`Operation "${operation}" not supported. Reason: ${reason}`); - } - }; - exports2.ErrUnsupportedOperation = ErrUnsupportedOperation; - var ErrBadType = class extends Err { - constructor(name2, type, value) { - super(`Bad type of "${name2}": ${value}. Expected type: ${type}`); - } - }; - exports2.ErrBadType = ErrBadType; - var ErrInvariantFailed = class extends Err { - constructor(message) { - super(`Invariant failed: [${message}]`); - } - }; - exports2.ErrInvariantFailed = ErrInvariantFailed; - var ErrUnexpectedCondition = class extends Err { - constructor(message) { - super(`Unexpected condition: [${message}]`); - } - }; - exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; - var ErrAddressCannotCreate = class extends Err { - constructor(input, inner) { - let message = `Cannot create address from: ${input}`; - super(message, inner); - } - }; - exports2.ErrAddressCannotCreate = ErrAddressCannotCreate; - var ErrAddressBadHrp = class extends Err { - constructor(expected, got) { - super(`Wrong address HRP. Expected: ${expected}, got ${got}`); - } - }; - exports2.ErrAddressBadHrp = ErrAddressBadHrp; - var ErrAddressEmpty = class extends Err { - constructor() { - super(`Address is empty`); - } - }; - exports2.ErrAddressEmpty = ErrAddressEmpty; - var ErrNotEnoughGas = class extends Err { - constructor(value) { - super(`Not enough gas provided: ${value}`); - } - }; - exports2.ErrNotEnoughGas = ErrNotEnoughGas; - var ErrNonceInvalid = class extends Err { - constructor(value) { - super(`Invalid nonce: ${value}`); - } - }; - exports2.ErrNonceInvalid = ErrNonceInvalid; - var ErrTransactionVersionInvalid = class extends Err { - constructor(value) { - super(`Invalid transaction version: ${value}`); - } - }; - exports2.ErrTransactionVersionInvalid = ErrTransactionVersionInvalid; - var ErrTransactionOptionsInvalid = class extends Err { - constructor(value) { - super(`Invalid transaction options: ${value}`); - } - }; - exports2.ErrTransactionOptionsInvalid = ErrTransactionOptionsInvalid; - var ErrSignatureCannotCreate = class extends Err { - constructor(input, inner) { - let message = `Cannot create signature from: ${input}`; - super(message, inner); - } - }; - exports2.ErrSignatureCannotCreate = ErrSignatureCannotCreate; - var ErrInvalidFunctionName = class extends Err { - constructor() { - super(`Invalid function name`); - } - }; - exports2.ErrInvalidFunctionName = ErrInvalidFunctionName; - var ErrAsyncTimerAlreadyRunning = class extends Err { - constructor() { - super("Async timer already running"); - } - }; - exports2.ErrAsyncTimerAlreadyRunning = ErrAsyncTimerAlreadyRunning; - var ErrAsyncTimerAborted = class extends Err { - constructor() { - super("Async timer aborted"); - } - }; - exports2.ErrAsyncTimerAborted = ErrAsyncTimerAborted; - var ErrTransactionWatcherTimeout = class extends Err { - constructor() { - super(`TransactionWatcher has timed out`); - } - }; - exports2.ErrTransactionWatcherTimeout = ErrTransactionWatcherTimeout; - var ErrExpectedTransactionStatusNotReached = class extends Err { - constructor() { - super(`Expected transaction status not reached`); - } - }; - exports2.ErrExpectedTransactionStatusNotReached = ErrExpectedTransactionStatusNotReached; - var ErrExpectedTransactionEventsNotFound = class extends Err { - constructor() { - super(`Expected transaction events not found`); - } - }; - exports2.ErrExpectedTransactionEventsNotFound = ErrExpectedTransactionEventsNotFound; - var ErrContract = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrContract = ErrContract; - var ErrContractHasNoAddress = class extends ErrContract { - constructor() { - super(` +var ck=Object.create;var Rd=Object.defineProperty;var lk=Object.getOwnPropertyDescriptor;var fk=Object.getOwnPropertyNames;var hk=Object.getPrototypeOf,dk=Object.prototype.hasOwnProperty;var Bd=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)Rd(t,r,{get:e[r],enumerable:!0})},Pd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fk(e))!dk.call(t,i)&&i!==r&&Rd(t,i,{get:()=>e[i],enumerable:!(n=lk(e,i))||n.enumerable});return t},Tr=(t,e,r)=>(Pd(t,e,"default"),r&&Pd(r,e,"default")),pe=(t,e,r)=>(r=t!=null?ck(hk(t)):{},Pd(e||!t||!t.__esModule?Rd(r,"default",{value:t,enumerable:!0}):r,t)),_e=t=>Pd(Rd({},"__esModule",{value:!0}),t);var w3=B(Md=>{"use strict";h();Md.byteLength=pk;Md.toByteArray=yk;Md.fromByteArray=Ak;var Pi=[],Tn=[],gk=typeof Uint8Array<"u"?Uint8Array:Array,mw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ba=0,m3=mw.length;ba0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function pk(t){var e=y3(t),r=e[0],n=e[1];return(r+n)*3/4-n}function mk(t,e,r){return(e+r)*3/4-r}function yk(t){var e,r=y3(t),n=r[0],i=r[1],s=new gk(mk(t,n,i)),o=0,u=i>0?n-4:n,a;for(a=0;a>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tn[t.charCodeAt(a)]<<2|Tn[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=Tn[t.charCodeAt(a)]<<10|Tn[t.charCodeAt(a+1)]<<4|Tn[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function wk(t){return Pi[t>>18&63]+Pi[t>>12&63]+Pi[t>>6&63]+Pi[t&63]}function vk(t,e,r){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=t[r-1],i.push(Pi[e>>2]+Pi[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Pi[e>>10]+Pi[e>>4&63]+Pi[e<<2&63]+"=")),i.join("")}});var v3=B(yw=>{h();yw.read=function(t,e,r,n,i){var s,o,u=i*8-n-1,a=(1<>1,f=-7,d=r?i-1:0,w=r?-1:1,A=t[e+d];for(d+=w,s=A&(1<<-f)-1,A>>=-f,f+=u;f>0;s=s*256+t[e+d],d+=w,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=w,f-=8);if(s===0)s=1-c;else{if(s===a)return o?NaN:(A?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(A?-1:1)*o*Math.pow(2,s-n)};yw.write=function(t,e,r,n,i,s){var o,u,a,c=s*8-i-1,f=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:s-1,T=n?1:-1,x=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=w/a:e+=w*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=f?(u=0,o=f):o+d>=1?(u=(e*a-1)*Math.pow(2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+A]=u&255,A+=T,u/=256,i-=8);for(o=o<0;t[r+A]=o&255,A+=T,o/=256,c-=8);t[r+A-T]|=x*128}});var io=B(Nu=>{"use strict";h();var ww=w3(),Cu=v3(),A3=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nu.Buffer=X;Nu.SlowBuffer=_k;Nu.INSPECT_MAX_BYTES=50;var Ld=2147483647;Nu.kMaxLength=Ld;X.TYPED_ARRAY_SUPPORT=Ek();!X.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 Ek(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(X.prototype,"parent",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.buffer}});Object.defineProperty(X.prototype,"offset",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.byteOffset}});function Cs(t){if(t>Ld)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,X.prototype),e}function X(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return bw(t)}return S3(t,e,r)}X.poolSize=8192;function S3(t,e,r){if(typeof t=="string")return Sk(t,e);if(ArrayBuffer.isView(t))return Ik(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Ri(t,ArrayBuffer)||t&&Ri(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ri(t,SharedArrayBuffer)||t&&Ri(t.buffer,SharedArrayBuffer)))return Aw(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return X.from(n,e,r);var i=Tk(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return X.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}X.from=function(t,e,r){return S3(t,e,r)};Object.setPrototypeOf(X.prototype,Uint8Array.prototype);Object.setPrototypeOf(X,Uint8Array);function I3(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function bk(t,e,r){return I3(t),t<=0?Cs(t):e!==void 0?typeof r=="string"?Cs(t).fill(e,r):Cs(t).fill(e):Cs(t)}X.alloc=function(t,e,r){return bk(t,e,r)};function bw(t){return I3(t),Cs(t<0?0:Sw(t)|0)}X.allocUnsafe=function(t){return bw(t)};X.allocUnsafeSlow=function(t){return bw(t)};function Sk(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!X.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=T3(t,e)|0,n=Cs(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function vw(t){for(var e=t.length<0?0:Sw(t.length)|0,r=Cs(e),n=0;n=Ld)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ld.toString(16)+" bytes");return t|0}function _k(t){return+t!=t&&(t=0),X.alloc(+t)}X.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==X.prototype};X.compare=function(e,r){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),Ri(r,Uint8Array)&&(r=X.from(r,r.offset,r.byteLength)),!X.isBuffer(e)||!X.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?X.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(X.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function T3(t,e){if(X.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ri(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Ew(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return D3(t).length;default:if(i)return n?-1:Ew(t).length;e=(""+e).toLowerCase(),i=!0}}X.byteLength=T3;function Ck(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return Fk(this,e,r);case"utf8":case"utf-8":return C3(this,e,r);case"ascii":return Mk(this,e,r);case"latin1":case"binary":return Lk(this,e,r);case"base64":return Rk(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Uk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}X.prototype._isBuffer=!0;function Sa(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}X.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};A3&&(X.prototype[A3]=X.prototype.inspect);X.prototype.compare=function(e,r,n,i,s){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),!X.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=n-r,a=Math.min(o,u),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Iw(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=X.from(e,n)),X.isBuffer(e))return e.length===0?-1:E3(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):E3(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function E3(t,e,r,n,i){var s=1,o=t.length,u=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,u/=2,r/=2}function a(A,T){return s===1?A[T]:A.readUInt16BE(T*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-u),c=r;c>=0;c--){for(var d=!0,w=0;wi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Nk(this,e,r,n);case"utf8":case"utf-8":return xk(this,e,r,n);case"ascii":case"latin1":case"binary":return Ok(this,e,r,n);case"base64":return Dk(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Pk(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Rk(t,e,r){return e===0&&r===t.length?ww.fromByteArray(t):ww.fromByteArray(t.slice(e,r))}function C3(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+u<=r){var a,c,f,d;switch(u){case 1:s<128&&(o=s);break;case 2:a=t[i+1],(a&192)===128&&(d=(s&31)<<6|a&63,d>127&&(o=d));break;case 3:a=t[i+1],c=t[i+2],(a&192)===128&&(c&192)===128&&(d=(s&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:a=t[i+1],c=t[i+2],f=t[i+3],(a&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(a&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=u}return Bk(n)}var b3=4096;function Bk(t){var e=t.length;if(e<=b3)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}X.prototype.readUintLE=X.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};X.prototype.readUint8=X.prototype.readUInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]};X.prototype.readUint16LE=X.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]|this[e+1]<<8};X.prototype.readUint16BE=X.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]<<8|this[e+1]};X.prototype.readUint32LE=X.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};X.prototype.readUint32BE=X.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};X.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};X.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};X.prototype.readInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};X.prototype.readInt16LE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};X.prototype.readInt16BE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};X.prototype.readInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};X.prototype.readInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};X.prototype.readFloatLE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!0,23,4)};X.prototype.readFloatBE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!1,23,4)};X.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!0,52,8)};X.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!1,52,8)};function zr(t,e,r,n,i,s){if(!X.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}X.prototype.writeUintLE=X.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=1,u=0;for(this[r]=e&255;++u>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=n-1,u=1;for(this[r+o]=e&255;--o>=0&&(u*=256);)this[r+o]=e/u&255;return r+n};X.prototype.writeUint8=X.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,255,0),this[r]=e&255,r+1};X.prototype.writeUint16LE=X.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeUint16BE=X.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeUint32LE=X.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};X.prototype.writeUint32BE=X.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};X.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=0,u=1,a=0;for(this[r]=e&255;++o>0)-a&255;return r+n};X.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=n-1,u=1,a=0;for(this[r+o]=e&255;--o>=0&&(u*=256);)e<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(e/u>>0)-a&255;return r+n};X.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};X.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};X.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function N3(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function x3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,4,34028234663852886e22,-34028234663852886e22),Cu.write(t,e,r,n,23,4),r+4}X.prototype.writeFloatLE=function(e,r,n){return x3(this,e,r,!0,n)};X.prototype.writeFloatBE=function(e,r,n){return x3(this,e,r,!1,n)};function O3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,8,17976931348623157e292,-17976931348623157e292),Cu.write(t,e,r,n,52,8),r+8}X.prototype.writeDoubleLE=function(e,r,n){return O3(this,e,r,!0,n)};X.prototype.writeDoubleBE=function(e,r,n){return O3(this,e,r,!1,n)};X.prototype.copy=function(e,r,n,i){if(!X.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function kk(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function D3(t){return ww.toByteArray(Vk(t))}function Fd(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Ri(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Iw(t){return t!==t}var Gk=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var L3=B((kge,M3)=>{h();var Wt=M3.exports={},Bi,Mi;function Tw(){throw new Error("setTimeout has not been defined")}function _w(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Bi=setTimeout:Bi=Tw}catch{Bi=Tw}try{typeof clearTimeout=="function"?Mi=clearTimeout:Mi=_w}catch{Mi=_w}})();function P3(t){if(Bi===setTimeout)return setTimeout(t,0);if((Bi===Tw||!Bi)&&setTimeout)return Bi=setTimeout,setTimeout(t,0);try{return Bi(t,0)}catch{try{return Bi.call(null,t,0)}catch{return Bi.call(this,t,0)}}}function jk(t){if(Mi===clearTimeout)return clearTimeout(t);if((Mi===_w||!Mi)&&clearTimeout)return Mi=clearTimeout,clearTimeout(t);try{return Mi(t)}catch{try{return Mi.call(null,t)}catch{return Mi.call(this,t)}}}var Ns=[],xu=!1,Ia,Ud=-1;function zk(){!xu||!Ia||(xu=!1,Ia.length?Ns=Ia.concat(Ns):Ud=-1,Ns.length&&R3())}function R3(){if(!xu){var t=P3(zk);xu=!0;for(var e=Ns.length;e;){for(Ia=Ns,Ns=[];++Ud1)for(var r=1;r{p=pe(io()),I=pe(L3()),Qk=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=Qk});var fr={};Bt(fr,{BigNumber:()=>q3,default:()=>Ou});function U3(t){var e,r,n,i=U.prototype={constructor:U,toString:null,valueOf:null},s=new U(1),o=20,u=4,a=-7,c=21,f=-1e7,d=1e7,w=!1,A=1,T=0,x={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},R="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function U(v,C){var D,F,P,l,g,y,E,S,_=this;if(!(_ instanceof U))return new U(v,C);if(C==null){if(v&&v._isBigNumber===!0){_.s=v.s,!v.c||v.e>d?_.c=_.e=null:v.e=10;g/=10,l++);l>d?_.c=_.e=null:(_.e=l,_.c=[v]);return}S=String(v)}else{if(!Kk.test(S=String(v)))return n(_,S,y);_.s=S.charCodeAt(0)==45?(S=S.slice(1),-1):1}(l=S.indexOf("."))>-1&&(S=S.replace(".","")),(g=S.search(/e/i))>0?(l<0&&(l=g),l+=+S.slice(g+1),S=S.substring(0,g)):l<0&&(l=S.length)}else{if(Ht(C,2,R.length,"Base"),C==10&&V)return _=new U(v),H(_,o+_.e+1,u);if(S=String(v),y=typeof v=="number"){if(v*0!=0)return n(_,S,y,C);if(_.s=1/v<0?(S=S.slice(1),-1):1,U.DEBUG&&S.replace(/^0\.0*|\./,"").length>15)throw Error(F3+v)}else _.s=S.charCodeAt(0)===45?(S=S.slice(1),-1):1;for(D=R.slice(0,C),l=g=0,E=S.length;gl){l=E;continue}}else if(!P&&(S==S.toUpperCase()&&(S=S.toLowerCase())||S==S.toLowerCase()&&(S=S.toUpperCase()))){P=!0,g=-1,l=0;continue}return n(_,String(v),y,C)}y=!1,S=r(S,C,10,_.s),(l=S.indexOf("."))>-1?S=S.replace(".",""):l=S.length}for(g=0;S.charCodeAt(g)===48;g++);for(E=S.length;S.charCodeAt(--E)===48;);if(S=S.slice(g,++E)){if(E-=g,y&&U.DEBUG&&E>15&&(v>Nw||v!==Cn(v)))throw Error(F3+_.s*v);if((l=l-g-1)>d)_.c=_.e=null;else if(l=-mr&&P<=mr&&P===Cn(P)){if(F[0]===0){if(P===0&&F.length===1)return!0;break e}if(C=(P+1)%be,C<1&&(C+=be),String(F[0]).length==C){for(C=0;C=di||D!==Cn(D))break e;if(D!==0)return!0}}}else if(F===null&&P===null&&(l===null||l===1||l===-1))return!0;throw Error(Qr+"Invalid BigNumber: "+v)},U.maximum=U.max=function(){return L(arguments,-1)},U.minimum=U.min=function(){return L(arguments,1)},U.random=function(){var v=9007199254740992,C=Math.random()*v&2097151?function(){return Cn(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var F,P,l,g,y,E=0,S=[],_=new U(s);if(D==null?D=o:Ht(D,0,mr),g=Cw(D/be),w)if(crypto.getRandomValues){for(F=crypto.getRandomValues(new Uint32Array(g*=2));E>>11),y>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),F[E]=P[0],F[E+1]=P[1]):(S.push(y%1e14),E+=2);E=g/2}else if(crypto.randomBytes){for(F=crypto.randomBytes(g*=7);E=9e15?crypto.randomBytes(7).copy(F,E):(S.push(y%1e14),E+=7);E=g/7}else throw w=!1,Error(Qr+"crypto unavailable");if(!w)for(;E=10;y/=10,E++);EP-1&&(y[g+1]==null&&(y[g+1]=0),y[g+1]+=y[g]/P|0,y[g]%=P)}return y.reverse()}return function(D,F,P,l,g){var y,E,S,_,M,N,m,O,Y=D.indexOf("."),$=o,b=u;for(Y>=0&&(_=T,T=0,D=D.replace(".",""),O=new U(F),N=O.pow(D.length-Y),T=_,O.c=C(Os(_n(N.c),N.e,"0"),10,P,v),O.e=O.c.length),m=C(D,F,P,g?(y=R,v):(y=v,R)),S=_=m.length;m[--_]==0;m.pop());if(!m[0])return y.charAt(0);if(Y<0?--S:(N.c=m,N.e=S,N.s=l,N=e(N,O,$,b,P),m=N.c,M=N.r,S=N.e),E=S+$+1,Y=m[E],_=P/2,M=M||E<0||m[E+1]!=null,M=b<4?(Y!=null||M)&&(b==0||b==(N.s<0?3:2)):Y>_||Y==_&&(b==4||M||b==6&&m[E-1]&1||b==(N.s<0?8:7)),E<1||!m[0])D=M?Os(y.charAt(1),-$,y.charAt(0)):y.charAt(0);else{if(m.length=E,M)for(--P;++m[--E]>P;)m[E]=0,E||(++S,m=[1].concat(m));for(_=m.length;!m[--_];);for(Y=0,D="";Y<=_;D+=y.charAt(m[Y++]));D=Os(D,S,y.charAt(0))}return D}}(),e=function(){function v(F,P,l){var g,y,E,S,_=0,M=F.length,N=P%so,m=P/so|0;for(F=F.slice();M--;)E=F[M]%so,S=F[M]/so|0,g=m*E+S*N,y=N*E+g%so*so+_,_=(y/l|0)+(g/so|0)+m*S,F[M]=y%l;return _&&(F=[_].concat(F)),F}function C(F,P,l,g){var y,E;if(l!=g)E=l>g?1:-1;else for(y=E=0;yP[y]?1:-1;break}return E}function D(F,P,l,g){for(var y=0;l--;)F[l]-=y,y=F[l]1;F.splice(0,1));}return function(F,P,l,g,y){var E,S,_,M,N,m,O,Y,$,b,j,z,W,ie,te,ee,se,oe=F.s==P.s?1:-1,J=F.c,ue=P.c;if(!J||!J[0]||!ue||!ue[0])return new U(!F.s||!P.s||(J?ue&&J[0]==ue[0]:!ue)?NaN:J&&J[0]==0||!ue?oe*0:oe/0);for(Y=new U(oe),$=Y.c=[],S=F.e-P.e,oe=l+S+1,y||(y=di,S=Nn(F.e/be)-Nn(P.e/be),oe=oe/be|0),_=0;ue[_]==(J[_]||0);_++);if(ue[_]>(J[_]||0)&&S--,oe<0)$.push(1),M=!0;else{for(ie=J.length,ee=ue.length,_=0,oe+=2,N=Cn(y/(ue[0]+1)),N>1&&(ue=v(ue,N,y),J=v(J,N,y),ee=ue.length,ie=J.length),W=ee,b=J.slice(0,ee),j=b.length;j=y/2&&te++;do{if(N=0,E=C(ue,b,ee,j),E<0){if(z=b[0],ee!=j&&(z=z*y+(b[1]||0)),N=Cn(z/te),N>1)for(N>=y&&(N=y-1),m=v(ue,N,y),O=m.length,j=b.length;C(m,b,O,j)==1;)N--,D(m,ee=10;oe/=10,_++);H(Y,l+(Y.e=_+S*be-1)+1,g,M)}else Y.e=S,Y.r=+M;return Y}}();function Q(v,C,D,F){var P,l,g,y,E;if(D==null?D=u:Ht(D,0,8),!v.c)return v.toString();if(P=v.c[0],g=v.e,C==null)E=_n(v.c),E=F==1||F==2&&(g<=a||g>=c)?Vd(E,g):Os(E,g,"0");else if(v=H(new U(v),C,D),l=v.e,E=_n(v.c),y=E.length,F==1||F==2&&(C<=l||l<=a)){for(;yy){if(--C>0)for(E+=".";C--;E+="0");}else if(C+=l-y,C>0)for(l+1==y&&(E+=".");C--;E+="0");return v.s<0&&P?"-"+E:E}function L(v,C){for(var D,F,P=1,l=new U(v[0]);P=10;P/=10,F++);return(D=F+D*be-1)>d?v.c=v.e=null:D=10;y/=10,P++);if(l=C-P,l<0)l+=be,g=C,E=M[S=0],_=Cn(E/N[P-g-1]%10);else if(S=Cw((l+1)/be),S>=M.length)if(F){for(;M.length<=S;M.push(0));E=_=0,P=1,l%=be,g=l-be+1}else break e;else{for(E=y=M[S],P=1;y>=10;y/=10,P++);l%=be,g=l-be+P,_=g<0?0:Cn(E/N[P-g-1]%10)}if(F=F||C<0||M[S+1]!=null||(g<0?E:E%N[P-g-1]),F=D<4?(_||F)&&(D==0||D==(v.s<0?3:2)):_>5||_==5&&(D==4||F||D==6&&(l>0?g>0?E/N[P-g]:0:M[S-1])%10&1||D==(v.s<0?8:7)),C<1||!M[0])return M.length=0,F?(C-=v.e+1,M[0]=N[(be-C%be)%be],v.e=-C||0):M[0]=v.e=0,v;if(l==0?(M.length=S,y=1,S--):(M.length=S+1,y=N[be-l],M[S]=g>0?Cn(E/N[P-g]%N[g])*y:0),F)for(;;)if(S==0){for(l=1,g=M[0];g>=10;g/=10,l++);for(g=M[0]+=y,y=1;g>=10;g/=10,y++);l!=y&&(v.e++,M[0]==di&&(M[0]=1));break}else{if(M[S]+=y,M[S]!=di)break;M[S--]=0,y=1}for(l=M.length;M[--l]===0;M.pop());}v.e>d?v.c=v.e=null:v.e=c?Vd(C,D):Os(C,D,"0"),v.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var v=new U(this);return v.s<0&&(v.s=1),v},i.comparedTo=function(v,C){return Ta(this,new U(v,C))},i.decimalPlaces=i.dp=function(v,C){var D,F,P,l=this;if(v!=null)return Ht(v,0,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v+l.e+1,C);if(!(D=l.c))return null;if(F=((P=D.length-1)-Nn(this.e/be))*be,P=D[P])for(;P%10==0;P/=10,F--);return F<0&&(F=0),F},i.dividedBy=i.div=function(v,C){return e(this,new U(v,C),o,u)},i.dividedToIntegerBy=i.idiv=function(v,C){return e(this,new U(v,C),0,1)},i.exponentiatedBy=i.pow=function(v,C){var D,F,P,l,g,y,E,S,_,M=this;if(v=new U(v),v.c&&!v.isInteger())throw Error(Qr+"Exponent not an integer: "+q(v));if(C!=null&&(C=new U(C)),y=v.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!v.c||!v.c[0])return _=new U(Math.pow(+q(M),y?v.s*(2-qd(v)):+q(v))),C?_.mod(C):_;if(E=v.s<0,C){if(C.c?!C.c[0]:!C.s)return new U(NaN);F=!E&&M.isInteger()&&C.isInteger(),F&&(M=M.mod(C))}else{if(v.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||y&&M.c[1]>=24e7:M.c[0]<8e13||y&&M.c[0]<=9999975e7)))return l=M.s<0&&qd(v)?-0:0,M.e>-1&&(l=1/l),new U(E?1/l:l);T&&(l=Cw(T/be+2))}for(y?(D=new U(.5),E&&(v.s=1),S=qd(v)):(P=Math.abs(+q(v)),S=P%2),_=new U(s);;){if(S){if(_=_.times(M),!_.c)break;l?_.c.length>l&&(_.c.length=l):F&&(_=_.mod(C))}if(P){if(P=Cn(P/2),P===0)break;S=P%2}else if(v=v.times(D),H(v,v.e+1,1),v.e>14)S=qd(v);else{if(P=+q(v),P===0)break;S=P%2}M=M.times(M),l?M.c&&M.c.length>l&&(M.c.length=l):F&&(M=M.mod(C))}return F?_:(E&&(_=s.div(_)),C?_.mod(C):l?H(_,T,u,g):_)},i.integerValue=function(v){var C=new U(this);return v==null?v=u:Ht(v,0,8),H(C,C.e+1,v)},i.isEqualTo=i.eq=function(v,C){return Ta(this,new U(v,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(v,C){return Ta(this,new U(v,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(v,C){return(C=Ta(this,new U(v,C)))===1||C===0},i.isInteger=function(){return!!this.c&&Nn(this.e/be)>this.c.length-2},i.isLessThan=i.lt=function(v,C){return Ta(this,new U(v,C))<0},i.isLessThanOrEqualTo=i.lte=function(v,C){return(C=Ta(this,new U(v,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(v,C){var D,F,P,l,g=this,y=g.s;if(v=new U(v,C),C=v.s,!y||!C)return new U(NaN);if(y!=C)return v.s=-C,g.plus(v);var E=g.e/be,S=v.e/be,_=g.c,M=v.c;if(!E||!S){if(!_||!M)return _?(v.s=-C,v):new U(M?g:NaN);if(!_[0]||!M[0])return M[0]?(v.s=-C,v):new U(_[0]?g:u==3?-0:0)}if(E=Nn(E),S=Nn(S),_=_.slice(),y=E-S){for((l=y<0)?(y=-y,P=_):(S=E,P=M),P.reverse(),C=y;C--;P.push(0));P.reverse()}else for(F=(l=(y=_.length)<(C=M.length))?y:C,y=C=0;C0)for(;C--;_[D++]=0);for(C=di-1;F>y;){if(_[--F]=0;){for(D=0,N=z[P]%$,m=z[P]/$|0,g=E,l=P+g;l>P;)S=j[--g]%$,_=j[g]/$|0,y=m*S+_*N,S=N*S+y%$*$+O[l]+D,D=(S/Y|0)+(y/$|0)+m*_,O[l--]=S%Y;O[l]=D}return D?++F:O.splice(0,1),k(v,O,F)},i.negated=function(){var v=new U(this);return v.s=-v.s||null,v},i.plus=function(v,C){var D,F=this,P=F.s;if(v=new U(v,C),C=v.s,!P||!C)return new U(NaN);if(P!=C)return v.s=-C,F.minus(v);var l=F.e/be,g=v.e/be,y=F.c,E=v.c;if(!l||!g){if(!y||!E)return new U(P/0);if(!y[0]||!E[0])return E[0]?v:new U(y[0]?F:P*0)}if(l=Nn(l),g=Nn(g),y=y.slice(),P=l-g){for(P>0?(g=l,D=E):(P=-P,D=y),D.reverse();P--;D.push(0));D.reverse()}for(P=y.length,C=E.length,P-C<0&&(D=E,E=y,y=D,C=P),P=0;C;)P=(y[--C]=y[C]+E[C]+P)/di|0,y[C]=di===y[C]?0:y[C]%di;return P&&(y=[P].concat(y),++g),k(v,y,g)},i.precision=i.sd=function(v,C){var D,F,P,l=this;if(v!=null&&v!==!!v)return Ht(v,1,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v,C);if(!(D=l.c))return null;if(P=D.length-1,F=P*be+1,P=D[P]){for(;P%10==0;P/=10,F--);for(P=D[0];P>=10;P/=10,F++);}return v&&l.e+1>F&&(F=l.e+1),F},i.shiftedBy=function(v){return Ht(v,-Nw,Nw),this.times("1e"+v)},i.squareRoot=i.sqrt=function(){var v,C,D,F,P,l=this,g=l.c,y=l.s,E=l.e,S=o+4,_=new U("0.5");if(y!==1||!g||!g[0])return new U(!y||y<0&&(!g||g[0])?NaN:g?l:1/0);if(y=Math.sqrt(+q(l)),y==0||y==1/0?(C=_n(g),(C.length+E)%2==0&&(C+="0"),y=Math.sqrt(+C),E=Nn((E+1)/2)-(E<0||E%2),y==1/0?C="5e"+E:(C=y.toExponential(),C=C.slice(0,C.indexOf("e")+1)+E),D=new U(C)):D=new U(y+""),D.c[0]){for(E=D.e,y=E+S,y<3&&(y=0);;)if(P=D,D=_.times(P.plus(e(l,P,S,1))),_n(P.c).slice(0,y)===(C=_n(D.c)).slice(0,y))if(D.e0&&O>0){for(l=O%y||y,_=m.substr(0,l);l0&&(_+=S+m.slice(l)),N&&(_="-"+_)}F=M?_+(D.decimalSeparator||"")+((E=+D.fractionGroupSize)?M.replace(new RegExp("\\d{"+E+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):M):_}return(D.prefix||"")+F+(D.suffix||"")},i.toFraction=function(v){var C,D,F,P,l,g,y,E,S,_,M,N,m=this,O=m.c;if(v!=null&&(y=new U(v),!y.isInteger()&&(y.c||y.s!==1)||y.lt(s)))throw Error(Qr+"Argument "+(y.isInteger()?"out of range: ":"not an integer: ")+q(y));if(!O)return new U(m);for(C=new U(s),S=D=new U(s),F=E=new U(s),N=_n(O),l=C.e=N.length-m.e-1,C.c[0]=xw[(g=l%be)<0?be+g:g],v=!v||y.comparedTo(C)>0?l>0?C:S:y,g=d,d=1/0,y=new U(N),E.c[0]=0;_=e(y,C,0,1),P=D.plus(_.times(F)),P.comparedTo(v)!=1;)D=F,F=P,S=E.plus(_.times(P=S)),E=P,C=y.minus(_.times(P=C)),y=P;return P=e(v.minus(D),F,0,1),E=E.plus(P.times(S)),D=D.plus(P.times(F)),E.s=S.s=m.s,l=l*2,M=e(S,F,l,u).minus(m).abs().comparedTo(e(E,D,l,u).minus(m).abs())<1?[S,F]:[E,D],d=g,M},i.toNumber=function(){return+q(this)},i.toPrecision=function(v,C){return v!=null&&Ht(v,1,mr),Q(this,v,C,2)},i.toString=function(v){var C,D=this,F=D.s,P=D.e;return P===null?F?(C="Infinity",F<0&&(C="-"+C)):C="NaN":(v==null?C=P<=a||P>=c?Vd(_n(D.c),P):Os(_n(D.c),P,"0"):v===10&&V?(D=H(new U(D),o+P+1,u),C=Os(_n(D.c),D.e,"0")):(Ht(v,2,R.length,"Base"),C=r(Os(_n(D.c),P,"0"),10,v,F,!0)),F<0&&D.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return q(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&U.set(t),U}function Nn(t){var e=t|0;return t>0||t===e?e:e-1}function _n(t){for(var e,r,n=1,i=t.length,s=t[0]+"";nc^r?1:-1;for(u=(a=i.length)<(c=s.length)?a:c,o=0;os[o]^r?1:-1;return a==c?0:a>c^r?1:-1}function Ht(t,e,r,n){if(tr||t!==Cn(t))throw Error(Qr+(n||"Argument")+(typeof t=="number"?tr?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function qd(t){var e=t.c.length-1;return Nn(t.e/be)==e&&t.c[e]%2!=0}function Vd(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Os(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e{h();Kk=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Cw=Math.ceil,Cn=Math.floor,Qr="[BigNumber Error] ",F3=Qr+"Number primitive has more than 15 significant digits: ",di=1e14,be=14,Nw=9007199254740991,xw=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],so=1e7,mr=1e9;q3=U3(),Ou=q3});var Ie=B(ce=>{"use strict";h();Object.defineProperty(ce,"__esModule",{value:!0});ce.ErrParseTransactionOutcome=ce.ErrInvalidInnerTransaction=ce.ErrBadUsage=ce.ErrInvalidTokenIdentifier=ce.ErrIsCompletedFieldIsMissingOnTransaction=ce.ErrGasLimitShouldBe0ForInnerTransaction=ce.ErrInvalidRelayedV2BuilderArguments=ce.ErrInvalidRelayedV1BuilderArguments=ce.ErrNotImplemented=ce.ErrContractInteraction=ce.ErrCodec=ce.ErrCannotParseTransactionOutcome=ce.ErrCannotParseContractResults=ce.ErrMissingFieldOnEnum=ce.ErrMissingFieldOnStruct=ce.ErrTypingSystem=ce.ErrMock=ce.ErrContractHasNoAddress=ce.ErrContract=ce.ErrExpectedTransactionEventsNotFound=ce.ErrExpectedTransactionStatusNotReached=ce.ErrTransactionWatcherTimeout=ce.ErrAsyncTimerAborted=ce.ErrAsyncTimerAlreadyRunning=ce.ErrInvalidFunctionName=ce.ErrSignatureCannotCreate=ce.ErrTransactionOptionsInvalid=ce.ErrTransactionVersionInvalid=ce.ErrNonceInvalid=ce.ErrNotEnoughGas=ce.ErrAddressEmpty=ce.ErrAddressBadHrp=ce.ErrAddressCannotCreate=ce.ErrUnexpectedCondition=ce.ErrInvariantFailed=ce.ErrBadType=ce.ErrUnsupportedOperation=ce.ErrInvalidArgument=ce.Err=void 0;var Ce=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};ce.Err=Ce;var Ow=class extends Ce{constructor(e,r){super(`Invalid argument: ${e}`,r)}};ce.ErrInvalidArgument=Ow;var Dw=class extends Ce{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};ce.ErrUnsupportedOperation=Dw;var Pw=class extends Ce{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};ce.ErrBadType=Pw;var Rw=class extends Ce{constructor(e){super(`Invariant failed: [${e}]`)}};ce.ErrInvariantFailed=Rw;var Bw=class extends Ce{constructor(e){super(`Unexpected condition: [${e}]`)}};ce.ErrUnexpectedCondition=Bw;var Mw=class extends Ce{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};ce.ErrAddressCannotCreate=Mw;var Lw=class extends Ce{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};ce.ErrAddressBadHrp=Lw;var Fw=class extends Ce{constructor(){super("Address is empty")}};ce.ErrAddressEmpty=Fw;var Uw=class extends Ce{constructor(e){super(`Not enough gas provided: ${e}`)}};ce.ErrNotEnoughGas=Uw;var qw=class extends Ce{constructor(e){super(`Invalid nonce: ${e}`)}};ce.ErrNonceInvalid=qw;var Vw=class extends Ce{constructor(e){super(`Invalid transaction version: ${e}`)}};ce.ErrTransactionVersionInvalid=Vw;var kw=class extends Ce{constructor(e){super(`Invalid transaction options: ${e}`)}};ce.ErrTransactionOptionsInvalid=kw;var Hw=class extends Ce{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};ce.ErrSignatureCannotCreate=Hw;var Gw=class extends Ce{constructor(){super("Invalid function name")}};ce.ErrInvalidFunctionName=Gw;var jw=class extends Ce{constructor(){super("Async timer already running")}};ce.ErrAsyncTimerAlreadyRunning=jw;var zw=class extends Ce{constructor(){super("Async timer aborted")}};ce.ErrAsyncTimerAborted=zw;var Qw=class extends Ce{constructor(){super("TransactionWatcher has timed out")}};ce.ErrTransactionWatcherTimeout=Qw;var Kw=class extends Ce{constructor(){super("Expected transaction status not reached")}};ce.ErrExpectedTransactionStatusNotReached=Kw;var Ww=class extends Ce{constructor(){super("Expected transaction events not found")}};ce.ErrExpectedTransactionEventsNotFound=Ww;var kd=class extends Ce{constructor(e){super(e)}};ce.ErrContract=kd;var $w=class extends kd{constructor(){super(` The smart contract has no address set. Make sure you provide the address in the constructor, or call setAddress() appropriately. If you need to recompute the address of the contract, make use of SmartContract.computeAddress() (static method). -`); - } - }; - exports2.ErrContractHasNoAddress = ErrContractHasNoAddress; - var ErrMock = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrMock = ErrMock; - var ErrTypingSystem = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrTypingSystem = ErrTypingSystem; - var ErrMissingFieldOnStruct = class extends Err { - constructor(fieldName, structName) { - super(`field ${fieldName} does not exist on struct ${structName}`); - } - }; - exports2.ErrMissingFieldOnStruct = ErrMissingFieldOnStruct; - var ErrMissingFieldOnEnum = class extends Err { - constructor(fieldName, enumName) { - super(`field ${fieldName} does not exist on enum ${enumName}`); - } - }; - exports2.ErrMissingFieldOnEnum = ErrMissingFieldOnEnum; - var ErrCannotParseContractResults = class extends Err { - constructor(details) { - super(`cannot parse contract results: ${details}`); - } - }; - exports2.ErrCannotParseContractResults = ErrCannotParseContractResults; - var ErrCannotParseTransactionOutcome = class extends Err { - constructor(transactionHash, message) { - super(`cannot parse outcome of transaction ${transactionHash}: ${message}`); - } - }; - exports2.ErrCannotParseTransactionOutcome = ErrCannotParseTransactionOutcome; - var ErrCodec = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrCodec = ErrCodec; - var ErrContractInteraction = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrContractInteraction = ErrContractInteraction; - var ErrNotImplemented = class extends Err { - constructor() { - super("Method not yet implemented"); - } - }; - exports2.ErrNotImplemented = ErrNotImplemented; - var ErrInvalidRelayedV1BuilderArguments = class extends Err { - constructor() { - super("invalid arguments for relayed v1 builder"); - } - }; - exports2.ErrInvalidRelayedV1BuilderArguments = ErrInvalidRelayedV1BuilderArguments; - var ErrInvalidRelayedV2BuilderArguments = class extends Err { - constructor() { - super("invalid arguments for relayed v2 builder"); - } - }; - exports2.ErrInvalidRelayedV2BuilderArguments = ErrInvalidRelayedV2BuilderArguments; - var ErrGasLimitShouldBe0ForInnerTransaction = class extends Err { - constructor() { - super("gas limit must be 0 for the inner transaction for relayed v2"); - } - }; - exports2.ErrGasLimitShouldBe0ForInnerTransaction = ErrGasLimitShouldBe0ForInnerTransaction; - var ErrIsCompletedFieldIsMissingOnTransaction = class extends Err { - constructor() { - super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`."); - } - }; - exports2.ErrIsCompletedFieldIsMissingOnTransaction = ErrIsCompletedFieldIsMissingOnTransaction; - var ErrInvalidTokenIdentifier = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrInvalidTokenIdentifier = ErrInvalidTokenIdentifier; - var ErrBadUsage = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrBadUsage = ErrBadUsage; - var ErrInvalidInnerTransaction = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrInvalidInnerTransaction = ErrInvalidInnerTransaction; - var ErrParseTransactionOutcome = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrParseTransactionOutcome = ErrParseTransactionOutcome; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokens.js -var require_tokens = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokens.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenPayment = exports2.TokenComputer = exports2.TokenTransfer = exports2.Token = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var errors_1 = require_errors(); - var EGLDTokenIdentifier = "EGLD"; - var EGLDNumDecimals = 18; - bignumber_js_1.default.set({ ROUNDING_MODE: 1 }); - var Token2 = class { - constructor(options) { - this.identifier = options.identifier; - this.nonce = options.nonce || 0n; - } - }; - exports2.Token = Token2; - var TokenTransfer2 = class _TokenTransfer { - constructor(options) { - if (this.isLegacyTokenTransferOptions(options)) { - const amount = new bignumber_js_1.default(options.amountAsBigInteger); - if (!amount.isInteger() || amount.isNegative()) { - throw new errors_1.ErrInvalidArgument(`bad amountAsBigInteger: ${options.amountAsBigInteger}`); - } - this.tokenIdentifier = options.tokenIdentifier; - this.nonce = options.nonce; - this.amountAsBigInteger = amount; - this.numDecimals = options.numDecimals || 0; - this.token = new Token2({ - identifier: options.tokenIdentifier, - nonce: BigInt(options.nonce) - }); - this.amount = BigInt(this.amountAsBigInteger.toFixed(0)); - } else { - this.token = options.token; - this.amount = options.amount; - this.tokenIdentifier = options.token.identifier; - this.nonce = Number(options.token.nonce); - this.amountAsBigInteger = new bignumber_js_1.default(this.amount.toString()); - this.numDecimals = 0; - } - } - isLegacyTokenTransferOptions(options) { - return options.tokenIdentifier !== void 0; - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static egldFromAmount(amount) { - const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(EGLDNumDecimals).decimalPlaces(0); - return this.egldFromBigInteger(amountAsBigInteger); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static egldFromBigInteger(amountAsBigInteger) { - return new _TokenTransfer({ - tokenIdentifier: EGLDTokenIdentifier, - nonce: 0, - amountAsBigInteger, - numDecimals: EGLDNumDecimals - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static fungibleFromAmount(tokenIdentifier, amount, numDecimals) { - const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); - return this.fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals = 0) { - return new _TokenTransfer({ - tokenIdentifier, - nonce: 0, - amountAsBigInteger, - numDecimals - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static nonFungible(tokenIdentifier, nonce) { - return new _TokenTransfer({ - tokenIdentifier, - nonce, - amountAsBigInteger: 1, - numDecimals: 0 - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static semiFungible(tokenIdentifier, nonce, quantity) { - return new _TokenTransfer({ - tokenIdentifier, - nonce, - amountAsBigInteger: quantity, - numDecimals: 0 - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static metaEsdtFromAmount(tokenIdentifier, nonce, amount, numDecimals) { - const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); - return this.metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals = 0) { - return new _TokenTransfer({ - tokenIdentifier, - nonce, - amountAsBigInteger, - numDecimals - }); - } - toString() { - return this.amount.toString(); - } - /** - * Legacy function. Use the "amount" field instead. - */ - valueOf() { - return new bignumber_js_1.default(this.amount.toString()); - } - /** - * Legacy function. For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. - */ - toPrettyString() { - return `${this.toAmount()} ${this.tokenIdentifier}`; - } - toAmount() { - return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals); - } - /** - * Legacy function. Within your code, don't mix native values (EGLD) and custom (ESDT) tokens. - * See "TransferTransactionsFactory.createTransactionForNativeTokenTransfer()" vs. "TransferTransactionsFactory.createTransactionForESDTTokenTransfer()". - */ - isEgld() { - return this.token.identifier == EGLDTokenIdentifier; - } - /** - * Legacy function. Use "TokenComputer.isFungible(token)" instead. - */ - isFungible() { - return this.token.nonce == 0n; - } - }; - exports2.TokenTransfer = TokenTransfer2; - var TokenComputer2 = class { - constructor() { - } - isFungible(token) { - return token.nonce === 0n; - } - extractNonceFromExtendedIdentifier(identifier) { - const parts = identifier.split("-"); - this.checkIfExtendedIdentifierWasProvided(parts); - this.checkLengthOfRandomSequence(parts[1]); - if (parts.length == 2) { - return 0; - } - const hexNonce = import_buffer.Buffer.from(parts[2], "hex"); - return decodeUnsignedNumber(hexNonce); - } - extractIdentifierFromExtendedIdentifier(identifier) { - const parts = identifier.split("-"); - this.checkIfExtendedIdentifierWasProvided(parts); - this.ensureTokenTickerValidity(parts[0]); - this.checkLengthOfRandomSequence(parts[1]); - return parts[0] + "-" + parts[1]; - } - checkIfExtendedIdentifierWasProvided(tokenParts) { - const MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 2; - const MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 3; - if (tokenParts.length < MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED || tokenParts.length > MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED) { - throw new errors_1.ErrInvalidTokenIdentifier("Invalid extended token identifier provided"); - } - } - checkLengthOfRandomSequence(randomSequence) { - const TOKEN_RANDOM_SEQUENCE_LENGTH = 6; - if (randomSequence.length !== TOKEN_RANDOM_SEQUENCE_LENGTH) { - throw new errors_1.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length"); - } - } - ensureTokenTickerValidity(ticker) { - const MIN_TICKER_LENGTH = 3; - const MAX_TICKER_LENGTH = 10; - if (ticker.length < MIN_TICKER_LENGTH || ticker.length > MAX_TICKER_LENGTH) { - throw new errors_1.ErrInvalidTokenIdentifier(`The token ticker should be between ${MIN_TICKER_LENGTH} and ${MAX_TICKER_LENGTH} characters`); - } - if (!ticker.match(/^[a-zA-Z0-9]+$/)) { - throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters"); - } - if (!(ticker == ticker.toUpperCase())) { - throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should be upper case"); - } - } - }; - exports2.TokenComputer = TokenComputer2; - function decodeUnsignedNumber(arg) { - return arg.readUIntBE(0, arg.length); - } - var TokenPayment = class extends TokenTransfer2 { - constructor(tokenIdentifier, nonce, amountAsBigInteger, numDecimals) { - super({ - tokenIdentifier, - nonce, - amountAsBigInteger, - numDecimals - }); - } - }; - exports2.TokenPayment = TokenPayment; - } -}); - -// node_modules/@multiversx/sdk-core/out/constants.js -var require_constants = __commonJS({ - "node_modules/@multiversx/sdk-core/out/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UNKNOWN_SIGNER = exports2.SDK_JS_SIGNER = exports2.METACHAIN_ID = exports2.WasmVirtualMachine = exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = exports2.BECH32_ADDRESS_LENGTH = exports2.HEX_TRANSACTION_HASH_LENGTH = exports2.MESSAGE_PREFIX = exports2.DEFAULT_MESSAGE_VERSION = exports2.ESDT_CONTRACT_ADDRESS = exports2.DEFAULT_HRP = exports2.DELEGATION_MANAGER_SC_ADDRESS = exports2.CONTRACT_DEPLOY_ADDRESS = exports2.VM_TYPE_WASM_VM = exports2.ARGUMENTS_SEPARATOR = exports2.ESDT_TRANSFER_VALUE = exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_GAS_LIMIT = exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = exports2.TRANSACTION_VERSION_DEFAULT = exports2.TRANSACTION_OPTIONS_TX_GUARDED = exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = exports2.TRANSACTION_OPTIONS_DEFAULT = exports2.TRANSACTION_MIN_GAS_PRICE = void 0; - exports2.TRANSACTION_MIN_GAS_PRICE = 1e9; - exports2.TRANSACTION_OPTIONS_DEFAULT = 0; - exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = 1; - exports2.TRANSACTION_OPTIONS_TX_GUARDED = 2; - exports2.TRANSACTION_VERSION_DEFAULT = 2; - exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = 2; - exports2.ESDT_TRANSFER_GAS_LIMIT = 5e5; - exports2.ESDT_TRANSFER_FUNCTION_NAME = "ESDTTransfer"; - exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = "ESDTNFTTransfer"; - exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = "MultiESDTNFTTransfer"; - exports2.ESDT_TRANSFER_VALUE = "0"; - exports2.ARGUMENTS_SEPARATOR = "@"; - exports2.VM_TYPE_WASM_VM = new Uint8Array([5, 0]); - exports2.CONTRACT_DEPLOY_ADDRESS = "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"; - exports2.DELEGATION_MANAGER_SC_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"; - exports2.DEFAULT_HRP = "erd"; - exports2.ESDT_CONTRACT_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"; - exports2.DEFAULT_MESSAGE_VERSION = 1; - exports2.MESSAGE_PREFIX = "Elrond Signed Message:\n"; - exports2.HEX_TRANSACTION_HASH_LENGTH = 64; - exports2.BECH32_ADDRESS_LENGTH = 62; - exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = 3; - exports2.WasmVirtualMachine = "0500"; - exports2.METACHAIN_ID = 4294967295; - exports2.SDK_JS_SIGNER = "sdk-js"; - exports2.UNKNOWN_SIGNER = "unknown"; - } -}); - -// node_modules/@multiversx/sdk-core/out/logger.js -var require_logger = __commonJS({ - "node_modules/@multiversx/sdk-core/out/logger.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Logger = exports2.LogLevel = void 0; - var LogLevel; - (function(LogLevel2) { - LogLevel2[LogLevel2["Trace"] = 0] = "Trace"; - LogLevel2[LogLevel2["Debug"] = 1] = "Debug"; - LogLevel2[LogLevel2["Info"] = 2] = "Info"; - LogLevel2[LogLevel2["Warn"] = 3] = "Warn"; - LogLevel2[LogLevel2["Error"] = 4] = "Error"; - LogLevel2[LogLevel2["None"] = 5] = "None"; - })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); - var Logger = class _Logger { - static setLevel(logLevel) { - _Logger.logLevel = logLevel; - } - static trace(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Debug) { - return; - } - console.debug(message, optionalParams); - } - static debug(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Debug) { - return; - } - console.debug(message, optionalParams); - } - static info(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Info) { - return; - } - console.log(message, optionalParams); - } - static warn(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Warn) { - return; - } - console.warn(message, optionalParams); - } - static error(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Error) { - return; - } - console.error(message, optionalParams); - } - }; - exports2.Logger = Logger; - Logger.logLevel = LogLevel.Debug; - } -}); - -// node_modules/@multiversx/sdk-core/out/networkParams.js -var require_networkParams = __commonJS({ - "node_modules/@multiversx/sdk-core/out/networkParams.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionOptions = exports2.TransactionVersion = void 0; - var constants_1 = require_constants(); - var errors = __importStar2(require_errors()); - var TransactionVersion2 = class _TransactionVersion { - /** - * Creates a TransactionVersion object given a value. - */ - constructor(value) { - value = Number(value); - if (value < 1) { - throw new errors.ErrTransactionVersionInvalid(value); - } - this.value = value; - } - /** - * Creates a TransactionVersion object with the default version setting - */ - static withDefaultVersion() { - return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); - } - /** - * Creates a TransactionVersion object with the VERSION setting for enabling options - */ - static withTxOptions() { - return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); - } - valueOf() { - return this.value; - } - }; - exports2.TransactionVersion = TransactionVersion2; - var TransactionOptions2 = class _TransactionOptions { - /** - * Creates a TransactionOptions from a numeric value. - */ - constructor(value) { - value = Number(value); - if (value < 0) { - throw new errors.ErrTransactionOptionsInvalid(value); - } - this.value = value; - } - /** - * Creates a TransactionOptions object with the default options. - */ - static withDefaultOptions() { - return new _TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); - } - /** - * Creates a TransactionOptions object from a set of options. - */ - static withOptions(options) { - let value = 0; - if (options.hashSign) { - value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - if (options.guarded) { - value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - return new _TransactionOptions(value); - } - /** - * Returns true if the "hash sign" option is set. - */ - isWithHashSign() { - return (this.value & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - /** - * Returns true if the "guarded transaction" option is set. - */ - isWithGuardian() { - return (this.value & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - /** - * Sets the "hash sign" option. - */ - setWithHashSign() { - this.value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - /** - * Sets the "guarded transaction" option. - */ - setWithGuardian() { - this.value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - valueOf() { - return this.value; - } - }; - exports2.TransactionOptions = TransactionOptions2; - } -}); - -// node_modules/bech32/index.js -var require_bech32 = __commonJS({ - "node_modules/bech32/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; - var ALPHABET_MAP = {}; - for (z3 = 0; z3 < ALPHABET.length; z3++) { - x3 = ALPHABET.charAt(z3); - if (ALPHABET_MAP[x3] !== void 0) - throw new TypeError(x3 + " is ambiguous"); - ALPHABET_MAP[x3] = z3; - } - var x3; - var z3; - function polymodStep(pre) { - var b4 = pre >> 25; - return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; - } - function prefixChk(prefix) { - var chk = 1; - for (var i2 = 0; i2 < prefix.length; ++i2) { - var c4 = prefix.charCodeAt(i2); - if (c4 < 33 || c4 > 126) - return "Invalid prefix (" + prefix + ")"; - chk = polymodStep(chk) ^ c4 >> 5; - } - chk = polymodStep(chk); - for (i2 = 0; i2 < prefix.length; ++i2) { - var v2 = prefix.charCodeAt(i2); - chk = polymodStep(chk) ^ v2 & 31; - } - return chk; - } - function encode5(prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if (prefix.length + 7 + words.length > LIMIT) - throw new TypeError("Exceeds length limit"); - prefix = prefix.toLowerCase(); - var chk = prefixChk(prefix); - if (typeof chk === "string") - throw new Error(chk); - var result = prefix + "1"; - for (var i2 = 0; i2 < words.length; ++i2) { - var x4 = words[i2]; - if (x4 >> 5 !== 0) - throw new Error("Non 5-bit word"); - chk = polymodStep(chk) ^ x4; - result += ALPHABET.charAt(x4); - } - for (i2 = 0; i2 < 6; ++i2) { - chk = polymodStep(chk); - } - chk ^= 1; - for (i2 = 0; i2 < 6; ++i2) { - var v2 = chk >> (5 - i2) * 5 & 31; - result += ALPHABET.charAt(v2); - } - return result; - } - function __decode(str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) - return str + " too short"; - if (str.length > LIMIT) - return "Exceeds length limit"; - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) - return "Mixed-case string " + str; - str = lowered; - var split = str.lastIndexOf("1"); - if (split === -1) - return "No separator character for " + str; - if (split === 0) - return "Missing prefix for " + str; - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) - return "Data too short"; - var chk = prefixChk(prefix); - if (typeof chk === "string") - return chk; - var words = []; - for (var i2 = 0; i2 < wordChars.length; ++i2) { - var c4 = wordChars.charAt(i2); - var v2 = ALPHABET_MAP[c4]; - if (v2 === void 0) - return "Unknown character " + c4; - chk = polymodStep(chk) ^ v2; - if (i2 + 6 >= wordChars.length) - continue; - words.push(v2); - } - if (chk !== 1) - return "Invalid checksum for " + str; - return { prefix, words }; - } - function decodeUnsafe() { - var res = __decode.apply(null, arguments); - if (typeof res === "object") - return res; - } - function decode6(str) { - var res = __decode.apply(null, arguments); - if (typeof res === "object") - return res; - throw new Error(res); - } - function convert(data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - var result = []; - for (var i2 = 0; i2 < data.length; ++i2) { - value = value << inBits | data[i2]; - bits += inBits; - while (bits >= outBits) { - bits -= outBits; - result.push(value >> bits & maxV); - } - } - if (pad) { - if (bits > 0) { - result.push(value << outBits - bits & maxV); - } - } else { - if (bits >= inBits) - return "Excess padding"; - if (value << outBits - bits & maxV) - return "Non-zero padding"; - } - return result; - } - function toWordsUnsafe(bytes) { - var res = convert(bytes, 8, 5, true); - if (Array.isArray(res)) - return res; - } - function toWords(bytes) { - var res = convert(bytes, 8, 5, true); - if (Array.isArray(res)) - return res; - throw new Error(res); - } - function fromWordsUnsafe(words) { - var res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - } - function fromWords(words) { - var res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - throw new Error(res); - } - module2.exports = { - decodeUnsafe, - decode: decode6, - encode: encode5, - toWordsUnsafe, - toWords, - fromWordsUnsafe, - fromWords - }; - } -}); - -// node_modules/@multiversx/sdk-core/out/utils.codec.js -var require_utils_codec = __commonJS({ - "node_modules/@multiversx/sdk-core/out/utils.codec.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.addressToHex = exports2.bigIntToHex = exports2.byteArrayToHex = exports2.boolToHex = exports2.utf8ToHex = exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var contractsCodecUtils = __importStar2(require_utils()); - function numberToPaddedHex(value) { - let hexableNumber; - if (typeof value === "bigint" || typeof value === "number") { - hexableNumber = value; - } else { - hexableNumber = new bignumber_js_1.default(value); - } - const hex = hexableNumber.toString(16); - return zeroPadStringIfOddLength(hex); - } - exports2.numberToPaddedHex = numberToPaddedHex; - function isPaddedHex(input) { - input = input || ""; - let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); - return input.toUpperCase() == decodedThenEncoded.toUpperCase(); - } - exports2.isPaddedHex = isPaddedHex; - function zeroPadStringIfOddLength(input) { - input = input || ""; - if (input.length % 2 == 1) { - return "0" + input; - } - return input; - } - exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; - function utf8ToHex(value) { - const hex = import_buffer.Buffer.from(value).toString("hex"); - return zeroPadStringIfOddLength(hex); - } - exports2.utf8ToHex = utf8ToHex; - function boolToHex(value) { - return utf8ToHex(value.toString()); - } - exports2.boolToHex = boolToHex; - function byteArrayToHex(byteArray) { - const hexString = import_buffer.Buffer.from(byteArray).toString("hex"); - return zeroPadStringIfOddLength(hexString); - } - exports2.byteArrayToHex = byteArrayToHex; - function bigIntToHex(value) { - if (value == 0) { - return ""; - } - return contractsCodecUtils.getHexMagnitudeOfBigInt(value); - } - exports2.bigIntToHex = bigIntToHex; - function addressToHex(address) { - const buffer = address_1.Address.fromBech32(address.toString()).pubkey(); - return buffer.toString("hex"); - } - exports2.addressToHex = addressToHex; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js -var require_utils = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.prependByteToBuffer = exports2.flipBufferBitsInPlace = exports2.getHexMagnitudeOfBigInt = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.cloneBuffer = exports2.isMsbZero = exports2.isMsbOne = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var utils_codec_1 = require_utils_codec(); - function isMsbOne(buffer, byteIndex = 0) { - let byte = buffer[byteIndex]; - let bit = byte >> 7; - let isSet = bit == 1; - return isSet; - } - exports2.isMsbOne = isMsbOne; - function isMsbZero(buffer, byteIndex = 0) { - return !isMsbOne(buffer, byteIndex); - } - exports2.isMsbZero = isMsbZero; - function cloneBuffer(buffer) { - let clone2 = import_buffer.Buffer.alloc(buffer.length); - buffer.copy(clone2); - return clone2; - } - exports2.cloneBuffer = cloneBuffer; - function bufferToBigInt(buffer) { - let hex = buffer.toString("hex"); - return new bignumber_js_1.default(`0x${hex}`, 16); - } - exports2.bufferToBigInt = bufferToBigInt; - function bigIntToBuffer(value) { - let hex = getHexMagnitudeOfBigInt(value); - return import_buffer.Buffer.from(hex, "hex"); - } - exports2.bigIntToBuffer = bigIntToBuffer; - function getHexMagnitudeOfBigInt(value) { - value = new bignumber_js_1.default(value); - if (!value) { - return ""; - } - if (value.isNegative()) { - value = value.multipliedBy(new bignumber_js_1.default(-1)); - } - return utils_codec_1.numberToPaddedHex(value); - } - exports2.getHexMagnitudeOfBigInt = getHexMagnitudeOfBigInt; - function flipBufferBitsInPlace(buffer) { - for (let i2 = 0; i2 < buffer.length; i2++) { - buffer[i2] = ~buffer[i2]; - } - } - exports2.flipBufferBitsInPlace = flipBufferBitsInPlace; - function prependByteToBuffer(buffer, byte) { - return import_buffer.Buffer.concat([import_buffer.Buffer.from([byte]), buffer]); - } - exports2.prependByteToBuffer = prependByteToBuffer; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js -var require_codec = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bufferToHex = exports2.addressToHex = exports2.bigIntToHex = exports2.utf8ToHex = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.stringToBuffer = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var contractsCodecUtils = __importStar2(require_utils()); - var codecUtils = __importStar2(require_utils_codec()); - function stringToBuffer(value) { - return import_buffer.Buffer.from(value); - } - exports2.stringToBuffer = stringToBuffer; - function bufferToBigInt(buffer) { - if (buffer.length == 0) { - return new bignumber_js_1.default(0); - } - return contractsCodecUtils.bufferToBigInt(buffer); - } - exports2.bufferToBigInt = bufferToBigInt; - function bigIntToBuffer(value) { - if (value == 0) { - return import_buffer.Buffer.from([]); - } - return contractsCodecUtils.bigIntToBuffer(value); - } - exports2.bigIntToBuffer = bigIntToBuffer; - var utils_codec_1 = require_utils_codec(); - Object.defineProperty(exports2, "utf8ToHex", { enumerable: true, get: function() { - return utils_codec_1.utf8ToHex; - } }); - Object.defineProperty(exports2, "bigIntToHex", { enumerable: true, get: function() { - return utils_codec_1.bigIntToHex; - } }); - Object.defineProperty(exports2, "addressToHex", { enumerable: true, get: function() { - return utils_codec_1.addressToHex; - } }); - function bufferToHex(value) { - const hex = value.toString("hex"); - return codecUtils.zeroPadStringIfOddLength(hex); - } - exports2.bufferToHex = bufferToHex; - } -}); - -// node_modules/events/events.js -var require_events = __commonJS({ - "node_modules/events/events.js"(exports2, module2) { - "use strict"; - init_shim(); - var R2 = typeof Reflect === "object" ? Reflect : null; - var ReflectApply = R2 && typeof R2.apply === "function" ? R2.apply : function ReflectApply2(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - }; - var ReflectOwnKeys; - if (R2 && typeof R2.ownKeys === "function") { - ReflectOwnKeys = R2.ownKeys; - } else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys2(target) { - return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); - }; - } else { - ReflectOwnKeys = function ReflectOwnKeys2(target) { - return Object.getOwnPropertyNames(target); - }; - } - function ProcessEmitWarning(warning) { - if (console && console.warn) - console.warn(warning); - } - var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { - return value !== value; - }; - function EventEmitter2() { - EventEmitter2.init.call(this); - } - module2.exports = EventEmitter2; - module2.exports.once = once; - EventEmitter2.EventEmitter = EventEmitter2; - EventEmitter2.prototype._events = void 0; - EventEmitter2.prototype._eventsCount = 0; - EventEmitter2.prototype._maxListeners = void 0; - var defaultMaxListeners = 10; - function checkListener(listener) { - if (typeof listener !== "function") { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - } - Object.defineProperty(EventEmitter2, "defaultMaxListeners", { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); - } - defaultMaxListeners = arg; - } - }); - EventEmitter2.init = function() { - if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - } - this._maxListeners = this._maxListeners || void 0; - }; - EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n3) { - if (typeof n3 !== "number" || n3 < 0 || NumberIsNaN(n3)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n3 + "."); - } - this._maxListeners = n3; - return this; - }; - function _getMaxListeners(that) { - if (that._maxListeners === void 0) - return EventEmitter2.defaultMaxListeners; - return that._maxListeners; - } - EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); - }; - EventEmitter2.prototype.emit = function emit(type) { - var args = []; - for (var i2 = 1; i2 < arguments.length; i2++) - args.push(arguments[i2]); - var doError = type === "error"; - var events = this._events; - if (events !== void 0) - doError = doError && events.error === void 0; - else if (!doError) - return false; - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - throw er; - } - var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); - err.context = er; - throw err; - } - var handler = events[type]; - if (handler === void 0) - return false; - if (typeof handler === "function") { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i2 = 0; i2 < len; ++i2) - ReflectApply(listeners[i2], this, args); - } - return true; - }; - function _addListener(target, type, listener, prepend) { - var m3; - var events; - var existing; - checkListener(listener); - events = target._events; - if (events === void 0) { - events = target._events = /* @__PURE__ */ Object.create(null); - target._eventsCount = 0; - } else { - if (events.newListener !== void 0) { - target.emit( - "newListener", - type, - listener.listener ? listener.listener : listener - ); - events = target._events; - } - existing = events[type]; - } - if (existing === void 0) { - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === "function") { - existing = events[type] = prepend ? [listener, existing] : [existing, listener]; - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - m3 = _getMaxListeners(target); - if (m3 > 0 && existing.length > m3 && !existing.warned) { - existing.warned = true; - var w4 = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); - w4.name = "MaxListenersExceededWarning"; - w4.emitter = target; - w4.type = type; - w4.count = existing.length; - ProcessEmitWarning(w4); - } - } - return target; - } - EventEmitter2.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); - }; - EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; - EventEmitter2.prototype.prependListener = function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } - } - function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: void 0, target, type, listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; - } - EventEmitter2.prototype.once = function once2(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; - EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - EventEmitter2.prototype.removeListener = function removeListener(type, listener) { - var list, events, position, i2, originalListener; - checkListener(listener); - events = this._events; - if (events === void 0) - return this; - list = events[type]; - if (list === void 0) - return this; - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = /* @__PURE__ */ Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit("removeListener", type, list.listener || listener); - } - } else if (typeof list !== "function") { - position = -1; - for (i2 = list.length - 1; i2 >= 0; i2--) { - if (list[i2] === listener || list[i2].listener === listener) { - originalListener = list[i2].listener; - position = i2; - break; - } - } - if (position < 0) - return this; - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - if (list.length === 1) - events[type] = list[0]; - if (events.removeListener !== void 0) - this.emit("removeListener", type, originalListener || listener); - } - return this; - }; - EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; - EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { - var listeners, events, i2; - events = this._events; - if (events === void 0) - return this; - if (events.removeListener === void 0) { - if (arguments.length === 0) { - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== void 0) { - if (--this._eventsCount === 0) - this._events = /* @__PURE__ */ Object.create(null); - else - delete events[type]; - } - return this; - } - if (arguments.length === 0) { - var keys2 = Object.keys(events); - var key; - for (i2 = 0; i2 < keys2.length; ++i2) { - key = keys2[i2]; - if (key === "removeListener") - continue; - this.removeAllListeners(key); - } - this.removeAllListeners("removeListener"); - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - return this; - } - listeners = events[type]; - if (typeof listeners === "function") { - this.removeListener(type, listeners); - } else if (listeners !== void 0) { - for (i2 = listeners.length - 1; i2 >= 0; i2--) { - this.removeListener(type, listeners[i2]); - } - } - return this; - }; - function _listeners(target, type, unwrap) { - var events = target._events; - if (events === void 0) - return []; - var evlistener = events[type]; - if (evlistener === void 0) - return []; - if (typeof evlistener === "function") - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); - } - EventEmitter2.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); - }; - EventEmitter2.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); - }; - EventEmitter2.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === "function") { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } - }; - EventEmitter2.prototype.listenerCount = listenerCount; - function listenerCount(type) { - var events = this._events; - if (events !== void 0) { - var evlistener = events[type]; - if (typeof evlistener === "function") { - return 1; - } else if (evlistener !== void 0) { - return evlistener.length; - } - } - return 0; - } - EventEmitter2.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; - }; - function arrayClone(arr, n3) { - var copy = new Array(n3); - for (var i2 = 0; i2 < n3; ++i2) - copy[i2] = arr[i2]; - return copy; - } - function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); - } - function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i2 = 0; i2 < ret.length; ++i2) { - ret[i2] = arr[i2].listener || arr[i2]; - } - return ret; - } - function once(emitter, name2) { - return new Promise(function(resolve, reject) { - function errorListener(err) { - emitter.removeListener(name2, resolver); - reject(err); - } - function resolver() { - if (typeof emitter.removeListener === "function") { - emitter.removeListener("error", errorListener); - } - resolve([].slice.call(arguments)); - } - ; - eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); - if (name2 !== "error") { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); - } - function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === "function") { - eventTargetAgnosticAddListener(emitter, "error", handler, flags); - } - } - function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { - if (typeof emitter.on === "function") { - if (flags.once) { - emitter.once(name2, listener); - } else { - emitter.on(name2, listener); - } - } else if (typeof emitter.addEventListener === "function") { - emitter.addEventListener(name2, function wrapListener(arg) { - if (flags.once) { - emitter.removeEventListener(name2, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } - } - } -}); - -// node_modules/readable-stream/lib/internal/streams/stream-browser.js -var require_stream_browser = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/stream-browser.js"(exports2, module2) { - init_shim(); - module2.exports = require_events().EventEmitter; - } -}); - -// node_modules/buffer/index.js -var require_buffer2 = __commonJS({ - "node_modules/buffer/index.js"(exports2) { - "use strict"; - init_shim(); - var base642 = require_base64_js(); - var ieee754 = require_ieee754(); - var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports2.Buffer = Buffer2; - exports2.SlowBuffer = SlowBuffer; - exports2.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 2147483647; - exports2.kMaxLength = K_MAX_LENGTH; - Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { - try { - const arr = new Uint8Array(1); - const proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e2) { - return false; - } - } - Object.defineProperty(Buffer2.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer2.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.byteOffset; - } - }); - function createBuffer(length2) { - if (length2 > K_MAX_LENGTH) { - throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); - } - const buf = new Uint8Array(length2); - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function Buffer2(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe2(arg); - } - return from3(arg, encodingOrOffset, length2); - } - Buffer2.poolSize = 8192; - function from3(value, encodingOrOffset, length2) { - if (typeof value === "string") { - return fromString3(value, encodingOrOffset); - } - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof value === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - const valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer2.from(valueOf, encodingOrOffset, length2); - } - const b4 = fromObject(value); - if (b4) - return b4; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length2); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - Buffer2.from = function(value, encodingOrOffset, length2) { - return from3(value, encodingOrOffset, length2); - }; - Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer2, Uint8Array); - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } - } - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); - } - Buffer2.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; - function allocUnsafe2(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - Buffer2.allocUnsafe = function(size) { - return allocUnsafe2(size); - }; - Buffer2.allocUnsafeSlow = function(size) { - return allocUnsafe2(size); - }; - function fromString3(string2, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - const length2 = byteLength(string2, encoding) | 0; - let buf = createBuffer(length2); - const actual = buf.write(string2, encoding); - if (actual !== length2) { - buf = buf.slice(0, actual); - } - return buf; - } - function fromArrayLike(array) { - const length2 = array.length < 0 ? 0 : checked(array.length) | 0; - const buf = createBuffer(length2); - for (let i2 = 0; i2 < length2; i2 += 1) { - buf[i2] = array[i2] & 255; - } - return buf; - } - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - const copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - return fromArrayLike(arrayView); - } - function fromArrayBuffer(array, byteOffset, length2) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length2 || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - let buf; - if (byteOffset === void 0 && length2 === void 0) { - buf = new Uint8Array(array); - } else if (length2 === void 0) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length2); - } - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function fromObject(obj) { - if (Buffer2.isBuffer(obj)) { - const len = checked(obj.length) | 0; - const buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - function checked(length2) { - if (length2 >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length2 | 0; - } - function SlowBuffer(length2) { - if (+length2 != length2) { - length2 = 0; - } - return Buffer2.alloc(+length2); - } - Buffer2.isBuffer = function isBuffer(b4) { - return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; - }; - Buffer2.compare = function compare3(a3, b4) { - if (isInstance(a3, Uint8Array)) - a3 = Buffer2.from(a3, a3.offset, a3.byteLength); - if (isInstance(b4, Uint8Array)) - b4 = Buffer2.from(b4, b4.offset, b4.byteLength); - if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a3 === b4) - return 0; - let x3 = a3.length; - let y4 = b4.length; - for (let i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { - if (a3[i2] !== b4[i2]) { - x3 = a3[i2]; - y4 = b4[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - Buffer2.isEncoding = function isEncoding(encoding) { - switch (String(encoding).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 true; - default: - return false; - } - }; - Buffer2.concat = function concat2(list, length2) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer2.alloc(0); - } - let i2; - if (length2 === void 0) { - length2 = 0; - for (i2 = 0; i2 < list.length; ++i2) { - length2 += list[i2].length; - } - } - const buffer = Buffer2.allocUnsafe(length2); - let pos = 0; - for (i2 = 0; i2 < list.length; ++i2) { - let buf = list[i2]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - if (!Buffer2.isBuffer(buf)) - buf = Buffer2.from(buf); - buf.copy(buffer, pos); - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ); - } - } else if (!Buffer2.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - pos += buf.length; - } - return buffer; - }; - function byteLength(string2, encoding) { - if (Buffer2.isBuffer(string2)) { - return string2.length; - } - if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { - return string2.byteLength; - } - if (typeof string2 !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 - ); - } - const len = string2.length; - const mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) - return 0; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes(string2).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string2).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string2).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.byteLength = byteLength; - function slowToString(encoding, start, end) { - let loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) - encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.prototype._isBuffer = true; - function swap(b4, n3, m3) { - const i2 = b4[n3]; - b4[n3] = b4[m3]; - b4[m3] = i2; - } - Buffer2.prototype.swap16 = function swap16() { - const len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (let i2 = 0; i2 < len; i2 += 2) { - swap(this, i2, i2 + 1); - } - return this; - }; - Buffer2.prototype.swap32 = function swap32() { - const len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i2 = 0; i2 < len; i2 += 4) { - swap(this, i2, i2 + 3); - swap(this, i2 + 1, i2 + 2); - } - return this; - }; - Buffer2.prototype.swap64 = function swap64() { - const len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (let i2 = 0; i2 < len; i2 += 8) { - swap(this, i2, i2 + 7); - swap(this, i2 + 1, i2 + 6); - swap(this, i2 + 2, i2 + 5); - swap(this, i2 + 3, i2 + 4); - } - return this; - }; - Buffer2.prototype.toString = function toString3() { - const length2 = this.length; - if (length2 === 0) - return ""; - if (arguments.length === 0) - return utf8Slice(this, 0, length2); - return slowToString.apply(this, arguments); - }; - Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; - Buffer2.prototype.equals = function equals4(b4) { - if (!Buffer2.isBuffer(b4)) - throw new TypeError("Argument must be a Buffer"); - if (this === b4) - return true; - return Buffer2.compare(this, b4) === 0; - }; - Buffer2.prototype.inspect = function inspect() { - let str = ""; - const max = exports2.INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) - str += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; - } - Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer2.from(target, target.offset, target.byteLength); - } - if (!Buffer2.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) - return 0; - let x3 = thisEnd - thisStart; - let y4 = end - start; - const len = Math.min(x3, y4); - const thisCopy = this.slice(thisStart, thisEnd); - const targetCopy = target.slice(start, end); - for (let i2 = 0; i2 < len; ++i2) { - if (thisCopy[i2] !== targetCopy[i2]) { - x3 = thisCopy[i2]; - y4 = targetCopy[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - if (buffer.length === 0) - return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length - 1; - } - if (byteOffset < 0) - byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) - return -1; - else - byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) - byteOffset = 0; - else - return -1; - } - if (typeof val === "string") { - val = Buffer2.from(val, encoding); - } - if (Buffer2.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); - } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - let indexSize = 1; - let arrLength = arr.length; - let valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read2(buf, i3) { - if (indexSize === 1) { - return buf[i3]; - } else { - return buf.readUInt16BE(i3 * indexSize); - } - } - let i2; - if (dir) { - let foundIndex = -1; - for (i2 = byteOffset; i2 < arrLength; i2++) { - if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { - if (foundIndex === -1) - foundIndex = i2; - if (i2 - foundIndex + 1 === valLength) - return foundIndex * indexSize; - } else { - if (foundIndex !== -1) - i2 -= i2 - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) - byteOffset = arrLength - valLength; - for (i2 = byteOffset; i2 >= 0; i2--) { - let found = true; - for (let j2 = 0; j2 < valLength; j2++) { - if (read2(arr, i2 + j2) !== read2(val, j2)) { - found = false; - break; - } - } - if (found) - return i2; - } - } - return -1; - } - Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string2, offset, length2) { - offset = Number(offset) || 0; - const remaining = buf.length - offset; - if (!length2) { - length2 = remaining; - } else { - length2 = Number(length2); - if (length2 > remaining) { - length2 = remaining; - } - } - const strLen = string2.length; - if (length2 > strLen / 2) { - length2 = strLen / 2; - } - let i2; - for (i2 = 0; i2 < length2; ++i2) { - const parsed = parseInt(string2.substr(i2 * 2, 2), 16); - if (numberIsNaN(parsed)) - return i2; - buf[offset + i2] = parsed; - } - return i2; - } - function utf8Write(buf, string2, offset, length2) { - return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); - } - function asciiWrite(buf, string2, offset, length2) { - return blitBuffer(asciiToBytes(string2), buf, offset, length2); - } - function base64Write(buf, string2, offset, length2) { - return blitBuffer(base64ToBytes(string2), buf, offset, length2); - } - function ucs2Write(buf, string2, offset, length2) { - return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); - } - Buffer2.prototype.write = function write(string2, offset, length2, encoding) { - if (offset === void 0) { - encoding = "utf8"; - length2 = this.length; - offset = 0; - } else if (length2 === void 0 && typeof offset === "string") { - encoding = offset; - length2 = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length2)) { - length2 = length2 >>> 0; - if (encoding === void 0) - encoding = "utf8"; - } else { - encoding = length2; - length2 = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - const remaining = this.length - offset; - if (length2 === void 0 || length2 > remaining) - length2 = remaining; - if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) - encoding = "utf8"; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string2, offset, length2); - case "utf8": - case "utf-8": - return utf8Write(this, string2, offset, length2); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string2, offset, length2); - case "base64": - return base64Write(this, string2, offset, length2); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string2, offset, length2); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - Buffer2.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base642.fromByteArray(buf); - } else { - return base642.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - const res = []; - let i2 = start; - while (i2 < end) { - const firstByte = buf[i2]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i2 + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i2 + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - fourthByte = buf[i2 + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i2 += bytesPerSequence; - } - return decodeCodePointsArray(res); - } - var MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - let res = ""; - let i2 = 0; - while (i2 < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) - ); - } - return res; - } - function asciiSlice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2] & 127); - } - return ret; - } - function latin1Slice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2]); - } - return ret; - } - function hexSlice(buf, start, end) { - const len = buf.length; - if (!start || start < 0) - start = 0; - if (!end || end < 0 || end > len) - end = len; - let out = ""; - for (let i2 = start; i2 < end; ++i2) { - out += hexSliceLookupTable[buf[i2]]; - } - return out; - } - function utf16leSlice(buf, start, end) { - const bytes = buf.slice(start, end); - let res = ""; - for (let i2 = 0; i2 < bytes.length - 1; i2 += 2) { - res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); - } - return res; - } - Buffer2.prototype.slice = function slice(start, end) { - const len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) - start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) - end = 0; - } else if (end > len) { - end = len; - } - if (end < start) - end = start; - const newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer2.prototype); - return newBuf; - }; - function checkOffset(offset, ext, length2) { - if (offset % 1 !== 0 || offset < 0) - throw new RangeError("offset is not uint"); - if (offset + ext > length2) - throw new RangeError("Trying to access beyond buffer length"); - } - Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - return val; - }; - Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength2, this.length); - } - let val = this[offset + --byteLength2]; - let mul = 1; - while (byteLength2 > 0 && (mul *= 256)) { - val += this[offset + --byteLength2] * mul; - } - return val; - }; - Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - return this[offset]; - }; - Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; - }; - Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; - const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; - return BigInt(lo) + (BigInt(hi) << BigInt(32)); - }); - Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; - return (BigInt(hi) << BigInt(32)) + BigInt(lo); - }); - Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let i2 = byteLength2; - let mul = 1; - let val = this[offset + --i2]; - while (i2 > 0 && (mul *= 256)) { - val += this[offset + --i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) - return this[offset]; - return (255 - this[offset] + 1) * -1; - }; - Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - const val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - const val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); - }); - Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = (first << 24) + // Overflow - this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); - }); - Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); - }; - Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); - }; - Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); - }; - Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); - }; - function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer2.isBuffer(buf)) - throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) - throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - } - Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let mul = 1; - let i2 = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let i2 = byteLength2 - 1; - let mul = 1; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 255, 0); - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - function wrtBigUInt64LE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - return offset; - } - function wrtBigUInt64BE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset + 7] = lo; - lo = lo >> 8; - buf[offset + 6] = lo; - lo = lo >> 8; - buf[offset + 5] = lo; - lo = lo >> 8; - buf[offset + 4] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset + 3] = hi; - hi = hi >> 8; - buf[offset + 2] = hi; - hi = hi >> 8; - buf[offset + 1] = hi; - hi = hi >> 8; - buf[offset] = hi; - return offset + 8; - } - Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i2 = 0; - let mul = 1; - let sub = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i2 = byteLength2 - 1; - let mul = 1; - let sub = 0; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 127, -128); - if (value < 0) - value = 255 + value + 1; - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; - }; - Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - if (value < 0) - value = 4294967295 + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - if (offset < 0) - throw new RangeError("Index out of range"); - } - function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); - }; - function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; - Buffer2.prototype.copy = function copy(target, targetStart, start, end) { - if (!Buffer2.isBuffer(target)) - throw new TypeError("argument should be a Buffer"); - if (!start) - start = 0; - if (!end && end !== 0) - end = this.length; - if (targetStart >= target.length) - targetStart = target.length; - if (!targetStart) - targetStart = 0; - if (end > 0 && end < start) - end = start; - if (end === start) - return 0; - if (target.length === 0 || this.length === 0) - return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) - throw new RangeError("Index out of range"); - if (end < 0) - throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) - end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - const len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); - } - return len; - }; - Buffer2.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - const code2 = val.charCodeAt(0); - if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { - val = code2; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) - val = 0; - let i2; - if (typeof val === "number") { - for (i2 = start; i2 < end; ++i2) { - this[i2] = val; - } - } else { - const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); - const len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i2 = 0; i2 < end - start; ++i2) { - this[i2 + start] = bytes[i2 % len]; - } - } - return this; - }; - var errors = {}; - function E4(sym, getMessage, Base) { - errors[sym] = class NodeError extends Base { - constructor() { - super(); - Object.defineProperty(this, "message", { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }); - this.name = `${this.name} [${sym}]`; - this.stack; - delete this.name; - } - get code() { - return sym; - } - set code(value) { - Object.defineProperty(this, "code", { - configurable: true, - enumerable: true, - value, - writable: true - }); - } - toString() { - return `${this.name} [${sym}]: ${this.message}`; - } - }; - } - E4( - "ERR_BUFFER_OUT_OF_BOUNDS", - function(name2) { - if (name2) { - return `${name2} is outside of buffer bounds`; - } - return "Attempt to access memory outside buffer bounds"; - }, - RangeError - ); - E4( - "ERR_INVALID_ARG_TYPE", - function(name2, actual) { - return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; - }, - TypeError - ); - E4( - "ERR_OUT_OF_RANGE", - function(str, range, input) { - let msg = `The value of "${str}" is out of range.`; - let received = input; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received); - } - received += "n"; - } - msg += ` It must be ${range}. Received ${received}`; - return msg; - }, - RangeError - ); - function addNumericalSeparator(val) { - let res = ""; - let i2 = val.length; - const start = val[0] === "-" ? 1 : 0; - for (; i2 >= start + 4; i2 -= 3) { - res = `_${val.slice(i2 - 3, i2)}${res}`; - } - return `${val.slice(0, i2)}${res}`; - } - function checkBounds(buf, offset, byteLength2) { - validateNumber(offset, "offset"); - if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { - boundsError(offset, buf.length - (byteLength2 + 1)); - } - } - function checkIntBI(value, min, max, buf, offset, byteLength2) { - if (value > max || value < min) { - const n3 = typeof min === "bigint" ? "n" : ""; - let range; - if (byteLength2 > 3) { - if (min === 0 || min === BigInt(0)) { - range = `>= 0${n3} and < 2${n3} ** ${(byteLength2 + 1) * 8}${n3}`; - } else { - range = `>= -(2${n3} ** ${(byteLength2 + 1) * 8 - 1}${n3}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n3}`; - } - } else { - range = `>= ${min}${n3} and <= ${max}${n3}`; - } - throw new errors.ERR_OUT_OF_RANGE("value", range, value); - } - checkBounds(buf, offset, byteLength2); - } - function validateNumber(value, name2) { - if (typeof value !== "number") { - throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value); - } - } - function boundsError(value, length2, type) { - if (Math.floor(value) !== value) { - validateNumber(value, type); - throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); - } - if (length2 < 0) { - throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); - } - throw new errors.ERR_OUT_OF_RANGE( - type || "offset", - `>= ${type ? 1 : 0} and <= ${length2}`, - value - ); - } - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) - return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } - function utf8ToBytes(string2, units) { - units = units || Infinity; - let codePoint; - const length2 = string2.length; - let leadSurrogate = null; - const bytes = []; - for (let i2 = 0; i2 < length2; ++i2) { - codePoint = string2.charCodeAt(i2); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } else if (i2 + 1 === length2) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) - break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) - break; - bytes.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) - break; - bytes.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) - break; - bytes.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; - } - function asciiToBytes(str) { - const byteArray = []; - for (let i2 = 0; i2 < str.length; ++i2) { - byteArray.push(str.charCodeAt(i2) & 255); - } - return byteArray; - } - function utf16leToBytes(str, units) { - let c4, hi, lo; - const byteArray = []; - for (let i2 = 0; i2 < str.length; ++i2) { - if ((units -= 2) < 0) - break; - c4 = str.charCodeAt(i2); - hi = c4 >> 8; - lo = c4 % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; - } - function base64ToBytes(str) { - return base642.toByteArray(base64clean(str)); - } - function blitBuffer(src2, dst, offset, length2) { - let i2; - for (i2 = 0; i2 < length2; ++i2) { - if (i2 + offset >= dst.length || i2 >= src2.length) - break; - dst[i2 + offset] = src2[i2]; - } - return i2; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - var hexSliceLookupTable = function() { - const alphabet2 = "0123456789abcdef"; - const table = new Array(256); - for (let i2 = 0; i2 < 16; ++i2) { - const i16 = i2 * 16; - for (let j2 = 0; j2 < 16; ++j2) { - table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; - } - } - return table; - }(); - function defineBigIntMethod(fn) { - return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; - } - function BufferBigIntNotDefined() { - throw new Error("BigInt not supported"); - } - } -}); - -// (disabled):node_modules/util/util.js -var require_util = __commonJS({ - "(disabled):node_modules/util/util.js"() { - init_shim(); - } -}); - -// node_modules/readable-stream/lib/internal/streams/buffer_list.js -var require_buffer_list = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { - "use strict"; - init_shim(); - function ownKeys(object, enumerableOnly) { - var keys2 = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys2.push.apply(keys2, symbols); - } - return keys2; - } - function _objectSpread(target) { - for (var i2 = 1; i2 < arguments.length; i2++) { - var source = null != arguments[i2] ? arguments[i2] : {}; - i2 % 2 ? ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; - } - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i2 = 0; i2 < props.length; i2++) { - var descriptor = props[i2]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) - descriptor.writable = true; - Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) - _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { writable: false }); - return Constructor; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) - return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") - return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var _require = require_buffer2(); - var Buffer2 = _require.Buffer; - var _require2 = require_util(); - var inspect = _require2.inspect; - var custom = inspect && inspect.custom || "inspect"; - function copyBuffer(src2, target, offset) { - Buffer2.prototype.copy.call(src2, target, offset); - } - module2.exports = /* @__PURE__ */ function() { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } - _createClass(BufferList, [{ - key: "push", - value: function push(v2) { - var entry = { - data: v2, - next: null - }; - if (this.length > 0) - this.tail.next = entry; - else - this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v2) { - var entry = { - data: v2, - next: this.head - }; - if (this.length === 0) - this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) - return; - var ret = this.head.data; - if (this.length === 1) - this.head = this.tail = null; - else - this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear2() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s2) { - if (this.length === 0) - return ""; - var p3 = this.head; - var ret = "" + p3.data; - while (p3 = p3.next) - ret += s2 + p3.data; - return ret; - } - }, { - key: "concat", - value: function concat2(n3) { - if (this.length === 0) - return Buffer2.alloc(0); - var ret = Buffer2.allocUnsafe(n3 >>> 0); - var p3 = this.head; - var i2 = 0; - while (p3) { - copyBuffer(p3.data, ret, i2); - i2 += p3.data.length; - p3 = p3.next; - } - return ret; - } - // Consumes a specified amount of bytes or characters from the buffered data. - }, { - key: "consume", - value: function consume(n3, hasStrings) { - var ret; - if (n3 < this.head.data.length) { - ret = this.head.data.slice(0, n3); - this.head.data = this.head.data.slice(n3); - } else if (n3 === this.head.data.length) { - ret = this.shift(); - } else { - ret = hasStrings ? this._getString(n3) : this._getBuffer(n3); - } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } - // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n3) { - var p3 = this.head; - var c4 = 1; - var ret = p3.data; - n3 -= ret.length; - while (p3 = p3.next) { - var str = p3.data; - var nb = n3 > str.length ? str.length : n3; - if (nb === str.length) - ret += str; - else - ret += str.slice(0, n3); - n3 -= nb; - if (n3 === 0) { - if (nb === str.length) { - ++c4; - if (p3.next) - this.head = p3.next; - else - this.head = this.tail = null; - } else { - this.head = p3; - p3.data = str.slice(nb); - } - break; - } - ++c4; - } - this.length -= c4; - return ret; - } - // Consumes a specified amount of bytes from the buffered data. - }, { - key: "_getBuffer", - value: function _getBuffer(n3) { - var ret = Buffer2.allocUnsafe(n3); - var p3 = this.head; - var c4 = 1; - p3.data.copy(ret); - n3 -= p3.data.length; - while (p3 = p3.next) { - var buf = p3.data; - var nb = n3 > buf.length ? buf.length : n3; - buf.copy(ret, ret.length - n3, 0, nb); - n3 -= nb; - if (n3 === 0) { - if (nb === buf.length) { - ++c4; - if (p3.next) - this.head = p3.next; - else - this.head = this.tail = null; - } else { - this.head = p3; - p3.data = buf.slice(nb); - } - break; - } - ++c4; - } - this.length -= c4; - return ret; - } - // Make sure the linked list only shows the minimal necessary information. - }, { - key: custom, - value: function value(_4, options) { - return inspect(this, _objectSpread(_objectSpread({}, options), {}, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - return BufferList; - }(); - } -}); - -// node_modules/readable-stream/lib/internal/streams/destroy.js -var require_destroy = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { - "use strict"; - init_shim(); - function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - import_process.default.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - import_process.default.nextTick(emitErrorNT, this, err); - } - } - return this; - } - if (this._readableState) { - this._readableState.destroyed = true; - } - if (this._writableState) { - this._writableState.destroyed = true; - } - this._destroy(err || null, function(err2) { - if (!cb && err2) { - if (!_this._writableState) { - import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); - } else { - import_process.default.nextTick(emitCloseNT, _this); - } - } else if (cb) { - import_process.default.nextTick(emitCloseNT, _this); - cb(err2); - } else { - import_process.default.nextTick(emitCloseNT, _this); - } - }); - return this; - } - function emitErrorAndCloseNT(self2, err) { - emitErrorNT(self2, err); - emitCloseNT(self2); - } - function emitCloseNT(self2) { - if (self2._writableState && !self2._writableState.emitClose) - return; - if (self2._readableState && !self2._readableState.emitClose) - return; - self2.emit("close"); - } - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } - } - function emitErrorNT(self2, err) { - self2.emit("error", err); - } - function errorOrDestroy(stream, err) { - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) - stream.destroy(err); - else - stream.emit("error", err); - } - module2.exports = { - destroy, - undestroy, - errorOrDestroy - }; - } -}); - -// node_modules/readable-stream/errors-browser.js -var require_errors_browser = __commonJS({ - "node_modules/readable-stream/errors-browser.js"(exports2, module2) { - "use strict"; - init_shim(); - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; - } - var codes = {}; - function createErrorType(code2, message, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message === "string") { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - var NodeError = /* @__PURE__ */ function(_Base) { - _inheritsLoose(NodeError2, _Base); - function NodeError2(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - return NodeError2; - }(Base); - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code2; - codes[code2] = NodeError; - } - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function(i2) { - return String(i2); - }); - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } - } - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - function endsWith(str, search, this_len) { - if (this_len === void 0 || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - function includes(str, search, start) { - if (typeof start !== "number") { - start = 0; - } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } - } - createErrorType("ERR_INVALID_OPT_VALUE", function(name2, value) { - return 'The value "' + value + '" is invalid for option "' + name2 + '"'; - }, TypeError); - createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) { - var determiner; - if (typeof expected === "string" && startsWith(expected, "not ")) { - determiner = "must not be"; - expected = expected.replace(/^not /, ""); - } else { - determiner = "must be"; - } - var msg; - if (endsWith(name2, " argument")) { - msg = "The ".concat(name2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); - } else { - var type = includes(name2, ".") ? "property" : "argument"; - msg = 'The "'.concat(name2, '" ').concat(type, " ").concat(determiner, " ").concat(oneOf(expected, "type")); - } - msg += ". Received type ".concat(typeof actual); - return msg; - }, TypeError); - createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); - createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name2) { - return "The " + name2 + " method is not implemented"; - }); - createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); - createErrorType("ERR_STREAM_DESTROYED", function(name2) { - return "Cannot call " + name2 + " after a stream was destroyed"; - }); - createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); - createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); - createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); - createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); - createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { - return "Unknown encoding: " + arg; - }, TypeError); - createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); - module2.exports.codes = codes; - } -}); - -// node_modules/readable-stream/lib/internal/streams/state.js -var require_state = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { - "use strict"; - init_shim(); - var ERR_INVALID_OPT_VALUE = require_errors_browser().codes.ERR_INVALID_OPT_VALUE; - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } - function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name2 = isDuplex ? duplexKey : "highWaterMark"; - throw new ERR_INVALID_OPT_VALUE(name2, hwm); - } - return Math.floor(hwm); - } - return state.objectMode ? 16 : 16 * 1024; - } - module2.exports = { - getHighWaterMark - }; - } -}); - -// node_modules/inherits/inherits_browser.js -var require_inherits_browser = __commonJS({ - "node_modules/inherits/inherits_browser.js"(exports2, module2) { - init_shim(); - if (typeof Object.create === "function") { - module2.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; - } else { - module2.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() { - }; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - }; - } - } -}); - -// node_modules/util-deprecate/browser.js -var require_browser2 = __commonJS({ - "node_modules/util-deprecate/browser.js"(exports2, module2) { - init_shim(); - module2.exports = deprecate2; - function deprecate2(fn, msg) { - if (config("noDeprecation")) { - return fn; - } - var warned = false; - function deprecated() { - if (!warned) { - if (config("throwDeprecation")) { - throw new Error(msg); - } else if (config("traceDeprecation")) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - return deprecated; - } - function config(name2) { - try { - if (!global.localStorage) - return false; - } catch (_4) { - return false; - } - var val = global.localStorage[name2]; - if (null == val) - return false; - return String(val).toLowerCase() === "true"; - } - } -}); - -// node_modules/readable-stream/lib/_stream_writable.js -var require_stream_writable = __commonJS({ - "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Writable; - function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function() { - onCorkedFinish(_this, state); - }; - } - var Duplex; - Writable.WritableState = WritableState; - var internalUtil = { - deprecate: require_browser2() - }; - var Stream = require_stream_browser(); - var Buffer2 = require_buffer2().Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors_browser().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; - var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; - var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - var errorOrDestroy = destroyImpl.errorOrDestroy; - require_inherits_browser()(Writable, Stream); - function nop() { - } - function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") - isDuplex = stream instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) - this.objectMode = this.objectMode || !!options.writableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); - this.finalCalled = false; - this.needDrain = false; - this.ending = false; - this.ended = false; - this.finished = false; - this.destroyed = false; - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.length = 0; - this.writing = false; - this.corked = 0; - this.sync = true; - this.bufferProcessing = false; - this.onwrite = function(er) { - onwrite(stream, er); - }; - this.writecb = null; - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; - this.pendingcb = 0; - this.prefinished = false; - this.errorEmitted = false; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.bufferedRequestCount = 0; - this.corkedRequestsFree = new CorkedRequest(this); - } - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - (function() { - try { - Object.defineProperty(WritableState.prototype, "buffer", { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") - }); - } catch (_4) { - } - })(); - var realHasInstance; - if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) - return true; - if (this !== Writable) - return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance2(object) { - return object instanceof this; - }; - } - function Writable(options) { - Duplex = Duplex || require_stream_duplex(); - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) - return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); - this.writable = true; - if (options) { - if (typeof options.write === "function") - this._write = options.write; - if (typeof options.writev === "function") - this._writev = options.writev; - if (typeof options.destroy === "function") - this._destroy = options.destroy; - if (typeof options.final === "function") - this._final = options.final; - } - Stream.call(this); - } - Writable.prototype.pipe = function() { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); - errorOrDestroy(stream, er); - import_process.default.nextTick(cb, er); - } - function validChunk(stream, state, chunk, cb) { - var er; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== "string" && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); - } - if (er) { - errorOrDestroy(stream, er); - import_process.default.nextTick(cb, er); - return false; - } - return true; - } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer2.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (isBuf) - encoding = "buffer"; - else if (!encoding) - encoding = state.defaultEncoding; - if (typeof cb !== "function") - cb = nop; - if (state.ending) - writeAfterEnd(this, cb); - else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; - Writable.prototype.cork = function() { - this._writableState.corked++; - }; - Writable.prototype.uncork = function() { - var state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) - clearBuffer(this, state); - } - }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - if (typeof encoding === "string") - encoding = encoding.toLowerCase(); - if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) - throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - Object.defineProperty(Writable.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState && this._writableState.getBuffer(); - } - }); - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { - chunk = Buffer2.from(chunk, encoding); - } - return chunk; - } - Object.defineProperty(Writable.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.highWaterMark; - } - }); - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = "buffer"; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; - if (!ret) - state.needDrain = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk, - encoding, - isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - return ret; - } - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) - state.onwrite(new ERR_STREAM_DESTROYED("write")); - else if (writev) - stream._writev(chunk, state.onwrite); - else - stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) { - import_process.default.nextTick(cb, er); - import_process.default.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - finishMaybe(stream, state); - } - } - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== "function") - throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) - onwriteError(stream, state, sync, er, cb); - else { - var finished = needFinish(state) || stream.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - if (sync) { - import_process.default.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } - } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit("drain"); - } - } - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { - var l4 = state.bufferedRequestCount; - var buffer = new Array(l4); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) - allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, "", holder.finish); - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - if (state.writing) { - break; - } - } - if (entry === null) - state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); - }; - Writable.prototype._writev = null; - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (chunk !== null && chunk !== void 0) - this.write(chunk, encoding); - if (state.corked) { - state.corked = 1; - this.uncork(); - } - if (!state.ending) - endWritable(this, state, cb); - return this; - }; - Object.defineProperty(Writable.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.length; - } - }); - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - function callFinal(stream, state) { - stream._final(function(err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream, err); - } - state.prefinished = true; - stream.emit("prefinish"); - finishMaybe(stream, state); - }); - } - function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === "function" && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - import_process.default.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit("prefinish"); - } - } - } - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit("finish"); - if (state.autoDestroy) { - var rState = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - return need; - } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - import_process.default.nextTick(cb); - else - stream.once("finish", cb); - } - state.ended = true; - stream.writable = false; - } - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - state.corkedRequestsFree.next = corkReq; - } - Object.defineProperty(Writable.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._writableState === void 0) { - return false; - } - return this._writableState.destroyed; - }, - set: function set2(value) { - if (!this._writableState) { - return; - } - this._writableState.destroyed = value; - } - }); - Writable.prototype.destroy = destroyImpl.destroy; - Writable.prototype._undestroy = destroyImpl.undestroy; - Writable.prototype._destroy = function(err, cb) { - cb(err); - }; - } -}); - -// node_modules/readable-stream/lib/_stream_duplex.js -var require_stream_duplex = __commonJS({ - "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { - "use strict"; - init_shim(); - var objectKeys = Object.keys || function(obj) { - var keys3 = []; - for (var key in obj) - keys3.push(key); - return keys3; - }; - module2.exports = Duplex; - var Readable = require_stream_readable(); - var Writable = require_stream_writable(); - require_inherits_browser()(Duplex, Readable); - { - keys2 = objectKeys(Writable.prototype); - for (v2 = 0; v2 < keys2.length; v2++) { - method = keys2[v2]; - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; - } - } - var keys2; - var method; - var v2; - function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) - this.readable = false; - if (options.writable === false) - this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once("end", onend); - } - } - } - Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.length; - } - }); - function onend() { - if (this._writableState.ended) - return; - import_process.default.nextTick(onEndNT, this); - } - function onEndNT(self2) { - self2.end(); - } - Object.defineProperty(Duplex.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._readableState === void 0 || this._writableState === void 0) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set2(value) { - if (this._readableState === void 0 || this._writableState === void 0) { - return; - } - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - } -}); - -// node_modules/safe-buffer/index.js -var require_safe_buffer = __commonJS({ - "node_modules/safe-buffer/index.js"(exports2, module2) { - init_shim(); - var buffer = require_buffer2(); - var Buffer2 = buffer.Buffer; - function copyProps(src2, dst) { - for (var key in src2) { - dst[key] = src2[key]; - } - } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { - module2.exports = buffer; - } else { - copyProps(buffer, exports2); - exports2.Buffer = SafeBuffer; - } - function SafeBuffer(arg, encodingOrOffset, length2) { - return Buffer2(arg, encodingOrOffset, length2); - } - SafeBuffer.prototype = Object.create(Buffer2.prototype); - copyProps(Buffer2, SafeBuffer); - SafeBuffer.from = function(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer2(arg, encodingOrOffset, length2); - }; - SafeBuffer.alloc = function(size, fill, encoding) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer2(size); - if (fill !== void 0) { - if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf; - }; - SafeBuffer.allocUnsafe = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer2(size); - }; - SafeBuffer.allocUnsafeSlow = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; - } -}); - -// node_modules/string_decoder/lib/string_decoder.js -var require_string_decoder = __commonJS({ - "node_modules/string_decoder/lib/string_decoder.js"(exports2) { - "use strict"; - init_shim(); - var Buffer2 = require_safe_buffer().Buffer; - var isEncoding = Buffer2.isEncoding || function(encoding) { - encoding = "" + encoding; - switch (encoding && encoding.toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - case "raw": - return true; - default: - return false; - } - }; - function _normalizeEncoding(enc) { - if (!enc) - return "utf8"; - var retried; - while (true) { - switch (enc) { - case "utf8": - case "utf-8": - return "utf8"; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return "utf16le"; - case "latin1": - case "binary": - return "latin1"; - case "base64": - case "ascii": - case "hex": - return enc; - default: - if (retried) - return; - enc = ("" + enc).toLowerCase(); - retried = true; - } - } - } - function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) - throw new Error("Unknown encoding: " + enc); - return nenc || enc; - } - exports2.StringDecoder = StringDecoder; - function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case "utf16le": - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case "utf8": - this.fillLast = utf8FillLast; - nb = 4; - break; - case "base64": - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer2.allocUnsafe(nb); - } - StringDecoder.prototype.write = function(buf) { - if (buf.length === 0) - return ""; - var r; - var i2; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === void 0) - return ""; - i2 = this.lastNeed; - this.lastNeed = 0; - } else { - i2 = 0; - } - if (i2 < buf.length) - return r ? r + this.text(buf, i2) : this.text(buf, i2); - return r || ""; - }; - StringDecoder.prototype.end = utf8End; - StringDecoder.prototype.text = utf8Text; - StringDecoder.prototype.fillLast = function(buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; - }; - function utf8CheckByte(byte) { - if (byte <= 127) - return 0; - else if (byte >> 5 === 6) - return 2; - else if (byte >> 4 === 14) - return 3; - else if (byte >> 3 === 30) - return 4; - return byte >> 6 === 2 ? -1 : -2; - } - function utf8CheckIncomplete(self2, buf, i2) { - var j2 = buf.length - 1; - if (j2 < i2) - return 0; - var nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) - self2.lastNeed = nb - 1; - return nb; - } - if (--j2 < i2 || nb === -2) - return 0; - nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) - self2.lastNeed = nb - 2; - return nb; - } - if (--j2 < i2 || nb === -2) - return 0; - nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) - nb = 0; - else - self2.lastNeed = nb - 3; - } - return nb; - } - return 0; - } - function utf8CheckExtraBytes(self2, buf, p3) { - if ((buf[0] & 192) !== 128) { - self2.lastNeed = 0; - return "\uFFFD"; - } - if (self2.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 192) !== 128) { - self2.lastNeed = 1; - return "\uFFFD"; - } - if (self2.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 192) !== 128) { - self2.lastNeed = 2; - return "\uFFFD"; - } - } - } - } - function utf8FillLast(buf) { - var p3 = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p3); - if (r !== void 0) - return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p3, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p3, 0, buf.length); - this.lastNeed -= buf.length; - } - function utf8Text(buf, i2) { - var total = utf8CheckIncomplete(this, buf, i2); - if (!this.lastNeed) - return buf.toString("utf8", i2); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString("utf8", i2, end); - } - function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) - return r + "\uFFFD"; - return r; - } - function utf16Text(buf, i2) { - if ((buf.length - i2) % 2 === 0) { - var r = buf.toString("utf16le", i2); - if (r) { - var c4 = r.charCodeAt(r.length - 1); - if (c4 >= 55296 && c4 <= 56319) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString("utf16le", i2, buf.length - 1); - } - function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString("utf16le", 0, end); - } - return r; - } - function base64Text(buf, i2) { - var n3 = (buf.length - i2) % 3; - if (n3 === 0) - return buf.toString("base64", i2); - this.lastNeed = 3 - n3; - this.lastTotal = 3; - if (n3 === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString("base64", i2, buf.length - n3); - } - function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) - return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); - return r; - } - function simpleWrite(buf) { - return buf.toString(this.encoding); - } - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ""; - } - } -}); - -// node_modules/readable-stream/lib/internal/streams/end-of-stream.js -var require_end_of_stream = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { - "use strict"; - init_shim(); - var ERR_STREAM_PREMATURE_CLOSE = require_errors_browser().codes.ERR_STREAM_PREMATURE_CLOSE; - function once(callback) { - var called = false; - return function() { - if (called) - return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - callback.apply(this, args); - }; - } - function noop() { - } - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - function eos(stream, opts, callback) { - if (typeof opts === "function") - return eos(stream, null, opts); - if (!opts) - opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - var onlegacyfinish = function onlegacyfinish2() { - if (!stream.writable) - onfinish(); - }; - var writableEnded = stream._writableState && stream._writableState.finished; - var onfinish = function onfinish2() { - writable = false; - writableEnded = true; - if (!readable) - callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend2() { - readable = false; - readableEnded = true; - if (!writable) - callback.call(stream); - }; - var onerror = function onerror2(err) { - callback.call(stream, err); - }; - var onclose = function onclose2() { - var err; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) - err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) - err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - var onrequest = function onrequest2() { - stream.req.on("finish", onfinish); - }; - if (isRequest(stream)) { - stream.on("complete", onfinish); - stream.on("abort", onclose); - if (stream.req) - onrequest(); - else - stream.on("request", onrequest); - } else if (writable && !stream._writableState) { - stream.on("end", onlegacyfinish); - stream.on("close", onlegacyfinish); - } - stream.on("end", onend); - stream.on("finish", onfinish); - if (opts.error !== false) - stream.on("error", onerror); - stream.on("close", onclose); - return function() { - stream.removeListener("complete", onfinish); - stream.removeListener("abort", onclose); - stream.removeListener("request", onrequest); - if (stream.req) - stream.req.removeListener("finish", onfinish); - stream.removeListener("end", onlegacyfinish); - stream.removeListener("close", onlegacyfinish); - stream.removeListener("finish", onfinish); - stream.removeListener("end", onend); - stream.removeListener("error", onerror); - stream.removeListener("close", onclose); - }; - } - module2.exports = eos; - } -}); - -// node_modules/readable-stream/lib/internal/streams/async_iterator.js -var require_async_iterator = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { - "use strict"; - init_shim(); - var _Object$setPrototypeO; - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) - return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") - return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var finished = require_end_of_stream(); - var kLastResolve = Symbol("lastResolve"); - var kLastReject = Symbol("lastReject"); - var kError = Symbol("error"); - var kEnded = Symbol("ended"); - var kLastPromise = Symbol("lastPromise"); - var kHandlePromise = Symbol("handlePromise"); - var kStream = Symbol("stream"); - function createIterResult(value, done) { - return { - value, - done - }; - } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - if (resolve !== null) { - var data = iter[kStream].read(); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } - } - function onReadable(iter) { - import_process.default.nextTick(readAndResolve, iter); - } - function wrapForNext(lastPromise, iter) { - return function(resolve, reject) { - lastPromise.then(function() { - if (iter[kEnded]) { - resolve(createIterResult(void 0, true)); - return; - } - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } - var AsyncIteratorPrototype = Object.getPrototypeOf(function() { - }); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - next: function next() { - var _this = this; - var error = this[kError]; - if (error !== null) { - return Promise.reject(error); - } - if (this[kEnded]) { - return Promise.resolve(createIterResult(void 0, true)); - } - if (this[kStream].destroyed) { - return new Promise(function(resolve, reject) { - import_process.default.nextTick(function() { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(void 0, true)); - } - }); - }); - } - var lastPromise = this[kLastPromise]; - var promise; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - var data = this[kStream].read(); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - promise = new Promise(this[kHandlePromise]); - } - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - return new Promise(function(resolve, reject) { - _this2[kStream].destroy(null, function(err) { - if (err) { - reject(err); - return; - } - resolve(createIterResult(void 0, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) { - var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function(err) { - if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { - var reject = iterator[kLastReject]; - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - iterator[kError] = err; - return; - } - var resolve = iterator[kLastResolve]; - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(void 0, true)); - } - iterator[kEnded] = true; - }); - stream.on("readable", onReadable.bind(null, iterator)); - return iterator; - }; - module2.exports = createReadableStreamAsyncIterator; - } -}); - -// node_modules/readable-stream/lib/internal/streams/from-browser.js -var require_from_browser = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/from-browser.js"(exports2, module2) { - init_shim(); - module2.exports = function() { - throw new Error("Readable.from is not available in the browser"); - }; - } -}); - -// node_modules/readable-stream/lib/_stream_readable.js -var require_stream_readable = __commonJS({ - "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Readable; - var Duplex; - Readable.ReadableState = ReadableState; - var EE = require_events().EventEmitter; - var EElistenerCount = function EElistenerCount2(emitter, type) { - return emitter.listeners(type).length; - }; - var Stream = require_stream_browser(); - var Buffer2 = require_buffer2().Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var debugUtil = require_util(); - var debug; - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); - } else { - debug = function debug2() { - }; - } - var BufferList = require_buffer_list(); - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors_browser().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - var StringDecoder; - var createReadableStreamAsyncIterator; - var from3; - require_inherits_browser()(Readable, Stream); - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; - function prependListener(emitter, event, fn) { - if (typeof emitter.prependListener === "function") - return emitter.prependListener(event, fn); - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") - isDuplex = stream instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) - this.objectMode = this.objectMode || !!options.readableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - this.sync = true; - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.destroyed = false; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.awaitDrain = 0; - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require_string_decoder().StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { - Duplex = Duplex || require_stream_duplex(); - if (!(this instanceof Readable)) - return new Readable(options); - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); - this.readable = true; - if (options) { - if (typeof options.read === "function") - this._read = options.read; - if (typeof options.destroy === "function") - this._destroy = options.destroy; - } - Stream.call(this); - } - Object.defineProperty(Readable.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._readableState === void 0) { - return false; - } - return this._readableState.destroyed; - }, - set: function set2(value) { - if (!this._readableState) { - return; - } - this._readableState.destroyed = value; - } - }); - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - Readable.prototype._destroy = function(err, cb) { - cb(err); - }; - Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - if (!state.objectMode) { - if (typeof chunk === "string") { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer2.from(chunk, encoding); - encoding = ""; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; - Readable.prototype.unshift = function(chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug("readableAddChunk", chunk); - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) - er = chunkInvalid(state, chunk); - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state.endEmitted) - errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); - else - addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) - addChunk(stream, state, chunk, false); - else - maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit("data", chunk); - } else { - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) - state.buffer.unshift(chunk); - else - state.buffer.push(chunk); - if (state.needReadable) - emitReadable(stream); - } - maybeReadMore(stream, state); - } - function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); - } - return er; - } - Readable.prototype.isPaused = function() { - return this._readableState.flowing === false; - }; - Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require_string_decoder().StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; - this._readableState.encoding = this._readableState.decoder.encoding; - var p3 = this._readableState.buffer.head; - var content = ""; - while (p3 !== null) { - content += decoder.write(p3.data); - p3 = p3.next; - } - this._readableState.buffer.clear(); - if (content !== "") - this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; - var MAX_HWM = 1073741824; - function computeNewHighWaterMark(n3) { - if (n3 >= MAX_HWM) { - n3 = MAX_HWM; - } else { - n3--; - n3 |= n3 >>> 1; - n3 |= n3 >>> 2; - n3 |= n3 >>> 4; - n3 |= n3 >>> 8; - n3 |= n3 >>> 16; - n3++; - } - return n3; - } - function howMuchToRead(n3, state) { - if (n3 <= 0 || state.length === 0 && state.ended) - return 0; - if (state.objectMode) - return 1; - if (n3 !== n3) { - if (state.flowing && state.length) - return state.buffer.head.data.length; - else - return state.length; - } - if (n3 > state.highWaterMark) - state.highWaterMark = computeNewHighWaterMark(n3); - if (n3 <= state.length) - return n3; - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; - } - Readable.prototype.read = function(n3) { - debug("read", n3); - n3 = parseInt(n3, 10); - var state = this._readableState; - var nOrig = n3; - if (n3 !== 0) - state.emittedReadable = false; - if (n3 === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug("read: emitReadable", state.length, state.ended); - if (state.length === 0 && state.ended) - endReadable(this); - else - emitReadable(this); - return null; - } - n3 = howMuchToRead(n3, state); - if (n3 === 0 && state.ended) { - if (state.length === 0) - endReadable(this); - return null; - } - var doRead = state.needReadable; - debug("need readable", doRead); - if (state.length === 0 || state.length - n3 < state.highWaterMark) { - doRead = true; - debug("length less than watermark", doRead); - } - if (state.ended || state.reading) { - doRead = false; - debug("reading or ended", doRead); - } else if (doRead) { - debug("do read"); - state.reading = true; - state.sync = true; - if (state.length === 0) - state.needReadable = true; - this._read(state.highWaterMark); - state.sync = false; - if (!state.reading) - n3 = howMuchToRead(nOrig, state); - } - var ret; - if (n3 > 0) - ret = fromList(n3, state); - else - ret = null; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n3 = 0; - } else { - state.length -= n3; - state.awaitDrain = 0; - } - if (state.length === 0) { - if (!state.ended) - state.needReadable = true; - if (nOrig !== n3 && state.ended) - endReadable(this); - } - if (ret !== null) - this.emit("data", ret); - return ret; - }; - function onEofChunk(stream, state) { - debug("onEofChunk"); - if (state.ended) - return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - if (state.sync) { - emitReadable(stream); - } else { - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } - } - function emitReadable(stream) { - var state = stream._readableState; - debug("emitReadable", state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug("emitReadable", state.flowing); - state.emittedReadable = true; - import_process.default.nextTick(emitReadable_, stream); - } - } - function emitReadable_(stream) { - var state = stream._readableState; - debug("emitReadable_", state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit("readable"); - state.emittedReadable = false; - } - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); - } - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - import_process.default.nextTick(maybeReadMore_, stream, state); - } - } - function maybeReadMore_(stream, state) { - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug("maybeReadMore read 0"); - stream.read(0); - if (len === state.length) - break; - } - state.readingMore = false; - } - Readable.prototype._read = function(n3) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); - }; - Readable.prototype.pipe = function(dest, pipeOpts) { - var src2 = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== import_process.default.stdout && dest !== import_process.default.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) - import_process.default.nextTick(endFn); - else - src2.once("end", endFn); - dest.on("unpipe", onunpipe); - function onunpipe(readable, unpipeInfo) { - debug("onunpipe"); - if (readable === src2) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - function onend() { - debug("onend"); - dest.end(); - } - var ondrain = pipeOnDrain(src2); - dest.on("drain", ondrain); - var cleanedUp = false; - function cleanup() { - debug("cleanup"); - dest.removeListener("close", onclose); - dest.removeListener("finish", onfinish); - dest.removeListener("drain", ondrain); - dest.removeListener("error", onerror); - dest.removeListener("unpipe", onunpipe); - src2.removeListener("end", onend); - src2.removeListener("end", unpipe); - src2.removeListener("data", ondata); - cleanedUp = true; - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) - ondrain(); - } - src2.on("data", ondata); - function ondata(chunk) { - debug("ondata"); - var ret = dest.write(chunk); - debug("dest.write", ret); - if (ret === false) { - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug("false write response, pause", state.awaitDrain); - state.awaitDrain++; - } - src2.pause(); - } - } - function onerror(er) { - debug("onerror", er); - unpipe(); - dest.removeListener("error", onerror); - if (EElistenerCount(dest, "error") === 0) - errorOrDestroy(dest, er); - } - prependListener(dest, "error", onerror); - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); - } - dest.once("close", onclose); - function onfinish() { - debug("onfinish"); - dest.removeListener("close", onclose); - unpipe(); - } - dest.once("finish", onfinish); - function unpipe() { - debug("unpipe"); - src2.unpipe(dest); - } - dest.emit("pipe", src2); - if (!state.flowing) { - debug("pipe resume"); - src2.resume(); - } - return dest; - }; - function pipeOnDrain(src2) { - return function pipeOnDrainFunctionResult() { - var state = src2._readableState; - debug("pipeOnDrain", state.awaitDrain); - if (state.awaitDrain) - state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src2, "data")) { - state.flowing = true; - flow(src2); - } - }; - } - Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; - if (state.pipesCount === 0) - return this; - if (state.pipesCount === 1) { - if (dest && dest !== state.pipes) - return this; - if (!dest) - dest = state.pipes; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) - dest.emit("unpipe", this, unpipeInfo); - return this; - } - if (!dest) { - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - for (var i2 = 0; i2 < len; i2++) - dests[i2].emit("unpipe", this, { - hasUnpiped: false - }); - return this; - } - var index = indexOf(state.pipes, dest); - if (index === -1) - return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - dest.emit("unpipe", this, unpipeInfo); - return this; - }; - Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - if (ev === "data") { - state.readableListening = this.listenerCount("readable") > 0; - if (state.flowing !== false) - this.resume(); - } else if (ev === "readable") { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug("on readable", state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - import_process.default.nextTick(nReadingNextTick, this); - } - } - } - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - Readable.prototype.removeListener = function(ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - if (ev === "readable") { - import_process.default.nextTick(updateReadableListening, this); - } - return res; - }; - Readable.prototype.removeAllListeners = function(ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === "readable" || ev === void 0) { - import_process.default.nextTick(updateReadableListening, this); - } - return res; - }; - function updateReadableListening(self2) { - var state = self2._readableState; - state.readableListening = self2.listenerCount("readable") > 0; - if (state.resumeScheduled && !state.paused) { - state.flowing = true; - } else if (self2.listenerCount("data") > 0) { - self2.resume(); - } - } - function nReadingNextTick(self2) { - debug("readable nexttick read 0"); - self2.read(0); - } - Readable.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug("resume"); - state.flowing = !state.readableListening; - resume(this, state); - } - state.paused = false; - return this; - }; - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - import_process.default.nextTick(resume_, stream, state); - } - } - function resume_(stream, state) { - debug("resume", state.reading); - if (!state.reading) { - stream.read(0); - } - state.resumeScheduled = false; - stream.emit("resume"); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); - } - Readable.prototype.pause = function() { - debug("call pause flowing=%j", this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug("pause"); - this._readableState.flowing = false; - this.emit("pause"); - } - this._readableState.paused = true; - return this; - }; - function flow(stream) { - var state = stream._readableState; - debug("flow", state.flowing); - while (state.flowing && stream.read() !== null) - ; - } - Readable.prototype.wrap = function(stream) { - var _this = this; - var state = this._readableState; - var paused = false; - stream.on("end", function() { - debug("wrapped end"); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - _this.push(chunk); - } - _this.push(null); - }); - stream.on("data", function(chunk) { - debug("wrapped data"); - if (state.decoder) - chunk = state.decoder.write(chunk); - if (state.objectMode && (chunk === null || chunk === void 0)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - for (var i2 in stream) { - if (this[i2] === void 0 && typeof stream[i2] === "function") { - this[i2] = /* @__PURE__ */ function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i2); - } - } - for (var n3 = 0; n3 < kProxyEvents.length; n3++) { - stream.on(kProxyEvents[n3], this.emit.bind(this, kProxyEvents[n3])); - } - this._read = function(n4) { - debug("wrapped _read", n4); - if (paused) { - paused = false; - stream.resume(); - } - }; - return this; - }; - if (typeof Symbol === "function") { - Readable.prototype[Symbol.asyncIterator] = function() { - if (createReadableStreamAsyncIterator === void 0) { - createReadableStreamAsyncIterator = require_async_iterator(); - } - return createReadableStreamAsyncIterator(this); - }; - } - Object.defineProperty(Readable.prototype, "readableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable.prototype, "readableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable.prototype, "readableFlowing", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.flowing; - }, - set: function set2(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); - Readable._fromList = fromList; - Object.defineProperty(Readable.prototype, "readableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.length; - } - }); - function fromList(n3, state) { - if (state.length === 0) - return null; - var ret; - if (state.objectMode) - ret = state.buffer.shift(); - else if (!n3 || n3 >= state.length) { - if (state.decoder) - ret = state.buffer.join(""); - else if (state.buffer.length === 1) - ret = state.buffer.first(); - else - ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - ret = state.buffer.consume(n3, state.decoder); - } - return ret; - } - function endReadable(stream) { - var state = stream._readableState; - debug("endReadable", state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - import_process.default.nextTick(endReadableNT, state, stream); - } - } - function endReadableNT(state, stream) { - debug("endReadableNT", state.endEmitted, state.length); - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit("end"); - if (state.autoDestroy) { - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } - } - if (typeof Symbol === "function") { - Readable.from = function(iterable, opts) { - if (from3 === void 0) { - from3 = require_from_browser(); - } - return from3(Readable, iterable, opts); - }; - } - function indexOf(xs, x3) { - for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { - if (xs[i2] === x3) - return i2; - } - return -1; - } - } -}); - -// node_modules/readable-stream/lib/_stream_transform.js -var require_stream_transform = __commonJS({ - "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Transform; - var _require$codes = require_errors_browser().codes; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; - var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - var Duplex = require_stream_duplex(); - require_inherits_browser()(Transform, Duplex); - function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (cb === null) { - return this.emit("error", new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data != null) - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } - } - function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - this._readableState.needReadable = true; - this._readableState.sync = false; - if (options) { - if (typeof options.transform === "function") - this._transform = options.transform; - if (typeof options.flush === "function") - this._flush = options.flush; - } - this.on("prefinish", prefinish); - } - function prefinish() { - var _this = this; - if (typeof this._flush === "function" && !this._readableState.destroyed) { - this._flush(function(er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } - } - Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - Transform.prototype._transform = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); - }; - Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } - }; - Transform.prototype._read = function(n3) { - var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - ts.needTransform = true; - } - }; - Transform.prototype._destroy = function(err, cb) { - Duplex.prototype._destroy.call(this, err, function(err2) { - cb(err2); - }); - }; - function done(stream, er, data) { - if (er) - return stream.emit("error", er); - if (data != null) - stream.push(data); - if (stream._writableState.length) - throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) - throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } - } -}); - -// node_modules/readable-stream/lib/_stream_passthrough.js -var require_stream_passthrough = __commonJS({ - "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = PassThrough; - var Transform = require_stream_transform(); - require_inherits_browser()(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - Transform.call(this, options); - } - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { - "use strict"; - init_shim(); - var eos; - function once(callback) { - var called = false; - return function() { - if (called) - return; - called = true; - callback.apply(void 0, arguments); - }; - } - var _require$codes = require_errors_browser().codes; - var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - function noop(err) { - if (err) - throw err; - } - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on("close", function() { - closed = true; - }); - if (eos === void 0) - eos = require_end_of_stream(); - eos(stream, { - readable: reading, - writable: writing - }, function(err) { - if (err) - return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function(err) { - if (closed) - return; - if (destroyed) - return; - destroyed = true; - if (isRequest(stream)) - return stream.abort(); - if (typeof stream.destroy === "function") - return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED("pipe")); - }; - } - function call(fn) { - fn(); - } - function pipe(from3, to) { - return from3.pipe(to); - } - function popCallback(streams) { - if (!streams.length) - return noop; - if (typeof streams[streams.length - 1] !== "function") - return noop; - return streams.pop(); - } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) - streams = streams[0]; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS("streams"); - } - var error; - var destroys = streams.map(function(stream, i2) { - var reading = i2 < streams.length - 1; - var writing = i2 > 0; - return destroyer(stream, reading, writing, function(err) { - if (!error) - error = err; - if (err) - destroys.forEach(call); - if (reading) - return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } - module2.exports = pipeline; - } -}); - -// node_modules/readable-stream/readable-browser.js -var require_readable_browser = __commonJS({ - "node_modules/readable-stream/readable-browser.js"(exports2, module2) { - init_shim(); - exports2 = module2.exports = require_stream_readable(); - exports2.Stream = exports2; - exports2.Readable = exports2; - exports2.Writable = require_stream_writable(); - exports2.Duplex = require_stream_duplex(); - exports2.Transform = require_stream_transform(); - exports2.PassThrough = require_stream_passthrough(); - exports2.finished = require_end_of_stream(); - exports2.pipeline = require_pipeline(); - } -}); - -// node_modules/keccak/lib/api/keccak.js -var require_keccak = __commonJS({ - "node_modules/keccak/lib/api/keccak.js"(exports2, module2) { - init_shim(); - var { Transform } = require_readable_browser(); - module2.exports = (KeccakState) => class Keccak extends Transform { - constructor(rate, capacity, delimitedSuffix, hashBitLength, options) { - super(options); - this._rate = rate; - this._capacity = capacity; - this._delimitedSuffix = delimitedSuffix; - this._hashBitLength = hashBitLength; - this._options = options; - this._state = new KeccakState(); - this._state.initialize(rate, capacity); - this._finalized = false; - } - _transform(chunk, encoding, callback) { - let error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - callback(error); - } - _flush(callback) { - let error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } - callback(error); - } - update(data, encoding) { - if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") - throw new TypeError("Data must be a string or a buffer"); - if (this._finalized) - throw new Error("Digest already called"); - if (!import_buffer.Buffer.isBuffer(data)) - data = import_buffer.Buffer.from(data, encoding); - this._state.absorb(data); - return this; - } - digest(encoding) { - if (this._finalized) - throw new Error("Digest already called"); - this._finalized = true; - if (this._delimitedSuffix) - this._state.absorbLastFewBits(this._delimitedSuffix); - let digest2 = this._state.squeeze(this._hashBitLength / 8); - if (encoding !== void 0) - digest2 = digest2.toString(encoding); - this._resetState(); - return digest2; - } - // remove result from memory - _resetState() { - this._state.initialize(this._rate, this._capacity); - return this; - } - // because sometimes we need hash right now and little later - _clone() { - const clone2 = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options); - this._state.copy(clone2._state); - clone2._finalized = this._finalized; - return clone2; - } - }; - } -}); - -// node_modules/keccak/lib/api/shake.js -var require_shake = __commonJS({ - "node_modules/keccak/lib/api/shake.js"(exports2, module2) { - init_shim(); - var { Transform } = require_readable_browser(); - module2.exports = (KeccakState) => class Shake extends Transform { - constructor(rate, capacity, delimitedSuffix, options) { - super(options); - this._rate = rate; - this._capacity = capacity; - this._delimitedSuffix = delimitedSuffix; - this._options = options; - this._state = new KeccakState(); - this._state.initialize(rate, capacity); - this._finalized = false; - } - _transform(chunk, encoding, callback) { - let error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - callback(error); - } - _flush() { - } - _read(size) { - this.push(this.squeeze(size)); - } - update(data, encoding) { - if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") - throw new TypeError("Data must be a string or a buffer"); - if (this._finalized) - throw new Error("Squeeze already called"); - if (!import_buffer.Buffer.isBuffer(data)) - data = import_buffer.Buffer.from(data, encoding); - this._state.absorb(data); - return this; - } - squeeze(dataByteLength, encoding) { - if (!this._finalized) { - this._finalized = true; - this._state.absorbLastFewBits(this._delimitedSuffix); - } - let data = this._state.squeeze(dataByteLength); - if (encoding !== void 0) - data = data.toString(encoding); - return data; - } - _resetState() { - this._state.initialize(this._rate, this._capacity); - return this; - } - _clone() { - const clone2 = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options); - this._state.copy(clone2._state); - clone2._finalized = this._finalized; - return clone2; - } - }; - } -}); - -// node_modules/keccak/lib/api/index.js -var require_api = __commonJS({ - "node_modules/keccak/lib/api/index.js"(exports2, module2) { - init_shim(); - var createKeccak = require_keccak(); - var createShake = require_shake(); - module2.exports = function(KeccakState) { - const Keccak = createKeccak(KeccakState); - const Shake = createShake(KeccakState); - return function(algorithm, options) { - const hash = typeof algorithm === "string" ? algorithm.toLowerCase() : algorithm; - switch (hash) { - case "keccak224": - return new Keccak(1152, 448, null, 224, options); - case "keccak256": - return new Keccak(1088, 512, null, 256, options); - case "keccak384": - return new Keccak(832, 768, null, 384, options); - case "keccak512": - return new Keccak(576, 1024, null, 512, options); - case "sha3-224": - return new Keccak(1152, 448, 6, 224, options); - case "sha3-256": - return new Keccak(1088, 512, 6, 256, options); - case "sha3-384": - return new Keccak(832, 768, 6, 384, options); - case "sha3-512": - return new Keccak(576, 1024, 6, 512, options); - case "shake128": - return new Shake(1344, 256, 31, options); - case "shake256": - return new Shake(1088, 512, 31, options); - default: - throw new Error("Invald algorithm: " + algorithm); - } - }; - }; - } -}); - -// node_modules/keccak/lib/keccak-state-unroll.js -var require_keccak_state_unroll = __commonJS({ - "node_modules/keccak/lib/keccak-state-unroll.js"(exports2) { - init_shim(); - var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; - exports2.p1600 = function(s2) { - for (let round = 0; round < 24; ++round) { - const lo0 = s2[0] ^ s2[10] ^ s2[20] ^ s2[30] ^ s2[40]; - const hi0 = s2[1] ^ s2[11] ^ s2[21] ^ s2[31] ^ s2[41]; - const lo1 = s2[2] ^ s2[12] ^ s2[22] ^ s2[32] ^ s2[42]; - const hi1 = s2[3] ^ s2[13] ^ s2[23] ^ s2[33] ^ s2[43]; - const lo2 = s2[4] ^ s2[14] ^ s2[24] ^ s2[34] ^ s2[44]; - const hi2 = s2[5] ^ s2[15] ^ s2[25] ^ s2[35] ^ s2[45]; - const lo3 = s2[6] ^ s2[16] ^ s2[26] ^ s2[36] ^ s2[46]; - const hi3 = s2[7] ^ s2[17] ^ s2[27] ^ s2[37] ^ s2[47]; - const lo4 = s2[8] ^ s2[18] ^ s2[28] ^ s2[38] ^ s2[48]; - const hi4 = s2[9] ^ s2[19] ^ s2[29] ^ s2[39] ^ s2[49]; - let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31); - let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31); - const t1slo0 = s2[0] ^ lo; - const t1shi0 = s2[1] ^ hi; - const t1slo5 = s2[10] ^ lo; - const t1shi5 = s2[11] ^ hi; - const t1slo10 = s2[20] ^ lo; - const t1shi10 = s2[21] ^ hi; - const t1slo15 = s2[30] ^ lo; - const t1shi15 = s2[31] ^ hi; - const t1slo20 = s2[40] ^ lo; - const t1shi20 = s2[41] ^ hi; - lo = lo0 ^ (lo2 << 1 | hi2 >>> 31); - hi = hi0 ^ (hi2 << 1 | lo2 >>> 31); - const t1slo1 = s2[2] ^ lo; - const t1shi1 = s2[3] ^ hi; - const t1slo6 = s2[12] ^ lo; - const t1shi6 = s2[13] ^ hi; - const t1slo11 = s2[22] ^ lo; - const t1shi11 = s2[23] ^ hi; - const t1slo16 = s2[32] ^ lo; - const t1shi16 = s2[33] ^ hi; - const t1slo21 = s2[42] ^ lo; - const t1shi21 = s2[43] ^ hi; - lo = lo1 ^ (lo3 << 1 | hi3 >>> 31); - hi = hi1 ^ (hi3 << 1 | lo3 >>> 31); - const t1slo2 = s2[4] ^ lo; - const t1shi2 = s2[5] ^ hi; - const t1slo7 = s2[14] ^ lo; - const t1shi7 = s2[15] ^ hi; - const t1slo12 = s2[24] ^ lo; - const t1shi12 = s2[25] ^ hi; - const t1slo17 = s2[34] ^ lo; - const t1shi17 = s2[35] ^ hi; - const t1slo22 = s2[44] ^ lo; - const t1shi22 = s2[45] ^ hi; - lo = lo2 ^ (lo4 << 1 | hi4 >>> 31); - hi = hi2 ^ (hi4 << 1 | lo4 >>> 31); - const t1slo3 = s2[6] ^ lo; - const t1shi3 = s2[7] ^ hi; - const t1slo8 = s2[16] ^ lo; - const t1shi8 = s2[17] ^ hi; - const t1slo13 = s2[26] ^ lo; - const t1shi13 = s2[27] ^ hi; - const t1slo18 = s2[36] ^ lo; - const t1shi18 = s2[37] ^ hi; - const t1slo23 = s2[46] ^ lo; - const t1shi23 = s2[47] ^ hi; - lo = lo3 ^ (lo0 << 1 | hi0 >>> 31); - hi = hi3 ^ (hi0 << 1 | lo0 >>> 31); - const t1slo4 = s2[8] ^ lo; - const t1shi4 = s2[9] ^ hi; - const t1slo9 = s2[18] ^ lo; - const t1shi9 = s2[19] ^ hi; - const t1slo14 = s2[28] ^ lo; - const t1shi14 = s2[29] ^ hi; - const t1slo19 = s2[38] ^ lo; - const t1shi19 = s2[39] ^ hi; - const t1slo24 = s2[48] ^ lo; - const t1shi24 = s2[49] ^ hi; - const t2slo0 = t1slo0; - const t2shi0 = t1shi0; - const t2slo16 = t1shi5 << 4 | t1slo5 >>> 28; - const t2shi16 = t1slo5 << 4 | t1shi5 >>> 28; - const t2slo7 = t1slo10 << 3 | t1shi10 >>> 29; - const t2shi7 = t1shi10 << 3 | t1slo10 >>> 29; - const t2slo23 = t1shi15 << 9 | t1slo15 >>> 23; - const t2shi23 = t1slo15 << 9 | t1shi15 >>> 23; - const t2slo14 = t1slo20 << 18 | t1shi20 >>> 14; - const t2shi14 = t1shi20 << 18 | t1slo20 >>> 14; - const t2slo10 = t1slo1 << 1 | t1shi1 >>> 31; - const t2shi10 = t1shi1 << 1 | t1slo1 >>> 31; - const t2slo1 = t1shi6 << 12 | t1slo6 >>> 20; - const t2shi1 = t1slo6 << 12 | t1shi6 >>> 20; - const t2slo17 = t1slo11 << 10 | t1shi11 >>> 22; - const t2shi17 = t1shi11 << 10 | t1slo11 >>> 22; - const t2slo8 = t1shi16 << 13 | t1slo16 >>> 19; - const t2shi8 = t1slo16 << 13 | t1shi16 >>> 19; - const t2slo24 = t1slo21 << 2 | t1shi21 >>> 30; - const t2shi24 = t1shi21 << 2 | t1slo21 >>> 30; - const t2slo20 = t1shi2 << 30 | t1slo2 >>> 2; - const t2shi20 = t1slo2 << 30 | t1shi2 >>> 2; - const t2slo11 = t1slo7 << 6 | t1shi7 >>> 26; - const t2shi11 = t1shi7 << 6 | t1slo7 >>> 26; - const t2slo2 = t1shi12 << 11 | t1slo12 >>> 21; - const t2shi2 = t1slo12 << 11 | t1shi12 >>> 21; - const t2slo18 = t1slo17 << 15 | t1shi17 >>> 17; - const t2shi18 = t1shi17 << 15 | t1slo17 >>> 17; - const t2slo9 = t1shi22 << 29 | t1slo22 >>> 3; - const t2shi9 = t1slo22 << 29 | t1shi22 >>> 3; - const t2slo5 = t1slo3 << 28 | t1shi3 >>> 4; - const t2shi5 = t1shi3 << 28 | t1slo3 >>> 4; - const t2slo21 = t1shi8 << 23 | t1slo8 >>> 9; - const t2shi21 = t1slo8 << 23 | t1shi8 >>> 9; - const t2slo12 = t1slo13 << 25 | t1shi13 >>> 7; - const t2shi12 = t1shi13 << 25 | t1slo13 >>> 7; - const t2slo3 = t1slo18 << 21 | t1shi18 >>> 11; - const t2shi3 = t1shi18 << 21 | t1slo18 >>> 11; - const t2slo19 = t1shi23 << 24 | t1slo23 >>> 8; - const t2shi19 = t1slo23 << 24 | t1shi23 >>> 8; - const t2slo15 = t1slo4 << 27 | t1shi4 >>> 5; - const t2shi15 = t1shi4 << 27 | t1slo4 >>> 5; - const t2slo6 = t1slo9 << 20 | t1shi9 >>> 12; - const t2shi6 = t1shi9 << 20 | t1slo9 >>> 12; - const t2slo22 = t1shi14 << 7 | t1slo14 >>> 25; - const t2shi22 = t1slo14 << 7 | t1shi14 >>> 25; - const t2slo13 = t1slo19 << 8 | t1shi19 >>> 24; - const t2shi13 = t1shi19 << 8 | t1slo19 >>> 24; - const t2slo4 = t1slo24 << 14 | t1shi24 >>> 18; - const t2shi4 = t1shi24 << 14 | t1slo24 >>> 18; - s2[0] = t2slo0 ^ ~t2slo1 & t2slo2; - s2[1] = t2shi0 ^ ~t2shi1 & t2shi2; - s2[10] = t2slo5 ^ ~t2slo6 & t2slo7; - s2[11] = t2shi5 ^ ~t2shi6 & t2shi7; - s2[20] = t2slo10 ^ ~t2slo11 & t2slo12; - s2[21] = t2shi10 ^ ~t2shi11 & t2shi12; - s2[30] = t2slo15 ^ ~t2slo16 & t2slo17; - s2[31] = t2shi15 ^ ~t2shi16 & t2shi17; - s2[40] = t2slo20 ^ ~t2slo21 & t2slo22; - s2[41] = t2shi20 ^ ~t2shi21 & t2shi22; - s2[2] = t2slo1 ^ ~t2slo2 & t2slo3; - s2[3] = t2shi1 ^ ~t2shi2 & t2shi3; - s2[12] = t2slo6 ^ ~t2slo7 & t2slo8; - s2[13] = t2shi6 ^ ~t2shi7 & t2shi8; - s2[22] = t2slo11 ^ ~t2slo12 & t2slo13; - s2[23] = t2shi11 ^ ~t2shi12 & t2shi13; - s2[32] = t2slo16 ^ ~t2slo17 & t2slo18; - s2[33] = t2shi16 ^ ~t2shi17 & t2shi18; - s2[42] = t2slo21 ^ ~t2slo22 & t2slo23; - s2[43] = t2shi21 ^ ~t2shi22 & t2shi23; - s2[4] = t2slo2 ^ ~t2slo3 & t2slo4; - s2[5] = t2shi2 ^ ~t2shi3 & t2shi4; - s2[14] = t2slo7 ^ ~t2slo8 & t2slo9; - s2[15] = t2shi7 ^ ~t2shi8 & t2shi9; - s2[24] = t2slo12 ^ ~t2slo13 & t2slo14; - s2[25] = t2shi12 ^ ~t2shi13 & t2shi14; - s2[34] = t2slo17 ^ ~t2slo18 & t2slo19; - s2[35] = t2shi17 ^ ~t2shi18 & t2shi19; - s2[44] = t2slo22 ^ ~t2slo23 & t2slo24; - s2[45] = t2shi22 ^ ~t2shi23 & t2shi24; - s2[6] = t2slo3 ^ ~t2slo4 & t2slo0; - s2[7] = t2shi3 ^ ~t2shi4 & t2shi0; - s2[16] = t2slo8 ^ ~t2slo9 & t2slo5; - s2[17] = t2shi8 ^ ~t2shi9 & t2shi5; - s2[26] = t2slo13 ^ ~t2slo14 & t2slo10; - s2[27] = t2shi13 ^ ~t2shi14 & t2shi10; - s2[36] = t2slo18 ^ ~t2slo19 & t2slo15; - s2[37] = t2shi18 ^ ~t2shi19 & t2shi15; - s2[46] = t2slo23 ^ ~t2slo24 & t2slo20; - s2[47] = t2shi23 ^ ~t2shi24 & t2shi20; - s2[8] = t2slo4 ^ ~t2slo0 & t2slo1; - s2[9] = t2shi4 ^ ~t2shi0 & t2shi1; - s2[18] = t2slo9 ^ ~t2slo5 & t2slo6; - s2[19] = t2shi9 ^ ~t2shi5 & t2shi6; - s2[28] = t2slo14 ^ ~t2slo10 & t2slo11; - s2[29] = t2shi14 ^ ~t2shi10 & t2shi11; - s2[38] = t2slo19 ^ ~t2slo15 & t2slo16; - s2[39] = t2shi19 ^ ~t2shi15 & t2shi16; - s2[48] = t2slo24 ^ ~t2slo20 & t2slo21; - s2[49] = t2shi24 ^ ~t2shi20 & t2shi21; - s2[0] ^= P1600_ROUND_CONSTANTS[round * 2]; - s2[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]; - } - }; - } -}); - -// node_modules/keccak/lib/keccak.js -var require_keccak2 = __commonJS({ - "node_modules/keccak/lib/keccak.js"(exports2, module2) { - init_shim(); - var keccakState = require_keccak_state_unroll(); - function Keccak() { - this.state = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - this.blockSize = null; - this.count = 0; - this.squeezing = false; - } - Keccak.prototype.initialize = function(rate, capacity) { - for (let i2 = 0; i2 < 50; ++i2) - this.state[i2] = 0; - this.blockSize = rate / 8; - this.count = 0; - this.squeezing = false; - }; - Keccak.prototype.absorb = function(data) { - for (let i2 = 0; i2 < data.length; ++i2) { - this.state[~~(this.count / 4)] ^= data[i2] << 8 * (this.count % 4); - this.count += 1; - if (this.count === this.blockSize) { - keccakState.p1600(this.state); - this.count = 0; - } - } - }; - Keccak.prototype.absorbLastFewBits = function(bits) { - this.state[~~(this.count / 4)] ^= bits << 8 * (this.count % 4); - if ((bits & 128) !== 0 && this.count === this.blockSize - 1) - keccakState.p1600(this.state); - this.state[~~((this.blockSize - 1) / 4)] ^= 128 << 8 * ((this.blockSize - 1) % 4); - keccakState.p1600(this.state); - this.count = 0; - this.squeezing = true; - }; - Keccak.prototype.squeeze = function(length2) { - if (!this.squeezing) - this.absorbLastFewBits(1); - const output = import_buffer.Buffer.alloc(length2); - for (let i2 = 0; i2 < length2; ++i2) { - output[i2] = this.state[~~(this.count / 4)] >>> 8 * (this.count % 4) & 255; - this.count += 1; - if (this.count === this.blockSize) { - keccakState.p1600(this.state); - this.count = 0; - } - } - return output; - }; - Keccak.prototype.copy = function(dest) { - for (let i2 = 0; i2 < 50; ++i2) - dest.state[i2] = this.state[i2]; - dest.blockSize = this.blockSize; - dest.count = this.count; - dest.squeezing = this.squeezing; - }; - module2.exports = Keccak; - } -}); - -// node_modules/keccak/js.js -var require_js = __commonJS({ - "node_modules/keccak/js.js"(exports2, module2) { - init_shim(); - module2.exports = require_api()(require_keccak2()); - } -}); - -// node_modules/@multiversx/sdk-core/out/address.js -var require_address = __commonJS({ - "node_modules/@multiversx/sdk-core/out/address.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AddressComputer = exports2.Address = void 0; - var bech32 = __importStar2(require_bech32()); - var bignumber_js_1 = __importDefault2(require_bignumber()); - var constants_1 = require_constants(); - var errors = __importStar2(require_errors()); - var codec_1 = require_codec(); - var createKeccakHash = require_js(); - var HRP = "erd"; - var PUBKEY_LENGTH = 32; - var SMART_CONTRACT_HEX_PUBKEY_PREFIX = "0".repeat(16); - var Address5 = class _Address { - /** - * Creates an address object, given a raw string (whether a hex pubkey or a Bech32 address), a sequence of bytes, or another Address object. - */ - constructor(value) { - this.valueHex = ""; - if (!value) { - return; - } - if (value instanceof _Address) { - return _Address.fromAddress(value); - } - if (ArrayBuffer.isView(value)) { - return _Address.fromBuffer(import_buffer.Buffer.from(value)); - } - if (typeof value === "string") { - return _Address.fromString(value); - } - throw new errors.ErrAddressCannotCreate(value); - } - /** - * Creates an address object from another address object - */ - static fromAddress(address) { - return _Address.fromValidHex(address.valueHex); - } - static fromValidHex(value) { - let result = _Address.empty(); - result.valueHex = value; - return result; - } - /** - * Creates an address object from a Buffer - */ - static fromBuffer(buffer) { - if (buffer.length != PUBKEY_LENGTH) { - throw new errors.ErrAddressCannotCreate(buffer); - } - return _Address.fromValidHex(buffer.toString("hex")); - } - /** - * Creates an address object from a string (hex or bech32) - */ - static fromString(value) { - if (_Address.isValidHex(value)) { - return _Address.fromValidHex(value); - } - return _Address.fromBech32(value); - } - static isValidHex(value) { - return import_buffer.Buffer.from(value, "hex").length == PUBKEY_LENGTH; - } - /** - * Creates an address object from a hex-encoded string - */ - static fromHex(value) { - if (!_Address.isValidHex(value)) { - throw new errors.ErrAddressCannotCreate(value); - } - return _Address.fromValidHex(value); - } - /** - * Creates an empty address object. - * Generally speaking, this should not be used by client code (internal use only). - */ - static empty() { - return new _Address(""); - } - /** - * Creates an address object from a bech32-encoded string - */ - static fromBech32(value) { - let decoded; - try { - decoded = bech32.decode(value); - } catch (err) { - throw new errors.ErrAddressCannotCreate(value, err); - } - const prefix = decoded.prefix; - if (prefix != HRP) { - throw new errors.ErrAddressBadHrp(HRP, prefix); - } - const pubkey = import_buffer.Buffer.from(bech32.fromWords(decoded.words)); - if (pubkey.length != PUBKEY_LENGTH) { - throw new errors.ErrAddressCannotCreate(value); - } - return _Address.fromValidHex(pubkey.toString("hex")); - } - /** - * Performs address validation without throwing errors - */ - static isValid(value) { - const decoded = bech32.decodeUnsafe(value); - const prefix = decoded?.prefix; - const pubkey = decoded ? import_buffer.Buffer.from(bech32.fromWords(decoded.words)) : void 0; - if (prefix !== HRP || pubkey?.length !== PUBKEY_LENGTH) { - return false; - } - return true; - } - /** - * Use {@link toHex} instead. - */ - hex() { - return this.toHex(); - } - /** - * Returns the hex representation of the address (pubkey) - */ - toHex() { - if (this.isEmpty()) { - return ""; - } - return this.valueHex; - } - /** - * Use {@link toBech32} instead. - */ - bech32() { - return this.toBech32(); - } - /** - * Returns the bech32 representation of the address - */ - toBech32() { - if (this.isEmpty()) { - return ""; - } - let words = bech32.toWords(this.pubkey()); - let address = bech32.encode(HRP, words); - return address; - } - /** - * Use {@link getPublicKey} instead. - */ - pubkey() { - return this.getPublicKey(); - } - /** - * Returns the pubkey as raw bytes (buffer) - */ - getPublicKey() { - if (this.isEmpty()) { - return import_buffer.Buffer.from([]); - } - return import_buffer.Buffer.from(this.valueHex, "hex"); - } - /** - * Returns the human-readable-part of the bech32 addresses. - * The HRP is currently hardcoded to "erd". - */ - getHrp() { - return HRP; - } - /** - * Returns whether the address is empty. - */ - isEmpty() { - return !this.valueHex; - } - /** - * Compares the address to another address - */ - equals(other) { - if (!other) { - return false; - } - return this.valueHex == other.valueHex; - } - /** - * Returns the bech32 representation of the address - */ - toString() { - return this.toBech32(); - } - /** - * Converts the address to a pretty, plain JavaScript object. - */ - toJSON() { - return { - bech32: this.toBech32(), - pubkey: this.toHex() - }; - } - /** - * Creates the Zero address (the one that should be used when deploying smart contracts). - * Generally speaking, this should not be used by client code (internal use only). - */ - static Zero() { - return new _Address("0".repeat(64)); - } - /** - * Use {@link isSmartContract} instead. - */ - isContractAddress() { - return this.isSmartContract(); - } - /** - * Returns whether the address is a smart contract address. - */ - isSmartContract() { - return this.toHex().startsWith(SMART_CONTRACT_HEX_PUBKEY_PREFIX); - } - }; - exports2.Address = Address5; - var AddressComputer = class { - constructor(numberOfShardsWithoutMeta) { - this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || constants_1.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; - } - computeContractAddress(deployer, deploymentNonce) { - const initialPadding = import_buffer.Buffer.alloc(8, 0); - const ownerPubkey = deployer.getPublicKey(); - const shardSelector = ownerPubkey.slice(30); - const ownerNonceBytes = import_buffer.Buffer.alloc(8); - const bigNonce = new bignumber_js_1.default(deploymentNonce.toString()); - const bigNonceBuffer = codec_1.bigIntToBuffer(bigNonce); - ownerNonceBytes.write(bigNonceBuffer.reverse().toString("hex"), "hex"); - const bytesToHash = import_buffer.Buffer.concat([ownerPubkey, ownerNonceBytes]); - const hash = createKeccakHash("keccak256").update(bytesToHash).digest(); - const vmTypeBytes = import_buffer.Buffer.from(constants_1.WasmVirtualMachine, "hex"); - const addressBytes = import_buffer.Buffer.concat([initialPadding, vmTypeBytes, hash.slice(10, 30), shardSelector]); - return new Address5(addressBytes); - } - getShardOfAddress(address) { - return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); - } - getShardOfPubkey(pubkey, numberOfShards) { - const maskHigh = parseInt("11", 2); - const maskLow = parseInt("01", 2); - const lastByteOfPubkey = pubkey[31]; - if (this.isPubkeyOfMetachain(pubkey)) { - return constants_1.METACHAIN_ID; - } - let shard = lastByteOfPubkey & maskHigh; - if (shard > numberOfShards - 1) { - shard = lastByteOfPubkey & maskLow; - } - return shard; - } - isPubkeyOfMetachain(pubkey) { - const metachainPrefix = import_buffer.Buffer.from([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]); - const pubkeyPrefix = import_buffer.Buffer.from(pubkey).slice(0, metachainPrefix.length); - if (metachainPrefix.equals(pubkeyPrefix)) { - return true; - } - const zeroAddress = import_buffer.Buffer.alloc(32); - if (zeroAddress.equals(import_buffer.Buffer.from(pubkey))) { - return true; - } - return false; - } - }; - exports2.AddressComputer = AddressComputer; - } -}); - -// node_modules/@multiversx/sdk-core/out/utils.js -var require_utils2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/utils.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isEmpty = exports2.guardEmpty = exports2.guardNotEmpty = exports2.guardLength = exports2.guardSameLength = exports2.guardValueIsSetWithMessage = exports2.guardValueIsSet = exports2.guardTrue = void 0; - var errors = __importStar2(require_errors()); - function guardTrue(value, what) { - if (!value) { - throw new errors.ErrInvariantFailed(`[<${what}>] isn't true`); - } - } - exports2.guardTrue = guardTrue; - function guardValueIsSet(name2, value) { - guardValueIsSetWithMessage(`${name2} isn't set (null or undefined)`, value); - } - exports2.guardValueIsSet = guardValueIsSet; - function guardValueIsSetWithMessage(message, value) { - if (value == null || value === void 0) { - throw new errors.ErrInvariantFailed(message); - } - } - exports2.guardValueIsSetWithMessage = guardValueIsSetWithMessage; - function guardSameLength(a3, b4) { - a3 = a3 || []; - b4 = b4 || []; - if (a3.length != b4.length) { - throw new errors.ErrInvariantFailed("arrays do not have the same length"); - } - } - exports2.guardSameLength = guardSameLength; - function guardLength(withLength, expectedLength) { - let actualLength = withLength.length || 0; - if (actualLength != expectedLength) { - throw new errors.ErrInvariantFailed(`wrong length, expected: ${expectedLength}, actual: ${actualLength}`); - } - } - exports2.guardLength = guardLength; - function guardNotEmpty(value, what) { - if (isEmpty(value)) { - throw new errors.ErrInvariantFailed(`${what} is empty`); - } - } - exports2.guardNotEmpty = guardNotEmpty; - function guardEmpty(value, what) { - if (!isEmpty(value)) { - throw new errors.ErrInvariantFailed(`${what} is not empty`); - } - } - exports2.guardEmpty = guardEmpty; - function isEmpty(value) { - if (value.isEmpty) { - return value.isEmpty(); - } - return value.length === 0; - } - exports2.isEmpty = isEmpty; - } -}); - -// node_modules/@multiversx/sdk-core/out/abi/typeFormula.js -var require_typeFormula = __commonJS({ - "node_modules/@multiversx/sdk-core/out/abi/typeFormula.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeFormula = void 0; - var TypeFormula = class { - constructor(name2, typeParameters) { - this.name = name2; - this.typeParameters = typeParameters; - } - toString() { - if (this.typeParameters.length > 0) { - const typeParameters = this.typeParameters.map((typeParameter) => typeParameter.toString()).join(", "); - return `${this.name}<${typeParameters}>`; - } else { - return this.name; - } - } - }; - exports2.TypeFormula = TypeFormula; - } -}); - -// node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js -var require_typeFormulaParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeFormulaParser = void 0; - var typeFormula_1 = require_typeFormula(); - var TypeFormulaParser = class _TypeFormulaParser { - parseExpression(expression) { - expression = expression.trim(); - const tokens = this.tokenizeExpression(expression).filter((token) => token !== _TypeFormulaParser.COMMA); - const stack = []; - for (const token of tokens) { - if (this.isPunctuation(token)) { - if (this.isEndOfTypeParameters(token)) { - const typeFormula = this.acquireTypeWithParameters(stack); - stack.push(typeFormula); - } else if (this.isBeginningOfTypeParameters(token)) { - stack.push(token); - } else { - throw new Error(`Unexpected token (punctuation): ${token}`); - } - } else { - stack.push(token); - } - } - if (stack.length !== 1) { - throw new Error(`Unexpected stack length at end of parsing: ${stack.length}`); - } - if (_TypeFormulaParser.PUNCTUATION.includes(stack[0])) { - throw new Error("Unexpected root element."); - } - const item = stack[0]; - if (item instanceof typeFormula_1.TypeFormula) { - return item; - } else if (typeof item === "string") { - return new typeFormula_1.TypeFormula(item, []); - } else { - throw new Error(`Unexpected item on stack: ${item}`); - } - } - tokenizeExpression(expression) { - const tokens = []; - let currentToken = ""; - for (const character of expression) { - if (this.isPunctuation(character)) { - if (currentToken) { - tokens.push(currentToken.trim()); - currentToken = ""; - } - tokens.push(character); - } else { - currentToken += character; - } - } - if (currentToken) { - tokens.push(currentToken.trim()); - } - return tokens; - } - acquireTypeWithParameters(stack) { - const typeParameters = this.acquireTypeParameters(stack); - const typeName = stack.pop(); - const typeFormula = new typeFormula_1.TypeFormula(typeName, typeParameters.reverse()); - return typeFormula; - } - acquireTypeParameters(stack) { - const typeParameters = []; - while (true) { - const item = stack.pop(); - if (item === void 0) { - throw new Error("Badly specified type parameters"); - } - if (this.isBeginningOfTypeParameters(item)) { - break; - } - if (item instanceof typeFormula_1.TypeFormula) { - typeParameters.push(item); - } else if (typeof item === "string") { - typeParameters.push(new typeFormula_1.TypeFormula(item, [])); - } else { - throw new Error(`Unexpected type parameter object in stack: ${item}`); - } - } - return typeParameters; - } - isPunctuation(token) { - return _TypeFormulaParser.PUNCTUATION.includes(token); - } - isEndOfTypeParameters(token) { - return token === _TypeFormulaParser.END_TYPE_PARAMETERS; - } - isBeginningOfTypeParameters(token) { - return token === _TypeFormulaParser.BEGIN_TYPE_PARAMETERS; - } - }; - exports2.TypeFormulaParser = TypeFormulaParser; - TypeFormulaParser.BEGIN_TYPE_PARAMETERS = "<"; - TypeFormulaParser.END_TYPE_PARAMETERS = ">"; - TypeFormulaParser.COMMA = ","; - TypeFormulaParser.PUNCTUATION = [ - TypeFormulaParser.COMMA, - TypeFormulaParser.BEGIN_TYPE_PARAMETERS, - TypeFormulaParser.END_TYPE_PARAMETERS - ]; - } -}); - -// node_modules/@multiversx/sdk-core/out/reflection.js -var require_reflection = __commonJS({ - "node_modules/@multiversx/sdk-core/out/reflection.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getJavascriptPrototypesInHierarchy = void 0; - function getJavascriptPrototypesInHierarchy(obj, filter) { - let prototypes = []; - let prototype = Object.getPrototypeOf(obj); - while (prototype && filter(prototype)) { - prototypes.push(prototype); - prototype = Object.getPrototypeOf(prototype); - } - return prototypes; - } - exports2.getJavascriptPrototypesInHierarchy = getJavascriptPrototypesInHierarchy; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js -var require_types = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NullType = exports2.TypePlaceholder = exports2.isTyped = exports2.PrimitiveValue = exports2.TypedValue = exports2.CustomType = exports2.PrimitiveType = exports2.TypeCardinality = exports2.Type = void 0; - var reflection_1 = require_reflection(); - var utils_1 = require_utils2(); - var Type = class _Type { - constructor(name2, typeParameters = [], cardinality = TypeCardinality.fixed(1)) { - utils_1.guardValueIsSet("name", name2); - this.name = name2; - this.typeParameters = typeParameters; - this.cardinality = cardinality; - } - getName() { - return this.name; - } - getClassName() { - return _Type.ClassName; - } - getClassHierarchy() { - let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); - let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); - return classNames; - } - /** - * Gets the fully qualified name of the type, to allow for better (efficient and non-ambiguous) type comparison within the custom typesystem. - */ - getFullyQualifiedName() { - let joinedTypeParameters = this.getTypeParameters().map((type) => type.getFullyQualifiedName()).join(", "); - return this.isGenericType() ? `multiversx:types:${this.getName()}<${joinedTypeParameters}>` : `multiversx:types:${this.getName()}`; - } - hasExactClass(className) { - return this.getClassName() == className; - } - hasClassOrSuperclass(className) { - let hierarchy = this.getClassHierarchy(); - return hierarchy.includes(className); - } - getTypeParameters() { - return this.typeParameters; - } - isGenericType() { - return this.typeParameters.length > 0; - } - getFirstTypeParameter() { - utils_1.guardTrue(this.typeParameters.length > 0, "type parameters length > 0"); - return this.typeParameters[0]; - } - /** - * Generates type expressions similar to mx-sdk-rs. - */ - toString() { - let typeParameters = this.getTypeParameters().map((type) => type.toString()).join(", "); - let typeParametersExpression = typeParameters ? `<${typeParameters}>` : ""; - return `${this.name}${typeParametersExpression}`; - } - equals(other) { - return _Type.equals(this, other); - } - static equals(a3, b4) { - return a3.getFullyQualifiedName() == b4.getFullyQualifiedName(); - } - static equalsMany(a3, b4) { - return a3.every((type, i2) => type.equals(b4[i2])); - } - static isAssignableFromMany(a3, b4) { - return a3.every((type, i2) => type.isAssignableFrom(b4[i2])); - } - differs(other) { - return !this.equals(other); - } - valueOf() { - return this.name; - } - /** - * Inspired from: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom - * For (most) generics, type invariance is expected (assumed) - neither covariance, nor contravariance are supported yet (will be supported in a next release). - * - * One exception though: for {@link OptionType}, we simulate covariance for missing (not provided) values. - * For example, Option is assignable from Option. - * For more details, see the implementation of {@link OptionType} and @{@link OptionalType}. - * - * Also see: - * - https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) - * - https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance - */ - isAssignableFrom(other) { - let invariantTypeParameters = _Type.equalsMany(this.getTypeParameters(), other.getTypeParameters()); - if (!invariantTypeParameters) { - return false; - } - let fullyQualifiedNameOfThis = this.getFullyQualifiedName(); - let fullyQualifiedNamesInHierarchyOfOther = _Type.getFullyQualifiedNamesInHierarchy(other); - if (fullyQualifiedNamesInHierarchyOfOther.includes(fullyQualifiedNameOfThis)) { - return true; - } - return other.hasClassOrSuperclass(this.getClassName()); - } - static getFullyQualifiedNamesInHierarchy(type) { - let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(type, (prototype) => prototype.belongsToTypesystem); - let fullyQualifiedNames = prototypes.map((prototype) => prototype.getFullyQualifiedName.call(type)); - return fullyQualifiedNames; - } - getNamesOfDependencies() { - const dependencies = []; - for (const type of this.typeParameters) { - dependencies.push(type.getName()); - dependencies.push(...type.getNamesOfDependencies()); - } - return [...new Set(dependencies)]; - } - /** - * Converts the account to a pretty, plain JavaScript object. - */ - toJSON() { - return { - name: this.name, - typeParameters: this.typeParameters.map((item) => item.toJSON()) - }; - } - getCardinality() { - return this.cardinality; - } - /** - * A special marker for types within the custom typesystem. - */ - belongsToTypesystem() { - } - }; - exports2.Type = Type; - Type.ClassName = "Type"; - var TypeCardinality = class _TypeCardinality { - constructor(lowerBound, upperBound) { - this.lowerBound = lowerBound; - this.upperBound = upperBound; - } - static fixed(value) { - return new _TypeCardinality(value, value); - } - static variable(value) { - return new _TypeCardinality(0, value); - } - isSingular() { - return this.lowerBound == 1 && this.upperBound == 1; - } - isSingularOrNone() { - return this.lowerBound == 0 && this.upperBound == 1; - } - isComposite() { - return this.upperBound != 1; - } - isFixed() { - return this.lowerBound == this.upperBound; - } - getLowerBound() { - return this.lowerBound; - } - getUpperBound() { - return this.upperBound || _TypeCardinality.MaxCardinality; - } - }; - exports2.TypeCardinality = TypeCardinality; - TypeCardinality.MaxCardinality = 4096; - var PrimitiveType = class _PrimitiveType extends Type { - constructor(name2) { - super(name2); - } - getClassName() { - return _PrimitiveType.ClassName; - } - }; - exports2.PrimitiveType = PrimitiveType; - PrimitiveType.ClassName = "PrimitiveType"; - var CustomType = class _CustomType extends Type { - getClassName() { - return _CustomType.ClassName; - } - }; - exports2.CustomType = CustomType; - CustomType.ClassName = "CustomType"; - var TypedValue = class _TypedValue { - constructor(type) { - this.type = type; - } - getClassName() { - return _TypedValue.ClassName; - } - getClassHierarchy() { - let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); - let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); - return classNames; - } - getType() { - return this.type; - } - hasExactClass(className) { - return this.getClassName() == className; - } - hasClassOrSuperclass(className) { - let hierarchy = this.getClassHierarchy(); - return hierarchy.includes(className); - } - /** - * A special marker for values within the custom typesystem. - */ - belongsToTypesystem() { - } - }; - exports2.TypedValue = TypedValue; - TypedValue.ClassName = "TypedValue"; - var PrimitiveValue = class _PrimitiveValue extends TypedValue { - constructor(type) { - super(type); - } - getClassName() { - return _PrimitiveValue.ClassName; - } - }; - exports2.PrimitiveValue = PrimitiveValue; - PrimitiveValue.ClassName = "PrimitiveValue"; - function isTyped(value) { - return value.belongsToTypesystem !== void 0; - } - exports2.isTyped = isTyped; - var TypePlaceholder = class _TypePlaceholder extends Type { - constructor() { - super("..."); - } - getClassName() { - return _TypePlaceholder.ClassName; - } - }; - exports2.TypePlaceholder = TypePlaceholder; - TypePlaceholder.ClassName = "TypePlaceholder"; - var NullType = class _NullType extends Type { - constructor() { - super("?"); - } - getClassName() { - return _NullType.ClassName; - } - }; - exports2.NullType = NullType; - NullType.ClassName = "NullType"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js -var require_typeExpressionParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeExpressionParser = void 0; - var typeFormulaParser_1 = require_typeFormulaParser(); - var errors_1 = require_errors(); - var types_1 = require_types(); - var TypeExpressionParser = class { - constructor() { - this.backingTypeFormulaParser = new typeFormulaParser_1.TypeFormulaParser(); - } - parse(expression) { - try { - return this.doParse(expression); - } catch (e2) { - throw new errors_1.ErrTypingSystem(`Failed to parse type expression: ${expression}. Error: ${e2}`); - } - } - doParse(expression) { - const typeFormula = this.backingTypeFormulaParser.parseExpression(expression); - const type = this.typeFormulaToType(typeFormula); - return type; - } - typeFormulaToType(typeFormula) { - const typeParameters = typeFormula.typeParameters.map((typeFormula2) => this.typeFormulaToType(typeFormula2)); - return new types_1.Type(typeFormula.name, typeParameters); - } - }; - exports2.TypeExpressionParser = TypeExpressionParser; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js -var require_endpoint = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EndpointParameterDefinition = exports2.EndpointModifiers = exports2.EndpointDefinition = void 0; - var typeExpressionParser_1 = require_typeExpressionParser(); - var NamePlaceholder = "?"; - var DescriptionPlaceholder = "N / A"; - var EndpointDefinition = class _EndpointDefinition { - constructor(name2, input, output, modifiers) { - this.input = []; - this.output = []; - this.name = name2; - this.input = input || []; - this.output = output || []; - this.modifiers = modifiers; - } - isConstructor() { - return this.name == "constructor"; - } - static fromJSON(json) { - json.name = json.name == null ? NamePlaceholder : json.name; - json.onlyOwner = json.onlyOwner || false; - json.payableInTokens = json.payableInTokens || []; - json.inputs = json.inputs || []; - json.outputs = json.outputs || []; - let input = json.inputs.map((param) => EndpointParameterDefinition.fromJSON(param)); - let output = json.outputs.map((param) => EndpointParameterDefinition.fromJSON(param)); - let modifiers = new EndpointModifiers(json.mutability, json.payableInTokens, json.onlyOwner); - return new _EndpointDefinition(json.name, input, output, modifiers); - } - }; - exports2.EndpointDefinition = EndpointDefinition; - var EndpointModifiers = class { - constructor(mutability, payableInTokens, onlyOwner) { - this.mutability = mutability || ""; - this.payableInTokens = payableInTokens || []; - this.onlyOwner = onlyOwner || false; - } - isPayableInEGLD() { - return this.isPayableInToken("EGLD"); - } - isPayableInToken(token) { - if (this.payableInTokens.includes(token)) { - return true; - } - if (this.payableInTokens.includes(`!${token}`)) { - return false; - } - if (this.payableInTokens.includes("*")) { - return true; - } - return false; - } - isPayable() { - return this.payableInTokens.length != 0; - } - isReadonly() { - return this.mutability == "readonly"; - } - isOnlyOwner() { - return this.onlyOwner; - } - }; - exports2.EndpointModifiers = EndpointModifiers; - var EndpointParameterDefinition = class _EndpointParameterDefinition { - constructor(name2, description, type) { - this.name = name2; - this.description = description; - this.type = type; - } - static fromJSON(json) { - let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); - return new _EndpointParameterDefinition(json.name || NamePlaceholder, json.description || DescriptionPlaceholder, parsedType); - } - }; - exports2.EndpointParameterDefinition = EndpointParameterDefinition; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js -var require_fields = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Fields = exports2.Field = exports2.FieldDefinition = void 0; - var errors = __importStar2(require_errors()); - var typeExpressionParser_1 = require_typeExpressionParser(); - var FieldDefinition = class _FieldDefinition { - constructor(name2, description, type) { - this.name = name2; - this.description = description; - this.type = type; - } - static fromJSON(json) { - let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); - return new _FieldDefinition(json.name, json.description, parsedType); - } - }; - exports2.FieldDefinition = FieldDefinition; - var Field = class { - constructor(value, name2 = "") { - this.value = value; - this.name = name2; - } - checkTyping(expectedDefinition) { - const actualType = this.value.getType(); - if (!actualType.equals(expectedDefinition.type)) { - throw new errors.ErrTypingSystem(`check type of field "${expectedDefinition.name}; expected: ${expectedDefinition.type}, actual: ${actualType}"`); - } - if (this.name != expectedDefinition.name) { - throw new errors.ErrTypingSystem(`check name of field "${expectedDefinition.name}"`); - } - } - equals(other) { - return this.name == other.name && this.value.equals(other.value); - } - }; - exports2.Field = Field; - var Fields = class { - static checkTyping(fields, definitions) { - if (fields.length != definitions.length) { - throw new errors.ErrTypingSystem("fields length vs. field definitions length"); - } - for (let i2 = 0; i2 < fields.length; i2++) { - let field = fields[i2]; - let definition = definitions[i2]; - field.checkTyping(definition); - } - } - static equals(actual, expected) { - if (actual.length != expected.length) { - return false; - } - for (let i2 = 0; i2 < actual.length; i2++) { - let selfField = actual[i2]; - let otherField = expected[i2]; - if (!selfField.equals(otherField)) { - return false; - } - } - return true; - } - static getNamesOfTypeDependencies(definitions) { - const dependencies = []; - for (const definition of definitions) { - dependencies.push(definition.type.getName()); - dependencies.push(...definition.type.getNamesOfDependencies()); - } - return [...new Set(dependencies)]; - } - }; - exports2.Fields = Fields; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js -var require_enum = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EnumValue = exports2.EnumVariantDefinition = exports2.EnumType = void 0; - var errors_1 = require_errors(); - var utils_1 = require_utils2(); - var fields_1 = require_fields(); - var types_1 = require_types(); - var SimpleEnumMaxDiscriminant = 256; - var EnumType = class _EnumType extends types_1.CustomType { - constructor(name2, variants) { - super(name2); - this.variants = []; - this.variants = variants; - } - getClassName() { - return _EnumType.ClassName; - } - static fromJSON(json) { - const rawVariants = _EnumType.assignMissingDiscriminants(json.variants || []); - const variants = rawVariants.map((variant) => EnumVariantDefinition.fromJSON(variant)); - return new _EnumType(json.name, variants); - } - // For some enums (e.g. some "explicit-enum" types), the discriminants are missing. - static assignMissingDiscriminants(variants) { - const allDiscriminantsAreMissing = variants.every((variant) => variant.discriminant == void 0); - if (!allDiscriminantsAreMissing) { - return variants; - } - return variants.map((variant, index) => { - return { - ...variant, - discriminant: index - }; - }); - } - getVariantByDiscriminant(discriminant) { - let result = this.variants.find((e2) => e2.discriminant == discriminant); - utils_1.guardValueIsSet(`variant by discriminant (${discriminant})`, result); - return result; - } - getVariantByName(name2) { - let result = this.variants.find((e2) => e2.name == name2); - utils_1.guardValueIsSet(`variant by name (${name2})`, result); - return result; - } - getNamesOfDependencies() { - const dependencies = []; - for (const variant of this.variants) { - dependencies.push(...variant.getNamesOfDependencies()); - } - return [...new Set(dependencies)]; - } - }; - exports2.EnumType = EnumType; - EnumType.ClassName = "EnumType"; - var EnumVariantDefinition = class _EnumVariantDefinition { - constructor(name2, discriminant, fieldsDefinitions = []) { - this.fieldsDefinitions = []; - utils_1.guardTrue(discriminant < SimpleEnumMaxDiscriminant, `discriminant for simple enum should be less than ${SimpleEnumMaxDiscriminant}`); - this.name = name2; - this.discriminant = discriminant; - this.fieldsDefinitions = fieldsDefinitions; - } - static fromJSON(json) { - let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); - return new _EnumVariantDefinition(json.name, json.discriminant, definitions); - } - getFieldsDefinitions() { - return this.fieldsDefinitions; - } - getFieldDefinition(name2) { - return this.fieldsDefinitions.find((item) => item.name == name2); - } - getNamesOfDependencies() { - return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); - } - }; - exports2.EnumVariantDefinition = EnumVariantDefinition; - var EnumValue = class _EnumValue extends types_1.TypedValue { - constructor(type, variant, fields) { - super(type); - this.fields = []; - this.name = variant.name; - this.discriminant = variant.discriminant; - this.fields = fields; - this.fieldsByName = new Map(fields.map((field) => [field.name, field])); - let definitions = variant.getFieldsDefinitions(); - fields_1.Fields.checkTyping(this.fields, definitions); - } - getClassName() { - return _EnumValue.ClassName; - } - /** - * Utility (named constructor) to create a simple (i.e. without fields) enum value. - */ - static fromName(type, name2) { - let variant = type.getVariantByName(name2); - return new _EnumValue(type, variant, []); - } - /** - * Utility (named constructor) to create a simple (i.e. without fields) enum value. - */ - static fromDiscriminant(type, discriminant) { - let variant = type.getVariantByDiscriminant(discriminant); - return new _EnumValue(type, variant, []); - } - equals(other) { - if (!this.getType().equals(other.getType())) { - return false; - } - let selfFields = this.getFields(); - let otherFields = other.getFields(); - const nameIsSame = this.name == other.name; - const discriminantIsSame = this.discriminant == other.discriminant; - const fieldsAreSame = fields_1.Fields.equals(selfFields, otherFields); - return nameIsSame && discriminantIsSame && fieldsAreSame; - } - getFields() { - return this.fields; - } - getFieldValue(name2) { - let field = this.fieldsByName.get(name2); - if (field) { - return field.value.valueOf(); - } - throw new errors_1.ErrMissingFieldOnEnum(name2, this.getType().getName()); - } - valueOf() { - let result = { name: this.name, fields: [] }; - this.fields.forEach((field, index) => result.fields[index] = field.value.valueOf()); - return result; - } - }; - exports2.EnumValue = EnumValue; - EnumValue.ClassName = "EnumValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js -var require_event = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EventTopicDefinition = exports2.EventDefinition = void 0; - var typeExpressionParser_1 = require_typeExpressionParser(); - var NamePlaceholder = "?"; - var EventDefinition = class _EventDefinition { - constructor(identifier, inputs) { - this.inputs = []; - this.identifier = identifier; - this.inputs = inputs || []; - } - static fromJSON(json) { - json.identifier = json.identifier == null ? NamePlaceholder : json.identifier; - json.inputs = json.inputs || []; - const inputs = json.inputs.map((param) => EventTopicDefinition.fromJSON(param)); - return new _EventDefinition(json.identifier, inputs); - } - }; - exports2.EventDefinition = EventDefinition; - var EventTopicDefinition = class _EventTopicDefinition { - constructor(options) { - this.name = options.name; - this.type = options.type; - this.indexed = options.indexed; - } - static fromJSON(json) { - const parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); - return new _EventTopicDefinition({ - name: json.name || NamePlaceholder, - type: parsedType, - indexed: json.indexed - }); - } - }; - exports2.EventTopicDefinition = EventTopicDefinition; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js -var require_struct = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Struct = exports2.StructType = void 0; - var errors_1 = require_errors(); - var fields_1 = require_fields(); - var types_1 = require_types(); - var StructType = class _StructType extends types_1.CustomType { - constructor(name2, fieldsDefinitions) { - super(name2); - this.fieldsDefinitions = []; - this.fieldsDefinitions = fieldsDefinitions; - } - getClassName() { - return _StructType.ClassName; - } - static fromJSON(json) { - let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); - return new _StructType(json.name, definitions); - } - getFieldsDefinitions() { - return this.fieldsDefinitions; - } - getFieldDefinition(name2) { - return this.fieldsDefinitions.find((item) => item.name == name2); - } - getNamesOfDependencies() { - return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); - } - }; - exports2.StructType = StructType; - StructType.ClassName = "StructType"; - var Struct = class _Struct extends types_1.TypedValue { - /** - * One can only set fields at initialization time. - */ - constructor(type, fields) { - super(type); - this.fields = fields; - this.fieldsByName = new Map(fields.map((field) => [field.name, field])); - this.checkTyping(); - } - getClassName() { - return _Struct.ClassName; - } - checkTyping() { - let type = this.getType(); - let definitions = type.getFieldsDefinitions(); - fields_1.Fields.checkTyping(this.fields, definitions); - } - getFields() { - return this.fields; - } - getFieldValue(name2) { - let field = this.fieldsByName.get(name2); - if (field) { - return field.value.valueOf(); - } - throw new errors_1.ErrMissingFieldOnStruct(name2, this.getType().getName()); - } - valueOf() { - let result = {}; - for (const field of this.fields) { - result[field.name] = field.value.valueOf(); - } - return result; - } - equals(other) { - if (!this.getType().equals(other.getType())) { - return false; - } - let selfFields = this.getFields(); - let otherFields = other.getFields(); - return fields_1.Fields.equals(selfFields, otherFields); - } - }; - exports2.Struct = Struct; - Struct.ClassName = "Struct"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js -var require_address2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AddressValue = exports2.AddressType = void 0; - var address_1 = require_address(); - var types_1 = require_types(); - var AddressType2 = class _AddressType extends types_1.PrimitiveType { - constructor() { - super("Address"); - } - getClassName() { - return _AddressType.ClassName; - } - }; - exports2.AddressType = AddressType2; - AddressType2.ClassName = "AddressType"; - var AddressValue2 = class _AddressValue extends types_1.PrimitiveValue { - constructor(value) { - super(new AddressType2()); - this.value = new address_1.Address(value.bech32()); - } - getClassName() { - return _AddressValue.ClassName; - } - /** - * Returns whether two objects have the same value. - * - * @param other another AddressValue - */ - equals(other) { - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - }; - exports2.AddressValue = AddressValue2; - AddressValue2.ClassName = "AddressValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js -var require_algebraic = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OptionalValue = exports2.OptionalType = void 0; - var utils_1 = require_utils2(); - var types_1 = require_types(); - var OptionalType = class _OptionalType extends types_1.Type { - constructor(typeParameter) { - super("Optional", [typeParameter], types_1.TypeCardinality.variable(1)); - } - getClassName() { - return _OptionalType.ClassName; - } - isAssignableFrom(type) { - if (!type.hasExactClass(_OptionalType.ClassName)) { - return false; - } - let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); - let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); - return invariantTypeParameters || fakeCovarianceToNull; - } - }; - exports2.OptionalType = OptionalType; - OptionalType.ClassName = "OptionalType"; - var OptionalValue = class _OptionalValue extends types_1.TypedValue { - constructor(type, value = null) { - super(type); - this.value = value; - } - getClassName() { - return _OptionalValue.ClassName; - } - /** - * Creates an OptionalValue, as not provided (missing). - */ - static newMissing() { - let type = new OptionalType(new types_1.NullType()); - return new _OptionalValue(type); - } - isSet() { - return this.value ? true : false; - } - getTypedValue() { - utils_1.guardValueIsSet("value", this.value); - return this.value; - } - valueOf() { - return this.value ? this.value.valueOf() : null; - } - equals(other) { - return this.value?.equals(other.value) || false; - } - }; - exports2.OptionalValue = OptionalValue; - OptionalValue.ClassName = "OptionalValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js -var require_boolean = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BooleanValue = exports2.BooleanType = void 0; - var types_1 = require_types(); - var BooleanType2 = class _BooleanType extends types_1.PrimitiveType { - constructor() { - super("bool"); - } - getClassName() { - return _BooleanType.ClassName; - } - }; - exports2.BooleanType = BooleanType2; - BooleanType2.ClassName = "BooleanType"; - var BooleanValue2 = class _BooleanValue extends types_1.PrimitiveValue { - constructor(value) { - super(new BooleanType2()); - this.value = value; - } - getClassName() { - return _BooleanValue.ClassName; - } - /** - * Returns whether two objects have the same value. - * - * @param other another BooleanValue - */ - equals(other) { - return this.value === other.value; - } - isTrue() { - return this.value === true; - } - isFalse() { - return !this.isTrue(); - } - valueOf() { - return this.value; - } - }; - exports2.BooleanValue = BooleanValue2; - BooleanValue2.ClassName = "BooleanValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js -var require_bytes = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesValue = exports2.BytesType = void 0; - var types_1 = require_types(); - var BytesType2 = class _BytesType extends types_1.PrimitiveType { - constructor() { - super("bytes"); - } - getClassName() { - return _BytesType.ClassName; - } - }; - exports2.BytesType = BytesType2; - BytesType2.ClassName = "BytesType"; - var BytesValue2 = class _BytesValue extends types_1.PrimitiveValue { - constructor(value) { - super(new BytesType2()); - this.value = value; - } - getClassName() { - return _BytesValue.ClassName; - } - /** - * Creates a BytesValue from a utf-8 string. - */ - static fromUTF8(value) { - let buffer = import_buffer.Buffer.from(value, "utf-8"); - return new _BytesValue(buffer); - } - /** - * Creates a BytesValue from a hex-encoded string. - */ - static fromHex(value) { - let buffer = import_buffer.Buffer.from(value, "hex"); - return new _BytesValue(buffer); - } - getLength() { - return this.value.length; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - if (this.getLength() != other.getLength()) { - return false; - } - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - toString() { - return this.value.toString(); - } - }; - exports2.BytesValue = BytesValue2; - BytesValue2.ClassName = "BytesValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js -var require_codeMetadata = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CodeMetadataValue = exports2.CodeMetadataType = void 0; - var types_1 = require_types(); - var CodeMetadataType = class extends types_1.PrimitiveType { - constructor() { - super("CodeMetadata"); - } - }; - exports2.CodeMetadataType = CodeMetadataType; - var CodeMetadataValue = class extends types_1.PrimitiveValue { - constructor(value) { - super(new CodeMetadataType()); - this.value = value; - } - equals(other) { - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - }; - exports2.CodeMetadataValue = CodeMetadataValue; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js -var require_composite = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CompositeValue = exports2.CompositeType = void 0; - var utils_1 = require_utils2(); - var types_1 = require_types(); - var CompositeType = class _CompositeType extends types_1.Type { - constructor(...typeParameters) { - super("Composite", typeParameters, types_1.TypeCardinality.variable(typeParameters.length)); - } - getClassName() { - return _CompositeType.ClassName; - } - }; - exports2.CompositeType = CompositeType; - CompositeType.ClassName = "CompositeType"; - var CompositeValue = class _CompositeValue extends types_1.TypedValue { - constructor(type, items) { - super(type); - utils_1.guardLength(items, type.getTypeParameters().length); - this.items = items; - } - getClassName() { - return _CompositeValue.ClassName; - } - static fromItems(...items) { - let typeParameters = items.map((value) => value.getType()); - let type = new CompositeType(...typeParameters); - return new _CompositeValue(type, items); - } - getItems() { - return this.items; - } - valueOf() { - return this.items.map((item) => item?.valueOf()); - } - equals(other) { - if (this.getType().differs(other.getType())) { - return false; - } - for (let i2 = 0; i2 < this.items.length; i2++) { - let selfItem = this.items[i2]; - let otherItem = other.items[i2]; - if (!selfItem.equals(otherItem)) { - return false; - } - } - return true; - } - }; - exports2.CompositeValue = CompositeValue; - CompositeValue.ClassName = "CompositeValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js -var require_collections = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CollectionOfTypedValues = void 0; - var CollectionOfTypedValues = class { - constructor(items) { - this.items = items; - } - getLength() { - return this.items.length; - } - getItems() { - return this.items; - } - valueOf() { - return this.items.map((item) => item.valueOf()); - } - equals(other) { - if (this.getLength() != other.getLength()) { - return false; - } - for (let i2 = 0; i2 < this.getLength(); i2++) { - let selfItem = this.items[i2]; - let otherItem = other.items[i2]; - if (!selfItem.equals(otherItem)) { - return false; - } - } - return true; - } - }; - exports2.CollectionOfTypedValues = CollectionOfTypedValues; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js -var require_generic = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.List = exports2.OptionValue = exports2.ListType = exports2.OptionType = void 0; - var utils_1 = require_utils2(); - var collections_1 = require_collections(); - var types_1 = require_types(); - var OptionType = class _OptionType extends types_1.Type { - constructor(typeParameter) { - super("Option", [typeParameter]); - } - getClassName() { - return _OptionType.ClassName; - } - isAssignableFrom(type) { - if (!type.hasExactClass(_OptionType.ClassName)) { - return false; - } - let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); - let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); - return invariantTypeParameters || fakeCovarianceToNull; - } - }; - exports2.OptionType = OptionType; - OptionType.ClassName = "OptionType"; - var ListType = class _ListType extends types_1.Type { - constructor(typeParameter) { - super("List", [typeParameter]); - } - getClassName() { - return _ListType.ClassName; - } - }; - exports2.ListType = ListType; - ListType.ClassName = "ListType"; - var OptionValue = class _OptionValue extends types_1.TypedValue { - constructor(type, value = null) { - super(type); - this.value = value; - } - getClassName() { - return _OptionValue.ClassName; - } - /** - * Creates an OptionValue, as a missing option argument. - */ - static newMissing() { - let type = new OptionType(new types_1.NullType()); - return new _OptionValue(type); - } - static newMissingTyped(type) { - return new _OptionValue(new OptionType(type)); - } - /** - * Creates an OptionValue, as a provided option argument. - */ - static newProvided(typedValue) { - let type = new OptionType(typedValue.getType()); - return new _OptionValue(type, typedValue); - } - isSet() { - return this.value ? true : false; - } - getTypedValue() { - utils_1.guardValueIsSet("value", this.value); - return this.value; - } - valueOf() { - return this.value ? this.value.valueOf() : null; - } - equals(other) { - return this.value?.equals(other.value) || false; - } - }; - exports2.OptionValue = OptionValue; - OptionValue.ClassName = "OptionValue"; - var List = class _List extends types_1.TypedValue { - /** - * - * @param type the type of this TypedValue (an instance of ListType), not the type parameter of the ListType - * @param items the items, having the type type.getFirstTypeParameter() - */ - constructor(type, items) { - super(type); - this.backingCollection = new collections_1.CollectionOfTypedValues(items); - } - getClassName() { - return _List.ClassName; - } - static fromItems(items) { - if (items.length == 0) { - return new _List(new types_1.TypePlaceholder(), []); - } - let typeParameter = items[0].getType(); - let listType = new ListType(typeParameter); - return new _List(listType, items); - } - getLength() { - return this.backingCollection.getLength(); - } - getItems() { - return this.backingCollection.getItems(); - } - valueOf() { - return this.backingCollection.valueOf(); - } - equals(other) { - return this.backingCollection.equals(other.backingCollection); - } - }; - exports2.List = List; - List.ClassName = "List"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js -var require_genericArray = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArrayVec = exports2.ArrayVecType = void 0; - var utils_1 = require_utils2(); - var collections_1 = require_collections(); - var types_1 = require_types(); - var ArrayVecType = class _ArrayVecType extends types_1.Type { - constructor(length2, typeParameter) { - super("Array", [typeParameter]); - utils_1.guardTrue(length2 > 0, "array length > 0"); - this.length = length2; - } - getClassName() { - return _ArrayVecType.ClassName; - } - }; - exports2.ArrayVecType = ArrayVecType; - ArrayVecType.ClassName = "ArrayVecType"; - var ArrayVec = class _ArrayVec extends types_1.TypedValue { - constructor(type, items) { - super(type); - utils_1.guardLength(items, type.length); - this.backingCollection = new collections_1.CollectionOfTypedValues(items); - } - getClassName() { - return _ArrayVec.ClassName; - } - getLength() { - return this.backingCollection.getLength(); - } - getItems() { - return this.backingCollection.getItems(); - } - valueOf() { - return this.backingCollection.valueOf(); - } - equals(other) { - return this.backingCollection.equals(other.backingCollection); - } - }; - exports2.ArrayVec = ArrayVec; - ArrayVec.ClassName = "ArrayVec"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js -var require_h256 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.H256Value = exports2.H256Type = void 0; - var types_1 = require_types(); - var H256Type = class _H256Type extends types_1.PrimitiveType { - constructor() { - super("H256"); - } - getClassName() { - return _H256Type.ClassName; - } - }; - exports2.H256Type = H256Type; - H256Type.ClassName = "H256Type"; - var H256Value = class _H256Value extends types_1.PrimitiveValue { - constructor(value) { - super(new H256Type()); - this.value = value; - } - getClassName() { - return _H256Value.ClassName; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - }; - exports2.H256Value = H256Value; - H256Value.ClassName = "H256Value"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js -var require_nothing = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NothingValue = exports2.NothingType = void 0; - var types_1 = require_types(); - var NothingType = class _NothingType extends types_1.PrimitiveType { - constructor() { - super("nothing"); - } - getClassName() { - return _NothingType.ClassName; - } - }; - exports2.NothingType = NothingType; - NothingType.ClassName = "NothingType"; - var NothingValue = class _NothingValue extends types_1.PrimitiveValue { - constructor() { - super(new NothingType()); - } - getClassName() { - return _NothingValue.ClassName; - } - equals(_other) { - return false; - } - valueOf() { - return {}; - } - }; - exports2.NothingValue = NothingValue; - NothingValue.ClassName = "NothingValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js -var require_numerical = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BigIntValue = exports2.BigUIntValue = exports2.I64Value = exports2.U64Value = exports2.I32Value = exports2.U32Value = exports2.I16Value = exports2.U16Value = exports2.I8Value = exports2.U8Value = exports2.NumericalValue = exports2.BigIntType = exports2.BigUIntType = exports2.I64Type = exports2.U64Type = exports2.I32Type = exports2.U32Type = exports2.I16Type = exports2.U16Type = exports2.I8Type = exports2.U8Type = exports2.NumericalType = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var errors = __importStar2(require_errors()); - var types_1 = require_types(); - var NumericalType = class _NumericalType extends types_1.PrimitiveType { - constructor(name2, sizeInBytes, withSign) { - super(name2); - this.sizeInBytes = sizeInBytes; - this.withSign = withSign; - } - getClassName() { - return _NumericalType.ClassName; - } - hasFixedSize() { - return this.sizeInBytes ? true : false; - } - hasArbitrarySize() { - return !this.hasFixedSize(); - } - }; - exports2.NumericalType = NumericalType; - NumericalType.ClassName = "NumericalType"; - var U8Type2 = class _U8Type extends NumericalType { - constructor() { - super("u8", 1, false); - } - getClassName() { - return _U8Type.ClassName; - } - }; - exports2.U8Type = U8Type2; - U8Type2.ClassName = "U8Type"; - var I8Type = class _I8Type extends NumericalType { - constructor() { - super("i8", 1, true); - } - getClassName() { - return _I8Type.ClassName; - } - }; - exports2.I8Type = I8Type; - I8Type.ClassName = "I8Type"; - var U16Type2 = class _U16Type extends NumericalType { - constructor() { - super("u16", 2, false); - } - getClassName() { - return _U16Type.ClassName; - } - }; - exports2.U16Type = U16Type2; - U16Type2.ClassName = "U16Type"; - var I16Type = class _I16Type extends NumericalType { - constructor() { - super("i16", 2, true); - } - getClassName() { - return _I16Type.ClassName; - } - }; - exports2.I16Type = I16Type; - I16Type.ClassName = "I16Type"; - var U32Type2 = class _U32Type extends NumericalType { - constructor() { - super("u32", 4, false); - } - getClassName() { - return _U32Type.ClassName; - } - }; - exports2.U32Type = U32Type2; - U32Type2.ClassName = "U32Type"; - var I32Type = class _I32Type extends NumericalType { - constructor() { - super("i32", 4, true); - } - getClassName() { - return _I32Type.ClassName; - } - }; - exports2.I32Type = I32Type; - I32Type.ClassName = "I32Type"; - var U64Type2 = class _U64Type extends NumericalType { - constructor() { - super("u64", 8, false); - } - getClassName() { - return _U64Type.ClassName; - } - }; - exports2.U64Type = U64Type2; - U64Type2.ClassName = "U64Type"; - var I64Type = class _I64Type extends NumericalType { - constructor() { - super("i64", 8, true); - } - getClassName() { - return _I64Type.ClassName; - } - }; - exports2.I64Type = I64Type; - I64Type.ClassName = "I64Type"; - var BigUIntType2 = class _BigUIntType extends NumericalType { - constructor() { - super("BigUint", 0, false); - } - getClassName() { - return _BigUIntType.ClassName; - } - }; - exports2.BigUIntType = BigUIntType2; - BigUIntType2.ClassName = "BigUIntType"; - var BigIntType = class _BigIntType extends NumericalType { - constructor() { - super("Bigint", 0, true); - } - getClassName() { - return _BigIntType.ClassName; - } - }; - exports2.BigIntType = BigIntType; - BigIntType.ClassName = "BigIntType"; - var NumericalValue = class _NumericalValue extends types_1.PrimitiveValue { - constructor(type, value) { - super(type); - if (typeof value === "bigint") { - value = value.toString(); - } - this.value = new bignumber_js_1.default(value); - this.sizeInBytes = type.sizeInBytes; - this.withSign = type.withSign; - if (this.value.isNaN()) { - throw new errors.ErrInvalidArgument(`not a number: ${value}`); - } - if (!this.withSign && this.value.isNegative()) { - throw new errors.ErrInvalidArgument(`negative, but type is unsigned: ${value}`); - } - } - getClassName() { - return _NumericalValue.ClassName; - } - /** - * Returns whether two objects have the same value. - * - * @param other another NumericalValue - */ - equals(other) { - return this.value.isEqualTo(other.value); - } - valueOf() { - return this.value; - } - toString() { - return this.value.toString(); - } - }; - exports2.NumericalValue = NumericalValue; - NumericalValue.ClassName = "NumericalValue"; - var U8Value2 = class _U8Value extends NumericalValue { - constructor(value) { - super(new U8Type2(), value); - } - getClassName() { - return _U8Value.ClassName; - } - }; - exports2.U8Value = U8Value2; - U8Value2.ClassName = "U8Value"; - var I8Value = class _I8Value extends NumericalValue { - constructor(value) { - super(new I8Type(), value); - } - getClassName() { - return _I8Value.ClassName; - } - }; - exports2.I8Value = I8Value; - I8Value.ClassName = "I8Value"; - var U16Value2 = class _U16Value extends NumericalValue { - constructor(value) { - super(new U16Type2(), value); - } - getClassName() { - return _U16Value.ClassName; - } - }; - exports2.U16Value = U16Value2; - U16Value2.ClassName = "U16Value"; - var I16Value = class _I16Value extends NumericalValue { - constructor(value) { - super(new I16Type(), value); - } - getClassName() { - return _I16Value.ClassName; - } - }; - exports2.I16Value = I16Value; - I16Value.ClassName = "I16Value"; - var U32Value2 = class _U32Value extends NumericalValue { - constructor(value) { - super(new U32Type2(), value); - } - getClassName() { - return _U32Value.ClassName; - } - }; - exports2.U32Value = U32Value2; - U32Value2.ClassName = "U32Value"; - var I32Value = class _I32Value extends NumericalValue { - constructor(value) { - super(new I32Type(), value); - } - getClassName() { - return _I32Value.ClassName; - } - }; - exports2.I32Value = I32Value; - I32Value.ClassName = "I32Value"; - var U64Value2 = class _U64Value extends NumericalValue { - constructor(value) { - super(new U64Type2(), value); - } - getClassName() { - return _U64Value.ClassName; - } - }; - exports2.U64Value = U64Value2; - U64Value2.ClassName = "U64Value"; - var I64Value = class _I64Value extends NumericalValue { - constructor(value) { - super(new I64Type(), value); - } - getClassName() { - return _I64Value.ClassName; - } - }; - exports2.I64Value = I64Value; - I64Value.ClassName = "I64Value"; - var BigUIntValue2 = class _BigUIntValue extends NumericalValue { - constructor(value) { - super(new BigUIntType2(), value); - } - getClassName() { - return _BigUIntValue.ClassName; - } - }; - exports2.BigUIntValue = BigUIntValue2; - BigUIntValue2.ClassName = "BigUIntValue"; - var BigIntValue = class _BigIntValue extends NumericalValue { - constructor(value) { - super(new BigIntType(), value); - } - getClassName() { - return _BigIntValue.ClassName; - } - }; - exports2.BigIntValue = BigIntValue; - BigIntValue.ClassName = "BigIntValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js -var require_string = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StringValue = exports2.StringType = void 0; - var types_1 = require_types(); - var StringType = class _StringType extends types_1.PrimitiveType { - constructor() { - super("utf-8 string"); - } - getClassName() { - return _StringType.ClassName; - } - }; - exports2.StringType = StringType; - StringType.ClassName = "StringType"; - var StringValue = class _StringValue extends types_1.PrimitiveValue { - constructor(value) { - super(new StringType()); - this.value = value; - } - getClassName() { - return _StringValue.ClassName; - } - /** - * Creates a StringValue from a utf-8 string. - */ - static fromUTF8(value) { - return new _StringValue(value); - } - /** - * Creates a StringValue from a hex-encoded string. - */ - static fromHex(value) { - let decodedValue = import_buffer.Buffer.from(value, "hex").toString(); - return new _StringValue(decodedValue); - } - getLength() { - return this.value.length; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - return this.value === other.value; - } - valueOf() { - return this.value; - } - }; - exports2.StringValue = StringValue; - StringValue.ClassName = "StringValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js -var require_tokenIdentifier = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenIdentifierValue = exports2.TokenIdentifierType = void 0; - var types_1 = require_types(); - var EGLDTokenIdentifier = "EGLD"; - var TokenIdentifierType = class _TokenIdentifierType extends types_1.PrimitiveType { - constructor() { - super("TokenIdentifier"); - } - getClassName() { - return _TokenIdentifierType.ClassName; - } - }; - exports2.TokenIdentifierType = TokenIdentifierType; - TokenIdentifierType.ClassName = "TokenIdentifierType"; - var TokenIdentifierValue = class _TokenIdentifierValue extends types_1.PrimitiveValue { - constructor(value) { - super(new TokenIdentifierType()); - this.value = value; - } - static egld() { - return new _TokenIdentifierValue(EGLDTokenIdentifier); - } - static esdtTokenIdentifier(identifier) { - return new _TokenIdentifierValue(identifier); - } - getClassName() { - return _TokenIdentifierValue.ClassName; - } - getLength() { - return this.value.length; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - if (this.getLength() != other.getLength()) { - return false; - } - return this.value == other.value; - } - valueOf() { - return this.value; - } - toString() { - return this.value.toString(); - } - }; - exports2.TokenIdentifierValue = TokenIdentifierValue; - TokenIdentifierValue.ClassName = "TokenIdentifierValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js -var require_tuple = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Tuple = exports2.TupleType = void 0; - var errors = __importStar2(require_errors()); - var fields_1 = require_fields(); - var struct_1 = require_struct(); - var TupleType = class _TupleType extends struct_1.StructType { - constructor(...typeParameters) { - super(_TupleType.prepareName(typeParameters), _TupleType.prepareFieldDefinitions(typeParameters)); - } - getClassName() { - return _TupleType.ClassName; - } - static prepareName(typeParameters) { - let fields = typeParameters.map((type) => type.toString()).join(", "); - let result = `tuple<${fields}>`; - return result; - } - static prepareFieldDefinitions(typeParameters) { - let result = typeParameters.map((type, i2) => new fields_1.FieldDefinition(prepareFieldName(i2), "anonymous tuple field", type)); - return result; - } - }; - exports2.TupleType = TupleType; - TupleType.ClassName = "TupleType"; - function prepareFieldName(fieldIndex) { - return `field${fieldIndex}`; - } - var Tuple = class _Tuple extends struct_1.Struct { - constructor(type, fields) { - super(type, fields); - } - getClassName() { - return _Tuple.ClassName; - } - static fromItems(items) { - if (items.length < 1) { - throw new errors.ErrTypingSystem("bad tuple items"); - } - let fieldsTypes = items.map((item) => item.getType()); - let tupleType = new TupleType(...fieldsTypes); - let fields = items.map((item, i2) => new fields_1.Field(item, prepareFieldName(i2))); - return new _Tuple(tupleType, fields); - } - }; - exports2.Tuple = Tuple; - Tuple.ClassName = "Tuple"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js -var require_variadic = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.VariadicValue = exports2.CountedVariadicType = exports2.VariadicType = void 0; - var types_1 = require_types(); - var VariadicType = class _VariadicType extends types_1.Type { - constructor(typeParameter, isCounted = false) { - super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); - this.isCounted = isCounted; - } - getClassName() { - return _VariadicType.ClassName; - } - }; - exports2.VariadicType = VariadicType; - VariadicType.ClassName = "VariadicType"; - var CountedVariadicType = class extends types_1.Type { - constructor(typeParameter) { - super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); - } - getClassName() { - return VariadicType.ClassName; - } - }; - exports2.CountedVariadicType = CountedVariadicType; - CountedVariadicType.ClassName = "VariadicType"; - var VariadicValue = class _VariadicValue extends types_1.TypedValue { - /** - * - * @param type the type of this TypedValue (an instance of VariadicType), not the type parameter of the VariadicType - * @param items the items, having the type type.getFirstTypeParameter() - */ - constructor(type, items) { - super(type); - this.items = items; - } - getClassName() { - return _VariadicValue.ClassName; - } - static fromItems(...items) { - return this.createFromItems(items, false); - } - static fromItemsCounted(...items) { - return this.createFromItems(items, true); - } - static createFromItems(items, isCounted) { - if (items.length == 0) { - return new _VariadicValue(new VariadicType(new types_1.TypePlaceholder(), isCounted), []); - } - const typeParameter = items[0].getType(); - return new _VariadicValue(new VariadicType(typeParameter, isCounted), items); - } - getItems() { - return this.items; - } - valueOf() { - return this.items.map((item) => item.valueOf()); - } - equals(other) { - if (this.getType().differs(other.getType())) { - return false; - } - for (let i2 = 0; i2 < this.items.length; i2++) { - let selfItem = this.items[i2]; - let otherItem = other.items[i2]; - if (!selfItem.equals(otherItem)) { - return false; - } - } - return true; - } - }; - exports2.VariadicValue = VariadicValue; - VariadicValue.ClassName = "VariadicValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js -var require_typeMapper = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeMapper = void 0; - var errors = __importStar2(require_errors()); - var address_1 = require_address2(); - var algebraic_1 = require_algebraic(); - var boolean_1 = require_boolean(); - var bytes_1 = require_bytes(); - var codeMetadata_1 = require_codeMetadata(); - var composite_1 = require_composite(); - var enum_1 = require_enum(); - var fields_1 = require_fields(); - var generic_1 = require_generic(); - var genericArray_1 = require_genericArray(); - var h256_1 = require_h256(); - var nothing_1 = require_nothing(); - var numerical_1 = require_numerical(); - var string_1 = require_string(); - var struct_1 = require_struct(); - var tokenIdentifier_1 = require_tokenIdentifier(); - var tuple_1 = require_tuple(); - var variadic_1 = require_variadic(); - var TypeMapper = class { - constructor(learnedTypes = []) { - this.openTypesFactories = /* @__PURE__ */ new Map([ - ["Option", (...typeParameters) => new generic_1.OptionType(typeParameters[0])], - ["List", (...typeParameters) => new generic_1.ListType(typeParameters[0])], - // For the following open generics, we use a slightly different typing than the one defined by mx-sdk-rs (temporary workaround). - ["VarArgs", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], - ["MultiResultVec", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], - ["variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], - ["counted-variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0], true)], - ["OptionalArg", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], - ["optional", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], - ["OptionalResult", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], - ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - ["MultiArg", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - ["MultiResult", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - // Perhaps we can adjust the ABI generator to only output "tuple", instead of "tupleN"? - ["tuple", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple2", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple3", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple4", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple5", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple6", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple7", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple8", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - // Known-length arrays. - // TODO: Handle these in typeExpressionParser! - ["array2", (...typeParameters) => new genericArray_1.ArrayVecType(2, typeParameters[0])], - ["array8", (...typeParameters) => new genericArray_1.ArrayVecType(8, typeParameters[0])], - ["array16", (...typeParameters) => new genericArray_1.ArrayVecType(16, typeParameters[0])], - ["array20", (...typeParameters) => new genericArray_1.ArrayVecType(20, typeParameters[0])], - ["array32", (...typeParameters) => new genericArray_1.ArrayVecType(32, typeParameters[0])], - ["array46", (...typeParameters) => new genericArray_1.ArrayVecType(46, typeParameters[0])], - ["array48", (...typeParameters) => new genericArray_1.ArrayVecType(48, typeParameters[0])], - ["array64", (...typeParameters) => new genericArray_1.ArrayVecType(64, typeParameters[0])], - ["array128", (...typeParameters) => new genericArray_1.ArrayVecType(128, typeParameters[0])], - ["array256", (...typeParameters) => new genericArray_1.ArrayVecType(256, typeParameters[0])] - ]); - this.closedTypesMap = /* @__PURE__ */ new Map([ - ["u8", new numerical_1.U8Type()], - ["u16", new numerical_1.U16Type()], - ["u32", new numerical_1.U32Type()], - ["u64", new numerical_1.U64Type()], - ["U64", new numerical_1.U64Type()], - ["BigUint", new numerical_1.BigUIntType()], - ["i8", new numerical_1.I8Type()], - ["i16", new numerical_1.I16Type()], - ["i32", new numerical_1.I32Type()], - ["i64", new numerical_1.I64Type()], - ["Bigint", new numerical_1.BigIntType()], - ["BigInt", new numerical_1.BigIntType()], - ["bool", new boolean_1.BooleanType()], - ["bytes", new bytes_1.BytesType()], - ["Address", new address_1.AddressType()], - ["H256", new h256_1.H256Type()], - ["utf-8 string", new string_1.StringType()], - ["TokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], - ["EgldOrEsdtTokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], - ["CodeMetadata", new codeMetadata_1.CodeMetadataType()], - ["nothing", new nothing_1.NothingType()], - ["AsyncCall", new nothing_1.NothingType()] - ]); - this.learnedTypesMap = /* @__PURE__ */ new Map(); - for (const type of learnedTypes) { - this.learnedTypesMap.set(type.getName(), type); - } - } - /** - * Maps a "raw type" object to a "known (specific) type" object. - * In the process, it also learns the new type. - * Can only map types if their dependencies were previously learned (through mapping). - */ - mapType(type) { - let mappedType = this.mapTypeRecursively(type); - if (mappedType) { - if (!mappedType.isGenericType()) { - this.learnType(mappedType); - } - return mappedType; - } - throw new errors.ErrTypingSystem(`Cannot map the type "${type.getName()}" to a known type`); - } - mapTypeRecursively(type) { - let isGeneric = type.isGenericType(); - let previouslyLearnedType = this.learnedTypesMap.get(type.getName()); - if (previouslyLearnedType) { - return previouslyLearnedType; - } - let knownClosedType = this.closedTypesMap.get(type.getName()); - if (knownClosedType) { - return knownClosedType; - } - if (type.hasExactClass(enum_1.EnumType.ClassName)) { - return this.mapEnumType(type); - } - if (type.hasExactClass(struct_1.StructType.ClassName)) { - return this.mapStructType(type); - } - if (isGeneric) { - return this.mapGenericType(type); - } - return null; - } - learnType(type) { - this.learnedTypesMap.delete(type.getName()); - this.learnedTypesMap.set(type.getName(), type); - } - mapStructType(type) { - let mappedFields = this.mappedFields(type.getFieldsDefinitions()); - let mappedStruct = new struct_1.StructType(type.getName(), mappedFields); - return mappedStruct; - } - mapEnumType(type) { - let variants = type.variants.map((variant) => new enum_1.EnumVariantDefinition(variant.name, variant.discriminant, this.mappedFields(variant.getFieldsDefinitions()))); - let mappedEnum = new enum_1.EnumType(type.getName(), variants); - return mappedEnum; - } - mappedFields(definitions) { - return definitions.map((definition) => new fields_1.FieldDefinition(definition.name, definition.description, this.mapType(definition.type))); - } - mapGenericType(type) { - let typeParameters = type.getTypeParameters(); - let mappedTypeParameters = typeParameters.map((item) => this.mapType(item)); - let factory = this.openTypesFactories.get(type.getName()); - if (!factory) { - throw new errors.ErrTypingSystem(`Cannot map the generic type "${type.getName()}" to a known type`); - } - return factory(...mappedTypeParameters); - } - }; - exports2.TypeMapper = TypeMapper; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js -var require_abiRegistry = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbiRegistry = void 0; - var errors = __importStar2(require_errors()); - var utils_1 = require_utils2(); - var endpoint_1 = require_endpoint(); - var enum_1 = require_enum(); - var event_1 = require_event(); - var struct_1 = require_struct(); - var typeMapper_1 = require_typeMapper(); - var interfaceNamePlaceholder = "?"; - var AbiRegistry = class _AbiRegistry { - constructor(options) { - this.endpoints = []; - this.customTypes = []; - this.events = []; - this.name = options.name; - this.constructorDefinition = options.constructorDefinition; - this.endpoints = options.endpoints; - this.customTypes = options.customTypes; - this.events = options.events || []; - } - static create(options) { - const name2 = options.name || interfaceNamePlaceholder; - const constructor = options.constructor || {}; - const endpoints = options.endpoints || []; - const types = options.types || {}; - const events = options.events || []; - const constructorDefinition = endpoint_1.EndpointDefinition.fromJSON({ name: "constructor", ...constructor }); - const endpointDefinitions = endpoints.map((item) => endpoint_1.EndpointDefinition.fromJSON(item)); - const customTypes = []; - for (const customTypeName in types) { - const typeDefinition = types[customTypeName]; - if (typeDefinition.type == "struct") { - customTypes.push(struct_1.StructType.fromJSON({ name: customTypeName, fields: typeDefinition.fields })); - } else if (typeDefinition.type == "enum" || typeDefinition.type == "explicit-enum") { - customTypes.push(enum_1.EnumType.fromJSON({ name: customTypeName, variants: typeDefinition.variants })); - } else { - throw new errors.ErrTypingSystem(`Cannot handle custom type: ${customTypeName}`); - } - } - const eventDefinitions = events.map((item) => event_1.EventDefinition.fromJSON(item)); - const registry = new _AbiRegistry({ - name: name2, - constructorDefinition, - endpoints: endpointDefinitions, - customTypes, - events: eventDefinitions - }); - const remappedRegistry = registry.remapToKnownTypes(); - return remappedRegistry; - } - getCustomType(name2) { - const result = this.customTypes.find((e2) => e2.getName() == name2); - utils_1.guardValueIsSetWithMessage(`custom type [${name2}] not found`, result); - return result; - } - getStruct(name2) { - const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(struct_1.StructType.ClassName)); - utils_1.guardValueIsSetWithMessage(`struct [${name2}] not found`, result); - return result; - } - getStructs(names) { - return names.map((name2) => this.getStruct(name2)); - } - getEnum(name2) { - const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(enum_1.EnumType.ClassName)); - utils_1.guardValueIsSetWithMessage(`enum [${name2}] not found`, result); - return result; - } - getEnums(names) { - return names.map((name2) => this.getEnum(name2)); - } - getEndpoints() { - return this.endpoints; - } - getEndpoint(name2) { - const result = this.endpoints.find((e2) => e2.name == name2); - utils_1.guardValueIsSetWithMessage(`endpoint [${name2}] not found`, result); - return result; - } - getEvent(name2) { - const result = this.events.find((e2) => e2.identifier == name2); - utils_1.guardValueIsSetWithMessage(`event [${name2}] not found`, result); - return result; - } - /** - * Right after loading ABI definitions into a registry, the endpoints and the custom types (structs, enums) - * use raw types for their I/O parameters (in the case of endpoints), or for their fields (in the case of structs). - * - * A raw type is merely an instance of {@link Type}, with a given name and type parameters (if it's a generic type). - * - * Though, for most (development) purposes, we'd like to operate using known, specific types (e.g. {@link List}, {@link U8Type} etc.). - * This function increases the specificity of the types used by parameter / field definitions within a registry (on best-efforts basis). - * The result is an equivalent, more explicit ABI registry. - */ - remapToKnownTypes() { - const mapper = new typeMapper_1.TypeMapper([]); - const newCustomTypes = []; - for (const type of this.customTypes) { - this.mapCustomTypeDepthFirst(type, this.customTypes, mapper, newCustomTypes); - } - if (this.customTypes.length != newCustomTypes.length) { - throw new errors.ErrTypingSystem("Did not re-map all custom types"); - } - const newConstructor = mapEndpoint(this.constructorDefinition, mapper); - const newEndpoints = []; - for (const endpoint of this.endpoints) { - newEndpoints.push(mapEndpoint(endpoint, mapper)); - } - const newEvents = this.events.map((event) => mapEvent(event, mapper)); - const newRegistry = new _AbiRegistry({ - name: this.name, - constructorDefinition: newConstructor, - endpoints: newEndpoints, - customTypes: newCustomTypes, - events: newEvents - }); - return newRegistry; - } - mapCustomTypeDepthFirst(typeToMap, allTypesToMap, mapper, mappedTypes) { - const hasBeenMapped = mappedTypes.findIndex((type) => type.getName() == typeToMap.getName()) >= 0; - if (hasBeenMapped) { - return; - } - for (const typeName of typeToMap.getNamesOfDependencies()) { - const dependencyType = allTypesToMap.find((type) => type.getName() == typeName); - if (!dependencyType) { - continue; - } - this.mapCustomTypeDepthFirst(dependencyType, allTypesToMap, mapper, mappedTypes); - } - const mappedType = mapper.mapType(typeToMap); - mappedTypes.push(mappedType); - } - }; - exports2.AbiRegistry = AbiRegistry; - function mapEndpoint(endpoint, mapper) { - const newInput = endpoint.input.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); - const newOutput = endpoint.output.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); - return new endpoint_1.EndpointDefinition(endpoint.name, newInput, newOutput, endpoint.modifiers); - } - function mapEvent(event, mapper) { - const newInputs = event.inputs.map((e2) => new event_1.EventTopicDefinition({ - name: e2.name, - type: mapper.mapType(e2.type), - indexed: e2.indexed - })); - return new event_1.EventDefinition(event.identifier, newInputs); - } - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js -var require_factory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createListOfTokenIdentifiers = exports2.createListOfAddresses = void 0; - var address_1 = require_address2(); - var generic_1 = require_generic(); - var tokenIdentifier_1 = require_tokenIdentifier(); - function createListOfAddresses(addresses) { - let addressesTyped = addresses.map((address) => new address_1.AddressValue(address)); - let list = generic_1.List.fromItems(addressesTyped); - return list; - } - exports2.createListOfAddresses = createListOfAddresses; - function createListOfTokenIdentifiers(identifiers) { - let identifiersTyped = identifiers.map((identifier) => new tokenIdentifier_1.TokenIdentifierValue(identifier)); - let list = generic_1.List.fromItems(identifiersTyped); - return list; - } - exports2.createListOfTokenIdentifiers = createListOfTokenIdentifiers; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js -var require_matchers = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.onPrimitiveTypeSelect = exports2.onPrimitiveValueSelect = exports2.onTypedValueSelect = exports2.onTypeSelect = void 0; - var errors = __importStar2(require_errors()); - var address_1 = require_address2(); - var boolean_1 = require_boolean(); - var bytes_1 = require_bytes(); - var enum_1 = require_enum(); - var generic_1 = require_generic(); - var h256_1 = require_h256(); - var numerical_1 = require_numerical(); - var nothing_1 = require_nothing(); - var struct_1 = require_struct(); - var tokenIdentifier_1 = require_tokenIdentifier(); - var tuple_1 = require_tuple(); - var types_1 = require_types(); - var genericArray_1 = require_genericArray(); - var string_1 = require_string(); - function onTypeSelect(type, selectors) { - if (type.hasExactClass(generic_1.OptionType.ClassName)) { - return selectors.onOption(); - } - if (type.hasExactClass(generic_1.ListType.ClassName)) { - return selectors.onList(); - } - if (type.hasExactClass(genericArray_1.ArrayVecType.ClassName)) { - return selectors.onArray(); - } - if (type.hasClassOrSuperclass(types_1.PrimitiveType.ClassName)) { - return selectors.onPrimitive(); - } - if (type.hasExactClass(struct_1.StructType.ClassName)) { - return selectors.onStruct(); - } - if (type.hasExactClass(tuple_1.TupleType.ClassName)) { - return selectors.onTuple(); - } - if (type.hasExactClass(enum_1.EnumType.ClassName)) { - return selectors.onEnum(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`type isn't known: ${type}`); - } - exports2.onTypeSelect = onTypeSelect; - function onTypedValueSelect(value, selectors) { - if (value.hasClassOrSuperclass(types_1.PrimitiveValue.ClassName)) { - return selectors.onPrimitive(); - } - if (value.hasExactClass(generic_1.OptionValue.ClassName)) { - return selectors.onOption(); - } - if (value.hasExactClass(generic_1.List.ClassName)) { - return selectors.onList(); - } - if (value.hasExactClass(genericArray_1.ArrayVec.ClassName)) { - return selectors.onArray(); - } - if (value.hasExactClass(struct_1.Struct.ClassName)) { - return selectors.onStruct(); - } - if (value.hasExactClass(tuple_1.Tuple.ClassName)) { - return selectors.onTuple(); - } - if (value.hasExactClass(enum_1.EnumValue.ClassName)) { - return selectors.onEnum(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`value isn't typed: ${value}`); - } - exports2.onTypedValueSelect = onTypedValueSelect; - function onPrimitiveValueSelect(value, selectors) { - if (value.hasExactClass(boolean_1.BooleanValue.ClassName)) { - return selectors.onBoolean(); - } - if (value.hasClassOrSuperclass(numerical_1.NumericalValue.ClassName)) { - return selectors.onNumerical(); - } - if (value.hasExactClass(address_1.AddressValue.ClassName)) { - return selectors.onAddress(); - } - if (value.hasExactClass(bytes_1.BytesValue.ClassName)) { - return selectors.onBytes(); - } - if (value.hasExactClass(string_1.StringValue.ClassName)) { - return selectors.onString(); - } - if (value.hasExactClass(h256_1.H256Value.ClassName)) { - return selectors.onH256(); - } - if (value.hasExactClass(tokenIdentifier_1.TokenIdentifierValue.ClassName)) { - return selectors.onTypeIdentifier(); - } - if (value.hasExactClass(nothing_1.NothingValue.ClassName)) { - return selectors.onNothing(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`value isn't a primitive: ${value.getType()}`); - } - exports2.onPrimitiveValueSelect = onPrimitiveValueSelect; - function onPrimitiveTypeSelect(type, selectors) { - if (type.hasExactClass(boolean_1.BooleanType.ClassName)) { - return selectors.onBoolean(); - } - if (type.hasClassOrSuperclass(numerical_1.NumericalType.ClassName)) { - return selectors.onNumerical(); - } - if (type.hasExactClass(address_1.AddressType.ClassName)) { - return selectors.onAddress(); - } - if (type.hasExactClass(bytes_1.BytesType.ClassName)) { - return selectors.onBytes(); - } - if (type.hasExactClass(string_1.StringType.ClassName)) { - return selectors.onString(); - } - if (type.hasExactClass(h256_1.H256Type.ClassName)) { - return selectors.onH256(); - } - if (type.hasExactClass(tokenIdentifier_1.TokenIdentifierType.ClassName)) { - return selectors.onTokenIndetifier(); - } - if (type.hasExactClass(nothing_1.NothingType.ClassName)) { - return selectors.onNothing(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`type isn't a known primitive: ${type}`); - } - exports2.onPrimitiveTypeSelect = onPrimitiveTypeSelect; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js -var require_typesystem = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_abiRegistry(), exports2); - __exportStar2(require_address2(), exports2); - __exportStar2(require_algebraic(), exports2); - __exportStar2(require_boolean(), exports2); - __exportStar2(require_bytes(), exports2); - __exportStar2(require_composite(), exports2); - __exportStar2(require_endpoint(), exports2); - __exportStar2(require_enum(), exports2); - __exportStar2(require_factory(), exports2); - __exportStar2(require_fields(), exports2); - __exportStar2(require_generic(), exports2); - __exportStar2(require_genericArray(), exports2); - __exportStar2(require_h256(), exports2); - __exportStar2(require_matchers(), exports2); - __exportStar2(require_nothing(), exports2); - __exportStar2(require_numerical(), exports2); - __exportStar2(require_string(), exports2); - __exportStar2(require_struct(), exports2); - __exportStar2(require_tokenIdentifier(), exports2); - __exportStar2(require_tuple(), exports2); - __exportStar2(require_typeExpressionParser(), exports2); - __exportStar2(require_typeMapper(), exports2); - __exportStar2(require_types(), exports2); - __exportStar2(require_variadic(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js -var require_option = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OptionValueBinaryCodec = void 0; - var errors = __importStar2(require_errors()); - var typesystem_1 = require_typesystem(); - var OptionValueBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, type) { - if (buffer[0] == 0) { - return [typesystem_1.OptionValue.newMissingTyped(type), 1]; - } - if (buffer[0] != 1) { - throw new errors.ErrCodec("invalid buffer for optional value"); - } - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); - return [typesystem_1.OptionValue.newProvided(decoded), decodedLength + 1]; - } - decodeTopLevel(buffer, type) { - if (buffer.length == 0) { - return new typesystem_1.OptionValue(type); - } - if (buffer[0] != 1) { - throw new errors.ErrCodec("invalid buffer for optional value"); - } - let [decoded, _decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); - return new typesystem_1.OptionValue(type, decoded); - } - encodeNested(optionValue) { - if (optionValue.isSet()) { - return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); - } - return import_buffer.Buffer.from([0]); - } - encodeTopLevel(optionValue) { - if (optionValue.isSet()) { - return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); - } - return import_buffer.Buffer.from([]); - } - }; - exports2.OptionValueBinaryCodec = OptionValueBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js -var require_address3 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AddressBinaryCodec = void 0; - var address_1 = require_address(); - var typesystem_1 = require_typesystem(); - var AddressBinaryCodec = class { - /** - * Reads and decodes an AddressValue from a given buffer. - * - * @param buffer the input buffer - */ - decodeNested(buffer) { - let slice = buffer.slice(0, 32); - let value = new address_1.Address(slice); - return [new typesystem_1.AddressValue(value), 32]; - } - /** - * Reads and decodes an AddressValue from a given buffer. - * - * @param buffer the input buffer - */ - decodeTopLevel(buffer) { - let [decoded, _length] = this.decodeNested(buffer); - return decoded; - } - /** - * Encodes an AddressValue to a buffer. - */ - encodeNested(primitive) { - return primitive.valueOf().pubkey(); - } - /** - * Encodes an AddressValue to a buffer. - */ - encodeTopLevel(primitive) { - return primitive.valueOf().pubkey(); - } - }; - exports2.AddressBinaryCodec = AddressBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js -var require_boolean2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BooleanBinaryCodec = void 0; - var errors = __importStar2(require_errors()); - var typesystem_1 = require_typesystem(); - var BooleanBinaryCodec = class _BooleanBinaryCodec { - decodeNested(buffer) { - let byte = buffer.readUInt8(0); - return [new typesystem_1.BooleanValue(byte == _BooleanBinaryCodec.TRUE), 1]; - } - decodeTopLevel(buffer) { - if (buffer.length > 1) { - throw new errors.ErrInvalidArgument("buffer should be of size <= 1"); - } - let firstByte = buffer[0]; - return new typesystem_1.BooleanValue(firstByte == _BooleanBinaryCodec.TRUE); - } - encodeNested(primitive) { - if (primitive.isTrue()) { - return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); - } - return import_buffer.Buffer.from([_BooleanBinaryCodec.FALSE]); - } - encodeTopLevel(primitive) { - if (primitive.isTrue()) { - return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); - } - return import_buffer.Buffer.from([]); - } - }; - exports2.BooleanBinaryCodec = BooleanBinaryCodec; - BooleanBinaryCodec.TRUE = 1; - BooleanBinaryCodec.FALSE = 0; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js -var require_constants2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SizeOfU32 = void 0; - exports2.SizeOfU32 = 4; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js -var require_numerical2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NumericalBinaryCodec = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var typesystem_1 = require_typesystem(); - var constants_1 = require_constants2(); - var utils_1 = require_utils(); - var NumericalBinaryCodec = class { - decodeNested(buffer, type) { - let offset = 0; - let length2 = type.sizeInBytes; - if (!length2) { - offset = constants_1.SizeOfU32; - length2 = buffer.readUInt32BE(0); - } - let payload = buffer.slice(offset, offset + length2); - let result = this.decodeTopLevel(payload, type); - let decodedLength = length2 + offset; - return [result, decodedLength]; - } - decodeTopLevel(buffer, type) { - let payload = utils_1.cloneBuffer(buffer); - let empty2 = buffer.length == 0; - if (empty2) { - return new typesystem_1.NumericalValue(type, new bignumber_js_1.default(0)); - } - let isPositive = !type.withSign || utils_1.isMsbZero(payload); - if (isPositive) { - let value2 = utils_1.bufferToBigInt(payload); - return new typesystem_1.NumericalValue(type, value2); - } - utils_1.flipBufferBitsInPlace(payload); - let value = utils_1.bufferToBigInt(payload); - let negativeValue = value.multipliedBy(new bignumber_js_1.default(-1)); - let negativeValueMinusOne = negativeValue.minus(new bignumber_js_1.default(1)); - return new typesystem_1.NumericalValue(type, negativeValueMinusOne); - } - encodeNested(primitive) { - if (primitive.sizeInBytes) { - return this.encodeNestedFixedSize(primitive, primitive.sizeInBytes); - } - let buffer = this.encodeTopLevel(primitive); - let length2 = import_buffer.Buffer.alloc(constants_1.SizeOfU32); - length2.writeUInt32BE(buffer.length); - return import_buffer.Buffer.concat([length2, buffer]); - } - encodeNestedFixedSize(primitive, size) { - if (primitive.value.isZero()) { - return import_buffer.Buffer.alloc(size, 0); - } - if (!primitive.withSign) { - const buffer2 = utils_1.bigIntToBuffer(primitive.value); - const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); - return import_buffer.Buffer.concat([paddingBytes2, buffer2]); - } - if (primitive.value.isPositive()) { - let buffer2 = utils_1.bigIntToBuffer(primitive.value); - if (utils_1.isMsbOne(buffer2)) { - buffer2 = utils_1.prependByteToBuffer(buffer2, 0); - } - const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); - return import_buffer.Buffer.concat([paddingBytes2, buffer2]); - } - let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); - let buffer = utils_1.bigIntToBuffer(valuePlusOne); - utils_1.flipBufferBitsInPlace(buffer); - if (utils_1.isMsbZero(buffer)) { - buffer = utils_1.prependByteToBuffer(buffer, 255); - } - const paddingBytes = import_buffer.Buffer.alloc(size - buffer.length, 255); - return import_buffer.Buffer.concat([paddingBytes, buffer]); - } - encodeTopLevel(primitive) { - let withSign = primitive.withSign; - if (primitive.value.isZero()) { - return import_buffer.Buffer.alloc(0); - } - if (!withSign) { - return utils_1.bigIntToBuffer(primitive.value); - } - return this.encodePrimitive(primitive); - } - encodePrimitive(primitive) { - if (primitive.value.isPositive()) { - let buffer2 = utils_1.bigIntToBuffer(primitive.value); - if (utils_1.isMsbOne(buffer2)) { - buffer2 = utils_1.prependByteToBuffer(buffer2, 0); - } - return buffer2; - } - let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); - let buffer = utils_1.bigIntToBuffer(valuePlusOne); - utils_1.flipBufferBitsInPlace(buffer); - if (utils_1.isMsbZero(buffer)) { - buffer = utils_1.prependByteToBuffer(buffer, 255); - } - return buffer; - } - }; - exports2.NumericalBinaryCodec = NumericalBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js -var require_h2562 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.H256BinaryCodec = void 0; - var h256_1 = require_h256(); - var H256BinaryCodec = class { - /** - * Reads and decodes a H256Value from a given buffer. - * - * @param buffer the input buffer - */ - decodeNested(buffer) { - let slice = buffer.slice(0, 32); - return [new h256_1.H256Value(slice), 32]; - } - /** - * Reads and decodes a H256Value from a given buffer. - * - * @param buffer the input buffer - */ - decodeTopLevel(buffer) { - let [decoded, _length] = this.decodeNested(buffer); - return decoded; - } - /** - * Encodes a H256Value to a buffer. - */ - encodeNested(primitive) { - return primitive.valueOf(); - } - /** - * Encodes a H256Value to a buffer. - */ - encodeTopLevel(primitive) { - return primitive.valueOf(); - } - }; - exports2.H256BinaryCodec = H256BinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js -var require_bytes2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesBinaryCodec = void 0; - var bytes_1 = require_bytes(); - var constants_1 = require_constants2(); - var BytesBinaryCodec = class { - decodeNested(buffer) { - let length2 = buffer.readUInt32BE(0); - let payload = buffer.slice(constants_1.SizeOfU32, constants_1.SizeOfU32 + length2); - let result = new bytes_1.BytesValue(payload); - return [result, constants_1.SizeOfU32 + length2]; - } - decodeTopLevel(buffer) { - return new bytes_1.BytesValue(buffer); - } - encodeNested(bytes) { - let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); - lengthBuffer.writeUInt32BE(bytes.getLength()); - let buffer = import_buffer.Buffer.concat([lengthBuffer, bytes.valueOf()]); - return buffer; - } - encodeTopLevel(bytes) { - return bytes.valueOf(); - } - }; - exports2.BytesBinaryCodec = BytesBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js -var require_tokenIdentifier2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenIdentifierCodec = void 0; - var bytes_1 = require_bytes(); - var tokenIdentifier_1 = require_tokenIdentifier(); - var bytes_2 = require_bytes2(); - var TokenIdentifierCodec = class { - constructor() { - this.bytesCodec = new bytes_2.BytesBinaryCodec(); - } - decodeNested(buffer) { - let [bytesValue, length2] = this.bytesCodec.decodeNested(buffer); - return [new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()), length2]; - } - decodeTopLevel(buffer) { - let bytesValue = this.bytesCodec.decodeTopLevel(buffer); - return new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()); - } - encodeNested(tokenIdentifier) { - let bytesValue = bytes_1.BytesValue.fromUTF8(tokenIdentifier.valueOf()); - return this.bytesCodec.encodeNested(bytesValue); - } - encodeTopLevel(tokenIdentifier) { - return import_buffer.Buffer.from(tokenIdentifier.valueOf()); - } - }; - exports2.TokenIdentifierCodec = TokenIdentifierCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js -var require_nothing2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NothingCodec = void 0; - var typesystem_1 = require_typesystem(); - var NothingCodec = class { - decodeNested() { - return [new typesystem_1.NothingValue(), 0]; - } - decodeTopLevel() { - return new typesystem_1.NothingValue(); - } - encodeNested() { - return import_buffer.Buffer.from([]); - } - encodeTopLevel() { - return import_buffer.Buffer.from([]); - } - }; - exports2.NothingCodec = NothingCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js -var require_string2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StringBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var bytes_1 = require_bytes(); - var bytes_2 = require_bytes2(); - var StringBinaryCodec = class { - constructor() { - this.bytesBinaryCodec = new bytes_2.BytesBinaryCodec(); - } - decodeNested(buffer) { - let [decoded, length2] = this.bytesBinaryCodec.decodeNested(buffer); - let decodedAsString = new typesystem_1.StringValue(decoded.valueOf().toString()); - return [decodedAsString, length2]; - } - decodeTopLevel(buffer) { - return new typesystem_1.StringValue(buffer.toString()); - } - encodeNested(value) { - let valueAsBytes = bytes_1.BytesValue.fromUTF8(value.valueOf()); - return this.bytesBinaryCodec.encodeNested(valueAsBytes); - } - encodeTopLevel(value) { - return import_buffer.Buffer.from(value.valueOf()); - } - }; - exports2.StringBinaryCodec = StringBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js -var require_primitive = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PrimitiveBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var address_1 = require_address3(); - var boolean_1 = require_boolean2(); - var numerical_1 = require_numerical2(); - var h256_1 = require_h2562(); - var bytes_1 = require_bytes2(); - var tokenIdentifier_1 = require_tokenIdentifier2(); - var nothing_1 = require_nothing2(); - var string_1 = require_string2(); - var PrimitiveBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - this.booleanCodec = new boolean_1.BooleanBinaryCodec(); - this.numericalCodec = new numerical_1.NumericalBinaryCodec(); - this.addressCodec = new address_1.AddressBinaryCodec(); - this.h256Codec = new h256_1.H256BinaryCodec(); - this.bytesCodec = new bytes_1.BytesBinaryCodec(); - this.stringCodec = new string_1.StringBinaryCodec(); - this.tokenIdentifierCodec = new tokenIdentifier_1.TokenIdentifierCodec(); - this.nothingCodec = new nothing_1.NothingCodec(); - } - decodeNested(buffer, type) { - return typesystem_1.onPrimitiveTypeSelect(type, { - onBoolean: () => this.booleanCodec.decodeNested(buffer), - onNumerical: () => this.numericalCodec.decodeNested(buffer, type), - onAddress: () => this.addressCodec.decodeNested(buffer), - onBytes: () => this.bytesCodec.decodeNested(buffer), - onString: () => this.stringCodec.decodeNested(buffer), - onH256: () => this.h256Codec.decodeNested(buffer), - onTokenIndetifier: () => this.tokenIdentifierCodec.decodeNested(buffer), - onNothing: () => this.nothingCodec.decodeNested() - }); - } - decodeTopLevel(buffer, type) { - return typesystem_1.onPrimitiveTypeSelect(type, { - onBoolean: () => this.booleanCodec.decodeTopLevel(buffer), - onNumerical: () => this.numericalCodec.decodeTopLevel(buffer, type), - onAddress: () => this.addressCodec.decodeTopLevel(buffer), - onBytes: () => this.bytesCodec.decodeTopLevel(buffer), - onString: () => this.stringCodec.decodeTopLevel(buffer), - onH256: () => this.h256Codec.decodeTopLevel(buffer), - onTokenIndetifier: () => this.tokenIdentifierCodec.decodeTopLevel(buffer), - onNothing: () => this.nothingCodec.decodeTopLevel() - }); - } - encodeNested(value) { - return typesystem_1.onPrimitiveValueSelect(value, { - onBoolean: () => this.booleanCodec.encodeNested(value), - onNumerical: () => this.numericalCodec.encodeNested(value), - onAddress: () => this.addressCodec.encodeNested(value), - onBytes: () => this.bytesCodec.encodeNested(value), - onString: () => this.stringCodec.encodeNested(value), - onH256: () => this.h256Codec.encodeNested(value), - onTypeIdentifier: () => this.tokenIdentifierCodec.encodeNested(value), - onNothing: () => this.nothingCodec.encodeNested() - }); - } - encodeTopLevel(value) { - return typesystem_1.onPrimitiveValueSelect(value, { - onBoolean: () => this.booleanCodec.encodeTopLevel(value), - onNumerical: () => this.numericalCodec.encodeTopLevel(value), - onAddress: () => this.addressCodec.encodeTopLevel(value), - onBytes: () => this.bytesCodec.encodeTopLevel(value), - onString: () => this.stringCodec.encodeTopLevel(value), - onH256: () => this.h256Codec.encodeTopLevel(value), - onTypeIdentifier: () => this.tokenIdentifierCodec.encodeTopLevel(value), - onNothing: () => this.nothingCodec.encodeTopLevel() - }); - } - }; - exports2.PrimitiveBinaryCodec = PrimitiveBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js -var require_list = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ListBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var constants_1 = require_constants2(); - var ListBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, type) { - let typeParameter = type.getFirstTypeParameter(); - let result = []; - let numItems = buffer.readUInt32BE(0); - this.binaryCodec.constraints.checkListLength(numItems); - let originalBuffer = buffer; - let offset = constants_1.SizeOfU32; - buffer = originalBuffer.slice(offset); - for (let i2 = 0; i2 < numItems; i2++) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); - result.push(decoded); - offset += decodedLength; - buffer = originalBuffer.slice(offset); - } - return [new typesystem_1.List(type, result), offset]; - } - decodeTopLevel(buffer, type) { - let typeParameter = type.getFirstTypeParameter(); - let result = []; - let originalBuffer = buffer; - let offset = 0; - while (buffer.length > 0) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); - result.push(decoded); - offset += decodedLength; - buffer = originalBuffer.slice(offset); - this.binaryCodec.constraints.checkListLength(result.length); - } - return new typesystem_1.List(type, result); - } - encodeNested(list) { - this.binaryCodec.constraints.checkListLength(list.getLength()); - let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); - lengthBuffer.writeUInt32BE(list.getLength()); - let itemsBuffers = []; - for (const item of list.getItems()) { - let itemBuffer = this.binaryCodec.encodeNested(item); - itemsBuffers.push(itemBuffer); - } - let buffer = import_buffer.Buffer.concat([lengthBuffer, ...itemsBuffers]); - return buffer; - } - encodeTopLevel(list) { - this.binaryCodec.constraints.checkListLength(list.getLength()); - let itemsBuffers = []; - for (const item of list.getItems()) { - let itemBuffer = this.binaryCodec.encodeNested(item); - itemsBuffers.push(itemBuffer); - } - let buffer = import_buffer.Buffer.concat(itemsBuffers); - return buffer; - } - }; - exports2.ListBinaryCodec = ListBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js -var require_fields2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.FieldsBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var FieldsBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, fieldDefinitions) { - let fields = []; - let totalLength = 0; - for (const fieldDefinition of fieldDefinitions) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, fieldDefinition.type); - buffer = buffer.slice(decodedLength); - totalLength += decodedLength; - let field = new typesystem_1.Field(decoded, fieldDefinition.name); - fields.push(field); - } - return [fields, totalLength]; - } - encodeNested(fields) { - let buffers = []; - for (const field of fields) { - let fieldBuffer = this.binaryCodec.encodeNested(field.value); - buffers.push(fieldBuffer); - } - return import_buffer.Buffer.concat(buffers); - } - }; - exports2.FieldsBinaryCodec = FieldsBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js -var require_struct2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StructBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var fields_1 = require_fields2(); - var StructBinaryCodec = class { - constructor(binaryCodec) { - this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); - } - decodeTopLevel(buffer, type) { - let [decoded] = this.decodeNested(buffer, type); - return decoded; - } - decodeNested(buffer, type) { - let fieldDefinitions = type.getFieldsDefinitions(); - let [fields, offset] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); - let struct = new typesystem_1.Struct(type, fields); - return [struct, offset]; - } - encodeNested(struct) { - let fields = struct.getFields(); - let buffer = this.fieldsCodec.encodeNested(fields); - return buffer; - } - encodeTopLevel(struct) { - return this.encodeNested(struct); - } - }; - exports2.StructBinaryCodec = StructBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js -var require_enum2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EnumBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var fields_1 = require_fields2(); - var EnumBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); - } - decodeTopLevel(buffer, type) { - let [enumValue] = this.decodeNested(buffer, type); - return enumValue; - } - decodeNested(buffer, type) { - let [discriminant, lengthOfDiscriminant] = this.readDiscriminant(buffer); - buffer = buffer.slice(lengthOfDiscriminant); - let variant = type.getVariantByDiscriminant(discriminant); - let fieldDefinitions = variant.getFieldsDefinitions(); - let [fields, lengthOfFields] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); - let enumValue = new typesystem_1.EnumValue(type, variant, fields); - return [enumValue, lengthOfDiscriminant + lengthOfFields]; - } - readDiscriminant(buffer) { - let [value, length2] = this.binaryCodec.decodeNested(buffer, new typesystem_1.U8Type()); - let discriminant = value.valueOf(); - return [discriminant, length2]; - } - encodeNested(enumValue) { - let discriminant = new typesystem_1.U8Value(enumValue.discriminant); - let discriminantBuffer = this.binaryCodec.encodeNested(discriminant); - let fields = enumValue.getFields(); - let fieldsBuffer = this.fieldsCodec.encodeNested(fields); - return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); - } - encodeTopLevel(enumValue) { - let fields = enumValue.getFields(); - let hasFields = fields.length > 0; - let fieldsBuffer = this.fieldsCodec.encodeNested(fields); - let discriminant = new typesystem_1.U8Value(enumValue.discriminant); - let discriminantBuffer = hasFields ? this.binaryCodec.encodeNested(discriminant) : this.binaryCodec.encodeTopLevel(discriminant); - return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); - } - }; - exports2.EnumBinaryCodec = EnumBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js -var require_tuple2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TupleBinaryCodec = void 0; - var struct_1 = require_struct2(); - var TupleBinaryCodec = class { - constructor(binaryCodec) { - this.structCodec = new struct_1.StructBinaryCodec(binaryCodec); - } - decodeTopLevel(buffer, type) { - return this.structCodec.decodeTopLevel(buffer, type); - } - decodeNested(buffer, type) { - return this.structCodec.decodeNested(buffer, type); - } - encodeNested(struct) { - return this.structCodec.encodeNested(struct); - } - encodeTopLevel(struct) { - return this.structCodec.encodeTopLevel(struct); - } - }; - exports2.TupleBinaryCodec = TupleBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js -var require_arrayVec = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArrayVecBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var ArrayVecBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, type) { - let arrayLength = type.length; - let typeParameter = type.getFirstTypeParameter(); - let result = []; - let totalLength = 0; - for (let i2 = 0; i2 < arrayLength; i2++) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); - result.push(decoded); - totalLength += decodedLength; - buffer = buffer.slice(decodedLength); - } - return [new typesystem_1.ArrayVec(type, result), totalLength]; - } - decodeTopLevel(buffer, type) { - let [result, _4] = this.decodeNested(buffer, type); - return result; - } - encodeNested(array) { - let itemsBuffers = []; - for (const item of array.getItems()) { - let itemBuffer = this.binaryCodec.encodeNested(item); - itemsBuffers.push(itemBuffer); - } - return import_buffer.Buffer.concat(itemsBuffers); - } - encodeTopLevel(array) { - return this.encodeNested(array); - } - }; - exports2.ArrayVecBinaryCodec = ArrayVecBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js -var require_binary = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryCodecConstraints = exports2.BinaryCodec = void 0; - var errors = __importStar2(require_errors()); - var typesystem_1 = require_typesystem(); - var utils_1 = require_utils2(); - var option_1 = require_option(); - var primitive_1 = require_primitive(); - var list_1 = require_list(); - var struct_1 = require_struct2(); - var enum_1 = require_enum2(); - var tuple_1 = require_tuple2(); - var arrayVec_1 = require_arrayVec(); - var BinaryCodec = class { - constructor(constraints = null) { - this.constraints = constraints || new BinaryCodecConstraints(); - this.optionCodec = new option_1.OptionValueBinaryCodec(this); - this.listCodec = new list_1.ListBinaryCodec(this); - this.arrayCodec = new arrayVec_1.ArrayVecBinaryCodec(this); - this.primitiveCodec = new primitive_1.PrimitiveBinaryCodec(this); - this.structCodec = new struct_1.StructBinaryCodec(this); - this.tupleCodec = new tuple_1.TupleBinaryCodec(this); - this.enumCodec = new enum_1.EnumBinaryCodec(this); - } - decodeTopLevel(buffer, type) { - this.constraints.checkBufferLength(buffer); - let typedValue = typesystem_1.onTypeSelect(type, { - onOption: () => this.optionCodec.decodeTopLevel(buffer, type.getFirstTypeParameter()), - onList: () => this.listCodec.decodeTopLevel(buffer, type), - onArray: () => this.arrayCodec.decodeTopLevel(buffer, type), - onPrimitive: () => this.primitiveCodec.decodeTopLevel(buffer, type), - onStruct: () => this.structCodec.decodeTopLevel(buffer, type), - onTuple: () => this.tupleCodec.decodeTopLevel(buffer, type), - onEnum: () => this.enumCodec.decodeTopLevel(buffer, type) - }); - return typedValue; - } - decodeNested(buffer, type) { - this.constraints.checkBufferLength(buffer); - let [typedResult, decodedLength] = typesystem_1.onTypeSelect(type, { - onOption: () => this.optionCodec.decodeNested(buffer, type.getFirstTypeParameter()), - onList: () => this.listCodec.decodeNested(buffer, type), - onArray: () => this.arrayCodec.decodeNested(buffer, type), - onPrimitive: () => this.primitiveCodec.decodeNested(buffer, type), - onStruct: () => this.structCodec.decodeNested(buffer, type), - onTuple: () => this.tupleCodec.decodeNested(buffer, type), - onEnum: () => this.enumCodec.decodeNested(buffer, type) - }); - return [typedResult, decodedLength]; - } - encodeNested(typedValue) { - utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); - return typesystem_1.onTypedValueSelect(typedValue, { - onPrimitive: () => this.primitiveCodec.encodeNested(typedValue), - onOption: () => this.optionCodec.encodeNested(typedValue), - onList: () => this.listCodec.encodeNested(typedValue), - onArray: () => this.arrayCodec.encodeNested(typedValue), - onStruct: () => this.structCodec.encodeNested(typedValue), - onTuple: () => this.tupleCodec.encodeNested(typedValue), - onEnum: () => this.enumCodec.encodeNested(typedValue) - }); - } - encodeTopLevel(typedValue) { - utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); - return typesystem_1.onTypedValueSelect(typedValue, { - onPrimitive: () => this.primitiveCodec.encodeTopLevel(typedValue), - onOption: () => this.optionCodec.encodeTopLevel(typedValue), - onList: () => this.listCodec.encodeTopLevel(typedValue), - onArray: () => this.arrayCodec.encodeTopLevel(typedValue), - onStruct: () => this.structCodec.encodeTopLevel(typedValue), - onTuple: () => this.tupleCodec.encodeTopLevel(typedValue), - onEnum: () => this.enumCodec.encodeTopLevel(typedValue) - }); - } - }; - exports2.BinaryCodec = BinaryCodec; - var BinaryCodecConstraints = class { - constructor(init) { - this.maxBufferLength = init?.maxBufferLength || 256e3; - this.maxListLength = init?.maxListLength || 128e3; - } - checkBufferLength(buffer) { - if (buffer.length > this.maxBufferLength) { - throw new errors.ErrCodec(`Buffer too large: ${buffer.length} > ${this.maxBufferLength}`); - } - } - /** - * This constraint avoids computer-freezing decode bugs (e.g. due to invalid ABI or struct definitions). - */ - checkListLength(length2) { - if (length2 > this.maxListLength) { - throw new errors.ErrCodec(`List too large: ${length2} > ${this.maxListLength}`); - } - } - }; - exports2.BinaryCodecConstraints = BinaryCodecConstraints; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js -var require_binaryCodecUtils = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decodeBigNumber = exports2.decodeString = exports2.decodeBool = exports2.decodeUnsignedNumber = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var typesystem_1 = require_typesystem(); - var binary_1 = require_binary(); - var Codec2 = new binary_1.BinaryCodec(); - function decodeUnsignedNumber(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); - let raw = Number(value.valueOf()); - return raw; - } - exports2.decodeUnsignedNumber = decodeUnsignedNumber; - function decodeBool(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BooleanType()); - let raw = Boolean(value.valueOf()); - return raw; - } - exports2.decodeBool = decodeBool; - function decodeString(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BytesType()); - let raw = String(value.valueOf()); - return raw; - } - exports2.decodeString = decodeString; - function decodeBigNumber(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); - let raw = new bignumber_js_1.default(value.valueOf()); - return raw; - } - exports2.decodeBigNumber = decodeBigNumber; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js -var require_codec2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_binary(), exports2); - __exportStar2(require_binaryCodecUtils(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js -var require_argSerializer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArgSerializer = void 0; - var constants_1 = require_constants(); - var codec_1 = require_codec2(); - var typesystem_1 = require_typesystem(); - var algebraic_1 = require_algebraic(); - var composite_1 = require_composite(); - var variadic_1 = require_variadic(); - var defaultArgSerializerOptions = { - codec: new codec_1.BinaryCodec() - }; - var ArgSerializer = class { - constructor(options) { - options = { ...defaultArgSerializerOptions, ...options }; - this.codec = options.codec; - } - /** - * Reads typed values from an arguments string (e.g. aa@bb@@cc), given parameter definitions. - */ - stringToValues(joinedString, parameters) { - let buffers = this.stringToBuffers(joinedString); - let values = this.buffersToValues(buffers, parameters); - return values; - } - /** - * Reads raw buffers from an arguments string (e.g. aa@bb@@cc). - */ - stringToBuffers(joinedString) { - return joinedString.split(constants_1.ARGUMENTS_SEPARATOR).map((item) => import_buffer.Buffer.from(item, "hex")); - } - /** - * Decodes a set of buffers into a set of typed values, given parameter definitions. - */ - buffersToValues(buffers, parameters) { - const self2 = this; - buffers = buffers || []; - let values = []; - let bufferIndex = 0; - let numBuffers = buffers.length; - for (let i2 = 0; i2 < parameters.length; i2++) { - let parameter = parameters[i2]; - let type = parameter.type; - let value = readValue(type); - values.push(value); - } - function readValue(type) { - if (type.hasExactClass(algebraic_1.OptionalType.ClassName)) { - const typedValue2 = readValue(type.getFirstTypeParameter()); - return new algebraic_1.OptionalValue(type, typedValue2); - } - if (type.hasExactClass(variadic_1.VariadicType.ClassName)) { - return readVariadicValue(type); - } - if (type.hasExactClass(composite_1.CompositeType.ClassName)) { - const typedValues = []; - for (const typeParameter of type.getTypeParameters()) { - typedValues.push(readValue(typeParameter)); - } - return new composite_1.CompositeValue(type, typedValues); - } - const typedValue = decodeNextBuffer(type); - return typedValue; - } - function readVariadicValue(type) { - const variadicType = type; - const typedValues = []; - if (variadicType.isCounted) { - const count = readValue(new typesystem_1.U32Type()).valueOf().toNumber(); - for (let i2 = 0; i2 < count; i2++) { - typedValues.push(readValue(type.getFirstTypeParameter())); - } - } else { - while (!hasReachedTheEnd()) { - typedValues.push(readValue(type.getFirstTypeParameter())); - } - } - return new variadic_1.VariadicValue(variadicType, typedValues); - } - function decodeNextBuffer(type) { - if (hasReachedTheEnd()) { - return null; - } - let buffer = buffers[bufferIndex++]; - let decodedValue = self2.codec.decodeTopLevel(buffer, type); - return decodedValue; - } - function hasReachedTheEnd() { - return bufferIndex >= numBuffers; - } - return values; - } - /** - * Serializes a set of typed values into an arguments string (e.g. aa@bb@@cc). - */ - valuesToString(values) { - let strings = this.valuesToStrings(values); - let argumentsString = strings.join(constants_1.ARGUMENTS_SEPARATOR); - let count = strings.length; - return { argumentsString, count }; - } - /** - * Serializes a set of typed values into a set of strings. - */ - valuesToStrings(values) { - let buffers = this.valuesToBuffers(values); - let strings = buffers.map((buffer) => buffer.toString("hex")); - return strings; - } - /** - * Serializes a set of typed values into a set of strings buffers. - * Variadic types and composite types might result into none, one or more buffers. - */ - valuesToBuffers(values) { - const self2 = this; - const buffers = []; - for (const value of values) { - handleValue(value); - } - function handleValue(value) { - if (value.hasExactClass(algebraic_1.OptionalValue.ClassName)) { - const valueAsOptional = value; - if (valueAsOptional.isSet()) { - handleValue(valueAsOptional.getTypedValue()); - } - return; - } - if (value.hasExactClass(variadic_1.VariadicValue.ClassName)) { - handleVariadicValue(value); - return; - } - if (value.hasExactClass(composite_1.CompositeValue.ClassName)) { - const valueAsComposite = value; - for (const item of valueAsComposite.getItems()) { - handleValue(item); - } - return; - } - const buffer = self2.codec.encodeTopLevel(value); - buffers.push(buffer); - } - function handleVariadicValue(value) { - const variadicType = value.getType(); - if (variadicType.isCounted) { - const countValue = new typesystem_1.U32Value(value.getItems().length); - buffers.push(self2.codec.encodeTopLevel(countValue)); - } - for (const item of value.getItems()) { - handleValue(item); - } - } - return buffers; - } - }; - exports2.ArgSerializer = ArgSerializer; - } -}); - -// node_modules/nanoassert/index.js -var require_nanoassert = __commonJS({ - "node_modules/nanoassert/index.js"(exports2, module2) { - init_shim(); - assert.notEqual = notEqual; - assert.notOk = notOk; - assert.equal = equal; - assert.ok = assert; - module2.exports = assert; - function equal(a3, b4, m3) { - assert(a3 == b4, m3); - } - function notEqual(a3, b4, m3) { - assert(a3 != b4, m3); - } - function notOk(t, m3) { - assert(!t, m3); - } - function assert(t, m3) { - if (!t) - throw new Error(m3 || "AssertionError"); - } - } -}); - -// node_modules/blake2b-wasm/blake2b.js -var require_blake2b = __commonJS({ - "node_modules/blake2b-wasm/blake2b.js"(exports2, module2) { - init_shim(); - module2.exports = loadWebAssembly; - loadWebAssembly.supported = typeof WebAssembly !== "undefined"; - function loadWebAssembly(opts) { - if (!loadWebAssembly.supported) - return null; - var imp = opts && opts.imports; - var wasm = toUint8Array("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"); - var ready = null; - var mod2 = { - buffer: wasm, - memory: null, - exports: null, - realloc, - onload - }; - onload(function() { - }); - return mod2; - function realloc(size) { - mod2.exports.memory.grow(Math.ceil(Math.abs(size - mod2.memory.length) / 65536)); - mod2.memory = new Uint8Array(mod2.exports.memory.buffer); - } - function onload(cb) { - if (mod2.exports) - return cb(); - if (ready) { - ready.then(cb.bind(null, null)).catch(cb); - return; - } - try { - if (opts && opts.async) - throw new Error("async"); - setup({ instance: new WebAssembly.Instance(new WebAssembly.Module(wasm), imp) }); - } catch (err) { - ready = WebAssembly.instantiate(wasm, imp).then(setup); - } - onload(cb); - } - function setup(w4) { - mod2.exports = w4.instance.exports; - mod2.memory = mod2.exports.memory && mod2.exports.memory.buffer && new Uint8Array(mod2.exports.memory.buffer); - } - } - function toUint8Array(s2) { - if (typeof atob === "function") - return new Uint8Array(atob(s2).split("").map(charCodeAt)); - return new (require_buffer2()).Buffer(s2, "base64"); - } - function charCodeAt(c4) { - return c4.charCodeAt(0); - } - } -}); - -// node_modules/blake2b-wasm/index.js -var require_blake2b_wasm = __commonJS({ - "node_modules/blake2b-wasm/index.js"(exports2, module2) { - init_shim(); - var assert = require_nanoassert(); - var wasm = require_blake2b()(); - var head = 64; - var freeList = []; - module2.exports = Blake2b; - var BYTES_MIN = module2.exports.BYTES_MIN = 16; - var BYTES_MAX = module2.exports.BYTES_MAX = 64; - var BYTES = module2.exports.BYTES = 32; - var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; - var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; - var KEYBYTES = module2.exports.KEYBYTES = 32; - var SALTBYTES = module2.exports.SALTBYTES = 16; - var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; - function Blake2b(digestLength, key, salt, personal, noAssert) { - if (!(this instanceof Blake2b)) - return new Blake2b(digestLength, key, salt, personal, noAssert); - if (!(wasm && wasm.exports)) - throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)"); - if (!digestLength) - digestLength = 32; - if (noAssert !== true) { - assert(digestLength >= BYTES_MIN, "digestLength must be at least " + BYTES_MIN + ", was given " + digestLength); - assert(digestLength <= BYTES_MAX, "digestLength must be at most " + BYTES_MAX + ", was given " + digestLength); - if (key != null) - assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); - if (key != null) - assert(key.length <= KEYBYTES_MAX, "key must be at least " + KEYBYTES_MAX + ", was given " + key.length); - if (salt != null) - assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); - if (personal != null) - assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); - } - if (!freeList.length) { - freeList.push(head); - head += 216; - } - this.digestLength = digestLength; - this.finalized = false; - this.pointer = freeList.pop(); - wasm.memory.fill(0, 0, 64); - wasm.memory[0] = this.digestLength; - wasm.memory[1] = key ? key.length : 0; - wasm.memory[2] = 1; - wasm.memory[3] = 1; - if (salt) - wasm.memory.set(salt, 32); - if (personal) - wasm.memory.set(personal, 48); - if (this.pointer + 216 > wasm.memory.length) - wasm.realloc(this.pointer + 216); - wasm.exports.blake2b_init(this.pointer, this.digestLength); - if (key) { - this.update(key); - wasm.memory.fill(0, head, head + key.length); - wasm.memory[this.pointer + 200] = 128; - } - } - Blake2b.prototype.update = function(input) { - assert(this.finalized === false, "Hash instance finalized"); - assert(input, "input must be TypedArray or Buffer"); - if (head + input.length > wasm.memory.length) - wasm.realloc(head + input.length); - wasm.memory.set(input, head); - wasm.exports.blake2b_update(this.pointer, head, head + input.length); - return this; - }; - Blake2b.prototype.digest = function(enc) { - assert(this.finalized === false, "Hash instance finalized"); - this.finalized = true; - freeList.push(this.pointer); - wasm.exports.blake2b_final(this.pointer); - if (!enc || enc === "binary") { - return wasm.memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength); - } - if (enc === "hex") { - return hexSlice(wasm.memory, this.pointer + 128, this.digestLength); - } - assert(enc.length >= this.digestLength, "input must be TypedArray or Buffer"); - for (var i2 = 0; i2 < this.digestLength; i2++) { - enc[i2] = wasm.memory[this.pointer + 128 + i2]; - } - return enc; - }; - Blake2b.prototype.final = Blake2b.prototype.digest; - Blake2b.WASM = wasm && wasm.buffer; - Blake2b.SUPPORTED = typeof WebAssembly !== "undefined"; - Blake2b.ready = function(cb) { - if (!cb) - cb = noop; - if (!wasm) - return cb(new Error("WebAssembly not supported")); - var p3 = new Promise(function(reject, resolve) { - wasm.onload(function(err) { - if (err) - resolve(); - else - reject(); - cb(err); - }); - }); - return p3; - }; - Blake2b.prototype.ready = Blake2b.ready; - function noop() { - } - function hexSlice(buf, start, len) { - var str = ""; - for (var i2 = 0; i2 < len; i2++) - str += toHex(buf[start + i2]); - return str; - } - function toHex(n3) { - if (n3 < 16) - return "0" + n3.toString(16); - return n3.toString(16); - } - } -}); - -// node_modules/blake2b/index.js -var require_blake2b2 = __commonJS({ - "node_modules/blake2b/index.js"(exports2, module2) { - init_shim(); - var assert = require_nanoassert(); - var b2wasm = require_blake2b_wasm(); - function ADD64AA(v3, a3, b4) { - var o0 = v3[a3] + v3[b4]; - var o1 = v3[a3 + 1] + v3[b4 + 1]; - if (o0 >= 4294967296) { - o1++; - } - v3[a3] = o0; - v3[a3 + 1] = o1; - } - function ADD64AC(v3, a3, b0, b1) { - var o0 = v3[a3] + b0; - if (b0 < 0) { - o0 += 4294967296; - } - var o1 = v3[a3 + 1] + b1; - if (o0 >= 4294967296) { - o1++; - } - v3[a3] = o0; - v3[a3 + 1] = o1; - } - function B2B_GET32(arr, i2) { - return arr[i2] ^ arr[i2 + 1] << 8 ^ arr[i2 + 2] << 16 ^ arr[i2 + 3] << 24; - } - function B2B_G(a3, b4, c4, d3, ix, iy) { - var x0 = m3[ix]; - var x1 = m3[ix + 1]; - var y0 = m3[iy]; - var y1 = m3[iy + 1]; - ADD64AA(v2, a3, b4); - ADD64AC(v2, a3, x0, x1); - var xor0 = v2[d3] ^ v2[a3]; - var xor1 = v2[d3 + 1] ^ v2[a3 + 1]; - v2[d3] = xor1; - v2[d3 + 1] = xor0; - ADD64AA(v2, c4, d3); - xor0 = v2[b4] ^ v2[c4]; - xor1 = v2[b4 + 1] ^ v2[c4 + 1]; - v2[b4] = xor0 >>> 24 ^ xor1 << 8; - v2[b4 + 1] = xor1 >>> 24 ^ xor0 << 8; - ADD64AA(v2, a3, b4); - ADD64AC(v2, a3, y0, y1); - xor0 = v2[d3] ^ v2[a3]; - xor1 = v2[d3 + 1] ^ v2[a3 + 1]; - v2[d3] = xor0 >>> 16 ^ xor1 << 16; - v2[d3 + 1] = xor1 >>> 16 ^ xor0 << 16; - ADD64AA(v2, c4, d3); - xor0 = v2[b4] ^ v2[c4]; - xor1 = v2[b4 + 1] ^ v2[c4 + 1]; - v2[b4] = xor1 >>> 31 ^ xor0 << 1; - v2[b4 + 1] = xor0 >>> 31 ^ xor1 << 1; - } - var BLAKE2B_IV32 = new Uint32Array([ - 4089235720, - 1779033703, - 2227873595, - 3144134277, - 4271175723, - 1013904242, - 1595750129, - 2773480762, - 2917565137, - 1359893119, - 725511199, - 2600822924, - 4215389547, - 528734635, - 327033209, - 1541459225 - ]); - var SIGMA8 = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - 11, - 8, - 12, - 0, - 5, - 2, - 15, - 13, - 10, - 14, - 3, - 6, - 7, - 1, - 9, - 4, - 7, - 9, - 3, - 1, - 13, - 12, - 11, - 14, - 2, - 6, - 5, - 10, - 4, - 0, - 15, - 8, - 9, - 0, - 5, - 7, - 2, - 4, - 10, - 15, - 14, - 1, - 11, - 12, - 6, - 8, - 3, - 13, - 2, - 12, - 6, - 10, - 0, - 11, - 8, - 3, - 4, - 13, - 7, - 5, - 15, - 14, - 1, - 9, - 12, - 5, - 1, - 15, - 14, - 13, - 4, - 10, - 0, - 7, - 6, - 3, - 9, - 2, - 8, - 11, - 13, - 11, - 7, - 14, - 12, - 1, - 3, - 9, - 5, - 0, - 15, - 4, - 8, - 6, - 2, - 10, - 6, - 15, - 14, - 9, - 11, - 3, - 0, - 8, - 12, - 2, - 13, - 7, - 1, - 4, - 10, - 5, - 10, - 2, - 8, - 4, - 7, - 6, - 1, - 5, - 15, - 11, - 9, - 14, - 3, - 12, - 13, - 0, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3 - ]; - var SIGMA82 = new Uint8Array(SIGMA8.map(function(x3) { - return x3 * 2; - })); - var v2 = new Uint32Array(32); - var m3 = new Uint32Array(32); - function blake2bCompress(ctx, last) { - var i2 = 0; - for (i2 = 0; i2 < 16; i2++) { - v2[i2] = ctx.h[i2]; - v2[i2 + 16] = BLAKE2B_IV32[i2]; - } - v2[24] = v2[24] ^ ctx.t; - v2[25] = v2[25] ^ ctx.t / 4294967296; - if (last) { - v2[28] = ~v2[28]; - v2[29] = ~v2[29]; - } - for (i2 = 0; i2 < 32; i2++) { - m3[i2] = B2B_GET32(ctx.b, 4 * i2); - } - for (i2 = 0; i2 < 12; i2++) { - B2B_G(0, 8, 16, 24, SIGMA82[i2 * 16 + 0], SIGMA82[i2 * 16 + 1]); - B2B_G(2, 10, 18, 26, SIGMA82[i2 * 16 + 2], SIGMA82[i2 * 16 + 3]); - B2B_G(4, 12, 20, 28, SIGMA82[i2 * 16 + 4], SIGMA82[i2 * 16 + 5]); - B2B_G(6, 14, 22, 30, SIGMA82[i2 * 16 + 6], SIGMA82[i2 * 16 + 7]); - B2B_G(0, 10, 20, 30, SIGMA82[i2 * 16 + 8], SIGMA82[i2 * 16 + 9]); - B2B_G(2, 12, 22, 24, SIGMA82[i2 * 16 + 10], SIGMA82[i2 * 16 + 11]); - B2B_G(4, 14, 16, 26, SIGMA82[i2 * 16 + 12], SIGMA82[i2 * 16 + 13]); - B2B_G(6, 8, 18, 28, SIGMA82[i2 * 16 + 14], SIGMA82[i2 * 16 + 15]); - } - for (i2 = 0; i2 < 16; i2++) { - ctx.h[i2] = ctx.h[i2] ^ v2[i2] ^ v2[i2 + 16]; - } - } - var parameter_block = new Uint8Array([ - 0, - 0, - 0, - 0, - // 0: outlen, keylen, fanout, depth - 0, - 0, - 0, - 0, - // 4: leaf length, sequential mode - 0, - 0, - 0, - 0, - // 8: node offset - 0, - 0, - 0, - 0, - // 12: node offset - 0, - 0, - 0, - 0, - // 16: node depth, inner length, rfu - 0, - 0, - 0, - 0, - // 20: rfu - 0, - 0, - 0, - 0, - // 24: rfu - 0, - 0, - 0, - 0, - // 28: rfu - 0, - 0, - 0, - 0, - // 32: salt - 0, - 0, - 0, - 0, - // 36: salt - 0, - 0, - 0, - 0, - // 40: salt - 0, - 0, - 0, - 0, - // 44: salt - 0, - 0, - 0, - 0, - // 48: personal - 0, - 0, - 0, - 0, - // 52: personal - 0, - 0, - 0, - 0, - // 56: personal - 0, - 0, - 0, - 0 - // 60: personal - ]); - function Blake2b(outlen, key, salt, personal) { - parameter_block.fill(0); - this.b = new Uint8Array(128); - this.h = new Uint32Array(16); - this.t = 0; - this.c = 0; - this.outlen = outlen; - parameter_block[0] = outlen; - if (key) - parameter_block[1] = key.length; - parameter_block[2] = 1; - parameter_block[3] = 1; - if (salt) - parameter_block.set(salt, 32); - if (personal) - parameter_block.set(personal, 48); - for (var i2 = 0; i2 < 16; i2++) { - this.h[i2] = BLAKE2B_IV32[i2] ^ B2B_GET32(parameter_block, i2 * 4); - } - if (key) { - blake2bUpdate(this, key); - this.c = 128; - } - } - Blake2b.prototype.update = function(input) { - assert(input != null, "input must be Uint8Array or Buffer"); - blake2bUpdate(this, input); - return this; - }; - Blake2b.prototype.digest = function(out) { - var buf = !out || out === "binary" || out === "hex" ? new Uint8Array(this.outlen) : out; - assert(buf.length >= this.outlen, "out must have at least outlen bytes of space"); - blake2bFinal(this, buf); - if (out === "hex") - return hexSlice(buf); - return buf; - }; - Blake2b.prototype.final = Blake2b.prototype.digest; - Blake2b.ready = function(cb) { - b2wasm.ready(function() { - cb(); - }); - }; - function blake2bUpdate(ctx, input) { - for (var i2 = 0; i2 < input.length; i2++) { - if (ctx.c === 128) { - ctx.t += ctx.c; - blake2bCompress(ctx, false); - ctx.c = 0; - } - ctx.b[ctx.c++] = input[i2]; - } - } - function blake2bFinal(ctx, out) { - ctx.t += ctx.c; - while (ctx.c < 128) { - ctx.b[ctx.c++] = 0; - } - blake2bCompress(ctx, true); - for (var i2 = 0; i2 < ctx.outlen; i2++) { - out[i2] = ctx.h[i2 >> 2] >> 8 * (i2 & 3); - } - return out; - } - function hexSlice(buf) { - var str = ""; - for (var i2 = 0; i2 < buf.length; i2++) - str += toHex(buf[i2]); - return str; - } - function toHex(n3) { - if (n3 < 16) - return "0" + n3.toString(16); - return n3.toString(16); - } - var Proto = Blake2b; - module2.exports = function createHash(outlen, key, salt, personal, noAssert) { - if (noAssert !== true) { - assert(outlen >= BYTES_MIN, "outlen must be at least " + BYTES_MIN + ", was given " + outlen); - assert(outlen <= BYTES_MAX, "outlen must be at most " + BYTES_MAX + ", was given " + outlen); - if (key != null) - assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); - if (key != null) - assert(key.length <= KEYBYTES_MAX, "key must be at most " + KEYBYTES_MAX + ", was given " + key.length); - if (salt != null) - assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); - if (personal != null) - assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); - } - return new Proto(outlen, key, salt, personal); - }; - module2.exports.ready = function(cb) { - b2wasm.ready(function() { - cb(); - }); - }; - module2.exports.WASM_SUPPORTED = b2wasm.SUPPORTED; - module2.exports.WASM_LOADED = false; - var BYTES_MIN = module2.exports.BYTES_MIN = 16; - var BYTES_MAX = module2.exports.BYTES_MAX = 64; - var BYTES = module2.exports.BYTES = 32; - var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; - var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; - var KEYBYTES = module2.exports.KEYBYTES = 32; - var SALTBYTES = module2.exports.SALTBYTES = 16; - var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; - b2wasm.ready(function(err) { - if (!err) { - module2.exports.WASM_LOADED = true; - Proto = b2wasm; - } - }); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/code.js -var require_code = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/code.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Code = void 0; - var createHasher = require_blake2b2(); - var CODE_HASH_LENGTH = 32; - var Code = class _Code { - constructor(hex) { - this.hex = hex; - } - /** - * Creates a Code object from a buffer (sequence of bytes). - */ - static fromBuffer(code2) { - return new _Code(code2.toString("hex")); - } - /** - * Creates a Code object from a hex-encoded string. - */ - static fromHex(hex) { - return new _Code(hex); - } - /** - * Returns the bytecode as a hex-encoded string. - */ - toString() { - return this.hex; - } - valueOf() { - return import_buffer.Buffer.from(this.hex, "hex"); - } - computeHash() { - const hash = createHasher(CODE_HASH_LENGTH).update(this.valueOf()).digest(); - return import_buffer.Buffer.from(hash); - } - }; - exports2.Code = Code; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js -var require_codeMetadata2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CodeMetadata = void 0; - var CodeMetadata = class _CodeMetadata { - /** - * Creates a metadata object. By default, set the `upgradeable` attribute, and uset all others. - * - * @param upgradeable Whether the contract is upgradeable - * @param readable Whether other contracts can read this contract's data (without calling one of its pure functions) - * @param payable Whether the contract is payable - * @param payableBySc Whether the contract is payable by other smart contracts - */ - constructor(upgradeable = true, readable = false, payable = false, payableBySc = false) { - this.upgradeable = upgradeable; - this.readable = readable; - this.payable = payable; - this.payableBySc = payableBySc; - } - static fromBytes(bytes) { - return _CodeMetadata.fromBuffer(import_buffer.Buffer.from(bytes)); - } - /** - * Creates a metadata object from a buffer. - */ - static fromBuffer(buffer) { - if (buffer.length < this.codeMetadataLength) { - throw new Error("Buffer is too short."); - } - const byteZero = buffer[0]; - const byteOne = buffer[1]; - const upgradeable = (byteZero & _CodeMetadata.ByteZero.Upgradeable) !== 0; - const readable = (byteZero & _CodeMetadata.ByteZero.Readable) !== 0; - const payable = (byteOne & _CodeMetadata.ByteOne.Payable) !== 0; - const payableBySc = (byteOne & _CodeMetadata.ByteOne.PayableBySc) !== 0; - return new _CodeMetadata(upgradeable, readable, payable, payableBySc); - } - /** - * Adjust the metadata (the `upgradeable` attribute), when preparing the deployment transaction. - */ - toggleUpgradeable(value) { - this.upgradeable = value; - } - /** - * Adjust the metadata (the `readable` attribute), when preparing the deployment transaction. - */ - toggleReadable(value) { - this.readable = value; - } - /** - * Adjust the metadata (the `payable` attribute), when preparing the deployment transaction. - */ - togglePayable(value) { - this.payable = value; - } - /** - * Adjust the metadata (the `payableBySc` attribute), when preparing the deployment transaction. - */ - togglePayableBySc(value) { - this.payableBySc = value; - } - /** - * Converts the metadata to the protocol-friendly representation. - */ - toBuffer() { - let byteZero = 0; - let byteOne = 0; - if (this.upgradeable) { - byteZero |= _CodeMetadata.ByteZero.Upgradeable; - } - if (this.readable) { - byteZero |= _CodeMetadata.ByteZero.Readable; - } - if (this.payable) { - byteOne |= _CodeMetadata.ByteOne.Payable; - } - if (this.payableBySc) { - byteOne |= _CodeMetadata.ByteOne.PayableBySc; - } - return import_buffer.Buffer.from([byteZero, byteOne]); - } - /** - * Converts the metadata to a hex-encoded string. - */ - toString() { - return this.toBuffer().toString("hex"); - } - /** - * Converts the metadata to a pretty, plain JavaScript object. - */ - toJSON() { - return { - upgradeable: this.upgradeable, - readable: this.readable, - payable: this.payable, - payableBySc: this.payableBySc - }; - } - equals(other) { - return this.upgradeable == other.upgradeable && this.readable == other.readable && this.payable == other.payable && this.payableBySc == other.payableBySc; - } - }; - exports2.CodeMetadata = CodeMetadata; - CodeMetadata.codeMetadataLength = 2; - CodeMetadata.ByteZero = { - Upgradeable: 1, - Reserved2: 2, - Readable: 4 - }; - CodeMetadata.ByteOne = { - Reserved1: 1, - Payable: 2, - PayableBySc: 4 - }; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/function.js -var require_function = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/function.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractFunction = void 0; - var errors = __importStar2(require_errors()); - var ContractFunction = class _ContractFunction { - /** - * Creates a ContractFunction object, given its name. - * - * @param name the name of the function - */ - constructor(name2) { - this.name = name2; - if (name2 == null) { - throw new errors.ErrInvalidFunctionName(); - } - } - /** - * Null-object pattern: creates an empty ContractFunction object. - */ - static none() { - return new _ContractFunction("untitled"); - } - /** - * Returns the name of the function. - */ - toString() { - return this.name; - } - valueOf() { - return this.name; - } - }; - exports2.ContractFunction = ContractFunction; - } -}); - -// node_modules/@multiversx/sdk-core/out/compatibility.js -var require_compatibility = __commonJS({ - "node_modules/@multiversx/sdk-core/out/compatibility.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Compatibility = void 0; - var address_1 = require_address(); - var Compatibility = class { - /** - * For internal use only. - */ - static guardAddressIsSetAndNonZero(address, context, resolution) { - if (!address || address.bech32() == "") { - console.warn(`${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); - } else if (address.bech32() == address_1.Address.Zero().bech32()) { - console.warn(`${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); - } - } - }; - exports2.Compatibility = Compatibility; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionPayload.js -var require_transactionPayload = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionPayload.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionPayload = void 0; - var TransactionPayload = class _TransactionPayload { - /** - * Creates a TransactionPayload from a utf-8 string or from a buffer. - */ - constructor(data) { - this.data = import_buffer.Buffer.from(data || []); - } - /** - * Creates a TransactionPayload from a base-64 encoded string. - */ - static fromEncoded(encoded) { - if (!encoded) { - return new _TransactionPayload(""); - } - let decoded = import_buffer.Buffer.from(encoded, "base64").toString(); - return new _TransactionPayload(decoded); - } - /** - * Returns whether the "data" is void. - */ - isEmpty() { - return this.data.length == 0; - } - /** - * Returns the base-64 representation of the data. - */ - encoded() { - return this.data.toString("base64"); - } - /** - * Returns the data as a buffer. - */ - valueOf() { - return this.data; - } - toString() { - return this.data.toString(); - } - getEncodedArguments() { - return this.toString().split("@"); - } - getRawArguments() { - return this.getEncodedArguments().map((argument) => import_buffer.Buffer.from(argument, "hex")); - } - /** - * Returns the length of the data. - */ - length() { - return import_buffer.Buffer.from(this.data).length; - } - }; - exports2.TransactionPayload = TransactionPayload; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js -var require_transactionBuilder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionBuilder = void 0; - var constants_1 = require_constants(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var TransactionBuilder = class { - constructor(options) { - this.config = options.config; - this.sender = options.sender; - this.receiver = options.receiver; - this.dataParts = options.dataParts; - this.providedGasLimit = options.gasLimit; - this.addDataMovementGas = options.addDataMovementGas; - this.amount = options.amount; - } - computeGasLimit(payload) { - if (!this.addDataMovementGas) { - return this.providedGasLimit; - } - const dataMovementGas = this.config.minGasLimit + this.config.gasLimitPerByte * BigInt(payload.length()); - const gasLimit = dataMovementGas + this.providedGasLimit; - return gasLimit; - } - buildTransactionPayload() { - const data = this.dataParts.join(constants_1.ARGUMENTS_SEPARATOR); - return new transactionPayload_1.TransactionPayload(data); - } - build() { - const data = this.buildTransactionPayload(); - const gasLimit = this.computeGasLimit(data); - return new transaction_1.Transaction({ - sender: this.sender.bech32(), - receiver: this.receiver.bech32(), - gasLimit, - value: this.amount || 0n, - data: data.valueOf(), - chainID: this.config.chainID - }); - } - }; - exports2.TransactionBuilder = TransactionBuilder; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js -var require_delegationTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DelegationTransactionsFactory = void 0; - var address_1 = require_address(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var transactionBuilder_1 = require_transactionBuilder(); - var DelegationTransactionsFactory = class { - constructor(options) { - this.config = options.config; - this.argSerializer = new smartcontracts_1.ArgSerializer(); - } - createTransactionForNewDelegationContract(options) { - const dataParts = [ - "createNewDelegationContract", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.BigUIntValue(options.totalDelegationCap), - new smartcontracts_1.BigUIntValue(options.serviceFee) - ]) - ]; - const executionGasLimit = this.config.gasLimitCreateDelegationContract + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.DELEGATION_MANAGER_SC_ADDRESS), - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true, - amount: options.amount - }).build(); - } - createTransactionForAddingNodes(options) { - if (options.publicKeys.length !== options.signedMessages.length) { - throw new errors_1.Err("The number of public keys should match the number of signed messages"); - } - const signedMessagesAsTypedValues = options.signedMessages.map((message) => new smartcontracts_1.BytesValue(import_buffer.Buffer.from(message))); - const messagesAsStrings = this.argSerializer.valuesToStrings(signedMessagesAsTypedValues); - const numNodes = options.publicKeys.length; - const dataParts = ["addNodes"]; - for (let i2 = 0; i2 < numNodes; i2++) { - dataParts.push(...[options.publicKeys[i2].hex(), messagesAsStrings[i2]]); - } - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), - addDataMovementGas: true - }).build(); - } - createTransactionForRemovingNodes(options) { - const dataParts = ["removeNodes"]; - for (const key of options.publicKeys) { - dataParts.push(key.hex()); - } - const numNodes = options.publicKeys.length; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), - addDataMovementGas: true - }).build(); - } - createTransactionForStakingNodes(options) { - let dataParts = ["stakeNodes"]; - for (const key of options.publicKeys) { - dataParts = dataParts.concat(key.hex()); - } - const numNodes = options.publicKeys.length; - const additionalGasForAllNodes = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode; - const executionGasLimit = additionalGasForAllNodes + this.config.gasLimitStake + this.config.gasLimitDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnbondingNodes(options) { - let dataParts = ["unBondNodes"]; - for (const key of options.publicKeys) { - dataParts = dataParts.concat(key.hex()); - } - const numNodes = options.publicKeys.length; - const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnbond + this.config.gasLimitDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnstakingNodes(options) { - let dataParts = ["unStakeNodes"]; - for (const key of options.publicKeys) { - dataParts = dataParts.concat(key.hex()); - } - const numNodes = options.publicKeys.length; - const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnstake + this.config.gasLimitDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnjailingNodes(options) { - const dataParts = ["unJailNodes"]; - for (const key of options.publicKeys) { - dataParts.push(key.hex()); - } - const numNodes = options.publicKeys.length; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), - addDataMovementGas: true - }).build(); - } - createTransactionForChangingServiceFee(options) { - const dataParts = [ - "changeServiceFee", - this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.serviceFee)])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForModifyingDelegationCap(options) { - const dataParts = [ - "modifyTotalDelegationCap", - this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.delegationCap)])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingAutomaticActivation(options) { - const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0]]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnsettingAutomaticActivation(options) { - const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0]]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingCapCheckOnRedelegateRewards(options) { - const dataParts = [ - "setCheckCapOnReDelegateRewards", - this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnsettingCapCheckOnRedelegateRewards(options) { - const dataParts = [ - "setCheckCapOnReDelegateRewards", - this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingMetadata(options) { - const dataParts = [ - "setMetaData", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.name), - new smartcontracts_1.StringValue(options.website), - new smartcontracts_1.StringValue(options.identifier) - ]) - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - computeExecutionGasLimitForNodesManagement(numNodes) { - const additionalGasForAllNodes = this.config.additionalGasLimitPerValidatorNode * BigInt(numNodes); - return this.config.gasLimitDelegationOperations + additionalGasForAllNodes; - } - }; - exports2.DelegationTransactionsFactory = DelegationTransactionsFactory; - } -}); - -// node_modules/json-bigint/lib/stringify.js -var require_stringify = __commonJS({ - "node_modules/json-bigint/lib/stringify.js"(exports2, module2) { - init_shim(); - var BigNumber2 = require_bignumber(); - var JSON2 = module2.exports; - (function() { - "use strict"; - function f4(n3) { - return n3 < 10 ? "0" + n3 : n3; - } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { - // table of character substitutions - "\b": "\\b", - " ": "\\t", - "\n": "\\n", - "\f": "\\f", - "\r": "\\r", - '"': '\\"', - "\\": "\\\\" - }, rep; - function quote(string2) { - escapable.lastIndex = 0; - return escapable.test(string2) ? '"' + string2.replace(escapable, function(a3) { - var c4 = meta[a3]; - return typeof c4 === "string" ? c4 : "\\u" + ("0000" + a3.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string2 + '"'; - } - function str(key, holder) { - var i2, k4, v2, length2, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber2 || BigNumber2.isBigNumber(value)); - if (value && typeof value === "object" && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - if (typeof rep === "function") { - value = rep.call(holder, key, value); - } - switch (typeof value) { - case "string": - if (isBigNumber) { - return value; - } else { - return quote(value); - } - case "number": - return isFinite(value) ? String(value) : "null"; - case "boolean": - case "null": - case "bigint": - return String(value); - case "object": - if (!value) { - return "null"; - } - gap += indent; - partial = []; - if (Object.prototype.toString.apply(value) === "[object Array]") { - length2 = value.length; - for (i2 = 0; i2 < length2; i2 += 1) { - partial[i2] = str(i2, value) || "null"; - } - v2 = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]"; - gap = mind; - return v2; - } - if (rep && typeof rep === "object") { - length2 = rep.length; - for (i2 = 0; i2 < length2; i2 += 1) { - if (typeof rep[i2] === "string") { - k4 = rep[i2]; - v2 = str(k4, value); - if (v2) { - partial.push(quote(k4) + (gap ? ": " : ":") + v2); - } - } - } - } else { - Object.keys(value).forEach(function(k5) { - var v3 = str(k5, value); - if (v3) { - partial.push(quote(k5) + (gap ? ": " : ":") + v3); - } - }); - } - v2 = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; - gap = mind; - return v2; - } - } - if (typeof JSON2.stringify !== "function") { - JSON2.stringify = function(value, replacer, space) { - var i2; - gap = ""; - indent = ""; - if (typeof space === "number") { - for (i2 = 0; i2 < space; i2 += 1) { - indent += " "; - } - } else if (typeof space === "string") { - indent = space; - } - rep = replacer; - if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { - throw new Error("JSON.stringify"); - } - return str("", { "": value }); - }; - } - })(); - } -}); - -// node_modules/json-bigint/lib/parse.js -var require_parse = __commonJS({ - "node_modules/json-bigint/lib/parse.js"(exports2, module2) { - init_shim(); - var BigNumber2 = null; - var suspectProtoRx2 = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; - var suspectConstructorRx2 = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; - var json_parse = function(options) { - "use strict"; - var _options = { - strict: false, - // not being strict means do not generate syntax errors for "duplicate key" - storeAsString: false, - // toggles whether the values should be stored as BigNumber (default) or a string - alwaysParseAsBig: false, - // toggles whether all numbers should be Big - useNativeBigInt: false, - // toggles whether to use native BigInt instead of bignumber.js - protoAction: "error", - constructorAction: "error" - }; - if (options !== void 0 && options !== null) { - if (options.strict === true) { - _options.strict = true; - } - if (options.storeAsString === true) { - _options.storeAsString = true; - } - _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; - _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; - if (typeof options.constructorAction !== "undefined") { - if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { - _options.constructorAction = options.constructorAction; - } else { - throw new Error( - `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` - ); - } - } - if (typeof options.protoAction !== "undefined") { - if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { - _options.protoAction = options.protoAction; - } else { - throw new Error( - `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` - ); - } - } - } - var at, ch, escapee = { - '"': '"', - "\\": "\\", - "/": "/", - b: "\b", - f: "\f", - n: "\n", - r: "\r", - t: " " - }, text, error = function(m3) { - throw { - name: "SyntaxError", - message: m3, - at, - text - }; - }, next = function(c4) { - if (c4 && c4 !== ch) { - error("Expected '" + c4 + "' instead of '" + ch + "'"); - } - ch = text.charAt(at); - at += 1; - return ch; - }, number = function() { - var number2, string3 = ""; - if (ch === "-") { - string3 = "-"; - next("-"); - } - while (ch >= "0" && ch <= "9") { - string3 += ch; - next(); - } - if (ch === ".") { - string3 += "."; - while (next() && ch >= "0" && ch <= "9") { - string3 += ch; - } - } - if (ch === "e" || ch === "E") { - string3 += ch; - next(); - if (ch === "-" || ch === "+") { - string3 += ch; - next(); - } - while (ch >= "0" && ch <= "9") { - string3 += ch; - next(); - } - } - number2 = +string3; - if (!isFinite(number2)) { - error("Bad number"); - } else { - if (BigNumber2 == null) - BigNumber2 = require_bignumber(); - if (string3.length > 15) - return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber2(string3); - else - return !_options.alwaysParseAsBig ? number2 : _options.useNativeBigInt ? BigInt(number2) : new BigNumber2(number2); - } - }, string2 = function() { - var hex, i2, string3 = "", uffff; - if (ch === '"') { - var startAt = at; - while (next()) { - if (ch === '"') { - if (at - 1 > startAt) - string3 += text.substring(startAt, at - 1); - next(); - return string3; - } - if (ch === "\\") { - if (at - 1 > startAt) - string3 += text.substring(startAt, at - 1); - next(); - if (ch === "u") { - uffff = 0; - for (i2 = 0; i2 < 4; i2 += 1) { - hex = parseInt(next(), 16); - if (!isFinite(hex)) { - break; - } - uffff = uffff * 16 + hex; - } - string3 += String.fromCharCode(uffff); - } else if (typeof escapee[ch] === "string") { - string3 += escapee[ch]; - } else { - break; - } - startAt = at; - } - } - } - error("Bad string"); - }, white = function() { - while (ch && ch <= " ") { - next(); - } - }, word = function() { - switch (ch) { - case "t": - next("t"); - next("r"); - next("u"); - next("e"); - return true; - case "f": - next("f"); - next("a"); - next("l"); - next("s"); - next("e"); - return false; - case "n": - next("n"); - next("u"); - next("l"); - next("l"); - return null; - } - error("Unexpected '" + ch + "'"); - }, value, array = function() { - var array2 = []; - if (ch === "[") { - next("["); - white(); - if (ch === "]") { - next("]"); - return array2; - } - while (ch) { - array2.push(value()); - white(); - if (ch === "]") { - next("]"); - return array2; - } - next(","); - white(); - } - } - error("Bad array"); - }, object = function() { - var key, object2 = /* @__PURE__ */ Object.create(null); - if (ch === "{") { - next("{"); - white(); - if (ch === "}") { - next("}"); - return object2; - } - while (ch) { - key = string2(); - white(); - next(":"); - if (_options.strict === true && Object.hasOwnProperty.call(object2, key)) { - error('Duplicate key "' + key + '"'); - } - if (suspectProtoRx2.test(key) === true) { - if (_options.protoAction === "error") { - error("Object contains forbidden prototype property"); - } else if (_options.protoAction === "ignore") { - value(); - } else { - object2[key] = value(); - } - } else if (suspectConstructorRx2.test(key) === true) { - if (_options.constructorAction === "error") { - error("Object contains forbidden constructor property"); - } else if (_options.constructorAction === "ignore") { - value(); - } else { - object2[key] = value(); - } - } else { - object2[key] = value(); - } - white(); - if (ch === "}") { - next("}"); - return object2; - } - next(","); - white(); - } - } - error("Bad object"); - }; - value = function() { - white(); - switch (ch) { - case "{": - return object(); - case "[": - return array(); - case '"': - return string2(); - case "-": - return number(); - default: - return ch >= "0" && ch <= "9" ? number() : word(); - } - }; - return function(source, reviver) { - var result; - text = source + ""; - at = 0; - ch = " "; - result = value(); - white(); - if (ch) { - error("Syntax error"); - } - return typeof reviver === "function" ? function walk(holder, key) { - var k4, v2, value2 = holder[key]; - if (value2 && typeof value2 === "object") { - Object.keys(value2).forEach(function(k5) { - v2 = walk(value2, k5); - if (v2 !== void 0) { - value2[k5] = v2; - } else { - delete value2[k5]; - } - }); - } - return reviver.call(holder, key, value2); - }({ "": result }, "") : result; - }; - }; - module2.exports = json_parse; - } -}); - -// node_modules/json-bigint/index.js -var require_json_bigint = __commonJS({ - "node_modules/json-bigint/index.js"(exports2, module2) { - init_shim(); - var json_stringify = require_stringify().stringify; - var json_parse = require_parse(); - module2.exports = function(options) { - return { - parse: json_parse(options), - stringify: json_stringify - }; - }; - module2.exports.parse = json_parse(); - module2.exports.stringify = json_stringify; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js -var require_relayedTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RelayedTransactionsFactory = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var transaction_1 = require_transaction(); - var JSONbig = require_json_bigint(); - var RelayedTransactionsFactory = class { - constructor(options) { - this.config = options.config; - } - createRelayedV1Transaction(options) { - if (!options.innerTransaction.gasLimit) { - throw new errors_1.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); - } - if (!options.innerTransaction.signature.length) { - throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); - } - const serializedTransaction = this.prepareInnerTransactionForRelayedV1(options.innerTransaction); - const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; - const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); - const gasLimit = this.config.minGasLimit + additionalGasForDataLength + options.innerTransaction.gasLimit; - return new transaction_1.Transaction({ - chainID: this.config.chainID, - sender: options.relayerAddress.bech32(), - receiver: options.innerTransaction.sender, - gasLimit, - data: import_buffer.Buffer.from(data) - }); - } - createRelayedV2Transaction(options) { - if (options.innerTransaction.gasLimit) { - throw new errors_1.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction"); - } - if (!options.innerTransaction.signature.length) { - throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - new smartcontracts_1.AddressValue(address_1.Address.fromBech32(options.innerTransaction.receiver)), - new smartcontracts_1.U64Value(new bignumber_js_1.default(options.innerTransaction.nonce.toString())), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.data)), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.signature)) - ]); - const data = `relayedTxV2@${argumentsString}`; - const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); - const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; - return new transaction_1.Transaction({ - sender: options.relayerAddress.bech32(), - receiver: options.innerTransaction.sender, - value: 0n, - gasLimit, - chainID: this.config.chainID, - data: import_buffer.Buffer.from(data), - version: options.innerTransaction.version, - options: options.innerTransaction.options - }); - } - prepareInnerTransactionForRelayedV1(innerTransaction) { - const txObject = { - nonce: innerTransaction.nonce, - sender: address_1.Address.fromBech32(innerTransaction.sender).pubkey().toString("base64"), - receiver: address_1.Address.fromBech32(innerTransaction.receiver).pubkey().toString("base64"), - value: innerTransaction.value, - gasPrice: innerTransaction.gasPrice, - gasLimit: innerTransaction.gasLimit, - data: import_buffer.Buffer.from(innerTransaction.data).toString("base64"), - signature: import_buffer.Buffer.from(innerTransaction.signature).toString("base64"), - chainID: import_buffer.Buffer.from(innerTransaction.chainID).toString("base64"), - version: innerTransaction.version, - options: innerTransaction.options.valueOf() == 0 ? void 0 : innerTransaction.options, - guardian: innerTransaction.guardian ? address_1.Address.fromBech32(innerTransaction.guardian).pubkey().toString("base64") : void 0, - guardianSignature: innerTransaction.guardianSignature.length ? import_buffer.Buffer.from(innerTransaction.guardianSignature).toString("base64") : void 0, - sndUserName: innerTransaction.senderUsername ? import_buffer.Buffer.from(innerTransaction.senderUsername).toString("base64") : void 0, - rcvUserName: innerTransaction.receiverUsername ? import_buffer.Buffer.from(innerTransaction.receiverUsername).toString("base64") : void 0 - }; - return JSONbig.stringify(txObject); - } - }; - exports2.RelayedTransactionsFactory = RelayedTransactionsFactory; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js -var require_argumentErrorContext = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArgumentErrorContext = void 0; - var errors_1 = require_errors(); - var ArgumentErrorContext = class { - constructor(endpointName, argumentIndex, parameterDefinition) { - this.endpointName = endpointName; - this.argumentIndex = argumentIndex; - this.parameterDefinition = parameterDefinition; - } - throwError(specificError) { - throw new errors_1.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) -Nested error: ${specificError}`); - } - convertError(native, typeName) { - this.throwError(`Can't convert argument (argument: ${native}, type ${typeof native}), wanted type: ${typeName})`); - } - unhandledType(functionName, type) { - this.throwError(`Unhandled type (function: ${functionName}, type: ${type})`); - } - guardSameLength(native, valueTypes) { - native = native || []; - if (native.length != valueTypes.length) { - this.throwError(`Incorrect composite type length: have ${native.length}, expected ${valueTypes.length} (argument: ${native})`); - } - } - guardHasField(native, fieldName) { - native = native || {}; - if (!(fieldName in native)) { - this.throwError(`Struct argument does not contain a field named "${fieldName}" (argument: ${JSON.stringify(native)})`); - } - } - }; - exports2.ArgumentErrorContext = ArgumentErrorContext; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js -var require_nativeSerializer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NativeSerializer = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var errors_1 = require_errors(); - var utils_codec_1 = require_utils_codec(); - var argumentErrorContext_1 = require_argumentErrorContext(); - var typesystem_1 = require_typesystem(); - var NativeSerializer; - (function(NativeSerializer2) { - function nativeToTypedValues(args, endpoint) { - args = args || []; - checkArgumentsCardinality(args, endpoint); - if (hasNonCountedVariadicParameter(endpoint)) { - args = repackNonCountedVariadicParameters(args, endpoint); - } else { - } - let parameters = endpoint.input; - let values = []; - for (let i2 = 0; i2 < parameters.length; i2++) { - let parameter = parameters[i2]; - let errorContext = new argumentErrorContext_1.ArgumentErrorContext(endpoint.name, i2, parameter); - let value = convertToTypedValue(args[i2], parameter.type, errorContext); - values.push(value); - } - return values; - } - NativeSerializer2.nativeToTypedValues = nativeToTypedValues; - function checkArgumentsCardinality(args, endpoint) { - const { min, max } = getArgumentsCardinality(endpoint.input); - if (!(min <= args.length && args.length <= max)) { - throw new errors_1.ErrInvalidArgument(`Wrong number of arguments for endpoint ${endpoint.name}: expected between ${min} and ${max} arguments, have ${args.length}`); - } - } - function hasNonCountedVariadicParameter(endpoint) { - const lastParameter = endpoint.input[endpoint.input.length - 1]; - return lastParameter?.type instanceof typesystem_1.VariadicType && !lastParameter.type.isCounted; - } - function repackNonCountedVariadicParameters(args, endpoint) { - const lastEndpointParamIndex = endpoint.input.length - 1; - const argAtIndex = args[lastEndpointParamIndex]; - if (argAtIndex?.belongsToTypesystem) { - const isVariadicValue = argAtIndex.hasClassOrSuperclass(typesystem_1.VariadicValue.ClassName); - if (!isVariadicValue) { - throw new errors_1.ErrInvalidArgument(`Wrong argument type for endpoint ${endpoint.name}: typed value provided; expected variadic type, have ${argAtIndex.getClassName()}`); - } - } else { - args[lastEndpointParamIndex] = args.slice(lastEndpointParamIndex); - } - return args; - } - function getArgumentsCardinality(parameters) { - let reversed = [...parameters].reverse(); - let min = parameters.length; - let max = parameters.length; - let variadic = false; - if (reversed.length > 0 && reversed[0].type.getCardinality().isComposite()) { - max = Infinity; - variadic = true; - } - for (let parameter of reversed) { - if (parameter.type.getCardinality().isSingular()) { - break; - } - min -= 1; - } - return { min, max, variadic }; - } - NativeSerializer2.getArgumentsCardinality = getArgumentsCardinality; - function convertToTypedValue(value, type, errorContext) { - if (value && value.belongsToTypesystem) { - return value; - } - if (type instanceof typesystem_1.OptionType) { - return toOptionValue(value, type, errorContext); - } - if (type instanceof typesystem_1.OptionalType) { - return toOptionalValue(value, type, errorContext); - } - if (type instanceof typesystem_1.VariadicType) { - return toVariadicValue(value, type, errorContext); - } - if (type instanceof typesystem_1.CompositeType) { - return toCompositeValue(value, type, errorContext); - } - if (type instanceof typesystem_1.TupleType) { - return toTupleValue(value, type, errorContext); - } - if (type instanceof typesystem_1.StructType) { - return toStructValue(value, type, errorContext); - } - if (type instanceof typesystem_1.ListType) { - return toListValue(value, type, errorContext); - } - if (type instanceof typesystem_1.PrimitiveType) { - return toPrimitive(value, type, errorContext); - } - if (type instanceof typesystem_1.EnumType) { - return toEnumValue(value, type, errorContext); - } - errorContext.throwError(`convertToTypedValue: unhandled type ${type}`); - } - function toOptionValue(native, type, errorContext) { - if (native == null) { - return typesystem_1.OptionValue.newMissing(); - } - let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); - return typesystem_1.OptionValue.newProvided(converted); - } - function toOptionalValue(native, type, errorContext) { - if (native == null) { - return new typesystem_1.OptionalValue(type); - } - let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); - return new typesystem_1.OptionalValue(type, converted); - } - function toVariadicValue(native, type, errorContext) { - if (type.isCounted) { - throw new errors_1.ErrInvalidArgument(`Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"`); - } - if (native == null) { - native = []; - } - if (native.map === void 0) { - errorContext.convertError(native, "Variadic"); - } - let converted = native.map(function(item) { - return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); - }); - return new typesystem_1.VariadicValue(type, converted); - } - function toListValue(native, type, errorContext) { - if (native.map === void 0) { - errorContext.convertError(native, "List"); - } - let converted = native.map(function(item) { - return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); - }); - return new typesystem_1.List(type, converted); - } - function toCompositeValue(native, type, errorContext) { - let typedValues = []; - let typeParameters = type.getTypeParameters(); - errorContext.guardSameLength(native, typeParameters); - for (let i2 = 0; i2 < typeParameters.length; i2++) { - typedValues.push(convertToTypedValue(native[i2], typeParameters[i2], errorContext)); - } - return new typesystem_1.CompositeValue(type, typedValues); - } - function toTupleValue(native, type, errorContext) { - let typedValues = []; - const fields = type.getFieldsDefinitions(); - errorContext.guardSameLength(native, fields); - for (let i2 = 0; i2 < fields.length; i2++) { - typedValues.push(convertToTypedValue(native[i2], fields[i2].type, errorContext)); - } - return typesystem_1.Tuple.fromItems(typedValues); - } - function toStructValue(native, type, errorContext) { - let structFieldValues = []; - const fields = type.getFieldsDefinitions(); - for (let i2 = 0; i2 < fields.length; i2++) { - const fieldName = fields[i2].name; - errorContext.guardHasField(native, fieldName); - const fieldNativeValue = native[fieldName]; - const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); - structFieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); - } - return new typesystem_1.Struct(type, structFieldValues); - } - function toPrimitive(native, type, errorContext) { - if (type instanceof typesystem_1.NumericalType) { - let number = new bignumber_js_1.default(native); - return convertNumericalType(number, type, errorContext); - } - if (type instanceof typesystem_1.BytesType) { - return convertNativeToBytesValue(native, errorContext); - } - if (type instanceof typesystem_1.AddressType) { - return new typesystem_1.AddressValue(convertNativeToAddress(native, errorContext)); - } - if (type instanceof typesystem_1.BooleanType) { - return new typesystem_1.BooleanValue(native); - } - if (type instanceof typesystem_1.TokenIdentifierType) { - return new typesystem_1.TokenIdentifierValue(convertNativeToString(native, errorContext)); - } - errorContext.throwError(`(function: toPrimitive) unsupported type ${type}`); - } - function toEnumValue(native, type, errorContext) { - if (typeof native === "number") { - return typesystem_1.EnumValue.fromDiscriminant(type, native); - } - if (typeof native === "string") { - return typesystem_1.EnumValue.fromName(type, native); - } - if (typeof native === "object") { - errorContext.guardHasField(native, "name"); - const variant = type.getVariantByName(native.name); - errorContext.guardHasField(native, "fields"); - const nativeFields = native.fields; - const fieldValues = []; - const fields = variant.getFieldsDefinitions(); - for (let i2 = 0; i2 < fields.length; i2++) { - const fieldName = fields[i2].name; - errorContext.guardHasField(nativeFields, fieldName); - const fieldNativeValue = nativeFields[fieldName]; - const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); - fieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); - } - return new typesystem_1.EnumValue(type, variant, fieldValues); - } - errorContext.throwError(`(function: toEnumValue) unsupported native type ${typeof native}`); - } - function convertNativeToBytesValue(native, errorContext) { - const innerValue = native.valueOf(); - if (native === void 0) { - errorContext.convertError(native, "BytesValue"); - } - if (native instanceof import_buffer.Buffer) { - return new typesystem_1.BytesValue(native); - } - if (typeof native === "string") { - return typesystem_1.BytesValue.fromUTF8(native); - } - if (innerValue instanceof import_buffer.Buffer) { - return new typesystem_1.BytesValue(innerValue); - } - if (typeof innerValue === "number") { - return typesystem_1.BytesValue.fromHex(utils_codec_1.numberToPaddedHex(innerValue)); - } - errorContext.convertError(native, "BytesValue"); - } - function convertNativeToString(native, errorContext) { - if (native === void 0) { - errorContext.convertError(native, "Buffer"); - } - if (native instanceof import_buffer.Buffer) { - return native.toString(); - } - if (typeof native === "string") { - return native; - } - errorContext.convertError(native, "Buffer"); - } - function convertNativeToAddress(native, errorContext) { - if (native.bech32) { - return native; - } - if (native.getAddress) { - return native.getAddress(); - } - switch (native.constructor) { - case import_buffer.Buffer: - case String: - return new address_1.Address(native); - default: - errorContext.convertError(native, "Address"); - } - } - NativeSerializer2.convertNativeToAddress = convertNativeToAddress; - function convertNumericalType(number, type, errorContext) { - switch (type.constructor) { - case typesystem_1.U8Type: - return new typesystem_1.U8Value(number); - case typesystem_1.I8Type: - return new typesystem_1.I8Value(number); - case typesystem_1.U16Type: - return new typesystem_1.U16Value(number); - case typesystem_1.I16Type: - return new typesystem_1.I16Value(number); - case typesystem_1.U32Type: - return new typesystem_1.U32Value(number); - case typesystem_1.I32Type: - return new typesystem_1.I32Value(number); - case typesystem_1.U64Type: - return new typesystem_1.U64Value(number); - case typesystem_1.I64Type: - return new typesystem_1.I64Value(number); - case typesystem_1.BigUIntType: - return new typesystem_1.BigUIntValue(number); - case typesystem_1.BigIntType: - return new typesystem_1.BigIntValue(number); - default: - errorContext.unhandledType("convertNumericalType", type); - } - } - })(NativeSerializer = exports2.NativeSerializer || (exports2.NativeSerializer = {})); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js -var require_tokenTransfersDataBuilder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenTransfersDataBuilder = void 0; - var argSerializer_1 = require_argSerializer(); - var typesystem_1 = require_typesystem(); - var tokens_1 = require_tokens(); - var TokenTransfersDataBuilder = class { - constructor() { - this.tokenComputer = new tokens_1.TokenComputer(); - this.argsSerializer = new argSerializer_1.ArgSerializer(); - } - buildDataPartsForESDTTransfer(transfer) { - const args = this.argsSerializer.valuesToStrings([ - new typesystem_1.TokenIdentifierValue(transfer.token.identifier), - new typesystem_1.BigUIntValue(transfer.amount) - ]); - return ["ESDTTransfer", ...args]; - } - buildDataPartsForSingleESDTNFTTransfer(transfer, receiver) { - const token = transfer.token; - const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(token.identifier); - const args = this.argsSerializer.valuesToStrings([ - new typesystem_1.TokenIdentifierValue(identifier), - new typesystem_1.BigUIntValue(token.nonce), - new typesystem_1.BigUIntValue(transfer.amount), - new typesystem_1.AddressValue(receiver) - ]); - return ["ESDTNFTTransfer", ...args]; - } - buildDataPartsForMultiESDTNFTTransfer(receiver, transfers) { - const argsTyped = [new typesystem_1.AddressValue(receiver), new typesystem_1.U32Value(transfers.length)]; - for (const transfer of transfers) { - const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(transfer.token.identifier); - argsTyped.push(...[ - new typesystem_1.TokenIdentifierValue(identifier), - new typesystem_1.BigUIntValue(transfer.token.nonce), - new typesystem_1.BigUIntValue(transfer.amount) - ]); - } - const args = this.argsSerializer.valuesToStrings(argsTyped); - return ["MultiESDTNFTTransfer", ...args]; - } - }; - exports2.TokenTransfersDataBuilder = TokenTransfersDataBuilder; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js -var require_smartContractTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractTransactionsFactory = void 0; - var address_1 = require_address(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var smartcontracts_1 = require_smartcontracts(); - var nativeSerializer_1 = require_nativeSerializer(); - var tokens_1 = require_tokens(); - var utils_codec_1 = require_utils_codec(); - var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); - var transactionBuilder_1 = require_transactionBuilder(); - var SmartContractTransactionsFactory2 = class { - constructor(options) { - this.config = options.config; - this.abi = options.abi; - this.tokenComputer = new tokens_1.TokenComputer(); - this.dataArgsBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); - } - createTransactionForDeploy(options) { - const nativeTransferAmount = options.nativeTransferAmount ?? 0n; - const isUpgradeable = options.isUpgradeable ?? true; - const isReadable = options.isReadable ?? true; - const isPayable = options.isPayable ?? false; - const isPayableBySmartContract = options.isPayableBySmartContract ?? true; - const args = options.arguments || []; - const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); - const dataParts = [utils_codec_1.byteArrayToHex(options.bytecode), utils_codec_1.byteArrayToHex(constants_1.VM_TYPE_WASM_VM), metadata.toString()]; - const endpoint = this.abi?.constructorDefinition; - const preparedArgs = this.argsToDataParts(args, endpoint); - dataParts.push(...preparedArgs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.CONTRACT_DEPLOY_ADDRESS), - dataParts, - gasLimit: options.gasLimit, - addDataMovementGas: false, - amount: nativeTransferAmount - }).build(); - } - createTransactionForExecute(options) { - const args = options.arguments || []; - const tokenTransfer = options.tokenTransfers || []; - const nativeTransferAmount = options.nativeTransferAmount ?? 0n; - const numberOfTokens = tokenTransfer.length; - if (nativeTransferAmount && numberOfTokens) { - throw new errors_1.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)"); - } - let receiver = options.contract; - let dataParts = []; - if (numberOfTokens === 1) { - const transfer = tokenTransfer[0]; - if (this.tokenComputer.isFungible(transfer.token)) { - dataParts = this.dataArgsBuilder.buildDataPartsForESDTTransfer(transfer); - } else { - dataParts = this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); - receiver = options.sender; - } - } else if (numberOfTokens > 1) { - dataParts = this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(receiver, tokenTransfer); - receiver = options.sender; - } - dataParts.push(dataParts.length ? utils_codec_1.utf8ToHex(options.function) : options.function); - const endpoint = this.abi?.getEndpoint(options.function); - const preparedArgs = this.argsToDataParts(args, endpoint); - dataParts.push(...preparedArgs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver, - dataParts, - gasLimit: options.gasLimit, - addDataMovementGas: false, - amount: nativeTransferAmount - }).build(); - } - createTransactionForUpgrade(options) { - const nativeTransferAmount = options.nativeTransferAmount ?? 0n; - const isUpgradeable = options.isUpgradeable ?? true; - const isReadable = options.isReadable ?? true; - const isPayable = options.isPayable ?? false; - const isPayableBySmartContract = options.isPayableBySmartContract ?? true; - const args = options.arguments || []; - const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); - const dataParts = ["upgradeContract", utils_codec_1.byteArrayToHex(options.bytecode), metadata.toString()]; - const endpoint = this.getEndpointForUpgrade(); - const preparedArgs = this.argsToDataParts(args, endpoint); - dataParts.push(...preparedArgs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.contract, - dataParts, - gasLimit: options.gasLimit, - addDataMovementGas: false, - amount: nativeTransferAmount - }).build(); - } - getEndpointForUpgrade() { - if (!this.abi) { - return void 0; - } - try { - return this.abi.getEndpoint("upgrade"); - } catch (error) { - logger_1.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."); - return this.abi.constructorDefinition; - } - } - createTransactionForClaimingDeveloperRewards(options) { - const dataParts = ["ClaimDeveloperRewards"]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.contract, - dataParts, - gasLimit: this.config.gasLimitClaimDeveloperRewards, - addDataMovementGas: false - }).build(); - } - createTransactionForChangingOwnerAddress(options) { - const dataParts = ["ChangeOwnerAddress", address_1.Address.fromBech32(options.newOwner.bech32()).toHex()]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.contract, - dataParts, - gasLimit: this.config.gasLimitChangeOwnerAddress, - addDataMovementGas: false - }).build(); - } - argsToDataParts(args, endpoint) { - if (endpoint) { - const typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args, endpoint); - return new smartcontracts_1.ArgSerializer().valuesToStrings(typedArgs); - } - if (this.areArgsOfTypedValue(args)) { - return new smartcontracts_1.ArgSerializer().valuesToStrings(args); - } - throw new errors_1.Err("Can't convert args to TypedValues"); - } - areArgsOfTypedValue(args) { - for (const arg of args) { - if (!arg.belongsToTypesystem) { - return false; - } - } - return true; - } - }; - exports2.SmartContractTransactionsFactory = SmartContractTransactionsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js -var require_tokenManagementTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenManagementTransactionsFactory = void 0; - var address_1 = require_address(); - var constants_1 = require_constants(); - var logger_1 = require_logger(); - var smartcontracts_1 = require_smartcontracts(); - var transactionBuilder_1 = require_transactionBuilder(); - var TokenManagementTransactionsFactory2 = class { - constructor(options) { - this.config = options.config; - this.argSerializer = new smartcontracts_1.ArgSerializer(); - this.trueAsString = "true"; - this.falseAsString = "false"; - } - createTransactionForIssuingFungible(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.BigUIntValue(options.initialSupply), - new smartcontracts_1.BigUIntValue(options.numDecimals), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["issue", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForIssuingSemiFungible(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canTransferNFTCreateRole"), - new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["issueSemiFungible", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForIssuingNonFungible(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canTransferNFTCreateRole"), - new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["issueNonFungible", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForRegisteringMetaESDT(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.BigUIntValue(options.numDecimals), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canTransferNFTCreateRole"), - new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["registerMetaESDT", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForRegisteringAndSettingRoles(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const dataParts = [ - "registerAndSetAllRoles", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.StringValue(options.tokenType), - new smartcontracts_1.BigUIntValue(options.numDecimals) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForSettingBurnRoleGlobally(options) { - const dataParts = [ - "setBurnRoleGlobally", - ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitToggleBurnRoleGlobally, - addDataMovementGas: true - }).build(); - } - createTransactionForUnsettingBurnRoleGlobally(options) { - const dataParts = [ - "unsetBurnRoleGlobally", - ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitToggleBurnRoleGlobally, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingSpecialRoleOnFungibleToken(options) { - const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; - options.addRoleLocalMint ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalMint")) : 0; - options.addRoleLocalBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalBurn")) : 0; - options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; - const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitSetSpecialRole, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingSpecialRoleOnSemiFungibleToken(options) { - const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; - options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; - options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; - options.addRoleNFTAddQuantity ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddQuantity")) : 0; - options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; - const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitSetSpecialRole, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingSpecialRoleOnMetaESDT(options) { - return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(options); - } - createTransactionForSettingSpecialRoleOnNonFungibleToken(options) { - const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; - options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; - options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; - options.addRoleNFTUpdateAttributes ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTUpdateAttributes")) : 0; - options.addRoleNFTAddURI ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddURI")) : 0; - options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; - const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitSetSpecialRole, - addDataMovementGas: true - }).build(); - } - createTransactionForCreatingNFT(options) { - const dataParts = [ - "ESDTNFTCreate", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.initialQuantity), - new smartcontracts_1.StringValue(options.name), - new smartcontracts_1.BigUIntValue(options.royalties), - new smartcontracts_1.StringValue(options.hash), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)), - ...options.uris.map((uri) => new smartcontracts_1.StringValue(uri)) - ]) - ]; - const nftData = options.name + options.hash + options.attributes + options.uris.join(""); - const storageGasLimit = this.config.gasLimitStorePerByte + BigInt(nftData.length); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftCreate + storageGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForPausing(options) { - const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)])]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitPausing, - addDataMovementGas: true - }).build(); - } - createTransactionForUnpausing(options) { - const dataParts = [ - "unPause", - ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitPausing, - addDataMovementGas: true - }).build(); - } - createTransactionForFreezing(options) { - const dataParts = [ - "freeze", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.AddressValue(options.user) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitFreezing, - addDataMovementGas: true - }).build(); - } - createTransactionForUnfreezing(options) { - const dataParts = [ - "UnFreeze", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.AddressValue(options.user) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitFreezing, - addDataMovementGas: true - }).build(); - } - createTransactionForWiping(options) { - const dataParts = [ - "wipe", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.AddressValue(options.user) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitWiping, - addDataMovementGas: true - }).build(); - } - createTransactionForLocalMint(options) { - const dataParts = [ - "ESDTLocalMint", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.supplyToMint) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtLocalMint, - addDataMovementGas: true - }).build(); - } - createTransactionForLocalBurning(options) { - const dataParts = [ - "ESDTLocalBurn", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.supplyToBurn) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtLocalBurn, - addDataMovementGas: true - }).build(); - } - createTransactionForUpdatingAttributes(options) { - const dataParts = [ - "ESDTNFTUpdateAttributes", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.tokenNonce), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftUpdateAttributes, - addDataMovementGas: true - }).build(); - } - createTransactionForAddingQuantity(options) { - const dataParts = [ - "ESDTNFTAddQuantity", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.tokenNonce), - new smartcontracts_1.BigUIntValue(options.quantityToAdd) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftAddQuantity, - addDataMovementGas: true - }).build(); - } - createTransactionForBurningQuantity(options) { - const dataParts = [ - "ESDTNFTBurn", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.tokenNonce), - new smartcontracts_1.BigUIntValue(options.quantityToBurn) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftBurn, - addDataMovementGas: true - }).build(); - } - notifyAboutUnsettingBurnRoleGlobally() { - logger_1.Logger.info(` +`)}};ce.ErrContractHasNoAddress=$w;var Yw=class extends Ce{constructor(e){super(e)}};ce.ErrMock=Yw;var Jw=class extends Ce{constructor(e){super(e)}};ce.ErrTypingSystem=Jw;var Xw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on struct ${r}`)}};ce.ErrMissingFieldOnStruct=Xw;var Zw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on enum ${r}`)}};ce.ErrMissingFieldOnEnum=Zw;var ev=class extends Ce{constructor(e){super(`cannot parse contract results: ${e}`)}};ce.ErrCannotParseContractResults=ev;var tv=class extends Ce{constructor(e,r){super(`cannot parse outcome of transaction ${e}: ${r}`)}};ce.ErrCannotParseTransactionOutcome=tv;var rv=class extends Ce{constructor(e){super(e)}};ce.ErrCodec=rv;var nv=class extends Ce{constructor(e){super(e)}};ce.ErrContractInteraction=nv;var iv=class extends Ce{constructor(){super("Method not yet implemented")}};ce.ErrNotImplemented=iv;var sv=class extends Ce{constructor(){super("invalid arguments for relayed v1 builder")}};ce.ErrInvalidRelayedV1BuilderArguments=sv;var ov=class extends Ce{constructor(){super("invalid arguments for relayed v2 builder")}};ce.ErrInvalidRelayedV2BuilderArguments=ov;var av=class extends Ce{constructor(){super("gas limit must be 0 for the inner transaction for relayed v2")}};ce.ErrGasLimitShouldBe0ForInnerTransaction=av;var uv=class extends Ce{constructor(){super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`.")}};ce.ErrIsCompletedFieldIsMissingOnTransaction=uv;var cv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidTokenIdentifier=cv;var lv=class extends Ce{constructor(e){super(e)}};ce.ErrBadUsage=lv;var fv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidInnerTransaction=fv;var hv=class extends Ce{constructor(e){super(e)}};ce.ErrParseTransactionOutcome=hv});var Ca=B(xn=>{"use strict";h();var Wk=xn&&xn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xn,"__esModule",{value:!0});xn.TokenPayment=xn.TokenComputer=xn.TokenTransfer=xn.Token=void 0;var _a=Wk((rr(),_e(fr))),Du=Ie(),V3="EGLD",k3=18;_a.default.set({ROUNDING_MODE:1});var Hd=class{constructor(e){this.identifier=e.identifier,this.nonce=e.nonce||0n}};xn.Token=Hd;var Gd=class t{constructor(e){if(this.isLegacyTokenTransferOptions(e)){let r=new _a.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new Du.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0,this.token=new Hd({identifier:e.tokenIdentifier,nonce:BigInt(e.nonce)}),this.amount=BigInt(this.amountAsBigInteger.toFixed(0))}else this.token=e.token,this.amount=e.amount,this.tokenIdentifier=e.token.identifier,this.nonce=Number(e.token.nonce),this.amountAsBigInteger=new _a.default(this.amount.toString()),this.numDecimals=0}isLegacyTokenTransferOptions(e){return e.tokenIdentifier!==void 0}static egldFromAmount(e){let r=new _a.default(e).shiftedBy(k3).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:V3,nonce:0,amountAsBigInteger:e,numDecimals:k3})}static fungibleFromAmount(e,r,n){let i=new _a.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new _a.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amount.toString()}valueOf(){return new _a.default(this.amount.toString())}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.token.identifier==V3}isFungible(){return this.token.nonce==0n}};xn.TokenTransfer=Gd;var dv=class{constructor(){}isFungible(e){return e.nonce===0n}extractNonceFromExtendedIdentifier(e){let r=e.split("-");if(this.checkIfExtendedIdentifierWasProvided(r),this.checkLengthOfRandomSequence(r[1]),r.length==2)return 0;let n=p.Buffer.from(r[2],"hex");return $k(n)}extractIdentifierFromExtendedIdentifier(e){let r=e.split("-");return this.checkIfExtendedIdentifierWasProvided(r),this.ensureTokenTickerValidity(r[0]),this.checkLengthOfRandomSequence(r[1]),r[0]+"-"+r[1]}checkIfExtendedIdentifierWasProvided(e){if(e.length<2||e.length>3)throw new Du.ErrInvalidTokenIdentifier("Invalid extended token identifier provided")}checkLengthOfRandomSequence(e){if(e.length!==6)throw new Du.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length")}ensureTokenTickerValidity(e){if(e.length<3||e.length>10)throw new Du.ErrInvalidTokenIdentifier("The token ticker should be between 3 and 10 characters");if(!e.match(/^[a-zA-Z0-9]+$/))throw new Du.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters");if(e!=e.toUpperCase())throw new Du.ErrInvalidTokenIdentifier("The token ticker should be upper case")}};xn.TokenComputer=dv;function $k(t){return t.readUIntBE(0,t.length)}var gv=class extends Gd{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};xn.TokenPayment=gv});var hr=B(Ae=>{"use strict";h();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.UNKNOWN_SIGNER=Ae.SDK_JS_SIGNER=Ae.METACHAIN_ID=Ae.WasmVirtualMachine=Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=Ae.BECH32_ADDRESS_LENGTH=Ae.HEX_TRANSACTION_HASH_LENGTH=Ae.MESSAGE_PREFIX=Ae.DEFAULT_MESSAGE_VERSION=Ae.ESDT_CONTRACT_ADDRESS=Ae.DEFAULT_HRP=Ae.DELEGATION_MANAGER_SC_ADDRESS=Ae.CONTRACT_DEPLOY_ADDRESS=Ae.VM_TYPE_WASM_VM=Ae.ARGUMENTS_SEPARATOR=Ae.ESDT_TRANSFER_VALUE=Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_GAS_LIMIT=Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=Ae.TRANSACTION_VERSION_DEFAULT=Ae.TRANSACTION_OPTIONS_TX_GUARDED=Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=Ae.TRANSACTION_OPTIONS_DEFAULT=Ae.TRANSACTION_MIN_GAS_PRICE=void 0;Ae.TRANSACTION_MIN_GAS_PRICE=1e9;Ae.TRANSACTION_OPTIONS_DEFAULT=0;Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Ae.TRANSACTION_OPTIONS_TX_GUARDED=2;Ae.TRANSACTION_VERSION_DEFAULT=2;Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=2;Ae.ESDT_TRANSFER_GAS_LIMIT=5e5;Ae.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Ae.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Ae.ESDT_TRANSFER_VALUE="0";Ae.ARGUMENTS_SEPARATOR="@";Ae.VM_TYPE_WASM_VM=new Uint8Array([5,0]);Ae.CONTRACT_DEPLOY_ADDRESS="erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu";Ae.DELEGATION_MANAGER_SC_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6";Ae.DEFAULT_HRP="erd";Ae.ESDT_CONTRACT_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u";Ae.DEFAULT_MESSAGE_VERSION=1;Ae.MESSAGE_PREFIX=`Elrond Signed Message: +`;Ae.HEX_TRANSACTION_HASH_LENGTH=64;Ae.BECH32_ADDRESS_LENGTH=62;Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=3;Ae.WasmVirtualMachine="0500";Ae.METACHAIN_ID=4294967295;Ae.SDK_JS_SIGNER="sdk-js";Ae.UNKNOWN_SIGNER="unknown"});var oo=B(xa=>{"use strict";h();Object.defineProperty(xa,"__esModule",{value:!0});xa.Logger=xa.LogLevel=void 0;var Na;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Na=xa.LogLevel||(xa.LogLevel={}));var jd=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Na.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Na.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Na.Error||console.error(e,r)}};xa.Logger=jd;jd.logLevel=Na.Debug});var $l=B(On=>{"use strict";h();var Yk=On&&On.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Jk=On&&On.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xk=On&&On.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yk(e,t,r);return Jk(e,t),e};Object.defineProperty(On,"__esModule",{value:!0});On.TransactionOptions=On.TransactionVersion=void 0;var gi=hr(),H3=Xk(Ie()),pv=class t{constructor(e){if(e=Number(e),e<1)throw new H3.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}valueOf(){return this.value}};On.TransactionVersion=pv;var mv=class t{constructor(e){if(e=Number(e),e<0)throw new H3.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(gi.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=gi.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&gi.TRANSACTION_OPTIONS_TX_HASH_SIGN)==gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&gi.TRANSACTION_OPTIONS_TX_GUARDED)==gi.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=gi.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};On.TransactionOptions=mv});var wv=B((tpe,z3)=>{"use strict";h();var Qd="qpzry9x8gf2tvdw0s3jn54khce6mua7l",yv={};for(Yl=0;Yl>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function G3(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=G3(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Pu(n)^o,i+=Qd.charAt(o)}for(s=0;s<6;++s)n=Pu(n);for(n^=1,s=0;s<6;++s){var u=n>>(5-s)*5&31;i+=Qd.charAt(u)}return i}function j3(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var u=G3(s);if(typeof u=="string")return u;for(var a=[],c=0;c=o.length)&&a.push(d)}return u!==1?"Invalid checksum for "+t:{prefix:s,words:a}}function eH(){var t=j3.apply(null,arguments);if(typeof t=="object")return t}function tH(t){var e=j3.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function Kd(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<{"use strict";h();var oH=Nt&&Nt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),aH=Nt&&Nt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uH=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oH(e,t,r);return aH(e,t),e},cH=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.addressToHex=Nt.bigIntToHex=Nt.byteArrayToHex=Nt.boolToHex=Nt.utf8ToHex=Nt.zeroPadStringIfOddLength=Nt.isPaddedHex=Nt.numberToPaddedHex=void 0;var lH=cH((rr(),_e(fr))),fH=Ve(),hH=uH(Bu());function dH(t){let e;typeof t=="bigint"||typeof t=="number"?e=t:e=new lH.default(t);let r=e.toString(16);return Wd(r)}Nt.numberToPaddedHex=dH;function gH(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Nt.isPaddedHex=gH;function Wd(t){return t=t||"",t.length%2==1?"0"+t:t}Nt.zeroPadStringIfOddLength=Wd;function Q3(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.utf8ToHex=Q3;function pH(t){return Q3(t.toString())}Nt.boolToHex=pH;function mH(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.byteArrayToHex=mH;function yH(t){return t==0?"":hH.getHexMagnitudeOfBigInt(t)}Nt.bigIntToHex=yH;function wH(t){return fH.Address.fromBech32(t.toString()).pubkey().toString("hex")}Nt.addressToHex=wH});var Bu=B(nr=>{"use strict";h();var vH=nr&&nr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nr,"__esModule",{value:!0});nr.prependByteToBuffer=nr.flipBufferBitsInPlace=nr.getHexMagnitudeOfBigInt=nr.bigIntToBuffer=nr.bufferToBigInt=nr.cloneBuffer=nr.isMsbZero=nr.isMsbOne=void 0;var vv=vH((rr(),_e(fr))),AH=Ru();function K3(t,e=0){return t[e]>>7==1}nr.isMsbOne=K3;function EH(t,e=0){return!K3(t,e)}nr.isMsbZero=EH;function bH(t){let e=p.Buffer.alloc(t.length);return t.copy(e),e}nr.cloneBuffer=bH;function SH(t){let e=t.toString("hex");return new vv.default(`0x${e}`,16)}nr.bufferToBigInt=SH;function IH(t){let e=W3(t);return p.Buffer.from(e,"hex")}nr.bigIntToBuffer=IH;function W3(t){return t=new vv.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new vv.default(-1))),AH.numberToPaddedHex(t)):""}nr.getHexMagnitudeOfBigInt=W3;function TH(t){for(let e=0;e{"use strict";h();var CH=Lt&&Lt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NH=Lt&&Lt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$3=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&CH(e,t,r);return NH(e,t),e},xH=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.bufferToHex=Lt.addressToHex=Lt.bigIntToHex=Lt.utf8ToHex=Lt.bigIntToBuffer=Lt.bufferToBigInt=Lt.stringToBuffer=void 0;var OH=xH((rr(),_e(fr))),Y3=$3(Bu()),DH=$3(Ru());function PH(t){return p.Buffer.from(t)}Lt.stringToBuffer=PH;function RH(t){return t.length==0?new OH.default(0):Y3.bufferToBigInt(t)}Lt.bufferToBigInt=RH;function BH(t){return t==0?p.Buffer.from([]):Y3.bigIntToBuffer(t)}Lt.bigIntToBuffer=BH;var Av=Ru();Object.defineProperty(Lt,"utf8ToHex",{enumerable:!0,get:function(){return Av.utf8ToHex}});Object.defineProperty(Lt,"bigIntToHex",{enumerable:!0,get:function(){return Av.bigIntToHex}});Object.defineProperty(Lt,"addressToHex",{enumerable:!0,get:function(){return Av.addressToHex}});function MH(t){let e=t.toString("hex");return DH.zeroPadStringIfOddLength(e)}Lt.bufferToHex=MH});var Ds=B((cpe,Ev)=>{"use strict";h();var Mu=typeof Reflect=="object"?Reflect:null,J3=Mu&&typeof Mu.apply=="function"?Mu.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Yd;Mu&&typeof Mu.ownKeys=="function"?Yd=Mu.ownKeys:Object.getOwnPropertySymbols?Yd=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Yd=function(e){return Object.getOwnPropertyNames(e)};function LH(t){console&&console.warn&&console.warn(t)}var Z3=Number.isNaN||function(e){return e!==e};function _t(){_t.init.call(this)}Ev.exports=_t;Ev.exports.once=VH;_t.EventEmitter=_t;_t.prototype._events=void 0;_t.prototype._eventsCount=0;_t.prototype._maxListeners=void 0;var X3=10;function Jd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_t,"defaultMaxListeners",{enumerable:!0,get:function(){return X3},set:function(t){if(typeof t!="number"||t<0||Z3(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");X3=t}});_t.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_t.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Z3(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function eN(t){return t._maxListeners===void 0?_t.defaultMaxListeners:t._maxListeners}_t.prototype.getMaxListeners=function(){return eN(this)};_t.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var u=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw u.context=o,u}var a=s[e];if(a===void 0)return!1;if(typeof a=="function")J3(a,this,r);else for(var c=a.length,f=sN(a,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=o.length,LH(u)}return t}_t.prototype.addListener=function(e,r){return tN(this,e,r,!1)};_t.prototype.on=_t.prototype.addListener;_t.prototype.prependListener=function(e,r){return tN(this,e,r,!0)};function FH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function rN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=FH.bind(n);return i.listener=r,n.wrapFn=i,i}_t.prototype.once=function(e,r){return Jd(r),this.on(e,rN(this,e,r)),this};_t.prototype.prependOnceListener=function(e,r){return Jd(r),this.prependListener(e,rN(this,e,r)),this};_t.prototype.removeListener=function(e,r){var n,i,s,o,u;if(Jd(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){u=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():UH(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||r)}return this};_t.prototype.off=_t.prototype.removeListener;_t.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function nN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?qH(i):sN(i,i.length)}_t.prototype.listeners=function(e){return nN(this,e,!0)};_t.prototype.rawListeners=function(e){return nN(this,e,!1)};_t.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):iN.call(t,e)};_t.prototype.listenerCount=iN;function iN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_t.prototype.eventNames=function(){return this._eventsCount>0?Yd(this._events):[]};function sN(t,e){for(var r=new Array(e),n=0;n{h();aN.exports=Ds().EventEmitter});var Sv=B(()=>{h()});var dN=B((mpe,hN)=>{"use strict";h();function uN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function cN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Xd.alloc(0);for(var n=Xd.allocUnsafe(r>>>0),i=this.head,s=0;i;)$H(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(u===o.length?s+=o:s+=o.slice(0,r),r-=u,r===0){u===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(u));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Xd.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,u=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,u),r-=u,r===0){u===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(u));break}++s}return this.length-=s,n}},{key:WH,value:function(r,n){return Iv(this,cN(cN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var _v=B((wpe,pN)=>{"use strict";h();function YH(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,I.default.nextTick(Tv,this,t)):I.default.nextTick(Tv,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?I.default.nextTick(Zd,r):(r._writableState.errorEmitted=!0,I.default.nextTick(gN,r,s)):I.default.nextTick(gN,r,s):e?(I.default.nextTick(Zd,r),e(s)):I.default.nextTick(Zd,r)}),this)}function gN(t,e){Tv(t,e),Zd(t)}function Zd(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function JH(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Tv(t,e){t.emit("error",e)}function XH(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}pN.exports={destroy:YH,undestroy:JH,errorOrDestroy:XH}});var Oa=B((Ape,wN)=>{"use strict";h();function ZH(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var yN={};function Dn(t,e,r){r||(r=Error);function n(s,o,u){return typeof e=="string"?e:e(s,o,u)}var i=function(s){ZH(o,s);function o(u,a,c){return s.call(this,n(u,a,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,yN[t]=i}function mN(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function eG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function tG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function rG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}Dn("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);Dn("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&eG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(tG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(mN(e,"type"));else{var s=rG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(mN(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);Dn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");Dn("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});Dn("ERR_STREAM_PREMATURE_CLOSE","Premature close");Dn("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});Dn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");Dn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");Dn("ERR_STREAM_WRITE_AFTER_END","write after end");Dn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Dn("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);Dn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");wN.exports.codes=yN});var Cv=B((bpe,vN)=>{"use strict";h();var nG=Oa().codes.ERR_INVALID_OPT_VALUE;function iG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function sG(t,e,r,n){var i=iG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new nG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}vN.exports={getHighWaterMark:sG}});var Lu=B((Ipe,Nv)=>{h();typeof Object.create=="function"?Nv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Nv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var EN=B((_pe,AN)=>{h();AN.exports=oG;function oG(t,e){if(xv("noDeprecation"))return t;var r=!1;function n(){if(!r){if(xv("throwDeprecation"))throw new Error(e);xv("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function xv(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var Pv=B((Npe,CN)=>{"use strict";h();CN.exports=Gt;function SN(t){var e=this;this.next=null,this.entry=null,this.finish=function(){RG(e,t)}}var Fu;Gt.WritableState=Xl;var aG={deprecate:EN()},IN=bv(),tg=io().Buffer,uG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cG(t){return tg.from(t)}function lG(t){return tg.isBuffer(t)||t instanceof uG}var Dv=_v(),fG=Cv(),hG=fG.getHighWaterMark,ao=Oa().codes,dG=ao.ERR_INVALID_ARG_TYPE,gG=ao.ERR_METHOD_NOT_IMPLEMENTED,pG=ao.ERR_MULTIPLE_CALLBACK,mG=ao.ERR_STREAM_CANNOT_PIPE,yG=ao.ERR_STREAM_DESTROYED,wG=ao.ERR_STREAM_NULL_VALUES,vG=ao.ERR_STREAM_WRITE_AFTER_END,AG=ao.ERR_UNKNOWN_ENCODING,Uu=Dv.errorOrDestroy;Lu()(Gt,IN);function EG(){}function Xl(t,e,r){Fu=Fu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof Fu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=hG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){NG(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new SN(this)}Xl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(Xl.prototype,"buffer",{get:aG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var eg;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(eg=Function.prototype[Symbol.hasInstance],Object.defineProperty(Gt,Symbol.hasInstance,{value:function(e){return eg.call(this,e)?!0:this!==Gt?!1:e&&e._writableState instanceof Xl}})):eg=function(e){return e instanceof this};function Gt(t){Fu=Fu||Da();var e=this instanceof Fu;if(!e&&!eg.call(Gt,this))return new Gt(t);this._writableState=new Xl(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),IN.call(this)}Gt.prototype.pipe=function(){Uu(this,new mG)};function bG(t,e){var r=new vG;Uu(t,r),I.default.nextTick(e,r)}function SG(t,e,r,n){var i;return r===null?i=new wG:typeof r!="string"&&!e.objectMode&&(i=new dG("chunk",["string","Buffer"],r)),i?(Uu(t,i),I.default.nextTick(n,i),!1):!0}Gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&lG(t);return s&&!tg.isBuffer(t)&&(t=cG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=EG),n.ending?bG(this,r):(s||SG(this,n,t,r))&&(n.pendingcb++,i=TG(this,n,s,t,e,r)),i};Gt.prototype.cork=function(){this._writableState.corked++};Gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&TN(this,t))};Gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new AG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function IG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=tg.from(e,r)),e}Object.defineProperty(Gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function TG(t,e,r,n,i,s){if(!r){var o=IG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length{"use strict";h();var BG=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};xN.exports=Li;var NN=Mv(),Bv=Pv();Lu()(Li,NN);for(Rv=BG(Bv.prototype),rg=0;rg{h();var ig=io(),Fi=ig.Buffer;function ON(t,e){for(var r in t)e[r]=t[r]}Fi.from&&Fi.alloc&&Fi.allocUnsafe&&Fi.allocUnsafeSlow?DN.exports=ig:(ON(ig,Lv),Lv.Buffer=Pa);function Pa(t,e,r){return Fi(t,e,r)}Pa.prototype=Object.create(Fi.prototype);ON(Fi,Pa);Pa.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Fi(t,e,r)};Pa.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Fi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Pa.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fi(t)};Pa.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ig.SlowBuffer(t)}});var qv=B(BN=>{"use strict";h();var Uv=PN().Buffer,RN=Uv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function FG(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function UG(t){var e=FG(t);if(typeof e!="string"&&(Uv.isEncoding===RN||!RN(t)))throw new Error("Unknown encoding: "+t);return e||t}BN.StringDecoder=Zl;function Zl(t){this.encoding=UG(t);var e;switch(this.encoding){case"utf16le":this.text=jG,this.end=zG,e=4;break;case"utf8":this.fillLast=kG,e=4;break;case"base64":this.text=QG,this.end=KG,e=3;break;default:this.write=WG,this.end=$G;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Uv.allocUnsafe(e)}Zl.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function qG(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function VG(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function kG(t){var e=this.lastTotal-this.lastNeed,r=VG(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function HG(t,e){var r=qG(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function GG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function jG(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function zG(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function QG(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function KG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function WG(t){return t.toString(this.encoding)}function $G(t){return t&&t.length?this.write(t):""}});var sg=B((Mpe,FN)=>{"use strict";h();var MN=Oa().codes.ERR_STREAM_PREMATURE_CLOSE;function YG(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";h();var og;function uo(t,e,r){return e=ZG(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ZG(t){var e=ej(t,"string");return typeof e=="symbol"?e:String(e)}function ej(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var tj=sg(),co=Symbol("lastResolve"),Ra=Symbol("lastReject"),ef=Symbol("error"),ag=Symbol("ended"),Ba=Symbol("lastPromise"),Vv=Symbol("handlePromise"),Ma=Symbol("stream");function lo(t,e){return{value:t,done:e}}function rj(t){var e=t[co];if(e!==null){var r=t[Ma].read();r!==null&&(t[Ba]=null,t[co]=null,t[Ra]=null,e(lo(r,!1)))}}function nj(t){I.default.nextTick(rj,t)}function ij(t,e){return function(r,n){t.then(function(){if(e[ag]){r(lo(void 0,!0));return}e[Vv](r,n)},n)}}var sj=Object.getPrototypeOf(function(){}),oj=Object.setPrototypeOf((og={get stream(){return this[Ma]},next:function(){var e=this,r=this[ef];if(r!==null)return Promise.reject(r);if(this[ag])return Promise.resolve(lo(void 0,!0));if(this[Ma].destroyed)return new Promise(function(o,u){I.default.nextTick(function(){e[ef]?u(e[ef]):o(lo(void 0,!0))})});var n=this[Ba],i;if(n)i=new Promise(ij(n,this));else{var s=this[Ma].read();if(s!==null)return Promise.resolve(lo(s,!1));i=new Promise(this[Vv])}return this[Ba]=i,i}},uo(og,Symbol.asyncIterator,function(){return this}),uo(og,"return",function(){var e=this;return new Promise(function(r,n){e[Ma].destroy(null,function(i){if(i){n(i);return}r(lo(void 0,!0))})})}),og),sj),aj=function(e){var r,n=Object.create(oj,(r={},uo(r,Ma,{value:e,writable:!0}),uo(r,co,{value:null,writable:!0}),uo(r,Ra,{value:null,writable:!0}),uo(r,ef,{value:null,writable:!0}),uo(r,ag,{value:e._readableState.endEmitted,writable:!0}),uo(r,Vv,{value:function(s,o){var u=n[Ma].read();u?(n[Ba]=null,n[co]=null,n[Ra]=null,s(lo(u,!1))):(n[co]=s,n[Ra]=o)},writable:!0}),r));return n[Ba]=null,tj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Ra];s!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,s(i)),n[ef]=i;return}var o=n[co];o!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,o(lo(void 0,!0))),n[ag]=!0}),e.on("readable",nj.bind(null,n)),n};UN.exports=aj});var kN=B((qpe,VN)=>{h();VN.exports=function(){throw new Error("Readable.from is not available in the browser")}});var Mv=B((Hpe,JN)=>{"use strict";h();JN.exports=Fe;var qu;Fe.ReadableState=zN;var kpe=Ds().EventEmitter,jN=function(e,r){return e.listeners(r).length},rf=bv(),ug=io().Buffer,uj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cj(t){return ug.from(t)}function lj(t){return ug.isBuffer(t)||t instanceof uj}var kv=Sv(),Ne;kv&&kv.debuglog?Ne=kv.debuglog("stream"):Ne=function(){};var fj=dN(),Wv=_v(),hj=Cv(),dj=hj.getHighWaterMark,cg=Oa().codes,gj=cg.ERR_INVALID_ARG_TYPE,pj=cg.ERR_STREAM_PUSH_AFTER_EOF,mj=cg.ERR_METHOD_NOT_IMPLEMENTED,yj=cg.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Vu,Hv,Gv;Lu()(Fe,rf);var tf=Wv.errorOrDestroy,jv=["error","close","destroy","pause","resume"];function wj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function zN(t,e,r){qu=qu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof qu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=dj(this,t,"readableHighWaterMark",r),this.buffer=new fj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Vu||(Vu=qv().StringDecoder),this.decoder=new Vu(t.encoding),this.encoding=t.encoding)}function Fe(t){if(qu=qu||Da(),!(this instanceof Fe))return new Fe(t);var e=this instanceof qu;this._readableState=new zN(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),rf.call(this)}Object.defineProperty(Fe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Fe.prototype.destroy=Wv.destroy;Fe.prototype._undestroy=Wv.undestroy;Fe.prototype._destroy=function(t,e){e(t)};Fe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=ug.from(t,e),e=""),n=!0),QN(this,t,e,!1,n)};Fe.prototype.unshift=function(t){return QN(this,t,null,!0,!1)};function QN(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Ej(t,s);else{var o;if(i||(o=vj(s,e)),o)tf(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==ug.prototype&&(e=cj(e)),n)s.endEmitted?tf(t,new yj):zv(t,s,e,!0);else if(s.ended)tf(t,new pj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?zv(t,s,e,!1):Kv(t,s)):zv(t,s,e,!1)}else n||(s.reading=!1,Kv(t,s))}return!s.ended&&(s.length=HN?t=HN:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function GN(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=Aj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}Fe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Qv(this):lg(this),null;if(t=GN(t,e),t===0&&e.ended)return e.length===0&&Qv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=$N(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Qv(this)),i!==null&&this.emit("data",i),i};function Ej(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?lg(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,KN(t)))}}function lg(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,I.default.nextTick(KN,t))}function KN(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,$v(t)}function Kv(t,e){e.readingMore||(e.readingMore=!0,I.default.nextTick(bj,t,e))}function bj(t,e){for(;!e.reading&&!e.ended&&(e.length1&&YN(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function w(R){Ne("onerror",R),x(),t.removeListener("error",w),jN(t,"error")===0&&tf(t,R)}wj(t,"error",w);function A(){t.removeListener("finish",T),x()}t.once("close",A);function T(){Ne("onfinish"),t.removeListener("close",A),x()}t.once("finish",T);function x(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Sj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&jN(t,"data")&&(r.flowing=!0,$v(t))}}Fe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?lg(this):n.reading||I.default.nextTick(Ij,this)),r};Fe.prototype.addListener=Fe.prototype.on;Fe.prototype.removeListener=function(t,e){var r=rf.prototype.removeListener.call(this,t,e);return t==="readable"&&I.default.nextTick(WN,this),r};Fe.prototype.removeAllListeners=function(t){var e=rf.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&I.default.nextTick(WN,this),e};function WN(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Ij(t){Ne("readable nexttick read 0"),t.read(0)}Fe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Tj(this,t)),t.paused=!1,this};function Tj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,I.default.nextTick(_j,t,e))}function _j(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),$v(t),e.flowing&&!e.reading&&t.read(0)}Fe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function $v(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}Fe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var u=e.push(o);u||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(u){return function(){return t[u].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Qv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,I.default.nextTick(Cj,e,t))}function Cj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(Fe.from=function(t,e){return Gv===void 0&&(Gv=kN()),Gv(Fe,t,e)});function YN(t,e){for(var r=0,n=t.length;r{"use strict";h();ZN.exports=Ps;var fg=Oa().codes,Nj=fg.ERR_METHOD_NOT_IMPLEMENTED,xj=fg.ERR_MULTIPLE_CALLBACK,Oj=fg.ERR_TRANSFORM_ALREADY_TRANSFORMING,Dj=fg.ERR_TRANSFORM_WITH_LENGTH_0,hg=Da();Lu()(Ps,hg);function Pj(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new xj);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";h();tx.exports=nf;var ex=Yv();Lu()(nf,ex);function nf(t){if(!(this instanceof nf))return new nf(t);ex.call(this,t)}nf.prototype._transform=function(t,e,r){r(null,t)}});var ax=B((Wpe,ox)=>{"use strict";h();var Jv;function Bj(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var sx=Oa().codes,Mj=sx.ERR_MISSING_ARGS,Lj=sx.ERR_STREAM_DESTROYED;function nx(t){if(t)throw t}function Fj(t){return t.setHeader&&typeof t.abort=="function"}function Uj(t,e,r,n){n=Bj(n);var i=!1;t.on("close",function(){i=!0}),Jv===void 0&&(Jv=sg()),Jv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Fj(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new Lj("pipe"))}}}function ix(t){t()}function qj(t,e){return t.pipe(e)}function Vj(t){return!t.length||typeof t[t.length-1]!="function"?nx:t.pop()}function kj(){for(var t=arguments.length,e=new Array(t),r=0;r0;return Uj(o,a,c,function(f){i||(i=f),f&&s.forEach(ix),!a&&(s.forEach(ix),n(i))})});return e.reduce(qj)}ox.exports=kj});var Xv=B((Pn,ux)=>{h();Pn=ux.exports=Mv();Pn.Stream=Pn;Pn.Readable=Pn;Pn.Writable=Pv();Pn.Duplex=Da();Pn.Transform=Yv();Pn.PassThrough=rx();Pn.finished=sg();Pn.pipeline=ax()});var fx=B((Jpe,lx)=>{h();var{Transform:Hj}=Xv();lx.exports=t=>class cx extends Hj{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new cx(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var gx=B((Zpe,dx)=>{h();var{Transform:Gj}=Xv();dx.exports=t=>class hx extends Gj{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new hx(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var mx=B((t0e,px)=>{h();var jj=fx(),zj=gx();px.exports=function(t){let e=jj(t),r=zj(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var vx=B(wx=>{h();var yx=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];wx.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],u=t[5]^t[15]^t[25]^t[35]^t[45],a=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],w=f^(i<<1|s>>>31),A=d^(s<<1|i>>>31),T=t[0]^w,x=t[1]^A,R=t[10]^w,V=t[11]^A,U=t[20]^w,Q=t[21]^A,L=t[30]^w,k=t[31]^A,H=t[40]^w,q=t[41]^A;w=r^(o<<1|u>>>31),A=n^(u<<1|o>>>31);let v=t[2]^w,C=t[3]^A,D=t[12]^w,F=t[13]^A,P=t[22]^w,l=t[23]^A,g=t[32]^w,y=t[33]^A,E=t[42]^w,S=t[43]^A;w=i^(a<<1|c>>>31),A=s^(c<<1|a>>>31);let _=t[4]^w,M=t[5]^A,N=t[14]^w,m=t[15]^A,O=t[24]^w,Y=t[25]^A,$=t[34]^w,b=t[35]^A,j=t[44]^w,z=t[45]^A;w=o^(f<<1|d>>>31),A=u^(d<<1|f>>>31);let W=t[6]^w,ie=t[7]^A,te=t[16]^w,ee=t[17]^A,se=t[26]^w,oe=t[27]^A,J=t[36]^w,ue=t[37]^A,wt=t[46]^w,vt=t[47]^A;w=a^(r<<1|n>>>31),A=c^(n<<1|r>>>31);let Ni=t[8]^w,At=t[9]^A,Et=t[18]^w,xi=t[19]^A,bt=t[28]^w,St=t[29]^A,Oi=t[38]^w,It=t[39]^A,Tt=t[48]^w,Di=t[49]^A,Qe=T,Ke=x,ri=V<<4|R>>>28,We=R<<4|V>>>28,$e=U<<3|Q>>>29,ni=Q<<3|U>>>29,Ye=k<<9|L>>>23,Je=L<<9|k>>>23,ii=H<<18|q>>>14,Xe=q<<18|H>>>14,Ze=v<<1|C>>>31,si=C<<1|v>>>31,et=F<<12|D>>>20,tt=D<<12|F>>>20,oi=P<<10|l>>>22,rt=l<<10|P>>>22,nt=y<<13|g>>>19,ai=g<<13|y>>>19,it=E<<2|S>>>30,st=S<<2|E>>>30,ui=M<<30|_>>>2,ot=_<<30|M>>>2,at=N<<6|m>>>26,ci=m<<6|N>>>26,ut=Y<<11|O>>>21,ct=O<<11|Y>>>21,li=$<<15|b>>>17,lt=b<<15|$>>>17,ft=z<<29|j>>>3,fi=j<<29|z>>>3,ht=W<<28|ie>>>4,dt=ie<<28|W>>>4,hi=ee<<23|te>>>9,gt=te<<23|ee>>>9,pt=se<<25|oe>>>7,vn=oe<<25|se>>>7,An=J<<21|ue>>>11,En=ue<<21|J>>>11,bn=vt<<24|wt>>>8,Sn=wt<<24|vt>>>8,In=Ni<<27|At>>>5,da=At<<27|Ni>>>5,ga=Et<<20|xi>>>12,pa=xi<<20|Et>>>12,ma=St<<7|bt>>>25,ya=bt<<7|St>>>25,wa=Oi<<8|It>>>24,va=It<<8|Oi>>>24,Aa=Tt<<14|Di>>>18,Ea=Di<<14|Tt>>>18;t[0]=Qe^~et&ut,t[1]=Ke^~tt&ct,t[10]=ht^~ga&$e,t[11]=dt^~pa&ni,t[20]=Ze^~at&pt,t[21]=si^~ci&vn,t[30]=In^~ri&oi,t[31]=da^~We&rt,t[40]=ui^~hi&ma,t[41]=ot^~gt&ya,t[2]=et^~ut&An,t[3]=tt^~ct&En,t[12]=ga^~$e&nt,t[13]=pa^~ni&ai,t[22]=at^~pt&wa,t[23]=ci^~vn&va,t[32]=ri^~oi&li,t[33]=We^~rt<,t[42]=hi^~ma&Ye,t[43]=gt^~ya&Je,t[4]=ut^~An&Aa,t[5]=ct^~En&Ea,t[14]=$e^~nt&ft,t[15]=ni^~ai&fi,t[24]=pt^~wa&ii,t[25]=vn^~va&Xe,t[34]=oi^~li&bn,t[35]=rt^~lt&Sn,t[44]=ma^~Ye&it,t[45]=ya^~Je&st,t[6]=An^~Aa&Qe,t[7]=En^~Ea&Ke,t[16]=nt^~ft&ht,t[17]=ai^~fi&dt,t[26]=wa^~ii&Ze,t[27]=va^~Xe&si,t[36]=li^~bn&In,t[37]=lt^~Sn&da,t[46]=Ye^~it&ui,t[47]=Je^~st&ot,t[8]=Aa^~Qe&et,t[9]=Ea^~Ke&tt,t[18]=ft^~ht&ga,t[19]=fi^~dt&pa,t[28]=ii^~Ze&at,t[29]=Xe^~si&ci,t[38]=bn^~In&ri,t[39]=Sn^~da&We,t[48]=it^~ui&hi,t[49]=st^~ot>,t[0]^=yx[e*2],t[1]^=yx[e*2+1]}}});var Ex=B((s0e,Ax)=>{h();var dg=vx();function ku(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}ku.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};ku.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(dg.p1600(this.state),this.count=0);return e};ku.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};Ax.exports=ku});var sf=B((a0e,bx)=>{h();bx.exports=mx()(Ex())});var Ve=B(Kr=>{"use strict";h();var Qj=Kr&&Kr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Kj=Kr&&Kr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Sx=Kr&&Kr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qj(e,t,r);return Kj(e,t),e},Wj=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.AddressComputer=Kr.Address=void 0;var Hu=Sx(wv()),$j=Wj((rr(),_e(fr))),Zv=hr(),Gu=Sx(Ie()),Yj=$d(),Jj=sf(),of="erd",gg=32,Xj="0".repeat(16),pg=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(ArrayBuffer.isView(e))return t.fromBuffer(p.Buffer.from(e));if(typeof e=="string")return t.fromString(e);throw new Gu.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=t.empty();return r.valueHex=e,r}static fromBuffer(e){if(e.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==gg}static fromHex(e){if(!t.isValidHex(e))throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t("")}static fromBech32(e){let r;try{r=Hu.decode(e)}catch(s){throw new Gu.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=of)throw new Gu.ErrAddressBadHrp(of,n);let i=p.Buffer.from(Hu.fromWords(r.words));if(i.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=Hu.decodeUnsafe(e),n=r?.prefix,i=r?p.Buffer.from(Hu.fromWords(r.words)):void 0;return!(n!==of||i?.length!==gg)}hex(){return this.toHex()}toHex(){return this.isEmpty()?"":this.valueHex}bech32(){return this.toBech32()}toBech32(){if(this.isEmpty())return"";let e=Hu.toWords(this.pubkey());return Hu.encode(of,e)}pubkey(){return this.getPublicKey()}getPublicKey(){return this.isEmpty()?p.Buffer.from([]):p.Buffer.from(this.valueHex,"hex")}getHrp(){return of}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.toBech32()}toJSON(){return{bech32:this.toBech32(),pubkey:this.toHex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.isSmartContract()}isSmartContract(){return this.toHex().startsWith(Xj)}};Kr.Address=pg;var eA=class{constructor(e){this.numberOfShardsWithoutMeta=e||Zv.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META}computeContractAddress(e,r){let n=p.Buffer.alloc(8,0),i=e.getPublicKey(),s=i.slice(30),o=p.Buffer.alloc(8),u=new $j.default(r.toString()),a=Yj.bigIntToBuffer(u);o.write(a.reverse().toString("hex"),"hex");let c=p.Buffer.concat([i,o]),f=Jj("keccak256").update(c).digest(),d=p.Buffer.from(Zv.WasmVirtualMachine,"hex"),w=p.Buffer.concat([n,d,f.slice(10,30),s]);return new pg(w)}getShardOfAddress(e){return this.getShardOfPubkey(e.getPublicKey(),this.numberOfShardsWithoutMeta)}getShardOfPubkey(e,r){let n=parseInt("11",2),i=parseInt("01",2),s=e[31];if(this.isPubkeyOfMetachain(e))return Zv.METACHAIN_ID;let o=s&n;return o>r-1&&(o=s&i),o}isPubkeyOfMetachain(e){let r=p.Buffer.from([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n=p.Buffer.from(e).slice(0,r.length);return!!(r.equals(n)||p.Buffer.alloc(32).equals(p.Buffer.from(e)))}};Kr.AddressComputer=eA});var Rn=B(Ft=>{"use strict";h();var Zj=Ft&&Ft.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ez=Ft&&Ft.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tz=Ft&&Ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zj(e,t,r);return ez(e,t),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.isEmpty=Ft.guardEmpty=Ft.guardNotEmpty=Ft.guardLength=Ft.guardSameLength=Ft.guardValueIsSetWithMessage=Ft.guardValueIsSet=Ft.guardTrue=void 0;var ju=tz(Ie());function rz(t,e){if(!t)throw new ju.ErrInvariantFailed(`[<${e}>] isn't true`)}Ft.guardTrue=rz;function nz(t,e){Ix(`${t} isn't set (null or undefined)`,e)}Ft.guardValueIsSet=nz;function Ix(t,e){if(e==null||e===void 0)throw new ju.ErrInvariantFailed(t)}Ft.guardValueIsSetWithMessage=Ix;function iz(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new ju.ErrInvariantFailed("arrays do not have the same length")}Ft.guardSameLength=iz;function sz(t,e){let r=t.length||0;if(r!=e)throw new ju.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}Ft.guardLength=sz;function oz(t,e){if(tA(t))throw new ju.ErrInvariantFailed(`${e} is empty`)}Ft.guardNotEmpty=oz;function az(t,e){if(!tA(t))throw new ju.ErrInvariantFailed(`${e} is not empty`)}Ft.guardEmpty=az;function tA(t){return t.isEmpty?t.isEmpty():t.length===0}Ft.isEmpty=tA});var Tx=B(mg=>{"use strict";h();Object.defineProperty(mg,"__esModule",{value:!0});mg.TypeFormula=void 0;var rA=class{constructor(e,r){this.name=e,this.typeParameters=r}toString(){if(this.typeParameters.length>0){let e=this.typeParameters.map(r=>r.toString()).join(", ");return`${this.name}<${e}>`}else return this.name}};mg.TypeFormula=rA});var _x=B(yg=>{"use strict";h();Object.defineProperty(yg,"__esModule",{value:!0});yg.TypeFormulaParser=void 0;var af=Tx(),Ui=class t{parseExpression(e){e=e.trim();let r=this.tokenizeExpression(e).filter(s=>s!==t.COMMA),n=[];for(let s of r)if(this.isPunctuation(s))if(this.isEndOfTypeParameters(s)){let o=this.acquireTypeWithParameters(n);n.push(o)}else if(this.isBeginningOfTypeParameters(s))n.push(s);else throw new Error(`Unexpected token (punctuation): ${s}`);else n.push(s);if(n.length!==1)throw new Error(`Unexpected stack length at end of parsing: ${n.length}`);if(t.PUNCTUATION.includes(n[0]))throw new Error("Unexpected root element.");let i=n[0];if(i instanceof af.TypeFormula)return i;if(typeof i=="string")return new af.TypeFormula(i,[]);throw new Error(`Unexpected item on stack: ${i}`)}tokenizeExpression(e){let r=[],n="";for(let i of e)this.isPunctuation(i)?(n&&(r.push(n.trim()),n=""),r.push(i)):n+=i;return n&&r.push(n.trim()),r}acquireTypeWithParameters(e){let r=this.acquireTypeParameters(e),n=e.pop();return new af.TypeFormula(n,r.reverse())}acquireTypeParameters(e){let r=[];for(;;){let n=e.pop();if(n===void 0)throw new Error("Badly specified type parameters");if(this.isBeginningOfTypeParameters(n))break;if(n instanceof af.TypeFormula)r.push(n);else if(typeof n=="string")r.push(new af.TypeFormula(n,[]));else throw new Error(`Unexpected type parameter object in stack: ${n}`)}return r}isPunctuation(e){return t.PUNCTUATION.includes(e)}isEndOfTypeParameters(e){return e===t.END_TYPE_PARAMETERS}isBeginningOfTypeParameters(e){return e===t.BEGIN_TYPE_PARAMETERS}};yg.TypeFormulaParser=Ui;Ui.BEGIN_TYPE_PARAMETERS="<";Ui.END_TYPE_PARAMETERS=">";Ui.COMMA=",";Ui.PUNCTUATION=[Ui.COMMA,Ui.BEGIN_TYPE_PARAMETERS,Ui.END_TYPE_PARAMETERS]});var Cx=B(wg=>{"use strict";h();Object.defineProperty(wg,"__esModule",{value:!0});wg.getJavascriptPrototypesInHierarchy=void 0;function uz(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}wg.getJavascriptPrototypesInHierarchy=uz});var sr=B(ir=>{"use strict";h();Object.defineProperty(ir,"__esModule",{value:!0});ir.NullType=ir.TypePlaceholder=ir.isTyped=ir.PrimitiveValue=ir.TypedValue=ir.CustomType=ir.PrimitiveType=ir.TypeCardinality=ir.Type=void 0;var nA=Cx(),Nx=Rn(),fo=class t{constructor(e,r=[],n=uf.fixed(1)){Nx.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return Nx.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return nA.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};ir.Type=fo;fo.ClassName="Type";var uf=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};ir.TypeCardinality=uf;uf.MaxCardinality=4096;var vg=class t extends fo{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveType=vg;vg.ClassName="PrimitiveType";var Ag=class t extends fo{getClassName(){return t.ClassName}};ir.CustomType=Ag;Ag.ClassName="CustomType";var cf=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};ir.TypedValue=cf;cf.ClassName="TypedValue";var Eg=class t extends cf{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveValue=Eg;Eg.ClassName="PrimitiveValue";function cz(t){return t.belongsToTypesystem!==void 0}ir.isTyped=cz;var bg=class t extends fo{constructor(){super("...")}getClassName(){return t.ClassName}};ir.TypePlaceholder=bg;bg.ClassName="TypePlaceholder";var Sg=class t extends fo{constructor(){super("?")}getClassName(){return t.ClassName}};ir.NullType=Sg;Sg.ClassName="NullType"});var lf=B(Ig=>{"use strict";h();Object.defineProperty(Ig,"__esModule",{value:!0});Ig.TypeExpressionParser=void 0;var lz=_x(),fz=Ie(),hz=sr(),iA=class{constructor(){this.backingTypeFormulaParser=new lz.TypeFormulaParser}parse(e){try{return this.doParse(e)}catch(r){throw new fz.ErrTypingSystem(`Failed to parse type expression: ${e}. Error: ${r}`)}}doParse(e){let r=this.backingTypeFormulaParser.parseExpression(e);return this.typeFormulaToType(r)}typeFormulaToType(e){let r=e.typeParameters.map(n=>this.typeFormulaToType(n));return new hz.Type(e.name,r)}};Ig.TypeExpressionParser=iA});var oA=B(ho=>{"use strict";h();Object.defineProperty(ho,"__esModule",{value:!0});ho.EndpointParameterDefinition=ho.EndpointModifiers=ho.EndpointDefinition=void 0;var dz=lf(),xx="?",gz="N / A",sA=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?xx:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>ff.fromJSON(s)),n=e.outputs.map(s=>ff.fromJSON(s)),i=new Tg(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};ho.EndpointDefinition=sA;var Tg=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};ho.EndpointModifiers=Tg;var ff=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new dz.TypeExpressionParser().parse(e.type);return new t(e.name||xx,e.description||gz,r)}};ho.EndpointParameterDefinition=ff});var zu=B(Wr=>{"use strict";h();var pz=Wr&&Wr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),mz=Wr&&Wr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yz=Wr&&Wr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&pz(e,t,r);return mz(e,t),e};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Fields=Wr.Field=Wr.FieldDefinition=void 0;var aA=yz(Ie()),wz=lf(),uA=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new wz.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};Wr.FieldDefinition=uA;var cA=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new aA.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new aA.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};Wr.Field=cA;var lA=class{static checkTyping(e,r){if(e.length!=r.length)throw new aA.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";h();Object.defineProperty(go,"__esModule",{value:!0});go.EnumValue=go.EnumVariantDefinition=go.EnumType=void 0;var vz=Ie(),fA=Rn(),_g=zu(),Dx=sr(),Ox=256,Cg=class t extends Dx.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>Ng.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>({...n,discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return fA.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return fA.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};go.EnumType=Cg;Cg.ClassName="EnumType";var Ng=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],fA.guardTrue(r_g.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return _g.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};go.EnumVariantDefinition=Ng;var xg=class t extends Dx.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();_g.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=_g.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new vz.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};go.EnumValue=xg;xg.ClassName="EnumValue"});var Rx=B(Qu=>{"use strict";h();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.EventTopicDefinition=Qu.EventDefinition=void 0;var Az=lf(),Px="?",hA=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?Px:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>Og.fromJSON(n));return new t(e.identifier,r)}};Qu.EventDefinition=hA;var Og=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Az.TypeExpressionParser().parse(e.type);return new t({name:e.name||Px,type:r,indexed:e.indexed})}};Qu.EventTopicDefinition=Og});var Wu=B(Ku=>{"use strict";h();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.Struct=Ku.StructType=void 0;var Ez=Ie(),Dg=zu(),Bx=sr(),Pg=class t extends Bx.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>Dg.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Dg.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Ku.StructType=Pg;Pg.ClassName="StructType";var Rg=class t extends Bx.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();Dg.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Ez.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return Dg.Fields.equals(r,n)}};Ku.Struct=Rg;Rg.ClassName="Struct"});var Yu=B($u=>{"use strict";h();Object.defineProperty($u,"__esModule",{value:!0});$u.AddressValue=$u.AddressType=void 0;var bz=Ve(),Mx=sr(),df=class t extends Mx.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};$u.AddressType=df;df.ClassName="AddressType";var Bg=class t extends Mx.PrimitiveValue{constructor(e){super(new df),this.value=new bz.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};$u.AddressValue=Bg;Bg.ClassName="AddressValue"});var Lg=B(Ju=>{"use strict";h();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.OptionalValue=Ju.OptionalType=void 0;var Sz=Rn(),gf=sr(),pf=class t extends gf.Type{constructor(e){super("Optional",[e],gf.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(gf.NullType.ClassName);return r||n}};Ju.OptionalType=pf;pf.ClassName="OptionalType";var Mg=class t extends gf.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new pf(new gf.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return Sz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};Ju.OptionalValue=Mg;Mg.ClassName="OptionalValue"});var yf=B(Xu=>{"use strict";h();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.BooleanValue=Xu.BooleanType=void 0;var Lx=sr(),mf=class t extends Lx.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};Xu.BooleanType=mf;mf.ClassName="BooleanType";var Fg=class t extends Lx.PrimitiveValue{constructor(e){super(new mf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};Xu.BooleanValue=Fg;Fg.ClassName="BooleanValue"});var po=B(Zu=>{"use strict";h();Object.defineProperty(Zu,"__esModule",{value:!0});Zu.BytesValue=Zu.BytesType=void 0;var Fx=sr(),wf=class t extends Fx.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Zu.BytesType=wf;wf.ClassName="BytesType";var Ug=class t extends Fx.PrimitiveValue{constructor(e){super(new wf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=p.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=p.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Zu.BytesValue=Ug;Ug.ClassName="BytesValue"});var qx=B(ec=>{"use strict";h();Object.defineProperty(ec,"__esModule",{value:!0});ec.CodeMetadataValue=ec.CodeMetadataType=void 0;var Ux=sr(),qg=class extends Ux.PrimitiveType{constructor(){super("CodeMetadata")}};ec.CodeMetadataType=qg;var dA=class extends Ux.PrimitiveValue{constructor(e){super(new qg),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};ec.CodeMetadataValue=dA});var kg=B(tc=>{"use strict";h();Object.defineProperty(tc,"__esModule",{value:!0});tc.CompositeValue=tc.CompositeType=void 0;var Iz=Rn(),gA=sr(),vf=class t extends gA.Type{constructor(...e){super("Composite",e,gA.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};tc.CompositeType=vf;vf.ClassName="CompositeType";var Vg=class t extends gA.TypedValue{constructor(e,r){super(e),Iz.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new vf(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();Object.defineProperty(Hg,"__esModule",{value:!0});Hg.CollectionOfTypedValues=void 0;var pA=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";h();Object.defineProperty(qi,"__esModule",{value:!0});qi.List=qi.OptionValue=qi.ListType=qi.OptionType=void 0;var Tz=Rn(),_z=mA(),Fa=sr(),La=class t extends Fa.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Fa.NullType.ClassName);return r||n}};qi.OptionType=La;La.ClassName="OptionType";var Af=class t extends Fa.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};qi.ListType=Af;Af.ClassName="ListType";var Gg=class t extends Fa.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new La(new Fa.NullType);return new t(e)}static newMissingTyped(e){return new t(new La(e))}static newProvided(e){let r=new La(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return Tz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};qi.OptionValue=Gg;Gg.ClassName="OptionValue";var jg=class t extends Fa.TypedValue{constructor(e,r){super(e),this.backingCollection=new _z.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new Fa.TypePlaceholder,[]);let r=e[0].getType(),n=new Af(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};qi.List=jg;jg.ClassName="List"});var Kg=B(rc=>{"use strict";h();Object.defineProperty(rc,"__esModule",{value:!0});rc.ArrayVec=rc.ArrayVecType=void 0;var Vx=Rn(),Cz=mA(),kx=sr(),zg=class t extends kx.Type{constructor(e,r){super("Array",[r]),Vx.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};rc.ArrayVecType=zg;zg.ClassName="ArrayVecType";var Qg=class t extends kx.TypedValue{constructor(e,r){super(e),Vx.guardLength(r,e.length),this.backingCollection=new Cz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};rc.ArrayVec=Qg;Qg.ClassName="ArrayVec"});var Sf=B(nc=>{"use strict";h();Object.defineProperty(nc,"__esModule",{value:!0});nc.H256Value=nc.H256Type=void 0;var Hx=sr(),bf=class t extends Hx.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};nc.H256Type=bf;bf.ClassName="H256Type";var Wg=class t extends Hx.PrimitiveValue{constructor(e){super(new bf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};nc.H256Value=Wg;Wg.ClassName="H256Value"});var Yg=B(ic=>{"use strict";h();Object.defineProperty(ic,"__esModule",{value:!0});ic.NothingValue=ic.NothingType=void 0;var Gx=sr(),If=class t extends Gx.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};ic.NothingType=If;If.ClassName="NothingType";var $g=class t extends Gx.PrimitiveValue{constructor(){super(new If)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};ic.NothingValue=$g;$g.ClassName="NothingValue"});var Mf=B(Ee=>{"use strict";h();var Nz=Ee&&Ee.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xz=Ee&&Ee.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oz=Ee&&Ee.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nz(e,t,r);return xz(e,t),e},Dz=Ee&&Ee.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.BigIntValue=Ee.BigUIntValue=Ee.I64Value=Ee.U64Value=Ee.I32Value=Ee.U32Value=Ee.I16Value=Ee.U16Value=Ee.I8Value=Ee.U8Value=Ee.NumericalValue=Ee.BigIntType=Ee.BigUIntType=Ee.I64Type=Ee.U64Type=Ee.I32Type=Ee.U32Type=Ee.I16Type=Ee.U16Type=Ee.I8Type=Ee.U8Type=Ee.NumericalType=void 0;var Pz=Dz((rr(),_e(fr))),jx=Oz(Ie()),zx=sr(),$r=class t extends zx.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ee.NumericalType=$r;$r.ClassName="NumericalType";var Tf=class t extends $r{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ee.U8Type=Tf;Tf.ClassName="U8Type";var _f=class t extends $r{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ee.I8Type=_f;_f.ClassName="I8Type";var Cf=class t extends $r{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ee.U16Type=Cf;Cf.ClassName="U16Type";var Nf=class t extends $r{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ee.I16Type=Nf;Nf.ClassName="I16Type";var xf=class t extends $r{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ee.U32Type=xf;xf.ClassName="U32Type";var Of=class t extends $r{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ee.I32Type=Of;Of.ClassName="I32Type";var Df=class t extends $r{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ee.U64Type=Df;Df.ClassName="U64Type";var Pf=class t extends $r{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ee.I64Type=Pf;Pf.ClassName="I64Type";var Rf=class t extends $r{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ee.BigUIntType=Rf;Rf.ClassName="BigUIntType";var Bf=class t extends $r{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ee.BigIntType=Bf;Bf.ClassName="BigIntType";var Yr=class t extends zx.PrimitiveValue{constructor(e,r){if(super(e),typeof r=="bigint"&&(r=r.toString()),this.value=new Pz.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new jx.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new jx.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ee.NumericalValue=Yr;Yr.ClassName="NumericalValue";var Jg=class t extends Yr{constructor(e){super(new Tf,e)}getClassName(){return t.ClassName}};Ee.U8Value=Jg;Jg.ClassName="U8Value";var Xg=class t extends Yr{constructor(e){super(new _f,e)}getClassName(){return t.ClassName}};Ee.I8Value=Xg;Xg.ClassName="I8Value";var Zg=class t extends Yr{constructor(e){super(new Cf,e)}getClassName(){return t.ClassName}};Ee.U16Value=Zg;Zg.ClassName="U16Value";var ep=class t extends Yr{constructor(e){super(new Nf,e)}getClassName(){return t.ClassName}};Ee.I16Value=ep;ep.ClassName="I16Value";var tp=class t extends Yr{constructor(e){super(new xf,e)}getClassName(){return t.ClassName}};Ee.U32Value=tp;tp.ClassName="U32Value";var rp=class t extends Yr{constructor(e){super(new Of,e)}getClassName(){return t.ClassName}};Ee.I32Value=rp;rp.ClassName="I32Value";var np=class t extends Yr{constructor(e){super(new Df,e)}getClassName(){return t.ClassName}};Ee.U64Value=np;np.ClassName="U64Value";var ip=class t extends Yr{constructor(e){super(new Pf,e)}getClassName(){return t.ClassName}};Ee.I64Value=ip;ip.ClassName="I64Value";var sp=class t extends Yr{constructor(e){super(new Rf,e)}getClassName(){return t.ClassName}};Ee.BigUIntValue=sp;sp.ClassName="BigUIntValue";var op=class t extends Yr{constructor(e){super(new Bf,e)}getClassName(){return t.ClassName}};Ee.BigIntValue=op;op.ClassName="BigIntValue"});var up=B(sc=>{"use strict";h();Object.defineProperty(sc,"__esModule",{value:!0});sc.StringValue=sc.StringType=void 0;var Qx=sr(),Lf=class t extends Qx.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};sc.StringType=Lf;Lf.ClassName="StringType";var ap=class t extends Qx.PrimitiveValue{constructor(e){super(new Lf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=p.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};sc.StringValue=ap;ap.ClassName="StringValue"});var ac=B(oc=>{"use strict";h();Object.defineProperty(oc,"__esModule",{value:!0});oc.TokenIdentifierValue=oc.TokenIdentifierType=void 0;var Kx=sr(),Rz="EGLD",Ff=class t extends Kx.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};oc.TokenIdentifierType=Ff;Ff.ClassName="TokenIdentifierType";var cp=class t extends Kx.PrimitiveValue{constructor(e){super(new Ff),this.value=e}static egld(){return new t(Rz)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};oc.TokenIdentifierValue=cp;cp.ClassName="TokenIdentifierValue"});var fp=B(Bn=>{"use strict";h();var Bz=Bn&&Bn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Mz=Bn&&Bn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Lz=Bn&&Bn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bz(e,t,r);return Mz(e,t),e};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Tuple=Bn.TupleType=void 0;var Fz=Lz(Ie()),Wx=zu(),$x=Wu(),Uf=class t extends $x.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new Wx.FieldDefinition(Yx(i),"anonymous tuple field",n))}};Bn.TupleType=Uf;Uf.ClassName="TupleType";function Yx(t){return`field${t}`}var lp=class t extends $x.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Fz.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new Uf(...r),i=e.map((s,o)=>new Wx.Field(s,Yx(o)));return new t(n,i)}};Bn.Tuple=lp;lp.ClassName="Tuple"});var gp=B(mo=>{"use strict";h();Object.defineProperty(mo,"__esModule",{value:!0});mo.VariadicValue=mo.CountedVariadicType=mo.VariadicType=void 0;var uc=sr(),Ua=class t extends uc.Type{constructor(e,r=!1){super("Variadic",[e],uc.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};mo.VariadicType=Ua;Ua.ClassName="VariadicType";var hp=class extends uc.Type{constructor(e){super("Variadic",[e],uc.TypeCardinality.variable())}getClassName(){return Ua.ClassName}};mo.CountedVariadicType=hp;hp.ClassName="VariadicType";var dp=class t extends uc.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Ua(new uc.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Ua(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();var Uz=ki&&ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qz=ki&&ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vz=ki&&ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Uz(e,t,r);return qz(e,t),e};Object.defineProperty(ki,"__esModule",{value:!0});ki.TypeMapper=void 0;var Jx=Vz(Ie()),kz=Yu(),yA=Lg(),Hz=yf(),Gz=po(),jz=qx(),pp=kg(),wA=hf(),zz=zu(),Xx=Ef(),Vi=Kg(),Qz=Sf(),Zx=Yg(),Mn=Mf(),Kz=up(),e6=Wu(),t6=ac(),yo=fp(),mp=gp(),vA=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new Xx.OptionType(r[0])],["List",(...r)=>new Xx.ListType(r[0])],["VarArgs",(...r)=>new mp.VariadicType(r[0])],["MultiResultVec",(...r)=>new mp.VariadicType(r[0])],["variadic",(...r)=>new mp.VariadicType(r[0])],["counted-variadic",(...r)=>new mp.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new yA.OptionalType(r[0])],["optional",(...r)=>new yA.OptionalType(r[0])],["OptionalResult",(...r)=>new yA.OptionalType(r[0])],["multi",(...r)=>new pp.CompositeType(...r)],["MultiArg",(...r)=>new pp.CompositeType(...r)],["MultiResult",(...r)=>new pp.CompositeType(...r)],["multi",(...r)=>new pp.CompositeType(...r)],["tuple",(...r)=>new yo.TupleType(...r)],["tuple2",(...r)=>new yo.TupleType(...r)],["tuple3",(...r)=>new yo.TupleType(...r)],["tuple4",(...r)=>new yo.TupleType(...r)],["tuple5",(...r)=>new yo.TupleType(...r)],["tuple6",(...r)=>new yo.TupleType(...r)],["tuple7",(...r)=>new yo.TupleType(...r)],["tuple8",(...r)=>new yo.TupleType(...r)],["array2",(...r)=>new Vi.ArrayVecType(2,r[0])],["array8",(...r)=>new Vi.ArrayVecType(8,r[0])],["array16",(...r)=>new Vi.ArrayVecType(16,r[0])],["array20",(...r)=>new Vi.ArrayVecType(20,r[0])],["array32",(...r)=>new Vi.ArrayVecType(32,r[0])],["array46",(...r)=>new Vi.ArrayVecType(46,r[0])],["array48",(...r)=>new Vi.ArrayVecType(48,r[0])],["array64",(...r)=>new Vi.ArrayVecType(64,r[0])],["array128",(...r)=>new Vi.ArrayVecType(128,r[0])],["array256",(...r)=>new Vi.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new Mn.U8Type],["u16",new Mn.U16Type],["u32",new Mn.U32Type],["u64",new Mn.U64Type],["U64",new Mn.U64Type],["BigUint",new Mn.BigUIntType],["i8",new Mn.I8Type],["i16",new Mn.I16Type],["i32",new Mn.I32Type],["i64",new Mn.I64Type],["Bigint",new Mn.BigIntType],["BigInt",new Mn.BigIntType],["bool",new Hz.BooleanType],["bytes",new Gz.BytesType],["Address",new kz.AddressType],["H256",new Qz.H256Type],["utf-8 string",new Kz.StringType],["TokenIdentifier",new t6.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new t6.TokenIdentifierType],["CodeMetadata",new jz.CodeMetadataType],["nothing",new Zx.NothingType],["AsyncCall",new Zx.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new Jx.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(wA.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(e6.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new e6.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new wA.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new wA.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new zz.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new Jx.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};ki.TypeMapper=vA});var o6=B(Hi=>{"use strict";h();var Wz=Hi&&Hi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),$z=Hi&&Hi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yz=Hi&&Hi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wz(e,t,r);return $z(e,t),e};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.AbiRegistry=void 0;var r6=Yz(Ie()),qf=Rn(),Vf=oA(),n6=hf(),EA=Rx(),i6=Wu(),Jz=AA(),Xz="?",bA=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||Xz,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],u=Vf.EndpointDefinition.fromJSON({name:"constructor",...n}),a=i.map(A=>Vf.EndpointDefinition.fromJSON(A)),c=[];for(let A in s){let T=s[A];if(T.type=="struct")c.push(i6.StructType.fromJSON({name:A,fields:T.fields}));else if(T.type=="enum"||T.type=="explicit-enum")c.push(n6.EnumType.fromJSON({name:A,variants:T.variants}));else throw new r6.ErrTypingSystem(`Cannot handle custom type: ${A}`)}let f=o.map(A=>EA.EventDefinition.fromJSON(A));return new t({name:r,constructorDefinition:u,endpoints:a,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return qf.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(i6.StructType.ClassName));return qf.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(n6.EnumType.ClassName));return qf.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return qf.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return qf.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new Jz.TypeMapper([]),r=[];for(let u of this.customTypes)this.mapCustomTypeDepthFirst(u,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new r6.ErrTypingSystem("Did not re-map all custom types");let n=s6(this.constructorDefinition,e),i=[];for(let u of this.endpoints)i.push(s6(u,e));let s=this.events.map(u=>Zz(u,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(u=>u.getName()==e.getName())>=0)return;for(let u of e.getNamesOfDependencies()){let a=r.find(c=>c.getName()==u);a&&this.mapCustomTypeDepthFirst(a,r,n,i)}let o=n.mapType(e);i.push(o)}};Hi.AbiRegistry=bA;function s6(t,e){let r=t.input.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new Vf.EndpointDefinition(t.name,r,n,t.modifiers)}function Zz(t,e){let r=t.inputs.map(n=>new EA.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new EA.EventDefinition(t.identifier,r)}});var u6=B(cc=>{"use strict";h();Object.defineProperty(cc,"__esModule",{value:!0});cc.createListOfTokenIdentifiers=cc.createListOfAddresses=void 0;var eQ=Yu(),a6=Ef(),tQ=ac();function rQ(t){let e=t.map(n=>new eQ.AddressValue(n));return a6.List.fromItems(e)}cc.createListOfAddresses=rQ;function nQ(t){let e=t.map(n=>new tQ.TokenIdentifierValue(n));return a6.List.fromItems(e)}cc.createListOfTokenIdentifiers=nQ});var b6=B(Dr=>{"use strict";h();var iQ=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sQ=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oQ=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iQ(e,t,r);return sQ(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.onPrimitiveTypeSelect=Dr.onPrimitiveValueSelect=Dr.onTypedValueSelect=Dr.onTypeSelect=void 0;var wp=oQ(Ie()),c6=Yu(),l6=yf(),f6=po(),h6=hf(),yp=Ef(),d6=Sf(),g6=Mf(),p6=Yg(),m6=Wu(),y6=ac(),w6=fp(),v6=sr(),A6=Kg(),E6=up();function aQ(t,e){if(t.hasExactClass(yp.OptionType.ClassName))return e.onOption();if(t.hasExactClass(yp.ListType.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(v6.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(m6.StructType.ClassName))return e.onStruct();if(t.hasExactClass(w6.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't known: ${t}`)}Dr.onTypeSelect=aQ;function uQ(t,e){if(t.hasClassOrSuperclass(v6.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(yp.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(yp.List.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(m6.Struct.ClassName))return e.onStruct();if(t.hasExactClass(w6.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't typed: ${t}`)}Dr.onTypedValueSelect=uQ;function cQ(t,e){if(t.hasExactClass(l6.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringValue.ClassName))return e.onString();if(t.hasExactClass(d6.H256Value.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(p6.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Dr.onPrimitiveValueSelect=cQ;function lQ(t,e){if(t.hasExactClass(l6.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringType.ClassName))return e.onString();if(t.hasExactClass(d6.H256Type.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(p6.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Dr.onPrimitiveTypeSelect=lQ});var dr=B(He=>{"use strict";h();var fQ=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ut=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fQ(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});Ut(o6(),He);Ut(Yu(),He);Ut(Lg(),He);Ut(yf(),He);Ut(po(),He);Ut(kg(),He);Ut(oA(),He);Ut(hf(),He);Ut(u6(),He);Ut(zu(),He);Ut(Ef(),He);Ut(Kg(),He);Ut(Sf(),He);Ut(b6(),He);Ut(Yg(),He);Ut(Mf(),He);Ut(up(),He);Ut(Wu(),He);Ut(ac(),He);Ut(fp(),He);Ut(lf(),He);Ut(AA(),He);Ut(sr(),He);Ut(gp(),He)});var I6=B(Gi=>{"use strict";h();var hQ=Gi&&Gi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),dQ=Gi&&Gi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gQ=Gi&&Gi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hQ(e,t,r);return dQ(e,t),e};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.OptionValueBinaryCodec=void 0;var S6=gQ(Ie()),vp=dr(),SA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[vp.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[vp.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new vp.OptionValue(r);if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new vp.OptionValue(r,n)}encodeNested(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([])}};Gi.OptionValueBinaryCodec=SA});var T6=B(Ap=>{"use strict";h();Object.defineProperty(Ap,"__esModule",{value:!0});Ap.AddressBinaryCodec=void 0;var pQ=Ve(),mQ=dr(),IA=class{decodeNested(e){let r=e.slice(0,32),n=new pQ.Address(r);return[new mQ.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};Ap.AddressBinaryCodec=IA});var C6=B(ji=>{"use strict";h();var yQ=ji&&ji.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wQ=ji&&ji.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vQ=ji&&ji.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yQ(e,t,r);return wQ(e,t),e};Object.defineProperty(ji,"__esModule",{value:!0});ji.BooleanBinaryCodec=void 0;var AQ=vQ(Ie()),_6=dr(),kf=class t{decodeNested(e){let r=e.readUInt8(0);return[new _6.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new AQ.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new _6.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([])}};ji.BooleanBinaryCodec=kf;kf.TRUE=1;kf.FALSE=0});var bp=B(Ep=>{"use strict";h();Object.defineProperty(Ep,"__esModule",{value:!0});Ep.SizeOfU32=void 0;Ep.SizeOfU32=4});var x6=B(lc=>{"use strict";h();var EQ=lc&&lc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lc,"__esModule",{value:!0});lc.NumericalBinaryCodec=void 0;var Hf=EQ((rr(),_e(fr))),TA=dr(),N6=bp(),$t=Bu(),_A=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=N6.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),u=i+n;return[o,u]}decodeTopLevel(e,r){let n=$t.cloneBuffer(e);if(e.length==0)return new TA.NumericalValue(r,new Hf.default(0));if(!r.withSign||$t.isMsbZero(n)){let c=$t.bufferToBigInt(n);return new TA.NumericalValue(r,c)}$t.flipBufferBitsInPlace(n);let a=$t.bufferToBigInt(n).multipliedBy(new Hf.default(-1)).minus(new Hf.default(1));return new TA.NumericalValue(r,a)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=p.Buffer.alloc(N6.SizeOfU32);return n.writeUInt32BE(r.length),p.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return p.Buffer.alloc(r,0);if(!e.withSign){let o=$t.bigIntToBuffer(e.value),u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}if(e.value.isPositive()){let o=$t.bigIntToBuffer(e.value);$t.isMsbOne(o)&&(o=$t.prependByteToBuffer(o,0));let u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}let n=e.value.plus(new Hf.default(1)),i=$t.bigIntToBuffer(n);$t.flipBufferBitsInPlace(i),$t.isMsbZero(i)&&(i=$t.prependByteToBuffer(i,255));let s=p.Buffer.alloc(r-i.length,255);return p.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?p.Buffer.alloc(0):r?this.encodePrimitive(e):$t.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=$t.bigIntToBuffer(e.value);return $t.isMsbOne(i)&&(i=$t.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Hf.default(1)),n=$t.bigIntToBuffer(r);return $t.flipBufferBitsInPlace(n),$t.isMsbZero(n)&&(n=$t.prependByteToBuffer(n,255)),n}};lc.NumericalBinaryCodec=_A});var O6=B(Sp=>{"use strict";h();Object.defineProperty(Sp,"__esModule",{value:!0});Sp.H256BinaryCodec=void 0;var bQ=Sf(),CA=class{decodeNested(e){let r=e.slice(0,32);return[new bQ.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Sp.H256BinaryCodec=CA});var _p=B(Tp=>{"use strict";h();Object.defineProperty(Tp,"__esModule",{value:!0});Tp.BytesBinaryCodec=void 0;var D6=po(),Ip=bp(),NA=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(Ip.SizeOfU32,Ip.SizeOfU32+r);return[new D6.BytesValue(n),Ip.SizeOfU32+r]}decodeTopLevel(e){return new D6.BytesValue(e)}encodeNested(e){let r=p.Buffer.alloc(Ip.SizeOfU32);return r.writeUInt32BE(e.getLength()),p.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Tp.BytesBinaryCodec=NA});var R6=B(Cp=>{"use strict";h();Object.defineProperty(Cp,"__esModule",{value:!0});Cp.TokenIdentifierCodec=void 0;var SQ=po(),P6=ac(),IQ=_p(),xA=class{constructor(){this.bytesCodec=new IQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new P6.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new P6.TokenIdentifierValue(r.toString())}encodeNested(e){let r=SQ.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Cp.TokenIdentifierCodec=xA});var M6=B(Np=>{"use strict";h();Object.defineProperty(Np,"__esModule",{value:!0});Np.NothingCodec=void 0;var B6=dr(),OA=class{decodeNested(){return[new B6.NothingValue,0]}decodeTopLevel(){return new B6.NothingValue}encodeNested(){return p.Buffer.from([])}encodeTopLevel(){return p.Buffer.from([])}};Np.NothingCodec=OA});var F6=B(xp=>{"use strict";h();Object.defineProperty(xp,"__esModule",{value:!0});xp.StringBinaryCodec=void 0;var L6=dr(),TQ=po(),_Q=_p(),DA=class{constructor(){this.bytesBinaryCodec=new _Q.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new L6.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new L6.StringValue(e.toString())}encodeNested(e){let r=TQ.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};xp.StringBinaryCodec=DA});var U6=B(Dp=>{"use strict";h();Object.defineProperty(Dp,"__esModule",{value:!0});Dp.PrimitiveBinaryCodec=void 0;var Op=dr(),CQ=T6(),NQ=C6(),xQ=x6(),OQ=O6(),DQ=_p(),PQ=R6(),RQ=M6(),BQ=F6(),PA=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new NQ.BooleanBinaryCodec,this.numericalCodec=new xQ.NumericalBinaryCodec,this.addressCodec=new CQ.AddressBinaryCodec,this.h256Codec=new OQ.H256BinaryCodec,this.bytesCodec=new DQ.BytesBinaryCodec,this.stringCodec=new BQ.StringBinaryCodec,this.tokenIdentifierCodec=new PQ.TokenIdentifierCodec,this.nothingCodec=new RQ.NothingCodec}decodeNested(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};Dp.PrimitiveBinaryCodec=PA});var k6=B(Pp=>{"use strict";h();Object.defineProperty(Pp,"__esModule",{value:!0});Pp.ListBinaryCodec=void 0;var q6=dr(),V6=bp(),RA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,u=V6.SizeOfU32;e=o.slice(u);for(let a=0;a0;){let[u,a]=this.binaryCodec.decodeNested(e,n);i.push(u),o+=a,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new q6.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=p.Buffer.alloc(V6.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return p.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return p.Buffer.concat(r)}};Pp.ListBinaryCodec=RA});var MA=B(Rp=>{"use strict";h();Object.defineProperty(Rp,"__esModule",{value:!0});Rp.FieldsBinaryCodec=void 0;var MQ=dr(),BA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,u]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(u),i+=u;let a=new MQ.Field(o,s.name);n.push(a)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return p.Buffer.concat(r)}};Rp.FieldsBinaryCodec=BA});var FA=B(Bp=>{"use strict";h();Object.defineProperty(Bp,"__esModule",{value:!0});Bp.StructBinaryCodec=void 0;var LQ=dr(),FQ=MA(),LA=class{constructor(e){this.fieldsCodec=new FQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new LQ.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Bp.StructBinaryCodec=LA});var H6=B(Lp=>{"use strict";h();Object.defineProperty(Lp,"__esModule",{value:!0});Lp.EnumBinaryCodec=void 0;var Mp=dr(),UQ=MA(),UA=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new UQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[u,a]=this.fieldsCodec.decodeNested(e,o);return[new Mp.EnumValue(r,s,u),i+a]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Mp.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Mp.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return p.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Mp.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return p.Buffer.concat([o,i])}};Lp.EnumBinaryCodec=UA});var G6=B(Fp=>{"use strict";h();Object.defineProperty(Fp,"__esModule",{value:!0});Fp.TupleBinaryCodec=void 0;var qQ=FA(),qA=class{constructor(e){this.structCodec=new qQ.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Fp.TupleBinaryCodec=qA});var j6=B(Up=>{"use strict";h();Object.defineProperty(Up,"__esModule",{value:!0});Up.ArrayVecBinaryCodec=void 0;var VQ=dr(),VA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let u=0;u{"use strict";h();var kQ=Ln&&Ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),HQ=Ln&&Ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GQ=Ln&&Ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&kQ(e,t,r);return HQ(e,t),e};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BinaryCodecConstraints=Ln.BinaryCodec=void 0;var z6=GQ(Ie()),qp=dr(),Q6=Rn(),jQ=I6(),zQ=U6(),QQ=k6(),KQ=FA(),WQ=H6(),$Q=G6(),YQ=j6(),kA=class{constructor(e=null){this.constraints=e||new Vp,this.optionCodec=new jQ.OptionValueBinaryCodec(this),this.listCodec=new QQ.ListBinaryCodec(this),this.arrayCodec=new YQ.ArrayVecBinaryCodec(this),this.primitiveCodec=new zQ.PrimitiveBinaryCodec(this),this.structCodec=new KQ.StructBinaryCodec(this),this.tupleCodec=new $Q.TupleBinaryCodec(this),this.enumCodec=new WQ.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Ln.BinaryCodec=kA;var Vp=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new z6.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new z6.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Ln.BinaryCodecConstraints=Vp});var K6=B(Fn=>{"use strict";h();var JQ=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decodeBigNumber=Fn.decodeString=Fn.decodeBool=Fn.decodeUnsignedNumber=void 0;var XQ=JQ((rr(),_e(fr))),kp=dr(),ZQ=HA(),Hp=new ZQ.BinaryCodec;function eK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return Number(e.valueOf())}Fn.decodeUnsignedNumber=eK;function tK(t){return!!Hp.decodeTopLevel(t,new kp.BooleanType).valueOf()}Fn.decodeBool=tK;function rK(t){let e=Hp.decodeTopLevel(t,new kp.BytesType);return String(e.valueOf())}Fn.decodeString=rK;function nK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return new XQ.default(e.valueOf())}Fn.decodeBigNumber=nK});var GA=B(wo=>{"use strict";h();var iK=wo&&wo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),W6=wo&&wo.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&iK(e,t,r)};Object.defineProperty(wo,"__esModule",{value:!0});W6(HA(),wo);W6(K6(),wo)});var fc=B(Gp=>{"use strict";h();Object.defineProperty(Gp,"__esModule",{value:!0});Gp.ArgSerializer=void 0;var $6=hr(),sK=GA(),Y6=dr(),jA=Lg(),zA=kg(),QA=gp(),oK={codec:new sK.BinaryCodec},KA=class{constructor(e){e={...oK,...e},this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split($6.ARGUMENTS_SEPARATOR).map(r=>p.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join($6.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(jA.OptionalValue.ClassName)){let a=o;a.isSet()&&i(a.getTypedValue());return}if(o.hasExactClass(QA.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(zA.CompositeValue.ClassName)){let a=o;for(let c of a.getItems())i(c);return}let u=r.codec.encodeTopLevel(o);n.push(u)}function s(o){if(o.getType().isCounted){let a=new Y6.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(a))}for(let a of o.getItems())i(a)}return n}};Gp.ArgSerializer=KA});var WA=B((cye,J6)=>{h();Rs.notEqual=uK;Rs.notOk=cK;Rs.equal=aK;Rs.ok=Rs;J6.exports=Rs;function aK(t,e,r){Rs(t==e,r)}function uK(t,e,r){Rs(t!=e,r)}function cK(t,e){Rs(!t,e)}function Rs(t,e){if(!t)throw new Error(e||"AssertionError")}});var Z6=B((fye,X6)=>{h();X6.exports=$A;$A.supported=typeof WebAssembly<"u";function $A(t){if(!$A.supported)return null;var e=t&&t.imports,r=lK("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(a){i.exports.memory.grow(Math.ceil(Math.abs(a-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(a){if(i.exports)return a();if(n){n.then(a.bind(null,null)).catch(a);return}try{if(t&&t.async)throw new Error("async");u({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(u)}o(a)}function u(a){i.exports=a.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function lK(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(fK)):new(io()).Buffer(t,"base64")}function fK(t){return t.charCodeAt(0)}});var oO=B((pye,Qi)=>{h();var zi=WA(),xt=Z6()(),Bs=64,jp=[];Qi.exports=Un;var eO=Qi.exports.BYTES_MIN=16,tO=Qi.exports.BYTES_MAX=64,dye=Qi.exports.BYTES=32,rO=Qi.exports.KEYBYTES_MIN=16,nO=Qi.exports.KEYBYTES_MAX=64,gye=Qi.exports.KEYBYTES=32,iO=Qi.exports.SALTBYTES=16,sO=Qi.exports.PERSONALBYTES=16;function Un(t,e,r,n,i){if(!(this instanceof Un))return new Un(t,e,r,n,i);if(!(xt&&xt.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(zi(t>=eO,"digestLength must be at least "+eO+", was given "+t),zi(t<=tO,"digestLength must be at most "+tO+", was given "+t),e!=null&&zi(e.length>=rO,"key must be at least "+rO+", was given "+e.length),e!=null&&zi(e.length<=nO,"key must be at least "+nO+", was given "+e.length),r!=null&&zi(r.length===iO,"salt must be exactly "+iO+", was given "+r.length),n!=null&&zi(n.length===sO,"personal must be exactly "+sO+", was given "+n.length)),jp.length||(jp.push(Bs),Bs+=216),this.digestLength=t,this.finalized=!1,this.pointer=jp.pop(),xt.memory.fill(0,0,64),xt.memory[0]=this.digestLength,xt.memory[1]=e?e.length:0,xt.memory[2]=1,xt.memory[3]=1,r&&xt.memory.set(r,32),n&&xt.memory.set(n,48),this.pointer+216>xt.memory.length&&xt.realloc(this.pointer+216),xt.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),xt.memory.fill(0,Bs,Bs+e.length),xt.memory[this.pointer+200]=128)}Un.prototype.update=function(t){return zi(this.finalized===!1,"Hash instance finalized"),zi(t,"input must be TypedArray or Buffer"),Bs+t.length>xt.memory.length&&xt.realloc(Bs+t.length),xt.memory.set(t,Bs),xt.exports.blake2b_update(this.pointer,Bs,Bs+t.length),this};Un.prototype.digest=function(t){if(zi(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,jp.push(this.pointer),xt.exports.blake2b_final(this.pointer),!t||t==="binary")return xt.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return dK(xt.memory,this.pointer+128,this.digestLength);zi(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{h();var Eo=WA(),jf=oO();function zp(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function aO(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function gO(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vo(t,e,r,n,i,s){var o=Gf[i],u=Gf[i+1],a=Gf[s],c=Gf[s+1];zp(Te,t,e),aO(Te,t,o,u);var f=Te[n]^Te[t],d=Te[n+1]^Te[t+1];Te[n]=d,Te[n+1]=f,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=f>>>24^d<<8,Te[e+1]=d>>>24^f<<8,zp(Te,t,e),aO(Te,t,a,c),f=Te[n]^Te[t],d=Te[n+1]^Te[t+1],Te[n]=f>>>16^d<<16,Te[n+1]=d>>>16^f<<16,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=d>>>31^f<<1,Te[e+1]=f>>>31^d<<1}var pO=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),pK=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Pr=new Uint8Array(pK.map(function(t){return t*2})),Te=new Uint32Array(32),Gf=new Uint32Array(32);function mO(t,e){var r=0;for(r=0;r<16;r++)Te[r]=t.h[r],Te[r+16]=pO[r];for(Te[24]=Te[24]^t.t,Te[25]=Te[25]^t.t/4294967296,e&&(Te[28]=~Te[28],Te[29]=~Te[29]),r=0;r<32;r++)Gf[r]=gO(t.b,4*r);for(r=0;r<12;r++)vo(0,8,16,24,Pr[r*16+0],Pr[r*16+1]),vo(2,10,18,26,Pr[r*16+2],Pr[r*16+3]),vo(4,12,20,28,Pr[r*16+4],Pr[r*16+5]),vo(6,14,22,30,Pr[r*16+6],Pr[r*16+7]),vo(0,10,20,30,Pr[r*16+8],Pr[r*16+9]),vo(2,12,22,24,Pr[r*16+10],Pr[r*16+11]),vo(4,14,16,26,Pr[r*16+12],Pr[r*16+13]),vo(6,8,18,28,Pr[r*16+14],Pr[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Te[r]^Te[r+16]}var Ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hc(t,e,r,n){Ao.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Ao[0]=t,e&&(Ao[1]=e.length),Ao[2]=1,Ao[3]=1,r&&Ao.set(r,32),n&&Ao.set(n,48);for(var i=0;i<16;i++)this.h[i]=pO[i]^gO(Ao,i*4);e&&(yO(this,e),this.c=128)}hc.prototype.update=function(t){return Eo(t!=null,"input must be Uint8Array or Buffer"),yO(this,t),this};hc.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Eo(e.length>=this.outlen,"out must have at least outlen bytes of space"),mK(this,e),t==="hex"?yK(e):e};hc.prototype.final=hc.prototype.digest;hc.ready=function(t){jf.ready(function(){t()})};function yO(t,e){for(var r=0;r>2]>>8*(r&3);return e}function yK(t){for(var e="",r=0;r=uO,"outlen must be at least "+uO+", was given "+e),Eo(e<=cO,"outlen must be at most "+cO+", was given "+e),r!=null&&Eo(r.length>=lO,"key must be at least "+lO+", was given "+r.length),r!=null&&Eo(r.length<=fO,"key must be at most "+fO+", was given "+r.length),n!=null&&Eo(n.length===hO,"salt must be exactly "+hO+", was given "+n.length),i!=null&&Eo(i.length===dO,"personal must be exactly "+dO+", was given "+i.length)),new wO(e,r,n,i)};Jr.exports.ready=function(t){jf.ready(function(){t()})};Jr.exports.WASM_SUPPORTED=jf.SUPPORTED;Jr.exports.WASM_LOADED=!1;var uO=Jr.exports.BYTES_MIN=16,cO=Jr.exports.BYTES_MAX=64,yye=Jr.exports.BYTES=32,lO=Jr.exports.KEYBYTES_MIN=16,fO=Jr.exports.KEYBYTES_MAX=64,wye=Jr.exports.KEYBYTES=32,hO=Jr.exports.SALTBYTES=16,dO=Jr.exports.PERSONALBYTES=16;jf.ready(function(t){t||(Jr.exports.WASM_LOADED=!0,wO=jf)})});var vO=B(Qp=>{"use strict";h();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.Code=void 0;var vK=YA(),AK=32,JA=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return p.Buffer.from(this.hex,"hex")}computeHash(){let e=vK(AK).update(this.valueOf()).digest();return p.Buffer.from(e)}};Qp.Code=JA});var XA=B(Kp=>{"use strict";h();Object.defineProperty(Kp,"__esModule",{value:!0});Kp.CodeMetadata=void 0;var dc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBytes(e){return t.fromBuffer(p.Buffer.from(e))}static fromBuffer(e){if(e.length{"use strict";h();var EK=Ki&&Ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bK=Ki&&Ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SK=Ki&&Ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EK(e,t,r);return bK(e,t),e};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ContractFunction=void 0;var IK=SK(Ie()),ZA=class t{constructor(e){if(this.name=e,e==null)throw new IK.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Ki.ContractFunction=ZA});var rE=B(Wp=>{"use strict";h();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.Compatibility=void 0;var TK=Ve(),tE=class{static guardAddressIsSetAndNonZero(e,r,n){!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==TK.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`)}};Wp.Compatibility=tE});var Ms=B($p=>{"use strict";h();Object.defineProperty($p,"__esModule",{value:!0});$p.TransactionPayload=void 0;var nE=class t{constructor(e){this.data=p.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=p.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>p.Buffer.from(e,"hex"))}length(){return p.Buffer.from(this.data).length}};$p.TransactionPayload=nE});var gc=B(Yp=>{"use strict";h();Object.defineProperty(Yp,"__esModule",{value:!0});Yp.TransactionBuilder=void 0;var _K=hr(),CK=Xr(),NK=Ms(),iE=class{constructor(e){this.config=e.config,this.sender=e.sender,this.receiver=e.receiver,this.dataParts=e.dataParts,this.providedGasLimit=e.gasLimit,this.addDataMovementGas=e.addDataMovementGas,this.amount=e.amount}computeGasLimit(e){return this.addDataMovementGas?this.config.minGasLimit+this.config.gasLimitPerByte*BigInt(e.length())+this.providedGasLimit:this.providedGasLimit}buildTransactionPayload(){let e=this.dataParts.join(_K.ARGUMENTS_SEPARATOR);return new NK.TransactionPayload(e)}build(){let e=this.buildTransactionPayload(),r=this.computeGasLimit(e);return new CK.Transaction({sender:this.sender.bech32(),receiver:this.receiver.bech32(),gasLimit:r,value:this.amount||0n,data:e.valueOf(),chainID:this.config.chainID})}};Yp.TransactionBuilder=iE});var AO=B(Jp=>{"use strict";h();Object.defineProperty(Jp,"__esModule",{value:!0});Jp.DelegationTransactionsFactory=void 0;var xK=Ve(),OK=hr(),DK=Ie(),fn=qn(),Zr=gc(),sE=class{constructor(e){this.config=e.config,this.argSerializer=new fn.ArgSerializer}createTransactionForNewDelegationContract(e){let r=["createNewDelegationContract",...this.argSerializer.valuesToStrings([new fn.BigUIntValue(e.totalDelegationCap),new fn.BigUIntValue(e.serviceFee)])],n=this.config.gasLimitCreateDelegationContract+this.config.additionalGasLimitForDelegationOperations;return new Zr.TransactionBuilder({config:this.config,sender:e.sender,receiver:xK.Address.fromBech32(OK.DELEGATION_MANAGER_SC_ADDRESS),dataParts:r,gasLimit:n,addDataMovementGas:!0,amount:e.amount}).build()}createTransactionForAddingNodes(e){if(e.publicKeys.length!==e.signedMessages.length)throw new DK.Err("The number of public keys should match the number of signed messages");let r=e.signedMessages.map(o=>new fn.BytesValue(p.Buffer.from(o))),n=this.argSerializer.valuesToStrings(r),i=e.publicKeys.length,s=["addNodes"];for(let o=0;o{h();var EO=(rr(),_e(fr)),bO=SO.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function u(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(f){var d=s[f];return typeof d=="string"?d:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function a(c,f){var d,w,A,T,x=n,R,V=f[c],U=V!=null&&(V instanceof EO||EO.isBigNumber(V));switch(V&&typeof V=="object"&&typeof V.toJSON=="function"&&(V=V.toJSON(c)),typeof o=="function"&&(V=o.call(f,c,V)),typeof V){case"string":return U?V:u(V);case"number":return isFinite(V)?String(V):"null";case"boolean":case"null":case"bigint":return String(V);case"object":if(!V)return"null";if(n+=i,R=[],Object.prototype.toString.apply(V)==="[object Array]"){for(T=V.length,d=0;d{h();var Xp=null,PK=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,RK=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,BK=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},s,o=function(x){throw{name:"SyntaxError",message:x,at:r,text:s}},u=function(x){return x&&x!==n&&o("Expected '"+x+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},a=function(){var x,R="";for(n==="-"&&(R="-",u("-"));n>="0"&&n<="9";)R+=n,u();if(n===".")for(R+=".";u()&&n>="0"&&n<="9";)R+=n;if(n==="e"||n==="E")for(R+=n,u(),(n==="-"||n==="+")&&(R+=n,u());n>="0"&&n<="9";)R+=n,u();if(x=+R,!isFinite(x))o("Bad number");else return Xp==null&&(Xp=(rr(),_e(fr))),R.length>15?e.storeAsString?R:e.useNativeBigInt?BigInt(R):new Xp(R):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(x):new Xp(x):x},c=function(){var x,R,V="",U;if(n==='"')for(var Q=r;u();){if(n==='"')return r-1>Q&&(V+=s.substring(Q,r-1)),u(),V;if(n==="\\"){if(r-1>Q&&(V+=s.substring(Q,r-1)),u(),n==="u"){for(U=0,R=0;R<4&&(x=parseInt(u(),16),!!isFinite(x));R+=1)U=U*16+x;V+=String.fromCharCode(U)}else if(typeof i[n]=="string")V+=i[n];else break;Q=r}}o("Bad string")},f=function(){for(;n&&n<=" ";)u()},d=function(){switch(n){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}o("Unexpected '"+n+"'")},w,A=function(){var x=[];if(n==="["){if(u("["),f(),n==="]")return u("]"),x;for(;n;){if(x.push(w()),f(),n==="]")return u("]"),x;u(","),f()}}o("Bad array")},T=function(){var x,R=Object.create(null);if(n==="{"){if(u("{"),f(),n==="}")return u("}"),R;for(;n;){if(x=c(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(R,x)&&o('Duplicate key "'+x+'"'),PK.test(x)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():R[x]=w():RK.test(x)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():R[x]=w():R[x]=w(),f(),n==="}")return u("}"),R;u(","),f()}}o("Bad object")};return w=function(){switch(f(),n){case"{":return T();case"[":return A();case'"':return c();case"-":return a();default:return n>="0"&&n<="9"?a():d()}},function(x,R){var V;return s=x+"",r=0,n=" ",V=w(),f(),n&&o("Syntax error"),typeof R=="function"?function U(Q,L){var k,H,q=Q[L];return q&&typeof q=="object"&&Object.keys(q).forEach(function(v){H=U(q,v),H!==void 0?q[v]=H:delete q[v]}),R.call(Q,L,q)}({"":V},""):V}};TO.exports=BK});var oE=B((qye,Zp)=>{h();var CO=IO().stringify,NO=_O();Zp.exports=function(t){return{parse:NO(t),stringify:CO}};Zp.exports.parse=NO();Zp.exports.stringify=CO});var OO=B(pc=>{"use strict";h();var MK=pc&&pc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pc,"__esModule",{value:!0});pc.RelayedTransactionsFactory=void 0;var LK=MK((rr(),_e(fr))),e0=Ve(),t0=Ie(),zf=qn(),xO=Xr(),FK=oE(),aE=class{constructor(e){this.config=e.config}createRelayedV1Transaction(e){if(!e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let r=this.prepareInnerTransactionForRelayedV1(e.innerTransaction),n=`relayedTx@${p.Buffer.from(r).toString("hex")}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=this.config.minGasLimit+i+e.innerTransaction.gasLimit;return new xO.Transaction({chainID:this.config.chainID,sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,gasLimit:s,data:p.Buffer.from(n)})}createRelayedV2Transaction(e){if(e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let{argumentsString:r}=new zf.ArgSerializer().valuesToString([new zf.AddressValue(e0.Address.fromBech32(e.innerTransaction.receiver)),new zf.U64Value(new LK.default(e.innerTransaction.nonce.toString())),new zf.BytesValue(p.Buffer.from(e.innerTransaction.data)),new zf.BytesValue(p.Buffer.from(e.innerTransaction.signature))]),n=`relayedTxV2@${r}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=e.innerTransactionGasLimit+this.config.minGasLimit+i;return new xO.Transaction({sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,value:0n,gasLimit:s,chainID:this.config.chainID,data:p.Buffer.from(n),version:e.innerTransaction.version,options:e.innerTransaction.options})}prepareInnerTransactionForRelayedV1(e){let r={nonce:e.nonce,sender:e0.Address.fromBech32(e.sender).pubkey().toString("base64"),receiver:e0.Address.fromBech32(e.receiver).pubkey().toString("base64"),value:e.value,gasPrice:e.gasPrice,gasLimit:e.gasLimit,data:p.Buffer.from(e.data).toString("base64"),signature:p.Buffer.from(e.signature).toString("base64"),chainID:p.Buffer.from(e.chainID).toString("base64"),version:e.version,options:e.options.valueOf()==0?void 0:e.options,guardian:e.guardian?e0.Address.fromBech32(e.guardian).pubkey().toString("base64"):void 0,guardianSignature:e.guardianSignature.length?p.Buffer.from(e.guardianSignature).toString("base64"):void 0,sndUserName:e.senderUsername?p.Buffer.from(e.senderUsername).toString("base64"):void 0,rcvUserName:e.receiverUsername?p.Buffer.from(e.receiverUsername).toString("base64"):void 0};return FK.stringify(r)}};pc.RelayedTransactionsFactory=aE});var DO=B(r0=>{"use strict";h();Object.defineProperty(r0,"__esModule",{value:!0});r0.ArgumentErrorContext=void 0;var UK=Ie(),uE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new UK.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) +Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};r0.ArgumentErrorContext=uE});var n0=B(qa=>{"use strict";h();var qK=qa&&qa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qa,"__esModule",{value:!0});qa.NativeSerializer=void 0;var VK=qK((rr(),_e(fr))),kK=Ve(),cE=Ie(),HK=Ru(),GK=DO(),ye=dr(),jK;(function(t){function e(L,k){L=L||[],r(L,k),n(k)&&(L=i(L,k));let H=k.input,q=[];for(let v=0;v0&&k[0].type.getCardinality().isComposite()&&(q=1/0,v=!0);for(let C of k){if(C.type.getCardinality().isSingular())break;H-=1}return{min:H,max:q,variadic:v}}t.getArgumentsCardinality=s;function o(L,k,H){if(L&&L.belongsToTypesystem)return L;if(k instanceof ye.OptionType)return u(L,k,H);if(k instanceof ye.OptionalType)return a(L,k,H);if(k instanceof ye.VariadicType)return c(L,k,H);if(k instanceof ye.CompositeType)return d(L,k,H);if(k instanceof ye.TupleType)return w(L,k,H);if(k instanceof ye.StructType)return A(L,k,H);if(k instanceof ye.ListType)return f(L,k,H);if(k instanceof ye.PrimitiveType)return T(L,k,H);if(k instanceof ye.EnumType)return x(L,k,H);H.throwError(`convertToTypedValue: unhandled type ${k}`)}function u(L,k,H){if(L==null)return ye.OptionValue.newMissing();let q=o(L,k.getFirstTypeParameter(),H);return ye.OptionValue.newProvided(q)}function a(L,k,H){if(L==null)return new ye.OptionalValue(k);let q=o(L,k.getFirstTypeParameter(),H);return new ye.OptionalValue(k,q)}function c(L,k,H){if(k.isCounted)throw new cE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');L==null&&(L=[]),L.map===void 0&&H.convertError(L,"Variadic");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.VariadicValue(k,q)}function f(L,k,H){L.map===void 0&&H.convertError(L,"List");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.List(k,q)}function d(L,k,H){let q=[],v=k.getTypeParameters();H.guardSameLength(L,v);for(let C=0;C{"use strict";h();Object.defineProperty(i0,"__esModule",{value:!0});i0.TokenTransfersDataBuilder=void 0;var zK=fc(),pi=dr(),QK=Ca(),lE=class{constructor(){this.tokenComputer=new QK.TokenComputer,this.argsSerializer=new zK.ArgSerializer}buildDataPartsForESDTTransfer(e){return["ESDTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(e.token.identifier),new pi.BigUIntValue(e.amount)])]}buildDataPartsForSingleESDTNFTTransfer(e,r){let n=e.token,i=this.tokenComputer.extractIdentifierFromExtendedIdentifier(n.identifier);return["ESDTNFTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(i),new pi.BigUIntValue(n.nonce),new pi.BigUIntValue(e.amount),new pi.AddressValue(r)])]}buildDataPartsForMultiESDTNFTTransfer(e,r){let n=[new pi.AddressValue(e),new pi.U32Value(r.length)];for(let s of r){let o=this.tokenComputer.extractIdentifierFromExtendedIdentifier(s.token.identifier);n.push(new pi.TokenIdentifierValue(o),new pi.BigUIntValue(s.token.nonce),new pi.BigUIntValue(s.amount))}return["MultiESDTNFTTransfer",...this.argsSerializer.valuesToStrings(n)]}};i0.TokenTransfersDataBuilder=lE});var dE=B(a0=>{"use strict";h();Object.defineProperty(a0,"__esModule",{value:!0});a0.SmartContractTransactionsFactory=void 0;var PO=Ve(),RO=hr(),BO=Ie(),KK=oo(),s0=qn(),WK=n0(),$K=Ca(),o0=Ru(),YK=fE(),Qf=gc(),hE=class{constructor(e){this.config=e.config,this.abi=e.abi,this.tokenComputer=new $K.TokenComputer,this.dataArgsBuilder=new YK.TokenTransfersDataBuilder}createTransactionForDeploy(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=[o0.byteArrayToHex(e.bytecode),o0.byteArrayToHex(RO.VM_TYPE_WASM_VM),a.toString()],f=this.abi?.constructorDefinition,d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:PO.Address.fromBech32(RO.CONTRACT_DEPLOY_ADDRESS),dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}createTransactionForExecute(e){let r=e.arguments||[],n=e.tokenTransfers||[],i=e.nativeTransferAmount??0n,s=n.length;if(i&&s)throw new BO.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)");let o=e.contract,u=[];if(s===1){let f=n[0];this.tokenComputer.isFungible(f.token)?u=this.dataArgsBuilder.buildDataPartsForESDTTransfer(f):(u=this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(f,o),o=e.sender)}else s>1&&(u=this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(o,n),o=e.sender);u.push(u.length?o0.utf8ToHex(e.function):e.function);let a=this.abi?.getEndpoint(e.function),c=this.argsToDataParts(r,a);return u.push(...c),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:o,dataParts:u,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:i}).build()}createTransactionForUpgrade(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=["upgradeContract",o0.byteArrayToHex(e.bytecode),a.toString()],f=this.getEndpointForUpgrade(),d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}getEndpointForUpgrade(){if(this.abi)try{return this.abi.getEndpoint("upgrade")}catch{return KK.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."),this.abi.constructorDefinition}}createTransactionForClaimingDeveloperRewards(e){let r=["ClaimDeveloperRewards"];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitClaimDeveloperRewards,addDataMovementGas:!1}).build()}createTransactionForChangingOwnerAddress(e){let r=["ChangeOwnerAddress",PO.Address.fromBech32(e.newOwner.bech32()).toHex()];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitChangeOwnerAddress,addDataMovementGas:!1}).build()}argsToDataParts(e,r){if(r){let n=WK.NativeSerializer.nativeToTypedValues(e,r);return new s0.ArgSerializer().valuesToStrings(n)}if(this.areArgsOfTypedValue(e))return new s0.ArgSerializer().valuesToStrings(e);throw new BO.Err("Can't convert args to TypedValues")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}};a0.SmartContractTransactionsFactory=hE});var MO=B(u0=>{"use strict";h();Object.defineProperty(u0,"__esModule",{value:!0});u0.TokenManagementTransactionsFactory=void 0;var Wi=Ve(),$i=hr(),JK=oo(),Z=qn(),Yt=gc(),gE=class{constructor(e){this.config=e.config,this.argSerializer=new Z.ArgSerializer,this.trueAsString="true",this.falseAsString="false"}createTransactionForIssuingFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.initialSupply),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issue",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueSemiFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueNonFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["registerMetaESDT",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringAndSettingRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue(e.tokenType),new Z.BigUIntValue(e.numDecimals)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForSettingBurnRoleGlobally(e){let r=["setBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForUnsettingBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleLocalMint&&r.push(new Z.StringValue("ESDTRoleLocalMint")),e.addRoleLocalBurn&&r.push(new Z.StringValue("ESDTRoleLocalBurn")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnSemiFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTAddQuantity&&r.push(new Z.StringValue("ESDTRoleNFTAddQuantity")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnMetaESDT(e){return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(e)}createTransactionForSettingSpecialRoleOnNonFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTUpdateAttributes&&r.push(new Z.StringValue("ESDTRoleNFTUpdateAttributes")),e.addRoleNFTAddURI&&r.push(new Z.StringValue("ESDTRoleNFTAddURI")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForCreatingNFT(e){let r=["ESDTNFTCreate",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.initialQuantity),new Z.StringValue(e.name),new Z.BigUIntValue(e.royalties),new Z.StringValue(e.hash),new Z.BytesValue(p.Buffer.from(e.attributes)),...e.uris.map(s=>new Z.StringValue(s))])],n=e.name+e.hash+e.attributes+e.uris.join(""),i=this.config.gasLimitStorePerByte+BigInt(n.length);return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftCreate+i,addDataMovementGas:!0}).build()}createTransactionForPausing(e){let r=["pause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForUnpausing(e){let r=["unPause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForFreezing(e){let r=["freeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForUnfreezing(e){let r=["UnFreeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForWiping(e){let r=["wipe",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitWiping,addDataMovementGas:!0}).build()}createTransactionForLocalMint(e){let r=["ESDTLocalMint",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToMint)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalMint,addDataMovementGas:!0}).build()}createTransactionForLocalBurning(e){let r=["ESDTLocalBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalBurn,addDataMovementGas:!0}).build()}createTransactionForUpdatingAttributes(e){let r=["ESDTNFTUpdateAttributes",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BytesValue(p.Buffer.from(e.attributes))])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftUpdateAttributes,addDataMovementGas:!0}).build()}createTransactionForAddingQuantity(e){let r=["ESDTNFTAddQuantity",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToAdd)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftAddQuantity,addDataMovementGas:!0}).build()}createTransactionForBurningQuantity(e){let r=["ESDTNFTBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftBurn,addDataMovementGas:!0}).build()}notifyAboutUnsettingBurnRoleGlobally(){JK.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); - } - boolToString(value) { - if (value) { - return this.trueAsString; - } - return this.falseAsString; - } - }; - exports2.TokenManagementTransactionsFactory = TokenManagementTransactionsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js -var require_transactionsFactoryConfig = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionsFactoryConfig = void 0; - var constants_1 = require_constants(); - var TransactionsFactoryConfig2 = class { - constructor(options) { - this.chainID = options.chainID; - this.addressHrp = constants_1.DEFAULT_HRP; - this.minGasLimit = 50000n; - this.gasLimitPerByte = 1500n; - this.gasLimitIssue = 60000000n; - this.gasLimitToggleBurnRoleGlobally = 60000000n; - this.gasLimitEsdtLocalMint = 300000n; - this.gasLimitEsdtLocalBurn = 300000n; - this.gasLimitSetSpecialRole = 60000000n; - this.gasLimitPausing = 60000000n; - this.gasLimitFreezing = 60000000n; - this.gasLimitWiping = 60000000n; - this.gasLimitEsdtNftCreate = 3000000n; - this.gasLimitEsdtNftUpdateAttributes = 1000000n; - this.gasLimitEsdtNftAddQuantity = 1000000n; - this.gasLimitEsdtNftBurn = 1000000n; - this.gasLimitStorePerByte = 10000n; - this.issueCost = 50000000000000000n; - this.gasLimitStake = 5000000n; - this.gasLimitUnstake = 5000000n; - this.gasLimitUnbond = 5000000n; - this.gasLimitCreateDelegationContract = 50000000n; - this.gasLimitDelegationOperations = 1000000n; - this.additionalGasLimitPerValidatorNode = 6000000n; - this.additionalGasLimitForDelegationOperations = 10000000n; - this.gasLimitSaveKeyValue = 100000n; - this.gasLimitPersistPerByte = 1000n; - this.gasLimitSetGuardian = 250000n; - this.gasLimitGuardAccount = 250000n; - this.gasLimitUnguardAccount = 250000n; - this.gasLimitESDTTransfer = 200000n; - this.gasLimitESDTNFTTransfer = 200000n; - this.gasLimitMultiESDTNFTTransfer = 200000n; - this.gasLimitClaimDeveloperRewards = 6000000n; - this.gasLimitChangeOwnerAddress = 6000000n; - } - }; - exports2.TransactionsFactoryConfig = TransactionsFactoryConfig2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js -var require_transferTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransferTransactionsFactory = void 0; - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var tokens_1 = require_tokens(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); - var transactionBuilder_1 = require_transactionBuilder(); - var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; - var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; - var TransferTransactionsFactory2 = class { - /** - * Should be instantiated using `Config` and `TokenComputer`. - * Instantiating this class using GasEstimator represents the legacy version of this class. - * The legacy version contains methods like `createEGLDTransfer`, `createESDTTransfer`, `createESDTNFTTransfer` and `createMultiESDTNFTTransfer`. - * This was done in order to minimize breaking changes in client code. - */ - constructor(options) { - if (this.isGasEstimator(options)) { - this.gasEstimator = options; - } else { - this.config = options.config; - this.tokenComputer = new tokens_1.TokenComputer(); - this.tokenTransfersDataBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); - } - } - isGasEstimator(options) { - return typeof options === "object" && typeof options.forEGLDTransfer === "function" && typeof options.forESDTTransfer === "function" && typeof options.forESDTNFTTransfer === "function" && typeof options.forMultiESDTNFTTransfer === "function"; - } - isGasEstimatorDefined() { - return this.gasEstimator !== void 0; - } - ensureMembersAreDefined() { - if (this.config === void 0) { - throw new errors_1.Err("'config' is not defined"); - } - if (this.tokenTransfersDataBuilder === void 0) { - throw new errors_1.Err("`dataArgsBuilder is not defined`"); - } - if (this.tokenComputer === void 0) { - throw new errors_1.Err("`tokenComputer is not defined`"); - } - } - createTransactionForNativeTokenTransfer(options) { - this.ensureMembersAreDefined(); - const data = options.data || new Uint8Array(); - return new transaction_1.Transaction({ - sender: options.sender.bech32(), - receiver: options.receiver.bech32(), - chainID: this.config.chainID, - gasLimit: this.computeGasForMoveBalance(this.config, data), - data, - value: options.nativeAmount - }); - } - createTransactionForESDTTokenTransfer(options) { - this.ensureMembersAreDefined(); - const numberOfTransfers = options.tokenTransfers.length; - if (numberOfTransfers === 0) { - throw new errors_1.ErrBadUsage("No token transfer has been provided"); - } - if (numberOfTransfers === 1) { - return this.createSingleESDTTransferTransaction(options); - } - const dataParts = this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(options.receiver, options.tokenTransfers); - const extraGasForTransfer = this.config.gasLimitMultiESDTNFTTransfer * BigInt(numberOfTransfers) + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: extraGasForTransfer, - addDataMovementGas: true - }).build(); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForNativeTokenTransfer} instead. - */ - createEGLDTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method."); - } - const dataLength = args.data?.length() || 0; - const estimatedGasLimit = this.gasEstimator.forEGLDTransfer(dataLength); - return new transaction_1.Transaction({ - nonce: args.nonce, - value: args.value, - receiver: args.receiver, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: args.data, - chainID: args.chainID - }); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createESDTTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - // The token identifier - smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), - // The transfered amount - new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()) - ]); - const data = `ESDTTransfer@${argumentsString}`; - const transactionPayload = new transactionPayload_1.TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; - const estimatedGasLimit = this.gasEstimator.forESDTTransfer(dataLength); - return new transaction_1.Transaction({ - nonce: args.nonce, - receiver: args.receiver, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: transactionPayload, - chainID: args.chainID - }); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createESDTNFTTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - // The token identifier - smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), - // The nonce of the token - new smartcontracts_1.U64Value(args.tokenTransfer.nonce), - // The transferred quantity - new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()), - // The destination address - new smartcontracts_1.AddressValue(args.destination) - ]); - const data = `ESDTNFTTransfer@${argumentsString}`; - const transactionPayload = new transactionPayload_1.TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; - const estimatedGasLimit = this.gasEstimator.forESDTNFTTransfer(dataLength); - return new transaction_1.Transaction({ - nonce: args.nonce, - receiver: args.sender, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: transactionPayload, - chainID: args.chainID - }); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createMultiESDTNFTTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); - } - const parts = [ - // The destination address - new smartcontracts_1.AddressValue(args.destination), - // Number of tokens - new smartcontracts_1.U16Value(args.tokenTransfers.length) - ]; - for (const payment of args.tokenTransfers) { - parts.push(...[ - // The token identifier - smartcontracts_1.BytesValue.fromUTF8(payment.tokenIdentifier), - // The nonce of the token - new smartcontracts_1.U64Value(payment.nonce), - // The transfered quantity - new smartcontracts_1.BigUIntValue(payment.valueOf()) - ]); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString(parts); - const data = `MultiESDTNFTTransfer@${argumentsString}`; - const transactionPayload = new transactionPayload_1.TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; - const estimatedGasLimit = this.gasEstimator.forMultiESDTNFTTransfer(dataLength, args.tokenTransfers.length); - return new transaction_1.Transaction({ - nonce: args.nonce, - receiver: args.sender, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: transactionPayload, - chainID: args.chainID - }); - } - createSingleESDTTransferTransaction(options) { - this.ensureMembersAreDefined(); - let dataParts = []; - const transfer = options.tokenTransfers[0]; - let extraGasForTransfer = 0n; - let receiver = options.receiver; - if (this.tokenComputer.isFungible(transfer.token)) { - dataParts = this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(transfer); - extraGasForTransfer = this.config.gasLimitESDTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_TRANSFER); - } else { - dataParts = this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); - extraGasForTransfer = this.config.gasLimitESDTNFTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); - receiver = options.sender; - } - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver, - dataParts, - gasLimit: extraGasForTransfer, - addDataMovementGas: true - }).build(); - } - computeGasForMoveBalance(config, data) { - return config.minGasLimit + config.gasLimitPerByte * BigInt(data.length); - } - }; - exports2.TransferTransactionsFactory = TransferTransactionsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js -var require_accountTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AccountTransactionsFactory = void 0; - var address_1 = require_address(); - var transactionBuilder_1 = require_transactionBuilder(); - var AccountTransactionsFactory = class { - constructor(options) { - this.config = options.config; - } - createTransactionForSavingKeyValue(options) { - const functionName = "SaveKeyValue"; - const keyValueParts = this.computeDataPartsForSavingKeyValue(options.keyValuePairs); - const dataParts = [functionName, ...keyValueParts]; - const extraGas = this.computeExtraGasForSavingKeyValue(options.keyValuePairs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: extraGas, - addDataMovementGas: true - }).build(); - } - computeExtraGasForSavingKeyValue(keyValuePairs) { - let extraGas = 0n; - keyValuePairs.forEach((value, key) => { - extraGas += this.config.gasLimitPersistPerByte * BigInt(key.length + value.length) + this.config.gasLimitStorePerByte * BigInt(value.length); - }); - return extraGas + this.config.gasLimitSaveKeyValue; - } - computeDataPartsForSavingKeyValue(keyValuePairs) { - const dataParts = []; - keyValuePairs.forEach((value, key) => { - dataParts.push(...[import_buffer.Buffer.from(key).toString("hex"), import_buffer.Buffer.from(value).toString("hex")]); - }); - return dataParts; - } - createTransactionForSettingGuardian(options) { - const dataParts = [ - "SetGuardian", - address_1.Address.fromBech32(options.guardianAddress.bech32()).toHex(), - import_buffer.Buffer.from(options.serviceID).toString("hex") - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitSetGuardian, - addDataMovementGas: true - }).build(); - } - createTransactionForGuardingAccount(options) { - const dataParts = ["GuardAccount"]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitGuardAccount, - addDataMovementGas: true - }).build(); - } - createTransactionForUnguardingAccount(options) { - const dataParts = ["UnGuardAccount"]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitUnguardAccount, - addDataMovementGas: true - }).build(); - } - }; - exports2.AccountTransactionsFactory = AccountTransactionsFactory; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js -var require_transactionsFactories = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_delegationTransactionsFactory(), exports2); - __exportStar2(require_relayedTransactionsFactory(), exports2); - __exportStar2(require_smartContractTransactionsFactory(), exports2); - __exportStar2(require_tokenManagementTransactionsFactory(), exports2); - __exportStar2(require_transactionsFactoryConfig(), exports2); - __exportStar2(require_transferTransactionsFactory(), exports2); - __exportStar2(require_accountTransactionsFactory(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js -var require_interactionChecker = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.InteractionChecker = void 0; - var errors = __importStar2(require_errors()); - var bignumber_js_1 = __importDefault2(require_bignumber()); - var InteractionChecker = class { - checkInteraction(interaction, definition) { - this.checkPayable(interaction, definition); - this.checkArguments(interaction, definition); - } - checkPayable(interaction, definition) { - let hasValue = !new bignumber_js_1.default(interaction.getValue().toString()).isZero(); - let isPayableInEGLD = definition.modifiers.isPayableInEGLD(); - if (hasValue && !isPayableInEGLD) { - throw new errors.ErrContractInteraction("cannot send EGLD value to non-payable"); - } - } - checkArguments(interaction, definition) { - let formalArguments = definition.input; - let actualArguments = interaction.getArguments(); - let numFormalArguments = formalArguments.length; - let numActualArguments = actualArguments.length; - if (numFormalArguments != numActualArguments) { - throw new errors.ErrContractInteraction(`bad arguments, expected: ${numFormalArguments}, got: ${numActualArguments}`); - } - for (let i2 = 0; i2 < numFormalArguments; i2++) { - let expectedType = formalArguments[i2].type; - let argument = actualArguments[i2]; - let actualType = argument.getType(); - let ok = expectedType.isAssignableFrom(actualType); - if (!ok) { - throw new errors.ErrContractInteraction(`type mismatch at index ${i2}, expected: ${expectedType}, got: ${actualType}`); - } - } - } - }; - exports2.InteractionChecker = InteractionChecker; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/query.js -var require_query = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/query.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Query = void 0; - var address_1 = require_address(); - var argSerializer_1 = require_argSerializer(); - var Query2 = class { - constructor(obj) { - this.caller = obj.caller || address_1.Address.empty(); - this.address = obj.address; - this.func = obj.func; - this.args = obj.args || []; - this.value = obj.value || 0; - } - getEncodedArguments() { - return new argSerializer_1.ArgSerializer().valuesToStrings(this.args); - } - }; - exports2.Query = Query2; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js -var require_interaction = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Interaction = void 0; - var address_1 = require_address(); - var compatibility_1 = require_compatibility(); - var constants_1 = require_constants(); - var tokens_1 = require_tokens(); - var transactionsFactories_1 = require_transactionsFactories(); - var interactionChecker_1 = require_interactionChecker(); - var query_1 = require_query(); - var Interaction = class { - constructor(contract, func, args) { - this.nonce = 0; - this.value = "0"; - this.gasLimit = 0; - this.gasPrice = void 0; - this.chainID = ""; - this.querent = address_1.Address.empty(); - this.sender = address_1.Address.empty(); - this.version = constants_1.TRANSACTION_VERSION_DEFAULT; - this.contract = contract; - this.function = func; - this.args = args; - this.tokenTransfers = []; - } - getContractAddress() { - return this.contract.getAddress(); - } - getFunction() { - return this.function; - } - getEndpoint() { - return this.contract.getEndpoint(this.function); - } - getArguments() { - return this.args; - } - getValue() { - return this.value; - } - getTokenTransfers() { - return this.tokenTransfers; - } - getGasLimit() { - return this.gasLimit; - } - getExplicitReceiver() { - return this.explicitReceiver; - } - buildTransaction() { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(this.sender, "'sender' of interaction", "use interaction.withSender()"); - const factoryConfig = new transactionsFactories_1.TransactionsFactoryConfig({ chainID: this.chainID.valueOf() }); - const factory = new transactionsFactories_1.SmartContractTransactionsFactory({ - config: factoryConfig - }); - const transaction = factory.createTransactionForExecute({ - sender: this.sender, - contract: this.contract.getAddress(), - function: this.function.valueOf(), - gasLimit: BigInt(this.gasLimit.valueOf()), - arguments: this.args, - nativeTransferAmount: BigInt(this.value.toString()), - tokenTransfers: this.tokenTransfers - }); - transaction.chainID = this.chainID.valueOf(); - transaction.nonce = BigInt(this.nonce.valueOf()); - transaction.version = this.version; - if (this.gasPrice) { - transaction.gasPrice = BigInt(this.gasPrice.valueOf()); - } - return transaction; - } - buildQuery() { - return new query_1.Query({ - address: this.contract.getAddress(), - func: this.function, - args: this.args, - // Value will be set using "withValue()". - value: this.value, - caller: this.querent - }); - } - withValue(value) { - this.value = value; - return this; - } - withSingleESDTTransfer(transfer) { - this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); - return this; - } - withSingleESDTNFTTransfer(transfer) { - this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); - return this; - } - withMultiESDTNFTTransfer(transfers) { - this.tokenTransfers = transfers.map((transfer) => new tokens_1.TokenTransfer(transfer)); - return this; - } - withGasLimit(gasLimit) { - this.gasLimit = gasLimit; - return this; - } - withGasPrice(gasPrice) { - this.gasPrice = gasPrice; - return this; - } - withNonce(nonce) { - this.nonce = nonce; - return this; - } - useThenIncrementNonceOf(account) { - return this.withNonce(account.getNonceThenIncrement()); - } - withChainID(chainID) { - this.chainID = chainID; - return this; - } - withSender(sender) { - this.sender = sender; - return this; - } - withVersion(version2) { - this.version = version2; - return this; - } - /** - * Sets the "caller" field on contract queries. - */ - withQuerent(querent) { - this.querent = querent; - return this; - } - withExplicitReceiver(receiver) { - this.explicitReceiver = receiver; - return this; - } - /** - * To perform custom checking, extend {@link Interaction} and override this method. - */ - check() { - new interactionChecker_1.InteractionChecker().checkInteraction(this, this.getEndpoint()); - return this; - } - }; - exports2.Interaction = Interaction; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js -var require_interface = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js -var require_dist = __commonJS({ - "node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bech32m = exports2.bech32 = void 0; - var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; - var ALPHABET_MAP = {}; - for (let z3 = 0; z3 < ALPHABET.length; z3++) { - const x3 = ALPHABET.charAt(z3); - ALPHABET_MAP[x3] = z3; - } - function polymodStep(pre) { - const b4 = pre >> 25; - return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; - } - function prefixChk(prefix) { - let chk = 1; - for (let i2 = 0; i2 < prefix.length; ++i2) { - const c4 = prefix.charCodeAt(i2); - if (c4 < 33 || c4 > 126) - return "Invalid prefix (" + prefix + ")"; - chk = polymodStep(chk) ^ c4 >> 5; - } - chk = polymodStep(chk); - for (let i2 = 0; i2 < prefix.length; ++i2) { - const v2 = prefix.charCodeAt(i2); - chk = polymodStep(chk) ^ v2 & 31; - } - return chk; - } - function convert(data, inBits, outBits, pad) { - let value = 0; - let bits = 0; - const maxV = (1 << outBits) - 1; - const result = []; - for (let i2 = 0; i2 < data.length; ++i2) { - value = value << inBits | data[i2]; - bits += inBits; - while (bits >= outBits) { - bits -= outBits; - result.push(value >> bits & maxV); - } - } - if (pad) { - if (bits > 0) { - result.push(value << outBits - bits & maxV); - } - } else { - if (bits >= inBits) - return "Excess padding"; - if (value << outBits - bits & maxV) - return "Non-zero padding"; - } - return result; - } - function toWords(bytes) { - return convert(bytes, 8, 5, true); - } - function fromWordsUnsafe(words) { - const res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - } - function fromWords(words) { - const res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - throw new Error(res); - } - function getLibraryFromEncoding(encoding) { - let ENCODING_CONST; - if (encoding === "bech32") { - ENCODING_CONST = 1; - } else { - ENCODING_CONST = 734539939; - } - function encode5(prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if (prefix.length + 7 + words.length > LIMIT) - throw new TypeError("Exceeds length limit"); - prefix = prefix.toLowerCase(); - let chk = prefixChk(prefix); - if (typeof chk === "string") - throw new Error(chk); - let result = prefix + "1"; - for (let i2 = 0; i2 < words.length; ++i2) { - const x3 = words[i2]; - if (x3 >> 5 !== 0) - throw new Error("Non 5-bit word"); - chk = polymodStep(chk) ^ x3; - result += ALPHABET.charAt(x3); - } - for (let i2 = 0; i2 < 6; ++i2) { - chk = polymodStep(chk); - } - chk ^= ENCODING_CONST; - for (let i2 = 0; i2 < 6; ++i2) { - const v2 = chk >> (5 - i2) * 5 & 31; - result += ALPHABET.charAt(v2); - } - return result; - } - function __decode(str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) - return str + " too short"; - if (str.length > LIMIT) - return "Exceeds length limit"; - const lowered = str.toLowerCase(); - const uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) - return "Mixed-case string " + str; - str = lowered; - const split = str.lastIndexOf("1"); - if (split === -1) - return "No separator character for " + str; - if (split === 0) - return "Missing prefix for " + str; - const prefix = str.slice(0, split); - const wordChars = str.slice(split + 1); - if (wordChars.length < 6) - return "Data too short"; - let chk = prefixChk(prefix); - if (typeof chk === "string") - return chk; - const words = []; - for (let i2 = 0; i2 < wordChars.length; ++i2) { - const c4 = wordChars.charAt(i2); - const v2 = ALPHABET_MAP[c4]; - if (v2 === void 0) - return "Unknown character " + c4; - chk = polymodStep(chk) ^ v2; - if (i2 + 6 >= wordChars.length) - continue; - words.push(v2); - } - if (chk !== ENCODING_CONST) - return "Invalid checksum for " + str; - return { prefix, words }; - } - function decodeUnsafe(str, LIMIT) { - const res = __decode(str, LIMIT); - if (typeof res === "object") - return res; - } - function decode6(str, LIMIT) { - const res = __decode(str, LIMIT); - if (typeof res === "object") - return res; - throw new Error(res); - } - return { - decodeUnsafe, - decode: decode6, - encode: encode5, - toWords, - fromWordsUnsafe, - fromWords - }; - } - exports2.bech32 = getLibraryFromEncoding("bech32"); - exports2.bech32m = getLibraryFromEncoding("bech32m"); - } -}); - -// node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js -var require_transaction_decoder = __commonJS({ - "node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenTransferProperties = exports2.TransactionMetadataTransfer = exports2.TransactionMetadata = exports2.TransactionToDecode = exports2.TransactionDecoder = void 0; - var bech32_1 = require_dist(); - var TransactionDecoder = class { - getTransactionMetadata(transaction) { - const metadata = this.getNormalTransactionMetadata(transaction); - const esdtMetadata = this.getEsdtTransactionMetadata(metadata); - if (esdtMetadata) { - return esdtMetadata; - } - const nftMetadata = this.getNftTransferMetadata(metadata); - if (nftMetadata) { - return nftMetadata; - } - const multiMetadata = this.getMultiTransferMetadata(metadata); - if (multiMetadata) { - return multiMetadata; - } - return metadata; - } - getNormalTransactionMetadata(transaction) { - const metadata = new TransactionMetadata(); - metadata.sender = transaction.sender; - metadata.receiver = transaction.receiver; - metadata.value = BigInt(transaction.value); - if (transaction.data) { - const decodedData = this.base64Decode(transaction.data); - const dataComponents = decodedData.split("@"); - const args = dataComponents.slice(1); - if (args.every((x3) => this.isSmartContractArgument(x3))) { - metadata.functionName = dataComponents[0]; - metadata.functionArgs = args; - } - if (metadata.functionName === "relayedTx" && metadata.functionArgs && metadata.functionArgs.length === 1) { - try { - const relayedTransaction = JSON.parse(this.hexToString(metadata.functionArgs[0])); - relayedTransaction.value = relayedTransaction.value.toString(); - relayedTransaction.sender = this.bech32Encode(this.base64ToHex(relayedTransaction.sender)); - relayedTransaction.receiver = this.bech32Encode(this.base64ToHex(relayedTransaction.receiver)); - return this.getNormalTransactionMetadata(relayedTransaction); - } catch (error) { - } - } - if (metadata.functionName === "relayedTxV2" && metadata.functionArgs && metadata.functionArgs.length === 4) { - try { - const relayedTransaction = new TransactionToDecode(); - relayedTransaction.sender = transaction.receiver; - relayedTransaction.receiver = this.bech32Encode(metadata.functionArgs[0]); - relayedTransaction.data = this.base64Encode(this.hexToString(metadata.functionArgs[2])); - relayedTransaction.value = "0"; - return this.getNormalTransactionMetadata(relayedTransaction); - } catch (error) { - } - } - } - return metadata; - } - getMultiTransferMetadata(metadata) { - if (metadata.sender !== metadata.receiver) { - return void 0; - } - if (metadata.functionName !== "MultiESDTNFTTransfer") { - return void 0; - } - const args = metadata.functionArgs; - if (!args) { - return void 0; - } - if (args.length < 3) { - return void 0; - } - if (!this.isAddressValid(args[0])) { - return void 0; - } - const receiver = this.bech32Encode(args[0]); - const transferCount = this.hexToNumber(args[1]); - const result = new TransactionMetadata(); - if (!result.transfers) { - result.transfers = []; - } - let index = 2; - for (let i2 = 0; i2 < transferCount; i2++) { - const identifier = this.hexToString(args[index++]); - const nonce = args[index++]; - const value = this.hexToBigInt(args[index++]); - if (nonce) { - result.transfers.push({ - value, - properties: { - collection: identifier, - identifier: `${identifier}-${nonce}` - } - }); - } else { - result.transfers.push({ - value, - properties: { - token: identifier - } - }); - } - } - result.sender = metadata.sender; - result.receiver = receiver; - if (args.length > index) { - result.functionName = this.hexToString(args[index++]); - result.functionArgs = args.slice(index++); - } - return result; - } - getNftTransferMetadata(metadata) { - if (metadata.sender !== metadata.receiver) { - return void 0; - } - if (metadata.functionName !== "ESDTNFTTransfer") { - return void 0; - } - const args = metadata.functionArgs; - if (!args) { - return void 0; - } - if (args.length < 4) { - return void 0; - } - if (!this.isAddressValid(args[3])) { - return void 0; - } - const collectionIdentifier = this.hexToString(args[0]); - const nonce = args[1]; - const value = this.hexToBigInt(args[2]); - const receiver = this.bech32Encode(args[3]); - const result = new TransactionMetadata(); - result.sender = metadata.sender; - result.receiver = receiver; - result.value = value; - if (args.length > 4) { - result.functionName = this.hexToString(args[4]); - result.functionArgs = args.slice(5); - } - result.transfers = [{ - value, - properties: { - collection: collectionIdentifier, - identifier: `${collectionIdentifier}-${nonce}` - } - }]; - return result; - } - base64Encode(str) { - return import_buffer.Buffer.from(str).toString("base64"); - } - base64Decode(str) { - return import_buffer.Buffer.from(str, "base64").toString("binary"); - } - hexToNumber(hex) { - return parseInt(hex, 16); - } - getEsdtTransactionMetadata(metadata) { - if (metadata.functionName !== "ESDTTransfer") { - return void 0; - } - const args = metadata.functionArgs; - if (!args) { - return void 0; - } - if (args.length < 2) { - return void 0; - } - const tokenIdentifier = this.hexToString(args[0]); - const value = this.hexToBigInt(args[1]); - const result = new TransactionMetadata(); - result.sender = metadata.sender; - result.receiver = metadata.receiver; - if (args.length > 2) { - result.functionName = this.hexToString(args[2]); - result.functionArgs = args.slice(3); - } - result.transfers = [{ - value, - properties: { - identifier: tokenIdentifier - } - }]; - result.value = value; - return result; - } - bech32Encode(address) { - const pubKey = import_buffer.Buffer.from(address, "hex"); - const words = bech32_1.bech32.toWords(pubKey); - return bech32_1.bech32.encode("erd", words); - } - isAddressValid(address) { - return import_buffer.Buffer.from(address, "hex").length == 32; - } - isSmartContractArgument(arg) { - if (!this.isHex(arg)) { - return false; - } - if (arg.length % 2 !== 0) { - return false; - } - return true; - } - isHex(value) { - return new RegExp(/[^a-f0-9]/gi).test(value) === false; - } - base64ToHex(str) { - return import_buffer.Buffer.from(str, "base64").toString("hex"); - } - hexToString(hex) { - return import_buffer.Buffer.from(hex, "hex").toString("ascii"); - } - hexToBigInt(hex) { - if (!hex) { - return BigInt(0); - } - return BigInt("0x" + hex); - } - }; - exports2.TransactionDecoder = TransactionDecoder; - var TransactionToDecode = class { - constructor() { - this.sender = ""; - this.receiver = ""; - this.data = ""; - this.value = "0"; - } - }; - exports2.TransactionToDecode = TransactionToDecode; - var TransactionMetadata = class { - constructor() { - this.sender = ""; - this.receiver = ""; - this.value = BigInt(0); - } - }; - exports2.TransactionMetadata = TransactionMetadata; - var TransactionMetadataTransfer = class { - constructor() { - this.value = BigInt(0); - } - }; - exports2.TransactionMetadataTransfer = TransactionMetadataTransfer; - var TokenTransferProperties = class { - }; - exports2.TokenTransferProperties = TokenTransferProperties; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js -var require_returnCode = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReturnCode = void 0; - var ReturnCode = class _ReturnCode { - constructor(text) { - this.text = text; - } - static fromBuffer(buffer) { - let text = buffer.toString(); - return new _ReturnCode(text); - } - toString() { - return this.text; - } - valueOf() { - return this.text; - } - equals(other) { - if (!other) { - return false; - } - return this.text == other.text; - } - isSuccess() { - return this.equals(_ReturnCode.Ok) || this.equals(_ReturnCode.None); - } - }; - exports2.ReturnCode = ReturnCode; - ReturnCode.None = new ReturnCode(""); - ReturnCode.Ok = new ReturnCode("ok"); - ReturnCode.FunctionNotFound = new ReturnCode("function not found"); - ReturnCode.FunctionWrongSignature = new ReturnCode("wrong signature for function"); - ReturnCode.ContractNotFound = new ReturnCode("contract not found"); - ReturnCode.UserError = new ReturnCode("user error"); - ReturnCode.OutOfGas = new ReturnCode("out of gas"); - ReturnCode.AccountCollision = new ReturnCode("account collision"); - ReturnCode.OutOfFunds = new ReturnCode("out of funds"); - ReturnCode.CallStackOverFlow = new ReturnCode("call stack overflow"); - ReturnCode.ContractInvalid = new ReturnCode("contract invalid"); - ReturnCode.ExecutionFailed = new ReturnCode("execution failed"); - ReturnCode.Unknown = new ReturnCode("unknown"); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js -var require_resultsParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ResultsParser = void 0; - var transaction_decoder_1 = require_transaction_decoder(); - var address_1 = require_address(); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var argSerializer_1 = require_argSerializer(); - var returnCode_1 = require_returnCode(); - var WellKnownEvents; - (function(WellKnownEvents2) { - WellKnownEvents2["OnTransactionCompleted"] = "completedTxEvent"; - WellKnownEvents2["OnSignalError"] = "signalError"; - WellKnownEvents2["OnWriteLog"] = "writeLog"; - })(WellKnownEvents || (WellKnownEvents = {})); - var WellKnownTopics; - (function(WellKnownTopics2) { - WellKnownTopics2["TooMuchGas"] = "@too much gas provided for processing"; - })(WellKnownTopics || (WellKnownTopics = {})); - var defaultResultsParserOptions = { - argsSerializer: new argSerializer_1.ArgSerializer() - }; - var ResultsParser = class { - constructor(options) { - options = { ...defaultResultsParserOptions, ...options }; - this.argsSerializer = options.argsSerializer; - } - /** - * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. - */ - parseQueryResponse(queryResponse, endpoint) { - let parts = queryResponse.getReturnDataParts(); - let values = this.argsSerializer.buffersToValues(parts, endpoint.output); - let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); - return { - returnCode, - returnMessage: queryResponse.returnMessage, - values, - firstValue: values[0], - secondValue: values[1], - thirdValue: values[2], - lastValue: values[values.length - 1] - }; - } - /** - * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. - */ - parseUntypedQueryResponse(queryResponse) { - let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); - return { - returnCode, - returnMessage: queryResponse.returnMessage, - values: queryResponse.getReturnDataParts() - }; - } - /** - * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. - */ - parseOutcome(transaction, endpoint) { - const untypedBundle = this.parseUntypedOutcome(transaction); - const typedBundle = this.parseOutcomeFromUntypedBundle(untypedBundle, endpoint); - return typedBundle; - } - /** - * @internal - * For internal use only. - */ - parseOutcomeFromUntypedBundle(bundle, endpoint) { - const values = this.argsSerializer.buffersToValues(bundle.values, endpoint.output); - return { - returnCode: bundle.returnCode, - returnMessage: bundle.returnMessage, - values, - firstValue: values[0], - secondValue: values[1], - thirdValue: values[2], - lastValue: values[values.length - 1] - }; - } - /** - * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. - */ - parseUntypedOutcome(transaction) { - let bundle; - let transactionMetadata = this.parseTransactionMetadata(transaction); - bundle = this.createBundleOnSimpleMoveBalance(transaction); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on simple move balance"); - return bundle; - } - bundle = this.createBundleOnInvalidTransaction(transaction); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on invalid transaction"); - return bundle; - } - bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.contractResults); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on easily found result with return data"); - return bundle; - } - bundle = this.createBundleOnSignalError(transaction.logs); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on signal error"); - return bundle; - } - bundle = this.createBundleOnTooMuchGasWarning(transaction.logs); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"); - return bundle; - } - bundle = this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(transaction.logs, transaction.sender); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"); - return bundle; - } - bundle = this.createBundleWithCustomHeuristics(transaction, transactionMetadata); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): with custom heuristics"); - return bundle; - } - bundle = this.createBundleWithFallbackHeuristics(transaction, transactionMetadata); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): with fallback heuristics"); - return bundle; - } - throw new errors_1.ErrCannotParseContractResults(`transaction ${transaction.hash.toString()}`); - } - parseTransactionMetadata(transaction) { - return new transaction_decoder_1.TransactionDecoder().getTransactionMetadata({ - sender: transaction.sender.bech32(), - receiver: transaction.receiver.bech32(), - data: transaction.data.toString("base64"), - value: transaction.value.toString() - }); - } - createBundleOnSimpleMoveBalance(transaction) { - let noResults = transaction.contractResults.items.length == 0; - let noLogs = transaction.logs.events.length == 0; - if (noResults && noLogs) { - return { - returnCode: returnCode_1.ReturnCode.None, - returnMessage: returnCode_1.ReturnCode.None.toString(), - values: [] - }; - } - return null; - } - createBundleOnInvalidTransaction(transaction) { - if (transaction.status.isInvalid()) { - if (transaction.receipt.data) { - return { - returnCode: returnCode_1.ReturnCode.OutOfFunds, - returnMessage: transaction.receipt.data, - values: [] - }; - } - } - return null; - } - createBundleOnEasilyFoundResultWithReturnData(results) { - let resultItemWithReturnData = results.items.find((item) => item.nonce.valueOf() != 0 && item.data.startsWith("@")); - if (!resultItemWithReturnData) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data); - let returnMessage = resultItemWithReturnData.returnMessage || returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - createBundleOnSignalError(logs) { - let eventSignalError = logs.findSingleOrNoneEvent(WellKnownEvents.OnSignalError); - if (!eventSignalError) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventSignalError.data); - let lastTopic = eventSignalError.getLastTopic(); - let returnMessage = lastTopic?.toString() || returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - createBundleOnTooMuchGasWarning(logs) { - let eventTooMuchGas = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.toString().startsWith(WellKnownTopics.TooMuchGas)) != void 0); - if (!eventTooMuchGas) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data); - let lastTopic = eventTooMuchGas.getLastTopic(); - let returnMessage = lastTopic?.toString() || returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - createBundleOnWriteLogWhereFirstTopicEqualsAddress(logs, address) { - let hexAddress = new address_1.Address(address.bech32()).hex(); - let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.hex() == hexAddress) != void 0); - if (!eventWriteLogWhereTopicIsSender) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventWriteLogWhereTopicIsSender.data); - let returnMessage = returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - /** - * Override this method (in a subclass of {@link ResultsParser}) if the basic heuristics of the parser are not sufficient. - */ - createBundleWithCustomHeuristics(_transaction, _transactionMetadata) { - return null; - } - createBundleWithFallbackHeuristics(transaction, transactionMetadata) { - let contractAddress = new address_1.Address(transactionMetadata.receiver); - for (const resultItem of transaction.contractResults.items) { - let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { - let addressIsSender = event.address.bech32() == transaction.sender.bech32(); - let firstTopicIsContract = event.topics[0]?.hex() == contractAddress.hex(); - return addressIsSender && firstTopicIsContract; - }); - if (writeLogWithReturnData) { - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(writeLogWithReturnData.data); - let returnMessage = returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - } - return null; - } - sliceDataFieldInParts(data) { - let startingIndex = 1; - if (data.startsWith("ESDTTransfer")) { - startingIndex = 3; - } else { - } - let parts = this.argsSerializer.stringToBuffers(data); - let returnCodePart = parts[startingIndex] || import_buffer.Buffer.from([]); - let returnDataParts = parts.slice(startingIndex + 1); - if (returnCodePart.length == 0) { - throw new errors_1.ErrCannotParseContractResults("no return code"); - } - let returnCode = returnCode_1.ReturnCode.fromBuffer(returnCodePart); - return { returnCode, returnDataParts }; - } - /** - * Legacy method, use "TransactionEventsParser.parseEvent()" instead. - */ - parseEvent(transactionEvent, eventDefinition) { - const topics = transactionEvent.topics.map((topic) => import_buffer.Buffer.from(topic.valueOf())).slice(1); - const legacyData = transactionEvent.dataPayload?.valueOf() || import_buffer.Buffer.from([]); - const dataItems = transactionEvent.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; - if (dataItems.length === 0) { - if (legacyData.length) { - dataItems.push(import_buffer.Buffer.from(legacyData)); - } - } - return this.doParseEvent({ topics, dataItems, eventDefinition }); - } - /** - * @internal - * For internal use only. - * - * Once the legacy "ResultParser" is deprecated & removed, this logic will be absorbed into "TransactionEventsParser". - */ - doParseEvent(options) { - const result = {}; - const indexedInputs = options.eventDefinition.inputs.filter((input) => input.indexed); - const decodedTopics = this.argsSerializer.buffersToValues(options.topics, indexedInputs); - for (let i2 = 0; i2 < indexedInputs.length; i2++) { - result[indexedInputs[i2].name] = decodedTopics[i2].valueOf(); - } - const nonIndexedInputs = options.eventDefinition.inputs.filter((input) => !input.indexed); - const decodedDataParts = this.argsSerializer.buffersToValues(options.dataItems, nonIndexedInputs); - for (let i2 = 0; i2 < nonIndexedInputs.length; i2++) { - result[nonIndexedInputs[i2].name] = decodedDataParts[i2].valueOf(); - } - return result; - } - }; - exports2.ResultsParser = ResultsParser; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js -var require_smartContract = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContract = void 0; - var address_1 = require_address(); - var compatibility_1 = require_compatibility(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var smartContractTransactionsFactory_1 = require_smartContractTransactionsFactory(); - var transactionsFactoryConfig_1 = require_transactionsFactoryConfig(); - var utils_1 = require_utils2(); - var codeMetadata_1 = require_codeMetadata2(); - var function_1 = require_function(); - var interaction_1 = require_interaction(); - var nativeSerializer_1 = require_nativeSerializer(); - var query_1 = require_query(); - var SmartContract = class { - /** - * Create a SmartContract object by providing its address on the Network. - */ - constructor(options = {}) { - this.address = address_1.Address.empty(); - this.methodsExplicit = {}; - this.methods = {}; - this.address = options.address || address_1.Address.empty(); - this.abi = options.abi; - if (this.abi) { - this.setupMethods(); - } - } - setupMethods() { - let contract = this; - let abi = this.getAbi(); - for (const definition of abi.getEndpoints()) { - let functionName = definition.name; - this.methodsExplicit[functionName] = function(args) { - let func = new function_1.ContractFunction(functionName); - let interaction = new interaction_1.Interaction(contract, func, args || []); - return interaction; - }; - this.methods[functionName] = function(args) { - let func = new function_1.ContractFunction(functionName); - let typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args || [], definition); - let interaction = new interaction_1.Interaction(contract, func, typedArgs || []); - return interaction; - }; - } - } - /** - * Sets the address, as on Network. - */ - setAddress(address) { - this.address = address; - } - /** - * Gets the address, as on Network. - */ - getAddress() { - return this.address; - } - getAbi() { - utils_1.guardValueIsSet("abi", this.abi); - return this.abi; - } - getEndpoint(name2) { - return this.getAbi().getEndpoint(name2); - } - /** - * Creates a {@link Transaction} for deploying the Smart Contract to the Network. - */ - deploy({ deployer, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(deployer, "'deployer' of SmartContract.deploy()", "pass the actual address to deploy()"); - const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); - const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ - config, - abi: this.abi - }); - const bytecode = import_buffer.Buffer.from(code2.toString(), "hex"); - const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); - const transaction = factory.createTransactionForDeploy({ - sender: deployer, - bytecode, - gasLimit: BigInt(gasLimit.valueOf()), - arguments: initArguments, - isUpgradeable: metadataAsJson.upgradeable, - isReadable: metadataAsJson.readable, - isPayable: metadataAsJson.payable, - isPayableBySmartContract: metadataAsJson.payableBySc - }); - transaction.setChainID(chainID); - transaction.setValue(value ?? 0); - transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); - return transaction; - } - getMetadataPropertiesAsObject(codeMetadata) { - let metadata; - if (codeMetadata) { - metadata = codeMetadata_1.CodeMetadata.fromBytes(import_buffer.Buffer.from(codeMetadata.toString(), "hex")); - } else { - metadata = new codeMetadata_1.CodeMetadata(); - } - const metadataAsJson = metadata.toJSON(); - return metadataAsJson; - } - /** - * Creates a {@link Transaction} for upgrading the Smart Contract on the Network. - */ - upgrade({ caller, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.upgrade()", "pass the actual address to upgrade()"); - this.ensureHasAddress(); - const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); - const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ - config, - abi: this.abi - }); - const bytecode = Uint8Array.from(import_buffer.Buffer.from(code2.toString(), "hex")); - const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); - const transaction = factory.createTransactionForUpgrade({ - sender: caller, - contract: this.getAddress(), - bytecode, - gasLimit: BigInt(gasLimit.valueOf()), - arguments: initArguments, - isUpgradeable: metadataAsJson.upgradeable, - isReadable: metadataAsJson.readable, - isPayable: metadataAsJson.payable, - isPayableBySmartContract: metadataAsJson.payableBySc - }); - transaction.setChainID(chainID); - transaction.setValue(value ?? 0); - transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); - return transaction; - } - /** - * Creates a {@link Transaction} for calling (a function of) the Smart Contract. - */ - call({ func, args, value, gasLimit, receiver, gasPrice, chainID, caller }) { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.call()", "pass the actual address to call()"); - this.ensureHasAddress(); - const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); - const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ - config, - abi: this.abi - }); - args = args || []; - value = value || 0; - const transaction = factory.createTransactionForExecute({ - sender: caller, - contract: receiver ? receiver : this.getAddress(), - function: func.toString(), - gasLimit: BigInt(gasLimit.valueOf()), - arguments: args - }); - transaction.setChainID(chainID); - transaction.setValue(value); - transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); - return transaction; - } - createQuery({ func, args, value, caller }) { - this.ensureHasAddress(); - return new query_1.Query({ - address: this.getAddress(), - func, - args, - value, - caller - }); - } - ensureHasAddress() { - if (!this.getAddress().bech32()) { - throw new errors_1.ErrContractHasNoAddress(); - } - } - /** - * Computes the address of a Smart Contract. - * The address is computed deterministically, from the address of the owner and the nonce of the deployment transaction. - * - * @param owner The owner of the Smart Contract - * @param nonce The owner nonce used for the deployment transaction - */ - static computeAddress(owner, nonce) { - const deployer = address_1.Address.fromBech32(owner.bech32()); - const addressComputer = new address_1.AddressComputer(); - return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); - } - }; - exports2.SmartContract = SmartContract; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js -var require_transactionPayloadBuilders = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractCallPayloadBuilder = exports2.ContractUpgradePayloadBuilder = exports2.ContractDeployPayloadBuilder = void 0; - var constants_1 = require_constants(); - var transactionPayload_1 = require_transactionPayload(); - var utils_1 = require_utils2(); - var argSerializer_1 = require_argSerializer(); - var ContractDeployPayloadBuilder = class { - constructor() { - this.code = null; - this.codeMetadata = ""; - this.arguments = []; - } - /** - * Sets the code of the Smart Contract. - */ - setCode(code2) { - this.code = code2; - return this; - } - /** - * Sets the code metadata of the Smart Contract. - */ - setCodeMetadata(codeMetadata) { - this.codeMetadata = codeMetadata; - return this; - } - /** - * Adds constructor (`init`) arguments. - */ - addInitArg(arg) { - this.arguments.push(arg); - return this; - } - /** - * Sets constructor (`init`) arguments. - */ - setInitArgs(args) { - this.arguments = args; - return this; - } - /** - * Builds the {@link TransactionPayload}. - */ - build() { - utils_1.guardValueIsSet("code", this.code); - let code2 = this.code.toString(); - let codeMetadata = this.codeMetadata.toString(); - let data = `${code2}@${constants_1.WasmVirtualMachine}@${codeMetadata}`; - data = appendArgumentsToString(data, this.arguments); - return new transactionPayload_1.TransactionPayload(data); - } - }; - exports2.ContractDeployPayloadBuilder = ContractDeployPayloadBuilder; - var ContractUpgradePayloadBuilder = class { - constructor() { - this.code = null; - this.codeMetadata = ""; - this.arguments = []; - } - /** - * Sets the code of the Smart Contract. - */ - setCode(code2) { - this.code = code2; - return this; - } - /** - * Sets the code metadata of the Smart Contract. - */ - setCodeMetadata(codeMetadata) { - this.codeMetadata = codeMetadata; - return this; - } - /** - * Adds upgrade (`init`) arguments. - */ - addInitArg(arg) { - this.arguments.push(arg); - return this; - } - /** - * Sets upgrade (`init`) arguments. - */ - setInitArgs(args) { - this.arguments = args; - return this; - } - /** - * Builds the {@link TransactionPayload}. - */ - build() { - utils_1.guardValueIsSet("code", this.code); - let code2 = this.code.toString(); - let codeMetadata = this.codeMetadata.toString(); - let data = `upgradeContract@${code2}@${codeMetadata}`; - data = appendArgumentsToString(data, this.arguments); - return new transactionPayload_1.TransactionPayload(data); - } - }; - exports2.ContractUpgradePayloadBuilder = ContractUpgradePayloadBuilder; - var ContractCallPayloadBuilder = class { - constructor() { - this.contractFunction = null; - this.arguments = []; - } - /** - * Sets the function to be called (executed). - */ - setFunction(contractFunction) { - this.contractFunction = contractFunction; - return this; - } - /** - * Adds a function argument. - */ - addArg(arg) { - this.arguments.push(arg); - return this; - } - /** - * Sets the function arguments. - */ - setArgs(args) { - this.arguments = args; - return this; - } - /** - * Builds the {@link TransactionPayload}. - */ - build() { - utils_1.guardValueIsSet("calledFunction", this.contractFunction); - let data = this.contractFunction.toString(); - data = appendArgumentsToString(data, this.arguments); - return new transactionPayload_1.TransactionPayload(data); - } - }; - exports2.ContractCallPayloadBuilder = ContractCallPayloadBuilder; - function appendArgumentsToString(to, values) { - let { argumentsString, count } = new argSerializer_1.ArgSerializer().valuesToString(values); - if (count == 0) { - return to; - } - return `${to}@${argumentsString}`; - } - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/index.js -var require_smartcontracts = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_argSerializer(), exports2); - __exportStar2(require_code(), exports2); - __exportStar2(require_codec2(), exports2); - __exportStar2(require_codeMetadata2(), exports2); - __exportStar2(require_function(), exports2); - __exportStar2(require_interaction(), exports2); - __exportStar2(require_interactionChecker(), exports2); - __exportStar2(require_interface(), exports2); - __exportStar2(require_nativeSerializer(), exports2); - __exportStar2(require_query(), exports2); - __exportStar2(require_resultsParser(), exports2); - __exportStar2(require_returnCode(), exports2); - __exportStar2(require_smartContract(), exports2); - __exportStar2(require_transactionPayloadBuilders(), exports2); - __exportStar2(require_typesystem(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js -var require_resources = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.gatherAllEvents = exports2.findEventsByFirstTopic = exports2.findEventsByIdentifier = exports2.findEventsByPredicate = exports2.SmartContractCallOutcome = exports2.TransactionOutcome = exports2.SmartContractResult = exports2.TransactionLogs = exports2.TransactionEvent = void 0; - var TransactionEvent = class { - constructor(init) { - this.address = ""; - this.identifier = ""; - this.topics = []; - this.dataItems = []; - Object.assign(this, init); - } - }; - exports2.TransactionEvent = TransactionEvent; - var TransactionLogs2 = class { - constructor(init) { - this.address = ""; - this.events = []; - Object.assign(this, init); - } - }; - exports2.TransactionLogs = TransactionLogs2; - var SmartContractResult = class { - constructor(init) { - this.sender = ""; - this.receiver = ""; - this.data = new Uint8Array(); - this.logs = new TransactionLogs2({}); - Object.assign(this, init); - } - }; - exports2.SmartContractResult = SmartContractResult; - var TransactionOutcome = class { - constructor(init) { - this.directSmartContractCallOutcome = new SmartContractCallOutcome({}); - this.smartContractResults = []; - this.logs = new TransactionLogs2({}); - Object.assign(this, init); - } - }; - exports2.TransactionOutcome = TransactionOutcome; - var SmartContractCallOutcome = class { - constructor(init) { - this.function = ""; - this.returnDataParts = []; - this.returnMessage = ""; - this.returnCode = ""; - Object.assign(this, init); - } - }; - exports2.SmartContractCallOutcome = SmartContractCallOutcome; - function findEventsByPredicate(transactionOutcome, predicate) { - return gatherAllEvents(transactionOutcome).filter(predicate); - } - exports2.findEventsByPredicate = findEventsByPredicate; - function findEventsByIdentifier(transactionOutcome, identifier) { - return findEventsByPredicate(transactionOutcome, (event) => event.identifier == identifier); - } - exports2.findEventsByIdentifier = findEventsByIdentifier; - function findEventsByFirstTopic(transactionOutcome, topic) { - return findEventsByPredicate(transactionOutcome, (event) => event.topics[0]?.toString() == topic); - } - exports2.findEventsByFirstTopic = findEventsByFirstTopic; - function gatherAllEvents(transactionOutcome) { - const allEvents = []; - allEvents.push(...transactionOutcome.logs.events); - for (const item of transactionOutcome.smartContractResults) { - allEvents.push(...item.logs.events); - } - return allEvents; - } - exports2.gatherAllEvents = gatherAllEvents; - } -}); - -// node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js -var require_transactionsConverter = __commonJS({ - "node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionsConverter = void 0; - var smartcontracts_1 = require_smartcontracts(); - var transaction_1 = require_transaction(); - var resources_1 = require_resources(); - var TransactionsConverter = class { - transactionToPlainObject(transaction) { - const plainObject = { - nonce: Number(transaction.nonce), - value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, - senderUsername: this.toBase64OrUndefined(transaction.senderUsername), - receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), - gasPrice: Number(transaction.gasPrice), - gasLimit: Number(transaction.gasLimit), - data: this.toBase64OrUndefined(transaction.data), - chainID: transaction.chainID.valueOf(), - version: transaction.version, - options: transaction.options == 0 ? void 0 : transaction.options, - guardian: transaction.guardian ? transaction.guardian : void 0, - signature: this.toHexOrUndefined(transaction.signature), - guardianSignature: this.toHexOrUndefined(transaction.guardianSignature) - }; - return plainObject; - } - toBase64OrUndefined(value) { - return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; - } - toHexOrUndefined(value) { - return value && value.length ? import_buffer.Buffer.from(value).toString("hex") : void 0; - } - plainObjectToTransaction(object) { - const transaction = new transaction_1.Transaction({ - nonce: BigInt(object.nonce), - value: BigInt(object.value || ""), - receiver: object.receiver, - receiverUsername: this.bufferFromBase64(object.receiverUsername).toString(), - sender: object.sender, - senderUsername: this.bufferFromBase64(object.senderUsername).toString(), - guardian: object.guardian, - gasPrice: BigInt(object.gasPrice), - gasLimit: BigInt(object.gasLimit), - data: this.bufferFromBase64(object.data), - chainID: String(object.chainID), - version: Number(object.version), - options: Number(object.options), - signature: this.bufferFromHex(object.signature), - guardianSignature: this.bufferFromHex(object.guardianSignature) - }); - return transaction; - } - bufferFromBase64(value) { - return import_buffer.Buffer.from(value || "", "base64"); - } - bufferFromHex(value) { - return import_buffer.Buffer.from(value || "", "hex"); - } - transactionOnNetworkToOutcome(transactionOnNetwork) { - const legacyResultsParser = new smartcontracts_1.ResultsParser(); - const callOutcomeBundle = legacyResultsParser.parseUntypedOutcome(transactionOnNetwork); - const callOutcome = new resources_1.SmartContractCallOutcome({ - function: transactionOnNetwork.function, - returnCode: callOutcomeBundle.returnCode.toString(), - returnMessage: callOutcomeBundle.returnMessage, - returnDataParts: callOutcomeBundle.values - }); - const contractResults = transactionOnNetwork.contractResults.items.map((result) => this.smartContractResultOnNetworkToSmartContractResult(result)); - const logs = new resources_1.TransactionLogs({ - address: transactionOnNetwork.logs.address.bech32(), - events: transactionOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) - }); - return new resources_1.TransactionOutcome({ - logs, - smartContractResults: contractResults, - directSmartContractCallOutcome: callOutcome - }); - } - smartContractResultOnNetworkToSmartContractResult(resultOnNetwork) { - return new resources_1.SmartContractResult({ - sender: resultOnNetwork.sender.bech32(), - receiver: resultOnNetwork.receiver.bech32(), - data: import_buffer.Buffer.from(resultOnNetwork.data), - logs: new resources_1.TransactionLogs({ - address: resultOnNetwork.logs.address.bech32(), - events: resultOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) - }) - }); - } - eventOnNetworkToEvent(eventOnNetwork) { - const legacyData = eventOnNetwork.dataPayload?.valueOf() || import_buffer.Buffer.from(eventOnNetwork.data || ""); - const dataItems = eventOnNetwork.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; - if (dataItems.length === 0) { - if (legacyData.length) { - dataItems.push(import_buffer.Buffer.from(legacyData)); - } - } - return new resources_1.TransactionEvent({ - address: eventOnNetwork.address.bech32(), - identifier: eventOnNetwork.identifier, - topics: eventOnNetwork.topics.map((topic) => import_buffer.Buffer.from(topic.hex(), "hex")), - dataItems - }); - } - }; - exports2.TransactionsConverter = TransactionsConverter; - } -}); - -// node_modules/@multiversx/sdk-core/out/hash.js -var require_hash = __commonJS({ - "node_modules/@multiversx/sdk-core/out/hash.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Hash = void 0; - var errors = __importStar2(require_errors()); - var Hash = class _Hash { - /** - * Creates a new Hash object. - * - * @param hash The hash, as a Buffer or a hex-encoded string. - */ - constructor(hash) { - if (!hash) { - this.hash = import_buffer.Buffer.from([]); - } else if (hash instanceof import_buffer.Buffer) { - this.hash = hash; - } else if (typeof hash === "string") { - this.hash = import_buffer.Buffer.from(hash, "hex"); - } else { - throw new errors.ErrBadType("hash", "buffer | string", hash); - } - } - static empty() { - return new _Hash(import_buffer.Buffer.from([])); - } - /** - * Returns whether the hash is empty (not computed). - */ - isEmpty() { - return this.hash.length == 0; - } - toString() { - return this.hex(); - } - hex() { - return this.hash.toString("hex"); - } - valueOf() { - return this.hash; - } - }; - exports2.Hash = Hash; - } -}); - -// node_modules/@multiversx/sdk-core/out/signature.js -var require_signature = __commonJS({ - "node_modules/@multiversx/sdk-core/out/signature.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.interpretSignatureAsBuffer = exports2.Signature = void 0; - var errors = __importStar2(require_errors()); - var SIGNATURE_LENGTH = 64; - var Signature = class _Signature { - constructor(value) { - this.valueHex = ""; - if (!value) { - return; - } - if (typeof value === "string") { - return _Signature.fromHex(value); - } - if (value instanceof import_buffer.Buffer) { - return _Signature.fromBuffer(value); - } - } - static empty() { - return new _Signature(); - } - static fromHex(value) { - if (value.startsWith("0x")) { - value = value.slice(2); - } - if (!_Signature.isValidHex(value)) { - throw new errors.ErrSignatureCannotCreate(value); - } - return _Signature.fromValidHex(value); - } - static isValidHex(value) { - return import_buffer.Buffer.from(value, "hex").length == SIGNATURE_LENGTH; - } - static fromValidHex(value) { - let result = new _Signature(); - result.valueHex = value; - return result; - } - static fromBuffer(buffer) { - if (buffer.length != SIGNATURE_LENGTH) { - throw new errors.ErrSignatureCannotCreate(buffer); - } - return _Signature.fromValidHex(buffer.toString("hex")); - } - hex() { - return this.valueHex; - } - }; - exports2.Signature = Signature; - function interpretSignatureAsBuffer(signature) { - if (ArrayBuffer.isView(signature)) { - return import_buffer.Buffer.from(signature); - } else if (signature.hex != null) { - return import_buffer.Buffer.from(signature.hex(), "hex"); - } - throw new Error(`Object cannot be interpreted as a signature: ${signature}`); - } - exports2.interpretSignatureAsBuffer = interpretSignatureAsBuffer; - } -}); - -// node_modules/@protobufjs/aspromise/index.js -var require_aspromise = __commonJS({ - "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = asPromise; - function asPromise(fn, ctx) { - var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params2 = new Array(arguments.length - 1), offset2 = 0; - while (offset2 < params2.length) - params2[offset2++] = arguments[offset2]; - resolve.apply(null, params2); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); - } - } -}); - -// node_modules/@protobufjs/base64/index.js -var require_base64 = __commonJS({ - "node_modules/@protobufjs/base64/index.js"(exports2) { - "use strict"; - init_shim(); - var base642 = exports2; - base642.length = function length2(string2) { - var p3 = string2.length; - if (!p3) - return 0; - var n3 = 0; - while (--p3 % 4 > 1 && string2.charAt(p3) === "=") - ++n3; - return Math.ceil(string2.length * 3) / 4 - n3; - }; - var b64 = new Array(64); - var s64 = new Array(123); - for (i2 = 0; i2 < 64; ) - s64[b64[i2] = i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 - 59 | 43] = i2++; - var i2; - base642.encode = function encode5(buffer, start, end) { - var parts = null, chunk = []; - var i3 = 0, j2 = 0, t; - while (start < end) { - var b4 = buffer[start++]; - switch (j2) { - case 0: - chunk[i3++] = b64[b4 >> 2]; - t = (b4 & 3) << 4; - j2 = 1; - break; - case 1: - chunk[i3++] = b64[t | b4 >> 4]; - t = (b4 & 15) << 2; - j2 = 2; - break; - case 2: - chunk[i3++] = b64[t | b4 >> 6]; - chunk[i3++] = b64[b4 & 63]; - j2 = 0; - break; - } - if (i3 > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i3 = 0; - } - } - if (j2) { - chunk[i3++] = b64[t]; - chunk[i3++] = 61; - if (j2 === 1) - chunk[i3++] = 61; - } - if (parts) { - if (i3) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i3))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i3)); - }; - var invalidEncoding = "invalid encoding"; - base642.decode = function decode6(string2, buffer, offset) { - var start = offset; - var j2 = 0, t; - for (var i3 = 0; i3 < string2.length; ) { - var c4 = string2.charCodeAt(i3++); - if (c4 === 61 && j2 > 1) - break; - if ((c4 = s64[c4]) === void 0) - throw Error(invalidEncoding); - switch (j2) { - case 0: - t = c4; - j2 = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c4 & 48) >> 4; - t = c4; - j2 = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c4 & 60) >> 2; - t = c4; - j2 = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c4; - j2 = 0; - break; - } - } - if (j2 === 1) - throw Error(invalidEncoding); - return offset - start; - }; - base642.test = function test(string2) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string2); - }; - } -}); - -// node_modules/@protobufjs/eventemitter/index.js -var require_eventemitter = __commonJS({ - "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = EventEmitter2; - function EventEmitter2() { - this._listeners = {}; - } - EventEmitter2.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn, - ctx: ctx || this - }); - return this; - }; - EventEmitter2.prototype.off = function off(evt, fn) { - if (evt === void 0) - this._listeners = {}; - else { - if (fn === void 0) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i2 = 0; i2 < listeners.length; ) - if (listeners[i2].fn === fn) - listeners.splice(i2, 1); - else - ++i2; - } - } - return this; - }; - EventEmitter2.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], i2 = 1; - for (; i2 < arguments.length; ) - args.push(arguments[i2++]); - for (i2 = 0; i2 < listeners.length; ) - listeners[i2].fn.apply(listeners[i2++].ctx, args); - } - return this; - }; - } -}); - -// node_modules/@protobufjs/float/index.js -var require_float = __commonJS({ - "node_modules/@protobufjs/float/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = factory(factory); - function factory(exports3) { - if (typeof Float32Array !== "undefined") - (function() { - var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - })(); - else - (function() { - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign2 = val < 0 ? 1 : 0; - if (sign2) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? ( - /* positive */ - 0 - ) : ( - /* negative 0 */ - 2147483648 - ), buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 34028234663852886e22) - writeUint((sign2 << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 11754943508222875e-54) - writeUint((sign2 << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign2 << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), sign2 = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; - return exponent === 255 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 1401298464324817e-60 * mantissa : sign2 * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - })(); - if (typeof Float64Array !== "undefined") - (function() { - var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - })(); - else - (function() { - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign2 = val < 0 ? 1 : 0; - if (sign2) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? ( - /* positive */ - 0 - ) : ( - /* negative 0 */ - 2147483648 - ), buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 17976931348623157e292) { - writeUint(0, buf, pos + off0); - writeUint((sign2 << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 22250738585072014e-324) { - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign2 << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign2 << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); - var sign2 = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 5e-324 * mantissa : sign2 * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - })(); - return exports3; - } - function writeUintLE(val, buf, pos) { - buf[pos] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; - } - function writeUintBE(val, buf, pos) { - buf[pos] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; - } - function readUintLE(buf, pos) { - return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; - } - function readUintBE(buf, pos) { - return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; - } - } -}); - -// node_modules/@protobufjs/inquire/index.js -var require_inquire = __commonJS({ - "node_modules/@protobufjs/inquire/index.js"(exports, module) { - "use strict"; - init_shim(); - module.exports = inquire; - function inquire(moduleName) { - try { - var mod = eval("quire".replace(/^/, "re"))(moduleName); - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (e2) { - } - return null; - } - } -}); - -// node_modules/@protobufjs/utf8/index.js -var require_utf8 = __commonJS({ - "node_modules/@protobufjs/utf8/index.js"(exports2) { - "use strict"; - init_shim(); - var utf8 = exports2; - utf8.length = function utf8_length(string2) { - var len = 0, c4 = 0; - for (var i2 = 0; i2 < string2.length; ++i2) { - c4 = string2.charCodeAt(i2); - if (c4 < 128) - len += 1; - else if (c4 < 2048) - len += 2; - else if ((c4 & 64512) === 55296 && (string2.charCodeAt(i2 + 1) & 64512) === 56320) { - ++i2; - len += 4; - } else - len += 3; - } - return len; - }; - utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, chunk = [], i2 = 0, t; - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i2++] = t; - else if (t > 191 && t < 224) - chunk[i2++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536; - chunk[i2++] = 55296 + (t >> 10); - chunk[i2++] = 56320 + (t & 1023); - } else - chunk[i2++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i2 > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i2 = 0; - } - } - if (parts) { - if (i2) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i2)); - }; - utf8.write = function utf8_write(string2, buffer, offset) { - var start = offset, c1, c22; - for (var i2 = 0; i2 < string2.length; ++i2) { - c1 = string2.charCodeAt(i2); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 64512) === 55296 && ((c22 = string2.charCodeAt(i2 + 1)) & 64512) === 56320) { - c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023); - ++i2; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; - }; - } -}); - -// node_modules/@protobufjs/pool/index.js -var require_pool = __commonJS({ - "node_modules/@protobufjs/pool/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = pool; - function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX2 = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size2) { - if (size2 < 1 || size2 > MAX2) - return alloc(size2); - if (offset + size2 > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size2); - if (offset & 7) - offset = (offset | 7) + 1; - return buf; - }; - } - } -}); - -// node_modules/protobufjs/src/util/longbits.js -var require_longbits = __commonJS({ - "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = LongBits; - var util = require_minimal(); - function LongBits(lo, hi) { - this.lo = lo >>> 0; - this.hi = hi >>> 0; - } - var zero = LongBits.zero = new LongBits(0, 0); - zero.toNumber = function() { - return 0; - }; - zero.zzEncode = zero.zzDecode = function() { - return this; - }; - zero.length = function() { - return 1; - }; - var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; - LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign2 = value < 0; - if (sign2) - value = -value; - var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; - if (sign2) { - hi = ~hi >>> 0; - lo = ~lo >>> 0; - if (++lo > 4294967295) { - lo = 0; - if (++hi > 4294967295) - hi = 0; - } - } - return new LongBits(lo, hi); - }; - LongBits.from = function from3(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (util.isString(value)) { - if (util.Long) - value = util.Long.fromString(value); - else - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; - }; - LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; - }; - LongBits.prototype.toLong = function toLong(unsigned) { - return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; - }; - var charCodeAt = String.prototype.charCodeAt; - LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, - (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 - ); - }; - LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24, - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); - }; - LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = (this.lo << 1 ^ mask) >>> 0; - return this; - }; - LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = (this.hi >>> 1 ^ mask) >>> 0; - return this; - }; - LongBits.prototype.length = function length2() { - var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; - return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; - }; - } -}); - -// node_modules/protobufjs/src/util/minimal.js -var require_minimal = __commonJS({ - "node_modules/protobufjs/src/util/minimal.js"(exports2) { - "use strict"; - init_shim(); - var util = exports2; - util.asPromise = require_aspromise(); - util.base64 = require_base64(); - util.EventEmitter = require_eventemitter(); - util.float = require_float(); - util.inquire = require_inquire(); - util.utf8 = require_utf8(); - util.pool = require_pool(); - util.LongBits = require_longbits(); - util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); - util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; - util.emptyArray = Object.freeze ? Object.freeze([]) : ( - /* istanbul ignore next */ - [] - ); - util.emptyObject = Object.freeze ? Object.freeze({}) : ( - /* istanbul ignore next */ - {} - ); - util.isInteger = Number.isInteger || /* istanbul ignore next */ - function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; - }; - util.isString = function isString2(value) { - return typeof value === "string" || value instanceof String; - }; - util.isObject = function isObject(value) { - return value && typeof value === "object"; - }; - util.isset = /** - * Checks if a property on a message is considered to be present. - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ - util.isSet = function isSet(obj, prop) { - var value = obj[prop]; - if (value != null && obj.hasOwnProperty(prop)) - return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; - return false; - }; - util.Buffer = function() { - try { - var Buffer2 = util.inquire("buffer").Buffer; - return Buffer2.prototype.utf8Write ? Buffer2 : ( - /* istanbul ignore next */ - null - ); - } catch (e2) { - return null; - } - }(); - util._Buffer_from = null; - util._Buffer_allocUnsafe = null; - util.newBuffer = function newBuffer(sizeOrArray) { - return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); - }; - util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - util.Long = /* istanbul ignore next */ - util.global.dcodeIO && /* istanbul ignore next */ - util.global.dcodeIO.Long || /* istanbul ignore next */ - util.global.Long || util.inquire("long"); - util.key2Re = /^true|false|0|1$/; - util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; - util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; - util.longToHash = function longToHash(value) { - return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; - }; - util.longFromHash = function longFromHash(hash, unsigned) { - var bits = util.LongBits.fromHash(hash); - if (util.Long) - return util.Long.fromBits(bits.lo, bits.hi, unsigned); - return bits.toNumber(Boolean(unsigned)); - }; - function merge(dst, src2, ifNotSet) { - for (var keys2 = Object.keys(src2), i2 = 0; i2 < keys2.length; ++i2) - if (dst[keys2[i2]] === void 0 || !ifNotSet) - dst[keys2[i2]] = src2[keys2[i2]]; - return dst; - } - util.merge = merge; - util.lcFirst = function lcFirst(str) { - return str.charAt(0).toLowerCase() + str.substring(1); - }; - function newError(name2) { - function CustomError(message, properties) { - if (!(this instanceof CustomError)) - return new CustomError(message, properties); - Object.defineProperty(this, "message", { get: function() { - return message; - } }); - if (Error.captureStackTrace) - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: new Error().stack || "" }); - if (properties) - merge(this, properties); - } - CustomError.prototype = Object.create(Error.prototype, { - constructor: { - value: CustomError, - writable: true, - enumerable: false, - configurable: true - }, - name: { - get: function get2() { - return name2; - }, - set: void 0, - enumerable: false, - // configurable: false would accurately preserve the behavior of - // the original, but I'm guessing that was not intentional. - // For an actual error subclass, this property would - // be configurable. - configurable: true - }, - toString: { - value: function value() { - return this.name + ": " + this.message; - }, - writable: true, - enumerable: false, - configurable: true - } - }); - return CustomError; - } - util.newError = newError; - util.ProtocolError = newError("ProtocolError"); - util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i2 = 0; i2 < fieldNames.length; ++i2) - fieldMap[fieldNames[i2]] = 1; - return function() { - for (var keys2 = Object.keys(this), i3 = keys2.length - 1; i3 > -1; --i3) - if (fieldMap[keys2[i3]] === 1 && this[keys2[i3]] !== void 0 && this[keys2[i3]] !== null) - return keys2[i3]; - }; - }; - util.oneOfSetter = function setOneOf(fieldNames) { - return function(name2) { - for (var i2 = 0; i2 < fieldNames.length; ++i2) - if (fieldNames[i2] !== name2) - delete this[fieldNames[i2]]; - }; - }; - util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true - }; - util._configure = function() { - var Buffer2 = util.Buffer; - if (!Buffer2) { - util._Buffer_from = util._Buffer_allocUnsafe = null; - return; - } - util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ - function Buffer_from(value, encoding) { - return new Buffer2(value, encoding); - }; - util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ - function Buffer_allocUnsafe(size) { - return new Buffer2(size); - }; - }; - } -}); - -// node_modules/protobufjs/src/writer.js -var require_writer = __commonJS({ - "node_modules/protobufjs/src/writer.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Writer; - var util = require_minimal(); - var BufferWriter; - var LongBits = util.LongBits; - var base642 = util.base64; - var utf8 = util.utf8; - function Op(fn, len, val) { - this.fn = fn; - this.len = len; - this.next = void 0; - this.val = val; - } - function noop() { - } - function State(writer) { - this.head = writer.head; - this.tail = writer.tail; - this.len = writer.len; - this.next = writer.states; - } - function Writer() { - this.len = 0; - this.head = new Op(noop, 0, 0); - this.tail = this.head; - this.states = null; - } - var create2 = function create3() { - return util.Buffer ? function create_buffer_setup() { - return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); - } : function create_array() { - return new Writer(); - }; - }; - Writer.create = create2(); - Writer.alloc = function alloc(size) { - return new util.Array(size); - }; - if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); - Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; - }; - function writeByte(val, buf, pos) { - buf[pos] = val & 255; - } - function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; - } - function VarintOp(len, val) { - this.len = len; - this.next = void 0; - this.val = val; - } - VarintOp.prototype = Object.create(Op.prototype); - VarintOp.prototype.fn = writeVarint32; - Writer.prototype.uint32 = function write_uint32(value) { - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, - value - )).len; - return this; - }; - Writer.prototype.int32 = function write_int32(value) { - return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); - }; - Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); - }; - function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; - } - Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); - }; - Writer.prototype.int64 = Writer.prototype.uint64; - Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); - }; - Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); - }; - function writeFixed32(val, buf, pos) { - buf[pos] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; - } - Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); - }; - Writer.prototype.sfixed32 = Writer.prototype.fixed32; - Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); - }; - Writer.prototype.sfixed64 = Writer.prototype.fixed64; - Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); - }; - Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); - }; - var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); - } : function writeBytes_for(val, buf, pos) { - for (var i2 = 0; i2 < val.length; ++i2) - buf[pos + i2] = val[i2]; - }; - Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - if (util.isString(value)) { - var buf = Writer.alloc(len = base642.length(value)); - base642.decode(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); - }; - Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); - }; - Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - return this; - }; - Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - } - return this; - }; - Writer.prototype.ldelim = function ldelim() { - var head = this.head, tail = this.tail, len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; - this.tail = tail; - this.len += len; - } - return this; - }; - Writer.prototype.finish = function finish() { - var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - return buf; - }; - Writer._configure = function(BufferWriter_) { - BufferWriter = BufferWriter_; - Writer.create = create2(); - BufferWriter._configure(); - }; - } -}); - -// node_modules/protobufjs/src/writer_buffer.js -var require_writer_buffer = __commonJS({ - "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = BufferWriter; - var Writer = require_writer(); - (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; - var util = require_minimal(); - function BufferWriter() { - Writer.call(this); - } - BufferWriter._configure = function() { - BufferWriter.alloc = util._Buffer_allocUnsafe; - BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { - buf.set(val, pos); - } : function writeBytesBuffer_copy(val, buf, pos) { - if (val.copy) - val.copy(buf, pos, 0, val.length); - else - for (var i2 = 0; i2 < val.length; ) - buf[pos++] = val[i2++]; - }; - }; - BufferWriter.prototype.bytes = function write_bytes_buffer(value) { - if (util.isString(value)) - value = util._Buffer_from(value, "base64"); - var len = value.length >>> 0; - this.uint32(len); - if (len) - this._push(BufferWriter.writeBytesBuffer, len, value); - return this; - }; - function writeStringBuffer(val, buf, pos) { - if (val.length < 40) - util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); - else - buf.write(val, pos); - } - BufferWriter.prototype.string = function write_string_buffer(value) { - var len = util.Buffer.byteLength(value); - this.uint32(len); - if (len) - this._push(writeStringBuffer, len, value); - return this; - }; - BufferWriter._configure(); - } -}); - -// node_modules/protobufjs/src/reader.js -var require_reader = __commonJS({ - "node_modules/protobufjs/src/reader.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Reader; - var util = require_minimal(); - var BufferReader; - var LongBits = util.LongBits; - var utf8 = util.utf8; - function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); - } - function Reader(buffer) { - this.buf = buffer; - this.pos = 0; - this.len = buffer.length; - } - var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - } : function create_array2(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - }; - var create2 = function create3() { - return util.Buffer ? function create_buffer_setup(buffer) { - return (Reader.create = function create_buffer(buffer2) { - return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); - })(buffer); - } : create_array; - }; - Reader.create = create2(); - Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ - util.Array.prototype.slice; - Reader.prototype.uint32 = /* @__PURE__ */ function read_uint32_setup() { - var value = 4294967295; - return function read_uint32() { - value = (this.buf[this.pos] & 127) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; - }(); - Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; - }; - Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; - }; - function readLongVarint() { - var bits = new LongBits(0, 0); - var i2 = 0; - if (this.len - this.pos > 4) { - for (; i2 < 4; ++i2) { - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i2 = 0; - } else { - for (; i2 < 3; ++i2) { - if (this.pos >= this.len) - throw indexOutOfRange(this); - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i2 * 7) >>> 0; - return bits; - } - if (this.len - this.pos > 4) { - for (; i2 < 5; ++i2) { - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } else { - for (; i2 < 5; ++i2) { - if (this.pos >= this.len) - throw indexOutOfRange(this); - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } - throw Error("invalid varint encoding"); - } - Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; - }; - function readFixed32_end(buf, end) { - return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; - } - Reader.prototype.fixed32 = function read_fixed32() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - return readFixed32_end(this.buf, this.pos += 4); - }; - Reader.prototype.sfixed32 = function read_sfixed32() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - return readFixed32_end(this.buf, this.pos += 4) | 0; - }; - function readFixed64() { - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); - } - Reader.prototype.float = function read_float() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; - }; - Reader.prototype.double = function read_double() { - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; - }; - Reader.prototype.bytes = function read_bytes() { - var length2 = this.uint32(), start = this.pos, end = this.pos + length2; - if (end > this.len) - throw indexOutOfRange(this, length2); - this.pos += length2; - if (Array.isArray(this.buf)) - return this.buf.slice(start, end); - if (start === end) { - var nativeBuffer = util.Buffer; - return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); - } - return this._slice.call(this.buf, start, end); - }; - Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); - }; - Reader.prototype.skip = function skip(length2) { - if (typeof length2 === "number") { - if (this.pos + length2 > this.len) - throw indexOutOfRange(this, length2); - this.pos += length2; - } else { - do { - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); - } - return this; - }; - Reader.prototype.skipType = function(wireType) { - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - while ((wireType = this.uint32() & 7) !== 4) { - this.skipType(wireType); - } - break; - case 5: - this.skip(4); - break; - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; - }; - Reader._configure = function(BufferReader_) { - BufferReader = BufferReader_; - Reader.create = create2(); - BufferReader._configure(); - var fn = util.Long ? "toLong" : ( - /* istanbul ignore next */ - "toNumber" - ); - util.merge(Reader.prototype, { - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); - } - }); - }; - } -}); - -// node_modules/protobufjs/src/reader_buffer.js -var require_reader_buffer = __commonJS({ - "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = BufferReader; - var Reader = require_reader(); - (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; - var util = require_minimal(); - function BufferReader(buffer) { - Reader.call(this, buffer); - } - BufferReader._configure = function() { - if (util.Buffer) - BufferReader.prototype._slice = util.Buffer.prototype.slice; - }; - BufferReader.prototype.string = function read_string_buffer() { - var len = this.uint32(); - return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); - }; - BufferReader._configure(); - } -}); - -// node_modules/protobufjs/src/rpc/service.js -var require_service = __commonJS({ - "node_modules/protobufjs/src/rpc/service.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Service; - var util = require_minimal(); - (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; - function Service(rpcImpl, requestDelimited, responseDelimited) { - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); - util.EventEmitter.call(this); - this.rpcImpl = rpcImpl; - this.requestDelimited = Boolean(requestDelimited); - this.responseDelimited = Boolean(responseDelimited); - } - Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { - if (!request) - throw TypeError("request must be specified"); - var self2 = this; - if (!callback) - return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request); - if (!self2.rpcImpl) { - setTimeout(function() { - callback(Error("already ended")); - }, 0); - return void 0; - } - try { - return self2.rpcImpl( - method, - requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), - function rpcCallback(err, response) { - if (err) { - self2.emit("error", err, method); - return callback(err); - } - if (response === null) { - self2.end( - /* endedByRPC */ - true - ); - return void 0; - } - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err2) { - self2.emit("error", err2, method); - return callback(err2); - } - } - self2.emit("data", response, method); - return callback(null, response); - } - ); - } catch (err) { - self2.emit("error", err, method); - setTimeout(function() { - callback(err); - }, 0); - return void 0; - } - }; - Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); - } - return this; - }; - } -}); - -// node_modules/protobufjs/src/rpc.js -var require_rpc = __commonJS({ - "node_modules/protobufjs/src/rpc.js"(exports2) { - "use strict"; - init_shim(); - var rpc = exports2; - rpc.Service = require_service(); - } -}); - -// node_modules/protobufjs/src/roots.js -var require_roots = __commonJS({ - "node_modules/protobufjs/src/roots.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = {}; - } -}); - -// node_modules/protobufjs/src/index-minimal.js -var require_index_minimal = __commonJS({ - "node_modules/protobufjs/src/index-minimal.js"(exports2) { - "use strict"; - init_shim(); - var protobuf = exports2; - protobuf.build = "minimal"; - protobuf.Writer = require_writer(); - protobuf.BufferWriter = require_writer_buffer(); - protobuf.Reader = require_reader(); - protobuf.BufferReader = require_reader_buffer(); - protobuf.util = require_minimal(); - protobuf.rpc = require_rpc(); - protobuf.roots = require_roots(); - protobuf.configure = configure; - function configure() { - protobuf.util._configure(); - protobuf.Writer._configure(protobuf.BufferWriter); - protobuf.Reader._configure(protobuf.BufferReader); - } - configure(); - } -}); - -// node_modules/protobufjs/minimal.js -var require_minimal2 = __commonJS({ - "node_modules/protobufjs/minimal.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = require_index_minimal(); - } -}); - -// node_modules/@multiversx/sdk-core/out/proto/compiled.js -var require_compiled = __commonJS({ - "node_modules/@multiversx/sdk-core/out/proto/compiled.js"(exports2, module2) { - "use strict"; - init_shim(); - (function(global2, factory) { - if (typeof define === "function" && define.amd) - define(["protobufjs/minimal"], factory); - else if (typeof __require === "function" && typeof module2 === "object" && module2 && module2.exports) - module2.exports = factory(require_minimal2()); - })(exports2, function($protobuf) { - "use strict"; - var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); - $root.proto = function() { - var proto = {}; - proto.Transaction = function() { - function Transaction4(properties) { - if (properties) { - for (var keys2 = Object.keys(properties), i2 = 0; i2 < keys2.length; ++i2) - if (properties[keys2[i2]] != null) - this[keys2[i2]] = properties[keys2[i2]]; - } - } - Transaction4.prototype.Nonce = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Transaction4.prototype.Value = $util.newBuffer([]); - Transaction4.prototype.RcvAddr = $util.newBuffer([]); - Transaction4.prototype.RcvUserName = $util.newBuffer([]); - Transaction4.prototype.SndAddr = $util.newBuffer([]); - Transaction4.prototype.SndUserName = $util.newBuffer([]); - Transaction4.prototype.GasPrice = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Transaction4.prototype.GasLimit = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Transaction4.prototype.Data = $util.newBuffer([]); - Transaction4.prototype.ChainID = $util.newBuffer([]); - Transaction4.prototype.Version = 0; - Transaction4.prototype.Signature = $util.newBuffer([]); - Transaction4.prototype.Options = 0; - Transaction4.prototype.GuardianAddr = $util.newBuffer([]); - Transaction4.prototype.GuardianSignature = $util.newBuffer([]); - Transaction4.create = function create2(properties) { - return new Transaction4(properties); - }; - Transaction4.encode = function encode5(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.Nonce != null && Object.hasOwnProperty.call(message, "Nonce")) - writer.uint32( - /* id 1, wireType 0 =*/ - 8 - ).uint64(message.Nonce); - if (message.Value != null && Object.hasOwnProperty.call(message, "Value")) - writer.uint32( - /* id 2, wireType 2 =*/ - 18 - ).bytes(message.Value); - if (message.RcvAddr != null && Object.hasOwnProperty.call(message, "RcvAddr")) - writer.uint32( - /* id 3, wireType 2 =*/ - 26 - ).bytes(message.RcvAddr); - if (message.RcvUserName != null && Object.hasOwnProperty.call(message, "RcvUserName")) - writer.uint32( - /* id 4, wireType 2 =*/ - 34 - ).bytes(message.RcvUserName); - if (message.SndAddr != null && Object.hasOwnProperty.call(message, "SndAddr")) - writer.uint32( - /* id 5, wireType 2 =*/ - 42 - ).bytes(message.SndAddr); - if (message.SndUserName != null && Object.hasOwnProperty.call(message, "SndUserName")) - writer.uint32( - /* id 6, wireType 2 =*/ - 50 - ).bytes(message.SndUserName); - if (message.GasPrice != null && Object.hasOwnProperty.call(message, "GasPrice")) - writer.uint32( - /* id 7, wireType 0 =*/ - 56 - ).uint64(message.GasPrice); - if (message.GasLimit != null && Object.hasOwnProperty.call(message, "GasLimit")) - writer.uint32( - /* id 8, wireType 0 =*/ - 64 - ).uint64(message.GasLimit); - if (message.Data != null && Object.hasOwnProperty.call(message, "Data")) - writer.uint32( - /* id 9, wireType 2 =*/ - 74 - ).bytes(message.Data); - if (message.ChainID != null && Object.hasOwnProperty.call(message, "ChainID")) - writer.uint32( - /* id 10, wireType 2 =*/ - 82 - ).bytes(message.ChainID); - if (message.Version != null && Object.hasOwnProperty.call(message, "Version")) - writer.uint32( - /* id 11, wireType 0 =*/ - 88 - ).uint32(message.Version); - if (message.Signature != null && Object.hasOwnProperty.call(message, "Signature")) - writer.uint32( - /* id 12, wireType 2 =*/ - 98 - ).bytes(message.Signature); - if (message.Options != null && Object.hasOwnProperty.call(message, "Options")) - writer.uint32( - /* id 13, wireType 0 =*/ - 104 - ).uint32(message.Options); - if (message.GuardianAddr != null && Object.hasOwnProperty.call(message, "GuardianAddr")) - writer.uint32( - /* id 14, wireType 2 =*/ - 114 - ).bytes(message.GuardianAddr); - if (message.GuardianSignature != null && Object.hasOwnProperty.call(message, "GuardianSignature")) - writer.uint32( - /* id 15, wireType 2 =*/ - 122 - ).bytes(message.GuardianSignature); - return writer; - }; - Transaction4.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - Transaction4.decode = function decode6(reader, length2) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length2 === void 0 ? reader.len : reader.pos + length2, message = new $root.proto.Transaction(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.Nonce = reader.uint64(); - break; - } - case 2: { - message.Value = reader.bytes(); - break; - } - case 3: { - message.RcvAddr = reader.bytes(); - break; - } - case 4: { - message.RcvUserName = reader.bytes(); - break; - } - case 5: { - message.SndAddr = reader.bytes(); - break; - } - case 6: { - message.SndUserName = reader.bytes(); - break; - } - case 7: { - message.GasPrice = reader.uint64(); - break; - } - case 8: { - message.GasLimit = reader.uint64(); - break; - } - case 9: { - message.Data = reader.bytes(); - break; - } - case 10: { - message.ChainID = reader.bytes(); - break; - } - case 11: { - message.Version = reader.uint32(); - break; - } - case 12: { - message.Signature = reader.bytes(); - break; - } - case 13: { - message.Options = reader.uint32(); - break; - } - case 14: { - message.GuardianAddr = reader.bytes(); - break; - } - case 15: { - message.GuardianSignature = reader.bytes(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - Transaction4.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - Transaction4.verify = function verify2(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.Nonce != null && message.hasOwnProperty("Nonce")) { - if (!$util.isInteger(message.Nonce) && !(message.Nonce && $util.isInteger(message.Nonce.low) && $util.isInteger(message.Nonce.high))) - return "Nonce: integer|Long expected"; - } - if (message.Value != null && message.hasOwnProperty("Value")) { - if (!(message.Value && typeof message.Value.length === "number" || $util.isString(message.Value))) - return "Value: buffer expected"; - } - if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) { - if (!(message.RcvAddr && typeof message.RcvAddr.length === "number" || $util.isString(message.RcvAddr))) - return "RcvAddr: buffer expected"; - } - if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) { - if (!(message.RcvUserName && typeof message.RcvUserName.length === "number" || $util.isString(message.RcvUserName))) - return "RcvUserName: buffer expected"; - } - if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) { - if (!(message.SndAddr && typeof message.SndAddr.length === "number" || $util.isString(message.SndAddr))) - return "SndAddr: buffer expected"; - } - if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) { - if (!(message.SndUserName && typeof message.SndUserName.length === "number" || $util.isString(message.SndUserName))) - return "SndUserName: buffer expected"; - } - if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) { - if (!$util.isInteger(message.GasPrice) && !(message.GasPrice && $util.isInteger(message.GasPrice.low) && $util.isInteger(message.GasPrice.high))) - return "GasPrice: integer|Long expected"; - } - if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) { - if (!$util.isInteger(message.GasLimit) && !(message.GasLimit && $util.isInteger(message.GasLimit.low) && $util.isInteger(message.GasLimit.high))) - return "GasLimit: integer|Long expected"; - } - if (message.Data != null && message.hasOwnProperty("Data")) { - if (!(message.Data && typeof message.Data.length === "number" || $util.isString(message.Data))) - return "Data: buffer expected"; - } - if (message.ChainID != null && message.hasOwnProperty("ChainID")) { - if (!(message.ChainID && typeof message.ChainID.length === "number" || $util.isString(message.ChainID))) - return "ChainID: buffer expected"; - } - if (message.Version != null && message.hasOwnProperty("Version")) { - if (!$util.isInteger(message.Version)) - return "Version: integer expected"; - } - if (message.Signature != null && message.hasOwnProperty("Signature")) { - if (!(message.Signature && typeof message.Signature.length === "number" || $util.isString(message.Signature))) - return "Signature: buffer expected"; - } - if (message.Options != null && message.hasOwnProperty("Options")) { - if (!$util.isInteger(message.Options)) - return "Options: integer expected"; - } - if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) { - if (!(message.GuardianAddr && typeof message.GuardianAddr.length === "number" || $util.isString(message.GuardianAddr))) - return "GuardianAddr: buffer expected"; - } - if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) { - if (!(message.GuardianSignature && typeof message.GuardianSignature.length === "number" || $util.isString(message.GuardianSignature))) - return "GuardianSignature: buffer expected"; - } - return null; - }; - Transaction4.fromObject = function fromObject(object) { - if (object instanceof $root.proto.Transaction) - return object; - var message = new $root.proto.Transaction(); - if (object.Nonce != null) { - if ($util.Long) - (message.Nonce = $util.Long.fromValue(object.Nonce)).unsigned = true; - else if (typeof object.Nonce === "string") - message.Nonce = parseInt(object.Nonce, 10); - else if (typeof object.Nonce === "number") - message.Nonce = object.Nonce; - else if (typeof object.Nonce === "object") - message.Nonce = new $util.LongBits(object.Nonce.low >>> 0, object.Nonce.high >>> 0).toNumber(true); - } - if (object.Value != null) { - if (typeof object.Value === "string") - $util.base64.decode(object.Value, message.Value = $util.newBuffer($util.base64.length(object.Value)), 0); - else if (object.Value.length >= 0) - message.Value = object.Value; - } - if (object.RcvAddr != null) { - if (typeof object.RcvAddr === "string") - $util.base64.decode(object.RcvAddr, message.RcvAddr = $util.newBuffer($util.base64.length(object.RcvAddr)), 0); - else if (object.RcvAddr.length >= 0) - message.RcvAddr = object.RcvAddr; - } - if (object.RcvUserName != null) { - if (typeof object.RcvUserName === "string") - $util.base64.decode(object.RcvUserName, message.RcvUserName = $util.newBuffer($util.base64.length(object.RcvUserName)), 0); - else if (object.RcvUserName.length >= 0) - message.RcvUserName = object.RcvUserName; - } - if (object.SndAddr != null) { - if (typeof object.SndAddr === "string") - $util.base64.decode(object.SndAddr, message.SndAddr = $util.newBuffer($util.base64.length(object.SndAddr)), 0); - else if (object.SndAddr.length >= 0) - message.SndAddr = object.SndAddr; - } - if (object.SndUserName != null) { - if (typeof object.SndUserName === "string") - $util.base64.decode(object.SndUserName, message.SndUserName = $util.newBuffer($util.base64.length(object.SndUserName)), 0); - else if (object.SndUserName.length >= 0) - message.SndUserName = object.SndUserName; - } - if (object.GasPrice != null) { - if ($util.Long) - (message.GasPrice = $util.Long.fromValue(object.GasPrice)).unsigned = true; - else if (typeof object.GasPrice === "string") - message.GasPrice = parseInt(object.GasPrice, 10); - else if (typeof object.GasPrice === "number") - message.GasPrice = object.GasPrice; - else if (typeof object.GasPrice === "object") - message.GasPrice = new $util.LongBits(object.GasPrice.low >>> 0, object.GasPrice.high >>> 0).toNumber(true); - } - if (object.GasLimit != null) { - if ($util.Long) - (message.GasLimit = $util.Long.fromValue(object.GasLimit)).unsigned = true; - else if (typeof object.GasLimit === "string") - message.GasLimit = parseInt(object.GasLimit, 10); - else if (typeof object.GasLimit === "number") - message.GasLimit = object.GasLimit; - else if (typeof object.GasLimit === "object") - message.GasLimit = new $util.LongBits(object.GasLimit.low >>> 0, object.GasLimit.high >>> 0).toNumber(true); - } - if (object.Data != null) { - if (typeof object.Data === "string") - $util.base64.decode(object.Data, message.Data = $util.newBuffer($util.base64.length(object.Data)), 0); - else if (object.Data.length >= 0) - message.Data = object.Data; - } - if (object.ChainID != null) { - if (typeof object.ChainID === "string") - $util.base64.decode(object.ChainID, message.ChainID = $util.newBuffer($util.base64.length(object.ChainID)), 0); - else if (object.ChainID.length >= 0) - message.ChainID = object.ChainID; - } - if (object.Version != null) - message.Version = object.Version >>> 0; - if (object.Signature != null) { - if (typeof object.Signature === "string") - $util.base64.decode(object.Signature, message.Signature = $util.newBuffer($util.base64.length(object.Signature)), 0); - else if (object.Signature.length >= 0) - message.Signature = object.Signature; - } - if (object.Options != null) - message.Options = object.Options >>> 0; - if (object.GuardianAddr != null) { - if (typeof object.GuardianAddr === "string") - $util.base64.decode(object.GuardianAddr, message.GuardianAddr = $util.newBuffer($util.base64.length(object.GuardianAddr)), 0); - else if (object.GuardianAddr.length >= 0) - message.GuardianAddr = object.GuardianAddr; - } - if (object.GuardianSignature != null) { - if (typeof object.GuardianSignature === "string") - $util.base64.decode(object.GuardianSignature, message.GuardianSignature = $util.newBuffer($util.base64.length(object.GuardianSignature)), 0); - else if (object.GuardianSignature.length >= 0) - message.GuardianSignature = object.GuardianSignature; - } - return message; - }; - Transaction4.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.Nonce = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.Nonce = options.longs === String ? "0" : 0; - if (options.bytes === String) - object.Value = ""; - else { - object.Value = []; - if (options.bytes !== Array) - object.Value = $util.newBuffer(object.Value); - } - if (options.bytes === String) - object.RcvAddr = ""; - else { - object.RcvAddr = []; - if (options.bytes !== Array) - object.RcvAddr = $util.newBuffer(object.RcvAddr); - } - if (options.bytes === String) - object.RcvUserName = ""; - else { - object.RcvUserName = []; - if (options.bytes !== Array) - object.RcvUserName = $util.newBuffer(object.RcvUserName); - } - if (options.bytes === String) - object.SndAddr = ""; - else { - object.SndAddr = []; - if (options.bytes !== Array) - object.SndAddr = $util.newBuffer(object.SndAddr); - } - if (options.bytes === String) - object.SndUserName = ""; - else { - object.SndUserName = []; - if (options.bytes !== Array) - object.SndUserName = $util.newBuffer(object.SndUserName); - } - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.GasPrice = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.GasPrice = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.GasLimit = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.GasLimit = options.longs === String ? "0" : 0; - if (options.bytes === String) - object.Data = ""; - else { - object.Data = []; - if (options.bytes !== Array) - object.Data = $util.newBuffer(object.Data); - } - if (options.bytes === String) - object.ChainID = ""; - else { - object.ChainID = []; - if (options.bytes !== Array) - object.ChainID = $util.newBuffer(object.ChainID); - } - object.Version = 0; - if (options.bytes === String) - object.Signature = ""; - else { - object.Signature = []; - if (options.bytes !== Array) - object.Signature = $util.newBuffer(object.Signature); - } - object.Options = 0; - if (options.bytes === String) - object.GuardianAddr = ""; - else { - object.GuardianAddr = []; - if (options.bytes !== Array) - object.GuardianAddr = $util.newBuffer(object.GuardianAddr); - } - if (options.bytes === String) - object.GuardianSignature = ""; - else { - object.GuardianSignature = []; - if (options.bytes !== Array) - object.GuardianSignature = $util.newBuffer(object.GuardianSignature); - } - } - if (message.Nonce != null && message.hasOwnProperty("Nonce")) - if (typeof message.Nonce === "number") - object.Nonce = options.longs === String ? String(message.Nonce) : message.Nonce; - else - object.Nonce = options.longs === String ? $util.Long.prototype.toString.call(message.Nonce) : options.longs === Number ? new $util.LongBits(message.Nonce.low >>> 0, message.Nonce.high >>> 0).toNumber(true) : message.Nonce; - if (message.Value != null && message.hasOwnProperty("Value")) - object.Value = options.bytes === String ? $util.base64.encode(message.Value, 0, message.Value.length) : options.bytes === Array ? Array.prototype.slice.call(message.Value) : message.Value; - if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) - object.RcvAddr = options.bytes === String ? $util.base64.encode(message.RcvAddr, 0, message.RcvAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvAddr) : message.RcvAddr; - if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) - object.RcvUserName = options.bytes === String ? $util.base64.encode(message.RcvUserName, 0, message.RcvUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvUserName) : message.RcvUserName; - if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) - object.SndAddr = options.bytes === String ? $util.base64.encode(message.SndAddr, 0, message.SndAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndAddr) : message.SndAddr; - if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) - object.SndUserName = options.bytes === String ? $util.base64.encode(message.SndUserName, 0, message.SndUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndUserName) : message.SndUserName; - if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) - if (typeof message.GasPrice === "number") - object.GasPrice = options.longs === String ? String(message.GasPrice) : message.GasPrice; - else - object.GasPrice = options.longs === String ? $util.Long.prototype.toString.call(message.GasPrice) : options.longs === Number ? new $util.LongBits(message.GasPrice.low >>> 0, message.GasPrice.high >>> 0).toNumber(true) : message.GasPrice; - if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) - if (typeof message.GasLimit === "number") - object.GasLimit = options.longs === String ? String(message.GasLimit) : message.GasLimit; - else - object.GasLimit = options.longs === String ? $util.Long.prototype.toString.call(message.GasLimit) : options.longs === Number ? new $util.LongBits(message.GasLimit.low >>> 0, message.GasLimit.high >>> 0).toNumber(true) : message.GasLimit; - if (message.Data != null && message.hasOwnProperty("Data")) - object.Data = options.bytes === String ? $util.base64.encode(message.Data, 0, message.Data.length) : options.bytes === Array ? Array.prototype.slice.call(message.Data) : message.Data; - if (message.ChainID != null && message.hasOwnProperty("ChainID")) - object.ChainID = options.bytes === String ? $util.base64.encode(message.ChainID, 0, message.ChainID.length) : options.bytes === Array ? Array.prototype.slice.call(message.ChainID) : message.ChainID; - if (message.Version != null && message.hasOwnProperty("Version")) - object.Version = message.Version; - if (message.Signature != null && message.hasOwnProperty("Signature")) - object.Signature = options.bytes === String ? $util.base64.encode(message.Signature, 0, message.Signature.length) : options.bytes === Array ? Array.prototype.slice.call(message.Signature) : message.Signature; - if (message.Options != null && message.hasOwnProperty("Options")) - object.Options = message.Options; - if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) - object.GuardianAddr = options.bytes === String ? $util.base64.encode(message.GuardianAddr, 0, message.GuardianAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianAddr) : message.GuardianAddr; - if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) - object.GuardianSignature = options.bytes === String ? $util.base64.encode(message.GuardianSignature, 0, message.GuardianSignature.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianSignature) : message.GuardianSignature; - return object; - }; - Transaction4.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - Transaction4.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === void 0) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/proto.Transaction"; - }; - return Transaction4; - }(); - return proto; - }(); - return $root; - }); - } -}); - -// node_modules/@multiversx/sdk-core/out/proto/serializer.js -var require_serializer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/proto/serializer.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ProtoSerializer = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var constants_1 = require_constants(); - var errors = __importStar2(require_errors()); - var utils_1 = require_utils(); - var ProtoSerializer = class { - /** - * Serializes a Transaction object to a Buffer. Handles low-level conversion logic and field-mappings as well. - */ - serializeTransaction(transaction) { - const proto = require_compiled().proto; - const receiverPubkey = new address_1.Address(transaction.getReceiver().bech32()).pubkey(); - const senderPubkey = new address_1.Address(transaction.getSender().bech32()).pubkey(); - let protoTransaction = new proto.Transaction({ - // mx-chain-go's serializer handles nonce == 0 differently, thus we treat 0 as "undefined". - Nonce: transaction.getNonce().valueOf() ? transaction.getNonce().valueOf() : void 0, - Value: this.serializeTransactionValue(transaction.getValue()), - RcvAddr: receiverPubkey, - RcvUserName: transaction.getReceiverUsername() ? import_buffer.Buffer.from(transaction.getReceiverUsername()).toString("base64") : void 0, - SndAddr: senderPubkey, - SndUserName: transaction.getSenderUsername() ? import_buffer.Buffer.from(transaction.getSenderUsername()).toString("base64") : void 0, - GasPrice: transaction.getGasPrice().valueOf(), - GasLimit: transaction.getGasLimit().valueOf(), - Data: transaction.getData().length() == 0 ? null : transaction.getData().valueOf(), - ChainID: import_buffer.Buffer.from(transaction.getChainID().valueOf()), - Version: transaction.getVersion().valueOf(), - Signature: transaction.getSignature() - }); - if (transaction.getOptions().valueOf() !== constants_1.TRANSACTION_OPTIONS_DEFAULT) { - protoTransaction.Options = transaction.getOptions().valueOf(); - } - if (transaction.isGuardedTransaction()) { - const guardianAddress = transaction.getGuardian(); - protoTransaction.GuardianAddr = new address_1.Address(guardianAddress.bech32()).pubkey(); - protoTransaction.GuardianSignature = transaction.getGuardianSignature(); - } - const encoded = proto.Transaction.encode(protoTransaction).finish(); - const buffer = import_buffer.Buffer.from(encoded); - return buffer; - } - /** - * Custom serialization, compatible with mx-chain-go. - */ - serializeTransactionValue(transactionValue) { - let value = new bignumber_js_1.default(transactionValue.toString()); - if (value.isZero()) { - return import_buffer.Buffer.from([0, 0]); - } - let buffer = utils_1.bigIntToBuffer(value); - buffer = import_buffer.Buffer.concat([import_buffer.Buffer.from([0]), buffer]); - return buffer; - } - deserializeTransaction(_buffer) { - throw new errors.ErrUnsupportedOperation("deserializeTransaction"); - } - }; - exports2.ProtoSerializer = ProtoSerializer; - } -}); - -// node_modules/@multiversx/sdk-core/out/proto/index.js -var require_proto = __commonJS({ - "node_modules/@multiversx/sdk-core/out/proto/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_serializer(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionComputer.js -var require_transactionComputer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionComputer.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionComputer = void 0; - var errors = __importStar2(require_errors()); - var bignumber_js_1 = __importDefault2(require_bignumber()); - var proto_1 = require_proto(); - var transaction_1 = require_transaction(); - var constants_1 = require_constants(); - var createTransactionHasher = require_blake2b2(); - var createKeccakHash = require_js(); - var TRANSACTION_HASH_LENGTH = 32; - var TransactionComputer2 = class { - constructor() { - } - computeTransactionFee(transaction, networkConfig2) { - const moveBalanceGas = BigInt(networkConfig2.MinGasLimit + transaction.data.length * networkConfig2.GasPerDataByte); - if (moveBalanceGas > transaction.gasLimit) { - throw new errors.ErrNotEnoughGas(parseInt(transaction.gasLimit.toString(), 10)); - } - const gasPrice = transaction.gasPrice; - const feeForMove = moveBalanceGas * gasPrice; - if (moveBalanceGas === transaction.gasLimit) { - return feeForMove; - } - const diff = transaction.gasLimit - moveBalanceGas; - const modifiedGasPrice = BigInt(new bignumber_js_1.default(gasPrice.toString()).multipliedBy(new bignumber_js_1.default(networkConfig2.GasPriceModifier)).toFixed(0)); - const processingFee = diff * modifiedGasPrice; - return feeForMove + processingFee; - } - computeBytesForSigning(transaction) { - this.ensureValidTransactionFields(transaction); - const plainTransaction = this.toPlainObjectForSigning(transaction); - const serialized = JSON.stringify(plainTransaction); - return new Uint8Array(import_buffer.Buffer.from(serialized)); - } - computeBytesForVerifying(transaction) { - const isTxSignedByHash = this.hasOptionsSetForHashSigning(transaction); - if (isTxSignedByHash) { - return this.computeHashForSigning(transaction); - } - return this.computeBytesForSigning(transaction); - } - computeHashForSigning(transaction) { - const plainTransaction = this.toPlainObjectForSigning(transaction); - const signable = import_buffer.Buffer.from(JSON.stringify(plainTransaction)); - return createKeccakHash("keccak256").update(signable).digest(); - } - computeTransactionHash(transaction) { - const serializer = new proto_1.ProtoSerializer(); - const buffer = serializer.serializeTransaction(new transaction_1.Transaction(transaction)); - const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); - return import_buffer.Buffer.from(hash, "hex"); - } - hasOptionsSetForGuardedTransaction(transaction) { - return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - hasOptionsSetForHashSigning(transaction) { - return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - applyGuardian(transaction, guardian) { - if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { - transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; - } - transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - transaction.guardian = guardian; - } - applyOptionsForHashSigning(transaction) { - if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { - transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; - } - transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - toPlainObjectForSigning(transaction) { - return { - nonce: Number(transaction.nonce), - value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, - senderUsername: this.toBase64OrUndefined(transaction.senderUsername), - receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), - gasPrice: Number(transaction.gasPrice), - gasLimit: Number(transaction.gasLimit), - data: this.toBase64OrUndefined(transaction.data), - chainID: transaction.chainID, - version: transaction.version, - options: transaction.options ? transaction.options : void 0, - guardian: transaction.guardian ? transaction.guardian : void 0 - }; - } - toBase64OrUndefined(value) { - return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; - } - ensureValidTransactionFields(transaction) { - if (transaction.sender.length !== constants_1.BECH32_ADDRESS_LENGTH) { - throw new errors.ErrBadUsage("Invalid `sender` field. Should be the bech32 address of the sender."); - } - if (transaction.receiver.length !== constants_1.BECH32_ADDRESS_LENGTH) { - throw new errors.ErrBadUsage("Invalid `receiver` field. Should be the bech32 address of the receiver."); - } - if (!transaction.chainID.length) { - throw new errors.ErrBadUsage("The `chainID` field is not set"); - } - if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { - if (this.hasOptionsSetForGuardedTransaction(transaction) || this.hasOptionsSetForHashSigning(transaction)) { - throw new errors.ErrBadUsage(`Non-empty transaction options requires transaction version >= ${constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`); - } - } - } - }; - exports2.TransactionComputer = TransactionComputer2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transaction.js -var require_transaction = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transaction.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionHash = exports2.Transaction = void 0; - var bignumber_js_1 = require_bignumber(); - var address_1 = require_address(); - var constants_1 = require_constants(); - var transactionsConverter_1 = require_transactionsConverter(); - var hash_1 = require_hash(); - var networkParams_1 = require_networkParams(); - var signature_1 = require_signature(); - var transactionPayload_1 = require_transactionPayload(); - var transactionComputer_1 = require_transactionComputer(); - var Transaction4 = class { - /** - * Creates a new Transaction object. - */ - constructor(options) { - this.nonce = BigInt(options.nonce?.valueOf() || 0n); - this.value = options.value ? BigInt(new bignumber_js_1.BigNumber(options.value.toString()).toFixed(0)) : 0n; - this.sender = this.addressAsBech32(options.sender); - this.receiver = this.addressAsBech32(options.receiver); - this.senderUsername = options.senderUsername || ""; - this.receiverUsername = options.receiverUsername || ""; - this.gasPrice = BigInt(options.gasPrice?.valueOf() || constants_1.TRANSACTION_MIN_GAS_PRICE); - this.gasLimit = BigInt(options.gasLimit.valueOf()); - this.data = options.data?.valueOf() || new Uint8Array(); - this.chainID = options.chainID.valueOf(); - this.version = Number(options.version?.valueOf() || constants_1.TRANSACTION_VERSION_DEFAULT); - this.options = Number(options.options?.valueOf() || constants_1.TRANSACTION_OPTIONS_DEFAULT); - this.guardian = options.guardian ? this.addressAsBech32(options.guardian) : ""; - this.signature = options.signature || import_buffer.Buffer.from([]); - this.guardianSignature = options.guardianSignature || import_buffer.Buffer.from([]); - } - addressAsBech32(address) { - return typeof address === "string" ? address : address.bech32(); - } - /** - * Legacy method, use the "nonce" property instead. - */ - getNonce() { - return Number(this.nonce); - } - /** - * Legacy method, use the "nonce" property instead. - * Sets the account sequence number of the sender. Must be done prior signing. - */ - setNonce(nonce) { - this.nonce = BigInt(nonce.valueOf()); - } - /** - * Legacy method, use the "value" property instead. - */ - getValue() { - return this.value; - } - /** - * Legacy method, use the "value" property instead. - */ - setValue(value) { - this.value = BigInt(value.toString()); - } - /** - * Legacy method, use the "sender" property instead. - */ - getSender() { - return address_1.Address.fromBech32(this.sender); - } - /** - * Legacy method, use the "sender" property instead. - */ - setSender(sender) { - this.sender = typeof sender === "string" ? sender : sender.bech32(); - } - /** - * Legacy method, use the "receiver" property instead. - */ - getReceiver() { - return address_1.Address.fromBech32(this.receiver); - } - /** - * Legacy method, use the "senderUsername" property instead. - */ - getSenderUsername() { - return this.senderUsername; - } - /** - * Legacy method, use the "senderUsername" property instead. - */ - setSenderUsername(senderUsername) { - this.senderUsername = senderUsername; - } - /** - * Legacy method, use the "receiverUsername" property instead. - */ - getReceiverUsername() { - return this.receiverUsername; - } - /** - * Legacy method, use the "receiverUsername" property instead. - */ - setReceiverUsername(receiverUsername) { - this.receiverUsername = receiverUsername; - } - /** - * Legacy method, use the "guardian" property instead. - */ - getGuardian() { - return new address_1.Address(this.guardian); - } - /** - * Legacy method, use the "gasPrice" property instead. - */ - getGasPrice() { - return Number(this.gasPrice); - } - /** - * Legacy method, use the "gasPrice" property instead. - */ - setGasPrice(gasPrice) { - this.gasPrice = BigInt(gasPrice.valueOf()); - } - /** - * Legacy method, use the "gasLimit" property instead. - */ - getGasLimit() { - return Number(this.gasLimit); - } - /** - * Legacy method, use the "gasLimit" property instead. - */ - setGasLimit(gasLimit) { - this.gasLimit = BigInt(gasLimit.valueOf()); - } - /** - * Legacy method, use the "data" property instead. - */ - getData() { - return new transactionPayload_1.TransactionPayload(import_buffer.Buffer.from(this.data)); - } - /** - * Legacy method, use the "chainID" property instead. - */ - getChainID() { - return this.chainID; - } - /** - * Legacy method, use the "chainID" property instead. - */ - setChainID(chainID) { - this.chainID = chainID.valueOf(); - } - /** - * Legacy method, use the "version" property instead. - */ - getVersion() { - return new networkParams_1.TransactionVersion(this.version); - } - /** - * Legacy method, use the "version" property instead. - */ - setVersion(version2) { - this.version = version2.valueOf(); - } - /** - * Legacy method, use the "options" property instead. - */ - getOptions() { - return new networkParams_1.TransactionOptions(this.options.valueOf()); - } - /** - * Legacy method, use the "options" property instead. - * - * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. - */ - setOptions(options) { - this.options = options.valueOf(); - } - /** - * Legacy method, use the "signature" property instead. - */ - getSignature() { - return import_buffer.Buffer.from(this.signature); - } - /** - * Legacy method, use the "guardianSignature" property instead. - */ - getGuardianSignature() { - return import_buffer.Buffer.from(this.guardianSignature); - } - /** - * Legacy method, use the "guardian" property instead. - */ - setGuardian(guardian) { - this.guardian = typeof guardian === "string" ? guardian : guardian.bech32(); - } - /** - * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. - */ - getHash() { - return TransactionHash.compute(this); - } - /** - * Legacy method, use "TransactionComputer.computeBytesForSigning()" instead. - * Serializes a transaction to a sequence of bytes, ready to be signed. - * This function is called internally by signers. - */ - serializeForSigning() { - const computer = new transactionComputer_1.TransactionComputer(); - const bytes = computer.computeBytesForSigning(this); - return import_buffer.Buffer.from(bytes); - } - /** - * Checks the integrity of the guarded transaction - */ - isGuardedTransaction() { - const hasGuardian = this.guardian.length > 0; - const hasGuardianSignature = this.guardianSignature.length > 0; - return this.getOptions().isWithGuardian() && hasGuardian && hasGuardianSignature; - } - /** - * Legacy method, use "TransactionsConverter.transactionToPlainObject()" instead. - * - * Converts the transaction object into a ready-to-serialize, plain JavaScript object. - * This function is called internally within the signing procedure. - */ - toPlainObject() { - const converter = new transactionsConverter_1.TransactionsConverter(); - return converter.transactionToPlainObject(this); - } - /** - * Legacy method, use "TransactionsConverter.plainObjectToTransaction()" instead. - * Converts a plain object transaction into a Transaction Object. - * - * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() - */ - static fromPlainObject(plainObjectTransaction) { - const converter = new transactionsConverter_1.TransactionsConverter(); - return converter.plainObjectToTransaction(plainObjectTransaction); - } - /** - * Legacy method, use the "signature" property instead. - * Applies the signature on the transaction. - * - * @param signature The signature, as computed by a signer. - */ - applySignature(signature) { - this.signature = signature_1.interpretSignatureAsBuffer(signature); - } - /** - * Legacy method, use the "guardianSignature" property instead. - * Applies the guardian signature on the transaction. - * - * @param guardianSignature The signature, as computed by a signer. - */ - applyGuardianSignature(guardianSignature) { - this.guardianSignature = signature_1.interpretSignatureAsBuffer(guardianSignature); - } - /** - * Converts a transaction to a ready-to-broadcast object. - * Called internally by the network provider. - */ - toSendable() { - return this.toPlainObject(); - } - /** - * Legacy method, use "TransactionComputer.computeTransactionFee()" instead. - * - * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties - * @param networkConfig {@link NetworkConfig} - */ - computeFee(networkConfig2) { - const computer = new transactionComputer_1.TransactionComputer(); - const fee = computer.computeTransactionFee(this, networkConfig2); - return new bignumber_js_1.BigNumber(fee.toString()); - } - }; - exports2.Transaction = Transaction4; - var TransactionHash = class _TransactionHash extends hash_1.Hash { - constructor(hash) { - super(hash); - } - /** - * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. - * Computes the hash of a transaction. - */ - static compute(transaction) { - const computer = new transactionComputer_1.TransactionComputer(); - const hash = computer.computeTransactionHash(transaction); - return new _TransactionHash(import_buffer.Buffer.from(hash).toString("hex")); - } - }; - exports2.TransactionHash = TransactionHash; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js -var require_tokenOperationsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenOperationsFactory = void 0; - var constants_1 = require_constants(); - var logger_1 = require_logger(); - var networkParams_1 = require_networkParams(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var codec_1 = require_codec(); - var TokenOperationsFactory2 = class { - constructor(config) { - this.config = config; - this.trueAsHex = codec_1.utf8ToHex("true"); - this.falseAsHex = codec_1.utf8ToHex("false"); - } - issueFungible(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "issue", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.bigIntToHex(args.initialSupply), - codec_1.bigIntToHex(args.numDecimals), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - notifyAboutUnsettingBurnRoleGlobally() { - logger_1.Logger.info(` +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}boolToString(e){return e?this.trueAsString:this.falseAsString}};u0.TokenManagementTransactionsFactory=gE});var mE=B(c0=>{"use strict";h();Object.defineProperty(c0,"__esModule",{value:!0});c0.TransactionsFactoryConfig=void 0;var XK=hr(),pE=class{constructor(e){this.chainID=e.chainID,this.addressHrp=XK.DEFAULT_HRP,this.minGasLimit=50000n,this.gasLimitPerByte=1500n,this.gasLimitIssue=60000000n,this.gasLimitToggleBurnRoleGlobally=60000000n,this.gasLimitEsdtLocalMint=300000n,this.gasLimitEsdtLocalBurn=300000n,this.gasLimitSetSpecialRole=60000000n,this.gasLimitPausing=60000000n,this.gasLimitFreezing=60000000n,this.gasLimitWiping=60000000n,this.gasLimitEsdtNftCreate=3000000n,this.gasLimitEsdtNftUpdateAttributes=1000000n,this.gasLimitEsdtNftAddQuantity=1000000n,this.gasLimitEsdtNftBurn=1000000n,this.gasLimitStorePerByte=10000n,this.issueCost=50000000000000000n,this.gasLimitStake=5000000n,this.gasLimitUnstake=5000000n,this.gasLimitUnbond=5000000n,this.gasLimitCreateDelegationContract=50000000n,this.gasLimitDelegationOperations=1000000n,this.additionalGasLimitPerValidatorNode=6000000n,this.additionalGasLimitForDelegationOperations=10000000n,this.gasLimitSaveKeyValue=100000n,this.gasLimitPersistPerByte=1000n,this.gasLimitSetGuardian=250000n,this.gasLimitGuardAccount=250000n,this.gasLimitUnguardAccount=250000n,this.gasLimitESDTTransfer=200000n,this.gasLimitESDTNFTTransfer=200000n,this.gasLimitMultiESDTNFTTransfer=200000n,this.gasLimitClaimDeveloperRewards=6000000n,this.gasLimitChangeOwnerAddress=6000000n}};c0.TransactionsFactoryConfig=pE});var UO=B(l0=>{"use strict";h();Object.defineProperty(l0,"__esModule",{value:!0});l0.TransferTransactionsFactory=void 0;var bo=Ie(),en=qn(),ZK=Ca(),Kf=Xr(),yE=Ms(),eW=fE(),LO=gc(),tW=1e5,FO=8e5,wE=class{constructor(e){this.isGasEstimator(e)?this.gasEstimator=e:(this.config=e.config,this.tokenComputer=new ZK.TokenComputer,this.tokenTransfersDataBuilder=new eW.TokenTransfersDataBuilder)}isGasEstimator(e){return typeof e=="object"&&typeof e.forEGLDTransfer=="function"&&typeof e.forESDTTransfer=="function"&&typeof e.forESDTNFTTransfer=="function"&&typeof e.forMultiESDTNFTTransfer=="function"}isGasEstimatorDefined(){return this.gasEstimator!==void 0}ensureMembersAreDefined(){if(this.config===void 0)throw new bo.Err("'config' is not defined");if(this.tokenTransfersDataBuilder===void 0)throw new bo.Err("`dataArgsBuilder is not defined`");if(this.tokenComputer===void 0)throw new bo.Err("`tokenComputer is not defined`")}createTransactionForNativeTokenTransfer(e){this.ensureMembersAreDefined();let r=e.data||new Uint8Array;return new Kf.Transaction({sender:e.sender.bech32(),receiver:e.receiver.bech32(),chainID:this.config.chainID,gasLimit:this.computeGasForMoveBalance(this.config,r),data:r,value:e.nativeAmount})}createTransactionForESDTTokenTransfer(e){this.ensureMembersAreDefined();let r=e.tokenTransfers.length;if(r===0)throw new bo.ErrBadUsage("No token transfer has been provided");if(r===1)return this.createSingleESDTTransferTransaction(e);let n=this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(e.receiver,e.tokenTransfers),i=this.config.gasLimitMultiESDTNFTTransfer*BigInt(r)+BigInt(FO);return new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:n,gasLimit:i,addDataMovementGas:!0}).build()}createEGLDTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.");let r=e.data?.length()||0,n=this.gasEstimator.forEGLDTransfer(r);return new Kf.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||n,data:e.data,chainID:e.chainID})}createESDTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.U64Value(e.tokenTransfer.nonce),new en.BigUIntValue(e.tokenTransfer.valueOf()),new en.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let r=[new en.AddressValue(e.destination),new en.U16Value(e.tokenTransfers.length)];for(let a of e.tokenTransfers)r.push(en.BytesValue.fromUTF8(a.tokenIdentifier),new en.U64Value(a.nonce),new en.BigUIntValue(a.valueOf()));let{argumentsString:n}=new en.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new yE.TransactionPayload(i),o=s.length()||0,u=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||u,data:s,chainID:e.chainID})}createSingleESDTTransferTransaction(e){this.ensureMembersAreDefined();let r=[],n=e.tokenTransfers[0],i=0n,s=e.receiver;return this.tokenComputer.isFungible(n.token)?(r=this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(n),i=this.config.gasLimitESDTTransfer+BigInt(tW)):(r=this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(n,s),i=this.config.gasLimitESDTNFTTransfer+BigInt(FO),s=e.sender),new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:s,dataParts:r,gasLimit:i,addDataMovementGas:!0}).build()}computeGasForMoveBalance(e,r){return e.minGasLimit+e.gasLimitPerByte*BigInt(r.length)}};l0.TransferTransactionsFactory=wE});var qO=B(h0=>{"use strict";h();Object.defineProperty(h0,"__esModule",{value:!0});h0.AccountTransactionsFactory=void 0;var rW=Ve(),f0=gc(),vE=class{constructor(e){this.config=e.config}createTransactionForSavingKeyValue(e){let r="SaveKeyValue",n=this.computeDataPartsForSavingKeyValue(e.keyValuePairs),i=[r,...n],s=this.computeExtraGasForSavingKeyValue(e.keyValuePairs);return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:i,gasLimit:s,addDataMovementGas:!0}).build()}computeExtraGasForSavingKeyValue(e){let r=0n;return e.forEach((n,i)=>{r+=this.config.gasLimitPersistPerByte*BigInt(i.length+n.length)+this.config.gasLimitStorePerByte*BigInt(n.length)}),r+this.config.gasLimitSaveKeyValue}computeDataPartsForSavingKeyValue(e){let r=[];return e.forEach((n,i)=>{r.push(p.Buffer.from(i).toString("hex"),p.Buffer.from(n).toString("hex"))}),r}createTransactionForSettingGuardian(e){let r=["SetGuardian",rW.Address.fromBech32(e.guardianAddress.bech32()).toHex(),p.Buffer.from(e.serviceID).toString("hex")];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitSetGuardian,addDataMovementGas:!0}).build()}createTransactionForGuardingAccount(e){let r=["GuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitGuardAccount,addDataMovementGas:!0}).build()}createTransactionForUnguardingAccount(e){let r=["UnGuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitUnguardAccount,addDataMovementGas:!0}).build()}};h0.AccountTransactionsFactory=vE});var d0=B(hn=>{"use strict";h();var nW=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Va=hn&&hn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&nW(e,t,r)};Object.defineProperty(hn,"__esModule",{value:!0});Va(AO(),hn);Va(OO(),hn);Va(dE(),hn);Va(MO(),hn);Va(mE(),hn);Va(UO(),hn);Va(qO(),hn)});var bE=B(Vn=>{"use strict";h();var iW=Vn&&Vn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sW=Vn&&Vn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oW=Vn&&Vn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iW(e,t,r);return sW(e,t),e},aW=Vn&&Vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.InteractionChecker=void 0;var AE=oW(Ie()),uW=aW((rr(),_e(fr))),EE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new uW.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new AE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new AE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let u=0;u{"use strict";h();Object.defineProperty(g0,"__esModule",{value:!0});g0.Query=void 0;var cW=Ve(),lW=fc(),SE=class{constructor(e){this.caller=e.caller||cW.Address.empty(),this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new lW.ArgSerializer().valuesToStrings(this.args)}};g0.Query=SE});var _E=B(p0=>{"use strict";h();Object.defineProperty(p0,"__esModule",{value:!0});p0.Interaction=void 0;var VO=Ve(),fW=rE(),hW=hr(),IE=Ca(),kO=d0(),dW=bE(),gW=Wf(),TE=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=VO.Address.empty(),this.sender=VO.Address.empty(),this.version=hW.TRANSACTION_VERSION_DEFAULT,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=[]}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){fW.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=new kO.TransactionsFactoryConfig({chainID:this.chainID.valueOf()}),n=new kO.SmartContractTransactionsFactory({config:e}).createTransactionForExecute({sender:this.sender,contract:this.contract.getAddress(),function:this.function.valueOf(),gasLimit:BigInt(this.gasLimit.valueOf()),arguments:this.args,nativeTransferAmount:BigInt(this.value.toString()),tokenTransfers:this.tokenTransfers});return n.chainID=this.chainID.valueOf(),n.nonce=BigInt(this.nonce.valueOf()),n.version=this.version,this.gasPrice&&(n.gasPrice=BigInt(this.gasPrice.valueOf())),n}buildQuery(){return new gW.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withSingleESDTNFTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withMultiESDTNFTTransfer(e){return this.tokenTransfers=e.map(r=>new IE.TokenTransfer(r)),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withVersion(e){return this.version=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new dW.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};p0.Interaction=TE});var CE=B(HO=>{"use strict";h();Object.defineProperty(HO,"__esModule",{value:!0})});var QO=B(yc=>{"use strict";h();Object.defineProperty(yc,"__esModule",{value:!0});yc.bech32m=yc.bech32=void 0;var m0="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jO={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function GO(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=mc(e)^n>>5}e=mc(e);for(let r=0;r=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<a)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=GO(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=mc(c)^w,f+=m0.charAt(w)}for(let d=0;d<6;++d)c=mc(c);c^=e;for(let d=0;d<6;++d){let w=c>>(5-d)*5&31;f+=m0.charAt(w)}return f}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";let a=o.toLowerCase(),c=o.toUpperCase();if(o!==a&&o!==c)return"Mixed-case string "+o;o=a;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),w=o.slice(f+1);if(w.length<6)return"Data too short";let A=GO(d);if(typeof A=="string")return A;let T=[];for(let x=0;x=w.length)&&T.push(V)}return A!==e?"Invalid checksum for "+o:{prefix:d,words:T}}function i(o,u){let a=n(o,u);if(typeof a=="object")return a}function s(o,u){let a=n(o,u);if(typeof a=="object")return a;throw new Error(a)}return{decodeUnsafe:i,decode:s,encode:r,toWords:pW,fromWordsUnsafe:mW,fromWords:yW}}yc.bech32=zO("bech32");yc.bech32m=zO("bech32m")});var WO=B(kn=>{"use strict";h();Object.defineProperty(kn,"__esModule",{value:!0});kn.TokenTransferProperties=kn.TransactionMetadataTransfer=kn.TransactionMetadata=kn.TransactionToDecode=kn.TransactionDecoder=void 0;var KO=QO(),xE=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new ka;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new y0;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new ka;s.transfers||(s.transfers=[]);let o=2;for(let u=0;uo&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),u=new ka;return u.sender=e.sender,u.receiver=o,u.value=s,r.length>4&&(u.functionName=this.hexToString(r[4]),u.functionArgs=r.slice(5)),u.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],u}base64Encode(e){return p.Buffer.from(e).toString("base64")}base64Decode(e){return p.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new ka;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=p.Buffer.from(e,"hex"),n=KO.bech32.toWords(r);return KO.bech32.encode("erd",n)}isAddressValid(e){return p.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return p.Buffer.from(e,"base64").toString("hex")}hexToString(e){return p.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};kn.TransactionDecoder=xE;var y0=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};kn.TransactionToDecode=y0;var ka=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};kn.TransactionMetadata=ka;var OE=class{constructor(){this.value=BigInt(0)}};kn.TransactionMetadataTransfer=OE;var DE=class{};kn.TokenTransferProperties=DE});var PE=B(w0=>{"use strict";h();Object.defineProperty(w0,"__esModule",{value:!0});w0.ReturnCode=void 0;var mt=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};w0.ReturnCode=mt;mt.None=new mt("");mt.Ok=new mt("ok");mt.FunctionNotFound=new mt("function not found");mt.FunctionWrongSignature=new mt("wrong signature for function");mt.ContractNotFound=new mt("contract not found");mt.UserError=new mt("user error");mt.OutOfGas=new mt("out of gas");mt.AccountCollision=new mt("account collision");mt.OutOfFunds=new mt("out of funds");mt.CallStackOverFlow=new mt("call stack overflow");mt.ContractInvalid=new mt("contract invalid");mt.ExecutionFailed=new mt("execution failed");mt.Unknown=new mt("unknown")});var JO=B(v0=>{"use strict";h();Object.defineProperty(v0,"__esModule",{value:!0});v0.ResultsParser=void 0;var wW=WO(),$O=Ve(),YO=Ie(),So=oo(),vW=fc(),wc=PE(),vc;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(vc||(vc={}));var RE;(function(t){t.TooMuchGas="@too much gas provided for processing"})(RE||(RE={}));var AW={argsSerializer:new vW.ArgSerializer},BE=class{constructor(e){e={...AW,...e},this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e);return this.parseOutcomeFromUntypedBundle(n,r)}parseOutcomeFromUntypedBundle(e,r){let n=this.argsSerializer.buffersToValues(e.values,r.output);return{returnCode:e.returnCode,returnMessage:e.returnMessage,values:n,firstValue:n[0],secondValue:n[1],thirdValue:n[2],lastValue:n[n.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return So.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return So.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return So.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return So.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new YO.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new wW.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:wc.ReturnCode.None,returnMessage:wc.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:wc.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(vc.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(vc.OnWriteLog,u=>u.findFirstOrNoneTopic(a=>a.toString().startsWith(RE.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new $O.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(vc.OnWriteLog,a=>a.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),u=s.toString();return{returnCode:s,returnMessage:u,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new $O.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(vc.OnWriteLog,o=>{let u=o.address.bech32()==e.sender.bech32(),a=o.topics[0]?.hex()==n.hex();return u&&a});if(s){let{returnCode:o,returnDataParts:u}=this.sliceDataFieldInParts(s.data),a=o.toString();return{returnCode:o,returnMessage:a,values:u}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||p.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new YO.ErrCannotParseContractResults("no return code");return{returnCode:wc.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){let n=e.topics.map(o=>p.Buffer.from(o.valueOf())).slice(1),i=e.dataPayload?.valueOf()||p.Buffer.from([]),s=e.additionalData?.map(o=>p.Buffer.from(o.valueOf()))||[];return s.length===0&&i.length&&s.push(p.Buffer.from(i)),this.doParseEvent({topics:n,dataItems:s,eventDefinition:r})}doParseEvent(e){let r={},n=e.eventDefinition.inputs.filter(u=>u.indexed),i=this.argsSerializer.buffersToValues(e.topics,n);for(let u=0;u!u.indexed),o=this.argsSerializer.buffersToValues(e.dataItems,s);for(let u=0;u{"use strict";h();Object.defineProperty(E0,"__esModule",{value:!0});E0.SmartContract=void 0;var A0=Ve(),ME=rE(),LE=hr(),EW=Ie(),FE=dE(),UE=mE(),bW=Rn(),XO=XA(),ZO=eE(),eD=_E(),SW=n0(),IW=Wf(),qE=class{constructor(e={}){this.address=A0.Address.empty(),this.methodsExplicit={},this.methods={},this.address=e.address||A0.Address.empty(),this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new ZO.ContractFunction(i);return new eD.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new ZO.ContractFunction(i),u=SW.NativeSerializer.nativeToTypedValues(s||[],n);return new eD.Interaction(e,o,u||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return bW.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()");let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=p.Buffer.from(r.toString(),"hex"),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForDeploy({sender:e,bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}getMetadataPropertiesAsObject(e){let r;return e?r=XO.CodeMetadata.fromBytes(p.Buffer.from(e.toString(),"hex")):r=new XO.CodeMetadata,r.toJSON()}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=Uint8Array.from(p.Buffer.from(r.toString(),"hex")),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForUpgrade({sender:e,contract:this.getAddress(),bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:u,caller:a}){ME.Compatibility.guardAddressIsSetAndNonZero(a,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:u.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi});r=r||[],n=n||0;let d=f.createTransactionForExecute({sender:a,contract:s||this.getAddress(),function:e.toString(),gasLimit:BigInt(i.valueOf()),arguments:r});return d.setChainID(u),d.setValue(n),d.setGasPrice(o??LE.TRANSACTION_MIN_GAS_PRICE),d}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new IW.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new EW.ErrContractHasNoAddress}static computeAddress(e,r){let n=A0.Address.fromBech32(e.bech32());return new A0.AddressComputer().computeContractAddress(n,BigInt(r.valueOf()))}};E0.SmartContract=qE});var rD=B(Io=>{"use strict";h();Object.defineProperty(Io,"__esModule",{value:!0});Io.ContractCallPayloadBuilder=Io.ContractUpgradePayloadBuilder=Io.ContractDeployPayloadBuilder=void 0;var TW=hr(),GE=Ms(),jE=Rn(),_W=fc(),VE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${TW.WasmVirtualMachine}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractDeployPayloadBuilder=VE;var kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractUpgradePayloadBuilder=kE;var HE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=zE(e,this.arguments),new GE.TransactionPayload(e)}};Io.ContractCallPayloadBuilder=HE;function zE(t,e){let{argumentsString:r,count:n}=new _W.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var qn=B(Jt=>{"use strict";h();var CW=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qr=Jt&&Jt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&CW(e,t,r)};Object.defineProperty(Jt,"__esModule",{value:!0});qr(fc(),Jt);qr(vO(),Jt);qr(GA(),Jt);qr(XA(),Jt);qr(eE(),Jt);qr(_E(),Jt);qr(bE(),Jt);qr(CE(),Jt);qr(n0(),Jt);qr(Wf(),Jt);qr(JO(),Jt);qr(PE(),Jt);qr(tD(),Jt);qr(rD(),Jt);qr(dr(),Jt)});var Ac=B(or=>{"use strict";h();Object.defineProperty(or,"__esModule",{value:!0});or.gatherAllEvents=or.findEventsByFirstTopic=or.findEventsByIdentifier=or.findEventsByPredicate=or.SmartContractCallOutcome=or.TransactionOutcome=or.SmartContractResult=or.TransactionLogs=or.TransactionEvent=void 0;var QE=class{constructor(e){this.address="",this.identifier="",this.topics=[],this.dataItems=[],Object.assign(this,e)}};or.TransactionEvent=QE;var $f=class{constructor(e){this.address="",this.events=[],Object.assign(this,e)}};or.TransactionLogs=$f;var KE=class{constructor(e){this.sender="",this.receiver="",this.data=new Uint8Array,this.logs=new $f({}),Object.assign(this,e)}};or.SmartContractResult=KE;var WE=class{constructor(e){this.directSmartContractCallOutcome=new b0({}),this.smartContractResults=[],this.logs=new $f({}),Object.assign(this,e)}};or.TransactionOutcome=WE;var b0=class{constructor(e){this.function="",this.returnDataParts=[],this.returnMessage="",this.returnCode="",Object.assign(this,e)}};or.SmartContractCallOutcome=b0;function $E(t,e){return nD(t).filter(e)}or.findEventsByPredicate=$E;function NW(t,e){return $E(t,r=>r.identifier==e)}or.findEventsByIdentifier=NW;function xW(t,e){return $E(t,r=>r.topics[0]?.toString()==e)}or.findEventsByFirstTopic=xW;function nD(t){let e=[];e.push(...t.logs.events);for(let r of t.smartContractResults)e.push(...r.logs.events);return e}or.gatherAllEvents=nD});var JE=B(S0=>{"use strict";h();Object.defineProperty(S0,"__esModule",{value:!0});S0.TransactionsConverter=void 0;var OW=qn(),DW=Xr(),Ec=Ac(),YE=class{transactionToPlainObject(e){return{nonce:Number(e.nonce),value:e.value.toString(),receiver:e.receiver,sender:e.sender,senderUsername:this.toBase64OrUndefined(e.senderUsername),receiverUsername:this.toBase64OrUndefined(e.receiverUsername),gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:this.toBase64OrUndefined(e.data),chainID:e.chainID.valueOf(),version:e.version,options:e.options==0?void 0:e.options,guardian:e.guardian?e.guardian:void 0,signature:this.toHexOrUndefined(e.signature),guardianSignature:this.toHexOrUndefined(e.guardianSignature)}}toBase64OrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("base64"):void 0}toHexOrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("hex"):void 0}plainObjectToTransaction(e){return new DW.Transaction({nonce:BigInt(e.nonce),value:BigInt(e.value||""),receiver:e.receiver,receiverUsername:this.bufferFromBase64(e.receiverUsername).toString(),sender:e.sender,senderUsername:this.bufferFromBase64(e.senderUsername).toString(),guardian:e.guardian,gasPrice:BigInt(e.gasPrice),gasLimit:BigInt(e.gasLimit),data:this.bufferFromBase64(e.data),chainID:String(e.chainID),version:Number(e.version),options:Number(e.options),signature:this.bufferFromHex(e.signature),guardianSignature:this.bufferFromHex(e.guardianSignature)})}bufferFromBase64(e){return p.Buffer.from(e||"","base64")}bufferFromHex(e){return p.Buffer.from(e||"","hex")}transactionOnNetworkToOutcome(e){let n=new OW.ResultsParser().parseUntypedOutcome(e),i=new Ec.SmartContractCallOutcome({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.values}),s=e.contractResults.items.map(u=>this.smartContractResultOnNetworkToSmartContractResult(u)),o=new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(u=>this.eventOnNetworkToEvent(u))});return new Ec.TransactionOutcome({logs:o,smartContractResults:s,directSmartContractCallOutcome:i})}smartContractResultOnNetworkToSmartContractResult(e){return new Ec.SmartContractResult({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:p.Buffer.from(e.data),logs:new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(r=>this.eventOnNetworkToEvent(r))})})}eventOnNetworkToEvent(e){let r=e.dataPayload?.valueOf()||p.Buffer.from(e.data||""),n=e.additionalData?.map(i=>p.Buffer.from(i.valueOf()))||[];return n.length===0&&r.length&&n.push(p.Buffer.from(r)),new Ec.TransactionEvent({address:e.address.bech32(),identifier:e.identifier,topics:e.topics.map(i=>p.Buffer.from(i.hex(),"hex")),dataItems:n})}};S0.TransactionsConverter=YE});var iD=B(Yi=>{"use strict";h();var PW=Yi&&Yi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RW=Yi&&Yi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BW=Yi&&Yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PW(e,t,r);return RW(e,t),e};Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Hash=void 0;var MW=BW(Ie()),XE=class t{constructor(e){if(!e)this.hash=p.Buffer.from([]);else if(e instanceof p.Buffer)this.hash=e;else if(typeof e=="string")this.hash=p.Buffer.from(e,"hex");else throw new MW.ErrBadType("hash","buffer | string",e)}static empty(){return new t(p.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};Yi.Hash=XE});var Yf=B(Hn=>{"use strict";h();var LW=Hn&&Hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FW=Hn&&Hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),UW=Hn&&Hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LW(e,t,r);return FW(e,t),e};Object.defineProperty(Hn,"__esModule",{value:!0});Hn.interpretSignatureAsBuffer=Hn.Signature=void 0;var sD=UW(Ie()),oD=64,ZE=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof p.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==oD}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=oD)throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Hn.Signature=ZE;function qW(t){if(ArrayBuffer.isView(t))return p.Buffer.from(t);if(t.hex!=null)return p.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Hn.interpretSignatureAsBuffer=qW});var uD=B((F1e,aD)=>{"use strict";h();aD.exports=VW;function VW(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";h();var I0=fD;I0.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bc=new Array(64),lD=new Array(123);for(mi=0;mi<64;)lD[bc[mi]=mi<26?mi+65:mi<52?mi+71:mi<62?mi-4:mi-59|43]=mi++;var mi;I0.encode=function(e,r,n){for(var i=null,s=[],o=0,u=0,a;r>2],a=(c&3)<<4,u=1;break;case 1:s[o++]=bc[a|c>>4],a=(c&15)<<2,u=2;break;case 2:s[o++]=bc[a|c>>6],s[o++]=bc[c&63],u=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return u&&(s[o++]=bc[a],s[o++]=61,u===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var cD="invalid encoding";I0.decode=function(e,r,n){for(var i=n,s=0,o,u=0;u1)break;if((a=lD[a])===void 0)throw Error(cD);switch(s){case 0:o=a,s=1;break;case 1:r[n++]=o<<2|(a&48)>>4,o=a,s=2;break;case 2:r[n++]=(o&15)<<4|(a&60)>>2,o=a,s=3;break;case 3:r[n++]=(o&3)<<6|a,s=0;break}}if(s===1)throw Error(cD);return n-i};I0.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var gD=B((k1e,dD)=>{"use strict";h();dD.exports=T0;function T0(){this._listeners={}}T0.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};T0.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";h();AD.exports=pD(pD);function pD(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(a,c,f){e[0]=a,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],e[0]}function u(a,c){return r[3]=a[c],r[2]=a[c+1],r[1]=a[c+2],r[0]=a[c+3],e[0]}t.readFloatLE=n?o:u,t.readFloatBE=n?u:o}():function(){function e(n,i,s,o){var u=i<0?1:0;if(u&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((u<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((u<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var a=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-a)*8388608)&8388607;n((u<<31|a+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,mD),t.writeFloatBE=e.bind(null,yD);function r(n,i,s){var o=n(i,s),u=(o>>31)*2+1,a=o>>>23&255,c=o&8388607;return a===255?c?NaN:u*(1/0):a===0?u*1401298464324817e-60*c:u*Math.pow(2,a-150)*(c+8388608)}t.readFloatLE=r.bind(null,wD),t.readFloatBE=r.bind(null,vD)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(a,c,f){e[0]=a,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],r[4]=a[c+4],r[5]=a[c+5],r[6]=a[c+6],r[7]=a[c+7],e[0]}function u(a,c){return r[7]=a[c],r[6]=a[c+1],r[5]=a[c+2],r[4]=a[c+3],r[3]=a[c+4],r[2]=a[c+5],r[1]=a[c+6],r[0]=a[c+7],e[0]}t.readDoubleLE=n?o:u,t.readDoubleBE=n?u:o}():function(){function e(n,i,s,o,u,a){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,u,a+i),n(1/o>0?0:2147483648,u,a+s);else if(isNaN(o))n(0,u,a+i),n(2146959360,u,a+s);else if(o>17976931348623157e292)n(0,u,a+i),n((c<<31|2146435072)>>>0,u,a+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,u,a+i),n((c<<31|f/4294967296)>>>0,u,a+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,u,a+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,u,a+s)}}}t.writeDoubleLE=e.bind(null,mD,0,4),t.writeDoubleBE=e.bind(null,yD,4,0);function r(n,i,s,o,u){var a=n(o,u+i),c=n(o,u+s),f=(c>>31)*2+1,d=c>>>20&2047,w=4294967296*(c&1048575)+a;return d===2047?w?NaN:f*(1/0):d===0?f*5e-324*w:f*Math.pow(2,d-1075)*(w+4503599627370496)}t.readDoubleLE=r.bind(null,wD,0,4),t.readDoubleBE=r.bind(null,vD,4,0)}(),t}function mD(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function yD(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function wD(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function vD(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var bD=B((exports,module)=>{"use strict";h();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var ID=B(SD=>{"use strict";h();var eb=SD;eb.length=function(e){for(var r=0,n=0,i=0;i191&&a<224?o[u++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[u++]=55296+(a>>10),o[u++]=56320+(a&1023)):o[u++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,u>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),u=0);return s?(u&&s.push(String.fromCharCode.apply(String,o.slice(0,u))),s.join("")):String.fromCharCode.apply(String,o.slice(0,u))};eb.write=function(e,r,n){for(var i=n,s,o,u=0;u>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(u+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++u,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var _D=B((W1e,TD)=>{"use strict";h();TD.exports=kW;function kW(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);var c=e.call(s,o,o+=a);return o&7&&(o=(o|7)+1),c}}});var ND=B((Y1e,CD)=>{"use strict";h();CD.exports=yr;var Jf=_o();function yr(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ha=yr.zero=new yr(0,0);Ha.toNumber=function(){return 0};Ha.zzEncode=Ha.zzDecode=function(){return this};Ha.length=function(){return 1};var HW=yr.zeroHash="\0\0\0\0\0\0\0\0";yr.fromNumber=function(e){if(e===0)return Ha;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new yr(n,i)};yr.from=function(e){if(typeof e=="number")return yr.fromNumber(e);if(Jf.isString(e))if(Jf.Long)e=Jf.Long.fromString(e);else return yr.fromNumber(parseInt(e,10));return e.low||e.high?new yr(e.low>>>0,e.high>>>0):Ha};yr.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};yr.prototype.toLong=function(e){return Jf.Long?new Jf.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var To=String.prototype.charCodeAt;yr.fromHash=function(e){return e===HW?Ha:new yr((To.call(e,0)|To.call(e,1)<<8|To.call(e,2)<<16|To.call(e,3)<<24)>>>0,(To.call(e,4)|To.call(e,5)<<8|To.call(e,6)<<16|To.call(e,7)<<24)>>>0)};yr.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};yr.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};yr.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};yr.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var _o=B(tb=>{"use strict";h();var we=tb;we.asPromise=uD();we.base64=hD();we.EventEmitter=gD();we.float=ED();we.inquire=bD();we.utf8=ID();we.pool=_D();we.LongBits=ND();we.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);we.global=we.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||tb;we.emptyArray=Object.freeze?Object.freeze([]):[];we.emptyObject=Object.freeze?Object.freeze({}):{};we.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};we.isString=function(e){return typeof e=="string"||e instanceof String};we.isObject=function(e){return e&&typeof e=="object"};we.isset=we.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};we.Buffer=function(){try{var t=we.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();we._Buffer_from=null;we._Buffer_allocUnsafe=null;we.newBuffer=function(e){return typeof e=="number"?we.Buffer?we._Buffer_allocUnsafe(e):new we.Array(e):we.Buffer?we._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};we.Array=typeof Uint8Array<"u"?Uint8Array:Array;we.Long=we.global.dcodeIO&&we.global.dcodeIO.Long||we.global.Long||we.inquire("long");we.key2Re=/^true|false|0|1$/;we.key32Re=/^-?(?:0|[1-9][0-9]*)$/;we.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;we.longToHash=function(e){return e?we.LongBits.from(e).toHash():we.LongBits.zeroHash};we.longFromHash=function(e,r){var n=we.LongBits.fromHash(e);return we.Long?we.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function xD(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};we.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";h();BD.exports=Ue;var Gn=_o(),rb,_0=Gn.LongBits,DD=Gn.base64,PD=Gn.utf8;function Xf(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function ib(){}function GW(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Xf(ib,0,0),this.tail=this.head,this.states=null}var RD=function(){return Gn.Buffer?function(){return(Ue.create=function(){return new rb})()}:function(){return new Ue}};Ue.create=RD();Ue.alloc=function(e){return new Gn.Array(e)};Gn.Array!==Array&&(Ue.alloc=Gn.pool(Ue.alloc,Gn.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Xf(e,r,n),this.len+=r,this};function sb(t,e,r){e[r]=t&255}function jW(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function ob(t,e){this.len=t,this.next=void 0,this.val=e}ob.prototype=Object.create(Xf.prototype);ob.prototype.fn=jW;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ob((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(ab,10,_0.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ab(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=_0.from(e);return this._push(ab,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=_0.from(e).zzEncode();return this._push(ab,r.length(),r)};Ue.prototype.bool=function(e){return this._push(sb,1,e?1:0)};function nb(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(nb,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=_0.from(e);return this._push(nb,4,r.lo)._push(nb,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Gn.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Gn.float.writeDoubleLE,8,e)};var zW=Gn.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(sb,1,0);if(Gn.isString(e)){var n=Ue.alloc(r=DD.length(e));DD.decode(e,n,0),e=n}return this.uint32(r)._push(zW,r,e)};Ue.prototype.string=function(e){var r=PD.length(e);return r?this.uint32(r)._push(PD.write,r,e):this._push(sb,1,0)};Ue.prototype.fork=function(){return this.states=new GW(this),this.head=this.tail=new Xf(ib,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xf(ib,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){rb=t,Ue.create=RD(),rb._configure()}});var FD=B((rwe,LD)=>{"use strict";h();LD.exports=Ji;var MD=ub();(Ji.prototype=Object.create(MD.prototype)).constructor=Ji;var Co=_o();function Ji(){MD.call(this)}Ji._configure=function(){Ji.alloc=Co._Buffer_allocUnsafe,Ji.writeBytesBuffer=Co.Buffer&&Co.Buffer.prototype instanceof Uint8Array&&Co.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Ji.writeBytesBuffer,r,e),this};function QW(t,e,r){t.length<40?Co.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ji.prototype.string=function(e){var r=Co.Buffer.byteLength(e);return this.uint32(r),r&&this._push(QW,r,e),this};Ji._configure()});var fb=B((iwe,HD)=>{"use strict";h();HD.exports=Xt;var yi=_o(),lb,VD=yi.LongBits,KW=yi.utf8;function wi(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Xt(t){this.buf=t,this.pos=0,this.len=t.length}var UD=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Xt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Xt(e);throw Error("illegal buffer")},kD=function(){return yi.Buffer?function(r){return(Xt.create=function(i){return yi.Buffer.isBuffer(i)?new lb(i):UD(i)})(r)}:UD};Xt.create=kD();Xt.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Xt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wi(this,10);return e}}();Xt.prototype.int32=function(){return this.uint32()|0};Xt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function cb(){var t=new VD(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw wi(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw wi(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Xt.prototype.bool=function(){return this.uint32()!==0};function C0(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Xt.prototype.fixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)};Xt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)|0};function qD(){if(this.pos+8>this.len)throw wi(this,8);return new VD(C0(this.buf,this.pos+=4),C0(this.buf,this.pos+=4))}Xt.prototype.float=function(){if(this.pos+4>this.len)throw wi(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Xt.prototype.double=function(){if(this.pos+8>this.len)throw wi(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Xt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw wi(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var i=yi.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Xt.prototype.string=function(){var e=this.bytes();return KW.read(e,0,e.length)};Xt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wi(this);while(this.buf[this.pos++]&128);return this};Xt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Xt._configure=function(t){lb=t,Xt.create=kD(),lb._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Xt.prototype,{int64:function(){return cb.call(this)[e](!1)},uint64:function(){return cb.call(this)[e](!0)},sint64:function(){return cb.call(this).zzDecode()[e](!1)},fixed64:function(){return qD.call(this)[e](!0)},sfixed64:function(){return qD.call(this)[e](!1)}})}});var QD=B((owe,zD)=>{"use strict";h();zD.exports=Ga;var jD=fb();(Ga.prototype=Object.create(jD.prototype)).constructor=Ga;var GD=_o();function Ga(t){jD.call(this,t)}Ga._configure=function(){GD.Buffer&&(Ga.prototype._slice=GD.Buffer.prototype.slice)};Ga.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ga._configure()});var WD=B((uwe,KD)=>{"use strict";h();KD.exports=Zf;var hb=_o();(Zf.prototype=Object.create(hb.EventEmitter.prototype)).constructor=Zf;function Zf(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");hb.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Zf.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return hb.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(a,c){if(a)return o.emit("error",a,e),s(a);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(u){o.emit("error",u,e),setTimeout(function(){s(u)},0);return}};Zf.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var YD=B($D=>{"use strict";h();var WW=$D;WW.Service=WD()});var XD=B((hwe,JD)=>{"use strict";h();JD.exports={}});var t8=B(e8=>{"use strict";h();var tn=e8;tn.build="minimal";tn.Writer=ub();tn.BufferWriter=FD();tn.Reader=fb();tn.BufferReader=QD();tn.util=_o();tn.rpc=YD();tn.roots=XD();tn.configure=ZD;function ZD(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}ZD()});var n8=B((mwe,r8)=>{"use strict";h();r8.exports=t8()});var s8=B((i8,eh)=>{"use strict";h();(function(t,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof Bd=="function"&&typeof eh=="object"&&eh&&eh.exports&&(eh.exports=e(n8()))})(i8,function(t){"use strict";var e=t.Reader,r=t.Writer,n=t.util,i=t.roots.default||(t.roots.default={});return i.proto=function(){var s={};return s.Transaction=function(){function o(u){if(u)for(var a=Object.keys(u),c=0;c>>3){case 1:{d.Nonce=a.uint64();break}case 2:{d.Value=a.bytes();break}case 3:{d.RcvAddr=a.bytes();break}case 4:{d.RcvUserName=a.bytes();break}case 5:{d.SndAddr=a.bytes();break}case 6:{d.SndUserName=a.bytes();break}case 7:{d.GasPrice=a.uint64();break}case 8:{d.GasLimit=a.uint64();break}case 9:{d.Data=a.bytes();break}case 10:{d.ChainID=a.bytes();break}case 11:{d.Version=a.uint32();break}case 12:{d.Signature=a.bytes();break}case 13:{d.Options=a.uint32();break}case 14:{d.GuardianAddr=a.bytes();break}case 15:{d.GuardianSignature=a.bytes();break}default:a.skipType(w&7);break}}return d},o.decodeDelimited=function(a){return a instanceof e||(a=new e(a)),this.decode(a,a.uint32())},o.verify=function(a){return typeof a!="object"||a===null?"object expected":a.Nonce!=null&&a.hasOwnProperty("Nonce")&&!n.isInteger(a.Nonce)&&!(a.Nonce&&n.isInteger(a.Nonce.low)&&n.isInteger(a.Nonce.high))?"Nonce: integer|Long expected":a.Value!=null&&a.hasOwnProperty("Value")&&!(a.Value&&typeof a.Value.length=="number"||n.isString(a.Value))?"Value: buffer expected":a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&!(a.RcvAddr&&typeof a.RcvAddr.length=="number"||n.isString(a.RcvAddr))?"RcvAddr: buffer expected":a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&!(a.RcvUserName&&typeof a.RcvUserName.length=="number"||n.isString(a.RcvUserName))?"RcvUserName: buffer expected":a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&!(a.SndAddr&&typeof a.SndAddr.length=="number"||n.isString(a.SndAddr))?"SndAddr: buffer expected":a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&!(a.SndUserName&&typeof a.SndUserName.length=="number"||n.isString(a.SndUserName))?"SndUserName: buffer expected":a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&!n.isInteger(a.GasPrice)&&!(a.GasPrice&&n.isInteger(a.GasPrice.low)&&n.isInteger(a.GasPrice.high))?"GasPrice: integer|Long expected":a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&!n.isInteger(a.GasLimit)&&!(a.GasLimit&&n.isInteger(a.GasLimit.low)&&n.isInteger(a.GasLimit.high))?"GasLimit: integer|Long expected":a.Data!=null&&a.hasOwnProperty("Data")&&!(a.Data&&typeof a.Data.length=="number"||n.isString(a.Data))?"Data: buffer expected":a.ChainID!=null&&a.hasOwnProperty("ChainID")&&!(a.ChainID&&typeof a.ChainID.length=="number"||n.isString(a.ChainID))?"ChainID: buffer expected":a.Version!=null&&a.hasOwnProperty("Version")&&!n.isInteger(a.Version)?"Version: integer expected":a.Signature!=null&&a.hasOwnProperty("Signature")&&!(a.Signature&&typeof a.Signature.length=="number"||n.isString(a.Signature))?"Signature: buffer expected":a.Options!=null&&a.hasOwnProperty("Options")&&!n.isInteger(a.Options)?"Options: integer expected":a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&!(a.GuardianAddr&&typeof a.GuardianAddr.length=="number"||n.isString(a.GuardianAddr))?"GuardianAddr: buffer expected":a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&!(a.GuardianSignature&&typeof a.GuardianSignature.length=="number"||n.isString(a.GuardianSignature))?"GuardianSignature: buffer expected":null},o.fromObject=function(a){if(a instanceof i.proto.Transaction)return a;var c=new i.proto.Transaction;return a.Nonce!=null&&(n.Long?(c.Nonce=n.Long.fromValue(a.Nonce)).unsigned=!0:typeof a.Nonce=="string"?c.Nonce=parseInt(a.Nonce,10):typeof a.Nonce=="number"?c.Nonce=a.Nonce:typeof a.Nonce=="object"&&(c.Nonce=new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0))),a.Value!=null&&(typeof a.Value=="string"?n.base64.decode(a.Value,c.Value=n.newBuffer(n.base64.length(a.Value)),0):a.Value.length>=0&&(c.Value=a.Value)),a.RcvAddr!=null&&(typeof a.RcvAddr=="string"?n.base64.decode(a.RcvAddr,c.RcvAddr=n.newBuffer(n.base64.length(a.RcvAddr)),0):a.RcvAddr.length>=0&&(c.RcvAddr=a.RcvAddr)),a.RcvUserName!=null&&(typeof a.RcvUserName=="string"?n.base64.decode(a.RcvUserName,c.RcvUserName=n.newBuffer(n.base64.length(a.RcvUserName)),0):a.RcvUserName.length>=0&&(c.RcvUserName=a.RcvUserName)),a.SndAddr!=null&&(typeof a.SndAddr=="string"?n.base64.decode(a.SndAddr,c.SndAddr=n.newBuffer(n.base64.length(a.SndAddr)),0):a.SndAddr.length>=0&&(c.SndAddr=a.SndAddr)),a.SndUserName!=null&&(typeof a.SndUserName=="string"?n.base64.decode(a.SndUserName,c.SndUserName=n.newBuffer(n.base64.length(a.SndUserName)),0):a.SndUserName.length>=0&&(c.SndUserName=a.SndUserName)),a.GasPrice!=null&&(n.Long?(c.GasPrice=n.Long.fromValue(a.GasPrice)).unsigned=!0:typeof a.GasPrice=="string"?c.GasPrice=parseInt(a.GasPrice,10):typeof a.GasPrice=="number"?c.GasPrice=a.GasPrice:typeof a.GasPrice=="object"&&(c.GasPrice=new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0))),a.GasLimit!=null&&(n.Long?(c.GasLimit=n.Long.fromValue(a.GasLimit)).unsigned=!0:typeof a.GasLimit=="string"?c.GasLimit=parseInt(a.GasLimit,10):typeof a.GasLimit=="number"?c.GasLimit=a.GasLimit:typeof a.GasLimit=="object"&&(c.GasLimit=new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0))),a.Data!=null&&(typeof a.Data=="string"?n.base64.decode(a.Data,c.Data=n.newBuffer(n.base64.length(a.Data)),0):a.Data.length>=0&&(c.Data=a.Data)),a.ChainID!=null&&(typeof a.ChainID=="string"?n.base64.decode(a.ChainID,c.ChainID=n.newBuffer(n.base64.length(a.ChainID)),0):a.ChainID.length>=0&&(c.ChainID=a.ChainID)),a.Version!=null&&(c.Version=a.Version>>>0),a.Signature!=null&&(typeof a.Signature=="string"?n.base64.decode(a.Signature,c.Signature=n.newBuffer(n.base64.length(a.Signature)),0):a.Signature.length>=0&&(c.Signature=a.Signature)),a.Options!=null&&(c.Options=a.Options>>>0),a.GuardianAddr!=null&&(typeof a.GuardianAddr=="string"?n.base64.decode(a.GuardianAddr,c.GuardianAddr=n.newBuffer(n.base64.length(a.GuardianAddr)),0):a.GuardianAddr.length>=0&&(c.GuardianAddr=a.GuardianAddr)),a.GuardianSignature!=null&&(typeof a.GuardianSignature=="string"?n.base64.decode(a.GuardianSignature,c.GuardianSignature=n.newBuffer(n.base64.length(a.GuardianSignature)),0):a.GuardianSignature.length>=0&&(c.GuardianSignature=a.GuardianSignature)),c},o.toObject=function(a,c){c||(c={});var f={};if(c.defaults){if(n.Long){var d=new n.Long(0,0,!0);f.Nonce=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.Nonce=c.longs===String?"0":0;if(c.bytes===String?f.Value="":(f.Value=[],c.bytes!==Array&&(f.Value=n.newBuffer(f.Value))),c.bytes===String?f.RcvAddr="":(f.RcvAddr=[],c.bytes!==Array&&(f.RcvAddr=n.newBuffer(f.RcvAddr))),c.bytes===String?f.RcvUserName="":(f.RcvUserName=[],c.bytes!==Array&&(f.RcvUserName=n.newBuffer(f.RcvUserName))),c.bytes===String?f.SndAddr="":(f.SndAddr=[],c.bytes!==Array&&(f.SndAddr=n.newBuffer(f.SndAddr))),c.bytes===String?f.SndUserName="":(f.SndUserName=[],c.bytes!==Array&&(f.SndUserName=n.newBuffer(f.SndUserName))),n.Long){var d=new n.Long(0,0,!0);f.GasPrice=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasPrice=c.longs===String?"0":0;if(n.Long){var d=new n.Long(0,0,!0);f.GasLimit=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasLimit=c.longs===String?"0":0;c.bytes===String?f.Data="":(f.Data=[],c.bytes!==Array&&(f.Data=n.newBuffer(f.Data))),c.bytes===String?f.ChainID="":(f.ChainID=[],c.bytes!==Array&&(f.ChainID=n.newBuffer(f.ChainID))),f.Version=0,c.bytes===String?f.Signature="":(f.Signature=[],c.bytes!==Array&&(f.Signature=n.newBuffer(f.Signature))),f.Options=0,c.bytes===String?f.GuardianAddr="":(f.GuardianAddr=[],c.bytes!==Array&&(f.GuardianAddr=n.newBuffer(f.GuardianAddr))),c.bytes===String?f.GuardianSignature="":(f.GuardianSignature=[],c.bytes!==Array&&(f.GuardianSignature=n.newBuffer(f.GuardianSignature)))}return a.Nonce!=null&&a.hasOwnProperty("Nonce")&&(typeof a.Nonce=="number"?f.Nonce=c.longs===String?String(a.Nonce):a.Nonce:f.Nonce=c.longs===String?n.Long.prototype.toString.call(a.Nonce):c.longs===Number?new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0):a.Nonce),a.Value!=null&&a.hasOwnProperty("Value")&&(f.Value=c.bytes===String?n.base64.encode(a.Value,0,a.Value.length):c.bytes===Array?Array.prototype.slice.call(a.Value):a.Value),a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&(f.RcvAddr=c.bytes===String?n.base64.encode(a.RcvAddr,0,a.RcvAddr.length):c.bytes===Array?Array.prototype.slice.call(a.RcvAddr):a.RcvAddr),a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&(f.RcvUserName=c.bytes===String?n.base64.encode(a.RcvUserName,0,a.RcvUserName.length):c.bytes===Array?Array.prototype.slice.call(a.RcvUserName):a.RcvUserName),a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&(f.SndAddr=c.bytes===String?n.base64.encode(a.SndAddr,0,a.SndAddr.length):c.bytes===Array?Array.prototype.slice.call(a.SndAddr):a.SndAddr),a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&(f.SndUserName=c.bytes===String?n.base64.encode(a.SndUserName,0,a.SndUserName.length):c.bytes===Array?Array.prototype.slice.call(a.SndUserName):a.SndUserName),a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&(typeof a.GasPrice=="number"?f.GasPrice=c.longs===String?String(a.GasPrice):a.GasPrice:f.GasPrice=c.longs===String?n.Long.prototype.toString.call(a.GasPrice):c.longs===Number?new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0):a.GasPrice),a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&(typeof a.GasLimit=="number"?f.GasLimit=c.longs===String?String(a.GasLimit):a.GasLimit:f.GasLimit=c.longs===String?n.Long.prototype.toString.call(a.GasLimit):c.longs===Number?new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0):a.GasLimit),a.Data!=null&&a.hasOwnProperty("Data")&&(f.Data=c.bytes===String?n.base64.encode(a.Data,0,a.Data.length):c.bytes===Array?Array.prototype.slice.call(a.Data):a.Data),a.ChainID!=null&&a.hasOwnProperty("ChainID")&&(f.ChainID=c.bytes===String?n.base64.encode(a.ChainID,0,a.ChainID.length):c.bytes===Array?Array.prototype.slice.call(a.ChainID):a.ChainID),a.Version!=null&&a.hasOwnProperty("Version")&&(f.Version=a.Version),a.Signature!=null&&a.hasOwnProperty("Signature")&&(f.Signature=c.bytes===String?n.base64.encode(a.Signature,0,a.Signature.length):c.bytes===Array?Array.prototype.slice.call(a.Signature):a.Signature),a.Options!=null&&a.hasOwnProperty("Options")&&(f.Options=a.Options),a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&(f.GuardianAddr=c.bytes===String?n.base64.encode(a.GuardianAddr,0,a.GuardianAddr.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianAddr):a.GuardianAddr),a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&(f.GuardianSignature=c.bytes===String?n.base64.encode(a.GuardianSignature,0,a.GuardianSignature.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianSignature):a.GuardianSignature),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,t.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Transaction"},o}(),s}(),i})});var o8=B(jn=>{"use strict";h();var $W=jn&&jn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),YW=jn&&jn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),JW=jn&&jn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$W(e,t,r);return YW(e,t),e},XW=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.ProtoSerializer=void 0;var ZW=XW((rr(),_e(fr))),db=Ve(),e$=hr(),t$=JW(Ie()),r$=Bu(),gb=class{serializeTransaction(e){let r=s8().proto,n=new db.Address(e.getReceiver().bech32()).pubkey(),i=new db.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?p.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?p.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:p.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==e$.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let a=e.getGuardian();s.GuardianAddr=new db.Address(a.bech32()).pubkey(),s.GuardianSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return p.Buffer.from(o)}serializeTransactionValue(e){let r=new ZW.default(e.toString());if(r.isZero())return p.Buffer.from([0,0]);let n=r$.bigIntToBuffer(r);return n=p.Buffer.concat([p.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new t$.ErrUnsupportedOperation("deserializeTransaction")}};jn.ProtoSerializer=gb});var a8=B(ja=>{"use strict";h();var n$=ja&&ja.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),i$=ja&&ja.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&n$(e,t,r)};Object.defineProperty(ja,"__esModule",{value:!0});i$(o8(),ja)});var N0=B(zn=>{"use strict";h();var s$=zn&&zn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),o$=zn&&zn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a$=zn&&zn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&s$(e,t,r);return o$(e,t),e},u$=zn&&zn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zn,"__esModule",{value:!0});zn.TransactionComputer=void 0;var th=a$(Ie()),u8=u$((rr(),_e(fr))),c$=a8(),l$=Xr(),rn=hr(),f$=YA(),h$=sf(),d$=32,pb=class{constructor(){}computeTransactionFee(e,r){let n=BigInt(r.MinGasLimit+e.data.length*r.GasPerDataByte);if(n>e.gasLimit)throw new th.ErrNotEnoughGas(parseInt(e.gasLimit.toString(),10));let i=e.gasPrice,s=n*i;if(n===e.gasLimit)return s;let o=e.gasLimit-n,u=BigInt(new u8.default(i.toString()).multipliedBy(new u8.default(r.GasPriceModifier)).toFixed(0)),a=o*u;return s+a}computeBytesForSigning(e){this.ensureValidTransactionFields(e);let r=this.toPlainObjectForSigning(e),n=JSON.stringify(r);return new Uint8Array(p.Buffer.from(n))}computeBytesForVerifying(e){return this.hasOptionsSetForHashSigning(e)?this.computeHashForSigning(e):this.computeBytesForSigning(e)}computeHashForSigning(e){let r=this.toPlainObjectForSigning(e),n=p.Buffer.from(JSON.stringify(r));return h$("keccak256").update(n).digest()}computeTransactionHash(e){let n=new c$.ProtoSerializer().serializeTransaction(new l$.Transaction(e)),i=f$(d$).update(n).digest("hex");return p.Buffer.from(i,"hex")}hasOptionsSetForGuardedTransaction(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_GUARDED)==rn.TRANSACTION_OPTIONS_TX_GUARDED}hasOptionsSetForHashSigning(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_HASH_SIGN)==rn.TRANSACTION_OPTIONS_TX_HASH_SIGN}applyGuardian(e,r){e.version= ${rn.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`)}};zn.TransactionComputer=pb});var Xr=B(Sc=>{"use strict";h();Object.defineProperty(Sc,"__esModule",{value:!0});Sc.TransactionHash=Sc.Transaction=void 0;var c8=(rr(),_e(fr)),mb=Ve(),yb=hr(),l8=JE(),g$=iD(),f8=$l(),h8=Yf(),p$=Ms(),wb=N0(),vb=class{constructor(e){this.nonce=BigInt(e.nonce?.valueOf()||0n),this.value=e.value?BigInt(new c8.BigNumber(e.value.toString()).toFixed(0)):0n,this.sender=this.addressAsBech32(e.sender),this.receiver=this.addressAsBech32(e.receiver),this.senderUsername=e.senderUsername||"",this.receiverUsername=e.receiverUsername||"",this.gasPrice=BigInt(e.gasPrice?.valueOf()||yb.TRANSACTION_MIN_GAS_PRICE),this.gasLimit=BigInt(e.gasLimit.valueOf()),this.data=e.data?.valueOf()||new Uint8Array,this.chainID=e.chainID.valueOf(),this.version=Number(e.version?.valueOf()||yb.TRANSACTION_VERSION_DEFAULT),this.options=Number(e.options?.valueOf()||yb.TRANSACTION_OPTIONS_DEFAULT),this.guardian=e.guardian?this.addressAsBech32(e.guardian):"",this.signature=e.signature||p.Buffer.from([]),this.guardianSignature=e.guardianSignature||p.Buffer.from([])}addressAsBech32(e){return typeof e=="string"?e:e.bech32()}getNonce(){return Number(this.nonce)}setNonce(e){this.nonce=BigInt(e.valueOf())}getValue(){return this.value}setValue(e){this.value=BigInt(e.toString())}getSender(){return mb.Address.fromBech32(this.sender)}setSender(e){this.sender=typeof e=="string"?e:e.bech32()}getReceiver(){return mb.Address.fromBech32(this.receiver)}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return new mb.Address(this.guardian)}getGasPrice(){return Number(this.gasPrice)}setGasPrice(e){this.gasPrice=BigInt(e.valueOf())}getGasLimit(){return Number(this.gasLimit)}setGasLimit(e){this.gasLimit=BigInt(e.valueOf())}getData(){return new p$.TransactionPayload(p.Buffer.from(this.data))}getChainID(){return this.chainID}setChainID(e){this.chainID=e.valueOf()}getVersion(){return new f8.TransactionVersion(this.version)}setVersion(e){this.version=e.valueOf()}getOptions(){return new f8.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=e.valueOf()}getSignature(){return p.Buffer.from(this.signature)}getGuardianSignature(){return p.Buffer.from(this.guardianSignature)}setGuardian(e){this.guardian=typeof e=="string"?e:e.bech32()}getHash(){return x0.compute(this)}serializeForSigning(){let r=new wb.TransactionComputer().computeBytesForSigning(this);return p.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){return new l8.TransactionsConverter().transactionToPlainObject(this)}static fromPlainObject(e){return new l8.TransactionsConverter().plainObjectToTransaction(e)}applySignature(e){this.signature=h8.interpretSignatureAsBuffer(e)}applyGuardianSignature(e){this.guardianSignature=h8.interpretSignatureAsBuffer(e)}toSendable(){return this.toPlainObject()}computeFee(e){let n=new wb.TransactionComputer().computeTransactionFee(this,e);return new c8.BigNumber(n.toString())}};Sc.Transaction=vb;var x0=class t extends g$.Hash{constructor(e){super(e)}static compute(e){let n=new wb.TransactionComputer().computeTransactionHash(e);return new t(p.Buffer.from(n).toString("hex"))}};Sc.TransactionHash=x0});var g8=B(O0=>{"use strict";h();Object.defineProperty(O0,"__esModule",{value:!0});O0.TokenOperationsFactory=void 0;var Ab=hr(),m$=oo(),d8=$l(),y$=Xr(),w$=Ms(),ae=$d(),Eb=class{constructor(e){this.config=e,this.trueAsHex=ae.utf8ToHex("true"),this.falseAsHex=ae.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.initialSupply),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){m$.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); - } - issueSemiFungible(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "issueSemiFungible", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - issueNonFungible(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "issueNonFungible", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - registerMetaESDT(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "registerMetaESDT", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.bigIntToHex(args.numDecimals), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - registerAndSetAllRoles(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "registerAndSetAllRoles", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.utf8ToHex(args.tokenType), - codec_1.bigIntToHex(args.numDecimals) - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - setBurnRoleGlobally(args) { - const parts = ["setBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, - dataParts: parts - }); - } - unsetBurnRoleGlobally(args) { - const parts = ["unsetBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, - dataParts: parts - }); - } - setSpecialRoleOnFungible(args) { - const parts = [ - "setSpecialRole", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.addressToHex(args.user), - ...args.addRoleLocalMint ? [codec_1.utf8ToHex("ESDTRoleLocalMint")] : [], - ...args.addRoleLocalBurn ? [codec_1.utf8ToHex("ESDTRoleLocalBurn")] : [] - ]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts - }); - } - setSpecialRoleOnSemiFungible(args) { - const parts = [ - "setSpecialRole", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.addressToHex(args.user), - ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], - ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], - ...args.addRoleNFTAddQuantity ? [codec_1.utf8ToHex("ESDTRoleNFTAddQuantity")] : [], - ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] - ]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts - }); - } - setSpecialRoleOnMetaESDT(args) { - return this.setSpecialRoleOnSemiFungible(args); - } - setSpecialRoleOnNonFungible(args) { - const parts = [ - "setSpecialRole", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.addressToHex(args.user), - ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], - ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], - ...args.addRoleNFTUpdateAttributes ? [codec_1.utf8ToHex("ESDTRoleNFTUpdateAttributes")] : [], - ...args.addRoleNFTAddURI ? [codec_1.utf8ToHex("ESDTRoleNFTAddURI")] : [], - ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] - ]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts - }); - } - nftCreate(args) { - const parts = [ - "ESDTNFTCreate", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.initialQuantity), - codec_1.utf8ToHex(args.name), - codec_1.bigIntToHex(args.royalties), - codec_1.utf8ToHex(args.hash), - codec_1.bufferToHex(args.attributes), - ...args.uris.map(codec_1.utf8ToHex) - ]; - const nftData = args.name + args.hash + args.attributes + args.uris.join(""); - const storageGasLimit = nftData.length * this.config.gasLimitStorePerByte.valueOf(); - return this.createTransaction({ - sender: args.creator, - receiver: args.creator, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTCreate.valueOf() + storageGasLimit.valueOf(), - dataParts: parts - }); - } - pause(args) { - const parts = ["pause", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitPausing, - dataParts: parts - }); - } - unpause(args) { - const parts = ["unPause", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitPausing, - dataParts: parts - }); - } - freeze(args) { - const parts = ["freeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitFreezing, - dataParts: parts - }); - } - unfreeze(args) { - const parts = ["unFreeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitFreezing, - dataParts: parts - }); - } - wipe(args) { - const parts = ["wipe", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitWiping, - dataParts: parts - }); - } - localMint(args) { - const parts = ["ESDTLocalMint", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToMint)]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTLocalMint, - dataParts: parts - }); - } - localBurn(args) { - const parts = ["ESDTLocalBurn", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToBurn)]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTLocalBurn, - dataParts: parts - }); - } - updateAttributes(args) { - const parts = [ - "ESDTNFTUpdateAttributes", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.tokenNonce), - codec_1.bufferToHex(args.attributes) - ]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTUpdateAttributes, - dataParts: parts - }); - } - addQuantity(args) { - const parts = [ - "ESDTNFTAddQuantity", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.tokenNonce), - codec_1.bigIntToHex(args.quantityToAdd) - ]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTAddQuantity, - dataParts: parts - }); - } - burnQuantity(args) { - const parts = [ - "ESDTNFTBurn", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.tokenNonce), - codec_1.bigIntToHex(args.quantityToBurn) - ]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTBurn, - dataParts: parts - }); - } - createTransaction({ sender, receiver, nonce, value, gasPrice, gasLimitHint, executionGasLimit, dataParts }) { - const payload = this.buildTransactionPayload(dataParts); - const gasLimit = gasLimitHint || this.computeGasLimit(payload, executionGasLimit); - const version2 = new networkParams_1.TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); - const options = new networkParams_1.TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); - return new transaction_1.Transaction({ - chainID: this.config.chainID, - sender, - receiver, - gasLimit, - gasPrice, - nonce: nonce || 0, - value: value || 0, - data: payload, - version: version2, - options - }); - } - buildTransactionPayload(parts) { - const data = parts.join(constants_1.ARGUMENTS_SEPARATOR); - return new transactionPayload_1.TransactionPayload(data); - } - computeGasLimit(payload, executionGas) { - const dataMovementGas = this.config.minGasLimit.valueOf() + this.config.gasLimitPerByte.valueOf() * payload.length(); - return dataMovementGas + executionGas.valueOf(); - } - }; - exports2.TokenOperationsFactory = TokenOperationsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js -var require_tokenOperationsFactoryConfig = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenOperationsFactoryConfig = void 0; - var address_1 = require_address(); - var TokenOperationsFactoryConfig2 = class { - constructor(chainID) { - this.minGasPrice = 1e9; - this.minGasLimit = 5e4; - this.gasLimitPerByte = 1500; - this.gasLimitIssue = 6e7; - this.gasLimitToggleBurnRoleGlobally = 6e7; - this.gasLimitESDTLocalMint = 3e5; - this.gasLimitESDTLocalBurn = 3e5; - this.gasLimitSetSpecialRole = 6e7; - this.gasLimitPausing = 6e7; - this.gasLimitFreezing = 6e7; - this.gasLimitWiping = 6e7; - this.gasLimitESDTNFTCreate = 3e6; - this.gasLimitESDTNFTUpdateAttributes = 1e6; - this.gasLimitESDTNFTAddQuantity = 1e6; - this.gasLimitESDTNFTBurn = 1e6; - this.gasLimitStorePerByte = 5e4; - this.issueCost = "50000000000000000"; - this.esdtContractAddress = address_1.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); - this.chainID = chainID; - } - }; - exports2.TokenOperationsFactoryConfig = TokenOperationsFactoryConfig2; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js -var require_tokenOperationsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenOperationsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var codec_1 = require_codec(); - var TokenOperationsOutcomeParser2 = class { - parseIssueFungible(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "issue"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseIssueNonFungible(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "issueNonFungible"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseIssueSemiFungible(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "issueSemiFungible"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseRegisterMetaESDT(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "registerMetaESDT"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseRegisterAndSetAllRoles(transaction) { - this.ensureNoError(transaction); - const eventRegister = this.findSingleEventByIdentifier(transaction, "registerAndSetAllRoles"); - const tokenIdentifier = this.extractTokenIdentifier(eventRegister); - const eventSetRole = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); - const roles = eventSetRole.topics.slice(3).map((topic) => topic.valueOf().toString()); - return { tokenIdentifier, roles }; - } - parseSetBurnRoleGlobally(transaction) { - this.ensureNoError(transaction); - return {}; - } - parseUnsetBurnRoleGlobally(transaction) { - this.ensureNoError(transaction); - return {}; - } - parseSetSpecialRole(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const roles = event.topics.slice(3).map((topic) => topic.valueOf().toString()); - return { userAddress, tokenIdentifier, roles }; - } - parseNFTCreate(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTCreate"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const initialQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, initialQuantity }; - } - parseLocalMint(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalMint"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const mintedSupply = this.extractAmount(event); - return { userAddress, tokenIdentifier, nonce, mintedSupply }; - } - parseLocalBurn(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalBurn"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntSupply = this.extractAmount(event); - return { userAddress, tokenIdentifier, nonce, burntSupply }; - } - parsePause(transaction) { - this.ensureNoError(transaction); - const _4 = this.findSingleEventByIdentifier(transaction, "ESDTPause"); - return {}; - } - parseUnpause(transaction) { - this.ensureNoError(transaction); - const _4 = this.findSingleEventByIdentifier(transaction, "ESDTUnPause"); - return {}; - } - parseFreeze(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTFreeze"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - parseUnfreeze(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTUnFreeze"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - parseWipe(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTWipe"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - parseUpdateAttributes(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTUpdateAttributes"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const attributes = event.topics[3]?.valueOf(); - return { tokenIdentifier, nonce, attributes }; - } - parseAddQuantity(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTAddQuantity"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const addedQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, addedQuantity }; - } - parseBurnQuantity(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTBurn"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, burntQuantity }; - } - ensureNoError(transaction) { - for (const event of transaction.logs.events) { - if (event.identifier == "signalError") { - const data = import_buffer.Buffer.from(event.data.substring(1), "hex").toString(); - const message = event.topics[1]?.valueOf().toString(); - throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `encountered signalError: ${message} (${data})`); - } - } - } - findSingleEventByIdentifier(transaction, identifier) { - const events = this.gatherAllEvents(transaction).filter((event) => event.identifier == identifier); - if (events.length == 0) { - throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `cannot find event of type ${identifier}`); - } - if (events.length > 1) { - throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `more than one event of type ${identifier}`); - } - return events[0]; - } - gatherAllEvents(transaction) { - const allEvents = []; - allEvents.push(...transaction.logs.events); - for (const item of transaction.contractResults.items) { - allEvents.push(...item.logs.events); - } - return allEvents; - } - extractTokenIdentifier(event) { - return event.topics[0]?.valueOf().toString(); - } - extractNonce(event) { - return codec_1.bufferToBigInt(event.topics[1]?.valueOf()).toFixed(0); - } - extractAmount(event) { - return codec_1.bufferToBigInt(event.topics[2]?.valueOf()).toFixed(0); - } - extractAddress(event) { - return address_1.Address.fromBuffer(event.topics[3]?.valueOf()).toString(); - } - }; - exports2.TokenOperationsOutcomeParser = TokenOperationsOutcomeParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/index.js -var require_tokenOperations = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_tokenOperationsFactory(), exports2); - __exportStar2(require_tokenOperationsFactoryConfig(), exports2); - __exportStar2(require_tokenOperationsOutcomeParser(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js -var require_delegationTransactionsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DelegationTransactionsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var resources_1 = require_resources(); - var DelegationTransactionsOutcomeParser = class { - constructor() { - } - parseCreateNewDelegationContract(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "SCDeploy"); - return events.map((event) => ({ contractAddress: this.extractContractAddress(event) })); - } - ensureNoError(transactionEvents) { - for (const event of transactionEvents) { - if (event.identifier == "signalError") { - const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; - const message = this.decodeTopicAsString(event.topics[1]); - throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); - } - } - } - extractContractAddress(event) { - if (!event.topics[0]?.length) { - return ""; - } - const address = import_buffer.Buffer.from(event.topics[0]); - return address_1.Address.fromBuffer(address).bech32(); - } - decodeTopicAsString(topic) { - return import_buffer.Buffer.from(topic).toString(); - } - }; - exports2.DelegationTransactionsOutcomeParser = DelegationTransactionsOutcomeParser; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js -var require_smartContractTransactionsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractTransactionsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var resources_1 = require_resources(); - var SmartContractTransactionsOutcomeParser2 = class { - constructor(options) { - this.abi = options?.abi; - this.legacyResultsParser = options?.legacyResultsParser || new smartcontracts_1.ResultsParser(); - } - parseDeploy(options) { - const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; - const events = resources_1.findEventsByIdentifier(options.transactionOutcome, "SCDeploy"); - const contracts = events.map((event) => this.parseScDeployEvent(event)); - return { - returnCode: directCallOutcome.returnCode, - returnMessage: directCallOutcome.returnMessage, - contracts - }; - } - parseScDeployEvent(event) { - const topicForAddress = event.topics[0]; - const topicForOwnerAddress = event.topics[1]; - const topicForCodeHash = event.topics[2]; - const address = topicForAddress?.length ? new address_1.Address(topicForAddress).toBech32() : ""; - const ownerAddress = topicForOwnerAddress?.length ? new address_1.Address(topicForOwnerAddress).toBech32() : ""; - const codeHash = topicForCodeHash; - return { - address, - ownerAddress, - codeHash - }; - } - parseExecute(options) { - const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; - if (!this.abi) { - return { - values: directCallOutcome.returnDataParts, - returnCode: directCallOutcome.returnCode, - returnMessage: directCallOutcome.returnMessage - }; - } - const functionName = options.function || directCallOutcome.function; - if (!functionName) { - throw new errors_1.Err(`Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?`); - } - const endpoint = this.abi.getEndpoint(functionName); - const legacyUntypedBundle = { - returnCode: new smartcontracts_1.ReturnCode(directCallOutcome.returnCode), - returnMessage: directCallOutcome.returnMessage, - values: directCallOutcome.returnDataParts.map((part) => import_buffer.Buffer.from(part)) - }; - const legacyTypedBundle = this.legacyResultsParser.parseOutcomeFromUntypedBundle(legacyUntypedBundle, endpoint); - return { - values: legacyTypedBundle.values.map((value) => value.valueOf()), - returnCode: legacyTypedBundle.returnCode.toString(), - returnMessage: legacyTypedBundle.returnMessage - }; - } - }; - exports2.SmartContractTransactionsOutcomeParser = SmartContractTransactionsOutcomeParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js -var require_tokenManagementTransactionsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenManagementTransactionsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var utils_1 = require_utils(); - var resources_1 = require_resources(); - var TokenManagementTransactionsOutcomeParser2 = class { - constructor() { - } - parseIssueFungible(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "issue"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseIssueNonFungible(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueNonFungible"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseIssueSemiFungible(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueSemiFungible"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseRegisterMetaEsdt(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "registerMetaESDT"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseRegisterAndSetAllRoles(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const registerEvents = resources_1.findEventsByIdentifier(transactionOutcome, "registerAndSetAllRoles"); - const setRoleEvents = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); - if (registerEvents.length !== setRoleEvents.length) { - throw new errors_1.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events."); - } - return registerEvents.map((registerEvent, index) => { - const tokenIdentifier = this.extractTokenIdentifier(registerEvent); - const encodedRoles = setRoleEvents[index].topics.slice(3); - const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); - return { tokenIdentifier, roles }; - }); - } - parseSetBurnRoleGlobally(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - } - parseUnsetBurnRoleGlobally(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - } - parseSetSpecialRole(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); - return events.map((event) => this.getOutputForSetSpecialRoleEvent(event)); - } - getOutputForSetSpecialRoleEvent(event) { - const userAddress = event.address; - const tokenIdentifier = this.extractTokenIdentifier(event); - const encodedRoles = event.topics.slice(3); - const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); - return { userAddress, tokenIdentifier, roles }; - } - parseNftCreate(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTCreate"); - return events.map((event) => this.getOutputForNftCreateEvent(event)); - } - getOutputForNftCreateEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const amount = this.extractAmount(event); - return { tokenIdentifier, nonce, initialQuantity: amount }; - } - parseLocalMint(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalMint"); - return events.map((event) => this.getOutputForLocalMintEvent(event)); - } - getOutputForLocalMintEvent(event) { - const userAddress = event.address; - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const mintedSupply = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - mintedSupply - }; - } - parseLocalBurn(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalBurn"); - return events.map((event) => this.getOutputForLocalBurnEvent(event)); - } - getOutputForLocalBurnEvent(event) { - const userAddress = event.address; - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntSupply = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - burntSupply - }; - } - parsePause(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTPause"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseUnpause(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnPause"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseFreeze(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTFreeze"); - return events.map((event) => this.getOutputForFreezeEvent(event)); - } - getOutputForFreezeEvent(event) { - const userAddress = this.extractAddress(event); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - balance - }; - } - parseUnfreeze(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnFreeze"); - return events.map((event) => this.getOutputForUnfreezeEvent(event)); - } - getOutputForUnfreezeEvent(event) { - const userAddress = this.extractAddress(event); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - balance - }; - } - parseWipe(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTWipe"); - return events.map((event) => this.getOutputForWipeEvent(event)); - } - getOutputForWipeEvent(event) { - const userAddress = this.extractAddress(event); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - balance - }; - } - parseUpdateAttributes(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTUpdateAttributes"); - return events.map((event) => this.getOutputForUpdateAttributesEvent(event)); - } - getOutputForUpdateAttributesEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const attributes = event.topics[3] ? event.topics[3] : new Uint8Array(); - return { - tokenIdentifier, - nonce, - attributes - }; - } - parseAddQuantity(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTAddQuantity"); - return events.map((event) => this.getOutputForAddQuantityEvent(event)); - } - getOutputForAddQuantityEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const addedQuantity = this.extractAmount(event); - return { - tokenIdentifier, - nonce, - addedQuantity - }; - } - parseBurnQuantity(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTBurn"); - return events.map((event) => this.getOutputForBurnQuantityEvent(event)); - } - getOutputForBurnQuantityEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntQuantity = this.extractAmount(event); - return { - tokenIdentifier, - nonce, - burntQuantity - }; - } - ensureNoError(transactionEvents) { - for (const event of transactionEvents) { - if (event.identifier == "signalError") { - const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; - const message = this.decodeTopicAsString(event.topics[1]); - throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); - } - } - } - extractTokenIdentifier(event) { - if (!event.topics[0]?.length) { - return ""; - } - return this.decodeTopicAsString(event.topics[0]); - } - extractNonce(event) { - if (!event.topics[1]?.length) { - return BigInt(0); - } - const nonce = import_buffer.Buffer.from(event.topics[1]); - return BigInt(utils_1.bufferToBigInt(nonce).toFixed(0)); - } - extractAmount(event) { - if (!event.topics[2]?.length) { - return BigInt(0); - } - const amount = import_buffer.Buffer.from(event.topics[2]); - return BigInt(utils_1.bufferToBigInt(amount).toFixed(0)); - } - extractAddress(event) { - if (!event.topics[3]?.length) { - return ""; - } - const address = import_buffer.Buffer.from(event.topics[3]); - return address_1.Address.fromBuffer(address).bech32(); - } - decodeTopicAsString(topic) { - return import_buffer.Buffer.from(topic).toString(); - } - }; - exports2.TokenManagementTransactionsOutcomeParser = TokenManagementTransactionsOutcomeParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js -var require_transactionEventsParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionEventsParser = void 0; - var smartcontracts_1 = require_smartcontracts(); - var TransactionEventsParser2 = class { - constructor(options) { - this.legacyResultsParser = new smartcontracts_1.ResultsParser(); - this.abi = options.abi; - this.firstTopicIsIdentifier = options.firstTopicIsIdentifier ?? true; - } - parseEvents(options) { - const results = []; - for (const event of options.events) { - const parsedEvent = this.parseEvent({ event }); - results.push(parsedEvent); - } - return results; - } - parseEvent(options) { - const topics = options.event.topics.map((topic) => import_buffer.Buffer.from(topic)); - const abiIdentifier = this.firstTopicIsIdentifier ? topics[0]?.toString() : options.event.identifier; - if (this.firstTopicIsIdentifier) { - topics.shift(); - } - const dataItems = options.event.dataItems.map((dataItem) => import_buffer.Buffer.from(dataItem)); - const eventDefinition = this.abi.getEvent(abiIdentifier); - const parsedEvent = this.legacyResultsParser.doParseEvent({ - topics, - dataItems, - eventDefinition - }); - return parsedEvent; - } - }; - exports2.TransactionEventsParser = TransactionEventsParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js -var require_transactionsOutcomeParsers = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_delegationTransactionsOutcomeParser(), exports2); - __exportStar2(require_resources(), exports2); - __exportStar2(require_smartContractTransactionsOutcomeParser(), exports2); - __exportStar2(require_tokenManagementTransactionsOutcomeParser(), exports2); - __exportStar2(require_transactionEventsParser(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/account.js -var require_account = __commonJS({ - "node_modules/@multiversx/sdk-core/out/account.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Account = void 0; - var address_1 = require_address(); - var Account5 = class { - /** - * Creates an account object from an address - */ - constructor(address) { - this.address = address_1.Address.empty(); - this.nonce = 0; - this.balance = "0"; - this.address = address; - } - /** - * Updates account properties (such as nonce, balance). - */ - update(obj) { - this.nonce = obj.nonce; - this.balance = obj.balance; - } - /** - * Increments (locally) the nonce (the account sequence number). - */ - incrementNonce() { - this.nonce = this.nonce.valueOf() + 1; - } - /** - * Gets then increments (locally) the nonce (the account sequence number). - */ - getNonceThenIncrement() { - let nonce = this.nonce; - this.nonce = this.nonce.valueOf() + 1; - return nonce; - } - /** - * Converts the account to a pretty, plain JavaScript object. - */ - toJSON() { - return { - address: this.address.bech32(), - nonce: this.nonce.valueOf(), - balance: this.balance.toString() - }; - } - }; - exports2.Account = Account5; - } -}); - -// node_modules/@multiversx/sdk-core/out/message.js -var require_message = __commonJS({ - "node_modules/@multiversx/sdk-core/out/message.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageComputer = exports2.Message = void 0; - var constants_1 = require_constants(); - var address_1 = require_address(); - var createKeccakHash = require_js(); - var Message2 = class { - constructor(options) { - this.data = options.data; - this.signature = options.signature; - this.address = options.address; - this.version = options.version || constants_1.DEFAULT_MESSAGE_VERSION; - this.signer = options.signer || constants_1.SDK_JS_SIGNER; - } - }; - exports2.Message = Message2; - var MessageComputer2 = class { - constructor() { - } - computeBytesForSigning(message) { - const messageSize = import_buffer.Buffer.from(message.data.length.toString()); - const signableMessage = import_buffer.Buffer.concat([messageSize, message.data]); - let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); - return createKeccakHash("keccak256").update(bytesToHash).digest(); - } - computeBytesForVerifying(message) { - return this.computeBytesForSigning(message); - } - packMessage(message) { - return { - message: import_buffer.Buffer.from(message.data).toString("hex"), - signature: message.signature ? import_buffer.Buffer.from(message.signature).toString("hex") : "", - address: message.address ? message.address.bech32() : "", - version: message.version, - signer: message.signer - }; - } - unpackMessage(packedMessage) { - const dataHex = this.trimHexPrefix(packedMessage.message); - const data = import_buffer.Buffer.from(dataHex, "hex"); - const signatureHex = this.trimHexPrefix(packedMessage.signature || ""); - const signature = import_buffer.Buffer.from(signatureHex, "hex"); - let address = void 0; - if (packedMessage.address) { - address = address_1.Address.fromBech32(packedMessage.address); - } - const version2 = packedMessage.version || constants_1.DEFAULT_MESSAGE_VERSION; - const signer = packedMessage.signer || constants_1.UNKNOWN_SIGNER; - return new Message2({ - data, - signature, - address, - version: version2, - signer - }); - } - trimHexPrefix(data) { - if (data.startsWith("0x") || data.startsWith("0X")) { - return data.slice(2); - } - return data; - } - }; - exports2.MessageComputer = MessageComputer2; - } -}); - -// node_modules/@multiversx/sdk-core/out/asyncTimer.js -var require_asyncTimer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/asyncTimer.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AsyncTimer = void 0; - var errors = __importStar2(require_errors()); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var AsyncTimer = class { - /** - * Creates an AsyncTimer. - */ - constructor(name2) { - this.timeoutHandle = null; - this.rejectionFunc = null; - this.name = name2; - this.correlationTag = 0; - } - /** - * Starts the timer. - * @param timeout The time (in milliseconds) to wait until resolving the promise. - */ - start(timeout) { - if (this.timeoutHandle) { - throw new errors.ErrAsyncTimerAlreadyRunning(); - } - this.correlationTag++; - logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`); - return new Promise((resolve, reject) => { - this.rejectionFunc = reject; - let timeoutCallback = () => { - this.rejectionFunc = null; - this.stop(); - resolve(); - }; - this.timeoutHandle = setTimeout(timeoutCallback, timeout); - }); - } - /** - * Aborts the timer: rejects the promise (if any) and stops the timer. - */ - abort() { - logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`); - if (this.rejectionFunc) { - this.rejectionFunc(new errors_1.ErrAsyncTimerAborted()); - this.rejectionFunc = null; - } - this.stop(); - } - /** - * Stops the timer. - */ - stop() { - if (this.isStopped()) { - return; - } - logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`); - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = null; - } - } - /** - * Returns whether the timer is stopped. - */ - isStopped() { - return this.timeoutHandle ? false : true; - } - }; - exports2.AsyncTimer = AsyncTimer; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionWatcher.js -var require_transactionWatcher = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionWatcher.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionWatcher = void 0; - var asyncTimer_1 = require_asyncTimer(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var TransactionWatcher3 = class _TransactionWatcher { - /** - * A transaction watcher (awaiter). - * - * @param fetcher The transaction fetcher - * @param options The options - * @param options.pollingIntervalMilliseconds The polling interval, in milliseconds - * @param options.timeoutMilliseconds The timeout, in milliseconds - * @param options.patienceMilliseconds The patience: an extra time (in milliseconds) to wait, after the transaction has reached its desired status. Currently there's a delay between the moment a transaction is marked as "completed" and the moment its outcome (contract results, events and logs) is available. - */ - constructor(fetcher, options = {}) { - this.fetcher = new TransactionFetcherWithTracing(fetcher); - this.pollingIntervalMilliseconds = options.pollingIntervalMilliseconds || _TransactionWatcher.DefaultPollingInterval; - this.timeoutMilliseconds = options.timeoutMilliseconds || _TransactionWatcher.DefaultTimeout; - this.patienceMilliseconds = options.patienceMilliseconds || _TransactionWatcher.DefaultPatience; - } - /** - * Waits until the transaction reaches the "pending" status. - * @param txHash The hex-encoded transaction hash - */ - async awaitPending(transactionOrTxHash) { - const isPending = (transaction) => transaction.status.isPending(); - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(isPending, doFetch, errorProvider); - } - /** - * Waits until the transaction is completely processed. - * @param txHash The hex-encoded transaction hash - */ - async awaitCompleted(transactionOrTxHash) { - const isCompleted = (transactionOnNetwork) => { - if (transactionOnNetwork.isCompleted === void 0) { - throw new errors_1.ErrIsCompletedFieldIsMissingOnTransaction(); - } - return transactionOnNetwork.isCompleted; - }; - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(isCompleted, doFetch, errorProvider); - } - async awaitAllEvents(transactionOrTxHash, events) { - const foundAllEvents = (transactionOnNetwork) => { - const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); - const allAreFound = events.every((event) => allEventIdentifiers.includes(event)); - return allAreFound; - }; - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); - return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); - } - async awaitAnyEvent(transactionOrTxHash, events) { - const foundAnyEvent = (transactionOnNetwork) => { - const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); - const anyIsFound = events.find((event) => allEventIdentifiers.includes(event)) != void 0; - return anyIsFound; - }; - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); - return this.awaitConditionally(foundAnyEvent, doFetch, errorProvider); - } - async awaitOnCondition(transactionOrTxHash, condition) { - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(condition, doFetch, errorProvider); - } - transactionOrTxHashToTxHash(transactionOrTxHash) { - const hash = typeof transactionOrTxHash === "string" ? transactionOrTxHash : transactionOrTxHash.getHash().hex(); - if (hash.length !== constants_1.HEX_TRANSACTION_HASH_LENGTH) { - throw new errors_1.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${constants_1.HEX_TRANSACTION_HASH_LENGTH}.`); - } - return hash; - } - async awaitConditionally(isSatisfied, doFetch, createError) { - const periodicTimer = new asyncTimer_1.AsyncTimer("watcher:periodic"); - const patienceTimer = new asyncTimer_1.AsyncTimer("watcher:patience"); - const timeoutTimer = new asyncTimer_1.AsyncTimer("watcher:timeout"); - let stop = false; - let fetchedData = void 0; - let satisfied = false; - timeoutTimer.start(this.timeoutMilliseconds).finally(() => { - timeoutTimer.stop(); - stop = true; - }); - while (!stop) { - await periodicTimer.start(this.pollingIntervalMilliseconds); - try { - fetchedData = await doFetch(); - satisfied = isSatisfied(fetchedData); - if (satisfied || stop) { - break; - } - } catch (error) { - logger_1.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."); - if (error instanceof errors_1.ErrIsCompletedFieldIsMissingOnTransaction) { - throw error; - } - if (!(error instanceof errors_1.Err)) { - throw error; - } - } - } - if (satisfied) { - await patienceTimer.start(this.patienceMilliseconds); - } - if (!timeoutTimer.isStopped()) { - timeoutTimer.stop(); - } - if (!fetchedData || !satisfied) { - throw createError(); - } - return fetchedData; - } - getAllTransactionEvents(transaction) { - const result = [...transaction.logs.events]; - for (const resultItem of transaction.contractResults.items) { - result.push(...resultItem.logs.events); - } - return result; - } - }; - exports2.TransactionWatcher = TransactionWatcher3; - TransactionWatcher3.DefaultPollingInterval = 6e3; - TransactionWatcher3.DefaultTimeout = TransactionWatcher3.DefaultPollingInterval * 15; - TransactionWatcher3.DefaultPatience = 0; - TransactionWatcher3.NoopOnStatusReceived = (_4) => { - }; - var TransactionFetcherWithTracing = class { - constructor(fetcher) { - this.fetcher = fetcher; - } - async getTransaction(txHash) { - logger_1.Logger.debug(`transactionWatcher, getTransaction(${txHash})`); - return await this.fetcher.getTransaction(txHash); - } - }; - } -}); - -// node_modules/@multiversx/sdk-core/out/signableMessage.js -var require_signableMessage = __commonJS({ - "node_modules/@multiversx/sdk-core/out/signableMessage.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SignableMessage = void 0; - var address_1 = require_address(); - var signature_1 = require_signature(); - var constants_1 = require_constants(); - var createKeccakHash = require_js(); - var SignableMessage3 = class { - constructor(init) { - this.message = import_buffer.Buffer.from([]); - this.signature = import_buffer.Buffer.from([]); - this.version = 1; - this.signer = "ErdJS"; - this.address = address_1.Address.empty(); - Object.assign(this, init); - } - serializeForSigning() { - const messageSize = import_buffer.Buffer.from(this.message.length.toString()); - const signableMessage = import_buffer.Buffer.concat([messageSize, this.message]); - let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); - return createKeccakHash("keccak256").update(bytesToHash).digest(); - } - serializeForSigningRaw() { - return import_buffer.Buffer.concat([this.getMessageSize(), this.message]); - } - getSignature() { - return this.signature; - } - applySignature(signature) { - this.signature = signature_1.interpretSignatureAsBuffer(signature); - } - getMessageSize() { - const messageSize = import_buffer.Buffer.alloc(4); - messageSize.writeUInt32BE(this.message.length, 0); - return messageSize; - } - toJSON() { - return { - address: this.address.bech32(), - message: "0x" + this.message.toString("hex"), - signature: "0x" + this.signature.toString("hex"), - version: this.version, - signer: this.signer - }; - } - }; - exports2.SignableMessage = SignableMessage3; - } -}); - -// node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js -var require_bignumber2 = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js"(exports2, module2) { - init_shim(); - (function(globalObject) { - "use strict"; - var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; - function clone2(configObject) { - var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; - function BigNumber3(v2, b4) { - var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; - if (!(x3 instanceof BigNumber3)) - return new BigNumber3(v2, b4); - if (b4 == null) { - if (v2 && v2._isBigNumber === true) { - x3.s = v2.s; - if (!v2.c || v2.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (v2.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = v2.e; - x3.c = v2.c.slice(); - } - return; - } - if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { - x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; - if (v2 === ~~v2) { - for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x3.c = x3.e = null; - } else { - x3.e = e2; - x3.c = [v2]; - } - return; - } - str = String(v2); - } else { - if (!isNumeric2.test(str = String(v2))) - return parseNumeric(x3, str, isNum); - x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i2 = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i2; - e2 += +str.slice(i2 + 1); - str = str.substring(0, i2); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - if (b4 == 10) { - x3 = new BigNumber3(v2); - return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); - } - str = String(v2); - if (isNum = typeof v2 == "number") { - if (v2 * 0 != 0) - return parseNumeric(x3, str, isNum, b4); - x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits2 + v2); - } - } else { - x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b4); - e2 = i2 = 0; - for (len = str.length; i2 < len; i2++) { - if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { - if (c4 == ".") { - if (i2 > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i2 = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x3, String(v2), isNum, b4); - } - } - isNum = false; - str = convertBase(str, b4, 10, x3.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i2 = 0; str.charCodeAt(i2) === 48; i2++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i2, ++len)) { - len -= i2; - if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { - throw Error(tooManyDigits2 + x3.s * v2); - } - if ((e2 = e2 - i2 - 1) > MAX_EXP) { - x3.c = x3.e = null; - } else if (e2 < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = e2; - x3.c = []; - i2 = (e2 + 1) % LOG_BASE2; - if (e2 < 0) - i2 += LOG_BASE2; - if (i2 < len) { - if (i2) - x3.c.push(+str.slice(0, i2)); - for (len -= LOG_BASE2; i2 < len; ) { - x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); - } - i2 = LOG_BASE2 - (str = str.slice(i2)).length; - } else { - i2 -= len; - } - for (; i2--; str += "0") - ; - x3.c.push(+str); - } - } else { - x3.c = [x3.e = 0]; - } - } - BigNumber3.clone = clone2; - BigNumber3.ROUND_UP = 0; - BigNumber3.ROUND_DOWN = 1; - BigNumber3.ROUND_CEIL = 2; - BigNumber3.ROUND_FLOOR = 3; - BigNumber3.ROUND_HALF_UP = 4; - BigNumber3.ROUND_HALF_DOWN = 5; - BigNumber3.ROUND_HALF_EVEN = 6; - BigNumber3.ROUND_HALF_CEIL = 7; - BigNumber3.ROUND_HALF_FLOOR = 8; - BigNumber3.EUCLID = 9; - BigNumber3.config = BigNumber3.set = function(obj) { - var p3, v2; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - DECIMAL_PLACES = v2; - } - if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 8, p3); - ROUNDING_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, 0, p3); - intCheck2(v2[1], 0, MAX2, p3); - TO_EXP_NEG = v2[0]; - TO_EXP_POS = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); - } - } - if (obj.hasOwnProperty(p3 = "RANGE")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, -1, p3); - intCheck2(v2[1], 1, MAX2, p3); - MIN_EXP = v2[0]; - MAX_EXP = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - if (v2) { - MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); - } else { - throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); - } - } - } - if (obj.hasOwnProperty(p3 = "CRYPTO")) { - v2 = obj[p3]; - if (v2 === !!v2) { - if (v2) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v2; - } else { - CRYPTO = !v2; - throw Error(bignumberError2 + "crypto unavailable"); - } - } else { - CRYPTO = v2; - } - } else { - throw Error(bignumberError2 + p3 + " not true or false: " + v2); - } - } - if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 9, p3); - MODULO_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - POW_PRECISION = v2; - } - if (obj.hasOwnProperty(p3 = "FORMAT")) { - v2 = obj[p3]; - if (typeof v2 == "object") - FORMAT = v2; - else - throw Error(bignumberError2 + p3 + " not an object: " + v2); - } - if (obj.hasOwnProperty(p3 = "ALPHABET")) { - v2 = obj[p3]; - if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { - ALPHABET = v2; - } else { - throw Error(bignumberError2 + p3 + " invalid: " + v2); - } - } - } else { - throw Error(bignumberError2 + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber3.isBigNumber = function(v2) { - if (!v2 || v2._isBigNumber !== true) - return false; - if (!BigNumber3.DEBUG) - return true; - var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; - out: - if ({}.toString.call(c4) == "[object Array]") { - if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { - if (c4[0] === 0) { - if (e2 === 0 && c4.length === 1) - return true; - break out; - } - i2 = (e2 + 1) % LOG_BASE2; - if (i2 < 1) - i2 += LOG_BASE2; - if (String(c4[0]).length == i2) { - for (i2 = 0; i2 < c4.length; i2++) { - n3 = c4[i2]; - if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) - break out; - } - if (n3 !== 0) - return true; - } - } - } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { - return true; - } - throw Error(bignumberError2 + "Invalid BigNumber: " + v2); - }; - BigNumber3.maximum = BigNumber3.max = function() { - return maxOrMin(arguments, P2.lt); - }; - BigNumber3.minimum = BigNumber3.min = function() { - return maxOrMin(arguments, P2.gt); - }; - BigNumber3.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor2(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck2(dp, 0, MAX2); - k4 = mathceil2(dp / LOG_BASE2); - if (CRYPTO) { - if (crypto.getRandomValues) { - a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); - for (; i2 < k4; ) { - v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); - if (v2 >= 9e15) { - b4 = crypto.getRandomValues(new Uint32Array(2)); - a3[i2] = b4[0]; - a3[i2 + 1] = b4[1]; - } else { - c4.push(v2 % 1e14); - i2 += 2; - } - } - i2 = k4 / 2; - } else if (crypto.randomBytes) { - a3 = crypto.randomBytes(k4 *= 7); - for (; i2 < k4; ) { - v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; - if (v2 >= 9e15) { - crypto.randomBytes(7).copy(a3, i2); - } else { - c4.push(v2 % 1e14); - i2 += 7; - } - } - i2 = k4 / 7; - } else { - CRYPTO = false; - throw Error(bignumberError2 + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (; i2 < k4; ) { - v2 = random53bitInt(); - if (v2 < 9e15) - c4[i2++] = v2 % 1e14; - } - } - k4 = c4[--i2]; - dp %= LOG_BASE2; - if (k4 && dp) { - v2 = POWS_TEN2[LOG_BASE2 - dp]; - c4[i2] = mathfloor2(k4 / v2) * v2; - } - for (; c4[i2] === 0; c4.pop(), i2--) - ; - if (i2 < 0) { - c4 = [e2 = 0]; - } else { - for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) - ; - for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) - ; - if (i2 < LOG_BASE2) - e2 -= LOG_BASE2 - i2; - } - rand.e = e2; - rand.c = c4; - return rand; - }; - }(); - BigNumber3.sum = function() { - var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); - for (; i2 < args.length; ) - sum = sum.plus(args[i2++]); - return sum; - }; - convertBase = /* @__PURE__ */ function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j2, arr = [0], arrL, i2 = 0, len = str.length; - for (; i2 < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i2++)); - for (j2 = 0; j2 < arr.length; j2++) { - if (arr[j2] > baseOut - 1) { - if (arr[j2 + 1] == null) - arr[j2 + 1] = 0; - arr[j2 + 1] += arr[j2] / baseOut | 0; - arr[j2] %= baseOut; - } - } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign2, callerIsToString) { - var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i2 >= 0) { - k4 = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y4 = new BigNumber3(baseIn); - x3 = y4.pow(str.length - i2); - POW_PRECISION = k4; - y4.c = toBaseOut( - toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), - 10, - baseOut, - decimal - ); - y4.e = y4.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k4 = xc.length; - for (; xc[--k4] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i2 < 0) { - --e2; - } else { - x3.c = xc; - x3.e = e2; - x3.s = sign2; - x3 = div(x3, y4, dp, rm, baseOut); - xc = x3.c; - r = x3.r; - e2 = x3.e; - } - d3 = e2 + dp + 1; - i2 = xc[d3]; - k4 = baseOut / 2; - r = r || d3 < 0 || xc[d3 + 1] != null; - r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (d3 < 1 || !xc[0]) { - str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d3; - if (r) { - for (--baseOut; ++xc[--d3] > baseOut; ) { - xc[d3] = 0; - if (!d3) { - ++e2; - xc = [1].concat(xc); - } - } - } - for (k4 = xc.length; !xc[--k4]; ) - ; - for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) - ; - str = toFixedPoint2(str, e2, alphabet2.charAt(0)); - } - return str; - }; - }(); - div = /* @__PURE__ */ function() { - function multiply(x3, k4, base3) { - var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; - for (x3 = x3.slice(); i2--; ) { - xlo = x3[i2] % SQRT_BASE2; - xhi = x3[i2] / SQRT_BASE2 | 0; - m3 = khi * xlo + xhi * klo; - temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; - carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; - x3[i2] = temp % base3; - } - if (carry) - x3 = [carry].concat(x3); - return x3; - } - function compare4(a3, b4, aL, bL) { - var i2, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i2 = cmp = 0; i2 < aL; i2++) { - if (a3[i2] != b4[i2]) { - cmp = a3[i2] > b4[i2] ? 1 : -1; - break; - } - } - } - return cmp; - } - function subtract(a3, b4, aL, base3) { - var i2 = 0; - for (; aL--; ) { - a3[aL] -= i2; - i2 = a3[aL] < b4[aL] ? 1 : 0; - a3[aL] = i2 * base3 + a3[aL] - b4[aL]; - } - for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) - ; - } - return function(x3, y4, dp, rm, base3) { - var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber3( - // Return NaN if either NaN, or both Infinity or 0. - !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 - ) - ); - } - q2 = new BigNumber3(s2); - qc = q2.c = []; - e2 = x3.e - y4.e; - s2 = dp + e2 + 1; - if (!base3) { - base3 = BASE2; - e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); - s2 = s2 / LOG_BASE2 | 0; - } - for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) - ; - if (yc[i2] > (xc[i2] || 0)) - e2--; - if (s2 < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i2 = 0; - s2 += 2; - n3 = mathfloor2(base3 / (yc[0] + 1)); - if (n3 > 1) { - yc = multiply(yc, n3, base3); - xc = multiply(xc, n3, base3); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base3 / 2) - yc0++; - do { - n3 = 0; - cmp = compare4(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base3 + (rem[1] || 0); - n3 = mathfloor2(rem0 / yc0); - if (n3 > 1) { - if (n3 >= base3) - n3 = base3 - 1; - prod = multiply(yc, n3, base3); - prodL = prod.length; - remL = rem.length; - while (compare4(prod, rem, prodL, remL) == 1) { - n3--; - subtract(prod, yL < prodL ? yz : yc, prodL, base3); - prodL = prod.length; - cmp = 1; - } - } else { - if (n3 == 0) { - cmp = n3 = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base3); - remL = rem.length; - if (cmp == -1) { - while (compare4(yc, rem, yL, remL) < 1) { - n3++; - subtract(rem, yL < remL ? yz : yc, remL, base3); - remL = rem.length; - } - } - } else if (cmp === 0) { - n3++; - rem = [0]; - } - qc[i2++] = n3; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s2--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base3 == BASE2) { - for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) - ; - round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); - } else { - q2.e = e2; - q2.r = +more; - } - return q2; - }; - }(); - function format(n3, i2, rm, id) { - var c0, e2, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - if (!n3.c) - return n3.toString(); - c0 = n3.c[0]; - ne = n3.e; - if (i2 == null) { - str = coeffToString2(n3.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); - } else { - n3 = round(new BigNumber3(n3), i2, rm); - e2 = n3.e; - str = coeffToString2(n3.c); - len = str.length; - if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { - for (; len < i2; str += "0", len++) - ; - str = toExponential2(str, e2); - } else { - i2 -= ne; - str = toFixedPoint2(str, e2, "0"); - if (e2 + 1 > len) { - if (--i2 > 0) - for (str += "."; i2--; str += "0") - ; - } else { - i2 += e2 - len; - if (i2 > 0) { - if (e2 + 1 == len) - str += "."; - for (; i2--; str += "0") - ; - } - } - } - } - return n3.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, method) { - var n3, i2 = 1, m3 = new BigNumber3(args[0]); - for (; i2 < args.length; i2++) { - n3 = new BigNumber3(args[i2]); - if (!n3.s) { - m3 = n3; - break; - } else if (method.call(m3, n3)) { - m3 = n3; - } - } - return m3; - } - function normalise(n3, c4, e2) { - var i2 = 1, j2 = c4.length; - for (; !c4[--j2]; c4.pop()) - ; - for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) - ; - if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { - n3.c = n3.e = null; - } else if (e2 < MIN_EXP) { - n3.c = [n3.e = 0]; - } else { - n3.e = e2; - n3.c = c4; - } - return n3; - } - parseNumeric = /* @__PURE__ */ function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x3, str, isNum, b4) { - var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s2)) { - x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; - } else { - if (!isNum) { - s2 = s2.replace(basePrefix, function(m3, p1, p22) { - base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; - return !b4 || b4 == base3 ? p1 : m3; - }); - if (b4) { - base3 = b4; - s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s2) - return new BigNumber3(s2, base3); - } - if (BigNumber3.DEBUG) { - throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); - } - x3.s = null; - } - x3.c = x3.e = null; - }; - }(); - function round(x3, sd, rm, r) { - var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; - if (xc) { - out: { - for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) - ; - i2 = sd - d3; - if (i2 < 0) { - i2 += LOG_BASE2; - j2 = sd; - n3 = xc[ni = 0]; - rd = n3 / pows10[d3 - j2 - 1] % 10 | 0; - } else { - ni = mathceil2((i2 + 1) / LOG_BASE2); - if (ni >= xc.length) { - if (r) { - for (; xc.length <= ni; xc.push(0)) - ; - n3 = rd = 0; - d3 = 1; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + 1; - } else { - break out; - } - } else { - n3 = k4 = xc[ni]; - for (d3 = 1; k4 >= 10; k4 /= 10, d3++) - ; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + d3; - rd = j2 < 0 ? 0 : n3 / pows10[d3 - j2 - 1] % 10 | 0; - } - } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x3.e + 1; - xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; - x3.e = -sd || 0; - } else { - xc[0] = x3.e = 0; - } - return x3; - } - if (i2 == 0) { - xc.length = ni; - k4 = 1; - ni--; - } else { - xc.length = ni + 1; - k4 = pows10[LOG_BASE2 - i2]; - xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; - } - if (r) { - for (; ; ) { - if (ni == 0) { - for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) - ; - j2 = xc[0] += k4; - for (k4 = 1; j2 >= 10; j2 /= 10, k4++) - ; - if (i2 != k4) { - x3.e++; - if (xc[0] == BASE2) - xc[0] = 1; - } - break; - } else { - xc[ni] += k4; - if (xc[ni] != BASE2) - break; - xc[ni--] = 0; - k4 = 1; - } - } - } - for (i2 = xc.length; xc[--i2] === 0; xc.pop()) - ; - } - if (x3.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (x3.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } - } - return x3; - } - function valueOf(n3) { - var str, e2 = n3.e; - if (e2 === null) - return n3.toString(); - str = coeffToString2(n3.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); - return n3.s < 0 ? "-" + str : str; - } - P2.absoluteValue = P2.abs = function() { - var x3 = new BigNumber3(this); - if (x3.s < 0) - x3.s = 1; - return x3; - }; - P2.comparedTo = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)); - }; - P2.decimalPlaces = P2.dp = function(dp, rm) { - var c4, n3, v2, x3 = this; - if (dp != null) { - intCheck2(dp, 0, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), dp + x3.e + 1, rm); - } - if (!(c4 = x3.c)) - return null; - n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; - if (v2 = c4[v2]) - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - if (n3 < 0) - n3 = 0; - return n3; - }; - P2.dividedBy = P2.div = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); - }; - P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), 0, 1); - }; - P2.exponentiatedBy = P2.pow = function(n3, m3) { - var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; - n3 = new BigNumber3(n3); - if (n3.c && !n3.isInteger()) { - throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); - } - if (m3 != null) - m3 = new BigNumber3(m3); - nIsBig = n3.e > 14; - if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { - y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? 2 - isOdd2(n3) : +valueOf(n3))); - return m3 ? y4.mod(m3) : y4; - } - nIsNeg = n3.s < 0; - if (m3) { - if (m3.c ? !m3.c[0] : !m3.s) - return new BigNumber3(NaN); - isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); - if (isModExp) - x3 = x3.mod(m3); - } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { - k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; - if (x3.e > -1) - k4 = 1 / k4; - return new BigNumber3(nIsNeg ? 1 / k4 : k4); - } else if (POW_PRECISION) { - k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); - } - if (nIsBig) { - half = new BigNumber3(0.5); - if (nIsNeg) - n3.s = 1; - nIsOdd = isOdd2(n3); - } else { - i2 = Math.abs(+valueOf(n3)); - nIsOdd = i2 % 2; - } - y4 = new BigNumber3(ONE); - for (; ; ) { - if (nIsOdd) { - y4 = y4.times(x3); - if (!y4.c) - break; - if (k4) { - if (y4.c.length > k4) - y4.c.length = k4; - } else if (isModExp) { - y4 = y4.mod(m3); - } - } - if (i2) { - i2 = mathfloor2(i2 / 2); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } else { - n3 = n3.times(half); - round(n3, n3.e + 1, 1); - if (n3.e > 14) { - nIsOdd = isOdd2(n3); - } else { - i2 = +valueOf(n3); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } - } - x3 = x3.times(x3); - if (k4) { - if (x3.c && x3.c.length > k4) - x3.c.length = k4; - } else if (isModExp) { - x3 = x3.mod(m3); - } - } - if (isModExp) - return y4; - if (nIsNeg) - y4 = ONE.div(y4); - return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; - }; - P2.integerValue = function(rm) { - var n3 = new BigNumber3(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(n3, n3.e + 1, rm); - }; - P2.isEqualTo = P2.eq = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) === 0; - }; - P2.isFinite = function() { - return !!this.c; - }; - P2.isGreaterThan = P2.gt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) > 0; - }; - P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; - }; - P2.isInteger = function() { - return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; - }; - P2.isLessThan = P2.lt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) < 0; - }; - P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; - }; - P2.isNaN = function() { - return !this.s; - }; - P2.isNegative = function() { - return this.s < 0; - }; - P2.isPositive = function() { - return this.s > 0; - }; - P2.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P2.minus = function(y4, b4) { - var i2, j2, t, xLTy, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.plus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); - } - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (xLTy = a3 < 0) { - a3 = -a3; - t = xc; - } else { - ye = xe; - t = yc; - } - t.reverse(); - for (b4 = a3; b4--; t.push(0)) - ; - t.reverse(); - } else { - j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; - for (a3 = b4 = 0; b4 < j2; b4++) { - if (xc[b4] != yc[b4]) { - xLTy = xc[b4] < yc[b4]; - break; - } - } - } - if (xLTy) - t = xc, xc = yc, yc = t, y4.s = -y4.s; - b4 = (j2 = yc.length) - (i2 = xc.length); - if (b4 > 0) - for (; b4--; xc[i2++] = 0) - ; - b4 = BASE2 - 1; - for (; j2 > a3; ) { - if (xc[--j2] < yc[j2]) { - for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) - ; - --xc[i2]; - xc[j2] += BASE2; - } - xc[j2] -= yc[j2]; - } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y4.s = ROUNDING_MODE == 3 ? -1 : 1; - y4.c = [y4.e = 0]; - return y4; - } - return normalise(y4, xc, ye); - }; - P2.modulo = P2.mod = function(y4, b4) { - var q2, s2, x3 = this; - y4 = new BigNumber3(y4, b4); - if (!x3.c || !y4.s || y4.c && !y4.c[0]) { - return new BigNumber3(NaN); - } else if (!y4.c || x3.c && !x3.c[0]) { - return new BigNumber3(x3); - } - if (MODULO_MODE == 9) { - s2 = y4.s; - y4.s = 1; - q2 = div(x3, y4, 0, 3); - y4.s = s2; - q2.s *= s2; - } else { - q2 = div(x3, y4, 0, MODULO_MODE); - } - y4 = x3.minus(q2.times(y4)); - if (!y4.c[0] && MODULO_MODE == 1) - y4.s = x3.s; - return y4; - }; - P2.multipliedBy = P2.times = function(y4, b4) { - var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y4.c = y4.e = y4.s = null; - } else { - y4.s *= x3.s; - if (!xc || !yc) { - y4.c = y4.e = null; - } else { - y4.c = [0]; - y4.e = 0; - } - } - return y4; - } - e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); - y4.s *= x3.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) - zc = xc, xc = yc, yc = zc, i2 = xcL, xcL = ycL, ycL = i2; - for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) - ; - base3 = BASE2; - sqrtBase = SQRT_BASE2; - for (i2 = ycL; --i2 >= 0; ) { - c4 = 0; - ylo = yc[i2] % sqrtBase; - yhi = yc[i2] / sqrtBase | 0; - for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { - xlo = xc[--k4] % sqrtBase; - xhi = xc[k4] / sqrtBase | 0; - m3 = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; - c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; - zc[j2--] = xlo % base3; - } - zc[j2] = c4; - } - if (c4) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y4, zc, e2); - }; - P2.negated = function() { - var x3 = new BigNumber3(this); - x3.s = -x3.s || null; - return x3; - }; - P2.plus = function(y4, b4) { - var t, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.minus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber3(a3 / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (a3 > 0) { - ye = xe; - t = yc; - } else { - a3 = -a3; - t = xc; - } - t.reverse(); - for (; a3--; t.push(0)) - ; - t.reverse(); - } - a3 = xc.length; - b4 = yc.length; - if (a3 - b4 < 0) - t = yc, yc = xc, xc = t, b4 = a3; - for (a3 = 0; b4; ) { - a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; - xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; - } - if (a3) { - xc = [a3].concat(xc); - ++ye; - } - return normalise(y4, xc, ye); - }; - P2.precision = P2.sd = function(sd, rm) { - var c4, n3, v2, x3 = this; - if (sd != null && sd !== !!sd) { - intCheck2(sd, 1, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), sd, rm); - } - if (!(c4 = x3.c)) - return null; - v2 = c4.length - 1; - n3 = v2 * LOG_BASE2 + 1; - if (v2 = c4[v2]) { - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) - ; - } - if (sd && x3.e + 1 > n3) - n3 = x3.e + 1; - return n3; - }; - P2.shiftedBy = function(k4) { - intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); - return this.times("1e" + k4); - }; - P2.squareRoot = P2.sqrt = function() { - var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); - if (s2 !== 1 || !c4 || !c4[0]) { - return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); - } - s2 = Math.sqrt(+valueOf(x3)); - if (s2 == 0 || s2 == 1 / 0) { - n3 = coeffToString2(c4); - if ((n3.length + e2) % 2 == 0) - n3 += "0"; - s2 = Math.sqrt(+n3); - e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s2 == 1 / 0) { - n3 = "5e" + e2; - } else { - n3 = s2.toExponential(); - n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; - } - r = new BigNumber3(n3); - } else { - r = new BigNumber3(s2 + ""); - } - if (r.c[0]) { - e2 = r.e; - s2 = e2 + dp; - if (s2 < 3) - s2 = 0; - for (; ; ) { - t = r; - r = half.times(t.plus(div(x3, t, dp, 1))); - if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { - if (r.e < e2) - --s2; - n3 = n3.slice(s2 - 3, s2 + 1); - if (n3 == "9999" || !rep && n3 == "4999") { - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - if (t.times(t).eq(x3)) { - r = t; - break; - } - } - dp += 4; - s2 += 4; - rep = 1; - } else { - if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m3 = !r.times(r).eq(x3); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); - }; - P2.toExponential = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp++; - } - return format(this, dp, rm, 1); - }; - P2.toFixed = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P2.toFormat = function(dp, rm, format2) { - var str, x3 = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError2 + "Argument not an object: " + format2); - } - str = x3.toFixed(dp, rm); - if (x3.c) { - var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g22) - i2 = g1, g1 = g22, g22 = i2, len -= i2; - if (g1 > 0 && len > 0) { - i2 = len % g1 || g1; - intPart = intDigits.substr(0, i2); - for (; i2 < len; i2 += g1) - intPart += groupSeparator + intDigits.substr(i2, g1); - if (g22 > 0) - intPart += groupSeparator + intDigits.slice(i2); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g22 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P2.toFraction = function(md) { - var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; - if (md != null) { - n3 = new BigNumber3(md); - if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { - throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); - } - } - if (!xc) - return new BigNumber3(x3); - d3 = new BigNumber3(ONE); - n1 = d0 = new BigNumber3(ONE); - d1 = n0 = new BigNumber3(ONE); - s2 = coeffToString2(xc); - e2 = d3.e = s2.length - x3.e - 1; - d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; - md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n3 = new BigNumber3(s2); - n0.c[0] = 0; - for (; ; ) { - q2 = div(n3, d3, 0, 1); - d22 = d0.plus(q2.times(d1)); - if (d22.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d22; - n1 = n0.plus(q2.times(d22 = n1)); - n0 = d22; - d3 = n3.minus(q2.times(d22 = d3)); - n3 = d22; - } - d22 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d22.times(n1)); - d0 = d0.plus(d22.times(d1)); - n0.s = n1.s = x3.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( - div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() - ) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P2.toNumber = function() { - return +valueOf(this); - }; - P2.toPrecision = function(sd, rm) { - if (sd != null) - intCheck2(sd, 1, MAX2); - return format(this, sd, rm, 2); - }; - P2.toString = function(b4) { - var str, n3 = this, s2 = n3.s, e2 = n3.e; - if (e2 === null) { - if (s2) { - str = "Infinity"; - if (s2 < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b4 == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); - } else if (b4 === 10) { - n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); - } - if (s2 < 0 && n3.c[0]) - str = "-" + str; - } - return str; - }; - P2.valueOf = P2.toJSON = function() { - return valueOf(this); - }; - P2._isBigNumber = true; - if (configObject != null) - BigNumber3.set(configObject); - return BigNumber3; - } - function bitFloor2(n3) { - var i2 = n3 | 0; - return n3 > 0 || n3 === i2 ? i2 : i2 - 1; - } - function coeffToString2(a3) { - var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; - for (; i2 < j2; ) { - s2 = a3[i2++] + ""; - z3 = LOG_BASE2 - s2.length; - for (; z3--; s2 = "0" + s2) - ; - r += s2; - } - for (j2 = r.length; r.charCodeAt(--j2) === 48; ) - ; - return r.slice(0, j2 + 1 || 1); - } - function compare3(x3, y4) { - var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; - if (!i2 || !j2) - return null; - a3 = xc && !xc[0]; - b4 = yc && !yc[0]; - if (a3 || b4) - return a3 ? b4 ? 0 : -j2 : i2; - if (i2 != j2) - return i2; - a3 = i2 < 0; - b4 = k4 == l4; - if (!xc || !yc) - return b4 ? 0 : !xc ^ a3 ? 1 : -1; - if (!b4) - return k4 > l4 ^ a3 ? 1 : -1; - j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; - for (i2 = 0; i2 < j2; i2++) - if (xc[i2] != yc[i2]) - return xc[i2] > yc[i2] ^ a3 ? 1 : -1; - return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; - } - function intCheck2(n3, min, max, name2) { - if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { - throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); - } - } - function isOdd2(n3) { - var k4 = n3.c.length - 1; - return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; - } - function toExponential2(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; - } - function toFixedPoint2(str, e2, z3) { - var len, zs; - if (e2 < 0) { - for (zs = z3 + "."; ++e2; zs += z3) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z3, e2 -= len; --e2; zs += z3) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } - } - return str; - } - BigNumber2 = clone2(); - BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; - if (typeof define == "function" && define.amd) { - define(function() { - return BigNumber2; - }); - } else if (typeof module2 != "undefined" && module2.exports) { - module2.exports = BigNumber2; - } else { - if (!globalObject) { - globalObject = typeof self != "undefined" && self ? self : window; - } - globalObject.BigNumber = BigNumber2; - } - })(exports2); - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/primitives.js -var require_primitives = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/primitives.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = exports2.Nonce = exports2.Address = void 0; - var bech32 = __importStar2(require_bech32()); - var HRP = "erd"; - var Address5 = class _Address { - constructor(value) { - this.value = value; - } - static fromPubkey(pubkey) { - let words = bech32.toWords(pubkey); - let address = bech32.encode(HRP, words); - return new _Address(address); - } - bech32() { - return this.value; - } - toString() { - return this.bech32(); - } - }; - exports2.Address = Address5; - var Nonce = class { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } - hex() { - return numberToPaddedHex(this.value); - } - }; - exports2.Nonce = Nonce; - function numberToPaddedHex(value) { - let hex = value.toString(16); - return zeroPadStringIfOddLength(hex); - } - exports2.numberToPaddedHex = numberToPaddedHex; - function isPaddedHex(input) { - input = input || ""; - let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); - return input.toUpperCase() == decodedThenEncoded.toUpperCase(); - } - exports2.isPaddedHex = isPaddedHex; - function zeroPadStringIfOddLength(input) { - input = input || ""; - if (input.length % 2 == 1) { - return "0" + input; - } - return input; - } - exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/constants.js -var require_constants3 = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/constants.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EsdtContractAddress = exports2.MaxUint64AsBigNumber = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber2()); - var primitives_1 = require_primitives(); - exports2.MaxUint64AsBigNumber = new bignumber_js_1.default("18446744073709551615"); - exports2.EsdtContractAddress = new primitives_1.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js -var require_contractQueryResponse = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractQueryResponse = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber2()); - var constants_1 = require_constants3(); - var ContractQueryResponse3 = class _ContractQueryResponse { - constructor(init) { - this.returnData = (init === null || init === void 0 ? void 0 : init.returnData) || []; - this.returnCode = (init === null || init === void 0 ? void 0 : init.returnCode) || ""; - this.returnMessage = (init === null || init === void 0 ? void 0 : init.returnMessage) || ""; - this.gasUsed = (init === null || init === void 0 ? void 0 : init.gasUsed) || 0; - } - /** - * Constructs a QueryResponse object from a HTTP response (as returned by the provider). - */ - static fromHttpResponse(payload) { - let returnData = payload["returnData"] || payload["ReturnData"]; - let returnCode = payload["returnCode"] || payload["ReturnCode"]; - let returnMessage = payload["returnMessage"] || payload["ReturnMessage"]; - let gasRemaining = new bignumber_js_1.default(payload["gasRemaining"] || payload["GasRemaining"] || 0); - let gasUsed = constants_1.MaxUint64AsBigNumber.minus(gasRemaining).toNumber(); - return new _ContractQueryResponse({ - returnData, - returnCode, - returnMessage, - gasUsed - }); - } - getReturnDataParts() { - return this.returnData.map((item) => import_buffer.Buffer.from(item || "", "base64")); - } - /** - * Converts the object to a pretty, plain JavaScript object. - */ - toJSON() { - return { - returnData: this.returnData, - returnCode: this.returnCode, - returnMessage: this.returnMessage, - gasUsed: this.gasUsed.valueOf() - }; - } - }; - exports2.ContractQueryResponse = ContractQueryResponse3; - } -}); - -// node_modules/@multiversx/sdk-extension-provider/out/errors.js -var require_errors2 = __commonJS({ - "node_modules/@multiversx/sdk-extension-provider/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrAccountNotConnected = exports2.ErrCannotSignSingleTransaction = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - }; - exports2.Err = Err; - var ErrCannotSignSingleTransaction = class extends Err { - constructor() { - super("Cannot sign single transaction."); - } - }; - exports2.ErrCannotSignSingleTransaction = ErrCannotSignSingleTransaction; - var ErrAccountNotConnected = class extends Err { - constructor() { - super("Account is not connected."); - } - }; - exports2.ErrAccountNotConnected = ErrAccountNotConnected; - } -}); - -// node_modules/@multiversx/sdk-extension-provider/out/operation.js -var require_operation = __commonJS({ - "node_modules/@multiversx/sdk-extension-provider/out/operation.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Operation = void 0; - var Operation; - (function(Operation2) { - Operation2["Connect"] = "connect"; - Operation2["Logout"] = "logout"; - Operation2["SignTransactions"] = "signTransactions"; - Operation2["SignMessage"] = "signMessage"; - Operation2["CancelAction"] = "cancelAction"; - })(Operation = exports2.Operation || (exports2.Operation = {})); - } -}); - -// node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js -var require_extensionProvider = __commonJS({ - "node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ExtensionProvider = void 0; - var transaction_1 = require_transaction(); - var errors_1 = require_errors2(); - var operation_1 = require_operation(); - var ExtensionProvider3 = class _ExtensionProvider { - constructor() { - this.account = { address: "" }; - this.initialized = false; - if (_ExtensionProvider._instance) { - throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new."); - } - _ExtensionProvider._instance = this; - } - static getInstance() { - return _ExtensionProvider._instance; - } - setAddress(address) { - this.account.address = address; - return _ExtensionProvider._instance; - } - init() { - return __awaiter2(this, void 0, void 0, function* () { - if (window && window.elrondWallet) { - this.initialized = true; - } - return this.initialized; - }); - } - login(options = {}) { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.initialized) { - throw new Error("Extension provider is not initialised, call init() first"); - } - const { token } = options; - const data = token ? token : ""; - yield this.startBgrMsgChannel(operation_1.Operation.Connect, data); - return this.account.address; - }); - } - logout() { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.initialized) { - throw new Error("Extension provider is not initialised, call init() first"); - } - try { - yield this.startBgrMsgChannel(operation_1.Operation.Logout, this.account.address); - this.disconnect(); - } catch (error) { - console.warn("Extension origin url is already cleared!", error); - } - return true; - }); - } - disconnect() { - this.account = { address: "" }; - } - getAddress() { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.initialized) { - throw new Error("Extension provider is not initialised, call init() first"); - } - return this.account ? this.account.address : ""; - }); - } - isInitialized() { - return this.initialized; - } - // TODO: In V3, this will not be an async function anymore. - isConnected() { - return __awaiter2(this, void 0, void 0, function* () { - return Boolean(this.account.address); - }); - } - signTransaction(transaction) { - return __awaiter2(this, void 0, void 0, function* () { - this.ensureConnected(); - const signedTransactions = yield this.signTransactions([transaction]); - if (signedTransactions.length != 1) { - throw new errors_1.ErrCannotSignSingleTransaction(); - } - return signedTransactions[0]; - }); - } - ensureConnected() { - if (!this.account.address) { - throw new errors_1.ErrAccountNotConnected(); - } - } - signTransactions(transactions) { - return __awaiter2(this, void 0, void 0, function* () { - this.ensureConnected(); - const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignTransactions, { - from: this.account.address, - transactions: transactions.map((transaction) => transaction.toPlainObject()) - }); - try { - const transactionsResponse = extensionResponse.map((transaction) => transaction_1.Transaction.fromPlainObject(transaction)); - return transactionsResponse; - } catch (error) { - throw new Error(`Transaction canceled: ${error.message}.`); - } - }); - } - signMessage(message) { - return __awaiter2(this, void 0, void 0, function* () { - this.ensureConnected(); - const data = { - account: this.account.address, - message: message.message.toString() - }; - const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignMessage, data); - const signatureHex = extensionResponse.signature; - const signature = import_buffer.Buffer.from(signatureHex, "hex"); - message.applySignature(signature); - return message; - }); - } - cancelAction() { - return this.startBgrMsgChannel(operation_1.Operation.CancelAction, {}); - } - startBgrMsgChannel(operation, connectData) { - return new Promise((resolve) => { - window.postMessage({ - target: "erdw-inpage", - type: operation, - data: connectData - }, window.origin); - const eventHandler = (event) => { - if (event.isTrusted && event.data.target === "erdw-contentScript") { - if (event.data.type === "connectResponse") { - if (event.data.data && Boolean(event.data.data.address)) { - this.account = event.data.data; - } - window.removeEventListener("message", eventHandler); - resolve(event.data.data); - } else { - window.removeEventListener("message", eventHandler); - resolve(event.data.data); - } - } - }; - window.addEventListener("message", eventHandler, false); - }); - } - }; - exports2.ExtensionProvider = ExtensionProvider3; - ExtensionProvider3._instance = new ExtensionProvider3(); - } -}); - -// node_modules/destr/dist/index.mjs -function jsonParseTransform(key, value) { - if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) { - warnKeyDropped(key); - return; - } - return value; -} -function warnKeyDropped(key) { - console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`); -} -function destr(value, options = {}) { - if (typeof value !== "string") { - return value; - } - const _value = value.trim(); - if ( - // eslint-disable-next-line unicorn/prefer-at - value[0] === '"' && value.endsWith('"') && !value.includes("\\") - ) { - return _value.slice(1, -1); - } - if (_value.length <= 9) { - const _lval = _value.toLowerCase(); - if (_lval === "true") { - return true; - } - if (_lval === "false") { - return false; - } - if (_lval === "undefined") { - return void 0; - } - if (_lval === "null") { - return null; - } - if (_lval === "nan") { - return Number.NaN; - } - if (_lval === "infinity") { - return Number.POSITIVE_INFINITY; - } - if (_lval === "-infinity") { - return Number.NEGATIVE_INFINITY; - } - } - if (!JsonSigRx.test(value)) { - if (options.strict) { - throw new SyntaxError("[destr] Invalid JSON"); - } - return value; - } - try { - if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) { - if (options.strict) { - throw new Error("[destr] Possible prototype pollution"); - } - return JSON.parse(value, jsonParseTransform); - } - return JSON.parse(value); - } catch (error) { - if (options.strict) { - throw error; - } - return value; - } -} -var suspectProtoRx, suspectConstructorRx, JsonSigRx; -var init_dist = __esm({ - "node_modules/destr/dist/index.mjs"() { - init_shim(); - suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/; - suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; - } -}); - -// node_modules/unstorage/dist/shared/unstorage.8581f561.mjs -function wrapToPromise(value) { - if (!value || typeof value.then !== "function") { - return Promise.resolve(value); - } - return value; -} -function asyncCall(function_, ...arguments_) { - try { - return wrapToPromise(function_(...arguments_)); - } catch (error) { - return Promise.reject(error); - } -} -function isPrimitive(value) { - const type = typeof value; - return value === null || type !== "object" && type !== "function"; -} -function isPureObject(value) { - const proto = Object.getPrototypeOf(value); - return !proto || proto.isPrototypeOf(Object); -} -function stringify(value) { - if (isPrimitive(value)) { - return String(value); - } - if (isPureObject(value) || Array.isArray(value)) { - return JSON.stringify(value); - } - if (typeof value.toJSON === "function") { - return stringify(value.toJSON()); - } - throw new Error("[unstorage] Cannot stringify value!"); -} -function checkBufferSupport() { - if (typeof import_buffer.Buffer === void 0) { - throw new TypeError("[unstorage] Buffer is not supported!"); - } -} -function serializeRaw(value) { - if (typeof value === "string") { - return value; - } - checkBufferSupport(); - const base642 = import_buffer.Buffer.from(value).toString("base64"); - return BASE64_PREFIX + base642; -} -function deserializeRaw(value) { - if (typeof value !== "string") { - return value; - } - if (!value.startsWith(BASE64_PREFIX)) { - return value; - } - checkBufferSupport(); - return import_buffer.Buffer.from(value.slice(BASE64_PREFIX.length), "base64"); -} -function normalizeKey(key) { - if (!key) { - return ""; - } - return key.split("?")[0].replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, ""); -} -function joinKeys(...keys2) { - return normalizeKey(keys2.join(":")); -} -function normalizeBaseKey(base3) { - base3 = normalizeKey(base3); - return base3 ? base3 + ":" : ""; -} -var BASE64_PREFIX; -var init_unstorage_8581f561 = __esm({ - "node_modules/unstorage/dist/shared/unstorage.8581f561.mjs"() { - init_shim(); - BASE64_PREFIX = "base64:"; - } -}); - -// node_modules/unstorage/dist/index.mjs -function defineDriver(factory) { - return factory; -} -function createStorage(options = {}) { - const context = { - mounts: { "": options.driver || memory() }, - mountpoints: [""], - watching: false, - watchListeners: [], - unwatch: {} - }; - const getMount = (key) => { - for (const base3 of context.mountpoints) { - if (key.startsWith(base3)) { - return { - base: base3, - relativeKey: key.slice(base3.length), - driver: context.mounts[base3] - }; - } - } - return { - base: "", - relativeKey: key, - driver: context.mounts[""] - }; - }; - const getMounts = (base3, includeParent) => { - return context.mountpoints.filter( - (mountpoint) => mountpoint.startsWith(base3) || includeParent && base3.startsWith(mountpoint) - ).map((mountpoint) => ({ - relativeBase: base3.length > mountpoint.length ? base3.slice(mountpoint.length) : void 0, - mountpoint, - driver: context.mounts[mountpoint] - })); - }; - const onChange = (event, key) => { - if (!context.watching) { - return; - } - key = normalizeKey(key); - for (const listener of context.watchListeners) { - listener(event, key); - } - }; - const startWatch = async () => { - if (context.watching) { - return; - } - context.watching = true; - for (const mountpoint in context.mounts) { - context.unwatch[mountpoint] = await watch( - context.mounts[mountpoint], - onChange, - mountpoint - ); - } - }; - const stopWatch = async () => { - if (!context.watching) { - return; - } - for (const mountpoint in context.unwatch) { - await context.unwatch[mountpoint](); - } - context.unwatch = {}; - context.watching = false; - }; - const runBatch = (items, commonOptions, cb) => { - const batches = /* @__PURE__ */ new Map(); - const getBatch = (mount) => { - let batch = batches.get(mount.base); - if (!batch) { - batch = { - driver: mount.driver, - base: mount.base, - items: [] - }; - batches.set(mount.base, batch); - } - return batch; - }; - for (const item of items) { - const isStringItem = typeof item === "string"; - const key = normalizeKey(isStringItem ? item : item.key); - const value = isStringItem ? void 0 : item.value; - const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options }; - const mount = getMount(key); - getBatch(mount).items.push({ - key, - value, - relativeKey: mount.relativeKey, - options: options2 - }); - } - return Promise.all([...batches.values()].map((batch) => cb(batch))).then( - (r) => r.flat() - ); - }; - const storage = { - // Item - hasItem(key, opts = {}) { - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - return asyncCall(driver.hasItem, relativeKey, opts); - }, - getItem(key, opts = {}) { - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - return asyncCall(driver.getItem, relativeKey, opts).then( - (value) => destr(value) - ); - }, - getItems(items, commonOptions) { - return runBatch(items, commonOptions, (batch) => { - if (batch.driver.getItems) { - return asyncCall( - batch.driver.getItems, - batch.items.map((item) => ({ - key: item.relativeKey, - options: item.options - })), - commonOptions - ).then( - (r) => r.map((item) => ({ - key: joinKeys(batch.base, item.key), - value: destr(item.value) - })) - ); - } - return Promise.all( - batch.items.map((item) => { - return asyncCall( - batch.driver.getItem, - item.relativeKey, - item.options - ).then((value) => ({ - key: item.key, - value: destr(value) - })); - }) - ); - }); - }, - getItemRaw(key, opts = {}) { - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (driver.getItemRaw) { - return asyncCall(driver.getItemRaw, relativeKey, opts); - } - return asyncCall(driver.getItem, relativeKey, opts).then( - (value) => deserializeRaw(value) - ); - }, - async setItem(key, value, opts = {}) { - if (value === void 0) { - return storage.removeItem(key); - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (!driver.setItem) { - return; - } - await asyncCall(driver.setItem, relativeKey, stringify(value), opts); - if (!driver.watch) { - onChange("update", key); - } - }, - async setItems(items, commonOptions) { - await runBatch(items, commonOptions, async (batch) => { - if (batch.driver.setItems) { - return asyncCall( - batch.driver.setItems, - batch.items.map((item) => ({ - key: item.relativeKey, - value: stringify(item.value), - options: item.options - })), - commonOptions - ); - } - if (!batch.driver.setItem) { - return; - } - await Promise.all( - batch.items.map((item) => { - return asyncCall( - batch.driver.setItem, - item.relativeKey, - stringify(item.value), - item.options - ); - }) - ); - }); - }, - async setItemRaw(key, value, opts = {}) { - if (value === void 0) { - return storage.removeItem(key, opts); - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (driver.setItemRaw) { - await asyncCall(driver.setItemRaw, relativeKey, value, opts); - } else if (driver.setItem) { - await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts); - } else { - return; - } - if (!driver.watch) { - onChange("update", key); - } - }, - async removeItem(key, opts = {}) { - if (typeof opts === "boolean") { - opts = { removeMeta: opts }; - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (!driver.removeItem) { - return; - } - await asyncCall(driver.removeItem, relativeKey, opts); - if (opts.removeMeta || opts.removeMata) { - await asyncCall(driver.removeItem, relativeKey + "$", opts); - } - if (!driver.watch) { - onChange("remove", key); - } - }, - // Meta - async getMeta(key, opts = {}) { - if (typeof opts === "boolean") { - opts = { nativeOnly: opts }; - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - const meta = /* @__PURE__ */ Object.create(null); - if (driver.getMeta) { - Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts)); - } - if (!opts.nativeOnly) { - const value = await asyncCall( - driver.getItem, - relativeKey + "$", - opts - ).then((value_) => destr(value_)); - if (value && typeof value === "object") { - if (typeof value.atime === "string") { - value.atime = new Date(value.atime); - } - if (typeof value.mtime === "string") { - value.mtime = new Date(value.mtime); - } - Object.assign(meta, value); - } - } - return meta; - }, - setMeta(key, value, opts = {}) { - return this.setItem(key + "$", value, opts); - }, - removeMeta(key, opts = {}) { - return this.removeItem(key + "$", opts); - }, - // Keys - async getKeys(base3, opts = {}) { - base3 = normalizeBaseKey(base3); - const mounts = getMounts(base3, true); - let maskedMounts = []; - const allKeys = []; - for (const mount of mounts) { - const rawKeys = await asyncCall( - mount.driver.getKeys, - mount.relativeBase, - opts - ); - const keys2 = rawKeys.map((key) => mount.mountpoint + normalizeKey(key)).filter((key) => !maskedMounts.some((p3) => key.startsWith(p3))); - allKeys.push(...keys2); - maskedMounts = [ - mount.mountpoint, - ...maskedMounts.filter((p3) => !p3.startsWith(mount.mountpoint)) - ]; - } - return base3 ? allKeys.filter((key) => key.startsWith(base3) && !key.endsWith("$")) : allKeys.filter((key) => !key.endsWith("$")); - }, - // Utils - async clear(base3, opts = {}) { - base3 = normalizeBaseKey(base3); - await Promise.all( - getMounts(base3, false).map(async (m3) => { - if (m3.driver.clear) { - return asyncCall(m3.driver.clear, m3.relativeBase, opts); - } - if (m3.driver.removeItem) { - const keys2 = await m3.driver.getKeys(m3.relativeBase || "", opts); - return Promise.all( - keys2.map((key) => m3.driver.removeItem(key, opts)) - ); - } - }) - ); - }, - async dispose() { - await Promise.all( - Object.values(context.mounts).map((driver) => dispose(driver)) - ); - }, - async watch(callback) { - await startWatch(); - context.watchListeners.push(callback); - return async () => { - context.watchListeners = context.watchListeners.filter( - (listener) => listener !== callback - ); - if (context.watchListeners.length === 0) { - await stopWatch(); - } - }; - }, - async unwatch() { - context.watchListeners = []; - await stopWatch(); - }, - // Mount - mount(base3, driver) { - base3 = normalizeBaseKey(base3); - if (base3 && context.mounts[base3]) { - throw new Error(`already mounted at ${base3}`); - } - if (base3) { - context.mountpoints.push(base3); - context.mountpoints.sort((a3, b4) => b4.length - a3.length); - } - context.mounts[base3] = driver; - if (context.watching) { - Promise.resolve(watch(driver, onChange, base3)).then((unwatcher) => { - context.unwatch[base3] = unwatcher; - }).catch(console.error); - } - return storage; - }, - async unmount(base3, _dispose = true) { - base3 = normalizeBaseKey(base3); - if (!base3 || !context.mounts[base3]) { - return; - } - if (context.watching && base3 in context.unwatch) { - context.unwatch[base3](); - delete context.unwatch[base3]; - } - if (_dispose) { - await dispose(context.mounts[base3]); - } - context.mountpoints = context.mountpoints.filter((key) => key !== base3); - delete context.mounts[base3]; - }, - getMount(key = "") { - key = normalizeKey(key) + ":"; - const m3 = getMount(key); - return { - driver: m3.driver, - base: m3.base - }; - }, - getMounts(base3 = "", opts = {}) { - base3 = normalizeKey(base3); - const mounts = getMounts(base3, opts.parents); - return mounts.map((m3) => ({ - driver: m3.driver, - base: m3.mountpoint - })); - } - }; - return storage; -} -function watch(driver, onChange, base3) { - return driver.watch ? driver.watch((event, key) => onChange(event, base3 + key)) : () => { - }; -} -async function dispose(driver) { - if (typeof driver.dispose === "function") { - await asyncCall(driver.dispose); - } -} -var DRIVER_NAME, memory; -var init_dist2 = __esm({ - "node_modules/unstorage/dist/index.mjs"() { - init_shim(); - init_dist(); - init_unstorage_8581f561(); - DRIVER_NAME = "memory"; - memory = defineDriver(() => { - const data = /* @__PURE__ */ new Map(); - return { - name: DRIVER_NAME, - options: {}, - hasItem(key) { - return data.has(key); - }, - getItem(key) { - return data.get(key) ?? null; - }, - getItemRaw(key) { - return data.get(key) ?? null; - }, - setItem(key, value) { - data.set(key, value); - }, - setItemRaw(key, value) { - data.set(key, value); - }, - removeItem(key) { - data.delete(key); - }, - getKeys() { - return Array.from(data.keys()); - }, - clear() { - data.clear(); - }, - dispose() { - data.clear(); - } - }; - }); - } -}); - -// node_modules/idb-keyval/dist/index.js -function promisifyRequest(request) { - return new Promise((resolve, reject) => { - request.oncomplete = request.onsuccess = () => resolve(request.result); - request.onabort = request.onerror = () => reject(request.error); - }); -} -function createStore(dbName, storeName) { - const request = indexedDB.open(dbName); - request.onupgradeneeded = () => request.result.createObjectStore(storeName); - const dbp = promisifyRequest(request); - return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName))); -} -function defaultGetStore() { - if (!defaultGetStoreFunc) { - defaultGetStoreFunc = createStore("keyval-store", "keyval"); - } - return defaultGetStoreFunc; -} -function get(key, customStore = defaultGetStore()) { - return customStore("readonly", (store) => promisifyRequest(store.get(key))); -} -function set(key, value, customStore = defaultGetStore()) { - return customStore("readwrite", (store) => { - store.put(value, key); - return promisifyRequest(store.transaction); - }); -} -function del(key, customStore = defaultGetStore()) { - return customStore("readwrite", (store) => { - store.delete(key); - return promisifyRequest(store.transaction); - }); -} -function clear(customStore = defaultGetStore()) { - return customStore("readwrite", (store) => { - store.clear(); - return promisifyRequest(store.transaction); - }); -} -function eachCursor(store, callback) { - store.openCursor().onsuccess = function() { - if (!this.result) - return; - callback(this.result); - this.result.continue(); - }; - return promisifyRequest(store.transaction); -} -function keys(customStore = defaultGetStore()) { - return customStore("readonly", (store) => { - if (store.getAllKeys) { - return promisifyRequest(store.getAllKeys()); - } - const items = []; - return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items); - }); -} -var defaultGetStoreFunc; -var init_dist3 = __esm({ - "node_modules/idb-keyval/dist/index.js"() { - init_shim(); - } -}); +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex(e.tokenType),ae.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleLocalMint?[ae.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ae.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ae.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ae.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ae.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.initialQuantity),ae.utf8ToHex(e.name),ae.bigIntToHex(e.royalties),ae.utf8ToHex(e.hash),ae.bufferToHex(e.attributes),...e.uris.map(ae.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:u,dataParts:a}){let c=this.buildTransactionPayload(a),f=o||this.computeGasLimit(c,u),d=new d8.TransactionVersion(Ab.TRANSACTION_VERSION_DEFAULT),w=new d8.TransactionOptions(Ab.TRANSACTION_OPTIONS_DEFAULT);return new y$.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:w})}buildTransactionPayload(e){let r=e.join(Ab.ARGUMENTS_SEPARATOR);return new w$.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};O0.TokenOperationsFactory=Eb});var p8=B(D0=>{"use strict";h();Object.defineProperty(D0,"__esModule",{value:!0});D0.TokenOperationsFactoryConfig=void 0;var v$=Ve(),bb=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=v$.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};D0.TokenOperationsFactoryConfig=bb});var y8=B(P0=>{"use strict";h();Object.defineProperty(P0,"__esModule",{value:!0});P0.TokenOperationsOutcomeParser=void 0;var A$=Ve(),Sb=Ie(),m8=$d(),Ib=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=r.topics[3]?.valueOf();return{tokenIdentifier:n,nonce:i,attributes:s}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){for(let r of e.logs.events)if(r.identifier=="signalError"){let n=p.Buffer.from(r.data.substring(1),"hex").toString(),i=r.topics[1]?.valueOf().toString();throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${i} (${n})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){return e.topics[0]?.valueOf().toString()}extractNonce(e){return m8.bufferToBigInt(e.topics[1]?.valueOf()).toFixed(0)}extractAmount(e){return m8.bufferToBigInt(e.topics[2]?.valueOf()).toFixed(0)}extractAddress(e){return A$.Address.fromBuffer(e.topics[3]?.valueOf()).toString()}};P0.TokenOperationsOutcomeParser=Ib});var _b=B(Ls=>{"use strict";h();var E$=Ls&&Ls.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Tb=Ls&&Ls.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&E$(e,t,r)};Object.defineProperty(Ls,"__esModule",{value:!0});Tb(g8(),Ls);Tb(p8(),Ls);Tb(y8(),Ls)});var w8=B(R0=>{"use strict";h();Object.defineProperty(R0,"__esModule",{value:!0});R0.DelegationTransactionsOutcomeParser=void 0;var b$=Ve(),S$=Ie(),I$=Ac(),Cb=class{constructor(){}parseCreateNewDelegationContract(e){return this.ensureNoError(e.logs.events),I$.findEventsByIdentifier(e,"SCDeploy").map(n=>({contractAddress:this.extractContractAddress(n)}))}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new S$.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractContractAddress(e){if(!e.topics[0]?.length)return"";let r=p.Buffer.from(e.topics[0]);return b$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};R0.DelegationTransactionsOutcomeParser=Cb});var E8=B(B0=>{"use strict";h();Object.defineProperty(B0,"__esModule",{value:!0});B0.SmartContractTransactionsOutcomeParser=void 0;var v8=Ve(),T$=Ie(),A8=qn(),_$=Ac(),Nb=class{constructor(e){this.abi=e?.abi,this.legacyResultsParser=e?.legacyResultsParser||new A8.ResultsParser}parseDeploy(e){let r=e.transactionOutcome.directSmartContractCallOutcome,i=_$.findEventsByIdentifier(e.transactionOutcome,"SCDeploy").map(s=>this.parseScDeployEvent(s));return{returnCode:r.returnCode,returnMessage:r.returnMessage,contracts:i}}parseScDeployEvent(e){let r=e.topics[0],n=e.topics[1],i=e.topics[2],s=r?.length?new v8.Address(r).toBech32():"",o=n?.length?new v8.Address(n).toBech32():"";return{address:s,ownerAddress:o,codeHash:i}}parseExecute(e){let r=e.transactionOutcome.directSmartContractCallOutcome;if(!this.abi)return{values:r.returnDataParts,returnCode:r.returnCode,returnMessage:r.returnMessage};let n=e.function||r.function;if(!n)throw new T$.Err('Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?');let i=this.abi.getEndpoint(n),s={returnCode:new A8.ReturnCode(r.returnCode),returnMessage:r.returnMessage,values:r.returnDataParts.map(u=>p.Buffer.from(u))},o=this.legacyResultsParser.parseOutcomeFromUntypedBundle(s,i);return{values:o.values.map(u=>u.valueOf()),returnCode:o.returnCode.toString(),returnMessage:o.returnMessage}}};B0.SmartContractTransactionsOutcomeParser=Nb});var I8=B(M0=>{"use strict";h();Object.defineProperty(M0,"__esModule",{value:!0});M0.TokenManagementTransactionsOutcomeParser=void 0;var C$=Ve(),b8=Ie(),S8=Bu(),wr=Ac(),xb=class{constructor(){}parseIssueFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issue").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueNonFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueNonFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueSemiFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueSemiFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterMetaEsdt(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"registerMetaESDT").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterAndSetAllRoles(e){this.ensureNoError(e.logs.events);let r=wr.findEventsByIdentifier(e,"registerAndSetAllRoles"),n=wr.findEventsByIdentifier(e,"ESDTSetRole");if(r.length!==n.length)throw new b8.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events.");return r.map((i,s)=>{let o=this.extractTokenIdentifier(i),a=n[s].topics.slice(3).map(c=>this.decodeTopicAsString(c));return{tokenIdentifier:o,roles:a}})}parseSetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseUnsetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseSetSpecialRole(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTSetRole").map(n=>this.getOutputForSetSpecialRoleEvent(n))}getOutputForSetSpecialRoleEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),s=e.topics.slice(3).map(o=>this.decodeTopicAsString(o));return{userAddress:r,tokenIdentifier:n,roles:s}}parseNftCreate(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTCreate").map(n=>this.getOutputForNftCreateEvent(n))}getOutputForNftCreateEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,initialQuantity:i}}parseLocalMint(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalMint").map(n=>this.getOutputForLocalMintEvent(n))}getOutputForLocalMintEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,mintedSupply:s}}parseLocalBurn(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalBurn").map(n=>this.getOutputForLocalBurnEvent(n))}getOutputForLocalBurnEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,burntSupply:s}}parsePause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseUnpause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseFreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTFreeze").map(n=>this.getOutputForFreezeEvent(n))}getOutputForFreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnFreeze").map(n=>this.getOutputForUnfreezeEvent(n))}getOutputForUnfreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTWipe").map(n=>this.getOutputForWipeEvent(n))}getOutputForWipeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTUpdateAttributes").map(n=>this.getOutputForUpdateAttributesEvent(n))}getOutputForUpdateAttributesEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=e.topics[3]?e.topics[3]:new Uint8Array;return{tokenIdentifier:r,nonce:n,attributes:i}}parseAddQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTAddQuantity").map(n=>this.getOutputForAddQuantityEvent(n))}getOutputForAddQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,addedQuantity:i}}parseBurnQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTBurn").map(n=>this.getOutputForBurnQuantityEvent(n))}getOutputForBurnQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,burntQuantity:i}}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new b8.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractTokenIdentifier(e){return e.topics[0]?.length?this.decodeTopicAsString(e.topics[0]):""}extractNonce(e){if(!e.topics[1]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[1]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAmount(e){if(!e.topics[2]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[2]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAddress(e){if(!e.topics[3]?.length)return"";let r=p.Buffer.from(e.topics[3]);return C$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};M0.TokenManagementTransactionsOutcomeParser=xb});var T8=B(L0=>{"use strict";h();Object.defineProperty(L0,"__esModule",{value:!0});L0.TransactionEventsParser=void 0;var N$=qn(),Ob=class{constructor(e){this.legacyResultsParser=new N$.ResultsParser,this.abi=e.abi,this.firstTopicIsIdentifier=e.firstTopicIsIdentifier??!0}parseEvents(e){let r=[];for(let n of e.events){let i=this.parseEvent({event:n});r.push(i)}return r}parseEvent(e){let r=e.event.topics.map(u=>p.Buffer.from(u)),n=this.firstTopicIsIdentifier?r[0]?.toString():e.event.identifier;this.firstTopicIsIdentifier&&r.shift();let i=e.event.dataItems.map(u=>p.Buffer.from(u)),s=this.abi.getEvent(n);return this.legacyResultsParser.doParseEvent({topics:r,dataItems:i,eventDefinition:s})}};L0.TransactionEventsParser=Ob});var Db=B(vi=>{"use strict";h();var x$=vi&&vi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=vi&&vi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&x$(e,t,r)};Object.defineProperty(vi,"__esModule",{value:!0});rh(w8(),vi);rh(Ac(),vi);rh(E8(),vi);rh(I8(),vi);rh(T8(),vi)});var Ic=B(F0=>{"use strict";h();Object.defineProperty(F0,"__esModule",{value:!0});F0.Account=void 0;var O$=Ve(),Pb=class{constructor(e){this.address=O$.Address.empty(),this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};F0.Account=Pb});var Bb=B(Tc=>{"use strict";h();Object.defineProperty(Tc,"__esModule",{value:!0});Tc.MessageComputer=Tc.Message=void 0;var nh=hr(),D$=Ve(),P$=sf(),U0=class{constructor(e){this.data=e.data,this.signature=e.signature,this.address=e.address,this.version=e.version||nh.DEFAULT_MESSAGE_VERSION,this.signer=e.signer||nh.SDK_JS_SIGNER}};Tc.Message=U0;var Rb=class{constructor(){}computeBytesForSigning(e){let r=p.Buffer.from(e.data.length.toString()),n=p.Buffer.concat([r,e.data]),i=p.Buffer.concat([p.Buffer.from(nh.MESSAGE_PREFIX),n]);return P$("keccak256").update(i).digest()}computeBytesForVerifying(e){return this.computeBytesForSigning(e)}packMessage(e){return{message:p.Buffer.from(e.data).toString("hex"),signature:e.signature?p.Buffer.from(e.signature).toString("hex"):"",address:e.address?e.address.bech32():"",version:e.version,signer:e.signer}}unpackMessage(e){let r=this.trimHexPrefix(e.message),n=p.Buffer.from(r,"hex"),i=this.trimHexPrefix(e.signature||""),s=p.Buffer.from(i,"hex"),o;e.address&&(o=D$.Address.fromBech32(e.address));let u=e.version||nh.DEFAULT_MESSAGE_VERSION,a=e.signer||nh.UNKNOWN_SIGNER;return new U0({data:n,signature:s,address:o,version:u,signer:a})}trimHexPrefix(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}};Tc.MessageComputer=Rb});var Fb=B(Xi=>{"use strict";h();var R$=Xi&&Xi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),B$=Xi&&Xi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Xi&&Xi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&R$(e,t,r);return B$(e,t),e};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AsyncTimer=void 0;var L$=M$(Ie()),F$=Ie(),Mb=oo(),Lb=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new L$.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new F$.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};Xi.AsyncTimer=Lb});var V0=B(q0=>{"use strict";h();Object.defineProperty(q0,"__esModule",{value:!0});q0.TransactionWatcher=void 0;var Ub=Fb(),_8=hr(),Fs=Ie(),C8=oo(),No=class t{constructor(e,r={}){this.fetcher=new qb(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}async awaitPending(e){let r=s=>s.status.isPending(),n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitCompleted(e){let r=s=>{if(s.isCompleted===void 0)throw new Fs.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitAllEvents(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>u.includes(c))},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitAnyEvent(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>u.includes(c))!=null},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitOnCondition(e,r){let n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}transactionOrTxHashToTxHash(e){let r=typeof e=="string"?e:e.getHash().hex();if(r.length!==_8.HEX_TRANSACTION_HASH_LENGTH)throw new Fs.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${_8.HEX_TRANSACTION_HASH_LENGTH}.`);return r}async awaitConditionally(e,r,n){let i=new Ub.AsyncTimer("watcher:periodic"),s=new Ub.AsyncTimer("watcher:patience"),o=new Ub.AsyncTimer("watcher:timeout"),u=!1,a,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),u=!0});!u;){await i.start(this.pollingIntervalMilliseconds);try{if(a=await r(),c=e(a),c||u)break}catch(f){if(C8.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Fs.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Fs.Err))throw f}}if(c&&await s.start(this.patienceMilliseconds),o.isStopped()||o.stop(),!a||!c)throw n();return a}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};q0.TransactionWatcher=No;No.DefaultPollingInterval=6e3;No.DefaultTimeout=No.DefaultPollingInterval*15;No.DefaultPatience=0;No.NoopOnStatusReceived=t=>{};var qb=class{constructor(e){this.fetcher=e}async getTransaction(e){return C8.Logger.debug(`transactionWatcher, getTransaction(${e})`),await this.fetcher.getTransaction(e)}}});var H0=B(k0=>{"use strict";h();Object.defineProperty(k0,"__esModule",{value:!0});k0.SignableMessage=void 0;var U$=Ve(),q$=Yf(),V$=hr(),k$=sf(),Vb=class{constructor(e){this.message=p.Buffer.from([]),this.signature=p.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=U$.Address.empty(),Object.assign(this,e)}serializeForSigning(){let e=p.Buffer.from(this.message.length.toString()),r=p.Buffer.concat([e,this.message]),n=p.Buffer.concat([p.Buffer.from(V$.MESSAGE_PREFIX),r]);return k$("keccak256").update(n).digest()}serializeForSigningRaw(){return p.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=q$.interpretSignatureAsBuffer(e)}getMessageSize(){let e=p.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};k0.SignableMessage=Vb});var _c=B(vr=>{"use strict";h();var H$=vr&&vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),G$=vr&&vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),j$=vr&&vr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H$(e,t,r);return G$(e,t),e};Object.defineProperty(vr,"__esModule",{value:!0});vr.zeroPadStringIfOddLength=vr.isPaddedHex=vr.numberToPaddedHex=vr.Nonce=vr.Address=void 0;var N8=j$(wv()),z$="erd",kb=class t{constructor(e){this.value=e}static fromPubkey(e){let r=N8.toWords(e),n=N8.encode(z$,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};vr.Address=kb;var Hb=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return x8(this.value)}};vr.Nonce=Hb;function x8(t){let e=t.toString(16);return O8(e)}vr.numberToPaddedHex=x8;function Q$(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}vr.isPaddedHex=Q$;function O8(t){return t=t||"",t.length%2==1?"0"+t:t}vr.zeroPadStringIfOddLength=O8});var D8=B(xo=>{"use strict";h();var K$=xo&&xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xo,"__esModule",{value:!0});xo.EsdtContractAddress=xo.MaxUint64AsBigNumber=void 0;var W$=K$((rr(),_e(fr))),$$=_c();xo.MaxUint64AsBigNumber=new W$.default("18446744073709551615");xo.EsdtContractAddress=new $$.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var jb=B(Cc=>{"use strict";h();var Y$=Cc&&Cc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ContractQueryResponse=void 0;var J$=Y$((rr(),_e(fr))),X$=D8(),Gb=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new J$.default(e.gasRemaining||e.GasRemaining||0),o=X$.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>p.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Cc.ContractQueryResponse=Gb});var P8=B(Oo=>{"use strict";h();Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ErrAccountNotConnected=Oo.ErrCannotSignSingleTransaction=Oo.Err=void 0;var ih=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Oo.Err=ih;var zb=class extends ih{constructor(){super("Cannot sign single transaction.")}};Oo.ErrCannotSignSingleTransaction=zb;var Qb=class extends ih{constructor(){super("Account is not connected.")}};Oo.ErrAccountNotConnected=Qb});var R8=B(sh=>{"use strict";h();Object.defineProperty(sh,"__esModule",{value:!0});sh.Operation=void 0;var Z$;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(Z$=sh.Operation||(sh.Operation={}))});var Kb=B(Nc=>{"use strict";h();var Do=Nc&&Nc.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Nc,"__esModule",{value:!0});Nc.ExtensionProvider=void 0;var eY=Xr(),B8=P8(),oh=R8(),ah=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return Do(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(oh.Operation.Connect,n),this.account.address})}logout(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(oh.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return Do(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new B8.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new B8.ErrAccountNotConnected}signTransactions(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(oh.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>eY.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(oh.Operation.SignMessage,r)).signature,s=p.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(oh.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};Nc.ExtensionProvider=ah;ah._instance=new ah});function iY(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){sY(t);return}return e}function sY(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function uh(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!nY.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(tY.test(t)||rY.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,iY)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var tY,rY,nY,q8=fe(()=>{h();tY=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,rY=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,nY=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function oY(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function gr(t,...e){try{return oY(t(...e))}catch(r){return Promise.reject(r)}}function aY(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function uY(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ch(t){if(aY(t))return String(t);if(uY(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ch(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function V8(){if(typeof p.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function k8(t){if(typeof t=="string")return t;V8();let e=p.Buffer.from(t).toString("base64");return Wb+e}function H8(t){return typeof t!="string"||!t.startsWith(Wb)?t:(V8(),p.Buffer.from(t.slice(Wb.length),"base64"))}function Vr(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function G8(...t){return Vr(t.join(":"))}function lh(t){return t=Vr(t),t?t+":":""}var Wb,j8=fe(()=>{h();Wb="base64:"});function K8(t={}){let e={mounts:{"":t.driver||lY()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=Vr(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await z8(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},u=(c,f,d)=>{let w=new Map,A=T=>{let x=w.get(T.base);return x||(x={driver:T.driver,base:T.base,items:[]},w.set(T.base,x)),x};for(let T of c){let x=typeof T=="string",R=Vr(x?T:T.key),V=x?void 0:T.value,U=x||!T.options?f:{...f,...T.options},Q=r(R);A(Q).items.push({key:R,value:V,relativeKey:Q.relativeKey,options:U})}return Promise.all([...w.values()].map(T=>d(T))).then(T=>T.flat())},a={hasItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.hasItem,d,f)},getItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.getItem,d,f).then(A=>uh(A))},getItems(c,f){return u(c,f,d=>d.driver.getItems?gr(d.driver.getItems,d.items.map(w=>({key:w.relativeKey,options:w.options})),f).then(w=>w.map(A=>({key:G8(d.base,A.key),value:uh(A.value)}))):Promise.all(d.items.map(w=>gr(d.driver.getItem,w.relativeKey,w.options).then(A=>({key:w.key,value:uh(A)})))))},getItemRaw(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return w.getItemRaw?gr(w.getItemRaw,d,f):gr(w.getItem,d,f).then(A=>H8(A))},async setItem(c,f,d={}){if(f===void 0)return a.removeItem(c);c=Vr(c);let{relativeKey:w,driver:A}=r(c);A.setItem&&(await gr(A.setItem,w,ch(f),d),A.watch||i("update",c))},async setItems(c,f){await u(c,f,async d=>{if(d.driver.setItems)return gr(d.driver.setItems,d.items.map(w=>({key:w.relativeKey,value:ch(w.value),options:w.options})),f);d.driver.setItem&&await Promise.all(d.items.map(w=>gr(d.driver.setItem,w.relativeKey,ch(w.value),w.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return a.removeItem(c,d);c=Vr(c);let{relativeKey:w,driver:A}=r(c);if(A.setItemRaw)await gr(A.setItemRaw,w,f,d);else if(A.setItem)await gr(A.setItem,w,k8(f),d);else return;A.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c);w.removeItem&&(await gr(w.removeItem,d,f),(f.removeMeta||f.removeMata)&&await gr(w.removeItem,d+"$",f),w.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c),A=Object.create(null);if(w.getMeta&&Object.assign(A,await gr(w.getMeta,d,f)),!f.nativeOnly){let T=await gr(w.getItem,d+"$",f).then(x=>uh(x));T&&typeof T=="object"&&(typeof T.atime=="string"&&(T.atime=new Date(T.atime)),typeof T.mtime=="string"&&(T.mtime=new Date(T.mtime)),Object.assign(A,T))}return A},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=lh(c);let d=n(c,!0),w=[],A=[];for(let T of d){let R=(await gr(T.driver.getKeys,T.relativeBase,f)).map(V=>T.mountpoint+Vr(V)).filter(V=>!w.some(U=>V.startsWith(U)));A.push(...R),w=[T.mountpoint,...w.filter(V=>!V.startsWith(T.mountpoint))]}return c?A.filter(T=>T.startsWith(c)&&!T.endsWith("$")):A.filter(T=>!T.endsWith("$"))},async clear(c,f={}){c=lh(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return gr(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let w=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(w.map(A=>d.driver.removeItem(A,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>Q8(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=lh(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,w)=>w.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(z8(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),a},async unmount(c,f=!0){c=lh(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await Q8(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=Vr(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=Vr(c),n(c,f.parents).map(w=>({driver:w.driver,base:w.mountpoint}))}};return a}function z8(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function Q8(t){typeof t.dispose=="function"&&await gr(t.dispose)}var cY,lY,W8=fe(()=>{h();q8();j8();cY="memory",lY=()=>{let t=new Map;return{name:cY,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function za(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Yb(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=za(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function fh(){return $b||($b=Yb("keyval-store","keyval")),$b}function Jb(t,e=fh()){return e("readonly",r=>za(r.get(t)))}function $8(t,e,r=fh()){return r("readwrite",n=>(n.put(e,t),za(n.transaction)))}function Y8(t,e=fh()){return e("readwrite",r=>(r.delete(t),za(r.transaction)))}function J8(t=fh()){return t("readwrite",e=>(e.clear(),za(e.transaction)))}function fY(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},za(t.transaction)}function X8(t=fh()){return t("readonly",e=>{if(e.getAllKeys)return za(e.getAllKeys());let r=[];return fY(e,n=>r.push(n.key)).then(()=>r)})}var $b,Z8=fe(()=>{h()});var eP={};Bt(eP,{safeJsonParse:()=>Ro,safeJsonStringify:()=>Ai});function Ro(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return dY(t)}catch{return t}}function Ai(t){return typeof t=="string"?t:hY(t)||""}var hY,dY,xc=fe(()=>{h();hY=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),dY=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var rP={};Bt(rP,{KeyValueStorage:()=>tS,default:()=>tS});function wY(t){var e;return[t[0],Ro((e=t[1])!=null?e:"")]}var gY,pY,mY,yY,Zb,Xb,Q0,eS,vY,tP,AY,EY,tS,nP=fe(()=>{h();W8();Z8();xc();gY="idb-keyval",pY=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Yb(t.dbName,t.storeName)),{name:gY,options:t,async hasItem(i){return!(typeof await Jb(r(i),n)>"u")},async getItem(i){return await Jb(r(i),n)??null},setItem(i,s){return $8(r(i),s,n)},removeItem(i){return Y8(r(i),n)},getKeys(){return X8(n)},clear(){return J8(n)}}},mY="WALLET_CONNECT_V2_INDEXED_DB",yY="keyvaluestorage",Zb=class{constructor(){this.indexedDb=K8({driver:pY({dbName:mY,storeName:yY})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ai(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Xb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Q0={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Xb<"u"&&Xb.localStorage?Q0.exports=Xb.localStorage:typeof window<"u"&&window.localStorage?Q0.exports=window.localStorage:Q0.exports=new e})();eS=class{constructor(){this.localStorage=Q0.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(wY)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return Ro(r)}async setItem(e,r){this.localStorage.setItem(e,Ai(r))}async removeItem(e){this.localStorage.removeItem(e)}},vY="wc_storage_version",tP=1,AY=async(t,e,r)=>{let n=vY,i=await e.getItem(n);if(i&&i>=tP){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let u=s.shift();if(!u)continue;let a=u.toLowerCase();if(a.includes("wc@")||a.includes("walletconnect")||a.includes("wc_")||a.includes("wallet_connect")){let c=await t.getItem(u);await e.setItem(u,c),o.push(u)}}await e.setItem(n,tP),r(e),EY(t,o)},EY=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},tS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new eS;this.storage=e;try{let r=new Zb;AY(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zi={};Bt(Zi,{__assign:()=>nS,__asyncDelegator:()=>BY,__asyncGenerator:()=>RY,__asyncValues:()=>MY,__await:()=>hh,__awaiter:()=>CY,__classPrivateFieldGet:()=>qY,__classPrivateFieldSet:()=>VY,__createBinding:()=>xY,__decorate:()=>IY,__exportStar:()=>OY,__extends:()=>bY,__generator:()=>NY,__importDefault:()=>UY,__importStar:()=>FY,__makeTemplateObject:()=>LY,__metadata:()=>_Y,__param:()=>TY,__read:()=>iP,__rest:()=>SY,__spread:()=>DY,__spreadArrays:()=>PY,__values:()=>iS});function bY(t,e){rS(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function SY(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;u--)(o=t[u])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function TY(t,e){return function(r,n){e(r,n,t)}}function _Y(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function CY(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})}function NY(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(c){return function(f){return a([c,f])}}function a(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function iP(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function DY(){for(var t=[],e=0;e1||u(w,A)})})}function u(w,A){try{a(n[w](A))}catch(T){d(s[0][3],T)}}function a(w){w.value instanceof hh?Promise.resolve(w.value.v).then(c,f):d(s[0][2],w)}function c(w){u("next",w)}function f(w){u("throw",w)}function d(w,A){w(A),s.shift(),s.length&&u(s[0][0],s[0][1])}}function BY(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:hh(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function MY(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof iS=="function"?iS(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(u,a){o=t[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(c){s({value:c,done:u})},o)}}function LY(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function FY(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function UY(t){return t&&t.__esModule?t:{default:t}}function qY(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function VY(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rS,nS,es=fe(()=>{h();rS=function(t,e){return rS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},rS(t,e)};nS=function(){return nS=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";h();Object.defineProperty(K0,"__esModule",{value:!0});K0.delay=void 0;function kY(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}K0.delay=kY});var oP=B(Oc=>{"use strict";h();Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ONE_THOUSAND=Oc.ONE_HUNDRED=void 0;Oc.ONE_HUNDRED=100;Oc.ONE_THOUSAND=1e3});var aP=B(le=>{"use strict";h();Object.defineProperty(le,"__esModule",{value:!0});le.ONE_YEAR=le.FOUR_WEEKS=le.THREE_WEEKS=le.TWO_WEEKS=le.ONE_WEEK=le.THIRTY_DAYS=le.SEVEN_DAYS=le.FIVE_DAYS=le.THREE_DAYS=le.ONE_DAY=le.TWENTY_FOUR_HOURS=le.TWELVE_HOURS=le.SIX_HOURS=le.THREE_HOURS=le.ONE_HOUR=le.SIXTY_MINUTES=le.THIRTY_MINUTES=le.TEN_MINUTES=le.FIVE_MINUTES=le.ONE_MINUTE=le.SIXTY_SECONDS=le.THIRTY_SECONDS=le.TEN_SECONDS=le.FIVE_SECONDS=le.ONE_SECOND=void 0;le.ONE_SECOND=1;le.FIVE_SECONDS=5;le.TEN_SECONDS=10;le.THIRTY_SECONDS=30;le.SIXTY_SECONDS=60;le.ONE_MINUTE=le.SIXTY_SECONDS;le.FIVE_MINUTES=le.ONE_MINUTE*5;le.TEN_MINUTES=le.ONE_MINUTE*10;le.THIRTY_MINUTES=le.ONE_MINUTE*30;le.SIXTY_MINUTES=le.ONE_MINUTE*60;le.ONE_HOUR=le.SIXTY_MINUTES;le.THREE_HOURS=le.ONE_HOUR*3;le.SIX_HOURS=le.ONE_HOUR*6;le.TWELVE_HOURS=le.ONE_HOUR*12;le.TWENTY_FOUR_HOURS=le.ONE_HOUR*24;le.ONE_DAY=le.TWENTY_FOUR_HOURS;le.THREE_DAYS=le.ONE_DAY*3;le.FIVE_DAYS=le.ONE_DAY*5;le.SEVEN_DAYS=le.ONE_DAY*7;le.THIRTY_DAYS=le.ONE_DAY*30;le.ONE_WEEK=le.SEVEN_DAYS;le.TWO_WEEKS=le.ONE_WEEK*2;le.THREE_WEEKS=le.ONE_WEEK*3;le.FOUR_WEEKS=le.ONE_WEEK*4;le.ONE_YEAR=le.ONE_DAY*365});var sS=B(W0=>{"use strict";h();Object.defineProperty(W0,"__esModule",{value:!0});var uP=(es(),_e(Zi));uP.__exportStar(oP(),W0);uP.__exportStar(aP(),W0)});var lP=B(Dc=>{"use strict";h();Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromMiliseconds=Dc.toMiliseconds=void 0;var cP=sS();function HY(t){return t*cP.ONE_THOUSAND}Dc.toMiliseconds=HY;function GY(t){return Math.floor(t/cP.ONE_THOUSAND)}Dc.fromMiliseconds=GY});var hP=B($0=>{"use strict";h();Object.defineProperty($0,"__esModule",{value:!0});var fP=(es(),_e(Zi));fP.__exportStar(sP(),$0);fP.__exportStar(lP(),$0)});var dP=B(dh=>{"use strict";h();Object.defineProperty(dh,"__esModule",{value:!0});dh.Watch=void 0;var Y0=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};dh.Watch=Y0;dh.default=Y0});var gP=B(J0=>{"use strict";h();Object.defineProperty(J0,"__esModule",{value:!0});J0.IWatch=void 0;var oS=class{};J0.IWatch=oS});var pP=B(aS=>{"use strict";h();Object.defineProperty(aS,"__esModule",{value:!0});var jY=(es(),_e(Zi));jY.__exportStar(gP(),aS)});var Qa=B(Pc=>{"use strict";h();Object.defineProperty(Pc,"__esModule",{value:!0});var X0=(es(),_e(Zi));X0.__exportStar(hP(),Pc);X0.__exportStar(dP(),Pc);X0.__exportStar(pP(),Pc);X0.__exportStar(sS(),Pc)});var uS,mP=fe(()=>{h();uS=class{}});var cS={};Bt(cS,{IEvents:()=>uS});var lS=fe(()=>{h();mP()});var yP=B(Z0=>{"use strict";h();Object.defineProperty(Z0,"__esModule",{value:!0});Z0.IHeartBeat=void 0;var zY=(lS(),_e(cS)),fS=class extends zY.IEvents{constructor(e){super()}};Z0.IHeartBeat=fS});var dS=B(hS=>{"use strict";h();Object.defineProperty(hS,"__esModule",{value:!0});var QY=(es(),_e(Zi));QY.__exportStar(yP(),hS)});var wP=B(Rc=>{"use strict";h();Object.defineProperty(Rc,"__esModule",{value:!0});Rc.HEARTBEAT_EVENTS=Rc.HEARTBEAT_INTERVAL=void 0;var KY=Qa();Rc.HEARTBEAT_INTERVAL=KY.FIVE_SECONDS;Rc.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var pS=B(gS=>{"use strict";h();Object.defineProperty(gS,"__esModule",{value:!0});var WY=(es(),_e(Zi));WY.__exportStar(wP(),gS)});var vP=B(em=>{"use strict";h();Object.defineProperty(em,"__esModule",{value:!0});em.HeartBeat=void 0;var mS=(es(),_e(Zi)),$Y=Ds(),YY=Qa(),JY=dS(),yS=pS(),wS=class t extends JY.IHeartBeat{constructor(e){super(e),this.events=new $Y.EventEmitter,this.interval=yS.HEARTBEAT_INTERVAL,this.interval=e?.interval||yS.HEARTBEAT_INTERVAL}static init(e){return mS.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return mS.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return mS.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),YY.toMiliseconds(this.interval))})}pulse(){this.events.emit(yS.HEARTBEAT_EVENTS.pulse)}};em.HeartBeat=wS});var AP=B(gh=>{"use strict";h();Object.defineProperty(gh,"__esModule",{value:!0});var vS=(es(),_e(Zi));vS.__exportStar(vP(),gh);vS.__exportStar(dS(),gh);vS.__exportStar(pS(),gh)});var bP=B((AAe,EP)=>{"use strict";h();function XY(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}EP.exports=ZY;function ZY(t,e,r){var n=r&&r.stringify||XY,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var u=1;u-1?d:0,t.charCodeAt(A+1)){case 100:case 102:if(f>=a||e[f]==null)break;d=a||e[f]==null)break;d=a||e[f]===void 0)break;d",d=A+2,A++;break}c+=n(e[f]),d=A+2,A++;break;case 115:if(f>=a)break;d{"use strict";h();var SP=bP();_P.exports=ts;var ph=cJ().console||{},eJ={mapHttpRequest:tm,mapHttpResponse:tm,wrapRequestSerializer:AS,wrapResponseSerializer:AS,wrapErrorSerializer:AS,req:tm,res:tm,err:sJ};function tJ(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ts(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||ph;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=tJ(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let u=t.level||"info",a=Object.create(r);a.log||(a.log=mh),Object.defineProperty(a,"levelVal",{get:f}),Object.defineProperty(a,"level",{get:d,set:w});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:oJ(t)};a.levels=ts.levels,a.level=u,a.setMaxListeners=a.getMaxListeners=a.emit=a.addListener=a.on=a.prependListener=a.once=a.prependOnceListener=a.removeListener=a.removeAllListeners=a.listeners=a.listenerCount=a.eventNames=a.write=a.flush=mh,a.serializers=n,a._serialize=i,a._stdErrSerialize=s,a.child=A,e&&(a._logEvent=ES());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function w(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,Bc(c,a,"error","log"),Bc(c,a,"fatal","error"),Bc(c,a,"warn","error"),Bc(c,a,"info","log"),Bc(c,a,"debug","log"),Bc(c,a,"trace","log")}function A(T,x){if(!T)throw new Error("missing bindings for child Pino");x=x||{},i&&T.serializers&&(x.serializers=T.serializers);let R=x.serializers;if(i&&R){var V=Object.assign({},n,R),U=t.browser.serialize===!0?Object.keys(V):i;delete T.serializers,rm([T],U,V,this._stdErrSerialize)}function Q(L){this._childLevel=(L._childLevel|0)+1,this.error=Mc(L,T,"error"),this.fatal=Mc(L,T,"fatal"),this.warn=Mc(L,T,"warn"),this.info=Mc(L,T,"info"),this.debug=Mc(L,T,"debug"),this.trace=Mc(L,T,"trace"),V&&(this.serializers=V,this._serialize=U),e&&(this._logEvent=ES([].concat(L._logEvent.bindings,T)))}return Q.prototype=this,new Q(this)}return a}ts.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};ts.stdSerializers=eJ;ts.stdTimeFunctions=Object.assign({},{nullTime:IP,epochTime:TP,unixTime:aJ,isoTime:uJ});function Bc(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mh:i[r]?i[r]:ph[r]||ph[n]||mh,rJ(t,e,r)}function rJ(t,e,r){!t.transmit&&e[r]===mh||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ph?ph:this;for(var a=0;a-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Mc(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;iam,PINO_CUSTOM_CONTEXT_KEY:()=>Lc,PINO_LOGGER_DEFAULTS:()=>OP,formatChildLoggerContext:()=>BP,generateChildLogger:()=>mJ,generateClientLogger:()=>MP,generatePlatformLogger:()=>yJ,generateServerLogger:()=>LP,getBrowserLoggerContext:()=>DP,getDefaultLoggerOptions:()=>pJ,getLoggerContext:()=>RP,pino:()=>xP.default,setBrowserLoggerContext:()=>PP});function pJ(t){return om(sm({},t),{level:t?.level||OP.level})}function DP(t,e=Lc){return t[e]||""}function PP(t,e,r=Lc){return t[r]=e,t}function RP(t,e=Lc){let r="";return typeof t.bindings>"u"?r=DP(t,e):r=t.bindings().context||"",r}function BP(t,e,r=Lc){let n=RP(t,r);return n.trim()?`${n}/${e}`:e}function mJ(t,e,r=Lc){let n=BP(t,e,r),i=t.child({context:n});return PP(i,n,r)}function MP(t){var e,r;let n=new IS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace",browser:om(sm({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function LP(t){var e;let r=new TS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function yJ(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?MP(t):LP(t)}var Us,xP,OP,Lc,am,SS,nm,im,IS,TS,lJ,fJ,hJ,CP,dJ,gJ,NP,sm,om,CS=fe(()=>{h();Us=pe(bS()),xP=pe(bS());xc();OP={level:"info"},Lc="custom_context",am=1e3*1024,SS=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},nm=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let r=new SS(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let r=e.value;return e=e.next,{done:!1,value:r}}}}},im=class{constructor(e,r=am){this.level=e??"error",this.levelValue=Us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Us.levels.values.error?console.error(e):r===Us.levels.values.warn?console.warn(e):r===Us.levels.values.debug?console.debug(e):r===Us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ai({timestamp:new Date().toISOString(),log:e}));let r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let r=this.getLogArray();return r.push(Ai({extraMetadata:e})),new Blob(r,{type:"application/json"})}},IS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},TS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}},lJ=Object.defineProperty,fJ=Object.defineProperties,hJ=Object.getOwnPropertyDescriptors,CP=Object.getOwnPropertySymbols,dJ=Object.prototype.hasOwnProperty,gJ=Object.prototype.propertyIsEnumerable,NP=(t,e,r)=>e in t?lJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sm=(t,e)=>{for(var r in e||(e={}))dJ.call(e,r)&&NP(t,r,e[r]);if(CP)for(var r of CP(e))gJ.call(e,r)&&NP(t,r,e[r]);return t},om=(t,e)=>fJ(t,hJ(e))});var QS=B(ar=>{"use strict";h();Object.defineProperty(ar,"__esModule",{value:!0});var Fc=(lS(),_e(cS)),FP=Ds();function wJ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var vJ=wJ(FP),NS=class extends Fc.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},xS=class{constructor(e,r,n){this.core=e,this.logger=r}},OS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},DS=class{constructor(e,r){this.logger=e,this.core=r}},PS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},RS=class extends Fc.IEvents{constructor(e){super()}},BS=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},MS=class{constructor(){this.map=new Map}},LS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},FS=class{constructor(e,r){this.core=e,this.logger=r}},US=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},qS=class{constructor(e,r){this.logger=e,this.core=r}},VS=class{constructor(e,r){this.projectId=e,this.logger=r}},kS=class{constructor(e,r){this.projectId=e,this.logger=r}},HS=class extends vJ.default{constructor(){super()}},GS=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},jS=class extends FP.EventEmitter{constructor(){super()}},zS=class{constructor(e){this.client=e}};ar.ICore=NS,ar.ICrypto=xS,ar.IEchoClient=kS,ar.IEngine=zS,ar.IEngineEvents=jS,ar.IExpirer=US,ar.IJsonRpcHistory=OS,ar.IKeyChain=FS,ar.IMessageTracker=DS,ar.IPairing=qS,ar.IPublisher=PS,ar.IRelayer=RS,ar.ISignClient=GS,ar.ISignClientEvents=HS,ar.IStore=BS,ar.ISubscriber=LS,ar.ISubscriberTopicMap=MS,ar.IVerify=VS});var qP=B(um=>{"use strict";h();Object.defineProperty(um,"__esModule",{value:!0});um.BrowserRandomSource=void 0;var UP=65536,KS=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";h();Object.defineProperty(WS,"__esModule",{value:!0});function AJ(t){for(var e=0;e{h()});var kP=B(cm=>{"use strict";h();Object.defineProperty(cm,"__esModule",{value:!0});cm.NodeRandomSource=void 0;var EJ=Qn(),$S=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof Bd<"u"){let e=VP();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";h();Object.defineProperty(lm,"__esModule",{value:!0});lm.SystemRandomSource=void 0;var bJ=qP(),SJ=kP(),YS=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new bJ.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new SJ.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};lm.SystemRandomSource=YS});var GP=B(dn=>{"use strict";h();Object.defineProperty(dn,"__esModule",{value:!0});function IJ(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}dn.mul=Math.imul||IJ;function TJ(t,e){return t+e|0}dn.add=TJ;function _J(t,e){return t-e|0}dn.sub=_J;function CJ(t,e){return t<>>32-e}dn.rotl=CJ;function NJ(t,e){return t<<32-e|t>>>e}dn.rotr=NJ;function xJ(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}dn.isInteger=Number.isInteger||xJ;dn.MAX_SAFE_INTEGER=9007199254740991;dn.isSafeInteger=function(t){return dn.isInteger(t)&&t>=-dn.MAX_SAFE_INTEGER&&t<=dn.MAX_SAFE_INTEGER}});var Uc=B(xe=>{"use strict";h();Object.defineProperty(xe,"__esModule",{value:!0});var jP=GP();function OJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}xe.readInt16BE=OJ;function DJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}xe.readUint16BE=DJ;function PJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}xe.readInt16LE=PJ;function RJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}xe.readUint16LE=RJ;function zP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}xe.writeUint16BE=zP;xe.writeInt16BE=zP;function QP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}xe.writeUint16LE=QP;xe.writeInt16LE=QP;function JS(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}xe.readInt32BE=JS;function XS(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}xe.readUint32BE=XS;function ZS(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}xe.readInt32LE=ZS;function eI(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}xe.readUint32LE=eI;function fm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}xe.writeUint32BE=fm;xe.writeInt32BE=fm;function hm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}xe.writeUint32LE=hm;xe.writeInt32LE=hm;function BJ(t,e){e===void 0&&(e=0);var r=JS(t,e),n=JS(t,e+4);return r*4294967296+n-(n>>31)*4294967296}xe.readInt64BE=BJ;function MJ(t,e){e===void 0&&(e=0);var r=XS(t,e),n=XS(t,e+4);return r*4294967296+n}xe.readUint64BE=MJ;function LJ(t,e){e===void 0&&(e=0);var r=ZS(t,e),n=ZS(t,e+4);return n*4294967296+r-(r>>31)*4294967296}xe.readInt64LE=LJ;function FJ(t,e){e===void 0&&(e=0);var r=eI(t,e),n=eI(t,e+4);return n*4294967296+r}xe.readUint64LE=FJ;function KP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),fm(t/4294967296>>>0,e,r),fm(t>>>0,e,r+4),e}xe.writeUint64BE=KP;xe.writeInt64BE=KP;function WP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),hm(t>>>0,e,r),hm(t/4294967296>>>0,e,r+4),e}xe.writeUint64LE=WP;xe.writeInt64LE=WP;function UJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}xe.readUintBE=UJ;function qJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}xe.writeUintBE=VJ;function kJ(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!jP.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";h();Object.defineProperty(Br,"__esModule",{value:!0});Br.randomStringForEntropy=Br.randomString=Br.randomUint32=Br.randomBytes=Br.defaultRandomSource=void 0;var YJ=HP(),JJ=Uc(),$P=Qn();Br.defaultRandomSource=new YJ.SystemRandomSource;function tI(t,e=Br.defaultRandomSource){return e.randomBytes(t)}Br.randomBytes=tI;function XJ(t=Br.defaultRandomSource){let e=tI(4,t),r=(0,JJ.readUint32LE)(e);return(0,$P.wipe)(e),r}Br.randomUint32=XJ;var YP="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function JP(t,e=YP,r=Br.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=tI(Math.ceil(t*256/s),r);for(let u=0;u0;u++){let a=o[u];a{"use strict";h();Object.defineProperty(qs,"__esModule",{value:!0});var Vc=Uc(),qc=Qn();qs.DIGEST_LENGTH=64;qs.BLOCK_SIZE=128;var ZP=function(){function t(){this.digestLength=qs.DIGEST_LENGTH,this.blockSize=qs.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){qc.wipe(this._buffer),qc.wipe(this._tempHi),qc.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){qc.wipe(e.stateHi),qc.wipe(e.stateLo),e.buffer&&qc.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();qs.SHA512=ZP;var XP=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function rI(t,e,r,n,i,s,o){for(var u=r[0],a=r[1],c=r[2],f=r[3],d=r[4],w=r[5],A=r[6],T=r[7],x=n[0],R=n[1],V=n[2],U=n[3],Q=n[4],L=n[5],k=n[6],H=n[7],q,v,C,D,F,P,l,g;o>=128;){for(var y=0;y<16;y++){var E=8*y+s;t[y]=Vc.readUint32BE(i,E),e[y]=Vc.readUint32BE(i,E+4)}for(var y=0;y<80;y++){var S=u,_=a,M=c,N=f,m=d,O=w,Y=A,$=T,b=x,j=R,z=V,W=U,ie=Q,te=L,ee=k,se=H;if(q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(d>>>14|Q<<18)^(d>>>18|Q<<14)^(Q>>>9|d<<23),v=(Q>>>14|d<<18)^(Q>>>18|d<<14)^(d>>>9|Q<<23),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=d&w^~d&A,v=Q&L^~Q&k,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=XP[y*2],v=XP[y*2+1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=t[y%16],v=e[y%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,C=l&65535|g<<16,D=F&65535|P<<16,q=C,v=D,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(u>>>28|x<<4)^(x>>>2|u<<30)^(x>>>7|u<<25),v=(x>>>28|u<<4)^(u>>>2|x<<30)^(u>>>7|x<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=u&a^u&c^a&c,v=x&R^x&V^R&V,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,$=l&65535|g<<16,se=F&65535|P<<16,q=N,v=W,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=C,v=D,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,N=l&65535|g<<16,W=F&65535|P<<16,a=S,c=_,f=M,d=N,w=m,A=O,T=Y,u=$,R=b,V=j,U=z,Q=W,L=ie,k=te,H=ee,x=se,y%16===15)for(var E=0;E<16;E++)q=t[E],v=e[E],F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=t[(E+9)%16],v=e[(E+9)%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+1)%16],D=e[(E+1)%16],q=(C>>>1|D<<31)^(C>>>8|D<<24)^C>>>7,v=(D>>>1|C<<31)^(D>>>8|C<<24)^(D>>>7|C<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+14)%16],D=e[(E+14)%16],q=(C>>>19|D<<13)^(D>>>29|C<<3)^C>>>6,v=(D>>>19|C<<13)^(C>>>29|D<<3)^(D>>>6|C<<26),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,t[E]=l&65535|g<<16,e[E]=F&65535|P<<16}q=u,v=x,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[0],v=n[0],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[0]=u=l&65535|g<<16,n[0]=x=F&65535|P<<16,q=a,v=R,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[1],v=n[1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[1]=a=l&65535|g<<16,n[1]=R=F&65535|P<<16,q=c,v=V,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[2],v=n[2],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[2]=c=l&65535|g<<16,n[2]=V=F&65535|P<<16,q=f,v=U,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[3],v=n[3],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[3]=f=l&65535|g<<16,n[3]=U=F&65535|P<<16,q=d,v=Q,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[4],v=n[4],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[4]=d=l&65535|g<<16,n[4]=Q=F&65535|P<<16,q=w,v=L,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[5],v=n[5],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[5]=w=l&65535|g<<16,n[5]=L=F&65535|P<<16,q=A,v=k,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[6],v=n[6],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[6]=A=l&65535|g<<16,n[6]=k=F&65535|P<<16,q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[7],v=n[7],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[7]=T=l&65535|g<<16,n[7]=H=F&65535|P<<16,s+=128,o-=128}return s}function eX(t){var e=new ZP;e.update(t);var r=e.digest();return e.clean(),r}qs.hash=eX});var gR=B(Ge=>{"use strict";h();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.convertSecretKeyToX25519=Ge.convertPublicKeyToX25519=Ge.verify=Ge.sign=Ge.extractPublicKeyFromSecretKey=Ge.generateKeyPair=Ge.generateKeyPairFromSeed=Ge.SEED_LENGTH=Ge.SECRET_KEY_LENGTH=Ge.PUBLIC_KEY_LENGTH=Ge.SIGNATURE_LENGTH=void 0;var tX=yh(),wh=eR(),sR=Qn();Ge.SIGNATURE_LENGTH=64;Ge.PUBLIC_KEY_LENGTH=32;Ge.SECRET_KEY_LENGTH=64;Ge.SEED_LENGTH=32;function ve(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,oR(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function aR(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function nR(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return vh(r,t),vh(n,e),aR(r,n)}function uR(t){let e=new Uint8Array(32);return vh(e,t),e[0]&1}function oX(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Ka(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function $a(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function Ct(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Wa(t,e){Ct(t,e,e)}function cR(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)Wa(r,r),n!==2&&n!==4&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function aX(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)Wa(r,r),n!==1&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function oI(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve(),c=ve(),f=ve();$a(r,t[1],t[0]),$a(f,e[1],e[0]),Ct(r,r,f),Ka(n,t[0],t[1]),Ka(f,e[0],e[1]),Ct(n,n,f),Ct(i,t[3],e[3]),Ct(i,i,iX),Ct(s,t[2],e[2]),Ka(s,s,s),$a(o,n,r),$a(u,s,i),Ka(a,s,i),Ka(c,n,r),Ct(t[0],o,u),Ct(t[1],c,a),Ct(t[2],a,u),Ct(t[3],o,c)}function iR(t,e,r){for(let n=0;n<4;n++)oR(t[n],e[n],r)}function uI(t,e){let r=ve(),n=ve(),i=ve();cR(i,e[2]),Ct(r,e[0],i),Ct(n,e[1],i),vh(t,n),t[31]^=uR(r)<<7}function lR(t,e,r){Bo(t[0],sI),Bo(t[1],kc),Bo(t[2],kc),Bo(t[3],sI);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;iR(t,e,i),oI(e,t),oI(t,t),iR(t,e,i)}}function cI(t,e){let r=[ve(),ve(),ve(),ve()];Bo(r[0],tR),Bo(r[1],rR),Bo(r[2],kc),Ct(r[3],tR,rR),lR(t,r,e)}function fR(t){if(t.length!==Ge.SEED_LENGTH)throw new Error(`ed25519: seed must be ${Ge.SEED_LENGTH} bytes`);let e=(0,wh.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[ve(),ve(),ve(),ve()];cI(n,e),uI(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}Ge.generateKeyPairFromSeed=fR;function uX(t){let e=(0,tX.randomBytes)(32,t),r=fR(e);return(0,sR.wipe)(e),r}Ge.generateKeyPair=uX;function cX(t){if(t.length!==Ge.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${Ge.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}Ge.extractPublicKeyFromSecretKey=cX;var iI=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function hR(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*iI[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*iI[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function aI(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;hR(t,e)}function lX(t,e){let r=new Float64Array(64),n=[ve(),ve(),ve(),ve()],i=(0,wh.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new wh.SHA512;o.update(s.subarray(32)),o.update(e);let u=o.digest();o.clean(),aI(u),cI(n,u),uI(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let a=o.digest();aI(a);for(let c=0;c<32;c++)r[c]=u[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=a[c]*i[f];return hR(s.subarray(32),r),s}Ge.sign=lX;function dR(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve();return Bo(t[2],kc),oX(t[1],e),Wa(i,t[1]),Ct(s,i,nX),$a(i,i,t[2]),Ka(s,t[2],s),Wa(o,s),Wa(u,o),Ct(a,u,o),Ct(r,a,i),Ct(r,r,s),aX(r,r),Ct(r,r,i),Ct(r,r,s),Ct(r,r,s),Ct(t[0],r,s),Wa(n,t[0]),Ct(n,n,s),nR(n,i)&&Ct(t[0],t[0],sX),Wa(n,t[0]),Ct(n,n,s),nR(n,i)?-1:(uR(t[0])===e[31]>>7&&$a(t[0],sI,t[0]),Ct(t[3],t[0],t[1]),0)}function fX(t,e,r){let n=new Uint8Array(32),i=[ve(),ve(),ve(),ve()],s=[ve(),ve(),ve(),ve()];if(r.length!==Ge.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${Ge.SIGNATURE_LENGTH} bytes`);if(dR(s,t))return!1;let o=new wh.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let u=o.digest();return aI(u),lR(i,s,u),cI(s,r.subarray(32)),oI(i,s),uI(n,i),!aR(r,n)}Ge.verify=fX;function hX(t){let e=[ve(),ve(),ve(),ve()];if(dR(e,t))throw new Error("Ed25519: invalid public key");let r=ve(),n=ve(),i=e[1];Ka(r,kc,i),$a(n,kc,i),cR(n,n),Ct(r,r,n);let s=new Uint8Array(32);return vh(s,r),s}Ge.convertPublicKeyToX25519=hX;function dX(t){let e=(0,wh.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,sR.wipe)(e),r}Ge.convertSecretKeyToX25519=dX});var dm,gm,Ya,Hc,pm,Ah,mm,ym,wm,Gc,vm,Am,pR,mR,Em=fe(()=>{h();dm="EdDSA",gm="JWT",Ya=".",Hc="base64url",pm="utf8",Ah="utf8",mm=":",ym="did",wm="key",Gc="base58btc",vm="z",Am="K36",pR=32,mR=32});function Mo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var Eh=fe(()=>{h()});function jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var bm=fe(()=>{h();Eh()});function Sm(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=jc(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Mo(r)}var lI=fe(()=>{h();bm();Eh()});function gX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var pX,mX,yR,wR=fe(()=>{h();pX=gX,mX=pX,yR=mX});var cEe,vR,Vs,AR,ER,Lo=fe(()=>{h();cEe=new Uint8Array(0),vR=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},AR=t=>new TextEncoder().encode(t),ER=t=>new TextDecoder().decode(t)});var fI,hI,dI,SR,gI,zc,Fo,yX,wX,jt,Ei=fe(()=>{h();wR();Lo();fI=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},hI=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SR(this,e)}},dI=class{constructor(e){this.decoders=e}or(e){return SR(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SR=(t,e)=>new dI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),gI=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new fI(e,r,n),this.decoder=new hI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zc=({name:t,prefix:e,encode:r,decode:n})=>new gI(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=yR(r,e);return zc({prefix:t,name:e,encode:n,decode:s=>Vs(i(s))})},yX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},wX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<zc({prefix:e,name:t,encode(i){return wX(i,n,r)},decode(i){return yX(i,n,r,t)}})});var pI={};Bt(pI,{identity:()=>vX});var vX,IR=fe(()=>{h();Ei();Lo();vX=zc({prefix:"\0",name:"identity",encode:t=>ER(t),decode:t=>AR(t)})});var mI={};Bt(mI,{base2:()=>AX});var AX,TR=fe(()=>{h();Ei();AX=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var yI={};Bt(yI,{base8:()=>EX});var EX,_R=fe(()=>{h();Ei();EX=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var wI={};Bt(wI,{base10:()=>bX});var bX,CR=fe(()=>{h();Ei();bX=Fo({prefix:"9",name:"base10",alphabet:"0123456789"})});var vI={};Bt(vI,{base16:()=>SX,base16upper:()=>IX});var SX,IX,NR=fe(()=>{h();Ei();SX=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),IX=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var AI={};Bt(AI,{base32:()=>Qc,base32hex:()=>NX,base32hexpad:()=>OX,base32hexpadupper:()=>DX,base32hexupper:()=>xX,base32pad:()=>_X,base32padupper:()=>CX,base32upper:()=>TX,base32z:()=>PX});var Qc,TX,_X,CX,NX,xX,OX,DX,PX,EI=fe(()=>{h();Ei();Qc=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),TX=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_X=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),CX=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),NX=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xX=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),OX=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DX=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PX=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bI={};Bt(bI,{base36:()=>RX,base36upper:()=>BX});var RX,BX,xR=fe(()=>{h();Ei();RX=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BX=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var SI={};Bt(SI,{base58btc:()=>rs,base58flickr:()=>MX});var rs,MX,II=fe(()=>{h();Ei();rs=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),MX=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var TI={};Bt(TI,{base64:()=>LX,base64pad:()=>FX,base64url:()=>UX,base64urlpad:()=>qX});var LX,FX,UX,qX,OR=fe(()=>{h();Ei();LX=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FX=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),UX=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qX=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var _I={};Bt(_I,{base256emoji:()=>jX});function HX(t){return t.reduce((e,r)=>(e+=VX[r],e),"")}function GX(t){let e=[];for(let r of t){let n=kX[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var DR,VX,kX,jX,PR=fe(()=>{h();Ei();DR=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VX=DR.reduce((t,e,r)=>(t[r]=e,t),[]),kX=DR.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);jX=zc({prefix:"\u{1F680}",name:"base256emoji",encode:HX,decode:GX})});function MR(t,e,r){e=e||[],r=r||0;for(var n=r;t>=WX;)e[r++]=t&255|RR,t/=128;for(;t&KX;)e[r++]=t&255|RR,t>>>=7;return e[r]=t|0,MR.bytes=r-n+1,e}function CI(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw CI.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&BR)<=YX);return CI.bytes=s-n,r}var zX,RR,QX,KX,WX,$X,YX,BR,JX,XX,ZX,eZ,tZ,rZ,nZ,iZ,sZ,oZ,aZ,uZ,bh,LR=fe(()=>{h();zX=MR,RR=128,QX=127,KX=~QX,WX=Math.pow(2,31);$X=CI,YX=128,BR=127;JX=Math.pow(2,7),XX=Math.pow(2,14),ZX=Math.pow(2,21),eZ=Math.pow(2,28),tZ=Math.pow(2,35),rZ=Math.pow(2,42),nZ=Math.pow(2,49),iZ=Math.pow(2,56),sZ=Math.pow(2,63),oZ=function(t){return t{h();LR();Sh=(t,e=0)=>[bh.decode(t,e),bh.decode.bytes],Kc=(t,e,r=0)=>(bh.encode(t,e,r),e),Wc=t=>bh.encodingLength(t)});var Ja,FR,UR,$c,Th=fe(()=>{h();Lo();Tm();Ja=(t,e)=>{let r=e.byteLength,n=Wc(t),i=n+Wc(r),s=new Uint8Array(i+r);return Kc(t,s,0),Kc(r,s,n),s.set(e,i),new $c(t,r,e,s)},FR=t=>{let e=Vs(t),[r,n]=Sh(e),[i,s]=Sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $c(r,i,o,e)},UR=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&vR(t.bytes,e.bytes),$c=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var xI,NI,OI=fe(()=>{h();Th();xI=({name:t,code:e,encode:r})=>new NI(t,e,r),NI=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ja(this.code,r):r.then(n=>Ja(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var DI={};Bt(DI,{sha256:()=>cZ,sha512:()=>lZ});var VR,cZ,lZ,kR=fe(()=>{h();OI();VR=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),cZ=xI({name:"sha2-256",code:18,encode:VR("SHA-256")}),lZ=xI({name:"sha2-512",code:19,encode:VR("SHA-512")})});var PI={};Bt(PI,{identity:()=>dZ});var HR,fZ,GR,hZ,dZ,jR=fe(()=>{h();Lo();Th();HR=0,fZ="identity",GR=Vs,hZ=t=>Ja(HR,GR(t)),dZ={code:HR,name:fZ,encode:GR,digest:hZ}});var zR=fe(()=>{h();Lo()});var $Ee,YEe,QR=fe(()=>{h();$Ee=new TextEncoder,YEe=new TextDecoder});var Nm,mZ,yZ,wZ,_h,vZ,KR,WR,_m,Cm,AZ,EZ,bZ,$R=fe(()=>{h();Tm();Th();II();EI();Lo();Nm=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Cm,byteLength:Cm,code:_m,version:_m,multihash:_m,bytes:_m,_baseCache:Cm,asCID:Cm})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==_h)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==vZ)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ja(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&UR(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return yZ(r,i,e||rs.encoder);default:return wZ(r,i,e||Qc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return EZ(/^0\.0/,bZ),!!(e&&(e[WR]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||KR(r,n,i.bytes))}else if(e!=null&&e[WR]===!0){let{version:r,multihash:n,code:i}=e,s=FR(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==_h)throw new Error(`Version 0 CID must use dag-pb (code: ${_h}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=KR(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_h,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Vs(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $c(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,w]=Sh(e.subarray(r));return r+=w,d},i=n(),s=_h;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,u=n(),a=n(),c=r+a,f=c-o;return{version:i,codec:s,multihashCode:u,digestSize:a,multihashSize:f,size:c}}static parse(e,r){let[n,i]=mZ(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},mZ=(t,e)=>{switch(t[0]){case"Q":{let r=e||rs;return[rs.prefix,r.decode(`${rs.prefix}${t}`)]}case rs.prefix:{let r=e||rs;return[rs.prefix,r.decode(t)]}case Qc.prefix:{let r=e||Qc;return[Qc.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},yZ=(t,e,r)=>{let{prefix:n}=r;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},wZ=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},_h=112,vZ=18,KR=(t,e,r)=>{let n=Wc(t),i=n+Wc(e),s=new Uint8Array(i+r.byteLength);return Kc(t,s,0),Kc(e,s,n),s.set(r,i),s},WR=Symbol.for("@ipld/js-cid/CID"),_m={writable:!1,configurable:!1,enumerable:!0},Cm={writable:!1,enumerable:!1,configurable:!1},AZ="0.0.0-dev",EZ=(t,e)=>{if(t.test(AZ))console.warn(e);else throw new Error(e)},bZ=`CID.isCID(v) is deprecated and will be removed in the next major release. +Following code pattern: -// node_modules/@walletconnect/safe-json/dist/esm/index.js -var esm_exports = {}; -__export(esm_exports, { - safeJsonParse: () => safeJsonParse, - safeJsonStringify: () => safeJsonStringify -}); -function safeJsonParse(value) { - if (typeof value !== "string") { - throw new Error(`Cannot safe json parse value of type ${typeof value}`); - } - try { - return JSONParse(value); - } catch (_a) { - return value; - } -} -function safeJsonStringify(value) { - return typeof value === "string" ? value : JSONStringify(value) || ""; +if (CID.isCID(value)) { + doSomethingWithCID(value) } -var JSONStringify, JSONParse; -var init_esm = __esm({ - "node_modules/@walletconnect/safe-json/dist/esm/index.js"() { - init_shim(); - JSONStringify = (data) => JSON.stringify(data, (_4, value) => typeof value === "bigint" ? value.toString() + "n" : value); - JSONParse = (json) => { - const numbersBiggerThanMaxInt = /([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g; - const serializedData = json.replace(numbersBiggerThanMaxInt, '$1"$2n"$3'); - return JSON.parse(serializedData, (_4, value) => { - const isCustomFormatBigInt = typeof value === "string" && value.match(/^\d+n$/); - if (isCustomFormatBigInt) - return BigInt(value.substring(0, value.length - 1)); - return value; - }); - }; - } -}); -// node_modules/@walletconnect/keyvaluestorage/dist/index.es.js -var index_es_exports = {}; -__export(index_es_exports, { - KeyValueStorage: () => h, - default: () => h -}); -function k(i2) { - var t; - return [i2[0], safeJsonParse((t = i2[1]) != null ? t : "")]; -} -var x, z, D, E, _, l, c, K, N, y, O, j, h; -var init_index_es = __esm({ - "node_modules/@walletconnect/keyvaluestorage/dist/index.es.js"() { - init_shim(); - init_dist2(); - init_dist3(); - init_esm(); - x = "idb-keyval"; - z = (i2 = {}) => { - const t = i2.base && i2.base.length > 0 ? `${i2.base}:` : "", e2 = (s2) => t + s2; - let n3; - return i2.dbName && i2.storeName && (n3 = createStore(i2.dbName, i2.storeName)), { name: x, options: i2, async hasItem(s2) { - return !(typeof await get(e2(s2), n3) > "u"); - }, async getItem(s2) { - return await get(e2(s2), n3) ?? null; - }, setItem(s2, a3) { - return set(e2(s2), a3, n3); - }, removeItem(s2) { - return del(e2(s2), n3); - }, getKeys() { - return keys(n3); - }, clear() { - return clear(n3); - } }; - }; - D = "WALLET_CONNECT_V2_INDEXED_DB"; - E = "keyvaluestorage"; - _ = class { - constructor() { - this.indexedDb = createStorage({ driver: z({ dbName: D, storeName: E }) }); - } - async getKeys() { - return this.indexedDb.getKeys(); - } - async getEntries() { - return (await this.indexedDb.getItems(await this.indexedDb.getKeys())).map((t) => [t.key, t.value]); - } - async getItem(t) { - const e2 = await this.indexedDb.getItem(t); - if (e2 !== null) - return e2; - } - async setItem(t, e2) { - await this.indexedDb.setItem(t, safeJsonStringify(e2)); - } - async removeItem(t) { - await this.indexedDb.removeItem(t); - } - }; - l = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; - c = { exports: {} }; - (function() { - let i2; - function t() { - } - i2 = t, i2.prototype.getItem = function(e2) { - return this.hasOwnProperty(e2) ? String(this[e2]) : null; - }, i2.prototype.setItem = function(e2, n3) { - this[e2] = String(n3); - }, i2.prototype.removeItem = function(e2) { - delete this[e2]; - }, i2.prototype.clear = function() { - const e2 = this; - Object.keys(e2).forEach(function(n3) { - e2[n3] = void 0, delete e2[n3]; - }); - }, i2.prototype.key = function(e2) { - return e2 = e2 || 0, Object.keys(this)[e2]; - }, i2.prototype.__defineGetter__("length", function() { - return Object.keys(this).length; - }), typeof l < "u" && l.localStorage ? c.exports = l.localStorage : typeof window < "u" && window.localStorage ? c.exports = window.localStorage : c.exports = new t(); - })(); - K = class { - constructor() { - this.localStorage = c.exports; - } - async getKeys() { - return Object.keys(this.localStorage); - } - async getEntries() { - return Object.entries(this.localStorage).map(k); - } - async getItem(t) { - const e2 = this.localStorage.getItem(t); - if (e2 !== null) - return safeJsonParse(e2); - } - async setItem(t, e2) { - this.localStorage.setItem(t, safeJsonStringify(e2)); - } - async removeItem(t) { - this.localStorage.removeItem(t); - } - }; - N = "wc_storage_version"; - y = 1; - O = async (i2, t, e2) => { - const n3 = N, s2 = await t.getItem(n3); - if (s2 && s2 >= y) { - e2(t); - return; - } - const a3 = await i2.getKeys(); - if (!a3.length) { - e2(t); - return; - } - const m3 = []; - for (; a3.length; ) { - const r = a3.shift(); - if (!r) - continue; - const o2 = r.toLowerCase(); - if (o2.includes("wc@") || o2.includes("walletconnect") || o2.includes("wc_") || o2.includes("wallet_connect")) { - const f4 = await i2.getItem(r); - await t.setItem(r, f4), m3.push(r); - } - } - await t.setItem(n3, y), e2(t), j(i2, m3); - }; - j = async (i2, t) => { - t.length && t.forEach(async (e2) => { - await i2.removeItem(e2); - }); - }; - h = class { - constructor() { - this.initialized = false, this.setInitialized = (e2) => { - this.storage = e2, this.initialized = true; - }; - const t = new K(); - this.storage = t; - try { - const e2 = new _(); - O(t, e2, this.setInitialized); - } catch { - this.initialized = true; - } - } - async getKeys() { - return await this.initialize(), this.storage.getKeys(); - } - async getEntries() { - return await this.initialize(), this.storage.getEntries(); - } - async getItem(t) { - return await this.initialize(), this.storage.getItem(t); - } - async setItem(t, e2) { - return await this.initialize(), this.storage.setItem(t, e2); - } - async removeItem(t) { - return await this.initialize(), this.storage.removeItem(t); - } - async initialize() { - this.initialized || await new Promise((t) => { - const e2 = setInterval(() => { - this.initialized && (clearInterval(e2), t()); - }, 20); - }); - } - }; - } -}); +Is replaced with: -// node_modules/tslib/tslib.es6.js -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __read: () => __read, - __rest: () => __rest, - __spread: () => __spread, - __spreadArrays: () => __spreadArrays, - __values: () => __values -}); -function __extends(d3, b4) { - extendStatics(d3, b4); - function __() { - this.constructor = d3; - } - d3.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); -} -function __rest(s2, e2) { - var t = {}; - for (var p3 in s2) - if (Object.prototype.hasOwnProperty.call(s2, p3) && e2.indexOf(p3) < 0) - t[p3] = s2[p3]; - if (s2 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i2 = 0, p3 = Object.getOwnPropertySymbols(s2); i2 < p3.length; i2++) { - if (e2.indexOf(p3[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p3[i2])) - t[p3[i2]] = s2[p3[i2]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c4 = arguments.length, r = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") - r = Reflect.decorate(decorators, target, key, desc); - else - for (var i2 = decorators.length - 1; i2 >= 0; i2--) - if (d3 = decorators[i2]) - r = (c4 < 3 ? d3(r) : c4 > 3 ? d3(target, key, r) : d3(target, key)) || r; - return c4 > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") - return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _4 = { label: 0, sent: function() { - if (t[0] & 1) - throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f4, y4, t, g3; - return g3 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() { - return this; - }), g3; - function verb(n3) { - return function(v2) { - return step([n3, v2]); - }; - } - function step(op) { - if (f4) - throw new TypeError("Generator is already executing."); - while (_4) - try { - if (f4 = 1, y4 && (t = op[0] & 2 ? y4["return"] : op[0] ? y4["throw"] || ((t = y4["return"]) && t.call(y4), 0) : y4.next) && !(t = t.call(y4, op[1])).done) - return t; - if (y4 = 0, t) - op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _4.label++; - return { value: op[1], done: false }; - case 5: - _4.label++; - y4 = op[1]; - op = [0]; - continue; - case 7: - op = _4.ops.pop(); - _4.trys.pop(); - continue; - default: - if (!(t = _4.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _4 = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _4.label = op[1]; - break; - } - if (op[0] === 6 && _4.label < t[1]) { - _4.label = t[1]; - t = op; - break; - } - if (t && _4.label < t[2]) { - _4.label = t[2]; - _4.ops.push(op); - break; - } - if (t[2]) - _4.ops.pop(); - _4.trys.pop(); - continue; - } - op = body.call(thisArg, _4); - } catch (e2) { - op = [6, e2]; - y4 = 0; - } finally { - f4 = t = 0; - } - if (op[0] & 5) - throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __createBinding(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; -} -function __exportStar(m3, exports2) { - for (var p3 in m3) - if (p3 !== "default" && !exports2.hasOwnProperty(p3)) - exports2[p3] = m3[p3]; -} -function __values(o2) { - var s2 = typeof Symbol === "function" && Symbol.iterator, m3 = s2 && o2[s2], i2 = 0; - if (m3) - return m3.call(o2); - if (o2 && typeof o2.length === "number") - return { - next: function() { - if (o2 && i2 >= o2.length) - o2 = void 0; - return { value: o2 && o2[i2++], done: !o2 }; - } - }; - throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o2, n3) { - var m3 = typeof Symbol === "function" && o2[Symbol.iterator]; - if (!m3) - return o2; - var i2 = m3.call(o2), r, ar = [], e2; - try { - while ((n3 === void 0 || n3-- > 0) && !(r = i2.next()).done) - ar.push(r.value); - } catch (error) { - e2 = { error }; - } finally { - try { - if (r && !r.done && (m3 = i2["return"])) - m3.call(i2); - } finally { - if (e2) - throw e2.error; - } - } - return ar; -} -function __spread() { - for (var ar = [], i2 = 0; i2 < arguments.length; i2++) - ar = ar.concat(__read(arguments[i2])); - return ar; -} -function __spreadArrays() { - for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) - s2 += arguments[i2].length; - for (var r = Array(s2), k4 = 0, i2 = 0; i2 < il; i2++) - for (var a3 = arguments[i2], j2 = 0, jl = a3.length; j2 < jl; j2++, k4++) - r[k4] = a3[j2]; - return r; -} -function __await(v2) { - return this instanceof __await ? (this.v = v2, this) : new __await(v2); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g3 = generator.apply(thisArg, _arguments || []), i2, q2 = []; - return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { - return this; - }, i2; - function verb(n3) { - if (g3[n3]) - i2[n3] = function(v2) { - return new Promise(function(a3, b4) { - q2.push([n3, v2, a3, b4]) > 1 || resume(n3, v2); - }); - }; - } - function resume(n3, v2) { - try { - step(g3[n3](v2)); - } catch (e2) { - settle(q2[0][3], e2); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f4, v2) { - if (f4(v2), q2.shift(), q2.length) - resume(q2[0][0], q2[0][1]); - } -} -function __asyncDelegator(o2) { - var i2, p3; - return i2 = {}, verb("next"), verb("throw", function(e2) { - throw e2; - }), verb("return"), i2[Symbol.iterator] = function() { - return this; - }, i2; - function verb(n3, f4) { - i2[n3] = o2[n3] ? function(v2) { - return (p3 = !p3) ? { value: __await(o2[n3](v2)), done: n3 === "return" } : f4 ? f4(v2) : v2; - } : f4; - } -} -function __asyncValues(o2) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var m3 = o2[Symbol.asyncIterator], i2; - return m3 ? m3.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { - return this; - }, i2); - function verb(n3) { - i2[n3] = o2[n3] && function(v2) { - return new Promise(function(resolve, reject) { - v2 = o2[n3](v2), settle(resolve, reject, v2.done, v2.value); - }); - }; - } - function settle(resolve, reject, d3, v2) { - Promise.resolve(v2).then(function(v3) { - resolve({ value: v3, done: d3 }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (Object.hasOwnProperty.call(mod2, k4)) - result[k4] = mod2[k4]; - } - result.default = mod2; - return result; -} -function __importDefault(mod2) { - return mod2 && mod2.__esModule ? mod2 : { default: mod2 }; -} -function __classPrivateFieldGet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); -} -function __classPrivateFieldSet(receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) } -var extendStatics, __assign; -var init_tslib_es6 = __esm({ - "node_modules/tslib/tslib.es6.js"() { - init_shim(); - extendStatics = function(d3, b4) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b5) { - d4.__proto__ = b5; - } || function(d4, b5) { - for (var p3 in b5) - if (b5.hasOwnProperty(p3)) - d4[p3] = b5[p3]; - }; - return extendStatics(d3, b4); - }; - __assign = function() { - __assign = Object.assign || function __assign2(t) { - for (var s2, i2 = 1, n3 = arguments.length; i2 < n3; i2++) { - s2 = arguments[i2]; - for (var p3 in s2) - if (Object.prototype.hasOwnProperty.call(s2, p3)) - t[p3] = s2[p3]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/utils/delay.js -var require_delay = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/utils/delay.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = void 0; - function delay(timeout) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(true); - }, timeout); - }); - } - exports2.delay = delay; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/constants/misc.js -var require_misc = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/constants/misc.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ONE_THOUSAND = exports2.ONE_HUNDRED = void 0; - exports2.ONE_HUNDRED = 100; - exports2.ONE_THOUSAND = 1e3; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/constants/time.js -var require_time = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/constants/time.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ONE_YEAR = exports2.FOUR_WEEKS = exports2.THREE_WEEKS = exports2.TWO_WEEKS = exports2.ONE_WEEK = exports2.THIRTY_DAYS = exports2.SEVEN_DAYS = exports2.FIVE_DAYS = exports2.THREE_DAYS = exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS = exports2.TWELVE_HOURS = exports2.SIX_HOURS = exports2.THREE_HOURS = exports2.ONE_HOUR = exports2.SIXTY_MINUTES = exports2.THIRTY_MINUTES = exports2.TEN_MINUTES = exports2.FIVE_MINUTES = exports2.ONE_MINUTE = exports2.SIXTY_SECONDS = exports2.THIRTY_SECONDS = exports2.TEN_SECONDS = exports2.FIVE_SECONDS = exports2.ONE_SECOND = void 0; - exports2.ONE_SECOND = 1; - exports2.FIVE_SECONDS = 5; - exports2.TEN_SECONDS = 10; - exports2.THIRTY_SECONDS = 30; - exports2.SIXTY_SECONDS = 60; - exports2.ONE_MINUTE = exports2.SIXTY_SECONDS; - exports2.FIVE_MINUTES = exports2.ONE_MINUTE * 5; - exports2.TEN_MINUTES = exports2.ONE_MINUTE * 10; - exports2.THIRTY_MINUTES = exports2.ONE_MINUTE * 30; - exports2.SIXTY_MINUTES = exports2.ONE_MINUTE * 60; - exports2.ONE_HOUR = exports2.SIXTY_MINUTES; - exports2.THREE_HOURS = exports2.ONE_HOUR * 3; - exports2.SIX_HOURS = exports2.ONE_HOUR * 6; - exports2.TWELVE_HOURS = exports2.ONE_HOUR * 12; - exports2.TWENTY_FOUR_HOURS = exports2.ONE_HOUR * 24; - exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS; - exports2.THREE_DAYS = exports2.ONE_DAY * 3; - exports2.FIVE_DAYS = exports2.ONE_DAY * 5; - exports2.SEVEN_DAYS = exports2.ONE_DAY * 7; - exports2.THIRTY_DAYS = exports2.ONE_DAY * 30; - exports2.ONE_WEEK = exports2.SEVEN_DAYS; - exports2.TWO_WEEKS = exports2.ONE_WEEK * 2; - exports2.THREE_WEEKS = exports2.ONE_WEEK * 3; - exports2.FOUR_WEEKS = exports2.ONE_WEEK * 4; - exports2.ONE_YEAR = exports2.ONE_DAY * 365; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/constants/index.js -var require_constants4 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/constants/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_misc(), exports2); - tslib_1.__exportStar(require_time(), exports2); - } -}); - -// node_modules/@walletconnect/time/dist/cjs/utils/convert.js -var require_convert = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/utils/convert.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.fromMiliseconds = exports2.toMiliseconds = void 0; - var constants_1 = require_constants4(); - function toMiliseconds(seconds) { - return seconds * constants_1.ONE_THOUSAND; - } - exports2.toMiliseconds = toMiliseconds; - function fromMiliseconds2(miliseconds) { - return Math.floor(miliseconds / constants_1.ONE_THOUSAND); - } - exports2.fromMiliseconds = fromMiliseconds2; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/utils/index.js -var require_utils3 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/utils/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_delay(), exports2); - tslib_1.__exportStar(require_convert(), exports2); - } -}); - -// node_modules/@walletconnect/time/dist/cjs/watch.js -var require_watch = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/watch.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Watch = void 0; - var Watch = class { - constructor() { - this.timestamps = /* @__PURE__ */ new Map(); - } - start(label) { - if (this.timestamps.has(label)) { - throw new Error(`Watch already started for label: ${label}`); - } - this.timestamps.set(label, { started: Date.now() }); - } - stop(label) { - const timestamp = this.get(label); - if (typeof timestamp.elapsed !== "undefined") { - throw new Error(`Watch already stopped for label: ${label}`); - } - const elapsed = Date.now() - timestamp.started; - this.timestamps.set(label, { started: timestamp.started, elapsed }); - } - get(label) { - const timestamp = this.timestamps.get(label); - if (typeof timestamp === "undefined") { - throw new Error(`No timestamp found for label: ${label}`); - } - return timestamp; - } - elapsed(label) { - const timestamp = this.get(label); - const elapsed = timestamp.elapsed || Date.now() - timestamp.started; - return elapsed; - } - }; - exports2.Watch = Watch; - exports2.default = Watch; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/types/watch.js -var require_watch2 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/types/watch.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.IWatch = void 0; - var IWatch = class { - }; - exports2.IWatch = IWatch; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/types/index.js -var require_types2 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/types/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_watch2(), exports2); - } -}); - -// node_modules/@walletconnect/time/dist/cjs/index.js -var require_cjs = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_utils3(), exports2); - tslib_1.__exportStar(require_watch(), exports2); - tslib_1.__exportStar(require_types2(), exports2); - tslib_1.__exportStar(require_constants4(), exports2); - } -}); - -// node_modules/@walletconnect/events/dist/esm/events.js -var IEvents; -var init_events = __esm({ - "node_modules/@walletconnect/events/dist/esm/events.js"() { - init_shim(); - IEvents = class { - }; - } -}); - -// node_modules/@walletconnect/events/dist/esm/index.js -var esm_exports2 = {}; -__export(esm_exports2, { - IEvents: () => IEvents -}); -var init_esm2 = __esm({ - "node_modules/@walletconnect/events/dist/esm/index.js"() { - init_shim(); - init_events(); - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js -var require_heartbeat = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.IHeartBeat = void 0; - var events_1 = (init_esm2(), __toCommonJS(esm_exports2)); - var IHeartBeat = class extends events_1.IEvents { - constructor(opts) { - super(); - } - }; - exports2.IHeartBeat = IHeartBeat; - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js -var require_types3 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_heartbeat(), exports2); - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js -var require_heartbeat2 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HEARTBEAT_EVENTS = exports2.HEARTBEAT_INTERVAL = void 0; - var time_1 = require_cjs(); - exports2.HEARTBEAT_INTERVAL = time_1.FIVE_SECONDS; - exports2.HEARTBEAT_EVENTS = { - pulse: "heartbeat_pulse" - }; - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js -var require_constants5 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_heartbeat2(), exports2); - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js -var require_heartbeat3 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HeartBeat = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var events_1 = require_events(); - var time_1 = require_cjs(); - var types_1 = require_types3(); - var constants_1 = require_constants5(); - var HeartBeat = class _HeartBeat extends types_1.IHeartBeat { - constructor(opts) { - super(opts); - this.events = new events_1.EventEmitter(); - this.interval = constants_1.HEARTBEAT_INTERVAL; - this.interval = (opts === null || opts === void 0 ? void 0 : opts.interval) || constants_1.HEARTBEAT_INTERVAL; - } - static init(opts) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const heartbeat = new _HeartBeat(opts); - yield heartbeat.init(); - return heartbeat; - }); - } - init() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - yield this.initialize(); - }); - } - stop() { - clearInterval(this.intervalRef); - } - on(event, listener) { - this.events.on(event, listener); - } - once(event, listener) { - this.events.once(event, listener); - } - off(event, listener) { - this.events.off(event, listener); - } - removeListener(event, listener) { - this.events.removeListener(event, listener); - } - initialize() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - this.intervalRef = setInterval(() => this.pulse(), time_1.toMiliseconds(this.interval)); - }); - } - pulse() { - this.events.emit(constants_1.HEARTBEAT_EVENTS.pulse); - } - }; - exports2.HeartBeat = HeartBeat; - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/index.js -var require_cjs2 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_heartbeat3(), exports2); - tslib_1.__exportStar(require_types3(), exports2); - tslib_1.__exportStar(require_constants5(), exports2); - } -}); - -// node_modules/quick-format-unescaped/index.js -var require_quick_format_unescaped = __commonJS({ - "node_modules/quick-format-unescaped/index.js"(exports2, module2) { - "use strict"; - init_shim(); - function tryStringify(o2) { - try { - return JSON.stringify(o2); - } catch (e2) { - return '"[Circular]"'; - } - } - module2.exports = format; - function format(f4, args, opts) { - var ss = opts && opts.stringify || tryStringify; - var offset = 1; - if (typeof f4 === "object" && f4 !== null) { - var len = args.length + offset; - if (len === 1) - return f4; - var objects = new Array(len); - objects[0] = ss(f4); - for (var index = 1; index < len; index++) { - objects[index] = ss(args[index]); - } - return objects.join(" "); - } - if (typeof f4 !== "string") { - return f4; - } - var argLen = args.length; - if (argLen === 0) - return f4; - var str = ""; - var a3 = 1 - offset; - var lastPos = -1; - var flen = f4 && f4.length || 0; - for (var i2 = 0; i2 < flen; ) { - if (f4.charCodeAt(i2) === 37 && i2 + 1 < flen) { - lastPos = lastPos > -1 ? lastPos : 0; - switch (f4.charCodeAt(i2 + 1)) { - case 100: - case 102: - if (a3 >= argLen) - break; - if (args[a3] == null) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += Number(args[a3]); - lastPos = i2 + 2; - i2++; - break; - case 105: - if (a3 >= argLen) - break; - if (args[a3] == null) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += Math.floor(Number(args[a3])); - lastPos = i2 + 2; - i2++; - break; - case 79: - case 111: - case 106: - if (a3 >= argLen) - break; - if (args[a3] === void 0) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - var type = typeof args[a3]; - if (type === "string") { - str += "'" + args[a3] + "'"; - lastPos = i2 + 2; - i2++; - break; - } - if (type === "function") { - str += args[a3].name || ""; - lastPos = i2 + 2; - i2++; - break; - } - str += ss(args[a3]); - lastPos = i2 + 2; - i2++; - break; - case 115: - if (a3 >= argLen) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += String(args[a3]); - lastPos = i2 + 2; - i2++; - break; - case 37: - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += "%"; - lastPos = i2 + 2; - i2++; - a3--; - break; - } - ++a3; - } - ++i2; - } - if (lastPos === -1) - return f4; - else if (lastPos < flen) { - str += f4.slice(lastPos); - } - return str; - } - } -}); - -// node_modules/pino/browser.js -var require_browser3 = __commonJS({ - "node_modules/pino/browser.js"(exports2, module2) { - "use strict"; - init_shim(); - var format = require_quick_format_unescaped(); - module2.exports = pino; - var _console = pfGlobalThisOrFallback().console || {}; - var stdSerializers = { - mapHttpRequest: mock, - mapHttpResponse: mock, - wrapRequestSerializer: passthrough, - wrapResponseSerializer: passthrough, - wrapErrorSerializer: passthrough, - req: mock, - res: mock, - err: asErrValue - }; - function shouldSerialize(serialize, serializers) { - if (Array.isArray(serialize)) { - const hasToFilter = serialize.filter(function(k4) { - return k4 !== "!stdSerializers.err"; - }); - return hasToFilter; - } else if (serialize === true) { - return Object.keys(serializers); - } - return false; - } - function pino(opts) { - opts = opts || {}; - opts.browser = opts.browser || {}; - const transmit2 = opts.browser.transmit; - if (transmit2 && typeof transmit2.send !== "function") { - throw Error("pino: transmit option must have a send function"); - } - const proto = opts.browser.write || _console; - if (opts.browser.write) - opts.browser.asObject = true; - const serializers = opts.serializers || {}; - const serialize = shouldSerialize(opts.browser.serialize, serializers); - let stdErrSerialize = opts.browser.serialize; - if (Array.isArray(opts.browser.serialize) && opts.browser.serialize.indexOf("!stdSerializers.err") > -1) - stdErrSerialize = false; - const levels = ["error", "fatal", "warn", "info", "debug", "trace"]; - if (typeof proto === "function") { - proto.error = proto.fatal = proto.warn = proto.info = proto.debug = proto.trace = proto; - } - if (opts.enabled === false) - opts.level = "silent"; - const level = opts.level || "info"; - const logger = Object.create(proto); - if (!logger.log) - logger.log = noop; - Object.defineProperty(logger, "levelVal", { - get: getLevelVal - }); - Object.defineProperty(logger, "level", { - get: getLevel, - set: setLevel - }); - const setOpts = { - transmit: transmit2, - serialize, - asObject: opts.browser.asObject, - levels, - timestamp: getTimeFunction(opts) - }; - logger.levels = pino.levels; - logger.level = level; - logger.setMaxListeners = logger.getMaxListeners = logger.emit = logger.addListener = logger.on = logger.prependListener = logger.once = logger.prependOnceListener = logger.removeListener = logger.removeAllListeners = logger.listeners = logger.listenerCount = logger.eventNames = logger.write = logger.flush = noop; - logger.serializers = serializers; - logger._serialize = serialize; - logger._stdErrSerialize = stdErrSerialize; - logger.child = child; - if (transmit2) - logger._logEvent = createLogEventShape(); - function getLevelVal() { - return this.level === "silent" ? Infinity : this.levels.values[this.level]; - } - function getLevel() { - return this._level; - } - function setLevel(level2) { - if (level2 !== "silent" && !this.levels.values[level2]) { - throw Error("unknown level " + level2); - } - this._level = level2; - set2(setOpts, logger, "error", "log"); - set2(setOpts, logger, "fatal", "error"); - set2(setOpts, logger, "warn", "error"); - set2(setOpts, logger, "info", "log"); - set2(setOpts, logger, "debug", "log"); - set2(setOpts, logger, "trace", "log"); - } - function child(bindings, childOptions) { - if (!bindings) { - throw new Error("missing bindings for child Pino"); - } - childOptions = childOptions || {}; - if (serialize && bindings.serializers) { - childOptions.serializers = bindings.serializers; - } - const childOptionsSerializers = childOptions.serializers; - if (serialize && childOptionsSerializers) { - var childSerializers = Object.assign({}, serializers, childOptionsSerializers); - var childSerialize = opts.browser.serialize === true ? Object.keys(childSerializers) : serialize; - delete bindings.serializers; - applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize); - } - function Child(parent) { - this._childLevel = (parent._childLevel | 0) + 1; - this.error = bind(parent, bindings, "error"); - this.fatal = bind(parent, bindings, "fatal"); - this.warn = bind(parent, bindings, "warn"); - this.info = bind(parent, bindings, "info"); - this.debug = bind(parent, bindings, "debug"); - this.trace = bind(parent, bindings, "trace"); - if (childSerializers) { - this.serializers = childSerializers; - this._serialize = childSerialize; - } - if (transmit2) { - this._logEvent = createLogEventShape( - [].concat(parent._logEvent.bindings, bindings) - ); - } - } - Child.prototype = this; - return new Child(this); - } - return logger; - } - pino.levels = { - values: { - fatal: 60, - error: 50, - warn: 40, - info: 30, - debug: 20, - trace: 10 - }, - labels: { - 10: "trace", - 20: "debug", - 30: "info", - 40: "warn", - 50: "error", - 60: "fatal" - } - }; - pino.stdSerializers = stdSerializers; - pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime }); - function set2(opts, logger, level, fallback) { - const proto = Object.getPrototypeOf(logger); - logger[level] = logger.levelVal > logger.levels.values[level] ? noop : proto[level] ? proto[level] : _console[level] || _console[fallback] || noop; - wrap(opts, logger, level); - } - function wrap(opts, logger, level) { - if (!opts.transmit && logger[level] === noop) - return; - logger[level] = /* @__PURE__ */ function(write) { - return function LOG() { - const ts = opts.timestamp(); - const args = new Array(arguments.length); - const proto = Object.getPrototypeOf && Object.getPrototypeOf(this) === _console ? _console : this; - for (var i2 = 0; i2 < args.length; i2++) - args[i2] = arguments[i2]; - if (opts.serialize && !opts.asObject) { - applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize); - } - if (opts.asObject) - write.call(proto, asObject(this, level, args, ts)); - else - write.apply(proto, args); - if (opts.transmit) { - const transmitLevel = opts.transmit.level || logger.level; - const transmitValue = pino.levels.values[transmitLevel]; - const methodValue = pino.levels.values[level]; - if (methodValue < transmitValue) - return; - transmit(this, { - ts, - methodLevel: level, - methodValue, - transmitLevel, - transmitValue: pino.levels.values[opts.transmit.level || logger.level], - send: opts.transmit.send, - val: logger.levelVal - }, args); - } - }; - }(logger[level]); - } - function asObject(logger, level, args, ts) { - if (logger._serialize) - applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize); - const argsCloned = args.slice(); - let msg = argsCloned[0]; - const o2 = {}; - if (ts) { - o2.time = ts; - } - o2.level = pino.levels.values[level]; - let lvl = (logger._childLevel | 0) + 1; - if (lvl < 1) - lvl = 1; - if (msg !== null && typeof msg === "object") { - while (lvl-- && typeof argsCloned[0] === "object") { - Object.assign(o2, argsCloned.shift()); - } - msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : void 0; - } else if (typeof msg === "string") - msg = format(argsCloned.shift(), argsCloned); - if (msg !== void 0) - o2.msg = msg; - return o2; - } - function applySerializers(args, serialize, serializers, stdErrSerialize) { - for (const i2 in args) { - if (stdErrSerialize && args[i2] instanceof Error) { - args[i2] = pino.stdSerializers.err(args[i2]); - } else if (typeof args[i2] === "object" && !Array.isArray(args[i2])) { - for (const k4 in args[i2]) { - if (serialize && serialize.indexOf(k4) > -1 && k4 in serializers) { - args[i2][k4] = serializers[k4](args[i2][k4]); - } - } - } - } - } - function bind(parent, bindings, level) { - return function() { - const args = new Array(1 + arguments.length); - args[0] = bindings; - for (var i2 = 1; i2 < args.length; i2++) { - args[i2] = arguments[i2 - 1]; - } - return parent[level].apply(this, args); - }; - } - function transmit(logger, opts, args) { - const send = opts.send; - const ts = opts.ts; - const methodLevel = opts.methodLevel; - const methodValue = opts.methodValue; - const val = opts.val; - const bindings = logger._logEvent.bindings; - applySerializers( - args, - logger._serialize || Object.keys(logger.serializers), - logger.serializers, - logger._stdErrSerialize === void 0 ? true : logger._stdErrSerialize - ); - logger._logEvent.ts = ts; - logger._logEvent.messages = args.filter(function(arg) { - return bindings.indexOf(arg) === -1; - }); - logger._logEvent.level.label = methodLevel; - logger._logEvent.level.value = methodValue; - send(methodLevel, logger._logEvent, val); - logger._logEvent = createLogEventShape(bindings); - } - function createLogEventShape(bindings) { - return { - ts: 0, - messages: [], - bindings: bindings || [], - level: { label: "", value: 0 } - }; - } - function asErrValue(err) { - const obj = { - type: err.constructor.name, - msg: err.message, - stack: err.stack - }; - for (const key in err) { - if (obj[key] === void 0) { - obj[key] = err[key]; - } - } - return obj; - } - function getTimeFunction(opts) { - if (typeof opts.timestamp === "function") { - return opts.timestamp; - } - if (opts.timestamp === false) { - return nullTime; - } - return epochTime; - } - function mock() { - return {}; - } - function passthrough(a3) { - return a3; - } - function noop() { - } - function nullTime() { - return false; - } - function epochTime() { - return Date.now(); - } - function unixTime() { - return Math.round(Date.now() / 1e3); - } - function isoTime() { - return new Date(Date.now()).toISOString(); - } - function pfGlobalThisOrFallback() { - function defd(o2) { - return typeof o2 !== "undefined" && o2; - } - try { - if (typeof globalThis !== "undefined") - return globalThis; - Object.defineProperty(Object.prototype, "globalThis", { - get: function() { - delete Object.prototype.globalThis; - return this.globalThis = this; - }, - configurable: true - }); - return globalThis; - } catch (e2) { - return defd(self) || defd(window) || defd(this) || {}; - } - } - } -}); - -// node_modules/@walletconnect/logger/dist/index.es.js -var index_es_exports2 = {}; -__export(index_es_exports2, { - MAX_LOG_SIZE_IN_BYTES_DEFAULT: () => l2, - PINO_CUSTOM_CONTEXT_KEY: () => n, - PINO_LOGGER_DEFAULTS: () => c2, - formatChildLoggerContext: () => w, - generateChildLogger: () => E2, - generateClientLogger: () => C, - generatePlatformLogger: () => A, - generateServerLogger: () => I, - getBrowserLoggerContext: () => v, - getDefaultLoggerOptions: () => k2, - getLoggerContext: () => y2, - pino: () => import_pino2.default, - setBrowserLoggerContext: () => b -}); -function k2(r) { - return g(i({}, r), { level: r?.level || c2.level }); -} -function v(r, e2 = n) { - return r[e2] || ""; -} -function b(r, e2, t = n) { - return r[t] = e2, r; -} -function y2(r, e2 = n) { - let t = ""; - return typeof r.bindings > "u" ? t = v(r, e2) : t = r.bindings().context || "", t; -} -function w(r, e2, t = n) { - const o2 = y2(r, t); - return o2.trim() ? `${o2}/${e2}` : e2; -} -function E2(r, e2, t = n) { - const o2 = w(r, e2, t), a3 = r.child({ context: o2 }); - return b(a3, o2, t); -} -function C(r) { - var e2, t; - const o2 = new m((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); - return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace", browser: g(i({}, (t = r.opts) == null ? void 0 : t.browser), { write: (a3) => o2.write(a3) }) })), chunkLoggerController: o2 }; -} -function I(r) { - var e2; - const t = new B((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); - return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace" }), t), chunkLoggerController: t }; -} -function A(r) { - return typeof r.loggerOverride < "u" && typeof r.loggerOverride != "string" ? { logger: r.loggerOverride, chunkLoggerController: null } : typeof window < "u" ? C(r) : I(r); -} -var import_pino, import_pino2, c2, n, l2, O2, d, L, m, B, x2, S, _2, p, T, z2, f, i, g; -var init_index_es2 = __esm({ - "node_modules/@walletconnect/logger/dist/index.es.js"() { - init_shim(); - import_pino = __toESM(require_browser3()); - import_pino2 = __toESM(require_browser3()); - init_esm(); - c2 = { level: "info" }; - n = "custom_context"; - l2 = 1e3 * 1024; - O2 = class { - constructor(e2) { - this.nodeValue = e2, this.sizeInBytes = new TextEncoder().encode(this.nodeValue).length, this.next = null; - } - get value() { - return this.nodeValue; - } - get size() { - return this.sizeInBytes; - } - }; - d = class { - constructor(e2) { - this.head = null, this.tail = null, this.lengthInNodes = 0, this.maxSizeInBytes = e2, this.sizeInBytes = 0; - } - append(e2) { - const t = new O2(e2); - if (t.size > this.maxSizeInBytes) - throw new Error(`[LinkedList] Value too big to insert into list: ${e2} with size ${t.size}`); - for (; this.size + t.size > this.maxSizeInBytes; ) - this.shift(); - this.head ? (this.tail && (this.tail.next = t), this.tail = t) : (this.head = t, this.tail = t), this.lengthInNodes++, this.sizeInBytes += t.size; - } - shift() { - if (!this.head) - return; - const e2 = this.head; - this.head = this.head.next, this.head || (this.tail = null), this.lengthInNodes--, this.sizeInBytes -= e2.size; - } - toArray() { - const e2 = []; - let t = this.head; - for (; t !== null; ) - e2.push(t.value), t = t.next; - return e2; - } - get length() { - return this.lengthInNodes; - } - get size() { - return this.sizeInBytes; - } - toOrderedArray() { - return Array.from(this); - } - [Symbol.iterator]() { - let e2 = this.head; - return { next: () => { - if (!e2) - return { done: true, value: null }; - const t = e2.value; - return e2 = e2.next, { done: false, value: t }; - } }; - } - }; - L = class { - constructor(e2, t = l2) { - this.level = e2 ?? "error", this.levelValue = import_pino.levels.values[this.level], this.MAX_LOG_SIZE_IN_BYTES = t, this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); - } - forwardToConsole(e2, t) { - t === import_pino.levels.values.error ? console.error(e2) : t === import_pino.levels.values.warn ? console.warn(e2) : t === import_pino.levels.values.debug ? console.debug(e2) : t === import_pino.levels.values.trace ? console.trace(e2) : console.log(e2); - } - appendToLogs(e2) { - this.logs.append(safeJsonStringify({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), log: e2 })); - const t = typeof e2 == "string" ? JSON.parse(e2).level : e2.level; - t >= this.levelValue && this.forwardToConsole(e2, t); - } - getLogs() { - return this.logs; - } - clearLogs() { - this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); - } - getLogArray() { - return Array.from(this.logs); - } - logsToBlob(e2) { - const t = this.getLogArray(); - return t.push(safeJsonStringify({ extraMetadata: e2 })), new Blob(t, { type: "application/json" }); - } - }; - m = class { - constructor(e2, t = l2) { - this.baseChunkLogger = new L(e2, t); - } - write(e2) { - this.baseChunkLogger.appendToLogs(e2); - } - getLogs() { - return this.baseChunkLogger.getLogs(); - } - clearLogs() { - this.baseChunkLogger.clearLogs(); - } - getLogArray() { - return this.baseChunkLogger.getLogArray(); - } - logsToBlob(e2) { - return this.baseChunkLogger.logsToBlob(e2); - } - downloadLogsBlobInBrowser(e2) { - const t = URL.createObjectURL(this.logsToBlob(e2)), o2 = document.createElement("a"); - o2.href = t, o2.download = `walletconnect-logs-${(/* @__PURE__ */ new Date()).toISOString()}.txt`, document.body.appendChild(o2), o2.click(), document.body.removeChild(o2), URL.revokeObjectURL(t); - } - }; - B = class { - constructor(e2, t = l2) { - this.baseChunkLogger = new L(e2, t); - } - write(e2) { - this.baseChunkLogger.appendToLogs(e2); - } - getLogs() { - return this.baseChunkLogger.getLogs(); - } - clearLogs() { - this.baseChunkLogger.clearLogs(); - } - getLogArray() { - return this.baseChunkLogger.getLogArray(); - } - logsToBlob(e2) { - return this.baseChunkLogger.logsToBlob(e2); - } - }; - x2 = Object.defineProperty; - S = Object.defineProperties; - _2 = Object.getOwnPropertyDescriptors; - p = Object.getOwnPropertySymbols; - T = Object.prototype.hasOwnProperty; - z2 = Object.prototype.propertyIsEnumerable; - f = (r, e2, t) => e2 in r ? x2(r, e2, { enumerable: true, configurable: true, writable: true, value: t }) : r[e2] = t; - i = (r, e2) => { - for (var t in e2 || (e2 = {})) - T.call(e2, t) && f(r, t, e2[t]); - if (p) - for (var t of p(e2)) - z2.call(e2, t) && f(r, t, e2[t]); - return r; - }; - g = (r, e2) => S(r, _2(e2)); - } -}); - -// node_modules/@walletconnect/types/dist/index.cjs.js -var require_index_cjs = __commonJS({ - "node_modules/@walletconnect/types/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var r = (init_esm2(), __toCommonJS(esm_exports2)); - var c4 = require_events(); - function i2(t) { - return t && typeof t == "object" && "default" in t ? t : { default: t }; - } - var n3 = i2(c4); - var l4 = class extends r.IEvents { - constructor(s2) { - super(), this.opts = s2, this.protocol = "wc", this.version = 2; - } - }; - var a3 = class { - constructor(s2, e2, o2) { - this.core = s2, this.logger = e2; - } - }; - var u3 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.core = s2, this.logger = e2, this.records = /* @__PURE__ */ new Map(); - } - }; - var I2 = class { - constructor(s2, e2) { - this.logger = s2, this.core = e2; - } - }; - var h5 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.relayer = s2, this.logger = e2; - } - }; - var g3 = class extends r.IEvents { - constructor(s2) { - super(); - } - }; - var p3 = class { - constructor(s2, e2, o2, _4) { - this.core = s2, this.logger = e2, this.name = o2; - } - }; - var E4 = class { - constructor() { - this.map = /* @__PURE__ */ new Map(); - } - }; - var v2 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.relayer = s2, this.logger = e2; - } - }; - var d3 = class { - constructor(s2, e2) { - this.core = s2, this.logger = e2; - } - }; - var y4 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.core = s2, this.logger = e2; - } - }; - var b4 = class { - constructor(s2, e2) { - this.logger = s2, this.core = e2; - } - }; - var C3 = class { - constructor(s2, e2) { - this.projectId = s2, this.logger = e2; - } - }; - var f4 = class { - constructor(s2, e2) { - this.projectId = s2, this.logger = e2; - } - }; - var x3 = class extends n3.default { - constructor() { - super(); - } - }; - var S4 = class { - constructor(s2) { - this.opts = s2, this.protocol = "wc", this.version = 2; - } - }; - var M = class extends c4.EventEmitter { - constructor() { - super(); - } - }; - var P2 = class { - constructor(s2) { - this.client = s2; - } - }; - exports2.ICore = l4, exports2.ICrypto = a3, exports2.IEchoClient = f4, exports2.IEngine = P2, exports2.IEngineEvents = M, exports2.IExpirer = y4, exports2.IJsonRpcHistory = u3, exports2.IKeyChain = d3, exports2.IMessageTracker = I2, exports2.IPairing = b4, exports2.IPublisher = h5, exports2.IRelayer = g3, exports2.ISignClient = S4, exports2.ISignClientEvents = x3, exports2.IStore = p3, exports2.ISubscriber = v2, exports2.ISubscriberTopicMap = E4, exports2.IVerify = C3; - } -}); - -// node_modules/@stablelib/random/lib/source/browser.js -var require_browser4 = __commonJS({ - "node_modules/@stablelib/random/lib/source/browser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BrowserRandomSource = void 0; - var QUOTA = 65536; - var BrowserRandomSource = class { - constructor() { - this.isAvailable = false; - this.isInstantiated = false; - const browserCrypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; - if (browserCrypto && browserCrypto.getRandomValues !== void 0) { - this._crypto = browserCrypto; - this.isAvailable = true; - this.isInstantiated = true; - } - } - randomBytes(length2) { - if (!this.isAvailable || !this._crypto) { - throw new Error("Browser random byte generator is not available."); - } - const out = new Uint8Array(length2); - for (let i2 = 0; i2 < out.length; i2 += QUOTA) { - this._crypto.getRandomValues(out.subarray(i2, i2 + Math.min(out.length - i2, QUOTA))); - } - return out; - } - }; - exports2.BrowserRandomSource = BrowserRandomSource; - } -}); - -// node_modules/@stablelib/wipe/lib/wipe.js -var require_wipe = __commonJS({ - "node_modules/@stablelib/wipe/lib/wipe.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function wipe(array) { - for (var i2 = 0; i2 < array.length; i2++) { - array[i2] = 0; - } - return array; - } - exports2.wipe = wipe; - } -}); - -// (disabled):crypto -var require_crypto = __commonJS({ - "(disabled):crypto"() { - init_shim(); - } -}); - -// node_modules/@stablelib/random/lib/source/node.js -var require_node = __commonJS({ - "node_modules/@stablelib/random/lib/source/node.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NodeRandomSource = void 0; - var wipe_1 = require_wipe(); - var NodeRandomSource = class { - constructor() { - this.isAvailable = false; - this.isInstantiated = false; - if (typeof __require !== "undefined") { - const nodeCrypto = require_crypto(); - if (nodeCrypto && nodeCrypto.randomBytes) { - this._crypto = nodeCrypto; - this.isAvailable = true; - this.isInstantiated = true; - } - } - } - randomBytes(length2) { - if (!this.isAvailable || !this._crypto) { - throw new Error("Node.js random byte generator is not available."); - } - let buffer = this._crypto.randomBytes(length2); - if (buffer.length !== length2) { - throw new Error("NodeRandomSource: got fewer bytes than requested"); - } - const out = new Uint8Array(length2); - for (let i2 = 0; i2 < out.length; i2++) { - out[i2] = buffer[i2]; - } - (0, wipe_1.wipe)(buffer); - return out; - } - }; - exports2.NodeRandomSource = NodeRandomSource; - } -}); - -// node_modules/@stablelib/random/lib/source/system.js -var require_system = __commonJS({ - "node_modules/@stablelib/random/lib/source/system.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SystemRandomSource = void 0; - var browser_1 = require_browser4(); - var node_1 = require_node(); - var SystemRandomSource = class { - constructor() { - this.isAvailable = false; - this.name = ""; - this._source = new browser_1.BrowserRandomSource(); - if (this._source.isAvailable) { - this.isAvailable = true; - this.name = "Browser"; - return; - } - this._source = new node_1.NodeRandomSource(); - if (this._source.isAvailable) { - this.isAvailable = true; - this.name = "Node"; - return; - } - } - randomBytes(length2) { - if (!this.isAvailable) { - throw new Error("System random byte generator is not available."); - } - return this._source.randomBytes(length2); - } - }; - exports2.SystemRandomSource = SystemRandomSource; - } -}); - -// node_modules/@stablelib/int/lib/int.js -var require_int = __commonJS({ - "node_modules/@stablelib/int/lib/int.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function imulShim(a3, b4) { - var ah = a3 >>> 16 & 65535, al = a3 & 65535; - var bh = b4 >>> 16 & 65535, bl = b4 & 65535; - return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; - } - exports2.mul = Math.imul || imulShim; - function add(a3, b4) { - return a3 + b4 | 0; - } - exports2.add = add; - function sub(a3, b4) { - return a3 - b4 | 0; - } - exports2.sub = sub; - function rotl(x3, n3) { - return x3 << n3 | x3 >>> 32 - n3; - } - exports2.rotl = rotl; - function rotr(x3, n3) { - return x3 << 32 - n3 | x3 >>> n3; - } - exports2.rotr = rotr; - function isIntegerShim(n3) { - return typeof n3 === "number" && isFinite(n3) && Math.floor(n3) === n3; - } - exports2.isInteger = Number.isInteger || isIntegerShim; - exports2.MAX_SAFE_INTEGER = 9007199254740991; - exports2.isSafeInteger = function(n3) { - return exports2.isInteger(n3) && (n3 >= -exports2.MAX_SAFE_INTEGER && n3 <= exports2.MAX_SAFE_INTEGER); - }; - } -}); - -// node_modules/@stablelib/binary/lib/binary.js -var require_binary2 = __commonJS({ - "node_modules/@stablelib/binary/lib/binary.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var int_1 = require_int(); - function readInt16BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 0] << 8 | array[offset + 1]) << 16 >> 16; - } - exports2.readInt16BE = readInt16BE; - function readUint16BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 0] << 8 | array[offset + 1]) >>> 0; - } - exports2.readUint16BE = readUint16BE; - function readInt16LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 1] << 8 | array[offset]) << 16 >> 16; - } - exports2.readInt16LE = readInt16LE; - function readUint16LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 1] << 8 | array[offset]) >>> 0; - } - exports2.readUint16LE = readUint16LE; - function writeUint16BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(2); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 8; - out[offset + 1] = value >>> 0; - return out; - } - exports2.writeUint16BE = writeUint16BE; - exports2.writeInt16BE = writeUint16BE; - function writeUint16LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(2); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 0; - out[offset + 1] = value >>> 8; - return out; - } - exports2.writeUint16LE = writeUint16LE; - exports2.writeInt16LE = writeUint16LE; - function readInt32BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]; - } - exports2.readInt32BE = readInt32BE; - function readUint32BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]) >>> 0; - } - exports2.readUint32BE = readUint32BE; - function readInt32LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]; - } - exports2.readInt32LE = readInt32LE; - function readUint32LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]) >>> 0; - } - exports2.readUint32LE = readUint32LE; - function writeUint32BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 24; - out[offset + 1] = value >>> 16; - out[offset + 2] = value >>> 8; - out[offset + 3] = value >>> 0; - return out; - } - exports2.writeUint32BE = writeUint32BE; - exports2.writeInt32BE = writeUint32BE; - function writeUint32LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 0; - out[offset + 1] = value >>> 8; - out[offset + 2] = value >>> 16; - out[offset + 3] = value >>> 24; - return out; - } - exports2.writeUint32LE = writeUint32LE; - exports2.writeInt32LE = writeUint32LE; - function readInt64BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var hi = readInt32BE(array, offset); - var lo = readInt32BE(array, offset + 4); - return hi * 4294967296 + lo - (lo >> 31) * 4294967296; - } - exports2.readInt64BE = readInt64BE; - function readUint64BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var hi = readUint32BE(array, offset); - var lo = readUint32BE(array, offset + 4); - return hi * 4294967296 + lo; - } - exports2.readUint64BE = readUint64BE; - function readInt64LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var lo = readInt32LE(array, offset); - var hi = readInt32LE(array, offset + 4); - return hi * 4294967296 + lo - (lo >> 31) * 4294967296; - } - exports2.readInt64LE = readInt64LE; - function readUint64LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var lo = readUint32LE(array, offset); - var hi = readUint32LE(array, offset + 4); - return hi * 4294967296 + lo; - } - exports2.readUint64LE = readUint64LE; - function writeUint64BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - writeUint32BE(value / 4294967296 >>> 0, out, offset); - writeUint32BE(value >>> 0, out, offset + 4); - return out; - } - exports2.writeUint64BE = writeUint64BE; - exports2.writeInt64BE = writeUint64BE; - function writeUint64LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - writeUint32LE(value >>> 0, out, offset); - writeUint32LE(value / 4294967296 >>> 0, out, offset + 4); - return out; - } - exports2.writeUint64LE = writeUint64LE; - exports2.writeInt64LE = writeUint64LE; - function readUintBE(bitLength, array, offset) { - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("readUintBE supports only bitLengths divisible by 8"); - } - if (bitLength / 8 > array.length - offset) { - throw new Error("readUintBE: array is too short for the given bitLength"); - } - var result = 0; - var mul = 1; - for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { - result += array[i2] * mul; - mul *= 256; - } - return result; - } - exports2.readUintBE = readUintBE; - function readUintLE(bitLength, array, offset) { - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("readUintLE supports only bitLengths divisible by 8"); - } - if (bitLength / 8 > array.length - offset) { - throw new Error("readUintLE: array is too short for the given bitLength"); - } - var result = 0; - var mul = 1; - for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { - result += array[i2] * mul; - mul *= 256; - } - return result; - } - exports2.readUintLE = readUintLE; - function writeUintBE(bitLength, value, out, offset) { - if (out === void 0) { - out = new Uint8Array(bitLength / 8); - } - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("writeUintBE supports only bitLengths divisible by 8"); - } - if (!int_1.isSafeInteger(value)) { - throw new Error("writeUintBE value must be an integer"); - } - var div = 1; - for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { - out[i2] = value / div & 255; - div *= 256; - } - return out; - } - exports2.writeUintBE = writeUintBE; - function writeUintLE(bitLength, value, out, offset) { - if (out === void 0) { - out = new Uint8Array(bitLength / 8); - } - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("writeUintLE supports only bitLengths divisible by 8"); - } - if (!int_1.isSafeInteger(value)) { - throw new Error("writeUintLE value must be an integer"); - } - var div = 1; - for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { - out[i2] = value / div & 255; - div *= 256; - } - return out; - } - exports2.writeUintLE = writeUintLE; - function readFloat32BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat32(offset); - } - exports2.readFloat32BE = readFloat32BE; - function readFloat32LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat32(offset, true); - } - exports2.readFloat32LE = readFloat32LE; - function readFloat64BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat64(offset); - } - exports2.readFloat64BE = readFloat64BE; - function readFloat64LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat64(offset, true); - } - exports2.readFloat64LE = readFloat64LE; - function writeFloat32BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat32(offset, value); - return out; - } - exports2.writeFloat32BE = writeFloat32BE; - function writeFloat32LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat32(offset, value, true); - return out; - } - exports2.writeFloat32LE = writeFloat32LE; - function writeFloat64BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat64(offset, value); - return out; - } - exports2.writeFloat64BE = writeFloat64BE; - function writeFloat64LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat64(offset, value, true); - return out; - } - exports2.writeFloat64LE = writeFloat64LE; - } -}); - -// node_modules/@stablelib/random/lib/random.js -var require_random = __commonJS({ - "node_modules/@stablelib/random/lib/random.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomStringForEntropy = exports2.randomString = exports2.randomUint32 = exports2.randomBytes = exports2.defaultRandomSource = void 0; - var system_1 = require_system(); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - exports2.defaultRandomSource = new system_1.SystemRandomSource(); - function randomBytes2(length2, prng = exports2.defaultRandomSource) { - return prng.randomBytes(length2); - } - exports2.randomBytes = randomBytes2; - function randomUint32(prng = exports2.defaultRandomSource) { - const buf = randomBytes2(4, prng); - const result = (0, binary_1.readUint32LE)(buf); - (0, wipe_1.wipe)(buf); - return result; - } - exports2.randomUint32 = randomUint32; - var ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - function randomString(length2, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { - if (charset.length < 2) { - throw new Error("randomString charset is too short"); - } - if (charset.length > 256) { - throw new Error("randomString charset is too long"); - } - let out = ""; - const charsLen = charset.length; - const maxByte = 256 - 256 % charsLen; - while (length2 > 0) { - const buf = randomBytes2(Math.ceil(length2 * 256 / maxByte), prng); - for (let i2 = 0; i2 < buf.length && length2 > 0; i2++) { - const randomByte = buf[i2]; - if (randomByte < maxByte) { - out += charset.charAt(randomByte % charsLen); - length2--; - } - } - (0, wipe_1.wipe)(buf); - } - return out; - } - exports2.randomString = randomString; - function randomStringForEntropy(bits, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { - const length2 = Math.ceil(bits / (Math.log(charset.length) / Math.LN2)); - return randomString(length2, charset, prng); - } - exports2.randomStringForEntropy = randomStringForEntropy; - } -}); - -// node_modules/@stablelib/sha512/lib/sha512.js -var require_sha512 = __commonJS({ - "node_modules/@stablelib/sha512/lib/sha512.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - exports2.DIGEST_LENGTH = 64; - exports2.BLOCK_SIZE = 128; - var SHA512 = ( - /** @class */ - function() { - function SHA5122() { - this.digestLength = exports2.DIGEST_LENGTH; - this.blockSize = exports2.BLOCK_SIZE; - this._stateHi = new Int32Array(8); - this._stateLo = new Int32Array(8); - this._tempHi = new Int32Array(16); - this._tempLo = new Int32Array(16); - this._buffer = new Uint8Array(256); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - this.reset(); - } - SHA5122.prototype._initState = function() { - this._stateHi[0] = 1779033703; - this._stateHi[1] = 3144134277; - this._stateHi[2] = 1013904242; - this._stateHi[3] = 2773480762; - this._stateHi[4] = 1359893119; - this._stateHi[5] = 2600822924; - this._stateHi[6] = 528734635; - this._stateHi[7] = 1541459225; - this._stateLo[0] = 4089235720; - this._stateLo[1] = 2227873595; - this._stateLo[2] = 4271175723; - this._stateLo[3] = 1595750129; - this._stateLo[4] = 2917565137; - this._stateLo[5] = 725511199; - this._stateLo[6] = 4215389547; - this._stateLo[7] = 327033209; - }; - SHA5122.prototype.reset = function() { - this._initState(); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - return this; - }; - SHA5122.prototype.clean = function() { - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._tempHi); - wipe_1.wipe(this._tempLo); - this.reset(); - }; - SHA5122.prototype.update = function(data, dataLength) { - if (dataLength === void 0) { - dataLength = data.length; - } - if (this._finished) { - throw new Error("SHA512: can't update because hash was finished."); - } - var dataPos = 0; - this._bytesHashed += dataLength; - if (this._bufferLength > 0) { - while (this._bufferLength < exports2.BLOCK_SIZE && dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - if (this._bufferLength === this.blockSize) { - hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize); - this._bufferLength = 0; - } - } - if (dataLength >= this.blockSize) { - dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength); - dataLength %= this.blockSize; - } - while (dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - return this; - }; - SHA5122.prototype.finish = function(out) { - if (!this._finished) { - var bytesHashed = this._bytesHashed; - var left = this._bufferLength; - var bitLenHi = bytesHashed / 536870912 | 0; - var bitLenLo = bytesHashed << 3; - var padLength = bytesHashed % 128 < 112 ? 128 : 256; - this._buffer[left] = 128; - for (var i2 = left + 1; i2 < padLength - 8; i2++) { - this._buffer[i2] = 0; - } - binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); - binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); - hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength); - this._finished = true; - } - for (var i2 = 0; i2 < this.digestLength / 8; i2++) { - binary_1.writeUint32BE(this._stateHi[i2], out, i2 * 8); - binary_1.writeUint32BE(this._stateLo[i2], out, i2 * 8 + 4); - } - return this; - }; - SHA5122.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - SHA5122.prototype.saveState = function() { - if (this._finished) { - throw new Error("SHA256: cannot save finished state"); - } - return { - stateHi: new Int32Array(this._stateHi), - stateLo: new Int32Array(this._stateLo), - buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, - bufferLength: this._bufferLength, - bytesHashed: this._bytesHashed - }; - }; - SHA5122.prototype.restoreState = function(savedState) { - this._stateHi.set(savedState.stateHi); - this._stateLo.set(savedState.stateLo); - this._bufferLength = savedState.bufferLength; - if (savedState.buffer) { - this._buffer.set(savedState.buffer); - } - this._bytesHashed = savedState.bytesHashed; - this._finished = false; - return this; - }; - SHA5122.prototype.cleanSavedState = function(savedState) { - wipe_1.wipe(savedState.stateHi); - wipe_1.wipe(savedState.stateLo); - if (savedState.buffer) { - wipe_1.wipe(savedState.buffer); - } - savedState.bufferLength = 0; - savedState.bytesHashed = 0; - }; - return SHA5122; - }() - ); - exports2.SHA512 = SHA512; - var K2 = new Int32Array([ - 1116352408, - 3609767458, - 1899447441, - 602891725, - 3049323471, - 3964484399, - 3921009573, - 2173295548, - 961987163, - 4081628472, - 1508970993, - 3053834265, - 2453635748, - 2937671579, - 2870763221, - 3664609560, - 3624381080, - 2734883394, - 310598401, - 1164996542, - 607225278, - 1323610764, - 1426881987, - 3590304994, - 1925078388, - 4068182383, - 2162078206, - 991336113, - 2614888103, - 633803317, - 3248222580, - 3479774868, - 3835390401, - 2666613458, - 4022224774, - 944711139, - 264347078, - 2341262773, - 604807628, - 2007800933, - 770255983, - 1495990901, - 1249150122, - 1856431235, - 1555081692, - 3175218132, - 1996064986, - 2198950837, - 2554220882, - 3999719339, - 2821834349, - 766784016, - 2952996808, - 2566594879, - 3210313671, - 3203337956, - 3336571891, - 1034457026, - 3584528711, - 2466948901, - 113926993, - 3758326383, - 338241895, - 168717936, - 666307205, - 1188179964, - 773529912, - 1546045734, - 1294757372, - 1522805485, - 1396182291, - 2643833823, - 1695183700, - 2343527390, - 1986661051, - 1014477480, - 2177026350, - 1206759142, - 2456956037, - 344077627, - 2730485921, - 1290863460, - 2820302411, - 3158454273, - 3259730800, - 3505952657, - 3345764771, - 106217008, - 3516065817, - 3606008344, - 3600352804, - 1432725776, - 4094571909, - 1467031594, - 275423344, - 851169720, - 430227734, - 3100823752, - 506948616, - 1363258195, - 659060556, - 3750685593, - 883997877, - 3785050280, - 958139571, - 3318307427, - 1322822218, - 3812723403, - 1537002063, - 2003034995, - 1747873779, - 3602036899, - 1955562222, - 1575990012, - 2024104815, - 1125592928, - 2227730452, - 2716904306, - 2361852424, - 442776044, - 2428436474, - 593698344, - 2756734187, - 3733110249, - 3204031479, - 2999351573, - 3329325298, - 3815920427, - 3391569614, - 3928383900, - 3515267271, - 566280711, - 3940187606, - 3454069534, - 4118630271, - 4000239992, - 116418474, - 1914138554, - 174292421, - 2731055270, - 289380356, - 3203993006, - 460393269, - 320620315, - 685471733, - 587496836, - 852142971, - 1086792851, - 1017036298, - 365543100, - 1126000580, - 2618297676, - 1288033470, - 3409855158, - 1501505948, - 4234509866, - 1607167915, - 987167468, - 1816402316, - 1246189591 - ]); - function hashBlocks(wh, wl, hh, hl, m3, pos, len) { - var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; - var h5, l4; - var th, tl; - var a3, b4, c4, d3; - while (len >= 128) { - for (var i2 = 0; i2 < 16; i2++) { - var j2 = 8 * i2 + pos; - wh[i2] = binary_1.readUint32BE(m3, j2); - wl[i2] = binary_1.readUint32BE(m3, j2 + 4); - } - for (var i2 = 0; i2 < 80; i2++) { - var bh0 = ah0; - var bh1 = ah1; - var bh2 = ah2; - var bh3 = ah3; - var bh4 = ah4; - var bh5 = ah5; - var bh6 = ah6; - var bh7 = ah7; - var bl0 = al0; - var bl1 = al1; - var bl2 = al2; - var bl3 = al3; - var bl4 = al4; - var bl5 = al5; - var bl6 = al6; - var bl7 = al7; - h5 = ah7; - l4 = al7; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); - l4 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = ah4 & ah5 ^ ~ah4 & ah6; - l4 = al4 & al5 ^ ~al4 & al6; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = K2[i2 * 2]; - l4 = K2[i2 * 2 + 1]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = wh[i2 % 16]; - l4 = wl[i2 % 16]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - th = c4 & 65535 | d3 << 16; - tl = a3 & 65535 | b4 << 16; - h5 = th; - l4 = tl; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); - l4 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; - l4 = al0 & al1 ^ al0 & al2 ^ al1 & al2; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - bh7 = c4 & 65535 | d3 << 16; - bl7 = a3 & 65535 | b4 << 16; - h5 = bh3; - l4 = bl3; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = th; - l4 = tl; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - bh3 = c4 & 65535 | d3 << 16; - bl3 = a3 & 65535 | b4 << 16; - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; - if (i2 % 16 === 15) { - for (var j2 = 0; j2 < 16; j2++) { - h5 = wh[j2]; - l4 = wl[j2]; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = wh[(j2 + 9) % 16]; - l4 = wl[(j2 + 9) % 16]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - th = wh[(j2 + 1) % 16]; - tl = wl[(j2 + 1) % 16]; - h5 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; - l4 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - th = wh[(j2 + 14) % 16]; - tl = wl[(j2 + 14) % 16]; - h5 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; - l4 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - wh[j2] = c4 & 65535 | d3 << 16; - wl[j2] = a3 & 65535 | b4 << 16; - } - } - } - h5 = ah0; - l4 = al0; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[0]; - l4 = hl[0]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[0] = ah0 = c4 & 65535 | d3 << 16; - hl[0] = al0 = a3 & 65535 | b4 << 16; - h5 = ah1; - l4 = al1; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[1]; - l4 = hl[1]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[1] = ah1 = c4 & 65535 | d3 << 16; - hl[1] = al1 = a3 & 65535 | b4 << 16; - h5 = ah2; - l4 = al2; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[2]; - l4 = hl[2]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[2] = ah2 = c4 & 65535 | d3 << 16; - hl[2] = al2 = a3 & 65535 | b4 << 16; - h5 = ah3; - l4 = al3; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[3]; - l4 = hl[3]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[3] = ah3 = c4 & 65535 | d3 << 16; - hl[3] = al3 = a3 & 65535 | b4 << 16; - h5 = ah4; - l4 = al4; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[4]; - l4 = hl[4]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[4] = ah4 = c4 & 65535 | d3 << 16; - hl[4] = al4 = a3 & 65535 | b4 << 16; - h5 = ah5; - l4 = al5; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[5]; - l4 = hl[5]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[5] = ah5 = c4 & 65535 | d3 << 16; - hl[5] = al5 = a3 & 65535 | b4 << 16; - h5 = ah6; - l4 = al6; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[6]; - l4 = hl[6]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[6] = ah6 = c4 & 65535 | d3 << 16; - hl[6] = al6 = a3 & 65535 | b4 << 16; - h5 = ah7; - l4 = al7; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[7]; - l4 = hl[7]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[7] = ah7 = c4 & 65535 | d3 << 16; - hl[7] = al7 = a3 & 65535 | b4 << 16; - pos += 128; - len -= 128; - } - return pos; - } - function hash(data) { - var h5 = new SHA512(); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.hash = hash; - } -}); - -// node_modules/@stablelib/ed25519/lib/ed25519.js -var require_ed25519 = __commonJS({ - "node_modules/@stablelib/ed25519/lib/ed25519.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.convertSecretKeyToX25519 = exports2.convertPublicKeyToX25519 = exports2.verify = exports2.sign = exports2.extractPublicKeyFromSecretKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.SEED_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = exports2.SIGNATURE_LENGTH = void 0; - var random_1 = require_random(); - var sha512_1 = require_sha512(); - var wipe_1 = require_wipe(); - exports2.SIGNATURE_LENGTH = 64; - exports2.PUBLIC_KEY_LENGTH = 32; - exports2.SECRET_KEY_LENGTH = 64; - exports2.SEED_LENGTH = 32; - function gf(init) { - const r = new Float64Array(16); - if (init) { - for (let i2 = 0; i2 < init.length; i2++) { - r[i2] = init[i2]; - } - } - return r; - } - var _9 = new Uint8Array(32); - _9[0] = 9; - var gf0 = gf(); - var gf1 = gf([1]); - var D2 = gf([ - 30883, - 4953, - 19914, - 30187, - 55467, - 16705, - 2637, - 112, - 59544, - 30585, - 16505, - 36039, - 65139, - 11119, - 27886, - 20995 - ]); - var D22 = gf([ - 61785, - 9906, - 39828, - 60374, - 45398, - 33411, - 5274, - 224, - 53552, - 61171, - 33010, - 6542, - 64743, - 22239, - 55772, - 9222 - ]); - var X = gf([ - 54554, - 36645, - 11616, - 51542, - 42930, - 38181, - 51040, - 26924, - 56412, - 64982, - 57905, - 49316, - 21502, - 52590, - 14035, - 8553 - ]); - var Y = gf([ - 26200, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214 - ]); - var I2 = gf([ - 41136, - 18958, - 6951, - 50414, - 58488, - 44335, - 6150, - 12099, - 55207, - 15867, - 153, - 11085, - 57099, - 20417, - 9344, - 11139 - ]); - function set25519(r, a3) { - for (let i2 = 0; i2 < 16; i2++) { - r[i2] = a3[i2] | 0; - } - } - function car25519(o2) { - let c4 = 1; - for (let i2 = 0; i2 < 16; i2++) { - let v2 = o2[i2] + c4 + 65535; - c4 = Math.floor(v2 / 65536); - o2[i2] = v2 - c4 * 65536; - } - o2[0] += c4 - 1 + 37 * (c4 - 1); - } - function sel25519(p3, q2, b4) { - const c4 = ~(b4 - 1); - for (let i2 = 0; i2 < 16; i2++) { - const t = c4 & (p3[i2] ^ q2[i2]); - p3[i2] ^= t; - q2[i2] ^= t; - } - } - function pack25519(o2, n3) { - const m3 = gf(); - const t = gf(); - for (let i2 = 0; i2 < 16; i2++) { - t[i2] = n3[i2]; - } - car25519(t); - car25519(t); - car25519(t); - for (let j2 = 0; j2 < 2; j2++) { - m3[0] = t[0] - 65517; - for (let i2 = 1; i2 < 15; i2++) { - m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); - m3[i2 - 1] &= 65535; - } - m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); - const b4 = m3[15] >> 16 & 1; - m3[14] &= 65535; - sel25519(t, m3, 1 - b4); - } - for (let i2 = 0; i2 < 16; i2++) { - o2[2 * i2] = t[i2] & 255; - o2[2 * i2 + 1] = t[i2] >> 8; - } - } - function verify32(x3, y4) { - let d3 = 0; - for (let i2 = 0; i2 < 32; i2++) { - d3 |= x3[i2] ^ y4[i2]; - } - return (1 & d3 - 1 >>> 8) - 1; - } - function neq25519(a3, b4) { - const c4 = new Uint8Array(32); - const d3 = new Uint8Array(32); - pack25519(c4, a3); - pack25519(d3, b4); - return verify32(c4, d3); - } - function par25519(a3) { - const d3 = new Uint8Array(32); - pack25519(d3, a3); - return d3[0] & 1; - } - function unpack25519(o2, n3) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); - } - o2[15] &= 32767; - } - function add(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] + b4[i2]; - } - } - function sub(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] - b4[i2]; - } - } - function mul(o2, a3, b4) { - let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; - v2 = a3[0]; - t0 += v2 * b0; - t1 += v2 * b1; - t2 += v2 * b22; - t3 += v2 * b32; - t4 += v2 * b42; - t5 += v2 * b5; - t6 += v2 * b6; - t7 += v2 * b7; - t8 += v2 * b8; - t9 += v2 * b9; - t10 += v2 * b10; - t11 += v2 * b11; - t12 += v2 * b12; - t13 += v2 * b13; - t14 += v2 * b14; - t15 += v2 * b15; - v2 = a3[1]; - t1 += v2 * b0; - t2 += v2 * b1; - t3 += v2 * b22; - t4 += v2 * b32; - t5 += v2 * b42; - t6 += v2 * b5; - t7 += v2 * b6; - t8 += v2 * b7; - t9 += v2 * b8; - t10 += v2 * b9; - t11 += v2 * b10; - t12 += v2 * b11; - t13 += v2 * b12; - t14 += v2 * b13; - t15 += v2 * b14; - t16 += v2 * b15; - v2 = a3[2]; - t2 += v2 * b0; - t3 += v2 * b1; - t4 += v2 * b22; - t5 += v2 * b32; - t6 += v2 * b42; - t7 += v2 * b5; - t8 += v2 * b6; - t9 += v2 * b7; - t10 += v2 * b8; - t11 += v2 * b9; - t12 += v2 * b10; - t13 += v2 * b11; - t14 += v2 * b12; - t15 += v2 * b13; - t16 += v2 * b14; - t17 += v2 * b15; - v2 = a3[3]; - t3 += v2 * b0; - t4 += v2 * b1; - t5 += v2 * b22; - t6 += v2 * b32; - t7 += v2 * b42; - t8 += v2 * b5; - t9 += v2 * b6; - t10 += v2 * b7; - t11 += v2 * b8; - t12 += v2 * b9; - t13 += v2 * b10; - t14 += v2 * b11; - t15 += v2 * b12; - t16 += v2 * b13; - t17 += v2 * b14; - t18 += v2 * b15; - v2 = a3[4]; - t4 += v2 * b0; - t5 += v2 * b1; - t6 += v2 * b22; - t7 += v2 * b32; - t8 += v2 * b42; - t9 += v2 * b5; - t10 += v2 * b6; - t11 += v2 * b7; - t12 += v2 * b8; - t13 += v2 * b9; - t14 += v2 * b10; - t15 += v2 * b11; - t16 += v2 * b12; - t17 += v2 * b13; - t18 += v2 * b14; - t19 += v2 * b15; - v2 = a3[5]; - t5 += v2 * b0; - t6 += v2 * b1; - t7 += v2 * b22; - t8 += v2 * b32; - t9 += v2 * b42; - t10 += v2 * b5; - t11 += v2 * b6; - t12 += v2 * b7; - t13 += v2 * b8; - t14 += v2 * b9; - t15 += v2 * b10; - t16 += v2 * b11; - t17 += v2 * b12; - t18 += v2 * b13; - t19 += v2 * b14; - t20 += v2 * b15; - v2 = a3[6]; - t6 += v2 * b0; - t7 += v2 * b1; - t8 += v2 * b22; - t9 += v2 * b32; - t10 += v2 * b42; - t11 += v2 * b5; - t12 += v2 * b6; - t13 += v2 * b7; - t14 += v2 * b8; - t15 += v2 * b9; - t16 += v2 * b10; - t17 += v2 * b11; - t18 += v2 * b12; - t19 += v2 * b13; - t20 += v2 * b14; - t21 += v2 * b15; - v2 = a3[7]; - t7 += v2 * b0; - t8 += v2 * b1; - t9 += v2 * b22; - t10 += v2 * b32; - t11 += v2 * b42; - t12 += v2 * b5; - t13 += v2 * b6; - t14 += v2 * b7; - t15 += v2 * b8; - t16 += v2 * b9; - t17 += v2 * b10; - t18 += v2 * b11; - t19 += v2 * b12; - t20 += v2 * b13; - t21 += v2 * b14; - t22 += v2 * b15; - v2 = a3[8]; - t8 += v2 * b0; - t9 += v2 * b1; - t10 += v2 * b22; - t11 += v2 * b32; - t12 += v2 * b42; - t13 += v2 * b5; - t14 += v2 * b6; - t15 += v2 * b7; - t16 += v2 * b8; - t17 += v2 * b9; - t18 += v2 * b10; - t19 += v2 * b11; - t20 += v2 * b12; - t21 += v2 * b13; - t22 += v2 * b14; - t23 += v2 * b15; - v2 = a3[9]; - t9 += v2 * b0; - t10 += v2 * b1; - t11 += v2 * b22; - t12 += v2 * b32; - t13 += v2 * b42; - t14 += v2 * b5; - t15 += v2 * b6; - t16 += v2 * b7; - t17 += v2 * b8; - t18 += v2 * b9; - t19 += v2 * b10; - t20 += v2 * b11; - t21 += v2 * b12; - t22 += v2 * b13; - t23 += v2 * b14; - t24 += v2 * b15; - v2 = a3[10]; - t10 += v2 * b0; - t11 += v2 * b1; - t12 += v2 * b22; - t13 += v2 * b32; - t14 += v2 * b42; - t15 += v2 * b5; - t16 += v2 * b6; - t17 += v2 * b7; - t18 += v2 * b8; - t19 += v2 * b9; - t20 += v2 * b10; - t21 += v2 * b11; - t22 += v2 * b12; - t23 += v2 * b13; - t24 += v2 * b14; - t25 += v2 * b15; - v2 = a3[11]; - t11 += v2 * b0; - t12 += v2 * b1; - t13 += v2 * b22; - t14 += v2 * b32; - t15 += v2 * b42; - t16 += v2 * b5; - t17 += v2 * b6; - t18 += v2 * b7; - t19 += v2 * b8; - t20 += v2 * b9; - t21 += v2 * b10; - t22 += v2 * b11; - t23 += v2 * b12; - t24 += v2 * b13; - t25 += v2 * b14; - t26 += v2 * b15; - v2 = a3[12]; - t12 += v2 * b0; - t13 += v2 * b1; - t14 += v2 * b22; - t15 += v2 * b32; - t16 += v2 * b42; - t17 += v2 * b5; - t18 += v2 * b6; - t19 += v2 * b7; - t20 += v2 * b8; - t21 += v2 * b9; - t22 += v2 * b10; - t23 += v2 * b11; - t24 += v2 * b12; - t25 += v2 * b13; - t26 += v2 * b14; - t27 += v2 * b15; - v2 = a3[13]; - t13 += v2 * b0; - t14 += v2 * b1; - t15 += v2 * b22; - t16 += v2 * b32; - t17 += v2 * b42; - t18 += v2 * b5; - t19 += v2 * b6; - t20 += v2 * b7; - t21 += v2 * b8; - t22 += v2 * b9; - t23 += v2 * b10; - t24 += v2 * b11; - t25 += v2 * b12; - t26 += v2 * b13; - t27 += v2 * b14; - t28 += v2 * b15; - v2 = a3[14]; - t14 += v2 * b0; - t15 += v2 * b1; - t16 += v2 * b22; - t17 += v2 * b32; - t18 += v2 * b42; - t19 += v2 * b5; - t20 += v2 * b6; - t21 += v2 * b7; - t22 += v2 * b8; - t23 += v2 * b9; - t24 += v2 * b10; - t25 += v2 * b11; - t26 += v2 * b12; - t27 += v2 * b13; - t28 += v2 * b14; - t29 += v2 * b15; - v2 = a3[15]; - t15 += v2 * b0; - t16 += v2 * b1; - t17 += v2 * b22; - t18 += v2 * b32; - t19 += v2 * b42; - t20 += v2 * b5; - t21 += v2 * b6; - t22 += v2 * b7; - t23 += v2 * b8; - t24 += v2 * b9; - t25 += v2 * b10; - t26 += v2 * b11; - t27 += v2 * b12; - t28 += v2 * b13; - t29 += v2 * b14; - t30 += v2 * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - o2[0] = t0; - o2[1] = t1; - o2[2] = t2; - o2[3] = t3; - o2[4] = t4; - o2[5] = t5; - o2[6] = t6; - o2[7] = t7; - o2[8] = t8; - o2[9] = t9; - o2[10] = t10; - o2[11] = t11; - o2[12] = t12; - o2[13] = t13; - o2[14] = t14; - o2[15] = t15; - } - function square(o2, a3) { - mul(o2, a3, a3); - } - function inv25519(o2, i2) { - const c4 = gf(); - let a3; - for (a3 = 0; a3 < 16; a3++) { - c4[a3] = i2[a3]; - } - for (a3 = 253; a3 >= 0; a3--) { - square(c4, c4); - if (a3 !== 2 && a3 !== 4) { - mul(c4, c4, i2); - } - } - for (a3 = 0; a3 < 16; a3++) { - o2[a3] = c4[a3]; - } - } - function pow2523(o2, i2) { - const c4 = gf(); - let a3; - for (a3 = 0; a3 < 16; a3++) { - c4[a3] = i2[a3]; - } - for (a3 = 250; a3 >= 0; a3--) { - square(c4, c4); - if (a3 !== 1) { - mul(c4, c4, i2); - } - } - for (a3 = 0; a3 < 16; a3++) { - o2[a3] = c4[a3]; - } - } - function edadd(p3, q2) { - const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(), g3 = gf(), h5 = gf(), t = gf(); - sub(a3, p3[1], p3[0]); - sub(t, q2[1], q2[0]); - mul(a3, a3, t); - add(b4, p3[0], p3[1]); - add(t, q2[0], q2[1]); - mul(b4, b4, t); - mul(c4, p3[3], q2[3]); - mul(c4, c4, D22); - mul(d3, p3[2], q2[2]); - add(d3, d3, d3); - sub(e2, b4, a3); - sub(f4, d3, c4); - add(g3, d3, c4); - add(h5, b4, a3); - mul(p3[0], e2, f4); - mul(p3[1], h5, g3); - mul(p3[2], g3, f4); - mul(p3[3], e2, h5); - } - function cswap(p3, q2, b4) { - for (let i2 = 0; i2 < 4; i2++) { - sel25519(p3[i2], q2[i2], b4); - } - } - function pack(r, p3) { - const tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p3[2]); - mul(tx, p3[0], zi); - mul(ty, p3[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function scalarmult(p3, q2, s2) { - set25519(p3[0], gf0); - set25519(p3[1], gf1); - set25519(p3[2], gf1); - set25519(p3[3], gf0); - for (let i2 = 255; i2 >= 0; --i2) { - const b4 = s2[i2 / 8 | 0] >> (i2 & 7) & 1; - cswap(p3, q2, b4); - edadd(q2, p3); - edadd(p3, p3); - cswap(p3, q2, b4); - } - } - function scalarbase(p3, s2) { - const q2 = [gf(), gf(), gf(), gf()]; - set25519(q2[0], X); - set25519(q2[1], Y); - set25519(q2[2], gf1); - mul(q2[3], X, Y); - scalarmult(p3, q2, s2); - } - function generateKeyPairFromSeed2(seed) { - if (seed.length !== exports2.SEED_LENGTH) { - throw new Error(`ed25519: seed must be ${exports2.SEED_LENGTH} bytes`); - } - const d3 = (0, sha512_1.hash)(seed); - d3[0] &= 248; - d3[31] &= 127; - d3[31] |= 64; - const publicKey = new Uint8Array(32); - const p3 = [gf(), gf(), gf(), gf()]; - scalarbase(p3, d3); - pack(publicKey, p3); - const secretKey = new Uint8Array(64); - secretKey.set(seed); - secretKey.set(publicKey, 32); - return { - publicKey, - secretKey - }; - } - exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; - function generateKeyPair2(prng) { - const seed = (0, random_1.randomBytes)(32, prng); - const result = generateKeyPairFromSeed2(seed); - (0, wipe_1.wipe)(seed); - return result; - } - exports2.generateKeyPair = generateKeyPair2; - function extractPublicKeyFromSecretKey(secretKey) { - if (secretKey.length !== exports2.SECRET_KEY_LENGTH) { - throw new Error(`ed25519: secret key must be ${exports2.SECRET_KEY_LENGTH} bytes`); - } - return new Uint8Array(secretKey.subarray(32)); - } - exports2.extractPublicKeyFromSecretKey = extractPublicKeyFromSecretKey; - var L2 = new Float64Array([ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16 - ]); - function modL(r, x3) { - let carry; - let i2; - let j2; - let k4; - for (i2 = 63; i2 >= 32; --i2) { - carry = 0; - for (j2 = i2 - 32, k4 = i2 - 12; j2 < k4; ++j2) { - x3[j2] += carry - 16 * x3[i2] * L2[j2 - (i2 - 32)]; - carry = Math.floor((x3[j2] + 128) / 256); - x3[j2] -= carry * 256; - } - x3[j2] += carry; - x3[i2] = 0; - } - carry = 0; - for (j2 = 0; j2 < 32; j2++) { - x3[j2] += carry - (x3[31] >> 4) * L2[j2]; - carry = x3[j2] >> 8; - x3[j2] &= 255; - } - for (j2 = 0; j2 < 32; j2++) { - x3[j2] -= carry * L2[j2]; - } - for (i2 = 0; i2 < 32; i2++) { - x3[i2 + 1] += x3[i2] >> 8; - r[i2] = x3[i2] & 255; - } - } - function reduce(r) { - const x3 = new Float64Array(64); - for (let i2 = 0; i2 < 64; i2++) { - x3[i2] = r[i2]; - } - for (let i2 = 0; i2 < 64; i2++) { - r[i2] = 0; - } - modL(r, x3); - } - function sign2(secretKey, message) { - const x3 = new Float64Array(64); - const p3 = [gf(), gf(), gf(), gf()]; - const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); - d3[0] &= 248; - d3[31] &= 127; - d3[31] |= 64; - const signature = new Uint8Array(64); - signature.set(d3.subarray(32), 32); - const hs = new sha512_1.SHA512(); - hs.update(signature.subarray(32)); - hs.update(message); - const r = hs.digest(); - hs.clean(); - reduce(r); - scalarbase(p3, r); - pack(signature, p3); - hs.reset(); - hs.update(signature.subarray(0, 32)); - hs.update(secretKey.subarray(32)); - hs.update(message); - const h5 = hs.digest(); - reduce(h5); - for (let i2 = 0; i2 < 32; i2++) { - x3[i2] = r[i2]; - } - for (let i2 = 0; i2 < 32; i2++) { - for (let j2 = 0; j2 < 32; j2++) { - x3[i2 + j2] += h5[i2] * d3[j2]; - } - } - modL(signature.subarray(32), x3); - return signature; - } - exports2.sign = sign2; - function unpackneg(r, p3) { - const t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p3); - square(num, r[1]); - mul(den, num, D2); - sub(num, num, r[2]); - add(den, r[2], den); - square(den2, den); - square(den4, den2); - mul(den6, den4, den2); - mul(t, den6, num); - mul(t, t, den); - pow2523(t, t); - mul(t, t, num); - mul(t, t, den); - mul(t, t, den); - mul(r[0], t, den); - square(chk, r[0]); - mul(chk, chk, den); - if (neq25519(chk, num)) { - mul(r[0], r[0], I2); - } - square(chk, r[0]); - mul(chk, chk, den); - if (neq25519(chk, num)) { - return -1; - } - if (par25519(r[0]) === p3[31] >> 7) { - sub(r[0], gf0, r[0]); - } - mul(r[3], r[0], r[1]); - return 0; - } - function verify2(publicKey, message, signature) { - const t = new Uint8Array(32); - const p3 = [gf(), gf(), gf(), gf()]; - const q2 = [gf(), gf(), gf(), gf()]; - if (signature.length !== exports2.SIGNATURE_LENGTH) { - throw new Error(`ed25519: signature must be ${exports2.SIGNATURE_LENGTH} bytes`); - } - if (unpackneg(q2, publicKey)) { - return false; - } - const hs = new sha512_1.SHA512(); - hs.update(signature.subarray(0, 32)); - hs.update(publicKey); - hs.update(message); - const h5 = hs.digest(); - reduce(h5); - scalarmult(p3, q2, h5); - scalarbase(q2, signature.subarray(32)); - edadd(p3, q2); - pack(t, p3); - if (verify32(signature, t)) { - return false; - } - return true; - } - exports2.verify = verify2; - function convertPublicKeyToX25519(publicKey) { - let q2 = [gf(), gf(), gf(), gf()]; - if (unpackneg(q2, publicKey)) { - throw new Error("Ed25519: invalid public key"); - } - let a3 = gf(); - let b4 = gf(); - let y4 = q2[1]; - add(a3, gf1, y4); - sub(b4, gf1, y4); - inv25519(b4, b4); - mul(a3, a3, b4); - let z3 = new Uint8Array(32); - pack25519(z3, a3); - return z3; - } - exports2.convertPublicKeyToX25519 = convertPublicKeyToX25519; - function convertSecretKeyToX25519(secretKey) { - const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); - d3[0] &= 248; - d3[31] &= 127; - d3[31] |= 64; - const o2 = new Uint8Array(d3.subarray(0, 32)); - (0, wipe_1.wipe)(d3); - return o2; - } - exports2.convertSecretKeyToX25519 = convertSecretKeyToX25519; - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/constants.js -var JWT_IRIDIUM_ALG, JWT_IRIDIUM_TYP, JWT_DELIMITER, JWT_ENCODING, JSON_ENCODING, DATA_ENCODING, DID_DELIMITER, DID_PREFIX, DID_METHOD, MULTICODEC_ED25519_ENCODING, MULTICODEC_ED25519_BASE, MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_LENGTH, KEY_PAIR_SEED_LENGTH; -var init_constants = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/constants.js"() { - init_shim(); - JWT_IRIDIUM_ALG = "EdDSA"; - JWT_IRIDIUM_TYP = "JWT"; - JWT_DELIMITER = "."; - JWT_ENCODING = "base64url"; - JSON_ENCODING = "utf8"; - DATA_ENCODING = "utf8"; - DID_DELIMITER = ":"; - DID_PREFIX = "did"; - DID_METHOD = "key"; - MULTICODEC_ED25519_ENCODING = "base58btc"; - MULTICODEC_ED25519_BASE = "z"; - MULTICODEC_ED25519_HEADER = "K36"; - MULTICODEC_ED25519_LENGTH = 32; - KEY_PAIR_SEED_LENGTH = 32; - } -}); - -// node_modules/uint8arrays/esm/src/util/as-uint8array.js -function asUint8Array(buf) { - if (globalThis.Buffer != null) { - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - return buf; -} -var init_as_uint8array = __esm({ - "node_modules/uint8arrays/esm/src/util/as-uint8array.js"() { - init_shim(); - } -}); - -// node_modules/uint8arrays/esm/src/alloc.js -function allocUnsafe(size = 0) { - if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) { - return asUint8Array(globalThis.Buffer.allocUnsafe(size)); - } - return new Uint8Array(size); -} -var init_alloc = __esm({ - "node_modules/uint8arrays/esm/src/alloc.js"() { - init_shim(); - init_as_uint8array(); - } -}); - -// node_modules/uint8arrays/esm/src/concat.js -function concat(arrays, length2) { - if (!length2) { - length2 = arrays.reduce((acc, curr) => acc + curr.length, 0); - } - const output = allocUnsafe(length2); - let offset = 0; - for (const arr of arrays) { - output.set(arr, offset); - offset += arr.length; - } - return asUint8Array(output); -} -var init_concat = __esm({ - "node_modules/uint8arrays/esm/src/concat.js"() { - init_shim(); - init_alloc(); - init_as_uint8array(); - } -}); - -// node_modules/multiformats/esm/vendor/base-x.js -function base(ALPHABET, name2) { - if (ALPHABET.length >= 255) { - throw new TypeError("Alphabet too long"); - } - var BASE_MAP = new Uint8Array(256); - for (var j2 = 0; j2 < BASE_MAP.length; j2++) { - BASE_MAP[j2] = 255; - } - for (var i2 = 0; i2 < ALPHABET.length; i2++) { - var x3 = ALPHABET.charAt(i2); - var xc = x3.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { - throw new TypeError(x3 + " is ambiguous"); - } - BASE_MAP[xc] = i2; - } - var BASE2 = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE2) / Math.log(256); - var iFACTOR = Math.log(256) / Math.log(BASE2); - function encode5(source) { - if (source instanceof Uint8Array) - ; - else if (ArrayBuffer.isView(source)) { - source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); - } else if (Array.isArray(source)) { - source = Uint8Array.from(source); - } - if (!(source instanceof Uint8Array)) { - throw new TypeError("Expected Uint8Array"); - } - if (source.length === 0) { - return ""; - } - var zeroes = 0; - var length2 = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - var size = (pend - pbegin) * iFACTOR + 1 >>> 0; - var b58 = new Uint8Array(size); - while (pbegin !== pend) { - var carry = source[pbegin]; - var i3 = 0; - for (var it1 = size - 1; (carry !== 0 || i3 < length2) && it1 !== -1; it1--, i3++) { - carry += 256 * b58[it1] >>> 0; - b58[it1] = carry % BASE2 >>> 0; - carry = carry / BASE2 >>> 0; - } - if (carry !== 0) { - throw new Error("Non-zero carry"); - } - length2 = i3; - pbegin++; - } - var it2 = size - length2; - while (it2 !== size && b58[it2] === 0) { - it2++; - } - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { - str += ALPHABET.charAt(b58[it2]); - } - return str; - } - function decodeUnsafe(source) { - if (typeof source !== "string") { - throw new TypeError("Expected String"); - } - if (source.length === 0) { - return new Uint8Array(); - } - var psz = 0; - if (source[psz] === " ") { - return; - } - var zeroes = 0; - var length2 = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; - } - var size = (source.length - psz) * FACTOR + 1 >>> 0; - var b256 = new Uint8Array(size); - while (source[psz]) { - var carry = BASE_MAP[source.charCodeAt(psz)]; - if (carry === 255) { - return; - } - var i3 = 0; - for (var it3 = size - 1; (carry !== 0 || i3 < length2) && it3 !== -1; it3--, i3++) { - carry += BASE2 * b256[it3] >>> 0; - b256[it3] = carry % 256 >>> 0; - carry = carry / 256 >>> 0; - } - if (carry !== 0) { - throw new Error("Non-zero carry"); - } - length2 = i3; - psz++; - } - if (source[psz] === " ") { - return; - } - var it4 = size - length2; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = new Uint8Array(zeroes + (size - it4)); - var j3 = zeroes; - while (it4 !== size) { - vch[j3++] = b256[it4++]; - } - return vch; - } - function decode6(string2) { - var buffer = decodeUnsafe(string2); - if (buffer) { - return buffer; - } - throw new Error(`Non-${name2} character`); - } - return { - encode: encode5, - decodeUnsafe, - decode: decode6 - }; -} -var src, _brrp__multiformats_scope_baseX, base_x_default; -var init_base_x = __esm({ - "node_modules/multiformats/esm/vendor/base-x.js"() { - init_shim(); - src = base; - _brrp__multiformats_scope_baseX = src; - base_x_default = _brrp__multiformats_scope_baseX; - } -}); - -// node_modules/multiformats/esm/src/bytes.js -var empty, equals, coerce, fromString, toString; -var init_bytes = __esm({ - "node_modules/multiformats/esm/src/bytes.js"() { - init_shim(); - empty = new Uint8Array(0); - equals = (aa, bb) => { - if (aa === bb) - return true; - if (aa.byteLength !== bb.byteLength) { - return false; - } - for (let ii = 0; ii < aa.byteLength; ii++) { - if (aa[ii] !== bb[ii]) { - return false; - } - } - return true; - }; - coerce = (o2) => { - if (o2 instanceof Uint8Array && o2.constructor.name === "Uint8Array") - return o2; - if (o2 instanceof ArrayBuffer) - return new Uint8Array(o2); - if (ArrayBuffer.isView(o2)) { - return new Uint8Array(o2.buffer, o2.byteOffset, o2.byteLength); - } - throw new Error("Unknown type, must be binary type"); - }; - fromString = (str) => new TextEncoder().encode(str); - toString = (b4) => new TextDecoder().decode(b4); - } -}); - -// node_modules/multiformats/esm/src/bases/base.js -var Encoder, Decoder, ComposedDecoder, or, Codec, from, baseX, decode, encode, rfc4648; -var init_base = __esm({ - "node_modules/multiformats/esm/src/bases/base.js"() { - init_shim(); - init_base_x(); - init_bytes(); - Encoder = class { - constructor(name2, prefix, baseEncode) { - this.name = name2; - this.prefix = prefix; - this.baseEncode = baseEncode; - } - encode(bytes) { - if (bytes instanceof Uint8Array) { - return `${this.prefix}${this.baseEncode(bytes)}`; - } else { - throw Error("Unknown type, must be binary type"); - } - } - }; - Decoder = class { - constructor(name2, prefix, baseDecode) { - this.name = name2; - this.prefix = prefix; - if (prefix.codePointAt(0) === void 0) { - throw new Error("Invalid prefix character"); - } - this.prefixCodePoint = prefix.codePointAt(0); - this.baseDecode = baseDecode; - } - decode(text) { - if (typeof text === "string") { - if (text.codePointAt(0) !== this.prefixCodePoint) { - throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); - } - return this.baseDecode(text.slice(this.prefix.length)); - } else { - throw Error("Can only multibase decode strings"); - } - } - or(decoder) { - return or(this, decoder); - } - }; - ComposedDecoder = class { - constructor(decoders) { - this.decoders = decoders; - } - or(decoder) { - return or(this, decoder); - } - decode(input) { - const prefix = input[0]; - const decoder = this.decoders[prefix]; - if (decoder) { - return decoder.decode(input); - } else { - throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); - } - } - }; - or = (left, right) => new ComposedDecoder({ - ...left.decoders || { [left.prefix]: left }, - ...right.decoders || { [right.prefix]: right } - }); - Codec = class { - constructor(name2, prefix, baseEncode, baseDecode) { - this.name = name2; - this.prefix = prefix; - this.baseEncode = baseEncode; - this.baseDecode = baseDecode; - this.encoder = new Encoder(name2, prefix, baseEncode); - this.decoder = new Decoder(name2, prefix, baseDecode); - } - encode(input) { - return this.encoder.encode(input); - } - decode(input) { - return this.decoder.decode(input); - } - }; - from = ({ name: name2, prefix, encode: encode5, decode: decode6 }) => new Codec(name2, prefix, encode5, decode6); - baseX = ({ prefix, name: name2, alphabet: alphabet2 }) => { - const { encode: encode5, decode: decode6 } = base_x_default(alphabet2, name2); - return from({ - prefix, - name: name2, - encode: encode5, - decode: (text) => coerce(decode6(text)) - }); - }; - decode = (string2, alphabet2, bitsPerChar, name2) => { - const codes = {}; - for (let i2 = 0; i2 < alphabet2.length; ++i2) { - codes[alphabet2[i2]] = i2; - } - let end = string2.length; - while (string2[end - 1] === "=") { - --end; - } - const out = new Uint8Array(end * bitsPerChar / 8 | 0); - let bits = 0; - let buffer = 0; - let written = 0; - for (let i2 = 0; i2 < end; ++i2) { - const value = codes[string2[i2]]; - if (value === void 0) { - throw new SyntaxError(`Non-${name2} character`); - } - buffer = buffer << bitsPerChar | value; - bits += bitsPerChar; - if (bits >= 8) { - bits -= 8; - out[written++] = 255 & buffer >> bits; - } - } - if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { - throw new SyntaxError("Unexpected end of data"); - } - return out; - }; - encode = (data, alphabet2, bitsPerChar) => { - const pad = alphabet2[alphabet2.length - 1] === "="; - const mask = (1 << bitsPerChar) - 1; - let out = ""; - let bits = 0; - let buffer = 0; - for (let i2 = 0; i2 < data.length; ++i2) { - buffer = buffer << 8 | data[i2]; - bits += 8; - while (bits > bitsPerChar) { - bits -= bitsPerChar; - out += alphabet2[mask & buffer >> bits]; - } - } - if (bits) { - out += alphabet2[mask & buffer << bitsPerChar - bits]; - } - if (pad) { - while (out.length * bitsPerChar & 7) { - out += "="; - } - } - return out; - }; - rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) => { - return from({ - prefix, - name: name2, - encode(input) { - return encode(input, alphabet2, bitsPerChar); - }, - decode(input) { - return decode(input, alphabet2, bitsPerChar, name2); - } - }); - }; - } -}); - -// node_modules/multiformats/esm/src/bases/identity.js -var identity_exports = {}; -__export(identity_exports, { - identity: () => identity -}); -var identity; -var init_identity = __esm({ - "node_modules/multiformats/esm/src/bases/identity.js"() { - init_shim(); - init_base(); - init_bytes(); - identity = from({ - prefix: "\0", - name: "identity", - encode: (buf) => toString(buf), - decode: (str) => fromString(str) - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base2.js -var base2_exports = {}; -__export(base2_exports, { - base2: () => base2 -}); -var base2; -var init_base2 = __esm({ - "node_modules/multiformats/esm/src/bases/base2.js"() { - init_shim(); - init_base(); - base2 = rfc4648({ - prefix: "0", - name: "base2", - alphabet: "01", - bitsPerChar: 1 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base8.js -var base8_exports = {}; -__export(base8_exports, { - base8: () => base8 -}); -var base8; -var init_base8 = __esm({ - "node_modules/multiformats/esm/src/bases/base8.js"() { - init_shim(); - init_base(); - base8 = rfc4648({ - prefix: "7", - name: "base8", - alphabet: "01234567", - bitsPerChar: 3 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base10.js -var base10_exports = {}; -__export(base10_exports, { - base10: () => base10 -}); -var base10; -var init_base10 = __esm({ - "node_modules/multiformats/esm/src/bases/base10.js"() { - init_shim(); - init_base(); - base10 = baseX({ - prefix: "9", - name: "base10", - alphabet: "0123456789" - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base16.js -var base16_exports = {}; -__export(base16_exports, { - base16: () => base16, - base16upper: () => base16upper -}); -var base16, base16upper; -var init_base16 = __esm({ - "node_modules/multiformats/esm/src/bases/base16.js"() { - init_shim(); - init_base(); - base16 = rfc4648({ - prefix: "f", - name: "base16", - alphabet: "0123456789abcdef", - bitsPerChar: 4 - }); - base16upper = rfc4648({ - prefix: "F", - name: "base16upper", - alphabet: "0123456789ABCDEF", - bitsPerChar: 4 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base32.js -var base32_exports = {}; -__export(base32_exports, { - base32: () => base32, - base32hex: () => base32hex, - base32hexpad: () => base32hexpad, - base32hexpadupper: () => base32hexpadupper, - base32hexupper: () => base32hexupper, - base32pad: () => base32pad, - base32padupper: () => base32padupper, - base32upper: () => base32upper, - base32z: () => base32z -}); -var base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z; -var init_base32 = __esm({ - "node_modules/multiformats/esm/src/bases/base32.js"() { - init_shim(); - init_base(); - base32 = rfc4648({ - prefix: "b", - name: "base32", - alphabet: "abcdefghijklmnopqrstuvwxyz234567", - bitsPerChar: 5 - }); - base32upper = rfc4648({ - prefix: "B", - name: "base32upper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - bitsPerChar: 5 - }); - base32pad = rfc4648({ - prefix: "c", - name: "base32pad", - alphabet: "abcdefghijklmnopqrstuvwxyz234567=", - bitsPerChar: 5 - }); - base32padupper = rfc4648({ - prefix: "C", - name: "base32padupper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", - bitsPerChar: 5 - }); - base32hex = rfc4648({ - prefix: "v", - name: "base32hex", - alphabet: "0123456789abcdefghijklmnopqrstuv", - bitsPerChar: 5 - }); - base32hexupper = rfc4648({ - prefix: "V", - name: "base32hexupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", - bitsPerChar: 5 - }); - base32hexpad = rfc4648({ - prefix: "t", - name: "base32hexpad", - alphabet: "0123456789abcdefghijklmnopqrstuv=", - bitsPerChar: 5 - }); - base32hexpadupper = rfc4648({ - prefix: "T", - name: "base32hexpadupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", - bitsPerChar: 5 - }); - base32z = rfc4648({ - prefix: "h", - name: "base32z", - alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", - bitsPerChar: 5 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base36.js -var base36_exports = {}; -__export(base36_exports, { - base36: () => base36, - base36upper: () => base36upper -}); -var base36, base36upper; -var init_base36 = __esm({ - "node_modules/multiformats/esm/src/bases/base36.js"() { - init_shim(); - init_base(); - base36 = baseX({ - prefix: "k", - name: "base36", - alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" - }); - base36upper = baseX({ - prefix: "K", - name: "base36upper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base58.js -var base58_exports = {}; -__export(base58_exports, { - base58btc: () => base58btc, - base58flickr: () => base58flickr -}); -var base58btc, base58flickr; -var init_base58 = __esm({ - "node_modules/multiformats/esm/src/bases/base58.js"() { - init_shim(); - init_base(); - base58btc = baseX({ - name: "base58btc", - prefix: "z", - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" - }); - base58flickr = baseX({ - name: "base58flickr", - prefix: "Z", - alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base64.js -var base64_exports = {}; -__export(base64_exports, { - base64: () => base64, - base64pad: () => base64pad, - base64url: () => base64url, - base64urlpad: () => base64urlpad -}); -var base64, base64pad, base64url, base64urlpad; -var init_base64 = __esm({ - "node_modules/multiformats/esm/src/bases/base64.js"() { - init_shim(); - init_base(); - base64 = rfc4648({ - prefix: "m", - name: "base64", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", - bitsPerChar: 6 - }); - base64pad = rfc4648({ - prefix: "M", - name: "base64pad", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", - bitsPerChar: 6 - }); - base64url = rfc4648({ - prefix: "u", - name: "base64url", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", - bitsPerChar: 6 - }); - base64urlpad = rfc4648({ - prefix: "U", - name: "base64urlpad", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", - bitsPerChar: 6 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base256emoji.js -var base256emoji_exports = {}; -__export(base256emoji_exports, { - base256emoji: () => base256emoji -}); -function encode2(data) { - return data.reduce((p3, c4) => { - p3 += alphabetBytesToChars[c4]; - return p3; - }, ""); -} -function decode2(str) { - const byts = []; - for (const char of str) { - const byt = alphabetCharsToBytes[char.codePointAt(0)]; - if (byt === void 0) { - throw new Error(`Non-base256emoji character: ${char}`); - } - byts.push(byt); - } - return new Uint8Array(byts); -} -var alphabet, alphabetBytesToChars, alphabetCharsToBytes, base256emoji; -var init_base256emoji = __esm({ - "node_modules/multiformats/esm/src/bases/base256emoji.js"() { - init_shim(); - init_base(); - alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); - alphabetBytesToChars = alphabet.reduce((p3, c4, i2) => { - p3[i2] = c4; - return p3; - }, []); - alphabetCharsToBytes = alphabet.reduce((p3, c4, i2) => { - p3[c4.codePointAt(0)] = i2; - return p3; - }, []); - base256emoji = from({ - prefix: "\u{1F680}", - name: "base256emoji", - encode: encode2, - decode: decode2 - }); - } -}); - -// node_modules/multiformats/esm/vendor/varint.js -function encode3(num, out, offset) { - out = out || []; - offset = offset || 0; - var oldOffset = offset; - while (num >= INT) { - out[offset++] = num & 255 | MSB; - num /= 128; - } - while (num & MSBALL) { - out[offset++] = num & 255 | MSB; - num >>>= 7; - } - out[offset] = num | 0; - encode3.bytes = offset - oldOffset + 1; - return out; -} -function read(buf, offset) { - var res = 0, offset = offset || 0, shift = 0, counter = offset, b4, l4 = buf.length; - do { - if (counter >= l4) { - read.bytes = 0; - throw new RangeError("Could not decode varint"); - } - b4 = buf[counter++]; - res += shift < 28 ? (b4 & REST$1) << shift : (b4 & REST$1) * Math.pow(2, shift); - shift += 7; - } while (b4 >= MSB$1); - read.bytes = counter - offset; - return res; -} -var encode_1, MSB, REST, MSBALL, INT, decode3, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default; -var init_varint = __esm({ - "node_modules/multiformats/esm/vendor/varint.js"() { - init_shim(); - encode_1 = encode3; - MSB = 128; - REST = 127; - MSBALL = ~REST; - INT = Math.pow(2, 31); - decode3 = read; - MSB$1 = 128; - REST$1 = 127; - N1 = Math.pow(2, 7); - N2 = Math.pow(2, 14); - N3 = Math.pow(2, 21); - N4 = Math.pow(2, 28); - N5 = Math.pow(2, 35); - N6 = Math.pow(2, 42); - N7 = Math.pow(2, 49); - N8 = Math.pow(2, 56); - N9 = Math.pow(2, 63); - length = function(value) { - return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; - }; - varint = { - encode: encode_1, - decode: decode3, - encodingLength: length - }; - _brrp_varint = varint; - varint_default = _brrp_varint; - } -}); - -// node_modules/multiformats/esm/src/varint.js -var decode4, encodeTo, encodingLength; -var init_varint2 = __esm({ - "node_modules/multiformats/esm/src/varint.js"() { - init_shim(); - init_varint(); - decode4 = (data, offset = 0) => { - const code2 = varint_default.decode(data, offset); - return [ - code2, - varint_default.decode.bytes - ]; - }; - encodeTo = (int, target, offset = 0) => { - varint_default.encode(int, target, offset); - return target; - }; - encodingLength = (int) => { - return varint_default.encodingLength(int); - }; - } -}); - -// node_modules/multiformats/esm/src/hashes/digest.js -var create, decode5, equals2, Digest; -var init_digest = __esm({ - "node_modules/multiformats/esm/src/hashes/digest.js"() { - init_shim(); - init_bytes(); - init_varint2(); - create = (code2, digest2) => { - const size = digest2.byteLength; - const sizeOffset = encodingLength(code2); - const digestOffset = sizeOffset + encodingLength(size); - const bytes = new Uint8Array(digestOffset + size); - encodeTo(code2, bytes, 0); - encodeTo(size, bytes, sizeOffset); - bytes.set(digest2, digestOffset); - return new Digest(code2, size, digest2, bytes); - }; - decode5 = (multihash) => { - const bytes = coerce(multihash); - const [code2, sizeOffset] = decode4(bytes); - const [size, digestOffset] = decode4(bytes.subarray(sizeOffset)); - const digest2 = bytes.subarray(sizeOffset + digestOffset); - if (digest2.byteLength !== size) { - throw new Error("Incorrect length"); - } - return new Digest(code2, size, digest2, bytes); - }; - equals2 = (a3, b4) => { - if (a3 === b4) { - return true; - } else { - return a3.code === b4.code && a3.size === b4.size && equals(a3.bytes, b4.bytes); - } - }; - Digest = class { - constructor(code2, size, digest2, bytes) { - this.code = code2; - this.size = size; - this.digest = digest2; - this.bytes = bytes; - } - }; - } -}); - -// node_modules/multiformats/esm/src/hashes/hasher.js -var from2, Hasher; -var init_hasher = __esm({ - "node_modules/multiformats/esm/src/hashes/hasher.js"() { - init_shim(); - init_digest(); - from2 = ({ name: name2, code: code2, encode: encode5 }) => new Hasher(name2, code2, encode5); - Hasher = class { - constructor(name2, code2, encode5) { - this.name = name2; - this.code = code2; - this.encode = encode5; - } - digest(input) { - if (input instanceof Uint8Array) { - const result = this.encode(input); - return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2)); - } else { - throw Error("Unknown type, must be binary type"); - } - } - }; - } -}); - -// node_modules/multiformats/esm/src/hashes/sha2-browser.js -var sha2_browser_exports = {}; -__export(sha2_browser_exports, { - sha256: () => sha256, - sha512: () => sha512 -}); -var sha, sha256, sha512; -var init_sha2_browser = __esm({ - "node_modules/multiformats/esm/src/hashes/sha2-browser.js"() { - init_shim(); - init_hasher(); - sha = (name2) => async (data) => new Uint8Array(await crypto.subtle.digest(name2, data)); - sha256 = from2({ - name: "sha2-256", - code: 18, - encode: sha("SHA-256") - }); - sha512 = from2({ - name: "sha2-512", - code: 19, - encode: sha("SHA-512") - }); - } -}); - -// node_modules/multiformats/esm/src/hashes/identity.js -var identity_exports2 = {}; -__export(identity_exports2, { - identity: () => identity2 -}); -var code, name, encode4, digest, identity2; -var init_identity2 = __esm({ - "node_modules/multiformats/esm/src/hashes/identity.js"() { - init_shim(); - init_bytes(); - init_digest(); - code = 0; - name = "identity"; - encode4 = coerce; - digest = (input) => create(code, encode4(input)); - identity2 = { - code, - name, - encode: encode4, - digest - }; - } -}); - -// node_modules/multiformats/esm/src/codecs/raw.js -var init_raw = __esm({ - "node_modules/multiformats/esm/src/codecs/raw.js"() { - init_shim(); - init_bytes(); - } -}); - -// node_modules/multiformats/esm/src/codecs/json.js -var textEncoder, textDecoder; -var init_json = __esm({ - "node_modules/multiformats/esm/src/codecs/json.js"() { - init_shim(); - textEncoder = new TextEncoder(); - textDecoder = new TextDecoder(); - } -}); - -// node_modules/multiformats/esm/src/cid.js -var CID, parseCIDtoBytes, toStringV0, toStringV1, DAG_PB_CODE, SHA_256_CODE, encodeCID, cidSymbol, readonly, hidden, version, deprecate, IS_CID_DEPRECATION; -var init_cid = __esm({ - "node_modules/multiformats/esm/src/cid.js"() { - init_shim(); - init_varint2(); - init_digest(); - init_base58(); - init_base32(); - init_bytes(); - CID = class _CID { - constructor(version2, code2, multihash, bytes) { - this.code = code2; - this.version = version2; - this.multihash = multihash; - this.bytes = bytes; - this.byteOffset = bytes.byteOffset; - this.byteLength = bytes.byteLength; - this.asCID = this; - this._baseCache = /* @__PURE__ */ new Map(); - Object.defineProperties(this, { - byteOffset: hidden, - byteLength: hidden, - code: readonly, - version: readonly, - multihash: readonly, - bytes: readonly, - _baseCache: hidden, - asCID: hidden - }); - } - toV0() { - switch (this.version) { - case 0: { - return this; - } - default: { - const { code: code2, multihash } = this; - if (code2 !== DAG_PB_CODE) { - throw new Error("Cannot convert a non dag-pb CID to CIDv0"); - } - if (multihash.code !== SHA_256_CODE) { - throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); - } - return _CID.createV0(multihash); - } - } - } - toV1() { - switch (this.version) { - case 0: { - const { code: code2, digest: digest2 } = this.multihash; - const multihash = create(code2, digest2); - return _CID.createV1(this.code, multihash); - } - case 1: { - return this; - } - default: { - throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); - } - } - } - equals(other) { - return other && this.code === other.code && this.version === other.version && equals2(this.multihash, other.multihash); - } - toString(base3) { - const { bytes, version: version2, _baseCache } = this; - switch (version2) { - case 0: - return toStringV0(bytes, _baseCache, base3 || base58btc.encoder); - default: - return toStringV1(bytes, _baseCache, base3 || base32.encoder); - } - } - toJSON() { - return { - code: this.code, - version: this.version, - hash: this.multihash.bytes - }; - } - get [Symbol.toStringTag]() { - return "CID"; - } - [Symbol.for("nodejs.util.inspect.custom")]() { - return "CID(" + this.toString() + ")"; - } - static isCID(value) { - deprecate(/^0\.0/, IS_CID_DEPRECATION); - return !!(value && (value[cidSymbol] || value.asCID === value)); - } - get toBaseEncodedString() { - throw new Error("Deprecated, use .toString()"); - } - get codec() { - throw new Error('"codec" property is deprecated, use integer "code" property instead'); - } - get buffer() { - throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); - } - get multibaseName() { - throw new Error('"multibaseName" property is deprecated'); - } - get prefix() { - throw new Error('"prefix" property is deprecated'); - } - static asCID(value) { - if (value instanceof _CID) { - return value; - } else if (value != null && value.asCID === value) { - const { version: version2, code: code2, multihash, bytes } = value; - return new _CID(version2, code2, multihash, bytes || encodeCID(version2, code2, multihash.bytes)); - } else if (value != null && value[cidSymbol] === true) { - const { version: version2, multihash, code: code2 } = value; - const digest2 = decode5(multihash); - return _CID.create(version2, code2, digest2); - } else { - return null; - } - } - static create(version2, code2, digest2) { - if (typeof code2 !== "number") { - throw new Error("String codecs are no longer supported"); - } - switch (version2) { - case 0: { - if (code2 !== DAG_PB_CODE) { - throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); - } else { - return new _CID(version2, code2, digest2, digest2.bytes); - } - } - case 1: { - const bytes = encodeCID(version2, code2, digest2.bytes); - return new _CID(version2, code2, digest2, bytes); - } - default: { - throw new Error("Invalid version"); - } - } - } - static createV0(digest2) { - return _CID.create(0, DAG_PB_CODE, digest2); - } - static createV1(code2, digest2) { - return _CID.create(1, code2, digest2); - } - static decode(bytes) { - const [cid, remainder] = _CID.decodeFirst(bytes); - if (remainder.length) { - throw new Error("Incorrect length"); - } - return cid; - } - static decodeFirst(bytes) { - const specs = _CID.inspectBytes(bytes); - const prefixSize = specs.size - specs.multihashSize; - const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); - if (multihashBytes.byteLength !== specs.multihashSize) { - throw new Error("Incorrect length"); - } - const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); - const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); - const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2); - return [ - cid, - bytes.subarray(specs.size) - ]; - } - static inspectBytes(initialBytes) { - let offset = 0; - const next = () => { - const [i2, length2] = decode4(initialBytes.subarray(offset)); - offset += length2; - return i2; - }; - let version2 = next(); - let codec = DAG_PB_CODE; - if (version2 === 18) { - version2 = 0; - offset = 0; - } else if (version2 === 1) { - codec = next(); - } - if (version2 !== 0 && version2 !== 1) { - throw new RangeError(`Invalid CID version ${version2}`); - } - const prefixSize = offset; - const multihashCode = next(); - const digestSize = next(); - const size = offset + digestSize; - const multihashSize = size - prefixSize; - return { - version: version2, - codec, - multihashCode, - digestSize, - multihashSize, - size - }; - } - static parse(source, base3) { - const [prefix, bytes] = parseCIDtoBytes(source, base3); - const cid = _CID.decode(bytes); - cid._baseCache.set(prefix, source); - return cid; - } - }; - parseCIDtoBytes = (source, base3) => { - switch (source[0]) { - case "Q": { - const decoder = base3 || base58btc; - return [ - base58btc.prefix, - decoder.decode(`${base58btc.prefix}${source}`) - ]; - } - case base58btc.prefix: { - const decoder = base3 || base58btc; - return [ - base58btc.prefix, - decoder.decode(source) - ]; - } - case base32.prefix: { - const decoder = base3 || base32; - return [ - base32.prefix, - decoder.decode(source) - ]; - } - default: { - if (base3 == null) { - throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); - } - return [ - source[0], - base3.decode(source) - ]; - } - } - }; - toStringV0 = (bytes, cache, base3) => { - const { prefix } = base3; - if (prefix !== base58btc.prefix) { - throw Error(`Cannot string encode V0 in ${base3.name} encoding`); - } - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base3.encode(bytes).slice(1); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; - } - }; - toStringV1 = (bytes, cache, base3) => { - const { prefix } = base3; - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base3.encode(bytes); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; - } - }; - DAG_PB_CODE = 112; - SHA_256_CODE = 18; - encodeCID = (version2, code2, multihash) => { - const codeOffset = encodingLength(version2); - const hashOffset = codeOffset + encodingLength(code2); - const bytes = new Uint8Array(hashOffset + multihash.byteLength); - encodeTo(version2, bytes, 0); - encodeTo(code2, bytes, codeOffset); - bytes.set(multihash, hashOffset); - return bytes; - }; - cidSymbol = Symbol.for("@ipld/js-cid/CID"); - readonly = { - writable: false, - configurable: false, - enumerable: true - }; - hidden = { - writable: false, - enumerable: false, - configurable: false - }; - version = "0.0.0-dev"; - deprecate = (range, message) => { - if (range.test(version)) { - console.warn(message); - } else { - throw new Error(message); - } - }; - IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. -Following code pattern: - -if (CID.isCID(value)) { - doSomethingWithCID(value) -} - -Is replaced with: - -const cid = CID.asCID(value) -if (cid) { - // Make sure to use cid instead of value - doSomethingWithCID(cid) -} -`; - } -}); - -// node_modules/multiformats/esm/src/index.js -var init_src = __esm({ - "node_modules/multiformats/esm/src/index.js"() { - init_shim(); - init_cid(); - init_varint2(); - init_bytes(); - init_hasher(); - init_digest(); - } -}); - -// node_modules/multiformats/esm/src/basics.js -var bases, hashes; -var init_basics = __esm({ - "node_modules/multiformats/esm/src/basics.js"() { - init_shim(); - init_identity(); - init_base2(); - init_base8(); - init_base10(); - init_base16(); - init_base32(); - init_base36(); - init_base58(); - init_base64(); - init_base256emoji(); - init_sha2_browser(); - init_identity2(); - init_raw(); - init_json(); - init_src(); - bases = { - ...identity_exports, - ...base2_exports, - ...base8_exports, - ...base10_exports, - ...base16_exports, - ...base32_exports, - ...base36_exports, - ...base58_exports, - ...base64_exports, - ...base256emoji_exports - }; - hashes = { - ...sha2_browser_exports, - ...identity_exports2 - }; - } -}); - -// node_modules/uint8arrays/esm/src/util/bases.js -function createCodec(name2, prefix, encode5, decode6) { - return { - name: name2, - prefix, - encoder: { - name: name2, - prefix, - encode: encode5 - }, - decoder: { decode: decode6 } - }; -} -var string, ascii, BASES, bases_default; -var init_bases = __esm({ - "node_modules/uint8arrays/esm/src/util/bases.js"() { - init_shim(); - init_basics(); - init_alloc(); - string = createCodec("utf8", "u", (buf) => { - const decoder = new TextDecoder("utf8"); - return "u" + decoder.decode(buf); - }, (str) => { - const encoder = new TextEncoder(); - return encoder.encode(str.substring(1)); - }); - ascii = createCodec("ascii", "a", (buf) => { - let string2 = "a"; - for (let i2 = 0; i2 < buf.length; i2++) { - string2 += String.fromCharCode(buf[i2]); - } - return string2; - }, (str) => { - str = str.substring(1); - const buf = allocUnsafe(str.length); - for (let i2 = 0; i2 < str.length; i2++) { - buf[i2] = str.charCodeAt(i2); - } - return buf; - }); - BASES = { - utf8: string, - "utf-8": string, - hex: bases.base16, - latin1: ascii, - ascii, - binary: ascii, - ...bases - }; - bases_default = BASES; - } -}); - -// node_modules/uint8arrays/esm/src/to-string.js -function toString2(array, encoding = "utf8") { - const base3 = bases_default[encoding]; - if (!base3) { - throw new Error(`Unsupported encoding "${encoding}"`); - } - if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { - return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); - } - return base3.encoder.encode(array).substring(1); -} -var init_to_string = __esm({ - "node_modules/uint8arrays/esm/src/to-string.js"() { - init_shim(); - init_bases(); - } -}); - -// node_modules/uint8arrays/esm/src/from-string.js -function fromString2(string2, encoding = "utf8") { - const base3 = bases_default[encoding]; - if (!base3) { - throw new Error(`Unsupported encoding "${encoding}"`); - } - if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { - return asUint8Array(globalThis.Buffer.from(string2, "utf-8")); - } - return base3.decoder.decode(`${base3.prefix}${string2}`); -} -var init_from_string = __esm({ - "node_modules/uint8arrays/esm/src/from-string.js"() { - init_shim(); - init_bases(); - init_as_uint8array(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/utils.js -function decodeJSON(str) { - return safeJsonParse(toString2(fromString2(str, JWT_ENCODING), JSON_ENCODING)); -} -function encodeJSON(val) { - return toString2(fromString2(safeJsonStringify(val), JSON_ENCODING), JWT_ENCODING); -} -function encodeIss(publicKey) { - const header = fromString2(MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_ENCODING); - const multicodec = MULTICODEC_ED25519_BASE + toString2(concat([header, publicKey]), MULTICODEC_ED25519_ENCODING); - return [DID_PREFIX, DID_METHOD, multicodec].join(DID_DELIMITER); -} -function decodeIss(issuer) { - const [prefix, method, multicodec] = issuer.split(DID_DELIMITER); - if (prefix !== DID_PREFIX || method !== DID_METHOD) { - throw new Error(`Issuer must be a DID with method "key"`); - } - const base3 = multicodec.slice(0, 1); - if (base3 !== MULTICODEC_ED25519_BASE) { - throw new Error(`Issuer must be a key in mulicodec format`); - } - const bytes = fromString2(multicodec.slice(1), MULTICODEC_ED25519_ENCODING); - const type = toString2(bytes.slice(0, 2), MULTICODEC_ED25519_ENCODING); - if (type !== MULTICODEC_ED25519_HEADER) { - throw new Error(`Issuer must be a public key with type "Ed25519"`); - } - const publicKey = bytes.slice(2); - if (publicKey.length !== MULTICODEC_ED25519_LENGTH) { - throw new Error(`Issuer must be a public key with length 32 bytes`); - } - return publicKey; -} -function encodeSig(bytes) { - return toString2(bytes, JWT_ENCODING); -} -function decodeSig(encoded) { - return fromString2(encoded, JWT_ENCODING); -} -function encodeData(params) { - return fromString2([encodeJSON(params.header), encodeJSON(params.payload)].join(JWT_DELIMITER), DATA_ENCODING); -} -function decodeData(data) { - const params = toString2(data, DATA_ENCODING).split(JWT_DELIMITER); - const header = decodeJSON(params[0]); - const payload = decodeJSON(params[1]); - return { header, payload }; -} -function encodeJWT(params) { - return [ - encodeJSON(params.header), - encodeJSON(params.payload), - encodeSig(params.signature) - ].join(JWT_DELIMITER); -} -function decodeJWT(jwt) { - const params = jwt.split(JWT_DELIMITER); - const header = decodeJSON(params[0]); - const payload = decodeJSON(params[1]); - const signature = decodeSig(params[2]); - const data = fromString2(params.slice(0, 2).join(JWT_DELIMITER), DATA_ENCODING); - return { header, payload, signature, data }; -} -var init_utils = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/utils.js"() { - init_shim(); - init_concat(); - init_to_string(); - init_from_string(); - init_esm(); - init_constants(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/api.js -function generateKeyPair(seed = (0, import_random.randomBytes)(KEY_PAIR_SEED_LENGTH)) { - return ed25519.generateKeyPairFromSeed(seed); -} -async function signJWT(sub, aud, ttl, keyPair, iat = (0, import_time.fromMiliseconds)(Date.now())) { - const header = { alg: JWT_IRIDIUM_ALG, typ: JWT_IRIDIUM_TYP }; - const iss = encodeIss(keyPair.publicKey); - const exp = iat + ttl; - const payload = { iss, sub, aud, iat, exp }; - const data = encodeData({ header, payload }); - const signature = ed25519.sign(keyPair.secretKey, data); - return encodeJWT({ header, payload, signature }); -} -async function verifyJWT(jwt) { - const { header, payload, data, signature } = decodeJWT(jwt); - if (header.alg !== JWT_IRIDIUM_ALG || header.typ !== JWT_IRIDIUM_TYP) { - throw new Error("JWT must use EdDSA algorithm"); - } - const publicKey = decodeIss(payload.iss); - return ed25519.verify(publicKey, data, signature); -} -var ed25519, import_random, import_time; -var init_api = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/api.js"() { - init_shim(); - ed25519 = __toESM(require_ed25519()); - import_random = __toESM(require_random()); - import_time = __toESM(require_cjs()); - init_constants(); - init_utils(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/types.js -var init_types = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/types.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/index.js -var esm_exports3 = {}; -__export(esm_exports3, { - DATA_ENCODING: () => DATA_ENCODING, - DID_DELIMITER: () => DID_DELIMITER, - DID_METHOD: () => DID_METHOD, - DID_PREFIX: () => DID_PREFIX, - JSON_ENCODING: () => JSON_ENCODING, - JWT_DELIMITER: () => JWT_DELIMITER, - JWT_ENCODING: () => JWT_ENCODING, - JWT_IRIDIUM_ALG: () => JWT_IRIDIUM_ALG, - JWT_IRIDIUM_TYP: () => JWT_IRIDIUM_TYP, - KEY_PAIR_SEED_LENGTH: () => KEY_PAIR_SEED_LENGTH, - MULTICODEC_ED25519_BASE: () => MULTICODEC_ED25519_BASE, - MULTICODEC_ED25519_ENCODING: () => MULTICODEC_ED25519_ENCODING, - MULTICODEC_ED25519_HEADER: () => MULTICODEC_ED25519_HEADER, - MULTICODEC_ED25519_LENGTH: () => MULTICODEC_ED25519_LENGTH, - decodeData: () => decodeData, - decodeIss: () => decodeIss, - decodeJSON: () => decodeJSON, - decodeJWT: () => decodeJWT, - decodeSig: () => decodeSig, - encodeData: () => encodeData, - encodeIss: () => encodeIss, - encodeJSON: () => encodeJSON, - encodeJWT: () => encodeJWT, - encodeSig: () => encodeSig, - generateKeyPair: () => generateKeyPair, - signJWT: () => signJWT, - verifyJWT: () => verifyJWT -}); -var init_esm3 = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/index.js"() { - init_shim(); - init_api(); - init_constants(); - init_types(); - init_utils(); - } -}); - -// node_modules/detect-browser/index.js -var require_detect_browser = __commonJS({ - "node_modules/detect-browser/index.js"(exports2) { - "use strict"; - init_shim(); - var __spreadArray = exports2 && exports2.__spreadArray || function(to, from3, pack) { - if (pack || arguments.length === 2) - for (var i2 = 0, l4 = from3.length, ar; i2 < l4; i2++) { - if (ar || !(i2 in from3)) { - if (!ar) - ar = Array.prototype.slice.call(from3, 0, i2); - ar[i2] = from3[i2]; - } - } - return to.concat(ar || Array.prototype.slice.call(from3)); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getNodeVersion = exports2.detectOS = exports2.parseUserAgent = exports2.browserName = exports2.detect = exports2.ReactNativeInfo = exports2.BotInfo = exports2.SearchBotDeviceInfo = exports2.NodeInfo = exports2.BrowserInfo = void 0; - var BrowserInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function BrowserInfo2(name2, version2, os) { - this.name = name2; - this.version = version2; - this.os = os; - this.type = "browser"; - } - return BrowserInfo2; - }() - ); - exports2.BrowserInfo = BrowserInfo; - var NodeInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function NodeInfo2(version2) { - this.version = version2; - this.type = "node"; - this.name = "node"; - this.os = import_process.default.platform; - } - return NodeInfo2; - }() - ); - exports2.NodeInfo = NodeInfo; - var SearchBotDeviceInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function SearchBotDeviceInfo2(name2, version2, os, bot) { - this.name = name2; - this.version = version2; - this.os = os; - this.bot = bot; - this.type = "bot-device"; - } - return SearchBotDeviceInfo2; - }() - ); - exports2.SearchBotDeviceInfo = SearchBotDeviceInfo; - var BotInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function BotInfo2() { - this.type = "bot"; - this.bot = true; - this.name = "bot"; - this.version = null; - this.os = null; - } - return BotInfo2; - }() - ); - exports2.BotInfo = BotInfo; - var ReactNativeInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function ReactNativeInfo2() { - this.type = "react-native"; - this.name = "react-native"; - this.version = null; - this.os = null; - } - return ReactNativeInfo2; - }() - ); - exports2.ReactNativeInfo = ReactNativeInfo; - var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/; - var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/; - var REQUIRED_VERSION_PARTS = 3; - var userAgentRules = [ - ["aol", /AOLShield\/([0-9\._]+)/], - ["edge", /Edge\/([0-9\._]+)/], - ["edge-ios", /EdgiOS\/([0-9\._]+)/], - ["yandexbrowser", /YaBrowser\/([0-9\._]+)/], - ["kakaotalk", /KAKAOTALK\s([0-9\.]+)/], - ["samsung", /SamsungBrowser\/([0-9\.]+)/], - ["silk", /\bSilk\/([0-9._-]+)\b/], - ["miui", /MiuiBrowser\/([0-9\.]+)$/], - ["beaker", /BeakerBrowser\/([0-9\.]+)/], - ["edge-chromium", /EdgA?\/([0-9\.]+)/], - [ - "chromium-webview", - /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ - ], - ["chrome", /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], - ["phantomjs", /PhantomJS\/([0-9\.]+)(:?\s|$)/], - ["crios", /CriOS\/([0-9\.]+)(:?\s|$)/], - ["firefox", /Firefox\/([0-9\.]+)(?:\s|$)/], - ["fxios", /FxiOS\/([0-9\.]+)/], - ["opera-mini", /Opera Mini.*Version\/([0-9\.]+)/], - ["opera", /Opera\/([0-9\.]+)(?:\s|$)/], - ["opera", /OPR\/([0-9\.]+)(:?\s|$)/], - ["pie", /^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/], - ["pie", /^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/], - ["netfront", /^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/], - ["ie", /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], - ["ie", /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], - ["ie", /MSIE\s(7\.0)/], - ["bb10", /BB10;\sTouch.*Version\/([0-9\.]+)/], - ["android", /Android\s([0-9\.]+)/], - ["ios", /Version\/([0-9\._]+).*Mobile.*Safari.*/], - ["safari", /Version\/([0-9\._]+).*Safari/], - ["facebook", /FB[AS]V\/([0-9\.]+)/], - ["instagram", /Instagram\s([0-9\.]+)/], - ["ios-webview", /AppleWebKit\/([0-9\.]+).*Mobile/], - ["ios-webview", /AppleWebKit\/([0-9\.]+).*Gecko\)$/], - ["curl", /^curl\/([0-9\.]+)$/], - ["searchbot", SEARCHBOX_UA_REGEX] - ]; - var operatingSystemRules = [ - ["iOS", /iP(hone|od|ad)/], - ["Android OS", /Android/], - ["BlackBerry OS", /BlackBerry|BB10/], - ["Windows Mobile", /IEMobile/], - ["Amazon OS", /Kindle/], - ["Windows 3.11", /Win16/], - ["Windows 95", /(Windows 95)|(Win95)|(Windows_95)/], - ["Windows 98", /(Windows 98)|(Win98)/], - ["Windows 2000", /(Windows NT 5.0)|(Windows 2000)/], - ["Windows XP", /(Windows NT 5.1)|(Windows XP)/], - ["Windows Server 2003", /(Windows NT 5.2)/], - ["Windows Vista", /(Windows NT 6.0)/], - ["Windows 7", /(Windows NT 6.1)/], - ["Windows 8", /(Windows NT 6.2)/], - ["Windows 8.1", /(Windows NT 6.3)/], - ["Windows 10", /(Windows NT 10.0)/], - ["Windows ME", /Windows ME/], - ["Windows CE", /Windows CE|WinCE|Microsoft Pocket Internet Explorer/], - ["Open BSD", /OpenBSD/], - ["Sun OS", /SunOS/], - ["Chrome OS", /CrOS/], - ["Linux", /(Linux)|(X11)/], - ["Mac OS", /(Mac_PowerPC)|(Macintosh)/], - ["QNX", /QNX/], - ["BeOS", /BeOS/], - ["OS/2", /OS\/2/] - ]; - function detect(userAgent) { - if (!!userAgent) { - return parseUserAgent(userAgent); - } - if (typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative") { - return new ReactNativeInfo(); - } - if (typeof navigator !== "undefined") { - return parseUserAgent(navigator.userAgent); - } - return getNodeVersion(); - } - exports2.detect = detect; - function matchUserAgent(ua) { - return ua !== "" && userAgentRules.reduce(function(matched, _a) { - var browser = _a[0], regex = _a[1]; - if (matched) { - return matched; - } - var uaMatch = regex.exec(ua); - return !!uaMatch && [browser, uaMatch]; - }, false); - } - function browserName(ua) { - var data = matchUserAgent(ua); - return data ? data[0] : null; - } - exports2.browserName = browserName; - function parseUserAgent(ua) { - var matchedRule = matchUserAgent(ua); - if (!matchedRule) { - return null; - } - var name2 = matchedRule[0], match = matchedRule[1]; - if (name2 === "searchbot") { - return new BotInfo(); - } - var versionParts = match[1] && match[1].split(".").join("_").split("_").slice(0, 3); - if (versionParts) { - if (versionParts.length < REQUIRED_VERSION_PARTS) { - versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true); - } - } else { - versionParts = []; - } - var version2 = versionParts.join("."); - var os = detectOS(ua); - var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua); - if (searchBotMatch && searchBotMatch[1]) { - return new SearchBotDeviceInfo(name2, version2, os, searchBotMatch[1]); - } - return new BrowserInfo(name2, version2, os); - } - exports2.parseUserAgent = parseUserAgent; - function detectOS(ua) { - for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) { - var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1]; - var match = regex.exec(ua); - if (match) { - return os; - } - } - return null; - } - exports2.detectOS = detectOS; - function getNodeVersion() { - var isNode2 = typeof import_process.default !== "undefined" && import_process.default.version; - return isNode2 ? new NodeInfo(import_process.default.version.slice(1)) : null; - } - exports2.getNodeVersion = getNodeVersion; - function createVersionParts(count) { - var output = []; - for (var ii = 0; ii < count; ii++) { - output.push("0"); - } - return output; - } - } -}); - -// node_modules/@walletconnect/window-getters/dist/cjs/index.js -var require_cjs3 = __commonJS({ - "node_modules/@walletconnect/window-getters/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getLocalStorage = exports2.getLocalStorageOrThrow = exports2.getCrypto = exports2.getCryptoOrThrow = exports2.getLocation = exports2.getLocationOrThrow = exports2.getNavigator = exports2.getNavigatorOrThrow = exports2.getDocument = exports2.getDocumentOrThrow = exports2.getFromWindowOrThrow = exports2.getFromWindow = void 0; - function getFromWindow(name2) { - let res = void 0; - if (typeof window !== "undefined" && typeof window[name2] !== "undefined") { - res = window[name2]; - } - return res; - } - exports2.getFromWindow = getFromWindow; - function getFromWindowOrThrow(name2) { - const res = getFromWindow(name2); - if (!res) { - throw new Error(`${name2} is not defined in Window`); - } - return res; - } - exports2.getFromWindowOrThrow = getFromWindowOrThrow; - function getDocumentOrThrow() { - return getFromWindowOrThrow("document"); - } - exports2.getDocumentOrThrow = getDocumentOrThrow; - function getDocument() { - return getFromWindow("document"); - } - exports2.getDocument = getDocument; - function getNavigatorOrThrow() { - return getFromWindowOrThrow("navigator"); - } - exports2.getNavigatorOrThrow = getNavigatorOrThrow; - function getNavigator() { - return getFromWindow("navigator"); - } - exports2.getNavigator = getNavigator; - function getLocationOrThrow() { - return getFromWindowOrThrow("location"); - } - exports2.getLocationOrThrow = getLocationOrThrow; - function getLocation() { - return getFromWindow("location"); - } - exports2.getLocation = getLocation; - function getCryptoOrThrow() { - return getFromWindowOrThrow("crypto"); - } - exports2.getCryptoOrThrow = getCryptoOrThrow; - function getCrypto() { - return getFromWindow("crypto"); - } - exports2.getCrypto = getCrypto; - function getLocalStorageOrThrow() { - return getFromWindowOrThrow("localStorage"); - } - exports2.getLocalStorageOrThrow = getLocalStorageOrThrow; - function getLocalStorage() { - return getFromWindow("localStorage"); - } - exports2.getLocalStorage = getLocalStorage; - } -}); - -// node_modules/@walletconnect/window-metadata/dist/cjs/index.js -var require_cjs4 = __commonJS({ - "node_modules/@walletconnect/window-metadata/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getWindowMetadata = void 0; - var window_getters_1 = require_cjs3(); - function getWindowMetadata() { - let doc; - let loc; - try { - doc = window_getters_1.getDocumentOrThrow(); - loc = window_getters_1.getLocationOrThrow(); - } catch (e2) { - return null; - } - function getIcons() { - const links = doc.getElementsByTagName("link"); - const icons2 = []; - for (let i2 = 0; i2 < links.length; i2++) { - const link = links[i2]; - const rel = link.getAttribute("rel"); - if (rel) { - if (rel.toLowerCase().indexOf("icon") > -1) { - const href = link.getAttribute("href"); - if (href) { - if (href.toLowerCase().indexOf("https:") === -1 && href.toLowerCase().indexOf("http:") === -1 && href.indexOf("//") !== 0) { - let absoluteHref = loc.protocol + "//" + loc.host; - if (href.indexOf("/") === 0) { - absoluteHref += href; - } else { - const path = loc.pathname.split("/"); - path.pop(); - const finalPath = path.join("/"); - absoluteHref += finalPath + "/" + href; - } - icons2.push(absoluteHref); - } else if (href.indexOf("//") === 0) { - const absoluteUrl = loc.protocol + href; - icons2.push(absoluteUrl); - } else { - icons2.push(href); - } - } - } - } - } - return icons2; - } - function getWindowMetadataOfAny(...args) { - const metaTags = doc.getElementsByTagName("meta"); - for (let i2 = 0; i2 < metaTags.length; i2++) { - const tag = metaTags[i2]; - const attributes = ["itemprop", "property", "name"].map((target) => tag.getAttribute(target)).filter((attr) => { - if (attr) { - return args.includes(attr); - } - return false; - }); - if (attributes.length && attributes) { - const content = tag.getAttribute("content"); - if (content) { - return content; - } - } - } - return ""; - } - function getName() { - let name3 = getWindowMetadataOfAny("name", "og:site_name", "og:title", "twitter:title"); - if (!name3) { - name3 = doc.title; - } - return name3; - } - function getDescription() { - const description2 = getWindowMetadataOfAny("description", "og:description", "twitter:description", "keywords"); - return description2; - } - const name2 = getName(); - const description = getDescription(); - const url = loc.origin; - const icons = getIcons(); - const meta = { - description, - url, - icons, - name: name2 - }; - return meta; - } - exports2.getWindowMetadata = getWindowMetadata; - } -}); - -// node_modules/strict-uri-encode/index.js -var require_strict_uri_encode = __commonJS({ - "node_modules/strict-uri-encode/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (x3) => `%${x3.charCodeAt(0).toString(16).toUpperCase()}`); - } -}); - -// node_modules/decode-uri-component/index.js -var require_decode_uri_component = __commonJS({ - "node_modules/decode-uri-component/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var token = "%[a-f0-9]{2}"; - var singleMatcher = new RegExp("(" + token + ")|([^%]+?)", "gi"); - var multiMatcher = new RegExp("(" + token + ")+", "gi"); - function decodeComponents(components, split) { - try { - return [decodeURIComponent(components.join(""))]; - } catch (err) { - } - if (components.length === 1) { - return components; - } - split = split || 1; - var left = components.slice(0, split); - var right = components.slice(split); - return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); - } - function decode6(input) { - try { - return decodeURIComponent(input); - } catch (err) { - var tokens = input.match(singleMatcher) || []; - for (var i2 = 1; i2 < tokens.length; i2++) { - input = decodeComponents(tokens, i2).join(""); - tokens = input.match(singleMatcher) || []; - } - return input; - } - } - function customDecodeURIComponent(input) { - var replaceMap = { - "%FE%FF": "\uFFFD\uFFFD", - "%FF%FE": "\uFFFD\uFFFD" - }; - var match = multiMatcher.exec(input); - while (match) { - try { - replaceMap[match[0]] = decodeURIComponent(match[0]); - } catch (err) { - var result = decode6(match[0]); - if (result !== match[0]) { - replaceMap[match[0]] = result; - } - } - match = multiMatcher.exec(input); - } - replaceMap["%C2"] = "\uFFFD"; - var entries = Object.keys(replaceMap); - for (var i2 = 0; i2 < entries.length; i2++) { - var key = entries[i2]; - input = input.replace(new RegExp(key, "g"), replaceMap[key]); - } - return input; - } - module2.exports = function(encodedURI) { - if (typeof encodedURI !== "string") { - throw new TypeError("Expected `encodedURI` to be of type `string`, got `" + typeof encodedURI + "`"); - } - try { - encodedURI = encodedURI.replace(/\+/g, " "); - return decodeURIComponent(encodedURI); - } catch (err) { - return customDecodeURIComponent(encodedURI); - } - }; - } -}); - -// node_modules/split-on-first/index.js -var require_split_on_first = __commonJS({ - "node_modules/split-on-first/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = (string2, separator) => { - if (!(typeof string2 === "string" && typeof separator === "string")) { - throw new TypeError("Expected the arguments to be of type `string`"); - } - if (separator === "") { - return [string2]; - } - const separatorIndex = string2.indexOf(separator); - if (separatorIndex === -1) { - return [string2]; - } - return [ - string2.slice(0, separatorIndex), - string2.slice(separatorIndex + separator.length) - ]; - }; - } -}); - -// node_modules/filter-obj/index.js -var require_filter_obj = __commonJS({ - "node_modules/filter-obj/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function(obj, predicate) { - var ret = {}; - var keys2 = Object.keys(obj); - var isArr = Array.isArray(predicate); - for (var i2 = 0; i2 < keys2.length; i2++) { - var key = keys2[i2]; - var val = obj[key]; - if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) { - ret[key] = val; - } - } - return ret; - }; - } -}); - -// node_modules/query-string/index.js -var require_query_string = __commonJS({ - "node_modules/query-string/index.js"(exports2) { - "use strict"; - init_shim(); - var strictUriEncode = require_strict_uri_encode(); - var decodeComponent = require_decode_uri_component(); - var splitOnFirst = require_split_on_first(); - var filterObject = require_filter_obj(); - var isNullOrUndefined = (value) => value === null || value === void 0; - var encodeFragmentIdentifier = Symbol("encodeFragmentIdentifier"); - function encoderForArrayFormat(options) { - switch (options.arrayFormat) { - case "index": - return (key) => (result, value) => { - const index = result.length; - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, [encode5(key, options), "[", index, "]"].join("")]; - } - return [ - ...result, - [encode5(key, options), "[", encode5(index, options), "]=", encode5(value, options)].join("") - ]; - }; - case "bracket": - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, [encode5(key, options), "[]"].join("")]; - } - return [...result, [encode5(key, options), "[]=", encode5(value, options)].join("")]; - }; - case "colon-list-separator": - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, [encode5(key, options), ":list="].join("")]; - } - return [...result, [encode5(key, options), ":list=", encode5(value, options)].join("")]; - }; - case "comma": - case "separator": - case "bracket-separator": { - const keyValueSep = options.arrayFormat === "bracket-separator" ? "[]=" : "="; - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - value = value === null ? "" : value; - if (result.length === 0) { - return [[encode5(key, options), keyValueSep, encode5(value, options)].join("")]; - } - return [[result, encode5(value, options)].join(options.arrayFormatSeparator)]; - }; - } - default: - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, encode5(key, options)]; - } - return [...result, [encode5(key, options), "=", encode5(value, options)].join("")]; - }; - } - } - function parserForArrayFormat(options) { - let result; - switch (options.arrayFormat) { - case "index": - return (key, value, accumulator) => { - result = /\[(\d*)\]$/.exec(key); - key = key.replace(/\[\d*\]$/, ""); - if (!result) { - accumulator[key] = value; - return; - } - if (accumulator[key] === void 0) { - accumulator[key] = {}; - } - accumulator[key][result[1]] = value; - }; - case "bracket": - return (key, value, accumulator) => { - result = /(\[\])$/.exec(key); - key = key.replace(/\[\]$/, ""); - if (!result) { - accumulator[key] = value; - return; - } - if (accumulator[key] === void 0) { - accumulator[key] = [value]; - return; - } - accumulator[key] = [].concat(accumulator[key], value); - }; - case "colon-list-separator": - return (key, value, accumulator) => { - result = /(:list)$/.exec(key); - key = key.replace(/:list$/, ""); - if (!result) { - accumulator[key] = value; - return; - } - if (accumulator[key] === void 0) { - accumulator[key] = [value]; - return; - } - accumulator[key] = [].concat(accumulator[key], value); - }; - case "comma": - case "separator": - return (key, value, accumulator) => { - const isArray = typeof value === "string" && value.includes(options.arrayFormatSeparator); - const isEncodedArray = typeof value === "string" && !isArray && decode6(value, options).includes(options.arrayFormatSeparator); - value = isEncodedArray ? decode6(value, options) : value; - const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)) : value === null ? value : decode6(value, options); - accumulator[key] = newValue; - }; - case "bracket-separator": - return (key, value, accumulator) => { - const isArray = /(\[\])$/.test(key); - key = key.replace(/\[\]$/, ""); - if (!isArray) { - accumulator[key] = value ? decode6(value, options) : value; - return; - } - const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)); - if (accumulator[key] === void 0) { - accumulator[key] = arrayValue; - return; - } - accumulator[key] = [].concat(accumulator[key], arrayValue); - }; - default: - return (key, value, accumulator) => { - if (accumulator[key] === void 0) { - accumulator[key] = value; - return; - } - accumulator[key] = [].concat(accumulator[key], value); - }; - } - } - function validateArrayFormatSeparator(value) { - if (typeof value !== "string" || value.length !== 1) { - throw new TypeError("arrayFormatSeparator must be single character string"); - } - } - function encode5(value, options) { - if (options.encode) { - return options.strict ? strictUriEncode(value) : encodeURIComponent(value); - } - return value; - } - function decode6(value, options) { - if (options.decode) { - return decodeComponent(value); - } - return value; - } - function keysSorter(input) { - if (Array.isArray(input)) { - return input.sort(); - } - if (typeof input === "object") { - return keysSorter(Object.keys(input)).sort((a3, b4) => Number(a3) - Number(b4)).map((key) => input[key]); - } - return input; - } - function removeHash(input) { - const hashStart = input.indexOf("#"); - if (hashStart !== -1) { - input = input.slice(0, hashStart); - } - return input; - } - function getHash(url) { - let hash = ""; - const hashStart = url.indexOf("#"); - if (hashStart !== -1) { - hash = url.slice(hashStart); - } - return hash; - } - function extract(input) { - input = removeHash(input); - const queryStart = input.indexOf("?"); - if (queryStart === -1) { - return ""; - } - return input.slice(queryStart + 1); - } - function parseValue(value, options) { - if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === "string" && value.trim() !== "")) { - value = Number(value); - } else if (options.parseBooleans && value !== null && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) { - value = value.toLowerCase() === "true"; - } - return value; - } - function parse(query, options) { - options = Object.assign({ - decode: true, - sort: true, - arrayFormat: "none", - arrayFormatSeparator: ",", - parseNumbers: false, - parseBooleans: false - }, options); - validateArrayFormatSeparator(options.arrayFormatSeparator); - const formatter = parserForArrayFormat(options); - const ret = /* @__PURE__ */ Object.create(null); - if (typeof query !== "string") { - return ret; - } - query = query.trim().replace(/^[?#&]/, ""); - if (!query) { - return ret; - } - for (const param of query.split("&")) { - if (param === "") { - continue; - } - let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, " ") : param, "="); - value = value === void 0 ? null : ["comma", "separator", "bracket-separator"].includes(options.arrayFormat) ? value : decode6(value, options); - formatter(decode6(key, options), value, ret); - } - for (const key of Object.keys(ret)) { - const value = ret[key]; - if (typeof value === "object" && value !== null) { - for (const k4 of Object.keys(value)) { - value[k4] = parseValue(value[k4], options); - } - } else { - ret[key] = parseValue(value, options); - } - } - if (options.sort === false) { - return ret; - } - return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { - const value = ret[key]; - if (Boolean(value) && typeof value === "object" && !Array.isArray(value)) { - result[key] = keysSorter(value); - } else { - result[key] = value; - } - return result; - }, /* @__PURE__ */ Object.create(null)); - } - exports2.extract = extract; - exports2.parse = parse; - exports2.stringify = (object, options) => { - if (!object) { - return ""; - } - options = Object.assign({ - encode: true, - strict: true, - arrayFormat: "none", - arrayFormatSeparator: "," - }, options); - validateArrayFormatSeparator(options.arrayFormatSeparator); - const shouldFilter = (key) => options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === ""; - const formatter = encoderForArrayFormat(options); - const objectCopy = {}; - for (const key of Object.keys(object)) { - if (!shouldFilter(key)) { - objectCopy[key] = object[key]; - } - } - const keys2 = Object.keys(objectCopy); - if (options.sort !== false) { - keys2.sort(options.sort); - } - return keys2.map((key) => { - const value = object[key]; - if (value === void 0) { - return ""; - } - if (value === null) { - return encode5(key, options); - } - if (Array.isArray(value)) { - if (value.length === 0 && options.arrayFormat === "bracket-separator") { - return encode5(key, options) + "[]"; - } - return value.reduce(formatter(key), []).join("&"); - } - return encode5(key, options) + "=" + encode5(value, options); - }).filter((x3) => x3.length > 0).join("&"); - }; - exports2.parseUrl = (url, options) => { - options = Object.assign({ - decode: true - }, options); - const [url_, hash] = splitOnFirst(url, "#"); - return Object.assign( - { - url: url_.split("?")[0] || "", - query: parse(extract(url), options) - }, - options && options.parseFragmentIdentifier && hash ? { fragmentIdentifier: decode6(hash, options) } : {} - ); - }; - exports2.stringifyUrl = (object, options) => { - options = Object.assign({ - encode: true, - strict: true, - [encodeFragmentIdentifier]: true - }, options); - const url = removeHash(object.url).split("?")[0] || ""; - const queryFromUrl = exports2.extract(object.url); - const parsedQueryFromUrl = exports2.parse(queryFromUrl, { sort: false }); - const query = Object.assign(parsedQueryFromUrl, object.query); - let queryString = exports2.stringify(query, options); - if (queryString) { - queryString = `?${queryString}`; - } - let hash = getHash(object.url); - if (object.fragmentIdentifier) { - hash = `#${options[encodeFragmentIdentifier] ? encode5(object.fragmentIdentifier, options) : object.fragmentIdentifier}`; - } - return `${url}${queryString}${hash}`; - }; - exports2.pick = (input, filter, options) => { - options = Object.assign({ - parseFragmentIdentifier: true, - [encodeFragmentIdentifier]: false - }, options); - const { url, query, fragmentIdentifier } = exports2.parseUrl(input, options); - return exports2.stringifyUrl({ - url, - query: filterObject(query, filter), - fragmentIdentifier - }, options); - }; - exports2.exclude = (input, filter, options) => { - const exclusionFilter = Array.isArray(filter) ? (key) => !filter.includes(key) : (key, value) => !filter(key, value); - return exports2.pick(input, exclusionFilter, options); - }; - } -}); - -// node_modules/@stablelib/chacha/lib/chacha.js -var require_chacha = __commonJS({ - "node_modules/@stablelib/chacha/lib/chacha.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - var ROUNDS = 20; - function core(out, input, key) { - var j0 = 1634760805; - var j1 = 857760878; - var j2 = 2036477234; - var j3 = 1797285236; - var j4 = key[3] << 24 | key[2] << 16 | key[1] << 8 | key[0]; - var j5 = key[7] << 24 | key[6] << 16 | key[5] << 8 | key[4]; - var j6 = key[11] << 24 | key[10] << 16 | key[9] << 8 | key[8]; - var j7 = key[15] << 24 | key[14] << 16 | key[13] << 8 | key[12]; - var j8 = key[19] << 24 | key[18] << 16 | key[17] << 8 | key[16]; - var j9 = key[23] << 24 | key[22] << 16 | key[21] << 8 | key[20]; - var j10 = key[27] << 24 | key[26] << 16 | key[25] << 8 | key[24]; - var j11 = key[31] << 24 | key[30] << 16 | key[29] << 8 | key[28]; - var j12 = input[3] << 24 | input[2] << 16 | input[1] << 8 | input[0]; - var j13 = input[7] << 24 | input[6] << 16 | input[5] << 8 | input[4]; - var j14 = input[11] << 24 | input[10] << 16 | input[9] << 8 | input[8]; - var j15 = input[15] << 24 | input[14] << 16 | input[13] << 8 | input[12]; - var x0 = j0; - var x1 = j1; - var x22 = j2; - var x3 = j3; - var x4 = j4; - var x5 = j5; - var x6 = j6; - var x7 = j7; - var x8 = j8; - var x9 = j9; - var x10 = j10; - var x11 = j11; - var x12 = j12; - var x13 = j13; - var x14 = j14; - var x15 = j15; - for (var i2 = 0; i2 < ROUNDS; i2 += 2) { - x0 = x0 + x4 | 0; - x12 ^= x0; - x12 = x12 >>> 32 - 16 | x12 << 16; - x8 = x8 + x12 | 0; - x4 ^= x8; - x4 = x4 >>> 32 - 12 | x4 << 12; - x1 = x1 + x5 | 0; - x13 ^= x1; - x13 = x13 >>> 32 - 16 | x13 << 16; - x9 = x9 + x13 | 0; - x5 ^= x9; - x5 = x5 >>> 32 - 12 | x5 << 12; - x22 = x22 + x6 | 0; - x14 ^= x22; - x14 = x14 >>> 32 - 16 | x14 << 16; - x10 = x10 + x14 | 0; - x6 ^= x10; - x6 = x6 >>> 32 - 12 | x6 << 12; - x3 = x3 + x7 | 0; - x15 ^= x3; - x15 = x15 >>> 32 - 16 | x15 << 16; - x11 = x11 + x15 | 0; - x7 ^= x11; - x7 = x7 >>> 32 - 12 | x7 << 12; - x22 = x22 + x6 | 0; - x14 ^= x22; - x14 = x14 >>> 32 - 8 | x14 << 8; - x10 = x10 + x14 | 0; - x6 ^= x10; - x6 = x6 >>> 32 - 7 | x6 << 7; - x3 = x3 + x7 | 0; - x15 ^= x3; - x15 = x15 >>> 32 - 8 | x15 << 8; - x11 = x11 + x15 | 0; - x7 ^= x11; - x7 = x7 >>> 32 - 7 | x7 << 7; - x1 = x1 + x5 | 0; - x13 ^= x1; - x13 = x13 >>> 32 - 8 | x13 << 8; - x9 = x9 + x13 | 0; - x5 ^= x9; - x5 = x5 >>> 32 - 7 | x5 << 7; - x0 = x0 + x4 | 0; - x12 ^= x0; - x12 = x12 >>> 32 - 8 | x12 << 8; - x8 = x8 + x12 | 0; - x4 ^= x8; - x4 = x4 >>> 32 - 7 | x4 << 7; - x0 = x0 + x5 | 0; - x15 ^= x0; - x15 = x15 >>> 32 - 16 | x15 << 16; - x10 = x10 + x15 | 0; - x5 ^= x10; - x5 = x5 >>> 32 - 12 | x5 << 12; - x1 = x1 + x6 | 0; - x12 ^= x1; - x12 = x12 >>> 32 - 16 | x12 << 16; - x11 = x11 + x12 | 0; - x6 ^= x11; - x6 = x6 >>> 32 - 12 | x6 << 12; - x22 = x22 + x7 | 0; - x13 ^= x22; - x13 = x13 >>> 32 - 16 | x13 << 16; - x8 = x8 + x13 | 0; - x7 ^= x8; - x7 = x7 >>> 32 - 12 | x7 << 12; - x3 = x3 + x4 | 0; - x14 ^= x3; - x14 = x14 >>> 32 - 16 | x14 << 16; - x9 = x9 + x14 | 0; - x4 ^= x9; - x4 = x4 >>> 32 - 12 | x4 << 12; - x22 = x22 + x7 | 0; - x13 ^= x22; - x13 = x13 >>> 32 - 8 | x13 << 8; - x8 = x8 + x13 | 0; - x7 ^= x8; - x7 = x7 >>> 32 - 7 | x7 << 7; - x3 = x3 + x4 | 0; - x14 ^= x3; - x14 = x14 >>> 32 - 8 | x14 << 8; - x9 = x9 + x14 | 0; - x4 ^= x9; - x4 = x4 >>> 32 - 7 | x4 << 7; - x1 = x1 + x6 | 0; - x12 ^= x1; - x12 = x12 >>> 32 - 8 | x12 << 8; - x11 = x11 + x12 | 0; - x6 ^= x11; - x6 = x6 >>> 32 - 7 | x6 << 7; - x0 = x0 + x5 | 0; - x15 ^= x0; - x15 = x15 >>> 32 - 8 | x15 << 8; - x10 = x10 + x15 | 0; - x5 ^= x10; - x5 = x5 >>> 32 - 7 | x5 << 7; - } - binary_1.writeUint32LE(x0 + j0 | 0, out, 0); - binary_1.writeUint32LE(x1 + j1 | 0, out, 4); - binary_1.writeUint32LE(x22 + j2 | 0, out, 8); - binary_1.writeUint32LE(x3 + j3 | 0, out, 12); - binary_1.writeUint32LE(x4 + j4 | 0, out, 16); - binary_1.writeUint32LE(x5 + j5 | 0, out, 20); - binary_1.writeUint32LE(x6 + j6 | 0, out, 24); - binary_1.writeUint32LE(x7 + j7 | 0, out, 28); - binary_1.writeUint32LE(x8 + j8 | 0, out, 32); - binary_1.writeUint32LE(x9 + j9 | 0, out, 36); - binary_1.writeUint32LE(x10 + j10 | 0, out, 40); - binary_1.writeUint32LE(x11 + j11 | 0, out, 44); - binary_1.writeUint32LE(x12 + j12 | 0, out, 48); - binary_1.writeUint32LE(x13 + j13 | 0, out, 52); - binary_1.writeUint32LE(x14 + j14 | 0, out, 56); - binary_1.writeUint32LE(x15 + j15 | 0, out, 60); - } - function streamXOR(key, nonce, src2, dst, nonceInplaceCounterLength) { - if (nonceInplaceCounterLength === void 0) { - nonceInplaceCounterLength = 0; - } - if (key.length !== 32) { - throw new Error("ChaCha: key size must be 32 bytes"); - } - if (dst.length < src2.length) { - throw new Error("ChaCha: destination is shorter than source"); - } - var nc; - var counterLength; - if (nonceInplaceCounterLength === 0) { - if (nonce.length !== 8 && nonce.length !== 12) { - throw new Error("ChaCha nonce must be 8 or 12 bytes"); - } - nc = new Uint8Array(16); - counterLength = nc.length - nonce.length; - nc.set(nonce, counterLength); - } else { - if (nonce.length !== 16) { - throw new Error("ChaCha nonce with counter must be 16 bytes"); - } - nc = nonce; - counterLength = nonceInplaceCounterLength; - } - var block = new Uint8Array(64); - for (var i2 = 0; i2 < src2.length; i2 += 64) { - core(block, nc, key); - for (var j2 = i2; j2 < i2 + 64 && j2 < src2.length; j2++) { - dst[j2] = src2[j2] ^ block[j2 - i2]; - } - incrementCounter(nc, 0, counterLength); - } - wipe_1.wipe(block); - if (nonceInplaceCounterLength === 0) { - wipe_1.wipe(nc); - } - return dst; - } - exports2.streamXOR = streamXOR; - function stream(key, nonce, dst, nonceInplaceCounterLength) { - if (nonceInplaceCounterLength === void 0) { - nonceInplaceCounterLength = 0; - } - wipe_1.wipe(dst); - return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength); - } - exports2.stream = stream; - function incrementCounter(counter, pos, len) { - var carry = 1; - while (len--) { - carry = carry + (counter[pos] & 255) | 0; - counter[pos] = carry & 255; - carry >>>= 8; - pos++; - } - if (carry > 0) { - throw new Error("ChaCha: counter overflow"); - } - } - } -}); - -// node_modules/@stablelib/constant-time/lib/constant-time.js -var require_constant_time = __commonJS({ - "node_modules/@stablelib/constant-time/lib/constant-time.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function select(subject, resultIfOne, resultIfZero) { - return ~(subject - 1) & resultIfOne | subject - 1 & resultIfZero; - } - exports2.select = select; - function lessOrEqual(a3, b4) { - return (a3 | 0) - (b4 | 0) - 1 >>> 31 & 1; - } - exports2.lessOrEqual = lessOrEqual; - function compare3(a3, b4) { - if (a3.length !== b4.length) { - return 0; - } - var result = 0; - for (var i2 = 0; i2 < a3.length; i2++) { - result |= a3[i2] ^ b4[i2]; - } - return 1 & result - 1 >>> 8; - } - exports2.compare = compare3; - function equal(a3, b4) { - if (a3.length === 0 || b4.length === 0) { - return false; - } - return compare3(a3, b4) !== 0; - } - exports2.equal = equal; - } -}); - -// node_modules/@stablelib/poly1305/lib/poly1305.js -var require_poly1305 = __commonJS({ - "node_modules/@stablelib/poly1305/lib/poly1305.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var constant_time_1 = require_constant_time(); - var wipe_1 = require_wipe(); - exports2.DIGEST_LENGTH = 16; - var Poly1305 = ( - /** @class */ - function() { - function Poly13052(key) { - this.digestLength = exports2.DIGEST_LENGTH; - this._buffer = new Uint8Array(16); - this._r = new Uint16Array(10); - this._h = new Uint16Array(10); - this._pad = new Uint16Array(8); - this._leftover = 0; - this._fin = 0; - this._finished = false; - var t0 = key[0] | key[1] << 8; - this._r[0] = t0 & 8191; - var t1 = key[2] | key[3] << 8; - this._r[1] = (t0 >>> 13 | t1 << 3) & 8191; - var t2 = key[4] | key[5] << 8; - this._r[2] = (t1 >>> 10 | t2 << 6) & 7939; - var t3 = key[6] | key[7] << 8; - this._r[3] = (t2 >>> 7 | t3 << 9) & 8191; - var t4 = key[8] | key[9] << 8; - this._r[4] = (t3 >>> 4 | t4 << 12) & 255; - this._r[5] = t4 >>> 1 & 8190; - var t5 = key[10] | key[11] << 8; - this._r[6] = (t4 >>> 14 | t5 << 2) & 8191; - var t6 = key[12] | key[13] << 8; - this._r[7] = (t5 >>> 11 | t6 << 5) & 8065; - var t7 = key[14] | key[15] << 8; - this._r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this._r[9] = t7 >>> 5 & 127; - this._pad[0] = key[16] | key[17] << 8; - this._pad[1] = key[18] | key[19] << 8; - this._pad[2] = key[20] | key[21] << 8; - this._pad[3] = key[22] | key[23] << 8; - this._pad[4] = key[24] | key[25] << 8; - this._pad[5] = key[26] | key[27] << 8; - this._pad[6] = key[28] | key[29] << 8; - this._pad[7] = key[30] | key[31] << 8; - } - Poly13052.prototype._blocks = function(m3, mpos, bytes) { - var hibit = this._fin ? 0 : 1 << 11; - var h0 = this._h[0], h1 = this._h[1], h22 = this._h[2], h32 = this._h[3], h42 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9]; - var r0 = this._r[0], r1 = this._r[1], r2 = this._r[2], r3 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9]; - while (bytes >= 16) { - var t0 = m3[mpos + 0] | m3[mpos + 1] << 8; - h0 += t0 & 8191; - var t1 = m3[mpos + 2] | m3[mpos + 3] << 8; - h1 += (t0 >>> 13 | t1 << 3) & 8191; - var t2 = m3[mpos + 4] | m3[mpos + 5] << 8; - h22 += (t1 >>> 10 | t2 << 6) & 8191; - var t3 = m3[mpos + 6] | m3[mpos + 7] << 8; - h32 += (t2 >>> 7 | t3 << 9) & 8191; - var t4 = m3[mpos + 8] | m3[mpos + 9] << 8; - h42 += (t3 >>> 4 | t4 << 12) & 8191; - h5 += t4 >>> 1 & 8191; - var t5 = m3[mpos + 10] | m3[mpos + 11] << 8; - h6 += (t4 >>> 14 | t5 << 2) & 8191; - var t6 = m3[mpos + 12] | m3[mpos + 13] << 8; - h7 += (t5 >>> 11 | t6 << 5) & 8191; - var t7 = m3[mpos + 14] | m3[mpos + 15] << 8; - h8 += (t6 >>> 8 | t7 << 8) & 8191; - h9 += t7 >>> 5 | hibit; - var c4 = 0; - var d0 = c4; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h22 * (5 * r8); - d0 += h32 * (5 * r7); - d0 += h42 * (5 * r6); - c4 = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c4 += d0 >>> 13; - d0 &= 8191; - var d1 = c4; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h22 * (5 * r9); - d1 += h32 * (5 * r8); - d1 += h42 * (5 * r7); - c4 = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c4 += d1 >>> 13; - d1 &= 8191; - var d22 = c4; - d22 += h0 * r2; - d22 += h1 * r1; - d22 += h22 * r0; - d22 += h32 * (5 * r9); - d22 += h42 * (5 * r8); - c4 = d22 >>> 13; - d22 &= 8191; - d22 += h5 * (5 * r7); - d22 += h6 * (5 * r6); - d22 += h7 * (5 * r5); - d22 += h8 * (5 * r4); - d22 += h9 * (5 * r3); - c4 += d22 >>> 13; - d22 &= 8191; - var d3 = c4; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h22 * r1; - d3 += h32 * r0; - d3 += h42 * (5 * r9); - c4 = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c4 += d3 >>> 13; - d3 &= 8191; - var d4 = c4; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h22 * r2; - d4 += h32 * r1; - d4 += h42 * r0; - c4 = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c4 += d4 >>> 13; - d4 &= 8191; - var d5 = c4; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h22 * r3; - d5 += h32 * r2; - d5 += h42 * r1; - c4 = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c4 += d5 >>> 13; - d5 &= 8191; - var d6 = c4; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h22 * r4; - d6 += h32 * r3; - d6 += h42 * r2; - c4 = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c4 += d6 >>> 13; - d6 &= 8191; - var d7 = c4; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h22 * r5; - d7 += h32 * r4; - d7 += h42 * r3; - c4 = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c4 += d7 >>> 13; - d7 &= 8191; - var d8 = c4; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h22 * r6; - d8 += h32 * r5; - d8 += h42 * r4; - c4 = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c4 += d8 >>> 13; - d8 &= 8191; - var d9 = c4; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h22 * r7; - d9 += h32 * r6; - d9 += h42 * r5; - c4 = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c4 += d9 >>> 13; - d9 &= 8191; - c4 = (c4 << 2) + c4 | 0; - c4 = c4 + d0 | 0; - d0 = c4 & 8191; - c4 = c4 >>> 13; - d1 += c4; - h0 = d0; - h1 = d1; - h22 = d22; - h32 = d3; - h42 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - mpos += 16; - bytes -= 16; - } - this._h[0] = h0; - this._h[1] = h1; - this._h[2] = h22; - this._h[3] = h32; - this._h[4] = h42; - this._h[5] = h5; - this._h[6] = h6; - this._h[7] = h7; - this._h[8] = h8; - this._h[9] = h9; - }; - Poly13052.prototype.finish = function(mac, macpos) { - if (macpos === void 0) { - macpos = 0; - } - var g3 = new Uint16Array(10); - var c4; - var mask; - var f4; - var i2; - if (this._leftover) { - i2 = this._leftover; - this._buffer[i2++] = 1; - for (; i2 < 16; i2++) { - this._buffer[i2] = 0; - } - this._fin = 1; - this._blocks(this._buffer, 0, 16); - } - c4 = this._h[1] >>> 13; - this._h[1] &= 8191; - for (i2 = 2; i2 < 10; i2++) { - this._h[i2] += c4; - c4 = this._h[i2] >>> 13; - this._h[i2] &= 8191; - } - this._h[0] += c4 * 5; - c4 = this._h[0] >>> 13; - this._h[0] &= 8191; - this._h[1] += c4; - c4 = this._h[1] >>> 13; - this._h[1] &= 8191; - this._h[2] += c4; - g3[0] = this._h[0] + 5; - c4 = g3[0] >>> 13; - g3[0] &= 8191; - for (i2 = 1; i2 < 10; i2++) { - g3[i2] = this._h[i2] + c4; - c4 = g3[i2] >>> 13; - g3[i2] &= 8191; - } - g3[9] -= 1 << 13; - mask = (c4 ^ 1) - 1; - for (i2 = 0; i2 < 10; i2++) { - g3[i2] &= mask; - } - mask = ~mask; - for (i2 = 0; i2 < 10; i2++) { - this._h[i2] = this._h[i2] & mask | g3[i2]; - } - this._h[0] = (this._h[0] | this._h[1] << 13) & 65535; - this._h[1] = (this._h[1] >>> 3 | this._h[2] << 10) & 65535; - this._h[2] = (this._h[2] >>> 6 | this._h[3] << 7) & 65535; - this._h[3] = (this._h[3] >>> 9 | this._h[4] << 4) & 65535; - this._h[4] = (this._h[4] >>> 12 | this._h[5] << 1 | this._h[6] << 14) & 65535; - this._h[5] = (this._h[6] >>> 2 | this._h[7] << 11) & 65535; - this._h[6] = (this._h[7] >>> 5 | this._h[8] << 8) & 65535; - this._h[7] = (this._h[8] >>> 8 | this._h[9] << 5) & 65535; - f4 = this._h[0] + this._pad[0]; - this._h[0] = f4 & 65535; - for (i2 = 1; i2 < 8; i2++) { - f4 = (this._h[i2] + this._pad[i2] | 0) + (f4 >>> 16) | 0; - this._h[i2] = f4 & 65535; - } - mac[macpos + 0] = this._h[0] >>> 0; - mac[macpos + 1] = this._h[0] >>> 8; - mac[macpos + 2] = this._h[1] >>> 0; - mac[macpos + 3] = this._h[1] >>> 8; - mac[macpos + 4] = this._h[2] >>> 0; - mac[macpos + 5] = this._h[2] >>> 8; - mac[macpos + 6] = this._h[3] >>> 0; - mac[macpos + 7] = this._h[3] >>> 8; - mac[macpos + 8] = this._h[4] >>> 0; - mac[macpos + 9] = this._h[4] >>> 8; - mac[macpos + 10] = this._h[5] >>> 0; - mac[macpos + 11] = this._h[5] >>> 8; - mac[macpos + 12] = this._h[6] >>> 0; - mac[macpos + 13] = this._h[6] >>> 8; - mac[macpos + 14] = this._h[7] >>> 0; - mac[macpos + 15] = this._h[7] >>> 8; - this._finished = true; - return this; - }; - Poly13052.prototype.update = function(m3) { - var mpos = 0; - var bytes = m3.length; - var want; - if (this._leftover) { - want = 16 - this._leftover; - if (want > bytes) { - want = bytes; - } - for (var i2 = 0; i2 < want; i2++) { - this._buffer[this._leftover + i2] = m3[mpos + i2]; - } - bytes -= want; - mpos += want; - this._leftover += want; - if (this._leftover < 16) { - return this; - } - this._blocks(this._buffer, 0, 16); - this._leftover = 0; - } - if (bytes >= 16) { - want = bytes - bytes % 16; - this._blocks(m3, mpos, want); - mpos += want; - bytes -= want; - } - if (bytes) { - for (var i2 = 0; i2 < bytes; i2++) { - this._buffer[this._leftover + i2] = m3[mpos + i2]; - } - this._leftover += bytes; - } - return this; - }; - Poly13052.prototype.digest = function() { - if (this._finished) { - throw new Error("Poly1305 was finished"); - } - var mac = new Uint8Array(16); - this.finish(mac); - return mac; - }; - Poly13052.prototype.clean = function() { - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._r); - wipe_1.wipe(this._h); - wipe_1.wipe(this._pad); - this._leftover = 0; - this._fin = 0; - this._finished = true; - return this; - }; - return Poly13052; - }() - ); - exports2.Poly1305 = Poly1305; - function oneTimeAuth(key, data) { - var h5 = new Poly1305(key); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.oneTimeAuth = oneTimeAuth; - function equal(a3, b4) { - if (a3.length !== exports2.DIGEST_LENGTH || b4.length !== exports2.DIGEST_LENGTH) { - return false; - } - return constant_time_1.equal(a3, b4); - } - exports2.equal = equal; - } -}); - -// node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js -var require_chacha20poly1305 = __commonJS({ - "node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var chacha_1 = require_chacha(); - var poly1305_1 = require_poly1305(); - var wipe_1 = require_wipe(); - var binary_1 = require_binary2(); - var constant_time_1 = require_constant_time(); - exports2.KEY_LENGTH = 32; - exports2.NONCE_LENGTH = 12; - exports2.TAG_LENGTH = 16; - var ZEROS = new Uint8Array(16); - var ChaCha20Poly1305 = ( - /** @class */ - function() { - function ChaCha20Poly13052(key) { - this.nonceLength = exports2.NONCE_LENGTH; - this.tagLength = exports2.TAG_LENGTH; - if (key.length !== exports2.KEY_LENGTH) { - throw new Error("ChaCha20Poly1305 needs 32-byte key"); - } - this._key = new Uint8Array(key); - } - ChaCha20Poly13052.prototype.seal = function(nonce, plaintext, associatedData, dst) { - if (nonce.length > 16) { - throw new Error("ChaCha20Poly1305: incorrect nonce length"); - } - var counter = new Uint8Array(16); - counter.set(nonce, counter.length - nonce.length); - var authKey = new Uint8Array(32); - chacha_1.stream(this._key, counter, authKey, 4); - var resultLength = plaintext.length + this.tagLength; - var result; - if (dst) { - if (dst.length !== resultLength) { - throw new Error("ChaCha20Poly1305: incorrect destination length"); - } - result = dst; - } else { - result = new Uint8Array(resultLength); - } - chacha_1.streamXOR(this._key, counter, plaintext, result, 4); - this._authenticate(result.subarray(result.length - this.tagLength, result.length), authKey, result.subarray(0, result.length - this.tagLength), associatedData); - wipe_1.wipe(counter); - return result; - }; - ChaCha20Poly13052.prototype.open = function(nonce, sealed, associatedData, dst) { - if (nonce.length > 16) { - throw new Error("ChaCha20Poly1305: incorrect nonce length"); - } - if (sealed.length < this.tagLength) { - return null; - } - var counter = new Uint8Array(16); - counter.set(nonce, counter.length - nonce.length); - var authKey = new Uint8Array(32); - chacha_1.stream(this._key, counter, authKey, 4); - var calculatedTag = new Uint8Array(this.tagLength); - this._authenticate(calculatedTag, authKey, sealed.subarray(0, sealed.length - this.tagLength), associatedData); - if (!constant_time_1.equal(calculatedTag, sealed.subarray(sealed.length - this.tagLength, sealed.length))) { - return null; - } - var resultLength = sealed.length - this.tagLength; - var result; - if (dst) { - if (dst.length !== resultLength) { - throw new Error("ChaCha20Poly1305: incorrect destination length"); - } - result = dst; - } else { - result = new Uint8Array(resultLength); - } - chacha_1.streamXOR(this._key, counter, sealed.subarray(0, sealed.length - this.tagLength), result, 4); - wipe_1.wipe(counter); - return result; - }; - ChaCha20Poly13052.prototype.clean = function() { - wipe_1.wipe(this._key); - return this; - }; - ChaCha20Poly13052.prototype._authenticate = function(tagOut, authKey, ciphertext, associatedData) { - var h5 = new poly1305_1.Poly1305(authKey); - if (associatedData) { - h5.update(associatedData); - if (associatedData.length % 16 > 0) { - h5.update(ZEROS.subarray(associatedData.length % 16)); - } - } - h5.update(ciphertext); - if (ciphertext.length % 16 > 0) { - h5.update(ZEROS.subarray(ciphertext.length % 16)); - } - var length2 = new Uint8Array(8); - if (associatedData) { - binary_1.writeUint64LE(associatedData.length, length2); - } - h5.update(length2); - binary_1.writeUint64LE(ciphertext.length, length2); - h5.update(length2); - var tag = h5.digest(); - for (var i2 = 0; i2 < tag.length; i2++) { - tagOut[i2] = tag[i2]; - } - h5.clean(); - wipe_1.wipe(tag); - wipe_1.wipe(length2); - }; - return ChaCha20Poly13052; - }() - ); - exports2.ChaCha20Poly1305 = ChaCha20Poly1305; - } -}); - -// node_modules/@stablelib/hash/lib/hash.js -var require_hash2 = __commonJS({ - "node_modules/@stablelib/hash/lib/hash.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function isSerializableHash(h5) { - return typeof h5.saveState !== "undefined" && typeof h5.restoreState !== "undefined" && typeof h5.cleanSavedState !== "undefined"; - } - exports2.isSerializableHash = isSerializableHash; - } -}); - -// node_modules/@stablelib/hmac/lib/hmac.js -var require_hmac = __commonJS({ - "node_modules/@stablelib/hmac/lib/hmac.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var hash_1 = require_hash2(); - var constant_time_1 = require_constant_time(); - var wipe_1 = require_wipe(); - var HMAC = ( - /** @class */ - function() { - function HMAC2(hash, key) { - this._finished = false; - this._inner = new hash(); - this._outer = new hash(); - this.blockSize = this._outer.blockSize; - this.digestLength = this._outer.digestLength; - var pad = new Uint8Array(this.blockSize); - if (key.length > this.blockSize) { - this._inner.update(key).finish(pad).clean(); - } else { - pad.set(key); - } - for (var i2 = 0; i2 < pad.length; i2++) { - pad[i2] ^= 54; - } - this._inner.update(pad); - for (var i2 = 0; i2 < pad.length; i2++) { - pad[i2] ^= 54 ^ 92; - } - this._outer.update(pad); - if (hash_1.isSerializableHash(this._inner) && hash_1.isSerializableHash(this._outer)) { - this._innerKeyedState = this._inner.saveState(); - this._outerKeyedState = this._outer.saveState(); - } - wipe_1.wipe(pad); - } - HMAC2.prototype.reset = function() { - if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { - throw new Error("hmac: can't reset() because hash doesn't implement restoreState()"); - } - this._inner.restoreState(this._innerKeyedState); - this._outer.restoreState(this._outerKeyedState); - this._finished = false; - return this; - }; - HMAC2.prototype.clean = function() { - if (hash_1.isSerializableHash(this._inner)) { - this._inner.cleanSavedState(this._innerKeyedState); - } - if (hash_1.isSerializableHash(this._outer)) { - this._outer.cleanSavedState(this._outerKeyedState); - } - this._inner.clean(); - this._outer.clean(); - }; - HMAC2.prototype.update = function(data) { - this._inner.update(data); - return this; - }; - HMAC2.prototype.finish = function(out) { - if (this._finished) { - this._outer.finish(out); - return this; - } - this._inner.finish(out); - this._outer.update(out.subarray(0, this.digestLength)).finish(out); - this._finished = true; - return this; - }; - HMAC2.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - HMAC2.prototype.saveState = function() { - if (!hash_1.isSerializableHash(this._inner)) { - throw new Error("hmac: can't saveState() because hash doesn't implement it"); - } - return this._inner.saveState(); - }; - HMAC2.prototype.restoreState = function(savedState) { - if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { - throw new Error("hmac: can't restoreState() because hash doesn't implement it"); - } - this._inner.restoreState(savedState); - this._outer.restoreState(this._outerKeyedState); - this._finished = false; - return this; - }; - HMAC2.prototype.cleanSavedState = function(savedState) { - if (!hash_1.isSerializableHash(this._inner)) { - throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it"); - } - this._inner.cleanSavedState(savedState); - }; - return HMAC2; - }() - ); - exports2.HMAC = HMAC; - function hmac(hash, key, data) { - var h5 = new HMAC(hash, key); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.hmac = hmac; - exports2.equal = constant_time_1.equal; - } -}); - -// node_modules/@stablelib/hkdf/lib/hkdf.js -var require_hkdf = __commonJS({ - "node_modules/@stablelib/hkdf/lib/hkdf.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var hmac_1 = require_hmac(); - var wipe_1 = require_wipe(); - var HKDF = ( - /** @class */ - function() { - function HKDF2(hash, key, salt, info) { - if (salt === void 0) { - salt = new Uint8Array(0); - } - this._counter = new Uint8Array(1); - this._hash = hash; - this._info = info; - var okm = hmac_1.hmac(this._hash, salt, key); - this._hmac = new hmac_1.HMAC(hash, okm); - this._buffer = new Uint8Array(this._hmac.digestLength); - this._bufpos = this._buffer.length; - } - HKDF2.prototype._fillBuffer = function() { - this._counter[0]++; - var ctr = this._counter[0]; - if (ctr === 0) { - throw new Error("hkdf: cannot expand more"); - } - this._hmac.reset(); - if (ctr > 1) { - this._hmac.update(this._buffer); - } - if (this._info) { - this._hmac.update(this._info); - } - this._hmac.update(this._counter); - this._hmac.finish(this._buffer); - this._bufpos = 0; - }; - HKDF2.prototype.expand = function(length2) { - var out = new Uint8Array(length2); - for (var i2 = 0; i2 < out.length; i2++) { - if (this._bufpos === this._buffer.length) { - this._fillBuffer(); - } - out[i2] = this._buffer[this._bufpos++]; - } - return out; - }; - HKDF2.prototype.clean = function() { - this._hmac.clean(); - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._counter); - this._bufpos = 0; - }; - return HKDF2; - }() - ); - exports2.HKDF = HKDF; - } -}); - -// node_modules/@stablelib/sha256/lib/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@stablelib/sha256/lib/sha256.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - exports2.DIGEST_LENGTH = 32; - exports2.BLOCK_SIZE = 64; - var SHA256 = ( - /** @class */ - function() { - function SHA2562() { - this.digestLength = exports2.DIGEST_LENGTH; - this.blockSize = exports2.BLOCK_SIZE; - this._state = new Int32Array(8); - this._temp = new Int32Array(64); - this._buffer = new Uint8Array(128); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - this.reset(); - } - SHA2562.prototype._initState = function() { - this._state[0] = 1779033703; - this._state[1] = 3144134277; - this._state[2] = 1013904242; - this._state[3] = 2773480762; - this._state[4] = 1359893119; - this._state[5] = 2600822924; - this._state[6] = 528734635; - this._state[7] = 1541459225; - }; - SHA2562.prototype.reset = function() { - this._initState(); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - return this; - }; - SHA2562.prototype.clean = function() { - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._temp); - this.reset(); - }; - SHA2562.prototype.update = function(data, dataLength) { - if (dataLength === void 0) { - dataLength = data.length; - } - if (this._finished) { - throw new Error("SHA256: can't update because hash was finished."); - } - var dataPos = 0; - this._bytesHashed += dataLength; - if (this._bufferLength > 0) { - while (this._bufferLength < this.blockSize && dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - if (this._bufferLength === this.blockSize) { - hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize); - this._bufferLength = 0; - } - } - if (dataLength >= this.blockSize) { - dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength); - dataLength %= this.blockSize; - } - while (dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - return this; - }; - SHA2562.prototype.finish = function(out) { - if (!this._finished) { - var bytesHashed = this._bytesHashed; - var left = this._bufferLength; - var bitLenHi = bytesHashed / 536870912 | 0; - var bitLenLo = bytesHashed << 3; - var padLength = bytesHashed % 64 < 56 ? 64 : 128; - this._buffer[left] = 128; - for (var i2 = left + 1; i2 < padLength - 8; i2++) { - this._buffer[i2] = 0; - } - binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); - binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); - hashBlocks(this._temp, this._state, this._buffer, 0, padLength); - this._finished = true; - } - for (var i2 = 0; i2 < this.digestLength / 4; i2++) { - binary_1.writeUint32BE(this._state[i2], out, i2 * 4); - } - return this; - }; - SHA2562.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - SHA2562.prototype.saveState = function() { - if (this._finished) { - throw new Error("SHA256: cannot save finished state"); - } - return { - state: new Int32Array(this._state), - buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, - bufferLength: this._bufferLength, - bytesHashed: this._bytesHashed - }; - }; - SHA2562.prototype.restoreState = function(savedState) { - this._state.set(savedState.state); - this._bufferLength = savedState.bufferLength; - if (savedState.buffer) { - this._buffer.set(savedState.buffer); - } - this._bytesHashed = savedState.bytesHashed; - this._finished = false; - return this; - }; - SHA2562.prototype.cleanSavedState = function(savedState) { - wipe_1.wipe(savedState.state); - if (savedState.buffer) { - wipe_1.wipe(savedState.buffer); - } - savedState.bufferLength = 0; - savedState.bytesHashed = 0; - }; - return SHA2562; - }() - ); - exports2.SHA256 = SHA256; - var K2 = new Int32Array([ - 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 - ]); - function hashBlocks(w4, v2, p3, pos, len) { - while (len >= 64) { - var a3 = v2[0]; - var b4 = v2[1]; - var c4 = v2[2]; - var d3 = v2[3]; - var e2 = v2[4]; - var f4 = v2[5]; - var g3 = v2[6]; - var h5 = v2[7]; - for (var i2 = 0; i2 < 16; i2++) { - var j2 = pos + i2 * 4; - w4[i2] = binary_1.readUint32BE(p3, j2); - } - for (var i2 = 16; i2 < 64; i2++) { - var u3 = w4[i2 - 2]; - var t1 = (u3 >>> 17 | u3 << 32 - 17) ^ (u3 >>> 19 | u3 << 32 - 19) ^ u3 >>> 10; - u3 = w4[i2 - 15]; - var t2 = (u3 >>> 7 | u3 << 32 - 7) ^ (u3 >>> 18 | u3 << 32 - 18) ^ u3 >>> 3; - w4[i2] = (t1 + w4[i2 - 7] | 0) + (t2 + w4[i2 - 16] | 0); - } - for (var i2 = 0; i2 < 64; i2++) { - var t1 = (((e2 >>> 6 | e2 << 32 - 6) ^ (e2 >>> 11 | e2 << 32 - 11) ^ (e2 >>> 25 | e2 << 32 - 25)) + (e2 & f4 ^ ~e2 & g3) | 0) + (h5 + (K2[i2] + w4[i2] | 0) | 0) | 0; - var t2 = ((a3 >>> 2 | a3 << 32 - 2) ^ (a3 >>> 13 | a3 << 32 - 13) ^ (a3 >>> 22 | a3 << 32 - 22)) + (a3 & b4 ^ a3 & c4 ^ b4 & c4) | 0; - h5 = g3; - g3 = f4; - f4 = e2; - e2 = d3 + t1 | 0; - d3 = c4; - c4 = b4; - b4 = a3; - a3 = t1 + t2 | 0; - } - v2[0] += a3; - v2[1] += b4; - v2[2] += c4; - v2[3] += d3; - v2[4] += e2; - v2[5] += f4; - v2[6] += g3; - v2[7] += h5; - pos += 64; - len -= 64; - } - return pos; - } - function hash(data) { - var h5 = new SHA256(); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.hash = hash; - } -}); - -// node_modules/@stablelib/x25519/lib/x25519.js -var require_x25519 = __commonJS({ - "node_modules/@stablelib/x25519/lib/x25519.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.sharedKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.scalarMultBase = exports2.scalarMult = exports2.SHARED_KEY_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = void 0; - var random_1 = require_random(); - var wipe_1 = require_wipe(); - exports2.PUBLIC_KEY_LENGTH = 32; - exports2.SECRET_KEY_LENGTH = 32; - exports2.SHARED_KEY_LENGTH = 32; - function gf(init) { - const r = new Float64Array(16); - if (init) { - for (let i2 = 0; i2 < init.length; i2++) { - r[i2] = init[i2]; - } - } - return r; - } - var _9 = new Uint8Array(32); - _9[0] = 9; - var _121665 = gf([56129, 1]); - function car25519(o2) { - let c4 = 1; - for (let i2 = 0; i2 < 16; i2++) { - let v2 = o2[i2] + c4 + 65535; - c4 = Math.floor(v2 / 65536); - o2[i2] = v2 - c4 * 65536; - } - o2[0] += c4 - 1 + 37 * (c4 - 1); - } - function sel25519(p3, q2, b4) { - const c4 = ~(b4 - 1); - for (let i2 = 0; i2 < 16; i2++) { - const t = c4 & (p3[i2] ^ q2[i2]); - p3[i2] ^= t; - q2[i2] ^= t; - } - } - function pack25519(o2, n3) { - const m3 = gf(); - const t = gf(); - for (let i2 = 0; i2 < 16; i2++) { - t[i2] = n3[i2]; - } - car25519(t); - car25519(t); - car25519(t); - for (let j2 = 0; j2 < 2; j2++) { - m3[0] = t[0] - 65517; - for (let i2 = 1; i2 < 15; i2++) { - m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); - m3[i2 - 1] &= 65535; - } - m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); - const b4 = m3[15] >> 16 & 1; - m3[14] &= 65535; - sel25519(t, m3, 1 - b4); - } - for (let i2 = 0; i2 < 16; i2++) { - o2[2 * i2] = t[i2] & 255; - o2[2 * i2 + 1] = t[i2] >> 8; - } - } - function unpack25519(o2, n3) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); - } - o2[15] &= 32767; - } - function add(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] + b4[i2]; - } - } - function sub(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] - b4[i2]; - } - } - function mul(o2, a3, b4) { - let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; - v2 = a3[0]; - t0 += v2 * b0; - t1 += v2 * b1; - t2 += v2 * b22; - t3 += v2 * b32; - t4 += v2 * b42; - t5 += v2 * b5; - t6 += v2 * b6; - t7 += v2 * b7; - t8 += v2 * b8; - t9 += v2 * b9; - t10 += v2 * b10; - t11 += v2 * b11; - t12 += v2 * b12; - t13 += v2 * b13; - t14 += v2 * b14; - t15 += v2 * b15; - v2 = a3[1]; - t1 += v2 * b0; - t2 += v2 * b1; - t3 += v2 * b22; - t4 += v2 * b32; - t5 += v2 * b42; - t6 += v2 * b5; - t7 += v2 * b6; - t8 += v2 * b7; - t9 += v2 * b8; - t10 += v2 * b9; - t11 += v2 * b10; - t12 += v2 * b11; - t13 += v2 * b12; - t14 += v2 * b13; - t15 += v2 * b14; - t16 += v2 * b15; - v2 = a3[2]; - t2 += v2 * b0; - t3 += v2 * b1; - t4 += v2 * b22; - t5 += v2 * b32; - t6 += v2 * b42; - t7 += v2 * b5; - t8 += v2 * b6; - t9 += v2 * b7; - t10 += v2 * b8; - t11 += v2 * b9; - t12 += v2 * b10; - t13 += v2 * b11; - t14 += v2 * b12; - t15 += v2 * b13; - t16 += v2 * b14; - t17 += v2 * b15; - v2 = a3[3]; - t3 += v2 * b0; - t4 += v2 * b1; - t5 += v2 * b22; - t6 += v2 * b32; - t7 += v2 * b42; - t8 += v2 * b5; - t9 += v2 * b6; - t10 += v2 * b7; - t11 += v2 * b8; - t12 += v2 * b9; - t13 += v2 * b10; - t14 += v2 * b11; - t15 += v2 * b12; - t16 += v2 * b13; - t17 += v2 * b14; - t18 += v2 * b15; - v2 = a3[4]; - t4 += v2 * b0; - t5 += v2 * b1; - t6 += v2 * b22; - t7 += v2 * b32; - t8 += v2 * b42; - t9 += v2 * b5; - t10 += v2 * b6; - t11 += v2 * b7; - t12 += v2 * b8; - t13 += v2 * b9; - t14 += v2 * b10; - t15 += v2 * b11; - t16 += v2 * b12; - t17 += v2 * b13; - t18 += v2 * b14; - t19 += v2 * b15; - v2 = a3[5]; - t5 += v2 * b0; - t6 += v2 * b1; - t7 += v2 * b22; - t8 += v2 * b32; - t9 += v2 * b42; - t10 += v2 * b5; - t11 += v2 * b6; - t12 += v2 * b7; - t13 += v2 * b8; - t14 += v2 * b9; - t15 += v2 * b10; - t16 += v2 * b11; - t17 += v2 * b12; - t18 += v2 * b13; - t19 += v2 * b14; - t20 += v2 * b15; - v2 = a3[6]; - t6 += v2 * b0; - t7 += v2 * b1; - t8 += v2 * b22; - t9 += v2 * b32; - t10 += v2 * b42; - t11 += v2 * b5; - t12 += v2 * b6; - t13 += v2 * b7; - t14 += v2 * b8; - t15 += v2 * b9; - t16 += v2 * b10; - t17 += v2 * b11; - t18 += v2 * b12; - t19 += v2 * b13; - t20 += v2 * b14; - t21 += v2 * b15; - v2 = a3[7]; - t7 += v2 * b0; - t8 += v2 * b1; - t9 += v2 * b22; - t10 += v2 * b32; - t11 += v2 * b42; - t12 += v2 * b5; - t13 += v2 * b6; - t14 += v2 * b7; - t15 += v2 * b8; - t16 += v2 * b9; - t17 += v2 * b10; - t18 += v2 * b11; - t19 += v2 * b12; - t20 += v2 * b13; - t21 += v2 * b14; - t22 += v2 * b15; - v2 = a3[8]; - t8 += v2 * b0; - t9 += v2 * b1; - t10 += v2 * b22; - t11 += v2 * b32; - t12 += v2 * b42; - t13 += v2 * b5; - t14 += v2 * b6; - t15 += v2 * b7; - t16 += v2 * b8; - t17 += v2 * b9; - t18 += v2 * b10; - t19 += v2 * b11; - t20 += v2 * b12; - t21 += v2 * b13; - t22 += v2 * b14; - t23 += v2 * b15; - v2 = a3[9]; - t9 += v2 * b0; - t10 += v2 * b1; - t11 += v2 * b22; - t12 += v2 * b32; - t13 += v2 * b42; - t14 += v2 * b5; - t15 += v2 * b6; - t16 += v2 * b7; - t17 += v2 * b8; - t18 += v2 * b9; - t19 += v2 * b10; - t20 += v2 * b11; - t21 += v2 * b12; - t22 += v2 * b13; - t23 += v2 * b14; - t24 += v2 * b15; - v2 = a3[10]; - t10 += v2 * b0; - t11 += v2 * b1; - t12 += v2 * b22; - t13 += v2 * b32; - t14 += v2 * b42; - t15 += v2 * b5; - t16 += v2 * b6; - t17 += v2 * b7; - t18 += v2 * b8; - t19 += v2 * b9; - t20 += v2 * b10; - t21 += v2 * b11; - t22 += v2 * b12; - t23 += v2 * b13; - t24 += v2 * b14; - t25 += v2 * b15; - v2 = a3[11]; - t11 += v2 * b0; - t12 += v2 * b1; - t13 += v2 * b22; - t14 += v2 * b32; - t15 += v2 * b42; - t16 += v2 * b5; - t17 += v2 * b6; - t18 += v2 * b7; - t19 += v2 * b8; - t20 += v2 * b9; - t21 += v2 * b10; - t22 += v2 * b11; - t23 += v2 * b12; - t24 += v2 * b13; - t25 += v2 * b14; - t26 += v2 * b15; - v2 = a3[12]; - t12 += v2 * b0; - t13 += v2 * b1; - t14 += v2 * b22; - t15 += v2 * b32; - t16 += v2 * b42; - t17 += v2 * b5; - t18 += v2 * b6; - t19 += v2 * b7; - t20 += v2 * b8; - t21 += v2 * b9; - t22 += v2 * b10; - t23 += v2 * b11; - t24 += v2 * b12; - t25 += v2 * b13; - t26 += v2 * b14; - t27 += v2 * b15; - v2 = a3[13]; - t13 += v2 * b0; - t14 += v2 * b1; - t15 += v2 * b22; - t16 += v2 * b32; - t17 += v2 * b42; - t18 += v2 * b5; - t19 += v2 * b6; - t20 += v2 * b7; - t21 += v2 * b8; - t22 += v2 * b9; - t23 += v2 * b10; - t24 += v2 * b11; - t25 += v2 * b12; - t26 += v2 * b13; - t27 += v2 * b14; - t28 += v2 * b15; - v2 = a3[14]; - t14 += v2 * b0; - t15 += v2 * b1; - t16 += v2 * b22; - t17 += v2 * b32; - t18 += v2 * b42; - t19 += v2 * b5; - t20 += v2 * b6; - t21 += v2 * b7; - t22 += v2 * b8; - t23 += v2 * b9; - t24 += v2 * b10; - t25 += v2 * b11; - t26 += v2 * b12; - t27 += v2 * b13; - t28 += v2 * b14; - t29 += v2 * b15; - v2 = a3[15]; - t15 += v2 * b0; - t16 += v2 * b1; - t17 += v2 * b22; - t18 += v2 * b32; - t19 += v2 * b42; - t20 += v2 * b5; - t21 += v2 * b6; - t22 += v2 * b7; - t23 += v2 * b8; - t24 += v2 * b9; - t25 += v2 * b10; - t26 += v2 * b11; - t27 += v2 * b12; - t28 += v2 * b13; - t29 += v2 * b14; - t30 += v2 * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - o2[0] = t0; - o2[1] = t1; - o2[2] = t2; - o2[3] = t3; - o2[4] = t4; - o2[5] = t5; - o2[6] = t6; - o2[7] = t7; - o2[8] = t8; - o2[9] = t9; - o2[10] = t10; - o2[11] = t11; - o2[12] = t12; - o2[13] = t13; - o2[14] = t14; - o2[15] = t15; - } - function square(o2, a3) { - mul(o2, a3, a3); - } - function inv25519(o2, inp) { - const c4 = gf(); - for (let i2 = 0; i2 < 16; i2++) { - c4[i2] = inp[i2]; - } - for (let i2 = 253; i2 >= 0; i2--) { - square(c4, c4); - if (i2 !== 2 && i2 !== 4) { - mul(c4, c4, inp); - } - } - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = c4[i2]; - } - } - function scalarMult(n3, p3) { - const z3 = new Uint8Array(32); - const x3 = new Float64Array(80); - const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(); - for (let i2 = 0; i2 < 31; i2++) { - z3[i2] = n3[i2]; - } - z3[31] = n3[31] & 127 | 64; - z3[0] &= 248; - unpack25519(x3, p3); - for (let i2 = 0; i2 < 16; i2++) { - b4[i2] = x3[i2]; - } - a3[0] = d3[0] = 1; - for (let i2 = 254; i2 >= 0; --i2) { - const r = z3[i2 >>> 3] >>> (i2 & 7) & 1; - sel25519(a3, b4, r); - sel25519(c4, d3, r); - add(e2, a3, c4); - sub(a3, a3, c4); - add(c4, b4, d3); - sub(b4, b4, d3); - square(d3, e2); - square(f4, a3); - mul(a3, c4, a3); - mul(c4, b4, e2); - add(e2, a3, c4); - sub(a3, a3, c4); - square(b4, a3); - sub(c4, d3, f4); - mul(a3, c4, _121665); - add(a3, a3, d3); - mul(c4, c4, a3); - mul(a3, d3, f4); - mul(d3, b4, x3); - square(b4, e2); - sel25519(a3, b4, r); - sel25519(c4, d3, r); - } - for (let i2 = 0; i2 < 16; i2++) { - x3[i2 + 16] = a3[i2]; - x3[i2 + 32] = c4[i2]; - x3[i2 + 48] = b4[i2]; - x3[i2 + 64] = d3[i2]; - } - const x32 = x3.subarray(32); - const x16 = x3.subarray(16); - inv25519(x32, x32); - mul(x16, x16, x32); - const q2 = new Uint8Array(32); - pack25519(q2, x16); - return q2; - } - exports2.scalarMult = scalarMult; - function scalarMultBase(n3) { - return scalarMult(n3, _9); - } - exports2.scalarMultBase = scalarMultBase; - function generateKeyPairFromSeed2(seed) { - if (seed.length !== exports2.SECRET_KEY_LENGTH) { - throw new Error(`x25519: seed must be ${exports2.SECRET_KEY_LENGTH} bytes`); - } - const secretKey = new Uint8Array(seed); - const publicKey = scalarMultBase(secretKey); - return { - publicKey, - secretKey - }; - } - exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; - function generateKeyPair2(prng) { - const seed = (0, random_1.randomBytes)(32, prng); - const result = generateKeyPairFromSeed2(seed); - (0, wipe_1.wipe)(seed); - return result; - } - exports2.generateKeyPair = generateKeyPair2; - function sharedKey(mySecretKey, theirPublicKey, rejectZero = false) { - if (mySecretKey.length !== exports2.PUBLIC_KEY_LENGTH) { - throw new Error("X25519: incorrect secret key length"); - } - if (theirPublicKey.length !== exports2.PUBLIC_KEY_LENGTH) { - throw new Error("X25519: incorrect public key length"); - } - const result = scalarMult(mySecretKey, theirPublicKey); - if (rejectZero) { - let zeros = 0; - for (let i2 = 0; i2 < result.length; i2++) { - zeros |= result[i2]; - } - if (zeros === 0) { - throw new Error("X25519: invalid shared key"); - } - } - return result; - } - exports2.sharedKey = sharedKey; - } -}); - -// node_modules/uint8arrays/esm/src/compare.js -function compare(a3, b4) { - for (let i2 = 0; i2 < a3.byteLength; i2++) { - if (a3[i2] < b4[i2]) { - return -1; - } - if (a3[i2] > b4[i2]) { - return 1; - } - } - if (a3.byteLength > b4.byteLength) { - return 1; - } - if (a3.byteLength < b4.byteLength) { - return -1; - } - return 0; -} -var init_compare = __esm({ - "node_modules/uint8arrays/esm/src/compare.js"() { - init_shim(); - } -}); - -// node_modules/uint8arrays/esm/src/equals.js -function equals3(a3, b4) { - if (a3 === b4) { - return true; - } - if (a3.byteLength !== b4.byteLength) { - return false; - } - for (let i2 = 0; i2 < a3.byteLength; i2++) { - if (a3[i2] !== b4[i2]) { - return false; - } - } - return true; -} -var init_equals = __esm({ - "node_modules/uint8arrays/esm/src/equals.js"() { - init_shim(); - } -}); - -// node_modules/uint8arrays/esm/src/xor.js -function xor(a3, b4) { - if (a3.length !== b4.length) { - throw new Error("Inputs should have the same length"); - } - const result = allocUnsafe(a3.length); - for (let i2 = 0; i2 < a3.length; i2++) { - result[i2] = a3[i2] ^ b4[i2]; - } - return asUint8Array(result); -} -var init_xor = __esm({ - "node_modules/uint8arrays/esm/src/xor.js"() { - init_shim(); - init_alloc(); - init_as_uint8array(); - } -}); - -// node_modules/uint8arrays/esm/src/index.js -var src_exports = {}; -__export(src_exports, { - compare: () => compare, - concat: () => concat, - equals: () => equals3, - fromString: () => fromString2, - toString: () => toString2, - xor: () => xor -}); -var init_src2 = __esm({ - "node_modules/uint8arrays/esm/src/index.js"() { - init_shim(); - init_compare(); - init_concat(); - init_equals(); - init_from_string(); - init_to_string(); - init_xor(); - } -}); - -// node_modules/@walletconnect/relay-api/dist/index.es.js -var index_es_exports3 = {}; -__export(index_es_exports3, { - RELAY_JSONRPC: () => C2, - isPublishMethod: () => c3, - isPublishParams: () => h3, - isPublishRequest: () => P, - isSubscribeMethod: () => b2, - isSubscribeParams: () => a, - isSubscribeRequest: () => R, - isSubscriptionMethod: () => m2, - isSubscriptionParams: () => d2, - isSubscriptionRequest: () => S2, - isUnsubscribeMethod: () => o, - isUnsubscribeParams: () => p2, - isUnsubscribeRequest: () => _3, - parsePublishRequest: () => q, - parseSubscribeRequest: () => g2, - parseSubscriptionRequest: () => k3, - parseUnsubscribeRequest: () => E3 -}); -function e(s2, r, i2 = "string") { - if (!s2[r] || typeof s2[r] !== i2) - throw new Error(`Missing or invalid "${r}" param`); -} -function l3(s2, r) { - let i2 = true; - return r.forEach((t) => { - t in s2 || (i2 = false); - }), i2; -} -function f2(s2, r) { - return Array.isArray(s2) ? s2.length === r : Object.keys(s2).length === r; -} -function w2(s2, r) { - return Array.isArray(s2) ? s2.length >= r : Object.keys(s2).length >= r; -} -function u(s2, r, i2) { - return (i2.length ? w2(s2, r.length) : f2(s2, r.length)) ? l3(s2, r) : false; -} -function n2(s2, r, i2 = "_") { - const t = s2.split(i2); - return t[t.length - 1].trim().toLowerCase() === r.trim().toLowerCase(); -} -function R(s2) { - return b2(s2.method) && a(s2.params); -} -function b2(s2) { - return n2(s2, "subscribe"); -} -function a(s2) { - return u(s2, ["topic"], []); -} -function P(s2) { - return c3(s2.method) && h3(s2.params); -} -function c3(s2) { - return n2(s2, "publish"); -} -function h3(s2) { - return u(s2, ["message", "topic", "ttl"], ["prompt", "tag"]); -} -function _3(s2) { - return o(s2.method) && p2(s2.params); -} -function o(s2) { - return n2(s2, "unsubscribe"); -} -function p2(s2) { - return u(s2, ["id", "topic"], []); -} -function S2(s2) { - return m2(s2.method) && d2(s2.params); -} -function m2(s2) { - return n2(s2, "subscription"); -} -function d2(s2) { - return u(s2, ["id", "data"], []); -} -function g2(s2) { - if (!b2(s2.method)) - throw new Error("JSON-RPC Request has invalid subscribe method"); - if (!a(s2.params)) - throw new Error("JSON-RPC Request has invalid subscribe params"); - const r = s2.params; - return e(r, "topic"), r; -} -function q(s2) { - if (!c3(s2.method)) - throw new Error("JSON-RPC Request has invalid publish method"); - if (!h3(s2.params)) - throw new Error("JSON-RPC Request has invalid publish params"); - const r = s2.params; - return e(r, "topic"), e(r, "message"), e(r, "ttl", "number"), r; -} -function E3(s2) { - if (!o(s2.method)) - throw new Error("JSON-RPC Request has invalid unsubscribe method"); - if (!p2(s2.params)) - throw new Error("JSON-RPC Request has invalid unsubscribe params"); - const r = s2.params; - return e(r, "id"), r; -} -function k3(s2) { - if (!m2(s2.method)) - throw new Error("JSON-RPC Request has invalid subscription method"); - if (!d2(s2.params)) - throw new Error("JSON-RPC Request has invalid subscription params"); - const r = s2.params; - return e(r, "id"), e(r, "data"), r; -} -var C2; -var init_index_es3 = __esm({ - "node_modules/@walletconnect/relay-api/dist/index.es.js"() { - init_shim(); - C2 = { waku: { publish: "waku_publish", batchPublish: "waku_batchPublish", subscribe: "waku_subscribe", batchSubscribe: "waku_batchSubscribe", subscription: "waku_subscription", unsubscribe: "waku_unsubscribe", batchUnsubscribe: "waku_batchUnsubscribe", batchFetchMessages: "waku_batchFetchMessages" }, irn: { publish: "irn_publish", batchPublish: "irn_batchPublish", subscribe: "irn_subscribe", batchSubscribe: "irn_batchSubscribe", subscription: "irn_subscription", unsubscribe: "irn_unsubscribe", batchUnsubscribe: "irn_batchUnsubscribe", batchFetchMessages: "irn_batchFetchMessages" }, iridium: { publish: "iridium_publish", batchPublish: "iridium_batchPublish", subscribe: "iridium_subscribe", batchSubscribe: "iridium_batchSubscribe", subscription: "iridium_subscription", unsubscribe: "iridium_unsubscribe", batchUnsubscribe: "iridium_batchUnsubscribe", batchFetchMessages: "iridium_batchFetchMessages" } }; - } -}); - -// node_modules/@walletconnect/utils/dist/index.cjs.js -var require_index_cjs2 = __commonJS({ - "node_modules/@walletconnect/utils/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var Ro = require_detect_browser(); - var tr = require_cjs(); - var er = require_cjs3(); - var Co = require_cjs4(); - var Oo = require_query_string(); - var fn = require_chacha20poly1305(); - var Po = require_hkdf(); - var on = require_random(); - var ci = require_sha256(); - var To = require_x25519(); - var Rt = (init_src2(), __toCommonJS(src_exports)); - var Fo = (init_index_es3(), __toCommonJS(index_es_exports3)); - function sn(e2) { - if (e2 && e2.__esModule) - return e2; - var t = /* @__PURE__ */ Object.create(null); - return e2 && Object.keys(e2).forEach(function(r) { - if (r !== "default") { - var i2 = Object.getOwnPropertyDescriptor(e2, r); - Object.defineProperty(t, r, i2.get ? i2 : { enumerable: true, get: function() { - return e2[r]; - } }); - } - }), t.default = e2, Object.freeze(t); - } - var Ir = sn(Oo); - var an = sn(To); - var _r = ":"; - function un(e2) { - const [t, r] = e2.split(_r); - return { namespace: t, reference: r }; - } - function hn(e2) { - const { namespace: t, reference: r } = e2; - return [t, r].join(_r); - } - function li(e2) { - const [t, r, i2] = e2.split(_r); - return { namespace: t, reference: r, address: i2 }; - } - function cn(e2) { - const { namespace: t, reference: r, address: i2 } = e2; - return [t, r, i2].join(_r); - } - function di(e2, t) { - const r = []; - return e2.forEach((i2) => { - const n3 = t(i2); - r.includes(n3) || r.push(n3); - }), r; - } - function ln(e2) { - const { address: t } = li(e2); - return t; - } - function dn(e2) { - const { namespace: t, reference: r } = li(e2); - return hn({ namespace: t, reference: r }); - } - function Do(e2, t) { - const { namespace: r, reference: i2 } = un(t); - return cn({ namespace: r, reference: i2, address: e2 }); - } - function Uo(e2) { - return di(e2, ln); - } - function pn(e2) { - return di(e2, dn); - } - function ko(e2, t = []) { - const r = []; - return Object.keys(e2).forEach((i2) => { - if (t.length && !t.includes(i2)) - return; - const n3 = e2[i2]; - r.push(...n3.accounts); - }), r; - } - function qo(e2, t = []) { - const r = []; - return Object.keys(e2).forEach((i2) => { - if (t.length && !t.includes(i2)) - return; - const n3 = e2[i2]; - r.push(...pn(n3.accounts)); - }), r; - } - function Ko(e2, t = []) { - const r = []; - return Object.keys(e2).forEach((i2) => { - if (t.length && !t.includes(i2)) - return; - const n3 = e2[i2]; - r.push(...Br(i2, n3)); - }), r; - } - function Br(e2, t) { - return e2.includes(":") ? [e2] : t.chains || []; - } - var Ho = Object.defineProperty; - var vn = Object.getOwnPropertySymbols; - var Lo = Object.prototype.hasOwnProperty; - var zo = Object.prototype.propertyIsEnumerable; - var gn = (e2, t, r) => t in e2 ? Ho(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var mn = (e2, t) => { - for (var r in t || (t = {})) - Lo.call(t, r) && gn(e2, r, t[r]); - if (vn) - for (var r of vn(t)) - zo.call(t, r) && gn(e2, r, t[r]); - return e2; - }; - var An = "ReactNative"; - var Kt = { reactNative: "react-native", node: "node", browser: "browser", unknown: "unknown" }; - var Rr = " "; - var jo = ":"; - var bn = "/"; - var pi = 2; - var Vo = 1e3; - var yn = "js"; - function vi() { - return typeof import_process.default < "u" && typeof import_process.default.versions < "u" && typeof import_process.default.versions.node < "u"; - } - function rr() { - return !er.getDocument() && !!er.getNavigator() && navigator.product === An; - } - function vr() { - return !vi() && !!er.getNavigator() && !!er.getDocument(); - } - function Ge() { - return rr() ? Kt.reactNative : vi() ? Kt.node : vr() ? Kt.browser : Kt.unknown; - } - function Qo() { - var e2; - try { - return rr() && typeof global < "u" && typeof (global == null ? void 0 : global.Application) < "u" ? (e2 = global.Application) == null ? void 0 : e2.applicationId : void 0; - } catch { - return; - } - } - function wn(e2, t) { - let r = Ir.parse(e2); - return r = mn(mn({}, r), t), e2 = Ir.stringify(r), e2; - } - function Jo() { - return Co.getWindowMetadata() || { name: "", description: "", url: "", icons: [""] }; - } - function Yo(e2, t) { - var r; - const i2 = Ge(), n3 = { protocol: e2, version: t, env: i2 }; - return i2 === "browser" && (n3.host = ((r = er.getLocation()) == null ? void 0 : r.host) || "unknown"), n3; - } - function xn() { - if (Ge() === Kt.reactNative && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u") { - const { OS: r, Version: i2 } = global.Platform; - return [r, i2].join("-"); - } - const e2 = Ro.detect(); - if (e2 === null) - return "unknown"; - const t = e2.os ? e2.os.replace(" ", "").toLowerCase() : "unknown"; - return e2.type === "browser" ? [t, e2.name, e2.version].join("-") : [t, e2.version].join("-"); - } - function Mn() { - var e2; - const t = Ge(); - return t === Kt.browser ? [t, ((e2 = er.getLocation()) == null ? void 0 : e2.host) || "unknown"].join(":") : t; - } - function En(e2, t, r) { - const i2 = xn(), n3 = Mn(); - return [[e2, t].join("-"), [yn, r].join("-"), i2, n3].join("/"); - } - function Go({ protocol: e2, version: t, relayUrl: r, sdkVersion: i2, auth: n3, projectId: o2, useOnCloseEvent: h5, bundleId: p3 }) { - const b4 = r.split("?"), g3 = En(e2, t, i2), w4 = { auth: n3, ua: g3, projectId: o2, useOnCloseEvent: h5 || void 0, origin: p3 || void 0 }, y4 = wn(b4[1] || "", w4); - return b4[0] + "?" + y4; - } - function Wo(e2) { - let t = (e2.match(/^[^:]+(?=:\/\/)/gi) || [])[0]; - const r = typeof t < "u" ? e2.split("://")[1] : e2; - return t = t === "wss" ? "https" : "http", [t, r].join("://"); - } - function Xo(e2, t, r) { - if (!e2[t] || typeof e2[t] !== r) - throw new Error(`Missing or invalid "${t}" param`); - } - function Sn(e2, t = pi) { - return Nn(e2.split(bn), t); - } - function Zo(e2) { - return Sn(e2).join(Rr); - } - function Ie(e2, t) { - return e2.filter((r) => t.includes(r)).length === e2.length; - } - function Nn(e2, t = pi) { - return e2.slice(Math.max(e2.length - t, 0)); - } - function $o(e2) { - return Object.fromEntries(e2.entries()); - } - function ts(e2) { - return new Map(Object.entries(e2)); - } - function es(e2, t) { - const r = {}; - return Object.keys(e2).forEach((i2) => { - r[i2] = t(e2[i2]); - }), r; - } - var rs = (e2) => e2; - function In(e2) { - return e2.trim().replace(/^\w/, (t) => t.toUpperCase()); - } - function is(e2) { - return e2.split(Rr).map((t) => In(t)).join(Rr); - } - function ns(e2 = tr.FIVE_MINUTES, t) { - const r = tr.toMiliseconds(e2 || tr.FIVE_MINUTES); - let i2, n3, o2; - return { resolve: (h5) => { - o2 && i2 && (clearTimeout(o2), i2(h5)); - }, reject: (h5) => { - o2 && n3 && (clearTimeout(o2), n3(h5)); - }, done: () => new Promise((h5, p3) => { - o2 = setTimeout(() => { - p3(new Error(t)); - }, r), i2 = h5, n3 = p3; - }) }; - } - function fs(e2, t, r) { - return new Promise(async (i2, n3) => { - const o2 = setTimeout(() => n3(new Error(r)), t); - try { - const h5 = await e2; - i2(h5); - } catch (h5) { - n3(h5); - } - clearTimeout(o2); - }); - } - function gi(e2, t) { - if (typeof t == "string" && t.startsWith(`${e2}:`)) - return t; - if (e2.toLowerCase() === "topic") { - if (typeof t != "string") - throw new Error('Value must be "string" for expirer target type: topic'); - return `topic:${t}`; - } else if (e2.toLowerCase() === "id") { - if (typeof t != "number") - throw new Error('Value must be "number" for expirer target type: id'); - return `id:${t}`; - } - throw new Error(`Unknown expirer target type: ${e2}`); - } - function os(e2) { - return gi("topic", e2); - } - function ss(e2) { - return gi("id", e2); - } - function as(e2) { - const [t, r] = e2.split(":"), i2 = { id: void 0, topic: void 0 }; - if (t === "topic" && typeof r == "string") - i2.topic = r; - else if (t === "id" && Number.isInteger(Number(r))) - i2.id = Number(r); - else - throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`); - return i2; - } - function us(e2, t) { - return tr.fromMiliseconds((t || Date.now()) + tr.toMiliseconds(e2)); - } - function hs(e2) { - return Date.now() >= tr.toMiliseconds(e2); - } - function cs(e2, t) { - return `${e2}${t ? `:${t}` : ""}`; - } - function ge(e2 = [], t = []) { - return [.../* @__PURE__ */ new Set([...e2, ...t])]; - } - async function ls2({ id: e2, topic: t, wcDeepLink: r }) { - try { - if (!r) - return; - const i2 = typeof r == "string" ? JSON.parse(r) : r; - let n3 = i2?.href; - if (typeof n3 != "string") - return; - n3.endsWith("/") && (n3 = n3.slice(0, -1)); - const o2 = `${n3}/wc?requestId=${e2}&sessionTopic=${t}`, h5 = Ge(); - h5 === Kt.browser ? o2.startsWith("https://") || o2.startsWith("http://") ? window.open(o2, "_blank", "noreferrer noopener") : window.open(o2, "_self", "noreferrer noopener") : h5 === Kt.reactNative && typeof (global == null ? void 0 : global.Linking) < "u" && await global.Linking.openURL(o2); - } catch (i2) { - console.error(i2); - } - } - async function ds(e2, t) { - try { - return await e2.getItem(t) || (vr() ? localStorage.getItem(t) : void 0); - } catch (r) { - console.error(r); - } - } - function mi(e2, t) { - return e2.filter((r) => t.includes(r)); - } - var _n = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; - function ps(e2) { - var t = e2.default; - if (typeof t == "function") { - var r = function() { - return t.apply(this, arguments); - }; - r.prototype = t.prototype; - } else - r = {}; - return Object.defineProperty(r, "__esModule", { value: true }), Object.keys(e2).forEach(function(i2) { - var n3 = Object.getOwnPropertyDescriptor(e2, i2); - Object.defineProperty(r, i2, n3.get ? n3 : { enumerable: true, get: function() { - return e2[i2]; - } }); - }), r; - } - var Bn = { exports: {} }; - (function(e2) { - (function() { - var t = "input is invalid type", r = "finalize already called", i2 = typeof window == "object", n3 = i2 ? window : {}; - n3.JS_SHA3_NO_WINDOW && (i2 = false); - var o2 = !i2 && typeof self == "object", h5 = !n3.JS_SHA3_NO_NODE_JS && typeof import_process.default == "object" && import_process.default.versions && import_process.default.versions.node; - h5 ? n3 = _n : o2 && (n3 = self); - var p3 = !n3.JS_SHA3_NO_COMMON_JS && true && e2.exports, b4 = !n3.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer < "u", g3 = "0123456789abcdef".split(""), w4 = [31, 7936, 2031616, 520093696], y4 = [4, 1024, 262144, 67108864], S4 = [1, 256, 65536, 16777216], I2 = [6, 1536, 393216, 100663296], N10 = [0, 8, 16, 24], R2 = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648], F = [224, 256, 384, 512], U2 = [128, 256], Q = ["hex", "buffer", "arrayBuffer", "array", "digest"], Bt = { 128: 168, 256: 136 }; - (n3.JS_SHA3_NO_NODE_JS || !Array.isArray) && (Array.isArray = function(u3) { - return Object.prototype.toString.call(u3) === "[object Array]"; - }), b4 && (n3.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView) && (ArrayBuffer.isView = function(u3) { - return typeof u3 == "object" && u3.buffer && u3.buffer.constructor === ArrayBuffer; - }); - for (var J = function(u3, E4, _4) { - return function(B2) { - return new s2(u3, E4, u3).update(B2)[_4](); - }; - }, H = function(u3, E4, _4) { - return function(B2, C3) { - return new s2(u3, E4, C3).update(B2)[_4](); - }; - }, L2 = function(u3, E4, _4) { - return function(B2, C3, D2, P2) { - return f4["cshake" + u3].update(B2, C3, D2, P2)[_4](); - }; - }, Tt = function(u3, E4, _4) { - return function(B2, C3, D2, P2) { - return f4["kmac" + u3].update(B2, C3, D2, P2)[_4](); - }; - }, W = function(u3, E4, _4, B2) { - for (var C3 = 0; C3 < Q.length; ++C3) { - var D2 = Q[C3]; - u3[D2] = E4(_4, B2, D2); - } - return u3; - }, Ot = function(u3, E4) { - var _4 = J(u3, E4, "hex"); - return _4.create = function() { - return new s2(u3, E4, u3); - }, _4.update = function(B2) { - return _4.create().update(B2); - }, W(_4, J, u3, E4); - }, Gt = function(u3, E4) { - var _4 = H(u3, E4, "hex"); - return _4.create = function(B2) { - return new s2(u3, E4, B2); - }, _4.update = function(B2, C3) { - return _4.create(C3).update(B2); - }, W(_4, H, u3, E4); - }, Y = function(u3, E4) { - var _4 = Bt[u3], B2 = L2(u3, E4, "hex"); - return B2.create = function(C3, D2, P2) { - return !D2 && !P2 ? f4["shake" + u3].create(C3) : new s2(u3, E4, C3).bytepad([D2, P2], _4); - }, B2.update = function(C3, D2, P2, O3) { - return B2.create(D2, P2, O3).update(C3); - }, W(B2, L2, u3, E4); - }, Wt = function(u3, E4) { - var _4 = Bt[u3], B2 = Tt(u3, E4, "hex"); - return B2.create = function(C3, D2, P2) { - return new v2(u3, E4, D2).bytepad(["KMAC", P2], _4).bytepad([C3], _4); - }, B2.update = function(C3, D2, P2, O3) { - return B2.create(C3, P2, O3).update(D2); - }, W(B2, Tt, u3, E4); - }, A2 = [{ name: "keccak", padding: S4, bits: F, createMethod: Ot }, { name: "sha3", padding: I2, bits: F, createMethod: Ot }, { name: "shake", padding: w4, bits: U2, createMethod: Gt }, { name: "cshake", padding: y4, bits: U2, createMethod: Y }, { name: "kmac", padding: y4, bits: U2, createMethod: Wt }], f4 = {}, a3 = [], c4 = 0; c4 < A2.length; ++c4) - for (var d3 = A2[c4], m3 = d3.bits, x3 = 0; x3 < m3.length; ++x3) { - var M = d3.name + "_" + m3[x3]; - if (a3.push(M), f4[M] = d3.createMethod(m3[x3], d3.padding), d3.name !== "sha3") { - var l4 = d3.name + m3[x3]; - a3.push(l4), f4[l4] = f4[M]; - } - } - function s2(u3, E4, _4) { - this.blocks = [], this.s = [], this.padding = E4, this.outputBits = _4, this.reset = true, this.finalized = false, this.block = 0, this.start = 0, this.blockCount = 1600 - (u3 << 1) >> 5, this.byteCount = this.blockCount << 2, this.outputBlocks = _4 >> 5, this.extraBytes = (_4 & 31) >> 3; - for (var B2 = 0; B2 < 50; ++B2) - this.s[B2] = 0; - } - s2.prototype.update = function(u3) { - if (this.finalized) - throw new Error(r); - var E4, _4 = typeof u3; - if (_4 !== "string") { - if (_4 === "object") { - if (u3 === null) - throw new Error(t); - if (b4 && u3.constructor === ArrayBuffer) - u3 = new Uint8Array(u3); - else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) - throw new Error(t); - } else - throw new Error(t); - E4 = true; - } - for (var B2 = this.blocks, C3 = this.byteCount, D2 = u3.length, P2 = this.blockCount, O3 = 0, Ct = this.s, T2, q2; O3 < D2; ) { - if (this.reset) - for (this.reset = false, B2[0] = this.block, T2 = 1; T2 < P2 + 1; ++T2) - B2[T2] = 0; - if (E4) - for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) - B2[T2 >> 2] |= u3[O3] << N10[T2++ & 3]; - else - for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) - q2 = u3.charCodeAt(O3), q2 < 128 ? B2[T2 >> 2] |= q2 << N10[T2++ & 3] : q2 < 2048 ? (B2[T2 >> 2] |= (192 | q2 >> 6) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : q2 < 55296 || q2 >= 57344 ? (B2[T2 >> 2] |= (224 | q2 >> 12) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : (q2 = 65536 + ((q2 & 1023) << 10 | u3.charCodeAt(++O3) & 1023), B2[T2 >> 2] |= (240 | q2 >> 18) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 12 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]); - if (this.lastByteIndex = T2, T2 >= C3) { - for (this.start = T2 - C3, this.block = B2[P2], T2 = 0; T2 < P2; ++T2) - Ct[T2] ^= B2[T2]; - k4(Ct), this.reset = true; - } else - this.start = T2; - } - return this; - }, s2.prototype.encode = function(u3, E4) { - var _4 = u3 & 255, B2 = 1, C3 = [_4]; - for (u3 = u3 >> 8, _4 = u3 & 255; _4 > 0; ) - C3.unshift(_4), u3 = u3 >> 8, _4 = u3 & 255, ++B2; - return E4 ? C3.push(B2) : C3.unshift(B2), this.update(C3), C3.length; - }, s2.prototype.encodeString = function(u3) { - var E4, _4 = typeof u3; - if (_4 !== "string") { - if (_4 === "object") { - if (u3 === null) - throw new Error(t); - if (b4 && u3.constructor === ArrayBuffer) - u3 = new Uint8Array(u3); - else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) - throw new Error(t); - } else - throw new Error(t); - E4 = true; - } - var B2 = 0, C3 = u3.length; - if (E4) - B2 = C3; - else - for (var D2 = 0; D2 < u3.length; ++D2) { - var P2 = u3.charCodeAt(D2); - P2 < 128 ? B2 += 1 : P2 < 2048 ? B2 += 2 : P2 < 55296 || P2 >= 57344 ? B2 += 3 : (P2 = 65536 + ((P2 & 1023) << 10 | u3.charCodeAt(++D2) & 1023), B2 += 4); - } - return B2 += this.encode(B2 * 8), this.update(u3), B2; - }, s2.prototype.bytepad = function(u3, E4) { - for (var _4 = this.encode(E4), B2 = 0; B2 < u3.length; ++B2) - _4 += this.encodeString(u3[B2]); - var C3 = E4 - _4 % E4, D2 = []; - return D2.length = C3, this.update(D2), this; - }, s2.prototype.finalize = function() { - if (!this.finalized) { - this.finalized = true; - var u3 = this.blocks, E4 = this.lastByteIndex, _4 = this.blockCount, B2 = this.s; - if (u3[E4 >> 2] |= this.padding[E4 & 3], this.lastByteIndex === this.byteCount) - for (u3[0] = u3[_4], E4 = 1; E4 < _4 + 1; ++E4) - u3[E4] = 0; - for (u3[_4 - 1] |= 2147483648, E4 = 0; E4 < _4; ++E4) - B2[E4] ^= u3[E4]; - k4(B2); - } - }, s2.prototype.toString = s2.prototype.hex = function() { - this.finalize(); - for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = "", O3; D2 < _4; ) { - for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) - O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15] + g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15] + g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15] + g3[O3 >> 28 & 15] + g3[O3 >> 24 & 15]; - D2 % u3 === 0 && (k4(E4), C3 = 0); - } - return B2 && (O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15], B2 > 1 && (P2 += g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15]), B2 > 2 && (P2 += g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15])), P2; - }, s2.prototype.arrayBuffer = function() { - this.finalize(); - var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = this.outputBits >> 3, O3; - B2 ? O3 = new ArrayBuffer(_4 + 1 << 2) : O3 = new ArrayBuffer(P2); - for (var Ct = new Uint32Array(O3); D2 < _4; ) { - for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) - Ct[D2] = E4[C3]; - D2 % u3 === 0 && k4(E4); - } - return B2 && (Ct[C3] = E4[C3], O3 = O3.slice(0, P2)), O3; - }, s2.prototype.buffer = s2.prototype.arrayBuffer, s2.prototype.digest = s2.prototype.array = function() { - this.finalize(); - for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = [], O3, Ct; D2 < _4; ) { - for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) - O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, P2[O3 + 1] = Ct >> 8 & 255, P2[O3 + 2] = Ct >> 16 & 255, P2[O3 + 3] = Ct >> 24 & 255; - D2 % u3 === 0 && k4(E4); - } - return B2 && (O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, B2 > 1 && (P2[O3 + 1] = Ct >> 8 & 255), B2 > 2 && (P2[O3 + 2] = Ct >> 16 & 255)), P2; - }; - function v2(u3, E4, _4) { - s2.call(this, u3, E4, _4); - } - v2.prototype = new s2(), v2.prototype.finalize = function() { - return this.encode(this.outputBits, true), s2.prototype.finalize.call(this); - }; - var k4 = function(u3) { - var E4, _4, B2, C3, D2, P2, O3, Ct, T2, q2, Pe, X, Z, Te, $, tt, Fe, et, rt, De, it, nt, Ue, ft, ot, ke, st, at, qe, ut, ht, Ke, ct, lt, He, dt, pt, Le, vt, gt, ze, mt, At, je, bt, yt, Ve, wt, xt, Qe, Mt, Et, Je, St, Nt, Ye, It, _t, xe, Me, Ee, Se, Ne; - for (B2 = 0; B2 < 48; B2 += 2) - C3 = u3[0] ^ u3[10] ^ u3[20] ^ u3[30] ^ u3[40], D2 = u3[1] ^ u3[11] ^ u3[21] ^ u3[31] ^ u3[41], P2 = u3[2] ^ u3[12] ^ u3[22] ^ u3[32] ^ u3[42], O3 = u3[3] ^ u3[13] ^ u3[23] ^ u3[33] ^ u3[43], Ct = u3[4] ^ u3[14] ^ u3[24] ^ u3[34] ^ u3[44], T2 = u3[5] ^ u3[15] ^ u3[25] ^ u3[35] ^ u3[45], q2 = u3[6] ^ u3[16] ^ u3[26] ^ u3[36] ^ u3[46], Pe = u3[7] ^ u3[17] ^ u3[27] ^ u3[37] ^ u3[47], X = u3[8] ^ u3[18] ^ u3[28] ^ u3[38] ^ u3[48], Z = u3[9] ^ u3[19] ^ u3[29] ^ u3[39] ^ u3[49], E4 = X ^ (P2 << 1 | O3 >>> 31), _4 = Z ^ (O3 << 1 | P2 >>> 31), u3[0] ^= E4, u3[1] ^= _4, u3[10] ^= E4, u3[11] ^= _4, u3[20] ^= E4, u3[21] ^= _4, u3[30] ^= E4, u3[31] ^= _4, u3[40] ^= E4, u3[41] ^= _4, E4 = C3 ^ (Ct << 1 | T2 >>> 31), _4 = D2 ^ (T2 << 1 | Ct >>> 31), u3[2] ^= E4, u3[3] ^= _4, u3[12] ^= E4, u3[13] ^= _4, u3[22] ^= E4, u3[23] ^= _4, u3[32] ^= E4, u3[33] ^= _4, u3[42] ^= E4, u3[43] ^= _4, E4 = P2 ^ (q2 << 1 | Pe >>> 31), _4 = O3 ^ (Pe << 1 | q2 >>> 31), u3[4] ^= E4, u3[5] ^= _4, u3[14] ^= E4, u3[15] ^= _4, u3[24] ^= E4, u3[25] ^= _4, u3[34] ^= E4, u3[35] ^= _4, u3[44] ^= E4, u3[45] ^= _4, E4 = Ct ^ (X << 1 | Z >>> 31), _4 = T2 ^ (Z << 1 | X >>> 31), u3[6] ^= E4, u3[7] ^= _4, u3[16] ^= E4, u3[17] ^= _4, u3[26] ^= E4, u3[27] ^= _4, u3[36] ^= E4, u3[37] ^= _4, u3[46] ^= E4, u3[47] ^= _4, E4 = q2 ^ (C3 << 1 | D2 >>> 31), _4 = Pe ^ (D2 << 1 | C3 >>> 31), u3[8] ^= E4, u3[9] ^= _4, u3[18] ^= E4, u3[19] ^= _4, u3[28] ^= E4, u3[29] ^= _4, u3[38] ^= E4, u3[39] ^= _4, u3[48] ^= E4, u3[49] ^= _4, Te = u3[0], $ = u3[1], yt = u3[11] << 4 | u3[10] >>> 28, Ve = u3[10] << 4 | u3[11] >>> 28, at = u3[20] << 3 | u3[21] >>> 29, qe = u3[21] << 3 | u3[20] >>> 29, Me = u3[31] << 9 | u3[30] >>> 23, Ee = u3[30] << 9 | u3[31] >>> 23, mt = u3[40] << 18 | u3[41] >>> 14, At = u3[41] << 18 | u3[40] >>> 14, lt = u3[2] << 1 | u3[3] >>> 31, He = u3[3] << 1 | u3[2] >>> 31, tt = u3[13] << 12 | u3[12] >>> 20, Fe = u3[12] << 12 | u3[13] >>> 20, wt = u3[22] << 10 | u3[23] >>> 22, xt = u3[23] << 10 | u3[22] >>> 22, ut = u3[33] << 13 | u3[32] >>> 19, ht = u3[32] << 13 | u3[33] >>> 19, Se = u3[42] << 2 | u3[43] >>> 30, Ne = u3[43] << 2 | u3[42] >>> 30, St = u3[5] << 30 | u3[4] >>> 2, Nt = u3[4] << 30 | u3[5] >>> 2, dt = u3[14] << 6 | u3[15] >>> 26, pt = u3[15] << 6 | u3[14] >>> 26, et = u3[25] << 11 | u3[24] >>> 21, rt = u3[24] << 11 | u3[25] >>> 21, Qe = u3[34] << 15 | u3[35] >>> 17, Mt = u3[35] << 15 | u3[34] >>> 17, Ke = u3[45] << 29 | u3[44] >>> 3, ct = u3[44] << 29 | u3[45] >>> 3, ft = u3[6] << 28 | u3[7] >>> 4, ot = u3[7] << 28 | u3[6] >>> 4, Ye = u3[17] << 23 | u3[16] >>> 9, It = u3[16] << 23 | u3[17] >>> 9, Le = u3[26] << 25 | u3[27] >>> 7, vt = u3[27] << 25 | u3[26] >>> 7, De = u3[36] << 21 | u3[37] >>> 11, it = u3[37] << 21 | u3[36] >>> 11, Et = u3[47] << 24 | u3[46] >>> 8, Je = u3[46] << 24 | u3[47] >>> 8, je = u3[8] << 27 | u3[9] >>> 5, bt = u3[9] << 27 | u3[8] >>> 5, ke = u3[18] << 20 | u3[19] >>> 12, st = u3[19] << 20 | u3[18] >>> 12, _t = u3[29] << 7 | u3[28] >>> 25, xe = u3[28] << 7 | u3[29] >>> 25, gt = u3[38] << 8 | u3[39] >>> 24, ze = u3[39] << 8 | u3[38] >>> 24, nt = u3[48] << 14 | u3[49] >>> 18, Ue = u3[49] << 14 | u3[48] >>> 18, u3[0] = Te ^ ~tt & et, u3[1] = $ ^ ~Fe & rt, u3[10] = ft ^ ~ke & at, u3[11] = ot ^ ~st & qe, u3[20] = lt ^ ~dt & Le, u3[21] = He ^ ~pt & vt, u3[30] = je ^ ~yt & wt, u3[31] = bt ^ ~Ve & xt, u3[40] = St ^ ~Ye & _t, u3[41] = Nt ^ ~It & xe, u3[2] = tt ^ ~et & De, u3[3] = Fe ^ ~rt & it, u3[12] = ke ^ ~at & ut, u3[13] = st ^ ~qe & ht, u3[22] = dt ^ ~Le & gt, u3[23] = pt ^ ~vt & ze, u3[32] = yt ^ ~wt & Qe, u3[33] = Ve ^ ~xt & Mt, u3[42] = Ye ^ ~_t & Me, u3[43] = It ^ ~xe & Ee, u3[4] = et ^ ~De & nt, u3[5] = rt ^ ~it & Ue, u3[14] = at ^ ~ut & Ke, u3[15] = qe ^ ~ht & ct, u3[24] = Le ^ ~gt & mt, u3[25] = vt ^ ~ze & At, u3[34] = wt ^ ~Qe & Et, u3[35] = xt ^ ~Mt & Je, u3[44] = _t ^ ~Me & Se, u3[45] = xe ^ ~Ee & Ne, u3[6] = De ^ ~nt & Te, u3[7] = it ^ ~Ue & $, u3[16] = ut ^ ~Ke & ft, u3[17] = ht ^ ~ct & ot, u3[26] = gt ^ ~mt & lt, u3[27] = ze ^ ~At & He, u3[36] = Qe ^ ~Et & je, u3[37] = Mt ^ ~Je & bt, u3[46] = Me ^ ~Se & St, u3[47] = Ee ^ ~Ne & Nt, u3[8] = nt ^ ~Te & tt, u3[9] = Ue ^ ~$ & Fe, u3[18] = Ke ^ ~ft & ke, u3[19] = ct ^ ~ot & st, u3[28] = mt ^ ~lt & dt, u3[29] = At ^ ~He & pt, u3[38] = Et ^ ~je & yt, u3[39] = Je ^ ~bt & Ve, u3[48] = Se ^ ~St & Ye, u3[49] = Ne ^ ~Nt & It, u3[0] ^= R2[B2], u3[1] ^= R2[B2 + 1]; - }; - if (p3) - e2.exports = f4; - else - for (c4 = 0; c4 < a3.length; ++c4) - n3[a3[c4]] = f4[a3[c4]]; - })(); - })(Bn); - var vs = Bn.exports; - var gs = "logger/5.7.0"; - var Rn = false; - var Cn = false; - var Cr = { debug: 1, default: 2, info: 2, warning: 3, error: 4, off: 5 }; - var On = Cr.default; - var Ai = null; - function ms() { - try { - const e2 = []; - if (["NFD", "NFC", "NFKD", "NFKC"].forEach((t) => { - try { - if ("test".normalize(t) !== "test") - throw new Error("bad normalize"); - } catch { - e2.push(t); - } - }), e2.length) - throw new Error("missing " + e2.join(", ")); - if (String.fromCharCode(233).normalize("NFD") !== String.fromCharCode(101, 769)) - throw new Error("broken implementation"); - } catch (e2) { - return e2.message; - } - return null; - } - var Pn = ms(); - var bi; - (function(e2) { - e2.DEBUG = "DEBUG", e2.INFO = "INFO", e2.WARNING = "WARNING", e2.ERROR = "ERROR", e2.OFF = "OFF"; - })(bi || (bi = {})); - var ee; - (function(e2) { - e2.UNKNOWN_ERROR = "UNKNOWN_ERROR", e2.NOT_IMPLEMENTED = "NOT_IMPLEMENTED", e2.UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION", e2.NETWORK_ERROR = "NETWORK_ERROR", e2.SERVER_ERROR = "SERVER_ERROR", e2.TIMEOUT = "TIMEOUT", e2.BUFFER_OVERRUN = "BUFFER_OVERRUN", e2.NUMERIC_FAULT = "NUMERIC_FAULT", e2.MISSING_NEW = "MISSING_NEW", e2.INVALID_ARGUMENT = "INVALID_ARGUMENT", e2.MISSING_ARGUMENT = "MISSING_ARGUMENT", e2.UNEXPECTED_ARGUMENT = "UNEXPECTED_ARGUMENT", e2.CALL_EXCEPTION = "CALL_EXCEPTION", e2.INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS", e2.NONCE_EXPIRED = "NONCE_EXPIRED", e2.REPLACEMENT_UNDERPRICED = "REPLACEMENT_UNDERPRICED", e2.UNPREDICTABLE_GAS_LIMIT = "UNPREDICTABLE_GAS_LIMIT", e2.TRANSACTION_REPLACED = "TRANSACTION_REPLACED", e2.ACTION_REJECTED = "ACTION_REJECTED"; - })(ee || (ee = {})); - var Tn = "0123456789abcdef"; - var z3 = class _z { - constructor(t) { - Object.defineProperty(this, "version", { enumerable: true, value: t, writable: false }); - } - _log(t, r) { - const i2 = t.toLowerCase(); - Cr[i2] == null && this.throwArgumentError("invalid log level name", "logLevel", t), !(On > Cr[i2]) && console.log.apply(console, r); - } - debug(...t) { - this._log(_z.levels.DEBUG, t); - } - info(...t) { - this._log(_z.levels.INFO, t); - } - warn(...t) { - this._log(_z.levels.WARNING, t); - } - makeError(t, r, i2) { - if (Cn) - return this.makeError("censored error", r, {}); - r || (r = _z.errors.UNKNOWN_ERROR), i2 || (i2 = {}); - const n3 = []; - Object.keys(i2).forEach((b4) => { - const g3 = i2[b4]; - try { - if (g3 instanceof Uint8Array) { - let w4 = ""; - for (let y4 = 0; y4 < g3.length; y4++) - w4 += Tn[g3[y4] >> 4], w4 += Tn[g3[y4] & 15]; - n3.push(b4 + "=Uint8Array(0x" + w4 + ")"); - } else - n3.push(b4 + "=" + JSON.stringify(g3)); - } catch { - n3.push(b4 + "=" + JSON.stringify(i2[b4].toString())); - } - }), n3.push(`code=${r}`), n3.push(`version=${this.version}`); - const o2 = t; - let h5 = ""; - switch (r) { - case ee.NUMERIC_FAULT: { - h5 = "NUMERIC_FAULT"; - const b4 = t; - switch (b4) { - case "overflow": - case "underflow": - case "division-by-zero": - h5 += "-" + b4; - break; - case "negative-power": - case "negative-width": - h5 += "-unsupported"; - break; - case "unbound-bitwise-result": - h5 += "-unbound-result"; - break; - } - break; - } - case ee.CALL_EXCEPTION: - case ee.INSUFFICIENT_FUNDS: - case ee.MISSING_NEW: - case ee.NONCE_EXPIRED: - case ee.REPLACEMENT_UNDERPRICED: - case ee.TRANSACTION_REPLACED: - case ee.UNPREDICTABLE_GAS_LIMIT: - h5 = r; - break; - } - h5 && (t += " [ See: https://links.ethers.org/v5-errors-" + h5 + " ]"), n3.length && (t += " (" + n3.join(", ") + ")"); - const p3 = new Error(t); - return p3.reason = o2, p3.code = r, Object.keys(i2).forEach(function(b4) { - p3[b4] = i2[b4]; - }), p3; - } - throwError(t, r, i2) { - throw this.makeError(t, r, i2); - } - throwArgumentError(t, r, i2) { - return this.throwError(t, _z.errors.INVALID_ARGUMENT, { argument: r, value: i2 }); - } - assert(t, r, i2, n3) { - t || this.throwError(r, i2, n3); - } - assertArgument(t, r, i2, n3) { - t || this.throwArgumentError(r, i2, n3); - } - checkNormalize(t) { - Pn && this.throwError("platform missing String.prototype.normalize", _z.errors.UNSUPPORTED_OPERATION, { operation: "String.prototype.normalize", form: Pn }); - } - checkSafeUint53(t, r) { - typeof t == "number" && (r == null && (r = "value not safe"), (t < 0 || t >= 9007199254740991) && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "out-of-safe-range", value: t }), t % 1 && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "non-integer", value: t })); - } - checkArgumentCount(t, r, i2) { - i2 ? i2 = ": " + i2 : i2 = "", t < r && this.throwError("missing argument" + i2, _z.errors.MISSING_ARGUMENT, { count: t, expectedCount: r }), t > r && this.throwError("too many arguments" + i2, _z.errors.UNEXPECTED_ARGUMENT, { count: t, expectedCount: r }); - } - checkNew(t, r) { - (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); - } - checkAbstract(t, r) { - t === r ? this.throwError("cannot instantiate abstract class " + JSON.stringify(r.name) + " directly; use a sub-class", _z.errors.UNSUPPORTED_OPERATION, { name: t.name, operation: "new" }) : (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); - } - static globalLogger() { - return Ai || (Ai = new _z(gs)), Ai; - } - static setCensorship(t, r) { - if (!t && r && this.globalLogger().throwError("cannot permanently disable censorship", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }), Rn) { - if (!t) - return; - this.globalLogger().throwError("error censorship permanent", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); - } - Cn = !!t, Rn = !!r; - } - static setLogLevel(t) { - const r = Cr[t.toLowerCase()]; - if (r == null) { - _z.globalLogger().warn("invalid log level - " + t); - return; - } - On = r; - } - static from(t) { - return new _z(t); - } - }; - z3.errors = ee, z3.levels = bi; - var As = "bytes/5.7.0"; - var Ft = new z3(As); - function Fn(e2) { - return !!e2.toHexString; - } - function ir(e2) { - return e2.slice || (e2.slice = function() { - const t = Array.prototype.slice.call(arguments); - return ir(new Uint8Array(Array.prototype.slice.apply(e2, t))); - }), e2; - } - function bs(e2) { - return Qt(e2) && !(e2.length % 2) || nr(e2); - } - function Dn(e2) { - return typeof e2 == "number" && e2 == e2 && e2 % 1 === 0; - } - function nr(e2) { - if (e2 == null) - return false; - if (e2.constructor === Uint8Array) - return true; - if (typeof e2 == "string" || !Dn(e2.length) || e2.length < 0) - return false; - for (let t = 0; t < e2.length; t++) { - const r = e2[t]; - if (!Dn(r) || r < 0 || r >= 256) - return false; - } - return true; - } - function Pt(e2, t) { - if (t || (t = {}), typeof e2 == "number") { - Ft.checkSafeUint53(e2, "invalid arrayify value"); - const r = []; - for (; e2; ) - r.unshift(e2 & 255), e2 = parseInt(String(e2 / 256)); - return r.length === 0 && r.push(0), ir(new Uint8Array(r)); - } - if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2) && (e2 = e2.toHexString()), Qt(e2)) { - let r = e2.substring(2); - r.length % 2 && (t.hexPad === "left" ? r = "0" + r : t.hexPad === "right" ? r += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)); - const i2 = []; - for (let n3 = 0; n3 < r.length; n3 += 2) - i2.push(parseInt(r.substring(n3, n3 + 2), 16)); - return ir(new Uint8Array(i2)); - } - return nr(e2) ? ir(new Uint8Array(e2)) : Ft.throwArgumentError("invalid arrayify value", "value", e2); - } - function ys(e2) { - const t = e2.map((n3) => Pt(n3)), r = t.reduce((n3, o2) => n3 + o2.length, 0), i2 = new Uint8Array(r); - return t.reduce((n3, o2) => (i2.set(o2, n3), n3 + o2.length), 0), ir(i2); - } - function ws(e2, t) { - e2 = Pt(e2), e2.length > t && Ft.throwArgumentError("value out of range", "value", arguments[0]); - const r = new Uint8Array(t); - return r.set(e2, t - e2.length), ir(r); - } - function Qt(e2, t) { - return !(typeof e2 != "string" || !e2.match(/^0x[0-9A-Fa-f]*$/) || t && e2.length !== 2 + 2 * t); - } - var yi = "0123456789abcdef"; - function Ht(e2, t) { - if (t || (t = {}), typeof e2 == "number") { - Ft.checkSafeUint53(e2, "invalid hexlify value"); - let r = ""; - for (; e2; ) - r = yi[e2 & 15] + r, e2 = Math.floor(e2 / 16); - return r.length ? (r.length % 2 && (r = "0" + r), "0x" + r) : "0x00"; - } - if (typeof e2 == "bigint") - return e2 = e2.toString(16), e2.length % 2 ? "0x0" + e2 : "0x" + e2; - if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2)) - return e2.toHexString(); - if (Qt(e2)) - return e2.length % 2 && (t.hexPad === "left" ? e2 = "0x0" + e2.substring(2) : t.hexPad === "right" ? e2 += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)), e2.toLowerCase(); - if (nr(e2)) { - let r = "0x"; - for (let i2 = 0; i2 < e2.length; i2++) { - let n3 = e2[i2]; - r += yi[(n3 & 240) >> 4] + yi[n3 & 15]; - } - return r; - } - return Ft.throwArgumentError("invalid hexlify value", "value", e2); - } - function xs(e2) { - if (typeof e2 != "string") - e2 = Ht(e2); - else if (!Qt(e2) || e2.length % 2) - return null; - return (e2.length - 2) / 2; - } - function Un(e2, t, r) { - return typeof e2 != "string" ? e2 = Ht(e2) : (!Qt(e2) || e2.length % 2) && Ft.throwArgumentError("invalid hexData", "value", e2), t = 2 + 2 * t, r != null ? "0x" + e2.substring(t, 2 + 2 * r) : "0x" + e2.substring(t); - } - function fe(e2, t) { - for (typeof e2 != "string" ? e2 = Ht(e2) : Qt(e2) || Ft.throwArgumentError("invalid hex string", "value", e2), e2.length > 2 * t + 2 && Ft.throwArgumentError("value out of range", "value", arguments[1]); e2.length < 2 * t + 2; ) - e2 = "0x0" + e2.substring(2); - return e2; - } - function kn(e2) { - const t = { r: "0x", s: "0x", _vs: "0x", recoveryParam: 0, v: 0, yParityAndS: "0x", compact: "0x" }; - if (bs(e2)) { - let r = Pt(e2); - r.length === 64 ? (t.v = 27 + (r[32] >> 7), r[32] &= 127, t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64))) : r.length === 65 ? (t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64)), t.v = r[64]) : Ft.throwArgumentError("invalid signature string", "signature", e2), t.v < 27 && (t.v === 0 || t.v === 1 ? t.v += 27 : Ft.throwArgumentError("signature invalid v byte", "signature", e2)), t.recoveryParam = 1 - t.v % 2, t.recoveryParam && (r[32] |= 128), t._vs = Ht(r.slice(32, 64)); - } else { - if (t.r = e2.r, t.s = e2.s, t.v = e2.v, t.recoveryParam = e2.recoveryParam, t._vs = e2._vs, t._vs != null) { - const n3 = ws(Pt(t._vs), 32); - t._vs = Ht(n3); - const o2 = n3[0] >= 128 ? 1 : 0; - t.recoveryParam == null ? t.recoveryParam = o2 : t.recoveryParam !== o2 && Ft.throwArgumentError("signature recoveryParam mismatch _vs", "signature", e2), n3[0] &= 127; - const h5 = Ht(n3); - t.s == null ? t.s = h5 : t.s !== h5 && Ft.throwArgumentError("signature v mismatch _vs", "signature", e2); - } - if (t.recoveryParam == null) - t.v == null ? Ft.throwArgumentError("signature missing v and recoveryParam", "signature", e2) : t.v === 0 || t.v === 1 ? t.recoveryParam = t.v : t.recoveryParam = 1 - t.v % 2; - else if (t.v == null) - t.v = 27 + t.recoveryParam; - else { - const n3 = t.v === 0 || t.v === 1 ? t.v : 1 - t.v % 2; - t.recoveryParam !== n3 && Ft.throwArgumentError("signature recoveryParam mismatch v", "signature", e2); - } - t.r == null || !Qt(t.r) ? Ft.throwArgumentError("signature missing or invalid r", "signature", e2) : t.r = fe(t.r, 32), t.s == null || !Qt(t.s) ? Ft.throwArgumentError("signature missing or invalid s", "signature", e2) : t.s = fe(t.s, 32); - const r = Pt(t.s); - r[0] >= 128 && Ft.throwArgumentError("signature s out of range", "signature", e2), t.recoveryParam && (r[0] |= 128); - const i2 = Ht(r); - t._vs && (Qt(t._vs) || Ft.throwArgumentError("signature invalid _vs", "signature", e2), t._vs = fe(t._vs, 32)), t._vs == null ? t._vs = i2 : t._vs !== i2 && Ft.throwArgumentError("signature _vs mismatch v and s", "signature", e2); - } - return t.yParityAndS = t._vs, t.compact = t.r + t.yParityAndS.substring(2), t; - } - function wi(e2) { - return "0x" + vs.keccak_256(Pt(e2)); - } - var qn = { exports: {} }; - var Ms = {}; - var Es = Object.freeze({ __proto__: null, default: Ms }); - var Ss = ps(Es); - (function(e2) { - (function(t, r) { - function i2(A2, f4) { - if (!A2) - throw new Error(f4 || "Assertion failed"); - } - function n3(A2, f4) { - A2.super_ = f4; - var a3 = function() { - }; - a3.prototype = f4.prototype, A2.prototype = new a3(), A2.prototype.constructor = A2; - } - function o2(A2, f4, a3) { - if (o2.isBN(A2)) - return A2; - this.negative = 0, this.words = null, this.length = 0, this.red = null, A2 !== null && ((f4 === "le" || f4 === "be") && (a3 = f4, f4 = 10), this._init(A2 || 0, f4 || 10, a3 || "be")); - } - typeof t == "object" ? t.exports = o2 : r.BN = o2, o2.BN = o2, o2.wordSize = 26; - var h5; - try { - typeof window < "u" && typeof window.Buffer < "u" ? h5 = window.Buffer : h5 = Ss.Buffer; - } catch { - } - o2.isBN = function(f4) { - return f4 instanceof o2 ? true : f4 !== null && typeof f4 == "object" && f4.constructor.wordSize === o2.wordSize && Array.isArray(f4.words); - }, o2.max = function(f4, a3) { - return f4.cmp(a3) > 0 ? f4 : a3; - }, o2.min = function(f4, a3) { - return f4.cmp(a3) < 0 ? f4 : a3; - }, o2.prototype._init = function(f4, a3, c4) { - if (typeof f4 == "number") - return this._initNumber(f4, a3, c4); - if (typeof f4 == "object") - return this._initArray(f4, a3, c4); - a3 === "hex" && (a3 = 16), i2(a3 === (a3 | 0) && a3 >= 2 && a3 <= 36), f4 = f4.toString().replace(/\s+/g, ""); - var d3 = 0; - f4[0] === "-" && (d3++, this.negative = 1), d3 < f4.length && (a3 === 16 ? this._parseHex(f4, d3, c4) : (this._parseBase(f4, a3, d3), c4 === "le" && this._initArray(this.toArray(), a3, c4))); - }, o2.prototype._initNumber = function(f4, a3, c4) { - f4 < 0 && (this.negative = 1, f4 = -f4), f4 < 67108864 ? (this.words = [f4 & 67108863], this.length = 1) : f4 < 4503599627370496 ? (this.words = [f4 & 67108863, f4 / 67108864 & 67108863], this.length = 2) : (i2(f4 < 9007199254740992), this.words = [f4 & 67108863, f4 / 67108864 & 67108863, 1], this.length = 3), c4 === "le" && this._initArray(this.toArray(), a3, c4); - }, o2.prototype._initArray = function(f4, a3, c4) { - if (i2(typeof f4.length == "number"), f4.length <= 0) - return this.words = [0], this.length = 1, this; - this.length = Math.ceil(f4.length / 3), this.words = new Array(this.length); - for (var d3 = 0; d3 < this.length; d3++) - this.words[d3] = 0; - var m3, x3, M = 0; - if (c4 === "be") - for (d3 = f4.length - 1, m3 = 0; d3 >= 0; d3 -= 3) - x3 = f4[d3] | f4[d3 - 1] << 8 | f4[d3 - 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); - else if (c4 === "le") - for (d3 = 0, m3 = 0; d3 < f4.length; d3 += 3) - x3 = f4[d3] | f4[d3 + 1] << 8 | f4[d3 + 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); - return this._strip(); - }; - function p3(A2, f4) { - var a3 = A2.charCodeAt(f4); - if (a3 >= 48 && a3 <= 57) - return a3 - 48; - if (a3 >= 65 && a3 <= 70) - return a3 - 55; - if (a3 >= 97 && a3 <= 102) - return a3 - 87; - i2(false, "Invalid character in " + A2); - } - function b4(A2, f4, a3) { - var c4 = p3(A2, a3); - return a3 - 1 >= f4 && (c4 |= p3(A2, a3 - 1) << 4), c4; - } - o2.prototype._parseHex = function(f4, a3, c4) { - this.length = Math.ceil((f4.length - a3) / 6), this.words = new Array(this.length); - for (var d3 = 0; d3 < this.length; d3++) - this.words[d3] = 0; - var m3 = 0, x3 = 0, M; - if (c4 === "be") - for (d3 = f4.length - 1; d3 >= a3; d3 -= 2) - M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; - else { - var l4 = f4.length - a3; - for (d3 = l4 % 2 === 0 ? a3 + 1 : a3; d3 < f4.length; d3 += 2) - M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; - } - this._strip(); - }; - function g3(A2, f4, a3, c4) { - for (var d3 = 0, m3 = 0, x3 = Math.min(A2.length, a3), M = f4; M < x3; M++) { - var l4 = A2.charCodeAt(M) - 48; - d3 *= c4, l4 >= 49 ? m3 = l4 - 49 + 10 : l4 >= 17 ? m3 = l4 - 17 + 10 : m3 = l4, i2(l4 >= 0 && m3 < c4, "Invalid character"), d3 += m3; - } - return d3; - } - o2.prototype._parseBase = function(f4, a3, c4) { - this.words = [0], this.length = 1; - for (var d3 = 0, m3 = 1; m3 <= 67108863; m3 *= a3) - d3++; - d3--, m3 = m3 / a3 | 0; - for (var x3 = f4.length - c4, M = x3 % d3, l4 = Math.min(x3, x3 - M) + c4, s2 = 0, v2 = c4; v2 < l4; v2 += d3) - s2 = g3(f4, v2, v2 + d3, a3), this.imuln(m3), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); - if (M !== 0) { - var k4 = 1; - for (s2 = g3(f4, v2, f4.length, a3), v2 = 0; v2 < M; v2++) - k4 *= a3; - this.imuln(k4), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); - } - this._strip(); - }, o2.prototype.copy = function(f4) { - f4.words = new Array(this.length); - for (var a3 = 0; a3 < this.length; a3++) - f4.words[a3] = this.words[a3]; - f4.length = this.length, f4.negative = this.negative, f4.red = this.red; - }; - function w4(A2, f4) { - A2.words = f4.words, A2.length = f4.length, A2.negative = f4.negative, A2.red = f4.red; - } - if (o2.prototype._move = function(f4) { - w4(f4, this); - }, o2.prototype.clone = function() { - var f4 = new o2(null); - return this.copy(f4), f4; - }, o2.prototype._expand = function(f4) { - for (; this.length < f4; ) - this.words[this.length++] = 0; - return this; - }, o2.prototype._strip = function() { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) - this.length--; - return this._normSign(); - }, o2.prototype._normSign = function() { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }, typeof Symbol < "u" && typeof Symbol.for == "function") - try { - o2.prototype[Symbol.for("nodejs.util.inspect.custom")] = y4; - } catch { - o2.prototype.inspect = y4; - } - else - o2.prototype.inspect = y4; - function y4() { - return (this.red ? ""; - } - var S4 = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], I2 = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], N10 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; - o2.prototype.toString = function(f4, a3) { - f4 = f4 || 10, a3 = a3 | 0 || 1; - var c4; - if (f4 === 16 || f4 === "hex") { - c4 = ""; - for (var d3 = 0, m3 = 0, x3 = 0; x3 < this.length; x3++) { - var M = this.words[x3], l4 = ((M << d3 | m3) & 16777215).toString(16); - m3 = M >>> 24 - d3 & 16777215, d3 += 2, d3 >= 26 && (d3 -= 26, x3--), m3 !== 0 || x3 !== this.length - 1 ? c4 = S4[6 - l4.length] + l4 + c4 : c4 = l4 + c4; - } - for (m3 !== 0 && (c4 = m3.toString(16) + c4); c4.length % a3 !== 0; ) - c4 = "0" + c4; - return this.negative !== 0 && (c4 = "-" + c4), c4; - } - if (f4 === (f4 | 0) && f4 >= 2 && f4 <= 36) { - var s2 = I2[f4], v2 = N10[f4]; - c4 = ""; - var k4 = this.clone(); - for (k4.negative = 0; !k4.isZero(); ) { - var u3 = k4.modrn(v2).toString(f4); - k4 = k4.idivn(v2), k4.isZero() ? c4 = u3 + c4 : c4 = S4[s2 - u3.length] + u3 + c4; - } - for (this.isZero() && (c4 = "0" + c4); c4.length % a3 !== 0; ) - c4 = "0" + c4; - return this.negative !== 0 && (c4 = "-" + c4), c4; - } - i2(false, "Base should be between 2 and 36"); - }, o2.prototype.toNumber = function() { - var f4 = this.words[0]; - return this.length === 2 ? f4 += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? f4 += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && i2(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -f4 : f4; - }, o2.prototype.toJSON = function() { - return this.toString(16, 2); - }, h5 && (o2.prototype.toBuffer = function(f4, a3) { - return this.toArrayLike(h5, f4, a3); - }), o2.prototype.toArray = function(f4, a3) { - return this.toArrayLike(Array, f4, a3); - }; - var R2 = function(f4, a3) { - return f4.allocUnsafe ? f4.allocUnsafe(a3) : new f4(a3); - }; - o2.prototype.toArrayLike = function(f4, a3, c4) { - this._strip(); - var d3 = this.byteLength(), m3 = c4 || Math.max(1, d3); - i2(d3 <= m3, "byte array longer than desired length"), i2(m3 > 0, "Requested array length <= 0"); - var x3 = R2(f4, m3), M = a3 === "le" ? "LE" : "BE"; - return this["_toArrayLike" + M](x3, d3), x3; - }, o2.prototype._toArrayLikeLE = function(f4, a3) { - for (var c4 = 0, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { - var M = this.words[m3] << x3 | d3; - f4[c4++] = M & 255, c4 < f4.length && (f4[c4++] = M >> 8 & 255), c4 < f4.length && (f4[c4++] = M >> 16 & 255), x3 === 6 ? (c4 < f4.length && (f4[c4++] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); - } - if (c4 < f4.length) - for (f4[c4++] = d3; c4 < f4.length; ) - f4[c4++] = 0; - }, o2.prototype._toArrayLikeBE = function(f4, a3) { - for (var c4 = f4.length - 1, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { - var M = this.words[m3] << x3 | d3; - f4[c4--] = M & 255, c4 >= 0 && (f4[c4--] = M >> 8 & 255), c4 >= 0 && (f4[c4--] = M >> 16 & 255), x3 === 6 ? (c4 >= 0 && (f4[c4--] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); - } - if (c4 >= 0) - for (f4[c4--] = d3; c4 >= 0; ) - f4[c4--] = 0; - }, Math.clz32 ? o2.prototype._countBits = function(f4) { - return 32 - Math.clz32(f4); - } : o2.prototype._countBits = function(f4) { - var a3 = f4, c4 = 0; - return a3 >= 4096 && (c4 += 13, a3 >>>= 13), a3 >= 64 && (c4 += 7, a3 >>>= 7), a3 >= 8 && (c4 += 4, a3 >>>= 4), a3 >= 2 && (c4 += 2, a3 >>>= 2), c4 + a3; - }, o2.prototype._zeroBits = function(f4) { - if (f4 === 0) - return 26; - var a3 = f4, c4 = 0; - return a3 & 8191 || (c4 += 13, a3 >>>= 13), a3 & 127 || (c4 += 7, a3 >>>= 7), a3 & 15 || (c4 += 4, a3 >>>= 4), a3 & 3 || (c4 += 2, a3 >>>= 2), a3 & 1 || c4++, c4; - }, o2.prototype.bitLength = function() { - var f4 = this.words[this.length - 1], a3 = this._countBits(f4); - return (this.length - 1) * 26 + a3; - }; - function F(A2) { - for (var f4 = new Array(A2.bitLength()), a3 = 0; a3 < f4.length; a3++) { - var c4 = a3 / 26 | 0, d3 = a3 % 26; - f4[a3] = A2.words[c4] >>> d3 & 1; - } - return f4; - } - o2.prototype.zeroBits = function() { - if (this.isZero()) - return 0; - for (var f4 = 0, a3 = 0; a3 < this.length; a3++) { - var c4 = this._zeroBits(this.words[a3]); - if (f4 += c4, c4 !== 26) - break; - } - return f4; - }, o2.prototype.byteLength = function() { - return Math.ceil(this.bitLength() / 8); - }, o2.prototype.toTwos = function(f4) { - return this.negative !== 0 ? this.abs().inotn(f4).iaddn(1) : this.clone(); - }, o2.prototype.fromTwos = function(f4) { - return this.testn(f4 - 1) ? this.notn(f4).iaddn(1).ineg() : this.clone(); - }, o2.prototype.isNeg = function() { - return this.negative !== 0; - }, o2.prototype.neg = function() { - return this.clone().ineg(); - }, o2.prototype.ineg = function() { - return this.isZero() || (this.negative ^= 1), this; - }, o2.prototype.iuor = function(f4) { - for (; this.length < f4.length; ) - this.words[this.length++] = 0; - for (var a3 = 0; a3 < f4.length; a3++) - this.words[a3] = this.words[a3] | f4.words[a3]; - return this._strip(); - }, o2.prototype.ior = function(f4) { - return i2((this.negative | f4.negative) === 0), this.iuor(f4); - }, o2.prototype.or = function(f4) { - return this.length > f4.length ? this.clone().ior(f4) : f4.clone().ior(this); - }, o2.prototype.uor = function(f4) { - return this.length > f4.length ? this.clone().iuor(f4) : f4.clone().iuor(this); - }, o2.prototype.iuand = function(f4) { - var a3; - this.length > f4.length ? a3 = f4 : a3 = this; - for (var c4 = 0; c4 < a3.length; c4++) - this.words[c4] = this.words[c4] & f4.words[c4]; - return this.length = a3.length, this._strip(); - }, o2.prototype.iand = function(f4) { - return i2((this.negative | f4.negative) === 0), this.iuand(f4); - }, o2.prototype.and = function(f4) { - return this.length > f4.length ? this.clone().iand(f4) : f4.clone().iand(this); - }, o2.prototype.uand = function(f4) { - return this.length > f4.length ? this.clone().iuand(f4) : f4.clone().iuand(this); - }, o2.prototype.iuxor = function(f4) { - var a3, c4; - this.length > f4.length ? (a3 = this, c4 = f4) : (a3 = f4, c4 = this); - for (var d3 = 0; d3 < c4.length; d3++) - this.words[d3] = a3.words[d3] ^ c4.words[d3]; - if (this !== a3) - for (; d3 < a3.length; d3++) - this.words[d3] = a3.words[d3]; - return this.length = a3.length, this._strip(); - }, o2.prototype.ixor = function(f4) { - return i2((this.negative | f4.negative) === 0), this.iuxor(f4); - }, o2.prototype.xor = function(f4) { - return this.length > f4.length ? this.clone().ixor(f4) : f4.clone().ixor(this); - }, o2.prototype.uxor = function(f4) { - return this.length > f4.length ? this.clone().iuxor(f4) : f4.clone().iuxor(this); - }, o2.prototype.inotn = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = Math.ceil(f4 / 26) | 0, c4 = f4 % 26; - this._expand(a3), c4 > 0 && a3--; - for (var d3 = 0; d3 < a3; d3++) - this.words[d3] = ~this.words[d3] & 67108863; - return c4 > 0 && (this.words[d3] = ~this.words[d3] & 67108863 >> 26 - c4), this._strip(); - }, o2.prototype.notn = function(f4) { - return this.clone().inotn(f4); - }, o2.prototype.setn = function(f4, a3) { - i2(typeof f4 == "number" && f4 >= 0); - var c4 = f4 / 26 | 0, d3 = f4 % 26; - return this._expand(c4 + 1), a3 ? this.words[c4] = this.words[c4] | 1 << d3 : this.words[c4] = this.words[c4] & ~(1 << d3), this._strip(); - }, o2.prototype.iadd = function(f4) { - var a3; - if (this.negative !== 0 && f4.negative === 0) - return this.negative = 0, a3 = this.isub(f4), this.negative ^= 1, this._normSign(); - if (this.negative === 0 && f4.negative !== 0) - return f4.negative = 0, a3 = this.isub(f4), f4.negative = 1, a3._normSign(); - var c4, d3; - this.length > f4.length ? (c4 = this, d3 = f4) : (c4 = f4, d3 = this); - for (var m3 = 0, x3 = 0; x3 < d3.length; x3++) - a3 = (c4.words[x3] | 0) + (d3.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; - for (; m3 !== 0 && x3 < c4.length; x3++) - a3 = (c4.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; - if (this.length = c4.length, m3 !== 0) - this.words[this.length] = m3, this.length++; - else if (c4 !== this) - for (; x3 < c4.length; x3++) - this.words[x3] = c4.words[x3]; - return this; - }, o2.prototype.add = function(f4) { - var a3; - return f4.negative !== 0 && this.negative === 0 ? (f4.negative = 0, a3 = this.sub(f4), f4.negative ^= 1, a3) : f4.negative === 0 && this.negative !== 0 ? (this.negative = 0, a3 = f4.sub(this), this.negative = 1, a3) : this.length > f4.length ? this.clone().iadd(f4) : f4.clone().iadd(this); - }, o2.prototype.isub = function(f4) { - if (f4.negative !== 0) { - f4.negative = 0; - var a3 = this.iadd(f4); - return f4.negative = 1, a3._normSign(); - } else if (this.negative !== 0) - return this.negative = 0, this.iadd(f4), this.negative = 1, this._normSign(); - var c4 = this.cmp(f4); - if (c4 === 0) - return this.negative = 0, this.length = 1, this.words[0] = 0, this; - var d3, m3; - c4 > 0 ? (d3 = this, m3 = f4) : (d3 = f4, m3 = this); - for (var x3 = 0, M = 0; M < m3.length; M++) - a3 = (d3.words[M] | 0) - (m3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; - for (; x3 !== 0 && M < d3.length; M++) - a3 = (d3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; - if (x3 === 0 && M < d3.length && d3 !== this) - for (; M < d3.length; M++) - this.words[M] = d3.words[M]; - return this.length = Math.max(this.length, M), d3 !== this && (this.negative = 1), this._strip(); - }, o2.prototype.sub = function(f4) { - return this.clone().isub(f4); - }; - function U2(A2, f4, a3) { - a3.negative = f4.negative ^ A2.negative; - var c4 = A2.length + f4.length | 0; - a3.length = c4, c4 = c4 - 1 | 0; - var d3 = A2.words[0] | 0, m3 = f4.words[0] | 0, x3 = d3 * m3, M = x3 & 67108863, l4 = x3 / 67108864 | 0; - a3.words[0] = M; - for (var s2 = 1; s2 < c4; s2++) { - for (var v2 = l4 >>> 26, k4 = l4 & 67108863, u3 = Math.min(s2, f4.length - 1), E4 = Math.max(0, s2 - A2.length + 1); E4 <= u3; E4++) { - var _4 = s2 - E4 | 0; - d3 = A2.words[_4] | 0, m3 = f4.words[E4] | 0, x3 = d3 * m3 + k4, v2 += x3 / 67108864 | 0, k4 = x3 & 67108863; - } - a3.words[s2] = k4 | 0, l4 = v2 | 0; - } - return l4 !== 0 ? a3.words[s2] = l4 | 0 : a3.length--, a3._strip(); - } - var Q = function(f4, a3, c4) { - var d3 = f4.words, m3 = a3.words, x3 = c4.words, M = 0, l4, s2, v2, k4 = d3[0] | 0, u3 = k4 & 8191, E4 = k4 >>> 13, _4 = d3[1] | 0, B2 = _4 & 8191, C3 = _4 >>> 13, D2 = d3[2] | 0, P2 = D2 & 8191, O3 = D2 >>> 13, Ct = d3[3] | 0, T2 = Ct & 8191, q2 = Ct >>> 13, Pe = d3[4] | 0, X = Pe & 8191, Z = Pe >>> 13, Te = d3[5] | 0, $ = Te & 8191, tt = Te >>> 13, Fe = d3[6] | 0, et = Fe & 8191, rt = Fe >>> 13, De = d3[7] | 0, it = De & 8191, nt = De >>> 13, Ue = d3[8] | 0, ft = Ue & 8191, ot = Ue >>> 13, ke = d3[9] | 0, st = ke & 8191, at = ke >>> 13, qe = m3[0] | 0, ut = qe & 8191, ht = qe >>> 13, Ke = m3[1] | 0, ct = Ke & 8191, lt = Ke >>> 13, He = m3[2] | 0, dt = He & 8191, pt = He >>> 13, Le = m3[3] | 0, vt = Le & 8191, gt = Le >>> 13, ze = m3[4] | 0, mt = ze & 8191, At = ze >>> 13, je = m3[5] | 0, bt = je & 8191, yt = je >>> 13, Ve = m3[6] | 0, wt = Ve & 8191, xt = Ve >>> 13, Qe = m3[7] | 0, Mt = Qe & 8191, Et = Qe >>> 13, Je = m3[8] | 0, St = Je & 8191, Nt = Je >>> 13, Ye = m3[9] | 0, It = Ye & 8191, _t = Ye >>> 13; - c4.negative = f4.negative ^ a3.negative, c4.length = 19, l4 = Math.imul(u3, ut), s2 = Math.imul(u3, ht), s2 = s2 + Math.imul(E4, ut) | 0, v2 = Math.imul(E4, ht); - var xe = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (xe >>> 26) | 0, xe &= 67108863, l4 = Math.imul(B2, ut), s2 = Math.imul(B2, ht), s2 = s2 + Math.imul(C3, ut) | 0, v2 = Math.imul(C3, ht), l4 = l4 + Math.imul(u3, ct) | 0, s2 = s2 + Math.imul(u3, lt) | 0, s2 = s2 + Math.imul(E4, ct) | 0, v2 = v2 + Math.imul(E4, lt) | 0; - var Me = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Me >>> 26) | 0, Me &= 67108863, l4 = Math.imul(P2, ut), s2 = Math.imul(P2, ht), s2 = s2 + Math.imul(O3, ut) | 0, v2 = Math.imul(O3, ht), l4 = l4 + Math.imul(B2, ct) | 0, s2 = s2 + Math.imul(B2, lt) | 0, s2 = s2 + Math.imul(C3, ct) | 0, v2 = v2 + Math.imul(C3, lt) | 0, l4 = l4 + Math.imul(u3, dt) | 0, s2 = s2 + Math.imul(u3, pt) | 0, s2 = s2 + Math.imul(E4, dt) | 0, v2 = v2 + Math.imul(E4, pt) | 0; - var Ee = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Ee >>> 26) | 0, Ee &= 67108863, l4 = Math.imul(T2, ut), s2 = Math.imul(T2, ht), s2 = s2 + Math.imul(q2, ut) | 0, v2 = Math.imul(q2, ht), l4 = l4 + Math.imul(P2, ct) | 0, s2 = s2 + Math.imul(P2, lt) | 0, s2 = s2 + Math.imul(O3, ct) | 0, v2 = v2 + Math.imul(O3, lt) | 0, l4 = l4 + Math.imul(B2, dt) | 0, s2 = s2 + Math.imul(B2, pt) | 0, s2 = s2 + Math.imul(C3, dt) | 0, v2 = v2 + Math.imul(C3, pt) | 0, l4 = l4 + Math.imul(u3, vt) | 0, s2 = s2 + Math.imul(u3, gt) | 0, s2 = s2 + Math.imul(E4, vt) | 0, v2 = v2 + Math.imul(E4, gt) | 0; - var Se = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Se >>> 26) | 0, Se &= 67108863, l4 = Math.imul(X, ut), s2 = Math.imul(X, ht), s2 = s2 + Math.imul(Z, ut) | 0, v2 = Math.imul(Z, ht), l4 = l4 + Math.imul(T2, ct) | 0, s2 = s2 + Math.imul(T2, lt) | 0, s2 = s2 + Math.imul(q2, ct) | 0, v2 = v2 + Math.imul(q2, lt) | 0, l4 = l4 + Math.imul(P2, dt) | 0, s2 = s2 + Math.imul(P2, pt) | 0, s2 = s2 + Math.imul(O3, dt) | 0, v2 = v2 + Math.imul(O3, pt) | 0, l4 = l4 + Math.imul(B2, vt) | 0, s2 = s2 + Math.imul(B2, gt) | 0, s2 = s2 + Math.imul(C3, vt) | 0, v2 = v2 + Math.imul(C3, gt) | 0, l4 = l4 + Math.imul(u3, mt) | 0, s2 = s2 + Math.imul(u3, At) | 0, s2 = s2 + Math.imul(E4, mt) | 0, v2 = v2 + Math.imul(E4, At) | 0; - var Ne = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Ne >>> 26) | 0, Ne &= 67108863, l4 = Math.imul($, ut), s2 = Math.imul($, ht), s2 = s2 + Math.imul(tt, ut) | 0, v2 = Math.imul(tt, ht), l4 = l4 + Math.imul(X, ct) | 0, s2 = s2 + Math.imul(X, lt) | 0, s2 = s2 + Math.imul(Z, ct) | 0, v2 = v2 + Math.imul(Z, lt) | 0, l4 = l4 + Math.imul(T2, dt) | 0, s2 = s2 + Math.imul(T2, pt) | 0, s2 = s2 + Math.imul(q2, dt) | 0, v2 = v2 + Math.imul(q2, pt) | 0, l4 = l4 + Math.imul(P2, vt) | 0, s2 = s2 + Math.imul(P2, gt) | 0, s2 = s2 + Math.imul(O3, vt) | 0, v2 = v2 + Math.imul(O3, gt) | 0, l4 = l4 + Math.imul(B2, mt) | 0, s2 = s2 + Math.imul(B2, At) | 0, s2 = s2 + Math.imul(C3, mt) | 0, v2 = v2 + Math.imul(C3, At) | 0, l4 = l4 + Math.imul(u3, bt) | 0, s2 = s2 + Math.imul(u3, yt) | 0, s2 = s2 + Math.imul(E4, bt) | 0, v2 = v2 + Math.imul(E4, yt) | 0; - var Xr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Xr >>> 26) | 0, Xr &= 67108863, l4 = Math.imul(et, ut), s2 = Math.imul(et, ht), s2 = s2 + Math.imul(rt, ut) | 0, v2 = Math.imul(rt, ht), l4 = l4 + Math.imul($, ct) | 0, s2 = s2 + Math.imul($, lt) | 0, s2 = s2 + Math.imul(tt, ct) | 0, v2 = v2 + Math.imul(tt, lt) | 0, l4 = l4 + Math.imul(X, dt) | 0, s2 = s2 + Math.imul(X, pt) | 0, s2 = s2 + Math.imul(Z, dt) | 0, v2 = v2 + Math.imul(Z, pt) | 0, l4 = l4 + Math.imul(T2, vt) | 0, s2 = s2 + Math.imul(T2, gt) | 0, s2 = s2 + Math.imul(q2, vt) | 0, v2 = v2 + Math.imul(q2, gt) | 0, l4 = l4 + Math.imul(P2, mt) | 0, s2 = s2 + Math.imul(P2, At) | 0, s2 = s2 + Math.imul(O3, mt) | 0, v2 = v2 + Math.imul(O3, At) | 0, l4 = l4 + Math.imul(B2, bt) | 0, s2 = s2 + Math.imul(B2, yt) | 0, s2 = s2 + Math.imul(C3, bt) | 0, v2 = v2 + Math.imul(C3, yt) | 0, l4 = l4 + Math.imul(u3, wt) | 0, s2 = s2 + Math.imul(u3, xt) | 0, s2 = s2 + Math.imul(E4, wt) | 0, v2 = v2 + Math.imul(E4, xt) | 0; - var Zr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Zr >>> 26) | 0, Zr &= 67108863, l4 = Math.imul(it, ut), s2 = Math.imul(it, ht), s2 = s2 + Math.imul(nt, ut) | 0, v2 = Math.imul(nt, ht), l4 = l4 + Math.imul(et, ct) | 0, s2 = s2 + Math.imul(et, lt) | 0, s2 = s2 + Math.imul(rt, ct) | 0, v2 = v2 + Math.imul(rt, lt) | 0, l4 = l4 + Math.imul($, dt) | 0, s2 = s2 + Math.imul($, pt) | 0, s2 = s2 + Math.imul(tt, dt) | 0, v2 = v2 + Math.imul(tt, pt) | 0, l4 = l4 + Math.imul(X, vt) | 0, s2 = s2 + Math.imul(X, gt) | 0, s2 = s2 + Math.imul(Z, vt) | 0, v2 = v2 + Math.imul(Z, gt) | 0, l4 = l4 + Math.imul(T2, mt) | 0, s2 = s2 + Math.imul(T2, At) | 0, s2 = s2 + Math.imul(q2, mt) | 0, v2 = v2 + Math.imul(q2, At) | 0, l4 = l4 + Math.imul(P2, bt) | 0, s2 = s2 + Math.imul(P2, yt) | 0, s2 = s2 + Math.imul(O3, bt) | 0, v2 = v2 + Math.imul(O3, yt) | 0, l4 = l4 + Math.imul(B2, wt) | 0, s2 = s2 + Math.imul(B2, xt) | 0, s2 = s2 + Math.imul(C3, wt) | 0, v2 = v2 + Math.imul(C3, xt) | 0, l4 = l4 + Math.imul(u3, Mt) | 0, s2 = s2 + Math.imul(u3, Et) | 0, s2 = s2 + Math.imul(E4, Mt) | 0, v2 = v2 + Math.imul(E4, Et) | 0; - var $r = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + ($r >>> 26) | 0, $r &= 67108863, l4 = Math.imul(ft, ut), s2 = Math.imul(ft, ht), s2 = s2 + Math.imul(ot, ut) | 0, v2 = Math.imul(ot, ht), l4 = l4 + Math.imul(it, ct) | 0, s2 = s2 + Math.imul(it, lt) | 0, s2 = s2 + Math.imul(nt, ct) | 0, v2 = v2 + Math.imul(nt, lt) | 0, l4 = l4 + Math.imul(et, dt) | 0, s2 = s2 + Math.imul(et, pt) | 0, s2 = s2 + Math.imul(rt, dt) | 0, v2 = v2 + Math.imul(rt, pt) | 0, l4 = l4 + Math.imul($, vt) | 0, s2 = s2 + Math.imul($, gt) | 0, s2 = s2 + Math.imul(tt, vt) | 0, v2 = v2 + Math.imul(tt, gt) | 0, l4 = l4 + Math.imul(X, mt) | 0, s2 = s2 + Math.imul(X, At) | 0, s2 = s2 + Math.imul(Z, mt) | 0, v2 = v2 + Math.imul(Z, At) | 0, l4 = l4 + Math.imul(T2, bt) | 0, s2 = s2 + Math.imul(T2, yt) | 0, s2 = s2 + Math.imul(q2, bt) | 0, v2 = v2 + Math.imul(q2, yt) | 0, l4 = l4 + Math.imul(P2, wt) | 0, s2 = s2 + Math.imul(P2, xt) | 0, s2 = s2 + Math.imul(O3, wt) | 0, v2 = v2 + Math.imul(O3, xt) | 0, l4 = l4 + Math.imul(B2, Mt) | 0, s2 = s2 + Math.imul(B2, Et) | 0, s2 = s2 + Math.imul(C3, Mt) | 0, v2 = v2 + Math.imul(C3, Et) | 0, l4 = l4 + Math.imul(u3, St) | 0, s2 = s2 + Math.imul(u3, Nt) | 0, s2 = s2 + Math.imul(E4, St) | 0, v2 = v2 + Math.imul(E4, Nt) | 0; - var ti = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ti >>> 26) | 0, ti &= 67108863, l4 = Math.imul(st, ut), s2 = Math.imul(st, ht), s2 = s2 + Math.imul(at, ut) | 0, v2 = Math.imul(at, ht), l4 = l4 + Math.imul(ft, ct) | 0, s2 = s2 + Math.imul(ft, lt) | 0, s2 = s2 + Math.imul(ot, ct) | 0, v2 = v2 + Math.imul(ot, lt) | 0, l4 = l4 + Math.imul(it, dt) | 0, s2 = s2 + Math.imul(it, pt) | 0, s2 = s2 + Math.imul(nt, dt) | 0, v2 = v2 + Math.imul(nt, pt) | 0, l4 = l4 + Math.imul(et, vt) | 0, s2 = s2 + Math.imul(et, gt) | 0, s2 = s2 + Math.imul(rt, vt) | 0, v2 = v2 + Math.imul(rt, gt) | 0, l4 = l4 + Math.imul($, mt) | 0, s2 = s2 + Math.imul($, At) | 0, s2 = s2 + Math.imul(tt, mt) | 0, v2 = v2 + Math.imul(tt, At) | 0, l4 = l4 + Math.imul(X, bt) | 0, s2 = s2 + Math.imul(X, yt) | 0, s2 = s2 + Math.imul(Z, bt) | 0, v2 = v2 + Math.imul(Z, yt) | 0, l4 = l4 + Math.imul(T2, wt) | 0, s2 = s2 + Math.imul(T2, xt) | 0, s2 = s2 + Math.imul(q2, wt) | 0, v2 = v2 + Math.imul(q2, xt) | 0, l4 = l4 + Math.imul(P2, Mt) | 0, s2 = s2 + Math.imul(P2, Et) | 0, s2 = s2 + Math.imul(O3, Mt) | 0, v2 = v2 + Math.imul(O3, Et) | 0, l4 = l4 + Math.imul(B2, St) | 0, s2 = s2 + Math.imul(B2, Nt) | 0, s2 = s2 + Math.imul(C3, St) | 0, v2 = v2 + Math.imul(C3, Nt) | 0, l4 = l4 + Math.imul(u3, It) | 0, s2 = s2 + Math.imul(u3, _t) | 0, s2 = s2 + Math.imul(E4, It) | 0, v2 = v2 + Math.imul(E4, _t) | 0; - var ei = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ei >>> 26) | 0, ei &= 67108863, l4 = Math.imul(st, ct), s2 = Math.imul(st, lt), s2 = s2 + Math.imul(at, ct) | 0, v2 = Math.imul(at, lt), l4 = l4 + Math.imul(ft, dt) | 0, s2 = s2 + Math.imul(ft, pt) | 0, s2 = s2 + Math.imul(ot, dt) | 0, v2 = v2 + Math.imul(ot, pt) | 0, l4 = l4 + Math.imul(it, vt) | 0, s2 = s2 + Math.imul(it, gt) | 0, s2 = s2 + Math.imul(nt, vt) | 0, v2 = v2 + Math.imul(nt, gt) | 0, l4 = l4 + Math.imul(et, mt) | 0, s2 = s2 + Math.imul(et, At) | 0, s2 = s2 + Math.imul(rt, mt) | 0, v2 = v2 + Math.imul(rt, At) | 0, l4 = l4 + Math.imul($, bt) | 0, s2 = s2 + Math.imul($, yt) | 0, s2 = s2 + Math.imul(tt, bt) | 0, v2 = v2 + Math.imul(tt, yt) | 0, l4 = l4 + Math.imul(X, wt) | 0, s2 = s2 + Math.imul(X, xt) | 0, s2 = s2 + Math.imul(Z, wt) | 0, v2 = v2 + Math.imul(Z, xt) | 0, l4 = l4 + Math.imul(T2, Mt) | 0, s2 = s2 + Math.imul(T2, Et) | 0, s2 = s2 + Math.imul(q2, Mt) | 0, v2 = v2 + Math.imul(q2, Et) | 0, l4 = l4 + Math.imul(P2, St) | 0, s2 = s2 + Math.imul(P2, Nt) | 0, s2 = s2 + Math.imul(O3, St) | 0, v2 = v2 + Math.imul(O3, Nt) | 0, l4 = l4 + Math.imul(B2, It) | 0, s2 = s2 + Math.imul(B2, _t) | 0, s2 = s2 + Math.imul(C3, It) | 0, v2 = v2 + Math.imul(C3, _t) | 0; - var ri = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ri >>> 26) | 0, ri &= 67108863, l4 = Math.imul(st, dt), s2 = Math.imul(st, pt), s2 = s2 + Math.imul(at, dt) | 0, v2 = Math.imul(at, pt), l4 = l4 + Math.imul(ft, vt) | 0, s2 = s2 + Math.imul(ft, gt) | 0, s2 = s2 + Math.imul(ot, vt) | 0, v2 = v2 + Math.imul(ot, gt) | 0, l4 = l4 + Math.imul(it, mt) | 0, s2 = s2 + Math.imul(it, At) | 0, s2 = s2 + Math.imul(nt, mt) | 0, v2 = v2 + Math.imul(nt, At) | 0, l4 = l4 + Math.imul(et, bt) | 0, s2 = s2 + Math.imul(et, yt) | 0, s2 = s2 + Math.imul(rt, bt) | 0, v2 = v2 + Math.imul(rt, yt) | 0, l4 = l4 + Math.imul($, wt) | 0, s2 = s2 + Math.imul($, xt) | 0, s2 = s2 + Math.imul(tt, wt) | 0, v2 = v2 + Math.imul(tt, xt) | 0, l4 = l4 + Math.imul(X, Mt) | 0, s2 = s2 + Math.imul(X, Et) | 0, s2 = s2 + Math.imul(Z, Mt) | 0, v2 = v2 + Math.imul(Z, Et) | 0, l4 = l4 + Math.imul(T2, St) | 0, s2 = s2 + Math.imul(T2, Nt) | 0, s2 = s2 + Math.imul(q2, St) | 0, v2 = v2 + Math.imul(q2, Nt) | 0, l4 = l4 + Math.imul(P2, It) | 0, s2 = s2 + Math.imul(P2, _t) | 0, s2 = s2 + Math.imul(O3, It) | 0, v2 = v2 + Math.imul(O3, _t) | 0; - var ii = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ii >>> 26) | 0, ii &= 67108863, l4 = Math.imul(st, vt), s2 = Math.imul(st, gt), s2 = s2 + Math.imul(at, vt) | 0, v2 = Math.imul(at, gt), l4 = l4 + Math.imul(ft, mt) | 0, s2 = s2 + Math.imul(ft, At) | 0, s2 = s2 + Math.imul(ot, mt) | 0, v2 = v2 + Math.imul(ot, At) | 0, l4 = l4 + Math.imul(it, bt) | 0, s2 = s2 + Math.imul(it, yt) | 0, s2 = s2 + Math.imul(nt, bt) | 0, v2 = v2 + Math.imul(nt, yt) | 0, l4 = l4 + Math.imul(et, wt) | 0, s2 = s2 + Math.imul(et, xt) | 0, s2 = s2 + Math.imul(rt, wt) | 0, v2 = v2 + Math.imul(rt, xt) | 0, l4 = l4 + Math.imul($, Mt) | 0, s2 = s2 + Math.imul($, Et) | 0, s2 = s2 + Math.imul(tt, Mt) | 0, v2 = v2 + Math.imul(tt, Et) | 0, l4 = l4 + Math.imul(X, St) | 0, s2 = s2 + Math.imul(X, Nt) | 0, s2 = s2 + Math.imul(Z, St) | 0, v2 = v2 + Math.imul(Z, Nt) | 0, l4 = l4 + Math.imul(T2, It) | 0, s2 = s2 + Math.imul(T2, _t) | 0, s2 = s2 + Math.imul(q2, It) | 0, v2 = v2 + Math.imul(q2, _t) | 0; - var ni = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ni >>> 26) | 0, ni &= 67108863, l4 = Math.imul(st, mt), s2 = Math.imul(st, At), s2 = s2 + Math.imul(at, mt) | 0, v2 = Math.imul(at, At), l4 = l4 + Math.imul(ft, bt) | 0, s2 = s2 + Math.imul(ft, yt) | 0, s2 = s2 + Math.imul(ot, bt) | 0, v2 = v2 + Math.imul(ot, yt) | 0, l4 = l4 + Math.imul(it, wt) | 0, s2 = s2 + Math.imul(it, xt) | 0, s2 = s2 + Math.imul(nt, wt) | 0, v2 = v2 + Math.imul(nt, xt) | 0, l4 = l4 + Math.imul(et, Mt) | 0, s2 = s2 + Math.imul(et, Et) | 0, s2 = s2 + Math.imul(rt, Mt) | 0, v2 = v2 + Math.imul(rt, Et) | 0, l4 = l4 + Math.imul($, St) | 0, s2 = s2 + Math.imul($, Nt) | 0, s2 = s2 + Math.imul(tt, St) | 0, v2 = v2 + Math.imul(tt, Nt) | 0, l4 = l4 + Math.imul(X, It) | 0, s2 = s2 + Math.imul(X, _t) | 0, s2 = s2 + Math.imul(Z, It) | 0, v2 = v2 + Math.imul(Z, _t) | 0; - var fi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (fi >>> 26) | 0, fi &= 67108863, l4 = Math.imul(st, bt), s2 = Math.imul(st, yt), s2 = s2 + Math.imul(at, bt) | 0, v2 = Math.imul(at, yt), l4 = l4 + Math.imul(ft, wt) | 0, s2 = s2 + Math.imul(ft, xt) | 0, s2 = s2 + Math.imul(ot, wt) | 0, v2 = v2 + Math.imul(ot, xt) | 0, l4 = l4 + Math.imul(it, Mt) | 0, s2 = s2 + Math.imul(it, Et) | 0, s2 = s2 + Math.imul(nt, Mt) | 0, v2 = v2 + Math.imul(nt, Et) | 0, l4 = l4 + Math.imul(et, St) | 0, s2 = s2 + Math.imul(et, Nt) | 0, s2 = s2 + Math.imul(rt, St) | 0, v2 = v2 + Math.imul(rt, Nt) | 0, l4 = l4 + Math.imul($, It) | 0, s2 = s2 + Math.imul($, _t) | 0, s2 = s2 + Math.imul(tt, It) | 0, v2 = v2 + Math.imul(tt, _t) | 0; - var oi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (oi >>> 26) | 0, oi &= 67108863, l4 = Math.imul(st, wt), s2 = Math.imul(st, xt), s2 = s2 + Math.imul(at, wt) | 0, v2 = Math.imul(at, xt), l4 = l4 + Math.imul(ft, Mt) | 0, s2 = s2 + Math.imul(ft, Et) | 0, s2 = s2 + Math.imul(ot, Mt) | 0, v2 = v2 + Math.imul(ot, Et) | 0, l4 = l4 + Math.imul(it, St) | 0, s2 = s2 + Math.imul(it, Nt) | 0, s2 = s2 + Math.imul(nt, St) | 0, v2 = v2 + Math.imul(nt, Nt) | 0, l4 = l4 + Math.imul(et, It) | 0, s2 = s2 + Math.imul(et, _t) | 0, s2 = s2 + Math.imul(rt, It) | 0, v2 = v2 + Math.imul(rt, _t) | 0; - var si = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (si >>> 26) | 0, si &= 67108863, l4 = Math.imul(st, Mt), s2 = Math.imul(st, Et), s2 = s2 + Math.imul(at, Mt) | 0, v2 = Math.imul(at, Et), l4 = l4 + Math.imul(ft, St) | 0, s2 = s2 + Math.imul(ft, Nt) | 0, s2 = s2 + Math.imul(ot, St) | 0, v2 = v2 + Math.imul(ot, Nt) | 0, l4 = l4 + Math.imul(it, It) | 0, s2 = s2 + Math.imul(it, _t) | 0, s2 = s2 + Math.imul(nt, It) | 0, v2 = v2 + Math.imul(nt, _t) | 0; - var ai = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ai >>> 26) | 0, ai &= 67108863, l4 = Math.imul(st, St), s2 = Math.imul(st, Nt), s2 = s2 + Math.imul(at, St) | 0, v2 = Math.imul(at, Nt), l4 = l4 + Math.imul(ft, It) | 0, s2 = s2 + Math.imul(ft, _t) | 0, s2 = s2 + Math.imul(ot, It) | 0, v2 = v2 + Math.imul(ot, _t) | 0; - var ui = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ui >>> 26) | 0, ui &= 67108863, l4 = Math.imul(st, It), s2 = Math.imul(st, _t), s2 = s2 + Math.imul(at, It) | 0, v2 = Math.imul(at, _t); - var hi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - return M = (v2 + (s2 >>> 13) | 0) + (hi >>> 26) | 0, hi &= 67108863, x3[0] = xe, x3[1] = Me, x3[2] = Ee, x3[3] = Se, x3[4] = Ne, x3[5] = Xr, x3[6] = Zr, x3[7] = $r, x3[8] = ti, x3[9] = ei, x3[10] = ri, x3[11] = ii, x3[12] = ni, x3[13] = fi, x3[14] = oi, x3[15] = si, x3[16] = ai, x3[17] = ui, x3[18] = hi, M !== 0 && (x3[19] = M, c4.length++), c4; - }; - Math.imul || (Q = U2); - function Bt(A2, f4, a3) { - a3.negative = f4.negative ^ A2.negative, a3.length = A2.length + f4.length; - for (var c4 = 0, d3 = 0, m3 = 0; m3 < a3.length - 1; m3++) { - var x3 = d3; - d3 = 0; - for (var M = c4 & 67108863, l4 = Math.min(m3, f4.length - 1), s2 = Math.max(0, m3 - A2.length + 1); s2 <= l4; s2++) { - var v2 = m3 - s2, k4 = A2.words[v2] | 0, u3 = f4.words[s2] | 0, E4 = k4 * u3, _4 = E4 & 67108863; - x3 = x3 + (E4 / 67108864 | 0) | 0, _4 = _4 + M | 0, M = _4 & 67108863, x3 = x3 + (_4 >>> 26) | 0, d3 += x3 >>> 26, x3 &= 67108863; - } - a3.words[m3] = M, c4 = x3, x3 = d3; - } - return c4 !== 0 ? a3.words[m3] = c4 : a3.length--, a3._strip(); - } - function J(A2, f4, a3) { - return Bt(A2, f4, a3); - } - o2.prototype.mulTo = function(f4, a3) { - var c4, d3 = this.length + f4.length; - return this.length === 10 && f4.length === 10 ? c4 = Q(this, f4, a3) : d3 < 63 ? c4 = U2(this, f4, a3) : d3 < 1024 ? c4 = Bt(this, f4, a3) : c4 = J(this, f4, a3), c4; - }, o2.prototype.mul = function(f4) { - var a3 = new o2(null); - return a3.words = new Array(this.length + f4.length), this.mulTo(f4, a3); - }, o2.prototype.mulf = function(f4) { - var a3 = new o2(null); - return a3.words = new Array(this.length + f4.length), J(this, f4, a3); - }, o2.prototype.imul = function(f4) { - return this.clone().mulTo(f4, this); - }, o2.prototype.imuln = function(f4) { - var a3 = f4 < 0; - a3 && (f4 = -f4), i2(typeof f4 == "number"), i2(f4 < 67108864); - for (var c4 = 0, d3 = 0; d3 < this.length; d3++) { - var m3 = (this.words[d3] | 0) * f4, x3 = (m3 & 67108863) + (c4 & 67108863); - c4 >>= 26, c4 += m3 / 67108864 | 0, c4 += x3 >>> 26, this.words[d3] = x3 & 67108863; - } - return c4 !== 0 && (this.words[d3] = c4, this.length++), a3 ? this.ineg() : this; - }, o2.prototype.muln = function(f4) { - return this.clone().imuln(f4); - }, o2.prototype.sqr = function() { - return this.mul(this); - }, o2.prototype.isqr = function() { - return this.imul(this.clone()); - }, o2.prototype.pow = function(f4) { - var a3 = F(f4); - if (a3.length === 0) - return new o2(1); - for (var c4 = this, d3 = 0; d3 < a3.length && a3[d3] === 0; d3++, c4 = c4.sqr()) - ; - if (++d3 < a3.length) - for (var m3 = c4.sqr(); d3 < a3.length; d3++, m3 = m3.sqr()) - a3[d3] !== 0 && (c4 = c4.mul(m3)); - return c4; - }, o2.prototype.iushln = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 67108863 >>> 26 - a3 << 26 - a3, m3; - if (a3 !== 0) { - var x3 = 0; - for (m3 = 0; m3 < this.length; m3++) { - var M = this.words[m3] & d3, l4 = (this.words[m3] | 0) - M << a3; - this.words[m3] = l4 | x3, x3 = M >>> 26 - a3; - } - x3 && (this.words[m3] = x3, this.length++); - } - if (c4 !== 0) { - for (m3 = this.length - 1; m3 >= 0; m3--) - this.words[m3 + c4] = this.words[m3]; - for (m3 = 0; m3 < c4; m3++) - this.words[m3] = 0; - this.length += c4; - } - return this._strip(); - }, o2.prototype.ishln = function(f4) { - return i2(this.negative === 0), this.iushln(f4); - }, o2.prototype.iushrn = function(f4, a3, c4) { - i2(typeof f4 == "number" && f4 >= 0); - var d3; - a3 ? d3 = (a3 - a3 % 26) / 26 : d3 = 0; - var m3 = f4 % 26, x3 = Math.min((f4 - m3) / 26, this.length), M = 67108863 ^ 67108863 >>> m3 << m3, l4 = c4; - if (d3 -= x3, d3 = Math.max(0, d3), l4) { - for (var s2 = 0; s2 < x3; s2++) - l4.words[s2] = this.words[s2]; - l4.length = x3; - } - if (x3 !== 0) - if (this.length > x3) - for (this.length -= x3, s2 = 0; s2 < this.length; s2++) - this.words[s2] = this.words[s2 + x3]; - else - this.words[0] = 0, this.length = 1; - var v2 = 0; - for (s2 = this.length - 1; s2 >= 0 && (v2 !== 0 || s2 >= d3); s2--) { - var k4 = this.words[s2] | 0; - this.words[s2] = v2 << 26 - m3 | k4 >>> m3, v2 = k4 & M; - } - return l4 && v2 !== 0 && (l4.words[l4.length++] = v2), this.length === 0 && (this.words[0] = 0, this.length = 1), this._strip(); - }, o2.prototype.ishrn = function(f4, a3, c4) { - return i2(this.negative === 0), this.iushrn(f4, a3, c4); - }, o2.prototype.shln = function(f4) { - return this.clone().ishln(f4); - }, o2.prototype.ushln = function(f4) { - return this.clone().iushln(f4); - }, o2.prototype.shrn = function(f4) { - return this.clone().ishrn(f4); - }, o2.prototype.ushrn = function(f4) { - return this.clone().iushrn(f4); - }, o2.prototype.testn = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; - if (this.length <= c4) - return false; - var m3 = this.words[c4]; - return !!(m3 & d3); - }, o2.prototype.imaskn = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = f4 % 26, c4 = (f4 - a3) / 26; - if (i2(this.negative === 0, "imaskn works only with positive numbers"), this.length <= c4) - return this; - if (a3 !== 0 && c4++, this.length = Math.min(c4, this.length), a3 !== 0) { - var d3 = 67108863 ^ 67108863 >>> a3 << a3; - this.words[this.length - 1] &= d3; - } - return this._strip(); - }, o2.prototype.maskn = function(f4) { - return this.clone().imaskn(f4); - }, o2.prototype.iaddn = function(f4) { - return i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0 ? this.isubn(-f4) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) <= f4 ? (this.words[0] = f4 - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(f4), this.negative = 1, this) : this._iaddn(f4); - }, o2.prototype._iaddn = function(f4) { - this.words[0] += f4; - for (var a3 = 0; a3 < this.length && this.words[a3] >= 67108864; a3++) - this.words[a3] -= 67108864, a3 === this.length - 1 ? this.words[a3 + 1] = 1 : this.words[a3 + 1]++; - return this.length = Math.max(this.length, a3 + 1), this; - }, o2.prototype.isubn = function(f4) { - if (i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0) - return this.iaddn(-f4); - if (this.negative !== 0) - return this.negative = 0, this.iaddn(f4), this.negative = 1, this; - if (this.words[0] -= f4, this.length === 1 && this.words[0] < 0) - this.words[0] = -this.words[0], this.negative = 1; - else - for (var a3 = 0; a3 < this.length && this.words[a3] < 0; a3++) - this.words[a3] += 67108864, this.words[a3 + 1] -= 1; - return this._strip(); - }, o2.prototype.addn = function(f4) { - return this.clone().iaddn(f4); - }, o2.prototype.subn = function(f4) { - return this.clone().isubn(f4); - }, o2.prototype.iabs = function() { - return this.negative = 0, this; - }, o2.prototype.abs = function() { - return this.clone().iabs(); - }, o2.prototype._ishlnsubmul = function(f4, a3, c4) { - var d3 = f4.length + c4, m3; - this._expand(d3); - var x3, M = 0; - for (m3 = 0; m3 < f4.length; m3++) { - x3 = (this.words[m3 + c4] | 0) + M; - var l4 = (f4.words[m3] | 0) * a3; - x3 -= l4 & 67108863, M = (x3 >> 26) - (l4 / 67108864 | 0), this.words[m3 + c4] = x3 & 67108863; - } - for (; m3 < this.length - c4; m3++) - x3 = (this.words[m3 + c4] | 0) + M, M = x3 >> 26, this.words[m3 + c4] = x3 & 67108863; - if (M === 0) - return this._strip(); - for (i2(M === -1), M = 0, m3 = 0; m3 < this.length; m3++) - x3 = -(this.words[m3] | 0) + M, M = x3 >> 26, this.words[m3] = x3 & 67108863; - return this.negative = 1, this._strip(); - }, o2.prototype._wordDiv = function(f4, a3) { - var c4 = this.length - f4.length, d3 = this.clone(), m3 = f4, x3 = m3.words[m3.length - 1] | 0, M = this._countBits(x3); - c4 = 26 - M, c4 !== 0 && (m3 = m3.ushln(c4), d3.iushln(c4), x3 = m3.words[m3.length - 1] | 0); - var l4 = d3.length - m3.length, s2; - if (a3 !== "mod") { - s2 = new o2(null), s2.length = l4 + 1, s2.words = new Array(s2.length); - for (var v2 = 0; v2 < s2.length; v2++) - s2.words[v2] = 0; - } - var k4 = d3.clone()._ishlnsubmul(m3, 1, l4); - k4.negative === 0 && (d3 = k4, s2 && (s2.words[l4] = 1)); - for (var u3 = l4 - 1; u3 >= 0; u3--) { - var E4 = (d3.words[m3.length + u3] | 0) * 67108864 + (d3.words[m3.length + u3 - 1] | 0); - for (E4 = Math.min(E4 / x3 | 0, 67108863), d3._ishlnsubmul(m3, E4, u3); d3.negative !== 0; ) - E4--, d3.negative = 0, d3._ishlnsubmul(m3, 1, u3), d3.isZero() || (d3.negative ^= 1); - s2 && (s2.words[u3] = E4); - } - return s2 && s2._strip(), d3._strip(), a3 !== "div" && c4 !== 0 && d3.iushrn(c4), { div: s2 || null, mod: d3 }; - }, o2.prototype.divmod = function(f4, a3, c4) { - if (i2(!f4.isZero()), this.isZero()) - return { div: new o2(0), mod: new o2(0) }; - var d3, m3, x3; - return this.negative !== 0 && f4.negative === 0 ? (x3 = this.neg().divmod(f4, a3), a3 !== "mod" && (d3 = x3.div.neg()), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.iadd(f4)), { div: d3, mod: m3 }) : this.negative === 0 && f4.negative !== 0 ? (x3 = this.divmod(f4.neg(), a3), a3 !== "mod" && (d3 = x3.div.neg()), { div: d3, mod: x3.mod }) : this.negative & f4.negative ? (x3 = this.neg().divmod(f4.neg(), a3), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.isub(f4)), { div: x3.div, mod: m3 }) : f4.length > this.length || this.cmp(f4) < 0 ? { div: new o2(0), mod: this } : f4.length === 1 ? a3 === "div" ? { div: this.divn(f4.words[0]), mod: null } : a3 === "mod" ? { div: null, mod: new o2(this.modrn(f4.words[0])) } : { div: this.divn(f4.words[0]), mod: new o2(this.modrn(f4.words[0])) } : this._wordDiv(f4, a3); - }, o2.prototype.div = function(f4) { - return this.divmod(f4, "div", false).div; - }, o2.prototype.mod = function(f4) { - return this.divmod(f4, "mod", false).mod; - }, o2.prototype.umod = function(f4) { - return this.divmod(f4, "mod", true).mod; - }, o2.prototype.divRound = function(f4) { - var a3 = this.divmod(f4); - if (a3.mod.isZero()) - return a3.div; - var c4 = a3.div.negative !== 0 ? a3.mod.isub(f4) : a3.mod, d3 = f4.ushrn(1), m3 = f4.andln(1), x3 = c4.cmp(d3); - return x3 < 0 || m3 === 1 && x3 === 0 ? a3.div : a3.div.negative !== 0 ? a3.div.isubn(1) : a3.div.iaddn(1); - }, o2.prototype.modrn = function(f4) { - var a3 = f4 < 0; - a3 && (f4 = -f4), i2(f4 <= 67108863); - for (var c4 = (1 << 26) % f4, d3 = 0, m3 = this.length - 1; m3 >= 0; m3--) - d3 = (c4 * d3 + (this.words[m3] | 0)) % f4; - return a3 ? -d3 : d3; - }, o2.prototype.modn = function(f4) { - return this.modrn(f4); - }, o2.prototype.idivn = function(f4) { - var a3 = f4 < 0; - a3 && (f4 = -f4), i2(f4 <= 67108863); - for (var c4 = 0, d3 = this.length - 1; d3 >= 0; d3--) { - var m3 = (this.words[d3] | 0) + c4 * 67108864; - this.words[d3] = m3 / f4 | 0, c4 = m3 % f4; - } - return this._strip(), a3 ? this.ineg() : this; - }, o2.prototype.divn = function(f4) { - return this.clone().idivn(f4); - }, o2.prototype.egcd = function(f4) { - i2(f4.negative === 0), i2(!f4.isZero()); - var a3 = this, c4 = f4.clone(); - a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); - for (var d3 = new o2(1), m3 = new o2(0), x3 = new o2(0), M = new o2(1), l4 = 0; a3.isEven() && c4.isEven(); ) - a3.iushrn(1), c4.iushrn(1), ++l4; - for (var s2 = c4.clone(), v2 = a3.clone(); !a3.isZero(); ) { - for (var k4 = 0, u3 = 1; !(a3.words[0] & u3) && k4 < 26; ++k4, u3 <<= 1) - ; - if (k4 > 0) - for (a3.iushrn(k4); k4-- > 0; ) - (d3.isOdd() || m3.isOdd()) && (d3.iadd(s2), m3.isub(v2)), d3.iushrn(1), m3.iushrn(1); - for (var E4 = 0, _4 = 1; !(c4.words[0] & _4) && E4 < 26; ++E4, _4 <<= 1) - ; - if (E4 > 0) - for (c4.iushrn(E4); E4-- > 0; ) - (x3.isOdd() || M.isOdd()) && (x3.iadd(s2), M.isub(v2)), x3.iushrn(1), M.iushrn(1); - a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(x3), m3.isub(M)) : (c4.isub(a3), x3.isub(d3), M.isub(m3)); - } - return { a: x3, b: M, gcd: c4.iushln(l4) }; - }, o2.prototype._invmp = function(f4) { - i2(f4.negative === 0), i2(!f4.isZero()); - var a3 = this, c4 = f4.clone(); - a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); - for (var d3 = new o2(1), m3 = new o2(0), x3 = c4.clone(); a3.cmpn(1) > 0 && c4.cmpn(1) > 0; ) { - for (var M = 0, l4 = 1; !(a3.words[0] & l4) && M < 26; ++M, l4 <<= 1) - ; - if (M > 0) - for (a3.iushrn(M); M-- > 0; ) - d3.isOdd() && d3.iadd(x3), d3.iushrn(1); - for (var s2 = 0, v2 = 1; !(c4.words[0] & v2) && s2 < 26; ++s2, v2 <<= 1) - ; - if (s2 > 0) - for (c4.iushrn(s2); s2-- > 0; ) - m3.isOdd() && m3.iadd(x3), m3.iushrn(1); - a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(m3)) : (c4.isub(a3), m3.isub(d3)); - } - var k4; - return a3.cmpn(1) === 0 ? k4 = d3 : k4 = m3, k4.cmpn(0) < 0 && k4.iadd(f4), k4; - }, o2.prototype.gcd = function(f4) { - if (this.isZero()) - return f4.abs(); - if (f4.isZero()) - return this.abs(); - var a3 = this.clone(), c4 = f4.clone(); - a3.negative = 0, c4.negative = 0; - for (var d3 = 0; a3.isEven() && c4.isEven(); d3++) - a3.iushrn(1), c4.iushrn(1); - do { - for (; a3.isEven(); ) - a3.iushrn(1); - for (; c4.isEven(); ) - c4.iushrn(1); - var m3 = a3.cmp(c4); - if (m3 < 0) { - var x3 = a3; - a3 = c4, c4 = x3; - } else if (m3 === 0 || c4.cmpn(1) === 0) - break; - a3.isub(c4); - } while (true); - return c4.iushln(d3); - }, o2.prototype.invm = function(f4) { - return this.egcd(f4).a.umod(f4); - }, o2.prototype.isEven = function() { - return (this.words[0] & 1) === 0; - }, o2.prototype.isOdd = function() { - return (this.words[0] & 1) === 1; - }, o2.prototype.andln = function(f4) { - return this.words[0] & f4; - }, o2.prototype.bincn = function(f4) { - i2(typeof f4 == "number"); - var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; - if (this.length <= c4) - return this._expand(c4 + 1), this.words[c4] |= d3, this; - for (var m3 = d3, x3 = c4; m3 !== 0 && x3 < this.length; x3++) { - var M = this.words[x3] | 0; - M += m3, m3 = M >>> 26, M &= 67108863, this.words[x3] = M; - } - return m3 !== 0 && (this.words[x3] = m3, this.length++), this; - }, o2.prototype.isZero = function() { - return this.length === 1 && this.words[0] === 0; - }, o2.prototype.cmpn = function(f4) { - var a3 = f4 < 0; - if (this.negative !== 0 && !a3) - return -1; - if (this.negative === 0 && a3) - return 1; - this._strip(); - var c4; - if (this.length > 1) - c4 = 1; - else { - a3 && (f4 = -f4), i2(f4 <= 67108863, "Number is too big"); - var d3 = this.words[0] | 0; - c4 = d3 === f4 ? 0 : d3 < f4 ? -1 : 1; - } - return this.negative !== 0 ? -c4 | 0 : c4; - }, o2.prototype.cmp = function(f4) { - if (this.negative !== 0 && f4.negative === 0) - return -1; - if (this.negative === 0 && f4.negative !== 0) - return 1; - var a3 = this.ucmp(f4); - return this.negative !== 0 ? -a3 | 0 : a3; - }, o2.prototype.ucmp = function(f4) { - if (this.length > f4.length) - return 1; - if (this.length < f4.length) - return -1; - for (var a3 = 0, c4 = this.length - 1; c4 >= 0; c4--) { - var d3 = this.words[c4] | 0, m3 = f4.words[c4] | 0; - if (d3 !== m3) { - d3 < m3 ? a3 = -1 : d3 > m3 && (a3 = 1); - break; - } - } - return a3; - }, o2.prototype.gtn = function(f4) { - return this.cmpn(f4) === 1; - }, o2.prototype.gt = function(f4) { - return this.cmp(f4) === 1; - }, o2.prototype.gten = function(f4) { - return this.cmpn(f4) >= 0; - }, o2.prototype.gte = function(f4) { - return this.cmp(f4) >= 0; - }, o2.prototype.ltn = function(f4) { - return this.cmpn(f4) === -1; - }, o2.prototype.lt = function(f4) { - return this.cmp(f4) === -1; - }, o2.prototype.lten = function(f4) { - return this.cmpn(f4) <= 0; - }, o2.prototype.lte = function(f4) { - return this.cmp(f4) <= 0; - }, o2.prototype.eqn = function(f4) { - return this.cmpn(f4) === 0; - }, o2.prototype.eq = function(f4) { - return this.cmp(f4) === 0; - }, o2.red = function(f4) { - return new Y(f4); - }, o2.prototype.toRed = function(f4) { - return i2(!this.red, "Already a number in reduction context"), i2(this.negative === 0, "red works only with positives"), f4.convertTo(this)._forceRed(f4); - }, o2.prototype.fromRed = function() { - return i2(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }, o2.prototype._forceRed = function(f4) { - return this.red = f4, this; - }, o2.prototype.forceRed = function(f4) { - return i2(!this.red, "Already a number in reduction context"), this._forceRed(f4); - }, o2.prototype.redAdd = function(f4) { - return i2(this.red, "redAdd works only with red numbers"), this.red.add(this, f4); - }, o2.prototype.redIAdd = function(f4) { - return i2(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, f4); - }, o2.prototype.redSub = function(f4) { - return i2(this.red, "redSub works only with red numbers"), this.red.sub(this, f4); - }, o2.prototype.redISub = function(f4) { - return i2(this.red, "redISub works only with red numbers"), this.red.isub(this, f4); - }, o2.prototype.redShl = function(f4) { - return i2(this.red, "redShl works only with red numbers"), this.red.shl(this, f4); - }, o2.prototype.redMul = function(f4) { - return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.mul(this, f4); - }, o2.prototype.redIMul = function(f4) { - return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.imul(this, f4); - }, o2.prototype.redSqr = function() { - return i2(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }, o2.prototype.redISqr = function() { - return i2(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }, o2.prototype.redSqrt = function() { - return i2(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }, o2.prototype.redInvm = function() { - return i2(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }, o2.prototype.redNeg = function() { - return i2(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }, o2.prototype.redPow = function(f4) { - return i2(this.red && !f4.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, f4); - }; - var H = { k256: null, p224: null, p192: null, p25519: null }; - function L2(A2, f4) { - this.name = A2, this.p = new o2(f4, 16), this.n = this.p.bitLength(), this.k = new o2(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); - } - L2.prototype._tmp = function() { - var f4 = new o2(null); - return f4.words = new Array(Math.ceil(this.n / 13)), f4; - }, L2.prototype.ireduce = function(f4) { - var a3 = f4, c4; - do - this.split(a3, this.tmp), a3 = this.imulK(a3), a3 = a3.iadd(this.tmp), c4 = a3.bitLength(); - while (c4 > this.n); - var d3 = c4 < this.n ? -1 : a3.ucmp(this.p); - return d3 === 0 ? (a3.words[0] = 0, a3.length = 1) : d3 > 0 ? a3.isub(this.p) : a3.strip !== void 0 ? a3.strip() : a3._strip(), a3; - }, L2.prototype.split = function(f4, a3) { - f4.iushrn(this.n, 0, a3); - }, L2.prototype.imulK = function(f4) { - return f4.imul(this.k); - }; - function Tt() { - L2.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - n3(Tt, L2), Tt.prototype.split = function(f4, a3) { - for (var c4 = 4194303, d3 = Math.min(f4.length, 9), m3 = 0; m3 < d3; m3++) - a3.words[m3] = f4.words[m3]; - if (a3.length = d3, f4.length <= 9) { - f4.words[0] = 0, f4.length = 1; - return; - } - var x3 = f4.words[9]; - for (a3.words[a3.length++] = x3 & c4, m3 = 10; m3 < f4.length; m3++) { - var M = f4.words[m3] | 0; - f4.words[m3 - 10] = (M & c4) << 4 | x3 >>> 22, x3 = M; - } - x3 >>>= 22, f4.words[m3 - 10] = x3, x3 === 0 && f4.length > 10 ? f4.length -= 10 : f4.length -= 9; - }, Tt.prototype.imulK = function(f4) { - f4.words[f4.length] = 0, f4.words[f4.length + 1] = 0, f4.length += 2; - for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { - var d3 = f4.words[c4] | 0; - a3 += d3 * 977, f4.words[c4] = a3 & 67108863, a3 = d3 * 64 + (a3 / 67108864 | 0); - } - return f4.words[f4.length - 1] === 0 && (f4.length--, f4.words[f4.length - 1] === 0 && f4.length--), f4; - }; - function W() { - L2.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - n3(W, L2); - function Ot() { - L2.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - n3(Ot, L2); - function Gt() { - L2.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - n3(Gt, L2), Gt.prototype.imulK = function(f4) { - for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { - var d3 = (f4.words[c4] | 0) * 19 + a3, m3 = d3 & 67108863; - d3 >>>= 26, f4.words[c4] = m3, a3 = d3; - } - return a3 !== 0 && (f4.words[f4.length++] = a3), f4; - }, o2._prime = function(f4) { - if (H[f4]) - return H[f4]; - var a3; - if (f4 === "k256") - a3 = new Tt(); - else if (f4 === "p224") - a3 = new W(); - else if (f4 === "p192") - a3 = new Ot(); - else if (f4 === "p25519") - a3 = new Gt(); - else - throw new Error("Unknown prime " + f4); - return H[f4] = a3, a3; - }; - function Y(A2) { - if (typeof A2 == "string") { - var f4 = o2._prime(A2); - this.m = f4.p, this.prime = f4; - } else - i2(A2.gtn(1), "modulus must be greater than 1"), this.m = A2, this.prime = null; - } - Y.prototype._verify1 = function(f4) { - i2(f4.negative === 0, "red works only with positives"), i2(f4.red, "red works only with red numbers"); - }, Y.prototype._verify2 = function(f4, a3) { - i2((f4.negative | a3.negative) === 0, "red works only with positives"), i2(f4.red && f4.red === a3.red, "red works only with red numbers"); - }, Y.prototype.imod = function(f4) { - return this.prime ? this.prime.ireduce(f4)._forceRed(this) : (w4(f4, f4.umod(this.m)._forceRed(this)), f4); - }, Y.prototype.neg = function(f4) { - return f4.isZero() ? f4.clone() : this.m.sub(f4)._forceRed(this); - }, Y.prototype.add = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.add(a3); - return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4._forceRed(this); - }, Y.prototype.iadd = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.iadd(a3); - return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4; - }, Y.prototype.sub = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.sub(a3); - return c4.cmpn(0) < 0 && c4.iadd(this.m), c4._forceRed(this); - }, Y.prototype.isub = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.isub(a3); - return c4.cmpn(0) < 0 && c4.iadd(this.m), c4; - }, Y.prototype.shl = function(f4, a3) { - return this._verify1(f4), this.imod(f4.ushln(a3)); - }, Y.prototype.imul = function(f4, a3) { - return this._verify2(f4, a3), this.imod(f4.imul(a3)); - }, Y.prototype.mul = function(f4, a3) { - return this._verify2(f4, a3), this.imod(f4.mul(a3)); - }, Y.prototype.isqr = function(f4) { - return this.imul(f4, f4.clone()); - }, Y.prototype.sqr = function(f4) { - return this.mul(f4, f4); - }, Y.prototype.sqrt = function(f4) { - if (f4.isZero()) - return f4.clone(); - var a3 = this.m.andln(3); - if (i2(a3 % 2 === 1), a3 === 3) { - var c4 = this.m.add(new o2(1)).iushrn(2); - return this.pow(f4, c4); - } - for (var d3 = this.m.subn(1), m3 = 0; !d3.isZero() && d3.andln(1) === 0; ) - m3++, d3.iushrn(1); - i2(!d3.isZero()); - var x3 = new o2(1).toRed(this), M = x3.redNeg(), l4 = this.m.subn(1).iushrn(1), s2 = this.m.bitLength(); - for (s2 = new o2(2 * s2 * s2).toRed(this); this.pow(s2, l4).cmp(M) !== 0; ) - s2.redIAdd(M); - for (var v2 = this.pow(s2, d3), k4 = this.pow(f4, d3.addn(1).iushrn(1)), u3 = this.pow(f4, d3), E4 = m3; u3.cmp(x3) !== 0; ) { - for (var _4 = u3, B2 = 0; _4.cmp(x3) !== 0; B2++) - _4 = _4.redSqr(); - i2(B2 < E4); - var C3 = this.pow(v2, new o2(1).iushln(E4 - B2 - 1)); - k4 = k4.redMul(C3), v2 = C3.redSqr(), u3 = u3.redMul(v2), E4 = B2; - } - return k4; - }, Y.prototype.invm = function(f4) { - var a3 = f4._invmp(this.m); - return a3.negative !== 0 ? (a3.negative = 0, this.imod(a3).redNeg()) : this.imod(a3); - }, Y.prototype.pow = function(f4, a3) { - if (a3.isZero()) - return new o2(1).toRed(this); - if (a3.cmpn(1) === 0) - return f4.clone(); - var c4 = 4, d3 = new Array(1 << c4); - d3[0] = new o2(1).toRed(this), d3[1] = f4; - for (var m3 = 2; m3 < d3.length; m3++) - d3[m3] = this.mul(d3[m3 - 1], f4); - var x3 = d3[0], M = 0, l4 = 0, s2 = a3.bitLength() % 26; - for (s2 === 0 && (s2 = 26), m3 = a3.length - 1; m3 >= 0; m3--) { - for (var v2 = a3.words[m3], k4 = s2 - 1; k4 >= 0; k4--) { - var u3 = v2 >> k4 & 1; - if (x3 !== d3[0] && (x3 = this.sqr(x3)), u3 === 0 && M === 0) { - l4 = 0; - continue; - } - M <<= 1, M |= u3, l4++, !(l4 !== c4 && (m3 !== 0 || k4 !== 0)) && (x3 = this.mul(x3, d3[M]), l4 = 0, M = 0); - } - s2 = 26; - } - return x3; - }, Y.prototype.convertTo = function(f4) { - var a3 = f4.umod(this.m); - return a3 === f4 ? a3.clone() : a3; - }, Y.prototype.convertFrom = function(f4) { - var a3 = f4.clone(); - return a3.red = null, a3; - }, o2.mont = function(f4) { - return new Wt(f4); - }; - function Wt(A2) { - Y.call(this, A2), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new o2(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); - } - n3(Wt, Y), Wt.prototype.convertTo = function(f4) { - return this.imod(f4.ushln(this.shift)); - }, Wt.prototype.convertFrom = function(f4) { - var a3 = this.imod(f4.mul(this.rinv)); - return a3.red = null, a3; - }, Wt.prototype.imul = function(f4, a3) { - if (f4.isZero() || a3.isZero()) - return f4.words[0] = 0, f4.length = 1, f4; - var c4 = f4.imul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; - return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); - }, Wt.prototype.mul = function(f4, a3) { - if (f4.isZero() || a3.isZero()) - return new o2(0)._forceRed(this); - var c4 = f4.mul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; - return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); - }, Wt.prototype.invm = function(f4) { - var a3 = this.imod(f4._invmp(this.m).mul(this.r2)); - return a3._forceRed(this); - }; - })(e2, _n); - })(qn); - var K2 = qn.exports; - var Kn = "bignumber/5.7.0"; - var Or = K2.BN; - var me = new z3(Kn); - var xi = {}; - var Hn = 9007199254740991; - function Ns(e2) { - return e2 != null && (G.isBigNumber(e2) || typeof e2 == "number" && e2 % 1 === 0 || typeof e2 == "string" && !!e2.match(/^-?[0-9]+$/) || Qt(e2) || typeof e2 == "bigint" || nr(e2)); - } - var Ln = false; - var G = class _G { - constructor(t, r) { - t !== xi && me.throwError("cannot call constructor directly; use BigNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new (BigNumber)" }), this._hex = r, this._isBigNumber = true, Object.freeze(this); - } - fromTwos(t) { - return jt(j2(this).fromTwos(t)); - } - toTwos(t) { - return jt(j2(this).toTwos(t)); - } - abs() { - return this._hex[0] === "-" ? _G.from(this._hex.substring(1)) : this; - } - add(t) { - return jt(j2(this).add(j2(t))); - } - sub(t) { - return jt(j2(this).sub(j2(t))); - } - div(t) { - return _G.from(t).isZero() && Xt("division-by-zero", "div"), jt(j2(this).div(j2(t))); - } - mul(t) { - return jt(j2(this).mul(j2(t))); - } - mod(t) { - const r = j2(t); - return r.isNeg() && Xt("division-by-zero", "mod"), jt(j2(this).umod(r)); - } - pow(t) { - const r = j2(t); - return r.isNeg() && Xt("negative-power", "pow"), jt(j2(this).pow(r)); - } - and(t) { - const r = j2(t); - return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "and"), jt(j2(this).and(r)); - } - or(t) { - const r = j2(t); - return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "or"), jt(j2(this).or(r)); - } - xor(t) { - const r = j2(t); - return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "xor"), jt(j2(this).xor(r)); - } - mask(t) { - return (this.isNegative() || t < 0) && Xt("negative-width", "mask"), jt(j2(this).maskn(t)); - } - shl(t) { - return (this.isNegative() || t < 0) && Xt("negative-width", "shl"), jt(j2(this).shln(t)); - } - shr(t) { - return (this.isNegative() || t < 0) && Xt("negative-width", "shr"), jt(j2(this).shrn(t)); - } - eq(t) { - return j2(this).eq(j2(t)); - } - lt(t) { - return j2(this).lt(j2(t)); - } - lte(t) { - return j2(this).lte(j2(t)); - } - gt(t) { - return j2(this).gt(j2(t)); - } - gte(t) { - return j2(this).gte(j2(t)); - } - isNegative() { - return this._hex[0] === "-"; - } - isZero() { - return j2(this).isZero(); - } - toNumber() { - try { - return j2(this).toNumber(); - } catch { - Xt("overflow", "toNumber", this.toString()); - } - return null; - } - toBigInt() { - try { - return BigInt(this.toString()); - } catch { - } - return me.throwError("this platform does not support BigInt", z3.errors.UNSUPPORTED_OPERATION, { value: this.toString() }); - } - toString() { - return arguments.length > 0 && (arguments[0] === 10 ? Ln || (Ln = true, me.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")) : arguments[0] === 16 ? me.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", z3.errors.UNEXPECTED_ARGUMENT, {}) : me.throwError("BigNumber.toString does not accept parameters", z3.errors.UNEXPECTED_ARGUMENT, {})), j2(this).toString(10); - } - toHexString() { - return this._hex; - } - toJSON(t) { - return { type: "BigNumber", hex: this.toHexString() }; - } - static from(t) { - if (t instanceof _G) - return t; - if (typeof t == "string") - return t.match(/^-?0x[0-9a-f]+$/i) ? new _G(xi, gr(t)) : t.match(/^-?[0-9]+$/) ? new _G(xi, gr(new Or(t))) : me.throwArgumentError("invalid BigNumber string", "value", t); - if (typeof t == "number") - return t % 1 && Xt("underflow", "BigNumber.from", t), (t >= Hn || t <= -Hn) && Xt("overflow", "BigNumber.from", t), _G.from(String(t)); - const r = t; - if (typeof r == "bigint") - return _G.from(r.toString()); - if (nr(r)) - return _G.from(Ht(r)); - if (r) - if (r.toHexString) { - const i2 = r.toHexString(); - if (typeof i2 == "string") - return _G.from(i2); - } else { - let i2 = r._hex; - if (i2 == null && r.type === "BigNumber" && (i2 = r.hex), typeof i2 == "string" && (Qt(i2) || i2[0] === "-" && Qt(i2.substring(1)))) - return _G.from(i2); - } - return me.throwArgumentError("invalid BigNumber value", "value", t); - } - static isBigNumber(t) { - return !!(t && t._isBigNumber); - } - }; - function gr(e2) { - if (typeof e2 != "string") - return gr(e2.toString(16)); - if (e2[0] === "-") - return e2 = e2.substring(1), e2[0] === "-" && me.throwArgumentError("invalid hex", "value", e2), e2 = gr(e2), e2 === "0x00" ? e2 : "-" + e2; - if (e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), e2 === "0x") - return "0x00"; - for (e2.length % 2 && (e2 = "0x0" + e2.substring(2)); e2.length > 4 && e2.substring(0, 4) === "0x00"; ) - e2 = "0x" + e2.substring(4); - return e2; - } - function jt(e2) { - return G.from(gr(e2)); - } - function j2(e2) { - const t = G.from(e2).toHexString(); - return t[0] === "-" ? new Or("-" + t.substring(3), 16) : new Or(t.substring(2), 16); - } - function Xt(e2, t, r) { - const i2 = { fault: e2, operation: t }; - return r != null && (i2.value = r), me.throwError(e2, z3.errors.NUMERIC_FAULT, i2); - } - function Is(e2) { - return new Or(e2, 36).toString(16); - } - var Lt = new z3(Kn); - var mr = {}; - var zn = G.from(0); - var jn = G.from(-1); - function Vn(e2, t, r, i2) { - const n3 = { fault: t, operation: r }; - return i2 !== void 0 && (n3.value = i2), Lt.throwError(e2, z3.errors.NUMERIC_FAULT, n3); - } - var Ar = "0"; - for (; Ar.length < 256; ) - Ar += Ar; - function Mi(e2) { - if (typeof e2 != "number") - try { - e2 = G.from(e2).toNumber(); - } catch { - } - return typeof e2 == "number" && e2 >= 0 && e2 <= 256 && !(e2 % 1) ? "1" + Ar.substring(0, e2) : Lt.throwArgumentError("invalid decimal size", "decimals", e2); - } - function Ei(e2, t) { - t == null && (t = 0); - const r = Mi(t); - e2 = G.from(e2); - const i2 = e2.lt(zn); - i2 && (e2 = e2.mul(jn)); - let n3 = e2.mod(r).toString(); - for (; n3.length < r.length - 1; ) - n3 = "0" + n3; - n3 = n3.match(/^([0-9]*[1-9]|0)(0*)/)[1]; - const o2 = e2.div(r).toString(); - return r.length === 1 ? e2 = o2 : e2 = o2 + "." + n3, i2 && (e2 = "-" + e2), e2; - } - function Ae(e2, t) { - t == null && (t = 0); - const r = Mi(t); - (typeof e2 != "string" || !e2.match(/^-?[0-9.]+$/)) && Lt.throwArgumentError("invalid decimal value", "value", e2); - const i2 = e2.substring(0, 1) === "-"; - i2 && (e2 = e2.substring(1)), e2 === "." && Lt.throwArgumentError("missing value", "value", e2); - const n3 = e2.split("."); - n3.length > 2 && Lt.throwArgumentError("too many decimal points", "value", e2); - let o2 = n3[0], h5 = n3[1]; - for (o2 || (o2 = "0"), h5 || (h5 = "0"); h5[h5.length - 1] === "0"; ) - h5 = h5.substring(0, h5.length - 1); - for (h5.length > r.length - 1 && Vn("fractional component exceeds decimals", "underflow", "parseFixed"), h5 === "" && (h5 = "0"); h5.length < r.length - 1; ) - h5 += "0"; - const p3 = G.from(o2), b4 = G.from(h5); - let g3 = p3.mul(r).add(b4); - return i2 && (g3 = g3.mul(jn)), g3; - } - var pr = class _pr { - constructor(t, r, i2, n3) { - t !== mr && Lt.throwError("cannot use FixedFormat constructor; use FixedFormat.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.signed = r, this.width = i2, this.decimals = n3, this.name = (r ? "" : "u") + "fixed" + String(i2) + "x" + String(n3), this._multiplier = Mi(n3), Object.freeze(this); - } - static from(t) { - if (t instanceof _pr) - return t; - typeof t == "number" && (t = `fixed128x${t}`); - let r = true, i2 = 128, n3 = 18; - if (typeof t == "string") { - if (t !== "fixed") - if (t === "ufixed") - r = false; - else { - const o2 = t.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - o2 || Lt.throwArgumentError("invalid fixed format", "format", t), r = o2[1] !== "u", i2 = parseInt(o2[2]), n3 = parseInt(o2[3]); - } - } else if (t) { - const o2 = (h5, p3, b4) => t[h5] == null ? b4 : (typeof t[h5] !== p3 && Lt.throwArgumentError("invalid fixed format (" + h5 + " not " + p3 + ")", "format." + h5, t[h5]), t[h5]); - r = o2("signed", "boolean", r), i2 = o2("width", "number", i2), n3 = o2("decimals", "number", n3); - } - return i2 % 8 && Lt.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", i2), n3 > 80 && Lt.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", n3), new _pr(mr, r, i2, n3); - } - }; - var kt = class _kt { - constructor(t, r, i2, n3) { - t !== mr && Lt.throwError("cannot use FixedNumber constructor; use FixedNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.format = n3, this._hex = r, this._value = i2, this._isFixedNumber = true, Object.freeze(this); - } - _checkFormat(t) { - this.format.name !== t.format.name && Lt.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", t); - } - addUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.add(i2), this.format.decimals, this.format); - } - subUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.sub(i2), this.format.decimals, this.format); - } - mulUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.mul(i2).div(this.format._multiplier), this.format.decimals, this.format); - } - divUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.mul(this.format._multiplier).div(i2), this.format.decimals, this.format); - } - floor() { - const t = this.toString().split("."); - t.length === 1 && t.push("0"); - let r = _kt.from(t[0], this.format); - const i2 = !t[1].match(/^(0*)$/); - return this.isNegative() && i2 && (r = r.subUnsafe(Qn.toFormat(r.format))), r; - } - ceiling() { - const t = this.toString().split("."); - t.length === 1 && t.push("0"); - let r = _kt.from(t[0], this.format); - const i2 = !t[1].match(/^(0*)$/); - return !this.isNegative() && i2 && (r = r.addUnsafe(Qn.toFormat(r.format))), r; - } - round(t) { - t == null && (t = 0); - const r = this.toString().split("."); - if (r.length === 1 && r.push("0"), (t < 0 || t > 80 || t % 1) && Lt.throwArgumentError("invalid decimal count", "decimals", t), r[1].length <= t) - return this; - const i2 = _kt.from("1" + Ar.substring(0, t), this.format), n3 = _s.toFormat(this.format); - return this.mulUnsafe(i2).addUnsafe(n3).floor().divUnsafe(i2); - } - isZero() { - return this._value === "0.0" || this._value === "0"; - } - isNegative() { - return this._value[0] === "-"; - } - toString() { - return this._value; - } - toHexString(t) { - if (t == null) - return this._hex; - t % 8 && Lt.throwArgumentError("invalid byte width", "width", t); - const r = G.from(this._hex).fromTwos(this.format.width).toTwos(t).toHexString(); - return fe(r, t / 8); - } - toUnsafeFloat() { - return parseFloat(this.toString()); - } - toFormat(t) { - return _kt.fromString(this._value, t); - } - static fromValue(t, r, i2) { - return i2 == null && r != null && !Ns(r) && (i2 = r, r = null), r == null && (r = 0), i2 == null && (i2 = "fixed"), _kt.fromString(Ei(t, r), pr.from(i2)); - } - static fromString(t, r) { - r == null && (r = "fixed"); - const i2 = pr.from(r), n3 = Ae(t, i2.decimals); - !i2.signed && n3.lt(zn) && Vn("unsigned value cannot be negative", "overflow", "value", t); - let o2 = null; - i2.signed ? o2 = n3.toTwos(i2.width).toHexString() : (o2 = n3.toHexString(), o2 = fe(o2, i2.width / 8)); - const h5 = Ei(n3, i2.decimals); - return new _kt(mr, o2, h5, i2); - } - static fromBytes(t, r) { - r == null && (r = "fixed"); - const i2 = pr.from(r); - if (Pt(t).length > i2.width / 8) - throw new Error("overflow"); - let n3 = G.from(t); - i2.signed && (n3 = n3.fromTwos(i2.width)); - const o2 = n3.toTwos((i2.signed ? 0 : 1) + i2.width).toHexString(), h5 = Ei(n3, i2.decimals); - return new _kt(mr, o2, h5, i2); - } - static from(t, r) { - if (typeof t == "string") - return _kt.fromString(t, r); - if (nr(t)) - return _kt.fromBytes(t, r); - try { - return _kt.fromValue(t, 0, r); - } catch (i2) { - if (i2.code !== z3.errors.INVALID_ARGUMENT) - throw i2; - } - return Lt.throwArgumentError("invalid FixedNumber value", "value", t); - } - static isFixedNumber(t) { - return !!(t && t._isFixedNumber); - } - }; - var Qn = kt.from(1); - var _s = kt.from("0.5"); - var Bs = "strings/5.7.0"; - var Jn = new z3(Bs); - var Pr; - (function(e2) { - e2.current = "", e2.NFC = "NFC", e2.NFD = "NFD", e2.NFKC = "NFKC", e2.NFKD = "NFKD"; - })(Pr || (Pr = {})); - var fr; - (function(e2) { - e2.UNEXPECTED_CONTINUE = "unexpected continuation byte", e2.BAD_PREFIX = "bad codepoint prefix", e2.OVERRUN = "string overrun", e2.MISSING_CONTINUE = "missing continuation byte", e2.OUT_OF_RANGE = "out of UTF-8 range", e2.UTF16_SURROGATE = "UTF-16 surrogate", e2.OVERLONG = "overlong representation"; - })(fr || (fr = {})); - function Rs(e2, t, r, i2, n3) { - return Jn.throwArgumentError(`invalid codepoint at offset ${t}; ${e2}`, "bytes", r); - } - function Yn(e2, t, r, i2, n3) { - if (e2 === fr.BAD_PREFIX || e2 === fr.UNEXPECTED_CONTINUE) { - let o2 = 0; - for (let h5 = t + 1; h5 < r.length && r[h5] >> 6 === 2; h5++) - o2++; - return o2; - } - return e2 === fr.OVERRUN ? r.length - t - 1 : 0; - } - function Cs(e2, t, r, i2, n3) { - return e2 === fr.OVERLONG ? (i2.push(n3), 0) : (i2.push(65533), Yn(e2, t, r)); - } - Object.freeze({ error: Rs, ignore: Yn, replace: Cs }); - function Si(e2, t = Pr.current) { - t != Pr.current && (Jn.checkNormalize(), e2 = e2.normalize(t)); - let r = []; - for (let i2 = 0; i2 < e2.length; i2++) { - const n3 = e2.charCodeAt(i2); - if (n3 < 128) - r.push(n3); - else if (n3 < 2048) - r.push(n3 >> 6 | 192), r.push(n3 & 63 | 128); - else if ((n3 & 64512) == 55296) { - i2++; - const o2 = e2.charCodeAt(i2); - if (i2 >= e2.length || (o2 & 64512) !== 56320) - throw new Error("invalid utf-8 string"); - const h5 = 65536 + ((n3 & 1023) << 10) + (o2 & 1023); - r.push(h5 >> 18 | 240), r.push(h5 >> 12 & 63 | 128), r.push(h5 >> 6 & 63 | 128), r.push(h5 & 63 | 128); - } else - r.push(n3 >> 12 | 224), r.push(n3 >> 6 & 63 | 128), r.push(n3 & 63 | 128); - } - return Pt(r); - } - function Os(e2) { - if (e2.length % 4 !== 0) - throw new Error("bad data"); - let t = []; - for (let r = 0; r < e2.length; r += 4) - t.push(parseInt(e2.substring(r, r + 4), 16)); - return t; - } - function Ni(e2, t) { - t || (t = function(n3) { - return [parseInt(n3, 16)]; - }); - let r = 0, i2 = {}; - return e2.split(",").forEach((n3) => { - let o2 = n3.split(":"); - r += parseInt(o2[0], 16), i2[r] = t(o2[1]); - }), i2; - } - function Gn(e2) { - let t = 0; - return e2.split(",").map((r) => { - let i2 = r.split("-"); - i2.length === 1 ? i2[1] = "0" : i2[1] === "" && (i2[1] = "1"); - let n3 = t + parseInt(i2[0], 16); - return t = parseInt(i2[1], 16), { l: n3, h: t }; - }); - } - Gn("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"), "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((e2) => parseInt(e2, 16)), Ni("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"), Ni("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"), Ni("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", Os), Gn("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); - var Wn = "hash/5.7.0"; - function Ps(e2) { - e2 = atob(e2); - const t = []; - for (let r = 0; r < e2.length; r++) - t.push(e2.charCodeAt(r)); - return Pt(t); - } - function Xn(e2, t) { - t == null && (t = 1); - const r = [], i2 = r.forEach, n3 = function(o2, h5) { - i2.call(o2, function(p3) { - h5 > 0 && Array.isArray(p3) ? n3(p3, h5 - 1) : r.push(p3); - }); - }; - return n3(e2, t), r; - } - function Ts(e2) { - const t = {}; - for (let r = 0; r < e2.length; r++) { - const i2 = e2[r]; - t[i2[0]] = i2[1]; - } - return t; - } - function Fs(e2) { - let t = 0; - function r() { - return e2[t++] << 8 | e2[t++]; - } - let i2 = r(), n3 = 1, o2 = [0, 1]; - for (let H = 1; H < i2; H++) - o2.push(n3 += r()); - let h5 = r(), p3 = t; - t += h5; - let b4 = 0, g3 = 0; - function w4() { - return b4 == 0 && (g3 = g3 << 8 | e2[t++], b4 = 8), g3 >> --b4 & 1; - } - const y4 = 31, S4 = Math.pow(2, y4), I2 = S4 >>> 1, N10 = I2 >> 1, R2 = S4 - 1; - let F = 0; - for (let H = 0; H < y4; H++) - F = F << 1 | w4(); - let U2 = [], Q = 0, Bt = S4; - for (; ; ) { - let H = Math.floor(((F - Q + 1) * n3 - 1) / Bt), L2 = 0, Tt = i2; - for (; Tt - L2 > 1; ) { - let Gt = L2 + Tt >>> 1; - H < o2[Gt] ? Tt = Gt : L2 = Gt; - } - if (L2 == 0) - break; - U2.push(L2); - let W = Q + Math.floor(Bt * o2[L2] / n3), Ot = Q + Math.floor(Bt * o2[L2 + 1] / n3) - 1; - for (; !((W ^ Ot) & I2); ) - F = F << 1 & R2 | w4(), W = W << 1 & R2, Ot = Ot << 1 & R2 | 1; - for (; W & ~Ot & N10; ) - F = F & I2 | F << 1 & R2 >>> 1 | w4(), W = W << 1 ^ I2, Ot = (Ot ^ I2) << 1 | I2 | 1; - Q = W, Bt = 1 + Ot - W; - } - let J = i2 - 4; - return U2.map((H) => { - switch (H - J) { - case 3: - return J + 65792 + (e2[p3++] << 16 | e2[p3++] << 8 | e2[p3++]); - case 2: - return J + 256 + (e2[p3++] << 8 | e2[p3++]); - case 1: - return J + e2[p3++]; - default: - return H - 1; - } - }); - } - function Ds(e2) { - let t = 0; - return () => e2[t++]; - } - function Us(e2) { - return Ds(Fs(e2)); - } - function ks(e2) { - return e2 & 1 ? ~e2 >> 1 : e2 >> 1; - } - function qs(e2, t) { - let r = Array(e2); - for (let i2 = 0; i2 < e2; i2++) - r[i2] = 1 + t(); - return r; - } - function Zn(e2, t) { - let r = Array(e2); - for (let i2 = 0, n3 = -1; i2 < e2; i2++) - r[i2] = n3 += 1 + t(); - return r; - } - function Ks(e2, t) { - let r = Array(e2); - for (let i2 = 0, n3 = 0; i2 < e2; i2++) - r[i2] = n3 += ks(t()); - return r; - } - function Tr(e2, t) { - let r = Zn(e2(), e2), i2 = e2(), n3 = Zn(i2, e2), o2 = qs(i2, e2); - for (let h5 = 0; h5 < i2; h5++) - for (let p3 = 0; p3 < o2[h5]; p3++) - r.push(n3[h5] + p3); - return t ? r.map((h5) => t[h5]) : r; - } - function Hs(e2) { - let t = []; - for (; ; ) { - let r = e2(); - if (r == 0) - break; - t.push(zs(r, e2)); - } - for (; ; ) { - let r = e2() - 1; - if (r < 0) - break; - t.push(js(r, e2)); - } - return Ts(Xn(t)); - } - function Ls(e2) { - let t = []; - for (; ; ) { - let r = e2(); - if (r == 0) - break; - t.push(r); - } - return t; - } - function $n(e2, t, r) { - let i2 = Array(e2).fill(void 0).map(() => []); - for (let n3 = 0; n3 < t; n3++) - Ks(e2, r).forEach((o2, h5) => i2[h5].push(o2)); - return i2; - } - function zs(e2, t) { - let r = 1 + t(), i2 = t(), n3 = Ls(t), o2 = $n(n3.length, 1 + e2, t); - return Xn(o2.map((h5, p3) => { - const b4 = h5[0], g3 = h5.slice(1); - return Array(n3[p3]).fill(void 0).map((w4, y4) => { - let S4 = y4 * i2; - return [b4 + y4 * r, g3.map((I2) => I2 + S4)]; - }); - })); - } - function js(e2, t) { - let r = 1 + t(); - return $n(r, 1 + e2, t).map((n3) => [n3[0], n3.slice(1)]); - } - function Vs(e2) { - let t = Tr(e2).sort((i2, n3) => i2 - n3); - return r(); - function r() { - let i2 = []; - for (; ; ) { - let g3 = Tr(e2, t); - if (g3.length == 0) - break; - i2.push({ set: new Set(g3), node: r() }); - } - i2.sort((g3, w4) => w4.set.size - g3.set.size); - let n3 = e2(), o2 = n3 % 3; - n3 = n3 / 3 | 0; - let h5 = !!(n3 & 1); - n3 >>= 1; - let p3 = n3 == 1, b4 = n3 == 2; - return { branches: i2, valid: o2, fe0f: h5, save: p3, check: b4 }; - } - } - function Qs() { - return Us(Ps("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); - } - var Fr = Qs(); - new Set(Tr(Fr)), new Set(Tr(Fr)), Hs(Fr), Vs(Fr), new z3(Wn); - var Js = new Uint8Array(32); - Js.fill(0); - var Ys = `Ethereum Signed Message: -`; - function tf(e2) { - return typeof e2 == "string" && (e2 = Si(e2)), wi(ys([Si(Ys), Si(String(e2.length)), e2])); - } - var Gs = "rlp/5.7.0"; - new z3(Gs); - var Ws = "address/5.7.0"; - var br = new z3(Ws); - function ef(e2) { - Qt(e2, 20) || br.throwArgumentError("invalid address", "address", e2), e2 = e2.toLowerCase(); - const t = e2.substring(2).split(""), r = new Uint8Array(40); - for (let n3 = 0; n3 < 40; n3++) - r[n3] = t[n3].charCodeAt(0); - const i2 = Pt(wi(r)); - for (let n3 = 0; n3 < 40; n3 += 2) - i2[n3 >> 1] >> 4 >= 8 && (t[n3] = t[n3].toUpperCase()), (i2[n3 >> 1] & 15) >= 8 && (t[n3 + 1] = t[n3 + 1].toUpperCase()); - return "0x" + t.join(""); - } - var Xs = 9007199254740991; - function Zs(e2) { - return Math.log10 ? Math.log10(e2) : Math.log(e2) / Math.LN10; - } - var Ii = {}; - for (let e2 = 0; e2 < 10; e2++) - Ii[String(e2)] = String(e2); - for (let e2 = 0; e2 < 26; e2++) - Ii[String.fromCharCode(65 + e2)] = String(10 + e2); - var rf = Math.floor(Zs(Xs)); - function $s(e2) { - e2 = e2.toUpperCase(), e2 = e2.substring(4) + e2.substring(0, 2) + "00"; - let t = e2.split("").map((i2) => Ii[i2]).join(""); - for (; t.length >= rf; ) { - let i2 = t.substring(0, rf); - t = parseInt(i2, 10) % 97 + t.substring(i2.length); - } - let r = String(98 - parseInt(t, 10) % 97); - for (; r.length < 2; ) - r = "0" + r; - return r; - } - function ta(e2) { - let t = null; - if (typeof e2 != "string" && br.throwArgumentError("invalid address", "address", e2), e2.match(/^(0x)?[0-9a-fA-F]{40}$/)) - e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), t = ef(e2), e2.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && t !== e2 && br.throwArgumentError("bad address checksum", "address", e2); - else if (e2.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { - for (e2.substring(2, 4) !== $s(e2) && br.throwArgumentError("bad icap checksum", "address", e2), t = Is(e2.substring(4)); t.length < 40; ) - t = "0" + t; - t = ef("0x" + t); - } else - br.throwArgumentError("invalid address", "address", e2); - return t; - } - var ea = "properties/5.7.0"; - new z3(ea); - function yr(e2, t, r) { - Object.defineProperty(e2, t, { enumerable: true, value: r, writable: false }); - } - new z3(Wn); - var ra = new Uint8Array(32); - ra.fill(0), G.from(-1); - var ia = G.from(0); - var na = G.from(1); - G.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), fe(na.toHexString(), 32), fe(ia.toHexString(), 32); - var oe = {}; - var V = {}; - var wr = nf; - function nf(e2, t) { - if (!e2) - throw new Error(t || "Assertion failed"); - } - nf.equal = function(t, r, i2) { - if (t != r) - throw new Error(i2 || "Assertion failed: " + t + " != " + r); - }; - var _i = { exports: {} }; - typeof Object.create == "function" ? _i.exports = function(t, r) { - r && (t.super_ = r, t.prototype = Object.create(r.prototype, { constructor: { value: t, enumerable: false, writable: true, configurable: true } })); - } : _i.exports = function(t, r) { - if (r) { - t.super_ = r; - var i2 = function() { - }; - i2.prototype = r.prototype, t.prototype = new i2(), t.prototype.constructor = t; - } - }; - var fa = wr; - var oa = _i.exports; - V.inherits = oa; - function sa(e2, t) { - return (e2.charCodeAt(t) & 64512) !== 55296 || t < 0 || t + 1 >= e2.length ? false : (e2.charCodeAt(t + 1) & 64512) === 56320; - } - function aa(e2, t) { - if (Array.isArray(e2)) - return e2.slice(); - if (!e2) - return []; - var r = []; - if (typeof e2 == "string") - if (t) { - if (t === "hex") - for (e2 = e2.replace(/[^a-z0-9]+/ig, ""), e2.length % 2 !== 0 && (e2 = "0" + e2), n3 = 0; n3 < e2.length; n3 += 2) - r.push(parseInt(e2[n3] + e2[n3 + 1], 16)); - } else - for (var i2 = 0, n3 = 0; n3 < e2.length; n3++) { - var o2 = e2.charCodeAt(n3); - o2 < 128 ? r[i2++] = o2 : o2 < 2048 ? (r[i2++] = o2 >> 6 | 192, r[i2++] = o2 & 63 | 128) : sa(e2, n3) ? (o2 = 65536 + ((o2 & 1023) << 10) + (e2.charCodeAt(++n3) & 1023), r[i2++] = o2 >> 18 | 240, r[i2++] = o2 >> 12 & 63 | 128, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128) : (r[i2++] = o2 >> 12 | 224, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128); - } - else - for (n3 = 0; n3 < e2.length; n3++) - r[n3] = e2[n3] | 0; - return r; - } - V.toArray = aa; - function ua(e2) { - for (var t = "", r = 0; r < e2.length; r++) - t += of(e2[r].toString(16)); - return t; - } - V.toHex = ua; - function ff(e2) { - var t = e2 >>> 24 | e2 >>> 8 & 65280 | e2 << 8 & 16711680 | (e2 & 255) << 24; - return t >>> 0; - } - V.htonl = ff; - function ha(e2, t) { - for (var r = "", i2 = 0; i2 < e2.length; i2++) { - var n3 = e2[i2]; - t === "little" && (n3 = ff(n3)), r += sf(n3.toString(16)); - } - return r; - } - V.toHex32 = ha; - function of(e2) { - return e2.length === 1 ? "0" + e2 : e2; - } - V.zero2 = of; - function sf(e2) { - return e2.length === 7 ? "0" + e2 : e2.length === 6 ? "00" + e2 : e2.length === 5 ? "000" + e2 : e2.length === 4 ? "0000" + e2 : e2.length === 3 ? "00000" + e2 : e2.length === 2 ? "000000" + e2 : e2.length === 1 ? "0000000" + e2 : e2; - } - V.zero8 = sf; - function ca(e2, t, r, i2) { - var n3 = r - t; - fa(n3 % 4 === 0); - for (var o2 = new Array(n3 / 4), h5 = 0, p3 = t; h5 < o2.length; h5++, p3 += 4) { - var b4; - i2 === "big" ? b4 = e2[p3] << 24 | e2[p3 + 1] << 16 | e2[p3 + 2] << 8 | e2[p3 + 3] : b4 = e2[p3 + 3] << 24 | e2[p3 + 2] << 16 | e2[p3 + 1] << 8 | e2[p3], o2[h5] = b4 >>> 0; - } - return o2; - } - V.join32 = ca; - function la(e2, t) { - for (var r = new Array(e2.length * 4), i2 = 0, n3 = 0; i2 < e2.length; i2++, n3 += 4) { - var o2 = e2[i2]; - t === "big" ? (r[n3] = o2 >>> 24, r[n3 + 1] = o2 >>> 16 & 255, r[n3 + 2] = o2 >>> 8 & 255, r[n3 + 3] = o2 & 255) : (r[n3 + 3] = o2 >>> 24, r[n3 + 2] = o2 >>> 16 & 255, r[n3 + 1] = o2 >>> 8 & 255, r[n3] = o2 & 255); - } - return r; - } - V.split32 = la; - function da(e2, t) { - return e2 >>> t | e2 << 32 - t; - } - V.rotr32 = da; - function pa(e2, t) { - return e2 << t | e2 >>> 32 - t; - } - V.rotl32 = pa; - function va(e2, t) { - return e2 + t >>> 0; - } - V.sum32 = va; - function ga(e2, t, r) { - return e2 + t + r >>> 0; - } - V.sum32_3 = ga; - function ma(e2, t, r, i2) { - return e2 + t + r + i2 >>> 0; - } - V.sum32_4 = ma; - function Aa(e2, t, r, i2, n3) { - return e2 + t + r + i2 + n3 >>> 0; - } - V.sum32_5 = Aa; - function ba(e2, t, r, i2) { - var n3 = e2[t], o2 = e2[t + 1], h5 = i2 + o2 >>> 0, p3 = (h5 < i2 ? 1 : 0) + r + n3; - e2[t] = p3 >>> 0, e2[t + 1] = h5; - } - V.sum64 = ba; - function ya(e2, t, r, i2) { - var n3 = t + i2 >>> 0, o2 = (n3 < t ? 1 : 0) + e2 + r; - return o2 >>> 0; - } - V.sum64_hi = ya; - function wa(e2, t, r, i2) { - var n3 = t + i2; - return n3 >>> 0; - } - V.sum64_lo = wa; - function xa(e2, t, r, i2, n3, o2, h5, p3) { - var b4 = 0, g3 = t; - g3 = g3 + i2 >>> 0, b4 += g3 < t ? 1 : 0, g3 = g3 + o2 >>> 0, b4 += g3 < o2 ? 1 : 0, g3 = g3 + p3 >>> 0, b4 += g3 < p3 ? 1 : 0; - var w4 = e2 + r + n3 + h5 + b4; - return w4 >>> 0; - } - V.sum64_4_hi = xa; - function Ma(e2, t, r, i2, n3, o2, h5, p3) { - var b4 = t + i2 + o2 + p3; - return b4 >>> 0; - } - V.sum64_4_lo = Ma; - function Ea(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { - var w4 = 0, y4 = t; - y4 = y4 + i2 >>> 0, w4 += y4 < t ? 1 : 0, y4 = y4 + o2 >>> 0, w4 += y4 < o2 ? 1 : 0, y4 = y4 + p3 >>> 0, w4 += y4 < p3 ? 1 : 0, y4 = y4 + g3 >>> 0, w4 += y4 < g3 ? 1 : 0; - var S4 = e2 + r + n3 + h5 + b4 + w4; - return S4 >>> 0; - } - V.sum64_5_hi = Ea; - function Sa(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { - var w4 = t + i2 + o2 + p3 + g3; - return w4 >>> 0; - } - V.sum64_5_lo = Sa; - function Na(e2, t, r) { - var i2 = t << 32 - r | e2 >>> r; - return i2 >>> 0; - } - V.rotr64_hi = Na; - function Ia(e2, t, r) { - var i2 = e2 << 32 - r | t >>> r; - return i2 >>> 0; - } - V.rotr64_lo = Ia; - function _a(e2, t, r) { - return e2 >>> r; - } - V.shr64_hi = _a; - function Ba(e2, t, r) { - var i2 = e2 << 32 - r | t >>> r; - return i2 >>> 0; - } - V.shr64_lo = Ba; - var or2 = {}; - var af = V; - var Ra = wr; - function Dr() { - this.pending = null, this.pendingTotal = 0, this.blockSize = this.constructor.blockSize, this.outSize = this.constructor.outSize, this.hmacStrength = this.constructor.hmacStrength, this.padLength = this.constructor.padLength / 8, this.endian = "big", this._delta8 = this.blockSize / 8, this._delta32 = this.blockSize / 32; - } - or2.BlockHash = Dr, Dr.prototype.update = function(t, r) { - if (t = af.toArray(t, r), this.pending ? this.pending = this.pending.concat(t) : this.pending = t, this.pendingTotal += t.length, this.pending.length >= this._delta8) { - t = this.pending; - var i2 = t.length % this._delta8; - this.pending = t.slice(t.length - i2, t.length), this.pending.length === 0 && (this.pending = null), t = af.join32(t, 0, t.length - i2, this.endian); - for (var n3 = 0; n3 < t.length; n3 += this._delta32) - this._update(t, n3, n3 + this._delta32); - } - return this; - }, Dr.prototype.digest = function(t) { - return this.update(this._pad()), Ra(this.pending === null), this._digest(t); - }, Dr.prototype._pad = function() { - var t = this.pendingTotal, r = this._delta8, i2 = r - (t + this.padLength) % r, n3 = new Array(i2 + this.padLength); - n3[0] = 128; - for (var o2 = 1; o2 < i2; o2++) - n3[o2] = 0; - if (t <<= 3, this.endian === "big") { - for (var h5 = 8; h5 < this.padLength; h5++) - n3[o2++] = 0; - n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = t >>> 24 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t & 255; - } else - for (n3[o2++] = t & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 24 & 255, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, h5 = 8; h5 < this.padLength; h5++) - n3[o2++] = 0; - return n3; - }; - var sr = {}; - var se = {}; - var Ca = V; - var ae = Ca.rotr32; - function Oa(e2, t, r, i2) { - if (e2 === 0) - return uf(t, r, i2); - if (e2 === 1 || e2 === 3) - return cf(t, r, i2); - if (e2 === 2) - return hf(t, r, i2); - } - se.ft_1 = Oa; - function uf(e2, t, r) { - return e2 & t ^ ~e2 & r; - } - se.ch32 = uf; - function hf(e2, t, r) { - return e2 & t ^ e2 & r ^ t & r; - } - se.maj32 = hf; - function cf(e2, t, r) { - return e2 ^ t ^ r; - } - se.p32 = cf; - function Pa(e2) { - return ae(e2, 2) ^ ae(e2, 13) ^ ae(e2, 22); - } - se.s0_256 = Pa; - function Ta(e2) { - return ae(e2, 6) ^ ae(e2, 11) ^ ae(e2, 25); - } - se.s1_256 = Ta; - function Fa(e2) { - return ae(e2, 7) ^ ae(e2, 18) ^ e2 >>> 3; - } - se.g0_256 = Fa; - function Da(e2) { - return ae(e2, 17) ^ ae(e2, 19) ^ e2 >>> 10; - } - se.g1_256 = Da; - var ar = V; - var Ua = or2; - var ka = se; - var Bi = ar.rotl32; - var xr = ar.sum32; - var qa = ar.sum32_5; - var Ka = ka.ft_1; - var lf = Ua.BlockHash; - var Ha = [1518500249, 1859775393, 2400959708, 3395469782]; - function ue() { - if (!(this instanceof ue)) - return new ue(); - lf.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.W = new Array(80); - } - ar.inherits(ue, lf); - var La = ue; - ue.blockSize = 512, ue.outSize = 160, ue.hmacStrength = 80, ue.padLength = 64, ue.prototype._update = function(t, r) { - for (var i2 = this.W, n3 = 0; n3 < 16; n3++) - i2[n3] = t[r + n3]; - for (; n3 < i2.length; n3++) - i2[n3] = Bi(i2[n3 - 3] ^ i2[n3 - 8] ^ i2[n3 - 14] ^ i2[n3 - 16], 1); - var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4]; - for (n3 = 0; n3 < i2.length; n3++) { - var w4 = ~~(n3 / 20), y4 = qa(Bi(o2, 5), Ka(w4, h5, p3, b4), g3, i2[n3], Ha[w4]); - g3 = b4, b4 = p3, p3 = Bi(h5, 30), h5 = o2, o2 = y4; - } - this.h[0] = xr(this.h[0], o2), this.h[1] = xr(this.h[1], h5), this.h[2] = xr(this.h[2], p3), this.h[3] = xr(this.h[3], b4), this.h[4] = xr(this.h[4], g3); - }, ue.prototype._digest = function(t) { - return t === "hex" ? ar.toHex32(this.h, "big") : ar.split32(this.h, "big"); - }; - var ur = V; - var za = or2; - var hr = se; - var ja = wr; - var re = ur.sum32; - var Va = ur.sum32_4; - var Qa = ur.sum32_5; - var Ja = hr.ch32; - var Ya = hr.maj32; - var Ga = hr.s0_256; - var Wa = hr.s1_256; - var Xa = hr.g0_256; - var Za = hr.g1_256; - var df = za.BlockHash; - var $a = [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]; - function he() { - if (!(this instanceof he)) - return new he(); - df.call(this), this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.k = $a, this.W = new Array(64); - } - ur.inherits(he, df); - var pf = he; - he.blockSize = 512, he.outSize = 256, he.hmacStrength = 192, he.padLength = 64, he.prototype._update = function(t, r) { - for (var i2 = this.W, n3 = 0; n3 < 16; n3++) - i2[n3] = t[r + n3]; - for (; n3 < i2.length; n3++) - i2[n3] = Va(Za(i2[n3 - 2]), i2[n3 - 7], Xa(i2[n3 - 15]), i2[n3 - 16]); - var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4], w4 = this.h[5], y4 = this.h[6], S4 = this.h[7]; - for (ja(this.k.length === i2.length), n3 = 0; n3 < i2.length; n3++) { - var I2 = Qa(S4, Wa(g3), Ja(g3, w4, y4), this.k[n3], i2[n3]), N10 = re(Ga(o2), Ya(o2, h5, p3)); - S4 = y4, y4 = w4, w4 = g3, g3 = re(b4, I2), b4 = p3, p3 = h5, h5 = o2, o2 = re(I2, N10); - } - this.h[0] = re(this.h[0], o2), this.h[1] = re(this.h[1], h5), this.h[2] = re(this.h[2], p3), this.h[3] = re(this.h[3], b4), this.h[4] = re(this.h[4], g3), this.h[5] = re(this.h[5], w4), this.h[6] = re(this.h[6], y4), this.h[7] = re(this.h[7], S4); - }, he.prototype._digest = function(t) { - return t === "hex" ? ur.toHex32(this.h, "big") : ur.split32(this.h, "big"); - }; - var Ri = V; - var vf = pf; - function be() { - if (!(this instanceof be)) - return new be(); - vf.call(this), this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]; - } - Ri.inherits(be, vf); - var t0 = be; - be.blockSize = 512, be.outSize = 224, be.hmacStrength = 192, be.padLength = 64, be.prototype._digest = function(t) { - return t === "hex" ? Ri.toHex32(this.h.slice(0, 7), "big") : Ri.split32(this.h.slice(0, 7), "big"); - }; - var Vt = V; - var e0 = or2; - var r0 = wr; - var ce = Vt.rotr64_hi; - var le = Vt.rotr64_lo; - var gf = Vt.shr64_hi; - var mf = Vt.shr64_lo; - var _e = Vt.sum64; - var Ci = Vt.sum64_hi; - var Oi = Vt.sum64_lo; - var i0 = Vt.sum64_4_hi; - var n0 = Vt.sum64_4_lo; - var f0 = Vt.sum64_5_hi; - var o0 = Vt.sum64_5_lo; - var Af = e0.BlockHash; - var s0 = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591]; - function ie() { - if (!(this instanceof ie)) - return new ie(); - Af.call(this), this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209], this.k = s0, this.W = new Array(160); - } - Vt.inherits(ie, Af); - var bf = ie; - ie.blockSize = 1024, ie.outSize = 512, ie.hmacStrength = 192, ie.padLength = 128, ie.prototype._prepareBlock = function(t, r) { - for (var i2 = this.W, n3 = 0; n3 < 32; n3++) - i2[n3] = t[r + n3]; - for (; n3 < i2.length; n3 += 2) { - var o2 = A0(i2[n3 - 4], i2[n3 - 3]), h5 = b0(i2[n3 - 4], i2[n3 - 3]), p3 = i2[n3 - 14], b4 = i2[n3 - 13], g3 = g0(i2[n3 - 30], i2[n3 - 29]), w4 = m0(i2[n3 - 30], i2[n3 - 29]), y4 = i2[n3 - 32], S4 = i2[n3 - 31]; - i2[n3] = i0(o2, h5, p3, b4, g3, w4, y4, S4), i2[n3 + 1] = n0(o2, h5, p3, b4, g3, w4, y4, S4); - } - }, ie.prototype._update = function(t, r) { - this._prepareBlock(t, r); - var i2 = this.W, n3 = this.h[0], o2 = this.h[1], h5 = this.h[2], p3 = this.h[3], b4 = this.h[4], g3 = this.h[5], w4 = this.h[6], y4 = this.h[7], S4 = this.h[8], I2 = this.h[9], N10 = this.h[10], R2 = this.h[11], F = this.h[12], U2 = this.h[13], Q = this.h[14], Bt = this.h[15]; - r0(this.k.length === i2.length); - for (var J = 0; J < i2.length; J += 2) { - var H = Q, L2 = Bt, Tt = p0(S4, I2), W = v0(S4, I2), Ot = a0(S4, I2, N10, R2, F), Gt = u0(S4, I2, N10, R2, F, U2), Y = this.k[J], Wt = this.k[J + 1], A2 = i2[J], f4 = i2[J + 1], a3 = f0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4), c4 = o0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4); - H = l0(n3, o2), L2 = d0(n3, o2), Tt = h0(n3, o2, h5, p3, b4), W = c0(n3, o2, h5, p3, b4, g3); - var d3 = Ci(H, L2, Tt, W), m3 = Oi(H, L2, Tt, W); - Q = F, Bt = U2, F = N10, U2 = R2, N10 = S4, R2 = I2, S4 = Ci(w4, y4, a3, c4), I2 = Oi(y4, y4, a3, c4), w4 = b4, y4 = g3, b4 = h5, g3 = p3, h5 = n3, p3 = o2, n3 = Ci(a3, c4, d3, m3), o2 = Oi(a3, c4, d3, m3); - } - _e(this.h, 0, n3, o2), _e(this.h, 2, h5, p3), _e(this.h, 4, b4, g3), _e(this.h, 6, w4, y4), _e(this.h, 8, S4, I2), _e(this.h, 10, N10, R2), _e(this.h, 12, F, U2), _e(this.h, 14, Q, Bt); - }, ie.prototype._digest = function(t) { - return t === "hex" ? Vt.toHex32(this.h, "big") : Vt.split32(this.h, "big"); - }; - function a0(e2, t, r, i2, n3) { - var o2 = e2 & r ^ ~e2 & n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function u0(e2, t, r, i2, n3, o2) { - var h5 = t & i2 ^ ~t & o2; - return h5 < 0 && (h5 += 4294967296), h5; - } - function h0(e2, t, r, i2, n3) { - var o2 = e2 & r ^ e2 & n3 ^ r & n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function c0(e2, t, r, i2, n3, o2) { - var h5 = t & i2 ^ t & o2 ^ i2 & o2; - return h5 < 0 && (h5 += 4294967296), h5; - } - function l0(e2, t) { - var r = ce(e2, t, 28), i2 = ce(t, e2, 2), n3 = ce(t, e2, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function d0(e2, t) { - var r = le(e2, t, 28), i2 = le(t, e2, 2), n3 = le(t, e2, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function p0(e2, t) { - var r = ce(e2, t, 14), i2 = ce(e2, t, 18), n3 = ce(t, e2, 9), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function v0(e2, t) { - var r = le(e2, t, 14), i2 = le(e2, t, 18), n3 = le(t, e2, 9), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function g0(e2, t) { - var r = ce(e2, t, 1), i2 = ce(e2, t, 8), n3 = gf(e2, t, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function m0(e2, t) { - var r = le(e2, t, 1), i2 = le(e2, t, 8), n3 = mf(e2, t, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function A0(e2, t) { - var r = ce(e2, t, 19), i2 = ce(t, e2, 29), n3 = gf(e2, t, 6), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function b0(e2, t) { - var r = le(e2, t, 19), i2 = le(t, e2, 29), n3 = mf(e2, t, 6), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - var Pi = V; - var yf = bf; - function ye() { - if (!(this instanceof ye)) - return new ye(); - yf.call(this), this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]; - } - Pi.inherits(ye, yf); - var y0 = ye; - ye.blockSize = 1024, ye.outSize = 384, ye.hmacStrength = 192, ye.padLength = 128, ye.prototype._digest = function(t) { - return t === "hex" ? Pi.toHex32(this.h.slice(0, 12), "big") : Pi.split32(this.h.slice(0, 12), "big"); - }, sr.sha1 = La, sr.sha224 = t0, sr.sha256 = pf, sr.sha384 = y0, sr.sha512 = bf; - var wf = {}; - var We = V; - var w0 = or2; - var Ur = We.rotl32; - var xf = We.sum32; - var Mr = We.sum32_3; - var Mf = We.sum32_4; - var Ef = w0.BlockHash; - function de() { - if (!(this instanceof de)) - return new de(); - Ef.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.endian = "little"; - } - We.inherits(de, Ef), wf.ripemd160 = de, de.blockSize = 512, de.outSize = 160, de.hmacStrength = 192, de.padLength = 64, de.prototype._update = function(t, r) { - for (var i2 = this.h[0], n3 = this.h[1], o2 = this.h[2], h5 = this.h[3], p3 = this.h[4], b4 = i2, g3 = n3, w4 = o2, y4 = h5, S4 = p3, I2 = 0; I2 < 80; I2++) { - var N10 = xf(Ur(Mf(i2, Sf(I2, n3, o2, h5), t[E0[I2] + r], x0(I2)), N0[I2]), p3); - i2 = p3, p3 = h5, h5 = Ur(o2, 10), o2 = n3, n3 = N10, N10 = xf(Ur(Mf(b4, Sf(79 - I2, g3, w4, y4), t[S0[I2] + r], M0(I2)), I0[I2]), S4), b4 = S4, S4 = y4, y4 = Ur(w4, 10), w4 = g3, g3 = N10; - } - N10 = Mr(this.h[1], o2, y4), this.h[1] = Mr(this.h[2], h5, S4), this.h[2] = Mr(this.h[3], p3, b4), this.h[3] = Mr(this.h[4], i2, g3), this.h[4] = Mr(this.h[0], n3, w4), this.h[0] = N10; - }, de.prototype._digest = function(t) { - return t === "hex" ? We.toHex32(this.h, "little") : We.split32(this.h, "little"); - }; - function Sf(e2, t, r, i2) { - return e2 <= 15 ? t ^ r ^ i2 : e2 <= 31 ? t & r | ~t & i2 : e2 <= 47 ? (t | ~r) ^ i2 : e2 <= 63 ? t & i2 | r & ~i2 : t ^ (r | ~i2); - } - function x0(e2) { - return e2 <= 15 ? 0 : e2 <= 31 ? 1518500249 : e2 <= 47 ? 1859775393 : e2 <= 63 ? 2400959708 : 2840853838; - } - function M0(e2) { - return e2 <= 15 ? 1352829926 : e2 <= 31 ? 1548603684 : e2 <= 47 ? 1836072691 : e2 <= 63 ? 2053994217 : 0; - } - var E0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; - var S0 = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; - var N0 = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]; - var I0 = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; - var _0 = V; - var B0 = wr; - function cr(e2, t, r) { - if (!(this instanceof cr)) - return new cr(e2, t, r); - this.Hash = e2, this.blockSize = e2.blockSize / 8, this.outSize = e2.outSize / 8, this.inner = null, this.outer = null, this._init(_0.toArray(t, r)); - } - var R0 = cr; - cr.prototype._init = function(t) { - t.length > this.blockSize && (t = new this.Hash().update(t).digest()), B0(t.length <= this.blockSize); - for (var r = t.length; r < this.blockSize; r++) - t.push(0); - for (r = 0; r < t.length; r++) - t[r] ^= 54; - for (this.inner = new this.Hash().update(t), r = 0; r < t.length; r++) - t[r] ^= 106; - this.outer = new this.Hash().update(t); - }, cr.prototype.update = function(t, r) { - return this.inner.update(t, r), this; - }, cr.prototype.digest = function(t) { - return this.outer.update(this.inner.digest()), this.outer.digest(t); - }, function(e2) { - var t = e2; - t.utils = V, t.common = or2, t.sha = sr, t.ripemd = wf, t.hmac = R0, t.sha1 = t.sha.sha1, t.sha256 = t.sha.sha256, t.sha224 = t.sha.sha224, t.sha384 = t.sha.sha384, t.sha512 = t.sha.sha512, t.ripemd160 = t.ripemd.ripemd160; - }(oe); - function lr(e2, t, r) { - return r = { path: t, exports: {}, require: function(i2, n3) { - return C0(i2, n3 ?? r.path); - } }, e2(r, r.exports), r.exports; - } - function C0() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); - } - var Ti = Nf; - function Nf(e2, t) { - if (!e2) - throw new Error(t || "Assertion failed"); - } - Nf.equal = function(t, r, i2) { - if (t != r) - throw new Error(i2 || "Assertion failed: " + t + " != " + r); - }; - var ne = lr(function(e2, t) { - var r = t; - function i2(h5, p3) { - if (Array.isArray(h5)) - return h5.slice(); - if (!h5) - return []; - var b4 = []; - if (typeof h5 != "string") { - for (var g3 = 0; g3 < h5.length; g3++) - b4[g3] = h5[g3] | 0; - return b4; - } - if (p3 === "hex") { - h5 = h5.replace(/[^a-z0-9]+/ig, ""), h5.length % 2 !== 0 && (h5 = "0" + h5); - for (var g3 = 0; g3 < h5.length; g3 += 2) - b4.push(parseInt(h5[g3] + h5[g3 + 1], 16)); - } else - for (var g3 = 0; g3 < h5.length; g3++) { - var w4 = h5.charCodeAt(g3), y4 = w4 >> 8, S4 = w4 & 255; - y4 ? b4.push(y4, S4) : b4.push(S4); - } - return b4; - } - r.toArray = i2; - function n3(h5) { - return h5.length === 1 ? "0" + h5 : h5; - } - r.zero2 = n3; - function o2(h5) { - for (var p3 = "", b4 = 0; b4 < h5.length; b4++) - p3 += n3(h5[b4].toString(16)); - return p3; - } - r.toHex = o2, r.encode = function(p3, b4) { - return b4 === "hex" ? o2(p3) : p3; - }; - }); - var Jt = lr(function(e2, t) { - var r = t; - r.assert = Ti, r.toArray = ne.toArray, r.zero2 = ne.zero2, r.toHex = ne.toHex, r.encode = ne.encode; - function i2(b4, g3, w4) { - var y4 = new Array(Math.max(b4.bitLength(), w4) + 1); - y4.fill(0); - for (var S4 = 1 << g3 + 1, I2 = b4.clone(), N10 = 0; N10 < y4.length; N10++) { - var R2, F = I2.andln(S4 - 1); - I2.isOdd() ? (F > (S4 >> 1) - 1 ? R2 = (S4 >> 1) - F : R2 = F, I2.isubn(R2)) : R2 = 0, y4[N10] = R2, I2.iushrn(1); - } - return y4; - } - r.getNAF = i2; - function n3(b4, g3) { - var w4 = [[], []]; - b4 = b4.clone(), g3 = g3.clone(); - for (var y4 = 0, S4 = 0, I2; b4.cmpn(-y4) > 0 || g3.cmpn(-S4) > 0; ) { - var N10 = b4.andln(3) + y4 & 3, R2 = g3.andln(3) + S4 & 3; - N10 === 3 && (N10 = -1), R2 === 3 && (R2 = -1); - var F; - N10 & 1 ? (I2 = b4.andln(7) + y4 & 7, (I2 === 3 || I2 === 5) && R2 === 2 ? F = -N10 : F = N10) : F = 0, w4[0].push(F); - var U2; - R2 & 1 ? (I2 = g3.andln(7) + S4 & 7, (I2 === 3 || I2 === 5) && N10 === 2 ? U2 = -R2 : U2 = R2) : U2 = 0, w4[1].push(U2), 2 * y4 === F + 1 && (y4 = 1 - y4), 2 * S4 === U2 + 1 && (S4 = 1 - S4), b4.iushrn(1), g3.iushrn(1); - } - return w4; - } - r.getJSF = n3; - function o2(b4, g3, w4) { - var y4 = "_" + g3; - b4.prototype[g3] = function() { - return this[y4] !== void 0 ? this[y4] : this[y4] = w4.call(this); - }; - } - r.cachedProperty = o2; - function h5(b4) { - return typeof b4 == "string" ? r.toArray(b4, "hex") : b4; - } - r.parseBytes = h5; - function p3(b4) { - return new K2(b4, "hex", "le"); - } - r.intFromLE = p3; - }); - var kr = Jt.getNAF; - var O0 = Jt.getJSF; - var qr = Jt.assert; - function Be(e2, t) { - this.type = e2, this.p = new K2(t.p, 16), this.red = t.prime ? K2.red(t.prime) : K2.mont(this.p), this.zero = new K2(0).toRed(this.red), this.one = new K2(1).toRed(this.red), this.two = new K2(2).toRed(this.red), this.n = t.n && new K2(t.n, 16), this.g = t.g && this.pointFromJSON(t.g, t.gRed), this._wnafT1 = new Array(4), this._wnafT2 = new Array(4), this._wnafT3 = new Array(4), this._wnafT4 = new Array(4), this._bitLength = this.n ? this.n.bitLength() : 0; - var r = this.n && this.p.div(this.n); - !r || r.cmpn(100) > 0 ? this.redN = null : (this._maxwellTrick = true, this.redN = this.n.toRed(this.red)); - } - var Xe = Be; - Be.prototype.point = function() { - throw new Error("Not implemented"); - }, Be.prototype.validate = function() { - throw new Error("Not implemented"); - }, Be.prototype._fixedNafMul = function(t, r) { - qr(t.precomputed); - var i2 = t._getDoubles(), n3 = kr(r, 1, this._bitLength), o2 = (1 << i2.step + 1) - (i2.step % 2 === 0 ? 2 : 1); - o2 /= 3; - var h5 = [], p3, b4; - for (p3 = 0; p3 < n3.length; p3 += i2.step) { - b4 = 0; - for (var g3 = p3 + i2.step - 1; g3 >= p3; g3--) - b4 = (b4 << 1) + n3[g3]; - h5.push(b4); - } - for (var w4 = this.jpoint(null, null, null), y4 = this.jpoint(null, null, null), S4 = o2; S4 > 0; S4--) { - for (p3 = 0; p3 < h5.length; p3++) - b4 = h5[p3], b4 === S4 ? y4 = y4.mixedAdd(i2.points[p3]) : b4 === -S4 && (y4 = y4.mixedAdd(i2.points[p3].neg())); - w4 = w4.add(y4); - } - return w4.toP(); - }, Be.prototype._wnafMul = function(t, r) { - var i2 = 4, n3 = t._getNAFPoints(i2); - i2 = n3.wnd; - for (var o2 = n3.points, h5 = kr(r, i2, this._bitLength), p3 = this.jpoint(null, null, null), b4 = h5.length - 1; b4 >= 0; b4--) { - for (var g3 = 0; b4 >= 0 && h5[b4] === 0; b4--) - g3++; - if (b4 >= 0 && g3++, p3 = p3.dblp(g3), b4 < 0) - break; - var w4 = h5[b4]; - qr(w4 !== 0), t.type === "affine" ? w4 > 0 ? p3 = p3.mixedAdd(o2[w4 - 1 >> 1]) : p3 = p3.mixedAdd(o2[-w4 - 1 >> 1].neg()) : w4 > 0 ? p3 = p3.add(o2[w4 - 1 >> 1]) : p3 = p3.add(o2[-w4 - 1 >> 1].neg()); - } - return t.type === "affine" ? p3.toP() : p3; - }, Be.prototype._wnafMulAdd = function(t, r, i2, n3, o2) { - var h5 = this._wnafT1, p3 = this._wnafT2, b4 = this._wnafT3, g3 = 0, w4, y4, S4; - for (w4 = 0; w4 < n3; w4++) { - S4 = r[w4]; - var I2 = S4._getNAFPoints(t); - h5[w4] = I2.wnd, p3[w4] = I2.points; - } - for (w4 = n3 - 1; w4 >= 1; w4 -= 2) { - var N10 = w4 - 1, R2 = w4; - if (h5[N10] !== 1 || h5[R2] !== 1) { - b4[N10] = kr(i2[N10], h5[N10], this._bitLength), b4[R2] = kr(i2[R2], h5[R2], this._bitLength), g3 = Math.max(b4[N10].length, g3), g3 = Math.max(b4[R2].length, g3); - continue; - } - var F = [r[N10], null, null, r[R2]]; - r[N10].y.cmp(r[R2].y) === 0 ? (F[1] = r[N10].add(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())) : r[N10].y.cmp(r[R2].y.redNeg()) === 0 ? (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].add(r[R2].neg())) : (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())); - var U2 = [-3, -1, -5, -7, 0, 7, 5, 1, 3], Q = O0(i2[N10], i2[R2]); - for (g3 = Math.max(Q[0].length, g3), b4[N10] = new Array(g3), b4[R2] = new Array(g3), y4 = 0; y4 < g3; y4++) { - var Bt = Q[0][y4] | 0, J = Q[1][y4] | 0; - b4[N10][y4] = U2[(Bt + 1) * 3 + (J + 1)], b4[R2][y4] = 0, p3[N10] = F; - } - } - var H = this.jpoint(null, null, null), L2 = this._wnafT4; - for (w4 = g3; w4 >= 0; w4--) { - for (var Tt = 0; w4 >= 0; ) { - var W = true; - for (y4 = 0; y4 < n3; y4++) - L2[y4] = b4[y4][w4] | 0, L2[y4] !== 0 && (W = false); - if (!W) - break; - Tt++, w4--; - } - if (w4 >= 0 && Tt++, H = H.dblp(Tt), w4 < 0) - break; - for (y4 = 0; y4 < n3; y4++) { - var Ot = L2[y4]; - Ot !== 0 && (Ot > 0 ? S4 = p3[y4][Ot - 1 >> 1] : Ot < 0 && (S4 = p3[y4][-Ot - 1 >> 1].neg()), S4.type === "affine" ? H = H.mixedAdd(S4) : H = H.add(S4)); - } - } - for (w4 = 0; w4 < n3; w4++) - p3[w4] = null; - return o2 ? H : H.toP(); - }; - function Zt(e2, t) { - this.curve = e2, this.type = t, this.precomputed = null; - } - Be.BasePoint = Zt, Zt.prototype.eq = function() { - throw new Error("Not implemented"); - }, Zt.prototype.validate = function() { - return this.curve.validate(this); - }, Be.prototype.decodePoint = function(t, r) { - t = Jt.toArray(t, r); - var i2 = this.p.byteLength(); - if ((t[0] === 4 || t[0] === 6 || t[0] === 7) && t.length - 1 === 2 * i2) { - t[0] === 6 ? qr(t[t.length - 1] % 2 === 0) : t[0] === 7 && qr(t[t.length - 1] % 2 === 1); - var n3 = this.point(t.slice(1, 1 + i2), t.slice(1 + i2, 1 + 2 * i2)); - return n3; - } else if ((t[0] === 2 || t[0] === 3) && t.length - 1 === i2) - return this.pointFromX(t.slice(1, 1 + i2), t[0] === 3); - throw new Error("Unknown point format"); - }, Zt.prototype.encodeCompressed = function(t) { - return this.encode(t, true); - }, Zt.prototype._encode = function(t) { - var r = this.curve.p.byteLength(), i2 = this.getX().toArray("be", r); - return t ? [this.getY().isEven() ? 2 : 3].concat(i2) : [4].concat(i2, this.getY().toArray("be", r)); - }, Zt.prototype.encode = function(t, r) { - return Jt.encode(this._encode(r), t); - }, Zt.prototype.precompute = function(t) { - if (this.precomputed) - return this; - var r = { doubles: null, naf: null, beta: null }; - return r.naf = this._getNAFPoints(8), r.doubles = this._getDoubles(4, t), r.beta = this._getBeta(), this.precomputed = r, this; - }, Zt.prototype._hasDoubles = function(t) { - if (!this.precomputed) - return false; - var r = this.precomputed.doubles; - return r ? r.points.length >= Math.ceil((t.bitLength() + 1) / r.step) : false; - }, Zt.prototype._getDoubles = function(t, r) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - for (var i2 = [this], n3 = this, o2 = 0; o2 < r; o2 += t) { - for (var h5 = 0; h5 < t; h5++) - n3 = n3.dbl(); - i2.push(n3); - } - return { step: t, points: i2 }; - }, Zt.prototype._getNAFPoints = function(t) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - for (var r = [this], i2 = (1 << t) - 1, n3 = i2 === 1 ? null : this.dbl(), o2 = 1; o2 < i2; o2++) - r[o2] = r[o2 - 1].add(n3); - return { wnd: t, points: r }; - }, Zt.prototype._getBeta = function() { - return null; - }, Zt.prototype.dblp = function(t) { - for (var r = this, i2 = 0; i2 < t; i2++) - r = r.dbl(); - return r; - }; - var Fi = lr(function(e2) { - typeof Object.create == "function" ? e2.exports = function(r, i2) { - i2 && (r.super_ = i2, r.prototype = Object.create(i2.prototype, { constructor: { value: r, enumerable: false, writable: true, configurable: true } })); - } : e2.exports = function(r, i2) { - if (i2) { - r.super_ = i2; - var n3 = function() { - }; - n3.prototype = i2.prototype, r.prototype = new n3(), r.prototype.constructor = r; - } - }; - }); - var P0 = Jt.assert; - function $t(e2) { - Xe.call(this, "short", e2), this.a = new K2(e2.a, 16).toRed(this.red), this.b = new K2(e2.b, 16).toRed(this.red), this.tinv = this.two.redInvm(), this.zeroA = this.a.fromRed().cmpn(0) === 0, this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0, this.endo = this._getEndomorphism(e2), this._endoWnafT1 = new Array(4), this._endoWnafT2 = new Array(4); - } - Fi($t, Xe); - var T0 = $t; - $t.prototype._getEndomorphism = function(t) { - if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { - var r, i2; - if (t.beta) - r = new K2(t.beta, 16).toRed(this.red); - else { - var n3 = this._getEndoRoots(this.p); - r = n3[0].cmp(n3[1]) < 0 ? n3[0] : n3[1], r = r.toRed(this.red); - } - if (t.lambda) - i2 = new K2(t.lambda, 16); - else { - var o2 = this._getEndoRoots(this.n); - this.g.mul(o2[0]).x.cmp(this.g.x.redMul(r)) === 0 ? i2 = o2[0] : (i2 = o2[1], P0(this.g.mul(i2).x.cmp(this.g.x.redMul(r)) === 0)); - } - var h5; - return t.basis ? h5 = t.basis.map(function(p3) { - return { a: new K2(p3.a, 16), b: new K2(p3.b, 16) }; - }) : h5 = this._getEndoBasis(i2), { beta: r, lambda: i2, basis: h5 }; - } - }, $t.prototype._getEndoRoots = function(t) { - var r = t === this.p ? this.red : K2.mont(t), i2 = new K2(2).toRed(r).redInvm(), n3 = i2.redNeg(), o2 = new K2(3).toRed(r).redNeg().redSqrt().redMul(i2), h5 = n3.redAdd(o2).fromRed(), p3 = n3.redSub(o2).fromRed(); - return [h5, p3]; - }, $t.prototype._getEndoBasis = function(t) { - for (var r = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), i2 = t, n3 = this.n.clone(), o2 = new K2(1), h5 = new K2(0), p3 = new K2(0), b4 = new K2(1), g3, w4, y4, S4, I2, N10, R2, F = 0, U2, Q; i2.cmpn(0) !== 0; ) { - var Bt = n3.div(i2); - U2 = n3.sub(Bt.mul(i2)), Q = p3.sub(Bt.mul(o2)); - var J = b4.sub(Bt.mul(h5)); - if (!y4 && U2.cmp(r) < 0) - g3 = R2.neg(), w4 = o2, y4 = U2.neg(), S4 = Q; - else if (y4 && ++F === 2) - break; - R2 = U2, n3 = i2, i2 = U2, p3 = o2, o2 = Q, b4 = h5, h5 = J; - } - I2 = U2.neg(), N10 = Q; - var H = y4.sqr().add(S4.sqr()), L2 = I2.sqr().add(N10.sqr()); - return L2.cmp(H) >= 0 && (I2 = g3, N10 = w4), y4.negative && (y4 = y4.neg(), S4 = S4.neg()), I2.negative && (I2 = I2.neg(), N10 = N10.neg()), [{ a: y4, b: S4 }, { a: I2, b: N10 }]; - }, $t.prototype._endoSplit = function(t) { - var r = this.endo.basis, i2 = r[0], n3 = r[1], o2 = n3.b.mul(t).divRound(this.n), h5 = i2.b.neg().mul(t).divRound(this.n), p3 = o2.mul(i2.a), b4 = h5.mul(n3.a), g3 = o2.mul(i2.b), w4 = h5.mul(n3.b), y4 = t.sub(p3).sub(b4), S4 = g3.add(w4).neg(); - return { k1: y4, k2: S4 }; - }, $t.prototype.pointFromX = function(t, r) { - t = new K2(t, 16), t.red || (t = t.toRed(this.red)); - var i2 = t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b), n3 = i2.redSqrt(); - if (n3.redSqr().redSub(i2).cmp(this.zero) !== 0) - throw new Error("invalid point"); - var o2 = n3.fromRed().isOdd(); - return (r && !o2 || !r && o2) && (n3 = n3.redNeg()), this.point(t, n3); - }, $t.prototype.validate = function(t) { - if (t.inf) - return true; - var r = t.x, i2 = t.y, n3 = this.a.redMul(r), o2 = r.redSqr().redMul(r).redIAdd(n3).redIAdd(this.b); - return i2.redSqr().redISub(o2).cmpn(0) === 0; - }, $t.prototype._endoWnafMulAdd = function(t, r, i2) { - for (var n3 = this._endoWnafT1, o2 = this._endoWnafT2, h5 = 0; h5 < t.length; h5++) { - var p3 = this._endoSplit(r[h5]), b4 = t[h5], g3 = b4._getBeta(); - p3.k1.negative && (p3.k1.ineg(), b4 = b4.neg(true)), p3.k2.negative && (p3.k2.ineg(), g3 = g3.neg(true)), n3[h5 * 2] = b4, n3[h5 * 2 + 1] = g3, o2[h5 * 2] = p3.k1, o2[h5 * 2 + 1] = p3.k2; - } - for (var w4 = this._wnafMulAdd(1, n3, o2, h5 * 2, i2), y4 = 0; y4 < h5 * 2; y4++) - n3[y4] = null, o2[y4] = null; - return w4; - }; - function Dt(e2, t, r, i2) { - Xe.BasePoint.call(this, e2, "affine"), t === null && r === null ? (this.x = null, this.y = null, this.inf = true) : (this.x = new K2(t, 16), this.y = new K2(r, 16), i2 && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.inf = false); - } - Fi(Dt, Xe.BasePoint), $t.prototype.point = function(t, r, i2) { - return new Dt(this, t, r, i2); - }, $t.prototype.pointFromJSON = function(t, r) { - return Dt.fromJSON(this, t, r); - }, Dt.prototype._getBeta = function() { - if (this.curve.endo) { - var t = this.precomputed; - if (t && t.beta) - return t.beta; - var r = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (t) { - var i2 = this.curve, n3 = function(o2) { - return i2.point(o2.x.redMul(i2.endo.beta), o2.y); - }; - t.beta = r, r.precomputed = { beta: null, naf: t.naf && { wnd: t.naf.wnd, points: t.naf.points.map(n3) }, doubles: t.doubles && { step: t.doubles.step, points: t.doubles.points.map(n3) } }; - } - return r; - } - }, Dt.prototype.toJSON = function() { - return this.precomputed ? [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }] : [this.x, this.y]; - }, Dt.fromJSON = function(t, r, i2) { - typeof r == "string" && (r = JSON.parse(r)); - var n3 = t.point(r[0], r[1], i2); - if (!r[2]) - return n3; - function o2(p3) { - return t.point(p3[0], p3[1], i2); - } - var h5 = r[2]; - return n3.precomputed = { beta: null, doubles: h5.doubles && { step: h5.doubles.step, points: [n3].concat(h5.doubles.points.map(o2)) }, naf: h5.naf && { wnd: h5.naf.wnd, points: [n3].concat(h5.naf.points.map(o2)) } }, n3; - }, Dt.prototype.inspect = function() { - return this.isInfinity() ? "" : ""; - }, Dt.prototype.isInfinity = function() { - return this.inf; - }, Dt.prototype.add = function(t) { - if (this.inf) - return t; - if (t.inf) - return this; - if (this.eq(t)) - return this.dbl(); - if (this.neg().eq(t)) - return this.curve.point(null, null); - if (this.x.cmp(t.x) === 0) - return this.curve.point(null, null); - var r = this.y.redSub(t.y); - r.cmpn(0) !== 0 && (r = r.redMul(this.x.redSub(t.x).redInvm())); - var i2 = r.redSqr().redISub(this.x).redISub(t.x), n3 = r.redMul(this.x.redSub(i2)).redISub(this.y); - return this.curve.point(i2, n3); - }, Dt.prototype.dbl = function() { - if (this.inf) - return this; - var t = this.y.redAdd(this.y); - if (t.cmpn(0) === 0) - return this.curve.point(null, null); - var r = this.curve.a, i2 = this.x.redSqr(), n3 = t.redInvm(), o2 = i2.redAdd(i2).redIAdd(i2).redIAdd(r).redMul(n3), h5 = o2.redSqr().redISub(this.x.redAdd(this.x)), p3 = o2.redMul(this.x.redSub(h5)).redISub(this.y); - return this.curve.point(h5, p3); - }, Dt.prototype.getX = function() { - return this.x.fromRed(); - }, Dt.prototype.getY = function() { - return this.y.fromRed(); - }, Dt.prototype.mul = function(t) { - return t = new K2(t, 16), this.isInfinity() ? this : this._hasDoubles(t) ? this.curve._fixedNafMul(this, t) : this.curve.endo ? this.curve._endoWnafMulAdd([this], [t]) : this.curve._wnafMul(this, t); - }, Dt.prototype.mulAdd = function(t, r, i2) { - var n3 = [this, r], o2 = [t, i2]; - return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2) : this.curve._wnafMulAdd(1, n3, o2, 2); - }, Dt.prototype.jmulAdd = function(t, r, i2) { - var n3 = [this, r], o2 = [t, i2]; - return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2, true) : this.curve._wnafMulAdd(1, n3, o2, 2, true); - }, Dt.prototype.eq = function(t) { - return this === t || this.inf === t.inf && (this.inf || this.x.cmp(t.x) === 0 && this.y.cmp(t.y) === 0); - }, Dt.prototype.neg = function(t) { - if (this.inf) - return this; - var r = this.curve.point(this.x, this.y.redNeg()); - if (t && this.precomputed) { - var i2 = this.precomputed, n3 = function(o2) { - return o2.neg(); - }; - r.precomputed = { naf: i2.naf && { wnd: i2.naf.wnd, points: i2.naf.points.map(n3) }, doubles: i2.doubles && { step: i2.doubles.step, points: i2.doubles.points.map(n3) } }; - } - return r; - }, Dt.prototype.toJ = function() { - if (this.inf) - return this.curve.jpoint(null, null, null); - var t = this.curve.jpoint(this.x, this.y, this.curve.one); - return t; - }; - function Ut(e2, t, r, i2) { - Xe.BasePoint.call(this, e2, "jacobian"), t === null && r === null && i2 === null ? (this.x = this.curve.one, this.y = this.curve.one, this.z = new K2(0)) : (this.x = new K2(t, 16), this.y = new K2(r, 16), this.z = new K2(i2, 16)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red)), this.zOne = this.z === this.curve.one; - } - Fi(Ut, Xe.BasePoint), $t.prototype.jpoint = function(t, r, i2) { - return new Ut(this, t, r, i2); - }, Ut.prototype.toP = function() { - if (this.isInfinity()) - return this.curve.point(null, null); - var t = this.z.redInvm(), r = t.redSqr(), i2 = this.x.redMul(r), n3 = this.y.redMul(r).redMul(t); - return this.curve.point(i2, n3); - }, Ut.prototype.neg = function() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }, Ut.prototype.add = function(t) { - if (this.isInfinity()) - return t; - if (t.isInfinity()) - return this; - var r = t.z.redSqr(), i2 = this.z.redSqr(), n3 = this.x.redMul(r), o2 = t.x.redMul(i2), h5 = this.y.redMul(r.redMul(t.z)), p3 = t.y.redMul(i2.redMul(this.z)), b4 = n3.redSub(o2), g3 = h5.redSub(p3); - if (b4.cmpn(0) === 0) - return g3.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); - var w4 = b4.redSqr(), y4 = w4.redMul(b4), S4 = n3.redMul(w4), I2 = g3.redSqr().redIAdd(y4).redISub(S4).redISub(S4), N10 = g3.redMul(S4.redISub(I2)).redISub(h5.redMul(y4)), R2 = this.z.redMul(t.z).redMul(b4); - return this.curve.jpoint(I2, N10, R2); - }, Ut.prototype.mixedAdd = function(t) { - if (this.isInfinity()) - return t.toJ(); - if (t.isInfinity()) - return this; - var r = this.z.redSqr(), i2 = this.x, n3 = t.x.redMul(r), o2 = this.y, h5 = t.y.redMul(r).redMul(this.z), p3 = i2.redSub(n3), b4 = o2.redSub(h5); - if (p3.cmpn(0) === 0) - return b4.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); - var g3 = p3.redSqr(), w4 = g3.redMul(p3), y4 = i2.redMul(g3), S4 = b4.redSqr().redIAdd(w4).redISub(y4).redISub(y4), I2 = b4.redMul(y4.redISub(S4)).redISub(o2.redMul(w4)), N10 = this.z.redMul(p3); - return this.curve.jpoint(S4, I2, N10); - }, Ut.prototype.dblp = function(t) { - if (t === 0) - return this; - if (this.isInfinity()) - return this; - if (!t) - return this.dbl(); - var r; - if (this.curve.zeroA || this.curve.threeA) { - var i2 = this; - for (r = 0; r < t; r++) - i2 = i2.dbl(); - return i2; - } - var n3 = this.curve.a, o2 = this.curve.tinv, h5 = this.x, p3 = this.y, b4 = this.z, g3 = b4.redSqr().redSqr(), w4 = p3.redAdd(p3); - for (r = 0; r < t; r++) { - var y4 = h5.redSqr(), S4 = w4.redSqr(), I2 = S4.redSqr(), N10 = y4.redAdd(y4).redIAdd(y4).redIAdd(n3.redMul(g3)), R2 = h5.redMul(S4), F = N10.redSqr().redISub(R2.redAdd(R2)), U2 = R2.redISub(F), Q = N10.redMul(U2); - Q = Q.redIAdd(Q).redISub(I2); - var Bt = w4.redMul(b4); - r + 1 < t && (g3 = g3.redMul(I2)), h5 = F, b4 = Bt, w4 = Q; - } - return this.curve.jpoint(h5, w4.redMul(o2), b4); - }, Ut.prototype.dbl = function() { - return this.isInfinity() ? this : this.curve.zeroA ? this._zeroDbl() : this.curve.threeA ? this._threeDbl() : this._dbl(); - }, Ut.prototype._zeroDbl = function() { - var t, r, i2; - if (this.zOne) { - var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); - p3 = p3.redIAdd(p3); - var b4 = n3.redAdd(n3).redIAdd(n3), g3 = b4.redSqr().redISub(p3).redISub(p3), w4 = h5.redIAdd(h5); - w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), t = g3, r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); - } else { - var y4 = this.x.redSqr(), S4 = this.y.redSqr(), I2 = S4.redSqr(), N10 = this.x.redAdd(S4).redSqr().redISub(y4).redISub(I2); - N10 = N10.redIAdd(N10); - var R2 = y4.redAdd(y4).redIAdd(y4), F = R2.redSqr(), U2 = I2.redIAdd(I2); - U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), t = F.redISub(N10).redISub(N10), r = R2.redMul(N10.redISub(t)).redISub(U2), i2 = this.y.redMul(this.z), i2 = i2.redIAdd(i2); - } - return this.curve.jpoint(t, r, i2); - }, Ut.prototype._threeDbl = function() { - var t, r, i2; - if (this.zOne) { - var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); - p3 = p3.redIAdd(p3); - var b4 = n3.redAdd(n3).redIAdd(n3).redIAdd(this.curve.a), g3 = b4.redSqr().redISub(p3).redISub(p3); - t = g3; - var w4 = h5.redIAdd(h5); - w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); - } else { - var y4 = this.z.redSqr(), S4 = this.y.redSqr(), I2 = this.x.redMul(S4), N10 = this.x.redSub(y4).redMul(this.x.redAdd(y4)); - N10 = N10.redAdd(N10).redIAdd(N10); - var R2 = I2.redIAdd(I2); - R2 = R2.redIAdd(R2); - var F = R2.redAdd(R2); - t = N10.redSqr().redISub(F), i2 = this.y.redAdd(this.z).redSqr().redISub(S4).redISub(y4); - var U2 = S4.redSqr(); - U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), r = N10.redMul(R2.redISub(t)).redISub(U2); - } - return this.curve.jpoint(t, r, i2); - }, Ut.prototype._dbl = function() { - var t = this.curve.a, r = this.x, i2 = this.y, n3 = this.z, o2 = n3.redSqr().redSqr(), h5 = r.redSqr(), p3 = i2.redSqr(), b4 = h5.redAdd(h5).redIAdd(h5).redIAdd(t.redMul(o2)), g3 = r.redAdd(r); - g3 = g3.redIAdd(g3); - var w4 = g3.redMul(p3), y4 = b4.redSqr().redISub(w4.redAdd(w4)), S4 = w4.redISub(y4), I2 = p3.redSqr(); - I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); - var N10 = b4.redMul(S4).redISub(I2), R2 = i2.redAdd(i2).redMul(n3); - return this.curve.jpoint(y4, N10, R2); - }, Ut.prototype.trpl = function() { - if (!this.curve.zeroA) - return this.dbl().add(this); - var t = this.x.redSqr(), r = this.y.redSqr(), i2 = this.z.redSqr(), n3 = r.redSqr(), o2 = t.redAdd(t).redIAdd(t), h5 = o2.redSqr(), p3 = this.x.redAdd(r).redSqr().redISub(t).redISub(n3); - p3 = p3.redIAdd(p3), p3 = p3.redAdd(p3).redIAdd(p3), p3 = p3.redISub(h5); - var b4 = p3.redSqr(), g3 = n3.redIAdd(n3); - g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3); - var w4 = o2.redIAdd(p3).redSqr().redISub(h5).redISub(b4).redISub(g3), y4 = r.redMul(w4); - y4 = y4.redIAdd(y4), y4 = y4.redIAdd(y4); - var S4 = this.x.redMul(b4).redISub(y4); - S4 = S4.redIAdd(S4), S4 = S4.redIAdd(S4); - var I2 = this.y.redMul(w4.redMul(g3.redISub(w4)).redISub(p3.redMul(b4))); - I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); - var N10 = this.z.redAdd(p3).redSqr().redISub(i2).redISub(b4); - return this.curve.jpoint(S4, I2, N10); - }, Ut.prototype.mul = function(t, r) { - return t = new K2(t, r), this.curve._wnafMul(this, t); - }, Ut.prototype.eq = function(t) { - if (t.type === "affine") - return this.eq(t.toJ()); - if (this === t) - return true; - var r = this.z.redSqr(), i2 = t.z.redSqr(); - if (this.x.redMul(i2).redISub(t.x.redMul(r)).cmpn(0) !== 0) - return false; - var n3 = r.redMul(this.z), o2 = i2.redMul(t.z); - return this.y.redMul(o2).redISub(t.y.redMul(n3)).cmpn(0) === 0; - }, Ut.prototype.eqXToP = function(t) { - var r = this.z.redSqr(), i2 = t.toRed(this.curve.red).redMul(r); - if (this.x.cmp(i2) === 0) - return true; - for (var n3 = t.clone(), o2 = this.curve.redN.redMul(r); ; ) { - if (n3.iadd(this.curve.n), n3.cmp(this.curve.p) >= 0) - return false; - if (i2.redIAdd(o2), this.x.cmp(i2) === 0) - return true; - } - }, Ut.prototype.inspect = function() { - return this.isInfinity() ? "" : ""; - }, Ut.prototype.isInfinity = function() { - return this.z.cmpn(0) === 0; - }; - var Kr = lr(function(e2, t) { - var r = t; - r.base = Xe, r.short = T0, r.mont = null, r.edwards = null; - }); - var Hr = lr(function(e2, t) { - var r = t, i2 = Jt.assert; - function n3(p3) { - p3.type === "short" ? this.curve = new Kr.short(p3) : p3.type === "edwards" ? this.curve = new Kr.edwards(p3) : this.curve = new Kr.mont(p3), this.g = this.curve.g, this.n = this.curve.n, this.hash = p3.hash, i2(this.g.validate(), "Invalid curve"), i2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); - } - r.PresetCurve = n3; - function o2(p3, b4) { - Object.defineProperty(r, p3, { configurable: true, enumerable: true, get: function() { - var g3 = new n3(b4); - return Object.defineProperty(r, p3, { configurable: true, enumerable: true, value: g3 }), g3; - } }); - } - o2("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: oe.sha256, gRed: false, g: ["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"] }), o2("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: oe.sha256, gRed: false, g: ["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"] }), o2("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: oe.sha256, gRed: false, g: ["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"] }), o2("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: oe.sha384, gRed: false, g: ["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"] }), o2("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: oe.sha512, gRed: false, g: ["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"] }), o2("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["9"] }), o2("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", "6666666666666666666666666666666666666666666666666666666666666658"] }); - var h5; - try { - h5 = null.crash(); - } catch { - h5 = void 0; - } - o2("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: oe.sha256, beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [{ a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" }], gRed: false, g: ["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", h5] }); - }); - function Re(e2) { - if (!(this instanceof Re)) - return new Re(e2); - this.hash = e2.hash, this.predResist = !!e2.predResist, this.outLen = this.hash.outSize, this.minEntropy = e2.minEntropy || this.hash.hmacStrength, this._reseed = null, this.reseedInterval = null, this.K = null, this.V = null; - var t = ne.toArray(e2.entropy, e2.entropyEnc || "hex"), r = ne.toArray(e2.nonce, e2.nonceEnc || "hex"), i2 = ne.toArray(e2.pers, e2.persEnc || "hex"); - Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._init(t, r, i2); - } - var If = Re; - Re.prototype._init = function(t, r, i2) { - var n3 = t.concat(r).concat(i2); - this.K = new Array(this.outLen / 8), this.V = new Array(this.outLen / 8); - for (var o2 = 0; o2 < this.V.length; o2++) - this.K[o2] = 0, this.V[o2] = 1; - this._update(n3), this._reseed = 1, this.reseedInterval = 281474976710656; - }, Re.prototype._hmac = function() { - return new oe.hmac(this.hash, this.K); - }, Re.prototype._update = function(t) { - var r = this._hmac().update(this.V).update([0]); - t && (r = r.update(t)), this.K = r.digest(), this.V = this._hmac().update(this.V).digest(), t && (this.K = this._hmac().update(this.V).update([1]).update(t).digest(), this.V = this._hmac().update(this.V).digest()); - }, Re.prototype.reseed = function(t, r, i2, n3) { - typeof r != "string" && (n3 = i2, i2 = r, r = null), t = ne.toArray(t, r), i2 = ne.toArray(i2, n3), Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._update(t.concat(i2 || [])), this._reseed = 1; - }, Re.prototype.generate = function(t, r, i2, n3) { - if (this._reseed > this.reseedInterval) - throw new Error("Reseed is required"); - typeof r != "string" && (n3 = i2, i2 = r, r = null), i2 && (i2 = ne.toArray(i2, n3 || "hex"), this._update(i2)); - for (var o2 = []; o2.length < t; ) - this.V = this._hmac().update(this.V).digest(), o2 = o2.concat(this.V); - var h5 = o2.slice(0, t); - return this._update(i2), this._reseed++, ne.encode(h5, r); - }; - var Di = Jt.assert; - function qt(e2, t) { - this.ec = e2, this.priv = null, this.pub = null, t.priv && this._importPrivate(t.priv, t.privEnc), t.pub && this._importPublic(t.pub, t.pubEnc); - } - var Ui = qt; - qt.fromPublic = function(t, r, i2) { - return r instanceof qt ? r : new qt(t, { pub: r, pubEnc: i2 }); - }, qt.fromPrivate = function(t, r, i2) { - return r instanceof qt ? r : new qt(t, { priv: r, privEnc: i2 }); - }, qt.prototype.validate = function() { - var t = this.getPublic(); - return t.isInfinity() ? { result: false, reason: "Invalid public key" } : t.validate() ? t.mul(this.ec.curve.n).isInfinity() ? { result: true, reason: null } : { result: false, reason: "Public key * N != O" } : { result: false, reason: "Public key is not a point" }; - }, qt.prototype.getPublic = function(t, r) { - return typeof t == "string" && (r = t, t = null), this.pub || (this.pub = this.ec.g.mul(this.priv)), r ? this.pub.encode(r, t) : this.pub; - }, qt.prototype.getPrivate = function(t) { - return t === "hex" ? this.priv.toString(16, 2) : this.priv; - }, qt.prototype._importPrivate = function(t, r) { - this.priv = new K2(t, r || 16), this.priv = this.priv.umod(this.ec.curve.n); - }, qt.prototype._importPublic = function(t, r) { - if (t.x || t.y) { - this.ec.curve.type === "mont" ? Di(t.x, "Need x coordinate") : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && Di(t.x && t.y, "Need both x and y coordinate"), this.pub = this.ec.curve.point(t.x, t.y); - return; - } - this.pub = this.ec.curve.decodePoint(t, r); - }, qt.prototype.derive = function(t) { - return t.validate() || Di(t.validate(), "public point not validated"), t.mul(this.priv).getX(); - }, qt.prototype.sign = function(t, r, i2) { - return this.ec.sign(t, this, r, i2); - }, qt.prototype.verify = function(t, r) { - return this.ec.verify(t, r, this); - }, qt.prototype.inspect = function() { - return ""; - }; - var F0 = Jt.assert; - function Lr(e2, t) { - if (e2 instanceof Lr) - return e2; - this._importDER(e2, t) || (F0(e2.r && e2.s, "Signature without r or s"), this.r = new K2(e2.r, 16), this.s = new K2(e2.s, 16), e2.recoveryParam === void 0 ? this.recoveryParam = null : this.recoveryParam = e2.recoveryParam); - } - var zr = Lr; - function D0() { - this.place = 0; - } - function ki(e2, t) { - var r = e2[t.place++]; - if (!(r & 128)) - return r; - var i2 = r & 15; - if (i2 === 0 || i2 > 4) - return false; - for (var n3 = 0, o2 = 0, h5 = t.place; o2 < i2; o2++, h5++) - n3 <<= 8, n3 |= e2[h5], n3 >>>= 0; - return n3 <= 127 ? false : (t.place = h5, n3); - } - function _f(e2) { - for (var t = 0, r = e2.length - 1; !e2[t] && !(e2[t + 1] & 128) && t < r; ) - t++; - return t === 0 ? e2 : e2.slice(t); - } - Lr.prototype._importDER = function(t, r) { - t = Jt.toArray(t, r); - var i2 = new D0(); - if (t[i2.place++] !== 48) - return false; - var n3 = ki(t, i2); - if (n3 === false || n3 + i2.place !== t.length || t[i2.place++] !== 2) - return false; - var o2 = ki(t, i2); - if (o2 === false) - return false; - var h5 = t.slice(i2.place, o2 + i2.place); - if (i2.place += o2, t[i2.place++] !== 2) - return false; - var p3 = ki(t, i2); - if (p3 === false || t.length !== p3 + i2.place) - return false; - var b4 = t.slice(i2.place, p3 + i2.place); - if (h5[0] === 0) - if (h5[1] & 128) - h5 = h5.slice(1); - else - return false; - if (b4[0] === 0) - if (b4[1] & 128) - b4 = b4.slice(1); - else - return false; - return this.r = new K2(h5), this.s = new K2(b4), this.recoveryParam = null, true; - }; - function qi(e2, t) { - if (t < 128) { - e2.push(t); - return; - } - var r = 1 + (Math.log(t) / Math.LN2 >>> 3); - for (e2.push(r | 128); --r; ) - e2.push(t >>> (r << 3) & 255); - e2.push(t); - } - Lr.prototype.toDER = function(t) { - var r = this.r.toArray(), i2 = this.s.toArray(); - for (r[0] & 128 && (r = [0].concat(r)), i2[0] & 128 && (i2 = [0].concat(i2)), r = _f(r), i2 = _f(i2); !i2[0] && !(i2[1] & 128); ) - i2 = i2.slice(1); - var n3 = [2]; - qi(n3, r.length), n3 = n3.concat(r), n3.push(2), qi(n3, i2.length); - var o2 = n3.concat(i2), h5 = [48]; - return qi(h5, o2.length), h5 = h5.concat(o2), Jt.encode(h5, t); - }; - var U0 = function() { - throw new Error("unsupported"); - }; - var Bf = Jt.assert; - function te(e2) { - if (!(this instanceof te)) - return new te(e2); - typeof e2 == "string" && (Bf(Object.prototype.hasOwnProperty.call(Hr, e2), "Unknown curve " + e2), e2 = Hr[e2]), e2 instanceof Hr.PresetCurve && (e2 = { curve: e2 }), this.curve = e2.curve.curve, this.n = this.curve.n, this.nh = this.n.ushrn(1), this.g = this.curve.g, this.g = e2.curve.g, this.g.precompute(e2.curve.n.bitLength() + 1), this.hash = e2.hash || e2.curve.hash; - } - var k0 = te; - te.prototype.keyPair = function(t) { - return new Ui(this, t); - }, te.prototype.keyFromPrivate = function(t, r) { - return Ui.fromPrivate(this, t, r); - }, te.prototype.keyFromPublic = function(t, r) { - return Ui.fromPublic(this, t, r); - }, te.prototype.genKeyPair = function(t) { - t || (t = {}); - for (var r = new If({ hash: this.hash, pers: t.pers, persEnc: t.persEnc || "utf8", entropy: t.entropy || U0(this.hash.hmacStrength), entropyEnc: t.entropy && t.entropyEnc || "utf8", nonce: this.n.toArray() }), i2 = this.n.byteLength(), n3 = this.n.sub(new K2(2)); ; ) { - var o2 = new K2(r.generate(i2)); - if (!(o2.cmp(n3) > 0)) - return o2.iaddn(1), this.keyFromPrivate(o2); - } - }, te.prototype._truncateToN = function(t, r) { - var i2 = t.byteLength() * 8 - this.n.bitLength(); - return i2 > 0 && (t = t.ushrn(i2)), !r && t.cmp(this.n) >= 0 ? t.sub(this.n) : t; - }, te.prototype.sign = function(t, r, i2, n3) { - typeof i2 == "object" && (n3 = i2, i2 = null), n3 || (n3 = {}), r = this.keyFromPrivate(r, i2), t = this._truncateToN(new K2(t, 16)); - for (var o2 = this.n.byteLength(), h5 = r.getPrivate().toArray("be", o2), p3 = t.toArray("be", o2), b4 = new If({ hash: this.hash, entropy: h5, nonce: p3, pers: n3.pers, persEnc: n3.persEnc || "utf8" }), g3 = this.n.sub(new K2(1)), w4 = 0; ; w4++) { - var y4 = n3.k ? n3.k(w4) : new K2(b4.generate(this.n.byteLength())); - if (y4 = this._truncateToN(y4, true), !(y4.cmpn(1) <= 0 || y4.cmp(g3) >= 0)) { - var S4 = this.g.mul(y4); - if (!S4.isInfinity()) { - var I2 = S4.getX(), N10 = I2.umod(this.n); - if (N10.cmpn(0) !== 0) { - var R2 = y4.invm(this.n).mul(N10.mul(r.getPrivate()).iadd(t)); - if (R2 = R2.umod(this.n), R2.cmpn(0) !== 0) { - var F = (S4.getY().isOdd() ? 1 : 0) | (I2.cmp(N10) !== 0 ? 2 : 0); - return n3.canonical && R2.cmp(this.nh) > 0 && (R2 = this.n.sub(R2), F ^= 1), new zr({ r: N10, s: R2, recoveryParam: F }); - } - } - } - } - } - }, te.prototype.verify = function(t, r, i2, n3) { - t = this._truncateToN(new K2(t, 16)), i2 = this.keyFromPublic(i2, n3), r = new zr(r, "hex"); - var o2 = r.r, h5 = r.s; - if (o2.cmpn(1) < 0 || o2.cmp(this.n) >= 0 || h5.cmpn(1) < 0 || h5.cmp(this.n) >= 0) - return false; - var p3 = h5.invm(this.n), b4 = p3.mul(t).umod(this.n), g3 = p3.mul(o2).umod(this.n), w4; - return this.curve._maxwellTrick ? (w4 = this.g.jmulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.eqXToP(o2)) : (w4 = this.g.mulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.getX().umod(this.n).cmp(o2) === 0); - }, te.prototype.recoverPubKey = function(e2, t, r, i2) { - Bf((3 & r) === r, "The recovery param is more than two bits"), t = new zr(t, i2); - var n3 = this.n, o2 = new K2(e2), h5 = t.r, p3 = t.s, b4 = r & 1, g3 = r >> 1; - if (h5.cmp(this.curve.p.umod(this.curve.n)) >= 0 && g3) - throw new Error("Unable to find sencond key candinate"); - g3 ? h5 = this.curve.pointFromX(h5.add(this.curve.n), b4) : h5 = this.curve.pointFromX(h5, b4); - var w4 = t.r.invm(n3), y4 = n3.sub(o2).mul(w4).umod(n3), S4 = p3.mul(w4).umod(n3); - return this.g.mulAdd(y4, h5, S4); - }, te.prototype.getKeyRecoveryParam = function(e2, t, r, i2) { - if (t = new zr(t, i2), t.recoveryParam !== null) - return t.recoveryParam; - for (var n3 = 0; n3 < 4; n3++) { - var o2; - try { - o2 = this.recoverPubKey(e2, t, n3); - } catch { - continue; - } - if (o2.eq(r)) - return n3; - } - throw new Error("Unable to find valid recovery factor"); - }; - var q0 = lr(function(e2, t) { - var r = t; - r.version = "6.5.4", r.utils = Jt, r.rand = function() { - throw new Error("unsupported"); - }, r.curve = Kr, r.curves = Hr, r.ec = k0, r.eddsa = null; - }); - var K0 = q0.ec; - var H0 = "signing-key/5.7.0"; - var Ki = new z3(H0); - var Hi = null; - function pe() { - return Hi || (Hi = new K0("secp256k1")), Hi; - } - var L0 = class { - constructor(t) { - yr(this, "curve", "secp256k1"), yr(this, "privateKey", Ht(t)), xs(this.privateKey) !== 32 && Ki.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); - const r = pe().keyFromPrivate(Pt(this.privateKey)); - yr(this, "publicKey", "0x" + r.getPublic(false, "hex")), yr(this, "compressedPublicKey", "0x" + r.getPublic(true, "hex")), yr(this, "_isSigningKey", true); - } - _addPoint(t) { - const r = pe().keyFromPublic(Pt(this.publicKey)), i2 = pe().keyFromPublic(Pt(t)); - return "0x" + r.pub.add(i2.pub).encodeCompressed("hex"); - } - signDigest(t) { - const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = Pt(t); - i2.length !== 32 && Ki.throwArgumentError("bad digest length", "digest", t); - const n3 = r.sign(i2, { canonical: true }); - return kn({ recoveryParam: n3.recoveryParam, r: fe("0x" + n3.r.toString(16), 32), s: fe("0x" + n3.s.toString(16), 32) }); - } - computeSharedSecret(t) { - const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = pe().keyFromPublic(Pt(Rf(t))); - return fe("0x" + r.derive(i2.getPublic()).toString(16), 32); - } - static isSigningKey(t) { - return !!(t && t._isSigningKey); - } - }; - function z0(e2, t) { - const r = kn(t), i2 = { r: Pt(r.r), s: Pt(r.s) }; - return "0x" + pe().recoverPubKey(Pt(e2), i2, r.recoveryParam).encode("hex", false); - } - function Rf(e2, t) { - const r = Pt(e2); - if (r.length === 32) { - const i2 = new L0(r); - return t ? "0x" + pe().keyFromPrivate(r).getPublic(true, "hex") : i2.publicKey; - } else { - if (r.length === 33) - return t ? Ht(r) : "0x" + pe().keyFromPublic(r).getPublic(false, "hex"); - if (r.length === 65) - return t ? "0x" + pe().keyFromPublic(r).getPublic(true, "hex") : Ht(r); - } - return Ki.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); - } - var j0 = "transactions/5.7.0"; - new z3(j0); - var Cf; - (function(e2) { - e2[e2.legacy = 0] = "legacy", e2[e2.eip2930 = 1] = "eip2930", e2[e2.eip1559 = 2] = "eip1559"; - })(Cf || (Cf = {})); - function V0(e2) { - const t = Rf(e2); - return ta(Un(wi(Un(t, 1)), 12)); - } - function Q0(e2, t) { - return V0(z0(Pt(e2), t)); - } - var J0 = "https://rpc.walletconnect.com/v1"; - async function Of(e2, t, r, i2, n3, o2) { - switch (r.t) { - case "eip191": - return Pf(e2, t, r.s); - case "eip1271": - return await Tf(e2, t, r.s, i2, n3, o2); - default: - throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`); - } - } - function Pf(e2, t, r) { - return Q0(tf(t), r).toLowerCase() === e2.toLowerCase(); - } - async function Tf(e2, t, r, i2, n3, o2) { - try { - const h5 = "0x1626ba7e", p3 = "0000000000000000000000000000000000000000000000000000000000000040", b4 = "0000000000000000000000000000000000000000000000000000000000000041", g3 = r.substring(2), w4 = tf(t).substring(2), y4 = h5 + w4 + p3 + b4 + g3, S4 = await fetch(`${o2 || J0}/?chainId=${i2}&projectId=${n3}`, { method: "POST", body: JSON.stringify({ id: Y0(), jsonrpc: "2.0", method: "eth_call", params: [{ to: e2, data: y4 }, "latest"] }) }), { result: I2 } = await S4.json(); - return I2 ? I2.slice(0, h5.length).toLowerCase() === h5.toLowerCase() : false; - } catch (h5) { - return console.error("isValidEip1271Signature: ", h5), false; - } - } - function Y0() { - return Date.now() + Math.floor(Math.random() * 1e3); - } - var G0 = Object.defineProperty; - var W0 = Object.defineProperties; - var X0 = Object.getOwnPropertyDescriptors; - var Ff = Object.getOwnPropertySymbols; - var Z0 = Object.prototype.hasOwnProperty; - var $0 = Object.prototype.propertyIsEnumerable; - var Df = (e2, t, r) => t in e2 ? G0(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var Li = (e2, t) => { - for (var r in t || (t = {})) - Z0.call(t, r) && Df(e2, r, t[r]); - if (Ff) - for (var r of Ff(t)) - $0.call(t, r) && Df(e2, r, t[r]); - return e2; - }; - var Uf = (e2, t) => W0(e2, X0(t)); - var tu = "did:pkh:"; - var jr = (e2) => e2?.split(":"); - var zi = (e2) => { - const t = e2 && jr(e2); - if (t) - return e2.includes(tu) ? t[3] : t[1]; - }; - var eu = (e2) => { - const t = e2 && jr(e2); - if (t) - return t[2] + ":" + t[3]; - }; - var ji = (e2) => { - const t = e2 && jr(e2); - if (t) - return t.pop(); - }; - async function ru(e2) { - const { cacao: t, projectId: r } = e2, { s: i2, p: n3 } = t, o2 = kf(n3, n3.iss), h5 = ji(n3.iss); - return await Of(h5, o2, i2, zi(n3.iss), r); - } - var kf = (e2, t) => { - const r = `${e2.domain} wants you to sign in with your Ethereum account:`, i2 = ji(t); - if (!e2.aud && !e2.uri) - throw new Error("Either `aud` or `uri` is required to construct the message"); - let n3 = e2.statement || void 0; - const o2 = `URI: ${e2.aud || e2.uri}`, h5 = `Version: ${e2.version}`, p3 = `Chain ID: ${zi(t)}`, b4 = `Nonce: ${e2.nonce}`, g3 = `Issued At: ${e2.iat}`, w4 = e2.resources ? `Resources:${e2.resources.map((S4) => ` -- ${S4}`).join("")}` : void 0, y4 = Qr(e2.resources); - if (y4) { - const S4 = Ce(y4); - n3 = Ji(n3, S4); - } - return [r, i2, "", n3, "", o2, h5, p3, b4, g3, w4].filter((S4) => S4 != null).join(` -`); - }; - function iu(e2, t, r) { - return r.includes("did:pkh:") || (r = `did:pkh:${r}`), { h: { t: "caip122" }, p: { iss: r, domain: e2.domain, aud: e2.aud, version: e2.version, nonce: e2.nonce, iat: e2.iat, statement: e2.statement, requestId: e2.requestId, resources: e2.resources, nbf: e2.nbf, exp: e2.exp }, s: t }; - } - function nu(e2) { - var t; - const { authPayload: r, chains: i2, methods: n3 } = e2, o2 = r.statement || ""; - if (!(i2 != null && i2.length)) - return r; - const h5 = r.chains, p3 = mi(h5, i2); - if (!(p3 != null && p3.length)) - throw new Error("No supported chains"); - const b4 = qf(r.resources); - if (!b4) - return r; - ve(b4); - const g3 = Kf(b4, "eip155"); - let w4 = r?.resources || []; - if (g3 != null && g3.length) { - const y4 = Hf(g3), S4 = mi(y4, n3); - if (!(S4 != null && S4.length)) - throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(y4)}, supported: ${JSON.stringify(n3)}`); - const I2 = Vi("request", S4, { chains: p3 }), N10 = Vf(b4, "eip155", I2); - w4 = ((t = r?.resources) == null ? void 0 : t.slice(0, -1)) || [], w4.push(Vr(N10)); - } - return Uf(Li({}, r), { statement: Jf(o2, Qr(w4)), chains: p3, resources: r != null && r.resources || w4.length > 0 ? w4 : void 0 }); - } - function qf(e2) { - const t = Qr(e2); - if (t && Qi(t)) - return Ce(t); - } - function fu(e2, t) { - var r; - return (r = e2?.att) == null ? void 0 : r.hasOwnProperty(t); - } - function Kf(e2, t) { - var r, i2; - return (r = e2?.att) != null && r[t] ? Object.keys((i2 = e2?.att) == null ? void 0 : i2[t]) : []; - } - function ou(e2) { - return e2?.map((t) => Object.keys(t)) || []; - } - function Hf(e2) { - return e2?.map((t) => { - var r; - return (r = t.split("/")) == null ? void 0 : r[1]; - }) || []; - } - function Lf(e2) { - return import_buffer.Buffer.from(JSON.stringify(e2)).toString("base64"); - } - function zf(e2) { - return JSON.parse(import_buffer.Buffer.from(e2, "base64").toString("utf-8")); - } - function ve(e2) { - if (!e2) - throw new Error("No recap provided, value is undefined"); - if (!e2.att) - throw new Error("No `att` property found"); - const t = Object.keys(e2.att); - if (!(t != null && t.length)) - throw new Error("No resources found in `att` property"); - t.forEach((r) => { - const i2 = e2.att[r]; - if (Array.isArray(i2)) - throw new Error(`Resource must be an object: ${r}`); - if (typeof i2 != "object") - throw new Error(`Resource must be an object: ${r}`); - if (!Object.keys(i2).length) - throw new Error(`Resource object is empty: ${r}`); - Object.keys(i2).forEach((n3) => { - const o2 = i2[n3]; - if (!Array.isArray(o2)) - throw new Error(`Ability limits ${n3} must be an array of objects, found: ${o2}`); - if (!o2.length) - throw new Error(`Value of ${n3} is empty array, must be an array with objects`); - o2.forEach((h5) => { - if (typeof h5 != "object") - throw new Error(`Ability limits (${n3}) must be an array of objects, found: ${h5}`); - }); - }); - }); - } - function jf(e2, t, r, i2 = {}) { - return r?.sort((n3, o2) => n3.localeCompare(o2)), { att: { [e2]: Vi(t, r, i2) } }; - } - function Vf(e2, t, r) { - var i2; - return e2.att[t] = Li({}, r), ((i2 = Object.keys(e2.att)) == null ? void 0 : i2.sort((n3, o2) => n3.localeCompare(o2))).reduce((n3, o2) => (n3.att[o2] = e2.att[o2], n3), { att: {} }); - } - function Vi(e2, t, r = {}) { - t = t?.sort((n3, o2) => n3.localeCompare(o2)); - const i2 = t.map((n3) => ({ [`${e2}/${n3}`]: [r] })); - return Object.assign({}, ...i2); - } - function Vr(e2) { - return ve(e2), `urn:recap:${Lf(e2).replace(/=/g, "")}`; - } - function Ce(e2) { - const t = zf(e2.replace("urn:recap:", "")); - return ve(t), t; - } - function su(e2, t, r) { - const i2 = jf(e2, t, r); - return Vr(i2); - } - function Qi(e2) { - return e2 && e2.includes("urn:recap:"); - } - function au(e2, t) { - const r = Ce(e2), i2 = Ce(t), n3 = Qf(r, i2); - return Vr(n3); - } - function Qf(e2, t) { - ve(e2), ve(t); - const r = Object.keys(e2.att).concat(Object.keys(t.att)).sort((n3, o2) => n3.localeCompare(o2)), i2 = { att: {} }; - return r.forEach((n3) => { - var o2, h5; - Object.keys(((o2 = e2.att) == null ? void 0 : o2[n3]) || {}).concat(Object.keys(((h5 = t.att) == null ? void 0 : h5[n3]) || {})).sort((p3, b4) => p3.localeCompare(b4)).forEach((p3) => { - var b4, g3; - i2.att[n3] = Uf(Li({}, i2.att[n3]), { [p3]: ((b4 = e2.att[n3]) == null ? void 0 : b4[p3]) || ((g3 = t.att[n3]) == null ? void 0 : g3[p3]) }); - }); - }), i2; - } - function Ji(e2 = "", t) { - ve(t); - const r = "I further authorize the stated URI to perform the following actions on my behalf: "; - if (e2.includes(r)) - return e2; - const i2 = []; - let n3 = 0; - Object.keys(t.att).forEach((p3) => { - const b4 = Object.keys(t.att[p3]).map((y4) => ({ ability: y4.split("/")[0], action: y4.split("/")[1] })); - b4.sort((y4, S4) => y4.action.localeCompare(S4.action)); - const g3 = {}; - b4.forEach((y4) => { - g3[y4.ability] || (g3[y4.ability] = []), g3[y4.ability].push(y4.action); - }); - const w4 = Object.keys(g3).map((y4) => (n3++, `(${n3}) '${y4}': '${g3[y4].join("', '")}' for '${p3}'.`)); - i2.push(w4.join(", ").replace(".,", ".")); - }); - const o2 = i2.join(" "), h5 = `${r}${o2}`; - return `${e2 ? e2 + " " : ""}${h5}`; - } - function uu(e2) { - var t; - const r = Ce(e2); - ve(r); - const i2 = (t = r.att) == null ? void 0 : t.eip155; - return i2 ? Object.keys(i2).map((n3) => n3.split("/")[1]) : []; - } - function hu(e2) { - const t = Ce(e2); - ve(t); - const r = []; - return Object.values(t.att).forEach((i2) => { - Object.values(i2).forEach((n3) => { - var o2; - (o2 = n3?.[0]) != null && o2.chains && r.push(n3[0].chains); - }); - }), [...new Set(r.flat())]; - } - function Jf(e2, t) { - if (!t) - return e2; - const r = Ce(t); - return ve(r), Ji(e2, r); - } - function Qr(e2) { - if (!e2) - return; - const t = e2?.[e2.length - 1]; - return Qi(t) ? t : void 0; - } - var Yi = "base10"; - var zt = "base16"; - var Jr = "base64pad"; - var Yr = "utf8"; - var Gi = 0; - var dr = 1; - var cu = 0; - var Yf = 1; - var Wi = 12; - var Xi = 32; - function lu() { - const e2 = an.generateKeyPair(); - return { privateKey: Rt.toString(e2.secretKey, zt), publicKey: Rt.toString(e2.publicKey, zt) }; - } - function du() { - const e2 = on.randomBytes(Xi); - return Rt.toString(e2, zt); - } - function pu(e2, t) { - const r = an.sharedKey(Rt.fromString(e2, zt), Rt.fromString(t, zt), true), i2 = new Po.HKDF(ci.SHA256, r).expand(Xi); - return Rt.toString(i2, zt); - } - function vu(e2) { - const t = ci.hash(Rt.fromString(e2, zt)); - return Rt.toString(t, zt); - } - function gu(e2) { - const t = ci.hash(Rt.fromString(e2, Yr)); - return Rt.toString(t, zt); - } - function Gf(e2) { - return Rt.fromString(`${e2}`, Yi); - } - function Er(e2) { - return Number(Rt.toString(e2, Yi)); - } - function mu(e2) { - const t = Gf(typeof e2.type < "u" ? e2.type : Gi); - if (Er(t) === dr && typeof e2.senderPublicKey > "u") - throw new Error("Missing sender public key for type 1 envelope"); - const r = typeof e2.senderPublicKey < "u" ? Rt.fromString(e2.senderPublicKey, zt) : void 0, i2 = typeof e2.iv < "u" ? Rt.fromString(e2.iv, zt) : on.randomBytes(Wi), n3 = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)).seal(i2, Rt.fromString(e2.message, Yr)); - return Wf({ type: t, sealed: n3, iv: i2, senderPublicKey: r }); - } - function Au(e2) { - const t = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)), { sealed: r, iv: i2 } = Zi(e2.encoded), n3 = t.open(i2, r); - if (n3 === null) - throw new Error("Failed to decrypt"); - return Rt.toString(n3, Yr); - } - function Wf(e2) { - if (Er(e2.type) === dr) { - if (typeof e2.senderPublicKey > "u") - throw new Error("Missing sender public key for type 1 envelope"); - return Rt.toString(Rt.concat([e2.type, e2.senderPublicKey, e2.iv, e2.sealed]), Jr); - } - return Rt.toString(Rt.concat([e2.type, e2.iv, e2.sealed]), Jr); - } - function Zi(e2) { - const t = Rt.fromString(e2, Jr), r = t.slice(cu, Yf), i2 = Yf; - if (Er(r) === dr) { - const p3 = i2 + Xi, b4 = p3 + Wi, g3 = t.slice(i2, p3), w4 = t.slice(p3, b4), y4 = t.slice(b4); - return { type: r, sealed: y4, iv: w4, senderPublicKey: g3 }; - } - const n3 = i2 + Wi, o2 = t.slice(i2, n3), h5 = t.slice(n3); - return { type: r, sealed: h5, iv: o2 }; - } - function bu(e2, t) { - const r = Zi(e2); - return Xf({ type: Er(r.type), senderPublicKey: typeof r.senderPublicKey < "u" ? Rt.toString(r.senderPublicKey, zt) : void 0, receiverPublicKey: t?.receiverPublicKey }); - } - function Xf(e2) { - const t = e2?.type || Gi; - if (t === dr) { - if (typeof e2?.senderPublicKey > "u") - throw new Error("missing sender public key"); - if (typeof e2?.receiverPublicKey > "u") - throw new Error("missing receiver public key"); - } - return { type: t, senderPublicKey: e2?.senderPublicKey, receiverPublicKey: e2?.receiverPublicKey }; - } - function yu(e2) { - return e2.type === dr && typeof e2.senderPublicKey == "string" && typeof e2.receiverPublicKey == "string"; - } - var Zf = "irn"; - function wu(e2) { - return e2?.relay || { protocol: Zf }; - } - function xu(e2) { - const t = Fo.RELAY_JSONRPC[e2]; - if (typeof t > "u") - throw new Error(`Relay Protocol not supported: ${e2}`); - return t; - } - var Mu = Object.defineProperty; - var Eu = Object.defineProperties; - var Su = Object.getOwnPropertyDescriptors; - var $f = Object.getOwnPropertySymbols; - var Nu = Object.prototype.hasOwnProperty; - var Iu = Object.prototype.propertyIsEnumerable; - var to = (e2, t, r) => t in e2 ? Mu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var eo = (e2, t) => { - for (var r in t || (t = {})) - Nu.call(t, r) && to(e2, r, t[r]); - if ($f) - for (var r of $f(t)) - Iu.call(t, r) && to(e2, r, t[r]); - return e2; - }; - var _u = (e2, t) => Eu(e2, Su(t)); - function ro(e2, t = "-") { - const r = {}, i2 = "relay" + t; - return Object.keys(e2).forEach((n3) => { - if (n3.startsWith(i2)) { - const o2 = n3.replace(i2, ""), h5 = e2[n3]; - r[o2] = h5; - } - }), r; - } - function Bu(e2) { - e2 = e2.includes("wc://") ? e2.replace("wc://", "") : e2, e2 = e2.includes("wc:") ? e2.replace("wc:", "") : e2; - const t = e2.indexOf(":"), r = e2.indexOf("?") !== -1 ? e2.indexOf("?") : void 0, i2 = e2.substring(0, t), n3 = e2.substring(t + 1, r).split("@"), o2 = typeof r < "u" ? e2.substring(r) : "", h5 = Ir.parse(o2), p3 = typeof h5.methods == "string" ? h5.methods.split(",") : void 0; - return { protocol: i2, topic: io(n3[0]), version: parseInt(n3[1], 10), symKey: h5.symKey, relay: ro(h5), methods: p3, expiryTimestamp: h5.expiryTimestamp ? parseInt(h5.expiryTimestamp, 10) : void 0 }; - } - function io(e2) { - return e2.startsWith("//") ? e2.substring(2) : e2; - } - function no(e2, t = "-") { - const r = "relay", i2 = {}; - return Object.keys(e2).forEach((n3) => { - const o2 = r + t + n3; - e2[n3] && (i2[o2] = e2[n3]); - }), i2; - } - function Ru(e2) { - return `${e2.protocol}:${e2.topic}@${e2.version}?` + Ir.stringify(eo(_u(eo({ symKey: e2.symKey }, no(e2.relay)), { expiryTimestamp: e2.expiryTimestamp }), e2.methods ? { methods: e2.methods.join(",") } : {})); - } - var Cu = Object.defineProperty; - var Ou = Object.defineProperties; - var Pu = Object.getOwnPropertyDescriptors; - var fo = Object.getOwnPropertySymbols; - var Tu = Object.prototype.hasOwnProperty; - var Fu = Object.prototype.propertyIsEnumerable; - var oo = (e2, t, r) => t in e2 ? Cu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var Du = (e2, t) => { - for (var r in t || (t = {})) - Tu.call(t, r) && oo(e2, r, t[r]); - if (fo) - for (var r of fo(t)) - Fu.call(t, r) && oo(e2, r, t[r]); - return e2; - }; - var Uu = (e2, t) => Ou(e2, Pu(t)); - function Ze(e2) { - const t = []; - return e2.forEach((r) => { - const [i2, n3] = r.split(":"); - t.push(`${i2}:${n3}`); - }), t; - } - function so(e2) { - const t = []; - return Object.values(e2).forEach((r) => { - t.push(...Ze(r.accounts)); - }), t; - } - function ao(e2, t) { - const r = []; - return Object.values(e2).forEach((i2) => { - Ze(i2.accounts).includes(t) && r.push(...i2.methods); - }), r; - } - function uo(e2, t) { - const r = []; - return Object.values(e2).forEach((i2) => { - Ze(i2.accounts).includes(t) && r.push(...i2.events); - }), r; - } - function ku(e2, t) { - const r = wo(e2, t); - if (r) - throw new Error(r.message); - const i2 = {}; - for (const [n3, o2] of Object.entries(e2)) - i2[n3] = { methods: o2.methods, events: o2.events, chains: o2.accounts.map((h5) => `${h5.split(":")[0]}:${h5.split(":")[1]}`) }; - return i2; - } - function qu(e2) { - const { proposal: { requiredNamespaces: t, optionalNamespaces: r = {} }, supportedNamespaces: i2 } = e2, n3 = tn(t), o2 = tn(r), h5 = {}; - Object.keys(i2).forEach((g3) => { - const w4 = i2[g3].chains, y4 = i2[g3].methods, S4 = i2[g3].events, I2 = i2[g3].accounts; - w4.forEach((N10) => { - if (!I2.some((R2) => R2.includes(N10))) - throw new Error(`No accounts provided for chain ${N10} in namespace ${g3}`); - }), h5[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; - }); - const p3 = Mo(t, h5, "approve()"); - if (p3) - throw new Error(p3.message); - const b4 = {}; - return !Object.keys(t).length && !Object.keys(r).length ? h5 : (Object.keys(n3).forEach((g3) => { - const w4 = i2[g3].chains.filter((N10) => { - var R2, F; - return (F = (R2 = n3[g3]) == null ? void 0 : R2.chains) == null ? void 0 : F.includes(N10); - }), y4 = i2[g3].methods.filter((N10) => { - var R2, F; - return (F = (R2 = n3[g3]) == null ? void 0 : R2.methods) == null ? void 0 : F.includes(N10); - }), S4 = i2[g3].events.filter((N10) => { - var R2, F; - return (F = (R2 = n3[g3]) == null ? void 0 : R2.events) == null ? void 0 : F.includes(N10); - }), I2 = w4.map((N10) => i2[g3].accounts.filter((R2) => R2.includes(`${N10}:`))).flat(); - b4[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; - }), Object.keys(o2).forEach((g3) => { - var w4, y4, S4, I2, N10, R2; - if (!i2[g3]) - return; - const F = (y4 = (w4 = o2[g3]) == null ? void 0 : w4.chains) == null ? void 0 : y4.filter((J) => i2[g3].chains.includes(J)), U2 = i2[g3].methods.filter((J) => { - var H, L2; - return (L2 = (H = o2[g3]) == null ? void 0 : H.methods) == null ? void 0 : L2.includes(J); - }), Q = i2[g3].events.filter((J) => { - var H, L2; - return (L2 = (H = o2[g3]) == null ? void 0 : H.events) == null ? void 0 : L2.includes(J); - }), Bt = F?.map((J) => i2[g3].accounts.filter((H) => H.includes(`${J}:`))).flat(); - b4[g3] = { chains: ge((S4 = b4[g3]) == null ? void 0 : S4.chains, F), methods: ge((I2 = b4[g3]) == null ? void 0 : I2.methods, U2), events: ge((N10 = b4[g3]) == null ? void 0 : N10.events, Q), accounts: ge((R2 = b4[g3]) == null ? void 0 : R2.accounts, Bt) }; - }), b4); - } - function $i(e2) { - return e2.includes(":"); - } - function ho(e2) { - return $i(e2) ? e2.split(":")[0] : e2; - } - function tn(e2) { - var t, r, i2; - const n3 = {}; - if (!Gr(e2)) - return n3; - for (const [o2, h5] of Object.entries(e2)) { - const p3 = $i(o2) ? [o2] : h5.chains, b4 = h5.methods || [], g3 = h5.events || [], w4 = ho(o2); - n3[w4] = Uu(Du({}, n3[w4]), { chains: ge(p3, (t = n3[w4]) == null ? void 0 : t.chains), methods: ge(b4, (r = n3[w4]) == null ? void 0 : r.methods), events: ge(g3, (i2 = n3[w4]) == null ? void 0 : i2.events) }); - } - return n3; - } - function co(e2) { - const t = {}; - return e2?.forEach((r) => { - const [i2, n3] = r.split(":"); - t[i2] || (t[i2] = { accounts: [], chains: [], events: [] }), t[i2].accounts.push(r), t[i2].chains.push(`${i2}:${n3}`); - }), t; - } - function Ku(e2, t) { - t = t.map((i2) => i2.replace("did:pkh:", "")); - const r = co(t); - for (const [i2, n3] of Object.entries(r)) - n3.methods ? n3.methods = ge(n3.methods, e2) : n3.methods = e2, n3.events = ["chainChanged", "accountsChanged"]; - return r; - } - var lo = { INVALID_METHOD: { message: "Invalid method.", code: 1001 }, INVALID_EVENT: { message: "Invalid event.", code: 1002 }, INVALID_UPDATE_REQUEST: { message: "Invalid update request.", code: 1003 }, INVALID_EXTEND_REQUEST: { message: "Invalid extend request.", code: 1004 }, INVALID_SESSION_SETTLE_REQUEST: { message: "Invalid session settle request.", code: 1005 }, UNAUTHORIZED_METHOD: { message: "Unauthorized method.", code: 3001 }, UNAUTHORIZED_EVENT: { message: "Unauthorized event.", code: 3002 }, UNAUTHORIZED_UPDATE_REQUEST: { message: "Unauthorized update request.", code: 3003 }, UNAUTHORIZED_EXTEND_REQUEST: { message: "Unauthorized extend request.", code: 3004 }, USER_REJECTED: { message: "User rejected.", code: 5e3 }, USER_REJECTED_CHAINS: { message: "User rejected chains.", code: 5001 }, USER_REJECTED_METHODS: { message: "User rejected methods.", code: 5002 }, USER_REJECTED_EVENTS: { message: "User rejected events.", code: 5003 }, UNSUPPORTED_CHAINS: { message: "Unsupported chains.", code: 5100 }, UNSUPPORTED_METHODS: { message: "Unsupported methods.", code: 5101 }, UNSUPPORTED_EVENTS: { message: "Unsupported events.", code: 5102 }, UNSUPPORTED_ACCOUNTS: { message: "Unsupported accounts.", code: 5103 }, UNSUPPORTED_NAMESPACE_KEY: { message: "Unsupported namespace key.", code: 5104 }, USER_DISCONNECTED: { message: "User disconnected.", code: 6e3 }, SESSION_SETTLEMENT_FAILED: { message: "Session settlement failed.", code: 7e3 }, WC_METHOD_UNSUPPORTED: { message: "Unsupported wc_ method.", code: 10001 } }; - var po = { NOT_INITIALIZED: { message: "Not initialized.", code: 1 }, NO_MATCHING_KEY: { message: "No matching key.", code: 2 }, RESTORE_WILL_OVERRIDE: { message: "Restore will override.", code: 3 }, RESUBSCRIBED: { message: "Resubscribed.", code: 4 }, MISSING_OR_INVALID: { message: "Missing or invalid.", code: 5 }, EXPIRED: { message: "Expired.", code: 6 }, UNKNOWN_TYPE: { message: "Unknown type.", code: 7 }, MISMATCHED_TOPIC: { message: "Mismatched topic.", code: 8 }, NON_CONFORMING_NAMESPACES: { message: "Non conforming namespaces.", code: 9 } }; - function we(e2, t) { - const { message: r, code: i2 } = po[e2]; - return { message: t ? `${r} ${t}` : r, code: i2 }; - } - function $e(e2, t) { - const { message: r, code: i2 } = lo[e2]; - return { message: t ? `${r} ${t}` : r, code: i2 }; - } - function Sr(e2, t) { - return Array.isArray(e2) ? typeof t < "u" && e2.length ? e2.every(t) : true : false; - } - function Gr(e2) { - return Object.getPrototypeOf(e2) === Object.prototype && Object.keys(e2).length; - } - function Oe(e2) { - return typeof e2 > "u"; - } - function Yt(e2, t) { - return t && Oe(e2) ? true : typeof e2 == "string" && !!e2.trim().length; - } - function Wr(e2, t) { - return t && Oe(e2) ? true : typeof e2 == "number" && !isNaN(e2); - } - function Hu(e2, t) { - const { requiredNamespaces: r } = t, i2 = Object.keys(e2.namespaces), n3 = Object.keys(r); - let o2 = true; - return Ie(n3, i2) ? (i2.forEach((h5) => { - const { accounts: p3, methods: b4, events: g3 } = e2.namespaces[h5], w4 = Ze(p3), y4 = r[h5]; - (!Ie(Br(h5, y4), w4) || !Ie(y4.methods, b4) || !Ie(y4.events, g3)) && (o2 = false); - }), o2) : false; - } - function Nr(e2) { - return Yt(e2, false) && e2.includes(":") ? e2.split(":").length === 2 : false; - } - function vo(e2) { - if (Yt(e2, false) && e2.includes(":")) { - const t = e2.split(":"); - if (t.length === 3) { - const r = t[0] + ":" + t[1]; - return !!t[2] && Nr(r); - } - } - return false; - } - function Lu(e2) { - if (Yt(e2, false)) - try { - return typeof new URL(e2) < "u"; - } catch { - return false; - } - return false; - } - function zu(e2) { - var t; - return (t = e2?.proposer) == null ? void 0 : t.publicKey; - } - function ju(e2) { - return e2?.topic; - } - function Vu(e2, t) { - let r = null; - return Yt(e2?.publicKey, false) || (r = we("MISSING_OR_INVALID", `${t} controller public key should be a string`)), r; - } - function en(e2) { - let t = true; - return Sr(e2) ? e2.length && (t = e2.every((r) => Yt(r, false))) : t = false, t; - } - function go(e2, t, r) { - let i2 = null; - return Sr(t) && t.length ? t.forEach((n3) => { - i2 || Nr(n3) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chain ${n3} should be a string and conform to "namespace:chainId" format`)); - }) : Nr(e2) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)), i2; - } - function mo(e2, t, r) { - let i2 = null; - return Object.entries(e2).forEach(([n3, o2]) => { - if (i2) - return; - const h5 = go(n3, Br(n3, o2), `${t} ${r}`); - h5 && (i2 = h5); - }), i2; - } - function Ao(e2, t) { - let r = null; - return Sr(e2) ? e2.forEach((i2) => { - r || vo(i2) || (r = $e("UNSUPPORTED_ACCOUNTS", `${t}, account ${i2} should be a string and conform to "namespace:chainId:address" format`)); - }) : r = $e("UNSUPPORTED_ACCOUNTS", `${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`), r; - } - function bo(e2, t) { - let r = null; - return Object.values(e2).forEach((i2) => { - if (r) - return; - const n3 = Ao(i2?.accounts, `${t} namespace`); - n3 && (r = n3); - }), r; - } - function yo(e2, t) { - let r = null; - return en(e2?.methods) ? en(e2?.events) || (r = $e("UNSUPPORTED_EVENTS", `${t}, events should be an array of strings or empty array for no events`)) : r = $e("UNSUPPORTED_METHODS", `${t}, methods should be an array of strings or empty array for no methods`), r; - } - function rn(e2, t) { - let r = null; - return Object.values(e2).forEach((i2) => { - if (r) - return; - const n3 = yo(i2, `${t}, namespace`); - n3 && (r = n3); - }), r; - } - function Qu(e2, t, r) { - let i2 = null; - if (e2 && Gr(e2)) { - const n3 = rn(e2, t); - n3 && (i2 = n3); - const o2 = mo(e2, t, r); - o2 && (i2 = o2); - } else - i2 = we("MISSING_OR_INVALID", `${t}, ${r} should be an object with data`); - return i2; - } - function wo(e2, t) { - let r = null; - if (e2 && Gr(e2)) { - const i2 = rn(e2, t); - i2 && (r = i2); - const n3 = bo(e2, t); - n3 && (r = n3); - } else - r = we("MISSING_OR_INVALID", `${t}, namespaces should be an object with data`); - return r; - } - function xo(e2) { - return Yt(e2.protocol, true); - } - function Ju(e2, t) { - let r = false; - return t && !e2 ? r = true : e2 && Sr(e2) && e2.length && e2.forEach((i2) => { - r = xo(i2); - }), r; - } - function Yu(e2) { - return typeof e2 == "number"; - } - function Gu(e2) { - return typeof e2 < "u" && typeof e2 !== null; - } - function Wu(e2) { - return !(!e2 || typeof e2 != "object" || !e2.code || !Wr(e2.code, false) || !e2.message || !Yt(e2.message, false)); - } - function Xu(e2) { - return !(Oe(e2) || !Yt(e2.method, false)); - } - function Zu(e2) { - return !(Oe(e2) || Oe(e2.result) && Oe(e2.error) || !Wr(e2.id, false) || !Yt(e2.jsonrpc, false)); - } - function $u(e2) { - return !(Oe(e2) || !Yt(e2.name, false)); - } - function th(e2, t) { - return !(!Nr(t) || !so(e2).includes(t)); - } - function eh(e2, t, r) { - return Yt(r, false) ? ao(e2, t).includes(r) : false; - } - function rh(e2, t, r) { - return Yt(r, false) ? uo(e2, t).includes(r) : false; - } - function Mo(e2, t, r) { - let i2 = null; - const n3 = ih(e2), o2 = nh(t), h5 = Object.keys(n3), p3 = Object.keys(o2), b4 = Eo(Object.keys(e2)), g3 = Eo(Object.keys(t)), w4 = b4.filter((y4) => !g3.includes(y4)); - return w4.length && (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces keys don't satisfy requiredNamespaces. - Required: ${w4.toString()} - Received: ${Object.keys(t).toString()}`)), Ie(h5, p3) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces chains don't satisfy required namespaces. - Required: ${h5.toString()} - Approved: ${p3.toString()}`)), Object.keys(t).forEach((y4) => { - if (!y4.includes(":") || i2) - return; - const S4 = Ze(t[y4].accounts); - S4.includes(y4) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces accounts don't satisfy namespace accounts for ${y4} - Required: ${y4} - Approved: ${S4.toString()}`)); - }), h5.forEach((y4) => { - i2 || (Ie(n3[y4].methods, o2[y4].methods) ? Ie(n3[y4].events, o2[y4].events) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces events don't satisfy namespace events for ${y4}`)) : i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces methods don't satisfy namespace methods for ${y4}`)); - }), i2; - } - function ih(e2) { - const t = {}; - return Object.keys(e2).forEach((r) => { - var i2; - r.includes(":") ? t[r] = e2[r] : (i2 = e2[r].chains) == null || i2.forEach((n3) => { - t[n3] = { methods: e2[r].methods, events: e2[r].events }; - }); - }), t; - } - function Eo(e2) { - return [...new Set(e2.map((t) => t.includes(":") ? t.split(":")[0] : t))]; - } - function nh(e2) { - const t = {}; - return Object.keys(e2).forEach((r) => { - if (r.includes(":")) - t[r] = e2[r]; - else { - const i2 = Ze(e2[r].accounts); - i2?.forEach((n3) => { - t[n3] = { accounts: e2[r].accounts.filter((o2) => o2.includes(`${n3}:`)), methods: e2[r].methods, events: e2[r].events }; - }); - } - }), t; - } - function fh(e2, t) { - return Wr(e2, false) && e2 <= t.max && e2 >= t.min; - } - function oh() { - const e2 = Ge(); - return new Promise((t) => { - switch (e2) { - case Kt.browser: - t(So()); - break; - case Kt.reactNative: - t(No()); - break; - case Kt.node: - t(Io()); - break; - default: - t(true); - } - }); - } - function So() { - return vr() && navigator?.onLine; - } - async function No() { - if (rr() && typeof global < "u" && global != null && global.NetInfo) { - const e2 = await (global == null ? void 0 : global.NetInfo.fetch()); - return e2?.isConnected; - } - return true; - } - function Io() { - return true; - } - function sh(e2) { - switch (Ge()) { - case Kt.browser: - _o(e2); - break; - case Kt.reactNative: - Bo(e2); - break; - case Kt.node: - break; - } - } - function _o(e2) { - !rr() && vr() && (window.addEventListener("online", () => e2(true)), window.addEventListener("offline", () => e2(false))); - } - function Bo(e2) { - rr() && typeof global < "u" && global != null && global.NetInfo && global?.NetInfo.addEventListener((t) => e2(t?.isConnected)); - } - var nn = {}; - var ah = class { - static get(t) { - return nn[t]; - } - static set(t, r) { - nn[t] = r; - } - static delete(t) { - delete nn[t]; - } - }; - exports2.BASE10 = Yi, exports2.BASE16 = zt, exports2.BASE64 = Jr, exports2.COLON = jo, exports2.DEFAULT_DEPTH = pi, exports2.EMPTY_SPACE = Rr, exports2.ENV_MAP = Kt, exports2.INTERNAL_ERRORS = po, exports2.MemoryStore = ah, exports2.ONE_THOUSAND = Vo, exports2.REACT_NATIVE_PRODUCT = An, exports2.RELAYER_DEFAULT_PROTOCOL = Zf, exports2.SDK_ERRORS = lo, exports2.SDK_TYPE = yn, exports2.SLASH = bn, exports2.TYPE_0 = Gi, exports2.TYPE_1 = dr, exports2.UTF8 = Yr, exports2.addResourceToRecap = Vf, exports2.appendToQueryString = wn, exports2.assertType = Xo, exports2.assignAbilityToActions = Vi, exports2.base64Decode = zf, exports2.base64Encode = Lf, exports2.buildApprovedNamespaces = qu, exports2.buildAuthObject = iu, exports2.buildNamespacesFromAuth = Ku, exports2.buildRecapStatement = Jf, exports2.calcExpiry = us, exports2.capitalize = is, exports2.capitalizeWord = In, exports2.createDelayedPromise = ns, exports2.createEncodedRecap = su, exports2.createExpiringPromise = fs, exports2.createRecap = jf, exports2.decodeRecap = Ce, exports2.decodeTypeByte = Er, exports2.decrypt = Au, exports2.deriveSymKey = pu, exports2.deserialize = Zi, exports2.encodeRecap = Vr, exports2.encodeTypeByte = Gf, exports2.encrypt = mu, exports2.engineEvent = cs, exports2.enumify = rs, exports2.formatAccountId = cn, exports2.formatAccountWithChain = Do, exports2.formatChainId = hn, exports2.formatExpirerTarget = gi, exports2.formatIdTarget = ss, exports2.formatMessage = kf, exports2.formatMessageContext = Zo, exports2.formatRelayParams = no, exports2.formatRelayRpcUrl = Go, exports2.formatStatementFromRecap = Ji, exports2.formatTopicTarget = os, exports2.formatUA = En, exports2.formatUri = Ru, exports2.generateKeyPair = lu, exports2.generateRandomBytes32 = du, exports2.getAccountsChains = Ze, exports2.getAccountsFromNamespaces = ko, exports2.getAddressFromAccount = ln, exports2.getAddressesFromAccounts = Uo, exports2.getAppMetadata = Jo, exports2.getBrowserOnlineStatus = So, exports2.getBundleId = Qo, exports2.getChainFromAccount = dn, exports2.getChainsFromAccounts = pn, exports2.getChainsFromNamespace = Br, exports2.getChainsFromNamespaces = qo, exports2.getChainsFromRecap = hu, exports2.getChainsFromRequiredNamespaces = Ko, exports2.getCommonValuesInArrays = mi, exports2.getDecodedRecapFromResources = qf, exports2.getDeepLink = ds, exports2.getDidAddress = ji, exports2.getDidAddressSegments = jr, exports2.getDidChainId = zi, exports2.getEnvironment = Ge, exports2.getHttpUrl = Wo, exports2.getInternalError = we, exports2.getJavascriptID = Mn, exports2.getJavascriptOS = xn, exports2.getLastItems = Nn, exports2.getMethodsFromRecap = uu, exports2.getNamespacedDidChainId = eu, exports2.getNamespacesChains = so, exports2.getNamespacesEventsForChainId = uo, exports2.getNamespacesFromAccounts = co, exports2.getNamespacesMethodsForChainId = ao, exports2.getNodeOnlineStatus = Io, exports2.getReCapActions = Hf, exports2.getReactNativeOnlineStatus = No, exports2.getRecapAbilitiesFromResource = ou, exports2.getRecapFromResources = Qr, exports2.getRecapResource = Kf, exports2.getRelayClientMetadata = Yo, exports2.getRelayProtocolApi = xu, exports2.getRelayProtocolName = wu, exports2.getRequiredNamespacesFromNamespaces = ku, exports2.getSdkError = $e, exports2.getUniqueValues = di, exports2.handleDeeplinkRedirect = ls2, exports2.hasOverlap = Ie, exports2.hashKey = vu, exports2.hashMessage = gu, exports2.isBrowser = vr, exports2.isCaipNamespace = $i, exports2.isConformingNamespaces = Mo, exports2.isExpired = hs, exports2.isNode = vi, exports2.isOnline = oh, exports2.isProposalStruct = zu, exports2.isReactNative = rr, exports2.isRecap = Qi, exports2.isSessionCompatible = Hu, exports2.isSessionStruct = ju, exports2.isTypeOneEnvelope = yu, exports2.isUndefined = Oe, exports2.isValidAccountId = vo, exports2.isValidAccounts = Ao, exports2.isValidActions = yo, exports2.isValidArray = Sr, exports2.isValidChainId = Nr, exports2.isValidChains = go, exports2.isValidController = Vu, exports2.isValidEip1271Signature = Tf, exports2.isValidEip191Signature = Pf, exports2.isValidErrorReason = Wu, exports2.isValidEvent = $u, exports2.isValidId = Yu, exports2.isValidNamespaceAccounts = bo, exports2.isValidNamespaceActions = rn, exports2.isValidNamespaceChains = mo, exports2.isValidNamespaceMethodsOrEvents = en, exports2.isValidNamespaces = wo, exports2.isValidNamespacesChainId = th, exports2.isValidNamespacesEvent = rh, exports2.isValidNamespacesRequest = eh, exports2.isValidNumber = Wr, exports2.isValidObject = Gr, exports2.isValidParams = Gu, exports2.isValidRecap = ve, exports2.isValidRelay = xo, exports2.isValidRelays = Ju, exports2.isValidRequest = Xu, exports2.isValidRequestExpiry = fh, exports2.isValidRequiredNamespaces = Qu, exports2.isValidResponse = Zu, exports2.isValidString = Yt, exports2.isValidUrl = Lu, exports2.mapEntries = es, exports2.mapToObj = $o, exports2.mergeArrays = ge, exports2.mergeEncodedRecaps = au, exports2.mergeRecaps = Qf, exports2.normalizeNamespaces = tn, exports2.objToMap = ts, exports2.parseAccountId = li, exports2.parseChainId = un, exports2.parseContextNames = Sn, exports2.parseExpirerTarget = as, exports2.parseNamespaceKey = ho, exports2.parseRelayParams = ro, exports2.parseTopic = io, exports2.parseUri = Bu, exports2.populateAuthPayload = nu, exports2.recapHasResource = fu, exports2.serialize = Wf, exports2.subscribeToBrowserNetworkChange = _o, exports2.subscribeToNetworkChange = sh, exports2.subscribeToReactNativeNetworkChange = Bo, exports2.validateDecoding = bu, exports2.validateEncoding = Xf, exports2.validateSignedCacao = ru, exports2.verifySignature = Of; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js -var PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, SERVER_ERROR, RESERVED_ERROR_CODES, SERVER_ERROR_CODE_RANGE, STANDARD_ERROR_MAP, DEFAULT_ERROR; -var init_constants2 = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js"() { - init_shim(); - PARSE_ERROR = "PARSE_ERROR"; - INVALID_REQUEST = "INVALID_REQUEST"; - METHOD_NOT_FOUND = "METHOD_NOT_FOUND"; - INVALID_PARAMS = "INVALID_PARAMS"; - INTERNAL_ERROR = "INTERNAL_ERROR"; - SERVER_ERROR = "SERVER_ERROR"; - RESERVED_ERROR_CODES = [-32700, -32600, -32601, -32602, -32603]; - SERVER_ERROR_CODE_RANGE = [-32e3, -32099]; - STANDARD_ERROR_MAP = { - [PARSE_ERROR]: { code: -32700, message: "Parse error" }, - [INVALID_REQUEST]: { code: -32600, message: "Invalid Request" }, - [METHOD_NOT_FOUND]: { code: -32601, message: "Method not found" }, - [INVALID_PARAMS]: { code: -32602, message: "Invalid params" }, - [INTERNAL_ERROR]: { code: -32603, message: "Internal error" }, - [SERVER_ERROR]: { code: -32e3, message: "Server error" } - }; - DEFAULT_ERROR = SERVER_ERROR; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js -function isServerErrorCode(code2) { - return code2 <= SERVER_ERROR_CODE_RANGE[0] && code2 >= SERVER_ERROR_CODE_RANGE[1]; -} -function isReservedErrorCode(code2) { - return RESERVED_ERROR_CODES.includes(code2); -} -function isValidErrorCode(code2) { - return typeof code2 === "number"; -} -function getError(type) { - if (!Object.keys(STANDARD_ERROR_MAP).includes(type)) { - return STANDARD_ERROR_MAP[DEFAULT_ERROR]; - } - return STANDARD_ERROR_MAP[type]; -} -function getErrorByCode(code2) { - const match = Object.values(STANDARD_ERROR_MAP).find((e2) => e2.code === code2); - if (!match) { - return STANDARD_ERROR_MAP[DEFAULT_ERROR]; - } - return match; -} -function validateJsonRpcError(response) { - if (typeof response.error.code === "undefined") { - return { valid: false, error: "Missing code for JSON-RPC error" }; - } - if (typeof response.error.message === "undefined") { - return { valid: false, error: "Missing message for JSON-RPC error" }; - } - if (!isValidErrorCode(response.error.code)) { - return { - valid: false, - error: `Invalid error code type for JSON-RPC: ${response.error.code}` - }; - } - if (isReservedErrorCode(response.error.code)) { - const error = getErrorByCode(response.error.code); - if (error.message !== STANDARD_ERROR_MAP[DEFAULT_ERROR].message && response.error.message === error.message) { - return { - valid: false, - error: `Invalid error code message for JSON-RPC: ${response.error.code}` - }; - } - } - return { valid: true }; -} -function parseConnectionError(e2, url, type) { - return e2.message.includes("getaddrinfo ENOTFOUND") || e2.message.includes("connect ECONNREFUSED") ? new Error(`Unavailable ${type} RPC url at ${url}`) : e2; -} -var init_error = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js"() { - init_shim(); - init_constants2(); - } -}); - -// node_modules/@walletconnect/environment/dist/cjs/crypto.js -var require_crypto2 = __commonJS({ - "node_modules/@walletconnect/environment/dist/cjs/crypto.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isBrowserCryptoAvailable = exports2.getSubtleCrypto = exports2.getBrowerCrypto = void 0; - function getBrowerCrypto() { - return (global === null || global === void 0 ? void 0 : global.crypto) || (global === null || global === void 0 ? void 0 : global.msCrypto) || {}; - } - exports2.getBrowerCrypto = getBrowerCrypto; - function getSubtleCrypto() { - const browserCrypto = getBrowerCrypto(); - return browserCrypto.subtle || browserCrypto.webkitSubtle; - } - exports2.getSubtleCrypto = getSubtleCrypto; - function isBrowserCryptoAvailable() { - return !!getBrowerCrypto() && !!getSubtleCrypto(); - } - exports2.isBrowserCryptoAvailable = isBrowserCryptoAvailable; - } -}); - -// node_modules/@walletconnect/environment/dist/cjs/env.js -var require_env = __commonJS({ - "node_modules/@walletconnect/environment/dist/cjs/env.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isBrowser = exports2.isNode = exports2.isReactNative = void 0; - function isReactNative() { - return typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative"; - } - exports2.isReactNative = isReactNative; - function isNode2() { - return typeof import_process.default !== "undefined" && typeof import_process.default.versions !== "undefined" && typeof import_process.default.versions.node !== "undefined"; - } - exports2.isNode = isNode2; - function isBrowser() { - return !isReactNative() && !isNode2(); - } - exports2.isBrowser = isBrowser; - } -}); - -// node_modules/@walletconnect/environment/dist/cjs/index.js -var require_cjs5 = __commonJS({ - "node_modules/@walletconnect/environment/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_crypto2(), exports2); - tslib_1.__exportStar(require_env(), exports2); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js -var env_exports = {}; -__export(env_exports, { - isNodeJs: () => isNodeJs -}); -var import_environment, isNodeJs; -var init_env = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js"() { - init_shim(); - import_environment = __toESM(require_cjs5()); - __reExport(env_exports, __toESM(require_cjs5())); - isNodeJs = import_environment.isNode; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js -function payloadId(entropy = 3) { - const date = Date.now() * Math.pow(10, entropy); - const extra = Math.floor(Math.random() * Math.pow(10, entropy)); - return date + extra; -} -function getBigIntRpcId(entropy = 6) { - return BigInt(payloadId(entropy)); -} -function formatJsonRpcRequest(method, params, id) { - return { - id: id || payloadId(), - jsonrpc: "2.0", - method, - params - }; -} -function formatJsonRpcResult(id, result) { - return { - id, - jsonrpc: "2.0", - result - }; -} -function formatJsonRpcError(id, error, data) { - return { - id, - jsonrpc: "2.0", - error: formatErrorMessage(error, data) - }; -} -function formatErrorMessage(error, data) { - if (typeof error === "undefined") { - return getError(INTERNAL_ERROR); - } - if (typeof error === "string") { - error = Object.assign(Object.assign({}, getError(SERVER_ERROR)), { message: error }); - } - if (typeof data !== "undefined") { - error.data = data; - } - if (isReservedErrorCode(error.code)) { - error = getErrorByCode(error.code); - } - return error; -} -var init_format = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js"() { - init_shim(); - init_error(); - init_constants2(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js -function isValidRoute(route) { - if (route.includes("*")) { - return isValidWildcardRoute(route); - } - if (/\W/g.test(route)) { - return false; - } - return true; -} -function isValidDefaultRoute(route) { - return route === "*"; -} -function isValidWildcardRoute(route) { - if (isValidDefaultRoute(route)) { - return true; - } - if (!route.includes("*")) { - return false; - } - if (route.split("*").length !== 2) { - return false; - } - if (route.split("*").filter((x3) => x3.trim() === "").length !== 1) { - return false; - } - return true; -} -function isValidLeadingWildcardRoute(route) { - return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[0].trim(); -} -function isValidTrailingWildcardRoute(route) { - return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[1].trim(); -} -var init_routing = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js -var init_jsonrpc = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js -var IEvents2; -var init_misc = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js"() { - init_shim(); - IEvents2 = class { - }; - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js -var IJsonRpcConnection, IBaseJsonRpcProvider, IJsonRpcProvider; -var init_provider = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js"() { - init_shim(); - init_misc(); - IJsonRpcConnection = class extends IEvents2 { - constructor(opts) { - super(); - } - }; - IBaseJsonRpcProvider = class extends IEvents2 { - constructor() { - super(); - } - }; - IJsonRpcProvider = class extends IBaseJsonRpcProvider { - constructor(connection) { - super(); - } - }; - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js -var init_validator = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js -var init_esm4 = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js"() { - init_shim(); - init_jsonrpc(); - init_misc(); - init_provider(); - init_validator(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js -var init_types2 = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js"() { - init_shim(); - init_esm4(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js -function getUrlProtocol(url) { - const matches = url.match(new RegExp(/^\w+:/, "gi")); - if (!matches || !matches.length) - return; - return matches[0]; -} -function matchRegexProtocol(url, regex) { - const protocol = getUrlProtocol(url); - if (typeof protocol === "undefined") - return false; - return new RegExp(regex).test(protocol); -} -function isHttpUrl(url) { - return matchRegexProtocol(url, HTTP_REGEX); -} -function isWsUrl(url) { - return matchRegexProtocol(url, WS_REGEX); -} -function isLocalhostUrl(url) { - return new RegExp("wss?://localhost(:d{2,5})?").test(url); -} -var HTTP_REGEX, WS_REGEX; -var init_url = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js"() { - init_shim(); - HTTP_REGEX = "^https?:"; - WS_REGEX = "^wss?:"; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js -function isJsonRpcPayload(payload) { - return typeof payload === "object" && "id" in payload && "jsonrpc" in payload && payload.jsonrpc === "2.0"; -} -function isJsonRpcRequest(payload) { - return isJsonRpcPayload(payload) && "method" in payload; -} -function isJsonRpcResponse(payload) { - return isJsonRpcPayload(payload) && (isJsonRpcResult(payload) || isJsonRpcError(payload)); -} -function isJsonRpcResult(payload) { - return "result" in payload; -} -function isJsonRpcError(payload) { - return "error" in payload; -} -function isJsonRpcValidationInvalid(validation) { - return "error" in validation && validation.valid === false; -} -var init_validators = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js -var esm_exports4 = {}; -__export(esm_exports4, { - DEFAULT_ERROR: () => DEFAULT_ERROR, - IBaseJsonRpcProvider: () => IBaseJsonRpcProvider, - IEvents: () => IEvents2, - IJsonRpcConnection: () => IJsonRpcConnection, - IJsonRpcProvider: () => IJsonRpcProvider, - INTERNAL_ERROR: () => INTERNAL_ERROR, - INVALID_PARAMS: () => INVALID_PARAMS, - INVALID_REQUEST: () => INVALID_REQUEST, - METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, - PARSE_ERROR: () => PARSE_ERROR, - RESERVED_ERROR_CODES: () => RESERVED_ERROR_CODES, - SERVER_ERROR: () => SERVER_ERROR, - SERVER_ERROR_CODE_RANGE: () => SERVER_ERROR_CODE_RANGE, - STANDARD_ERROR_MAP: () => STANDARD_ERROR_MAP, - formatErrorMessage: () => formatErrorMessage, - formatJsonRpcError: () => formatJsonRpcError, - formatJsonRpcRequest: () => formatJsonRpcRequest, - formatJsonRpcResult: () => formatJsonRpcResult, - getBigIntRpcId: () => getBigIntRpcId, - getError: () => getError, - getErrorByCode: () => getErrorByCode, - isHttpUrl: () => isHttpUrl, - isJsonRpcError: () => isJsonRpcError, - isJsonRpcPayload: () => isJsonRpcPayload, - isJsonRpcRequest: () => isJsonRpcRequest, - isJsonRpcResponse: () => isJsonRpcResponse, - isJsonRpcResult: () => isJsonRpcResult, - isJsonRpcValidationInvalid: () => isJsonRpcValidationInvalid, - isLocalhostUrl: () => isLocalhostUrl, - isNodeJs: () => isNodeJs, - isReservedErrorCode: () => isReservedErrorCode, - isServerErrorCode: () => isServerErrorCode, - isValidDefaultRoute: () => isValidDefaultRoute, - isValidErrorCode: () => isValidErrorCode, - isValidLeadingWildcardRoute: () => isValidLeadingWildcardRoute, - isValidRoute: () => isValidRoute, - isValidTrailingWildcardRoute: () => isValidTrailingWildcardRoute, - isValidWildcardRoute: () => isValidWildcardRoute, - isWsUrl: () => isWsUrl, - parseConnectionError: () => parseConnectionError, - payloadId: () => payloadId, - validateJsonRpcError: () => validateJsonRpcError -}); -var init_esm5 = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js"() { - init_shim(); - init_constants2(); - init_error(); - init_env(); - __reExport(esm_exports4, env_exports); - init_format(); - init_routing(); - init_types2(); - init_url(); - init_validators(); - } -}); - -// node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js -var import_events, JsonRpcProvider, provider_default; -var init_provider2 = __esm({ - "node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js"() { - init_shim(); - import_events = __toESM(require_events()); - init_esm5(); - JsonRpcProvider = class extends IJsonRpcProvider { - constructor(connection) { - super(connection); - this.events = new import_events.EventEmitter(); - this.hasRegisteredEventListeners = false; - this.connection = this.setConnection(connection); - if (this.connection.connected) { - this.registerEventListeners(); - } - } - async connect(connection = this.connection) { - await this.open(connection); - } - async disconnect() { - await this.close(); - } - on(event, listener) { - this.events.on(event, listener); - } - once(event, listener) { - this.events.once(event, listener); - } - off(event, listener) { - this.events.off(event, listener); - } - removeListener(event, listener) { - this.events.removeListener(event, listener); - } - async request(request, context) { - return this.requestStrict(formatJsonRpcRequest(request.method, request.params || [], request.id || getBigIntRpcId().toString()), context); - } - async requestStrict(request, context) { - return new Promise(async (resolve, reject) => { - if (!this.connection.connected) { - try { - await this.open(); - } catch (e2) { - reject(e2); - } - } - this.events.on(`${request.id}`, (response) => { - if (isJsonRpcError(response)) { - reject(response.error); - } else { - resolve(response.result); - } - }); - try { - await this.connection.send(request, context); - } catch (e2) { - reject(e2); - } - }); - } - setConnection(connection = this.connection) { - return connection; - } - onPayload(payload) { - this.events.emit("payload", payload); - if (isJsonRpcResponse(payload)) { - this.events.emit(`${payload.id}`, payload); - } else { - this.events.emit("message", { - type: payload.method, - data: payload.params - }); - } - } - onClose(event) { - if (event && event.code === 3e3) { - this.events.emit("error", new Error(`WebSocket connection closed abnormally with code: ${event.code} ${event.reason ? `(${event.reason})` : ""}`)); - } - this.events.emit("disconnect"); - } - async open(connection = this.connection) { - if (this.connection === connection && this.connection.connected) - return; - if (this.connection.connected) - this.close(); - if (typeof connection === "string") { - await this.connection.open(connection); - connection = this.connection; - } - this.connection = this.setConnection(connection); - await this.connection.open(); - this.registerEventListeners(); - this.events.emit("connect"); - } - async close() { - await this.connection.close(); - } - registerEventListeners() { - if (this.hasRegisteredEventListeners) - return; - this.connection.on("payload", (payload) => this.onPayload(payload)); - this.connection.on("close", (event) => this.onClose(event)); - this.connection.on("error", (error) => this.events.emit("error", error)); - this.connection.on("register_error", (error) => this.onClose()); - this.hasRegisteredEventListeners = true; - } - }; - provider_default = JsonRpcProvider; - } -}); - -// node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js -var esm_exports5 = {}; -__export(esm_exports5, { - JsonRpcProvider: () => JsonRpcProvider, - default: () => esm_default -}); -var esm_default; -var init_esm6 = __esm({ - "node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js"() { - init_shim(); - init_provider2(); - init_provider2(); - esm_default = provider_default; - } -}); - -// node_modules/ws/browser.js -var require_browser5 = __commonJS({ - "node_modules/ws/browser.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function() { - throw new Error( - "ws does not work in the browser. Browser clients must use the native WebSocket object" - ); - }; - } -}); - -// node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js -var index_es_exports4 = {}; -__export(index_es_exports4, { - WsConnection: () => f3, - default: () => f3 -}); -var import_events2, w3, b3, a2, h4, S3, f3; -var init_index_es4 = __esm({ - "node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js"() { - init_shim(); - import_events2 = __toESM(require_events()); - init_esm(); - init_esm5(); - w3 = () => typeof WebSocket < "u" ? WebSocket : typeof global < "u" && typeof global.WebSocket < "u" ? global.WebSocket : typeof window < "u" && typeof window.WebSocket < "u" ? window.WebSocket : typeof self < "u" && typeof self.WebSocket < "u" ? self.WebSocket : require_browser5(); - b3 = () => typeof WebSocket < "u" || typeof global < "u" && typeof global.WebSocket < "u" || typeof window < "u" && typeof window.WebSocket < "u" || typeof self < "u" && typeof self.WebSocket < "u"; - a2 = (c4) => c4.split("?")[0]; - h4 = 10; - S3 = w3(); - f3 = class { - constructor(e2) { - if (this.url = e2, this.events = new import_events2.EventEmitter(), this.registering = false, !isWsUrl(e2)) - throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); - this.url = e2; - } - get connected() { - return typeof this.socket < "u"; - } - get connecting() { - return this.registering; - } - on(e2, t) { - this.events.on(e2, t); - } - once(e2, t) { - this.events.once(e2, t); - } - off(e2, t) { - this.events.off(e2, t); - } - removeListener(e2, t) { - this.events.removeListener(e2, t); - } - async open(e2 = this.url) { - await this.register(e2); - } - async close() { - return new Promise((e2, t) => { - if (typeof this.socket > "u") { - t(new Error("Connection already closed")); - return; - } - this.socket.onclose = (n3) => { - this.onClose(n3), e2(); - }, this.socket.close(); - }); - } - async send(e2) { - typeof this.socket > "u" && (this.socket = await this.register()); - try { - this.socket.send(safeJsonStringify(e2)); - } catch (t) { - this.onError(e2.id, t); - } - } - register(e2 = this.url) { - if (!isWsUrl(e2)) - throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); - if (this.registering) { - const t = this.events.getMaxListeners(); - return (this.events.listenerCount("register_error") >= t || this.events.listenerCount("open") >= t) && this.events.setMaxListeners(t + 1), new Promise((n3, o2) => { - this.events.once("register_error", (s2) => { - this.resetMaxListeners(), o2(s2); - }), this.events.once("open", () => { - if (this.resetMaxListeners(), typeof this.socket > "u") - return o2(new Error("WebSocket connection is missing or invalid")); - n3(this.socket); - }); - }); - } - return this.url = e2, this.registering = true, new Promise((t, n3) => { - const o2 = new URLSearchParams(e2).get("origin"), s2 = (0, esm_exports4.isReactNative)() ? { headers: { origin: o2 } } : { rejectUnauthorized: !isLocalhostUrl(e2) }, i2 = new S3(e2, [], s2); - b3() ? i2.onerror = (r) => { - const l4 = r; - n3(this.emitError(l4.error)); - } : i2.on("error", (r) => { - n3(this.emitError(r)); - }), i2.onopen = () => { - this.onOpen(i2), t(i2); - }; - }); - } - onOpen(e2) { - e2.onmessage = (t) => this.onPayload(t), e2.onclose = (t) => this.onClose(t), this.socket = e2, this.registering = false, this.events.emit("open"); - } - onClose(e2) { - this.socket = void 0, this.registering = false, this.events.emit("close", e2); - } - onPayload(e2) { - if (typeof e2.data > "u") - return; - const t = typeof e2.data == "string" ? safeJsonParse(e2.data) : e2.data; - this.events.emit("payload", t); - } - onError(e2, t) { - const n3 = this.parseError(t), o2 = n3.message || n3.toString(), s2 = formatJsonRpcError(e2, o2); - this.events.emit("payload", s2); - } - parseError(e2, t = this.url) { - return parseConnectionError(e2, a2(t), "WS"); - } - resetMaxListeners() { - this.events.getMaxListeners() > h4 && this.events.setMaxListeners(h4); - } - emitError(e2) { - const t = this.parseError(new Error(e2?.message || `WebSocket connection failed for host: ${a2(this.url)}`)); - return this.events.emit("register_error", t), t; - } - }; - } -}); - -// node_modules/lodash.isequal/index.js -var require_lodash = __commonJS({ - "node_modules/lodash.isequal/index.js"(exports2, module2) { - init_shim(); - var LARGE_ARRAY_SIZE = 200; - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - var COMPARE_PARTIAL_FLAG = 1; - var COMPARE_UNORDERED_FLAG = 2; - var MAX_SAFE_INTEGER2 = 9007199254740991; - var argsTag = "[object Arguments]"; - var arrayTag = "[object Array]"; - var asyncTag = "[object AsyncFunction]"; - var boolTag = "[object Boolean]"; - var dateTag = "[object Date]"; - var errorTag = "[object Error]"; - var funcTag = "[object Function]"; - var genTag = "[object GeneratorFunction]"; - var mapTag = "[object Map]"; - var numberTag = "[object Number]"; - var nullTag = "[object Null]"; - var objectTag = "[object Object]"; - var promiseTag = "[object Promise]"; - var proxyTag = "[object Proxy]"; - var regexpTag = "[object RegExp]"; - var setTag = "[object Set]"; - var stringTag = "[object String]"; - var symbolTag = "[object Symbol]"; - var undefinedTag = "[object Undefined]"; - var weakMapTag = "[object WeakMap]"; - var arrayBufferTag = "[object ArrayBuffer]"; - var dataViewTag = "[object DataView]"; - var float32Tag = "[object Float32Array]"; - var float64Tag = "[object Float64Array]"; - var int8Tag = "[object Int8Array]"; - var int16Tag = "[object Int16Array]"; - var int32Tag = "[object Int32Array]"; - var uint8Tag = "[object Uint8Array]"; - var uint8ClampedTag = "[object Uint8ClampedArray]"; - var uint16Tag = "[object Uint16Array]"; - var uint32Tag = "[object Uint32Array]"; - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - var reIsHostCtor = /^\[object .+?Constructor\]$/; - var reIsUint = /^(?:0|[1-9]\d*)$/; - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; - var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = function() { - try { - return freeProcess && freeProcess.binding && freeProcess.binding("util"); - } catch (e2) { - } - }(); - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - function arrayFilter(array, predicate) { - var index = -1, length2 = array == null ? 0 : array.length, resIndex = 0, result = []; - while (++index < length2) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - function arrayPush(array, values) { - var index = -1, length2 = values.length, offset = array.length; - while (++index < length2) { - array[offset + index] = values[index]; - } - return array; - } - function arraySome(array, predicate) { - var index = -1, length2 = array == null ? 0 : array.length; - while (++index < length2) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - function baseTimes(n3, iteratee) { - var index = -1, result = Array(n3); - while (++index < n3) { - result[index] = iteratee(index); - } - return result; - } - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - function cacheHas(cache, key) { - return cache.has(key); - } - function getValue(object, key) { - return object == null ? void 0 : object[key]; - } - function mapToArray(map) { - var index = -1, result = Array(map.size); - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - function setToArray(set2) { - var index = -1, result = Array(set2.size); - set2.forEach(function(value) { - result[++index] = value; - }); - return result; - } - var arrayProto = Array.prototype; - var funcProto = Function.prototype; - var objectProto = Object.prototype; - var coreJsData = root["__core-js_shared__"]; - var funcToString = funcProto.toString; - var hasOwnProperty = objectProto.hasOwnProperty; - var maskSrcKey = function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); - return uid ? "Symbol(src)_1." + uid : ""; - }(); - var nativeObjectToString = objectProto.toString; - var reIsNative = RegExp( - "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" - ); - var Buffer2 = moduleExports ? root.Buffer : void 0; - var Symbol2 = root.Symbol; - var Uint8Array2 = root.Uint8Array; - var propertyIsEnumerable = objectProto.propertyIsEnumerable; - var splice = arrayProto.splice; - var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; - var nativeGetSymbols = Object.getOwnPropertySymbols; - var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; - var nativeKeys = overArg(Object.keys, Object); - var DataView2 = getNative(root, "DataView"); - var Map2 = getNative(root, "Map"); - var Promise2 = getNative(root, "Promise"); - var Set2 = getNative(root, "Set"); - var WeakMap2 = getNative(root, "WeakMap"); - var nativeCreate = getNative(Object, "create"); - var dataViewCtorString = toSource(DataView2); - var mapCtorString = toSource(Map2); - var promiseCtorString = toSource(Promise2); - var setCtorString = toSource(Set2); - var weakMapCtorString = toSource(WeakMap2); - var symbolProto = Symbol2 ? Symbol2.prototype : void 0; - var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; - function Hash(entries) { - var index = -1, length2 = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length2) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? void 0 : result; - } - return hasOwnProperty.call(data, key) ? data[key] : void 0; - } - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); - } - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; - return this; - } - Hash.prototype.clear = hashClear; - Hash.prototype["delete"] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - function ListCache(entries) { - var index = -1, length2 = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length2) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - function listCacheDelete(key) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - function listCacheGet(key) { - var data = this.__data__, index = assocIndexOf(data, key); - return index < 0 ? void 0 : data[index][1]; - } - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - function listCacheSet(key, value) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - ListCache.prototype.clear = listCacheClear; - ListCache.prototype["delete"] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - function MapCache(entries) { - var index = -1, length2 = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length2) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function mapCacheClear() { - this.size = 0; - this.__data__ = { - "hash": new Hash(), - "map": new (Map2 || ListCache)(), - "string": new Hash() - }; - } - function mapCacheDelete(key) { - var result = getMapData(this, key)["delete"](key); - this.size -= result ? 1 : 0; - return result; - } - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - function mapCacheSet(key, value) { - var data = getMapData(this, key), size = data.size; - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype["delete"] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - function SetCache(values) { - var index = -1, length2 = values == null ? 0 : values.length; - this.__data__ = new MapCache(); - while (++index < length2) { - this.add(values[index]); - } - } - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - function setCacheHas(value) { - return this.__data__.has(value); - } - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - function stackClear() { - this.__data__ = new ListCache(); - this.size = 0; - } - function stackDelete(key) { - var data = this.__data__, result = data["delete"](key); - this.size = data.size; - return result; - } - function stackGet(key) { - return this.__data__.get(key); - } - function stackHas(key) { - return this.__data__.has(key); - } - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - Stack.prototype.clear = stackClear; - Stack.prototype["delete"] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length2 = result.length; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. - (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. - isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. - isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. - isIndex(key, length2)))) { - result.push(key); - } - } - return result; - } - function assocIndexOf(array, key) { - var length2 = array.length; - while (length2--) { - if (eq(array[length2][0], key)) { - return length2; - } - } - return -1; - } - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - function baseGetTag(value) { - if (value == null) { - return value === void 0 ? undefinedTag : nullTag; - } - return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); - } - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack()); - return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack()); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack()); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - function baseIsTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != "constructor") { - result.push(key); - } - } - return result; - } - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0; - stack.set(array, other); - stack.set(other, array); - while (++index < arrLength) { - var arrValue = array[index], othValue = other[index]; - if (customizer) { - var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== void 0) { - if (compared) { - continue; - } - result = false; - break; - } - if (seen) { - if (!arraySome(other, function(othValue2, othIndex) { - if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - result = false; - break; - } - } - stack["delete"](array); - stack["delete"](other); - return result; - } - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { - return false; - } - object = object.buffer; - other = other.buffer; - case arrayBufferTag: - if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { - return false; - } - return true; - case boolTag: - case dateTag: - case numberTag: - return eq(+object, +other); - case errorTag: - return object.name == other.name && object.message == other.message; - case regexpTag: - case stringTag: - return object == other + ""; - case mapTag: - var convert = mapToArray; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - if (object.size != other.size && !isPartial) { - return false; - } - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack["delete"](object); - return result; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], othValue = other[key]; - if (customizer) { - var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); - } - if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { - result = false; - break; - } - skipCtor || (skipCtor = key == "constructor"); - } - if (result && !skipCtor) { - var objCtor = object.constructor, othCtor = other.constructor; - if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { - result = false; - } - } - stack["delete"](object); - stack["delete"](other); - return result; - } - function getAllKeys(object) { - return baseGetAllKeys(object, keys2, getSymbols); - } - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; - } - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : void 0; - } - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; - try { - value[symToStringTag] = void 0; - var unmasked = true; - } catch (e2) { - } - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - var getTag = baseGetTag; - if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) { - getTag = function(value) { - var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: - return dataViewTag; - case mapCtorString: - return mapTag; - case promiseCtorString: - return promiseTag; - case setCtorString: - return setTag; - case weakMapCtorString: - return weakMapTag; - } - } - return result; - }; - } - function isIndex(value, length2) { - length2 = length2 == null ? MAX_SAFE_INTEGER2 : length2; - return !!length2 && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length2); - } - function isKeyable(value) { - var type = typeof value; - return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; - } - function isMasked(func) { - return !!maskSrcKey && maskSrcKey in func; - } - function isPrototype(value) { - var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; - return value === proto; - } - function objectToString(value) { - return nativeObjectToString.call(value); - } - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e2) { - } - try { - return func + ""; - } catch (e2) { - } - } - return ""; - } - function eq(value, other) { - return value === other || value !== value && other !== other; - } - var isArguments = baseIsArguments(/* @__PURE__ */ function() { - return arguments; - }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); - }; - var isArray = Array.isArray; - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - var isBuffer = nativeIsBuffer || stubFalse; - function isEqual(value, other) { - return baseIsEqual(value, other); - } - function isFunction(value) { - if (!isObject(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - function isLength(value) { - return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; - } - function isObject(value) { - var type = typeof value; - return value != null && (type == "object" || type == "function"); - } - function isObjectLike(value) { - return value != null && typeof value == "object"; - } - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - function keys2(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - function stubArray() { - return []; - } - function stubFalse() { - return false; - } - module2.exports = isEqual; - } -}); - -// node_modules/unfetch/dist/unfetch.js -var require_unfetch = __commonJS({ - "node_modules/unfetch/dist/unfetch.js"(exports2, module2) { - init_shim(); - module2.exports = function(e2, n3) { - return n3 = n3 || {}, new Promise(function(t, r) { - var s2 = new XMLHttpRequest(), o2 = [], u3 = [], i2 = {}, a3 = function() { - return { ok: 2 == (s2.status / 100 | 0), statusText: s2.statusText, status: s2.status, url: s2.responseURL, text: function() { - return Promise.resolve(s2.responseText); - }, json: function() { - return Promise.resolve(s2.responseText).then(JSON.parse); - }, blob: function() { - return Promise.resolve(new Blob([s2.response])); - }, clone: a3, headers: { keys: function() { - return o2; - }, entries: function() { - return u3; - }, get: function(e3) { - return i2[e3.toLowerCase()]; - }, has: function(e3) { - return e3.toLowerCase() in i2; - } } }; - }; - for (var l4 in s2.open(n3.method || "get", e2, true), s2.onload = function() { - s2.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function(e3, n4, t2) { - o2.push(n4 = n4.toLowerCase()), u3.push([n4, t2]), i2[n4] = i2[n4] ? i2[n4] + "," + t2 : t2; - }), t(a3()); - }, s2.onerror = r, s2.withCredentials = "include" == n3.credentials, n3.headers) - s2.setRequestHeader(l4, n3.headers[l4]); - s2.send(n3.body || null); - }); - }; - } -}); - -// node_modules/isomorphic-unfetch/browser.js -var require_browser6 = __commonJS({ - "node_modules/isomorphic-unfetch/browser.js"(exports2, module2) { - init_shim(); - module2.exports = self.fetch || (self.fetch = require_unfetch().default || require_unfetch()); - } -}); - -// node_modules/@walletconnect/core/dist/index.cjs.js -var require_index_cjs3 = __commonJS({ - "node_modules/@walletconnect/core/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var z3 = require_events(); - var It = (init_index_es(), __toCommonJS(index_es_exports)); - var $ = require_cjs2(); - var g3 = (init_index_es2(), __toCommonJS(index_es_exports2)); - var x3 = require_index_cjs(); - var oe = (init_esm(), __toCommonJS(esm_exports)); - var Rt = (init_esm3(), __toCommonJS(esm_exports3)); - var a3 = require_index_cjs2(); - var _t = (init_src2(), __toCommonJS(src_exports)); - var l4 = require_cjs(); - var Ct = (init_esm6(), __toCommonJS(esm_exports5)); - var f4 = (init_esm5(), __toCommonJS(esm_exports4)); - var Tt = (init_index_es4(), __toCommonJS(index_es_exports4)); - var St = require_lodash(); - var Ot = require_browser6(); - function k4(n3) { - return n3 && typeof n3 == "object" && "default" in n3 ? n3 : { default: n3 }; - } - function Pt(n3) { - if (n3 && n3.__esModule) - return n3; - var e2 = /* @__PURE__ */ Object.create(null); - return n3 && Object.keys(n3).forEach(function(t) { - if (t !== "default") { - var i2 = Object.getOwnPropertyDescriptor(n3, t); - Object.defineProperty(e2, t, i2.get ? i2 : { enumerable: true, get: function() { - return n3[t]; - } }); - } - }), e2.default = n3, Object.freeze(e2); - } - var At = k4(z3); - var xt = k4(It); - var j2 = Pt(Rt); - var Nt = k4(Tt); - var Lt = k4(St); - var Ut = k4(Ot); - function zt(n3, e2) { - if (n3.length >= 255) - throw new TypeError("Alphabet too long"); - for (var t = new Uint8Array(256), i2 = 0; i2 < t.length; i2++) - t[i2] = 255; - for (var s2 = 0; s2 < n3.length; s2++) { - var r = n3.charAt(s2), o2 = r.charCodeAt(0); - if (t[o2] !== 255) - throw new TypeError(r + " is ambiguous"); - t[o2] = s2; - } - var h5 = n3.length, c4 = n3.charAt(0), u3 = Math.log(h5) / Math.log(256), p3 = Math.log(256) / Math.log(h5); - function D2(d3) { - if (d3 instanceof Uint8Array || (ArrayBuffer.isView(d3) ? d3 = new Uint8Array(d3.buffer, d3.byteOffset, d3.byteLength) : Array.isArray(d3) && (d3 = Uint8Array.from(d3))), !(d3 instanceof Uint8Array)) - throw new TypeError("Expected Uint8Array"); - if (d3.length === 0) - return ""; - for (var y4 = 0, C3 = 0, E4 = 0, O3 = d3.length; E4 !== O3 && d3[E4] === 0; ) - E4++, y4++; - for (var P2 = (O3 - E4) * p3 + 1 >>> 0, v2 = new Uint8Array(P2); E4 !== O3; ) { - for (var A2 = d3[E4], U2 = 0, T2 = P2 - 1; (A2 !== 0 || U2 < C3) && T2 !== -1; T2--, U2++) - A2 += 256 * v2[T2] >>> 0, v2[T2] = A2 % h5 >>> 0, A2 = A2 / h5 >>> 0; - if (A2 !== 0) - throw new Error("Non-zero carry"); - C3 = U2, E4++; - } - for (var N10 = P2 - C3; N10 !== P2 && v2[N10] === 0; ) - N10++; - for (var Y = c4.repeat(y4); N10 < P2; ++N10) - Y += n3.charAt(v2[N10]); - return Y; - } - function b4(d3) { - if (typeof d3 != "string") - throw new TypeError("Expected String"); - if (d3.length === 0) - return new Uint8Array(); - var y4 = 0; - if (d3[y4] !== " ") { - for (var C3 = 0, E4 = 0; d3[y4] === c4; ) - C3++, y4++; - for (var O3 = (d3.length - y4) * u3 + 1 >>> 0, P2 = new Uint8Array(O3); d3[y4]; ) { - var v2 = t[d3.charCodeAt(y4)]; - if (v2 === 255) - return; - for (var A2 = 0, U2 = O3 - 1; (v2 !== 0 || A2 < E4) && U2 !== -1; U2--, A2++) - v2 += h5 * P2[U2] >>> 0, P2[U2] = v2 % 256 >>> 0, v2 = v2 / 256 >>> 0; - if (v2 !== 0) - throw new Error("Non-zero carry"); - E4 = A2, y4++; - } - if (d3[y4] !== " ") { - for (var T2 = O3 - E4; T2 !== O3 && P2[T2] === 0; ) - T2++; - for (var N10 = new Uint8Array(C3 + (O3 - T2)), Y = C3; T2 !== O3; ) - N10[Y++] = P2[T2++]; - return N10; - } - } - } - function F(d3) { - var y4 = b4(d3); - if (y4) - return y4; - throw new Error(`Non-${e2} character`); - } - return { encode: D2, decodeUnsafe: b4, decode: F }; - } - var Ft = zt; - var Mt = Ft; - var ae = (n3) => { - if (n3 instanceof Uint8Array && n3.constructor.name === "Uint8Array") - return n3; - if (n3 instanceof ArrayBuffer) - return new Uint8Array(n3); - if (ArrayBuffer.isView(n3)) - return new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength); - throw new Error("Unknown type, must be binary type"); - }; - var Bt = (n3) => new TextEncoder().encode(n3); - var $t = (n3) => new TextDecoder().decode(n3); - var kt = class { - constructor(e2, t, i2) { - this.name = e2, this.prefix = t, this.baseEncode = i2; - } - encode(e2) { - if (e2 instanceof Uint8Array) - return `${this.prefix}${this.baseEncode(e2)}`; - throw Error("Unknown type, must be binary type"); - } - }; - var Vt = class { - constructor(e2, t, i2) { - if (this.name = e2, this.prefix = t, t.codePointAt(0) === void 0) - throw new Error("Invalid prefix character"); - this.prefixCodePoint = t.codePointAt(0), this.baseDecode = i2; - } - decode(e2) { - if (typeof e2 == "string") { - if (e2.codePointAt(0) !== this.prefixCodePoint) - throw Error(`Unable to decode multibase string ${JSON.stringify(e2)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); - return this.baseDecode(e2.slice(this.prefix.length)); - } else - throw Error("Can only multibase decode strings"); - } - or(e2) { - return he(this, e2); - } - }; - var Kt = class { - constructor(e2) { - this.decoders = e2; - } - or(e2) { - return he(this, e2); - } - decode(e2) { - const t = e2[0], i2 = this.decoders[t]; - if (i2) - return i2.decode(e2); - throw RangeError(`Unable to decode multibase string ${JSON.stringify(e2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); - } - }; - var he = (n3, e2) => new Kt({ ...n3.decoders || { [n3.prefix]: n3 }, ...e2.decoders || { [e2.prefix]: e2 } }); - var qt = class { - constructor(e2, t, i2, s2) { - this.name = e2, this.prefix = t, this.baseEncode = i2, this.baseDecode = s2, this.encoder = new kt(e2, t, i2), this.decoder = new Vt(e2, t, s2); - } - encode(e2) { - return this.encoder.encode(e2); - } - decode(e2) { - return this.decoder.decode(e2); - } - }; - var G = ({ name: n3, prefix: e2, encode: t, decode: i2 }) => new qt(n3, e2, t, i2); - var V = ({ prefix: n3, name: e2, alphabet: t }) => { - const { encode: i2, decode: s2 } = Mt(t, e2); - return G({ prefix: n3, name: e2, encode: i2, decode: (r) => ae(s2(r)) }); - }; - var Yt = (n3, e2, t, i2) => { - const s2 = {}; - for (let p3 = 0; p3 < e2.length; ++p3) - s2[e2[p3]] = p3; - let r = n3.length; - for (; n3[r - 1] === "="; ) - --r; - const o2 = new Uint8Array(r * t / 8 | 0); - let h5 = 0, c4 = 0, u3 = 0; - for (let p3 = 0; p3 < r; ++p3) { - const D2 = s2[n3[p3]]; - if (D2 === void 0) - throw new SyntaxError(`Non-${i2} character`); - c4 = c4 << t | D2, h5 += t, h5 >= 8 && (h5 -= 8, o2[u3++] = 255 & c4 >> h5); - } - if (h5 >= t || 255 & c4 << 8 - h5) - throw new SyntaxError("Unexpected end of data"); - return o2; - }; - var jt = (n3, e2, t) => { - const i2 = e2[e2.length - 1] === "=", s2 = (1 << t) - 1; - let r = "", o2 = 0, h5 = 0; - for (let c4 = 0; c4 < n3.length; ++c4) - for (h5 = h5 << 8 | n3[c4], o2 += 8; o2 > t; ) - o2 -= t, r += e2[s2 & h5 >> o2]; - if (o2 && (r += e2[s2 & h5 << t - o2]), i2) - for (; r.length * t & 7; ) - r += "="; - return r; - }; - var m3 = ({ name: n3, prefix: e2, bitsPerChar: t, alphabet: i2 }) => G({ prefix: e2, name: n3, encode(s2) { - return jt(s2, i2, t); - }, decode(s2) { - return Yt(s2, i2, t, n3); - } }); - var Gt = G({ prefix: "\0", name: "identity", encode: (n3) => $t(n3), decode: (n3) => Bt(n3) }); - var Ht = Object.freeze({ __proto__: null, identity: Gt }); - var Xt = m3({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); - var Jt = Object.freeze({ __proto__: null, base2: Xt }); - var Wt = m3({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); - var Qt = Object.freeze({ __proto__: null, base8: Wt }); - var Zt = V({ prefix: "9", name: "base10", alphabet: "0123456789" }); - var ei = Object.freeze({ __proto__: null, base10: Zt }); - var ti = m3({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); - var ii = m3({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); - var si = Object.freeze({ __proto__: null, base16: ti, base16upper: ii }); - var ri = m3({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); - var ni = m3({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); - var oi = m3({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); - var ai = m3({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); - var hi = m3({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); - var ci = m3({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); - var li = m3({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); - var ui = m3({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); - var gi = m3({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); - var di = Object.freeze({ __proto__: null, base32: ri, base32upper: ni, base32pad: oi, base32padupper: ai, base32hex: hi, base32hexupper: ci, base32hexpad: li, base32hexpadupper: ui, base32z: gi }); - var pi = V({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); - var Di = V({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); - var yi = Object.freeze({ __proto__: null, base36: pi, base36upper: Di }); - var Ei = V({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); - var mi = V({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); - var bi = Object.freeze({ __proto__: null, base58btc: Ei, base58flickr: mi }); - var fi = m3({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); - var wi = m3({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); - var vi = m3({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); - var Ii = m3({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); - var Ri = Object.freeze({ __proto__: null, base64: fi, base64pad: wi, base64url: vi, base64urlpad: Ii }); - var ce = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); - var _i = ce.reduce((n3, e2, t) => (n3[t] = e2, n3), []); - var Ci = ce.reduce((n3, e2, t) => (n3[e2.codePointAt(0)] = t, n3), []); - function Ti(n3) { - return n3.reduce((e2, t) => (e2 += _i[t], e2), ""); - } - function Si(n3) { - const e2 = []; - for (const t of n3) { - const i2 = Ci[t.codePointAt(0)]; - if (i2 === void 0) - throw new Error(`Non-base256emoji character: ${t}`); - e2.push(i2); - } - return new Uint8Array(e2); - } - var Oi = G({ prefix: "\u{1F680}", name: "base256emoji", encode: Ti, decode: Si }); - var Pi = Object.freeze({ __proto__: null, base256emoji: Oi }); - var Ai = ue; - var le = 128; - var xi = 127; - var Ni = ~xi; - var Li = Math.pow(2, 31); - function ue(n3, e2, t) { - e2 = e2 || [], t = t || 0; - for (var i2 = t; n3 >= Li; ) - e2[t++] = n3 & 255 | le, n3 /= 128; - for (; n3 & Ni; ) - e2[t++] = n3 & 255 | le, n3 >>>= 7; - return e2[t] = n3 | 0, ue.bytes = t - i2 + 1, e2; - } - var Ui = Q; - var zi = 128; - var ge = 127; - function Q(n3, i2) { - var t = 0, i2 = i2 || 0, s2 = 0, r = i2, o2, h5 = n3.length; - do { - if (r >= h5) - throw Q.bytes = 0, new RangeError("Could not decode varint"); - o2 = n3[r++], t += s2 < 28 ? (o2 & ge) << s2 : (o2 & ge) * Math.pow(2, s2), s2 += 7; - } while (o2 >= zi); - return Q.bytes = r - i2, t; - } - var Fi = Math.pow(2, 7); - var Mi = Math.pow(2, 14); - var Bi = Math.pow(2, 21); - var $i = Math.pow(2, 28); - var ki = Math.pow(2, 35); - var Vi = Math.pow(2, 42); - var Ki = Math.pow(2, 49); - var qi = Math.pow(2, 56); - var Yi = Math.pow(2, 63); - var ji = function(n3) { - return n3 < Fi ? 1 : n3 < Mi ? 2 : n3 < Bi ? 3 : n3 < $i ? 4 : n3 < ki ? 5 : n3 < Vi ? 6 : n3 < Ki ? 7 : n3 < qi ? 8 : n3 < Yi ? 9 : 10; - }; - var Gi = { encode: Ai, decode: Ui, encodingLength: ji }; - var de = Gi; - var pe = (n3, e2, t = 0) => (de.encode(n3, e2, t), e2); - var De = (n3) => de.encodingLength(n3); - var Z = (n3, e2) => { - const t = e2.byteLength, i2 = De(n3), s2 = i2 + De(t), r = new Uint8Array(s2 + t); - return pe(n3, r, 0), pe(t, r, i2), r.set(e2, s2), new Hi(n3, t, e2, r); - }; - var Hi = class { - constructor(e2, t, i2, s2) { - this.code = e2, this.size = t, this.digest = i2, this.bytes = s2; - } - }; - var ye = ({ name: n3, code: e2, encode: t }) => new Xi(n3, e2, t); - var Xi = class { - constructor(e2, t, i2) { - this.name = e2, this.code = t, this.encode = i2; - } - digest(e2) { - if (e2 instanceof Uint8Array) { - const t = this.encode(e2); - return t instanceof Uint8Array ? Z(this.code, t) : t.then((i2) => Z(this.code, i2)); - } else - throw Error("Unknown type, must be binary type"); - } - }; - var Ee = (n3) => async (e2) => new Uint8Array(await crypto.subtle.digest(n3, e2)); - var Ji = ye({ name: "sha2-256", code: 18, encode: Ee("SHA-256") }); - var Wi = ye({ name: "sha2-512", code: 19, encode: Ee("SHA-512") }); - var Qi = Object.freeze({ __proto__: null, sha256: Ji, sha512: Wi }); - var me = 0; - var Zi = "identity"; - var be = ae; - var es = (n3) => Z(me, be(n3)); - var ts = { code: me, name: Zi, encode: be, digest: es }; - var is = Object.freeze({ __proto__: null, identity: ts }); - new TextEncoder(), new TextDecoder(); - var fe = { ...Ht, ...Jt, ...Qt, ...ei, ...si, ...di, ...yi, ...bi, ...Ri, ...Pi }; - ({ ...Qi, ...is }); - function we(n3) { - return globalThis.Buffer != null ? new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength) : n3; - } - function ss(n3 = 0) { - return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? we(globalThis.Buffer.allocUnsafe(n3)) : new Uint8Array(n3); - } - function ve(n3, e2, t, i2) { - return { name: n3, prefix: e2, encoder: { name: n3, prefix: e2, encode: t }, decoder: { decode: i2 } }; - } - var Ie = ve("utf8", "u", (n3) => "u" + new TextDecoder("utf8").decode(n3), (n3) => new TextEncoder().encode(n3.substring(1))); - var ee = ve("ascii", "a", (n3) => { - let e2 = "a"; - for (let t = 0; t < n3.length; t++) - e2 += String.fromCharCode(n3[t]); - return e2; - }, (n3) => { - n3 = n3.substring(1); - const e2 = ss(n3.length); - for (let t = 0; t < n3.length; t++) - e2[t] = n3.charCodeAt(t); - return e2; - }); - var rs = { utf8: Ie, "utf-8": Ie, hex: fe.base16, latin1: ee, ascii: ee, binary: ee, ...fe }; - function ns(n3, e2 = "utf8") { - const t = rs[e2]; - if (!t) - throw new Error(`Unsupported encoding "${e2}"`); - return (e2 === "utf8" || e2 === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? we(globalThis.Buffer.from(n3, "utf-8")) : t.decoder.decode(`${t.prefix}${n3}`); - } - var te = "wc"; - var Re = 2; - var H = "core"; - var L2 = `${te}@2:${H}:`; - var _e = { name: H, logger: "error" }; - var Ce = { database: ":memory:" }; - var Te = "crypto"; - var ie = "client_ed25519_seed"; - var Se = l4.ONE_DAY; - var Oe = "keychain"; - var Pe = "0.3"; - var Ae = "messages"; - var xe = "0.3"; - var Ne = l4.SIX_HOURS; - var Le = "publisher"; - var Ue = "irn"; - var ze = "error"; - var se = "wss://relay.walletconnect.com"; - var re = "wss://relay.walletconnect.org"; - var Fe = "relayer"; - var I2 = { message: "relayer_message", message_ack: "relayer_message_ack", connect: "relayer_connect", disconnect: "relayer_disconnect", error: "relayer_error", connection_stalled: "relayer_connection_stalled", transport_closed: "relayer_transport_closed", publish: "relayer_publish" }; - var Me = "_subscription"; - var w4 = { payload: "payload", connect: "connect", disconnect: "disconnect", error: "error" }; - var Be = l4.ONE_SECOND; - var os = { database: ":memory:" }; - var $e = "2.12.2"; - var ke = 1e4; - var Ve = "0.3"; - var Ke = "WALLETCONNECT_CLIENT_ID"; - var S4 = { created: "subscription_created", deleted: "subscription_deleted", expired: "subscription_expired", disabled: "subscription_disabled", sync: "subscription_sync", resubscribed: "subscription_resubscribed" }; - var as = l4.THIRTY_DAYS; - var qe = "subscription"; - var Ye = "0.3"; - var je = l4.FIVE_SECONDS * 1e3; - var Ge = "pairing"; - var He = "0.3"; - var hs = l4.THIRTY_DAYS; - var M = { wc_pairingDelete: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 1e3 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 1001 } }, wc_pairingPing: { req: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1002 }, res: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1003 } }, unregistered_method: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 0 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 0 } } }; - var K2 = { create: "pairing_create", expire: "pairing_expire", delete: "pairing_delete", ping: "pairing_ping" }; - var R2 = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; - var Xe = "history"; - var Je = "0.3"; - var We = "expirer"; - var _4 = { created: "expirer_created", deleted: "expirer_deleted", expired: "expirer_expired", sync: "expirer_sync" }; - var Qe = "0.3"; - var cs = l4.ONE_DAY; - var X = "verify-api"; - var B2 = "https://verify.walletconnect.com"; - var J = "https://verify.walletconnect.org"; - var Ze = [B2, J]; - var et = "echo"; - var tt = "https://echo.walletconnect.com"; - var it = class { - constructor(e2, t) { - this.core = e2, this.logger = t, this.keychain = /* @__PURE__ */ new Map(), this.name = Oe, this.version = Pe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { - if (!this.initialized) { - const i2 = await this.getKeyChain(); - typeof i2 < "u" && (this.keychain = i2), this.initialized = true; - } - }, this.has = (i2) => (this.isInitialized(), this.keychain.has(i2)), this.set = async (i2, s2) => { - this.isInitialized(), this.keychain.set(i2, s2), await this.persist(); - }, this.get = (i2) => { - this.isInitialized(); - const s2 = this.keychain.get(i2); - if (typeof s2 > "u") { - const { message: r } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${i2}`); - throw new Error(r); - } - return s2; - }, this.del = async (i2) => { - this.isInitialized(), this.keychain.delete(i2), await this.persist(); - }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - async setKeyChain(e2) { - await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); - } - async getKeyChain() { - const e2 = await this.core.storage.getItem(this.storageKey); - return typeof e2 < "u" ? a3.objToMap(e2) : void 0; - } - async persist() { - await this.setKeyChain(this.keychain); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var st = class { - constructor(e2, t, i2) { - this.core = e2, this.logger = t, this.name = Te, this.initialized = false, this.init = async () => { - this.initialized || (await this.keychain.init(), this.initialized = true); - }, this.hasKeys = (s2) => (this.isInitialized(), this.keychain.has(s2)), this.getClientId = async () => { - this.isInitialized(); - const s2 = await this.getClientSeed(), r = j2.generateKeyPair(s2); - return j2.encodeIss(r.publicKey); - }, this.generateKeyPair = () => { - this.isInitialized(); - const s2 = a3.generateKeyPair(); - return this.setPrivateKey(s2.publicKey, s2.privateKey); - }, this.signJWT = async (s2) => { - this.isInitialized(); - const r = await this.getClientSeed(), o2 = j2.generateKeyPair(r), h5 = a3.generateRandomBytes32(), c4 = Se; - return await j2.signJWT(h5, s2, c4, o2); - }, this.generateSharedKey = (s2, r, o2) => { - this.isInitialized(); - const h5 = this.getPrivateKey(s2), c4 = a3.deriveSymKey(h5, r); - return this.setSymKey(c4, o2); - }, this.setSymKey = async (s2, r) => { - this.isInitialized(); - const o2 = r || a3.hashKey(s2); - return await this.keychain.set(o2, s2), o2; - }, this.deleteKeyPair = async (s2) => { - this.isInitialized(), await this.keychain.del(s2); - }, this.deleteSymKey = async (s2) => { - this.isInitialized(), await this.keychain.del(s2); - }, this.encode = async (s2, r, o2) => { - this.isInitialized(); - const h5 = a3.validateEncoding(o2), c4 = oe.safeJsonStringify(r); - if (a3.isTypeOneEnvelope(h5)) { - const b4 = h5.senderPublicKey, F = h5.receiverPublicKey; - s2 = await this.generateSharedKey(b4, F); - } - const u3 = this.getSymKey(s2), { type: p3, senderPublicKey: D2 } = h5; - return a3.encrypt({ type: p3, symKey: u3, message: c4, senderPublicKey: D2 }); - }, this.decode = async (s2, r, o2) => { - this.isInitialized(); - const h5 = a3.validateDecoding(r, o2); - if (a3.isTypeOneEnvelope(h5)) { - const c4 = h5.receiverPublicKey, u3 = h5.senderPublicKey; - s2 = await this.generateSharedKey(c4, u3); - } - try { - const c4 = this.getSymKey(s2), u3 = a3.decrypt({ symKey: c4, encoded: r }); - return oe.safeJsonParse(u3); - } catch (c4) { - this.logger.error(`Failed to decode message from topic: '${s2}', clientId: '${await this.getClientId()}'`), this.logger.error(c4); - } - }, this.getPayloadType = (s2) => { - const r = a3.deserialize(s2); - return a3.decodeTypeByte(r.type); - }, this.getPayloadSenderPublicKey = (s2) => { - const r = a3.deserialize(s2); - return r.senderPublicKey ? _t.toString(r.senderPublicKey, a3.BASE16) : void 0; - }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.keychain = i2 || new it(this.core, this.logger); - } - get context() { - return g3.getLoggerContext(this.logger); - } - async setPrivateKey(e2, t) { - return await this.keychain.set(e2, t), e2; - } - getPrivateKey(e2) { - return this.keychain.get(e2); - } - async getClientSeed() { - let e2 = ""; - try { - e2 = this.keychain.get(ie); - } catch { - e2 = a3.generateRandomBytes32(), await this.keychain.set(ie, e2); - } - return ns(e2, "base16"); - } - getSymKey(e2) { - return this.keychain.get(e2); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var rt = class extends x3.IMessageTracker { - constructor(e2, t) { - super(e2, t), this.logger = e2, this.core = t, this.messages = /* @__PURE__ */ new Map(), this.name = Ae, this.version = xe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { - if (!this.initialized) { - this.logger.trace("Initialized"); - try { - const i2 = await this.getRelayerMessages(); - typeof i2 < "u" && (this.messages = i2), this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", size: this.messages.size }); - } catch (i2) { - this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(i2); - } finally { - this.initialized = true; - } - } - }, this.set = async (i2, s2) => { - this.isInitialized(); - const r = a3.hashMessage(s2); - let o2 = this.messages.get(i2); - return typeof o2 > "u" && (o2 = {}), typeof o2[r] < "u" || (o2[r] = s2, this.messages.set(i2, o2), await this.persist()), r; - }, this.get = (i2) => { - this.isInitialized(); - let s2 = this.messages.get(i2); - return typeof s2 > "u" && (s2 = {}), s2; - }, this.has = (i2, s2) => { - this.isInitialized(); - const r = this.get(i2), o2 = a3.hashMessage(s2); - return typeof r[o2] < "u"; - }, this.del = async (i2) => { - this.isInitialized(), this.messages.delete(i2), await this.persist(); - }, this.logger = g3.generateChildLogger(e2, this.name), this.core = t; - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - async setRelayerMessages(e2) { - await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); - } - async getRelayerMessages() { - const e2 = await this.core.storage.getItem(this.storageKey); - return typeof e2 < "u" ? a3.objToMap(e2) : void 0; - } - async persist() { - await this.setRelayerMessages(this.messages); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var ls2 = class extends x3.IPublisher { - constructor(e2, t) { - super(e2, t), this.relayer = e2, this.logger = t, this.events = new z3.EventEmitter(), this.name = Le, this.queue = /* @__PURE__ */ new Map(), this.publishTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.failedPublishTimeout = l4.toMiliseconds(l4.ONE_SECOND), this.needsTransportRestart = false, this.publish = async (i2, s2, r) => { - var o2; - this.logger.debug("Publishing Payload"), this.logger.trace({ type: "method", method: "publish", params: { topic: i2, message: s2, opts: r } }); - const h5 = r?.ttl || Ne, c4 = a3.getRelayProtocolName(r), u3 = r?.prompt || false, p3 = r?.tag || 0, D2 = r?.id || f4.getBigIntRpcId().toString(), b4 = { topic: i2, message: s2, opts: { ttl: h5, relay: c4, prompt: u3, tag: p3, id: D2 } }, F = `Failed to publish payload, please try again. id:${D2} tag:${p3}`, d3 = Date.now(); - let y4, C3 = 1; - try { - for (; y4 === void 0; ) { - if (Date.now() - d3 > this.publishTimeout) - throw new Error(F); - this.logger.trace({ id: D2, attempts: C3 }, `publisher.publish - attempt ${C3}`), y4 = await await a3.createExpiringPromise(this.rpcPublish(i2, s2, h5, c4, u3, p3, D2).catch((E4) => this.logger.warn(E4)), this.publishTimeout, F), C3++, y4 || await new Promise((E4) => setTimeout(E4, this.failedPublishTimeout)); - } - this.relayer.events.emit(I2.publish, b4), this.logger.debug("Successfully Published Payload"), this.logger.trace({ type: "method", method: "publish", params: { id: D2, topic: i2, message: s2, opts: r } }); - } catch (E4) { - if (this.logger.debug("Failed to Publish Payload"), this.logger.error(E4), (o2 = r?.internal) != null && o2.throwOnFailedPublish) - throw E4; - this.queue.set(D2, b4); - } - }, this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.registerEventListeners(); - } - get context() { - return g3.getLoggerContext(this.logger); - } - rpcPublish(e2, t, i2, s2, r, o2, h5) { - var c4, u3, p3, D2; - const b4 = { method: a3.getRelayProtocolApi(s2.protocol).publish, params: { topic: e2, message: t, ttl: i2, prompt: r, tag: o2 }, id: h5 }; - return a3.isUndefined((c4 = b4.params) == null ? void 0 : c4.prompt) && ((u3 = b4.params) == null || delete u3.prompt), a3.isUndefined((p3 = b4.params) == null ? void 0 : p3.tag) && ((D2 = b4.params) == null || delete D2.tag), this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "message", direction: "outgoing", request: b4 }), this.relayer.request(b4); - } - removeRequestFromQueue(e2) { - this.queue.delete(e2); - } - checkQueue() { - this.queue.forEach(async (e2) => { - const { topic: t, message: i2, opts: s2 } = e2; - await this.publish(t, i2, s2); - }); - } - registerEventListeners() { - this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { - if (this.needsTransportRestart) { - this.needsTransportRestart = false, this.relayer.events.emit(I2.connection_stalled); - return; - } - this.checkQueue(); - }), this.relayer.on(I2.message_ack, (e2) => { - this.removeRequestFromQueue(e2.id.toString()); - }); - } - }; - var us = class { - constructor() { - this.map = /* @__PURE__ */ new Map(), this.set = (e2, t) => { - const i2 = this.get(e2); - this.exists(e2, t) || this.map.set(e2, [...i2, t]); - }, this.get = (e2) => this.map.get(e2) || [], this.exists = (e2, t) => this.get(e2).includes(t), this.delete = (e2, t) => { - if (typeof t > "u") { - this.map.delete(e2); - return; - } - if (!this.map.has(e2)) - return; - const i2 = this.get(e2); - if (!this.exists(e2, t)) - return; - const s2 = i2.filter((r) => r !== t); - if (!s2.length) { - this.map.delete(e2); - return; - } - this.map.set(e2, s2); - }, this.clear = () => { - this.map.clear(); - }; - } - get topics() { - return Array.from(this.map.keys()); - } - }; - var gs = Object.defineProperty; - var ds = Object.defineProperties; - var ps = Object.getOwnPropertyDescriptors; - var nt = Object.getOwnPropertySymbols; - var Ds = Object.prototype.hasOwnProperty; - var ys = Object.prototype.propertyIsEnumerable; - var ot = (n3, e2, t) => e2 in n3 ? gs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var q2 = (n3, e2) => { - for (var t in e2 || (e2 = {})) - Ds.call(e2, t) && ot(n3, t, e2[t]); - if (nt) - for (var t of nt(e2)) - ys.call(e2, t) && ot(n3, t, e2[t]); - return n3; - }; - var ne = (n3, e2) => ds(n3, ps(e2)); - var at = class extends x3.ISubscriber { - constructor(e2, t) { - super(e2, t), this.relayer = e2, this.logger = t, this.subscriptions = /* @__PURE__ */ new Map(), this.topicMap = new us(), this.events = new z3.EventEmitter(), this.name = qe, this.version = Ye, this.pending = /* @__PURE__ */ new Map(), this.cached = [], this.initialized = false, this.pendingSubscriptionWatchLabel = "pending_sub_watch_label", this.pollingInterval = 20, this.storagePrefix = L2, this.subscribeTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.restartInProgress = false, this.batchSubscribeTopicsLimit = 500, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), this.registerEventListeners(), this.clientId = await this.relayer.core.crypto.getClientId()); - }, this.subscribe = async (i2, s2) => { - await this.restartToComplete(), this.isInitialized(), this.logger.debug("Subscribing Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } }); - try { - const r = a3.getRelayProtocolName(s2), o2 = { topic: i2, relay: r }; - this.pending.set(i2, o2); - const h5 = await this.rpcSubscribe(i2, r); - return typeof h5 == "string" && (this.onSubscribe(h5, o2), this.logger.debug("Successfully Subscribed Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } })), h5; - } catch (r) { - throw this.logger.debug("Failed to Subscribe Topic"), this.logger.error(r), r; - } - }, this.unsubscribe = async (i2, s2) => { - await this.restartToComplete(), this.isInitialized(), typeof s2?.id < "u" ? await this.unsubscribeById(i2, s2.id, s2) : await this.unsubscribeByTopic(i2, s2); - }, this.isSubscribed = async (i2) => { - if (this.topics.includes(i2)) - return true; - const s2 = `${this.pendingSubscriptionWatchLabel}_${i2}`; - return await new Promise((r, o2) => { - const h5 = new l4.Watch(); - h5.start(s2); - const c4 = setInterval(() => { - !this.pending.has(i2) && this.topics.includes(i2) && (clearInterval(c4), h5.stop(s2), r(true)), h5.elapsed(s2) >= je && (clearInterval(c4), h5.stop(s2), o2(new Error("Subscription resolution timeout"))); - }, this.pollingInterval); - }).catch(() => false); - }, this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.start = async () => { - await this.onConnect(); - }, this.stop = async () => { - await this.onDisconnect(); - }, this.restart = async () => { - this.restartInProgress = true, await this.restore(), await this.reset(), this.restartInProgress = false; - }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.clientId = ""; - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.relayer.core.customStoragePrefix + "//" + this.name; - } - get length() { - return this.subscriptions.size; - } - get ids() { - return Array.from(this.subscriptions.keys()); - } - get values() { - return Array.from(this.subscriptions.values()); - } - get topics() { - return this.topicMap.topics; - } - hasSubscription(e2, t) { - let i2 = false; - try { - i2 = this.getSubscription(e2).topic === t; - } catch { - } - return i2; - } - onEnable() { - this.cached = [], this.initialized = true; - } - onDisable() { - this.cached = this.values, this.subscriptions.clear(), this.topicMap.clear(); - } - async unsubscribeByTopic(e2, t) { - const i2 = this.topicMap.get(e2); - await Promise.all(i2.map(async (s2) => await this.unsubscribeById(e2, s2, t))); - } - async unsubscribeById(e2, t, i2) { - this.logger.debug("Unsubscribing Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); - try { - const s2 = a3.getRelayProtocolName(i2); - await this.rpcUnsubscribe(e2, t, s2); - const r = a3.getSdkError("USER_DISCONNECTED", `${this.name}, ${e2}`); - await this.onUnsubscribe(e2, t, r), this.logger.debug("Successfully Unsubscribed Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); - } catch (s2) { - throw this.logger.debug("Failed to Unsubscribe Topic"), this.logger.error(s2), s2; - } - } - async rpcSubscribe(e2, t) { - const i2 = { method: a3.getRelayProtocolApi(t.protocol).subscribe, params: { topic: e2 } }; - this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); - try { - return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout) ? a3.hashMessage(e2 + this.clientId) : null; - } catch { - this.logger.debug("Outgoing Relay Subscribe Payload stalled"), this.relayer.events.emit(I2.connection_stalled); - } - return null; - } - async rpcBatchSubscribe(e2) { - if (!e2.length) - return; - const t = e2[0].relay, i2 = { method: a3.getRelayProtocolApi(t.protocol).batchSubscribe, params: { topics: e2.map((s2) => s2.topic) } }; - this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); - try { - return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout); - } catch { - this.relayer.events.emit(I2.connection_stalled); - } - } - rpcUnsubscribe(e2, t, i2) { - const s2 = { method: a3.getRelayProtocolApi(i2.protocol).unsubscribe, params: { topic: e2, id: t } }; - return this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s2 }), this.relayer.request(s2); - } - onSubscribe(e2, t) { - this.setSubscription(e2, ne(q2({}, t), { id: e2 })), this.pending.delete(t.topic); - } - onBatchSubscribe(e2) { - e2.length && e2.forEach((t) => { - this.setSubscription(t.id, q2({}, t)), this.pending.delete(t.topic); - }); - } - async onUnsubscribe(e2, t, i2) { - this.events.removeAllListeners(t), this.hasSubscription(t, e2) && this.deleteSubscription(t, i2), await this.relayer.messages.del(e2); - } - async setRelayerSubscriptions(e2) { - await this.relayer.core.storage.setItem(this.storageKey, e2); - } - async getRelayerSubscriptions() { - return await this.relayer.core.storage.getItem(this.storageKey); - } - setSubscription(e2, t) { - this.logger.debug("Setting subscription"), this.logger.trace({ type: "method", method: "setSubscription", id: e2, subscription: t }), this.addSubscription(e2, t); - } - addSubscription(e2, t) { - this.subscriptions.set(e2, q2({}, t)), this.topicMap.set(t.topic, e2), this.events.emit(S4.created, t); - } - getSubscription(e2) { - this.logger.debug("Getting subscription"), this.logger.trace({ type: "method", method: "getSubscription", id: e2 }); - const t = this.subscriptions.get(e2); - if (!t) { - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw new Error(i2); - } - return t; - } - deleteSubscription(e2, t) { - this.logger.debug("Deleting subscription"), this.logger.trace({ type: "method", method: "deleteSubscription", id: e2, reason: t }); - const i2 = this.getSubscription(e2); - this.subscriptions.delete(e2), this.topicMap.delete(i2.topic, e2), this.events.emit(S4.deleted, ne(q2({}, i2), { reason: t })); - } - async persist() { - await this.setRelayerSubscriptions(this.values), this.events.emit(S4.sync); - } - async reset() { - if (this.cached.length) { - const e2 = Math.ceil(this.cached.length / this.batchSubscribeTopicsLimit); - for (let t = 0; t < e2; t++) { - const i2 = this.cached.splice(0, this.batchSubscribeTopicsLimit); - await this.batchSubscribe(i2); - } - } - this.events.emit(S4.resubscribed); - } - async restore() { - try { - const e2 = await this.getRelayerSubscriptions(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.subscriptions.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored subscriptions for ${this.name}`), this.logger.trace({ type: "method", method: "restore", subscriptions: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore subscriptions for ${this.name}`), this.logger.error(e2); - } - } - async batchSubscribe(e2) { - if (!e2.length) - return; - const t = await this.rpcBatchSubscribe(e2); - a3.isValidArray(t) && this.onBatchSubscribe(t.map((i2, s2) => ne(q2({}, e2[s2]), { id: i2 }))); - } - async onConnect() { - await this.restart(), this.onEnable(); - } - onDisconnect() { - this.onDisable(); - } - async checkPending() { - if (!this.initialized || !this.relayer.connected) - return; - const e2 = []; - this.pending.forEach((t) => { - e2.push(t); - }), await this.batchSubscribe(e2); - } - registerEventListeners() { - this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, async () => { - await this.checkPending(); - }), this.events.on(S4.created, async (e2) => { - const t = S4.created; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); - }), this.events.on(S4.deleted, async (e2) => { - const t = S4.deleted; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); - }); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - async restartToComplete() { - this.restartInProgress && await new Promise((e2) => { - const t = setInterval(() => { - this.restartInProgress || (clearInterval(t), e2()); - }, this.pollingInterval); - }); - } - }; - var Es = Object.defineProperty; - var ht = Object.getOwnPropertySymbols; - var ms = Object.prototype.hasOwnProperty; - var bs = Object.prototype.propertyIsEnumerable; - var ct = (n3, e2, t) => e2 in n3 ? Es(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var fs = (n3, e2) => { - for (var t in e2 || (e2 = {})) - ms.call(e2, t) && ct(n3, t, e2[t]); - if (ht) - for (var t of ht(e2)) - bs.call(e2, t) && ct(n3, t, e2[t]); - return n3; - }; - var lt = class extends x3.IRelayer { - constructor(e2) { - super(e2), this.protocol = "wc", this.version = 2, this.events = new z3.EventEmitter(), this.name = Fe, this.transportExplicitlyClosed = false, this.initialized = false, this.connectionAttemptInProgress = false, this.connectionStatusPollingInterval = 20, this.staleConnectionErrors = ["socket hang up", "socket stalled", "interrupted"], this.hasExperiencedNetworkDisruption = false, this.requestsInFlight = /* @__PURE__ */ new Map(), this.heartBeatTimeout = l4.toMiliseconds(l4.THIRTY_SECONDS + l4.ONE_SECOND), this.request = async (t) => { - var i2, s2; - this.logger.debug("Publishing Request Payload"); - const r = t.id || f4.getBigIntRpcId().toString(); - await this.toEstablishConnection(); - try { - const o2 = this.provider.request(t); - this.requestsInFlight.set(r, { promise: o2, request: t }), this.logger.trace({ id: r, method: t.method, topic: (i2 = t.params) == null ? void 0 : i2.topic }, "relayer.request - attempt to publish..."); - const h5 = await new Promise(async (c4, u3) => { - const p3 = () => { - u3(new Error(`relayer.request - publish interrupted, id: ${r}`)); - }; - this.provider.on(w4.disconnect, p3); - const D2 = await o2; - this.provider.off(w4.disconnect, p3), c4(D2); - }); - return this.logger.trace({ id: r, method: t.method, topic: (s2 = t.params) == null ? void 0 : s2.topic }, "relayer.request - published"), h5; - } catch (o2) { - throw this.logger.debug(`Failed to Publish Request: ${r}`), o2; - } finally { - this.requestsInFlight.delete(r); - } - }, this.resetPingTimeout = () => { - if (a3.isNode()) - try { - clearTimeout(this.pingTimeout), this.pingTimeout = setTimeout(() => { - var t, i2, s2; - (s2 = (i2 = (t = this.provider) == null ? void 0 : t.connection) == null ? void 0 : i2.socket) == null || s2.terminate(); - }, this.heartBeatTimeout); - } catch (t) { - this.logger.warn(t); - } - }, this.onPayloadHandler = (t) => { - this.onProviderPayload(t), this.resetPingTimeout(); - }, this.onConnectHandler = () => { - this.startPingTimeout(), this.events.emit(I2.connect); - }, this.onDisconnectHandler = () => { - this.onProviderDisconnect(); - }, this.onProviderErrorHandler = (t) => { - this.logger.error(t), this.events.emit(I2.error, t), this.logger.info("Fatal socket error received, closing transport"), this.transportClose(); - }, this.registerProviderListeners = () => { - this.provider.on(w4.payload, this.onPayloadHandler), this.provider.on(w4.connect, this.onConnectHandler), this.provider.on(w4.disconnect, this.onDisconnectHandler), this.provider.on(w4.error, this.onProviderErrorHandler); - }, this.core = e2.core, this.logger = typeof e2.logger < "u" && typeof e2.logger != "string" ? g3.generateChildLogger(e2.logger, this.name) : g3.pino(g3.getDefaultLoggerOptions({ level: e2.logger || ze })), this.messages = new rt(this.logger, e2.core), this.subscriber = new at(this, this.logger), this.publisher = new ls2(this, this.logger), this.relayUrl = e2?.relayUrl || se, this.projectId = e2.projectId, this.bundleId = a3.getBundleId(), this.provider = {}; - } - async init() { - this.logger.trace("Initialized"), this.registerEventListeners(), await this.createProvider(), await Promise.all([this.messages.init(), this.subscriber.init()]); - try { - await this.transportOpen(); - } catch { - this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${re}...`), await this.restartTransport(re); - } - this.initialized = true, setTimeout(async () => { - this.subscriber.topics.length === 0 && this.subscriber.pending.size === 0 && (this.logger.info("No topics subscribed to after init, closing transport"), await this.transportClose(), this.transportExplicitlyClosed = false); - }, ke); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get connected() { - var e2, t, i2; - return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 1; - } - get connecting() { - var e2, t, i2; - return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 0; - } - async publish(e2, t, i2) { - this.isInitialized(), await this.publisher.publish(e2, t, i2), await this.recordMessageEvent({ topic: e2, message: t, publishedAt: Date.now() }); - } - async subscribe(e2, t) { - var i2; - this.isInitialized(); - let s2 = ((i2 = this.subscriber.topicMap.get(e2)) == null ? void 0 : i2[0]) || "", r; - const o2 = (h5) => { - h5.topic === e2 && (this.subscriber.off(S4.created, o2), r()); - }; - return await Promise.all([new Promise((h5) => { - r = h5, this.subscriber.on(S4.created, o2); - }), new Promise(async (h5) => { - s2 = await this.subscriber.subscribe(e2, t) || s2, h5(); - })]), s2; - } - async unsubscribe(e2, t) { - this.isInitialized(), await this.subscriber.unsubscribe(e2, t); - } - on(e2, t) { - this.events.on(e2, t); - } - once(e2, t) { - this.events.once(e2, t); - } - off(e2, t) { - this.events.off(e2, t); - } - removeListener(e2, t) { - this.events.removeListener(e2, t); - } - async transportDisconnect() { - if (!this.hasExperiencedNetworkDisruption && this.connected && this.requestsInFlight.size > 0) - try { - await Promise.all(Array.from(this.requestsInFlight.values()).map((e2) => e2.promise)); - } catch (e2) { - this.logger.warn(e2); - } - this.hasExperiencedNetworkDisruption || this.connected ? await a3.createExpiringPromise(this.provider.disconnect(), 2e3, "provider.disconnect()").catch(() => this.onProviderDisconnect()) : this.onProviderDisconnect(); - } - async transportClose() { - this.transportExplicitlyClosed = true, await this.transportDisconnect(); - } - async transportOpen(e2) { - await this.confirmOnlineStateOrThrow(), e2 && e2 !== this.relayUrl && (this.relayUrl = e2, await this.transportDisconnect(), await this.createProvider()), this.connectionAttemptInProgress = true, this.transportExplicitlyClosed = false; - try { - await new Promise(async (t, i2) => { - const s2 = () => { - this.provider.off(w4.disconnect, s2), i2(new Error("Connection interrupted while trying to subscribe")); - }; - this.provider.on(w4.disconnect, s2), await a3.createExpiringPromise(this.provider.connect(), l4.toMiliseconds(l4.ONE_MINUTE), `Socket stalled when trying to connect to ${this.relayUrl}`).catch((r) => { - i2(r); - }), await this.subscriber.start(), this.hasExperiencedNetworkDisruption = false, t(); - }); - } catch (t) { - this.logger.error(t); - const i2 = t; - if (!this.isConnectionStalled(i2.message)) - throw t; - } finally { - this.connectionAttemptInProgress = false; - } - } - async restartTransport(e2) { - this.connectionAttemptInProgress || (this.relayUrl = e2 || this.relayUrl, await this.confirmOnlineStateOrThrow(), await this.transportClose(), await this.createProvider(), await this.transportOpen()); - } - async confirmOnlineStateOrThrow() { - if (!await a3.isOnline()) - throw new Error("No internet connection detected. Please restart your network and try again."); - } - startPingTimeout() { - var e2, t, i2, s2, r; - if (a3.isNode()) - try { - (t = (e2 = this.provider) == null ? void 0 : e2.connection) != null && t.socket && ((r = (s2 = (i2 = this.provider) == null ? void 0 : i2.connection) == null ? void 0 : s2.socket) == null || r.once("ping", () => { - this.resetPingTimeout(); - })), this.resetPingTimeout(); - } catch (o2) { - this.logger.warn(o2); - } - } - isConnectionStalled(e2) { - return this.staleConnectionErrors.some((t) => e2.includes(t)); - } - async createProvider() { - this.provider.connection && this.unregisterProviderListeners(); - const e2 = await this.core.crypto.signJWT(this.relayUrl); - this.provider = new Ct.JsonRpcProvider(new Nt.default(a3.formatRelayRpcUrl({ sdkVersion: $e, protocol: this.protocol, version: this.version, relayUrl: this.relayUrl, projectId: this.projectId, auth: e2, useOnCloseEvent: true, bundleId: this.bundleId }))), this.registerProviderListeners(); - } - async recordMessageEvent(e2) { - const { topic: t, message: i2 } = e2; - await this.messages.set(t, i2); - } - async shouldIgnoreMessageEvent(e2) { - const { topic: t, message: i2 } = e2; - if (!i2 || i2.length === 0) - return this.logger.debug(`Ignoring invalid/empty message: ${i2}`), true; - if (!await this.subscriber.isSubscribed(t)) - return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`), true; - const s2 = this.messages.has(t, i2); - return s2 && this.logger.debug(`Ignoring duplicate message: ${i2}`), s2; - } - async onProviderPayload(e2) { - if (this.logger.debug("Incoming Relay Payload"), this.logger.trace({ type: "payload", direction: "incoming", payload: e2 }), f4.isJsonRpcRequest(e2)) { - if (!e2.method.endsWith(Me)) - return; - const t = e2.params, { topic: i2, message: s2, publishedAt: r } = t.data, o2 = { topic: i2, message: s2, publishedAt: r }; - this.logger.debug("Emitting Relayer Payload"), this.logger.trace(fs({ type: "event", event: t.id }, o2)), this.events.emit(t.id, o2), await this.acknowledgePayload(e2), await this.onMessageEvent(o2); - } else - f4.isJsonRpcResponse(e2) && this.events.emit(I2.message_ack, e2); - } - async onMessageEvent(e2) { - await this.shouldIgnoreMessageEvent(e2) || (this.events.emit(I2.message, e2), await this.recordMessageEvent(e2)); - } - async acknowledgePayload(e2) { - const t = f4.formatJsonRpcResult(e2.id, true); - await this.provider.connection.send(t); - } - unregisterProviderListeners() { - this.provider.off(w4.payload, this.onPayloadHandler), this.provider.off(w4.connect, this.onConnectHandler), this.provider.off(w4.disconnect, this.onDisconnectHandler), this.provider.off(w4.error, this.onProviderErrorHandler); - } - async registerEventListeners() { - let e2 = await a3.isOnline(); - a3.subscribeToNetworkChange(async (t) => { - e2 !== t && (e2 = t, t ? await this.restartTransport().catch((i2) => this.logger.error(i2)) : (this.hasExperiencedNetworkDisruption = true, await this.transportDisconnect(), this.transportExplicitlyClosed = false)); - }); - } - async onProviderDisconnect() { - await this.subscriber.stop(), this.events.emit(I2.disconnect), this.connectionAttemptInProgress = false, !this.transportExplicitlyClosed && setTimeout(async () => { - await this.transportOpen().catch((e2) => this.logger.error(e2)); - }, l4.toMiliseconds(Be)); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - async toEstablishConnection() { - await this.confirmOnlineStateOrThrow(), !this.connected && (this.connectionAttemptInProgress && await new Promise((e2) => { - const t = setInterval(() => { - this.connected && (clearInterval(t), e2()); - }, this.connectionStatusPollingInterval); - }), await this.transportOpen()); - } - }; - var ws = Object.defineProperty; - var ut = Object.getOwnPropertySymbols; - var vs = Object.prototype.hasOwnProperty; - var Is = Object.prototype.propertyIsEnumerable; - var gt = (n3, e2, t) => e2 in n3 ? ws(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var dt = (n3, e2) => { - for (var t in e2 || (e2 = {})) - vs.call(e2, t) && gt(n3, t, e2[t]); - if (ut) - for (var t of ut(e2)) - Is.call(e2, t) && gt(n3, t, e2[t]); - return n3; - }; - var pt = class extends x3.IStore { - constructor(e2, t, i2, s2 = L2, r = void 0) { - super(e2, t, i2, s2), this.core = e2, this.logger = t, this.name = i2, this.map = /* @__PURE__ */ new Map(), this.version = Ve, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.recentlyDeleted = [], this.recentlyDeletedLimit = 200, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((o2) => { - this.getKey && o2 !== null && !a3.isUndefined(o2) ? this.map.set(this.getKey(o2), o2) : a3.isProposalStruct(o2) ? this.map.set(o2.id, o2) : a3.isSessionStruct(o2) && this.map.set(o2.topic, o2); - }), this.cached = [], this.initialized = true); - }, this.set = async (o2, h5) => { - this.isInitialized(), this.map.has(o2) ? await this.update(o2, h5) : (this.logger.debug("Setting value"), this.logger.trace({ type: "method", method: "set", key: o2, value: h5 }), this.map.set(o2, h5), await this.persist()); - }, this.get = (o2) => (this.isInitialized(), this.logger.debug("Getting value"), this.logger.trace({ type: "method", method: "get", key: o2 }), this.getData(o2)), this.getAll = (o2) => (this.isInitialized(), o2 ? this.values.filter((h5) => Object.keys(o2).every((c4) => Lt.default(h5[c4], o2[c4]))) : this.values), this.update = async (o2, h5) => { - this.isInitialized(), this.logger.debug("Updating value"), this.logger.trace({ type: "method", method: "update", key: o2, update: h5 }); - const c4 = dt(dt({}, this.getData(o2)), h5); - this.map.set(o2, c4), await this.persist(); - }, this.delete = async (o2, h5) => { - this.isInitialized(), this.map.has(o2) && (this.logger.debug("Deleting value"), this.logger.trace({ type: "method", method: "delete", key: o2, reason: h5 }), this.map.delete(o2), this.addToRecentlyDeleted(o2), await this.persist()); - }, this.logger = g3.generateChildLogger(t, this.name), this.storagePrefix = s2, this.getKey = r; - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - get length() { - return this.map.size; - } - get keys() { - return Array.from(this.map.keys()); - } - get values() { - return Array.from(this.map.values()); - } - addToRecentlyDeleted(e2) { - this.recentlyDeleted.push(e2), this.recentlyDeleted.length >= this.recentlyDeletedLimit && this.recentlyDeleted.splice(0, this.recentlyDeletedLimit / 2); - } - async setDataStore(e2) { - await this.core.storage.setItem(this.storageKey, e2); - } - async getDataStore() { - return await this.core.storage.getItem(this.storageKey); - } - getData(e2) { - const t = this.map.get(e2); - if (!t) { - if (this.recentlyDeleted.includes(e2)) { - const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${this.name}: ${e2}`); - throw this.logger.error(s2), new Error(s2); - } - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw this.logger.error(i2), new Error(i2); - } - return t; - } - async persist() { - await this.setDataStore(this.values); - } - async restore() { - try { - const e2 = await this.getDataStore(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.map.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored value for ${this.name}`), this.logger.trace({ type: "method", method: "restore", value: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore value for ${this.name}`), this.logger.error(e2); - } - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var Dt = class { - constructor(e2, t) { - this.core = e2, this.logger = t, this.name = Ge, this.version = He, this.events = new At.default(), this.initialized = false, this.storagePrefix = L2, this.ignoredPayloadTypes = [a3.TYPE_1], this.registeredMethods = [], this.init = async () => { - this.initialized || (await this.pairings.init(), await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.initialized = true, this.logger.trace("Initialized")); - }, this.register = ({ methods: i2 }) => { - this.isInitialized(), this.registeredMethods = [.../* @__PURE__ */ new Set([...this.registeredMethods, ...i2])]; - }, this.create = async (i2) => { - this.isInitialized(); - const s2 = a3.generateRandomBytes32(), r = await this.core.crypto.setSymKey(s2), o2 = a3.calcExpiry(l4.FIVE_MINUTES), h5 = { protocol: Ue }, c4 = { topic: r, expiry: o2, relay: h5, active: false }, u3 = a3.formatUri({ protocol: this.core.protocol, version: this.core.version, topic: r, symKey: s2, relay: h5, expiryTimestamp: o2, methods: i2?.methods }); - return await this.pairings.set(r, c4), await this.core.relayer.subscribe(r), this.core.expirer.set(r, o2), { topic: r, uri: u3 }; - }, this.pair = async (i2) => { - this.isInitialized(), this.isValidPair(i2); - const { topic: s2, symKey: r, relay: o2, expiryTimestamp: h5, methods: c4 } = a3.parseUri(i2.uri); - let u3; - if (this.pairings.keys.includes(s2) && (u3 = this.pairings.get(s2), u3.active)) - throw new Error(`Pairing already exists: ${s2}. Please try again with a new connection URI.`); - const p3 = h5 || a3.calcExpiry(l4.FIVE_MINUTES), D2 = { topic: s2, relay: o2, expiry: p3, active: false, methods: c4 }; - return await this.pairings.set(s2, D2), this.core.expirer.set(s2, p3), i2.activatePairing && await this.activate({ topic: s2 }), this.events.emit(K2.create, D2), this.core.crypto.keychain.has(s2) || await this.core.crypto.setSymKey(r, s2), await this.core.relayer.subscribe(s2, { relay: o2 }), D2; - }, this.activate = async ({ topic: i2 }) => { - this.isInitialized(); - const s2 = a3.calcExpiry(l4.THIRTY_DAYS); - await this.pairings.update(i2, { active: true, expiry: s2 }), this.core.expirer.set(i2, s2); - }, this.ping = async (i2) => { - this.isInitialized(), await this.isValidPing(i2); - const { topic: s2 } = i2; - if (this.pairings.keys.includes(s2)) { - const r = await this.sendRequest(s2, "wc_pairingPing", {}), { done: o2, resolve: h5, reject: c4 } = a3.createDelayedPromise(); - this.events.once(a3.engineEvent("pairing_ping", r), ({ error: u3 }) => { - u3 ? c4(u3) : h5(); - }), await o2(); - } - }, this.updateExpiry = async ({ topic: i2, expiry: s2 }) => { - this.isInitialized(), await this.pairings.update(i2, { expiry: s2 }); - }, this.updateMetadata = async ({ topic: i2, metadata: s2 }) => { - this.isInitialized(), await this.pairings.update(i2, { peerMetadata: s2 }); - }, this.getPairings = () => (this.isInitialized(), this.pairings.values), this.disconnect = async (i2) => { - this.isInitialized(), await this.isValidDisconnect(i2); - const { topic: s2 } = i2; - this.pairings.keys.includes(s2) && (await this.sendRequest(s2, "wc_pairingDelete", a3.getSdkError("USER_DISCONNECTED")), await this.deletePairing(s2)); - }, this.sendRequest = async (i2, s2, r) => { - const o2 = f4.formatJsonRpcRequest(s2, r), h5 = await this.core.crypto.encode(i2, o2), c4 = M[s2].req; - return this.core.history.set(i2, o2), this.core.relayer.publish(i2, h5, c4), o2.id; - }, this.sendResult = async (i2, s2, r) => { - const o2 = f4.formatJsonRpcResult(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method].res; - await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); - }, this.sendError = async (i2, s2, r) => { - const o2 = f4.formatJsonRpcError(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method] ? M[c4.request.method].res : M.unregistered_method.res; - await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); - }, this.deletePairing = async (i2, s2) => { - await this.core.relayer.unsubscribe(i2), await Promise.all([this.pairings.delete(i2, a3.getSdkError("USER_DISCONNECTED")), this.core.crypto.deleteSymKey(i2), s2 ? Promise.resolve() : this.core.expirer.del(i2)]); - }, this.cleanup = async () => { - const i2 = this.pairings.getAll().filter((s2) => a3.isExpired(s2.expiry)); - await Promise.all(i2.map((s2) => this.deletePairing(s2.topic))); - }, this.onRelayEventRequest = (i2) => { - const { topic: s2, payload: r } = i2; - switch (r.method) { - case "wc_pairingPing": - return this.onPairingPingRequest(s2, r); - case "wc_pairingDelete": - return this.onPairingDeleteRequest(s2, r); - default: - return this.onUnknownRpcMethodRequest(s2, r); - } - }, this.onRelayEventResponse = async (i2) => { - const { topic: s2, payload: r } = i2, o2 = (await this.core.history.get(s2, r.id)).request.method; - switch (o2) { - case "wc_pairingPing": - return this.onPairingPingResponse(s2, r); - default: - return this.onUnknownRpcMethodResponse(o2); - } - }, this.onPairingPingRequest = async (i2, s2) => { - const { id: r } = s2; - try { - this.isValidPing({ topic: i2 }), await this.sendResult(r, i2, true), this.events.emit(K2.ping, { id: r, topic: i2 }); - } catch (o2) { - await this.sendError(r, i2, o2), this.logger.error(o2); - } - }, this.onPairingPingResponse = (i2, s2) => { - const { id: r } = s2; - setTimeout(() => { - f4.isJsonRpcResult(s2) ? this.events.emit(a3.engineEvent("pairing_ping", r), {}) : f4.isJsonRpcError(s2) && this.events.emit(a3.engineEvent("pairing_ping", r), { error: s2.error }); - }, 500); - }, this.onPairingDeleteRequest = async (i2, s2) => { - const { id: r } = s2; - try { - this.isValidDisconnect({ topic: i2 }), await this.deletePairing(i2), this.events.emit(K2.delete, { id: r, topic: i2 }); - } catch (o2) { - await this.sendError(r, i2, o2), this.logger.error(o2); - } - }, this.onUnknownRpcMethodRequest = async (i2, s2) => { - const { id: r, method: o2 } = s2; - try { - if (this.registeredMethods.includes(o2)) - return; - const h5 = a3.getSdkError("WC_METHOD_UNSUPPORTED", o2); - await this.sendError(r, i2, h5), this.logger.error(h5); - } catch (h5) { - await this.sendError(r, i2, h5), this.logger.error(h5); - } - }, this.onUnknownRpcMethodResponse = (i2) => { - this.registeredMethods.includes(i2) || this.logger.error(a3.getSdkError("WC_METHOD_UNSUPPORTED", i2)); - }, this.isValidPair = (i2) => { - var s2; - if (!a3.isValidParams(i2)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() params: ${i2}`); - throw new Error(o2); - } - if (!a3.isValidUrl(i2.uri)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() uri: ${i2.uri}`); - throw new Error(o2); - } - const r = a3.parseUri(i2.uri); - if (!((s2 = r?.relay) != null && s2.protocol)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#relay-protocol"); - throw new Error(o2); - } - if (!(r != null && r.symKey)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#symKey"); - throw new Error(o2); - } - if (r != null && r.expiryTimestamp && l4.toMiliseconds(r?.expiryTimestamp) < Date.now()) { - const { message: o2 } = a3.getInternalError("EXPIRED", "pair() URI has expired. Please try again with a new connection URI."); - throw new Error(o2); - } - }, this.isValidPing = async (i2) => { - if (!a3.isValidParams(i2)) { - const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `ping() params: ${i2}`); - throw new Error(r); - } - const { topic: s2 } = i2; - await this.isValidPairingTopic(s2); - }, this.isValidDisconnect = async (i2) => { - if (!a3.isValidParams(i2)) { - const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${i2}`); - throw new Error(r); - } - const { topic: s2 } = i2; - await this.isValidPairingTopic(s2); - }, this.isValidPairingTopic = async (i2) => { - if (!a3.isValidString(i2, false)) { - const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${i2}`); - throw new Error(s2); - } - if (!this.pairings.keys.includes(i2)) { - const { message: s2 } = a3.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${i2}`); - throw new Error(s2); - } - if (a3.isExpired(this.pairings.get(i2).expiry)) { - await this.deletePairing(i2); - const { message: s2 } = a3.getInternalError("EXPIRED", `pairing topic: ${i2}`); - throw new Error(s2); - } - }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.pairings = new pt(this.core, this.logger, this.name, this.storagePrefix); - } - get context() { - return g3.getLoggerContext(this.logger); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - registerRelayerEvents() { - this.core.relayer.on(I2.message, async (e2) => { - const { topic: t, message: i2 } = e2; - if (!this.pairings.keys.includes(t) || this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i2))) - return; - const s2 = await this.core.crypto.decode(t, i2); - try { - f4.isJsonRpcRequest(s2) ? (this.core.history.set(t, s2), this.onRelayEventRequest({ topic: t, payload: s2 })) : f4.isJsonRpcResponse(s2) && (await this.core.history.resolve(s2), await this.onRelayEventResponse({ topic: t, payload: s2 }), this.core.history.delete(t, s2.id)); - } catch (r) { - this.logger.error(r); - } - }); - } - registerExpirerEvents() { - this.core.expirer.on(_4.expired, async (e2) => { - const { topic: t } = a3.parseExpirerTarget(e2.target); - t && this.pairings.keys.includes(t) && (await this.deletePairing(t, true), this.events.emit(K2.expire, { topic: t })); - }); - } - }; - var yt = class extends x3.IJsonRpcHistory { - constructor(e2, t) { - super(e2, t), this.core = e2, this.logger = t, this.records = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = Xe, this.version = Je, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.records.set(i2.id, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); - }, this.set = (i2, s2, r) => { - if (this.isInitialized(), this.logger.debug("Setting JSON-RPC request history record"), this.logger.trace({ type: "method", method: "set", topic: i2, request: s2, chainId: r }), this.records.has(s2.id)) - return; - const o2 = { id: s2.id, topic: i2, request: { method: s2.method, params: s2.params || null }, chainId: r, expiry: a3.calcExpiry(l4.THIRTY_DAYS) }; - this.records.set(o2.id, o2), this.persist(), this.events.emit(R2.created, o2); - }, this.resolve = async (i2) => { - if (this.isInitialized(), this.logger.debug("Updating JSON-RPC response history record"), this.logger.trace({ type: "method", method: "update", response: i2 }), !this.records.has(i2.id)) - return; - const s2 = await this.getRecord(i2.id); - typeof s2.response > "u" && (s2.response = f4.isJsonRpcError(i2) ? { error: i2.error } : { result: i2.result }, this.records.set(s2.id, s2), this.persist(), this.events.emit(R2.updated, s2)); - }, this.get = async (i2, s2) => (this.isInitialized(), this.logger.debug("Getting record"), this.logger.trace({ type: "method", method: "get", topic: i2, id: s2 }), await this.getRecord(s2)), this.delete = (i2, s2) => { - this.isInitialized(), this.logger.debug("Deleting record"), this.logger.trace({ type: "method", method: "delete", id: s2 }), this.values.forEach((r) => { - if (r.topic === i2) { - if (typeof s2 < "u" && r.id !== s2) - return; - this.records.delete(r.id), this.events.emit(R2.deleted, r); - } - }), this.persist(); - }, this.exists = async (i2, s2) => (this.isInitialized(), this.records.has(s2) ? (await this.getRecord(s2)).topic === i2 : false), this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.logger = g3.generateChildLogger(t, this.name); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - get size() { - return this.records.size; - } - get keys() { - return Array.from(this.records.keys()); - } - get values() { - return Array.from(this.records.values()); - } - get pending() { - const e2 = []; - return this.values.forEach((t) => { - if (typeof t.response < "u") - return; - const i2 = { topic: t.topic, request: f4.formatJsonRpcRequest(t.request.method, t.request.params, t.id), chainId: t.chainId }; - return e2.push(i2); - }), e2; - } - async setJsonRpcRecords(e2) { - await this.core.storage.setItem(this.storageKey, e2); - } - async getJsonRpcRecords() { - return await this.core.storage.getItem(this.storageKey); - } - getRecord(e2) { - this.isInitialized(); - const t = this.records.get(e2); - if (!t) { - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw new Error(i2); - } - return t; - } - async persist() { - await this.setJsonRpcRecords(this.values), this.events.emit(R2.sync); - } - async restore() { - try { - const e2 = await this.getJsonRpcRecords(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.records.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", records: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(e2); - } - } - registerEventListeners() { - this.events.on(R2.created, (e2) => { - const t = R2.created; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); - }), this.events.on(R2.updated, (e2) => { - const t = R2.updated; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); - }), this.events.on(R2.deleted, (e2) => { - const t = R2.deleted; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); - }), this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { - this.cleanup(); - }); - } - cleanup() { - try { - this.isInitialized(); - let e2 = false; - this.records.forEach((t) => { - l4.toMiliseconds(t.expiry || 0) - Date.now() <= 0 && (this.logger.info(`Deleting expired history log: ${t.id}`), this.records.delete(t.id), this.events.emit(R2.deleted, t, false), e2 = true); - }), e2 && this.persist(); - } catch (e2) { - this.logger.warn(e2); - } - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var Et = class extends x3.IExpirer { - constructor(e2, t) { - super(e2, t), this.core = e2, this.logger = t, this.expirations = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = We, this.version = Qe, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.expirations.set(i2.target, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); - }, this.has = (i2) => { - try { - const s2 = this.formatTarget(i2); - return typeof this.getExpiration(s2) < "u"; - } catch { - return false; - } - }, this.set = (i2, s2) => { - this.isInitialized(); - const r = this.formatTarget(i2), o2 = { target: r, expiry: s2 }; - this.expirations.set(r, o2), this.checkExpiry(r, o2), this.events.emit(_4.created, { target: r, expiration: o2 }); - }, this.get = (i2) => { - this.isInitialized(); - const s2 = this.formatTarget(i2); - return this.getExpiration(s2); - }, this.del = (i2) => { - if (this.isInitialized(), this.has(i2)) { - const s2 = this.formatTarget(i2), r = this.getExpiration(s2); - this.expirations.delete(s2), this.events.emit(_4.deleted, { target: s2, expiration: r }); - } - }, this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.logger = g3.generateChildLogger(t, this.name); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - get length() { - return this.expirations.size; - } - get keys() { - return Array.from(this.expirations.keys()); - } - get values() { - return Array.from(this.expirations.values()); - } - formatTarget(e2) { - if (typeof e2 == "string") - return a3.formatTopicTarget(e2); - if (typeof e2 == "number") - return a3.formatIdTarget(e2); - const { message: t } = a3.getInternalError("UNKNOWN_TYPE", `Target type: ${typeof e2}`); - throw new Error(t); - } - async setExpirations(e2) { - await this.core.storage.setItem(this.storageKey, e2); - } - async getExpirations() { - return await this.core.storage.getItem(this.storageKey); - } - async persist() { - await this.setExpirations(this.values), this.events.emit(_4.sync); - } - async restore() { - try { - const e2 = await this.getExpirations(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.expirations.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored expirations for ${this.name}`), this.logger.trace({ type: "method", method: "restore", expirations: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore expirations for ${this.name}`), this.logger.error(e2); - } - } - getExpiration(e2) { - const t = this.expirations.get(e2); - if (!t) { - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw this.logger.warn(i2), new Error(i2); - } - return t; - } - checkExpiry(e2, t) { - const { expiry: i2 } = t; - l4.toMiliseconds(i2) - Date.now() <= 0 && this.expire(e2, t); - } - expire(e2, t) { - this.expirations.delete(e2), this.events.emit(_4.expired, { target: e2, expiration: t }); - } - checkExpirations() { - this.core.relayer.connected && this.expirations.forEach((e2, t) => this.checkExpiry(t, e2)); - } - registerEventListeners() { - this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => this.checkExpirations()), this.events.on(_4.created, (e2) => { - const t = _4.created; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); - }), this.events.on(_4.expired, (e2) => { - const t = _4.expired; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); - }), this.events.on(_4.deleted, (e2) => { - const t = _4.deleted; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); - }); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var mt = class extends x3.IVerify { - constructor(e2, t) { - super(e2, t), this.projectId = e2, this.logger = t, this.name = X, this.initialized = false, this.queue = [], this.verifyDisabled = false, this.init = async (i2) => { - if (this.verifyDisabled || a3.isReactNative() || !a3.isBrowser()) - return; - const s2 = this.getVerifyUrl(i2?.verifyUrl); - this.verifyUrl !== s2 && this.removeIframe(), this.verifyUrl = s2; - try { - await this.createIframe(); - } catch (r) { - this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r); - } - if (!this.initialized) { - this.removeIframe(), this.verifyUrl = J; - try { - await this.createIframe(); - } catch (r) { - this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r), this.verifyDisabled = true; - } - } - }, this.register = async (i2) => { - this.initialized ? this.sendPost(i2.attestationId) : (this.addToQueue(i2.attestationId), await this.init()); - }, this.resolve = async (i2) => { - if (this.isDevEnv) - return ""; - const s2 = this.getVerifyUrl(i2?.verifyUrl); - let r; - try { - r = await this.fetchAttestation(i2.attestationId, s2); - } catch (o2) { - this.logger.info(`failed to resolve attestation: ${i2.attestationId} from url: ${s2}`), this.logger.info(o2), r = await this.fetchAttestation(i2.attestationId, J); - } - return r; - }, this.fetchAttestation = async (i2, s2) => { - this.logger.info(`resolving attestation: ${i2} from url: ${s2}`); - const r = this.startAbortTimer(l4.ONE_SECOND * 2), o2 = await fetch(`${s2}/attestation/${i2}`, { signal: this.abortController.signal }); - return clearTimeout(r), o2.status === 200 ? await o2.json() : void 0; - }, this.addToQueue = (i2) => { - this.queue.push(i2); - }, this.processQueue = () => { - this.queue.length !== 0 && (this.queue.forEach((i2) => this.sendPost(i2)), this.queue = []); - }, this.sendPost = (i2) => { - var s2; - try { - if (!this.iframe) - return; - (s2 = this.iframe.contentWindow) == null || s2.postMessage(i2, "*"), this.logger.info(`postMessage sent: ${i2} ${this.verifyUrl}`); - } catch { - } - }, this.createIframe = async () => { - let i2; - const s2 = (r) => { - r.data === "verify_ready" && (this.onInit(), window.removeEventListener("message", s2), i2()); - }; - await Promise.race([new Promise((r) => { - const o2 = document.getElementById(X); - if (o2) - return this.iframe = o2, this.onInit(), r(); - window.addEventListener("message", s2); - const h5 = document.createElement("iframe"); - h5.id = X, h5.src = `${this.verifyUrl}/${this.projectId}`, h5.style.display = "none", document.body.append(h5), this.iframe = h5, i2 = r; - }), new Promise((r, o2) => setTimeout(() => { - window.removeEventListener("message", s2), o2("verify iframe load timeout"); - }, l4.toMiliseconds(l4.FIVE_SECONDS)))]); - }, this.onInit = () => { - this.initialized = true, this.processQueue(); - }, this.removeIframe = () => { - this.iframe && (this.iframe.remove(), this.iframe = void 0, this.initialized = false); - }, this.getVerifyUrl = (i2) => { - let s2 = i2 || B2; - return Ze.includes(s2) || (this.logger.info(`verify url: ${s2}, not included in trusted list, assigning default: ${B2}`), s2 = B2), s2; - }, this.logger = g3.generateChildLogger(t, this.name), this.verifyUrl = B2, this.abortController = new AbortController(), this.isDevEnv = a3.isNode() && import_process.default.env.IS_VITEST; - } - get context() { - return g3.getLoggerContext(this.logger); - } - startAbortTimer(e2) { - return this.abortController = new AbortController(), setTimeout(() => this.abortController.abort(), l4.toMiliseconds(e2)); - } - }; - var bt = class extends x3.IEchoClient { - constructor(e2, t) { - super(e2, t), this.projectId = e2, this.logger = t, this.context = et, this.registerDeviceToken = async (i2) => { - const { clientId: s2, token: r, notificationType: o2, enableEncrypted: h5 = false } = i2, c4 = `${tt}/${this.projectId}/clients`; - await Ut.default(c4, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: s2, type: o2, token: r, always_raw: h5 }) }); - }, this.logger = g3.generateChildLogger(t, this.context); - } - }; - var Rs = Object.defineProperty; - var ft = Object.getOwnPropertySymbols; - var _s = Object.prototype.hasOwnProperty; - var Cs = Object.prototype.propertyIsEnumerable; - var wt = (n3, e2, t) => e2 in n3 ? Rs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var vt = (n3, e2) => { - for (var t in e2 || (e2 = {})) - _s.call(e2, t) && wt(n3, t, e2[t]); - if (ft) - for (var t of ft(e2)) - Cs.call(e2, t) && wt(n3, t, e2[t]); - return n3; - }; - var W = class _W extends x3.ICore { - constructor(e2) { - var t; - super(e2), this.protocol = te, this.version = Re, this.name = H, this.events = new z3.EventEmitter(), this.initialized = false, this.on = (o2, h5) => this.events.on(o2, h5), this.once = (o2, h5) => this.events.once(o2, h5), this.off = (o2, h5) => this.events.off(o2, h5), this.removeListener = (o2, h5) => this.events.removeListener(o2, h5), this.projectId = e2?.projectId, this.relayUrl = e2?.relayUrl || se, this.customStoragePrefix = e2 != null && e2.customStoragePrefix ? `:${e2.customStoragePrefix}` : ""; - const i2 = g3.getDefaultLoggerOptions({ level: typeof e2?.logger == "string" && e2.logger ? e2.logger : _e.logger }), { logger: s2, chunkLoggerController: r } = g3.generatePlatformLogger({ opts: i2, maxSizeInBytes: e2?.maxLogBlobSizeInBytes, loggerOverride: e2?.logger }); - this.logChunkController = r, (t = this.logChunkController) != null && t.downloadLogsBlobInBrowser && (window.downloadLogsBlobInBrowser = async () => { - var o2, h5; - (o2 = this.logChunkController) != null && o2.downloadLogsBlobInBrowser && ((h5 = this.logChunkController) == null || h5.downloadLogsBlobInBrowser({ clientId: await this.crypto.getClientId() })); - }), this.logger = g3.generateChildLogger(s2, this.name), this.heartbeat = new $.HeartBeat(), this.crypto = new st(this, this.logger, e2?.keychain), this.history = new yt(this, this.logger), this.expirer = new Et(this, this.logger), this.storage = e2 != null && e2.storage ? e2.storage : new xt.default(vt(vt({}, Ce), e2?.storageOptions)), this.relayer = new lt({ core: this, logger: this.logger, relayUrl: this.relayUrl, projectId: this.projectId }), this.pairing = new Dt(this, this.logger), this.verify = new mt(this.projectId || "", this.logger), this.echoClient = new bt(this.projectId || "", this.logger); - } - static async init(e2) { - const t = new _W(e2); - await t.initialize(); - const i2 = await t.crypto.getClientId(); - return await t.storage.setItem(Ke, i2), t; - } - get context() { - return g3.getLoggerContext(this.logger); - } - async start() { - this.initialized || await this.initialize(); - } - async getLogsBlob() { - var e2; - return (e2 = this.logChunkController) == null ? void 0 : e2.logsToBlob({ clientId: await this.crypto.getClientId() }); - } - async initialize() { - this.logger.trace("Initialized"); - try { - await this.crypto.init(), await this.history.init(), await this.expirer.init(), await this.relayer.init(), await this.heartbeat.init(), await this.pairing.init(), this.initialized = true, this.logger.info("Core Initialization Success"); - } catch (e2) { - throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`, e2), this.logger.error(e2.message), e2; - } - } - }; - var Ts = W; - exports2.CORE_CONTEXT = H, exports2.CORE_DEFAULT = _e, exports2.CORE_PROTOCOL = te, exports2.CORE_STORAGE_OPTIONS = Ce, exports2.CORE_STORAGE_PREFIX = L2, exports2.CORE_VERSION = Re, exports2.CRYPTO_CLIENT_SEED = ie, exports2.CRYPTO_CONTEXT = Te, exports2.CRYPTO_JWT_TTL = Se, exports2.Core = Ts, exports2.Crypto = st, exports2.ECHO_CONTEXT = et, exports2.ECHO_URL = tt, exports2.EXPIRER_CONTEXT = We, exports2.EXPIRER_DEFAULT_TTL = cs, exports2.EXPIRER_EVENTS = _4, exports2.EXPIRER_STORAGE_VERSION = Qe, exports2.EchoClient = bt, exports2.Expirer = Et, exports2.HISTORY_CONTEXT = Xe, exports2.HISTORY_EVENTS = R2, exports2.HISTORY_STORAGE_VERSION = Je, exports2.JsonRpcHistory = yt, exports2.KEYCHAIN_CONTEXT = Oe, exports2.KEYCHAIN_STORAGE_VERSION = Pe, exports2.KeyChain = it, exports2.MESSAGES_CONTEXT = Ae, exports2.MESSAGES_STORAGE_VERSION = xe, exports2.MessageTracker = rt, exports2.PAIRING_CONTEXT = Ge, exports2.PAIRING_DEFAULT_TTL = hs, exports2.PAIRING_EVENTS = K2, exports2.PAIRING_RPC_OPTS = M, exports2.PAIRING_STORAGE_VERSION = He, exports2.PENDING_SUB_RESOLUTION_TIMEOUT = je, exports2.PUBLISHER_CONTEXT = Le, exports2.PUBLISHER_DEFAULT_TTL = Ne, exports2.Pairing = Dt, exports2.RELAYER_CONTEXT = Fe, exports2.RELAYER_DEFAULT_LOGGER = ze, exports2.RELAYER_DEFAULT_PROTOCOL = Ue, exports2.RELAYER_DEFAULT_RELAY_URL = se, exports2.RELAYER_EVENTS = I2, exports2.RELAYER_FAILOVER_RELAY_URL = re, exports2.RELAYER_PROVIDER_EVENTS = w4, exports2.RELAYER_RECONNECT_TIMEOUT = Be, exports2.RELAYER_SDK_VERSION = $e, exports2.RELAYER_STORAGE_OPTIONS = os, exports2.RELAYER_SUBSCRIBER_SUFFIX = Me, exports2.RELAYER_TRANSPORT_CUTOFF = ke, exports2.Relayer = lt, exports2.STORE_STORAGE_VERSION = Ve, exports2.SUBSCRIBER_CONTEXT = qe, exports2.SUBSCRIBER_DEFAULT_TTL = as, exports2.SUBSCRIBER_EVENTS = S4, exports2.SUBSCRIBER_STORAGE_VERSION = Ye, exports2.Store = pt, exports2.Subscriber = at, exports2.TRUSTED_VERIFY_URLS = Ze, exports2.VERIFY_CONTEXT = X, exports2.VERIFY_FALLBACK_SERVER = J, exports2.VERIFY_SERVER = B2, exports2.Verify = mt, exports2.WALLETCONNECT_CLIENT_ID = Ke, exports2.default = W; - } -}); - -// node_modules/@walletconnect/sign-client/dist/index.cjs.js -var require_index_cjs4 = __commonJS({ - "node_modules/@walletconnect/sign-client/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var N10 = require_index_cjs3(); - var k4 = (init_index_es2(), __toCommonJS(index_es_exports2)); - var oe = require_index_cjs(); - var s2 = require_index_cjs2(); - var ae = require_events(); - var w4 = require_cjs(); - var u3 = (init_esm5(), __toCommonJS(esm_exports4)); - function fe(y4) { - return y4 && typeof y4 == "object" && "default" in y4 ? y4 : { default: y4 }; - } - var qe = fe(ae); - var ee = "wc"; - var te = 2; - var ie = "client"; - var F = `${ee}@${te}:${ie}:`; - var Y = { name: ie, logger: "error", controller: false, relayUrl: "wss://relay.walletconnect.com" }; - var Pe = { session_proposal: "session_proposal", session_update: "session_update", session_extend: "session_extend", session_ping: "session_ping", session_delete: "session_delete", session_expire: "session_expire", session_request: "session_request", session_request_sent: "session_request_sent", session_event: "session_event", proposal_expire: "proposal_expire", session_authenticate: "session_authenticate", session_request_expire: "session_request_expire" }; - var Te = { database: ":memory:" }; - var se = "WALLETCONNECT_DEEPLINK_CHOICE"; - var ve = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; - var Oe = "history"; - var Ae = "0.3"; - var ce = "proposal"; - var Ve = w4.THIRTY_DAYS; - var le = "Proposal expired"; - var he = "session"; - var V = w4.SEVEN_DAYS; - var pe = "engine"; - var q2 = { wc_sessionPropose: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1100 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1101 } }, wc_sessionSettle: { req: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1102 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1103 } }, wc_sessionUpdate: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1104 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1105 } }, wc_sessionExtend: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1106 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1107 } }, wc_sessionRequest: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1108 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1109 } }, wc_sessionEvent: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1110 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1111 } }, wc_sessionDelete: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1112 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1113 } }, wc_sessionPing: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1114 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1115 } }, wc_sessionAuthenticate: { req: { ttl: w4.ONE_HOUR, prompt: true, tag: 1116 }, res: { ttl: w4.ONE_HOUR, prompt: false, tag: 1117 } } }; - var H = { min: w4.FIVE_MINUTES, max: w4.SEVEN_DAYS }; - var A2 = { idle: "IDLE", active: "ACTIVE" }; - var de = "request"; - var ue = ["wc_sessionPropose", "wc_sessionRequest", "wc_authRequest"]; - var ge = "wc"; - var De = 1.5; - var Ee = "auth"; - var we = "authKeys"; - var ye = "pairingTopics"; - var me = "requests"; - var L2 = `${ge}@${1.5}:${Ee}:`; - var U2 = `${L2}:PUB_KEY`; - var Ce = Object.defineProperty; - var xe = Object.defineProperties; - var be = Object.getOwnPropertyDescriptors; - var Se = Object.getOwnPropertySymbols; - var Me = Object.prototype.hasOwnProperty; - var Le = Object.prototype.propertyIsEnumerable; - var Ie = (y4, o2, t) => o2 in y4 ? Ce(y4, o2, { enumerable: true, configurable: true, writable: true, value: t }) : y4[o2] = t; - var S4 = (y4, o2) => { - for (var t in o2 || (o2 = {})) - Me.call(o2, t) && Ie(y4, t, o2[t]); - if (Se) - for (var t of Se(o2)) - Le.call(o2, t) && Ie(y4, t, o2[t]); - return y4; - }; - var C3 = (y4, o2) => xe(y4, be(o2)); - var Ue = class extends oe.IEngine { - constructor(o2) { - super(o2), this.name = pe, this.events = new qe.default(), this.initialized = false, this.requestQueue = { state: A2.idle, queue: [] }, this.sessionRequestQueue = { state: A2.idle, queue: [] }, this.requestQueueDelay = w4.ONE_SECOND, this.expectedPairingMethodMap = /* @__PURE__ */ new Map(), this.recentlyDeletedMap = /* @__PURE__ */ new Map(), this.recentlyDeletedLimit = 200, this.init = async () => { - this.initialized || (await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.registerPairingEvents(), this.client.core.pairing.register({ methods: Object.keys(q2) }), this.initialized = true, setTimeout(() => { - this.sessionRequestQueue.queue = this.getPendingSessionRequests(), this.processSessionRequestQueue(); - }, w4.toMiliseconds(this.requestQueueDelay))); - }, this.connect = async (t) => { - await this.isInitialized(); - const e2 = C3(S4({}, t), { requiredNamespaces: t.requiredNamespaces || {}, optionalNamespaces: t.optionalNamespaces || {} }); - await this.isValidConnect(e2); - const { pairingTopic: i2, requiredNamespaces: r, optionalNamespaces: n3, sessionProperties: a3, relays: c4 } = e2; - let l4 = i2, d3, p3 = false; - try { - l4 && (p3 = this.client.core.pairing.pairings.get(l4).active); - } catch (f4) { - throw this.client.logger.error(`connect() -> pairing.get(${l4}) failed`), f4; - } - if (!l4 || !p3) { - const { topic: f4, uri: T2 } = await this.client.core.pairing.create(); - l4 = f4, d3 = T2; - } - if (!l4) { - const { message: f4 } = s2.getInternalError("NO_MATCHING_KEY", `connect() pairing topic: ${l4}`); - throw new Error(f4); - } - const g3 = await this.client.core.crypto.generateKeyPair(), h5 = q2.wc_sessionPropose.req.ttl || w4.FIVE_MINUTES, m3 = s2.calcExpiry(h5), E4 = S4({ requiredNamespaces: r, optionalNamespaces: n3, relays: c4 ?? [{ protocol: N10.RELAYER_DEFAULT_PROTOCOL }], proposer: { publicKey: g3, metadata: this.client.metadata }, expiryTimestamp: m3 }, a3 && { sessionProperties: a3 }), { reject: R2, resolve: O3, done: I2 } = s2.createDelayedPromise(h5, le); - this.events.once(s2.engineEvent("session_connect"), async ({ error: f4, session: T2 }) => { - if (f4) - R2(f4); - else if (T2) { - T2.self.publicKey = g3; - const x3 = C3(S4({}, T2), { requiredNamespaces: E4.requiredNamespaces, optionalNamespaces: E4.optionalNamespaces }); - await this.client.session.set(T2.topic, x3), await this.setExpiry(T2.topic, T2.expiry), l4 && await this.client.core.pairing.updateMetadata({ topic: l4, metadata: T2.peer.metadata }), O3(x3); - } - }); - const P2 = await this.sendRequest({ topic: l4, method: "wc_sessionPropose", params: E4, throwOnFailedPublish: true }); - return await this.setProposal(P2, S4({ id: P2 }, E4)), { uri: d3, approval: I2 }; - }, this.pair = async (t) => { - await this.isInitialized(); - try { - return await this.client.core.pairing.pair(t); - } catch (e2) { - throw this.client.logger.error("pair() failed"), e2; - } - }, this.approve = async (t) => { - await this.isInitialized(); - try { - await this.isValidApprove(t); - } catch (I2) { - throw this.client.logger.error("approve() -> isValidApprove() failed"), I2; - } - const { id: e2, relayProtocol: i2, namespaces: r, sessionProperties: n3, sessionConfig: a3 } = t; - let c4; - try { - c4 = this.client.proposal.get(e2); - } catch (I2) { - throw this.client.logger.error(`approve() -> proposal.get(${e2}) failed`), I2; - } - let { pairingTopic: l4, proposer: d3, requiredNamespaces: p3, optionalNamespaces: g3 } = c4; - l4 = l4 || ""; - const h5 = await this.client.core.crypto.generateKeyPair(), m3 = d3.publicKey, E4 = await this.client.core.crypto.generateSharedKey(h5, m3), R2 = S4(S4({ relay: { protocol: i2 ?? "irn" }, namespaces: r, pairingTopic: l4, controller: { publicKey: h5, metadata: this.client.metadata }, expiry: s2.calcExpiry(V) }, n3 && { sessionProperties: n3 }), a3 && { sessionConfig: a3 }); - await this.client.core.relayer.subscribe(E4); - const O3 = C3(S4({}, R2), { topic: E4, requiredNamespaces: p3, optionalNamespaces: g3, pairingTopic: l4, acknowledged: false, self: R2.controller, peer: { publicKey: d3.publicKey, metadata: d3.metadata }, controller: h5 }); - await this.client.session.set(E4, O3); - try { - await this.sendResult({ id: e2, topic: l4, result: { relay: { protocol: i2 ?? "irn" }, responderPublicKey: h5 }, throwOnFailedPublish: true }), await this.sendRequest({ topic: E4, method: "wc_sessionSettle", params: R2, throwOnFailedPublish: true }); - } catch (I2) { - throw this.client.logger.error(I2), this.client.session.delete(E4, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.relayer.unsubscribe(E4), I2; - } - return await this.client.core.pairing.updateMetadata({ topic: l4, metadata: d3.metadata }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.pairing.activate({ topic: l4 }), await this.setExpiry(E4, s2.calcExpiry(V)), { topic: E4, acknowledged: () => new Promise((I2) => setTimeout(() => I2(this.client.session.get(E4)), 500)) }; - }, this.reject = async (t) => { - await this.isInitialized(); - try { - await this.isValidReject(t); - } catch (n3) { - throw this.client.logger.error("reject() -> isValidReject() failed"), n3; - } - const { id: e2, reason: i2 } = t; - let r; - try { - r = this.client.proposal.get(e2).pairingTopic; - } catch (n3) { - throw this.client.logger.error(`reject() -> proposal.get(${e2}) failed`), n3; - } - r && (await this.sendError({ id: e2, topic: r, error: i2 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED"))); - }, this.update = async (t) => { - await this.isInitialized(); - try { - await this.isValidUpdate(t); - } catch (p3) { - throw this.client.logger.error("update() -> isValidUpdate() failed"), p3; - } - const { topic: e2, namespaces: i2 } = t, { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), d3 = this.client.session.get(e2).namespaces; - return this.events.once(s2.engineEvent("session_update", c4), ({ error: p3 }) => { - p3 ? a3(p3) : n3(); - }), await this.client.session.update(e2, { namespaces: i2 }), this.sendRequest({ topic: e2, method: "wc_sessionUpdate", params: { namespaces: i2 }, throwOnFailedPublish: true, clientRpcId: c4, relayRpcId: l4 }).catch((p3) => { - this.client.logger.error(p3), this.client.session.update(e2, { namespaces: d3 }), a3(p3); - }), { acknowledged: r }; - }, this.extend = async (t) => { - await this.isInitialized(); - try { - await this.isValidExtend(t); - } catch (c4) { - throw this.client.logger.error("extend() -> isValidExtend() failed"), c4; - } - const { topic: e2 } = t, i2 = u3.payloadId(), { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(); - return this.events.once(s2.engineEvent("session_extend", i2), ({ error: c4 }) => { - c4 ? a3(c4) : n3(); - }), await this.setExpiry(e2, s2.calcExpiry(V)), this.sendRequest({ topic: e2, method: "wc_sessionExtend", params: {}, clientRpcId: i2, throwOnFailedPublish: true }).catch((c4) => { - a3(c4); - }), { acknowledged: r }; - }, this.request = async (t) => { - await this.isInitialized(); - try { - await this.isValidRequest(t); - } catch (h5) { - throw this.client.logger.error("request() -> isValidRequest() failed"), h5; - } - const { chainId: e2, request: i2, topic: r, expiry: n3 = q2.wc_sessionRequest.req.ttl } = t, a3 = this.client.session.get(r), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), { done: d3, resolve: p3, reject: g3 } = s2.createDelayedPromise(n3, "Request expired. Please try again."); - return this.events.once(s2.engineEvent("session_request", c4), ({ error: h5, result: m3 }) => { - h5 ? g3(h5) : p3(m3); - }), await Promise.all([new Promise(async (h5) => { - await this.sendRequest({ clientRpcId: c4, relayRpcId: l4, topic: r, method: "wc_sessionRequest", params: { request: C3(S4({}, i2), { expiryTimestamp: s2.calcExpiry(n3) }), chainId: e2 }, expiry: n3, throwOnFailedPublish: true }).catch((m3) => g3(m3)), this.client.events.emit("session_request_sent", { topic: r, request: i2, chainId: e2, id: c4 }), h5(); - }), new Promise(async (h5) => { - var m3; - if (!((m3 = a3.sessionConfig) != null && m3.disableDeepLink)) { - const E4 = await s2.getDeepLink(this.client.core.storage, se); - s2.handleDeeplinkRedirect({ id: c4, topic: r, wcDeepLink: E4 }); - } - h5(); - }), d3()]).then((h5) => h5[2]); - }, this.respond = async (t) => { - await this.isInitialized(), await this.isValidRespond(t); - const { topic: e2, response: i2 } = t, { id: r } = i2; - u3.isJsonRpcResult(i2) ? await this.sendResult({ id: r, topic: e2, result: i2.result, throwOnFailedPublish: true }) : u3.isJsonRpcError(i2) && await this.sendError({ id: r, topic: e2, error: i2.error }), this.cleanupAfterResponse(t); - }, this.ping = async (t) => { - await this.isInitialized(); - try { - await this.isValidPing(t); - } catch (i2) { - throw this.client.logger.error("ping() -> isValidPing() failed"), i2; - } - const { topic: e2 } = t; - if (this.client.session.keys.includes(e2)) { - const i2 = u3.payloadId(), r = u3.getBigIntRpcId().toString(), { done: n3, resolve: a3, reject: c4 } = s2.createDelayedPromise(); - this.events.once(s2.engineEvent("session_ping", i2), ({ error: l4 }) => { - l4 ? c4(l4) : a3(); - }), await Promise.all([this.sendRequest({ topic: e2, method: "wc_sessionPing", params: {}, throwOnFailedPublish: true, clientRpcId: i2, relayRpcId: r }), n3()]); - } else - this.client.core.pairing.pairings.keys.includes(e2) && await this.client.core.pairing.ping({ topic: e2 }); - }, this.emit = async (t) => { - await this.isInitialized(), await this.isValidEmit(t); - const { topic: e2, event: i2, chainId: r } = t, n3 = u3.getBigIntRpcId().toString(); - await this.sendRequest({ topic: e2, method: "wc_sessionEvent", params: { event: i2, chainId: r }, throwOnFailedPublish: true, relayRpcId: n3 }); - }, this.disconnect = async (t) => { - await this.isInitialized(), await this.isValidDisconnect(t); - const { topic: e2 } = t; - if (this.client.session.keys.includes(e2)) - await this.sendRequest({ topic: e2, method: "wc_sessionDelete", params: s2.getSdkError("USER_DISCONNECTED"), throwOnFailedPublish: true }), await this.deleteSession({ topic: e2, emitEvent: false }); - else if (this.client.core.pairing.pairings.keys.includes(e2)) - await this.client.core.pairing.disconnect({ topic: e2 }); - else { - const { message: i2 } = s2.getInternalError("MISMATCHED_TOPIC", `Session or pairing topic not found: ${e2}`); - throw new Error(i2); - } - }, this.find = (t) => (this.isInitialized(), this.client.session.getAll().filter((e2) => s2.isSessionCompatible(e2, t))), this.getPendingSessionRequests = () => this.client.pendingRequest.getAll(), this.authenticate = async (t) => { - this.isInitialized(), this.isValidAuthenticate(t); - const { chains: e2, statement: i2 = "", uri: r, domain: n3, nonce: a3, type: c4, exp: l4, nbf: d3, methods: p3 = [] } = t, g3 = [...t.resources || []], { topic: h5, uri: m3 } = await this.client.core.pairing.create({ methods: ["wc_sessionAuthenticate"] }); - this.client.logger.info({ message: "Generated new pairing", pairing: { topic: h5, uri: m3 } }); - const E4 = await this.client.core.crypto.generateKeyPair(), R2 = s2.hashKey(E4); - if (await Promise.all([this.client.auth.authKeys.set(U2, { responseTopic: R2, publicKey: E4 }), this.client.auth.pairingTopics.set(R2, { topic: R2, pairingTopic: h5 })]), await this.client.core.relayer.subscribe(R2), this.client.logger.info(`sending request to new pairing topic: ${h5}`), p3.length > 0) { - const { namespace: v2 } = s2.parseChainId(e2[0]); - let _4 = s2.createEncodedRecap(v2, "request", p3); - s2.getRecapFromResources(g3) && (_4 = s2.mergeEncodedRecaps(_4, g3.pop())), g3.push(_4); - } - const O3 = s2.calcExpiry(q2.wc_sessionPropose.req.ttl), I2 = { authPayload: { type: c4 ?? "caip122", chains: e2, statement: i2, aud: r, domain: n3, version: "1", nonce: a3, iat: (/* @__PURE__ */ new Date()).toISOString(), exp: l4, nbf: d3, resources: g3 }, requester: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, P2 = { eip155: { chains: e2, methods: [.../* @__PURE__ */ new Set(["personal_sign", ...p3])], events: ["chainChanged", "accountsChanged"] } }, f4 = { requiredNamespaces: {}, optionalNamespaces: P2, relays: [{ protocol: "irn" }], proposer: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, { done: T2, resolve: x3, reject: Q } = s2.createDelayedPromise(q2.wc_sessionAuthenticate.req.ttl, "Request expired"), $ = async ({ error: v2, session: _4 }) => { - if (this.events.off(s2.engineEvent("session_request", D2), X), v2) - Q(v2); - else if (_4) { - _4.self.publicKey = E4, await this.client.session.set(_4.topic, _4), await this.setExpiry(_4.topic, _4.expiry), h5 && await this.client.core.pairing.updateMetadata({ topic: h5, metadata: _4.peer.metadata }); - const b4 = this.client.session.get(_4.topic); - x3({ session: b4 }); - } - }, X = async (v2) => { - if (v2.error) { - const M = s2.getSdkError("WC_METHOD_UNSUPPORTED", "wc_sessionAuthenticate"); - return v2.error.code === M.code ? void 0 : (this.events.off(s2.engineEvent("session_connect"), $), Q(v2.error.message)); - } - this.events.off(s2.engineEvent("session_connect"), $); - const { cacaos: _4, responder: b4 } = v2.result, z3 = [], re = []; - for (const M of _4) { - await s2.validateSignedCacao({ cacao: M, projectId: this.client.core.projectId }) || (this.client.logger.error(M, "Signature verification failed"), Q(s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"))); - const { p: B2 } = M, W = s2.getRecapFromResources(B2.resources), ne = [s2.getNamespacedDidChainId(B2.iss)], Re = s2.getDidAddress(B2.iss); - if (W) { - const Z = s2.getMethodsFromRecap(W), Ne = s2.getChainsFromRecap(W); - z3.push(...Z), ne.push(...Ne); - } - for (const Z of ne) - re.push(`${Z}:${Re}`); - } - const G = await this.client.core.crypto.generateSharedKey(E4, b4.publicKey); - let K2; - z3.length > 0 && (K2 = { topic: G, acknowledged: true, self: { publicKey: E4, metadata: this.client.metadata }, peer: b4, controller: b4.publicKey, expiry: s2.calcExpiry(V), requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: h5, namespaces: s2.buildNamespacesFromAuth([...new Set(z3)], [...new Set(re)]) }, await this.client.core.relayer.subscribe(G), await this.client.session.set(G, K2), K2 = this.client.session.get(G)), x3({ auths: _4, session: K2 }); - }, D2 = u3.payloadId(), J = u3.payloadId(); - this.events.once(s2.engineEvent("session_connect"), $), this.events.once(s2.engineEvent("session_request", D2), X); - try { - await Promise.all([this.sendRequest({ topic: h5, method: "wc_sessionAuthenticate", params: I2, expiry: t.expiry, throwOnFailedPublish: true, clientRpcId: D2 }), this.sendRequest({ topic: h5, method: "wc_sessionPropose", params: f4, expiry: q2.wc_sessionPropose.req.ttl, throwOnFailedPublish: true, clientRpcId: J })]); - } catch (v2) { - throw this.events.off(s2.engineEvent("session_connect"), $), this.events.off(s2.engineEvent("session_request", D2), X), v2; - } - return await this.setProposal(J, S4({ id: J }, f4)), await this.client.auth.requests.set(D2, { authPayload: I2.authPayload, requester: I2.requester, expiryTimestamp: O3, id: D2, pairingTopic: h5, verifyContext: {} }), { uri: m3, response: T2 }; - }, this.approveSessionAuthenticate = async (t) => { - this.isInitialized(); - const { id: e2, auths: i2 } = t, r = this.getPendingAuthRequest(e2); - if (!r) - throw new Error(`Could not find pending auth request with id ${e2}`); - const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }, d3 = [], p3 = []; - for (const m3 of i2) { - if (!await s2.validateSignedCacao({ cacao: m3, projectId: this.client.core.projectId })) { - const P2 = s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"); - throw await this.sendError({ id: e2, topic: c4, error: P2, encodeOpts: l4 }), new Error(P2.message); - } - const { p: E4 } = m3, R2 = s2.getRecapFromResources(E4.resources), O3 = [s2.getNamespacedDidChainId(E4.iss)], I2 = s2.getDidAddress(E4.iss); - if (R2) { - const P2 = s2.getMethodsFromRecap(R2), f4 = s2.getChainsFromRecap(R2); - d3.push(...P2), O3.push(...f4); - } - for (const P2 of O3) - p3.push(`${P2}:${I2}`); - } - const g3 = await this.client.core.crypto.generateSharedKey(a3, n3); - let h5; - return d3?.length > 0 && (h5 = { topic: g3, acknowledged: true, self: { publicKey: a3, metadata: this.client.metadata }, peer: { publicKey: n3, metadata: r.requester.metadata }, controller: n3, expiry: s2.calcExpiry(V), authentication: i2, requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: "", namespaces: s2.buildNamespacesFromAuth([...new Set(d3)], [...new Set(p3)]) }, await this.client.core.relayer.subscribe(g3), await this.client.session.set(g3, h5)), await this.sendResult({ topic: c4, id: e2, result: { cacaos: i2, responder: { publicKey: a3, metadata: this.client.metadata } }, encodeOpts: l4, throwOnFailedPublish: true }), await this.client.auth.requests.delete(e2, { message: "fullfilled", code: 0 }), await this.client.core.pairing.activate({ topic: r.pairingTopic }), { session: h5 }; - }, this.rejectSessionAuthenticate = async (t) => { - await this.isInitialized(); - const { id: e2, reason: i2 } = t, r = this.getPendingAuthRequest(e2); - if (!r) - throw new Error(`Could not find pending auth request with id ${e2}`); - const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }; - await this.sendError({ id: e2, topic: c4, error: i2, encodeOpts: l4 }), await this.client.auth.requests.delete(e2, { message: "rejected", code: 0 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")); - }, this.formatAuthMessage = (t) => { - this.isInitialized(); - const { request: e2, iss: i2 } = t; - return s2.formatMessage(e2, i2); - }, this.cleanupDuplicatePairings = async (t) => { - if (t.pairingTopic) - try { - const e2 = this.client.core.pairing.pairings.get(t.pairingTopic), i2 = this.client.core.pairing.pairings.getAll().filter((r) => { - var n3, a3; - return ((n3 = r.peerMetadata) == null ? void 0 : n3.url) && ((a3 = r.peerMetadata) == null ? void 0 : a3.url) === t.peer.metadata.url && r.topic && r.topic !== e2.topic; - }); - if (i2.length === 0) - return; - this.client.logger.info(`Cleaning up ${i2.length} duplicate pairing(s)`), await Promise.all(i2.map((r) => this.client.core.pairing.disconnect({ topic: r.topic }))), this.client.logger.info("Duplicate pairings clean up finished"); - } catch (e2) { - this.client.logger.error(e2); - } - }, this.deleteSession = async (t) => { - const { topic: e2, expirerHasDeleted: i2 = false, emitEvent: r = true, id: n3 = 0 } = t, { self: a3 } = this.client.session.get(e2); - await this.client.core.relayer.unsubscribe(e2), await this.client.session.delete(e2, s2.getSdkError("USER_DISCONNECTED")), this.addToRecentlyDeleted(e2, "session"), this.client.core.crypto.keychain.has(a3.publicKey) && await this.client.core.crypto.deleteKeyPair(a3.publicKey), this.client.core.crypto.keychain.has(e2) && await this.client.core.crypto.deleteSymKey(e2), i2 || this.client.core.expirer.del(e2), this.client.core.storage.removeItem(se).catch((c4) => this.client.logger.warn(c4)), this.getPendingSessionRequests().forEach((c4) => { - c4.topic === e2 && this.deletePendingSessionRequest(c4.id, s2.getSdkError("USER_DISCONNECTED")); - }), r && this.client.events.emit("session_delete", { id: n3, topic: e2 }); - }, this.deleteProposal = async (t, e2) => { - await Promise.all([this.client.proposal.delete(t, s2.getSdkError("USER_DISCONNECTED")), e2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "proposal"); - }, this.deletePendingSessionRequest = async (t, e2, i2 = false) => { - await Promise.all([this.client.pendingRequest.delete(t, e2), i2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "request"), this.sessionRequestQueue.queue = this.sessionRequestQueue.queue.filter((r) => r.id !== t), i2 && (this.sessionRequestQueue.state = A2.idle, this.client.events.emit("session_request_expire", { id: t })); - }, this.setExpiry = async (t, e2) => { - this.client.session.keys.includes(t) && await this.client.session.update(t, { expiry: e2 }), this.client.core.expirer.set(t, e2); - }, this.setProposal = async (t, e2) => { - await this.client.proposal.set(t, e2), this.client.core.expirer.set(t, s2.calcExpiry(q2.wc_sessionPropose.req.ttl)); - }, this.setPendingSessionRequest = async (t) => { - const { id: e2, topic: i2, params: r, verifyContext: n3 } = t, a3 = r.request.expiryTimestamp || s2.calcExpiry(q2.wc_sessionRequest.req.ttl); - await this.client.pendingRequest.set(e2, { id: e2, topic: i2, params: r, verifyContext: n3 }), a3 && this.client.core.expirer.set(e2, a3); - }, this.sendRequest = async (t) => { - const { topic: e2, method: i2, params: r, expiry: n3, relayRpcId: a3, clientRpcId: c4, throwOnFailedPublish: l4 } = t, d3 = u3.formatJsonRpcRequest(i2, r, c4); - if (s2.isBrowser() && ue.includes(i2)) { - const h5 = s2.hashMessage(JSON.stringify(d3)); - this.client.core.verify.register({ attestationId: h5 }); - } - let p3; - try { - p3 = await this.client.core.crypto.encode(e2, d3); - } catch (h5) { - throw await this.cleanup(), this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${e2} failed`), h5; - } - const g3 = q2[i2].req; - return n3 && (g3.ttl = n3), a3 && (g3.id = a3), this.client.core.history.set(e2, d3), l4 ? (g3.internal = C3(S4({}, g3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(e2, p3, g3)) : this.client.core.relayer.publish(e2, p3, g3).catch((h5) => this.client.logger.error(h5)), d3.id; - }, this.sendResult = async (t) => { - const { id: e2, topic: i2, result: r, throwOnFailedPublish: n3, encodeOpts: a3 } = t, c4 = u3.formatJsonRpcResult(e2, r); - let l4; - try { - l4 = await this.client.core.crypto.encode(i2, c4, a3); - } catch (g3) { - throw await this.cleanup(), this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i2} failed`), g3; - } - let d3; - try { - d3 = await this.client.core.history.get(i2, e2); - } catch (g3) { - throw this.client.logger.error(`sendResult() -> history.get(${i2}, ${e2}) failed`), g3; - } - const p3 = q2[d3.request.method].res; - n3 ? (p3.internal = C3(S4({}, p3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(i2, l4, p3)) : this.client.core.relayer.publish(i2, l4, p3).catch((g3) => this.client.logger.error(g3)), await this.client.core.history.resolve(c4); - }, this.sendError = async (t) => { - const { id: e2, topic: i2, error: r, encodeOpts: n3 } = t, a3 = u3.formatJsonRpcError(e2, r); - let c4; - try { - c4 = await this.client.core.crypto.encode(i2, a3, n3); - } catch (p3) { - throw await this.cleanup(), this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i2} failed`), p3; - } - let l4; - try { - l4 = await this.client.core.history.get(i2, e2); - } catch (p3) { - throw this.client.logger.error(`sendError() -> history.get(${i2}, ${e2}) failed`), p3; - } - const d3 = q2[l4.request.method].res; - this.client.core.relayer.publish(i2, c4, d3), await this.client.core.history.resolve(a3); - }, this.cleanup = async () => { - const t = [], e2 = []; - this.client.session.getAll().forEach((i2) => { - let r = false; - s2.isExpired(i2.expiry) && (r = true), this.client.core.crypto.keychain.has(i2.topic) || (r = true), r && t.push(i2.topic); - }), this.client.proposal.getAll().forEach((i2) => { - s2.isExpired(i2.expiryTimestamp) && e2.push(i2.id); - }), await Promise.all([...t.map((i2) => this.deleteSession({ topic: i2 })), ...e2.map((i2) => this.deleteProposal(i2))]); - }, this.onRelayEventRequest = async (t) => { - this.requestQueue.queue.push(t), await this.processRequestsQueue(); - }, this.processRequestsQueue = async () => { - if (this.requestQueue.state === A2.active) { - this.client.logger.info("Request queue already active, skipping..."); - return; - } - for (this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`); this.requestQueue.queue.length > 0; ) { - this.requestQueue.state = A2.active; - const t = this.requestQueue.queue.shift(); - if (t) - try { - this.processRequest(t), await new Promise((e2) => setTimeout(e2, 300)); - } catch (e2) { - this.client.logger.warn(e2); - } - } - this.requestQueue.state = A2.idle; - }, this.processRequest = (t) => { - const { topic: e2, payload: i2 } = t, r = i2.method; - if (!this.shouldIgnorePairingRequest({ topic: e2, requestMethod: r })) - switch (r) { - case "wc_sessionPropose": - return this.onSessionProposeRequest(e2, i2); - case "wc_sessionSettle": - return this.onSessionSettleRequest(e2, i2); - case "wc_sessionUpdate": - return this.onSessionUpdateRequest(e2, i2); - case "wc_sessionExtend": - return this.onSessionExtendRequest(e2, i2); - case "wc_sessionPing": - return this.onSessionPingRequest(e2, i2); - case "wc_sessionDelete": - return this.onSessionDeleteRequest(e2, i2); - case "wc_sessionRequest": - return this.onSessionRequest(e2, i2); - case "wc_sessionEvent": - return this.onSessionEventRequest(e2, i2); - case "wc_sessionAuthenticate": - return this.onSessionAuthenticateRequest(e2, i2); - default: - return this.client.logger.info(`Unsupported request method ${r}`); - } - }, this.onRelayEventResponse = async (t) => { - const { topic: e2, payload: i2 } = t, r = (await this.client.core.history.get(e2, i2.id)).request.method; - switch (r) { - case "wc_sessionPropose": - return this.onSessionProposeResponse(e2, i2); - case "wc_sessionSettle": - return this.onSessionSettleResponse(e2, i2); - case "wc_sessionUpdate": - return this.onSessionUpdateResponse(e2, i2); - case "wc_sessionExtend": - return this.onSessionExtendResponse(e2, i2); - case "wc_sessionPing": - return this.onSessionPingResponse(e2, i2); - case "wc_sessionRequest": - return this.onSessionRequestResponse(e2, i2); - case "wc_sessionAuthenticate": - return this.onSessionAuthenticateResponse(e2, i2); - default: - return this.client.logger.info(`Unsupported response method ${r}`); - } - }, this.onRelayEventUnknownPayload = (t) => { - const { topic: e2 } = t, { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Decoded payload on topic ${e2} is not identifiable as a JSON-RPC request or a response.`); - throw new Error(i2); - }, this.shouldIgnorePairingRequest = (t) => { - const { topic: e2, requestMethod: i2 } = t, r = this.expectedPairingMethodMap.get(e2); - return !r || r.includes(i2) ? false : !!(r.includes("wc_sessionAuthenticate") && this.client.events.listenerCount("session_authenticate") > 0); - }, this.onSessionProposeRequest = async (t, e2) => { - const { params: i2, id: r } = e2; - try { - this.isValidConnect(S4({}, e2.params)); - const n3 = i2.expiryTimestamp || s2.calcExpiry(q2.wc_sessionPropose.req.ttl), a3 = S4({ id: r, pairingTopic: t, expiryTimestamp: n3 }, i2); - await this.setProposal(r, a3); - const c4 = s2.hashMessage(JSON.stringify(e2)), l4 = await this.getVerifyContext(c4, a3.proposer.metadata); - this.client.events.emit("session_proposal", { id: r, params: a3, verifyContext: l4 }); - } catch (n3) { - await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionProposeResponse = async (t, e2) => { - const { id: i2 } = e2; - if (u3.isJsonRpcResult(e2)) { - const { result: r } = e2; - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", result: r }); - const n3 = this.client.proposal.get(i2); - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", proposal: n3 }); - const a3 = n3.proposer.publicKey; - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", selfPublicKey: a3 }); - const c4 = r.responderPublicKey; - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", peerPublicKey: c4 }); - const l4 = await this.client.core.crypto.generateSharedKey(a3, c4); - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", sessionTopic: l4 }); - const d3 = await this.client.core.relayer.subscribe(l4); - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", subscriptionId: d3 }), await this.client.core.pairing.activate({ topic: t }); - } else if (u3.isJsonRpcError(e2)) { - await this.client.proposal.delete(i2, s2.getSdkError("USER_DISCONNECTED")); - const r = s2.engineEvent("session_connect"); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners, 954`); - this.events.emit(s2.engineEvent("session_connect"), { error: e2.error }); - } - }, this.onSessionSettleRequest = async (t, e2) => { - const { id: i2, params: r } = e2; - try { - this.isValidSessionSettleRequest(r); - const { relay: n3, controller: a3, expiry: c4, namespaces: l4, sessionProperties: d3, pairingTopic: p3, sessionConfig: g3 } = e2.params, h5 = S4(S4({ topic: t, relay: n3, expiry: c4, namespaces: l4, acknowledged: true, pairingTopic: p3, requiredNamespaces: {}, optionalNamespaces: {}, controller: a3.publicKey, self: { publicKey: "", metadata: this.client.metadata }, peer: { publicKey: a3.publicKey, metadata: a3.metadata } }, d3 && { sessionProperties: d3 }), g3 && { sessionConfig: g3 }); - await this.sendResult({ id: e2.id, topic: t, result: true, throwOnFailedPublish: true }); - const m3 = s2.engineEvent("session_connect"); - if (this.events.listenerCount(m3) === 0) - throw new Error(`emitting ${m3} without any listeners 997`); - this.events.emit(s2.engineEvent("session_connect"), { session: h5 }), this.cleanupDuplicatePairings(h5); - } catch (n3) { - await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionSettleResponse = async (t, e2) => { - const { id: i2 } = e2; - u3.isJsonRpcResult(e2) ? (await this.client.session.update(t, { acknowledged: true }), this.events.emit(s2.engineEvent("session_approve", i2), {})) : u3.isJsonRpcError(e2) && (await this.client.session.delete(t, s2.getSdkError("USER_DISCONNECTED")), this.events.emit(s2.engineEvent("session_approve", i2), { error: e2.error })); - }, this.onSessionUpdateRequest = async (t, e2) => { - const { params: i2, id: r } = e2; - try { - const n3 = `${t}_session_update`, a3 = s2.MemoryStore.get(n3); - if (a3 && this.isRequestOutOfSync(a3, r)) { - this.client.logger.info(`Discarding out of sync request - ${r}`), this.sendError({ id: r, topic: t, error: s2.getSdkError("INVALID_UPDATE_REQUEST") }); - return; - } - this.isValidUpdate(S4({ topic: t }, i2)); - try { - s2.MemoryStore.set(n3, r), await this.client.session.update(t, { namespaces: i2.namespaces }), await this.sendResult({ id: r, topic: t, result: true, throwOnFailedPublish: true }); - } catch (c4) { - throw s2.MemoryStore.delete(n3), c4; - } - this.client.events.emit("session_update", { id: r, topic: t, params: i2 }); - } catch (n3) { - await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.isRequestOutOfSync = (t, e2) => parseInt(e2.toString().slice(0, -3)) <= parseInt(t.toString().slice(0, -3)), this.onSessionUpdateResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_update", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_update", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_update", i2), { error: e2.error }); - }, this.onSessionExtendRequest = async (t, e2) => { - const { id: i2 } = e2; - try { - this.isValidExtend({ topic: t }), await this.setExpiry(t, s2.calcExpiry(V)), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_extend", { id: i2, topic: t }); - } catch (r) { - await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); - } - }, this.onSessionExtendResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_extend", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_extend", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_extend", i2), { error: e2.error }); - }, this.onSessionPingRequest = async (t, e2) => { - const { id: i2 } = e2; - try { - this.isValidPing({ topic: t }), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_ping", { id: i2, topic: t }); - } catch (r) { - await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); - } - }, this.onSessionPingResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_ping", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - setTimeout(() => { - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_ping", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_ping", i2), { error: e2.error }); - }, 500); - }, this.onSessionDeleteRequest = async (t, e2) => { - const { id: i2 } = e2; - try { - this.isValidDisconnect({ topic: t, reason: e2.params }), await Promise.all([new Promise((r) => { - this.client.core.relayer.once(N10.RELAYER_EVENTS.publish, async () => { - r(await this.deleteSession({ topic: t, id: i2 })); - }); - }), this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.cleanupPendingSentRequestsForTopic({ topic: t, error: s2.getSdkError("USER_DISCONNECTED") })]); - } catch (r) { - this.client.logger.error(r); - } - }, this.onSessionRequest = async (t, e2) => { - const { id: i2, params: r } = e2; - try { - await this.isValidRequest(S4({ topic: t }, r)); - const n3 = s2.hashMessage(JSON.stringify(u3.formatJsonRpcRequest("wc_sessionRequest", r, i2))), a3 = this.client.session.get(t), c4 = await this.getVerifyContext(n3, a3.peer.metadata), l4 = { id: i2, topic: t, params: r, verifyContext: c4 }; - await this.setPendingSessionRequest(l4), this.addSessionRequestToSessionRequestQueue(l4), this.processSessionRequestQueue(); - } catch (n3) { - await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionRequestResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_request", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); - }, this.onSessionEventRequest = async (t, e2) => { - const { id: i2, params: r } = e2; - try { - const n3 = `${t}_session_event_${r.event.name}`, a3 = s2.MemoryStore.get(n3); - if (a3 && this.isRequestOutOfSync(a3, i2)) { - this.client.logger.info(`Discarding out of sync request - ${i2}`); - return; - } - this.isValidEmit(S4({ topic: t }, r)), this.client.events.emit("session_event", { id: i2, topic: t, params: r }), s2.MemoryStore.set(n3, i2); - } catch (n3) { - await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionAuthenticateResponse = (t, e2) => { - const { id: i2 } = e2; - this.client.logger.trace({ type: "method", method: "onSessionAuthenticateResponse", topic: t, payload: e2 }), u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); - }, this.onSessionAuthenticateRequest = async (t, e2) => { - const { requester: i2, authPayload: r, expiryTimestamp: n3 } = e2.params, a3 = s2.hashMessage(JSON.stringify(e2)), c4 = await this.getVerifyContext(a3, this.client.metadata), l4 = { requester: i2, pairingTopic: t, id: e2.id, authPayload: r, verifyContext: c4, expiryTimestamp: n3 }; - await this.client.auth.requests.set(e2.id, l4), this.client.events.emit("session_authenticate", { topic: t, params: e2.params, id: e2.id }); - }, this.addSessionRequestToSessionRequestQueue = (t) => { - this.sessionRequestQueue.queue.push(t); - }, this.cleanupAfterResponse = (t) => { - this.deletePendingSessionRequest(t.response.id, { message: "fulfilled", code: 0 }), setTimeout(() => { - this.sessionRequestQueue.state = A2.idle, this.processSessionRequestQueue(); - }, w4.toMiliseconds(this.requestQueueDelay)); - }, this.cleanupPendingSentRequestsForTopic = ({ topic: t, error: e2 }) => { - const i2 = this.client.core.history.pending; - i2.length > 0 && i2.filter((r) => r.topic === t && r.request.method === "wc_sessionRequest").forEach((r) => { - const n3 = r.request.id, a3 = s2.engineEvent("session_request", n3); - if (this.events.listenerCount(a3) === 0) - throw new Error(`emitting ${a3} without any listeners`); - this.events.emit(s2.engineEvent("session_request", r.request.id), { error: e2 }); - }); - }, this.processSessionRequestQueue = () => { - if (this.sessionRequestQueue.state === A2.active) { - this.client.logger.info("session request queue is already active."); - return; - } - const t = this.sessionRequestQueue.queue[0]; - if (!t) { - this.client.logger.info("session request queue is empty."); - return; - } - try { - this.sessionRequestQueue.state = A2.active, this.client.events.emit("session_request", t); - } catch (e2) { - this.client.logger.error(e2); - } - }, this.onPairingCreated = (t) => { - if (t.methods && this.expectedPairingMethodMap.set(t.topic, t.methods), t.active) - return; - const e2 = this.client.proposal.getAll().find((i2) => i2.pairingTopic === t.topic); - e2 && this.onSessionProposeRequest(t.topic, u3.formatJsonRpcRequest("wc_sessionPropose", { requiredNamespaces: e2.requiredNamespaces, optionalNamespaces: e2.optionalNamespaces, relays: e2.relays, proposer: e2.proposer, sessionProperties: e2.sessionProperties }, e2.id)); - }, this.isValidConnect = async (t) => { - if (!s2.isValidParams(t)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() params: ${JSON.stringify(t)}`); - throw new Error(c4); - } - const { pairingTopic: e2, requiredNamespaces: i2, optionalNamespaces: r, sessionProperties: n3, relays: a3 } = t; - if (s2.isUndefined(e2) || await this.isValidPairingTopic(e2), !s2.isValidRelays(a3, true)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() relays: ${a3}`); - throw new Error(c4); - } - !s2.isUndefined(i2) && s2.isValidObject(i2) !== 0 && this.validateNamespaces(i2, "requiredNamespaces"), !s2.isUndefined(r) && s2.isValidObject(r) !== 0 && this.validateNamespaces(r, "optionalNamespaces"), s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); - }, this.validateNamespaces = (t, e2) => { - const i2 = s2.isValidRequiredNamespaces(t, "connect()", e2); - if (i2) - throw new Error(i2.message); - }, this.isValidApprove = async (t) => { - if (!s2.isValidParams(t)) - throw new Error(s2.getInternalError("MISSING_OR_INVALID", `approve() params: ${t}`).message); - const { id: e2, namespaces: i2, relayProtocol: r, sessionProperties: n3 } = t; - this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2); - const a3 = this.client.proposal.get(e2), c4 = s2.isValidNamespaces(i2, "approve()"); - if (c4) - throw new Error(c4.message); - const l4 = s2.isConformingNamespaces(a3.requiredNamespaces, i2, "approve()"); - if (l4) - throw new Error(l4.message); - if (!s2.isValidString(r, true)) { - const { message: d3 } = s2.getInternalError("MISSING_OR_INVALID", `approve() relayProtocol: ${r}`); - throw new Error(d3); - } - s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); - }, this.isValidReject = async (t) => { - if (!s2.isValidParams(t)) { - const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() params: ${t}`); - throw new Error(r); - } - const { id: e2, reason: i2 } = t; - if (this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2), !s2.isValidErrorReason(i2)) { - const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() reason: ${JSON.stringify(i2)}`); - throw new Error(r); - } - }, this.isValidSessionSettleRequest = (t) => { - if (!s2.isValidParams(t)) { - const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", `onSessionSettleRequest() params: ${t}`); - throw new Error(l4); - } - const { relay: e2, controller: i2, namespaces: r, expiry: n3 } = t; - if (!s2.isValidRelay(e2)) { - const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", "onSessionSettleRequest() relay protocol should be a string"); - throw new Error(l4); - } - const a3 = s2.isValidController(i2, "onSessionSettleRequest()"); - if (a3) - throw new Error(a3.message); - const c4 = s2.isValidNamespaces(r, "onSessionSettleRequest()"); - if (c4) - throw new Error(c4.message); - if (s2.isExpired(n3)) { - const { message: l4 } = s2.getInternalError("EXPIRED", "onSessionSettleRequest()"); - throw new Error(l4); - } - }, this.isValidUpdate = async (t) => { - if (!s2.isValidParams(t)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `update() params: ${t}`); - throw new Error(c4); - } - const { topic: e2, namespaces: i2 } = t; - this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); - const r = this.client.session.get(e2), n3 = s2.isValidNamespaces(i2, "update()"); - if (n3) - throw new Error(n3.message); - const a3 = s2.isConformingNamespaces(r.requiredNamespaces, i2, "update()"); - if (a3) - throw new Error(a3.message); - }, this.isValidExtend = async (t) => { - if (!s2.isValidParams(t)) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `extend() params: ${t}`); - throw new Error(i2); - } - const { topic: e2 } = t; - this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); - }, this.isValidRequest = async (t) => { - if (!s2.isValidParams(t)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() params: ${t}`); - throw new Error(c4); - } - const { topic: e2, request: i2, chainId: r, expiry: n3 } = t; - this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); - const { namespaces: a3 } = this.client.session.get(e2); - if (!s2.isValidNamespacesChainId(a3, r)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() chainId: ${r}`); - throw new Error(c4); - } - if (!s2.isValidRequest(i2)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() ${JSON.stringify(i2)}`); - throw new Error(c4); - } - if (!s2.isValidNamespacesRequest(a3, r, i2.method)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() method: ${i2.method}`); - throw new Error(c4); - } - if (n3 && !s2.isValidRequestExpiry(n3, H)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() expiry: ${n3}. Expiry must be a number (in seconds) between ${H.min} and ${H.max}`); - throw new Error(c4); - } - }, this.isValidRespond = async (t) => { - var e2; - if (!s2.isValidParams(t)) { - const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() params: ${t}`); - throw new Error(n3); - } - const { topic: i2, response: r } = t; - try { - await this.isValidSessionTopic(i2); - } catch (n3) { - throw (e2 = t?.response) != null && e2.id && this.cleanupAfterResponse(t), n3; - } - if (!s2.isValidResponse(r)) { - const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() response: ${JSON.stringify(r)}`); - throw new Error(n3); - } - }, this.isValidPing = async (t) => { - if (!s2.isValidParams(t)) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `ping() params: ${t}`); - throw new Error(i2); - } - const { topic: e2 } = t; - await this.isValidSessionOrPairingTopic(e2); - }, this.isValidEmit = async (t) => { - if (!s2.isValidParams(t)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() params: ${t}`); - throw new Error(a3); - } - const { topic: e2, event: i2, chainId: r } = t; - await this.isValidSessionTopic(e2); - const { namespaces: n3 } = this.client.session.get(e2); - if (!s2.isValidNamespacesChainId(n3, r)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() chainId: ${r}`); - throw new Error(a3); - } - if (!s2.isValidEvent(i2)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); - throw new Error(a3); - } - if (!s2.isValidNamespacesEvent(n3, r, i2.name)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); - throw new Error(a3); - } - }, this.isValidDisconnect = async (t) => { - if (!s2.isValidParams(t)) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${t}`); - throw new Error(i2); - } - const { topic: e2 } = t; - await this.isValidSessionOrPairingTopic(e2); - }, this.isValidAuthenticate = (t) => { - const { chains: e2, uri: i2, domain: r, nonce: n3 } = t; - if (!Array.isArray(e2) || e2.length === 0) - throw new Error("chains is required and must be a non-empty array"); - if (!s2.isValidString(i2, false)) - throw new Error("uri is required parameter"); - if (!s2.isValidString(r, false)) - throw new Error("domain is required parameter"); - if (!s2.isValidString(n3, false)) - throw new Error("nonce is required parameter"); - if ([...new Set(e2.map((c4) => s2.parseChainId(c4).namespace))].length > 1) - throw new Error("Multi-namespace requests are not supported. Please request single namespace only."); - const { namespace: a3 } = s2.parseChainId(e2[0]); - if (a3 !== "eip155") - throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains."); - }, this.getVerifyContext = async (t, e2) => { - const i2 = { verified: { verifyUrl: e2.verifyUrl || N10.VERIFY_SERVER, validation: "UNKNOWN", origin: e2.url || "" } }; - try { - const r = await this.client.core.verify.resolve({ attestationId: t, verifyUrl: e2.verifyUrl }); - r && (i2.verified.origin = r.origin, i2.verified.isScam = r.isScam, i2.verified.validation = r.origin === new URL(e2.url).origin ? "VALID" : "INVALID"); - } catch (r) { - this.client.logger.info(r); - } - return this.client.logger.info(`Verify context: ${JSON.stringify(i2)}`), i2; - }, this.validateSessionProps = (t, e2) => { - Object.values(t).forEach((i2) => { - if (!s2.isValidString(i2, false)) { - const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `${e2} must be in Record format. Received: ${JSON.stringify(i2)}`); - throw new Error(r); - } - }); - }, this.getPendingAuthRequest = (t) => { - const e2 = this.client.auth.requests.get(t); - return typeof e2 == "object" ? e2 : void 0; - }, this.addToRecentlyDeleted = (t, e2) => { - if (this.recentlyDeletedMap.set(t, e2), this.recentlyDeletedMap.size >= this.recentlyDeletedLimit) { - let i2 = 0; - const r = this.recentlyDeletedLimit / 2; - for (const n3 of this.recentlyDeletedMap.keys()) { - if (i2++ >= r) - break; - this.recentlyDeletedMap.delete(n3); - } - } - }, this.checkRecentlyDeleted = (t) => { - const e2 = this.recentlyDeletedMap.get(t); - if (e2) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${e2}: ${t}`); - throw new Error(i2); - } - }; - } - async isInitialized() { - if (!this.initialized) { - const { message: o2 } = s2.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(o2); - } - await this.client.core.relayer.confirmOnlineStateOrThrow(); - } - registerRelayerEvents() { - this.client.core.relayer.on(N10.RELAYER_EVENTS.message, async (o2) => { - const { topic: t, message: e2 } = o2, { publicKey: i2 } = this.client.auth.authKeys.keys.includes(U2) ? this.client.auth.authKeys.get(U2) : { responseTopic: void 0, publicKey: void 0 }, r = await this.client.core.crypto.decode(t, e2, { receiverPublicKey: i2 }); - try { - u3.isJsonRpcRequest(r) ? (this.client.core.history.set(t, r), this.onRelayEventRequest({ topic: t, payload: r })) : u3.isJsonRpcResponse(r) ? (await this.client.core.history.resolve(r), await this.onRelayEventResponse({ topic: t, payload: r }), this.client.core.history.delete(t, r.id)) : this.onRelayEventUnknownPayload({ topic: t, payload: r }); - } catch (n3) { - this.client.logger.error(n3); - } - }); - } - registerExpirerEvents() { - this.client.core.expirer.on(N10.EXPIRER_EVENTS.expired, async (o2) => { - const { topic: t, id: e2 } = s2.parseExpirerTarget(o2.target); - if (e2 && this.client.pendingRequest.keys.includes(e2)) - return await this.deletePendingSessionRequest(e2, s2.getInternalError("EXPIRED"), true); - t ? this.client.session.keys.includes(t) && (await this.deleteSession({ topic: t, expirerHasDeleted: true }), this.client.events.emit("session_expire", { topic: t })) : e2 && (await this.deleteProposal(e2, true), this.client.events.emit("proposal_expire", { id: e2 })); - }); - } - registerPairingEvents() { - this.client.core.pairing.events.on(N10.PAIRING_EVENTS.create, (o2) => this.onPairingCreated(o2)), this.client.core.pairing.events.on(N10.PAIRING_EVENTS.delete, (o2) => { - this.addToRecentlyDeleted(o2.topic, "pairing"); - }); - } - isValidPairingTopic(o2) { - if (!s2.isValidString(o2, false)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${o2}`); - throw new Error(t); - } - if (!this.client.core.pairing.pairings.keys.includes(o2)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${o2}`); - throw new Error(t); - } - if (s2.isExpired(this.client.core.pairing.pairings.get(o2).expiry)) { - const { message: t } = s2.getInternalError("EXPIRED", `pairing topic: ${o2}`); - throw new Error(t); - } - } - async isValidSessionTopic(o2) { - if (!s2.isValidString(o2, false)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic should be a string: ${o2}`); - throw new Error(t); - } - if (this.checkRecentlyDeleted(o2), !this.client.session.keys.includes(o2)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session topic doesn't exist: ${o2}`); - throw new Error(t); - } - if (s2.isExpired(this.client.session.get(o2).expiry)) { - await this.deleteSession({ topic: o2 }); - const { message: t } = s2.getInternalError("EXPIRED", `session topic: ${o2}`); - throw new Error(t); - } - if (!this.client.core.crypto.keychain.has(o2)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic does not exist in keychain: ${o2}`); - throw await this.deleteSession({ topic: o2 }), new Error(t); - } - } - async isValidSessionOrPairingTopic(o2) { - if (this.checkRecentlyDeleted(o2), this.client.session.keys.includes(o2)) - await this.isValidSessionTopic(o2); - else if (this.client.core.pairing.pairings.keys.includes(o2)) - this.isValidPairingTopic(o2); - else if (s2.isValidString(o2, false)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session or pairing topic doesn't exist: ${o2}`); - throw new Error(t); - } else { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session or pairing topic should be a string: ${o2}`); - throw new Error(t); - } - } - async isValidProposalId(o2) { - if (!s2.isValidId(o2)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `proposal id should be a number: ${o2}`); - throw new Error(t); - } - if (!this.client.proposal.keys.includes(o2)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `proposal id doesn't exist: ${o2}`); - throw new Error(t); - } - if (s2.isExpired(this.client.proposal.get(o2).expiryTimestamp)) { - await this.deleteProposal(o2); - const { message: t } = s2.getInternalError("EXPIRED", `proposal id: ${o2}`); - throw new Error(t); - } - } - }; - var $e = class extends N10.Store { - constructor(o2, t) { - super(o2, t, ce, F), this.core = o2, this.logger = t; - } - }; - var _e = class extends N10.Store { - constructor(o2, t) { - super(o2, t, he, F), this.core = o2, this.logger = t; - } - }; - var Ge = class extends N10.Store { - constructor(o2, t) { - super(o2, t, de, F, (e2) => e2.id), this.core = o2, this.logger = t; - } - }; - var Ke = class extends N10.Store { - constructor(o2, t) { - super(o2, t, we, L2, () => U2), this.core = o2, this.logger = t; - } - }; - var ke = class extends N10.Store { - constructor(o2, t) { - super(o2, t, ye, L2), this.core = o2, this.logger = t; - } - }; - var Fe = class extends N10.Store { - constructor(o2, t) { - super(o2, t, me, L2, (e2) => e2.id), this.core = o2, this.logger = t; - } - }; - var Ye = class { - constructor(o2, t) { - this.core = o2, this.logger = t, this.authKeys = new Ke(this.core, this.logger), this.pairingTopics = new ke(this.core, this.logger), this.requests = new Fe(this.core, this.logger); - } - async init() { - await this.authKeys.init(), await this.pairingTopics.init(), await this.requests.init(); - } - }; - var j2 = class _j extends oe.ISignClient { - constructor(o2) { - super(o2), this.protocol = ee, this.version = te, this.name = Y.name, this.events = new ae.EventEmitter(), this.on = (e2, i2) => this.events.on(e2, i2), this.once = (e2, i2) => this.events.once(e2, i2), this.off = (e2, i2) => this.events.off(e2, i2), this.removeListener = (e2, i2) => this.events.removeListener(e2, i2), this.removeAllListeners = (e2) => this.events.removeAllListeners(e2), this.connect = async (e2) => { - try { - return await this.engine.connect(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.pair = async (e2) => { - try { - return await this.engine.pair(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.approve = async (e2) => { - try { - return await this.engine.approve(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.reject = async (e2) => { - try { - return await this.engine.reject(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.update = async (e2) => { - try { - return await this.engine.update(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.extend = async (e2) => { - try { - return await this.engine.extend(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.request = async (e2) => { - try { - return await this.engine.request(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.respond = async (e2) => { - try { - return await this.engine.respond(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.ping = async (e2) => { - try { - return await this.engine.ping(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.emit = async (e2) => { - try { - return await this.engine.emit(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.disconnect = async (e2) => { - try { - return await this.engine.disconnect(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.find = (e2) => { - try { - return this.engine.find(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.getPendingSessionRequests = () => { - try { - return this.engine.getPendingSessionRequests(); - } catch (e2) { - throw this.logger.error(e2.message), e2; - } - }, this.authenticate = async (e2) => { - try { - return await this.engine.authenticate(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.formatAuthMessage = (e2) => { - try { - return this.engine.formatAuthMessage(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.approveSessionAuthenticate = async (e2) => { - try { - return await this.engine.approveSessionAuthenticate(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.rejectSessionAuthenticate = async (e2) => { - try { - return await this.engine.rejectSessionAuthenticate(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.name = o2?.name || Y.name, this.metadata = o2?.metadata || s2.getAppMetadata(); - const t = typeof o2?.logger < "u" && typeof o2?.logger != "string" ? o2.logger : k4.pino(k4.getDefaultLoggerOptions({ level: o2?.logger || Y.logger })); - this.core = o2?.core || new N10.Core(o2), this.logger = k4.generateChildLogger(t, this.name), this.session = new _e(this.core, this.logger), this.proposal = new $e(this.core, this.logger), this.pendingRequest = new Ge(this.core, this.logger), this.engine = new Ue(this), this.auth = new Ye(this.core, this.logger); - } - static async init(o2) { - const t = new _j(o2); - return await t.initialize(), t; - } - get context() { - return k4.getLoggerContext(this.logger); - } - get pairing() { - return this.core.pairing.pairings; - } - async initialize() { - this.logger.trace("Initialized"); - try { - await this.core.start(), await this.session.init(), await this.proposal.init(), await this.pendingRequest.init(), await this.engine.init(), await this.auth.init(), this.core.verify.init({ verifyUrl: this.metadata.verifyUrl }), this.logger.info("SignClient Initialization Success"); - } catch (o2) { - throw this.logger.info("SignClient Initialization Failure"), this.logger.error(o2.message), o2; - } - } - }; - var He = _e; - var je = j2; - exports2.AUTH_CONTEXT = Ee, exports2.AUTH_KEYS_CONTEXT = we, exports2.AUTH_PAIRING_TOPIC_CONTEXT = ye, exports2.AUTH_PROTOCOL = ge, exports2.AUTH_PUBLIC_KEY_NAME = U2, exports2.AUTH_REQUEST_CONTEXT = me, exports2.AUTH_STORAGE_PREFIX = L2, exports2.AUTH_VERSION = De, exports2.ENGINE_CONTEXT = pe, exports2.ENGINE_QUEUE_STATES = A2, exports2.ENGINE_RPC_OPTS = q2, exports2.HISTORY_CONTEXT = Oe, exports2.HISTORY_EVENTS = ve, exports2.HISTORY_STORAGE_VERSION = Ae, exports2.METHODS_TO_VERIFY = ue, exports2.PROPOSAL_CONTEXT = ce, exports2.PROPOSAL_EXPIRY = Ve, exports2.PROPOSAL_EXPIRY_MESSAGE = le, exports2.REQUEST_CONTEXT = de, exports2.SESSION_CONTEXT = he, exports2.SESSION_EXPIRY = V, exports2.SESSION_REQUEST_EXPIRY_BOUNDARIES = H, exports2.SIGN_CLIENT_CONTEXT = ie, exports2.SIGN_CLIENT_DEFAULT = Y, exports2.SIGN_CLIENT_EVENTS = Pe, exports2.SIGN_CLIENT_PROTOCOL = ee, exports2.SIGN_CLIENT_STORAGE_OPTIONS = Te, exports2.SIGN_CLIENT_STORAGE_PREFIX = F, exports2.SIGN_CLIENT_VERSION = te, exports2.SessionStore = He, exports2.SignClient = je, exports2.WALLETCONNECT_DEEPLINK_CHOICE = se, exports2.default = j2; - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js -var require_operation2 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OptionalOperation = exports2.Operation = void 0; - var Operation; - (function(Operation2) { - Operation2["SIGN_TRANSACTION"] = "mvx_signTransaction"; - Operation2["SIGN_TRANSACTIONS"] = "mvx_signTransactions"; - Operation2["SIGN_MESSAGE"] = "mvx_signMessage"; - })(Operation = exports2.Operation || (exports2.Operation = {})); - var OptionalOperation; - (function(OptionalOperation2) { - OptionalOperation2["SIGN_LOGIN_TOKEN"] = "mvx_signLoginToken"; - OptionalOperation2["SIGN_NATIVE_AUTH_TOKEN"] = "mvx_signNativeAuthToken"; - OptionalOperation2["CANCEL_ACTION"] = "mvx_cancelAction"; - })(OptionalOperation = exports2.OptionalOperation || (exports2.OptionalOperation = {})); - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js -var require_constants6 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = exports2.WALLETCONNECT_MULTIVERSX_METHODS = exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = void 0; - var operation_1 = require_operation2(); - exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = "mvx"; - exports2.WALLETCONNECT_MULTIVERSX_METHODS = Object.values(operation_1.Operation); - exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = Object.values(operation_1.OptionalOperation); - exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = 500; - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js -var require_errors3 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WalletConnectV2ProviderErrorMessagesEnum = exports2.ErrBadAddress = exports2.ErrNotImplemented = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - }; - exports2.Err = Err; - var ErrNotImplemented = class extends Err { - constructor() { - super("Method not yet implemented"); - } - }; - exports2.ErrNotImplemented = ErrNotImplemented; - var ErrBadAddress = class extends Err { - constructor(value, inner) { - super(`Bad address: ${value}`, inner); - } - }; - exports2.ErrBadAddress = ErrBadAddress; - var WalletConnectV2ProviderErrorMessagesEnum; - (function(WalletConnectV2ProviderErrorMessagesEnum2) { - WalletConnectV2ProviderErrorMessagesEnum2["unableToInit"] = "WalletConnect is unable to init"; - WalletConnectV2ProviderErrorMessagesEnum2["notInitialized"] = "WalletConnect is not initialized"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToConnect"] = "WalletConnect is unable to connect"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToConnectExisting"] = "WalletConnect is unable to connect to existing pairing"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToSignLoginToken"] = "WalletConnect could not sign login token"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToSign"] = "WalletConnect could not sign the message"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToLogin"] = "WalletConnect is unable to login"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleTopic"] = "WalletConnect: Unable to handle topic update"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleEvent"] = "WalletConnect: Unable to handle events"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleCleanup"] = "WalletConnect: Unable to handle cleanup"; - WalletConnectV2ProviderErrorMessagesEnum2["sessionNotConnected"] = "WalletConnect Session is not connected"; - WalletConnectV2ProviderErrorMessagesEnum2["sessionDeleted"] = "WalletConnect Session Deleted"; - WalletConnectV2ProviderErrorMessagesEnum2["sessionExpired"] = "WalletConnect Session Expired"; - WalletConnectV2ProviderErrorMessagesEnum2["alreadyLoggedOut"] = "WalletConnect: Already logged out"; - WalletConnectV2ProviderErrorMessagesEnum2["pingFailed"] = "WalletConnect Ping Failed"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidAddress"] = "WalletConnect: Invalid address"; - WalletConnectV2ProviderErrorMessagesEnum2["requestDifferentChain"] = "WalletConnect: Request Chain Id different than Connection Chain Id"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageResponse"] = "WalletConnect could not sign the message"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageSignature"] = "WalletConnect: Invalid message signature"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidTransactionResponse"] = "WalletConnect could not sign the transactions. Invalid signatures"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidCustomRequestResponse"] = "WalletConnect could not send the custom request"; - WalletConnectV2ProviderErrorMessagesEnum2["transactionError"] = "Transaction canceled"; - WalletConnectV2ProviderErrorMessagesEnum2["connectionError"] = "WalletConnect could not establish a connection"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidGuardian"] = "WalletConnect: Invalid Guardian"; - })(WalletConnectV2ProviderErrorMessagesEnum = exports2.WalletConnectV2ProviderErrorMessagesEnum || (exports2.WalletConnectV2ProviderErrorMessagesEnum = {})); - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js -var require_logger2 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Logger = void 0; - var Logger = class { - static error(message) { - console.error(message); - } - static trace(message) { - console.trace(message); - } - }; - exports2.Logger = Logger; - } -}); - -// node_modules/@multiversx/sdk-core/out/globals.js -var require_globals = __commonJS({ - "node_modules/@multiversx/sdk-core/out/globals.js"() { - "use strict"; - init_shim(); - if (!global.Buffer) { - global.Buffer = require_buffer2().Buffer; - } - } -}); - -// node_modules/@multiversx/sdk-core/out/smartContractQuery.js -var require_smartContractQuery = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartContractQuery.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractQueryResponse = exports2.SmartContractQuery = void 0; - var SmartContractQuery = class { - constructor(options) { - this.contract = options.contract; - this.caller = options.caller; - this.value = options.value; - this.function = options.function; - this.arguments = options.arguments; - } - }; - exports2.SmartContractQuery = SmartContractQuery; - var SmartContractQueryResponse = class { - constructor(obj) { - this.function = obj.function; - this.returnCode = obj.returnCode; - this.returnMessage = obj.returnMessage; - this.returnDataParts = obj.returnDataParts; - } - }; - exports2.SmartContractQueryResponse = SmartContractQueryResponse; - } -}); - -// node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js -var require_queryRunnerAdapter = __commonJS({ - "node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.QueryRunnerAdapter = void 0; - var address_1 = require_address(); - var smartContractQuery_1 = require_smartContractQuery(); - var QueryRunnerAdapter = class { - constructor(options) { - this.networkProvider = options.networkProvider; - } - async runQuery(query) { - const adaptedQuery = { - address: address_1.Address.fromBech32(query.contract), - caller: query.caller ? address_1.Address.fromBech32(query.caller) : void 0, - func: query.function, - value: query.value, - getEncodedArguments: () => query.arguments.map((arg) => import_buffer.Buffer.from(arg).toString("hex")) - }; - const adaptedQueryResponse = await this.networkProvider.queryContract(adaptedQuery); - return new smartContractQuery_1.SmartContractQueryResponse({ - function: query.function, - returnCode: adaptedQueryResponse.returnCode.toString(), - returnMessage: adaptedQueryResponse.returnMessage, - returnDataParts: adaptedQueryResponse.getReturnDataParts() - }); - } - }; - exports2.QueryRunnerAdapter = QueryRunnerAdapter; - } -}); - -// node_modules/@multiversx/sdk-core/out/adapters/index.js -var require_adapters = __commonJS({ - "node_modules/@multiversx/sdk-core/out/adapters/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_queryRunnerAdapter(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/converters/index.js -var require_converters = __commonJS({ - "node_modules/@multiversx/sdk-core/out/converters/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_transactionsConverter(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/gasEstimator.js -var require_gasEstimator = __commonJS({ - "node_modules/@multiversx/sdk-core/out/gasEstimator.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.GasEstimator = exports2.DefaultGasConfiguration = void 0; - exports2.DefaultGasConfiguration = { - minGasLimit: 5e4, - gasPerDataByte: 1500, - gasCostESDTTransfer: 2e5, - gasCostESDTNFTTransfer: 2e5, - gasCostESDTNFTMultiTransfer: 2e5 - }; - var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; - var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; - var GasEstimator = class { - constructor(gasConfiguration) { - this.gasConfiguration = gasConfiguration || exports2.DefaultGasConfiguration; - } - forEGLDTransfer(dataLength) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasPerDataByte * dataLength; - return gasLimit; - } - forESDTTransfer(dataLength) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_TRANSFER; - return gasLimit; - } - forESDTNFTTransfer(dataLength) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTNFTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER; - return gasLimit; - } - forMultiESDTNFTTransfer(dataLength, numTransfers) { - const gasLimit = this.gasConfiguration.minGasLimit + (this.gasConfiguration.gasCostESDTNFTMultiTransfer + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER) * numTransfers + this.gasConfiguration.gasPerDataByte * dataLength; - return gasLimit; - } - }; - exports2.GasEstimator = GasEstimator; - } -}); - -// node_modules/@multiversx/sdk-core/out/interface.js -var require_interface2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/interface.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js -var require_interfaceOfNetwork = __commonJS({ - "node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js -var require_relayedTransactionV1Builder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RelayedTransactionV1Builder = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var JSONbig = require_json_bigint(); - var RelayedTransactionV1Builder = class { - /** - * Sets the inner transaction to be used. It has to be already signed. - * - * @param {Transaction} transaction The inner transaction to be used - */ - setInnerTransaction(transaction) { - this.innerTransaction = transaction; - return this; - } - /** - * Sets the network config to be used for building the relayed v1 transaction - * - * @param {INetworkConfig} netConfig The network configuration to be used - */ - setNetworkConfig(netConfig) { - this.netConfig = netConfig; - return this; - } - /** - * Sets the address of the relayer (the one that will actually pay the fee) - * - * @param relayerAddress - */ - setRelayerAddress(relayerAddress) { - this.relayerAddress = relayerAddress; - return this; - } - /** - * (optional) Sets the nonce of the relayer - * - * @param relayerNonce - */ - setRelayerNonce(relayerNonce) { - this.relayerNonce = relayerNonce; - return this; - } - /** - * (optional) Sets the version of the relayed transaction - * - * @param relayedTxVersion - */ - setRelayedTransactionVersion(relayedTxVersion) { - this.relayedTransactionVersion = relayedTxVersion; - return this; - } - /** - * (optional) Sets the options of the relayed transaction - * - * @param relayedTxOptions - */ - setRelayedTransactionOptions(relayedTxOptions) { - this.relayedTransactionOptions = relayedTxOptions; - return this; - } - /** - * (optional) Sets the guardian of the relayed transaction - * - * @param relayedTxGuardian - */ - setRelayedTransactionGuardian(relayedTxGuardian) { - this.relayedTransactionGuardian = relayedTxGuardian; - return this; - } - /** - * Tries to build the relayed v1 transaction based on the previously set fields - * - * @throws ErrInvalidRelayedV1BuilderArguments - * @return Transaction - */ - build() { - if (!this.innerTransaction || !this.netConfig || !this.relayerAddress || !this.innerTransaction.getSignature()) { - throw new errors_1.ErrInvalidRelayedV1BuilderArguments(); - } - const serializedTransaction = this.prepareInnerTransaction(); - const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; - const payload = new transactionPayload_1.TransactionPayload(data); - const gasLimit = this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length() + this.innerTransaction.getGasLimit().valueOf(); - let relayedTransaction = new transaction_1.Transaction({ - nonce: this.relayerNonce, - sender: this.relayerAddress, - receiver: this.innerTransaction.getSender(), - value: 0, - gasLimit, - data: payload, - chainID: this.netConfig.ChainID, - version: this.relayedTransactionVersion, - options: this.relayedTransactionOptions, - guardian: this.relayedTransactionGuardian - }); - if (this.relayerNonce) { - relayedTransaction.setNonce(this.relayerNonce); - } - return relayedTransaction; - } - prepareInnerTransaction() { - if (!this.innerTransaction) { - return ""; - } - const txObject = { - nonce: this.innerTransaction.getNonce().valueOf(), - sender: new address_1.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"), - receiver: new address_1.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"), - value: BigInt(this.innerTransaction.getValue().toString()), - gasPrice: this.innerTransaction.getGasPrice().valueOf(), - gasLimit: this.innerTransaction.getGasLimit().valueOf(), - data: this.innerTransaction.getData().valueOf().toString("base64"), - signature: this.innerTransaction.getSignature().toString("base64"), - chainID: import_buffer.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"), - version: this.innerTransaction.getVersion().valueOf(), - options: this.innerTransaction.getOptions().valueOf() == 0 ? void 0 : this.innerTransaction.getOptions().valueOf(), - guardian: this.innerTransaction.getGuardian().bech32() ? new address_1.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64") : void 0, - guardianSignature: this.innerTransaction.getGuardianSignature().toString("hex") ? this.innerTransaction.getGuardianSignature().toString("base64") : void 0, - sndUserName: this.innerTransaction.getSenderUsername() ? import_buffer.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64") : void 0, - rcvUserName: this.innerTransaction.getReceiverUsername() ? import_buffer.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64") : void 0 - }; - return JSONbig.stringify(txObject); - } - }; - exports2.RelayedTransactionV1Builder = RelayedTransactionV1Builder; - } -}); - -// node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js -var require_relayedTransactionV2Builder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RelayedTransactionV2Builder = void 0; - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var RelayedTransactionV2Builder = class { - /** - * Sets the inner transaction to be used. It has to be already signed and with gasLimit set to 0. These checks - * are performed on the build() method - * - * @param {Transaction} transaction The inner transaction to be used - */ - setInnerTransaction(transaction) { - this.innerTransaction = transaction; - return this; - } - /** - * Sets the gas limit to be used for the SC Call inside the inner transaction - * - * @param {IGasLimit} gasLimit The gas limit to be used. The inner transaction needs to have the gas limit set to 0, - * so this field will specify the gas to be used for the SC call of the inner transaction - */ - setInnerTransactionGasLimit(gasLimit) { - this.innerTransactionGasLimit = gasLimit; - return this; - } - /** - * Sets the network config to be used for building the relayed v2 transaction - * - * @param {INetworkConfig} netConfig The network configuration to be used - */ - setNetworkConfig(netConfig) { - this.netConfig = netConfig; - return this; - } - /** - * Sets the address of the relayer (the one that will actually pay the fee) - * - * @param relayerAddress - */ - setRelayerAddress(relayerAddress) { - this.relayerAddress = relayerAddress; - return this; - } - /** - * (optional) Sets the nonce of the relayer - * - * @param relayerNonce - */ - setRelayerNonce(relayerNonce) { - this.relayerNonce = relayerNonce; - return this; - } - /** - * Tries to build the relayed v2 transaction based on the previously set fields. - * It returns a transaction that isn't signed - * - * @throws ErrInvalidRelayedV2BuilderArguments - * @throws ErrGasLimitShouldBe0ForInnerTransaction - * @return Transaction - */ - build() { - if (!this.innerTransaction || !this.innerTransactionGasLimit || !this.relayerAddress || !this.netConfig || !this.innerTransaction.getSignature()) { - throw new errors_1.ErrInvalidRelayedV2BuilderArguments(); - } - if (this.innerTransaction.getGasLimit() != 0) { - throw new errors_1.ErrGasLimitShouldBe0ForInnerTransaction(); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - new smartcontracts_1.AddressValue(this.innerTransaction.getReceiver()), - new smartcontracts_1.U64Value(this.innerTransaction.getNonce().valueOf()), - new smartcontracts_1.BytesValue(this.innerTransaction.getData().valueOf()), - new smartcontracts_1.BytesValue(this.innerTransaction.getSignature()) - ]); - const data = `relayedTxV2@${argumentsString}`; - const payload = new transactionPayload_1.TransactionPayload(data); - let relayedTransaction = new transaction_1.Transaction({ - sender: this.relayerAddress, - receiver: this.innerTransaction.getSender(), - value: 0, - gasLimit: this.innerTransactionGasLimit.valueOf() + this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length(), - data: payload, - chainID: this.netConfig.ChainID, - version: this.innerTransaction.getVersion(), - options: this.innerTransaction.getOptions() - }); - if (this.relayerNonce) { - relayedTransaction.setNonce(this.relayerNonce); - } - return relayedTransaction; - } - }; - exports2.RelayedTransactionV2Builder = RelayedTransactionV2Builder; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js -var require_smartContractQueriesController = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractQueriesController = void 0; - var errors_1 = require_errors(); - var smartContractQuery_1 = require_smartContractQuery(); - var smartcontracts_1 = require_smartcontracts(); - var SmartContractQueriesController = class { - constructor(options) { - this.abi = options.abi; - this.queryRunner = options.queryRunner; - this.legacyResultsParser = new smartcontracts_1.ResultsParser(); - } - createQuery(options) { - const preparedArguments = this.encodeArguments(options.function, options.arguments); - return new smartContractQuery_1.SmartContractQuery({ - contract: options.contract, - caller: options.caller, - function: options.function, - arguments: preparedArguments, - value: options.value - }); - } - encodeArguments(functionName, args) { - const endpoint = this.abi?.getEndpoint(functionName); - if (endpoint) { - const typedArgs = smartcontracts_1.NativeSerializer.nativeToTypedValues(args, endpoint); - return new smartcontracts_1.ArgSerializer().valuesToBuffers(typedArgs); - } - if (this.areArgsOfTypedValue(args)) { - return new smartcontracts_1.ArgSerializer().valuesToBuffers(args); - } - if (this.areArgsBuffers(args)) { - return args.map((arg) => import_buffer.Buffer.from(arg)); - } - throw new errors_1.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers"); - } - areArgsOfTypedValue(args) { - for (const arg of args) { - if (!arg.belongsToTypesystem) { - return false; - } - } - return true; - } - areArgsBuffers(args) { - for (const arg of args) { - if (!ArrayBuffer.isView(arg)) { - return false; - } - } - return true; - } - async runQuery(query) { - const queryResponse = await this.queryRunner.runQuery(query); - return queryResponse; - } - parseQueryResponse(response) { - if (!this.abi) { - return response.returnDataParts; - } - const legacyQueryResponse = { - returnCode: response.returnCode, - returnMessage: response.returnMessage, - getReturnDataParts: () => response.returnDataParts.map((part) => import_buffer.Buffer.from(part)) - }; - const functionName = response.function; - const endpoint = this.abi.getEndpoint(functionName); - const legacyBundle = this.legacyResultsParser.parseQueryResponse(legacyQueryResponse, endpoint); - const nativeValues = legacyBundle.values.map((value) => value.valueOf()); - return nativeValues; - } - }; - exports2.SmartContractQueriesController = SmartContractQueriesController; - } -}); - -// node_modules/@multiversx/sdk-core/out/index.js -var require_out = __commonJS({ - "node_modules/@multiversx/sdk-core/out/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - require_globals(); - __exportStar2(require_account(), exports2); - __exportStar2(require_adapters(), exports2); - __exportStar2(require_address(), exports2); - __exportStar2(require_asyncTimer(), exports2); - __exportStar2(require_converters(), exports2); - __exportStar2(require_errors(), exports2); - __exportStar2(require_gasEstimator(), exports2); - __exportStar2(require_interface2(), exports2); - __exportStar2(require_interfaceOfNetwork(), exports2); - __exportStar2(require_logger(), exports2); - __exportStar2(require_message(), exports2); - __exportStar2(require_networkParams(), exports2); - __exportStar2(require_relayedTransactionV1Builder(), exports2); - __exportStar2(require_relayedTransactionV2Builder(), exports2); - __exportStar2(require_signableMessage(), exports2); - __exportStar2(require_smartContractQueriesController(), exports2); - __exportStar2(require_smartcontracts(), exports2); - __exportStar2(require_tokenOperations(), exports2); - __exportStar2(require_tokens(), exports2); - __exportStar2(require_transaction(), exports2); - __exportStar2(require_transactionComputer(), exports2); - __exportStar2(require_transactionPayload(), exports2); - __exportStar2(require_transactionWatcher(), exports2); - __exportStar2(require_transactionsFactories(), exports2); - __exportStar2(require_transactionsOutcomeParsers(), exports2); - __exportStar2(require_utils2(), exports2); - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js -var require_utils4 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.sleep = exports2.getMetadata = exports2.applyTransactionSignature = exports2.getAddressFromSession = exports2.addressIsValid = exports2.getConnectionParams = exports2.getCurrentTopic = exports2.getCurrentSession = void 0; - var sdk_core_1 = require_out(); - var signature_1 = require_signature(); - var utils_1 = require_index_cjs2(); - var constants_1 = require_constants6(); - var errors_1 = require_errors3(); - var logger_1 = require_logger2(); - var operation_1 = require_operation2(); - function getCurrentSession(chainId, client) { - if (!client) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - const acknowledgedSessions = client.find(getConnectionParams(chainId)).filter((s2) => s2.acknowledged); - if (acknowledgedSessions.length > 0) { - const lastKeyIndex = acknowledgedSessions.length - 1; - const session = acknowledgedSessions[lastKeyIndex]; - return session; - } - if (client.session.length > 0) { - const lastKeyIndex = client.session.keys.length - 1; - const session = client.session.get(client.session.keys[lastKeyIndex]); - return session; - } - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - exports2.getCurrentSession = getCurrentSession; - function getCurrentTopic(chainId, client) { - if (!client) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - const session = getCurrentSession(chainId, client); - if (!(session === null || session === void 0 ? void 0 : session.topic)) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - return session.topic; - } - exports2.getCurrentTopic = getCurrentTopic; - function getConnectionParams(chainId, options) { - var _a, _b, _c; - const methods = [ - ...constants_1.WALLETCONNECT_MULTIVERSX_METHODS, - ...(_a = options === null || options === void 0 ? void 0 : options.methods) !== null && _a !== void 0 ? _a : [] - ]; - if (!((_b = options === null || options === void 0 ? void 0 : options.methods) === null || _b === void 0 ? void 0 : _b.includes(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN))) { - methods.push(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN); - } - const chains = [`${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${chainId}`]; - const events = (_c = options === null || options === void 0 ? void 0 : options.events) !== null && _c !== void 0 ? _c : []; - return { - requiredNamespaces: { - [constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]: { - methods, - chains, - events - } - } - }; - } - exports2.getConnectionParams = getConnectionParams; - function addressIsValid(destinationAddress) { - try { - const address = sdk_core_1.Address.fromBech32(destinationAddress); - return !address.isEmpty(); - } catch (_a) { - return false; - } - } - exports2.addressIsValid = addressIsValid; - function getAddressFromSession(session) { - const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; - if (selectedNamespace && selectedNamespace.accounts) { - const currentSession = selectedNamespace.accounts[0]; - const [namespace, reference, address] = currentSession.split(":"); - return address; - } - return ""; - } - exports2.getAddressFromSession = getAddressFromSession; - function applyTransactionSignature({ transaction, response }) { - if (!response) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - } - const { signature, guardianSignature, version: version2, options, guardian } = response; - const transactionGuardian = transaction.getGuardian().bech32(); - if (transactionGuardian && transactionGuardian !== guardian) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); - } - if (guardian) { - transaction.setGuardian(sdk_core_1.Address.fromBech32(guardian)); - } - if (version2) { - transaction.setVersion(version2); - } - if (options != null) { - transaction.setOptions(options); - } - transaction.applySignature(new signature_1.Signature(signature)); - if (guardianSignature) { - transaction.applyGuardianSignature(new signature_1.Signature(guardianSignature)); - } - return transaction; - } - exports2.applyTransactionSignature = applyTransactionSignature; - function getMetadata(metadata) { - if (metadata) { - return Object.assign(Object.assign({}, metadata), { url: utils_1.getAppMetadata().url }); - } - return; - } - exports2.getMetadata = getMetadata; - function sleep(timeout) { - return __awaiter2(this, void 0, void 0, function* () { - return yield new Promise((resolve) => setTimeout(() => { - resolve(); - }, timeout)); - }); - } - exports2.sleep = sleep; - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js -var require_walletConnectV2Provider = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WalletConnectV2Provider = exports2.OptionalOperation = exports2.Operation = exports2.WalletConnectV2ProviderErrorMessagesEnum = void 0; - var signature_1 = require_signature(); - var sign_client_1 = __importDefault2(require_index_cjs4()); - var utils_1 = require_index_cjs2(); - var constants_1 = require_constants6(); - var errors_1 = require_errors3(); - Object.defineProperty(exports2, "WalletConnectV2ProviderErrorMessagesEnum", { enumerable: true, get: function() { - return errors_1.WalletConnectV2ProviderErrorMessagesEnum; - } }); - var logger_1 = require_logger2(); - var operation_1 = require_operation2(); - Object.defineProperty(exports2, "Operation", { enumerable: true, get: function() { - return operation_1.Operation; - } }); - Object.defineProperty(exports2, "OptionalOperation", { enumerable: true, get: function() { - return operation_1.OptionalOperation; - } }); - var utils_2 = require_utils4(); - var WalletConnectV2Provider5 = class { - constructor(onClientConnect, chainId, walletConnectV2Relay, walletConnectV2ProjectId, options) { - this.chainId = ""; - this.address = ""; - this.signature = ""; - this.isInitializing = false; - this.processingTopic = ""; - this.options = {}; - this.onClientConnect = onClientConnect; - this.chainId = chainId; - this.walletConnectV2Relay = walletConnectV2Relay; - this.walletConnectV2ProjectId = walletConnectV2ProjectId; - this.options = options; - } - reset() { - this.address = ""; - this.signature = ""; - this.walletConnector = void 0; - this.session = void 0; - this.pairings = void 0; - } - /** - * Initiates WalletConnect client. - */ - init() { - var _a, _b; - return __awaiter2(this, void 0, void 0, function* () { - if (this.isInitialized()) { - return this.isInitialized(); - } else { - try { - if (!this.isInitializing) { - this.isInitializing = true; - this.reset(); - const metadata = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.metadata) ? { - metadata: utils_2.getMetadata((_b = this.options) === null || _b === void 0 ? void 0 : _b.metadata) - } : {}; - const client = yield sign_client_1.default.init(Object.assign(Object.assign(Object.assign({}, this.options), { relayUrl: this.walletConnectV2Relay, projectId: this.walletConnectV2ProjectId }), metadata)); - this.walletConnector = client; - this.isInitializing = false; - yield this.subscribeToEvents(client); - yield this.checkPersistedState(client); - } - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToInit); - } finally { - this.isInitializing = false; - return this.isInitialized(); - } - } - }); - } - /** - * Returns true if init() was previously called successfully - */ - isInitialized() { - return !!this.walletConnector && !this.isInitializing; - } - /** - * Returns true if provider is initialized and a valid session is set - */ - isConnected() { - return new Promise((resolve, _4) => resolve(Boolean(this.isInitialized() && typeof this.session !== "undefined"))); - } - connect(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - const connectParams = utils_2.getConnectionParams(this.chainId, options); - try { - const response = yield this.walletConnector.connect(Object.assign({ pairingTopic: options === null || options === void 0 ? void 0 : options.topic }, connectParams)); - return response; - } catch (error) { - this.reset(); - logger_1.Logger.error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); - throw new Error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); - } - }); - } - login(options) { - var _a; - return __awaiter2(this, void 0, void 0, function* () { - this.isInitializing = true; - if (typeof this.walletConnector === "undefined") { - yield this.connect(); - } - if (typeof this.walletConnector === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session !== "undefined") { - yield this.logout({ topic: (_a = this.session) === null || _a === void 0 ? void 0 : _a.topic }); - } - try { - if (options && options.approval) { - const session = yield options.approval(); - if (options.token) { - yield utils_2.sleep(constants_1.WALLETCONNECT_SIGN_LOGIN_DELAY); - const address = utils_2.getAddressFromSession(session); - const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; - const method = selectedNamespace.methods.includes(operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN) ? operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN : operation_1.OptionalOperation.SIGN_LOGIN_TOKEN; - const { signature } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: session.topic, - request: { - method, - params: { - token: options.token, - address - } - } - }); - if (!signature) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); - } - return yield this.onSessionConnected({ - session, - signature - }); - } - return yield this.onSessionConnected({ - session, - signature: "" - }); - } - } catch (error) { - this.reset(); - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); - } finally { - this.isInitializing = false; - } - return ""; - }); - } - /** - * Mocks a logout request by returning true - */ - logout(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - try { - if (this.processingTopic === ((options === null || options === void 0 ? void 0 : options.topic) || utils_2.getCurrentTopic(this.chainId, this.walletConnector))) { - return true; - } - if (options === null || options === void 0 ? void 0 : options.topic) { - this.processingTopic = options.topic; - yield this.walletConnector.disconnect({ - topic: options.topic, - reason: utils_1.getSdkError("USER_DISCONNECTED") - }); - } else { - const currentSessionTopic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); - this.processingTopic = currentSessionTopic; - yield this.walletConnector.disconnect({ - topic: currentSessionTopic, - reason: utils_1.getSdkError("USER_DISCONNECTED") - }); - this.reset(); - yield this.cleanupPendingPairings({ deletePairings: true }); - } - } catch (_a) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut); - } finally { - this.processingTopic = ""; - } - return true; - }); - } - /** - * Fetches the WalletConnect address - */ - getAddress() { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - return this.address; - }); - } - /** - * Fetches the WalletConnect signature - */ - getSignature() { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - return this.signature; - }); - } - /** - * Fetches the WalletConnect pairings - */ - getPairings() { - var _a, _b, _c, _d, _e; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - return (_e = (_d = (_c = (_b = (_a = this.walletConnector) === null || _a === void 0 ? void 0 : _a.core) === null || _b === void 0 ? void 0 : _b.pairing) === null || _c === void 0 ? void 0 : _c.pairings) === null || _d === void 0 ? void 0 : _d.getAll({ active: true })) !== null && _e !== void 0 ? _e : []; - }); - } - /** - * Signs a message and returns it signed - * @param message - */ - signMessage(message) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - try { - const address = yield this.getAddress(); - const { signature } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: { - method: operation_1.Operation.SIGN_MESSAGE, - params: { - address, - message: message.message.toString() - } - } - }); - if (!signature) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); - } - try { - message.applySignature(new signature_1.Signature(signature)); - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); - } - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSign); - } - return message; - }); - } - /** - * Signs a transaction and returns it signed - * @param transaction - */ - signTransaction(transaction) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - const plainTransaction = transaction.toPlainObject(); - if (this.chainId !== transaction.getChainID().valueOf()) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - } - try { - const response = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: { - method: operation_1.Operation.SIGN_TRANSACTION, - params: { - transaction: plainTransaction - } - } - }); - return utils_2.applyTransactionSignature({ transaction, response }); - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); - } - }); - } - /** - * Signs an array of transactions and returns it signed - * @param transactions - */ - signTransactions(transactions) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - const plainTransactions = transactions.map((transaction) => { - if (this.chainId !== transaction.getChainID().valueOf()) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - } - return transaction.toPlainObject(); - }); - try { - const { signatures } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: { - method: operation_1.Operation.SIGN_TRANSACTIONS, - params: { - transactions: plainTransactions - } - } - }); - if (!signatures) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - } - if (!Array.isArray(signatures) || transactions.length !== signatures.length) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - } - for (const [index, transaction] of transactions.entries()) { - const response = signatures[index]; - utils_2.applyTransactionSignature({ transaction, response }); - } - return transactions; - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); - } - }); - } - /** - * Sends a custom request - * @param request - */ - sendCustomRequest(options) { - var _a; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - if ((_a = options === null || options === void 0 ? void 0 : options.request) === null || _a === void 0 ? void 0 : _a.method) { - try { - const request = Object.assign({}, options.request); - let { method } = request; - const { response } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: Object.assign(Object.assign({}, request), { method }) - }); - if (!response) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); - } - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); - } - return; - } - }); - } - /** - * Ping helper - */ - ping() { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - try { - const topic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); - yield this.walletConnector.ping({ - topic - }); - return true; - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.pingFailed); - return false; - } - }); - } - loginAccount(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (!options) { - return ""; - } - if (utils_2.addressIsValid(options.address)) { - this.address = options.address; - if (options.signature) { - this.signature = options.signature; - } - this.onClientConnect.onClientLogin(); - return this.address; - } - logger_1.Logger.error(`${errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${options.address}`); - if (this.walletConnector) { - yield this.logout(); - } - return ""; - }); - } - onSessionConnected(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (!options) { - return ""; - } - this.session = options.session; - const address = utils_2.getAddressFromSession(options.session); - if (address) { - yield this.loginAccount({ address, signature: options.signature }); - return address; - } - return ""; - }); - } - handleTopicUpdateEvent({ topic }) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - return; - } - try { - const existingPairings = yield this.getPairings(); - if (this.address && !this.isInitializing && existingPairings) { - if ((existingPairings === null || existingPairings === void 0 ? void 0 : existingPairings.length) === 0) { - this.onClientConnect.onClientLogout(); - } else { - const lastActivePairing = existingPairings[existingPairings.length - 1]; - if ((lastActivePairing === null || lastActivePairing === void 0 ? void 0 : lastActivePairing.topic) === topic) { - this.onClientConnect.onClientLogout(); - } - } - } - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic); - } finally { - this.pairings = yield this.getPairings(); - } - }); - } - handleSessionEvents({ topic, params }) { - var _a; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (this.session && ((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) !== topic) { - return; - } - const { event } = params; - if ((event === null || event === void 0 ? void 0 : event.name) && utils_2.getCurrentTopic(this.chainId, this.walletConnector) === topic) { - const eventData = event.data; - this.onClientConnect.onClientEvent(eventData); - } - }); - } - subscribeToEvents(client) { - var _a, _b, _c, _d; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof client === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - try { - client.on("session_update", ({ topic, params }) => { - var _a2; - if (!this.session || ((_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.topic) !== topic) { - return; - } - const { namespaces } = params; - const _session = client.session.get(topic); - const updatedSession = Object.assign(Object.assign({}, _session), { namespaces }); - this.onSessionConnected({ session: updatedSession }); - }); - client.on("session_event", this.handleSessionEvents.bind(this)); - client.on("session_delete", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { - var _e; - if (this.isInitializing) { - this.onClientConnect.onClientLogout(); - this.reset(); - } - if (!this.session || ((_e = this.session) === null || _e === void 0 ? void 0 : _e.topic) !== topic) { - return; - } - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted); - this.onClientConnect.onClientLogout(); - this.reset(); - yield this.cleanupPendingPairings({ deletePairings: true }); - })); - client.on("session_expire", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { - var _f; - if (!this.session || ((_f = this.session) === null || _f === void 0 ? void 0 : _f.topic) !== topic) { - return; - } - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired); - this.onClientConnect.onClientLogout(); - this.reset(); - yield this.cleanupPendingPairings({ deletePairings: true }); - })); - (_b = (_a = client.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.events.on("pairing_delete", this.handleTopicUpdateEvent.bind(this)); - (_d = (_c = client.core) === null || _c === void 0 ? void 0 : _c.pairing) === null || _d === void 0 ? void 0 : _d.events.on("pairing_expire", this.handleTopicUpdateEvent.bind(this)); - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent); - } - }); - } - checkPersistedState(client) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof client === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - this.pairings = yield this.getPairings(); - if (typeof this.session !== "undefined") { - return; - } - if (client.session.length && !this.address && !this.isInitializing) { - const session = utils_2.getCurrentSession(this.chainId, client); - if (session) { - yield this.onSessionConnected({ session }); - return session; - } - } - return; - }); - } - cleanupPendingPairings(options = {}) { - var _a, _b, _c, _d, _e, _f, _g, _h; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - return; - } - try { - const inactivePairings = (_c = (_b = (_a = this.walletConnector.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.pairings) === null || _c === void 0 ? void 0 : _c.getAll({ active: false }); - if (!utils_1.isValidArray(inactivePairings)) { - return; - } - for (const pairing of inactivePairings) { - if (options.deletePairings) { - (_e = (_d = this.walletConnector.core) === null || _d === void 0 ? void 0 : _d.expirer) === null || _e === void 0 ? void 0 : _e.set(pairing.topic, 0); - } else { - try { - yield (_h = (_g = (_f = this.walletConnector.core) === null || _f === void 0 ? void 0 : _f.relayer) === null || _g === void 0 ? void 0 : _g.subscriber) === null || _h === void 0 ? void 0 : _h.unsubscribe(pairing.topic); - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); - } - } - } - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); - } - }); - } - }; - exports2.WalletConnectV2Provider = WalletConnectV2Provider5; - } -}); - -// node_modules/has-symbols/shams.js -var require_shams = __commonJS({ - "node_modules/has-symbols/shams.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function hasSymbols() { - if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { - return false; - } - if (typeof Symbol.iterator === "symbol") { - return true; - } - var obj = {}; - var sym = Symbol("test"); - var symObj = Object(sym); - if (typeof sym === "string") { - return false; - } - if (Object.prototype.toString.call(sym) !== "[object Symbol]") { - return false; - } - if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { - return false; - } - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { - return false; - } - if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { - return false; - } - if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { - return false; - } - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { - return false; - } - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { - return false; - } - if (typeof Object.getOwnPropertyDescriptor === "function") { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/has-symbols/index.js -var require_has_symbols = __commonJS({ - "node_modules/has-symbols/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var origSymbol = typeof Symbol !== "undefined" && Symbol; - var hasSymbolSham = require_shams(); - module2.exports = function hasNativeSymbols() { - if (typeof origSymbol !== "function") { - return false; - } - if (typeof Symbol !== "function") { - return false; - } - if (typeof origSymbol("foo") !== "symbol") { - return false; - } - if (typeof Symbol("bar") !== "symbol") { - return false; - } - return hasSymbolSham(); - }; - } -}); - -// node_modules/has-proto/index.js -var require_has_proto = __commonJS({ - "node_modules/has-proto/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var test = { - foo: {} - }; - var $Object = Object; - module2.exports = function hasProto() { - return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); - }; - } -}); - -// node_modules/function-bind/implementation.js -var require_implementation = __commonJS({ - "node_modules/function-bind/implementation.js"(exports2, module2) { - "use strict"; - init_shim(); - var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; - var toStr = Object.prototype.toString; - var max = Math.max; - var funcType = "[object Function]"; - var concatty = function concatty2(a3, b4) { - var arr = []; - for (var i2 = 0; i2 < a3.length; i2 += 1) { - arr[i2] = a3[i2]; - } - for (var j2 = 0; j2 < b4.length; j2 += 1) { - arr[j2 + a3.length] = b4[j2]; - } - return arr; - }; - var slicy = function slicy2(arrLike, offset) { - var arr = []; - for (var i2 = offset || 0, j2 = 0; i2 < arrLike.length; i2 += 1, j2 += 1) { - arr[j2] = arrLike[i2]; - } - return arr; - }; - var joiny = function(arr, joiner) { - var str = ""; - for (var i2 = 0; i2 < arr.length; i2 += 1) { - str += arr[i2]; - if (i2 + 1 < arr.length) { - str += joiner; - } - } - return str; - }; - module2.exports = function bind(that) { - var target = this; - if (typeof target !== "function" || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - var bound; - var binder = function() { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - }; - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i2 = 0; i2 < boundLength; i2++) { - boundArgs[i2] = "$" + i2; - } - bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); - if (target.prototype) { - var Empty = function Empty2() { - }; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - return bound; - }; - } -}); - -// node_modules/function-bind/index.js -var require_function_bind = __commonJS({ - "node_modules/function-bind/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var implementation = require_implementation(); - module2.exports = Function.prototype.bind || implementation; - } -}); - -// node_modules/hasown/index.js -var require_hasown = __commonJS({ - "node_modules/hasown/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var call = Function.prototype.call; - var $hasOwn = Object.prototype.hasOwnProperty; - var bind = require_function_bind(); - module2.exports = bind.call(call, $hasOwn); - } -}); - -// node_modules/get-intrinsic/index.js -var require_get_intrinsic = __commonJS({ - "node_modules/get-intrinsic/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var undefined2; - var $SyntaxError = SyntaxError; - var $Function = Function; - var $TypeError = TypeError; - var getEvalledConstructor = function(expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); - } catch (e2) { - } - }; - var $gOPD = Object.getOwnPropertyDescriptor; - if ($gOPD) { - try { - $gOPD({}, ""); - } catch (e2) { - $gOPD = null; - } - } - var throwTypeError = function() { - throw new $TypeError(); - }; - var ThrowTypeError = $gOPD ? function() { - try { - arguments.callee; - return throwTypeError; - } catch (calleeThrows) { - try { - return $gOPD(arguments, "callee").get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }() : throwTypeError; - var hasSymbols = require_has_symbols()(); - var hasProto = require_has_proto()(); - var getProto = Object.getPrototypeOf || (hasProto ? function(x3) { - return x3.__proto__; - } : null); - var needsEval = {}; - var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); - var INTRINSICS = { - "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, - "%Array%": Array, - "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, - "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, - "%AsyncFromSyncIteratorPrototype%": undefined2, - "%AsyncFunction%": needsEval, - "%AsyncGenerator%": needsEval, - "%AsyncGeneratorFunction%": needsEval, - "%AsyncIteratorPrototype%": needsEval, - "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, - "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, - "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, - "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, - "%Boolean%": Boolean, - "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, - "%Date%": Date, - "%decodeURI%": decodeURI, - "%decodeURIComponent%": decodeURIComponent, - "%encodeURI%": encodeURI, - "%encodeURIComponent%": encodeURIComponent, - "%Error%": Error, - "%eval%": eval, - // eslint-disable-line no-eval - "%EvalError%": EvalError, - "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, - "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, - "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, - "%Function%": $Function, - "%GeneratorFunction%": needsEval, - "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, - "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, - "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, - "%isFinite%": isFinite, - "%isNaN%": isNaN, - "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, - "%JSON%": typeof JSON === "object" ? JSON : undefined2, - "%Map%": typeof Map === "undefined" ? undefined2 : Map, - "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), - "%Math%": Math, - "%Number%": Number, - "%Object%": Object, - "%parseFloat%": parseFloat, - "%parseInt%": parseInt, - "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, - "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, - "%RangeError%": RangeError, - "%ReferenceError%": ReferenceError, - "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, - "%RegExp%": RegExp, - "%Set%": typeof Set === "undefined" ? undefined2 : Set, - "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), - "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, - "%String%": String, - "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, - "%Symbol%": hasSymbols ? Symbol : undefined2, - "%SyntaxError%": $SyntaxError, - "%ThrowTypeError%": ThrowTypeError, - "%TypedArray%": TypedArray, - "%TypeError%": $TypeError, - "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, - "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, - "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, - "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, - "%URIError%": URIError, - "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, - "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, - "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet - }; - if (getProto) { - try { - null.error; - } catch (e2) { - errorProto = getProto(getProto(e2)); - INTRINSICS["%Error.prototype%"] = errorProto; - } - } - var errorProto; - var doEval = function doEval2(name2) { - var value; - if (name2 === "%AsyncFunction%") { - value = getEvalledConstructor("async function () {}"); - } else if (name2 === "%GeneratorFunction%") { - value = getEvalledConstructor("function* () {}"); - } else if (name2 === "%AsyncGeneratorFunction%") { - value = getEvalledConstructor("async function* () {}"); - } else if (name2 === "%AsyncGenerator%") { - var fn = doEval2("%AsyncGeneratorFunction%"); - if (fn) { - value = fn.prototype; - } - } else if (name2 === "%AsyncIteratorPrototype%") { - var gen = doEval2("%AsyncGenerator%"); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } - INTRINSICS[name2] = value; - return value; - }; - var LEGACY_ALIASES = { - "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], - "%ArrayPrototype%": ["Array", "prototype"], - "%ArrayProto_entries%": ["Array", "prototype", "entries"], - "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], - "%ArrayProto_keys%": ["Array", "prototype", "keys"], - "%ArrayProto_values%": ["Array", "prototype", "values"], - "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], - "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], - "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], - "%BooleanPrototype%": ["Boolean", "prototype"], - "%DataViewPrototype%": ["DataView", "prototype"], - "%DatePrototype%": ["Date", "prototype"], - "%ErrorPrototype%": ["Error", "prototype"], - "%EvalErrorPrototype%": ["EvalError", "prototype"], - "%Float32ArrayPrototype%": ["Float32Array", "prototype"], - "%Float64ArrayPrototype%": ["Float64Array", "prototype"], - "%FunctionPrototype%": ["Function", "prototype"], - "%Generator%": ["GeneratorFunction", "prototype"], - "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], - "%Int8ArrayPrototype%": ["Int8Array", "prototype"], - "%Int16ArrayPrototype%": ["Int16Array", "prototype"], - "%Int32ArrayPrototype%": ["Int32Array", "prototype"], - "%JSONParse%": ["JSON", "parse"], - "%JSONStringify%": ["JSON", "stringify"], - "%MapPrototype%": ["Map", "prototype"], - "%NumberPrototype%": ["Number", "prototype"], - "%ObjectPrototype%": ["Object", "prototype"], - "%ObjProto_toString%": ["Object", "prototype", "toString"], - "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], - "%PromisePrototype%": ["Promise", "prototype"], - "%PromiseProto_then%": ["Promise", "prototype", "then"], - "%Promise_all%": ["Promise", "all"], - "%Promise_reject%": ["Promise", "reject"], - "%Promise_resolve%": ["Promise", "resolve"], - "%RangeErrorPrototype%": ["RangeError", "prototype"], - "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], - "%RegExpPrototype%": ["RegExp", "prototype"], - "%SetPrototype%": ["Set", "prototype"], - "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], - "%StringPrototype%": ["String", "prototype"], - "%SymbolPrototype%": ["Symbol", "prototype"], - "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], - "%TypedArrayPrototype%": ["TypedArray", "prototype"], - "%TypeErrorPrototype%": ["TypeError", "prototype"], - "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], - "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], - "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], - "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], - "%URIErrorPrototype%": ["URIError", "prototype"], - "%WeakMapPrototype%": ["WeakMap", "prototype"], - "%WeakSetPrototype%": ["WeakSet", "prototype"] - }; - var bind = require_function_bind(); - var hasOwn = require_hasown(); - var $concat = bind.call(Function.call, Array.prototype.concat); - var $spliceApply = bind.call(Function.apply, Array.prototype.splice); - var $replace = bind.call(Function.call, String.prototype.replace); - var $strSlice = bind.call(Function.call, String.prototype.slice); - var $exec = bind.call(Function.call, RegExp.prototype.exec); - var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; - var reEscapeChar = /\\(\\)?/g; - var stringToPath = function stringToPath2(string2) { - var first = $strSlice(string2, 0, 1); - var last = $strSlice(string2, -1); - if (first === "%" && last !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); - } else if (last === "%" && first !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); - } - var result = []; - $replace(string2, rePropName, function(match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; - }); - return result; - }; - var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) { - var intrinsicName = name2; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = "%" + alias[0] + "%"; - } - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === "undefined" && !allowMissing) { - throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!"); - } - return { - alias, - name: intrinsicName, - value - }; - } - throw new $SyntaxError("intrinsic " + name2 + " does not exist!"); - }; - module2.exports = function GetIntrinsic(name2, allowMissing) { - if (typeof name2 !== "string" || name2.length === 0) { - throw new $TypeError("intrinsic name must be a non-empty string"); - } - if (arguments.length > 1 && typeof allowMissing !== "boolean") { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - if ($exec(/^%?[^%]*%?$/, name2) === null) { - throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); - } - var parts = stringToPath(name2); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; - var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - for (var i2 = 1, isOwn = true; i2 < parts.length; i2 += 1) { - var part = parts[i2]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { - throw new $SyntaxError("property names with quotes must have matching quotes"); - } - if (part === "constructor" || !isOwn) { - skipFurtherCaching = true; - } - intrinsicBaseName += "." + part; - intrinsicRealName = "%" + intrinsicBaseName + "%"; - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available."); - } - return void 0; - } - if ($gOPD && i2 + 1 >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - if (isOwn && "get" in desc && !("originalValue" in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; - }; - } -}); - -// node_modules/has-property-descriptors/index.js -var require_has_property_descriptors = __commonJS({ - "node_modules/has-property-descriptors/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); - var hasPropertyDescriptors = function hasPropertyDescriptors2() { - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - return true; - } catch (e2) { - return false; - } - } - return false; - }; - hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { - if (!hasPropertyDescriptors()) { - return null; - } - try { - return $defineProperty([], "length", { value: 1 }).length !== 1; - } catch (e2) { - return true; - } - }; - module2.exports = hasPropertyDescriptors; - } -}); - -// node_modules/gopd/index.js -var require_gopd = __commonJS({ - "node_modules/gopd/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); - if ($gOPD) { - try { - $gOPD([], "length"); - } catch (e2) { - $gOPD = null; - } - } - module2.exports = $gOPD; - } -}); - -// node_modules/define-data-property/index.js -var require_define_data_property = __commonJS({ - "node_modules/define-data-property/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var hasPropertyDescriptors = require_has_property_descriptors()(); - var GetIntrinsic = require_get_intrinsic(); - var $defineProperty = hasPropertyDescriptors && GetIntrinsic("%Object.defineProperty%", true); - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - } catch (e2) { - $defineProperty = false; - } - } - var $SyntaxError = GetIntrinsic("%SyntaxError%"); - var $TypeError = GetIntrinsic("%TypeError%"); - var gopd = require_gopd(); - module2.exports = function defineDataProperty(obj, property, value) { - if (!obj || typeof obj !== "object" && typeof obj !== "function") { - throw new $TypeError("`obj` must be an object or a function`"); - } - if (typeof property !== "string" && typeof property !== "symbol") { - throw new $TypeError("`property` must be a string or a symbol`"); - } - if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) { - throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null"); - } - if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) { - throw new $TypeError("`nonWritable`, if provided, must be a boolean or null"); - } - if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) { - throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null"); - } - if (arguments.length > 6 && typeof arguments[6] !== "boolean") { - throw new $TypeError("`loose`, if provided, must be a boolean"); - } - var nonEnumerable = arguments.length > 3 ? arguments[3] : null; - var nonWritable = arguments.length > 4 ? arguments[4] : null; - var nonConfigurable = arguments.length > 5 ? arguments[5] : null; - var loose = arguments.length > 6 ? arguments[6] : false; - var desc = !!gopd && gopd(obj, property); - if ($defineProperty) { - $defineProperty(obj, property, { - configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, - enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, - value, - writable: nonWritable === null && desc ? desc.writable : !nonWritable - }); - } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) { - obj[property] = value; - } else { - throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable."); - } - }; - } -}); - -// node_modules/set-function-length/index.js -var require_set_function_length = __commonJS({ - "node_modules/set-function-length/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var define2 = require_define_data_property(); - var hasDescriptors = require_has_property_descriptors()(); - var gOPD = require_gopd(); - var $TypeError = GetIntrinsic("%TypeError%"); - var $floor = GetIntrinsic("%Math.floor%"); - module2.exports = function setFunctionLength(fn, length2) { - if (typeof fn !== "function") { - throw new $TypeError("`fn` is not a function"); - } - if (typeof length2 !== "number" || length2 < 0 || length2 > 4294967295 || $floor(length2) !== length2) { - throw new $TypeError("`length` must be a positive 32-bit integer"); - } - var loose = arguments.length > 2 && !!arguments[2]; - var functionLengthIsConfigurable = true; - var functionLengthIsWritable = true; - if ("length" in fn && gOPD) { - var desc = gOPD(fn, "length"); - if (desc && !desc.configurable) { - functionLengthIsConfigurable = false; - } - if (desc && !desc.writable) { - functionLengthIsWritable = false; - } - } - if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { - if (hasDescriptors) { - define2( - /** @type {Parameters[0]} */ - fn, - "length", - length2, - true, - true - ); - } else { - define2( - /** @type {Parameters[0]} */ - fn, - "length", - length2 - ); - } - } - return fn; - }; - } -}); - -// node_modules/call-bind/index.js -var require_call_bind = __commonJS({ - "node_modules/call-bind/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var bind = require_function_bind(); - var GetIntrinsic = require_get_intrinsic(); - var setFunctionLength = require_set_function_length(); - var $TypeError = GetIntrinsic("%TypeError%"); - var $apply = GetIntrinsic("%Function.prototype.apply%"); - var $call = GetIntrinsic("%Function.prototype.call%"); - var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind.call($call, $apply); - var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); - var $max = GetIntrinsic("%Math.max%"); - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - } catch (e2) { - $defineProperty = null; - } - } - module2.exports = function callBind(originalFunction) { - if (typeof originalFunction !== "function") { - throw new $TypeError("a function is required"); - } - var func = $reflectApply(bind, $call, arguments); - return setFunctionLength( - func, - 1 + $max(0, originalFunction.length - (arguments.length - 1)), - true - ); - }; - var applyBind = function applyBind2() { - return $reflectApply(bind, $apply, arguments); - }; - if ($defineProperty) { - $defineProperty(module2.exports, "apply", { value: applyBind }); - } else { - module2.exports.apply = applyBind; - } - } -}); - -// node_modules/call-bind/callBound.js -var require_callBound = __commonJS({ - "node_modules/call-bind/callBound.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var callBind = require_call_bind(); - var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf")); - module2.exports = function callBoundIntrinsic(name2, allowMissing) { - var intrinsic = GetIntrinsic(name2, !!allowMissing); - if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) { - return callBind(intrinsic); - } - return intrinsic; - }; - } -}); - -// (disabled):node_modules/object-inspect/util.inspect -var require_util2 = __commonJS({ - "(disabled):node_modules/object-inspect/util.inspect"() { - init_shim(); - } -}); - -// node_modules/object-inspect/index.js -var require_object_inspect = __commonJS({ - "node_modules/object-inspect/index.js"(exports2, module2) { - init_shim(); - var hasMap = typeof Map === "function" && Map.prototype; - var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; - var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; - var mapForEach = hasMap && Map.prototype.forEach; - var hasSet = typeof Set === "function" && Set.prototype; - var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; - var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; - var setForEach = hasSet && Set.prototype.forEach; - var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; - var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; - var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; - var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; - var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; - var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; - var booleanValueOf = Boolean.prototype.valueOf; - var objectToString = Object.prototype.toString; - var functionToString = Function.prototype.toString; - var $match = String.prototype.match; - var $slice = String.prototype.slice; - var $replace = String.prototype.replace; - var $toUpperCase = String.prototype.toUpperCase; - var $toLowerCase = String.prototype.toLowerCase; - var $test = RegExp.prototype.test; - var $concat = Array.prototype.concat; - var $join = Array.prototype.join; - var $arrSlice = Array.prototype.slice; - var $floor = Math.floor; - var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; - var gOPS = Object.getOwnPropertySymbols; - var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; - var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; - var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; - var isEnumerable = Object.prototype.propertyIsEnumerable; - var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O3) { - return O3.__proto__; - } : null); - function addNumericSeparator(num, str) { - if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { - return str; - } - var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; - if (typeof num === "number") { - var int = num < 0 ? -$floor(-num) : $floor(num); - if (int !== num) { - var intStr = String(int); - var dec = $slice.call(str, intStr.length + 1); - return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); - } - } - return $replace.call(str, sepRegex, "$&_"); - } - var utilInspect = require_util2(); - var inspectCustom = utilInspect.custom; - var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; - module2.exports = function inspect_(obj, options, depth, seen) { - var opts = options || {}; - if (has(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) { - throw new TypeError('option "quoteStyle" must be "single" or "double"'); - } - if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { - throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); - } - var customInspect = has(opts, "customInspect") ? opts.customInspect : true; - if (typeof customInspect !== "boolean" && customInspect !== "symbol") { - throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); - } - if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { - throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); - } - if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { - throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); - } - var numericSeparator = opts.numericSeparator; - if (typeof obj === "undefined") { - return "undefined"; - } - if (obj === null) { - return "null"; - } - if (typeof obj === "boolean") { - return obj ? "true" : "false"; - } - if (typeof obj === "string") { - return inspectString(obj, opts); - } - if (typeof obj === "number") { - if (obj === 0) { - return Infinity / obj > 0 ? "0" : "-0"; - } - var str = String(obj); - return numericSeparator ? addNumericSeparator(obj, str) : str; - } - if (typeof obj === "bigint") { - var bigIntStr = String(obj) + "n"; - return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; - } - var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; - if (typeof depth === "undefined") { - depth = 0; - } - if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { - return isArray(obj) ? "[Array]" : "[Object]"; - } - var indent = getIndent(opts, depth); - if (typeof seen === "undefined") { - seen = []; - } else if (indexOf(seen, obj) >= 0) { - return "[Circular]"; - } - function inspect(value, from3, noIndent) { - if (from3) { - seen = $arrSlice.call(seen); - seen.push(from3); - } - if (noIndent) { - var newOpts = { - depth: opts.depth - }; - if (has(opts, "quoteStyle")) { - newOpts.quoteStyle = opts.quoteStyle; - } - return inspect_(value, newOpts, depth + 1, seen); - } - return inspect_(value, opts, depth + 1, seen); - } - if (typeof obj === "function" && !isRegExp(obj)) { - var name2 = nameOf(obj); - var keys2 = arrObjKeys(obj, inspect); - return "[Function" + (name2 ? ": " + name2 : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : ""); - } - if (isSymbol(obj)) { - var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); - return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; - } - if (isElement(obj)) { - var s2 = "<" + $toLowerCase.call(String(obj.nodeName)); - var attrs = obj.attributes || []; - for (var i2 = 0; i2 < attrs.length; i2++) { - s2 += " " + attrs[i2].name + "=" + wrapQuotes(quote(attrs[i2].value), "double", opts); - } - s2 += ">"; - if (obj.childNodes && obj.childNodes.length) { - s2 += "..."; - } - s2 += ""; - return s2; - } - if (isArray(obj)) { - if (obj.length === 0) { - return "[]"; - } - var xs = arrObjKeys(obj, inspect); - if (indent && !singleLineValues(xs)) { - return "[" + indentedJoin(xs, indent) + "]"; - } - return "[ " + $join.call(xs, ", ") + " ]"; - } - if (isError(obj)) { - var parts = arrObjKeys(obj, inspect); - if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { - return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; - } - if (parts.length === 0) { - return "[" + String(obj) + "]"; - } - return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; - } - if (typeof obj === "object" && customInspect) { - if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { - return utilInspect(obj, { depth: maxDepth - depth }); - } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { - return obj.inspect(); - } - } - if (isMap(obj)) { - var mapParts = []; - if (mapForEach) { - mapForEach.call(obj, function(value, key) { - mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); - }); - } - return collectionOf("Map", mapSize.call(obj), mapParts, indent); - } - if (isSet(obj)) { - var setParts = []; - if (setForEach) { - setForEach.call(obj, function(value) { - setParts.push(inspect(value, obj)); - }); - } - return collectionOf("Set", setSize.call(obj), setParts, indent); - } - if (isWeakMap(obj)) { - return weakCollectionOf("WeakMap"); - } - if (isWeakSet(obj)) { - return weakCollectionOf("WeakSet"); - } - if (isWeakRef(obj)) { - return weakCollectionOf("WeakRef"); - } - if (isNumber(obj)) { - return markBoxed(inspect(Number(obj))); - } - if (isBigInt(obj)) { - return markBoxed(inspect(bigIntValueOf.call(obj))); - } - if (isBoolean(obj)) { - return markBoxed(booleanValueOf.call(obj)); - } - if (isString2(obj)) { - return markBoxed(inspect(String(obj))); - } - if (typeof window !== "undefined" && obj === window) { - return "{ [object Window] }"; - } - if (obj === global) { - return "{ [object globalThis] }"; - } - if (!isDate(obj) && !isRegExp(obj)) { - var ys = arrObjKeys(obj, inspect); - var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; - var protoTag = obj instanceof Object ? "" : "null prototype"; - var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; - var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; - var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); - if (ys.length === 0) { - return tag + "{}"; - } - if (indent) { - return tag + "{" + indentedJoin(ys, indent) + "}"; - } - return tag + "{ " + $join.call(ys, ", ") + " }"; - } - return String(obj); - }; - function wrapQuotes(s2, defaultStyle, opts) { - var quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'"; - return quoteChar + s2 + quoteChar; - } - function quote(s2) { - return $replace.call(String(s2), /"/g, """); - } - function isArray(obj) { - return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isDate(obj) { - return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isRegExp(obj) { - return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isError(obj) { - return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isString2(obj) { - return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isNumber(obj) { - return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isBoolean(obj) { - return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isSymbol(obj) { - if (hasShammedSymbols) { - return obj && typeof obj === "object" && obj instanceof Symbol; - } - if (typeof obj === "symbol") { - return true; - } - if (!obj || typeof obj !== "object" || !symToString) { - return false; - } - try { - symToString.call(obj); - return true; - } catch (e2) { - } - return false; - } - function isBigInt(obj) { - if (!obj || typeof obj !== "object" || !bigIntValueOf) { - return false; - } - try { - bigIntValueOf.call(obj); - return true; - } catch (e2) { - } - return false; - } - var hasOwn = Object.prototype.hasOwnProperty || function(key) { - return key in this; - }; - function has(obj, key) { - return hasOwn.call(obj, key); - } - function toStr(obj) { - return objectToString.call(obj); - } - function nameOf(f4) { - if (f4.name) { - return f4.name; - } - var m3 = $match.call(functionToString.call(f4), /^function\s*([\w$]+)/); - if (m3) { - return m3[1]; - } - return null; - } - function indexOf(xs, x3) { - if (xs.indexOf) { - return xs.indexOf(x3); - } - for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { - if (xs[i2] === x3) { - return i2; - } - } - return -1; - } - function isMap(x3) { - if (!mapSize || !x3 || typeof x3 !== "object") { - return false; - } - try { - mapSize.call(x3); - try { - setSize.call(x3); - } catch (s2) { - return true; - } - return x3 instanceof Map; - } catch (e2) { - } - return false; - } - function isWeakMap(x3) { - if (!weakMapHas || !x3 || typeof x3 !== "object") { - return false; - } - try { - weakMapHas.call(x3, weakMapHas); - try { - weakSetHas.call(x3, weakSetHas); - } catch (s2) { - return true; - } - return x3 instanceof WeakMap; - } catch (e2) { - } - return false; - } - function isWeakRef(x3) { - if (!weakRefDeref || !x3 || typeof x3 !== "object") { - return false; - } - try { - weakRefDeref.call(x3); - return true; - } catch (e2) { - } - return false; - } - function isSet(x3) { - if (!setSize || !x3 || typeof x3 !== "object") { - return false; - } - try { - setSize.call(x3); - try { - mapSize.call(x3); - } catch (m3) { - return true; - } - return x3 instanceof Set; - } catch (e2) { - } - return false; - } - function isWeakSet(x3) { - if (!weakSetHas || !x3 || typeof x3 !== "object") { - return false; - } - try { - weakSetHas.call(x3, weakSetHas); - try { - weakMapHas.call(x3, weakMapHas); - } catch (s2) { - return true; - } - return x3 instanceof WeakSet; - } catch (e2) { - } - return false; - } - function isElement(x3) { - if (!x3 || typeof x3 !== "object") { - return false; - } - if (typeof HTMLElement !== "undefined" && x3 instanceof HTMLElement) { - return true; - } - return typeof x3.nodeName === "string" && typeof x3.getAttribute === "function"; - } - function inspectString(str, opts) { - if (str.length > opts.maxStringLength) { - var remaining = str.length - opts.maxStringLength; - var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); - return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; - } - var s2 = $replace.call($replace.call(str, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte); - return wrapQuotes(s2, "single", opts); - } - function lowbyte(c4) { - var n3 = c4.charCodeAt(0); - var x3 = { - 8: "b", - 9: "t", - 10: "n", - 12: "f", - 13: "r" - }[n3]; - if (x3) { - return "\\" + x3; - } - return "\\x" + (n3 < 16 ? "0" : "") + $toUpperCase.call(n3.toString(16)); - } - function markBoxed(str) { - return "Object(" + str + ")"; - } - function weakCollectionOf(type) { - return type + " { ? }"; - } - function collectionOf(type, size, entries, indent) { - var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); - return type + " (" + size + ") {" + joinedEntries + "}"; - } - function singleLineValues(xs) { - for (var i2 = 0; i2 < xs.length; i2++) { - if (indexOf(xs[i2], "\n") >= 0) { - return false; - } - } - return true; - } - function getIndent(opts, depth) { - var baseIndent; - if (opts.indent === " ") { - baseIndent = " "; - } else if (typeof opts.indent === "number" && opts.indent > 0) { - baseIndent = $join.call(Array(opts.indent + 1), " "); - } else { - return null; - } - return { - base: baseIndent, - prev: $join.call(Array(depth + 1), baseIndent) - }; - } - function indentedJoin(xs, indent) { - if (xs.length === 0) { - return ""; - } - var lineJoiner = "\n" + indent.prev + indent.base; - return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; - } - function arrObjKeys(obj, inspect) { - var isArr = isArray(obj); - var xs = []; - if (isArr) { - xs.length = obj.length; - for (var i2 = 0; i2 < obj.length; i2++) { - xs[i2] = has(obj, i2) ? inspect(obj[i2], obj) : ""; - } - } - var syms = typeof gOPS === "function" ? gOPS(obj) : []; - var symMap; - if (hasShammedSymbols) { - symMap = {}; - for (var k4 = 0; k4 < syms.length; k4++) { - symMap["$" + syms[k4]] = syms[k4]; - } - } - for (var key in obj) { - if (!has(obj, key)) { - continue; - } - if (isArr && String(Number(key)) === key && key < obj.length) { - continue; - } - if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { - continue; - } else if ($test.call(/[^\w$]/, key)) { - xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); - } else { - xs.push(key + ": " + inspect(obj[key], obj)); - } - } - if (typeof gOPS === "function") { - for (var j2 = 0; j2 < syms.length; j2++) { - if (isEnumerable.call(obj, syms[j2])) { - xs.push("[" + inspect(syms[j2]) + "]: " + inspect(obj[syms[j2]], obj)); - } - } - } - return xs; - } - } -}); - -// node_modules/side-channel/index.js -var require_side_channel = __commonJS({ - "node_modules/side-channel/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var callBound = require_callBound(); - var inspect = require_object_inspect(); - var $TypeError = GetIntrinsic("%TypeError%"); - var $WeakMap = GetIntrinsic("%WeakMap%", true); - var $Map = GetIntrinsic("%Map%", true); - var $weakMapGet = callBound("WeakMap.prototype.get", true); - var $weakMapSet = callBound("WeakMap.prototype.set", true); - var $weakMapHas = callBound("WeakMap.prototype.has", true); - var $mapGet = callBound("Map.prototype.get", true); - var $mapSet = callBound("Map.prototype.set", true); - var $mapHas = callBound("Map.prototype.has", true); - var listGetNode = function(list, key) { - for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { - if (curr.key === key) { - prev.next = curr.next; - curr.next = list.next; - list.next = curr; - return curr; - } - } - }; - var listGet = function(objects, key) { - var node = listGetNode(objects, key); - return node && node.value; - }; - var listSet = function(objects, key, value) { - var node = listGetNode(objects, key); - if (node) { - node.value = value; - } else { - objects.next = { - // eslint-disable-line no-param-reassign - key, - next: objects.next, - value - }; - } - }; - var listHas = function(objects, key) { - return !!listGetNode(objects, key); - }; - module2.exports = function getSideChannel() { - var $wm; - var $m; - var $o; - var channel = { - assert: function(key) { - if (!channel.has(key)) { - throw new $TypeError("Side channel does not contain " + inspect(key)); - } - }, - get: function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapGet($wm, key); - } - } else if ($Map) { - if ($m) { - return $mapGet($m, key); - } - } else { - if ($o) { - return listGet($o, key); - } - } - }, - has: function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapHas($wm, key); - } - } else if ($Map) { - if ($m) { - return $mapHas($m, key); - } - } else { - if ($o) { - return listHas($o, key); - } - } - return false; - }, - set: function(key, value) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if (!$wm) { - $wm = new $WeakMap(); - } - $weakMapSet($wm, key, value); - } else if ($Map) { - if (!$m) { - $m = new $Map(); - } - $mapSet($m, key, value); - } else { - if (!$o) { - $o = { key: {}, next: null }; - } - listSet($o, key, value); - } - } - }; - return channel; - }; - } -}); - -// node_modules/qs/lib/formats.js -var require_formats = __commonJS({ - "node_modules/qs/lib/formats.js"(exports2, module2) { - "use strict"; - init_shim(); - var replace = String.prototype.replace; - var percentTwenties = /%20/g; - var Format = { - RFC1738: "RFC1738", - RFC3986: "RFC3986" - }; - module2.exports = { - "default": Format.RFC3986, - formatters: { - RFC1738: function(value) { - return replace.call(value, percentTwenties, "+"); - }, - RFC3986: function(value) { - return String(value); - } - }, - RFC1738: Format.RFC1738, - RFC3986: Format.RFC3986 - }; - } -}); - -// node_modules/qs/lib/utils.js -var require_utils5 = __commonJS({ - "node_modules/qs/lib/utils.js"(exports2, module2) { - "use strict"; - init_shim(); - var formats = require_formats(); - var has = Object.prototype.hasOwnProperty; - var isArray = Array.isArray; - var hexTable = function() { - var array = []; - for (var i2 = 0; i2 < 256; ++i2) { - array.push("%" + ((i2 < 16 ? "0" : "") + i2.toString(16)).toUpperCase()); - } - return array; - }(); - var compactQueue = function compactQueue2(queue) { - while (queue.length > 1) { - var item = queue.pop(); - var obj = item.obj[item.prop]; - if (isArray(obj)) { - var compacted = []; - for (var j2 = 0; j2 < obj.length; ++j2) { - if (typeof obj[j2] !== "undefined") { - compacted.push(obj[j2]); - } - } - item.obj[item.prop] = compacted; - } - } - }; - var arrayToObject = function arrayToObject2(source, options) { - var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - for (var i2 = 0; i2 < source.length; ++i2) { - if (typeof source[i2] !== "undefined") { - obj[i2] = source[i2]; - } - } - return obj; - }; - var merge = function merge2(target, source, options) { - if (!source) { - return target; - } - if (typeof source !== "object") { - if (isArray(target)) { - target.push(source); - } else if (target && typeof target === "object") { - if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; - } - return target; - } - if (!target || typeof target !== "object") { - return [target].concat(source); - } - var mergeTarget = target; - if (isArray(target) && !isArray(source)) { - mergeTarget = arrayToObject(target, options); - } - if (isArray(target) && isArray(source)) { - source.forEach(function(item, i2) { - if (has.call(target, i2)) { - var targetItem = target[i2]; - if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { - target[i2] = merge2(targetItem, item, options); - } else { - target.push(item); - } - } else { - target[i2] = item; - } - }); - return target; - } - return Object.keys(source).reduce(function(acc, key) { - var value = source[key]; - if (has.call(acc, key)) { - acc[key] = merge2(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); - }; - var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function(acc, key) { - acc[key] = source[key]; - return acc; - }, target); - }; - var decode6 = function(str, decoder, charset) { - var strWithoutPlus = str.replace(/\+/g, " "); - if (charset === "iso-8859-1") { - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - try { - return decodeURIComponent(strWithoutPlus); - } catch (e2) { - return strWithoutPlus; - } - }; - var encode5 = function encode6(str, defaultEncoder, charset, kind, format) { - if (str.length === 0) { - return str; - } - var string2 = str; - if (typeof str === "symbol") { - string2 = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string2 = String(str); - } - if (charset === "iso-8859-1") { - return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - var out = ""; - for (var i2 = 0; i2 < string2.length; ++i2) { - var c4 = string2.charCodeAt(i2); - if (c4 === 45 || c4 === 46 || c4 === 95 || c4 === 126 || c4 >= 48 && c4 <= 57 || c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122 || format === formats.RFC1738 && (c4 === 40 || c4 === 41)) { - out += string2.charAt(i2); - continue; - } - if (c4 < 128) { - out = out + hexTable[c4]; - continue; - } - if (c4 < 2048) { - out = out + (hexTable[192 | c4 >> 6] + hexTable[128 | c4 & 63]); - continue; - } - if (c4 < 55296 || c4 >= 57344) { - out = out + (hexTable[224 | c4 >> 12] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]); - continue; - } - i2 += 1; - c4 = 65536 + ((c4 & 1023) << 10 | string2.charCodeAt(i2) & 1023); - out += hexTable[240 | c4 >> 18] + hexTable[128 | c4 >> 12 & 63] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]; - } - return out; - }; - var compact = function compact2(value) { - var queue = [{ obj: { o: value }, prop: "o" }]; - var refs = []; - for (var i2 = 0; i2 < queue.length; ++i2) { - var item = queue[i2]; - var obj = item.obj[item.prop]; - var keys2 = Object.keys(obj); - for (var j2 = 0; j2 < keys2.length; ++j2) { - var key = keys2[j2]; - var val = obj[key]; - if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj, prop: key }); - refs.push(val); - } - } - } - compactQueue(queue); - return value; - }; - var isRegExp = function isRegExp2(obj) { - return Object.prototype.toString.call(obj) === "[object RegExp]"; - }; - var isBuffer = function isBuffer2(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); - }; - var combine = function combine2(a3, b4) { - return [].concat(a3, b4); - }; - var maybeMap = function maybeMap2(val, fn) { - if (isArray(val)) { - var mapped = []; - for (var i2 = 0; i2 < val.length; i2 += 1) { - mapped.push(fn(val[i2])); - } - return mapped; - } - return fn(val); - }; - module2.exports = { - arrayToObject, - assign, - combine, - compact, - decode: decode6, - encode: encode5, - isBuffer, - isRegExp, - maybeMap, - merge - }; - } -}); - -// node_modules/qs/lib/stringify.js -var require_stringify2 = __commonJS({ - "node_modules/qs/lib/stringify.js"(exports2, module2) { - "use strict"; - init_shim(); - var getSideChannel = require_side_channel(); - var utils = require_utils5(); - var formats = require_formats(); - var has = Object.prototype.hasOwnProperty; - var arrayPrefixGenerators = { - brackets: function brackets(prefix) { - return prefix + "[]"; - }, - comma: "comma", - indices: function indices(prefix, key) { - return prefix + "[" + key + "]"; - }, - repeat: function repeat(prefix) { - return prefix; - } - }; - var isArray = Array.isArray; - var split = String.prototype.split; - var push = Array.prototype.push; - var pushToArray = function(arr, valueOrArray) { - push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); - }; - var toISO = Date.prototype.toISOString; - var defaultFormat = formats["default"]; - var defaults = { - addQueryPrefix: false, - allowDots: false, - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encoder: utils.encode, - encodeValuesOnly: false, - format: defaultFormat, - formatter: formats.formatters[defaultFormat], - // deprecated - indices: false, - serializeDate: function serializeDate(date) { - return toISO.call(date); - }, - skipNulls: false, - strictNullHandling: false - }; - var isNonNullishPrimitive = function isNonNullishPrimitive2(v2) { - return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean" || typeof v2 === "symbol" || typeof v2 === "bigint"; - }; - var sentinel = {}; - var stringify2 = function stringify3(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - var obj = object; - var tmpSc = sideChannel; - var step = 0; - var findFlag = false; - while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { - var pos = tmpSc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - findFlag = true; - } - } - if (typeof tmpSc.get(sentinel) === "undefined") { - step = 0; - } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate(obj); - } else if (generateArrayPrefix === "comma" && isArray(obj)) { - obj = utils.maybeMap(obj, function(value2) { - if (value2 instanceof Date) { - return serializeDate(value2); - } - return value2; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; - } - obj = ""; - } - if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { - if (encoder) { - var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); - if (generateArrayPrefix === "comma" && encodeValuesOnly) { - var valuesArray = split.call(String(obj), ","); - var valuesJoined = ""; - for (var i2 = 0; i2 < valuesArray.length; ++i2) { - valuesJoined += (i2 === 0 ? "" : ",") + formatter(encoder(valuesArray[i2], defaults.encoder, charset, "value", format)); - } - return [formatter(keyValue) + "=" + valuesJoined]; - } - return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults.encoder, charset, "value", format))]; - } - return [formatter(prefix) + "=" + formatter(String(obj))]; - } - var values = []; - if (typeof obj === "undefined") { - return values; - } - var objKeys; - if (generateArrayPrefix === "comma" && isArray(obj)) { - objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray(filter)) { - objKeys = filter; - } else { - var keys2 = Object.keys(obj); - objKeys = sort ? keys2.sort(sort) : keys2; - } - for (var j2 = 0; j2 < objKeys.length; ++j2) { - var key = objKeys[j2]; - var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; - if (skipNulls && value === null) { - continue; - } - var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? "." + key : "[" + key + "]"); - sideChannel.set(object, step); - var valueSideChannel = getSideChannel(); - valueSideChannel.set(sentinel, sideChannel); - pushToArray(values, stringify3( - value, - keyPrefix, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; - }; - var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { - if (!opts) { - return defaults; - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - var charset = opts.charset || defaults.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - var format = formats["default"]; - if (typeof opts.format !== "undefined") { - if (!has.call(formats.formatters, opts.format)) { - throw new TypeError("Unknown format option provided."); - } - format = opts.format; - } - var formatter = formats.formatters[format]; - var filter = defaults.filter; - if (typeof opts.filter === "function" || isArray(opts.filter)) { - filter = opts.filter; - } - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, - allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; - }; - module2.exports = function(object, opts) { - var obj = object; - var options = normalizeStringifyOptions(opts); - var objKeys; - var filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray(options.filter)) { - filter = options.filter; - objKeys = filter; - } - var keys2 = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - var arrayFormat; - if (opts && opts.arrayFormat in arrayPrefixGenerators) { - arrayFormat = opts.arrayFormat; - } else if (opts && "indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = "indices"; - } - var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; - if (!objKeys) { - objKeys = Object.keys(obj); - } - if (options.sort) { - objKeys.sort(options.sort); - } - var sideChannel = getSideChannel(); - for (var i2 = 0; i2 < objKeys.length; ++i2) { - var key = objKeys[i2]; - if (options.skipNulls && obj[key] === null) { - continue; - } - pushToArray(keys2, stringify2( - obj[key], - key, - generateArrayPrefix, - options.strictNullHandling, - options.skipNulls, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - var joined = keys2.join(options.delimiter); - var prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; - } - } - return joined.length > 0 ? prefix + joined : ""; - }; - } -}); - -// node_modules/qs/lib/parse.js -var require_parse2 = __commonJS({ - "node_modules/qs/lib/parse.js"(exports2, module2) { - "use strict"; - init_shim(); - var utils = require_utils5(); - var has = Object.prototype.hasOwnProperty; - var isArray = Array.isArray; - var defaults = { - allowDots: false, - allowPrototypes: false, - allowSparse: false, - arrayLimit: 20, - charset: "utf-8", - charsetSentinel: false, - comma: false, - decoder: utils.decode, - delimiter: "&", - depth: 5, - ignoreQueryPrefix: false, - interpretNumericEntities: false, - parameterLimit: 1e3, - parseArrays: true, - plainObjects: false, - strictNullHandling: false - }; - var interpretNumericEntities = function(str) { - return str.replace(/&#(\d+);/g, function($0, numberStr) { - return String.fromCharCode(parseInt(numberStr, 10)); - }); - }; - var parseArrayValue = function(val, options) { - if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { - return val.split(","); - } - return val; - }; - var isoSentinel = "utf8=%26%2310003%3B"; - var charsetSentinel = "utf8=%E2%9C%93"; - var parseValues = function parseQueryStringValues(str, options) { - var obj = {}; - var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; - var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; - var parts = cleanStr.split(options.delimiter, limit); - var skipIndex = -1; - var i2; - var charset = options.charset; - if (options.charsetSentinel) { - for (i2 = 0; i2 < parts.length; ++i2) { - if (parts[i2].indexOf("utf8=") === 0) { - if (parts[i2] === charsetSentinel) { - charset = "utf-8"; - } else if (parts[i2] === isoSentinel) { - charset = "iso-8859-1"; - } - skipIndex = i2; - i2 = parts.length; - } - } - } - for (i2 = 0; i2 < parts.length; ++i2) { - if (i2 === skipIndex) { - continue; - } - var part = parts[i2]; - var bracketEqualsPos = part.indexOf("]="); - var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; - var key, val; - if (pos === -1) { - key = options.decoder(part, defaults.decoder, charset, "key"); - val = options.strictNullHandling ? null : ""; - } else { - key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); - val = utils.maybeMap( - parseArrayValue(part.slice(pos + 1), options), - function(encodedVal) { - return options.decoder(encodedVal, defaults.decoder, charset, "value"); - } - ); - } - if (val && options.interpretNumericEntities && charset === "iso-8859-1") { - val = interpretNumericEntities(val); - } - if (part.indexOf("[]=") > -1) { - val = isArray(val) ? [val] : val; - } - if (has.call(obj, key)) { - obj[key] = utils.combine(obj[key], val); - } else { - obj[key] = val; - } - } - return obj; - }; - var parseObject = function(chain, val, options, valuesParsed) { - var leaf = valuesParsed ? val : parseArrayValue(val, options); - for (var i2 = chain.length - 1; i2 >= 0; --i2) { - var obj; - var root = chain[i2]; - if (root === "[]" && options.parseArrays) { - obj = [].concat(leaf); - } else { - obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; - var index = parseInt(cleanRoot, 10); - if (!options.parseArrays && cleanRoot === "") { - obj = { 0: leaf }; - } else if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) { - obj = []; - obj[index] = leaf; - } else if (cleanRoot !== "__proto__") { - obj[cleanRoot] = leaf; - } - } - leaf = obj; - } - return leaf; - }; - var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { - if (!givenKey) { - return; - } - var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; - var brackets = /(\[[^[\]]*])/; - var child = /(\[[^[\]]*])/g; - var segment = options.depth > 0 && brackets.exec(key); - var parent = segment ? key.slice(0, segment.index) : key; - var keys2 = []; - if (parent) { - if (!options.plainObjects && has.call(Object.prototype, parent)) { - if (!options.allowPrototypes) { - return; - } - } - keys2.push(parent); - } - var i2 = 0; - while (options.depth > 0 && (segment = child.exec(key)) !== null && i2 < options.depth) { - i2 += 1; - if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { - if (!options.allowPrototypes) { - return; - } - } - keys2.push(segment[1]); - } - if (segment) { - keys2.push("[" + key.slice(segment.index) + "]"); - } - return parseObject(keys2, val, options, valuesParsed); - }; - var normalizeParseOptions = function normalizeParseOptions2(opts) { - if (!opts) { - return defaults; - } - if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") { - throw new TypeError("Decoder has to be a function."); - } - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; - return { - allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, - allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, - allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, - arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, - decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, - delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, - // eslint-disable-next-line no-implicit-coercion, no-extra-parens - depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, - ignoreQueryPrefix: opts.ignoreQueryPrefix === true, - interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, - parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, - parseArrays: opts.parseArrays !== false, - plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; - }; - module2.exports = function(str, opts) { - var options = normalizeParseOptions(opts); - if (str === "" || str === null || typeof str === "undefined") { - return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - } - var tempObj = typeof str === "string" ? parseValues(str, options) : str; - var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - var keys2 = Object.keys(tempObj); - for (var i2 = 0; i2 < keys2.length; ++i2) { - var key = keys2[i2]; - var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); - obj = utils.merge(obj, newObj, options); - } - if (options.allowSparse === true) { - return obj; - } - return utils.compact(obj); - }; - } -}); - -// node_modules/qs/lib/index.js -var require_lib = __commonJS({ - "node_modules/qs/lib/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var stringify2 = require_stringify2(); - var parse = require_parse2(); - var formats = require_formats(); - module2.exports = { - formats, - parse, - stringify: stringify2 - }; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js -var require_constants7 = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = exports2.WALLET_PROVIDER_CALLBACK_PARAM = exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = exports2.WALLET_PROVIDER_DISCONNECT_URL = exports2.WALLET_PROVIDER_CONNECT_URL = exports2.XALIAS_PROVIDER_TESTNET = exports2.XALIAS_PROVIDER_DEVNET = exports2.XALIAS_PROVIDER_MAINNET = exports2.WALLET_PROVIDER_TESTNET = exports2.WALLET_PROVIDER_DEVNET = exports2.WALLET_PROVIDER_MAINNET = void 0; - exports2.WALLET_PROVIDER_MAINNET = "https://wallet.multiversx.com/dapp/init"; - exports2.WALLET_PROVIDER_DEVNET = "https://devnet-wallet.multiversx.com/dapp/init"; - exports2.WALLET_PROVIDER_TESTNET = "https://testnet-wallet.multiversx.com/dapp/init"; - exports2.XALIAS_PROVIDER_MAINNET = "https://xalias.com"; - exports2.XALIAS_PROVIDER_DEVNET = "https://devnet.xalias.com"; - exports2.XALIAS_PROVIDER_TESTNET = "https://testnet.xalias.com"; - exports2.WALLET_PROVIDER_CONNECT_URL = "hook/login"; - exports2.WALLET_PROVIDER_DISCONNECT_URL = "hook/logout"; - exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = "hook/transaction"; - exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = "hook/sign"; - exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = "hook/2fa"; - exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = "hook/sign-message"; - exports2.WALLET_PROVIDER_CALLBACK_PARAM = "walletProviderStatus"; - exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = "transactionsSigned"; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js -var require_errors4 = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrCannotSignedMessage = exports2.ErrCannotGetSignedTransactions = void 0; - var ErrCannotGetSignedTransactions = class extends Error { - constructor() { - super("Cannot get signed transaction(s)"); - } - }; - exports2.ErrCannotGetSignedTransactions = ErrCannotGetSignedTransactions; - var ErrCannotSignedMessage = class extends Error { - constructor() { - super("Cannot get signed message"); - } - }; - exports2.ErrCannotSignedMessage = ErrCannotSignedMessage; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js -var require_plainSignedTransaction = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PlainSignedTransaction = void 0; - var PlainSignedTransaction = class { - constructor(init) { - this.nonce = 0; - this.value = ""; - this.receiver = ""; - this.sender = ""; - this.gasPrice = 0; - this.gasLimit = 0; - this.data = ""; - this.chainID = ""; - this.version = 0; - this.signature = ""; - Object.assign(this, init); - } - }; - exports2.PlainSignedTransaction = PlainSignedTransaction; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js -var require_walletProvider = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WalletProvider = void 0; - var qs_1 = __importDefault2(require_lib()); - var constants_1 = require_constants7(); - var errors_1 = require_errors4(); - var plainSignedTransaction_1 = require_plainSignedTransaction(); - var WalletProvider6 = class _WalletProvider { - /** - * Creates a new WalletProvider - * @param walletURL - */ - constructor(walletURL) { - this.walletUrl = walletURL; - } - /** - * Fetches the login hook url and redirects the client to the wallet login. - */ - login(options) { - return __awaiter2(this, void 0, void 0, function* () { - const redirectUrl = this.buildWalletUrl({ - endpoint: constants_1.WALLET_PROVIDER_CONNECT_URL, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, - params: { - token: options === null || options === void 0 ? void 0 : options.token - } - }); - yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); - return redirectUrl; - }); - } - redirect(url, delayMilliseconds) { - return __awaiter2(this, void 0, void 0, function* () { - if (delayMilliseconds) { - yield this.redirectLater(url, delayMilliseconds); - } else { - this.redirectImmediately(url); - } - }); - } - redirectImmediately(url) { - window.location.href = url; - } - redirectLater(url, delayMilliseconds) { - return __awaiter2(this, void 0, void 0, function* () { - yield new Promise((resolve) => { - setTimeout(() => { - window.location.href = url; - resolve(true); - }, delayMilliseconds); - }); - }); - } - /** - * Fetches the logout hook url and redirects the client to the wallet logout. - */ - logout(options) { - return __awaiter2(this, void 0, void 0, function* () { - const redirectUrl = this.buildWalletUrl({ - endpoint: constants_1.WALLET_PROVIDER_DISCONNECT_URL, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl - }); - yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); - return true; - }); - } - /** - * Packs a {@link SignMessage} and fetches correct redirect URL from the wallet API. Then redirects - * the client to the sign message hook - * @param message - * @param options - */ - signMessage(message, options) { - return __awaiter2(this, void 0, void 0, function* () { - const redirectUrl = this.buildWalletUrl({ - endpoint: constants_1.WALLET_PROVIDER_SIGN_MESSAGE_URL, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, - params: { - message: message.message.toString() - } - }); - yield this.redirect(redirectUrl); - return redirectUrl; - }); - } - getMessageSignatureFromWalletUrl() { - var _a, _b; - const url = window.location.search.slice(1); - console.info("getMessageSignatureFromWalletUrl(), url:", url); - const urlParams = qs_1.default.parse(url); - const status = ((_a = urlParams.status) === null || _a === void 0 ? void 0 : _a.toString()) || ""; - const expectedStatus = "signed"; - if (status !== expectedStatus) { - throw new errors_1.ErrCannotSignedMessage(); - } - const signature = ((_b = urlParams.signature) === null || _b === void 0 ? void 0 : _b.toString()) || ""; - return signature; - } - /** - * Packs an array of {$link Transaction} and redirects to the 2fa hook - * - * @param transactions - * @param options - */ - guardTransactions(transactions, options) { - return __awaiter2(this, void 0, void 0, function* () { - this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_GUARD_TRANSACTION_URL, transactions, options); - }); - } - /** - * Packs an array of {$link Transaction} and redirects to the correct transaction sigining hook - * - * @param transactions - * @param options - */ - signTransactions(transactions, options) { - return __awaiter2(this, void 0, void 0, function* () { - this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_SIGN_TRANSACTION_URL, transactions, options); - }); - } - /** - * Packs a {@link Transaction} and fetches correct redirect URL from the wallet API. Then redirects - * the client to the sign transaction hook - * @param transaction - * @param options - */ - signTransaction(transaction, options) { - return __awaiter2(this, void 0, void 0, function* () { - yield this.signTransactions([transaction], options); - }); - } - getTransactionsFromWalletUrl(search = window.location.search) { - const urlParams = qs_1.default.parse(search.slice(1)); - if (!_WalletProvider.isTxSignReturnSuccess(urlParams)) { - return []; - } - return this.getTxSignReturnValue(urlParams); - } - static isTxSignReturnSuccess(urlParams) { - return urlParams.hasOwnProperty(constants_1.WALLET_PROVIDER_CALLBACK_PARAM) && urlParams[constants_1.WALLET_PROVIDER_CALLBACK_PARAM] === constants_1.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED; - } - getTxSignReturnValue(urlParams) { - console.info("getTxSignReturnValue(), urlParams:", urlParams); - const expectedProps = [ - "nonce", - "value", - "receiver", - "sender", - "gasPrice", - "gasLimit", - "chainID", - "version", - "signature" - ]; - for (let txProp of expectedProps) { - if (!urlParams[txProp] || !Array.isArray(urlParams[txProp])) { - throw new errors_1.ErrCannotGetSignedTransactions(); - } - } - const expectedLength = urlParams["nonce"].length; - for (let txProp of expectedProps) { - if (urlParams[txProp].length !== expectedLength) { - throw new errors_1.ErrCannotGetSignedTransactions(); - } - } - const transactions = []; - for (let i2 = 0; i2 < expectedLength; i2++) { - let plainSignedTransaction = new plainSignedTransaction_1.PlainSignedTransaction(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ - nonce: parseInt(urlParams["nonce"][i2]), - value: urlParams["value"][i2], - receiver: urlParams["receiver"][i2], - sender: urlParams["sender"][i2], - gasPrice: parseInt(urlParams["gasPrice"][i2]), - gasLimit: parseInt(urlParams["gasLimit"][i2]), - // Handle the optional "data" property. - data: urlParams["data"] && urlParams["data"][i2] ? urlParams["data"][i2] : "", - chainID: urlParams["chainID"][i2], - version: parseInt(urlParams["version"][i2]) - }, urlParams["guardian"] && urlParams["guardian"][i2] ? { guardian: urlParams["guardian"][i2] } : {}), urlParams["guardianSignature"] && urlParams["guardianSignature"][i2] ? { guardianSignature: urlParams["guardianSignature"][i2] } : {}), urlParams["options"] && urlParams["options"][i2] ? { - options: parseInt(urlParams["options"][i2]) - } : {}), urlParams["senderUsername"] && urlParams["senderUsername"][i2] ? { senderUsername: urlParams["senderUsername"][i2] } : {}), urlParams["receiverUsername"] && urlParams["receiverUsername"][i2] ? { receiverUsername: urlParams["receiverUsername"][i2] } : {}), { signature: urlParams["signature"][i2] })); - transactions.push(plainSignedTransaction); - } - return transactions; - } - static prepareWalletTransaction(transaction) { - let plainTransaction = transaction.toPlainObject(); - if (plainTransaction.data) { - plainTransaction.data = import_buffer.Buffer.from(plainTransaction.data, "base64").toString(); - } else { - plainTransaction.data = ""; - } - return plainTransaction; - } - buildWalletUrl(options) { - const callbackUrl = (options === null || options === void 0 ? void 0 : options.callbackUrl) || window.location.href; - const partialQueryString = qs_1.default.stringify(options.params || {}); - const fullQueryString = partialQueryString ? `${partialQueryString}&callbackUrl=${callbackUrl}` : `callbackUrl=${callbackUrl}`; - const url = `${this.baseWalletUrl()}/${options.endpoint}?${fullQueryString}`; - console.info(`Redirecting to Wallet URL: ${decodeURI(url)}`); - return url; - } - baseWalletUrl() { - const pathArray = this.walletUrl.split("/"); - const protocol = pathArray[0]; - const host = pathArray[2]; - return protocol + "//" + host; - } - /** - * Packs an array of {$link Transaction} and redirects to the specified wallet hook - * - * @param transactions - * @param options - */ - redirectTransactionsToEndpoint(endpoint, transactions, options) { - const jsonToSend = {}; - transactions.map((tx) => { - let plainTx = _WalletProvider.prepareWalletTransaction(tx); - for (let txProp in plainTx) { - if (plainTx.hasOwnProperty(txProp) && !jsonToSend.hasOwnProperty(txProp)) { - jsonToSend[txProp] = []; - } - jsonToSend[txProp].push(plainTx[txProp]); - } - }); - const redirectUrl = this.buildWalletUrl({ - endpoint, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, - params: jsonToSend - }); - window.location.href = redirectUrl; - } - }; - exports2.WalletProvider = WalletProvider6; - } -}); - -// node_modules/axios/dist/browser/axios.cjs -var require_axios = __commonJS({ - "node_modules/axios/dist/browser/axios.cjs"(exports2, module2) { - "use strict"; - init_shim(); - function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; - } - var { toString: toString3 } = Object.prototype; - var { getPrototypeOf } = Object; - var kindOf = /* @__PURE__ */ ((cache) => (thing) => { - const str = toString3.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - })(/* @__PURE__ */ Object.create(null)); - var kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type; - }; - var typeOfTest = (type) => (thing) => typeof thing === type; - var { isArray } = Array; - var isUndefined = typeOfTest("undefined"); - function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); - } - var isArrayBuffer = kindOfTest("ArrayBuffer"); - function isArrayBufferView(val) { - let result; - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && isArrayBuffer(val.buffer); - } - return result; - } - var isString2 = typeOfTest("string"); - var isFunction = typeOfTest("function"); - var isNumber = typeOfTest("number"); - var isObject = (thing) => thing !== null && typeof thing === "object"; - var isBoolean = (thing) => thing === true || thing === false; - var isPlainObject = (val) => { - if (kindOf(val) !== "object") { - return false; - } - const prototype2 = getPrototypeOf(val); - return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); - }; - var isDate = kindOfTest("Date"); - var isFile = kindOfTest("File"); - var isBlob = kindOfTest("Blob"); - var isFileList = kindOfTest("FileList"); - var isStream = (val) => isObject(val) && isFunction(val.pipe); - var isFormData = (thing) => { - let kind; - return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance - kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); - }; - var isURLSearchParams = kindOfTest("URLSearchParams"); - var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); - function forEach(obj, fn, { allOwnKeys = false } = {}) { - if (obj === null || typeof obj === "undefined") { - return; - } - let i2; - let l4; - if (typeof obj !== "object") { - obj = [obj]; - } - if (isArray(obj)) { - for (i2 = 0, l4 = obj.length; i2 < l4; i2++) { - fn.call(null, obj[i2], i2, obj); - } - } else { - const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys2.length; - let key; - for (i2 = 0; i2 < len; i2++) { - key = keys2[i2]; - fn.call(null, obj[key], key, obj); - } - } - } - function findKey(obj, key) { - key = key.toLowerCase(); - const keys2 = Object.keys(obj); - let i2 = keys2.length; - let _key; - while (i2-- > 0) { - _key = keys2[i2]; - if (key === _key.toLowerCase()) { - return _key; - } - } - return null; - } - var _global = (() => { - if (typeof globalThis !== "undefined") - return globalThis; - return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; - })(); - var isContextDefined = (context) => !isUndefined(context) && context !== _global; - function merge() { - const { caseless } = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; - } - }; - for (let i2 = 0, l4 = arguments.length; i2 < l4; i2++) { - arguments[i2] && forEach(arguments[i2], assignValue); - } - return result; - } - var extend = (a3, b4, thisArg, { allOwnKeys } = {}) => { - forEach(b4, (val, key) => { - if (thisArg && isFunction(val)) { - a3[key] = bind(val, thisArg); - } else { - a3[key] = val; - } - }, { allOwnKeys }); - return a3; - }; - var stripBOM = (content) => { - if (content.charCodeAt(0) === 65279) { - content = content.slice(1); - } - return content; - }; - var inherits = (constructor, superConstructor, props, descriptors2) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors2); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, "super", { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); - }; - var toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i2; - let prop; - const merged = {}; - destObj = destObj || {}; - if (sourceObj == null) - return destObj; - do { - props = Object.getOwnPropertyNames(sourceObj); - i2 = props.length; - while (i2-- > 0) { - prop = props[i2]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - return destObj; - }; - var endsWith = (str, searchString, position) => { - str = String(str); - if (position === void 0 || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; - }; - var toArray = (thing) => { - if (!thing) - return null; - if (isArray(thing)) - return thing; - let i2 = thing.length; - if (!isNumber(i2)) - return null; - const arr = new Array(i2); - while (i2-- > 0) { - arr[i2] = thing[i2]; - } - return arr; - }; - var isTypedArray = /* @__PURE__ */ ((TypedArray) => { - return (thing) => { - return TypedArray && thing instanceof TypedArray; - }; - })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); - var forEachEntry = (obj, fn) => { - const generator = obj && obj[Symbol.iterator]; - const iterator = generator.call(obj); - let result; - while ((result = iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); - } - }; - var matchAll = (regExp, str) => { - let matches; - const arr = []; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } - return arr; - }; - var isHTMLForm = kindOfTest("HTMLFormElement"); - var toCamelCase = (str) => { - return str.toLowerCase().replace( - /[-_\s]([a-z\d])(\w*)/g, - function replacer(m3, p1, p22) { - return p1.toUpperCase() + p22; - } - ); - }; - var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); - var isRegExp = kindOfTest("RegExp"); - var reduceDescriptors = (obj, reducer) => { - const descriptors2 = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - forEach(descriptors2, (descriptor, name2) => { - let ret; - if ((ret = reducer(descriptor, name2, obj)) !== false) { - reducedDescriptors[name2] = ret || descriptor; - } - }); - Object.defineProperties(obj, reducedDescriptors); - }; - var freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name2) => { - if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) { - return false; - } - const value = obj[name2]; - if (!isFunction(value)) - return; - descriptor.enumerable = false; - if ("writable" in descriptor) { - descriptor.writable = false; - return; - } - if (!descriptor.set) { - descriptor.set = () => { - throw Error("Can not rewrite read-only method '" + name2 + "'"); - }; - } - }); - }; - var toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - const define2 = (arr) => { - arr.forEach((value) => { - obj[value] = true; - }); - }; - isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); - return obj; - }; - var noop = () => { - }; - var toFiniteNumber = (value, defaultValue) => { - value = +value; - return Number.isFinite(value) ? value : defaultValue; - }; - var ALPHA = "abcdefghijklmnopqrstuvwxyz"; - var DIGIT = "0123456789"; - var ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT - }; - var generateString = (size = 16, alphabet2 = ALPHABET.ALPHA_DIGIT) => { - let str = ""; - const { length: length2 } = alphabet2; - while (size--) { - str += alphabet2[Math.random() * length2 | 0]; - } - return str; - }; - function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); - } - var toJSONObject = (obj) => { - const stack = new Array(10); - const visit = (source, i2) => { - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - if (!("toJSON" in source)) { - stack[i2] = source; - const target = isArray(source) ? [] : {}; - forEach(source, (value, key) => { - const reducedValue = visit(value, i2 + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); - stack[i2] = void 0; - return target; - } - } - return source; - }; - return visit(obj, 0); - }; - var isAsyncFn = kindOfTest("AsyncFunction"); - var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); - var utils$1 = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString: isString2, - isNumber, - isBoolean, - isObject, - isPlainObject, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, - // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - ALPHABET, - generateString, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable - }; - function AxiosError(message, code2, config, request, response) { - Error.call(this); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error().stack; - } - this.message = message; - this.name = "AxiosError"; - code2 && (this.code = code2); - config && (this.config = config); - request && (this.request = request); - response && (this.response = response); - } - utils$1.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - } - }); - var prototype$1 = AxiosError.prototype; - var descriptors = {}; - [ - "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" - // eslint-disable-next-line func-names - ].forEach((code2) => { - descriptors[code2] = { value: code2 }; - }); - Object.defineProperties(AxiosError, descriptors); - Object.defineProperty(prototype$1, "isAxiosError", { value: true }); - AxiosError.from = (error, code2, config, request, response, customProps) => { - const axiosError = Object.create(prototype$1); - utils$1.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, (prop) => { - return prop !== "isAxiosError"; - }); - AxiosError.call(axiosError, error.message, code2, config, request, response); - axiosError.cause = error; - axiosError.name = error.name; - customProps && Object.assign(axiosError, customProps); - return axiosError; - }; - var httpAdapter = null; - function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); - } - function removeBrackets(key) { - return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; - } - function renderKey(path, key, dots) { - if (!path) - return key; - return path.concat(key).map(function each(token, i2) { - token = removeBrackets(token); - return !dots && i2 ? "[" + token + "]" : token; - }).join(dots ? "." : ""); - } - function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); - } - var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); - }); - function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { - throw new TypeError("target must be an object"); - } - formData = formData || new FormData(); - options = utils$1.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - return !utils$1.isUndefined(source[option]); - }); - const metaTokens = options.metaTokens; - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); - if (!utils$1.isFunction(visitor)) { - throw new TypeError("visitor must be a function"); - } - function convertValue(value) { - if (value === null) - return ""; - if (utils$1.isDate(value)) { - return value.toISOString(); - } - if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError("Blob is not supported. Use a Buffer instead."); - } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === "function" ? new Blob([value]) : import_buffer.Buffer.from(value); - } - return value; - } - function defaultVisitor(value, key, path) { - let arr = value; - if (value && !path && typeof value === "object") { - if (utils$1.endsWith(key, "{}")) { - key = metaTokens ? key : key.slice(0, -2); - value = JSON.stringify(value); - } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { - key = removeBrackets(key); - arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", - convertValue(el) - ); - }); - return false; - } - } - if (isVisitable(value)) { - return true; - } - formData.append(renderKey(path, key, dots), convertValue(value)); - return false; - } - const stack = []; - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); - function build(value, path) { - if (utils$1.isUndefined(value)) - return; - if (stack.indexOf(value) !== -1) { - throw Error("Circular reference detected in " + path.join(".")); - } - stack.push(value); - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, - el, - utils$1.isString(key) ? key.trim() : key, - path, - exposedHelpers - ); - if (result === true) { - build(el, path ? path.concat(key) : [key]); - } - }); - stack.pop(); - } - if (!utils$1.isObject(obj)) { - throw new TypeError("data must be an object"); - } - build(obj); - return formData; - } - function encode$1(str) { - const charMap = { - "!": "%21", - "'": "%27", - "(": "%28", - ")": "%29", - "~": "%7E", - "%20": "+", - "%00": "\0" - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); - } - function AxiosURLSearchParams(params, options) { - this._pairs = []; - params && toFormData(params, this, options); - } - var prototype = AxiosURLSearchParams.prototype; - prototype.append = function append(name2, value) { - this._pairs.push([name2, value]); - }; - prototype.toString = function toString4(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode$1); - } : encode$1; - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + "=" + _encode(pair[1]); - }, "").join("&"); - }; - function encode5(val) { - return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); - } - function buildURL(url, params, options) { - if (!params) { - return url; - } - const _encode = options && options.encode || encode5; - const serializeFn = options && options.serialize; - let serializedParams; - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); - } - if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; - } - return url; - } - var InterceptorManager = class { - constructor() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise - */ - eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - } - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; - } - } - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h5) { - if (h5 !== null) { - fn(h5); - } - }); - } - }; - var InterceptorManager$1 = InterceptorManager; - var transitionalDefaults = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }; - var URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams; - var FormData$1 = typeof FormData !== "undefined" ? FormData : null; - var Blob$1 = typeof Blob !== "undefined" ? Blob : null; - var platform$1 = { - isBrowser: true, - classes: { - URLSearchParams: URLSearchParams$1, - FormData: FormData$1, - Blob: Blob$1 - }, - protocols: ["http", "https", "file", "blob", "url", "data"] - }; - var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; - var hasStandardBrowserEnv = ((product) => { - return hasBrowserEnv && ["ReactNative", "NativeScript", "NS"].indexOf(product) < 0; - })(typeof navigator !== "undefined" && navigator.product); - var hasStandardBrowserWebWorkerEnv = (() => { - return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; - })(); - var utils = /* @__PURE__ */ Object.freeze({ - __proto__: null, - hasBrowserEnv, - hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv - }); - var platform = { - ...utils, - ...platform$1 - }; - function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ - visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { - this.append(key, value.toString("base64")); - return false; - } - return helpers.defaultVisitor.apply(this, arguments); - } - }, options)); - } - function parsePropPath(name2) { - return utils$1.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => { - return match[0] === "[]" ? "" : match[1] || match[0]; - }); - } - function arrayToObject(arr) { - const obj = {}; - const keys2 = Object.keys(arr); - let i2; - const len = keys2.length; - let key; - for (i2 = 0; i2 < len; i2++) { - key = keys2[i2]; - obj[key] = arr[key]; - } - return obj; - } - function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - let name2 = path[index++]; - if (name2 === "__proto__") - return true; - const isNumericKey = Number.isFinite(+name2); - const isLast = index >= path.length; - name2 = !name2 && utils$1.isArray(target) ? target.length : name2; - if (isLast) { - if (utils$1.hasOwnProp(target, name2)) { - target[name2] = [target[name2], value]; - } else { - target[name2] = value; - } - return !isNumericKey; - } - if (!target[name2] || !utils$1.isObject(target[name2])) { - target[name2] = []; - } - const result = buildPath(path, value, target[name2], index); - if (result && utils$1.isArray(target[name2])) { - target[name2] = arrayToObject(target[name2]); - } - return !isNumericKey; - } - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { - const obj = {}; - utils$1.forEachEntry(formData, (name2, value) => { - buildPath(parsePropPath(name2), value, obj, 0); - }); - return obj; - } - return null; - } - function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); - } catch (e2) { - if (e2.name !== "SyntaxError") { - throw e2; - } - } - } - return (encoder || JSON.stringify)(rawValue); - } - var defaults = { - transitional: transitionalDefaults, - adapter: ["xhr", "http"], - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ""; - const hasJSONContentType = contentType.indexOf("application/json") > -1; - const isObjectPayload = utils$1.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { - data = new FormData(data); - } - const isFormData2 = utils$1.isFormData(data); - if (isFormData2) { - return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; - } - if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data)) { - return data; - } - if (utils$1.isArrayBufferView(data)) { - return data.buffer; - } - if (utils$1.isURLSearchParams(data)) { - headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); - return data.toString(); - } - let isFileList2; - if (isObjectPayload) { - if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { - const _FormData = this.env && this.env.FormData; - return toFormData( - isFileList2 ? { "files[]": data } : data, - _FormData && new _FormData(), - this.formSerializer - ); - } - } - if (isObjectPayload || hasJSONContentType) { - headers.setContentType("application/json", false); - return stringifySafely(data); - } - return data; - }], - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === "json"; - if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - try { - return JSON.parse(data); - } catch (e2) { - if (strictJSONParsing) { - if (e2.name === "SyntaxError") { - throw AxiosError.from(e2, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e2; - } - } - } - return data; - }], - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: "XSRF-TOKEN", - xsrfHeaderName: "X-XSRF-TOKEN", - maxContentLength: -1, - maxBodyLength: -1, - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob - }, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - "Accept": "application/json, text/plain, */*", - "Content-Type": void 0 - } - } - }; - utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { - defaults.headers[method] = {}; - }); - var defaults$1 = defaults; - var ignoreDuplicateOf = utils$1.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" - ]); - var parseHeaders = (rawHeaders) => { - const parsed = {}; - let key; - let val; - let i2; - rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { - i2 = line.indexOf(":"); - key = line.substring(0, i2).trim().toLowerCase(); - val = line.substring(i2 + 1).trim(); - if (!key || parsed[key] && ignoreDuplicateOf[key]) { - return; - } - if (key === "set-cookie") { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; - } - }); - return parsed; - }; - var $internals = Symbol("internals"); - function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); - } - function normalizeValue(value) { - if (value === false || value == null) { - return value; - } - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); - } - function parseTokens(str) { - const tokens = /* @__PURE__ */ Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - while (match = tokensRE.exec(str)) { - tokens[match[1]] = match[2]; - } - return tokens; - } - var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); - function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { - return filter.call(this, value, header); - } - if (isHeaderNameFilter) { - value = header; - } - if (!utils$1.isString(value)) - return; - if (utils$1.isString(filter)) { - return value.indexOf(filter) !== -1; - } - if (utils$1.isRegExp(filter)) { - return filter.test(value); - } - } - function formatHeader(header) { - return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w4, char, str) => { - return char.toUpperCase() + str; - }); - } - function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(" " + header); - ["get", "set", "has"].forEach((methodName) => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); - } - var AxiosHeaders = class { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self2 = this; - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); - if (!lHeader) { - throw new Error("header name must be a non-empty string"); - } - const key = utils$1.findKey(self2, lHeader); - if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { - self2[key || _header] = normalizeValue(_value); - } - } - const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); - } - return this; - } - get(header, parser) { - header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); - if (key) { - const value = this[key]; - if (!parser) { - return value; - } - if (parser === true) { - return parseTokens(value); - } - if (utils$1.isFunction(parser)) { - return parser.call(this, value, key); - } - if (utils$1.isRegExp(parser)) { - return parser.exec(value); - } - throw new TypeError("parser must be boolean|regexp|function"); - } - } - } - has(header, matcher) { - header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); - return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); - } - return false; - } - delete(header, matcher) { - const self2 = this; - let deleted = false; - function deleteHeader(_header) { - _header = normalizeHeader(_header); - if (_header) { - const key = utils$1.findKey(self2, _header); - if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { - delete self2[key]; - deleted = true; - } - } - } - if (utils$1.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); - } - return deleted; - } - clear(matcher) { - const keys2 = Object.keys(this); - let i2 = keys2.length; - let deleted = false; - while (i2--) { - const key = keys2[i2]; - if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } - return deleted; - } - normalize(format) { - const self2 = this; - const headers = {}; - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); - if (key) { - self2[key] = normalizeValue(value); - delete self2[header]; - return; - } - const normalized = format ? formatHeader(header) : String(header).trim(); - if (normalized !== header) { - delete self2[header]; - } - self2[normalized] = normalizeValue(value); - headers[normalized] = true; - }); - return this; - } - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - toJSON(asStrings) { - const obj = /* @__PURE__ */ Object.create(null); - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); - }); - return obj; - } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); - } - get [Symbol.toStringTag]() { - return "AxiosHeaders"; - } - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } - static concat(first, ...targets) { - const computed = new this(first); - targets.forEach((target) => computed.set(target)); - return computed; - } - static accessor(header) { - const internals = this[$internals] = this[$internals] = { - accessors: {} - }; - const accessors = internals.accessors; - const prototype2 = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); - if (!accessors[lHeader]) { - buildAccessors(prototype2, _header); - accessors[lHeader] = true; - } - } - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - return this; - } - }; - AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); - utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; - } - }; - }); - utils$1.freezeMethods(AxiosHeaders); - var AxiosHeaders$1 = AxiosHeaders; - function transformData(fns, response) { - const config = this || defaults$1; - const context = response || config; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; - utils$1.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); - }); - headers.normalize(); - return data; - } - function isCancel(value) { - return !!(value && value.__CANCEL__); - } - function CanceledError(message, config, request) { - AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request); - this.name = "CanceledError"; - } - utils$1.inherits(CanceledError, AxiosError, { - __CANCEL__: true - }); - function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - "Request failed with status code " + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } - } - var cookies = platform.hasStandardBrowserEnv ? ( - // Standard browser envs support document.cookie - { - write(name2, value, expires, path, domain, secure) { - const cookie = [name2 + "=" + encodeURIComponent(value)]; - utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); - utils$1.isString(path) && cookie.push("path=" + path); - utils$1.isString(domain) && cookie.push("domain=" + domain); - secure === true && cookie.push("secure"); - document.cookie = cookie.join("; "); - }, - read(name2) { - const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name2 + ")=([^;]*)")); - return match ? decodeURIComponent(match[3]) : null; - }, - remove(name2) { - this.write(name2, "", Date.now() - 864e5); - } - } - ) : ( - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() { - }, - read() { - return null; - }, - remove() { - } - } - ); - function isAbsoluteURL(url) { - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); - } - function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; - } - function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; - } - var isURLSameOrigin = platform.hasStandardBrowserEnv ? ( - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - function standardBrowserEnv() { - const msie = /(msie|trident)/i.test(navigator.userAgent); - const urlParsingNode = document.createElement("a"); - let originURL; - function resolveURL(url) { - let href = url; - if (msie) { - urlParsingNode.setAttribute("href", href); - href = urlParsingNode.href; - } - urlParsingNode.setAttribute("href", href); - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname - }; - } - originURL = resolveURL(window.location.href); - return function isURLSameOrigin2(requestURL) { - const parsed = utils$1.isString(requestURL) ? resolveURL(requestURL) : requestURL; - return parsed.protocol === originURL.protocol && parsed.host === originURL.host; - }; - }() - ) : ( - // Non standard browser envs (web workers, react-native) lack needed support. - /* @__PURE__ */ function nonStandardBrowserEnv() { - return function isURLSameOrigin2() { - return true; - }; - }() - ); - function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ""; - } - function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - min = min !== void 0 ? min : 1e3; - return function push(chunkLength) { - const now = Date.now(); - const startedAt = timestamps[tail]; - if (!firstSampleTS) { - firstSampleTS = now; - } - bytes[head] = chunkLength; - timestamps[head] = now; - let i2 = tail; - let bytesCount = 0; - while (i2 !== head) { - bytesCount += bytes[i2++]; - i2 = i2 % samplesCount; - } - head = (head + 1) % samplesCount; - if (head === tail) { - tail = (tail + 1) % samplesCount; - } - if (now - firstSampleTS < min) { - return; - } - const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; - }; - } - function progressEventReducer(listener, isDownloadStream) { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); - return (e2) => { - const loaded = e2.loaded; - const total = e2.lengthComputable ? e2.total : void 0; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; - bytesNotified = loaded; - const data = { - loaded, - total, - progress: total ? loaded / total : void 0, - bytes: progressBytes, - rate: rate ? rate : void 0, - estimated: rate && total && inRange ? (total - loaded) / rate : void 0, - event: e2 - }; - data[isDownloadStream ? "download" : "upload"] = true; - listener(data); - }; - } - var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; - var xhrAdapter = isXHRAdapterSupported && function(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - let requestData = config.data; - const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); - let { responseType, withXSRFToken } = config; - let onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - if (config.signal) { - config.signal.removeEventListener("abort", onCanceled); - } - } - let contentType; - if (utils$1.isFormData(requestData)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - requestHeaders.setContentType(false); - } else if ((contentType = requestHeaders.getContentType()) !== false) { - const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; - requestHeaders.setContentType([type || "multipart/form-data", ...tokens].join("; ")); - } - } - let request = new XMLHttpRequest(); - if (config.auth) { - const username = config.auth.username || ""; - const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; - requestHeaders.set("Authorization", "Basic " + btoa(username + ":" + password)); - } - const fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - request.timeout = config.timeout; - function onloadend() { - if (!request) { - return; - } - const responseHeaders = AxiosHeaders$1.from( - "getAllResponseHeaders" in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - request = null; - } - if ("onloadend" in request) { - request.onloadend = onloadend; - } else { - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { - return; - } - setTimeout(onloadend); - }; - } - request.onabort = function handleAbort() { - if (!request) { - return; - } - reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request)); - request = null; - }; - request.onerror = function handleError() { - reject(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request)); - request = null; - }; - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; - const transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request - )); - request = null; - }; - if (platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); - if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(fullPath)) { - const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); - if (xsrfValue) { - requestHeaders.set(config.xsrfHeaderName, xsrfValue); - } - } - } - requestData === void 0 && requestHeaders.setContentType(null); - if ("setRequestHeader" in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - } - if (!utils$1.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } - if (responseType && responseType !== "json") { - request.responseType = config.responseType; - } - if (typeof config.onDownloadProgress === "function") { - request.addEventListener("progress", progressEventReducer(config.onDownloadProgress, true)); - } - if (typeof config.onUploadProgress === "function" && request.upload) { - request.upload.addEventListener("progress", progressEventReducer(config.onUploadProgress)); - } - if (config.cancelToken || config.signal) { - onCanceled = (cancel) => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); - request = null; - }; - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); - } - } - const protocol = parseProtocol(fullPath); - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config)); - return; - } - request.send(requestData || null); - }); - }; - var knownAdapters = { - http: httpAdapter, - xhr: xhrAdapter - }; - utils$1.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, "name", { value }); - } catch (e2) { - } - Object.defineProperty(fn, "adapterName", { value }); - } - }); - var renderReason = (reason) => `- ${reason}`; - var isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; - var adapters = { - getAdapter: (adapters2) => { - adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; - const { length: length2 } = adapters2; - let nameOrAdapter; - let adapter; - const rejectedReasons = {}; - for (let i2 = 0; i2 < length2; i2++) { - nameOrAdapter = adapters2[i2]; - let id; - adapter = nameOrAdapter; - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; - if (adapter === void 0) { - throw new AxiosError(`Unknown adapter '${id}'`); - } - } - if (adapter) { - break; - } - rejectedReasons[id || "#" + i2] = adapter; - } - if (!adapter) { - const reasons = Object.entries(rejectedReasons).map( - ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build") - ); - let s2 = length2 ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; - throw new AxiosError( - `There is no suitable adapter to dispatch the request ` + s2, - "ERR_NOT_SUPPORT" - ); - } - return adapter; - }, - adapters: knownAdapters - }; - function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); - } - } - function dispatchRequest(config) { - throwIfCancellationRequested(config); - config.headers = AxiosHeaders$1.from(config.headers); - config.data = transformData.call( - config, - config.transformRequest - ); - if (["post", "put", "patch"].indexOf(config.method) !== -1) { - config.headers.setContentType("application/x-www-form-urlencoded", false); - } - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - response.data = transformData.call( - config, - config.transformResponse, - response - ); - response.headers = AxiosHeaders$1.from(response.headers); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); - } - } - return Promise.reject(reason); - }); - } - var headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; - function mergeConfig(config1, config2) { - config2 = config2 || {}; - const config = {}; - function getMergedValue(target, source, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({ caseless }, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; - } - function mergeDeepProperties(a3, b4, caseless) { - if (!utils$1.isUndefined(b4)) { - return getMergedValue(a3, b4, caseless); - } else if (!utils$1.isUndefined(a3)) { - return getMergedValue(void 0, a3, caseless); - } - } - function valueFromConfig2(a3, b4) { - if (!utils$1.isUndefined(b4)) { - return getMergedValue(void 0, b4); - } - } - function defaultToConfig2(a3, b4) { - if (!utils$1.isUndefined(b4)) { - return getMergedValue(void 0, b4); - } else if (!utils$1.isUndefined(a3)) { - return getMergedValue(void 0, a3); - } - } - function mergeDirectKeys(a3, b4, prop) { - if (prop in config2) { - return getMergedValue(a3, b4); - } else if (prop in config1) { - return getMergedValue(void 0, a3); - } - } - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a3, b4) => mergeDeepProperties(headersToObject(a3), headersToObject(b4), true) - }; - utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { - const merge2 = mergeMap[prop] || mergeDeepProperties; - const configValue = merge2(config1[prop], config2[prop], prop); - utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); - }); - return config; - } - var VERSION = "1.6.8"; - var validators$1 = {}; - ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => { - validators$1[type] = function validator2(thing) { - return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type; - }; - }); - var deprecatedWarnings = {}; - validators$1.transitional = function transitional(validator2, version2, message) { - function formatMessage(opt, desc) { - return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); - } - return (value, opt, opts) => { - if (validator2 === false) { - throw new AxiosError( - formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")), - AxiosError.ERR_DEPRECATED - ); - } - if (version2 && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - console.warn( - formatMessage( - opt, - " has been deprecated since v" + version2 + " and will be removed in the near future" - ) - ); - } - return validator2 ? validator2(value, opt, opts) : true; - }; - }; - function assertOptions(options, schema, allowUnknown) { - if (typeof options !== "object") { - throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE); - } - const keys2 = Object.keys(options); - let i2 = keys2.length; - while (i2-- > 0) { - const opt = keys2[i2]; - const validator2 = schema[opt]; - if (validator2) { - const value = options[opt]; - const result = value === void 0 || validator2(value, opt, options); - if (result !== true) { - throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE); - } - continue; - } - if (allowUnknown !== true) { - throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION); - } - } - } - var validator = { - assertOptions, - validators: validators$1 - }; - var validators = validator.validators; - var Axios = class { - constructor(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() - }; - } - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy; - Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : dummy = new Error(); - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; - if (!err.stack) { - err.stack = stack; - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { - err.stack += "\n" + stack; - } - } - throw err; - } - } - _request(configOrUrl, config) { - if (typeof configOrUrl === "string") { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; - } - config = mergeConfig(this.defaults, config); - const { transitional, paramsSerializer, headers } = config; - if (transitional !== void 0) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } - if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { - config.paramsSerializer = { - serialize: paramsSerializer - }; - } else { - validator.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); - } - } - config.method = (config.method || this.defaults.method || "get").toLowerCase(); - let contextHeaders = headers && utils$1.merge( - headers.common, - headers[config.method] - ); - headers && utils$1.forEach( - ["delete", "get", "head", "post", "put", "patch", "common"], - (method) => { - delete headers[method]; - } - ); - config.headers = AxiosHeaders$1.concat(contextHeaders, headers); - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { - return; - } - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - let promise; - let i2 = 0; - let len; - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), void 0]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); - len = chain.length; - promise = Promise.resolve(config); - while (i2 < len) { - promise = promise.then(chain[i2++], chain[i2++]); - } - return promise; - } - len = requestInterceptorChain.length; - let newConfig = config; - i2 = 0; - while (i2 < len) { - const onFulfilled = requestInterceptorChain[i2++]; - const onRejected = requestInterceptorChain[i2++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; - } - } - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); - } - i2 = 0; - len = responseInterceptorChain.length; - while (i2 < len) { - promise = promise.then(responseInterceptorChain[i2++], responseInterceptorChain[i2++]); - } - return promise; - } - getUri(config) { - config = mergeConfig(this.defaults, config); - const fullPath = buildFullPath(config.baseURL, config.url); - return buildURL(fullPath, config.params, config.paramsSerializer); - } - }; - utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: (config || {}).data - })); - }; - }); - utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - "Content-Type": "multipart/form-data" - } : {}, - url, - data - })); - }; - } - Axios.prototype[method] = generateHTTPMethod(); - Axios.prototype[method + "Form"] = generateHTTPMethod(true); - }); - var Axios$1 = Axios; - var CancelToken = class _CancelToken { - constructor(executor) { - if (typeof executor !== "function") { - throw new TypeError("executor must be a function."); - } - let resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - const token = this; - this.promise.then((cancel) => { - if (!token._listeners) - return; - let i2 = token._listeners.length; - while (i2-- > 0) { - token._listeners[i2](cancel); - } - token._listeners = null; - }); - this.promise.then = (onfulfilled) => { - let _resolve; - const promise = new Promise((resolve) => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - return promise; - }; - executor(function cancel(message, config, request) { - if (token.reason) { - return; - } - token.reason = new CanceledError(message, config, request); - resolvePromise(token.reason); - }); - } - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) { - throw this.reason; - } - } - /** - * Subscribe to the cancel signal - */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - } - /** - * Unsubscribe from the cancel signal - */ - unsubscribe(listener) { - if (!this._listeners) { - return; - } - const index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); - } - } - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - const token = new _CancelToken(function executor(c4) { - cancel = c4; - }); - return { - token, - cancel - }; - } - }; - var CancelToken$1 = CancelToken; - function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - } - function isAxiosError(payload) { - return utils$1.isObject(payload) && payload.isAxiosError === true; - } - var HttpStatusCode = { - 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(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; - }); - var HttpStatusCode$1 = HttpStatusCode; - function createInstance(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind(Axios$1.prototype.request, context); - utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); - utils$1.extend(instance, context, null, { allOwnKeys: true }); - instance.create = function create2(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - return instance; - } - var axios = createInstance(defaults$1); - axios.Axios = Axios$1; - axios.CanceledError = CanceledError; - axios.CancelToken = CancelToken$1; - axios.isCancel = isCancel; - axios.VERSION = VERSION; - axios.toFormData = toFormData; - axios.AxiosError = AxiosError; - axios.Cancel = axios.CanceledError; - axios.all = function all(promises) { - return Promise.all(promises); - }; - axios.spread = spread; - axios.isAxiosError = isAxiosError; - axios.mergeConfig = mergeConfig; - axios.AxiosHeaders = AxiosHeaders$1; - axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); - axios.getAdapter = adapters.getAdapter; - axios.HttpStatusCode = HttpStatusCode$1; - axios.default = axios; - module2.exports = axios; - } -}); - -// node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js -var require_native_auth_client_config = __commonJS({ - "node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NativeAuthClientConfig = void 0; - var NativeAuthClientConfig = class { - constructor() { - this.origin = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.hostname : ""; - this.apiUrl = "https://api.multiversx.com"; - this.expirySeconds = 60 * 60 * 24; - } - }; - exports2.NativeAuthClientConfig = NativeAuthClientConfig; - } -}); - -// node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js -var require_native_auth_client = __commonJS({ - "node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NativeAuthClient = void 0; - var axios_1 = require_axios(); - var native_auth_client_config_1 = require_native_auth_client_config(); - var NativeAuthClient3 = class { - constructor(config) { - this.config = Object.assign(new native_auth_client_config_1.NativeAuthClientConfig(), config); - } - getToken(address, token, signature) { - const encodedAddress = this.encodeValue(address); - const encodedToken = this.encodeValue(token); - const accessToken = `${encodedAddress}.${encodedToken}.${signature}`; - return accessToken; - } - initialize(extraInfo = {}) { - return __awaiter2(this, void 0, void 0, function* () { - const blockHash = yield this.getCurrentBlockHash(); - const encodedExtraInfo = this.encodeValue(JSON.stringify(extraInfo)); - const origin = this.encodeValue(this.config.origin); - return `${origin}.${blockHash}.${this.config.expirySeconds}.${encodedExtraInfo}`; - }); - } - getCurrentBlockHash() { - return __awaiter2(this, void 0, void 0, function* () { - if (this.config.gatewayUrl) { - return yield this.getCurrentBlockHashWithGateway(); - } - return yield this.getCurrentBlockHashWithApi(); - }); - } - getCurrentBlockHashWithGateway() { - return __awaiter2(this, void 0, void 0, function* () { - const round = yield this.getCurrentRound(); - const url = `${this.config.gatewayUrl}/blocks/by-round/${round}`; - const response = yield this.get(url); - const blocks = response.data.data.blocks; - const block = blocks.filter((block2) => block2.shard === this.config.blockHashShard)[0]; - return block.hash; - }); - } - getCurrentRound() { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.config.gatewayUrl) { - throw new Error("Gateway URL not set"); - } - if (!this.config.blockHashShard) { - throw new Error("Blockhash shard not set"); - } - const url = `${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`; - const response = yield this.get(url); - const status = response.data.data.status; - return status.erd_current_round; - }); - } - getCurrentBlockHashWithApi() { - return __awaiter2(this, void 0, void 0, function* () { - try { - const url = `${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`; - const response = yield this.get(url); - if (response.data[0].hash !== void 0) { - return response.data[0].hash; - } - } catch (error) { - } - return this.getCurrentBlockHashWithApiFallback(); - }); - } - getCurrentBlockHashWithApiFallback() { - return __awaiter2(this, void 0, void 0, function* () { - let url = `${this.config.apiUrl}/blocks?size=1&fields=hash`; - if (this.config.blockHashShard !== void 0) { - url += `&shard=${this.config.blockHashShard}`; - } - const response = yield this.get(url); - return response.data[0].hash; - }); - } - encodeValue(str) { - return this.escape(import_buffer.Buffer.from(str, "utf8").toString("base64")); - } - escape(str) { - return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - } - get(url) { - return __awaiter2(this, void 0, void 0, function* () { - return yield axios_1.default.get(url, { headers: this.config.extraRequestHeaders }); - }); - } - }; - exports2.NativeAuthClient = NativeAuthClient3; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js -var require_transactionStatus = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionStatus = void 0; - var TransactionStatus2 = class _TransactionStatus { - /** - * Creates a new TransactionStatus object. - */ - constructor(status) { - this.status = (status || "").toLowerCase(); - } - /** - * Creates an unknown status. - */ - static createUnknown() { - return new _TransactionStatus("unknown"); - } - /** - * Returns whether the transaction is pending (e.g. in mempool). - */ - isPending() { - return this.status == "received" || this.status == "pending"; - } - /** - * Returns whether the transaction has been executed (not necessarily with success). - */ - isExecuted() { - return this.isSuccessful() || this.isFailed() || this.isInvalid(); - } - /** - * Returns whether the transaction has been executed successfully. - */ - isSuccessful() { - return this.status == "executed" || this.status == "success" || this.status == "successful"; - } - /** - * Returns whether the transaction has been executed, but with a failure. - */ - isFailed() { - return this.status == "fail" || this.status == "failed" || this.status == "unsuccessful" || this.isInvalid(); - } - /** - * Returns whether the transaction has been executed, but marked as invalid (e.g. due to "insufficient funds"). - */ - isInvalid() { - return this.status == "invalid"; - } - toString() { - return this.status; - } - valueOf() { - return this.status; - } - equals(other) { - if (!other) { - return false; - } - return this.status == other.status; - } - }; - exports2.TransactionStatus = TransactionStatus2; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js -var require_transactionReceipt = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionReceipt = void 0; - var primitives_1 = require_primitives(); - var TransactionReceipt2 = class _TransactionReceipt { - constructor() { - this.value = ""; - this.sender = new primitives_1.Address(""); - this.data = ""; - this.hash = ""; - } - static fromHttpResponse(response) { - let receipt = new _TransactionReceipt(); - receipt.value = (response.value || 0).toString(); - receipt.sender = new primitives_1.Address(response.sender); - receipt.data = response.data; - receipt.hash = response.txHash; - return receipt; - } - }; - exports2.TransactionReceipt = TransactionReceipt2; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/errors.js -var require_errors5 = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrContractQuery = exports2.ErrNetworkProvider = exports2.ErrUnexpectedCondition = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - }; - exports2.Err = Err; - var ErrUnexpectedCondition = class extends Err { - constructor(message) { - super(`Unexpected condition: [${message}]`); - } - }; - exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; - var ErrNetworkProvider = class extends Err { - constructor(url, error, inner) { - let message = `Request error on url [${url}]: [${error}]`; - super(message, inner); - } - }; - exports2.ErrNetworkProvider = ErrNetworkProvider; - var ErrContractQuery = class extends Err { - constructor(originalError) { - super(originalError.message.replace("executeQuery:", "")); - } - }; - exports2.ErrContractQuery = ErrContractQuery; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js -var require_transactionEvents = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionEventTopic = exports2.TransactionEventData = exports2.TransactionEvent = void 0; - var primitives_1 = require_primitives(); - var TransactionEvent = class _TransactionEvent { - constructor(init) { - this.address = new primitives_1.Address(""); - this.identifier = ""; - this.topics = []; - this.data = ""; - this.dataPayload = new TransactionEventData(import_buffer.Buffer.from("", "utf8")); - this.additionalData = []; - Object.assign(this, init); - } - static fromHttpResponse(responsePart) { - let result = new _TransactionEvent(); - result.address = new primitives_1.Address(responsePart.address); - result.identifier = responsePart.identifier || ""; - result.topics = (responsePart.topics || []).map((topic) => new TransactionEventTopic(topic)); - result.dataPayload = TransactionEventData.fromBase64(responsePart.data); - result.additionalData = (responsePart.additionalData || []).map(TransactionEventData.fromBase64); - result.data = result.dataPayload.toString(); - return result; - } - findFirstOrNoneTopic(predicate) { - return this.topics.filter((topic) => predicate(topic))[0]; - } - getLastTopic() { - return this.topics[this.topics.length - 1]; - } - }; - exports2.TransactionEvent = TransactionEvent; - var TransactionEventData = class _TransactionEventData { - constructor(data) { - this.raw = data; - } - static fromBase64(str) { - return new _TransactionEventData(import_buffer.Buffer.from(str || "", "base64")); - } - toString() { - return this.raw.toString("utf8"); - } - hex() { - return this.raw.toString("hex"); - } - valueOf() { - return this.raw; - } - }; - exports2.TransactionEventData = TransactionEventData; - var TransactionEventTopic = class { - constructor(topic) { - this.raw = import_buffer.Buffer.from(topic || "", "base64"); - } - toString() { - return this.raw.toString("utf8"); - } - hex() { - return this.raw.toString("hex"); - } - valueOf() { - return this.raw; - } - }; - exports2.TransactionEventTopic = TransactionEventTopic; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js -var require_transactionLogs = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionLogs = void 0; - var errors_1 = require_errors5(); - var primitives_1 = require_primitives(); - var transactionEvents_1 = require_transactionEvents(); - var TransactionLogs2 = class _TransactionLogs { - constructor(init) { - this.address = new primitives_1.Address(""); - this.events = []; - Object.assign(this, init); - } - static fromHttpResponse(logs) { - let result = new _TransactionLogs(); - result.address = new primitives_1.Address(logs.address); - result.events = (logs.events || []).map((event) => transactionEvents_1.TransactionEvent.fromHttpResponse(event)); - return result; - } - findSingleOrNoneEvent(identifier, predicate) { - let events = this.findEvents(identifier, predicate); - if (events.length > 1) { - throw new errors_1.ErrUnexpectedCondition(`more than one event of type ${identifier}`); - } - return events[0]; - } - findFirstOrNoneEvent(identifier, predicate) { - return this.findEvents(identifier, predicate)[0]; - } - findEvents(identifier, predicate) { - let events = this.events.filter((event) => event.identifier == identifier); - if (predicate) { - events = events.filter((event) => predicate(event)); - } - return events; - } - }; - exports2.TransactionLogs = TransactionLogs2; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/contractResults.js -var require_contractResults = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/contractResults.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractResultItem = exports2.ContractResults = void 0; - var transactionLogs_1 = require_transactionLogs(); - var primitives_1 = require_primitives(); - var ContractResults2 = class _ContractResults { - constructor(items) { - this.items = items; - this.items.sort(function(a3, b4) { - return a3.nonce.valueOf() - b4.nonce.valueOf(); - }); - } - static fromProxyHttpResponse(results) { - let items = results.map((item) => ContractResultItem.fromProxyHttpResponse(item)); - return new _ContractResults(items); - } - static fromApiHttpResponse(results) { - let items = results.map((item) => ContractResultItem.fromApiHttpResponse(item)); - return new _ContractResults(items); - } - }; - exports2.ContractResults = ContractResults2; - var ContractResultItem = class _ContractResultItem { - constructor(init) { - this.hash = ""; - this.nonce = 0; - this.value = ""; - this.receiver = new primitives_1.Address(""); - this.sender = new primitives_1.Address(""); - this.data = ""; - this.previousHash = ""; - this.originalHash = ""; - this.gasLimit = 0; - this.gasPrice = 0; - this.callType = 0; - this.returnMessage = ""; - this.logs = new transactionLogs_1.TransactionLogs(); - Object.assign(this, init); - } - static fromProxyHttpResponse(response) { - let item = _ContractResultItem.fromHttpResponse(response); - return item; - } - static fromApiHttpResponse(response) { - let item = _ContractResultItem.fromHttpResponse(response); - item.data = import_buffer.Buffer.from(item.data, "base64").toString(); - item.callType = Number(item.callType); - return item; - } - static fromHttpResponse(response) { - let item = new _ContractResultItem(); - item.hash = response.hash; - item.nonce = Number(response.nonce || 0); - item.value = (response.value || 0).toString(); - item.receiver = new primitives_1.Address(response.receiver); - item.sender = new primitives_1.Address(response.sender); - item.previousHash = response.prevTxHash; - item.originalHash = response.originalTxHash; - item.gasLimit = Number(response.gasLimit || 0); - item.gasPrice = Number(response.gasPrice || 0); - item.data = response.data || ""; - item.callType = response.callType; - item.returnMessage = response.returnMessage; - item.logs = transactionLogs_1.TransactionLogs.fromHttpResponse(response.logs || {}); - return item; - } - }; - exports2.ContractResultItem = ContractResultItem; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js -var require_contractQueryRequest = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractQueryRequest = void 0; - var ContractQueryRequest2 = class { - constructor(query) { - this.query = query; - } - toHttpRequest() { - var _a; - let request = {}; - let query = this.query; - request.scAddress = query.address.bech32(); - request.caller = ((_a = query.caller) === null || _a === void 0 ? void 0 : _a.bech32()) ? query.caller.bech32() : void 0; - request.funcName = query.func.toString(); - request.value = query.value ? query.value.toString() : void 0; - request.args = query.getEncodedArguments(); - return request; - } - }; - exports2.ContractQueryRequest = ContractQueryRequest2; - } -}); - -// node_modules/qrcode/lib/can-promise.js -var require_can_promise = __commonJS({ - "node_modules/qrcode/lib/can-promise.js"(exports2, module2) { - init_shim(); - module2.exports = function() { - return typeof Promise === "function" && Promise.prototype && Promise.prototype.then; - }; - } -}); - -// node_modules/qrcode/lib/core/utils.js -var require_utils6 = __commonJS({ - "node_modules/qrcode/lib/core/utils.js"(exports2) { - init_shim(); - var toSJISFunction; - var CODEWORDS_COUNT = [ - 0, - // Not used - 26, - 44, - 70, - 100, - 134, - 172, - 196, - 242, - 292, - 346, - 404, - 466, - 532, - 581, - 655, - 733, - 815, - 901, - 991, - 1085, - 1156, - 1258, - 1364, - 1474, - 1588, - 1706, - 1828, - 1921, - 2051, - 2185, - 2323, - 2465, - 2611, - 2761, - 2876, - 3034, - 3196, - 3362, - 3532, - 3706 - ]; - exports2.getSymbolSize = function getSymbolSize(version2) { - if (!version2) - throw new Error('"version" cannot be null or undefined'); - if (version2 < 1 || version2 > 40) - throw new Error('"version" should be in range from 1 to 40'); - return version2 * 4 + 17; - }; - exports2.getSymbolTotalCodewords = function getSymbolTotalCodewords(version2) { - return CODEWORDS_COUNT[version2]; - }; - exports2.getBCHDigit = function(data) { - let digit = 0; - while (data !== 0) { - digit++; - data >>>= 1; - } - return digit; - }; - exports2.setToSJISFunction = function setToSJISFunction(f4) { - if (typeof f4 !== "function") { - throw new Error('"toSJISFunc" is not a valid function.'); - } - toSJISFunction = f4; - }; - exports2.isKanjiModeEnabled = function() { - return typeof toSJISFunction !== "undefined"; - }; - exports2.toSJIS = function toSJIS(kanji) { - return toSJISFunction(kanji); - }; - } -}); - -// node_modules/qrcode/lib/core/error-correction-level.js -var require_error_correction_level = __commonJS({ - "node_modules/qrcode/lib/core/error-correction-level.js"(exports2) { - init_shim(); - exports2.L = { bit: 1 }; - exports2.M = { bit: 0 }; - exports2.Q = { bit: 3 }; - exports2.H = { bit: 2 }; - function fromString3(string2) { - if (typeof string2 !== "string") { - throw new Error("Param is not a string"); - } - const lcStr = string2.toLowerCase(); - switch (lcStr) { - case "l": - case "low": - return exports2.L; - case "m": - case "medium": - return exports2.M; - case "q": - case "quartile": - return exports2.Q; - case "h": - case "high": - return exports2.H; - default: - throw new Error("Unknown EC Level: " + string2); - } - } - exports2.isValid = function isValid(level) { - return level && typeof level.bit !== "undefined" && level.bit >= 0 && level.bit < 4; - }; - exports2.from = function from3(value, defaultValue) { - if (exports2.isValid(value)) { - return value; - } - try { - return fromString3(value); - } catch (e2) { - return defaultValue; - } - }; - } -}); - -// node_modules/qrcode/lib/core/bit-buffer.js -var require_bit_buffer = __commonJS({ - "node_modules/qrcode/lib/core/bit-buffer.js"(exports2, module2) { - init_shim(); - function BitBuffer() { - this.buffer = []; - this.length = 0; - } - BitBuffer.prototype = { - get: function(index) { - const bufIndex = Math.floor(index / 8); - return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1; - }, - put: function(num, length2) { - for (let i2 = 0; i2 < length2; i2++) { - this.putBit((num >>> length2 - i2 - 1 & 1) === 1); - } - }, - getLengthInBits: function() { - return this.length; - }, - putBit: function(bit) { - const bufIndex = Math.floor(this.length / 8); - if (this.buffer.length <= bufIndex) { - this.buffer.push(0); - } - if (bit) { - this.buffer[bufIndex] |= 128 >>> this.length % 8; - } - this.length++; - } - }; - module2.exports = BitBuffer; - } -}); - -// node_modules/qrcode/lib/core/bit-matrix.js -var require_bit_matrix = __commonJS({ - "node_modules/qrcode/lib/core/bit-matrix.js"(exports2, module2) { - init_shim(); - function BitMatrix(size) { - if (!size || size < 1) { - throw new Error("BitMatrix size must be defined and greater than 0"); - } - this.size = size; - this.data = new Uint8Array(size * size); - this.reservedBit = new Uint8Array(size * size); - } - BitMatrix.prototype.set = function(row, col, value, reserved) { - const index = row * this.size + col; - this.data[index] = value; - if (reserved) - this.reservedBit[index] = true; - }; - BitMatrix.prototype.get = function(row, col) { - return this.data[row * this.size + col]; - }; - BitMatrix.prototype.xor = function(row, col, value) { - this.data[row * this.size + col] ^= value; - }; - BitMatrix.prototype.isReserved = function(row, col) { - return this.reservedBit[row * this.size + col]; - }; - module2.exports = BitMatrix; - } -}); - -// node_modules/qrcode/lib/core/alignment-pattern.js -var require_alignment_pattern = __commonJS({ - "node_modules/qrcode/lib/core/alignment-pattern.js"(exports2) { - init_shim(); - var getSymbolSize = require_utils6().getSymbolSize; - exports2.getRowColCoords = function getRowColCoords(version2) { - if (version2 === 1) - return []; - const posCount = Math.floor(version2 / 7) + 2; - const size = getSymbolSize(version2); - const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2; - const positions = [size - 7]; - for (let i2 = 1; i2 < posCount - 1; i2++) { - positions[i2] = positions[i2 - 1] - intervals; - } - positions.push(6); - return positions.reverse(); - }; - exports2.getPositions = function getPositions(version2) { - const coords = []; - const pos = exports2.getRowColCoords(version2); - const posLength = pos.length; - for (let i2 = 0; i2 < posLength; i2++) { - for (let j2 = 0; j2 < posLength; j2++) { - if (i2 === 0 && j2 === 0 || // top-left - i2 === 0 && j2 === posLength - 1 || // bottom-left - i2 === posLength - 1 && j2 === 0) { - continue; - } - coords.push([pos[i2], pos[j2]]); - } - } - return coords; - }; - } -}); - -// node_modules/qrcode/lib/core/finder-pattern.js -var require_finder_pattern = __commonJS({ - "node_modules/qrcode/lib/core/finder-pattern.js"(exports2) { - init_shim(); - var getSymbolSize = require_utils6().getSymbolSize; - var FINDER_PATTERN_SIZE = 7; - exports2.getPositions = function getPositions(version2) { - const size = getSymbolSize(version2); - return [ - // top-left - [0, 0], - // top-right - [size - FINDER_PATTERN_SIZE, 0], - // bottom-left - [0, size - FINDER_PATTERN_SIZE] - ]; - }; - } -}); - -// node_modules/qrcode/lib/core/mask-pattern.js -var require_mask_pattern = __commonJS({ - "node_modules/qrcode/lib/core/mask-pattern.js"(exports2) { - init_shim(); - exports2.Patterns = { - PATTERN000: 0, - PATTERN001: 1, - PATTERN010: 2, - PATTERN011: 3, - PATTERN100: 4, - PATTERN101: 5, - PATTERN110: 6, - PATTERN111: 7 - }; - var PenaltyScores = { - N1: 3, - N2: 3, - N3: 40, - N4: 10 - }; - exports2.isValid = function isValid(mask) { - return mask != null && mask !== "" && !isNaN(mask) && mask >= 0 && mask <= 7; - }; - exports2.from = function from3(value) { - return exports2.isValid(value) ? parseInt(value, 10) : void 0; - }; - exports2.getPenaltyN1 = function getPenaltyN1(data) { - const size = data.size; - let points = 0; - let sameCountCol = 0; - let sameCountRow = 0; - let lastCol = null; - let lastRow = null; - for (let row = 0; row < size; row++) { - sameCountCol = sameCountRow = 0; - lastCol = lastRow = null; - for (let col = 0; col < size; col++) { - let module3 = data.get(row, col); - if (module3 === lastCol) { - sameCountCol++; - } else { - if (sameCountCol >= 5) - points += PenaltyScores.N1 + (sameCountCol - 5); - lastCol = module3; - sameCountCol = 1; - } - module3 = data.get(col, row); - if (module3 === lastRow) { - sameCountRow++; - } else { - if (sameCountRow >= 5) - points += PenaltyScores.N1 + (sameCountRow - 5); - lastRow = module3; - sameCountRow = 1; - } - } - if (sameCountCol >= 5) - points += PenaltyScores.N1 + (sameCountCol - 5); - if (sameCountRow >= 5) - points += PenaltyScores.N1 + (sameCountRow - 5); - } - return points; - }; - exports2.getPenaltyN2 = function getPenaltyN2(data) { - const size = data.size; - let points = 0; - for (let row = 0; row < size - 1; row++) { - for (let col = 0; col < size - 1; col++) { - const last = data.get(row, col) + data.get(row, col + 1) + data.get(row + 1, col) + data.get(row + 1, col + 1); - if (last === 4 || last === 0) - points++; - } - } - return points * PenaltyScores.N2; - }; - exports2.getPenaltyN3 = function getPenaltyN3(data) { - const size = data.size; - let points = 0; - let bitsCol = 0; - let bitsRow = 0; - for (let row = 0; row < size; row++) { - bitsCol = bitsRow = 0; - for (let col = 0; col < size; col++) { - bitsCol = bitsCol << 1 & 2047 | data.get(row, col); - if (col >= 10 && (bitsCol === 1488 || bitsCol === 93)) - points++; - bitsRow = bitsRow << 1 & 2047 | data.get(col, row); - if (col >= 10 && (bitsRow === 1488 || bitsRow === 93)) - points++; - } - } - return points * PenaltyScores.N3; - }; - exports2.getPenaltyN4 = function getPenaltyN4(data) { - let darkCount = 0; - const modulesCount = data.data.length; - for (let i2 = 0; i2 < modulesCount; i2++) - darkCount += data.data[i2]; - const k4 = Math.abs(Math.ceil(darkCount * 100 / modulesCount / 5) - 10); - return k4 * PenaltyScores.N4; - }; - function getMaskAt(maskPattern, i2, j2) { - switch (maskPattern) { - case exports2.Patterns.PATTERN000: - return (i2 + j2) % 2 === 0; - case exports2.Patterns.PATTERN001: - return i2 % 2 === 0; - case exports2.Patterns.PATTERN010: - return j2 % 3 === 0; - case exports2.Patterns.PATTERN011: - return (i2 + j2) % 3 === 0; - case exports2.Patterns.PATTERN100: - return (Math.floor(i2 / 2) + Math.floor(j2 / 3)) % 2 === 0; - case exports2.Patterns.PATTERN101: - return i2 * j2 % 2 + i2 * j2 % 3 === 0; - case exports2.Patterns.PATTERN110: - return (i2 * j2 % 2 + i2 * j2 % 3) % 2 === 0; - case exports2.Patterns.PATTERN111: - return (i2 * j2 % 3 + (i2 + j2) % 2) % 2 === 0; - default: - throw new Error("bad maskPattern:" + maskPattern); - } - } - exports2.applyMask = function applyMask(pattern, data) { - const size = data.size; - for (let col = 0; col < size; col++) { - for (let row = 0; row < size; row++) { - if (data.isReserved(row, col)) - continue; - data.xor(row, col, getMaskAt(pattern, row, col)); - } - } - }; - exports2.getBestMask = function getBestMask(data, setupFormatFunc) { - const numPatterns = Object.keys(exports2.Patterns).length; - let bestPattern = 0; - let lowerPenalty = Infinity; - for (let p3 = 0; p3 < numPatterns; p3++) { - setupFormatFunc(p3); - exports2.applyMask(p3, data); - const penalty = exports2.getPenaltyN1(data) + exports2.getPenaltyN2(data) + exports2.getPenaltyN3(data) + exports2.getPenaltyN4(data); - exports2.applyMask(p3, data); - if (penalty < lowerPenalty) { - lowerPenalty = penalty; - bestPattern = p3; - } - } - return bestPattern; - }; - } -}); - -// node_modules/qrcode/lib/core/error-correction-code.js -var require_error_correction_code = __commonJS({ - "node_modules/qrcode/lib/core/error-correction-code.js"(exports2) { - init_shim(); - var ECLevel = require_error_correction_level(); - var EC_BLOCKS_TABLE = [ - // L M Q H - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 2, - 2, - 1, - 2, - 2, - 4, - 1, - 2, - 4, - 4, - 2, - 4, - 4, - 4, - 2, - 4, - 6, - 5, - 2, - 4, - 6, - 6, - 2, - 5, - 8, - 8, - 4, - 5, - 8, - 8, - 4, - 5, - 8, - 11, - 4, - 8, - 10, - 11, - 4, - 9, - 12, - 16, - 4, - 9, - 16, - 16, - 6, - 10, - 12, - 18, - 6, - 10, - 17, - 16, - 6, - 11, - 16, - 19, - 6, - 13, - 18, - 21, - 7, - 14, - 21, - 25, - 8, - 16, - 20, - 25, - 8, - 17, - 23, - 25, - 9, - 17, - 23, - 34, - 9, - 18, - 25, - 30, - 10, - 20, - 27, - 32, - 12, - 21, - 29, - 35, - 12, - 23, - 34, - 37, - 12, - 25, - 34, - 40, - 13, - 26, - 35, - 42, - 14, - 28, - 38, - 45, - 15, - 29, - 40, - 48, - 16, - 31, - 43, - 51, - 17, - 33, - 45, - 54, - 18, - 35, - 48, - 57, - 19, - 37, - 51, - 60, - 19, - 38, - 53, - 63, - 20, - 40, - 56, - 66, - 21, - 43, - 59, - 70, - 22, - 45, - 62, - 74, - 24, - 47, - 65, - 77, - 25, - 49, - 68, - 81 - ]; - var EC_CODEWORDS_TABLE = [ - // L M Q H - 7, - 10, - 13, - 17, - 10, - 16, - 22, - 28, - 15, - 26, - 36, - 44, - 20, - 36, - 52, - 64, - 26, - 48, - 72, - 88, - 36, - 64, - 96, - 112, - 40, - 72, - 108, - 130, - 48, - 88, - 132, - 156, - 60, - 110, - 160, - 192, - 72, - 130, - 192, - 224, - 80, - 150, - 224, - 264, - 96, - 176, - 260, - 308, - 104, - 198, - 288, - 352, - 120, - 216, - 320, - 384, - 132, - 240, - 360, - 432, - 144, - 280, - 408, - 480, - 168, - 308, - 448, - 532, - 180, - 338, - 504, - 588, - 196, - 364, - 546, - 650, - 224, - 416, - 600, - 700, - 224, - 442, - 644, - 750, - 252, - 476, - 690, - 816, - 270, - 504, - 750, - 900, - 300, - 560, - 810, - 960, - 312, - 588, - 870, - 1050, - 336, - 644, - 952, - 1110, - 360, - 700, - 1020, - 1200, - 390, - 728, - 1050, - 1260, - 420, - 784, - 1140, - 1350, - 450, - 812, - 1200, - 1440, - 480, - 868, - 1290, - 1530, - 510, - 924, - 1350, - 1620, - 540, - 980, - 1440, - 1710, - 570, - 1036, - 1530, - 1800, - 570, - 1064, - 1590, - 1890, - 600, - 1120, - 1680, - 1980, - 630, - 1204, - 1770, - 2100, - 660, - 1260, - 1860, - 2220, - 720, - 1316, - 1950, - 2310, - 750, - 1372, - 2040, - 2430 - ]; - exports2.getBlocksCount = function getBlocksCount(version2, errorCorrectionLevel) { - switch (errorCorrectionLevel) { - case ECLevel.L: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 0]; - case ECLevel.M: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 1]; - case ECLevel.Q: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 2]; - case ECLevel.H: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 3]; - default: - return void 0; - } - }; - exports2.getTotalCodewordsCount = function getTotalCodewordsCount(version2, errorCorrectionLevel) { - switch (errorCorrectionLevel) { - case ECLevel.L: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 0]; - case ECLevel.M: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 1]; - case ECLevel.Q: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 2]; - case ECLevel.H: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 3]; - default: - return void 0; - } - }; - } -}); - -// node_modules/qrcode/lib/core/galois-field.js -var require_galois_field = __commonJS({ - "node_modules/qrcode/lib/core/galois-field.js"(exports2) { - init_shim(); - var EXP_TABLE = new Uint8Array(512); - var LOG_TABLE = new Uint8Array(256); - (function initTables() { - let x3 = 1; - for (let i2 = 0; i2 < 255; i2++) { - EXP_TABLE[i2] = x3; - LOG_TABLE[x3] = i2; - x3 <<= 1; - if (x3 & 256) { - x3 ^= 285; - } - } - for (let i2 = 255; i2 < 512; i2++) { - EXP_TABLE[i2] = EXP_TABLE[i2 - 255]; - } - })(); - exports2.log = function log(n3) { - if (n3 < 1) - throw new Error("log(" + n3 + ")"); - return LOG_TABLE[n3]; - }; - exports2.exp = function exp(n3) { - return EXP_TABLE[n3]; - }; - exports2.mul = function mul(x3, y4) { - if (x3 === 0 || y4 === 0) - return 0; - return EXP_TABLE[LOG_TABLE[x3] + LOG_TABLE[y4]]; - }; - } -}); - -// node_modules/qrcode/lib/core/polynomial.js -var require_polynomial = __commonJS({ - "node_modules/qrcode/lib/core/polynomial.js"(exports2) { - init_shim(); - var GF = require_galois_field(); - exports2.mul = function mul(p1, p22) { - const coeff = new Uint8Array(p1.length + p22.length - 1); - for (let i2 = 0; i2 < p1.length; i2++) { - for (let j2 = 0; j2 < p22.length; j2++) { - coeff[i2 + j2] ^= GF.mul(p1[i2], p22[j2]); - } - } - return coeff; - }; - exports2.mod = function mod2(divident, divisor) { - let result = new Uint8Array(divident); - while (result.length - divisor.length >= 0) { - const coeff = result[0]; - for (let i2 = 0; i2 < divisor.length; i2++) { - result[i2] ^= GF.mul(divisor[i2], coeff); - } - let offset = 0; - while (offset < result.length && result[offset] === 0) - offset++; - result = result.slice(offset); - } - return result; - }; - exports2.generateECPolynomial = function generateECPolynomial(degree) { - let poly = new Uint8Array([1]); - for (let i2 = 0; i2 < degree; i2++) { - poly = exports2.mul(poly, new Uint8Array([1, GF.exp(i2)])); - } - return poly; - }; - } -}); - -// node_modules/qrcode/lib/core/reed-solomon-encoder.js -var require_reed_solomon_encoder = __commonJS({ - "node_modules/qrcode/lib/core/reed-solomon-encoder.js"(exports2, module2) { - init_shim(); - var Polynomial = require_polynomial(); - function ReedSolomonEncoder(degree) { - this.genPoly = void 0; - this.degree = degree; - if (this.degree) - this.initialize(this.degree); - } - ReedSolomonEncoder.prototype.initialize = function initialize(degree) { - this.degree = degree; - this.genPoly = Polynomial.generateECPolynomial(this.degree); - }; - ReedSolomonEncoder.prototype.encode = function encode5(data) { - if (!this.genPoly) { - throw new Error("Encoder not initialized"); - } - const paddedData = new Uint8Array(data.length + this.degree); - paddedData.set(data); - const remainder = Polynomial.mod(paddedData, this.genPoly); - const start = this.degree - remainder.length; - if (start > 0) { - const buff = new Uint8Array(this.degree); - buff.set(remainder, start); - return buff; - } - return remainder; - }; - module2.exports = ReedSolomonEncoder; - } -}); - -// node_modules/qrcode/lib/core/version-check.js -var require_version_check = __commonJS({ - "node_modules/qrcode/lib/core/version-check.js"(exports2) { - init_shim(); - exports2.isValid = function isValid(version2) { - return !isNaN(version2) && version2 >= 1 && version2 <= 40; - }; - } -}); - -// node_modules/qrcode/lib/core/regex.js -var require_regex = __commonJS({ - "node_modules/qrcode/lib/core/regex.js"(exports2) { - init_shim(); - var numeric = "[0-9]+"; - var alphanumeric = "[A-Z $%*+\\-./:]+"; - var kanji = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+"; - kanji = kanji.replace(/u/g, "\\u"); - var byte = "(?:(?![A-Z0-9 $%*+\\-./:]|" + kanji + ")(?:.|[\r\n]))+"; - exports2.KANJI = new RegExp(kanji, "g"); - exports2.BYTE_KANJI = new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g"); - exports2.BYTE = new RegExp(byte, "g"); - exports2.NUMERIC = new RegExp(numeric, "g"); - exports2.ALPHANUMERIC = new RegExp(alphanumeric, "g"); - var TEST_KANJI = new RegExp("^" + kanji + "$"); - var TEST_NUMERIC = new RegExp("^" + numeric + "$"); - var TEST_ALPHANUMERIC = new RegExp("^[A-Z0-9 $%*+\\-./:]+$"); - exports2.testKanji = function testKanji(str) { - return TEST_KANJI.test(str); - }; - exports2.testNumeric = function testNumeric(str) { - return TEST_NUMERIC.test(str); - }; - exports2.testAlphanumeric = function testAlphanumeric(str) { - return TEST_ALPHANUMERIC.test(str); - }; - } -}); - -// node_modules/qrcode/lib/core/mode.js -var require_mode = __commonJS({ - "node_modules/qrcode/lib/core/mode.js"(exports2) { - init_shim(); - var VersionCheck = require_version_check(); - var Regex = require_regex(); - exports2.NUMERIC = { - id: "Numeric", - bit: 1 << 0, - ccBits: [10, 12, 14] - }; - exports2.ALPHANUMERIC = { - id: "Alphanumeric", - bit: 1 << 1, - ccBits: [9, 11, 13] - }; - exports2.BYTE = { - id: "Byte", - bit: 1 << 2, - ccBits: [8, 16, 16] - }; - exports2.KANJI = { - id: "Kanji", - bit: 1 << 3, - ccBits: [8, 10, 12] - }; - exports2.MIXED = { - bit: -1 - }; - exports2.getCharCountIndicator = function getCharCountIndicator(mode, version2) { - if (!mode.ccBits) - throw new Error("Invalid mode: " + mode); - if (!VersionCheck.isValid(version2)) { - throw new Error("Invalid version: " + version2); - } - if (version2 >= 1 && version2 < 10) - return mode.ccBits[0]; - else if (version2 < 27) - return mode.ccBits[1]; - return mode.ccBits[2]; - }; - exports2.getBestModeForData = function getBestModeForData(dataStr) { - if (Regex.testNumeric(dataStr)) - return exports2.NUMERIC; - else if (Regex.testAlphanumeric(dataStr)) - return exports2.ALPHANUMERIC; - else if (Regex.testKanji(dataStr)) - return exports2.KANJI; - else - return exports2.BYTE; - }; - exports2.toString = function toString3(mode) { - if (mode && mode.id) - return mode.id; - throw new Error("Invalid mode"); - }; - exports2.isValid = function isValid(mode) { - return mode && mode.bit && mode.ccBits; - }; - function fromString3(string2) { - if (typeof string2 !== "string") { - throw new Error("Param is not a string"); - } - const lcStr = string2.toLowerCase(); - switch (lcStr) { - case "numeric": - return exports2.NUMERIC; - case "alphanumeric": - return exports2.ALPHANUMERIC; - case "kanji": - return exports2.KANJI; - case "byte": - return exports2.BYTE; - default: - throw new Error("Unknown mode: " + string2); - } - } - exports2.from = function from3(value, defaultValue) { - if (exports2.isValid(value)) { - return value; - } - try { - return fromString3(value); - } catch (e2) { - return defaultValue; - } - }; - } -}); - -// node_modules/qrcode/lib/core/version.js -var require_version = __commonJS({ - "node_modules/qrcode/lib/core/version.js"(exports2) { - init_shim(); - var Utils = require_utils6(); - var ECCode = require_error_correction_code(); - var ECLevel = require_error_correction_level(); - var Mode = require_mode(); - var VersionCheck = require_version_check(); - var G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0; - var G18_BCH = Utils.getBCHDigit(G18); - function getBestVersionForDataLength(mode, length2, errorCorrectionLevel) { - for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { - if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, mode)) { - return currentVersion; - } - } - return void 0; - } - function getReservedBitsCount(mode, version2) { - return Mode.getCharCountIndicator(mode, version2) + 4; - } - function getTotalBitsFromDataArray(segments, version2) { - let totalBits = 0; - segments.forEach(function(data) { - const reservedBits = getReservedBitsCount(data.mode, version2); - totalBits += reservedBits + data.getBitsLength(); - }); - return totalBits; - } - function getBestVersionForMixedData(segments, errorCorrectionLevel) { - for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { - const length2 = getTotalBitsFromDataArray(segments, currentVersion); - if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { - return currentVersion; - } - } - return void 0; - } - exports2.from = function from3(value, defaultValue) { - if (VersionCheck.isValid(value)) { - return parseInt(value, 10); - } - return defaultValue; - }; - exports2.getCapacity = function getCapacity(version2, errorCorrectionLevel, mode) { - if (!VersionCheck.isValid(version2)) { - throw new Error("Invalid QR Code version"); - } - if (typeof mode === "undefined") - mode = Mode.BYTE; - const totalCodewords = Utils.getSymbolTotalCodewords(version2); - const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); - const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; - if (mode === Mode.MIXED) - return dataTotalCodewordsBits; - const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version2); - switch (mode) { - case Mode.NUMERIC: - return Math.floor(usableBits / 10 * 3); - case Mode.ALPHANUMERIC: - return Math.floor(usableBits / 11 * 2); - case Mode.KANJI: - return Math.floor(usableBits / 13); - case Mode.BYTE: - default: - return Math.floor(usableBits / 8); - } - }; - exports2.getBestVersionForData = function getBestVersionForData(data, errorCorrectionLevel) { - let seg; - const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M); - if (Array.isArray(data)) { - if (data.length > 1) { - return getBestVersionForMixedData(data, ecl); - } - if (data.length === 0) { - return 1; - } - seg = data[0]; - } else { - seg = data; - } - return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl); - }; - exports2.getEncodedBits = function getEncodedBits(version2) { - if (!VersionCheck.isValid(version2) || version2 < 7) { - throw new Error("Invalid QR Code version"); - } - let d3 = version2 << 12; - while (Utils.getBCHDigit(d3) - G18_BCH >= 0) { - d3 ^= G18 << Utils.getBCHDigit(d3) - G18_BCH; - } - return version2 << 12 | d3; - }; - } -}); - -// node_modules/qrcode/lib/core/format-info.js -var require_format_info = __commonJS({ - "node_modules/qrcode/lib/core/format-info.js"(exports2) { - init_shim(); - var Utils = require_utils6(); - var G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0; - var G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1; - var G15_BCH = Utils.getBCHDigit(G15); - exports2.getEncodedBits = function getEncodedBits(errorCorrectionLevel, mask) { - const data = errorCorrectionLevel.bit << 3 | mask; - let d3 = data << 10; - while (Utils.getBCHDigit(d3) - G15_BCH >= 0) { - d3 ^= G15 << Utils.getBCHDigit(d3) - G15_BCH; - } - return (data << 10 | d3) ^ G15_MASK; - }; - } -}); - -// node_modules/qrcode/lib/core/numeric-data.js -var require_numeric_data = __commonJS({ - "node_modules/qrcode/lib/core/numeric-data.js"(exports2, module2) { - init_shim(); - var Mode = require_mode(); - function NumericData(data) { - this.mode = Mode.NUMERIC; - this.data = data.toString(); - } - NumericData.getBitsLength = function getBitsLength(length2) { - return 10 * Math.floor(length2 / 3) + (length2 % 3 ? length2 % 3 * 3 + 1 : 0); - }; - NumericData.prototype.getLength = function getLength() { - return this.data.length; - }; - NumericData.prototype.getBitsLength = function getBitsLength() { - return NumericData.getBitsLength(this.data.length); - }; - NumericData.prototype.write = function write(bitBuffer) { - let i2, group, value; - for (i2 = 0; i2 + 3 <= this.data.length; i2 += 3) { - group = this.data.substr(i2, 3); - value = parseInt(group, 10); - bitBuffer.put(value, 10); - } - const remainingNum = this.data.length - i2; - if (remainingNum > 0) { - group = this.data.substr(i2); - value = parseInt(group, 10); - bitBuffer.put(value, remainingNum * 3 + 1); - } - }; - module2.exports = NumericData; - } -}); - -// node_modules/qrcode/lib/core/alphanumeric-data.js -var require_alphanumeric_data = __commonJS({ - "node_modules/qrcode/lib/core/alphanumeric-data.js"(exports2, module2) { - init_shim(); - var Mode = require_mode(); - var ALPHA_NUM_CHARS = [ - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "A", - "B", - "C", - "D", - "E", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "N", - "O", - "P", - "Q", - "R", - "S", - "T", - "U", - "V", - "W", - "X", - "Y", - "Z", - " ", - "$", - "%", - "*", - "+", - "-", - ".", - "/", - ":" - ]; - function AlphanumericData(data) { - this.mode = Mode.ALPHANUMERIC; - this.data = data; - } - AlphanumericData.getBitsLength = function getBitsLength(length2) { - return 11 * Math.floor(length2 / 2) + 6 * (length2 % 2); - }; - AlphanumericData.prototype.getLength = function getLength() { - return this.data.length; - }; - AlphanumericData.prototype.getBitsLength = function getBitsLength() { - return AlphanumericData.getBitsLength(this.data.length); - }; - AlphanumericData.prototype.write = function write(bitBuffer) { - let i2; - for (i2 = 0; i2 + 2 <= this.data.length; i2 += 2) { - let value = ALPHA_NUM_CHARS.indexOf(this.data[i2]) * 45; - value += ALPHA_NUM_CHARS.indexOf(this.data[i2 + 1]); - bitBuffer.put(value, 11); - } - if (this.data.length % 2) { - bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i2]), 6); - } - }; - module2.exports = AlphanumericData; - } -}); - -// node_modules/encode-utf8/index.js -var require_encode_utf8 = __commonJS({ - "node_modules/encode-utf8/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function encodeUtf8(input) { - var result = []; - var size = input.length; - for (var index = 0; index < size; index++) { - var point = input.charCodeAt(index); - if (point >= 55296 && point <= 56319 && size > index + 1) { - var second = input.charCodeAt(index + 1); - if (second >= 56320 && second <= 57343) { - point = (point - 55296) * 1024 + second - 56320 + 65536; - index += 1; - } - } - if (point < 128) { - result.push(point); - continue; - } - if (point < 2048) { - result.push(point >> 6 | 192); - result.push(point & 63 | 128); - continue; - } - if (point < 55296 || point >= 57344 && point < 65536) { - result.push(point >> 12 | 224); - result.push(point >> 6 & 63 | 128); - result.push(point & 63 | 128); - continue; - } - if (point >= 65536 && point <= 1114111) { - result.push(point >> 18 | 240); - result.push(point >> 12 & 63 | 128); - result.push(point >> 6 & 63 | 128); - result.push(point & 63 | 128); - continue; - } - result.push(239, 191, 189); - } - return new Uint8Array(result).buffer; - }; - } -}); - -// node_modules/qrcode/lib/core/byte-data.js -var require_byte_data = __commonJS({ - "node_modules/qrcode/lib/core/byte-data.js"(exports2, module2) { - init_shim(); - var encodeUtf8 = require_encode_utf8(); - var Mode = require_mode(); - function ByteData(data) { - this.mode = Mode.BYTE; - if (typeof data === "string") { - data = encodeUtf8(data); - } - this.data = new Uint8Array(data); - } - ByteData.getBitsLength = function getBitsLength(length2) { - return length2 * 8; - }; - ByteData.prototype.getLength = function getLength() { - return this.data.length; - }; - ByteData.prototype.getBitsLength = function getBitsLength() { - return ByteData.getBitsLength(this.data.length); - }; - ByteData.prototype.write = function(bitBuffer) { - for (let i2 = 0, l4 = this.data.length; i2 < l4; i2++) { - bitBuffer.put(this.data[i2], 8); - } - }; - module2.exports = ByteData; - } -}); - -// node_modules/qrcode/lib/core/kanji-data.js -var require_kanji_data = __commonJS({ - "node_modules/qrcode/lib/core/kanji-data.js"(exports2, module2) { - init_shim(); - var Mode = require_mode(); - var Utils = require_utils6(); - function KanjiData(data) { - this.mode = Mode.KANJI; - this.data = data; - } - KanjiData.getBitsLength = function getBitsLength(length2) { - return length2 * 13; - }; - KanjiData.prototype.getLength = function getLength() { - return this.data.length; - }; - KanjiData.prototype.getBitsLength = function getBitsLength() { - return KanjiData.getBitsLength(this.data.length); - }; - KanjiData.prototype.write = function(bitBuffer) { - let i2; - for (i2 = 0; i2 < this.data.length; i2++) { - let value = Utils.toSJIS(this.data[i2]); - if (value >= 33088 && value <= 40956) { - value -= 33088; - } else if (value >= 57408 && value <= 60351) { - value -= 49472; - } else { - throw new Error( - "Invalid SJIS character: " + this.data[i2] + "\nMake sure your charset is UTF-8" - ); - } - value = (value >>> 8 & 255) * 192 + (value & 255); - bitBuffer.put(value, 13); - } - }; - module2.exports = KanjiData; - } -}); - -// node_modules/dijkstrajs/dijkstra.js -var require_dijkstra = __commonJS({ - "node_modules/dijkstrajs/dijkstra.js"(exports2, module2) { - "use strict"; - init_shim(); - var dijkstra = { - single_source_shortest_paths: function(graph, s2, d3) { - var predecessors = {}; - var costs = {}; - costs[s2] = 0; - var open = dijkstra.PriorityQueue.make(); - open.push(s2, 0); - var closest, u3, v2, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit; - while (!open.empty()) { - closest = open.pop(); - u3 = closest.value; - cost_of_s_to_u = closest.cost; - adjacent_nodes = graph[u3] || {}; - for (v2 in adjacent_nodes) { - if (adjacent_nodes.hasOwnProperty(v2)) { - cost_of_e = adjacent_nodes[v2]; - cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; - cost_of_s_to_v = costs[v2]; - first_visit = typeof costs[v2] === "undefined"; - if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { - costs[v2] = cost_of_s_to_u_plus_cost_of_e; - open.push(v2, cost_of_s_to_u_plus_cost_of_e); - predecessors[v2] = u3; - } - } - } - } - if (typeof d3 !== "undefined" && typeof costs[d3] === "undefined") { - var msg = ["Could not find a path from ", s2, " to ", d3, "."].join(""); - throw new Error(msg); - } - return predecessors; - }, - extract_shortest_path_from_predecessor_list: function(predecessors, d3) { - var nodes = []; - var u3 = d3; - var predecessor; - while (u3) { - nodes.push(u3); - predecessor = predecessors[u3]; - u3 = predecessors[u3]; - } - nodes.reverse(); - return nodes; - }, - find_path: function(graph, s2, d3) { - var predecessors = dijkstra.single_source_shortest_paths(graph, s2, d3); - return dijkstra.extract_shortest_path_from_predecessor_list( - predecessors, - d3 - ); - }, - /** - * A very naive priority queue implementation. - */ - PriorityQueue: { - make: function(opts) { - var T2 = dijkstra.PriorityQueue, t = {}, key; - opts = opts || {}; - for (key in T2) { - if (T2.hasOwnProperty(key)) { - t[key] = T2[key]; - } - } - t.queue = []; - t.sorter = opts.sorter || T2.default_sorter; - return t; - }, - default_sorter: function(a3, b4) { - return a3.cost - b4.cost; - }, - /** - * Add a new item to the queue and ensure the highest priority element - * is at the front of the queue. - */ - push: function(value, cost) { - var item = { value, cost }; - this.queue.push(item); - this.queue.sort(this.sorter); - }, - /** - * Return the highest priority element in the queue. - */ - pop: function() { - return this.queue.shift(); - }, - empty: function() { - return this.queue.length === 0; - } - } - }; - if (typeof module2 !== "undefined") { - module2.exports = dijkstra; - } - } -}); - -// node_modules/qrcode/lib/core/segments.js -var require_segments = __commonJS({ - "node_modules/qrcode/lib/core/segments.js"(exports2) { - init_shim(); - var Mode = require_mode(); - var NumericData = require_numeric_data(); - var AlphanumericData = require_alphanumeric_data(); - var ByteData = require_byte_data(); - var KanjiData = require_kanji_data(); - var Regex = require_regex(); - var Utils = require_utils6(); - var dijkstra = require_dijkstra(); - function getStringByteLength(str) { - return unescape(encodeURIComponent(str)).length; - } - function getSegments(regex, mode, str) { - const segments = []; - let result; - while ((result = regex.exec(str)) !== null) { - segments.push({ - data: result[0], - index: result.index, - mode, - length: result[0].length - }); - } - return segments; - } - function getSegmentsFromString(dataStr) { - const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr); - const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr); - let byteSegs; - let kanjiSegs; - if (Utils.isKanjiModeEnabled()) { - byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr); - kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr); - } else { - byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr); - kanjiSegs = []; - } - const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs); - return segs.sort(function(s1, s2) { - return s1.index - s2.index; - }).map(function(obj) { - return { - data: obj.data, - mode: obj.mode, - length: obj.length - }; - }); - } - function getSegmentBitsLength(length2, mode) { - switch (mode) { - case Mode.NUMERIC: - return NumericData.getBitsLength(length2); - case Mode.ALPHANUMERIC: - return AlphanumericData.getBitsLength(length2); - case Mode.KANJI: - return KanjiData.getBitsLength(length2); - case Mode.BYTE: - return ByteData.getBitsLength(length2); - } - } - function mergeSegments(segs) { - return segs.reduce(function(acc, curr) { - const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null; - if (prevSeg && prevSeg.mode === curr.mode) { - acc[acc.length - 1].data += curr.data; - return acc; - } - acc.push(curr); - return acc; - }, []); - } - function buildNodes(segs) { - const nodes = []; - for (let i2 = 0; i2 < segs.length; i2++) { - const seg = segs[i2]; - switch (seg.mode) { - case Mode.NUMERIC: - nodes.push([ - seg, - { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, - { data: seg.data, mode: Mode.BYTE, length: seg.length } - ]); - break; - case Mode.ALPHANUMERIC: - nodes.push([ - seg, - { data: seg.data, mode: Mode.BYTE, length: seg.length } - ]); - break; - case Mode.KANJI: - nodes.push([ - seg, - { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } - ]); - break; - case Mode.BYTE: - nodes.push([ - { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } - ]); - } - } - return nodes; - } - function buildGraph(nodes, version2) { - const table = {}; - const graph = { start: {} }; - let prevNodeIds = ["start"]; - for (let i2 = 0; i2 < nodes.length; i2++) { - const nodeGroup = nodes[i2]; - const currentNodeIds = []; - for (let j2 = 0; j2 < nodeGroup.length; j2++) { - const node = nodeGroup[j2]; - const key = "" + i2 + j2; - currentNodeIds.push(key); - table[key] = { node, lastCount: 0 }; - graph[key] = {}; - for (let n3 = 0; n3 < prevNodeIds.length; n3++) { - const prevNodeId = prevNodeIds[n3]; - if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { - graph[prevNodeId][key] = getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - getSegmentBitsLength(table[prevNodeId].lastCount, node.mode); - table[prevNodeId].lastCount += node.length; - } else { - if (table[prevNodeId]) - table[prevNodeId].lastCount = node.length; - graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + 4 + Mode.getCharCountIndicator(node.mode, version2); - } - } - } - prevNodeIds = currentNodeIds; - } - for (let n3 = 0; n3 < prevNodeIds.length; n3++) { - graph[prevNodeIds[n3]].end = 0; - } - return { map: graph, table }; - } - function buildSingleSegment(data, modesHint) { - let mode; - const bestMode = Mode.getBestModeForData(data); - mode = Mode.from(modesHint, bestMode); - if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { - throw new Error('"' + data + '" cannot be encoded with mode ' + Mode.toString(mode) + ".\n Suggested mode is: " + Mode.toString(bestMode)); - } - if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { - mode = Mode.BYTE; - } - switch (mode) { - case Mode.NUMERIC: - return new NumericData(data); - case Mode.ALPHANUMERIC: - return new AlphanumericData(data); - case Mode.KANJI: - return new KanjiData(data); - case Mode.BYTE: - return new ByteData(data); - } - } - exports2.fromArray = function fromArray(array) { - return array.reduce(function(acc, seg) { - if (typeof seg === "string") { - acc.push(buildSingleSegment(seg, null)); - } else if (seg.data) { - acc.push(buildSingleSegment(seg.data, seg.mode)); - } - return acc; - }, []); - }; - exports2.fromString = function fromString3(data, version2) { - const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()); - const nodes = buildNodes(segs); - const graph = buildGraph(nodes, version2); - const path = dijkstra.find_path(graph.map, "start", "end"); - const optimizedSegs = []; - for (let i2 = 1; i2 < path.length - 1; i2++) { - optimizedSegs.push(graph.table[path[i2]].node); - } - return exports2.fromArray(mergeSegments(optimizedSegs)); - }; - exports2.rawSplit = function rawSplit(data) { - return exports2.fromArray( - getSegmentsFromString(data, Utils.isKanjiModeEnabled()) - ); - }; - } -}); - -// node_modules/qrcode/lib/core/qrcode.js -var require_qrcode = __commonJS({ - "node_modules/qrcode/lib/core/qrcode.js"(exports2) { - init_shim(); - var Utils = require_utils6(); - var ECLevel = require_error_correction_level(); - var BitBuffer = require_bit_buffer(); - var BitMatrix = require_bit_matrix(); - var AlignmentPattern = require_alignment_pattern(); - var FinderPattern = require_finder_pattern(); - var MaskPattern = require_mask_pattern(); - var ECCode = require_error_correction_code(); - var ReedSolomonEncoder = require_reed_solomon_encoder(); - var Version = require_version(); - var FormatInfo = require_format_info(); - var Mode = require_mode(); - var Segments = require_segments(); - function setupFinderPattern(matrix, version2) { - const size = matrix.size; - const pos = FinderPattern.getPositions(version2); - for (let i2 = 0; i2 < pos.length; i2++) { - const row = pos[i2][0]; - const col = pos[i2][1]; - for (let r = -1; r <= 7; r++) { - if (row + r <= -1 || size <= row + r) - continue; - for (let c4 = -1; c4 <= 7; c4++) { - if (col + c4 <= -1 || size <= col + c4) - continue; - if (r >= 0 && r <= 6 && (c4 === 0 || c4 === 6) || c4 >= 0 && c4 <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c4 >= 2 && c4 <= 4) { - matrix.set(row + r, col + c4, true, true); - } else { - matrix.set(row + r, col + c4, false, true); - } - } - } - } - } - function setupTimingPattern(matrix) { - const size = matrix.size; - for (let r = 8; r < size - 8; r++) { - const value = r % 2 === 0; - matrix.set(r, 6, value, true); - matrix.set(6, r, value, true); - } - } - function setupAlignmentPattern(matrix, version2) { - const pos = AlignmentPattern.getPositions(version2); - for (let i2 = 0; i2 < pos.length; i2++) { - const row = pos[i2][0]; - const col = pos[i2][1]; - for (let r = -2; r <= 2; r++) { - for (let c4 = -2; c4 <= 2; c4++) { - if (r === -2 || r === 2 || c4 === -2 || c4 === 2 || r === 0 && c4 === 0) { - matrix.set(row + r, col + c4, true, true); - } else { - matrix.set(row + r, col + c4, false, true); - } - } - } - } - } - function setupVersionInfo(matrix, version2) { - const size = matrix.size; - const bits = Version.getEncodedBits(version2); - let row, col, mod2; - for (let i2 = 0; i2 < 18; i2++) { - row = Math.floor(i2 / 3); - col = i2 % 3 + size - 8 - 3; - mod2 = (bits >> i2 & 1) === 1; - matrix.set(row, col, mod2, true); - matrix.set(col, row, mod2, true); - } - } - function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) { - const size = matrix.size; - const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern); - let i2, mod2; - for (i2 = 0; i2 < 15; i2++) { - mod2 = (bits >> i2 & 1) === 1; - if (i2 < 6) { - matrix.set(i2, 8, mod2, true); - } else if (i2 < 8) { - matrix.set(i2 + 1, 8, mod2, true); - } else { - matrix.set(size - 15 + i2, 8, mod2, true); - } - if (i2 < 8) { - matrix.set(8, size - i2 - 1, mod2, true); - } else if (i2 < 9) { - matrix.set(8, 15 - i2 - 1 + 1, mod2, true); - } else { - matrix.set(8, 15 - i2 - 1, mod2, true); - } - } - matrix.set(size - 8, 8, 1, true); - } - function setupData(matrix, data) { - const size = matrix.size; - let inc = -1; - let row = size - 1; - let bitIndex = 7; - let byteIndex = 0; - for (let col = size - 1; col > 0; col -= 2) { - if (col === 6) - col--; - while (true) { - for (let c4 = 0; c4 < 2; c4++) { - if (!matrix.isReserved(row, col - c4)) { - let dark = false; - if (byteIndex < data.length) { - dark = (data[byteIndex] >>> bitIndex & 1) === 1; - } - matrix.set(row, col - c4, dark); - bitIndex--; - if (bitIndex === -1) { - byteIndex++; - bitIndex = 7; - } - } - } - row += inc; - if (row < 0 || size <= row) { - row -= inc; - inc = -inc; - break; - } - } - } - } - function createData(version2, errorCorrectionLevel, segments) { - const buffer = new BitBuffer(); - segments.forEach(function(data) { - buffer.put(data.mode.bit, 4); - buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version2)); - data.write(buffer); - }); - const totalCodewords = Utils.getSymbolTotalCodewords(version2); - const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); - const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; - if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) { - buffer.put(0, 4); - } - while (buffer.getLengthInBits() % 8 !== 0) { - buffer.putBit(0); - } - const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8; - for (let i2 = 0; i2 < remainingByte; i2++) { - buffer.put(i2 % 2 ? 17 : 236, 8); - } - return createCodewords(buffer, version2, errorCorrectionLevel); - } - function createCodewords(bitBuffer, version2, errorCorrectionLevel) { - const totalCodewords = Utils.getSymbolTotalCodewords(version2); - const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); - const dataTotalCodewords = totalCodewords - ecTotalCodewords; - const ecTotalBlocks = ECCode.getBlocksCount(version2, errorCorrectionLevel); - const blocksInGroup2 = totalCodewords % ecTotalBlocks; - const blocksInGroup1 = ecTotalBlocks - blocksInGroup2; - const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks); - const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks); - const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1; - const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1; - const rs = new ReedSolomonEncoder(ecCount); - let offset = 0; - const dcData = new Array(ecTotalBlocks); - const ecData = new Array(ecTotalBlocks); - let maxDataSize = 0; - const buffer = new Uint8Array(bitBuffer.buffer); - for (let b4 = 0; b4 < ecTotalBlocks; b4++) { - const dataSize = b4 < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2; - dcData[b4] = buffer.slice(offset, offset + dataSize); - ecData[b4] = rs.encode(dcData[b4]); - offset += dataSize; - maxDataSize = Math.max(maxDataSize, dataSize); - } - const data = new Uint8Array(totalCodewords); - let index = 0; - let i2, r; - for (i2 = 0; i2 < maxDataSize; i2++) { - for (r = 0; r < ecTotalBlocks; r++) { - if (i2 < dcData[r].length) { - data[index++] = dcData[r][i2]; - } - } - } - for (i2 = 0; i2 < ecCount; i2++) { - for (r = 0; r < ecTotalBlocks; r++) { - data[index++] = ecData[r][i2]; - } - } - return data; - } - function createSymbol(data, version2, errorCorrectionLevel, maskPattern) { - let segments; - if (Array.isArray(data)) { - segments = Segments.fromArray(data); - } else if (typeof data === "string") { - let estimatedVersion = version2; - if (!estimatedVersion) { - const rawSegments = Segments.rawSplit(data); - estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel); - } - segments = Segments.fromString(data, estimatedVersion || 40); - } else { - throw new Error("Invalid data"); - } - const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel); - if (!bestVersion) { - throw new Error("The amount of data is too big to be stored in a QR Code"); - } - if (!version2) { - version2 = bestVersion; - } else if (version2 < bestVersion) { - throw new Error( - "\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: " + bestVersion + ".\n" - ); - } - const dataBits = createData(version2, errorCorrectionLevel, segments); - const moduleCount = Utils.getSymbolSize(version2); - const modules = new BitMatrix(moduleCount); - setupFinderPattern(modules, version2); - setupTimingPattern(modules); - setupAlignmentPattern(modules, version2); - setupFormatInfo(modules, errorCorrectionLevel, 0); - if (version2 >= 7) { - setupVersionInfo(modules, version2); - } - setupData(modules, dataBits); - if (isNaN(maskPattern)) { - maskPattern = MaskPattern.getBestMask( - modules, - setupFormatInfo.bind(null, modules, errorCorrectionLevel) - ); - } - MaskPattern.applyMask(maskPattern, modules); - setupFormatInfo(modules, errorCorrectionLevel, maskPattern); - return { - modules, - version: version2, - errorCorrectionLevel, - maskPattern, - segments - }; - } - exports2.create = function create2(data, options) { - if (typeof data === "undefined" || data === "") { - throw new Error("No input text"); - } - let errorCorrectionLevel = ECLevel.M; - let version2; - let mask; - if (typeof options !== "undefined") { - errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M); - version2 = Version.from(options.version); - mask = MaskPattern.from(options.maskPattern); - if (options.toSJISFunc) { - Utils.setToSJISFunction(options.toSJISFunc); - } - } - return createSymbol(data, version2, errorCorrectionLevel, mask); - }; - } -}); - -// node_modules/qrcode/lib/renderer/utils.js -var require_utils7 = __commonJS({ - "node_modules/qrcode/lib/renderer/utils.js"(exports2) { - init_shim(); - function hex2rgba(hex) { - if (typeof hex === "number") { - hex = hex.toString(); - } - if (typeof hex !== "string") { - throw new Error("Color should be defined as hex string"); - } - let hexCode = hex.slice().replace("#", "").split(""); - if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { - throw new Error("Invalid hex color: " + hex); - } - if (hexCode.length === 3 || hexCode.length === 4) { - hexCode = Array.prototype.concat.apply([], hexCode.map(function(c4) { - return [c4, c4]; - })); - } - if (hexCode.length === 6) - hexCode.push("F", "F"); - const hexValue = parseInt(hexCode.join(""), 16); - return { - r: hexValue >> 24 & 255, - g: hexValue >> 16 & 255, - b: hexValue >> 8 & 255, - a: hexValue & 255, - hex: "#" + hexCode.slice(0, 6).join("") - }; - } - exports2.getOptions = function getOptions(options) { - if (!options) - options = {}; - if (!options.color) - options.color = {}; - const margin = typeof options.margin === "undefined" || options.margin === null || options.margin < 0 ? 4 : options.margin; - const width = options.width && options.width >= 21 ? options.width : void 0; - const scale = options.scale || 4; - return { - width, - scale: width ? 4 : scale, - margin, - color: { - dark: hex2rgba(options.color.dark || "#000000ff"), - light: hex2rgba(options.color.light || "#ffffffff") - }, - type: options.type, - rendererOpts: options.rendererOpts || {} - }; - }; - exports2.getScale = function getScale(qrSize, opts) { - return opts.width && opts.width >= qrSize + opts.margin * 2 ? opts.width / (qrSize + opts.margin * 2) : opts.scale; - }; - exports2.getImageWidth = function getImageWidth(qrSize, opts) { - const scale = exports2.getScale(qrSize, opts); - return Math.floor((qrSize + opts.margin * 2) * scale); - }; - exports2.qrToImageData = function qrToImageData(imgData, qr, opts) { - const size = qr.modules.size; - const data = qr.modules.data; - const scale = exports2.getScale(size, opts); - const symbolSize = Math.floor((size + opts.margin * 2) * scale); - const scaledMargin = opts.margin * scale; - const palette = [opts.color.light, opts.color.dark]; - for (let i2 = 0; i2 < symbolSize; i2++) { - for (let j2 = 0; j2 < symbolSize; j2++) { - let posDst = (i2 * symbolSize + j2) * 4; - let pxColor = opts.color.light; - if (i2 >= scaledMargin && j2 >= scaledMargin && i2 < symbolSize - scaledMargin && j2 < symbolSize - scaledMargin) { - const iSrc = Math.floor((i2 - scaledMargin) / scale); - const jSrc = Math.floor((j2 - scaledMargin) / scale); - pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]; - } - imgData[posDst++] = pxColor.r; - imgData[posDst++] = pxColor.g; - imgData[posDst++] = pxColor.b; - imgData[posDst] = pxColor.a; - } - } - }; - } -}); - -// node_modules/qrcode/lib/renderer/canvas.js -var require_canvas = __commonJS({ - "node_modules/qrcode/lib/renderer/canvas.js"(exports2) { - init_shim(); - var Utils = require_utils7(); - function clearCanvas(ctx, canvas, size) { - ctx.clearRect(0, 0, canvas.width, canvas.height); - if (!canvas.style) - canvas.style = {}; - canvas.height = size; - canvas.width = size; - canvas.style.height = size + "px"; - canvas.style.width = size + "px"; - } - function getCanvasElement() { - try { - return document.createElement("canvas"); - } catch (e2) { - throw new Error("You need to specify a canvas element"); - } - } - exports2.render = function render(qrData, canvas, options) { - let opts = options; - let canvasEl = canvas; - if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { - opts = canvas; - canvas = void 0; - } - if (!canvas) { - canvasEl = getCanvasElement(); - } - opts = Utils.getOptions(opts); - const size = Utils.getImageWidth(qrData.modules.size, opts); - const ctx = canvasEl.getContext("2d"); - const image = ctx.createImageData(size, size); - Utils.qrToImageData(image.data, qrData, opts); - clearCanvas(ctx, canvasEl, size); - ctx.putImageData(image, 0, 0); - return canvasEl; - }; - exports2.renderToDataURL = function renderToDataURL(qrData, canvas, options) { - let opts = options; - if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { - opts = canvas; - canvas = void 0; - } - if (!opts) - opts = {}; - const canvasEl = exports2.render(qrData, canvas, opts); - const type = opts.type || "image/png"; - const rendererOpts = opts.rendererOpts || {}; - return canvasEl.toDataURL(type, rendererOpts.quality); - }; - } -}); - -// node_modules/qrcode/lib/renderer/svg-tag.js -var require_svg_tag = __commonJS({ - "node_modules/qrcode/lib/renderer/svg-tag.js"(exports2) { - init_shim(); - var Utils = require_utils7(); - function getColorAttrib(color, attrib) { - const alpha = color.a / 255; - const str = attrib + '="' + color.hex + '"'; - return alpha < 1 ? str + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str; - } - function svgCmd(cmd, x3, y4) { - let str = cmd + x3; - if (typeof y4 !== "undefined") - str += " " + y4; - return str; - } - function qrToPath(data, size, margin) { - let path = ""; - let moveBy = 0; - let newRow = false; - let lineLength = 0; - for (let i2 = 0; i2 < data.length; i2++) { - const col = Math.floor(i2 % size); - const row = Math.floor(i2 / size); - if (!col && !newRow) - newRow = true; - if (data[i2]) { - lineLength++; - if (!(i2 > 0 && col > 0 && data[i2 - 1])) { - path += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0); - moveBy = 0; - newRow = false; - } - if (!(col + 1 < size && data[i2 + 1])) { - path += svgCmd("h", lineLength); - lineLength = 0; - } - } else { - moveBy++; - } - } - return path; - } - exports2.render = function render(qrData, options, cb) { - const opts = Utils.getOptions(options); - const size = qrData.modules.size; - const data = qrData.modules.data; - const qrcodesize = size + opts.margin * 2; - const bg = !opts.color.light.a ? "" : "'; - const path = "'; - const viewBox = 'viewBox="0 0 ' + qrcodesize + " " + qrcodesize + '"'; - const width = !opts.width ? "" : 'width="' + opts.width + '" height="' + opts.width + '" '; - const svgTag = '' + bg + path + "\n"; - if (typeof cb === "function") { - cb(null, svgTag); - } - return svgTag; - }; - } -}); - -// node_modules/qrcode/lib/browser.js -var require_browser7 = __commonJS({ - "node_modules/qrcode/lib/browser.js"(exports2) { - init_shim(); - var canPromise = require_can_promise(); - var QRCode2 = require_qrcode(); - var CanvasRenderer = require_canvas(); - var SvgRenderer = require_svg_tag(); - function renderCanvas(renderFunc, canvas, text, opts, cb) { - const args = [].slice.call(arguments, 1); - const argsNum = args.length; - const isLastArgCb = typeof args[argsNum - 1] === "function"; - if (!isLastArgCb && !canPromise()) { - throw new Error("Callback required as last argument"); - } - if (isLastArgCb) { - if (argsNum < 2) { - throw new Error("Too few arguments provided"); - } - if (argsNum === 2) { - cb = text; - text = canvas; - canvas = opts = void 0; - } else if (argsNum === 3) { - if (canvas.getContext && typeof cb === "undefined") { - cb = opts; - opts = void 0; - } else { - cb = opts; - opts = text; - text = canvas; - canvas = void 0; - } - } - } else { - if (argsNum < 1) { - throw new Error("Too few arguments provided"); - } - if (argsNum === 1) { - text = canvas; - canvas = opts = void 0; - } else if (argsNum === 2 && !canvas.getContext) { - opts = text; - text = canvas; - canvas = void 0; - } - return new Promise(function(resolve, reject) { - try { - const data = QRCode2.create(text, opts); - resolve(renderFunc(data, canvas, opts)); - } catch (e2) { - reject(e2); - } - }); - } - try { - const data = QRCode2.create(text, opts); - cb(null, renderFunc(data, canvas, opts)); - } catch (e2) { - cb(e2); - } - } - exports2.create = QRCode2.create; - exports2.toCanvas = renderCanvas.bind(null, CanvasRenderer.render); - exports2.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL); - exports2.toString = renderCanvas.bind(null, function(data, _4, opts) { - return SvgRenderer.render(data, opts); - }); - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/index.js -var require_out2 = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_walletProvider(), exports2); - __exportStar2(require_constants7(), exports2); - } -}); - -// src/elven.ts -init_shim(); -var import_tokens = __toESM(require_tokens(), 1); -var import_tokenOperations = __toESM(require_tokenOperations(), 1); -var import_transactionsFactories = __toESM(require_transactionsFactories(), 1); -var import_transactionsOutcomeParsers = __toESM(require_transactionsOutcomeParsers(), 1); -var import_address4 = __toESM(require_address(), 1); -var import_account4 = __toESM(require_account(), 1); -var import_transaction3 = __toESM(require_transaction(), 1); -var import_transactionComputer = __toESM(require_transactionComputer(), 1); -var import_message = __toESM(require_message(), 1); -var import_transactionWatcher2 = __toESM(require_transactionWatcher(), 1); -var import_signableMessage2 = __toESM(require_signableMessage(), 1); -var import_bytes7 = __toESM(require_bytes(), 1); -var import_numerical = __toESM(require_numerical(), 1); -var import_boolean = __toESM(require_boolean(), 1); -var import_address5 = __toESM(require_address2(), 1); -var import_interface = __toESM(require_interface(), 1); -var import_contractQueryResponse2 = __toESM(require_contractQueryResponse(), 1); - -// src/main.ts -init_shim(); - -// src/auth/init-extension-provider.ts -init_shim(); -var import_extensionProvider = __toESM(require_extensionProvider(), 1); - -// src/utils/ls-helpers.ts -init_shim(); - -// src/utils/constants.ts -init_shim(); -var LOCAL_STORAGE_KEY = "elvenjs_state"; -var defaultApiEndpoint = "https://devnet-api.multiversx.com"; -var DAPP_INIT_ROUTE = "/dapp/init"; -var defaultChainTypeConfig = "devnet"; -var walletConnectDeepLink = "https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/"; -var defaultWalletConnectV2RelayAddresses = [ - "wss://relay.walletconnect.com" -]; -var networkConfig = { - devnet: { - id: "devnet", - shortId: "D", - name: "Devnet", - egldLabel: "xEGLD", - egldDenomination: "18", - decimals: "4", - gasPerDataByte: "1500", - walletAddress: "https://devnet-wallet.multiversx.com", - xAliasAddress: "https://devnet.xalias.com", - apiAddress: "https://devnet-api.multiversx.com", - explorerAddress: "https://devnet-explorer.multiversx.com", - apiTimeout: 1e4 - }, - testnet: { - id: "testnet", - shortId: "T", - name: "Testnet", - egldLabel: "xEGLD", - egldDenomination: "18", - decimals: "4", - gasPerDataByte: "1500", - walletAddress: "https://testnet-wallet.multiversx.com", - xAliasAddress: "https://testnet.xalias.com", - apiAddress: "https://testnet-api.multiversx.com", - explorerAddress: "https://testnet-explorer.multiversx.com", - apiTimeout: 1e4 - }, - mainnet: { - id: "mainnet", - shortId: "1", - name: "Mainnet", - egldLabel: "EGLD", - egldDenomination: "18", - decimals: "4", - gasPerDataByte: "1500", - walletAddress: "https://wallet.multiversx.com", - xAliasAddress: "https://xalias.com", - apiAddress: "https://api.multiversx.com", - explorerAddress: "https://explorer.multiversx.com", - apiTimeout: 1e4 - } -}; - -// src/utils/ls-helpers.ts -var ls = { - get(key) { - const state = localStorage.getItem(LOCAL_STORAGE_KEY); - if (!state) - return {}; - const parsedState = JSON.parse(state); - if (key) { - return parsedState[key]; - } - return parsedState; - }, - set(key, value) { - const currentState = this.get(); - currentState[key] = value; - localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(currentState)); - }, - clear() { - localStorage.removeItem(LOCAL_STORAGE_KEY); - } -}; - -// src/auth/init-extension-provider.ts -var initExtensionProvider = async () => { - const dappProvider = import_extensionProvider.ExtensionProvider.getInstance(); - try { - const isSuccessfullyInitialized = await dappProvider.init(); - const currentState = ls.get(); - if (currentState?.address) { - dappProvider.setAddress(currentState.address); - } - if (!isSuccessfullyInitialized) { - console.warn( - "Something went wrong when trying to initialize the ExtensionProvider.." - ); - return; - } - return dappProvider; - } catch (e2) { - console.warn("Can't initialize the Dapp Provider!"); - } -}; - -// src/main.ts -var import_extensionProvider2 = __toESM(require_extensionProvider(), 1); -var import_walletConnectV2Provider4 = __toESM(require_walletConnectV2Provider(), 1); -var import_walletProvider4 = __toESM(require_walletProvider(), 1); -var import_native_auth2 = __toESM(require_native_auth_client(), 1); -var import_signableMessage = __toESM(require_signableMessage(), 1); - -// src/auth/init-mobile-provider.ts -init_shim(); -var import_walletConnectV2Provider = __toESM(require_walletConnectV2Provider(), 1); - -// src/auth/logout.ts -init_shim(); - -// src/events-store.ts -init_shim(); -var EventsStore = class { - static set(name2, fn) { - if (!name2) - return; - const eventsObj = { ...this.events, [name2]: fn }; - this.events = eventsObj; - } - static get(name2) { - if (!name2 || !this.events) - return; - return this.events[name2]; - } - static run(name2, ...args) { - if (!name2 || !this.events) - return; - this.events[name2]?.(...args); - } - static clear() { - this.events = void 0; - } -}; - -// src/types.ts -init_shim(); -var EventStoreEvents = /* @__PURE__ */ ((EventStoreEvents2) => { - EventStoreEvents2["onLoginStart"] = "onLoginStart"; - EventStoreEvents2["onLoginSuccess"] = "onLoginSuccess"; - EventStoreEvents2["onLoginFailure"] = "onLoginFailure"; - EventStoreEvents2["onLogoutStart"] = "onLogoutStart"; - EventStoreEvents2["onLogoutSuccess"] = "onLogoutSuccess"; - EventStoreEvents2["onLogoutFailure"] = "onLogoutFailure"; - EventStoreEvents2["onQrPending"] = "onQrPending"; - EventStoreEvents2["onQrLoaded"] = "onQrLoaded"; - EventStoreEvents2["onTxStart"] = "onTxStart"; - EventStoreEvents2["onTxSent"] = "onTxSent"; - EventStoreEvents2["onTxFinalized"] = "onTxFinalized"; - EventStoreEvents2["onTxFailure"] = "onTxFailure"; - EventStoreEvents2["onSignMsgStart"] = "onSignMsgStart"; - EventStoreEvents2["onSignMsgFinalized"] = "onSignMsgFinalized"; - EventStoreEvents2["onSignMsgFailure"] = "onSignMsgFailure"; - EventStoreEvents2["onQueryStart"] = "onQueryStart"; - EventStoreEvents2["onQueryFinalized"] = "onQueryFinalized"; - EventStoreEvents2["onQueryFailure"] = "onQueryFailure"; - return EventStoreEvents2; -})(EventStoreEvents || {}); -var LoginMethodsEnum = /* @__PURE__ */ ((LoginMethodsEnum2) => { - LoginMethodsEnum2["ledger"] = "ledger"; - LoginMethodsEnum2["mobile"] = "mobile"; - LoginMethodsEnum2["webWallet"] = "web-wallet"; - LoginMethodsEnum2["browserExtension"] = "browser-extension"; - LoginMethodsEnum2["xAlias"] = "x-alias"; - LoginMethodsEnum2["xPortalHub"] = "x-portal-hub"; - return LoginMethodsEnum2; -})(LoginMethodsEnum || {}); -var DappCoreWCV2CustomMethodsEnum = /* @__PURE__ */ ((DappCoreWCV2CustomMethodsEnum2) => { - DappCoreWCV2CustomMethodsEnum2["mvx_cancelAction"] = "mvx_cancelAction"; - DappCoreWCV2CustomMethodsEnum2["mvx_signNativeAuthToken"] = "mvx_signNativeAuthToken"; - return DappCoreWCV2CustomMethodsEnum2; -})(DappCoreWCV2CustomMethodsEnum || {}); -var WebWalletUrlParamsEnum = /* @__PURE__ */ ((WebWalletUrlParamsEnum2) => { - WebWalletUrlParamsEnum2["hasWebWalletGuardianSign"] = "hasWebWalletGuardianSign"; - return WebWalletUrlParamsEnum2; -})(WebWalletUrlParamsEnum || {}); - -// src/utils/error-parse.ts -init_shim(); -var errorParse = (err) => { - if (typeof err === "string") { - return err.toUpperCase(); - } else if (err instanceof Error) { - return err.message; - } - return JSON.stringify(err); -}; - -// src/auth/logout.ts -var logout = async (elven) => { - if (!elven.dappProvider) { - throw new Error("Logout failed: There is no active session!"); - } - EventsStore.run("onLogoutStart" /* onLogoutStart */); - try { - const isLoggedOut = await elven.dappProvider.logout(); - if (isLoggedOut) { - ls.clear(); - EventsStore.run("onLogoutSuccess" /* onLogoutSuccess */); - } - return isLoggedOut; - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to logout the user: ${err}`); - EventsStore.run("onLogoutFailure" /* onLogoutFailure */, err); - } -}; - -// src/utils/get-random-address-from-network.ts -init_shim(); -function getRandomAddressFromNetwork(addresses) { - return addresses[Math.floor(Math.random() * addresses.length)]; -} - -// src/auth/init-mobile-provider.ts -var initMobileProvider = async (elven) => { - if (!elven.initOptions.walletConnectV2ProjectId || !elven.initOptions.chainType) { - return void 0; - } - const providerHandlers = { - onClientLogin: () => { - }, - onClientLogout: () => logout(elven), - onClientEvent: (event) => { - console.log("wc2 session event: ", event); - } - }; - const relayAddress = getRandomAddressFromNetwork( - elven.initOptions.walletConnectV2RelayAddresses - ); - const dappProviderInstance = new import_walletConnectV2Provider.WalletConnectV2Provider( - providerHandlers, - networkConfig[elven.initOptions.chainType].shortId, - relayAddress, - elven.initOptions.walletConnectV2ProjectId - ); - try { - await dappProviderInstance.init(); - return dappProviderInstance; - } catch { - console.warn("Can't initialize the Dapp Provider!"); - } -}; - -// src/network-provider.ts -init_shim(); -var import_address = __toESM(require_address(), 1); -var import_transactionStatus = __toESM(require_transactionStatus(), 1); -var import_transactionReceipt = __toESM(require_transactionReceipt(), 1); -var import_transactionLogs = __toESM(require_transactionLogs(), 1); -var import_contractResults = __toESM(require_contractResults(), 1); -var import_contractQueryResponse = __toESM(require_contractQueryResponse(), 1); -var import_contractQueryRequest = __toESM(require_contractQueryRequest(), 1); -var import_query = __toESM(require_query(), 1); -var ApiNetworkProvider = class { - constructor({ apiUrl, chainType, apiTimeout }) { - this.chainType = chainType || defaultChainTypeConfig; - this.apiUrl = apiUrl || networkConfig[this.chainType]?.apiAddress; - this.apiTimeout = apiTimeout || networkConfig[this.chainType]?.apiTimeout; - } - async apiGet(endpoint, options) { - if (typeof fetch !== "undefined") { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); - const defaultOptions = { - method: "GET", - headers: { - "Content-Type": "application/json", - Accept: "application/json" - }, - signal: controller.signal - }; - try { - const response = await fetch( - this.apiUrl + "/" + endpoint, - Object.assign(defaultOptions, options || {}) - ); - const result = await response.json(); - if (!response.ok) { - const error = result?.error || response.status; - clearTimeout(timeoutId); - return Promise.reject(error); - } - clearTimeout(timeoutId); - return result; - } catch (e2) { - this.handleApiError(e2, endpoint); - } - } - } - async apiPost(endpoint, payload, options) { - if (typeof fetch !== "undefined") { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); - const defaultOptions = { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json" - }, - body: JSON.stringify(payload || {}), - signal: controller.signal - }; - try { - const response = await fetch( - this.apiUrl + "/" + endpoint, - Object.assign(defaultOptions, options || {}) - ); - const result = await response.json(); - if (!response.ok) { - const error = result?.error || response.status; - clearTimeout(timeoutId); - return Promise.reject(error); - } - clearTimeout(timeoutId); - return result; - } catch (e2) { - this.handleApiError(e2, endpoint); - } - } - } - handleApiError(error, resourceUrl) { - if (!error.response) { - throw new Error( - `Request error on url [${resourceUrl}]: [${error.toString()}]` - ); - } - const errorData = error.response.data; - const originalErrorMessage = errorData.error || errorData.message || JSON.stringify(errorData); - throw new Error(originalErrorMessage); - } - async sendTransaction(tx) { - const response = await this.apiPost("transactions", tx.toSendable()); - return response.txHash; - } - async getAccount(address) { - const responsePayload = await this.apiGet(`accounts/${address.bech32()}`); - const account = { - address: new import_address.Address(responsePayload?.address || ""), - nonce: Number(responsePayload?.nonce || 0), - balance: BigInt(responsePayload?.balance || 0), - code: responsePayload?.code || "", - userName: responsePayload?.username || "" - }; - return account; - } - async getGuardianData(address) { - const response = await this.apiGet( - `address/${address.bech32()}/guardian-data` - ); - const accountGuardian = { - guarded: response?.data?.guardianData?.guarded || false, - activeGuardian: response?.data?.guardianData?.activeGuardian, - pendingGuardian: response?.data?.guardianData?.pendingGuardian - }; - return accountGuardian; - } - async getTransaction(txHash) { - const payload = await this.apiGet(`transactions/${txHash}`); - const status = new import_transactionStatus.TransactionStatus(payload.status); - const transaction = { - hash: txHash, - type: payload.type || "", - nonce: payload.nonce || 0, - round: payload.round, - epoch: payload.epoch || 0, - value: (payload.value || 0).toString(), - sender: new import_address.Address(payload.sender), - receiver: new import_address.Address(payload.receiver), - gasPrice: payload.gasPrice || 0, - gasLimit: payload.gasLimit || 0, - data: import_buffer.Buffer.from(payload.data || "", "base64"), - status, - timestamp: payload.timestamp || 0, - blockNonce: payload.blockNonce || 0, - hyperblockNonce: payload.hyperblockNonce || 0, - hyperblockHash: payload.hyperblockHash || "", - receipt: import_transactionReceipt.TransactionReceipt.fromHttpResponse(payload.receipt || {}), - logs: import_transactionLogs.TransactionLogs.fromHttpResponse(payload.logs || {}), - contractResults: import_contractResults.ContractResults.fromApiHttpResponse( - payload.results || [] - ), - isCompleted: !status.isPending() - }; - return transaction; - } - async queryContract({ - address, - func, - args, - value, - caller - }) { - try { - const query = new import_query.Query({ - address, - func, - args, - value, - caller - }); - const request = new import_contractQueryRequest.ContractQueryRequest(query).toHttpRequest(); - const response = await this.apiPost("query", request); - return import_contractQueryResponse.ContractQueryResponse.fromHttpResponse(response); - } catch (e2) { - this.handleApiError(e2, "query"); - } - } -}; - -// src/auth/login-with-extension.ts -init_shim(); - -// src/auth/expires-at.ts -init_shim(); -var getNewLoginExpiresTimestamp = () => { - return (/* @__PURE__ */ new Date()).setHours((/* @__PURE__ */ new Date()).getHours() + 24); -}; -var isLoginExpired = (expirationTimestamp) => { - return Date.now() > expirationTimestamp; -}; - -// src/auth/account-sync.ts -init_shim(); -var import_address2 = __toESM(require_address(), 1); -var import_account = __toESM(require_account(), 1); -var accountSync = async (elven) => { - const address = ls.get("address"); - const loginExpires = ls.get("expires"); - const loginExpired = loginExpires && isLoginExpired(loginExpires); - if (!loginExpired && address && elven.networkProvider) { - const userAddressInstance = new import_address2.Address(address); - const userAccountInstance = new import_account.Account(userAddressInstance); - try { - const userAccountOnNetwork = await elven.networkProvider.getAccount(userAddressInstance); - const userGuardianOnNetwork = await elven.networkProvider.getGuardianData(userAddressInstance); - ls.set("address", address); - ls.set( - "activeGuardian", - userGuardianOnNetwork.guarded && userGuardianOnNetwork.activeGuardian?.address ? userGuardianOnNetwork.activeGuardian.address : "" - ); - ls.set("nonce", userAccountOnNetwork.nonce.valueOf()); - ls.set("balance", userAccountOnNetwork.balance.toString()); - userAccountInstance.update(userAccountOnNetwork); - } catch (e2) { - const err = errorParse(e2); - console.warn( - `Something went wrong trying to synchronize the user account: ${err}` - ); - } - } -}; - -// src/auth/login-with-extension.ts -var loginWithExtension = async (elven, loginToken, nativeAuthClient, callbackRoute = "/") => { - const dappProvider = await initExtensionProvider(); - const callbackUrl = encodeURIComponent( - `${window.location.origin}${callbackRoute}` - ); - const providerLoginData = { - callbackUrl, - token: loginToken - }; - try { - if (dappProvider) { - const address = await dappProvider.login(providerLoginData); - if (!address) { - throw new Error("There were problems while logging in!"); - } - } - } catch (e2) { - const err = errorParse(e2); - throw new Error(err); - } - if (!dappProvider) { - throw new Error("There were problems with auth provider initialization!"); - } - const { signature } = dappProvider.account; - ls.set("loginToken", loginToken); - if (signature) { - ls.set("signature", signature); - } - if (elven.networkProvider && signature) { - try { - const address = await dappProvider.getAddress(); - if (!address) { - throw new Error("Canceled!"); - } - ls.set("address", address); - ls.set("loginMethod", "browser-extension" /* browserExtension */); - ls.set("expires", getNewLoginExpiresTimestamp()); - await accountSync(elven); - const accessToken = nativeAuthClient.getToken( - address, - loginToken, - signature - ); - ls.set("accessToken", accessToken); - EventsStore.run("onLoginSuccess" /* onLoginSuccess */); - return dappProvider; - } catch (e2) { - throw new Error( - `Something went wrong trying to synchronize the user account: ${e2?.message}` - ); - } - } -}; - -// src/auth/login-with-mobile.ts -init_shim(); - -// src/auth/qr-code-and-pairings-builder.ts -init_shim(); -var import_qrcode = __toESM(require_browser7(), 1); -var import_walletConnectV2Provider2 = __toESM(require_walletConnectV2Provider(), 1); -var htmlStringToElement = (htmlString) => { - const template = document.createElement("template"); - template.innerHTML = htmlString.trim(); - return template.content.firstChild?.cloneNode(true); -}; -var buildDeepLink = (walletConnectUri) => { - const hrefVal = `${walletConnectDeepLink}?wallet-connect=${encodeURIComponent( - walletConnectUri - )}`; - const aElem = document.createElement("a"); - aElem.setAttribute("href", hrefVal); - aElem.setAttribute("rel", "noopener noreferrer nofollow"); - aElem.setAttribute("target", "_blank"); - aElem.textContent = "xPortal login"; - aElem.classList.add("elven-qr-code-deep-link"); - return aElem; -}; -var buildPairingsContainer = () => { - const container = document.createElement("div"); - container.classList.add("elven-wc-pairings"); - return container; -}; -var buildPairingsHeader = () => { - const headerElem = document.createElement("div"); - headerElem.textContent = "Existing WalletConnect pairings:"; - headerElem.classList.add("elven-wc-pairings-header"); - return headerElem; -}; -var pairingRemoveControllers = {}; -var buildPairingsRemoveButton = (pairing, removeExistingPairing) => { - const btn = document.createElement("button"); - btn.classList.add("elven-wc-pairings-remove-btn"); - btn.textContent = "\u2716"; - pairingRemoveControllers[pairing.topic] = new AbortController(); - btn.addEventListener( - "click", - (e2) => { - e2.stopImmediatePropagation(); - removeExistingPairing(pairing.topic); - }, - { - signal: pairingRemoveControllers[pairing.topic].signal - } - ); - return btn; -}; -var pairingLoginControllers = {}; -var buildPairingItem = (pairing, removeExistingPairing, loginThroughExistingPairing) => { - const itemElem = document.createElement("div"); - const itemTextWrapper = document.createElement("div"); - itemElem.classList.add("elven-wc-pairing-item"); - itemElem.setAttribute("id", pairing.topic); - itemTextWrapper.classList.add("elven-wc-pairing-item-description"); - itemTextWrapper.textContent = `${pairing.peerMetadata?.description} (${pairing.peerMetadata?.url})`; - itemElem.appendChild(itemTextWrapper); - const button = buildPairingsRemoveButton(pairing, removeExistingPairing); - itemElem.appendChild(button); - pairingLoginControllers[pairing.topic] = new AbortController(); - itemElem.addEventListener( - "click", - () => loginThroughExistingPairing(pairing.topic), - { signal: pairingLoginControllers[pairing.topic].signal } - ); - return itemElem; -}; -var buildPairingItemConfirmMessage = () => { - const itemElem = document.createElement("div"); - itemElem.classList.add("elven-wc-pairing-item-confirm-msessage"); - itemElem.setAttribute("id", "elven-wc-pairing-item-confirm-msessage"); - itemElem.innerText = "Confirm on xPortal app!"; - return itemElem; -}; -var removePairingItem = (topic) => { - if (!topic) - return; - const pairingElement = document.getElementById(topic); - pairingElement?.remove(); -}; -var isMobile = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( - navigator.userAgent -); -var generateQRCode = async (walletConnectUri) => { - if (!walletConnectUri) { - return; - } - const svg = await import_qrcode.default.toString(walletConnectUri, { - type: "svg" - }); - return svg; -}; -var qrCodeAndPairingsBuilder = async (qrCodeContainer, walletConnectUri, dappProvider, token) => { - if (!qrCodeContainer) - throw new Error( - "Please provide the QR Code and WalletConnect Pairings container id!" - ); - let containerElem = null; - if (typeof qrCodeContainer === "string") { - containerElem = document.getElementById(qrCodeContainer); - } else if (qrCodeContainer instanceof HTMLElement) { - containerElem = qrCodeContainer; - } - const qrCodeElementString = await generateQRCode(walletConnectUri); - let qrCodeSvg; - if (qrCodeElementString) { - qrCodeSvg = htmlStringToElement(qrCodeElementString); - } - if (containerElem && qrCodeSvg) { - containerElem.replaceChildren(); - containerElem.appendChild(qrCodeSvg); - if (isMobile()) { - containerElem.appendChild(buildDeepLink(walletConnectUri)); - } - } - if (containerElem && dappProvider instanceof import_walletConnectV2Provider2.WalletConnectV2Provider) { - const wcPairings = dappProvider.pairings; - const removeExistingPairing = async (topic) => { - try { - if (topic) { - await dappProvider.logout({ - topic - }); - removePairingItem(topic); - } - } catch (e2) { - const err = errorParse(e2); - console.warn( - `Something went wrong trying to remove the existing pairing: ${err}` - ); - } finally { - pairingLoginControllers[topic].abort(); - } - }; - const loginThroughExistingPairing = async (topic) => { - try { - const { approval } = await dappProvider.connect({ - topic, - methods: [ - "mvx_cancelAction" /* mvx_cancelAction */, - "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ - ] - }); - const pairingItemConfirmation = document.getElementById( - "elven-wc-pairing-item-confirm-msessage" - ); - if (!pairingItemConfirmation) { - const pairingItemElement = document.getElementById(topic); - pairingItemElement?.after(buildPairingItemConfirmMessage()); - } - await dappProvider.login({ - approval, - token - }); - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - } finally { - for (const abortController of Object.values(pairingLoginControllers)) { - abortController?.abort(); - } - for (const abortController of Object.values(pairingRemoveControllers)) { - abortController?.abort(); - } - } - }; - if (wcPairings && wcPairings.length > 0) { - const container = buildPairingsContainer(); - containerElem.appendChild(container); - const headerElem = buildPairingsHeader(); - container.appendChild(headerElem); - for (const pairing of wcPairings) { - const itemElem = buildPairingItem( - pairing, - removeExistingPairing, - loginThroughExistingPairing - ); - container.appendChild(itemElem); - } - } - } - return containerElem; -}; - -// src/auth/login-with-mobile.ts -var import_walletConnectV2Provider3 = __toESM(require_walletConnectV2Provider(), 1); -var loginWithMobile = async (elven, loginToken, nativeAuthClient, qrCodeContainer) => { - if (!qrCodeContainer) { - throw new Error( - "You haven't provided the QR code container DOM element id" - ); - } - const relayAddress = getRandomAddressFromNetwork( - elven.initOptions.walletConnectV2RelayAddresses - ); - if (!relayAddress || !elven.networkProvider) { - throw new Error( - "Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!" - ); - } - if (!elven.initOptions.walletConnectV2ProjectId) { - throw new Error( - "Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)" - ); - } - if (!elven.initOptions.chainType) { - throw new Error("Please provide the chain type in ElvenJS.init function!"); - } - let qrCodeElement; - const providerHandlers = { - onClientLogin: async () => { - if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { - const address = await elven.dappProvider.getAddress(); - const signature = await elven.dappProvider.getSignature(); - ls.set("address", address); - ls.set("loginMethod", "mobile" /* mobile */); - ls.set("expires", getNewLoginExpiresTimestamp()); - await accountSync(elven); - if (signature) { - ls.set("signature", signature); - } - ls.set("loginToken", loginToken); - const accessToken = nativeAuthClient.getToken( - address, - loginToken, - signature - ); - ls.set("accessToken", accessToken); - EventsStore.run("onLoginSuccess" /* onLoginSuccess */); - qrCodeElement?.replaceChildren(); - } - }, - onClientLogout: async () => { - if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { - await logout(elven); - } - }, - onClientEvent: (event) => { - console.log("wc2 session event: ", event); - } - }; - const dappProvider = new import_walletConnectV2Provider3.WalletConnectV2Provider( - providerHandlers, - networkConfig[elven.initOptions.chainType].shortId, - relayAddress, - elven.initOptions.walletConnectV2ProjectId - ); - try { - if (dappProvider) { - elven.dappProvider = dappProvider; - EventsStore.run("onQrPending" /* onQrPending */); - await dappProvider.init(); - const { uri: walletConnectUri, approval } = await dappProvider.connect({ - methods: [ - "mvx_cancelAction" /* mvx_cancelAction */, - "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ - ] - }); - const wCUri = loginToken ? `${walletConnectUri}&token=${loginToken}` : walletConnectUri; - if (qrCodeContainer && wCUri) { - qrCodeElement = await qrCodeAndPairingsBuilder( - qrCodeContainer, - wCUri, - dappProvider, - loginToken - ); - EventsStore.run("onQrLoaded" /* onQrLoaded */); - } - await dappProvider.login({ - approval, - token: loginToken - }); - return dappProvider; - } - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - EventsStore.run("onLoginFailure" /* onLoginFailure */, err); - } -}; - -// src/auth/login-with-web-wallet.ts -init_shim(); -var import_walletProvider = __toESM(require_walletProvider(), 1); -var loginWithWebWallet = async (urlAddress, loginToken, chainType, callbackRoute) => { - const dappProvider = new import_walletProvider.WalletProvider(`${urlAddress}${DAPP_INIT_ROUTE}`); - const callbackUrl = typeof window !== "undefined" ? encodeURIComponent(`${window.location.origin}${callbackRoute || "/"}`) : "/"; - const providerLoginData = { - callbackUrl, - token: loginToken - }; - try { - ls.set( - "loginMethod", - networkConfig[chainType].xAliasAddress === urlAddress ? "x-alias" /* xAlias */ : "web-wallet" /* webWallet */ - ); - await dappProvider.login(providerLoginData); - ls.set("expires", getNewLoginExpiresTimestamp()); - ls.set("loginToken", loginToken); - return dappProvider; - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - ls.set("loginMethod", ""); - EventsStore.run("onLoginFailure" /* onLoginFailure */, err); - } -}; - -// src/utils/get-param-from-url.ts -init_shim(); -var getParamFromUrl = (paramName) => { - if (typeof window !== "undefined") { - const url = new URL(window.location.href); - const params = new URLSearchParams(url.search); - return params.get(paramName); - } -}; - -// src/auth/init-web-wallet-provider.ts -init_shim(); -var import_walletProvider2 = __toESM(require_walletProvider(), 1); -var import_native_auth = __toESM(require_native_auth_client(), 1); -var initWebWalletProvider = async (webWalletAddress, apiUrl) => { - const signature = getParamFromUrl("signature"); - const urlAddress = getParamFromUrl("address"); - const lsAddress = ls.get("address"); - const loginToken = ls.get("loginToken"); - if (signature) { - ls.set("signature", signature); - } - if (urlAddress || lsAddress) { - if (urlAddress) { - ls.set("address", urlAddress); - window.history.replaceState(null, "", window.location.pathname); - } - const dappProvider = new import_walletProvider2.WalletProvider( - `${webWalletAddress}${DAPP_INIT_ROUTE}` - ); - if (signature && apiUrl && urlAddress) { - const nativeAuthClient = new import_native_auth.NativeAuthClient({ - apiUrl, - origin: window.location.origin - }); - const accessToken = nativeAuthClient.getToken( - urlAddress, - loginToken, - signature - ); - ls.set("accessToken", accessToken); - } - return dappProvider; - } -}; - -// src/interaction/post-send-tx.ts -init_shim(); -var import_account2 = __toESM(require_account(), 1); -var import_transactionWatcher = __toESM(require_transactionWatcher(), 1); -var postSendTx = async (transaction, networkProvider) => { - EventsStore.run("onTxSent" /* onTxSent */, transaction); - const transactionWatcher = new import_transactionWatcher.TransactionWatcher(networkProvider); - const transactionOnNetwork = await transactionWatcher.awaitCompleted(transaction); - const sender = transactionOnNetwork.sender; - const senderAccount = new import_account2.Account(sender); - const userAccountOnNetwork = await networkProvider.getAccount(sender); - senderAccount.update(userAccountOnNetwork); - ls.set("address", senderAccount.address.bech32()); - ls.set("balance", senderAccount.balance.toString()); - EventsStore.run("onTxFinalized" /* onTxFinalized */, transactionOnNetwork); -}; - -// src/interaction/web-wallet-tx-finalize.ts -init_shim(); -var import_out = __toESM(require_out2(), 1); -var import_transaction = __toESM(require_transaction(), 1); - -// src/interaction/pre-send-tx.ts -init_shim(); -var import_account3 = __toESM(require_account(), 1); -var preSendTx = (tx) => { - const sender = tx.getSender(); - const senderAccount = new import_account3.Account(sender); - const currentNonce = tx.nonce.valueOf(); - senderAccount.incrementNonce(); - ls.set("nonce", (currentNonce + 1n).toString()); -}; - -// src/interaction/web-wallet-tx-finalize.ts -var webWalletTxFinalize = async (dappProvider, networkProvider, urlAddress, nonce) => { - const walletProviderStatus = getParamFromUrl(import_out.WALLET_PROVIDER_CALLBACK_PARAM); - if (walletProviderStatus === import_out.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED && dappProvider && networkProvider) { - const guardian = ls.get("activeGuardian"); - const loginMethod = ls.get("loginMethod"); - const hasWebWalletGuardianSign = getParamFromUrl( - "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */ - ); - let transactionObj; - if ("getTransactionsFromWalletUrl" in dappProvider) { - const txs = dappProvider.getTransactionsFromWalletUrl(); - transactionObj = txs?.[0]; - if (!transactionObj) - return; - if (loginMethod === "web-wallet" /* webWallet */) { - transactionObj.data = import_buffer.Buffer.from(transactionObj.data).toString( - "base64" - ); - } - } else if (guardian && loginMethod !== "web-wallet" /* webWallet */ && loginMethod !== "x-alias" /* xAlias */ && hasWebWalletGuardianSign) { - const webWalletProvider = new import_out.WalletProvider( - `${urlAddress}${DAPP_INIT_ROUTE}` - ); - const txs = webWalletProvider.getTransactionsFromWalletUrl(); - transactionObj = txs?.[0]; - } - if (transactionObj) { - const transaction = import_transaction.Transaction.fromPlainObject(transactionObj); - transaction.nonce = BigInt(nonce); - preSendTx(transaction); - try { - EventsStore.run("onTxStart" /* onTxStart */, transaction); - await networkProvider.sendTransaction(transaction); - await postSendTx(transaction, networkProvider); - } catch (e2) { - const err = errorParse(e2); - const errMsg = `Getting transaction information failed! ${err}`; - EventsStore.run("onTxFailure" /* onTxFailure */, transaction, errMsg); - throw new Error(errMsg); - } finally { - window.history.replaceState(null, "", window.location.pathname); - } - } - window.history.replaceState(null, "", window.location.pathname); - } -}; - -// src/interaction/guardian-operations.ts -init_shim(); -var import_networkParams = __toESM(require_networkParams(), 1); -var import_address3 = __toESM(require_address(), 1); -var import_walletProvider3 = __toESM(require_walletProvider(), 1); -var guardianPreSignTxOperations = (tx) => { - const guardian = ls.get("activeGuardian"); - if (guardian) { - const options = { - guarded: true - }; - tx.setVersion(import_networkParams.TransactionVersion.withTxOptions()); - tx.setOptions(import_networkParams.TransactionOptions.withOptions(options)); - tx.setGuardian(import_address3.Address.fromBech32(guardian)); - } - return tx; -}; -var sendTxToGuardian = async (signedTx, walletAddress) => { - const webWalletProvider = new import_walletProvider3.WalletProvider( - `${walletAddress}${DAPP_INIT_ROUTE}` - ); - const currentUrl = window?.location.href; - const alteredCallbackUrl = new URL(currentUrl); - alteredCallbackUrl.searchParams.set( - "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */, - "true" - ); - await webWalletProvider.guardTransactions([signedTx], { - callbackUrl: encodeURIComponent(alteredCallbackUrl.toString()) - }); -}; -var checkNeedsGuardianSigning = (signedTx) => { - const guardian = ls.get("activeGuardian"); - const address = ls.get("address"); - if (!address || !guardian) { - return false; - } - if (signedTx.isGuardedTransaction()) { - return false; - } - return true; -}; - -// src/interaction/web-wallet-sign-message-finalize.ts -init_shim(); -var webWalletSignMessageFinalize = () => { - const isNotTransaction = !getParamFromUrl("walletProviderStatus"); - const isSigned = getParamFromUrl("status") === "signed"; - const message = getParamFromUrl("message"); - const signature = getParamFromUrl("signature"); - if (isNotTransaction && isSigned && message && signature) { - EventsStore.run("onSignMsgFinalized" /* onSignMsgFinalized */, message, signature); - window.history.replaceState(null, "", window.location.pathname); - } -}; - -// src/webview-provider/webview-provider.ts -init_shim(); -var import_transaction2 = __toESM(require_transaction(), 1); - -// src/webview-provider/types.ts -init_shim(); -var WebViewProviderResponseBaseEnums = /* @__PURE__ */ ((WebViewProviderResponseBaseEnums2) => { - WebViewProviderResponseBaseEnums2["reloginResponse"] = "RELOGIN_RESPONSE"; - return WebViewProviderResponseBaseEnums2; -})(WebViewProviderResponseBaseEnums || {}); -var CrossWindowProviderResponseEnums = /* @__PURE__ */ ((CrossWindowProviderResponseEnums2) => { - CrossWindowProviderResponseEnums2["handshakeResponse"] = "HANDSHAKE_RESPONSE"; - CrossWindowProviderResponseEnums2["loginResponse"] = "LOGIN_RESPONSE"; - CrossWindowProviderResponseEnums2["disconnectResponse"] = "DISCONNECT_RESPONSE"; - CrossWindowProviderResponseEnums2["cancelResponse"] = "CANCEL_RESPONSE"; - CrossWindowProviderResponseEnums2["signTransactionsResponse"] = "SIGN_TRANSACTIONS_RESPONSE"; - CrossWindowProviderResponseEnums2["signMessageResponse"] = "SIGN_MESSAGE_RESPONSE"; - CrossWindowProviderResponseEnums2["noneResponse"] = "NONE_RESPONSE"; - return CrossWindowProviderResponseEnums2; -})(CrossWindowProviderResponseEnums || {}); -var WebViewProviderResponseEnums = { - ...CrossWindowProviderResponseEnums, - ...WebViewProviderResponseBaseEnums -}; -var WebViewProviderRequestBaseEnums = /* @__PURE__ */ ((WebViewProviderRequestBaseEnums2) => { - WebViewProviderRequestBaseEnums2["signTransactionsWithGuardianResponse"] = "SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE"; - WebViewProviderRequestBaseEnums2["reloginRequest"] = "RELOGIN_REQUEST"; - return WebViewProviderRequestBaseEnums2; -})(WebViewProviderRequestBaseEnums || {}); -var CrossWindowProviderRequestEnums = /* @__PURE__ */ ((CrossWindowProviderRequestEnums2) => { - CrossWindowProviderRequestEnums2["signTransactionsRequest"] = "SIGN_TRANSACTIONS_REQUEST"; - CrossWindowProviderRequestEnums2["signMessageRequest"] = "SIGN_MESSAGE_REQUEST"; - CrossWindowProviderRequestEnums2["loginRequest"] = "LOGIN_REQUEST"; - CrossWindowProviderRequestEnums2["logoutRequest"] = "LOGOUT_REQUEST"; - CrossWindowProviderRequestEnums2["cancelAction"] = "CANCEL_ACTION_REQUEST"; - CrossWindowProviderRequestEnums2["finalizeHandshakeRequest"] = "FINALIZE_HANDSHAKE_REQUEST"; - return CrossWindowProviderRequestEnums2; -})(CrossWindowProviderRequestEnums || {}); -var WebViewProviderRequestEnums = { - ...CrossWindowProviderRequestEnums, - ...WebViewProviderRequestBaseEnums -}; - -// src/webview-provider/utils.ts -init_shim(); -var safeWindow = typeof window !== "undefined" ? window : {}; -var detectCurrentPlatform = () => { - if (safeWindow.ReactNativeWebView) { - return "reactNative" /* reactNative */; - } - if (safeWindow.webkit) { - return "ios" /* ios */; - } - return "web" /* web */; -}; -var getTargetOrigin = () => { - return typeof window != "undefined" && typeof window?.location != "undefined" ? window?.parent?.origin ?? "*" : "*"; -}; -var isString = (x3) => { - return Object.prototype.toString.call(x3) === "[object String]"; -}; - -// src/webview-provider/request-methods.ts -init_shim(); -var requestMethods = { - signTransactions: { - ["ios" /* ios */]: (transactions) => window.webkit.messageHandlers.signTransactions.postMessage( - transactions, - getTargetOrigin() - ), - ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signTransactionsRequest, - message - }) - ), - ["web" /* web */]: (message) => window?.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signTransactionsRequest, - message - }), - getTargetOrigin() - ) - }, - signMessage: { - ["ios" /* ios */]: (message) => window.webkit.messageHandlers.signMessage.postMessage(message), - ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signMessageRequest, - message - }) - ), - ["web" /* web */]: (message) => window?.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signMessageRequest, - message - }), - getTargetOrigin() - ) - }, - logout: { - ["ios" /* ios */]: () => window.webkit.messageHandlers.logout.postMessage(), - ["reactNative" /* reactNative */]: () => window?.ReactNativeWebView.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.logoutRequest - }) - ), - ["web" /* web */]: () => window?.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.logoutRequest - }), - getTargetOrigin() - ) - } -}; - -// src/webview-provider/webview-provider.ts -var currentPlatform = detectCurrentPlatform(); -var messageType = "message"; -var handleWaitForMessage = (cb) => { - const handleMessageReceived = (event) => { - let eventData = event.data; - if (event.target.origin != getTargetOrigin() && currentPlatform != "reactNative" /* reactNative */) { - return; - } - try { - eventData = JSON.parse(eventData); - cb(eventData); - } catch (err) { - console.error("error parsing response"); - } - }; - if (document) { - document.addEventListener(messageType, handleMessageReceived); - } - if (window) { - window.addEventListener(messageType, handleMessageReceived); - } -}; -var WebviewProvider = class { - constructor() { - } - async logout() { - requestMethods.logout[currentPlatform](); - return new Promise((resolve) => { - resolve(true); - }); - } - async signMessage(message) { - try { - requestMethods.signMessage[currentPlatform](message); - const waitForSignedMessageResponse = new Promise( - (resolve, reject) => { - window.signMessageResponse = (signedMessage, error) => { - if (error) { - reject(error); - window.signMessageResponse = null; - return; - } - resolve(signedMessage); - window.signMessageResponse = null; - }; - function handleSignMessageResponse(eventData) { - const { message: message2, type } = eventData; - if (type === WebViewProviderResponseEnums.signMessageResponse && message2 != null) { - const { signedMessage, error } = message2; - if (!error) { - resolve(signedMessage); - } else { - reject(error); - } - } - document?.removeEventListener( - messageType, - handleSignMessageResponse - ); - } - handleWaitForMessage(handleSignMessageResponse); - } - ); - return await waitForSignedMessageResponse; - } catch (err) { - console.error("error sending transaction", err); - throw err; - } - } - async signTransactions(transactions) { - try { - const plainTransactions = transactions.map((tx) => tx.toPlainObject()); - requestMethods.signTransactions[currentPlatform](plainTransactions); - const waitForSignedTransactionsResponse = new Promise((resolve, reject) => { - window.transactionsSigned = (txs, error) => { - txs = JSON.parse(txs); - if (error) { - reject(error); - window.transactionsSigned = null; - return; - } - resolve(txs.map((tx) => import_transaction2.Transaction.fromPlainObject(tx))); - window.transactionsSigned = null; - }; - function handleSignTransactionResponse(eventData) { - const { message, type } = eventData; - if (type === WebViewProviderResponseEnums.signTransactionsResponse) { - const { transactions: transactions2, error } = message; - try { - if (!error) { - resolve( - transactions2.map( - (tx) => import_transaction2.Transaction.fromPlainObject(tx) - ) - ); - } else { - reject(error); - } - } catch (err) { - reject("Unable to sign"); - } - } - if (document) { - document.removeEventListener( - messageType, - handleSignTransactionResponse - ); - } - } - handleWaitForMessage(handleSignTransactionResponse); - }); - return await waitForSignedTransactionsResponse; - } catch (err) { - console.error("error sending transaction", err); - throw err; - } - } - async signTransaction(transaction) { - const response = await this.signTransactions([transaction]); - return response[0]; - } -}; - -// src/auth/login-with-native-auth-token.ts -init_shim(); - -// src/webview-provider/decode-native-auth-token.ts -init_shim(); - -// src/webview-provider/base64-utils.ts -init_shim(); -function isStringBase64(str) { - try { - const atobDecoded = atob(str); - const btoaEncoded = btoa(atobDecoded); - const bufferFromDecoded = import_buffer.Buffer.from(str, "base64").toString(); - const bufferFromEncoded = import_buffer.Buffer.from(bufferFromDecoded).toString("base64"); - const isEqualToInitialString = str === btoaEncoded && str === bufferFromEncoded; - const isAtobEqualToBufferFrom = atobDecoded === bufferFromDecoded; - if (isEqualToInitialString || isAtobEqualToBufferFrom) { - return true; - } - } catch (e2) { - return false; - } - return false; -} -function decodeBase64(string2) { - if (!isStringBase64(string2)) { - return string2; - } - return atob(string2); -} - -// src/webview-provider/decode-login-token.ts -init_shim(); -var decodeLoginToken = (loginToken) => { - if (!loginToken || !isString(loginToken)) { - return null; - } - const parts = loginToken.split("."); - if (parts.length !== 4) { - return null; - } - try { - const [origin, blockHash, ttl, extraInfo] = parts; - const parsedExtraInfo = JSON.parse(decodeBase64(extraInfo)); - const parsedOrigin = decodeBase64(origin); - return { - ttl: Number(ttl), - extraInfo: parsedExtraInfo, - origin: parsedOrigin, - blockHash - }; - } catch (e2) { - console.error(`Error trying to decode ${loginToken}:`, e2); - return null; - } -}; - -// src/webview-provider/decode-native-auth-token.ts -var decodeNativeAuthToken = (accessToken) => { - if (!accessToken || !isString(accessToken)) { - return null; - } - const parts = accessToken.split("."); - if (parts.length !== 3) { - console.error( - "Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead" - ); - return null; - } - try { - const [address, body, signature] = parts; - const parsedAddress = decodeBase64(address); - const parsedBody = decodeBase64(body); - const parsedInitToken = decodeLoginToken(parsedBody); - if (!parsedInitToken) { - return { - address: parsedAddress, - body: parsedBody, - signature, - blockHash: "", - origin: "", - ttl: 0 - }; - } - const result = { - ...parsedInitToken, - address: parsedAddress, - body: parsedBody, - signature - }; - if (!parsedInitToken.extraInfo?.timestamp) { - delete result.extraInfo; - } - return result; - } catch (err) { - return null; - } -}; - -// src/auth/login-with-native-auth-token.ts -function loginWithNativeAuthToken(token, elven) { - const nativeAuthInfo = decodeNativeAuthToken(token); - if (nativeAuthInfo == null) { - return; - } - const { signature, address, body } = nativeAuthInfo; - if (signature && token && address) { - ls.set("loginToken", body); - ls.set("accessToken", token); - ls.set("signature", signature); - ls.set("address", address); - ls.set("loginMethod", "x-portal-hub" /* xPortalHub */); - elven.dappProvider = new WebviewProvider(); - } -} - -// src/initialize-events-store.ts -init_shim(); -var initializeEventsStore = (initOptions) => { - if (initOptions.onLoginStart) { - EventsStore.set("onLoginStart" /* onLoginStart */, initOptions.onLoginStart); - } - if (initOptions.onLoginSuccess) { - EventsStore.set( - "onLoginSuccess" /* onLoginSuccess */, - initOptions.onLoginSuccess - ); - } - if (initOptions.onLoginFailure) { - EventsStore.set( - "onLoginFailure" /* onLoginFailure */, - initOptions.onLoginFailure - ); - } - if (initOptions.onLogoutStart) { - EventsStore.set("onLogoutStart" /* onLogoutStart */, initOptions.onLogoutStart); - } - if (initOptions.onLogoutSuccess) { - EventsStore.set( - "onLogoutSuccess" /* onLogoutSuccess */, - initOptions.onLogoutSuccess - ); - } - if (initOptions.onLogoutFailure) { - EventsStore.set( - "onLogoutFailure" /* onLogoutFailure */, - initOptions.onLogoutFailure - ); - } - if (initOptions.onQrPending) { - EventsStore.set("onQrPending" /* onQrPending */, initOptions.onQrPending); - } - if (initOptions.onQrLoaded) { - EventsStore.set("onQrLoaded" /* onQrLoaded */, initOptions.onQrLoaded); - } - if (initOptions.onTxStart) { - EventsStore.set("onTxStart" /* onTxStart */, initOptions.onTxStart); - } - if (initOptions.onTxSent) { - EventsStore.set("onTxSent" /* onTxSent */, initOptions.onTxSent); - } - if (initOptions.onTxFinalized) { - EventsStore.set("onTxFinalized" /* onTxFinalized */, initOptions.onTxFinalized); - } - if (initOptions.onTxFailure) { - EventsStore.set("onTxFailure" /* onTxFailure */, initOptions.onTxFailure); - } - if (initOptions.onSignMsgStart) { - EventsStore.set( - "onSignMsgStart" /* onSignMsgStart */, - initOptions.onSignMsgStart - ); - } - if (initOptions.onSignMsgFinalized) { - EventsStore.set( - "onSignMsgFinalized" /* onSignMsgFinalized */, - initOptions.onSignMsgFinalized - ); - } - if (initOptions.onSignMsgFailure) { - EventsStore.set( - "onSignMsgFailure" /* onSignMsgFailure */, - initOptions.onSignMsgFailure - ); - } - if (initOptions.onQueryStart) { - EventsStore.set("onQueryStart" /* onQueryStart */, initOptions.onQueryStart); - } - if (initOptions.onQueryFinalized) { - EventsStore.set( - "onQueryFinalized" /* onQueryFinalized */, - initOptions.onQueryFinalized - ); - } - if (initOptions.onQueryFailure) { - EventsStore.set( - "onQueryFailure" /* onQueryFailure */, - initOptions.onQueryFailure - ); - } -}; - -// src/utils/with-login-events.ts -init_shim(); -var withLoginEvents = async (fn) => { - EventsStore.run("onLoginStart" /* onLoginStart */); - try { - await fn(() => { - EventsStore.run("onLoginSuccess" /* onLoginSuccess */); - }); - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - EventsStore.run("onLoginFailure" /* onLoginFailure */, err); - } -}; - -// src/main.ts -var ElvenJS = class { - /** - * Initialization of the Elven.js - */ - static async init(options) { - const state = ls.get(); - if (state.expires && isLoginExpired(state.expires)) { - ls.clear(); - this.dappProvider = void 0; - return; - } - this.initOptions = { - chainType: defaultChainTypeConfig, - apiUrl: defaultApiEndpoint, - apiTimeout: 1e4, - walletConnectV2ProjectId: "", - walletConnectV2RelayAddresses: defaultWalletConnectV2RelayAddresses, - ...options - }; - this.networkProvider = new ApiNetworkProvider(this.initOptions); - initializeEventsStore(this.initOptions); - const nativeAuthTokenFromUrl = getParamFromUrl("accessToken"); - if (nativeAuthTokenFromUrl) { - await withLoginEvents(async (onLoginSuccess) => { - loginWithNativeAuthToken(nativeAuthTokenFromUrl, this); - await accountSync(this); - onLoginSuccess(); - }); - } - const isAddress = state?.address || (state.loginMethod === "web-wallet" /* webWallet */ || state.loginMethod === "x-alias" /* xAlias */) && getParamFromUrl("address"); - if (isAddress && state?.loginMethod) { - await withLoginEvents(async (onLoginSuccess) => { - if (state.loginMethod === "browser-extension" /* browserExtension */) { - this.dappProvider = await initExtensionProvider(); - } - if (state.loginMethod === "mobile" /* mobile */) { - this.dappProvider = await initMobileProvider(this); - } - if (state.loginMethod === "x-portal-hub" /* xPortalHub */) { - this.dappProvider = new WebviewProvider(); - } - if (state.loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { - this.dappProvider = await initWebWalletProvider( - networkConfig[this.initOptions.chainType].walletAddress, - this.initOptions.apiUrl - ); - } - if (state.loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { - this.dappProvider = await initWebWalletProvider( - networkConfig[this.initOptions.chainType].xAliasAddress, - this.initOptions.apiUrl - ); - } - await accountSync(this); - onLoginSuccess(); - }); - if (this.initOptions?.chainType) { - await webWalletTxFinalize( - this.dappProvider, - this.networkProvider, - networkConfig[this.initOptions.chainType][state.loginMethod === "x-alias" /* xAlias */ ? "xAliasAddress" : "walletAddress"], - state.nonce - ); - webWalletSignMessageFinalize(); - } - } - } - /** - * Login function - */ - static async login(loginMethod, options) { - const isProperLoginMethod = Object.values(LoginMethodsEnum).includes(loginMethod); - if (!isProperLoginMethod) { - const error = "Wrong login method!"; - EventsStore.run("onLoginFailure" /* onLoginFailure */, error); - throw new Error(error); - } - if (!this.networkProvider) { - const error = "Login failed: Use ElvenJs.init() first!"; - EventsStore.run("onLoginFailure" /* onLoginFailure */, error); - throw new Error(error); - } - await withLoginEvents(async () => { - const nativeAuthClient = new import_native_auth2.NativeAuthClient({ - apiUrl: this.initOptions?.apiUrl, - origin: window.location.origin - }); - const loginToken = await nativeAuthClient.initialize(); - if (loginMethod === "browser-extension" /* browserExtension */) { - const dappProvider = await loginWithExtension( - this, - loginToken, - nativeAuthClient, - options?.callbackRoute - ); - this.dappProvider = dappProvider; - } - if (loginMethod === "mobile" /* mobile */) { - const dappProvider = await loginWithMobile( - this, - loginToken, - nativeAuthClient, - options?.qrCodeContainer - ); - this.dappProvider = dappProvider; - } - if (loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { - const dappProvider = await loginWithWebWallet( - networkConfig[this.initOptions.chainType].walletAddress, - loginToken, - this.initOptions?.chainType, - options?.callbackRoute - ); - this.dappProvider = dappProvider; - } - if (loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { - const dappProvider = await loginWithWebWallet( - networkConfig[this.initOptions.chainType].xAliasAddress, - loginToken, - this.initOptions?.chainType, - options?.callbackRoute - ); - this.dappProvider = dappProvider; - } - }); - } - /** - * Logout function - */ - static async logout() { - try { - const isLoggedOut = await logout(this); - this.dappProvider = void 0; - return isLoggedOut; - } catch (e2) { - const err = errorParse(e2); - console.warn("Something went wrong when logging out: ", err); - } - } - /** - * Sign and send function - */ - static async signAndSendTransaction(transaction) { - if (!this.dappProvider) { - const error = "Transaction signing failed: There is no active session!"; - EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); - throw new Error(error); - } - if (!this.networkProvider) { - const error = "Transaction signing failed: There is no active network provider!"; - EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); - throw new Error(error); - } - let signedTx = guardianPreSignTxOperations(transaction); - try { - EventsStore.run("onTxStart" /* onTxStart */, transaction); - const currentState = ls.get(); - transaction.nonce = currentState.nonce; - if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { - signedTx = await this.dappProvider.signTransaction(transaction); - } - if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { - signedTx = await this.dappProvider.signTransaction(transaction); - } - if (this.dappProvider instanceof WebviewProvider) { - signedTx = await this.dappProvider.signTransaction(transaction); - } - if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { - await this.dappProvider.signTransaction(transaction); - } - if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { - const needsGuardianSign = checkNeedsGuardianSigning(signedTx); - if (!needsGuardianSign) { - preSendTx(signedTx); - } - if (needsGuardianSign && this.initOptions?.chainType) { - await sendTxToGuardian( - signedTx, - networkConfig[this.initOptions.chainType].walletAddress - ); - return; - } - await this.networkProvider.sendTransaction(signedTx); - await postSendTx(signedTx, this.networkProvider); - } - } catch (e2) { - const err = errorParse(e2); - EventsStore.run( - "onTxFailure" /* onTxFailure */, - signedTx, - `Getting transaction information failed! ${err}` - ); - throw new Error(`Getting transaction information failed! ${err}`); - } - return signedTx; - } - /** - * Sign a single message - */ - static async signMessage(message, options) { - if (!this.dappProvider) { - const error = "Message signing failed: There is no active session!"; - EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); - throw new Error(error); - } - if (!this.networkProvider) { - const error = "Message signing failed: There is no active network provider!"; - EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); - throw new Error(error); - } - let messageSignature = ""; - try { - EventsStore.run("onSignMsgStart" /* onSignMsgStart */, message); - if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { - const signedMessage = await this.dappProvider.signMessage( - new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) - ); - messageSignature = signedMessage.getSignature().toString("hex"); - } - if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { - const signedMessage = await this.dappProvider.signMessage( - new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) - ); - messageSignature = signedMessage.getSignature().toString("hex"); - } - if (this.dappProvider instanceof WebviewProvider) { - messageSignature = await this.dappProvider.signMessage(message); - } - if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { - const encodeRFC3986URIComponent = (str) => { - return encodeURIComponent(str).replace( - /[!'()*]/g, - (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}` - ); - }; - const url = options?.callbackUrl || window.location.origin; - await this.dappProvider.signMessage( - new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }), - { - callbackUrl: encodeURIComponent( - `${url}${url.includes("?") ? "&" : "?"}message=${encodeRFC3986URIComponent(message)}` - ) - } - ); - } - const currentState = ls.get(); - if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { - EventsStore.run( - "onSignMsgFinalized" /* onSignMsgFinalized */, - message, - messageSignature - ); - } - return { message, messageSignature }; - } catch (e2) { - const err = errorParse(e2); - EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, err); - throw new Error(`Message signing failed! ${err}`); - } - } - /** - * Query Smart Contracts - */ - static async queryContract({ - address, - func, - args = [], - value = 0, - caller - }) { - if (!this.networkProvider) { - throw new Error("Query failed: There is no active network provider!"); - } - if (!address || !func) { - throw new Error( - "Query failed: The Query arguments are not valid! Address and func required" - ); - } - const queryArgs = { - address, - func, - args, - value, - caller - }; - try { - EventsStore.run("onQueryStart" /* onQueryStart */, queryArgs); - const response = await this.networkProvider.queryContract(queryArgs); - EventsStore.run("onQueryFinalized" /* onQueryFinalized */, response); - return response; - } catch (e2) { - const err = errorParse(e2); - EventsStore.run("onQueryFinalized" /* onQueryFinalized */, queryArgs, err); - throw new Error(`Smart contract query failed! ${err}`); - } - } - static { - /** - * Main storage - */ - this.storage = ls; - } - static { - /** - * Destroy and cleanup if needed - */ - this.destroy = () => { - this.networkProvider = void 0; - this.dappProvider = void 0; - this.initOptions = void 0; - EventsStore.clear(); - }; - } -}; - -// src/utils/amount.ts -init_shim(); - -// node_modules/bignumber.js/bignumber.mjs -init_shim(); -var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; -var mathceil = Math.ceil; -var mathfloor = Math.floor; -var bignumberError = "[BigNumber Error] "; -var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; -var BASE = 1e14; -var LOG_BASE = 14; -var MAX_SAFE_INTEGER = 9007199254740991; -var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13]; -var SQRT_BASE = 1e7; -var MAX = 1e9; -function clone(configObject) { - var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber2(v2, b4) { - var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; - if (!(x3 instanceof BigNumber2)) - return new BigNumber2(v2, b4); - if (b4 == null) { - if (v2 && v2._isBigNumber === true) { - x3.s = v2.s; - if (!v2.c || v2.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (v2.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = v2.e; - x3.c = v2.c.slice(); - } - return; - } - if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { - x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; - if (v2 === ~~v2) { - for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x3.c = x3.e = null; - } else { - x3.e = e2; - x3.c = [v2]; - } - return; - } - str = String(v2); - } else { - if (!isNumeric.test(str = String(v2))) - return parseNumeric(x3, str, isNum); - x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i2 = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i2; - e2 += +str.slice(i2 + 1); - str = str.substring(0, i2); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck(b4, 2, ALPHABET.length, "Base"); - if (b4 == 10 && alphabetHasNormalDecimalDigits) { - x3 = new BigNumber2(v2); - return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); - } - str = String(v2); - if (isNum = typeof v2 == "number") { - if (v2 * 0 != 0) - return parseNumeric(x3, str, isNum, b4); - x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits + v2); - } - } else { - x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b4); - e2 = i2 = 0; - for (len = str.length; i2 < len; i2++) { - if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { - if (c4 == ".") { - if (i2 > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i2 = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x3, String(v2), isNum, b4); - } - } - isNum = false; - str = convertBase(str, b4, 10, x3.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i2 = 0; str.charCodeAt(i2) === 48; i2++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i2, ++len)) { - len -= i2; - if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) { - throw Error(tooManyDigits + x3.s * v2); - } - if ((e2 = e2 - i2 - 1) > MAX_EXP) { - x3.c = x3.e = null; - } else if (e2 < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = e2; - x3.c = []; - i2 = (e2 + 1) % LOG_BASE; - if (e2 < 0) - i2 += LOG_BASE; - if (i2 < len) { - if (i2) - x3.c.push(+str.slice(0, i2)); - for (len -= LOG_BASE; i2 < len; ) { - x3.c.push(+str.slice(i2, i2 += LOG_BASE)); - } - i2 = LOG_BASE - (str = str.slice(i2)).length; - } else { - i2 -= len; - } - for (; i2--; str += "0") - ; - x3.c.push(+str); - } - } else { - x3.c = [x3.e = 0]; - } - } - BigNumber2.clone = clone; - BigNumber2.ROUND_UP = 0; - BigNumber2.ROUND_DOWN = 1; - BigNumber2.ROUND_CEIL = 2; - BigNumber2.ROUND_FLOOR = 3; - BigNumber2.ROUND_HALF_UP = 4; - BigNumber2.ROUND_HALF_DOWN = 5; - BigNumber2.ROUND_HALF_EVEN = 6; - BigNumber2.ROUND_HALF_CEIL = 7; - BigNumber2.ROUND_HALF_FLOOR = 8; - BigNumber2.EUCLID = 9; - BigNumber2.config = BigNumber2.set = function(obj) { - var p3, v2; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { - v2 = obj[p3]; - intCheck(v2, 0, MAX, p3); - DECIMAL_PLACES = v2; - } - if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { - v2 = obj[p3]; - intCheck(v2, 0, 8, p3); - ROUNDING_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck(v2[0], -MAX, 0, p3); - intCheck(v2[1], 0, MAX, p3); - TO_EXP_NEG = v2[0]; - TO_EXP_POS = v2[1]; - } else { - intCheck(v2, -MAX, MAX, p3); - TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); - } - } - if (obj.hasOwnProperty(p3 = "RANGE")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck(v2[0], -MAX, -1, p3); - intCheck(v2[1], 1, MAX, p3); - MIN_EXP = v2[0]; - MAX_EXP = v2[1]; - } else { - intCheck(v2, -MAX, MAX, p3); - if (v2) { - MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); - } else { - throw Error(bignumberError + p3 + " cannot be zero: " + v2); - } - } - } - if (obj.hasOwnProperty(p3 = "CRYPTO")) { - v2 = obj[p3]; - if (v2 === !!v2) { - if (v2) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v2; - } else { - CRYPTO = !v2; - throw Error(bignumberError + "crypto unavailable"); - } - } else { - CRYPTO = v2; - } - } else { - throw Error(bignumberError + p3 + " not true or false: " + v2); - } - } - if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { - v2 = obj[p3]; - intCheck(v2, 0, 9, p3); - MODULO_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { - v2 = obj[p3]; - intCheck(v2, 0, MAX, p3); - POW_PRECISION = v2; - } - if (obj.hasOwnProperty(p3 = "FORMAT")) { - v2 = obj[p3]; - if (typeof v2 == "object") - FORMAT = v2; - else - throw Error(bignumberError + p3 + " not an object: " + v2); - } - if (obj.hasOwnProperty(p3 = "ALPHABET")) { - v2 = obj[p3]; - if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { - alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; - ALPHABET = v2; - } else { - throw Error(bignumberError + p3 + " invalid: " + v2); - } - } - } else { - throw Error(bignumberError + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber2.isBigNumber = function(v2) { - if (!v2 || v2._isBigNumber !== true) - return false; - if (!BigNumber2.DEBUG) - return true; - var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; - out: - if ({}.toString.call(c4) == "[object Array]") { - if ((s2 === 1 || s2 === -1) && e2 >= -MAX && e2 <= MAX && e2 === mathfloor(e2)) { - if (c4[0] === 0) { - if (e2 === 0 && c4.length === 1) - return true; - break out; - } - i2 = (e2 + 1) % LOG_BASE; - if (i2 < 1) - i2 += LOG_BASE; - if (String(c4[0]).length == i2) { - for (i2 = 0; i2 < c4.length; i2++) { - n3 = c4[i2]; - if (n3 < 0 || n3 >= BASE || n3 !== mathfloor(n3)) - break out; - } - if (n3 !== 0) - return true; - } - } - } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { - return true; - } - throw Error(bignumberError + "Invalid BigNumber: " + v2); - }; - BigNumber2.maximum = BigNumber2.max = function() { - return maxOrMin(arguments, -1); - }; - BigNumber2.minimum = BigNumber2.min = function() { - return maxOrMin(arguments, 1); - }; - BigNumber2.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber2(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck(dp, 0, MAX); - k4 = mathceil(dp / LOG_BASE); - if (CRYPTO) { - if (crypto.getRandomValues) { - a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); - for (; i2 < k4; ) { - v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); - if (v2 >= 9e15) { - b4 = crypto.getRandomValues(new Uint32Array(2)); - a3[i2] = b4[0]; - a3[i2 + 1] = b4[1]; - } else { - c4.push(v2 % 1e14); - i2 += 2; - } - } - i2 = k4 / 2; - } else if (crypto.randomBytes) { - a3 = crypto.randomBytes(k4 *= 7); - for (; i2 < k4; ) { - v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; - if (v2 >= 9e15) { - crypto.randomBytes(7).copy(a3, i2); - } else { - c4.push(v2 % 1e14); - i2 += 7; - } - } - i2 = k4 / 7; - } else { - CRYPTO = false; - throw Error(bignumberError + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (; i2 < k4; ) { - v2 = random53bitInt(); - if (v2 < 9e15) - c4[i2++] = v2 % 1e14; - } - } - k4 = c4[--i2]; - dp %= LOG_BASE; - if (k4 && dp) { - v2 = POWS_TEN[LOG_BASE - dp]; - c4[i2] = mathfloor(k4 / v2) * v2; - } - for (; c4[i2] === 0; c4.pop(), i2--) - ; - if (i2 < 0) { - c4 = [e2 = 0]; - } else { - for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE) - ; - for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) - ; - if (i2 < LOG_BASE) - e2 -= LOG_BASE - i2; - } - rand.e = e2; - rand.c = c4; - return rand; - }; - }(); - BigNumber2.sum = function() { - var i2 = 1, args = arguments, sum = new BigNumber2(args[0]); - for (; i2 < args.length; ) - sum = sum.plus(args[i2++]); - return sum; - }; - convertBase = /* @__PURE__ */ function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j2, arr = [0], arrL, i2 = 0, len = str.length; - for (; i2 < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i2++)); - for (j2 = 0; j2 < arr.length; j2++) { - if (arr[j2] > baseOut - 1) { - if (arr[j2 + 1] == null) - arr[j2 + 1] = 0; - arr[j2 + 1] += arr[j2] / baseOut | 0; - arr[j2] %= baseOut; - } - } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign2, callerIsToString) { - var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i2 >= 0) { - k4 = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y4 = new BigNumber2(baseIn); - x3 = y4.pow(str.length - i2); - POW_PRECISION = k4; - y4.c = toBaseOut( - toFixedPoint(coeffToString(x3.c), x3.e, "0"), - 10, - baseOut, - decimal - ); - y4.e = y4.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k4 = xc.length; - for (; xc[--k4] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i2 < 0) { - --e2; - } else { - x3.c = xc; - x3.e = e2; - x3.s = sign2; - x3 = div(x3, y4, dp, rm, baseOut); - xc = x3.c; - r = x3.r; - e2 = x3.e; - } - d3 = e2 + dp + 1; - i2 = xc[d3]; - k4 = baseOut / 2; - r = r || d3 < 0 || xc[d3 + 1] != null; - r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (d3 < 1 || !xc[0]) { - str = r ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d3; - if (r) { - for (--baseOut; ++xc[--d3] > baseOut; ) { - xc[d3] = 0; - if (!d3) { - ++e2; - xc = [1].concat(xc); - } - } - } - for (k4 = xc.length; !xc[--k4]; ) - ; - for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) - ; - str = toFixedPoint(str, e2, alphabet2.charAt(0)); - } - return str; - }; - }(); - div = /* @__PURE__ */ function() { - function multiply(x3, k4, base3) { - var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE, khi = k4 / SQRT_BASE | 0; - for (x3 = x3.slice(); i2--; ) { - xlo = x3[i2] % SQRT_BASE; - xhi = x3[i2] / SQRT_BASE | 0; - m3 = khi * xlo + xhi * klo; - temp = klo * xlo + m3 % SQRT_BASE * SQRT_BASE + carry; - carry = (temp / base3 | 0) + (m3 / SQRT_BASE | 0) + khi * xhi; - x3[i2] = temp % base3; - } - if (carry) - x3 = [carry].concat(x3); - return x3; - } - function compare3(a3, b4, aL, bL) { - var i2, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i2 = cmp = 0; i2 < aL; i2++) { - if (a3[i2] != b4[i2]) { - cmp = a3[i2] > b4[i2] ? 1 : -1; - break; - } - } - } - return cmp; - } - function subtract(a3, b4, aL, base3) { - var i2 = 0; - for (; aL--; ) { - a3[aL] -= i2; - i2 = a3[aL] < b4[aL] ? 1 : 0; - a3[aL] = i2 * base3 + a3[aL] - b4[aL]; - } - for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) - ; - } - return function(x3, y4, dp, rm, base3) { - var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber2( - // Return NaN if either NaN, or both Infinity or 0. - !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 - ) - ); - } - q2 = new BigNumber2(s2); - qc = q2.c = []; - e2 = x3.e - y4.e; - s2 = dp + e2 + 1; - if (!base3) { - base3 = BASE; - e2 = bitFloor(x3.e / LOG_BASE) - bitFloor(y4.e / LOG_BASE); - s2 = s2 / LOG_BASE | 0; - } - for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) - ; - if (yc[i2] > (xc[i2] || 0)) - e2--; - if (s2 < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i2 = 0; - s2 += 2; - n3 = mathfloor(base3 / (yc[0] + 1)); - if (n3 > 1) { - yc = multiply(yc, n3, base3); - xc = multiply(xc, n3, base3); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base3 / 2) - yc0++; - do { - n3 = 0; - cmp = compare3(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base3 + (rem[1] || 0); - n3 = mathfloor(rem0 / yc0); - if (n3 > 1) { - if (n3 >= base3) - n3 = base3 - 1; - prod = multiply(yc, n3, base3); - prodL = prod.length; - remL = rem.length; - while (compare3(prod, rem, prodL, remL) == 1) { - n3--; - subtract(prod, yL < prodL ? yz : yc, prodL, base3); - prodL = prod.length; - cmp = 1; - } - } else { - if (n3 == 0) { - cmp = n3 = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base3); - remL = rem.length; - if (cmp == -1) { - while (compare3(yc, rem, yL, remL) < 1) { - n3++; - subtract(rem, yL < remL ? yz : yc, remL, base3); - remL = rem.length; - } - } - } else if (cmp === 0) { - n3++; - rem = [0]; - } - qc[i2++] = n3; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s2--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base3 == BASE) { - for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) - ; - round(q2, dp + (q2.e = i2 + e2 * LOG_BASE - 1) + 1, rm, more); - } else { - q2.e = e2; - q2.r = +more; - } - return q2; - }; - }(); - function format(n3, i2, rm, id) { - var c0, e2, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - if (!n3.c) - return n3.toString(); - c0 = n3.c[0]; - ne = n3.e; - if (i2 == null) { - str = coeffToString(n3.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0"); - } else { - n3 = round(new BigNumber2(n3), i2, rm); - e2 = n3.e; - str = coeffToString(n3.c); - len = str.length; - if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { - for (; len < i2; str += "0", len++) - ; - str = toExponential(str, e2); - } else { - i2 -= ne; - str = toFixedPoint(str, e2, "0"); - if (e2 + 1 > len) { - if (--i2 > 0) - for (str += "."; i2--; str += "0") - ; - } else { - i2 += e2 - len; - if (i2 > 0) { - if (e2 + 1 == len) - str += "."; - for (; i2--; str += "0") - ; - } - } - } - } - return n3.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, n3) { - var k4, y4, i2 = 1, x3 = new BigNumber2(args[0]); - for (; i2 < args.length; i2++) { - y4 = new BigNumber2(args[i2]); - if (!y4.s || (k4 = compare2(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { - x3 = y4; - } - } - return x3; - } - function normalise(n3, c4, e2) { - var i2 = 1, j2 = c4.length; - for (; !c4[--j2]; c4.pop()) - ; - for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) - ; - if ((e2 = i2 + e2 * LOG_BASE - 1) > MAX_EXP) { - n3.c = n3.e = null; - } else if (e2 < MIN_EXP) { - n3.c = [n3.e = 0]; - } else { - n3.e = e2; - n3.c = c4; - } - return n3; - } - parseNumeric = /* @__PURE__ */ function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x3, str, isNum, b4) { - var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s2)) { - x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; - } else { - if (!isNum) { - s2 = s2.replace(basePrefix, function(m3, p1, p22) { - base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; - return !b4 || b4 == base3 ? p1 : m3; - }); - if (b4) { - base3 = b4; - s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s2) - return new BigNumber2(s2, base3); - } - if (BigNumber2.DEBUG) { - throw Error(bignumberError + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); - } - x3.s = null; - } - x3.c = x3.e = null; - }; - }(); - function round(x3, sd, rm, r) { - var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN; - if (xc) { - out: { - for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) - ; - i2 = sd - d3; - if (i2 < 0) { - i2 += LOG_BASE; - j2 = sd; - n3 = xc[ni = 0]; - rd = mathfloor(n3 / pows10[d3 - j2 - 1] % 10); - } else { - ni = mathceil((i2 + 1) / LOG_BASE); - if (ni >= xc.length) { - if (r) { - for (; xc.length <= ni; xc.push(0)) - ; - n3 = rd = 0; - d3 = 1; - i2 %= LOG_BASE; - j2 = i2 - LOG_BASE + 1; - } else { - break out; - } - } else { - n3 = k4 = xc[ni]; - for (d3 = 1; k4 >= 10; k4 /= 10, d3++) - ; - i2 %= LOG_BASE; - j2 = i2 - LOG_BASE + d3; - rd = j2 < 0 ? 0 : mathfloor(n3 / pows10[d3 - j2 - 1] % 10); - } - } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x3.e + 1; - xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; - x3.e = -sd || 0; - } else { - xc[0] = x3.e = 0; - } - return x3; - } - if (i2 == 0) { - xc.length = ni; - k4 = 1; - ni--; - } else { - xc.length = ni + 1; - k4 = pows10[LOG_BASE - i2]; - xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; - } - if (r) { - for (; ; ) { - if (ni == 0) { - for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) - ; - j2 = xc[0] += k4; - for (k4 = 1; j2 >= 10; j2 /= 10, k4++) - ; - if (i2 != k4) { - x3.e++; - if (xc[0] == BASE) - xc[0] = 1; - } - break; - } else { - xc[ni] += k4; - if (xc[ni] != BASE) - break; - xc[ni--] = 0; - k4 = 1; - } - } - } - for (i2 = xc.length; xc[--i2] === 0; xc.pop()) - ; - } - if (x3.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (x3.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } - } - return x3; - } - function valueOf(n3) { - var str, e2 = n3.e; - if (e2 === null) - return n3.toString(); - str = coeffToString(n3.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); - return n3.s < 0 ? "-" + str : str; - } - P2.absoluteValue = P2.abs = function() { - var x3 = new BigNumber2(this); - if (x3.s < 0) - x3.s = 1; - return x3; - }; - P2.comparedTo = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)); - }; - P2.decimalPlaces = P2.dp = function(dp, rm) { - var c4, n3, v2, x3 = this; - if (dp != null) { - intCheck(dp, 0, MAX); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - return round(new BigNumber2(x3), dp + x3.e + 1, rm); - } - if (!(c4 = x3.c)) - return null; - n3 = ((v2 = c4.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; - if (v2 = c4[v2]) - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - if (n3 < 0) - n3 = 0; - return n3; - }; - P2.dividedBy = P2.div = function(y4, b4) { - return div(this, new BigNumber2(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); - }; - P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { - return div(this, new BigNumber2(y4, b4), 0, 1); - }; - P2.exponentiatedBy = P2.pow = function(n3, m3) { - var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; - n3 = new BigNumber2(n3); - if (n3.c && !n3.isInteger()) { - throw Error(bignumberError + "Exponent not an integer: " + valueOf(n3)); - } - if (m3 != null) - m3 = new BigNumber2(m3); - nIsBig = n3.e > 14; - if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { - y4 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd(n3)) : +valueOf(n3))); - return m3 ? y4.mod(m3) : y4; - } - nIsNeg = n3.s < 0; - if (m3) { - if (m3.c ? !m3.c[0] : !m3.s) - return new BigNumber2(NaN); - isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); - if (isModExp) - x3 = x3.mod(m3); - } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { - k4 = x3.s < 0 && isOdd(n3) ? -0 : 0; - if (x3.e > -1) - k4 = 1 / k4; - return new BigNumber2(nIsNeg ? 1 / k4 : k4); - } else if (POW_PRECISION) { - k4 = mathceil(POW_PRECISION / LOG_BASE + 2); - } - if (nIsBig) { - half = new BigNumber2(0.5); - if (nIsNeg) - n3.s = 1; - nIsOdd = isOdd(n3); - } else { - i2 = Math.abs(+valueOf(n3)); - nIsOdd = i2 % 2; - } - y4 = new BigNumber2(ONE); - for (; ; ) { - if (nIsOdd) { - y4 = y4.times(x3); - if (!y4.c) - break; - if (k4) { - if (y4.c.length > k4) - y4.c.length = k4; - } else if (isModExp) { - y4 = y4.mod(m3); - } - } - if (i2) { - i2 = mathfloor(i2 / 2); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } else { - n3 = n3.times(half); - round(n3, n3.e + 1, 1); - if (n3.e > 14) { - nIsOdd = isOdd(n3); - } else { - i2 = +valueOf(n3); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } - } - x3 = x3.times(x3); - if (k4) { - if (x3.c && x3.c.length > k4) - x3.c.length = k4; - } else if (isModExp) { - x3 = x3.mod(m3); - } - } - if (isModExp) - return y4; - if (nIsNeg) - y4 = ONE.div(y4); - return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; - }; - P2.integerValue = function(rm) { - var n3 = new BigNumber2(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - return round(n3, n3.e + 1, rm); - }; - P2.isEqualTo = P2.eq = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)) === 0; - }; - P2.isFinite = function() { - return !!this.c; - }; - P2.isGreaterThan = P2.gt = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)) > 0; - }; - P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { - return (b4 = compare2(this, new BigNumber2(y4, b4))) === 1 || b4 === 0; - }; - P2.isInteger = function() { - return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; - }; - P2.isLessThan = P2.lt = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)) < 0; - }; - P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { - return (b4 = compare2(this, new BigNumber2(y4, b4))) === -1 || b4 === 0; - }; - P2.isNaN = function() { - return !this.s; - }; - P2.isNegative = function() { - return this.s < 0; - }; - P2.isPositive = function() { - return this.s > 0; - }; - P2.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P2.minus = function(y4, b4) { - var i2, j2, t, xLTy, x3 = this, a3 = x3.s; - y4 = new BigNumber2(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber2(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.plus(y4); - } - var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y4.s = -b4, y4) : new BigNumber2(yc ? x3 : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y4.s = -b4, y4) : new BigNumber2(xc[0] ? x3 : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); - } - } - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (xLTy = a3 < 0) { - a3 = -a3; - t = xc; - } else { - ye = xe; - t = yc; - } - t.reverse(); - for (b4 = a3; b4--; t.push(0)) - ; - t.reverse(); - } else { - j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; - for (a3 = b4 = 0; b4 < j2; b4++) { - if (xc[b4] != yc[b4]) { - xLTy = xc[b4] < yc[b4]; - break; - } - } - } - if (xLTy) { - t = xc; - xc = yc; - yc = t; - y4.s = -y4.s; - } - b4 = (j2 = yc.length) - (i2 = xc.length); - if (b4 > 0) - for (; b4--; xc[i2++] = 0) - ; - b4 = BASE - 1; - for (; j2 > a3; ) { - if (xc[--j2] < yc[j2]) { - for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) - ; - --xc[i2]; - xc[j2] += BASE; - } - xc[j2] -= yc[j2]; - } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y4.s = ROUNDING_MODE == 3 ? -1 : 1; - y4.c = [y4.e = 0]; - return y4; - } - return normalise(y4, xc, ye); - }; - P2.modulo = P2.mod = function(y4, b4) { - var q2, s2, x3 = this; - y4 = new BigNumber2(y4, b4); - if (!x3.c || !y4.s || y4.c && !y4.c[0]) { - return new BigNumber2(NaN); - } else if (!y4.c || x3.c && !x3.c[0]) { - return new BigNumber2(x3); - } - if (MODULO_MODE == 9) { - s2 = y4.s; - y4.s = 1; - q2 = div(x3, y4, 0, 3); - y4.s = s2; - q2.s *= s2; - } else { - q2 = div(x3, y4, 0, MODULO_MODE); - } - y4 = x3.minus(q2.times(y4)); - if (!y4.c[0] && MODULO_MODE == 1) - y4.s = x3.s; - return y4; - }; - P2.multipliedBy = P2.times = function(y4, b4) { - var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber2(y4, b4)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y4.c = y4.e = y4.s = null; - } else { - y4.s *= x3.s; - if (!xc || !yc) { - y4.c = y4.e = null; - } else { - y4.c = [0]; - y4.e = 0; - } - } - return y4; - } - e2 = bitFloor(x3.e / LOG_BASE) + bitFloor(y4.e / LOG_BASE); - y4.s *= x3.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) { - zc = xc; - xc = yc; - yc = zc; - i2 = xcL; - xcL = ycL; - ycL = i2; - } - for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) - ; - base3 = BASE; - sqrtBase = SQRT_BASE; - for (i2 = ycL; --i2 >= 0; ) { - c4 = 0; - ylo = yc[i2] % sqrtBase; - yhi = yc[i2] / sqrtBase | 0; - for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { - xlo = xc[--k4] % sqrtBase; - xhi = xc[k4] / sqrtBase | 0; - m3 = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; - c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; - zc[j2--] = xlo % base3; - } - zc[j2] = c4; - } - if (c4) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y4, zc, e2); - }; - P2.negated = function() { - var x3 = new BigNumber2(this); - x3.s = -x3.s || null; - return x3; - }; - P2.plus = function(y4, b4) { - var t, x3 = this, a3 = x3.s; - y4 = new BigNumber2(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber2(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.minus(y4); - } - var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber2(a3 / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y4 : new BigNumber2(xc[0] ? x3 : a3 * 0); - } - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (a3 > 0) { - ye = xe; - t = yc; - } else { - a3 = -a3; - t = xc; - } - t.reverse(); - for (; a3--; t.push(0)) - ; - t.reverse(); - } - a3 = xc.length; - b4 = yc.length; - if (a3 - b4 < 0) { - t = yc; - yc = xc; - xc = t; - b4 = a3; - } - for (a3 = 0; b4; ) { - a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE | 0; - xc[b4] = BASE === xc[b4] ? 0 : xc[b4] % BASE; - } - if (a3) { - xc = [a3].concat(xc); - ++ye; - } - return normalise(y4, xc, ye); - }; - P2.precision = P2.sd = function(sd, rm) { - var c4, n3, v2, x3 = this; - if (sd != null && sd !== !!sd) { - intCheck(sd, 1, MAX); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - return round(new BigNumber2(x3), sd, rm); - } - if (!(c4 = x3.c)) - return null; - v2 = c4.length - 1; - n3 = v2 * LOG_BASE + 1; - if (v2 = c4[v2]) { - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) - ; - } - if (sd && x3.e + 1 > n3) - n3 = x3.e + 1; - return n3; - }; - P2.shiftedBy = function(k4) { - intCheck(k4, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); - return this.times("1e" + k4); - }; - P2.squareRoot = P2.sqrt = function() { - var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); - if (s2 !== 1 || !c4 || !c4[0]) { - return new BigNumber2(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); - } - s2 = Math.sqrt(+valueOf(x3)); - if (s2 == 0 || s2 == 1 / 0) { - n3 = coeffToString(c4); - if ((n3.length + e2) % 2 == 0) - n3 += "0"; - s2 = Math.sqrt(+n3); - e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s2 == 1 / 0) { - n3 = "5e" + e2; - } else { - n3 = s2.toExponential(); - n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; - } - r = new BigNumber2(n3); - } else { - r = new BigNumber2(s2 + ""); - } - if (r.c[0]) { - e2 = r.e; - s2 = e2 + dp; - if (s2 < 3) - s2 = 0; - for (; ; ) { - t = r; - r = half.times(t.plus(div(x3, t, dp, 1))); - if (coeffToString(t.c).slice(0, s2) === (n3 = coeffToString(r.c)).slice(0, s2)) { - if (r.e < e2) - --s2; - n3 = n3.slice(s2 - 3, s2 + 1); - if (n3 == "9999" || !rep && n3 == "4999") { - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - if (t.times(t).eq(x3)) { - r = t; - break; - } - } - dp += 4; - s2 += 4; - rep = 1; - } else { - if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m3 = !r.times(r).eq(x3); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); - }; - P2.toExponential = function(dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp++; - } - return format(this, dp, rm, 1); - }; - P2.toFixed = function(dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P2.toFormat = function(dp, rm, format2) { - var str, x3 = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError + "Argument not an object: " + format2); - } - str = x3.toFixed(dp, rm); - if (x3.c) { - var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g22) { - i2 = g1; - g1 = g22; - g22 = i2; - len -= i2; - } - if (g1 > 0 && len > 0) { - i2 = len % g1 || g1; - intPart = intDigits.substr(0, i2); - for (; i2 < len; i2 += g1) - intPart += groupSeparator + intDigits.substr(i2, g1); - if (g22 > 0) - intPart += groupSeparator + intDigits.slice(i2); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g22 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P2.toFraction = function(md) { - var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; - if (md != null) { - n3 = new BigNumber2(md); - if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { - throw Error(bignumberError + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); - } - } - if (!xc) - return new BigNumber2(x3); - d3 = new BigNumber2(ONE); - n1 = d0 = new BigNumber2(ONE); - d1 = n0 = new BigNumber2(ONE); - s2 = coeffToString(xc); - e2 = d3.e = s2.length - x3.e - 1; - d3.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; - md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n3 = new BigNumber2(s2); - n0.c[0] = 0; - for (; ; ) { - q2 = div(n3, d3, 0, 1); - d22 = d0.plus(q2.times(d1)); - if (d22.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d22; - n1 = n0.plus(q2.times(d22 = n1)); - n0 = d22; - d3 = n3.minus(q2.times(d22 = d3)); - n3 = d22; - } - d22 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d22.times(n1)); - d0 = d0.plus(d22.times(d1)); - n0.s = n1.s = x3.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( - div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() - ) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P2.toNumber = function() { - return +valueOf(this); - }; - P2.toPrecision = function(sd, rm) { - if (sd != null) - intCheck(sd, 1, MAX); - return format(this, sd, rm, 2); - }; - P2.toString = function(b4) { - var str, n3 = this, s2 = n3.s, e2 = n3.e; - if (e2 === null) { - if (s2) { - str = "Infinity"; - if (s2 < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b4 == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n3.c), e2) : toFixedPoint(coeffToString(n3.c), e2, "0"); - } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { - n3 = round(new BigNumber2(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n3.c), n3.e, "0"); - } else { - intCheck(b4, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint(coeffToString(n3.c), e2, "0"), 10, b4, s2, true); - } - if (s2 < 0 && n3.c[0]) - str = "-" + str; - } - return str; - }; - P2.valueOf = P2.toJSON = function() { - return valueOf(this); - }; - P2._isBigNumber = true; - P2[Symbol.toStringTag] = "BigNumber"; - P2[Symbol.for("nodejs.util.inspect.custom")] = P2.valueOf; - if (configObject != null) - BigNumber2.set(configObject); - return BigNumber2; -} -function bitFloor(n3) { - var i2 = n3 | 0; - return n3 > 0 || n3 === i2 ? i2 : i2 - 1; -} -function coeffToString(a3) { - var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; - for (; i2 < j2; ) { - s2 = a3[i2++] + ""; - z3 = LOG_BASE - s2.length; - for (; z3--; s2 = "0" + s2) - ; - r += s2; - } - for (j2 = r.length; r.charCodeAt(--j2) === 48; ) - ; - return r.slice(0, j2 + 1 || 1); -} -function compare2(x3, y4) { - var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; - if (!i2 || !j2) - return null; - a3 = xc && !xc[0]; - b4 = yc && !yc[0]; - if (a3 || b4) - return a3 ? b4 ? 0 : -j2 : i2; - if (i2 != j2) - return i2; - a3 = i2 < 0; - b4 = k4 == l4; - if (!xc || !yc) - return b4 ? 0 : !xc ^ a3 ? 1 : -1; - if (!b4) - return k4 > l4 ^ a3 ? 1 : -1; - j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; - for (i2 = 0; i2 < j2; i2++) - if (xc[i2] != yc[i2]) - return xc[i2] > yc[i2] ^ a3 ? 1 : -1; - return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; -} -function intCheck(n3, min, max, name2) { - if (n3 < min || n3 > max || n3 !== mathfloor(n3)) { - throw Error(bignumberError + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); - } -} -function isOdd(n3) { - var k4 = n3.c.length - 1; - return bitFloor(n3.e / LOG_BASE) == k4 && n3.c[k4] % 2 != 0; -} -function toExponential(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; -} -function toFixedPoint(str, e2, z3) { - var len, zs; - if (e2 < 0) { - for (zs = z3 + "."; ++e2; zs += z3) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z3, e2 -= len; --e2; zs += z3) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } - } - return str; -} -var BigNumber = clone(); -var bignumber_default = BigNumber; - -// src/utils/amount.ts -bignumber_default.config({ ROUNDING_MODE: bignumber_default.ROUND_FLOOR }); -var parseAmount = ({ - amount, - decimals -}) => { - if (decimals < 0) - throw new Error("Decimal places shouldn't be negative number!"); - return BigInt(new bignumber_default(amount).shiftedBy(decimals).toFixed()); -}; -var formatAmount = ({ - amount, - decimals, - rounding = decimals -}) => { - if (decimals < 0) - throw new Error("Decimal places shouldn't be negative number!"); - return new bignumber_default(amount).shiftedBy(-decimals).decimalPlaces(rounding).toFixed(); -}; -var export_Account = import_account4.Account; -var export_Address = import_address4.Address; -var export_AddressType = import_address5.AddressType; -var export_AddressValue = import_address5.AddressValue; -var export_BigUIntType = import_numerical.BigUIntType; -var export_BigUIntValue = import_numerical.BigUIntValue; -var export_BooleanType = import_boolean.BooleanType; -var export_BooleanValue = import_boolean.BooleanValue; -var export_BytesType = import_bytes7.BytesType; -var export_BytesValue = import_bytes7.BytesValue; -var export_ContractQueryResponse = import_contractQueryResponse2.ContractQueryResponse; -var export_Message = import_message.Message; -var export_MessageComputer = import_message.MessageComputer; -var export_QueryArguments = import_interface.QueryArguments; -var export_SignableMessage = import_signableMessage2.SignableMessage; -var export_SmartContractTransactionsFactory = import_transactionsFactories.SmartContractTransactionsFactory; -var export_SmartContractTransactionsOutcomeParser = import_transactionsOutcomeParsers.SmartContractTransactionsOutcomeParser; -var export_Token = import_tokens.Token; -var export_TokenComputer = import_tokens.TokenComputer; -var export_TokenManagementTransactionsFactory = import_transactionsFactories.TokenManagementTransactionsFactory; -var export_TokenManagementTransactionsOutcomeParser = import_transactionsOutcomeParsers.TokenManagementTransactionsOutcomeParser; -var export_TokenOperationsFactory = import_tokenOperations.TokenOperationsFactory; -var export_TokenOperationsFactoryConfig = import_tokenOperations.TokenOperationsFactoryConfig; -var export_TokenOperationsOutcomeParser = import_tokenOperations.TokenOperationsOutcomeParser; -var export_TokenTransfer = import_tokens.TokenTransfer; -var export_Transaction = import_transaction3.Transaction; -var export_TransactionComputer = import_transactionComputer.TransactionComputer; -var export_TransactionEventsParser = import_transactionsOutcomeParsers.TransactionEventsParser; -var export_TransactionWatcher = import_transactionWatcher2.TransactionWatcher; -var export_TransactionsFactoryConfig = import_transactionsFactories.TransactionsFactoryConfig; -var export_TransferTransactionsFactory = import_transactionsFactories.TransferTransactionsFactory; -var export_U16Type = import_numerical.U16Type; -var export_U16Value = import_numerical.U16Value; -var export_U32Type = import_numerical.U32Type; -var export_U32Value = import_numerical.U32Value; -var export_U64Type = import_numerical.U64Type; -var export_U64Value = import_numerical.U64Value; -var export_U8Type = import_numerical.U8Type; -var export_U8Value = import_numerical.U8Value; -export { - export_Account as Account, - export_Address as Address, - export_AddressType as AddressType, - export_AddressValue as AddressValue, - export_BigUIntType as BigUIntType, - export_BigUIntValue as BigUIntValue, - export_BooleanType as BooleanType, - export_BooleanValue as BooleanValue, - export_BytesType as BytesType, - export_BytesValue as BytesValue, - export_ContractQueryResponse as ContractQueryResponse, - DappCoreWCV2CustomMethodsEnum, - ElvenJS, - EventStoreEvents, - LoginMethodsEnum, - export_Message as Message, - export_MessageComputer as MessageComputer, - export_QueryArguments as QueryArguments, - export_SignableMessage as SignableMessage, - export_SmartContractTransactionsFactory as SmartContractTransactionsFactory, - export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser, - export_Token as Token, - export_TokenComputer as TokenComputer, - export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory, - export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser, - export_TokenOperationsFactory as TokenOperationsFactory, - export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig, - export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser, - export_TokenTransfer as TokenTransfer, - export_Transaction as Transaction, - export_TransactionComputer as TransactionComputer, - export_TransactionEventsParser as TransactionEventsParser, - export_TransactionWatcher as TransactionWatcher, - export_TransactionsFactoryConfig as TransactionsFactoryConfig, - export_TransferTransactionsFactory as TransferTransactionsFactory, - export_U16Type as U16Type, - export_U16Value as U16Value, - export_U32Type as U32Type, - export_U32Value as U32Value, - export_U64Type as U64Type, - export_U64Value as U64Value, - export_U8Type as U8Type, - export_U8Value as U8Value, - WebWalletUrlParamsEnum, - formatAmount, - parseAmount -}; -/*! Bundled license information: +`});var YR=fe(()=>{h();$R();Tm();Lo();OI();Th()});var RI,abe,JR=fe(()=>{h();IR();TR();_R();CR();NR();EI();xR();II();OR();PR();kR();jR();zR();QR();YR();RI={...pI,...mI,...yI,...wI,...vI,...AI,...bI,...SI,...TI,..._I},abe={...DI,...PI}});function ZR(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var XR,BI,SZ,xm,MI=fe(()=>{h();JR();bm();XR=ZR("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),BI=ZR("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=jc(t.length);for(let r=0;r{h();MI()});function ns(t,e="utf8"){let r=xm[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var FI=fe(()=>{h();MI();Eh()});function Ch(t){return Ro(ks(ns(t,Hc),pm))}function Nh(t){return ks(ns(Ai(t),pm),Hc)}function UI(t){let e=ns(Am,Gc),r=vm+ks(Sm([e,t]),Gc);return[ym,wm,r].join(mm)}function qI(t){let[e,r,n]=t.split(mm);if(e!==ym||r!==wm)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==vm)throw new Error("Issuer must be a key in mulicodec format");let s=ns(n.slice(1),Gc);if(ks(s.slice(0,2),Gc)!==Am)throw new Error('Issuer must be a public key with type "Ed25519"');let u=s.slice(2);if(u.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return u}function eB(t){return ks(t,Hc)}function tB(t){return ns(t,Hc)}function VI(t){return ns([Nh(t.header),Nh(t.payload)].join(Ya),Ah)}function IZ(t){let e=ks(t,Ah).split(Ya),r=Ch(e[0]),n=Ch(e[1]);return{header:r,payload:n}}function kI(t){return[Nh(t.header),Nh(t.payload),eB(t.signature)].join(Ya)}function HI(t){let e=t.split(Ya),r=Ch(e[0]),n=Ch(e[1]),i=tB(e[2]),s=ns(e.slice(0,2).join(Ya),Ah);return{header:r,payload:n,signature:i,data:s}}var GI=fe(()=>{h();lI();LI();FI();xc();Em()});function TZ(t=(0,rB.randomBytes)(32)){return Yc.generateKeyPairFromSeed(t)}async function _Z(t,e,r,n,i=(0,nB.fromMiliseconds)(Date.now())){let s={alg:dm,typ:gm},o=UI(n.publicKey),u=i+r,a={iss:o,sub:t,aud:e,iat:i,exp:u},c=VI({header:s,payload:a}),f=Yc.sign(n.secretKey,c);return kI({header:s,payload:a,signature:f})}async function CZ(t){let{header:e,payload:r,data:n,signature:i}=HI(t);if(e.alg!==dm||e.typ!==gm)throw new Error("JWT must use EdDSA algorithm");let s=qI(r.iss);return Yc.verify(s,n,i)}var Yc,rB,nB,iB=fe(()=>{h();Yc=pe(gR()),rB=pe(yh()),nB=pe(Qa());Em();GI()});var sB=fe(()=>{h()});var oB={};Bt(oB,{DATA_ENCODING:()=>Ah,DID_DELIMITER:()=>mm,DID_METHOD:()=>wm,DID_PREFIX:()=>ym,JSON_ENCODING:()=>pm,JWT_DELIMITER:()=>Ya,JWT_ENCODING:()=>Hc,JWT_IRIDIUM_ALG:()=>dm,JWT_IRIDIUM_TYP:()=>gm,KEY_PAIR_SEED_LENGTH:()=>mR,MULTICODEC_ED25519_BASE:()=>vm,MULTICODEC_ED25519_ENCODING:()=>Gc,MULTICODEC_ED25519_HEADER:()=>Am,MULTICODEC_ED25519_LENGTH:()=>pR,decodeData:()=>IZ,decodeIss:()=>qI,decodeJSON:()=>Ch,decodeJWT:()=>HI,decodeSig:()=>tB,encodeData:()=>VI,encodeIss:()=>UI,encodeJSON:()=>Nh,encodeJWT:()=>kI,encodeSig:()=>eB,generateKeyPair:()=>TZ,signJWT:()=>_Z,verifyJWT:()=>CZ});var aB=fe(()=>{h();iB();Em();sB();GI()});var vB=B(qt=>{"use strict";h();var uB=qt&&qt.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new pB:typeof navigator<"u"?jI(navigator.userAgent):wB()}qt.detect=DZ;function mB(t){return t!==""&&OZ.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function PZ(t){var e=mB(t);return e?e[0]:null}qt.browserName=PZ;function jI(t){var e=mB(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new gB;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getLocalStorage=Ot.getLocalStorageOrThrow=Ot.getCrypto=Ot.getCryptoOrThrow=Ot.getLocation=Ot.getLocationOrThrow=Ot.getNavigator=Ot.getNavigatorOrThrow=Ot.getDocument=Ot.getDocumentOrThrow=Ot.getFromWindowOrThrow=Ot.getFromWindow=void 0;function Xa(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}Ot.getFromWindow=Xa;function Jc(t){let e=Xa(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}Ot.getFromWindowOrThrow=Jc;function BZ(){return Jc("document")}Ot.getDocumentOrThrow=BZ;function MZ(){return Xa("document")}Ot.getDocument=MZ;function LZ(){return Jc("navigator")}Ot.getNavigatorOrThrow=LZ;function FZ(){return Xa("navigator")}Ot.getNavigator=FZ;function UZ(){return Jc("location")}Ot.getLocationOrThrow=UZ;function qZ(){return Xa("location")}Ot.getLocation=qZ;function VZ(){return Jc("crypto")}Ot.getCryptoOrThrow=VZ;function kZ(){return Xa("crypto")}Ot.getCrypto=kZ;function HZ(){return Jc("localStorage")}Ot.getLocalStorageOrThrow=HZ;function GZ(){return Xa("localStorage")}Ot.getLocalStorage=GZ});var EB=B(Om=>{"use strict";h();Object.defineProperty(Om,"__esModule",{value:!0});Om.getWindowMetadata=void 0;var AB=zI();function jZ(){let t,e;try{t=AB.getDocumentOrThrow(),e=AB.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),w=[];for(let A=0;A-1){let R=T.getAttribute("href");if(R)if(R.toLowerCase().indexOf("https:")===-1&&R.toLowerCase().indexOf("http:")===-1&&R.indexOf("//")!==0){let V=e.protocol+"//"+e.host;if(R.indexOf("/")===0)V+=R;else{let U=e.pathname.split("/");U.pop();let Q=U.join("/");V+=Q+"/"+R}w.push(V)}else if(R.indexOf("//")===0){let V=e.protocol+R;w.push(V)}else w.push(R)}}return w}function n(...d){let w=t.getElementsByTagName("meta");for(let A=0;AT.getAttribute(R)).filter(R=>R?d.includes(R):!1);if(x.length&&x){let R=T.getAttribute("content");if(R)return R}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),u=s(),a=e.origin,c=r();return{description:u,url:a,icons:c,name:o}}Om.getWindowMetadata=jZ});var SB=B((jbe,bB)=>{"use strict";h();bB.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var NB=B((Qbe,CB)=>{"use strict";h();var _B="%[a-f0-9]{2}",IB=new RegExp("("+_B+")|([^%]+?)","gi"),TB=new RegExp("("+_B+")+","gi");function QI(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],QI(r),QI(n))}function zZ(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(IB)||[],r=1;r{"use strict";h();xB.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var PB=B((Ybe,DB)=>{"use strict";h();DB.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";h();var KZ=SB(),WZ=NB(),BB=OB(),$Z=PB(),YZ=t=>t==null,KI=Symbol("encodeFragmentIdentifier");function JZ(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[",i,"]"].join("")]:[...r,[Zt(e,t),"[",Zt(i,t),"]=",Zt(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[]"].join("")]:[...r,[Zt(e,t),"[]=",Zt(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),":list="].join("")]:[...r,[Zt(e,t),":list=",Zt(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[Zt(r,t),e,Zt(i,t)].join("")]:[[n,Zt(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,Zt(e,t)]:[...r,[Zt(e,t),"=",Zt(n,t)].join("")]}}function XZ(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&Hs(n,t).includes(t.arrayFormatSeparator);n=o?Hs(n,t):n;let u=s||o?n.split(t.arrayFormatSeparator).map(a=>Hs(a,t)):n===null?n:Hs(n,t);i[r]=u};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&Hs(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(u=>Hs(u,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function MB(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Zt(t,e){return e.encode?e.strict?KZ(t):encodeURIComponent(t):t}function Hs(t,e){return e.decode?WZ(t):t}function LB(t){return Array.isArray(t)?t.sort():typeof t=="object"?LB(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function FB(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function ZZ(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function UB(t){t=FB(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function RB(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function qB(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),MB(e.arrayFormatSeparator);let r=XZ(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=BB(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:Hs(o,e),r(Hs(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=RB(s[o],e);else n[i]=RB(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=LB(o):i[s]=o,i},Object.create(null))}nn.extract=UB;nn.parse=qB;nn.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),MB(e.arrayFormatSeparator);let r=o=>e.skipNull&&YZ(t[o])||e.skipEmptyString&&t[o]==="",n=JZ(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let u=t[o];return u===void 0?"":u===null?Zt(o,e):Array.isArray(u)?u.length===0&&e.arrayFormat==="bracket-separator"?Zt(o,e)+"[]":u.reduce(n(o),[]).join("&"):Zt(o,e)+"="+Zt(u,e)}).filter(o=>o.length>0).join("&")};nn.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=BB(t,"#");return Object.assign({url:r.split("?")[0]||"",query:qB(UB(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:Hs(n,e)}:{})};nn.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[KI]:!0},e);let r=FB(t.url).split("?")[0]||"",n=nn.extract(t.url),i=nn.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=nn.stringify(s,e);o&&(o=`?${o}`);let u=ZZ(t.url);return t.fragmentIdentifier&&(u=`#${e[KI]?Zt(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${u}`};nn.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[KI]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=nn.parseUrl(t,r);return nn.stringifyUrl({url:n,query:$Z(i,e),fragmentIdentifier:s},r)};nn.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return nn.pick(t,n,r)}});var HB=B(Dm=>{"use strict";h();Object.defineProperty(Dm,"__esModule",{value:!0});var Mr=Uc(),WI=Qn(),eee=20;function tee(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,u=r[3]<<24|r[2]<<16|r[1]<<8|r[0],a=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],w=r[23]<<24|r[22]<<16|r[21]<<8|r[20],A=r[27]<<24|r[26]<<16|r[25]<<8|r[24],T=r[31]<<24|r[30]<<16|r[29]<<8|r[28],x=e[3]<<24|e[2]<<16|e[1]<<8|e[0],R=e[7]<<24|e[6]<<16|e[5]<<8|e[4],V=e[11]<<24|e[10]<<16|e[9]<<8|e[8],U=e[15]<<24|e[14]<<16|e[13]<<8|e[12],Q=n,L=i,k=s,H=o,q=u,v=a,C=c,D=f,F=d,P=w,l=A,g=T,y=x,E=R,S=V,_=U,M=0;M>>16|y<<16,F=F+y|0,q^=F,q=q>>>20|q<<12,L=L+v|0,E^=L,E=E>>>16|E<<16,P=P+E|0,v^=P,v=v>>>20|v<<12,k=k+C|0,S^=k,S=S>>>16|S<<16,l=l+S|0,C^=l,C=C>>>20|C<<12,H=H+D|0,_^=H,_=_>>>16|_<<16,g=g+_|0,D^=g,D=D>>>20|D<<12,k=k+C|0,S^=k,S=S>>>24|S<<8,l=l+S|0,C^=l,C=C>>>25|C<<7,H=H+D|0,_^=H,_=_>>>24|_<<8,g=g+_|0,D^=g,D=D>>>25|D<<7,L=L+v|0,E^=L,E=E>>>24|E<<8,P=P+E|0,v^=P,v=v>>>25|v<<7,Q=Q+q|0,y^=Q,y=y>>>24|y<<8,F=F+y|0,q^=F,q=q>>>25|q<<7,Q=Q+v|0,_^=Q,_=_>>>16|_<<16,l=l+_|0,v^=l,v=v>>>20|v<<12,L=L+C|0,y^=L,y=y>>>16|y<<16,g=g+y|0,C^=g,C=C>>>20|C<<12,k=k+D|0,E^=k,E=E>>>16|E<<16,F=F+E|0,D^=F,D=D>>>20|D<<12,H=H+q|0,S^=H,S=S>>>16|S<<16,P=P+S|0,q^=P,q=q>>>20|q<<12,k=k+D|0,E^=k,E=E>>>24|E<<8,F=F+E|0,D^=F,D=D>>>25|D<<7,H=H+q|0,S^=H,S=S>>>24|S<<8,P=P+S|0,q^=P,q=q>>>25|q<<7,L=L+C|0,y^=L,y=y>>>24|y<<8,g=g+y|0,C^=g,C=C>>>25|C<<7,Q=Q+v|0,_^=Q,_=_>>>24|_<<8,l=l+_|0,v^=l,v=v>>>25|v<<7;Mr.writeUint32LE(Q+n|0,t,0),Mr.writeUint32LE(L+i|0,t,4),Mr.writeUint32LE(k+s|0,t,8),Mr.writeUint32LE(H+o|0,t,12),Mr.writeUint32LE(q+u|0,t,16),Mr.writeUint32LE(v+a|0,t,20),Mr.writeUint32LE(C+c|0,t,24),Mr.writeUint32LE(D+f|0,t,28),Mr.writeUint32LE(F+d|0,t,32),Mr.writeUint32LE(P+w|0,t,36),Mr.writeUint32LE(l+A|0,t,40),Mr.writeUint32LE(g+T|0,t,44),Mr.writeUint32LE(y+x|0,t,48),Mr.writeUint32LE(E+R|0,t,52),Mr.writeUint32LE(S+V|0,t,56),Mr.writeUint32LE(_+U|0,t,60)}function kB(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Pm=B(Xc=>{"use strict";h();Object.defineProperty(Xc,"__esModule",{value:!0});function iee(t,e,r){return~(t-1)&e|t-1&r}Xc.select=iee;function see(t,e){return(t|0)-(e|0)-1>>>31&1}Xc.lessOrEqual=see;function GB(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xc.compare=GB;function oee(t,e){return t.length===0||e.length===0?!1:GB(t,e)!==0}Xc.equal=oee});var zB=B(Gs=>{"use strict";h();Object.defineProperty(Gs,"__esModule",{value:!0});var aee=Pm(),Rm=Qn();Gs.DIGEST_LENGTH=16;var jB=function(){function t(e){this.digestLength=Gs.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var u=e[10]|e[11]<<8;this._r[6]=(o>>>14|u<<2)&8191;var a=e[12]|e[13]<<8;this._r[7]=(u>>>11|a<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(a>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],u=this._h[2],a=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],w=this._h[7],A=this._h[8],T=this._h[9],x=this._r[0],R=this._r[1],V=this._r[2],U=this._r[3],Q=this._r[4],L=this._r[5],k=this._r[6],H=this._r[7],q=this._r[8],v=this._r[9];n>=16;){var C=e[r+0]|e[r+1]<<8;s+=C&8191;var D=e[r+2]|e[r+3]<<8;o+=(C>>>13|D<<3)&8191;var F=e[r+4]|e[r+5]<<8;u+=(D>>>10|F<<6)&8191;var P=e[r+6]|e[r+7]<<8;a+=(F>>>7|P<<9)&8191;var l=e[r+8]|e[r+9]<<8;c+=(P>>>4|l<<12)&8191,f+=l>>>1&8191;var g=e[r+10]|e[r+11]<<8;d+=(l>>>14|g<<2)&8191;var y=e[r+12]|e[r+13]<<8;w+=(g>>>11|y<<5)&8191;var E=e[r+14]|e[r+15]<<8;A+=(y>>>8|E<<8)&8191,T+=E>>>5|i;var S=0,_=S;_+=s*x,_+=o*(5*v),_+=u*(5*q),_+=a*(5*H),_+=c*(5*k),S=_>>>13,_&=8191,_+=f*(5*L),_+=d*(5*Q),_+=w*(5*U),_+=A*(5*V),_+=T*(5*R),S+=_>>>13,_&=8191;var M=S;M+=s*R,M+=o*x,M+=u*(5*v),M+=a*(5*q),M+=c*(5*H),S=M>>>13,M&=8191,M+=f*(5*k),M+=d*(5*L),M+=w*(5*Q),M+=A*(5*U),M+=T*(5*V),S+=M>>>13,M&=8191;var N=S;N+=s*V,N+=o*R,N+=u*x,N+=a*(5*v),N+=c*(5*q),S=N>>>13,N&=8191,N+=f*(5*H),N+=d*(5*k),N+=w*(5*L),N+=A*(5*Q),N+=T*(5*U),S+=N>>>13,N&=8191;var m=S;m+=s*U,m+=o*V,m+=u*R,m+=a*x,m+=c*(5*v),S=m>>>13,m&=8191,m+=f*(5*q),m+=d*(5*H),m+=w*(5*k),m+=A*(5*L),m+=T*(5*Q),S+=m>>>13,m&=8191;var O=S;O+=s*Q,O+=o*U,O+=u*V,O+=a*R,O+=c*x,S=O>>>13,O&=8191,O+=f*(5*v),O+=d*(5*q),O+=w*(5*H),O+=A*(5*k),O+=T*(5*L),S+=O>>>13,O&=8191;var Y=S;Y+=s*L,Y+=o*Q,Y+=u*U,Y+=a*V,Y+=c*R,S=Y>>>13,Y&=8191,Y+=f*x,Y+=d*(5*v),Y+=w*(5*q),Y+=A*(5*H),Y+=T*(5*k),S+=Y>>>13,Y&=8191;var $=S;$+=s*k,$+=o*L,$+=u*Q,$+=a*U,$+=c*V,S=$>>>13,$&=8191,$+=f*R,$+=d*x,$+=w*(5*v),$+=A*(5*q),$+=T*(5*H),S+=$>>>13,$&=8191;var b=S;b+=s*H,b+=o*k,b+=u*L,b+=a*Q,b+=c*U,S=b>>>13,b&=8191,b+=f*V,b+=d*R,b+=w*x,b+=A*(5*v),b+=T*(5*q),S+=b>>>13,b&=8191;var j=S;j+=s*q,j+=o*H,j+=u*k,j+=a*L,j+=c*Q,S=j>>>13,j&=8191,j+=f*U,j+=d*V,j+=w*R,j+=A*x,j+=T*(5*v),S+=j>>>13,j&=8191;var z=S;z+=s*v,z+=o*q,z+=u*H,z+=a*k,z+=c*L,S=z>>>13,z&=8191,z+=f*Q,z+=d*U,z+=w*V,z+=A*R,z+=T*x,S+=z>>>13,z&=8191,S=(S<<2)+S|0,S=S+_|0,_=S&8191,S=S>>>13,M+=S,s=_,o=M,u=N,a=m,c=O,f=Y,d=$,w=b,A=j,T=z,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=u,this._h[3]=a,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=w,this._h[8]=A,this._h[9]=T},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,u;if(this._leftover){for(u=this._leftover,this._buffer[u++]=1;u<16;u++)this._buffer[u]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,u=2;u<10;u++)this._h[u]+=i,i=this._h[u]>>>13,this._h[u]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,u=1;u<10;u++)n[u]=this._h[u]+i,i=n[u]>>>13,n[u]&=8191;for(n[9]-=8192,s=(i^1)-1,u=0;u<10;u++)n[u]&=s;for(s=~s,u=0;u<10;u++)this._h[u]=this._h[u]&s|n[u];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,u=1;u<8;u++)o=(this._h[u]+this._pad[u]|0)+(o>>>16)|0,this._h[u]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";h();Object.defineProperty(js,"__esModule",{value:!0});var Bm=HB(),lee=zB(),xh=Qn(),QB=Uc(),fee=Pm();js.KEY_LENGTH=32;js.NONCE_LENGTH=12;js.TAG_LENGTH=16;var KB=new Uint8Array(16),hee=function(){function t(e){if(this.nonceLength=js.NONCE_LENGTH,this.tagLength=js.TAG_LENGTH,e.length!==js.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Bm.stream(this._key,s,o,4);var u=r.length+this.tagLength,a;if(i){if(i.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");a=i}else a=new Uint8Array(u);return Bm.streamXOR(this._key,s,r,a,4),this._authenticate(a.subarray(a.length-this.tagLength,a.length),o,a.subarray(0,a.length-this.tagLength),n),xh.wipe(s),a},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(KB.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(KB.subarray(n.length%16));var o=new Uint8Array(8);i&&QB.writeUint64LE(i.length,o),s.update(o),QB.writeUint64LE(n.length,o),s.update(o);for(var u=s.digest(),a=0;a{"use strict";h();Object.defineProperty($I,"__esModule",{value:!0});function dee(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}$I.isSerializableHash=dee});var JB=B(Oh=>{"use strict";h();Object.defineProperty(Oh,"__esModule",{value:!0});var is=$B(),gee=Pm(),pee=Qn(),YB=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";h();Object.defineProperty(YI,"__esModule",{value:!0});var XB=JB(),ZB=Qn(),yee=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=XB.hmac(this._hash,n,r);this._hmac=new XB.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";h();Object.defineProperty(Uo,"__esModule",{value:!0});var Lm=Uc(),Mm=Qn();Uo.DIGEST_LENGTH=32;Uo.BLOCK_SIZE=64;var tM=function(){function t(){this.digestLength=Uo.DIGEST_LENGTH,this.blockSize=Uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Mm.wipe(this._buffer),Mm.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(JI(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=JI(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Mm.wipe(e.state),e.buffer&&Mm.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Uo.SHA256=tM;var wee=new Int32Array([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]);function JI(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],u=e[2],a=e[3],c=e[4],f=e[5],d=e[6],w=e[7],A=0;A<16;A++){var T=n+A*4;t[A]=Lm.readUint32BE(r,T)}for(var A=16;A<64;A++){var x=t[A-2],R=(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10;x=t[A-15];var V=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3;t[A]=(R+t[A-7]|0)+(V+t[A-16]|0)}for(var A=0;A<64;A++){var R=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(w+(wee[A]+t[A]|0)|0)|0,V=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&u^o&u)|0;w=d,d=f,f=c,c=a+R|0,a=u,u=o,o=s,s=R+V|0}e[0]+=s,e[1]+=o,e[2]+=u,e[3]+=a,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=w,n+=64,i-=64}return n}function vee(t){var e=new tM;e.update(t);var r=e.digest();return e.clean(),r}Uo.hash=vee});var oM=B(zt=>{"use strict";h();Object.defineProperty(zt,"__esModule",{value:!0});zt.sharedKey=zt.generateKeyPair=zt.generateKeyPairFromSeed=zt.scalarMultBase=zt.scalarMult=zt.SHARED_KEY_LENGTH=zt.SECRET_KEY_LENGTH=zt.PUBLIC_KEY_LENGTH=void 0;var Aee=yh(),Eee=Qn();zt.PUBLIC_KEY_LENGTH=32;zt.SECRET_KEY_LENGTH=32;zt.SHARED_KEY_LENGTH=32;function ss(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Dh(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function Iee(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Fm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Um(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function zs(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ph(t,e){zs(t,e,e)}function Tee(t,e){let r=ss();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)Ph(r,r),n!==2&&n!==4&&zs(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function ZI(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=ss(),s=ss(),o=ss(),u=ss(),a=ss(),c=ss();for(let A=0;A<31;A++)r[A]=t[A];r[31]=t[31]&127|64,r[0]&=248,Iee(n,e);for(let A=0;A<16;A++)s[A]=n[A];i[0]=u[0]=1;for(let A=254;A>=0;--A){let T=r[A>>>3]>>>(A&7)&1;Dh(i,s,T),Dh(o,u,T),Fm(a,i,o),Um(i,i,o),Fm(o,s,u),Um(s,s,u),Ph(u,a),Ph(c,i),zs(i,o,i),zs(o,s,a),Fm(a,i,o),Um(i,i,o),Ph(s,i),Um(o,u,c),zs(i,o,bee),Fm(i,i,u),zs(o,o,i),zs(i,u,c),zs(u,s,n),Ph(s,a),Dh(i,s,T),Dh(o,u,T)}for(let A=0;A<16;A++)n[A+16]=i[A],n[A+32]=o[A],n[A+48]=s[A],n[A+64]=u[A];let f=n.subarray(32),d=n.subarray(16);Tee(f,f),zs(d,d,f);let w=new Uint8Array(32);return See(w,d),w}zt.scalarMult=ZI;function iM(t){return ZI(t,nM)}zt.scalarMultBase=iM;function sM(t){if(t.length!==zt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${zt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:iM(e),secretKey:e}}zt.generateKeyPairFromSeed=sM;function _ee(t){let e=(0,Aee.randomBytes)(32,t),r=sM(e);return(0,Eee.wipe)(e),r}zt.generateKeyPair=_ee;function Cee(t,e,r=!1){if(t.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=ZI(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{h()});function cM(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{h()});function fM(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=jc(t.length);for(let n=0;n{h();bm();Eh()});var eT={};Bt(eT,{compare:()=>aM,concat:()=>Sm,equals:()=>cM,fromString:()=>ns,toString:()=>ks,xor:()=>fM});var tT=fe(()=>{h();uM();lI();lM();FI();LI();hM()});var dM={};Bt(dM,{RELAY_JSONRPC:()=>qee,isPublishMethod:()=>iT,isPublishParams:()=>sT,isPublishRequest:()=>Pee,isSubscribeMethod:()=>rT,isSubscribeParams:()=>nT,isSubscribeRequest:()=>Dee,isSubscriptionMethod:()=>uT,isSubscriptionParams:()=>cT,isSubscriptionRequest:()=>Bee,isUnsubscribeMethod:()=>oT,isUnsubscribeParams:()=>aT,isUnsubscribeRequest:()=>Ree,parsePublishRequest:()=>Lee,parseSubscribeRequest:()=>Mee,parseSubscriptionRequest:()=>Uee,parseUnsubscribeRequest:()=>Fee});function Za(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function Nee(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function xee(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function Oee(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function qm(t,e,r){return(r.length?Oee(t,e.length):xee(t,e.length))?Nee(t,e):!1}function Vm(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}function Dee(t){return rT(t.method)&&nT(t.params)}function rT(t){return Vm(t,"subscribe")}function nT(t){return qm(t,["topic"],[])}function Pee(t){return iT(t.method)&&sT(t.params)}function iT(t){return Vm(t,"publish")}function sT(t){return qm(t,["message","topic","ttl"],["prompt","tag"])}function Ree(t){return oT(t.method)&&aT(t.params)}function oT(t){return Vm(t,"unsubscribe")}function aT(t){return qm(t,["id","topic"],[])}function Bee(t){return uT(t.method)&&cT(t.params)}function uT(t){return Vm(t,"subscription")}function cT(t){return qm(t,["id","data"],[])}function Mee(t){if(!rT(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!nT(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Za(e,"topic"),e}function Lee(t){if(!iT(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!sT(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Za(e,"topic"),Za(e,"message"),Za(e,"ttl","number"),e}function Fee(t){if(!oT(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!aT(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Za(e,"id"),e}function Uee(t){if(!uT(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!cT(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Za(e,"id"),Za(e,"data"),e}var qee,gM=fe(()=>{h();qee={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var Qh=B(K=>{"use strict";h();Object.defineProperty(K,"__esModule",{value:!0});var Vee=vB(),el=Qa(),il=zI(),kee=EB(),Hee=VB(),WM=WB(),Gee=eM(),$M=yh(),LT=rM(),jee=oM(),Vt=(tT(),_e(eT)),zee=(gM(),_e(dM));function YM(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var $m=YM(Hee),JM=YM(jee),ny=":";function XM(t){let[e,r]=t.split(ny);return{namespace:e,reference:r}}function ZM(t){let{namespace:e,reference:r}=t;return[e,r].join(ny)}function FT(t){let[e,r,n]=t.split(ny);return{namespace:e,reference:r,address:n}}function e4(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(ny)}function UT(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function t4(t){let{address:e}=FT(t);return e}function r4(t){let{namespace:e,reference:r}=FT(t);return ZM({namespace:e,reference:r})}function Qee(t,e){let{namespace:r,reference:n}=XM(e);return e4({namespace:r,reference:n,address:t})}function Kee(t){return UT(t,t4)}function n4(t){return UT(t,r4)}function Wee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function $ee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...n4(i.accounts))}),r}function Yee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...iy(n,i))}),r}function iy(t,e){return t.includes(":")?[t]:e.chains||[]}var Jee=Object.defineProperty,pM=Object.getOwnPropertySymbols,Xee=Object.prototype.hasOwnProperty,Zee=Object.prototype.propertyIsEnumerable,mM=(t,e,r)=>e in t?Jee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yM=(t,e)=>{for(var r in e||(e={}))Xee.call(e,r)&&mM(t,r,e[r]);if(pM)for(var r of pM(e))Zee.call(e,r)&&mM(t,r,e[r]);return t},i4="ReactNative",Gr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Ym=" ",ete=":",s4="/",qT=2,tte=1e3,o4="js";function VT(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}function al(){return!il.getDocument()&&!!il.getNavigator()&&navigator.product===i4}function Hh(){return!VT()&&!!il.getNavigator()&&!!il.getDocument()}function ru(){return al()?Gr.reactNative:VT()?Gr.node:Hh()?Gr.browser:Gr.unknown}function rte(){var t;try{return al()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function a4(t,e){let r=$m.parse(t);return r=yM(yM({},r),e),t=$m.stringify(r),t}function nte(){return kee.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function ite(t,e){var r;let n=ru(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=il.getLocation())==null?void 0:r.host)||"unknown"),i}function u4(){if(ru()===Gr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=Vee.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function c4(){var t;let e=ru();return e===Gr.browser?[e,((t=il.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function l4(t,e,r){let n=u4(),i=c4();return[[t,e].join("-"),[o4,r].join("-"),n,i].join("/")}function ste({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:u}){let a=r.split("?"),c=l4(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:u||void 0},d=a4(a[1]||"",f);return a[0]+"?"+d}function ote(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function ate(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function f4(t,e=qT){return h4(t.split(s4),e)}function ute(t){return f4(t).join(Ym)}function Ho(t,e){return t.filter(r=>e.includes(r)).length===t.length}function h4(t,e=qT){return t.slice(Math.max(t.length-e,0))}function cte(t){return Object.fromEntries(t.entries())}function lte(t){return new Map(Object.entries(t))}function fte(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var hte=t=>t;function d4(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function dte(t){return t.split(Ym).map(e=>d4(e)).join(Ym)}function gte(t=el.FIVE_MINUTES,e){let r=el.toMiliseconds(t||el.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,u)=>{s=setTimeout(()=>{u(new Error(e))},r),n=o,i=u})}}function pte(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function kT(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function mte(t){return kT("topic",t)}function yte(t){return kT("id",t)}function wte(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function vte(t,e){return el.fromMiliseconds((e||Date.now())+el.toMiliseconds(t))}function Ate(t){return Date.now()>=el.toMiliseconds(t)}function Ete(t,e){return`${t}${e?`:${e}`:""}`}function Js(t=[],e=[]){return[...new Set([...t,...e])]}async function bte({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=ru();o===Gr.browser?s.startsWith("https://")||s.startsWith("http://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===Gr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function Ste(t,e){try{return await t.getItem(e)||(Hh()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}function TT(t,e){return t.filter(r=>e.includes(r))}var g4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ite(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var p4={exports:{}};(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!i.JS_SHA3_NO_NODE_JS&&typeof I.default=="object"&&I.default.versions&&I.default.versions.node;o?i=g4:s&&(i=self);var u=!i.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),f=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],w=[1,256,65536,16777216],A=[6,1536,393216,100663296],T=[0,8,16,24],x=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],R=[224,256,384,512],V=[128,256],U=["hex","buffer","arrayBuffer","array","digest"],Q={128:168,256:136};(i.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(b){return Object.prototype.toString.call(b)==="[object Array]"}),a&&(i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(b){return typeof b=="object"&&b.buffer&&b.buffer.constructor===ArrayBuffer});for(var L=function(b,j,z){return function(W){return new O(b,j,b).update(W)[z]()}},k=function(b,j,z){return function(W,ie){return new O(b,j,ie).update(W)[z]()}},H=function(b,j,z){return function(W,ie,te,ee){return g["cshake"+b].update(W,ie,te,ee)[z]()}},q=function(b,j,z){return function(W,ie,te,ee){return g["kmac"+b].update(W,ie,te,ee)[z]()}},v=function(b,j,z,W){for(var ie=0;ie>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var W=0;W<50;++W)this.s[W]=0}O.prototype.update=function(b){if(this.finalized)throw new Error(r);var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}for(var W=this.blocks,ie=this.byteCount,te=b.length,ee=this.blockCount,se=0,oe=this.s,J,ue;se>2]|=b[se]<>2]|=ue<>2]|=(192|ue>>6)<>2]|=(128|ue&63)<=57344?(W[J>>2]|=(224|ue>>12)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<>2]|=(240|ue>>18)<>2]|=(128|ue>>12&63)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<=ie){for(this.start=J-ie,this.block=W[ee],J=0;J>8,z=b&255;z>0;)ie.unshift(z),b=b>>8,z=b&255,++W;return j?ie.push(W):ie.unshift(W),this.update(ie),ie.length},O.prototype.encodeString=function(b){var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}var W=0,ie=b.length;if(j)W=ie;else for(var te=0;te=57344?W+=3:(ee=65536+((ee&1023)<<10|b.charCodeAt(++te)&1023),W+=4)}return W+=this.encode(W*8),this.update(b),W},O.prototype.bytepad=function(b,j){for(var z=this.encode(j),W=0;W>2]|=this.padding[j&3],this.lastByteIndex===this.byteCount)for(b[0]=b[z],j=1;j>4&15]+c[se&15]+c[se>>12&15]+c[se>>8&15]+c[se>>20&15]+c[se>>16&15]+c[se>>28&15]+c[se>>24&15];te%b===0&&($(j),ie=0)}return W&&(se=j[ie],ee+=c[se>>4&15]+c[se&15],W>1&&(ee+=c[se>>12&15]+c[se>>8&15]),W>2&&(ee+=c[se>>20&15]+c[se>>16&15])),ee},O.prototype.arrayBuffer=function(){this.finalize();var b=this.blockCount,j=this.s,z=this.outputBlocks,W=this.extraBytes,ie=0,te=0,ee=this.outputBits>>3,se;W?se=new ArrayBuffer(z+1<<2):se=new ArrayBuffer(ee);for(var oe=new Uint32Array(se);te>8&255,ee[se+2]=oe>>16&255,ee[se+3]=oe>>24&255;te%b===0&&$(j)}return W&&(se=te<<2,oe=j[ie],ee[se]=oe&255,W>1&&(ee[se+1]=oe>>8&255),W>2&&(ee[se+2]=oe>>16&255)),ee};function Y(b,j,z){O.call(this,b,j,z)}Y.prototype=new O,Y.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var $=function(b){var j,z,W,ie,te,ee,se,oe,J,ue,wt,vt,Ni,At,Et,xi,bt,St,Oi,It,Tt,Di,Qe,Ke,ri,We,$e,ni,Ye,Je,ii,Xe,Ze,si,et,tt,oi,rt,nt,ai,it,st,ui,ot,at,ci,ut,ct,li,lt,ft,fi,ht,dt,hi,gt,pt,vn,An,En,bn,Sn,In;for(W=0;W<48;W+=2)ie=b[0]^b[10]^b[20]^b[30]^b[40],te=b[1]^b[11]^b[21]^b[31]^b[41],ee=b[2]^b[12]^b[22]^b[32]^b[42],se=b[3]^b[13]^b[23]^b[33]^b[43],oe=b[4]^b[14]^b[24]^b[34]^b[44],J=b[5]^b[15]^b[25]^b[35]^b[45],ue=b[6]^b[16]^b[26]^b[36]^b[46],wt=b[7]^b[17]^b[27]^b[37]^b[47],vt=b[8]^b[18]^b[28]^b[38]^b[48],Ni=b[9]^b[19]^b[29]^b[39]^b[49],j=vt^(ee<<1|se>>>31),z=Ni^(se<<1|ee>>>31),b[0]^=j,b[1]^=z,b[10]^=j,b[11]^=z,b[20]^=j,b[21]^=z,b[30]^=j,b[31]^=z,b[40]^=j,b[41]^=z,j=ie^(oe<<1|J>>>31),z=te^(J<<1|oe>>>31),b[2]^=j,b[3]^=z,b[12]^=j,b[13]^=z,b[22]^=j,b[23]^=z,b[32]^=j,b[33]^=z,b[42]^=j,b[43]^=z,j=ee^(ue<<1|wt>>>31),z=se^(wt<<1|ue>>>31),b[4]^=j,b[5]^=z,b[14]^=j,b[15]^=z,b[24]^=j,b[25]^=z,b[34]^=j,b[35]^=z,b[44]^=j,b[45]^=z,j=oe^(vt<<1|Ni>>>31),z=J^(Ni<<1|vt>>>31),b[6]^=j,b[7]^=z,b[16]^=j,b[17]^=z,b[26]^=j,b[27]^=z,b[36]^=j,b[37]^=z,b[46]^=j,b[47]^=z,j=ue^(ie<<1|te>>>31),z=wt^(te<<1|ie>>>31),b[8]^=j,b[9]^=z,b[18]^=j,b[19]^=z,b[28]^=j,b[29]^=z,b[38]^=j,b[39]^=z,b[48]^=j,b[49]^=z,At=b[0],Et=b[1],ci=b[11]<<4|b[10]>>>28,ut=b[10]<<4|b[11]>>>28,ni=b[20]<<3|b[21]>>>29,Ye=b[21]<<3|b[20]>>>29,En=b[31]<<9|b[30]>>>23,bn=b[30]<<9|b[31]>>>23,st=b[40]<<18|b[41]>>>14,ui=b[41]<<18|b[40]>>>14,si=b[2]<<1|b[3]>>>31,et=b[3]<<1|b[2]>>>31,xi=b[13]<<12|b[12]>>>20,bt=b[12]<<12|b[13]>>>20,ct=b[22]<<10|b[23]>>>22,li=b[23]<<10|b[22]>>>22,Je=b[33]<<13|b[32]>>>19,ii=b[32]<<13|b[33]>>>19,Sn=b[42]<<2|b[43]>>>30,In=b[43]<<2|b[42]>>>30,dt=b[5]<<30|b[4]>>>2,hi=b[4]<<30|b[5]>>>2,tt=b[14]<<6|b[15]>>>26,oi=b[15]<<6|b[14]>>>26,St=b[25]<<11|b[24]>>>21,Oi=b[24]<<11|b[25]>>>21,lt=b[34]<<15|b[35]>>>17,ft=b[35]<<15|b[34]>>>17,Xe=b[45]<<29|b[44]>>>3,Ze=b[44]<<29|b[45]>>>3,Ke=b[6]<<28|b[7]>>>4,ri=b[7]<<28|b[6]>>>4,gt=b[17]<<23|b[16]>>>9,pt=b[16]<<23|b[17]>>>9,rt=b[26]<<25|b[27]>>>7,nt=b[27]<<25|b[26]>>>7,It=b[36]<<21|b[37]>>>11,Tt=b[37]<<21|b[36]>>>11,fi=b[47]<<24|b[46]>>>8,ht=b[46]<<24|b[47]>>>8,ot=b[8]<<27|b[9]>>>5,at=b[9]<<27|b[8]>>>5,We=b[18]<<20|b[19]>>>12,$e=b[19]<<20|b[18]>>>12,vn=b[29]<<7|b[28]>>>25,An=b[28]<<7|b[29]>>>25,ai=b[38]<<8|b[39]>>>24,it=b[39]<<8|b[38]>>>24,Di=b[48]<<14|b[49]>>>18,Qe=b[49]<<14|b[48]>>>18,b[0]=At^~xi&St,b[1]=Et^~bt&Oi,b[10]=Ke^~We&ni,b[11]=ri^~$e&Ye,b[20]=si^~tt&rt,b[21]=et^~oi&nt,b[30]=ot^~ci&ct,b[31]=at^~ut&li,b[40]=dt^~gt&vn,b[41]=hi^~pt&An,b[2]=xi^~St&It,b[3]=bt^~Oi&Tt,b[12]=We^~ni&Je,b[13]=$e^~Ye&ii,b[22]=tt^~rt&ai,b[23]=oi^~nt&it,b[32]=ci^~ct<,b[33]=ut^~li&ft,b[42]=gt^~vn&En,b[43]=pt^~An&bn,b[4]=St^~It&Di,b[5]=Oi^~Tt&Qe,b[14]=ni^~Je&Xe,b[15]=Ye^~ii&Ze,b[24]=rt^~ai&st,b[25]=nt^~it&ui,b[34]=ct^~lt&fi,b[35]=li^~ft&ht,b[44]=vn^~En&Sn,b[45]=An^~bn&In,b[6]=It^~Di&At,b[7]=Tt^~Qe&Et,b[16]=Je^~Xe&Ke,b[17]=ii^~Ze&ri,b[26]=ai^~st&si,b[27]=it^~ui&et,b[36]=lt^~fi&ot,b[37]=ft^~ht&at,b[46]=En^~Sn&dt,b[47]=bn^~In&hi,b[8]=Di^~At&xi,b[9]=Qe^~Et&bt,b[18]=Xe^~Ke&We,b[19]=Ze^~ri&$e,b[28]=st^~si&tt,b[29]=ui^~et&oi,b[38]=fi^~ot&ci,b[39]=ht^~at&ut,b[48]=Sn^~dt>,b[49]=In^~hi&pt,b[0]^=x[W],b[1]^=x[W+1]};if(u)t.exports=g;else for(E=0;E{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken implementation")}catch(t){return t.message}return null}var EM=Cte(),_T;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(_T||(_T={}));var Si;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Si||(Si={}));var bM="0123456789abcdef",kt=class t{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){let n=e.toLowerCase();Qm[n]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(AM>Qm[n])&&console.log.apply(console,r)}debug(...e){this._log(t.levels.DEBUG,e)}info(...e){this._log(t.levels.INFO,e)}warn(...e){this._log(t.levels.WARNING,e)}makeError(e,r,n){if(vM)return this.makeError("censored error",r,{});r||(r=t.errors.UNKNOWN_ERROR),n||(n={});let i=[];Object.keys(n).forEach(a=>{let c=n[a];try{if(c instanceof Uint8Array){let f="";for(let d=0;d>4],f+=bM[c[d]&15];i.push(a+"=Uint8Array(0x"+f+")")}else i.push(a+"="+JSON.stringify(c))}catch{i.push(a+"="+JSON.stringify(n[a].toString()))}}),i.push(`code=${r}`),i.push(`version=${this.version}`);let s=e,o="";switch(r){case Si.NUMERIC_FAULT:{o="NUMERIC_FAULT";let a=e;switch(a){case"overflow":case"underflow":case"division-by-zero":o+="-"+a;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Si.CALL_EXCEPTION:case Si.INSUFFICIENT_FUNDS:case Si.MISSING_NEW:case Si.NONCE_EXPIRED:case Si.REPLACEMENT_UNDERPRICED:case Si.TRANSACTION_REPLACED:case Si.UNPREDICTABLE_GAS_LIMIT:o=r;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),i.length&&(e+=" ("+i.join(", ")+")");let u=new Error(e);return u.reason=s,u.code=r,Object.keys(n).forEach(function(a){u[a]=n[a]}),u}throwError(e,r,n){throw this.makeError(e,r,n)}throwArgumentError(e,r,n){return this.throwError(e,t.errors.INVALID_ARGUMENT,{argument:r,value:n})}assert(e,r,n,i){e||this.throwError(r,n,i)}assertArgument(e,r,n,i){e||this.throwArgumentError(r,n,i)}checkNormalize(e){EM&&this.throwError("platform missing String.prototype.normalize",t.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:EM})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,n){n?n=": "+n:n="",er&&this.throwError("too many arguments"+n,t.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",t.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return lT||(lT=new t(_te)),lT}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),wM){if(!e)return;this.globalLogger().throwError("error censorship permanent",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}vM=!!e,wM=!!r}static setLogLevel(e){let r=Qm[e.toLowerCase()];if(r==null){t.globalLogger().warn("invalid log level - "+e);return}AM=r}static from(e){return new t(e)}};kt.errors=Si,kt.levels=_T;var Nte="bytes/5.7.0",er=new kt(Nte);function m4(t){return!!t.toHexString}function tl(t){return t.slice||(t.slice=function(){let e=Array.prototype.slice.call(arguments);return tl(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function xte(t){return gn(t)&&!(t.length%2)||ul(t)}function SM(t){return typeof t=="number"&&t==t&&t%1===0}function ul(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!SM(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function Qt(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid arrayify value");let r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),tl(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t)&&(t=t.toHexString()),gn(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":er.throwArgumentError("hex data is odd-length","value",t));let n=[];for(let i=0;iQt(i)),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);return e.reduce((i,s)=>(n.set(s,i),i+s.length),0),tl(n)}function Dte(t,e){t=Qt(t),t.length>e&&er.throwArgumentError("value out of range","value",arguments[0]);let r=new Uint8Array(e);return r.set(t,e-t.length),tl(r)}function gn(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}var fT="0123456789abcdef";function kr(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=fT[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t))return t.toHexString();if(gn(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":er.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(ul(t)){let r="0x";for(let n=0;n>4]+fT[i&15]}return r}return er.throwArgumentError("invalid hexlify value","value",t)}function Pte(t){if(typeof t!="string")t=kr(t);else if(!gn(t)||t.length%2)return null;return(t.length-2)/2}function IM(t,e,r){return typeof t!="string"?t=kr(t):(!gn(t)||t.length%2)&&er.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function fs(t,e){for(typeof t!="string"?t=kr(t):gn(t)||er.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&er.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function y4(t){let e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(xte(t)){let r=Qt(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64))):r.length===65?(e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64)),e.v=r[64]):er.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:er.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=kr(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){let i=Dte(Qt(e._vs),32);e._vs=kr(i);let s=i[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&er.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),i[0]&=127;let o=kr(i);e.s==null?e.s=o:e.s!==o&&er.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?er.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{let i=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==i&&er.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!gn(e.r)?er.throwArgumentError("signature missing or invalid r","signature",t):e.r=fs(e.r,32),e.s==null||!gn(e.s)?er.throwArgumentError("signature missing or invalid s","signature",t):e.s=fs(e.s,32);let r=Qt(e.s);r[0]>=128&&er.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);let n=kr(r);e._vs&&(gn(e._vs)||er.throwArgumentError("signature invalid _vs","signature",t),e._vs=fs(e._vs,32)),e._vs==null?e._vs=n:e._vs!==n&&er.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function HT(t){return"0x"+Tte.keccak_256(Qt(t))}var w4={exports:{}},Rte={},Bte=Object.freeze({__proto__:null,default:Rte}),Mte=Ite(Bte);(function(t){(function(e,r){function n(l,g){if(!l)throw new Error(g||"Assertion failed")}function i(l,g){l.super_=g;var y=function(){};y.prototype=g.prototype,l.prototype=new y,l.prototype.constructor=l}function s(l,g,y){if(s.isBN(l))return l;this.negative=0,this.words=null,this.length=0,this.red=null,l!==null&&((g==="le"||g==="be")&&(y=g,g=10),this._init(l||0,g||10,y||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Mte.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,g){return l.cmp(g)>0?l:g},s.min=function(l,g){return l.cmp(g)<0?l:g},s.prototype._init=function(l,g,y){if(typeof l=="number")return this._initNumber(l,g,y);if(typeof l=="object")return this._initArray(l,g,y);g==="hex"&&(g=16),n(g===(g|0)&&g>=2&&g<=36),l=l.toString().replace(/\s+/g,"");var E=0;l[0]==="-"&&(E++,this.negative=1),E=0;E-=3)_=l[E]|l[E-1]<<8|l[E-2]<<16,this.words[S]|=_<>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);else if(y==="le")for(E=0,S=0;E>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);return this._strip()};function u(l,g){var y=l.charCodeAt(g);if(y>=48&&y<=57)return y-48;if(y>=65&&y<=70)return y-55;if(y>=97&&y<=102)return y-87;n(!1,"Invalid character in "+l)}function a(l,g,y){var E=u(l,y);return y-1>=g&&(E|=u(l,y-1)<<4),E}s.prototype._parseHex=function(l,g,y){this.length=Math.ceil((l.length-g)/6),this.words=new Array(this.length);for(var E=0;E=g;E-=2)M=a(l,g,E)<=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8;else{var N=l.length-g;for(E=N%2===0?g+1:g;E=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8}this._strip()};function c(l,g,y,E){for(var S=0,_=0,M=Math.min(l.length,y),N=g;N=49?_=m-49+10:m>=17?_=m-17+10:_=m,n(m>=0&&_1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch{s.prototype.inspect=d}else s.prototype.inspect=d;function d(){return(this.red?""}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],A=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(l,g){l=l||10,g=g|0||1;var y;if(l===16||l==="hex"){y="";for(var E=0,S=0,_=0;_>>24-E&16777215,E+=2,E>=26&&(E-=26,_--),S!==0||_!==this.length-1?y=w[6-N.length]+N+y:y=N+y}for(S!==0&&(y=S.toString(16)+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var m=A[l],O=T[l];y="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var $=Y.modrn(O).toString(l);Y=Y.idivn(O),Y.isZero()?y=$+y:y=w[m-$.length]+$+y}for(this.isZero()&&(y="0"+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(l,g){return this.toArrayLike(o,l,g)}),s.prototype.toArray=function(l,g){return this.toArrayLike(Array,l,g)};var x=function(l,g){return l.allocUnsafe?l.allocUnsafe(g):new l(g)};s.prototype.toArrayLike=function(l,g,y){this._strip();var E=this.byteLength(),S=y||Math.max(1,E);n(E<=S,"byte array longer than desired length"),n(S>0,"Requested array length <= 0");var _=x(l,S),M=g==="le"?"LE":"BE";return this["_toArrayLike"+M](_,E),_},s.prototype._toArrayLikeLE=function(l,g){for(var y=0,E=0,S=0,_=0;S>8&255),y>16&255),_===6?(y>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y=0&&(l[y--]=M>>8&255),y>=0&&(l[y--]=M>>16&255),_===6?(y>=0&&(l[y--]=M>>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y>=0)for(l[y--]=E;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var g=l,y=0;return g>=4096&&(y+=13,g>>>=13),g>=64&&(y+=7,g>>>=7),g>=8&&(y+=4,g>>>=4),g>=2&&(y+=2,g>>>=2),y+g},s.prototype._zeroBits=function(l){if(l===0)return 26;var g=l,y=0;return g&8191||(y+=13,g>>>=13),g&127||(y+=7,g>>>=7),g&15||(y+=4,g>>>=4),g&3||(y+=2,g>>>=2),g&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],g=this._countBits(l);return(this.length-1)*26+g};function R(l){for(var g=new Array(l.bitLength()),y=0;y>>S&1}return g}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,g=0;gl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var g;this.length>l.length?g=l:g=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var g,y;this.length>l.length?(g=this,y=l):(g=l,y=this);for(var E=0;El.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var g=Math.ceil(l/26)|0,y=l%26;this._expand(g),y>0&&g--;for(var E=0;E0&&(this.words[E]=~this.words[E]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,g){n(typeof l=="number"&&l>=0);var y=l/26|0,E=l%26;return this._expand(y+1),g?this.words[y]=this.words[y]|1<l.length?(y=this,E=l):(y=l,E=this);for(var S=0,_=0;_>>26;for(;S!==0&&_>>26;if(this.length=y.length,S!==0)this.words[this.length]=S,this.length++;else if(y!==this)for(;_l.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var g=this.iadd(l);return l.negative=1,g._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,S;y>0?(E=this,S=l):(E=l,S=this);for(var _=0,M=0;M>26,this.words[M]=g&67108863;for(;_!==0&&M>26,this.words[M]=g&67108863;if(_===0&&M>>26,$=m&67108863,b=Math.min(O,g.length-1),j=Math.max(0,O-l.length+1);j<=b;j++){var z=O-j|0;S=l.words[z]|0,_=g.words[j]|0,M=S*_+$,Y+=M/67108864|0,$=M&67108863}y.words[O]=$|0,m=Y|0}return m!==0?y.words[O]=m|0:y.length--,y._strip()}var U=function(l,g,y){var E=l.words,S=g.words,_=y.words,M=0,N,m,O,Y=E[0]|0,$=Y&8191,b=Y>>>13,j=E[1]|0,z=j&8191,W=j>>>13,ie=E[2]|0,te=ie&8191,ee=ie>>>13,se=E[3]|0,oe=se&8191,J=se>>>13,ue=E[4]|0,wt=ue&8191,vt=ue>>>13,Ni=E[5]|0,At=Ni&8191,Et=Ni>>>13,xi=E[6]|0,bt=xi&8191,St=xi>>>13,Oi=E[7]|0,It=Oi&8191,Tt=Oi>>>13,Di=E[8]|0,Qe=Di&8191,Ke=Di>>>13,ri=E[9]|0,We=ri&8191,$e=ri>>>13,ni=S[0]|0,Ye=ni&8191,Je=ni>>>13,ii=S[1]|0,Xe=ii&8191,Ze=ii>>>13,si=S[2]|0,et=si&8191,tt=si>>>13,oi=S[3]|0,rt=oi&8191,nt=oi>>>13,ai=S[4]|0,it=ai&8191,st=ai>>>13,ui=S[5]|0,ot=ui&8191,at=ui>>>13,ci=S[6]|0,ut=ci&8191,ct=ci>>>13,li=S[7]|0,lt=li&8191,ft=li>>>13,fi=S[8]|0,ht=fi&8191,dt=fi>>>13,hi=S[9]|0,gt=hi&8191,pt=hi>>>13;y.negative=l.negative^g.negative,y.length=19,N=Math.imul($,Ye),m=Math.imul($,Je),m=m+Math.imul(b,Ye)|0,O=Math.imul(b,Je);var vn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(vn>>>26)|0,vn&=67108863,N=Math.imul(z,Ye),m=Math.imul(z,Je),m=m+Math.imul(W,Ye)|0,O=Math.imul(W,Je),N=N+Math.imul($,Xe)|0,m=m+Math.imul($,Ze)|0,m=m+Math.imul(b,Xe)|0,O=O+Math.imul(b,Ze)|0;var An=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(An>>>26)|0,An&=67108863,N=Math.imul(te,Ye),m=Math.imul(te,Je),m=m+Math.imul(ee,Ye)|0,O=Math.imul(ee,Je),N=N+Math.imul(z,Xe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(W,Xe)|0,O=O+Math.imul(W,Ze)|0,N=N+Math.imul($,et)|0,m=m+Math.imul($,tt)|0,m=m+Math.imul(b,et)|0,O=O+Math.imul(b,tt)|0;var En=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(En>>>26)|0,En&=67108863,N=Math.imul(oe,Ye),m=Math.imul(oe,Je),m=m+Math.imul(J,Ye)|0,O=Math.imul(J,Je),N=N+Math.imul(te,Xe)|0,m=m+Math.imul(te,Ze)|0,m=m+Math.imul(ee,Xe)|0,O=O+Math.imul(ee,Ze)|0,N=N+Math.imul(z,et)|0,m=m+Math.imul(z,tt)|0,m=m+Math.imul(W,et)|0,O=O+Math.imul(W,tt)|0,N=N+Math.imul($,rt)|0,m=m+Math.imul($,nt)|0,m=m+Math.imul(b,rt)|0,O=O+Math.imul(b,nt)|0;var bn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(bn>>>26)|0,bn&=67108863,N=Math.imul(wt,Ye),m=Math.imul(wt,Je),m=m+Math.imul(vt,Ye)|0,O=Math.imul(vt,Je),N=N+Math.imul(oe,Xe)|0,m=m+Math.imul(oe,Ze)|0,m=m+Math.imul(J,Xe)|0,O=O+Math.imul(J,Ze)|0,N=N+Math.imul(te,et)|0,m=m+Math.imul(te,tt)|0,m=m+Math.imul(ee,et)|0,O=O+Math.imul(ee,tt)|0,N=N+Math.imul(z,rt)|0,m=m+Math.imul(z,nt)|0,m=m+Math.imul(W,rt)|0,O=O+Math.imul(W,nt)|0,N=N+Math.imul($,it)|0,m=m+Math.imul($,st)|0,m=m+Math.imul(b,it)|0,O=O+Math.imul(b,st)|0;var Sn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Sn>>>26)|0,Sn&=67108863,N=Math.imul(At,Ye),m=Math.imul(At,Je),m=m+Math.imul(Et,Ye)|0,O=Math.imul(Et,Je),N=N+Math.imul(wt,Xe)|0,m=m+Math.imul(wt,Ze)|0,m=m+Math.imul(vt,Xe)|0,O=O+Math.imul(vt,Ze)|0,N=N+Math.imul(oe,et)|0,m=m+Math.imul(oe,tt)|0,m=m+Math.imul(J,et)|0,O=O+Math.imul(J,tt)|0,N=N+Math.imul(te,rt)|0,m=m+Math.imul(te,nt)|0,m=m+Math.imul(ee,rt)|0,O=O+Math.imul(ee,nt)|0,N=N+Math.imul(z,it)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(W,it)|0,O=O+Math.imul(W,st)|0,N=N+Math.imul($,ot)|0,m=m+Math.imul($,at)|0,m=m+Math.imul(b,ot)|0,O=O+Math.imul(b,at)|0;var In=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(In>>>26)|0,In&=67108863,N=Math.imul(bt,Ye),m=Math.imul(bt,Je),m=m+Math.imul(St,Ye)|0,O=Math.imul(St,Je),N=N+Math.imul(At,Xe)|0,m=m+Math.imul(At,Ze)|0,m=m+Math.imul(Et,Xe)|0,O=O+Math.imul(Et,Ze)|0,N=N+Math.imul(wt,et)|0,m=m+Math.imul(wt,tt)|0,m=m+Math.imul(vt,et)|0,O=O+Math.imul(vt,tt)|0,N=N+Math.imul(oe,rt)|0,m=m+Math.imul(oe,nt)|0,m=m+Math.imul(J,rt)|0,O=O+Math.imul(J,nt)|0,N=N+Math.imul(te,it)|0,m=m+Math.imul(te,st)|0,m=m+Math.imul(ee,it)|0,O=O+Math.imul(ee,st)|0,N=N+Math.imul(z,ot)|0,m=m+Math.imul(z,at)|0,m=m+Math.imul(W,ot)|0,O=O+Math.imul(W,at)|0,N=N+Math.imul($,ut)|0,m=m+Math.imul($,ct)|0,m=m+Math.imul(b,ut)|0,O=O+Math.imul(b,ct)|0;var da=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(da>>>26)|0,da&=67108863,N=Math.imul(It,Ye),m=Math.imul(It,Je),m=m+Math.imul(Tt,Ye)|0,O=Math.imul(Tt,Je),N=N+Math.imul(bt,Xe)|0,m=m+Math.imul(bt,Ze)|0,m=m+Math.imul(St,Xe)|0,O=O+Math.imul(St,Ze)|0,N=N+Math.imul(At,et)|0,m=m+Math.imul(At,tt)|0,m=m+Math.imul(Et,et)|0,O=O+Math.imul(Et,tt)|0,N=N+Math.imul(wt,rt)|0,m=m+Math.imul(wt,nt)|0,m=m+Math.imul(vt,rt)|0,O=O+Math.imul(vt,nt)|0,N=N+Math.imul(oe,it)|0,m=m+Math.imul(oe,st)|0,m=m+Math.imul(J,it)|0,O=O+Math.imul(J,st)|0,N=N+Math.imul(te,ot)|0,m=m+Math.imul(te,at)|0,m=m+Math.imul(ee,ot)|0,O=O+Math.imul(ee,at)|0,N=N+Math.imul(z,ut)|0,m=m+Math.imul(z,ct)|0,m=m+Math.imul(W,ut)|0,O=O+Math.imul(W,ct)|0,N=N+Math.imul($,lt)|0,m=m+Math.imul($,ft)|0,m=m+Math.imul(b,lt)|0,O=O+Math.imul(b,ft)|0;var ga=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ga>>>26)|0,ga&=67108863,N=Math.imul(Qe,Ye),m=Math.imul(Qe,Je),m=m+Math.imul(Ke,Ye)|0,O=Math.imul(Ke,Je),N=N+Math.imul(It,Xe)|0,m=m+Math.imul(It,Ze)|0,m=m+Math.imul(Tt,Xe)|0,O=O+Math.imul(Tt,Ze)|0,N=N+Math.imul(bt,et)|0,m=m+Math.imul(bt,tt)|0,m=m+Math.imul(St,et)|0,O=O+Math.imul(St,tt)|0,N=N+Math.imul(At,rt)|0,m=m+Math.imul(At,nt)|0,m=m+Math.imul(Et,rt)|0,O=O+Math.imul(Et,nt)|0,N=N+Math.imul(wt,it)|0,m=m+Math.imul(wt,st)|0,m=m+Math.imul(vt,it)|0,O=O+Math.imul(vt,st)|0,N=N+Math.imul(oe,ot)|0,m=m+Math.imul(oe,at)|0,m=m+Math.imul(J,ot)|0,O=O+Math.imul(J,at)|0,N=N+Math.imul(te,ut)|0,m=m+Math.imul(te,ct)|0,m=m+Math.imul(ee,ut)|0,O=O+Math.imul(ee,ct)|0,N=N+Math.imul(z,lt)|0,m=m+Math.imul(z,ft)|0,m=m+Math.imul(W,lt)|0,O=O+Math.imul(W,ft)|0,N=N+Math.imul($,ht)|0,m=m+Math.imul($,dt)|0,m=m+Math.imul(b,ht)|0,O=O+Math.imul(b,dt)|0;var pa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pa>>>26)|0,pa&=67108863,N=Math.imul(We,Ye),m=Math.imul(We,Je),m=m+Math.imul($e,Ye)|0,O=Math.imul($e,Je),N=N+Math.imul(Qe,Xe)|0,m=m+Math.imul(Qe,Ze)|0,m=m+Math.imul(Ke,Xe)|0,O=O+Math.imul(Ke,Ze)|0,N=N+Math.imul(It,et)|0,m=m+Math.imul(It,tt)|0,m=m+Math.imul(Tt,et)|0,O=O+Math.imul(Tt,tt)|0,N=N+Math.imul(bt,rt)|0,m=m+Math.imul(bt,nt)|0,m=m+Math.imul(St,rt)|0,O=O+Math.imul(St,nt)|0,N=N+Math.imul(At,it)|0,m=m+Math.imul(At,st)|0,m=m+Math.imul(Et,it)|0,O=O+Math.imul(Et,st)|0,N=N+Math.imul(wt,ot)|0,m=m+Math.imul(wt,at)|0,m=m+Math.imul(vt,ot)|0,O=O+Math.imul(vt,at)|0,N=N+Math.imul(oe,ut)|0,m=m+Math.imul(oe,ct)|0,m=m+Math.imul(J,ut)|0,O=O+Math.imul(J,ct)|0,N=N+Math.imul(te,lt)|0,m=m+Math.imul(te,ft)|0,m=m+Math.imul(ee,lt)|0,O=O+Math.imul(ee,ft)|0,N=N+Math.imul(z,ht)|0,m=m+Math.imul(z,dt)|0,m=m+Math.imul(W,ht)|0,O=O+Math.imul(W,dt)|0,N=N+Math.imul($,gt)|0,m=m+Math.imul($,pt)|0,m=m+Math.imul(b,gt)|0,O=O+Math.imul(b,pt)|0;var ma=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ma>>>26)|0,ma&=67108863,N=Math.imul(We,Xe),m=Math.imul(We,Ze),m=m+Math.imul($e,Xe)|0,O=Math.imul($e,Ze),N=N+Math.imul(Qe,et)|0,m=m+Math.imul(Qe,tt)|0,m=m+Math.imul(Ke,et)|0,O=O+Math.imul(Ke,tt)|0,N=N+Math.imul(It,rt)|0,m=m+Math.imul(It,nt)|0,m=m+Math.imul(Tt,rt)|0,O=O+Math.imul(Tt,nt)|0,N=N+Math.imul(bt,it)|0,m=m+Math.imul(bt,st)|0,m=m+Math.imul(St,it)|0,O=O+Math.imul(St,st)|0,N=N+Math.imul(At,ot)|0,m=m+Math.imul(At,at)|0,m=m+Math.imul(Et,ot)|0,O=O+Math.imul(Et,at)|0,N=N+Math.imul(wt,ut)|0,m=m+Math.imul(wt,ct)|0,m=m+Math.imul(vt,ut)|0,O=O+Math.imul(vt,ct)|0,N=N+Math.imul(oe,lt)|0,m=m+Math.imul(oe,ft)|0,m=m+Math.imul(J,lt)|0,O=O+Math.imul(J,ft)|0,N=N+Math.imul(te,ht)|0,m=m+Math.imul(te,dt)|0,m=m+Math.imul(ee,ht)|0,O=O+Math.imul(ee,dt)|0,N=N+Math.imul(z,gt)|0,m=m+Math.imul(z,pt)|0,m=m+Math.imul(W,gt)|0,O=O+Math.imul(W,pt)|0;var ya=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ya>>>26)|0,ya&=67108863,N=Math.imul(We,et),m=Math.imul(We,tt),m=m+Math.imul($e,et)|0,O=Math.imul($e,tt),N=N+Math.imul(Qe,rt)|0,m=m+Math.imul(Qe,nt)|0,m=m+Math.imul(Ke,rt)|0,O=O+Math.imul(Ke,nt)|0,N=N+Math.imul(It,it)|0,m=m+Math.imul(It,st)|0,m=m+Math.imul(Tt,it)|0,O=O+Math.imul(Tt,st)|0,N=N+Math.imul(bt,ot)|0,m=m+Math.imul(bt,at)|0,m=m+Math.imul(St,ot)|0,O=O+Math.imul(St,at)|0,N=N+Math.imul(At,ut)|0,m=m+Math.imul(At,ct)|0,m=m+Math.imul(Et,ut)|0,O=O+Math.imul(Et,ct)|0,N=N+Math.imul(wt,lt)|0,m=m+Math.imul(wt,ft)|0,m=m+Math.imul(vt,lt)|0,O=O+Math.imul(vt,ft)|0,N=N+Math.imul(oe,ht)|0,m=m+Math.imul(oe,dt)|0,m=m+Math.imul(J,ht)|0,O=O+Math.imul(J,dt)|0,N=N+Math.imul(te,gt)|0,m=m+Math.imul(te,pt)|0,m=m+Math.imul(ee,gt)|0,O=O+Math.imul(ee,pt)|0;var wa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(wa>>>26)|0,wa&=67108863,N=Math.imul(We,rt),m=Math.imul(We,nt),m=m+Math.imul($e,rt)|0,O=Math.imul($e,nt),N=N+Math.imul(Qe,it)|0,m=m+Math.imul(Qe,st)|0,m=m+Math.imul(Ke,it)|0,O=O+Math.imul(Ke,st)|0,N=N+Math.imul(It,ot)|0,m=m+Math.imul(It,at)|0,m=m+Math.imul(Tt,ot)|0,O=O+Math.imul(Tt,at)|0,N=N+Math.imul(bt,ut)|0,m=m+Math.imul(bt,ct)|0,m=m+Math.imul(St,ut)|0,O=O+Math.imul(St,ct)|0,N=N+Math.imul(At,lt)|0,m=m+Math.imul(At,ft)|0,m=m+Math.imul(Et,lt)|0,O=O+Math.imul(Et,ft)|0,N=N+Math.imul(wt,ht)|0,m=m+Math.imul(wt,dt)|0,m=m+Math.imul(vt,ht)|0,O=O+Math.imul(vt,dt)|0,N=N+Math.imul(oe,gt)|0,m=m+Math.imul(oe,pt)|0,m=m+Math.imul(J,gt)|0,O=O+Math.imul(J,pt)|0;var va=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(va>>>26)|0,va&=67108863,N=Math.imul(We,it),m=Math.imul(We,st),m=m+Math.imul($e,it)|0,O=Math.imul($e,st),N=N+Math.imul(Qe,ot)|0,m=m+Math.imul(Qe,at)|0,m=m+Math.imul(Ke,ot)|0,O=O+Math.imul(Ke,at)|0,N=N+Math.imul(It,ut)|0,m=m+Math.imul(It,ct)|0,m=m+Math.imul(Tt,ut)|0,O=O+Math.imul(Tt,ct)|0,N=N+Math.imul(bt,lt)|0,m=m+Math.imul(bt,ft)|0,m=m+Math.imul(St,lt)|0,O=O+Math.imul(St,ft)|0,N=N+Math.imul(At,ht)|0,m=m+Math.imul(At,dt)|0,m=m+Math.imul(Et,ht)|0,O=O+Math.imul(Et,dt)|0,N=N+Math.imul(wt,gt)|0,m=m+Math.imul(wt,pt)|0,m=m+Math.imul(vt,gt)|0,O=O+Math.imul(vt,pt)|0;var Aa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,N=Math.imul(We,ot),m=Math.imul(We,at),m=m+Math.imul($e,ot)|0,O=Math.imul($e,at),N=N+Math.imul(Qe,ut)|0,m=m+Math.imul(Qe,ct)|0,m=m+Math.imul(Ke,ut)|0,O=O+Math.imul(Ke,ct)|0,N=N+Math.imul(It,lt)|0,m=m+Math.imul(It,ft)|0,m=m+Math.imul(Tt,lt)|0,O=O+Math.imul(Tt,ft)|0,N=N+Math.imul(bt,ht)|0,m=m+Math.imul(bt,dt)|0,m=m+Math.imul(St,ht)|0,O=O+Math.imul(St,dt)|0,N=N+Math.imul(At,gt)|0,m=m+Math.imul(At,pt)|0,m=m+Math.imul(Et,gt)|0,O=O+Math.imul(Et,pt)|0;var Ea=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Ea>>>26)|0,Ea&=67108863,N=Math.imul(We,ut),m=Math.imul(We,ct),m=m+Math.imul($e,ut)|0,O=Math.imul($e,ct),N=N+Math.imul(Qe,lt)|0,m=m+Math.imul(Qe,ft)|0,m=m+Math.imul(Ke,lt)|0,O=O+Math.imul(Ke,ft)|0,N=N+Math.imul(It,ht)|0,m=m+Math.imul(It,dt)|0,m=m+Math.imul(Tt,ht)|0,O=O+Math.imul(Tt,dt)|0,N=N+Math.imul(bt,gt)|0,m=m+Math.imul(bt,pt)|0,m=m+Math.imul(St,gt)|0,O=O+Math.imul(St,pt)|0;var hw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(hw>>>26)|0,hw&=67108863,N=Math.imul(We,lt),m=Math.imul(We,ft),m=m+Math.imul($e,lt)|0,O=Math.imul($e,ft),N=N+Math.imul(Qe,ht)|0,m=m+Math.imul(Qe,dt)|0,m=m+Math.imul(Ke,ht)|0,O=O+Math.imul(Ke,dt)|0,N=N+Math.imul(It,gt)|0,m=m+Math.imul(It,pt)|0,m=m+Math.imul(Tt,gt)|0,O=O+Math.imul(Tt,pt)|0;var dw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(dw>>>26)|0,dw&=67108863,N=Math.imul(We,ht),m=Math.imul(We,dt),m=m+Math.imul($e,ht)|0,O=Math.imul($e,dt),N=N+Math.imul(Qe,gt)|0,m=m+Math.imul(Qe,pt)|0,m=m+Math.imul(Ke,gt)|0,O=O+Math.imul(Ke,pt)|0;var gw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(gw>>>26)|0,gw&=67108863,N=Math.imul(We,gt),m=Math.imul(We,pt),m=m+Math.imul($e,gt)|0,O=Math.imul($e,pt);var pw=(M+N|0)+((m&8191)<<13)|0;return M=(O+(m>>>13)|0)+(pw>>>26)|0,pw&=67108863,_[0]=vn,_[1]=An,_[2]=En,_[3]=bn,_[4]=Sn,_[5]=In,_[6]=da,_[7]=ga,_[8]=pa,_[9]=ma,_[10]=ya,_[11]=wa,_[12]=va,_[13]=Aa,_[14]=Ea,_[15]=hw,_[16]=dw,_[17]=gw,_[18]=pw,M!==0&&(_[19]=M,y.length++),y};Math.imul||(U=V);function Q(l,g,y){y.negative=g.negative^l.negative,y.length=l.length+g.length;for(var E=0,S=0,_=0;_>>26)|0,S+=M>>>26,M&=67108863}y.words[_]=N,E=M,M=S}return E!==0?y.words[_]=E:y.length--,y._strip()}function L(l,g,y){return Q(l,g,y)}s.prototype.mulTo=function(l,g){var y,E=this.length+l.length;return this.length===10&&l.length===10?y=U(this,l,g):E<63?y=V(this,l,g):E<1024?y=Q(this,l,g):y=L(this,l,g),y},s.prototype.mul=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),this.mulTo(l,g)},s.prototype.mulf=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),L(this,l,g)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var g=l<0;g&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var y=0,E=0;E>=26,y+=S/67108864|0,y+=_>>>26,this.words[E]=_&67108863}return y!==0&&(this.words[E]=y,this.length++),g?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var g=R(l);if(g.length===0)return new s(1);for(var y=this,E=0;E=0);var g=l%26,y=(l-g)/26,E=67108863>>>26-g<<26-g,S;if(g!==0){var _=0;for(S=0;S>>26-g}_&&(this.words[S]=_,this.length++)}if(y!==0){for(S=this.length-1;S>=0;S--)this.words[S+y]=this.words[S];for(S=0;S=0);var E;g?E=(g-g%26)/26:E=0;var S=l%26,_=Math.min((l-S)/26,this.length),M=67108863^67108863>>>S<_)for(this.length-=_,m=0;m=0&&(O!==0||m>=E);m--){var Y=this.words[m]|0;this.words[m]=O<<26-S|Y>>>S,O=Y&M}return N&&O!==0&&(N.words[N.length++]=O),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,g,y){return n(this.negative===0),this.iushrn(l,g,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var g=l%26,y=(l-g)/26,E=1<=0);var g=l%26,y=(l-g)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(g!==0&&y++,this.length=Math.min(y,this.length),g!==0){var E=67108863^67108863>>>g<=67108864;g++)this.words[g]-=67108864,g===this.length-1?this.words[g+1]=1:this.words[g+1]++;return this.length=Math.max(this.length,g+1),this},s.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var g=0;g>26)-(N/67108864|0),this.words[S+y]=_&67108863}for(;S>26,this.words[S+y]=_&67108863;if(M===0)return this._strip();for(n(M===-1),M=0,S=0;S>26,this.words[S]=_&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,g){var y=this.length-l.length,E=this.clone(),S=l,_=S.words[S.length-1]|0,M=this._countBits(_);y=26-M,y!==0&&(S=S.ushln(y),E.iushln(y),_=S.words[S.length-1]|0);var N=E.length-S.length,m;if(g!=="mod"){m=new s(null),m.length=N+1,m.words=new Array(m.length);for(var O=0;O=0;$--){var b=(E.words[S.length+$]|0)*67108864+(E.words[S.length+$-1]|0);for(b=Math.min(b/_|0,67108863),E._ishlnsubmul(S,b,$);E.negative!==0;)b--,E.negative=0,E._ishlnsubmul(S,1,$),E.isZero()||(E.negative^=1);m&&(m.words[$]=b)}return m&&m._strip(),E._strip(),g!=="div"&&y!==0&&E.iushrn(y),{div:m||null,mod:E}},s.prototype.divmod=function(l,g,y){if(n(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,S,_;return this.negative!==0&&l.negative===0?(_=this.neg().divmod(l,g),g!=="mod"&&(E=_.div.neg()),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.iadd(l)),{div:E,mod:S}):this.negative===0&&l.negative!==0?(_=this.divmod(l.neg(),g),g!=="mod"&&(E=_.div.neg()),{div:E,mod:_.mod}):this.negative&l.negative?(_=this.neg().divmod(l.neg(),g),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.isub(l)),{div:_.div,mod:S}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?g==="div"?{div:this.divn(l.words[0]),mod:null}:g==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,g)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var g=this.divmod(l);if(g.mod.isZero())return g.div;var y=g.div.negative!==0?g.mod.isub(l):g.mod,E=l.ushrn(1),S=l.andln(1),_=y.cmp(E);return _<0||S===1&&_===0?g.div:g.div.negative!==0?g.div.isubn(1):g.div.iaddn(1)},s.prototype.modrn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=(1<<26)%l,E=0,S=this.length-1;S>=0;S--)E=(y*E+(this.words[S]|0))%l;return g?-E:E},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=0,E=this.length-1;E>=0;E--){var S=(this.words[E]|0)+y*67108864;this.words[E]=S/l|0,y=S%l}return this._strip(),g?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=new s(0),M=new s(1),N=0;g.isEven()&&y.isEven();)g.iushrn(1),y.iushrn(1),++N;for(var m=y.clone(),O=g.clone();!g.isZero();){for(var Y=0,$=1;!(g.words[0]&$)&&Y<26;++Y,$<<=1);if(Y>0)for(g.iushrn(Y);Y-- >0;)(E.isOdd()||S.isOdd())&&(E.iadd(m),S.isub(O)),E.iushrn(1),S.iushrn(1);for(var b=0,j=1;!(y.words[0]&j)&&b<26;++b,j<<=1);if(b>0)for(y.iushrn(b);b-- >0;)(_.isOdd()||M.isOdd())&&(_.iadd(m),M.isub(O)),_.iushrn(1),M.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(_),S.isub(M)):(y.isub(g),_.isub(E),M.isub(S))}return{a:_,b:M,gcd:y.iushln(N)}},s.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=y.clone();g.cmpn(1)>0&&y.cmpn(1)>0;){for(var M=0,N=1;!(g.words[0]&N)&&M<26;++M,N<<=1);if(M>0)for(g.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(_),E.iushrn(1);for(var m=0,O=1;!(y.words[0]&O)&&m<26;++m,O<<=1);if(m>0)for(y.iushrn(m);m-- >0;)S.isOdd()&&S.iadd(_),S.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(S)):(y.isub(g),S.isub(E))}var Y;return g.cmpn(1)===0?Y=E:Y=S,Y.cmpn(0)<0&&Y.iadd(l),Y},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var g=this.clone(),y=l.clone();g.negative=0,y.negative=0;for(var E=0;g.isEven()&&y.isEven();E++)g.iushrn(1),y.iushrn(1);do{for(;g.isEven();)g.iushrn(1);for(;y.isEven();)y.iushrn(1);var S=g.cmp(y);if(S<0){var _=g;g=y,y=_}else if(S===0||y.cmpn(1)===0)break;g.isub(y)}while(!0);return y.iushln(E)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){n(typeof l=="number");var g=l%26,y=(l-g)/26,E=1<>>26,M&=67108863,this.words[_]=M}return S!==0&&(this.words[_]=S,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var g=l<0;if(this.negative!==0&&!g)return-1;if(this.negative===0&&g)return 1;this._strip();var y;if(this.length>1)y=1;else{g&&(l=-l),n(l<=67108863,"Number is too big");var E=this.words[0]|0;y=E===l?0:El.length)return 1;if(this.length=0;y--){var E=this.words[y]|0,S=l.words[y]|0;if(E!==S){ES&&(g=1);break}}return g},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new F(l)},s.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var k={k256:null,p224:null,p192:null,p25519:null};function H(l,g){this.name=l,this.p=new s(g,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},H.prototype.ireduce=function(l){var g=l,y;do this.split(g,this.tmp),g=this.imulK(g),g=g.iadd(this.tmp),y=g.bitLength();while(y>this.n);var E=y0?g.isub(this.p):g.strip!==void 0?g.strip():g._strip(),g},H.prototype.split=function(l,g){l.iushrn(this.n,0,g)},H.prototype.imulK=function(l){return l.imul(this.k)};function q(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(q,H),q.prototype.split=function(l,g){for(var y=4194303,E=Math.min(l.length,9),S=0;S>>22,_=M}_>>>=22,l.words[S-10]=_,_===0&&l.length>10?l.length-=10:l.length-=9},q.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var g=0,y=0;y>>=26,l.words[y]=S,g=E}return g!==0&&(l.words[l.length++]=g),l},s._prime=function(l){if(k[l])return k[l];var g;if(l==="k256")g=new q;else if(l==="p224")g=new v;else if(l==="p192")g=new C;else if(l==="p25519")g=new D;else throw new Error("Unknown prime "+l);return k[l]=g,g};function F(l){if(typeof l=="string"){var g=s._prime(l);this.m=g.p,this.prime=g}else n(l.gtn(1),"modulus must be greater than 1"),this.m=l,this.prime=null}F.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},F.prototype._verify2=function(l,g){n((l.negative|g.negative)===0,"red works only with positives"),n(l.red&&l.red===g.red,"red works only with red numbers")},F.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(f(l,l.umod(this.m)._forceRed(this)),l)},F.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},F.prototype.add=function(l,g){this._verify2(l,g);var y=l.add(g);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},F.prototype.iadd=function(l,g){this._verify2(l,g);var y=l.iadd(g);return y.cmp(this.m)>=0&&y.isub(this.m),y},F.prototype.sub=function(l,g){this._verify2(l,g);var y=l.sub(g);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},F.prototype.isub=function(l,g){this._verify2(l,g);var y=l.isub(g);return y.cmpn(0)<0&&y.iadd(this.m),y},F.prototype.shl=function(l,g){return this._verify1(l),this.imod(l.ushln(g))},F.prototype.imul=function(l,g){return this._verify2(l,g),this.imod(l.imul(g))},F.prototype.mul=function(l,g){return this._verify2(l,g),this.imod(l.mul(g))},F.prototype.isqr=function(l){return this.imul(l,l.clone())},F.prototype.sqr=function(l){return this.mul(l,l)},F.prototype.sqrt=function(l){if(l.isZero())return l.clone();var g=this.m.andln(3);if(n(g%2===1),g===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var E=this.m.subn(1),S=0;!E.isZero()&&E.andln(1)===0;)S++,E.iushrn(1);n(!E.isZero());var _=new s(1).toRed(this),M=_.redNeg(),N=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,N).cmp(M)!==0;)m.redIAdd(M);for(var O=this.pow(m,E),Y=this.pow(l,E.addn(1).iushrn(1)),$=this.pow(l,E),b=S;$.cmp(_)!==0;){for(var j=$,z=0;j.cmp(_)!==0;z++)j=j.redSqr();n(z=0;S--){for(var O=g.words[S],Y=m-1;Y>=0;Y--){var $=O>>Y&1;if(_!==E[0]&&(_=this.sqr(_)),$===0&&M===0){N=0;continue}M<<=1,M|=$,N++,!(N!==y&&(S!==0||Y!==0))&&(_=this.mul(_,E[M]),N=0,M=0)}m=26}return _},F.prototype.convertTo=function(l){var g=l.umod(this.m);return g===l?g.clone():g},F.prototype.convertFrom=function(l){var g=l.clone();return g.red=null,g},s.mont=function(l){return new P(l)};function P(l){F.call(this,l),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(P,F),P.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},P.prototype.convertFrom=function(l){var g=this.imod(l.mul(this.rinv));return g.red=null,g},P.prototype.imul=function(l,g){if(l.isZero()||g.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.mul=function(l,g){if(l.isZero()||g.isZero())return new s(0)._forceRed(this);var y=l.mul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.invm=function(l){var g=this.imod(l._invmp(this.m).mul(this.r2));return g._forceRed(this)}})(t,g4)})(w4);var Se=w4.exports,v4="bignumber/5.7.0",Jm=Se.BN,Ks=new kt(v4),hT={},TM=9007199254740991;function Lte(t){return t!=null&&(Cr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||gn(t)||typeof t=="bigint"||ul(t))}var _M=!1,Cr=class t{constructor(e,r){e!==hT&&Ks.throwError("cannot call constructor directly; use BigNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return sn(De(this).fromTwos(e))}toTwos(e){return sn(De(this).toTwos(e))}abs(){return this._hex[0]==="-"?t.from(this._hex.substring(1)):this}add(e){return sn(De(this).add(De(e)))}sub(e){return sn(De(this).sub(De(e)))}div(e){return t.from(e).isZero()&&Kn("division-by-zero","div"),sn(De(this).div(De(e)))}mul(e){return sn(De(this).mul(De(e)))}mod(e){let r=De(e);return r.isNeg()&&Kn("division-by-zero","mod"),sn(De(this).umod(r))}pow(e){let r=De(e);return r.isNeg()&&Kn("negative-power","pow"),sn(De(this).pow(r))}and(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","and"),sn(De(this).and(r))}or(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","or"),sn(De(this).or(r))}xor(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","xor"),sn(De(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Kn("negative-width","mask"),sn(De(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Kn("negative-width","shl"),sn(De(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Kn("negative-width","shr"),sn(De(this).shrn(e))}eq(e){return De(this).eq(De(e))}lt(e){return De(this).lt(De(e))}lte(e){return De(this).lte(De(e))}gt(e){return De(this).gt(De(e))}gte(e){return De(this).gte(De(e))}isNegative(){return this._hex[0]==="-"}isZero(){return De(this).isZero()}toNumber(){try{return De(this).toNumber()}catch{Kn("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ks.throwError("this platform does not support BigInt",kt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?_M||(_M=!0,Ks.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ks.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",kt.errors.UNEXPECTED_ARGUMENT,{}):Ks.throwError("BigNumber.toString does not accept parameters",kt.errors.UNEXPECTED_ARGUMENT,{})),De(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof t)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new t(hT,Vh(e)):e.match(/^-?[0-9]+$/)?new t(hT,Vh(new Jm(e))):Ks.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Kn("underflow","BigNumber.from",e),(e>=TM||e<=-TM)&&Kn("overflow","BigNumber.from",e),t.from(String(e));let r=e;if(typeof r=="bigint")return t.from(r.toString());if(ul(r))return t.from(kr(r));if(r)if(r.toHexString){let n=r.toHexString();if(typeof n=="string")return t.from(n)}else{let n=r._hex;if(n==null&&r.type==="BigNumber"&&(n=r.hex),typeof n=="string"&&(gn(n)||n[0]==="-"&&gn(n.substring(1))))return t.from(n)}return Ks.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}};function Vh(t){if(typeof t!="string")return Vh(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ks.throwArgumentError("invalid hex","value",t),t=Vh(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function sn(t){return Cr.from(Vh(t))}function De(t){let e=Cr.from(t).toHexString();return e[0]==="-"?new Jm("-"+e.substring(3),16):new Jm(e.substring(2),16)}function Kn(t,e,r){let n={fault:t,operation:e};return r!=null&&(n.value=r),Ks.throwError(t,kt.errors.NUMERIC_FAULT,n)}function Fte(t){return new Jm(t,36).toString(16)}var Hr=new kt(v4),Fh={},A4=Cr.from(0),E4=Cr.from(-1);function b4(t,e,r,n){let i={fault:e,operation:r};return n!==void 0&&(i.value=n),Hr.throwError(t,kt.errors.NUMERIC_FAULT,i)}var Uh="0";for(;Uh.length<256;)Uh+=Uh;function GT(t){if(typeof t!="number")try{t=Cr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+Uh.substring(0,t):Hr.throwArgumentError("invalid decimal size","decimals",t)}function dT(t,e){e==null&&(e=0);let r=GT(e);t=Cr.from(t);let n=t.lt(A4);n&&(t=t.mul(E4));let i=t.mod(r).toString();for(;i.length2&&Hr.throwArgumentError("too many decimal points","value",t);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");o[o.length-1]==="0";)o=o.substring(0,o.length-1);for(o.length>r.length-1&&b4("fractional component exceeds decimals","underflow","parseFixed"),o===""&&(o="0");o.lengthe[o]==null?a:(typeof e[o]!==u&&Hr.throwArgumentError("invalid fixed format ("+o+" not "+u+")","format."+o,e[o]),e[o]);r=s("signed","boolean",r),n=s("width","number",n),i=s("decimals","number",i)}return n%8&&Hr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),i>80&&Hr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",i),new t(Fh,r,n,i)}},Xm=class t{constructor(e,r,n,i){e!==Fh&&Hr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=r,this._value=n,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Hr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.add(n),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.sub(n),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return this.isNegative()&&n&&(r=r.subUnsafe(CM.toFormat(r.format))),r}ceiling(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return!this.isNegative()&&n&&(r=r.addUnsafe(CM.toFormat(r.format))),r}round(e){e==null&&(e=0);let r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&Hr.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;let n=t.from("1"+Uh.substring(0,e),this.format),i=Ute.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(i).floor().divUnsafe(n)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Hr.throwArgumentError("invalid byte width","width",e);let r=Cr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return fs(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return t.fromString(this._value,e)}static fromValue(e,r,n){return n==null&&r!=null&&!Lte(r)&&(n=r,r=null),r==null&&(r=0),n==null&&(n="fixed"),t.fromString(dT(e,r),qh.from(n))}static fromString(e,r){r==null&&(r="fixed");let n=qh.from(r),i=Qs(e,n.decimals);!n.signed&&i.lt(A4)&&b4("unsigned value cannot be negative","overflow","value",e);let s=null;n.signed?s=i.toTwos(n.width).toHexString():(s=i.toHexString(),s=fs(s,n.width/8));let o=dT(i,n.decimals);return new t(Fh,s,o,n)}static fromBytes(e,r){r==null&&(r="fixed");let n=qh.from(r);if(Qt(e).length>n.width/8)throw new Error("overflow");let i=Cr.from(e);n.signed&&(i=i.fromTwos(n.width));let s=i.toTwos((n.signed?0:1)+n.width).toHexString(),o=dT(i,n.decimals);return new t(Fh,s,o,n)}static from(e,r){if(typeof e=="string")return t.fromString(e,r);if(ul(e))return t.fromBytes(e,r);try{return t.fromValue(e,0,r)}catch(n){if(n.code!==kt.errors.INVALID_ARGUMENT)throw n}return Hr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}},CM=Xm.from(1),Ute=Xm.from("0.5"),qte="strings/5.7.0",S4=new kt(qte),Zm;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(Zm||(Zm={}));var rl;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(rl||(rl={}));function Vte(t,e,r,n,i){return S4.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function I4(t,e,r,n,i){if(t===rl.BAD_PREFIX||t===rl.UNEXPECTED_CONTINUE){let s=0;for(let o=e+1;o>6===2;o++)s++;return s}return t===rl.OVERRUN?r.length-e-1:0}function kte(t,e,r,n,i){return t===rl.OVERLONG?(n.push(i),0):(n.push(65533),I4(t,e,r))}Object.freeze({error:Vte,ignore:I4,replace:kte});function gT(t,e=Zm.current){e!=Zm.current&&(S4.checkNormalize(),t=t.normalize(e));let r=[];for(let n=0;n>6|192),r.push(i&63|128);else if((i&64512)==55296){n++;let s=t.charCodeAt(n);if(n>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");let o=65536+((i&1023)<<10)+(s&1023);r.push(o>>18|240),r.push(o>>12&63|128),r.push(o>>6&63|128),r.push(o&63|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(i&63|128)}return Qt(r)}function Hte(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r{let s=i.split(":");r+=parseInt(s[0],16),n[r]=e(s[1])}),n}function NM(t){let e=0;return t.split(",").map(r=>{let n=r.split("-");n.length===1?n[1]="0":n[1]===""&&(n[1]="1");let i=e+parseInt(n[0],16);return e=parseInt(n[1],16),{l:i,h:e}})}NM("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),pT("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),pT("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),pT("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",Hte),NM("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");var T4="hash/5.7.0";function Gte(t){t=atob(t);let e=[];for(let r=0;r0&&Array.isArray(u)?i(u,o-1):r.push(u)})};return i(t,e),r}function jte(t){let e={};for(let r=0;r>--a&1}let d=31,w=Math.pow(2,d),A=w>>>1,T=A>>1,x=w-1,R=0;for(let k=0;k1;){let D=H+q>>>1;k>>1|f(),v=v<<1^A,C=(C^A)<<1|A|1;U=v,Q=1+C-v}let L=n-4;return V.map(k=>{switch(k-L){case 3:return L+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return L+256+(t[u++]<<8|t[u++]);case 1:return L+t[u++];default:return k-1}})}function Qte(t){let e=0;return()=>t[e++]}function Kte(t){return Qte(zte(t))}function Wte(t){return t&1?~t>>1:t>>1}function $te(t,e){let r=Array(t);for(let n=0;ne[o]):r}function Jte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(Zte(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(ere(r,t))}return jte(_4(e))}function Xte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function C4(t,e,r){let n=Array(t).fill(void 0).map(()=>[]);for(let i=0;in[o].push(s));return n}function Zte(t,e){let r=1+e(),n=e(),i=Xte(e),s=C4(i.length,1+t,e);return _4(s.map((o,u)=>{let a=o[0],c=o.slice(1);return Array(i[u]).fill(void 0).map((f,d)=>{let w=d*n;return[a+d*r,c.map(A=>A+w)]})}))}function ere(t,e){let r=1+e();return C4(r,1+t,e).map(n=>[n[0],n.slice(1)])}function tre(t){let e=ey(t).sort((n,i)=>n-i);return r();function r(){let n=[];for(;;){let c=ey(t,e);if(c.length==0)break;n.push({set:new Set(c),node:r()})}n.sort((c,f)=>f.set.size-c.set.size);let i=t(),s=i%3;i=i/3|0;let o=!!(i&1);i>>=1;let u=i==1,a=i==2;return{branches:n,valid:s,fe0f:o,save:u,check:a}}}function rre(){return Kte(Gte("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}var km=rre();new Set(ey(km)),new Set(ey(km)),Jte(km),tre(km),new kt(T4);var nre=new Uint8Array(32);nre.fill(0);var ire=`Ethereum Signed Message: +`;function N4(t){return typeof t=="string"&&(t=gT(t)),HT(Ote([gT(ire),gT(String(t.length)),t]))}var sre="rlp/5.7.0";new kt(sre);var ore="address/5.7.0",Lh=new kt(ore);function OM(t){gn(t,20)||Lh.throwArgumentError("invalid address","address",t),t=t.toLowerCase();let e=t.substring(2).split(""),r=new Uint8Array(40);for(let i=0;i<40;i++)r[i]=e[i].charCodeAt(0);let n=Qt(HT(r));for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&(e[i]=e[i].toUpperCase()),(n[i>>1]&15)>=8&&(e[i+1]=e[i+1].toUpperCase());return"0x"+e.join("")}var are=9007199254740991;function ure(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}var jT={};for(let t=0;t<10;t++)jT[String(t)]=String(t);for(let t=0;t<26;t++)jT[String.fromCharCode(65+t)]=String(10+t);var DM=Math.floor(ure(are));function cre(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(n=>jT[n]).join("");for(;e.length>=DM;){let n=e.substring(0,DM);e=parseInt(n,10)%97+e.substring(n.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function lre(t){let e=null;if(typeof t!="string"&&Lh.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=OM(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&Lh.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==cre(t)&&Lh.throwArgumentError("bad icap checksum","address",t),e=Fte(t.substring(4));e.length<40;)e="0"+e;e=OM("0x"+e)}else Lh.throwArgumentError("invalid address","address",t);return e}var fre="properties/5.7.0";new kt(fre);function Rh(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new kt(T4);var hre=new Uint8Array(32);hre.fill(0),Cr.from(-1);var dre=Cr.from(0),gre=Cr.from(1);Cr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fs(gre.toHexString(),32),fs(dre.toHexString(),32);var os={},Pe={},Gh=x4;function x4(t,e){if(!t)throw new Error(e||"Assertion failed")}x4.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var CT={exports:{}};typeof Object.create=="function"?CT.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:CT.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var pre=Gh,mre=CT.exports;Pe.inherits=mre;function yre(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function wre(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),i=0;i>6|192,r[n++]=s&63|128):yre(t,i)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023),r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128)}else for(i=0;i>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Pe.htonl=O4;function Are(t,e){for(var r="",n=0;n>>0}return s}Pe.join32=Ere;function bre(t,e){for(var r=new Array(t.length*4),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=s&255):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=s&255)}return r}Pe.split32=bre;function Sre(t,e){return t>>>e|t<<32-e}Pe.rotr32=Sre;function Ire(t,e){return t<>>32-e}Pe.rotl32=Ire;function Tre(t,e){return t+e>>>0}Pe.sum32=Tre;function _re(t,e,r){return t+e+r>>>0}Pe.sum32_3=_re;function Cre(t,e,r,n){return t+e+r+n>>>0}Pe.sum32_4=Cre;function Nre(t,e,r,n,i){return t+e+r+n+i>>>0}Pe.sum32_5=Nre;function xre(t,e,r,n){var i=t[e],s=t[e+1],o=n+s>>>0,u=(o>>0,t[e+1]=o}Pe.sum64=xre;function Ore(t,e,r,n){var i=e+n>>>0,s=(i>>0}Pe.sum64_hi=Ore;function Dre(t,e,r,n){var i=e+n;return i>>>0}Pe.sum64_lo=Dre;function Pre(t,e,r,n,i,s,o,u){var a=0,c=e;c=c+n>>>0,a+=c>>0,a+=c>>0,a+=c>>0}Pe.sum64_4_hi=Pre;function Rre(t,e,r,n,i,s,o,u){var a=e+n+s+u;return a>>>0}Pe.sum64_4_lo=Rre;function Bre(t,e,r,n,i,s,o,u,a,c){var f=0,d=e;d=d+n>>>0,f+=d>>0,f+=d>>0,f+=d>>0,f+=d>>0}Pe.sum64_5_hi=Bre;function Mre(t,e,r,n,i,s,o,u,a,c){var f=e+n+s+u+c;return f>>>0}Pe.sum64_5_lo=Mre;function Lre(t,e,r){var n=e<<32-r|t>>>r;return n>>>0}Pe.rotr64_hi=Lre;function Fre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.rotr64_lo=Fre;function Ure(t,e,r){return t>>>r}Pe.shr64_hi=Ure;function qre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.shr64_lo=qre;var cl={},PM=Pe,Vre=Gh;function Hm(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}cl.BlockHash=Hm,Hm.prototype.update=function(t,e){if(t=PM.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=PM.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=t&255}else for(n[i++]=t&255,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s>>3}ms.g0_256=zre;function Qre(t){return hs(t,17)^hs(t,19)^t>>>10}ms.g1_256=Qre;var sl=Pe,Kre=cl,Wre=ms,mT=sl.rotl32,Bh=sl.sum32,$re=sl.sum32_5,Yre=Wre.ft_1,L4=Kre.BlockHash,Jre=[1518500249,1859775393,2400959708,3395469782];function us(){if(!(this instanceof us))return new us;L4.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}sl.inherits(us,L4);var Xre=us;us.blockSize=512,us.outSize=160,us.hmacStrength=80,us.padLength=64,us.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=new this.Hash().update(t).digest()),qne(t.length<=this.blockSize);for(var e=t.length;e>8,w=f&255;d?a.push(d,w):a.push(w)}return a}r.toArray=n;function i(o){return o.length===1?"0"+o:o}r.zero2=i;function s(o){for(var u="",a=0;a(w>>1)-1?x=(w>>1)-R:x=R,A.isubn(x)):x=0,d[T]=x,A.iushrn(1)}return d}r.getNAF=n;function i(a,c){var f=[[],[]];a=a.clone(),c=c.clone();for(var d=0,w=0,A;a.cmpn(-d)>0||c.cmpn(-w)>0;){var T=a.andln(3)+d&3,x=c.andln(3)+w&3;T===3&&(T=-1),x===3&&(x=-1);var R;T&1?(A=a.andln(7)+d&7,(A===3||A===5)&&x===2?R=-T:R=T):R=0,f[0].push(R);var V;x&1?(A=c.andln(7)+w&7,(A===3||A===5)&&T===2?V=-x:V=x):V=0,f[1].push(V),2*d===R+1&&(d=1-d),2*w===V+1&&(w=1-w),a.iushrn(1),c.iushrn(1)}return f}r.getJSF=i;function s(a,c,f){var d="_"+c;a.prototype[c]=function(){return this[d]!==void 0?this[d]:this[d]=f.call(this)}}r.cachedProperty=s;function o(a){return typeof a=="string"?r.toArray(a,"hex"):a}r.parseBytes=o;function u(a){return new Se(a,"hex","le")}r.intFromLE=u}),jm=pn.getNAF,Hne=pn.getJSF,ty=pn.assert;function Vo(t,e){this.type=t,this.p=new Se(e.p,16),this.red=e.prime?Se.red(e.prime):Se.mont(this.p),this.zero=new Se(0).toRed(this.red),this.one=new Se(1).toRed(this.red),this.two=new Se(2).toRed(this.red),this.n=e.n&&new Se(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var nu=Vo;Vo.prototype.point=function(){throw new Error("Not implemented")},Vo.prototype.validate=function(){throw new Error("Not implemented")},Vo.prototype._fixedNafMul=function(t,e){ty(t.precomputed);var r=t._getDoubles(),n=jm(e,1,this._bitLength),i=(1<=o;a--)u=(u<<1)+n[a];s.push(u)}for(var c=this.jpoint(null,null,null),f=this.jpoint(null,null,null),d=i;d>0;d--){for(o=0;o=0;u--){for(var a=0;u>=0&&s[u]===0;u--)a++;if(u>=0&&a++,o=o.dblp(a),u<0)break;var c=s[u];ty(c!==0),t.type==="affine"?c>0?o=o.mixedAdd(i[c-1>>1]):o=o.mixedAdd(i[-c-1>>1].neg()):c>0?o=o.add(i[c-1>>1]):o=o.add(i[-c-1>>1].neg())}return t.type==="affine"?o.toP():o},Vo.prototype._wnafMulAdd=function(t,e,r,n,i){var s=this._wnafT1,o=this._wnafT2,u=this._wnafT3,a=0,c,f,d;for(c=0;c=1;c-=2){var A=c-1,T=c;if(s[A]!==1||s[T]!==1){u[A]=jm(r[A],s[A],this._bitLength),u[T]=jm(r[T],s[T],this._bitLength),a=Math.max(u[A].length,a),a=Math.max(u[T].length,a);continue}var x=[e[A],null,null,e[T]];e[A].y.cmp(e[T].y)===0?(x[1]=e[A].add(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg())):e[A].y.cmp(e[T].y.redNeg())===0?(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].add(e[T].neg())):(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg()));var R=[-3,-1,-5,-7,0,7,5,1,3],V=Hne(r[A],r[T]);for(a=Math.max(V[0].length,a),u[A]=new Array(a),u[T]=new Array(a),f=0;f=0;c--){for(var H=0;c>=0;){var q=!0;for(f=0;f=0&&H++,L=L.dblp(H),c<0)break;for(f=0;f0?d=o[f][v-1>>1]:v<0&&(d=o[f][-v-1>>1].neg()),d.type==="affine"?L=L.mixedAdd(d):L=L.add(d))}}for(c=0;c=Math.ceil((t.bitLength()+1)/e.step):!1},Wn.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(w=a,A=c),f.negative&&(f=f.neg(),d=d.neg()),w.negative&&(w=w.neg(),A=A.neg()),[{a:f,b:d},{a:w,b:A}]},Yn.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),u=s.mul(n.a),a=i.mul(r.b),c=s.mul(n.b),f=t.sub(o).sub(u),d=a.add(c).neg();return{k1:f,k2:d}},Yn.prototype.pointFromX=function(t,e){t=new Se(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(n.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},Yn.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return r.redSqr().redISub(i).cmpn(0)===0},Yn.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Ar.prototype.isInfinity=function(){return this.inf},Ar.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Ar.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Ar.prototype.getX=function(){return this.x.fromRed()},Ar.prototype.getY=function(){return this.y.fromRed()},Ar.prototype.mul=function(t){return t=new Se(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Ar.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Ar.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Ar.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Ar.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(i){return i.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Ar.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function _r(t,e,r,n){nu.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&n===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Se(0)):(this.x=new Se(e,16),this.y=new Se(r,16),this.z=new Se(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}QT(_r,nu.BasePoint),Yn.prototype.jpoint=function(t,e,r){return new _r(this,t,e,r)},_r.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},_r.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_r.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=s.redSub(o);if(u.cmpn(0)===0)return a.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var c=u.redSqr(),f=c.redMul(u),d=n.redMul(c),w=a.redSqr().redIAdd(f).redISub(d).redISub(d),A=a.redMul(d.redISub(w)).redISub(s.redMul(f)),T=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(w,A,T)},_r.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),u=i.redSub(s);if(o.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),c=a.redMul(o),f=r.redMul(a),d=u.redSqr().redIAdd(c).redISub(f).redISub(f),w=u.redMul(f.redISub(d)).redISub(i.redMul(c)),A=this.z.redMul(o);return this.curve.jpoint(d,w,A)},_r.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),this.x.cmp(r)===0)return!0}},_r.prototype.inspect=function(){return this.isInfinity()?"":""},_r.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Km=fl(function(t,e){var r=e;r.base=nu,r.short=jne,r.mont=null,r.edwards=null}),Wm=fl(function(t,e){var r=e,n=pn.assert;function i(u){u.type==="short"?this.curve=new Km.short(u):u.type==="edwards"?this.curve=new Km.edwards(u):this.curve=new Km.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=i;function s(u,a){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var c=new i(a);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:c}),c}})}s("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:os.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:os.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:os.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:os.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),s("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:os.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var o;try{o=null.crash()}catch{o=void 0}s("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:os.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",o]})});function ko(t){if(!(this instanceof ko))return new ko(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Ti.toArray(t.entropy,t.entropyEnc||"hex"),r=Ti.toArray(t.nonce,t.nonceEnc||"hex"),n=Ti.toArray(t.pers,t.persEnc||"hex");zT(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var LM=ko;ko.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},ko.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(n=r,r=e,e=null),r&&(r=Ti.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var zne=pn.assert;function sy(t,e){if(t instanceof sy)return t;this._importDER(t,e)||(zne(t.r&&t.s,"Signature without r or s"),this.r=new Se(t.r,16),this.s=new Se(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var zm=sy;function Qne(){this.place=0}function ET(t,e){var r=t[e.place++];if(!(r&128))return r;var n=r&15;if(n===0||n>4)return!1;for(var i=0,s=0,o=e.place;s>>=0;return i<=127?!1:(e.place=o,i)}function FM(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}sy.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=FM(e),r=FM(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var n=[2];bT(n,e.length),n=n.concat(e),n.push(2),bT(n,r.length);var i=n.concat(r),s=[48];return bT(s,i.length),s=s.concat(i),pn.encode(s,t)};var Kne=function(){throw new Error("unsupported")},W4=pn.assert;function $n(t){if(!(this instanceof $n))return new $n(t);typeof t=="string"&&(W4(Object.prototype.hasOwnProperty.call(Wm,t),"Unknown curve "+t),t=Wm[t]),t instanceof Wm.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Wne=$n;$n.prototype.keyPair=function(t){return new AT(this,t)},$n.prototype.keyFromPrivate=function(t,e){return AT.fromPrivate(this,t,e)},$n.prototype.keyFromPublic=function(t,e){return AT.fromPublic(this,t,e)},$n.prototype.genKeyPair=function(t){t||(t={});for(var e=new LM({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Kne(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Se(2));;){var i=new Se(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},$n.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},$n.prototype.sign=function(t,e,r,n){typeof r=="object"&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Se(t,16));for(var i=this.n.byteLength(),s=e.getPrivate().toArray("be",i),o=t.toArray("be",i),u=new LM({hash:this.hash,entropy:s,nonce:o,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Se(1)),c=0;;c++){var f=n.k?n.k(c):new Se(u.generate(this.n.byteLength()));if(f=this._truncateToN(f,!0),!(f.cmpn(1)<=0||f.cmp(a)>=0)){var d=this.g.mul(f);if(!d.isInfinity()){var w=d.getX(),A=w.umod(this.n);if(A.cmpn(0)!==0){var T=f.invm(this.n).mul(A.mul(e.getPrivate()).iadd(t));if(T=T.umod(this.n),T.cmpn(0)!==0){var x=(d.getY().isOdd()?1:0)|(w.cmp(A)!==0?2:0);return n.canonical&&T.cmp(this.nh)>0&&(T=this.n.sub(T),x^=1),new zm({r:A,s:T,recoveryParam:x})}}}}}},$n.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Se(t,16)),r=this.keyFromPublic(r,n),e=new zm(e,"hex");var i=e.r,s=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o=s.invm(this.n),u=o.mul(t).umod(this.n),a=o.mul(i).umod(this.n),c;return this.curve._maxwellTrick?(c=this.g.jmulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.eqXToP(i)):(c=this.g.mulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.getX().umod(this.n).cmp(i)===0)},$n.prototype.recoverPubKey=function(t,e,r,n){W4((3&r)===r,"The recovery param is more than two bits"),e=new zm(e,n);var i=this.n,s=new Se(t),o=e.r,u=e.s,a=r&1,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");c?o=this.curve.pointFromX(o.add(this.curve.n),a):o=this.curve.pointFromX(o,a);var f=e.r.invm(i),d=i.sub(s).mul(f).umod(i),w=u.mul(f).umod(i);return this.g.mulAdd(d,o,w)},$n.prototype.getKeyRecoveryParam=function(t,e,r,n){if(e=new zm(e,n),e.recoveryParam!==null)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch{continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var $ne=fl(function(t,e){var r=e;r.version="6.5.4",r.utils=pn,r.rand=function(){throw new Error("unsupported")},r.curve=Km,r.curves=Wm,r.ec=Wne,r.eddsa=null}),Yne=$ne.ec,Jne="signing-key/5.7.0",OT=new kt(Jne),ST=null;function ls(){return ST||(ST=new Yne("secp256k1")),ST}var DT=class{constructor(e){Rh(this,"curve","secp256k1"),Rh(this,"privateKey",kr(e)),Pte(this.privateKey)!==32&&OT.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");let r=ls().keyFromPrivate(Qt(this.privateKey));Rh(this,"publicKey","0x"+r.getPublic(!1,"hex")),Rh(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),Rh(this,"_isSigningKey",!0)}_addPoint(e){let r=ls().keyFromPublic(Qt(this.publicKey)),n=ls().keyFromPublic(Qt(e));return"0x"+r.pub.add(n.pub).encodeCompressed("hex")}signDigest(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=Qt(e);n.length!==32&&OT.throwArgumentError("bad digest length","digest",e);let i=r.sign(n,{canonical:!0});return y4({recoveryParam:i.recoveryParam,r:fs("0x"+i.r.toString(16),32),s:fs("0x"+i.s.toString(16),32)})}computeSharedSecret(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=ls().keyFromPublic(Qt($4(e)));return fs("0x"+r.derive(n.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}};function Xne(t,e){let r=y4(e),n={r:Qt(r.r),s:Qt(r.s)};return"0x"+ls().recoverPubKey(Qt(t),n,r.recoveryParam).encode("hex",!1)}function $4(t,e){let r=Qt(t);if(r.length===32){let n=new DT(r);return e?"0x"+ls().keyFromPrivate(r).getPublic(!0,"hex"):n.publicKey}else{if(r.length===33)return e?kr(r):"0x"+ls().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+ls().keyFromPublic(r).getPublic(!0,"hex"):kr(r)}return OT.throwArgumentError("invalid public or private key","key","[REDACTED]")}var Zne="transactions/5.7.0";new kt(Zne);var UM;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(UM||(UM={}));function eie(t){let e=$4(t);return lre(IM(HT(IM(e,1)),12))}function tie(t,e){return eie(Xne(Qt(t),e))}var rie="https://rpc.walletconnect.com/v1";async function Y4(t,e,r,n,i,s){switch(r.t){case"eip191":return J4(t,e,r.s);case"eip1271":return await X4(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function J4(t,e,r){return tie(N4(e),r).toLowerCase()===t.toLowerCase()}async function X4(t,e,r,n,i,s){try{let o="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",c=r.substring(2),f=N4(e).substring(2),d=o+f+u+a+c,w=await fetch(`${s||rie}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:nie(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:A}=await w.json();return A?A.slice(0,o.length).toLowerCase()===o.toLowerCase():!1}catch(o){return console.error("isValidEip1271Signature: ",o),!1}}function nie(){return Date.now()+Math.floor(Math.random()*1e3)}var iie=Object.defineProperty,sie=Object.defineProperties,oie=Object.getOwnPropertyDescriptors,qM=Object.getOwnPropertySymbols,aie=Object.prototype.hasOwnProperty,uie=Object.prototype.propertyIsEnumerable,VM=(t,e,r)=>e in t?iie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KT=(t,e)=>{for(var r in e||(e={}))aie.call(e,r)&&VM(t,r,e[r]);if(qM)for(var r of qM(e))uie.call(e,r)&&VM(t,r,e[r]);return t},Z4=(t,e)=>sie(t,oie(e)),cie="did:pkh:",oy=t=>t?.split(":"),WT=t=>{let e=t&&oy(t);if(e)return t.includes(cie)?e[3]:e[1]},lie=t=>{let e=t&&oy(t);if(e)return e[2]+":"+e[3]},$T=t=>{let e=t&&oy(t);if(e)return e.pop()};async function fie(t){let{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=e5(i,i.iss),o=$T(i.iss);return await Y4(o,s,n,WT(i.iss),r)}var e5=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=$T(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0,s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,u=`Chain ID: ${WT(e)}`,a=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources?`Resources:${t.resources.map(w=>` +- ${w}`).join("")}`:void 0,d=uy(t.resources);if(d){let w=jo(d);i=XT(i,w)}return[r,n,"",i,"",s,o,u,a,c,f].filter(w=>w!=null).join(` +`)};function hie(t,e,r){return r.includes("did:pkh:")||(r=`did:pkh:${r}`),{h:{t:"caip122"},p:{iss:r,domain:t.domain,aud:t.aud,version:t.version,nonce:t.nonce,iat:t.iat,statement:t.statement,requestId:t.requestId,resources:t.resources,nbf:t.nbf,exp:t.exp},s:e}}function die(t){var e;let{authPayload:r,chains:n,methods:i}=t,s=r.statement||"";if(!(n!=null&&n.length))return r;let o=r.chains,u=TT(o,n);if(!(u!=null&&u.length))throw new Error("No supported chains");let a=t5(r.resources);if(!a)return r;ps(a);let c=r5(a,"eip155"),f=r?.resources||[];if(c!=null&&c.length){let d=n5(c),w=TT(d,i);if(!(w!=null&&w.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(d)}, supported: ${JSON.stringify(i)}`);let A=YT("request",w,{chains:u}),T=a5(a,"eip155",A);f=((e=r?.resources)==null?void 0:e.slice(0,-1))||[],f.push(ay(T))}return Z4(KT({},r),{statement:c5(s,uy(f)),chains:u,resources:r!=null&&r.resources||f.length>0?f:void 0})}function t5(t){let e=uy(t);if(e&&JT(e))return jo(e)}function gie(t,e){var r;return(r=t?.att)==null?void 0:r.hasOwnProperty(e)}function r5(t,e){var r,n;return(r=t?.att)!=null&&r[e]?Object.keys((n=t?.att)==null?void 0:n[e]):[]}function pie(t){return t?.map(e=>Object.keys(e))||[]}function n5(t){return t?.map(e=>{var r;return(r=e.split("/"))==null?void 0:r[1]})||[]}function i5(t){return p.Buffer.from(JSON.stringify(t)).toString("base64")}function s5(t){return JSON.parse(p.Buffer.from(t,"base64").toString("utf-8"))}function ps(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");let e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{let n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{let s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function o5(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:YT(e,r,n)}}}function a5(t,e,r){var n;return t.att[e]=KT({},r),((n=Object.keys(t.att))==null?void 0:n.sort((i,s)=>i.localeCompare(s))).reduce((i,s)=>(i.att[s]=t.att[s],i),{att:{}})}function YT(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));let n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function ay(t){return ps(t),`urn:recap:${i5(t).replace(/=/g,"")}`}function jo(t){let e=s5(t.replace("urn:recap:",""));return ps(e),e}function mie(t,e,r){let n=o5(t,e,r);return ay(n)}function JT(t){return t&&t.includes("urn:recap:")}function yie(t,e){let r=jo(t),n=jo(e),i=u5(r,n);return ay(i)}function u5(t,e){ps(t),ps(e);let r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((u,a)=>u.localeCompare(a)).forEach(u=>{var a,c;n.att[i]=Z4(KT({},n.att[i]),{[u]:((a=t.att[i])==null?void 0:a[u])||((c=e.att[i])==null?void 0:c[u])})})}),n}function XT(t="",e){ps(e);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;let n=[],i=0;Object.keys(e.att).forEach(u=>{let a=Object.keys(e.att[u]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));a.sort((d,w)=>d.action.localeCompare(w.action));let c={};a.forEach(d=>{c[d.ability]||(c[d.ability]=[]),c[d.ability].push(d.action)});let f=Object.keys(c).map(d=>(i++,`(${i}) '${d}': '${c[d].join("', '")}' for '${u}'.`));n.push(f.join(", ").replace(".,","."))});let s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function wie(t){var e;let r=jo(t);ps(r);let n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function vie(t){let e=jo(t);ps(e);let r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function c5(t,e){if(!e)return t;let r=jo(e);return ps(r),XT(t,r)}function uy(t){if(!t)return;let e=t?.[t.length-1];return JT(e)?e:void 0}var ZT="base10",jr="base16",ry="base64pad",cy="utf8",e_=0,hl=1,Aie=0,kM=1,PT=12,t_=32;function Eie(){let t=JM.generateKeyPair();return{privateKey:Vt.toString(t.secretKey,jr),publicKey:Vt.toString(t.publicKey,jr)}}function bie(){let t=$M.randomBytes(t_);return Vt.toString(t,jr)}function Sie(t,e){let r=JM.sharedKey(Vt.fromString(t,jr),Vt.fromString(e,jr),!0),n=new Gee.HKDF(LT.SHA256,r).expand(t_);return Vt.toString(n,jr)}function Iie(t){let e=LT.hash(Vt.fromString(t,jr));return Vt.toString(e,jr)}function Tie(t){let e=LT.hash(Vt.fromString(t,cy));return Vt.toString(e,jr)}function l5(t){return Vt.fromString(`${t}`,ZT)}function jh(t){return Number(Vt.toString(t,ZT))}function _ie(t){let e=l5(typeof t.type<"u"?t.type:e_);if(jh(e)===hl&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?Vt.fromString(t.senderPublicKey,jr):void 0,n=typeof t.iv<"u"?Vt.fromString(t.iv,jr):$M.randomBytes(PT),i=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)).seal(n,Vt.fromString(t.message,cy));return f5({type:e,sealed:i,iv:n,senderPublicKey:r})}function Cie(t){let e=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)),{sealed:r,iv:n}=r_(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Vt.toString(i,cy)}function f5(t){if(jh(t.type)===hl){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Vt.toString(Vt.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),ry)}return Vt.toString(Vt.concat([t.type,t.iv,t.sealed]),ry)}function r_(t){let e=Vt.fromString(t,ry),r=e.slice(Aie,kM),n=kM;if(jh(r)===hl){let u=n+t_,a=u+PT,c=e.slice(n,u),f=e.slice(u,a),d=e.slice(a);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+PT,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Nie(t,e){let r=r_(t);return h5({type:jh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Vt.toString(r.senderPublicKey,jr):void 0,receiverPublicKey:e?.receiverPublicKey})}function h5(t){let e=t?.type||e_;if(e===hl){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function xie(t){return t.type===hl&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var d5="irn";function Oie(t){return t?.relay||{protocol:d5}}function Die(t){let e=zee.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Pie=Object.defineProperty,Rie=Object.defineProperties,Bie=Object.getOwnPropertyDescriptors,HM=Object.getOwnPropertySymbols,Mie=Object.prototype.hasOwnProperty,Lie=Object.prototype.propertyIsEnumerable,GM=(t,e,r)=>e in t?Pie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jM=(t,e)=>{for(var r in e||(e={}))Mie.call(e,r)&&GM(t,r,e[r]);if(HM)for(var r of HM(e))Lie.call(e,r)&&GM(t,r,e[r]);return t},Fie=(t,e)=>Rie(t,Bie(e));function g5(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Uie(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=$m.parse(s),u=typeof o.methods=="string"?o.methods.split(","):void 0;return{protocol:n,topic:p5(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:g5(o),methods:u,expiryTimestamp:o.expiryTimestamp?parseInt(o.expiryTimestamp,10):void 0}}function p5(t){return t.startsWith("//")?t.substring(2):t}function m5(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function qie(t){return`${t.protocol}:${t.topic}@${t.version}?`+$m.stringify(jM(Fie(jM({symKey:t.symKey},m5(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}var Vie=Object.defineProperty,kie=Object.defineProperties,Hie=Object.getOwnPropertyDescriptors,zM=Object.getOwnPropertySymbols,Gie=Object.prototype.hasOwnProperty,jie=Object.prototype.propertyIsEnumerable,QM=(t,e,r)=>e in t?Vie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zie=(t,e)=>{for(var r in e||(e={}))Gie.call(e,r)&&QM(t,r,e[r]);if(zM)for(var r of zM(e))jie.call(e,r)&&QM(t,r,e[r]);return t},Qie=(t,e)=>kie(t,Hie(e));function iu(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function y5(t){let e=[];return Object.values(t).forEach(r=>{e.push(...iu(r.accounts))}),e}function w5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.methods)}),r}function v5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.events)}),r}function Kie(t,e){let r=O5(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function Wie(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=RT(e),s=RT(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,w=n[c].events,A=n[c].accounts;f.forEach(T=>{if(!A.some(x=>x.includes(T)))throw new Error(`No accounts provided for chain ${T} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:w,accounts:A}});let u=P5(e,o,"approve()");if(u)throw new Error(u.message);let a={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.chains)==null?void 0:R.includes(T)}),d=n[c].methods.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.methods)==null?void 0:R.includes(T)}),w=n[c].events.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.events)==null?void 0:R.includes(T)}),A=f.map(T=>n[c].accounts.filter(x=>x.includes(`${T}:`))).flat();a[c]={chains:f,methods:d,events:w,accounts:A}}),Object.keys(s).forEach(c=>{var f,d,w,A,T,x;if(!n[c])return;let R=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(L=>n[c].chains.includes(L)),V=n[c].methods.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.methods)==null?void 0:H.includes(L)}),U=n[c].events.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.events)==null?void 0:H.includes(L)}),Q=R?.map(L=>n[c].accounts.filter(k=>k.includes(`${L}:`))).flat();a[c]={chains:Js((w=a[c])==null?void 0:w.chains,R),methods:Js((A=a[c])==null?void 0:A.methods,V),events:Js((T=a[c])==null?void 0:T.events,U),accounts:Js((x=a[c])==null?void 0:x.accounts,Q)}}),a)}function n_(t){return t.includes(":")}function A5(t){return n_(t)?t.split(":")[0]:t}function RT(t){var e,r,n;let i={};if(!ly(t))return i;for(let[s,o]of Object.entries(t)){let u=n_(s)?[s]:o.chains,a=o.methods||[],c=o.events||[],f=A5(s);i[f]=Qie(zie({},i[f]),{chains:Js(u,(e=i[f])==null?void 0:e.chains),methods:Js(a,(r=i[f])==null?void 0:r.methods),events:Js(c,(n=i[f])==null?void 0:n.events)})}return i}function E5(t){let e={};return t?.forEach(r=>{let[n,i]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[]}),e[n].accounts.push(r),e[n].chains.push(`${n}:${i}`)}),e}function $ie(t,e){e=e.map(n=>n.replace("did:pkh:",""));let r=E5(e);for(let[n,i]of Object.entries(r))i.methods?i.methods=Js(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}var b5={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},S5={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ys(t,e){let{message:r,code:n}=S5[t];return{message:e?`${r} ${e}`:r,code:n}}function tu(t,e){let{message:r,code:n}=b5[t];return{message:e?`${r} ${e}`:r,code:n}}function zh(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function ly(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Go(t){return typeof t>"u"}function mn(t,e){return e&&Go(t)?!0:typeof t=="string"&&!!t.trim().length}function fy(t,e){return e&&Go(t)?!0:typeof t=="number"&&!isNaN(t)}function Yie(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Ho(i,n)?(n.forEach(o=>{let{accounts:u,methods:a,events:c}=t.namespaces[o],f=iu(u),d=r[o];(!Ho(iy(o,d),f)||!Ho(d.methods,a)||!Ho(d.events,c))&&(s=!1)}),s):!1}function kh(t){return mn(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function I5(t){if(mn(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&kh(r)}}return!1}function Jie(t){if(mn(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function Xie(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function Zie(t){return t?.topic}function ese(t,e){let r=null;return mn(t?.publicKey,!1)||(r=Ys("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function BT(t){let e=!0;return zh(t)?t.length&&(e=t.every(r=>mn(r,!1))):e=!1,e}function T5(t,e,r){let n=null;return zh(e)&&e.length?e.forEach(i=>{n||kh(i)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):kh(t)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function _5(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=T5(i,iy(i,s),`${e} ${r}`);o&&(n=o)}),n}function C5(t,e){let r=null;return zh(t)?t.forEach(n=>{r||I5(n)||(r=tu("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=tu("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function N5(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=C5(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function x5(t,e){let r=null;return BT(t?.methods)?BT(t?.events)||(r=tu("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=tu("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function i_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=x5(n,`${e}, namespace`);i&&(r=i)}),r}function tse(t,e,r){let n=null;if(t&&ly(t)){let i=i_(t,e);i&&(n=i);let s=_5(t,e,r);s&&(n=s)}else n=Ys("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function O5(t,e){let r=null;if(t&&ly(t)){let n=i_(t,e);n&&(r=n);let i=N5(t,e);i&&(r=i)}else r=Ys("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function D5(t){return mn(t.protocol,!0)}function rse(t,e){let r=!1;return e&&!t?r=!0:t&&zh(t)&&t.length&&t.forEach(n=>{r=D5(n)}),r}function nse(t){return typeof t=="number"}function ise(t){return typeof t<"u"&&typeof t!==null}function sse(t){return!(!t||typeof t!="object"||!t.code||!fy(t.code,!1)||!t.message||!mn(t.message,!1))}function ose(t){return!(Go(t)||!mn(t.method,!1))}function ase(t){return!(Go(t)||Go(t.result)&&Go(t.error)||!fy(t.id,!1)||!mn(t.jsonrpc,!1))}function use(t){return!(Go(t)||!mn(t.name,!1))}function cse(t,e){return!(!kh(e)||!y5(t).includes(e))}function lse(t,e,r){return mn(r,!1)?w5(t,e).includes(r):!1}function fse(t,e,r){return mn(r,!1)?v5(t,e).includes(r):!1}function P5(t,e,r){let n=null,i=hse(t),s=dse(e),o=Object.keys(i),u=Object.keys(s),a=KM(Object.keys(t)),c=KM(Object.keys(e)),f=a.filter(d=>!c.includes(d));return f.length&&(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. + Required: ${f.toString()} + Received: ${Object.keys(e).toString()}`)),Ho(o,u)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. + Required: ${o.toString()} + Approved: ${u.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let w=iu(e[d].accounts);w.includes(d)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} + Required: ${d} + Approved: ${w.toString()}`))}),o.forEach(d=>{n||(Ho(i[d].methods,s[d].methods)?Ho(i[d].events,s[d].events)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function hse(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function KM(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dse(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:iu(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function gse(t,e){return fy(t,!1)&&t<=e.max&&t>=e.min}function pse(){let t=ru();return new Promise(e=>{switch(t){case Gr.browser:e(R5());break;case Gr.reactNative:e(B5());break;case Gr.node:e(M5());break;default:e(!0)}})}function R5(){return Hh()&&navigator?.onLine}async function B5(){return al()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function M5(){return!0}function mse(t){switch(ru()){case Gr.browser:L5(t);break;case Gr.reactNative:F5(t);break;case Gr.node:break}}function L5(t){!al()&&Hh()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function F5(t){al()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var IT={},MT=class{static get(e){return IT[e]}static set(e,r){IT[e]=r}static delete(e){delete IT[e]}};K.BASE10=ZT,K.BASE16=jr,K.BASE64=ry,K.COLON=ete,K.DEFAULT_DEPTH=qT,K.EMPTY_SPACE=Ym,K.ENV_MAP=Gr,K.INTERNAL_ERRORS=S5,K.MemoryStore=MT,K.ONE_THOUSAND=tte,K.REACT_NATIVE_PRODUCT=i4,K.RELAYER_DEFAULT_PROTOCOL=d5,K.SDK_ERRORS=b5,K.SDK_TYPE=o4,K.SLASH=s4,K.TYPE_0=e_,K.TYPE_1=hl,K.UTF8=cy,K.addResourceToRecap=a5,K.appendToQueryString=a4,K.assertType=ate,K.assignAbilityToActions=YT,K.base64Decode=s5,K.base64Encode=i5,K.buildApprovedNamespaces=Wie,K.buildAuthObject=hie,K.buildNamespacesFromAuth=$ie,K.buildRecapStatement=c5,K.calcExpiry=vte,K.capitalize=dte,K.capitalizeWord=d4,K.createDelayedPromise=gte,K.createEncodedRecap=mie,K.createExpiringPromise=pte,K.createRecap=o5,K.decodeRecap=jo,K.decodeTypeByte=jh,K.decrypt=Cie,K.deriveSymKey=Sie,K.deserialize=r_,K.encodeRecap=ay,K.encodeTypeByte=l5,K.encrypt=_ie,K.engineEvent=Ete,K.enumify=hte,K.formatAccountId=e4,K.formatAccountWithChain=Qee,K.formatChainId=ZM,K.formatExpirerTarget=kT,K.formatIdTarget=yte,K.formatMessage=e5,K.formatMessageContext=ute,K.formatRelayParams=m5,K.formatRelayRpcUrl=ste,K.formatStatementFromRecap=XT,K.formatTopicTarget=mte,K.formatUA=l4,K.formatUri=qie,K.generateKeyPair=Eie,K.generateRandomBytes32=bie,K.getAccountsChains=iu,K.getAccountsFromNamespaces=Wee,K.getAddressFromAccount=t4,K.getAddressesFromAccounts=Kee,K.getAppMetadata=nte,K.getBrowserOnlineStatus=R5,K.getBundleId=rte,K.getChainFromAccount=r4,K.getChainsFromAccounts=n4,K.getChainsFromNamespace=iy,K.getChainsFromNamespaces=$ee,K.getChainsFromRecap=vie,K.getChainsFromRequiredNamespaces=Yee,K.getCommonValuesInArrays=TT,K.getDecodedRecapFromResources=t5,K.getDeepLink=Ste,K.getDidAddress=$T,K.getDidAddressSegments=oy,K.getDidChainId=WT,K.getEnvironment=ru,K.getHttpUrl=ote,K.getInternalError=Ys,K.getJavascriptID=c4,K.getJavascriptOS=u4,K.getLastItems=h4,K.getMethodsFromRecap=wie,K.getNamespacedDidChainId=lie,K.getNamespacesChains=y5,K.getNamespacesEventsForChainId=v5,K.getNamespacesFromAccounts=E5,K.getNamespacesMethodsForChainId=w5,K.getNodeOnlineStatus=M5,K.getReCapActions=n5,K.getReactNativeOnlineStatus=B5,K.getRecapAbilitiesFromResource=pie,K.getRecapFromResources=uy,K.getRecapResource=r5,K.getRelayClientMetadata=ite,K.getRelayProtocolApi=Die,K.getRelayProtocolName=Oie,K.getRequiredNamespacesFromNamespaces=Kie,K.getSdkError=tu,K.getUniqueValues=UT,K.handleDeeplinkRedirect=bte,K.hasOverlap=Ho,K.hashKey=Iie,K.hashMessage=Tie,K.isBrowser=Hh,K.isCaipNamespace=n_,K.isConformingNamespaces=P5,K.isExpired=Ate,K.isNode=VT,K.isOnline=pse,K.isProposalStruct=Xie,K.isReactNative=al,K.isRecap=JT,K.isSessionCompatible=Yie,K.isSessionStruct=Zie,K.isTypeOneEnvelope=xie,K.isUndefined=Go,K.isValidAccountId=I5,K.isValidAccounts=C5,K.isValidActions=x5,K.isValidArray=zh,K.isValidChainId=kh,K.isValidChains=T5,K.isValidController=ese,K.isValidEip1271Signature=X4,K.isValidEip191Signature=J4,K.isValidErrorReason=sse,K.isValidEvent=use,K.isValidId=nse,K.isValidNamespaceAccounts=N5,K.isValidNamespaceActions=i_,K.isValidNamespaceChains=_5,K.isValidNamespaceMethodsOrEvents=BT,K.isValidNamespaces=O5,K.isValidNamespacesChainId=cse,K.isValidNamespacesEvent=fse,K.isValidNamespacesRequest=lse,K.isValidNumber=fy,K.isValidObject=ly,K.isValidParams=ise,K.isValidRecap=ps,K.isValidRelay=D5,K.isValidRelays=rse,K.isValidRequest=ose,K.isValidRequestExpiry=gse,K.isValidRequiredNamespaces=tse,K.isValidResponse=ase,K.isValidString=mn,K.isValidUrl=Jie,K.mapEntries=fte,K.mapToObj=cte,K.mergeArrays=Js,K.mergeEncodedRecaps=yie,K.mergeRecaps=u5,K.normalizeNamespaces=RT,K.objToMap=lte,K.parseAccountId=FT,K.parseChainId=XM,K.parseContextNames=f4,K.parseExpirerTarget=wte,K.parseNamespaceKey=A5,K.parseRelayParams=g5,K.parseTopic=p5,K.parseUri=Uie,K.populateAuthPayload=die,K.recapHasResource=gie,K.serialize=f5,K.subscribeToBrowserNetworkChange=L5,K.subscribeToNetworkChange=mse,K.subscribeToReactNativeNetworkChange=F5,K.validateDecoding=Nie,K.validateEncoding=h5,K.validateSignedCacao=fie,K.verifySignature=Y4});var U5,q5,V5,k5,hy,Kh,s_,dy,zo,Wh,gy=fe(()=>{h();U5="PARSE_ERROR",q5="INVALID_REQUEST",V5="METHOD_NOT_FOUND",k5="INVALID_PARAMS",hy="INTERNAL_ERROR",Kh="SERVER_ERROR",s_=[-32700,-32600,-32601,-32602,-32603],dy=[-32e3,-32099],zo={[U5]:{code:-32700,message:"Parse error"},[q5]:{code:-32600,message:"Invalid Request"},[V5]:{code:-32601,message:"Method not found"},[k5]:{code:-32602,message:"Invalid params"},[hy]:{code:-32603,message:"Internal error"},[Kh]:{code:-32e3,message:"Server error"}},Wh=Kh});function yse(t){return t<=dy[0]&&t>=dy[1]}function py(t){return s_.includes(t)}function H5(t){return typeof t=="number"}function my(t){return Object.keys(zo).includes(t)?zo[t]:zo[Wh]}function yy(t){let e=Object.values(zo).find(r=>r.code===t);return e||zo[Wh]}function wse(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!H5(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(py(t.error.code)){let e=yy(t.error.code);if(e.message!==zo[Wh].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function o_(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var a_=fe(()=>{h();gy()});var j5=B(Qo=>{"use strict";h();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.isBrowserCryptoAvailable=Qo.getSubtleCrypto=Qo.getBrowerCrypto=void 0;function u_(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}Qo.getBrowerCrypto=u_;function G5(){let t=u_();return t.subtle||t.webkitSubtle}Qo.getSubtleCrypto=G5;function vse(){return!!u_()&&!!G5()}Qo.isBrowserCryptoAvailable=vse});var K5=B(Ko=>{"use strict";h();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.isBrowser=Ko.isNode=Ko.isReactNative=void 0;function z5(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ko.isReactNative=z5;function Q5(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}Ko.isNode=Q5;function Ase(){return!z5()&&!Q5()}Ko.isBrowser=Ase});var c_=B(wy=>{"use strict";h();Object.defineProperty(wy,"__esModule",{value:!0});var W5=(es(),_e(Zi));W5.__exportStar(j5(),wy);W5.__exportStar(K5(),wy)});var Er={};Bt(Er,{isNodeJs:()=>Y5});var $5,Y5,J5=fe(()=>{h();$5=pe(c_());Tr(Er,pe(c_()));Y5=$5.isNode});function l_(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function f_(t=6){return BigInt(l_(t))}function h_(t,e,r){return{id:r||l_(),jsonrpc:"2.0",method:t,params:e}}function Ese(t,e){return{id:t,jsonrpc:"2.0",result:e}}function d_(t,e,r){return{id:t,jsonrpc:"2.0",error:X5(e,r)}}function X5(t,e){return typeof t>"u"?my(hy):(typeof t=="string"&&(t=Object.assign(Object.assign({},my(Kh)),{message:t})),typeof e<"u"&&(t.data=e),py(t.code)&&(t=yy(t.code)),t)}var Z5=fe(()=>{h();a_();gy()});function bse(t){return t.includes("*")?Ay(t):!/\W/g.test(t)}function vy(t){return t==="*"}function Ay(t){return vy(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function Sse(t){return!vy(t)&&Ay(t)&&!t.split("*")[0].trim()}function Ise(t){return!vy(t)&&Ay(t)&&!t.split("*")[1].trim()}var eL=fe(()=>{h()});var tL=fe(()=>{h()});var dl,g_=fe(()=>{h();dl=class{}});var p_,Ey,$h,rL=fe(()=>{h();g_();p_=class extends dl{constructor(e){super()}},Ey=class extends dl{constructor(){super()}},$h=class extends Ey{constructor(e){super()}}});var nL=fe(()=>{h()});var iL=fe(()=>{h();tL();g_();rL();nL()});var sL=fe(()=>{h();iL()});function Cse(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function oL(t,e){let r=Cse(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Nse(t){return oL(t,Tse)}function by(t){return oL(t,_se)}function m_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var Tse,_se,aL=fe(()=>{h();Tse="^https?:",_se="^wss?:"});function y_(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function xse(t){return y_(t)&&"method"in t}function w_(t){return y_(t)&&(uL(t)||Sy(t))}function uL(t){return"result"in t}function Sy(t){return"error"in t}function Ose(t){return"error"in t&&t.valid===!1}var cL=fe(()=>{h()});var Fr={};Bt(Fr,{DEFAULT_ERROR:()=>Wh,IBaseJsonRpcProvider:()=>Ey,IEvents:()=>dl,IJsonRpcConnection:()=>p_,IJsonRpcProvider:()=>$h,INTERNAL_ERROR:()=>hy,INVALID_PARAMS:()=>k5,INVALID_REQUEST:()=>q5,METHOD_NOT_FOUND:()=>V5,PARSE_ERROR:()=>U5,RESERVED_ERROR_CODES:()=>s_,SERVER_ERROR:()=>Kh,SERVER_ERROR_CODE_RANGE:()=>dy,STANDARD_ERROR_MAP:()=>zo,formatErrorMessage:()=>X5,formatJsonRpcError:()=>d_,formatJsonRpcRequest:()=>h_,formatJsonRpcResult:()=>Ese,getBigIntRpcId:()=>f_,getError:()=>my,getErrorByCode:()=>yy,isHttpUrl:()=>Nse,isJsonRpcError:()=>Sy,isJsonRpcPayload:()=>y_,isJsonRpcRequest:()=>xse,isJsonRpcResponse:()=>w_,isJsonRpcResult:()=>uL,isJsonRpcValidationInvalid:()=>Ose,isLocalhostUrl:()=>m_,isNodeJs:()=>Y5,isReservedErrorCode:()=>py,isServerErrorCode:()=>yse,isValidDefaultRoute:()=>vy,isValidErrorCode:()=>H5,isValidLeadingWildcardRoute:()=>Sse,isValidRoute:()=>bse,isValidTrailingWildcardRoute:()=>Ise,isValidWildcardRoute:()=>Ay,isWsUrl:()=>by,parseConnectionError:()=>o_,payloadId:()=>l_,validateJsonRpcError:()=>wse});var Yh=fe(()=>{h();gy();a_();J5();Tr(Fr,Er);Z5();eL();sL();aL();cL()});var lL,Iy,fL,v_=fe(()=>{h();lL=pe(Ds());Yh();Iy=class extends $h{constructor(e){super(e),this.events=new lL.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(h_(e.method,e.params||[],e.id||f_().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Sy(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),w_(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},fL=Iy});var hL={};Bt(hL,{JsonRpcProvider:()=>Iy,default:()=>Dse});var Dse,dL=fe(()=>{h();v_();v_();Dse=fL});var pL=B((LIe,gL)=>{"use strict";h();gL.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var vL={};Bt(vL,{WsConnection:()=>A_,default:()=>A_});var wL,Pse,Rse,mL,yL,Bse,A_,AL=fe(()=>{h();wL=pe(Ds());xc();Yh();Pse=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:pL(),Rse=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",mL=t=>t.split("?")[0],yL=10,Bse=Pse(),A_=class{constructor(e){if(this.url=e,this.events=new wL.EventEmitter,this.registering=!1,!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ai(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,Fr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!m_(e)},o=new Bse(e,[],s);Rse()?o.onerror=u=>{let a=u;n(this.emitError(a.error))}:o.on("error",u=>{n(this.emitError(u))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?Ro(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=d_(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return o_(e,mL(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>yL&&this.events.setMaxListeners(yL)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${mL(this.url)}`));return this.events.emit("register_error",r),r}}});var tF=B((Jh,pl)=>{h();var Mse=200,D_="__lodash_hash_undefined__",Py=1,PL=2,RL=9007199254740991,Ty="[object Arguments]",I_="[object Array]",Lse="[object AsyncFunction]",BL="[object Boolean]",ML="[object Date]",LL="[object Error]",FL="[object Function]",Fse="[object GeneratorFunction]",_y="[object Map]",UL="[object Number]",Use="[object Null]",gl="[object Object]",EL="[object Promise]",qse="[object Proxy]",qL="[object RegExp]",Cy="[object Set]",VL="[object String]",Vse="[object Symbol]",kse="[object Undefined]",T_="[object WeakMap]",kL="[object ArrayBuffer]",Ny="[object DataView]",Hse="[object Float32Array]",Gse="[object Float64Array]",jse="[object Int8Array]",zse="[object Int16Array]",Qse="[object Int32Array]",Kse="[object Uint8Array]",Wse="[object Uint8ClampedArray]",$se="[object Uint16Array]",Yse="[object Uint32Array]",Jse=/[\\^$.*+?()[\]{}|]/g,Xse=/^\[object .+?Constructor\]$/,Zse=/^(?:0|[1-9]\d*)$/,Mt={};Mt[Hse]=Mt[Gse]=Mt[jse]=Mt[zse]=Mt[Qse]=Mt[Kse]=Mt[Wse]=Mt[$se]=Mt[Yse]=!0;Mt[Ty]=Mt[I_]=Mt[kL]=Mt[BL]=Mt[Ny]=Mt[ML]=Mt[LL]=Mt[FL]=Mt[_y]=Mt[UL]=Mt[gl]=Mt[qL]=Mt[Cy]=Mt[VL]=Mt[T_]=!1;var HL=typeof global=="object"&&global&&global.Object===Object&&global,eoe=typeof self=="object"&&self&&self.Object===Object&&self,Xs=HL||eoe||Function("return this")(),GL=typeof Jh=="object"&&Jh&&!Jh.nodeType&&Jh,bL=GL&&typeof pl=="object"&&pl&&!pl.nodeType&&pl,jL=bL&&bL.exports===GL,E_=jL&&HL.process,SL=function(){try{return E_&&E_.binding&&E_.binding("util")}catch{}}(),IL=SL&&SL.isTypedArray;function toe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function Doe(t,e){var r=this.__data__,n=By(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}Zs.prototype.clear=Coe;Zs.prototype.delete=Noe;Zs.prototype.get=xoe;Zs.prototype.has=Ooe;Zs.prototype.set=Doe;function au(t){var e=-1,r=t==null?0:t.length;for(this.clear();++eu))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,w=r&PL?new Oy:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=RL}function ZL(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ed(t){return t!=null&&typeof t=="object"}var eF=IL?soe(IL):Woe;function uae(t){return oae(t)?joe(t):$oe(t)}function cae(){return[]}function lae(){return!1}pl.exports=aae});var P_=B((HIe,rF)=>{h();rF.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},a=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:a,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return u[f.toLowerCase()]},has:function(f){return f.toLowerCase()in u}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,w){s.push(d=d.toLowerCase()),o.push([d,w]),u[d]=u[d]?u[d]+","+w:w}),r(a())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var iF=B((jIe,nF)=>{h();nF.exports=self.fetch||(self.fetch=P_().default||P_())});var fU=B(de=>{"use strict";h();Object.defineProperty(de,"__esModule",{value:!0});var cu=Ds(),fae=(nP(),_e(rP)),id=AP(),yt=(CS(),_e(_S)),ws=QS(),sF=(xc(),_e(eP)),hae=(aB(),_e(oB)),ne=Qh(),dae=(tT(),_e(eT)),Oe=Qa(),gae=(dL(),_e(hL)),an=(Yh(),_e(Fr)),pae=(AL(),_e(vL)),mae=tF(),yae=iF();function sd(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function wae(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var vae=sd(cu),Aae=sd(fae),Ly=wae(hae),Eae=sd(pae),bae=sd(mae),Sae=sd(yae);function Iae(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var Tae=Iae,_ae=Tae,bF=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Cae=t=>new TextEncoder().encode(t),Nae=t=>new TextDecoder().decode(t),M_=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},L_=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SF(this,e)}},F_=class{constructor(e){this.decoders=e}or(e){return SF(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SF=(t,e)=>new F_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),U_=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new M_(e,r,n),this.decoder=new L_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Jy=({name:t,prefix:e,encode:r,decode:n})=>new U_(t,e,r,n),od=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=_ae(r,e);return Jy({prefix:t,name:e,encode:n,decode:s=>bF(i(s))})},xae=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},Oae=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<Jy({prefix:e,name:t,encode(i){return Oae(i,n,r)},decode(i){return xae(i,n,r,t)}}),Dae=Jy({prefix:"\0",name:"identity",encode:t=>Nae(t),decode:t=>Cae(t)}),Pae=Object.freeze({__proto__:null,identity:Dae}),Rae=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Bae=Object.freeze({__proto__:null,base2:Rae}),Mae=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Lae=Object.freeze({__proto__:null,base8:Mae}),Fae=od({prefix:"9",name:"base10",alphabet:"0123456789"}),Uae=Object.freeze({__proto__:null,base10:Fae}),qae=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vae=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),kae=Object.freeze({__proto__:null,base16:qae,base16upper:Vae}),Hae=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gae=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jae=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zae=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qae=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kae=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wae=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$ae=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yae=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Jae=Object.freeze({__proto__:null,base32:Hae,base32upper:Gae,base32pad:jae,base32padupper:zae,base32hex:Qae,base32hexupper:Kae,base32hexpad:Wae,base32hexpadupper:$ae,base32z:Yae}),Xae=od({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zae=od({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),eue=Object.freeze({__proto__:null,base36:Xae,base36upper:Zae}),tue=od({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rue=od({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),nue=Object.freeze({__proto__:null,base58btc:tue,base58flickr:rue}),iue=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sue=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oue=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aue=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),uue=Object.freeze({__proto__:null,base64:iue,base64pad:sue,base64url:oue,base64urlpad:aue}),IF=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),cue=IF.reduce((t,e,r)=>(t[r]=e,t),[]),lue=IF.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fue(t){return t.reduce((e,r)=>(e+=cue[r],e),"")}function hue(t){let e=[];for(let r of t){let n=lue[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var due=Jy({prefix:"\u{1F680}",name:"base256emoji",encode:fue,decode:hue}),gue=Object.freeze({__proto__:null,base256emoji:due}),pue=TF,oF=128,mue=127,yue=~mue,wue=Math.pow(2,31);function TF(t,e,r){e=e||[],r=r||0;for(var n=r;t>=wue;)e[r++]=t&255|oF,t/=128;for(;t&yue;)e[r++]=t&255|oF,t>>>=7;return e[r]=t|0,TF.bytes=r-n+1,e}var vue=q_,Aue=128,aF=127;function q_(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw q_.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&aF)<=Aue);return q_.bytes=s-n,r}var Eue=Math.pow(2,7),bue=Math.pow(2,14),Sue=Math.pow(2,21),Iue=Math.pow(2,28),Tue=Math.pow(2,35),_ue=Math.pow(2,42),Cue=Math.pow(2,49),Nue=Math.pow(2,56),xue=Math.pow(2,63),Oue=function(t){return t(_F.encode(t,e,r),e),cF=t=>_F.encodingLength(t),V_=(t,e)=>{let r=e.byteLength,n=cF(t),i=n+cF(r),s=new Uint8Array(i+r);return uF(t,s,0),uF(r,s,n),s.set(e,i),new k_(t,r,e,s)},k_=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},CF=({name:t,code:e,encode:r})=>new H_(t,e,r),H_=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?V_(this.code,r):r.then(n=>V_(this.code,n))}else throw Error("Unknown type, must be binary type")}},NF=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pue=CF({name:"sha2-256",code:18,encode:NF("SHA-256")}),Rue=CF({name:"sha2-512",code:19,encode:NF("SHA-512")}),Bue=Object.freeze({__proto__:null,sha256:Pue,sha512:Rue}),xF=0,Mue="identity",OF=bF,Lue=t=>V_(xF,OF(t)),Fue={code:xF,name:Mue,encode:OF,digest:Lue},Uue=Object.freeze({__proto__:null,identity:Fue});new TextEncoder,new TextDecoder;var lF={...Pae,...Bae,...Lae,...Uae,...kae,...Jae,...eue,...nue,...uue,...gue};({...Bue,...Uue});function DF(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function que(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?DF(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function PF(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var fF=PF("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),R_=PF("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=que(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Vy=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=LF,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=Ly.generateKeyPair(i);return Ly.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=ne.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=Ly.generateKeyPair(s),u=ne.generateRandomBytes32(),a=FF;return await Ly.signJWT(u,i,a,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let u=this.getPrivateKey(i),a=ne.deriveSymKey(u,s);return this.setSymKey(a,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||ne.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let u=ne.validateEncoding(o),a=sF.safeJsonStringify(s);if(ne.isTypeOneEnvelope(u)){let w=u.senderPublicKey,A=u.receiverPublicKey;i=await this.generateSharedKey(w,A)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=u;return ne.encrypt({type:f,symKey:c,message:a,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let u=ne.validateDecoding(s,o);if(ne.isTypeOneEnvelope(u)){let a=u.receiverPublicKey,c=u.senderPublicKey;i=await this.generateSharedKey(a,c)}try{let a=this.getSymKey(i),c=ne.decrypt({symKey:a,encoded:s});return sF.safeJsonParse(c)}catch(a){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(a)}},this.getPayloadType=i=>{let s=ne.deserialize(i);return ne.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=ne.deserialize(i);return s.senderPublicKey?dae.toString(s.senderPublicKey,ne.BASE16):void 0},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.keychain=n||new qy(this.core,this.logger)}get context(){return yt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(G_)}catch{e=ne.generateRandomBytes32(),await this.keychain.set(G_,e)}return kue(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},ky=class extends ws.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=VF,this.version=kF,this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=ne.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=ne.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=yt.generateChildLogger(e,this.name),this.core=r}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},z_=class extends ws.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new cu.EventEmitter,this.name=GF,this.queue=new Map,this.publishTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.failedPublishTimeout=Oe.toMiliseconds(Oe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});let u=s?.ttl||HF,a=ne.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||an.getBigIntRpcId().toString(),w={topic:n,message:i,opts:{ttl:u,relay:a,prompt:c,tag:f,id:d}},A=`Failed to publish payload, please try again. id:${d} tag:${f}`,T=Date.now(),x,R=1;try{for(;x===void 0;){if(Date.now()-T>this.publishTimeout)throw new Error(A);this.logger.trace({id:d,attempts:R},`publisher.publish - attempt ${R}`),x=await await ne.createExpiringPromise(this.rpcPublish(n,i,u,a,c,f,d).catch(V=>this.logger.warn(V)),this.publishTimeout,A),R++,x||await new Promise(V=>setTimeout(V,this.failedPublishTimeout))}this.relayer.events.emit(Zn.publish,w),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}})}catch(V){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(V),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw V;this.queue.set(d,w)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return yt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,u){var a,c,f,d;let w={method:ne.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:u};return ne.isUndefined((a=w.params)==null?void 0:a.prompt)&&((c=w.params)==null||delete c.prompt),ne.isUndefined((f=w.params)==null?void 0:f.tag)&&((d=w.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w}),this.relayer.request(w)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Zn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Zn.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},Q_=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Que=Object.defineProperty,Kue=Object.defineProperties,Wue=Object.getOwnPropertyDescriptors,hF=Object.getOwnPropertySymbols,$ue=Object.prototype.hasOwnProperty,Yue=Object.prototype.propertyIsEnumerable,dF=(t,e,r)=>e in t?Que(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rd=(t,e)=>{for(var r in e||(e={}))$ue.call(e,r)&&dF(t,r,e[r]);if(hF)for(var r of hF(e))Yue.call(e,r)&&dF(t,r,e[r]);return t},B_=(t,e)=>Kue(t,Wue(e)),Hy=class extends ws.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new Q_,this.events=new cu.EventEmitter,this.name=ZF,this.version=eU,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=eo,this.subscribeTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=ne.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let u=await this.rpcSubscribe(n,s);return typeof u=="string"&&(this.onSubscribe(u,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;let i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((s,o)=>{let u=new Oe.Watch;u.start(i);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),u.stop(i),s(!0)),u.elapsed(i)>=tU&&(clearInterval(a),u.stop(i),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.clientId=""}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=ne.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=ne.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:ne.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?ne.hashMessage(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Zn.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:ne.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(Zn.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:ne.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,B_(rd({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rd({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rd({},r)),this.topicMap.set(r.topic,e),this.events.emit(_i.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(_i.deleted,B_(rd({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_i.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);ne.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>B_(rd({},e[i]),{id:n})))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(_i.created,async e=>{let r=_i.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(_i.deleted,async e=>{let r=_i.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},Jue=Object.defineProperty,gF=Object.getOwnPropertySymbols,Xue=Object.prototype.hasOwnProperty,Zue=Object.prototype.propertyIsEnumerable,pF=(t,e,r)=>e in t?Jue(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ece=(t,e)=>{for(var r in e||(e={}))Xue.call(e,r)&&pF(t,r,e[r]);if(gF)for(var r of gF(e))Zue.call(e,r)&&pF(t,r,e[r]);return t},Gy=class extends ws.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new cu.EventEmitter,this.name=QF,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Oe.toMiliseconds(Oe.THIRTY_SECONDS+Oe.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");let s=r.id||an.getBigIntRpcId().toString();await this.toEstablishConnection();try{let o=this.provider.request(r);this.requestsInFlight.set(s,{promise:o,request:r}),this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");let u=await new Promise(async(a,c)=>{let f=()=>{c(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(yn.disconnect,f);let d=await o;this.provider.off(yn.disconnect,f),a(d)});return this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),u}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(ne.isNode())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(Zn.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Zn.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(yn.payload,this.onPayloadHandler),this.provider.on(yn.connect,this.onConnectHandler),this.provider.on(yn.disconnect,this.onDisconnectHandler),this.provider.on(yn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?yt.generateChildLogger(e.logger,this.name):yt.pino(yt.getDefaultLoggerOptions({level:e.logger||zF})),this.messages=new ky(this.logger,e.core),this.subscriber=new Hy(this,this.logger),this.publisher=new z_(this,this.logger),this.relayUrl=e?.relayUrl||W_,this.projectId=e.projectId,this.bundleId=ne.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${j_}...`),await this.restartTransport(j_)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},YF)}get context(){return yt.getLoggerContext(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",s,o=u=>{u.topic===e&&(this.subscriber.off(_i.created,o),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(_i.created,o)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,r)||i,u()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await ne.createExpiringPromise(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect(),await this.createProvider()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{let i=()=>{this.provider.off(yn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(yn.disconnect,i),await ne.createExpiringPromise(this.provider.connect(),Oe.toMiliseconds(Oe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{n(s)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ne.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}startPingTimeout(){var e,r,n,i,s;if(ne.isNode())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new gae.JsonRpcProvider(new Eae.default(ne.formatRelayRpcUrl({sdkVersion:$F,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),an.isJsonRpcRequest(e)){if(!e.method.endsWith(KF))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ece({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else an.isJsonRpcResponse(e)&&this.events.emit(Zn.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Zn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=an.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(yn.payload,this.onPayloadHandler),this.provider.off(yn.connect,this.onConnectHandler),this.provider.off(yn.disconnect,this.onDisconnectHandler),this.provider.off(yn.error,this.onProviderErrorHandler)}async registerEventListeners(){let e=await ne.isOnline();ne.subscribeToNetworkChange(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.events.emit(Zn.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Oe.toMiliseconds(WF))}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}},tce=Object.defineProperty,mF=Object.getOwnPropertySymbols,rce=Object.prototype.hasOwnProperty,nce=Object.prototype.propertyIsEnumerable,yF=(t,e,r)=>e in t?tce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wF=(t,e)=>{for(var r in e||(e={}))rce.call(e,r)&&yF(t,r,e[r]);if(mF)for(var r of mF(e))nce.call(e,r)&&yF(t,r,e[r]);return t},jy=class extends ws.IStore{constructor(e,r,n,i=eo,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=JF,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ne.isUndefined(o)?this.map.set(this.getKey(o),o):ne.isProposalStruct(o)?this.map.set(o.id,o):ne.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,u)=>{this.isInitialized(),this.map.has(o)?await this.update(o,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:u}),this.map.set(o,u),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(u=>Object.keys(o).every(a=>bae.default(u[a],o[a]))):this.values),this.update=async(o,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:u});let a=wF(wF({},this.getData(o)),u);this.map.set(o,a),await this.persist()},this.delete=async(o,u)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:u}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())},this.logger=yt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},zy=class{constructor(e,r){this.core=e,this.logger=r,this.name=rU,this.version=nU,this.events=new vae.default,this.initialized=!1,this.storagePrefix=eo,this.ignoredPayloadTypes=[ne.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let i=ne.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),o=ne.calcExpiry(Oe.FIVE_MINUTES),u={protocol:jF},a={topic:s,expiry:o,relay:u,active:!1},c=ne.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:u,expiryTimestamp:o,methods:n?.methods});return await this.pairings.set(s,a),await this.core.relayer.subscribe(s),this.core.expirer.set(s,o),{topic:s,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o,expiryTimestamp:u,methods:a}=ne.parseUri(n.uri),c;if(this.pairings.keys.includes(i)&&(c=this.pairings.get(i),c.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let f=u||ne.calcExpiry(Oe.FIVE_MINUTES),d={topic:i,relay:o,expiry:f,active:!1,methods:a};return await this.pairings.set(i,d),this.core.expirer.set(i,f),n.activatePairing&&await this.activate({topic:i}),this.events.emit(nd.create,d),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),d},this.activate=async({topic:n})=>{this.isInitialized();let i=ne.calcExpiry(Oe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:u,reject:a}=ne.createDelayedPromise();this.events.once(ne.engineEvent("pairing_ping",s),({error:c})=>{c?a(c):u()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ne.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=an.formatJsonRpcRequest(i,s),u=await this.core.crypto.encode(n,o),a=yl[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,u,a),o.id},this.sendResult=async(n,i,s)=>{let o=an.formatJsonRpcResult(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method].res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=an.formatJsonRpcError(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method]?yl[a.request.method].res:yl.unregistered_method.res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,ne.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>ne.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(nd.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{an.isJsonRpcResult(i)?this.events.emit(ne.engineEvent("pairing_ping",s),{}):an.isJsonRpcError(i)&&this.events.emit(ne.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(nd.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let u=ne.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,u),this.logger.error(u)}catch(u){await this.sendError(s,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(ne.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!ne.isValidParams(n)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!ne.isValidUrl(n.uri)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=ne.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(s!=null&&s.expiryTimestamp&&Oe.toMiliseconds(s?.expiryTimestamp){if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ne.isValidString(n,!1)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=ne.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ne.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=ne.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.pairings=new jy(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Zn.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{an.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):an.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Xn.expired,async e=>{let{topic:r}=ne.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(nd.expire,{topic:r}))})}},Qy=class extends ws.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new cu.EventEmitter,this.name=iU,this.version=sU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:ne.calcExpiry(Oe.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=an.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Jn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Jn.deleted,s)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:an.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jn.created,e=>{let r=Jn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.updated,e=>{let r=Jn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.deleted,e=>{let r=Jn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Oe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Jn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ky=class extends ws.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new cu.EventEmitter,this.name=oU,this.version=aU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Xn.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Xn.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ne.formatTopicTarget(e);if(typeof e=="number")return ne.formatIdTarget(e);let{message:r}=ne.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Xn.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Oe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Xn.created,e=>{let r=Xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.expired,e=>{let r=Xn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.deleted,e=>{let r=Xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wy=class extends ws.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=Fy,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||ne.isReactNative()||!ne.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Uy;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,Uy)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Oe.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{let o=document.getElementById(Fy);if(o)return this.iframe=o,this.onInit(),s();window.addEventListener("message",i);let u=document.createElement("iframe");u.id=Fy,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Oe.toMiliseconds(Oe.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||wl;return uU.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${wl}`),i=wl),i},this.logger=yt.generateChildLogger(r,this.name),this.verifyUrl=wl,this.abortController=new AbortController,this.isDevEnv=ne.isNode()&&I.default.env.IS_VITEST}get context(){return yt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Oe.toMiliseconds(e))}},$y=class extends ws.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=cU,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:u=!1}=n,a=`${lU}/${this.projectId}/clients`;await Sae.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:u})})},this.logger=yt.generateChildLogger(r,this.context)}},ice=Object.defineProperty,vF=Object.getOwnPropertySymbols,sce=Object.prototype.hasOwnProperty,oce=Object.prototype.propertyIsEnumerable,AF=(t,e,r)=>e in t?ice(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,EF=(t,e)=>{for(var r in e||(e={}))sce.call(e,r)&&AF(t,r,e[r]);if(vF)for(var r of vF(e))oce.call(e,r)&&AF(t,r,e[r]);return t},Yy=class t extends ws.ICore{constructor(e){var r;super(e),this.protocol=K_,this.version=RF,this.name=Xy,this.events=new cu.EventEmitter,this.initialized=!1,this.on=(o,u)=>this.events.on(o,u),this.once=(o,u)=>this.events.once(o,u),this.off=(o,u)=>this.events.off(o,u),this.removeListener=(o,u)=>this.events.removeListener(o,u),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||W_,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let n=yt.getDefaultLoggerOptions({level:typeof e?.logger=="string"&&e.logger?e.logger:BF.logger}),{logger:i,chunkLoggerController:s}=yt.generatePlatformLogger({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,u;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=yt.generateChildLogger(i,this.name),this.heartbeat=new id.HeartBeat,this.crypto=new Vy(this,this.logger,e?.keychain),this.history=new Qy(this,this.logger),this.expirer=new Ky(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Aae.default(EF(EF({},MF),e?.storageOptions)),this.relayer=new Gy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new zy(this,this.logger),this.verify=new Wy(this.projectId||"",this.logger),this.echoClient=new $y(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(XF,n),r}get context(){return yt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},ace=Yy;de.CORE_CONTEXT=Xy,de.CORE_DEFAULT=BF,de.CORE_PROTOCOL=K_,de.CORE_STORAGE_OPTIONS=MF,de.CORE_STORAGE_PREFIX=eo,de.CORE_VERSION=RF,de.CRYPTO_CLIENT_SEED=G_,de.CRYPTO_CONTEXT=LF,de.CRYPTO_JWT_TTL=FF,de.Core=ace,de.Crypto=Vy,de.ECHO_CONTEXT=cU,de.ECHO_URL=lU,de.EXPIRER_CONTEXT=oU,de.EXPIRER_DEFAULT_TTL=zue,de.EXPIRER_EVENTS=Xn,de.EXPIRER_STORAGE_VERSION=aU,de.EchoClient=$y,de.Expirer=Ky,de.HISTORY_CONTEXT=iU,de.HISTORY_EVENTS=Jn,de.HISTORY_STORAGE_VERSION=sU,de.JsonRpcHistory=Qy,de.KEYCHAIN_CONTEXT=UF,de.KEYCHAIN_STORAGE_VERSION=qF,de.KeyChain=qy,de.MESSAGES_CONTEXT=VF,de.MESSAGES_STORAGE_VERSION=kF,de.MessageTracker=ky,de.PAIRING_CONTEXT=rU,de.PAIRING_DEFAULT_TTL=jue,de.PAIRING_EVENTS=nd,de.PAIRING_RPC_OPTS=yl,de.PAIRING_STORAGE_VERSION=nU,de.PENDING_SUB_RESOLUTION_TIMEOUT=tU,de.PUBLISHER_CONTEXT=GF,de.PUBLISHER_DEFAULT_TTL=HF,de.Pairing=zy,de.RELAYER_CONTEXT=QF,de.RELAYER_DEFAULT_LOGGER=zF,de.RELAYER_DEFAULT_PROTOCOL=jF,de.RELAYER_DEFAULT_RELAY_URL=W_,de.RELAYER_EVENTS=Zn,de.RELAYER_FAILOVER_RELAY_URL=j_,de.RELAYER_PROVIDER_EVENTS=yn,de.RELAYER_RECONNECT_TIMEOUT=WF,de.RELAYER_SDK_VERSION=$F,de.RELAYER_STORAGE_OPTIONS=Hue,de.RELAYER_SUBSCRIBER_SUFFIX=KF,de.RELAYER_TRANSPORT_CUTOFF=YF,de.Relayer=Gy,de.STORE_STORAGE_VERSION=JF,de.SUBSCRIBER_CONTEXT=ZF,de.SUBSCRIBER_DEFAULT_TTL=Gue,de.SUBSCRIBER_EVENTS=_i,de.SUBSCRIBER_STORAGE_VERSION=eU,de.Store=jy,de.Subscriber=Hy,de.TRUSTED_VERIFY_URLS=uU,de.VERIFY_CONTEXT=Fy,de.VERIFY_FALLBACK_SERVER=Uy,de.VERIFY_SERVER=wl,de.Verify=Wy,de.WALLETCONNECT_CLIENT_ID=XF,de.default=Yy});var CU=B(Be=>{"use strict";h();Object.defineProperty(Be,"__esModule",{value:!0});var un=fU(),Zy=(CS(),_e(_S)),gU=QS(),G=Qh(),pU=Ds(),Dt=Qa(),qe=(Yh(),_e(Fr));function uce(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var cce=uce(pU),n2="wc",i2=2,s2="client",i1=`${n2}@${i2}:${s2}:`,e1={name:s2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},lce={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},fce={database:":memory:"},$_="WALLETCONNECT_DEEPLINK_CHOICE",hce={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},dce="history",gce="0.3",mU="proposal",pce=Dt.THIRTY_DAYS,yU="Proposal expired",wU="session",lu=Dt.SEVEN_DAYS,vU="engine",wn={wc_sessionPropose:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Dt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Dt.ONE_HOUR,prompt:!1,tag:1117}}},t1={min:Dt.FIVE_MINUTES,max:Dt.SEVEN_DAYS},vs={idle:"IDLE",active:"ACTIVE"},AU="request",EU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],bU="wc",mce=1.5,SU="auth",IU="authKeys",TU="pairingTopics",_U="requests",ud=`${bU}@${1.5}:${SU}:`,ad=`${ud}:PUB_KEY`,yce=Object.defineProperty,wce=Object.defineProperties,vce=Object.getOwnPropertyDescriptors,hU=Object.getOwnPropertySymbols,Ace=Object.prototype.hasOwnProperty,Ece=Object.prototype.propertyIsEnumerable,dU=(t,e,r)=>e in t?yce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e)=>{for(var r in e||(e={}))Ace.call(e,r)&&dU(t,r,e[r]);if(hU)for(var r of hU(e))Ece.call(e,r)&&dU(t,r,e[r]);return t},vl=(t,e)=>wce(t,vce(e)),Y_=class extends gU.IEngine{constructor(e){super(e),this.name=vU,this.events=new cce.default,this.initialized=!1,this.requestQueue={state:vs.idle,queue:[]},this.sessionRequestQueue={state:vs.idle,queue:[]},this.requestQueueDelay=Dt.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=vl(br({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:u,relays:a}=n,c=i,f,d=!1;try{c&&(d=this.client.core.pairing.pairings.get(c).active)}catch(L){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),L}if(!c||!d){let{topic:L,uri:k}=await this.client.core.pairing.create();c=L,f=k}if(!c){let{message:L}=G.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(L)}let w=await this.client.core.crypto.generateKeyPair(),A=wn.wc_sessionPropose.req.ttl||Dt.FIVE_MINUTES,T=G.calcExpiry(A),x=br({requiredNamespaces:s,optionalNamespaces:o,relays:a??[{protocol:un.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:T},u&&{sessionProperties:u}),{reject:R,resolve:V,done:U}=G.createDelayedPromise(A,yU);this.events.once(G.engineEvent("session_connect"),async({error:L,session:k})=>{if(L)R(L);else if(k){k.self.publicKey=w;let H=vl(br({},k),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:k.peer.metadata}),V(H)}});let Q=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:x,throwOnFailedPublish:!0});return await this.setProposal(Q,br({id:Q},x)),{uri:f,approval:U}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),U}let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o,sessionConfig:u}=r,a;try{a=this.client.proposal.get(n)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),U}let{pairingTopic:c,proposer:f,requiredNamespaces:d,optionalNamespaces:w}=a;c=c||"";let A=await this.client.core.crypto.generateKeyPair(),T=f.publicKey,x=await this.client.core.crypto.generateSharedKey(A,T),R=br(br({relay:{protocol:i??"irn"},namespaces:s,pairingTopic:c,controller:{publicKey:A,metadata:this.client.metadata},expiry:G.calcExpiry(lu)},o&&{sessionProperties:o}),u&&{sessionConfig:u});await this.client.core.relayer.subscribe(x);let V=vl(br({},R),{topic:x,requiredNamespaces:d,optionalNamespaces:w,pairingTopic:c,acknowledged:!1,self:R.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A});await this.client.session.set(x,V);try{await this.sendResult({id:n,topic:c,result:{relay:{protocol:i??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:R,throwOnFailedPublish:!0})}catch(U){throw this.client.logger.error(U),this.client.session.delete(x,G.getSdkError("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),U}return await this.client.core.pairing.updateMetadata({topic:c,metadata:f.metadata}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}),await this.setExpiry(x,G.calcExpiry(lu)),{topic:x,acknowledged:()=>new Promise(U=>setTimeout(()=>U(this.client.session.get(x)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}let{id:n,reason:i}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}let{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:u}=G.createDelayedPromise(),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),f=this.client.session.get(n).namespaces;return this.events.once(G.engineEvent("session_update",a),({error:d})=>{d?u(d):o()}),await this.client.session.update(n,{namespaces:i}),this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:f}),u(d)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}let{topic:n}=r,i=qe.payloadId(),{done:s,resolve:o,reject:u}=G.createDelayedPromise();return this.events.once(G.engineEvent("session_extend",i),({error:a})=>{a?u(a):o()}),await this.setExpiry(n,G.calcExpiry(lu)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(a=>{u(a)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(A){throw this.client.logger.error("request() -> isValidRequest() failed"),A}let{chainId:n,request:i,topic:s,expiry:o=wn.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),{done:f,resolve:d,reject:w}=G.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(G.engineEvent("session_request",a),({error:A,result:T})=>{A?w(A):d(T)}),await Promise.all([new Promise(async A=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:s,method:"wc_sessionRequest",params:{request:vl(br({},i),{expiryTimestamp:G.calcExpiry(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(T=>w(T)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),A()}),new Promise(async A=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){let x=await G.getDeepLink(this.client.core.storage,$_);G.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:x})}A()}),f()]).then(A=>A[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;qe.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):qe.isJsonRpcError(i)&&await this.sendError({id:s,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=qe.payloadId(),s=qe.getBigIntRpcId().toString(),{done:o,resolve:u,reject:a}=G.createDelayedPromise();this.events.once(G.engineEvent("session_ping",i),({error:c})=>{c?a(c):u()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r,o=qe.getBigIntRpcId().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:G.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:i}=G.getInternalError("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>G.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);let{chains:n,statement:i="",uri:s,domain:o,nonce:u,type:a,exp:c,nbf:f,methods:d=[]}=r,w=[...r.resources||[]],{topic:A,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:T}});let x=await this.client.core.crypto.generateKeyPair(),R=G.hashKey(x);if(await Promise.all([this.client.auth.authKeys.set(ad,{responseTopic:R,publicKey:x}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:A})]),await this.client.core.relayer.subscribe(R),this.client.logger.info(`sending request to new pairing topic: ${A}`),d.length>0){let{namespace:P}=G.parseChainId(n[0]),l=G.createEncodedRecap(P,"request",d);G.getRecapFromResources(w)&&(l=G.mergeEncodedRecaps(l,w.pop())),w.push(l)}let V=G.calcExpiry(wn.wc_sessionPropose.req.ttl),U={authPayload:{type:a??"caip122",chains:n,statement:i,aud:s,domain:o,version:"1",nonce:u,iat:new Date().toISOString(),exp:c,nbf:f,resources:w},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},Q={eip155:{chains:n,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},L={requiredNamespaces:{},optionalNamespaces:Q,relays:[{protocol:"irn"}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},{done:k,resolve:H,reject:q}=G.createDelayedPromise(wn.wc_sessionAuthenticate.req.ttl,"Request expired"),v=async({error:P,session:l})=>{if(this.events.off(G.engineEvent("session_request",D),C),P)q(P);else if(l){l.self.publicKey=x,await this.client.session.set(l.topic,l),await this.setExpiry(l.topic,l.expiry),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:l.peer.metadata});let g=this.client.session.get(l.topic);H({session:g})}},C=async P=>{if(P.error){let M=G.getSdkError("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===M.code?void 0:(this.events.off(G.engineEvent("session_connect"),v),q(P.error.message))}this.events.off(G.engineEvent("session_connect"),v);let{cacaos:l,responder:g}=P.result,y=[],E=[];for(let M of l){await G.validateSignedCacao({cacao:M,projectId:this.client.core.projectId})||(this.client.logger.error(M,"Signature verification failed"),q(G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:N}=M,m=G.getRecapFromResources(N.resources),O=[G.getNamespacedDidChainId(N.iss)],Y=G.getDidAddress(N.iss);if(m){let $=G.getMethodsFromRecap(m),b=G.getChainsFromRecap(m);y.push(...$),O.push(...b)}for(let $ of O)E.push(`${$}:${Y}`)}let S=await this.client.core.crypto.generateSharedKey(x,g.publicKey),_;y.length>0&&(_={topic:S,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:g,controller:g.publicKey,expiry:G.calcExpiry(lu),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:G.buildNamespacesFromAuth([...new Set(y)],[...new Set(E)])},await this.client.core.relayer.subscribe(S),await this.client.session.set(S,_),_=this.client.session.get(S)),H({auths:l,session:_})},D=qe.payloadId(),F=qe.payloadId();this.events.once(G.engineEvent("session_connect"),v),this.events.once(G.engineEvent("session_request",D),C);try{await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:D}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:L,expiry:wn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:F})])}catch(P){throw this.events.off(G.engineEvent("session_connect"),v),this.events.off(G.engineEvent("session_request",D),C),P}return await this.setProposal(F,br({id:F},L)),await this.client.auth.requests.set(D,{authPayload:U.authPayload,requester:U.requester,expiryTimestamp:V,id:D,pairingTopic:A,verifyContext:{}}),{uri:T,response:k}},this.approveSessionAuthenticate=async r=>{this.isInitialized();let{id:n,auths:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u},f=[],d=[];for(let T of i){if(!await G.validateSignedCacao({cacao:T,projectId:this.client.core.projectId})){let Q=G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:a,error:Q,encodeOpts:c}),new Error(Q.message)}let{p:x}=T,R=G.getRecapFromResources(x.resources),V=[G.getNamespacedDidChainId(x.iss)],U=G.getDidAddress(x.iss);if(R){let Q=G.getMethodsFromRecap(R),L=G.getChainsFromRecap(R);f.push(...Q),V.push(...L)}for(let Q of V)d.push(`${Q}:${U}`)}let w=await this.client.core.crypto.generateSharedKey(u,o),A;return f?.length>0&&(A={topic:w,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:o,metadata:s.requester.metadata},controller:o,expiry:G.calcExpiry(lu),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:G.buildNamespacesFromAuth([...new Set(f)],[...new Set(d)])},await this.client.core.relayer.subscribe(w),await this.client.session.set(w,A)),await this.sendResult({topic:a,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:c,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fullfilled",code:0}),await this.client.core.pairing.activate({topic:s.pairingTopic}),{session:A}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();let{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u};await this.sendError({id:n,topic:a,error:i,encodeOpts:c}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:i}=r;return G.formatMessage(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,u;return((o=s.peerMetadata)==null?void 0:o.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:i=!1,emitEvent:s=!0,id:o=0}=r,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,G.getSdkError("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem($_).catch(a=>this.client.logger.warn(a)),this.getPendingSessionRequests().forEach(a=>{a.topic===n&&this.deletePendingSessionRequest(a.id,G.getSdkError("USER_DISCONNECTED"))}),s&&this.client.events.emit("session_delete",{id:o,topic:n})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,G.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=vs.idle,this.client.events.emit("session_request_expire",{id:r}))},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,G.calcExpiry(wn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async r=>{let{id:n,topic:i,params:s,verifyContext:o}=r,u=s.request.expiryTimestamp||G.calcExpiry(wn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:u,clientRpcId:a,throwOnFailedPublish:c}=r,f=qe.formatJsonRpcRequest(i,s,a);if(G.isBrowser()&&EU.includes(i)){let A=G.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:A})}let d;try{d=await this.client.core.crypto.encode(n,f)}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let w=wn[i].req;return o&&(w.ttl=o),u&&(w.id=u),this.client.core.history.set(n,f),c?(w.internal=vl(br({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(A=>this.client.logger.error(A)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:u}=r,a=qe.formatJsonRpcResult(n,s),c;try{c=await this.client.core.crypto.encode(i,a,u)}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let f;try{f=await this.client.core.history.get(i,n)}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),w}let d=wn[f.request.method].res;o?(d.internal=vl(br({},d.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,c,d)):this.client.core.relayer.publish(i,c,d).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(a)},this.sendError=async r=>{let{id:n,topic:i,error:s,encodeOpts:o}=r,u=qe.formatJsonRpcError(n,s),a;try{a=await this.client.core.crypto.encode(i,u,o)}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let c;try{c=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}let f=wn[c.request.method].res;this.client.core.relayer.publish(i,a,f),await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;G.isExpired(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{G.isExpired(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===vs.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vs.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=vs.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:s}))switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=G.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(br({},n.params));let o=i.expiryTimestamp||G.calcExpiry(wn.wc_sessionPropose.req.ttl),u=br({id:s,pairingTopic:r,expiryTimestamp:o},i);await this.setProposal(s,u);let a=G.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(a,u.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:u,verifyContext:c})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(qe.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let u=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});let a=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});let c=await this.client.core.crypto.generateSharedKey(u,a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(qe.isJsonRpcError(n)){await this.client.proposal.delete(i,G.getSdkError("USER_DISCONNECTED"));let s=G.engineEvent("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners, 954`);this.events.emit(G.engineEvent("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:u,expiry:a,namespaces:c,sessionProperties:f,pairingTopic:d,sessionConfig:w}=n.params,A=br(br({topic:r,relay:o,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:d,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},f&&{sessionProperties:f}),w&&{sessionConfig:w});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});let T=G.engineEvent("session_connect");if(this.events.listenerCount(T)===0)throw new Error(`emitting ${T} without any listeners 997`);this.events.emit(G.engineEvent("session_connect"),{session:A}),this.cleanupDuplicatePairings(A)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;qe.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(G.engineEvent("session_approve",i),{})):qe.isJsonRpcError(n)&&(await this.client.session.delete(r,G.getSdkError("USER_DISCONNECTED")),this.events.emit(G.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:G.getSdkError("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(br({topic:r},i));try{G.MemoryStore.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){throw G.MemoryStore.delete(o),a}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_update",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,G.calcExpiry(lu)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_extend",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_ping",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_ping",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(un.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:G.getSdkError("USER_DISCONNECTED")})])}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{await this.isValidRequest(br({topic:r},s));let o=G.hashMessage(JSON.stringify(qe.formatJsonRpcRequest("wc_sessionRequest",s,i))),u=this.client.session.get(r),a=await this.getVerifyContext(o,u.peer.metadata),c={id:i,topic:r,params:s,verifyContext:a};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(br({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),G.MemoryStore.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{let{requester:i,authPayload:s,expiryTimestamp:o}=n.params,u=G.hashMessage(JSON.stringify(n)),a=await this.getVerifyContext(u,this.client.metadata),c={requester:i,pairingTopic:r,id:n.id,authPayload:s,verifyContext:a,expiryTimestamp:o};await this.client.auth.requests.set(n.id,c),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vs.idle,this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{let o=s.request.id,u=G.engineEvent("session_request",o);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(G.engineEvent("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===vs.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vs.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,qe.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(a)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:u}=r;if(G.isUndefined(n)||await this.isValidPairingTopic(n),!G.isValidRelays(u,!0)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(a)}!G.isUndefined(i)&&G.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!G.isUndefined(s)&&G.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=G.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!G.isValidParams(r))throw new Error(G.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let u=this.client.proposal.get(n),a=G.isValidNamespaces(i,"approve()");if(a)throw new Error(a.message);let c=G.isConformingNamespaces(u.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!G.isValidString(s,!0)){let{message:f}=G.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!G.isValidParams(r)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!G.isValidErrorReason(i)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!G.isValidParams(r)){let{message:c}=G.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!G.isValidRelay(n)){let{message:c}=G.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let u=G.isValidController(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);let a=G.isValidNamespaces(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(G.isExpired(o)){let{message:c}=G.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(a)}let{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=G.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let u=G.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(a)}let{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:u}=this.client.session.get(n);if(!G.isValidNamespacesChainId(u,s)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(a)}if(!G.isValidRequest(i)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(a)}if(!G.isValidNamespacesRequest(u,s,i.method)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(a)}if(o&&!G.isValidRequestExpiry(o,t1)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${t1.min} and ${t1.max}`);throw new Error(a)}},this.isValidRespond=async r=>{var n;if(!G.isValidParams(r)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!G.isValidResponse(s)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!G.isValidParams(r)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!G.isValidNamespacesChainId(o,s)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!G.isValidEvent(i)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!G.isValidNamespacesEvent(o,s,i.name)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!G.isValidString(i,!1))throw new Error("uri is required parameter");if(!G.isValidString(s,!1))throw new Error("domain is required parameter");if(!G.isValidString(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(a=>G.parseChainId(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:u}=G.parseChainId(n[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||un.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!G.isValidString(i,!1)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0,s=this.recentlyDeletedLimit/2;for(let o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){let{message:e}=G.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(un.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(ad)?this.client.auth.authKeys.get(ad):{responseTopic:void 0,publicKey:void 0},s=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{qe.isJsonRpcRequest(s)?(this.client.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):qe.isJsonRpcResponse(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.client.core.history.delete(r,s.id)):this.onRelayEventUnknownPayload({topic:r,payload:s})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(un.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=G.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,G.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(un.PAIRING_EVENTS.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(un.PAIRING_EVENTS.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=G.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:r}=G.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(G.isValidString(e,!1)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!G.isValidId(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:r}=G.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},J_=class extends un.Store{constructor(e,r){super(e,r,mU,i1),this.core=e,this.logger=r}},r1=class extends un.Store{constructor(e,r){super(e,r,wU,i1),this.core=e,this.logger=r}},X_=class extends un.Store{constructor(e,r){super(e,r,AU,i1,n=>n.id),this.core=e,this.logger=r}},Z_=class extends un.Store{constructor(e,r){super(e,r,IU,ud,()=>ad),this.core=e,this.logger=r}},e2=class extends un.Store{constructor(e,r){super(e,r,TU,ud),this.core=e,this.logger=r}},t2=class extends un.Store{constructor(e,r){super(e,r,_U,ud,n=>n.id),this.core=e,this.logger=r}},r2=class{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new Z_(this.core,this.logger),this.pairingTopics=new e2(this.core,this.logger),this.requests=new t2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},n1=class t extends gU.ISignClient{constructor(e){super(e),this.protocol=n2,this.version=i2,this.name=e1.name,this.events=new pU.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||e1.name,this.metadata=e?.metadata||G.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zy.pino(Zy.getDefaultLoggerOptions({level:e?.logger||e1.logger}));this.core=e?.core||new un.Core(e),this.logger=Zy.generateChildLogger(r,this.name),this.session=new r1(this.core,this.logger),this.proposal=new J_(this.core,this.logger),this.pendingRequest=new X_(this.core,this.logger),this.engine=new Y_(this),this.auth=new r2(this.core,this.logger)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Zy.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},bce=r1,Sce=n1;Be.AUTH_CONTEXT=SU,Be.AUTH_KEYS_CONTEXT=IU,Be.AUTH_PAIRING_TOPIC_CONTEXT=TU,Be.AUTH_PROTOCOL=bU,Be.AUTH_PUBLIC_KEY_NAME=ad,Be.AUTH_REQUEST_CONTEXT=_U,Be.AUTH_STORAGE_PREFIX=ud,Be.AUTH_VERSION=mce,Be.ENGINE_CONTEXT=vU,Be.ENGINE_QUEUE_STATES=vs,Be.ENGINE_RPC_OPTS=wn,Be.HISTORY_CONTEXT=dce,Be.HISTORY_EVENTS=hce,Be.HISTORY_STORAGE_VERSION=gce,Be.METHODS_TO_VERIFY=EU,Be.PROPOSAL_CONTEXT=mU,Be.PROPOSAL_EXPIRY=pce,Be.PROPOSAL_EXPIRY_MESSAGE=yU,Be.REQUEST_CONTEXT=AU,Be.SESSION_CONTEXT=wU,Be.SESSION_EXPIRY=lu,Be.SESSION_REQUEST_EXPIRY_BOUNDARIES=t1,Be.SIGN_CLIENT_CONTEXT=s2,Be.SIGN_CLIENT_DEFAULT=e1,Be.SIGN_CLIENT_EVENTS=lce,Be.SIGN_CLIENT_PROTOCOL=n2,Be.SIGN_CLIENT_STORAGE_OPTIONS=fce,Be.SIGN_CLIENT_STORAGE_PREFIX=i1,Be.SIGN_CLIENT_VERSION=i2,Be.SessionStore=bce,Be.SignClient=Sce,Be.WALLETCONNECT_DEEPLINK_CHOICE=$_,Be.default=n1});var s1=B(Yo=>{"use strict";h();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.OptionalOperation=Yo.Operation=void 0;var Ice;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(Ice=Yo.Operation||(Yo.Operation={}));var Tce;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(Tce=Yo.OptionalOperation||(Yo.OptionalOperation={}))});var o2=B(As=>{"use strict";h();Object.defineProperty(As,"__esModule",{value:!0});As.WALLETCONNECT_SIGN_LOGIN_DELAY=As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=As.WALLETCONNECT_MULTIVERSX_METHODS=As.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var NU=s1();As.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";As.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(NU.Operation);As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(NU.OptionalOperation);As.WALLETCONNECT_SIGN_LOGIN_DELAY=500});var c2=B(Ci=>{"use strict";h();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WalletConnectV2ProviderErrorMessagesEnum=Ci.ErrBadAddress=Ci.ErrNotImplemented=Ci.Err=void 0;var cd=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ci.Err=cd;var a2=class extends cd{constructor(){super("Method not yet implemented")}};Ci.ErrNotImplemented=a2;var u2=class extends cd{constructor(e,r){super(`Bad address: ${e}`,r)}};Ci.ErrBadAddress=u2;var _ce;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(_ce=Ci.WalletConnectV2ProviderErrorMessagesEnum||(Ci.WalletConnectV2ProviderErrorMessagesEnum={}))});var f2=B(o1=>{"use strict";h();Object.defineProperty(o1,"__esModule",{value:!0});o1.Logger=void 0;var l2=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};o1.Logger=l2});var xU=B(()=>{"use strict";h();global.Buffer||(global.Buffer=io().Buffer)});var g2=B(Al=>{"use strict";h();Object.defineProperty(Al,"__esModule",{value:!0});Al.SmartContractQueryResponse=Al.SmartContractQuery=void 0;var h2=class{constructor(e){this.contract=e.contract,this.caller=e.caller,this.value=e.value,this.function=e.function,this.arguments=e.arguments}};Al.SmartContractQuery=h2;var d2=class{constructor(e){this.function=e.function,this.returnCode=e.returnCode,this.returnMessage=e.returnMessage,this.returnDataParts=e.returnDataParts}};Al.SmartContractQueryResponse=d2});var DU=B(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});a1.QueryRunnerAdapter=void 0;var OU=Ve(),Cce=g2(),p2=class{constructor(e){this.networkProvider=e.networkProvider}async runQuery(e){let r={address:OU.Address.fromBech32(e.contract),caller:e.caller?OU.Address.fromBech32(e.caller):void 0,func:e.function,value:e.value,getEncodedArguments:()=>e.arguments.map(i=>p.Buffer.from(i).toString("hex"))},n=await this.networkProvider.queryContract(r);return new Cce.SmartContractQueryResponse({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.getReturnDataParts()})}};a1.QueryRunnerAdapter=p2});var PU=B(fu=>{"use strict";h();var Nce=fu&&fu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xce=fu&&fu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Nce(e,t,r)};Object.defineProperty(fu,"__esModule",{value:!0});xce(DU(),fu)});var RU=B(hu=>{"use strict";h();var Oce=hu&&hu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dce=hu&&hu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Oce(e,t,r)};Object.defineProperty(hu,"__esModule",{value:!0});Dce(JE(),hu)});var MU=B(du=>{"use strict";h();Object.defineProperty(du,"__esModule",{value:!0});du.GasEstimator=du.DefaultGasConfiguration=void 0;du.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Pce=1e5,BU=8e5,m2=class{constructor(e){this.gasConfiguration=e||du.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Pce}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+BU}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+BU)*r+this.gasConfiguration.gasPerDataByte*e}};du.GasEstimator=m2});var FU=B(LU=>{"use strict";h();Object.defineProperty(LU,"__esModule",{value:!0})});var qU=B(UU=>{"use strict";h();Object.defineProperty(UU,"__esModule",{value:!0})});var VU=B(u1=>{"use strict";h();Object.defineProperty(u1,"__esModule",{value:!0});u1.RelayedTransactionV1Builder=void 0;var y2=Ve(),Rce=Ie(),Bce=Xr(),Mce=Ms(),Lce=oE(),w2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new Rce.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${p.Buffer.from(e).toString("hex")}`,n=new Mce.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new Bce.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new y2.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new y2.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:BigInt(this.innerTransaction.getValue().toString()),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:p.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new y2.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?p.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?p.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return Lce.stringify(e)}};u1.RelayedTransactionV1Builder=w2});var HU=B(c1=>{"use strict";h();Object.defineProperty(c1,"__esModule",{value:!0});c1.RelayedTransactionV2Builder=void 0;var kU=Ie(),ld=qn(),Fce=Xr(),Uce=Ms(),v2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new kU.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new kU.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new ld.ArgSerializer().valuesToString([new ld.AddressValue(this.innerTransaction.getReceiver()),new ld.U64Value(this.innerTransaction.getNonce().valueOf()),new ld.BytesValue(this.innerTransaction.getData().valueOf()),new ld.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Uce.TransactionPayload(r),i=new Fce.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID,version:this.innerTransaction.getVersion(),options:this.innerTransaction.getOptions()});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};c1.RelayedTransactionV2Builder=v2});var GU=B(f1=>{"use strict";h();Object.defineProperty(f1,"__esModule",{value:!0});f1.SmartContractQueriesController=void 0;var qce=Ie(),Vce=g2(),l1=qn(),A2=class{constructor(e){this.abi=e.abi,this.queryRunner=e.queryRunner,this.legacyResultsParser=new l1.ResultsParser}createQuery(e){let r=this.encodeArguments(e.function,e.arguments);return new Vce.SmartContractQuery({contract:e.contract,caller:e.caller,function:e.function,arguments:r,value:e.value})}encodeArguments(e,r){let n=this.abi?.getEndpoint(e);if(n){let i=l1.NativeSerializer.nativeToTypedValues(r,n);return new l1.ArgSerializer().valuesToBuffers(i)}if(this.areArgsOfTypedValue(r))return new l1.ArgSerializer().valuesToBuffers(r);if(this.areArgsBuffers(r))return r.map(i=>p.Buffer.from(i));throw new qce.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}areArgsBuffers(e){for(let r of e)if(!ArrayBuffer.isView(r))return!1;return!0}async runQuery(e){return await this.queryRunner.runQuery(e)}parseQueryResponse(e){if(!this.abi)return e.returnDataParts;let r={returnCode:e.returnCode,returnMessage:e.returnMessage,getReturnDataParts:()=>e.returnDataParts.map(u=>p.Buffer.from(u))},n=e.function,i=this.abi.getEndpoint(n);return this.legacyResultsParser.parseQueryResponse(r,i).values.map(u=>u.valueOf())}};f1.SmartContractQueriesController=A2});var jU=B(ke=>{"use strict";h();var kce=ke&&ke.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pt=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kce(e,t,r)};Object.defineProperty(ke,"__esModule",{value:!0});xU();Pt(Ic(),ke);Pt(PU(),ke);Pt(Ve(),ke);Pt(Fb(),ke);Pt(RU(),ke);Pt(Ie(),ke);Pt(MU(),ke);Pt(FU(),ke);Pt(qU(),ke);Pt(oo(),ke);Pt(Bb(),ke);Pt($l(),ke);Pt(VU(),ke);Pt(HU(),ke);Pt(H0(),ke);Pt(GU(),ke);Pt(qn(),ke);Pt(_b(),ke);Pt(Ca(),ke);Pt(Xr(),ke);Pt(N0(),ke);Pt(Ms(),ke);Pt(V0(),ke);Pt(d0(),ke);Pt(Db(),ke);Pt(Rn(),ke)});var YU=B(ur=>{"use strict";h();var Hce=ur&&ur.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ur,"__esModule",{value:!0});ur.sleep=ur.getMetadata=ur.applyTransactionSignature=ur.getAddressFromSession=ur.addressIsValid=ur.getConnectionParams=ur.getCurrentTopic=ur.getCurrentSession=void 0;var KU=jU(),zU=Yf(),Gce=Qh(),h1=o2(),to=c2(),E2=f2(),QU=s1();function WU(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find($U(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}ur.getCurrentSession=WU;function jce(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=WU(t,e);if(!r?.topic)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}ur.getCurrentTopic=jce;function $U(t,e){var r,n,i;let s=[...h1.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(QU.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(QU.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${h1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],u=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:u}}}}ur.getConnectionParams=$U;function zce(t){try{return!KU.Address.fromBech32(t).isEmpty()}catch{return!1}}ur.addressIsValid=zce;function Qce(t){let e=t.namespaces[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}ur.getAddressFromSession=Qce;function Kce({transaction:t,response:e}){if(!e)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,u=t.getGuardian().bech32();if(u&&u!==o)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(KU.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new zU.Signature(r)),n&&t.applyGuardianSignature(new zU.Signature(n)),t}ur.applyTransactionSignature=Kce;function Wce(t){if(t)return Object.assign(Object.assign({},t),{url:Gce.getAppMetadata().url})}ur.getMetadata=Wce;function $ce(t){return Hce(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}ur.sleep=$ce});var fd=B(cn=>{"use strict";h();var tr=cn&&cn.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Yce=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WalletConnectV2Provider=cn.OptionalOperation=cn.Operation=cn.WalletConnectV2ProviderErrorMessagesEnum=void 0;var Jce=Yf(),Xce=Yce(CU()),b2=Qh(),gu=o2(),he=c2();Object.defineProperty(cn,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return he.WalletConnectV2ProviderErrorMessagesEnum}});var Me=f2(),Jo=s1();Object.defineProperty(cn,"Operation",{enumerable:!0,get:function(){return Jo.Operation}});Object.defineProperty(cn,"OptionalOperation",{enumerable:!0,get:function(){return Jo.OptionalOperation}});var xr=YU(),S2=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return tr(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:xr.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield Xce.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=xr.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Me.Logger.error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return tr(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield xr.sleep(gu.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=xr.getAddressFromSession(n),o=n.namespaces[gu.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:Jo.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:u}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!u)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:u})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||xr.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:b2.getSdkError("USER_DISCONNECTED")});else{let r=xr.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:b2.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new Jce.Signature(n))}catch{throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return xr.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];xr.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=xr.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return tr(this,void 0,void 0,function*(){return e?xr.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Me.Logger.error(`${he.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return tr(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=xr.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&xr.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:u})=>{var a;if(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)return;let{namespaces:c}=u,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>tr(this,void 0,void 0,function*(){var u;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)&&(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>tr(this,void 0,void 0,function*(){var u;!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o||(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=xr.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,u,a,c;return tr(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!b2.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(a=(u=this.walletConnector.core)===null||u===void 0?void 0:u.relayer)===null||a===void 0?void 0:a.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};cn.WalletConnectV2Provider=S2});var XU=B((RTe,JU)=>{"use strict";h();JU.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var tq=B((MTe,eq)=>{"use strict";h();var ZU=typeof Symbol<"u"&&Symbol,Zce=XU();eq.exports=function(){return typeof ZU!="function"||typeof Symbol!="function"||typeof ZU("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Zce()}});var iq=B((FTe,nq)=>{"use strict";h();var rq={foo:{}},ele=Object;nq.exports=function(){return{__proto__:rq}.foo===rq.foo&&!({__proto__:null}instanceof ele)}});var aq=B((qTe,oq)=>{"use strict";h();var tle="Function.prototype.bind called on incompatible ",rle=Object.prototype.toString,nle=Math.max,ile="[object Function]",sq=function(e,r){for(var n=[],i=0;i{"use strict";h();var ale=aq();uq.exports=Function.prototype.bind||ale});var lq=B((GTe,cq)=>{"use strict";h();var ule=Function.prototype.call,cle=Object.prototype.hasOwnProperty,lle=d1();cq.exports=lle.call(ule,cle)});var Xo=B((zTe,pq)=>{"use strict";h();var Re,Il=SyntaxError,gq=Function,Sl=TypeError,I2=function(t){try{return gq('"use strict"; return ('+t+").constructor;")()}catch{}},pu=Object.getOwnPropertyDescriptor;if(pu)try{pu({},"")}catch{pu=null}var T2=function(){throw new Sl},fle=pu?function(){try{return arguments.callee,T2}catch{try{return pu(arguments,"callee").get}catch{return T2}}}():T2,El=tq()(),hle=iq()(),Sr=Object.getPrototypeOf||(hle?function(t){return t.__proto__}:null),bl={},dle=typeof Uint8Array>"u"||!Sr?Re:Sr(Uint8Array),mu={"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":El&&Sr?Sr([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":bl,"%AsyncGenerator%":bl,"%AsyncGeneratorFunction%":bl,"%AsyncIteratorPrototype%":bl,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":gq,"%GeneratorFunction%":bl,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":El&&Sr?Sr(Sr([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!El||!Sr?Re:Sr(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!El||!Sr?Re:Sr(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":El&&Sr?Sr(""[Symbol.iterator]()):Re,"%Symbol%":El?Symbol:Re,"%SyntaxError%":Il,"%ThrowTypeError%":fle,"%TypedArray%":dle,"%TypeError%":Sl,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Sr)try{null.error}catch(t){fq=Sr(Sr(t)),mu["%Error.prototype%"]=fq}var fq,gle=function t(e){var r;if(e==="%AsyncFunction%")r=I2("async function () {}");else if(e==="%GeneratorFunction%")r=I2("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=I2("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Sr&&(r=Sr(i.prototype))}return mu[e]=r,r},hq={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},hd=d1(),g1=lq(),ple=hd.call(Function.call,Array.prototype.concat),mle=hd.call(Function.apply,Array.prototype.splice),dq=hd.call(Function.call,String.prototype.replace),p1=hd.call(Function.call,String.prototype.slice),yle=hd.call(Function.call,RegExp.prototype.exec),wle=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,vle=/\\(\\)?/g,Ale=function(e){var r=p1(e,0,1),n=p1(e,-1);if(r==="%"&&n!=="%")throw new Il("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Il("invalid intrinsic syntax, expected opening `%`");var i=[];return dq(e,wle,function(s,o,u,a){i[i.length]=u?dq(a,vle,"$1"):o||s}),i},Ele=function(e,r){var n=e,i;if(g1(hq,n)&&(i=hq[n],n="%"+i[0]+"%"),g1(mu,n)){var s=mu[n];if(s===bl&&(s=gle(n)),typeof s>"u"&&!r)throw new Sl("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Il("intrinsic "+e+" does not exist!")};pq.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Sl("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Sl('"allowMissing" argument must be a boolean');if(yle(/^%?[^%]*%?$/,e)===null)throw new Il("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Ale(e),i=n.length>0?n[0]:"",s=Ele("%"+i+"%",r),o=s.name,u=s.value,a=!1,c=s.alias;c&&(i=c[0],mle(n,ple([0,1],c)));for(var f=1,d=!0;f=n.length){var x=pu(u,w);d=!!x,d&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[w]}else d=g1(u,w),u=u[w];d&&!a&&(mu[o]=u)}}return u}});var N2=B((KTe,mq)=>{"use strict";h();var ble=Xo(),_2=ble("%Object.defineProperty%",!0),C2=function(){if(_2)try{return _2({},"a",{value:1}),!0}catch{return!1}return!1};C2.hasArrayLengthDefineBug=function(){if(!C2())return null;try{return _2([],"length",{value:1}).length!==1}catch{return!0}};mq.exports=C2});var x2=B(($Te,yq)=>{"use strict";h();var Sle=Xo(),m1=Sle("%Object.getOwnPropertyDescriptor%",!0);if(m1)try{m1([],"length")}catch{m1=null}yq.exports=m1});var Aq=B((JTe,vq)=>{"use strict";h();var Ile=N2()(),O2=Xo(),dd=Ile&&O2("%Object.defineProperty%",!0);if(dd)try{dd({},"a",{value:1})}catch{dd=!1}var Tle=O2("%SyntaxError%"),Tl=O2("%TypeError%"),wq=x2();vq.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Tl("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Tl("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Tl("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Tl("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Tl("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Tl("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,a=!!wq&&wq(e,r);if(dd)dd(e,r,{configurable:o===null&&a?a.configurable:!o,enumerable:i===null&&a?a.enumerable:!i,value:n,writable:s===null&&a?a.writable:!s});else if(u||!i&&!s&&!o)e[r]=n;else throw new Tle("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var _q=B((ZTe,Tq)=>{"use strict";h();var Iq=Xo(),Eq=Aq(),_le=N2()(),bq=x2(),Sq=Iq("%TypeError%"),Cle=Iq("%Math.floor%");Tq.exports=function(e,r){if(typeof e!="function")throw new Sq("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Cle(r)!==r)throw new Sq("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&bq){var o=bq(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(_le?Eq(e,"length",r,!0,!0):Eq(e,"length",r)),e}});var Dq=B((t_e,y1)=>{"use strict";h();var D2=d1(),_l=Xo(),Nle=_q(),xle=_l("%TypeError%"),Nq=_l("%Function.prototype.apply%"),xq=_l("%Function.prototype.call%"),Oq=_l("%Reflect.apply%",!0)||D2.call(xq,Nq),gd=_l("%Object.defineProperty%",!0),Ole=_l("%Math.max%");if(gd)try{gd({},"a",{value:1})}catch{gd=null}y1.exports=function(e){if(typeof e!="function")throw new xle("a function is required");var r=Oq(D2,xq,arguments);return Nle(r,1+Ole(0,e.length-(arguments.length-1)),!0)};var Cq=function(){return Oq(D2,Nq,arguments)};gd?gd(y1.exports,"apply",{value:Cq}):y1.exports.apply=Cq});var Mq=B((n_e,Bq)=>{"use strict";h();var Pq=Xo(),Rq=Dq(),Dle=Rq(Pq("String.prototype.indexOf"));Bq.exports=function(e,r){var n=Pq(e,!!r);return typeof n=="function"&&Dle(e,".prototype.")>-1?Rq(n):n}});var Lq=B(()=>{h()});var r7=B((u_e,t7)=>{h();var k2=typeof Map=="function"&&Map.prototype,P2=Object.getOwnPropertyDescriptor&&k2?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,v1=k2&&P2&&typeof P2.get=="function"?P2.get:null,Fq=k2&&Map.prototype.forEach,H2=typeof Set=="function"&&Set.prototype,R2=Object.getOwnPropertyDescriptor&&H2?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,A1=H2&&R2&&typeof R2.get=="function"?R2.get:null,Uq=H2&&Set.prototype.forEach,Ple=typeof WeakMap=="function"&&WeakMap.prototype,md=Ple?WeakMap.prototype.has:null,Rle=typeof WeakSet=="function"&&WeakSet.prototype,yd=Rle?WeakSet.prototype.has:null,Ble=typeof WeakRef=="function"&&WeakRef.prototype,qq=Ble?WeakRef.prototype.deref:null,Mle=Boolean.prototype.valueOf,Lle=Object.prototype.toString,Fle=Function.prototype.toString,Ule=String.prototype.match,G2=String.prototype.slice,ea=String.prototype.replace,qle=String.prototype.toUpperCase,Vq=String.prototype.toLowerCase,$q=RegExp.prototype.test,kq=Array.prototype.concat,Es=Array.prototype.join,Vle=Array.prototype.slice,Hq=Math.floor,L2=typeof BigInt=="function"?BigInt.prototype.valueOf:null,B2=Object.getOwnPropertySymbols,F2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,Cl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Ur=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Cl||!0)?Symbol.toStringTag:null,Yq=Object.prototype.propertyIsEnumerable,Gq=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function jq(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||$q.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-Hq(-t):Hq(t);if(n!==t){var i=String(n),s=G2.call(e,i.length+1);return ea.call(i,r,"$&_")+"."+ea.call(ea.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return ea.call(e,r,"$&_")}var U2=Lq(),zq=U2.custom,Qq=Xq(zq)?zq:null;t7.exports=function t(e,r,n,i){var s=r||{};if(Zo(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Zo(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=Zo(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Zo(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Zo(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var u=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return e7(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var a=String(e);return u?jq(e,a):a}if(typeof e=="bigint"){var c=String(e)+"n";return u?jq(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return q2(e)?"[Array]":"[Object]";var d=ife(s,n);if(typeof i>"u")i=[];else if(Zq(i,e)>=0)return"[Circular]";function w(l,g,y){if(g&&(i=Vle.call(i),i.push(g)),y){var E={depth:s.depth};return Zo(s,"quoteStyle")&&(E.quoteStyle=s.quoteStyle),t(l,E,n+1,i)}return t(l,s,n+1,i)}if(typeof e=="function"&&!Kq(e)){var A=$le(e),T=w1(e,w);return"[Function"+(A?": "+A:" (anonymous)")+"]"+(T.length>0?" { "+Es.call(T,", ")+" }":"")}if(Xq(e)){var x=Cl?ea.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):F2.call(e);return typeof e=="object"&&!Cl?pd(x):x}if(tfe(e)){for(var R="<"+Vq.call(String(e.nodeName)),V=e.attributes||[],U=0;U",R}if(q2(e)){if(e.length===0)return"[]";var Q=w1(e,w);return d&&!nfe(Q)?"["+V2(Q,d)+"]":"[ "+Es.call(Q,", ")+" ]"}if(Gle(e)){var L=w1(e,w);return!("cause"in Error.prototype)&&"cause"in e&&!Yq.call(e,"cause")?"{ ["+String(e)+"] "+Es.call(kq.call("[cause]: "+w(e.cause),L),", ")+" }":L.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+Es.call(L,", ")+" }"}if(typeof e=="object"&&o){if(Qq&&typeof e[Qq]=="function"&&U2)return U2(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(Yle(e)){var k=[];return Fq&&Fq.call(e,function(l,g){k.push(w(g,e,!0)+" => "+w(l,e))}),Wq("Map",v1.call(e),k,d)}if(Zle(e)){var H=[];return Uq&&Uq.call(e,function(l){H.push(w(l,e))}),Wq("Set",A1.call(e),H,d)}if(Jle(e))return M2("WeakMap");if(efe(e))return M2("WeakSet");if(Xle(e))return M2("WeakRef");if(zle(e))return pd(w(Number(e)));if(Kle(e))return pd(w(L2.call(e)));if(Qle(e))return pd(Mle.call(e));if(jle(e))return pd(w(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!Hle(e)&&!Kq(e)){var q=w1(e,w),v=Gq?Gq(e)===Object.prototype:e instanceof Object||e.constructor===Object,C=e instanceof Object?"":"null prototype",D=!v&&Ur&&Object(e)===e&&Ur in e?G2.call(ta(e),8,-1):C?"Object":"",F=v||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",P=F+(D||C?"["+Es.call(kq.call([],D||[],C||[]),": ")+"] ":"");return q.length===0?P+"{}":d?P+"{"+V2(q,d)+"}":P+"{ "+Es.call(q,", ")+" }"}return String(e)};function Jq(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function kle(t){return ea.call(String(t),/"/g,""")}function q2(t){return ta(t)==="[object Array]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Hle(t){return ta(t)==="[object Date]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Kq(t){return ta(t)==="[object RegExp]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Gle(t){return ta(t)==="[object Error]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function jle(t){return ta(t)==="[object String]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function zle(t){return ta(t)==="[object Number]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Qle(t){return ta(t)==="[object Boolean]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Xq(t){if(Cl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!F2)return!1;try{return F2.call(t),!0}catch{}return!1}function Kle(t){if(!t||typeof t!="object"||!L2)return!1;try{return L2.call(t),!0}catch{}return!1}var Wle=Object.prototype.hasOwnProperty||function(t){return t in this};function Zo(t,e){return Wle.call(t,e)}function ta(t){return Lle.call(t)}function $le(t){if(t.name)return t.name;var e=Ule.call(Fle.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function Zq(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return e7(G2.call(t,0,e.maxStringLength),e)+n}var i=ea.call(ea.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,rfe);return Jq(i,"single",e)}function rfe(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+qle.call(e.toString(16))}function pd(t){return"Object("+t+")"}function M2(t){return t+" { ? }"}function Wq(t,e,r,n){var i=n?V2(r,n):Es.call(r,", ");return t+" ("+e+") {"+i+"}"}function nfe(t){for(var e=0;e=0)return!1;return!0}function ife(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Es.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Es.call(Array(e+1),r)}}function V2(t,e){if(t.length===0)return"";var r=` +`+e.prev+e.base;return r+Es.call(t,","+r)+` +`+e.prev}function w1(t,e){var r=q2(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";h();var j2=Xo(),Nl=Mq(),sfe=r7(),ofe=j2("%TypeError%"),E1=j2("%WeakMap%",!0),b1=j2("%Map%",!0),afe=Nl("WeakMap.prototype.get",!0),ufe=Nl("WeakMap.prototype.set",!0),cfe=Nl("WeakMap.prototype.has",!0),lfe=Nl("Map.prototype.get",!0),ffe=Nl("Map.prototype.set",!0),hfe=Nl("Map.prototype.has",!0),z2=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},dfe=function(t,e){var r=z2(t,e);return r&&r.value},gfe=function(t,e,r){var n=z2(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},pfe=function(t,e){return!!z2(t,e)};n7.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new ofe("Side channel does not contain "+sfe(s))},get:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return afe(e,s)}else if(b1){if(r)return lfe(r,s)}else if(n)return dfe(n,s)},has:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return cfe(e,s)}else if(b1){if(r)return hfe(r,s)}else if(n)return pfe(n,s);return!1},set:function(s,o){E1&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new E1),ufe(e,s,o)):b1?(r||(r=new b1),ffe(r,s,o)):(n||(n={key:{},next:null}),gfe(n,s,o))}};return i}});var S1=B((h_e,s7)=>{"use strict";h();var mfe=String.prototype.replace,yfe=/%20/g,Q2={RFC1738:"RFC1738",RFC3986:"RFC3986"};s7.exports={default:Q2.RFC3986,formatters:{RFC1738:function(t){return mfe.call(t,yfe,"+")},RFC3986:function(t){return String(t)}},RFC1738:Q2.RFC1738,RFC3986:Q2.RFC3986}});var W2=B((g_e,a7)=>{"use strict";h();var wfe=S1(),K2=Object.prototype.hasOwnProperty,yu=Array.isArray,bs=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),vfe=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(yu(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===wfe.RFC1738&&(c===40||c===41)){u+=o.charAt(a);continue}if(c<128){u=u+bs[c];continue}if(c<2048){u=u+(bs[192|c>>6]+bs[128|c&63]);continue}if(c<55296||c>=57344){u=u+(bs[224|c>>12]+bs[128|c>>6&63]+bs[128|c&63]);continue}a+=1,c=65536+((c&1023)<<10|o.charCodeAt(a)&1023),u+=bs[240|c>>18]+bs[128|c>>12&63]+bs[128|c>>6&63]+bs[128|c&63]}return u},Ife=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";h();var l7=i7(),Y2=W2(),wd=S1(),xfe=Object.prototype.hasOwnProperty,u7={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},wu=Array.isArray,Ofe=String.prototype.split,Dfe=Array.prototype.push,f7=function(t,e){Dfe.apply(t,wu(e)?e:[e])},Pfe=Date.prototype.toISOString,c7=wd.default,Or={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Y2.encode,encodeValuesOnly:!1,format:c7,formatter:wd.formatters[c7],indices:!1,serializeDate:function(e){return Pfe.call(e)},skipNulls:!1,strictNullHandling:!1},Rfe=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},$2={},Bfe=function t(e,r,n,i,s,o,u,a,c,f,d,w,A,T,x){for(var R=e,V=x,U=0,Q=!1;(V=V.get($2))!==void 0&&!Q;){var L=V.get(e);if(U+=1,typeof L<"u"){if(L===U)throw new RangeError("Cyclic object value");Q=!0}typeof V.get($2)>"u"&&(U=0)}if(typeof u=="function"?R=u(r,R):R instanceof Date?R=f(R):n==="comma"&&wu(R)&&(R=Y2.maybeMap(R,function(S){return S instanceof Date?f(S):S})),R===null){if(i)return o&&!A?o(r,Or.encoder,T,"key",d):r;R=""}if(Rfe(R)||Y2.isBuffer(R)){if(o){var k=A?r:o(r,Or.encoder,T,"key",d);if(n==="comma"&&A){for(var H=Ofe.call(String(R),","),q="",v=0;v"u")return C;var D;if(n==="comma"&&wu(R))D=[{value:R.length>0?R.join(",")||null:void 0}];else if(wu(u))D=u;else{var F=Object.keys(R);D=a?F.sort(a):F}for(var P=0;P"u"?Or.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Or.charsetSentinel,delimiter:typeof e.delimiter>"u"?Or.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Or.encode,encoder:typeof e.encoder=="function"?e.encoder:Or.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Or.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Or.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Or.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Or.strictNullHandling}};h7.exports=function(t,e){var r=t,n=Mfe(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):wu(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var u;e&&e.arrayFormat in u7?u=e.arrayFormat:e&&"indices"in e?u=e.indices?"indices":"repeat":u="indices";var a=u7[u];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=l7(),f=0;f0?A+w:""}});var m7=B((w_e,p7)=>{"use strict";h();var xl=W2(),J2=Object.prototype.hasOwnProperty,Lfe=Array.isArray,Ir={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:xl.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Ffe=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},g7=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},Ufe="utf8=%26%2310003%3B",qfe="utf8=%E2%9C%93",Vfe=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),u=-1,a,c=r.charset;if(r.charsetSentinel)for(a=0;a-1&&(T=Lfe(T)?[T]:T),J2.call(n,A)?n[A]=xl.combine(n[A],T):n[A]=T}return n},kfe=function(t,e,r,n){for(var i=n?e:g7(e,r),s=t.length-1;s>=0;--s){var o,u=t[s];if(u==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var a=u.charAt(0)==="["&&u.charAt(u.length-1)==="]"?u.slice(1,-1):u,c=parseInt(a,10);!r.parseArrays&&a===""?o={0:i}:!isNaN(c)&&u!==a&&String(c)===a&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):a!=="__proto__"&&(o[a]=i)}i=o}return i},Hfe=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,u=/(\[[^[\]]*])/g,a=n.depth>0&&o.exec(s),c=a?s.slice(0,a.index):s,f=[];if(c){if(!n.plainObjects&&J2.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(a=u.exec(s))!==null&&d"u"?Ir.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?Ir.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:Ir.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:Ir.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:Ir.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ir.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:Ir.comma,decoder:typeof e.decoder=="function"?e.decoder:Ir.decoder,delimiter:typeof e.delimiter=="string"||xl.isRegExp(e.delimiter)?e.delimiter:Ir.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:Ir.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:Ir.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:Ir.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:Ir.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ir.strictNullHandling}};p7.exports=function(t,e){var r=Gfe(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?Vfe(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";h();var jfe=d7(),zfe=m7(),Qfe=S1();y7.exports={formats:Qfe,parse:zfe,stringify:jfe}});var X2=B(je=>{"use strict";h();Object.defineProperty(je,"__esModule",{value:!0});je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=je.WALLET_PROVIDER_CALLBACK_PARAM=je.WALLET_PROVIDER_SIGN_MESSAGE_URL=je.WALLET_PROVIDER_GUARD_TRANSACTION_URL=je.WALLET_PROVIDER_SIGN_TRANSACTION_URL=je.WALLET_PROVIDER_SEND_TRANSACTION_URL=je.WALLET_PROVIDER_DISCONNECT_URL=je.WALLET_PROVIDER_CONNECT_URL=je.XALIAS_PROVIDER_TESTNET=je.XALIAS_PROVIDER_DEVNET=je.XALIAS_PROVIDER_MAINNET=je.WALLET_PROVIDER_TESTNET=je.WALLET_PROVIDER_DEVNET=je.WALLET_PROVIDER_MAINNET=void 0;je.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";je.XALIAS_PROVIDER_MAINNET="https://xalias.com";je.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";je.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";je.WALLET_PROVIDER_CONNECT_URL="hook/login";je.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";je.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";je.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";je.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";je.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";je.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var v7=B(Ol=>{"use strict";h();Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrCannotSignedMessage=Ol.ErrCannotGetSignedTransactions=void 0;var Z2=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Ol.ErrCannotGetSignedTransactions=Z2;var eC=class extends Error{constructor(){super("Cannot get signed message")}};Ol.ErrCannotSignedMessage=eC});var A7=B(I1=>{"use strict";h();Object.defineProperty(I1,"__esModule",{value:!0});I1.PlainSignedTransaction=void 0;var tC=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};I1.PlainSignedTransaction=tC});var Dl=B(ia=>{"use strict";h();var ra=ia&&ia.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Kfe=ia&&ia.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ia,"__esModule",{value:!0});ia.WalletProvider=void 0;var rC=Kfe(w7()),na=X2(),nC=v7(),Wfe=A7(),iC=class t{constructor(e){this.walletUrl=e}login(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return ra(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return ra(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return ra(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=rC.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new nC.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return ra(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(e=window.location.search){let r=rC.default.parse(e.slice(1));return t.isTxSignReturnSuccess(r)?this.getTxSignReturnValue(r):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(na.WALLET_PROVIDER_CALLBACK_PARAM)&&e[na.WALLET_PROVIDER_CALLBACK_PARAM]===na.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new nC.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new nC.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let u=t.prepareWalletTransaction(o);for(let a in u)u.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(i[a]=[]),i[a].push(u[a])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};ia.WalletProvider=iC});var e9=B((O_e,Z7)=>{"use strict";h();function P7(t,e){return function(){return t.apply(e,arguments)}}var{toString:$fe}=Object.prototype,{getPrototypeOf:mC}=Object,N1=(t=>e=>{let r=$fe.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Is=t=>(t=t.toLowerCase(),e=>N1(e)===t),x1=t=>e=>typeof e===t,{isArray:Ml}=Array,Ad=x1("undefined");function Yfe(t){return t!==null&&!Ad(t)&&t.constructor!==null&&!Ad(t.constructor)&&ei(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var R7=Is("ArrayBuffer");function Jfe(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&R7(t.buffer),e}var Xfe=x1("string"),ei=x1("function"),B7=x1("number"),O1=t=>t!==null&&typeof t=="object",Zfe=t=>t===!0||t===!1,T1=t=>{if(N1(t)!=="object")return!1;let e=mC(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ehe=Is("Date"),the=Is("File"),rhe=Is("Blob"),nhe=Is("FileList"),ihe=t=>O1(t)&&ei(t.pipe),she=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ei(t.append)&&((e=N1(t))==="formdata"||e==="object"&&ei(t.toString)&&t.toString()==="[object FormData]"))},ohe=Is("URLSearchParams"),ahe=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ed(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ml(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var L7=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F7=t=>!Ad(t)&&t!==L7;function cC(){let{caseless:t}=F7(this)&&this||{},e={},r=(n,i)=>{let s=t&&M7(e,i)||i;T1(e[s])&&T1(n)?e[s]=cC(e[s],n):T1(n)?e[s]=cC({},n):Ml(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(Ed(e,(i,s)=>{r&&ei(i)?t[s]=P7(i,r):t[s]=i},{allOwnKeys:n}),t),che=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),lhe=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},fhe=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&mC(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},hhe=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},dhe=t=>{if(!t)return null;if(Ml(t))return t;let e=t.length;if(!B7(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},ghe=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&mC(Uint8Array)),phe=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},mhe=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},yhe=Is("HTMLFormElement"),whe=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),E7=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),vhe=Is("RegExp"),U7=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};Ed(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},Ahe=t=>{U7(t,(e,r)=>{if(ei(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(ei(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Ehe=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ml(t)?n(t):n(String(t).split(e)),r},bhe=()=>{},She=(t,e)=>(t=+t,Number.isFinite(t)?t:e),sC="abcdefghijklmnopqrstuvwxyz",b7="0123456789",q7={DIGIT:b7,ALPHA:sC,ALPHA_DIGIT:sC+sC.toUpperCase()+b7},Ihe=(t=16,e=q7.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function The(t){return!!(t&&ei(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var _he=t=>{let e=new Array(10),r=(n,i)=>{if(O1(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ml(n)?[]:{};return Ed(n,(o,u)=>{let a=r(o,i+1);!Ad(a)&&(s[u]=a)}),e[i]=void 0,s}}return n};return r(t,0)},Che=Is("AsyncFunction"),Nhe=t=>t&&(O1(t)||ei(t))&&ei(t.then)&&ei(t.catch),re={isArray:Ml,isArrayBuffer:R7,isBuffer:Yfe,isFormData:she,isArrayBufferView:Jfe,isString:Xfe,isNumber:B7,isBoolean:Zfe,isObject:O1,isPlainObject:T1,isUndefined:Ad,isDate:ehe,isFile:the,isBlob:rhe,isRegExp:vhe,isFunction:ei,isStream:ihe,isURLSearchParams:ohe,isTypedArray:ghe,isFileList:nhe,forEach:Ed,merge:cC,extend:uhe,trim:ahe,stripBOM:che,inherits:lhe,toFlatObject:fhe,kindOf:N1,kindOfTest:Is,endsWith:hhe,toArray:dhe,forEachEntry:phe,matchAll:mhe,isHTMLForm:yhe,hasOwnProperty:E7,hasOwnProp:E7,reduceDescriptors:U7,freezeMethods:Ahe,toObjectSet:Ehe,toCamelCase:whe,noop:bhe,toFiniteNumber:She,findKey:M7,global:L7,isContextDefined:F7,ALPHABET:q7,generateString:Ihe,isSpecCompliantForm:The,toJSONObject:_he,isAsyncFn:Che,isThenable:Nhe};function Le(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}re.inherits(Le,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:re.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var V7=Le.prototype,k7={};["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(t=>{k7[t]={value:t}});Object.defineProperties(Le,k7);Object.defineProperty(V7,"isAxiosError",{value:!0});Le.from=(t,e,r,n,i,s)=>{let o=Object.create(V7);return re.toFlatObject(t,o,function(a){return a!==Error.prototype},u=>u!=="isAxiosError"),Le.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var xhe=null;function lC(t){return re.isPlainObject(t)||re.isArray(t)}function H7(t){return re.endsWith(t,"[]")?t.slice(0,-2):t}function S7(t,e,r){return t?t.concat(e).map(function(i,s){return i=H7(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Ohe(t){return re.isArray(t)&&!t.some(lC)}var Dhe=re.toFlatObject(re,{},null,function(e){return/^is[A-Z]/.test(e)});function D1(t,e,r){if(!re.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=re.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,R){return!re.isUndefined(R[x])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,a=(r.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function c(T){if(T===null)return"";if(re.isDate(T))return T.toISOString();if(!a&&re.isBlob(T))throw new Le("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(T)||re.isTypedArray(T)?a&&typeof Blob=="function"?new Blob([T]):p.Buffer.from(T):T}function f(T,x,R){let V=T;if(T&&!R&&typeof T=="object"){if(re.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=JSON.stringify(T);else if(re.isArray(T)&&Ohe(T)||(re.isFileList(T)||re.endsWith(x,"[]"))&&(V=re.toArray(T)))return x=H7(x),V.forEach(function(Q,L){!(re.isUndefined(Q)||Q===null)&&e.append(o===!0?S7([x],L,s):o===null?x:x+"[]",c(Q))}),!1}return lC(T)?!0:(e.append(S7(R,x,s),c(T)),!1)}let d=[],w=Object.assign(Dhe,{defaultVisitor:f,convertValue:c,isVisitable:lC});function A(T,x){if(!re.isUndefined(T)){if(d.indexOf(T)!==-1)throw Error("Circular reference detected in "+x.join("."));d.push(T),re.forEach(T,function(V,U){(!(re.isUndefined(V)||V===null)&&i.call(e,V,re.isString(U)?U.trim():U,x,w))===!0&&A(V,x?x.concat(U):[U])}),d.pop()}}if(!re.isObject(t))throw new TypeError("data must be an object");return A(t),e}function I7(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function yC(t,e){this._pairs=[],t&&D1(t,this,e)}var G7=yC.prototype;G7.append=function(e,r){this._pairs.push([e,r])};G7.toString=function(e){let r=e?function(n){return e.call(this,n,I7)}:I7;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Phe(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function j7(t,e,r){if(!e)return t;let n=r&&r.encode||Phe,i=r&&r.serialize,s;if(i?s=i(e,r):s=re.isURLSearchParams(e)?e.toString():new yC(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var fC=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(n){n!==null&&e(n)})}},T7=fC,z7={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Rhe=typeof URLSearchParams<"u"?URLSearchParams:yC,Bhe=typeof FormData<"u"?FormData:null,Mhe=typeof Blob<"u"?Blob:null,Lhe={isBrowser:!0,classes:{URLSearchParams:Rhe,FormData:Bhe,Blob:Mhe},protocols:["http","https","file","blob","url","data"]},Q7=typeof window<"u"&&typeof document<"u",Fhe=(t=>Q7&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),Uhe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",qhe=Object.freeze({__proto__:null,hasBrowserEnv:Q7,hasStandardBrowserWebWorkerEnv:Uhe,hasStandardBrowserEnv:Fhe}),Ss={...qhe,...Lhe};function Vhe(t,e){return D1(t,new Ss.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Ss.isNode&&re.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function khe(t){return re.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Hhe(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&re.isArray(i)?i.length:o,a?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&re.isArray(i[o])&&(i[o]=Hhe(i[o])),!u)}if(re.isFormData(t)&&re.isFunction(t.entries)){let r={};return re.forEachEntry(t,(n,i)=>{e(khe(n),i,r,0)}),r}return null}function Ghe(t,e,r){if(re.isString(t))try{return(e||JSON.parse)(t),re.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var wC={transitional:z7,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=re.isObject(e);if(s&&re.isHTMLForm(e)&&(e=new FormData(e)),re.isFormData(e))return i?JSON.stringify(K7(e)):e;if(re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e))return e;if(re.isArrayBufferView(e))return e.buffer;if(re.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Vhe(e,this.formSerializer).toString();if((u=re.isFileList(e))||n.indexOf("multipart/form-data")>-1){let a=this.env&&this.env.FormData;return D1(u?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Ghe(e)):e}],transformResponse:[function(e){let r=this.transitional||wC.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&re.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?Le.from(u,Le.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ss.classes.FormData,Blob:Ss.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],t=>{wC.headers[t]={}});var vC=wC,jhe=re.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"]),zhe=t=>{let e={},r,n,i;return t&&t.split(` +`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&jhe[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},_7=Symbol("internals");function vd(t){return t&&String(t).trim().toLowerCase()}function _1(t){return t===!1||t==null?t:re.isArray(t)?t.map(_1):String(t)}function Qhe(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Khe=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function oC(t,e,r,n,i){if(re.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function Whe(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function $he(t,e){let r=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Pl=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,a,c){let f=vd(a);if(!f)throw new Error("header name must be a non-empty string");let d=re.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||a]=_1(u))}let o=(u,a)=>re.forEach(u,(c,f)=>s(c,f,a));return re.isPlainObject(e)||e instanceof this.constructor?o(e,r):re.isString(e)&&(e=e.trim())&&!Khe(e)?o(zhe(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=vd(e),e){let n=re.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Qhe(i);if(re.isFunction(r))return r.call(this,i,n);if(re.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=vd(e),e){let n=re.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||oC(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=vd(o),o){let u=re.findKey(n,o);u&&(!r||oC(n,n[u],u,r))&&(delete n[u],i=!0)}}return re.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||oC(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return re.forEach(this,(i,s)=>{let o=re.findKey(n,s);if(o){r[o]=_1(i),delete r[s];return}let u=e?Whe(s):String(s).trim();u!==s&&delete r[s],r[u]=_1(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return re.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&re.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[_7]=this[_7]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=vd(o);n[u]||($he(i,o),n[u]=!0)}return re.isArray(e)?e.forEach(s):s(e),this}};Pl.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);re.reduceDescriptors(Pl.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});re.freezeMethods(Pl);var ro=Pl;function aC(t,e){let r=this||vC,n=e||r,i=ro.from(n.headers),s=n.data;return re.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function W7(t){return!!(t&&t.__CANCEL__)}function bd(t,e,r){Le.call(this,t??"canceled",Le.ERR_CANCELED,e,r),this.name="CanceledError"}re.inherits(bd,Le,{__CANCEL__:!0});function Yhe(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Le("Request failed with status code "+r.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var Jhe=Ss.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];re.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),re.isString(n)&&o.push("path="+n),re.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Xhe(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Zhe(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function $7(t,e){return t&&!Xhe(e)?Zhe(t,e):e}var ede=Ss.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=re.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function tde(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function rde(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(a){let c=Date.now(),f=n[s];o||(o=c),r[i]=a,n[i]=c;let d=s,w=0;for(;d!==i;)w+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,a=n(u),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:a||void 0,estimated:a&&o&&c?(o-s)/a:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var nde=typeof XMLHttpRequest<"u",ide=nde&&function(t){return new Promise(function(r,n){let i=t.data,s=ro.from(t.headers).normalize(),{responseType:o,withXSRFToken:u}=t,a;function c(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}let f;if(re.isFormData(i)){if(Ss.hasStandardBrowserEnv||Ss.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[x,...R]=f?f.split(";").map(V=>V.trim()).filter(Boolean):[];s.setContentType([x||"multipart/form-data",...R].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let x=t.auth.username||"",R=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(x+":"+R))}let w=$7(t.baseURL,t.url);d.open(t.method.toUpperCase(),j7(w,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function A(){if(!d)return;let x=ro.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),V={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:x,config:t,request:d};Yhe(function(Q){r(Q),c()},function(Q){n(Q),c()},V),d=null}if("onloadend"in d?d.onloadend=A:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(A)},d.onabort=function(){d&&(n(new Le("Request aborted",Le.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Le("Network Error",Le.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let R=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||z7;t.timeoutErrorMessage&&(R=t.timeoutErrorMessage),n(new Le(R,V.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,t,d)),d=null},Ss.hasStandardBrowserEnv&&(u&&re.isFunction(u)&&(u=u(t)),u||u!==!1&&ede(w))){let x=t.xsrfHeaderName&&t.xsrfCookieName&&Jhe.read(t.xsrfCookieName);x&&s.set(t.xsrfHeaderName,x)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&re.forEach(s.toJSON(),function(R,V){d.setRequestHeader(V,R)}),re.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",C7(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",C7(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=x=>{d&&(n(!x||x.type?new bd(null,t,d):x),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));let T=tde(w);if(T&&Ss.protocols.indexOf(T)===-1){n(new Le("Unsupported protocol "+T+":",Le.ERR_BAD_REQUEST,t));return}d.send(i||null)})},hC={http:xhe,xhr:ide};re.forEach(hC,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var N7=t=>`- ${t}`,sde=t=>re.isFunction(t)||t===null||t===!1,Y7={getAdapter:t=>{t=re.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${u} `+(a===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : +`+s.map(N7).join(` +`):" "+N7(s[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:hC};function uC(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new bd(null,t)}function x7(t){return uC(t),t.headers=ro.from(t.headers),t.data=aC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Y7.getAdapter(t.adapter||vC.adapter)(t).then(function(n){return uC(t),n.data=aC.call(t,t.transformResponse,n),n.headers=ro.from(n.headers),n},function(n){return W7(n)||(uC(t),n&&n.response&&(n.response.data=aC.call(t,t.transformResponse,n.response),n.response.headers=ro.from(n.response.headers))),Promise.reject(n)})}var O7=t=>t instanceof ro?{...t}:t;function Rl(t,e){e=e||{};let r={};function n(c,f,d){return re.isPlainObject(c)&&re.isPlainObject(f)?re.merge.call({caseless:d},c,f):re.isPlainObject(f)?re.merge({},f):re.isArray(f)?f.slice():f}function i(c,f,d){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!re.isUndefined(f))return n(void 0,f)}function o(c,f){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function u(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let 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:u,headers:(c,f)=>i(O7(c),O7(f),!0)};return re.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=a[f]||i,w=d(t[f],e[f],f);re.isUndefined(w)&&d!==u||(r[f]=w)}),r}var J7="1.6.8",AC={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{AC[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var D7={};AC.transitional=function(e,r,n){function i(s,o){return"[Axios v"+J7+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new Le(i(o," has been removed"+(r?" in "+r:"")),Le.ERR_DEPRECATED);return r&&!D7[o]&&(D7[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function ode(t,e,r){if(typeof t!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],a=u===void 0||o(u,s,t);if(a!==!0)throw new Le("option "+s+" must be "+a,Le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}var dC={assertOptions:ode,validators:AC},sa=dC.validators,Bl=class{constructor(e){this.defaults=e,this.interceptors={request:new T7,response:new T7}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` +`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Rl(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&dC.assertOptions(n,{silentJSONParsing:sa.transitional(sa.boolean),forcedJSONParsing:sa.transitional(sa.boolean),clarifyTimeoutError:sa.transitional(sa.boolean)},!1),i!=null&&(re.isFunction(i)?r.paramsSerializer={serialize:i}:dC.assertOptions(i,{encode:sa.function,serialize:sa.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&re.merge(s.common,s[r.method]);s&&re.forEach(["delete","get","head","post","put","patch","common"],T=>{delete s[T]}),r.headers=ro.concat(o,s);let u=[],a=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(r)===!1||(a=a&&x.synchronous,u.unshift(x.fulfilled,x.rejected))});let c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let f,d=0,w;if(!a){let T=[x7.bind(this),void 0];for(T.unshift.apply(T,u),T.push.apply(T,c),w=T.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new bd(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},ade=gC;function ude(t){return function(r){return t.apply(null,r)}}function cde(t){return re.isObject(t)&&t.isAxiosError===!0}var pC={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(pC).forEach(([t,e])=>{pC[e]=t});var lde=pC;function X7(t){let e=new C1(t),r=P7(C1.prototype.request,e);return re.extend(r,C1.prototype,e,{allOwnKeys:!0}),re.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return X7(Rl(t,i))},r}var cr=X7(vC);cr.Axios=C1;cr.CanceledError=bd;cr.CancelToken=ade;cr.isCancel=W7;cr.VERSION=J7;cr.toFormData=D1;cr.AxiosError=Le;cr.Cancel=cr.CanceledError;cr.all=function(e){return Promise.all(e)};cr.spread=ude;cr.isAxiosError=cde;cr.mergeConfig=Rl;cr.AxiosHeaders=ro;cr.formToJSON=t=>K7(re.isHTMLForm(t)?new FormData(t):t);cr.getAdapter=Y7.getAdapter;cr.HttpStatusCode=lde;cr.default=cr;Z7.exports=cr});var t9=B(P1=>{"use strict";h();Object.defineProperty(P1,"__esModule",{value:!0});P1.NativeAuthClientConfig=void 0;var EC=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};P1.NativeAuthClientConfig=EC});var SC=B(Ll=>{"use strict";h();var vu=Ll&&Ll.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.NativeAuthClient=void 0;var fde=e9(),hde=t9(),bC=class{constructor(e){this.config=Object.assign(new hde.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vu(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vu(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vu(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vu(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vu(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vu(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(p.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vu(this,void 0,void 0,function*(){return yield fde.default.get(e,{headers:this.config.extraRequestHeaders})})}};Ll.NativeAuthClient=bC});var s9=B(B1=>{"use strict";h();Object.defineProperty(B1,"__esModule",{value:!0});B1.TransactionStatus=void 0;var TC=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};B1.TransactionStatus=TC});var a9=B(M1=>{"use strict";h();Object.defineProperty(M1,"__esModule",{value:!0});M1.TransactionReceipt=void 0;var o9=_c(),_C=class t{constructor(){this.value="",this.sender=new o9.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new o9.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};M1.TransactionReceipt=_C});var u9=B(Ts=>{"use strict";h();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ErrContractQuery=Ts.ErrNetworkProvider=Ts.ErrUnexpectedCondition=Ts.Err=void 0;var Ul=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ts.Err=Ul;var CC=class extends Ul{constructor(e){super(`Unexpected condition: [${e}]`)}};Ts.ErrUnexpectedCondition=CC;var NC=class extends Ul{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Ts.ErrNetworkProvider=NC;var xC=class extends Ul{constructor(e){super(e.message.replace("executeQuery:",""))}};Ts.ErrContractQuery=xC});var l9=B(oa=>{"use strict";h();Object.defineProperty(oa,"__esModule",{value:!0});oa.TransactionEventTopic=oa.TransactionEventData=oa.TransactionEvent=void 0;var c9=_c(),OC=class t{constructor(e){this.address=new c9.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new ql(p.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new c9.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new L1(n)),r.dataPayload=ql.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(ql.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};oa.TransactionEvent=OC;var ql=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(p.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventData=ql;var L1=class{constructor(e){this.raw=p.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventTopic=L1});var PC=B(F1=>{"use strict";h();Object.defineProperty(F1,"__esModule",{value:!0});F1.TransactionLogs=void 0;var pde=u9(),f9=_c(),mde=l9(),DC=class t{constructor(e){this.address=new f9.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new f9.Address(e.address),r.events=(e.events||[]).map(n=>mde.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new pde.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};F1.TransactionLogs=DC});var d9=B(Vl=>{"use strict";h();Object.defineProperty(Vl,"__esModule",{value:!0});Vl.ContractResultItem=Vl.ContractResults=void 0;var h9=PC(),U1=_c(),RC=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>Sd.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>Sd.fromApiHttpResponse(n));return new t(r)}};Vl.ContractResults=RC;var Sd=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new U1.Address(""),this.sender=new U1.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new h9.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=p.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new U1.Address(e.receiver),r.sender=new U1.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=h9.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Vl.ContractResultItem=Sd});var g9=B(q1=>{"use strict";h();Object.defineProperty(q1,"__esModule",{value:!0});q1.ContractQueryRequest=void 0;var BC=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};q1.ContractQueryRequest=BC});var _9=B((R2e,T9)=>{h();T9.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var aa=B(Eu=>{h();var MC,yde=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Eu.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Eu.getSymbolTotalCodewords=function(e){return yde[e]};Eu.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Eu.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');MC=e};Eu.isKanjiModeEnabled=function(){return typeof MC<"u"};Eu.toSJIS=function(e){return MC(e)}});var G1=B(ti=>{h();ti.L={bit:1};ti.M={bit:0};ti.Q={bit:3};ti.H={bit:2};function wde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ti.L;case"m":case"medium":return ti.M;case"q":case"quartile":return ti.Q;case"h":case"high":return ti.H;default:throw new Error("Unknown EC Level: "+t)}}ti.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ti.from=function(e,r){if(ti.isValid(e))return e;try{return wde(e)}catch{return r}}});var x9=B((q2e,N9)=>{h();function C9(){this.buffer=[],this.length=0}C9.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};N9.exports=C9});var D9=B((k2e,O9)=>{h();function Id(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Id.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};Id.prototype.get=function(t,e){return this.data[t*this.size+e]};Id.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Id.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};O9.exports=Id});var P9=B(j1=>{h();var vde=aa().getSymbolSize;j1.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=vde(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{h();var Ade=aa().getSymbolSize,R9=7;B9.getPositions=function(e){let r=Ade(e);return[[0,0],[r-R9,0],[0,r-R9]]}});var L9=B(Rt=>{h();Rt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bu={N1:3,N2:3,N3:40,N4:10};Rt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Rt.from=function(e){return Rt.isValid(e)?parseInt(e,10):void 0};Rt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,u=null;for(let a=0;a=5&&(n+=bu.N1+(i-5)),o=f,i=1),f=e.get(c,a),f===u?s++:(s>=5&&(n+=bu.N1+(s-5)),u=f,s=1)}i>=5&&(n+=bu.N1+(i-5)),s>=5&&(n+=bu.N1+(s-5))}return n};Rt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(u,o),u>=10&&(s===1488||s===93)&&n++}return n*bu.N3};Rt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{h();var ua=G1(),z1=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Q1=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];LC.getBlocksCount=function(e,r){switch(r){case ua.L:return z1[(e-1)*4+0];case ua.M:return z1[(e-1)*4+1];case ua.Q:return z1[(e-1)*4+2];case ua.H:return z1[(e-1)*4+3];default:return}};LC.getTotalCodewordsCount=function(e,r){switch(r){case ua.L:return Q1[(e-1)*4+0];case ua.M:return Q1[(e-1)*4+1];case ua.Q:return Q1[(e-1)*4+2];case ua.H:return Q1[(e-1)*4+3];default:return}}});var F9=B(W1=>{h();var Td=new Uint8Array(512),K1=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Td[r]=e,K1[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Td[r]=Td[r-255]})();W1.log=function(e){if(e<1)throw new Error("log("+e+")");return K1[e]};W1.exp=function(e){return Td[e]};W1.mul=function(e,r){return e===0||r===0?0:Td[K1[e]+K1[r]]}});var U9=B(_d=>{h();var UC=F9();_d.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{h();var q9=U9();function qC(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}qC.prototype.initialize=function(e){this.degree=e,this.genPoly=q9.generateECPolynomial(this.degree)};qC.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=q9.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};V9.exports=qC});var VC=B(H9=>{h();H9.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var kC=B(no=>{h();var G9="[0-9]+",bde="[A-Z $%*+\\-./:]+",Cd="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Cd=Cd.replace(/u/g,"\\u");var Sde="(?:(?![A-Z0-9 $%*+\\-./:]|"+Cd+`)(?:.|[\r +]))+`;no.KANJI=new RegExp(Cd,"g");no.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");no.BYTE=new RegExp(Sde,"g");no.NUMERIC=new RegExp(G9,"g");no.ALPHANUMERIC=new RegExp(bde,"g");var Ide=new RegExp("^"+Cd+"$"),Tde=new RegExp("^"+G9+"$"),_de=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");no.testKanji=function(e){return Ide.test(e)};no.testNumeric=function(e){return Tde.test(e)};no.testAlphanumeric=function(e){return _de.test(e)}});var ca=B(lr=>{h();var Cde=VC(),HC=kC();lr.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};lr.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};lr.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};lr.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};lr.MIXED={bit:-1};lr.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Cde.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};lr.getBestModeForData=function(e){return HC.testNumeric(e)?lr.NUMERIC:HC.testAlphanumeric(e)?lr.ALPHANUMERIC:HC.testKanji(e)?lr.KANJI:lr.BYTE};lr.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};lr.isValid=function(e){return e&&e.bit&&e.ccBits};function Nde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return lr.NUMERIC;case"alphanumeric":return lr.ALPHANUMERIC;case"kanji":return lr.KANJI;case"byte":return lr.BYTE;default:throw new Error("Unknown mode: "+t)}}lr.from=function(e,r){if(lr.isValid(e))return e;try{return Nde(e)}catch{return r}}});var W9=B(Su=>{h();var $1=aa(),xde=FC(),j9=G1(),la=ca(),GC=VC(),Q9=7973,z9=$1.getBCHDigit(Q9);function Ode(t,e,r){for(let n=1;n<=40;n++)if(e<=Su.getCapacity(n,r,t))return n}function K9(t,e){return la.getCharCountIndicator(t,e)+4}function Dde(t,e){let r=0;return t.forEach(function(n){let i=K9(n.mode,e);r+=i+n.getBitsLength()}),r}function Pde(t,e){for(let r=1;r<=40;r++)if(Dde(t,r)<=Su.getCapacity(r,e,la.MIXED))return r}Su.from=function(e,r){return GC.isValid(e)?parseInt(e,10):r};Su.getCapacity=function(e,r,n){if(!GC.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=la.BYTE);let i=$1.getSymbolTotalCodewords(e),s=xde.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===la.MIXED)return o;let u=o-K9(n,e);switch(n){case la.NUMERIC:return Math.floor(u/10*3);case la.ALPHANUMERIC:return Math.floor(u/11*2);case la.KANJI:return Math.floor(u/13);case la.BYTE:default:return Math.floor(u/8)}};Su.getBestVersionForData=function(e,r){let n,i=j9.from(r,j9.M);if(Array.isArray(e)){if(e.length>1)return Pde(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Ode(n.mode,n.getLength(),i)};Su.getEncodedBits=function(e){if(!GC.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;$1.getBCHDigit(r)-z9>=0;)r^=Q9<<$1.getBCHDigit(r)-z9;return e<<12|r}});var X9=B(J9=>{h();var jC=aa(),Y9=1335,Rde=21522,$9=jC.getBCHDigit(Y9);J9.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;jC.getBCHDigit(i)-$9>=0;)i^=Y9<{h();var Bde=ca();function Hl(t){this.mode=Bde.NUMERIC,this.data=t.toString()}Hl.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Hl.prototype.getLength=function(){return this.data.length};Hl.prototype.getBitsLength=function(){return Hl.getBitsLength(this.data.length)};Hl.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};Z9.exports=Hl});var rV=B((pCe,tV)=>{h();var Mde=ca(),zC=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Gl(t){this.mode=Mde.ALPHANUMERIC,this.data=t}Gl.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Gl.prototype.getLength=function(){return this.data.length};Gl.prototype.getBitsLength=function(){return Gl.getBitsLength(this.data.length)};Gl.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=zC.indexOf(this.data[r])*45;n+=zC.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(zC.indexOf(this.data[r]),6)};tV.exports=Gl});var iV=B((yCe,nV)=>{"use strict";h();nV.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var oV=B((vCe,sV)=>{h();var Lde=iV(),Fde=ca();function jl(t){this.mode=Fde.BYTE,typeof t=="string"&&(t=Lde(t)),this.data=new Uint8Array(t)}jl.getBitsLength=function(e){return e*8};jl.prototype.getLength=function(){return this.data.length};jl.prototype.getBitsLength=function(){return jl.getBitsLength(this.data.length)};jl.prototype.write=function(t){for(let e=0,r=this.data.length;e{h();var Ude=ca(),qde=aa();function zl(t){this.mode=Ude.KANJI,this.data=t}zl.getBitsLength=function(e){return e*13};zl.prototype.getLength=function(){return this.data.length};zl.prototype.getBitsLength=function(){return zl.getBitsLength(this.data.length)};zl.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` +Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};aV.exports=zl});var cV=B((SCe,QC)=>{"use strict";h();var Nd={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=Nd.PriorityQueue.make();s.push(e,0);for(var o,u,a,c,f,d,w,A,T;!s.empty();){o=s.pop(),u=o.value,c=o.cost,f=t[u]||{};for(a in f)f.hasOwnProperty(a)&&(d=f[a],w=c+d,A=i[a],T=typeof i[a]>"u",(T||A>w)&&(i[a]=w,s.push(a,w),n[a]=u))}if(typeof r<"u"&&typeof i[r]>"u"){var x=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(x)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=Nd.single_source_shortest_paths(t,e,r);return Nd.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Nd.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof QC<"u"&&(QC.exports=Nd)});var yV=B(Ql=>{h();var ze=ca(),hV=eV(),dV=rV(),gV=oV(),pV=uV(),xd=kC(),Y1=aa(),Vde=cV();function lV(t){return unescape(encodeURIComponent(t)).length}function Od(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function mV(t){let e=Od(xd.NUMERIC,ze.NUMERIC,t),r=Od(xd.ALPHANUMERIC,ze.ALPHANUMERIC,t),n,i;return Y1.isKanjiModeEnabled()?(n=Od(xd.BYTE,ze.BYTE,t),i=Od(xd.KANJI,ze.KANJI,t)):(n=Od(xd.BYTE_KANJI,ze.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,u){return o.index-u.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function KC(t,e){switch(e){case ze.NUMERIC:return hV.getBitsLength(t);case ze.ALPHANUMERIC:return dV.getBitsLength(t);case ze.KANJI:return pV.getBitsLength(t);case ze.BYTE:return gV.getBitsLength(t)}}function kde(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Hde(t){let e=[];for(let r=0;r{h();var X1=aa(),WC=G1(),jde=x9(),zde=D9(),Qde=P9(),Kde=M9(),JC=L9(),XC=FC(),Wde=k9(),J1=W9(),$de=X9(),Yde=ca(),$C=yV();function Jde(t,e){let r=t.size,n=Kde.getPositions(e);for(let i=0;i=0&&u<=6&&(a===0||a===6)||a>=0&&a<=6&&(u===0||u===6)||u>=2&&u<=4&&a>=2&&a<=4?t.set(s+u,o+a,!0,!0):t.set(s+u,o+a,!1,!0))}}function Xde(t){let e=t.size;for(let r=8;r>u&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function YC(t,e,r){let n=t.size,i=$de.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function tge(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let u=r-1;u>0;u-=2)for(u===6&&u--;;){for(let a=0;a<2;a++)if(!t.isReserved(i,u-a)){let c=!1;o>>s&1)===1),t.set(i,u-a,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function rge(t,e,r){let n=new jde;r.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),Yde.getCharCountIndicator(a.mode,t)),a.write(n)});let i=X1.getSymbolTotalCodewords(t),s=XC.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let u=(o-n.getLengthInBits())/8;for(let a=0;a=7&&ege(a,e),tge(a,o),isNaN(n)&&(n=JC.getBestMask(a,YC.bind(null,a,r))),JC.applyMask(n,a),YC(a,r,n),{modules:a,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}wV.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=WC.M,i,s;return typeof r<"u"&&(n=WC.from(r.errorCorrectionLevel,WC.M),i=J1.from(r.version),s=JC.from(r.maskPattern),r.toSJISFunc&&X1.setToSJISFunction(r.toSJISFunc)),ige(e,i,n,s)}});var ZC=B(Iu=>{h();function AV(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Iu.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:AV(e.color.dark||"#000000ff"),light:AV(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Iu.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Iu.getImageWidth=function(e,r){let n=Iu.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Iu.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Iu.getScale(i,n),u=Math.floor((i+n.margin*2)*o),a=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=a&&d>=a&&f{h();var e3=ZC();function sge(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function oge(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Z1.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=oge()),i=e3.getOptions(i);let o=e3.getImageWidth(e.modules.size,i),u=s.getContext("2d"),a=u.createImageData(o,o);return e3.qrToImageData(a.data,e,i),sge(u,s,o),u.putImageData(a,0,0),s};Z1.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Z1.render(e,r,i),o=i.type||"image/png",u=i.rendererOpts||{};return s.toDataURL(o,u.quality)}});var IV=B(SV=>{h();var age=ZC();function bV(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function t3(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function uge(t,e,r){let n="",i=0,s=!1,o=0;for(let u=0;u0&&a>0&&t[u-1]||(n+=s?t3("M",a+r,.5+c+r):t3("m",i,0),i=0,s=!1),a+1':"",c="',f='viewBox="0 0 '+u+" "+u+'"',w=''+a+c+` +`;return typeof n=="function"&&n(null,w),w}});var _V=B(Dd=>{h();var cge=_9(),r3=vV(),TV=EV(),lge=IV();function n3(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,u=typeof s[o-1]=="function";if(!u&&!cge())throw new Error("Callback required as last argument");if(u){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(a,c){try{let f=r3.create(r,n);a(t(f,e,n))}catch(f){c(f)}})}try{let a=r3.create(r,n);i(null,t(a,e,n))}catch(a){i(a)}}Dd.create=r3.create;Dd.toCanvas=n3.bind(null,TV.render);Dd.toDataURL=n3.bind(null,TV.renderToDataURL);Dd.toString=n3.bind(null,function(t,e,r){return lge.render(t,r)})});var FV=B(fa=>{"use strict";h();var Ege=fa&&fa.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LV=fa&&fa.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ege(e,t,r)};Object.defineProperty(fa,"__esModule",{value:!0});LV(Dl(),fa);LV(X2(),fa)});h();var d3=pe(Ca(),1),g3=pe(_b(),1),fw=pe(d0(),1),p3=pe(Db(),1),_ge=pe(Ve(),1),Cge=pe(Ic(),1),Nge=pe(Xr(),1),xge=pe(N0(),1),sk=pe(Bb(),1),Oge=pe(V0(),1),Dge=pe(H0(),1),ok=pe(po(),1),_s=pe(Mf(),1),ak=pe(yf(),1),uk=pe(Yu(),1),Pge=pe(CE(),1),Rge=pe(jb(),1);h();h();var U8=pe(Kb(),1);h();h();var G0="elvenjs_state",M8="https://devnet-api.multiversx.com";var Po="/dapp/init",j0="devnet",L8="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",F8=["wss://relay.walletconnect.com"],Rr={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var me={get(t){let e=localStorage.getItem(G0);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem(G0,JSON.stringify(r))},clear(){localStorage.removeItem(G0)}};var z0=async()=>{let t=U8.ExtensionProvider.getInstance();try{let e=await t.init(),r=me.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var c3=pe(Kb(),1),l3=pe(fd(),1),f3=pe(Dl(),1),ik=pe(SC(),1),lw=pe(H0(),1);h();var n9=pe(fd(),1);h();h();var ge=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};h();var r9=(U=>(U.onLoginStart="onLoginStart",U.onLoginSuccess="onLoginSuccess",U.onLoginFailure="onLoginFailure",U.onLogoutStart="onLogoutStart",U.onLogoutSuccess="onLogoutSuccess",U.onLogoutFailure="onLogoutFailure",U.onQrPending="onQrPending",U.onQrLoaded="onQrLoaded",U.onTxStart="onTxStart",U.onTxSent="onTxSent",U.onTxFinalized="onTxFinalized",U.onTxFailure="onTxFailure",U.onSignMsgStart="onSignMsgStart",U.onSignMsgFinalized="onSignMsgFinalized",U.onSignMsgFailure="onSignMsgFailure",U.onQueryStart="onQueryStart",U.onQueryFinalized="onQueryFinalized",U.onQueryFailure="onQueryFailure",U))(r9||{}),IC=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(IC||{}),dde=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(dde||{}),gde=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(gde||{});h();var Kt=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Fl=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");ge.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(me.clear(),ge.run("onLogoutSuccess")),e}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to logout the user: ${r}`),ge.run("onLogoutFailure",r)}};h();function R1(t){return t[Math.floor(Math.random()*t.length)]}var i9=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Fl(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=R1(t.initOptions.walletConnectV2RelayAddresses),n=new n9.WalletConnectV2Provider(e,Rr[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};h();var V1=pe(Ve(),1),p9=pe(s9(),1),m9=pe(a9(),1),y9=pe(PC(),1),w9=pe(d9(),1),v9=pe(jb(),1),A9=pe(g9(),1),E9=pe(Wf(),1);var k1=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||j0,this.apiUrl=e||Rr[this.chainType]?.apiAddress,this.apiTimeout=n||Rr[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),u=await o.json();if(!o.ok){let a=u?.error||o.status;return clearTimeout(i),Promise.reject(a)}return clearTimeout(i),u}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let u=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),a=await u.json();if(!u.ok){let c=a?.error||u.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),a}catch(u){this.handleApiError(u,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new V1.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new p9.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new V1.Address(r.sender),receiver:new V1.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:p.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:m9.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:y9.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:w9.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new E9.Query({address:e,func:r,args:n,value:i,caller:s}),u=new A9.ContractQueryRequest(o).toHttpRequest(),a=await this.apiPost("query",u);return v9.ContractQueryResponse.fromHttpResponse(a)}catch(o){this.handleApiError(o,"query")}}};h();h();var kl=()=>new Date().setHours(new Date().getHours()+24),H1=t=>Date.now()>t;h();var b9=pe(Ve(),1),S9=pe(Ic(),1);var Au=async t=>{let e=me.get("address"),r=me.get("expires");if(!(r&&H1(r))&&e&&t.networkProvider){let i=new b9.Address(e),s=new S9.Account(i);try{let o=await t.networkProvider.getAccount(i),u=await t.networkProvider.getGuardianData(i);me.set("address",e),me.set("activeGuardian",u.guarded&&u.activeGuardian?.address?u.activeGuardian.address:""),me.set("nonce",o.nonce.valueOf()),me.set("balance",o.balance.toString()),s.update(o)}catch(o){let u=Kt(o);console.warn(`Something went wrong trying to synchronize the user account: ${u}`)}}};var I9=async(t,e,r,n="/")=>{let i=await z0(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(a){let c=Kt(a);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:u}=i.account;if(me.set("loginToken",e),u&&me.set("signature",u),t.networkProvider&&u)try{let a=await i.getAddress();if(!a)throw new Error("Canceled!");me.set("address",a),me.set("loginMethod","browser-extension"),me.set("expires",kl()),await Au(t);let c=r.getToken(a,e,u);return me.set("accessToken",c),ge.run("onLoginSuccess"),i}catch(a){throw new Error(`Something went wrong trying to synchronize the user account: ${a?.message}`)}};h();h();var CV=pe(_V(),1),NV=pe(fd(),1);var fge=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},hge=t=>{let e=`${L8}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},dge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},gge=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},i3={},pge=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",i3[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:i3[t.topic].signal}),r},ew={},mge=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=pge(t,e);return n.appendChild(s),ew[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:ew[t.topic].signal}),n},yge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},wge=t=>{if(!t)return;document.getElementById(t)?.remove()},vge=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),Age=async t=>t?await CV.default.toString(t,{type:"svg"}):void 0,xV=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await Age(e),o;if(s&&(o=fge(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),vge()&&i.appendChild(hge(e))),i&&r instanceof NV.WalletConnectV2Provider){let u=r.pairings,a=async f=>{try{f&&(await r.logout({topic:f}),wge(f))}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to remove the existing pairing: ${w}`)}finally{ew[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(yge()),await r.login({approval:d,token:n})}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to login the user: ${w}`)}finally{for(let d of Object.values(ew))d?.abort();for(let d of Object.values(i3))d?.abort()}};if(u&&u.length>0){let f=dge();i.appendChild(f);let d=gge();f.appendChild(d);for(let w of u){let A=mge(w,a,c);f.appendChild(A)}}}return i};var tw=pe(fd(),1);var OV=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=R1(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof tw.WalletConnectV2Provider){let a=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();me.set("address",a),me.set("loginMethod","mobile"),me.set("expires",kl()),await Au(t),c&&me.set("signature",c),me.set("loginToken",e);let f=r.getToken(a,e,c);me.set("accessToken",f),ge.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof tw.WalletConnectV2Provider&&await Fl(t)},onClientEvent:a=>{console.log("wc2 session event: ",a)}},u=new tw.WalletConnectV2Provider(o,Rr[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(u){t.dappProvider=u,ge.run("onQrPending"),await u.init();let{uri:a,approval:c}=await u.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${a}&token=${e}`:a;return n&&f&&(s=await xV(n,f,u,e),ge.run("onQrLoaded")),await u.login({approval:c,token:e}),u}}catch(a){let c=Kt(a);console.warn(`Something went wrong trying to login the user: ${c}`),ge.run("onLoginFailure",c)}};h();var DV=pe(Dl(),1);var s3=async(t,e,r,n)=>{let i=new DV.WalletProvider(`${t}${Po}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return me.set("loginMethod",Rr[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),me.set("expires",kl()),me.set("loginToken",e),i}catch(u){let a=Kt(u);console.warn(`Something went wrong trying to login the user: ${a}`),me.set("loginMethod",""),ge.run("onLoginFailure",a)}};h();var ln=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};h();var PV=pe(Dl(),1);var RV=pe(SC(),1),o3=async(t,e)=>{let r=ln("signature"),n=ln("address"),i=me.get("address"),s=me.get("loginToken");if(r&&me.set("signature",r),n||i){n&&(me.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new PV.WalletProvider(`${t}${Po}`);if(r&&e&&n){let a=new RV.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);me.set("accessToken",a)}return o}};h();var BV=pe(Ic(),1),MV=pe(V0(),1);var rw=async(t,e)=>{ge.run("onTxSent",t);let n=await new MV.TransactionWatcher(e).awaitCompleted(t),i=n.sender,s=new BV.Account(i),o=await e.getAccount(i);s.update(o),me.set("address",s.address.bech32()),me.set("balance",s.balance.toString()),ge.run("onTxFinalized",n)};h();var Kl=pe(FV(),1),qV=pe(Xr(),1);h();var UV=pe(Ic(),1);var nw=t=>{let e=t.getSender(),r=new UV.Account(e),n=t.nonce.valueOf();r.incrementNonce(),me.set("nonce",(n+1n).toString())};var VV=async(t,e,r,n)=>{if(ln(Kl.WALLET_PROVIDER_CALLBACK_PARAM)===Kl.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=me.get("activeGuardian"),o=me.get("loginMethod"),u=ln("hasWebWalletGuardianSign"),a;if("getTransactionsFromWalletUrl"in t){if(a=t.getTransactionsFromWalletUrl()?.[0],!a)return;o==="web-wallet"&&(a.data=p.Buffer.from(a.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&u&&(a=new Kl.WalletProvider(`${r}${Po}`).getTransactionsFromWalletUrl()?.[0]);if(a){let c=qV.Transaction.fromPlainObject(a);c.nonce=BigInt(n),nw(c);try{ge.run("onTxStart",c),await e.sendTransaction(c),await rw(c,e)}catch(f){let w=`Getting transaction information failed! ${Kt(f)}`;throw ge.run("onTxFailure",c,w),new Error(w)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};h();var iw=pe($l(),1),kV=pe(Ve(),1),HV=pe(Dl(),1);var GV=t=>{let e=me.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(iw.TransactionVersion.withTxOptions()),t.setOptions(iw.TransactionOptions.withOptions(r)),t.setGuardian(kV.Address.fromBech32(e))}return t},jV=async(t,e)=>{let r=new HV.WalletProvider(`${e}${Po}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},zV=t=>{let e=me.get("activeGuardian");return!(!me.get("address")||!e||t.isGuardedTransaction())};h();var QV=()=>{let t=!ln("walletProviderStatus"),e=ln("status")==="signed",r=ln("message"),n=ln("signature");t&&e&&r&&n&&(ge.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};h();var u3=pe(Xr(),1);h();var KV=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(KV||{}),WV=(u=>(u.handshakeResponse="HANDSHAKE_RESPONSE",u.loginResponse="LOGIN_RESPONSE",u.disconnectResponse="DISCONNECT_RESPONSE",u.cancelResponse="CANCEL_RESPONSE",u.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",u.signMessageResponse="SIGN_MESSAGE_RESPONSE",u.noneResponse="NONE_RESPONSE",u))(WV||{}),a3={...WV,...KV},$V=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))($V||{}),YV=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(YV||{}),Tu={...YV,...$V};h();var JV=typeof window<"u"?window:{},XV=()=>JV.ReactNativeWebView?"reactNative":JV.webkit?"ios":"web",_u=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",sw=t=>Object.prototype.toString.call(t)==="[object String]";h();var ow={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,_u()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t}),_u())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t}),_u())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:Tu.logoutRequest}),_u())}};var aw=XV(),uw="message",ZV=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=_u()&&aw!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(uw,e),window&&window.addEventListener(uw,e)},ha=class{constructor(){}async logout(){return ow.logout[aw](),new Promise(e=>{e(!0)})}async signMessage(e){try{return ow.signMessage[aw](e),await new Promise((n,i)=>{window.signMessageResponse=(o,u)=>{if(u){i(u),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:u,type:a}=o;if(a===a3.signMessageResponse&&u!=null){let{signedMessage:c,error:f}=u;f?i(f):n(c)}document?.removeEventListener(uw,s)}ZV(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return ow.signTransactions[aw](r),await new Promise((i,s)=>{window.transactionsSigned=(u,a)=>{if(u=JSON.parse(u),a){s(a),window.transactionsSigned=null;return}i(u.map(c=>u3.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(u){let{message:a,type:c}=u;if(c===a3.signTransactionsResponse){let{transactions:f,error:d}=a;try{d?s(d):i(f.map(w=>u3.Transaction.fromPlainObject(w)))}catch{s("Unable to sign")}}document&&document.removeEventListener(uw,o)}ZV(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};h();h();h();function Sge(t){try{let e=atob(t),r=btoa(e),n=p.Buffer.from(t,"base64").toString(),i=p.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Wl(t){return Sge(t)?atob(t):t}h();var ek=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Wl(s)),u=Wl(r);return{ttl:Number(i),extraInfo:o,origin:u,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var tk=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Wl(r),o=Wl(n),u=ek(o);if(!u)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let a={...u,address:s,body:o,signature:i};return u.extraInfo?.timestamp||delete a.extraInfo,a}catch{return null}};function rk(t,e){let r=tk(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(me.set("loginToken",s),me.set("accessToken",t),me.set("signature",n),me.set("address",i),me.set("loginMethod","x-portal-hub"),e.dappProvider=new ha)}h();var nk=t=>{t.onLoginStart&&ge.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&ge.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&ge.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&ge.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&ge.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&ge.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&ge.set("onQrPending",t.onQrPending),t.onQrLoaded&&ge.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&ge.set("onTxStart",t.onTxStart),t.onTxSent&&ge.set("onTxSent",t.onTxSent),t.onTxFinalized&&ge.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&ge.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&ge.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&ge.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&ge.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&ge.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&ge.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&ge.set("onQueryFailure",t.onQueryFailure)};h();var cw=async t=>{ge.run("onLoginStart");try{await t(()=>{ge.run("onLoginSuccess")})}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to login the user: ${r}`),ge.run("onLoginFailure",r)}};var h3=class{static async init(e){let r=me.get();if(r.expires&&H1(r.expires)){me.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:j0,apiUrl:M8,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:F8,...e},this.networkProvider=new k1(this.initOptions),nk(this.initOptions);let n=ln("accessToken");n&&await cw(async s=>{rk(n,this),await Au(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&ln("address"))&&r?.loginMethod&&(await cw(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await z0()),r.loginMethod==="mobile"&&(this.dappProvider=await i9(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new ha),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Au(this),s()}),this.initOptions?.chainType&&(await VV(this.dappProvider,this.networkProvider,Rr[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),QV()))}static async login(e,r){if(!Object.values(IC).includes(e)){let i="Wrong login method!";throw ge.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw ge.run("onLoginFailure",i),new Error(i)}await cw(async()=>{let i=new ik.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await I9(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await OV(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Fl(this);return this.dappProvider=void 0,e}catch(e){let r=Kt(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw ge.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw ge.run("onTxFailure",e,n),new Error(n)}let r=GV(e);try{ge.run("onTxStart",e);let n=me.get();if(e.nonce=n.nonce,this.dappProvider instanceof c3.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof l3.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof ha&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof f3.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=zV(r);if(i||nw(r),i&&this.initOptions?.chainType){await jV(r,Rr[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await rw(r,this.networkProvider)}}catch(n){let i=Kt(n);throw ge.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(ge.run("onSignMsgStart",e),this.dappProvider instanceof c3.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof l3.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof ha&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof f3.WalletProvider){let s=u=>encodeURIComponent(u).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=me.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&ge.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Kt(i);throw ge.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{ge.run("onQueryStart",o);let u=await this.networkProvider.queryContract(o);return ge.run("onQueryFinalized",u),u}catch(u){let a=Kt(u);throw ge.run("onQueryFinalized",o,a),new Error(`Smart contract query failed! ${a}`)}}static{this.storage=me}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,ge.clear()}}};h();rr();Ou.config({ROUNDING_MODE:Ou.ROUND_FLOOR});var Ige=({amount:t,decimals:e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return BigInt(new Ou(t).shiftedBy(e).toFixed())},Tge=({amount:t,decimals:e,rounding:r=e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return new Ou(t).shiftedBy(-e).decimalPlaces(r).toFixed()};var export_Account=Cge.Account;var export_Address=_ge.Address;var export_AddressType=uk.AddressType;var export_AddressValue=uk.AddressValue;var export_BigUIntType=_s.BigUIntType;var export_BigUIntValue=_s.BigUIntValue;var export_BooleanType=ak.BooleanType;var export_BooleanValue=ak.BooleanValue;var export_BytesType=ok.BytesType;var export_BytesValue=ok.BytesValue;var export_ContractQueryResponse=Rge.ContractQueryResponse;var export_Message=sk.Message;var export_MessageComputer=sk.MessageComputer;var export_QueryArguments=Pge.QueryArguments;var export_SignableMessage=Dge.SignableMessage;var export_SmartContractTransactionsFactory=fw.SmartContractTransactionsFactory;var export_SmartContractTransactionsOutcomeParser=p3.SmartContractTransactionsOutcomeParser;var export_Token=d3.Token;var export_TokenComputer=d3.TokenComputer;var export_TokenManagementTransactionsFactory=fw.TokenManagementTransactionsFactory;var export_TokenManagementTransactionsOutcomeParser=p3.TokenManagementTransactionsOutcomeParser;var export_TokenOperationsFactory=g3.TokenOperationsFactory;var export_TokenOperationsFactoryConfig=g3.TokenOperationsFactoryConfig;var export_TokenOperationsOutcomeParser=g3.TokenOperationsOutcomeParser;var export_TokenTransfer=d3.TokenTransfer;var export_Transaction=Nge.Transaction;var export_TransactionComputer=xge.TransactionComputer;var export_TransactionEventsParser=p3.TransactionEventsParser;var export_TransactionWatcher=Oge.TransactionWatcher;var export_TransactionsFactoryConfig=fw.TransactionsFactoryConfig;var export_TransferTransactionsFactory=fw.TransferTransactionsFactory;var export_U16Type=_s.U16Type;var export_U16Value=_s.U16Value;var export_U32Type=_s.U32Type;var export_U32Value=_s.U32Value;var export_U64Type=_s.U64Type;var export_U64Value=_s.U64Value;var export_U8Type=_s.U8Type;var export_U8Value=_s.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractQueryResponse as ContractQueryResponse,dde as DappCoreWCV2CustomMethodsEnum,h3 as ElvenJS,r9 as EventStoreEvents,IC as LoginMethodsEnum,export_Message as Message,export_MessageComputer as MessageComputer,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContractTransactionsFactory as SmartContractTransactionsFactory,export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser,export_Token as Token,export_TokenComputer as TokenComputer,export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory,export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser,export_TokenOperationsFactory as TokenOperationsFactory,export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig,export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionComputer as TransactionComputer,export_TransactionEventsParser as TransactionEventsParser,export_TransactionWatcher as TransactionWatcher,export_TransactionsFactoryConfig as TransactionsFactoryConfig,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,gde as WebWalletUrlParamsEnum,Tge as formatAmount,Ige as parseAmount}; +/*! Bundled license information: ieee754/index.js: (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) @@ -54994,14 +72,6 @@ buffer/index.js: * @license MIT *) -buffer/index.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) - safe-buffer/index.js: (*! safe-buffer. MIT License. Feross Aboukhadijeh *) diff --git a/esbuild.config.cjs b/esbuild.config.cjs index b3f3a77..eb8334e 100644 --- a/esbuild.config.cjs +++ b/esbuild.config.cjs @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-var-requires */ const esbuild = require('esbuild'); +const path = require('path'); const fs = require('fs'); @@ -10,9 +11,32 @@ esbuild entryPoints: ['./src/elven.ts'], bundle: true, metafile: true, - minify: false, + minify: true, outdir: 'build', platform: 'browser', + plugins: [ + { + name: 'alias', + setup(build) { + build.onResolve({ filter: /^bignumber\.js$/ }, () => { + return { + path: path.resolve( + __dirname, + 'node_modules/bignumber.js/bignumber.mjs' + ), + }; + }); + build.onResolve({ filter: /^buffer$/ }, () => { + return { + path: path.resolve( + __dirname, + 'node_modules/node-stdlib-browser/node_modules/buffer/index.js' + ), + }; + }); + }, + }, + ], }) .then((result) => { fs.writeFileSync('./build/meta.json', JSON.stringify(result.metafile)); diff --git a/example/elven.js b/example/elven.js index aab57b0..ec95d64 100644 --- a/example/elven.js +++ b/example/elven.js @@ -1,54987 +1,65 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, { - get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] -}) : x3)(function(x3) { - if (typeof require !== "undefined") - return require.apply(this, arguments); - throw Error('Dynamic require of "' + x3 + '" is not supported'); -}); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod2) => function __require2() { - return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; -}; -var __export = (target, all) => { - for (var name2 in all) - __defProp(target, name2, { get: all[name2], enumerable: true }); -}; -var __copyProps = (to, from3, except, desc) => { - if (from3 && typeof from3 === "object" || typeof from3 === "function") { - for (let key of __getOwnPropNames(from3)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default")); -var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, - mod2 -)); -var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); - -// node_modules/base64-js/index.js -var require_base64_js = __commonJS({ - "node_modules/base64-js/index.js"(exports2) { - "use strict"; - init_shim(); - exports2.byteLength = byteLength; - exports2.toByteArray = toByteArray; - exports2.fromByteArray = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i2 = 0, len = code2.length; i2 < len; ++i2) { - lookup[i2] = code2[i2]; - revLookup[code2.charCodeAt(i2)] = i2; - } - var i2; - var len; - revLookup["-".charCodeAt(0)] = 62; - revLookup["_".charCodeAt(0)] = 63; - function getLens(b64) { - var len2 = b64.length; - if (len2 % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) - validLen = len2; - var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } - function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i3; - for (i3 = 0; i3 < len2; i3 += 4) { - tmp = revLookup[b64.charCodeAt(i3)] << 18 | revLookup[b64.charCodeAt(i3 + 1)] << 12 | revLookup[b64.charCodeAt(i3 + 2)] << 6 | revLookup[b64.charCodeAt(i3 + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i3)] << 2 | revLookup[b64.charCodeAt(i3 + 1)] >> 4; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i3)] << 10 | revLookup[b64.charCodeAt(i3 + 1)] << 4 | revLookup[b64.charCodeAt(i3 + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - return arr; - } - function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; - } - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i3 = start; i3 < end; i3 += 3) { - tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255); - output.push(tripletToBase64(tmp)); - } - return output.join(""); - } - function fromByteArray(uint8) { - var tmp; - var len2 = uint8.length; - var extraBytes = len2 % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) { - parts.push(encodeChunk(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength)); - } - if (extraBytes === 1) { - tmp = uint8[len2 - 1]; - parts.push( - lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" - ); - } else if (extraBytes === 2) { - tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; - parts.push( - lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" - ); - } - return parts.join(""); - } - } -}); - -// node_modules/ieee754/index.js -var require_ieee754 = __commonJS({ - "node_modules/ieee754/index.js"(exports2) { - init_shim(); - exports2.read = function(buffer, offset, isLE, mLen, nBytes) { - var e2, m3; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i2 = isLE ? nBytes - 1 : 0; - var d3 = isLE ? -1 : 1; - var s2 = buffer[offset + i2]; - i2 += d3; - e2 = s2 & (1 << -nBits) - 1; - s2 >>= -nBits; - nBits += eLen; - for (; nBits > 0; e2 = e2 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { - } - m3 = e2 & (1 << -nBits) - 1; - e2 >>= -nBits; - nBits += mLen; - for (; nBits > 0; m3 = m3 * 256 + buffer[offset + i2], i2 += d3, nBits -= 8) { - } - if (e2 === 0) { - e2 = 1 - eBias; - } else if (e2 === eMax) { - return m3 ? NaN : (s2 ? -1 : 1) * Infinity; - } else { - m3 = m3 + Math.pow(2, mLen); - e2 = e2 - eBias; - } - return (s2 ? -1 : 1) * m3 * Math.pow(2, e2 - mLen); - }; - exports2.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e2, m3, c4; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i2 = isLE ? 0 : nBytes - 1; - var d3 = isLE ? 1 : -1; - var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m3 = isNaN(value) ? 1 : 0; - e2 = eMax; - } else { - e2 = Math.floor(Math.log(value) / Math.LN2); - if (value * (c4 = Math.pow(2, -e2)) < 1) { - e2--; - c4 *= 2; - } - if (e2 + eBias >= 1) { - value += rt / c4; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c4 >= 2) { - e2++; - c4 /= 2; - } - if (e2 + eBias >= eMax) { - m3 = 0; - e2 = eMax; - } else if (e2 + eBias >= 1) { - m3 = (value * c4 - 1) * Math.pow(2, mLen); - e2 = e2 + eBias; - } else { - m3 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e2 = 0; - } - } - for (; mLen >= 8; buffer[offset + i2] = m3 & 255, i2 += d3, m3 /= 256, mLen -= 8) { - } - e2 = e2 << mLen | m3; - eLen += mLen; - for (; eLen > 0; buffer[offset + i2] = e2 & 255, i2 += d3, e2 /= 256, eLen -= 8) { - } - buffer[offset + i2 - d3] |= s2 * 128; - }; - } -}); - -// node_modules/node-stdlib-browser/node_modules/buffer/index.js -var require_buffer = __commonJS({ - "node_modules/node-stdlib-browser/node_modules/buffer/index.js"(exports2) { - "use strict"; - init_shim(); - var base642 = require_base64_js(); - var ieee754 = require_ieee754(); - var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports2.Buffer = Buffer2; - exports2.SlowBuffer = SlowBuffer; - exports2.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 2147483647; - exports2.kMaxLength = K_MAX_LENGTH; - Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { - try { - var arr = new Uint8Array(1); - var proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e2) { - return false; - } - } - Object.defineProperty(Buffer2.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer2.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.byteOffset; - } - }); - function createBuffer(length2) { - if (length2 > K_MAX_LENGTH) { - throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); - } - var buf = new Uint8Array(length2); - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function Buffer2(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe2(arg); - } - return from3(arg, encodingOrOffset, length2); - } - Buffer2.poolSize = 8192; - function from3(value, encodingOrOffset, length2) { - if (typeof value === "string") { - return fromString3(value, encodingOrOffset); - } - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof value === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - var valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer2.from(valueOf, encodingOrOffset, length2); - } - var b4 = fromObject(value); - if (b4) - return b4; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer2.from( - value[Symbol.toPrimitive]("string"), - encodingOrOffset, - length2 - ); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - Buffer2.from = function(value, encodingOrOffset, length2) { - return from3(value, encodingOrOffset, length2); - }; - Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer2, Uint8Array); - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } - } - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); - } - Buffer2.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; - function allocUnsafe2(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - Buffer2.allocUnsafe = function(size) { - return allocUnsafe2(size); - }; - Buffer2.allocUnsafeSlow = function(size) { - return allocUnsafe2(size); - }; - function fromString3(string2, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - var length2 = byteLength(string2, encoding) | 0; - var buf = createBuffer(length2); - var actual = buf.write(string2, encoding); - if (actual !== length2) { - buf = buf.slice(0, actual); - } - return buf; - } - function fromArrayLike(array) { - var length2 = array.length < 0 ? 0 : checked(array.length) | 0; - var buf = createBuffer(length2); - for (var i2 = 0; i2 < length2; i2 += 1) { - buf[i2] = array[i2] & 255; - } - return buf; - } - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - return fromArrayLike(arrayView); - } - function fromArrayBuffer(array, byteOffset, length2) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length2 || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - var buf; - if (byteOffset === void 0 && length2 === void 0) { - buf = new Uint8Array(array); - } else if (length2 === void 0) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length2); - } - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function fromObject(obj) { - if (Buffer2.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - function checked(length2) { - if (length2 >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length2 | 0; - } - function SlowBuffer(length2) { - if (+length2 != length2) { - length2 = 0; - } - return Buffer2.alloc(+length2); - } - Buffer2.isBuffer = function isBuffer(b4) { - return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; - }; - Buffer2.compare = function compare3(a3, b4) { - if (isInstance(a3, Uint8Array)) - a3 = Buffer2.from(a3, a3.offset, a3.byteLength); - if (isInstance(b4, Uint8Array)) - b4 = Buffer2.from(b4, b4.offset, b4.byteLength); - if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a3 === b4) - return 0; - var x3 = a3.length; - var y4 = b4.length; - for (var i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { - if (a3[i2] !== b4[i2]) { - x3 = a3[i2]; - y4 = b4[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - Buffer2.isEncoding = function isEncoding(encoding) { - switch (String(encoding).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 true; - default: - return false; - } - }; - Buffer2.concat = function concat2(list, length2) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer2.alloc(0); - } - var i2; - if (length2 === void 0) { - length2 = 0; - for (i2 = 0; i2 < list.length; ++i2) { - length2 += list[i2].length; - } - } - var buffer = Buffer2.allocUnsafe(length2); - var pos = 0; - for (i2 = 0; i2 < list.length; ++i2) { - var buf = list[i2]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer2.from(buf).copy(buffer, pos); - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ); - } - } else if (!Buffer2.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - pos += buf.length; - } - return buffer; - }; - function byteLength(string2, encoding) { - if (Buffer2.isBuffer(string2)) { - return string2.length; - } - if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { - return string2.byteLength; - } - if (typeof string2 !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 - ); - } - var len = string2.length; - var mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) - return 0; - var loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes(string2).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string2).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string2).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.byteLength = byteLength; - function slowToString(encoding, start, end) { - var loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) - encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.prototype._isBuffer = true; - function swap(b4, n3, m3) { - var i2 = b4[n3]; - b4[n3] = b4[m3]; - b4[m3] = i2; - } - Buffer2.prototype.swap16 = function swap16() { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (var i2 = 0; i2 < len; i2 += 2) { - swap(this, i2, i2 + 1); - } - return this; - }; - Buffer2.prototype.swap32 = function swap32() { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (var i2 = 0; i2 < len; i2 += 4) { - swap(this, i2, i2 + 3); - swap(this, i2 + 1, i2 + 2); - } - return this; - }; - Buffer2.prototype.swap64 = function swap64() { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (var i2 = 0; i2 < len; i2 += 8) { - swap(this, i2, i2 + 7); - swap(this, i2 + 1, i2 + 6); - swap(this, i2 + 2, i2 + 5); - swap(this, i2 + 3, i2 + 4); - } - return this; - }; - Buffer2.prototype.toString = function toString3() { - var length2 = this.length; - if (length2 === 0) - return ""; - if (arguments.length === 0) - return utf8Slice(this, 0, length2); - return slowToString.apply(this, arguments); - }; - Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; - Buffer2.prototype.equals = function equals4(b4) { - if (!Buffer2.isBuffer(b4)) - throw new TypeError("Argument must be a Buffer"); - if (this === b4) - return true; - return Buffer2.compare(this, b4) === 0; - }; - Buffer2.prototype.inspect = function inspect() { - var str = ""; - var max = exports2.INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) - str += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; - } - Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer2.from(target, target.offset, target.byteLength); - } - if (!Buffer2.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) - return 0; - var x3 = thisEnd - thisStart; - var y4 = end - start; - var len = Math.min(x3, y4); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - for (var i2 = 0; i2 < len; ++i2) { - if (thisCopy[i2] !== targetCopy[i2]) { - x3 = thisCopy[i2]; - y4 = targetCopy[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - if (buffer.length === 0) - return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length - 1; - } - if (byteOffset < 0) - byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) - return -1; - else - byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) - byteOffset = 0; - else - return -1; - } - if (typeof val === "string") { - val = Buffer2.from(val, encoding); - } - if (Buffer2.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); - } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read2(buf, i3) { - if (indexSize === 1) { - return buf[i3]; - } else { - return buf.readUInt16BE(i3 * indexSize); - } - } - var i2; - if (dir) { - var foundIndex = -1; - for (i2 = byteOffset; i2 < arrLength; i2++) { - if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { - if (foundIndex === -1) - foundIndex = i2; - if (i2 - foundIndex + 1 === valLength) - return foundIndex * indexSize; - } else { - if (foundIndex !== -1) - i2 -= i2 - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) - byteOffset = arrLength - valLength; - for (i2 = byteOffset; i2 >= 0; i2--) { - var found = true; - for (var j2 = 0; j2 < valLength; j2++) { - if (read2(arr, i2 + j2) !== read2(val, j2)) { - found = false; - break; - } - } - if (found) - return i2; - } - } - return -1; - } - Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string2, offset, length2) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length2) { - length2 = remaining; - } else { - length2 = Number(length2); - if (length2 > remaining) { - length2 = remaining; - } - } - var strLen = string2.length; - if (length2 > strLen / 2) { - length2 = strLen / 2; - } - for (var i2 = 0; i2 < length2; ++i2) { - var parsed = parseInt(string2.substr(i2 * 2, 2), 16); - if (numberIsNaN(parsed)) - return i2; - buf[offset + i2] = parsed; - } - return i2; - } - function utf8Write(buf, string2, offset, length2) { - return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); - } - function asciiWrite(buf, string2, offset, length2) { - return blitBuffer(asciiToBytes(string2), buf, offset, length2); - } - function base64Write(buf, string2, offset, length2) { - return blitBuffer(base64ToBytes(string2), buf, offset, length2); - } - function ucs2Write(buf, string2, offset, length2) { - return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); - } - Buffer2.prototype.write = function write(string2, offset, length2, encoding) { - if (offset === void 0) { - encoding = "utf8"; - length2 = this.length; - offset = 0; - } else if (length2 === void 0 && typeof offset === "string") { - encoding = offset; - length2 = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length2)) { - length2 = length2 >>> 0; - if (encoding === void 0) - encoding = "utf8"; - } else { - encoding = length2; - length2 = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - var remaining = this.length - offset; - if (length2 === void 0 || length2 > remaining) - length2 = remaining; - if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) - encoding = "utf8"; - var loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string2, offset, length2); - case "utf8": - case "utf-8": - return utf8Write(this, string2, offset, length2); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string2, offset, length2); - case "base64": - return base64Write(this, string2, offset, length2); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string2, offset, length2); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - Buffer2.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base642.fromByteArray(buf); - } else { - return base642.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i2 = start; - while (i2 < end) { - var firstByte = buf[i2]; - var codePoint = null; - var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i2 + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i2 + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - fourthByte = buf[i2 + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i2 += bytesPerSequence; - } - return decodeCodePointsArray(res); - } - var MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - var res = ""; - var i2 = 0; - while (i2 < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) - ); - } - return res; - } - function asciiSlice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); - for (var i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2] & 127); - } - return ret; - } - function latin1Slice(buf, start, end) { - var ret = ""; - end = Math.min(buf.length, end); - for (var i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2]); - } - return ret; - } - function hexSlice(buf, start, end) { - var len = buf.length; - if (!start || start < 0) - start = 0; - if (!end || end < 0 || end > len) - end = len; - var out = ""; - for (var i2 = start; i2 < end; ++i2) { - out += hexSliceLookupTable[buf[i2]]; - } - return out; - } - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ""; - for (var i2 = 0; i2 < bytes.length - 1; i2 += 2) { - res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); - } - return res; - } - Buffer2.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) - start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) - end = 0; - } else if (end > len) { - end = len; - } - if (end < start) - end = start; - var newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer2.prototype); - return newBuf; - }; - function checkOffset(offset, ext, length2) { - if (offset % 1 !== 0 || offset < 0) - throw new RangeError("offset is not uint"); - if (offset + ext > length2) - throw new RangeError("Trying to access beyond buffer length"); - } - Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - var val = this[offset]; - var mul = 1; - var i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - return val; - }; - Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength2, this.length); - } - var val = this[offset + --byteLength2]; - var mul = 1; - while (byteLength2 > 0 && (mul *= 256)) { - val += this[offset + --byteLength2] * mul; - } - return val; - }; - Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - return this[offset]; - }; - Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; - }; - Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - var val = this[offset]; - var mul = 1; - var i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - var i2 = byteLength2; - var mul = 1; - var val = this[offset + --i2]; - while (i2 > 0 && (mul *= 256)) { - val += this[offset + --i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) - return this[offset]; - return (255 - this[offset] + 1) * -1; - }; - Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - var val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - var val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); - }; - Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); - }; - Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); - }; - Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); - }; - function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer2.isBuffer(buf)) - throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) - throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - } - Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - var mul = 1; - var i2 = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - var i2 = byteLength2 - 1; - var mul = 1; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 255, 0); - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - var i2 = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - var i2 = byteLength2 - 1; - var mul = 1; - var sub = 0; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 127, -128); - if (value < 0) - value = 255 + value + 1; - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; - }; - Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - if (value < 0) - value = 4294967295 + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - if (offset < 0) - throw new RangeError("Index out of range"); - } - function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); - }; - function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; - Buffer2.prototype.copy = function copy(target, targetStart, start, end) { - if (!Buffer2.isBuffer(target)) - throw new TypeError("argument should be a Buffer"); - if (!start) - start = 0; - if (!end && end !== 0) - end = this.length; - if (targetStart >= target.length) - targetStart = target.length; - if (!targetStart) - targetStart = 0; - if (end > 0 && end < start) - end = start; - if (end === start) - return 0; - if (target.length === 0 || this.length === 0) - return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) - throw new RangeError("Index out of range"); - if (end < 0) - throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) - end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - var len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); - } - return len; - }; - Buffer2.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - var code2 = val.charCodeAt(0); - if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { - val = code2; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) - val = 0; - var i2; - if (typeof val === "number") { - for (i2 = start; i2 < end; ++i2) { - this[i2] = val; - } - } else { - var bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); - var len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i2 = 0; i2 < end - start; ++i2) { - this[i2 + start] = bytes[i2 % len]; - } - } - return this; - }; - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) - return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } - function utf8ToBytes(string2, units) { - units = units || Infinity; - var codePoint; - var length2 = string2.length; - var leadSurrogate = null; - var bytes = []; - for (var i2 = 0; i2 < length2; ++i2) { - codePoint = string2.charCodeAt(i2); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } else if (i2 + 1 === length2) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) - break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) - break; - bytes.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) - break; - bytes.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) - break; - bytes.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; - } - function asciiToBytes(str) { - var byteArray = []; - for (var i2 = 0; i2 < str.length; ++i2) { - byteArray.push(str.charCodeAt(i2) & 255); - } - return byteArray; - } - function utf16leToBytes(str, units) { - var c4, hi, lo; - var byteArray = []; - for (var i2 = 0; i2 < str.length; ++i2) { - if ((units -= 2) < 0) - break; - c4 = str.charCodeAt(i2); - hi = c4 >> 8; - lo = c4 % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; - } - function base64ToBytes(str) { - return base642.toByteArray(base64clean(str)); - } - function blitBuffer(src2, dst, offset, length2) { - for (var i2 = 0; i2 < length2; ++i2) { - if (i2 + offset >= dst.length || i2 >= src2.length) - break; - dst[i2 + offset] = src2[i2]; - } - return i2; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - var hexSliceLookupTable = function() { - var alphabet2 = "0123456789abcdef"; - var table = new Array(256); - for (var i2 = 0; i2 < 16; ++i2) { - var i16 = i2 * 16; - for (var j2 = 0; j2 < 16; ++j2) { - table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; - } - } - return table; - }(); - } -}); - -// node_modules/process/browser.js -var require_browser = __commonJS({ - "node_modules/process/browser.js"(exports2, module2) { - init_shim(); - var process2 = module2.exports = {}; - var cachedSetTimeout; - var cachedClearTimeout; - function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); - } - function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); - } - (function() { - try { - if (typeof setTimeout === "function") { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e2) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === "function") { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e2) { - cachedClearTimeout = defaultClearTimeout; - } - })(); - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - return setTimeout(fun, 0); - } - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - return cachedSetTimeout(fun, 0); - } catch (e2) { - try { - return cachedSetTimeout.call(null, fun, 0); - } catch (e3) { - return cachedSetTimeout.call(this, fun, 0); - } - } - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - return clearTimeout(marker); - } - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - return cachedClearTimeout(marker); - } catch (e2) { - try { - return cachedClearTimeout.call(null, marker); - } catch (e3) { - return cachedClearTimeout.call(this, marker); - } - } - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - process2.nextTick = function(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i2 = 1; i2 < arguments.length; i2++) { - args[i2 - 1] = arguments[i2]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function() { - this.fun.apply(null, this.array); - }; - process2.title = "browser"; - process2.browser = true; - process2.env = {}; - process2.argv = []; - process2.version = ""; - process2.versions = {}; - function noop() { - } - process2.on = noop; - process2.addListener = noop; - process2.once = noop; - process2.off = noop; - process2.removeListener = noop; - process2.removeAllListeners = noop; - process2.emit = noop; - process2.prependListener = noop; - process2.prependOnceListener = noop; - process2.listeners = function(name2) { - return []; - }; - process2.binding = function(name2) { - throw new Error("process.binding is not supported"); - }; - process2.cwd = function() { - return "/"; - }; - process2.chdir = function(dir) { - throw new Error("process.chdir is not supported"); - }; - process2.umask = function() { - return 0; - }; - } -}); - -// node_modules/node-stdlib-browser/helpers/esbuild/shim.js -var import_buffer, import_process, _globalThis, global; -var init_shim = __esm({ - "node_modules/node-stdlib-browser/helpers/esbuild/shim.js"() { - import_buffer = __toESM(require_buffer()); - import_process = __toESM(require_browser()); - _globalThis = function(Object2) { - function get2() { - var _global2 = this || self; - delete Object2.prototype.__magic__; - return _global2; - } - if (typeof globalThis === "object") { - return globalThis; - } - if (this) { - return get2(); - } else { - Object2.defineProperty(Object2.prototype, "__magic__", { - configurable: true, - get: get2 - }); - var _global = __magic__; - return _global; - } - }(Object); - global = _globalThis; - } -}); - -// node_modules/bignumber.js/bignumber.js -var require_bignumber = __commonJS({ - "node_modules/bignumber.js/bignumber.js"(exports2, module2) { - init_shim(); - (function(globalObject) { - "use strict"; - var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; - function clone2(configObject) { - var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber3(v2, b4) { - var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; - if (!(x3 instanceof BigNumber3)) - return new BigNumber3(v2, b4); - if (b4 == null) { - if (v2 && v2._isBigNumber === true) { - x3.s = v2.s; - if (!v2.c || v2.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (v2.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = v2.e; - x3.c = v2.c.slice(); - } - return; - } - if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { - x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; - if (v2 === ~~v2) { - for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x3.c = x3.e = null; - } else { - x3.e = e2; - x3.c = [v2]; - } - return; - } - str = String(v2); - } else { - if (!isNumeric2.test(str = String(v2))) - return parseNumeric(x3, str, isNum); - x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i2 = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i2; - e2 += +str.slice(i2 + 1); - str = str.substring(0, i2); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - if (b4 == 10 && alphabetHasNormalDecimalDigits) { - x3 = new BigNumber3(v2); - return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); - } - str = String(v2); - if (isNum = typeof v2 == "number") { - if (v2 * 0 != 0) - return parseNumeric(x3, str, isNum, b4); - x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits2 + v2); - } - } else { - x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b4); - e2 = i2 = 0; - for (len = str.length; i2 < len; i2++) { - if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { - if (c4 == ".") { - if (i2 > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i2 = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x3, String(v2), isNum, b4); - } - } - isNum = false; - str = convertBase(str, b4, 10, x3.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i2 = 0; str.charCodeAt(i2) === 48; i2++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i2, ++len)) { - len -= i2; - if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { - throw Error(tooManyDigits2 + x3.s * v2); - } - if ((e2 = e2 - i2 - 1) > MAX_EXP) { - x3.c = x3.e = null; - } else if (e2 < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = e2; - x3.c = []; - i2 = (e2 + 1) % LOG_BASE2; - if (e2 < 0) - i2 += LOG_BASE2; - if (i2 < len) { - if (i2) - x3.c.push(+str.slice(0, i2)); - for (len -= LOG_BASE2; i2 < len; ) { - x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); - } - i2 = LOG_BASE2 - (str = str.slice(i2)).length; - } else { - i2 -= len; - } - for (; i2--; str += "0") - ; - x3.c.push(+str); - } - } else { - x3.c = [x3.e = 0]; - } - } - BigNumber3.clone = clone2; - BigNumber3.ROUND_UP = 0; - BigNumber3.ROUND_DOWN = 1; - BigNumber3.ROUND_CEIL = 2; - BigNumber3.ROUND_FLOOR = 3; - BigNumber3.ROUND_HALF_UP = 4; - BigNumber3.ROUND_HALF_DOWN = 5; - BigNumber3.ROUND_HALF_EVEN = 6; - BigNumber3.ROUND_HALF_CEIL = 7; - BigNumber3.ROUND_HALF_FLOOR = 8; - BigNumber3.EUCLID = 9; - BigNumber3.config = BigNumber3.set = function(obj) { - var p3, v2; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - DECIMAL_PLACES = v2; - } - if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 8, p3); - ROUNDING_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, 0, p3); - intCheck2(v2[1], 0, MAX2, p3); - TO_EXP_NEG = v2[0]; - TO_EXP_POS = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); - } - } - if (obj.hasOwnProperty(p3 = "RANGE")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, -1, p3); - intCheck2(v2[1], 1, MAX2, p3); - MIN_EXP = v2[0]; - MAX_EXP = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - if (v2) { - MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); - } else { - throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); - } - } - } - if (obj.hasOwnProperty(p3 = "CRYPTO")) { - v2 = obj[p3]; - if (v2 === !!v2) { - if (v2) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v2; - } else { - CRYPTO = !v2; - throw Error(bignumberError2 + "crypto unavailable"); - } - } else { - CRYPTO = v2; - } - } else { - throw Error(bignumberError2 + p3 + " not true or false: " + v2); - } - } - if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 9, p3); - MODULO_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - POW_PRECISION = v2; - } - if (obj.hasOwnProperty(p3 = "FORMAT")) { - v2 = obj[p3]; - if (typeof v2 == "object") - FORMAT = v2; - else - throw Error(bignumberError2 + p3 + " not an object: " + v2); - } - if (obj.hasOwnProperty(p3 = "ALPHABET")) { - v2 = obj[p3]; - if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { - alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; - ALPHABET = v2; - } else { - throw Error(bignumberError2 + p3 + " invalid: " + v2); - } - } - } else { - throw Error(bignumberError2 + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber3.isBigNumber = function(v2) { - if (!v2 || v2._isBigNumber !== true) - return false; - if (!BigNumber3.DEBUG) - return true; - var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; - out: - if ({}.toString.call(c4) == "[object Array]") { - if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { - if (c4[0] === 0) { - if (e2 === 0 && c4.length === 1) - return true; - break out; - } - i2 = (e2 + 1) % LOG_BASE2; - if (i2 < 1) - i2 += LOG_BASE2; - if (String(c4[0]).length == i2) { - for (i2 = 0; i2 < c4.length; i2++) { - n3 = c4[i2]; - if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) - break out; - } - if (n3 !== 0) - return true; - } - } - } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { - return true; - } - throw Error(bignumberError2 + "Invalid BigNumber: " + v2); - }; - BigNumber3.maximum = BigNumber3.max = function() { - return maxOrMin(arguments, -1); - }; - BigNumber3.minimum = BigNumber3.min = function() { - return maxOrMin(arguments, 1); - }; - BigNumber3.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor2(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck2(dp, 0, MAX2); - k4 = mathceil2(dp / LOG_BASE2); - if (CRYPTO) { - if (crypto.getRandomValues) { - a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); - for (; i2 < k4; ) { - v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); - if (v2 >= 9e15) { - b4 = crypto.getRandomValues(new Uint32Array(2)); - a3[i2] = b4[0]; - a3[i2 + 1] = b4[1]; - } else { - c4.push(v2 % 1e14); - i2 += 2; - } - } - i2 = k4 / 2; - } else if (crypto.randomBytes) { - a3 = crypto.randomBytes(k4 *= 7); - for (; i2 < k4; ) { - v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; - if (v2 >= 9e15) { - crypto.randomBytes(7).copy(a3, i2); - } else { - c4.push(v2 % 1e14); - i2 += 7; - } - } - i2 = k4 / 7; - } else { - CRYPTO = false; - throw Error(bignumberError2 + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (; i2 < k4; ) { - v2 = random53bitInt(); - if (v2 < 9e15) - c4[i2++] = v2 % 1e14; - } - } - k4 = c4[--i2]; - dp %= LOG_BASE2; - if (k4 && dp) { - v2 = POWS_TEN2[LOG_BASE2 - dp]; - c4[i2] = mathfloor2(k4 / v2) * v2; - } - for (; c4[i2] === 0; c4.pop(), i2--) - ; - if (i2 < 0) { - c4 = [e2 = 0]; - } else { - for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) - ; - for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) - ; - if (i2 < LOG_BASE2) - e2 -= LOG_BASE2 - i2; - } - rand.e = e2; - rand.c = c4; - return rand; - }; - }(); - BigNumber3.sum = function() { - var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); - for (; i2 < args.length; ) - sum = sum.plus(args[i2++]); - return sum; - }; - convertBase = /* @__PURE__ */ function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j2, arr = [0], arrL, i2 = 0, len = str.length; - for (; i2 < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i2++)); - for (j2 = 0; j2 < arr.length; j2++) { - if (arr[j2] > baseOut - 1) { - if (arr[j2 + 1] == null) - arr[j2 + 1] = 0; - arr[j2 + 1] += arr[j2] / baseOut | 0; - arr[j2] %= baseOut; - } - } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign2, callerIsToString) { - var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i2 >= 0) { - k4 = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y4 = new BigNumber3(baseIn); - x3 = y4.pow(str.length - i2); - POW_PRECISION = k4; - y4.c = toBaseOut( - toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), - 10, - baseOut, - decimal - ); - y4.e = y4.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k4 = xc.length; - for (; xc[--k4] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i2 < 0) { - --e2; - } else { - x3.c = xc; - x3.e = e2; - x3.s = sign2; - x3 = div(x3, y4, dp, rm, baseOut); - xc = x3.c; - r = x3.r; - e2 = x3.e; - } - d3 = e2 + dp + 1; - i2 = xc[d3]; - k4 = baseOut / 2; - r = r || d3 < 0 || xc[d3 + 1] != null; - r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (d3 < 1 || !xc[0]) { - str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d3; - if (r) { - for (--baseOut; ++xc[--d3] > baseOut; ) { - xc[d3] = 0; - if (!d3) { - ++e2; - xc = [1].concat(xc); - } - } - } - for (k4 = xc.length; !xc[--k4]; ) - ; - for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) - ; - str = toFixedPoint2(str, e2, alphabet2.charAt(0)); - } - return str; - }; - }(); - div = /* @__PURE__ */ function() { - function multiply(x3, k4, base3) { - var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; - for (x3 = x3.slice(); i2--; ) { - xlo = x3[i2] % SQRT_BASE2; - xhi = x3[i2] / SQRT_BASE2 | 0; - m3 = khi * xlo + xhi * klo; - temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; - carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; - x3[i2] = temp % base3; - } - if (carry) - x3 = [carry].concat(x3); - return x3; - } - function compare4(a3, b4, aL, bL) { - var i2, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i2 = cmp = 0; i2 < aL; i2++) { - if (a3[i2] != b4[i2]) { - cmp = a3[i2] > b4[i2] ? 1 : -1; - break; - } - } - } - return cmp; - } - function subtract(a3, b4, aL, base3) { - var i2 = 0; - for (; aL--; ) { - a3[aL] -= i2; - i2 = a3[aL] < b4[aL] ? 1 : 0; - a3[aL] = i2 * base3 + a3[aL] - b4[aL]; - } - for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) - ; - } - return function(x3, y4, dp, rm, base3) { - var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber3( - // Return NaN if either NaN, or both Infinity or 0. - !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 - ) - ); - } - q2 = new BigNumber3(s2); - qc = q2.c = []; - e2 = x3.e - y4.e; - s2 = dp + e2 + 1; - if (!base3) { - base3 = BASE2; - e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); - s2 = s2 / LOG_BASE2 | 0; - } - for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) - ; - if (yc[i2] > (xc[i2] || 0)) - e2--; - if (s2 < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i2 = 0; - s2 += 2; - n3 = mathfloor2(base3 / (yc[0] + 1)); - if (n3 > 1) { - yc = multiply(yc, n3, base3); - xc = multiply(xc, n3, base3); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base3 / 2) - yc0++; - do { - n3 = 0; - cmp = compare4(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base3 + (rem[1] || 0); - n3 = mathfloor2(rem0 / yc0); - if (n3 > 1) { - if (n3 >= base3) - n3 = base3 - 1; - prod = multiply(yc, n3, base3); - prodL = prod.length; - remL = rem.length; - while (compare4(prod, rem, prodL, remL) == 1) { - n3--; - subtract(prod, yL < prodL ? yz : yc, prodL, base3); - prodL = prod.length; - cmp = 1; - } - } else { - if (n3 == 0) { - cmp = n3 = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base3); - remL = rem.length; - if (cmp == -1) { - while (compare4(yc, rem, yL, remL) < 1) { - n3++; - subtract(rem, yL < remL ? yz : yc, remL, base3); - remL = rem.length; - } - } - } else if (cmp === 0) { - n3++; - rem = [0]; - } - qc[i2++] = n3; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s2--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base3 == BASE2) { - for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) - ; - round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); - } else { - q2.e = e2; - q2.r = +more; - } - return q2; - }; - }(); - function format(n3, i2, rm, id) { - var c0, e2, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - if (!n3.c) - return n3.toString(); - c0 = n3.c[0]; - ne = n3.e; - if (i2 == null) { - str = coeffToString2(n3.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); - } else { - n3 = round(new BigNumber3(n3), i2, rm); - e2 = n3.e; - str = coeffToString2(n3.c); - len = str.length; - if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { - for (; len < i2; str += "0", len++) - ; - str = toExponential2(str, e2); - } else { - i2 -= ne; - str = toFixedPoint2(str, e2, "0"); - if (e2 + 1 > len) { - if (--i2 > 0) - for (str += "."; i2--; str += "0") - ; - } else { - i2 += e2 - len; - if (i2 > 0) { - if (e2 + 1 == len) - str += "."; - for (; i2--; str += "0") - ; - } - } - } - } - return n3.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, n3) { - var k4, y4, i2 = 1, x3 = new BigNumber3(args[0]); - for (; i2 < args.length; i2++) { - y4 = new BigNumber3(args[i2]); - if (!y4.s || (k4 = compare3(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { - x3 = y4; - } - } - return x3; - } - function normalise(n3, c4, e2) { - var i2 = 1, j2 = c4.length; - for (; !c4[--j2]; c4.pop()) - ; - for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) - ; - if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { - n3.c = n3.e = null; - } else if (e2 < MIN_EXP) { - n3.c = [n3.e = 0]; - } else { - n3.e = e2; - n3.c = c4; - } - return n3; - } - parseNumeric = /* @__PURE__ */ function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x3, str, isNum, b4) { - var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s2)) { - x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; - } else { - if (!isNum) { - s2 = s2.replace(basePrefix, function(m3, p1, p22) { - base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; - return !b4 || b4 == base3 ? p1 : m3; - }); - if (b4) { - base3 = b4; - s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s2) - return new BigNumber3(s2, base3); - } - if (BigNumber3.DEBUG) { - throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); - } - x3.s = null; - } - x3.c = x3.e = null; - }; - }(); - function round(x3, sd, rm, r) { - var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; - if (xc) { - out: { - for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) - ; - i2 = sd - d3; - if (i2 < 0) { - i2 += LOG_BASE2; - j2 = sd; - n3 = xc[ni = 0]; - rd = mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); - } else { - ni = mathceil2((i2 + 1) / LOG_BASE2); - if (ni >= xc.length) { - if (r) { - for (; xc.length <= ni; xc.push(0)) - ; - n3 = rd = 0; - d3 = 1; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + 1; - } else { - break out; - } - } else { - n3 = k4 = xc[ni]; - for (d3 = 1; k4 >= 10; k4 /= 10, d3++) - ; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + d3; - rd = j2 < 0 ? 0 : mathfloor2(n3 / pows10[d3 - j2 - 1] % 10); - } - } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x3.e + 1; - xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; - x3.e = -sd || 0; - } else { - xc[0] = x3.e = 0; - } - return x3; - } - if (i2 == 0) { - xc.length = ni; - k4 = 1; - ni--; - } else { - xc.length = ni + 1; - k4 = pows10[LOG_BASE2 - i2]; - xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; - } - if (r) { - for (; ; ) { - if (ni == 0) { - for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) - ; - j2 = xc[0] += k4; - for (k4 = 1; j2 >= 10; j2 /= 10, k4++) - ; - if (i2 != k4) { - x3.e++; - if (xc[0] == BASE2) - xc[0] = 1; - } - break; - } else { - xc[ni] += k4; - if (xc[ni] != BASE2) - break; - xc[ni--] = 0; - k4 = 1; - } - } - } - for (i2 = xc.length; xc[--i2] === 0; xc.pop()) - ; - } - if (x3.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (x3.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } - } - return x3; - } - function valueOf(n3) { - var str, e2 = n3.e; - if (e2 === null) - return n3.toString(); - str = coeffToString2(n3.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); - return n3.s < 0 ? "-" + str : str; - } - P2.absoluteValue = P2.abs = function() { - var x3 = new BigNumber3(this); - if (x3.s < 0) - x3.s = 1; - return x3; - }; - P2.comparedTo = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)); - }; - P2.decimalPlaces = P2.dp = function(dp, rm) { - var c4, n3, v2, x3 = this; - if (dp != null) { - intCheck2(dp, 0, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), dp + x3.e + 1, rm); - } - if (!(c4 = x3.c)) - return null; - n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; - if (v2 = c4[v2]) - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - if (n3 < 0) - n3 = 0; - return n3; - }; - P2.dividedBy = P2.div = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); - }; - P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), 0, 1); - }; - P2.exponentiatedBy = P2.pow = function(n3, m3) { - var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; - n3 = new BigNumber3(n3); - if (n3.c && !n3.isInteger()) { - throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); - } - if (m3 != null) - m3 = new BigNumber3(m3); - nIsBig = n3.e > 14; - if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { - y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd2(n3)) : +valueOf(n3))); - return m3 ? y4.mod(m3) : y4; - } - nIsNeg = n3.s < 0; - if (m3) { - if (m3.c ? !m3.c[0] : !m3.s) - return new BigNumber3(NaN); - isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); - if (isModExp) - x3 = x3.mod(m3); - } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { - k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; - if (x3.e > -1) - k4 = 1 / k4; - return new BigNumber3(nIsNeg ? 1 / k4 : k4); - } else if (POW_PRECISION) { - k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); - } - if (nIsBig) { - half = new BigNumber3(0.5); - if (nIsNeg) - n3.s = 1; - nIsOdd = isOdd2(n3); - } else { - i2 = Math.abs(+valueOf(n3)); - nIsOdd = i2 % 2; - } - y4 = new BigNumber3(ONE); - for (; ; ) { - if (nIsOdd) { - y4 = y4.times(x3); - if (!y4.c) - break; - if (k4) { - if (y4.c.length > k4) - y4.c.length = k4; - } else if (isModExp) { - y4 = y4.mod(m3); - } - } - if (i2) { - i2 = mathfloor2(i2 / 2); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } else { - n3 = n3.times(half); - round(n3, n3.e + 1, 1); - if (n3.e > 14) { - nIsOdd = isOdd2(n3); - } else { - i2 = +valueOf(n3); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } - } - x3 = x3.times(x3); - if (k4) { - if (x3.c && x3.c.length > k4) - x3.c.length = k4; - } else if (isModExp) { - x3 = x3.mod(m3); - } - } - if (isModExp) - return y4; - if (nIsNeg) - y4 = ONE.div(y4); - return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; - }; - P2.integerValue = function(rm) { - var n3 = new BigNumber3(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(n3, n3.e + 1, rm); - }; - P2.isEqualTo = P2.eq = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) === 0; - }; - P2.isFinite = function() { - return !!this.c; - }; - P2.isGreaterThan = P2.gt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) > 0; - }; - P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; - }; - P2.isInteger = function() { - return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; - }; - P2.isLessThan = P2.lt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) < 0; - }; - P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; - }; - P2.isNaN = function() { - return !this.s; - }; - P2.isNegative = function() { - return this.s < 0; - }; - P2.isPositive = function() { - return this.s > 0; - }; - P2.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P2.minus = function(y4, b4) { - var i2, j2, t, xLTy, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.plus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); - } - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (xLTy = a3 < 0) { - a3 = -a3; - t = xc; - } else { - ye = xe; - t = yc; - } - t.reverse(); - for (b4 = a3; b4--; t.push(0)) - ; - t.reverse(); - } else { - j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; - for (a3 = b4 = 0; b4 < j2; b4++) { - if (xc[b4] != yc[b4]) { - xLTy = xc[b4] < yc[b4]; - break; - } - } - } - if (xLTy) { - t = xc; - xc = yc; - yc = t; - y4.s = -y4.s; - } - b4 = (j2 = yc.length) - (i2 = xc.length); - if (b4 > 0) - for (; b4--; xc[i2++] = 0) - ; - b4 = BASE2 - 1; - for (; j2 > a3; ) { - if (xc[--j2] < yc[j2]) { - for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) - ; - --xc[i2]; - xc[j2] += BASE2; - } - xc[j2] -= yc[j2]; - } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y4.s = ROUNDING_MODE == 3 ? -1 : 1; - y4.c = [y4.e = 0]; - return y4; - } - return normalise(y4, xc, ye); - }; - P2.modulo = P2.mod = function(y4, b4) { - var q2, s2, x3 = this; - y4 = new BigNumber3(y4, b4); - if (!x3.c || !y4.s || y4.c && !y4.c[0]) { - return new BigNumber3(NaN); - } else if (!y4.c || x3.c && !x3.c[0]) { - return new BigNumber3(x3); - } - if (MODULO_MODE == 9) { - s2 = y4.s; - y4.s = 1; - q2 = div(x3, y4, 0, 3); - y4.s = s2; - q2.s *= s2; - } else { - q2 = div(x3, y4, 0, MODULO_MODE); - } - y4 = x3.minus(q2.times(y4)); - if (!y4.c[0] && MODULO_MODE == 1) - y4.s = x3.s; - return y4; - }; - P2.multipliedBy = P2.times = function(y4, b4) { - var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y4.c = y4.e = y4.s = null; - } else { - y4.s *= x3.s; - if (!xc || !yc) { - y4.c = y4.e = null; - } else { - y4.c = [0]; - y4.e = 0; - } - } - return y4; - } - e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); - y4.s *= x3.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) { - zc = xc; - xc = yc; - yc = zc; - i2 = xcL; - xcL = ycL; - ycL = i2; - } - for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) - ; - base3 = BASE2; - sqrtBase = SQRT_BASE2; - for (i2 = ycL; --i2 >= 0; ) { - c4 = 0; - ylo = yc[i2] % sqrtBase; - yhi = yc[i2] / sqrtBase | 0; - for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { - xlo = xc[--k4] % sqrtBase; - xhi = xc[k4] / sqrtBase | 0; - m3 = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; - c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; - zc[j2--] = xlo % base3; - } - zc[j2] = c4; - } - if (c4) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y4, zc, e2); - }; - P2.negated = function() { - var x3 = new BigNumber3(this); - x3.s = -x3.s || null; - return x3; - }; - P2.plus = function(y4, b4) { - var t, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.minus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber3(a3 / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (a3 > 0) { - ye = xe; - t = yc; - } else { - a3 = -a3; - t = xc; - } - t.reverse(); - for (; a3--; t.push(0)) - ; - t.reverse(); - } - a3 = xc.length; - b4 = yc.length; - if (a3 - b4 < 0) { - t = yc; - yc = xc; - xc = t; - b4 = a3; - } - for (a3 = 0; b4; ) { - a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; - xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; - } - if (a3) { - xc = [a3].concat(xc); - ++ye; - } - return normalise(y4, xc, ye); - }; - P2.precision = P2.sd = function(sd, rm) { - var c4, n3, v2, x3 = this; - if (sd != null && sd !== !!sd) { - intCheck2(sd, 1, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), sd, rm); - } - if (!(c4 = x3.c)) - return null; - v2 = c4.length - 1; - n3 = v2 * LOG_BASE2 + 1; - if (v2 = c4[v2]) { - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) - ; - } - if (sd && x3.e + 1 > n3) - n3 = x3.e + 1; - return n3; - }; - P2.shiftedBy = function(k4) { - intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); - return this.times("1e" + k4); - }; - P2.squareRoot = P2.sqrt = function() { - var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); - if (s2 !== 1 || !c4 || !c4[0]) { - return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); - } - s2 = Math.sqrt(+valueOf(x3)); - if (s2 == 0 || s2 == 1 / 0) { - n3 = coeffToString2(c4); - if ((n3.length + e2) % 2 == 0) - n3 += "0"; - s2 = Math.sqrt(+n3); - e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s2 == 1 / 0) { - n3 = "5e" + e2; - } else { - n3 = s2.toExponential(); - n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; - } - r = new BigNumber3(n3); - } else { - r = new BigNumber3(s2 + ""); - } - if (r.c[0]) { - e2 = r.e; - s2 = e2 + dp; - if (s2 < 3) - s2 = 0; - for (; ; ) { - t = r; - r = half.times(t.plus(div(x3, t, dp, 1))); - if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { - if (r.e < e2) - --s2; - n3 = n3.slice(s2 - 3, s2 + 1); - if (n3 == "9999" || !rep && n3 == "4999") { - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - if (t.times(t).eq(x3)) { - r = t; - break; - } - } - dp += 4; - s2 += 4; - rep = 1; - } else { - if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m3 = !r.times(r).eq(x3); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); - }; - P2.toExponential = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp++; - } - return format(this, dp, rm, 1); - }; - P2.toFixed = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P2.toFormat = function(dp, rm, format2) { - var str, x3 = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError2 + "Argument not an object: " + format2); - } - str = x3.toFixed(dp, rm); - if (x3.c) { - var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g22) { - i2 = g1; - g1 = g22; - g22 = i2; - len -= i2; - } - if (g1 > 0 && len > 0) { - i2 = len % g1 || g1; - intPart = intDigits.substr(0, i2); - for (; i2 < len; i2 += g1) - intPart += groupSeparator + intDigits.substr(i2, g1); - if (g22 > 0) - intPart += groupSeparator + intDigits.slice(i2); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g22 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P2.toFraction = function(md) { - var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; - if (md != null) { - n3 = new BigNumber3(md); - if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { - throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); - } - } - if (!xc) - return new BigNumber3(x3); - d3 = new BigNumber3(ONE); - n1 = d0 = new BigNumber3(ONE); - d1 = n0 = new BigNumber3(ONE); - s2 = coeffToString2(xc); - e2 = d3.e = s2.length - x3.e - 1; - d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; - md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n3 = new BigNumber3(s2); - n0.c[0] = 0; - for (; ; ) { - q2 = div(n3, d3, 0, 1); - d22 = d0.plus(q2.times(d1)); - if (d22.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d22; - n1 = n0.plus(q2.times(d22 = n1)); - n0 = d22; - d3 = n3.minus(q2.times(d22 = d3)); - n3 = d22; - } - d22 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d22.times(n1)); - d0 = d0.plus(d22.times(d1)); - n0.s = n1.s = x3.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( - div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() - ) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P2.toNumber = function() { - return +valueOf(this); - }; - P2.toPrecision = function(sd, rm) { - if (sd != null) - intCheck2(sd, 1, MAX2); - return format(this, sd, rm, 2); - }; - P2.toString = function(b4) { - var str, n3 = this, s2 = n3.s, e2 = n3.e; - if (e2 === null) { - if (s2) { - str = "Infinity"; - if (s2 < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b4 == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); - } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { - n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); - } - if (s2 < 0 && n3.c[0]) - str = "-" + str; - } - return str; - }; - P2.valueOf = P2.toJSON = function() { - return valueOf(this); - }; - P2._isBigNumber = true; - if (configObject != null) - BigNumber3.set(configObject); - return BigNumber3; - } - function bitFloor2(n3) { - var i2 = n3 | 0; - return n3 > 0 || n3 === i2 ? i2 : i2 - 1; - } - function coeffToString2(a3) { - var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; - for (; i2 < j2; ) { - s2 = a3[i2++] + ""; - z3 = LOG_BASE2 - s2.length; - for (; z3--; s2 = "0" + s2) - ; - r += s2; - } - for (j2 = r.length; r.charCodeAt(--j2) === 48; ) - ; - return r.slice(0, j2 + 1 || 1); - } - function compare3(x3, y4) { - var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; - if (!i2 || !j2) - return null; - a3 = xc && !xc[0]; - b4 = yc && !yc[0]; - if (a3 || b4) - return a3 ? b4 ? 0 : -j2 : i2; - if (i2 != j2) - return i2; - a3 = i2 < 0; - b4 = k4 == l4; - if (!xc || !yc) - return b4 ? 0 : !xc ^ a3 ? 1 : -1; - if (!b4) - return k4 > l4 ^ a3 ? 1 : -1; - j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; - for (i2 = 0; i2 < j2; i2++) - if (xc[i2] != yc[i2]) - return xc[i2] > yc[i2] ^ a3 ? 1 : -1; - return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; - } - function intCheck2(n3, min, max, name2) { - if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { - throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); - } - } - function isOdd2(n3) { - var k4 = n3.c.length - 1; - return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; - } - function toExponential2(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; - } - function toFixedPoint2(str, e2, z3) { - var len, zs; - if (e2 < 0) { - for (zs = z3 + "."; ++e2; zs += z3) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z3, e2 -= len; --e2; zs += z3) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } - } - return str; - } - BigNumber2 = clone2(); - BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; - if (typeof define == "function" && define.amd) { - define(function() { - return BigNumber2; - }); - } else if (typeof module2 != "undefined" && module2.exports) { - module2.exports = BigNumber2; - } else { - if (!globalObject) { - globalObject = typeof self != "undefined" && self ? self : window; - } - globalObject.BigNumber = BigNumber2; - } - })(exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/errors.js -var require_errors = __commonJS({ - "node_modules/@multiversx/sdk-core/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrParseTransactionOutcome = exports2.ErrInvalidInnerTransaction = exports2.ErrBadUsage = exports2.ErrInvalidTokenIdentifier = exports2.ErrIsCompletedFieldIsMissingOnTransaction = exports2.ErrGasLimitShouldBe0ForInnerTransaction = exports2.ErrInvalidRelayedV2BuilderArguments = exports2.ErrInvalidRelayedV1BuilderArguments = exports2.ErrNotImplemented = exports2.ErrContractInteraction = exports2.ErrCodec = exports2.ErrCannotParseTransactionOutcome = exports2.ErrCannotParseContractResults = exports2.ErrMissingFieldOnEnum = exports2.ErrMissingFieldOnStruct = exports2.ErrTypingSystem = exports2.ErrMock = exports2.ErrContractHasNoAddress = exports2.ErrContract = exports2.ErrExpectedTransactionEventsNotFound = exports2.ErrExpectedTransactionStatusNotReached = exports2.ErrTransactionWatcherTimeout = exports2.ErrAsyncTimerAborted = exports2.ErrAsyncTimerAlreadyRunning = exports2.ErrInvalidFunctionName = exports2.ErrSignatureCannotCreate = exports2.ErrTransactionOptionsInvalid = exports2.ErrTransactionVersionInvalid = exports2.ErrNonceInvalid = exports2.ErrNotEnoughGas = exports2.ErrAddressEmpty = exports2.ErrAddressBadHrp = exports2.ErrAddressCannotCreate = exports2.ErrUnexpectedCondition = exports2.ErrInvariantFailed = exports2.ErrBadType = exports2.ErrUnsupportedOperation = exports2.ErrInvalidArgument = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - /** - * Returns a pretty, friendly summary for the error or for the chain of errros (if appropriate). - */ - summary() { - let result = []; - result.push({ name: this.name, message: this.message }); - let inner = this.inner; - while (inner) { - result.push({ name: inner.name, message: inner.message }); - inner = inner.inner; - } - return result; - } - }; - exports2.Err = Err; - var ErrInvalidArgument = class extends Err { - constructor(message, inner) { - super(`Invalid argument: ${message}`, inner); - } - }; - exports2.ErrInvalidArgument = ErrInvalidArgument; - var ErrUnsupportedOperation = class extends Err { - constructor(operation, reason = "not specified") { - super(`Operation "${operation}" not supported. Reason: ${reason}`); - } - }; - exports2.ErrUnsupportedOperation = ErrUnsupportedOperation; - var ErrBadType = class extends Err { - constructor(name2, type, value) { - super(`Bad type of "${name2}": ${value}. Expected type: ${type}`); - } - }; - exports2.ErrBadType = ErrBadType; - var ErrInvariantFailed = class extends Err { - constructor(message) { - super(`Invariant failed: [${message}]`); - } - }; - exports2.ErrInvariantFailed = ErrInvariantFailed; - var ErrUnexpectedCondition = class extends Err { - constructor(message) { - super(`Unexpected condition: [${message}]`); - } - }; - exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; - var ErrAddressCannotCreate = class extends Err { - constructor(input, inner) { - let message = `Cannot create address from: ${input}`; - super(message, inner); - } - }; - exports2.ErrAddressCannotCreate = ErrAddressCannotCreate; - var ErrAddressBadHrp = class extends Err { - constructor(expected, got) { - super(`Wrong address HRP. Expected: ${expected}, got ${got}`); - } - }; - exports2.ErrAddressBadHrp = ErrAddressBadHrp; - var ErrAddressEmpty = class extends Err { - constructor() { - super(`Address is empty`); - } - }; - exports2.ErrAddressEmpty = ErrAddressEmpty; - var ErrNotEnoughGas = class extends Err { - constructor(value) { - super(`Not enough gas provided: ${value}`); - } - }; - exports2.ErrNotEnoughGas = ErrNotEnoughGas; - var ErrNonceInvalid = class extends Err { - constructor(value) { - super(`Invalid nonce: ${value}`); - } - }; - exports2.ErrNonceInvalid = ErrNonceInvalid; - var ErrTransactionVersionInvalid = class extends Err { - constructor(value) { - super(`Invalid transaction version: ${value}`); - } - }; - exports2.ErrTransactionVersionInvalid = ErrTransactionVersionInvalid; - var ErrTransactionOptionsInvalid = class extends Err { - constructor(value) { - super(`Invalid transaction options: ${value}`); - } - }; - exports2.ErrTransactionOptionsInvalid = ErrTransactionOptionsInvalid; - var ErrSignatureCannotCreate = class extends Err { - constructor(input, inner) { - let message = `Cannot create signature from: ${input}`; - super(message, inner); - } - }; - exports2.ErrSignatureCannotCreate = ErrSignatureCannotCreate; - var ErrInvalidFunctionName = class extends Err { - constructor() { - super(`Invalid function name`); - } - }; - exports2.ErrInvalidFunctionName = ErrInvalidFunctionName; - var ErrAsyncTimerAlreadyRunning = class extends Err { - constructor() { - super("Async timer already running"); - } - }; - exports2.ErrAsyncTimerAlreadyRunning = ErrAsyncTimerAlreadyRunning; - var ErrAsyncTimerAborted = class extends Err { - constructor() { - super("Async timer aborted"); - } - }; - exports2.ErrAsyncTimerAborted = ErrAsyncTimerAborted; - var ErrTransactionWatcherTimeout = class extends Err { - constructor() { - super(`TransactionWatcher has timed out`); - } - }; - exports2.ErrTransactionWatcherTimeout = ErrTransactionWatcherTimeout; - var ErrExpectedTransactionStatusNotReached = class extends Err { - constructor() { - super(`Expected transaction status not reached`); - } - }; - exports2.ErrExpectedTransactionStatusNotReached = ErrExpectedTransactionStatusNotReached; - var ErrExpectedTransactionEventsNotFound = class extends Err { - constructor() { - super(`Expected transaction events not found`); - } - }; - exports2.ErrExpectedTransactionEventsNotFound = ErrExpectedTransactionEventsNotFound; - var ErrContract = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrContract = ErrContract; - var ErrContractHasNoAddress = class extends ErrContract { - constructor() { - super(` +var ck=Object.create;var Rd=Object.defineProperty;var lk=Object.getOwnPropertyDescriptor;var fk=Object.getOwnPropertyNames;var hk=Object.getPrototypeOf,dk=Object.prototype.hasOwnProperty;var Bd=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)Rd(t,r,{get:e[r],enumerable:!0})},Pd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fk(e))!dk.call(t,i)&&i!==r&&Rd(t,i,{get:()=>e[i],enumerable:!(n=lk(e,i))||n.enumerable});return t},Tr=(t,e,r)=>(Pd(t,e,"default"),r&&Pd(r,e,"default")),pe=(t,e,r)=>(r=t!=null?ck(hk(t)):{},Pd(e||!t||!t.__esModule?Rd(r,"default",{value:t,enumerable:!0}):r,t)),_e=t=>Pd(Rd({},"__esModule",{value:!0}),t);var w3=B(Md=>{"use strict";h();Md.byteLength=pk;Md.toByteArray=yk;Md.fromByteArray=Ak;var Pi=[],Tn=[],gk=typeof Uint8Array<"u"?Uint8Array:Array,mw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ba=0,m3=mw.length;ba0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function pk(t){var e=y3(t),r=e[0],n=e[1];return(r+n)*3/4-n}function mk(t,e,r){return(e+r)*3/4-r}function yk(t){var e,r=y3(t),n=r[0],i=r[1],s=new gk(mk(t,n,i)),o=0,u=i>0?n-4:n,a;for(a=0;a>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tn[t.charCodeAt(a)]<<2|Tn[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=Tn[t.charCodeAt(a)]<<10|Tn[t.charCodeAt(a+1)]<<4|Tn[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function wk(t){return Pi[t>>18&63]+Pi[t>>12&63]+Pi[t>>6&63]+Pi[t&63]}function vk(t,e,r){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=t[r-1],i.push(Pi[e>>2]+Pi[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Pi[e>>10]+Pi[e>>4&63]+Pi[e<<2&63]+"=")),i.join("")}});var v3=B(yw=>{h();yw.read=function(t,e,r,n,i){var s,o,u=i*8-n-1,a=(1<>1,f=-7,d=r?i-1:0,w=r?-1:1,A=t[e+d];for(d+=w,s=A&(1<<-f)-1,A>>=-f,f+=u;f>0;s=s*256+t[e+d],d+=w,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=w,f-=8);if(s===0)s=1-c;else{if(s===a)return o?NaN:(A?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(A?-1:1)*o*Math.pow(2,s-n)};yw.write=function(t,e,r,n,i,s){var o,u,a,c=s*8-i-1,f=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:s-1,T=n?1:-1,x=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=w/a:e+=w*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=f?(u=0,o=f):o+d>=1?(u=(e*a-1)*Math.pow(2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+A]=u&255,A+=T,u/=256,i-=8);for(o=o<0;t[r+A]=o&255,A+=T,o/=256,c-=8);t[r+A-T]|=x*128}});var io=B(Nu=>{"use strict";h();var ww=w3(),Cu=v3(),A3=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nu.Buffer=X;Nu.SlowBuffer=_k;Nu.INSPECT_MAX_BYTES=50;var Ld=2147483647;Nu.kMaxLength=Ld;X.TYPED_ARRAY_SUPPORT=Ek();!X.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 Ek(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(X.prototype,"parent",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.buffer}});Object.defineProperty(X.prototype,"offset",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.byteOffset}});function Cs(t){if(t>Ld)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,X.prototype),e}function X(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return bw(t)}return S3(t,e,r)}X.poolSize=8192;function S3(t,e,r){if(typeof t=="string")return Sk(t,e);if(ArrayBuffer.isView(t))return Ik(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Ri(t,ArrayBuffer)||t&&Ri(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ri(t,SharedArrayBuffer)||t&&Ri(t.buffer,SharedArrayBuffer)))return Aw(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return X.from(n,e,r);var i=Tk(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return X.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}X.from=function(t,e,r){return S3(t,e,r)};Object.setPrototypeOf(X.prototype,Uint8Array.prototype);Object.setPrototypeOf(X,Uint8Array);function I3(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function bk(t,e,r){return I3(t),t<=0?Cs(t):e!==void 0?typeof r=="string"?Cs(t).fill(e,r):Cs(t).fill(e):Cs(t)}X.alloc=function(t,e,r){return bk(t,e,r)};function bw(t){return I3(t),Cs(t<0?0:Sw(t)|0)}X.allocUnsafe=function(t){return bw(t)};X.allocUnsafeSlow=function(t){return bw(t)};function Sk(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!X.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=T3(t,e)|0,n=Cs(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function vw(t){for(var e=t.length<0?0:Sw(t.length)|0,r=Cs(e),n=0;n=Ld)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ld.toString(16)+" bytes");return t|0}function _k(t){return+t!=t&&(t=0),X.alloc(+t)}X.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==X.prototype};X.compare=function(e,r){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),Ri(r,Uint8Array)&&(r=X.from(r,r.offset,r.byteLength)),!X.isBuffer(e)||!X.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?X.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(X.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function T3(t,e){if(X.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ri(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Ew(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return D3(t).length;default:if(i)return n?-1:Ew(t).length;e=(""+e).toLowerCase(),i=!0}}X.byteLength=T3;function Ck(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return Fk(this,e,r);case"utf8":case"utf-8":return C3(this,e,r);case"ascii":return Mk(this,e,r);case"latin1":case"binary":return Lk(this,e,r);case"base64":return Rk(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Uk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}X.prototype._isBuffer=!0;function Sa(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}X.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};A3&&(X.prototype[A3]=X.prototype.inspect);X.prototype.compare=function(e,r,n,i,s){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),!X.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=n-r,a=Math.min(o,u),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Iw(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=X.from(e,n)),X.isBuffer(e))return e.length===0?-1:E3(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):E3(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function E3(t,e,r,n,i){var s=1,o=t.length,u=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,u/=2,r/=2}function a(A,T){return s===1?A[T]:A.readUInt16BE(T*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-u),c=r;c>=0;c--){for(var d=!0,w=0;wi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Nk(this,e,r,n);case"utf8":case"utf-8":return xk(this,e,r,n);case"ascii":case"latin1":case"binary":return Ok(this,e,r,n);case"base64":return Dk(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Pk(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Rk(t,e,r){return e===0&&r===t.length?ww.fromByteArray(t):ww.fromByteArray(t.slice(e,r))}function C3(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+u<=r){var a,c,f,d;switch(u){case 1:s<128&&(o=s);break;case 2:a=t[i+1],(a&192)===128&&(d=(s&31)<<6|a&63,d>127&&(o=d));break;case 3:a=t[i+1],c=t[i+2],(a&192)===128&&(c&192)===128&&(d=(s&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:a=t[i+1],c=t[i+2],f=t[i+3],(a&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(a&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=u}return Bk(n)}var b3=4096;function Bk(t){var e=t.length;if(e<=b3)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}X.prototype.readUintLE=X.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};X.prototype.readUint8=X.prototype.readUInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]};X.prototype.readUint16LE=X.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]|this[e+1]<<8};X.prototype.readUint16BE=X.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]<<8|this[e+1]};X.prototype.readUint32LE=X.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};X.prototype.readUint32BE=X.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};X.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};X.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};X.prototype.readInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};X.prototype.readInt16LE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};X.prototype.readInt16BE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};X.prototype.readInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};X.prototype.readInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};X.prototype.readFloatLE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!0,23,4)};X.prototype.readFloatBE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!1,23,4)};X.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!0,52,8)};X.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!1,52,8)};function zr(t,e,r,n,i,s){if(!X.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}X.prototype.writeUintLE=X.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=1,u=0;for(this[r]=e&255;++u>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=n-1,u=1;for(this[r+o]=e&255;--o>=0&&(u*=256);)this[r+o]=e/u&255;return r+n};X.prototype.writeUint8=X.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,255,0),this[r]=e&255,r+1};X.prototype.writeUint16LE=X.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeUint16BE=X.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeUint32LE=X.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};X.prototype.writeUint32BE=X.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};X.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=0,u=1,a=0;for(this[r]=e&255;++o>0)-a&255;return r+n};X.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=n-1,u=1,a=0;for(this[r+o]=e&255;--o>=0&&(u*=256);)e<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(e/u>>0)-a&255;return r+n};X.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};X.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};X.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function N3(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function x3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,4,34028234663852886e22,-34028234663852886e22),Cu.write(t,e,r,n,23,4),r+4}X.prototype.writeFloatLE=function(e,r,n){return x3(this,e,r,!0,n)};X.prototype.writeFloatBE=function(e,r,n){return x3(this,e,r,!1,n)};function O3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,8,17976931348623157e292,-17976931348623157e292),Cu.write(t,e,r,n,52,8),r+8}X.prototype.writeDoubleLE=function(e,r,n){return O3(this,e,r,!0,n)};X.prototype.writeDoubleBE=function(e,r,n){return O3(this,e,r,!1,n)};X.prototype.copy=function(e,r,n,i){if(!X.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function kk(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function D3(t){return ww.toByteArray(Vk(t))}function Fd(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Ri(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Iw(t){return t!==t}var Gk=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var L3=B((kge,M3)=>{h();var Wt=M3.exports={},Bi,Mi;function Tw(){throw new Error("setTimeout has not been defined")}function _w(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Bi=setTimeout:Bi=Tw}catch{Bi=Tw}try{typeof clearTimeout=="function"?Mi=clearTimeout:Mi=_w}catch{Mi=_w}})();function P3(t){if(Bi===setTimeout)return setTimeout(t,0);if((Bi===Tw||!Bi)&&setTimeout)return Bi=setTimeout,setTimeout(t,0);try{return Bi(t,0)}catch{try{return Bi.call(null,t,0)}catch{return Bi.call(this,t,0)}}}function jk(t){if(Mi===clearTimeout)return clearTimeout(t);if((Mi===_w||!Mi)&&clearTimeout)return Mi=clearTimeout,clearTimeout(t);try{return Mi(t)}catch{try{return Mi.call(null,t)}catch{return Mi.call(this,t)}}}var Ns=[],xu=!1,Ia,Ud=-1;function zk(){!xu||!Ia||(xu=!1,Ia.length?Ns=Ia.concat(Ns):Ud=-1,Ns.length&&R3())}function R3(){if(!xu){var t=P3(zk);xu=!0;for(var e=Ns.length;e;){for(Ia=Ns,Ns=[];++Ud1)for(var r=1;r{p=pe(io()),I=pe(L3()),Qk=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=Qk});var fr={};Bt(fr,{BigNumber:()=>q3,default:()=>Ou});function U3(t){var e,r,n,i=U.prototype={constructor:U,toString:null,valueOf:null},s=new U(1),o=20,u=4,a=-7,c=21,f=-1e7,d=1e7,w=!1,A=1,T=0,x={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},R="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function U(v,C){var D,F,P,l,g,y,E,S,_=this;if(!(_ instanceof U))return new U(v,C);if(C==null){if(v&&v._isBigNumber===!0){_.s=v.s,!v.c||v.e>d?_.c=_.e=null:v.e=10;g/=10,l++);l>d?_.c=_.e=null:(_.e=l,_.c=[v]);return}S=String(v)}else{if(!Kk.test(S=String(v)))return n(_,S,y);_.s=S.charCodeAt(0)==45?(S=S.slice(1),-1):1}(l=S.indexOf("."))>-1&&(S=S.replace(".","")),(g=S.search(/e/i))>0?(l<0&&(l=g),l+=+S.slice(g+1),S=S.substring(0,g)):l<0&&(l=S.length)}else{if(Ht(C,2,R.length,"Base"),C==10&&V)return _=new U(v),H(_,o+_.e+1,u);if(S=String(v),y=typeof v=="number"){if(v*0!=0)return n(_,S,y,C);if(_.s=1/v<0?(S=S.slice(1),-1):1,U.DEBUG&&S.replace(/^0\.0*|\./,"").length>15)throw Error(F3+v)}else _.s=S.charCodeAt(0)===45?(S=S.slice(1),-1):1;for(D=R.slice(0,C),l=g=0,E=S.length;gl){l=E;continue}}else if(!P&&(S==S.toUpperCase()&&(S=S.toLowerCase())||S==S.toLowerCase()&&(S=S.toUpperCase()))){P=!0,g=-1,l=0;continue}return n(_,String(v),y,C)}y=!1,S=r(S,C,10,_.s),(l=S.indexOf("."))>-1?S=S.replace(".",""):l=S.length}for(g=0;S.charCodeAt(g)===48;g++);for(E=S.length;S.charCodeAt(--E)===48;);if(S=S.slice(g,++E)){if(E-=g,y&&U.DEBUG&&E>15&&(v>Nw||v!==Cn(v)))throw Error(F3+_.s*v);if((l=l-g-1)>d)_.c=_.e=null;else if(l=-mr&&P<=mr&&P===Cn(P)){if(F[0]===0){if(P===0&&F.length===1)return!0;break e}if(C=(P+1)%be,C<1&&(C+=be),String(F[0]).length==C){for(C=0;C=di||D!==Cn(D))break e;if(D!==0)return!0}}}else if(F===null&&P===null&&(l===null||l===1||l===-1))return!0;throw Error(Qr+"Invalid BigNumber: "+v)},U.maximum=U.max=function(){return L(arguments,-1)},U.minimum=U.min=function(){return L(arguments,1)},U.random=function(){var v=9007199254740992,C=Math.random()*v&2097151?function(){return Cn(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var F,P,l,g,y,E=0,S=[],_=new U(s);if(D==null?D=o:Ht(D,0,mr),g=Cw(D/be),w)if(crypto.getRandomValues){for(F=crypto.getRandomValues(new Uint32Array(g*=2));E>>11),y>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),F[E]=P[0],F[E+1]=P[1]):(S.push(y%1e14),E+=2);E=g/2}else if(crypto.randomBytes){for(F=crypto.randomBytes(g*=7);E=9e15?crypto.randomBytes(7).copy(F,E):(S.push(y%1e14),E+=7);E=g/7}else throw w=!1,Error(Qr+"crypto unavailable");if(!w)for(;E=10;y/=10,E++);EP-1&&(y[g+1]==null&&(y[g+1]=0),y[g+1]+=y[g]/P|0,y[g]%=P)}return y.reverse()}return function(D,F,P,l,g){var y,E,S,_,M,N,m,O,Y=D.indexOf("."),$=o,b=u;for(Y>=0&&(_=T,T=0,D=D.replace(".",""),O=new U(F),N=O.pow(D.length-Y),T=_,O.c=C(Os(_n(N.c),N.e,"0"),10,P,v),O.e=O.c.length),m=C(D,F,P,g?(y=R,v):(y=v,R)),S=_=m.length;m[--_]==0;m.pop());if(!m[0])return y.charAt(0);if(Y<0?--S:(N.c=m,N.e=S,N.s=l,N=e(N,O,$,b,P),m=N.c,M=N.r,S=N.e),E=S+$+1,Y=m[E],_=P/2,M=M||E<0||m[E+1]!=null,M=b<4?(Y!=null||M)&&(b==0||b==(N.s<0?3:2)):Y>_||Y==_&&(b==4||M||b==6&&m[E-1]&1||b==(N.s<0?8:7)),E<1||!m[0])D=M?Os(y.charAt(1),-$,y.charAt(0)):y.charAt(0);else{if(m.length=E,M)for(--P;++m[--E]>P;)m[E]=0,E||(++S,m=[1].concat(m));for(_=m.length;!m[--_];);for(Y=0,D="";Y<=_;D+=y.charAt(m[Y++]));D=Os(D,S,y.charAt(0))}return D}}(),e=function(){function v(F,P,l){var g,y,E,S,_=0,M=F.length,N=P%so,m=P/so|0;for(F=F.slice();M--;)E=F[M]%so,S=F[M]/so|0,g=m*E+S*N,y=N*E+g%so*so+_,_=(y/l|0)+(g/so|0)+m*S,F[M]=y%l;return _&&(F=[_].concat(F)),F}function C(F,P,l,g){var y,E;if(l!=g)E=l>g?1:-1;else for(y=E=0;yP[y]?1:-1;break}return E}function D(F,P,l,g){for(var y=0;l--;)F[l]-=y,y=F[l]1;F.splice(0,1));}return function(F,P,l,g,y){var E,S,_,M,N,m,O,Y,$,b,j,z,W,ie,te,ee,se,oe=F.s==P.s?1:-1,J=F.c,ue=P.c;if(!J||!J[0]||!ue||!ue[0])return new U(!F.s||!P.s||(J?ue&&J[0]==ue[0]:!ue)?NaN:J&&J[0]==0||!ue?oe*0:oe/0);for(Y=new U(oe),$=Y.c=[],S=F.e-P.e,oe=l+S+1,y||(y=di,S=Nn(F.e/be)-Nn(P.e/be),oe=oe/be|0),_=0;ue[_]==(J[_]||0);_++);if(ue[_]>(J[_]||0)&&S--,oe<0)$.push(1),M=!0;else{for(ie=J.length,ee=ue.length,_=0,oe+=2,N=Cn(y/(ue[0]+1)),N>1&&(ue=v(ue,N,y),J=v(J,N,y),ee=ue.length,ie=J.length),W=ee,b=J.slice(0,ee),j=b.length;j=y/2&&te++;do{if(N=0,E=C(ue,b,ee,j),E<0){if(z=b[0],ee!=j&&(z=z*y+(b[1]||0)),N=Cn(z/te),N>1)for(N>=y&&(N=y-1),m=v(ue,N,y),O=m.length,j=b.length;C(m,b,O,j)==1;)N--,D(m,ee=10;oe/=10,_++);H(Y,l+(Y.e=_+S*be-1)+1,g,M)}else Y.e=S,Y.r=+M;return Y}}();function Q(v,C,D,F){var P,l,g,y,E;if(D==null?D=u:Ht(D,0,8),!v.c)return v.toString();if(P=v.c[0],g=v.e,C==null)E=_n(v.c),E=F==1||F==2&&(g<=a||g>=c)?Vd(E,g):Os(E,g,"0");else if(v=H(new U(v),C,D),l=v.e,E=_n(v.c),y=E.length,F==1||F==2&&(C<=l||l<=a)){for(;yy){if(--C>0)for(E+=".";C--;E+="0");}else if(C+=l-y,C>0)for(l+1==y&&(E+=".");C--;E+="0");return v.s<0&&P?"-"+E:E}function L(v,C){for(var D,F,P=1,l=new U(v[0]);P=10;P/=10,F++);return(D=F+D*be-1)>d?v.c=v.e=null:D=10;y/=10,P++);if(l=C-P,l<0)l+=be,g=C,E=M[S=0],_=Cn(E/N[P-g-1]%10);else if(S=Cw((l+1)/be),S>=M.length)if(F){for(;M.length<=S;M.push(0));E=_=0,P=1,l%=be,g=l-be+1}else break e;else{for(E=y=M[S],P=1;y>=10;y/=10,P++);l%=be,g=l-be+P,_=g<0?0:Cn(E/N[P-g-1]%10)}if(F=F||C<0||M[S+1]!=null||(g<0?E:E%N[P-g-1]),F=D<4?(_||F)&&(D==0||D==(v.s<0?3:2)):_>5||_==5&&(D==4||F||D==6&&(l>0?g>0?E/N[P-g]:0:M[S-1])%10&1||D==(v.s<0?8:7)),C<1||!M[0])return M.length=0,F?(C-=v.e+1,M[0]=N[(be-C%be)%be],v.e=-C||0):M[0]=v.e=0,v;if(l==0?(M.length=S,y=1,S--):(M.length=S+1,y=N[be-l],M[S]=g>0?Cn(E/N[P-g]%N[g])*y:0),F)for(;;)if(S==0){for(l=1,g=M[0];g>=10;g/=10,l++);for(g=M[0]+=y,y=1;g>=10;g/=10,y++);l!=y&&(v.e++,M[0]==di&&(M[0]=1));break}else{if(M[S]+=y,M[S]!=di)break;M[S--]=0,y=1}for(l=M.length;M[--l]===0;M.pop());}v.e>d?v.c=v.e=null:v.e=c?Vd(C,D):Os(C,D,"0"),v.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var v=new U(this);return v.s<0&&(v.s=1),v},i.comparedTo=function(v,C){return Ta(this,new U(v,C))},i.decimalPlaces=i.dp=function(v,C){var D,F,P,l=this;if(v!=null)return Ht(v,0,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v+l.e+1,C);if(!(D=l.c))return null;if(F=((P=D.length-1)-Nn(this.e/be))*be,P=D[P])for(;P%10==0;P/=10,F--);return F<0&&(F=0),F},i.dividedBy=i.div=function(v,C){return e(this,new U(v,C),o,u)},i.dividedToIntegerBy=i.idiv=function(v,C){return e(this,new U(v,C),0,1)},i.exponentiatedBy=i.pow=function(v,C){var D,F,P,l,g,y,E,S,_,M=this;if(v=new U(v),v.c&&!v.isInteger())throw Error(Qr+"Exponent not an integer: "+q(v));if(C!=null&&(C=new U(C)),y=v.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!v.c||!v.c[0])return _=new U(Math.pow(+q(M),y?v.s*(2-qd(v)):+q(v))),C?_.mod(C):_;if(E=v.s<0,C){if(C.c?!C.c[0]:!C.s)return new U(NaN);F=!E&&M.isInteger()&&C.isInteger(),F&&(M=M.mod(C))}else{if(v.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||y&&M.c[1]>=24e7:M.c[0]<8e13||y&&M.c[0]<=9999975e7)))return l=M.s<0&&qd(v)?-0:0,M.e>-1&&(l=1/l),new U(E?1/l:l);T&&(l=Cw(T/be+2))}for(y?(D=new U(.5),E&&(v.s=1),S=qd(v)):(P=Math.abs(+q(v)),S=P%2),_=new U(s);;){if(S){if(_=_.times(M),!_.c)break;l?_.c.length>l&&(_.c.length=l):F&&(_=_.mod(C))}if(P){if(P=Cn(P/2),P===0)break;S=P%2}else if(v=v.times(D),H(v,v.e+1,1),v.e>14)S=qd(v);else{if(P=+q(v),P===0)break;S=P%2}M=M.times(M),l?M.c&&M.c.length>l&&(M.c.length=l):F&&(M=M.mod(C))}return F?_:(E&&(_=s.div(_)),C?_.mod(C):l?H(_,T,u,g):_)},i.integerValue=function(v){var C=new U(this);return v==null?v=u:Ht(v,0,8),H(C,C.e+1,v)},i.isEqualTo=i.eq=function(v,C){return Ta(this,new U(v,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(v,C){return Ta(this,new U(v,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(v,C){return(C=Ta(this,new U(v,C)))===1||C===0},i.isInteger=function(){return!!this.c&&Nn(this.e/be)>this.c.length-2},i.isLessThan=i.lt=function(v,C){return Ta(this,new U(v,C))<0},i.isLessThanOrEqualTo=i.lte=function(v,C){return(C=Ta(this,new U(v,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(v,C){var D,F,P,l,g=this,y=g.s;if(v=new U(v,C),C=v.s,!y||!C)return new U(NaN);if(y!=C)return v.s=-C,g.plus(v);var E=g.e/be,S=v.e/be,_=g.c,M=v.c;if(!E||!S){if(!_||!M)return _?(v.s=-C,v):new U(M?g:NaN);if(!_[0]||!M[0])return M[0]?(v.s=-C,v):new U(_[0]?g:u==3?-0:0)}if(E=Nn(E),S=Nn(S),_=_.slice(),y=E-S){for((l=y<0)?(y=-y,P=_):(S=E,P=M),P.reverse(),C=y;C--;P.push(0));P.reverse()}else for(F=(l=(y=_.length)<(C=M.length))?y:C,y=C=0;C0)for(;C--;_[D++]=0);for(C=di-1;F>y;){if(_[--F]=0;){for(D=0,N=z[P]%$,m=z[P]/$|0,g=E,l=P+g;l>P;)S=j[--g]%$,_=j[g]/$|0,y=m*S+_*N,S=N*S+y%$*$+O[l]+D,D=(S/Y|0)+(y/$|0)+m*_,O[l--]=S%Y;O[l]=D}return D?++F:O.splice(0,1),k(v,O,F)},i.negated=function(){var v=new U(this);return v.s=-v.s||null,v},i.plus=function(v,C){var D,F=this,P=F.s;if(v=new U(v,C),C=v.s,!P||!C)return new U(NaN);if(P!=C)return v.s=-C,F.minus(v);var l=F.e/be,g=v.e/be,y=F.c,E=v.c;if(!l||!g){if(!y||!E)return new U(P/0);if(!y[0]||!E[0])return E[0]?v:new U(y[0]?F:P*0)}if(l=Nn(l),g=Nn(g),y=y.slice(),P=l-g){for(P>0?(g=l,D=E):(P=-P,D=y),D.reverse();P--;D.push(0));D.reverse()}for(P=y.length,C=E.length,P-C<0&&(D=E,E=y,y=D,C=P),P=0;C;)P=(y[--C]=y[C]+E[C]+P)/di|0,y[C]=di===y[C]?0:y[C]%di;return P&&(y=[P].concat(y),++g),k(v,y,g)},i.precision=i.sd=function(v,C){var D,F,P,l=this;if(v!=null&&v!==!!v)return Ht(v,1,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v,C);if(!(D=l.c))return null;if(P=D.length-1,F=P*be+1,P=D[P]){for(;P%10==0;P/=10,F--);for(P=D[0];P>=10;P/=10,F++);}return v&&l.e+1>F&&(F=l.e+1),F},i.shiftedBy=function(v){return Ht(v,-Nw,Nw),this.times("1e"+v)},i.squareRoot=i.sqrt=function(){var v,C,D,F,P,l=this,g=l.c,y=l.s,E=l.e,S=o+4,_=new U("0.5");if(y!==1||!g||!g[0])return new U(!y||y<0&&(!g||g[0])?NaN:g?l:1/0);if(y=Math.sqrt(+q(l)),y==0||y==1/0?(C=_n(g),(C.length+E)%2==0&&(C+="0"),y=Math.sqrt(+C),E=Nn((E+1)/2)-(E<0||E%2),y==1/0?C="5e"+E:(C=y.toExponential(),C=C.slice(0,C.indexOf("e")+1)+E),D=new U(C)):D=new U(y+""),D.c[0]){for(E=D.e,y=E+S,y<3&&(y=0);;)if(P=D,D=_.times(P.plus(e(l,P,S,1))),_n(P.c).slice(0,y)===(C=_n(D.c)).slice(0,y))if(D.e0&&O>0){for(l=O%y||y,_=m.substr(0,l);l0&&(_+=S+m.slice(l)),N&&(_="-"+_)}F=M?_+(D.decimalSeparator||"")+((E=+D.fractionGroupSize)?M.replace(new RegExp("\\d{"+E+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):M):_}return(D.prefix||"")+F+(D.suffix||"")},i.toFraction=function(v){var C,D,F,P,l,g,y,E,S,_,M,N,m=this,O=m.c;if(v!=null&&(y=new U(v),!y.isInteger()&&(y.c||y.s!==1)||y.lt(s)))throw Error(Qr+"Argument "+(y.isInteger()?"out of range: ":"not an integer: ")+q(y));if(!O)return new U(m);for(C=new U(s),S=D=new U(s),F=E=new U(s),N=_n(O),l=C.e=N.length-m.e-1,C.c[0]=xw[(g=l%be)<0?be+g:g],v=!v||y.comparedTo(C)>0?l>0?C:S:y,g=d,d=1/0,y=new U(N),E.c[0]=0;_=e(y,C,0,1),P=D.plus(_.times(F)),P.comparedTo(v)!=1;)D=F,F=P,S=E.plus(_.times(P=S)),E=P,C=y.minus(_.times(P=C)),y=P;return P=e(v.minus(D),F,0,1),E=E.plus(P.times(S)),D=D.plus(P.times(F)),E.s=S.s=m.s,l=l*2,M=e(S,F,l,u).minus(m).abs().comparedTo(e(E,D,l,u).minus(m).abs())<1?[S,F]:[E,D],d=g,M},i.toNumber=function(){return+q(this)},i.toPrecision=function(v,C){return v!=null&&Ht(v,1,mr),Q(this,v,C,2)},i.toString=function(v){var C,D=this,F=D.s,P=D.e;return P===null?F?(C="Infinity",F<0&&(C="-"+C)):C="NaN":(v==null?C=P<=a||P>=c?Vd(_n(D.c),P):Os(_n(D.c),P,"0"):v===10&&V?(D=H(new U(D),o+P+1,u),C=Os(_n(D.c),D.e,"0")):(Ht(v,2,R.length,"Base"),C=r(Os(_n(D.c),P,"0"),10,v,F,!0)),F<0&&D.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return q(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&U.set(t),U}function Nn(t){var e=t|0;return t>0||t===e?e:e-1}function _n(t){for(var e,r,n=1,i=t.length,s=t[0]+"";nc^r?1:-1;for(u=(a=i.length)<(c=s.length)?a:c,o=0;os[o]^r?1:-1;return a==c?0:a>c^r?1:-1}function Ht(t,e,r,n){if(tr||t!==Cn(t))throw Error(Qr+(n||"Argument")+(typeof t=="number"?tr?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function qd(t){var e=t.c.length-1;return Nn(t.e/be)==e&&t.c[e]%2!=0}function Vd(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Os(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e{h();Kk=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Cw=Math.ceil,Cn=Math.floor,Qr="[BigNumber Error] ",F3=Qr+"Number primitive has more than 15 significant digits: ",di=1e14,be=14,Nw=9007199254740991,xw=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],so=1e7,mr=1e9;q3=U3(),Ou=q3});var Ie=B(ce=>{"use strict";h();Object.defineProperty(ce,"__esModule",{value:!0});ce.ErrParseTransactionOutcome=ce.ErrInvalidInnerTransaction=ce.ErrBadUsage=ce.ErrInvalidTokenIdentifier=ce.ErrIsCompletedFieldIsMissingOnTransaction=ce.ErrGasLimitShouldBe0ForInnerTransaction=ce.ErrInvalidRelayedV2BuilderArguments=ce.ErrInvalidRelayedV1BuilderArguments=ce.ErrNotImplemented=ce.ErrContractInteraction=ce.ErrCodec=ce.ErrCannotParseTransactionOutcome=ce.ErrCannotParseContractResults=ce.ErrMissingFieldOnEnum=ce.ErrMissingFieldOnStruct=ce.ErrTypingSystem=ce.ErrMock=ce.ErrContractHasNoAddress=ce.ErrContract=ce.ErrExpectedTransactionEventsNotFound=ce.ErrExpectedTransactionStatusNotReached=ce.ErrTransactionWatcherTimeout=ce.ErrAsyncTimerAborted=ce.ErrAsyncTimerAlreadyRunning=ce.ErrInvalidFunctionName=ce.ErrSignatureCannotCreate=ce.ErrTransactionOptionsInvalid=ce.ErrTransactionVersionInvalid=ce.ErrNonceInvalid=ce.ErrNotEnoughGas=ce.ErrAddressEmpty=ce.ErrAddressBadHrp=ce.ErrAddressCannotCreate=ce.ErrUnexpectedCondition=ce.ErrInvariantFailed=ce.ErrBadType=ce.ErrUnsupportedOperation=ce.ErrInvalidArgument=ce.Err=void 0;var Ce=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};ce.Err=Ce;var Ow=class extends Ce{constructor(e,r){super(`Invalid argument: ${e}`,r)}};ce.ErrInvalidArgument=Ow;var Dw=class extends Ce{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};ce.ErrUnsupportedOperation=Dw;var Pw=class extends Ce{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};ce.ErrBadType=Pw;var Rw=class extends Ce{constructor(e){super(`Invariant failed: [${e}]`)}};ce.ErrInvariantFailed=Rw;var Bw=class extends Ce{constructor(e){super(`Unexpected condition: [${e}]`)}};ce.ErrUnexpectedCondition=Bw;var Mw=class extends Ce{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};ce.ErrAddressCannotCreate=Mw;var Lw=class extends Ce{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};ce.ErrAddressBadHrp=Lw;var Fw=class extends Ce{constructor(){super("Address is empty")}};ce.ErrAddressEmpty=Fw;var Uw=class extends Ce{constructor(e){super(`Not enough gas provided: ${e}`)}};ce.ErrNotEnoughGas=Uw;var qw=class extends Ce{constructor(e){super(`Invalid nonce: ${e}`)}};ce.ErrNonceInvalid=qw;var Vw=class extends Ce{constructor(e){super(`Invalid transaction version: ${e}`)}};ce.ErrTransactionVersionInvalid=Vw;var kw=class extends Ce{constructor(e){super(`Invalid transaction options: ${e}`)}};ce.ErrTransactionOptionsInvalid=kw;var Hw=class extends Ce{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};ce.ErrSignatureCannotCreate=Hw;var Gw=class extends Ce{constructor(){super("Invalid function name")}};ce.ErrInvalidFunctionName=Gw;var jw=class extends Ce{constructor(){super("Async timer already running")}};ce.ErrAsyncTimerAlreadyRunning=jw;var zw=class extends Ce{constructor(){super("Async timer aborted")}};ce.ErrAsyncTimerAborted=zw;var Qw=class extends Ce{constructor(){super("TransactionWatcher has timed out")}};ce.ErrTransactionWatcherTimeout=Qw;var Kw=class extends Ce{constructor(){super("Expected transaction status not reached")}};ce.ErrExpectedTransactionStatusNotReached=Kw;var Ww=class extends Ce{constructor(){super("Expected transaction events not found")}};ce.ErrExpectedTransactionEventsNotFound=Ww;var kd=class extends Ce{constructor(e){super(e)}};ce.ErrContract=kd;var $w=class extends kd{constructor(){super(` The smart contract has no address set. Make sure you provide the address in the constructor, or call setAddress() appropriately. If you need to recompute the address of the contract, make use of SmartContract.computeAddress() (static method). -`); - } - }; - exports2.ErrContractHasNoAddress = ErrContractHasNoAddress; - var ErrMock = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrMock = ErrMock; - var ErrTypingSystem = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrTypingSystem = ErrTypingSystem; - var ErrMissingFieldOnStruct = class extends Err { - constructor(fieldName, structName) { - super(`field ${fieldName} does not exist on struct ${structName}`); - } - }; - exports2.ErrMissingFieldOnStruct = ErrMissingFieldOnStruct; - var ErrMissingFieldOnEnum = class extends Err { - constructor(fieldName, enumName) { - super(`field ${fieldName} does not exist on enum ${enumName}`); - } - }; - exports2.ErrMissingFieldOnEnum = ErrMissingFieldOnEnum; - var ErrCannotParseContractResults = class extends Err { - constructor(details) { - super(`cannot parse contract results: ${details}`); - } - }; - exports2.ErrCannotParseContractResults = ErrCannotParseContractResults; - var ErrCannotParseTransactionOutcome = class extends Err { - constructor(transactionHash, message) { - super(`cannot parse outcome of transaction ${transactionHash}: ${message}`); - } - }; - exports2.ErrCannotParseTransactionOutcome = ErrCannotParseTransactionOutcome; - var ErrCodec = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrCodec = ErrCodec; - var ErrContractInteraction = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrContractInteraction = ErrContractInteraction; - var ErrNotImplemented = class extends Err { - constructor() { - super("Method not yet implemented"); - } - }; - exports2.ErrNotImplemented = ErrNotImplemented; - var ErrInvalidRelayedV1BuilderArguments = class extends Err { - constructor() { - super("invalid arguments for relayed v1 builder"); - } - }; - exports2.ErrInvalidRelayedV1BuilderArguments = ErrInvalidRelayedV1BuilderArguments; - var ErrInvalidRelayedV2BuilderArguments = class extends Err { - constructor() { - super("invalid arguments for relayed v2 builder"); - } - }; - exports2.ErrInvalidRelayedV2BuilderArguments = ErrInvalidRelayedV2BuilderArguments; - var ErrGasLimitShouldBe0ForInnerTransaction = class extends Err { - constructor() { - super("gas limit must be 0 for the inner transaction for relayed v2"); - } - }; - exports2.ErrGasLimitShouldBe0ForInnerTransaction = ErrGasLimitShouldBe0ForInnerTransaction; - var ErrIsCompletedFieldIsMissingOnTransaction = class extends Err { - constructor() { - super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`."); - } - }; - exports2.ErrIsCompletedFieldIsMissingOnTransaction = ErrIsCompletedFieldIsMissingOnTransaction; - var ErrInvalidTokenIdentifier = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrInvalidTokenIdentifier = ErrInvalidTokenIdentifier; - var ErrBadUsage = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrBadUsage = ErrBadUsage; - var ErrInvalidInnerTransaction = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrInvalidInnerTransaction = ErrInvalidInnerTransaction; - var ErrParseTransactionOutcome = class extends Err { - constructor(message) { - super(message); - } - }; - exports2.ErrParseTransactionOutcome = ErrParseTransactionOutcome; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokens.js -var require_tokens = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokens.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenPayment = exports2.TokenComputer = exports2.TokenTransfer = exports2.Token = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var errors_1 = require_errors(); - var EGLDTokenIdentifier = "EGLD"; - var EGLDNumDecimals = 18; - bignumber_js_1.default.set({ ROUNDING_MODE: 1 }); - var Token2 = class { - constructor(options) { - this.identifier = options.identifier; - this.nonce = options.nonce || 0n; - } - }; - exports2.Token = Token2; - var TokenTransfer2 = class _TokenTransfer { - constructor(options) { - if (this.isLegacyTokenTransferOptions(options)) { - const amount = new bignumber_js_1.default(options.amountAsBigInteger); - if (!amount.isInteger() || amount.isNegative()) { - throw new errors_1.ErrInvalidArgument(`bad amountAsBigInteger: ${options.amountAsBigInteger}`); - } - this.tokenIdentifier = options.tokenIdentifier; - this.nonce = options.nonce; - this.amountAsBigInteger = amount; - this.numDecimals = options.numDecimals || 0; - this.token = new Token2({ - identifier: options.tokenIdentifier, - nonce: BigInt(options.nonce) - }); - this.amount = BigInt(this.amountAsBigInteger.toFixed(0)); - } else { - this.token = options.token; - this.amount = options.amount; - this.tokenIdentifier = options.token.identifier; - this.nonce = Number(options.token.nonce); - this.amountAsBigInteger = new bignumber_js_1.default(this.amount.toString()); - this.numDecimals = 0; - } - } - isLegacyTokenTransferOptions(options) { - return options.tokenIdentifier !== void 0; - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static egldFromAmount(amount) { - const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(EGLDNumDecimals).decimalPlaces(0); - return this.egldFromBigInteger(amountAsBigInteger); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static egldFromBigInteger(amountAsBigInteger) { - return new _TokenTransfer({ - tokenIdentifier: EGLDTokenIdentifier, - nonce: 0, - amountAsBigInteger, - numDecimals: EGLDNumDecimals - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static fungibleFromAmount(tokenIdentifier, amount, numDecimals) { - const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); - return this.fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static fungibleFromBigInteger(tokenIdentifier, amountAsBigInteger, numDecimals = 0) { - return new _TokenTransfer({ - tokenIdentifier, - nonce: 0, - amountAsBigInteger, - numDecimals - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static nonFungible(tokenIdentifier, nonce) { - return new _TokenTransfer({ - tokenIdentifier, - nonce, - amountAsBigInteger: 1, - numDecimals: 0 - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static semiFungible(tokenIdentifier, nonce, quantity) { - return new _TokenTransfer({ - tokenIdentifier, - nonce, - amountAsBigInteger: quantity, - numDecimals: 0 - }); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static metaEsdtFromAmount(tokenIdentifier, nonce, amount, numDecimals) { - const amountAsBigInteger = new bignumber_js_1.default(amount).shiftedBy(numDecimals).decimalPlaces(0); - return this.metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals); - } - /** - * Legacy function. Use the constructor instead: new TokenTransfer({ token, amount }); - */ - static metaEsdtFromBigInteger(tokenIdentifier, nonce, amountAsBigInteger, numDecimals = 0) { - return new _TokenTransfer({ - tokenIdentifier, - nonce, - amountAsBigInteger, - numDecimals - }); - } - toString() { - return this.amount.toString(); - } - /** - * Legacy function. Use the "amount" field instead. - */ - valueOf() { - return new bignumber_js_1.default(this.amount.toString()); - } - /** - * Legacy function. For formatting and parsing amounts, use "sdk-dapp" or "bignumber.js" directly. - */ - toPrettyString() { - return `${this.toAmount()} ${this.tokenIdentifier}`; - } - toAmount() { - return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals); - } - /** - * Legacy function. Within your code, don't mix native values (EGLD) and custom (ESDT) tokens. - * See "TransferTransactionsFactory.createTransactionForNativeTokenTransfer()" vs. "TransferTransactionsFactory.createTransactionForESDTTokenTransfer()". - */ - isEgld() { - return this.token.identifier == EGLDTokenIdentifier; - } - /** - * Legacy function. Use "TokenComputer.isFungible(token)" instead. - */ - isFungible() { - return this.token.nonce == 0n; - } - }; - exports2.TokenTransfer = TokenTransfer2; - var TokenComputer2 = class { - constructor() { - } - isFungible(token) { - return token.nonce === 0n; - } - extractNonceFromExtendedIdentifier(identifier) { - const parts = identifier.split("-"); - this.checkIfExtendedIdentifierWasProvided(parts); - this.checkLengthOfRandomSequence(parts[1]); - if (parts.length == 2) { - return 0; - } - const hexNonce = import_buffer.Buffer.from(parts[2], "hex"); - return decodeUnsignedNumber(hexNonce); - } - extractIdentifierFromExtendedIdentifier(identifier) { - const parts = identifier.split("-"); - this.checkIfExtendedIdentifierWasProvided(parts); - this.ensureTokenTickerValidity(parts[0]); - this.checkLengthOfRandomSequence(parts[1]); - return parts[0] + "-" + parts[1]; - } - checkIfExtendedIdentifierWasProvided(tokenParts) { - const MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 2; - const MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED = 3; - if (tokenParts.length < MIN_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED || tokenParts.length > MAX_EXTENDED_IDENTIFIER_LENGTH_IF_SPLITTED) { - throw new errors_1.ErrInvalidTokenIdentifier("Invalid extended token identifier provided"); - } - } - checkLengthOfRandomSequence(randomSequence) { - const TOKEN_RANDOM_SEQUENCE_LENGTH = 6; - if (randomSequence.length !== TOKEN_RANDOM_SEQUENCE_LENGTH) { - throw new errors_1.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length"); - } - } - ensureTokenTickerValidity(ticker) { - const MIN_TICKER_LENGTH = 3; - const MAX_TICKER_LENGTH = 10; - if (ticker.length < MIN_TICKER_LENGTH || ticker.length > MAX_TICKER_LENGTH) { - throw new errors_1.ErrInvalidTokenIdentifier(`The token ticker should be between ${MIN_TICKER_LENGTH} and ${MAX_TICKER_LENGTH} characters`); - } - if (!ticker.match(/^[a-zA-Z0-9]+$/)) { - throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters"); - } - if (!(ticker == ticker.toUpperCase())) { - throw new errors_1.ErrInvalidTokenIdentifier("The token ticker should be upper case"); - } - } - }; - exports2.TokenComputer = TokenComputer2; - function decodeUnsignedNumber(arg) { - return arg.readUIntBE(0, arg.length); - } - var TokenPayment = class extends TokenTransfer2 { - constructor(tokenIdentifier, nonce, amountAsBigInteger, numDecimals) { - super({ - tokenIdentifier, - nonce, - amountAsBigInteger, - numDecimals - }); - } - }; - exports2.TokenPayment = TokenPayment; - } -}); - -// node_modules/@multiversx/sdk-core/out/constants.js -var require_constants = __commonJS({ - "node_modules/@multiversx/sdk-core/out/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.UNKNOWN_SIGNER = exports2.SDK_JS_SIGNER = exports2.METACHAIN_ID = exports2.WasmVirtualMachine = exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = exports2.BECH32_ADDRESS_LENGTH = exports2.HEX_TRANSACTION_HASH_LENGTH = exports2.MESSAGE_PREFIX = exports2.DEFAULT_MESSAGE_VERSION = exports2.ESDT_CONTRACT_ADDRESS = exports2.DEFAULT_HRP = exports2.DELEGATION_MANAGER_SC_ADDRESS = exports2.CONTRACT_DEPLOY_ADDRESS = exports2.VM_TYPE_WASM_VM = exports2.ARGUMENTS_SEPARATOR = exports2.ESDT_TRANSFER_VALUE = exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_FUNCTION_NAME = exports2.ESDT_TRANSFER_GAS_LIMIT = exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = exports2.TRANSACTION_VERSION_DEFAULT = exports2.TRANSACTION_OPTIONS_TX_GUARDED = exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = exports2.TRANSACTION_OPTIONS_DEFAULT = exports2.TRANSACTION_MIN_GAS_PRICE = void 0; - exports2.TRANSACTION_MIN_GAS_PRICE = 1e9; - exports2.TRANSACTION_OPTIONS_DEFAULT = 0; - exports2.TRANSACTION_OPTIONS_TX_HASH_SIGN = 1; - exports2.TRANSACTION_OPTIONS_TX_GUARDED = 2; - exports2.TRANSACTION_VERSION_DEFAULT = 2; - exports2.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS = 2; - exports2.ESDT_TRANSFER_GAS_LIMIT = 5e5; - exports2.ESDT_TRANSFER_FUNCTION_NAME = "ESDTTransfer"; - exports2.ESDTNFT_TRANSFER_FUNCTION_NAME = "ESDTNFTTransfer"; - exports2.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME = "MultiESDTNFTTransfer"; - exports2.ESDT_TRANSFER_VALUE = "0"; - exports2.ARGUMENTS_SEPARATOR = "@"; - exports2.VM_TYPE_WASM_VM = new Uint8Array([5, 0]); - exports2.CONTRACT_DEPLOY_ADDRESS = "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"; - exports2.DELEGATION_MANAGER_SC_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"; - exports2.DEFAULT_HRP = "erd"; - exports2.ESDT_CONTRACT_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"; - exports2.DEFAULT_MESSAGE_VERSION = 1; - exports2.MESSAGE_PREFIX = "Elrond Signed Message:\n"; - exports2.HEX_TRANSACTION_HASH_LENGTH = 64; - exports2.BECH32_ADDRESS_LENGTH = 62; - exports2.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META = 3; - exports2.WasmVirtualMachine = "0500"; - exports2.METACHAIN_ID = 4294967295; - exports2.SDK_JS_SIGNER = "sdk-js"; - exports2.UNKNOWN_SIGNER = "unknown"; - } -}); - -// node_modules/@multiversx/sdk-core/out/logger.js -var require_logger = __commonJS({ - "node_modules/@multiversx/sdk-core/out/logger.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Logger = exports2.LogLevel = void 0; - var LogLevel; - (function(LogLevel2) { - LogLevel2[LogLevel2["Trace"] = 0] = "Trace"; - LogLevel2[LogLevel2["Debug"] = 1] = "Debug"; - LogLevel2[LogLevel2["Info"] = 2] = "Info"; - LogLevel2[LogLevel2["Warn"] = 3] = "Warn"; - LogLevel2[LogLevel2["Error"] = 4] = "Error"; - LogLevel2[LogLevel2["None"] = 5] = "None"; - })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); - var Logger = class _Logger { - static setLevel(logLevel) { - _Logger.logLevel = logLevel; - } - static trace(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Debug) { - return; - } - console.debug(message, optionalParams); - } - static debug(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Debug) { - return; - } - console.debug(message, optionalParams); - } - static info(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Info) { - return; - } - console.log(message, optionalParams); - } - static warn(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Warn) { - return; - } - console.warn(message, optionalParams); - } - static error(message, ...optionalParams) { - if (_Logger.logLevel >= LogLevel.Error) { - return; - } - console.error(message, optionalParams); - } - }; - exports2.Logger = Logger; - Logger.logLevel = LogLevel.Debug; - } -}); - -// node_modules/@multiversx/sdk-core/out/networkParams.js -var require_networkParams = __commonJS({ - "node_modules/@multiversx/sdk-core/out/networkParams.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionOptions = exports2.TransactionVersion = void 0; - var constants_1 = require_constants(); - var errors = __importStar2(require_errors()); - var TransactionVersion2 = class _TransactionVersion { - /** - * Creates a TransactionVersion object given a value. - */ - constructor(value) { - value = Number(value); - if (value < 1) { - throw new errors.ErrTransactionVersionInvalid(value); - } - this.value = value; - } - /** - * Creates a TransactionVersion object with the default version setting - */ - static withDefaultVersion() { - return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); - } - /** - * Creates a TransactionVersion object with the VERSION setting for enabling options - */ - static withTxOptions() { - return new _TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); - } - valueOf() { - return this.value; - } - }; - exports2.TransactionVersion = TransactionVersion2; - var TransactionOptions2 = class _TransactionOptions { - /** - * Creates a TransactionOptions from a numeric value. - */ - constructor(value) { - value = Number(value); - if (value < 0) { - throw new errors.ErrTransactionOptionsInvalid(value); - } - this.value = value; - } - /** - * Creates a TransactionOptions object with the default options. - */ - static withDefaultOptions() { - return new _TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); - } - /** - * Creates a TransactionOptions object from a set of options. - */ - static withOptions(options) { - let value = 0; - if (options.hashSign) { - value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - if (options.guarded) { - value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - return new _TransactionOptions(value); - } - /** - * Returns true if the "hash sign" option is set. - */ - isWithHashSign() { - return (this.value & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - /** - * Returns true if the "guarded transaction" option is set. - */ - isWithGuardian() { - return (this.value & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - /** - * Sets the "hash sign" option. - */ - setWithHashSign() { - this.value |= constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - /** - * Sets the "guarded transaction" option. - */ - setWithGuardian() { - this.value |= constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - valueOf() { - return this.value; - } - }; - exports2.TransactionOptions = TransactionOptions2; - } -}); - -// node_modules/bech32/index.js -var require_bech32 = __commonJS({ - "node_modules/bech32/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; - var ALPHABET_MAP = {}; - for (z3 = 0; z3 < ALPHABET.length; z3++) { - x3 = ALPHABET.charAt(z3); - if (ALPHABET_MAP[x3] !== void 0) - throw new TypeError(x3 + " is ambiguous"); - ALPHABET_MAP[x3] = z3; - } - var x3; - var z3; - function polymodStep(pre) { - var b4 = pre >> 25; - return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; - } - function prefixChk(prefix) { - var chk = 1; - for (var i2 = 0; i2 < prefix.length; ++i2) { - var c4 = prefix.charCodeAt(i2); - if (c4 < 33 || c4 > 126) - return "Invalid prefix (" + prefix + ")"; - chk = polymodStep(chk) ^ c4 >> 5; - } - chk = polymodStep(chk); - for (i2 = 0; i2 < prefix.length; ++i2) { - var v2 = prefix.charCodeAt(i2); - chk = polymodStep(chk) ^ v2 & 31; - } - return chk; - } - function encode5(prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if (prefix.length + 7 + words.length > LIMIT) - throw new TypeError("Exceeds length limit"); - prefix = prefix.toLowerCase(); - var chk = prefixChk(prefix); - if (typeof chk === "string") - throw new Error(chk); - var result = prefix + "1"; - for (var i2 = 0; i2 < words.length; ++i2) { - var x4 = words[i2]; - if (x4 >> 5 !== 0) - throw new Error("Non 5-bit word"); - chk = polymodStep(chk) ^ x4; - result += ALPHABET.charAt(x4); - } - for (i2 = 0; i2 < 6; ++i2) { - chk = polymodStep(chk); - } - chk ^= 1; - for (i2 = 0; i2 < 6; ++i2) { - var v2 = chk >> (5 - i2) * 5 & 31; - result += ALPHABET.charAt(v2); - } - return result; - } - function __decode(str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) - return str + " too short"; - if (str.length > LIMIT) - return "Exceeds length limit"; - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) - return "Mixed-case string " + str; - str = lowered; - var split = str.lastIndexOf("1"); - if (split === -1) - return "No separator character for " + str; - if (split === 0) - return "Missing prefix for " + str; - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) - return "Data too short"; - var chk = prefixChk(prefix); - if (typeof chk === "string") - return chk; - var words = []; - for (var i2 = 0; i2 < wordChars.length; ++i2) { - var c4 = wordChars.charAt(i2); - var v2 = ALPHABET_MAP[c4]; - if (v2 === void 0) - return "Unknown character " + c4; - chk = polymodStep(chk) ^ v2; - if (i2 + 6 >= wordChars.length) - continue; - words.push(v2); - } - if (chk !== 1) - return "Invalid checksum for " + str; - return { prefix, words }; - } - function decodeUnsafe() { - var res = __decode.apply(null, arguments); - if (typeof res === "object") - return res; - } - function decode6(str) { - var res = __decode.apply(null, arguments); - if (typeof res === "object") - return res; - throw new Error(res); - } - function convert(data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - var result = []; - for (var i2 = 0; i2 < data.length; ++i2) { - value = value << inBits | data[i2]; - bits += inBits; - while (bits >= outBits) { - bits -= outBits; - result.push(value >> bits & maxV); - } - } - if (pad) { - if (bits > 0) { - result.push(value << outBits - bits & maxV); - } - } else { - if (bits >= inBits) - return "Excess padding"; - if (value << outBits - bits & maxV) - return "Non-zero padding"; - } - return result; - } - function toWordsUnsafe(bytes) { - var res = convert(bytes, 8, 5, true); - if (Array.isArray(res)) - return res; - } - function toWords(bytes) { - var res = convert(bytes, 8, 5, true); - if (Array.isArray(res)) - return res; - throw new Error(res); - } - function fromWordsUnsafe(words) { - var res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - } - function fromWords(words) { - var res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - throw new Error(res); - } - module2.exports = { - decodeUnsafe, - decode: decode6, - encode: encode5, - toWordsUnsafe, - toWords, - fromWordsUnsafe, - fromWords - }; - } -}); - -// node_modules/@multiversx/sdk-core/out/utils.codec.js -var require_utils_codec = __commonJS({ - "node_modules/@multiversx/sdk-core/out/utils.codec.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.addressToHex = exports2.bigIntToHex = exports2.byteArrayToHex = exports2.boolToHex = exports2.utf8ToHex = exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var contractsCodecUtils = __importStar2(require_utils()); - function numberToPaddedHex(value) { - let hexableNumber; - if (typeof value === "bigint" || typeof value === "number") { - hexableNumber = value; - } else { - hexableNumber = new bignumber_js_1.default(value); - } - const hex = hexableNumber.toString(16); - return zeroPadStringIfOddLength(hex); - } - exports2.numberToPaddedHex = numberToPaddedHex; - function isPaddedHex(input) { - input = input || ""; - let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); - return input.toUpperCase() == decodedThenEncoded.toUpperCase(); - } - exports2.isPaddedHex = isPaddedHex; - function zeroPadStringIfOddLength(input) { - input = input || ""; - if (input.length % 2 == 1) { - return "0" + input; - } - return input; - } - exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; - function utf8ToHex(value) { - const hex = import_buffer.Buffer.from(value).toString("hex"); - return zeroPadStringIfOddLength(hex); - } - exports2.utf8ToHex = utf8ToHex; - function boolToHex(value) { - return utf8ToHex(value.toString()); - } - exports2.boolToHex = boolToHex; - function byteArrayToHex(byteArray) { - const hexString = import_buffer.Buffer.from(byteArray).toString("hex"); - return zeroPadStringIfOddLength(hexString); - } - exports2.byteArrayToHex = byteArrayToHex; - function bigIntToHex(value) { - if (value == 0) { - return ""; - } - return contractsCodecUtils.getHexMagnitudeOfBigInt(value); - } - exports2.bigIntToHex = bigIntToHex; - function addressToHex(address) { - const buffer = address_1.Address.fromBech32(address.toString()).pubkey(); - return buffer.toString("hex"); - } - exports2.addressToHex = addressToHex; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js -var require_utils = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/utils.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.prependByteToBuffer = exports2.flipBufferBitsInPlace = exports2.getHexMagnitudeOfBigInt = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.cloneBuffer = exports2.isMsbZero = exports2.isMsbOne = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var utils_codec_1 = require_utils_codec(); - function isMsbOne(buffer, byteIndex = 0) { - let byte = buffer[byteIndex]; - let bit = byte >> 7; - let isSet = bit == 1; - return isSet; - } - exports2.isMsbOne = isMsbOne; - function isMsbZero(buffer, byteIndex = 0) { - return !isMsbOne(buffer, byteIndex); - } - exports2.isMsbZero = isMsbZero; - function cloneBuffer(buffer) { - let clone2 = import_buffer.Buffer.alloc(buffer.length); - buffer.copy(clone2); - return clone2; - } - exports2.cloneBuffer = cloneBuffer; - function bufferToBigInt(buffer) { - let hex = buffer.toString("hex"); - return new bignumber_js_1.default(`0x${hex}`, 16); - } - exports2.bufferToBigInt = bufferToBigInt; - function bigIntToBuffer(value) { - let hex = getHexMagnitudeOfBigInt(value); - return import_buffer.Buffer.from(hex, "hex"); - } - exports2.bigIntToBuffer = bigIntToBuffer; - function getHexMagnitudeOfBigInt(value) { - value = new bignumber_js_1.default(value); - if (!value) { - return ""; - } - if (value.isNegative()) { - value = value.multipliedBy(new bignumber_js_1.default(-1)); - } - return utils_codec_1.numberToPaddedHex(value); - } - exports2.getHexMagnitudeOfBigInt = getHexMagnitudeOfBigInt; - function flipBufferBitsInPlace(buffer) { - for (let i2 = 0; i2 < buffer.length; i2++) { - buffer[i2] = ~buffer[i2]; - } - } - exports2.flipBufferBitsInPlace = flipBufferBitsInPlace; - function prependByteToBuffer(buffer, byte) { - return import_buffer.Buffer.concat([import_buffer.Buffer.from([byte]), buffer]); - } - exports2.prependByteToBuffer = prependByteToBuffer; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js -var require_codec = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/codec.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bufferToHex = exports2.addressToHex = exports2.bigIntToHex = exports2.utf8ToHex = exports2.bigIntToBuffer = exports2.bufferToBigInt = exports2.stringToBuffer = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var contractsCodecUtils = __importStar2(require_utils()); - var codecUtils = __importStar2(require_utils_codec()); - function stringToBuffer(value) { - return import_buffer.Buffer.from(value); - } - exports2.stringToBuffer = stringToBuffer; - function bufferToBigInt(buffer) { - if (buffer.length == 0) { - return new bignumber_js_1.default(0); - } - return contractsCodecUtils.bufferToBigInt(buffer); - } - exports2.bufferToBigInt = bufferToBigInt; - function bigIntToBuffer(value) { - if (value == 0) { - return import_buffer.Buffer.from([]); - } - return contractsCodecUtils.bigIntToBuffer(value); - } - exports2.bigIntToBuffer = bigIntToBuffer; - var utils_codec_1 = require_utils_codec(); - Object.defineProperty(exports2, "utf8ToHex", { enumerable: true, get: function() { - return utils_codec_1.utf8ToHex; - } }); - Object.defineProperty(exports2, "bigIntToHex", { enumerable: true, get: function() { - return utils_codec_1.bigIntToHex; - } }); - Object.defineProperty(exports2, "addressToHex", { enumerable: true, get: function() { - return utils_codec_1.addressToHex; - } }); - function bufferToHex(value) { - const hex = value.toString("hex"); - return codecUtils.zeroPadStringIfOddLength(hex); - } - exports2.bufferToHex = bufferToHex; - } -}); - -// node_modules/events/events.js -var require_events = __commonJS({ - "node_modules/events/events.js"(exports2, module2) { - "use strict"; - init_shim(); - var R2 = typeof Reflect === "object" ? Reflect : null; - var ReflectApply = R2 && typeof R2.apply === "function" ? R2.apply : function ReflectApply2(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - }; - var ReflectOwnKeys; - if (R2 && typeof R2.ownKeys === "function") { - ReflectOwnKeys = R2.ownKeys; - } else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys2(target) { - return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); - }; - } else { - ReflectOwnKeys = function ReflectOwnKeys2(target) { - return Object.getOwnPropertyNames(target); - }; - } - function ProcessEmitWarning(warning) { - if (console && console.warn) - console.warn(warning); - } - var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { - return value !== value; - }; - function EventEmitter2() { - EventEmitter2.init.call(this); - } - module2.exports = EventEmitter2; - module2.exports.once = once; - EventEmitter2.EventEmitter = EventEmitter2; - EventEmitter2.prototype._events = void 0; - EventEmitter2.prototype._eventsCount = 0; - EventEmitter2.prototype._maxListeners = void 0; - var defaultMaxListeners = 10; - function checkListener(listener) { - if (typeof listener !== "function") { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } - } - Object.defineProperty(EventEmitter2, "defaultMaxListeners", { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); - } - defaultMaxListeners = arg; - } - }); - EventEmitter2.init = function() { - if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - } - this._maxListeners = this._maxListeners || void 0; - }; - EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n3) { - if (typeof n3 !== "number" || n3 < 0 || NumberIsNaN(n3)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n3 + "."); - } - this._maxListeners = n3; - return this; - }; - function _getMaxListeners(that) { - if (that._maxListeners === void 0) - return EventEmitter2.defaultMaxListeners; - return that._maxListeners; - } - EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); - }; - EventEmitter2.prototype.emit = function emit(type) { - var args = []; - for (var i2 = 1; i2 < arguments.length; i2++) - args.push(arguments[i2]); - var doError = type === "error"; - var events = this._events; - if (events !== void 0) - doError = doError && events.error === void 0; - else if (!doError) - return false; - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - throw er; - } - var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); - err.context = er; - throw err; - } - var handler = events[type]; - if (handler === void 0) - return false; - if (typeof handler === "function") { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i2 = 0; i2 < len; ++i2) - ReflectApply(listeners[i2], this, args); - } - return true; - }; - function _addListener(target, type, listener, prepend) { - var m3; - var events; - var existing; - checkListener(listener); - events = target._events; - if (events === void 0) { - events = target._events = /* @__PURE__ */ Object.create(null); - target._eventsCount = 0; - } else { - if (events.newListener !== void 0) { - target.emit( - "newListener", - type, - listener.listener ? listener.listener : listener - ); - events = target._events; - } - existing = events[type]; - } - if (existing === void 0) { - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === "function") { - existing = events[type] = prepend ? [listener, existing] : [existing, listener]; - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - m3 = _getMaxListeners(target); - if (m3 > 0 && existing.length > m3 && !existing.warned) { - existing.warned = true; - var w4 = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); - w4.name = "MaxListenersExceededWarning"; - w4.emitter = target; - w4.type = type; - w4.count = existing.length; - ProcessEmitWarning(w4); - } - } - return target; - } - EventEmitter2.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); - }; - EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; - EventEmitter2.prototype.prependListener = function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } - } - function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: void 0, target, type, listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; - } - EventEmitter2.prototype.once = function once2(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; - EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - EventEmitter2.prototype.removeListener = function removeListener(type, listener) { - var list, events, position, i2, originalListener; - checkListener(listener); - events = this._events; - if (events === void 0) - return this; - list = events[type]; - if (list === void 0) - return this; - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = /* @__PURE__ */ Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit("removeListener", type, list.listener || listener); - } - } else if (typeof list !== "function") { - position = -1; - for (i2 = list.length - 1; i2 >= 0; i2--) { - if (list[i2] === listener || list[i2].listener === listener) { - originalListener = list[i2].listener; - position = i2; - break; - } - } - if (position < 0) - return this; - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - if (list.length === 1) - events[type] = list[0]; - if (events.removeListener !== void 0) - this.emit("removeListener", type, originalListener || listener); - } - return this; - }; - EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; - EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { - var listeners, events, i2; - events = this._events; - if (events === void 0) - return this; - if (events.removeListener === void 0) { - if (arguments.length === 0) { - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== void 0) { - if (--this._eventsCount === 0) - this._events = /* @__PURE__ */ Object.create(null); - else - delete events[type]; - } - return this; - } - if (arguments.length === 0) { - var keys2 = Object.keys(events); - var key; - for (i2 = 0; i2 < keys2.length; ++i2) { - key = keys2[i2]; - if (key === "removeListener") - continue; - this.removeAllListeners(key); - } - this.removeAllListeners("removeListener"); - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - return this; - } - listeners = events[type]; - if (typeof listeners === "function") { - this.removeListener(type, listeners); - } else if (listeners !== void 0) { - for (i2 = listeners.length - 1; i2 >= 0; i2--) { - this.removeListener(type, listeners[i2]); - } - } - return this; - }; - function _listeners(target, type, unwrap) { - var events = target._events; - if (events === void 0) - return []; - var evlistener = events[type]; - if (evlistener === void 0) - return []; - if (typeof evlistener === "function") - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); - } - EventEmitter2.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); - }; - EventEmitter2.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); - }; - EventEmitter2.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === "function") { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } - }; - EventEmitter2.prototype.listenerCount = listenerCount; - function listenerCount(type) { - var events = this._events; - if (events !== void 0) { - var evlistener = events[type]; - if (typeof evlistener === "function") { - return 1; - } else if (evlistener !== void 0) { - return evlistener.length; - } - } - return 0; - } - EventEmitter2.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; - }; - function arrayClone(arr, n3) { - var copy = new Array(n3); - for (var i2 = 0; i2 < n3; ++i2) - copy[i2] = arr[i2]; - return copy; - } - function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); - } - function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i2 = 0; i2 < ret.length; ++i2) { - ret[i2] = arr[i2].listener || arr[i2]; - } - return ret; - } - function once(emitter, name2) { - return new Promise(function(resolve, reject) { - function errorListener(err) { - emitter.removeListener(name2, resolver); - reject(err); - } - function resolver() { - if (typeof emitter.removeListener === "function") { - emitter.removeListener("error", errorListener); - } - resolve([].slice.call(arguments)); - } - ; - eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); - if (name2 !== "error") { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); - } - function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === "function") { - eventTargetAgnosticAddListener(emitter, "error", handler, flags); - } - } - function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { - if (typeof emitter.on === "function") { - if (flags.once) { - emitter.once(name2, listener); - } else { - emitter.on(name2, listener); - } - } else if (typeof emitter.addEventListener === "function") { - emitter.addEventListener(name2, function wrapListener(arg) { - if (flags.once) { - emitter.removeEventListener(name2, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } - } - } -}); - -// node_modules/readable-stream/lib/internal/streams/stream-browser.js -var require_stream_browser = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/stream-browser.js"(exports2, module2) { - init_shim(); - module2.exports = require_events().EventEmitter; - } -}); - -// node_modules/buffer/index.js -var require_buffer2 = __commonJS({ - "node_modules/buffer/index.js"(exports2) { - "use strict"; - init_shim(); - var base642 = require_base64_js(); - var ieee754 = require_ieee754(); - var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports2.Buffer = Buffer2; - exports2.SlowBuffer = SlowBuffer; - exports2.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 2147483647; - exports2.kMaxLength = K_MAX_LENGTH; - Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && 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 typedArraySupport() { - try { - const arr = new Uint8Array(1); - const proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e2) { - return false; - } - } - Object.defineProperty(Buffer2.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer2.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) - return void 0; - return this.byteOffset; - } - }); - function createBuffer(length2) { - if (length2 > K_MAX_LENGTH) { - throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); - } - const buf = new Uint8Array(length2); - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function Buffer2(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe2(arg); - } - return from3(arg, encodingOrOffset, length2); - } - Buffer2.poolSize = 8192; - function from3(value, encodingOrOffset, length2) { - if (typeof value === "string") { - return fromString3(value, encodingOrOffset); - } - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length2); - } - if (typeof value === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - const valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer2.from(valueOf, encodingOrOffset, length2); - } - const b4 = fromObject(value); - if (b4) - return b4; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length2); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - Buffer2.from = function(value, encodingOrOffset, length2) { - return from3(value, encodingOrOffset, length2); - }; - Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer2, Uint8Array); - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } - } - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); - } - Buffer2.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; - function allocUnsafe2(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - Buffer2.allocUnsafe = function(size) { - return allocUnsafe2(size); - }; - Buffer2.allocUnsafeSlow = function(size) { - return allocUnsafe2(size); - }; - function fromString3(string2, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - const length2 = byteLength(string2, encoding) | 0; - let buf = createBuffer(length2); - const actual = buf.write(string2, encoding); - if (actual !== length2) { - buf = buf.slice(0, actual); - } - return buf; - } - function fromArrayLike(array) { - const length2 = array.length < 0 ? 0 : checked(array.length) | 0; - const buf = createBuffer(length2); - for (let i2 = 0; i2 < length2; i2 += 1) { - buf[i2] = array[i2] & 255; - } - return buf; - } - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - const copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - return fromArrayLike(arrayView); - } - function fromArrayBuffer(array, byteOffset, length2) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length2 || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - let buf; - if (byteOffset === void 0 && length2 === void 0) { - buf = new Uint8Array(array); - } else if (length2 === void 0) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length2); - } - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function fromObject(obj) { - if (Buffer2.isBuffer(obj)) { - const len = checked(obj.length) | 0; - const buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - function checked(length2) { - if (length2 >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length2 | 0; - } - function SlowBuffer(length2) { - if (+length2 != length2) { - length2 = 0; - } - return Buffer2.alloc(+length2); - } - Buffer2.isBuffer = function isBuffer(b4) { - return b4 != null && b4._isBuffer === true && b4 !== Buffer2.prototype; - }; - Buffer2.compare = function compare3(a3, b4) { - if (isInstance(a3, Uint8Array)) - a3 = Buffer2.from(a3, a3.offset, a3.byteLength); - if (isInstance(b4, Uint8Array)) - b4 = Buffer2.from(b4, b4.offset, b4.byteLength); - if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b4)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a3 === b4) - return 0; - let x3 = a3.length; - let y4 = b4.length; - for (let i2 = 0, len = Math.min(x3, y4); i2 < len; ++i2) { - if (a3[i2] !== b4[i2]) { - x3 = a3[i2]; - y4 = b4[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - Buffer2.isEncoding = function isEncoding(encoding) { - switch (String(encoding).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 true; - default: - return false; - } - }; - Buffer2.concat = function concat2(list, length2) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer2.alloc(0); - } - let i2; - if (length2 === void 0) { - length2 = 0; - for (i2 = 0; i2 < list.length; ++i2) { - length2 += list[i2].length; - } - } - const buffer = Buffer2.allocUnsafe(length2); - let pos = 0; - for (i2 = 0; i2 < list.length; ++i2) { - let buf = list[i2]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - if (!Buffer2.isBuffer(buf)) - buf = Buffer2.from(buf); - buf.copy(buffer, pos); - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ); - } - } else if (!Buffer2.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - pos += buf.length; - } - return buffer; - }; - function byteLength(string2, encoding) { - if (Buffer2.isBuffer(string2)) { - return string2.length; - } - if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { - return string2.byteLength; - } - if (typeof string2 !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 - ); - } - const len = string2.length; - const mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) - return 0; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes(string2).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string2).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string2).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.byteLength = byteLength; - function slowToString(encoding, start, end) { - let loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) - encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.prototype._isBuffer = true; - function swap(b4, n3, m3) { - const i2 = b4[n3]; - b4[n3] = b4[m3]; - b4[m3] = i2; - } - Buffer2.prototype.swap16 = function swap16() { - const len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (let i2 = 0; i2 < len; i2 += 2) { - swap(this, i2, i2 + 1); - } - return this; - }; - Buffer2.prototype.swap32 = function swap32() { - const len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i2 = 0; i2 < len; i2 += 4) { - swap(this, i2, i2 + 3); - swap(this, i2 + 1, i2 + 2); - } - return this; - }; - Buffer2.prototype.swap64 = function swap64() { - const len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (let i2 = 0; i2 < len; i2 += 8) { - swap(this, i2, i2 + 7); - swap(this, i2 + 1, i2 + 6); - swap(this, i2 + 2, i2 + 5); - swap(this, i2 + 3, i2 + 4); - } - return this; - }; - Buffer2.prototype.toString = function toString3() { - const length2 = this.length; - if (length2 === 0) - return ""; - if (arguments.length === 0) - return utf8Slice(this, 0, length2); - return slowToString.apply(this, arguments); - }; - Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; - Buffer2.prototype.equals = function equals4(b4) { - if (!Buffer2.isBuffer(b4)) - throw new TypeError("Argument must be a Buffer"); - if (this === b4) - return true; - return Buffer2.compare(this, b4) === 0; - }; - Buffer2.prototype.inspect = function inspect() { - let str = ""; - const max = exports2.INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) - str += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; - } - Buffer2.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer2.from(target, target.offset, target.byteLength); - } - if (!Buffer2.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) - return 0; - let x3 = thisEnd - thisStart; - let y4 = end - start; - const len = Math.min(x3, y4); - const thisCopy = this.slice(thisStart, thisEnd); - const targetCopy = target.slice(start, end); - for (let i2 = 0; i2 < len; ++i2) { - if (thisCopy[i2] !== targetCopy[i2]) { - x3 = thisCopy[i2]; - y4 = targetCopy[i2]; - break; - } - } - if (x3 < y4) - return -1; - if (y4 < x3) - return 1; - return 0; - }; - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - if (buffer.length === 0) - return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length - 1; - } - if (byteOffset < 0) - byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) - return -1; - else - byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) - byteOffset = 0; - else - return -1; - } - if (typeof val === "string") { - val = Buffer2.from(val, encoding); - } - if (Buffer2.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); - } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - let indexSize = 1; - let arrLength = arr.length; - let valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read2(buf, i3) { - if (indexSize === 1) { - return buf[i3]; - } else { - return buf.readUInt16BE(i3 * indexSize); - } - } - let i2; - if (dir) { - let foundIndex = -1; - for (i2 = byteOffset; i2 < arrLength; i2++) { - if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) { - if (foundIndex === -1) - foundIndex = i2; - if (i2 - foundIndex + 1 === valLength) - return foundIndex * indexSize; - } else { - if (foundIndex !== -1) - i2 -= i2 - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) - byteOffset = arrLength - valLength; - for (i2 = byteOffset; i2 >= 0; i2--) { - let found = true; - for (let j2 = 0; j2 < valLength; j2++) { - if (read2(arr, i2 + j2) !== read2(val, j2)) { - found = false; - break; - } - } - if (found) - return i2; - } - } - return -1; - } - Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string2, offset, length2) { - offset = Number(offset) || 0; - const remaining = buf.length - offset; - if (!length2) { - length2 = remaining; - } else { - length2 = Number(length2); - if (length2 > remaining) { - length2 = remaining; - } - } - const strLen = string2.length; - if (length2 > strLen / 2) { - length2 = strLen / 2; - } - let i2; - for (i2 = 0; i2 < length2; ++i2) { - const parsed = parseInt(string2.substr(i2 * 2, 2), 16); - if (numberIsNaN(parsed)) - return i2; - buf[offset + i2] = parsed; - } - return i2; - } - function utf8Write(buf, string2, offset, length2) { - return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); - } - function asciiWrite(buf, string2, offset, length2) { - return blitBuffer(asciiToBytes(string2), buf, offset, length2); - } - function base64Write(buf, string2, offset, length2) { - return blitBuffer(base64ToBytes(string2), buf, offset, length2); - } - function ucs2Write(buf, string2, offset, length2) { - return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); - } - Buffer2.prototype.write = function write(string2, offset, length2, encoding) { - if (offset === void 0) { - encoding = "utf8"; - length2 = this.length; - offset = 0; - } else if (length2 === void 0 && typeof offset === "string") { - encoding = offset; - length2 = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length2)) { - length2 = length2 >>> 0; - if (encoding === void 0) - encoding = "utf8"; - } else { - encoding = length2; - length2 = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - const remaining = this.length - offset; - if (length2 === void 0 || length2 > remaining) - length2 = remaining; - if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) - encoding = "utf8"; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string2, offset, length2); - case "utf8": - case "utf-8": - return utf8Write(this, string2, offset, length2); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string2, offset, length2); - case "base64": - return base64Write(this, string2, offset, length2); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string2, offset, length2); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - Buffer2.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base642.fromByteArray(buf); - } else { - return base642.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - const res = []; - let i2 = start; - while (i2 < end) { - const firstByte = buf[i2]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i2 + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i2 + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i2 + 1]; - thirdByte = buf[i2 + 2]; - fourthByte = buf[i2 + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i2 += bytesPerSequence; - } - return decodeCodePointsArray(res); - } - var MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - let res = ""; - let i2 = 0; - while (i2 < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH) - ); - } - return res; - } - function asciiSlice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2] & 127); - } - return ret; - } - function latin1Slice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i2 = start; i2 < end; ++i2) { - ret += String.fromCharCode(buf[i2]); - } - return ret; - } - function hexSlice(buf, start, end) { - const len = buf.length; - if (!start || start < 0) - start = 0; - if (!end || end < 0 || end > len) - end = len; - let out = ""; - for (let i2 = start; i2 < end; ++i2) { - out += hexSliceLookupTable[buf[i2]]; - } - return out; - } - function utf16leSlice(buf, start, end) { - const bytes = buf.slice(start, end); - let res = ""; - for (let i2 = 0; i2 < bytes.length - 1; i2 += 2) { - res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256); - } - return res; - } - Buffer2.prototype.slice = function slice(start, end) { - const len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) - start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) - end = 0; - } else if (end > len) { - end = len; - } - if (end < start) - end = start; - const newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer2.prototype); - return newBuf; - }; - function checkOffset(offset, ext, length2) { - if (offset % 1 !== 0 || offset < 0) - throw new RangeError("offset is not uint"); - if (offset + ext > length2) - throw new RangeError("Trying to access beyond buffer length"); - } - Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - return val; - }; - Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength2, this.length); - } - let val = this[offset + --byteLength2]; - let mul = 1; - while (byteLength2 > 0 && (mul *= 256)) { - val += this[offset + --byteLength2] * mul; - } - return val; - }; - Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - return this[offset]; - }; - Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; - }; - Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; - const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; - return BigInt(lo) + (BigInt(hi) << BigInt(32)); - }); - Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; - return (BigInt(hi) << BigInt(32)) + BigInt(lo); - }); - Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i2 = 0; - while (++i2 < byteLength2 && (mul *= 256)) { - val += this[offset + i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let i2 = byteLength2; - let mul = 1; - let val = this[offset + --i2]; - while (i2 > 0 && (mul *= 256)) { - val += this[offset + --i2] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) - return this[offset]; - return (255 - this[offset] + 1) * -1; - }; - Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - const val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - const val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); - }); - Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = (first << 24) + // Overflow - this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); - }); - Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); - }; - Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); - }; - Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); - }; - Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); - }; - function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer2.isBuffer(buf)) - throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) - throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - } - Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let mul = 1; - let i2 = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let i2 = byteLength2 - 1; - let mul = 1; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - this[offset + i2] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 255, 0); - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - function wrtBigUInt64LE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - return offset; - } - function wrtBigUInt64BE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset + 7] = lo; - lo = lo >> 8; - buf[offset + 6] = lo; - lo = lo >> 8; - buf[offset + 5] = lo; - lo = lo >> 8; - buf[offset + 4] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset + 3] = hi; - hi = hi >> 8; - buf[offset + 2] = hi; - hi = hi >> 8; - buf[offset + 1] = hi; - hi = hi >> 8; - buf[offset] = hi; - return offset + 8; - } - Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i2 = 0; - let mul = 1; - let sub = 0; - this[offset] = value & 255; - while (++i2 < byteLength2 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i2 = byteLength2 - 1; - let mul = 1; - let sub = 0; - this[offset + i2] = value & 255; - while (--i2 >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) { - sub = 1; - } - this[offset + i2] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 127, -128); - if (value < 0) - value = 255 + value + 1; - this[offset] = value & 255; - return offset + 1; - }; - Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; - }; - Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - if (value < 0) - value = 4294967295 + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - if (offset < 0) - throw new RangeError("Index out of range"); - } - function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); - }; - function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; - Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; - Buffer2.prototype.copy = function copy(target, targetStart, start, end) { - if (!Buffer2.isBuffer(target)) - throw new TypeError("argument should be a Buffer"); - if (!start) - start = 0; - if (!end && end !== 0) - end = this.length; - if (targetStart >= target.length) - targetStart = target.length; - if (!targetStart) - targetStart = 0; - if (end > 0 && end < start) - end = start; - if (end === start) - return 0; - if (target.length === 0 || this.length === 0) - return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) - throw new RangeError("Index out of range"); - if (end < 0) - throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) - end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - const len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); - } - return len; - }; - Buffer2.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - const code2 = val.charCodeAt(0); - if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { - val = code2; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) - val = 0; - let i2; - if (typeof val === "number") { - for (i2 = start; i2 < end; ++i2) { - this[i2] = val; - } - } else { - const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); - const len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i2 = 0; i2 < end - start; ++i2) { - this[i2 + start] = bytes[i2 % len]; - } - } - return this; - }; - var errors = {}; - function E4(sym, getMessage, Base) { - errors[sym] = class NodeError extends Base { - constructor() { - super(); - Object.defineProperty(this, "message", { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }); - this.name = `${this.name} [${sym}]`; - this.stack; - delete this.name; - } - get code() { - return sym; - } - set code(value) { - Object.defineProperty(this, "code", { - configurable: true, - enumerable: true, - value, - writable: true - }); - } - toString() { - return `${this.name} [${sym}]: ${this.message}`; - } - }; - } - E4( - "ERR_BUFFER_OUT_OF_BOUNDS", - function(name2) { - if (name2) { - return `${name2} is outside of buffer bounds`; - } - return "Attempt to access memory outside buffer bounds"; - }, - RangeError - ); - E4( - "ERR_INVALID_ARG_TYPE", - function(name2, actual) { - return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; - }, - TypeError - ); - E4( - "ERR_OUT_OF_RANGE", - function(str, range, input) { - let msg = `The value of "${str}" is out of range.`; - let received = input; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received); - } - received += "n"; - } - msg += ` It must be ${range}. Received ${received}`; - return msg; - }, - RangeError - ); - function addNumericalSeparator(val) { - let res = ""; - let i2 = val.length; - const start = val[0] === "-" ? 1 : 0; - for (; i2 >= start + 4; i2 -= 3) { - res = `_${val.slice(i2 - 3, i2)}${res}`; - } - return `${val.slice(0, i2)}${res}`; - } - function checkBounds(buf, offset, byteLength2) { - validateNumber(offset, "offset"); - if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { - boundsError(offset, buf.length - (byteLength2 + 1)); - } - } - function checkIntBI(value, min, max, buf, offset, byteLength2) { - if (value > max || value < min) { - const n3 = typeof min === "bigint" ? "n" : ""; - let range; - if (byteLength2 > 3) { - if (min === 0 || min === BigInt(0)) { - range = `>= 0${n3} and < 2${n3} ** ${(byteLength2 + 1) * 8}${n3}`; - } else { - range = `>= -(2${n3} ** ${(byteLength2 + 1) * 8 - 1}${n3}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n3}`; - } - } else { - range = `>= ${min}${n3} and <= ${max}${n3}`; - } - throw new errors.ERR_OUT_OF_RANGE("value", range, value); - } - checkBounds(buf, offset, byteLength2); - } - function validateNumber(value, name2) { - if (typeof value !== "number") { - throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value); - } - } - function boundsError(value, length2, type) { - if (Math.floor(value) !== value) { - validateNumber(value, type); - throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); - } - if (length2 < 0) { - throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); - } - throw new errors.ERR_OUT_OF_RANGE( - type || "offset", - `>= ${type ? 1 : 0} and <= ${length2}`, - value - ); - } - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) - return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } - function utf8ToBytes(string2, units) { - units = units || Infinity; - let codePoint; - const length2 = string2.length; - let leadSurrogate = null; - const bytes = []; - for (let i2 = 0; i2 < length2; ++i2) { - codePoint = string2.charCodeAt(i2); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } else if (i2 + 1 === length2) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) - break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) - break; - bytes.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) - break; - bytes.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) - break; - bytes.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; - } - function asciiToBytes(str) { - const byteArray = []; - for (let i2 = 0; i2 < str.length; ++i2) { - byteArray.push(str.charCodeAt(i2) & 255); - } - return byteArray; - } - function utf16leToBytes(str, units) { - let c4, hi, lo; - const byteArray = []; - for (let i2 = 0; i2 < str.length; ++i2) { - if ((units -= 2) < 0) - break; - c4 = str.charCodeAt(i2); - hi = c4 >> 8; - lo = c4 % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; - } - function base64ToBytes(str) { - return base642.toByteArray(base64clean(str)); - } - function blitBuffer(src2, dst, offset, length2) { - let i2; - for (i2 = 0; i2 < length2; ++i2) { - if (i2 + offset >= dst.length || i2 >= src2.length) - break; - dst[i2 + offset] = src2[i2]; - } - return i2; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - var hexSliceLookupTable = function() { - const alphabet2 = "0123456789abcdef"; - const table = new Array(256); - for (let i2 = 0; i2 < 16; ++i2) { - const i16 = i2 * 16; - for (let j2 = 0; j2 < 16; ++j2) { - table[i16 + j2] = alphabet2[i2] + alphabet2[j2]; - } - } - return table; - }(); - function defineBigIntMethod(fn) { - return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; - } - function BufferBigIntNotDefined() { - throw new Error("BigInt not supported"); - } - } -}); - -// (disabled):node_modules/util/util.js -var require_util = __commonJS({ - "(disabled):node_modules/util/util.js"() { - init_shim(); - } -}); - -// node_modules/readable-stream/lib/internal/streams/buffer_list.js -var require_buffer_list = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { - "use strict"; - init_shim(); - function ownKeys(object, enumerableOnly) { - var keys2 = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys2.push.apply(keys2, symbols); - } - return keys2; - } - function _objectSpread(target) { - for (var i2 = 1; i2 < arguments.length; i2++) { - var source = null != arguments[i2] ? arguments[i2] : {}; - i2 % 2 ? ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; - } - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i2 = 0; i2 < props.length; i2++) { - var descriptor = props[i2]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) - descriptor.writable = true; - Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) - _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { writable: false }); - return Constructor; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) - return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") - return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var _require = require_buffer2(); - var Buffer2 = _require.Buffer; - var _require2 = require_util(); - var inspect = _require2.inspect; - var custom = inspect && inspect.custom || "inspect"; - function copyBuffer(src2, target, offset) { - Buffer2.prototype.copy.call(src2, target, offset); - } - module2.exports = /* @__PURE__ */ function() { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } - _createClass(BufferList, [{ - key: "push", - value: function push(v2) { - var entry = { - data: v2, - next: null - }; - if (this.length > 0) - this.tail.next = entry; - else - this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v2) { - var entry = { - data: v2, - next: this.head - }; - if (this.length === 0) - this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) - return; - var ret = this.head.data; - if (this.length === 1) - this.head = this.tail = null; - else - this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear2() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s2) { - if (this.length === 0) - return ""; - var p3 = this.head; - var ret = "" + p3.data; - while (p3 = p3.next) - ret += s2 + p3.data; - return ret; - } - }, { - key: "concat", - value: function concat2(n3) { - if (this.length === 0) - return Buffer2.alloc(0); - var ret = Buffer2.allocUnsafe(n3 >>> 0); - var p3 = this.head; - var i2 = 0; - while (p3) { - copyBuffer(p3.data, ret, i2); - i2 += p3.data.length; - p3 = p3.next; - } - return ret; - } - // Consumes a specified amount of bytes or characters from the buffered data. - }, { - key: "consume", - value: function consume(n3, hasStrings) { - var ret; - if (n3 < this.head.data.length) { - ret = this.head.data.slice(0, n3); - this.head.data = this.head.data.slice(n3); - } else if (n3 === this.head.data.length) { - ret = this.shift(); - } else { - ret = hasStrings ? this._getString(n3) : this._getBuffer(n3); - } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } - // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n3) { - var p3 = this.head; - var c4 = 1; - var ret = p3.data; - n3 -= ret.length; - while (p3 = p3.next) { - var str = p3.data; - var nb = n3 > str.length ? str.length : n3; - if (nb === str.length) - ret += str; - else - ret += str.slice(0, n3); - n3 -= nb; - if (n3 === 0) { - if (nb === str.length) { - ++c4; - if (p3.next) - this.head = p3.next; - else - this.head = this.tail = null; - } else { - this.head = p3; - p3.data = str.slice(nb); - } - break; - } - ++c4; - } - this.length -= c4; - return ret; - } - // Consumes a specified amount of bytes from the buffered data. - }, { - key: "_getBuffer", - value: function _getBuffer(n3) { - var ret = Buffer2.allocUnsafe(n3); - var p3 = this.head; - var c4 = 1; - p3.data.copy(ret); - n3 -= p3.data.length; - while (p3 = p3.next) { - var buf = p3.data; - var nb = n3 > buf.length ? buf.length : n3; - buf.copy(ret, ret.length - n3, 0, nb); - n3 -= nb; - if (n3 === 0) { - if (nb === buf.length) { - ++c4; - if (p3.next) - this.head = p3.next; - else - this.head = this.tail = null; - } else { - this.head = p3; - p3.data = buf.slice(nb); - } - break; - } - ++c4; - } - this.length -= c4; - return ret; - } - // Make sure the linked list only shows the minimal necessary information. - }, { - key: custom, - value: function value(_4, options) { - return inspect(this, _objectSpread(_objectSpread({}, options), {}, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - return BufferList; - }(); - } -}); - -// node_modules/readable-stream/lib/internal/streams/destroy.js -var require_destroy = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { - "use strict"; - init_shim(); - function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - import_process.default.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - import_process.default.nextTick(emitErrorNT, this, err); - } - } - return this; - } - if (this._readableState) { - this._readableState.destroyed = true; - } - if (this._writableState) { - this._writableState.destroyed = true; - } - this._destroy(err || null, function(err2) { - if (!cb && err2) { - if (!_this._writableState) { - import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - import_process.default.nextTick(emitErrorAndCloseNT, _this, err2); - } else { - import_process.default.nextTick(emitCloseNT, _this); - } - } else if (cb) { - import_process.default.nextTick(emitCloseNT, _this); - cb(err2); - } else { - import_process.default.nextTick(emitCloseNT, _this); - } - }); - return this; - } - function emitErrorAndCloseNT(self2, err) { - emitErrorNT(self2, err); - emitCloseNT(self2); - } - function emitCloseNT(self2) { - if (self2._writableState && !self2._writableState.emitClose) - return; - if (self2._readableState && !self2._readableState.emitClose) - return; - self2.emit("close"); - } - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } - } - function emitErrorNT(self2, err) { - self2.emit("error", err); - } - function errorOrDestroy(stream, err) { - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) - stream.destroy(err); - else - stream.emit("error", err); - } - module2.exports = { - destroy, - undestroy, - errorOrDestroy - }; - } -}); - -// node_modules/readable-stream/errors-browser.js -var require_errors_browser = __commonJS({ - "node_modules/readable-stream/errors-browser.js"(exports2, module2) { - "use strict"; - init_shim(); - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; - } - var codes = {}; - function createErrorType(code2, message, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message === "string") { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - var NodeError = /* @__PURE__ */ function(_Base) { - _inheritsLoose(NodeError2, _Base); - function NodeError2(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - return NodeError2; - }(Base); - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code2; - codes[code2] = NodeError; - } - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function(i2) { - return String(i2); - }); - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } - } - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - function endsWith(str, search, this_len) { - if (this_len === void 0 || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - function includes(str, search, start) { - if (typeof start !== "number") { - start = 0; - } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } - } - createErrorType("ERR_INVALID_OPT_VALUE", function(name2, value) { - return 'The value "' + value + '" is invalid for option "' + name2 + '"'; - }, TypeError); - createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) { - var determiner; - if (typeof expected === "string" && startsWith(expected, "not ")) { - determiner = "must not be"; - expected = expected.replace(/^not /, ""); - } else { - determiner = "must be"; - } - var msg; - if (endsWith(name2, " argument")) { - msg = "The ".concat(name2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); - } else { - var type = includes(name2, ".") ? "property" : "argument"; - msg = 'The "'.concat(name2, '" ').concat(type, " ").concat(determiner, " ").concat(oneOf(expected, "type")); - } - msg += ". Received type ".concat(typeof actual); - return msg; - }, TypeError); - createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); - createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name2) { - return "The " + name2 + " method is not implemented"; - }); - createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); - createErrorType("ERR_STREAM_DESTROYED", function(name2) { - return "Cannot call " + name2 + " after a stream was destroyed"; - }); - createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); - createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); - createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); - createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); - createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { - return "Unknown encoding: " + arg; - }, TypeError); - createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); - module2.exports.codes = codes; - } -}); - -// node_modules/readable-stream/lib/internal/streams/state.js -var require_state = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { - "use strict"; - init_shim(); - var ERR_INVALID_OPT_VALUE = require_errors_browser().codes.ERR_INVALID_OPT_VALUE; - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } - function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name2 = isDuplex ? duplexKey : "highWaterMark"; - throw new ERR_INVALID_OPT_VALUE(name2, hwm); - } - return Math.floor(hwm); - } - return state.objectMode ? 16 : 16 * 1024; - } - module2.exports = { - getHighWaterMark - }; - } -}); - -// node_modules/inherits/inherits_browser.js -var require_inherits_browser = __commonJS({ - "node_modules/inherits/inherits_browser.js"(exports2, module2) { - init_shim(); - if (typeof Object.create === "function") { - module2.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; - } else { - module2.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() { - }; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - }; - } - } -}); - -// node_modules/util-deprecate/browser.js -var require_browser2 = __commonJS({ - "node_modules/util-deprecate/browser.js"(exports2, module2) { - init_shim(); - module2.exports = deprecate2; - function deprecate2(fn, msg) { - if (config("noDeprecation")) { - return fn; - } - var warned = false; - function deprecated() { - if (!warned) { - if (config("throwDeprecation")) { - throw new Error(msg); - } else if (config("traceDeprecation")) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - return deprecated; - } - function config(name2) { - try { - if (!global.localStorage) - return false; - } catch (_4) { - return false; - } - var val = global.localStorage[name2]; - if (null == val) - return false; - return String(val).toLowerCase() === "true"; - } - } -}); - -// node_modules/readable-stream/lib/_stream_writable.js -var require_stream_writable = __commonJS({ - "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Writable; - function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function() { - onCorkedFinish(_this, state); - }; - } - var Duplex; - Writable.WritableState = WritableState; - var internalUtil = { - deprecate: require_browser2() - }; - var Stream = require_stream_browser(); - var Buffer2 = require_buffer2().Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors_browser().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; - var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; - var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - var errorOrDestroy = destroyImpl.errorOrDestroy; - require_inherits_browser()(Writable, Stream); - function nop() { - } - function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") - isDuplex = stream instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) - this.objectMode = this.objectMode || !!options.writableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); - this.finalCalled = false; - this.needDrain = false; - this.ending = false; - this.ended = false; - this.finished = false; - this.destroyed = false; - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.length = 0; - this.writing = false; - this.corked = 0; - this.sync = true; - this.bufferProcessing = false; - this.onwrite = function(er) { - onwrite(stream, er); - }; - this.writecb = null; - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; - this.pendingcb = 0; - this.prefinished = false; - this.errorEmitted = false; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.bufferedRequestCount = 0; - this.corkedRequestsFree = new CorkedRequest(this); - } - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - (function() { - try { - Object.defineProperty(WritableState.prototype, "buffer", { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") - }); - } catch (_4) { - } - })(); - var realHasInstance; - if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) - return true; - if (this !== Writable) - return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance2(object) { - return object instanceof this; - }; - } - function Writable(options) { - Duplex = Duplex || require_stream_duplex(); - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) - return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); - this.writable = true; - if (options) { - if (typeof options.write === "function") - this._write = options.write; - if (typeof options.writev === "function") - this._writev = options.writev; - if (typeof options.destroy === "function") - this._destroy = options.destroy; - if (typeof options.final === "function") - this._final = options.final; - } - Stream.call(this); - } - Writable.prototype.pipe = function() { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); - errorOrDestroy(stream, er); - import_process.default.nextTick(cb, er); - } - function validChunk(stream, state, chunk, cb) { - var er; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== "string" && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); - } - if (er) { - errorOrDestroy(stream, er); - import_process.default.nextTick(cb, er); - return false; - } - return true; - } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer2.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (isBuf) - encoding = "buffer"; - else if (!encoding) - encoding = state.defaultEncoding; - if (typeof cb !== "function") - cb = nop; - if (state.ending) - writeAfterEnd(this, cb); - else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; - Writable.prototype.cork = function() { - this._writableState.corked++; - }; - Writable.prototype.uncork = function() { - var state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) - clearBuffer(this, state); - } - }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - if (typeof encoding === "string") - encoding = encoding.toLowerCase(); - if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) - throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - Object.defineProperty(Writable.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState && this._writableState.getBuffer(); - } - }); - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { - chunk = Buffer2.from(chunk, encoding); - } - return chunk; - } - Object.defineProperty(Writable.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.highWaterMark; - } - }); - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = "buffer"; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; - if (!ret) - state.needDrain = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk, - encoding, - isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - return ret; - } - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) - state.onwrite(new ERR_STREAM_DESTROYED("write")); - else if (writev) - stream._writev(chunk, state.onwrite); - else - stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) { - import_process.default.nextTick(cb, er); - import_process.default.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - finishMaybe(stream, state); - } - } - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== "function") - throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) - onwriteError(stream, state, sync, er, cb); - else { - var finished = needFinish(state) || stream.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - if (sync) { - import_process.default.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } - } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit("drain"); - } - } - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { - var l4 = state.bufferedRequestCount; - var buffer = new Array(l4); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) - allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, "", holder.finish); - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - if (state.writing) { - break; - } - } - if (entry === null) - state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); - }; - Writable.prototype._writev = null; - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (chunk !== null && chunk !== void 0) - this.write(chunk, encoding); - if (state.corked) { - state.corked = 1; - this.uncork(); - } - if (!state.ending) - endWritable(this, state, cb); - return this; - }; - Object.defineProperty(Writable.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.length; - } - }); - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - function callFinal(stream, state) { - stream._final(function(err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream, err); - } - state.prefinished = true; - stream.emit("prefinish"); - finishMaybe(stream, state); - }); - } - function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === "function" && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - import_process.default.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit("prefinish"); - } - } - } - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit("finish"); - if (state.autoDestroy) { - var rState = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - return need; - } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - import_process.default.nextTick(cb); - else - stream.once("finish", cb); - } - state.ended = true; - stream.writable = false; - } - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - state.corkedRequestsFree.next = corkReq; - } - Object.defineProperty(Writable.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._writableState === void 0) { - return false; - } - return this._writableState.destroyed; - }, - set: function set2(value) { - if (!this._writableState) { - return; - } - this._writableState.destroyed = value; - } - }); - Writable.prototype.destroy = destroyImpl.destroy; - Writable.prototype._undestroy = destroyImpl.undestroy; - Writable.prototype._destroy = function(err, cb) { - cb(err); - }; - } -}); - -// node_modules/readable-stream/lib/_stream_duplex.js -var require_stream_duplex = __commonJS({ - "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { - "use strict"; - init_shim(); - var objectKeys = Object.keys || function(obj) { - var keys3 = []; - for (var key in obj) - keys3.push(key); - return keys3; - }; - module2.exports = Duplex; - var Readable = require_stream_readable(); - var Writable = require_stream_writable(); - require_inherits_browser()(Duplex, Readable); - { - keys2 = objectKeys(Writable.prototype); - for (v2 = 0; v2 < keys2.length; v2++) { - method = keys2[v2]; - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; - } - } - var keys2; - var method; - var v2; - function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) - this.readable = false; - if (options.writable === false) - this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once("end", onend); - } - } - } - Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.length; - } - }); - function onend() { - if (this._writableState.ended) - return; - import_process.default.nextTick(onEndNT, this); - } - function onEndNT(self2) { - self2.end(); - } - Object.defineProperty(Duplex.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._readableState === void 0 || this._writableState === void 0) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set2(value) { - if (this._readableState === void 0 || this._writableState === void 0) { - return; - } - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - } -}); - -// node_modules/safe-buffer/index.js -var require_safe_buffer = __commonJS({ - "node_modules/safe-buffer/index.js"(exports2, module2) { - init_shim(); - var buffer = require_buffer2(); - var Buffer2 = buffer.Buffer; - function copyProps(src2, dst) { - for (var key in src2) { - dst[key] = src2[key]; - } - } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { - module2.exports = buffer; - } else { - copyProps(buffer, exports2); - exports2.Buffer = SafeBuffer; - } - function SafeBuffer(arg, encodingOrOffset, length2) { - return Buffer2(arg, encodingOrOffset, length2); - } - SafeBuffer.prototype = Object.create(Buffer2.prototype); - copyProps(Buffer2, SafeBuffer); - SafeBuffer.from = function(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer2(arg, encodingOrOffset, length2); - }; - SafeBuffer.alloc = function(size, fill, encoding) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer2(size); - if (fill !== void 0) { - if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf; - }; - SafeBuffer.allocUnsafe = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer2(size); - }; - SafeBuffer.allocUnsafeSlow = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; - } -}); - -// node_modules/string_decoder/lib/string_decoder.js -var require_string_decoder = __commonJS({ - "node_modules/string_decoder/lib/string_decoder.js"(exports2) { - "use strict"; - init_shim(); - var Buffer2 = require_safe_buffer().Buffer; - var isEncoding = Buffer2.isEncoding || function(encoding) { - encoding = "" + encoding; - switch (encoding && encoding.toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - case "raw": - return true; - default: - return false; - } - }; - function _normalizeEncoding(enc) { - if (!enc) - return "utf8"; - var retried; - while (true) { - switch (enc) { - case "utf8": - case "utf-8": - return "utf8"; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return "utf16le"; - case "latin1": - case "binary": - return "latin1"; - case "base64": - case "ascii": - case "hex": - return enc; - default: - if (retried) - return; - enc = ("" + enc).toLowerCase(); - retried = true; - } - } - } - function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) - throw new Error("Unknown encoding: " + enc); - return nenc || enc; - } - exports2.StringDecoder = StringDecoder; - function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case "utf16le": - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case "utf8": - this.fillLast = utf8FillLast; - nb = 4; - break; - case "base64": - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer2.allocUnsafe(nb); - } - StringDecoder.prototype.write = function(buf) { - if (buf.length === 0) - return ""; - var r; - var i2; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === void 0) - return ""; - i2 = this.lastNeed; - this.lastNeed = 0; - } else { - i2 = 0; - } - if (i2 < buf.length) - return r ? r + this.text(buf, i2) : this.text(buf, i2); - return r || ""; - }; - StringDecoder.prototype.end = utf8End; - StringDecoder.prototype.text = utf8Text; - StringDecoder.prototype.fillLast = function(buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; - }; - function utf8CheckByte(byte) { - if (byte <= 127) - return 0; - else if (byte >> 5 === 6) - return 2; - else if (byte >> 4 === 14) - return 3; - else if (byte >> 3 === 30) - return 4; - return byte >> 6 === 2 ? -1 : -2; - } - function utf8CheckIncomplete(self2, buf, i2) { - var j2 = buf.length - 1; - if (j2 < i2) - return 0; - var nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) - self2.lastNeed = nb - 1; - return nb; - } - if (--j2 < i2 || nb === -2) - return 0; - nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) - self2.lastNeed = nb - 2; - return nb; - } - if (--j2 < i2 || nb === -2) - return 0; - nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) - nb = 0; - else - self2.lastNeed = nb - 3; - } - return nb; - } - return 0; - } - function utf8CheckExtraBytes(self2, buf, p3) { - if ((buf[0] & 192) !== 128) { - self2.lastNeed = 0; - return "\uFFFD"; - } - if (self2.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 192) !== 128) { - self2.lastNeed = 1; - return "\uFFFD"; - } - if (self2.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 192) !== 128) { - self2.lastNeed = 2; - return "\uFFFD"; - } - } - } - } - function utf8FillLast(buf) { - var p3 = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p3); - if (r !== void 0) - return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p3, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p3, 0, buf.length); - this.lastNeed -= buf.length; - } - function utf8Text(buf, i2) { - var total = utf8CheckIncomplete(this, buf, i2); - if (!this.lastNeed) - return buf.toString("utf8", i2); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString("utf8", i2, end); - } - function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) - return r + "\uFFFD"; - return r; - } - function utf16Text(buf, i2) { - if ((buf.length - i2) % 2 === 0) { - var r = buf.toString("utf16le", i2); - if (r) { - var c4 = r.charCodeAt(r.length - 1); - if (c4 >= 55296 && c4 <= 56319) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString("utf16le", i2, buf.length - 1); - } - function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString("utf16le", 0, end); - } - return r; - } - function base64Text(buf, i2) { - var n3 = (buf.length - i2) % 3; - if (n3 === 0) - return buf.toString("base64", i2); - this.lastNeed = 3 - n3; - this.lastTotal = 3; - if (n3 === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString("base64", i2, buf.length - n3); - } - function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) - return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); - return r; - } - function simpleWrite(buf) { - return buf.toString(this.encoding); - } - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ""; - } - } -}); - -// node_modules/readable-stream/lib/internal/streams/end-of-stream.js -var require_end_of_stream = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { - "use strict"; - init_shim(); - var ERR_STREAM_PREMATURE_CLOSE = require_errors_browser().codes.ERR_STREAM_PREMATURE_CLOSE; - function once(callback) { - var called = false; - return function() { - if (called) - return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - callback.apply(this, args); - }; - } - function noop() { - } - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - function eos(stream, opts, callback) { - if (typeof opts === "function") - return eos(stream, null, opts); - if (!opts) - opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - var onlegacyfinish = function onlegacyfinish2() { - if (!stream.writable) - onfinish(); - }; - var writableEnded = stream._writableState && stream._writableState.finished; - var onfinish = function onfinish2() { - writable = false; - writableEnded = true; - if (!readable) - callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend2() { - readable = false; - readableEnded = true; - if (!writable) - callback.call(stream); - }; - var onerror = function onerror2(err) { - callback.call(stream, err); - }; - var onclose = function onclose2() { - var err; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) - err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) - err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - var onrequest = function onrequest2() { - stream.req.on("finish", onfinish); - }; - if (isRequest(stream)) { - stream.on("complete", onfinish); - stream.on("abort", onclose); - if (stream.req) - onrequest(); - else - stream.on("request", onrequest); - } else if (writable && !stream._writableState) { - stream.on("end", onlegacyfinish); - stream.on("close", onlegacyfinish); - } - stream.on("end", onend); - stream.on("finish", onfinish); - if (opts.error !== false) - stream.on("error", onerror); - stream.on("close", onclose); - return function() { - stream.removeListener("complete", onfinish); - stream.removeListener("abort", onclose); - stream.removeListener("request", onrequest); - if (stream.req) - stream.req.removeListener("finish", onfinish); - stream.removeListener("end", onlegacyfinish); - stream.removeListener("close", onlegacyfinish); - stream.removeListener("finish", onfinish); - stream.removeListener("end", onend); - stream.removeListener("error", onerror); - stream.removeListener("close", onclose); - }; - } - module2.exports = eos; - } -}); - -// node_modules/readable-stream/lib/internal/streams/async_iterator.js -var require_async_iterator = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { - "use strict"; - init_shim(); - var _Object$setPrototypeO; - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) - return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") - return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var finished = require_end_of_stream(); - var kLastResolve = Symbol("lastResolve"); - var kLastReject = Symbol("lastReject"); - var kError = Symbol("error"); - var kEnded = Symbol("ended"); - var kLastPromise = Symbol("lastPromise"); - var kHandlePromise = Symbol("handlePromise"); - var kStream = Symbol("stream"); - function createIterResult(value, done) { - return { - value, - done - }; - } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - if (resolve !== null) { - var data = iter[kStream].read(); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } - } - function onReadable(iter) { - import_process.default.nextTick(readAndResolve, iter); - } - function wrapForNext(lastPromise, iter) { - return function(resolve, reject) { - lastPromise.then(function() { - if (iter[kEnded]) { - resolve(createIterResult(void 0, true)); - return; - } - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } - var AsyncIteratorPrototype = Object.getPrototypeOf(function() { - }); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - next: function next() { - var _this = this; - var error = this[kError]; - if (error !== null) { - return Promise.reject(error); - } - if (this[kEnded]) { - return Promise.resolve(createIterResult(void 0, true)); - } - if (this[kStream].destroyed) { - return new Promise(function(resolve, reject) { - import_process.default.nextTick(function() { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(void 0, true)); - } - }); - }); - } - var lastPromise = this[kLastPromise]; - var promise; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - var data = this[kStream].read(); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - promise = new Promise(this[kHandlePromise]); - } - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - return new Promise(function(resolve, reject) { - _this2[kStream].destroy(null, function(err) { - if (err) { - reject(err); - return; - } - resolve(createIterResult(void 0, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) { - var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function(err) { - if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { - var reject = iterator[kLastReject]; - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - iterator[kError] = err; - return; - } - var resolve = iterator[kLastResolve]; - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(void 0, true)); - } - iterator[kEnded] = true; - }); - stream.on("readable", onReadable.bind(null, iterator)); - return iterator; - }; - module2.exports = createReadableStreamAsyncIterator; - } -}); - -// node_modules/readable-stream/lib/internal/streams/from-browser.js -var require_from_browser = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/from-browser.js"(exports2, module2) { - init_shim(); - module2.exports = function() { - throw new Error("Readable.from is not available in the browser"); - }; - } -}); - -// node_modules/readable-stream/lib/_stream_readable.js -var require_stream_readable = __commonJS({ - "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Readable; - var Duplex; - Readable.ReadableState = ReadableState; - var EE = require_events().EventEmitter; - var EElistenerCount = function EElistenerCount2(emitter, type) { - return emitter.listeners(type).length; - }; - var Stream = require_stream_browser(); - var Buffer2 = require_buffer2().Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var debugUtil = require_util(); - var debug; - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); - } else { - debug = function debug2() { - }; - } - var BufferList = require_buffer_list(); - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors_browser().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - var StringDecoder; - var createReadableStreamAsyncIterator; - var from3; - require_inherits_browser()(Readable, Stream); - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; - function prependListener(emitter, event, fn) { - if (typeof emitter.prependListener === "function") - return emitter.prependListener(event, fn); - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") - isDuplex = stream instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) - this.objectMode = this.objectMode || !!options.readableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - this.sync = true; - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.destroyed = false; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.awaitDrain = 0; - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require_string_decoder().StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { - Duplex = Duplex || require_stream_duplex(); - if (!(this instanceof Readable)) - return new Readable(options); - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); - this.readable = true; - if (options) { - if (typeof options.read === "function") - this._read = options.read; - if (typeof options.destroy === "function") - this._destroy = options.destroy; - } - Stream.call(this); - } - Object.defineProperty(Readable.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._readableState === void 0) { - return false; - } - return this._readableState.destroyed; - }, - set: function set2(value) { - if (!this._readableState) { - return; - } - this._readableState.destroyed = value; - } - }); - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - Readable.prototype._destroy = function(err, cb) { - cb(err); - }; - Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - if (!state.objectMode) { - if (typeof chunk === "string") { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer2.from(chunk, encoding); - encoding = ""; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; - Readable.prototype.unshift = function(chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug("readableAddChunk", chunk); - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) - er = chunkInvalid(state, chunk); - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state.endEmitted) - errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); - else - addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) - addChunk(stream, state, chunk, false); - else - maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit("data", chunk); - } else { - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) - state.buffer.unshift(chunk); - else - state.buffer.push(chunk); - if (state.needReadable) - emitReadable(stream); - } - maybeReadMore(stream, state); - } - function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); - } - return er; - } - Readable.prototype.isPaused = function() { - return this._readableState.flowing === false; - }; - Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require_string_decoder().StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; - this._readableState.encoding = this._readableState.decoder.encoding; - var p3 = this._readableState.buffer.head; - var content = ""; - while (p3 !== null) { - content += decoder.write(p3.data); - p3 = p3.next; - } - this._readableState.buffer.clear(); - if (content !== "") - this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; - var MAX_HWM = 1073741824; - function computeNewHighWaterMark(n3) { - if (n3 >= MAX_HWM) { - n3 = MAX_HWM; - } else { - n3--; - n3 |= n3 >>> 1; - n3 |= n3 >>> 2; - n3 |= n3 >>> 4; - n3 |= n3 >>> 8; - n3 |= n3 >>> 16; - n3++; - } - return n3; - } - function howMuchToRead(n3, state) { - if (n3 <= 0 || state.length === 0 && state.ended) - return 0; - if (state.objectMode) - return 1; - if (n3 !== n3) { - if (state.flowing && state.length) - return state.buffer.head.data.length; - else - return state.length; - } - if (n3 > state.highWaterMark) - state.highWaterMark = computeNewHighWaterMark(n3); - if (n3 <= state.length) - return n3; - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; - } - Readable.prototype.read = function(n3) { - debug("read", n3); - n3 = parseInt(n3, 10); - var state = this._readableState; - var nOrig = n3; - if (n3 !== 0) - state.emittedReadable = false; - if (n3 === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug("read: emitReadable", state.length, state.ended); - if (state.length === 0 && state.ended) - endReadable(this); - else - emitReadable(this); - return null; - } - n3 = howMuchToRead(n3, state); - if (n3 === 0 && state.ended) { - if (state.length === 0) - endReadable(this); - return null; - } - var doRead = state.needReadable; - debug("need readable", doRead); - if (state.length === 0 || state.length - n3 < state.highWaterMark) { - doRead = true; - debug("length less than watermark", doRead); - } - if (state.ended || state.reading) { - doRead = false; - debug("reading or ended", doRead); - } else if (doRead) { - debug("do read"); - state.reading = true; - state.sync = true; - if (state.length === 0) - state.needReadable = true; - this._read(state.highWaterMark); - state.sync = false; - if (!state.reading) - n3 = howMuchToRead(nOrig, state); - } - var ret; - if (n3 > 0) - ret = fromList(n3, state); - else - ret = null; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n3 = 0; - } else { - state.length -= n3; - state.awaitDrain = 0; - } - if (state.length === 0) { - if (!state.ended) - state.needReadable = true; - if (nOrig !== n3 && state.ended) - endReadable(this); - } - if (ret !== null) - this.emit("data", ret); - return ret; - }; - function onEofChunk(stream, state) { - debug("onEofChunk"); - if (state.ended) - return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - if (state.sync) { - emitReadable(stream); - } else { - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } - } - function emitReadable(stream) { - var state = stream._readableState; - debug("emitReadable", state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug("emitReadable", state.flowing); - state.emittedReadable = true; - import_process.default.nextTick(emitReadable_, stream); - } - } - function emitReadable_(stream) { - var state = stream._readableState; - debug("emitReadable_", state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit("readable"); - state.emittedReadable = false; - } - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); - } - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - import_process.default.nextTick(maybeReadMore_, stream, state); - } - } - function maybeReadMore_(stream, state) { - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug("maybeReadMore read 0"); - stream.read(0); - if (len === state.length) - break; - } - state.readingMore = false; - } - Readable.prototype._read = function(n3) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); - }; - Readable.prototype.pipe = function(dest, pipeOpts) { - var src2 = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== import_process.default.stdout && dest !== import_process.default.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) - import_process.default.nextTick(endFn); - else - src2.once("end", endFn); - dest.on("unpipe", onunpipe); - function onunpipe(readable, unpipeInfo) { - debug("onunpipe"); - if (readable === src2) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - function onend() { - debug("onend"); - dest.end(); - } - var ondrain = pipeOnDrain(src2); - dest.on("drain", ondrain); - var cleanedUp = false; - function cleanup() { - debug("cleanup"); - dest.removeListener("close", onclose); - dest.removeListener("finish", onfinish); - dest.removeListener("drain", ondrain); - dest.removeListener("error", onerror); - dest.removeListener("unpipe", onunpipe); - src2.removeListener("end", onend); - src2.removeListener("end", unpipe); - src2.removeListener("data", ondata); - cleanedUp = true; - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) - ondrain(); - } - src2.on("data", ondata); - function ondata(chunk) { - debug("ondata"); - var ret = dest.write(chunk); - debug("dest.write", ret); - if (ret === false) { - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug("false write response, pause", state.awaitDrain); - state.awaitDrain++; - } - src2.pause(); - } - } - function onerror(er) { - debug("onerror", er); - unpipe(); - dest.removeListener("error", onerror); - if (EElistenerCount(dest, "error") === 0) - errorOrDestroy(dest, er); - } - prependListener(dest, "error", onerror); - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); - } - dest.once("close", onclose); - function onfinish() { - debug("onfinish"); - dest.removeListener("close", onclose); - unpipe(); - } - dest.once("finish", onfinish); - function unpipe() { - debug("unpipe"); - src2.unpipe(dest); - } - dest.emit("pipe", src2); - if (!state.flowing) { - debug("pipe resume"); - src2.resume(); - } - return dest; - }; - function pipeOnDrain(src2) { - return function pipeOnDrainFunctionResult() { - var state = src2._readableState; - debug("pipeOnDrain", state.awaitDrain); - if (state.awaitDrain) - state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src2, "data")) { - state.flowing = true; - flow(src2); - } - }; - } - Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; - if (state.pipesCount === 0) - return this; - if (state.pipesCount === 1) { - if (dest && dest !== state.pipes) - return this; - if (!dest) - dest = state.pipes; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) - dest.emit("unpipe", this, unpipeInfo); - return this; - } - if (!dest) { - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - for (var i2 = 0; i2 < len; i2++) - dests[i2].emit("unpipe", this, { - hasUnpiped: false - }); - return this; - } - var index = indexOf(state.pipes, dest); - if (index === -1) - return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - dest.emit("unpipe", this, unpipeInfo); - return this; - }; - Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - if (ev === "data") { - state.readableListening = this.listenerCount("readable") > 0; - if (state.flowing !== false) - this.resume(); - } else if (ev === "readable") { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug("on readable", state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - import_process.default.nextTick(nReadingNextTick, this); - } - } - } - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - Readable.prototype.removeListener = function(ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - if (ev === "readable") { - import_process.default.nextTick(updateReadableListening, this); - } - return res; - }; - Readable.prototype.removeAllListeners = function(ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === "readable" || ev === void 0) { - import_process.default.nextTick(updateReadableListening, this); - } - return res; - }; - function updateReadableListening(self2) { - var state = self2._readableState; - state.readableListening = self2.listenerCount("readable") > 0; - if (state.resumeScheduled && !state.paused) { - state.flowing = true; - } else if (self2.listenerCount("data") > 0) { - self2.resume(); - } - } - function nReadingNextTick(self2) { - debug("readable nexttick read 0"); - self2.read(0); - } - Readable.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug("resume"); - state.flowing = !state.readableListening; - resume(this, state); - } - state.paused = false; - return this; - }; - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - import_process.default.nextTick(resume_, stream, state); - } - } - function resume_(stream, state) { - debug("resume", state.reading); - if (!state.reading) { - stream.read(0); - } - state.resumeScheduled = false; - stream.emit("resume"); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); - } - Readable.prototype.pause = function() { - debug("call pause flowing=%j", this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug("pause"); - this._readableState.flowing = false; - this.emit("pause"); - } - this._readableState.paused = true; - return this; - }; - function flow(stream) { - var state = stream._readableState; - debug("flow", state.flowing); - while (state.flowing && stream.read() !== null) - ; - } - Readable.prototype.wrap = function(stream) { - var _this = this; - var state = this._readableState; - var paused = false; - stream.on("end", function() { - debug("wrapped end"); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - _this.push(chunk); - } - _this.push(null); - }); - stream.on("data", function(chunk) { - debug("wrapped data"); - if (state.decoder) - chunk = state.decoder.write(chunk); - if (state.objectMode && (chunk === null || chunk === void 0)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - for (var i2 in stream) { - if (this[i2] === void 0 && typeof stream[i2] === "function") { - this[i2] = /* @__PURE__ */ function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i2); - } - } - for (var n3 = 0; n3 < kProxyEvents.length; n3++) { - stream.on(kProxyEvents[n3], this.emit.bind(this, kProxyEvents[n3])); - } - this._read = function(n4) { - debug("wrapped _read", n4); - if (paused) { - paused = false; - stream.resume(); - } - }; - return this; - }; - if (typeof Symbol === "function") { - Readable.prototype[Symbol.asyncIterator] = function() { - if (createReadableStreamAsyncIterator === void 0) { - createReadableStreamAsyncIterator = require_async_iterator(); - } - return createReadableStreamAsyncIterator(this); - }; - } - Object.defineProperty(Readable.prototype, "readableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable.prototype, "readableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable.prototype, "readableFlowing", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.flowing; - }, - set: function set2(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); - Readable._fromList = fromList; - Object.defineProperty(Readable.prototype, "readableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.length; - } - }); - function fromList(n3, state) { - if (state.length === 0) - return null; - var ret; - if (state.objectMode) - ret = state.buffer.shift(); - else if (!n3 || n3 >= state.length) { - if (state.decoder) - ret = state.buffer.join(""); - else if (state.buffer.length === 1) - ret = state.buffer.first(); - else - ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - ret = state.buffer.consume(n3, state.decoder); - } - return ret; - } - function endReadable(stream) { - var state = stream._readableState; - debug("endReadable", state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - import_process.default.nextTick(endReadableNT, state, stream); - } - } - function endReadableNT(state, stream) { - debug("endReadableNT", state.endEmitted, state.length); - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit("end"); - if (state.autoDestroy) { - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } - } - if (typeof Symbol === "function") { - Readable.from = function(iterable, opts) { - if (from3 === void 0) { - from3 = require_from_browser(); - } - return from3(Readable, iterable, opts); - }; - } - function indexOf(xs, x3) { - for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { - if (xs[i2] === x3) - return i2; - } - return -1; - } - } -}); - -// node_modules/readable-stream/lib/_stream_transform.js -var require_stream_transform = __commonJS({ - "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Transform; - var _require$codes = require_errors_browser().codes; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; - var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - var Duplex = require_stream_duplex(); - require_inherits_browser()(Transform, Duplex); - function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (cb === null) { - return this.emit("error", new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data != null) - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } - } - function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - this._readableState.needReadable = true; - this._readableState.sync = false; - if (options) { - if (typeof options.transform === "function") - this._transform = options.transform; - if (typeof options.flush === "function") - this._flush = options.flush; - } - this.on("prefinish", prefinish); - } - function prefinish() { - var _this = this; - if (typeof this._flush === "function" && !this._readableState.destroyed) { - this._flush(function(er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } - } - Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - Transform.prototype._transform = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); - }; - Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } - }; - Transform.prototype._read = function(n3) { - var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - ts.needTransform = true; - } - }; - Transform.prototype._destroy = function(err, cb) { - Duplex.prototype._destroy.call(this, err, function(err2) { - cb(err2); - }); - }; - function done(stream, er, data) { - if (er) - return stream.emit("error", er); - if (data != null) - stream.push(data); - if (stream._writableState.length) - throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) - throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } - } -}); - -// node_modules/readable-stream/lib/_stream_passthrough.js -var require_stream_passthrough = __commonJS({ - "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = PassThrough; - var Transform = require_stream_transform(); - require_inherits_browser()(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - Transform.call(this, options); - } - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); - }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { - "use strict"; - init_shim(); - var eos; - function once(callback) { - var called = false; - return function() { - if (called) - return; - called = true; - callback.apply(void 0, arguments); - }; - } - var _require$codes = require_errors_browser().codes; - var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - function noop(err) { - if (err) - throw err; - } - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on("close", function() { - closed = true; - }); - if (eos === void 0) - eos = require_end_of_stream(); - eos(stream, { - readable: reading, - writable: writing - }, function(err) { - if (err) - return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function(err) { - if (closed) - return; - if (destroyed) - return; - destroyed = true; - if (isRequest(stream)) - return stream.abort(); - if (typeof stream.destroy === "function") - return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED("pipe")); - }; - } - function call(fn) { - fn(); - } - function pipe(from3, to) { - return from3.pipe(to); - } - function popCallback(streams) { - if (!streams.length) - return noop; - if (typeof streams[streams.length - 1] !== "function") - return noop; - return streams.pop(); - } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) - streams = streams[0]; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS("streams"); - } - var error; - var destroys = streams.map(function(stream, i2) { - var reading = i2 < streams.length - 1; - var writing = i2 > 0; - return destroyer(stream, reading, writing, function(err) { - if (!error) - error = err; - if (err) - destroys.forEach(call); - if (reading) - return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } - module2.exports = pipeline; - } -}); - -// node_modules/readable-stream/readable-browser.js -var require_readable_browser = __commonJS({ - "node_modules/readable-stream/readable-browser.js"(exports2, module2) { - init_shim(); - exports2 = module2.exports = require_stream_readable(); - exports2.Stream = exports2; - exports2.Readable = exports2; - exports2.Writable = require_stream_writable(); - exports2.Duplex = require_stream_duplex(); - exports2.Transform = require_stream_transform(); - exports2.PassThrough = require_stream_passthrough(); - exports2.finished = require_end_of_stream(); - exports2.pipeline = require_pipeline(); - } -}); - -// node_modules/keccak/lib/api/keccak.js -var require_keccak = __commonJS({ - "node_modules/keccak/lib/api/keccak.js"(exports2, module2) { - init_shim(); - var { Transform } = require_readable_browser(); - module2.exports = (KeccakState) => class Keccak extends Transform { - constructor(rate, capacity, delimitedSuffix, hashBitLength, options) { - super(options); - this._rate = rate; - this._capacity = capacity; - this._delimitedSuffix = delimitedSuffix; - this._hashBitLength = hashBitLength; - this._options = options; - this._state = new KeccakState(); - this._state.initialize(rate, capacity); - this._finalized = false; - } - _transform(chunk, encoding, callback) { - let error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - callback(error); - } - _flush(callback) { - let error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } - callback(error); - } - update(data, encoding) { - if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") - throw new TypeError("Data must be a string or a buffer"); - if (this._finalized) - throw new Error("Digest already called"); - if (!import_buffer.Buffer.isBuffer(data)) - data = import_buffer.Buffer.from(data, encoding); - this._state.absorb(data); - return this; - } - digest(encoding) { - if (this._finalized) - throw new Error("Digest already called"); - this._finalized = true; - if (this._delimitedSuffix) - this._state.absorbLastFewBits(this._delimitedSuffix); - let digest2 = this._state.squeeze(this._hashBitLength / 8); - if (encoding !== void 0) - digest2 = digest2.toString(encoding); - this._resetState(); - return digest2; - } - // remove result from memory - _resetState() { - this._state.initialize(this._rate, this._capacity); - return this; - } - // because sometimes we need hash right now and little later - _clone() { - const clone2 = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options); - this._state.copy(clone2._state); - clone2._finalized = this._finalized; - return clone2; - } - }; - } -}); - -// node_modules/keccak/lib/api/shake.js -var require_shake = __commonJS({ - "node_modules/keccak/lib/api/shake.js"(exports2, module2) { - init_shim(); - var { Transform } = require_readable_browser(); - module2.exports = (KeccakState) => class Shake extends Transform { - constructor(rate, capacity, delimitedSuffix, options) { - super(options); - this._rate = rate; - this._capacity = capacity; - this._delimitedSuffix = delimitedSuffix; - this._options = options; - this._state = new KeccakState(); - this._state.initialize(rate, capacity); - this._finalized = false; - } - _transform(chunk, encoding, callback) { - let error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - callback(error); - } - _flush() { - } - _read(size) { - this.push(this.squeeze(size)); - } - update(data, encoding) { - if (!import_buffer.Buffer.isBuffer(data) && typeof data !== "string") - throw new TypeError("Data must be a string or a buffer"); - if (this._finalized) - throw new Error("Squeeze already called"); - if (!import_buffer.Buffer.isBuffer(data)) - data = import_buffer.Buffer.from(data, encoding); - this._state.absorb(data); - return this; - } - squeeze(dataByteLength, encoding) { - if (!this._finalized) { - this._finalized = true; - this._state.absorbLastFewBits(this._delimitedSuffix); - } - let data = this._state.squeeze(dataByteLength); - if (encoding !== void 0) - data = data.toString(encoding); - return data; - } - _resetState() { - this._state.initialize(this._rate, this._capacity); - return this; - } - _clone() { - const clone2 = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options); - this._state.copy(clone2._state); - clone2._finalized = this._finalized; - return clone2; - } - }; - } -}); - -// node_modules/keccak/lib/api/index.js -var require_api = __commonJS({ - "node_modules/keccak/lib/api/index.js"(exports2, module2) { - init_shim(); - var createKeccak = require_keccak(); - var createShake = require_shake(); - module2.exports = function(KeccakState) { - const Keccak = createKeccak(KeccakState); - const Shake = createShake(KeccakState); - return function(algorithm, options) { - const hash = typeof algorithm === "string" ? algorithm.toLowerCase() : algorithm; - switch (hash) { - case "keccak224": - return new Keccak(1152, 448, null, 224, options); - case "keccak256": - return new Keccak(1088, 512, null, 256, options); - case "keccak384": - return new Keccak(832, 768, null, 384, options); - case "keccak512": - return new Keccak(576, 1024, null, 512, options); - case "sha3-224": - return new Keccak(1152, 448, 6, 224, options); - case "sha3-256": - return new Keccak(1088, 512, 6, 256, options); - case "sha3-384": - return new Keccak(832, 768, 6, 384, options); - case "sha3-512": - return new Keccak(576, 1024, 6, 512, options); - case "shake128": - return new Shake(1344, 256, 31, options); - case "shake256": - return new Shake(1088, 512, 31, options); - default: - throw new Error("Invald algorithm: " + algorithm); - } - }; - }; - } -}); - -// node_modules/keccak/lib/keccak-state-unroll.js -var require_keccak_state_unroll = __commonJS({ - "node_modules/keccak/lib/keccak-state-unroll.js"(exports2) { - init_shim(); - var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; - exports2.p1600 = function(s2) { - for (let round = 0; round < 24; ++round) { - const lo0 = s2[0] ^ s2[10] ^ s2[20] ^ s2[30] ^ s2[40]; - const hi0 = s2[1] ^ s2[11] ^ s2[21] ^ s2[31] ^ s2[41]; - const lo1 = s2[2] ^ s2[12] ^ s2[22] ^ s2[32] ^ s2[42]; - const hi1 = s2[3] ^ s2[13] ^ s2[23] ^ s2[33] ^ s2[43]; - const lo2 = s2[4] ^ s2[14] ^ s2[24] ^ s2[34] ^ s2[44]; - const hi2 = s2[5] ^ s2[15] ^ s2[25] ^ s2[35] ^ s2[45]; - const lo3 = s2[6] ^ s2[16] ^ s2[26] ^ s2[36] ^ s2[46]; - const hi3 = s2[7] ^ s2[17] ^ s2[27] ^ s2[37] ^ s2[47]; - const lo4 = s2[8] ^ s2[18] ^ s2[28] ^ s2[38] ^ s2[48]; - const hi4 = s2[9] ^ s2[19] ^ s2[29] ^ s2[39] ^ s2[49]; - let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31); - let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31); - const t1slo0 = s2[0] ^ lo; - const t1shi0 = s2[1] ^ hi; - const t1slo5 = s2[10] ^ lo; - const t1shi5 = s2[11] ^ hi; - const t1slo10 = s2[20] ^ lo; - const t1shi10 = s2[21] ^ hi; - const t1slo15 = s2[30] ^ lo; - const t1shi15 = s2[31] ^ hi; - const t1slo20 = s2[40] ^ lo; - const t1shi20 = s2[41] ^ hi; - lo = lo0 ^ (lo2 << 1 | hi2 >>> 31); - hi = hi0 ^ (hi2 << 1 | lo2 >>> 31); - const t1slo1 = s2[2] ^ lo; - const t1shi1 = s2[3] ^ hi; - const t1slo6 = s2[12] ^ lo; - const t1shi6 = s2[13] ^ hi; - const t1slo11 = s2[22] ^ lo; - const t1shi11 = s2[23] ^ hi; - const t1slo16 = s2[32] ^ lo; - const t1shi16 = s2[33] ^ hi; - const t1slo21 = s2[42] ^ lo; - const t1shi21 = s2[43] ^ hi; - lo = lo1 ^ (lo3 << 1 | hi3 >>> 31); - hi = hi1 ^ (hi3 << 1 | lo3 >>> 31); - const t1slo2 = s2[4] ^ lo; - const t1shi2 = s2[5] ^ hi; - const t1slo7 = s2[14] ^ lo; - const t1shi7 = s2[15] ^ hi; - const t1slo12 = s2[24] ^ lo; - const t1shi12 = s2[25] ^ hi; - const t1slo17 = s2[34] ^ lo; - const t1shi17 = s2[35] ^ hi; - const t1slo22 = s2[44] ^ lo; - const t1shi22 = s2[45] ^ hi; - lo = lo2 ^ (lo4 << 1 | hi4 >>> 31); - hi = hi2 ^ (hi4 << 1 | lo4 >>> 31); - const t1slo3 = s2[6] ^ lo; - const t1shi3 = s2[7] ^ hi; - const t1slo8 = s2[16] ^ lo; - const t1shi8 = s2[17] ^ hi; - const t1slo13 = s2[26] ^ lo; - const t1shi13 = s2[27] ^ hi; - const t1slo18 = s2[36] ^ lo; - const t1shi18 = s2[37] ^ hi; - const t1slo23 = s2[46] ^ lo; - const t1shi23 = s2[47] ^ hi; - lo = lo3 ^ (lo0 << 1 | hi0 >>> 31); - hi = hi3 ^ (hi0 << 1 | lo0 >>> 31); - const t1slo4 = s2[8] ^ lo; - const t1shi4 = s2[9] ^ hi; - const t1slo9 = s2[18] ^ lo; - const t1shi9 = s2[19] ^ hi; - const t1slo14 = s2[28] ^ lo; - const t1shi14 = s2[29] ^ hi; - const t1slo19 = s2[38] ^ lo; - const t1shi19 = s2[39] ^ hi; - const t1slo24 = s2[48] ^ lo; - const t1shi24 = s2[49] ^ hi; - const t2slo0 = t1slo0; - const t2shi0 = t1shi0; - const t2slo16 = t1shi5 << 4 | t1slo5 >>> 28; - const t2shi16 = t1slo5 << 4 | t1shi5 >>> 28; - const t2slo7 = t1slo10 << 3 | t1shi10 >>> 29; - const t2shi7 = t1shi10 << 3 | t1slo10 >>> 29; - const t2slo23 = t1shi15 << 9 | t1slo15 >>> 23; - const t2shi23 = t1slo15 << 9 | t1shi15 >>> 23; - const t2slo14 = t1slo20 << 18 | t1shi20 >>> 14; - const t2shi14 = t1shi20 << 18 | t1slo20 >>> 14; - const t2slo10 = t1slo1 << 1 | t1shi1 >>> 31; - const t2shi10 = t1shi1 << 1 | t1slo1 >>> 31; - const t2slo1 = t1shi6 << 12 | t1slo6 >>> 20; - const t2shi1 = t1slo6 << 12 | t1shi6 >>> 20; - const t2slo17 = t1slo11 << 10 | t1shi11 >>> 22; - const t2shi17 = t1shi11 << 10 | t1slo11 >>> 22; - const t2slo8 = t1shi16 << 13 | t1slo16 >>> 19; - const t2shi8 = t1slo16 << 13 | t1shi16 >>> 19; - const t2slo24 = t1slo21 << 2 | t1shi21 >>> 30; - const t2shi24 = t1shi21 << 2 | t1slo21 >>> 30; - const t2slo20 = t1shi2 << 30 | t1slo2 >>> 2; - const t2shi20 = t1slo2 << 30 | t1shi2 >>> 2; - const t2slo11 = t1slo7 << 6 | t1shi7 >>> 26; - const t2shi11 = t1shi7 << 6 | t1slo7 >>> 26; - const t2slo2 = t1shi12 << 11 | t1slo12 >>> 21; - const t2shi2 = t1slo12 << 11 | t1shi12 >>> 21; - const t2slo18 = t1slo17 << 15 | t1shi17 >>> 17; - const t2shi18 = t1shi17 << 15 | t1slo17 >>> 17; - const t2slo9 = t1shi22 << 29 | t1slo22 >>> 3; - const t2shi9 = t1slo22 << 29 | t1shi22 >>> 3; - const t2slo5 = t1slo3 << 28 | t1shi3 >>> 4; - const t2shi5 = t1shi3 << 28 | t1slo3 >>> 4; - const t2slo21 = t1shi8 << 23 | t1slo8 >>> 9; - const t2shi21 = t1slo8 << 23 | t1shi8 >>> 9; - const t2slo12 = t1slo13 << 25 | t1shi13 >>> 7; - const t2shi12 = t1shi13 << 25 | t1slo13 >>> 7; - const t2slo3 = t1slo18 << 21 | t1shi18 >>> 11; - const t2shi3 = t1shi18 << 21 | t1slo18 >>> 11; - const t2slo19 = t1shi23 << 24 | t1slo23 >>> 8; - const t2shi19 = t1slo23 << 24 | t1shi23 >>> 8; - const t2slo15 = t1slo4 << 27 | t1shi4 >>> 5; - const t2shi15 = t1shi4 << 27 | t1slo4 >>> 5; - const t2slo6 = t1slo9 << 20 | t1shi9 >>> 12; - const t2shi6 = t1shi9 << 20 | t1slo9 >>> 12; - const t2slo22 = t1shi14 << 7 | t1slo14 >>> 25; - const t2shi22 = t1slo14 << 7 | t1shi14 >>> 25; - const t2slo13 = t1slo19 << 8 | t1shi19 >>> 24; - const t2shi13 = t1shi19 << 8 | t1slo19 >>> 24; - const t2slo4 = t1slo24 << 14 | t1shi24 >>> 18; - const t2shi4 = t1shi24 << 14 | t1slo24 >>> 18; - s2[0] = t2slo0 ^ ~t2slo1 & t2slo2; - s2[1] = t2shi0 ^ ~t2shi1 & t2shi2; - s2[10] = t2slo5 ^ ~t2slo6 & t2slo7; - s2[11] = t2shi5 ^ ~t2shi6 & t2shi7; - s2[20] = t2slo10 ^ ~t2slo11 & t2slo12; - s2[21] = t2shi10 ^ ~t2shi11 & t2shi12; - s2[30] = t2slo15 ^ ~t2slo16 & t2slo17; - s2[31] = t2shi15 ^ ~t2shi16 & t2shi17; - s2[40] = t2slo20 ^ ~t2slo21 & t2slo22; - s2[41] = t2shi20 ^ ~t2shi21 & t2shi22; - s2[2] = t2slo1 ^ ~t2slo2 & t2slo3; - s2[3] = t2shi1 ^ ~t2shi2 & t2shi3; - s2[12] = t2slo6 ^ ~t2slo7 & t2slo8; - s2[13] = t2shi6 ^ ~t2shi7 & t2shi8; - s2[22] = t2slo11 ^ ~t2slo12 & t2slo13; - s2[23] = t2shi11 ^ ~t2shi12 & t2shi13; - s2[32] = t2slo16 ^ ~t2slo17 & t2slo18; - s2[33] = t2shi16 ^ ~t2shi17 & t2shi18; - s2[42] = t2slo21 ^ ~t2slo22 & t2slo23; - s2[43] = t2shi21 ^ ~t2shi22 & t2shi23; - s2[4] = t2slo2 ^ ~t2slo3 & t2slo4; - s2[5] = t2shi2 ^ ~t2shi3 & t2shi4; - s2[14] = t2slo7 ^ ~t2slo8 & t2slo9; - s2[15] = t2shi7 ^ ~t2shi8 & t2shi9; - s2[24] = t2slo12 ^ ~t2slo13 & t2slo14; - s2[25] = t2shi12 ^ ~t2shi13 & t2shi14; - s2[34] = t2slo17 ^ ~t2slo18 & t2slo19; - s2[35] = t2shi17 ^ ~t2shi18 & t2shi19; - s2[44] = t2slo22 ^ ~t2slo23 & t2slo24; - s2[45] = t2shi22 ^ ~t2shi23 & t2shi24; - s2[6] = t2slo3 ^ ~t2slo4 & t2slo0; - s2[7] = t2shi3 ^ ~t2shi4 & t2shi0; - s2[16] = t2slo8 ^ ~t2slo9 & t2slo5; - s2[17] = t2shi8 ^ ~t2shi9 & t2shi5; - s2[26] = t2slo13 ^ ~t2slo14 & t2slo10; - s2[27] = t2shi13 ^ ~t2shi14 & t2shi10; - s2[36] = t2slo18 ^ ~t2slo19 & t2slo15; - s2[37] = t2shi18 ^ ~t2shi19 & t2shi15; - s2[46] = t2slo23 ^ ~t2slo24 & t2slo20; - s2[47] = t2shi23 ^ ~t2shi24 & t2shi20; - s2[8] = t2slo4 ^ ~t2slo0 & t2slo1; - s2[9] = t2shi4 ^ ~t2shi0 & t2shi1; - s2[18] = t2slo9 ^ ~t2slo5 & t2slo6; - s2[19] = t2shi9 ^ ~t2shi5 & t2shi6; - s2[28] = t2slo14 ^ ~t2slo10 & t2slo11; - s2[29] = t2shi14 ^ ~t2shi10 & t2shi11; - s2[38] = t2slo19 ^ ~t2slo15 & t2slo16; - s2[39] = t2shi19 ^ ~t2shi15 & t2shi16; - s2[48] = t2slo24 ^ ~t2slo20 & t2slo21; - s2[49] = t2shi24 ^ ~t2shi20 & t2shi21; - s2[0] ^= P1600_ROUND_CONSTANTS[round * 2]; - s2[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]; - } - }; - } -}); - -// node_modules/keccak/lib/keccak.js -var require_keccak2 = __commonJS({ - "node_modules/keccak/lib/keccak.js"(exports2, module2) { - init_shim(); - var keccakState = require_keccak_state_unroll(); - function Keccak() { - this.state = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - this.blockSize = null; - this.count = 0; - this.squeezing = false; - } - Keccak.prototype.initialize = function(rate, capacity) { - for (let i2 = 0; i2 < 50; ++i2) - this.state[i2] = 0; - this.blockSize = rate / 8; - this.count = 0; - this.squeezing = false; - }; - Keccak.prototype.absorb = function(data) { - for (let i2 = 0; i2 < data.length; ++i2) { - this.state[~~(this.count / 4)] ^= data[i2] << 8 * (this.count % 4); - this.count += 1; - if (this.count === this.blockSize) { - keccakState.p1600(this.state); - this.count = 0; - } - } - }; - Keccak.prototype.absorbLastFewBits = function(bits) { - this.state[~~(this.count / 4)] ^= bits << 8 * (this.count % 4); - if ((bits & 128) !== 0 && this.count === this.blockSize - 1) - keccakState.p1600(this.state); - this.state[~~((this.blockSize - 1) / 4)] ^= 128 << 8 * ((this.blockSize - 1) % 4); - keccakState.p1600(this.state); - this.count = 0; - this.squeezing = true; - }; - Keccak.prototype.squeeze = function(length2) { - if (!this.squeezing) - this.absorbLastFewBits(1); - const output = import_buffer.Buffer.alloc(length2); - for (let i2 = 0; i2 < length2; ++i2) { - output[i2] = this.state[~~(this.count / 4)] >>> 8 * (this.count % 4) & 255; - this.count += 1; - if (this.count === this.blockSize) { - keccakState.p1600(this.state); - this.count = 0; - } - } - return output; - }; - Keccak.prototype.copy = function(dest) { - for (let i2 = 0; i2 < 50; ++i2) - dest.state[i2] = this.state[i2]; - dest.blockSize = this.blockSize; - dest.count = this.count; - dest.squeezing = this.squeezing; - }; - module2.exports = Keccak; - } -}); - -// node_modules/keccak/js.js -var require_js = __commonJS({ - "node_modules/keccak/js.js"(exports2, module2) { - init_shim(); - module2.exports = require_api()(require_keccak2()); - } -}); - -// node_modules/@multiversx/sdk-core/out/address.js -var require_address = __commonJS({ - "node_modules/@multiversx/sdk-core/out/address.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AddressComputer = exports2.Address = void 0; - var bech32 = __importStar2(require_bech32()); - var bignumber_js_1 = __importDefault2(require_bignumber()); - var constants_1 = require_constants(); - var errors = __importStar2(require_errors()); - var codec_1 = require_codec(); - var createKeccakHash = require_js(); - var HRP = "erd"; - var PUBKEY_LENGTH = 32; - var SMART_CONTRACT_HEX_PUBKEY_PREFIX = "0".repeat(16); - var Address5 = class _Address { - /** - * Creates an address object, given a raw string (whether a hex pubkey or a Bech32 address), a sequence of bytes, or another Address object. - */ - constructor(value) { - this.valueHex = ""; - if (!value) { - return; - } - if (value instanceof _Address) { - return _Address.fromAddress(value); - } - if (ArrayBuffer.isView(value)) { - return _Address.fromBuffer(import_buffer.Buffer.from(value)); - } - if (typeof value === "string") { - return _Address.fromString(value); - } - throw new errors.ErrAddressCannotCreate(value); - } - /** - * Creates an address object from another address object - */ - static fromAddress(address) { - return _Address.fromValidHex(address.valueHex); - } - static fromValidHex(value) { - let result = _Address.empty(); - result.valueHex = value; - return result; - } - /** - * Creates an address object from a Buffer - */ - static fromBuffer(buffer) { - if (buffer.length != PUBKEY_LENGTH) { - throw new errors.ErrAddressCannotCreate(buffer); - } - return _Address.fromValidHex(buffer.toString("hex")); - } - /** - * Creates an address object from a string (hex or bech32) - */ - static fromString(value) { - if (_Address.isValidHex(value)) { - return _Address.fromValidHex(value); - } - return _Address.fromBech32(value); - } - static isValidHex(value) { - return import_buffer.Buffer.from(value, "hex").length == PUBKEY_LENGTH; - } - /** - * Creates an address object from a hex-encoded string - */ - static fromHex(value) { - if (!_Address.isValidHex(value)) { - throw new errors.ErrAddressCannotCreate(value); - } - return _Address.fromValidHex(value); - } - /** - * Creates an empty address object. - * Generally speaking, this should not be used by client code (internal use only). - */ - static empty() { - return new _Address(""); - } - /** - * Creates an address object from a bech32-encoded string - */ - static fromBech32(value) { - let decoded; - try { - decoded = bech32.decode(value); - } catch (err) { - throw new errors.ErrAddressCannotCreate(value, err); - } - const prefix = decoded.prefix; - if (prefix != HRP) { - throw new errors.ErrAddressBadHrp(HRP, prefix); - } - const pubkey = import_buffer.Buffer.from(bech32.fromWords(decoded.words)); - if (pubkey.length != PUBKEY_LENGTH) { - throw new errors.ErrAddressCannotCreate(value); - } - return _Address.fromValidHex(pubkey.toString("hex")); - } - /** - * Performs address validation without throwing errors - */ - static isValid(value) { - const decoded = bech32.decodeUnsafe(value); - const prefix = decoded?.prefix; - const pubkey = decoded ? import_buffer.Buffer.from(bech32.fromWords(decoded.words)) : void 0; - if (prefix !== HRP || pubkey?.length !== PUBKEY_LENGTH) { - return false; - } - return true; - } - /** - * Use {@link toHex} instead. - */ - hex() { - return this.toHex(); - } - /** - * Returns the hex representation of the address (pubkey) - */ - toHex() { - if (this.isEmpty()) { - return ""; - } - return this.valueHex; - } - /** - * Use {@link toBech32} instead. - */ - bech32() { - return this.toBech32(); - } - /** - * Returns the bech32 representation of the address - */ - toBech32() { - if (this.isEmpty()) { - return ""; - } - let words = bech32.toWords(this.pubkey()); - let address = bech32.encode(HRP, words); - return address; - } - /** - * Use {@link getPublicKey} instead. - */ - pubkey() { - return this.getPublicKey(); - } - /** - * Returns the pubkey as raw bytes (buffer) - */ - getPublicKey() { - if (this.isEmpty()) { - return import_buffer.Buffer.from([]); - } - return import_buffer.Buffer.from(this.valueHex, "hex"); - } - /** - * Returns the human-readable-part of the bech32 addresses. - * The HRP is currently hardcoded to "erd". - */ - getHrp() { - return HRP; - } - /** - * Returns whether the address is empty. - */ - isEmpty() { - return !this.valueHex; - } - /** - * Compares the address to another address - */ - equals(other) { - if (!other) { - return false; - } - return this.valueHex == other.valueHex; - } - /** - * Returns the bech32 representation of the address - */ - toString() { - return this.toBech32(); - } - /** - * Converts the address to a pretty, plain JavaScript object. - */ - toJSON() { - return { - bech32: this.toBech32(), - pubkey: this.toHex() - }; - } - /** - * Creates the Zero address (the one that should be used when deploying smart contracts). - * Generally speaking, this should not be used by client code (internal use only). - */ - static Zero() { - return new _Address("0".repeat(64)); - } - /** - * Use {@link isSmartContract} instead. - */ - isContractAddress() { - return this.isSmartContract(); - } - /** - * Returns whether the address is a smart contract address. - */ - isSmartContract() { - return this.toHex().startsWith(SMART_CONTRACT_HEX_PUBKEY_PREFIX); - } - }; - exports2.Address = Address5; - var AddressComputer = class { - constructor(numberOfShardsWithoutMeta) { - this.numberOfShardsWithoutMeta = numberOfShardsWithoutMeta || constants_1.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META; - } - computeContractAddress(deployer, deploymentNonce) { - const initialPadding = import_buffer.Buffer.alloc(8, 0); - const ownerPubkey = deployer.getPublicKey(); - const shardSelector = ownerPubkey.slice(30); - const ownerNonceBytes = import_buffer.Buffer.alloc(8); - const bigNonce = new bignumber_js_1.default(deploymentNonce.toString()); - const bigNonceBuffer = codec_1.bigIntToBuffer(bigNonce); - ownerNonceBytes.write(bigNonceBuffer.reverse().toString("hex"), "hex"); - const bytesToHash = import_buffer.Buffer.concat([ownerPubkey, ownerNonceBytes]); - const hash = createKeccakHash("keccak256").update(bytesToHash).digest(); - const vmTypeBytes = import_buffer.Buffer.from(constants_1.WasmVirtualMachine, "hex"); - const addressBytes = import_buffer.Buffer.concat([initialPadding, vmTypeBytes, hash.slice(10, 30), shardSelector]); - return new Address5(addressBytes); - } - getShardOfAddress(address) { - return this.getShardOfPubkey(address.getPublicKey(), this.numberOfShardsWithoutMeta); - } - getShardOfPubkey(pubkey, numberOfShards) { - const maskHigh = parseInt("11", 2); - const maskLow = parseInt("01", 2); - const lastByteOfPubkey = pubkey[31]; - if (this.isPubkeyOfMetachain(pubkey)) { - return constants_1.METACHAIN_ID; - } - let shard = lastByteOfPubkey & maskHigh; - if (shard > numberOfShards - 1) { - shard = lastByteOfPubkey & maskLow; - } - return shard; - } - isPubkeyOfMetachain(pubkey) { - const metachainPrefix = import_buffer.Buffer.from([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]); - const pubkeyPrefix = import_buffer.Buffer.from(pubkey).slice(0, metachainPrefix.length); - if (metachainPrefix.equals(pubkeyPrefix)) { - return true; - } - const zeroAddress = import_buffer.Buffer.alloc(32); - if (zeroAddress.equals(import_buffer.Buffer.from(pubkey))) { - return true; - } - return false; - } - }; - exports2.AddressComputer = AddressComputer; - } -}); - -// node_modules/@multiversx/sdk-core/out/utils.js -var require_utils2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/utils.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isEmpty = exports2.guardEmpty = exports2.guardNotEmpty = exports2.guardLength = exports2.guardSameLength = exports2.guardValueIsSetWithMessage = exports2.guardValueIsSet = exports2.guardTrue = void 0; - var errors = __importStar2(require_errors()); - function guardTrue(value, what) { - if (!value) { - throw new errors.ErrInvariantFailed(`[<${what}>] isn't true`); - } - } - exports2.guardTrue = guardTrue; - function guardValueIsSet(name2, value) { - guardValueIsSetWithMessage(`${name2} isn't set (null or undefined)`, value); - } - exports2.guardValueIsSet = guardValueIsSet; - function guardValueIsSetWithMessage(message, value) { - if (value == null || value === void 0) { - throw new errors.ErrInvariantFailed(message); - } - } - exports2.guardValueIsSetWithMessage = guardValueIsSetWithMessage; - function guardSameLength(a3, b4) { - a3 = a3 || []; - b4 = b4 || []; - if (a3.length != b4.length) { - throw new errors.ErrInvariantFailed("arrays do not have the same length"); - } - } - exports2.guardSameLength = guardSameLength; - function guardLength(withLength, expectedLength) { - let actualLength = withLength.length || 0; - if (actualLength != expectedLength) { - throw new errors.ErrInvariantFailed(`wrong length, expected: ${expectedLength}, actual: ${actualLength}`); - } - } - exports2.guardLength = guardLength; - function guardNotEmpty(value, what) { - if (isEmpty(value)) { - throw new errors.ErrInvariantFailed(`${what} is empty`); - } - } - exports2.guardNotEmpty = guardNotEmpty; - function guardEmpty(value, what) { - if (!isEmpty(value)) { - throw new errors.ErrInvariantFailed(`${what} is not empty`); - } - } - exports2.guardEmpty = guardEmpty; - function isEmpty(value) { - if (value.isEmpty) { - return value.isEmpty(); - } - return value.length === 0; - } - exports2.isEmpty = isEmpty; - } -}); - -// node_modules/@multiversx/sdk-core/out/abi/typeFormula.js -var require_typeFormula = __commonJS({ - "node_modules/@multiversx/sdk-core/out/abi/typeFormula.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeFormula = void 0; - var TypeFormula = class { - constructor(name2, typeParameters) { - this.name = name2; - this.typeParameters = typeParameters; - } - toString() { - if (this.typeParameters.length > 0) { - const typeParameters = this.typeParameters.map((typeParameter) => typeParameter.toString()).join(", "); - return `${this.name}<${typeParameters}>`; - } else { - return this.name; - } - } - }; - exports2.TypeFormula = TypeFormula; - } -}); - -// node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js -var require_typeFormulaParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/abi/typeFormulaParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeFormulaParser = void 0; - var typeFormula_1 = require_typeFormula(); - var TypeFormulaParser = class _TypeFormulaParser { - parseExpression(expression) { - expression = expression.trim(); - const tokens = this.tokenizeExpression(expression).filter((token) => token !== _TypeFormulaParser.COMMA); - const stack = []; - for (const token of tokens) { - if (this.isPunctuation(token)) { - if (this.isEndOfTypeParameters(token)) { - const typeFormula = this.acquireTypeWithParameters(stack); - stack.push(typeFormula); - } else if (this.isBeginningOfTypeParameters(token)) { - stack.push(token); - } else { - throw new Error(`Unexpected token (punctuation): ${token}`); - } - } else { - stack.push(token); - } - } - if (stack.length !== 1) { - throw new Error(`Unexpected stack length at end of parsing: ${stack.length}`); - } - if (_TypeFormulaParser.PUNCTUATION.includes(stack[0])) { - throw new Error("Unexpected root element."); - } - const item = stack[0]; - if (item instanceof typeFormula_1.TypeFormula) { - return item; - } else if (typeof item === "string") { - return new typeFormula_1.TypeFormula(item, []); - } else { - throw new Error(`Unexpected item on stack: ${item}`); - } - } - tokenizeExpression(expression) { - const tokens = []; - let currentToken = ""; - for (const character of expression) { - if (this.isPunctuation(character)) { - if (currentToken) { - tokens.push(currentToken.trim()); - currentToken = ""; - } - tokens.push(character); - } else { - currentToken += character; - } - } - if (currentToken) { - tokens.push(currentToken.trim()); - } - return tokens; - } - acquireTypeWithParameters(stack) { - const typeParameters = this.acquireTypeParameters(stack); - const typeName = stack.pop(); - const typeFormula = new typeFormula_1.TypeFormula(typeName, typeParameters.reverse()); - return typeFormula; - } - acquireTypeParameters(stack) { - const typeParameters = []; - while (true) { - const item = stack.pop(); - if (item === void 0) { - throw new Error("Badly specified type parameters"); - } - if (this.isBeginningOfTypeParameters(item)) { - break; - } - if (item instanceof typeFormula_1.TypeFormula) { - typeParameters.push(item); - } else if (typeof item === "string") { - typeParameters.push(new typeFormula_1.TypeFormula(item, [])); - } else { - throw new Error(`Unexpected type parameter object in stack: ${item}`); - } - } - return typeParameters; - } - isPunctuation(token) { - return _TypeFormulaParser.PUNCTUATION.includes(token); - } - isEndOfTypeParameters(token) { - return token === _TypeFormulaParser.END_TYPE_PARAMETERS; - } - isBeginningOfTypeParameters(token) { - return token === _TypeFormulaParser.BEGIN_TYPE_PARAMETERS; - } - }; - exports2.TypeFormulaParser = TypeFormulaParser; - TypeFormulaParser.BEGIN_TYPE_PARAMETERS = "<"; - TypeFormulaParser.END_TYPE_PARAMETERS = ">"; - TypeFormulaParser.COMMA = ","; - TypeFormulaParser.PUNCTUATION = [ - TypeFormulaParser.COMMA, - TypeFormulaParser.BEGIN_TYPE_PARAMETERS, - TypeFormulaParser.END_TYPE_PARAMETERS - ]; - } -}); - -// node_modules/@multiversx/sdk-core/out/reflection.js -var require_reflection = __commonJS({ - "node_modules/@multiversx/sdk-core/out/reflection.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getJavascriptPrototypesInHierarchy = void 0; - function getJavascriptPrototypesInHierarchy(obj, filter) { - let prototypes = []; - let prototype = Object.getPrototypeOf(obj); - while (prototype && filter(prototype)) { - prototypes.push(prototype); - prototype = Object.getPrototypeOf(prototype); - } - return prototypes; - } - exports2.getJavascriptPrototypesInHierarchy = getJavascriptPrototypesInHierarchy; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js -var require_types = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/types.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NullType = exports2.TypePlaceholder = exports2.isTyped = exports2.PrimitiveValue = exports2.TypedValue = exports2.CustomType = exports2.PrimitiveType = exports2.TypeCardinality = exports2.Type = void 0; - var reflection_1 = require_reflection(); - var utils_1 = require_utils2(); - var Type = class _Type { - constructor(name2, typeParameters = [], cardinality = TypeCardinality.fixed(1)) { - utils_1.guardValueIsSet("name", name2); - this.name = name2; - this.typeParameters = typeParameters; - this.cardinality = cardinality; - } - getName() { - return this.name; - } - getClassName() { - return _Type.ClassName; - } - getClassHierarchy() { - let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); - let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); - return classNames; - } - /** - * Gets the fully qualified name of the type, to allow for better (efficient and non-ambiguous) type comparison within the custom typesystem. - */ - getFullyQualifiedName() { - let joinedTypeParameters = this.getTypeParameters().map((type) => type.getFullyQualifiedName()).join(", "); - return this.isGenericType() ? `multiversx:types:${this.getName()}<${joinedTypeParameters}>` : `multiversx:types:${this.getName()}`; - } - hasExactClass(className) { - return this.getClassName() == className; - } - hasClassOrSuperclass(className) { - let hierarchy = this.getClassHierarchy(); - return hierarchy.includes(className); - } - getTypeParameters() { - return this.typeParameters; - } - isGenericType() { - return this.typeParameters.length > 0; - } - getFirstTypeParameter() { - utils_1.guardTrue(this.typeParameters.length > 0, "type parameters length > 0"); - return this.typeParameters[0]; - } - /** - * Generates type expressions similar to mx-sdk-rs. - */ - toString() { - let typeParameters = this.getTypeParameters().map((type) => type.toString()).join(", "); - let typeParametersExpression = typeParameters ? `<${typeParameters}>` : ""; - return `${this.name}${typeParametersExpression}`; - } - equals(other) { - return _Type.equals(this, other); - } - static equals(a3, b4) { - return a3.getFullyQualifiedName() == b4.getFullyQualifiedName(); - } - static equalsMany(a3, b4) { - return a3.every((type, i2) => type.equals(b4[i2])); - } - static isAssignableFromMany(a3, b4) { - return a3.every((type, i2) => type.isAssignableFrom(b4[i2])); - } - differs(other) { - return !this.equals(other); - } - valueOf() { - return this.name; - } - /** - * Inspired from: https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom - * For (most) generics, type invariance is expected (assumed) - neither covariance, nor contravariance are supported yet (will be supported in a next release). - * - * One exception though: for {@link OptionType}, we simulate covariance for missing (not provided) values. - * For example, Option is assignable from Option. - * For more details, see the implementation of {@link OptionType} and @{@link OptionalType}. - * - * Also see: - * - https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) - * - https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance - */ - isAssignableFrom(other) { - let invariantTypeParameters = _Type.equalsMany(this.getTypeParameters(), other.getTypeParameters()); - if (!invariantTypeParameters) { - return false; - } - let fullyQualifiedNameOfThis = this.getFullyQualifiedName(); - let fullyQualifiedNamesInHierarchyOfOther = _Type.getFullyQualifiedNamesInHierarchy(other); - if (fullyQualifiedNamesInHierarchyOfOther.includes(fullyQualifiedNameOfThis)) { - return true; - } - return other.hasClassOrSuperclass(this.getClassName()); - } - static getFullyQualifiedNamesInHierarchy(type) { - let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(type, (prototype) => prototype.belongsToTypesystem); - let fullyQualifiedNames = prototypes.map((prototype) => prototype.getFullyQualifiedName.call(type)); - return fullyQualifiedNames; - } - getNamesOfDependencies() { - const dependencies = []; - for (const type of this.typeParameters) { - dependencies.push(type.getName()); - dependencies.push(...type.getNamesOfDependencies()); - } - return [...new Set(dependencies)]; - } - /** - * Converts the account to a pretty, plain JavaScript object. - */ - toJSON() { - return { - name: this.name, - typeParameters: this.typeParameters.map((item) => item.toJSON()) - }; - } - getCardinality() { - return this.cardinality; - } - /** - * A special marker for types within the custom typesystem. - */ - belongsToTypesystem() { - } - }; - exports2.Type = Type; - Type.ClassName = "Type"; - var TypeCardinality = class _TypeCardinality { - constructor(lowerBound, upperBound) { - this.lowerBound = lowerBound; - this.upperBound = upperBound; - } - static fixed(value) { - return new _TypeCardinality(value, value); - } - static variable(value) { - return new _TypeCardinality(0, value); - } - isSingular() { - return this.lowerBound == 1 && this.upperBound == 1; - } - isSingularOrNone() { - return this.lowerBound == 0 && this.upperBound == 1; - } - isComposite() { - return this.upperBound != 1; - } - isFixed() { - return this.lowerBound == this.upperBound; - } - getLowerBound() { - return this.lowerBound; - } - getUpperBound() { - return this.upperBound || _TypeCardinality.MaxCardinality; - } - }; - exports2.TypeCardinality = TypeCardinality; - TypeCardinality.MaxCardinality = 4096; - var PrimitiveType = class _PrimitiveType extends Type { - constructor(name2) { - super(name2); - } - getClassName() { - return _PrimitiveType.ClassName; - } - }; - exports2.PrimitiveType = PrimitiveType; - PrimitiveType.ClassName = "PrimitiveType"; - var CustomType = class _CustomType extends Type { - getClassName() { - return _CustomType.ClassName; - } - }; - exports2.CustomType = CustomType; - CustomType.ClassName = "CustomType"; - var TypedValue = class _TypedValue { - constructor(type) { - this.type = type; - } - getClassName() { - return _TypedValue.ClassName; - } - getClassHierarchy() { - let prototypes = reflection_1.getJavascriptPrototypesInHierarchy(this, (prototype) => prototype.belongsToTypesystem); - let classNames = prototypes.map((prototype) => prototype.getClassName()).reverse(); - return classNames; - } - getType() { - return this.type; - } - hasExactClass(className) { - return this.getClassName() == className; - } - hasClassOrSuperclass(className) { - let hierarchy = this.getClassHierarchy(); - return hierarchy.includes(className); - } - /** - * A special marker for values within the custom typesystem. - */ - belongsToTypesystem() { - } - }; - exports2.TypedValue = TypedValue; - TypedValue.ClassName = "TypedValue"; - var PrimitiveValue = class _PrimitiveValue extends TypedValue { - constructor(type) { - super(type); - } - getClassName() { - return _PrimitiveValue.ClassName; - } - }; - exports2.PrimitiveValue = PrimitiveValue; - PrimitiveValue.ClassName = "PrimitiveValue"; - function isTyped(value) { - return value.belongsToTypesystem !== void 0; - } - exports2.isTyped = isTyped; - var TypePlaceholder = class _TypePlaceholder extends Type { - constructor() { - super("..."); - } - getClassName() { - return _TypePlaceholder.ClassName; - } - }; - exports2.TypePlaceholder = TypePlaceholder; - TypePlaceholder.ClassName = "TypePlaceholder"; - var NullType = class _NullType extends Type { - constructor() { - super("?"); - } - getClassName() { - return _NullType.ClassName; - } - }; - exports2.NullType = NullType; - NullType.ClassName = "NullType"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js -var require_typeExpressionParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeExpressionParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeExpressionParser = void 0; - var typeFormulaParser_1 = require_typeFormulaParser(); - var errors_1 = require_errors(); - var types_1 = require_types(); - var TypeExpressionParser = class { - constructor() { - this.backingTypeFormulaParser = new typeFormulaParser_1.TypeFormulaParser(); - } - parse(expression) { - try { - return this.doParse(expression); - } catch (e2) { - throw new errors_1.ErrTypingSystem(`Failed to parse type expression: ${expression}. Error: ${e2}`); - } - } - doParse(expression) { - const typeFormula = this.backingTypeFormulaParser.parseExpression(expression); - const type = this.typeFormulaToType(typeFormula); - return type; - } - typeFormulaToType(typeFormula) { - const typeParameters = typeFormula.typeParameters.map((typeFormula2) => this.typeFormulaToType(typeFormula2)); - return new types_1.Type(typeFormula.name, typeParameters); - } - }; - exports2.TypeExpressionParser = TypeExpressionParser; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js -var require_endpoint = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/endpoint.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EndpointParameterDefinition = exports2.EndpointModifiers = exports2.EndpointDefinition = void 0; - var typeExpressionParser_1 = require_typeExpressionParser(); - var NamePlaceholder = "?"; - var DescriptionPlaceholder = "N / A"; - var EndpointDefinition = class _EndpointDefinition { - constructor(name2, input, output, modifiers) { - this.input = []; - this.output = []; - this.name = name2; - this.input = input || []; - this.output = output || []; - this.modifiers = modifiers; - } - isConstructor() { - return this.name == "constructor"; - } - static fromJSON(json) { - json.name = json.name == null ? NamePlaceholder : json.name; - json.onlyOwner = json.onlyOwner || false; - json.payableInTokens = json.payableInTokens || []; - json.inputs = json.inputs || []; - json.outputs = json.outputs || []; - let input = json.inputs.map((param) => EndpointParameterDefinition.fromJSON(param)); - let output = json.outputs.map((param) => EndpointParameterDefinition.fromJSON(param)); - let modifiers = new EndpointModifiers(json.mutability, json.payableInTokens, json.onlyOwner); - return new _EndpointDefinition(json.name, input, output, modifiers); - } - }; - exports2.EndpointDefinition = EndpointDefinition; - var EndpointModifiers = class { - constructor(mutability, payableInTokens, onlyOwner) { - this.mutability = mutability || ""; - this.payableInTokens = payableInTokens || []; - this.onlyOwner = onlyOwner || false; - } - isPayableInEGLD() { - return this.isPayableInToken("EGLD"); - } - isPayableInToken(token) { - if (this.payableInTokens.includes(token)) { - return true; - } - if (this.payableInTokens.includes(`!${token}`)) { - return false; - } - if (this.payableInTokens.includes("*")) { - return true; - } - return false; - } - isPayable() { - return this.payableInTokens.length != 0; - } - isReadonly() { - return this.mutability == "readonly"; - } - isOnlyOwner() { - return this.onlyOwner; - } - }; - exports2.EndpointModifiers = EndpointModifiers; - var EndpointParameterDefinition = class _EndpointParameterDefinition { - constructor(name2, description, type) { - this.name = name2; - this.description = description; - this.type = type; - } - static fromJSON(json) { - let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); - return new _EndpointParameterDefinition(json.name || NamePlaceholder, json.description || DescriptionPlaceholder, parsedType); - } - }; - exports2.EndpointParameterDefinition = EndpointParameterDefinition; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js -var require_fields = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/fields.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Fields = exports2.Field = exports2.FieldDefinition = void 0; - var errors = __importStar2(require_errors()); - var typeExpressionParser_1 = require_typeExpressionParser(); - var FieldDefinition = class _FieldDefinition { - constructor(name2, description, type) { - this.name = name2; - this.description = description; - this.type = type; - } - static fromJSON(json) { - let parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); - return new _FieldDefinition(json.name, json.description, parsedType); - } - }; - exports2.FieldDefinition = FieldDefinition; - var Field = class { - constructor(value, name2 = "") { - this.value = value; - this.name = name2; - } - checkTyping(expectedDefinition) { - const actualType = this.value.getType(); - if (!actualType.equals(expectedDefinition.type)) { - throw new errors.ErrTypingSystem(`check type of field "${expectedDefinition.name}; expected: ${expectedDefinition.type}, actual: ${actualType}"`); - } - if (this.name != expectedDefinition.name) { - throw new errors.ErrTypingSystem(`check name of field "${expectedDefinition.name}"`); - } - } - equals(other) { - return this.name == other.name && this.value.equals(other.value); - } - }; - exports2.Field = Field; - var Fields = class { - static checkTyping(fields, definitions) { - if (fields.length != definitions.length) { - throw new errors.ErrTypingSystem("fields length vs. field definitions length"); - } - for (let i2 = 0; i2 < fields.length; i2++) { - let field = fields[i2]; - let definition = definitions[i2]; - field.checkTyping(definition); - } - } - static equals(actual, expected) { - if (actual.length != expected.length) { - return false; - } - for (let i2 = 0; i2 < actual.length; i2++) { - let selfField = actual[i2]; - let otherField = expected[i2]; - if (!selfField.equals(otherField)) { - return false; - } - } - return true; - } - static getNamesOfTypeDependencies(definitions) { - const dependencies = []; - for (const definition of definitions) { - dependencies.push(definition.type.getName()); - dependencies.push(...definition.type.getNamesOfDependencies()); - } - return [...new Set(dependencies)]; - } - }; - exports2.Fields = Fields; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js -var require_enum = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/enum.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EnumValue = exports2.EnumVariantDefinition = exports2.EnumType = void 0; - var errors_1 = require_errors(); - var utils_1 = require_utils2(); - var fields_1 = require_fields(); - var types_1 = require_types(); - var SimpleEnumMaxDiscriminant = 256; - var EnumType = class _EnumType extends types_1.CustomType { - constructor(name2, variants) { - super(name2); - this.variants = []; - this.variants = variants; - } - getClassName() { - return _EnumType.ClassName; - } - static fromJSON(json) { - const rawVariants = _EnumType.assignMissingDiscriminants(json.variants || []); - const variants = rawVariants.map((variant) => EnumVariantDefinition.fromJSON(variant)); - return new _EnumType(json.name, variants); - } - // For some enums (e.g. some "explicit-enum" types), the discriminants are missing. - static assignMissingDiscriminants(variants) { - const allDiscriminantsAreMissing = variants.every((variant) => variant.discriminant == void 0); - if (!allDiscriminantsAreMissing) { - return variants; - } - return variants.map((variant, index) => { - return { - ...variant, - discriminant: index - }; - }); - } - getVariantByDiscriminant(discriminant) { - let result = this.variants.find((e2) => e2.discriminant == discriminant); - utils_1.guardValueIsSet(`variant by discriminant (${discriminant})`, result); - return result; - } - getVariantByName(name2) { - let result = this.variants.find((e2) => e2.name == name2); - utils_1.guardValueIsSet(`variant by name (${name2})`, result); - return result; - } - getNamesOfDependencies() { - const dependencies = []; - for (const variant of this.variants) { - dependencies.push(...variant.getNamesOfDependencies()); - } - return [...new Set(dependencies)]; - } - }; - exports2.EnumType = EnumType; - EnumType.ClassName = "EnumType"; - var EnumVariantDefinition = class _EnumVariantDefinition { - constructor(name2, discriminant, fieldsDefinitions = []) { - this.fieldsDefinitions = []; - utils_1.guardTrue(discriminant < SimpleEnumMaxDiscriminant, `discriminant for simple enum should be less than ${SimpleEnumMaxDiscriminant}`); - this.name = name2; - this.discriminant = discriminant; - this.fieldsDefinitions = fieldsDefinitions; - } - static fromJSON(json) { - let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); - return new _EnumVariantDefinition(json.name, json.discriminant, definitions); - } - getFieldsDefinitions() { - return this.fieldsDefinitions; - } - getFieldDefinition(name2) { - return this.fieldsDefinitions.find((item) => item.name == name2); - } - getNamesOfDependencies() { - return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); - } - }; - exports2.EnumVariantDefinition = EnumVariantDefinition; - var EnumValue = class _EnumValue extends types_1.TypedValue { - constructor(type, variant, fields) { - super(type); - this.fields = []; - this.name = variant.name; - this.discriminant = variant.discriminant; - this.fields = fields; - this.fieldsByName = new Map(fields.map((field) => [field.name, field])); - let definitions = variant.getFieldsDefinitions(); - fields_1.Fields.checkTyping(this.fields, definitions); - } - getClassName() { - return _EnumValue.ClassName; - } - /** - * Utility (named constructor) to create a simple (i.e. without fields) enum value. - */ - static fromName(type, name2) { - let variant = type.getVariantByName(name2); - return new _EnumValue(type, variant, []); - } - /** - * Utility (named constructor) to create a simple (i.e. without fields) enum value. - */ - static fromDiscriminant(type, discriminant) { - let variant = type.getVariantByDiscriminant(discriminant); - return new _EnumValue(type, variant, []); - } - equals(other) { - if (!this.getType().equals(other.getType())) { - return false; - } - let selfFields = this.getFields(); - let otherFields = other.getFields(); - const nameIsSame = this.name == other.name; - const discriminantIsSame = this.discriminant == other.discriminant; - const fieldsAreSame = fields_1.Fields.equals(selfFields, otherFields); - return nameIsSame && discriminantIsSame && fieldsAreSame; - } - getFields() { - return this.fields; - } - getFieldValue(name2) { - let field = this.fieldsByName.get(name2); - if (field) { - return field.value.valueOf(); - } - throw new errors_1.ErrMissingFieldOnEnum(name2, this.getType().getName()); - } - valueOf() { - let result = { name: this.name, fields: [] }; - this.fields.forEach((field, index) => result.fields[index] = field.value.valueOf()); - return result; - } - }; - exports2.EnumValue = EnumValue; - EnumValue.ClassName = "EnumValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js -var require_event = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/event.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EventTopicDefinition = exports2.EventDefinition = void 0; - var typeExpressionParser_1 = require_typeExpressionParser(); - var NamePlaceholder = "?"; - var EventDefinition = class _EventDefinition { - constructor(identifier, inputs) { - this.inputs = []; - this.identifier = identifier; - this.inputs = inputs || []; - } - static fromJSON(json) { - json.identifier = json.identifier == null ? NamePlaceholder : json.identifier; - json.inputs = json.inputs || []; - const inputs = json.inputs.map((param) => EventTopicDefinition.fromJSON(param)); - return new _EventDefinition(json.identifier, inputs); - } - }; - exports2.EventDefinition = EventDefinition; - var EventTopicDefinition = class _EventTopicDefinition { - constructor(options) { - this.name = options.name; - this.type = options.type; - this.indexed = options.indexed; - } - static fromJSON(json) { - const parsedType = new typeExpressionParser_1.TypeExpressionParser().parse(json.type); - return new _EventTopicDefinition({ - name: json.name || NamePlaceholder, - type: parsedType, - indexed: json.indexed - }); - } - }; - exports2.EventTopicDefinition = EventTopicDefinition; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js -var require_struct = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/struct.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Struct = exports2.StructType = void 0; - var errors_1 = require_errors(); - var fields_1 = require_fields(); - var types_1 = require_types(); - var StructType = class _StructType extends types_1.CustomType { - constructor(name2, fieldsDefinitions) { - super(name2); - this.fieldsDefinitions = []; - this.fieldsDefinitions = fieldsDefinitions; - } - getClassName() { - return _StructType.ClassName; - } - static fromJSON(json) { - let definitions = (json.fields || []).map((definition) => fields_1.FieldDefinition.fromJSON(definition)); - return new _StructType(json.name, definitions); - } - getFieldsDefinitions() { - return this.fieldsDefinitions; - } - getFieldDefinition(name2) { - return this.fieldsDefinitions.find((item) => item.name == name2); - } - getNamesOfDependencies() { - return fields_1.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions); - } - }; - exports2.StructType = StructType; - StructType.ClassName = "StructType"; - var Struct = class _Struct extends types_1.TypedValue { - /** - * One can only set fields at initialization time. - */ - constructor(type, fields) { - super(type); - this.fields = fields; - this.fieldsByName = new Map(fields.map((field) => [field.name, field])); - this.checkTyping(); - } - getClassName() { - return _Struct.ClassName; - } - checkTyping() { - let type = this.getType(); - let definitions = type.getFieldsDefinitions(); - fields_1.Fields.checkTyping(this.fields, definitions); - } - getFields() { - return this.fields; - } - getFieldValue(name2) { - let field = this.fieldsByName.get(name2); - if (field) { - return field.value.valueOf(); - } - throw new errors_1.ErrMissingFieldOnStruct(name2, this.getType().getName()); - } - valueOf() { - let result = {}; - for (const field of this.fields) { - result[field.name] = field.value.valueOf(); - } - return result; - } - equals(other) { - if (!this.getType().equals(other.getType())) { - return false; - } - let selfFields = this.getFields(); - let otherFields = other.getFields(); - return fields_1.Fields.equals(selfFields, otherFields); - } - }; - exports2.Struct = Struct; - Struct.ClassName = "Struct"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js -var require_address2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/address.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AddressValue = exports2.AddressType = void 0; - var address_1 = require_address(); - var types_1 = require_types(); - var AddressType2 = class _AddressType extends types_1.PrimitiveType { - constructor() { - super("Address"); - } - getClassName() { - return _AddressType.ClassName; - } - }; - exports2.AddressType = AddressType2; - AddressType2.ClassName = "AddressType"; - var AddressValue2 = class _AddressValue extends types_1.PrimitiveValue { - constructor(value) { - super(new AddressType2()); - this.value = new address_1.Address(value.bech32()); - } - getClassName() { - return _AddressValue.ClassName; - } - /** - * Returns whether two objects have the same value. - * - * @param other another AddressValue - */ - equals(other) { - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - }; - exports2.AddressValue = AddressValue2; - AddressValue2.ClassName = "AddressValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js -var require_algebraic = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/algebraic.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OptionalValue = exports2.OptionalType = void 0; - var utils_1 = require_utils2(); - var types_1 = require_types(); - var OptionalType = class _OptionalType extends types_1.Type { - constructor(typeParameter) { - super("Optional", [typeParameter], types_1.TypeCardinality.variable(1)); - } - getClassName() { - return _OptionalType.ClassName; - } - isAssignableFrom(type) { - if (!type.hasExactClass(_OptionalType.ClassName)) { - return false; - } - let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); - let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); - return invariantTypeParameters || fakeCovarianceToNull; - } - }; - exports2.OptionalType = OptionalType; - OptionalType.ClassName = "OptionalType"; - var OptionalValue = class _OptionalValue extends types_1.TypedValue { - constructor(type, value = null) { - super(type); - this.value = value; - } - getClassName() { - return _OptionalValue.ClassName; - } - /** - * Creates an OptionalValue, as not provided (missing). - */ - static newMissing() { - let type = new OptionalType(new types_1.NullType()); - return new _OptionalValue(type); - } - isSet() { - return this.value ? true : false; - } - getTypedValue() { - utils_1.guardValueIsSet("value", this.value); - return this.value; - } - valueOf() { - return this.value ? this.value.valueOf() : null; - } - equals(other) { - return this.value?.equals(other.value) || false; - } - }; - exports2.OptionalValue = OptionalValue; - OptionalValue.ClassName = "OptionalValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js -var require_boolean = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/boolean.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BooleanValue = exports2.BooleanType = void 0; - var types_1 = require_types(); - var BooleanType2 = class _BooleanType extends types_1.PrimitiveType { - constructor() { - super("bool"); - } - getClassName() { - return _BooleanType.ClassName; - } - }; - exports2.BooleanType = BooleanType2; - BooleanType2.ClassName = "BooleanType"; - var BooleanValue2 = class _BooleanValue extends types_1.PrimitiveValue { - constructor(value) { - super(new BooleanType2()); - this.value = value; - } - getClassName() { - return _BooleanValue.ClassName; - } - /** - * Returns whether two objects have the same value. - * - * @param other another BooleanValue - */ - equals(other) { - return this.value === other.value; - } - isTrue() { - return this.value === true; - } - isFalse() { - return !this.isTrue(); - } - valueOf() { - return this.value; - } - }; - exports2.BooleanValue = BooleanValue2; - BooleanValue2.ClassName = "BooleanValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js -var require_bytes = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/bytes.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesValue = exports2.BytesType = void 0; - var types_1 = require_types(); - var BytesType2 = class _BytesType extends types_1.PrimitiveType { - constructor() { - super("bytes"); - } - getClassName() { - return _BytesType.ClassName; - } - }; - exports2.BytesType = BytesType2; - BytesType2.ClassName = "BytesType"; - var BytesValue2 = class _BytesValue extends types_1.PrimitiveValue { - constructor(value) { - super(new BytesType2()); - this.value = value; - } - getClassName() { - return _BytesValue.ClassName; - } - /** - * Creates a BytesValue from a utf-8 string. - */ - static fromUTF8(value) { - let buffer = import_buffer.Buffer.from(value, "utf-8"); - return new _BytesValue(buffer); - } - /** - * Creates a BytesValue from a hex-encoded string. - */ - static fromHex(value) { - let buffer = import_buffer.Buffer.from(value, "hex"); - return new _BytesValue(buffer); - } - getLength() { - return this.value.length; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - if (this.getLength() != other.getLength()) { - return false; - } - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - toString() { - return this.value.toString(); - } - }; - exports2.BytesValue = BytesValue2; - BytesValue2.ClassName = "BytesValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js -var require_codeMetadata = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/codeMetadata.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CodeMetadataValue = exports2.CodeMetadataType = void 0; - var types_1 = require_types(); - var CodeMetadataType = class extends types_1.PrimitiveType { - constructor() { - super("CodeMetadata"); - } - }; - exports2.CodeMetadataType = CodeMetadataType; - var CodeMetadataValue = class extends types_1.PrimitiveValue { - constructor(value) { - super(new CodeMetadataType()); - this.value = value; - } - equals(other) { - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - }; - exports2.CodeMetadataValue = CodeMetadataValue; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js -var require_composite = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/composite.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CompositeValue = exports2.CompositeType = void 0; - var utils_1 = require_utils2(); - var types_1 = require_types(); - var CompositeType = class _CompositeType extends types_1.Type { - constructor(...typeParameters) { - super("Composite", typeParameters, types_1.TypeCardinality.variable(typeParameters.length)); - } - getClassName() { - return _CompositeType.ClassName; - } - }; - exports2.CompositeType = CompositeType; - CompositeType.ClassName = "CompositeType"; - var CompositeValue = class _CompositeValue extends types_1.TypedValue { - constructor(type, items) { - super(type); - utils_1.guardLength(items, type.getTypeParameters().length); - this.items = items; - } - getClassName() { - return _CompositeValue.ClassName; - } - static fromItems(...items) { - let typeParameters = items.map((value) => value.getType()); - let type = new CompositeType(...typeParameters); - return new _CompositeValue(type, items); - } - getItems() { - return this.items; - } - valueOf() { - return this.items.map((item) => item?.valueOf()); - } - equals(other) { - if (this.getType().differs(other.getType())) { - return false; - } - for (let i2 = 0; i2 < this.items.length; i2++) { - let selfItem = this.items[i2]; - let otherItem = other.items[i2]; - if (!selfItem.equals(otherItem)) { - return false; - } - } - return true; - } - }; - exports2.CompositeValue = CompositeValue; - CompositeValue.ClassName = "CompositeValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js -var require_collections = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/collections.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CollectionOfTypedValues = void 0; - var CollectionOfTypedValues = class { - constructor(items) { - this.items = items; - } - getLength() { - return this.items.length; - } - getItems() { - return this.items; - } - valueOf() { - return this.items.map((item) => item.valueOf()); - } - equals(other) { - if (this.getLength() != other.getLength()) { - return false; - } - for (let i2 = 0; i2 < this.getLength(); i2++) { - let selfItem = this.items[i2]; - let otherItem = other.items[i2]; - if (!selfItem.equals(otherItem)) { - return false; - } - } - return true; - } - }; - exports2.CollectionOfTypedValues = CollectionOfTypedValues; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js -var require_generic = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/generic.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.List = exports2.OptionValue = exports2.ListType = exports2.OptionType = void 0; - var utils_1 = require_utils2(); - var collections_1 = require_collections(); - var types_1 = require_types(); - var OptionType = class _OptionType extends types_1.Type { - constructor(typeParameter) { - super("Option", [typeParameter]); - } - getClassName() { - return _OptionType.ClassName; - } - isAssignableFrom(type) { - if (!type.hasExactClass(_OptionType.ClassName)) { - return false; - } - let invariantTypeParameters = this.getFirstTypeParameter().equals(type.getFirstTypeParameter()); - let fakeCovarianceToNull = type.getFirstTypeParameter().hasExactClass(types_1.NullType.ClassName); - return invariantTypeParameters || fakeCovarianceToNull; - } - }; - exports2.OptionType = OptionType; - OptionType.ClassName = "OptionType"; - var ListType = class _ListType extends types_1.Type { - constructor(typeParameter) { - super("List", [typeParameter]); - } - getClassName() { - return _ListType.ClassName; - } - }; - exports2.ListType = ListType; - ListType.ClassName = "ListType"; - var OptionValue = class _OptionValue extends types_1.TypedValue { - constructor(type, value = null) { - super(type); - this.value = value; - } - getClassName() { - return _OptionValue.ClassName; - } - /** - * Creates an OptionValue, as a missing option argument. - */ - static newMissing() { - let type = new OptionType(new types_1.NullType()); - return new _OptionValue(type); - } - static newMissingTyped(type) { - return new _OptionValue(new OptionType(type)); - } - /** - * Creates an OptionValue, as a provided option argument. - */ - static newProvided(typedValue) { - let type = new OptionType(typedValue.getType()); - return new _OptionValue(type, typedValue); - } - isSet() { - return this.value ? true : false; - } - getTypedValue() { - utils_1.guardValueIsSet("value", this.value); - return this.value; - } - valueOf() { - return this.value ? this.value.valueOf() : null; - } - equals(other) { - return this.value?.equals(other.value) || false; - } - }; - exports2.OptionValue = OptionValue; - OptionValue.ClassName = "OptionValue"; - var List = class _List extends types_1.TypedValue { - /** - * - * @param type the type of this TypedValue (an instance of ListType), not the type parameter of the ListType - * @param items the items, having the type type.getFirstTypeParameter() - */ - constructor(type, items) { - super(type); - this.backingCollection = new collections_1.CollectionOfTypedValues(items); - } - getClassName() { - return _List.ClassName; - } - static fromItems(items) { - if (items.length == 0) { - return new _List(new types_1.TypePlaceholder(), []); - } - let typeParameter = items[0].getType(); - let listType = new ListType(typeParameter); - return new _List(listType, items); - } - getLength() { - return this.backingCollection.getLength(); - } - getItems() { - return this.backingCollection.getItems(); - } - valueOf() { - return this.backingCollection.valueOf(); - } - equals(other) { - return this.backingCollection.equals(other.backingCollection); - } - }; - exports2.List = List; - List.ClassName = "List"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js -var require_genericArray = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/genericArray.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArrayVec = exports2.ArrayVecType = void 0; - var utils_1 = require_utils2(); - var collections_1 = require_collections(); - var types_1 = require_types(); - var ArrayVecType = class _ArrayVecType extends types_1.Type { - constructor(length2, typeParameter) { - super("Array", [typeParameter]); - utils_1.guardTrue(length2 > 0, "array length > 0"); - this.length = length2; - } - getClassName() { - return _ArrayVecType.ClassName; - } - }; - exports2.ArrayVecType = ArrayVecType; - ArrayVecType.ClassName = "ArrayVecType"; - var ArrayVec = class _ArrayVec extends types_1.TypedValue { - constructor(type, items) { - super(type); - utils_1.guardLength(items, type.length); - this.backingCollection = new collections_1.CollectionOfTypedValues(items); - } - getClassName() { - return _ArrayVec.ClassName; - } - getLength() { - return this.backingCollection.getLength(); - } - getItems() { - return this.backingCollection.getItems(); - } - valueOf() { - return this.backingCollection.valueOf(); - } - equals(other) { - return this.backingCollection.equals(other.backingCollection); - } - }; - exports2.ArrayVec = ArrayVec; - ArrayVec.ClassName = "ArrayVec"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js -var require_h256 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/h256.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.H256Value = exports2.H256Type = void 0; - var types_1 = require_types(); - var H256Type = class _H256Type extends types_1.PrimitiveType { - constructor() { - super("H256"); - } - getClassName() { - return _H256Type.ClassName; - } - }; - exports2.H256Type = H256Type; - H256Type.ClassName = "H256Type"; - var H256Value = class _H256Value extends types_1.PrimitiveValue { - constructor(value) { - super(new H256Type()); - this.value = value; - } - getClassName() { - return _H256Value.ClassName; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - return this.value.equals(other.value); - } - valueOf() { - return this.value; - } - }; - exports2.H256Value = H256Value; - H256Value.ClassName = "H256Value"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js -var require_nothing = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/nothing.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NothingValue = exports2.NothingType = void 0; - var types_1 = require_types(); - var NothingType = class _NothingType extends types_1.PrimitiveType { - constructor() { - super("nothing"); - } - getClassName() { - return _NothingType.ClassName; - } - }; - exports2.NothingType = NothingType; - NothingType.ClassName = "NothingType"; - var NothingValue = class _NothingValue extends types_1.PrimitiveValue { - constructor() { - super(new NothingType()); - } - getClassName() { - return _NothingValue.ClassName; - } - equals(_other) { - return false; - } - valueOf() { - return {}; - } - }; - exports2.NothingValue = NothingValue; - NothingValue.ClassName = "NothingValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js -var require_numerical = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/numerical.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BigIntValue = exports2.BigUIntValue = exports2.I64Value = exports2.U64Value = exports2.I32Value = exports2.U32Value = exports2.I16Value = exports2.U16Value = exports2.I8Value = exports2.U8Value = exports2.NumericalValue = exports2.BigIntType = exports2.BigUIntType = exports2.I64Type = exports2.U64Type = exports2.I32Type = exports2.U32Type = exports2.I16Type = exports2.U16Type = exports2.I8Type = exports2.U8Type = exports2.NumericalType = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var errors = __importStar2(require_errors()); - var types_1 = require_types(); - var NumericalType = class _NumericalType extends types_1.PrimitiveType { - constructor(name2, sizeInBytes, withSign) { - super(name2); - this.sizeInBytes = sizeInBytes; - this.withSign = withSign; - } - getClassName() { - return _NumericalType.ClassName; - } - hasFixedSize() { - return this.sizeInBytes ? true : false; - } - hasArbitrarySize() { - return !this.hasFixedSize(); - } - }; - exports2.NumericalType = NumericalType; - NumericalType.ClassName = "NumericalType"; - var U8Type2 = class _U8Type extends NumericalType { - constructor() { - super("u8", 1, false); - } - getClassName() { - return _U8Type.ClassName; - } - }; - exports2.U8Type = U8Type2; - U8Type2.ClassName = "U8Type"; - var I8Type = class _I8Type extends NumericalType { - constructor() { - super("i8", 1, true); - } - getClassName() { - return _I8Type.ClassName; - } - }; - exports2.I8Type = I8Type; - I8Type.ClassName = "I8Type"; - var U16Type2 = class _U16Type extends NumericalType { - constructor() { - super("u16", 2, false); - } - getClassName() { - return _U16Type.ClassName; - } - }; - exports2.U16Type = U16Type2; - U16Type2.ClassName = "U16Type"; - var I16Type = class _I16Type extends NumericalType { - constructor() { - super("i16", 2, true); - } - getClassName() { - return _I16Type.ClassName; - } - }; - exports2.I16Type = I16Type; - I16Type.ClassName = "I16Type"; - var U32Type2 = class _U32Type extends NumericalType { - constructor() { - super("u32", 4, false); - } - getClassName() { - return _U32Type.ClassName; - } - }; - exports2.U32Type = U32Type2; - U32Type2.ClassName = "U32Type"; - var I32Type = class _I32Type extends NumericalType { - constructor() { - super("i32", 4, true); - } - getClassName() { - return _I32Type.ClassName; - } - }; - exports2.I32Type = I32Type; - I32Type.ClassName = "I32Type"; - var U64Type2 = class _U64Type extends NumericalType { - constructor() { - super("u64", 8, false); - } - getClassName() { - return _U64Type.ClassName; - } - }; - exports2.U64Type = U64Type2; - U64Type2.ClassName = "U64Type"; - var I64Type = class _I64Type extends NumericalType { - constructor() { - super("i64", 8, true); - } - getClassName() { - return _I64Type.ClassName; - } - }; - exports2.I64Type = I64Type; - I64Type.ClassName = "I64Type"; - var BigUIntType2 = class _BigUIntType extends NumericalType { - constructor() { - super("BigUint", 0, false); - } - getClassName() { - return _BigUIntType.ClassName; - } - }; - exports2.BigUIntType = BigUIntType2; - BigUIntType2.ClassName = "BigUIntType"; - var BigIntType = class _BigIntType extends NumericalType { - constructor() { - super("Bigint", 0, true); - } - getClassName() { - return _BigIntType.ClassName; - } - }; - exports2.BigIntType = BigIntType; - BigIntType.ClassName = "BigIntType"; - var NumericalValue = class _NumericalValue extends types_1.PrimitiveValue { - constructor(type, value) { - super(type); - if (typeof value === "bigint") { - value = value.toString(); - } - this.value = new bignumber_js_1.default(value); - this.sizeInBytes = type.sizeInBytes; - this.withSign = type.withSign; - if (this.value.isNaN()) { - throw new errors.ErrInvalidArgument(`not a number: ${value}`); - } - if (!this.withSign && this.value.isNegative()) { - throw new errors.ErrInvalidArgument(`negative, but type is unsigned: ${value}`); - } - } - getClassName() { - return _NumericalValue.ClassName; - } - /** - * Returns whether two objects have the same value. - * - * @param other another NumericalValue - */ - equals(other) { - return this.value.isEqualTo(other.value); - } - valueOf() { - return this.value; - } - toString() { - return this.value.toString(); - } - }; - exports2.NumericalValue = NumericalValue; - NumericalValue.ClassName = "NumericalValue"; - var U8Value2 = class _U8Value extends NumericalValue { - constructor(value) { - super(new U8Type2(), value); - } - getClassName() { - return _U8Value.ClassName; - } - }; - exports2.U8Value = U8Value2; - U8Value2.ClassName = "U8Value"; - var I8Value = class _I8Value extends NumericalValue { - constructor(value) { - super(new I8Type(), value); - } - getClassName() { - return _I8Value.ClassName; - } - }; - exports2.I8Value = I8Value; - I8Value.ClassName = "I8Value"; - var U16Value2 = class _U16Value extends NumericalValue { - constructor(value) { - super(new U16Type2(), value); - } - getClassName() { - return _U16Value.ClassName; - } - }; - exports2.U16Value = U16Value2; - U16Value2.ClassName = "U16Value"; - var I16Value = class _I16Value extends NumericalValue { - constructor(value) { - super(new I16Type(), value); - } - getClassName() { - return _I16Value.ClassName; - } - }; - exports2.I16Value = I16Value; - I16Value.ClassName = "I16Value"; - var U32Value2 = class _U32Value extends NumericalValue { - constructor(value) { - super(new U32Type2(), value); - } - getClassName() { - return _U32Value.ClassName; - } - }; - exports2.U32Value = U32Value2; - U32Value2.ClassName = "U32Value"; - var I32Value = class _I32Value extends NumericalValue { - constructor(value) { - super(new I32Type(), value); - } - getClassName() { - return _I32Value.ClassName; - } - }; - exports2.I32Value = I32Value; - I32Value.ClassName = "I32Value"; - var U64Value2 = class _U64Value extends NumericalValue { - constructor(value) { - super(new U64Type2(), value); - } - getClassName() { - return _U64Value.ClassName; - } - }; - exports2.U64Value = U64Value2; - U64Value2.ClassName = "U64Value"; - var I64Value = class _I64Value extends NumericalValue { - constructor(value) { - super(new I64Type(), value); - } - getClassName() { - return _I64Value.ClassName; - } - }; - exports2.I64Value = I64Value; - I64Value.ClassName = "I64Value"; - var BigUIntValue2 = class _BigUIntValue extends NumericalValue { - constructor(value) { - super(new BigUIntType2(), value); - } - getClassName() { - return _BigUIntValue.ClassName; - } - }; - exports2.BigUIntValue = BigUIntValue2; - BigUIntValue2.ClassName = "BigUIntValue"; - var BigIntValue = class _BigIntValue extends NumericalValue { - constructor(value) { - super(new BigIntType(), value); - } - getClassName() { - return _BigIntValue.ClassName; - } - }; - exports2.BigIntValue = BigIntValue; - BigIntValue.ClassName = "BigIntValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js -var require_string = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/string.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StringValue = exports2.StringType = void 0; - var types_1 = require_types(); - var StringType = class _StringType extends types_1.PrimitiveType { - constructor() { - super("utf-8 string"); - } - getClassName() { - return _StringType.ClassName; - } - }; - exports2.StringType = StringType; - StringType.ClassName = "StringType"; - var StringValue = class _StringValue extends types_1.PrimitiveValue { - constructor(value) { - super(new StringType()); - this.value = value; - } - getClassName() { - return _StringValue.ClassName; - } - /** - * Creates a StringValue from a utf-8 string. - */ - static fromUTF8(value) { - return new _StringValue(value); - } - /** - * Creates a StringValue from a hex-encoded string. - */ - static fromHex(value) { - let decodedValue = import_buffer.Buffer.from(value, "hex").toString(); - return new _StringValue(decodedValue); - } - getLength() { - return this.value.length; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - return this.value === other.value; - } - valueOf() { - return this.value; - } - }; - exports2.StringValue = StringValue; - StringValue.ClassName = "StringValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js -var require_tokenIdentifier = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tokenIdentifier.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenIdentifierValue = exports2.TokenIdentifierType = void 0; - var types_1 = require_types(); - var EGLDTokenIdentifier = "EGLD"; - var TokenIdentifierType = class _TokenIdentifierType extends types_1.PrimitiveType { - constructor() { - super("TokenIdentifier"); - } - getClassName() { - return _TokenIdentifierType.ClassName; - } - }; - exports2.TokenIdentifierType = TokenIdentifierType; - TokenIdentifierType.ClassName = "TokenIdentifierType"; - var TokenIdentifierValue = class _TokenIdentifierValue extends types_1.PrimitiveValue { - constructor(value) { - super(new TokenIdentifierType()); - this.value = value; - } - static egld() { - return new _TokenIdentifierValue(EGLDTokenIdentifier); - } - static esdtTokenIdentifier(identifier) { - return new _TokenIdentifierValue(identifier); - } - getClassName() { - return _TokenIdentifierValue.ClassName; - } - getLength() { - return this.value.length; - } - /** - * Returns whether two objects have the same value. - */ - equals(other) { - if (this.getLength() != other.getLength()) { - return false; - } - return this.value == other.value; - } - valueOf() { - return this.value; - } - toString() { - return this.value.toString(); - } - }; - exports2.TokenIdentifierValue = TokenIdentifierValue; - TokenIdentifierValue.ClassName = "TokenIdentifierValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js -var require_tuple = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/tuple.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Tuple = exports2.TupleType = void 0; - var errors = __importStar2(require_errors()); - var fields_1 = require_fields(); - var struct_1 = require_struct(); - var TupleType = class _TupleType extends struct_1.StructType { - constructor(...typeParameters) { - super(_TupleType.prepareName(typeParameters), _TupleType.prepareFieldDefinitions(typeParameters)); - } - getClassName() { - return _TupleType.ClassName; - } - static prepareName(typeParameters) { - let fields = typeParameters.map((type) => type.toString()).join(", "); - let result = `tuple<${fields}>`; - return result; - } - static prepareFieldDefinitions(typeParameters) { - let result = typeParameters.map((type, i2) => new fields_1.FieldDefinition(prepareFieldName(i2), "anonymous tuple field", type)); - return result; - } - }; - exports2.TupleType = TupleType; - TupleType.ClassName = "TupleType"; - function prepareFieldName(fieldIndex) { - return `field${fieldIndex}`; - } - var Tuple = class _Tuple extends struct_1.Struct { - constructor(type, fields) { - super(type, fields); - } - getClassName() { - return _Tuple.ClassName; - } - static fromItems(items) { - if (items.length < 1) { - throw new errors.ErrTypingSystem("bad tuple items"); - } - let fieldsTypes = items.map((item) => item.getType()); - let tupleType = new TupleType(...fieldsTypes); - let fields = items.map((item, i2) => new fields_1.Field(item, prepareFieldName(i2))); - return new _Tuple(tupleType, fields); - } - }; - exports2.Tuple = Tuple; - Tuple.ClassName = "Tuple"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js -var require_variadic = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/variadic.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.VariadicValue = exports2.CountedVariadicType = exports2.VariadicType = void 0; - var types_1 = require_types(); - var VariadicType = class _VariadicType extends types_1.Type { - constructor(typeParameter, isCounted = false) { - super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); - this.isCounted = isCounted; - } - getClassName() { - return _VariadicType.ClassName; - } - }; - exports2.VariadicType = VariadicType; - VariadicType.ClassName = "VariadicType"; - var CountedVariadicType = class extends types_1.Type { - constructor(typeParameter) { - super("Variadic", [typeParameter], types_1.TypeCardinality.variable()); - } - getClassName() { - return VariadicType.ClassName; - } - }; - exports2.CountedVariadicType = CountedVariadicType; - CountedVariadicType.ClassName = "VariadicType"; - var VariadicValue = class _VariadicValue extends types_1.TypedValue { - /** - * - * @param type the type of this TypedValue (an instance of VariadicType), not the type parameter of the VariadicType - * @param items the items, having the type type.getFirstTypeParameter() - */ - constructor(type, items) { - super(type); - this.items = items; - } - getClassName() { - return _VariadicValue.ClassName; - } - static fromItems(...items) { - return this.createFromItems(items, false); - } - static fromItemsCounted(...items) { - return this.createFromItems(items, true); - } - static createFromItems(items, isCounted) { - if (items.length == 0) { - return new _VariadicValue(new VariadicType(new types_1.TypePlaceholder(), isCounted), []); - } - const typeParameter = items[0].getType(); - return new _VariadicValue(new VariadicType(typeParameter, isCounted), items); - } - getItems() { - return this.items; - } - valueOf() { - return this.items.map((item) => item.valueOf()); - } - equals(other) { - if (this.getType().differs(other.getType())) { - return false; - } - for (let i2 = 0; i2 < this.items.length; i2++) { - let selfItem = this.items[i2]; - let otherItem = other.items[i2]; - if (!selfItem.equals(otherItem)) { - return false; - } - } - return true; - } - }; - exports2.VariadicValue = VariadicValue; - VariadicValue.ClassName = "VariadicValue"; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js -var require_typeMapper = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/typeMapper.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TypeMapper = void 0; - var errors = __importStar2(require_errors()); - var address_1 = require_address2(); - var algebraic_1 = require_algebraic(); - var boolean_1 = require_boolean(); - var bytes_1 = require_bytes(); - var codeMetadata_1 = require_codeMetadata(); - var composite_1 = require_composite(); - var enum_1 = require_enum(); - var fields_1 = require_fields(); - var generic_1 = require_generic(); - var genericArray_1 = require_genericArray(); - var h256_1 = require_h256(); - var nothing_1 = require_nothing(); - var numerical_1 = require_numerical(); - var string_1 = require_string(); - var struct_1 = require_struct(); - var tokenIdentifier_1 = require_tokenIdentifier(); - var tuple_1 = require_tuple(); - var variadic_1 = require_variadic(); - var TypeMapper = class { - constructor(learnedTypes = []) { - this.openTypesFactories = /* @__PURE__ */ new Map([ - ["Option", (...typeParameters) => new generic_1.OptionType(typeParameters[0])], - ["List", (...typeParameters) => new generic_1.ListType(typeParameters[0])], - // For the following open generics, we use a slightly different typing than the one defined by mx-sdk-rs (temporary workaround). - ["VarArgs", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], - ["MultiResultVec", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], - ["variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0])], - ["counted-variadic", (...typeParameters) => new variadic_1.VariadicType(typeParameters[0], true)], - ["OptionalArg", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], - ["optional", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], - ["OptionalResult", (...typeParameters) => new algebraic_1.OptionalType(typeParameters[0])], - ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - ["MultiArg", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - ["MultiResult", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - ["multi", (...typeParameters) => new composite_1.CompositeType(...typeParameters)], - // Perhaps we can adjust the ABI generator to only output "tuple", instead of "tupleN"? - ["tuple", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple2", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple3", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple4", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple5", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple6", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple7", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - ["tuple8", (...typeParameters) => new tuple_1.TupleType(...typeParameters)], - // Known-length arrays. - // TODO: Handle these in typeExpressionParser! - ["array2", (...typeParameters) => new genericArray_1.ArrayVecType(2, typeParameters[0])], - ["array8", (...typeParameters) => new genericArray_1.ArrayVecType(8, typeParameters[0])], - ["array16", (...typeParameters) => new genericArray_1.ArrayVecType(16, typeParameters[0])], - ["array20", (...typeParameters) => new genericArray_1.ArrayVecType(20, typeParameters[0])], - ["array32", (...typeParameters) => new genericArray_1.ArrayVecType(32, typeParameters[0])], - ["array46", (...typeParameters) => new genericArray_1.ArrayVecType(46, typeParameters[0])], - ["array48", (...typeParameters) => new genericArray_1.ArrayVecType(48, typeParameters[0])], - ["array64", (...typeParameters) => new genericArray_1.ArrayVecType(64, typeParameters[0])], - ["array128", (...typeParameters) => new genericArray_1.ArrayVecType(128, typeParameters[0])], - ["array256", (...typeParameters) => new genericArray_1.ArrayVecType(256, typeParameters[0])] - ]); - this.closedTypesMap = /* @__PURE__ */ new Map([ - ["u8", new numerical_1.U8Type()], - ["u16", new numerical_1.U16Type()], - ["u32", new numerical_1.U32Type()], - ["u64", new numerical_1.U64Type()], - ["U64", new numerical_1.U64Type()], - ["BigUint", new numerical_1.BigUIntType()], - ["i8", new numerical_1.I8Type()], - ["i16", new numerical_1.I16Type()], - ["i32", new numerical_1.I32Type()], - ["i64", new numerical_1.I64Type()], - ["Bigint", new numerical_1.BigIntType()], - ["BigInt", new numerical_1.BigIntType()], - ["bool", new boolean_1.BooleanType()], - ["bytes", new bytes_1.BytesType()], - ["Address", new address_1.AddressType()], - ["H256", new h256_1.H256Type()], - ["utf-8 string", new string_1.StringType()], - ["TokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], - ["EgldOrEsdtTokenIdentifier", new tokenIdentifier_1.TokenIdentifierType()], - ["CodeMetadata", new codeMetadata_1.CodeMetadataType()], - ["nothing", new nothing_1.NothingType()], - ["AsyncCall", new nothing_1.NothingType()] - ]); - this.learnedTypesMap = /* @__PURE__ */ new Map(); - for (const type of learnedTypes) { - this.learnedTypesMap.set(type.getName(), type); - } - } - /** - * Maps a "raw type" object to a "known (specific) type" object. - * In the process, it also learns the new type. - * Can only map types if their dependencies were previously learned (through mapping). - */ - mapType(type) { - let mappedType = this.mapTypeRecursively(type); - if (mappedType) { - if (!mappedType.isGenericType()) { - this.learnType(mappedType); - } - return mappedType; - } - throw new errors.ErrTypingSystem(`Cannot map the type "${type.getName()}" to a known type`); - } - mapTypeRecursively(type) { - let isGeneric = type.isGenericType(); - let previouslyLearnedType = this.learnedTypesMap.get(type.getName()); - if (previouslyLearnedType) { - return previouslyLearnedType; - } - let knownClosedType = this.closedTypesMap.get(type.getName()); - if (knownClosedType) { - return knownClosedType; - } - if (type.hasExactClass(enum_1.EnumType.ClassName)) { - return this.mapEnumType(type); - } - if (type.hasExactClass(struct_1.StructType.ClassName)) { - return this.mapStructType(type); - } - if (isGeneric) { - return this.mapGenericType(type); - } - return null; - } - learnType(type) { - this.learnedTypesMap.delete(type.getName()); - this.learnedTypesMap.set(type.getName(), type); - } - mapStructType(type) { - let mappedFields = this.mappedFields(type.getFieldsDefinitions()); - let mappedStruct = new struct_1.StructType(type.getName(), mappedFields); - return mappedStruct; - } - mapEnumType(type) { - let variants = type.variants.map((variant) => new enum_1.EnumVariantDefinition(variant.name, variant.discriminant, this.mappedFields(variant.getFieldsDefinitions()))); - let mappedEnum = new enum_1.EnumType(type.getName(), variants); - return mappedEnum; - } - mappedFields(definitions) { - return definitions.map((definition) => new fields_1.FieldDefinition(definition.name, definition.description, this.mapType(definition.type))); - } - mapGenericType(type) { - let typeParameters = type.getTypeParameters(); - let mappedTypeParameters = typeParameters.map((item) => this.mapType(item)); - let factory = this.openTypesFactories.get(type.getName()); - if (!factory) { - throw new errors.ErrTypingSystem(`Cannot map the generic type "${type.getName()}" to a known type`); - } - return factory(...mappedTypeParameters); - } - }; - exports2.TypeMapper = TypeMapper; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js -var require_abiRegistry = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/abiRegistry.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AbiRegistry = void 0; - var errors = __importStar2(require_errors()); - var utils_1 = require_utils2(); - var endpoint_1 = require_endpoint(); - var enum_1 = require_enum(); - var event_1 = require_event(); - var struct_1 = require_struct(); - var typeMapper_1 = require_typeMapper(); - var interfaceNamePlaceholder = "?"; - var AbiRegistry = class _AbiRegistry { - constructor(options) { - this.endpoints = []; - this.customTypes = []; - this.events = []; - this.name = options.name; - this.constructorDefinition = options.constructorDefinition; - this.endpoints = options.endpoints; - this.customTypes = options.customTypes; - this.events = options.events || []; - } - static create(options) { - const name2 = options.name || interfaceNamePlaceholder; - const constructor = options.constructor || {}; - const endpoints = options.endpoints || []; - const types = options.types || {}; - const events = options.events || []; - const constructorDefinition = endpoint_1.EndpointDefinition.fromJSON({ name: "constructor", ...constructor }); - const endpointDefinitions = endpoints.map((item) => endpoint_1.EndpointDefinition.fromJSON(item)); - const customTypes = []; - for (const customTypeName in types) { - const typeDefinition = types[customTypeName]; - if (typeDefinition.type == "struct") { - customTypes.push(struct_1.StructType.fromJSON({ name: customTypeName, fields: typeDefinition.fields })); - } else if (typeDefinition.type == "enum" || typeDefinition.type == "explicit-enum") { - customTypes.push(enum_1.EnumType.fromJSON({ name: customTypeName, variants: typeDefinition.variants })); - } else { - throw new errors.ErrTypingSystem(`Cannot handle custom type: ${customTypeName}`); - } - } - const eventDefinitions = events.map((item) => event_1.EventDefinition.fromJSON(item)); - const registry = new _AbiRegistry({ - name: name2, - constructorDefinition, - endpoints: endpointDefinitions, - customTypes, - events: eventDefinitions - }); - const remappedRegistry = registry.remapToKnownTypes(); - return remappedRegistry; - } - getCustomType(name2) { - const result = this.customTypes.find((e2) => e2.getName() == name2); - utils_1.guardValueIsSetWithMessage(`custom type [${name2}] not found`, result); - return result; - } - getStruct(name2) { - const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(struct_1.StructType.ClassName)); - utils_1.guardValueIsSetWithMessage(`struct [${name2}] not found`, result); - return result; - } - getStructs(names) { - return names.map((name2) => this.getStruct(name2)); - } - getEnum(name2) { - const result = this.customTypes.find((e2) => e2.getName() == name2 && e2.hasExactClass(enum_1.EnumType.ClassName)); - utils_1.guardValueIsSetWithMessage(`enum [${name2}] not found`, result); - return result; - } - getEnums(names) { - return names.map((name2) => this.getEnum(name2)); - } - getEndpoints() { - return this.endpoints; - } - getEndpoint(name2) { - const result = this.endpoints.find((e2) => e2.name == name2); - utils_1.guardValueIsSetWithMessage(`endpoint [${name2}] not found`, result); - return result; - } - getEvent(name2) { - const result = this.events.find((e2) => e2.identifier == name2); - utils_1.guardValueIsSetWithMessage(`event [${name2}] not found`, result); - return result; - } - /** - * Right after loading ABI definitions into a registry, the endpoints and the custom types (structs, enums) - * use raw types for their I/O parameters (in the case of endpoints), or for their fields (in the case of structs). - * - * A raw type is merely an instance of {@link Type}, with a given name and type parameters (if it's a generic type). - * - * Though, for most (development) purposes, we'd like to operate using known, specific types (e.g. {@link List}, {@link U8Type} etc.). - * This function increases the specificity of the types used by parameter / field definitions within a registry (on best-efforts basis). - * The result is an equivalent, more explicit ABI registry. - */ - remapToKnownTypes() { - const mapper = new typeMapper_1.TypeMapper([]); - const newCustomTypes = []; - for (const type of this.customTypes) { - this.mapCustomTypeDepthFirst(type, this.customTypes, mapper, newCustomTypes); - } - if (this.customTypes.length != newCustomTypes.length) { - throw new errors.ErrTypingSystem("Did not re-map all custom types"); - } - const newConstructor = mapEndpoint(this.constructorDefinition, mapper); - const newEndpoints = []; - for (const endpoint of this.endpoints) { - newEndpoints.push(mapEndpoint(endpoint, mapper)); - } - const newEvents = this.events.map((event) => mapEvent(event, mapper)); - const newRegistry = new _AbiRegistry({ - name: this.name, - constructorDefinition: newConstructor, - endpoints: newEndpoints, - customTypes: newCustomTypes, - events: newEvents - }); - return newRegistry; - } - mapCustomTypeDepthFirst(typeToMap, allTypesToMap, mapper, mappedTypes) { - const hasBeenMapped = mappedTypes.findIndex((type) => type.getName() == typeToMap.getName()) >= 0; - if (hasBeenMapped) { - return; - } - for (const typeName of typeToMap.getNamesOfDependencies()) { - const dependencyType = allTypesToMap.find((type) => type.getName() == typeName); - if (!dependencyType) { - continue; - } - this.mapCustomTypeDepthFirst(dependencyType, allTypesToMap, mapper, mappedTypes); - } - const mappedType = mapper.mapType(typeToMap); - mappedTypes.push(mappedType); - } - }; - exports2.AbiRegistry = AbiRegistry; - function mapEndpoint(endpoint, mapper) { - const newInput = endpoint.input.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); - const newOutput = endpoint.output.map((e2) => new endpoint_1.EndpointParameterDefinition(e2.name, e2.description, mapper.mapType(e2.type))); - return new endpoint_1.EndpointDefinition(endpoint.name, newInput, newOutput, endpoint.modifiers); - } - function mapEvent(event, mapper) { - const newInputs = event.inputs.map((e2) => new event_1.EventTopicDefinition({ - name: e2.name, - type: mapper.mapType(e2.type), - indexed: e2.indexed - })); - return new event_1.EventDefinition(event.identifier, newInputs); - } - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js -var require_factory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/factory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.createListOfTokenIdentifiers = exports2.createListOfAddresses = void 0; - var address_1 = require_address2(); - var generic_1 = require_generic(); - var tokenIdentifier_1 = require_tokenIdentifier(); - function createListOfAddresses(addresses) { - let addressesTyped = addresses.map((address) => new address_1.AddressValue(address)); - let list = generic_1.List.fromItems(addressesTyped); - return list; - } - exports2.createListOfAddresses = createListOfAddresses; - function createListOfTokenIdentifiers(identifiers) { - let identifiersTyped = identifiers.map((identifier) => new tokenIdentifier_1.TokenIdentifierValue(identifier)); - let list = generic_1.List.fromItems(identifiersTyped); - return list; - } - exports2.createListOfTokenIdentifiers = createListOfTokenIdentifiers; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js -var require_matchers = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/matchers.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.onPrimitiveTypeSelect = exports2.onPrimitiveValueSelect = exports2.onTypedValueSelect = exports2.onTypeSelect = void 0; - var errors = __importStar2(require_errors()); - var address_1 = require_address2(); - var boolean_1 = require_boolean(); - var bytes_1 = require_bytes(); - var enum_1 = require_enum(); - var generic_1 = require_generic(); - var h256_1 = require_h256(); - var numerical_1 = require_numerical(); - var nothing_1 = require_nothing(); - var struct_1 = require_struct(); - var tokenIdentifier_1 = require_tokenIdentifier(); - var tuple_1 = require_tuple(); - var types_1 = require_types(); - var genericArray_1 = require_genericArray(); - var string_1 = require_string(); - function onTypeSelect(type, selectors) { - if (type.hasExactClass(generic_1.OptionType.ClassName)) { - return selectors.onOption(); - } - if (type.hasExactClass(generic_1.ListType.ClassName)) { - return selectors.onList(); - } - if (type.hasExactClass(genericArray_1.ArrayVecType.ClassName)) { - return selectors.onArray(); - } - if (type.hasClassOrSuperclass(types_1.PrimitiveType.ClassName)) { - return selectors.onPrimitive(); - } - if (type.hasExactClass(struct_1.StructType.ClassName)) { - return selectors.onStruct(); - } - if (type.hasExactClass(tuple_1.TupleType.ClassName)) { - return selectors.onTuple(); - } - if (type.hasExactClass(enum_1.EnumType.ClassName)) { - return selectors.onEnum(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`type isn't known: ${type}`); - } - exports2.onTypeSelect = onTypeSelect; - function onTypedValueSelect(value, selectors) { - if (value.hasClassOrSuperclass(types_1.PrimitiveValue.ClassName)) { - return selectors.onPrimitive(); - } - if (value.hasExactClass(generic_1.OptionValue.ClassName)) { - return selectors.onOption(); - } - if (value.hasExactClass(generic_1.List.ClassName)) { - return selectors.onList(); - } - if (value.hasExactClass(genericArray_1.ArrayVec.ClassName)) { - return selectors.onArray(); - } - if (value.hasExactClass(struct_1.Struct.ClassName)) { - return selectors.onStruct(); - } - if (value.hasExactClass(tuple_1.Tuple.ClassName)) { - return selectors.onTuple(); - } - if (value.hasExactClass(enum_1.EnumValue.ClassName)) { - return selectors.onEnum(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`value isn't typed: ${value}`); - } - exports2.onTypedValueSelect = onTypedValueSelect; - function onPrimitiveValueSelect(value, selectors) { - if (value.hasExactClass(boolean_1.BooleanValue.ClassName)) { - return selectors.onBoolean(); - } - if (value.hasClassOrSuperclass(numerical_1.NumericalValue.ClassName)) { - return selectors.onNumerical(); - } - if (value.hasExactClass(address_1.AddressValue.ClassName)) { - return selectors.onAddress(); - } - if (value.hasExactClass(bytes_1.BytesValue.ClassName)) { - return selectors.onBytes(); - } - if (value.hasExactClass(string_1.StringValue.ClassName)) { - return selectors.onString(); - } - if (value.hasExactClass(h256_1.H256Value.ClassName)) { - return selectors.onH256(); - } - if (value.hasExactClass(tokenIdentifier_1.TokenIdentifierValue.ClassName)) { - return selectors.onTypeIdentifier(); - } - if (value.hasExactClass(nothing_1.NothingValue.ClassName)) { - return selectors.onNothing(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`value isn't a primitive: ${value.getType()}`); - } - exports2.onPrimitiveValueSelect = onPrimitiveValueSelect; - function onPrimitiveTypeSelect(type, selectors) { - if (type.hasExactClass(boolean_1.BooleanType.ClassName)) { - return selectors.onBoolean(); - } - if (type.hasClassOrSuperclass(numerical_1.NumericalType.ClassName)) { - return selectors.onNumerical(); - } - if (type.hasExactClass(address_1.AddressType.ClassName)) { - return selectors.onAddress(); - } - if (type.hasExactClass(bytes_1.BytesType.ClassName)) { - return selectors.onBytes(); - } - if (type.hasExactClass(string_1.StringType.ClassName)) { - return selectors.onString(); - } - if (type.hasExactClass(h256_1.H256Type.ClassName)) { - return selectors.onH256(); - } - if (type.hasExactClass(tokenIdentifier_1.TokenIdentifierType.ClassName)) { - return selectors.onTokenIndetifier(); - } - if (type.hasExactClass(nothing_1.NothingType.ClassName)) { - return selectors.onNothing(); - } - if (selectors.onOther) { - return selectors.onOther(); - } - throw new errors.ErrTypingSystem(`type isn't a known primitive: ${type}`); - } - exports2.onPrimitiveTypeSelect = onPrimitiveTypeSelect; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js -var require_typesystem = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/typesystem/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_abiRegistry(), exports2); - __exportStar2(require_address2(), exports2); - __exportStar2(require_algebraic(), exports2); - __exportStar2(require_boolean(), exports2); - __exportStar2(require_bytes(), exports2); - __exportStar2(require_composite(), exports2); - __exportStar2(require_endpoint(), exports2); - __exportStar2(require_enum(), exports2); - __exportStar2(require_factory(), exports2); - __exportStar2(require_fields(), exports2); - __exportStar2(require_generic(), exports2); - __exportStar2(require_genericArray(), exports2); - __exportStar2(require_h256(), exports2); - __exportStar2(require_matchers(), exports2); - __exportStar2(require_nothing(), exports2); - __exportStar2(require_numerical(), exports2); - __exportStar2(require_string(), exports2); - __exportStar2(require_struct(), exports2); - __exportStar2(require_tokenIdentifier(), exports2); - __exportStar2(require_tuple(), exports2); - __exportStar2(require_typeExpressionParser(), exports2); - __exportStar2(require_typeMapper(), exports2); - __exportStar2(require_types(), exports2); - __exportStar2(require_variadic(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js -var require_option = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/option.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OptionValueBinaryCodec = void 0; - var errors = __importStar2(require_errors()); - var typesystem_1 = require_typesystem(); - var OptionValueBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, type) { - if (buffer[0] == 0) { - return [typesystem_1.OptionValue.newMissingTyped(type), 1]; - } - if (buffer[0] != 1) { - throw new errors.ErrCodec("invalid buffer for optional value"); - } - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); - return [typesystem_1.OptionValue.newProvided(decoded), decodedLength + 1]; - } - decodeTopLevel(buffer, type) { - if (buffer.length == 0) { - return new typesystem_1.OptionValue(type); - } - if (buffer[0] != 1) { - throw new errors.ErrCodec("invalid buffer for optional value"); - } - let [decoded, _decodedLength] = this.binaryCodec.decodeNested(buffer.slice(1), type); - return new typesystem_1.OptionValue(type, decoded); - } - encodeNested(optionValue) { - if (optionValue.isSet()) { - return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); - } - return import_buffer.Buffer.from([0]); - } - encodeTopLevel(optionValue) { - if (optionValue.isSet()) { - return import_buffer.Buffer.concat([import_buffer.Buffer.from([1]), this.binaryCodec.encodeNested(optionValue.getTypedValue())]); - } - return import_buffer.Buffer.from([]); - } - }; - exports2.OptionValueBinaryCodec = OptionValueBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js -var require_address3 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/address.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AddressBinaryCodec = void 0; - var address_1 = require_address(); - var typesystem_1 = require_typesystem(); - var AddressBinaryCodec = class { - /** - * Reads and decodes an AddressValue from a given buffer. - * - * @param buffer the input buffer - */ - decodeNested(buffer) { - let slice = buffer.slice(0, 32); - let value = new address_1.Address(slice); - return [new typesystem_1.AddressValue(value), 32]; - } - /** - * Reads and decodes an AddressValue from a given buffer. - * - * @param buffer the input buffer - */ - decodeTopLevel(buffer) { - let [decoded, _length] = this.decodeNested(buffer); - return decoded; - } - /** - * Encodes an AddressValue to a buffer. - */ - encodeNested(primitive) { - return primitive.valueOf().pubkey(); - } - /** - * Encodes an AddressValue to a buffer. - */ - encodeTopLevel(primitive) { - return primitive.valueOf().pubkey(); - } - }; - exports2.AddressBinaryCodec = AddressBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js -var require_boolean2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/boolean.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BooleanBinaryCodec = void 0; - var errors = __importStar2(require_errors()); - var typesystem_1 = require_typesystem(); - var BooleanBinaryCodec = class _BooleanBinaryCodec { - decodeNested(buffer) { - let byte = buffer.readUInt8(0); - return [new typesystem_1.BooleanValue(byte == _BooleanBinaryCodec.TRUE), 1]; - } - decodeTopLevel(buffer) { - if (buffer.length > 1) { - throw new errors.ErrInvalidArgument("buffer should be of size <= 1"); - } - let firstByte = buffer[0]; - return new typesystem_1.BooleanValue(firstByte == _BooleanBinaryCodec.TRUE); - } - encodeNested(primitive) { - if (primitive.isTrue()) { - return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); - } - return import_buffer.Buffer.from([_BooleanBinaryCodec.FALSE]); - } - encodeTopLevel(primitive) { - if (primitive.isTrue()) { - return import_buffer.Buffer.from([_BooleanBinaryCodec.TRUE]); - } - return import_buffer.Buffer.from([]); - } - }; - exports2.BooleanBinaryCodec = BooleanBinaryCodec; - BooleanBinaryCodec.TRUE = 1; - BooleanBinaryCodec.FALSE = 0; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js -var require_constants2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SizeOfU32 = void 0; - exports2.SizeOfU32 = 4; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js -var require_numerical2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/numerical.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NumericalBinaryCodec = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var typesystem_1 = require_typesystem(); - var constants_1 = require_constants2(); - var utils_1 = require_utils(); - var NumericalBinaryCodec = class { - decodeNested(buffer, type) { - let offset = 0; - let length2 = type.sizeInBytes; - if (!length2) { - offset = constants_1.SizeOfU32; - length2 = buffer.readUInt32BE(0); - } - let payload = buffer.slice(offset, offset + length2); - let result = this.decodeTopLevel(payload, type); - let decodedLength = length2 + offset; - return [result, decodedLength]; - } - decodeTopLevel(buffer, type) { - let payload = utils_1.cloneBuffer(buffer); - let empty2 = buffer.length == 0; - if (empty2) { - return new typesystem_1.NumericalValue(type, new bignumber_js_1.default(0)); - } - let isPositive = !type.withSign || utils_1.isMsbZero(payload); - if (isPositive) { - let value2 = utils_1.bufferToBigInt(payload); - return new typesystem_1.NumericalValue(type, value2); - } - utils_1.flipBufferBitsInPlace(payload); - let value = utils_1.bufferToBigInt(payload); - let negativeValue = value.multipliedBy(new bignumber_js_1.default(-1)); - let negativeValueMinusOne = negativeValue.minus(new bignumber_js_1.default(1)); - return new typesystem_1.NumericalValue(type, negativeValueMinusOne); - } - encodeNested(primitive) { - if (primitive.sizeInBytes) { - return this.encodeNestedFixedSize(primitive, primitive.sizeInBytes); - } - let buffer = this.encodeTopLevel(primitive); - let length2 = import_buffer.Buffer.alloc(constants_1.SizeOfU32); - length2.writeUInt32BE(buffer.length); - return import_buffer.Buffer.concat([length2, buffer]); - } - encodeNestedFixedSize(primitive, size) { - if (primitive.value.isZero()) { - return import_buffer.Buffer.alloc(size, 0); - } - if (!primitive.withSign) { - const buffer2 = utils_1.bigIntToBuffer(primitive.value); - const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); - return import_buffer.Buffer.concat([paddingBytes2, buffer2]); - } - if (primitive.value.isPositive()) { - let buffer2 = utils_1.bigIntToBuffer(primitive.value); - if (utils_1.isMsbOne(buffer2)) { - buffer2 = utils_1.prependByteToBuffer(buffer2, 0); - } - const paddingBytes2 = import_buffer.Buffer.alloc(size - buffer2.length, 0); - return import_buffer.Buffer.concat([paddingBytes2, buffer2]); - } - let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); - let buffer = utils_1.bigIntToBuffer(valuePlusOne); - utils_1.flipBufferBitsInPlace(buffer); - if (utils_1.isMsbZero(buffer)) { - buffer = utils_1.prependByteToBuffer(buffer, 255); - } - const paddingBytes = import_buffer.Buffer.alloc(size - buffer.length, 255); - return import_buffer.Buffer.concat([paddingBytes, buffer]); - } - encodeTopLevel(primitive) { - let withSign = primitive.withSign; - if (primitive.value.isZero()) { - return import_buffer.Buffer.alloc(0); - } - if (!withSign) { - return utils_1.bigIntToBuffer(primitive.value); - } - return this.encodePrimitive(primitive); - } - encodePrimitive(primitive) { - if (primitive.value.isPositive()) { - let buffer2 = utils_1.bigIntToBuffer(primitive.value); - if (utils_1.isMsbOne(buffer2)) { - buffer2 = utils_1.prependByteToBuffer(buffer2, 0); - } - return buffer2; - } - let valuePlusOne = primitive.value.plus(new bignumber_js_1.default(1)); - let buffer = utils_1.bigIntToBuffer(valuePlusOne); - utils_1.flipBufferBitsInPlace(buffer); - if (utils_1.isMsbZero(buffer)) { - buffer = utils_1.prependByteToBuffer(buffer, 255); - } - return buffer; - } - }; - exports2.NumericalBinaryCodec = NumericalBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js -var require_h2562 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/h256.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.H256BinaryCodec = void 0; - var h256_1 = require_h256(); - var H256BinaryCodec = class { - /** - * Reads and decodes a H256Value from a given buffer. - * - * @param buffer the input buffer - */ - decodeNested(buffer) { - let slice = buffer.slice(0, 32); - return [new h256_1.H256Value(slice), 32]; - } - /** - * Reads and decodes a H256Value from a given buffer. - * - * @param buffer the input buffer - */ - decodeTopLevel(buffer) { - let [decoded, _length] = this.decodeNested(buffer); - return decoded; - } - /** - * Encodes a H256Value to a buffer. - */ - encodeNested(primitive) { - return primitive.valueOf(); - } - /** - * Encodes a H256Value to a buffer. - */ - encodeTopLevel(primitive) { - return primitive.valueOf(); - } - }; - exports2.H256BinaryCodec = H256BinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js -var require_bytes2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/bytes.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BytesBinaryCodec = void 0; - var bytes_1 = require_bytes(); - var constants_1 = require_constants2(); - var BytesBinaryCodec = class { - decodeNested(buffer) { - let length2 = buffer.readUInt32BE(0); - let payload = buffer.slice(constants_1.SizeOfU32, constants_1.SizeOfU32 + length2); - let result = new bytes_1.BytesValue(payload); - return [result, constants_1.SizeOfU32 + length2]; - } - decodeTopLevel(buffer) { - return new bytes_1.BytesValue(buffer); - } - encodeNested(bytes) { - let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); - lengthBuffer.writeUInt32BE(bytes.getLength()); - let buffer = import_buffer.Buffer.concat([lengthBuffer, bytes.valueOf()]); - return buffer; - } - encodeTopLevel(bytes) { - return bytes.valueOf(); - } - }; - exports2.BytesBinaryCodec = BytesBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js -var require_tokenIdentifier2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tokenIdentifier.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenIdentifierCodec = void 0; - var bytes_1 = require_bytes(); - var tokenIdentifier_1 = require_tokenIdentifier(); - var bytes_2 = require_bytes2(); - var TokenIdentifierCodec = class { - constructor() { - this.bytesCodec = new bytes_2.BytesBinaryCodec(); - } - decodeNested(buffer) { - let [bytesValue, length2] = this.bytesCodec.decodeNested(buffer); - return [new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()), length2]; - } - decodeTopLevel(buffer) { - let bytesValue = this.bytesCodec.decodeTopLevel(buffer); - return new tokenIdentifier_1.TokenIdentifierValue(bytesValue.toString()); - } - encodeNested(tokenIdentifier) { - let bytesValue = bytes_1.BytesValue.fromUTF8(tokenIdentifier.valueOf()); - return this.bytesCodec.encodeNested(bytesValue); - } - encodeTopLevel(tokenIdentifier) { - return import_buffer.Buffer.from(tokenIdentifier.valueOf()); - } - }; - exports2.TokenIdentifierCodec = TokenIdentifierCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js -var require_nothing2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/nothing.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NothingCodec = void 0; - var typesystem_1 = require_typesystem(); - var NothingCodec = class { - decodeNested() { - return [new typesystem_1.NothingValue(), 0]; - } - decodeTopLevel() { - return new typesystem_1.NothingValue(); - } - encodeNested() { - return import_buffer.Buffer.from([]); - } - encodeTopLevel() { - return import_buffer.Buffer.from([]); - } - }; - exports2.NothingCodec = NothingCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js -var require_string2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/string.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StringBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var bytes_1 = require_bytes(); - var bytes_2 = require_bytes2(); - var StringBinaryCodec = class { - constructor() { - this.bytesBinaryCodec = new bytes_2.BytesBinaryCodec(); - } - decodeNested(buffer) { - let [decoded, length2] = this.bytesBinaryCodec.decodeNested(buffer); - let decodedAsString = new typesystem_1.StringValue(decoded.valueOf().toString()); - return [decodedAsString, length2]; - } - decodeTopLevel(buffer) { - return new typesystem_1.StringValue(buffer.toString()); - } - encodeNested(value) { - let valueAsBytes = bytes_1.BytesValue.fromUTF8(value.valueOf()); - return this.bytesBinaryCodec.encodeNested(valueAsBytes); - } - encodeTopLevel(value) { - return import_buffer.Buffer.from(value.valueOf()); - } - }; - exports2.StringBinaryCodec = StringBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js -var require_primitive = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/primitive.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PrimitiveBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var address_1 = require_address3(); - var boolean_1 = require_boolean2(); - var numerical_1 = require_numerical2(); - var h256_1 = require_h2562(); - var bytes_1 = require_bytes2(); - var tokenIdentifier_1 = require_tokenIdentifier2(); - var nothing_1 = require_nothing2(); - var string_1 = require_string2(); - var PrimitiveBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - this.booleanCodec = new boolean_1.BooleanBinaryCodec(); - this.numericalCodec = new numerical_1.NumericalBinaryCodec(); - this.addressCodec = new address_1.AddressBinaryCodec(); - this.h256Codec = new h256_1.H256BinaryCodec(); - this.bytesCodec = new bytes_1.BytesBinaryCodec(); - this.stringCodec = new string_1.StringBinaryCodec(); - this.tokenIdentifierCodec = new tokenIdentifier_1.TokenIdentifierCodec(); - this.nothingCodec = new nothing_1.NothingCodec(); - } - decodeNested(buffer, type) { - return typesystem_1.onPrimitiveTypeSelect(type, { - onBoolean: () => this.booleanCodec.decodeNested(buffer), - onNumerical: () => this.numericalCodec.decodeNested(buffer, type), - onAddress: () => this.addressCodec.decodeNested(buffer), - onBytes: () => this.bytesCodec.decodeNested(buffer), - onString: () => this.stringCodec.decodeNested(buffer), - onH256: () => this.h256Codec.decodeNested(buffer), - onTokenIndetifier: () => this.tokenIdentifierCodec.decodeNested(buffer), - onNothing: () => this.nothingCodec.decodeNested() - }); - } - decodeTopLevel(buffer, type) { - return typesystem_1.onPrimitiveTypeSelect(type, { - onBoolean: () => this.booleanCodec.decodeTopLevel(buffer), - onNumerical: () => this.numericalCodec.decodeTopLevel(buffer, type), - onAddress: () => this.addressCodec.decodeTopLevel(buffer), - onBytes: () => this.bytesCodec.decodeTopLevel(buffer), - onString: () => this.stringCodec.decodeTopLevel(buffer), - onH256: () => this.h256Codec.decodeTopLevel(buffer), - onTokenIndetifier: () => this.tokenIdentifierCodec.decodeTopLevel(buffer), - onNothing: () => this.nothingCodec.decodeTopLevel() - }); - } - encodeNested(value) { - return typesystem_1.onPrimitiveValueSelect(value, { - onBoolean: () => this.booleanCodec.encodeNested(value), - onNumerical: () => this.numericalCodec.encodeNested(value), - onAddress: () => this.addressCodec.encodeNested(value), - onBytes: () => this.bytesCodec.encodeNested(value), - onString: () => this.stringCodec.encodeNested(value), - onH256: () => this.h256Codec.encodeNested(value), - onTypeIdentifier: () => this.tokenIdentifierCodec.encodeNested(value), - onNothing: () => this.nothingCodec.encodeNested() - }); - } - encodeTopLevel(value) { - return typesystem_1.onPrimitiveValueSelect(value, { - onBoolean: () => this.booleanCodec.encodeTopLevel(value), - onNumerical: () => this.numericalCodec.encodeTopLevel(value), - onAddress: () => this.addressCodec.encodeTopLevel(value), - onBytes: () => this.bytesCodec.encodeTopLevel(value), - onString: () => this.stringCodec.encodeTopLevel(value), - onH256: () => this.h256Codec.encodeTopLevel(value), - onTypeIdentifier: () => this.tokenIdentifierCodec.encodeTopLevel(value), - onNothing: () => this.nothingCodec.encodeTopLevel() - }); - } - }; - exports2.PrimitiveBinaryCodec = PrimitiveBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js -var require_list = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/list.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ListBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var constants_1 = require_constants2(); - var ListBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, type) { - let typeParameter = type.getFirstTypeParameter(); - let result = []; - let numItems = buffer.readUInt32BE(0); - this.binaryCodec.constraints.checkListLength(numItems); - let originalBuffer = buffer; - let offset = constants_1.SizeOfU32; - buffer = originalBuffer.slice(offset); - for (let i2 = 0; i2 < numItems; i2++) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); - result.push(decoded); - offset += decodedLength; - buffer = originalBuffer.slice(offset); - } - return [new typesystem_1.List(type, result), offset]; - } - decodeTopLevel(buffer, type) { - let typeParameter = type.getFirstTypeParameter(); - let result = []; - let originalBuffer = buffer; - let offset = 0; - while (buffer.length > 0) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); - result.push(decoded); - offset += decodedLength; - buffer = originalBuffer.slice(offset); - this.binaryCodec.constraints.checkListLength(result.length); - } - return new typesystem_1.List(type, result); - } - encodeNested(list) { - this.binaryCodec.constraints.checkListLength(list.getLength()); - let lengthBuffer = import_buffer.Buffer.alloc(constants_1.SizeOfU32); - lengthBuffer.writeUInt32BE(list.getLength()); - let itemsBuffers = []; - for (const item of list.getItems()) { - let itemBuffer = this.binaryCodec.encodeNested(item); - itemsBuffers.push(itemBuffer); - } - let buffer = import_buffer.Buffer.concat([lengthBuffer, ...itemsBuffers]); - return buffer; - } - encodeTopLevel(list) { - this.binaryCodec.constraints.checkListLength(list.getLength()); - let itemsBuffers = []; - for (const item of list.getItems()) { - let itemBuffer = this.binaryCodec.encodeNested(item); - itemsBuffers.push(itemBuffer); - } - let buffer = import_buffer.Buffer.concat(itemsBuffers); - return buffer; - } - }; - exports2.ListBinaryCodec = ListBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js -var require_fields2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/fields.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.FieldsBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var FieldsBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, fieldDefinitions) { - let fields = []; - let totalLength = 0; - for (const fieldDefinition of fieldDefinitions) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, fieldDefinition.type); - buffer = buffer.slice(decodedLength); - totalLength += decodedLength; - let field = new typesystem_1.Field(decoded, fieldDefinition.name); - fields.push(field); - } - return [fields, totalLength]; - } - encodeNested(fields) { - let buffers = []; - for (const field of fields) { - let fieldBuffer = this.binaryCodec.encodeNested(field.value); - buffers.push(fieldBuffer); - } - return import_buffer.Buffer.concat(buffers); - } - }; - exports2.FieldsBinaryCodec = FieldsBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js -var require_struct2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/struct.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.StructBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var fields_1 = require_fields2(); - var StructBinaryCodec = class { - constructor(binaryCodec) { - this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); - } - decodeTopLevel(buffer, type) { - let [decoded] = this.decodeNested(buffer, type); - return decoded; - } - decodeNested(buffer, type) { - let fieldDefinitions = type.getFieldsDefinitions(); - let [fields, offset] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); - let struct = new typesystem_1.Struct(type, fields); - return [struct, offset]; - } - encodeNested(struct) { - let fields = struct.getFields(); - let buffer = this.fieldsCodec.encodeNested(fields); - return buffer; - } - encodeTopLevel(struct) { - return this.encodeNested(struct); - } - }; - exports2.StructBinaryCodec = StructBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js -var require_enum2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/enum.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EnumBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var fields_1 = require_fields2(); - var EnumBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - this.fieldsCodec = new fields_1.FieldsBinaryCodec(binaryCodec); - } - decodeTopLevel(buffer, type) { - let [enumValue] = this.decodeNested(buffer, type); - return enumValue; - } - decodeNested(buffer, type) { - let [discriminant, lengthOfDiscriminant] = this.readDiscriminant(buffer); - buffer = buffer.slice(lengthOfDiscriminant); - let variant = type.getVariantByDiscriminant(discriminant); - let fieldDefinitions = variant.getFieldsDefinitions(); - let [fields, lengthOfFields] = this.fieldsCodec.decodeNested(buffer, fieldDefinitions); - let enumValue = new typesystem_1.EnumValue(type, variant, fields); - return [enumValue, lengthOfDiscriminant + lengthOfFields]; - } - readDiscriminant(buffer) { - let [value, length2] = this.binaryCodec.decodeNested(buffer, new typesystem_1.U8Type()); - let discriminant = value.valueOf(); - return [discriminant, length2]; - } - encodeNested(enumValue) { - let discriminant = new typesystem_1.U8Value(enumValue.discriminant); - let discriminantBuffer = this.binaryCodec.encodeNested(discriminant); - let fields = enumValue.getFields(); - let fieldsBuffer = this.fieldsCodec.encodeNested(fields); - return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); - } - encodeTopLevel(enumValue) { - let fields = enumValue.getFields(); - let hasFields = fields.length > 0; - let fieldsBuffer = this.fieldsCodec.encodeNested(fields); - let discriminant = new typesystem_1.U8Value(enumValue.discriminant); - let discriminantBuffer = hasFields ? this.binaryCodec.encodeNested(discriminant) : this.binaryCodec.encodeTopLevel(discriminant); - return import_buffer.Buffer.concat([discriminantBuffer, fieldsBuffer]); - } - }; - exports2.EnumBinaryCodec = EnumBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js -var require_tuple2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/tuple.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TupleBinaryCodec = void 0; - var struct_1 = require_struct2(); - var TupleBinaryCodec = class { - constructor(binaryCodec) { - this.structCodec = new struct_1.StructBinaryCodec(binaryCodec); - } - decodeTopLevel(buffer, type) { - return this.structCodec.decodeTopLevel(buffer, type); - } - decodeNested(buffer, type) { - return this.structCodec.decodeNested(buffer, type); - } - encodeNested(struct) { - return this.structCodec.encodeNested(struct); - } - encodeTopLevel(struct) { - return this.structCodec.encodeTopLevel(struct); - } - }; - exports2.TupleBinaryCodec = TupleBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js -var require_arrayVec = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/arrayVec.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArrayVecBinaryCodec = void 0; - var typesystem_1 = require_typesystem(); - var ArrayVecBinaryCodec = class { - constructor(binaryCodec) { - this.binaryCodec = binaryCodec; - } - decodeNested(buffer, type) { - let arrayLength = type.length; - let typeParameter = type.getFirstTypeParameter(); - let result = []; - let totalLength = 0; - for (let i2 = 0; i2 < arrayLength; i2++) { - let [decoded, decodedLength] = this.binaryCodec.decodeNested(buffer, typeParameter); - result.push(decoded); - totalLength += decodedLength; - buffer = buffer.slice(decodedLength); - } - return [new typesystem_1.ArrayVec(type, result), totalLength]; - } - decodeTopLevel(buffer, type) { - let [result, _4] = this.decodeNested(buffer, type); - return result; - } - encodeNested(array) { - let itemsBuffers = []; - for (const item of array.getItems()) { - let itemBuffer = this.binaryCodec.encodeNested(item); - itemsBuffers.push(itemBuffer); - } - return import_buffer.Buffer.concat(itemsBuffers); - } - encodeTopLevel(array) { - return this.encodeNested(array); - } - }; - exports2.ArrayVecBinaryCodec = ArrayVecBinaryCodec; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js -var require_binary = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binary.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinaryCodecConstraints = exports2.BinaryCodec = void 0; - var errors = __importStar2(require_errors()); - var typesystem_1 = require_typesystem(); - var utils_1 = require_utils2(); - var option_1 = require_option(); - var primitive_1 = require_primitive(); - var list_1 = require_list(); - var struct_1 = require_struct2(); - var enum_1 = require_enum2(); - var tuple_1 = require_tuple2(); - var arrayVec_1 = require_arrayVec(); - var BinaryCodec = class { - constructor(constraints = null) { - this.constraints = constraints || new BinaryCodecConstraints(); - this.optionCodec = new option_1.OptionValueBinaryCodec(this); - this.listCodec = new list_1.ListBinaryCodec(this); - this.arrayCodec = new arrayVec_1.ArrayVecBinaryCodec(this); - this.primitiveCodec = new primitive_1.PrimitiveBinaryCodec(this); - this.structCodec = new struct_1.StructBinaryCodec(this); - this.tupleCodec = new tuple_1.TupleBinaryCodec(this); - this.enumCodec = new enum_1.EnumBinaryCodec(this); - } - decodeTopLevel(buffer, type) { - this.constraints.checkBufferLength(buffer); - let typedValue = typesystem_1.onTypeSelect(type, { - onOption: () => this.optionCodec.decodeTopLevel(buffer, type.getFirstTypeParameter()), - onList: () => this.listCodec.decodeTopLevel(buffer, type), - onArray: () => this.arrayCodec.decodeTopLevel(buffer, type), - onPrimitive: () => this.primitiveCodec.decodeTopLevel(buffer, type), - onStruct: () => this.structCodec.decodeTopLevel(buffer, type), - onTuple: () => this.tupleCodec.decodeTopLevel(buffer, type), - onEnum: () => this.enumCodec.decodeTopLevel(buffer, type) - }); - return typedValue; - } - decodeNested(buffer, type) { - this.constraints.checkBufferLength(buffer); - let [typedResult, decodedLength] = typesystem_1.onTypeSelect(type, { - onOption: () => this.optionCodec.decodeNested(buffer, type.getFirstTypeParameter()), - onList: () => this.listCodec.decodeNested(buffer, type), - onArray: () => this.arrayCodec.decodeNested(buffer, type), - onPrimitive: () => this.primitiveCodec.decodeNested(buffer, type), - onStruct: () => this.structCodec.decodeNested(buffer, type), - onTuple: () => this.tupleCodec.decodeNested(buffer, type), - onEnum: () => this.enumCodec.decodeNested(buffer, type) - }); - return [typedResult, decodedLength]; - } - encodeNested(typedValue) { - utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); - return typesystem_1.onTypedValueSelect(typedValue, { - onPrimitive: () => this.primitiveCodec.encodeNested(typedValue), - onOption: () => this.optionCodec.encodeNested(typedValue), - onList: () => this.listCodec.encodeNested(typedValue), - onArray: () => this.arrayCodec.encodeNested(typedValue), - onStruct: () => this.structCodec.encodeNested(typedValue), - onTuple: () => this.tupleCodec.encodeNested(typedValue), - onEnum: () => this.enumCodec.encodeNested(typedValue) - }); - } - encodeTopLevel(typedValue) { - utils_1.guardTrue(typedValue.getType().getCardinality().isSingular(), "singular cardinality, thus encodable type"); - return typesystem_1.onTypedValueSelect(typedValue, { - onPrimitive: () => this.primitiveCodec.encodeTopLevel(typedValue), - onOption: () => this.optionCodec.encodeTopLevel(typedValue), - onList: () => this.listCodec.encodeTopLevel(typedValue), - onArray: () => this.arrayCodec.encodeTopLevel(typedValue), - onStruct: () => this.structCodec.encodeTopLevel(typedValue), - onTuple: () => this.tupleCodec.encodeTopLevel(typedValue), - onEnum: () => this.enumCodec.encodeTopLevel(typedValue) - }); - } - }; - exports2.BinaryCodec = BinaryCodec; - var BinaryCodecConstraints = class { - constructor(init) { - this.maxBufferLength = init?.maxBufferLength || 256e3; - this.maxListLength = init?.maxListLength || 128e3; - } - checkBufferLength(buffer) { - if (buffer.length > this.maxBufferLength) { - throw new errors.ErrCodec(`Buffer too large: ${buffer.length} > ${this.maxBufferLength}`); - } - } - /** - * This constraint avoids computer-freezing decode bugs (e.g. due to invalid ABI or struct definitions). - */ - checkListLength(length2) { - if (length2 > this.maxListLength) { - throw new errors.ErrCodec(`List too large: ${length2} > ${this.maxListLength}`); - } - } - }; - exports2.BinaryCodecConstraints = BinaryCodecConstraints; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js -var require_binaryCodecUtils = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/binaryCodecUtils.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decodeBigNumber = exports2.decodeString = exports2.decodeBool = exports2.decodeUnsignedNumber = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var typesystem_1 = require_typesystem(); - var binary_1 = require_binary(); - var Codec2 = new binary_1.BinaryCodec(); - function decodeUnsignedNumber(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); - let raw = Number(value.valueOf()); - return raw; - } - exports2.decodeUnsignedNumber = decodeUnsignedNumber; - function decodeBool(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BooleanType()); - let raw = Boolean(value.valueOf()); - return raw; - } - exports2.decodeBool = decodeBool; - function decodeString(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BytesType()); - let raw = String(value.valueOf()); - return raw; - } - exports2.decodeString = decodeString; - function decodeBigNumber(buffer) { - let value = Codec2.decodeTopLevel(buffer, new typesystem_1.BigUIntType()); - let raw = new bignumber_js_1.default(value.valueOf()); - return raw; - } - exports2.decodeBigNumber = decodeBigNumber; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js -var require_codec2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codec/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_binary(), exports2); - __exportStar2(require_binaryCodecUtils(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js -var require_argSerializer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/argSerializer.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArgSerializer = void 0; - var constants_1 = require_constants(); - var codec_1 = require_codec2(); - var typesystem_1 = require_typesystem(); - var algebraic_1 = require_algebraic(); - var composite_1 = require_composite(); - var variadic_1 = require_variadic(); - var defaultArgSerializerOptions = { - codec: new codec_1.BinaryCodec() - }; - var ArgSerializer = class { - constructor(options) { - options = { ...defaultArgSerializerOptions, ...options }; - this.codec = options.codec; - } - /** - * Reads typed values from an arguments string (e.g. aa@bb@@cc), given parameter definitions. - */ - stringToValues(joinedString, parameters) { - let buffers = this.stringToBuffers(joinedString); - let values = this.buffersToValues(buffers, parameters); - return values; - } - /** - * Reads raw buffers from an arguments string (e.g. aa@bb@@cc). - */ - stringToBuffers(joinedString) { - return joinedString.split(constants_1.ARGUMENTS_SEPARATOR).map((item) => import_buffer.Buffer.from(item, "hex")); - } - /** - * Decodes a set of buffers into a set of typed values, given parameter definitions. - */ - buffersToValues(buffers, parameters) { - const self2 = this; - buffers = buffers || []; - let values = []; - let bufferIndex = 0; - let numBuffers = buffers.length; - for (let i2 = 0; i2 < parameters.length; i2++) { - let parameter = parameters[i2]; - let type = parameter.type; - let value = readValue(type); - values.push(value); - } - function readValue(type) { - if (type.hasExactClass(algebraic_1.OptionalType.ClassName)) { - const typedValue2 = readValue(type.getFirstTypeParameter()); - return new algebraic_1.OptionalValue(type, typedValue2); - } - if (type.hasExactClass(variadic_1.VariadicType.ClassName)) { - return readVariadicValue(type); - } - if (type.hasExactClass(composite_1.CompositeType.ClassName)) { - const typedValues = []; - for (const typeParameter of type.getTypeParameters()) { - typedValues.push(readValue(typeParameter)); - } - return new composite_1.CompositeValue(type, typedValues); - } - const typedValue = decodeNextBuffer(type); - return typedValue; - } - function readVariadicValue(type) { - const variadicType = type; - const typedValues = []; - if (variadicType.isCounted) { - const count = readValue(new typesystem_1.U32Type()).valueOf().toNumber(); - for (let i2 = 0; i2 < count; i2++) { - typedValues.push(readValue(type.getFirstTypeParameter())); - } - } else { - while (!hasReachedTheEnd()) { - typedValues.push(readValue(type.getFirstTypeParameter())); - } - } - return new variadic_1.VariadicValue(variadicType, typedValues); - } - function decodeNextBuffer(type) { - if (hasReachedTheEnd()) { - return null; - } - let buffer = buffers[bufferIndex++]; - let decodedValue = self2.codec.decodeTopLevel(buffer, type); - return decodedValue; - } - function hasReachedTheEnd() { - return bufferIndex >= numBuffers; - } - return values; - } - /** - * Serializes a set of typed values into an arguments string (e.g. aa@bb@@cc). - */ - valuesToString(values) { - let strings = this.valuesToStrings(values); - let argumentsString = strings.join(constants_1.ARGUMENTS_SEPARATOR); - let count = strings.length; - return { argumentsString, count }; - } - /** - * Serializes a set of typed values into a set of strings. - */ - valuesToStrings(values) { - let buffers = this.valuesToBuffers(values); - let strings = buffers.map((buffer) => buffer.toString("hex")); - return strings; - } - /** - * Serializes a set of typed values into a set of strings buffers. - * Variadic types and composite types might result into none, one or more buffers. - */ - valuesToBuffers(values) { - const self2 = this; - const buffers = []; - for (const value of values) { - handleValue(value); - } - function handleValue(value) { - if (value.hasExactClass(algebraic_1.OptionalValue.ClassName)) { - const valueAsOptional = value; - if (valueAsOptional.isSet()) { - handleValue(valueAsOptional.getTypedValue()); - } - return; - } - if (value.hasExactClass(variadic_1.VariadicValue.ClassName)) { - handleVariadicValue(value); - return; - } - if (value.hasExactClass(composite_1.CompositeValue.ClassName)) { - const valueAsComposite = value; - for (const item of valueAsComposite.getItems()) { - handleValue(item); - } - return; - } - const buffer = self2.codec.encodeTopLevel(value); - buffers.push(buffer); - } - function handleVariadicValue(value) { - const variadicType = value.getType(); - if (variadicType.isCounted) { - const countValue = new typesystem_1.U32Value(value.getItems().length); - buffers.push(self2.codec.encodeTopLevel(countValue)); - } - for (const item of value.getItems()) { - handleValue(item); - } - } - return buffers; - } - }; - exports2.ArgSerializer = ArgSerializer; - } -}); - -// node_modules/nanoassert/index.js -var require_nanoassert = __commonJS({ - "node_modules/nanoassert/index.js"(exports2, module2) { - init_shim(); - assert.notEqual = notEqual; - assert.notOk = notOk; - assert.equal = equal; - assert.ok = assert; - module2.exports = assert; - function equal(a3, b4, m3) { - assert(a3 == b4, m3); - } - function notEqual(a3, b4, m3) { - assert(a3 != b4, m3); - } - function notOk(t, m3) { - assert(!t, m3); - } - function assert(t, m3) { - if (!t) - throw new Error(m3 || "AssertionError"); - } - } -}); - -// node_modules/blake2b-wasm/blake2b.js -var require_blake2b = __commonJS({ - "node_modules/blake2b-wasm/blake2b.js"(exports2, module2) { - init_shim(); - module2.exports = loadWebAssembly; - loadWebAssembly.supported = typeof WebAssembly !== "undefined"; - function loadWebAssembly(opts) { - if (!loadWebAssembly.supported) - return null; - var imp = opts && opts.imports; - var wasm = toUint8Array("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"); - var ready = null; - var mod2 = { - buffer: wasm, - memory: null, - exports: null, - realloc, - onload - }; - onload(function() { - }); - return mod2; - function realloc(size) { - mod2.exports.memory.grow(Math.ceil(Math.abs(size - mod2.memory.length) / 65536)); - mod2.memory = new Uint8Array(mod2.exports.memory.buffer); - } - function onload(cb) { - if (mod2.exports) - return cb(); - if (ready) { - ready.then(cb.bind(null, null)).catch(cb); - return; - } - try { - if (opts && opts.async) - throw new Error("async"); - setup({ instance: new WebAssembly.Instance(new WebAssembly.Module(wasm), imp) }); - } catch (err) { - ready = WebAssembly.instantiate(wasm, imp).then(setup); - } - onload(cb); - } - function setup(w4) { - mod2.exports = w4.instance.exports; - mod2.memory = mod2.exports.memory && mod2.exports.memory.buffer && new Uint8Array(mod2.exports.memory.buffer); - } - } - function toUint8Array(s2) { - if (typeof atob === "function") - return new Uint8Array(atob(s2).split("").map(charCodeAt)); - return new (require_buffer2()).Buffer(s2, "base64"); - } - function charCodeAt(c4) { - return c4.charCodeAt(0); - } - } -}); - -// node_modules/blake2b-wasm/index.js -var require_blake2b_wasm = __commonJS({ - "node_modules/blake2b-wasm/index.js"(exports2, module2) { - init_shim(); - var assert = require_nanoassert(); - var wasm = require_blake2b()(); - var head = 64; - var freeList = []; - module2.exports = Blake2b; - var BYTES_MIN = module2.exports.BYTES_MIN = 16; - var BYTES_MAX = module2.exports.BYTES_MAX = 64; - var BYTES = module2.exports.BYTES = 32; - var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; - var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; - var KEYBYTES = module2.exports.KEYBYTES = 32; - var SALTBYTES = module2.exports.SALTBYTES = 16; - var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; - function Blake2b(digestLength, key, salt, personal, noAssert) { - if (!(this instanceof Blake2b)) - return new Blake2b(digestLength, key, salt, personal, noAssert); - if (!(wasm && wasm.exports)) - throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)"); - if (!digestLength) - digestLength = 32; - if (noAssert !== true) { - assert(digestLength >= BYTES_MIN, "digestLength must be at least " + BYTES_MIN + ", was given " + digestLength); - assert(digestLength <= BYTES_MAX, "digestLength must be at most " + BYTES_MAX + ", was given " + digestLength); - if (key != null) - assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); - if (key != null) - assert(key.length <= KEYBYTES_MAX, "key must be at least " + KEYBYTES_MAX + ", was given " + key.length); - if (salt != null) - assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); - if (personal != null) - assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); - } - if (!freeList.length) { - freeList.push(head); - head += 216; - } - this.digestLength = digestLength; - this.finalized = false; - this.pointer = freeList.pop(); - wasm.memory.fill(0, 0, 64); - wasm.memory[0] = this.digestLength; - wasm.memory[1] = key ? key.length : 0; - wasm.memory[2] = 1; - wasm.memory[3] = 1; - if (salt) - wasm.memory.set(salt, 32); - if (personal) - wasm.memory.set(personal, 48); - if (this.pointer + 216 > wasm.memory.length) - wasm.realloc(this.pointer + 216); - wasm.exports.blake2b_init(this.pointer, this.digestLength); - if (key) { - this.update(key); - wasm.memory.fill(0, head, head + key.length); - wasm.memory[this.pointer + 200] = 128; - } - } - Blake2b.prototype.update = function(input) { - assert(this.finalized === false, "Hash instance finalized"); - assert(input, "input must be TypedArray or Buffer"); - if (head + input.length > wasm.memory.length) - wasm.realloc(head + input.length); - wasm.memory.set(input, head); - wasm.exports.blake2b_update(this.pointer, head, head + input.length); - return this; - }; - Blake2b.prototype.digest = function(enc) { - assert(this.finalized === false, "Hash instance finalized"); - this.finalized = true; - freeList.push(this.pointer); - wasm.exports.blake2b_final(this.pointer); - if (!enc || enc === "binary") { - return wasm.memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength); - } - if (enc === "hex") { - return hexSlice(wasm.memory, this.pointer + 128, this.digestLength); - } - assert(enc.length >= this.digestLength, "input must be TypedArray or Buffer"); - for (var i2 = 0; i2 < this.digestLength; i2++) { - enc[i2] = wasm.memory[this.pointer + 128 + i2]; - } - return enc; - }; - Blake2b.prototype.final = Blake2b.prototype.digest; - Blake2b.WASM = wasm && wasm.buffer; - Blake2b.SUPPORTED = typeof WebAssembly !== "undefined"; - Blake2b.ready = function(cb) { - if (!cb) - cb = noop; - if (!wasm) - return cb(new Error("WebAssembly not supported")); - var p3 = new Promise(function(reject, resolve) { - wasm.onload(function(err) { - if (err) - resolve(); - else - reject(); - cb(err); - }); - }); - return p3; - }; - Blake2b.prototype.ready = Blake2b.ready; - function noop() { - } - function hexSlice(buf, start, len) { - var str = ""; - for (var i2 = 0; i2 < len; i2++) - str += toHex(buf[start + i2]); - return str; - } - function toHex(n3) { - if (n3 < 16) - return "0" + n3.toString(16); - return n3.toString(16); - } - } -}); - -// node_modules/blake2b/index.js -var require_blake2b2 = __commonJS({ - "node_modules/blake2b/index.js"(exports2, module2) { - init_shim(); - var assert = require_nanoassert(); - var b2wasm = require_blake2b_wasm(); - function ADD64AA(v3, a3, b4) { - var o0 = v3[a3] + v3[b4]; - var o1 = v3[a3 + 1] + v3[b4 + 1]; - if (o0 >= 4294967296) { - o1++; - } - v3[a3] = o0; - v3[a3 + 1] = o1; - } - function ADD64AC(v3, a3, b0, b1) { - var o0 = v3[a3] + b0; - if (b0 < 0) { - o0 += 4294967296; - } - var o1 = v3[a3 + 1] + b1; - if (o0 >= 4294967296) { - o1++; - } - v3[a3] = o0; - v3[a3 + 1] = o1; - } - function B2B_GET32(arr, i2) { - return arr[i2] ^ arr[i2 + 1] << 8 ^ arr[i2 + 2] << 16 ^ arr[i2 + 3] << 24; - } - function B2B_G(a3, b4, c4, d3, ix, iy) { - var x0 = m3[ix]; - var x1 = m3[ix + 1]; - var y0 = m3[iy]; - var y1 = m3[iy + 1]; - ADD64AA(v2, a3, b4); - ADD64AC(v2, a3, x0, x1); - var xor0 = v2[d3] ^ v2[a3]; - var xor1 = v2[d3 + 1] ^ v2[a3 + 1]; - v2[d3] = xor1; - v2[d3 + 1] = xor0; - ADD64AA(v2, c4, d3); - xor0 = v2[b4] ^ v2[c4]; - xor1 = v2[b4 + 1] ^ v2[c4 + 1]; - v2[b4] = xor0 >>> 24 ^ xor1 << 8; - v2[b4 + 1] = xor1 >>> 24 ^ xor0 << 8; - ADD64AA(v2, a3, b4); - ADD64AC(v2, a3, y0, y1); - xor0 = v2[d3] ^ v2[a3]; - xor1 = v2[d3 + 1] ^ v2[a3 + 1]; - v2[d3] = xor0 >>> 16 ^ xor1 << 16; - v2[d3 + 1] = xor1 >>> 16 ^ xor0 << 16; - ADD64AA(v2, c4, d3); - xor0 = v2[b4] ^ v2[c4]; - xor1 = v2[b4 + 1] ^ v2[c4 + 1]; - v2[b4] = xor1 >>> 31 ^ xor0 << 1; - v2[b4 + 1] = xor0 >>> 31 ^ xor1 << 1; - } - var BLAKE2B_IV32 = new Uint32Array([ - 4089235720, - 1779033703, - 2227873595, - 3144134277, - 4271175723, - 1013904242, - 1595750129, - 2773480762, - 2917565137, - 1359893119, - 725511199, - 2600822924, - 4215389547, - 528734635, - 327033209, - 1541459225 - ]); - var SIGMA8 = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - 11, - 8, - 12, - 0, - 5, - 2, - 15, - 13, - 10, - 14, - 3, - 6, - 7, - 1, - 9, - 4, - 7, - 9, - 3, - 1, - 13, - 12, - 11, - 14, - 2, - 6, - 5, - 10, - 4, - 0, - 15, - 8, - 9, - 0, - 5, - 7, - 2, - 4, - 10, - 15, - 14, - 1, - 11, - 12, - 6, - 8, - 3, - 13, - 2, - 12, - 6, - 10, - 0, - 11, - 8, - 3, - 4, - 13, - 7, - 5, - 15, - 14, - 1, - 9, - 12, - 5, - 1, - 15, - 14, - 13, - 4, - 10, - 0, - 7, - 6, - 3, - 9, - 2, - 8, - 11, - 13, - 11, - 7, - 14, - 12, - 1, - 3, - 9, - 5, - 0, - 15, - 4, - 8, - 6, - 2, - 10, - 6, - 15, - 14, - 9, - 11, - 3, - 0, - 8, - 12, - 2, - 13, - 7, - 1, - 4, - 10, - 5, - 10, - 2, - 8, - 4, - 7, - 6, - 1, - 5, - 15, - 11, - 9, - 14, - 3, - 12, - 13, - 0, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3 - ]; - var SIGMA82 = new Uint8Array(SIGMA8.map(function(x3) { - return x3 * 2; - })); - var v2 = new Uint32Array(32); - var m3 = new Uint32Array(32); - function blake2bCompress(ctx, last) { - var i2 = 0; - for (i2 = 0; i2 < 16; i2++) { - v2[i2] = ctx.h[i2]; - v2[i2 + 16] = BLAKE2B_IV32[i2]; - } - v2[24] = v2[24] ^ ctx.t; - v2[25] = v2[25] ^ ctx.t / 4294967296; - if (last) { - v2[28] = ~v2[28]; - v2[29] = ~v2[29]; - } - for (i2 = 0; i2 < 32; i2++) { - m3[i2] = B2B_GET32(ctx.b, 4 * i2); - } - for (i2 = 0; i2 < 12; i2++) { - B2B_G(0, 8, 16, 24, SIGMA82[i2 * 16 + 0], SIGMA82[i2 * 16 + 1]); - B2B_G(2, 10, 18, 26, SIGMA82[i2 * 16 + 2], SIGMA82[i2 * 16 + 3]); - B2B_G(4, 12, 20, 28, SIGMA82[i2 * 16 + 4], SIGMA82[i2 * 16 + 5]); - B2B_G(6, 14, 22, 30, SIGMA82[i2 * 16 + 6], SIGMA82[i2 * 16 + 7]); - B2B_G(0, 10, 20, 30, SIGMA82[i2 * 16 + 8], SIGMA82[i2 * 16 + 9]); - B2B_G(2, 12, 22, 24, SIGMA82[i2 * 16 + 10], SIGMA82[i2 * 16 + 11]); - B2B_G(4, 14, 16, 26, SIGMA82[i2 * 16 + 12], SIGMA82[i2 * 16 + 13]); - B2B_G(6, 8, 18, 28, SIGMA82[i2 * 16 + 14], SIGMA82[i2 * 16 + 15]); - } - for (i2 = 0; i2 < 16; i2++) { - ctx.h[i2] = ctx.h[i2] ^ v2[i2] ^ v2[i2 + 16]; - } - } - var parameter_block = new Uint8Array([ - 0, - 0, - 0, - 0, - // 0: outlen, keylen, fanout, depth - 0, - 0, - 0, - 0, - // 4: leaf length, sequential mode - 0, - 0, - 0, - 0, - // 8: node offset - 0, - 0, - 0, - 0, - // 12: node offset - 0, - 0, - 0, - 0, - // 16: node depth, inner length, rfu - 0, - 0, - 0, - 0, - // 20: rfu - 0, - 0, - 0, - 0, - // 24: rfu - 0, - 0, - 0, - 0, - // 28: rfu - 0, - 0, - 0, - 0, - // 32: salt - 0, - 0, - 0, - 0, - // 36: salt - 0, - 0, - 0, - 0, - // 40: salt - 0, - 0, - 0, - 0, - // 44: salt - 0, - 0, - 0, - 0, - // 48: personal - 0, - 0, - 0, - 0, - // 52: personal - 0, - 0, - 0, - 0, - // 56: personal - 0, - 0, - 0, - 0 - // 60: personal - ]); - function Blake2b(outlen, key, salt, personal) { - parameter_block.fill(0); - this.b = new Uint8Array(128); - this.h = new Uint32Array(16); - this.t = 0; - this.c = 0; - this.outlen = outlen; - parameter_block[0] = outlen; - if (key) - parameter_block[1] = key.length; - parameter_block[2] = 1; - parameter_block[3] = 1; - if (salt) - parameter_block.set(salt, 32); - if (personal) - parameter_block.set(personal, 48); - for (var i2 = 0; i2 < 16; i2++) { - this.h[i2] = BLAKE2B_IV32[i2] ^ B2B_GET32(parameter_block, i2 * 4); - } - if (key) { - blake2bUpdate(this, key); - this.c = 128; - } - } - Blake2b.prototype.update = function(input) { - assert(input != null, "input must be Uint8Array or Buffer"); - blake2bUpdate(this, input); - return this; - }; - Blake2b.prototype.digest = function(out) { - var buf = !out || out === "binary" || out === "hex" ? new Uint8Array(this.outlen) : out; - assert(buf.length >= this.outlen, "out must have at least outlen bytes of space"); - blake2bFinal(this, buf); - if (out === "hex") - return hexSlice(buf); - return buf; - }; - Blake2b.prototype.final = Blake2b.prototype.digest; - Blake2b.ready = function(cb) { - b2wasm.ready(function() { - cb(); - }); - }; - function blake2bUpdate(ctx, input) { - for (var i2 = 0; i2 < input.length; i2++) { - if (ctx.c === 128) { - ctx.t += ctx.c; - blake2bCompress(ctx, false); - ctx.c = 0; - } - ctx.b[ctx.c++] = input[i2]; - } - } - function blake2bFinal(ctx, out) { - ctx.t += ctx.c; - while (ctx.c < 128) { - ctx.b[ctx.c++] = 0; - } - blake2bCompress(ctx, true); - for (var i2 = 0; i2 < ctx.outlen; i2++) { - out[i2] = ctx.h[i2 >> 2] >> 8 * (i2 & 3); - } - return out; - } - function hexSlice(buf) { - var str = ""; - for (var i2 = 0; i2 < buf.length; i2++) - str += toHex(buf[i2]); - return str; - } - function toHex(n3) { - if (n3 < 16) - return "0" + n3.toString(16); - return n3.toString(16); - } - var Proto = Blake2b; - module2.exports = function createHash(outlen, key, salt, personal, noAssert) { - if (noAssert !== true) { - assert(outlen >= BYTES_MIN, "outlen must be at least " + BYTES_MIN + ", was given " + outlen); - assert(outlen <= BYTES_MAX, "outlen must be at most " + BYTES_MAX + ", was given " + outlen); - if (key != null) - assert(key.length >= KEYBYTES_MIN, "key must be at least " + KEYBYTES_MIN + ", was given " + key.length); - if (key != null) - assert(key.length <= KEYBYTES_MAX, "key must be at most " + KEYBYTES_MAX + ", was given " + key.length); - if (salt != null) - assert(salt.length === SALTBYTES, "salt must be exactly " + SALTBYTES + ", was given " + salt.length); - if (personal != null) - assert(personal.length === PERSONALBYTES, "personal must be exactly " + PERSONALBYTES + ", was given " + personal.length); - } - return new Proto(outlen, key, salt, personal); - }; - module2.exports.ready = function(cb) { - b2wasm.ready(function() { - cb(); - }); - }; - module2.exports.WASM_SUPPORTED = b2wasm.SUPPORTED; - module2.exports.WASM_LOADED = false; - var BYTES_MIN = module2.exports.BYTES_MIN = 16; - var BYTES_MAX = module2.exports.BYTES_MAX = 64; - var BYTES = module2.exports.BYTES = 32; - var KEYBYTES_MIN = module2.exports.KEYBYTES_MIN = 16; - var KEYBYTES_MAX = module2.exports.KEYBYTES_MAX = 64; - var KEYBYTES = module2.exports.KEYBYTES = 32; - var SALTBYTES = module2.exports.SALTBYTES = 16; - var PERSONALBYTES = module2.exports.PERSONALBYTES = 16; - b2wasm.ready(function(err) { - if (!err) { - module2.exports.WASM_LOADED = true; - Proto = b2wasm; - } - }); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/code.js -var require_code = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/code.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Code = void 0; - var createHasher = require_blake2b2(); - var CODE_HASH_LENGTH = 32; - var Code = class _Code { - constructor(hex) { - this.hex = hex; - } - /** - * Creates a Code object from a buffer (sequence of bytes). - */ - static fromBuffer(code2) { - return new _Code(code2.toString("hex")); - } - /** - * Creates a Code object from a hex-encoded string. - */ - static fromHex(hex) { - return new _Code(hex); - } - /** - * Returns the bytecode as a hex-encoded string. - */ - toString() { - return this.hex; - } - valueOf() { - return import_buffer.Buffer.from(this.hex, "hex"); - } - computeHash() { - const hash = createHasher(CODE_HASH_LENGTH).update(this.valueOf()).digest(); - return import_buffer.Buffer.from(hash); - } - }; - exports2.Code = Code; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js -var require_codeMetadata2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/codeMetadata.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.CodeMetadata = void 0; - var CodeMetadata = class _CodeMetadata { - /** - * Creates a metadata object. By default, set the `upgradeable` attribute, and uset all others. - * - * @param upgradeable Whether the contract is upgradeable - * @param readable Whether other contracts can read this contract's data (without calling one of its pure functions) - * @param payable Whether the contract is payable - * @param payableBySc Whether the contract is payable by other smart contracts - */ - constructor(upgradeable = true, readable = false, payable = false, payableBySc = false) { - this.upgradeable = upgradeable; - this.readable = readable; - this.payable = payable; - this.payableBySc = payableBySc; - } - static fromBytes(bytes) { - return _CodeMetadata.fromBuffer(import_buffer.Buffer.from(bytes)); - } - /** - * Creates a metadata object from a buffer. - */ - static fromBuffer(buffer) { - if (buffer.length < this.codeMetadataLength) { - throw new Error("Buffer is too short."); - } - const byteZero = buffer[0]; - const byteOne = buffer[1]; - const upgradeable = (byteZero & _CodeMetadata.ByteZero.Upgradeable) !== 0; - const readable = (byteZero & _CodeMetadata.ByteZero.Readable) !== 0; - const payable = (byteOne & _CodeMetadata.ByteOne.Payable) !== 0; - const payableBySc = (byteOne & _CodeMetadata.ByteOne.PayableBySc) !== 0; - return new _CodeMetadata(upgradeable, readable, payable, payableBySc); - } - /** - * Adjust the metadata (the `upgradeable` attribute), when preparing the deployment transaction. - */ - toggleUpgradeable(value) { - this.upgradeable = value; - } - /** - * Adjust the metadata (the `readable` attribute), when preparing the deployment transaction. - */ - toggleReadable(value) { - this.readable = value; - } - /** - * Adjust the metadata (the `payable` attribute), when preparing the deployment transaction. - */ - togglePayable(value) { - this.payable = value; - } - /** - * Adjust the metadata (the `payableBySc` attribute), when preparing the deployment transaction. - */ - togglePayableBySc(value) { - this.payableBySc = value; - } - /** - * Converts the metadata to the protocol-friendly representation. - */ - toBuffer() { - let byteZero = 0; - let byteOne = 0; - if (this.upgradeable) { - byteZero |= _CodeMetadata.ByteZero.Upgradeable; - } - if (this.readable) { - byteZero |= _CodeMetadata.ByteZero.Readable; - } - if (this.payable) { - byteOne |= _CodeMetadata.ByteOne.Payable; - } - if (this.payableBySc) { - byteOne |= _CodeMetadata.ByteOne.PayableBySc; - } - return import_buffer.Buffer.from([byteZero, byteOne]); - } - /** - * Converts the metadata to a hex-encoded string. - */ - toString() { - return this.toBuffer().toString("hex"); - } - /** - * Converts the metadata to a pretty, plain JavaScript object. - */ - toJSON() { - return { - upgradeable: this.upgradeable, - readable: this.readable, - payable: this.payable, - payableBySc: this.payableBySc - }; - } - equals(other) { - return this.upgradeable == other.upgradeable && this.readable == other.readable && this.payable == other.payable && this.payableBySc == other.payableBySc; - } - }; - exports2.CodeMetadata = CodeMetadata; - CodeMetadata.codeMetadataLength = 2; - CodeMetadata.ByteZero = { - Upgradeable: 1, - Reserved2: 2, - Readable: 4 - }; - CodeMetadata.ByteOne = { - Reserved1: 1, - Payable: 2, - PayableBySc: 4 - }; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/function.js -var require_function = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/function.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractFunction = void 0; - var errors = __importStar2(require_errors()); - var ContractFunction = class _ContractFunction { - /** - * Creates a ContractFunction object, given its name. - * - * @param name the name of the function - */ - constructor(name2) { - this.name = name2; - if (name2 == null) { - throw new errors.ErrInvalidFunctionName(); - } - } - /** - * Null-object pattern: creates an empty ContractFunction object. - */ - static none() { - return new _ContractFunction("untitled"); - } - /** - * Returns the name of the function. - */ - toString() { - return this.name; - } - valueOf() { - return this.name; - } - }; - exports2.ContractFunction = ContractFunction; - } -}); - -// node_modules/@multiversx/sdk-core/out/compatibility.js -var require_compatibility = __commonJS({ - "node_modules/@multiversx/sdk-core/out/compatibility.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Compatibility = void 0; - var address_1 = require_address(); - var Compatibility = class { - /** - * For internal use only. - */ - static guardAddressIsSetAndNonZero(address, context, resolution) { - if (!address || address.bech32() == "") { - console.warn(`${context}: address should be set; ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); - } else if (address.bech32() == address_1.Address.Zero().bech32()) { - console.warn(`${context}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${resolution}. In the future, this will throw an exception instead of emitting a WARN.`); - } - } - }; - exports2.Compatibility = Compatibility; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionPayload.js -var require_transactionPayload = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionPayload.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionPayload = void 0; - var TransactionPayload = class _TransactionPayload { - /** - * Creates a TransactionPayload from a utf-8 string or from a buffer. - */ - constructor(data) { - this.data = import_buffer.Buffer.from(data || []); - } - /** - * Creates a TransactionPayload from a base-64 encoded string. - */ - static fromEncoded(encoded) { - if (!encoded) { - return new _TransactionPayload(""); - } - let decoded = import_buffer.Buffer.from(encoded, "base64").toString(); - return new _TransactionPayload(decoded); - } - /** - * Returns whether the "data" is void. - */ - isEmpty() { - return this.data.length == 0; - } - /** - * Returns the base-64 representation of the data. - */ - encoded() { - return this.data.toString("base64"); - } - /** - * Returns the data as a buffer. - */ - valueOf() { - return this.data; - } - toString() { - return this.data.toString(); - } - getEncodedArguments() { - return this.toString().split("@"); - } - getRawArguments() { - return this.getEncodedArguments().map((argument) => import_buffer.Buffer.from(argument, "hex")); - } - /** - * Returns the length of the data. - */ - length() { - return import_buffer.Buffer.from(this.data).length; - } - }; - exports2.TransactionPayload = TransactionPayload; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js -var require_transactionBuilder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionBuilder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionBuilder = void 0; - var constants_1 = require_constants(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var TransactionBuilder = class { - constructor(options) { - this.config = options.config; - this.sender = options.sender; - this.receiver = options.receiver; - this.dataParts = options.dataParts; - this.providedGasLimit = options.gasLimit; - this.addDataMovementGas = options.addDataMovementGas; - this.amount = options.amount; - } - computeGasLimit(payload) { - if (!this.addDataMovementGas) { - return this.providedGasLimit; - } - const dataMovementGas = this.config.minGasLimit + this.config.gasLimitPerByte * BigInt(payload.length()); - const gasLimit = dataMovementGas + this.providedGasLimit; - return gasLimit; - } - buildTransactionPayload() { - const data = this.dataParts.join(constants_1.ARGUMENTS_SEPARATOR); - return new transactionPayload_1.TransactionPayload(data); - } - build() { - const data = this.buildTransactionPayload(); - const gasLimit = this.computeGasLimit(data); - return new transaction_1.Transaction({ - sender: this.sender.bech32(), - receiver: this.receiver.bech32(), - gasLimit, - value: this.amount || 0n, - data: data.valueOf(), - chainID: this.config.chainID - }); - } - }; - exports2.TransactionBuilder = TransactionBuilder; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js -var require_delegationTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/delegationTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DelegationTransactionsFactory = void 0; - var address_1 = require_address(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var transactionBuilder_1 = require_transactionBuilder(); - var DelegationTransactionsFactory = class { - constructor(options) { - this.config = options.config; - this.argSerializer = new smartcontracts_1.ArgSerializer(); - } - createTransactionForNewDelegationContract(options) { - const dataParts = [ - "createNewDelegationContract", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.BigUIntValue(options.totalDelegationCap), - new smartcontracts_1.BigUIntValue(options.serviceFee) - ]) - ]; - const executionGasLimit = this.config.gasLimitCreateDelegationContract + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.DELEGATION_MANAGER_SC_ADDRESS), - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true, - amount: options.amount - }).build(); - } - createTransactionForAddingNodes(options) { - if (options.publicKeys.length !== options.signedMessages.length) { - throw new errors_1.Err("The number of public keys should match the number of signed messages"); - } - const signedMessagesAsTypedValues = options.signedMessages.map((message) => new smartcontracts_1.BytesValue(import_buffer.Buffer.from(message))); - const messagesAsStrings = this.argSerializer.valuesToStrings(signedMessagesAsTypedValues); - const numNodes = options.publicKeys.length; - const dataParts = ["addNodes"]; - for (let i2 = 0; i2 < numNodes; i2++) { - dataParts.push(...[options.publicKeys[i2].hex(), messagesAsStrings[i2]]); - } - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), - addDataMovementGas: true - }).build(); - } - createTransactionForRemovingNodes(options) { - const dataParts = ["removeNodes"]; - for (const key of options.publicKeys) { - dataParts.push(key.hex()); - } - const numNodes = options.publicKeys.length; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), - addDataMovementGas: true - }).build(); - } - createTransactionForStakingNodes(options) { - let dataParts = ["stakeNodes"]; - for (const key of options.publicKeys) { - dataParts = dataParts.concat(key.hex()); - } - const numNodes = options.publicKeys.length; - const additionalGasForAllNodes = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode; - const executionGasLimit = additionalGasForAllNodes + this.config.gasLimitStake + this.config.gasLimitDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnbondingNodes(options) { - let dataParts = ["unBondNodes"]; - for (const key of options.publicKeys) { - dataParts = dataParts.concat(key.hex()); - } - const numNodes = options.publicKeys.length; - const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnbond + this.config.gasLimitDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnstakingNodes(options) { - let dataParts = ["unStakeNodes"]; - for (const key of options.publicKeys) { - dataParts = dataParts.concat(key.hex()); - } - const numNodes = options.publicKeys.length; - const executionGasLimit = BigInt(numNodes) * this.config.additionalGasLimitPerValidatorNode + this.config.gasLimitUnstake + this.config.gasLimitDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: executionGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnjailingNodes(options) { - const dataParts = ["unJailNodes"]; - for (const key of options.publicKeys) { - dataParts.push(key.hex()); - } - const numNodes = options.publicKeys.length; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit: this.computeExecutionGasLimitForNodesManagement(numNodes), - addDataMovementGas: true - }).build(); - } - createTransactionForChangingServiceFee(options) { - const dataParts = [ - "changeServiceFee", - this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.serviceFee)])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForModifyingDelegationCap(options) { - const dataParts = [ - "modifyTotalDelegationCap", - this.argSerializer.valuesToStrings([new smartcontracts_1.BigUIntValue(options.delegationCap)])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingAutomaticActivation(options) { - const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0]]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnsettingAutomaticActivation(options) { - const dataParts = ["setAutomaticActivation", this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0]]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingCapCheckOnRedelegateRewards(options) { - const dataParts = [ - "setCheckCapOnReDelegateRewards", - this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("true")])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForUnsettingCapCheckOnRedelegateRewards(options) { - const dataParts = [ - "setCheckCapOnReDelegateRewards", - this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue("false")])[0] - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingMetadata(options) { - const dataParts = [ - "setMetaData", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.name), - new smartcontracts_1.StringValue(options.website), - new smartcontracts_1.StringValue(options.identifier) - ]) - ]; - const gasLimit = this.config.gasLimitDelegationOperations + this.config.additionalGasLimitForDelegationOperations; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.delegationContract, - dataParts, - gasLimit, - addDataMovementGas: true - }).build(); - } - computeExecutionGasLimitForNodesManagement(numNodes) { - const additionalGasForAllNodes = this.config.additionalGasLimitPerValidatorNode * BigInt(numNodes); - return this.config.gasLimitDelegationOperations + additionalGasForAllNodes; - } - }; - exports2.DelegationTransactionsFactory = DelegationTransactionsFactory; - } -}); - -// node_modules/json-bigint/lib/stringify.js -var require_stringify = __commonJS({ - "node_modules/json-bigint/lib/stringify.js"(exports2, module2) { - init_shim(); - var BigNumber2 = require_bignumber(); - var JSON2 = module2.exports; - (function() { - "use strict"; - function f4(n3) { - return n3 < 10 ? "0" + n3 : n3; - } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { - // table of character substitutions - "\b": "\\b", - " ": "\\t", - "\n": "\\n", - "\f": "\\f", - "\r": "\\r", - '"': '\\"', - "\\": "\\\\" - }, rep; - function quote(string2) { - escapable.lastIndex = 0; - return escapable.test(string2) ? '"' + string2.replace(escapable, function(a3) { - var c4 = meta[a3]; - return typeof c4 === "string" ? c4 : "\\u" + ("0000" + a3.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string2 + '"'; - } - function str(key, holder) { - var i2, k4, v2, length2, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber2 || BigNumber2.isBigNumber(value)); - if (value && typeof value === "object" && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - if (typeof rep === "function") { - value = rep.call(holder, key, value); - } - switch (typeof value) { - case "string": - if (isBigNumber) { - return value; - } else { - return quote(value); - } - case "number": - return isFinite(value) ? String(value) : "null"; - case "boolean": - case "null": - case "bigint": - return String(value); - case "object": - if (!value) { - return "null"; - } - gap += indent; - partial = []; - if (Object.prototype.toString.apply(value) === "[object Array]") { - length2 = value.length; - for (i2 = 0; i2 < length2; i2 += 1) { - partial[i2] = str(i2, value) || "null"; - } - v2 = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]"; - gap = mind; - return v2; - } - if (rep && typeof rep === "object") { - length2 = rep.length; - for (i2 = 0; i2 < length2; i2 += 1) { - if (typeof rep[i2] === "string") { - k4 = rep[i2]; - v2 = str(k4, value); - if (v2) { - partial.push(quote(k4) + (gap ? ": " : ":") + v2); - } - } - } - } else { - Object.keys(value).forEach(function(k5) { - var v3 = str(k5, value); - if (v3) { - partial.push(quote(k5) + (gap ? ": " : ":") + v3); - } - }); - } - v2 = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}"; - gap = mind; - return v2; - } - } - if (typeof JSON2.stringify !== "function") { - JSON2.stringify = function(value, replacer, space) { - var i2; - gap = ""; - indent = ""; - if (typeof space === "number") { - for (i2 = 0; i2 < space; i2 += 1) { - indent += " "; - } - } else if (typeof space === "string") { - indent = space; - } - rep = replacer; - if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { - throw new Error("JSON.stringify"); - } - return str("", { "": value }); - }; - } - })(); - } -}); - -// node_modules/json-bigint/lib/parse.js -var require_parse = __commonJS({ - "node_modules/json-bigint/lib/parse.js"(exports2, module2) { - init_shim(); - var BigNumber2 = null; - var suspectProtoRx2 = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; - var suspectConstructorRx2 = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; - var json_parse = function(options) { - "use strict"; - var _options = { - strict: false, - // not being strict means do not generate syntax errors for "duplicate key" - storeAsString: false, - // toggles whether the values should be stored as BigNumber (default) or a string - alwaysParseAsBig: false, - // toggles whether all numbers should be Big - useNativeBigInt: false, - // toggles whether to use native BigInt instead of bignumber.js - protoAction: "error", - constructorAction: "error" - }; - if (options !== void 0 && options !== null) { - if (options.strict === true) { - _options.strict = true; - } - if (options.storeAsString === true) { - _options.storeAsString = true; - } - _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; - _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; - if (typeof options.constructorAction !== "undefined") { - if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { - _options.constructorAction = options.constructorAction; - } else { - throw new Error( - `Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}` - ); - } - } - if (typeof options.protoAction !== "undefined") { - if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { - _options.protoAction = options.protoAction; - } else { - throw new Error( - `Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}` - ); - } - } - } - var at, ch, escapee = { - '"': '"', - "\\": "\\", - "/": "/", - b: "\b", - f: "\f", - n: "\n", - r: "\r", - t: " " - }, text, error = function(m3) { - throw { - name: "SyntaxError", - message: m3, - at, - text - }; - }, next = function(c4) { - if (c4 && c4 !== ch) { - error("Expected '" + c4 + "' instead of '" + ch + "'"); - } - ch = text.charAt(at); - at += 1; - return ch; - }, number = function() { - var number2, string3 = ""; - if (ch === "-") { - string3 = "-"; - next("-"); - } - while (ch >= "0" && ch <= "9") { - string3 += ch; - next(); - } - if (ch === ".") { - string3 += "."; - while (next() && ch >= "0" && ch <= "9") { - string3 += ch; - } - } - if (ch === "e" || ch === "E") { - string3 += ch; - next(); - if (ch === "-" || ch === "+") { - string3 += ch; - next(); - } - while (ch >= "0" && ch <= "9") { - string3 += ch; - next(); - } - } - number2 = +string3; - if (!isFinite(number2)) { - error("Bad number"); - } else { - if (BigNumber2 == null) - BigNumber2 = require_bignumber(); - if (string3.length > 15) - return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber2(string3); - else - return !_options.alwaysParseAsBig ? number2 : _options.useNativeBigInt ? BigInt(number2) : new BigNumber2(number2); - } - }, string2 = function() { - var hex, i2, string3 = "", uffff; - if (ch === '"') { - var startAt = at; - while (next()) { - if (ch === '"') { - if (at - 1 > startAt) - string3 += text.substring(startAt, at - 1); - next(); - return string3; - } - if (ch === "\\") { - if (at - 1 > startAt) - string3 += text.substring(startAt, at - 1); - next(); - if (ch === "u") { - uffff = 0; - for (i2 = 0; i2 < 4; i2 += 1) { - hex = parseInt(next(), 16); - if (!isFinite(hex)) { - break; - } - uffff = uffff * 16 + hex; - } - string3 += String.fromCharCode(uffff); - } else if (typeof escapee[ch] === "string") { - string3 += escapee[ch]; - } else { - break; - } - startAt = at; - } - } - } - error("Bad string"); - }, white = function() { - while (ch && ch <= " ") { - next(); - } - }, word = function() { - switch (ch) { - case "t": - next("t"); - next("r"); - next("u"); - next("e"); - return true; - case "f": - next("f"); - next("a"); - next("l"); - next("s"); - next("e"); - return false; - case "n": - next("n"); - next("u"); - next("l"); - next("l"); - return null; - } - error("Unexpected '" + ch + "'"); - }, value, array = function() { - var array2 = []; - if (ch === "[") { - next("["); - white(); - if (ch === "]") { - next("]"); - return array2; - } - while (ch) { - array2.push(value()); - white(); - if (ch === "]") { - next("]"); - return array2; - } - next(","); - white(); - } - } - error("Bad array"); - }, object = function() { - var key, object2 = /* @__PURE__ */ Object.create(null); - if (ch === "{") { - next("{"); - white(); - if (ch === "}") { - next("}"); - return object2; - } - while (ch) { - key = string2(); - white(); - next(":"); - if (_options.strict === true && Object.hasOwnProperty.call(object2, key)) { - error('Duplicate key "' + key + '"'); - } - if (suspectProtoRx2.test(key) === true) { - if (_options.protoAction === "error") { - error("Object contains forbidden prototype property"); - } else if (_options.protoAction === "ignore") { - value(); - } else { - object2[key] = value(); - } - } else if (suspectConstructorRx2.test(key) === true) { - if (_options.constructorAction === "error") { - error("Object contains forbidden constructor property"); - } else if (_options.constructorAction === "ignore") { - value(); - } else { - object2[key] = value(); - } - } else { - object2[key] = value(); - } - white(); - if (ch === "}") { - next("}"); - return object2; - } - next(","); - white(); - } - } - error("Bad object"); - }; - value = function() { - white(); - switch (ch) { - case "{": - return object(); - case "[": - return array(); - case '"': - return string2(); - case "-": - return number(); - default: - return ch >= "0" && ch <= "9" ? number() : word(); - } - }; - return function(source, reviver) { - var result; - text = source + ""; - at = 0; - ch = " "; - result = value(); - white(); - if (ch) { - error("Syntax error"); - } - return typeof reviver === "function" ? function walk(holder, key) { - var k4, v2, value2 = holder[key]; - if (value2 && typeof value2 === "object") { - Object.keys(value2).forEach(function(k5) { - v2 = walk(value2, k5); - if (v2 !== void 0) { - value2[k5] = v2; - } else { - delete value2[k5]; - } - }); - } - return reviver.call(holder, key, value2); - }({ "": result }, "") : result; - }; - }; - module2.exports = json_parse; - } -}); - -// node_modules/json-bigint/index.js -var require_json_bigint = __commonJS({ - "node_modules/json-bigint/index.js"(exports2, module2) { - init_shim(); - var json_stringify = require_stringify().stringify; - var json_parse = require_parse(); - module2.exports = function(options) { - return { - parse: json_parse(options), - stringify: json_stringify - }; - }; - module2.exports.parse = json_parse(); - module2.exports.stringify = json_stringify; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js -var require_relayedTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/relayedTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RelayedTransactionsFactory = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var transaction_1 = require_transaction(); - var JSONbig = require_json_bigint(); - var RelayedTransactionsFactory = class { - constructor(options) { - this.config = options.config; - } - createRelayedV1Transaction(options) { - if (!options.innerTransaction.gasLimit) { - throw new errors_1.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction"); - } - if (!options.innerTransaction.signature.length) { - throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); - } - const serializedTransaction = this.prepareInnerTransactionForRelayedV1(options.innerTransaction); - const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; - const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); - const gasLimit = this.config.minGasLimit + additionalGasForDataLength + options.innerTransaction.gasLimit; - return new transaction_1.Transaction({ - chainID: this.config.chainID, - sender: options.relayerAddress.bech32(), - receiver: options.innerTransaction.sender, - gasLimit, - data: import_buffer.Buffer.from(data) - }); - } - createRelayedV2Transaction(options) { - if (options.innerTransaction.gasLimit) { - throw new errors_1.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction"); - } - if (!options.innerTransaction.signature.length) { - throw new errors_1.ErrInvalidInnerTransaction("The inner transaction is not signed"); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - new smartcontracts_1.AddressValue(address_1.Address.fromBech32(options.innerTransaction.receiver)), - new smartcontracts_1.U64Value(new bignumber_js_1.default(options.innerTransaction.nonce.toString())), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.data)), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.innerTransaction.signature)) - ]); - const data = `relayedTxV2@${argumentsString}`; - const additionalGasForDataLength = this.config.gasLimitPerByte * BigInt(data.length); - const gasLimit = options.innerTransactionGasLimit + this.config.minGasLimit + additionalGasForDataLength; - return new transaction_1.Transaction({ - sender: options.relayerAddress.bech32(), - receiver: options.innerTransaction.sender, - value: 0n, - gasLimit, - chainID: this.config.chainID, - data: import_buffer.Buffer.from(data), - version: options.innerTransaction.version, - options: options.innerTransaction.options - }); - } - prepareInnerTransactionForRelayedV1(innerTransaction) { - const txObject = { - nonce: innerTransaction.nonce, - sender: address_1.Address.fromBech32(innerTransaction.sender).pubkey().toString("base64"), - receiver: address_1.Address.fromBech32(innerTransaction.receiver).pubkey().toString("base64"), - value: innerTransaction.value, - gasPrice: innerTransaction.gasPrice, - gasLimit: innerTransaction.gasLimit, - data: import_buffer.Buffer.from(innerTransaction.data).toString("base64"), - signature: import_buffer.Buffer.from(innerTransaction.signature).toString("base64"), - chainID: import_buffer.Buffer.from(innerTransaction.chainID).toString("base64"), - version: innerTransaction.version, - options: innerTransaction.options.valueOf() == 0 ? void 0 : innerTransaction.options, - guardian: innerTransaction.guardian ? address_1.Address.fromBech32(innerTransaction.guardian).pubkey().toString("base64") : void 0, - guardianSignature: innerTransaction.guardianSignature.length ? import_buffer.Buffer.from(innerTransaction.guardianSignature).toString("base64") : void 0, - sndUserName: innerTransaction.senderUsername ? import_buffer.Buffer.from(innerTransaction.senderUsername).toString("base64") : void 0, - rcvUserName: innerTransaction.receiverUsername ? import_buffer.Buffer.from(innerTransaction.receiverUsername).toString("base64") : void 0 - }; - return JSONbig.stringify(txObject); - } - }; - exports2.RelayedTransactionsFactory = RelayedTransactionsFactory; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js -var require_argumentErrorContext = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/argumentErrorContext.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ArgumentErrorContext = void 0; - var errors_1 = require_errors(); - var ArgumentErrorContext = class { - constructor(endpointName, argumentIndex, parameterDefinition) { - this.endpointName = endpointName; - this.argumentIndex = argumentIndex; - this.parameterDefinition = parameterDefinition; - } - throwError(specificError) { - throw new errors_1.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) -Nested error: ${specificError}`); - } - convertError(native, typeName) { - this.throwError(`Can't convert argument (argument: ${native}, type ${typeof native}), wanted type: ${typeName})`); - } - unhandledType(functionName, type) { - this.throwError(`Unhandled type (function: ${functionName}, type: ${type})`); - } - guardSameLength(native, valueTypes) { - native = native || []; - if (native.length != valueTypes.length) { - this.throwError(`Incorrect composite type length: have ${native.length}, expected ${valueTypes.length} (argument: ${native})`); - } - } - guardHasField(native, fieldName) { - native = native || {}; - if (!(fieldName in native)) { - this.throwError(`Struct argument does not contain a field named "${fieldName}" (argument: ${JSON.stringify(native)})`); - } - } - }; - exports2.ArgumentErrorContext = ArgumentErrorContext; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js -var require_nativeSerializer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/nativeSerializer.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NativeSerializer = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var errors_1 = require_errors(); - var utils_codec_1 = require_utils_codec(); - var argumentErrorContext_1 = require_argumentErrorContext(); - var typesystem_1 = require_typesystem(); - var NativeSerializer; - (function(NativeSerializer2) { - function nativeToTypedValues(args, endpoint) { - args = args || []; - checkArgumentsCardinality(args, endpoint); - if (hasNonCountedVariadicParameter(endpoint)) { - args = repackNonCountedVariadicParameters(args, endpoint); - } else { - } - let parameters = endpoint.input; - let values = []; - for (let i2 = 0; i2 < parameters.length; i2++) { - let parameter = parameters[i2]; - let errorContext = new argumentErrorContext_1.ArgumentErrorContext(endpoint.name, i2, parameter); - let value = convertToTypedValue(args[i2], parameter.type, errorContext); - values.push(value); - } - return values; - } - NativeSerializer2.nativeToTypedValues = nativeToTypedValues; - function checkArgumentsCardinality(args, endpoint) { - const { min, max } = getArgumentsCardinality(endpoint.input); - if (!(min <= args.length && args.length <= max)) { - throw new errors_1.ErrInvalidArgument(`Wrong number of arguments for endpoint ${endpoint.name}: expected between ${min} and ${max} arguments, have ${args.length}`); - } - } - function hasNonCountedVariadicParameter(endpoint) { - const lastParameter = endpoint.input[endpoint.input.length - 1]; - return lastParameter?.type instanceof typesystem_1.VariadicType && !lastParameter.type.isCounted; - } - function repackNonCountedVariadicParameters(args, endpoint) { - const lastEndpointParamIndex = endpoint.input.length - 1; - const argAtIndex = args[lastEndpointParamIndex]; - if (argAtIndex?.belongsToTypesystem) { - const isVariadicValue = argAtIndex.hasClassOrSuperclass(typesystem_1.VariadicValue.ClassName); - if (!isVariadicValue) { - throw new errors_1.ErrInvalidArgument(`Wrong argument type for endpoint ${endpoint.name}: typed value provided; expected variadic type, have ${argAtIndex.getClassName()}`); - } - } else { - args[lastEndpointParamIndex] = args.slice(lastEndpointParamIndex); - } - return args; - } - function getArgumentsCardinality(parameters) { - let reversed = [...parameters].reverse(); - let min = parameters.length; - let max = parameters.length; - let variadic = false; - if (reversed.length > 0 && reversed[0].type.getCardinality().isComposite()) { - max = Infinity; - variadic = true; - } - for (let parameter of reversed) { - if (parameter.type.getCardinality().isSingular()) { - break; - } - min -= 1; - } - return { min, max, variadic }; - } - NativeSerializer2.getArgumentsCardinality = getArgumentsCardinality; - function convertToTypedValue(value, type, errorContext) { - if (value && value.belongsToTypesystem) { - return value; - } - if (type instanceof typesystem_1.OptionType) { - return toOptionValue(value, type, errorContext); - } - if (type instanceof typesystem_1.OptionalType) { - return toOptionalValue(value, type, errorContext); - } - if (type instanceof typesystem_1.VariadicType) { - return toVariadicValue(value, type, errorContext); - } - if (type instanceof typesystem_1.CompositeType) { - return toCompositeValue(value, type, errorContext); - } - if (type instanceof typesystem_1.TupleType) { - return toTupleValue(value, type, errorContext); - } - if (type instanceof typesystem_1.StructType) { - return toStructValue(value, type, errorContext); - } - if (type instanceof typesystem_1.ListType) { - return toListValue(value, type, errorContext); - } - if (type instanceof typesystem_1.PrimitiveType) { - return toPrimitive(value, type, errorContext); - } - if (type instanceof typesystem_1.EnumType) { - return toEnumValue(value, type, errorContext); - } - errorContext.throwError(`convertToTypedValue: unhandled type ${type}`); - } - function toOptionValue(native, type, errorContext) { - if (native == null) { - return typesystem_1.OptionValue.newMissing(); - } - let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); - return typesystem_1.OptionValue.newProvided(converted); - } - function toOptionalValue(native, type, errorContext) { - if (native == null) { - return new typesystem_1.OptionalValue(type); - } - let converted = convertToTypedValue(native, type.getFirstTypeParameter(), errorContext); - return new typesystem_1.OptionalValue(type, converted); - } - function toVariadicValue(native, type, errorContext) { - if (type.isCounted) { - throw new errors_1.ErrInvalidArgument(`Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"`); - } - if (native == null) { - native = []; - } - if (native.map === void 0) { - errorContext.convertError(native, "Variadic"); - } - let converted = native.map(function(item) { - return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); - }); - return new typesystem_1.VariadicValue(type, converted); - } - function toListValue(native, type, errorContext) { - if (native.map === void 0) { - errorContext.convertError(native, "List"); - } - let converted = native.map(function(item) { - return convertToTypedValue(item, type.getFirstTypeParameter(), errorContext); - }); - return new typesystem_1.List(type, converted); - } - function toCompositeValue(native, type, errorContext) { - let typedValues = []; - let typeParameters = type.getTypeParameters(); - errorContext.guardSameLength(native, typeParameters); - for (let i2 = 0; i2 < typeParameters.length; i2++) { - typedValues.push(convertToTypedValue(native[i2], typeParameters[i2], errorContext)); - } - return new typesystem_1.CompositeValue(type, typedValues); - } - function toTupleValue(native, type, errorContext) { - let typedValues = []; - const fields = type.getFieldsDefinitions(); - errorContext.guardSameLength(native, fields); - for (let i2 = 0; i2 < fields.length; i2++) { - typedValues.push(convertToTypedValue(native[i2], fields[i2].type, errorContext)); - } - return typesystem_1.Tuple.fromItems(typedValues); - } - function toStructValue(native, type, errorContext) { - let structFieldValues = []; - const fields = type.getFieldsDefinitions(); - for (let i2 = 0; i2 < fields.length; i2++) { - const fieldName = fields[i2].name; - errorContext.guardHasField(native, fieldName); - const fieldNativeValue = native[fieldName]; - const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); - structFieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); - } - return new typesystem_1.Struct(type, structFieldValues); - } - function toPrimitive(native, type, errorContext) { - if (type instanceof typesystem_1.NumericalType) { - let number = new bignumber_js_1.default(native); - return convertNumericalType(number, type, errorContext); - } - if (type instanceof typesystem_1.BytesType) { - return convertNativeToBytesValue(native, errorContext); - } - if (type instanceof typesystem_1.AddressType) { - return new typesystem_1.AddressValue(convertNativeToAddress(native, errorContext)); - } - if (type instanceof typesystem_1.BooleanType) { - return new typesystem_1.BooleanValue(native); - } - if (type instanceof typesystem_1.TokenIdentifierType) { - return new typesystem_1.TokenIdentifierValue(convertNativeToString(native, errorContext)); - } - errorContext.throwError(`(function: toPrimitive) unsupported type ${type}`); - } - function toEnumValue(native, type, errorContext) { - if (typeof native === "number") { - return typesystem_1.EnumValue.fromDiscriminant(type, native); - } - if (typeof native === "string") { - return typesystem_1.EnumValue.fromName(type, native); - } - if (typeof native === "object") { - errorContext.guardHasField(native, "name"); - const variant = type.getVariantByName(native.name); - errorContext.guardHasField(native, "fields"); - const nativeFields = native.fields; - const fieldValues = []; - const fields = variant.getFieldsDefinitions(); - for (let i2 = 0; i2 < fields.length; i2++) { - const fieldName = fields[i2].name; - errorContext.guardHasField(nativeFields, fieldName); - const fieldNativeValue = nativeFields[fieldName]; - const fieldTypedValue = convertToTypedValue(fieldNativeValue, fields[i2].type, errorContext); - fieldValues.push(new typesystem_1.Field(fieldTypedValue, fieldName)); - } - return new typesystem_1.EnumValue(type, variant, fieldValues); - } - errorContext.throwError(`(function: toEnumValue) unsupported native type ${typeof native}`); - } - function convertNativeToBytesValue(native, errorContext) { - const innerValue = native.valueOf(); - if (native === void 0) { - errorContext.convertError(native, "BytesValue"); - } - if (native instanceof import_buffer.Buffer) { - return new typesystem_1.BytesValue(native); - } - if (typeof native === "string") { - return typesystem_1.BytesValue.fromUTF8(native); - } - if (innerValue instanceof import_buffer.Buffer) { - return new typesystem_1.BytesValue(innerValue); - } - if (typeof innerValue === "number") { - return typesystem_1.BytesValue.fromHex(utils_codec_1.numberToPaddedHex(innerValue)); - } - errorContext.convertError(native, "BytesValue"); - } - function convertNativeToString(native, errorContext) { - if (native === void 0) { - errorContext.convertError(native, "Buffer"); - } - if (native instanceof import_buffer.Buffer) { - return native.toString(); - } - if (typeof native === "string") { - return native; - } - errorContext.convertError(native, "Buffer"); - } - function convertNativeToAddress(native, errorContext) { - if (native.bech32) { - return native; - } - if (native.getAddress) { - return native.getAddress(); - } - switch (native.constructor) { - case import_buffer.Buffer: - case String: - return new address_1.Address(native); - default: - errorContext.convertError(native, "Address"); - } - } - NativeSerializer2.convertNativeToAddress = convertNativeToAddress; - function convertNumericalType(number, type, errorContext) { - switch (type.constructor) { - case typesystem_1.U8Type: - return new typesystem_1.U8Value(number); - case typesystem_1.I8Type: - return new typesystem_1.I8Value(number); - case typesystem_1.U16Type: - return new typesystem_1.U16Value(number); - case typesystem_1.I16Type: - return new typesystem_1.I16Value(number); - case typesystem_1.U32Type: - return new typesystem_1.U32Value(number); - case typesystem_1.I32Type: - return new typesystem_1.I32Value(number); - case typesystem_1.U64Type: - return new typesystem_1.U64Value(number); - case typesystem_1.I64Type: - return new typesystem_1.I64Value(number); - case typesystem_1.BigUIntType: - return new typesystem_1.BigUIntValue(number); - case typesystem_1.BigIntType: - return new typesystem_1.BigIntValue(number); - default: - errorContext.unhandledType("convertNumericalType", type); - } - } - })(NativeSerializer = exports2.NativeSerializer || (exports2.NativeSerializer = {})); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js -var require_tokenTransfersDataBuilder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenTransfersDataBuilder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenTransfersDataBuilder = void 0; - var argSerializer_1 = require_argSerializer(); - var typesystem_1 = require_typesystem(); - var tokens_1 = require_tokens(); - var TokenTransfersDataBuilder = class { - constructor() { - this.tokenComputer = new tokens_1.TokenComputer(); - this.argsSerializer = new argSerializer_1.ArgSerializer(); - } - buildDataPartsForESDTTransfer(transfer) { - const args = this.argsSerializer.valuesToStrings([ - new typesystem_1.TokenIdentifierValue(transfer.token.identifier), - new typesystem_1.BigUIntValue(transfer.amount) - ]); - return ["ESDTTransfer", ...args]; - } - buildDataPartsForSingleESDTNFTTransfer(transfer, receiver) { - const token = transfer.token; - const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(token.identifier); - const args = this.argsSerializer.valuesToStrings([ - new typesystem_1.TokenIdentifierValue(identifier), - new typesystem_1.BigUIntValue(token.nonce), - new typesystem_1.BigUIntValue(transfer.amount), - new typesystem_1.AddressValue(receiver) - ]); - return ["ESDTNFTTransfer", ...args]; - } - buildDataPartsForMultiESDTNFTTransfer(receiver, transfers) { - const argsTyped = [new typesystem_1.AddressValue(receiver), new typesystem_1.U32Value(transfers.length)]; - for (const transfer of transfers) { - const identifier = this.tokenComputer.extractIdentifierFromExtendedIdentifier(transfer.token.identifier); - argsTyped.push(...[ - new typesystem_1.TokenIdentifierValue(identifier), - new typesystem_1.BigUIntValue(transfer.token.nonce), - new typesystem_1.BigUIntValue(transfer.amount) - ]); - } - const args = this.argsSerializer.valuesToStrings(argsTyped); - return ["MultiESDTNFTTransfer", ...args]; - } - }; - exports2.TokenTransfersDataBuilder = TokenTransfersDataBuilder; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js -var require_smartContractTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/smartContractTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractTransactionsFactory = void 0; - var address_1 = require_address(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var smartcontracts_1 = require_smartcontracts(); - var nativeSerializer_1 = require_nativeSerializer(); - var tokens_1 = require_tokens(); - var utils_codec_1 = require_utils_codec(); - var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); - var transactionBuilder_1 = require_transactionBuilder(); - var SmartContractTransactionsFactory2 = class { - constructor(options) { - this.config = options.config; - this.abi = options.abi; - this.tokenComputer = new tokens_1.TokenComputer(); - this.dataArgsBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); - } - createTransactionForDeploy(options) { - const nativeTransferAmount = options.nativeTransferAmount ?? 0n; - const isUpgradeable = options.isUpgradeable ?? true; - const isReadable = options.isReadable ?? true; - const isPayable = options.isPayable ?? false; - const isPayableBySmartContract = options.isPayableBySmartContract ?? true; - const args = options.arguments || []; - const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); - const dataParts = [utils_codec_1.byteArrayToHex(options.bytecode), utils_codec_1.byteArrayToHex(constants_1.VM_TYPE_WASM_VM), metadata.toString()]; - const endpoint = this.abi?.constructorDefinition; - const preparedArgs = this.argsToDataParts(args, endpoint); - dataParts.push(...preparedArgs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.CONTRACT_DEPLOY_ADDRESS), - dataParts, - gasLimit: options.gasLimit, - addDataMovementGas: false, - amount: nativeTransferAmount - }).build(); - } - createTransactionForExecute(options) { - const args = options.arguments || []; - const tokenTransfer = options.tokenTransfers || []; - const nativeTransferAmount = options.nativeTransferAmount ?? 0n; - const numberOfTokens = tokenTransfer.length; - if (nativeTransferAmount && numberOfTokens) { - throw new errors_1.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)"); - } - let receiver = options.contract; - let dataParts = []; - if (numberOfTokens === 1) { - const transfer = tokenTransfer[0]; - if (this.tokenComputer.isFungible(transfer.token)) { - dataParts = this.dataArgsBuilder.buildDataPartsForESDTTransfer(transfer); - } else { - dataParts = this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); - receiver = options.sender; - } - } else if (numberOfTokens > 1) { - dataParts = this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(receiver, tokenTransfer); - receiver = options.sender; - } - dataParts.push(dataParts.length ? utils_codec_1.utf8ToHex(options.function) : options.function); - const endpoint = this.abi?.getEndpoint(options.function); - const preparedArgs = this.argsToDataParts(args, endpoint); - dataParts.push(...preparedArgs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver, - dataParts, - gasLimit: options.gasLimit, - addDataMovementGas: false, - amount: nativeTransferAmount - }).build(); - } - createTransactionForUpgrade(options) { - const nativeTransferAmount = options.nativeTransferAmount ?? 0n; - const isUpgradeable = options.isUpgradeable ?? true; - const isReadable = options.isReadable ?? true; - const isPayable = options.isPayable ?? false; - const isPayableBySmartContract = options.isPayableBySmartContract ?? true; - const args = options.arguments || []; - const metadata = new smartcontracts_1.CodeMetadata(isUpgradeable, isReadable, isPayable, isPayableBySmartContract); - const dataParts = ["upgradeContract", utils_codec_1.byteArrayToHex(options.bytecode), metadata.toString()]; - const endpoint = this.getEndpointForUpgrade(); - const preparedArgs = this.argsToDataParts(args, endpoint); - dataParts.push(...preparedArgs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.contract, - dataParts, - gasLimit: options.gasLimit, - addDataMovementGas: false, - amount: nativeTransferAmount - }).build(); - } - getEndpointForUpgrade() { - if (!this.abi) { - return void 0; - } - try { - return this.abi.getEndpoint("upgrade"); - } catch (error) { - logger_1.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."); - return this.abi.constructorDefinition; - } - } - createTransactionForClaimingDeveloperRewards(options) { - const dataParts = ["ClaimDeveloperRewards"]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.contract, - dataParts, - gasLimit: this.config.gasLimitClaimDeveloperRewards, - addDataMovementGas: false - }).build(); - } - createTransactionForChangingOwnerAddress(options) { - const dataParts = ["ChangeOwnerAddress", address_1.Address.fromBech32(options.newOwner.bech32()).toHex()]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.contract, - dataParts, - gasLimit: this.config.gasLimitChangeOwnerAddress, - addDataMovementGas: false - }).build(); - } - argsToDataParts(args, endpoint) { - if (endpoint) { - const typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args, endpoint); - return new smartcontracts_1.ArgSerializer().valuesToStrings(typedArgs); - } - if (this.areArgsOfTypedValue(args)) { - return new smartcontracts_1.ArgSerializer().valuesToStrings(args); - } - throw new errors_1.Err("Can't convert args to TypedValues"); - } - areArgsOfTypedValue(args) { - for (const arg of args) { - if (!arg.belongsToTypesystem) { - return false; - } - } - return true; - } - }; - exports2.SmartContractTransactionsFactory = SmartContractTransactionsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js -var require_tokenManagementTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/tokenManagementTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenManagementTransactionsFactory = void 0; - var address_1 = require_address(); - var constants_1 = require_constants(); - var logger_1 = require_logger(); - var smartcontracts_1 = require_smartcontracts(); - var transactionBuilder_1 = require_transactionBuilder(); - var TokenManagementTransactionsFactory2 = class { - constructor(options) { - this.config = options.config; - this.argSerializer = new smartcontracts_1.ArgSerializer(); - this.trueAsString = "true"; - this.falseAsString = "false"; - } - createTransactionForIssuingFungible(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.BigUIntValue(options.initialSupply), - new smartcontracts_1.BigUIntValue(options.numDecimals), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["issue", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForIssuingSemiFungible(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canTransferNFTCreateRole"), - new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["issueSemiFungible", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForIssuingNonFungible(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canTransferNFTCreateRole"), - new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["issueNonFungible", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForRegisteringMetaESDT(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const args = [ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.BigUIntValue(options.numDecimals), - new smartcontracts_1.StringValue("canFreeze"), - new smartcontracts_1.StringValue(this.boolToString(options.canFreeze)), - new smartcontracts_1.StringValue("canWipe"), - new smartcontracts_1.StringValue(this.boolToString(options.canWipe)), - new smartcontracts_1.StringValue("canPause"), - new smartcontracts_1.StringValue(this.boolToString(options.canPause)), - new smartcontracts_1.StringValue("canTransferNFTCreateRole"), - new smartcontracts_1.StringValue(this.boolToString(options.canTransferNFTCreateRole)), - new smartcontracts_1.StringValue("canChangeOwner"), - new smartcontracts_1.StringValue(this.boolToString(options.canChangeOwner)), - new smartcontracts_1.StringValue("canUpgrade"), - new smartcontracts_1.StringValue(this.boolToString(options.canUpgrade)), - new smartcontracts_1.StringValue("canAddSpecialRoles"), - new smartcontracts_1.StringValue(this.boolToString(options.canAddSpecialRoles)) - ]; - const dataParts = ["registerMetaESDT", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForRegisteringAndSettingRoles(options) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const dataParts = [ - "registerAndSetAllRoles", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenName), - new smartcontracts_1.StringValue(options.tokenTicker), - new smartcontracts_1.StringValue(options.tokenType), - new smartcontracts_1.BigUIntValue(options.numDecimals) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitIssue, - addDataMovementGas: true, - amount: this.config.issueCost - }).build(); - } - createTransactionForSettingBurnRoleGlobally(options) { - const dataParts = [ - "setBurnRoleGlobally", - ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitToggleBurnRoleGlobally, - addDataMovementGas: true - }).build(); - } - createTransactionForUnsettingBurnRoleGlobally(options) { - const dataParts = [ - "unsetBurnRoleGlobally", - ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitToggleBurnRoleGlobally, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingSpecialRoleOnFungibleToken(options) { - const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; - options.addRoleLocalMint ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalMint")) : 0; - options.addRoleLocalBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleLocalBurn")) : 0; - options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; - const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitSetSpecialRole, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingSpecialRoleOnSemiFungibleToken(options) { - const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; - options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; - options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; - options.addRoleNFTAddQuantity ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddQuantity")) : 0; - options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; - const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitSetSpecialRole, - addDataMovementGas: true - }).build(); - } - createTransactionForSettingSpecialRoleOnMetaESDT(options) { - return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(options); - } - createTransactionForSettingSpecialRoleOnNonFungibleToken(options) { - const args = [new smartcontracts_1.StringValue(options.tokenIdentifier), new smartcontracts_1.AddressValue(options.user)]; - options.addRoleNFTCreate ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTCreate")) : 0; - options.addRoleNFTBurn ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTBurn")) : 0; - options.addRoleNFTUpdateAttributes ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTUpdateAttributes")) : 0; - options.addRoleNFTAddURI ? args.push(new smartcontracts_1.StringValue("ESDTRoleNFTAddURI")) : 0; - options.addRoleESDTTransferRole ? args.push(new smartcontracts_1.StringValue("ESDTTransferRole")) : 0; - const dataParts = ["setSpecialRole", ...this.argSerializer.valuesToStrings(args)]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: address_1.Address.fromBech32(constants_1.ESDT_CONTRACT_ADDRESS), - dataParts, - gasLimit: this.config.gasLimitSetSpecialRole, - addDataMovementGas: true - }).build(); - } - createTransactionForCreatingNFT(options) { - const dataParts = [ - "ESDTNFTCreate", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.initialQuantity), - new smartcontracts_1.StringValue(options.name), - new smartcontracts_1.BigUIntValue(options.royalties), - new smartcontracts_1.StringValue(options.hash), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)), - ...options.uris.map((uri) => new smartcontracts_1.StringValue(uri)) - ]) - ]; - const nftData = options.name + options.hash + options.attributes + options.uris.join(""); - const storageGasLimit = this.config.gasLimitStorePerByte + BigInt(nftData.length); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftCreate + storageGasLimit, - addDataMovementGas: true - }).build(); - } - createTransactionForPausing(options) { - const dataParts = ["pause", ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)])]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitPausing, - addDataMovementGas: true - }).build(); - } - createTransactionForUnpausing(options) { - const dataParts = [ - "unPause", - ...this.argSerializer.valuesToStrings([new smartcontracts_1.StringValue(options.tokenIdentifier)]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitPausing, - addDataMovementGas: true - }).build(); - } - createTransactionForFreezing(options) { - const dataParts = [ - "freeze", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.AddressValue(options.user) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitFreezing, - addDataMovementGas: true - }).build(); - } - createTransactionForUnfreezing(options) { - const dataParts = [ - "UnFreeze", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.AddressValue(options.user) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitFreezing, - addDataMovementGas: true - }).build(); - } - createTransactionForWiping(options) { - const dataParts = [ - "wipe", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.AddressValue(options.user) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitWiping, - addDataMovementGas: true - }).build(); - } - createTransactionForLocalMint(options) { - const dataParts = [ - "ESDTLocalMint", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.supplyToMint) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtLocalMint, - addDataMovementGas: true - }).build(); - } - createTransactionForLocalBurning(options) { - const dataParts = [ - "ESDTLocalBurn", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.supplyToBurn) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtLocalBurn, - addDataMovementGas: true - }).build(); - } - createTransactionForUpdatingAttributes(options) { - const dataParts = [ - "ESDTNFTUpdateAttributes", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.tokenNonce), - new smartcontracts_1.BytesValue(import_buffer.Buffer.from(options.attributes)) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftUpdateAttributes, - addDataMovementGas: true - }).build(); - } - createTransactionForAddingQuantity(options) { - const dataParts = [ - "ESDTNFTAddQuantity", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.tokenNonce), - new smartcontracts_1.BigUIntValue(options.quantityToAdd) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftAddQuantity, - addDataMovementGas: true - }).build(); - } - createTransactionForBurningQuantity(options) { - const dataParts = [ - "ESDTNFTBurn", - ...this.argSerializer.valuesToStrings([ - new smartcontracts_1.StringValue(options.tokenIdentifier), - new smartcontracts_1.BigUIntValue(options.tokenNonce), - new smartcontracts_1.BigUIntValue(options.quantityToBurn) - ]) - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitEsdtNftBurn, - addDataMovementGas: true - }).build(); - } - notifyAboutUnsettingBurnRoleGlobally() { - logger_1.Logger.info(` +`)}};ce.ErrContractHasNoAddress=$w;var Yw=class extends Ce{constructor(e){super(e)}};ce.ErrMock=Yw;var Jw=class extends Ce{constructor(e){super(e)}};ce.ErrTypingSystem=Jw;var Xw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on struct ${r}`)}};ce.ErrMissingFieldOnStruct=Xw;var Zw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on enum ${r}`)}};ce.ErrMissingFieldOnEnum=Zw;var ev=class extends Ce{constructor(e){super(`cannot parse contract results: ${e}`)}};ce.ErrCannotParseContractResults=ev;var tv=class extends Ce{constructor(e,r){super(`cannot parse outcome of transaction ${e}: ${r}`)}};ce.ErrCannotParseTransactionOutcome=tv;var rv=class extends Ce{constructor(e){super(e)}};ce.ErrCodec=rv;var nv=class extends Ce{constructor(e){super(e)}};ce.ErrContractInteraction=nv;var iv=class extends Ce{constructor(){super("Method not yet implemented")}};ce.ErrNotImplemented=iv;var sv=class extends Ce{constructor(){super("invalid arguments for relayed v1 builder")}};ce.ErrInvalidRelayedV1BuilderArguments=sv;var ov=class extends Ce{constructor(){super("invalid arguments for relayed v2 builder")}};ce.ErrInvalidRelayedV2BuilderArguments=ov;var av=class extends Ce{constructor(){super("gas limit must be 0 for the inner transaction for relayed v2")}};ce.ErrGasLimitShouldBe0ForInnerTransaction=av;var uv=class extends Ce{constructor(){super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`.")}};ce.ErrIsCompletedFieldIsMissingOnTransaction=uv;var cv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidTokenIdentifier=cv;var lv=class extends Ce{constructor(e){super(e)}};ce.ErrBadUsage=lv;var fv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidInnerTransaction=fv;var hv=class extends Ce{constructor(e){super(e)}};ce.ErrParseTransactionOutcome=hv});var Ca=B(xn=>{"use strict";h();var Wk=xn&&xn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xn,"__esModule",{value:!0});xn.TokenPayment=xn.TokenComputer=xn.TokenTransfer=xn.Token=void 0;var _a=Wk((rr(),_e(fr))),Du=Ie(),V3="EGLD",k3=18;_a.default.set({ROUNDING_MODE:1});var Hd=class{constructor(e){this.identifier=e.identifier,this.nonce=e.nonce||0n}};xn.Token=Hd;var Gd=class t{constructor(e){if(this.isLegacyTokenTransferOptions(e)){let r=new _a.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new Du.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0,this.token=new Hd({identifier:e.tokenIdentifier,nonce:BigInt(e.nonce)}),this.amount=BigInt(this.amountAsBigInteger.toFixed(0))}else this.token=e.token,this.amount=e.amount,this.tokenIdentifier=e.token.identifier,this.nonce=Number(e.token.nonce),this.amountAsBigInteger=new _a.default(this.amount.toString()),this.numDecimals=0}isLegacyTokenTransferOptions(e){return e.tokenIdentifier!==void 0}static egldFromAmount(e){let r=new _a.default(e).shiftedBy(k3).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:V3,nonce:0,amountAsBigInteger:e,numDecimals:k3})}static fungibleFromAmount(e,r,n){let i=new _a.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new _a.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amount.toString()}valueOf(){return new _a.default(this.amount.toString())}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.token.identifier==V3}isFungible(){return this.token.nonce==0n}};xn.TokenTransfer=Gd;var dv=class{constructor(){}isFungible(e){return e.nonce===0n}extractNonceFromExtendedIdentifier(e){let r=e.split("-");if(this.checkIfExtendedIdentifierWasProvided(r),this.checkLengthOfRandomSequence(r[1]),r.length==2)return 0;let n=p.Buffer.from(r[2],"hex");return $k(n)}extractIdentifierFromExtendedIdentifier(e){let r=e.split("-");return this.checkIfExtendedIdentifierWasProvided(r),this.ensureTokenTickerValidity(r[0]),this.checkLengthOfRandomSequence(r[1]),r[0]+"-"+r[1]}checkIfExtendedIdentifierWasProvided(e){if(e.length<2||e.length>3)throw new Du.ErrInvalidTokenIdentifier("Invalid extended token identifier provided")}checkLengthOfRandomSequence(e){if(e.length!==6)throw new Du.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length")}ensureTokenTickerValidity(e){if(e.length<3||e.length>10)throw new Du.ErrInvalidTokenIdentifier("The token ticker should be between 3 and 10 characters");if(!e.match(/^[a-zA-Z0-9]+$/))throw new Du.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters");if(e!=e.toUpperCase())throw new Du.ErrInvalidTokenIdentifier("The token ticker should be upper case")}};xn.TokenComputer=dv;function $k(t){return t.readUIntBE(0,t.length)}var gv=class extends Gd{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};xn.TokenPayment=gv});var hr=B(Ae=>{"use strict";h();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.UNKNOWN_SIGNER=Ae.SDK_JS_SIGNER=Ae.METACHAIN_ID=Ae.WasmVirtualMachine=Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=Ae.BECH32_ADDRESS_LENGTH=Ae.HEX_TRANSACTION_HASH_LENGTH=Ae.MESSAGE_PREFIX=Ae.DEFAULT_MESSAGE_VERSION=Ae.ESDT_CONTRACT_ADDRESS=Ae.DEFAULT_HRP=Ae.DELEGATION_MANAGER_SC_ADDRESS=Ae.CONTRACT_DEPLOY_ADDRESS=Ae.VM_TYPE_WASM_VM=Ae.ARGUMENTS_SEPARATOR=Ae.ESDT_TRANSFER_VALUE=Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_GAS_LIMIT=Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=Ae.TRANSACTION_VERSION_DEFAULT=Ae.TRANSACTION_OPTIONS_TX_GUARDED=Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=Ae.TRANSACTION_OPTIONS_DEFAULT=Ae.TRANSACTION_MIN_GAS_PRICE=void 0;Ae.TRANSACTION_MIN_GAS_PRICE=1e9;Ae.TRANSACTION_OPTIONS_DEFAULT=0;Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Ae.TRANSACTION_OPTIONS_TX_GUARDED=2;Ae.TRANSACTION_VERSION_DEFAULT=2;Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=2;Ae.ESDT_TRANSFER_GAS_LIMIT=5e5;Ae.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Ae.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Ae.ESDT_TRANSFER_VALUE="0";Ae.ARGUMENTS_SEPARATOR="@";Ae.VM_TYPE_WASM_VM=new Uint8Array([5,0]);Ae.CONTRACT_DEPLOY_ADDRESS="erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu";Ae.DELEGATION_MANAGER_SC_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6";Ae.DEFAULT_HRP="erd";Ae.ESDT_CONTRACT_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u";Ae.DEFAULT_MESSAGE_VERSION=1;Ae.MESSAGE_PREFIX=`Elrond Signed Message: +`;Ae.HEX_TRANSACTION_HASH_LENGTH=64;Ae.BECH32_ADDRESS_LENGTH=62;Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=3;Ae.WasmVirtualMachine="0500";Ae.METACHAIN_ID=4294967295;Ae.SDK_JS_SIGNER="sdk-js";Ae.UNKNOWN_SIGNER="unknown"});var oo=B(xa=>{"use strict";h();Object.defineProperty(xa,"__esModule",{value:!0});xa.Logger=xa.LogLevel=void 0;var Na;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Na=xa.LogLevel||(xa.LogLevel={}));var jd=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Na.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Na.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Na.Error||console.error(e,r)}};xa.Logger=jd;jd.logLevel=Na.Debug});var $l=B(On=>{"use strict";h();var Yk=On&&On.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Jk=On&&On.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xk=On&&On.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yk(e,t,r);return Jk(e,t),e};Object.defineProperty(On,"__esModule",{value:!0});On.TransactionOptions=On.TransactionVersion=void 0;var gi=hr(),H3=Xk(Ie()),pv=class t{constructor(e){if(e=Number(e),e<1)throw new H3.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}valueOf(){return this.value}};On.TransactionVersion=pv;var mv=class t{constructor(e){if(e=Number(e),e<0)throw new H3.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(gi.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=gi.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&gi.TRANSACTION_OPTIONS_TX_HASH_SIGN)==gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&gi.TRANSACTION_OPTIONS_TX_GUARDED)==gi.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=gi.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};On.TransactionOptions=mv});var wv=B((tpe,z3)=>{"use strict";h();var Qd="qpzry9x8gf2tvdw0s3jn54khce6mua7l",yv={};for(Yl=0;Yl>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function G3(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=G3(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Pu(n)^o,i+=Qd.charAt(o)}for(s=0;s<6;++s)n=Pu(n);for(n^=1,s=0;s<6;++s){var u=n>>(5-s)*5&31;i+=Qd.charAt(u)}return i}function j3(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var u=G3(s);if(typeof u=="string")return u;for(var a=[],c=0;c=o.length)&&a.push(d)}return u!==1?"Invalid checksum for "+t:{prefix:s,words:a}}function eH(){var t=j3.apply(null,arguments);if(typeof t=="object")return t}function tH(t){var e=j3.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function Kd(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<{"use strict";h();var oH=Nt&&Nt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),aH=Nt&&Nt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uH=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oH(e,t,r);return aH(e,t),e},cH=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.addressToHex=Nt.bigIntToHex=Nt.byteArrayToHex=Nt.boolToHex=Nt.utf8ToHex=Nt.zeroPadStringIfOddLength=Nt.isPaddedHex=Nt.numberToPaddedHex=void 0;var lH=cH((rr(),_e(fr))),fH=Ve(),hH=uH(Bu());function dH(t){let e;typeof t=="bigint"||typeof t=="number"?e=t:e=new lH.default(t);let r=e.toString(16);return Wd(r)}Nt.numberToPaddedHex=dH;function gH(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Nt.isPaddedHex=gH;function Wd(t){return t=t||"",t.length%2==1?"0"+t:t}Nt.zeroPadStringIfOddLength=Wd;function Q3(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.utf8ToHex=Q3;function pH(t){return Q3(t.toString())}Nt.boolToHex=pH;function mH(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.byteArrayToHex=mH;function yH(t){return t==0?"":hH.getHexMagnitudeOfBigInt(t)}Nt.bigIntToHex=yH;function wH(t){return fH.Address.fromBech32(t.toString()).pubkey().toString("hex")}Nt.addressToHex=wH});var Bu=B(nr=>{"use strict";h();var vH=nr&&nr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nr,"__esModule",{value:!0});nr.prependByteToBuffer=nr.flipBufferBitsInPlace=nr.getHexMagnitudeOfBigInt=nr.bigIntToBuffer=nr.bufferToBigInt=nr.cloneBuffer=nr.isMsbZero=nr.isMsbOne=void 0;var vv=vH((rr(),_e(fr))),AH=Ru();function K3(t,e=0){return t[e]>>7==1}nr.isMsbOne=K3;function EH(t,e=0){return!K3(t,e)}nr.isMsbZero=EH;function bH(t){let e=p.Buffer.alloc(t.length);return t.copy(e),e}nr.cloneBuffer=bH;function SH(t){let e=t.toString("hex");return new vv.default(`0x${e}`,16)}nr.bufferToBigInt=SH;function IH(t){let e=W3(t);return p.Buffer.from(e,"hex")}nr.bigIntToBuffer=IH;function W3(t){return t=new vv.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new vv.default(-1))),AH.numberToPaddedHex(t)):""}nr.getHexMagnitudeOfBigInt=W3;function TH(t){for(let e=0;e{"use strict";h();var CH=Lt&&Lt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NH=Lt&&Lt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$3=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&CH(e,t,r);return NH(e,t),e},xH=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.bufferToHex=Lt.addressToHex=Lt.bigIntToHex=Lt.utf8ToHex=Lt.bigIntToBuffer=Lt.bufferToBigInt=Lt.stringToBuffer=void 0;var OH=xH((rr(),_e(fr))),Y3=$3(Bu()),DH=$3(Ru());function PH(t){return p.Buffer.from(t)}Lt.stringToBuffer=PH;function RH(t){return t.length==0?new OH.default(0):Y3.bufferToBigInt(t)}Lt.bufferToBigInt=RH;function BH(t){return t==0?p.Buffer.from([]):Y3.bigIntToBuffer(t)}Lt.bigIntToBuffer=BH;var Av=Ru();Object.defineProperty(Lt,"utf8ToHex",{enumerable:!0,get:function(){return Av.utf8ToHex}});Object.defineProperty(Lt,"bigIntToHex",{enumerable:!0,get:function(){return Av.bigIntToHex}});Object.defineProperty(Lt,"addressToHex",{enumerable:!0,get:function(){return Av.addressToHex}});function MH(t){let e=t.toString("hex");return DH.zeroPadStringIfOddLength(e)}Lt.bufferToHex=MH});var Ds=B((cpe,Ev)=>{"use strict";h();var Mu=typeof Reflect=="object"?Reflect:null,J3=Mu&&typeof Mu.apply=="function"?Mu.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Yd;Mu&&typeof Mu.ownKeys=="function"?Yd=Mu.ownKeys:Object.getOwnPropertySymbols?Yd=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Yd=function(e){return Object.getOwnPropertyNames(e)};function LH(t){console&&console.warn&&console.warn(t)}var Z3=Number.isNaN||function(e){return e!==e};function _t(){_t.init.call(this)}Ev.exports=_t;Ev.exports.once=VH;_t.EventEmitter=_t;_t.prototype._events=void 0;_t.prototype._eventsCount=0;_t.prototype._maxListeners=void 0;var X3=10;function Jd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_t,"defaultMaxListeners",{enumerable:!0,get:function(){return X3},set:function(t){if(typeof t!="number"||t<0||Z3(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");X3=t}});_t.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_t.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Z3(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function eN(t){return t._maxListeners===void 0?_t.defaultMaxListeners:t._maxListeners}_t.prototype.getMaxListeners=function(){return eN(this)};_t.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var u=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw u.context=o,u}var a=s[e];if(a===void 0)return!1;if(typeof a=="function")J3(a,this,r);else for(var c=a.length,f=sN(a,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=o.length,LH(u)}return t}_t.prototype.addListener=function(e,r){return tN(this,e,r,!1)};_t.prototype.on=_t.prototype.addListener;_t.prototype.prependListener=function(e,r){return tN(this,e,r,!0)};function FH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function rN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=FH.bind(n);return i.listener=r,n.wrapFn=i,i}_t.prototype.once=function(e,r){return Jd(r),this.on(e,rN(this,e,r)),this};_t.prototype.prependOnceListener=function(e,r){return Jd(r),this.prependListener(e,rN(this,e,r)),this};_t.prototype.removeListener=function(e,r){var n,i,s,o,u;if(Jd(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){u=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():UH(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||r)}return this};_t.prototype.off=_t.prototype.removeListener;_t.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function nN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?qH(i):sN(i,i.length)}_t.prototype.listeners=function(e){return nN(this,e,!0)};_t.prototype.rawListeners=function(e){return nN(this,e,!1)};_t.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):iN.call(t,e)};_t.prototype.listenerCount=iN;function iN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_t.prototype.eventNames=function(){return this._eventsCount>0?Yd(this._events):[]};function sN(t,e){for(var r=new Array(e),n=0;n{h();aN.exports=Ds().EventEmitter});var Sv=B(()=>{h()});var dN=B((mpe,hN)=>{"use strict";h();function uN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function cN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Xd.alloc(0);for(var n=Xd.allocUnsafe(r>>>0),i=this.head,s=0;i;)$H(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(u===o.length?s+=o:s+=o.slice(0,r),r-=u,r===0){u===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(u));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Xd.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,u=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,u),r-=u,r===0){u===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(u));break}++s}return this.length-=s,n}},{key:WH,value:function(r,n){return Iv(this,cN(cN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var _v=B((wpe,pN)=>{"use strict";h();function YH(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,I.default.nextTick(Tv,this,t)):I.default.nextTick(Tv,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?I.default.nextTick(Zd,r):(r._writableState.errorEmitted=!0,I.default.nextTick(gN,r,s)):I.default.nextTick(gN,r,s):e?(I.default.nextTick(Zd,r),e(s)):I.default.nextTick(Zd,r)}),this)}function gN(t,e){Tv(t,e),Zd(t)}function Zd(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function JH(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Tv(t,e){t.emit("error",e)}function XH(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}pN.exports={destroy:YH,undestroy:JH,errorOrDestroy:XH}});var Oa=B((Ape,wN)=>{"use strict";h();function ZH(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var yN={};function Dn(t,e,r){r||(r=Error);function n(s,o,u){return typeof e=="string"?e:e(s,o,u)}var i=function(s){ZH(o,s);function o(u,a,c){return s.call(this,n(u,a,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,yN[t]=i}function mN(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function eG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function tG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function rG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}Dn("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);Dn("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&eG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(tG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(mN(e,"type"));else{var s=rG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(mN(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);Dn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");Dn("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});Dn("ERR_STREAM_PREMATURE_CLOSE","Premature close");Dn("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});Dn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");Dn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");Dn("ERR_STREAM_WRITE_AFTER_END","write after end");Dn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Dn("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);Dn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");wN.exports.codes=yN});var Cv=B((bpe,vN)=>{"use strict";h();var nG=Oa().codes.ERR_INVALID_OPT_VALUE;function iG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function sG(t,e,r,n){var i=iG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new nG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}vN.exports={getHighWaterMark:sG}});var Lu=B((Ipe,Nv)=>{h();typeof Object.create=="function"?Nv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Nv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var EN=B((_pe,AN)=>{h();AN.exports=oG;function oG(t,e){if(xv("noDeprecation"))return t;var r=!1;function n(){if(!r){if(xv("throwDeprecation"))throw new Error(e);xv("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function xv(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var Pv=B((Npe,CN)=>{"use strict";h();CN.exports=Gt;function SN(t){var e=this;this.next=null,this.entry=null,this.finish=function(){RG(e,t)}}var Fu;Gt.WritableState=Xl;var aG={deprecate:EN()},IN=bv(),tg=io().Buffer,uG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cG(t){return tg.from(t)}function lG(t){return tg.isBuffer(t)||t instanceof uG}var Dv=_v(),fG=Cv(),hG=fG.getHighWaterMark,ao=Oa().codes,dG=ao.ERR_INVALID_ARG_TYPE,gG=ao.ERR_METHOD_NOT_IMPLEMENTED,pG=ao.ERR_MULTIPLE_CALLBACK,mG=ao.ERR_STREAM_CANNOT_PIPE,yG=ao.ERR_STREAM_DESTROYED,wG=ao.ERR_STREAM_NULL_VALUES,vG=ao.ERR_STREAM_WRITE_AFTER_END,AG=ao.ERR_UNKNOWN_ENCODING,Uu=Dv.errorOrDestroy;Lu()(Gt,IN);function EG(){}function Xl(t,e,r){Fu=Fu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof Fu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=hG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){NG(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new SN(this)}Xl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(Xl.prototype,"buffer",{get:aG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var eg;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(eg=Function.prototype[Symbol.hasInstance],Object.defineProperty(Gt,Symbol.hasInstance,{value:function(e){return eg.call(this,e)?!0:this!==Gt?!1:e&&e._writableState instanceof Xl}})):eg=function(e){return e instanceof this};function Gt(t){Fu=Fu||Da();var e=this instanceof Fu;if(!e&&!eg.call(Gt,this))return new Gt(t);this._writableState=new Xl(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),IN.call(this)}Gt.prototype.pipe=function(){Uu(this,new mG)};function bG(t,e){var r=new vG;Uu(t,r),I.default.nextTick(e,r)}function SG(t,e,r,n){var i;return r===null?i=new wG:typeof r!="string"&&!e.objectMode&&(i=new dG("chunk",["string","Buffer"],r)),i?(Uu(t,i),I.default.nextTick(n,i),!1):!0}Gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&lG(t);return s&&!tg.isBuffer(t)&&(t=cG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=EG),n.ending?bG(this,r):(s||SG(this,n,t,r))&&(n.pendingcb++,i=TG(this,n,s,t,e,r)),i};Gt.prototype.cork=function(){this._writableState.corked++};Gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&TN(this,t))};Gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new AG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function IG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=tg.from(e,r)),e}Object.defineProperty(Gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function TG(t,e,r,n,i,s){if(!r){var o=IG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length{"use strict";h();var BG=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};xN.exports=Li;var NN=Mv(),Bv=Pv();Lu()(Li,NN);for(Rv=BG(Bv.prototype),rg=0;rg{h();var ig=io(),Fi=ig.Buffer;function ON(t,e){for(var r in t)e[r]=t[r]}Fi.from&&Fi.alloc&&Fi.allocUnsafe&&Fi.allocUnsafeSlow?DN.exports=ig:(ON(ig,Lv),Lv.Buffer=Pa);function Pa(t,e,r){return Fi(t,e,r)}Pa.prototype=Object.create(Fi.prototype);ON(Fi,Pa);Pa.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Fi(t,e,r)};Pa.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Fi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Pa.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fi(t)};Pa.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ig.SlowBuffer(t)}});var qv=B(BN=>{"use strict";h();var Uv=PN().Buffer,RN=Uv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function FG(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function UG(t){var e=FG(t);if(typeof e!="string"&&(Uv.isEncoding===RN||!RN(t)))throw new Error("Unknown encoding: "+t);return e||t}BN.StringDecoder=Zl;function Zl(t){this.encoding=UG(t);var e;switch(this.encoding){case"utf16le":this.text=jG,this.end=zG,e=4;break;case"utf8":this.fillLast=kG,e=4;break;case"base64":this.text=QG,this.end=KG,e=3;break;default:this.write=WG,this.end=$G;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Uv.allocUnsafe(e)}Zl.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function qG(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function VG(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function kG(t){var e=this.lastTotal-this.lastNeed,r=VG(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function HG(t,e){var r=qG(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function GG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function jG(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function zG(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function QG(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function KG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function WG(t){return t.toString(this.encoding)}function $G(t){return t&&t.length?this.write(t):""}});var sg=B((Mpe,FN)=>{"use strict";h();var MN=Oa().codes.ERR_STREAM_PREMATURE_CLOSE;function YG(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";h();var og;function uo(t,e,r){return e=ZG(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ZG(t){var e=ej(t,"string");return typeof e=="symbol"?e:String(e)}function ej(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var tj=sg(),co=Symbol("lastResolve"),Ra=Symbol("lastReject"),ef=Symbol("error"),ag=Symbol("ended"),Ba=Symbol("lastPromise"),Vv=Symbol("handlePromise"),Ma=Symbol("stream");function lo(t,e){return{value:t,done:e}}function rj(t){var e=t[co];if(e!==null){var r=t[Ma].read();r!==null&&(t[Ba]=null,t[co]=null,t[Ra]=null,e(lo(r,!1)))}}function nj(t){I.default.nextTick(rj,t)}function ij(t,e){return function(r,n){t.then(function(){if(e[ag]){r(lo(void 0,!0));return}e[Vv](r,n)},n)}}var sj=Object.getPrototypeOf(function(){}),oj=Object.setPrototypeOf((og={get stream(){return this[Ma]},next:function(){var e=this,r=this[ef];if(r!==null)return Promise.reject(r);if(this[ag])return Promise.resolve(lo(void 0,!0));if(this[Ma].destroyed)return new Promise(function(o,u){I.default.nextTick(function(){e[ef]?u(e[ef]):o(lo(void 0,!0))})});var n=this[Ba],i;if(n)i=new Promise(ij(n,this));else{var s=this[Ma].read();if(s!==null)return Promise.resolve(lo(s,!1));i=new Promise(this[Vv])}return this[Ba]=i,i}},uo(og,Symbol.asyncIterator,function(){return this}),uo(og,"return",function(){var e=this;return new Promise(function(r,n){e[Ma].destroy(null,function(i){if(i){n(i);return}r(lo(void 0,!0))})})}),og),sj),aj=function(e){var r,n=Object.create(oj,(r={},uo(r,Ma,{value:e,writable:!0}),uo(r,co,{value:null,writable:!0}),uo(r,Ra,{value:null,writable:!0}),uo(r,ef,{value:null,writable:!0}),uo(r,ag,{value:e._readableState.endEmitted,writable:!0}),uo(r,Vv,{value:function(s,o){var u=n[Ma].read();u?(n[Ba]=null,n[co]=null,n[Ra]=null,s(lo(u,!1))):(n[co]=s,n[Ra]=o)},writable:!0}),r));return n[Ba]=null,tj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Ra];s!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,s(i)),n[ef]=i;return}var o=n[co];o!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,o(lo(void 0,!0))),n[ag]=!0}),e.on("readable",nj.bind(null,n)),n};UN.exports=aj});var kN=B((qpe,VN)=>{h();VN.exports=function(){throw new Error("Readable.from is not available in the browser")}});var Mv=B((Hpe,JN)=>{"use strict";h();JN.exports=Fe;var qu;Fe.ReadableState=zN;var kpe=Ds().EventEmitter,jN=function(e,r){return e.listeners(r).length},rf=bv(),ug=io().Buffer,uj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cj(t){return ug.from(t)}function lj(t){return ug.isBuffer(t)||t instanceof uj}var kv=Sv(),Ne;kv&&kv.debuglog?Ne=kv.debuglog("stream"):Ne=function(){};var fj=dN(),Wv=_v(),hj=Cv(),dj=hj.getHighWaterMark,cg=Oa().codes,gj=cg.ERR_INVALID_ARG_TYPE,pj=cg.ERR_STREAM_PUSH_AFTER_EOF,mj=cg.ERR_METHOD_NOT_IMPLEMENTED,yj=cg.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Vu,Hv,Gv;Lu()(Fe,rf);var tf=Wv.errorOrDestroy,jv=["error","close","destroy","pause","resume"];function wj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function zN(t,e,r){qu=qu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof qu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=dj(this,t,"readableHighWaterMark",r),this.buffer=new fj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Vu||(Vu=qv().StringDecoder),this.decoder=new Vu(t.encoding),this.encoding=t.encoding)}function Fe(t){if(qu=qu||Da(),!(this instanceof Fe))return new Fe(t);var e=this instanceof qu;this._readableState=new zN(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),rf.call(this)}Object.defineProperty(Fe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Fe.prototype.destroy=Wv.destroy;Fe.prototype._undestroy=Wv.undestroy;Fe.prototype._destroy=function(t,e){e(t)};Fe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=ug.from(t,e),e=""),n=!0),QN(this,t,e,!1,n)};Fe.prototype.unshift=function(t){return QN(this,t,null,!0,!1)};function QN(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Ej(t,s);else{var o;if(i||(o=vj(s,e)),o)tf(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==ug.prototype&&(e=cj(e)),n)s.endEmitted?tf(t,new yj):zv(t,s,e,!0);else if(s.ended)tf(t,new pj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?zv(t,s,e,!1):Kv(t,s)):zv(t,s,e,!1)}else n||(s.reading=!1,Kv(t,s))}return!s.ended&&(s.length=HN?t=HN:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function GN(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=Aj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}Fe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Qv(this):lg(this),null;if(t=GN(t,e),t===0&&e.ended)return e.length===0&&Qv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=$N(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Qv(this)),i!==null&&this.emit("data",i),i};function Ej(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?lg(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,KN(t)))}}function lg(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,I.default.nextTick(KN,t))}function KN(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,$v(t)}function Kv(t,e){e.readingMore||(e.readingMore=!0,I.default.nextTick(bj,t,e))}function bj(t,e){for(;!e.reading&&!e.ended&&(e.length1&&YN(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function w(R){Ne("onerror",R),x(),t.removeListener("error",w),jN(t,"error")===0&&tf(t,R)}wj(t,"error",w);function A(){t.removeListener("finish",T),x()}t.once("close",A);function T(){Ne("onfinish"),t.removeListener("close",A),x()}t.once("finish",T);function x(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Sj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&jN(t,"data")&&(r.flowing=!0,$v(t))}}Fe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?lg(this):n.reading||I.default.nextTick(Ij,this)),r};Fe.prototype.addListener=Fe.prototype.on;Fe.prototype.removeListener=function(t,e){var r=rf.prototype.removeListener.call(this,t,e);return t==="readable"&&I.default.nextTick(WN,this),r};Fe.prototype.removeAllListeners=function(t){var e=rf.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&I.default.nextTick(WN,this),e};function WN(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Ij(t){Ne("readable nexttick read 0"),t.read(0)}Fe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Tj(this,t)),t.paused=!1,this};function Tj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,I.default.nextTick(_j,t,e))}function _j(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),$v(t),e.flowing&&!e.reading&&t.read(0)}Fe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function $v(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}Fe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var u=e.push(o);u||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(u){return function(){return t[u].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Qv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,I.default.nextTick(Cj,e,t))}function Cj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(Fe.from=function(t,e){return Gv===void 0&&(Gv=kN()),Gv(Fe,t,e)});function YN(t,e){for(var r=0,n=t.length;r{"use strict";h();ZN.exports=Ps;var fg=Oa().codes,Nj=fg.ERR_METHOD_NOT_IMPLEMENTED,xj=fg.ERR_MULTIPLE_CALLBACK,Oj=fg.ERR_TRANSFORM_ALREADY_TRANSFORMING,Dj=fg.ERR_TRANSFORM_WITH_LENGTH_0,hg=Da();Lu()(Ps,hg);function Pj(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new xj);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";h();tx.exports=nf;var ex=Yv();Lu()(nf,ex);function nf(t){if(!(this instanceof nf))return new nf(t);ex.call(this,t)}nf.prototype._transform=function(t,e,r){r(null,t)}});var ax=B((Wpe,ox)=>{"use strict";h();var Jv;function Bj(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var sx=Oa().codes,Mj=sx.ERR_MISSING_ARGS,Lj=sx.ERR_STREAM_DESTROYED;function nx(t){if(t)throw t}function Fj(t){return t.setHeader&&typeof t.abort=="function"}function Uj(t,e,r,n){n=Bj(n);var i=!1;t.on("close",function(){i=!0}),Jv===void 0&&(Jv=sg()),Jv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Fj(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new Lj("pipe"))}}}function ix(t){t()}function qj(t,e){return t.pipe(e)}function Vj(t){return!t.length||typeof t[t.length-1]!="function"?nx:t.pop()}function kj(){for(var t=arguments.length,e=new Array(t),r=0;r0;return Uj(o,a,c,function(f){i||(i=f),f&&s.forEach(ix),!a&&(s.forEach(ix),n(i))})});return e.reduce(qj)}ox.exports=kj});var Xv=B((Pn,ux)=>{h();Pn=ux.exports=Mv();Pn.Stream=Pn;Pn.Readable=Pn;Pn.Writable=Pv();Pn.Duplex=Da();Pn.Transform=Yv();Pn.PassThrough=rx();Pn.finished=sg();Pn.pipeline=ax()});var fx=B((Jpe,lx)=>{h();var{Transform:Hj}=Xv();lx.exports=t=>class cx extends Hj{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new cx(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var gx=B((Zpe,dx)=>{h();var{Transform:Gj}=Xv();dx.exports=t=>class hx extends Gj{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new hx(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var mx=B((t0e,px)=>{h();var jj=fx(),zj=gx();px.exports=function(t){let e=jj(t),r=zj(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var vx=B(wx=>{h();var yx=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];wx.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],u=t[5]^t[15]^t[25]^t[35]^t[45],a=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],w=f^(i<<1|s>>>31),A=d^(s<<1|i>>>31),T=t[0]^w,x=t[1]^A,R=t[10]^w,V=t[11]^A,U=t[20]^w,Q=t[21]^A,L=t[30]^w,k=t[31]^A,H=t[40]^w,q=t[41]^A;w=r^(o<<1|u>>>31),A=n^(u<<1|o>>>31);let v=t[2]^w,C=t[3]^A,D=t[12]^w,F=t[13]^A,P=t[22]^w,l=t[23]^A,g=t[32]^w,y=t[33]^A,E=t[42]^w,S=t[43]^A;w=i^(a<<1|c>>>31),A=s^(c<<1|a>>>31);let _=t[4]^w,M=t[5]^A,N=t[14]^w,m=t[15]^A,O=t[24]^w,Y=t[25]^A,$=t[34]^w,b=t[35]^A,j=t[44]^w,z=t[45]^A;w=o^(f<<1|d>>>31),A=u^(d<<1|f>>>31);let W=t[6]^w,ie=t[7]^A,te=t[16]^w,ee=t[17]^A,se=t[26]^w,oe=t[27]^A,J=t[36]^w,ue=t[37]^A,wt=t[46]^w,vt=t[47]^A;w=a^(r<<1|n>>>31),A=c^(n<<1|r>>>31);let Ni=t[8]^w,At=t[9]^A,Et=t[18]^w,xi=t[19]^A,bt=t[28]^w,St=t[29]^A,Oi=t[38]^w,It=t[39]^A,Tt=t[48]^w,Di=t[49]^A,Qe=T,Ke=x,ri=V<<4|R>>>28,We=R<<4|V>>>28,$e=U<<3|Q>>>29,ni=Q<<3|U>>>29,Ye=k<<9|L>>>23,Je=L<<9|k>>>23,ii=H<<18|q>>>14,Xe=q<<18|H>>>14,Ze=v<<1|C>>>31,si=C<<1|v>>>31,et=F<<12|D>>>20,tt=D<<12|F>>>20,oi=P<<10|l>>>22,rt=l<<10|P>>>22,nt=y<<13|g>>>19,ai=g<<13|y>>>19,it=E<<2|S>>>30,st=S<<2|E>>>30,ui=M<<30|_>>>2,ot=_<<30|M>>>2,at=N<<6|m>>>26,ci=m<<6|N>>>26,ut=Y<<11|O>>>21,ct=O<<11|Y>>>21,li=$<<15|b>>>17,lt=b<<15|$>>>17,ft=z<<29|j>>>3,fi=j<<29|z>>>3,ht=W<<28|ie>>>4,dt=ie<<28|W>>>4,hi=ee<<23|te>>>9,gt=te<<23|ee>>>9,pt=se<<25|oe>>>7,vn=oe<<25|se>>>7,An=J<<21|ue>>>11,En=ue<<21|J>>>11,bn=vt<<24|wt>>>8,Sn=wt<<24|vt>>>8,In=Ni<<27|At>>>5,da=At<<27|Ni>>>5,ga=Et<<20|xi>>>12,pa=xi<<20|Et>>>12,ma=St<<7|bt>>>25,ya=bt<<7|St>>>25,wa=Oi<<8|It>>>24,va=It<<8|Oi>>>24,Aa=Tt<<14|Di>>>18,Ea=Di<<14|Tt>>>18;t[0]=Qe^~et&ut,t[1]=Ke^~tt&ct,t[10]=ht^~ga&$e,t[11]=dt^~pa&ni,t[20]=Ze^~at&pt,t[21]=si^~ci&vn,t[30]=In^~ri&oi,t[31]=da^~We&rt,t[40]=ui^~hi&ma,t[41]=ot^~gt&ya,t[2]=et^~ut&An,t[3]=tt^~ct&En,t[12]=ga^~$e&nt,t[13]=pa^~ni&ai,t[22]=at^~pt&wa,t[23]=ci^~vn&va,t[32]=ri^~oi&li,t[33]=We^~rt<,t[42]=hi^~ma&Ye,t[43]=gt^~ya&Je,t[4]=ut^~An&Aa,t[5]=ct^~En&Ea,t[14]=$e^~nt&ft,t[15]=ni^~ai&fi,t[24]=pt^~wa&ii,t[25]=vn^~va&Xe,t[34]=oi^~li&bn,t[35]=rt^~lt&Sn,t[44]=ma^~Ye&it,t[45]=ya^~Je&st,t[6]=An^~Aa&Qe,t[7]=En^~Ea&Ke,t[16]=nt^~ft&ht,t[17]=ai^~fi&dt,t[26]=wa^~ii&Ze,t[27]=va^~Xe&si,t[36]=li^~bn&In,t[37]=lt^~Sn&da,t[46]=Ye^~it&ui,t[47]=Je^~st&ot,t[8]=Aa^~Qe&et,t[9]=Ea^~Ke&tt,t[18]=ft^~ht&ga,t[19]=fi^~dt&pa,t[28]=ii^~Ze&at,t[29]=Xe^~si&ci,t[38]=bn^~In&ri,t[39]=Sn^~da&We,t[48]=it^~ui&hi,t[49]=st^~ot>,t[0]^=yx[e*2],t[1]^=yx[e*2+1]}}});var Ex=B((s0e,Ax)=>{h();var dg=vx();function ku(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}ku.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};ku.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(dg.p1600(this.state),this.count=0);return e};ku.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};Ax.exports=ku});var sf=B((a0e,bx)=>{h();bx.exports=mx()(Ex())});var Ve=B(Kr=>{"use strict";h();var Qj=Kr&&Kr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Kj=Kr&&Kr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Sx=Kr&&Kr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qj(e,t,r);return Kj(e,t),e},Wj=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.AddressComputer=Kr.Address=void 0;var Hu=Sx(wv()),$j=Wj((rr(),_e(fr))),Zv=hr(),Gu=Sx(Ie()),Yj=$d(),Jj=sf(),of="erd",gg=32,Xj="0".repeat(16),pg=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(ArrayBuffer.isView(e))return t.fromBuffer(p.Buffer.from(e));if(typeof e=="string")return t.fromString(e);throw new Gu.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=t.empty();return r.valueHex=e,r}static fromBuffer(e){if(e.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==gg}static fromHex(e){if(!t.isValidHex(e))throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t("")}static fromBech32(e){let r;try{r=Hu.decode(e)}catch(s){throw new Gu.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=of)throw new Gu.ErrAddressBadHrp(of,n);let i=p.Buffer.from(Hu.fromWords(r.words));if(i.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=Hu.decodeUnsafe(e),n=r?.prefix,i=r?p.Buffer.from(Hu.fromWords(r.words)):void 0;return!(n!==of||i?.length!==gg)}hex(){return this.toHex()}toHex(){return this.isEmpty()?"":this.valueHex}bech32(){return this.toBech32()}toBech32(){if(this.isEmpty())return"";let e=Hu.toWords(this.pubkey());return Hu.encode(of,e)}pubkey(){return this.getPublicKey()}getPublicKey(){return this.isEmpty()?p.Buffer.from([]):p.Buffer.from(this.valueHex,"hex")}getHrp(){return of}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.toBech32()}toJSON(){return{bech32:this.toBech32(),pubkey:this.toHex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.isSmartContract()}isSmartContract(){return this.toHex().startsWith(Xj)}};Kr.Address=pg;var eA=class{constructor(e){this.numberOfShardsWithoutMeta=e||Zv.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META}computeContractAddress(e,r){let n=p.Buffer.alloc(8,0),i=e.getPublicKey(),s=i.slice(30),o=p.Buffer.alloc(8),u=new $j.default(r.toString()),a=Yj.bigIntToBuffer(u);o.write(a.reverse().toString("hex"),"hex");let c=p.Buffer.concat([i,o]),f=Jj("keccak256").update(c).digest(),d=p.Buffer.from(Zv.WasmVirtualMachine,"hex"),w=p.Buffer.concat([n,d,f.slice(10,30),s]);return new pg(w)}getShardOfAddress(e){return this.getShardOfPubkey(e.getPublicKey(),this.numberOfShardsWithoutMeta)}getShardOfPubkey(e,r){let n=parseInt("11",2),i=parseInt("01",2),s=e[31];if(this.isPubkeyOfMetachain(e))return Zv.METACHAIN_ID;let o=s&n;return o>r-1&&(o=s&i),o}isPubkeyOfMetachain(e){let r=p.Buffer.from([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n=p.Buffer.from(e).slice(0,r.length);return!!(r.equals(n)||p.Buffer.alloc(32).equals(p.Buffer.from(e)))}};Kr.AddressComputer=eA});var Rn=B(Ft=>{"use strict";h();var Zj=Ft&&Ft.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ez=Ft&&Ft.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tz=Ft&&Ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zj(e,t,r);return ez(e,t),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.isEmpty=Ft.guardEmpty=Ft.guardNotEmpty=Ft.guardLength=Ft.guardSameLength=Ft.guardValueIsSetWithMessage=Ft.guardValueIsSet=Ft.guardTrue=void 0;var ju=tz(Ie());function rz(t,e){if(!t)throw new ju.ErrInvariantFailed(`[<${e}>] isn't true`)}Ft.guardTrue=rz;function nz(t,e){Ix(`${t} isn't set (null or undefined)`,e)}Ft.guardValueIsSet=nz;function Ix(t,e){if(e==null||e===void 0)throw new ju.ErrInvariantFailed(t)}Ft.guardValueIsSetWithMessage=Ix;function iz(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new ju.ErrInvariantFailed("arrays do not have the same length")}Ft.guardSameLength=iz;function sz(t,e){let r=t.length||0;if(r!=e)throw new ju.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}Ft.guardLength=sz;function oz(t,e){if(tA(t))throw new ju.ErrInvariantFailed(`${e} is empty`)}Ft.guardNotEmpty=oz;function az(t,e){if(!tA(t))throw new ju.ErrInvariantFailed(`${e} is not empty`)}Ft.guardEmpty=az;function tA(t){return t.isEmpty?t.isEmpty():t.length===0}Ft.isEmpty=tA});var Tx=B(mg=>{"use strict";h();Object.defineProperty(mg,"__esModule",{value:!0});mg.TypeFormula=void 0;var rA=class{constructor(e,r){this.name=e,this.typeParameters=r}toString(){if(this.typeParameters.length>0){let e=this.typeParameters.map(r=>r.toString()).join(", ");return`${this.name}<${e}>`}else return this.name}};mg.TypeFormula=rA});var _x=B(yg=>{"use strict";h();Object.defineProperty(yg,"__esModule",{value:!0});yg.TypeFormulaParser=void 0;var af=Tx(),Ui=class t{parseExpression(e){e=e.trim();let r=this.tokenizeExpression(e).filter(s=>s!==t.COMMA),n=[];for(let s of r)if(this.isPunctuation(s))if(this.isEndOfTypeParameters(s)){let o=this.acquireTypeWithParameters(n);n.push(o)}else if(this.isBeginningOfTypeParameters(s))n.push(s);else throw new Error(`Unexpected token (punctuation): ${s}`);else n.push(s);if(n.length!==1)throw new Error(`Unexpected stack length at end of parsing: ${n.length}`);if(t.PUNCTUATION.includes(n[0]))throw new Error("Unexpected root element.");let i=n[0];if(i instanceof af.TypeFormula)return i;if(typeof i=="string")return new af.TypeFormula(i,[]);throw new Error(`Unexpected item on stack: ${i}`)}tokenizeExpression(e){let r=[],n="";for(let i of e)this.isPunctuation(i)?(n&&(r.push(n.trim()),n=""),r.push(i)):n+=i;return n&&r.push(n.trim()),r}acquireTypeWithParameters(e){let r=this.acquireTypeParameters(e),n=e.pop();return new af.TypeFormula(n,r.reverse())}acquireTypeParameters(e){let r=[];for(;;){let n=e.pop();if(n===void 0)throw new Error("Badly specified type parameters");if(this.isBeginningOfTypeParameters(n))break;if(n instanceof af.TypeFormula)r.push(n);else if(typeof n=="string")r.push(new af.TypeFormula(n,[]));else throw new Error(`Unexpected type parameter object in stack: ${n}`)}return r}isPunctuation(e){return t.PUNCTUATION.includes(e)}isEndOfTypeParameters(e){return e===t.END_TYPE_PARAMETERS}isBeginningOfTypeParameters(e){return e===t.BEGIN_TYPE_PARAMETERS}};yg.TypeFormulaParser=Ui;Ui.BEGIN_TYPE_PARAMETERS="<";Ui.END_TYPE_PARAMETERS=">";Ui.COMMA=",";Ui.PUNCTUATION=[Ui.COMMA,Ui.BEGIN_TYPE_PARAMETERS,Ui.END_TYPE_PARAMETERS]});var Cx=B(wg=>{"use strict";h();Object.defineProperty(wg,"__esModule",{value:!0});wg.getJavascriptPrototypesInHierarchy=void 0;function uz(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}wg.getJavascriptPrototypesInHierarchy=uz});var sr=B(ir=>{"use strict";h();Object.defineProperty(ir,"__esModule",{value:!0});ir.NullType=ir.TypePlaceholder=ir.isTyped=ir.PrimitiveValue=ir.TypedValue=ir.CustomType=ir.PrimitiveType=ir.TypeCardinality=ir.Type=void 0;var nA=Cx(),Nx=Rn(),fo=class t{constructor(e,r=[],n=uf.fixed(1)){Nx.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return Nx.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return nA.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};ir.Type=fo;fo.ClassName="Type";var uf=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};ir.TypeCardinality=uf;uf.MaxCardinality=4096;var vg=class t extends fo{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveType=vg;vg.ClassName="PrimitiveType";var Ag=class t extends fo{getClassName(){return t.ClassName}};ir.CustomType=Ag;Ag.ClassName="CustomType";var cf=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};ir.TypedValue=cf;cf.ClassName="TypedValue";var Eg=class t extends cf{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveValue=Eg;Eg.ClassName="PrimitiveValue";function cz(t){return t.belongsToTypesystem!==void 0}ir.isTyped=cz;var bg=class t extends fo{constructor(){super("...")}getClassName(){return t.ClassName}};ir.TypePlaceholder=bg;bg.ClassName="TypePlaceholder";var Sg=class t extends fo{constructor(){super("?")}getClassName(){return t.ClassName}};ir.NullType=Sg;Sg.ClassName="NullType"});var lf=B(Ig=>{"use strict";h();Object.defineProperty(Ig,"__esModule",{value:!0});Ig.TypeExpressionParser=void 0;var lz=_x(),fz=Ie(),hz=sr(),iA=class{constructor(){this.backingTypeFormulaParser=new lz.TypeFormulaParser}parse(e){try{return this.doParse(e)}catch(r){throw new fz.ErrTypingSystem(`Failed to parse type expression: ${e}. Error: ${r}`)}}doParse(e){let r=this.backingTypeFormulaParser.parseExpression(e);return this.typeFormulaToType(r)}typeFormulaToType(e){let r=e.typeParameters.map(n=>this.typeFormulaToType(n));return new hz.Type(e.name,r)}};Ig.TypeExpressionParser=iA});var oA=B(ho=>{"use strict";h();Object.defineProperty(ho,"__esModule",{value:!0});ho.EndpointParameterDefinition=ho.EndpointModifiers=ho.EndpointDefinition=void 0;var dz=lf(),xx="?",gz="N / A",sA=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?xx:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>ff.fromJSON(s)),n=e.outputs.map(s=>ff.fromJSON(s)),i=new Tg(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};ho.EndpointDefinition=sA;var Tg=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};ho.EndpointModifiers=Tg;var ff=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new dz.TypeExpressionParser().parse(e.type);return new t(e.name||xx,e.description||gz,r)}};ho.EndpointParameterDefinition=ff});var zu=B(Wr=>{"use strict";h();var pz=Wr&&Wr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),mz=Wr&&Wr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yz=Wr&&Wr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&pz(e,t,r);return mz(e,t),e};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Fields=Wr.Field=Wr.FieldDefinition=void 0;var aA=yz(Ie()),wz=lf(),uA=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new wz.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};Wr.FieldDefinition=uA;var cA=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new aA.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new aA.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};Wr.Field=cA;var lA=class{static checkTyping(e,r){if(e.length!=r.length)throw new aA.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";h();Object.defineProperty(go,"__esModule",{value:!0});go.EnumValue=go.EnumVariantDefinition=go.EnumType=void 0;var vz=Ie(),fA=Rn(),_g=zu(),Dx=sr(),Ox=256,Cg=class t extends Dx.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>Ng.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>({...n,discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return fA.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return fA.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};go.EnumType=Cg;Cg.ClassName="EnumType";var Ng=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],fA.guardTrue(r_g.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return _g.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};go.EnumVariantDefinition=Ng;var xg=class t extends Dx.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();_g.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=_g.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new vz.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};go.EnumValue=xg;xg.ClassName="EnumValue"});var Rx=B(Qu=>{"use strict";h();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.EventTopicDefinition=Qu.EventDefinition=void 0;var Az=lf(),Px="?",hA=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?Px:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>Og.fromJSON(n));return new t(e.identifier,r)}};Qu.EventDefinition=hA;var Og=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Az.TypeExpressionParser().parse(e.type);return new t({name:e.name||Px,type:r,indexed:e.indexed})}};Qu.EventTopicDefinition=Og});var Wu=B(Ku=>{"use strict";h();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.Struct=Ku.StructType=void 0;var Ez=Ie(),Dg=zu(),Bx=sr(),Pg=class t extends Bx.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>Dg.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Dg.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Ku.StructType=Pg;Pg.ClassName="StructType";var Rg=class t extends Bx.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();Dg.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Ez.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return Dg.Fields.equals(r,n)}};Ku.Struct=Rg;Rg.ClassName="Struct"});var Yu=B($u=>{"use strict";h();Object.defineProperty($u,"__esModule",{value:!0});$u.AddressValue=$u.AddressType=void 0;var bz=Ve(),Mx=sr(),df=class t extends Mx.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};$u.AddressType=df;df.ClassName="AddressType";var Bg=class t extends Mx.PrimitiveValue{constructor(e){super(new df),this.value=new bz.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};$u.AddressValue=Bg;Bg.ClassName="AddressValue"});var Lg=B(Ju=>{"use strict";h();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.OptionalValue=Ju.OptionalType=void 0;var Sz=Rn(),gf=sr(),pf=class t extends gf.Type{constructor(e){super("Optional",[e],gf.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(gf.NullType.ClassName);return r||n}};Ju.OptionalType=pf;pf.ClassName="OptionalType";var Mg=class t extends gf.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new pf(new gf.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return Sz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};Ju.OptionalValue=Mg;Mg.ClassName="OptionalValue"});var yf=B(Xu=>{"use strict";h();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.BooleanValue=Xu.BooleanType=void 0;var Lx=sr(),mf=class t extends Lx.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};Xu.BooleanType=mf;mf.ClassName="BooleanType";var Fg=class t extends Lx.PrimitiveValue{constructor(e){super(new mf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};Xu.BooleanValue=Fg;Fg.ClassName="BooleanValue"});var po=B(Zu=>{"use strict";h();Object.defineProperty(Zu,"__esModule",{value:!0});Zu.BytesValue=Zu.BytesType=void 0;var Fx=sr(),wf=class t extends Fx.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Zu.BytesType=wf;wf.ClassName="BytesType";var Ug=class t extends Fx.PrimitiveValue{constructor(e){super(new wf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=p.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=p.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Zu.BytesValue=Ug;Ug.ClassName="BytesValue"});var qx=B(ec=>{"use strict";h();Object.defineProperty(ec,"__esModule",{value:!0});ec.CodeMetadataValue=ec.CodeMetadataType=void 0;var Ux=sr(),qg=class extends Ux.PrimitiveType{constructor(){super("CodeMetadata")}};ec.CodeMetadataType=qg;var dA=class extends Ux.PrimitiveValue{constructor(e){super(new qg),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};ec.CodeMetadataValue=dA});var kg=B(tc=>{"use strict";h();Object.defineProperty(tc,"__esModule",{value:!0});tc.CompositeValue=tc.CompositeType=void 0;var Iz=Rn(),gA=sr(),vf=class t extends gA.Type{constructor(...e){super("Composite",e,gA.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};tc.CompositeType=vf;vf.ClassName="CompositeType";var Vg=class t extends gA.TypedValue{constructor(e,r){super(e),Iz.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new vf(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();Object.defineProperty(Hg,"__esModule",{value:!0});Hg.CollectionOfTypedValues=void 0;var pA=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";h();Object.defineProperty(qi,"__esModule",{value:!0});qi.List=qi.OptionValue=qi.ListType=qi.OptionType=void 0;var Tz=Rn(),_z=mA(),Fa=sr(),La=class t extends Fa.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Fa.NullType.ClassName);return r||n}};qi.OptionType=La;La.ClassName="OptionType";var Af=class t extends Fa.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};qi.ListType=Af;Af.ClassName="ListType";var Gg=class t extends Fa.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new La(new Fa.NullType);return new t(e)}static newMissingTyped(e){return new t(new La(e))}static newProvided(e){let r=new La(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return Tz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};qi.OptionValue=Gg;Gg.ClassName="OptionValue";var jg=class t extends Fa.TypedValue{constructor(e,r){super(e),this.backingCollection=new _z.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new Fa.TypePlaceholder,[]);let r=e[0].getType(),n=new Af(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};qi.List=jg;jg.ClassName="List"});var Kg=B(rc=>{"use strict";h();Object.defineProperty(rc,"__esModule",{value:!0});rc.ArrayVec=rc.ArrayVecType=void 0;var Vx=Rn(),Cz=mA(),kx=sr(),zg=class t extends kx.Type{constructor(e,r){super("Array",[r]),Vx.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};rc.ArrayVecType=zg;zg.ClassName="ArrayVecType";var Qg=class t extends kx.TypedValue{constructor(e,r){super(e),Vx.guardLength(r,e.length),this.backingCollection=new Cz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};rc.ArrayVec=Qg;Qg.ClassName="ArrayVec"});var Sf=B(nc=>{"use strict";h();Object.defineProperty(nc,"__esModule",{value:!0});nc.H256Value=nc.H256Type=void 0;var Hx=sr(),bf=class t extends Hx.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};nc.H256Type=bf;bf.ClassName="H256Type";var Wg=class t extends Hx.PrimitiveValue{constructor(e){super(new bf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};nc.H256Value=Wg;Wg.ClassName="H256Value"});var Yg=B(ic=>{"use strict";h();Object.defineProperty(ic,"__esModule",{value:!0});ic.NothingValue=ic.NothingType=void 0;var Gx=sr(),If=class t extends Gx.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};ic.NothingType=If;If.ClassName="NothingType";var $g=class t extends Gx.PrimitiveValue{constructor(){super(new If)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};ic.NothingValue=$g;$g.ClassName="NothingValue"});var Mf=B(Ee=>{"use strict";h();var Nz=Ee&&Ee.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xz=Ee&&Ee.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oz=Ee&&Ee.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nz(e,t,r);return xz(e,t),e},Dz=Ee&&Ee.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.BigIntValue=Ee.BigUIntValue=Ee.I64Value=Ee.U64Value=Ee.I32Value=Ee.U32Value=Ee.I16Value=Ee.U16Value=Ee.I8Value=Ee.U8Value=Ee.NumericalValue=Ee.BigIntType=Ee.BigUIntType=Ee.I64Type=Ee.U64Type=Ee.I32Type=Ee.U32Type=Ee.I16Type=Ee.U16Type=Ee.I8Type=Ee.U8Type=Ee.NumericalType=void 0;var Pz=Dz((rr(),_e(fr))),jx=Oz(Ie()),zx=sr(),$r=class t extends zx.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ee.NumericalType=$r;$r.ClassName="NumericalType";var Tf=class t extends $r{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ee.U8Type=Tf;Tf.ClassName="U8Type";var _f=class t extends $r{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ee.I8Type=_f;_f.ClassName="I8Type";var Cf=class t extends $r{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ee.U16Type=Cf;Cf.ClassName="U16Type";var Nf=class t extends $r{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ee.I16Type=Nf;Nf.ClassName="I16Type";var xf=class t extends $r{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ee.U32Type=xf;xf.ClassName="U32Type";var Of=class t extends $r{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ee.I32Type=Of;Of.ClassName="I32Type";var Df=class t extends $r{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ee.U64Type=Df;Df.ClassName="U64Type";var Pf=class t extends $r{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ee.I64Type=Pf;Pf.ClassName="I64Type";var Rf=class t extends $r{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ee.BigUIntType=Rf;Rf.ClassName="BigUIntType";var Bf=class t extends $r{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ee.BigIntType=Bf;Bf.ClassName="BigIntType";var Yr=class t extends zx.PrimitiveValue{constructor(e,r){if(super(e),typeof r=="bigint"&&(r=r.toString()),this.value=new Pz.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new jx.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new jx.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ee.NumericalValue=Yr;Yr.ClassName="NumericalValue";var Jg=class t extends Yr{constructor(e){super(new Tf,e)}getClassName(){return t.ClassName}};Ee.U8Value=Jg;Jg.ClassName="U8Value";var Xg=class t extends Yr{constructor(e){super(new _f,e)}getClassName(){return t.ClassName}};Ee.I8Value=Xg;Xg.ClassName="I8Value";var Zg=class t extends Yr{constructor(e){super(new Cf,e)}getClassName(){return t.ClassName}};Ee.U16Value=Zg;Zg.ClassName="U16Value";var ep=class t extends Yr{constructor(e){super(new Nf,e)}getClassName(){return t.ClassName}};Ee.I16Value=ep;ep.ClassName="I16Value";var tp=class t extends Yr{constructor(e){super(new xf,e)}getClassName(){return t.ClassName}};Ee.U32Value=tp;tp.ClassName="U32Value";var rp=class t extends Yr{constructor(e){super(new Of,e)}getClassName(){return t.ClassName}};Ee.I32Value=rp;rp.ClassName="I32Value";var np=class t extends Yr{constructor(e){super(new Df,e)}getClassName(){return t.ClassName}};Ee.U64Value=np;np.ClassName="U64Value";var ip=class t extends Yr{constructor(e){super(new Pf,e)}getClassName(){return t.ClassName}};Ee.I64Value=ip;ip.ClassName="I64Value";var sp=class t extends Yr{constructor(e){super(new Rf,e)}getClassName(){return t.ClassName}};Ee.BigUIntValue=sp;sp.ClassName="BigUIntValue";var op=class t extends Yr{constructor(e){super(new Bf,e)}getClassName(){return t.ClassName}};Ee.BigIntValue=op;op.ClassName="BigIntValue"});var up=B(sc=>{"use strict";h();Object.defineProperty(sc,"__esModule",{value:!0});sc.StringValue=sc.StringType=void 0;var Qx=sr(),Lf=class t extends Qx.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};sc.StringType=Lf;Lf.ClassName="StringType";var ap=class t extends Qx.PrimitiveValue{constructor(e){super(new Lf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=p.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};sc.StringValue=ap;ap.ClassName="StringValue"});var ac=B(oc=>{"use strict";h();Object.defineProperty(oc,"__esModule",{value:!0});oc.TokenIdentifierValue=oc.TokenIdentifierType=void 0;var Kx=sr(),Rz="EGLD",Ff=class t extends Kx.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};oc.TokenIdentifierType=Ff;Ff.ClassName="TokenIdentifierType";var cp=class t extends Kx.PrimitiveValue{constructor(e){super(new Ff),this.value=e}static egld(){return new t(Rz)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};oc.TokenIdentifierValue=cp;cp.ClassName="TokenIdentifierValue"});var fp=B(Bn=>{"use strict";h();var Bz=Bn&&Bn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Mz=Bn&&Bn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Lz=Bn&&Bn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bz(e,t,r);return Mz(e,t),e};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Tuple=Bn.TupleType=void 0;var Fz=Lz(Ie()),Wx=zu(),$x=Wu(),Uf=class t extends $x.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new Wx.FieldDefinition(Yx(i),"anonymous tuple field",n))}};Bn.TupleType=Uf;Uf.ClassName="TupleType";function Yx(t){return`field${t}`}var lp=class t extends $x.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Fz.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new Uf(...r),i=e.map((s,o)=>new Wx.Field(s,Yx(o)));return new t(n,i)}};Bn.Tuple=lp;lp.ClassName="Tuple"});var gp=B(mo=>{"use strict";h();Object.defineProperty(mo,"__esModule",{value:!0});mo.VariadicValue=mo.CountedVariadicType=mo.VariadicType=void 0;var uc=sr(),Ua=class t extends uc.Type{constructor(e,r=!1){super("Variadic",[e],uc.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};mo.VariadicType=Ua;Ua.ClassName="VariadicType";var hp=class extends uc.Type{constructor(e){super("Variadic",[e],uc.TypeCardinality.variable())}getClassName(){return Ua.ClassName}};mo.CountedVariadicType=hp;hp.ClassName="VariadicType";var dp=class t extends uc.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Ua(new uc.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Ua(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();var Uz=ki&&ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qz=ki&&ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vz=ki&&ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Uz(e,t,r);return qz(e,t),e};Object.defineProperty(ki,"__esModule",{value:!0});ki.TypeMapper=void 0;var Jx=Vz(Ie()),kz=Yu(),yA=Lg(),Hz=yf(),Gz=po(),jz=qx(),pp=kg(),wA=hf(),zz=zu(),Xx=Ef(),Vi=Kg(),Qz=Sf(),Zx=Yg(),Mn=Mf(),Kz=up(),e6=Wu(),t6=ac(),yo=fp(),mp=gp(),vA=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new Xx.OptionType(r[0])],["List",(...r)=>new Xx.ListType(r[0])],["VarArgs",(...r)=>new mp.VariadicType(r[0])],["MultiResultVec",(...r)=>new mp.VariadicType(r[0])],["variadic",(...r)=>new mp.VariadicType(r[0])],["counted-variadic",(...r)=>new mp.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new yA.OptionalType(r[0])],["optional",(...r)=>new yA.OptionalType(r[0])],["OptionalResult",(...r)=>new yA.OptionalType(r[0])],["multi",(...r)=>new pp.CompositeType(...r)],["MultiArg",(...r)=>new pp.CompositeType(...r)],["MultiResult",(...r)=>new pp.CompositeType(...r)],["multi",(...r)=>new pp.CompositeType(...r)],["tuple",(...r)=>new yo.TupleType(...r)],["tuple2",(...r)=>new yo.TupleType(...r)],["tuple3",(...r)=>new yo.TupleType(...r)],["tuple4",(...r)=>new yo.TupleType(...r)],["tuple5",(...r)=>new yo.TupleType(...r)],["tuple6",(...r)=>new yo.TupleType(...r)],["tuple7",(...r)=>new yo.TupleType(...r)],["tuple8",(...r)=>new yo.TupleType(...r)],["array2",(...r)=>new Vi.ArrayVecType(2,r[0])],["array8",(...r)=>new Vi.ArrayVecType(8,r[0])],["array16",(...r)=>new Vi.ArrayVecType(16,r[0])],["array20",(...r)=>new Vi.ArrayVecType(20,r[0])],["array32",(...r)=>new Vi.ArrayVecType(32,r[0])],["array46",(...r)=>new Vi.ArrayVecType(46,r[0])],["array48",(...r)=>new Vi.ArrayVecType(48,r[0])],["array64",(...r)=>new Vi.ArrayVecType(64,r[0])],["array128",(...r)=>new Vi.ArrayVecType(128,r[0])],["array256",(...r)=>new Vi.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new Mn.U8Type],["u16",new Mn.U16Type],["u32",new Mn.U32Type],["u64",new Mn.U64Type],["U64",new Mn.U64Type],["BigUint",new Mn.BigUIntType],["i8",new Mn.I8Type],["i16",new Mn.I16Type],["i32",new Mn.I32Type],["i64",new Mn.I64Type],["Bigint",new Mn.BigIntType],["BigInt",new Mn.BigIntType],["bool",new Hz.BooleanType],["bytes",new Gz.BytesType],["Address",new kz.AddressType],["H256",new Qz.H256Type],["utf-8 string",new Kz.StringType],["TokenIdentifier",new t6.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new t6.TokenIdentifierType],["CodeMetadata",new jz.CodeMetadataType],["nothing",new Zx.NothingType],["AsyncCall",new Zx.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new Jx.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(wA.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(e6.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new e6.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new wA.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new wA.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new zz.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new Jx.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};ki.TypeMapper=vA});var o6=B(Hi=>{"use strict";h();var Wz=Hi&&Hi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),$z=Hi&&Hi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yz=Hi&&Hi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wz(e,t,r);return $z(e,t),e};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.AbiRegistry=void 0;var r6=Yz(Ie()),qf=Rn(),Vf=oA(),n6=hf(),EA=Rx(),i6=Wu(),Jz=AA(),Xz="?",bA=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||Xz,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],u=Vf.EndpointDefinition.fromJSON({name:"constructor",...n}),a=i.map(A=>Vf.EndpointDefinition.fromJSON(A)),c=[];for(let A in s){let T=s[A];if(T.type=="struct")c.push(i6.StructType.fromJSON({name:A,fields:T.fields}));else if(T.type=="enum"||T.type=="explicit-enum")c.push(n6.EnumType.fromJSON({name:A,variants:T.variants}));else throw new r6.ErrTypingSystem(`Cannot handle custom type: ${A}`)}let f=o.map(A=>EA.EventDefinition.fromJSON(A));return new t({name:r,constructorDefinition:u,endpoints:a,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return qf.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(i6.StructType.ClassName));return qf.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(n6.EnumType.ClassName));return qf.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return qf.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return qf.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new Jz.TypeMapper([]),r=[];for(let u of this.customTypes)this.mapCustomTypeDepthFirst(u,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new r6.ErrTypingSystem("Did not re-map all custom types");let n=s6(this.constructorDefinition,e),i=[];for(let u of this.endpoints)i.push(s6(u,e));let s=this.events.map(u=>Zz(u,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(u=>u.getName()==e.getName())>=0)return;for(let u of e.getNamesOfDependencies()){let a=r.find(c=>c.getName()==u);a&&this.mapCustomTypeDepthFirst(a,r,n,i)}let o=n.mapType(e);i.push(o)}};Hi.AbiRegistry=bA;function s6(t,e){let r=t.input.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new Vf.EndpointDefinition(t.name,r,n,t.modifiers)}function Zz(t,e){let r=t.inputs.map(n=>new EA.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new EA.EventDefinition(t.identifier,r)}});var u6=B(cc=>{"use strict";h();Object.defineProperty(cc,"__esModule",{value:!0});cc.createListOfTokenIdentifiers=cc.createListOfAddresses=void 0;var eQ=Yu(),a6=Ef(),tQ=ac();function rQ(t){let e=t.map(n=>new eQ.AddressValue(n));return a6.List.fromItems(e)}cc.createListOfAddresses=rQ;function nQ(t){let e=t.map(n=>new tQ.TokenIdentifierValue(n));return a6.List.fromItems(e)}cc.createListOfTokenIdentifiers=nQ});var b6=B(Dr=>{"use strict";h();var iQ=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sQ=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oQ=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iQ(e,t,r);return sQ(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.onPrimitiveTypeSelect=Dr.onPrimitiveValueSelect=Dr.onTypedValueSelect=Dr.onTypeSelect=void 0;var wp=oQ(Ie()),c6=Yu(),l6=yf(),f6=po(),h6=hf(),yp=Ef(),d6=Sf(),g6=Mf(),p6=Yg(),m6=Wu(),y6=ac(),w6=fp(),v6=sr(),A6=Kg(),E6=up();function aQ(t,e){if(t.hasExactClass(yp.OptionType.ClassName))return e.onOption();if(t.hasExactClass(yp.ListType.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(v6.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(m6.StructType.ClassName))return e.onStruct();if(t.hasExactClass(w6.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't known: ${t}`)}Dr.onTypeSelect=aQ;function uQ(t,e){if(t.hasClassOrSuperclass(v6.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(yp.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(yp.List.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(m6.Struct.ClassName))return e.onStruct();if(t.hasExactClass(w6.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't typed: ${t}`)}Dr.onTypedValueSelect=uQ;function cQ(t,e){if(t.hasExactClass(l6.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringValue.ClassName))return e.onString();if(t.hasExactClass(d6.H256Value.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(p6.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Dr.onPrimitiveValueSelect=cQ;function lQ(t,e){if(t.hasExactClass(l6.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringType.ClassName))return e.onString();if(t.hasExactClass(d6.H256Type.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(p6.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Dr.onPrimitiveTypeSelect=lQ});var dr=B(He=>{"use strict";h();var fQ=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ut=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fQ(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});Ut(o6(),He);Ut(Yu(),He);Ut(Lg(),He);Ut(yf(),He);Ut(po(),He);Ut(kg(),He);Ut(oA(),He);Ut(hf(),He);Ut(u6(),He);Ut(zu(),He);Ut(Ef(),He);Ut(Kg(),He);Ut(Sf(),He);Ut(b6(),He);Ut(Yg(),He);Ut(Mf(),He);Ut(up(),He);Ut(Wu(),He);Ut(ac(),He);Ut(fp(),He);Ut(lf(),He);Ut(AA(),He);Ut(sr(),He);Ut(gp(),He)});var I6=B(Gi=>{"use strict";h();var hQ=Gi&&Gi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),dQ=Gi&&Gi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gQ=Gi&&Gi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hQ(e,t,r);return dQ(e,t),e};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.OptionValueBinaryCodec=void 0;var S6=gQ(Ie()),vp=dr(),SA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[vp.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[vp.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new vp.OptionValue(r);if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new vp.OptionValue(r,n)}encodeNested(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([])}};Gi.OptionValueBinaryCodec=SA});var T6=B(Ap=>{"use strict";h();Object.defineProperty(Ap,"__esModule",{value:!0});Ap.AddressBinaryCodec=void 0;var pQ=Ve(),mQ=dr(),IA=class{decodeNested(e){let r=e.slice(0,32),n=new pQ.Address(r);return[new mQ.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};Ap.AddressBinaryCodec=IA});var C6=B(ji=>{"use strict";h();var yQ=ji&&ji.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wQ=ji&&ji.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vQ=ji&&ji.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yQ(e,t,r);return wQ(e,t),e};Object.defineProperty(ji,"__esModule",{value:!0});ji.BooleanBinaryCodec=void 0;var AQ=vQ(Ie()),_6=dr(),kf=class t{decodeNested(e){let r=e.readUInt8(0);return[new _6.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new AQ.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new _6.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([])}};ji.BooleanBinaryCodec=kf;kf.TRUE=1;kf.FALSE=0});var bp=B(Ep=>{"use strict";h();Object.defineProperty(Ep,"__esModule",{value:!0});Ep.SizeOfU32=void 0;Ep.SizeOfU32=4});var x6=B(lc=>{"use strict";h();var EQ=lc&&lc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lc,"__esModule",{value:!0});lc.NumericalBinaryCodec=void 0;var Hf=EQ((rr(),_e(fr))),TA=dr(),N6=bp(),$t=Bu(),_A=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=N6.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),u=i+n;return[o,u]}decodeTopLevel(e,r){let n=$t.cloneBuffer(e);if(e.length==0)return new TA.NumericalValue(r,new Hf.default(0));if(!r.withSign||$t.isMsbZero(n)){let c=$t.bufferToBigInt(n);return new TA.NumericalValue(r,c)}$t.flipBufferBitsInPlace(n);let a=$t.bufferToBigInt(n).multipliedBy(new Hf.default(-1)).minus(new Hf.default(1));return new TA.NumericalValue(r,a)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=p.Buffer.alloc(N6.SizeOfU32);return n.writeUInt32BE(r.length),p.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return p.Buffer.alloc(r,0);if(!e.withSign){let o=$t.bigIntToBuffer(e.value),u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}if(e.value.isPositive()){let o=$t.bigIntToBuffer(e.value);$t.isMsbOne(o)&&(o=$t.prependByteToBuffer(o,0));let u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}let n=e.value.plus(new Hf.default(1)),i=$t.bigIntToBuffer(n);$t.flipBufferBitsInPlace(i),$t.isMsbZero(i)&&(i=$t.prependByteToBuffer(i,255));let s=p.Buffer.alloc(r-i.length,255);return p.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?p.Buffer.alloc(0):r?this.encodePrimitive(e):$t.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=$t.bigIntToBuffer(e.value);return $t.isMsbOne(i)&&(i=$t.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Hf.default(1)),n=$t.bigIntToBuffer(r);return $t.flipBufferBitsInPlace(n),$t.isMsbZero(n)&&(n=$t.prependByteToBuffer(n,255)),n}};lc.NumericalBinaryCodec=_A});var O6=B(Sp=>{"use strict";h();Object.defineProperty(Sp,"__esModule",{value:!0});Sp.H256BinaryCodec=void 0;var bQ=Sf(),CA=class{decodeNested(e){let r=e.slice(0,32);return[new bQ.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Sp.H256BinaryCodec=CA});var _p=B(Tp=>{"use strict";h();Object.defineProperty(Tp,"__esModule",{value:!0});Tp.BytesBinaryCodec=void 0;var D6=po(),Ip=bp(),NA=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(Ip.SizeOfU32,Ip.SizeOfU32+r);return[new D6.BytesValue(n),Ip.SizeOfU32+r]}decodeTopLevel(e){return new D6.BytesValue(e)}encodeNested(e){let r=p.Buffer.alloc(Ip.SizeOfU32);return r.writeUInt32BE(e.getLength()),p.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Tp.BytesBinaryCodec=NA});var R6=B(Cp=>{"use strict";h();Object.defineProperty(Cp,"__esModule",{value:!0});Cp.TokenIdentifierCodec=void 0;var SQ=po(),P6=ac(),IQ=_p(),xA=class{constructor(){this.bytesCodec=new IQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new P6.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new P6.TokenIdentifierValue(r.toString())}encodeNested(e){let r=SQ.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Cp.TokenIdentifierCodec=xA});var M6=B(Np=>{"use strict";h();Object.defineProperty(Np,"__esModule",{value:!0});Np.NothingCodec=void 0;var B6=dr(),OA=class{decodeNested(){return[new B6.NothingValue,0]}decodeTopLevel(){return new B6.NothingValue}encodeNested(){return p.Buffer.from([])}encodeTopLevel(){return p.Buffer.from([])}};Np.NothingCodec=OA});var F6=B(xp=>{"use strict";h();Object.defineProperty(xp,"__esModule",{value:!0});xp.StringBinaryCodec=void 0;var L6=dr(),TQ=po(),_Q=_p(),DA=class{constructor(){this.bytesBinaryCodec=new _Q.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new L6.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new L6.StringValue(e.toString())}encodeNested(e){let r=TQ.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};xp.StringBinaryCodec=DA});var U6=B(Dp=>{"use strict";h();Object.defineProperty(Dp,"__esModule",{value:!0});Dp.PrimitiveBinaryCodec=void 0;var Op=dr(),CQ=T6(),NQ=C6(),xQ=x6(),OQ=O6(),DQ=_p(),PQ=R6(),RQ=M6(),BQ=F6(),PA=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new NQ.BooleanBinaryCodec,this.numericalCodec=new xQ.NumericalBinaryCodec,this.addressCodec=new CQ.AddressBinaryCodec,this.h256Codec=new OQ.H256BinaryCodec,this.bytesCodec=new DQ.BytesBinaryCodec,this.stringCodec=new BQ.StringBinaryCodec,this.tokenIdentifierCodec=new PQ.TokenIdentifierCodec,this.nothingCodec=new RQ.NothingCodec}decodeNested(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};Dp.PrimitiveBinaryCodec=PA});var k6=B(Pp=>{"use strict";h();Object.defineProperty(Pp,"__esModule",{value:!0});Pp.ListBinaryCodec=void 0;var q6=dr(),V6=bp(),RA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,u=V6.SizeOfU32;e=o.slice(u);for(let a=0;a0;){let[u,a]=this.binaryCodec.decodeNested(e,n);i.push(u),o+=a,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new q6.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=p.Buffer.alloc(V6.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return p.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return p.Buffer.concat(r)}};Pp.ListBinaryCodec=RA});var MA=B(Rp=>{"use strict";h();Object.defineProperty(Rp,"__esModule",{value:!0});Rp.FieldsBinaryCodec=void 0;var MQ=dr(),BA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,u]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(u),i+=u;let a=new MQ.Field(o,s.name);n.push(a)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return p.Buffer.concat(r)}};Rp.FieldsBinaryCodec=BA});var FA=B(Bp=>{"use strict";h();Object.defineProperty(Bp,"__esModule",{value:!0});Bp.StructBinaryCodec=void 0;var LQ=dr(),FQ=MA(),LA=class{constructor(e){this.fieldsCodec=new FQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new LQ.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Bp.StructBinaryCodec=LA});var H6=B(Lp=>{"use strict";h();Object.defineProperty(Lp,"__esModule",{value:!0});Lp.EnumBinaryCodec=void 0;var Mp=dr(),UQ=MA(),UA=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new UQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[u,a]=this.fieldsCodec.decodeNested(e,o);return[new Mp.EnumValue(r,s,u),i+a]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Mp.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Mp.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return p.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Mp.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return p.Buffer.concat([o,i])}};Lp.EnumBinaryCodec=UA});var G6=B(Fp=>{"use strict";h();Object.defineProperty(Fp,"__esModule",{value:!0});Fp.TupleBinaryCodec=void 0;var qQ=FA(),qA=class{constructor(e){this.structCodec=new qQ.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Fp.TupleBinaryCodec=qA});var j6=B(Up=>{"use strict";h();Object.defineProperty(Up,"__esModule",{value:!0});Up.ArrayVecBinaryCodec=void 0;var VQ=dr(),VA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let u=0;u{"use strict";h();var kQ=Ln&&Ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),HQ=Ln&&Ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GQ=Ln&&Ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&kQ(e,t,r);return HQ(e,t),e};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BinaryCodecConstraints=Ln.BinaryCodec=void 0;var z6=GQ(Ie()),qp=dr(),Q6=Rn(),jQ=I6(),zQ=U6(),QQ=k6(),KQ=FA(),WQ=H6(),$Q=G6(),YQ=j6(),kA=class{constructor(e=null){this.constraints=e||new Vp,this.optionCodec=new jQ.OptionValueBinaryCodec(this),this.listCodec=new QQ.ListBinaryCodec(this),this.arrayCodec=new YQ.ArrayVecBinaryCodec(this),this.primitiveCodec=new zQ.PrimitiveBinaryCodec(this),this.structCodec=new KQ.StructBinaryCodec(this),this.tupleCodec=new $Q.TupleBinaryCodec(this),this.enumCodec=new WQ.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Ln.BinaryCodec=kA;var Vp=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new z6.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new z6.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Ln.BinaryCodecConstraints=Vp});var K6=B(Fn=>{"use strict";h();var JQ=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decodeBigNumber=Fn.decodeString=Fn.decodeBool=Fn.decodeUnsignedNumber=void 0;var XQ=JQ((rr(),_e(fr))),kp=dr(),ZQ=HA(),Hp=new ZQ.BinaryCodec;function eK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return Number(e.valueOf())}Fn.decodeUnsignedNumber=eK;function tK(t){return!!Hp.decodeTopLevel(t,new kp.BooleanType).valueOf()}Fn.decodeBool=tK;function rK(t){let e=Hp.decodeTopLevel(t,new kp.BytesType);return String(e.valueOf())}Fn.decodeString=rK;function nK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return new XQ.default(e.valueOf())}Fn.decodeBigNumber=nK});var GA=B(wo=>{"use strict";h();var iK=wo&&wo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),W6=wo&&wo.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&iK(e,t,r)};Object.defineProperty(wo,"__esModule",{value:!0});W6(HA(),wo);W6(K6(),wo)});var fc=B(Gp=>{"use strict";h();Object.defineProperty(Gp,"__esModule",{value:!0});Gp.ArgSerializer=void 0;var $6=hr(),sK=GA(),Y6=dr(),jA=Lg(),zA=kg(),QA=gp(),oK={codec:new sK.BinaryCodec},KA=class{constructor(e){e={...oK,...e},this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split($6.ARGUMENTS_SEPARATOR).map(r=>p.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join($6.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(jA.OptionalValue.ClassName)){let a=o;a.isSet()&&i(a.getTypedValue());return}if(o.hasExactClass(QA.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(zA.CompositeValue.ClassName)){let a=o;for(let c of a.getItems())i(c);return}let u=r.codec.encodeTopLevel(o);n.push(u)}function s(o){if(o.getType().isCounted){let a=new Y6.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(a))}for(let a of o.getItems())i(a)}return n}};Gp.ArgSerializer=KA});var WA=B((cye,J6)=>{h();Rs.notEqual=uK;Rs.notOk=cK;Rs.equal=aK;Rs.ok=Rs;J6.exports=Rs;function aK(t,e,r){Rs(t==e,r)}function uK(t,e,r){Rs(t!=e,r)}function cK(t,e){Rs(!t,e)}function Rs(t,e){if(!t)throw new Error(e||"AssertionError")}});var Z6=B((fye,X6)=>{h();X6.exports=$A;$A.supported=typeof WebAssembly<"u";function $A(t){if(!$A.supported)return null;var e=t&&t.imports,r=lK("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(a){i.exports.memory.grow(Math.ceil(Math.abs(a-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(a){if(i.exports)return a();if(n){n.then(a.bind(null,null)).catch(a);return}try{if(t&&t.async)throw new Error("async");u({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(u)}o(a)}function u(a){i.exports=a.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function lK(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(fK)):new(io()).Buffer(t,"base64")}function fK(t){return t.charCodeAt(0)}});var oO=B((pye,Qi)=>{h();var zi=WA(),xt=Z6()(),Bs=64,jp=[];Qi.exports=Un;var eO=Qi.exports.BYTES_MIN=16,tO=Qi.exports.BYTES_MAX=64,dye=Qi.exports.BYTES=32,rO=Qi.exports.KEYBYTES_MIN=16,nO=Qi.exports.KEYBYTES_MAX=64,gye=Qi.exports.KEYBYTES=32,iO=Qi.exports.SALTBYTES=16,sO=Qi.exports.PERSONALBYTES=16;function Un(t,e,r,n,i){if(!(this instanceof Un))return new Un(t,e,r,n,i);if(!(xt&&xt.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(zi(t>=eO,"digestLength must be at least "+eO+", was given "+t),zi(t<=tO,"digestLength must be at most "+tO+", was given "+t),e!=null&&zi(e.length>=rO,"key must be at least "+rO+", was given "+e.length),e!=null&&zi(e.length<=nO,"key must be at least "+nO+", was given "+e.length),r!=null&&zi(r.length===iO,"salt must be exactly "+iO+", was given "+r.length),n!=null&&zi(n.length===sO,"personal must be exactly "+sO+", was given "+n.length)),jp.length||(jp.push(Bs),Bs+=216),this.digestLength=t,this.finalized=!1,this.pointer=jp.pop(),xt.memory.fill(0,0,64),xt.memory[0]=this.digestLength,xt.memory[1]=e?e.length:0,xt.memory[2]=1,xt.memory[3]=1,r&&xt.memory.set(r,32),n&&xt.memory.set(n,48),this.pointer+216>xt.memory.length&&xt.realloc(this.pointer+216),xt.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),xt.memory.fill(0,Bs,Bs+e.length),xt.memory[this.pointer+200]=128)}Un.prototype.update=function(t){return zi(this.finalized===!1,"Hash instance finalized"),zi(t,"input must be TypedArray or Buffer"),Bs+t.length>xt.memory.length&&xt.realloc(Bs+t.length),xt.memory.set(t,Bs),xt.exports.blake2b_update(this.pointer,Bs,Bs+t.length),this};Un.prototype.digest=function(t){if(zi(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,jp.push(this.pointer),xt.exports.blake2b_final(this.pointer),!t||t==="binary")return xt.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return dK(xt.memory,this.pointer+128,this.digestLength);zi(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{h();var Eo=WA(),jf=oO();function zp(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function aO(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function gO(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vo(t,e,r,n,i,s){var o=Gf[i],u=Gf[i+1],a=Gf[s],c=Gf[s+1];zp(Te,t,e),aO(Te,t,o,u);var f=Te[n]^Te[t],d=Te[n+1]^Te[t+1];Te[n]=d,Te[n+1]=f,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=f>>>24^d<<8,Te[e+1]=d>>>24^f<<8,zp(Te,t,e),aO(Te,t,a,c),f=Te[n]^Te[t],d=Te[n+1]^Te[t+1],Te[n]=f>>>16^d<<16,Te[n+1]=d>>>16^f<<16,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=d>>>31^f<<1,Te[e+1]=f>>>31^d<<1}var pO=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),pK=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Pr=new Uint8Array(pK.map(function(t){return t*2})),Te=new Uint32Array(32),Gf=new Uint32Array(32);function mO(t,e){var r=0;for(r=0;r<16;r++)Te[r]=t.h[r],Te[r+16]=pO[r];for(Te[24]=Te[24]^t.t,Te[25]=Te[25]^t.t/4294967296,e&&(Te[28]=~Te[28],Te[29]=~Te[29]),r=0;r<32;r++)Gf[r]=gO(t.b,4*r);for(r=0;r<12;r++)vo(0,8,16,24,Pr[r*16+0],Pr[r*16+1]),vo(2,10,18,26,Pr[r*16+2],Pr[r*16+3]),vo(4,12,20,28,Pr[r*16+4],Pr[r*16+5]),vo(6,14,22,30,Pr[r*16+6],Pr[r*16+7]),vo(0,10,20,30,Pr[r*16+8],Pr[r*16+9]),vo(2,12,22,24,Pr[r*16+10],Pr[r*16+11]),vo(4,14,16,26,Pr[r*16+12],Pr[r*16+13]),vo(6,8,18,28,Pr[r*16+14],Pr[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Te[r]^Te[r+16]}var Ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hc(t,e,r,n){Ao.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Ao[0]=t,e&&(Ao[1]=e.length),Ao[2]=1,Ao[3]=1,r&&Ao.set(r,32),n&&Ao.set(n,48);for(var i=0;i<16;i++)this.h[i]=pO[i]^gO(Ao,i*4);e&&(yO(this,e),this.c=128)}hc.prototype.update=function(t){return Eo(t!=null,"input must be Uint8Array or Buffer"),yO(this,t),this};hc.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Eo(e.length>=this.outlen,"out must have at least outlen bytes of space"),mK(this,e),t==="hex"?yK(e):e};hc.prototype.final=hc.prototype.digest;hc.ready=function(t){jf.ready(function(){t()})};function yO(t,e){for(var r=0;r>2]>>8*(r&3);return e}function yK(t){for(var e="",r=0;r=uO,"outlen must be at least "+uO+", was given "+e),Eo(e<=cO,"outlen must be at most "+cO+", was given "+e),r!=null&&Eo(r.length>=lO,"key must be at least "+lO+", was given "+r.length),r!=null&&Eo(r.length<=fO,"key must be at most "+fO+", was given "+r.length),n!=null&&Eo(n.length===hO,"salt must be exactly "+hO+", was given "+n.length),i!=null&&Eo(i.length===dO,"personal must be exactly "+dO+", was given "+i.length)),new wO(e,r,n,i)};Jr.exports.ready=function(t){jf.ready(function(){t()})};Jr.exports.WASM_SUPPORTED=jf.SUPPORTED;Jr.exports.WASM_LOADED=!1;var uO=Jr.exports.BYTES_MIN=16,cO=Jr.exports.BYTES_MAX=64,yye=Jr.exports.BYTES=32,lO=Jr.exports.KEYBYTES_MIN=16,fO=Jr.exports.KEYBYTES_MAX=64,wye=Jr.exports.KEYBYTES=32,hO=Jr.exports.SALTBYTES=16,dO=Jr.exports.PERSONALBYTES=16;jf.ready(function(t){t||(Jr.exports.WASM_LOADED=!0,wO=jf)})});var vO=B(Qp=>{"use strict";h();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.Code=void 0;var vK=YA(),AK=32,JA=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return p.Buffer.from(this.hex,"hex")}computeHash(){let e=vK(AK).update(this.valueOf()).digest();return p.Buffer.from(e)}};Qp.Code=JA});var XA=B(Kp=>{"use strict";h();Object.defineProperty(Kp,"__esModule",{value:!0});Kp.CodeMetadata=void 0;var dc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBytes(e){return t.fromBuffer(p.Buffer.from(e))}static fromBuffer(e){if(e.length{"use strict";h();var EK=Ki&&Ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bK=Ki&&Ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SK=Ki&&Ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EK(e,t,r);return bK(e,t),e};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ContractFunction=void 0;var IK=SK(Ie()),ZA=class t{constructor(e){if(this.name=e,e==null)throw new IK.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Ki.ContractFunction=ZA});var rE=B(Wp=>{"use strict";h();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.Compatibility=void 0;var TK=Ve(),tE=class{static guardAddressIsSetAndNonZero(e,r,n){!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==TK.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`)}};Wp.Compatibility=tE});var Ms=B($p=>{"use strict";h();Object.defineProperty($p,"__esModule",{value:!0});$p.TransactionPayload=void 0;var nE=class t{constructor(e){this.data=p.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=p.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>p.Buffer.from(e,"hex"))}length(){return p.Buffer.from(this.data).length}};$p.TransactionPayload=nE});var gc=B(Yp=>{"use strict";h();Object.defineProperty(Yp,"__esModule",{value:!0});Yp.TransactionBuilder=void 0;var _K=hr(),CK=Xr(),NK=Ms(),iE=class{constructor(e){this.config=e.config,this.sender=e.sender,this.receiver=e.receiver,this.dataParts=e.dataParts,this.providedGasLimit=e.gasLimit,this.addDataMovementGas=e.addDataMovementGas,this.amount=e.amount}computeGasLimit(e){return this.addDataMovementGas?this.config.minGasLimit+this.config.gasLimitPerByte*BigInt(e.length())+this.providedGasLimit:this.providedGasLimit}buildTransactionPayload(){let e=this.dataParts.join(_K.ARGUMENTS_SEPARATOR);return new NK.TransactionPayload(e)}build(){let e=this.buildTransactionPayload(),r=this.computeGasLimit(e);return new CK.Transaction({sender:this.sender.bech32(),receiver:this.receiver.bech32(),gasLimit:r,value:this.amount||0n,data:e.valueOf(),chainID:this.config.chainID})}};Yp.TransactionBuilder=iE});var AO=B(Jp=>{"use strict";h();Object.defineProperty(Jp,"__esModule",{value:!0});Jp.DelegationTransactionsFactory=void 0;var xK=Ve(),OK=hr(),DK=Ie(),fn=qn(),Zr=gc(),sE=class{constructor(e){this.config=e.config,this.argSerializer=new fn.ArgSerializer}createTransactionForNewDelegationContract(e){let r=["createNewDelegationContract",...this.argSerializer.valuesToStrings([new fn.BigUIntValue(e.totalDelegationCap),new fn.BigUIntValue(e.serviceFee)])],n=this.config.gasLimitCreateDelegationContract+this.config.additionalGasLimitForDelegationOperations;return new Zr.TransactionBuilder({config:this.config,sender:e.sender,receiver:xK.Address.fromBech32(OK.DELEGATION_MANAGER_SC_ADDRESS),dataParts:r,gasLimit:n,addDataMovementGas:!0,amount:e.amount}).build()}createTransactionForAddingNodes(e){if(e.publicKeys.length!==e.signedMessages.length)throw new DK.Err("The number of public keys should match the number of signed messages");let r=e.signedMessages.map(o=>new fn.BytesValue(p.Buffer.from(o))),n=this.argSerializer.valuesToStrings(r),i=e.publicKeys.length,s=["addNodes"];for(let o=0;o{h();var EO=(rr(),_e(fr)),bO=SO.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function u(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(f){var d=s[f];return typeof d=="string"?d:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function a(c,f){var d,w,A,T,x=n,R,V=f[c],U=V!=null&&(V instanceof EO||EO.isBigNumber(V));switch(V&&typeof V=="object"&&typeof V.toJSON=="function"&&(V=V.toJSON(c)),typeof o=="function"&&(V=o.call(f,c,V)),typeof V){case"string":return U?V:u(V);case"number":return isFinite(V)?String(V):"null";case"boolean":case"null":case"bigint":return String(V);case"object":if(!V)return"null";if(n+=i,R=[],Object.prototype.toString.apply(V)==="[object Array]"){for(T=V.length,d=0;d{h();var Xp=null,PK=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,RK=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,BK=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},s,o=function(x){throw{name:"SyntaxError",message:x,at:r,text:s}},u=function(x){return x&&x!==n&&o("Expected '"+x+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},a=function(){var x,R="";for(n==="-"&&(R="-",u("-"));n>="0"&&n<="9";)R+=n,u();if(n===".")for(R+=".";u()&&n>="0"&&n<="9";)R+=n;if(n==="e"||n==="E")for(R+=n,u(),(n==="-"||n==="+")&&(R+=n,u());n>="0"&&n<="9";)R+=n,u();if(x=+R,!isFinite(x))o("Bad number");else return Xp==null&&(Xp=(rr(),_e(fr))),R.length>15?e.storeAsString?R:e.useNativeBigInt?BigInt(R):new Xp(R):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(x):new Xp(x):x},c=function(){var x,R,V="",U;if(n==='"')for(var Q=r;u();){if(n==='"')return r-1>Q&&(V+=s.substring(Q,r-1)),u(),V;if(n==="\\"){if(r-1>Q&&(V+=s.substring(Q,r-1)),u(),n==="u"){for(U=0,R=0;R<4&&(x=parseInt(u(),16),!!isFinite(x));R+=1)U=U*16+x;V+=String.fromCharCode(U)}else if(typeof i[n]=="string")V+=i[n];else break;Q=r}}o("Bad string")},f=function(){for(;n&&n<=" ";)u()},d=function(){switch(n){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}o("Unexpected '"+n+"'")},w,A=function(){var x=[];if(n==="["){if(u("["),f(),n==="]")return u("]"),x;for(;n;){if(x.push(w()),f(),n==="]")return u("]"),x;u(","),f()}}o("Bad array")},T=function(){var x,R=Object.create(null);if(n==="{"){if(u("{"),f(),n==="}")return u("}"),R;for(;n;){if(x=c(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(R,x)&&o('Duplicate key "'+x+'"'),PK.test(x)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():R[x]=w():RK.test(x)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():R[x]=w():R[x]=w(),f(),n==="}")return u("}"),R;u(","),f()}}o("Bad object")};return w=function(){switch(f(),n){case"{":return T();case"[":return A();case'"':return c();case"-":return a();default:return n>="0"&&n<="9"?a():d()}},function(x,R){var V;return s=x+"",r=0,n=" ",V=w(),f(),n&&o("Syntax error"),typeof R=="function"?function U(Q,L){var k,H,q=Q[L];return q&&typeof q=="object"&&Object.keys(q).forEach(function(v){H=U(q,v),H!==void 0?q[v]=H:delete q[v]}),R.call(Q,L,q)}({"":V},""):V}};TO.exports=BK});var oE=B((qye,Zp)=>{h();var CO=IO().stringify,NO=_O();Zp.exports=function(t){return{parse:NO(t),stringify:CO}};Zp.exports.parse=NO();Zp.exports.stringify=CO});var OO=B(pc=>{"use strict";h();var MK=pc&&pc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pc,"__esModule",{value:!0});pc.RelayedTransactionsFactory=void 0;var LK=MK((rr(),_e(fr))),e0=Ve(),t0=Ie(),zf=qn(),xO=Xr(),FK=oE(),aE=class{constructor(e){this.config=e.config}createRelayedV1Transaction(e){if(!e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let r=this.prepareInnerTransactionForRelayedV1(e.innerTransaction),n=`relayedTx@${p.Buffer.from(r).toString("hex")}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=this.config.minGasLimit+i+e.innerTransaction.gasLimit;return new xO.Transaction({chainID:this.config.chainID,sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,gasLimit:s,data:p.Buffer.from(n)})}createRelayedV2Transaction(e){if(e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let{argumentsString:r}=new zf.ArgSerializer().valuesToString([new zf.AddressValue(e0.Address.fromBech32(e.innerTransaction.receiver)),new zf.U64Value(new LK.default(e.innerTransaction.nonce.toString())),new zf.BytesValue(p.Buffer.from(e.innerTransaction.data)),new zf.BytesValue(p.Buffer.from(e.innerTransaction.signature))]),n=`relayedTxV2@${r}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=e.innerTransactionGasLimit+this.config.minGasLimit+i;return new xO.Transaction({sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,value:0n,gasLimit:s,chainID:this.config.chainID,data:p.Buffer.from(n),version:e.innerTransaction.version,options:e.innerTransaction.options})}prepareInnerTransactionForRelayedV1(e){let r={nonce:e.nonce,sender:e0.Address.fromBech32(e.sender).pubkey().toString("base64"),receiver:e0.Address.fromBech32(e.receiver).pubkey().toString("base64"),value:e.value,gasPrice:e.gasPrice,gasLimit:e.gasLimit,data:p.Buffer.from(e.data).toString("base64"),signature:p.Buffer.from(e.signature).toString("base64"),chainID:p.Buffer.from(e.chainID).toString("base64"),version:e.version,options:e.options.valueOf()==0?void 0:e.options,guardian:e.guardian?e0.Address.fromBech32(e.guardian).pubkey().toString("base64"):void 0,guardianSignature:e.guardianSignature.length?p.Buffer.from(e.guardianSignature).toString("base64"):void 0,sndUserName:e.senderUsername?p.Buffer.from(e.senderUsername).toString("base64"):void 0,rcvUserName:e.receiverUsername?p.Buffer.from(e.receiverUsername).toString("base64"):void 0};return FK.stringify(r)}};pc.RelayedTransactionsFactory=aE});var DO=B(r0=>{"use strict";h();Object.defineProperty(r0,"__esModule",{value:!0});r0.ArgumentErrorContext=void 0;var UK=Ie(),uE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new UK.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) +Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};r0.ArgumentErrorContext=uE});var n0=B(qa=>{"use strict";h();var qK=qa&&qa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qa,"__esModule",{value:!0});qa.NativeSerializer=void 0;var VK=qK((rr(),_e(fr))),kK=Ve(),cE=Ie(),HK=Ru(),GK=DO(),ye=dr(),jK;(function(t){function e(L,k){L=L||[],r(L,k),n(k)&&(L=i(L,k));let H=k.input,q=[];for(let v=0;v0&&k[0].type.getCardinality().isComposite()&&(q=1/0,v=!0);for(let C of k){if(C.type.getCardinality().isSingular())break;H-=1}return{min:H,max:q,variadic:v}}t.getArgumentsCardinality=s;function o(L,k,H){if(L&&L.belongsToTypesystem)return L;if(k instanceof ye.OptionType)return u(L,k,H);if(k instanceof ye.OptionalType)return a(L,k,H);if(k instanceof ye.VariadicType)return c(L,k,H);if(k instanceof ye.CompositeType)return d(L,k,H);if(k instanceof ye.TupleType)return w(L,k,H);if(k instanceof ye.StructType)return A(L,k,H);if(k instanceof ye.ListType)return f(L,k,H);if(k instanceof ye.PrimitiveType)return T(L,k,H);if(k instanceof ye.EnumType)return x(L,k,H);H.throwError(`convertToTypedValue: unhandled type ${k}`)}function u(L,k,H){if(L==null)return ye.OptionValue.newMissing();let q=o(L,k.getFirstTypeParameter(),H);return ye.OptionValue.newProvided(q)}function a(L,k,H){if(L==null)return new ye.OptionalValue(k);let q=o(L,k.getFirstTypeParameter(),H);return new ye.OptionalValue(k,q)}function c(L,k,H){if(k.isCounted)throw new cE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');L==null&&(L=[]),L.map===void 0&&H.convertError(L,"Variadic");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.VariadicValue(k,q)}function f(L,k,H){L.map===void 0&&H.convertError(L,"List");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.List(k,q)}function d(L,k,H){let q=[],v=k.getTypeParameters();H.guardSameLength(L,v);for(let C=0;C{"use strict";h();Object.defineProperty(i0,"__esModule",{value:!0});i0.TokenTransfersDataBuilder=void 0;var zK=fc(),pi=dr(),QK=Ca(),lE=class{constructor(){this.tokenComputer=new QK.TokenComputer,this.argsSerializer=new zK.ArgSerializer}buildDataPartsForESDTTransfer(e){return["ESDTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(e.token.identifier),new pi.BigUIntValue(e.amount)])]}buildDataPartsForSingleESDTNFTTransfer(e,r){let n=e.token,i=this.tokenComputer.extractIdentifierFromExtendedIdentifier(n.identifier);return["ESDTNFTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(i),new pi.BigUIntValue(n.nonce),new pi.BigUIntValue(e.amount),new pi.AddressValue(r)])]}buildDataPartsForMultiESDTNFTTransfer(e,r){let n=[new pi.AddressValue(e),new pi.U32Value(r.length)];for(let s of r){let o=this.tokenComputer.extractIdentifierFromExtendedIdentifier(s.token.identifier);n.push(new pi.TokenIdentifierValue(o),new pi.BigUIntValue(s.token.nonce),new pi.BigUIntValue(s.amount))}return["MultiESDTNFTTransfer",...this.argsSerializer.valuesToStrings(n)]}};i0.TokenTransfersDataBuilder=lE});var dE=B(a0=>{"use strict";h();Object.defineProperty(a0,"__esModule",{value:!0});a0.SmartContractTransactionsFactory=void 0;var PO=Ve(),RO=hr(),BO=Ie(),KK=oo(),s0=qn(),WK=n0(),$K=Ca(),o0=Ru(),YK=fE(),Qf=gc(),hE=class{constructor(e){this.config=e.config,this.abi=e.abi,this.tokenComputer=new $K.TokenComputer,this.dataArgsBuilder=new YK.TokenTransfersDataBuilder}createTransactionForDeploy(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=[o0.byteArrayToHex(e.bytecode),o0.byteArrayToHex(RO.VM_TYPE_WASM_VM),a.toString()],f=this.abi?.constructorDefinition,d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:PO.Address.fromBech32(RO.CONTRACT_DEPLOY_ADDRESS),dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}createTransactionForExecute(e){let r=e.arguments||[],n=e.tokenTransfers||[],i=e.nativeTransferAmount??0n,s=n.length;if(i&&s)throw new BO.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)");let o=e.contract,u=[];if(s===1){let f=n[0];this.tokenComputer.isFungible(f.token)?u=this.dataArgsBuilder.buildDataPartsForESDTTransfer(f):(u=this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(f,o),o=e.sender)}else s>1&&(u=this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(o,n),o=e.sender);u.push(u.length?o0.utf8ToHex(e.function):e.function);let a=this.abi?.getEndpoint(e.function),c=this.argsToDataParts(r,a);return u.push(...c),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:o,dataParts:u,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:i}).build()}createTransactionForUpgrade(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=["upgradeContract",o0.byteArrayToHex(e.bytecode),a.toString()],f=this.getEndpointForUpgrade(),d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}getEndpointForUpgrade(){if(this.abi)try{return this.abi.getEndpoint("upgrade")}catch{return KK.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."),this.abi.constructorDefinition}}createTransactionForClaimingDeveloperRewards(e){let r=["ClaimDeveloperRewards"];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitClaimDeveloperRewards,addDataMovementGas:!1}).build()}createTransactionForChangingOwnerAddress(e){let r=["ChangeOwnerAddress",PO.Address.fromBech32(e.newOwner.bech32()).toHex()];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitChangeOwnerAddress,addDataMovementGas:!1}).build()}argsToDataParts(e,r){if(r){let n=WK.NativeSerializer.nativeToTypedValues(e,r);return new s0.ArgSerializer().valuesToStrings(n)}if(this.areArgsOfTypedValue(e))return new s0.ArgSerializer().valuesToStrings(e);throw new BO.Err("Can't convert args to TypedValues")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}};a0.SmartContractTransactionsFactory=hE});var MO=B(u0=>{"use strict";h();Object.defineProperty(u0,"__esModule",{value:!0});u0.TokenManagementTransactionsFactory=void 0;var Wi=Ve(),$i=hr(),JK=oo(),Z=qn(),Yt=gc(),gE=class{constructor(e){this.config=e.config,this.argSerializer=new Z.ArgSerializer,this.trueAsString="true",this.falseAsString="false"}createTransactionForIssuingFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.initialSupply),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issue",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueSemiFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueNonFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["registerMetaESDT",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringAndSettingRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue(e.tokenType),new Z.BigUIntValue(e.numDecimals)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForSettingBurnRoleGlobally(e){let r=["setBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForUnsettingBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleLocalMint&&r.push(new Z.StringValue("ESDTRoleLocalMint")),e.addRoleLocalBurn&&r.push(new Z.StringValue("ESDTRoleLocalBurn")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnSemiFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTAddQuantity&&r.push(new Z.StringValue("ESDTRoleNFTAddQuantity")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnMetaESDT(e){return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(e)}createTransactionForSettingSpecialRoleOnNonFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTUpdateAttributes&&r.push(new Z.StringValue("ESDTRoleNFTUpdateAttributes")),e.addRoleNFTAddURI&&r.push(new Z.StringValue("ESDTRoleNFTAddURI")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForCreatingNFT(e){let r=["ESDTNFTCreate",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.initialQuantity),new Z.StringValue(e.name),new Z.BigUIntValue(e.royalties),new Z.StringValue(e.hash),new Z.BytesValue(p.Buffer.from(e.attributes)),...e.uris.map(s=>new Z.StringValue(s))])],n=e.name+e.hash+e.attributes+e.uris.join(""),i=this.config.gasLimitStorePerByte+BigInt(n.length);return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftCreate+i,addDataMovementGas:!0}).build()}createTransactionForPausing(e){let r=["pause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForUnpausing(e){let r=["unPause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForFreezing(e){let r=["freeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForUnfreezing(e){let r=["UnFreeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForWiping(e){let r=["wipe",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitWiping,addDataMovementGas:!0}).build()}createTransactionForLocalMint(e){let r=["ESDTLocalMint",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToMint)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalMint,addDataMovementGas:!0}).build()}createTransactionForLocalBurning(e){let r=["ESDTLocalBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalBurn,addDataMovementGas:!0}).build()}createTransactionForUpdatingAttributes(e){let r=["ESDTNFTUpdateAttributes",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BytesValue(p.Buffer.from(e.attributes))])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftUpdateAttributes,addDataMovementGas:!0}).build()}createTransactionForAddingQuantity(e){let r=["ESDTNFTAddQuantity",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToAdd)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftAddQuantity,addDataMovementGas:!0}).build()}createTransactionForBurningQuantity(e){let r=["ESDTNFTBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftBurn,addDataMovementGas:!0}).build()}notifyAboutUnsettingBurnRoleGlobally(){JK.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); - } - boolToString(value) { - if (value) { - return this.trueAsString; - } - return this.falseAsString; - } - }; - exports2.TokenManagementTransactionsFactory = TokenManagementTransactionsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js -var require_transactionsFactoryConfig = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/transactionsFactoryConfig.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionsFactoryConfig = void 0; - var constants_1 = require_constants(); - var TransactionsFactoryConfig2 = class { - constructor(options) { - this.chainID = options.chainID; - this.addressHrp = constants_1.DEFAULT_HRP; - this.minGasLimit = 50000n; - this.gasLimitPerByte = 1500n; - this.gasLimitIssue = 60000000n; - this.gasLimitToggleBurnRoleGlobally = 60000000n; - this.gasLimitEsdtLocalMint = 300000n; - this.gasLimitEsdtLocalBurn = 300000n; - this.gasLimitSetSpecialRole = 60000000n; - this.gasLimitPausing = 60000000n; - this.gasLimitFreezing = 60000000n; - this.gasLimitWiping = 60000000n; - this.gasLimitEsdtNftCreate = 3000000n; - this.gasLimitEsdtNftUpdateAttributes = 1000000n; - this.gasLimitEsdtNftAddQuantity = 1000000n; - this.gasLimitEsdtNftBurn = 1000000n; - this.gasLimitStorePerByte = 10000n; - this.issueCost = 50000000000000000n; - this.gasLimitStake = 5000000n; - this.gasLimitUnstake = 5000000n; - this.gasLimitUnbond = 5000000n; - this.gasLimitCreateDelegationContract = 50000000n; - this.gasLimitDelegationOperations = 1000000n; - this.additionalGasLimitPerValidatorNode = 6000000n; - this.additionalGasLimitForDelegationOperations = 10000000n; - this.gasLimitSaveKeyValue = 100000n; - this.gasLimitPersistPerByte = 1000n; - this.gasLimitSetGuardian = 250000n; - this.gasLimitGuardAccount = 250000n; - this.gasLimitUnguardAccount = 250000n; - this.gasLimitESDTTransfer = 200000n; - this.gasLimitESDTNFTTransfer = 200000n; - this.gasLimitMultiESDTNFTTransfer = 200000n; - this.gasLimitClaimDeveloperRewards = 6000000n; - this.gasLimitChangeOwnerAddress = 6000000n; - } - }; - exports2.TransactionsFactoryConfig = TransactionsFactoryConfig2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js -var require_transferTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/transferTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransferTransactionsFactory = void 0; - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var tokens_1 = require_tokens(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var tokenTransfersDataBuilder_1 = require_tokenTransfersDataBuilder(); - var transactionBuilder_1 = require_transactionBuilder(); - var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; - var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; - var TransferTransactionsFactory2 = class { - /** - * Should be instantiated using `Config` and `TokenComputer`. - * Instantiating this class using GasEstimator represents the legacy version of this class. - * The legacy version contains methods like `createEGLDTransfer`, `createESDTTransfer`, `createESDTNFTTransfer` and `createMultiESDTNFTTransfer`. - * This was done in order to minimize breaking changes in client code. - */ - constructor(options) { - if (this.isGasEstimator(options)) { - this.gasEstimator = options; - } else { - this.config = options.config; - this.tokenComputer = new tokens_1.TokenComputer(); - this.tokenTransfersDataBuilder = new tokenTransfersDataBuilder_1.TokenTransfersDataBuilder(); - } - } - isGasEstimator(options) { - return typeof options === "object" && typeof options.forEGLDTransfer === "function" && typeof options.forESDTTransfer === "function" && typeof options.forESDTNFTTransfer === "function" && typeof options.forMultiESDTNFTTransfer === "function"; - } - isGasEstimatorDefined() { - return this.gasEstimator !== void 0; - } - ensureMembersAreDefined() { - if (this.config === void 0) { - throw new errors_1.Err("'config' is not defined"); - } - if (this.tokenTransfersDataBuilder === void 0) { - throw new errors_1.Err("`dataArgsBuilder is not defined`"); - } - if (this.tokenComputer === void 0) { - throw new errors_1.Err("`tokenComputer is not defined`"); - } - } - createTransactionForNativeTokenTransfer(options) { - this.ensureMembersAreDefined(); - const data = options.data || new Uint8Array(); - return new transaction_1.Transaction({ - sender: options.sender.bech32(), - receiver: options.receiver.bech32(), - chainID: this.config.chainID, - gasLimit: this.computeGasForMoveBalance(this.config, data), - data, - value: options.nativeAmount - }); - } - createTransactionForESDTTokenTransfer(options) { - this.ensureMembersAreDefined(); - const numberOfTransfers = options.tokenTransfers.length; - if (numberOfTransfers === 0) { - throw new errors_1.ErrBadUsage("No token transfer has been provided"); - } - if (numberOfTransfers === 1) { - return this.createSingleESDTTransferTransaction(options); - } - const dataParts = this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(options.receiver, options.tokenTransfers); - const extraGasForTransfer = this.config.gasLimitMultiESDTNFTTransfer * BigInt(numberOfTransfers) + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: extraGasForTransfer, - addDataMovementGas: true - }).build(); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForNativeTokenTransfer} instead. - */ - createEGLDTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method."); - } - const dataLength = args.data?.length() || 0; - const estimatedGasLimit = this.gasEstimator.forEGLDTransfer(dataLength); - return new transaction_1.Transaction({ - nonce: args.nonce, - value: args.value, - receiver: args.receiver, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: args.data, - chainID: args.chainID - }); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createESDTTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - // The token identifier - smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), - // The transfered amount - new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()) - ]); - const data = `ESDTTransfer@${argumentsString}`; - const transactionPayload = new transactionPayload_1.TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; - const estimatedGasLimit = this.gasEstimator.forESDTTransfer(dataLength); - return new transaction_1.Transaction({ - nonce: args.nonce, - receiver: args.receiver, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: transactionPayload, - chainID: args.chainID - }); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createESDTNFTTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - // The token identifier - smartcontracts_1.BytesValue.fromUTF8(args.tokenTransfer.tokenIdentifier), - // The nonce of the token - new smartcontracts_1.U64Value(args.tokenTransfer.nonce), - // The transferred quantity - new smartcontracts_1.BigUIntValue(args.tokenTransfer.valueOf()), - // The destination address - new smartcontracts_1.AddressValue(args.destination) - ]); - const data = `ESDTNFTTransfer@${argumentsString}`; - const transactionPayload = new transactionPayload_1.TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; - const estimatedGasLimit = this.gasEstimator.forESDTNFTTransfer(dataLength); - return new transaction_1.Transaction({ - nonce: args.nonce, - receiver: args.sender, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: transactionPayload, - chainID: args.chainID - }); - } - /** - * This is a legacy method. Can only be used if the class was instantiated using `GasEstimator`. - * Use {@link createTransactionForESDTTokenTransfer} instead. - */ - createMultiESDTNFTTransfer(args) { - if (!this.isGasEstimatorDefined()) { - throw new errors_1.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method."); - } - const parts = [ - // The destination address - new smartcontracts_1.AddressValue(args.destination), - // Number of tokens - new smartcontracts_1.U16Value(args.tokenTransfers.length) - ]; - for (const payment of args.tokenTransfers) { - parts.push(...[ - // The token identifier - smartcontracts_1.BytesValue.fromUTF8(payment.tokenIdentifier), - // The nonce of the token - new smartcontracts_1.U64Value(payment.nonce), - // The transfered quantity - new smartcontracts_1.BigUIntValue(payment.valueOf()) - ]); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString(parts); - const data = `MultiESDTNFTTransfer@${argumentsString}`; - const transactionPayload = new transactionPayload_1.TransactionPayload(data); - const dataLength = transactionPayload.length() || 0; - const estimatedGasLimit = this.gasEstimator.forMultiESDTNFTTransfer(dataLength, args.tokenTransfers.length); - return new transaction_1.Transaction({ - nonce: args.nonce, - receiver: args.sender, - sender: args.sender, - gasPrice: args.gasPrice, - gasLimit: args.gasLimit || estimatedGasLimit, - data: transactionPayload, - chainID: args.chainID - }); - } - createSingleESDTTransferTransaction(options) { - this.ensureMembersAreDefined(); - let dataParts = []; - const transfer = options.tokenTransfers[0]; - let extraGasForTransfer = 0n; - let receiver = options.receiver; - if (this.tokenComputer.isFungible(transfer.token)) { - dataParts = this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(transfer); - extraGasForTransfer = this.config.gasLimitESDTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_TRANSFER); - } else { - dataParts = this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(transfer, receiver); - extraGasForTransfer = this.config.gasLimitESDTNFTTransfer + BigInt(ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER); - receiver = options.sender; - } - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver, - dataParts, - gasLimit: extraGasForTransfer, - addDataMovementGas: true - }).build(); - } - computeGasForMoveBalance(config, data) { - return config.minGasLimit + config.gasLimitPerByte * BigInt(data.length); - } - }; - exports2.TransferTransactionsFactory = TransferTransactionsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js -var require_accountTransactionsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/accountTransactionsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AccountTransactionsFactory = void 0; - var address_1 = require_address(); - var transactionBuilder_1 = require_transactionBuilder(); - var AccountTransactionsFactory = class { - constructor(options) { - this.config = options.config; - } - createTransactionForSavingKeyValue(options) { - const functionName = "SaveKeyValue"; - const keyValueParts = this.computeDataPartsForSavingKeyValue(options.keyValuePairs); - const dataParts = [functionName, ...keyValueParts]; - const extraGas = this.computeExtraGasForSavingKeyValue(options.keyValuePairs); - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: extraGas, - addDataMovementGas: true - }).build(); - } - computeExtraGasForSavingKeyValue(keyValuePairs) { - let extraGas = 0n; - keyValuePairs.forEach((value, key) => { - extraGas += this.config.gasLimitPersistPerByte * BigInt(key.length + value.length) + this.config.gasLimitStorePerByte * BigInt(value.length); - }); - return extraGas + this.config.gasLimitSaveKeyValue; - } - computeDataPartsForSavingKeyValue(keyValuePairs) { - const dataParts = []; - keyValuePairs.forEach((value, key) => { - dataParts.push(...[import_buffer.Buffer.from(key).toString("hex"), import_buffer.Buffer.from(value).toString("hex")]); - }); - return dataParts; - } - createTransactionForSettingGuardian(options) { - const dataParts = [ - "SetGuardian", - address_1.Address.fromBech32(options.guardianAddress.bech32()).toHex(), - import_buffer.Buffer.from(options.serviceID).toString("hex") - ]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitSetGuardian, - addDataMovementGas: true - }).build(); - } - createTransactionForGuardingAccount(options) { - const dataParts = ["GuardAccount"]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitGuardAccount, - addDataMovementGas: true - }).build(); - } - createTransactionForUnguardingAccount(options) { - const dataParts = ["UnGuardAccount"]; - return new transactionBuilder_1.TransactionBuilder({ - config: this.config, - sender: options.sender, - receiver: options.sender, - dataParts, - gasLimit: this.config.gasLimitUnguardAccount, - addDataMovementGas: true - }).build(); - } - }; - exports2.AccountTransactionsFactory = AccountTransactionsFactory; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js -var require_transactionsFactories = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsFactories/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_delegationTransactionsFactory(), exports2); - __exportStar2(require_relayedTransactionsFactory(), exports2); - __exportStar2(require_smartContractTransactionsFactory(), exports2); - __exportStar2(require_tokenManagementTransactionsFactory(), exports2); - __exportStar2(require_transactionsFactoryConfig(), exports2); - __exportStar2(require_transferTransactionsFactory(), exports2); - __exportStar2(require_accountTransactionsFactory(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js -var require_interactionChecker = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/interactionChecker.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.InteractionChecker = void 0; - var errors = __importStar2(require_errors()); - var bignumber_js_1 = __importDefault2(require_bignumber()); - var InteractionChecker = class { - checkInteraction(interaction, definition) { - this.checkPayable(interaction, definition); - this.checkArguments(interaction, definition); - } - checkPayable(interaction, definition) { - let hasValue = !new bignumber_js_1.default(interaction.getValue().toString()).isZero(); - let isPayableInEGLD = definition.modifiers.isPayableInEGLD(); - if (hasValue && !isPayableInEGLD) { - throw new errors.ErrContractInteraction("cannot send EGLD value to non-payable"); - } - } - checkArguments(interaction, definition) { - let formalArguments = definition.input; - let actualArguments = interaction.getArguments(); - let numFormalArguments = formalArguments.length; - let numActualArguments = actualArguments.length; - if (numFormalArguments != numActualArguments) { - throw new errors.ErrContractInteraction(`bad arguments, expected: ${numFormalArguments}, got: ${numActualArguments}`); - } - for (let i2 = 0; i2 < numFormalArguments; i2++) { - let expectedType = formalArguments[i2].type; - let argument = actualArguments[i2]; - let actualType = argument.getType(); - let ok = expectedType.isAssignableFrom(actualType); - if (!ok) { - throw new errors.ErrContractInteraction(`type mismatch at index ${i2}, expected: ${expectedType}, got: ${actualType}`); - } - } - } - }; - exports2.InteractionChecker = InteractionChecker; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/query.js -var require_query = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/query.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Query = void 0; - var address_1 = require_address(); - var argSerializer_1 = require_argSerializer(); - var Query2 = class { - constructor(obj) { - this.caller = obj.caller || address_1.Address.empty(); - this.address = obj.address; - this.func = obj.func; - this.args = obj.args || []; - this.value = obj.value || 0; - } - getEncodedArguments() { - return new argSerializer_1.ArgSerializer().valuesToStrings(this.args); - } - }; - exports2.Query = Query2; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js -var require_interaction = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/interaction.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Interaction = void 0; - var address_1 = require_address(); - var compatibility_1 = require_compatibility(); - var constants_1 = require_constants(); - var tokens_1 = require_tokens(); - var transactionsFactories_1 = require_transactionsFactories(); - var interactionChecker_1 = require_interactionChecker(); - var query_1 = require_query(); - var Interaction = class { - constructor(contract, func, args) { - this.nonce = 0; - this.value = "0"; - this.gasLimit = 0; - this.gasPrice = void 0; - this.chainID = ""; - this.querent = address_1.Address.empty(); - this.sender = address_1.Address.empty(); - this.version = constants_1.TRANSACTION_VERSION_DEFAULT; - this.contract = contract; - this.function = func; - this.args = args; - this.tokenTransfers = []; - } - getContractAddress() { - return this.contract.getAddress(); - } - getFunction() { - return this.function; - } - getEndpoint() { - return this.contract.getEndpoint(this.function); - } - getArguments() { - return this.args; - } - getValue() { - return this.value; - } - getTokenTransfers() { - return this.tokenTransfers; - } - getGasLimit() { - return this.gasLimit; - } - getExplicitReceiver() { - return this.explicitReceiver; - } - buildTransaction() { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(this.sender, "'sender' of interaction", "use interaction.withSender()"); - const factoryConfig = new transactionsFactories_1.TransactionsFactoryConfig({ chainID: this.chainID.valueOf() }); - const factory = new transactionsFactories_1.SmartContractTransactionsFactory({ - config: factoryConfig - }); - const transaction = factory.createTransactionForExecute({ - sender: this.sender, - contract: this.contract.getAddress(), - function: this.function.valueOf(), - gasLimit: BigInt(this.gasLimit.valueOf()), - arguments: this.args, - nativeTransferAmount: BigInt(this.value.toString()), - tokenTransfers: this.tokenTransfers - }); - transaction.chainID = this.chainID.valueOf(); - transaction.nonce = BigInt(this.nonce.valueOf()); - transaction.version = this.version; - if (this.gasPrice) { - transaction.gasPrice = BigInt(this.gasPrice.valueOf()); - } - return transaction; - } - buildQuery() { - return new query_1.Query({ - address: this.contract.getAddress(), - func: this.function, - args: this.args, - // Value will be set using "withValue()". - value: this.value, - caller: this.querent - }); - } - withValue(value) { - this.value = value; - return this; - } - withSingleESDTTransfer(transfer) { - this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); - return this; - } - withSingleESDTNFTTransfer(transfer) { - this.tokenTransfers = [transfer].map((transfer2) => new tokens_1.TokenTransfer(transfer2)); - return this; - } - withMultiESDTNFTTransfer(transfers) { - this.tokenTransfers = transfers.map((transfer) => new tokens_1.TokenTransfer(transfer)); - return this; - } - withGasLimit(gasLimit) { - this.gasLimit = gasLimit; - return this; - } - withGasPrice(gasPrice) { - this.gasPrice = gasPrice; - return this; - } - withNonce(nonce) { - this.nonce = nonce; - return this; - } - useThenIncrementNonceOf(account) { - return this.withNonce(account.getNonceThenIncrement()); - } - withChainID(chainID) { - this.chainID = chainID; - return this; - } - withSender(sender) { - this.sender = sender; - return this; - } - withVersion(version2) { - this.version = version2; - return this; - } - /** - * Sets the "caller" field on contract queries. - */ - withQuerent(querent) { - this.querent = querent; - return this; - } - withExplicitReceiver(receiver) { - this.explicitReceiver = receiver; - return this; - } - /** - * To perform custom checking, extend {@link Interaction} and override this method. - */ - check() { - new interactionChecker_1.InteractionChecker().checkInteraction(this, this.getEndpoint()); - return this; - } - }; - exports2.Interaction = Interaction; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js -var require_interface = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/interface.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js -var require_dist = __commonJS({ - "node_modules/@multiversx/sdk-transaction-decoder/node_modules/bech32/dist/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.bech32m = exports2.bech32 = void 0; - var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; - var ALPHABET_MAP = {}; - for (let z3 = 0; z3 < ALPHABET.length; z3++) { - const x3 = ALPHABET.charAt(z3); - ALPHABET_MAP[x3] = z3; - } - function polymodStep(pre) { - const b4 = pre >> 25; - return (pre & 33554431) << 5 ^ -(b4 >> 0 & 1) & 996825010 ^ -(b4 >> 1 & 1) & 642813549 ^ -(b4 >> 2 & 1) & 513874426 ^ -(b4 >> 3 & 1) & 1027748829 ^ -(b4 >> 4 & 1) & 705979059; - } - function prefixChk(prefix) { - let chk = 1; - for (let i2 = 0; i2 < prefix.length; ++i2) { - const c4 = prefix.charCodeAt(i2); - if (c4 < 33 || c4 > 126) - return "Invalid prefix (" + prefix + ")"; - chk = polymodStep(chk) ^ c4 >> 5; - } - chk = polymodStep(chk); - for (let i2 = 0; i2 < prefix.length; ++i2) { - const v2 = prefix.charCodeAt(i2); - chk = polymodStep(chk) ^ v2 & 31; - } - return chk; - } - function convert(data, inBits, outBits, pad) { - let value = 0; - let bits = 0; - const maxV = (1 << outBits) - 1; - const result = []; - for (let i2 = 0; i2 < data.length; ++i2) { - value = value << inBits | data[i2]; - bits += inBits; - while (bits >= outBits) { - bits -= outBits; - result.push(value >> bits & maxV); - } - } - if (pad) { - if (bits > 0) { - result.push(value << outBits - bits & maxV); - } - } else { - if (bits >= inBits) - return "Excess padding"; - if (value << outBits - bits & maxV) - return "Non-zero padding"; - } - return result; - } - function toWords(bytes) { - return convert(bytes, 8, 5, true); - } - function fromWordsUnsafe(words) { - const res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - } - function fromWords(words) { - const res = convert(words, 5, 8, false); - if (Array.isArray(res)) - return res; - throw new Error(res); - } - function getLibraryFromEncoding(encoding) { - let ENCODING_CONST; - if (encoding === "bech32") { - ENCODING_CONST = 1; - } else { - ENCODING_CONST = 734539939; - } - function encode5(prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if (prefix.length + 7 + words.length > LIMIT) - throw new TypeError("Exceeds length limit"); - prefix = prefix.toLowerCase(); - let chk = prefixChk(prefix); - if (typeof chk === "string") - throw new Error(chk); - let result = prefix + "1"; - for (let i2 = 0; i2 < words.length; ++i2) { - const x3 = words[i2]; - if (x3 >> 5 !== 0) - throw new Error("Non 5-bit word"); - chk = polymodStep(chk) ^ x3; - result += ALPHABET.charAt(x3); - } - for (let i2 = 0; i2 < 6; ++i2) { - chk = polymodStep(chk); - } - chk ^= ENCODING_CONST; - for (let i2 = 0; i2 < 6; ++i2) { - const v2 = chk >> (5 - i2) * 5 & 31; - result += ALPHABET.charAt(v2); - } - return result; - } - function __decode(str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) - return str + " too short"; - if (str.length > LIMIT) - return "Exceeds length limit"; - const lowered = str.toLowerCase(); - const uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) - return "Mixed-case string " + str; - str = lowered; - const split = str.lastIndexOf("1"); - if (split === -1) - return "No separator character for " + str; - if (split === 0) - return "Missing prefix for " + str; - const prefix = str.slice(0, split); - const wordChars = str.slice(split + 1); - if (wordChars.length < 6) - return "Data too short"; - let chk = prefixChk(prefix); - if (typeof chk === "string") - return chk; - const words = []; - for (let i2 = 0; i2 < wordChars.length; ++i2) { - const c4 = wordChars.charAt(i2); - const v2 = ALPHABET_MAP[c4]; - if (v2 === void 0) - return "Unknown character " + c4; - chk = polymodStep(chk) ^ v2; - if (i2 + 6 >= wordChars.length) - continue; - words.push(v2); - } - if (chk !== ENCODING_CONST) - return "Invalid checksum for " + str; - return { prefix, words }; - } - function decodeUnsafe(str, LIMIT) { - const res = __decode(str, LIMIT); - if (typeof res === "object") - return res; - } - function decode6(str, LIMIT) { - const res = __decode(str, LIMIT); - if (typeof res === "object") - return res; - throw new Error(res); - } - return { - decodeUnsafe, - decode: decode6, - encode: encode5, - toWords, - fromWordsUnsafe, - fromWords - }; - } - exports2.bech32 = getLibraryFromEncoding("bech32"); - exports2.bech32m = getLibraryFromEncoding("bech32m"); - } -}); - -// node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js -var require_transaction_decoder = __commonJS({ - "node_modules/@multiversx/sdk-transaction-decoder/lib/src/transaction.decoder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenTransferProperties = exports2.TransactionMetadataTransfer = exports2.TransactionMetadata = exports2.TransactionToDecode = exports2.TransactionDecoder = void 0; - var bech32_1 = require_dist(); - var TransactionDecoder = class { - getTransactionMetadata(transaction) { - const metadata = this.getNormalTransactionMetadata(transaction); - const esdtMetadata = this.getEsdtTransactionMetadata(metadata); - if (esdtMetadata) { - return esdtMetadata; - } - const nftMetadata = this.getNftTransferMetadata(metadata); - if (nftMetadata) { - return nftMetadata; - } - const multiMetadata = this.getMultiTransferMetadata(metadata); - if (multiMetadata) { - return multiMetadata; - } - return metadata; - } - getNormalTransactionMetadata(transaction) { - const metadata = new TransactionMetadata(); - metadata.sender = transaction.sender; - metadata.receiver = transaction.receiver; - metadata.value = BigInt(transaction.value); - if (transaction.data) { - const decodedData = this.base64Decode(transaction.data); - const dataComponents = decodedData.split("@"); - const args = dataComponents.slice(1); - if (args.every((x3) => this.isSmartContractArgument(x3))) { - metadata.functionName = dataComponents[0]; - metadata.functionArgs = args; - } - if (metadata.functionName === "relayedTx" && metadata.functionArgs && metadata.functionArgs.length === 1) { - try { - const relayedTransaction = JSON.parse(this.hexToString(metadata.functionArgs[0])); - relayedTransaction.value = relayedTransaction.value.toString(); - relayedTransaction.sender = this.bech32Encode(this.base64ToHex(relayedTransaction.sender)); - relayedTransaction.receiver = this.bech32Encode(this.base64ToHex(relayedTransaction.receiver)); - return this.getNormalTransactionMetadata(relayedTransaction); - } catch (error) { - } - } - if (metadata.functionName === "relayedTxV2" && metadata.functionArgs && metadata.functionArgs.length === 4) { - try { - const relayedTransaction = new TransactionToDecode(); - relayedTransaction.sender = transaction.receiver; - relayedTransaction.receiver = this.bech32Encode(metadata.functionArgs[0]); - relayedTransaction.data = this.base64Encode(this.hexToString(metadata.functionArgs[2])); - relayedTransaction.value = "0"; - return this.getNormalTransactionMetadata(relayedTransaction); - } catch (error) { - } - } - } - return metadata; - } - getMultiTransferMetadata(metadata) { - if (metadata.sender !== metadata.receiver) { - return void 0; - } - if (metadata.functionName !== "MultiESDTNFTTransfer") { - return void 0; - } - const args = metadata.functionArgs; - if (!args) { - return void 0; - } - if (args.length < 3) { - return void 0; - } - if (!this.isAddressValid(args[0])) { - return void 0; - } - const receiver = this.bech32Encode(args[0]); - const transferCount = this.hexToNumber(args[1]); - const result = new TransactionMetadata(); - if (!result.transfers) { - result.transfers = []; - } - let index = 2; - for (let i2 = 0; i2 < transferCount; i2++) { - const identifier = this.hexToString(args[index++]); - const nonce = args[index++]; - const value = this.hexToBigInt(args[index++]); - if (nonce) { - result.transfers.push({ - value, - properties: { - collection: identifier, - identifier: `${identifier}-${nonce}` - } - }); - } else { - result.transfers.push({ - value, - properties: { - token: identifier - } - }); - } - } - result.sender = metadata.sender; - result.receiver = receiver; - if (args.length > index) { - result.functionName = this.hexToString(args[index++]); - result.functionArgs = args.slice(index++); - } - return result; - } - getNftTransferMetadata(metadata) { - if (metadata.sender !== metadata.receiver) { - return void 0; - } - if (metadata.functionName !== "ESDTNFTTransfer") { - return void 0; - } - const args = metadata.functionArgs; - if (!args) { - return void 0; - } - if (args.length < 4) { - return void 0; - } - if (!this.isAddressValid(args[3])) { - return void 0; - } - const collectionIdentifier = this.hexToString(args[0]); - const nonce = args[1]; - const value = this.hexToBigInt(args[2]); - const receiver = this.bech32Encode(args[3]); - const result = new TransactionMetadata(); - result.sender = metadata.sender; - result.receiver = receiver; - result.value = value; - if (args.length > 4) { - result.functionName = this.hexToString(args[4]); - result.functionArgs = args.slice(5); - } - result.transfers = [{ - value, - properties: { - collection: collectionIdentifier, - identifier: `${collectionIdentifier}-${nonce}` - } - }]; - return result; - } - base64Encode(str) { - return import_buffer.Buffer.from(str).toString("base64"); - } - base64Decode(str) { - return import_buffer.Buffer.from(str, "base64").toString("binary"); - } - hexToNumber(hex) { - return parseInt(hex, 16); - } - getEsdtTransactionMetadata(metadata) { - if (metadata.functionName !== "ESDTTransfer") { - return void 0; - } - const args = metadata.functionArgs; - if (!args) { - return void 0; - } - if (args.length < 2) { - return void 0; - } - const tokenIdentifier = this.hexToString(args[0]); - const value = this.hexToBigInt(args[1]); - const result = new TransactionMetadata(); - result.sender = metadata.sender; - result.receiver = metadata.receiver; - if (args.length > 2) { - result.functionName = this.hexToString(args[2]); - result.functionArgs = args.slice(3); - } - result.transfers = [{ - value, - properties: { - identifier: tokenIdentifier - } - }]; - result.value = value; - return result; - } - bech32Encode(address) { - const pubKey = import_buffer.Buffer.from(address, "hex"); - const words = bech32_1.bech32.toWords(pubKey); - return bech32_1.bech32.encode("erd", words); - } - isAddressValid(address) { - return import_buffer.Buffer.from(address, "hex").length == 32; - } - isSmartContractArgument(arg) { - if (!this.isHex(arg)) { - return false; - } - if (arg.length % 2 !== 0) { - return false; - } - return true; - } - isHex(value) { - return new RegExp(/[^a-f0-9]/gi).test(value) === false; - } - base64ToHex(str) { - return import_buffer.Buffer.from(str, "base64").toString("hex"); - } - hexToString(hex) { - return import_buffer.Buffer.from(hex, "hex").toString("ascii"); - } - hexToBigInt(hex) { - if (!hex) { - return BigInt(0); - } - return BigInt("0x" + hex); - } - }; - exports2.TransactionDecoder = TransactionDecoder; - var TransactionToDecode = class { - constructor() { - this.sender = ""; - this.receiver = ""; - this.data = ""; - this.value = "0"; - } - }; - exports2.TransactionToDecode = TransactionToDecode; - var TransactionMetadata = class { - constructor() { - this.sender = ""; - this.receiver = ""; - this.value = BigInt(0); - } - }; - exports2.TransactionMetadata = TransactionMetadata; - var TransactionMetadataTransfer = class { - constructor() { - this.value = BigInt(0); - } - }; - exports2.TransactionMetadataTransfer = TransactionMetadataTransfer; - var TokenTransferProperties = class { - }; - exports2.TokenTransferProperties = TokenTransferProperties; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js -var require_returnCode = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/returnCode.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ReturnCode = void 0; - var ReturnCode = class _ReturnCode { - constructor(text) { - this.text = text; - } - static fromBuffer(buffer) { - let text = buffer.toString(); - return new _ReturnCode(text); - } - toString() { - return this.text; - } - valueOf() { - return this.text; - } - equals(other) { - if (!other) { - return false; - } - return this.text == other.text; - } - isSuccess() { - return this.equals(_ReturnCode.Ok) || this.equals(_ReturnCode.None); - } - }; - exports2.ReturnCode = ReturnCode; - ReturnCode.None = new ReturnCode(""); - ReturnCode.Ok = new ReturnCode("ok"); - ReturnCode.FunctionNotFound = new ReturnCode("function not found"); - ReturnCode.FunctionWrongSignature = new ReturnCode("wrong signature for function"); - ReturnCode.ContractNotFound = new ReturnCode("contract not found"); - ReturnCode.UserError = new ReturnCode("user error"); - ReturnCode.OutOfGas = new ReturnCode("out of gas"); - ReturnCode.AccountCollision = new ReturnCode("account collision"); - ReturnCode.OutOfFunds = new ReturnCode("out of funds"); - ReturnCode.CallStackOverFlow = new ReturnCode("call stack overflow"); - ReturnCode.ContractInvalid = new ReturnCode("contract invalid"); - ReturnCode.ExecutionFailed = new ReturnCode("execution failed"); - ReturnCode.Unknown = new ReturnCode("unknown"); - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js -var require_resultsParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/resultsParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ResultsParser = void 0; - var transaction_decoder_1 = require_transaction_decoder(); - var address_1 = require_address(); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var argSerializer_1 = require_argSerializer(); - var returnCode_1 = require_returnCode(); - var WellKnownEvents; - (function(WellKnownEvents2) { - WellKnownEvents2["OnTransactionCompleted"] = "completedTxEvent"; - WellKnownEvents2["OnSignalError"] = "signalError"; - WellKnownEvents2["OnWriteLog"] = "writeLog"; - })(WellKnownEvents || (WellKnownEvents = {})); - var WellKnownTopics; - (function(WellKnownTopics2) { - WellKnownTopics2["TooMuchGas"] = "@too much gas provided for processing"; - })(WellKnownTopics || (WellKnownTopics = {})); - var defaultResultsParserOptions = { - argsSerializer: new argSerializer_1.ArgSerializer() - }; - var ResultsParser = class { - constructor(options) { - options = { ...defaultResultsParserOptions, ...options }; - this.argsSerializer = options.argsSerializer; - } - /** - * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. - */ - parseQueryResponse(queryResponse, endpoint) { - let parts = queryResponse.getReturnDataParts(); - let values = this.argsSerializer.buffersToValues(parts, endpoint.output); - let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); - return { - returnCode, - returnMessage: queryResponse.returnMessage, - values, - firstValue: values[0], - secondValue: values[1], - thirdValue: values[2], - lastValue: values[values.length - 1] - }; - } - /** - * Legacy method, use "SmartContractQueriesController.parseQueryResponse()" instead. - */ - parseUntypedQueryResponse(queryResponse) { - let returnCode = new returnCode_1.ReturnCode(queryResponse.returnCode.toString()); - return { - returnCode, - returnMessage: queryResponse.returnMessage, - values: queryResponse.getReturnDataParts() - }; - } - /** - * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. - */ - parseOutcome(transaction, endpoint) { - const untypedBundle = this.parseUntypedOutcome(transaction); - const typedBundle = this.parseOutcomeFromUntypedBundle(untypedBundle, endpoint); - return typedBundle; - } - /** - * @internal - * For internal use only. - */ - parseOutcomeFromUntypedBundle(bundle, endpoint) { - const values = this.argsSerializer.buffersToValues(bundle.values, endpoint.output); - return { - returnCode: bundle.returnCode, - returnMessage: bundle.returnMessage, - values, - firstValue: values[0], - secondValue: values[1], - thirdValue: values[2], - lastValue: values[values.length - 1] - }; - } - /** - * Legacy method, use "SmartContractTransactionsOutcomeParser.parseExecute()" instead. - */ - parseUntypedOutcome(transaction) { - let bundle; - let transactionMetadata = this.parseTransactionMetadata(transaction); - bundle = this.createBundleOnSimpleMoveBalance(transaction); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on simple move balance"); - return bundle; - } - bundle = this.createBundleOnInvalidTransaction(transaction); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on invalid transaction"); - return bundle; - } - bundle = this.createBundleOnEasilyFoundResultWithReturnData(transaction.contractResults); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on easily found result with return data"); - return bundle; - } - bundle = this.createBundleOnSignalError(transaction.logs); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on signal error"); - return bundle; - } - bundle = this.createBundleOnTooMuchGasWarning(transaction.logs); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"); - return bundle; - } - bundle = this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(transaction.logs, transaction.sender); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"); - return bundle; - } - bundle = this.createBundleWithCustomHeuristics(transaction, transactionMetadata); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): with custom heuristics"); - return bundle; - } - bundle = this.createBundleWithFallbackHeuristics(transaction, transactionMetadata); - if (bundle) { - logger_1.Logger.trace("parseUntypedOutcome(): with fallback heuristics"); - return bundle; - } - throw new errors_1.ErrCannotParseContractResults(`transaction ${transaction.hash.toString()}`); - } - parseTransactionMetadata(transaction) { - return new transaction_decoder_1.TransactionDecoder().getTransactionMetadata({ - sender: transaction.sender.bech32(), - receiver: transaction.receiver.bech32(), - data: transaction.data.toString("base64"), - value: transaction.value.toString() - }); - } - createBundleOnSimpleMoveBalance(transaction) { - let noResults = transaction.contractResults.items.length == 0; - let noLogs = transaction.logs.events.length == 0; - if (noResults && noLogs) { - return { - returnCode: returnCode_1.ReturnCode.None, - returnMessage: returnCode_1.ReturnCode.None.toString(), - values: [] - }; - } - return null; - } - createBundleOnInvalidTransaction(transaction) { - if (transaction.status.isInvalid()) { - if (transaction.receipt.data) { - return { - returnCode: returnCode_1.ReturnCode.OutOfFunds, - returnMessage: transaction.receipt.data, - values: [] - }; - } - } - return null; - } - createBundleOnEasilyFoundResultWithReturnData(results) { - let resultItemWithReturnData = results.items.find((item) => item.nonce.valueOf() != 0 && item.data.startsWith("@")); - if (!resultItemWithReturnData) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(resultItemWithReturnData.data); - let returnMessage = resultItemWithReturnData.returnMessage || returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - createBundleOnSignalError(logs) { - let eventSignalError = logs.findSingleOrNoneEvent(WellKnownEvents.OnSignalError); - if (!eventSignalError) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventSignalError.data); - let lastTopic = eventSignalError.getLastTopic(); - let returnMessage = lastTopic?.toString() || returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - createBundleOnTooMuchGasWarning(logs) { - let eventTooMuchGas = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.toString().startsWith(WellKnownTopics.TooMuchGas)) != void 0); - if (!eventTooMuchGas) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventTooMuchGas.data); - let lastTopic = eventTooMuchGas.getLastTopic(); - let returnMessage = lastTopic?.toString() || returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - createBundleOnWriteLogWhereFirstTopicEqualsAddress(logs, address) { - let hexAddress = new address_1.Address(address.bech32()).hex(); - let eventWriteLogWhereTopicIsSender = logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => event.findFirstOrNoneTopic((topic) => topic.hex() == hexAddress) != void 0); - if (!eventWriteLogWhereTopicIsSender) { - return null; - } - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(eventWriteLogWhereTopicIsSender.data); - let returnMessage = returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - /** - * Override this method (in a subclass of {@link ResultsParser}) if the basic heuristics of the parser are not sufficient. - */ - createBundleWithCustomHeuristics(_transaction, _transactionMetadata) { - return null; - } - createBundleWithFallbackHeuristics(transaction, transactionMetadata) { - let contractAddress = new address_1.Address(transactionMetadata.receiver); - for (const resultItem of transaction.contractResults.items) { - let writeLogWithReturnData = resultItem.logs.findSingleOrNoneEvent(WellKnownEvents.OnWriteLog, (event) => { - let addressIsSender = event.address.bech32() == transaction.sender.bech32(); - let firstTopicIsContract = event.topics[0]?.hex() == contractAddress.hex(); - return addressIsSender && firstTopicIsContract; - }); - if (writeLogWithReturnData) { - let { returnCode, returnDataParts } = this.sliceDataFieldInParts(writeLogWithReturnData.data); - let returnMessage = returnCode.toString(); - return { - returnCode, - returnMessage, - values: returnDataParts - }; - } - } - return null; - } - sliceDataFieldInParts(data) { - let startingIndex = 1; - if (data.startsWith("ESDTTransfer")) { - startingIndex = 3; - } else { - } - let parts = this.argsSerializer.stringToBuffers(data); - let returnCodePart = parts[startingIndex] || import_buffer.Buffer.from([]); - let returnDataParts = parts.slice(startingIndex + 1); - if (returnCodePart.length == 0) { - throw new errors_1.ErrCannotParseContractResults("no return code"); - } - let returnCode = returnCode_1.ReturnCode.fromBuffer(returnCodePart); - return { returnCode, returnDataParts }; - } - /** - * Legacy method, use "TransactionEventsParser.parseEvent()" instead. - */ - parseEvent(transactionEvent, eventDefinition) { - const topics = transactionEvent.topics.map((topic) => import_buffer.Buffer.from(topic.valueOf())).slice(1); - const legacyData = transactionEvent.dataPayload?.valueOf() || import_buffer.Buffer.from([]); - const dataItems = transactionEvent.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; - if (dataItems.length === 0) { - if (legacyData.length) { - dataItems.push(import_buffer.Buffer.from(legacyData)); - } - } - return this.doParseEvent({ topics, dataItems, eventDefinition }); - } - /** - * @internal - * For internal use only. - * - * Once the legacy "ResultParser" is deprecated & removed, this logic will be absorbed into "TransactionEventsParser". - */ - doParseEvent(options) { - const result = {}; - const indexedInputs = options.eventDefinition.inputs.filter((input) => input.indexed); - const decodedTopics = this.argsSerializer.buffersToValues(options.topics, indexedInputs); - for (let i2 = 0; i2 < indexedInputs.length; i2++) { - result[indexedInputs[i2].name] = decodedTopics[i2].valueOf(); - } - const nonIndexedInputs = options.eventDefinition.inputs.filter((input) => !input.indexed); - const decodedDataParts = this.argsSerializer.buffersToValues(options.dataItems, nonIndexedInputs); - for (let i2 = 0; i2 < nonIndexedInputs.length; i2++) { - result[nonIndexedInputs[i2].name] = decodedDataParts[i2].valueOf(); - } - return result; - } - }; - exports2.ResultsParser = ResultsParser; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js -var require_smartContract = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/smartContract.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContract = void 0; - var address_1 = require_address(); - var compatibility_1 = require_compatibility(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var smartContractTransactionsFactory_1 = require_smartContractTransactionsFactory(); - var transactionsFactoryConfig_1 = require_transactionsFactoryConfig(); - var utils_1 = require_utils2(); - var codeMetadata_1 = require_codeMetadata2(); - var function_1 = require_function(); - var interaction_1 = require_interaction(); - var nativeSerializer_1 = require_nativeSerializer(); - var query_1 = require_query(); - var SmartContract = class { - /** - * Create a SmartContract object by providing its address on the Network. - */ - constructor(options = {}) { - this.address = address_1.Address.empty(); - this.methodsExplicit = {}; - this.methods = {}; - this.address = options.address || address_1.Address.empty(); - this.abi = options.abi; - if (this.abi) { - this.setupMethods(); - } - } - setupMethods() { - let contract = this; - let abi = this.getAbi(); - for (const definition of abi.getEndpoints()) { - let functionName = definition.name; - this.methodsExplicit[functionName] = function(args) { - let func = new function_1.ContractFunction(functionName); - let interaction = new interaction_1.Interaction(contract, func, args || []); - return interaction; - }; - this.methods[functionName] = function(args) { - let func = new function_1.ContractFunction(functionName); - let typedArgs = nativeSerializer_1.NativeSerializer.nativeToTypedValues(args || [], definition); - let interaction = new interaction_1.Interaction(contract, func, typedArgs || []); - return interaction; - }; - } - } - /** - * Sets the address, as on Network. - */ - setAddress(address) { - this.address = address; - } - /** - * Gets the address, as on Network. - */ - getAddress() { - return this.address; - } - getAbi() { - utils_1.guardValueIsSet("abi", this.abi); - return this.abi; - } - getEndpoint(name2) { - return this.getAbi().getEndpoint(name2); - } - /** - * Creates a {@link Transaction} for deploying the Smart Contract to the Network. - */ - deploy({ deployer, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(deployer, "'deployer' of SmartContract.deploy()", "pass the actual address to deploy()"); - const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); - const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ - config, - abi: this.abi - }); - const bytecode = import_buffer.Buffer.from(code2.toString(), "hex"); - const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); - const transaction = factory.createTransactionForDeploy({ - sender: deployer, - bytecode, - gasLimit: BigInt(gasLimit.valueOf()), - arguments: initArguments, - isUpgradeable: metadataAsJson.upgradeable, - isReadable: metadataAsJson.readable, - isPayable: metadataAsJson.payable, - isPayableBySmartContract: metadataAsJson.payableBySc - }); - transaction.setChainID(chainID); - transaction.setValue(value ?? 0); - transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); - return transaction; - } - getMetadataPropertiesAsObject(codeMetadata) { - let metadata; - if (codeMetadata) { - metadata = codeMetadata_1.CodeMetadata.fromBytes(import_buffer.Buffer.from(codeMetadata.toString(), "hex")); - } else { - metadata = new codeMetadata_1.CodeMetadata(); - } - const metadataAsJson = metadata.toJSON(); - return metadataAsJson; - } - /** - * Creates a {@link Transaction} for upgrading the Smart Contract on the Network. - */ - upgrade({ caller, code: code2, codeMetadata, initArguments, value, gasLimit, gasPrice, chainID }) { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.upgrade()", "pass the actual address to upgrade()"); - this.ensureHasAddress(); - const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); - const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ - config, - abi: this.abi - }); - const bytecode = Uint8Array.from(import_buffer.Buffer.from(code2.toString(), "hex")); - const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata); - const transaction = factory.createTransactionForUpgrade({ - sender: caller, - contract: this.getAddress(), - bytecode, - gasLimit: BigInt(gasLimit.valueOf()), - arguments: initArguments, - isUpgradeable: metadataAsJson.upgradeable, - isReadable: metadataAsJson.readable, - isPayable: metadataAsJson.payable, - isPayableBySmartContract: metadataAsJson.payableBySc - }); - transaction.setChainID(chainID); - transaction.setValue(value ?? 0); - transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); - return transaction; - } - /** - * Creates a {@link Transaction} for calling (a function of) the Smart Contract. - */ - call({ func, args, value, gasLimit, receiver, gasPrice, chainID, caller }) { - compatibility_1.Compatibility.guardAddressIsSetAndNonZero(caller, "'caller' of SmartContract.call()", "pass the actual address to call()"); - this.ensureHasAddress(); - const config = new transactionsFactoryConfig_1.TransactionsFactoryConfig({ chainID: chainID.valueOf() }); - const factory = new smartContractTransactionsFactory_1.SmartContractTransactionsFactory({ - config, - abi: this.abi - }); - args = args || []; - value = value || 0; - const transaction = factory.createTransactionForExecute({ - sender: caller, - contract: receiver ? receiver : this.getAddress(), - function: func.toString(), - gasLimit: BigInt(gasLimit.valueOf()), - arguments: args - }); - transaction.setChainID(chainID); - transaction.setValue(value); - transaction.setGasPrice(gasPrice ?? constants_1.TRANSACTION_MIN_GAS_PRICE); - return transaction; - } - createQuery({ func, args, value, caller }) { - this.ensureHasAddress(); - return new query_1.Query({ - address: this.getAddress(), - func, - args, - value, - caller - }); - } - ensureHasAddress() { - if (!this.getAddress().bech32()) { - throw new errors_1.ErrContractHasNoAddress(); - } - } - /** - * Computes the address of a Smart Contract. - * The address is computed deterministically, from the address of the owner and the nonce of the deployment transaction. - * - * @param owner The owner of the Smart Contract - * @param nonce The owner nonce used for the deployment transaction - */ - static computeAddress(owner, nonce) { - const deployer = address_1.Address.fromBech32(owner.bech32()); - const addressComputer = new address_1.AddressComputer(); - return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf())); - } - }; - exports2.SmartContract = SmartContract; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js -var require_transactionPayloadBuilders = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/transactionPayloadBuilders.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractCallPayloadBuilder = exports2.ContractUpgradePayloadBuilder = exports2.ContractDeployPayloadBuilder = void 0; - var constants_1 = require_constants(); - var transactionPayload_1 = require_transactionPayload(); - var utils_1 = require_utils2(); - var argSerializer_1 = require_argSerializer(); - var ContractDeployPayloadBuilder = class { - constructor() { - this.code = null; - this.codeMetadata = ""; - this.arguments = []; - } - /** - * Sets the code of the Smart Contract. - */ - setCode(code2) { - this.code = code2; - return this; - } - /** - * Sets the code metadata of the Smart Contract. - */ - setCodeMetadata(codeMetadata) { - this.codeMetadata = codeMetadata; - return this; - } - /** - * Adds constructor (`init`) arguments. - */ - addInitArg(arg) { - this.arguments.push(arg); - return this; - } - /** - * Sets constructor (`init`) arguments. - */ - setInitArgs(args) { - this.arguments = args; - return this; - } - /** - * Builds the {@link TransactionPayload}. - */ - build() { - utils_1.guardValueIsSet("code", this.code); - let code2 = this.code.toString(); - let codeMetadata = this.codeMetadata.toString(); - let data = `${code2}@${constants_1.WasmVirtualMachine}@${codeMetadata}`; - data = appendArgumentsToString(data, this.arguments); - return new transactionPayload_1.TransactionPayload(data); - } - }; - exports2.ContractDeployPayloadBuilder = ContractDeployPayloadBuilder; - var ContractUpgradePayloadBuilder = class { - constructor() { - this.code = null; - this.codeMetadata = ""; - this.arguments = []; - } - /** - * Sets the code of the Smart Contract. - */ - setCode(code2) { - this.code = code2; - return this; - } - /** - * Sets the code metadata of the Smart Contract. - */ - setCodeMetadata(codeMetadata) { - this.codeMetadata = codeMetadata; - return this; - } - /** - * Adds upgrade (`init`) arguments. - */ - addInitArg(arg) { - this.arguments.push(arg); - return this; - } - /** - * Sets upgrade (`init`) arguments. - */ - setInitArgs(args) { - this.arguments = args; - return this; - } - /** - * Builds the {@link TransactionPayload}. - */ - build() { - utils_1.guardValueIsSet("code", this.code); - let code2 = this.code.toString(); - let codeMetadata = this.codeMetadata.toString(); - let data = `upgradeContract@${code2}@${codeMetadata}`; - data = appendArgumentsToString(data, this.arguments); - return new transactionPayload_1.TransactionPayload(data); - } - }; - exports2.ContractUpgradePayloadBuilder = ContractUpgradePayloadBuilder; - var ContractCallPayloadBuilder = class { - constructor() { - this.contractFunction = null; - this.arguments = []; - } - /** - * Sets the function to be called (executed). - */ - setFunction(contractFunction) { - this.contractFunction = contractFunction; - return this; - } - /** - * Adds a function argument. - */ - addArg(arg) { - this.arguments.push(arg); - return this; - } - /** - * Sets the function arguments. - */ - setArgs(args) { - this.arguments = args; - return this; - } - /** - * Builds the {@link TransactionPayload}. - */ - build() { - utils_1.guardValueIsSet("calledFunction", this.contractFunction); - let data = this.contractFunction.toString(); - data = appendArgumentsToString(data, this.arguments); - return new transactionPayload_1.TransactionPayload(data); - } - }; - exports2.ContractCallPayloadBuilder = ContractCallPayloadBuilder; - function appendArgumentsToString(to, values) { - let { argumentsString, count } = new argSerializer_1.ArgSerializer().valuesToString(values); - if (count == 0) { - return to; - } - return `${to}@${argumentsString}`; - } - } -}); - -// node_modules/@multiversx/sdk-core/out/smartcontracts/index.js -var require_smartcontracts = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartcontracts/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_argSerializer(), exports2); - __exportStar2(require_code(), exports2); - __exportStar2(require_codec2(), exports2); - __exportStar2(require_codeMetadata2(), exports2); - __exportStar2(require_function(), exports2); - __exportStar2(require_interaction(), exports2); - __exportStar2(require_interactionChecker(), exports2); - __exportStar2(require_interface(), exports2); - __exportStar2(require_nativeSerializer(), exports2); - __exportStar2(require_query(), exports2); - __exportStar2(require_resultsParser(), exports2); - __exportStar2(require_returnCode(), exports2); - __exportStar2(require_smartContract(), exports2); - __exportStar2(require_transactionPayloadBuilders(), exports2); - __exportStar2(require_typesystem(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js -var require_resources = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/resources.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.gatherAllEvents = exports2.findEventsByFirstTopic = exports2.findEventsByIdentifier = exports2.findEventsByPredicate = exports2.SmartContractCallOutcome = exports2.TransactionOutcome = exports2.SmartContractResult = exports2.TransactionLogs = exports2.TransactionEvent = void 0; - var TransactionEvent = class { - constructor(init) { - this.address = ""; - this.identifier = ""; - this.topics = []; - this.dataItems = []; - Object.assign(this, init); - } - }; - exports2.TransactionEvent = TransactionEvent; - var TransactionLogs2 = class { - constructor(init) { - this.address = ""; - this.events = []; - Object.assign(this, init); - } - }; - exports2.TransactionLogs = TransactionLogs2; - var SmartContractResult = class { - constructor(init) { - this.sender = ""; - this.receiver = ""; - this.data = new Uint8Array(); - this.logs = new TransactionLogs2({}); - Object.assign(this, init); - } - }; - exports2.SmartContractResult = SmartContractResult; - var TransactionOutcome = class { - constructor(init) { - this.directSmartContractCallOutcome = new SmartContractCallOutcome({}); - this.smartContractResults = []; - this.logs = new TransactionLogs2({}); - Object.assign(this, init); - } - }; - exports2.TransactionOutcome = TransactionOutcome; - var SmartContractCallOutcome = class { - constructor(init) { - this.function = ""; - this.returnDataParts = []; - this.returnMessage = ""; - this.returnCode = ""; - Object.assign(this, init); - } - }; - exports2.SmartContractCallOutcome = SmartContractCallOutcome; - function findEventsByPredicate(transactionOutcome, predicate) { - return gatherAllEvents(transactionOutcome).filter(predicate); - } - exports2.findEventsByPredicate = findEventsByPredicate; - function findEventsByIdentifier(transactionOutcome, identifier) { - return findEventsByPredicate(transactionOutcome, (event) => event.identifier == identifier); - } - exports2.findEventsByIdentifier = findEventsByIdentifier; - function findEventsByFirstTopic(transactionOutcome, topic) { - return findEventsByPredicate(transactionOutcome, (event) => event.topics[0]?.toString() == topic); - } - exports2.findEventsByFirstTopic = findEventsByFirstTopic; - function gatherAllEvents(transactionOutcome) { - const allEvents = []; - allEvents.push(...transactionOutcome.logs.events); - for (const item of transactionOutcome.smartContractResults) { - allEvents.push(...item.logs.events); - } - return allEvents; - } - exports2.gatherAllEvents = gatherAllEvents; - } -}); - -// node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js -var require_transactionsConverter = __commonJS({ - "node_modules/@multiversx/sdk-core/out/converters/transactionsConverter.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionsConverter = void 0; - var smartcontracts_1 = require_smartcontracts(); - var transaction_1 = require_transaction(); - var resources_1 = require_resources(); - var TransactionsConverter = class { - transactionToPlainObject(transaction) { - const plainObject = { - nonce: Number(transaction.nonce), - value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, - senderUsername: this.toBase64OrUndefined(transaction.senderUsername), - receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), - gasPrice: Number(transaction.gasPrice), - gasLimit: Number(transaction.gasLimit), - data: this.toBase64OrUndefined(transaction.data), - chainID: transaction.chainID.valueOf(), - version: transaction.version, - options: transaction.options == 0 ? void 0 : transaction.options, - guardian: transaction.guardian ? transaction.guardian : void 0, - signature: this.toHexOrUndefined(transaction.signature), - guardianSignature: this.toHexOrUndefined(transaction.guardianSignature) - }; - return plainObject; - } - toBase64OrUndefined(value) { - return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; - } - toHexOrUndefined(value) { - return value && value.length ? import_buffer.Buffer.from(value).toString("hex") : void 0; - } - plainObjectToTransaction(object) { - const transaction = new transaction_1.Transaction({ - nonce: BigInt(object.nonce), - value: BigInt(object.value || ""), - receiver: object.receiver, - receiverUsername: this.bufferFromBase64(object.receiverUsername).toString(), - sender: object.sender, - senderUsername: this.bufferFromBase64(object.senderUsername).toString(), - guardian: object.guardian, - gasPrice: BigInt(object.gasPrice), - gasLimit: BigInt(object.gasLimit), - data: this.bufferFromBase64(object.data), - chainID: String(object.chainID), - version: Number(object.version), - options: Number(object.options), - signature: this.bufferFromHex(object.signature), - guardianSignature: this.bufferFromHex(object.guardianSignature) - }); - return transaction; - } - bufferFromBase64(value) { - return import_buffer.Buffer.from(value || "", "base64"); - } - bufferFromHex(value) { - return import_buffer.Buffer.from(value || "", "hex"); - } - transactionOnNetworkToOutcome(transactionOnNetwork) { - const legacyResultsParser = new smartcontracts_1.ResultsParser(); - const callOutcomeBundle = legacyResultsParser.parseUntypedOutcome(transactionOnNetwork); - const callOutcome = new resources_1.SmartContractCallOutcome({ - function: transactionOnNetwork.function, - returnCode: callOutcomeBundle.returnCode.toString(), - returnMessage: callOutcomeBundle.returnMessage, - returnDataParts: callOutcomeBundle.values - }); - const contractResults = transactionOnNetwork.contractResults.items.map((result) => this.smartContractResultOnNetworkToSmartContractResult(result)); - const logs = new resources_1.TransactionLogs({ - address: transactionOnNetwork.logs.address.bech32(), - events: transactionOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) - }); - return new resources_1.TransactionOutcome({ - logs, - smartContractResults: contractResults, - directSmartContractCallOutcome: callOutcome - }); - } - smartContractResultOnNetworkToSmartContractResult(resultOnNetwork) { - return new resources_1.SmartContractResult({ - sender: resultOnNetwork.sender.bech32(), - receiver: resultOnNetwork.receiver.bech32(), - data: import_buffer.Buffer.from(resultOnNetwork.data), - logs: new resources_1.TransactionLogs({ - address: resultOnNetwork.logs.address.bech32(), - events: resultOnNetwork.logs.events.map((event) => this.eventOnNetworkToEvent(event)) - }) - }); - } - eventOnNetworkToEvent(eventOnNetwork) { - const legacyData = eventOnNetwork.dataPayload?.valueOf() || import_buffer.Buffer.from(eventOnNetwork.data || ""); - const dataItems = eventOnNetwork.additionalData?.map((data) => import_buffer.Buffer.from(data.valueOf())) || []; - if (dataItems.length === 0) { - if (legacyData.length) { - dataItems.push(import_buffer.Buffer.from(legacyData)); - } - } - return new resources_1.TransactionEvent({ - address: eventOnNetwork.address.bech32(), - identifier: eventOnNetwork.identifier, - topics: eventOnNetwork.topics.map((topic) => import_buffer.Buffer.from(topic.hex(), "hex")), - dataItems - }); - } - }; - exports2.TransactionsConverter = TransactionsConverter; - } -}); - -// node_modules/@multiversx/sdk-core/out/hash.js -var require_hash = __commonJS({ - "node_modules/@multiversx/sdk-core/out/hash.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Hash = void 0; - var errors = __importStar2(require_errors()); - var Hash = class _Hash { - /** - * Creates a new Hash object. - * - * @param hash The hash, as a Buffer or a hex-encoded string. - */ - constructor(hash) { - if (!hash) { - this.hash = import_buffer.Buffer.from([]); - } else if (hash instanceof import_buffer.Buffer) { - this.hash = hash; - } else if (typeof hash === "string") { - this.hash = import_buffer.Buffer.from(hash, "hex"); - } else { - throw new errors.ErrBadType("hash", "buffer | string", hash); - } - } - static empty() { - return new _Hash(import_buffer.Buffer.from([])); - } - /** - * Returns whether the hash is empty (not computed). - */ - isEmpty() { - return this.hash.length == 0; - } - toString() { - return this.hex(); - } - hex() { - return this.hash.toString("hex"); - } - valueOf() { - return this.hash; - } - }; - exports2.Hash = Hash; - } -}); - -// node_modules/@multiversx/sdk-core/out/signature.js -var require_signature = __commonJS({ - "node_modules/@multiversx/sdk-core/out/signature.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.interpretSignatureAsBuffer = exports2.Signature = void 0; - var errors = __importStar2(require_errors()); - var SIGNATURE_LENGTH = 64; - var Signature = class _Signature { - constructor(value) { - this.valueHex = ""; - if (!value) { - return; - } - if (typeof value === "string") { - return _Signature.fromHex(value); - } - if (value instanceof import_buffer.Buffer) { - return _Signature.fromBuffer(value); - } - } - static empty() { - return new _Signature(); - } - static fromHex(value) { - if (value.startsWith("0x")) { - value = value.slice(2); - } - if (!_Signature.isValidHex(value)) { - throw new errors.ErrSignatureCannotCreate(value); - } - return _Signature.fromValidHex(value); - } - static isValidHex(value) { - return import_buffer.Buffer.from(value, "hex").length == SIGNATURE_LENGTH; - } - static fromValidHex(value) { - let result = new _Signature(); - result.valueHex = value; - return result; - } - static fromBuffer(buffer) { - if (buffer.length != SIGNATURE_LENGTH) { - throw new errors.ErrSignatureCannotCreate(buffer); - } - return _Signature.fromValidHex(buffer.toString("hex")); - } - hex() { - return this.valueHex; - } - }; - exports2.Signature = Signature; - function interpretSignatureAsBuffer(signature) { - if (ArrayBuffer.isView(signature)) { - return import_buffer.Buffer.from(signature); - } else if (signature.hex != null) { - return import_buffer.Buffer.from(signature.hex(), "hex"); - } - throw new Error(`Object cannot be interpreted as a signature: ${signature}`); - } - exports2.interpretSignatureAsBuffer = interpretSignatureAsBuffer; - } -}); - -// node_modules/@protobufjs/aspromise/index.js -var require_aspromise = __commonJS({ - "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = asPromise; - function asPromise(fn, ctx) { - var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params2 = new Array(arguments.length - 1), offset2 = 0; - while (offset2 < params2.length) - params2[offset2++] = arguments[offset2]; - resolve.apply(null, params2); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); - } - } -}); - -// node_modules/@protobufjs/base64/index.js -var require_base64 = __commonJS({ - "node_modules/@protobufjs/base64/index.js"(exports2) { - "use strict"; - init_shim(); - var base642 = exports2; - base642.length = function length2(string2) { - var p3 = string2.length; - if (!p3) - return 0; - var n3 = 0; - while (--p3 % 4 > 1 && string2.charAt(p3) === "=") - ++n3; - return Math.ceil(string2.length * 3) / 4 - n3; - }; - var b64 = new Array(64); - var s64 = new Array(123); - for (i2 = 0; i2 < 64; ) - s64[b64[i2] = i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 - 59 | 43] = i2++; - var i2; - base642.encode = function encode5(buffer, start, end) { - var parts = null, chunk = []; - var i3 = 0, j2 = 0, t; - while (start < end) { - var b4 = buffer[start++]; - switch (j2) { - case 0: - chunk[i3++] = b64[b4 >> 2]; - t = (b4 & 3) << 4; - j2 = 1; - break; - case 1: - chunk[i3++] = b64[t | b4 >> 4]; - t = (b4 & 15) << 2; - j2 = 2; - break; - case 2: - chunk[i3++] = b64[t | b4 >> 6]; - chunk[i3++] = b64[b4 & 63]; - j2 = 0; - break; - } - if (i3 > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i3 = 0; - } - } - if (j2) { - chunk[i3++] = b64[t]; - chunk[i3++] = 61; - if (j2 === 1) - chunk[i3++] = 61; - } - if (parts) { - if (i3) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i3))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i3)); - }; - var invalidEncoding = "invalid encoding"; - base642.decode = function decode6(string2, buffer, offset) { - var start = offset; - var j2 = 0, t; - for (var i3 = 0; i3 < string2.length; ) { - var c4 = string2.charCodeAt(i3++); - if (c4 === 61 && j2 > 1) - break; - if ((c4 = s64[c4]) === void 0) - throw Error(invalidEncoding); - switch (j2) { - case 0: - t = c4; - j2 = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c4 & 48) >> 4; - t = c4; - j2 = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c4 & 60) >> 2; - t = c4; - j2 = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c4; - j2 = 0; - break; - } - } - if (j2 === 1) - throw Error(invalidEncoding); - return offset - start; - }; - base642.test = function test(string2) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string2); - }; - } -}); - -// node_modules/@protobufjs/eventemitter/index.js -var require_eventemitter = __commonJS({ - "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = EventEmitter2; - function EventEmitter2() { - this._listeners = {}; - } - EventEmitter2.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn, - ctx: ctx || this - }); - return this; - }; - EventEmitter2.prototype.off = function off(evt, fn) { - if (evt === void 0) - this._listeners = {}; - else { - if (fn === void 0) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i2 = 0; i2 < listeners.length; ) - if (listeners[i2].fn === fn) - listeners.splice(i2, 1); - else - ++i2; - } - } - return this; - }; - EventEmitter2.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], i2 = 1; - for (; i2 < arguments.length; ) - args.push(arguments[i2++]); - for (i2 = 0; i2 < listeners.length; ) - listeners[i2].fn.apply(listeners[i2++].ctx, args); - } - return this; - }; - } -}); - -// node_modules/@protobufjs/float/index.js -var require_float = __commonJS({ - "node_modules/@protobufjs/float/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = factory(factory); - function factory(exports3) { - if (typeof Float32Array !== "undefined") - (function() { - var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - })(); - else - (function() { - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign2 = val < 0 ? 1 : 0; - if (sign2) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? ( - /* positive */ - 0 - ) : ( - /* negative 0 */ - 2147483648 - ), buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 34028234663852886e22) - writeUint((sign2 << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 11754943508222875e-54) - writeUint((sign2 << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign2 << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), sign2 = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; - return exponent === 255 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 1401298464324817e-60 * mantissa : sign2 * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - })(); - if (typeof Float64Array !== "undefined") - (function() { - var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - })(); - else - (function() { - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign2 = val < 0 ? 1 : 0; - if (sign2) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? ( - /* positive */ - 0 - ) : ( - /* negative 0 */ - 2147483648 - ), buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 17976931348623157e292) { - writeUint(0, buf, pos + off0); - writeUint((sign2 << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 22250738585072014e-324) { - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign2 << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign2 << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); - var sign2 = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 ? mantissa ? NaN : sign2 * Infinity : exponent === 0 ? sign2 * 5e-324 * mantissa : sign2 * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - })(); - return exports3; - } - function writeUintLE(val, buf, pos) { - buf[pos] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; - } - function writeUintBE(val, buf, pos) { - buf[pos] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; - } - function readUintLE(buf, pos) { - return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; - } - function readUintBE(buf, pos) { - return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; - } - } -}); - -// node_modules/@protobufjs/inquire/index.js -var require_inquire = __commonJS({ - "node_modules/@protobufjs/inquire/index.js"(exports, module) { - "use strict"; - init_shim(); - module.exports = inquire; - function inquire(moduleName) { - try { - var mod = eval("quire".replace(/^/, "re"))(moduleName); - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (e2) { - } - return null; - } - } -}); - -// node_modules/@protobufjs/utf8/index.js -var require_utf8 = __commonJS({ - "node_modules/@protobufjs/utf8/index.js"(exports2) { - "use strict"; - init_shim(); - var utf8 = exports2; - utf8.length = function utf8_length(string2) { - var len = 0, c4 = 0; - for (var i2 = 0; i2 < string2.length; ++i2) { - c4 = string2.charCodeAt(i2); - if (c4 < 128) - len += 1; - else if (c4 < 2048) - len += 2; - else if ((c4 & 64512) === 55296 && (string2.charCodeAt(i2 + 1) & 64512) === 56320) { - ++i2; - len += 4; - } else - len += 3; - } - return len; - }; - utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, chunk = [], i2 = 0, t; - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i2++] = t; - else if (t > 191 && t < 224) - chunk[i2++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 65536; - chunk[i2++] = 55296 + (t >> 10); - chunk[i2++] = 56320 + (t & 1023); - } else - chunk[i2++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i2 > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i2 = 0; - } - } - if (parts) { - if (i2) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i2)); - }; - utf8.write = function utf8_write(string2, buffer, offset) { - var start = offset, c1, c22; - for (var i2 = 0; i2 < string2.length; ++i2) { - c1 = string2.charCodeAt(i2); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 64512) === 55296 && ((c22 = string2.charCodeAt(i2 + 1)) & 64512) === 56320) { - c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023); - ++i2; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; - }; - } -}); - -// node_modules/@protobufjs/pool/index.js -var require_pool = __commonJS({ - "node_modules/@protobufjs/pool/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = pool; - function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX2 = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size2) { - if (size2 < 1 || size2 > MAX2) - return alloc(size2); - if (offset + size2 > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size2); - if (offset & 7) - offset = (offset | 7) + 1; - return buf; - }; - } - } -}); - -// node_modules/protobufjs/src/util/longbits.js -var require_longbits = __commonJS({ - "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = LongBits; - var util = require_minimal(); - function LongBits(lo, hi) { - this.lo = lo >>> 0; - this.hi = hi >>> 0; - } - var zero = LongBits.zero = new LongBits(0, 0); - zero.toNumber = function() { - return 0; - }; - zero.zzEncode = zero.zzDecode = function() { - return this; - }; - zero.length = function() { - return 1; - }; - var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; - LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign2 = value < 0; - if (sign2) - value = -value; - var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; - if (sign2) { - hi = ~hi >>> 0; - lo = ~lo >>> 0; - if (++lo > 4294967295) { - lo = 0; - if (++hi > 4294967295) - hi = 0; - } - } - return new LongBits(lo, hi); - }; - LongBits.from = function from3(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (util.isString(value)) { - if (util.Long) - value = util.Long.fromString(value); - else - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; - }; - LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; - }; - LongBits.prototype.toLong = function toLong(unsigned) { - return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; - }; - var charCodeAt = String.prototype.charCodeAt; - LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - (charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, - (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 - ); - }; - LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24, - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); - }; - LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = (this.lo << 1 ^ mask) >>> 0; - return this; - }; - LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = (this.hi >>> 1 ^ mask) >>> 0; - return this; - }; - LongBits.prototype.length = function length2() { - var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; - return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; - }; - } -}); - -// node_modules/protobufjs/src/util/minimal.js -var require_minimal = __commonJS({ - "node_modules/protobufjs/src/util/minimal.js"(exports2) { - "use strict"; - init_shim(); - var util = exports2; - util.asPromise = require_aspromise(); - util.base64 = require_base64(); - util.EventEmitter = require_eventemitter(); - util.float = require_float(); - util.inquire = require_inquire(); - util.utf8 = require_utf8(); - util.pool = require_pool(); - util.LongBits = require_longbits(); - util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); - util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; - util.emptyArray = Object.freeze ? Object.freeze([]) : ( - /* istanbul ignore next */ - [] - ); - util.emptyObject = Object.freeze ? Object.freeze({}) : ( - /* istanbul ignore next */ - {} - ); - util.isInteger = Number.isInteger || /* istanbul ignore next */ - function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; - }; - util.isString = function isString2(value) { - return typeof value === "string" || value instanceof String; - }; - util.isObject = function isObject(value) { - return value && typeof value === "object"; - }; - util.isset = /** - * Checks if a property on a message is considered to be present. - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ - util.isSet = function isSet(obj, prop) { - var value = obj[prop]; - if (value != null && obj.hasOwnProperty(prop)) - return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; - return false; - }; - util.Buffer = function() { - try { - var Buffer2 = util.inquire("buffer").Buffer; - return Buffer2.prototype.utf8Write ? Buffer2 : ( - /* istanbul ignore next */ - null - ); - } catch (e2) { - return null; - } - }(); - util._Buffer_from = null; - util._Buffer_allocUnsafe = null; - util.newBuffer = function newBuffer(sizeOrArray) { - return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); - }; - util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - util.Long = /* istanbul ignore next */ - util.global.dcodeIO && /* istanbul ignore next */ - util.global.dcodeIO.Long || /* istanbul ignore next */ - util.global.Long || util.inquire("long"); - util.key2Re = /^true|false|0|1$/; - util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; - util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; - util.longToHash = function longToHash(value) { - return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; - }; - util.longFromHash = function longFromHash(hash, unsigned) { - var bits = util.LongBits.fromHash(hash); - if (util.Long) - return util.Long.fromBits(bits.lo, bits.hi, unsigned); - return bits.toNumber(Boolean(unsigned)); - }; - function merge(dst, src2, ifNotSet) { - for (var keys2 = Object.keys(src2), i2 = 0; i2 < keys2.length; ++i2) - if (dst[keys2[i2]] === void 0 || !ifNotSet) - dst[keys2[i2]] = src2[keys2[i2]]; - return dst; - } - util.merge = merge; - util.lcFirst = function lcFirst(str) { - return str.charAt(0).toLowerCase() + str.substring(1); - }; - function newError(name2) { - function CustomError(message, properties) { - if (!(this instanceof CustomError)) - return new CustomError(message, properties); - Object.defineProperty(this, "message", { get: function() { - return message; - } }); - if (Error.captureStackTrace) - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: new Error().stack || "" }); - if (properties) - merge(this, properties); - } - CustomError.prototype = Object.create(Error.prototype, { - constructor: { - value: CustomError, - writable: true, - enumerable: false, - configurable: true - }, - name: { - get: function get2() { - return name2; - }, - set: void 0, - enumerable: false, - // configurable: false would accurately preserve the behavior of - // the original, but I'm guessing that was not intentional. - // For an actual error subclass, this property would - // be configurable. - configurable: true - }, - toString: { - value: function value() { - return this.name + ": " + this.message; - }, - writable: true, - enumerable: false, - configurable: true - } - }); - return CustomError; - } - util.newError = newError; - util.ProtocolError = newError("ProtocolError"); - util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i2 = 0; i2 < fieldNames.length; ++i2) - fieldMap[fieldNames[i2]] = 1; - return function() { - for (var keys2 = Object.keys(this), i3 = keys2.length - 1; i3 > -1; --i3) - if (fieldMap[keys2[i3]] === 1 && this[keys2[i3]] !== void 0 && this[keys2[i3]] !== null) - return keys2[i3]; - }; - }; - util.oneOfSetter = function setOneOf(fieldNames) { - return function(name2) { - for (var i2 = 0; i2 < fieldNames.length; ++i2) - if (fieldNames[i2] !== name2) - delete this[fieldNames[i2]]; - }; - }; - util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true - }; - util._configure = function() { - var Buffer2 = util.Buffer; - if (!Buffer2) { - util._Buffer_from = util._Buffer_allocUnsafe = null; - return; - } - util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ - function Buffer_from(value, encoding) { - return new Buffer2(value, encoding); - }; - util._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ - function Buffer_allocUnsafe(size) { - return new Buffer2(size); - }; - }; - } -}); - -// node_modules/protobufjs/src/writer.js -var require_writer = __commonJS({ - "node_modules/protobufjs/src/writer.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Writer; - var util = require_minimal(); - var BufferWriter; - var LongBits = util.LongBits; - var base642 = util.base64; - var utf8 = util.utf8; - function Op(fn, len, val) { - this.fn = fn; - this.len = len; - this.next = void 0; - this.val = val; - } - function noop() { - } - function State(writer) { - this.head = writer.head; - this.tail = writer.tail; - this.len = writer.len; - this.next = writer.states; - } - function Writer() { - this.len = 0; - this.head = new Op(noop, 0, 0); - this.tail = this.head; - this.states = null; - } - var create2 = function create3() { - return util.Buffer ? function create_buffer_setup() { - return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); - } : function create_array() { - return new Writer(); - }; - }; - Writer.create = create2(); - Writer.alloc = function alloc(size) { - return new util.Array(size); - }; - if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); - Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; - }; - function writeByte(val, buf, pos) { - buf[pos] = val & 255; - } - function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; - } - function VarintOp(len, val) { - this.len = len; - this.next = void 0; - this.val = val; - } - VarintOp.prototype = Object.create(Op.prototype); - VarintOp.prototype.fn = writeVarint32; - Writer.prototype.uint32 = function write_uint32(value) { - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, - value - )).len; - return this; - }; - Writer.prototype.int32 = function write_int32(value) { - return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); - }; - Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); - }; - function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; - } - Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); - }; - Writer.prototype.int64 = Writer.prototype.uint64; - Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); - }; - Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); - }; - function writeFixed32(val, buf, pos) { - buf[pos] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; - } - Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); - }; - Writer.prototype.sfixed32 = Writer.prototype.fixed32; - Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); - }; - Writer.prototype.sfixed64 = Writer.prototype.fixed64; - Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); - }; - Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); - }; - var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); - } : function writeBytes_for(val, buf, pos) { - for (var i2 = 0; i2 < val.length; ++i2) - buf[pos + i2] = val[i2]; - }; - Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - if (util.isString(value)) { - var buf = Writer.alloc(len = base642.length(value)); - base642.decode(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); - }; - Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); - }; - Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - return this; - }; - Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - } - return this; - }; - Writer.prototype.ldelim = function ldelim() { - var head = this.head, tail = this.tail, len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; - this.tail = tail; - this.len += len; - } - return this; - }; - Writer.prototype.finish = function finish() { - var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - return buf; - }; - Writer._configure = function(BufferWriter_) { - BufferWriter = BufferWriter_; - Writer.create = create2(); - BufferWriter._configure(); - }; - } -}); - -// node_modules/protobufjs/src/writer_buffer.js -var require_writer_buffer = __commonJS({ - "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = BufferWriter; - var Writer = require_writer(); - (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; - var util = require_minimal(); - function BufferWriter() { - Writer.call(this); - } - BufferWriter._configure = function() { - BufferWriter.alloc = util._Buffer_allocUnsafe; - BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { - buf.set(val, pos); - } : function writeBytesBuffer_copy(val, buf, pos) { - if (val.copy) - val.copy(buf, pos, 0, val.length); - else - for (var i2 = 0; i2 < val.length; ) - buf[pos++] = val[i2++]; - }; - }; - BufferWriter.prototype.bytes = function write_bytes_buffer(value) { - if (util.isString(value)) - value = util._Buffer_from(value, "base64"); - var len = value.length >>> 0; - this.uint32(len); - if (len) - this._push(BufferWriter.writeBytesBuffer, len, value); - return this; - }; - function writeStringBuffer(val, buf, pos) { - if (val.length < 40) - util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); - else - buf.write(val, pos); - } - BufferWriter.prototype.string = function write_string_buffer(value) { - var len = util.Buffer.byteLength(value); - this.uint32(len); - if (len) - this._push(writeStringBuffer, len, value); - return this; - }; - BufferWriter._configure(); - } -}); - -// node_modules/protobufjs/src/reader.js -var require_reader = __commonJS({ - "node_modules/protobufjs/src/reader.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Reader; - var util = require_minimal(); - var BufferReader; - var LongBits = util.LongBits; - var utf8 = util.utf8; - function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); - } - function Reader(buffer) { - this.buf = buffer; - this.pos = 0; - this.len = buffer.length; - } - var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - } : function create_array2(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - }; - var create2 = function create3() { - return util.Buffer ? function create_buffer_setup(buffer) { - return (Reader.create = function create_buffer(buffer2) { - return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); - })(buffer); - } : create_array; - }; - Reader.create = create2(); - Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ - util.Array.prototype.slice; - Reader.prototype.uint32 = /* @__PURE__ */ function read_uint32_setup() { - var value = 4294967295; - return function read_uint32() { - value = (this.buf[this.pos] & 127) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; - if (this.buf[this.pos++] < 128) - return value; - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; - }(); - Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; - }; - Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; - }; - function readLongVarint() { - var bits = new LongBits(0, 0); - var i2 = 0; - if (this.len - this.pos > 4) { - for (; i2 < 4; ++i2) { - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i2 = 0; - } else { - for (; i2 < 3; ++i2) { - if (this.pos >= this.len) - throw indexOutOfRange(this); - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i2 * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i2 * 7) >>> 0; - return bits; - } - if (this.len - this.pos > 4) { - for (; i2 < 5; ++i2) { - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } else { - for (; i2 < 5; ++i2) { - if (this.pos >= this.len) - throw indexOutOfRange(this); - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i2 * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } - throw Error("invalid varint encoding"); - } - Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; - }; - function readFixed32_end(buf, end) { - return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; - } - Reader.prototype.fixed32 = function read_fixed32() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - return readFixed32_end(this.buf, this.pos += 4); - }; - Reader.prototype.sfixed32 = function read_sfixed32() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - return readFixed32_end(this.buf, this.pos += 4) | 0; - }; - function readFixed64() { - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); - } - Reader.prototype.float = function read_float() { - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; - }; - Reader.prototype.double = function read_double() { - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; - }; - Reader.prototype.bytes = function read_bytes() { - var length2 = this.uint32(), start = this.pos, end = this.pos + length2; - if (end > this.len) - throw indexOutOfRange(this, length2); - this.pos += length2; - if (Array.isArray(this.buf)) - return this.buf.slice(start, end); - if (start === end) { - var nativeBuffer = util.Buffer; - return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); - } - return this._slice.call(this.buf, start, end); - }; - Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); - }; - Reader.prototype.skip = function skip(length2) { - if (typeof length2 === "number") { - if (this.pos + length2 > this.len) - throw indexOutOfRange(this, length2); - this.pos += length2; - } else { - do { - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); - } - return this; - }; - Reader.prototype.skipType = function(wireType) { - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - while ((wireType = this.uint32() & 7) !== 4) { - this.skipType(wireType); - } - break; - case 5: - this.skip(4); - break; - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; - }; - Reader._configure = function(BufferReader_) { - BufferReader = BufferReader_; - Reader.create = create2(); - BufferReader._configure(); - var fn = util.Long ? "toLong" : ( - /* istanbul ignore next */ - "toNumber" - ); - util.merge(Reader.prototype, { - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); - } - }); - }; - } -}); - -// node_modules/protobufjs/src/reader_buffer.js -var require_reader_buffer = __commonJS({ - "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = BufferReader; - var Reader = require_reader(); - (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; - var util = require_minimal(); - function BufferReader(buffer) { - Reader.call(this, buffer); - } - BufferReader._configure = function() { - if (util.Buffer) - BufferReader.prototype._slice = util.Buffer.prototype.slice; - }; - BufferReader.prototype.string = function read_string_buffer() { - var len = this.uint32(); - return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); - }; - BufferReader._configure(); - } -}); - -// node_modules/protobufjs/src/rpc/service.js -var require_service = __commonJS({ - "node_modules/protobufjs/src/rpc/service.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = Service; - var util = require_minimal(); - (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; - function Service(rpcImpl, requestDelimited, responseDelimited) { - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); - util.EventEmitter.call(this); - this.rpcImpl = rpcImpl; - this.requestDelimited = Boolean(requestDelimited); - this.responseDelimited = Boolean(responseDelimited); - } - Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { - if (!request) - throw TypeError("request must be specified"); - var self2 = this; - if (!callback) - return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request); - if (!self2.rpcImpl) { - setTimeout(function() { - callback(Error("already ended")); - }, 0); - return void 0; - } - try { - return self2.rpcImpl( - method, - requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), - function rpcCallback(err, response) { - if (err) { - self2.emit("error", err, method); - return callback(err); - } - if (response === null) { - self2.end( - /* endedByRPC */ - true - ); - return void 0; - } - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err2) { - self2.emit("error", err2, method); - return callback(err2); - } - } - self2.emit("data", response, method); - return callback(null, response); - } - ); - } catch (err) { - self2.emit("error", err, method); - setTimeout(function() { - callback(err); - }, 0); - return void 0; - } - }; - Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); - } - return this; - }; - } -}); - -// node_modules/protobufjs/src/rpc.js -var require_rpc = __commonJS({ - "node_modules/protobufjs/src/rpc.js"(exports2) { - "use strict"; - init_shim(); - var rpc = exports2; - rpc.Service = require_service(); - } -}); - -// node_modules/protobufjs/src/roots.js -var require_roots = __commonJS({ - "node_modules/protobufjs/src/roots.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = {}; - } -}); - -// node_modules/protobufjs/src/index-minimal.js -var require_index_minimal = __commonJS({ - "node_modules/protobufjs/src/index-minimal.js"(exports2) { - "use strict"; - init_shim(); - var protobuf = exports2; - protobuf.build = "minimal"; - protobuf.Writer = require_writer(); - protobuf.BufferWriter = require_writer_buffer(); - protobuf.Reader = require_reader(); - protobuf.BufferReader = require_reader_buffer(); - protobuf.util = require_minimal(); - protobuf.rpc = require_rpc(); - protobuf.roots = require_roots(); - protobuf.configure = configure; - function configure() { - protobuf.util._configure(); - protobuf.Writer._configure(protobuf.BufferWriter); - protobuf.Reader._configure(protobuf.BufferReader); - } - configure(); - } -}); - -// node_modules/protobufjs/minimal.js -var require_minimal2 = __commonJS({ - "node_modules/protobufjs/minimal.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = require_index_minimal(); - } -}); - -// node_modules/@multiversx/sdk-core/out/proto/compiled.js -var require_compiled = __commonJS({ - "node_modules/@multiversx/sdk-core/out/proto/compiled.js"(exports2, module2) { - "use strict"; - init_shim(); - (function(global2, factory) { - if (typeof define === "function" && define.amd) - define(["protobufjs/minimal"], factory); - else if (typeof __require === "function" && typeof module2 === "object" && module2 && module2.exports) - module2.exports = factory(require_minimal2()); - })(exports2, function($protobuf) { - "use strict"; - var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); - $root.proto = function() { - var proto = {}; - proto.Transaction = function() { - function Transaction4(properties) { - if (properties) { - for (var keys2 = Object.keys(properties), i2 = 0; i2 < keys2.length; ++i2) - if (properties[keys2[i2]] != null) - this[keys2[i2]] = properties[keys2[i2]]; - } - } - Transaction4.prototype.Nonce = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Transaction4.prototype.Value = $util.newBuffer([]); - Transaction4.prototype.RcvAddr = $util.newBuffer([]); - Transaction4.prototype.RcvUserName = $util.newBuffer([]); - Transaction4.prototype.SndAddr = $util.newBuffer([]); - Transaction4.prototype.SndUserName = $util.newBuffer([]); - Transaction4.prototype.GasPrice = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Transaction4.prototype.GasLimit = $util.Long ? $util.Long.fromBits(0, 0, true) : 0; - Transaction4.prototype.Data = $util.newBuffer([]); - Transaction4.prototype.ChainID = $util.newBuffer([]); - Transaction4.prototype.Version = 0; - Transaction4.prototype.Signature = $util.newBuffer([]); - Transaction4.prototype.Options = 0; - Transaction4.prototype.GuardianAddr = $util.newBuffer([]); - Transaction4.prototype.GuardianSignature = $util.newBuffer([]); - Transaction4.create = function create2(properties) { - return new Transaction4(properties); - }; - Transaction4.encode = function encode5(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.Nonce != null && Object.hasOwnProperty.call(message, "Nonce")) - writer.uint32( - /* id 1, wireType 0 =*/ - 8 - ).uint64(message.Nonce); - if (message.Value != null && Object.hasOwnProperty.call(message, "Value")) - writer.uint32( - /* id 2, wireType 2 =*/ - 18 - ).bytes(message.Value); - if (message.RcvAddr != null && Object.hasOwnProperty.call(message, "RcvAddr")) - writer.uint32( - /* id 3, wireType 2 =*/ - 26 - ).bytes(message.RcvAddr); - if (message.RcvUserName != null && Object.hasOwnProperty.call(message, "RcvUserName")) - writer.uint32( - /* id 4, wireType 2 =*/ - 34 - ).bytes(message.RcvUserName); - if (message.SndAddr != null && Object.hasOwnProperty.call(message, "SndAddr")) - writer.uint32( - /* id 5, wireType 2 =*/ - 42 - ).bytes(message.SndAddr); - if (message.SndUserName != null && Object.hasOwnProperty.call(message, "SndUserName")) - writer.uint32( - /* id 6, wireType 2 =*/ - 50 - ).bytes(message.SndUserName); - if (message.GasPrice != null && Object.hasOwnProperty.call(message, "GasPrice")) - writer.uint32( - /* id 7, wireType 0 =*/ - 56 - ).uint64(message.GasPrice); - if (message.GasLimit != null && Object.hasOwnProperty.call(message, "GasLimit")) - writer.uint32( - /* id 8, wireType 0 =*/ - 64 - ).uint64(message.GasLimit); - if (message.Data != null && Object.hasOwnProperty.call(message, "Data")) - writer.uint32( - /* id 9, wireType 2 =*/ - 74 - ).bytes(message.Data); - if (message.ChainID != null && Object.hasOwnProperty.call(message, "ChainID")) - writer.uint32( - /* id 10, wireType 2 =*/ - 82 - ).bytes(message.ChainID); - if (message.Version != null && Object.hasOwnProperty.call(message, "Version")) - writer.uint32( - /* id 11, wireType 0 =*/ - 88 - ).uint32(message.Version); - if (message.Signature != null && Object.hasOwnProperty.call(message, "Signature")) - writer.uint32( - /* id 12, wireType 2 =*/ - 98 - ).bytes(message.Signature); - if (message.Options != null && Object.hasOwnProperty.call(message, "Options")) - writer.uint32( - /* id 13, wireType 0 =*/ - 104 - ).uint32(message.Options); - if (message.GuardianAddr != null && Object.hasOwnProperty.call(message, "GuardianAddr")) - writer.uint32( - /* id 14, wireType 2 =*/ - 114 - ).bytes(message.GuardianAddr); - if (message.GuardianSignature != null && Object.hasOwnProperty.call(message, "GuardianSignature")) - writer.uint32( - /* id 15, wireType 2 =*/ - 122 - ).bytes(message.GuardianSignature); - return writer; - }; - Transaction4.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - Transaction4.decode = function decode6(reader, length2) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length2 === void 0 ? reader.len : reader.pos + length2, message = new $root.proto.Transaction(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.Nonce = reader.uint64(); - break; - } - case 2: { - message.Value = reader.bytes(); - break; - } - case 3: { - message.RcvAddr = reader.bytes(); - break; - } - case 4: { - message.RcvUserName = reader.bytes(); - break; - } - case 5: { - message.SndAddr = reader.bytes(); - break; - } - case 6: { - message.SndUserName = reader.bytes(); - break; - } - case 7: { - message.GasPrice = reader.uint64(); - break; - } - case 8: { - message.GasLimit = reader.uint64(); - break; - } - case 9: { - message.Data = reader.bytes(); - break; - } - case 10: { - message.ChainID = reader.bytes(); - break; - } - case 11: { - message.Version = reader.uint32(); - break; - } - case 12: { - message.Signature = reader.bytes(); - break; - } - case 13: { - message.Options = reader.uint32(); - break; - } - case 14: { - message.GuardianAddr = reader.bytes(); - break; - } - case 15: { - message.GuardianSignature = reader.bytes(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - Transaction4.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - Transaction4.verify = function verify2(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.Nonce != null && message.hasOwnProperty("Nonce")) { - if (!$util.isInteger(message.Nonce) && !(message.Nonce && $util.isInteger(message.Nonce.low) && $util.isInteger(message.Nonce.high))) - return "Nonce: integer|Long expected"; - } - if (message.Value != null && message.hasOwnProperty("Value")) { - if (!(message.Value && typeof message.Value.length === "number" || $util.isString(message.Value))) - return "Value: buffer expected"; - } - if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) { - if (!(message.RcvAddr && typeof message.RcvAddr.length === "number" || $util.isString(message.RcvAddr))) - return "RcvAddr: buffer expected"; - } - if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) { - if (!(message.RcvUserName && typeof message.RcvUserName.length === "number" || $util.isString(message.RcvUserName))) - return "RcvUserName: buffer expected"; - } - if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) { - if (!(message.SndAddr && typeof message.SndAddr.length === "number" || $util.isString(message.SndAddr))) - return "SndAddr: buffer expected"; - } - if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) { - if (!(message.SndUserName && typeof message.SndUserName.length === "number" || $util.isString(message.SndUserName))) - return "SndUserName: buffer expected"; - } - if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) { - if (!$util.isInteger(message.GasPrice) && !(message.GasPrice && $util.isInteger(message.GasPrice.low) && $util.isInteger(message.GasPrice.high))) - return "GasPrice: integer|Long expected"; - } - if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) { - if (!$util.isInteger(message.GasLimit) && !(message.GasLimit && $util.isInteger(message.GasLimit.low) && $util.isInteger(message.GasLimit.high))) - return "GasLimit: integer|Long expected"; - } - if (message.Data != null && message.hasOwnProperty("Data")) { - if (!(message.Data && typeof message.Data.length === "number" || $util.isString(message.Data))) - return "Data: buffer expected"; - } - if (message.ChainID != null && message.hasOwnProperty("ChainID")) { - if (!(message.ChainID && typeof message.ChainID.length === "number" || $util.isString(message.ChainID))) - return "ChainID: buffer expected"; - } - if (message.Version != null && message.hasOwnProperty("Version")) { - if (!$util.isInteger(message.Version)) - return "Version: integer expected"; - } - if (message.Signature != null && message.hasOwnProperty("Signature")) { - if (!(message.Signature && typeof message.Signature.length === "number" || $util.isString(message.Signature))) - return "Signature: buffer expected"; - } - if (message.Options != null && message.hasOwnProperty("Options")) { - if (!$util.isInteger(message.Options)) - return "Options: integer expected"; - } - if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) { - if (!(message.GuardianAddr && typeof message.GuardianAddr.length === "number" || $util.isString(message.GuardianAddr))) - return "GuardianAddr: buffer expected"; - } - if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) { - if (!(message.GuardianSignature && typeof message.GuardianSignature.length === "number" || $util.isString(message.GuardianSignature))) - return "GuardianSignature: buffer expected"; - } - return null; - }; - Transaction4.fromObject = function fromObject(object) { - if (object instanceof $root.proto.Transaction) - return object; - var message = new $root.proto.Transaction(); - if (object.Nonce != null) { - if ($util.Long) - (message.Nonce = $util.Long.fromValue(object.Nonce)).unsigned = true; - else if (typeof object.Nonce === "string") - message.Nonce = parseInt(object.Nonce, 10); - else if (typeof object.Nonce === "number") - message.Nonce = object.Nonce; - else if (typeof object.Nonce === "object") - message.Nonce = new $util.LongBits(object.Nonce.low >>> 0, object.Nonce.high >>> 0).toNumber(true); - } - if (object.Value != null) { - if (typeof object.Value === "string") - $util.base64.decode(object.Value, message.Value = $util.newBuffer($util.base64.length(object.Value)), 0); - else if (object.Value.length >= 0) - message.Value = object.Value; - } - if (object.RcvAddr != null) { - if (typeof object.RcvAddr === "string") - $util.base64.decode(object.RcvAddr, message.RcvAddr = $util.newBuffer($util.base64.length(object.RcvAddr)), 0); - else if (object.RcvAddr.length >= 0) - message.RcvAddr = object.RcvAddr; - } - if (object.RcvUserName != null) { - if (typeof object.RcvUserName === "string") - $util.base64.decode(object.RcvUserName, message.RcvUserName = $util.newBuffer($util.base64.length(object.RcvUserName)), 0); - else if (object.RcvUserName.length >= 0) - message.RcvUserName = object.RcvUserName; - } - if (object.SndAddr != null) { - if (typeof object.SndAddr === "string") - $util.base64.decode(object.SndAddr, message.SndAddr = $util.newBuffer($util.base64.length(object.SndAddr)), 0); - else if (object.SndAddr.length >= 0) - message.SndAddr = object.SndAddr; - } - if (object.SndUserName != null) { - if (typeof object.SndUserName === "string") - $util.base64.decode(object.SndUserName, message.SndUserName = $util.newBuffer($util.base64.length(object.SndUserName)), 0); - else if (object.SndUserName.length >= 0) - message.SndUserName = object.SndUserName; - } - if (object.GasPrice != null) { - if ($util.Long) - (message.GasPrice = $util.Long.fromValue(object.GasPrice)).unsigned = true; - else if (typeof object.GasPrice === "string") - message.GasPrice = parseInt(object.GasPrice, 10); - else if (typeof object.GasPrice === "number") - message.GasPrice = object.GasPrice; - else if (typeof object.GasPrice === "object") - message.GasPrice = new $util.LongBits(object.GasPrice.low >>> 0, object.GasPrice.high >>> 0).toNumber(true); - } - if (object.GasLimit != null) { - if ($util.Long) - (message.GasLimit = $util.Long.fromValue(object.GasLimit)).unsigned = true; - else if (typeof object.GasLimit === "string") - message.GasLimit = parseInt(object.GasLimit, 10); - else if (typeof object.GasLimit === "number") - message.GasLimit = object.GasLimit; - else if (typeof object.GasLimit === "object") - message.GasLimit = new $util.LongBits(object.GasLimit.low >>> 0, object.GasLimit.high >>> 0).toNumber(true); - } - if (object.Data != null) { - if (typeof object.Data === "string") - $util.base64.decode(object.Data, message.Data = $util.newBuffer($util.base64.length(object.Data)), 0); - else if (object.Data.length >= 0) - message.Data = object.Data; - } - if (object.ChainID != null) { - if (typeof object.ChainID === "string") - $util.base64.decode(object.ChainID, message.ChainID = $util.newBuffer($util.base64.length(object.ChainID)), 0); - else if (object.ChainID.length >= 0) - message.ChainID = object.ChainID; - } - if (object.Version != null) - message.Version = object.Version >>> 0; - if (object.Signature != null) { - if (typeof object.Signature === "string") - $util.base64.decode(object.Signature, message.Signature = $util.newBuffer($util.base64.length(object.Signature)), 0); - else if (object.Signature.length >= 0) - message.Signature = object.Signature; - } - if (object.Options != null) - message.Options = object.Options >>> 0; - if (object.GuardianAddr != null) { - if (typeof object.GuardianAddr === "string") - $util.base64.decode(object.GuardianAddr, message.GuardianAddr = $util.newBuffer($util.base64.length(object.GuardianAddr)), 0); - else if (object.GuardianAddr.length >= 0) - message.GuardianAddr = object.GuardianAddr; - } - if (object.GuardianSignature != null) { - if (typeof object.GuardianSignature === "string") - $util.base64.decode(object.GuardianSignature, message.GuardianSignature = $util.newBuffer($util.base64.length(object.GuardianSignature)), 0); - else if (object.GuardianSignature.length >= 0) - message.GuardianSignature = object.GuardianSignature; - } - return message; - }; - Transaction4.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.Nonce = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.Nonce = options.longs === String ? "0" : 0; - if (options.bytes === String) - object.Value = ""; - else { - object.Value = []; - if (options.bytes !== Array) - object.Value = $util.newBuffer(object.Value); - } - if (options.bytes === String) - object.RcvAddr = ""; - else { - object.RcvAddr = []; - if (options.bytes !== Array) - object.RcvAddr = $util.newBuffer(object.RcvAddr); - } - if (options.bytes === String) - object.RcvUserName = ""; - else { - object.RcvUserName = []; - if (options.bytes !== Array) - object.RcvUserName = $util.newBuffer(object.RcvUserName); - } - if (options.bytes === String) - object.SndAddr = ""; - else { - object.SndAddr = []; - if (options.bytes !== Array) - object.SndAddr = $util.newBuffer(object.SndAddr); - } - if (options.bytes === String) - object.SndUserName = ""; - else { - object.SndUserName = []; - if (options.bytes !== Array) - object.SndUserName = $util.newBuffer(object.SndUserName); - } - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.GasPrice = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.GasPrice = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.GasLimit = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.GasLimit = options.longs === String ? "0" : 0; - if (options.bytes === String) - object.Data = ""; - else { - object.Data = []; - if (options.bytes !== Array) - object.Data = $util.newBuffer(object.Data); - } - if (options.bytes === String) - object.ChainID = ""; - else { - object.ChainID = []; - if (options.bytes !== Array) - object.ChainID = $util.newBuffer(object.ChainID); - } - object.Version = 0; - if (options.bytes === String) - object.Signature = ""; - else { - object.Signature = []; - if (options.bytes !== Array) - object.Signature = $util.newBuffer(object.Signature); - } - object.Options = 0; - if (options.bytes === String) - object.GuardianAddr = ""; - else { - object.GuardianAddr = []; - if (options.bytes !== Array) - object.GuardianAddr = $util.newBuffer(object.GuardianAddr); - } - if (options.bytes === String) - object.GuardianSignature = ""; - else { - object.GuardianSignature = []; - if (options.bytes !== Array) - object.GuardianSignature = $util.newBuffer(object.GuardianSignature); - } - } - if (message.Nonce != null && message.hasOwnProperty("Nonce")) - if (typeof message.Nonce === "number") - object.Nonce = options.longs === String ? String(message.Nonce) : message.Nonce; - else - object.Nonce = options.longs === String ? $util.Long.prototype.toString.call(message.Nonce) : options.longs === Number ? new $util.LongBits(message.Nonce.low >>> 0, message.Nonce.high >>> 0).toNumber(true) : message.Nonce; - if (message.Value != null && message.hasOwnProperty("Value")) - object.Value = options.bytes === String ? $util.base64.encode(message.Value, 0, message.Value.length) : options.bytes === Array ? Array.prototype.slice.call(message.Value) : message.Value; - if (message.RcvAddr != null && message.hasOwnProperty("RcvAddr")) - object.RcvAddr = options.bytes === String ? $util.base64.encode(message.RcvAddr, 0, message.RcvAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvAddr) : message.RcvAddr; - if (message.RcvUserName != null && message.hasOwnProperty("RcvUserName")) - object.RcvUserName = options.bytes === String ? $util.base64.encode(message.RcvUserName, 0, message.RcvUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.RcvUserName) : message.RcvUserName; - if (message.SndAddr != null && message.hasOwnProperty("SndAddr")) - object.SndAddr = options.bytes === String ? $util.base64.encode(message.SndAddr, 0, message.SndAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndAddr) : message.SndAddr; - if (message.SndUserName != null && message.hasOwnProperty("SndUserName")) - object.SndUserName = options.bytes === String ? $util.base64.encode(message.SndUserName, 0, message.SndUserName.length) : options.bytes === Array ? Array.prototype.slice.call(message.SndUserName) : message.SndUserName; - if (message.GasPrice != null && message.hasOwnProperty("GasPrice")) - if (typeof message.GasPrice === "number") - object.GasPrice = options.longs === String ? String(message.GasPrice) : message.GasPrice; - else - object.GasPrice = options.longs === String ? $util.Long.prototype.toString.call(message.GasPrice) : options.longs === Number ? new $util.LongBits(message.GasPrice.low >>> 0, message.GasPrice.high >>> 0).toNumber(true) : message.GasPrice; - if (message.GasLimit != null && message.hasOwnProperty("GasLimit")) - if (typeof message.GasLimit === "number") - object.GasLimit = options.longs === String ? String(message.GasLimit) : message.GasLimit; - else - object.GasLimit = options.longs === String ? $util.Long.prototype.toString.call(message.GasLimit) : options.longs === Number ? new $util.LongBits(message.GasLimit.low >>> 0, message.GasLimit.high >>> 0).toNumber(true) : message.GasLimit; - if (message.Data != null && message.hasOwnProperty("Data")) - object.Data = options.bytes === String ? $util.base64.encode(message.Data, 0, message.Data.length) : options.bytes === Array ? Array.prototype.slice.call(message.Data) : message.Data; - if (message.ChainID != null && message.hasOwnProperty("ChainID")) - object.ChainID = options.bytes === String ? $util.base64.encode(message.ChainID, 0, message.ChainID.length) : options.bytes === Array ? Array.prototype.slice.call(message.ChainID) : message.ChainID; - if (message.Version != null && message.hasOwnProperty("Version")) - object.Version = message.Version; - if (message.Signature != null && message.hasOwnProperty("Signature")) - object.Signature = options.bytes === String ? $util.base64.encode(message.Signature, 0, message.Signature.length) : options.bytes === Array ? Array.prototype.slice.call(message.Signature) : message.Signature; - if (message.Options != null && message.hasOwnProperty("Options")) - object.Options = message.Options; - if (message.GuardianAddr != null && message.hasOwnProperty("GuardianAddr")) - object.GuardianAddr = options.bytes === String ? $util.base64.encode(message.GuardianAddr, 0, message.GuardianAddr.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianAddr) : message.GuardianAddr; - if (message.GuardianSignature != null && message.hasOwnProperty("GuardianSignature")) - object.GuardianSignature = options.bytes === String ? $util.base64.encode(message.GuardianSignature, 0, message.GuardianSignature.length) : options.bytes === Array ? Array.prototype.slice.call(message.GuardianSignature) : message.GuardianSignature; - return object; - }; - Transaction4.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - Transaction4.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === void 0) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/proto.Transaction"; - }; - return Transaction4; - }(); - return proto; - }(); - return $root; - }); - } -}); - -// node_modules/@multiversx/sdk-core/out/proto/serializer.js -var require_serializer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/proto/serializer.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ProtoSerializer = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber()); - var address_1 = require_address(); - var constants_1 = require_constants(); - var errors = __importStar2(require_errors()); - var utils_1 = require_utils(); - var ProtoSerializer = class { - /** - * Serializes a Transaction object to a Buffer. Handles low-level conversion logic and field-mappings as well. - */ - serializeTransaction(transaction) { - const proto = require_compiled().proto; - const receiverPubkey = new address_1.Address(transaction.getReceiver().bech32()).pubkey(); - const senderPubkey = new address_1.Address(transaction.getSender().bech32()).pubkey(); - let protoTransaction = new proto.Transaction({ - // mx-chain-go's serializer handles nonce == 0 differently, thus we treat 0 as "undefined". - Nonce: transaction.getNonce().valueOf() ? transaction.getNonce().valueOf() : void 0, - Value: this.serializeTransactionValue(transaction.getValue()), - RcvAddr: receiverPubkey, - RcvUserName: transaction.getReceiverUsername() ? import_buffer.Buffer.from(transaction.getReceiverUsername()).toString("base64") : void 0, - SndAddr: senderPubkey, - SndUserName: transaction.getSenderUsername() ? import_buffer.Buffer.from(transaction.getSenderUsername()).toString("base64") : void 0, - GasPrice: transaction.getGasPrice().valueOf(), - GasLimit: transaction.getGasLimit().valueOf(), - Data: transaction.getData().length() == 0 ? null : transaction.getData().valueOf(), - ChainID: import_buffer.Buffer.from(transaction.getChainID().valueOf()), - Version: transaction.getVersion().valueOf(), - Signature: transaction.getSignature() - }); - if (transaction.getOptions().valueOf() !== constants_1.TRANSACTION_OPTIONS_DEFAULT) { - protoTransaction.Options = transaction.getOptions().valueOf(); - } - if (transaction.isGuardedTransaction()) { - const guardianAddress = transaction.getGuardian(); - protoTransaction.GuardianAddr = new address_1.Address(guardianAddress.bech32()).pubkey(); - protoTransaction.GuardianSignature = transaction.getGuardianSignature(); - } - const encoded = proto.Transaction.encode(protoTransaction).finish(); - const buffer = import_buffer.Buffer.from(encoded); - return buffer; - } - /** - * Custom serialization, compatible with mx-chain-go. - */ - serializeTransactionValue(transactionValue) { - let value = new bignumber_js_1.default(transactionValue.toString()); - if (value.isZero()) { - return import_buffer.Buffer.from([0, 0]); - } - let buffer = utils_1.bigIntToBuffer(value); - buffer = import_buffer.Buffer.concat([import_buffer.Buffer.from([0]), buffer]); - return buffer; - } - deserializeTransaction(_buffer) { - throw new errors.ErrUnsupportedOperation("deserializeTransaction"); - } - }; - exports2.ProtoSerializer = ProtoSerializer; - } -}); - -// node_modules/@multiversx/sdk-core/out/proto/index.js -var require_proto = __commonJS({ - "node_modules/@multiversx/sdk-core/out/proto/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_serializer(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionComputer.js -var require_transactionComputer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionComputer.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionComputer = void 0; - var errors = __importStar2(require_errors()); - var bignumber_js_1 = __importDefault2(require_bignumber()); - var proto_1 = require_proto(); - var transaction_1 = require_transaction(); - var constants_1 = require_constants(); - var createTransactionHasher = require_blake2b2(); - var createKeccakHash = require_js(); - var TRANSACTION_HASH_LENGTH = 32; - var TransactionComputer2 = class { - constructor() { - } - computeTransactionFee(transaction, networkConfig2) { - const moveBalanceGas = BigInt(networkConfig2.MinGasLimit + transaction.data.length * networkConfig2.GasPerDataByte); - if (moveBalanceGas > transaction.gasLimit) { - throw new errors.ErrNotEnoughGas(parseInt(transaction.gasLimit.toString(), 10)); - } - const gasPrice = transaction.gasPrice; - const feeForMove = moveBalanceGas * gasPrice; - if (moveBalanceGas === transaction.gasLimit) { - return feeForMove; - } - const diff = transaction.gasLimit - moveBalanceGas; - const modifiedGasPrice = BigInt(new bignumber_js_1.default(gasPrice.toString()).multipliedBy(new bignumber_js_1.default(networkConfig2.GasPriceModifier)).toFixed(0)); - const processingFee = diff * modifiedGasPrice; - return feeForMove + processingFee; - } - computeBytesForSigning(transaction) { - this.ensureValidTransactionFields(transaction); - const plainTransaction = this.toPlainObjectForSigning(transaction); - const serialized = JSON.stringify(plainTransaction); - return new Uint8Array(import_buffer.Buffer.from(serialized)); - } - computeBytesForVerifying(transaction) { - const isTxSignedByHash = this.hasOptionsSetForHashSigning(transaction); - if (isTxSignedByHash) { - return this.computeHashForSigning(transaction); - } - return this.computeBytesForSigning(transaction); - } - computeHashForSigning(transaction) { - const plainTransaction = this.toPlainObjectForSigning(transaction); - const signable = import_buffer.Buffer.from(JSON.stringify(plainTransaction)); - return createKeccakHash("keccak256").update(signable).digest(); - } - computeTransactionHash(transaction) { - const serializer = new proto_1.ProtoSerializer(); - const buffer = serializer.serializeTransaction(new transaction_1.Transaction(transaction)); - const hash = createTransactionHasher(TRANSACTION_HASH_LENGTH).update(buffer).digest("hex"); - return import_buffer.Buffer.from(hash, "hex"); - } - hasOptionsSetForGuardedTransaction(transaction) { - return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_GUARDED) == constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - } - hasOptionsSetForHashSigning(transaction) { - return (transaction.options & constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN) == constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - applyGuardian(transaction, guardian) { - if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { - transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; - } - transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_GUARDED; - transaction.guardian = guardian; - } - applyOptionsForHashSigning(transaction) { - if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { - transaction.version = constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS; - } - transaction.options = transaction.options | constants_1.TRANSACTION_OPTIONS_TX_HASH_SIGN; - } - toPlainObjectForSigning(transaction) { - return { - nonce: Number(transaction.nonce), - value: transaction.value.toString(), - receiver: transaction.receiver, - sender: transaction.sender, - senderUsername: this.toBase64OrUndefined(transaction.senderUsername), - receiverUsername: this.toBase64OrUndefined(transaction.receiverUsername), - gasPrice: Number(transaction.gasPrice), - gasLimit: Number(transaction.gasLimit), - data: this.toBase64OrUndefined(transaction.data), - chainID: transaction.chainID, - version: transaction.version, - options: transaction.options ? transaction.options : void 0, - guardian: transaction.guardian ? transaction.guardian : void 0 - }; - } - toBase64OrUndefined(value) { - return value && value.length ? import_buffer.Buffer.from(value).toString("base64") : void 0; - } - ensureValidTransactionFields(transaction) { - if (transaction.sender.length !== constants_1.BECH32_ADDRESS_LENGTH) { - throw new errors.ErrBadUsage("Invalid `sender` field. Should be the bech32 address of the sender."); - } - if (transaction.receiver.length !== constants_1.BECH32_ADDRESS_LENGTH) { - throw new errors.ErrBadUsage("Invalid `receiver` field. Should be the bech32 address of the receiver."); - } - if (!transaction.chainID.length) { - throw new errors.ErrBadUsage("The `chainID` field is not set"); - } - if (transaction.version < constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS) { - if (this.hasOptionsSetForGuardedTransaction(transaction) || this.hasOptionsSetForHashSigning(transaction)) { - throw new errors.ErrBadUsage(`Non-empty transaction options requires transaction version >= ${constants_1.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`); - } - } - } - }; - exports2.TransactionComputer = TransactionComputer2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transaction.js -var require_transaction = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transaction.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionHash = exports2.Transaction = void 0; - var bignumber_js_1 = require_bignumber(); - var address_1 = require_address(); - var constants_1 = require_constants(); - var transactionsConverter_1 = require_transactionsConverter(); - var hash_1 = require_hash(); - var networkParams_1 = require_networkParams(); - var signature_1 = require_signature(); - var transactionPayload_1 = require_transactionPayload(); - var transactionComputer_1 = require_transactionComputer(); - var Transaction4 = class { - /** - * Creates a new Transaction object. - */ - constructor(options) { - this.nonce = BigInt(options.nonce?.valueOf() || 0n); - this.value = options.value ? BigInt(new bignumber_js_1.BigNumber(options.value.toString()).toFixed(0)) : 0n; - this.sender = this.addressAsBech32(options.sender); - this.receiver = this.addressAsBech32(options.receiver); - this.senderUsername = options.senderUsername || ""; - this.receiverUsername = options.receiverUsername || ""; - this.gasPrice = BigInt(options.gasPrice?.valueOf() || constants_1.TRANSACTION_MIN_GAS_PRICE); - this.gasLimit = BigInt(options.gasLimit.valueOf()); - this.data = options.data?.valueOf() || new Uint8Array(); - this.chainID = options.chainID.valueOf(); - this.version = Number(options.version?.valueOf() || constants_1.TRANSACTION_VERSION_DEFAULT); - this.options = Number(options.options?.valueOf() || constants_1.TRANSACTION_OPTIONS_DEFAULT); - this.guardian = options.guardian ? this.addressAsBech32(options.guardian) : ""; - this.signature = options.signature || import_buffer.Buffer.from([]); - this.guardianSignature = options.guardianSignature || import_buffer.Buffer.from([]); - } - addressAsBech32(address) { - return typeof address === "string" ? address : address.bech32(); - } - /** - * Legacy method, use the "nonce" property instead. - */ - getNonce() { - return Number(this.nonce); - } - /** - * Legacy method, use the "nonce" property instead. - * Sets the account sequence number of the sender. Must be done prior signing. - */ - setNonce(nonce) { - this.nonce = BigInt(nonce.valueOf()); - } - /** - * Legacy method, use the "value" property instead. - */ - getValue() { - return this.value; - } - /** - * Legacy method, use the "value" property instead. - */ - setValue(value) { - this.value = BigInt(value.toString()); - } - /** - * Legacy method, use the "sender" property instead. - */ - getSender() { - return address_1.Address.fromBech32(this.sender); - } - /** - * Legacy method, use the "sender" property instead. - */ - setSender(sender) { - this.sender = typeof sender === "string" ? sender : sender.bech32(); - } - /** - * Legacy method, use the "receiver" property instead. - */ - getReceiver() { - return address_1.Address.fromBech32(this.receiver); - } - /** - * Legacy method, use the "senderUsername" property instead. - */ - getSenderUsername() { - return this.senderUsername; - } - /** - * Legacy method, use the "senderUsername" property instead. - */ - setSenderUsername(senderUsername) { - this.senderUsername = senderUsername; - } - /** - * Legacy method, use the "receiverUsername" property instead. - */ - getReceiverUsername() { - return this.receiverUsername; - } - /** - * Legacy method, use the "receiverUsername" property instead. - */ - setReceiverUsername(receiverUsername) { - this.receiverUsername = receiverUsername; - } - /** - * Legacy method, use the "guardian" property instead. - */ - getGuardian() { - return new address_1.Address(this.guardian); - } - /** - * Legacy method, use the "gasPrice" property instead. - */ - getGasPrice() { - return Number(this.gasPrice); - } - /** - * Legacy method, use the "gasPrice" property instead. - */ - setGasPrice(gasPrice) { - this.gasPrice = BigInt(gasPrice.valueOf()); - } - /** - * Legacy method, use the "gasLimit" property instead. - */ - getGasLimit() { - return Number(this.gasLimit); - } - /** - * Legacy method, use the "gasLimit" property instead. - */ - setGasLimit(gasLimit) { - this.gasLimit = BigInt(gasLimit.valueOf()); - } - /** - * Legacy method, use the "data" property instead. - */ - getData() { - return new transactionPayload_1.TransactionPayload(import_buffer.Buffer.from(this.data)); - } - /** - * Legacy method, use the "chainID" property instead. - */ - getChainID() { - return this.chainID; - } - /** - * Legacy method, use the "chainID" property instead. - */ - setChainID(chainID) { - this.chainID = chainID.valueOf(); - } - /** - * Legacy method, use the "version" property instead. - */ - getVersion() { - return new networkParams_1.TransactionVersion(this.version); - } - /** - * Legacy method, use the "version" property instead. - */ - setVersion(version2) { - this.version = version2.valueOf(); - } - /** - * Legacy method, use the "options" property instead. - */ - getOptions() { - return new networkParams_1.TransactionOptions(this.options.valueOf()); - } - /** - * Legacy method, use the "options" property instead. - * - * Question for review: check how the options are set by sdk-dapp, wallet, ledger, extension. - */ - setOptions(options) { - this.options = options.valueOf(); - } - /** - * Legacy method, use the "signature" property instead. - */ - getSignature() { - return import_buffer.Buffer.from(this.signature); - } - /** - * Legacy method, use the "guardianSignature" property instead. - */ - getGuardianSignature() { - return import_buffer.Buffer.from(this.guardianSignature); - } - /** - * Legacy method, use the "guardian" property instead. - */ - setGuardian(guardian) { - this.guardian = typeof guardian === "string" ? guardian : guardian.bech32(); - } - /** - * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. - */ - getHash() { - return TransactionHash.compute(this); - } - /** - * Legacy method, use "TransactionComputer.computeBytesForSigning()" instead. - * Serializes a transaction to a sequence of bytes, ready to be signed. - * This function is called internally by signers. - */ - serializeForSigning() { - const computer = new transactionComputer_1.TransactionComputer(); - const bytes = computer.computeBytesForSigning(this); - return import_buffer.Buffer.from(bytes); - } - /** - * Checks the integrity of the guarded transaction - */ - isGuardedTransaction() { - const hasGuardian = this.guardian.length > 0; - const hasGuardianSignature = this.guardianSignature.length > 0; - return this.getOptions().isWithGuardian() && hasGuardian && hasGuardianSignature; - } - /** - * Legacy method, use "TransactionsConverter.transactionToPlainObject()" instead. - * - * Converts the transaction object into a ready-to-serialize, plain JavaScript object. - * This function is called internally within the signing procedure. - */ - toPlainObject() { - const converter = new transactionsConverter_1.TransactionsConverter(); - return converter.transactionToPlainObject(this); - } - /** - * Legacy method, use "TransactionsConverter.plainObjectToTransaction()" instead. - * Converts a plain object transaction into a Transaction Object. - * - * @param plainObjectTransaction Raw data of a transaction, usually obtained by calling toPlainObject() - */ - static fromPlainObject(plainObjectTransaction) { - const converter = new transactionsConverter_1.TransactionsConverter(); - return converter.plainObjectToTransaction(plainObjectTransaction); - } - /** - * Legacy method, use the "signature" property instead. - * Applies the signature on the transaction. - * - * @param signature The signature, as computed by a signer. - */ - applySignature(signature) { - this.signature = signature_1.interpretSignatureAsBuffer(signature); - } - /** - * Legacy method, use the "guardianSignature" property instead. - * Applies the guardian signature on the transaction. - * - * @param guardianSignature The signature, as computed by a signer. - */ - applyGuardianSignature(guardianSignature) { - this.guardianSignature = signature_1.interpretSignatureAsBuffer(guardianSignature); - } - /** - * Converts a transaction to a ready-to-broadcast object. - * Called internally by the network provider. - */ - toSendable() { - return this.toPlainObject(); - } - /** - * Legacy method, use "TransactionComputer.computeTransactionFee()" instead. - * - * Computes the current transaction fee based on the {@link NetworkConfig} and transaction properties - * @param networkConfig {@link NetworkConfig} - */ - computeFee(networkConfig2) { - const computer = new transactionComputer_1.TransactionComputer(); - const fee = computer.computeTransactionFee(this, networkConfig2); - return new bignumber_js_1.BigNumber(fee.toString()); - } - }; - exports2.Transaction = Transaction4; - var TransactionHash = class _TransactionHash extends hash_1.Hash { - constructor(hash) { - super(hash); - } - /** - * Legacy method, use "TransactionComputer.computeTransactionHash()" instead. - * Computes the hash of a transaction. - */ - static compute(transaction) { - const computer = new transactionComputer_1.TransactionComputer(); - const hash = computer.computeTransactionHash(transaction); - return new _TransactionHash(import_buffer.Buffer.from(hash).toString("hex")); - } - }; - exports2.TransactionHash = TransactionHash; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js -var require_tokenOperationsFactory = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactory.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenOperationsFactory = void 0; - var constants_1 = require_constants(); - var logger_1 = require_logger(); - var networkParams_1 = require_networkParams(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var codec_1 = require_codec(); - var TokenOperationsFactory2 = class { - constructor(config) { - this.config = config; - this.trueAsHex = codec_1.utf8ToHex("true"); - this.falseAsHex = codec_1.utf8ToHex("false"); - } - issueFungible(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "issue", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.bigIntToHex(args.initialSupply), - codec_1.bigIntToHex(args.numDecimals), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - notifyAboutUnsettingBurnRoleGlobally() { - logger_1.Logger.info(` +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}boolToString(e){return e?this.trueAsString:this.falseAsString}};u0.TokenManagementTransactionsFactory=gE});var mE=B(c0=>{"use strict";h();Object.defineProperty(c0,"__esModule",{value:!0});c0.TransactionsFactoryConfig=void 0;var XK=hr(),pE=class{constructor(e){this.chainID=e.chainID,this.addressHrp=XK.DEFAULT_HRP,this.minGasLimit=50000n,this.gasLimitPerByte=1500n,this.gasLimitIssue=60000000n,this.gasLimitToggleBurnRoleGlobally=60000000n,this.gasLimitEsdtLocalMint=300000n,this.gasLimitEsdtLocalBurn=300000n,this.gasLimitSetSpecialRole=60000000n,this.gasLimitPausing=60000000n,this.gasLimitFreezing=60000000n,this.gasLimitWiping=60000000n,this.gasLimitEsdtNftCreate=3000000n,this.gasLimitEsdtNftUpdateAttributes=1000000n,this.gasLimitEsdtNftAddQuantity=1000000n,this.gasLimitEsdtNftBurn=1000000n,this.gasLimitStorePerByte=10000n,this.issueCost=50000000000000000n,this.gasLimitStake=5000000n,this.gasLimitUnstake=5000000n,this.gasLimitUnbond=5000000n,this.gasLimitCreateDelegationContract=50000000n,this.gasLimitDelegationOperations=1000000n,this.additionalGasLimitPerValidatorNode=6000000n,this.additionalGasLimitForDelegationOperations=10000000n,this.gasLimitSaveKeyValue=100000n,this.gasLimitPersistPerByte=1000n,this.gasLimitSetGuardian=250000n,this.gasLimitGuardAccount=250000n,this.gasLimitUnguardAccount=250000n,this.gasLimitESDTTransfer=200000n,this.gasLimitESDTNFTTransfer=200000n,this.gasLimitMultiESDTNFTTransfer=200000n,this.gasLimitClaimDeveloperRewards=6000000n,this.gasLimitChangeOwnerAddress=6000000n}};c0.TransactionsFactoryConfig=pE});var UO=B(l0=>{"use strict";h();Object.defineProperty(l0,"__esModule",{value:!0});l0.TransferTransactionsFactory=void 0;var bo=Ie(),en=qn(),ZK=Ca(),Kf=Xr(),yE=Ms(),eW=fE(),LO=gc(),tW=1e5,FO=8e5,wE=class{constructor(e){this.isGasEstimator(e)?this.gasEstimator=e:(this.config=e.config,this.tokenComputer=new ZK.TokenComputer,this.tokenTransfersDataBuilder=new eW.TokenTransfersDataBuilder)}isGasEstimator(e){return typeof e=="object"&&typeof e.forEGLDTransfer=="function"&&typeof e.forESDTTransfer=="function"&&typeof e.forESDTNFTTransfer=="function"&&typeof e.forMultiESDTNFTTransfer=="function"}isGasEstimatorDefined(){return this.gasEstimator!==void 0}ensureMembersAreDefined(){if(this.config===void 0)throw new bo.Err("'config' is not defined");if(this.tokenTransfersDataBuilder===void 0)throw new bo.Err("`dataArgsBuilder is not defined`");if(this.tokenComputer===void 0)throw new bo.Err("`tokenComputer is not defined`")}createTransactionForNativeTokenTransfer(e){this.ensureMembersAreDefined();let r=e.data||new Uint8Array;return new Kf.Transaction({sender:e.sender.bech32(),receiver:e.receiver.bech32(),chainID:this.config.chainID,gasLimit:this.computeGasForMoveBalance(this.config,r),data:r,value:e.nativeAmount})}createTransactionForESDTTokenTransfer(e){this.ensureMembersAreDefined();let r=e.tokenTransfers.length;if(r===0)throw new bo.ErrBadUsage("No token transfer has been provided");if(r===1)return this.createSingleESDTTransferTransaction(e);let n=this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(e.receiver,e.tokenTransfers),i=this.config.gasLimitMultiESDTNFTTransfer*BigInt(r)+BigInt(FO);return new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:n,gasLimit:i,addDataMovementGas:!0}).build()}createEGLDTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.");let r=e.data?.length()||0,n=this.gasEstimator.forEGLDTransfer(r);return new Kf.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||n,data:e.data,chainID:e.chainID})}createESDTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.U64Value(e.tokenTransfer.nonce),new en.BigUIntValue(e.tokenTransfer.valueOf()),new en.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let r=[new en.AddressValue(e.destination),new en.U16Value(e.tokenTransfers.length)];for(let a of e.tokenTransfers)r.push(en.BytesValue.fromUTF8(a.tokenIdentifier),new en.U64Value(a.nonce),new en.BigUIntValue(a.valueOf()));let{argumentsString:n}=new en.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new yE.TransactionPayload(i),o=s.length()||0,u=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||u,data:s,chainID:e.chainID})}createSingleESDTTransferTransaction(e){this.ensureMembersAreDefined();let r=[],n=e.tokenTransfers[0],i=0n,s=e.receiver;return this.tokenComputer.isFungible(n.token)?(r=this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(n),i=this.config.gasLimitESDTTransfer+BigInt(tW)):(r=this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(n,s),i=this.config.gasLimitESDTNFTTransfer+BigInt(FO),s=e.sender),new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:s,dataParts:r,gasLimit:i,addDataMovementGas:!0}).build()}computeGasForMoveBalance(e,r){return e.minGasLimit+e.gasLimitPerByte*BigInt(r.length)}};l0.TransferTransactionsFactory=wE});var qO=B(h0=>{"use strict";h();Object.defineProperty(h0,"__esModule",{value:!0});h0.AccountTransactionsFactory=void 0;var rW=Ve(),f0=gc(),vE=class{constructor(e){this.config=e.config}createTransactionForSavingKeyValue(e){let r="SaveKeyValue",n=this.computeDataPartsForSavingKeyValue(e.keyValuePairs),i=[r,...n],s=this.computeExtraGasForSavingKeyValue(e.keyValuePairs);return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:i,gasLimit:s,addDataMovementGas:!0}).build()}computeExtraGasForSavingKeyValue(e){let r=0n;return e.forEach((n,i)=>{r+=this.config.gasLimitPersistPerByte*BigInt(i.length+n.length)+this.config.gasLimitStorePerByte*BigInt(n.length)}),r+this.config.gasLimitSaveKeyValue}computeDataPartsForSavingKeyValue(e){let r=[];return e.forEach((n,i)=>{r.push(p.Buffer.from(i).toString("hex"),p.Buffer.from(n).toString("hex"))}),r}createTransactionForSettingGuardian(e){let r=["SetGuardian",rW.Address.fromBech32(e.guardianAddress.bech32()).toHex(),p.Buffer.from(e.serviceID).toString("hex")];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitSetGuardian,addDataMovementGas:!0}).build()}createTransactionForGuardingAccount(e){let r=["GuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitGuardAccount,addDataMovementGas:!0}).build()}createTransactionForUnguardingAccount(e){let r=["UnGuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitUnguardAccount,addDataMovementGas:!0}).build()}};h0.AccountTransactionsFactory=vE});var d0=B(hn=>{"use strict";h();var nW=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Va=hn&&hn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&nW(e,t,r)};Object.defineProperty(hn,"__esModule",{value:!0});Va(AO(),hn);Va(OO(),hn);Va(dE(),hn);Va(MO(),hn);Va(mE(),hn);Va(UO(),hn);Va(qO(),hn)});var bE=B(Vn=>{"use strict";h();var iW=Vn&&Vn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sW=Vn&&Vn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oW=Vn&&Vn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iW(e,t,r);return sW(e,t),e},aW=Vn&&Vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.InteractionChecker=void 0;var AE=oW(Ie()),uW=aW((rr(),_e(fr))),EE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new uW.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new AE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new AE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let u=0;u{"use strict";h();Object.defineProperty(g0,"__esModule",{value:!0});g0.Query=void 0;var cW=Ve(),lW=fc(),SE=class{constructor(e){this.caller=e.caller||cW.Address.empty(),this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new lW.ArgSerializer().valuesToStrings(this.args)}};g0.Query=SE});var _E=B(p0=>{"use strict";h();Object.defineProperty(p0,"__esModule",{value:!0});p0.Interaction=void 0;var VO=Ve(),fW=rE(),hW=hr(),IE=Ca(),kO=d0(),dW=bE(),gW=Wf(),TE=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=VO.Address.empty(),this.sender=VO.Address.empty(),this.version=hW.TRANSACTION_VERSION_DEFAULT,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=[]}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){fW.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=new kO.TransactionsFactoryConfig({chainID:this.chainID.valueOf()}),n=new kO.SmartContractTransactionsFactory({config:e}).createTransactionForExecute({sender:this.sender,contract:this.contract.getAddress(),function:this.function.valueOf(),gasLimit:BigInt(this.gasLimit.valueOf()),arguments:this.args,nativeTransferAmount:BigInt(this.value.toString()),tokenTransfers:this.tokenTransfers});return n.chainID=this.chainID.valueOf(),n.nonce=BigInt(this.nonce.valueOf()),n.version=this.version,this.gasPrice&&(n.gasPrice=BigInt(this.gasPrice.valueOf())),n}buildQuery(){return new gW.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withSingleESDTNFTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withMultiESDTNFTTransfer(e){return this.tokenTransfers=e.map(r=>new IE.TokenTransfer(r)),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withVersion(e){return this.version=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new dW.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};p0.Interaction=TE});var CE=B(HO=>{"use strict";h();Object.defineProperty(HO,"__esModule",{value:!0})});var QO=B(yc=>{"use strict";h();Object.defineProperty(yc,"__esModule",{value:!0});yc.bech32m=yc.bech32=void 0;var m0="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jO={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function GO(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=mc(e)^n>>5}e=mc(e);for(let r=0;r=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<a)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=GO(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=mc(c)^w,f+=m0.charAt(w)}for(let d=0;d<6;++d)c=mc(c);c^=e;for(let d=0;d<6;++d){let w=c>>(5-d)*5&31;f+=m0.charAt(w)}return f}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";let a=o.toLowerCase(),c=o.toUpperCase();if(o!==a&&o!==c)return"Mixed-case string "+o;o=a;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),w=o.slice(f+1);if(w.length<6)return"Data too short";let A=GO(d);if(typeof A=="string")return A;let T=[];for(let x=0;x=w.length)&&T.push(V)}return A!==e?"Invalid checksum for "+o:{prefix:d,words:T}}function i(o,u){let a=n(o,u);if(typeof a=="object")return a}function s(o,u){let a=n(o,u);if(typeof a=="object")return a;throw new Error(a)}return{decodeUnsafe:i,decode:s,encode:r,toWords:pW,fromWordsUnsafe:mW,fromWords:yW}}yc.bech32=zO("bech32");yc.bech32m=zO("bech32m")});var WO=B(kn=>{"use strict";h();Object.defineProperty(kn,"__esModule",{value:!0});kn.TokenTransferProperties=kn.TransactionMetadataTransfer=kn.TransactionMetadata=kn.TransactionToDecode=kn.TransactionDecoder=void 0;var KO=QO(),xE=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new ka;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new y0;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new ka;s.transfers||(s.transfers=[]);let o=2;for(let u=0;uo&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),u=new ka;return u.sender=e.sender,u.receiver=o,u.value=s,r.length>4&&(u.functionName=this.hexToString(r[4]),u.functionArgs=r.slice(5)),u.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],u}base64Encode(e){return p.Buffer.from(e).toString("base64")}base64Decode(e){return p.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new ka;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=p.Buffer.from(e,"hex"),n=KO.bech32.toWords(r);return KO.bech32.encode("erd",n)}isAddressValid(e){return p.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return p.Buffer.from(e,"base64").toString("hex")}hexToString(e){return p.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};kn.TransactionDecoder=xE;var y0=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};kn.TransactionToDecode=y0;var ka=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};kn.TransactionMetadata=ka;var OE=class{constructor(){this.value=BigInt(0)}};kn.TransactionMetadataTransfer=OE;var DE=class{};kn.TokenTransferProperties=DE});var PE=B(w0=>{"use strict";h();Object.defineProperty(w0,"__esModule",{value:!0});w0.ReturnCode=void 0;var mt=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};w0.ReturnCode=mt;mt.None=new mt("");mt.Ok=new mt("ok");mt.FunctionNotFound=new mt("function not found");mt.FunctionWrongSignature=new mt("wrong signature for function");mt.ContractNotFound=new mt("contract not found");mt.UserError=new mt("user error");mt.OutOfGas=new mt("out of gas");mt.AccountCollision=new mt("account collision");mt.OutOfFunds=new mt("out of funds");mt.CallStackOverFlow=new mt("call stack overflow");mt.ContractInvalid=new mt("contract invalid");mt.ExecutionFailed=new mt("execution failed");mt.Unknown=new mt("unknown")});var JO=B(v0=>{"use strict";h();Object.defineProperty(v0,"__esModule",{value:!0});v0.ResultsParser=void 0;var wW=WO(),$O=Ve(),YO=Ie(),So=oo(),vW=fc(),wc=PE(),vc;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(vc||(vc={}));var RE;(function(t){t.TooMuchGas="@too much gas provided for processing"})(RE||(RE={}));var AW={argsSerializer:new vW.ArgSerializer},BE=class{constructor(e){e={...AW,...e},this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e);return this.parseOutcomeFromUntypedBundle(n,r)}parseOutcomeFromUntypedBundle(e,r){let n=this.argsSerializer.buffersToValues(e.values,r.output);return{returnCode:e.returnCode,returnMessage:e.returnMessage,values:n,firstValue:n[0],secondValue:n[1],thirdValue:n[2],lastValue:n[n.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return So.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return So.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return So.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return So.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new YO.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new wW.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:wc.ReturnCode.None,returnMessage:wc.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:wc.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(vc.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(vc.OnWriteLog,u=>u.findFirstOrNoneTopic(a=>a.toString().startsWith(RE.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new $O.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(vc.OnWriteLog,a=>a.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),u=s.toString();return{returnCode:s,returnMessage:u,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new $O.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(vc.OnWriteLog,o=>{let u=o.address.bech32()==e.sender.bech32(),a=o.topics[0]?.hex()==n.hex();return u&&a});if(s){let{returnCode:o,returnDataParts:u}=this.sliceDataFieldInParts(s.data),a=o.toString();return{returnCode:o,returnMessage:a,values:u}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||p.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new YO.ErrCannotParseContractResults("no return code");return{returnCode:wc.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){let n=e.topics.map(o=>p.Buffer.from(o.valueOf())).slice(1),i=e.dataPayload?.valueOf()||p.Buffer.from([]),s=e.additionalData?.map(o=>p.Buffer.from(o.valueOf()))||[];return s.length===0&&i.length&&s.push(p.Buffer.from(i)),this.doParseEvent({topics:n,dataItems:s,eventDefinition:r})}doParseEvent(e){let r={},n=e.eventDefinition.inputs.filter(u=>u.indexed),i=this.argsSerializer.buffersToValues(e.topics,n);for(let u=0;u!u.indexed),o=this.argsSerializer.buffersToValues(e.dataItems,s);for(let u=0;u{"use strict";h();Object.defineProperty(E0,"__esModule",{value:!0});E0.SmartContract=void 0;var A0=Ve(),ME=rE(),LE=hr(),EW=Ie(),FE=dE(),UE=mE(),bW=Rn(),XO=XA(),ZO=eE(),eD=_E(),SW=n0(),IW=Wf(),qE=class{constructor(e={}){this.address=A0.Address.empty(),this.methodsExplicit={},this.methods={},this.address=e.address||A0.Address.empty(),this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new ZO.ContractFunction(i);return new eD.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new ZO.ContractFunction(i),u=SW.NativeSerializer.nativeToTypedValues(s||[],n);return new eD.Interaction(e,o,u||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return bW.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()");let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=p.Buffer.from(r.toString(),"hex"),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForDeploy({sender:e,bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}getMetadataPropertiesAsObject(e){let r;return e?r=XO.CodeMetadata.fromBytes(p.Buffer.from(e.toString(),"hex")):r=new XO.CodeMetadata,r.toJSON()}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=Uint8Array.from(p.Buffer.from(r.toString(),"hex")),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForUpgrade({sender:e,contract:this.getAddress(),bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:u,caller:a}){ME.Compatibility.guardAddressIsSetAndNonZero(a,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:u.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi});r=r||[],n=n||0;let d=f.createTransactionForExecute({sender:a,contract:s||this.getAddress(),function:e.toString(),gasLimit:BigInt(i.valueOf()),arguments:r});return d.setChainID(u),d.setValue(n),d.setGasPrice(o??LE.TRANSACTION_MIN_GAS_PRICE),d}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new IW.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new EW.ErrContractHasNoAddress}static computeAddress(e,r){let n=A0.Address.fromBech32(e.bech32());return new A0.AddressComputer().computeContractAddress(n,BigInt(r.valueOf()))}};E0.SmartContract=qE});var rD=B(Io=>{"use strict";h();Object.defineProperty(Io,"__esModule",{value:!0});Io.ContractCallPayloadBuilder=Io.ContractUpgradePayloadBuilder=Io.ContractDeployPayloadBuilder=void 0;var TW=hr(),GE=Ms(),jE=Rn(),_W=fc(),VE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${TW.WasmVirtualMachine}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractDeployPayloadBuilder=VE;var kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractUpgradePayloadBuilder=kE;var HE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=zE(e,this.arguments),new GE.TransactionPayload(e)}};Io.ContractCallPayloadBuilder=HE;function zE(t,e){let{argumentsString:r,count:n}=new _W.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var qn=B(Jt=>{"use strict";h();var CW=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qr=Jt&&Jt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&CW(e,t,r)};Object.defineProperty(Jt,"__esModule",{value:!0});qr(fc(),Jt);qr(vO(),Jt);qr(GA(),Jt);qr(XA(),Jt);qr(eE(),Jt);qr(_E(),Jt);qr(bE(),Jt);qr(CE(),Jt);qr(n0(),Jt);qr(Wf(),Jt);qr(JO(),Jt);qr(PE(),Jt);qr(tD(),Jt);qr(rD(),Jt);qr(dr(),Jt)});var Ac=B(or=>{"use strict";h();Object.defineProperty(or,"__esModule",{value:!0});or.gatherAllEvents=or.findEventsByFirstTopic=or.findEventsByIdentifier=or.findEventsByPredicate=or.SmartContractCallOutcome=or.TransactionOutcome=or.SmartContractResult=or.TransactionLogs=or.TransactionEvent=void 0;var QE=class{constructor(e){this.address="",this.identifier="",this.topics=[],this.dataItems=[],Object.assign(this,e)}};or.TransactionEvent=QE;var $f=class{constructor(e){this.address="",this.events=[],Object.assign(this,e)}};or.TransactionLogs=$f;var KE=class{constructor(e){this.sender="",this.receiver="",this.data=new Uint8Array,this.logs=new $f({}),Object.assign(this,e)}};or.SmartContractResult=KE;var WE=class{constructor(e){this.directSmartContractCallOutcome=new b0({}),this.smartContractResults=[],this.logs=new $f({}),Object.assign(this,e)}};or.TransactionOutcome=WE;var b0=class{constructor(e){this.function="",this.returnDataParts=[],this.returnMessage="",this.returnCode="",Object.assign(this,e)}};or.SmartContractCallOutcome=b0;function $E(t,e){return nD(t).filter(e)}or.findEventsByPredicate=$E;function NW(t,e){return $E(t,r=>r.identifier==e)}or.findEventsByIdentifier=NW;function xW(t,e){return $E(t,r=>r.topics[0]?.toString()==e)}or.findEventsByFirstTopic=xW;function nD(t){let e=[];e.push(...t.logs.events);for(let r of t.smartContractResults)e.push(...r.logs.events);return e}or.gatherAllEvents=nD});var JE=B(S0=>{"use strict";h();Object.defineProperty(S0,"__esModule",{value:!0});S0.TransactionsConverter=void 0;var OW=qn(),DW=Xr(),Ec=Ac(),YE=class{transactionToPlainObject(e){return{nonce:Number(e.nonce),value:e.value.toString(),receiver:e.receiver,sender:e.sender,senderUsername:this.toBase64OrUndefined(e.senderUsername),receiverUsername:this.toBase64OrUndefined(e.receiverUsername),gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:this.toBase64OrUndefined(e.data),chainID:e.chainID.valueOf(),version:e.version,options:e.options==0?void 0:e.options,guardian:e.guardian?e.guardian:void 0,signature:this.toHexOrUndefined(e.signature),guardianSignature:this.toHexOrUndefined(e.guardianSignature)}}toBase64OrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("base64"):void 0}toHexOrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("hex"):void 0}plainObjectToTransaction(e){return new DW.Transaction({nonce:BigInt(e.nonce),value:BigInt(e.value||""),receiver:e.receiver,receiverUsername:this.bufferFromBase64(e.receiverUsername).toString(),sender:e.sender,senderUsername:this.bufferFromBase64(e.senderUsername).toString(),guardian:e.guardian,gasPrice:BigInt(e.gasPrice),gasLimit:BigInt(e.gasLimit),data:this.bufferFromBase64(e.data),chainID:String(e.chainID),version:Number(e.version),options:Number(e.options),signature:this.bufferFromHex(e.signature),guardianSignature:this.bufferFromHex(e.guardianSignature)})}bufferFromBase64(e){return p.Buffer.from(e||"","base64")}bufferFromHex(e){return p.Buffer.from(e||"","hex")}transactionOnNetworkToOutcome(e){let n=new OW.ResultsParser().parseUntypedOutcome(e),i=new Ec.SmartContractCallOutcome({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.values}),s=e.contractResults.items.map(u=>this.smartContractResultOnNetworkToSmartContractResult(u)),o=new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(u=>this.eventOnNetworkToEvent(u))});return new Ec.TransactionOutcome({logs:o,smartContractResults:s,directSmartContractCallOutcome:i})}smartContractResultOnNetworkToSmartContractResult(e){return new Ec.SmartContractResult({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:p.Buffer.from(e.data),logs:new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(r=>this.eventOnNetworkToEvent(r))})})}eventOnNetworkToEvent(e){let r=e.dataPayload?.valueOf()||p.Buffer.from(e.data||""),n=e.additionalData?.map(i=>p.Buffer.from(i.valueOf()))||[];return n.length===0&&r.length&&n.push(p.Buffer.from(r)),new Ec.TransactionEvent({address:e.address.bech32(),identifier:e.identifier,topics:e.topics.map(i=>p.Buffer.from(i.hex(),"hex")),dataItems:n})}};S0.TransactionsConverter=YE});var iD=B(Yi=>{"use strict";h();var PW=Yi&&Yi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RW=Yi&&Yi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BW=Yi&&Yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PW(e,t,r);return RW(e,t),e};Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Hash=void 0;var MW=BW(Ie()),XE=class t{constructor(e){if(!e)this.hash=p.Buffer.from([]);else if(e instanceof p.Buffer)this.hash=e;else if(typeof e=="string")this.hash=p.Buffer.from(e,"hex");else throw new MW.ErrBadType("hash","buffer | string",e)}static empty(){return new t(p.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};Yi.Hash=XE});var Yf=B(Hn=>{"use strict";h();var LW=Hn&&Hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FW=Hn&&Hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),UW=Hn&&Hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LW(e,t,r);return FW(e,t),e};Object.defineProperty(Hn,"__esModule",{value:!0});Hn.interpretSignatureAsBuffer=Hn.Signature=void 0;var sD=UW(Ie()),oD=64,ZE=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof p.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==oD}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=oD)throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Hn.Signature=ZE;function qW(t){if(ArrayBuffer.isView(t))return p.Buffer.from(t);if(t.hex!=null)return p.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Hn.interpretSignatureAsBuffer=qW});var uD=B((F1e,aD)=>{"use strict";h();aD.exports=VW;function VW(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";h();var I0=fD;I0.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bc=new Array(64),lD=new Array(123);for(mi=0;mi<64;)lD[bc[mi]=mi<26?mi+65:mi<52?mi+71:mi<62?mi-4:mi-59|43]=mi++;var mi;I0.encode=function(e,r,n){for(var i=null,s=[],o=0,u=0,a;r>2],a=(c&3)<<4,u=1;break;case 1:s[o++]=bc[a|c>>4],a=(c&15)<<2,u=2;break;case 2:s[o++]=bc[a|c>>6],s[o++]=bc[c&63],u=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return u&&(s[o++]=bc[a],s[o++]=61,u===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var cD="invalid encoding";I0.decode=function(e,r,n){for(var i=n,s=0,o,u=0;u1)break;if((a=lD[a])===void 0)throw Error(cD);switch(s){case 0:o=a,s=1;break;case 1:r[n++]=o<<2|(a&48)>>4,o=a,s=2;break;case 2:r[n++]=(o&15)<<4|(a&60)>>2,o=a,s=3;break;case 3:r[n++]=(o&3)<<6|a,s=0;break}}if(s===1)throw Error(cD);return n-i};I0.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var gD=B((k1e,dD)=>{"use strict";h();dD.exports=T0;function T0(){this._listeners={}}T0.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};T0.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";h();AD.exports=pD(pD);function pD(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(a,c,f){e[0]=a,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],e[0]}function u(a,c){return r[3]=a[c],r[2]=a[c+1],r[1]=a[c+2],r[0]=a[c+3],e[0]}t.readFloatLE=n?o:u,t.readFloatBE=n?u:o}():function(){function e(n,i,s,o){var u=i<0?1:0;if(u&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((u<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((u<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var a=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-a)*8388608)&8388607;n((u<<31|a+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,mD),t.writeFloatBE=e.bind(null,yD);function r(n,i,s){var o=n(i,s),u=(o>>31)*2+1,a=o>>>23&255,c=o&8388607;return a===255?c?NaN:u*(1/0):a===0?u*1401298464324817e-60*c:u*Math.pow(2,a-150)*(c+8388608)}t.readFloatLE=r.bind(null,wD),t.readFloatBE=r.bind(null,vD)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(a,c,f){e[0]=a,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],r[4]=a[c+4],r[5]=a[c+5],r[6]=a[c+6],r[7]=a[c+7],e[0]}function u(a,c){return r[7]=a[c],r[6]=a[c+1],r[5]=a[c+2],r[4]=a[c+3],r[3]=a[c+4],r[2]=a[c+5],r[1]=a[c+6],r[0]=a[c+7],e[0]}t.readDoubleLE=n?o:u,t.readDoubleBE=n?u:o}():function(){function e(n,i,s,o,u,a){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,u,a+i),n(1/o>0?0:2147483648,u,a+s);else if(isNaN(o))n(0,u,a+i),n(2146959360,u,a+s);else if(o>17976931348623157e292)n(0,u,a+i),n((c<<31|2146435072)>>>0,u,a+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,u,a+i),n((c<<31|f/4294967296)>>>0,u,a+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,u,a+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,u,a+s)}}}t.writeDoubleLE=e.bind(null,mD,0,4),t.writeDoubleBE=e.bind(null,yD,4,0);function r(n,i,s,o,u){var a=n(o,u+i),c=n(o,u+s),f=(c>>31)*2+1,d=c>>>20&2047,w=4294967296*(c&1048575)+a;return d===2047?w?NaN:f*(1/0):d===0?f*5e-324*w:f*Math.pow(2,d-1075)*(w+4503599627370496)}t.readDoubleLE=r.bind(null,wD,0,4),t.readDoubleBE=r.bind(null,vD,4,0)}(),t}function mD(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function yD(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function wD(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function vD(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var bD=B((exports,module)=>{"use strict";h();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var ID=B(SD=>{"use strict";h();var eb=SD;eb.length=function(e){for(var r=0,n=0,i=0;i191&&a<224?o[u++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[u++]=55296+(a>>10),o[u++]=56320+(a&1023)):o[u++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,u>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),u=0);return s?(u&&s.push(String.fromCharCode.apply(String,o.slice(0,u))),s.join("")):String.fromCharCode.apply(String,o.slice(0,u))};eb.write=function(e,r,n){for(var i=n,s,o,u=0;u>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(u+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++u,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var _D=B((W1e,TD)=>{"use strict";h();TD.exports=kW;function kW(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);var c=e.call(s,o,o+=a);return o&7&&(o=(o|7)+1),c}}});var ND=B((Y1e,CD)=>{"use strict";h();CD.exports=yr;var Jf=_o();function yr(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ha=yr.zero=new yr(0,0);Ha.toNumber=function(){return 0};Ha.zzEncode=Ha.zzDecode=function(){return this};Ha.length=function(){return 1};var HW=yr.zeroHash="\0\0\0\0\0\0\0\0";yr.fromNumber=function(e){if(e===0)return Ha;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new yr(n,i)};yr.from=function(e){if(typeof e=="number")return yr.fromNumber(e);if(Jf.isString(e))if(Jf.Long)e=Jf.Long.fromString(e);else return yr.fromNumber(parseInt(e,10));return e.low||e.high?new yr(e.low>>>0,e.high>>>0):Ha};yr.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};yr.prototype.toLong=function(e){return Jf.Long?new Jf.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var To=String.prototype.charCodeAt;yr.fromHash=function(e){return e===HW?Ha:new yr((To.call(e,0)|To.call(e,1)<<8|To.call(e,2)<<16|To.call(e,3)<<24)>>>0,(To.call(e,4)|To.call(e,5)<<8|To.call(e,6)<<16|To.call(e,7)<<24)>>>0)};yr.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};yr.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};yr.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};yr.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var _o=B(tb=>{"use strict";h();var we=tb;we.asPromise=uD();we.base64=hD();we.EventEmitter=gD();we.float=ED();we.inquire=bD();we.utf8=ID();we.pool=_D();we.LongBits=ND();we.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);we.global=we.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||tb;we.emptyArray=Object.freeze?Object.freeze([]):[];we.emptyObject=Object.freeze?Object.freeze({}):{};we.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};we.isString=function(e){return typeof e=="string"||e instanceof String};we.isObject=function(e){return e&&typeof e=="object"};we.isset=we.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};we.Buffer=function(){try{var t=we.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();we._Buffer_from=null;we._Buffer_allocUnsafe=null;we.newBuffer=function(e){return typeof e=="number"?we.Buffer?we._Buffer_allocUnsafe(e):new we.Array(e):we.Buffer?we._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};we.Array=typeof Uint8Array<"u"?Uint8Array:Array;we.Long=we.global.dcodeIO&&we.global.dcodeIO.Long||we.global.Long||we.inquire("long");we.key2Re=/^true|false|0|1$/;we.key32Re=/^-?(?:0|[1-9][0-9]*)$/;we.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;we.longToHash=function(e){return e?we.LongBits.from(e).toHash():we.LongBits.zeroHash};we.longFromHash=function(e,r){var n=we.LongBits.fromHash(e);return we.Long?we.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function xD(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};we.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";h();BD.exports=Ue;var Gn=_o(),rb,_0=Gn.LongBits,DD=Gn.base64,PD=Gn.utf8;function Xf(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function ib(){}function GW(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Xf(ib,0,0),this.tail=this.head,this.states=null}var RD=function(){return Gn.Buffer?function(){return(Ue.create=function(){return new rb})()}:function(){return new Ue}};Ue.create=RD();Ue.alloc=function(e){return new Gn.Array(e)};Gn.Array!==Array&&(Ue.alloc=Gn.pool(Ue.alloc,Gn.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Xf(e,r,n),this.len+=r,this};function sb(t,e,r){e[r]=t&255}function jW(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function ob(t,e){this.len=t,this.next=void 0,this.val=e}ob.prototype=Object.create(Xf.prototype);ob.prototype.fn=jW;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ob((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(ab,10,_0.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ab(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=_0.from(e);return this._push(ab,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=_0.from(e).zzEncode();return this._push(ab,r.length(),r)};Ue.prototype.bool=function(e){return this._push(sb,1,e?1:0)};function nb(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(nb,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=_0.from(e);return this._push(nb,4,r.lo)._push(nb,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Gn.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Gn.float.writeDoubleLE,8,e)};var zW=Gn.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(sb,1,0);if(Gn.isString(e)){var n=Ue.alloc(r=DD.length(e));DD.decode(e,n,0),e=n}return this.uint32(r)._push(zW,r,e)};Ue.prototype.string=function(e){var r=PD.length(e);return r?this.uint32(r)._push(PD.write,r,e):this._push(sb,1,0)};Ue.prototype.fork=function(){return this.states=new GW(this),this.head=this.tail=new Xf(ib,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xf(ib,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){rb=t,Ue.create=RD(),rb._configure()}});var FD=B((rwe,LD)=>{"use strict";h();LD.exports=Ji;var MD=ub();(Ji.prototype=Object.create(MD.prototype)).constructor=Ji;var Co=_o();function Ji(){MD.call(this)}Ji._configure=function(){Ji.alloc=Co._Buffer_allocUnsafe,Ji.writeBytesBuffer=Co.Buffer&&Co.Buffer.prototype instanceof Uint8Array&&Co.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Ji.writeBytesBuffer,r,e),this};function QW(t,e,r){t.length<40?Co.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ji.prototype.string=function(e){var r=Co.Buffer.byteLength(e);return this.uint32(r),r&&this._push(QW,r,e),this};Ji._configure()});var fb=B((iwe,HD)=>{"use strict";h();HD.exports=Xt;var yi=_o(),lb,VD=yi.LongBits,KW=yi.utf8;function wi(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Xt(t){this.buf=t,this.pos=0,this.len=t.length}var UD=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Xt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Xt(e);throw Error("illegal buffer")},kD=function(){return yi.Buffer?function(r){return(Xt.create=function(i){return yi.Buffer.isBuffer(i)?new lb(i):UD(i)})(r)}:UD};Xt.create=kD();Xt.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Xt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wi(this,10);return e}}();Xt.prototype.int32=function(){return this.uint32()|0};Xt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function cb(){var t=new VD(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw wi(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw wi(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Xt.prototype.bool=function(){return this.uint32()!==0};function C0(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Xt.prototype.fixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)};Xt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)|0};function qD(){if(this.pos+8>this.len)throw wi(this,8);return new VD(C0(this.buf,this.pos+=4),C0(this.buf,this.pos+=4))}Xt.prototype.float=function(){if(this.pos+4>this.len)throw wi(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Xt.prototype.double=function(){if(this.pos+8>this.len)throw wi(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Xt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw wi(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var i=yi.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Xt.prototype.string=function(){var e=this.bytes();return KW.read(e,0,e.length)};Xt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wi(this);while(this.buf[this.pos++]&128);return this};Xt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Xt._configure=function(t){lb=t,Xt.create=kD(),lb._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Xt.prototype,{int64:function(){return cb.call(this)[e](!1)},uint64:function(){return cb.call(this)[e](!0)},sint64:function(){return cb.call(this).zzDecode()[e](!1)},fixed64:function(){return qD.call(this)[e](!0)},sfixed64:function(){return qD.call(this)[e](!1)}})}});var QD=B((owe,zD)=>{"use strict";h();zD.exports=Ga;var jD=fb();(Ga.prototype=Object.create(jD.prototype)).constructor=Ga;var GD=_o();function Ga(t){jD.call(this,t)}Ga._configure=function(){GD.Buffer&&(Ga.prototype._slice=GD.Buffer.prototype.slice)};Ga.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ga._configure()});var WD=B((uwe,KD)=>{"use strict";h();KD.exports=Zf;var hb=_o();(Zf.prototype=Object.create(hb.EventEmitter.prototype)).constructor=Zf;function Zf(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");hb.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Zf.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return hb.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(a,c){if(a)return o.emit("error",a,e),s(a);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(u){o.emit("error",u,e),setTimeout(function(){s(u)},0);return}};Zf.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var YD=B($D=>{"use strict";h();var WW=$D;WW.Service=WD()});var XD=B((hwe,JD)=>{"use strict";h();JD.exports={}});var t8=B(e8=>{"use strict";h();var tn=e8;tn.build="minimal";tn.Writer=ub();tn.BufferWriter=FD();tn.Reader=fb();tn.BufferReader=QD();tn.util=_o();tn.rpc=YD();tn.roots=XD();tn.configure=ZD;function ZD(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}ZD()});var n8=B((mwe,r8)=>{"use strict";h();r8.exports=t8()});var s8=B((i8,eh)=>{"use strict";h();(function(t,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof Bd=="function"&&typeof eh=="object"&&eh&&eh.exports&&(eh.exports=e(n8()))})(i8,function(t){"use strict";var e=t.Reader,r=t.Writer,n=t.util,i=t.roots.default||(t.roots.default={});return i.proto=function(){var s={};return s.Transaction=function(){function o(u){if(u)for(var a=Object.keys(u),c=0;c>>3){case 1:{d.Nonce=a.uint64();break}case 2:{d.Value=a.bytes();break}case 3:{d.RcvAddr=a.bytes();break}case 4:{d.RcvUserName=a.bytes();break}case 5:{d.SndAddr=a.bytes();break}case 6:{d.SndUserName=a.bytes();break}case 7:{d.GasPrice=a.uint64();break}case 8:{d.GasLimit=a.uint64();break}case 9:{d.Data=a.bytes();break}case 10:{d.ChainID=a.bytes();break}case 11:{d.Version=a.uint32();break}case 12:{d.Signature=a.bytes();break}case 13:{d.Options=a.uint32();break}case 14:{d.GuardianAddr=a.bytes();break}case 15:{d.GuardianSignature=a.bytes();break}default:a.skipType(w&7);break}}return d},o.decodeDelimited=function(a){return a instanceof e||(a=new e(a)),this.decode(a,a.uint32())},o.verify=function(a){return typeof a!="object"||a===null?"object expected":a.Nonce!=null&&a.hasOwnProperty("Nonce")&&!n.isInteger(a.Nonce)&&!(a.Nonce&&n.isInteger(a.Nonce.low)&&n.isInteger(a.Nonce.high))?"Nonce: integer|Long expected":a.Value!=null&&a.hasOwnProperty("Value")&&!(a.Value&&typeof a.Value.length=="number"||n.isString(a.Value))?"Value: buffer expected":a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&!(a.RcvAddr&&typeof a.RcvAddr.length=="number"||n.isString(a.RcvAddr))?"RcvAddr: buffer expected":a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&!(a.RcvUserName&&typeof a.RcvUserName.length=="number"||n.isString(a.RcvUserName))?"RcvUserName: buffer expected":a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&!(a.SndAddr&&typeof a.SndAddr.length=="number"||n.isString(a.SndAddr))?"SndAddr: buffer expected":a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&!(a.SndUserName&&typeof a.SndUserName.length=="number"||n.isString(a.SndUserName))?"SndUserName: buffer expected":a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&!n.isInteger(a.GasPrice)&&!(a.GasPrice&&n.isInteger(a.GasPrice.low)&&n.isInteger(a.GasPrice.high))?"GasPrice: integer|Long expected":a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&!n.isInteger(a.GasLimit)&&!(a.GasLimit&&n.isInteger(a.GasLimit.low)&&n.isInteger(a.GasLimit.high))?"GasLimit: integer|Long expected":a.Data!=null&&a.hasOwnProperty("Data")&&!(a.Data&&typeof a.Data.length=="number"||n.isString(a.Data))?"Data: buffer expected":a.ChainID!=null&&a.hasOwnProperty("ChainID")&&!(a.ChainID&&typeof a.ChainID.length=="number"||n.isString(a.ChainID))?"ChainID: buffer expected":a.Version!=null&&a.hasOwnProperty("Version")&&!n.isInteger(a.Version)?"Version: integer expected":a.Signature!=null&&a.hasOwnProperty("Signature")&&!(a.Signature&&typeof a.Signature.length=="number"||n.isString(a.Signature))?"Signature: buffer expected":a.Options!=null&&a.hasOwnProperty("Options")&&!n.isInteger(a.Options)?"Options: integer expected":a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&!(a.GuardianAddr&&typeof a.GuardianAddr.length=="number"||n.isString(a.GuardianAddr))?"GuardianAddr: buffer expected":a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&!(a.GuardianSignature&&typeof a.GuardianSignature.length=="number"||n.isString(a.GuardianSignature))?"GuardianSignature: buffer expected":null},o.fromObject=function(a){if(a instanceof i.proto.Transaction)return a;var c=new i.proto.Transaction;return a.Nonce!=null&&(n.Long?(c.Nonce=n.Long.fromValue(a.Nonce)).unsigned=!0:typeof a.Nonce=="string"?c.Nonce=parseInt(a.Nonce,10):typeof a.Nonce=="number"?c.Nonce=a.Nonce:typeof a.Nonce=="object"&&(c.Nonce=new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0))),a.Value!=null&&(typeof a.Value=="string"?n.base64.decode(a.Value,c.Value=n.newBuffer(n.base64.length(a.Value)),0):a.Value.length>=0&&(c.Value=a.Value)),a.RcvAddr!=null&&(typeof a.RcvAddr=="string"?n.base64.decode(a.RcvAddr,c.RcvAddr=n.newBuffer(n.base64.length(a.RcvAddr)),0):a.RcvAddr.length>=0&&(c.RcvAddr=a.RcvAddr)),a.RcvUserName!=null&&(typeof a.RcvUserName=="string"?n.base64.decode(a.RcvUserName,c.RcvUserName=n.newBuffer(n.base64.length(a.RcvUserName)),0):a.RcvUserName.length>=0&&(c.RcvUserName=a.RcvUserName)),a.SndAddr!=null&&(typeof a.SndAddr=="string"?n.base64.decode(a.SndAddr,c.SndAddr=n.newBuffer(n.base64.length(a.SndAddr)),0):a.SndAddr.length>=0&&(c.SndAddr=a.SndAddr)),a.SndUserName!=null&&(typeof a.SndUserName=="string"?n.base64.decode(a.SndUserName,c.SndUserName=n.newBuffer(n.base64.length(a.SndUserName)),0):a.SndUserName.length>=0&&(c.SndUserName=a.SndUserName)),a.GasPrice!=null&&(n.Long?(c.GasPrice=n.Long.fromValue(a.GasPrice)).unsigned=!0:typeof a.GasPrice=="string"?c.GasPrice=parseInt(a.GasPrice,10):typeof a.GasPrice=="number"?c.GasPrice=a.GasPrice:typeof a.GasPrice=="object"&&(c.GasPrice=new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0))),a.GasLimit!=null&&(n.Long?(c.GasLimit=n.Long.fromValue(a.GasLimit)).unsigned=!0:typeof a.GasLimit=="string"?c.GasLimit=parseInt(a.GasLimit,10):typeof a.GasLimit=="number"?c.GasLimit=a.GasLimit:typeof a.GasLimit=="object"&&(c.GasLimit=new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0))),a.Data!=null&&(typeof a.Data=="string"?n.base64.decode(a.Data,c.Data=n.newBuffer(n.base64.length(a.Data)),0):a.Data.length>=0&&(c.Data=a.Data)),a.ChainID!=null&&(typeof a.ChainID=="string"?n.base64.decode(a.ChainID,c.ChainID=n.newBuffer(n.base64.length(a.ChainID)),0):a.ChainID.length>=0&&(c.ChainID=a.ChainID)),a.Version!=null&&(c.Version=a.Version>>>0),a.Signature!=null&&(typeof a.Signature=="string"?n.base64.decode(a.Signature,c.Signature=n.newBuffer(n.base64.length(a.Signature)),0):a.Signature.length>=0&&(c.Signature=a.Signature)),a.Options!=null&&(c.Options=a.Options>>>0),a.GuardianAddr!=null&&(typeof a.GuardianAddr=="string"?n.base64.decode(a.GuardianAddr,c.GuardianAddr=n.newBuffer(n.base64.length(a.GuardianAddr)),0):a.GuardianAddr.length>=0&&(c.GuardianAddr=a.GuardianAddr)),a.GuardianSignature!=null&&(typeof a.GuardianSignature=="string"?n.base64.decode(a.GuardianSignature,c.GuardianSignature=n.newBuffer(n.base64.length(a.GuardianSignature)),0):a.GuardianSignature.length>=0&&(c.GuardianSignature=a.GuardianSignature)),c},o.toObject=function(a,c){c||(c={});var f={};if(c.defaults){if(n.Long){var d=new n.Long(0,0,!0);f.Nonce=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.Nonce=c.longs===String?"0":0;if(c.bytes===String?f.Value="":(f.Value=[],c.bytes!==Array&&(f.Value=n.newBuffer(f.Value))),c.bytes===String?f.RcvAddr="":(f.RcvAddr=[],c.bytes!==Array&&(f.RcvAddr=n.newBuffer(f.RcvAddr))),c.bytes===String?f.RcvUserName="":(f.RcvUserName=[],c.bytes!==Array&&(f.RcvUserName=n.newBuffer(f.RcvUserName))),c.bytes===String?f.SndAddr="":(f.SndAddr=[],c.bytes!==Array&&(f.SndAddr=n.newBuffer(f.SndAddr))),c.bytes===String?f.SndUserName="":(f.SndUserName=[],c.bytes!==Array&&(f.SndUserName=n.newBuffer(f.SndUserName))),n.Long){var d=new n.Long(0,0,!0);f.GasPrice=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasPrice=c.longs===String?"0":0;if(n.Long){var d=new n.Long(0,0,!0);f.GasLimit=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasLimit=c.longs===String?"0":0;c.bytes===String?f.Data="":(f.Data=[],c.bytes!==Array&&(f.Data=n.newBuffer(f.Data))),c.bytes===String?f.ChainID="":(f.ChainID=[],c.bytes!==Array&&(f.ChainID=n.newBuffer(f.ChainID))),f.Version=0,c.bytes===String?f.Signature="":(f.Signature=[],c.bytes!==Array&&(f.Signature=n.newBuffer(f.Signature))),f.Options=0,c.bytes===String?f.GuardianAddr="":(f.GuardianAddr=[],c.bytes!==Array&&(f.GuardianAddr=n.newBuffer(f.GuardianAddr))),c.bytes===String?f.GuardianSignature="":(f.GuardianSignature=[],c.bytes!==Array&&(f.GuardianSignature=n.newBuffer(f.GuardianSignature)))}return a.Nonce!=null&&a.hasOwnProperty("Nonce")&&(typeof a.Nonce=="number"?f.Nonce=c.longs===String?String(a.Nonce):a.Nonce:f.Nonce=c.longs===String?n.Long.prototype.toString.call(a.Nonce):c.longs===Number?new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0):a.Nonce),a.Value!=null&&a.hasOwnProperty("Value")&&(f.Value=c.bytes===String?n.base64.encode(a.Value,0,a.Value.length):c.bytes===Array?Array.prototype.slice.call(a.Value):a.Value),a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&(f.RcvAddr=c.bytes===String?n.base64.encode(a.RcvAddr,0,a.RcvAddr.length):c.bytes===Array?Array.prototype.slice.call(a.RcvAddr):a.RcvAddr),a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&(f.RcvUserName=c.bytes===String?n.base64.encode(a.RcvUserName,0,a.RcvUserName.length):c.bytes===Array?Array.prototype.slice.call(a.RcvUserName):a.RcvUserName),a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&(f.SndAddr=c.bytes===String?n.base64.encode(a.SndAddr,0,a.SndAddr.length):c.bytes===Array?Array.prototype.slice.call(a.SndAddr):a.SndAddr),a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&(f.SndUserName=c.bytes===String?n.base64.encode(a.SndUserName,0,a.SndUserName.length):c.bytes===Array?Array.prototype.slice.call(a.SndUserName):a.SndUserName),a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&(typeof a.GasPrice=="number"?f.GasPrice=c.longs===String?String(a.GasPrice):a.GasPrice:f.GasPrice=c.longs===String?n.Long.prototype.toString.call(a.GasPrice):c.longs===Number?new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0):a.GasPrice),a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&(typeof a.GasLimit=="number"?f.GasLimit=c.longs===String?String(a.GasLimit):a.GasLimit:f.GasLimit=c.longs===String?n.Long.prototype.toString.call(a.GasLimit):c.longs===Number?new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0):a.GasLimit),a.Data!=null&&a.hasOwnProperty("Data")&&(f.Data=c.bytes===String?n.base64.encode(a.Data,0,a.Data.length):c.bytes===Array?Array.prototype.slice.call(a.Data):a.Data),a.ChainID!=null&&a.hasOwnProperty("ChainID")&&(f.ChainID=c.bytes===String?n.base64.encode(a.ChainID,0,a.ChainID.length):c.bytes===Array?Array.prototype.slice.call(a.ChainID):a.ChainID),a.Version!=null&&a.hasOwnProperty("Version")&&(f.Version=a.Version),a.Signature!=null&&a.hasOwnProperty("Signature")&&(f.Signature=c.bytes===String?n.base64.encode(a.Signature,0,a.Signature.length):c.bytes===Array?Array.prototype.slice.call(a.Signature):a.Signature),a.Options!=null&&a.hasOwnProperty("Options")&&(f.Options=a.Options),a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&(f.GuardianAddr=c.bytes===String?n.base64.encode(a.GuardianAddr,0,a.GuardianAddr.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianAddr):a.GuardianAddr),a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&(f.GuardianSignature=c.bytes===String?n.base64.encode(a.GuardianSignature,0,a.GuardianSignature.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianSignature):a.GuardianSignature),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,t.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Transaction"},o}(),s}(),i})});var o8=B(jn=>{"use strict";h();var $W=jn&&jn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),YW=jn&&jn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),JW=jn&&jn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$W(e,t,r);return YW(e,t),e},XW=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.ProtoSerializer=void 0;var ZW=XW((rr(),_e(fr))),db=Ve(),e$=hr(),t$=JW(Ie()),r$=Bu(),gb=class{serializeTransaction(e){let r=s8().proto,n=new db.Address(e.getReceiver().bech32()).pubkey(),i=new db.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?p.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?p.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:p.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==e$.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let a=e.getGuardian();s.GuardianAddr=new db.Address(a.bech32()).pubkey(),s.GuardianSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return p.Buffer.from(o)}serializeTransactionValue(e){let r=new ZW.default(e.toString());if(r.isZero())return p.Buffer.from([0,0]);let n=r$.bigIntToBuffer(r);return n=p.Buffer.concat([p.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new t$.ErrUnsupportedOperation("deserializeTransaction")}};jn.ProtoSerializer=gb});var a8=B(ja=>{"use strict";h();var n$=ja&&ja.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),i$=ja&&ja.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&n$(e,t,r)};Object.defineProperty(ja,"__esModule",{value:!0});i$(o8(),ja)});var N0=B(zn=>{"use strict";h();var s$=zn&&zn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),o$=zn&&zn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a$=zn&&zn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&s$(e,t,r);return o$(e,t),e},u$=zn&&zn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zn,"__esModule",{value:!0});zn.TransactionComputer=void 0;var th=a$(Ie()),u8=u$((rr(),_e(fr))),c$=a8(),l$=Xr(),rn=hr(),f$=YA(),h$=sf(),d$=32,pb=class{constructor(){}computeTransactionFee(e,r){let n=BigInt(r.MinGasLimit+e.data.length*r.GasPerDataByte);if(n>e.gasLimit)throw new th.ErrNotEnoughGas(parseInt(e.gasLimit.toString(),10));let i=e.gasPrice,s=n*i;if(n===e.gasLimit)return s;let o=e.gasLimit-n,u=BigInt(new u8.default(i.toString()).multipliedBy(new u8.default(r.GasPriceModifier)).toFixed(0)),a=o*u;return s+a}computeBytesForSigning(e){this.ensureValidTransactionFields(e);let r=this.toPlainObjectForSigning(e),n=JSON.stringify(r);return new Uint8Array(p.Buffer.from(n))}computeBytesForVerifying(e){return this.hasOptionsSetForHashSigning(e)?this.computeHashForSigning(e):this.computeBytesForSigning(e)}computeHashForSigning(e){let r=this.toPlainObjectForSigning(e),n=p.Buffer.from(JSON.stringify(r));return h$("keccak256").update(n).digest()}computeTransactionHash(e){let n=new c$.ProtoSerializer().serializeTransaction(new l$.Transaction(e)),i=f$(d$).update(n).digest("hex");return p.Buffer.from(i,"hex")}hasOptionsSetForGuardedTransaction(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_GUARDED)==rn.TRANSACTION_OPTIONS_TX_GUARDED}hasOptionsSetForHashSigning(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_HASH_SIGN)==rn.TRANSACTION_OPTIONS_TX_HASH_SIGN}applyGuardian(e,r){e.version= ${rn.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`)}};zn.TransactionComputer=pb});var Xr=B(Sc=>{"use strict";h();Object.defineProperty(Sc,"__esModule",{value:!0});Sc.TransactionHash=Sc.Transaction=void 0;var c8=(rr(),_e(fr)),mb=Ve(),yb=hr(),l8=JE(),g$=iD(),f8=$l(),h8=Yf(),p$=Ms(),wb=N0(),vb=class{constructor(e){this.nonce=BigInt(e.nonce?.valueOf()||0n),this.value=e.value?BigInt(new c8.BigNumber(e.value.toString()).toFixed(0)):0n,this.sender=this.addressAsBech32(e.sender),this.receiver=this.addressAsBech32(e.receiver),this.senderUsername=e.senderUsername||"",this.receiverUsername=e.receiverUsername||"",this.gasPrice=BigInt(e.gasPrice?.valueOf()||yb.TRANSACTION_MIN_GAS_PRICE),this.gasLimit=BigInt(e.gasLimit.valueOf()),this.data=e.data?.valueOf()||new Uint8Array,this.chainID=e.chainID.valueOf(),this.version=Number(e.version?.valueOf()||yb.TRANSACTION_VERSION_DEFAULT),this.options=Number(e.options?.valueOf()||yb.TRANSACTION_OPTIONS_DEFAULT),this.guardian=e.guardian?this.addressAsBech32(e.guardian):"",this.signature=e.signature||p.Buffer.from([]),this.guardianSignature=e.guardianSignature||p.Buffer.from([])}addressAsBech32(e){return typeof e=="string"?e:e.bech32()}getNonce(){return Number(this.nonce)}setNonce(e){this.nonce=BigInt(e.valueOf())}getValue(){return this.value}setValue(e){this.value=BigInt(e.toString())}getSender(){return mb.Address.fromBech32(this.sender)}setSender(e){this.sender=typeof e=="string"?e:e.bech32()}getReceiver(){return mb.Address.fromBech32(this.receiver)}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return new mb.Address(this.guardian)}getGasPrice(){return Number(this.gasPrice)}setGasPrice(e){this.gasPrice=BigInt(e.valueOf())}getGasLimit(){return Number(this.gasLimit)}setGasLimit(e){this.gasLimit=BigInt(e.valueOf())}getData(){return new p$.TransactionPayload(p.Buffer.from(this.data))}getChainID(){return this.chainID}setChainID(e){this.chainID=e.valueOf()}getVersion(){return new f8.TransactionVersion(this.version)}setVersion(e){this.version=e.valueOf()}getOptions(){return new f8.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=e.valueOf()}getSignature(){return p.Buffer.from(this.signature)}getGuardianSignature(){return p.Buffer.from(this.guardianSignature)}setGuardian(e){this.guardian=typeof e=="string"?e:e.bech32()}getHash(){return x0.compute(this)}serializeForSigning(){let r=new wb.TransactionComputer().computeBytesForSigning(this);return p.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){return new l8.TransactionsConverter().transactionToPlainObject(this)}static fromPlainObject(e){return new l8.TransactionsConverter().plainObjectToTransaction(e)}applySignature(e){this.signature=h8.interpretSignatureAsBuffer(e)}applyGuardianSignature(e){this.guardianSignature=h8.interpretSignatureAsBuffer(e)}toSendable(){return this.toPlainObject()}computeFee(e){let n=new wb.TransactionComputer().computeTransactionFee(this,e);return new c8.BigNumber(n.toString())}};Sc.Transaction=vb;var x0=class t extends g$.Hash{constructor(e){super(e)}static compute(e){let n=new wb.TransactionComputer().computeTransactionHash(e);return new t(p.Buffer.from(n).toString("hex"))}};Sc.TransactionHash=x0});var g8=B(O0=>{"use strict";h();Object.defineProperty(O0,"__esModule",{value:!0});O0.TokenOperationsFactory=void 0;var Ab=hr(),m$=oo(),d8=$l(),y$=Xr(),w$=Ms(),ae=$d(),Eb=class{constructor(e){this.config=e,this.trueAsHex=ae.utf8ToHex("true"),this.falseAsHex=ae.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.initialSupply),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){m$.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`); - } - issueSemiFungible(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "issueSemiFungible", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - issueNonFungible(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "issueNonFungible", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - registerMetaESDT(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "registerMetaESDT", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.bigIntToHex(args.numDecimals), - codec_1.utf8ToHex("canFreeze"), - args.canFreeze ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canWipe"), - args.canWipe ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canPause"), - args.canPause ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canTransferNFTCreateRole"), - args.canTransferNFTCreateRole ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canChangeOwner"), - args.canChangeOwner ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canUpgrade"), - args.canUpgrade ? this.trueAsHex : this.falseAsHex, - codec_1.utf8ToHex("canAddSpecialRoles"), - args.canAddSpecialRoles ? this.trueAsHex : this.falseAsHex - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - registerAndSetAllRoles(args) { - this.notifyAboutUnsettingBurnRoleGlobally(); - const parts = [ - "registerAndSetAllRoles", - codec_1.utf8ToHex(args.tokenName), - codec_1.utf8ToHex(args.tokenTicker), - codec_1.utf8ToHex(args.tokenType), - codec_1.bigIntToHex(args.numDecimals) - ]; - return this.createTransaction({ - sender: args.issuer, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - value: this.config.issueCost, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitIssue, - dataParts: parts - }); - } - setBurnRoleGlobally(args) { - const parts = ["setBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, - dataParts: parts - }); - } - unsetBurnRoleGlobally(args) { - const parts = ["unsetBurnRoleGlobally", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitToggleBurnRoleGlobally, - dataParts: parts - }); - } - setSpecialRoleOnFungible(args) { - const parts = [ - "setSpecialRole", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.addressToHex(args.user), - ...args.addRoleLocalMint ? [codec_1.utf8ToHex("ESDTRoleLocalMint")] : [], - ...args.addRoleLocalBurn ? [codec_1.utf8ToHex("ESDTRoleLocalBurn")] : [] - ]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts - }); - } - setSpecialRoleOnSemiFungible(args) { - const parts = [ - "setSpecialRole", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.addressToHex(args.user), - ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], - ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], - ...args.addRoleNFTAddQuantity ? [codec_1.utf8ToHex("ESDTRoleNFTAddQuantity")] : [], - ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] - ]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts - }); - } - setSpecialRoleOnMetaESDT(args) { - return this.setSpecialRoleOnSemiFungible(args); - } - setSpecialRoleOnNonFungible(args) { - const parts = [ - "setSpecialRole", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.addressToHex(args.user), - ...args.addRoleNFTCreate ? [codec_1.utf8ToHex("ESDTRoleNFTCreate")] : [], - ...args.addRoleNFTBurn ? [codec_1.utf8ToHex("ESDTRoleNFTBurn")] : [], - ...args.addRoleNFTUpdateAttributes ? [codec_1.utf8ToHex("ESDTRoleNFTUpdateAttributes")] : [], - ...args.addRoleNFTAddURI ? [codec_1.utf8ToHex("ESDTRoleNFTAddURI")] : [], - ...args.addRoleESDTTransferRole ? [codec_1.utf8ToHex("ESDTTransferRole")] : [] - ]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitSetSpecialRole, - dataParts: parts - }); - } - nftCreate(args) { - const parts = [ - "ESDTNFTCreate", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.initialQuantity), - codec_1.utf8ToHex(args.name), - codec_1.bigIntToHex(args.royalties), - codec_1.utf8ToHex(args.hash), - codec_1.bufferToHex(args.attributes), - ...args.uris.map(codec_1.utf8ToHex) - ]; - const nftData = args.name + args.hash + args.attributes + args.uris.join(""); - const storageGasLimit = nftData.length * this.config.gasLimitStorePerByte.valueOf(); - return this.createTransaction({ - sender: args.creator, - receiver: args.creator, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTCreate.valueOf() + storageGasLimit.valueOf(), - dataParts: parts - }); - } - pause(args) { - const parts = ["pause", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitPausing, - dataParts: parts - }); - } - unpause(args) { - const parts = ["unPause", codec_1.utf8ToHex(args.tokenIdentifier)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitPausing, - dataParts: parts - }); - } - freeze(args) { - const parts = ["freeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitFreezing, - dataParts: parts - }); - } - unfreeze(args) { - const parts = ["unFreeze", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitFreezing, - dataParts: parts - }); - } - wipe(args) { - const parts = ["wipe", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.addressToHex(args.user)]; - return this.createTransaction({ - sender: args.manager, - receiver: this.config.esdtContractAddress, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitWiping, - dataParts: parts - }); - } - localMint(args) { - const parts = ["ESDTLocalMint", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToMint)]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTLocalMint, - dataParts: parts - }); - } - localBurn(args) { - const parts = ["ESDTLocalBurn", codec_1.utf8ToHex(args.tokenIdentifier), codec_1.bigIntToHex(args.supplyToBurn)]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTLocalBurn, - dataParts: parts - }); - } - updateAttributes(args) { - const parts = [ - "ESDTNFTUpdateAttributes", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.tokenNonce), - codec_1.bufferToHex(args.attributes) - ]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTUpdateAttributes, - dataParts: parts - }); - } - addQuantity(args) { - const parts = [ - "ESDTNFTAddQuantity", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.tokenNonce), - codec_1.bigIntToHex(args.quantityToAdd) - ]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTAddQuantity, - dataParts: parts - }); - } - burnQuantity(args) { - const parts = [ - "ESDTNFTBurn", - codec_1.utf8ToHex(args.tokenIdentifier), - codec_1.bigIntToHex(args.tokenNonce), - codec_1.bigIntToHex(args.quantityToBurn) - ]; - return this.createTransaction({ - sender: args.manager, - receiver: args.manager, - nonce: args.transactionNonce, - gasPrice: args.gasPrice, - gasLimitHint: args.gasLimit, - executionGasLimit: this.config.gasLimitESDTNFTBurn, - dataParts: parts - }); - } - createTransaction({ sender, receiver, nonce, value, gasPrice, gasLimitHint, executionGasLimit, dataParts }) { - const payload = this.buildTransactionPayload(dataParts); - const gasLimit = gasLimitHint || this.computeGasLimit(payload, executionGasLimit); - const version2 = new networkParams_1.TransactionVersion(constants_1.TRANSACTION_VERSION_DEFAULT); - const options = new networkParams_1.TransactionOptions(constants_1.TRANSACTION_OPTIONS_DEFAULT); - return new transaction_1.Transaction({ - chainID: this.config.chainID, - sender, - receiver, - gasLimit, - gasPrice, - nonce: nonce || 0, - value: value || 0, - data: payload, - version: version2, - options - }); - } - buildTransactionPayload(parts) { - const data = parts.join(constants_1.ARGUMENTS_SEPARATOR); - return new transactionPayload_1.TransactionPayload(data); - } - computeGasLimit(payload, executionGas) { - const dataMovementGas = this.config.minGasLimit.valueOf() + this.config.gasLimitPerByte.valueOf() * payload.length(); - return dataMovementGas + executionGas.valueOf(); - } - }; - exports2.TokenOperationsFactory = TokenOperationsFactory2; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js -var require_tokenOperationsFactoryConfig = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsFactoryConfig.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenOperationsFactoryConfig = void 0; - var address_1 = require_address(); - var TokenOperationsFactoryConfig2 = class { - constructor(chainID) { - this.minGasPrice = 1e9; - this.minGasLimit = 5e4; - this.gasLimitPerByte = 1500; - this.gasLimitIssue = 6e7; - this.gasLimitToggleBurnRoleGlobally = 6e7; - this.gasLimitESDTLocalMint = 3e5; - this.gasLimitESDTLocalBurn = 3e5; - this.gasLimitSetSpecialRole = 6e7; - this.gasLimitPausing = 6e7; - this.gasLimitFreezing = 6e7; - this.gasLimitWiping = 6e7; - this.gasLimitESDTNFTCreate = 3e6; - this.gasLimitESDTNFTUpdateAttributes = 1e6; - this.gasLimitESDTNFTAddQuantity = 1e6; - this.gasLimitESDTNFTBurn = 1e6; - this.gasLimitStorePerByte = 5e4; - this.issueCost = "50000000000000000"; - this.esdtContractAddress = address_1.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); - this.chainID = chainID; - } - }; - exports2.TokenOperationsFactoryConfig = TokenOperationsFactoryConfig2; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js -var require_tokenOperationsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/tokenOperationsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenOperationsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var codec_1 = require_codec(); - var TokenOperationsOutcomeParser2 = class { - parseIssueFungible(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "issue"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseIssueNonFungible(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "issueNonFungible"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseIssueSemiFungible(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "issueSemiFungible"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseRegisterMetaESDT(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "registerMetaESDT"); - const tokenIdentifier = this.extractTokenIdentifier(event); - return { tokenIdentifier }; - } - parseRegisterAndSetAllRoles(transaction) { - this.ensureNoError(transaction); - const eventRegister = this.findSingleEventByIdentifier(transaction, "registerAndSetAllRoles"); - const tokenIdentifier = this.extractTokenIdentifier(eventRegister); - const eventSetRole = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); - const roles = eventSetRole.topics.slice(3).map((topic) => topic.valueOf().toString()); - return { tokenIdentifier, roles }; - } - parseSetBurnRoleGlobally(transaction) { - this.ensureNoError(transaction); - return {}; - } - parseUnsetBurnRoleGlobally(transaction) { - this.ensureNoError(transaction); - return {}; - } - parseSetSpecialRole(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTSetRole"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const roles = event.topics.slice(3).map((topic) => topic.valueOf().toString()); - return { userAddress, tokenIdentifier, roles }; - } - parseNFTCreate(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTCreate"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const initialQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, initialQuantity }; - } - parseLocalMint(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalMint"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const mintedSupply = this.extractAmount(event); - return { userAddress, tokenIdentifier, nonce, mintedSupply }; - } - parseLocalBurn(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTLocalBurn"); - const userAddress = event.address.toString(); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntSupply = this.extractAmount(event); - return { userAddress, tokenIdentifier, nonce, burntSupply }; - } - parsePause(transaction) { - this.ensureNoError(transaction); - const _4 = this.findSingleEventByIdentifier(transaction, "ESDTPause"); - return {}; - } - parseUnpause(transaction) { - this.ensureNoError(transaction); - const _4 = this.findSingleEventByIdentifier(transaction, "ESDTUnPause"); - return {}; - } - parseFreeze(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTFreeze"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - parseUnfreeze(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTUnFreeze"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - parseWipe(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTWipe"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - const userAddress = this.extractAddress(event); - return { userAddress, tokenIdentifier, nonce, balance }; - } - parseUpdateAttributes(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTUpdateAttributes"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const attributes = event.topics[3]?.valueOf(); - return { tokenIdentifier, nonce, attributes }; - } - parseAddQuantity(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTAddQuantity"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const addedQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, addedQuantity }; - } - parseBurnQuantity(transaction) { - this.ensureNoError(transaction); - const event = this.findSingleEventByIdentifier(transaction, "ESDTNFTBurn"); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntQuantity = this.extractAmount(event); - return { tokenIdentifier, nonce, burntQuantity }; - } - ensureNoError(transaction) { - for (const event of transaction.logs.events) { - if (event.identifier == "signalError") { - const data = import_buffer.Buffer.from(event.data.substring(1), "hex").toString(); - const message = event.topics[1]?.valueOf().toString(); - throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `encountered signalError: ${message} (${data})`); - } - } - } - findSingleEventByIdentifier(transaction, identifier) { - const events = this.gatherAllEvents(transaction).filter((event) => event.identifier == identifier); - if (events.length == 0) { - throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `cannot find event of type ${identifier}`); - } - if (events.length > 1) { - throw new errors_1.ErrCannotParseTransactionOutcome(transaction.hash, `more than one event of type ${identifier}`); - } - return events[0]; - } - gatherAllEvents(transaction) { - const allEvents = []; - allEvents.push(...transaction.logs.events); - for (const item of transaction.contractResults.items) { - allEvents.push(...item.logs.events); - } - return allEvents; - } - extractTokenIdentifier(event) { - return event.topics[0]?.valueOf().toString(); - } - extractNonce(event) { - return codec_1.bufferToBigInt(event.topics[1]?.valueOf()).toFixed(0); - } - extractAmount(event) { - return codec_1.bufferToBigInt(event.topics[2]?.valueOf()).toFixed(0); - } - extractAddress(event) { - return address_1.Address.fromBuffer(event.topics[3]?.valueOf()).toString(); - } - }; - exports2.TokenOperationsOutcomeParser = TokenOperationsOutcomeParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/tokenOperations/index.js -var require_tokenOperations = __commonJS({ - "node_modules/@multiversx/sdk-core/out/tokenOperations/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_tokenOperationsFactory(), exports2); - __exportStar2(require_tokenOperationsFactoryConfig(), exports2); - __exportStar2(require_tokenOperationsOutcomeParser(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js -var require_delegationTransactionsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/delegationTransactionsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.DelegationTransactionsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var resources_1 = require_resources(); - var DelegationTransactionsOutcomeParser = class { - constructor() { - } - parseCreateNewDelegationContract(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "SCDeploy"); - return events.map((event) => ({ contractAddress: this.extractContractAddress(event) })); - } - ensureNoError(transactionEvents) { - for (const event of transactionEvents) { - if (event.identifier == "signalError") { - const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; - const message = this.decodeTopicAsString(event.topics[1]); - throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); - } - } - } - extractContractAddress(event) { - if (!event.topics[0]?.length) { - return ""; - } - const address = import_buffer.Buffer.from(event.topics[0]); - return address_1.Address.fromBuffer(address).bech32(); - } - decodeTopicAsString(topic) { - return import_buffer.Buffer.from(topic).toString(); - } - }; - exports2.DelegationTransactionsOutcomeParser = DelegationTransactionsOutcomeParser; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js -var require_smartContractTransactionsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/smartContractTransactionsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractTransactionsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var resources_1 = require_resources(); - var SmartContractTransactionsOutcomeParser2 = class { - constructor(options) { - this.abi = options?.abi; - this.legacyResultsParser = options?.legacyResultsParser || new smartcontracts_1.ResultsParser(); - } - parseDeploy(options) { - const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; - const events = resources_1.findEventsByIdentifier(options.transactionOutcome, "SCDeploy"); - const contracts = events.map((event) => this.parseScDeployEvent(event)); - return { - returnCode: directCallOutcome.returnCode, - returnMessage: directCallOutcome.returnMessage, - contracts - }; - } - parseScDeployEvent(event) { - const topicForAddress = event.topics[0]; - const topicForOwnerAddress = event.topics[1]; - const topicForCodeHash = event.topics[2]; - const address = topicForAddress?.length ? new address_1.Address(topicForAddress).toBech32() : ""; - const ownerAddress = topicForOwnerAddress?.length ? new address_1.Address(topicForOwnerAddress).toBech32() : ""; - const codeHash = topicForCodeHash; - return { - address, - ownerAddress, - codeHash - }; - } - parseExecute(options) { - const directCallOutcome = options.transactionOutcome.directSmartContractCallOutcome; - if (!this.abi) { - return { - values: directCallOutcome.returnDataParts, - returnCode: directCallOutcome.returnCode, - returnMessage: directCallOutcome.returnMessage - }; - } - const functionName = options.function || directCallOutcome.function; - if (!functionName) { - throw new errors_1.Err(`Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?`); - } - const endpoint = this.abi.getEndpoint(functionName); - const legacyUntypedBundle = { - returnCode: new smartcontracts_1.ReturnCode(directCallOutcome.returnCode), - returnMessage: directCallOutcome.returnMessage, - values: directCallOutcome.returnDataParts.map((part) => import_buffer.Buffer.from(part)) - }; - const legacyTypedBundle = this.legacyResultsParser.parseOutcomeFromUntypedBundle(legacyUntypedBundle, endpoint); - return { - values: legacyTypedBundle.values.map((value) => value.valueOf()), - returnCode: legacyTypedBundle.returnCode.toString(), - returnMessage: legacyTypedBundle.returnMessage - }; - } - }; - exports2.SmartContractTransactionsOutcomeParser = SmartContractTransactionsOutcomeParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js -var require_tokenManagementTransactionsOutcomeParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/tokenManagementTransactionsOutcomeParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TokenManagementTransactionsOutcomeParser = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var utils_1 = require_utils(); - var resources_1 = require_resources(); - var TokenManagementTransactionsOutcomeParser2 = class { - constructor() { - } - parseIssueFungible(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "issue"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseIssueNonFungible(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueNonFungible"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseIssueSemiFungible(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "issueSemiFungible"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseRegisterMetaEsdt(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "registerMetaESDT"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseRegisterAndSetAllRoles(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const registerEvents = resources_1.findEventsByIdentifier(transactionOutcome, "registerAndSetAllRoles"); - const setRoleEvents = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); - if (registerEvents.length !== setRoleEvents.length) { - throw new errors_1.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events."); - } - return registerEvents.map((registerEvent, index) => { - const tokenIdentifier = this.extractTokenIdentifier(registerEvent); - const encodedRoles = setRoleEvents[index].topics.slice(3); - const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); - return { tokenIdentifier, roles }; - }); - } - parseSetBurnRoleGlobally(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - } - parseUnsetBurnRoleGlobally(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - } - parseSetSpecialRole(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTSetRole"); - return events.map((event) => this.getOutputForSetSpecialRoleEvent(event)); - } - getOutputForSetSpecialRoleEvent(event) { - const userAddress = event.address; - const tokenIdentifier = this.extractTokenIdentifier(event); - const encodedRoles = event.topics.slice(3); - const roles = encodedRoles.map((role) => this.decodeTopicAsString(role)); - return { userAddress, tokenIdentifier, roles }; - } - parseNftCreate(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTCreate"); - return events.map((event) => this.getOutputForNftCreateEvent(event)); - } - getOutputForNftCreateEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const amount = this.extractAmount(event); - return { tokenIdentifier, nonce, initialQuantity: amount }; - } - parseLocalMint(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalMint"); - return events.map((event) => this.getOutputForLocalMintEvent(event)); - } - getOutputForLocalMintEvent(event) { - const userAddress = event.address; - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const mintedSupply = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - mintedSupply - }; - } - parseLocalBurn(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTLocalBurn"); - return events.map((event) => this.getOutputForLocalBurnEvent(event)); - } - getOutputForLocalBurnEvent(event) { - const userAddress = event.address; - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntSupply = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - burntSupply - }; - } - parsePause(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTPause"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseUnpause(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnPause"); - return events.map((event) => ({ tokenIdentifier: this.extractTokenIdentifier(event) })); - } - parseFreeze(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTFreeze"); - return events.map((event) => this.getOutputForFreezeEvent(event)); - } - getOutputForFreezeEvent(event) { - const userAddress = this.extractAddress(event); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - balance - }; - } - parseUnfreeze(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTUnFreeze"); - return events.map((event) => this.getOutputForUnfreezeEvent(event)); - } - getOutputForUnfreezeEvent(event) { - const userAddress = this.extractAddress(event); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - balance - }; - } - parseWipe(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTWipe"); - return events.map((event) => this.getOutputForWipeEvent(event)); - } - getOutputForWipeEvent(event) { - const userAddress = this.extractAddress(event); - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const balance = this.extractAmount(event); - return { - userAddress, - tokenIdentifier, - nonce, - balance - }; - } - parseUpdateAttributes(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTUpdateAttributes"); - return events.map((event) => this.getOutputForUpdateAttributesEvent(event)); - } - getOutputForUpdateAttributesEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const attributes = event.topics[3] ? event.topics[3] : new Uint8Array(); - return { - tokenIdentifier, - nonce, - attributes - }; - } - parseAddQuantity(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTAddQuantity"); - return events.map((event) => this.getOutputForAddQuantityEvent(event)); - } - getOutputForAddQuantityEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const addedQuantity = this.extractAmount(event); - return { - tokenIdentifier, - nonce, - addedQuantity - }; - } - parseBurnQuantity(transactionOutcome) { - this.ensureNoError(transactionOutcome.logs.events); - const events = resources_1.findEventsByIdentifier(transactionOutcome, "ESDTNFTBurn"); - return events.map((event) => this.getOutputForBurnQuantityEvent(event)); - } - getOutputForBurnQuantityEvent(event) { - const tokenIdentifier = this.extractTokenIdentifier(event); - const nonce = this.extractNonce(event); - const burntQuantity = this.extractAmount(event); - return { - tokenIdentifier, - nonce, - burntQuantity - }; - } - ensureNoError(transactionEvents) { - for (const event of transactionEvents) { - if (event.identifier == "signalError") { - const data = import_buffer.Buffer.from(event.dataItems[0]?.toString().slice(1)).toString() || ""; - const message = this.decodeTopicAsString(event.topics[1]); - throw new errors_1.ErrParseTransactionOutcome(`encountered signalError: ${message} (${import_buffer.Buffer.from(data, "hex").toString()})`); - } - } - } - extractTokenIdentifier(event) { - if (!event.topics[0]?.length) { - return ""; - } - return this.decodeTopicAsString(event.topics[0]); - } - extractNonce(event) { - if (!event.topics[1]?.length) { - return BigInt(0); - } - const nonce = import_buffer.Buffer.from(event.topics[1]); - return BigInt(utils_1.bufferToBigInt(nonce).toFixed(0)); - } - extractAmount(event) { - if (!event.topics[2]?.length) { - return BigInt(0); - } - const amount = import_buffer.Buffer.from(event.topics[2]); - return BigInt(utils_1.bufferToBigInt(amount).toFixed(0)); - } - extractAddress(event) { - if (!event.topics[3]?.length) { - return ""; - } - const address = import_buffer.Buffer.from(event.topics[3]); - return address_1.Address.fromBuffer(address).bech32(); - } - decodeTopicAsString(topic) { - return import_buffer.Buffer.from(topic).toString(); - } - }; - exports2.TokenManagementTransactionsOutcomeParser = TokenManagementTransactionsOutcomeParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js -var require_transactionEventsParser = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/transactionEventsParser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionEventsParser = void 0; - var smartcontracts_1 = require_smartcontracts(); - var TransactionEventsParser2 = class { - constructor(options) { - this.legacyResultsParser = new smartcontracts_1.ResultsParser(); - this.abi = options.abi; - this.firstTopicIsIdentifier = options.firstTopicIsIdentifier ?? true; - } - parseEvents(options) { - const results = []; - for (const event of options.events) { - const parsedEvent = this.parseEvent({ event }); - results.push(parsedEvent); - } - return results; - } - parseEvent(options) { - const topics = options.event.topics.map((topic) => import_buffer.Buffer.from(topic)); - const abiIdentifier = this.firstTopicIsIdentifier ? topics[0]?.toString() : options.event.identifier; - if (this.firstTopicIsIdentifier) { - topics.shift(); - } - const dataItems = options.event.dataItems.map((dataItem) => import_buffer.Buffer.from(dataItem)); - const eventDefinition = this.abi.getEvent(abiIdentifier); - const parsedEvent = this.legacyResultsParser.doParseEvent({ - topics, - dataItems, - eventDefinition - }); - return parsedEvent; - } - }; - exports2.TransactionEventsParser = TransactionEventsParser2; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js -var require_transactionsOutcomeParsers = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionsOutcomeParsers/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_delegationTransactionsOutcomeParser(), exports2); - __exportStar2(require_resources(), exports2); - __exportStar2(require_smartContractTransactionsOutcomeParser(), exports2); - __exportStar2(require_tokenManagementTransactionsOutcomeParser(), exports2); - __exportStar2(require_transactionEventsParser(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/account.js -var require_account = __commonJS({ - "node_modules/@multiversx/sdk-core/out/account.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Account = void 0; - var address_1 = require_address(); - var Account5 = class { - /** - * Creates an account object from an address - */ - constructor(address) { - this.address = address_1.Address.empty(); - this.nonce = 0; - this.balance = "0"; - this.address = address; - } - /** - * Updates account properties (such as nonce, balance). - */ - update(obj) { - this.nonce = obj.nonce; - this.balance = obj.balance; - } - /** - * Increments (locally) the nonce (the account sequence number). - */ - incrementNonce() { - this.nonce = this.nonce.valueOf() + 1; - } - /** - * Gets then increments (locally) the nonce (the account sequence number). - */ - getNonceThenIncrement() { - let nonce = this.nonce; - this.nonce = this.nonce.valueOf() + 1; - return nonce; - } - /** - * Converts the account to a pretty, plain JavaScript object. - */ - toJSON() { - return { - address: this.address.bech32(), - nonce: this.nonce.valueOf(), - balance: this.balance.toString() - }; - } - }; - exports2.Account = Account5; - } -}); - -// node_modules/@multiversx/sdk-core/out/message.js -var require_message = __commonJS({ - "node_modules/@multiversx/sdk-core/out/message.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.MessageComputer = exports2.Message = void 0; - var constants_1 = require_constants(); - var address_1 = require_address(); - var createKeccakHash = require_js(); - var Message2 = class { - constructor(options) { - this.data = options.data; - this.signature = options.signature; - this.address = options.address; - this.version = options.version || constants_1.DEFAULT_MESSAGE_VERSION; - this.signer = options.signer || constants_1.SDK_JS_SIGNER; - } - }; - exports2.Message = Message2; - var MessageComputer2 = class { - constructor() { - } - computeBytesForSigning(message) { - const messageSize = import_buffer.Buffer.from(message.data.length.toString()); - const signableMessage = import_buffer.Buffer.concat([messageSize, message.data]); - let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); - return createKeccakHash("keccak256").update(bytesToHash).digest(); - } - computeBytesForVerifying(message) { - return this.computeBytesForSigning(message); - } - packMessage(message) { - return { - message: import_buffer.Buffer.from(message.data).toString("hex"), - signature: message.signature ? import_buffer.Buffer.from(message.signature).toString("hex") : "", - address: message.address ? message.address.bech32() : "", - version: message.version, - signer: message.signer - }; - } - unpackMessage(packedMessage) { - const dataHex = this.trimHexPrefix(packedMessage.message); - const data = import_buffer.Buffer.from(dataHex, "hex"); - const signatureHex = this.trimHexPrefix(packedMessage.signature || ""); - const signature = import_buffer.Buffer.from(signatureHex, "hex"); - let address = void 0; - if (packedMessage.address) { - address = address_1.Address.fromBech32(packedMessage.address); - } - const version2 = packedMessage.version || constants_1.DEFAULT_MESSAGE_VERSION; - const signer = packedMessage.signer || constants_1.UNKNOWN_SIGNER; - return new Message2({ - data, - signature, - address, - version: version2, - signer - }); - } - trimHexPrefix(data) { - if (data.startsWith("0x") || data.startsWith("0X")) { - return data.slice(2); - } - return data; - } - }; - exports2.MessageComputer = MessageComputer2; - } -}); - -// node_modules/@multiversx/sdk-core/out/asyncTimer.js -var require_asyncTimer = __commonJS({ - "node_modules/@multiversx/sdk-core/out/asyncTimer.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.AsyncTimer = void 0; - var errors = __importStar2(require_errors()); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var AsyncTimer = class { - /** - * Creates an AsyncTimer. - */ - constructor(name2) { - this.timeoutHandle = null; - this.rejectionFunc = null; - this.name = name2; - this.correlationTag = 0; - } - /** - * Starts the timer. - * @param timeout The time (in milliseconds) to wait until resolving the promise. - */ - start(timeout) { - if (this.timeoutHandle) { - throw new errors.ErrAsyncTimerAlreadyRunning(); - } - this.correlationTag++; - logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`); - return new Promise((resolve, reject) => { - this.rejectionFunc = reject; - let timeoutCallback = () => { - this.rejectionFunc = null; - this.stop(); - resolve(); - }; - this.timeoutHandle = setTimeout(timeoutCallback, timeout); - }); - } - /** - * Aborts the timer: rejects the promise (if any) and stops the timer. - */ - abort() { - logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`); - if (this.rejectionFunc) { - this.rejectionFunc(new errors_1.ErrAsyncTimerAborted()); - this.rejectionFunc = null; - } - this.stop(); - } - /** - * Stops the timer. - */ - stop() { - if (this.isStopped()) { - return; - } - logger_1.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`); - if (this.timeoutHandle) { - clearTimeout(this.timeoutHandle); - this.timeoutHandle = null; - } - } - /** - * Returns whether the timer is stopped. - */ - isStopped() { - return this.timeoutHandle ? false : true; - } - }; - exports2.AsyncTimer = AsyncTimer; - } -}); - -// node_modules/@multiversx/sdk-core/out/transactionWatcher.js -var require_transactionWatcher = __commonJS({ - "node_modules/@multiversx/sdk-core/out/transactionWatcher.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionWatcher = void 0; - var asyncTimer_1 = require_asyncTimer(); - var constants_1 = require_constants(); - var errors_1 = require_errors(); - var logger_1 = require_logger(); - var TransactionWatcher3 = class _TransactionWatcher { - /** - * A transaction watcher (awaiter). - * - * @param fetcher The transaction fetcher - * @param options The options - * @param options.pollingIntervalMilliseconds The polling interval, in milliseconds - * @param options.timeoutMilliseconds The timeout, in milliseconds - * @param options.patienceMilliseconds The patience: an extra time (in milliseconds) to wait, after the transaction has reached its desired status. Currently there's a delay between the moment a transaction is marked as "completed" and the moment its outcome (contract results, events and logs) is available. - */ - constructor(fetcher, options = {}) { - this.fetcher = new TransactionFetcherWithTracing(fetcher); - this.pollingIntervalMilliseconds = options.pollingIntervalMilliseconds || _TransactionWatcher.DefaultPollingInterval; - this.timeoutMilliseconds = options.timeoutMilliseconds || _TransactionWatcher.DefaultTimeout; - this.patienceMilliseconds = options.patienceMilliseconds || _TransactionWatcher.DefaultPatience; - } - /** - * Waits until the transaction reaches the "pending" status. - * @param txHash The hex-encoded transaction hash - */ - async awaitPending(transactionOrTxHash) { - const isPending = (transaction) => transaction.status.isPending(); - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(isPending, doFetch, errorProvider); - } - /** - * Waits until the transaction is completely processed. - * @param txHash The hex-encoded transaction hash - */ - async awaitCompleted(transactionOrTxHash) { - const isCompleted = (transactionOnNetwork) => { - if (transactionOnNetwork.isCompleted === void 0) { - throw new errors_1.ErrIsCompletedFieldIsMissingOnTransaction(); - } - return transactionOnNetwork.isCompleted; - }; - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(isCompleted, doFetch, errorProvider); - } - async awaitAllEvents(transactionOrTxHash, events) { - const foundAllEvents = (transactionOnNetwork) => { - const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); - const allAreFound = events.every((event) => allEventIdentifiers.includes(event)); - return allAreFound; - }; - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); - return this.awaitConditionally(foundAllEvents, doFetch, errorProvider); - } - async awaitAnyEvent(transactionOrTxHash, events) { - const foundAnyEvent = (transactionOnNetwork) => { - const allEventIdentifiers = this.getAllTransactionEvents(transactionOnNetwork).map((event) => event.identifier); - const anyIsFound = events.find((event) => allEventIdentifiers.includes(event)) != void 0; - return anyIsFound; - }; - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionEventsNotFound(); - return this.awaitConditionally(foundAnyEvent, doFetch, errorProvider); - } - async awaitOnCondition(transactionOrTxHash, condition) { - const doFetch = async () => { - const hash = this.transactionOrTxHashToTxHash(transactionOrTxHash); - return await this.fetcher.getTransaction(hash); - }; - const errorProvider = () => new errors_1.ErrExpectedTransactionStatusNotReached(); - return this.awaitConditionally(condition, doFetch, errorProvider); - } - transactionOrTxHashToTxHash(transactionOrTxHash) { - const hash = typeof transactionOrTxHash === "string" ? transactionOrTxHash : transactionOrTxHash.getHash().hex(); - if (hash.length !== constants_1.HEX_TRANSACTION_HASH_LENGTH) { - throw new errors_1.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${constants_1.HEX_TRANSACTION_HASH_LENGTH}.`); - } - return hash; - } - async awaitConditionally(isSatisfied, doFetch, createError) { - const periodicTimer = new asyncTimer_1.AsyncTimer("watcher:periodic"); - const patienceTimer = new asyncTimer_1.AsyncTimer("watcher:patience"); - const timeoutTimer = new asyncTimer_1.AsyncTimer("watcher:timeout"); - let stop = false; - let fetchedData = void 0; - let satisfied = false; - timeoutTimer.start(this.timeoutMilliseconds).finally(() => { - timeoutTimer.stop(); - stop = true; - }); - while (!stop) { - await periodicTimer.start(this.pollingIntervalMilliseconds); - try { - fetchedData = await doFetch(); - satisfied = isSatisfied(fetchedData); - if (satisfied || stop) { - break; - } - } catch (error) { - logger_1.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."); - if (error instanceof errors_1.ErrIsCompletedFieldIsMissingOnTransaction) { - throw error; - } - if (!(error instanceof errors_1.Err)) { - throw error; - } - } - } - if (satisfied) { - await patienceTimer.start(this.patienceMilliseconds); - } - if (!timeoutTimer.isStopped()) { - timeoutTimer.stop(); - } - if (!fetchedData || !satisfied) { - throw createError(); - } - return fetchedData; - } - getAllTransactionEvents(transaction) { - const result = [...transaction.logs.events]; - for (const resultItem of transaction.contractResults.items) { - result.push(...resultItem.logs.events); - } - return result; - } - }; - exports2.TransactionWatcher = TransactionWatcher3; - TransactionWatcher3.DefaultPollingInterval = 6e3; - TransactionWatcher3.DefaultTimeout = TransactionWatcher3.DefaultPollingInterval * 15; - TransactionWatcher3.DefaultPatience = 0; - TransactionWatcher3.NoopOnStatusReceived = (_4) => { - }; - var TransactionFetcherWithTracing = class { - constructor(fetcher) { - this.fetcher = fetcher; - } - async getTransaction(txHash) { - logger_1.Logger.debug(`transactionWatcher, getTransaction(${txHash})`); - return await this.fetcher.getTransaction(txHash); - } - }; - } -}); - -// node_modules/@multiversx/sdk-core/out/signableMessage.js -var require_signableMessage = __commonJS({ - "node_modules/@multiversx/sdk-core/out/signableMessage.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SignableMessage = void 0; - var address_1 = require_address(); - var signature_1 = require_signature(); - var constants_1 = require_constants(); - var createKeccakHash = require_js(); - var SignableMessage3 = class { - constructor(init) { - this.message = import_buffer.Buffer.from([]); - this.signature = import_buffer.Buffer.from([]); - this.version = 1; - this.signer = "ErdJS"; - this.address = address_1.Address.empty(); - Object.assign(this, init); - } - serializeForSigning() { - const messageSize = import_buffer.Buffer.from(this.message.length.toString()); - const signableMessage = import_buffer.Buffer.concat([messageSize, this.message]); - let bytesToHash = import_buffer.Buffer.concat([import_buffer.Buffer.from(constants_1.MESSAGE_PREFIX), signableMessage]); - return createKeccakHash("keccak256").update(bytesToHash).digest(); - } - serializeForSigningRaw() { - return import_buffer.Buffer.concat([this.getMessageSize(), this.message]); - } - getSignature() { - return this.signature; - } - applySignature(signature) { - this.signature = signature_1.interpretSignatureAsBuffer(signature); - } - getMessageSize() { - const messageSize = import_buffer.Buffer.alloc(4); - messageSize.writeUInt32BE(this.message.length, 0); - return messageSize; - } - toJSON() { - return { - address: this.address.bech32(), - message: "0x" + this.message.toString("hex"), - signature: "0x" + this.signature.toString("hex"), - version: this.version, - signer: this.signer - }; - } - }; - exports2.SignableMessage = SignableMessage3; - } -}); - -// node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js -var require_bignumber2 = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/node_modules/bignumber.js/bignumber.js"(exports2, module2) { - init_shim(); - (function(globalObject) { - "use strict"; - var BigNumber2, isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil2 = Math.ceil, mathfloor2 = Math.floor, bignumberError2 = "[BigNumber Error] ", tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: ", BASE2 = 1e14, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE2 = 1e7, MAX2 = 1e9; - function clone2(configObject) { - var div, convertBase, parseNumeric, P2 = BigNumber3.prototype = { constructor: BigNumber3, toString: null, valueOf: null }, ONE = new BigNumber3(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; - function BigNumber3(v2, b4) { - var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; - if (!(x3 instanceof BigNumber3)) - return new BigNumber3(v2, b4); - if (b4 == null) { - if (v2 && v2._isBigNumber === true) { - x3.s = v2.s; - if (!v2.c || v2.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (v2.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = v2.e; - x3.c = v2.c.slice(); - } - return; - } - if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { - x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; - if (v2 === ~~v2) { - for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x3.c = x3.e = null; - } else { - x3.e = e2; - x3.c = [v2]; - } - return; - } - str = String(v2); - } else { - if (!isNumeric2.test(str = String(v2))) - return parseNumeric(x3, str, isNum); - x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i2 = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i2; - e2 += +str.slice(i2 + 1); - str = str.substring(0, i2); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - if (b4 == 10) { - x3 = new BigNumber3(v2); - return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); - } - str = String(v2); - if (isNum = typeof v2 == "number") { - if (v2 * 0 != 0) - return parseNumeric(x3, str, isNum, b4); - x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber3.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits2 + v2); - } - } else { - x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b4); - e2 = i2 = 0; - for (len = str.length; i2 < len; i2++) { - if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { - if (c4 == ".") { - if (i2 > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i2 = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x3, String(v2), isNum, b4); - } - } - isNum = false; - str = convertBase(str, b4, 10, x3.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i2 = 0; str.charCodeAt(i2) === 48; i2++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i2, ++len)) { - len -= i2; - if (isNum && BigNumber3.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER2 || v2 !== mathfloor2(v2))) { - throw Error(tooManyDigits2 + x3.s * v2); - } - if ((e2 = e2 - i2 - 1) > MAX_EXP) { - x3.c = x3.e = null; - } else if (e2 < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = e2; - x3.c = []; - i2 = (e2 + 1) % LOG_BASE2; - if (e2 < 0) - i2 += LOG_BASE2; - if (i2 < len) { - if (i2) - x3.c.push(+str.slice(0, i2)); - for (len -= LOG_BASE2; i2 < len; ) { - x3.c.push(+str.slice(i2, i2 += LOG_BASE2)); - } - i2 = LOG_BASE2 - (str = str.slice(i2)).length; - } else { - i2 -= len; - } - for (; i2--; str += "0") - ; - x3.c.push(+str); - } - } else { - x3.c = [x3.e = 0]; - } - } - BigNumber3.clone = clone2; - BigNumber3.ROUND_UP = 0; - BigNumber3.ROUND_DOWN = 1; - BigNumber3.ROUND_CEIL = 2; - BigNumber3.ROUND_FLOOR = 3; - BigNumber3.ROUND_HALF_UP = 4; - BigNumber3.ROUND_HALF_DOWN = 5; - BigNumber3.ROUND_HALF_EVEN = 6; - BigNumber3.ROUND_HALF_CEIL = 7; - BigNumber3.ROUND_HALF_FLOOR = 8; - BigNumber3.EUCLID = 9; - BigNumber3.config = BigNumber3.set = function(obj) { - var p3, v2; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - DECIMAL_PLACES = v2; - } - if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 8, p3); - ROUNDING_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, 0, p3); - intCheck2(v2[1], 0, MAX2, p3); - TO_EXP_NEG = v2[0]; - TO_EXP_POS = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); - } - } - if (obj.hasOwnProperty(p3 = "RANGE")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck2(v2[0], -MAX2, -1, p3); - intCheck2(v2[1], 1, MAX2, p3); - MIN_EXP = v2[0]; - MAX_EXP = v2[1]; - } else { - intCheck2(v2, -MAX2, MAX2, p3); - if (v2) { - MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); - } else { - throw Error(bignumberError2 + p3 + " cannot be zero: " + v2); - } - } - } - if (obj.hasOwnProperty(p3 = "CRYPTO")) { - v2 = obj[p3]; - if (v2 === !!v2) { - if (v2) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v2; - } else { - CRYPTO = !v2; - throw Error(bignumberError2 + "crypto unavailable"); - } - } else { - CRYPTO = v2; - } - } else { - throw Error(bignumberError2 + p3 + " not true or false: " + v2); - } - } - if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { - v2 = obj[p3]; - intCheck2(v2, 0, 9, p3); - MODULO_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { - v2 = obj[p3]; - intCheck2(v2, 0, MAX2, p3); - POW_PRECISION = v2; - } - if (obj.hasOwnProperty(p3 = "FORMAT")) { - v2 = obj[p3]; - if (typeof v2 == "object") - FORMAT = v2; - else - throw Error(bignumberError2 + p3 + " not an object: " + v2); - } - if (obj.hasOwnProperty(p3 = "ALPHABET")) { - v2 = obj[p3]; - if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { - ALPHABET = v2; - } else { - throw Error(bignumberError2 + p3 + " invalid: " + v2); - } - } - } else { - throw Error(bignumberError2 + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber3.isBigNumber = function(v2) { - if (!v2 || v2._isBigNumber !== true) - return false; - if (!BigNumber3.DEBUG) - return true; - var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; - out: - if ({}.toString.call(c4) == "[object Array]") { - if ((s2 === 1 || s2 === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { - if (c4[0] === 0) { - if (e2 === 0 && c4.length === 1) - return true; - break out; - } - i2 = (e2 + 1) % LOG_BASE2; - if (i2 < 1) - i2 += LOG_BASE2; - if (String(c4[0]).length == i2) { - for (i2 = 0; i2 < c4.length; i2++) { - n3 = c4[i2]; - if (n3 < 0 || n3 >= BASE2 || n3 !== mathfloor2(n3)) - break out; - } - if (n3 !== 0) - return true; - } - } - } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { - return true; - } - throw Error(bignumberError2 + "Invalid BigNumber: " + v2); - }; - BigNumber3.maximum = BigNumber3.max = function() { - return maxOrMin(arguments, P2.lt); - }; - BigNumber3.minimum = BigNumber3.min = function() { - return maxOrMin(arguments, P2.gt); - }; - BigNumber3.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor2(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber3(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck2(dp, 0, MAX2); - k4 = mathceil2(dp / LOG_BASE2); - if (CRYPTO) { - if (crypto.getRandomValues) { - a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); - for (; i2 < k4; ) { - v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); - if (v2 >= 9e15) { - b4 = crypto.getRandomValues(new Uint32Array(2)); - a3[i2] = b4[0]; - a3[i2 + 1] = b4[1]; - } else { - c4.push(v2 % 1e14); - i2 += 2; - } - } - i2 = k4 / 2; - } else if (crypto.randomBytes) { - a3 = crypto.randomBytes(k4 *= 7); - for (; i2 < k4; ) { - v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; - if (v2 >= 9e15) { - crypto.randomBytes(7).copy(a3, i2); - } else { - c4.push(v2 % 1e14); - i2 += 7; - } - } - i2 = k4 / 7; - } else { - CRYPTO = false; - throw Error(bignumberError2 + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (; i2 < k4; ) { - v2 = random53bitInt(); - if (v2 < 9e15) - c4[i2++] = v2 % 1e14; - } - } - k4 = c4[--i2]; - dp %= LOG_BASE2; - if (k4 && dp) { - v2 = POWS_TEN2[LOG_BASE2 - dp]; - c4[i2] = mathfloor2(k4 / v2) * v2; - } - for (; c4[i2] === 0; c4.pop(), i2--) - ; - if (i2 < 0) { - c4 = [e2 = 0]; - } else { - for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE2) - ; - for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) - ; - if (i2 < LOG_BASE2) - e2 -= LOG_BASE2 - i2; - } - rand.e = e2; - rand.c = c4; - return rand; - }; - }(); - BigNumber3.sum = function() { - var i2 = 1, args = arguments, sum = new BigNumber3(args[0]); - for (; i2 < args.length; ) - sum = sum.plus(args[i2++]); - return sum; - }; - convertBase = /* @__PURE__ */ function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j2, arr = [0], arrL, i2 = 0, len = str.length; - for (; i2 < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i2++)); - for (j2 = 0; j2 < arr.length; j2++) { - if (arr[j2] > baseOut - 1) { - if (arr[j2 + 1] == null) - arr[j2 + 1] = 0; - arr[j2 + 1] += arr[j2] / baseOut | 0; - arr[j2] %= baseOut; - } - } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign2, callerIsToString) { - var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i2 >= 0) { - k4 = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y4 = new BigNumber3(baseIn); - x3 = y4.pow(str.length - i2); - POW_PRECISION = k4; - y4.c = toBaseOut( - toFixedPoint2(coeffToString2(x3.c), x3.e, "0"), - 10, - baseOut, - decimal - ); - y4.e = y4.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k4 = xc.length; - for (; xc[--k4] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i2 < 0) { - --e2; - } else { - x3.c = xc; - x3.e = e2; - x3.s = sign2; - x3 = div(x3, y4, dp, rm, baseOut); - xc = x3.c; - r = x3.r; - e2 = x3.e; - } - d3 = e2 + dp + 1; - i2 = xc[d3]; - k4 = baseOut / 2; - r = r || d3 < 0 || xc[d3 + 1] != null; - r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (d3 < 1 || !xc[0]) { - str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d3; - if (r) { - for (--baseOut; ++xc[--d3] > baseOut; ) { - xc[d3] = 0; - if (!d3) { - ++e2; - xc = [1].concat(xc); - } - } - } - for (k4 = xc.length; !xc[--k4]; ) - ; - for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) - ; - str = toFixedPoint2(str, e2, alphabet2.charAt(0)); - } - return str; - }; - }(); - div = /* @__PURE__ */ function() { - function multiply(x3, k4, base3) { - var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE2, khi = k4 / SQRT_BASE2 | 0; - for (x3 = x3.slice(); i2--; ) { - xlo = x3[i2] % SQRT_BASE2; - xhi = x3[i2] / SQRT_BASE2 | 0; - m3 = khi * xlo + xhi * klo; - temp = klo * xlo + m3 % SQRT_BASE2 * SQRT_BASE2 + carry; - carry = (temp / base3 | 0) + (m3 / SQRT_BASE2 | 0) + khi * xhi; - x3[i2] = temp % base3; - } - if (carry) - x3 = [carry].concat(x3); - return x3; - } - function compare4(a3, b4, aL, bL) { - var i2, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i2 = cmp = 0; i2 < aL; i2++) { - if (a3[i2] != b4[i2]) { - cmp = a3[i2] > b4[i2] ? 1 : -1; - break; - } - } - } - return cmp; - } - function subtract(a3, b4, aL, base3) { - var i2 = 0; - for (; aL--; ) { - a3[aL] -= i2; - i2 = a3[aL] < b4[aL] ? 1 : 0; - a3[aL] = i2 * base3 + a3[aL] - b4[aL]; - } - for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) - ; - } - return function(x3, y4, dp, rm, base3) { - var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber3( - // Return NaN if either NaN, or both Infinity or 0. - !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 - ) - ); - } - q2 = new BigNumber3(s2); - qc = q2.c = []; - e2 = x3.e - y4.e; - s2 = dp + e2 + 1; - if (!base3) { - base3 = BASE2; - e2 = bitFloor2(x3.e / LOG_BASE2) - bitFloor2(y4.e / LOG_BASE2); - s2 = s2 / LOG_BASE2 | 0; - } - for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) - ; - if (yc[i2] > (xc[i2] || 0)) - e2--; - if (s2 < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i2 = 0; - s2 += 2; - n3 = mathfloor2(base3 / (yc[0] + 1)); - if (n3 > 1) { - yc = multiply(yc, n3, base3); - xc = multiply(xc, n3, base3); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base3 / 2) - yc0++; - do { - n3 = 0; - cmp = compare4(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base3 + (rem[1] || 0); - n3 = mathfloor2(rem0 / yc0); - if (n3 > 1) { - if (n3 >= base3) - n3 = base3 - 1; - prod = multiply(yc, n3, base3); - prodL = prod.length; - remL = rem.length; - while (compare4(prod, rem, prodL, remL) == 1) { - n3--; - subtract(prod, yL < prodL ? yz : yc, prodL, base3); - prodL = prod.length; - cmp = 1; - } - } else { - if (n3 == 0) { - cmp = n3 = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base3); - remL = rem.length; - if (cmp == -1) { - while (compare4(yc, rem, yL, remL) < 1) { - n3++; - subtract(rem, yL < remL ? yz : yc, remL, base3); - remL = rem.length; - } - } - } else if (cmp === 0) { - n3++; - rem = [0]; - } - qc[i2++] = n3; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s2--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base3 == BASE2) { - for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) - ; - round(q2, dp + (q2.e = i2 + e2 * LOG_BASE2 - 1) + 1, rm, more); - } else { - q2.e = e2; - q2.r = +more; - } - return q2; - }; - }(); - function format(n3, i2, rm, id) { - var c0, e2, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - if (!n3.c) - return n3.toString(); - c0 = n3.c[0]; - ne = n3.e; - if (i2 == null) { - str = coeffToString2(n3.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential2(str, ne) : toFixedPoint2(str, ne, "0"); - } else { - n3 = round(new BigNumber3(n3), i2, rm); - e2 = n3.e; - str = coeffToString2(n3.c); - len = str.length; - if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { - for (; len < i2; str += "0", len++) - ; - str = toExponential2(str, e2); - } else { - i2 -= ne; - str = toFixedPoint2(str, e2, "0"); - if (e2 + 1 > len) { - if (--i2 > 0) - for (str += "."; i2--; str += "0") - ; - } else { - i2 += e2 - len; - if (i2 > 0) { - if (e2 + 1 == len) - str += "."; - for (; i2--; str += "0") - ; - } - } - } - } - return n3.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, method) { - var n3, i2 = 1, m3 = new BigNumber3(args[0]); - for (; i2 < args.length; i2++) { - n3 = new BigNumber3(args[i2]); - if (!n3.s) { - m3 = n3; - break; - } else if (method.call(m3, n3)) { - m3 = n3; - } - } - return m3; - } - function normalise(n3, c4, e2) { - var i2 = 1, j2 = c4.length; - for (; !c4[--j2]; c4.pop()) - ; - for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) - ; - if ((e2 = i2 + e2 * LOG_BASE2 - 1) > MAX_EXP) { - n3.c = n3.e = null; - } else if (e2 < MIN_EXP) { - n3.c = [n3.e = 0]; - } else { - n3.e = e2; - n3.c = c4; - } - return n3; - } - parseNumeric = /* @__PURE__ */ function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x3, str, isNum, b4) { - var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s2)) { - x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; - } else { - if (!isNum) { - s2 = s2.replace(basePrefix, function(m3, p1, p22) { - base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; - return !b4 || b4 == base3 ? p1 : m3; - }); - if (b4) { - base3 = b4; - s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s2) - return new BigNumber3(s2, base3); - } - if (BigNumber3.DEBUG) { - throw Error(bignumberError2 + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); - } - x3.s = null; - } - x3.c = x3.e = null; - }; - }(); - function round(x3, sd, rm, r) { - var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN2; - if (xc) { - out: { - for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) - ; - i2 = sd - d3; - if (i2 < 0) { - i2 += LOG_BASE2; - j2 = sd; - n3 = xc[ni = 0]; - rd = n3 / pows10[d3 - j2 - 1] % 10 | 0; - } else { - ni = mathceil2((i2 + 1) / LOG_BASE2); - if (ni >= xc.length) { - if (r) { - for (; xc.length <= ni; xc.push(0)) - ; - n3 = rd = 0; - d3 = 1; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + 1; - } else { - break out; - } - } else { - n3 = k4 = xc[ni]; - for (d3 = 1; k4 >= 10; k4 /= 10, d3++) - ; - i2 %= LOG_BASE2; - j2 = i2 - LOG_BASE2 + d3; - rd = j2 < 0 ? 0 : n3 / pows10[d3 - j2 - 1] % 10 | 0; - } - } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x3.e + 1; - xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; - x3.e = -sd || 0; - } else { - xc[0] = x3.e = 0; - } - return x3; - } - if (i2 == 0) { - xc.length = ni; - k4 = 1; - ni--; - } else { - xc.length = ni + 1; - k4 = pows10[LOG_BASE2 - i2]; - xc[ni] = j2 > 0 ? mathfloor2(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; - } - if (r) { - for (; ; ) { - if (ni == 0) { - for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) - ; - j2 = xc[0] += k4; - for (k4 = 1; j2 >= 10; j2 /= 10, k4++) - ; - if (i2 != k4) { - x3.e++; - if (xc[0] == BASE2) - xc[0] = 1; - } - break; - } else { - xc[ni] += k4; - if (xc[ni] != BASE2) - break; - xc[ni--] = 0; - k4 = 1; - } - } - } - for (i2 = xc.length; xc[--i2] === 0; xc.pop()) - ; - } - if (x3.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (x3.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } - } - return x3; - } - function valueOf(n3) { - var str, e2 = n3.e; - if (e2 === null) - return n3.toString(); - str = coeffToString2(n3.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); - return n3.s < 0 ? "-" + str : str; - } - P2.absoluteValue = P2.abs = function() { - var x3 = new BigNumber3(this); - if (x3.s < 0) - x3.s = 1; - return x3; - }; - P2.comparedTo = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)); - }; - P2.decimalPlaces = P2.dp = function(dp, rm) { - var c4, n3, v2, x3 = this; - if (dp != null) { - intCheck2(dp, 0, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), dp + x3.e + 1, rm); - } - if (!(c4 = x3.c)) - return null; - n3 = ((v2 = c4.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; - if (v2 = c4[v2]) - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - if (n3 < 0) - n3 = 0; - return n3; - }; - P2.dividedBy = P2.div = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); - }; - P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { - return div(this, new BigNumber3(y4, b4), 0, 1); - }; - P2.exponentiatedBy = P2.pow = function(n3, m3) { - var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; - n3 = new BigNumber3(n3); - if (n3.c && !n3.isInteger()) { - throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n3)); - } - if (m3 != null) - m3 = new BigNumber3(m3); - nIsBig = n3.e > 14; - if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { - y4 = new BigNumber3(Math.pow(+valueOf(x3), nIsBig ? 2 - isOdd2(n3) : +valueOf(n3))); - return m3 ? y4.mod(m3) : y4; - } - nIsNeg = n3.s < 0; - if (m3) { - if (m3.c ? !m3.c[0] : !m3.s) - return new BigNumber3(NaN); - isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); - if (isModExp) - x3 = x3.mod(m3); - } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { - k4 = x3.s < 0 && isOdd2(n3) ? -0 : 0; - if (x3.e > -1) - k4 = 1 / k4; - return new BigNumber3(nIsNeg ? 1 / k4 : k4); - } else if (POW_PRECISION) { - k4 = mathceil2(POW_PRECISION / LOG_BASE2 + 2); - } - if (nIsBig) { - half = new BigNumber3(0.5); - if (nIsNeg) - n3.s = 1; - nIsOdd = isOdd2(n3); - } else { - i2 = Math.abs(+valueOf(n3)); - nIsOdd = i2 % 2; - } - y4 = new BigNumber3(ONE); - for (; ; ) { - if (nIsOdd) { - y4 = y4.times(x3); - if (!y4.c) - break; - if (k4) { - if (y4.c.length > k4) - y4.c.length = k4; - } else if (isModExp) { - y4 = y4.mod(m3); - } - } - if (i2) { - i2 = mathfloor2(i2 / 2); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } else { - n3 = n3.times(half); - round(n3, n3.e + 1, 1); - if (n3.e > 14) { - nIsOdd = isOdd2(n3); - } else { - i2 = +valueOf(n3); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } - } - x3 = x3.times(x3); - if (k4) { - if (x3.c && x3.c.length > k4) - x3.c.length = k4; - } else if (isModExp) { - x3 = x3.mod(m3); - } - } - if (isModExp) - return y4; - if (nIsNeg) - y4 = ONE.div(y4); - return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; - }; - P2.integerValue = function(rm) { - var n3 = new BigNumber3(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(n3, n3.e + 1, rm); - }; - P2.isEqualTo = P2.eq = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) === 0; - }; - P2.isFinite = function() { - return !!this.c; - }; - P2.isGreaterThan = P2.gt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) > 0; - }; - P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === 1 || b4 === 0; - }; - P2.isInteger = function() { - return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; - }; - P2.isLessThan = P2.lt = function(y4, b4) { - return compare3(this, new BigNumber3(y4, b4)) < 0; - }; - P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { - return (b4 = compare3(this, new BigNumber3(y4, b4))) === -1 || b4 === 0; - }; - P2.isNaN = function() { - return !this.s; - }; - P2.isNegative = function() { - return this.s < 0; - }; - P2.isPositive = function() { - return this.s > 0; - }; - P2.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P2.minus = function(y4, b4) { - var i2, j2, t, xLTy, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.plus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y4.s = -b4, y4) : new BigNumber3(yc ? x3 : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y4.s = -b4, y4) : new BigNumber3(xc[0] ? x3 : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); - } - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (xLTy = a3 < 0) { - a3 = -a3; - t = xc; - } else { - ye = xe; - t = yc; - } - t.reverse(); - for (b4 = a3; b4--; t.push(0)) - ; - t.reverse(); - } else { - j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; - for (a3 = b4 = 0; b4 < j2; b4++) { - if (xc[b4] != yc[b4]) { - xLTy = xc[b4] < yc[b4]; - break; - } - } - } - if (xLTy) - t = xc, xc = yc, yc = t, y4.s = -y4.s; - b4 = (j2 = yc.length) - (i2 = xc.length); - if (b4 > 0) - for (; b4--; xc[i2++] = 0) - ; - b4 = BASE2 - 1; - for (; j2 > a3; ) { - if (xc[--j2] < yc[j2]) { - for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) - ; - --xc[i2]; - xc[j2] += BASE2; - } - xc[j2] -= yc[j2]; - } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y4.s = ROUNDING_MODE == 3 ? -1 : 1; - y4.c = [y4.e = 0]; - return y4; - } - return normalise(y4, xc, ye); - }; - P2.modulo = P2.mod = function(y4, b4) { - var q2, s2, x3 = this; - y4 = new BigNumber3(y4, b4); - if (!x3.c || !y4.s || y4.c && !y4.c[0]) { - return new BigNumber3(NaN); - } else if (!y4.c || x3.c && !x3.c[0]) { - return new BigNumber3(x3); - } - if (MODULO_MODE == 9) { - s2 = y4.s; - y4.s = 1; - q2 = div(x3, y4, 0, 3); - y4.s = s2; - q2.s *= s2; - } else { - q2 = div(x3, y4, 0, MODULO_MODE); - } - y4 = x3.minus(q2.times(y4)); - if (!y4.c[0] && MODULO_MODE == 1) - y4.s = x3.s; - return y4; - }; - P2.multipliedBy = P2.times = function(y4, b4) { - var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber3(y4, b4)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y4.c = y4.e = y4.s = null; - } else { - y4.s *= x3.s; - if (!xc || !yc) { - y4.c = y4.e = null; - } else { - y4.c = [0]; - y4.e = 0; - } - } - return y4; - } - e2 = bitFloor2(x3.e / LOG_BASE2) + bitFloor2(y4.e / LOG_BASE2); - y4.s *= x3.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) - zc = xc, xc = yc, yc = zc, i2 = xcL, xcL = ycL, ycL = i2; - for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) - ; - base3 = BASE2; - sqrtBase = SQRT_BASE2; - for (i2 = ycL; --i2 >= 0; ) { - c4 = 0; - ylo = yc[i2] % sqrtBase; - yhi = yc[i2] / sqrtBase | 0; - for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { - xlo = xc[--k4] % sqrtBase; - xhi = xc[k4] / sqrtBase | 0; - m3 = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; - c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; - zc[j2--] = xlo % base3; - } - zc[j2] = c4; - } - if (c4) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y4, zc, e2); - }; - P2.negated = function() { - var x3 = new BigNumber3(this); - x3.s = -x3.s || null; - return x3; - }; - P2.plus = function(y4, b4) { - var t, x3 = this, a3 = x3.s; - y4 = new BigNumber3(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber3(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.minus(y4); - } - var xe = x3.e / LOG_BASE2, ye = y4.e / LOG_BASE2, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber3(a3 / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y4 : new BigNumber3(xc[0] ? x3 : a3 * 0); - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (a3 > 0) { - ye = xe; - t = yc; - } else { - a3 = -a3; - t = xc; - } - t.reverse(); - for (; a3--; t.push(0)) - ; - t.reverse(); - } - a3 = xc.length; - b4 = yc.length; - if (a3 - b4 < 0) - t = yc, yc = xc, xc = t, b4 = a3; - for (a3 = 0; b4; ) { - a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE2 | 0; - xc[b4] = BASE2 === xc[b4] ? 0 : xc[b4] % BASE2; - } - if (a3) { - xc = [a3].concat(xc); - ++ye; - } - return normalise(y4, xc, ye); - }; - P2.precision = P2.sd = function(sd, rm) { - var c4, n3, v2, x3 = this; - if (sd != null && sd !== !!sd) { - intCheck2(sd, 1, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber3(x3), sd, rm); - } - if (!(c4 = x3.c)) - return null; - v2 = c4.length - 1; - n3 = v2 * LOG_BASE2 + 1; - if (v2 = c4[v2]) { - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) - ; - } - if (sd && x3.e + 1 > n3) - n3 = x3.e + 1; - return n3; - }; - P2.shiftedBy = function(k4) { - intCheck2(k4, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); - return this.times("1e" + k4); - }; - P2.squareRoot = P2.sqrt = function() { - var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber3("0.5"); - if (s2 !== 1 || !c4 || !c4[0]) { - return new BigNumber3(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); - } - s2 = Math.sqrt(+valueOf(x3)); - if (s2 == 0 || s2 == 1 / 0) { - n3 = coeffToString2(c4); - if ((n3.length + e2) % 2 == 0) - n3 += "0"; - s2 = Math.sqrt(+n3); - e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s2 == 1 / 0) { - n3 = "5e" + e2; - } else { - n3 = s2.toExponential(); - n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; - } - r = new BigNumber3(n3); - } else { - r = new BigNumber3(s2 + ""); - } - if (r.c[0]) { - e2 = r.e; - s2 = e2 + dp; - if (s2 < 3) - s2 = 0; - for (; ; ) { - t = r; - r = half.times(t.plus(div(x3, t, dp, 1))); - if (coeffToString2(t.c).slice(0, s2) === (n3 = coeffToString2(r.c)).slice(0, s2)) { - if (r.e < e2) - --s2; - n3 = n3.slice(s2 - 3, s2 + 1); - if (n3 == "9999" || !rep && n3 == "4999") { - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - if (t.times(t).eq(x3)) { - r = t; - break; - } - } - dp += 4; - s2 += 4; - rep = 1; - } else { - if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m3 = !r.times(r).eq(x3); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); - }; - P2.toExponential = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp++; - } - return format(this, dp, rm, 1); - }; - P2.toFixed = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P2.toFormat = function(dp, rm, format2) { - var str, x3 = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError2 + "Argument not an object: " + format2); - } - str = x3.toFixed(dp, rm); - if (x3.c) { - var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g22) - i2 = g1, g1 = g22, g22 = i2, len -= i2; - if (g1 > 0 && len > 0) { - i2 = len % g1 || g1; - intPart = intDigits.substr(0, i2); - for (; i2 < len; i2 += g1) - intPart += groupSeparator + intDigits.substr(i2, g1); - if (g22 > 0) - intPart += groupSeparator + intDigits.slice(i2); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g22 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P2.toFraction = function(md) { - var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; - if (md != null) { - n3 = new BigNumber3(md); - if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { - throw Error(bignumberError2 + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); - } - } - if (!xc) - return new BigNumber3(x3); - d3 = new BigNumber3(ONE); - n1 = d0 = new BigNumber3(ONE); - d1 = n0 = new BigNumber3(ONE); - s2 = coeffToString2(xc); - e2 = d3.e = s2.length - x3.e - 1; - d3.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; - md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n3 = new BigNumber3(s2); - n0.c[0] = 0; - for (; ; ) { - q2 = div(n3, d3, 0, 1); - d22 = d0.plus(q2.times(d1)); - if (d22.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d22; - n1 = n0.plus(q2.times(d22 = n1)); - n0 = d22; - d3 = n3.minus(q2.times(d22 = d3)); - n3 = d22; - } - d22 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d22.times(n1)); - d0 = d0.plus(d22.times(d1)); - n0.s = n1.s = x3.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( - div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() - ) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P2.toNumber = function() { - return +valueOf(this); - }; - P2.toPrecision = function(sd, rm) { - if (sd != null) - intCheck2(sd, 1, MAX2); - return format(this, sd, rm, 2); - }; - P2.toString = function(b4) { - var str, n3 = this, s2 = n3.s, e2 = n3.e; - if (e2 === null) { - if (s2) { - str = "Infinity"; - if (s2 < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b4 == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n3.c), e2) : toFixedPoint2(coeffToString2(n3.c), e2, "0"); - } else if (b4 === 10) { - n3 = round(new BigNumber3(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint2(coeffToString2(n3.c), n3.e, "0"); - } else { - intCheck2(b4, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint2(coeffToString2(n3.c), e2, "0"), 10, b4, s2, true); - } - if (s2 < 0 && n3.c[0]) - str = "-" + str; - } - return str; - }; - P2.valueOf = P2.toJSON = function() { - return valueOf(this); - }; - P2._isBigNumber = true; - if (configObject != null) - BigNumber3.set(configObject); - return BigNumber3; - } - function bitFloor2(n3) { - var i2 = n3 | 0; - return n3 > 0 || n3 === i2 ? i2 : i2 - 1; - } - function coeffToString2(a3) { - var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; - for (; i2 < j2; ) { - s2 = a3[i2++] + ""; - z3 = LOG_BASE2 - s2.length; - for (; z3--; s2 = "0" + s2) - ; - r += s2; - } - for (j2 = r.length; r.charCodeAt(--j2) === 48; ) - ; - return r.slice(0, j2 + 1 || 1); - } - function compare3(x3, y4) { - var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; - if (!i2 || !j2) - return null; - a3 = xc && !xc[0]; - b4 = yc && !yc[0]; - if (a3 || b4) - return a3 ? b4 ? 0 : -j2 : i2; - if (i2 != j2) - return i2; - a3 = i2 < 0; - b4 = k4 == l4; - if (!xc || !yc) - return b4 ? 0 : !xc ^ a3 ? 1 : -1; - if (!b4) - return k4 > l4 ^ a3 ? 1 : -1; - j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; - for (i2 = 0; i2 < j2; i2++) - if (xc[i2] != yc[i2]) - return xc[i2] > yc[i2] ^ a3 ? 1 : -1; - return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; - } - function intCheck2(n3, min, max, name2) { - if (n3 < min || n3 > max || n3 !== mathfloor2(n3)) { - throw Error(bignumberError2 + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); - } - } - function isOdd2(n3) { - var k4 = n3.c.length - 1; - return bitFloor2(n3.e / LOG_BASE2) == k4 && n3.c[k4] % 2 != 0; - } - function toExponential2(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; - } - function toFixedPoint2(str, e2, z3) { - var len, zs; - if (e2 < 0) { - for (zs = z3 + "."; ++e2; zs += z3) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z3, e2 -= len; --e2; zs += z3) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } - } - return str; - } - BigNumber2 = clone2(); - BigNumber2["default"] = BigNumber2.BigNumber = BigNumber2; - if (typeof define == "function" && define.amd) { - define(function() { - return BigNumber2; - }); - } else if (typeof module2 != "undefined" && module2.exports) { - module2.exports = BigNumber2; - } else { - if (!globalObject) { - globalObject = typeof self != "undefined" && self ? self : window; - } - globalObject.BigNumber = BigNumber2; - } - })(exports2); - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/primitives.js -var require_primitives = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/primitives.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o2, v2) { - Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); - } : function(o2, v2) { - o2["default"] = v2; - }); - var __importStar2 = exports2 && exports2.__importStar || function(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (k4 !== "default" && Object.prototype.hasOwnProperty.call(mod2, k4)) - __createBinding2(result, mod2, k4); - } - __setModuleDefault(result, mod2); - return result; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.zeroPadStringIfOddLength = exports2.isPaddedHex = exports2.numberToPaddedHex = exports2.Nonce = exports2.Address = void 0; - var bech32 = __importStar2(require_bech32()); - var HRP = "erd"; - var Address5 = class _Address { - constructor(value) { - this.value = value; - } - static fromPubkey(pubkey) { - let words = bech32.toWords(pubkey); - let address = bech32.encode(HRP, words); - return new _Address(address); - } - bech32() { - return this.value; - } - toString() { - return this.bech32(); - } - }; - exports2.Address = Address5; - var Nonce = class { - constructor(value) { - this.value = value; - } - valueOf() { - return this.value; - } - hex() { - return numberToPaddedHex(this.value); - } - }; - exports2.Nonce = Nonce; - function numberToPaddedHex(value) { - let hex = value.toString(16); - return zeroPadStringIfOddLength(hex); - } - exports2.numberToPaddedHex = numberToPaddedHex; - function isPaddedHex(input) { - input = input || ""; - let decodedThenEncoded = import_buffer.Buffer.from(input, "hex").toString("hex"); - return input.toUpperCase() == decodedThenEncoded.toUpperCase(); - } - exports2.isPaddedHex = isPaddedHex; - function zeroPadStringIfOddLength(input) { - input = input || ""; - if (input.length % 2 == 1) { - return "0" + input; - } - return input; - } - exports2.zeroPadStringIfOddLength = zeroPadStringIfOddLength; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/constants.js -var require_constants3 = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/constants.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.EsdtContractAddress = exports2.MaxUint64AsBigNumber = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber2()); - var primitives_1 = require_primitives(); - exports2.MaxUint64AsBigNumber = new bignumber_js_1.default("18446744073709551615"); - exports2.EsdtContractAddress = new primitives_1.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"); - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js -var require_contractQueryResponse = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/contractQueryResponse.js"(exports2) { - "use strict"; - init_shim(); - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractQueryResponse = void 0; - var bignumber_js_1 = __importDefault2(require_bignumber2()); - var constants_1 = require_constants3(); - var ContractQueryResponse3 = class _ContractQueryResponse { - constructor(init) { - this.returnData = (init === null || init === void 0 ? void 0 : init.returnData) || []; - this.returnCode = (init === null || init === void 0 ? void 0 : init.returnCode) || ""; - this.returnMessage = (init === null || init === void 0 ? void 0 : init.returnMessage) || ""; - this.gasUsed = (init === null || init === void 0 ? void 0 : init.gasUsed) || 0; - } - /** - * Constructs a QueryResponse object from a HTTP response (as returned by the provider). - */ - static fromHttpResponse(payload) { - let returnData = payload["returnData"] || payload["ReturnData"]; - let returnCode = payload["returnCode"] || payload["ReturnCode"]; - let returnMessage = payload["returnMessage"] || payload["ReturnMessage"]; - let gasRemaining = new bignumber_js_1.default(payload["gasRemaining"] || payload["GasRemaining"] || 0); - let gasUsed = constants_1.MaxUint64AsBigNumber.minus(gasRemaining).toNumber(); - return new _ContractQueryResponse({ - returnData, - returnCode, - returnMessage, - gasUsed - }); - } - getReturnDataParts() { - return this.returnData.map((item) => import_buffer.Buffer.from(item || "", "base64")); - } - /** - * Converts the object to a pretty, plain JavaScript object. - */ - toJSON() { - return { - returnData: this.returnData, - returnCode: this.returnCode, - returnMessage: this.returnMessage, - gasUsed: this.gasUsed.valueOf() - }; - } - }; - exports2.ContractQueryResponse = ContractQueryResponse3; - } -}); - -// node_modules/@multiversx/sdk-extension-provider/out/errors.js -var require_errors2 = __commonJS({ - "node_modules/@multiversx/sdk-extension-provider/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrAccountNotConnected = exports2.ErrCannotSignSingleTransaction = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - }; - exports2.Err = Err; - var ErrCannotSignSingleTransaction = class extends Err { - constructor() { - super("Cannot sign single transaction."); - } - }; - exports2.ErrCannotSignSingleTransaction = ErrCannotSignSingleTransaction; - var ErrAccountNotConnected = class extends Err { - constructor() { - super("Account is not connected."); - } - }; - exports2.ErrAccountNotConnected = ErrAccountNotConnected; - } -}); - -// node_modules/@multiversx/sdk-extension-provider/out/operation.js -var require_operation = __commonJS({ - "node_modules/@multiversx/sdk-extension-provider/out/operation.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Operation = void 0; - var Operation; - (function(Operation2) { - Operation2["Connect"] = "connect"; - Operation2["Logout"] = "logout"; - Operation2["SignTransactions"] = "signTransactions"; - Operation2["SignMessage"] = "signMessage"; - Operation2["CancelAction"] = "cancelAction"; - })(Operation = exports2.Operation || (exports2.Operation = {})); - } -}); - -// node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js -var require_extensionProvider = __commonJS({ - "node_modules/@multiversx/sdk-extension-provider/out/extensionProvider.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ExtensionProvider = void 0; - var transaction_1 = require_transaction(); - var errors_1 = require_errors2(); - var operation_1 = require_operation(); - var ExtensionProvider3 = class _ExtensionProvider { - constructor() { - this.account = { address: "" }; - this.initialized = false; - if (_ExtensionProvider._instance) { - throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new."); - } - _ExtensionProvider._instance = this; - } - static getInstance() { - return _ExtensionProvider._instance; - } - setAddress(address) { - this.account.address = address; - return _ExtensionProvider._instance; - } - init() { - return __awaiter2(this, void 0, void 0, function* () { - if (window && window.elrondWallet) { - this.initialized = true; - } - return this.initialized; - }); - } - login(options = {}) { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.initialized) { - throw new Error("Extension provider is not initialised, call init() first"); - } - const { token } = options; - const data = token ? token : ""; - yield this.startBgrMsgChannel(operation_1.Operation.Connect, data); - return this.account.address; - }); - } - logout() { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.initialized) { - throw new Error("Extension provider is not initialised, call init() first"); - } - try { - yield this.startBgrMsgChannel(operation_1.Operation.Logout, this.account.address); - this.disconnect(); - } catch (error) { - console.warn("Extension origin url is already cleared!", error); - } - return true; - }); - } - disconnect() { - this.account = { address: "" }; - } - getAddress() { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.initialized) { - throw new Error("Extension provider is not initialised, call init() first"); - } - return this.account ? this.account.address : ""; - }); - } - isInitialized() { - return this.initialized; - } - // TODO: In V3, this will not be an async function anymore. - isConnected() { - return __awaiter2(this, void 0, void 0, function* () { - return Boolean(this.account.address); - }); - } - signTransaction(transaction) { - return __awaiter2(this, void 0, void 0, function* () { - this.ensureConnected(); - const signedTransactions = yield this.signTransactions([transaction]); - if (signedTransactions.length != 1) { - throw new errors_1.ErrCannotSignSingleTransaction(); - } - return signedTransactions[0]; - }); - } - ensureConnected() { - if (!this.account.address) { - throw new errors_1.ErrAccountNotConnected(); - } - } - signTransactions(transactions) { - return __awaiter2(this, void 0, void 0, function* () { - this.ensureConnected(); - const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignTransactions, { - from: this.account.address, - transactions: transactions.map((transaction) => transaction.toPlainObject()) - }); - try { - const transactionsResponse = extensionResponse.map((transaction) => transaction_1.Transaction.fromPlainObject(transaction)); - return transactionsResponse; - } catch (error) { - throw new Error(`Transaction canceled: ${error.message}.`); - } - }); - } - signMessage(message) { - return __awaiter2(this, void 0, void 0, function* () { - this.ensureConnected(); - const data = { - account: this.account.address, - message: message.message.toString() - }; - const extensionResponse = yield this.startBgrMsgChannel(operation_1.Operation.SignMessage, data); - const signatureHex = extensionResponse.signature; - const signature = import_buffer.Buffer.from(signatureHex, "hex"); - message.applySignature(signature); - return message; - }); - } - cancelAction() { - return this.startBgrMsgChannel(operation_1.Operation.CancelAction, {}); - } - startBgrMsgChannel(operation, connectData) { - return new Promise((resolve) => { - window.postMessage({ - target: "erdw-inpage", - type: operation, - data: connectData - }, window.origin); - const eventHandler = (event) => { - if (event.isTrusted && event.data.target === "erdw-contentScript") { - if (event.data.type === "connectResponse") { - if (event.data.data && Boolean(event.data.data.address)) { - this.account = event.data.data; - } - window.removeEventListener("message", eventHandler); - resolve(event.data.data); - } else { - window.removeEventListener("message", eventHandler); - resolve(event.data.data); - } - } - }; - window.addEventListener("message", eventHandler, false); - }); - } - }; - exports2.ExtensionProvider = ExtensionProvider3; - ExtensionProvider3._instance = new ExtensionProvider3(); - } -}); - -// node_modules/destr/dist/index.mjs -function jsonParseTransform(key, value) { - if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) { - warnKeyDropped(key); - return; - } - return value; -} -function warnKeyDropped(key) { - console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`); -} -function destr(value, options = {}) { - if (typeof value !== "string") { - return value; - } - const _value = value.trim(); - if ( - // eslint-disable-next-line unicorn/prefer-at - value[0] === '"' && value.endsWith('"') && !value.includes("\\") - ) { - return _value.slice(1, -1); - } - if (_value.length <= 9) { - const _lval = _value.toLowerCase(); - if (_lval === "true") { - return true; - } - if (_lval === "false") { - return false; - } - if (_lval === "undefined") { - return void 0; - } - if (_lval === "null") { - return null; - } - if (_lval === "nan") { - return Number.NaN; - } - if (_lval === "infinity") { - return Number.POSITIVE_INFINITY; - } - if (_lval === "-infinity") { - return Number.NEGATIVE_INFINITY; - } - } - if (!JsonSigRx.test(value)) { - if (options.strict) { - throw new SyntaxError("[destr] Invalid JSON"); - } - return value; - } - try { - if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) { - if (options.strict) { - throw new Error("[destr] Possible prototype pollution"); - } - return JSON.parse(value, jsonParseTransform); - } - return JSON.parse(value); - } catch (error) { - if (options.strict) { - throw error; - } - return value; - } -} -var suspectProtoRx, suspectConstructorRx, JsonSigRx; -var init_dist = __esm({ - "node_modules/destr/dist/index.mjs"() { - init_shim(); - suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/; - suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; - JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; - } -}); - -// node_modules/unstorage/dist/shared/unstorage.8581f561.mjs -function wrapToPromise(value) { - if (!value || typeof value.then !== "function") { - return Promise.resolve(value); - } - return value; -} -function asyncCall(function_, ...arguments_) { - try { - return wrapToPromise(function_(...arguments_)); - } catch (error) { - return Promise.reject(error); - } -} -function isPrimitive(value) { - const type = typeof value; - return value === null || type !== "object" && type !== "function"; -} -function isPureObject(value) { - const proto = Object.getPrototypeOf(value); - return !proto || proto.isPrototypeOf(Object); -} -function stringify(value) { - if (isPrimitive(value)) { - return String(value); - } - if (isPureObject(value) || Array.isArray(value)) { - return JSON.stringify(value); - } - if (typeof value.toJSON === "function") { - return stringify(value.toJSON()); - } - throw new Error("[unstorage] Cannot stringify value!"); -} -function checkBufferSupport() { - if (typeof import_buffer.Buffer === void 0) { - throw new TypeError("[unstorage] Buffer is not supported!"); - } -} -function serializeRaw(value) { - if (typeof value === "string") { - return value; - } - checkBufferSupport(); - const base642 = import_buffer.Buffer.from(value).toString("base64"); - return BASE64_PREFIX + base642; -} -function deserializeRaw(value) { - if (typeof value !== "string") { - return value; - } - if (!value.startsWith(BASE64_PREFIX)) { - return value; - } - checkBufferSupport(); - return import_buffer.Buffer.from(value.slice(BASE64_PREFIX.length), "base64"); -} -function normalizeKey(key) { - if (!key) { - return ""; - } - return key.split("?")[0].replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, ""); -} -function joinKeys(...keys2) { - return normalizeKey(keys2.join(":")); -} -function normalizeBaseKey(base3) { - base3 = normalizeKey(base3); - return base3 ? base3 + ":" : ""; -} -var BASE64_PREFIX; -var init_unstorage_8581f561 = __esm({ - "node_modules/unstorage/dist/shared/unstorage.8581f561.mjs"() { - init_shim(); - BASE64_PREFIX = "base64:"; - } -}); - -// node_modules/unstorage/dist/index.mjs -function defineDriver(factory) { - return factory; -} -function createStorage(options = {}) { - const context = { - mounts: { "": options.driver || memory() }, - mountpoints: [""], - watching: false, - watchListeners: [], - unwatch: {} - }; - const getMount = (key) => { - for (const base3 of context.mountpoints) { - if (key.startsWith(base3)) { - return { - base: base3, - relativeKey: key.slice(base3.length), - driver: context.mounts[base3] - }; - } - } - return { - base: "", - relativeKey: key, - driver: context.mounts[""] - }; - }; - const getMounts = (base3, includeParent) => { - return context.mountpoints.filter( - (mountpoint) => mountpoint.startsWith(base3) || includeParent && base3.startsWith(mountpoint) - ).map((mountpoint) => ({ - relativeBase: base3.length > mountpoint.length ? base3.slice(mountpoint.length) : void 0, - mountpoint, - driver: context.mounts[mountpoint] - })); - }; - const onChange = (event, key) => { - if (!context.watching) { - return; - } - key = normalizeKey(key); - for (const listener of context.watchListeners) { - listener(event, key); - } - }; - const startWatch = async () => { - if (context.watching) { - return; - } - context.watching = true; - for (const mountpoint in context.mounts) { - context.unwatch[mountpoint] = await watch( - context.mounts[mountpoint], - onChange, - mountpoint - ); - } - }; - const stopWatch = async () => { - if (!context.watching) { - return; - } - for (const mountpoint in context.unwatch) { - await context.unwatch[mountpoint](); - } - context.unwatch = {}; - context.watching = false; - }; - const runBatch = (items, commonOptions, cb) => { - const batches = /* @__PURE__ */ new Map(); - const getBatch = (mount) => { - let batch = batches.get(mount.base); - if (!batch) { - batch = { - driver: mount.driver, - base: mount.base, - items: [] - }; - batches.set(mount.base, batch); - } - return batch; - }; - for (const item of items) { - const isStringItem = typeof item === "string"; - const key = normalizeKey(isStringItem ? item : item.key); - const value = isStringItem ? void 0 : item.value; - const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options }; - const mount = getMount(key); - getBatch(mount).items.push({ - key, - value, - relativeKey: mount.relativeKey, - options: options2 - }); - } - return Promise.all([...batches.values()].map((batch) => cb(batch))).then( - (r) => r.flat() - ); - }; - const storage = { - // Item - hasItem(key, opts = {}) { - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - return asyncCall(driver.hasItem, relativeKey, opts); - }, - getItem(key, opts = {}) { - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - return asyncCall(driver.getItem, relativeKey, opts).then( - (value) => destr(value) - ); - }, - getItems(items, commonOptions) { - return runBatch(items, commonOptions, (batch) => { - if (batch.driver.getItems) { - return asyncCall( - batch.driver.getItems, - batch.items.map((item) => ({ - key: item.relativeKey, - options: item.options - })), - commonOptions - ).then( - (r) => r.map((item) => ({ - key: joinKeys(batch.base, item.key), - value: destr(item.value) - })) - ); - } - return Promise.all( - batch.items.map((item) => { - return asyncCall( - batch.driver.getItem, - item.relativeKey, - item.options - ).then((value) => ({ - key: item.key, - value: destr(value) - })); - }) - ); - }); - }, - getItemRaw(key, opts = {}) { - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (driver.getItemRaw) { - return asyncCall(driver.getItemRaw, relativeKey, opts); - } - return asyncCall(driver.getItem, relativeKey, opts).then( - (value) => deserializeRaw(value) - ); - }, - async setItem(key, value, opts = {}) { - if (value === void 0) { - return storage.removeItem(key); - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (!driver.setItem) { - return; - } - await asyncCall(driver.setItem, relativeKey, stringify(value), opts); - if (!driver.watch) { - onChange("update", key); - } - }, - async setItems(items, commonOptions) { - await runBatch(items, commonOptions, async (batch) => { - if (batch.driver.setItems) { - return asyncCall( - batch.driver.setItems, - batch.items.map((item) => ({ - key: item.relativeKey, - value: stringify(item.value), - options: item.options - })), - commonOptions - ); - } - if (!batch.driver.setItem) { - return; - } - await Promise.all( - batch.items.map((item) => { - return asyncCall( - batch.driver.setItem, - item.relativeKey, - stringify(item.value), - item.options - ); - }) - ); - }); - }, - async setItemRaw(key, value, opts = {}) { - if (value === void 0) { - return storage.removeItem(key, opts); - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (driver.setItemRaw) { - await asyncCall(driver.setItemRaw, relativeKey, value, opts); - } else if (driver.setItem) { - await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts); - } else { - return; - } - if (!driver.watch) { - onChange("update", key); - } - }, - async removeItem(key, opts = {}) { - if (typeof opts === "boolean") { - opts = { removeMeta: opts }; - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - if (!driver.removeItem) { - return; - } - await asyncCall(driver.removeItem, relativeKey, opts); - if (opts.removeMeta || opts.removeMata) { - await asyncCall(driver.removeItem, relativeKey + "$", opts); - } - if (!driver.watch) { - onChange("remove", key); - } - }, - // Meta - async getMeta(key, opts = {}) { - if (typeof opts === "boolean") { - opts = { nativeOnly: opts }; - } - key = normalizeKey(key); - const { relativeKey, driver } = getMount(key); - const meta = /* @__PURE__ */ Object.create(null); - if (driver.getMeta) { - Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts)); - } - if (!opts.nativeOnly) { - const value = await asyncCall( - driver.getItem, - relativeKey + "$", - opts - ).then((value_) => destr(value_)); - if (value && typeof value === "object") { - if (typeof value.atime === "string") { - value.atime = new Date(value.atime); - } - if (typeof value.mtime === "string") { - value.mtime = new Date(value.mtime); - } - Object.assign(meta, value); - } - } - return meta; - }, - setMeta(key, value, opts = {}) { - return this.setItem(key + "$", value, opts); - }, - removeMeta(key, opts = {}) { - return this.removeItem(key + "$", opts); - }, - // Keys - async getKeys(base3, opts = {}) { - base3 = normalizeBaseKey(base3); - const mounts = getMounts(base3, true); - let maskedMounts = []; - const allKeys = []; - for (const mount of mounts) { - const rawKeys = await asyncCall( - mount.driver.getKeys, - mount.relativeBase, - opts - ); - const keys2 = rawKeys.map((key) => mount.mountpoint + normalizeKey(key)).filter((key) => !maskedMounts.some((p3) => key.startsWith(p3))); - allKeys.push(...keys2); - maskedMounts = [ - mount.mountpoint, - ...maskedMounts.filter((p3) => !p3.startsWith(mount.mountpoint)) - ]; - } - return base3 ? allKeys.filter((key) => key.startsWith(base3) && !key.endsWith("$")) : allKeys.filter((key) => !key.endsWith("$")); - }, - // Utils - async clear(base3, opts = {}) { - base3 = normalizeBaseKey(base3); - await Promise.all( - getMounts(base3, false).map(async (m3) => { - if (m3.driver.clear) { - return asyncCall(m3.driver.clear, m3.relativeBase, opts); - } - if (m3.driver.removeItem) { - const keys2 = await m3.driver.getKeys(m3.relativeBase || "", opts); - return Promise.all( - keys2.map((key) => m3.driver.removeItem(key, opts)) - ); - } - }) - ); - }, - async dispose() { - await Promise.all( - Object.values(context.mounts).map((driver) => dispose(driver)) - ); - }, - async watch(callback) { - await startWatch(); - context.watchListeners.push(callback); - return async () => { - context.watchListeners = context.watchListeners.filter( - (listener) => listener !== callback - ); - if (context.watchListeners.length === 0) { - await stopWatch(); - } - }; - }, - async unwatch() { - context.watchListeners = []; - await stopWatch(); - }, - // Mount - mount(base3, driver) { - base3 = normalizeBaseKey(base3); - if (base3 && context.mounts[base3]) { - throw new Error(`already mounted at ${base3}`); - } - if (base3) { - context.mountpoints.push(base3); - context.mountpoints.sort((a3, b4) => b4.length - a3.length); - } - context.mounts[base3] = driver; - if (context.watching) { - Promise.resolve(watch(driver, onChange, base3)).then((unwatcher) => { - context.unwatch[base3] = unwatcher; - }).catch(console.error); - } - return storage; - }, - async unmount(base3, _dispose = true) { - base3 = normalizeBaseKey(base3); - if (!base3 || !context.mounts[base3]) { - return; - } - if (context.watching && base3 in context.unwatch) { - context.unwatch[base3](); - delete context.unwatch[base3]; - } - if (_dispose) { - await dispose(context.mounts[base3]); - } - context.mountpoints = context.mountpoints.filter((key) => key !== base3); - delete context.mounts[base3]; - }, - getMount(key = "") { - key = normalizeKey(key) + ":"; - const m3 = getMount(key); - return { - driver: m3.driver, - base: m3.base - }; - }, - getMounts(base3 = "", opts = {}) { - base3 = normalizeKey(base3); - const mounts = getMounts(base3, opts.parents); - return mounts.map((m3) => ({ - driver: m3.driver, - base: m3.mountpoint - })); - } - }; - return storage; -} -function watch(driver, onChange, base3) { - return driver.watch ? driver.watch((event, key) => onChange(event, base3 + key)) : () => { - }; -} -async function dispose(driver) { - if (typeof driver.dispose === "function") { - await asyncCall(driver.dispose); - } -} -var DRIVER_NAME, memory; -var init_dist2 = __esm({ - "node_modules/unstorage/dist/index.mjs"() { - init_shim(); - init_dist(); - init_unstorage_8581f561(); - DRIVER_NAME = "memory"; - memory = defineDriver(() => { - const data = /* @__PURE__ */ new Map(); - return { - name: DRIVER_NAME, - options: {}, - hasItem(key) { - return data.has(key); - }, - getItem(key) { - return data.get(key) ?? null; - }, - getItemRaw(key) { - return data.get(key) ?? null; - }, - setItem(key, value) { - data.set(key, value); - }, - setItemRaw(key, value) { - data.set(key, value); - }, - removeItem(key) { - data.delete(key); - }, - getKeys() { - return Array.from(data.keys()); - }, - clear() { - data.clear(); - }, - dispose() { - data.clear(); - } - }; - }); - } -}); - -// node_modules/idb-keyval/dist/index.js -function promisifyRequest(request) { - return new Promise((resolve, reject) => { - request.oncomplete = request.onsuccess = () => resolve(request.result); - request.onabort = request.onerror = () => reject(request.error); - }); -} -function createStore(dbName, storeName) { - const request = indexedDB.open(dbName); - request.onupgradeneeded = () => request.result.createObjectStore(storeName); - const dbp = promisifyRequest(request); - return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName))); -} -function defaultGetStore() { - if (!defaultGetStoreFunc) { - defaultGetStoreFunc = createStore("keyval-store", "keyval"); - } - return defaultGetStoreFunc; -} -function get(key, customStore = defaultGetStore()) { - return customStore("readonly", (store) => promisifyRequest(store.get(key))); -} -function set(key, value, customStore = defaultGetStore()) { - return customStore("readwrite", (store) => { - store.put(value, key); - return promisifyRequest(store.transaction); - }); -} -function del(key, customStore = defaultGetStore()) { - return customStore("readwrite", (store) => { - store.delete(key); - return promisifyRequest(store.transaction); - }); -} -function clear(customStore = defaultGetStore()) { - return customStore("readwrite", (store) => { - store.clear(); - return promisifyRequest(store.transaction); - }); -} -function eachCursor(store, callback) { - store.openCursor().onsuccess = function() { - if (!this.result) - return; - callback(this.result); - this.result.continue(); - }; - return promisifyRequest(store.transaction); -} -function keys(customStore = defaultGetStore()) { - return customStore("readonly", (store) => { - if (store.getAllKeys) { - return promisifyRequest(store.getAllKeys()); - } - const items = []; - return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items); - }); -} -var defaultGetStoreFunc; -var init_dist3 = __esm({ - "node_modules/idb-keyval/dist/index.js"() { - init_shim(); - } -}); +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex(e.tokenType),ae.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleLocalMint?[ae.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ae.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ae.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ae.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ae.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.initialQuantity),ae.utf8ToHex(e.name),ae.bigIntToHex(e.royalties),ae.utf8ToHex(e.hash),ae.bufferToHex(e.attributes),...e.uris.map(ae.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:u,dataParts:a}){let c=this.buildTransactionPayload(a),f=o||this.computeGasLimit(c,u),d=new d8.TransactionVersion(Ab.TRANSACTION_VERSION_DEFAULT),w=new d8.TransactionOptions(Ab.TRANSACTION_OPTIONS_DEFAULT);return new y$.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:w})}buildTransactionPayload(e){let r=e.join(Ab.ARGUMENTS_SEPARATOR);return new w$.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};O0.TokenOperationsFactory=Eb});var p8=B(D0=>{"use strict";h();Object.defineProperty(D0,"__esModule",{value:!0});D0.TokenOperationsFactoryConfig=void 0;var v$=Ve(),bb=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=v$.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};D0.TokenOperationsFactoryConfig=bb});var y8=B(P0=>{"use strict";h();Object.defineProperty(P0,"__esModule",{value:!0});P0.TokenOperationsOutcomeParser=void 0;var A$=Ve(),Sb=Ie(),m8=$d(),Ib=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=r.topics[3]?.valueOf();return{tokenIdentifier:n,nonce:i,attributes:s}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){for(let r of e.logs.events)if(r.identifier=="signalError"){let n=p.Buffer.from(r.data.substring(1),"hex").toString(),i=r.topics[1]?.valueOf().toString();throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${i} (${n})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){return e.topics[0]?.valueOf().toString()}extractNonce(e){return m8.bufferToBigInt(e.topics[1]?.valueOf()).toFixed(0)}extractAmount(e){return m8.bufferToBigInt(e.topics[2]?.valueOf()).toFixed(0)}extractAddress(e){return A$.Address.fromBuffer(e.topics[3]?.valueOf()).toString()}};P0.TokenOperationsOutcomeParser=Ib});var _b=B(Ls=>{"use strict";h();var E$=Ls&&Ls.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Tb=Ls&&Ls.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&E$(e,t,r)};Object.defineProperty(Ls,"__esModule",{value:!0});Tb(g8(),Ls);Tb(p8(),Ls);Tb(y8(),Ls)});var w8=B(R0=>{"use strict";h();Object.defineProperty(R0,"__esModule",{value:!0});R0.DelegationTransactionsOutcomeParser=void 0;var b$=Ve(),S$=Ie(),I$=Ac(),Cb=class{constructor(){}parseCreateNewDelegationContract(e){return this.ensureNoError(e.logs.events),I$.findEventsByIdentifier(e,"SCDeploy").map(n=>({contractAddress:this.extractContractAddress(n)}))}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new S$.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractContractAddress(e){if(!e.topics[0]?.length)return"";let r=p.Buffer.from(e.topics[0]);return b$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};R0.DelegationTransactionsOutcomeParser=Cb});var E8=B(B0=>{"use strict";h();Object.defineProperty(B0,"__esModule",{value:!0});B0.SmartContractTransactionsOutcomeParser=void 0;var v8=Ve(),T$=Ie(),A8=qn(),_$=Ac(),Nb=class{constructor(e){this.abi=e?.abi,this.legacyResultsParser=e?.legacyResultsParser||new A8.ResultsParser}parseDeploy(e){let r=e.transactionOutcome.directSmartContractCallOutcome,i=_$.findEventsByIdentifier(e.transactionOutcome,"SCDeploy").map(s=>this.parseScDeployEvent(s));return{returnCode:r.returnCode,returnMessage:r.returnMessage,contracts:i}}parseScDeployEvent(e){let r=e.topics[0],n=e.topics[1],i=e.topics[2],s=r?.length?new v8.Address(r).toBech32():"",o=n?.length?new v8.Address(n).toBech32():"";return{address:s,ownerAddress:o,codeHash:i}}parseExecute(e){let r=e.transactionOutcome.directSmartContractCallOutcome;if(!this.abi)return{values:r.returnDataParts,returnCode:r.returnCode,returnMessage:r.returnMessage};let n=e.function||r.function;if(!n)throw new T$.Err('Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?');let i=this.abi.getEndpoint(n),s={returnCode:new A8.ReturnCode(r.returnCode),returnMessage:r.returnMessage,values:r.returnDataParts.map(u=>p.Buffer.from(u))},o=this.legacyResultsParser.parseOutcomeFromUntypedBundle(s,i);return{values:o.values.map(u=>u.valueOf()),returnCode:o.returnCode.toString(),returnMessage:o.returnMessage}}};B0.SmartContractTransactionsOutcomeParser=Nb});var I8=B(M0=>{"use strict";h();Object.defineProperty(M0,"__esModule",{value:!0});M0.TokenManagementTransactionsOutcomeParser=void 0;var C$=Ve(),b8=Ie(),S8=Bu(),wr=Ac(),xb=class{constructor(){}parseIssueFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issue").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueNonFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueNonFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueSemiFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueSemiFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterMetaEsdt(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"registerMetaESDT").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterAndSetAllRoles(e){this.ensureNoError(e.logs.events);let r=wr.findEventsByIdentifier(e,"registerAndSetAllRoles"),n=wr.findEventsByIdentifier(e,"ESDTSetRole");if(r.length!==n.length)throw new b8.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events.");return r.map((i,s)=>{let o=this.extractTokenIdentifier(i),a=n[s].topics.slice(3).map(c=>this.decodeTopicAsString(c));return{tokenIdentifier:o,roles:a}})}parseSetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseUnsetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseSetSpecialRole(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTSetRole").map(n=>this.getOutputForSetSpecialRoleEvent(n))}getOutputForSetSpecialRoleEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),s=e.topics.slice(3).map(o=>this.decodeTopicAsString(o));return{userAddress:r,tokenIdentifier:n,roles:s}}parseNftCreate(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTCreate").map(n=>this.getOutputForNftCreateEvent(n))}getOutputForNftCreateEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,initialQuantity:i}}parseLocalMint(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalMint").map(n=>this.getOutputForLocalMintEvent(n))}getOutputForLocalMintEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,mintedSupply:s}}parseLocalBurn(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalBurn").map(n=>this.getOutputForLocalBurnEvent(n))}getOutputForLocalBurnEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,burntSupply:s}}parsePause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseUnpause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseFreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTFreeze").map(n=>this.getOutputForFreezeEvent(n))}getOutputForFreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnFreeze").map(n=>this.getOutputForUnfreezeEvent(n))}getOutputForUnfreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTWipe").map(n=>this.getOutputForWipeEvent(n))}getOutputForWipeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTUpdateAttributes").map(n=>this.getOutputForUpdateAttributesEvent(n))}getOutputForUpdateAttributesEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=e.topics[3]?e.topics[3]:new Uint8Array;return{tokenIdentifier:r,nonce:n,attributes:i}}parseAddQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTAddQuantity").map(n=>this.getOutputForAddQuantityEvent(n))}getOutputForAddQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,addedQuantity:i}}parseBurnQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTBurn").map(n=>this.getOutputForBurnQuantityEvent(n))}getOutputForBurnQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,burntQuantity:i}}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new b8.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractTokenIdentifier(e){return e.topics[0]?.length?this.decodeTopicAsString(e.topics[0]):""}extractNonce(e){if(!e.topics[1]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[1]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAmount(e){if(!e.topics[2]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[2]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAddress(e){if(!e.topics[3]?.length)return"";let r=p.Buffer.from(e.topics[3]);return C$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};M0.TokenManagementTransactionsOutcomeParser=xb});var T8=B(L0=>{"use strict";h();Object.defineProperty(L0,"__esModule",{value:!0});L0.TransactionEventsParser=void 0;var N$=qn(),Ob=class{constructor(e){this.legacyResultsParser=new N$.ResultsParser,this.abi=e.abi,this.firstTopicIsIdentifier=e.firstTopicIsIdentifier??!0}parseEvents(e){let r=[];for(let n of e.events){let i=this.parseEvent({event:n});r.push(i)}return r}parseEvent(e){let r=e.event.topics.map(u=>p.Buffer.from(u)),n=this.firstTopicIsIdentifier?r[0]?.toString():e.event.identifier;this.firstTopicIsIdentifier&&r.shift();let i=e.event.dataItems.map(u=>p.Buffer.from(u)),s=this.abi.getEvent(n);return this.legacyResultsParser.doParseEvent({topics:r,dataItems:i,eventDefinition:s})}};L0.TransactionEventsParser=Ob});var Db=B(vi=>{"use strict";h();var x$=vi&&vi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=vi&&vi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&x$(e,t,r)};Object.defineProperty(vi,"__esModule",{value:!0});rh(w8(),vi);rh(Ac(),vi);rh(E8(),vi);rh(I8(),vi);rh(T8(),vi)});var Ic=B(F0=>{"use strict";h();Object.defineProperty(F0,"__esModule",{value:!0});F0.Account=void 0;var O$=Ve(),Pb=class{constructor(e){this.address=O$.Address.empty(),this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};F0.Account=Pb});var Bb=B(Tc=>{"use strict";h();Object.defineProperty(Tc,"__esModule",{value:!0});Tc.MessageComputer=Tc.Message=void 0;var nh=hr(),D$=Ve(),P$=sf(),U0=class{constructor(e){this.data=e.data,this.signature=e.signature,this.address=e.address,this.version=e.version||nh.DEFAULT_MESSAGE_VERSION,this.signer=e.signer||nh.SDK_JS_SIGNER}};Tc.Message=U0;var Rb=class{constructor(){}computeBytesForSigning(e){let r=p.Buffer.from(e.data.length.toString()),n=p.Buffer.concat([r,e.data]),i=p.Buffer.concat([p.Buffer.from(nh.MESSAGE_PREFIX),n]);return P$("keccak256").update(i).digest()}computeBytesForVerifying(e){return this.computeBytesForSigning(e)}packMessage(e){return{message:p.Buffer.from(e.data).toString("hex"),signature:e.signature?p.Buffer.from(e.signature).toString("hex"):"",address:e.address?e.address.bech32():"",version:e.version,signer:e.signer}}unpackMessage(e){let r=this.trimHexPrefix(e.message),n=p.Buffer.from(r,"hex"),i=this.trimHexPrefix(e.signature||""),s=p.Buffer.from(i,"hex"),o;e.address&&(o=D$.Address.fromBech32(e.address));let u=e.version||nh.DEFAULT_MESSAGE_VERSION,a=e.signer||nh.UNKNOWN_SIGNER;return new U0({data:n,signature:s,address:o,version:u,signer:a})}trimHexPrefix(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}};Tc.MessageComputer=Rb});var Fb=B(Xi=>{"use strict";h();var R$=Xi&&Xi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),B$=Xi&&Xi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Xi&&Xi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&R$(e,t,r);return B$(e,t),e};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AsyncTimer=void 0;var L$=M$(Ie()),F$=Ie(),Mb=oo(),Lb=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new L$.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new F$.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};Xi.AsyncTimer=Lb});var V0=B(q0=>{"use strict";h();Object.defineProperty(q0,"__esModule",{value:!0});q0.TransactionWatcher=void 0;var Ub=Fb(),_8=hr(),Fs=Ie(),C8=oo(),No=class t{constructor(e,r={}){this.fetcher=new qb(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}async awaitPending(e){let r=s=>s.status.isPending(),n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitCompleted(e){let r=s=>{if(s.isCompleted===void 0)throw new Fs.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitAllEvents(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>u.includes(c))},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitAnyEvent(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>u.includes(c))!=null},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitOnCondition(e,r){let n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}transactionOrTxHashToTxHash(e){let r=typeof e=="string"?e:e.getHash().hex();if(r.length!==_8.HEX_TRANSACTION_HASH_LENGTH)throw new Fs.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${_8.HEX_TRANSACTION_HASH_LENGTH}.`);return r}async awaitConditionally(e,r,n){let i=new Ub.AsyncTimer("watcher:periodic"),s=new Ub.AsyncTimer("watcher:patience"),o=new Ub.AsyncTimer("watcher:timeout"),u=!1,a,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),u=!0});!u;){await i.start(this.pollingIntervalMilliseconds);try{if(a=await r(),c=e(a),c||u)break}catch(f){if(C8.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Fs.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Fs.Err))throw f}}if(c&&await s.start(this.patienceMilliseconds),o.isStopped()||o.stop(),!a||!c)throw n();return a}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};q0.TransactionWatcher=No;No.DefaultPollingInterval=6e3;No.DefaultTimeout=No.DefaultPollingInterval*15;No.DefaultPatience=0;No.NoopOnStatusReceived=t=>{};var qb=class{constructor(e){this.fetcher=e}async getTransaction(e){return C8.Logger.debug(`transactionWatcher, getTransaction(${e})`),await this.fetcher.getTransaction(e)}}});var H0=B(k0=>{"use strict";h();Object.defineProperty(k0,"__esModule",{value:!0});k0.SignableMessage=void 0;var U$=Ve(),q$=Yf(),V$=hr(),k$=sf(),Vb=class{constructor(e){this.message=p.Buffer.from([]),this.signature=p.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=U$.Address.empty(),Object.assign(this,e)}serializeForSigning(){let e=p.Buffer.from(this.message.length.toString()),r=p.Buffer.concat([e,this.message]),n=p.Buffer.concat([p.Buffer.from(V$.MESSAGE_PREFIX),r]);return k$("keccak256").update(n).digest()}serializeForSigningRaw(){return p.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=q$.interpretSignatureAsBuffer(e)}getMessageSize(){let e=p.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};k0.SignableMessage=Vb});var _c=B(vr=>{"use strict";h();var H$=vr&&vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),G$=vr&&vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),j$=vr&&vr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H$(e,t,r);return G$(e,t),e};Object.defineProperty(vr,"__esModule",{value:!0});vr.zeroPadStringIfOddLength=vr.isPaddedHex=vr.numberToPaddedHex=vr.Nonce=vr.Address=void 0;var N8=j$(wv()),z$="erd",kb=class t{constructor(e){this.value=e}static fromPubkey(e){let r=N8.toWords(e),n=N8.encode(z$,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};vr.Address=kb;var Hb=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return x8(this.value)}};vr.Nonce=Hb;function x8(t){let e=t.toString(16);return O8(e)}vr.numberToPaddedHex=x8;function Q$(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}vr.isPaddedHex=Q$;function O8(t){return t=t||"",t.length%2==1?"0"+t:t}vr.zeroPadStringIfOddLength=O8});var D8=B(xo=>{"use strict";h();var K$=xo&&xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xo,"__esModule",{value:!0});xo.EsdtContractAddress=xo.MaxUint64AsBigNumber=void 0;var W$=K$((rr(),_e(fr))),$$=_c();xo.MaxUint64AsBigNumber=new W$.default("18446744073709551615");xo.EsdtContractAddress=new $$.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var jb=B(Cc=>{"use strict";h();var Y$=Cc&&Cc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ContractQueryResponse=void 0;var J$=Y$((rr(),_e(fr))),X$=D8(),Gb=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new J$.default(e.gasRemaining||e.GasRemaining||0),o=X$.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>p.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Cc.ContractQueryResponse=Gb});var P8=B(Oo=>{"use strict";h();Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ErrAccountNotConnected=Oo.ErrCannotSignSingleTransaction=Oo.Err=void 0;var ih=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Oo.Err=ih;var zb=class extends ih{constructor(){super("Cannot sign single transaction.")}};Oo.ErrCannotSignSingleTransaction=zb;var Qb=class extends ih{constructor(){super("Account is not connected.")}};Oo.ErrAccountNotConnected=Qb});var R8=B(sh=>{"use strict";h();Object.defineProperty(sh,"__esModule",{value:!0});sh.Operation=void 0;var Z$;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(Z$=sh.Operation||(sh.Operation={}))});var Kb=B(Nc=>{"use strict";h();var Do=Nc&&Nc.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Nc,"__esModule",{value:!0});Nc.ExtensionProvider=void 0;var eY=Xr(),B8=P8(),oh=R8(),ah=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return Do(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(oh.Operation.Connect,n),this.account.address})}logout(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(oh.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return Do(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new B8.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new B8.ErrAccountNotConnected}signTransactions(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(oh.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>eY.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(oh.Operation.SignMessage,r)).signature,s=p.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(oh.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};Nc.ExtensionProvider=ah;ah._instance=new ah});function iY(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){sY(t);return}return e}function sY(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function uh(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!nY.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(tY.test(t)||rY.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,iY)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var tY,rY,nY,q8=fe(()=>{h();tY=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,rY=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,nY=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function oY(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function gr(t,...e){try{return oY(t(...e))}catch(r){return Promise.reject(r)}}function aY(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function uY(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ch(t){if(aY(t))return String(t);if(uY(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ch(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function V8(){if(typeof p.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function k8(t){if(typeof t=="string")return t;V8();let e=p.Buffer.from(t).toString("base64");return Wb+e}function H8(t){return typeof t!="string"||!t.startsWith(Wb)?t:(V8(),p.Buffer.from(t.slice(Wb.length),"base64"))}function Vr(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function G8(...t){return Vr(t.join(":"))}function lh(t){return t=Vr(t),t?t+":":""}var Wb,j8=fe(()=>{h();Wb="base64:"});function K8(t={}){let e={mounts:{"":t.driver||lY()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=Vr(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await z8(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},u=(c,f,d)=>{let w=new Map,A=T=>{let x=w.get(T.base);return x||(x={driver:T.driver,base:T.base,items:[]},w.set(T.base,x)),x};for(let T of c){let x=typeof T=="string",R=Vr(x?T:T.key),V=x?void 0:T.value,U=x||!T.options?f:{...f,...T.options},Q=r(R);A(Q).items.push({key:R,value:V,relativeKey:Q.relativeKey,options:U})}return Promise.all([...w.values()].map(T=>d(T))).then(T=>T.flat())},a={hasItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.hasItem,d,f)},getItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.getItem,d,f).then(A=>uh(A))},getItems(c,f){return u(c,f,d=>d.driver.getItems?gr(d.driver.getItems,d.items.map(w=>({key:w.relativeKey,options:w.options})),f).then(w=>w.map(A=>({key:G8(d.base,A.key),value:uh(A.value)}))):Promise.all(d.items.map(w=>gr(d.driver.getItem,w.relativeKey,w.options).then(A=>({key:w.key,value:uh(A)})))))},getItemRaw(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return w.getItemRaw?gr(w.getItemRaw,d,f):gr(w.getItem,d,f).then(A=>H8(A))},async setItem(c,f,d={}){if(f===void 0)return a.removeItem(c);c=Vr(c);let{relativeKey:w,driver:A}=r(c);A.setItem&&(await gr(A.setItem,w,ch(f),d),A.watch||i("update",c))},async setItems(c,f){await u(c,f,async d=>{if(d.driver.setItems)return gr(d.driver.setItems,d.items.map(w=>({key:w.relativeKey,value:ch(w.value),options:w.options})),f);d.driver.setItem&&await Promise.all(d.items.map(w=>gr(d.driver.setItem,w.relativeKey,ch(w.value),w.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return a.removeItem(c,d);c=Vr(c);let{relativeKey:w,driver:A}=r(c);if(A.setItemRaw)await gr(A.setItemRaw,w,f,d);else if(A.setItem)await gr(A.setItem,w,k8(f),d);else return;A.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c);w.removeItem&&(await gr(w.removeItem,d,f),(f.removeMeta||f.removeMata)&&await gr(w.removeItem,d+"$",f),w.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c),A=Object.create(null);if(w.getMeta&&Object.assign(A,await gr(w.getMeta,d,f)),!f.nativeOnly){let T=await gr(w.getItem,d+"$",f).then(x=>uh(x));T&&typeof T=="object"&&(typeof T.atime=="string"&&(T.atime=new Date(T.atime)),typeof T.mtime=="string"&&(T.mtime=new Date(T.mtime)),Object.assign(A,T))}return A},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=lh(c);let d=n(c,!0),w=[],A=[];for(let T of d){let R=(await gr(T.driver.getKeys,T.relativeBase,f)).map(V=>T.mountpoint+Vr(V)).filter(V=>!w.some(U=>V.startsWith(U)));A.push(...R),w=[T.mountpoint,...w.filter(V=>!V.startsWith(T.mountpoint))]}return c?A.filter(T=>T.startsWith(c)&&!T.endsWith("$")):A.filter(T=>!T.endsWith("$"))},async clear(c,f={}){c=lh(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return gr(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let w=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(w.map(A=>d.driver.removeItem(A,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>Q8(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=lh(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,w)=>w.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(z8(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),a},async unmount(c,f=!0){c=lh(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await Q8(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=Vr(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=Vr(c),n(c,f.parents).map(w=>({driver:w.driver,base:w.mountpoint}))}};return a}function z8(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function Q8(t){typeof t.dispose=="function"&&await gr(t.dispose)}var cY,lY,W8=fe(()=>{h();q8();j8();cY="memory",lY=()=>{let t=new Map;return{name:cY,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function za(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Yb(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=za(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function fh(){return $b||($b=Yb("keyval-store","keyval")),$b}function Jb(t,e=fh()){return e("readonly",r=>za(r.get(t)))}function $8(t,e,r=fh()){return r("readwrite",n=>(n.put(e,t),za(n.transaction)))}function Y8(t,e=fh()){return e("readwrite",r=>(r.delete(t),za(r.transaction)))}function J8(t=fh()){return t("readwrite",e=>(e.clear(),za(e.transaction)))}function fY(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},za(t.transaction)}function X8(t=fh()){return t("readonly",e=>{if(e.getAllKeys)return za(e.getAllKeys());let r=[];return fY(e,n=>r.push(n.key)).then(()=>r)})}var $b,Z8=fe(()=>{h()});var eP={};Bt(eP,{safeJsonParse:()=>Ro,safeJsonStringify:()=>Ai});function Ro(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return dY(t)}catch{return t}}function Ai(t){return typeof t=="string"?t:hY(t)||""}var hY,dY,xc=fe(()=>{h();hY=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),dY=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var rP={};Bt(rP,{KeyValueStorage:()=>tS,default:()=>tS});function wY(t){var e;return[t[0],Ro((e=t[1])!=null?e:"")]}var gY,pY,mY,yY,Zb,Xb,Q0,eS,vY,tP,AY,EY,tS,nP=fe(()=>{h();W8();Z8();xc();gY="idb-keyval",pY=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Yb(t.dbName,t.storeName)),{name:gY,options:t,async hasItem(i){return!(typeof await Jb(r(i),n)>"u")},async getItem(i){return await Jb(r(i),n)??null},setItem(i,s){return $8(r(i),s,n)},removeItem(i){return Y8(r(i),n)},getKeys(){return X8(n)},clear(){return J8(n)}}},mY="WALLET_CONNECT_V2_INDEXED_DB",yY="keyvaluestorage",Zb=class{constructor(){this.indexedDb=K8({driver:pY({dbName:mY,storeName:yY})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ai(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Xb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Q0={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Xb<"u"&&Xb.localStorage?Q0.exports=Xb.localStorage:typeof window<"u"&&window.localStorage?Q0.exports=window.localStorage:Q0.exports=new e})();eS=class{constructor(){this.localStorage=Q0.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(wY)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return Ro(r)}async setItem(e,r){this.localStorage.setItem(e,Ai(r))}async removeItem(e){this.localStorage.removeItem(e)}},vY="wc_storage_version",tP=1,AY=async(t,e,r)=>{let n=vY,i=await e.getItem(n);if(i&&i>=tP){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let u=s.shift();if(!u)continue;let a=u.toLowerCase();if(a.includes("wc@")||a.includes("walletconnect")||a.includes("wc_")||a.includes("wallet_connect")){let c=await t.getItem(u);await e.setItem(u,c),o.push(u)}}await e.setItem(n,tP),r(e),EY(t,o)},EY=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},tS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new eS;this.storage=e;try{let r=new Zb;AY(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zi={};Bt(Zi,{__assign:()=>nS,__asyncDelegator:()=>BY,__asyncGenerator:()=>RY,__asyncValues:()=>MY,__await:()=>hh,__awaiter:()=>CY,__classPrivateFieldGet:()=>qY,__classPrivateFieldSet:()=>VY,__createBinding:()=>xY,__decorate:()=>IY,__exportStar:()=>OY,__extends:()=>bY,__generator:()=>NY,__importDefault:()=>UY,__importStar:()=>FY,__makeTemplateObject:()=>LY,__metadata:()=>_Y,__param:()=>TY,__read:()=>iP,__rest:()=>SY,__spread:()=>DY,__spreadArrays:()=>PY,__values:()=>iS});function bY(t,e){rS(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function SY(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;u--)(o=t[u])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function TY(t,e){return function(r,n){e(r,n,t)}}function _Y(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function CY(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})}function NY(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(c){return function(f){return a([c,f])}}function a(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function iP(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function DY(){for(var t=[],e=0;e1||u(w,A)})})}function u(w,A){try{a(n[w](A))}catch(T){d(s[0][3],T)}}function a(w){w.value instanceof hh?Promise.resolve(w.value.v).then(c,f):d(s[0][2],w)}function c(w){u("next",w)}function f(w){u("throw",w)}function d(w,A){w(A),s.shift(),s.length&&u(s[0][0],s[0][1])}}function BY(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:hh(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function MY(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof iS=="function"?iS(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(u,a){o=t[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(c){s({value:c,done:u})},o)}}function LY(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function FY(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function UY(t){return t&&t.__esModule?t:{default:t}}function qY(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function VY(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rS,nS,es=fe(()=>{h();rS=function(t,e){return rS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},rS(t,e)};nS=function(){return nS=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";h();Object.defineProperty(K0,"__esModule",{value:!0});K0.delay=void 0;function kY(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}K0.delay=kY});var oP=B(Oc=>{"use strict";h();Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ONE_THOUSAND=Oc.ONE_HUNDRED=void 0;Oc.ONE_HUNDRED=100;Oc.ONE_THOUSAND=1e3});var aP=B(le=>{"use strict";h();Object.defineProperty(le,"__esModule",{value:!0});le.ONE_YEAR=le.FOUR_WEEKS=le.THREE_WEEKS=le.TWO_WEEKS=le.ONE_WEEK=le.THIRTY_DAYS=le.SEVEN_DAYS=le.FIVE_DAYS=le.THREE_DAYS=le.ONE_DAY=le.TWENTY_FOUR_HOURS=le.TWELVE_HOURS=le.SIX_HOURS=le.THREE_HOURS=le.ONE_HOUR=le.SIXTY_MINUTES=le.THIRTY_MINUTES=le.TEN_MINUTES=le.FIVE_MINUTES=le.ONE_MINUTE=le.SIXTY_SECONDS=le.THIRTY_SECONDS=le.TEN_SECONDS=le.FIVE_SECONDS=le.ONE_SECOND=void 0;le.ONE_SECOND=1;le.FIVE_SECONDS=5;le.TEN_SECONDS=10;le.THIRTY_SECONDS=30;le.SIXTY_SECONDS=60;le.ONE_MINUTE=le.SIXTY_SECONDS;le.FIVE_MINUTES=le.ONE_MINUTE*5;le.TEN_MINUTES=le.ONE_MINUTE*10;le.THIRTY_MINUTES=le.ONE_MINUTE*30;le.SIXTY_MINUTES=le.ONE_MINUTE*60;le.ONE_HOUR=le.SIXTY_MINUTES;le.THREE_HOURS=le.ONE_HOUR*3;le.SIX_HOURS=le.ONE_HOUR*6;le.TWELVE_HOURS=le.ONE_HOUR*12;le.TWENTY_FOUR_HOURS=le.ONE_HOUR*24;le.ONE_DAY=le.TWENTY_FOUR_HOURS;le.THREE_DAYS=le.ONE_DAY*3;le.FIVE_DAYS=le.ONE_DAY*5;le.SEVEN_DAYS=le.ONE_DAY*7;le.THIRTY_DAYS=le.ONE_DAY*30;le.ONE_WEEK=le.SEVEN_DAYS;le.TWO_WEEKS=le.ONE_WEEK*2;le.THREE_WEEKS=le.ONE_WEEK*3;le.FOUR_WEEKS=le.ONE_WEEK*4;le.ONE_YEAR=le.ONE_DAY*365});var sS=B(W0=>{"use strict";h();Object.defineProperty(W0,"__esModule",{value:!0});var uP=(es(),_e(Zi));uP.__exportStar(oP(),W0);uP.__exportStar(aP(),W0)});var lP=B(Dc=>{"use strict";h();Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromMiliseconds=Dc.toMiliseconds=void 0;var cP=sS();function HY(t){return t*cP.ONE_THOUSAND}Dc.toMiliseconds=HY;function GY(t){return Math.floor(t/cP.ONE_THOUSAND)}Dc.fromMiliseconds=GY});var hP=B($0=>{"use strict";h();Object.defineProperty($0,"__esModule",{value:!0});var fP=(es(),_e(Zi));fP.__exportStar(sP(),$0);fP.__exportStar(lP(),$0)});var dP=B(dh=>{"use strict";h();Object.defineProperty(dh,"__esModule",{value:!0});dh.Watch=void 0;var Y0=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};dh.Watch=Y0;dh.default=Y0});var gP=B(J0=>{"use strict";h();Object.defineProperty(J0,"__esModule",{value:!0});J0.IWatch=void 0;var oS=class{};J0.IWatch=oS});var pP=B(aS=>{"use strict";h();Object.defineProperty(aS,"__esModule",{value:!0});var jY=(es(),_e(Zi));jY.__exportStar(gP(),aS)});var Qa=B(Pc=>{"use strict";h();Object.defineProperty(Pc,"__esModule",{value:!0});var X0=(es(),_e(Zi));X0.__exportStar(hP(),Pc);X0.__exportStar(dP(),Pc);X0.__exportStar(pP(),Pc);X0.__exportStar(sS(),Pc)});var uS,mP=fe(()=>{h();uS=class{}});var cS={};Bt(cS,{IEvents:()=>uS});var lS=fe(()=>{h();mP()});var yP=B(Z0=>{"use strict";h();Object.defineProperty(Z0,"__esModule",{value:!0});Z0.IHeartBeat=void 0;var zY=(lS(),_e(cS)),fS=class extends zY.IEvents{constructor(e){super()}};Z0.IHeartBeat=fS});var dS=B(hS=>{"use strict";h();Object.defineProperty(hS,"__esModule",{value:!0});var QY=(es(),_e(Zi));QY.__exportStar(yP(),hS)});var wP=B(Rc=>{"use strict";h();Object.defineProperty(Rc,"__esModule",{value:!0});Rc.HEARTBEAT_EVENTS=Rc.HEARTBEAT_INTERVAL=void 0;var KY=Qa();Rc.HEARTBEAT_INTERVAL=KY.FIVE_SECONDS;Rc.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var pS=B(gS=>{"use strict";h();Object.defineProperty(gS,"__esModule",{value:!0});var WY=(es(),_e(Zi));WY.__exportStar(wP(),gS)});var vP=B(em=>{"use strict";h();Object.defineProperty(em,"__esModule",{value:!0});em.HeartBeat=void 0;var mS=(es(),_e(Zi)),$Y=Ds(),YY=Qa(),JY=dS(),yS=pS(),wS=class t extends JY.IHeartBeat{constructor(e){super(e),this.events=new $Y.EventEmitter,this.interval=yS.HEARTBEAT_INTERVAL,this.interval=e?.interval||yS.HEARTBEAT_INTERVAL}static init(e){return mS.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return mS.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return mS.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),YY.toMiliseconds(this.interval))})}pulse(){this.events.emit(yS.HEARTBEAT_EVENTS.pulse)}};em.HeartBeat=wS});var AP=B(gh=>{"use strict";h();Object.defineProperty(gh,"__esModule",{value:!0});var vS=(es(),_e(Zi));vS.__exportStar(vP(),gh);vS.__exportStar(dS(),gh);vS.__exportStar(pS(),gh)});var bP=B((AAe,EP)=>{"use strict";h();function XY(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}EP.exports=ZY;function ZY(t,e,r){var n=r&&r.stringify||XY,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var u=1;u-1?d:0,t.charCodeAt(A+1)){case 100:case 102:if(f>=a||e[f]==null)break;d=a||e[f]==null)break;d=a||e[f]===void 0)break;d",d=A+2,A++;break}c+=n(e[f]),d=A+2,A++;break;case 115:if(f>=a)break;d{"use strict";h();var SP=bP();_P.exports=ts;var ph=cJ().console||{},eJ={mapHttpRequest:tm,mapHttpResponse:tm,wrapRequestSerializer:AS,wrapResponseSerializer:AS,wrapErrorSerializer:AS,req:tm,res:tm,err:sJ};function tJ(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ts(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||ph;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=tJ(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let u=t.level||"info",a=Object.create(r);a.log||(a.log=mh),Object.defineProperty(a,"levelVal",{get:f}),Object.defineProperty(a,"level",{get:d,set:w});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:oJ(t)};a.levels=ts.levels,a.level=u,a.setMaxListeners=a.getMaxListeners=a.emit=a.addListener=a.on=a.prependListener=a.once=a.prependOnceListener=a.removeListener=a.removeAllListeners=a.listeners=a.listenerCount=a.eventNames=a.write=a.flush=mh,a.serializers=n,a._serialize=i,a._stdErrSerialize=s,a.child=A,e&&(a._logEvent=ES());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function w(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,Bc(c,a,"error","log"),Bc(c,a,"fatal","error"),Bc(c,a,"warn","error"),Bc(c,a,"info","log"),Bc(c,a,"debug","log"),Bc(c,a,"trace","log")}function A(T,x){if(!T)throw new Error("missing bindings for child Pino");x=x||{},i&&T.serializers&&(x.serializers=T.serializers);let R=x.serializers;if(i&&R){var V=Object.assign({},n,R),U=t.browser.serialize===!0?Object.keys(V):i;delete T.serializers,rm([T],U,V,this._stdErrSerialize)}function Q(L){this._childLevel=(L._childLevel|0)+1,this.error=Mc(L,T,"error"),this.fatal=Mc(L,T,"fatal"),this.warn=Mc(L,T,"warn"),this.info=Mc(L,T,"info"),this.debug=Mc(L,T,"debug"),this.trace=Mc(L,T,"trace"),V&&(this.serializers=V,this._serialize=U),e&&(this._logEvent=ES([].concat(L._logEvent.bindings,T)))}return Q.prototype=this,new Q(this)}return a}ts.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};ts.stdSerializers=eJ;ts.stdTimeFunctions=Object.assign({},{nullTime:IP,epochTime:TP,unixTime:aJ,isoTime:uJ});function Bc(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mh:i[r]?i[r]:ph[r]||ph[n]||mh,rJ(t,e,r)}function rJ(t,e,r){!t.transmit&&e[r]===mh||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ph?ph:this;for(var a=0;a-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Mc(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;iam,PINO_CUSTOM_CONTEXT_KEY:()=>Lc,PINO_LOGGER_DEFAULTS:()=>OP,formatChildLoggerContext:()=>BP,generateChildLogger:()=>mJ,generateClientLogger:()=>MP,generatePlatformLogger:()=>yJ,generateServerLogger:()=>LP,getBrowserLoggerContext:()=>DP,getDefaultLoggerOptions:()=>pJ,getLoggerContext:()=>RP,pino:()=>xP.default,setBrowserLoggerContext:()=>PP});function pJ(t){return om(sm({},t),{level:t?.level||OP.level})}function DP(t,e=Lc){return t[e]||""}function PP(t,e,r=Lc){return t[r]=e,t}function RP(t,e=Lc){let r="";return typeof t.bindings>"u"?r=DP(t,e):r=t.bindings().context||"",r}function BP(t,e,r=Lc){let n=RP(t,r);return n.trim()?`${n}/${e}`:e}function mJ(t,e,r=Lc){let n=BP(t,e,r),i=t.child({context:n});return PP(i,n,r)}function MP(t){var e,r;let n=new IS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace",browser:om(sm({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function LP(t){var e;let r=new TS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function yJ(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?MP(t):LP(t)}var Us,xP,OP,Lc,am,SS,nm,im,IS,TS,lJ,fJ,hJ,CP,dJ,gJ,NP,sm,om,CS=fe(()=>{h();Us=pe(bS()),xP=pe(bS());xc();OP={level:"info"},Lc="custom_context",am=1e3*1024,SS=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},nm=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let r=new SS(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let r=e.value;return e=e.next,{done:!1,value:r}}}}},im=class{constructor(e,r=am){this.level=e??"error",this.levelValue=Us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Us.levels.values.error?console.error(e):r===Us.levels.values.warn?console.warn(e):r===Us.levels.values.debug?console.debug(e):r===Us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ai({timestamp:new Date().toISOString(),log:e}));let r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let r=this.getLogArray();return r.push(Ai({extraMetadata:e})),new Blob(r,{type:"application/json"})}},IS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},TS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}},lJ=Object.defineProperty,fJ=Object.defineProperties,hJ=Object.getOwnPropertyDescriptors,CP=Object.getOwnPropertySymbols,dJ=Object.prototype.hasOwnProperty,gJ=Object.prototype.propertyIsEnumerable,NP=(t,e,r)=>e in t?lJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sm=(t,e)=>{for(var r in e||(e={}))dJ.call(e,r)&&NP(t,r,e[r]);if(CP)for(var r of CP(e))gJ.call(e,r)&&NP(t,r,e[r]);return t},om=(t,e)=>fJ(t,hJ(e))});var QS=B(ar=>{"use strict";h();Object.defineProperty(ar,"__esModule",{value:!0});var Fc=(lS(),_e(cS)),FP=Ds();function wJ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var vJ=wJ(FP),NS=class extends Fc.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},xS=class{constructor(e,r,n){this.core=e,this.logger=r}},OS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},DS=class{constructor(e,r){this.logger=e,this.core=r}},PS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},RS=class extends Fc.IEvents{constructor(e){super()}},BS=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},MS=class{constructor(){this.map=new Map}},LS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},FS=class{constructor(e,r){this.core=e,this.logger=r}},US=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},qS=class{constructor(e,r){this.logger=e,this.core=r}},VS=class{constructor(e,r){this.projectId=e,this.logger=r}},kS=class{constructor(e,r){this.projectId=e,this.logger=r}},HS=class extends vJ.default{constructor(){super()}},GS=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},jS=class extends FP.EventEmitter{constructor(){super()}},zS=class{constructor(e){this.client=e}};ar.ICore=NS,ar.ICrypto=xS,ar.IEchoClient=kS,ar.IEngine=zS,ar.IEngineEvents=jS,ar.IExpirer=US,ar.IJsonRpcHistory=OS,ar.IKeyChain=FS,ar.IMessageTracker=DS,ar.IPairing=qS,ar.IPublisher=PS,ar.IRelayer=RS,ar.ISignClient=GS,ar.ISignClientEvents=HS,ar.IStore=BS,ar.ISubscriber=LS,ar.ISubscriberTopicMap=MS,ar.IVerify=VS});var qP=B(um=>{"use strict";h();Object.defineProperty(um,"__esModule",{value:!0});um.BrowserRandomSource=void 0;var UP=65536,KS=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";h();Object.defineProperty(WS,"__esModule",{value:!0});function AJ(t){for(var e=0;e{h()});var kP=B(cm=>{"use strict";h();Object.defineProperty(cm,"__esModule",{value:!0});cm.NodeRandomSource=void 0;var EJ=Qn(),$S=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof Bd<"u"){let e=VP();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";h();Object.defineProperty(lm,"__esModule",{value:!0});lm.SystemRandomSource=void 0;var bJ=qP(),SJ=kP(),YS=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new bJ.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new SJ.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};lm.SystemRandomSource=YS});var GP=B(dn=>{"use strict";h();Object.defineProperty(dn,"__esModule",{value:!0});function IJ(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}dn.mul=Math.imul||IJ;function TJ(t,e){return t+e|0}dn.add=TJ;function _J(t,e){return t-e|0}dn.sub=_J;function CJ(t,e){return t<>>32-e}dn.rotl=CJ;function NJ(t,e){return t<<32-e|t>>>e}dn.rotr=NJ;function xJ(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}dn.isInteger=Number.isInteger||xJ;dn.MAX_SAFE_INTEGER=9007199254740991;dn.isSafeInteger=function(t){return dn.isInteger(t)&&t>=-dn.MAX_SAFE_INTEGER&&t<=dn.MAX_SAFE_INTEGER}});var Uc=B(xe=>{"use strict";h();Object.defineProperty(xe,"__esModule",{value:!0});var jP=GP();function OJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}xe.readInt16BE=OJ;function DJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}xe.readUint16BE=DJ;function PJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}xe.readInt16LE=PJ;function RJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}xe.readUint16LE=RJ;function zP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}xe.writeUint16BE=zP;xe.writeInt16BE=zP;function QP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}xe.writeUint16LE=QP;xe.writeInt16LE=QP;function JS(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}xe.readInt32BE=JS;function XS(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}xe.readUint32BE=XS;function ZS(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}xe.readInt32LE=ZS;function eI(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}xe.readUint32LE=eI;function fm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}xe.writeUint32BE=fm;xe.writeInt32BE=fm;function hm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}xe.writeUint32LE=hm;xe.writeInt32LE=hm;function BJ(t,e){e===void 0&&(e=0);var r=JS(t,e),n=JS(t,e+4);return r*4294967296+n-(n>>31)*4294967296}xe.readInt64BE=BJ;function MJ(t,e){e===void 0&&(e=0);var r=XS(t,e),n=XS(t,e+4);return r*4294967296+n}xe.readUint64BE=MJ;function LJ(t,e){e===void 0&&(e=0);var r=ZS(t,e),n=ZS(t,e+4);return n*4294967296+r-(r>>31)*4294967296}xe.readInt64LE=LJ;function FJ(t,e){e===void 0&&(e=0);var r=eI(t,e),n=eI(t,e+4);return n*4294967296+r}xe.readUint64LE=FJ;function KP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),fm(t/4294967296>>>0,e,r),fm(t>>>0,e,r+4),e}xe.writeUint64BE=KP;xe.writeInt64BE=KP;function WP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),hm(t>>>0,e,r),hm(t/4294967296>>>0,e,r+4),e}xe.writeUint64LE=WP;xe.writeInt64LE=WP;function UJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}xe.readUintBE=UJ;function qJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}xe.writeUintBE=VJ;function kJ(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!jP.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";h();Object.defineProperty(Br,"__esModule",{value:!0});Br.randomStringForEntropy=Br.randomString=Br.randomUint32=Br.randomBytes=Br.defaultRandomSource=void 0;var YJ=HP(),JJ=Uc(),$P=Qn();Br.defaultRandomSource=new YJ.SystemRandomSource;function tI(t,e=Br.defaultRandomSource){return e.randomBytes(t)}Br.randomBytes=tI;function XJ(t=Br.defaultRandomSource){let e=tI(4,t),r=(0,JJ.readUint32LE)(e);return(0,$P.wipe)(e),r}Br.randomUint32=XJ;var YP="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function JP(t,e=YP,r=Br.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=tI(Math.ceil(t*256/s),r);for(let u=0;u0;u++){let a=o[u];a{"use strict";h();Object.defineProperty(qs,"__esModule",{value:!0});var Vc=Uc(),qc=Qn();qs.DIGEST_LENGTH=64;qs.BLOCK_SIZE=128;var ZP=function(){function t(){this.digestLength=qs.DIGEST_LENGTH,this.blockSize=qs.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){qc.wipe(this._buffer),qc.wipe(this._tempHi),qc.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){qc.wipe(e.stateHi),qc.wipe(e.stateLo),e.buffer&&qc.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();qs.SHA512=ZP;var XP=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function rI(t,e,r,n,i,s,o){for(var u=r[0],a=r[1],c=r[2],f=r[3],d=r[4],w=r[5],A=r[6],T=r[7],x=n[0],R=n[1],V=n[2],U=n[3],Q=n[4],L=n[5],k=n[6],H=n[7],q,v,C,D,F,P,l,g;o>=128;){for(var y=0;y<16;y++){var E=8*y+s;t[y]=Vc.readUint32BE(i,E),e[y]=Vc.readUint32BE(i,E+4)}for(var y=0;y<80;y++){var S=u,_=a,M=c,N=f,m=d,O=w,Y=A,$=T,b=x,j=R,z=V,W=U,ie=Q,te=L,ee=k,se=H;if(q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(d>>>14|Q<<18)^(d>>>18|Q<<14)^(Q>>>9|d<<23),v=(Q>>>14|d<<18)^(Q>>>18|d<<14)^(d>>>9|Q<<23),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=d&w^~d&A,v=Q&L^~Q&k,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=XP[y*2],v=XP[y*2+1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=t[y%16],v=e[y%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,C=l&65535|g<<16,D=F&65535|P<<16,q=C,v=D,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(u>>>28|x<<4)^(x>>>2|u<<30)^(x>>>7|u<<25),v=(x>>>28|u<<4)^(u>>>2|x<<30)^(u>>>7|x<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=u&a^u&c^a&c,v=x&R^x&V^R&V,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,$=l&65535|g<<16,se=F&65535|P<<16,q=N,v=W,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=C,v=D,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,N=l&65535|g<<16,W=F&65535|P<<16,a=S,c=_,f=M,d=N,w=m,A=O,T=Y,u=$,R=b,V=j,U=z,Q=W,L=ie,k=te,H=ee,x=se,y%16===15)for(var E=0;E<16;E++)q=t[E],v=e[E],F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=t[(E+9)%16],v=e[(E+9)%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+1)%16],D=e[(E+1)%16],q=(C>>>1|D<<31)^(C>>>8|D<<24)^C>>>7,v=(D>>>1|C<<31)^(D>>>8|C<<24)^(D>>>7|C<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+14)%16],D=e[(E+14)%16],q=(C>>>19|D<<13)^(D>>>29|C<<3)^C>>>6,v=(D>>>19|C<<13)^(C>>>29|D<<3)^(D>>>6|C<<26),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,t[E]=l&65535|g<<16,e[E]=F&65535|P<<16}q=u,v=x,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[0],v=n[0],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[0]=u=l&65535|g<<16,n[0]=x=F&65535|P<<16,q=a,v=R,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[1],v=n[1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[1]=a=l&65535|g<<16,n[1]=R=F&65535|P<<16,q=c,v=V,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[2],v=n[2],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[2]=c=l&65535|g<<16,n[2]=V=F&65535|P<<16,q=f,v=U,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[3],v=n[3],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[3]=f=l&65535|g<<16,n[3]=U=F&65535|P<<16,q=d,v=Q,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[4],v=n[4],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[4]=d=l&65535|g<<16,n[4]=Q=F&65535|P<<16,q=w,v=L,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[5],v=n[5],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[5]=w=l&65535|g<<16,n[5]=L=F&65535|P<<16,q=A,v=k,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[6],v=n[6],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[6]=A=l&65535|g<<16,n[6]=k=F&65535|P<<16,q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[7],v=n[7],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[7]=T=l&65535|g<<16,n[7]=H=F&65535|P<<16,s+=128,o-=128}return s}function eX(t){var e=new ZP;e.update(t);var r=e.digest();return e.clean(),r}qs.hash=eX});var gR=B(Ge=>{"use strict";h();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.convertSecretKeyToX25519=Ge.convertPublicKeyToX25519=Ge.verify=Ge.sign=Ge.extractPublicKeyFromSecretKey=Ge.generateKeyPair=Ge.generateKeyPairFromSeed=Ge.SEED_LENGTH=Ge.SECRET_KEY_LENGTH=Ge.PUBLIC_KEY_LENGTH=Ge.SIGNATURE_LENGTH=void 0;var tX=yh(),wh=eR(),sR=Qn();Ge.SIGNATURE_LENGTH=64;Ge.PUBLIC_KEY_LENGTH=32;Ge.SECRET_KEY_LENGTH=64;Ge.SEED_LENGTH=32;function ve(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,oR(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function aR(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function nR(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return vh(r,t),vh(n,e),aR(r,n)}function uR(t){let e=new Uint8Array(32);return vh(e,t),e[0]&1}function oX(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Ka(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function $a(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function Ct(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Wa(t,e){Ct(t,e,e)}function cR(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)Wa(r,r),n!==2&&n!==4&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function aX(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)Wa(r,r),n!==1&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function oI(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve(),c=ve(),f=ve();$a(r,t[1],t[0]),$a(f,e[1],e[0]),Ct(r,r,f),Ka(n,t[0],t[1]),Ka(f,e[0],e[1]),Ct(n,n,f),Ct(i,t[3],e[3]),Ct(i,i,iX),Ct(s,t[2],e[2]),Ka(s,s,s),$a(o,n,r),$a(u,s,i),Ka(a,s,i),Ka(c,n,r),Ct(t[0],o,u),Ct(t[1],c,a),Ct(t[2],a,u),Ct(t[3],o,c)}function iR(t,e,r){for(let n=0;n<4;n++)oR(t[n],e[n],r)}function uI(t,e){let r=ve(),n=ve(),i=ve();cR(i,e[2]),Ct(r,e[0],i),Ct(n,e[1],i),vh(t,n),t[31]^=uR(r)<<7}function lR(t,e,r){Bo(t[0],sI),Bo(t[1],kc),Bo(t[2],kc),Bo(t[3],sI);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;iR(t,e,i),oI(e,t),oI(t,t),iR(t,e,i)}}function cI(t,e){let r=[ve(),ve(),ve(),ve()];Bo(r[0],tR),Bo(r[1],rR),Bo(r[2],kc),Ct(r[3],tR,rR),lR(t,r,e)}function fR(t){if(t.length!==Ge.SEED_LENGTH)throw new Error(`ed25519: seed must be ${Ge.SEED_LENGTH} bytes`);let e=(0,wh.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[ve(),ve(),ve(),ve()];cI(n,e),uI(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}Ge.generateKeyPairFromSeed=fR;function uX(t){let e=(0,tX.randomBytes)(32,t),r=fR(e);return(0,sR.wipe)(e),r}Ge.generateKeyPair=uX;function cX(t){if(t.length!==Ge.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${Ge.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}Ge.extractPublicKeyFromSecretKey=cX;var iI=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function hR(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*iI[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*iI[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function aI(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;hR(t,e)}function lX(t,e){let r=new Float64Array(64),n=[ve(),ve(),ve(),ve()],i=(0,wh.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new wh.SHA512;o.update(s.subarray(32)),o.update(e);let u=o.digest();o.clean(),aI(u),cI(n,u),uI(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let a=o.digest();aI(a);for(let c=0;c<32;c++)r[c]=u[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=a[c]*i[f];return hR(s.subarray(32),r),s}Ge.sign=lX;function dR(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve();return Bo(t[2],kc),oX(t[1],e),Wa(i,t[1]),Ct(s,i,nX),$a(i,i,t[2]),Ka(s,t[2],s),Wa(o,s),Wa(u,o),Ct(a,u,o),Ct(r,a,i),Ct(r,r,s),aX(r,r),Ct(r,r,i),Ct(r,r,s),Ct(r,r,s),Ct(t[0],r,s),Wa(n,t[0]),Ct(n,n,s),nR(n,i)&&Ct(t[0],t[0],sX),Wa(n,t[0]),Ct(n,n,s),nR(n,i)?-1:(uR(t[0])===e[31]>>7&&$a(t[0],sI,t[0]),Ct(t[3],t[0],t[1]),0)}function fX(t,e,r){let n=new Uint8Array(32),i=[ve(),ve(),ve(),ve()],s=[ve(),ve(),ve(),ve()];if(r.length!==Ge.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${Ge.SIGNATURE_LENGTH} bytes`);if(dR(s,t))return!1;let o=new wh.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let u=o.digest();return aI(u),lR(i,s,u),cI(s,r.subarray(32)),oI(i,s),uI(n,i),!aR(r,n)}Ge.verify=fX;function hX(t){let e=[ve(),ve(),ve(),ve()];if(dR(e,t))throw new Error("Ed25519: invalid public key");let r=ve(),n=ve(),i=e[1];Ka(r,kc,i),$a(n,kc,i),cR(n,n),Ct(r,r,n);let s=new Uint8Array(32);return vh(s,r),s}Ge.convertPublicKeyToX25519=hX;function dX(t){let e=(0,wh.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,sR.wipe)(e),r}Ge.convertSecretKeyToX25519=dX});var dm,gm,Ya,Hc,pm,Ah,mm,ym,wm,Gc,vm,Am,pR,mR,Em=fe(()=>{h();dm="EdDSA",gm="JWT",Ya=".",Hc="base64url",pm="utf8",Ah="utf8",mm=":",ym="did",wm="key",Gc="base58btc",vm="z",Am="K36",pR=32,mR=32});function Mo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var Eh=fe(()=>{h()});function jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var bm=fe(()=>{h();Eh()});function Sm(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=jc(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Mo(r)}var lI=fe(()=>{h();bm();Eh()});function gX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var pX,mX,yR,wR=fe(()=>{h();pX=gX,mX=pX,yR=mX});var cEe,vR,Vs,AR,ER,Lo=fe(()=>{h();cEe=new Uint8Array(0),vR=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},AR=t=>new TextEncoder().encode(t),ER=t=>new TextDecoder().decode(t)});var fI,hI,dI,SR,gI,zc,Fo,yX,wX,jt,Ei=fe(()=>{h();wR();Lo();fI=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},hI=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SR(this,e)}},dI=class{constructor(e){this.decoders=e}or(e){return SR(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SR=(t,e)=>new dI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),gI=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new fI(e,r,n),this.decoder=new hI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zc=({name:t,prefix:e,encode:r,decode:n})=>new gI(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=yR(r,e);return zc({prefix:t,name:e,encode:n,decode:s=>Vs(i(s))})},yX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},wX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<zc({prefix:e,name:t,encode(i){return wX(i,n,r)},decode(i){return yX(i,n,r,t)}})});var pI={};Bt(pI,{identity:()=>vX});var vX,IR=fe(()=>{h();Ei();Lo();vX=zc({prefix:"\0",name:"identity",encode:t=>ER(t),decode:t=>AR(t)})});var mI={};Bt(mI,{base2:()=>AX});var AX,TR=fe(()=>{h();Ei();AX=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var yI={};Bt(yI,{base8:()=>EX});var EX,_R=fe(()=>{h();Ei();EX=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var wI={};Bt(wI,{base10:()=>bX});var bX,CR=fe(()=>{h();Ei();bX=Fo({prefix:"9",name:"base10",alphabet:"0123456789"})});var vI={};Bt(vI,{base16:()=>SX,base16upper:()=>IX});var SX,IX,NR=fe(()=>{h();Ei();SX=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),IX=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var AI={};Bt(AI,{base32:()=>Qc,base32hex:()=>NX,base32hexpad:()=>OX,base32hexpadupper:()=>DX,base32hexupper:()=>xX,base32pad:()=>_X,base32padupper:()=>CX,base32upper:()=>TX,base32z:()=>PX});var Qc,TX,_X,CX,NX,xX,OX,DX,PX,EI=fe(()=>{h();Ei();Qc=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),TX=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_X=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),CX=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),NX=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xX=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),OX=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DX=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PX=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bI={};Bt(bI,{base36:()=>RX,base36upper:()=>BX});var RX,BX,xR=fe(()=>{h();Ei();RX=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BX=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var SI={};Bt(SI,{base58btc:()=>rs,base58flickr:()=>MX});var rs,MX,II=fe(()=>{h();Ei();rs=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),MX=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var TI={};Bt(TI,{base64:()=>LX,base64pad:()=>FX,base64url:()=>UX,base64urlpad:()=>qX});var LX,FX,UX,qX,OR=fe(()=>{h();Ei();LX=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FX=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),UX=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qX=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var _I={};Bt(_I,{base256emoji:()=>jX});function HX(t){return t.reduce((e,r)=>(e+=VX[r],e),"")}function GX(t){let e=[];for(let r of t){let n=kX[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var DR,VX,kX,jX,PR=fe(()=>{h();Ei();DR=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VX=DR.reduce((t,e,r)=>(t[r]=e,t),[]),kX=DR.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);jX=zc({prefix:"\u{1F680}",name:"base256emoji",encode:HX,decode:GX})});function MR(t,e,r){e=e||[],r=r||0;for(var n=r;t>=WX;)e[r++]=t&255|RR,t/=128;for(;t&KX;)e[r++]=t&255|RR,t>>>=7;return e[r]=t|0,MR.bytes=r-n+1,e}function CI(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw CI.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&BR)<=YX);return CI.bytes=s-n,r}var zX,RR,QX,KX,WX,$X,YX,BR,JX,XX,ZX,eZ,tZ,rZ,nZ,iZ,sZ,oZ,aZ,uZ,bh,LR=fe(()=>{h();zX=MR,RR=128,QX=127,KX=~QX,WX=Math.pow(2,31);$X=CI,YX=128,BR=127;JX=Math.pow(2,7),XX=Math.pow(2,14),ZX=Math.pow(2,21),eZ=Math.pow(2,28),tZ=Math.pow(2,35),rZ=Math.pow(2,42),nZ=Math.pow(2,49),iZ=Math.pow(2,56),sZ=Math.pow(2,63),oZ=function(t){return t{h();LR();Sh=(t,e=0)=>[bh.decode(t,e),bh.decode.bytes],Kc=(t,e,r=0)=>(bh.encode(t,e,r),e),Wc=t=>bh.encodingLength(t)});var Ja,FR,UR,$c,Th=fe(()=>{h();Lo();Tm();Ja=(t,e)=>{let r=e.byteLength,n=Wc(t),i=n+Wc(r),s=new Uint8Array(i+r);return Kc(t,s,0),Kc(r,s,n),s.set(e,i),new $c(t,r,e,s)},FR=t=>{let e=Vs(t),[r,n]=Sh(e),[i,s]=Sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $c(r,i,o,e)},UR=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&vR(t.bytes,e.bytes),$c=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var xI,NI,OI=fe(()=>{h();Th();xI=({name:t,code:e,encode:r})=>new NI(t,e,r),NI=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ja(this.code,r):r.then(n=>Ja(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var DI={};Bt(DI,{sha256:()=>cZ,sha512:()=>lZ});var VR,cZ,lZ,kR=fe(()=>{h();OI();VR=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),cZ=xI({name:"sha2-256",code:18,encode:VR("SHA-256")}),lZ=xI({name:"sha2-512",code:19,encode:VR("SHA-512")})});var PI={};Bt(PI,{identity:()=>dZ});var HR,fZ,GR,hZ,dZ,jR=fe(()=>{h();Lo();Th();HR=0,fZ="identity",GR=Vs,hZ=t=>Ja(HR,GR(t)),dZ={code:HR,name:fZ,encode:GR,digest:hZ}});var zR=fe(()=>{h();Lo()});var $Ee,YEe,QR=fe(()=>{h();$Ee=new TextEncoder,YEe=new TextDecoder});var Nm,mZ,yZ,wZ,_h,vZ,KR,WR,_m,Cm,AZ,EZ,bZ,$R=fe(()=>{h();Tm();Th();II();EI();Lo();Nm=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Cm,byteLength:Cm,code:_m,version:_m,multihash:_m,bytes:_m,_baseCache:Cm,asCID:Cm})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==_h)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==vZ)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ja(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&UR(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return yZ(r,i,e||rs.encoder);default:return wZ(r,i,e||Qc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return EZ(/^0\.0/,bZ),!!(e&&(e[WR]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||KR(r,n,i.bytes))}else if(e!=null&&e[WR]===!0){let{version:r,multihash:n,code:i}=e,s=FR(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==_h)throw new Error(`Version 0 CID must use dag-pb (code: ${_h}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=KR(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_h,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Vs(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $c(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,w]=Sh(e.subarray(r));return r+=w,d},i=n(),s=_h;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,u=n(),a=n(),c=r+a,f=c-o;return{version:i,codec:s,multihashCode:u,digestSize:a,multihashSize:f,size:c}}static parse(e,r){let[n,i]=mZ(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},mZ=(t,e)=>{switch(t[0]){case"Q":{let r=e||rs;return[rs.prefix,r.decode(`${rs.prefix}${t}`)]}case rs.prefix:{let r=e||rs;return[rs.prefix,r.decode(t)]}case Qc.prefix:{let r=e||Qc;return[Qc.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},yZ=(t,e,r)=>{let{prefix:n}=r;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},wZ=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},_h=112,vZ=18,KR=(t,e,r)=>{let n=Wc(t),i=n+Wc(e),s=new Uint8Array(i+r.byteLength);return Kc(t,s,0),Kc(e,s,n),s.set(r,i),s},WR=Symbol.for("@ipld/js-cid/CID"),_m={writable:!1,configurable:!1,enumerable:!0},Cm={writable:!1,enumerable:!1,configurable:!1},AZ="0.0.0-dev",EZ=(t,e)=>{if(t.test(AZ))console.warn(e);else throw new Error(e)},bZ=`CID.isCID(v) is deprecated and will be removed in the next major release. +Following code pattern: -// node_modules/@walletconnect/safe-json/dist/esm/index.js -var esm_exports = {}; -__export(esm_exports, { - safeJsonParse: () => safeJsonParse, - safeJsonStringify: () => safeJsonStringify -}); -function safeJsonParse(value) { - if (typeof value !== "string") { - throw new Error(`Cannot safe json parse value of type ${typeof value}`); - } - try { - return JSONParse(value); - } catch (_a) { - return value; - } -} -function safeJsonStringify(value) { - return typeof value === "string" ? value : JSONStringify(value) || ""; +if (CID.isCID(value)) { + doSomethingWithCID(value) } -var JSONStringify, JSONParse; -var init_esm = __esm({ - "node_modules/@walletconnect/safe-json/dist/esm/index.js"() { - init_shim(); - JSONStringify = (data) => JSON.stringify(data, (_4, value) => typeof value === "bigint" ? value.toString() + "n" : value); - JSONParse = (json) => { - const numbersBiggerThanMaxInt = /([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g; - const serializedData = json.replace(numbersBiggerThanMaxInt, '$1"$2n"$3'); - return JSON.parse(serializedData, (_4, value) => { - const isCustomFormatBigInt = typeof value === "string" && value.match(/^\d+n$/); - if (isCustomFormatBigInt) - return BigInt(value.substring(0, value.length - 1)); - return value; - }); - }; - } -}); -// node_modules/@walletconnect/keyvaluestorage/dist/index.es.js -var index_es_exports = {}; -__export(index_es_exports, { - KeyValueStorage: () => h, - default: () => h -}); -function k(i2) { - var t; - return [i2[0], safeJsonParse((t = i2[1]) != null ? t : "")]; -} -var x, z, D, E, _, l, c, K, N, y, O, j, h; -var init_index_es = __esm({ - "node_modules/@walletconnect/keyvaluestorage/dist/index.es.js"() { - init_shim(); - init_dist2(); - init_dist3(); - init_esm(); - x = "idb-keyval"; - z = (i2 = {}) => { - const t = i2.base && i2.base.length > 0 ? `${i2.base}:` : "", e2 = (s2) => t + s2; - let n3; - return i2.dbName && i2.storeName && (n3 = createStore(i2.dbName, i2.storeName)), { name: x, options: i2, async hasItem(s2) { - return !(typeof await get(e2(s2), n3) > "u"); - }, async getItem(s2) { - return await get(e2(s2), n3) ?? null; - }, setItem(s2, a3) { - return set(e2(s2), a3, n3); - }, removeItem(s2) { - return del(e2(s2), n3); - }, getKeys() { - return keys(n3); - }, clear() { - return clear(n3); - } }; - }; - D = "WALLET_CONNECT_V2_INDEXED_DB"; - E = "keyvaluestorage"; - _ = class { - constructor() { - this.indexedDb = createStorage({ driver: z({ dbName: D, storeName: E }) }); - } - async getKeys() { - return this.indexedDb.getKeys(); - } - async getEntries() { - return (await this.indexedDb.getItems(await this.indexedDb.getKeys())).map((t) => [t.key, t.value]); - } - async getItem(t) { - const e2 = await this.indexedDb.getItem(t); - if (e2 !== null) - return e2; - } - async setItem(t, e2) { - await this.indexedDb.setItem(t, safeJsonStringify(e2)); - } - async removeItem(t) { - await this.indexedDb.removeItem(t); - } - }; - l = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; - c = { exports: {} }; - (function() { - let i2; - function t() { - } - i2 = t, i2.prototype.getItem = function(e2) { - return this.hasOwnProperty(e2) ? String(this[e2]) : null; - }, i2.prototype.setItem = function(e2, n3) { - this[e2] = String(n3); - }, i2.prototype.removeItem = function(e2) { - delete this[e2]; - }, i2.prototype.clear = function() { - const e2 = this; - Object.keys(e2).forEach(function(n3) { - e2[n3] = void 0, delete e2[n3]; - }); - }, i2.prototype.key = function(e2) { - return e2 = e2 || 0, Object.keys(this)[e2]; - }, i2.prototype.__defineGetter__("length", function() { - return Object.keys(this).length; - }), typeof l < "u" && l.localStorage ? c.exports = l.localStorage : typeof window < "u" && window.localStorage ? c.exports = window.localStorage : c.exports = new t(); - })(); - K = class { - constructor() { - this.localStorage = c.exports; - } - async getKeys() { - return Object.keys(this.localStorage); - } - async getEntries() { - return Object.entries(this.localStorage).map(k); - } - async getItem(t) { - const e2 = this.localStorage.getItem(t); - if (e2 !== null) - return safeJsonParse(e2); - } - async setItem(t, e2) { - this.localStorage.setItem(t, safeJsonStringify(e2)); - } - async removeItem(t) { - this.localStorage.removeItem(t); - } - }; - N = "wc_storage_version"; - y = 1; - O = async (i2, t, e2) => { - const n3 = N, s2 = await t.getItem(n3); - if (s2 && s2 >= y) { - e2(t); - return; - } - const a3 = await i2.getKeys(); - if (!a3.length) { - e2(t); - return; - } - const m3 = []; - for (; a3.length; ) { - const r = a3.shift(); - if (!r) - continue; - const o2 = r.toLowerCase(); - if (o2.includes("wc@") || o2.includes("walletconnect") || o2.includes("wc_") || o2.includes("wallet_connect")) { - const f4 = await i2.getItem(r); - await t.setItem(r, f4), m3.push(r); - } - } - await t.setItem(n3, y), e2(t), j(i2, m3); - }; - j = async (i2, t) => { - t.length && t.forEach(async (e2) => { - await i2.removeItem(e2); - }); - }; - h = class { - constructor() { - this.initialized = false, this.setInitialized = (e2) => { - this.storage = e2, this.initialized = true; - }; - const t = new K(); - this.storage = t; - try { - const e2 = new _(); - O(t, e2, this.setInitialized); - } catch { - this.initialized = true; - } - } - async getKeys() { - return await this.initialize(), this.storage.getKeys(); - } - async getEntries() { - return await this.initialize(), this.storage.getEntries(); - } - async getItem(t) { - return await this.initialize(), this.storage.getItem(t); - } - async setItem(t, e2) { - return await this.initialize(), this.storage.setItem(t, e2); - } - async removeItem(t) { - return await this.initialize(), this.storage.removeItem(t); - } - async initialize() { - this.initialized || await new Promise((t) => { - const e2 = setInterval(() => { - this.initialized && (clearInterval(e2), t()); - }, 20); - }); - } - }; - } -}); +Is replaced with: -// node_modules/tslib/tslib.es6.js -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __read: () => __read, - __rest: () => __rest, - __spread: () => __spread, - __spreadArrays: () => __spreadArrays, - __values: () => __values -}); -function __extends(d3, b4) { - extendStatics(d3, b4); - function __() { - this.constructor = d3; - } - d3.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); -} -function __rest(s2, e2) { - var t = {}; - for (var p3 in s2) - if (Object.prototype.hasOwnProperty.call(s2, p3) && e2.indexOf(p3) < 0) - t[p3] = s2[p3]; - if (s2 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i2 = 0, p3 = Object.getOwnPropertySymbols(s2); i2 < p3.length; i2++) { - if (e2.indexOf(p3[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p3[i2])) - t[p3[i2]] = s2[p3[i2]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c4 = arguments.length, r = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") - r = Reflect.decorate(decorators, target, key, desc); - else - for (var i2 = decorators.length - 1; i2 >= 0; i2--) - if (d3 = decorators[i2]) - r = (c4 < 3 ? d3(r) : c4 > 3 ? d3(target, key, r) : d3(target, key)) || r; - return c4 > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") - return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _4 = { label: 0, sent: function() { - if (t[0] & 1) - throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f4, y4, t, g3; - return g3 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() { - return this; - }), g3; - function verb(n3) { - return function(v2) { - return step([n3, v2]); - }; - } - function step(op) { - if (f4) - throw new TypeError("Generator is already executing."); - while (_4) - try { - if (f4 = 1, y4 && (t = op[0] & 2 ? y4["return"] : op[0] ? y4["throw"] || ((t = y4["return"]) && t.call(y4), 0) : y4.next) && !(t = t.call(y4, op[1])).done) - return t; - if (y4 = 0, t) - op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _4.label++; - return { value: op[1], done: false }; - case 5: - _4.label++; - y4 = op[1]; - op = [0]; - continue; - case 7: - op = _4.ops.pop(); - _4.trys.pop(); - continue; - default: - if (!(t = _4.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _4 = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _4.label = op[1]; - break; - } - if (op[0] === 6 && _4.label < t[1]) { - _4.label = t[1]; - t = op; - break; - } - if (t && _4.label < t[2]) { - _4.label = t[2]; - _4.ops.push(op); - break; - } - if (t[2]) - _4.ops.pop(); - _4.trys.pop(); - continue; - } - op = body.call(thisArg, _4); - } catch (e2) { - op = [6, e2]; - y4 = 0; - } finally { - f4 = t = 0; - } - if (op[0] & 5) - throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __createBinding(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; -} -function __exportStar(m3, exports2) { - for (var p3 in m3) - if (p3 !== "default" && !exports2.hasOwnProperty(p3)) - exports2[p3] = m3[p3]; -} -function __values(o2) { - var s2 = typeof Symbol === "function" && Symbol.iterator, m3 = s2 && o2[s2], i2 = 0; - if (m3) - return m3.call(o2); - if (o2 && typeof o2.length === "number") - return { - next: function() { - if (o2 && i2 >= o2.length) - o2 = void 0; - return { value: o2 && o2[i2++], done: !o2 }; - } - }; - throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o2, n3) { - var m3 = typeof Symbol === "function" && o2[Symbol.iterator]; - if (!m3) - return o2; - var i2 = m3.call(o2), r, ar = [], e2; - try { - while ((n3 === void 0 || n3-- > 0) && !(r = i2.next()).done) - ar.push(r.value); - } catch (error) { - e2 = { error }; - } finally { - try { - if (r && !r.done && (m3 = i2["return"])) - m3.call(i2); - } finally { - if (e2) - throw e2.error; - } - } - return ar; -} -function __spread() { - for (var ar = [], i2 = 0; i2 < arguments.length; i2++) - ar = ar.concat(__read(arguments[i2])); - return ar; -} -function __spreadArrays() { - for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) - s2 += arguments[i2].length; - for (var r = Array(s2), k4 = 0, i2 = 0; i2 < il; i2++) - for (var a3 = arguments[i2], j2 = 0, jl = a3.length; j2 < jl; j2++, k4++) - r[k4] = a3[j2]; - return r; -} -function __await(v2) { - return this instanceof __await ? (this.v = v2, this) : new __await(v2); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g3 = generator.apply(thisArg, _arguments || []), i2, q2 = []; - return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { - return this; - }, i2; - function verb(n3) { - if (g3[n3]) - i2[n3] = function(v2) { - return new Promise(function(a3, b4) { - q2.push([n3, v2, a3, b4]) > 1 || resume(n3, v2); - }); - }; - } - function resume(n3, v2) { - try { - step(g3[n3](v2)); - } catch (e2) { - settle(q2[0][3], e2); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f4, v2) { - if (f4(v2), q2.shift(), q2.length) - resume(q2[0][0], q2[0][1]); - } -} -function __asyncDelegator(o2) { - var i2, p3; - return i2 = {}, verb("next"), verb("throw", function(e2) { - throw e2; - }), verb("return"), i2[Symbol.iterator] = function() { - return this; - }, i2; - function verb(n3, f4) { - i2[n3] = o2[n3] ? function(v2) { - return (p3 = !p3) ? { value: __await(o2[n3](v2)), done: n3 === "return" } : f4 ? f4(v2) : v2; - } : f4; - } -} -function __asyncValues(o2) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var m3 = o2[Symbol.asyncIterator], i2; - return m3 ? m3.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { - return this; - }, i2); - function verb(n3) { - i2[n3] = o2[n3] && function(v2) { - return new Promise(function(resolve, reject) { - v2 = o2[n3](v2), settle(resolve, reject, v2.done, v2.value); - }); - }; - } - function settle(resolve, reject, d3, v2) { - Promise.resolve(v2).then(function(v3) { - resolve({ value: v3, done: d3 }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod2) { - if (mod2 && mod2.__esModule) - return mod2; - var result = {}; - if (mod2 != null) { - for (var k4 in mod2) - if (Object.hasOwnProperty.call(mod2, k4)) - result[k4] = mod2[k4]; - } - result.default = mod2; - return result; -} -function __importDefault(mod2) { - return mod2 && mod2.__esModule ? mod2 : { default: mod2 }; -} -function __classPrivateFieldGet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); -} -function __classPrivateFieldSet(receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) } -var extendStatics, __assign; -var init_tslib_es6 = __esm({ - "node_modules/tslib/tslib.es6.js"() { - init_shim(); - extendStatics = function(d3, b4) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b5) { - d4.__proto__ = b5; - } || function(d4, b5) { - for (var p3 in b5) - if (b5.hasOwnProperty(p3)) - d4[p3] = b5[p3]; - }; - return extendStatics(d3, b4); - }; - __assign = function() { - __assign = Object.assign || function __assign2(t) { - for (var s2, i2 = 1, n3 = arguments.length; i2 < n3; i2++) { - s2 = arguments[i2]; - for (var p3 in s2) - if (Object.prototype.hasOwnProperty.call(s2, p3)) - t[p3] = s2[p3]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/utils/delay.js -var require_delay = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/utils/delay.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.delay = void 0; - function delay(timeout) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(true); - }, timeout); - }); - } - exports2.delay = delay; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/constants/misc.js -var require_misc = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/constants/misc.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ONE_THOUSAND = exports2.ONE_HUNDRED = void 0; - exports2.ONE_HUNDRED = 100; - exports2.ONE_THOUSAND = 1e3; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/constants/time.js -var require_time = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/constants/time.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ONE_YEAR = exports2.FOUR_WEEKS = exports2.THREE_WEEKS = exports2.TWO_WEEKS = exports2.ONE_WEEK = exports2.THIRTY_DAYS = exports2.SEVEN_DAYS = exports2.FIVE_DAYS = exports2.THREE_DAYS = exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS = exports2.TWELVE_HOURS = exports2.SIX_HOURS = exports2.THREE_HOURS = exports2.ONE_HOUR = exports2.SIXTY_MINUTES = exports2.THIRTY_MINUTES = exports2.TEN_MINUTES = exports2.FIVE_MINUTES = exports2.ONE_MINUTE = exports2.SIXTY_SECONDS = exports2.THIRTY_SECONDS = exports2.TEN_SECONDS = exports2.FIVE_SECONDS = exports2.ONE_SECOND = void 0; - exports2.ONE_SECOND = 1; - exports2.FIVE_SECONDS = 5; - exports2.TEN_SECONDS = 10; - exports2.THIRTY_SECONDS = 30; - exports2.SIXTY_SECONDS = 60; - exports2.ONE_MINUTE = exports2.SIXTY_SECONDS; - exports2.FIVE_MINUTES = exports2.ONE_MINUTE * 5; - exports2.TEN_MINUTES = exports2.ONE_MINUTE * 10; - exports2.THIRTY_MINUTES = exports2.ONE_MINUTE * 30; - exports2.SIXTY_MINUTES = exports2.ONE_MINUTE * 60; - exports2.ONE_HOUR = exports2.SIXTY_MINUTES; - exports2.THREE_HOURS = exports2.ONE_HOUR * 3; - exports2.SIX_HOURS = exports2.ONE_HOUR * 6; - exports2.TWELVE_HOURS = exports2.ONE_HOUR * 12; - exports2.TWENTY_FOUR_HOURS = exports2.ONE_HOUR * 24; - exports2.ONE_DAY = exports2.TWENTY_FOUR_HOURS; - exports2.THREE_DAYS = exports2.ONE_DAY * 3; - exports2.FIVE_DAYS = exports2.ONE_DAY * 5; - exports2.SEVEN_DAYS = exports2.ONE_DAY * 7; - exports2.THIRTY_DAYS = exports2.ONE_DAY * 30; - exports2.ONE_WEEK = exports2.SEVEN_DAYS; - exports2.TWO_WEEKS = exports2.ONE_WEEK * 2; - exports2.THREE_WEEKS = exports2.ONE_WEEK * 3; - exports2.FOUR_WEEKS = exports2.ONE_WEEK * 4; - exports2.ONE_YEAR = exports2.ONE_DAY * 365; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/constants/index.js -var require_constants4 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/constants/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_misc(), exports2); - tslib_1.__exportStar(require_time(), exports2); - } -}); - -// node_modules/@walletconnect/time/dist/cjs/utils/convert.js -var require_convert = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/utils/convert.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.fromMiliseconds = exports2.toMiliseconds = void 0; - var constants_1 = require_constants4(); - function toMiliseconds(seconds) { - return seconds * constants_1.ONE_THOUSAND; - } - exports2.toMiliseconds = toMiliseconds; - function fromMiliseconds2(miliseconds) { - return Math.floor(miliseconds / constants_1.ONE_THOUSAND); - } - exports2.fromMiliseconds = fromMiliseconds2; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/utils/index.js -var require_utils3 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/utils/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_delay(), exports2); - tslib_1.__exportStar(require_convert(), exports2); - } -}); - -// node_modules/@walletconnect/time/dist/cjs/watch.js -var require_watch = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/watch.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Watch = void 0; - var Watch = class { - constructor() { - this.timestamps = /* @__PURE__ */ new Map(); - } - start(label) { - if (this.timestamps.has(label)) { - throw new Error(`Watch already started for label: ${label}`); - } - this.timestamps.set(label, { started: Date.now() }); - } - stop(label) { - const timestamp = this.get(label); - if (typeof timestamp.elapsed !== "undefined") { - throw new Error(`Watch already stopped for label: ${label}`); - } - const elapsed = Date.now() - timestamp.started; - this.timestamps.set(label, { started: timestamp.started, elapsed }); - } - get(label) { - const timestamp = this.timestamps.get(label); - if (typeof timestamp === "undefined") { - throw new Error(`No timestamp found for label: ${label}`); - } - return timestamp; - } - elapsed(label) { - const timestamp = this.get(label); - const elapsed = timestamp.elapsed || Date.now() - timestamp.started; - return elapsed; - } - }; - exports2.Watch = Watch; - exports2.default = Watch; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/types/watch.js -var require_watch2 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/types/watch.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.IWatch = void 0; - var IWatch = class { - }; - exports2.IWatch = IWatch; - } -}); - -// node_modules/@walletconnect/time/dist/cjs/types/index.js -var require_types2 = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/types/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_watch2(), exports2); - } -}); - -// node_modules/@walletconnect/time/dist/cjs/index.js -var require_cjs = __commonJS({ - "node_modules/@walletconnect/time/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_utils3(), exports2); - tslib_1.__exportStar(require_watch(), exports2); - tslib_1.__exportStar(require_types2(), exports2); - tslib_1.__exportStar(require_constants4(), exports2); - } -}); - -// node_modules/@walletconnect/events/dist/esm/events.js -var IEvents; -var init_events = __esm({ - "node_modules/@walletconnect/events/dist/esm/events.js"() { - init_shim(); - IEvents = class { - }; - } -}); - -// node_modules/@walletconnect/events/dist/esm/index.js -var esm_exports2 = {}; -__export(esm_exports2, { - IEvents: () => IEvents -}); -var init_esm2 = __esm({ - "node_modules/@walletconnect/events/dist/esm/index.js"() { - init_shim(); - init_events(); - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js -var require_heartbeat = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/types/heartbeat.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.IHeartBeat = void 0; - var events_1 = (init_esm2(), __toCommonJS(esm_exports2)); - var IHeartBeat = class extends events_1.IEvents { - constructor(opts) { - super(); - } - }; - exports2.IHeartBeat = IHeartBeat; - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js -var require_types3 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/types/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_heartbeat(), exports2); - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js -var require_heartbeat2 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/constants/heartbeat.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HEARTBEAT_EVENTS = exports2.HEARTBEAT_INTERVAL = void 0; - var time_1 = require_cjs(); - exports2.HEARTBEAT_INTERVAL = time_1.FIVE_SECONDS; - exports2.HEARTBEAT_EVENTS = { - pulse: "heartbeat_pulse" - }; - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js -var require_constants5 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/constants/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_heartbeat2(), exports2); - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js -var require_heartbeat3 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/heartbeat.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.HeartBeat = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var events_1 = require_events(); - var time_1 = require_cjs(); - var types_1 = require_types3(); - var constants_1 = require_constants5(); - var HeartBeat = class _HeartBeat extends types_1.IHeartBeat { - constructor(opts) { - super(opts); - this.events = new events_1.EventEmitter(); - this.interval = constants_1.HEARTBEAT_INTERVAL; - this.interval = (opts === null || opts === void 0 ? void 0 : opts.interval) || constants_1.HEARTBEAT_INTERVAL; - } - static init(opts) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const heartbeat = new _HeartBeat(opts); - yield heartbeat.init(); - return heartbeat; - }); - } - init() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - yield this.initialize(); - }); - } - stop() { - clearInterval(this.intervalRef); - } - on(event, listener) { - this.events.on(event, listener); - } - once(event, listener) { - this.events.once(event, listener); - } - off(event, listener) { - this.events.off(event, listener); - } - removeListener(event, listener) { - this.events.removeListener(event, listener); - } - initialize() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - this.intervalRef = setInterval(() => this.pulse(), time_1.toMiliseconds(this.interval)); - }); - } - pulse() { - this.events.emit(constants_1.HEARTBEAT_EVENTS.pulse); - } - }; - exports2.HeartBeat = HeartBeat; - } -}); - -// node_modules/@walletconnect/heartbeat/dist/cjs/index.js -var require_cjs2 = __commonJS({ - "node_modules/@walletconnect/heartbeat/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_heartbeat3(), exports2); - tslib_1.__exportStar(require_types3(), exports2); - tslib_1.__exportStar(require_constants5(), exports2); - } -}); - -// node_modules/quick-format-unescaped/index.js -var require_quick_format_unescaped = __commonJS({ - "node_modules/quick-format-unescaped/index.js"(exports2, module2) { - "use strict"; - init_shim(); - function tryStringify(o2) { - try { - return JSON.stringify(o2); - } catch (e2) { - return '"[Circular]"'; - } - } - module2.exports = format; - function format(f4, args, opts) { - var ss = opts && opts.stringify || tryStringify; - var offset = 1; - if (typeof f4 === "object" && f4 !== null) { - var len = args.length + offset; - if (len === 1) - return f4; - var objects = new Array(len); - objects[0] = ss(f4); - for (var index = 1; index < len; index++) { - objects[index] = ss(args[index]); - } - return objects.join(" "); - } - if (typeof f4 !== "string") { - return f4; - } - var argLen = args.length; - if (argLen === 0) - return f4; - var str = ""; - var a3 = 1 - offset; - var lastPos = -1; - var flen = f4 && f4.length || 0; - for (var i2 = 0; i2 < flen; ) { - if (f4.charCodeAt(i2) === 37 && i2 + 1 < flen) { - lastPos = lastPos > -1 ? lastPos : 0; - switch (f4.charCodeAt(i2 + 1)) { - case 100: - case 102: - if (a3 >= argLen) - break; - if (args[a3] == null) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += Number(args[a3]); - lastPos = i2 + 2; - i2++; - break; - case 105: - if (a3 >= argLen) - break; - if (args[a3] == null) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += Math.floor(Number(args[a3])); - lastPos = i2 + 2; - i2++; - break; - case 79: - case 111: - case 106: - if (a3 >= argLen) - break; - if (args[a3] === void 0) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - var type = typeof args[a3]; - if (type === "string") { - str += "'" + args[a3] + "'"; - lastPos = i2 + 2; - i2++; - break; - } - if (type === "function") { - str += args[a3].name || ""; - lastPos = i2 + 2; - i2++; - break; - } - str += ss(args[a3]); - lastPos = i2 + 2; - i2++; - break; - case 115: - if (a3 >= argLen) - break; - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += String(args[a3]); - lastPos = i2 + 2; - i2++; - break; - case 37: - if (lastPos < i2) - str += f4.slice(lastPos, i2); - str += "%"; - lastPos = i2 + 2; - i2++; - a3--; - break; - } - ++a3; - } - ++i2; - } - if (lastPos === -1) - return f4; - else if (lastPos < flen) { - str += f4.slice(lastPos); - } - return str; - } - } -}); - -// node_modules/pino/browser.js -var require_browser3 = __commonJS({ - "node_modules/pino/browser.js"(exports2, module2) { - "use strict"; - init_shim(); - var format = require_quick_format_unescaped(); - module2.exports = pino; - var _console = pfGlobalThisOrFallback().console || {}; - var stdSerializers = { - mapHttpRequest: mock, - mapHttpResponse: mock, - wrapRequestSerializer: passthrough, - wrapResponseSerializer: passthrough, - wrapErrorSerializer: passthrough, - req: mock, - res: mock, - err: asErrValue - }; - function shouldSerialize(serialize, serializers) { - if (Array.isArray(serialize)) { - const hasToFilter = serialize.filter(function(k4) { - return k4 !== "!stdSerializers.err"; - }); - return hasToFilter; - } else if (serialize === true) { - return Object.keys(serializers); - } - return false; - } - function pino(opts) { - opts = opts || {}; - opts.browser = opts.browser || {}; - const transmit2 = opts.browser.transmit; - if (transmit2 && typeof transmit2.send !== "function") { - throw Error("pino: transmit option must have a send function"); - } - const proto = opts.browser.write || _console; - if (opts.browser.write) - opts.browser.asObject = true; - const serializers = opts.serializers || {}; - const serialize = shouldSerialize(opts.browser.serialize, serializers); - let stdErrSerialize = opts.browser.serialize; - if (Array.isArray(opts.browser.serialize) && opts.browser.serialize.indexOf("!stdSerializers.err") > -1) - stdErrSerialize = false; - const levels = ["error", "fatal", "warn", "info", "debug", "trace"]; - if (typeof proto === "function") { - proto.error = proto.fatal = proto.warn = proto.info = proto.debug = proto.trace = proto; - } - if (opts.enabled === false) - opts.level = "silent"; - const level = opts.level || "info"; - const logger = Object.create(proto); - if (!logger.log) - logger.log = noop; - Object.defineProperty(logger, "levelVal", { - get: getLevelVal - }); - Object.defineProperty(logger, "level", { - get: getLevel, - set: setLevel - }); - const setOpts = { - transmit: transmit2, - serialize, - asObject: opts.browser.asObject, - levels, - timestamp: getTimeFunction(opts) - }; - logger.levels = pino.levels; - logger.level = level; - logger.setMaxListeners = logger.getMaxListeners = logger.emit = logger.addListener = logger.on = logger.prependListener = logger.once = logger.prependOnceListener = logger.removeListener = logger.removeAllListeners = logger.listeners = logger.listenerCount = logger.eventNames = logger.write = logger.flush = noop; - logger.serializers = serializers; - logger._serialize = serialize; - logger._stdErrSerialize = stdErrSerialize; - logger.child = child; - if (transmit2) - logger._logEvent = createLogEventShape(); - function getLevelVal() { - return this.level === "silent" ? Infinity : this.levels.values[this.level]; - } - function getLevel() { - return this._level; - } - function setLevel(level2) { - if (level2 !== "silent" && !this.levels.values[level2]) { - throw Error("unknown level " + level2); - } - this._level = level2; - set2(setOpts, logger, "error", "log"); - set2(setOpts, logger, "fatal", "error"); - set2(setOpts, logger, "warn", "error"); - set2(setOpts, logger, "info", "log"); - set2(setOpts, logger, "debug", "log"); - set2(setOpts, logger, "trace", "log"); - } - function child(bindings, childOptions) { - if (!bindings) { - throw new Error("missing bindings for child Pino"); - } - childOptions = childOptions || {}; - if (serialize && bindings.serializers) { - childOptions.serializers = bindings.serializers; - } - const childOptionsSerializers = childOptions.serializers; - if (serialize && childOptionsSerializers) { - var childSerializers = Object.assign({}, serializers, childOptionsSerializers); - var childSerialize = opts.browser.serialize === true ? Object.keys(childSerializers) : serialize; - delete bindings.serializers; - applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize); - } - function Child(parent) { - this._childLevel = (parent._childLevel | 0) + 1; - this.error = bind(parent, bindings, "error"); - this.fatal = bind(parent, bindings, "fatal"); - this.warn = bind(parent, bindings, "warn"); - this.info = bind(parent, bindings, "info"); - this.debug = bind(parent, bindings, "debug"); - this.trace = bind(parent, bindings, "trace"); - if (childSerializers) { - this.serializers = childSerializers; - this._serialize = childSerialize; - } - if (transmit2) { - this._logEvent = createLogEventShape( - [].concat(parent._logEvent.bindings, bindings) - ); - } - } - Child.prototype = this; - return new Child(this); - } - return logger; - } - pino.levels = { - values: { - fatal: 60, - error: 50, - warn: 40, - info: 30, - debug: 20, - trace: 10 - }, - labels: { - 10: "trace", - 20: "debug", - 30: "info", - 40: "warn", - 50: "error", - 60: "fatal" - } - }; - pino.stdSerializers = stdSerializers; - pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime }); - function set2(opts, logger, level, fallback) { - const proto = Object.getPrototypeOf(logger); - logger[level] = logger.levelVal > logger.levels.values[level] ? noop : proto[level] ? proto[level] : _console[level] || _console[fallback] || noop; - wrap(opts, logger, level); - } - function wrap(opts, logger, level) { - if (!opts.transmit && logger[level] === noop) - return; - logger[level] = /* @__PURE__ */ function(write) { - return function LOG() { - const ts = opts.timestamp(); - const args = new Array(arguments.length); - const proto = Object.getPrototypeOf && Object.getPrototypeOf(this) === _console ? _console : this; - for (var i2 = 0; i2 < args.length; i2++) - args[i2] = arguments[i2]; - if (opts.serialize && !opts.asObject) { - applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize); - } - if (opts.asObject) - write.call(proto, asObject(this, level, args, ts)); - else - write.apply(proto, args); - if (opts.transmit) { - const transmitLevel = opts.transmit.level || logger.level; - const transmitValue = pino.levels.values[transmitLevel]; - const methodValue = pino.levels.values[level]; - if (methodValue < transmitValue) - return; - transmit(this, { - ts, - methodLevel: level, - methodValue, - transmitLevel, - transmitValue: pino.levels.values[opts.transmit.level || logger.level], - send: opts.transmit.send, - val: logger.levelVal - }, args); - } - }; - }(logger[level]); - } - function asObject(logger, level, args, ts) { - if (logger._serialize) - applySerializers(args, logger._serialize, logger.serializers, logger._stdErrSerialize); - const argsCloned = args.slice(); - let msg = argsCloned[0]; - const o2 = {}; - if (ts) { - o2.time = ts; - } - o2.level = pino.levels.values[level]; - let lvl = (logger._childLevel | 0) + 1; - if (lvl < 1) - lvl = 1; - if (msg !== null && typeof msg === "object") { - while (lvl-- && typeof argsCloned[0] === "object") { - Object.assign(o2, argsCloned.shift()); - } - msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : void 0; - } else if (typeof msg === "string") - msg = format(argsCloned.shift(), argsCloned); - if (msg !== void 0) - o2.msg = msg; - return o2; - } - function applySerializers(args, serialize, serializers, stdErrSerialize) { - for (const i2 in args) { - if (stdErrSerialize && args[i2] instanceof Error) { - args[i2] = pino.stdSerializers.err(args[i2]); - } else if (typeof args[i2] === "object" && !Array.isArray(args[i2])) { - for (const k4 in args[i2]) { - if (serialize && serialize.indexOf(k4) > -1 && k4 in serializers) { - args[i2][k4] = serializers[k4](args[i2][k4]); - } - } - } - } - } - function bind(parent, bindings, level) { - return function() { - const args = new Array(1 + arguments.length); - args[0] = bindings; - for (var i2 = 1; i2 < args.length; i2++) { - args[i2] = arguments[i2 - 1]; - } - return parent[level].apply(this, args); - }; - } - function transmit(logger, opts, args) { - const send = opts.send; - const ts = opts.ts; - const methodLevel = opts.methodLevel; - const methodValue = opts.methodValue; - const val = opts.val; - const bindings = logger._logEvent.bindings; - applySerializers( - args, - logger._serialize || Object.keys(logger.serializers), - logger.serializers, - logger._stdErrSerialize === void 0 ? true : logger._stdErrSerialize - ); - logger._logEvent.ts = ts; - logger._logEvent.messages = args.filter(function(arg) { - return bindings.indexOf(arg) === -1; - }); - logger._logEvent.level.label = methodLevel; - logger._logEvent.level.value = methodValue; - send(methodLevel, logger._logEvent, val); - logger._logEvent = createLogEventShape(bindings); - } - function createLogEventShape(bindings) { - return { - ts: 0, - messages: [], - bindings: bindings || [], - level: { label: "", value: 0 } - }; - } - function asErrValue(err) { - const obj = { - type: err.constructor.name, - msg: err.message, - stack: err.stack - }; - for (const key in err) { - if (obj[key] === void 0) { - obj[key] = err[key]; - } - } - return obj; - } - function getTimeFunction(opts) { - if (typeof opts.timestamp === "function") { - return opts.timestamp; - } - if (opts.timestamp === false) { - return nullTime; - } - return epochTime; - } - function mock() { - return {}; - } - function passthrough(a3) { - return a3; - } - function noop() { - } - function nullTime() { - return false; - } - function epochTime() { - return Date.now(); - } - function unixTime() { - return Math.round(Date.now() / 1e3); - } - function isoTime() { - return new Date(Date.now()).toISOString(); - } - function pfGlobalThisOrFallback() { - function defd(o2) { - return typeof o2 !== "undefined" && o2; - } - try { - if (typeof globalThis !== "undefined") - return globalThis; - Object.defineProperty(Object.prototype, "globalThis", { - get: function() { - delete Object.prototype.globalThis; - return this.globalThis = this; - }, - configurable: true - }); - return globalThis; - } catch (e2) { - return defd(self) || defd(window) || defd(this) || {}; - } - } - } -}); - -// node_modules/@walletconnect/logger/dist/index.es.js -var index_es_exports2 = {}; -__export(index_es_exports2, { - MAX_LOG_SIZE_IN_BYTES_DEFAULT: () => l2, - PINO_CUSTOM_CONTEXT_KEY: () => n, - PINO_LOGGER_DEFAULTS: () => c2, - formatChildLoggerContext: () => w, - generateChildLogger: () => E2, - generateClientLogger: () => C, - generatePlatformLogger: () => A, - generateServerLogger: () => I, - getBrowserLoggerContext: () => v, - getDefaultLoggerOptions: () => k2, - getLoggerContext: () => y2, - pino: () => import_pino2.default, - setBrowserLoggerContext: () => b -}); -function k2(r) { - return g(i({}, r), { level: r?.level || c2.level }); -} -function v(r, e2 = n) { - return r[e2] || ""; -} -function b(r, e2, t = n) { - return r[t] = e2, r; -} -function y2(r, e2 = n) { - let t = ""; - return typeof r.bindings > "u" ? t = v(r, e2) : t = r.bindings().context || "", t; -} -function w(r, e2, t = n) { - const o2 = y2(r, t); - return o2.trim() ? `${o2}/${e2}` : e2; -} -function E2(r, e2, t = n) { - const o2 = w(r, e2, t), a3 = r.child({ context: o2 }); - return b(a3, o2, t); -} -function C(r) { - var e2, t; - const o2 = new m((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); - return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace", browser: g(i({}, (t = r.opts) == null ? void 0 : t.browser), { write: (a3) => o2.write(a3) }) })), chunkLoggerController: o2 }; -} -function I(r) { - var e2; - const t = new B((e2 = r.opts) == null ? void 0 : e2.level, r.maxSizeInBytes); - return { logger: (0, import_pino.default)(g(i({}, r.opts), { level: "trace" }), t), chunkLoggerController: t }; -} -function A(r) { - return typeof r.loggerOverride < "u" && typeof r.loggerOverride != "string" ? { logger: r.loggerOverride, chunkLoggerController: null } : typeof window < "u" ? C(r) : I(r); -} -var import_pino, import_pino2, c2, n, l2, O2, d, L, m, B, x2, S, _2, p, T, z2, f, i, g; -var init_index_es2 = __esm({ - "node_modules/@walletconnect/logger/dist/index.es.js"() { - init_shim(); - import_pino = __toESM(require_browser3()); - import_pino2 = __toESM(require_browser3()); - init_esm(); - c2 = { level: "info" }; - n = "custom_context"; - l2 = 1e3 * 1024; - O2 = class { - constructor(e2) { - this.nodeValue = e2, this.sizeInBytes = new TextEncoder().encode(this.nodeValue).length, this.next = null; - } - get value() { - return this.nodeValue; - } - get size() { - return this.sizeInBytes; - } - }; - d = class { - constructor(e2) { - this.head = null, this.tail = null, this.lengthInNodes = 0, this.maxSizeInBytes = e2, this.sizeInBytes = 0; - } - append(e2) { - const t = new O2(e2); - if (t.size > this.maxSizeInBytes) - throw new Error(`[LinkedList] Value too big to insert into list: ${e2} with size ${t.size}`); - for (; this.size + t.size > this.maxSizeInBytes; ) - this.shift(); - this.head ? (this.tail && (this.tail.next = t), this.tail = t) : (this.head = t, this.tail = t), this.lengthInNodes++, this.sizeInBytes += t.size; - } - shift() { - if (!this.head) - return; - const e2 = this.head; - this.head = this.head.next, this.head || (this.tail = null), this.lengthInNodes--, this.sizeInBytes -= e2.size; - } - toArray() { - const e2 = []; - let t = this.head; - for (; t !== null; ) - e2.push(t.value), t = t.next; - return e2; - } - get length() { - return this.lengthInNodes; - } - get size() { - return this.sizeInBytes; - } - toOrderedArray() { - return Array.from(this); - } - [Symbol.iterator]() { - let e2 = this.head; - return { next: () => { - if (!e2) - return { done: true, value: null }; - const t = e2.value; - return e2 = e2.next, { done: false, value: t }; - } }; - } - }; - L = class { - constructor(e2, t = l2) { - this.level = e2 ?? "error", this.levelValue = import_pino.levels.values[this.level], this.MAX_LOG_SIZE_IN_BYTES = t, this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); - } - forwardToConsole(e2, t) { - t === import_pino.levels.values.error ? console.error(e2) : t === import_pino.levels.values.warn ? console.warn(e2) : t === import_pino.levels.values.debug ? console.debug(e2) : t === import_pino.levels.values.trace ? console.trace(e2) : console.log(e2); - } - appendToLogs(e2) { - this.logs.append(safeJsonStringify({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), log: e2 })); - const t = typeof e2 == "string" ? JSON.parse(e2).level : e2.level; - t >= this.levelValue && this.forwardToConsole(e2, t); - } - getLogs() { - return this.logs; - } - clearLogs() { - this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); - } - getLogArray() { - return Array.from(this.logs); - } - logsToBlob(e2) { - const t = this.getLogArray(); - return t.push(safeJsonStringify({ extraMetadata: e2 })), new Blob(t, { type: "application/json" }); - } - }; - m = class { - constructor(e2, t = l2) { - this.baseChunkLogger = new L(e2, t); - } - write(e2) { - this.baseChunkLogger.appendToLogs(e2); - } - getLogs() { - return this.baseChunkLogger.getLogs(); - } - clearLogs() { - this.baseChunkLogger.clearLogs(); - } - getLogArray() { - return this.baseChunkLogger.getLogArray(); - } - logsToBlob(e2) { - return this.baseChunkLogger.logsToBlob(e2); - } - downloadLogsBlobInBrowser(e2) { - const t = URL.createObjectURL(this.logsToBlob(e2)), o2 = document.createElement("a"); - o2.href = t, o2.download = `walletconnect-logs-${(/* @__PURE__ */ new Date()).toISOString()}.txt`, document.body.appendChild(o2), o2.click(), document.body.removeChild(o2), URL.revokeObjectURL(t); - } - }; - B = class { - constructor(e2, t = l2) { - this.baseChunkLogger = new L(e2, t); - } - write(e2) { - this.baseChunkLogger.appendToLogs(e2); - } - getLogs() { - return this.baseChunkLogger.getLogs(); - } - clearLogs() { - this.baseChunkLogger.clearLogs(); - } - getLogArray() { - return this.baseChunkLogger.getLogArray(); - } - logsToBlob(e2) { - return this.baseChunkLogger.logsToBlob(e2); - } - }; - x2 = Object.defineProperty; - S = Object.defineProperties; - _2 = Object.getOwnPropertyDescriptors; - p = Object.getOwnPropertySymbols; - T = Object.prototype.hasOwnProperty; - z2 = Object.prototype.propertyIsEnumerable; - f = (r, e2, t) => e2 in r ? x2(r, e2, { enumerable: true, configurable: true, writable: true, value: t }) : r[e2] = t; - i = (r, e2) => { - for (var t in e2 || (e2 = {})) - T.call(e2, t) && f(r, t, e2[t]); - if (p) - for (var t of p(e2)) - z2.call(e2, t) && f(r, t, e2[t]); - return r; - }; - g = (r, e2) => S(r, _2(e2)); - } -}); - -// node_modules/@walletconnect/types/dist/index.cjs.js -var require_index_cjs = __commonJS({ - "node_modules/@walletconnect/types/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var r = (init_esm2(), __toCommonJS(esm_exports2)); - var c4 = require_events(); - function i2(t) { - return t && typeof t == "object" && "default" in t ? t : { default: t }; - } - var n3 = i2(c4); - var l4 = class extends r.IEvents { - constructor(s2) { - super(), this.opts = s2, this.protocol = "wc", this.version = 2; - } - }; - var a3 = class { - constructor(s2, e2, o2) { - this.core = s2, this.logger = e2; - } - }; - var u3 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.core = s2, this.logger = e2, this.records = /* @__PURE__ */ new Map(); - } - }; - var I2 = class { - constructor(s2, e2) { - this.logger = s2, this.core = e2; - } - }; - var h5 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.relayer = s2, this.logger = e2; - } - }; - var g3 = class extends r.IEvents { - constructor(s2) { - super(); - } - }; - var p3 = class { - constructor(s2, e2, o2, _4) { - this.core = s2, this.logger = e2, this.name = o2; - } - }; - var E4 = class { - constructor() { - this.map = /* @__PURE__ */ new Map(); - } - }; - var v2 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.relayer = s2, this.logger = e2; - } - }; - var d3 = class { - constructor(s2, e2) { - this.core = s2, this.logger = e2; - } - }; - var y4 = class extends r.IEvents { - constructor(s2, e2) { - super(), this.core = s2, this.logger = e2; - } - }; - var b4 = class { - constructor(s2, e2) { - this.logger = s2, this.core = e2; - } - }; - var C3 = class { - constructor(s2, e2) { - this.projectId = s2, this.logger = e2; - } - }; - var f4 = class { - constructor(s2, e2) { - this.projectId = s2, this.logger = e2; - } - }; - var x3 = class extends n3.default { - constructor() { - super(); - } - }; - var S4 = class { - constructor(s2) { - this.opts = s2, this.protocol = "wc", this.version = 2; - } - }; - var M = class extends c4.EventEmitter { - constructor() { - super(); - } - }; - var P2 = class { - constructor(s2) { - this.client = s2; - } - }; - exports2.ICore = l4, exports2.ICrypto = a3, exports2.IEchoClient = f4, exports2.IEngine = P2, exports2.IEngineEvents = M, exports2.IExpirer = y4, exports2.IJsonRpcHistory = u3, exports2.IKeyChain = d3, exports2.IMessageTracker = I2, exports2.IPairing = b4, exports2.IPublisher = h5, exports2.IRelayer = g3, exports2.ISignClient = S4, exports2.ISignClientEvents = x3, exports2.IStore = p3, exports2.ISubscriber = v2, exports2.ISubscriberTopicMap = E4, exports2.IVerify = C3; - } -}); - -// node_modules/@stablelib/random/lib/source/browser.js -var require_browser4 = __commonJS({ - "node_modules/@stablelib/random/lib/source/browser.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BrowserRandomSource = void 0; - var QUOTA = 65536; - var BrowserRandomSource = class { - constructor() { - this.isAvailable = false; - this.isInstantiated = false; - const browserCrypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; - if (browserCrypto && browserCrypto.getRandomValues !== void 0) { - this._crypto = browserCrypto; - this.isAvailable = true; - this.isInstantiated = true; - } - } - randomBytes(length2) { - if (!this.isAvailable || !this._crypto) { - throw new Error("Browser random byte generator is not available."); - } - const out = new Uint8Array(length2); - for (let i2 = 0; i2 < out.length; i2 += QUOTA) { - this._crypto.getRandomValues(out.subarray(i2, i2 + Math.min(out.length - i2, QUOTA))); - } - return out; - } - }; - exports2.BrowserRandomSource = BrowserRandomSource; - } -}); - -// node_modules/@stablelib/wipe/lib/wipe.js -var require_wipe = __commonJS({ - "node_modules/@stablelib/wipe/lib/wipe.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function wipe(array) { - for (var i2 = 0; i2 < array.length; i2++) { - array[i2] = 0; - } - return array; - } - exports2.wipe = wipe; - } -}); - -// (disabled):crypto -var require_crypto = __commonJS({ - "(disabled):crypto"() { - init_shim(); - } -}); - -// node_modules/@stablelib/random/lib/source/node.js -var require_node = __commonJS({ - "node_modules/@stablelib/random/lib/source/node.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NodeRandomSource = void 0; - var wipe_1 = require_wipe(); - var NodeRandomSource = class { - constructor() { - this.isAvailable = false; - this.isInstantiated = false; - if (typeof __require !== "undefined") { - const nodeCrypto = require_crypto(); - if (nodeCrypto && nodeCrypto.randomBytes) { - this._crypto = nodeCrypto; - this.isAvailable = true; - this.isInstantiated = true; - } - } - } - randomBytes(length2) { - if (!this.isAvailable || !this._crypto) { - throw new Error("Node.js random byte generator is not available."); - } - let buffer = this._crypto.randomBytes(length2); - if (buffer.length !== length2) { - throw new Error("NodeRandomSource: got fewer bytes than requested"); - } - const out = new Uint8Array(length2); - for (let i2 = 0; i2 < out.length; i2++) { - out[i2] = buffer[i2]; - } - (0, wipe_1.wipe)(buffer); - return out; - } - }; - exports2.NodeRandomSource = NodeRandomSource; - } -}); - -// node_modules/@stablelib/random/lib/source/system.js -var require_system = __commonJS({ - "node_modules/@stablelib/random/lib/source/system.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SystemRandomSource = void 0; - var browser_1 = require_browser4(); - var node_1 = require_node(); - var SystemRandomSource = class { - constructor() { - this.isAvailable = false; - this.name = ""; - this._source = new browser_1.BrowserRandomSource(); - if (this._source.isAvailable) { - this.isAvailable = true; - this.name = "Browser"; - return; - } - this._source = new node_1.NodeRandomSource(); - if (this._source.isAvailable) { - this.isAvailable = true; - this.name = "Node"; - return; - } - } - randomBytes(length2) { - if (!this.isAvailable) { - throw new Error("System random byte generator is not available."); - } - return this._source.randomBytes(length2); - } - }; - exports2.SystemRandomSource = SystemRandomSource; - } -}); - -// node_modules/@stablelib/int/lib/int.js -var require_int = __commonJS({ - "node_modules/@stablelib/int/lib/int.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function imulShim(a3, b4) { - var ah = a3 >>> 16 & 65535, al = a3 & 65535; - var bh = b4 >>> 16 & 65535, bl = b4 & 65535; - return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; - } - exports2.mul = Math.imul || imulShim; - function add(a3, b4) { - return a3 + b4 | 0; - } - exports2.add = add; - function sub(a3, b4) { - return a3 - b4 | 0; - } - exports2.sub = sub; - function rotl(x3, n3) { - return x3 << n3 | x3 >>> 32 - n3; - } - exports2.rotl = rotl; - function rotr(x3, n3) { - return x3 << 32 - n3 | x3 >>> n3; - } - exports2.rotr = rotr; - function isIntegerShim(n3) { - return typeof n3 === "number" && isFinite(n3) && Math.floor(n3) === n3; - } - exports2.isInteger = Number.isInteger || isIntegerShim; - exports2.MAX_SAFE_INTEGER = 9007199254740991; - exports2.isSafeInteger = function(n3) { - return exports2.isInteger(n3) && (n3 >= -exports2.MAX_SAFE_INTEGER && n3 <= exports2.MAX_SAFE_INTEGER); - }; - } -}); - -// node_modules/@stablelib/binary/lib/binary.js -var require_binary2 = __commonJS({ - "node_modules/@stablelib/binary/lib/binary.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var int_1 = require_int(); - function readInt16BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 0] << 8 | array[offset + 1]) << 16 >> 16; - } - exports2.readInt16BE = readInt16BE; - function readUint16BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 0] << 8 | array[offset + 1]) >>> 0; - } - exports2.readUint16BE = readUint16BE; - function readInt16LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 1] << 8 | array[offset]) << 16 >> 16; - } - exports2.readInt16LE = readInt16LE; - function readUint16LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 1] << 8 | array[offset]) >>> 0; - } - exports2.readUint16LE = readUint16LE; - function writeUint16BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(2); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 8; - out[offset + 1] = value >>> 0; - return out; - } - exports2.writeUint16BE = writeUint16BE; - exports2.writeInt16BE = writeUint16BE; - function writeUint16LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(2); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 0; - out[offset + 1] = value >>> 8; - return out; - } - exports2.writeUint16LE = writeUint16LE; - exports2.writeInt16LE = writeUint16LE; - function readInt32BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]; - } - exports2.readInt32BE = readInt32BE; - function readUint32BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]) >>> 0; - } - exports2.readUint32BE = readUint32BE; - function readInt32LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]; - } - exports2.readInt32LE = readInt32LE; - function readUint32LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - return (array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]) >>> 0; - } - exports2.readUint32LE = readUint32LE; - function writeUint32BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 24; - out[offset + 1] = value >>> 16; - out[offset + 2] = value >>> 8; - out[offset + 3] = value >>> 0; - return out; - } - exports2.writeUint32BE = writeUint32BE; - exports2.writeInt32BE = writeUint32BE; - function writeUint32LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - out[offset + 0] = value >>> 0; - out[offset + 1] = value >>> 8; - out[offset + 2] = value >>> 16; - out[offset + 3] = value >>> 24; - return out; - } - exports2.writeUint32LE = writeUint32LE; - exports2.writeInt32LE = writeUint32LE; - function readInt64BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var hi = readInt32BE(array, offset); - var lo = readInt32BE(array, offset + 4); - return hi * 4294967296 + lo - (lo >> 31) * 4294967296; - } - exports2.readInt64BE = readInt64BE; - function readUint64BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var hi = readUint32BE(array, offset); - var lo = readUint32BE(array, offset + 4); - return hi * 4294967296 + lo; - } - exports2.readUint64BE = readUint64BE; - function readInt64LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var lo = readInt32LE(array, offset); - var hi = readInt32LE(array, offset + 4); - return hi * 4294967296 + lo - (lo >> 31) * 4294967296; - } - exports2.readInt64LE = readInt64LE; - function readUint64LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var lo = readUint32LE(array, offset); - var hi = readUint32LE(array, offset + 4); - return hi * 4294967296 + lo; - } - exports2.readUint64LE = readUint64LE; - function writeUint64BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - writeUint32BE(value / 4294967296 >>> 0, out, offset); - writeUint32BE(value >>> 0, out, offset + 4); - return out; - } - exports2.writeUint64BE = writeUint64BE; - exports2.writeInt64BE = writeUint64BE; - function writeUint64LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - writeUint32LE(value >>> 0, out, offset); - writeUint32LE(value / 4294967296 >>> 0, out, offset + 4); - return out; - } - exports2.writeUint64LE = writeUint64LE; - exports2.writeInt64LE = writeUint64LE; - function readUintBE(bitLength, array, offset) { - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("readUintBE supports only bitLengths divisible by 8"); - } - if (bitLength / 8 > array.length - offset) { - throw new Error("readUintBE: array is too short for the given bitLength"); - } - var result = 0; - var mul = 1; - for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { - result += array[i2] * mul; - mul *= 256; - } - return result; - } - exports2.readUintBE = readUintBE; - function readUintLE(bitLength, array, offset) { - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("readUintLE supports only bitLengths divisible by 8"); - } - if (bitLength / 8 > array.length - offset) { - throw new Error("readUintLE: array is too short for the given bitLength"); - } - var result = 0; - var mul = 1; - for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { - result += array[i2] * mul; - mul *= 256; - } - return result; - } - exports2.readUintLE = readUintLE; - function writeUintBE(bitLength, value, out, offset) { - if (out === void 0) { - out = new Uint8Array(bitLength / 8); - } - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("writeUintBE supports only bitLengths divisible by 8"); - } - if (!int_1.isSafeInteger(value)) { - throw new Error("writeUintBE value must be an integer"); - } - var div = 1; - for (var i2 = bitLength / 8 + offset - 1; i2 >= offset; i2--) { - out[i2] = value / div & 255; - div *= 256; - } - return out; - } - exports2.writeUintBE = writeUintBE; - function writeUintLE(bitLength, value, out, offset) { - if (out === void 0) { - out = new Uint8Array(bitLength / 8); - } - if (offset === void 0) { - offset = 0; - } - if (bitLength % 8 !== 0) { - throw new Error("writeUintLE supports only bitLengths divisible by 8"); - } - if (!int_1.isSafeInteger(value)) { - throw new Error("writeUintLE value must be an integer"); - } - var div = 1; - for (var i2 = offset; i2 < offset + bitLength / 8; i2++) { - out[i2] = value / div & 255; - div *= 256; - } - return out; - } - exports2.writeUintLE = writeUintLE; - function readFloat32BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat32(offset); - } - exports2.readFloat32BE = readFloat32BE; - function readFloat32LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat32(offset, true); - } - exports2.readFloat32LE = readFloat32LE; - function readFloat64BE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat64(offset); - } - exports2.readFloat64BE = readFloat64BE; - function readFloat64LE(array, offset) { - if (offset === void 0) { - offset = 0; - } - var view = new DataView(array.buffer, array.byteOffset, array.byteLength); - return view.getFloat64(offset, true); - } - exports2.readFloat64LE = readFloat64LE; - function writeFloat32BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat32(offset, value); - return out; - } - exports2.writeFloat32BE = writeFloat32BE; - function writeFloat32LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(4); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat32(offset, value, true); - return out; - } - exports2.writeFloat32LE = writeFloat32LE; - function writeFloat64BE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat64(offset, value); - return out; - } - exports2.writeFloat64BE = writeFloat64BE; - function writeFloat64LE(value, out, offset) { - if (out === void 0) { - out = new Uint8Array(8); - } - if (offset === void 0) { - offset = 0; - } - var view = new DataView(out.buffer, out.byteOffset, out.byteLength); - view.setFloat64(offset, value, true); - return out; - } - exports2.writeFloat64LE = writeFloat64LE; - } -}); - -// node_modules/@stablelib/random/lib/random.js -var require_random = __commonJS({ - "node_modules/@stablelib/random/lib/random.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.randomStringForEntropy = exports2.randomString = exports2.randomUint32 = exports2.randomBytes = exports2.defaultRandomSource = void 0; - var system_1 = require_system(); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - exports2.defaultRandomSource = new system_1.SystemRandomSource(); - function randomBytes2(length2, prng = exports2.defaultRandomSource) { - return prng.randomBytes(length2); - } - exports2.randomBytes = randomBytes2; - function randomUint32(prng = exports2.defaultRandomSource) { - const buf = randomBytes2(4, prng); - const result = (0, binary_1.readUint32LE)(buf); - (0, wipe_1.wipe)(buf); - return result; - } - exports2.randomUint32 = randomUint32; - var ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - function randomString(length2, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { - if (charset.length < 2) { - throw new Error("randomString charset is too short"); - } - if (charset.length > 256) { - throw new Error("randomString charset is too long"); - } - let out = ""; - const charsLen = charset.length; - const maxByte = 256 - 256 % charsLen; - while (length2 > 0) { - const buf = randomBytes2(Math.ceil(length2 * 256 / maxByte), prng); - for (let i2 = 0; i2 < buf.length && length2 > 0; i2++) { - const randomByte = buf[i2]; - if (randomByte < maxByte) { - out += charset.charAt(randomByte % charsLen); - length2--; - } - } - (0, wipe_1.wipe)(buf); - } - return out; - } - exports2.randomString = randomString; - function randomStringForEntropy(bits, charset = ALPHANUMERIC, prng = exports2.defaultRandomSource) { - const length2 = Math.ceil(bits / (Math.log(charset.length) / Math.LN2)); - return randomString(length2, charset, prng); - } - exports2.randomStringForEntropy = randomStringForEntropy; - } -}); - -// node_modules/@stablelib/sha512/lib/sha512.js -var require_sha512 = __commonJS({ - "node_modules/@stablelib/sha512/lib/sha512.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - exports2.DIGEST_LENGTH = 64; - exports2.BLOCK_SIZE = 128; - var SHA512 = ( - /** @class */ - function() { - function SHA5122() { - this.digestLength = exports2.DIGEST_LENGTH; - this.blockSize = exports2.BLOCK_SIZE; - this._stateHi = new Int32Array(8); - this._stateLo = new Int32Array(8); - this._tempHi = new Int32Array(16); - this._tempLo = new Int32Array(16); - this._buffer = new Uint8Array(256); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - this.reset(); - } - SHA5122.prototype._initState = function() { - this._stateHi[0] = 1779033703; - this._stateHi[1] = 3144134277; - this._stateHi[2] = 1013904242; - this._stateHi[3] = 2773480762; - this._stateHi[4] = 1359893119; - this._stateHi[5] = 2600822924; - this._stateHi[6] = 528734635; - this._stateHi[7] = 1541459225; - this._stateLo[0] = 4089235720; - this._stateLo[1] = 2227873595; - this._stateLo[2] = 4271175723; - this._stateLo[3] = 1595750129; - this._stateLo[4] = 2917565137; - this._stateLo[5] = 725511199; - this._stateLo[6] = 4215389547; - this._stateLo[7] = 327033209; - }; - SHA5122.prototype.reset = function() { - this._initState(); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - return this; - }; - SHA5122.prototype.clean = function() { - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._tempHi); - wipe_1.wipe(this._tempLo); - this.reset(); - }; - SHA5122.prototype.update = function(data, dataLength) { - if (dataLength === void 0) { - dataLength = data.length; - } - if (this._finished) { - throw new Error("SHA512: can't update because hash was finished."); - } - var dataPos = 0; - this._bytesHashed += dataLength; - if (this._bufferLength > 0) { - while (this._bufferLength < exports2.BLOCK_SIZE && dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - if (this._bufferLength === this.blockSize) { - hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize); - this._bufferLength = 0; - } - } - if (dataLength >= this.blockSize) { - dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength); - dataLength %= this.blockSize; - } - while (dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - return this; - }; - SHA5122.prototype.finish = function(out) { - if (!this._finished) { - var bytesHashed = this._bytesHashed; - var left = this._bufferLength; - var bitLenHi = bytesHashed / 536870912 | 0; - var bitLenLo = bytesHashed << 3; - var padLength = bytesHashed % 128 < 112 ? 128 : 256; - this._buffer[left] = 128; - for (var i2 = left + 1; i2 < padLength - 8; i2++) { - this._buffer[i2] = 0; - } - binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); - binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); - hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength); - this._finished = true; - } - for (var i2 = 0; i2 < this.digestLength / 8; i2++) { - binary_1.writeUint32BE(this._stateHi[i2], out, i2 * 8); - binary_1.writeUint32BE(this._stateLo[i2], out, i2 * 8 + 4); - } - return this; - }; - SHA5122.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - SHA5122.prototype.saveState = function() { - if (this._finished) { - throw new Error("SHA256: cannot save finished state"); - } - return { - stateHi: new Int32Array(this._stateHi), - stateLo: new Int32Array(this._stateLo), - buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, - bufferLength: this._bufferLength, - bytesHashed: this._bytesHashed - }; - }; - SHA5122.prototype.restoreState = function(savedState) { - this._stateHi.set(savedState.stateHi); - this._stateLo.set(savedState.stateLo); - this._bufferLength = savedState.bufferLength; - if (savedState.buffer) { - this._buffer.set(savedState.buffer); - } - this._bytesHashed = savedState.bytesHashed; - this._finished = false; - return this; - }; - SHA5122.prototype.cleanSavedState = function(savedState) { - wipe_1.wipe(savedState.stateHi); - wipe_1.wipe(savedState.stateLo); - if (savedState.buffer) { - wipe_1.wipe(savedState.buffer); - } - savedState.bufferLength = 0; - savedState.bytesHashed = 0; - }; - return SHA5122; - }() - ); - exports2.SHA512 = SHA512; - var K2 = new Int32Array([ - 1116352408, - 3609767458, - 1899447441, - 602891725, - 3049323471, - 3964484399, - 3921009573, - 2173295548, - 961987163, - 4081628472, - 1508970993, - 3053834265, - 2453635748, - 2937671579, - 2870763221, - 3664609560, - 3624381080, - 2734883394, - 310598401, - 1164996542, - 607225278, - 1323610764, - 1426881987, - 3590304994, - 1925078388, - 4068182383, - 2162078206, - 991336113, - 2614888103, - 633803317, - 3248222580, - 3479774868, - 3835390401, - 2666613458, - 4022224774, - 944711139, - 264347078, - 2341262773, - 604807628, - 2007800933, - 770255983, - 1495990901, - 1249150122, - 1856431235, - 1555081692, - 3175218132, - 1996064986, - 2198950837, - 2554220882, - 3999719339, - 2821834349, - 766784016, - 2952996808, - 2566594879, - 3210313671, - 3203337956, - 3336571891, - 1034457026, - 3584528711, - 2466948901, - 113926993, - 3758326383, - 338241895, - 168717936, - 666307205, - 1188179964, - 773529912, - 1546045734, - 1294757372, - 1522805485, - 1396182291, - 2643833823, - 1695183700, - 2343527390, - 1986661051, - 1014477480, - 2177026350, - 1206759142, - 2456956037, - 344077627, - 2730485921, - 1290863460, - 2820302411, - 3158454273, - 3259730800, - 3505952657, - 3345764771, - 106217008, - 3516065817, - 3606008344, - 3600352804, - 1432725776, - 4094571909, - 1467031594, - 275423344, - 851169720, - 430227734, - 3100823752, - 506948616, - 1363258195, - 659060556, - 3750685593, - 883997877, - 3785050280, - 958139571, - 3318307427, - 1322822218, - 3812723403, - 1537002063, - 2003034995, - 1747873779, - 3602036899, - 1955562222, - 1575990012, - 2024104815, - 1125592928, - 2227730452, - 2716904306, - 2361852424, - 442776044, - 2428436474, - 593698344, - 2756734187, - 3733110249, - 3204031479, - 2999351573, - 3329325298, - 3815920427, - 3391569614, - 3928383900, - 3515267271, - 566280711, - 3940187606, - 3454069534, - 4118630271, - 4000239992, - 116418474, - 1914138554, - 174292421, - 2731055270, - 289380356, - 3203993006, - 460393269, - 320620315, - 685471733, - 587496836, - 852142971, - 1086792851, - 1017036298, - 365543100, - 1126000580, - 2618297676, - 1288033470, - 3409855158, - 1501505948, - 4234509866, - 1607167915, - 987167468, - 1816402316, - 1246189591 - ]); - function hashBlocks(wh, wl, hh, hl, m3, pos, len) { - var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; - var h5, l4; - var th, tl; - var a3, b4, c4, d3; - while (len >= 128) { - for (var i2 = 0; i2 < 16; i2++) { - var j2 = 8 * i2 + pos; - wh[i2] = binary_1.readUint32BE(m3, j2); - wl[i2] = binary_1.readUint32BE(m3, j2 + 4); - } - for (var i2 = 0; i2 < 80; i2++) { - var bh0 = ah0; - var bh1 = ah1; - var bh2 = ah2; - var bh3 = ah3; - var bh4 = ah4; - var bh5 = ah5; - var bh6 = ah6; - var bh7 = ah7; - var bl0 = al0; - var bl1 = al1; - var bl2 = al2; - var bl3 = al3; - var bl4 = al4; - var bl5 = al5; - var bl6 = al6; - var bl7 = al7; - h5 = ah7; - l4 = al7; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); - l4 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = ah4 & ah5 ^ ~ah4 & ah6; - l4 = al4 & al5 ^ ~al4 & al6; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = K2[i2 * 2]; - l4 = K2[i2 * 2 + 1]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = wh[i2 % 16]; - l4 = wl[i2 % 16]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - th = c4 & 65535 | d3 << 16; - tl = a3 & 65535 | b4 << 16; - h5 = th; - l4 = tl; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); - l4 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - h5 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; - l4 = al0 & al1 ^ al0 & al2 ^ al1 & al2; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - bh7 = c4 & 65535 | d3 << 16; - bl7 = a3 & 65535 | b4 << 16; - h5 = bh3; - l4 = bl3; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = th; - l4 = tl; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - bh3 = c4 & 65535 | d3 << 16; - bl3 = a3 & 65535 | b4 << 16; - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; - if (i2 % 16 === 15) { - for (var j2 = 0; j2 < 16; j2++) { - h5 = wh[j2]; - l4 = wl[j2]; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = wh[(j2 + 9) % 16]; - l4 = wl[(j2 + 9) % 16]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - th = wh[(j2 + 1) % 16]; - tl = wl[(j2 + 1) % 16]; - h5 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; - l4 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - th = wh[(j2 + 14) % 16]; - tl = wl[(j2 + 14) % 16]; - h5 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; - l4 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - wh[j2] = c4 & 65535 | d3 << 16; - wl[j2] = a3 & 65535 | b4 << 16; - } - } - } - h5 = ah0; - l4 = al0; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[0]; - l4 = hl[0]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[0] = ah0 = c4 & 65535 | d3 << 16; - hl[0] = al0 = a3 & 65535 | b4 << 16; - h5 = ah1; - l4 = al1; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[1]; - l4 = hl[1]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[1] = ah1 = c4 & 65535 | d3 << 16; - hl[1] = al1 = a3 & 65535 | b4 << 16; - h5 = ah2; - l4 = al2; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[2]; - l4 = hl[2]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[2] = ah2 = c4 & 65535 | d3 << 16; - hl[2] = al2 = a3 & 65535 | b4 << 16; - h5 = ah3; - l4 = al3; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[3]; - l4 = hl[3]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[3] = ah3 = c4 & 65535 | d3 << 16; - hl[3] = al3 = a3 & 65535 | b4 << 16; - h5 = ah4; - l4 = al4; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[4]; - l4 = hl[4]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[4] = ah4 = c4 & 65535 | d3 << 16; - hl[4] = al4 = a3 & 65535 | b4 << 16; - h5 = ah5; - l4 = al5; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[5]; - l4 = hl[5]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[5] = ah5 = c4 & 65535 | d3 << 16; - hl[5] = al5 = a3 & 65535 | b4 << 16; - h5 = ah6; - l4 = al6; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[6]; - l4 = hl[6]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[6] = ah6 = c4 & 65535 | d3 << 16; - hl[6] = al6 = a3 & 65535 | b4 << 16; - h5 = ah7; - l4 = al7; - a3 = l4 & 65535; - b4 = l4 >>> 16; - c4 = h5 & 65535; - d3 = h5 >>> 16; - h5 = hh[7]; - l4 = hl[7]; - a3 += l4 & 65535; - b4 += l4 >>> 16; - c4 += h5 & 65535; - d3 += h5 >>> 16; - b4 += a3 >>> 16; - c4 += b4 >>> 16; - d3 += c4 >>> 16; - hh[7] = ah7 = c4 & 65535 | d3 << 16; - hl[7] = al7 = a3 & 65535 | b4 << 16; - pos += 128; - len -= 128; - } - return pos; - } - function hash(data) { - var h5 = new SHA512(); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.hash = hash; - } -}); - -// node_modules/@stablelib/ed25519/lib/ed25519.js -var require_ed25519 = __commonJS({ - "node_modules/@stablelib/ed25519/lib/ed25519.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.convertSecretKeyToX25519 = exports2.convertPublicKeyToX25519 = exports2.verify = exports2.sign = exports2.extractPublicKeyFromSecretKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.SEED_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = exports2.SIGNATURE_LENGTH = void 0; - var random_1 = require_random(); - var sha512_1 = require_sha512(); - var wipe_1 = require_wipe(); - exports2.SIGNATURE_LENGTH = 64; - exports2.PUBLIC_KEY_LENGTH = 32; - exports2.SECRET_KEY_LENGTH = 64; - exports2.SEED_LENGTH = 32; - function gf(init) { - const r = new Float64Array(16); - if (init) { - for (let i2 = 0; i2 < init.length; i2++) { - r[i2] = init[i2]; - } - } - return r; - } - var _9 = new Uint8Array(32); - _9[0] = 9; - var gf0 = gf(); - var gf1 = gf([1]); - var D2 = gf([ - 30883, - 4953, - 19914, - 30187, - 55467, - 16705, - 2637, - 112, - 59544, - 30585, - 16505, - 36039, - 65139, - 11119, - 27886, - 20995 - ]); - var D22 = gf([ - 61785, - 9906, - 39828, - 60374, - 45398, - 33411, - 5274, - 224, - 53552, - 61171, - 33010, - 6542, - 64743, - 22239, - 55772, - 9222 - ]); - var X = gf([ - 54554, - 36645, - 11616, - 51542, - 42930, - 38181, - 51040, - 26924, - 56412, - 64982, - 57905, - 49316, - 21502, - 52590, - 14035, - 8553 - ]); - var Y = gf([ - 26200, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214 - ]); - var I2 = gf([ - 41136, - 18958, - 6951, - 50414, - 58488, - 44335, - 6150, - 12099, - 55207, - 15867, - 153, - 11085, - 57099, - 20417, - 9344, - 11139 - ]); - function set25519(r, a3) { - for (let i2 = 0; i2 < 16; i2++) { - r[i2] = a3[i2] | 0; - } - } - function car25519(o2) { - let c4 = 1; - for (let i2 = 0; i2 < 16; i2++) { - let v2 = o2[i2] + c4 + 65535; - c4 = Math.floor(v2 / 65536); - o2[i2] = v2 - c4 * 65536; - } - o2[0] += c4 - 1 + 37 * (c4 - 1); - } - function sel25519(p3, q2, b4) { - const c4 = ~(b4 - 1); - for (let i2 = 0; i2 < 16; i2++) { - const t = c4 & (p3[i2] ^ q2[i2]); - p3[i2] ^= t; - q2[i2] ^= t; - } - } - function pack25519(o2, n3) { - const m3 = gf(); - const t = gf(); - for (let i2 = 0; i2 < 16; i2++) { - t[i2] = n3[i2]; - } - car25519(t); - car25519(t); - car25519(t); - for (let j2 = 0; j2 < 2; j2++) { - m3[0] = t[0] - 65517; - for (let i2 = 1; i2 < 15; i2++) { - m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); - m3[i2 - 1] &= 65535; - } - m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); - const b4 = m3[15] >> 16 & 1; - m3[14] &= 65535; - sel25519(t, m3, 1 - b4); - } - for (let i2 = 0; i2 < 16; i2++) { - o2[2 * i2] = t[i2] & 255; - o2[2 * i2 + 1] = t[i2] >> 8; - } - } - function verify32(x3, y4) { - let d3 = 0; - for (let i2 = 0; i2 < 32; i2++) { - d3 |= x3[i2] ^ y4[i2]; - } - return (1 & d3 - 1 >>> 8) - 1; - } - function neq25519(a3, b4) { - const c4 = new Uint8Array(32); - const d3 = new Uint8Array(32); - pack25519(c4, a3); - pack25519(d3, b4); - return verify32(c4, d3); - } - function par25519(a3) { - const d3 = new Uint8Array(32); - pack25519(d3, a3); - return d3[0] & 1; - } - function unpack25519(o2, n3) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); - } - o2[15] &= 32767; - } - function add(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] + b4[i2]; - } - } - function sub(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] - b4[i2]; - } - } - function mul(o2, a3, b4) { - let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; - v2 = a3[0]; - t0 += v2 * b0; - t1 += v2 * b1; - t2 += v2 * b22; - t3 += v2 * b32; - t4 += v2 * b42; - t5 += v2 * b5; - t6 += v2 * b6; - t7 += v2 * b7; - t8 += v2 * b8; - t9 += v2 * b9; - t10 += v2 * b10; - t11 += v2 * b11; - t12 += v2 * b12; - t13 += v2 * b13; - t14 += v2 * b14; - t15 += v2 * b15; - v2 = a3[1]; - t1 += v2 * b0; - t2 += v2 * b1; - t3 += v2 * b22; - t4 += v2 * b32; - t5 += v2 * b42; - t6 += v2 * b5; - t7 += v2 * b6; - t8 += v2 * b7; - t9 += v2 * b8; - t10 += v2 * b9; - t11 += v2 * b10; - t12 += v2 * b11; - t13 += v2 * b12; - t14 += v2 * b13; - t15 += v2 * b14; - t16 += v2 * b15; - v2 = a3[2]; - t2 += v2 * b0; - t3 += v2 * b1; - t4 += v2 * b22; - t5 += v2 * b32; - t6 += v2 * b42; - t7 += v2 * b5; - t8 += v2 * b6; - t9 += v2 * b7; - t10 += v2 * b8; - t11 += v2 * b9; - t12 += v2 * b10; - t13 += v2 * b11; - t14 += v2 * b12; - t15 += v2 * b13; - t16 += v2 * b14; - t17 += v2 * b15; - v2 = a3[3]; - t3 += v2 * b0; - t4 += v2 * b1; - t5 += v2 * b22; - t6 += v2 * b32; - t7 += v2 * b42; - t8 += v2 * b5; - t9 += v2 * b6; - t10 += v2 * b7; - t11 += v2 * b8; - t12 += v2 * b9; - t13 += v2 * b10; - t14 += v2 * b11; - t15 += v2 * b12; - t16 += v2 * b13; - t17 += v2 * b14; - t18 += v2 * b15; - v2 = a3[4]; - t4 += v2 * b0; - t5 += v2 * b1; - t6 += v2 * b22; - t7 += v2 * b32; - t8 += v2 * b42; - t9 += v2 * b5; - t10 += v2 * b6; - t11 += v2 * b7; - t12 += v2 * b8; - t13 += v2 * b9; - t14 += v2 * b10; - t15 += v2 * b11; - t16 += v2 * b12; - t17 += v2 * b13; - t18 += v2 * b14; - t19 += v2 * b15; - v2 = a3[5]; - t5 += v2 * b0; - t6 += v2 * b1; - t7 += v2 * b22; - t8 += v2 * b32; - t9 += v2 * b42; - t10 += v2 * b5; - t11 += v2 * b6; - t12 += v2 * b7; - t13 += v2 * b8; - t14 += v2 * b9; - t15 += v2 * b10; - t16 += v2 * b11; - t17 += v2 * b12; - t18 += v2 * b13; - t19 += v2 * b14; - t20 += v2 * b15; - v2 = a3[6]; - t6 += v2 * b0; - t7 += v2 * b1; - t8 += v2 * b22; - t9 += v2 * b32; - t10 += v2 * b42; - t11 += v2 * b5; - t12 += v2 * b6; - t13 += v2 * b7; - t14 += v2 * b8; - t15 += v2 * b9; - t16 += v2 * b10; - t17 += v2 * b11; - t18 += v2 * b12; - t19 += v2 * b13; - t20 += v2 * b14; - t21 += v2 * b15; - v2 = a3[7]; - t7 += v2 * b0; - t8 += v2 * b1; - t9 += v2 * b22; - t10 += v2 * b32; - t11 += v2 * b42; - t12 += v2 * b5; - t13 += v2 * b6; - t14 += v2 * b7; - t15 += v2 * b8; - t16 += v2 * b9; - t17 += v2 * b10; - t18 += v2 * b11; - t19 += v2 * b12; - t20 += v2 * b13; - t21 += v2 * b14; - t22 += v2 * b15; - v2 = a3[8]; - t8 += v2 * b0; - t9 += v2 * b1; - t10 += v2 * b22; - t11 += v2 * b32; - t12 += v2 * b42; - t13 += v2 * b5; - t14 += v2 * b6; - t15 += v2 * b7; - t16 += v2 * b8; - t17 += v2 * b9; - t18 += v2 * b10; - t19 += v2 * b11; - t20 += v2 * b12; - t21 += v2 * b13; - t22 += v2 * b14; - t23 += v2 * b15; - v2 = a3[9]; - t9 += v2 * b0; - t10 += v2 * b1; - t11 += v2 * b22; - t12 += v2 * b32; - t13 += v2 * b42; - t14 += v2 * b5; - t15 += v2 * b6; - t16 += v2 * b7; - t17 += v2 * b8; - t18 += v2 * b9; - t19 += v2 * b10; - t20 += v2 * b11; - t21 += v2 * b12; - t22 += v2 * b13; - t23 += v2 * b14; - t24 += v2 * b15; - v2 = a3[10]; - t10 += v2 * b0; - t11 += v2 * b1; - t12 += v2 * b22; - t13 += v2 * b32; - t14 += v2 * b42; - t15 += v2 * b5; - t16 += v2 * b6; - t17 += v2 * b7; - t18 += v2 * b8; - t19 += v2 * b9; - t20 += v2 * b10; - t21 += v2 * b11; - t22 += v2 * b12; - t23 += v2 * b13; - t24 += v2 * b14; - t25 += v2 * b15; - v2 = a3[11]; - t11 += v2 * b0; - t12 += v2 * b1; - t13 += v2 * b22; - t14 += v2 * b32; - t15 += v2 * b42; - t16 += v2 * b5; - t17 += v2 * b6; - t18 += v2 * b7; - t19 += v2 * b8; - t20 += v2 * b9; - t21 += v2 * b10; - t22 += v2 * b11; - t23 += v2 * b12; - t24 += v2 * b13; - t25 += v2 * b14; - t26 += v2 * b15; - v2 = a3[12]; - t12 += v2 * b0; - t13 += v2 * b1; - t14 += v2 * b22; - t15 += v2 * b32; - t16 += v2 * b42; - t17 += v2 * b5; - t18 += v2 * b6; - t19 += v2 * b7; - t20 += v2 * b8; - t21 += v2 * b9; - t22 += v2 * b10; - t23 += v2 * b11; - t24 += v2 * b12; - t25 += v2 * b13; - t26 += v2 * b14; - t27 += v2 * b15; - v2 = a3[13]; - t13 += v2 * b0; - t14 += v2 * b1; - t15 += v2 * b22; - t16 += v2 * b32; - t17 += v2 * b42; - t18 += v2 * b5; - t19 += v2 * b6; - t20 += v2 * b7; - t21 += v2 * b8; - t22 += v2 * b9; - t23 += v2 * b10; - t24 += v2 * b11; - t25 += v2 * b12; - t26 += v2 * b13; - t27 += v2 * b14; - t28 += v2 * b15; - v2 = a3[14]; - t14 += v2 * b0; - t15 += v2 * b1; - t16 += v2 * b22; - t17 += v2 * b32; - t18 += v2 * b42; - t19 += v2 * b5; - t20 += v2 * b6; - t21 += v2 * b7; - t22 += v2 * b8; - t23 += v2 * b9; - t24 += v2 * b10; - t25 += v2 * b11; - t26 += v2 * b12; - t27 += v2 * b13; - t28 += v2 * b14; - t29 += v2 * b15; - v2 = a3[15]; - t15 += v2 * b0; - t16 += v2 * b1; - t17 += v2 * b22; - t18 += v2 * b32; - t19 += v2 * b42; - t20 += v2 * b5; - t21 += v2 * b6; - t22 += v2 * b7; - t23 += v2 * b8; - t24 += v2 * b9; - t25 += v2 * b10; - t26 += v2 * b11; - t27 += v2 * b12; - t28 += v2 * b13; - t29 += v2 * b14; - t30 += v2 * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - o2[0] = t0; - o2[1] = t1; - o2[2] = t2; - o2[3] = t3; - o2[4] = t4; - o2[5] = t5; - o2[6] = t6; - o2[7] = t7; - o2[8] = t8; - o2[9] = t9; - o2[10] = t10; - o2[11] = t11; - o2[12] = t12; - o2[13] = t13; - o2[14] = t14; - o2[15] = t15; - } - function square(o2, a3) { - mul(o2, a3, a3); - } - function inv25519(o2, i2) { - const c4 = gf(); - let a3; - for (a3 = 0; a3 < 16; a3++) { - c4[a3] = i2[a3]; - } - for (a3 = 253; a3 >= 0; a3--) { - square(c4, c4); - if (a3 !== 2 && a3 !== 4) { - mul(c4, c4, i2); - } - } - for (a3 = 0; a3 < 16; a3++) { - o2[a3] = c4[a3]; - } - } - function pow2523(o2, i2) { - const c4 = gf(); - let a3; - for (a3 = 0; a3 < 16; a3++) { - c4[a3] = i2[a3]; - } - for (a3 = 250; a3 >= 0; a3--) { - square(c4, c4); - if (a3 !== 1) { - mul(c4, c4, i2); - } - } - for (a3 = 0; a3 < 16; a3++) { - o2[a3] = c4[a3]; - } - } - function edadd(p3, q2) { - const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(), g3 = gf(), h5 = gf(), t = gf(); - sub(a3, p3[1], p3[0]); - sub(t, q2[1], q2[0]); - mul(a3, a3, t); - add(b4, p3[0], p3[1]); - add(t, q2[0], q2[1]); - mul(b4, b4, t); - mul(c4, p3[3], q2[3]); - mul(c4, c4, D22); - mul(d3, p3[2], q2[2]); - add(d3, d3, d3); - sub(e2, b4, a3); - sub(f4, d3, c4); - add(g3, d3, c4); - add(h5, b4, a3); - mul(p3[0], e2, f4); - mul(p3[1], h5, g3); - mul(p3[2], g3, f4); - mul(p3[3], e2, h5); - } - function cswap(p3, q2, b4) { - for (let i2 = 0; i2 < 4; i2++) { - sel25519(p3[i2], q2[i2], b4); - } - } - function pack(r, p3) { - const tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p3[2]); - mul(tx, p3[0], zi); - mul(ty, p3[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function scalarmult(p3, q2, s2) { - set25519(p3[0], gf0); - set25519(p3[1], gf1); - set25519(p3[2], gf1); - set25519(p3[3], gf0); - for (let i2 = 255; i2 >= 0; --i2) { - const b4 = s2[i2 / 8 | 0] >> (i2 & 7) & 1; - cswap(p3, q2, b4); - edadd(q2, p3); - edadd(p3, p3); - cswap(p3, q2, b4); - } - } - function scalarbase(p3, s2) { - const q2 = [gf(), gf(), gf(), gf()]; - set25519(q2[0], X); - set25519(q2[1], Y); - set25519(q2[2], gf1); - mul(q2[3], X, Y); - scalarmult(p3, q2, s2); - } - function generateKeyPairFromSeed2(seed) { - if (seed.length !== exports2.SEED_LENGTH) { - throw new Error(`ed25519: seed must be ${exports2.SEED_LENGTH} bytes`); - } - const d3 = (0, sha512_1.hash)(seed); - d3[0] &= 248; - d3[31] &= 127; - d3[31] |= 64; - const publicKey = new Uint8Array(32); - const p3 = [gf(), gf(), gf(), gf()]; - scalarbase(p3, d3); - pack(publicKey, p3); - const secretKey = new Uint8Array(64); - secretKey.set(seed); - secretKey.set(publicKey, 32); - return { - publicKey, - secretKey - }; - } - exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; - function generateKeyPair2(prng) { - const seed = (0, random_1.randomBytes)(32, prng); - const result = generateKeyPairFromSeed2(seed); - (0, wipe_1.wipe)(seed); - return result; - } - exports2.generateKeyPair = generateKeyPair2; - function extractPublicKeyFromSecretKey(secretKey) { - if (secretKey.length !== exports2.SECRET_KEY_LENGTH) { - throw new Error(`ed25519: secret key must be ${exports2.SECRET_KEY_LENGTH} bytes`); - } - return new Uint8Array(secretKey.subarray(32)); - } - exports2.extractPublicKeyFromSecretKey = extractPublicKeyFromSecretKey; - var L2 = new Float64Array([ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16 - ]); - function modL(r, x3) { - let carry; - let i2; - let j2; - let k4; - for (i2 = 63; i2 >= 32; --i2) { - carry = 0; - for (j2 = i2 - 32, k4 = i2 - 12; j2 < k4; ++j2) { - x3[j2] += carry - 16 * x3[i2] * L2[j2 - (i2 - 32)]; - carry = Math.floor((x3[j2] + 128) / 256); - x3[j2] -= carry * 256; - } - x3[j2] += carry; - x3[i2] = 0; - } - carry = 0; - for (j2 = 0; j2 < 32; j2++) { - x3[j2] += carry - (x3[31] >> 4) * L2[j2]; - carry = x3[j2] >> 8; - x3[j2] &= 255; - } - for (j2 = 0; j2 < 32; j2++) { - x3[j2] -= carry * L2[j2]; - } - for (i2 = 0; i2 < 32; i2++) { - x3[i2 + 1] += x3[i2] >> 8; - r[i2] = x3[i2] & 255; - } - } - function reduce(r) { - const x3 = new Float64Array(64); - for (let i2 = 0; i2 < 64; i2++) { - x3[i2] = r[i2]; - } - for (let i2 = 0; i2 < 64; i2++) { - r[i2] = 0; - } - modL(r, x3); - } - function sign2(secretKey, message) { - const x3 = new Float64Array(64); - const p3 = [gf(), gf(), gf(), gf()]; - const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); - d3[0] &= 248; - d3[31] &= 127; - d3[31] |= 64; - const signature = new Uint8Array(64); - signature.set(d3.subarray(32), 32); - const hs = new sha512_1.SHA512(); - hs.update(signature.subarray(32)); - hs.update(message); - const r = hs.digest(); - hs.clean(); - reduce(r); - scalarbase(p3, r); - pack(signature, p3); - hs.reset(); - hs.update(signature.subarray(0, 32)); - hs.update(secretKey.subarray(32)); - hs.update(message); - const h5 = hs.digest(); - reduce(h5); - for (let i2 = 0; i2 < 32; i2++) { - x3[i2] = r[i2]; - } - for (let i2 = 0; i2 < 32; i2++) { - for (let j2 = 0; j2 < 32; j2++) { - x3[i2 + j2] += h5[i2] * d3[j2]; - } - } - modL(signature.subarray(32), x3); - return signature; - } - exports2.sign = sign2; - function unpackneg(r, p3) { - const t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p3); - square(num, r[1]); - mul(den, num, D2); - sub(num, num, r[2]); - add(den, r[2], den); - square(den2, den); - square(den4, den2); - mul(den6, den4, den2); - mul(t, den6, num); - mul(t, t, den); - pow2523(t, t); - mul(t, t, num); - mul(t, t, den); - mul(t, t, den); - mul(r[0], t, den); - square(chk, r[0]); - mul(chk, chk, den); - if (neq25519(chk, num)) { - mul(r[0], r[0], I2); - } - square(chk, r[0]); - mul(chk, chk, den); - if (neq25519(chk, num)) { - return -1; - } - if (par25519(r[0]) === p3[31] >> 7) { - sub(r[0], gf0, r[0]); - } - mul(r[3], r[0], r[1]); - return 0; - } - function verify2(publicKey, message, signature) { - const t = new Uint8Array(32); - const p3 = [gf(), gf(), gf(), gf()]; - const q2 = [gf(), gf(), gf(), gf()]; - if (signature.length !== exports2.SIGNATURE_LENGTH) { - throw new Error(`ed25519: signature must be ${exports2.SIGNATURE_LENGTH} bytes`); - } - if (unpackneg(q2, publicKey)) { - return false; - } - const hs = new sha512_1.SHA512(); - hs.update(signature.subarray(0, 32)); - hs.update(publicKey); - hs.update(message); - const h5 = hs.digest(); - reduce(h5); - scalarmult(p3, q2, h5); - scalarbase(q2, signature.subarray(32)); - edadd(p3, q2); - pack(t, p3); - if (verify32(signature, t)) { - return false; - } - return true; - } - exports2.verify = verify2; - function convertPublicKeyToX25519(publicKey) { - let q2 = [gf(), gf(), gf(), gf()]; - if (unpackneg(q2, publicKey)) { - throw new Error("Ed25519: invalid public key"); - } - let a3 = gf(); - let b4 = gf(); - let y4 = q2[1]; - add(a3, gf1, y4); - sub(b4, gf1, y4); - inv25519(b4, b4); - mul(a3, a3, b4); - let z3 = new Uint8Array(32); - pack25519(z3, a3); - return z3; - } - exports2.convertPublicKeyToX25519 = convertPublicKeyToX25519; - function convertSecretKeyToX25519(secretKey) { - const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); - d3[0] &= 248; - d3[31] &= 127; - d3[31] |= 64; - const o2 = new Uint8Array(d3.subarray(0, 32)); - (0, wipe_1.wipe)(d3); - return o2; - } - exports2.convertSecretKeyToX25519 = convertSecretKeyToX25519; - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/constants.js -var JWT_IRIDIUM_ALG, JWT_IRIDIUM_TYP, JWT_DELIMITER, JWT_ENCODING, JSON_ENCODING, DATA_ENCODING, DID_DELIMITER, DID_PREFIX, DID_METHOD, MULTICODEC_ED25519_ENCODING, MULTICODEC_ED25519_BASE, MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_LENGTH, KEY_PAIR_SEED_LENGTH; -var init_constants = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/constants.js"() { - init_shim(); - JWT_IRIDIUM_ALG = "EdDSA"; - JWT_IRIDIUM_TYP = "JWT"; - JWT_DELIMITER = "."; - JWT_ENCODING = "base64url"; - JSON_ENCODING = "utf8"; - DATA_ENCODING = "utf8"; - DID_DELIMITER = ":"; - DID_PREFIX = "did"; - DID_METHOD = "key"; - MULTICODEC_ED25519_ENCODING = "base58btc"; - MULTICODEC_ED25519_BASE = "z"; - MULTICODEC_ED25519_HEADER = "K36"; - MULTICODEC_ED25519_LENGTH = 32; - KEY_PAIR_SEED_LENGTH = 32; - } -}); - -// node_modules/uint8arrays/esm/src/util/as-uint8array.js -function asUint8Array(buf) { - if (globalThis.Buffer != null) { - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - return buf; -} -var init_as_uint8array = __esm({ - "node_modules/uint8arrays/esm/src/util/as-uint8array.js"() { - init_shim(); - } -}); - -// node_modules/uint8arrays/esm/src/alloc.js -function allocUnsafe(size = 0) { - if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) { - return asUint8Array(globalThis.Buffer.allocUnsafe(size)); - } - return new Uint8Array(size); -} -var init_alloc = __esm({ - "node_modules/uint8arrays/esm/src/alloc.js"() { - init_shim(); - init_as_uint8array(); - } -}); - -// node_modules/uint8arrays/esm/src/concat.js -function concat(arrays, length2) { - if (!length2) { - length2 = arrays.reduce((acc, curr) => acc + curr.length, 0); - } - const output = allocUnsafe(length2); - let offset = 0; - for (const arr of arrays) { - output.set(arr, offset); - offset += arr.length; - } - return asUint8Array(output); -} -var init_concat = __esm({ - "node_modules/uint8arrays/esm/src/concat.js"() { - init_shim(); - init_alloc(); - init_as_uint8array(); - } -}); - -// node_modules/multiformats/esm/vendor/base-x.js -function base(ALPHABET, name2) { - if (ALPHABET.length >= 255) { - throw new TypeError("Alphabet too long"); - } - var BASE_MAP = new Uint8Array(256); - for (var j2 = 0; j2 < BASE_MAP.length; j2++) { - BASE_MAP[j2] = 255; - } - for (var i2 = 0; i2 < ALPHABET.length; i2++) { - var x3 = ALPHABET.charAt(i2); - var xc = x3.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { - throw new TypeError(x3 + " is ambiguous"); - } - BASE_MAP[xc] = i2; - } - var BASE2 = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE2) / Math.log(256); - var iFACTOR = Math.log(256) / Math.log(BASE2); - function encode5(source) { - if (source instanceof Uint8Array) - ; - else if (ArrayBuffer.isView(source)) { - source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); - } else if (Array.isArray(source)) { - source = Uint8Array.from(source); - } - if (!(source instanceof Uint8Array)) { - throw new TypeError("Expected Uint8Array"); - } - if (source.length === 0) { - return ""; - } - var zeroes = 0; - var length2 = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - var size = (pend - pbegin) * iFACTOR + 1 >>> 0; - var b58 = new Uint8Array(size); - while (pbegin !== pend) { - var carry = source[pbegin]; - var i3 = 0; - for (var it1 = size - 1; (carry !== 0 || i3 < length2) && it1 !== -1; it1--, i3++) { - carry += 256 * b58[it1] >>> 0; - b58[it1] = carry % BASE2 >>> 0; - carry = carry / BASE2 >>> 0; - } - if (carry !== 0) { - throw new Error("Non-zero carry"); - } - length2 = i3; - pbegin++; - } - var it2 = size - length2; - while (it2 !== size && b58[it2] === 0) { - it2++; - } - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { - str += ALPHABET.charAt(b58[it2]); - } - return str; - } - function decodeUnsafe(source) { - if (typeof source !== "string") { - throw new TypeError("Expected String"); - } - if (source.length === 0) { - return new Uint8Array(); - } - var psz = 0; - if (source[psz] === " ") { - return; - } - var zeroes = 0; - var length2 = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; - } - var size = (source.length - psz) * FACTOR + 1 >>> 0; - var b256 = new Uint8Array(size); - while (source[psz]) { - var carry = BASE_MAP[source.charCodeAt(psz)]; - if (carry === 255) { - return; - } - var i3 = 0; - for (var it3 = size - 1; (carry !== 0 || i3 < length2) && it3 !== -1; it3--, i3++) { - carry += BASE2 * b256[it3] >>> 0; - b256[it3] = carry % 256 >>> 0; - carry = carry / 256 >>> 0; - } - if (carry !== 0) { - throw new Error("Non-zero carry"); - } - length2 = i3; - psz++; - } - if (source[psz] === " ") { - return; - } - var it4 = size - length2; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = new Uint8Array(zeroes + (size - it4)); - var j3 = zeroes; - while (it4 !== size) { - vch[j3++] = b256[it4++]; - } - return vch; - } - function decode6(string2) { - var buffer = decodeUnsafe(string2); - if (buffer) { - return buffer; - } - throw new Error(`Non-${name2} character`); - } - return { - encode: encode5, - decodeUnsafe, - decode: decode6 - }; -} -var src, _brrp__multiformats_scope_baseX, base_x_default; -var init_base_x = __esm({ - "node_modules/multiformats/esm/vendor/base-x.js"() { - init_shim(); - src = base; - _brrp__multiformats_scope_baseX = src; - base_x_default = _brrp__multiformats_scope_baseX; - } -}); - -// node_modules/multiformats/esm/src/bytes.js -var empty, equals, coerce, fromString, toString; -var init_bytes = __esm({ - "node_modules/multiformats/esm/src/bytes.js"() { - init_shim(); - empty = new Uint8Array(0); - equals = (aa, bb) => { - if (aa === bb) - return true; - if (aa.byteLength !== bb.byteLength) { - return false; - } - for (let ii = 0; ii < aa.byteLength; ii++) { - if (aa[ii] !== bb[ii]) { - return false; - } - } - return true; - }; - coerce = (o2) => { - if (o2 instanceof Uint8Array && o2.constructor.name === "Uint8Array") - return o2; - if (o2 instanceof ArrayBuffer) - return new Uint8Array(o2); - if (ArrayBuffer.isView(o2)) { - return new Uint8Array(o2.buffer, o2.byteOffset, o2.byteLength); - } - throw new Error("Unknown type, must be binary type"); - }; - fromString = (str) => new TextEncoder().encode(str); - toString = (b4) => new TextDecoder().decode(b4); - } -}); - -// node_modules/multiformats/esm/src/bases/base.js -var Encoder, Decoder, ComposedDecoder, or, Codec, from, baseX, decode, encode, rfc4648; -var init_base = __esm({ - "node_modules/multiformats/esm/src/bases/base.js"() { - init_shim(); - init_base_x(); - init_bytes(); - Encoder = class { - constructor(name2, prefix, baseEncode) { - this.name = name2; - this.prefix = prefix; - this.baseEncode = baseEncode; - } - encode(bytes) { - if (bytes instanceof Uint8Array) { - return `${this.prefix}${this.baseEncode(bytes)}`; - } else { - throw Error("Unknown type, must be binary type"); - } - } - }; - Decoder = class { - constructor(name2, prefix, baseDecode) { - this.name = name2; - this.prefix = prefix; - if (prefix.codePointAt(0) === void 0) { - throw new Error("Invalid prefix character"); - } - this.prefixCodePoint = prefix.codePointAt(0); - this.baseDecode = baseDecode; - } - decode(text) { - if (typeof text === "string") { - if (text.codePointAt(0) !== this.prefixCodePoint) { - throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); - } - return this.baseDecode(text.slice(this.prefix.length)); - } else { - throw Error("Can only multibase decode strings"); - } - } - or(decoder) { - return or(this, decoder); - } - }; - ComposedDecoder = class { - constructor(decoders) { - this.decoders = decoders; - } - or(decoder) { - return or(this, decoder); - } - decode(input) { - const prefix = input[0]; - const decoder = this.decoders[prefix]; - if (decoder) { - return decoder.decode(input); - } else { - throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); - } - } - }; - or = (left, right) => new ComposedDecoder({ - ...left.decoders || { [left.prefix]: left }, - ...right.decoders || { [right.prefix]: right } - }); - Codec = class { - constructor(name2, prefix, baseEncode, baseDecode) { - this.name = name2; - this.prefix = prefix; - this.baseEncode = baseEncode; - this.baseDecode = baseDecode; - this.encoder = new Encoder(name2, prefix, baseEncode); - this.decoder = new Decoder(name2, prefix, baseDecode); - } - encode(input) { - return this.encoder.encode(input); - } - decode(input) { - return this.decoder.decode(input); - } - }; - from = ({ name: name2, prefix, encode: encode5, decode: decode6 }) => new Codec(name2, prefix, encode5, decode6); - baseX = ({ prefix, name: name2, alphabet: alphabet2 }) => { - const { encode: encode5, decode: decode6 } = base_x_default(alphabet2, name2); - return from({ - prefix, - name: name2, - encode: encode5, - decode: (text) => coerce(decode6(text)) - }); - }; - decode = (string2, alphabet2, bitsPerChar, name2) => { - const codes = {}; - for (let i2 = 0; i2 < alphabet2.length; ++i2) { - codes[alphabet2[i2]] = i2; - } - let end = string2.length; - while (string2[end - 1] === "=") { - --end; - } - const out = new Uint8Array(end * bitsPerChar / 8 | 0); - let bits = 0; - let buffer = 0; - let written = 0; - for (let i2 = 0; i2 < end; ++i2) { - const value = codes[string2[i2]]; - if (value === void 0) { - throw new SyntaxError(`Non-${name2} character`); - } - buffer = buffer << bitsPerChar | value; - bits += bitsPerChar; - if (bits >= 8) { - bits -= 8; - out[written++] = 255 & buffer >> bits; - } - } - if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { - throw new SyntaxError("Unexpected end of data"); - } - return out; - }; - encode = (data, alphabet2, bitsPerChar) => { - const pad = alphabet2[alphabet2.length - 1] === "="; - const mask = (1 << bitsPerChar) - 1; - let out = ""; - let bits = 0; - let buffer = 0; - for (let i2 = 0; i2 < data.length; ++i2) { - buffer = buffer << 8 | data[i2]; - bits += 8; - while (bits > bitsPerChar) { - bits -= bitsPerChar; - out += alphabet2[mask & buffer >> bits]; - } - } - if (bits) { - out += alphabet2[mask & buffer << bitsPerChar - bits]; - } - if (pad) { - while (out.length * bitsPerChar & 7) { - out += "="; - } - } - return out; - }; - rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) => { - return from({ - prefix, - name: name2, - encode(input) { - return encode(input, alphabet2, bitsPerChar); - }, - decode(input) { - return decode(input, alphabet2, bitsPerChar, name2); - } - }); - }; - } -}); - -// node_modules/multiformats/esm/src/bases/identity.js -var identity_exports = {}; -__export(identity_exports, { - identity: () => identity -}); -var identity; -var init_identity = __esm({ - "node_modules/multiformats/esm/src/bases/identity.js"() { - init_shim(); - init_base(); - init_bytes(); - identity = from({ - prefix: "\0", - name: "identity", - encode: (buf) => toString(buf), - decode: (str) => fromString(str) - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base2.js -var base2_exports = {}; -__export(base2_exports, { - base2: () => base2 -}); -var base2; -var init_base2 = __esm({ - "node_modules/multiformats/esm/src/bases/base2.js"() { - init_shim(); - init_base(); - base2 = rfc4648({ - prefix: "0", - name: "base2", - alphabet: "01", - bitsPerChar: 1 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base8.js -var base8_exports = {}; -__export(base8_exports, { - base8: () => base8 -}); -var base8; -var init_base8 = __esm({ - "node_modules/multiformats/esm/src/bases/base8.js"() { - init_shim(); - init_base(); - base8 = rfc4648({ - prefix: "7", - name: "base8", - alphabet: "01234567", - bitsPerChar: 3 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base10.js -var base10_exports = {}; -__export(base10_exports, { - base10: () => base10 -}); -var base10; -var init_base10 = __esm({ - "node_modules/multiformats/esm/src/bases/base10.js"() { - init_shim(); - init_base(); - base10 = baseX({ - prefix: "9", - name: "base10", - alphabet: "0123456789" - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base16.js -var base16_exports = {}; -__export(base16_exports, { - base16: () => base16, - base16upper: () => base16upper -}); -var base16, base16upper; -var init_base16 = __esm({ - "node_modules/multiformats/esm/src/bases/base16.js"() { - init_shim(); - init_base(); - base16 = rfc4648({ - prefix: "f", - name: "base16", - alphabet: "0123456789abcdef", - bitsPerChar: 4 - }); - base16upper = rfc4648({ - prefix: "F", - name: "base16upper", - alphabet: "0123456789ABCDEF", - bitsPerChar: 4 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base32.js -var base32_exports = {}; -__export(base32_exports, { - base32: () => base32, - base32hex: () => base32hex, - base32hexpad: () => base32hexpad, - base32hexpadupper: () => base32hexpadupper, - base32hexupper: () => base32hexupper, - base32pad: () => base32pad, - base32padupper: () => base32padupper, - base32upper: () => base32upper, - base32z: () => base32z -}); -var base32, base32upper, base32pad, base32padupper, base32hex, base32hexupper, base32hexpad, base32hexpadupper, base32z; -var init_base32 = __esm({ - "node_modules/multiformats/esm/src/bases/base32.js"() { - init_shim(); - init_base(); - base32 = rfc4648({ - prefix: "b", - name: "base32", - alphabet: "abcdefghijklmnopqrstuvwxyz234567", - bitsPerChar: 5 - }); - base32upper = rfc4648({ - prefix: "B", - name: "base32upper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - bitsPerChar: 5 - }); - base32pad = rfc4648({ - prefix: "c", - name: "base32pad", - alphabet: "abcdefghijklmnopqrstuvwxyz234567=", - bitsPerChar: 5 - }); - base32padupper = rfc4648({ - prefix: "C", - name: "base32padupper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", - bitsPerChar: 5 - }); - base32hex = rfc4648({ - prefix: "v", - name: "base32hex", - alphabet: "0123456789abcdefghijklmnopqrstuv", - bitsPerChar: 5 - }); - base32hexupper = rfc4648({ - prefix: "V", - name: "base32hexupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", - bitsPerChar: 5 - }); - base32hexpad = rfc4648({ - prefix: "t", - name: "base32hexpad", - alphabet: "0123456789abcdefghijklmnopqrstuv=", - bitsPerChar: 5 - }); - base32hexpadupper = rfc4648({ - prefix: "T", - name: "base32hexpadupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", - bitsPerChar: 5 - }); - base32z = rfc4648({ - prefix: "h", - name: "base32z", - alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", - bitsPerChar: 5 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base36.js -var base36_exports = {}; -__export(base36_exports, { - base36: () => base36, - base36upper: () => base36upper -}); -var base36, base36upper; -var init_base36 = __esm({ - "node_modules/multiformats/esm/src/bases/base36.js"() { - init_shim(); - init_base(); - base36 = baseX({ - prefix: "k", - name: "base36", - alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" - }); - base36upper = baseX({ - prefix: "K", - name: "base36upper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base58.js -var base58_exports = {}; -__export(base58_exports, { - base58btc: () => base58btc, - base58flickr: () => base58flickr -}); -var base58btc, base58flickr; -var init_base58 = __esm({ - "node_modules/multiformats/esm/src/bases/base58.js"() { - init_shim(); - init_base(); - base58btc = baseX({ - name: "base58btc", - prefix: "z", - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" - }); - base58flickr = baseX({ - name: "base58flickr", - prefix: "Z", - alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base64.js -var base64_exports = {}; -__export(base64_exports, { - base64: () => base64, - base64pad: () => base64pad, - base64url: () => base64url, - base64urlpad: () => base64urlpad -}); -var base64, base64pad, base64url, base64urlpad; -var init_base64 = __esm({ - "node_modules/multiformats/esm/src/bases/base64.js"() { - init_shim(); - init_base(); - base64 = rfc4648({ - prefix: "m", - name: "base64", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", - bitsPerChar: 6 - }); - base64pad = rfc4648({ - prefix: "M", - name: "base64pad", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", - bitsPerChar: 6 - }); - base64url = rfc4648({ - prefix: "u", - name: "base64url", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", - bitsPerChar: 6 - }); - base64urlpad = rfc4648({ - prefix: "U", - name: "base64urlpad", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", - bitsPerChar: 6 - }); - } -}); - -// node_modules/multiformats/esm/src/bases/base256emoji.js -var base256emoji_exports = {}; -__export(base256emoji_exports, { - base256emoji: () => base256emoji -}); -function encode2(data) { - return data.reduce((p3, c4) => { - p3 += alphabetBytesToChars[c4]; - return p3; - }, ""); -} -function decode2(str) { - const byts = []; - for (const char of str) { - const byt = alphabetCharsToBytes[char.codePointAt(0)]; - if (byt === void 0) { - throw new Error(`Non-base256emoji character: ${char}`); - } - byts.push(byt); - } - return new Uint8Array(byts); -} -var alphabet, alphabetBytesToChars, alphabetCharsToBytes, base256emoji; -var init_base256emoji = __esm({ - "node_modules/multiformats/esm/src/bases/base256emoji.js"() { - init_shim(); - init_base(); - alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); - alphabetBytesToChars = alphabet.reduce((p3, c4, i2) => { - p3[i2] = c4; - return p3; - }, []); - alphabetCharsToBytes = alphabet.reduce((p3, c4, i2) => { - p3[c4.codePointAt(0)] = i2; - return p3; - }, []); - base256emoji = from({ - prefix: "\u{1F680}", - name: "base256emoji", - encode: encode2, - decode: decode2 - }); - } -}); - -// node_modules/multiformats/esm/vendor/varint.js -function encode3(num, out, offset) { - out = out || []; - offset = offset || 0; - var oldOffset = offset; - while (num >= INT) { - out[offset++] = num & 255 | MSB; - num /= 128; - } - while (num & MSBALL) { - out[offset++] = num & 255 | MSB; - num >>>= 7; - } - out[offset] = num | 0; - encode3.bytes = offset - oldOffset + 1; - return out; -} -function read(buf, offset) { - var res = 0, offset = offset || 0, shift = 0, counter = offset, b4, l4 = buf.length; - do { - if (counter >= l4) { - read.bytes = 0; - throw new RangeError("Could not decode varint"); - } - b4 = buf[counter++]; - res += shift < 28 ? (b4 & REST$1) << shift : (b4 & REST$1) * Math.pow(2, shift); - shift += 7; - } while (b4 >= MSB$1); - read.bytes = counter - offset; - return res; -} -var encode_1, MSB, REST, MSBALL, INT, decode3, MSB$1, REST$1, N1, N2, N3, N4, N5, N6, N7, N8, N9, length, varint, _brrp_varint, varint_default; -var init_varint = __esm({ - "node_modules/multiformats/esm/vendor/varint.js"() { - init_shim(); - encode_1 = encode3; - MSB = 128; - REST = 127; - MSBALL = ~REST; - INT = Math.pow(2, 31); - decode3 = read; - MSB$1 = 128; - REST$1 = 127; - N1 = Math.pow(2, 7); - N2 = Math.pow(2, 14); - N3 = Math.pow(2, 21); - N4 = Math.pow(2, 28); - N5 = Math.pow(2, 35); - N6 = Math.pow(2, 42); - N7 = Math.pow(2, 49); - N8 = Math.pow(2, 56); - N9 = Math.pow(2, 63); - length = function(value) { - return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; - }; - varint = { - encode: encode_1, - decode: decode3, - encodingLength: length - }; - _brrp_varint = varint; - varint_default = _brrp_varint; - } -}); - -// node_modules/multiformats/esm/src/varint.js -var decode4, encodeTo, encodingLength; -var init_varint2 = __esm({ - "node_modules/multiformats/esm/src/varint.js"() { - init_shim(); - init_varint(); - decode4 = (data, offset = 0) => { - const code2 = varint_default.decode(data, offset); - return [ - code2, - varint_default.decode.bytes - ]; - }; - encodeTo = (int, target, offset = 0) => { - varint_default.encode(int, target, offset); - return target; - }; - encodingLength = (int) => { - return varint_default.encodingLength(int); - }; - } -}); - -// node_modules/multiformats/esm/src/hashes/digest.js -var create, decode5, equals2, Digest; -var init_digest = __esm({ - "node_modules/multiformats/esm/src/hashes/digest.js"() { - init_shim(); - init_bytes(); - init_varint2(); - create = (code2, digest2) => { - const size = digest2.byteLength; - const sizeOffset = encodingLength(code2); - const digestOffset = sizeOffset + encodingLength(size); - const bytes = new Uint8Array(digestOffset + size); - encodeTo(code2, bytes, 0); - encodeTo(size, bytes, sizeOffset); - bytes.set(digest2, digestOffset); - return new Digest(code2, size, digest2, bytes); - }; - decode5 = (multihash) => { - const bytes = coerce(multihash); - const [code2, sizeOffset] = decode4(bytes); - const [size, digestOffset] = decode4(bytes.subarray(sizeOffset)); - const digest2 = bytes.subarray(sizeOffset + digestOffset); - if (digest2.byteLength !== size) { - throw new Error("Incorrect length"); - } - return new Digest(code2, size, digest2, bytes); - }; - equals2 = (a3, b4) => { - if (a3 === b4) { - return true; - } else { - return a3.code === b4.code && a3.size === b4.size && equals(a3.bytes, b4.bytes); - } - }; - Digest = class { - constructor(code2, size, digest2, bytes) { - this.code = code2; - this.size = size; - this.digest = digest2; - this.bytes = bytes; - } - }; - } -}); - -// node_modules/multiformats/esm/src/hashes/hasher.js -var from2, Hasher; -var init_hasher = __esm({ - "node_modules/multiformats/esm/src/hashes/hasher.js"() { - init_shim(); - init_digest(); - from2 = ({ name: name2, code: code2, encode: encode5 }) => new Hasher(name2, code2, encode5); - Hasher = class { - constructor(name2, code2, encode5) { - this.name = name2; - this.code = code2; - this.encode = encode5; - } - digest(input) { - if (input instanceof Uint8Array) { - const result = this.encode(input); - return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2)); - } else { - throw Error("Unknown type, must be binary type"); - } - } - }; - } -}); - -// node_modules/multiformats/esm/src/hashes/sha2-browser.js -var sha2_browser_exports = {}; -__export(sha2_browser_exports, { - sha256: () => sha256, - sha512: () => sha512 -}); -var sha, sha256, sha512; -var init_sha2_browser = __esm({ - "node_modules/multiformats/esm/src/hashes/sha2-browser.js"() { - init_shim(); - init_hasher(); - sha = (name2) => async (data) => new Uint8Array(await crypto.subtle.digest(name2, data)); - sha256 = from2({ - name: "sha2-256", - code: 18, - encode: sha("SHA-256") - }); - sha512 = from2({ - name: "sha2-512", - code: 19, - encode: sha("SHA-512") - }); - } -}); - -// node_modules/multiformats/esm/src/hashes/identity.js -var identity_exports2 = {}; -__export(identity_exports2, { - identity: () => identity2 -}); -var code, name, encode4, digest, identity2; -var init_identity2 = __esm({ - "node_modules/multiformats/esm/src/hashes/identity.js"() { - init_shim(); - init_bytes(); - init_digest(); - code = 0; - name = "identity"; - encode4 = coerce; - digest = (input) => create(code, encode4(input)); - identity2 = { - code, - name, - encode: encode4, - digest - }; - } -}); - -// node_modules/multiformats/esm/src/codecs/raw.js -var init_raw = __esm({ - "node_modules/multiformats/esm/src/codecs/raw.js"() { - init_shim(); - init_bytes(); - } -}); - -// node_modules/multiformats/esm/src/codecs/json.js -var textEncoder, textDecoder; -var init_json = __esm({ - "node_modules/multiformats/esm/src/codecs/json.js"() { - init_shim(); - textEncoder = new TextEncoder(); - textDecoder = new TextDecoder(); - } -}); - -// node_modules/multiformats/esm/src/cid.js -var CID, parseCIDtoBytes, toStringV0, toStringV1, DAG_PB_CODE, SHA_256_CODE, encodeCID, cidSymbol, readonly, hidden, version, deprecate, IS_CID_DEPRECATION; -var init_cid = __esm({ - "node_modules/multiformats/esm/src/cid.js"() { - init_shim(); - init_varint2(); - init_digest(); - init_base58(); - init_base32(); - init_bytes(); - CID = class _CID { - constructor(version2, code2, multihash, bytes) { - this.code = code2; - this.version = version2; - this.multihash = multihash; - this.bytes = bytes; - this.byteOffset = bytes.byteOffset; - this.byteLength = bytes.byteLength; - this.asCID = this; - this._baseCache = /* @__PURE__ */ new Map(); - Object.defineProperties(this, { - byteOffset: hidden, - byteLength: hidden, - code: readonly, - version: readonly, - multihash: readonly, - bytes: readonly, - _baseCache: hidden, - asCID: hidden - }); - } - toV0() { - switch (this.version) { - case 0: { - return this; - } - default: { - const { code: code2, multihash } = this; - if (code2 !== DAG_PB_CODE) { - throw new Error("Cannot convert a non dag-pb CID to CIDv0"); - } - if (multihash.code !== SHA_256_CODE) { - throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); - } - return _CID.createV0(multihash); - } - } - } - toV1() { - switch (this.version) { - case 0: { - const { code: code2, digest: digest2 } = this.multihash; - const multihash = create(code2, digest2); - return _CID.createV1(this.code, multihash); - } - case 1: { - return this; - } - default: { - throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); - } - } - } - equals(other) { - return other && this.code === other.code && this.version === other.version && equals2(this.multihash, other.multihash); - } - toString(base3) { - const { bytes, version: version2, _baseCache } = this; - switch (version2) { - case 0: - return toStringV0(bytes, _baseCache, base3 || base58btc.encoder); - default: - return toStringV1(bytes, _baseCache, base3 || base32.encoder); - } - } - toJSON() { - return { - code: this.code, - version: this.version, - hash: this.multihash.bytes - }; - } - get [Symbol.toStringTag]() { - return "CID"; - } - [Symbol.for("nodejs.util.inspect.custom")]() { - return "CID(" + this.toString() + ")"; - } - static isCID(value) { - deprecate(/^0\.0/, IS_CID_DEPRECATION); - return !!(value && (value[cidSymbol] || value.asCID === value)); - } - get toBaseEncodedString() { - throw new Error("Deprecated, use .toString()"); - } - get codec() { - throw new Error('"codec" property is deprecated, use integer "code" property instead'); - } - get buffer() { - throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); - } - get multibaseName() { - throw new Error('"multibaseName" property is deprecated'); - } - get prefix() { - throw new Error('"prefix" property is deprecated'); - } - static asCID(value) { - if (value instanceof _CID) { - return value; - } else if (value != null && value.asCID === value) { - const { version: version2, code: code2, multihash, bytes } = value; - return new _CID(version2, code2, multihash, bytes || encodeCID(version2, code2, multihash.bytes)); - } else if (value != null && value[cidSymbol] === true) { - const { version: version2, multihash, code: code2 } = value; - const digest2 = decode5(multihash); - return _CID.create(version2, code2, digest2); - } else { - return null; - } - } - static create(version2, code2, digest2) { - if (typeof code2 !== "number") { - throw new Error("String codecs are no longer supported"); - } - switch (version2) { - case 0: { - if (code2 !== DAG_PB_CODE) { - throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); - } else { - return new _CID(version2, code2, digest2, digest2.bytes); - } - } - case 1: { - const bytes = encodeCID(version2, code2, digest2.bytes); - return new _CID(version2, code2, digest2, bytes); - } - default: { - throw new Error("Invalid version"); - } - } - } - static createV0(digest2) { - return _CID.create(0, DAG_PB_CODE, digest2); - } - static createV1(code2, digest2) { - return _CID.create(1, code2, digest2); - } - static decode(bytes) { - const [cid, remainder] = _CID.decodeFirst(bytes); - if (remainder.length) { - throw new Error("Incorrect length"); - } - return cid; - } - static decodeFirst(bytes) { - const specs = _CID.inspectBytes(bytes); - const prefixSize = specs.size - specs.multihashSize; - const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); - if (multihashBytes.byteLength !== specs.multihashSize) { - throw new Error("Incorrect length"); - } - const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); - const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); - const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2); - return [ - cid, - bytes.subarray(specs.size) - ]; - } - static inspectBytes(initialBytes) { - let offset = 0; - const next = () => { - const [i2, length2] = decode4(initialBytes.subarray(offset)); - offset += length2; - return i2; - }; - let version2 = next(); - let codec = DAG_PB_CODE; - if (version2 === 18) { - version2 = 0; - offset = 0; - } else if (version2 === 1) { - codec = next(); - } - if (version2 !== 0 && version2 !== 1) { - throw new RangeError(`Invalid CID version ${version2}`); - } - const prefixSize = offset; - const multihashCode = next(); - const digestSize = next(); - const size = offset + digestSize; - const multihashSize = size - prefixSize; - return { - version: version2, - codec, - multihashCode, - digestSize, - multihashSize, - size - }; - } - static parse(source, base3) { - const [prefix, bytes] = parseCIDtoBytes(source, base3); - const cid = _CID.decode(bytes); - cid._baseCache.set(prefix, source); - return cid; - } - }; - parseCIDtoBytes = (source, base3) => { - switch (source[0]) { - case "Q": { - const decoder = base3 || base58btc; - return [ - base58btc.prefix, - decoder.decode(`${base58btc.prefix}${source}`) - ]; - } - case base58btc.prefix: { - const decoder = base3 || base58btc; - return [ - base58btc.prefix, - decoder.decode(source) - ]; - } - case base32.prefix: { - const decoder = base3 || base32; - return [ - base32.prefix, - decoder.decode(source) - ]; - } - default: { - if (base3 == null) { - throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); - } - return [ - source[0], - base3.decode(source) - ]; - } - } - }; - toStringV0 = (bytes, cache, base3) => { - const { prefix } = base3; - if (prefix !== base58btc.prefix) { - throw Error(`Cannot string encode V0 in ${base3.name} encoding`); - } - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base3.encode(bytes).slice(1); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; - } - }; - toStringV1 = (bytes, cache, base3) => { - const { prefix } = base3; - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base3.encode(bytes); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; - } - }; - DAG_PB_CODE = 112; - SHA_256_CODE = 18; - encodeCID = (version2, code2, multihash) => { - const codeOffset = encodingLength(version2); - const hashOffset = codeOffset + encodingLength(code2); - const bytes = new Uint8Array(hashOffset + multihash.byteLength); - encodeTo(version2, bytes, 0); - encodeTo(code2, bytes, codeOffset); - bytes.set(multihash, hashOffset); - return bytes; - }; - cidSymbol = Symbol.for("@ipld/js-cid/CID"); - readonly = { - writable: false, - configurable: false, - enumerable: true - }; - hidden = { - writable: false, - enumerable: false, - configurable: false - }; - version = "0.0.0-dev"; - deprecate = (range, message) => { - if (range.test(version)) { - console.warn(message); - } else { - throw new Error(message); - } - }; - IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. -Following code pattern: - -if (CID.isCID(value)) { - doSomethingWithCID(value) -} - -Is replaced with: - -const cid = CID.asCID(value) -if (cid) { - // Make sure to use cid instead of value - doSomethingWithCID(cid) -} -`; - } -}); - -// node_modules/multiformats/esm/src/index.js -var init_src = __esm({ - "node_modules/multiformats/esm/src/index.js"() { - init_shim(); - init_cid(); - init_varint2(); - init_bytes(); - init_hasher(); - init_digest(); - } -}); - -// node_modules/multiformats/esm/src/basics.js -var bases, hashes; -var init_basics = __esm({ - "node_modules/multiformats/esm/src/basics.js"() { - init_shim(); - init_identity(); - init_base2(); - init_base8(); - init_base10(); - init_base16(); - init_base32(); - init_base36(); - init_base58(); - init_base64(); - init_base256emoji(); - init_sha2_browser(); - init_identity2(); - init_raw(); - init_json(); - init_src(); - bases = { - ...identity_exports, - ...base2_exports, - ...base8_exports, - ...base10_exports, - ...base16_exports, - ...base32_exports, - ...base36_exports, - ...base58_exports, - ...base64_exports, - ...base256emoji_exports - }; - hashes = { - ...sha2_browser_exports, - ...identity_exports2 - }; - } -}); - -// node_modules/uint8arrays/esm/src/util/bases.js -function createCodec(name2, prefix, encode5, decode6) { - return { - name: name2, - prefix, - encoder: { - name: name2, - prefix, - encode: encode5 - }, - decoder: { decode: decode6 } - }; -} -var string, ascii, BASES, bases_default; -var init_bases = __esm({ - "node_modules/uint8arrays/esm/src/util/bases.js"() { - init_shim(); - init_basics(); - init_alloc(); - string = createCodec("utf8", "u", (buf) => { - const decoder = new TextDecoder("utf8"); - return "u" + decoder.decode(buf); - }, (str) => { - const encoder = new TextEncoder(); - return encoder.encode(str.substring(1)); - }); - ascii = createCodec("ascii", "a", (buf) => { - let string2 = "a"; - for (let i2 = 0; i2 < buf.length; i2++) { - string2 += String.fromCharCode(buf[i2]); - } - return string2; - }, (str) => { - str = str.substring(1); - const buf = allocUnsafe(str.length); - for (let i2 = 0; i2 < str.length; i2++) { - buf[i2] = str.charCodeAt(i2); - } - return buf; - }); - BASES = { - utf8: string, - "utf-8": string, - hex: bases.base16, - latin1: ascii, - ascii, - binary: ascii, - ...bases - }; - bases_default = BASES; - } -}); - -// node_modules/uint8arrays/esm/src/to-string.js -function toString2(array, encoding = "utf8") { - const base3 = bases_default[encoding]; - if (!base3) { - throw new Error(`Unsupported encoding "${encoding}"`); - } - if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { - return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); - } - return base3.encoder.encode(array).substring(1); -} -var init_to_string = __esm({ - "node_modules/uint8arrays/esm/src/to-string.js"() { - init_shim(); - init_bases(); - } -}); - -// node_modules/uint8arrays/esm/src/from-string.js -function fromString2(string2, encoding = "utf8") { - const base3 = bases_default[encoding]; - if (!base3) { - throw new Error(`Unsupported encoding "${encoding}"`); - } - if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { - return asUint8Array(globalThis.Buffer.from(string2, "utf-8")); - } - return base3.decoder.decode(`${base3.prefix}${string2}`); -} -var init_from_string = __esm({ - "node_modules/uint8arrays/esm/src/from-string.js"() { - init_shim(); - init_bases(); - init_as_uint8array(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/utils.js -function decodeJSON(str) { - return safeJsonParse(toString2(fromString2(str, JWT_ENCODING), JSON_ENCODING)); -} -function encodeJSON(val) { - return toString2(fromString2(safeJsonStringify(val), JSON_ENCODING), JWT_ENCODING); -} -function encodeIss(publicKey) { - const header = fromString2(MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_ENCODING); - const multicodec = MULTICODEC_ED25519_BASE + toString2(concat([header, publicKey]), MULTICODEC_ED25519_ENCODING); - return [DID_PREFIX, DID_METHOD, multicodec].join(DID_DELIMITER); -} -function decodeIss(issuer) { - const [prefix, method, multicodec] = issuer.split(DID_DELIMITER); - if (prefix !== DID_PREFIX || method !== DID_METHOD) { - throw new Error(`Issuer must be a DID with method "key"`); - } - const base3 = multicodec.slice(0, 1); - if (base3 !== MULTICODEC_ED25519_BASE) { - throw new Error(`Issuer must be a key in mulicodec format`); - } - const bytes = fromString2(multicodec.slice(1), MULTICODEC_ED25519_ENCODING); - const type = toString2(bytes.slice(0, 2), MULTICODEC_ED25519_ENCODING); - if (type !== MULTICODEC_ED25519_HEADER) { - throw new Error(`Issuer must be a public key with type "Ed25519"`); - } - const publicKey = bytes.slice(2); - if (publicKey.length !== MULTICODEC_ED25519_LENGTH) { - throw new Error(`Issuer must be a public key with length 32 bytes`); - } - return publicKey; -} -function encodeSig(bytes) { - return toString2(bytes, JWT_ENCODING); -} -function decodeSig(encoded) { - return fromString2(encoded, JWT_ENCODING); -} -function encodeData(params) { - return fromString2([encodeJSON(params.header), encodeJSON(params.payload)].join(JWT_DELIMITER), DATA_ENCODING); -} -function decodeData(data) { - const params = toString2(data, DATA_ENCODING).split(JWT_DELIMITER); - const header = decodeJSON(params[0]); - const payload = decodeJSON(params[1]); - return { header, payload }; -} -function encodeJWT(params) { - return [ - encodeJSON(params.header), - encodeJSON(params.payload), - encodeSig(params.signature) - ].join(JWT_DELIMITER); -} -function decodeJWT(jwt) { - const params = jwt.split(JWT_DELIMITER); - const header = decodeJSON(params[0]); - const payload = decodeJSON(params[1]); - const signature = decodeSig(params[2]); - const data = fromString2(params.slice(0, 2).join(JWT_DELIMITER), DATA_ENCODING); - return { header, payload, signature, data }; -} -var init_utils = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/utils.js"() { - init_shim(); - init_concat(); - init_to_string(); - init_from_string(); - init_esm(); - init_constants(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/api.js -function generateKeyPair(seed = (0, import_random.randomBytes)(KEY_PAIR_SEED_LENGTH)) { - return ed25519.generateKeyPairFromSeed(seed); -} -async function signJWT(sub, aud, ttl, keyPair, iat = (0, import_time.fromMiliseconds)(Date.now())) { - const header = { alg: JWT_IRIDIUM_ALG, typ: JWT_IRIDIUM_TYP }; - const iss = encodeIss(keyPair.publicKey); - const exp = iat + ttl; - const payload = { iss, sub, aud, iat, exp }; - const data = encodeData({ header, payload }); - const signature = ed25519.sign(keyPair.secretKey, data); - return encodeJWT({ header, payload, signature }); -} -async function verifyJWT(jwt) { - const { header, payload, data, signature } = decodeJWT(jwt); - if (header.alg !== JWT_IRIDIUM_ALG || header.typ !== JWT_IRIDIUM_TYP) { - throw new Error("JWT must use EdDSA algorithm"); - } - const publicKey = decodeIss(payload.iss); - return ed25519.verify(publicKey, data, signature); -} -var ed25519, import_random, import_time; -var init_api = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/api.js"() { - init_shim(); - ed25519 = __toESM(require_ed25519()); - import_random = __toESM(require_random()); - import_time = __toESM(require_cjs()); - init_constants(); - init_utils(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/types.js -var init_types = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/types.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/relay-auth/dist/esm/index.js -var esm_exports3 = {}; -__export(esm_exports3, { - DATA_ENCODING: () => DATA_ENCODING, - DID_DELIMITER: () => DID_DELIMITER, - DID_METHOD: () => DID_METHOD, - DID_PREFIX: () => DID_PREFIX, - JSON_ENCODING: () => JSON_ENCODING, - JWT_DELIMITER: () => JWT_DELIMITER, - JWT_ENCODING: () => JWT_ENCODING, - JWT_IRIDIUM_ALG: () => JWT_IRIDIUM_ALG, - JWT_IRIDIUM_TYP: () => JWT_IRIDIUM_TYP, - KEY_PAIR_SEED_LENGTH: () => KEY_PAIR_SEED_LENGTH, - MULTICODEC_ED25519_BASE: () => MULTICODEC_ED25519_BASE, - MULTICODEC_ED25519_ENCODING: () => MULTICODEC_ED25519_ENCODING, - MULTICODEC_ED25519_HEADER: () => MULTICODEC_ED25519_HEADER, - MULTICODEC_ED25519_LENGTH: () => MULTICODEC_ED25519_LENGTH, - decodeData: () => decodeData, - decodeIss: () => decodeIss, - decodeJSON: () => decodeJSON, - decodeJWT: () => decodeJWT, - decodeSig: () => decodeSig, - encodeData: () => encodeData, - encodeIss: () => encodeIss, - encodeJSON: () => encodeJSON, - encodeJWT: () => encodeJWT, - encodeSig: () => encodeSig, - generateKeyPair: () => generateKeyPair, - signJWT: () => signJWT, - verifyJWT: () => verifyJWT -}); -var init_esm3 = __esm({ - "node_modules/@walletconnect/relay-auth/dist/esm/index.js"() { - init_shim(); - init_api(); - init_constants(); - init_types(); - init_utils(); - } -}); - -// node_modules/detect-browser/index.js -var require_detect_browser = __commonJS({ - "node_modules/detect-browser/index.js"(exports2) { - "use strict"; - init_shim(); - var __spreadArray = exports2 && exports2.__spreadArray || function(to, from3, pack) { - if (pack || arguments.length === 2) - for (var i2 = 0, l4 = from3.length, ar; i2 < l4; i2++) { - if (ar || !(i2 in from3)) { - if (!ar) - ar = Array.prototype.slice.call(from3, 0, i2); - ar[i2] = from3[i2]; - } - } - return to.concat(ar || Array.prototype.slice.call(from3)); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getNodeVersion = exports2.detectOS = exports2.parseUserAgent = exports2.browserName = exports2.detect = exports2.ReactNativeInfo = exports2.BotInfo = exports2.SearchBotDeviceInfo = exports2.NodeInfo = exports2.BrowserInfo = void 0; - var BrowserInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function BrowserInfo2(name2, version2, os) { - this.name = name2; - this.version = version2; - this.os = os; - this.type = "browser"; - } - return BrowserInfo2; - }() - ); - exports2.BrowserInfo = BrowserInfo; - var NodeInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function NodeInfo2(version2) { - this.version = version2; - this.type = "node"; - this.name = "node"; - this.os = import_process.default.platform; - } - return NodeInfo2; - }() - ); - exports2.NodeInfo = NodeInfo; - var SearchBotDeviceInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function SearchBotDeviceInfo2(name2, version2, os, bot) { - this.name = name2; - this.version = version2; - this.os = os; - this.bot = bot; - this.type = "bot-device"; - } - return SearchBotDeviceInfo2; - }() - ); - exports2.SearchBotDeviceInfo = SearchBotDeviceInfo; - var BotInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function BotInfo2() { - this.type = "bot"; - this.bot = true; - this.name = "bot"; - this.version = null; - this.os = null; - } - return BotInfo2; - }() - ); - exports2.BotInfo = BotInfo; - var ReactNativeInfo = ( - /** @class */ - /* @__PURE__ */ function() { - function ReactNativeInfo2() { - this.type = "react-native"; - this.name = "react-native"; - this.version = null; - this.os = null; - } - return ReactNativeInfo2; - }() - ); - exports2.ReactNativeInfo = ReactNativeInfo; - var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/; - var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/; - var REQUIRED_VERSION_PARTS = 3; - var userAgentRules = [ - ["aol", /AOLShield\/([0-9\._]+)/], - ["edge", /Edge\/([0-9\._]+)/], - ["edge-ios", /EdgiOS\/([0-9\._]+)/], - ["yandexbrowser", /YaBrowser\/([0-9\._]+)/], - ["kakaotalk", /KAKAOTALK\s([0-9\.]+)/], - ["samsung", /SamsungBrowser\/([0-9\.]+)/], - ["silk", /\bSilk\/([0-9._-]+)\b/], - ["miui", /MiuiBrowser\/([0-9\.]+)$/], - ["beaker", /BeakerBrowser\/([0-9\.]+)/], - ["edge-chromium", /EdgA?\/([0-9\.]+)/], - [ - "chromium-webview", - /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ - ], - ["chrome", /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], - ["phantomjs", /PhantomJS\/([0-9\.]+)(:?\s|$)/], - ["crios", /CriOS\/([0-9\.]+)(:?\s|$)/], - ["firefox", /Firefox\/([0-9\.]+)(?:\s|$)/], - ["fxios", /FxiOS\/([0-9\.]+)/], - ["opera-mini", /Opera Mini.*Version\/([0-9\.]+)/], - ["opera", /Opera\/([0-9\.]+)(?:\s|$)/], - ["opera", /OPR\/([0-9\.]+)(:?\s|$)/], - ["pie", /^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/], - ["pie", /^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/], - ["netfront", /^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/], - ["ie", /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], - ["ie", /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], - ["ie", /MSIE\s(7\.0)/], - ["bb10", /BB10;\sTouch.*Version\/([0-9\.]+)/], - ["android", /Android\s([0-9\.]+)/], - ["ios", /Version\/([0-9\._]+).*Mobile.*Safari.*/], - ["safari", /Version\/([0-9\._]+).*Safari/], - ["facebook", /FB[AS]V\/([0-9\.]+)/], - ["instagram", /Instagram\s([0-9\.]+)/], - ["ios-webview", /AppleWebKit\/([0-9\.]+).*Mobile/], - ["ios-webview", /AppleWebKit\/([0-9\.]+).*Gecko\)$/], - ["curl", /^curl\/([0-9\.]+)$/], - ["searchbot", SEARCHBOX_UA_REGEX] - ]; - var operatingSystemRules = [ - ["iOS", /iP(hone|od|ad)/], - ["Android OS", /Android/], - ["BlackBerry OS", /BlackBerry|BB10/], - ["Windows Mobile", /IEMobile/], - ["Amazon OS", /Kindle/], - ["Windows 3.11", /Win16/], - ["Windows 95", /(Windows 95)|(Win95)|(Windows_95)/], - ["Windows 98", /(Windows 98)|(Win98)/], - ["Windows 2000", /(Windows NT 5.0)|(Windows 2000)/], - ["Windows XP", /(Windows NT 5.1)|(Windows XP)/], - ["Windows Server 2003", /(Windows NT 5.2)/], - ["Windows Vista", /(Windows NT 6.0)/], - ["Windows 7", /(Windows NT 6.1)/], - ["Windows 8", /(Windows NT 6.2)/], - ["Windows 8.1", /(Windows NT 6.3)/], - ["Windows 10", /(Windows NT 10.0)/], - ["Windows ME", /Windows ME/], - ["Windows CE", /Windows CE|WinCE|Microsoft Pocket Internet Explorer/], - ["Open BSD", /OpenBSD/], - ["Sun OS", /SunOS/], - ["Chrome OS", /CrOS/], - ["Linux", /(Linux)|(X11)/], - ["Mac OS", /(Mac_PowerPC)|(Macintosh)/], - ["QNX", /QNX/], - ["BeOS", /BeOS/], - ["OS/2", /OS\/2/] - ]; - function detect(userAgent) { - if (!!userAgent) { - return parseUserAgent(userAgent); - } - if (typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative") { - return new ReactNativeInfo(); - } - if (typeof navigator !== "undefined") { - return parseUserAgent(navigator.userAgent); - } - return getNodeVersion(); - } - exports2.detect = detect; - function matchUserAgent(ua) { - return ua !== "" && userAgentRules.reduce(function(matched, _a) { - var browser = _a[0], regex = _a[1]; - if (matched) { - return matched; - } - var uaMatch = regex.exec(ua); - return !!uaMatch && [browser, uaMatch]; - }, false); - } - function browserName(ua) { - var data = matchUserAgent(ua); - return data ? data[0] : null; - } - exports2.browserName = browserName; - function parseUserAgent(ua) { - var matchedRule = matchUserAgent(ua); - if (!matchedRule) { - return null; - } - var name2 = matchedRule[0], match = matchedRule[1]; - if (name2 === "searchbot") { - return new BotInfo(); - } - var versionParts = match[1] && match[1].split(".").join("_").split("_").slice(0, 3); - if (versionParts) { - if (versionParts.length < REQUIRED_VERSION_PARTS) { - versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true); - } - } else { - versionParts = []; - } - var version2 = versionParts.join("."); - var os = detectOS(ua); - var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua); - if (searchBotMatch && searchBotMatch[1]) { - return new SearchBotDeviceInfo(name2, version2, os, searchBotMatch[1]); - } - return new BrowserInfo(name2, version2, os); - } - exports2.parseUserAgent = parseUserAgent; - function detectOS(ua) { - for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) { - var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1]; - var match = regex.exec(ua); - if (match) { - return os; - } - } - return null; - } - exports2.detectOS = detectOS; - function getNodeVersion() { - var isNode2 = typeof import_process.default !== "undefined" && import_process.default.version; - return isNode2 ? new NodeInfo(import_process.default.version.slice(1)) : null; - } - exports2.getNodeVersion = getNodeVersion; - function createVersionParts(count) { - var output = []; - for (var ii = 0; ii < count; ii++) { - output.push("0"); - } - return output; - } - } -}); - -// node_modules/@walletconnect/window-getters/dist/cjs/index.js -var require_cjs3 = __commonJS({ - "node_modules/@walletconnect/window-getters/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getLocalStorage = exports2.getLocalStorageOrThrow = exports2.getCrypto = exports2.getCryptoOrThrow = exports2.getLocation = exports2.getLocationOrThrow = exports2.getNavigator = exports2.getNavigatorOrThrow = exports2.getDocument = exports2.getDocumentOrThrow = exports2.getFromWindowOrThrow = exports2.getFromWindow = void 0; - function getFromWindow(name2) { - let res = void 0; - if (typeof window !== "undefined" && typeof window[name2] !== "undefined") { - res = window[name2]; - } - return res; - } - exports2.getFromWindow = getFromWindow; - function getFromWindowOrThrow(name2) { - const res = getFromWindow(name2); - if (!res) { - throw new Error(`${name2} is not defined in Window`); - } - return res; - } - exports2.getFromWindowOrThrow = getFromWindowOrThrow; - function getDocumentOrThrow() { - return getFromWindowOrThrow("document"); - } - exports2.getDocumentOrThrow = getDocumentOrThrow; - function getDocument() { - return getFromWindow("document"); - } - exports2.getDocument = getDocument; - function getNavigatorOrThrow() { - return getFromWindowOrThrow("navigator"); - } - exports2.getNavigatorOrThrow = getNavigatorOrThrow; - function getNavigator() { - return getFromWindow("navigator"); - } - exports2.getNavigator = getNavigator; - function getLocationOrThrow() { - return getFromWindowOrThrow("location"); - } - exports2.getLocationOrThrow = getLocationOrThrow; - function getLocation() { - return getFromWindow("location"); - } - exports2.getLocation = getLocation; - function getCryptoOrThrow() { - return getFromWindowOrThrow("crypto"); - } - exports2.getCryptoOrThrow = getCryptoOrThrow; - function getCrypto() { - return getFromWindow("crypto"); - } - exports2.getCrypto = getCrypto; - function getLocalStorageOrThrow() { - return getFromWindowOrThrow("localStorage"); - } - exports2.getLocalStorageOrThrow = getLocalStorageOrThrow; - function getLocalStorage() { - return getFromWindow("localStorage"); - } - exports2.getLocalStorage = getLocalStorage; - } -}); - -// node_modules/@walletconnect/window-metadata/dist/cjs/index.js -var require_cjs4 = __commonJS({ - "node_modules/@walletconnect/window-metadata/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getWindowMetadata = void 0; - var window_getters_1 = require_cjs3(); - function getWindowMetadata() { - let doc; - let loc; - try { - doc = window_getters_1.getDocumentOrThrow(); - loc = window_getters_1.getLocationOrThrow(); - } catch (e2) { - return null; - } - function getIcons() { - const links = doc.getElementsByTagName("link"); - const icons2 = []; - for (let i2 = 0; i2 < links.length; i2++) { - const link = links[i2]; - const rel = link.getAttribute("rel"); - if (rel) { - if (rel.toLowerCase().indexOf("icon") > -1) { - const href = link.getAttribute("href"); - if (href) { - if (href.toLowerCase().indexOf("https:") === -1 && href.toLowerCase().indexOf("http:") === -1 && href.indexOf("//") !== 0) { - let absoluteHref = loc.protocol + "//" + loc.host; - if (href.indexOf("/") === 0) { - absoluteHref += href; - } else { - const path = loc.pathname.split("/"); - path.pop(); - const finalPath = path.join("/"); - absoluteHref += finalPath + "/" + href; - } - icons2.push(absoluteHref); - } else if (href.indexOf("//") === 0) { - const absoluteUrl = loc.protocol + href; - icons2.push(absoluteUrl); - } else { - icons2.push(href); - } - } - } - } - } - return icons2; - } - function getWindowMetadataOfAny(...args) { - const metaTags = doc.getElementsByTagName("meta"); - for (let i2 = 0; i2 < metaTags.length; i2++) { - const tag = metaTags[i2]; - const attributes = ["itemprop", "property", "name"].map((target) => tag.getAttribute(target)).filter((attr) => { - if (attr) { - return args.includes(attr); - } - return false; - }); - if (attributes.length && attributes) { - const content = tag.getAttribute("content"); - if (content) { - return content; - } - } - } - return ""; - } - function getName() { - let name3 = getWindowMetadataOfAny("name", "og:site_name", "og:title", "twitter:title"); - if (!name3) { - name3 = doc.title; - } - return name3; - } - function getDescription() { - const description2 = getWindowMetadataOfAny("description", "og:description", "twitter:description", "keywords"); - return description2; - } - const name2 = getName(); - const description = getDescription(); - const url = loc.origin; - const icons = getIcons(); - const meta = { - description, - url, - icons, - name: name2 - }; - return meta; - } - exports2.getWindowMetadata = getWindowMetadata; - } -}); - -// node_modules/strict-uri-encode/index.js -var require_strict_uri_encode = __commonJS({ - "node_modules/strict-uri-encode/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (x3) => `%${x3.charCodeAt(0).toString(16).toUpperCase()}`); - } -}); - -// node_modules/decode-uri-component/index.js -var require_decode_uri_component = __commonJS({ - "node_modules/decode-uri-component/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var token = "%[a-f0-9]{2}"; - var singleMatcher = new RegExp("(" + token + ")|([^%]+?)", "gi"); - var multiMatcher = new RegExp("(" + token + ")+", "gi"); - function decodeComponents(components, split) { - try { - return [decodeURIComponent(components.join(""))]; - } catch (err) { - } - if (components.length === 1) { - return components; - } - split = split || 1; - var left = components.slice(0, split); - var right = components.slice(split); - return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); - } - function decode6(input) { - try { - return decodeURIComponent(input); - } catch (err) { - var tokens = input.match(singleMatcher) || []; - for (var i2 = 1; i2 < tokens.length; i2++) { - input = decodeComponents(tokens, i2).join(""); - tokens = input.match(singleMatcher) || []; - } - return input; - } - } - function customDecodeURIComponent(input) { - var replaceMap = { - "%FE%FF": "\uFFFD\uFFFD", - "%FF%FE": "\uFFFD\uFFFD" - }; - var match = multiMatcher.exec(input); - while (match) { - try { - replaceMap[match[0]] = decodeURIComponent(match[0]); - } catch (err) { - var result = decode6(match[0]); - if (result !== match[0]) { - replaceMap[match[0]] = result; - } - } - match = multiMatcher.exec(input); - } - replaceMap["%C2"] = "\uFFFD"; - var entries = Object.keys(replaceMap); - for (var i2 = 0; i2 < entries.length; i2++) { - var key = entries[i2]; - input = input.replace(new RegExp(key, "g"), replaceMap[key]); - } - return input; - } - module2.exports = function(encodedURI) { - if (typeof encodedURI !== "string") { - throw new TypeError("Expected `encodedURI` to be of type `string`, got `" + typeof encodedURI + "`"); - } - try { - encodedURI = encodedURI.replace(/\+/g, " "); - return decodeURIComponent(encodedURI); - } catch (err) { - return customDecodeURIComponent(encodedURI); - } - }; - } -}); - -// node_modules/split-on-first/index.js -var require_split_on_first = __commonJS({ - "node_modules/split-on-first/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = (string2, separator) => { - if (!(typeof string2 === "string" && typeof separator === "string")) { - throw new TypeError("Expected the arguments to be of type `string`"); - } - if (separator === "") { - return [string2]; - } - const separatorIndex = string2.indexOf(separator); - if (separatorIndex === -1) { - return [string2]; - } - return [ - string2.slice(0, separatorIndex), - string2.slice(separatorIndex + separator.length) - ]; - }; - } -}); - -// node_modules/filter-obj/index.js -var require_filter_obj = __commonJS({ - "node_modules/filter-obj/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function(obj, predicate) { - var ret = {}; - var keys2 = Object.keys(obj); - var isArr = Array.isArray(predicate); - for (var i2 = 0; i2 < keys2.length; i2++) { - var key = keys2[i2]; - var val = obj[key]; - if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) { - ret[key] = val; - } - } - return ret; - }; - } -}); - -// node_modules/query-string/index.js -var require_query_string = __commonJS({ - "node_modules/query-string/index.js"(exports2) { - "use strict"; - init_shim(); - var strictUriEncode = require_strict_uri_encode(); - var decodeComponent = require_decode_uri_component(); - var splitOnFirst = require_split_on_first(); - var filterObject = require_filter_obj(); - var isNullOrUndefined = (value) => value === null || value === void 0; - var encodeFragmentIdentifier = Symbol("encodeFragmentIdentifier"); - function encoderForArrayFormat(options) { - switch (options.arrayFormat) { - case "index": - return (key) => (result, value) => { - const index = result.length; - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, [encode5(key, options), "[", index, "]"].join("")]; - } - return [ - ...result, - [encode5(key, options), "[", encode5(index, options), "]=", encode5(value, options)].join("") - ]; - }; - case "bracket": - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, [encode5(key, options), "[]"].join("")]; - } - return [...result, [encode5(key, options), "[]=", encode5(value, options)].join("")]; - }; - case "colon-list-separator": - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, [encode5(key, options), ":list="].join("")]; - } - return [...result, [encode5(key, options), ":list=", encode5(value, options)].join("")]; - }; - case "comma": - case "separator": - case "bracket-separator": { - const keyValueSep = options.arrayFormat === "bracket-separator" ? "[]=" : "="; - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - value = value === null ? "" : value; - if (result.length === 0) { - return [[encode5(key, options), keyValueSep, encode5(value, options)].join("")]; - } - return [[result, encode5(value, options)].join(options.arrayFormatSeparator)]; - }; - } - default: - return (key) => (result, value) => { - if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { - return result; - } - if (value === null) { - return [...result, encode5(key, options)]; - } - return [...result, [encode5(key, options), "=", encode5(value, options)].join("")]; - }; - } - } - function parserForArrayFormat(options) { - let result; - switch (options.arrayFormat) { - case "index": - return (key, value, accumulator) => { - result = /\[(\d*)\]$/.exec(key); - key = key.replace(/\[\d*\]$/, ""); - if (!result) { - accumulator[key] = value; - return; - } - if (accumulator[key] === void 0) { - accumulator[key] = {}; - } - accumulator[key][result[1]] = value; - }; - case "bracket": - return (key, value, accumulator) => { - result = /(\[\])$/.exec(key); - key = key.replace(/\[\]$/, ""); - if (!result) { - accumulator[key] = value; - return; - } - if (accumulator[key] === void 0) { - accumulator[key] = [value]; - return; - } - accumulator[key] = [].concat(accumulator[key], value); - }; - case "colon-list-separator": - return (key, value, accumulator) => { - result = /(:list)$/.exec(key); - key = key.replace(/:list$/, ""); - if (!result) { - accumulator[key] = value; - return; - } - if (accumulator[key] === void 0) { - accumulator[key] = [value]; - return; - } - accumulator[key] = [].concat(accumulator[key], value); - }; - case "comma": - case "separator": - return (key, value, accumulator) => { - const isArray = typeof value === "string" && value.includes(options.arrayFormatSeparator); - const isEncodedArray = typeof value === "string" && !isArray && decode6(value, options).includes(options.arrayFormatSeparator); - value = isEncodedArray ? decode6(value, options) : value; - const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)) : value === null ? value : decode6(value, options); - accumulator[key] = newValue; - }; - case "bracket-separator": - return (key, value, accumulator) => { - const isArray = /(\[\])$/.test(key); - key = key.replace(/\[\]$/, ""); - if (!isArray) { - accumulator[key] = value ? decode6(value, options) : value; - return; - } - const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map((item) => decode6(item, options)); - if (accumulator[key] === void 0) { - accumulator[key] = arrayValue; - return; - } - accumulator[key] = [].concat(accumulator[key], arrayValue); - }; - default: - return (key, value, accumulator) => { - if (accumulator[key] === void 0) { - accumulator[key] = value; - return; - } - accumulator[key] = [].concat(accumulator[key], value); - }; - } - } - function validateArrayFormatSeparator(value) { - if (typeof value !== "string" || value.length !== 1) { - throw new TypeError("arrayFormatSeparator must be single character string"); - } - } - function encode5(value, options) { - if (options.encode) { - return options.strict ? strictUriEncode(value) : encodeURIComponent(value); - } - return value; - } - function decode6(value, options) { - if (options.decode) { - return decodeComponent(value); - } - return value; - } - function keysSorter(input) { - if (Array.isArray(input)) { - return input.sort(); - } - if (typeof input === "object") { - return keysSorter(Object.keys(input)).sort((a3, b4) => Number(a3) - Number(b4)).map((key) => input[key]); - } - return input; - } - function removeHash(input) { - const hashStart = input.indexOf("#"); - if (hashStart !== -1) { - input = input.slice(0, hashStart); - } - return input; - } - function getHash(url) { - let hash = ""; - const hashStart = url.indexOf("#"); - if (hashStart !== -1) { - hash = url.slice(hashStart); - } - return hash; - } - function extract(input) { - input = removeHash(input); - const queryStart = input.indexOf("?"); - if (queryStart === -1) { - return ""; - } - return input.slice(queryStart + 1); - } - function parseValue(value, options) { - if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === "string" && value.trim() !== "")) { - value = Number(value); - } else if (options.parseBooleans && value !== null && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) { - value = value.toLowerCase() === "true"; - } - return value; - } - function parse(query, options) { - options = Object.assign({ - decode: true, - sort: true, - arrayFormat: "none", - arrayFormatSeparator: ",", - parseNumbers: false, - parseBooleans: false - }, options); - validateArrayFormatSeparator(options.arrayFormatSeparator); - const formatter = parserForArrayFormat(options); - const ret = /* @__PURE__ */ Object.create(null); - if (typeof query !== "string") { - return ret; - } - query = query.trim().replace(/^[?#&]/, ""); - if (!query) { - return ret; - } - for (const param of query.split("&")) { - if (param === "") { - continue; - } - let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, " ") : param, "="); - value = value === void 0 ? null : ["comma", "separator", "bracket-separator"].includes(options.arrayFormat) ? value : decode6(value, options); - formatter(decode6(key, options), value, ret); - } - for (const key of Object.keys(ret)) { - const value = ret[key]; - if (typeof value === "object" && value !== null) { - for (const k4 of Object.keys(value)) { - value[k4] = parseValue(value[k4], options); - } - } else { - ret[key] = parseValue(value, options); - } - } - if (options.sort === false) { - return ret; - } - return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => { - const value = ret[key]; - if (Boolean(value) && typeof value === "object" && !Array.isArray(value)) { - result[key] = keysSorter(value); - } else { - result[key] = value; - } - return result; - }, /* @__PURE__ */ Object.create(null)); - } - exports2.extract = extract; - exports2.parse = parse; - exports2.stringify = (object, options) => { - if (!object) { - return ""; - } - options = Object.assign({ - encode: true, - strict: true, - arrayFormat: "none", - arrayFormatSeparator: "," - }, options); - validateArrayFormatSeparator(options.arrayFormatSeparator); - const shouldFilter = (key) => options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === ""; - const formatter = encoderForArrayFormat(options); - const objectCopy = {}; - for (const key of Object.keys(object)) { - if (!shouldFilter(key)) { - objectCopy[key] = object[key]; - } - } - const keys2 = Object.keys(objectCopy); - if (options.sort !== false) { - keys2.sort(options.sort); - } - return keys2.map((key) => { - const value = object[key]; - if (value === void 0) { - return ""; - } - if (value === null) { - return encode5(key, options); - } - if (Array.isArray(value)) { - if (value.length === 0 && options.arrayFormat === "bracket-separator") { - return encode5(key, options) + "[]"; - } - return value.reduce(formatter(key), []).join("&"); - } - return encode5(key, options) + "=" + encode5(value, options); - }).filter((x3) => x3.length > 0).join("&"); - }; - exports2.parseUrl = (url, options) => { - options = Object.assign({ - decode: true - }, options); - const [url_, hash] = splitOnFirst(url, "#"); - return Object.assign( - { - url: url_.split("?")[0] || "", - query: parse(extract(url), options) - }, - options && options.parseFragmentIdentifier && hash ? { fragmentIdentifier: decode6(hash, options) } : {} - ); - }; - exports2.stringifyUrl = (object, options) => { - options = Object.assign({ - encode: true, - strict: true, - [encodeFragmentIdentifier]: true - }, options); - const url = removeHash(object.url).split("?")[0] || ""; - const queryFromUrl = exports2.extract(object.url); - const parsedQueryFromUrl = exports2.parse(queryFromUrl, { sort: false }); - const query = Object.assign(parsedQueryFromUrl, object.query); - let queryString = exports2.stringify(query, options); - if (queryString) { - queryString = `?${queryString}`; - } - let hash = getHash(object.url); - if (object.fragmentIdentifier) { - hash = `#${options[encodeFragmentIdentifier] ? encode5(object.fragmentIdentifier, options) : object.fragmentIdentifier}`; - } - return `${url}${queryString}${hash}`; - }; - exports2.pick = (input, filter, options) => { - options = Object.assign({ - parseFragmentIdentifier: true, - [encodeFragmentIdentifier]: false - }, options); - const { url, query, fragmentIdentifier } = exports2.parseUrl(input, options); - return exports2.stringifyUrl({ - url, - query: filterObject(query, filter), - fragmentIdentifier - }, options); - }; - exports2.exclude = (input, filter, options) => { - const exclusionFilter = Array.isArray(filter) ? (key) => !filter.includes(key) : (key, value) => !filter(key, value); - return exports2.pick(input, exclusionFilter, options); - }; - } -}); - -// node_modules/@stablelib/chacha/lib/chacha.js -var require_chacha = __commonJS({ - "node_modules/@stablelib/chacha/lib/chacha.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - var ROUNDS = 20; - function core(out, input, key) { - var j0 = 1634760805; - var j1 = 857760878; - var j2 = 2036477234; - var j3 = 1797285236; - var j4 = key[3] << 24 | key[2] << 16 | key[1] << 8 | key[0]; - var j5 = key[7] << 24 | key[6] << 16 | key[5] << 8 | key[4]; - var j6 = key[11] << 24 | key[10] << 16 | key[9] << 8 | key[8]; - var j7 = key[15] << 24 | key[14] << 16 | key[13] << 8 | key[12]; - var j8 = key[19] << 24 | key[18] << 16 | key[17] << 8 | key[16]; - var j9 = key[23] << 24 | key[22] << 16 | key[21] << 8 | key[20]; - var j10 = key[27] << 24 | key[26] << 16 | key[25] << 8 | key[24]; - var j11 = key[31] << 24 | key[30] << 16 | key[29] << 8 | key[28]; - var j12 = input[3] << 24 | input[2] << 16 | input[1] << 8 | input[0]; - var j13 = input[7] << 24 | input[6] << 16 | input[5] << 8 | input[4]; - var j14 = input[11] << 24 | input[10] << 16 | input[9] << 8 | input[8]; - var j15 = input[15] << 24 | input[14] << 16 | input[13] << 8 | input[12]; - var x0 = j0; - var x1 = j1; - var x22 = j2; - var x3 = j3; - var x4 = j4; - var x5 = j5; - var x6 = j6; - var x7 = j7; - var x8 = j8; - var x9 = j9; - var x10 = j10; - var x11 = j11; - var x12 = j12; - var x13 = j13; - var x14 = j14; - var x15 = j15; - for (var i2 = 0; i2 < ROUNDS; i2 += 2) { - x0 = x0 + x4 | 0; - x12 ^= x0; - x12 = x12 >>> 32 - 16 | x12 << 16; - x8 = x8 + x12 | 0; - x4 ^= x8; - x4 = x4 >>> 32 - 12 | x4 << 12; - x1 = x1 + x5 | 0; - x13 ^= x1; - x13 = x13 >>> 32 - 16 | x13 << 16; - x9 = x9 + x13 | 0; - x5 ^= x9; - x5 = x5 >>> 32 - 12 | x5 << 12; - x22 = x22 + x6 | 0; - x14 ^= x22; - x14 = x14 >>> 32 - 16 | x14 << 16; - x10 = x10 + x14 | 0; - x6 ^= x10; - x6 = x6 >>> 32 - 12 | x6 << 12; - x3 = x3 + x7 | 0; - x15 ^= x3; - x15 = x15 >>> 32 - 16 | x15 << 16; - x11 = x11 + x15 | 0; - x7 ^= x11; - x7 = x7 >>> 32 - 12 | x7 << 12; - x22 = x22 + x6 | 0; - x14 ^= x22; - x14 = x14 >>> 32 - 8 | x14 << 8; - x10 = x10 + x14 | 0; - x6 ^= x10; - x6 = x6 >>> 32 - 7 | x6 << 7; - x3 = x3 + x7 | 0; - x15 ^= x3; - x15 = x15 >>> 32 - 8 | x15 << 8; - x11 = x11 + x15 | 0; - x7 ^= x11; - x7 = x7 >>> 32 - 7 | x7 << 7; - x1 = x1 + x5 | 0; - x13 ^= x1; - x13 = x13 >>> 32 - 8 | x13 << 8; - x9 = x9 + x13 | 0; - x5 ^= x9; - x5 = x5 >>> 32 - 7 | x5 << 7; - x0 = x0 + x4 | 0; - x12 ^= x0; - x12 = x12 >>> 32 - 8 | x12 << 8; - x8 = x8 + x12 | 0; - x4 ^= x8; - x4 = x4 >>> 32 - 7 | x4 << 7; - x0 = x0 + x5 | 0; - x15 ^= x0; - x15 = x15 >>> 32 - 16 | x15 << 16; - x10 = x10 + x15 | 0; - x5 ^= x10; - x5 = x5 >>> 32 - 12 | x5 << 12; - x1 = x1 + x6 | 0; - x12 ^= x1; - x12 = x12 >>> 32 - 16 | x12 << 16; - x11 = x11 + x12 | 0; - x6 ^= x11; - x6 = x6 >>> 32 - 12 | x6 << 12; - x22 = x22 + x7 | 0; - x13 ^= x22; - x13 = x13 >>> 32 - 16 | x13 << 16; - x8 = x8 + x13 | 0; - x7 ^= x8; - x7 = x7 >>> 32 - 12 | x7 << 12; - x3 = x3 + x4 | 0; - x14 ^= x3; - x14 = x14 >>> 32 - 16 | x14 << 16; - x9 = x9 + x14 | 0; - x4 ^= x9; - x4 = x4 >>> 32 - 12 | x4 << 12; - x22 = x22 + x7 | 0; - x13 ^= x22; - x13 = x13 >>> 32 - 8 | x13 << 8; - x8 = x8 + x13 | 0; - x7 ^= x8; - x7 = x7 >>> 32 - 7 | x7 << 7; - x3 = x3 + x4 | 0; - x14 ^= x3; - x14 = x14 >>> 32 - 8 | x14 << 8; - x9 = x9 + x14 | 0; - x4 ^= x9; - x4 = x4 >>> 32 - 7 | x4 << 7; - x1 = x1 + x6 | 0; - x12 ^= x1; - x12 = x12 >>> 32 - 8 | x12 << 8; - x11 = x11 + x12 | 0; - x6 ^= x11; - x6 = x6 >>> 32 - 7 | x6 << 7; - x0 = x0 + x5 | 0; - x15 ^= x0; - x15 = x15 >>> 32 - 8 | x15 << 8; - x10 = x10 + x15 | 0; - x5 ^= x10; - x5 = x5 >>> 32 - 7 | x5 << 7; - } - binary_1.writeUint32LE(x0 + j0 | 0, out, 0); - binary_1.writeUint32LE(x1 + j1 | 0, out, 4); - binary_1.writeUint32LE(x22 + j2 | 0, out, 8); - binary_1.writeUint32LE(x3 + j3 | 0, out, 12); - binary_1.writeUint32LE(x4 + j4 | 0, out, 16); - binary_1.writeUint32LE(x5 + j5 | 0, out, 20); - binary_1.writeUint32LE(x6 + j6 | 0, out, 24); - binary_1.writeUint32LE(x7 + j7 | 0, out, 28); - binary_1.writeUint32LE(x8 + j8 | 0, out, 32); - binary_1.writeUint32LE(x9 + j9 | 0, out, 36); - binary_1.writeUint32LE(x10 + j10 | 0, out, 40); - binary_1.writeUint32LE(x11 + j11 | 0, out, 44); - binary_1.writeUint32LE(x12 + j12 | 0, out, 48); - binary_1.writeUint32LE(x13 + j13 | 0, out, 52); - binary_1.writeUint32LE(x14 + j14 | 0, out, 56); - binary_1.writeUint32LE(x15 + j15 | 0, out, 60); - } - function streamXOR(key, nonce, src2, dst, nonceInplaceCounterLength) { - if (nonceInplaceCounterLength === void 0) { - nonceInplaceCounterLength = 0; - } - if (key.length !== 32) { - throw new Error("ChaCha: key size must be 32 bytes"); - } - if (dst.length < src2.length) { - throw new Error("ChaCha: destination is shorter than source"); - } - var nc; - var counterLength; - if (nonceInplaceCounterLength === 0) { - if (nonce.length !== 8 && nonce.length !== 12) { - throw new Error("ChaCha nonce must be 8 or 12 bytes"); - } - nc = new Uint8Array(16); - counterLength = nc.length - nonce.length; - nc.set(nonce, counterLength); - } else { - if (nonce.length !== 16) { - throw new Error("ChaCha nonce with counter must be 16 bytes"); - } - nc = nonce; - counterLength = nonceInplaceCounterLength; - } - var block = new Uint8Array(64); - for (var i2 = 0; i2 < src2.length; i2 += 64) { - core(block, nc, key); - for (var j2 = i2; j2 < i2 + 64 && j2 < src2.length; j2++) { - dst[j2] = src2[j2] ^ block[j2 - i2]; - } - incrementCounter(nc, 0, counterLength); - } - wipe_1.wipe(block); - if (nonceInplaceCounterLength === 0) { - wipe_1.wipe(nc); - } - return dst; - } - exports2.streamXOR = streamXOR; - function stream(key, nonce, dst, nonceInplaceCounterLength) { - if (nonceInplaceCounterLength === void 0) { - nonceInplaceCounterLength = 0; - } - wipe_1.wipe(dst); - return streamXOR(key, nonce, dst, dst, nonceInplaceCounterLength); - } - exports2.stream = stream; - function incrementCounter(counter, pos, len) { - var carry = 1; - while (len--) { - carry = carry + (counter[pos] & 255) | 0; - counter[pos] = carry & 255; - carry >>>= 8; - pos++; - } - if (carry > 0) { - throw new Error("ChaCha: counter overflow"); - } - } - } -}); - -// node_modules/@stablelib/constant-time/lib/constant-time.js -var require_constant_time = __commonJS({ - "node_modules/@stablelib/constant-time/lib/constant-time.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function select(subject, resultIfOne, resultIfZero) { - return ~(subject - 1) & resultIfOne | subject - 1 & resultIfZero; - } - exports2.select = select; - function lessOrEqual(a3, b4) { - return (a3 | 0) - (b4 | 0) - 1 >>> 31 & 1; - } - exports2.lessOrEqual = lessOrEqual; - function compare3(a3, b4) { - if (a3.length !== b4.length) { - return 0; - } - var result = 0; - for (var i2 = 0; i2 < a3.length; i2++) { - result |= a3[i2] ^ b4[i2]; - } - return 1 & result - 1 >>> 8; - } - exports2.compare = compare3; - function equal(a3, b4) { - if (a3.length === 0 || b4.length === 0) { - return false; - } - return compare3(a3, b4) !== 0; - } - exports2.equal = equal; - } -}); - -// node_modules/@stablelib/poly1305/lib/poly1305.js -var require_poly1305 = __commonJS({ - "node_modules/@stablelib/poly1305/lib/poly1305.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var constant_time_1 = require_constant_time(); - var wipe_1 = require_wipe(); - exports2.DIGEST_LENGTH = 16; - var Poly1305 = ( - /** @class */ - function() { - function Poly13052(key) { - this.digestLength = exports2.DIGEST_LENGTH; - this._buffer = new Uint8Array(16); - this._r = new Uint16Array(10); - this._h = new Uint16Array(10); - this._pad = new Uint16Array(8); - this._leftover = 0; - this._fin = 0; - this._finished = false; - var t0 = key[0] | key[1] << 8; - this._r[0] = t0 & 8191; - var t1 = key[2] | key[3] << 8; - this._r[1] = (t0 >>> 13 | t1 << 3) & 8191; - var t2 = key[4] | key[5] << 8; - this._r[2] = (t1 >>> 10 | t2 << 6) & 7939; - var t3 = key[6] | key[7] << 8; - this._r[3] = (t2 >>> 7 | t3 << 9) & 8191; - var t4 = key[8] | key[9] << 8; - this._r[4] = (t3 >>> 4 | t4 << 12) & 255; - this._r[5] = t4 >>> 1 & 8190; - var t5 = key[10] | key[11] << 8; - this._r[6] = (t4 >>> 14 | t5 << 2) & 8191; - var t6 = key[12] | key[13] << 8; - this._r[7] = (t5 >>> 11 | t6 << 5) & 8065; - var t7 = key[14] | key[15] << 8; - this._r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this._r[9] = t7 >>> 5 & 127; - this._pad[0] = key[16] | key[17] << 8; - this._pad[1] = key[18] | key[19] << 8; - this._pad[2] = key[20] | key[21] << 8; - this._pad[3] = key[22] | key[23] << 8; - this._pad[4] = key[24] | key[25] << 8; - this._pad[5] = key[26] | key[27] << 8; - this._pad[6] = key[28] | key[29] << 8; - this._pad[7] = key[30] | key[31] << 8; - } - Poly13052.prototype._blocks = function(m3, mpos, bytes) { - var hibit = this._fin ? 0 : 1 << 11; - var h0 = this._h[0], h1 = this._h[1], h22 = this._h[2], h32 = this._h[3], h42 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9]; - var r0 = this._r[0], r1 = this._r[1], r2 = this._r[2], r3 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9]; - while (bytes >= 16) { - var t0 = m3[mpos + 0] | m3[mpos + 1] << 8; - h0 += t0 & 8191; - var t1 = m3[mpos + 2] | m3[mpos + 3] << 8; - h1 += (t0 >>> 13 | t1 << 3) & 8191; - var t2 = m3[mpos + 4] | m3[mpos + 5] << 8; - h22 += (t1 >>> 10 | t2 << 6) & 8191; - var t3 = m3[mpos + 6] | m3[mpos + 7] << 8; - h32 += (t2 >>> 7 | t3 << 9) & 8191; - var t4 = m3[mpos + 8] | m3[mpos + 9] << 8; - h42 += (t3 >>> 4 | t4 << 12) & 8191; - h5 += t4 >>> 1 & 8191; - var t5 = m3[mpos + 10] | m3[mpos + 11] << 8; - h6 += (t4 >>> 14 | t5 << 2) & 8191; - var t6 = m3[mpos + 12] | m3[mpos + 13] << 8; - h7 += (t5 >>> 11 | t6 << 5) & 8191; - var t7 = m3[mpos + 14] | m3[mpos + 15] << 8; - h8 += (t6 >>> 8 | t7 << 8) & 8191; - h9 += t7 >>> 5 | hibit; - var c4 = 0; - var d0 = c4; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h22 * (5 * r8); - d0 += h32 * (5 * r7); - d0 += h42 * (5 * r6); - c4 = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c4 += d0 >>> 13; - d0 &= 8191; - var d1 = c4; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h22 * (5 * r9); - d1 += h32 * (5 * r8); - d1 += h42 * (5 * r7); - c4 = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c4 += d1 >>> 13; - d1 &= 8191; - var d22 = c4; - d22 += h0 * r2; - d22 += h1 * r1; - d22 += h22 * r0; - d22 += h32 * (5 * r9); - d22 += h42 * (5 * r8); - c4 = d22 >>> 13; - d22 &= 8191; - d22 += h5 * (5 * r7); - d22 += h6 * (5 * r6); - d22 += h7 * (5 * r5); - d22 += h8 * (5 * r4); - d22 += h9 * (5 * r3); - c4 += d22 >>> 13; - d22 &= 8191; - var d3 = c4; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h22 * r1; - d3 += h32 * r0; - d3 += h42 * (5 * r9); - c4 = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c4 += d3 >>> 13; - d3 &= 8191; - var d4 = c4; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h22 * r2; - d4 += h32 * r1; - d4 += h42 * r0; - c4 = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c4 += d4 >>> 13; - d4 &= 8191; - var d5 = c4; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h22 * r3; - d5 += h32 * r2; - d5 += h42 * r1; - c4 = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c4 += d5 >>> 13; - d5 &= 8191; - var d6 = c4; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h22 * r4; - d6 += h32 * r3; - d6 += h42 * r2; - c4 = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c4 += d6 >>> 13; - d6 &= 8191; - var d7 = c4; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h22 * r5; - d7 += h32 * r4; - d7 += h42 * r3; - c4 = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c4 += d7 >>> 13; - d7 &= 8191; - var d8 = c4; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h22 * r6; - d8 += h32 * r5; - d8 += h42 * r4; - c4 = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c4 += d8 >>> 13; - d8 &= 8191; - var d9 = c4; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h22 * r7; - d9 += h32 * r6; - d9 += h42 * r5; - c4 = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c4 += d9 >>> 13; - d9 &= 8191; - c4 = (c4 << 2) + c4 | 0; - c4 = c4 + d0 | 0; - d0 = c4 & 8191; - c4 = c4 >>> 13; - d1 += c4; - h0 = d0; - h1 = d1; - h22 = d22; - h32 = d3; - h42 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - mpos += 16; - bytes -= 16; - } - this._h[0] = h0; - this._h[1] = h1; - this._h[2] = h22; - this._h[3] = h32; - this._h[4] = h42; - this._h[5] = h5; - this._h[6] = h6; - this._h[7] = h7; - this._h[8] = h8; - this._h[9] = h9; - }; - Poly13052.prototype.finish = function(mac, macpos) { - if (macpos === void 0) { - macpos = 0; - } - var g3 = new Uint16Array(10); - var c4; - var mask; - var f4; - var i2; - if (this._leftover) { - i2 = this._leftover; - this._buffer[i2++] = 1; - for (; i2 < 16; i2++) { - this._buffer[i2] = 0; - } - this._fin = 1; - this._blocks(this._buffer, 0, 16); - } - c4 = this._h[1] >>> 13; - this._h[1] &= 8191; - for (i2 = 2; i2 < 10; i2++) { - this._h[i2] += c4; - c4 = this._h[i2] >>> 13; - this._h[i2] &= 8191; - } - this._h[0] += c4 * 5; - c4 = this._h[0] >>> 13; - this._h[0] &= 8191; - this._h[1] += c4; - c4 = this._h[1] >>> 13; - this._h[1] &= 8191; - this._h[2] += c4; - g3[0] = this._h[0] + 5; - c4 = g3[0] >>> 13; - g3[0] &= 8191; - for (i2 = 1; i2 < 10; i2++) { - g3[i2] = this._h[i2] + c4; - c4 = g3[i2] >>> 13; - g3[i2] &= 8191; - } - g3[9] -= 1 << 13; - mask = (c4 ^ 1) - 1; - for (i2 = 0; i2 < 10; i2++) { - g3[i2] &= mask; - } - mask = ~mask; - for (i2 = 0; i2 < 10; i2++) { - this._h[i2] = this._h[i2] & mask | g3[i2]; - } - this._h[0] = (this._h[0] | this._h[1] << 13) & 65535; - this._h[1] = (this._h[1] >>> 3 | this._h[2] << 10) & 65535; - this._h[2] = (this._h[2] >>> 6 | this._h[3] << 7) & 65535; - this._h[3] = (this._h[3] >>> 9 | this._h[4] << 4) & 65535; - this._h[4] = (this._h[4] >>> 12 | this._h[5] << 1 | this._h[6] << 14) & 65535; - this._h[5] = (this._h[6] >>> 2 | this._h[7] << 11) & 65535; - this._h[6] = (this._h[7] >>> 5 | this._h[8] << 8) & 65535; - this._h[7] = (this._h[8] >>> 8 | this._h[9] << 5) & 65535; - f4 = this._h[0] + this._pad[0]; - this._h[0] = f4 & 65535; - for (i2 = 1; i2 < 8; i2++) { - f4 = (this._h[i2] + this._pad[i2] | 0) + (f4 >>> 16) | 0; - this._h[i2] = f4 & 65535; - } - mac[macpos + 0] = this._h[0] >>> 0; - mac[macpos + 1] = this._h[0] >>> 8; - mac[macpos + 2] = this._h[1] >>> 0; - mac[macpos + 3] = this._h[1] >>> 8; - mac[macpos + 4] = this._h[2] >>> 0; - mac[macpos + 5] = this._h[2] >>> 8; - mac[macpos + 6] = this._h[3] >>> 0; - mac[macpos + 7] = this._h[3] >>> 8; - mac[macpos + 8] = this._h[4] >>> 0; - mac[macpos + 9] = this._h[4] >>> 8; - mac[macpos + 10] = this._h[5] >>> 0; - mac[macpos + 11] = this._h[5] >>> 8; - mac[macpos + 12] = this._h[6] >>> 0; - mac[macpos + 13] = this._h[6] >>> 8; - mac[macpos + 14] = this._h[7] >>> 0; - mac[macpos + 15] = this._h[7] >>> 8; - this._finished = true; - return this; - }; - Poly13052.prototype.update = function(m3) { - var mpos = 0; - var bytes = m3.length; - var want; - if (this._leftover) { - want = 16 - this._leftover; - if (want > bytes) { - want = bytes; - } - for (var i2 = 0; i2 < want; i2++) { - this._buffer[this._leftover + i2] = m3[mpos + i2]; - } - bytes -= want; - mpos += want; - this._leftover += want; - if (this._leftover < 16) { - return this; - } - this._blocks(this._buffer, 0, 16); - this._leftover = 0; - } - if (bytes >= 16) { - want = bytes - bytes % 16; - this._blocks(m3, mpos, want); - mpos += want; - bytes -= want; - } - if (bytes) { - for (var i2 = 0; i2 < bytes; i2++) { - this._buffer[this._leftover + i2] = m3[mpos + i2]; - } - this._leftover += bytes; - } - return this; - }; - Poly13052.prototype.digest = function() { - if (this._finished) { - throw new Error("Poly1305 was finished"); - } - var mac = new Uint8Array(16); - this.finish(mac); - return mac; - }; - Poly13052.prototype.clean = function() { - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._r); - wipe_1.wipe(this._h); - wipe_1.wipe(this._pad); - this._leftover = 0; - this._fin = 0; - this._finished = true; - return this; - }; - return Poly13052; - }() - ); - exports2.Poly1305 = Poly1305; - function oneTimeAuth(key, data) { - var h5 = new Poly1305(key); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.oneTimeAuth = oneTimeAuth; - function equal(a3, b4) { - if (a3.length !== exports2.DIGEST_LENGTH || b4.length !== exports2.DIGEST_LENGTH) { - return false; - } - return constant_time_1.equal(a3, b4); - } - exports2.equal = equal; - } -}); - -// node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js -var require_chacha20poly1305 = __commonJS({ - "node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var chacha_1 = require_chacha(); - var poly1305_1 = require_poly1305(); - var wipe_1 = require_wipe(); - var binary_1 = require_binary2(); - var constant_time_1 = require_constant_time(); - exports2.KEY_LENGTH = 32; - exports2.NONCE_LENGTH = 12; - exports2.TAG_LENGTH = 16; - var ZEROS = new Uint8Array(16); - var ChaCha20Poly1305 = ( - /** @class */ - function() { - function ChaCha20Poly13052(key) { - this.nonceLength = exports2.NONCE_LENGTH; - this.tagLength = exports2.TAG_LENGTH; - if (key.length !== exports2.KEY_LENGTH) { - throw new Error("ChaCha20Poly1305 needs 32-byte key"); - } - this._key = new Uint8Array(key); - } - ChaCha20Poly13052.prototype.seal = function(nonce, plaintext, associatedData, dst) { - if (nonce.length > 16) { - throw new Error("ChaCha20Poly1305: incorrect nonce length"); - } - var counter = new Uint8Array(16); - counter.set(nonce, counter.length - nonce.length); - var authKey = new Uint8Array(32); - chacha_1.stream(this._key, counter, authKey, 4); - var resultLength = plaintext.length + this.tagLength; - var result; - if (dst) { - if (dst.length !== resultLength) { - throw new Error("ChaCha20Poly1305: incorrect destination length"); - } - result = dst; - } else { - result = new Uint8Array(resultLength); - } - chacha_1.streamXOR(this._key, counter, plaintext, result, 4); - this._authenticate(result.subarray(result.length - this.tagLength, result.length), authKey, result.subarray(0, result.length - this.tagLength), associatedData); - wipe_1.wipe(counter); - return result; - }; - ChaCha20Poly13052.prototype.open = function(nonce, sealed, associatedData, dst) { - if (nonce.length > 16) { - throw new Error("ChaCha20Poly1305: incorrect nonce length"); - } - if (sealed.length < this.tagLength) { - return null; - } - var counter = new Uint8Array(16); - counter.set(nonce, counter.length - nonce.length); - var authKey = new Uint8Array(32); - chacha_1.stream(this._key, counter, authKey, 4); - var calculatedTag = new Uint8Array(this.tagLength); - this._authenticate(calculatedTag, authKey, sealed.subarray(0, sealed.length - this.tagLength), associatedData); - if (!constant_time_1.equal(calculatedTag, sealed.subarray(sealed.length - this.tagLength, sealed.length))) { - return null; - } - var resultLength = sealed.length - this.tagLength; - var result; - if (dst) { - if (dst.length !== resultLength) { - throw new Error("ChaCha20Poly1305: incorrect destination length"); - } - result = dst; - } else { - result = new Uint8Array(resultLength); - } - chacha_1.streamXOR(this._key, counter, sealed.subarray(0, sealed.length - this.tagLength), result, 4); - wipe_1.wipe(counter); - return result; - }; - ChaCha20Poly13052.prototype.clean = function() { - wipe_1.wipe(this._key); - return this; - }; - ChaCha20Poly13052.prototype._authenticate = function(tagOut, authKey, ciphertext, associatedData) { - var h5 = new poly1305_1.Poly1305(authKey); - if (associatedData) { - h5.update(associatedData); - if (associatedData.length % 16 > 0) { - h5.update(ZEROS.subarray(associatedData.length % 16)); - } - } - h5.update(ciphertext); - if (ciphertext.length % 16 > 0) { - h5.update(ZEROS.subarray(ciphertext.length % 16)); - } - var length2 = new Uint8Array(8); - if (associatedData) { - binary_1.writeUint64LE(associatedData.length, length2); - } - h5.update(length2); - binary_1.writeUint64LE(ciphertext.length, length2); - h5.update(length2); - var tag = h5.digest(); - for (var i2 = 0; i2 < tag.length; i2++) { - tagOut[i2] = tag[i2]; - } - h5.clean(); - wipe_1.wipe(tag); - wipe_1.wipe(length2); - }; - return ChaCha20Poly13052; - }() - ); - exports2.ChaCha20Poly1305 = ChaCha20Poly1305; - } -}); - -// node_modules/@stablelib/hash/lib/hash.js -var require_hash2 = __commonJS({ - "node_modules/@stablelib/hash/lib/hash.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - function isSerializableHash(h5) { - return typeof h5.saveState !== "undefined" && typeof h5.restoreState !== "undefined" && typeof h5.cleanSavedState !== "undefined"; - } - exports2.isSerializableHash = isSerializableHash; - } -}); - -// node_modules/@stablelib/hmac/lib/hmac.js -var require_hmac = __commonJS({ - "node_modules/@stablelib/hmac/lib/hmac.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var hash_1 = require_hash2(); - var constant_time_1 = require_constant_time(); - var wipe_1 = require_wipe(); - var HMAC = ( - /** @class */ - function() { - function HMAC2(hash, key) { - this._finished = false; - this._inner = new hash(); - this._outer = new hash(); - this.blockSize = this._outer.blockSize; - this.digestLength = this._outer.digestLength; - var pad = new Uint8Array(this.blockSize); - if (key.length > this.blockSize) { - this._inner.update(key).finish(pad).clean(); - } else { - pad.set(key); - } - for (var i2 = 0; i2 < pad.length; i2++) { - pad[i2] ^= 54; - } - this._inner.update(pad); - for (var i2 = 0; i2 < pad.length; i2++) { - pad[i2] ^= 54 ^ 92; - } - this._outer.update(pad); - if (hash_1.isSerializableHash(this._inner) && hash_1.isSerializableHash(this._outer)) { - this._innerKeyedState = this._inner.saveState(); - this._outerKeyedState = this._outer.saveState(); - } - wipe_1.wipe(pad); - } - HMAC2.prototype.reset = function() { - if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { - throw new Error("hmac: can't reset() because hash doesn't implement restoreState()"); - } - this._inner.restoreState(this._innerKeyedState); - this._outer.restoreState(this._outerKeyedState); - this._finished = false; - return this; - }; - HMAC2.prototype.clean = function() { - if (hash_1.isSerializableHash(this._inner)) { - this._inner.cleanSavedState(this._innerKeyedState); - } - if (hash_1.isSerializableHash(this._outer)) { - this._outer.cleanSavedState(this._outerKeyedState); - } - this._inner.clean(); - this._outer.clean(); - }; - HMAC2.prototype.update = function(data) { - this._inner.update(data); - return this; - }; - HMAC2.prototype.finish = function(out) { - if (this._finished) { - this._outer.finish(out); - return this; - } - this._inner.finish(out); - this._outer.update(out.subarray(0, this.digestLength)).finish(out); - this._finished = true; - return this; - }; - HMAC2.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - HMAC2.prototype.saveState = function() { - if (!hash_1.isSerializableHash(this._inner)) { - throw new Error("hmac: can't saveState() because hash doesn't implement it"); - } - return this._inner.saveState(); - }; - HMAC2.prototype.restoreState = function(savedState) { - if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { - throw new Error("hmac: can't restoreState() because hash doesn't implement it"); - } - this._inner.restoreState(savedState); - this._outer.restoreState(this._outerKeyedState); - this._finished = false; - return this; - }; - HMAC2.prototype.cleanSavedState = function(savedState) { - if (!hash_1.isSerializableHash(this._inner)) { - throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it"); - } - this._inner.cleanSavedState(savedState); - }; - return HMAC2; - }() - ); - exports2.HMAC = HMAC; - function hmac(hash, key, data) { - var h5 = new HMAC(hash, key); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.hmac = hmac; - exports2.equal = constant_time_1.equal; - } -}); - -// node_modules/@stablelib/hkdf/lib/hkdf.js -var require_hkdf = __commonJS({ - "node_modules/@stablelib/hkdf/lib/hkdf.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var hmac_1 = require_hmac(); - var wipe_1 = require_wipe(); - var HKDF = ( - /** @class */ - function() { - function HKDF2(hash, key, salt, info) { - if (salt === void 0) { - salt = new Uint8Array(0); - } - this._counter = new Uint8Array(1); - this._hash = hash; - this._info = info; - var okm = hmac_1.hmac(this._hash, salt, key); - this._hmac = new hmac_1.HMAC(hash, okm); - this._buffer = new Uint8Array(this._hmac.digestLength); - this._bufpos = this._buffer.length; - } - HKDF2.prototype._fillBuffer = function() { - this._counter[0]++; - var ctr = this._counter[0]; - if (ctr === 0) { - throw new Error("hkdf: cannot expand more"); - } - this._hmac.reset(); - if (ctr > 1) { - this._hmac.update(this._buffer); - } - if (this._info) { - this._hmac.update(this._info); - } - this._hmac.update(this._counter); - this._hmac.finish(this._buffer); - this._bufpos = 0; - }; - HKDF2.prototype.expand = function(length2) { - var out = new Uint8Array(length2); - for (var i2 = 0; i2 < out.length; i2++) { - if (this._bufpos === this._buffer.length) { - this._fillBuffer(); - } - out[i2] = this._buffer[this._bufpos++]; - } - return out; - }; - HKDF2.prototype.clean = function() { - this._hmac.clean(); - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._counter); - this._bufpos = 0; - }; - return HKDF2; - }() - ); - exports2.HKDF = HKDF; - } -}); - -// node_modules/@stablelib/sha256/lib/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@stablelib/sha256/lib/sha256.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var binary_1 = require_binary2(); - var wipe_1 = require_wipe(); - exports2.DIGEST_LENGTH = 32; - exports2.BLOCK_SIZE = 64; - var SHA256 = ( - /** @class */ - function() { - function SHA2562() { - this.digestLength = exports2.DIGEST_LENGTH; - this.blockSize = exports2.BLOCK_SIZE; - this._state = new Int32Array(8); - this._temp = new Int32Array(64); - this._buffer = new Uint8Array(128); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - this.reset(); - } - SHA2562.prototype._initState = function() { - this._state[0] = 1779033703; - this._state[1] = 3144134277; - this._state[2] = 1013904242; - this._state[3] = 2773480762; - this._state[4] = 1359893119; - this._state[5] = 2600822924; - this._state[6] = 528734635; - this._state[7] = 1541459225; - }; - SHA2562.prototype.reset = function() { - this._initState(); - this._bufferLength = 0; - this._bytesHashed = 0; - this._finished = false; - return this; - }; - SHA2562.prototype.clean = function() { - wipe_1.wipe(this._buffer); - wipe_1.wipe(this._temp); - this.reset(); - }; - SHA2562.prototype.update = function(data, dataLength) { - if (dataLength === void 0) { - dataLength = data.length; - } - if (this._finished) { - throw new Error("SHA256: can't update because hash was finished."); - } - var dataPos = 0; - this._bytesHashed += dataLength; - if (this._bufferLength > 0) { - while (this._bufferLength < this.blockSize && dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - if (this._bufferLength === this.blockSize) { - hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize); - this._bufferLength = 0; - } - } - if (dataLength >= this.blockSize) { - dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength); - dataLength %= this.blockSize; - } - while (dataLength > 0) { - this._buffer[this._bufferLength++] = data[dataPos++]; - dataLength--; - } - return this; - }; - SHA2562.prototype.finish = function(out) { - if (!this._finished) { - var bytesHashed = this._bytesHashed; - var left = this._bufferLength; - var bitLenHi = bytesHashed / 536870912 | 0; - var bitLenLo = bytesHashed << 3; - var padLength = bytesHashed % 64 < 56 ? 64 : 128; - this._buffer[left] = 128; - for (var i2 = left + 1; i2 < padLength - 8; i2++) { - this._buffer[i2] = 0; - } - binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); - binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); - hashBlocks(this._temp, this._state, this._buffer, 0, padLength); - this._finished = true; - } - for (var i2 = 0; i2 < this.digestLength / 4; i2++) { - binary_1.writeUint32BE(this._state[i2], out, i2 * 4); - } - return this; - }; - SHA2562.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - SHA2562.prototype.saveState = function() { - if (this._finished) { - throw new Error("SHA256: cannot save finished state"); - } - return { - state: new Int32Array(this._state), - buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, - bufferLength: this._bufferLength, - bytesHashed: this._bytesHashed - }; - }; - SHA2562.prototype.restoreState = function(savedState) { - this._state.set(savedState.state); - this._bufferLength = savedState.bufferLength; - if (savedState.buffer) { - this._buffer.set(savedState.buffer); - } - this._bytesHashed = savedState.bytesHashed; - this._finished = false; - return this; - }; - SHA2562.prototype.cleanSavedState = function(savedState) { - wipe_1.wipe(savedState.state); - if (savedState.buffer) { - wipe_1.wipe(savedState.buffer); - } - savedState.bufferLength = 0; - savedState.bytesHashed = 0; - }; - return SHA2562; - }() - ); - exports2.SHA256 = SHA256; - var K2 = new Int32Array([ - 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 - ]); - function hashBlocks(w4, v2, p3, pos, len) { - while (len >= 64) { - var a3 = v2[0]; - var b4 = v2[1]; - var c4 = v2[2]; - var d3 = v2[3]; - var e2 = v2[4]; - var f4 = v2[5]; - var g3 = v2[6]; - var h5 = v2[7]; - for (var i2 = 0; i2 < 16; i2++) { - var j2 = pos + i2 * 4; - w4[i2] = binary_1.readUint32BE(p3, j2); - } - for (var i2 = 16; i2 < 64; i2++) { - var u3 = w4[i2 - 2]; - var t1 = (u3 >>> 17 | u3 << 32 - 17) ^ (u3 >>> 19 | u3 << 32 - 19) ^ u3 >>> 10; - u3 = w4[i2 - 15]; - var t2 = (u3 >>> 7 | u3 << 32 - 7) ^ (u3 >>> 18 | u3 << 32 - 18) ^ u3 >>> 3; - w4[i2] = (t1 + w4[i2 - 7] | 0) + (t2 + w4[i2 - 16] | 0); - } - for (var i2 = 0; i2 < 64; i2++) { - var t1 = (((e2 >>> 6 | e2 << 32 - 6) ^ (e2 >>> 11 | e2 << 32 - 11) ^ (e2 >>> 25 | e2 << 32 - 25)) + (e2 & f4 ^ ~e2 & g3) | 0) + (h5 + (K2[i2] + w4[i2] | 0) | 0) | 0; - var t2 = ((a3 >>> 2 | a3 << 32 - 2) ^ (a3 >>> 13 | a3 << 32 - 13) ^ (a3 >>> 22 | a3 << 32 - 22)) + (a3 & b4 ^ a3 & c4 ^ b4 & c4) | 0; - h5 = g3; - g3 = f4; - f4 = e2; - e2 = d3 + t1 | 0; - d3 = c4; - c4 = b4; - b4 = a3; - a3 = t1 + t2 | 0; - } - v2[0] += a3; - v2[1] += b4; - v2[2] += c4; - v2[3] += d3; - v2[4] += e2; - v2[5] += f4; - v2[6] += g3; - v2[7] += h5; - pos += 64; - len -= 64; - } - return pos; - } - function hash(data) { - var h5 = new SHA256(); - h5.update(data); - var digest2 = h5.digest(); - h5.clean(); - return digest2; - } - exports2.hash = hash; - } -}); - -// node_modules/@stablelib/x25519/lib/x25519.js -var require_x25519 = __commonJS({ - "node_modules/@stablelib/x25519/lib/x25519.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.sharedKey = exports2.generateKeyPair = exports2.generateKeyPairFromSeed = exports2.scalarMultBase = exports2.scalarMult = exports2.SHARED_KEY_LENGTH = exports2.SECRET_KEY_LENGTH = exports2.PUBLIC_KEY_LENGTH = void 0; - var random_1 = require_random(); - var wipe_1 = require_wipe(); - exports2.PUBLIC_KEY_LENGTH = 32; - exports2.SECRET_KEY_LENGTH = 32; - exports2.SHARED_KEY_LENGTH = 32; - function gf(init) { - const r = new Float64Array(16); - if (init) { - for (let i2 = 0; i2 < init.length; i2++) { - r[i2] = init[i2]; - } - } - return r; - } - var _9 = new Uint8Array(32); - _9[0] = 9; - var _121665 = gf([56129, 1]); - function car25519(o2) { - let c4 = 1; - for (let i2 = 0; i2 < 16; i2++) { - let v2 = o2[i2] + c4 + 65535; - c4 = Math.floor(v2 / 65536); - o2[i2] = v2 - c4 * 65536; - } - o2[0] += c4 - 1 + 37 * (c4 - 1); - } - function sel25519(p3, q2, b4) { - const c4 = ~(b4 - 1); - for (let i2 = 0; i2 < 16; i2++) { - const t = c4 & (p3[i2] ^ q2[i2]); - p3[i2] ^= t; - q2[i2] ^= t; - } - } - function pack25519(o2, n3) { - const m3 = gf(); - const t = gf(); - for (let i2 = 0; i2 < 16; i2++) { - t[i2] = n3[i2]; - } - car25519(t); - car25519(t); - car25519(t); - for (let j2 = 0; j2 < 2; j2++) { - m3[0] = t[0] - 65517; - for (let i2 = 1; i2 < 15; i2++) { - m3[i2] = t[i2] - 65535 - (m3[i2 - 1] >> 16 & 1); - m3[i2 - 1] &= 65535; - } - m3[15] = t[15] - 32767 - (m3[14] >> 16 & 1); - const b4 = m3[15] >> 16 & 1; - m3[14] &= 65535; - sel25519(t, m3, 1 - b4); - } - for (let i2 = 0; i2 < 16; i2++) { - o2[2 * i2] = t[i2] & 255; - o2[2 * i2 + 1] = t[i2] >> 8; - } - } - function unpack25519(o2, n3) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = n3[2 * i2] + (n3[2 * i2 + 1] << 8); - } - o2[15] &= 32767; - } - function add(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] + b4[i2]; - } - } - function sub(o2, a3, b4) { - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = a3[i2] - b4[i2]; - } - } - function mul(o2, a3, b4) { - let v2, c4, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b4[0], b1 = b4[1], b22 = b4[2], b32 = b4[3], b42 = b4[4], b5 = b4[5], b6 = b4[6], b7 = b4[7], b8 = b4[8], b9 = b4[9], b10 = b4[10], b11 = b4[11], b12 = b4[12], b13 = b4[13], b14 = b4[14], b15 = b4[15]; - v2 = a3[0]; - t0 += v2 * b0; - t1 += v2 * b1; - t2 += v2 * b22; - t3 += v2 * b32; - t4 += v2 * b42; - t5 += v2 * b5; - t6 += v2 * b6; - t7 += v2 * b7; - t8 += v2 * b8; - t9 += v2 * b9; - t10 += v2 * b10; - t11 += v2 * b11; - t12 += v2 * b12; - t13 += v2 * b13; - t14 += v2 * b14; - t15 += v2 * b15; - v2 = a3[1]; - t1 += v2 * b0; - t2 += v2 * b1; - t3 += v2 * b22; - t4 += v2 * b32; - t5 += v2 * b42; - t6 += v2 * b5; - t7 += v2 * b6; - t8 += v2 * b7; - t9 += v2 * b8; - t10 += v2 * b9; - t11 += v2 * b10; - t12 += v2 * b11; - t13 += v2 * b12; - t14 += v2 * b13; - t15 += v2 * b14; - t16 += v2 * b15; - v2 = a3[2]; - t2 += v2 * b0; - t3 += v2 * b1; - t4 += v2 * b22; - t5 += v2 * b32; - t6 += v2 * b42; - t7 += v2 * b5; - t8 += v2 * b6; - t9 += v2 * b7; - t10 += v2 * b8; - t11 += v2 * b9; - t12 += v2 * b10; - t13 += v2 * b11; - t14 += v2 * b12; - t15 += v2 * b13; - t16 += v2 * b14; - t17 += v2 * b15; - v2 = a3[3]; - t3 += v2 * b0; - t4 += v2 * b1; - t5 += v2 * b22; - t6 += v2 * b32; - t7 += v2 * b42; - t8 += v2 * b5; - t9 += v2 * b6; - t10 += v2 * b7; - t11 += v2 * b8; - t12 += v2 * b9; - t13 += v2 * b10; - t14 += v2 * b11; - t15 += v2 * b12; - t16 += v2 * b13; - t17 += v2 * b14; - t18 += v2 * b15; - v2 = a3[4]; - t4 += v2 * b0; - t5 += v2 * b1; - t6 += v2 * b22; - t7 += v2 * b32; - t8 += v2 * b42; - t9 += v2 * b5; - t10 += v2 * b6; - t11 += v2 * b7; - t12 += v2 * b8; - t13 += v2 * b9; - t14 += v2 * b10; - t15 += v2 * b11; - t16 += v2 * b12; - t17 += v2 * b13; - t18 += v2 * b14; - t19 += v2 * b15; - v2 = a3[5]; - t5 += v2 * b0; - t6 += v2 * b1; - t7 += v2 * b22; - t8 += v2 * b32; - t9 += v2 * b42; - t10 += v2 * b5; - t11 += v2 * b6; - t12 += v2 * b7; - t13 += v2 * b8; - t14 += v2 * b9; - t15 += v2 * b10; - t16 += v2 * b11; - t17 += v2 * b12; - t18 += v2 * b13; - t19 += v2 * b14; - t20 += v2 * b15; - v2 = a3[6]; - t6 += v2 * b0; - t7 += v2 * b1; - t8 += v2 * b22; - t9 += v2 * b32; - t10 += v2 * b42; - t11 += v2 * b5; - t12 += v2 * b6; - t13 += v2 * b7; - t14 += v2 * b8; - t15 += v2 * b9; - t16 += v2 * b10; - t17 += v2 * b11; - t18 += v2 * b12; - t19 += v2 * b13; - t20 += v2 * b14; - t21 += v2 * b15; - v2 = a3[7]; - t7 += v2 * b0; - t8 += v2 * b1; - t9 += v2 * b22; - t10 += v2 * b32; - t11 += v2 * b42; - t12 += v2 * b5; - t13 += v2 * b6; - t14 += v2 * b7; - t15 += v2 * b8; - t16 += v2 * b9; - t17 += v2 * b10; - t18 += v2 * b11; - t19 += v2 * b12; - t20 += v2 * b13; - t21 += v2 * b14; - t22 += v2 * b15; - v2 = a3[8]; - t8 += v2 * b0; - t9 += v2 * b1; - t10 += v2 * b22; - t11 += v2 * b32; - t12 += v2 * b42; - t13 += v2 * b5; - t14 += v2 * b6; - t15 += v2 * b7; - t16 += v2 * b8; - t17 += v2 * b9; - t18 += v2 * b10; - t19 += v2 * b11; - t20 += v2 * b12; - t21 += v2 * b13; - t22 += v2 * b14; - t23 += v2 * b15; - v2 = a3[9]; - t9 += v2 * b0; - t10 += v2 * b1; - t11 += v2 * b22; - t12 += v2 * b32; - t13 += v2 * b42; - t14 += v2 * b5; - t15 += v2 * b6; - t16 += v2 * b7; - t17 += v2 * b8; - t18 += v2 * b9; - t19 += v2 * b10; - t20 += v2 * b11; - t21 += v2 * b12; - t22 += v2 * b13; - t23 += v2 * b14; - t24 += v2 * b15; - v2 = a3[10]; - t10 += v2 * b0; - t11 += v2 * b1; - t12 += v2 * b22; - t13 += v2 * b32; - t14 += v2 * b42; - t15 += v2 * b5; - t16 += v2 * b6; - t17 += v2 * b7; - t18 += v2 * b8; - t19 += v2 * b9; - t20 += v2 * b10; - t21 += v2 * b11; - t22 += v2 * b12; - t23 += v2 * b13; - t24 += v2 * b14; - t25 += v2 * b15; - v2 = a3[11]; - t11 += v2 * b0; - t12 += v2 * b1; - t13 += v2 * b22; - t14 += v2 * b32; - t15 += v2 * b42; - t16 += v2 * b5; - t17 += v2 * b6; - t18 += v2 * b7; - t19 += v2 * b8; - t20 += v2 * b9; - t21 += v2 * b10; - t22 += v2 * b11; - t23 += v2 * b12; - t24 += v2 * b13; - t25 += v2 * b14; - t26 += v2 * b15; - v2 = a3[12]; - t12 += v2 * b0; - t13 += v2 * b1; - t14 += v2 * b22; - t15 += v2 * b32; - t16 += v2 * b42; - t17 += v2 * b5; - t18 += v2 * b6; - t19 += v2 * b7; - t20 += v2 * b8; - t21 += v2 * b9; - t22 += v2 * b10; - t23 += v2 * b11; - t24 += v2 * b12; - t25 += v2 * b13; - t26 += v2 * b14; - t27 += v2 * b15; - v2 = a3[13]; - t13 += v2 * b0; - t14 += v2 * b1; - t15 += v2 * b22; - t16 += v2 * b32; - t17 += v2 * b42; - t18 += v2 * b5; - t19 += v2 * b6; - t20 += v2 * b7; - t21 += v2 * b8; - t22 += v2 * b9; - t23 += v2 * b10; - t24 += v2 * b11; - t25 += v2 * b12; - t26 += v2 * b13; - t27 += v2 * b14; - t28 += v2 * b15; - v2 = a3[14]; - t14 += v2 * b0; - t15 += v2 * b1; - t16 += v2 * b22; - t17 += v2 * b32; - t18 += v2 * b42; - t19 += v2 * b5; - t20 += v2 * b6; - t21 += v2 * b7; - t22 += v2 * b8; - t23 += v2 * b9; - t24 += v2 * b10; - t25 += v2 * b11; - t26 += v2 * b12; - t27 += v2 * b13; - t28 += v2 * b14; - t29 += v2 * b15; - v2 = a3[15]; - t15 += v2 * b0; - t16 += v2 * b1; - t17 += v2 * b22; - t18 += v2 * b32; - t19 += v2 * b42; - t20 += v2 * b5; - t21 += v2 * b6; - t22 += v2 * b7; - t23 += v2 * b8; - t24 += v2 * b9; - t25 += v2 * b10; - t26 += v2 * b11; - t27 += v2 * b12; - t28 += v2 * b13; - t29 += v2 * b14; - t30 += v2 * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - c4 = 1; - v2 = t0 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t0 = v2 - c4 * 65536; - v2 = t1 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t1 = v2 - c4 * 65536; - v2 = t2 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t2 = v2 - c4 * 65536; - v2 = t3 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t3 = v2 - c4 * 65536; - v2 = t4 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t4 = v2 - c4 * 65536; - v2 = t5 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t5 = v2 - c4 * 65536; - v2 = t6 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t6 = v2 - c4 * 65536; - v2 = t7 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t7 = v2 - c4 * 65536; - v2 = t8 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t8 = v2 - c4 * 65536; - v2 = t9 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t9 = v2 - c4 * 65536; - v2 = t10 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t10 = v2 - c4 * 65536; - v2 = t11 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t11 = v2 - c4 * 65536; - v2 = t12 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t12 = v2 - c4 * 65536; - v2 = t13 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t13 = v2 - c4 * 65536; - v2 = t14 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t14 = v2 - c4 * 65536; - v2 = t15 + c4 + 65535; - c4 = Math.floor(v2 / 65536); - t15 = v2 - c4 * 65536; - t0 += c4 - 1 + 37 * (c4 - 1); - o2[0] = t0; - o2[1] = t1; - o2[2] = t2; - o2[3] = t3; - o2[4] = t4; - o2[5] = t5; - o2[6] = t6; - o2[7] = t7; - o2[8] = t8; - o2[9] = t9; - o2[10] = t10; - o2[11] = t11; - o2[12] = t12; - o2[13] = t13; - o2[14] = t14; - o2[15] = t15; - } - function square(o2, a3) { - mul(o2, a3, a3); - } - function inv25519(o2, inp) { - const c4 = gf(); - for (let i2 = 0; i2 < 16; i2++) { - c4[i2] = inp[i2]; - } - for (let i2 = 253; i2 >= 0; i2--) { - square(c4, c4); - if (i2 !== 2 && i2 !== 4) { - mul(c4, c4, inp); - } - } - for (let i2 = 0; i2 < 16; i2++) { - o2[i2] = c4[i2]; - } - } - function scalarMult(n3, p3) { - const z3 = new Uint8Array(32); - const x3 = new Float64Array(80); - const a3 = gf(), b4 = gf(), c4 = gf(), d3 = gf(), e2 = gf(), f4 = gf(); - for (let i2 = 0; i2 < 31; i2++) { - z3[i2] = n3[i2]; - } - z3[31] = n3[31] & 127 | 64; - z3[0] &= 248; - unpack25519(x3, p3); - for (let i2 = 0; i2 < 16; i2++) { - b4[i2] = x3[i2]; - } - a3[0] = d3[0] = 1; - for (let i2 = 254; i2 >= 0; --i2) { - const r = z3[i2 >>> 3] >>> (i2 & 7) & 1; - sel25519(a3, b4, r); - sel25519(c4, d3, r); - add(e2, a3, c4); - sub(a3, a3, c4); - add(c4, b4, d3); - sub(b4, b4, d3); - square(d3, e2); - square(f4, a3); - mul(a3, c4, a3); - mul(c4, b4, e2); - add(e2, a3, c4); - sub(a3, a3, c4); - square(b4, a3); - sub(c4, d3, f4); - mul(a3, c4, _121665); - add(a3, a3, d3); - mul(c4, c4, a3); - mul(a3, d3, f4); - mul(d3, b4, x3); - square(b4, e2); - sel25519(a3, b4, r); - sel25519(c4, d3, r); - } - for (let i2 = 0; i2 < 16; i2++) { - x3[i2 + 16] = a3[i2]; - x3[i2 + 32] = c4[i2]; - x3[i2 + 48] = b4[i2]; - x3[i2 + 64] = d3[i2]; - } - const x32 = x3.subarray(32); - const x16 = x3.subarray(16); - inv25519(x32, x32); - mul(x16, x16, x32); - const q2 = new Uint8Array(32); - pack25519(q2, x16); - return q2; - } - exports2.scalarMult = scalarMult; - function scalarMultBase(n3) { - return scalarMult(n3, _9); - } - exports2.scalarMultBase = scalarMultBase; - function generateKeyPairFromSeed2(seed) { - if (seed.length !== exports2.SECRET_KEY_LENGTH) { - throw new Error(`x25519: seed must be ${exports2.SECRET_KEY_LENGTH} bytes`); - } - const secretKey = new Uint8Array(seed); - const publicKey = scalarMultBase(secretKey); - return { - publicKey, - secretKey - }; - } - exports2.generateKeyPairFromSeed = generateKeyPairFromSeed2; - function generateKeyPair2(prng) { - const seed = (0, random_1.randomBytes)(32, prng); - const result = generateKeyPairFromSeed2(seed); - (0, wipe_1.wipe)(seed); - return result; - } - exports2.generateKeyPair = generateKeyPair2; - function sharedKey(mySecretKey, theirPublicKey, rejectZero = false) { - if (mySecretKey.length !== exports2.PUBLIC_KEY_LENGTH) { - throw new Error("X25519: incorrect secret key length"); - } - if (theirPublicKey.length !== exports2.PUBLIC_KEY_LENGTH) { - throw new Error("X25519: incorrect public key length"); - } - const result = scalarMult(mySecretKey, theirPublicKey); - if (rejectZero) { - let zeros = 0; - for (let i2 = 0; i2 < result.length; i2++) { - zeros |= result[i2]; - } - if (zeros === 0) { - throw new Error("X25519: invalid shared key"); - } - } - return result; - } - exports2.sharedKey = sharedKey; - } -}); - -// node_modules/uint8arrays/esm/src/compare.js -function compare(a3, b4) { - for (let i2 = 0; i2 < a3.byteLength; i2++) { - if (a3[i2] < b4[i2]) { - return -1; - } - if (a3[i2] > b4[i2]) { - return 1; - } - } - if (a3.byteLength > b4.byteLength) { - return 1; - } - if (a3.byteLength < b4.byteLength) { - return -1; - } - return 0; -} -var init_compare = __esm({ - "node_modules/uint8arrays/esm/src/compare.js"() { - init_shim(); - } -}); - -// node_modules/uint8arrays/esm/src/equals.js -function equals3(a3, b4) { - if (a3 === b4) { - return true; - } - if (a3.byteLength !== b4.byteLength) { - return false; - } - for (let i2 = 0; i2 < a3.byteLength; i2++) { - if (a3[i2] !== b4[i2]) { - return false; - } - } - return true; -} -var init_equals = __esm({ - "node_modules/uint8arrays/esm/src/equals.js"() { - init_shim(); - } -}); - -// node_modules/uint8arrays/esm/src/xor.js -function xor(a3, b4) { - if (a3.length !== b4.length) { - throw new Error("Inputs should have the same length"); - } - const result = allocUnsafe(a3.length); - for (let i2 = 0; i2 < a3.length; i2++) { - result[i2] = a3[i2] ^ b4[i2]; - } - return asUint8Array(result); -} -var init_xor = __esm({ - "node_modules/uint8arrays/esm/src/xor.js"() { - init_shim(); - init_alloc(); - init_as_uint8array(); - } -}); - -// node_modules/uint8arrays/esm/src/index.js -var src_exports = {}; -__export(src_exports, { - compare: () => compare, - concat: () => concat, - equals: () => equals3, - fromString: () => fromString2, - toString: () => toString2, - xor: () => xor -}); -var init_src2 = __esm({ - "node_modules/uint8arrays/esm/src/index.js"() { - init_shim(); - init_compare(); - init_concat(); - init_equals(); - init_from_string(); - init_to_string(); - init_xor(); - } -}); - -// node_modules/@walletconnect/relay-api/dist/index.es.js -var index_es_exports3 = {}; -__export(index_es_exports3, { - RELAY_JSONRPC: () => C2, - isPublishMethod: () => c3, - isPublishParams: () => h3, - isPublishRequest: () => P, - isSubscribeMethod: () => b2, - isSubscribeParams: () => a, - isSubscribeRequest: () => R, - isSubscriptionMethod: () => m2, - isSubscriptionParams: () => d2, - isSubscriptionRequest: () => S2, - isUnsubscribeMethod: () => o, - isUnsubscribeParams: () => p2, - isUnsubscribeRequest: () => _3, - parsePublishRequest: () => q, - parseSubscribeRequest: () => g2, - parseSubscriptionRequest: () => k3, - parseUnsubscribeRequest: () => E3 -}); -function e(s2, r, i2 = "string") { - if (!s2[r] || typeof s2[r] !== i2) - throw new Error(`Missing or invalid "${r}" param`); -} -function l3(s2, r) { - let i2 = true; - return r.forEach((t) => { - t in s2 || (i2 = false); - }), i2; -} -function f2(s2, r) { - return Array.isArray(s2) ? s2.length === r : Object.keys(s2).length === r; -} -function w2(s2, r) { - return Array.isArray(s2) ? s2.length >= r : Object.keys(s2).length >= r; -} -function u(s2, r, i2) { - return (i2.length ? w2(s2, r.length) : f2(s2, r.length)) ? l3(s2, r) : false; -} -function n2(s2, r, i2 = "_") { - const t = s2.split(i2); - return t[t.length - 1].trim().toLowerCase() === r.trim().toLowerCase(); -} -function R(s2) { - return b2(s2.method) && a(s2.params); -} -function b2(s2) { - return n2(s2, "subscribe"); -} -function a(s2) { - return u(s2, ["topic"], []); -} -function P(s2) { - return c3(s2.method) && h3(s2.params); -} -function c3(s2) { - return n2(s2, "publish"); -} -function h3(s2) { - return u(s2, ["message", "topic", "ttl"], ["prompt", "tag"]); -} -function _3(s2) { - return o(s2.method) && p2(s2.params); -} -function o(s2) { - return n2(s2, "unsubscribe"); -} -function p2(s2) { - return u(s2, ["id", "topic"], []); -} -function S2(s2) { - return m2(s2.method) && d2(s2.params); -} -function m2(s2) { - return n2(s2, "subscription"); -} -function d2(s2) { - return u(s2, ["id", "data"], []); -} -function g2(s2) { - if (!b2(s2.method)) - throw new Error("JSON-RPC Request has invalid subscribe method"); - if (!a(s2.params)) - throw new Error("JSON-RPC Request has invalid subscribe params"); - const r = s2.params; - return e(r, "topic"), r; -} -function q(s2) { - if (!c3(s2.method)) - throw new Error("JSON-RPC Request has invalid publish method"); - if (!h3(s2.params)) - throw new Error("JSON-RPC Request has invalid publish params"); - const r = s2.params; - return e(r, "topic"), e(r, "message"), e(r, "ttl", "number"), r; -} -function E3(s2) { - if (!o(s2.method)) - throw new Error("JSON-RPC Request has invalid unsubscribe method"); - if (!p2(s2.params)) - throw new Error("JSON-RPC Request has invalid unsubscribe params"); - const r = s2.params; - return e(r, "id"), r; -} -function k3(s2) { - if (!m2(s2.method)) - throw new Error("JSON-RPC Request has invalid subscription method"); - if (!d2(s2.params)) - throw new Error("JSON-RPC Request has invalid subscription params"); - const r = s2.params; - return e(r, "id"), e(r, "data"), r; -} -var C2; -var init_index_es3 = __esm({ - "node_modules/@walletconnect/relay-api/dist/index.es.js"() { - init_shim(); - C2 = { waku: { publish: "waku_publish", batchPublish: "waku_batchPublish", subscribe: "waku_subscribe", batchSubscribe: "waku_batchSubscribe", subscription: "waku_subscription", unsubscribe: "waku_unsubscribe", batchUnsubscribe: "waku_batchUnsubscribe", batchFetchMessages: "waku_batchFetchMessages" }, irn: { publish: "irn_publish", batchPublish: "irn_batchPublish", subscribe: "irn_subscribe", batchSubscribe: "irn_batchSubscribe", subscription: "irn_subscription", unsubscribe: "irn_unsubscribe", batchUnsubscribe: "irn_batchUnsubscribe", batchFetchMessages: "irn_batchFetchMessages" }, iridium: { publish: "iridium_publish", batchPublish: "iridium_batchPublish", subscribe: "iridium_subscribe", batchSubscribe: "iridium_batchSubscribe", subscription: "iridium_subscription", unsubscribe: "iridium_unsubscribe", batchUnsubscribe: "iridium_batchUnsubscribe", batchFetchMessages: "iridium_batchFetchMessages" } }; - } -}); - -// node_modules/@walletconnect/utils/dist/index.cjs.js -var require_index_cjs2 = __commonJS({ - "node_modules/@walletconnect/utils/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var Ro = require_detect_browser(); - var tr = require_cjs(); - var er = require_cjs3(); - var Co = require_cjs4(); - var Oo = require_query_string(); - var fn = require_chacha20poly1305(); - var Po = require_hkdf(); - var on = require_random(); - var ci = require_sha256(); - var To = require_x25519(); - var Rt = (init_src2(), __toCommonJS(src_exports)); - var Fo = (init_index_es3(), __toCommonJS(index_es_exports3)); - function sn(e2) { - if (e2 && e2.__esModule) - return e2; - var t = /* @__PURE__ */ Object.create(null); - return e2 && Object.keys(e2).forEach(function(r) { - if (r !== "default") { - var i2 = Object.getOwnPropertyDescriptor(e2, r); - Object.defineProperty(t, r, i2.get ? i2 : { enumerable: true, get: function() { - return e2[r]; - } }); - } - }), t.default = e2, Object.freeze(t); - } - var Ir = sn(Oo); - var an = sn(To); - var _r = ":"; - function un(e2) { - const [t, r] = e2.split(_r); - return { namespace: t, reference: r }; - } - function hn(e2) { - const { namespace: t, reference: r } = e2; - return [t, r].join(_r); - } - function li(e2) { - const [t, r, i2] = e2.split(_r); - return { namespace: t, reference: r, address: i2 }; - } - function cn(e2) { - const { namespace: t, reference: r, address: i2 } = e2; - return [t, r, i2].join(_r); - } - function di(e2, t) { - const r = []; - return e2.forEach((i2) => { - const n3 = t(i2); - r.includes(n3) || r.push(n3); - }), r; - } - function ln(e2) { - const { address: t } = li(e2); - return t; - } - function dn(e2) { - const { namespace: t, reference: r } = li(e2); - return hn({ namespace: t, reference: r }); - } - function Do(e2, t) { - const { namespace: r, reference: i2 } = un(t); - return cn({ namespace: r, reference: i2, address: e2 }); - } - function Uo(e2) { - return di(e2, ln); - } - function pn(e2) { - return di(e2, dn); - } - function ko(e2, t = []) { - const r = []; - return Object.keys(e2).forEach((i2) => { - if (t.length && !t.includes(i2)) - return; - const n3 = e2[i2]; - r.push(...n3.accounts); - }), r; - } - function qo(e2, t = []) { - const r = []; - return Object.keys(e2).forEach((i2) => { - if (t.length && !t.includes(i2)) - return; - const n3 = e2[i2]; - r.push(...pn(n3.accounts)); - }), r; - } - function Ko(e2, t = []) { - const r = []; - return Object.keys(e2).forEach((i2) => { - if (t.length && !t.includes(i2)) - return; - const n3 = e2[i2]; - r.push(...Br(i2, n3)); - }), r; - } - function Br(e2, t) { - return e2.includes(":") ? [e2] : t.chains || []; - } - var Ho = Object.defineProperty; - var vn = Object.getOwnPropertySymbols; - var Lo = Object.prototype.hasOwnProperty; - var zo = Object.prototype.propertyIsEnumerable; - var gn = (e2, t, r) => t in e2 ? Ho(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var mn = (e2, t) => { - for (var r in t || (t = {})) - Lo.call(t, r) && gn(e2, r, t[r]); - if (vn) - for (var r of vn(t)) - zo.call(t, r) && gn(e2, r, t[r]); - return e2; - }; - var An = "ReactNative"; - var Kt = { reactNative: "react-native", node: "node", browser: "browser", unknown: "unknown" }; - var Rr = " "; - var jo = ":"; - var bn = "/"; - var pi = 2; - var Vo = 1e3; - var yn = "js"; - function vi() { - return typeof import_process.default < "u" && typeof import_process.default.versions < "u" && typeof import_process.default.versions.node < "u"; - } - function rr() { - return !er.getDocument() && !!er.getNavigator() && navigator.product === An; - } - function vr() { - return !vi() && !!er.getNavigator() && !!er.getDocument(); - } - function Ge() { - return rr() ? Kt.reactNative : vi() ? Kt.node : vr() ? Kt.browser : Kt.unknown; - } - function Qo() { - var e2; - try { - return rr() && typeof global < "u" && typeof (global == null ? void 0 : global.Application) < "u" ? (e2 = global.Application) == null ? void 0 : e2.applicationId : void 0; - } catch { - return; - } - } - function wn(e2, t) { - let r = Ir.parse(e2); - return r = mn(mn({}, r), t), e2 = Ir.stringify(r), e2; - } - function Jo() { - return Co.getWindowMetadata() || { name: "", description: "", url: "", icons: [""] }; - } - function Yo(e2, t) { - var r; - const i2 = Ge(), n3 = { protocol: e2, version: t, env: i2 }; - return i2 === "browser" && (n3.host = ((r = er.getLocation()) == null ? void 0 : r.host) || "unknown"), n3; - } - function xn() { - if (Ge() === Kt.reactNative && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u") { - const { OS: r, Version: i2 } = global.Platform; - return [r, i2].join("-"); - } - const e2 = Ro.detect(); - if (e2 === null) - return "unknown"; - const t = e2.os ? e2.os.replace(" ", "").toLowerCase() : "unknown"; - return e2.type === "browser" ? [t, e2.name, e2.version].join("-") : [t, e2.version].join("-"); - } - function Mn() { - var e2; - const t = Ge(); - return t === Kt.browser ? [t, ((e2 = er.getLocation()) == null ? void 0 : e2.host) || "unknown"].join(":") : t; - } - function En(e2, t, r) { - const i2 = xn(), n3 = Mn(); - return [[e2, t].join("-"), [yn, r].join("-"), i2, n3].join("/"); - } - function Go({ protocol: e2, version: t, relayUrl: r, sdkVersion: i2, auth: n3, projectId: o2, useOnCloseEvent: h5, bundleId: p3 }) { - const b4 = r.split("?"), g3 = En(e2, t, i2), w4 = { auth: n3, ua: g3, projectId: o2, useOnCloseEvent: h5 || void 0, origin: p3 || void 0 }, y4 = wn(b4[1] || "", w4); - return b4[0] + "?" + y4; - } - function Wo(e2) { - let t = (e2.match(/^[^:]+(?=:\/\/)/gi) || [])[0]; - const r = typeof t < "u" ? e2.split("://")[1] : e2; - return t = t === "wss" ? "https" : "http", [t, r].join("://"); - } - function Xo(e2, t, r) { - if (!e2[t] || typeof e2[t] !== r) - throw new Error(`Missing or invalid "${t}" param`); - } - function Sn(e2, t = pi) { - return Nn(e2.split(bn), t); - } - function Zo(e2) { - return Sn(e2).join(Rr); - } - function Ie(e2, t) { - return e2.filter((r) => t.includes(r)).length === e2.length; - } - function Nn(e2, t = pi) { - return e2.slice(Math.max(e2.length - t, 0)); - } - function $o(e2) { - return Object.fromEntries(e2.entries()); - } - function ts(e2) { - return new Map(Object.entries(e2)); - } - function es(e2, t) { - const r = {}; - return Object.keys(e2).forEach((i2) => { - r[i2] = t(e2[i2]); - }), r; - } - var rs = (e2) => e2; - function In(e2) { - return e2.trim().replace(/^\w/, (t) => t.toUpperCase()); - } - function is(e2) { - return e2.split(Rr).map((t) => In(t)).join(Rr); - } - function ns(e2 = tr.FIVE_MINUTES, t) { - const r = tr.toMiliseconds(e2 || tr.FIVE_MINUTES); - let i2, n3, o2; - return { resolve: (h5) => { - o2 && i2 && (clearTimeout(o2), i2(h5)); - }, reject: (h5) => { - o2 && n3 && (clearTimeout(o2), n3(h5)); - }, done: () => new Promise((h5, p3) => { - o2 = setTimeout(() => { - p3(new Error(t)); - }, r), i2 = h5, n3 = p3; - }) }; - } - function fs(e2, t, r) { - return new Promise(async (i2, n3) => { - const o2 = setTimeout(() => n3(new Error(r)), t); - try { - const h5 = await e2; - i2(h5); - } catch (h5) { - n3(h5); - } - clearTimeout(o2); - }); - } - function gi(e2, t) { - if (typeof t == "string" && t.startsWith(`${e2}:`)) - return t; - if (e2.toLowerCase() === "topic") { - if (typeof t != "string") - throw new Error('Value must be "string" for expirer target type: topic'); - return `topic:${t}`; - } else if (e2.toLowerCase() === "id") { - if (typeof t != "number") - throw new Error('Value must be "number" for expirer target type: id'); - return `id:${t}`; - } - throw new Error(`Unknown expirer target type: ${e2}`); - } - function os(e2) { - return gi("topic", e2); - } - function ss(e2) { - return gi("id", e2); - } - function as(e2) { - const [t, r] = e2.split(":"), i2 = { id: void 0, topic: void 0 }; - if (t === "topic" && typeof r == "string") - i2.topic = r; - else if (t === "id" && Number.isInteger(Number(r))) - i2.id = Number(r); - else - throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`); - return i2; - } - function us(e2, t) { - return tr.fromMiliseconds((t || Date.now()) + tr.toMiliseconds(e2)); - } - function hs(e2) { - return Date.now() >= tr.toMiliseconds(e2); - } - function cs(e2, t) { - return `${e2}${t ? `:${t}` : ""}`; - } - function ge(e2 = [], t = []) { - return [.../* @__PURE__ */ new Set([...e2, ...t])]; - } - async function ls2({ id: e2, topic: t, wcDeepLink: r }) { - try { - if (!r) - return; - const i2 = typeof r == "string" ? JSON.parse(r) : r; - let n3 = i2?.href; - if (typeof n3 != "string") - return; - n3.endsWith("/") && (n3 = n3.slice(0, -1)); - const o2 = `${n3}/wc?requestId=${e2}&sessionTopic=${t}`, h5 = Ge(); - h5 === Kt.browser ? o2.startsWith("https://") || o2.startsWith("http://") ? window.open(o2, "_blank", "noreferrer noopener") : window.open(o2, "_self", "noreferrer noopener") : h5 === Kt.reactNative && typeof (global == null ? void 0 : global.Linking) < "u" && await global.Linking.openURL(o2); - } catch (i2) { - console.error(i2); - } - } - async function ds(e2, t) { - try { - return await e2.getItem(t) || (vr() ? localStorage.getItem(t) : void 0); - } catch (r) { - console.error(r); - } - } - function mi(e2, t) { - return e2.filter((r) => t.includes(r)); - } - var _n = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; - function ps(e2) { - var t = e2.default; - if (typeof t == "function") { - var r = function() { - return t.apply(this, arguments); - }; - r.prototype = t.prototype; - } else - r = {}; - return Object.defineProperty(r, "__esModule", { value: true }), Object.keys(e2).forEach(function(i2) { - var n3 = Object.getOwnPropertyDescriptor(e2, i2); - Object.defineProperty(r, i2, n3.get ? n3 : { enumerable: true, get: function() { - return e2[i2]; - } }); - }), r; - } - var Bn = { exports: {} }; - (function(e2) { - (function() { - var t = "input is invalid type", r = "finalize already called", i2 = typeof window == "object", n3 = i2 ? window : {}; - n3.JS_SHA3_NO_WINDOW && (i2 = false); - var o2 = !i2 && typeof self == "object", h5 = !n3.JS_SHA3_NO_NODE_JS && typeof import_process.default == "object" && import_process.default.versions && import_process.default.versions.node; - h5 ? n3 = _n : o2 && (n3 = self); - var p3 = !n3.JS_SHA3_NO_COMMON_JS && true && e2.exports, b4 = !n3.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer < "u", g3 = "0123456789abcdef".split(""), w4 = [31, 7936, 2031616, 520093696], y4 = [4, 1024, 262144, 67108864], S4 = [1, 256, 65536, 16777216], I2 = [6, 1536, 393216, 100663296], N10 = [0, 8, 16, 24], R2 = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648], F = [224, 256, 384, 512], U2 = [128, 256], Q = ["hex", "buffer", "arrayBuffer", "array", "digest"], Bt = { 128: 168, 256: 136 }; - (n3.JS_SHA3_NO_NODE_JS || !Array.isArray) && (Array.isArray = function(u3) { - return Object.prototype.toString.call(u3) === "[object Array]"; - }), b4 && (n3.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView) && (ArrayBuffer.isView = function(u3) { - return typeof u3 == "object" && u3.buffer && u3.buffer.constructor === ArrayBuffer; - }); - for (var J = function(u3, E4, _4) { - return function(B2) { - return new s2(u3, E4, u3).update(B2)[_4](); - }; - }, H = function(u3, E4, _4) { - return function(B2, C3) { - return new s2(u3, E4, C3).update(B2)[_4](); - }; - }, L2 = function(u3, E4, _4) { - return function(B2, C3, D2, P2) { - return f4["cshake" + u3].update(B2, C3, D2, P2)[_4](); - }; - }, Tt = function(u3, E4, _4) { - return function(B2, C3, D2, P2) { - return f4["kmac" + u3].update(B2, C3, D2, P2)[_4](); - }; - }, W = function(u3, E4, _4, B2) { - for (var C3 = 0; C3 < Q.length; ++C3) { - var D2 = Q[C3]; - u3[D2] = E4(_4, B2, D2); - } - return u3; - }, Ot = function(u3, E4) { - var _4 = J(u3, E4, "hex"); - return _4.create = function() { - return new s2(u3, E4, u3); - }, _4.update = function(B2) { - return _4.create().update(B2); - }, W(_4, J, u3, E4); - }, Gt = function(u3, E4) { - var _4 = H(u3, E4, "hex"); - return _4.create = function(B2) { - return new s2(u3, E4, B2); - }, _4.update = function(B2, C3) { - return _4.create(C3).update(B2); - }, W(_4, H, u3, E4); - }, Y = function(u3, E4) { - var _4 = Bt[u3], B2 = L2(u3, E4, "hex"); - return B2.create = function(C3, D2, P2) { - return !D2 && !P2 ? f4["shake" + u3].create(C3) : new s2(u3, E4, C3).bytepad([D2, P2], _4); - }, B2.update = function(C3, D2, P2, O3) { - return B2.create(D2, P2, O3).update(C3); - }, W(B2, L2, u3, E4); - }, Wt = function(u3, E4) { - var _4 = Bt[u3], B2 = Tt(u3, E4, "hex"); - return B2.create = function(C3, D2, P2) { - return new v2(u3, E4, D2).bytepad(["KMAC", P2], _4).bytepad([C3], _4); - }, B2.update = function(C3, D2, P2, O3) { - return B2.create(C3, P2, O3).update(D2); - }, W(B2, Tt, u3, E4); - }, A2 = [{ name: "keccak", padding: S4, bits: F, createMethod: Ot }, { name: "sha3", padding: I2, bits: F, createMethod: Ot }, { name: "shake", padding: w4, bits: U2, createMethod: Gt }, { name: "cshake", padding: y4, bits: U2, createMethod: Y }, { name: "kmac", padding: y4, bits: U2, createMethod: Wt }], f4 = {}, a3 = [], c4 = 0; c4 < A2.length; ++c4) - for (var d3 = A2[c4], m3 = d3.bits, x3 = 0; x3 < m3.length; ++x3) { - var M = d3.name + "_" + m3[x3]; - if (a3.push(M), f4[M] = d3.createMethod(m3[x3], d3.padding), d3.name !== "sha3") { - var l4 = d3.name + m3[x3]; - a3.push(l4), f4[l4] = f4[M]; - } - } - function s2(u3, E4, _4) { - this.blocks = [], this.s = [], this.padding = E4, this.outputBits = _4, this.reset = true, this.finalized = false, this.block = 0, this.start = 0, this.blockCount = 1600 - (u3 << 1) >> 5, this.byteCount = this.blockCount << 2, this.outputBlocks = _4 >> 5, this.extraBytes = (_4 & 31) >> 3; - for (var B2 = 0; B2 < 50; ++B2) - this.s[B2] = 0; - } - s2.prototype.update = function(u3) { - if (this.finalized) - throw new Error(r); - var E4, _4 = typeof u3; - if (_4 !== "string") { - if (_4 === "object") { - if (u3 === null) - throw new Error(t); - if (b4 && u3.constructor === ArrayBuffer) - u3 = new Uint8Array(u3); - else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) - throw new Error(t); - } else - throw new Error(t); - E4 = true; - } - for (var B2 = this.blocks, C3 = this.byteCount, D2 = u3.length, P2 = this.blockCount, O3 = 0, Ct = this.s, T2, q2; O3 < D2; ) { - if (this.reset) - for (this.reset = false, B2[0] = this.block, T2 = 1; T2 < P2 + 1; ++T2) - B2[T2] = 0; - if (E4) - for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) - B2[T2 >> 2] |= u3[O3] << N10[T2++ & 3]; - else - for (T2 = this.start; O3 < D2 && T2 < C3; ++O3) - q2 = u3.charCodeAt(O3), q2 < 128 ? B2[T2 >> 2] |= q2 << N10[T2++ & 3] : q2 < 2048 ? (B2[T2 >> 2] |= (192 | q2 >> 6) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : q2 < 55296 || q2 >= 57344 ? (B2[T2 >> 2] |= (224 | q2 >> 12) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]) : (q2 = 65536 + ((q2 & 1023) << 10 | u3.charCodeAt(++O3) & 1023), B2[T2 >> 2] |= (240 | q2 >> 18) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 12 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 >> 6 & 63) << N10[T2++ & 3], B2[T2 >> 2] |= (128 | q2 & 63) << N10[T2++ & 3]); - if (this.lastByteIndex = T2, T2 >= C3) { - for (this.start = T2 - C3, this.block = B2[P2], T2 = 0; T2 < P2; ++T2) - Ct[T2] ^= B2[T2]; - k4(Ct), this.reset = true; - } else - this.start = T2; - } - return this; - }, s2.prototype.encode = function(u3, E4) { - var _4 = u3 & 255, B2 = 1, C3 = [_4]; - for (u3 = u3 >> 8, _4 = u3 & 255; _4 > 0; ) - C3.unshift(_4), u3 = u3 >> 8, _4 = u3 & 255, ++B2; - return E4 ? C3.push(B2) : C3.unshift(B2), this.update(C3), C3.length; - }, s2.prototype.encodeString = function(u3) { - var E4, _4 = typeof u3; - if (_4 !== "string") { - if (_4 === "object") { - if (u3 === null) - throw new Error(t); - if (b4 && u3.constructor === ArrayBuffer) - u3 = new Uint8Array(u3); - else if (!Array.isArray(u3) && (!b4 || !ArrayBuffer.isView(u3))) - throw new Error(t); - } else - throw new Error(t); - E4 = true; - } - var B2 = 0, C3 = u3.length; - if (E4) - B2 = C3; - else - for (var D2 = 0; D2 < u3.length; ++D2) { - var P2 = u3.charCodeAt(D2); - P2 < 128 ? B2 += 1 : P2 < 2048 ? B2 += 2 : P2 < 55296 || P2 >= 57344 ? B2 += 3 : (P2 = 65536 + ((P2 & 1023) << 10 | u3.charCodeAt(++D2) & 1023), B2 += 4); - } - return B2 += this.encode(B2 * 8), this.update(u3), B2; - }, s2.prototype.bytepad = function(u3, E4) { - for (var _4 = this.encode(E4), B2 = 0; B2 < u3.length; ++B2) - _4 += this.encodeString(u3[B2]); - var C3 = E4 - _4 % E4, D2 = []; - return D2.length = C3, this.update(D2), this; - }, s2.prototype.finalize = function() { - if (!this.finalized) { - this.finalized = true; - var u3 = this.blocks, E4 = this.lastByteIndex, _4 = this.blockCount, B2 = this.s; - if (u3[E4 >> 2] |= this.padding[E4 & 3], this.lastByteIndex === this.byteCount) - for (u3[0] = u3[_4], E4 = 1; E4 < _4 + 1; ++E4) - u3[E4] = 0; - for (u3[_4 - 1] |= 2147483648, E4 = 0; E4 < _4; ++E4) - B2[E4] ^= u3[E4]; - k4(B2); - } - }, s2.prototype.toString = s2.prototype.hex = function() { - this.finalize(); - for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = "", O3; D2 < _4; ) { - for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) - O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15] + g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15] + g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15] + g3[O3 >> 28 & 15] + g3[O3 >> 24 & 15]; - D2 % u3 === 0 && (k4(E4), C3 = 0); - } - return B2 && (O3 = E4[C3], P2 += g3[O3 >> 4 & 15] + g3[O3 & 15], B2 > 1 && (P2 += g3[O3 >> 12 & 15] + g3[O3 >> 8 & 15]), B2 > 2 && (P2 += g3[O3 >> 20 & 15] + g3[O3 >> 16 & 15])), P2; - }, s2.prototype.arrayBuffer = function() { - this.finalize(); - var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = this.outputBits >> 3, O3; - B2 ? O3 = new ArrayBuffer(_4 + 1 << 2) : O3 = new ArrayBuffer(P2); - for (var Ct = new Uint32Array(O3); D2 < _4; ) { - for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) - Ct[D2] = E4[C3]; - D2 % u3 === 0 && k4(E4); - } - return B2 && (Ct[C3] = E4[C3], O3 = O3.slice(0, P2)), O3; - }, s2.prototype.buffer = s2.prototype.arrayBuffer, s2.prototype.digest = s2.prototype.array = function() { - this.finalize(); - for (var u3 = this.blockCount, E4 = this.s, _4 = this.outputBlocks, B2 = this.extraBytes, C3 = 0, D2 = 0, P2 = [], O3, Ct; D2 < _4; ) { - for (C3 = 0; C3 < u3 && D2 < _4; ++C3, ++D2) - O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, P2[O3 + 1] = Ct >> 8 & 255, P2[O3 + 2] = Ct >> 16 & 255, P2[O3 + 3] = Ct >> 24 & 255; - D2 % u3 === 0 && k4(E4); - } - return B2 && (O3 = D2 << 2, Ct = E4[C3], P2[O3] = Ct & 255, B2 > 1 && (P2[O3 + 1] = Ct >> 8 & 255), B2 > 2 && (P2[O3 + 2] = Ct >> 16 & 255)), P2; - }; - function v2(u3, E4, _4) { - s2.call(this, u3, E4, _4); - } - v2.prototype = new s2(), v2.prototype.finalize = function() { - return this.encode(this.outputBits, true), s2.prototype.finalize.call(this); - }; - var k4 = function(u3) { - var E4, _4, B2, C3, D2, P2, O3, Ct, T2, q2, Pe, X, Z, Te, $, tt, Fe, et, rt, De, it, nt, Ue, ft, ot, ke, st, at, qe, ut, ht, Ke, ct, lt, He, dt, pt, Le, vt, gt, ze, mt, At, je, bt, yt, Ve, wt, xt, Qe, Mt, Et, Je, St, Nt, Ye, It, _t, xe, Me, Ee, Se, Ne; - for (B2 = 0; B2 < 48; B2 += 2) - C3 = u3[0] ^ u3[10] ^ u3[20] ^ u3[30] ^ u3[40], D2 = u3[1] ^ u3[11] ^ u3[21] ^ u3[31] ^ u3[41], P2 = u3[2] ^ u3[12] ^ u3[22] ^ u3[32] ^ u3[42], O3 = u3[3] ^ u3[13] ^ u3[23] ^ u3[33] ^ u3[43], Ct = u3[4] ^ u3[14] ^ u3[24] ^ u3[34] ^ u3[44], T2 = u3[5] ^ u3[15] ^ u3[25] ^ u3[35] ^ u3[45], q2 = u3[6] ^ u3[16] ^ u3[26] ^ u3[36] ^ u3[46], Pe = u3[7] ^ u3[17] ^ u3[27] ^ u3[37] ^ u3[47], X = u3[8] ^ u3[18] ^ u3[28] ^ u3[38] ^ u3[48], Z = u3[9] ^ u3[19] ^ u3[29] ^ u3[39] ^ u3[49], E4 = X ^ (P2 << 1 | O3 >>> 31), _4 = Z ^ (O3 << 1 | P2 >>> 31), u3[0] ^= E4, u3[1] ^= _4, u3[10] ^= E4, u3[11] ^= _4, u3[20] ^= E4, u3[21] ^= _4, u3[30] ^= E4, u3[31] ^= _4, u3[40] ^= E4, u3[41] ^= _4, E4 = C3 ^ (Ct << 1 | T2 >>> 31), _4 = D2 ^ (T2 << 1 | Ct >>> 31), u3[2] ^= E4, u3[3] ^= _4, u3[12] ^= E4, u3[13] ^= _4, u3[22] ^= E4, u3[23] ^= _4, u3[32] ^= E4, u3[33] ^= _4, u3[42] ^= E4, u3[43] ^= _4, E4 = P2 ^ (q2 << 1 | Pe >>> 31), _4 = O3 ^ (Pe << 1 | q2 >>> 31), u3[4] ^= E4, u3[5] ^= _4, u3[14] ^= E4, u3[15] ^= _4, u3[24] ^= E4, u3[25] ^= _4, u3[34] ^= E4, u3[35] ^= _4, u3[44] ^= E4, u3[45] ^= _4, E4 = Ct ^ (X << 1 | Z >>> 31), _4 = T2 ^ (Z << 1 | X >>> 31), u3[6] ^= E4, u3[7] ^= _4, u3[16] ^= E4, u3[17] ^= _4, u3[26] ^= E4, u3[27] ^= _4, u3[36] ^= E4, u3[37] ^= _4, u3[46] ^= E4, u3[47] ^= _4, E4 = q2 ^ (C3 << 1 | D2 >>> 31), _4 = Pe ^ (D2 << 1 | C3 >>> 31), u3[8] ^= E4, u3[9] ^= _4, u3[18] ^= E4, u3[19] ^= _4, u3[28] ^= E4, u3[29] ^= _4, u3[38] ^= E4, u3[39] ^= _4, u3[48] ^= E4, u3[49] ^= _4, Te = u3[0], $ = u3[1], yt = u3[11] << 4 | u3[10] >>> 28, Ve = u3[10] << 4 | u3[11] >>> 28, at = u3[20] << 3 | u3[21] >>> 29, qe = u3[21] << 3 | u3[20] >>> 29, Me = u3[31] << 9 | u3[30] >>> 23, Ee = u3[30] << 9 | u3[31] >>> 23, mt = u3[40] << 18 | u3[41] >>> 14, At = u3[41] << 18 | u3[40] >>> 14, lt = u3[2] << 1 | u3[3] >>> 31, He = u3[3] << 1 | u3[2] >>> 31, tt = u3[13] << 12 | u3[12] >>> 20, Fe = u3[12] << 12 | u3[13] >>> 20, wt = u3[22] << 10 | u3[23] >>> 22, xt = u3[23] << 10 | u3[22] >>> 22, ut = u3[33] << 13 | u3[32] >>> 19, ht = u3[32] << 13 | u3[33] >>> 19, Se = u3[42] << 2 | u3[43] >>> 30, Ne = u3[43] << 2 | u3[42] >>> 30, St = u3[5] << 30 | u3[4] >>> 2, Nt = u3[4] << 30 | u3[5] >>> 2, dt = u3[14] << 6 | u3[15] >>> 26, pt = u3[15] << 6 | u3[14] >>> 26, et = u3[25] << 11 | u3[24] >>> 21, rt = u3[24] << 11 | u3[25] >>> 21, Qe = u3[34] << 15 | u3[35] >>> 17, Mt = u3[35] << 15 | u3[34] >>> 17, Ke = u3[45] << 29 | u3[44] >>> 3, ct = u3[44] << 29 | u3[45] >>> 3, ft = u3[6] << 28 | u3[7] >>> 4, ot = u3[7] << 28 | u3[6] >>> 4, Ye = u3[17] << 23 | u3[16] >>> 9, It = u3[16] << 23 | u3[17] >>> 9, Le = u3[26] << 25 | u3[27] >>> 7, vt = u3[27] << 25 | u3[26] >>> 7, De = u3[36] << 21 | u3[37] >>> 11, it = u3[37] << 21 | u3[36] >>> 11, Et = u3[47] << 24 | u3[46] >>> 8, Je = u3[46] << 24 | u3[47] >>> 8, je = u3[8] << 27 | u3[9] >>> 5, bt = u3[9] << 27 | u3[8] >>> 5, ke = u3[18] << 20 | u3[19] >>> 12, st = u3[19] << 20 | u3[18] >>> 12, _t = u3[29] << 7 | u3[28] >>> 25, xe = u3[28] << 7 | u3[29] >>> 25, gt = u3[38] << 8 | u3[39] >>> 24, ze = u3[39] << 8 | u3[38] >>> 24, nt = u3[48] << 14 | u3[49] >>> 18, Ue = u3[49] << 14 | u3[48] >>> 18, u3[0] = Te ^ ~tt & et, u3[1] = $ ^ ~Fe & rt, u3[10] = ft ^ ~ke & at, u3[11] = ot ^ ~st & qe, u3[20] = lt ^ ~dt & Le, u3[21] = He ^ ~pt & vt, u3[30] = je ^ ~yt & wt, u3[31] = bt ^ ~Ve & xt, u3[40] = St ^ ~Ye & _t, u3[41] = Nt ^ ~It & xe, u3[2] = tt ^ ~et & De, u3[3] = Fe ^ ~rt & it, u3[12] = ke ^ ~at & ut, u3[13] = st ^ ~qe & ht, u3[22] = dt ^ ~Le & gt, u3[23] = pt ^ ~vt & ze, u3[32] = yt ^ ~wt & Qe, u3[33] = Ve ^ ~xt & Mt, u3[42] = Ye ^ ~_t & Me, u3[43] = It ^ ~xe & Ee, u3[4] = et ^ ~De & nt, u3[5] = rt ^ ~it & Ue, u3[14] = at ^ ~ut & Ke, u3[15] = qe ^ ~ht & ct, u3[24] = Le ^ ~gt & mt, u3[25] = vt ^ ~ze & At, u3[34] = wt ^ ~Qe & Et, u3[35] = xt ^ ~Mt & Je, u3[44] = _t ^ ~Me & Se, u3[45] = xe ^ ~Ee & Ne, u3[6] = De ^ ~nt & Te, u3[7] = it ^ ~Ue & $, u3[16] = ut ^ ~Ke & ft, u3[17] = ht ^ ~ct & ot, u3[26] = gt ^ ~mt & lt, u3[27] = ze ^ ~At & He, u3[36] = Qe ^ ~Et & je, u3[37] = Mt ^ ~Je & bt, u3[46] = Me ^ ~Se & St, u3[47] = Ee ^ ~Ne & Nt, u3[8] = nt ^ ~Te & tt, u3[9] = Ue ^ ~$ & Fe, u3[18] = Ke ^ ~ft & ke, u3[19] = ct ^ ~ot & st, u3[28] = mt ^ ~lt & dt, u3[29] = At ^ ~He & pt, u3[38] = Et ^ ~je & yt, u3[39] = Je ^ ~bt & Ve, u3[48] = Se ^ ~St & Ye, u3[49] = Ne ^ ~Nt & It, u3[0] ^= R2[B2], u3[1] ^= R2[B2 + 1]; - }; - if (p3) - e2.exports = f4; - else - for (c4 = 0; c4 < a3.length; ++c4) - n3[a3[c4]] = f4[a3[c4]]; - })(); - })(Bn); - var vs = Bn.exports; - var gs = "logger/5.7.0"; - var Rn = false; - var Cn = false; - var Cr = { debug: 1, default: 2, info: 2, warning: 3, error: 4, off: 5 }; - var On = Cr.default; - var Ai = null; - function ms() { - try { - const e2 = []; - if (["NFD", "NFC", "NFKD", "NFKC"].forEach((t) => { - try { - if ("test".normalize(t) !== "test") - throw new Error("bad normalize"); - } catch { - e2.push(t); - } - }), e2.length) - throw new Error("missing " + e2.join(", ")); - if (String.fromCharCode(233).normalize("NFD") !== String.fromCharCode(101, 769)) - throw new Error("broken implementation"); - } catch (e2) { - return e2.message; - } - return null; - } - var Pn = ms(); - var bi; - (function(e2) { - e2.DEBUG = "DEBUG", e2.INFO = "INFO", e2.WARNING = "WARNING", e2.ERROR = "ERROR", e2.OFF = "OFF"; - })(bi || (bi = {})); - var ee; - (function(e2) { - e2.UNKNOWN_ERROR = "UNKNOWN_ERROR", e2.NOT_IMPLEMENTED = "NOT_IMPLEMENTED", e2.UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION", e2.NETWORK_ERROR = "NETWORK_ERROR", e2.SERVER_ERROR = "SERVER_ERROR", e2.TIMEOUT = "TIMEOUT", e2.BUFFER_OVERRUN = "BUFFER_OVERRUN", e2.NUMERIC_FAULT = "NUMERIC_FAULT", e2.MISSING_NEW = "MISSING_NEW", e2.INVALID_ARGUMENT = "INVALID_ARGUMENT", e2.MISSING_ARGUMENT = "MISSING_ARGUMENT", e2.UNEXPECTED_ARGUMENT = "UNEXPECTED_ARGUMENT", e2.CALL_EXCEPTION = "CALL_EXCEPTION", e2.INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS", e2.NONCE_EXPIRED = "NONCE_EXPIRED", e2.REPLACEMENT_UNDERPRICED = "REPLACEMENT_UNDERPRICED", e2.UNPREDICTABLE_GAS_LIMIT = "UNPREDICTABLE_GAS_LIMIT", e2.TRANSACTION_REPLACED = "TRANSACTION_REPLACED", e2.ACTION_REJECTED = "ACTION_REJECTED"; - })(ee || (ee = {})); - var Tn = "0123456789abcdef"; - var z3 = class _z { - constructor(t) { - Object.defineProperty(this, "version", { enumerable: true, value: t, writable: false }); - } - _log(t, r) { - const i2 = t.toLowerCase(); - Cr[i2] == null && this.throwArgumentError("invalid log level name", "logLevel", t), !(On > Cr[i2]) && console.log.apply(console, r); - } - debug(...t) { - this._log(_z.levels.DEBUG, t); - } - info(...t) { - this._log(_z.levels.INFO, t); - } - warn(...t) { - this._log(_z.levels.WARNING, t); - } - makeError(t, r, i2) { - if (Cn) - return this.makeError("censored error", r, {}); - r || (r = _z.errors.UNKNOWN_ERROR), i2 || (i2 = {}); - const n3 = []; - Object.keys(i2).forEach((b4) => { - const g3 = i2[b4]; - try { - if (g3 instanceof Uint8Array) { - let w4 = ""; - for (let y4 = 0; y4 < g3.length; y4++) - w4 += Tn[g3[y4] >> 4], w4 += Tn[g3[y4] & 15]; - n3.push(b4 + "=Uint8Array(0x" + w4 + ")"); - } else - n3.push(b4 + "=" + JSON.stringify(g3)); - } catch { - n3.push(b4 + "=" + JSON.stringify(i2[b4].toString())); - } - }), n3.push(`code=${r}`), n3.push(`version=${this.version}`); - const o2 = t; - let h5 = ""; - switch (r) { - case ee.NUMERIC_FAULT: { - h5 = "NUMERIC_FAULT"; - const b4 = t; - switch (b4) { - case "overflow": - case "underflow": - case "division-by-zero": - h5 += "-" + b4; - break; - case "negative-power": - case "negative-width": - h5 += "-unsupported"; - break; - case "unbound-bitwise-result": - h5 += "-unbound-result"; - break; - } - break; - } - case ee.CALL_EXCEPTION: - case ee.INSUFFICIENT_FUNDS: - case ee.MISSING_NEW: - case ee.NONCE_EXPIRED: - case ee.REPLACEMENT_UNDERPRICED: - case ee.TRANSACTION_REPLACED: - case ee.UNPREDICTABLE_GAS_LIMIT: - h5 = r; - break; - } - h5 && (t += " [ See: https://links.ethers.org/v5-errors-" + h5 + " ]"), n3.length && (t += " (" + n3.join(", ") + ")"); - const p3 = new Error(t); - return p3.reason = o2, p3.code = r, Object.keys(i2).forEach(function(b4) { - p3[b4] = i2[b4]; - }), p3; - } - throwError(t, r, i2) { - throw this.makeError(t, r, i2); - } - throwArgumentError(t, r, i2) { - return this.throwError(t, _z.errors.INVALID_ARGUMENT, { argument: r, value: i2 }); - } - assert(t, r, i2, n3) { - t || this.throwError(r, i2, n3); - } - assertArgument(t, r, i2, n3) { - t || this.throwArgumentError(r, i2, n3); - } - checkNormalize(t) { - Pn && this.throwError("platform missing String.prototype.normalize", _z.errors.UNSUPPORTED_OPERATION, { operation: "String.prototype.normalize", form: Pn }); - } - checkSafeUint53(t, r) { - typeof t == "number" && (r == null && (r = "value not safe"), (t < 0 || t >= 9007199254740991) && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "out-of-safe-range", value: t }), t % 1 && this.throwError(r, _z.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "non-integer", value: t })); - } - checkArgumentCount(t, r, i2) { - i2 ? i2 = ": " + i2 : i2 = "", t < r && this.throwError("missing argument" + i2, _z.errors.MISSING_ARGUMENT, { count: t, expectedCount: r }), t > r && this.throwError("too many arguments" + i2, _z.errors.UNEXPECTED_ARGUMENT, { count: t, expectedCount: r }); - } - checkNew(t, r) { - (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); - } - checkAbstract(t, r) { - t === r ? this.throwError("cannot instantiate abstract class " + JSON.stringify(r.name) + " directly; use a sub-class", _z.errors.UNSUPPORTED_OPERATION, { name: t.name, operation: "new" }) : (t === Object || t == null) && this.throwError("missing new", _z.errors.MISSING_NEW, { name: r.name }); - } - static globalLogger() { - return Ai || (Ai = new _z(gs)), Ai; - } - static setCensorship(t, r) { - if (!t && r && this.globalLogger().throwError("cannot permanently disable censorship", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }), Rn) { - if (!t) - return; - this.globalLogger().throwError("error censorship permanent", _z.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); - } - Cn = !!t, Rn = !!r; - } - static setLogLevel(t) { - const r = Cr[t.toLowerCase()]; - if (r == null) { - _z.globalLogger().warn("invalid log level - " + t); - return; - } - On = r; - } - static from(t) { - return new _z(t); - } - }; - z3.errors = ee, z3.levels = bi; - var As = "bytes/5.7.0"; - var Ft = new z3(As); - function Fn(e2) { - return !!e2.toHexString; - } - function ir(e2) { - return e2.slice || (e2.slice = function() { - const t = Array.prototype.slice.call(arguments); - return ir(new Uint8Array(Array.prototype.slice.apply(e2, t))); - }), e2; - } - function bs(e2) { - return Qt(e2) && !(e2.length % 2) || nr(e2); - } - function Dn(e2) { - return typeof e2 == "number" && e2 == e2 && e2 % 1 === 0; - } - function nr(e2) { - if (e2 == null) - return false; - if (e2.constructor === Uint8Array) - return true; - if (typeof e2 == "string" || !Dn(e2.length) || e2.length < 0) - return false; - for (let t = 0; t < e2.length; t++) { - const r = e2[t]; - if (!Dn(r) || r < 0 || r >= 256) - return false; - } - return true; - } - function Pt(e2, t) { - if (t || (t = {}), typeof e2 == "number") { - Ft.checkSafeUint53(e2, "invalid arrayify value"); - const r = []; - for (; e2; ) - r.unshift(e2 & 255), e2 = parseInt(String(e2 / 256)); - return r.length === 0 && r.push(0), ir(new Uint8Array(r)); - } - if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2) && (e2 = e2.toHexString()), Qt(e2)) { - let r = e2.substring(2); - r.length % 2 && (t.hexPad === "left" ? r = "0" + r : t.hexPad === "right" ? r += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)); - const i2 = []; - for (let n3 = 0; n3 < r.length; n3 += 2) - i2.push(parseInt(r.substring(n3, n3 + 2), 16)); - return ir(new Uint8Array(i2)); - } - return nr(e2) ? ir(new Uint8Array(e2)) : Ft.throwArgumentError("invalid arrayify value", "value", e2); - } - function ys(e2) { - const t = e2.map((n3) => Pt(n3)), r = t.reduce((n3, o2) => n3 + o2.length, 0), i2 = new Uint8Array(r); - return t.reduce((n3, o2) => (i2.set(o2, n3), n3 + o2.length), 0), ir(i2); - } - function ws(e2, t) { - e2 = Pt(e2), e2.length > t && Ft.throwArgumentError("value out of range", "value", arguments[0]); - const r = new Uint8Array(t); - return r.set(e2, t - e2.length), ir(r); - } - function Qt(e2, t) { - return !(typeof e2 != "string" || !e2.match(/^0x[0-9A-Fa-f]*$/) || t && e2.length !== 2 + 2 * t); - } - var yi = "0123456789abcdef"; - function Ht(e2, t) { - if (t || (t = {}), typeof e2 == "number") { - Ft.checkSafeUint53(e2, "invalid hexlify value"); - let r = ""; - for (; e2; ) - r = yi[e2 & 15] + r, e2 = Math.floor(e2 / 16); - return r.length ? (r.length % 2 && (r = "0" + r), "0x" + r) : "0x00"; - } - if (typeof e2 == "bigint") - return e2 = e2.toString(16), e2.length % 2 ? "0x0" + e2 : "0x" + e2; - if (t.allowMissingPrefix && typeof e2 == "string" && e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), Fn(e2)) - return e2.toHexString(); - if (Qt(e2)) - return e2.length % 2 && (t.hexPad === "left" ? e2 = "0x0" + e2.substring(2) : t.hexPad === "right" ? e2 += "0" : Ft.throwArgumentError("hex data is odd-length", "value", e2)), e2.toLowerCase(); - if (nr(e2)) { - let r = "0x"; - for (let i2 = 0; i2 < e2.length; i2++) { - let n3 = e2[i2]; - r += yi[(n3 & 240) >> 4] + yi[n3 & 15]; - } - return r; - } - return Ft.throwArgumentError("invalid hexlify value", "value", e2); - } - function xs(e2) { - if (typeof e2 != "string") - e2 = Ht(e2); - else if (!Qt(e2) || e2.length % 2) - return null; - return (e2.length - 2) / 2; - } - function Un(e2, t, r) { - return typeof e2 != "string" ? e2 = Ht(e2) : (!Qt(e2) || e2.length % 2) && Ft.throwArgumentError("invalid hexData", "value", e2), t = 2 + 2 * t, r != null ? "0x" + e2.substring(t, 2 + 2 * r) : "0x" + e2.substring(t); - } - function fe(e2, t) { - for (typeof e2 != "string" ? e2 = Ht(e2) : Qt(e2) || Ft.throwArgumentError("invalid hex string", "value", e2), e2.length > 2 * t + 2 && Ft.throwArgumentError("value out of range", "value", arguments[1]); e2.length < 2 * t + 2; ) - e2 = "0x0" + e2.substring(2); - return e2; - } - function kn(e2) { - const t = { r: "0x", s: "0x", _vs: "0x", recoveryParam: 0, v: 0, yParityAndS: "0x", compact: "0x" }; - if (bs(e2)) { - let r = Pt(e2); - r.length === 64 ? (t.v = 27 + (r[32] >> 7), r[32] &= 127, t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64))) : r.length === 65 ? (t.r = Ht(r.slice(0, 32)), t.s = Ht(r.slice(32, 64)), t.v = r[64]) : Ft.throwArgumentError("invalid signature string", "signature", e2), t.v < 27 && (t.v === 0 || t.v === 1 ? t.v += 27 : Ft.throwArgumentError("signature invalid v byte", "signature", e2)), t.recoveryParam = 1 - t.v % 2, t.recoveryParam && (r[32] |= 128), t._vs = Ht(r.slice(32, 64)); - } else { - if (t.r = e2.r, t.s = e2.s, t.v = e2.v, t.recoveryParam = e2.recoveryParam, t._vs = e2._vs, t._vs != null) { - const n3 = ws(Pt(t._vs), 32); - t._vs = Ht(n3); - const o2 = n3[0] >= 128 ? 1 : 0; - t.recoveryParam == null ? t.recoveryParam = o2 : t.recoveryParam !== o2 && Ft.throwArgumentError("signature recoveryParam mismatch _vs", "signature", e2), n3[0] &= 127; - const h5 = Ht(n3); - t.s == null ? t.s = h5 : t.s !== h5 && Ft.throwArgumentError("signature v mismatch _vs", "signature", e2); - } - if (t.recoveryParam == null) - t.v == null ? Ft.throwArgumentError("signature missing v and recoveryParam", "signature", e2) : t.v === 0 || t.v === 1 ? t.recoveryParam = t.v : t.recoveryParam = 1 - t.v % 2; - else if (t.v == null) - t.v = 27 + t.recoveryParam; - else { - const n3 = t.v === 0 || t.v === 1 ? t.v : 1 - t.v % 2; - t.recoveryParam !== n3 && Ft.throwArgumentError("signature recoveryParam mismatch v", "signature", e2); - } - t.r == null || !Qt(t.r) ? Ft.throwArgumentError("signature missing or invalid r", "signature", e2) : t.r = fe(t.r, 32), t.s == null || !Qt(t.s) ? Ft.throwArgumentError("signature missing or invalid s", "signature", e2) : t.s = fe(t.s, 32); - const r = Pt(t.s); - r[0] >= 128 && Ft.throwArgumentError("signature s out of range", "signature", e2), t.recoveryParam && (r[0] |= 128); - const i2 = Ht(r); - t._vs && (Qt(t._vs) || Ft.throwArgumentError("signature invalid _vs", "signature", e2), t._vs = fe(t._vs, 32)), t._vs == null ? t._vs = i2 : t._vs !== i2 && Ft.throwArgumentError("signature _vs mismatch v and s", "signature", e2); - } - return t.yParityAndS = t._vs, t.compact = t.r + t.yParityAndS.substring(2), t; - } - function wi(e2) { - return "0x" + vs.keccak_256(Pt(e2)); - } - var qn = { exports: {} }; - var Ms = {}; - var Es = Object.freeze({ __proto__: null, default: Ms }); - var Ss = ps(Es); - (function(e2) { - (function(t, r) { - function i2(A2, f4) { - if (!A2) - throw new Error(f4 || "Assertion failed"); - } - function n3(A2, f4) { - A2.super_ = f4; - var a3 = function() { - }; - a3.prototype = f4.prototype, A2.prototype = new a3(), A2.prototype.constructor = A2; - } - function o2(A2, f4, a3) { - if (o2.isBN(A2)) - return A2; - this.negative = 0, this.words = null, this.length = 0, this.red = null, A2 !== null && ((f4 === "le" || f4 === "be") && (a3 = f4, f4 = 10), this._init(A2 || 0, f4 || 10, a3 || "be")); - } - typeof t == "object" ? t.exports = o2 : r.BN = o2, o2.BN = o2, o2.wordSize = 26; - var h5; - try { - typeof window < "u" && typeof window.Buffer < "u" ? h5 = window.Buffer : h5 = Ss.Buffer; - } catch { - } - o2.isBN = function(f4) { - return f4 instanceof o2 ? true : f4 !== null && typeof f4 == "object" && f4.constructor.wordSize === o2.wordSize && Array.isArray(f4.words); - }, o2.max = function(f4, a3) { - return f4.cmp(a3) > 0 ? f4 : a3; - }, o2.min = function(f4, a3) { - return f4.cmp(a3) < 0 ? f4 : a3; - }, o2.prototype._init = function(f4, a3, c4) { - if (typeof f4 == "number") - return this._initNumber(f4, a3, c4); - if (typeof f4 == "object") - return this._initArray(f4, a3, c4); - a3 === "hex" && (a3 = 16), i2(a3 === (a3 | 0) && a3 >= 2 && a3 <= 36), f4 = f4.toString().replace(/\s+/g, ""); - var d3 = 0; - f4[0] === "-" && (d3++, this.negative = 1), d3 < f4.length && (a3 === 16 ? this._parseHex(f4, d3, c4) : (this._parseBase(f4, a3, d3), c4 === "le" && this._initArray(this.toArray(), a3, c4))); - }, o2.prototype._initNumber = function(f4, a3, c4) { - f4 < 0 && (this.negative = 1, f4 = -f4), f4 < 67108864 ? (this.words = [f4 & 67108863], this.length = 1) : f4 < 4503599627370496 ? (this.words = [f4 & 67108863, f4 / 67108864 & 67108863], this.length = 2) : (i2(f4 < 9007199254740992), this.words = [f4 & 67108863, f4 / 67108864 & 67108863, 1], this.length = 3), c4 === "le" && this._initArray(this.toArray(), a3, c4); - }, o2.prototype._initArray = function(f4, a3, c4) { - if (i2(typeof f4.length == "number"), f4.length <= 0) - return this.words = [0], this.length = 1, this; - this.length = Math.ceil(f4.length / 3), this.words = new Array(this.length); - for (var d3 = 0; d3 < this.length; d3++) - this.words[d3] = 0; - var m3, x3, M = 0; - if (c4 === "be") - for (d3 = f4.length - 1, m3 = 0; d3 >= 0; d3 -= 3) - x3 = f4[d3] | f4[d3 - 1] << 8 | f4[d3 - 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); - else if (c4 === "le") - for (d3 = 0, m3 = 0; d3 < f4.length; d3 += 3) - x3 = f4[d3] | f4[d3 + 1] << 8 | f4[d3 + 2] << 16, this.words[m3] |= x3 << M & 67108863, this.words[m3 + 1] = x3 >>> 26 - M & 67108863, M += 24, M >= 26 && (M -= 26, m3++); - return this._strip(); - }; - function p3(A2, f4) { - var a3 = A2.charCodeAt(f4); - if (a3 >= 48 && a3 <= 57) - return a3 - 48; - if (a3 >= 65 && a3 <= 70) - return a3 - 55; - if (a3 >= 97 && a3 <= 102) - return a3 - 87; - i2(false, "Invalid character in " + A2); - } - function b4(A2, f4, a3) { - var c4 = p3(A2, a3); - return a3 - 1 >= f4 && (c4 |= p3(A2, a3 - 1) << 4), c4; - } - o2.prototype._parseHex = function(f4, a3, c4) { - this.length = Math.ceil((f4.length - a3) / 6), this.words = new Array(this.length); - for (var d3 = 0; d3 < this.length; d3++) - this.words[d3] = 0; - var m3 = 0, x3 = 0, M; - if (c4 === "be") - for (d3 = f4.length - 1; d3 >= a3; d3 -= 2) - M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; - else { - var l4 = f4.length - a3; - for (d3 = l4 % 2 === 0 ? a3 + 1 : a3; d3 < f4.length; d3 += 2) - M = b4(f4, a3, d3) << m3, this.words[x3] |= M & 67108863, m3 >= 18 ? (m3 -= 18, x3 += 1, this.words[x3] |= M >>> 26) : m3 += 8; - } - this._strip(); - }; - function g3(A2, f4, a3, c4) { - for (var d3 = 0, m3 = 0, x3 = Math.min(A2.length, a3), M = f4; M < x3; M++) { - var l4 = A2.charCodeAt(M) - 48; - d3 *= c4, l4 >= 49 ? m3 = l4 - 49 + 10 : l4 >= 17 ? m3 = l4 - 17 + 10 : m3 = l4, i2(l4 >= 0 && m3 < c4, "Invalid character"), d3 += m3; - } - return d3; - } - o2.prototype._parseBase = function(f4, a3, c4) { - this.words = [0], this.length = 1; - for (var d3 = 0, m3 = 1; m3 <= 67108863; m3 *= a3) - d3++; - d3--, m3 = m3 / a3 | 0; - for (var x3 = f4.length - c4, M = x3 % d3, l4 = Math.min(x3, x3 - M) + c4, s2 = 0, v2 = c4; v2 < l4; v2 += d3) - s2 = g3(f4, v2, v2 + d3, a3), this.imuln(m3), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); - if (M !== 0) { - var k4 = 1; - for (s2 = g3(f4, v2, f4.length, a3), v2 = 0; v2 < M; v2++) - k4 *= a3; - this.imuln(k4), this.words[0] + s2 < 67108864 ? this.words[0] += s2 : this._iaddn(s2); - } - this._strip(); - }, o2.prototype.copy = function(f4) { - f4.words = new Array(this.length); - for (var a3 = 0; a3 < this.length; a3++) - f4.words[a3] = this.words[a3]; - f4.length = this.length, f4.negative = this.negative, f4.red = this.red; - }; - function w4(A2, f4) { - A2.words = f4.words, A2.length = f4.length, A2.negative = f4.negative, A2.red = f4.red; - } - if (o2.prototype._move = function(f4) { - w4(f4, this); - }, o2.prototype.clone = function() { - var f4 = new o2(null); - return this.copy(f4), f4; - }, o2.prototype._expand = function(f4) { - for (; this.length < f4; ) - this.words[this.length++] = 0; - return this; - }, o2.prototype._strip = function() { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) - this.length--; - return this._normSign(); - }, o2.prototype._normSign = function() { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }, typeof Symbol < "u" && typeof Symbol.for == "function") - try { - o2.prototype[Symbol.for("nodejs.util.inspect.custom")] = y4; - } catch { - o2.prototype.inspect = y4; - } - else - o2.prototype.inspect = y4; - function y4() { - return (this.red ? ""; - } - var S4 = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], I2 = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], N10 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; - o2.prototype.toString = function(f4, a3) { - f4 = f4 || 10, a3 = a3 | 0 || 1; - var c4; - if (f4 === 16 || f4 === "hex") { - c4 = ""; - for (var d3 = 0, m3 = 0, x3 = 0; x3 < this.length; x3++) { - var M = this.words[x3], l4 = ((M << d3 | m3) & 16777215).toString(16); - m3 = M >>> 24 - d3 & 16777215, d3 += 2, d3 >= 26 && (d3 -= 26, x3--), m3 !== 0 || x3 !== this.length - 1 ? c4 = S4[6 - l4.length] + l4 + c4 : c4 = l4 + c4; - } - for (m3 !== 0 && (c4 = m3.toString(16) + c4); c4.length % a3 !== 0; ) - c4 = "0" + c4; - return this.negative !== 0 && (c4 = "-" + c4), c4; - } - if (f4 === (f4 | 0) && f4 >= 2 && f4 <= 36) { - var s2 = I2[f4], v2 = N10[f4]; - c4 = ""; - var k4 = this.clone(); - for (k4.negative = 0; !k4.isZero(); ) { - var u3 = k4.modrn(v2).toString(f4); - k4 = k4.idivn(v2), k4.isZero() ? c4 = u3 + c4 : c4 = S4[s2 - u3.length] + u3 + c4; - } - for (this.isZero() && (c4 = "0" + c4); c4.length % a3 !== 0; ) - c4 = "0" + c4; - return this.negative !== 0 && (c4 = "-" + c4), c4; - } - i2(false, "Base should be between 2 and 36"); - }, o2.prototype.toNumber = function() { - var f4 = this.words[0]; - return this.length === 2 ? f4 += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? f4 += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && i2(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -f4 : f4; - }, o2.prototype.toJSON = function() { - return this.toString(16, 2); - }, h5 && (o2.prototype.toBuffer = function(f4, a3) { - return this.toArrayLike(h5, f4, a3); - }), o2.prototype.toArray = function(f4, a3) { - return this.toArrayLike(Array, f4, a3); - }; - var R2 = function(f4, a3) { - return f4.allocUnsafe ? f4.allocUnsafe(a3) : new f4(a3); - }; - o2.prototype.toArrayLike = function(f4, a3, c4) { - this._strip(); - var d3 = this.byteLength(), m3 = c4 || Math.max(1, d3); - i2(d3 <= m3, "byte array longer than desired length"), i2(m3 > 0, "Requested array length <= 0"); - var x3 = R2(f4, m3), M = a3 === "le" ? "LE" : "BE"; - return this["_toArrayLike" + M](x3, d3), x3; - }, o2.prototype._toArrayLikeLE = function(f4, a3) { - for (var c4 = 0, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { - var M = this.words[m3] << x3 | d3; - f4[c4++] = M & 255, c4 < f4.length && (f4[c4++] = M >> 8 & 255), c4 < f4.length && (f4[c4++] = M >> 16 & 255), x3 === 6 ? (c4 < f4.length && (f4[c4++] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); - } - if (c4 < f4.length) - for (f4[c4++] = d3; c4 < f4.length; ) - f4[c4++] = 0; - }, o2.prototype._toArrayLikeBE = function(f4, a3) { - for (var c4 = f4.length - 1, d3 = 0, m3 = 0, x3 = 0; m3 < this.length; m3++) { - var M = this.words[m3] << x3 | d3; - f4[c4--] = M & 255, c4 >= 0 && (f4[c4--] = M >> 8 & 255), c4 >= 0 && (f4[c4--] = M >> 16 & 255), x3 === 6 ? (c4 >= 0 && (f4[c4--] = M >> 24 & 255), d3 = 0, x3 = 0) : (d3 = M >>> 24, x3 += 2); - } - if (c4 >= 0) - for (f4[c4--] = d3; c4 >= 0; ) - f4[c4--] = 0; - }, Math.clz32 ? o2.prototype._countBits = function(f4) { - return 32 - Math.clz32(f4); - } : o2.prototype._countBits = function(f4) { - var a3 = f4, c4 = 0; - return a3 >= 4096 && (c4 += 13, a3 >>>= 13), a3 >= 64 && (c4 += 7, a3 >>>= 7), a3 >= 8 && (c4 += 4, a3 >>>= 4), a3 >= 2 && (c4 += 2, a3 >>>= 2), c4 + a3; - }, o2.prototype._zeroBits = function(f4) { - if (f4 === 0) - return 26; - var a3 = f4, c4 = 0; - return a3 & 8191 || (c4 += 13, a3 >>>= 13), a3 & 127 || (c4 += 7, a3 >>>= 7), a3 & 15 || (c4 += 4, a3 >>>= 4), a3 & 3 || (c4 += 2, a3 >>>= 2), a3 & 1 || c4++, c4; - }, o2.prototype.bitLength = function() { - var f4 = this.words[this.length - 1], a3 = this._countBits(f4); - return (this.length - 1) * 26 + a3; - }; - function F(A2) { - for (var f4 = new Array(A2.bitLength()), a3 = 0; a3 < f4.length; a3++) { - var c4 = a3 / 26 | 0, d3 = a3 % 26; - f4[a3] = A2.words[c4] >>> d3 & 1; - } - return f4; - } - o2.prototype.zeroBits = function() { - if (this.isZero()) - return 0; - for (var f4 = 0, a3 = 0; a3 < this.length; a3++) { - var c4 = this._zeroBits(this.words[a3]); - if (f4 += c4, c4 !== 26) - break; - } - return f4; - }, o2.prototype.byteLength = function() { - return Math.ceil(this.bitLength() / 8); - }, o2.prototype.toTwos = function(f4) { - return this.negative !== 0 ? this.abs().inotn(f4).iaddn(1) : this.clone(); - }, o2.prototype.fromTwos = function(f4) { - return this.testn(f4 - 1) ? this.notn(f4).iaddn(1).ineg() : this.clone(); - }, o2.prototype.isNeg = function() { - return this.negative !== 0; - }, o2.prototype.neg = function() { - return this.clone().ineg(); - }, o2.prototype.ineg = function() { - return this.isZero() || (this.negative ^= 1), this; - }, o2.prototype.iuor = function(f4) { - for (; this.length < f4.length; ) - this.words[this.length++] = 0; - for (var a3 = 0; a3 < f4.length; a3++) - this.words[a3] = this.words[a3] | f4.words[a3]; - return this._strip(); - }, o2.prototype.ior = function(f4) { - return i2((this.negative | f4.negative) === 0), this.iuor(f4); - }, o2.prototype.or = function(f4) { - return this.length > f4.length ? this.clone().ior(f4) : f4.clone().ior(this); - }, o2.prototype.uor = function(f4) { - return this.length > f4.length ? this.clone().iuor(f4) : f4.clone().iuor(this); - }, o2.prototype.iuand = function(f4) { - var a3; - this.length > f4.length ? a3 = f4 : a3 = this; - for (var c4 = 0; c4 < a3.length; c4++) - this.words[c4] = this.words[c4] & f4.words[c4]; - return this.length = a3.length, this._strip(); - }, o2.prototype.iand = function(f4) { - return i2((this.negative | f4.negative) === 0), this.iuand(f4); - }, o2.prototype.and = function(f4) { - return this.length > f4.length ? this.clone().iand(f4) : f4.clone().iand(this); - }, o2.prototype.uand = function(f4) { - return this.length > f4.length ? this.clone().iuand(f4) : f4.clone().iuand(this); - }, o2.prototype.iuxor = function(f4) { - var a3, c4; - this.length > f4.length ? (a3 = this, c4 = f4) : (a3 = f4, c4 = this); - for (var d3 = 0; d3 < c4.length; d3++) - this.words[d3] = a3.words[d3] ^ c4.words[d3]; - if (this !== a3) - for (; d3 < a3.length; d3++) - this.words[d3] = a3.words[d3]; - return this.length = a3.length, this._strip(); - }, o2.prototype.ixor = function(f4) { - return i2((this.negative | f4.negative) === 0), this.iuxor(f4); - }, o2.prototype.xor = function(f4) { - return this.length > f4.length ? this.clone().ixor(f4) : f4.clone().ixor(this); - }, o2.prototype.uxor = function(f4) { - return this.length > f4.length ? this.clone().iuxor(f4) : f4.clone().iuxor(this); - }, o2.prototype.inotn = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = Math.ceil(f4 / 26) | 0, c4 = f4 % 26; - this._expand(a3), c4 > 0 && a3--; - for (var d3 = 0; d3 < a3; d3++) - this.words[d3] = ~this.words[d3] & 67108863; - return c4 > 0 && (this.words[d3] = ~this.words[d3] & 67108863 >> 26 - c4), this._strip(); - }, o2.prototype.notn = function(f4) { - return this.clone().inotn(f4); - }, o2.prototype.setn = function(f4, a3) { - i2(typeof f4 == "number" && f4 >= 0); - var c4 = f4 / 26 | 0, d3 = f4 % 26; - return this._expand(c4 + 1), a3 ? this.words[c4] = this.words[c4] | 1 << d3 : this.words[c4] = this.words[c4] & ~(1 << d3), this._strip(); - }, o2.prototype.iadd = function(f4) { - var a3; - if (this.negative !== 0 && f4.negative === 0) - return this.negative = 0, a3 = this.isub(f4), this.negative ^= 1, this._normSign(); - if (this.negative === 0 && f4.negative !== 0) - return f4.negative = 0, a3 = this.isub(f4), f4.negative = 1, a3._normSign(); - var c4, d3; - this.length > f4.length ? (c4 = this, d3 = f4) : (c4 = f4, d3 = this); - for (var m3 = 0, x3 = 0; x3 < d3.length; x3++) - a3 = (c4.words[x3] | 0) + (d3.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; - for (; m3 !== 0 && x3 < c4.length; x3++) - a3 = (c4.words[x3] | 0) + m3, this.words[x3] = a3 & 67108863, m3 = a3 >>> 26; - if (this.length = c4.length, m3 !== 0) - this.words[this.length] = m3, this.length++; - else if (c4 !== this) - for (; x3 < c4.length; x3++) - this.words[x3] = c4.words[x3]; - return this; - }, o2.prototype.add = function(f4) { - var a3; - return f4.negative !== 0 && this.negative === 0 ? (f4.negative = 0, a3 = this.sub(f4), f4.negative ^= 1, a3) : f4.negative === 0 && this.negative !== 0 ? (this.negative = 0, a3 = f4.sub(this), this.negative = 1, a3) : this.length > f4.length ? this.clone().iadd(f4) : f4.clone().iadd(this); - }, o2.prototype.isub = function(f4) { - if (f4.negative !== 0) { - f4.negative = 0; - var a3 = this.iadd(f4); - return f4.negative = 1, a3._normSign(); - } else if (this.negative !== 0) - return this.negative = 0, this.iadd(f4), this.negative = 1, this._normSign(); - var c4 = this.cmp(f4); - if (c4 === 0) - return this.negative = 0, this.length = 1, this.words[0] = 0, this; - var d3, m3; - c4 > 0 ? (d3 = this, m3 = f4) : (d3 = f4, m3 = this); - for (var x3 = 0, M = 0; M < m3.length; M++) - a3 = (d3.words[M] | 0) - (m3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; - for (; x3 !== 0 && M < d3.length; M++) - a3 = (d3.words[M] | 0) + x3, x3 = a3 >> 26, this.words[M] = a3 & 67108863; - if (x3 === 0 && M < d3.length && d3 !== this) - for (; M < d3.length; M++) - this.words[M] = d3.words[M]; - return this.length = Math.max(this.length, M), d3 !== this && (this.negative = 1), this._strip(); - }, o2.prototype.sub = function(f4) { - return this.clone().isub(f4); - }; - function U2(A2, f4, a3) { - a3.negative = f4.negative ^ A2.negative; - var c4 = A2.length + f4.length | 0; - a3.length = c4, c4 = c4 - 1 | 0; - var d3 = A2.words[0] | 0, m3 = f4.words[0] | 0, x3 = d3 * m3, M = x3 & 67108863, l4 = x3 / 67108864 | 0; - a3.words[0] = M; - for (var s2 = 1; s2 < c4; s2++) { - for (var v2 = l4 >>> 26, k4 = l4 & 67108863, u3 = Math.min(s2, f4.length - 1), E4 = Math.max(0, s2 - A2.length + 1); E4 <= u3; E4++) { - var _4 = s2 - E4 | 0; - d3 = A2.words[_4] | 0, m3 = f4.words[E4] | 0, x3 = d3 * m3 + k4, v2 += x3 / 67108864 | 0, k4 = x3 & 67108863; - } - a3.words[s2] = k4 | 0, l4 = v2 | 0; - } - return l4 !== 0 ? a3.words[s2] = l4 | 0 : a3.length--, a3._strip(); - } - var Q = function(f4, a3, c4) { - var d3 = f4.words, m3 = a3.words, x3 = c4.words, M = 0, l4, s2, v2, k4 = d3[0] | 0, u3 = k4 & 8191, E4 = k4 >>> 13, _4 = d3[1] | 0, B2 = _4 & 8191, C3 = _4 >>> 13, D2 = d3[2] | 0, P2 = D2 & 8191, O3 = D2 >>> 13, Ct = d3[3] | 0, T2 = Ct & 8191, q2 = Ct >>> 13, Pe = d3[4] | 0, X = Pe & 8191, Z = Pe >>> 13, Te = d3[5] | 0, $ = Te & 8191, tt = Te >>> 13, Fe = d3[6] | 0, et = Fe & 8191, rt = Fe >>> 13, De = d3[7] | 0, it = De & 8191, nt = De >>> 13, Ue = d3[8] | 0, ft = Ue & 8191, ot = Ue >>> 13, ke = d3[9] | 0, st = ke & 8191, at = ke >>> 13, qe = m3[0] | 0, ut = qe & 8191, ht = qe >>> 13, Ke = m3[1] | 0, ct = Ke & 8191, lt = Ke >>> 13, He = m3[2] | 0, dt = He & 8191, pt = He >>> 13, Le = m3[3] | 0, vt = Le & 8191, gt = Le >>> 13, ze = m3[4] | 0, mt = ze & 8191, At = ze >>> 13, je = m3[5] | 0, bt = je & 8191, yt = je >>> 13, Ve = m3[6] | 0, wt = Ve & 8191, xt = Ve >>> 13, Qe = m3[7] | 0, Mt = Qe & 8191, Et = Qe >>> 13, Je = m3[8] | 0, St = Je & 8191, Nt = Je >>> 13, Ye = m3[9] | 0, It = Ye & 8191, _t = Ye >>> 13; - c4.negative = f4.negative ^ a3.negative, c4.length = 19, l4 = Math.imul(u3, ut), s2 = Math.imul(u3, ht), s2 = s2 + Math.imul(E4, ut) | 0, v2 = Math.imul(E4, ht); - var xe = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (xe >>> 26) | 0, xe &= 67108863, l4 = Math.imul(B2, ut), s2 = Math.imul(B2, ht), s2 = s2 + Math.imul(C3, ut) | 0, v2 = Math.imul(C3, ht), l4 = l4 + Math.imul(u3, ct) | 0, s2 = s2 + Math.imul(u3, lt) | 0, s2 = s2 + Math.imul(E4, ct) | 0, v2 = v2 + Math.imul(E4, lt) | 0; - var Me = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Me >>> 26) | 0, Me &= 67108863, l4 = Math.imul(P2, ut), s2 = Math.imul(P2, ht), s2 = s2 + Math.imul(O3, ut) | 0, v2 = Math.imul(O3, ht), l4 = l4 + Math.imul(B2, ct) | 0, s2 = s2 + Math.imul(B2, lt) | 0, s2 = s2 + Math.imul(C3, ct) | 0, v2 = v2 + Math.imul(C3, lt) | 0, l4 = l4 + Math.imul(u3, dt) | 0, s2 = s2 + Math.imul(u3, pt) | 0, s2 = s2 + Math.imul(E4, dt) | 0, v2 = v2 + Math.imul(E4, pt) | 0; - var Ee = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Ee >>> 26) | 0, Ee &= 67108863, l4 = Math.imul(T2, ut), s2 = Math.imul(T2, ht), s2 = s2 + Math.imul(q2, ut) | 0, v2 = Math.imul(q2, ht), l4 = l4 + Math.imul(P2, ct) | 0, s2 = s2 + Math.imul(P2, lt) | 0, s2 = s2 + Math.imul(O3, ct) | 0, v2 = v2 + Math.imul(O3, lt) | 0, l4 = l4 + Math.imul(B2, dt) | 0, s2 = s2 + Math.imul(B2, pt) | 0, s2 = s2 + Math.imul(C3, dt) | 0, v2 = v2 + Math.imul(C3, pt) | 0, l4 = l4 + Math.imul(u3, vt) | 0, s2 = s2 + Math.imul(u3, gt) | 0, s2 = s2 + Math.imul(E4, vt) | 0, v2 = v2 + Math.imul(E4, gt) | 0; - var Se = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Se >>> 26) | 0, Se &= 67108863, l4 = Math.imul(X, ut), s2 = Math.imul(X, ht), s2 = s2 + Math.imul(Z, ut) | 0, v2 = Math.imul(Z, ht), l4 = l4 + Math.imul(T2, ct) | 0, s2 = s2 + Math.imul(T2, lt) | 0, s2 = s2 + Math.imul(q2, ct) | 0, v2 = v2 + Math.imul(q2, lt) | 0, l4 = l4 + Math.imul(P2, dt) | 0, s2 = s2 + Math.imul(P2, pt) | 0, s2 = s2 + Math.imul(O3, dt) | 0, v2 = v2 + Math.imul(O3, pt) | 0, l4 = l4 + Math.imul(B2, vt) | 0, s2 = s2 + Math.imul(B2, gt) | 0, s2 = s2 + Math.imul(C3, vt) | 0, v2 = v2 + Math.imul(C3, gt) | 0, l4 = l4 + Math.imul(u3, mt) | 0, s2 = s2 + Math.imul(u3, At) | 0, s2 = s2 + Math.imul(E4, mt) | 0, v2 = v2 + Math.imul(E4, At) | 0; - var Ne = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Ne >>> 26) | 0, Ne &= 67108863, l4 = Math.imul($, ut), s2 = Math.imul($, ht), s2 = s2 + Math.imul(tt, ut) | 0, v2 = Math.imul(tt, ht), l4 = l4 + Math.imul(X, ct) | 0, s2 = s2 + Math.imul(X, lt) | 0, s2 = s2 + Math.imul(Z, ct) | 0, v2 = v2 + Math.imul(Z, lt) | 0, l4 = l4 + Math.imul(T2, dt) | 0, s2 = s2 + Math.imul(T2, pt) | 0, s2 = s2 + Math.imul(q2, dt) | 0, v2 = v2 + Math.imul(q2, pt) | 0, l4 = l4 + Math.imul(P2, vt) | 0, s2 = s2 + Math.imul(P2, gt) | 0, s2 = s2 + Math.imul(O3, vt) | 0, v2 = v2 + Math.imul(O3, gt) | 0, l4 = l4 + Math.imul(B2, mt) | 0, s2 = s2 + Math.imul(B2, At) | 0, s2 = s2 + Math.imul(C3, mt) | 0, v2 = v2 + Math.imul(C3, At) | 0, l4 = l4 + Math.imul(u3, bt) | 0, s2 = s2 + Math.imul(u3, yt) | 0, s2 = s2 + Math.imul(E4, bt) | 0, v2 = v2 + Math.imul(E4, yt) | 0; - var Xr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Xr >>> 26) | 0, Xr &= 67108863, l4 = Math.imul(et, ut), s2 = Math.imul(et, ht), s2 = s2 + Math.imul(rt, ut) | 0, v2 = Math.imul(rt, ht), l4 = l4 + Math.imul($, ct) | 0, s2 = s2 + Math.imul($, lt) | 0, s2 = s2 + Math.imul(tt, ct) | 0, v2 = v2 + Math.imul(tt, lt) | 0, l4 = l4 + Math.imul(X, dt) | 0, s2 = s2 + Math.imul(X, pt) | 0, s2 = s2 + Math.imul(Z, dt) | 0, v2 = v2 + Math.imul(Z, pt) | 0, l4 = l4 + Math.imul(T2, vt) | 0, s2 = s2 + Math.imul(T2, gt) | 0, s2 = s2 + Math.imul(q2, vt) | 0, v2 = v2 + Math.imul(q2, gt) | 0, l4 = l4 + Math.imul(P2, mt) | 0, s2 = s2 + Math.imul(P2, At) | 0, s2 = s2 + Math.imul(O3, mt) | 0, v2 = v2 + Math.imul(O3, At) | 0, l4 = l4 + Math.imul(B2, bt) | 0, s2 = s2 + Math.imul(B2, yt) | 0, s2 = s2 + Math.imul(C3, bt) | 0, v2 = v2 + Math.imul(C3, yt) | 0, l4 = l4 + Math.imul(u3, wt) | 0, s2 = s2 + Math.imul(u3, xt) | 0, s2 = s2 + Math.imul(E4, wt) | 0, v2 = v2 + Math.imul(E4, xt) | 0; - var Zr = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (Zr >>> 26) | 0, Zr &= 67108863, l4 = Math.imul(it, ut), s2 = Math.imul(it, ht), s2 = s2 + Math.imul(nt, ut) | 0, v2 = Math.imul(nt, ht), l4 = l4 + Math.imul(et, ct) | 0, s2 = s2 + Math.imul(et, lt) | 0, s2 = s2 + Math.imul(rt, ct) | 0, v2 = v2 + Math.imul(rt, lt) | 0, l4 = l4 + Math.imul($, dt) | 0, s2 = s2 + Math.imul($, pt) | 0, s2 = s2 + Math.imul(tt, dt) | 0, v2 = v2 + Math.imul(tt, pt) | 0, l4 = l4 + Math.imul(X, vt) | 0, s2 = s2 + Math.imul(X, gt) | 0, s2 = s2 + Math.imul(Z, vt) | 0, v2 = v2 + Math.imul(Z, gt) | 0, l4 = l4 + Math.imul(T2, mt) | 0, s2 = s2 + Math.imul(T2, At) | 0, s2 = s2 + Math.imul(q2, mt) | 0, v2 = v2 + Math.imul(q2, At) | 0, l4 = l4 + Math.imul(P2, bt) | 0, s2 = s2 + Math.imul(P2, yt) | 0, s2 = s2 + Math.imul(O3, bt) | 0, v2 = v2 + Math.imul(O3, yt) | 0, l4 = l4 + Math.imul(B2, wt) | 0, s2 = s2 + Math.imul(B2, xt) | 0, s2 = s2 + Math.imul(C3, wt) | 0, v2 = v2 + Math.imul(C3, xt) | 0, l4 = l4 + Math.imul(u3, Mt) | 0, s2 = s2 + Math.imul(u3, Et) | 0, s2 = s2 + Math.imul(E4, Mt) | 0, v2 = v2 + Math.imul(E4, Et) | 0; - var $r = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + ($r >>> 26) | 0, $r &= 67108863, l4 = Math.imul(ft, ut), s2 = Math.imul(ft, ht), s2 = s2 + Math.imul(ot, ut) | 0, v2 = Math.imul(ot, ht), l4 = l4 + Math.imul(it, ct) | 0, s2 = s2 + Math.imul(it, lt) | 0, s2 = s2 + Math.imul(nt, ct) | 0, v2 = v2 + Math.imul(nt, lt) | 0, l4 = l4 + Math.imul(et, dt) | 0, s2 = s2 + Math.imul(et, pt) | 0, s2 = s2 + Math.imul(rt, dt) | 0, v2 = v2 + Math.imul(rt, pt) | 0, l4 = l4 + Math.imul($, vt) | 0, s2 = s2 + Math.imul($, gt) | 0, s2 = s2 + Math.imul(tt, vt) | 0, v2 = v2 + Math.imul(tt, gt) | 0, l4 = l4 + Math.imul(X, mt) | 0, s2 = s2 + Math.imul(X, At) | 0, s2 = s2 + Math.imul(Z, mt) | 0, v2 = v2 + Math.imul(Z, At) | 0, l4 = l4 + Math.imul(T2, bt) | 0, s2 = s2 + Math.imul(T2, yt) | 0, s2 = s2 + Math.imul(q2, bt) | 0, v2 = v2 + Math.imul(q2, yt) | 0, l4 = l4 + Math.imul(P2, wt) | 0, s2 = s2 + Math.imul(P2, xt) | 0, s2 = s2 + Math.imul(O3, wt) | 0, v2 = v2 + Math.imul(O3, xt) | 0, l4 = l4 + Math.imul(B2, Mt) | 0, s2 = s2 + Math.imul(B2, Et) | 0, s2 = s2 + Math.imul(C3, Mt) | 0, v2 = v2 + Math.imul(C3, Et) | 0, l4 = l4 + Math.imul(u3, St) | 0, s2 = s2 + Math.imul(u3, Nt) | 0, s2 = s2 + Math.imul(E4, St) | 0, v2 = v2 + Math.imul(E4, Nt) | 0; - var ti = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ti >>> 26) | 0, ti &= 67108863, l4 = Math.imul(st, ut), s2 = Math.imul(st, ht), s2 = s2 + Math.imul(at, ut) | 0, v2 = Math.imul(at, ht), l4 = l4 + Math.imul(ft, ct) | 0, s2 = s2 + Math.imul(ft, lt) | 0, s2 = s2 + Math.imul(ot, ct) | 0, v2 = v2 + Math.imul(ot, lt) | 0, l4 = l4 + Math.imul(it, dt) | 0, s2 = s2 + Math.imul(it, pt) | 0, s2 = s2 + Math.imul(nt, dt) | 0, v2 = v2 + Math.imul(nt, pt) | 0, l4 = l4 + Math.imul(et, vt) | 0, s2 = s2 + Math.imul(et, gt) | 0, s2 = s2 + Math.imul(rt, vt) | 0, v2 = v2 + Math.imul(rt, gt) | 0, l4 = l4 + Math.imul($, mt) | 0, s2 = s2 + Math.imul($, At) | 0, s2 = s2 + Math.imul(tt, mt) | 0, v2 = v2 + Math.imul(tt, At) | 0, l4 = l4 + Math.imul(X, bt) | 0, s2 = s2 + Math.imul(X, yt) | 0, s2 = s2 + Math.imul(Z, bt) | 0, v2 = v2 + Math.imul(Z, yt) | 0, l4 = l4 + Math.imul(T2, wt) | 0, s2 = s2 + Math.imul(T2, xt) | 0, s2 = s2 + Math.imul(q2, wt) | 0, v2 = v2 + Math.imul(q2, xt) | 0, l4 = l4 + Math.imul(P2, Mt) | 0, s2 = s2 + Math.imul(P2, Et) | 0, s2 = s2 + Math.imul(O3, Mt) | 0, v2 = v2 + Math.imul(O3, Et) | 0, l4 = l4 + Math.imul(B2, St) | 0, s2 = s2 + Math.imul(B2, Nt) | 0, s2 = s2 + Math.imul(C3, St) | 0, v2 = v2 + Math.imul(C3, Nt) | 0, l4 = l4 + Math.imul(u3, It) | 0, s2 = s2 + Math.imul(u3, _t) | 0, s2 = s2 + Math.imul(E4, It) | 0, v2 = v2 + Math.imul(E4, _t) | 0; - var ei = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ei >>> 26) | 0, ei &= 67108863, l4 = Math.imul(st, ct), s2 = Math.imul(st, lt), s2 = s2 + Math.imul(at, ct) | 0, v2 = Math.imul(at, lt), l4 = l4 + Math.imul(ft, dt) | 0, s2 = s2 + Math.imul(ft, pt) | 0, s2 = s2 + Math.imul(ot, dt) | 0, v2 = v2 + Math.imul(ot, pt) | 0, l4 = l4 + Math.imul(it, vt) | 0, s2 = s2 + Math.imul(it, gt) | 0, s2 = s2 + Math.imul(nt, vt) | 0, v2 = v2 + Math.imul(nt, gt) | 0, l4 = l4 + Math.imul(et, mt) | 0, s2 = s2 + Math.imul(et, At) | 0, s2 = s2 + Math.imul(rt, mt) | 0, v2 = v2 + Math.imul(rt, At) | 0, l4 = l4 + Math.imul($, bt) | 0, s2 = s2 + Math.imul($, yt) | 0, s2 = s2 + Math.imul(tt, bt) | 0, v2 = v2 + Math.imul(tt, yt) | 0, l4 = l4 + Math.imul(X, wt) | 0, s2 = s2 + Math.imul(X, xt) | 0, s2 = s2 + Math.imul(Z, wt) | 0, v2 = v2 + Math.imul(Z, xt) | 0, l4 = l4 + Math.imul(T2, Mt) | 0, s2 = s2 + Math.imul(T2, Et) | 0, s2 = s2 + Math.imul(q2, Mt) | 0, v2 = v2 + Math.imul(q2, Et) | 0, l4 = l4 + Math.imul(P2, St) | 0, s2 = s2 + Math.imul(P2, Nt) | 0, s2 = s2 + Math.imul(O3, St) | 0, v2 = v2 + Math.imul(O3, Nt) | 0, l4 = l4 + Math.imul(B2, It) | 0, s2 = s2 + Math.imul(B2, _t) | 0, s2 = s2 + Math.imul(C3, It) | 0, v2 = v2 + Math.imul(C3, _t) | 0; - var ri = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ri >>> 26) | 0, ri &= 67108863, l4 = Math.imul(st, dt), s2 = Math.imul(st, pt), s2 = s2 + Math.imul(at, dt) | 0, v2 = Math.imul(at, pt), l4 = l4 + Math.imul(ft, vt) | 0, s2 = s2 + Math.imul(ft, gt) | 0, s2 = s2 + Math.imul(ot, vt) | 0, v2 = v2 + Math.imul(ot, gt) | 0, l4 = l4 + Math.imul(it, mt) | 0, s2 = s2 + Math.imul(it, At) | 0, s2 = s2 + Math.imul(nt, mt) | 0, v2 = v2 + Math.imul(nt, At) | 0, l4 = l4 + Math.imul(et, bt) | 0, s2 = s2 + Math.imul(et, yt) | 0, s2 = s2 + Math.imul(rt, bt) | 0, v2 = v2 + Math.imul(rt, yt) | 0, l4 = l4 + Math.imul($, wt) | 0, s2 = s2 + Math.imul($, xt) | 0, s2 = s2 + Math.imul(tt, wt) | 0, v2 = v2 + Math.imul(tt, xt) | 0, l4 = l4 + Math.imul(X, Mt) | 0, s2 = s2 + Math.imul(X, Et) | 0, s2 = s2 + Math.imul(Z, Mt) | 0, v2 = v2 + Math.imul(Z, Et) | 0, l4 = l4 + Math.imul(T2, St) | 0, s2 = s2 + Math.imul(T2, Nt) | 0, s2 = s2 + Math.imul(q2, St) | 0, v2 = v2 + Math.imul(q2, Nt) | 0, l4 = l4 + Math.imul(P2, It) | 0, s2 = s2 + Math.imul(P2, _t) | 0, s2 = s2 + Math.imul(O3, It) | 0, v2 = v2 + Math.imul(O3, _t) | 0; - var ii = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ii >>> 26) | 0, ii &= 67108863, l4 = Math.imul(st, vt), s2 = Math.imul(st, gt), s2 = s2 + Math.imul(at, vt) | 0, v2 = Math.imul(at, gt), l4 = l4 + Math.imul(ft, mt) | 0, s2 = s2 + Math.imul(ft, At) | 0, s2 = s2 + Math.imul(ot, mt) | 0, v2 = v2 + Math.imul(ot, At) | 0, l4 = l4 + Math.imul(it, bt) | 0, s2 = s2 + Math.imul(it, yt) | 0, s2 = s2 + Math.imul(nt, bt) | 0, v2 = v2 + Math.imul(nt, yt) | 0, l4 = l4 + Math.imul(et, wt) | 0, s2 = s2 + Math.imul(et, xt) | 0, s2 = s2 + Math.imul(rt, wt) | 0, v2 = v2 + Math.imul(rt, xt) | 0, l4 = l4 + Math.imul($, Mt) | 0, s2 = s2 + Math.imul($, Et) | 0, s2 = s2 + Math.imul(tt, Mt) | 0, v2 = v2 + Math.imul(tt, Et) | 0, l4 = l4 + Math.imul(X, St) | 0, s2 = s2 + Math.imul(X, Nt) | 0, s2 = s2 + Math.imul(Z, St) | 0, v2 = v2 + Math.imul(Z, Nt) | 0, l4 = l4 + Math.imul(T2, It) | 0, s2 = s2 + Math.imul(T2, _t) | 0, s2 = s2 + Math.imul(q2, It) | 0, v2 = v2 + Math.imul(q2, _t) | 0; - var ni = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ni >>> 26) | 0, ni &= 67108863, l4 = Math.imul(st, mt), s2 = Math.imul(st, At), s2 = s2 + Math.imul(at, mt) | 0, v2 = Math.imul(at, At), l4 = l4 + Math.imul(ft, bt) | 0, s2 = s2 + Math.imul(ft, yt) | 0, s2 = s2 + Math.imul(ot, bt) | 0, v2 = v2 + Math.imul(ot, yt) | 0, l4 = l4 + Math.imul(it, wt) | 0, s2 = s2 + Math.imul(it, xt) | 0, s2 = s2 + Math.imul(nt, wt) | 0, v2 = v2 + Math.imul(nt, xt) | 0, l4 = l4 + Math.imul(et, Mt) | 0, s2 = s2 + Math.imul(et, Et) | 0, s2 = s2 + Math.imul(rt, Mt) | 0, v2 = v2 + Math.imul(rt, Et) | 0, l4 = l4 + Math.imul($, St) | 0, s2 = s2 + Math.imul($, Nt) | 0, s2 = s2 + Math.imul(tt, St) | 0, v2 = v2 + Math.imul(tt, Nt) | 0, l4 = l4 + Math.imul(X, It) | 0, s2 = s2 + Math.imul(X, _t) | 0, s2 = s2 + Math.imul(Z, It) | 0, v2 = v2 + Math.imul(Z, _t) | 0; - var fi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (fi >>> 26) | 0, fi &= 67108863, l4 = Math.imul(st, bt), s2 = Math.imul(st, yt), s2 = s2 + Math.imul(at, bt) | 0, v2 = Math.imul(at, yt), l4 = l4 + Math.imul(ft, wt) | 0, s2 = s2 + Math.imul(ft, xt) | 0, s2 = s2 + Math.imul(ot, wt) | 0, v2 = v2 + Math.imul(ot, xt) | 0, l4 = l4 + Math.imul(it, Mt) | 0, s2 = s2 + Math.imul(it, Et) | 0, s2 = s2 + Math.imul(nt, Mt) | 0, v2 = v2 + Math.imul(nt, Et) | 0, l4 = l4 + Math.imul(et, St) | 0, s2 = s2 + Math.imul(et, Nt) | 0, s2 = s2 + Math.imul(rt, St) | 0, v2 = v2 + Math.imul(rt, Nt) | 0, l4 = l4 + Math.imul($, It) | 0, s2 = s2 + Math.imul($, _t) | 0, s2 = s2 + Math.imul(tt, It) | 0, v2 = v2 + Math.imul(tt, _t) | 0; - var oi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (oi >>> 26) | 0, oi &= 67108863, l4 = Math.imul(st, wt), s2 = Math.imul(st, xt), s2 = s2 + Math.imul(at, wt) | 0, v2 = Math.imul(at, xt), l4 = l4 + Math.imul(ft, Mt) | 0, s2 = s2 + Math.imul(ft, Et) | 0, s2 = s2 + Math.imul(ot, Mt) | 0, v2 = v2 + Math.imul(ot, Et) | 0, l4 = l4 + Math.imul(it, St) | 0, s2 = s2 + Math.imul(it, Nt) | 0, s2 = s2 + Math.imul(nt, St) | 0, v2 = v2 + Math.imul(nt, Nt) | 0, l4 = l4 + Math.imul(et, It) | 0, s2 = s2 + Math.imul(et, _t) | 0, s2 = s2 + Math.imul(rt, It) | 0, v2 = v2 + Math.imul(rt, _t) | 0; - var si = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (si >>> 26) | 0, si &= 67108863, l4 = Math.imul(st, Mt), s2 = Math.imul(st, Et), s2 = s2 + Math.imul(at, Mt) | 0, v2 = Math.imul(at, Et), l4 = l4 + Math.imul(ft, St) | 0, s2 = s2 + Math.imul(ft, Nt) | 0, s2 = s2 + Math.imul(ot, St) | 0, v2 = v2 + Math.imul(ot, Nt) | 0, l4 = l4 + Math.imul(it, It) | 0, s2 = s2 + Math.imul(it, _t) | 0, s2 = s2 + Math.imul(nt, It) | 0, v2 = v2 + Math.imul(nt, _t) | 0; - var ai = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ai >>> 26) | 0, ai &= 67108863, l4 = Math.imul(st, St), s2 = Math.imul(st, Nt), s2 = s2 + Math.imul(at, St) | 0, v2 = Math.imul(at, Nt), l4 = l4 + Math.imul(ft, It) | 0, s2 = s2 + Math.imul(ft, _t) | 0, s2 = s2 + Math.imul(ot, It) | 0, v2 = v2 + Math.imul(ot, _t) | 0; - var ui = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - M = (v2 + (s2 >>> 13) | 0) + (ui >>> 26) | 0, ui &= 67108863, l4 = Math.imul(st, It), s2 = Math.imul(st, _t), s2 = s2 + Math.imul(at, It) | 0, v2 = Math.imul(at, _t); - var hi = (M + l4 | 0) + ((s2 & 8191) << 13) | 0; - return M = (v2 + (s2 >>> 13) | 0) + (hi >>> 26) | 0, hi &= 67108863, x3[0] = xe, x3[1] = Me, x3[2] = Ee, x3[3] = Se, x3[4] = Ne, x3[5] = Xr, x3[6] = Zr, x3[7] = $r, x3[8] = ti, x3[9] = ei, x3[10] = ri, x3[11] = ii, x3[12] = ni, x3[13] = fi, x3[14] = oi, x3[15] = si, x3[16] = ai, x3[17] = ui, x3[18] = hi, M !== 0 && (x3[19] = M, c4.length++), c4; - }; - Math.imul || (Q = U2); - function Bt(A2, f4, a3) { - a3.negative = f4.negative ^ A2.negative, a3.length = A2.length + f4.length; - for (var c4 = 0, d3 = 0, m3 = 0; m3 < a3.length - 1; m3++) { - var x3 = d3; - d3 = 0; - for (var M = c4 & 67108863, l4 = Math.min(m3, f4.length - 1), s2 = Math.max(0, m3 - A2.length + 1); s2 <= l4; s2++) { - var v2 = m3 - s2, k4 = A2.words[v2] | 0, u3 = f4.words[s2] | 0, E4 = k4 * u3, _4 = E4 & 67108863; - x3 = x3 + (E4 / 67108864 | 0) | 0, _4 = _4 + M | 0, M = _4 & 67108863, x3 = x3 + (_4 >>> 26) | 0, d3 += x3 >>> 26, x3 &= 67108863; - } - a3.words[m3] = M, c4 = x3, x3 = d3; - } - return c4 !== 0 ? a3.words[m3] = c4 : a3.length--, a3._strip(); - } - function J(A2, f4, a3) { - return Bt(A2, f4, a3); - } - o2.prototype.mulTo = function(f4, a3) { - var c4, d3 = this.length + f4.length; - return this.length === 10 && f4.length === 10 ? c4 = Q(this, f4, a3) : d3 < 63 ? c4 = U2(this, f4, a3) : d3 < 1024 ? c4 = Bt(this, f4, a3) : c4 = J(this, f4, a3), c4; - }, o2.prototype.mul = function(f4) { - var a3 = new o2(null); - return a3.words = new Array(this.length + f4.length), this.mulTo(f4, a3); - }, o2.prototype.mulf = function(f4) { - var a3 = new o2(null); - return a3.words = new Array(this.length + f4.length), J(this, f4, a3); - }, o2.prototype.imul = function(f4) { - return this.clone().mulTo(f4, this); - }, o2.prototype.imuln = function(f4) { - var a3 = f4 < 0; - a3 && (f4 = -f4), i2(typeof f4 == "number"), i2(f4 < 67108864); - for (var c4 = 0, d3 = 0; d3 < this.length; d3++) { - var m3 = (this.words[d3] | 0) * f4, x3 = (m3 & 67108863) + (c4 & 67108863); - c4 >>= 26, c4 += m3 / 67108864 | 0, c4 += x3 >>> 26, this.words[d3] = x3 & 67108863; - } - return c4 !== 0 && (this.words[d3] = c4, this.length++), a3 ? this.ineg() : this; - }, o2.prototype.muln = function(f4) { - return this.clone().imuln(f4); - }, o2.prototype.sqr = function() { - return this.mul(this); - }, o2.prototype.isqr = function() { - return this.imul(this.clone()); - }, o2.prototype.pow = function(f4) { - var a3 = F(f4); - if (a3.length === 0) - return new o2(1); - for (var c4 = this, d3 = 0; d3 < a3.length && a3[d3] === 0; d3++, c4 = c4.sqr()) - ; - if (++d3 < a3.length) - for (var m3 = c4.sqr(); d3 < a3.length; d3++, m3 = m3.sqr()) - a3[d3] !== 0 && (c4 = c4.mul(m3)); - return c4; - }, o2.prototype.iushln = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 67108863 >>> 26 - a3 << 26 - a3, m3; - if (a3 !== 0) { - var x3 = 0; - for (m3 = 0; m3 < this.length; m3++) { - var M = this.words[m3] & d3, l4 = (this.words[m3] | 0) - M << a3; - this.words[m3] = l4 | x3, x3 = M >>> 26 - a3; - } - x3 && (this.words[m3] = x3, this.length++); - } - if (c4 !== 0) { - for (m3 = this.length - 1; m3 >= 0; m3--) - this.words[m3 + c4] = this.words[m3]; - for (m3 = 0; m3 < c4; m3++) - this.words[m3] = 0; - this.length += c4; - } - return this._strip(); - }, o2.prototype.ishln = function(f4) { - return i2(this.negative === 0), this.iushln(f4); - }, o2.prototype.iushrn = function(f4, a3, c4) { - i2(typeof f4 == "number" && f4 >= 0); - var d3; - a3 ? d3 = (a3 - a3 % 26) / 26 : d3 = 0; - var m3 = f4 % 26, x3 = Math.min((f4 - m3) / 26, this.length), M = 67108863 ^ 67108863 >>> m3 << m3, l4 = c4; - if (d3 -= x3, d3 = Math.max(0, d3), l4) { - for (var s2 = 0; s2 < x3; s2++) - l4.words[s2] = this.words[s2]; - l4.length = x3; - } - if (x3 !== 0) - if (this.length > x3) - for (this.length -= x3, s2 = 0; s2 < this.length; s2++) - this.words[s2] = this.words[s2 + x3]; - else - this.words[0] = 0, this.length = 1; - var v2 = 0; - for (s2 = this.length - 1; s2 >= 0 && (v2 !== 0 || s2 >= d3); s2--) { - var k4 = this.words[s2] | 0; - this.words[s2] = v2 << 26 - m3 | k4 >>> m3, v2 = k4 & M; - } - return l4 && v2 !== 0 && (l4.words[l4.length++] = v2), this.length === 0 && (this.words[0] = 0, this.length = 1), this._strip(); - }, o2.prototype.ishrn = function(f4, a3, c4) { - return i2(this.negative === 0), this.iushrn(f4, a3, c4); - }, o2.prototype.shln = function(f4) { - return this.clone().ishln(f4); - }, o2.prototype.ushln = function(f4) { - return this.clone().iushln(f4); - }, o2.prototype.shrn = function(f4) { - return this.clone().ishrn(f4); - }, o2.prototype.ushrn = function(f4) { - return this.clone().iushrn(f4); - }, o2.prototype.testn = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; - if (this.length <= c4) - return false; - var m3 = this.words[c4]; - return !!(m3 & d3); - }, o2.prototype.imaskn = function(f4) { - i2(typeof f4 == "number" && f4 >= 0); - var a3 = f4 % 26, c4 = (f4 - a3) / 26; - if (i2(this.negative === 0, "imaskn works only with positive numbers"), this.length <= c4) - return this; - if (a3 !== 0 && c4++, this.length = Math.min(c4, this.length), a3 !== 0) { - var d3 = 67108863 ^ 67108863 >>> a3 << a3; - this.words[this.length - 1] &= d3; - } - return this._strip(); - }, o2.prototype.maskn = function(f4) { - return this.clone().imaskn(f4); - }, o2.prototype.iaddn = function(f4) { - return i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0 ? this.isubn(-f4) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) <= f4 ? (this.words[0] = f4 - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(f4), this.negative = 1, this) : this._iaddn(f4); - }, o2.prototype._iaddn = function(f4) { - this.words[0] += f4; - for (var a3 = 0; a3 < this.length && this.words[a3] >= 67108864; a3++) - this.words[a3] -= 67108864, a3 === this.length - 1 ? this.words[a3 + 1] = 1 : this.words[a3 + 1]++; - return this.length = Math.max(this.length, a3 + 1), this; - }, o2.prototype.isubn = function(f4) { - if (i2(typeof f4 == "number"), i2(f4 < 67108864), f4 < 0) - return this.iaddn(-f4); - if (this.negative !== 0) - return this.negative = 0, this.iaddn(f4), this.negative = 1, this; - if (this.words[0] -= f4, this.length === 1 && this.words[0] < 0) - this.words[0] = -this.words[0], this.negative = 1; - else - for (var a3 = 0; a3 < this.length && this.words[a3] < 0; a3++) - this.words[a3] += 67108864, this.words[a3 + 1] -= 1; - return this._strip(); - }, o2.prototype.addn = function(f4) { - return this.clone().iaddn(f4); - }, o2.prototype.subn = function(f4) { - return this.clone().isubn(f4); - }, o2.prototype.iabs = function() { - return this.negative = 0, this; - }, o2.prototype.abs = function() { - return this.clone().iabs(); - }, o2.prototype._ishlnsubmul = function(f4, a3, c4) { - var d3 = f4.length + c4, m3; - this._expand(d3); - var x3, M = 0; - for (m3 = 0; m3 < f4.length; m3++) { - x3 = (this.words[m3 + c4] | 0) + M; - var l4 = (f4.words[m3] | 0) * a3; - x3 -= l4 & 67108863, M = (x3 >> 26) - (l4 / 67108864 | 0), this.words[m3 + c4] = x3 & 67108863; - } - for (; m3 < this.length - c4; m3++) - x3 = (this.words[m3 + c4] | 0) + M, M = x3 >> 26, this.words[m3 + c4] = x3 & 67108863; - if (M === 0) - return this._strip(); - for (i2(M === -1), M = 0, m3 = 0; m3 < this.length; m3++) - x3 = -(this.words[m3] | 0) + M, M = x3 >> 26, this.words[m3] = x3 & 67108863; - return this.negative = 1, this._strip(); - }, o2.prototype._wordDiv = function(f4, a3) { - var c4 = this.length - f4.length, d3 = this.clone(), m3 = f4, x3 = m3.words[m3.length - 1] | 0, M = this._countBits(x3); - c4 = 26 - M, c4 !== 0 && (m3 = m3.ushln(c4), d3.iushln(c4), x3 = m3.words[m3.length - 1] | 0); - var l4 = d3.length - m3.length, s2; - if (a3 !== "mod") { - s2 = new o2(null), s2.length = l4 + 1, s2.words = new Array(s2.length); - for (var v2 = 0; v2 < s2.length; v2++) - s2.words[v2] = 0; - } - var k4 = d3.clone()._ishlnsubmul(m3, 1, l4); - k4.negative === 0 && (d3 = k4, s2 && (s2.words[l4] = 1)); - for (var u3 = l4 - 1; u3 >= 0; u3--) { - var E4 = (d3.words[m3.length + u3] | 0) * 67108864 + (d3.words[m3.length + u3 - 1] | 0); - for (E4 = Math.min(E4 / x3 | 0, 67108863), d3._ishlnsubmul(m3, E4, u3); d3.negative !== 0; ) - E4--, d3.negative = 0, d3._ishlnsubmul(m3, 1, u3), d3.isZero() || (d3.negative ^= 1); - s2 && (s2.words[u3] = E4); - } - return s2 && s2._strip(), d3._strip(), a3 !== "div" && c4 !== 0 && d3.iushrn(c4), { div: s2 || null, mod: d3 }; - }, o2.prototype.divmod = function(f4, a3, c4) { - if (i2(!f4.isZero()), this.isZero()) - return { div: new o2(0), mod: new o2(0) }; - var d3, m3, x3; - return this.negative !== 0 && f4.negative === 0 ? (x3 = this.neg().divmod(f4, a3), a3 !== "mod" && (d3 = x3.div.neg()), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.iadd(f4)), { div: d3, mod: m3 }) : this.negative === 0 && f4.negative !== 0 ? (x3 = this.divmod(f4.neg(), a3), a3 !== "mod" && (d3 = x3.div.neg()), { div: d3, mod: x3.mod }) : this.negative & f4.negative ? (x3 = this.neg().divmod(f4.neg(), a3), a3 !== "div" && (m3 = x3.mod.neg(), c4 && m3.negative !== 0 && m3.isub(f4)), { div: x3.div, mod: m3 }) : f4.length > this.length || this.cmp(f4) < 0 ? { div: new o2(0), mod: this } : f4.length === 1 ? a3 === "div" ? { div: this.divn(f4.words[0]), mod: null } : a3 === "mod" ? { div: null, mod: new o2(this.modrn(f4.words[0])) } : { div: this.divn(f4.words[0]), mod: new o2(this.modrn(f4.words[0])) } : this._wordDiv(f4, a3); - }, o2.prototype.div = function(f4) { - return this.divmod(f4, "div", false).div; - }, o2.prototype.mod = function(f4) { - return this.divmod(f4, "mod", false).mod; - }, o2.prototype.umod = function(f4) { - return this.divmod(f4, "mod", true).mod; - }, o2.prototype.divRound = function(f4) { - var a3 = this.divmod(f4); - if (a3.mod.isZero()) - return a3.div; - var c4 = a3.div.negative !== 0 ? a3.mod.isub(f4) : a3.mod, d3 = f4.ushrn(1), m3 = f4.andln(1), x3 = c4.cmp(d3); - return x3 < 0 || m3 === 1 && x3 === 0 ? a3.div : a3.div.negative !== 0 ? a3.div.isubn(1) : a3.div.iaddn(1); - }, o2.prototype.modrn = function(f4) { - var a3 = f4 < 0; - a3 && (f4 = -f4), i2(f4 <= 67108863); - for (var c4 = (1 << 26) % f4, d3 = 0, m3 = this.length - 1; m3 >= 0; m3--) - d3 = (c4 * d3 + (this.words[m3] | 0)) % f4; - return a3 ? -d3 : d3; - }, o2.prototype.modn = function(f4) { - return this.modrn(f4); - }, o2.prototype.idivn = function(f4) { - var a3 = f4 < 0; - a3 && (f4 = -f4), i2(f4 <= 67108863); - for (var c4 = 0, d3 = this.length - 1; d3 >= 0; d3--) { - var m3 = (this.words[d3] | 0) + c4 * 67108864; - this.words[d3] = m3 / f4 | 0, c4 = m3 % f4; - } - return this._strip(), a3 ? this.ineg() : this; - }, o2.prototype.divn = function(f4) { - return this.clone().idivn(f4); - }, o2.prototype.egcd = function(f4) { - i2(f4.negative === 0), i2(!f4.isZero()); - var a3 = this, c4 = f4.clone(); - a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); - for (var d3 = new o2(1), m3 = new o2(0), x3 = new o2(0), M = new o2(1), l4 = 0; a3.isEven() && c4.isEven(); ) - a3.iushrn(1), c4.iushrn(1), ++l4; - for (var s2 = c4.clone(), v2 = a3.clone(); !a3.isZero(); ) { - for (var k4 = 0, u3 = 1; !(a3.words[0] & u3) && k4 < 26; ++k4, u3 <<= 1) - ; - if (k4 > 0) - for (a3.iushrn(k4); k4-- > 0; ) - (d3.isOdd() || m3.isOdd()) && (d3.iadd(s2), m3.isub(v2)), d3.iushrn(1), m3.iushrn(1); - for (var E4 = 0, _4 = 1; !(c4.words[0] & _4) && E4 < 26; ++E4, _4 <<= 1) - ; - if (E4 > 0) - for (c4.iushrn(E4); E4-- > 0; ) - (x3.isOdd() || M.isOdd()) && (x3.iadd(s2), M.isub(v2)), x3.iushrn(1), M.iushrn(1); - a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(x3), m3.isub(M)) : (c4.isub(a3), x3.isub(d3), M.isub(m3)); - } - return { a: x3, b: M, gcd: c4.iushln(l4) }; - }, o2.prototype._invmp = function(f4) { - i2(f4.negative === 0), i2(!f4.isZero()); - var a3 = this, c4 = f4.clone(); - a3.negative !== 0 ? a3 = a3.umod(f4) : a3 = a3.clone(); - for (var d3 = new o2(1), m3 = new o2(0), x3 = c4.clone(); a3.cmpn(1) > 0 && c4.cmpn(1) > 0; ) { - for (var M = 0, l4 = 1; !(a3.words[0] & l4) && M < 26; ++M, l4 <<= 1) - ; - if (M > 0) - for (a3.iushrn(M); M-- > 0; ) - d3.isOdd() && d3.iadd(x3), d3.iushrn(1); - for (var s2 = 0, v2 = 1; !(c4.words[0] & v2) && s2 < 26; ++s2, v2 <<= 1) - ; - if (s2 > 0) - for (c4.iushrn(s2); s2-- > 0; ) - m3.isOdd() && m3.iadd(x3), m3.iushrn(1); - a3.cmp(c4) >= 0 ? (a3.isub(c4), d3.isub(m3)) : (c4.isub(a3), m3.isub(d3)); - } - var k4; - return a3.cmpn(1) === 0 ? k4 = d3 : k4 = m3, k4.cmpn(0) < 0 && k4.iadd(f4), k4; - }, o2.prototype.gcd = function(f4) { - if (this.isZero()) - return f4.abs(); - if (f4.isZero()) - return this.abs(); - var a3 = this.clone(), c4 = f4.clone(); - a3.negative = 0, c4.negative = 0; - for (var d3 = 0; a3.isEven() && c4.isEven(); d3++) - a3.iushrn(1), c4.iushrn(1); - do { - for (; a3.isEven(); ) - a3.iushrn(1); - for (; c4.isEven(); ) - c4.iushrn(1); - var m3 = a3.cmp(c4); - if (m3 < 0) { - var x3 = a3; - a3 = c4, c4 = x3; - } else if (m3 === 0 || c4.cmpn(1) === 0) - break; - a3.isub(c4); - } while (true); - return c4.iushln(d3); - }, o2.prototype.invm = function(f4) { - return this.egcd(f4).a.umod(f4); - }, o2.prototype.isEven = function() { - return (this.words[0] & 1) === 0; - }, o2.prototype.isOdd = function() { - return (this.words[0] & 1) === 1; - }, o2.prototype.andln = function(f4) { - return this.words[0] & f4; - }, o2.prototype.bincn = function(f4) { - i2(typeof f4 == "number"); - var a3 = f4 % 26, c4 = (f4 - a3) / 26, d3 = 1 << a3; - if (this.length <= c4) - return this._expand(c4 + 1), this.words[c4] |= d3, this; - for (var m3 = d3, x3 = c4; m3 !== 0 && x3 < this.length; x3++) { - var M = this.words[x3] | 0; - M += m3, m3 = M >>> 26, M &= 67108863, this.words[x3] = M; - } - return m3 !== 0 && (this.words[x3] = m3, this.length++), this; - }, o2.prototype.isZero = function() { - return this.length === 1 && this.words[0] === 0; - }, o2.prototype.cmpn = function(f4) { - var a3 = f4 < 0; - if (this.negative !== 0 && !a3) - return -1; - if (this.negative === 0 && a3) - return 1; - this._strip(); - var c4; - if (this.length > 1) - c4 = 1; - else { - a3 && (f4 = -f4), i2(f4 <= 67108863, "Number is too big"); - var d3 = this.words[0] | 0; - c4 = d3 === f4 ? 0 : d3 < f4 ? -1 : 1; - } - return this.negative !== 0 ? -c4 | 0 : c4; - }, o2.prototype.cmp = function(f4) { - if (this.negative !== 0 && f4.negative === 0) - return -1; - if (this.negative === 0 && f4.negative !== 0) - return 1; - var a3 = this.ucmp(f4); - return this.negative !== 0 ? -a3 | 0 : a3; - }, o2.prototype.ucmp = function(f4) { - if (this.length > f4.length) - return 1; - if (this.length < f4.length) - return -1; - for (var a3 = 0, c4 = this.length - 1; c4 >= 0; c4--) { - var d3 = this.words[c4] | 0, m3 = f4.words[c4] | 0; - if (d3 !== m3) { - d3 < m3 ? a3 = -1 : d3 > m3 && (a3 = 1); - break; - } - } - return a3; - }, o2.prototype.gtn = function(f4) { - return this.cmpn(f4) === 1; - }, o2.prototype.gt = function(f4) { - return this.cmp(f4) === 1; - }, o2.prototype.gten = function(f4) { - return this.cmpn(f4) >= 0; - }, o2.prototype.gte = function(f4) { - return this.cmp(f4) >= 0; - }, o2.prototype.ltn = function(f4) { - return this.cmpn(f4) === -1; - }, o2.prototype.lt = function(f4) { - return this.cmp(f4) === -1; - }, o2.prototype.lten = function(f4) { - return this.cmpn(f4) <= 0; - }, o2.prototype.lte = function(f4) { - return this.cmp(f4) <= 0; - }, o2.prototype.eqn = function(f4) { - return this.cmpn(f4) === 0; - }, o2.prototype.eq = function(f4) { - return this.cmp(f4) === 0; - }, o2.red = function(f4) { - return new Y(f4); - }, o2.prototype.toRed = function(f4) { - return i2(!this.red, "Already a number in reduction context"), i2(this.negative === 0, "red works only with positives"), f4.convertTo(this)._forceRed(f4); - }, o2.prototype.fromRed = function() { - return i2(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }, o2.prototype._forceRed = function(f4) { - return this.red = f4, this; - }, o2.prototype.forceRed = function(f4) { - return i2(!this.red, "Already a number in reduction context"), this._forceRed(f4); - }, o2.prototype.redAdd = function(f4) { - return i2(this.red, "redAdd works only with red numbers"), this.red.add(this, f4); - }, o2.prototype.redIAdd = function(f4) { - return i2(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, f4); - }, o2.prototype.redSub = function(f4) { - return i2(this.red, "redSub works only with red numbers"), this.red.sub(this, f4); - }, o2.prototype.redISub = function(f4) { - return i2(this.red, "redISub works only with red numbers"), this.red.isub(this, f4); - }, o2.prototype.redShl = function(f4) { - return i2(this.red, "redShl works only with red numbers"), this.red.shl(this, f4); - }, o2.prototype.redMul = function(f4) { - return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.mul(this, f4); - }, o2.prototype.redIMul = function(f4) { - return i2(this.red, "redMul works only with red numbers"), this.red._verify2(this, f4), this.red.imul(this, f4); - }, o2.prototype.redSqr = function() { - return i2(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }, o2.prototype.redISqr = function() { - return i2(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }, o2.prototype.redSqrt = function() { - return i2(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }, o2.prototype.redInvm = function() { - return i2(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }, o2.prototype.redNeg = function() { - return i2(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }, o2.prototype.redPow = function(f4) { - return i2(this.red && !f4.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, f4); - }; - var H = { k256: null, p224: null, p192: null, p25519: null }; - function L2(A2, f4) { - this.name = A2, this.p = new o2(f4, 16), this.n = this.p.bitLength(), this.k = new o2(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); - } - L2.prototype._tmp = function() { - var f4 = new o2(null); - return f4.words = new Array(Math.ceil(this.n / 13)), f4; - }, L2.prototype.ireduce = function(f4) { - var a3 = f4, c4; - do - this.split(a3, this.tmp), a3 = this.imulK(a3), a3 = a3.iadd(this.tmp), c4 = a3.bitLength(); - while (c4 > this.n); - var d3 = c4 < this.n ? -1 : a3.ucmp(this.p); - return d3 === 0 ? (a3.words[0] = 0, a3.length = 1) : d3 > 0 ? a3.isub(this.p) : a3.strip !== void 0 ? a3.strip() : a3._strip(), a3; - }, L2.prototype.split = function(f4, a3) { - f4.iushrn(this.n, 0, a3); - }, L2.prototype.imulK = function(f4) { - return f4.imul(this.k); - }; - function Tt() { - L2.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - n3(Tt, L2), Tt.prototype.split = function(f4, a3) { - for (var c4 = 4194303, d3 = Math.min(f4.length, 9), m3 = 0; m3 < d3; m3++) - a3.words[m3] = f4.words[m3]; - if (a3.length = d3, f4.length <= 9) { - f4.words[0] = 0, f4.length = 1; - return; - } - var x3 = f4.words[9]; - for (a3.words[a3.length++] = x3 & c4, m3 = 10; m3 < f4.length; m3++) { - var M = f4.words[m3] | 0; - f4.words[m3 - 10] = (M & c4) << 4 | x3 >>> 22, x3 = M; - } - x3 >>>= 22, f4.words[m3 - 10] = x3, x3 === 0 && f4.length > 10 ? f4.length -= 10 : f4.length -= 9; - }, Tt.prototype.imulK = function(f4) { - f4.words[f4.length] = 0, f4.words[f4.length + 1] = 0, f4.length += 2; - for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { - var d3 = f4.words[c4] | 0; - a3 += d3 * 977, f4.words[c4] = a3 & 67108863, a3 = d3 * 64 + (a3 / 67108864 | 0); - } - return f4.words[f4.length - 1] === 0 && (f4.length--, f4.words[f4.length - 1] === 0 && f4.length--), f4; - }; - function W() { - L2.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - n3(W, L2); - function Ot() { - L2.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - n3(Ot, L2); - function Gt() { - L2.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - n3(Gt, L2), Gt.prototype.imulK = function(f4) { - for (var a3 = 0, c4 = 0; c4 < f4.length; c4++) { - var d3 = (f4.words[c4] | 0) * 19 + a3, m3 = d3 & 67108863; - d3 >>>= 26, f4.words[c4] = m3, a3 = d3; - } - return a3 !== 0 && (f4.words[f4.length++] = a3), f4; - }, o2._prime = function(f4) { - if (H[f4]) - return H[f4]; - var a3; - if (f4 === "k256") - a3 = new Tt(); - else if (f4 === "p224") - a3 = new W(); - else if (f4 === "p192") - a3 = new Ot(); - else if (f4 === "p25519") - a3 = new Gt(); - else - throw new Error("Unknown prime " + f4); - return H[f4] = a3, a3; - }; - function Y(A2) { - if (typeof A2 == "string") { - var f4 = o2._prime(A2); - this.m = f4.p, this.prime = f4; - } else - i2(A2.gtn(1), "modulus must be greater than 1"), this.m = A2, this.prime = null; - } - Y.prototype._verify1 = function(f4) { - i2(f4.negative === 0, "red works only with positives"), i2(f4.red, "red works only with red numbers"); - }, Y.prototype._verify2 = function(f4, a3) { - i2((f4.negative | a3.negative) === 0, "red works only with positives"), i2(f4.red && f4.red === a3.red, "red works only with red numbers"); - }, Y.prototype.imod = function(f4) { - return this.prime ? this.prime.ireduce(f4)._forceRed(this) : (w4(f4, f4.umod(this.m)._forceRed(this)), f4); - }, Y.prototype.neg = function(f4) { - return f4.isZero() ? f4.clone() : this.m.sub(f4)._forceRed(this); - }, Y.prototype.add = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.add(a3); - return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4._forceRed(this); - }, Y.prototype.iadd = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.iadd(a3); - return c4.cmp(this.m) >= 0 && c4.isub(this.m), c4; - }, Y.prototype.sub = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.sub(a3); - return c4.cmpn(0) < 0 && c4.iadd(this.m), c4._forceRed(this); - }, Y.prototype.isub = function(f4, a3) { - this._verify2(f4, a3); - var c4 = f4.isub(a3); - return c4.cmpn(0) < 0 && c4.iadd(this.m), c4; - }, Y.prototype.shl = function(f4, a3) { - return this._verify1(f4), this.imod(f4.ushln(a3)); - }, Y.prototype.imul = function(f4, a3) { - return this._verify2(f4, a3), this.imod(f4.imul(a3)); - }, Y.prototype.mul = function(f4, a3) { - return this._verify2(f4, a3), this.imod(f4.mul(a3)); - }, Y.prototype.isqr = function(f4) { - return this.imul(f4, f4.clone()); - }, Y.prototype.sqr = function(f4) { - return this.mul(f4, f4); - }, Y.prototype.sqrt = function(f4) { - if (f4.isZero()) - return f4.clone(); - var a3 = this.m.andln(3); - if (i2(a3 % 2 === 1), a3 === 3) { - var c4 = this.m.add(new o2(1)).iushrn(2); - return this.pow(f4, c4); - } - for (var d3 = this.m.subn(1), m3 = 0; !d3.isZero() && d3.andln(1) === 0; ) - m3++, d3.iushrn(1); - i2(!d3.isZero()); - var x3 = new o2(1).toRed(this), M = x3.redNeg(), l4 = this.m.subn(1).iushrn(1), s2 = this.m.bitLength(); - for (s2 = new o2(2 * s2 * s2).toRed(this); this.pow(s2, l4).cmp(M) !== 0; ) - s2.redIAdd(M); - for (var v2 = this.pow(s2, d3), k4 = this.pow(f4, d3.addn(1).iushrn(1)), u3 = this.pow(f4, d3), E4 = m3; u3.cmp(x3) !== 0; ) { - for (var _4 = u3, B2 = 0; _4.cmp(x3) !== 0; B2++) - _4 = _4.redSqr(); - i2(B2 < E4); - var C3 = this.pow(v2, new o2(1).iushln(E4 - B2 - 1)); - k4 = k4.redMul(C3), v2 = C3.redSqr(), u3 = u3.redMul(v2), E4 = B2; - } - return k4; - }, Y.prototype.invm = function(f4) { - var a3 = f4._invmp(this.m); - return a3.negative !== 0 ? (a3.negative = 0, this.imod(a3).redNeg()) : this.imod(a3); - }, Y.prototype.pow = function(f4, a3) { - if (a3.isZero()) - return new o2(1).toRed(this); - if (a3.cmpn(1) === 0) - return f4.clone(); - var c4 = 4, d3 = new Array(1 << c4); - d3[0] = new o2(1).toRed(this), d3[1] = f4; - for (var m3 = 2; m3 < d3.length; m3++) - d3[m3] = this.mul(d3[m3 - 1], f4); - var x3 = d3[0], M = 0, l4 = 0, s2 = a3.bitLength() % 26; - for (s2 === 0 && (s2 = 26), m3 = a3.length - 1; m3 >= 0; m3--) { - for (var v2 = a3.words[m3], k4 = s2 - 1; k4 >= 0; k4--) { - var u3 = v2 >> k4 & 1; - if (x3 !== d3[0] && (x3 = this.sqr(x3)), u3 === 0 && M === 0) { - l4 = 0; - continue; - } - M <<= 1, M |= u3, l4++, !(l4 !== c4 && (m3 !== 0 || k4 !== 0)) && (x3 = this.mul(x3, d3[M]), l4 = 0, M = 0); - } - s2 = 26; - } - return x3; - }, Y.prototype.convertTo = function(f4) { - var a3 = f4.umod(this.m); - return a3 === f4 ? a3.clone() : a3; - }, Y.prototype.convertFrom = function(f4) { - var a3 = f4.clone(); - return a3.red = null, a3; - }, o2.mont = function(f4) { - return new Wt(f4); - }; - function Wt(A2) { - Y.call(this, A2), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new o2(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); - } - n3(Wt, Y), Wt.prototype.convertTo = function(f4) { - return this.imod(f4.ushln(this.shift)); - }, Wt.prototype.convertFrom = function(f4) { - var a3 = this.imod(f4.mul(this.rinv)); - return a3.red = null, a3; - }, Wt.prototype.imul = function(f4, a3) { - if (f4.isZero() || a3.isZero()) - return f4.words[0] = 0, f4.length = 1, f4; - var c4 = f4.imul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; - return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); - }, Wt.prototype.mul = function(f4, a3) { - if (f4.isZero() || a3.isZero()) - return new o2(0)._forceRed(this); - var c4 = f4.mul(a3), d3 = c4.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), m3 = c4.isub(d3).iushrn(this.shift), x3 = m3; - return m3.cmp(this.m) >= 0 ? x3 = m3.isub(this.m) : m3.cmpn(0) < 0 && (x3 = m3.iadd(this.m)), x3._forceRed(this); - }, Wt.prototype.invm = function(f4) { - var a3 = this.imod(f4._invmp(this.m).mul(this.r2)); - return a3._forceRed(this); - }; - })(e2, _n); - })(qn); - var K2 = qn.exports; - var Kn = "bignumber/5.7.0"; - var Or = K2.BN; - var me = new z3(Kn); - var xi = {}; - var Hn = 9007199254740991; - function Ns(e2) { - return e2 != null && (G.isBigNumber(e2) || typeof e2 == "number" && e2 % 1 === 0 || typeof e2 == "string" && !!e2.match(/^-?[0-9]+$/) || Qt(e2) || typeof e2 == "bigint" || nr(e2)); - } - var Ln = false; - var G = class _G { - constructor(t, r) { - t !== xi && me.throwError("cannot call constructor directly; use BigNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new (BigNumber)" }), this._hex = r, this._isBigNumber = true, Object.freeze(this); - } - fromTwos(t) { - return jt(j2(this).fromTwos(t)); - } - toTwos(t) { - return jt(j2(this).toTwos(t)); - } - abs() { - return this._hex[0] === "-" ? _G.from(this._hex.substring(1)) : this; - } - add(t) { - return jt(j2(this).add(j2(t))); - } - sub(t) { - return jt(j2(this).sub(j2(t))); - } - div(t) { - return _G.from(t).isZero() && Xt("division-by-zero", "div"), jt(j2(this).div(j2(t))); - } - mul(t) { - return jt(j2(this).mul(j2(t))); - } - mod(t) { - const r = j2(t); - return r.isNeg() && Xt("division-by-zero", "mod"), jt(j2(this).umod(r)); - } - pow(t) { - const r = j2(t); - return r.isNeg() && Xt("negative-power", "pow"), jt(j2(this).pow(r)); - } - and(t) { - const r = j2(t); - return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "and"), jt(j2(this).and(r)); - } - or(t) { - const r = j2(t); - return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "or"), jt(j2(this).or(r)); - } - xor(t) { - const r = j2(t); - return (this.isNegative() || r.isNeg()) && Xt("unbound-bitwise-result", "xor"), jt(j2(this).xor(r)); - } - mask(t) { - return (this.isNegative() || t < 0) && Xt("negative-width", "mask"), jt(j2(this).maskn(t)); - } - shl(t) { - return (this.isNegative() || t < 0) && Xt("negative-width", "shl"), jt(j2(this).shln(t)); - } - shr(t) { - return (this.isNegative() || t < 0) && Xt("negative-width", "shr"), jt(j2(this).shrn(t)); - } - eq(t) { - return j2(this).eq(j2(t)); - } - lt(t) { - return j2(this).lt(j2(t)); - } - lte(t) { - return j2(this).lte(j2(t)); - } - gt(t) { - return j2(this).gt(j2(t)); - } - gte(t) { - return j2(this).gte(j2(t)); - } - isNegative() { - return this._hex[0] === "-"; - } - isZero() { - return j2(this).isZero(); - } - toNumber() { - try { - return j2(this).toNumber(); - } catch { - Xt("overflow", "toNumber", this.toString()); - } - return null; - } - toBigInt() { - try { - return BigInt(this.toString()); - } catch { - } - return me.throwError("this platform does not support BigInt", z3.errors.UNSUPPORTED_OPERATION, { value: this.toString() }); - } - toString() { - return arguments.length > 0 && (arguments[0] === 10 ? Ln || (Ln = true, me.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")) : arguments[0] === 16 ? me.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", z3.errors.UNEXPECTED_ARGUMENT, {}) : me.throwError("BigNumber.toString does not accept parameters", z3.errors.UNEXPECTED_ARGUMENT, {})), j2(this).toString(10); - } - toHexString() { - return this._hex; - } - toJSON(t) { - return { type: "BigNumber", hex: this.toHexString() }; - } - static from(t) { - if (t instanceof _G) - return t; - if (typeof t == "string") - return t.match(/^-?0x[0-9a-f]+$/i) ? new _G(xi, gr(t)) : t.match(/^-?[0-9]+$/) ? new _G(xi, gr(new Or(t))) : me.throwArgumentError("invalid BigNumber string", "value", t); - if (typeof t == "number") - return t % 1 && Xt("underflow", "BigNumber.from", t), (t >= Hn || t <= -Hn) && Xt("overflow", "BigNumber.from", t), _G.from(String(t)); - const r = t; - if (typeof r == "bigint") - return _G.from(r.toString()); - if (nr(r)) - return _G.from(Ht(r)); - if (r) - if (r.toHexString) { - const i2 = r.toHexString(); - if (typeof i2 == "string") - return _G.from(i2); - } else { - let i2 = r._hex; - if (i2 == null && r.type === "BigNumber" && (i2 = r.hex), typeof i2 == "string" && (Qt(i2) || i2[0] === "-" && Qt(i2.substring(1)))) - return _G.from(i2); - } - return me.throwArgumentError("invalid BigNumber value", "value", t); - } - static isBigNumber(t) { - return !!(t && t._isBigNumber); - } - }; - function gr(e2) { - if (typeof e2 != "string") - return gr(e2.toString(16)); - if (e2[0] === "-") - return e2 = e2.substring(1), e2[0] === "-" && me.throwArgumentError("invalid hex", "value", e2), e2 = gr(e2), e2 === "0x00" ? e2 : "-" + e2; - if (e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), e2 === "0x") - return "0x00"; - for (e2.length % 2 && (e2 = "0x0" + e2.substring(2)); e2.length > 4 && e2.substring(0, 4) === "0x00"; ) - e2 = "0x" + e2.substring(4); - return e2; - } - function jt(e2) { - return G.from(gr(e2)); - } - function j2(e2) { - const t = G.from(e2).toHexString(); - return t[0] === "-" ? new Or("-" + t.substring(3), 16) : new Or(t.substring(2), 16); - } - function Xt(e2, t, r) { - const i2 = { fault: e2, operation: t }; - return r != null && (i2.value = r), me.throwError(e2, z3.errors.NUMERIC_FAULT, i2); - } - function Is(e2) { - return new Or(e2, 36).toString(16); - } - var Lt = new z3(Kn); - var mr = {}; - var zn = G.from(0); - var jn = G.from(-1); - function Vn(e2, t, r, i2) { - const n3 = { fault: t, operation: r }; - return i2 !== void 0 && (n3.value = i2), Lt.throwError(e2, z3.errors.NUMERIC_FAULT, n3); - } - var Ar = "0"; - for (; Ar.length < 256; ) - Ar += Ar; - function Mi(e2) { - if (typeof e2 != "number") - try { - e2 = G.from(e2).toNumber(); - } catch { - } - return typeof e2 == "number" && e2 >= 0 && e2 <= 256 && !(e2 % 1) ? "1" + Ar.substring(0, e2) : Lt.throwArgumentError("invalid decimal size", "decimals", e2); - } - function Ei(e2, t) { - t == null && (t = 0); - const r = Mi(t); - e2 = G.from(e2); - const i2 = e2.lt(zn); - i2 && (e2 = e2.mul(jn)); - let n3 = e2.mod(r).toString(); - for (; n3.length < r.length - 1; ) - n3 = "0" + n3; - n3 = n3.match(/^([0-9]*[1-9]|0)(0*)/)[1]; - const o2 = e2.div(r).toString(); - return r.length === 1 ? e2 = o2 : e2 = o2 + "." + n3, i2 && (e2 = "-" + e2), e2; - } - function Ae(e2, t) { - t == null && (t = 0); - const r = Mi(t); - (typeof e2 != "string" || !e2.match(/^-?[0-9.]+$/)) && Lt.throwArgumentError("invalid decimal value", "value", e2); - const i2 = e2.substring(0, 1) === "-"; - i2 && (e2 = e2.substring(1)), e2 === "." && Lt.throwArgumentError("missing value", "value", e2); - const n3 = e2.split("."); - n3.length > 2 && Lt.throwArgumentError("too many decimal points", "value", e2); - let o2 = n3[0], h5 = n3[1]; - for (o2 || (o2 = "0"), h5 || (h5 = "0"); h5[h5.length - 1] === "0"; ) - h5 = h5.substring(0, h5.length - 1); - for (h5.length > r.length - 1 && Vn("fractional component exceeds decimals", "underflow", "parseFixed"), h5 === "" && (h5 = "0"); h5.length < r.length - 1; ) - h5 += "0"; - const p3 = G.from(o2), b4 = G.from(h5); - let g3 = p3.mul(r).add(b4); - return i2 && (g3 = g3.mul(jn)), g3; - } - var pr = class _pr { - constructor(t, r, i2, n3) { - t !== mr && Lt.throwError("cannot use FixedFormat constructor; use FixedFormat.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.signed = r, this.width = i2, this.decimals = n3, this.name = (r ? "" : "u") + "fixed" + String(i2) + "x" + String(n3), this._multiplier = Mi(n3), Object.freeze(this); - } - static from(t) { - if (t instanceof _pr) - return t; - typeof t == "number" && (t = `fixed128x${t}`); - let r = true, i2 = 128, n3 = 18; - if (typeof t == "string") { - if (t !== "fixed") - if (t === "ufixed") - r = false; - else { - const o2 = t.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - o2 || Lt.throwArgumentError("invalid fixed format", "format", t), r = o2[1] !== "u", i2 = parseInt(o2[2]), n3 = parseInt(o2[3]); - } - } else if (t) { - const o2 = (h5, p3, b4) => t[h5] == null ? b4 : (typeof t[h5] !== p3 && Lt.throwArgumentError("invalid fixed format (" + h5 + " not " + p3 + ")", "format." + h5, t[h5]), t[h5]); - r = o2("signed", "boolean", r), i2 = o2("width", "number", i2), n3 = o2("decimals", "number", n3); - } - return i2 % 8 && Lt.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", i2), n3 > 80 && Lt.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", n3), new _pr(mr, r, i2, n3); - } - }; - var kt = class _kt { - constructor(t, r, i2, n3) { - t !== mr && Lt.throwError("cannot use FixedNumber constructor; use FixedNumber.from", z3.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }), this.format = n3, this._hex = r, this._value = i2, this._isFixedNumber = true, Object.freeze(this); - } - _checkFormat(t) { - this.format.name !== t.format.name && Lt.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", t); - } - addUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.add(i2), this.format.decimals, this.format); - } - subUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.sub(i2), this.format.decimals, this.format); - } - mulUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.mul(i2).div(this.format._multiplier), this.format.decimals, this.format); - } - divUnsafe(t) { - this._checkFormat(t); - const r = Ae(this._value, this.format.decimals), i2 = Ae(t._value, t.format.decimals); - return _kt.fromValue(r.mul(this.format._multiplier).div(i2), this.format.decimals, this.format); - } - floor() { - const t = this.toString().split("."); - t.length === 1 && t.push("0"); - let r = _kt.from(t[0], this.format); - const i2 = !t[1].match(/^(0*)$/); - return this.isNegative() && i2 && (r = r.subUnsafe(Qn.toFormat(r.format))), r; - } - ceiling() { - const t = this.toString().split("."); - t.length === 1 && t.push("0"); - let r = _kt.from(t[0], this.format); - const i2 = !t[1].match(/^(0*)$/); - return !this.isNegative() && i2 && (r = r.addUnsafe(Qn.toFormat(r.format))), r; - } - round(t) { - t == null && (t = 0); - const r = this.toString().split("."); - if (r.length === 1 && r.push("0"), (t < 0 || t > 80 || t % 1) && Lt.throwArgumentError("invalid decimal count", "decimals", t), r[1].length <= t) - return this; - const i2 = _kt.from("1" + Ar.substring(0, t), this.format), n3 = _s.toFormat(this.format); - return this.mulUnsafe(i2).addUnsafe(n3).floor().divUnsafe(i2); - } - isZero() { - return this._value === "0.0" || this._value === "0"; - } - isNegative() { - return this._value[0] === "-"; - } - toString() { - return this._value; - } - toHexString(t) { - if (t == null) - return this._hex; - t % 8 && Lt.throwArgumentError("invalid byte width", "width", t); - const r = G.from(this._hex).fromTwos(this.format.width).toTwos(t).toHexString(); - return fe(r, t / 8); - } - toUnsafeFloat() { - return parseFloat(this.toString()); - } - toFormat(t) { - return _kt.fromString(this._value, t); - } - static fromValue(t, r, i2) { - return i2 == null && r != null && !Ns(r) && (i2 = r, r = null), r == null && (r = 0), i2 == null && (i2 = "fixed"), _kt.fromString(Ei(t, r), pr.from(i2)); - } - static fromString(t, r) { - r == null && (r = "fixed"); - const i2 = pr.from(r), n3 = Ae(t, i2.decimals); - !i2.signed && n3.lt(zn) && Vn("unsigned value cannot be negative", "overflow", "value", t); - let o2 = null; - i2.signed ? o2 = n3.toTwos(i2.width).toHexString() : (o2 = n3.toHexString(), o2 = fe(o2, i2.width / 8)); - const h5 = Ei(n3, i2.decimals); - return new _kt(mr, o2, h5, i2); - } - static fromBytes(t, r) { - r == null && (r = "fixed"); - const i2 = pr.from(r); - if (Pt(t).length > i2.width / 8) - throw new Error("overflow"); - let n3 = G.from(t); - i2.signed && (n3 = n3.fromTwos(i2.width)); - const o2 = n3.toTwos((i2.signed ? 0 : 1) + i2.width).toHexString(), h5 = Ei(n3, i2.decimals); - return new _kt(mr, o2, h5, i2); - } - static from(t, r) { - if (typeof t == "string") - return _kt.fromString(t, r); - if (nr(t)) - return _kt.fromBytes(t, r); - try { - return _kt.fromValue(t, 0, r); - } catch (i2) { - if (i2.code !== z3.errors.INVALID_ARGUMENT) - throw i2; - } - return Lt.throwArgumentError("invalid FixedNumber value", "value", t); - } - static isFixedNumber(t) { - return !!(t && t._isFixedNumber); - } - }; - var Qn = kt.from(1); - var _s = kt.from("0.5"); - var Bs = "strings/5.7.0"; - var Jn = new z3(Bs); - var Pr; - (function(e2) { - e2.current = "", e2.NFC = "NFC", e2.NFD = "NFD", e2.NFKC = "NFKC", e2.NFKD = "NFKD"; - })(Pr || (Pr = {})); - var fr; - (function(e2) { - e2.UNEXPECTED_CONTINUE = "unexpected continuation byte", e2.BAD_PREFIX = "bad codepoint prefix", e2.OVERRUN = "string overrun", e2.MISSING_CONTINUE = "missing continuation byte", e2.OUT_OF_RANGE = "out of UTF-8 range", e2.UTF16_SURROGATE = "UTF-16 surrogate", e2.OVERLONG = "overlong representation"; - })(fr || (fr = {})); - function Rs(e2, t, r, i2, n3) { - return Jn.throwArgumentError(`invalid codepoint at offset ${t}; ${e2}`, "bytes", r); - } - function Yn(e2, t, r, i2, n3) { - if (e2 === fr.BAD_PREFIX || e2 === fr.UNEXPECTED_CONTINUE) { - let o2 = 0; - for (let h5 = t + 1; h5 < r.length && r[h5] >> 6 === 2; h5++) - o2++; - return o2; - } - return e2 === fr.OVERRUN ? r.length - t - 1 : 0; - } - function Cs(e2, t, r, i2, n3) { - return e2 === fr.OVERLONG ? (i2.push(n3), 0) : (i2.push(65533), Yn(e2, t, r)); - } - Object.freeze({ error: Rs, ignore: Yn, replace: Cs }); - function Si(e2, t = Pr.current) { - t != Pr.current && (Jn.checkNormalize(), e2 = e2.normalize(t)); - let r = []; - for (let i2 = 0; i2 < e2.length; i2++) { - const n3 = e2.charCodeAt(i2); - if (n3 < 128) - r.push(n3); - else if (n3 < 2048) - r.push(n3 >> 6 | 192), r.push(n3 & 63 | 128); - else if ((n3 & 64512) == 55296) { - i2++; - const o2 = e2.charCodeAt(i2); - if (i2 >= e2.length || (o2 & 64512) !== 56320) - throw new Error("invalid utf-8 string"); - const h5 = 65536 + ((n3 & 1023) << 10) + (o2 & 1023); - r.push(h5 >> 18 | 240), r.push(h5 >> 12 & 63 | 128), r.push(h5 >> 6 & 63 | 128), r.push(h5 & 63 | 128); - } else - r.push(n3 >> 12 | 224), r.push(n3 >> 6 & 63 | 128), r.push(n3 & 63 | 128); - } - return Pt(r); - } - function Os(e2) { - if (e2.length % 4 !== 0) - throw new Error("bad data"); - let t = []; - for (let r = 0; r < e2.length; r += 4) - t.push(parseInt(e2.substring(r, r + 4), 16)); - return t; - } - function Ni(e2, t) { - t || (t = function(n3) { - return [parseInt(n3, 16)]; - }); - let r = 0, i2 = {}; - return e2.split(",").forEach((n3) => { - let o2 = n3.split(":"); - r += parseInt(o2[0], 16), i2[r] = t(o2[1]); - }), i2; - } - function Gn(e2) { - let t = 0; - return e2.split(",").map((r) => { - let i2 = r.split("-"); - i2.length === 1 ? i2[1] = "0" : i2[1] === "" && (i2[1] = "1"); - let n3 = t + parseInt(i2[0], 16); - return t = parseInt(i2[1], 16), { l: n3, h: t }; - }); - } - Gn("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"), "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((e2) => parseInt(e2, 16)), Ni("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"), Ni("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"), Ni("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", Os), Gn("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); - var Wn = "hash/5.7.0"; - function Ps(e2) { - e2 = atob(e2); - const t = []; - for (let r = 0; r < e2.length; r++) - t.push(e2.charCodeAt(r)); - return Pt(t); - } - function Xn(e2, t) { - t == null && (t = 1); - const r = [], i2 = r.forEach, n3 = function(o2, h5) { - i2.call(o2, function(p3) { - h5 > 0 && Array.isArray(p3) ? n3(p3, h5 - 1) : r.push(p3); - }); - }; - return n3(e2, t), r; - } - function Ts(e2) { - const t = {}; - for (let r = 0; r < e2.length; r++) { - const i2 = e2[r]; - t[i2[0]] = i2[1]; - } - return t; - } - function Fs(e2) { - let t = 0; - function r() { - return e2[t++] << 8 | e2[t++]; - } - let i2 = r(), n3 = 1, o2 = [0, 1]; - for (let H = 1; H < i2; H++) - o2.push(n3 += r()); - let h5 = r(), p3 = t; - t += h5; - let b4 = 0, g3 = 0; - function w4() { - return b4 == 0 && (g3 = g3 << 8 | e2[t++], b4 = 8), g3 >> --b4 & 1; - } - const y4 = 31, S4 = Math.pow(2, y4), I2 = S4 >>> 1, N10 = I2 >> 1, R2 = S4 - 1; - let F = 0; - for (let H = 0; H < y4; H++) - F = F << 1 | w4(); - let U2 = [], Q = 0, Bt = S4; - for (; ; ) { - let H = Math.floor(((F - Q + 1) * n3 - 1) / Bt), L2 = 0, Tt = i2; - for (; Tt - L2 > 1; ) { - let Gt = L2 + Tt >>> 1; - H < o2[Gt] ? Tt = Gt : L2 = Gt; - } - if (L2 == 0) - break; - U2.push(L2); - let W = Q + Math.floor(Bt * o2[L2] / n3), Ot = Q + Math.floor(Bt * o2[L2 + 1] / n3) - 1; - for (; !((W ^ Ot) & I2); ) - F = F << 1 & R2 | w4(), W = W << 1 & R2, Ot = Ot << 1 & R2 | 1; - for (; W & ~Ot & N10; ) - F = F & I2 | F << 1 & R2 >>> 1 | w4(), W = W << 1 ^ I2, Ot = (Ot ^ I2) << 1 | I2 | 1; - Q = W, Bt = 1 + Ot - W; - } - let J = i2 - 4; - return U2.map((H) => { - switch (H - J) { - case 3: - return J + 65792 + (e2[p3++] << 16 | e2[p3++] << 8 | e2[p3++]); - case 2: - return J + 256 + (e2[p3++] << 8 | e2[p3++]); - case 1: - return J + e2[p3++]; - default: - return H - 1; - } - }); - } - function Ds(e2) { - let t = 0; - return () => e2[t++]; - } - function Us(e2) { - return Ds(Fs(e2)); - } - function ks(e2) { - return e2 & 1 ? ~e2 >> 1 : e2 >> 1; - } - function qs(e2, t) { - let r = Array(e2); - for (let i2 = 0; i2 < e2; i2++) - r[i2] = 1 + t(); - return r; - } - function Zn(e2, t) { - let r = Array(e2); - for (let i2 = 0, n3 = -1; i2 < e2; i2++) - r[i2] = n3 += 1 + t(); - return r; - } - function Ks(e2, t) { - let r = Array(e2); - for (let i2 = 0, n3 = 0; i2 < e2; i2++) - r[i2] = n3 += ks(t()); - return r; - } - function Tr(e2, t) { - let r = Zn(e2(), e2), i2 = e2(), n3 = Zn(i2, e2), o2 = qs(i2, e2); - for (let h5 = 0; h5 < i2; h5++) - for (let p3 = 0; p3 < o2[h5]; p3++) - r.push(n3[h5] + p3); - return t ? r.map((h5) => t[h5]) : r; - } - function Hs(e2) { - let t = []; - for (; ; ) { - let r = e2(); - if (r == 0) - break; - t.push(zs(r, e2)); - } - for (; ; ) { - let r = e2() - 1; - if (r < 0) - break; - t.push(js(r, e2)); - } - return Ts(Xn(t)); - } - function Ls(e2) { - let t = []; - for (; ; ) { - let r = e2(); - if (r == 0) - break; - t.push(r); - } - return t; - } - function $n(e2, t, r) { - let i2 = Array(e2).fill(void 0).map(() => []); - for (let n3 = 0; n3 < t; n3++) - Ks(e2, r).forEach((o2, h5) => i2[h5].push(o2)); - return i2; - } - function zs(e2, t) { - let r = 1 + t(), i2 = t(), n3 = Ls(t), o2 = $n(n3.length, 1 + e2, t); - return Xn(o2.map((h5, p3) => { - const b4 = h5[0], g3 = h5.slice(1); - return Array(n3[p3]).fill(void 0).map((w4, y4) => { - let S4 = y4 * i2; - return [b4 + y4 * r, g3.map((I2) => I2 + S4)]; - }); - })); - } - function js(e2, t) { - let r = 1 + t(); - return $n(r, 1 + e2, t).map((n3) => [n3[0], n3.slice(1)]); - } - function Vs(e2) { - let t = Tr(e2).sort((i2, n3) => i2 - n3); - return r(); - function r() { - let i2 = []; - for (; ; ) { - let g3 = Tr(e2, t); - if (g3.length == 0) - break; - i2.push({ set: new Set(g3), node: r() }); - } - i2.sort((g3, w4) => w4.set.size - g3.set.size); - let n3 = e2(), o2 = n3 % 3; - n3 = n3 / 3 | 0; - let h5 = !!(n3 & 1); - n3 >>= 1; - let p3 = n3 == 1, b4 = n3 == 2; - return { branches: i2, valid: o2, fe0f: h5, save: p3, check: b4 }; - } - } - function Qs() { - return Us(Ps("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); - } - var Fr = Qs(); - new Set(Tr(Fr)), new Set(Tr(Fr)), Hs(Fr), Vs(Fr), new z3(Wn); - var Js = new Uint8Array(32); - Js.fill(0); - var Ys = `Ethereum Signed Message: -`; - function tf(e2) { - return typeof e2 == "string" && (e2 = Si(e2)), wi(ys([Si(Ys), Si(String(e2.length)), e2])); - } - var Gs = "rlp/5.7.0"; - new z3(Gs); - var Ws = "address/5.7.0"; - var br = new z3(Ws); - function ef(e2) { - Qt(e2, 20) || br.throwArgumentError("invalid address", "address", e2), e2 = e2.toLowerCase(); - const t = e2.substring(2).split(""), r = new Uint8Array(40); - for (let n3 = 0; n3 < 40; n3++) - r[n3] = t[n3].charCodeAt(0); - const i2 = Pt(wi(r)); - for (let n3 = 0; n3 < 40; n3 += 2) - i2[n3 >> 1] >> 4 >= 8 && (t[n3] = t[n3].toUpperCase()), (i2[n3 >> 1] & 15) >= 8 && (t[n3 + 1] = t[n3 + 1].toUpperCase()); - return "0x" + t.join(""); - } - var Xs = 9007199254740991; - function Zs(e2) { - return Math.log10 ? Math.log10(e2) : Math.log(e2) / Math.LN10; - } - var Ii = {}; - for (let e2 = 0; e2 < 10; e2++) - Ii[String(e2)] = String(e2); - for (let e2 = 0; e2 < 26; e2++) - Ii[String.fromCharCode(65 + e2)] = String(10 + e2); - var rf = Math.floor(Zs(Xs)); - function $s(e2) { - e2 = e2.toUpperCase(), e2 = e2.substring(4) + e2.substring(0, 2) + "00"; - let t = e2.split("").map((i2) => Ii[i2]).join(""); - for (; t.length >= rf; ) { - let i2 = t.substring(0, rf); - t = parseInt(i2, 10) % 97 + t.substring(i2.length); - } - let r = String(98 - parseInt(t, 10) % 97); - for (; r.length < 2; ) - r = "0" + r; - return r; - } - function ta(e2) { - let t = null; - if (typeof e2 != "string" && br.throwArgumentError("invalid address", "address", e2), e2.match(/^(0x)?[0-9a-fA-F]{40}$/)) - e2.substring(0, 2) !== "0x" && (e2 = "0x" + e2), t = ef(e2), e2.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && t !== e2 && br.throwArgumentError("bad address checksum", "address", e2); - else if (e2.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { - for (e2.substring(2, 4) !== $s(e2) && br.throwArgumentError("bad icap checksum", "address", e2), t = Is(e2.substring(4)); t.length < 40; ) - t = "0" + t; - t = ef("0x" + t); - } else - br.throwArgumentError("invalid address", "address", e2); - return t; - } - var ea = "properties/5.7.0"; - new z3(ea); - function yr(e2, t, r) { - Object.defineProperty(e2, t, { enumerable: true, value: r, writable: false }); - } - new z3(Wn); - var ra = new Uint8Array(32); - ra.fill(0), G.from(-1); - var ia = G.from(0); - var na = G.from(1); - G.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), fe(na.toHexString(), 32), fe(ia.toHexString(), 32); - var oe = {}; - var V = {}; - var wr = nf; - function nf(e2, t) { - if (!e2) - throw new Error(t || "Assertion failed"); - } - nf.equal = function(t, r, i2) { - if (t != r) - throw new Error(i2 || "Assertion failed: " + t + " != " + r); - }; - var _i = { exports: {} }; - typeof Object.create == "function" ? _i.exports = function(t, r) { - r && (t.super_ = r, t.prototype = Object.create(r.prototype, { constructor: { value: t, enumerable: false, writable: true, configurable: true } })); - } : _i.exports = function(t, r) { - if (r) { - t.super_ = r; - var i2 = function() { - }; - i2.prototype = r.prototype, t.prototype = new i2(), t.prototype.constructor = t; - } - }; - var fa = wr; - var oa = _i.exports; - V.inherits = oa; - function sa(e2, t) { - return (e2.charCodeAt(t) & 64512) !== 55296 || t < 0 || t + 1 >= e2.length ? false : (e2.charCodeAt(t + 1) & 64512) === 56320; - } - function aa(e2, t) { - if (Array.isArray(e2)) - return e2.slice(); - if (!e2) - return []; - var r = []; - if (typeof e2 == "string") - if (t) { - if (t === "hex") - for (e2 = e2.replace(/[^a-z0-9]+/ig, ""), e2.length % 2 !== 0 && (e2 = "0" + e2), n3 = 0; n3 < e2.length; n3 += 2) - r.push(parseInt(e2[n3] + e2[n3 + 1], 16)); - } else - for (var i2 = 0, n3 = 0; n3 < e2.length; n3++) { - var o2 = e2.charCodeAt(n3); - o2 < 128 ? r[i2++] = o2 : o2 < 2048 ? (r[i2++] = o2 >> 6 | 192, r[i2++] = o2 & 63 | 128) : sa(e2, n3) ? (o2 = 65536 + ((o2 & 1023) << 10) + (e2.charCodeAt(++n3) & 1023), r[i2++] = o2 >> 18 | 240, r[i2++] = o2 >> 12 & 63 | 128, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128) : (r[i2++] = o2 >> 12 | 224, r[i2++] = o2 >> 6 & 63 | 128, r[i2++] = o2 & 63 | 128); - } - else - for (n3 = 0; n3 < e2.length; n3++) - r[n3] = e2[n3] | 0; - return r; - } - V.toArray = aa; - function ua(e2) { - for (var t = "", r = 0; r < e2.length; r++) - t += of(e2[r].toString(16)); - return t; - } - V.toHex = ua; - function ff(e2) { - var t = e2 >>> 24 | e2 >>> 8 & 65280 | e2 << 8 & 16711680 | (e2 & 255) << 24; - return t >>> 0; - } - V.htonl = ff; - function ha(e2, t) { - for (var r = "", i2 = 0; i2 < e2.length; i2++) { - var n3 = e2[i2]; - t === "little" && (n3 = ff(n3)), r += sf(n3.toString(16)); - } - return r; - } - V.toHex32 = ha; - function of(e2) { - return e2.length === 1 ? "0" + e2 : e2; - } - V.zero2 = of; - function sf(e2) { - return e2.length === 7 ? "0" + e2 : e2.length === 6 ? "00" + e2 : e2.length === 5 ? "000" + e2 : e2.length === 4 ? "0000" + e2 : e2.length === 3 ? "00000" + e2 : e2.length === 2 ? "000000" + e2 : e2.length === 1 ? "0000000" + e2 : e2; - } - V.zero8 = sf; - function ca(e2, t, r, i2) { - var n3 = r - t; - fa(n3 % 4 === 0); - for (var o2 = new Array(n3 / 4), h5 = 0, p3 = t; h5 < o2.length; h5++, p3 += 4) { - var b4; - i2 === "big" ? b4 = e2[p3] << 24 | e2[p3 + 1] << 16 | e2[p3 + 2] << 8 | e2[p3 + 3] : b4 = e2[p3 + 3] << 24 | e2[p3 + 2] << 16 | e2[p3 + 1] << 8 | e2[p3], o2[h5] = b4 >>> 0; - } - return o2; - } - V.join32 = ca; - function la(e2, t) { - for (var r = new Array(e2.length * 4), i2 = 0, n3 = 0; i2 < e2.length; i2++, n3 += 4) { - var o2 = e2[i2]; - t === "big" ? (r[n3] = o2 >>> 24, r[n3 + 1] = o2 >>> 16 & 255, r[n3 + 2] = o2 >>> 8 & 255, r[n3 + 3] = o2 & 255) : (r[n3 + 3] = o2 >>> 24, r[n3 + 2] = o2 >>> 16 & 255, r[n3 + 1] = o2 >>> 8 & 255, r[n3] = o2 & 255); - } - return r; - } - V.split32 = la; - function da(e2, t) { - return e2 >>> t | e2 << 32 - t; - } - V.rotr32 = da; - function pa(e2, t) { - return e2 << t | e2 >>> 32 - t; - } - V.rotl32 = pa; - function va(e2, t) { - return e2 + t >>> 0; - } - V.sum32 = va; - function ga(e2, t, r) { - return e2 + t + r >>> 0; - } - V.sum32_3 = ga; - function ma(e2, t, r, i2) { - return e2 + t + r + i2 >>> 0; - } - V.sum32_4 = ma; - function Aa(e2, t, r, i2, n3) { - return e2 + t + r + i2 + n3 >>> 0; - } - V.sum32_5 = Aa; - function ba(e2, t, r, i2) { - var n3 = e2[t], o2 = e2[t + 1], h5 = i2 + o2 >>> 0, p3 = (h5 < i2 ? 1 : 0) + r + n3; - e2[t] = p3 >>> 0, e2[t + 1] = h5; - } - V.sum64 = ba; - function ya(e2, t, r, i2) { - var n3 = t + i2 >>> 0, o2 = (n3 < t ? 1 : 0) + e2 + r; - return o2 >>> 0; - } - V.sum64_hi = ya; - function wa(e2, t, r, i2) { - var n3 = t + i2; - return n3 >>> 0; - } - V.sum64_lo = wa; - function xa(e2, t, r, i2, n3, o2, h5, p3) { - var b4 = 0, g3 = t; - g3 = g3 + i2 >>> 0, b4 += g3 < t ? 1 : 0, g3 = g3 + o2 >>> 0, b4 += g3 < o2 ? 1 : 0, g3 = g3 + p3 >>> 0, b4 += g3 < p3 ? 1 : 0; - var w4 = e2 + r + n3 + h5 + b4; - return w4 >>> 0; - } - V.sum64_4_hi = xa; - function Ma(e2, t, r, i2, n3, o2, h5, p3) { - var b4 = t + i2 + o2 + p3; - return b4 >>> 0; - } - V.sum64_4_lo = Ma; - function Ea(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { - var w4 = 0, y4 = t; - y4 = y4 + i2 >>> 0, w4 += y4 < t ? 1 : 0, y4 = y4 + o2 >>> 0, w4 += y4 < o2 ? 1 : 0, y4 = y4 + p3 >>> 0, w4 += y4 < p3 ? 1 : 0, y4 = y4 + g3 >>> 0, w4 += y4 < g3 ? 1 : 0; - var S4 = e2 + r + n3 + h5 + b4 + w4; - return S4 >>> 0; - } - V.sum64_5_hi = Ea; - function Sa(e2, t, r, i2, n3, o2, h5, p3, b4, g3) { - var w4 = t + i2 + o2 + p3 + g3; - return w4 >>> 0; - } - V.sum64_5_lo = Sa; - function Na(e2, t, r) { - var i2 = t << 32 - r | e2 >>> r; - return i2 >>> 0; - } - V.rotr64_hi = Na; - function Ia(e2, t, r) { - var i2 = e2 << 32 - r | t >>> r; - return i2 >>> 0; - } - V.rotr64_lo = Ia; - function _a(e2, t, r) { - return e2 >>> r; - } - V.shr64_hi = _a; - function Ba(e2, t, r) { - var i2 = e2 << 32 - r | t >>> r; - return i2 >>> 0; - } - V.shr64_lo = Ba; - var or2 = {}; - var af = V; - var Ra = wr; - function Dr() { - this.pending = null, this.pendingTotal = 0, this.blockSize = this.constructor.blockSize, this.outSize = this.constructor.outSize, this.hmacStrength = this.constructor.hmacStrength, this.padLength = this.constructor.padLength / 8, this.endian = "big", this._delta8 = this.blockSize / 8, this._delta32 = this.blockSize / 32; - } - or2.BlockHash = Dr, Dr.prototype.update = function(t, r) { - if (t = af.toArray(t, r), this.pending ? this.pending = this.pending.concat(t) : this.pending = t, this.pendingTotal += t.length, this.pending.length >= this._delta8) { - t = this.pending; - var i2 = t.length % this._delta8; - this.pending = t.slice(t.length - i2, t.length), this.pending.length === 0 && (this.pending = null), t = af.join32(t, 0, t.length - i2, this.endian); - for (var n3 = 0; n3 < t.length; n3 += this._delta32) - this._update(t, n3, n3 + this._delta32); - } - return this; - }, Dr.prototype.digest = function(t) { - return this.update(this._pad()), Ra(this.pending === null), this._digest(t); - }, Dr.prototype._pad = function() { - var t = this.pendingTotal, r = this._delta8, i2 = r - (t + this.padLength) % r, n3 = new Array(i2 + this.padLength); - n3[0] = 128; - for (var o2 = 1; o2 < i2; o2++) - n3[o2] = 0; - if (t <<= 3, this.endian === "big") { - for (var h5 = 8; h5 < this.padLength; h5++) - n3[o2++] = 0; - n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = t >>> 24 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t & 255; - } else - for (n3[o2++] = t & 255, n3[o2++] = t >>> 8 & 255, n3[o2++] = t >>> 16 & 255, n3[o2++] = t >>> 24 & 255, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, n3[o2++] = 0, h5 = 8; h5 < this.padLength; h5++) - n3[o2++] = 0; - return n3; - }; - var sr = {}; - var se = {}; - var Ca = V; - var ae = Ca.rotr32; - function Oa(e2, t, r, i2) { - if (e2 === 0) - return uf(t, r, i2); - if (e2 === 1 || e2 === 3) - return cf(t, r, i2); - if (e2 === 2) - return hf(t, r, i2); - } - se.ft_1 = Oa; - function uf(e2, t, r) { - return e2 & t ^ ~e2 & r; - } - se.ch32 = uf; - function hf(e2, t, r) { - return e2 & t ^ e2 & r ^ t & r; - } - se.maj32 = hf; - function cf(e2, t, r) { - return e2 ^ t ^ r; - } - se.p32 = cf; - function Pa(e2) { - return ae(e2, 2) ^ ae(e2, 13) ^ ae(e2, 22); - } - se.s0_256 = Pa; - function Ta(e2) { - return ae(e2, 6) ^ ae(e2, 11) ^ ae(e2, 25); - } - se.s1_256 = Ta; - function Fa(e2) { - return ae(e2, 7) ^ ae(e2, 18) ^ e2 >>> 3; - } - se.g0_256 = Fa; - function Da(e2) { - return ae(e2, 17) ^ ae(e2, 19) ^ e2 >>> 10; - } - se.g1_256 = Da; - var ar = V; - var Ua = or2; - var ka = se; - var Bi = ar.rotl32; - var xr = ar.sum32; - var qa = ar.sum32_5; - var Ka = ka.ft_1; - var lf = Ua.BlockHash; - var Ha = [1518500249, 1859775393, 2400959708, 3395469782]; - function ue() { - if (!(this instanceof ue)) - return new ue(); - lf.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.W = new Array(80); - } - ar.inherits(ue, lf); - var La = ue; - ue.blockSize = 512, ue.outSize = 160, ue.hmacStrength = 80, ue.padLength = 64, ue.prototype._update = function(t, r) { - for (var i2 = this.W, n3 = 0; n3 < 16; n3++) - i2[n3] = t[r + n3]; - for (; n3 < i2.length; n3++) - i2[n3] = Bi(i2[n3 - 3] ^ i2[n3 - 8] ^ i2[n3 - 14] ^ i2[n3 - 16], 1); - var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4]; - for (n3 = 0; n3 < i2.length; n3++) { - var w4 = ~~(n3 / 20), y4 = qa(Bi(o2, 5), Ka(w4, h5, p3, b4), g3, i2[n3], Ha[w4]); - g3 = b4, b4 = p3, p3 = Bi(h5, 30), h5 = o2, o2 = y4; - } - this.h[0] = xr(this.h[0], o2), this.h[1] = xr(this.h[1], h5), this.h[2] = xr(this.h[2], p3), this.h[3] = xr(this.h[3], b4), this.h[4] = xr(this.h[4], g3); - }, ue.prototype._digest = function(t) { - return t === "hex" ? ar.toHex32(this.h, "big") : ar.split32(this.h, "big"); - }; - var ur = V; - var za = or2; - var hr = se; - var ja = wr; - var re = ur.sum32; - var Va = ur.sum32_4; - var Qa = ur.sum32_5; - var Ja = hr.ch32; - var Ya = hr.maj32; - var Ga = hr.s0_256; - var Wa = hr.s1_256; - var Xa = hr.g0_256; - var Za = hr.g1_256; - var df = za.BlockHash; - var $a = [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]; - function he() { - if (!(this instanceof he)) - return new he(); - df.call(this), this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.k = $a, this.W = new Array(64); - } - ur.inherits(he, df); - var pf = he; - he.blockSize = 512, he.outSize = 256, he.hmacStrength = 192, he.padLength = 64, he.prototype._update = function(t, r) { - for (var i2 = this.W, n3 = 0; n3 < 16; n3++) - i2[n3] = t[r + n3]; - for (; n3 < i2.length; n3++) - i2[n3] = Va(Za(i2[n3 - 2]), i2[n3 - 7], Xa(i2[n3 - 15]), i2[n3 - 16]); - var o2 = this.h[0], h5 = this.h[1], p3 = this.h[2], b4 = this.h[3], g3 = this.h[4], w4 = this.h[5], y4 = this.h[6], S4 = this.h[7]; - for (ja(this.k.length === i2.length), n3 = 0; n3 < i2.length; n3++) { - var I2 = Qa(S4, Wa(g3), Ja(g3, w4, y4), this.k[n3], i2[n3]), N10 = re(Ga(o2), Ya(o2, h5, p3)); - S4 = y4, y4 = w4, w4 = g3, g3 = re(b4, I2), b4 = p3, p3 = h5, h5 = o2, o2 = re(I2, N10); - } - this.h[0] = re(this.h[0], o2), this.h[1] = re(this.h[1], h5), this.h[2] = re(this.h[2], p3), this.h[3] = re(this.h[3], b4), this.h[4] = re(this.h[4], g3), this.h[5] = re(this.h[5], w4), this.h[6] = re(this.h[6], y4), this.h[7] = re(this.h[7], S4); - }, he.prototype._digest = function(t) { - return t === "hex" ? ur.toHex32(this.h, "big") : ur.split32(this.h, "big"); - }; - var Ri = V; - var vf = pf; - function be() { - if (!(this instanceof be)) - return new be(); - vf.call(this), this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]; - } - Ri.inherits(be, vf); - var t0 = be; - be.blockSize = 512, be.outSize = 224, be.hmacStrength = 192, be.padLength = 64, be.prototype._digest = function(t) { - return t === "hex" ? Ri.toHex32(this.h.slice(0, 7), "big") : Ri.split32(this.h.slice(0, 7), "big"); - }; - var Vt = V; - var e0 = or2; - var r0 = wr; - var ce = Vt.rotr64_hi; - var le = Vt.rotr64_lo; - var gf = Vt.shr64_hi; - var mf = Vt.shr64_lo; - var _e = Vt.sum64; - var Ci = Vt.sum64_hi; - var Oi = Vt.sum64_lo; - var i0 = Vt.sum64_4_hi; - var n0 = Vt.sum64_4_lo; - var f0 = Vt.sum64_5_hi; - var o0 = Vt.sum64_5_lo; - var Af = e0.BlockHash; - var s0 = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591]; - function ie() { - if (!(this instanceof ie)) - return new ie(); - Af.call(this), this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209], this.k = s0, this.W = new Array(160); - } - Vt.inherits(ie, Af); - var bf = ie; - ie.blockSize = 1024, ie.outSize = 512, ie.hmacStrength = 192, ie.padLength = 128, ie.prototype._prepareBlock = function(t, r) { - for (var i2 = this.W, n3 = 0; n3 < 32; n3++) - i2[n3] = t[r + n3]; - for (; n3 < i2.length; n3 += 2) { - var o2 = A0(i2[n3 - 4], i2[n3 - 3]), h5 = b0(i2[n3 - 4], i2[n3 - 3]), p3 = i2[n3 - 14], b4 = i2[n3 - 13], g3 = g0(i2[n3 - 30], i2[n3 - 29]), w4 = m0(i2[n3 - 30], i2[n3 - 29]), y4 = i2[n3 - 32], S4 = i2[n3 - 31]; - i2[n3] = i0(o2, h5, p3, b4, g3, w4, y4, S4), i2[n3 + 1] = n0(o2, h5, p3, b4, g3, w4, y4, S4); - } - }, ie.prototype._update = function(t, r) { - this._prepareBlock(t, r); - var i2 = this.W, n3 = this.h[0], o2 = this.h[1], h5 = this.h[2], p3 = this.h[3], b4 = this.h[4], g3 = this.h[5], w4 = this.h[6], y4 = this.h[7], S4 = this.h[8], I2 = this.h[9], N10 = this.h[10], R2 = this.h[11], F = this.h[12], U2 = this.h[13], Q = this.h[14], Bt = this.h[15]; - r0(this.k.length === i2.length); - for (var J = 0; J < i2.length; J += 2) { - var H = Q, L2 = Bt, Tt = p0(S4, I2), W = v0(S4, I2), Ot = a0(S4, I2, N10, R2, F), Gt = u0(S4, I2, N10, R2, F, U2), Y = this.k[J], Wt = this.k[J + 1], A2 = i2[J], f4 = i2[J + 1], a3 = f0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4), c4 = o0(H, L2, Tt, W, Ot, Gt, Y, Wt, A2, f4); - H = l0(n3, o2), L2 = d0(n3, o2), Tt = h0(n3, o2, h5, p3, b4), W = c0(n3, o2, h5, p3, b4, g3); - var d3 = Ci(H, L2, Tt, W), m3 = Oi(H, L2, Tt, W); - Q = F, Bt = U2, F = N10, U2 = R2, N10 = S4, R2 = I2, S4 = Ci(w4, y4, a3, c4), I2 = Oi(y4, y4, a3, c4), w4 = b4, y4 = g3, b4 = h5, g3 = p3, h5 = n3, p3 = o2, n3 = Ci(a3, c4, d3, m3), o2 = Oi(a3, c4, d3, m3); - } - _e(this.h, 0, n3, o2), _e(this.h, 2, h5, p3), _e(this.h, 4, b4, g3), _e(this.h, 6, w4, y4), _e(this.h, 8, S4, I2), _e(this.h, 10, N10, R2), _e(this.h, 12, F, U2), _e(this.h, 14, Q, Bt); - }, ie.prototype._digest = function(t) { - return t === "hex" ? Vt.toHex32(this.h, "big") : Vt.split32(this.h, "big"); - }; - function a0(e2, t, r, i2, n3) { - var o2 = e2 & r ^ ~e2 & n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function u0(e2, t, r, i2, n3, o2) { - var h5 = t & i2 ^ ~t & o2; - return h5 < 0 && (h5 += 4294967296), h5; - } - function h0(e2, t, r, i2, n3) { - var o2 = e2 & r ^ e2 & n3 ^ r & n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function c0(e2, t, r, i2, n3, o2) { - var h5 = t & i2 ^ t & o2 ^ i2 & o2; - return h5 < 0 && (h5 += 4294967296), h5; - } - function l0(e2, t) { - var r = ce(e2, t, 28), i2 = ce(t, e2, 2), n3 = ce(t, e2, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function d0(e2, t) { - var r = le(e2, t, 28), i2 = le(t, e2, 2), n3 = le(t, e2, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function p0(e2, t) { - var r = ce(e2, t, 14), i2 = ce(e2, t, 18), n3 = ce(t, e2, 9), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function v0(e2, t) { - var r = le(e2, t, 14), i2 = le(e2, t, 18), n3 = le(t, e2, 9), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function g0(e2, t) { - var r = ce(e2, t, 1), i2 = ce(e2, t, 8), n3 = gf(e2, t, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function m0(e2, t) { - var r = le(e2, t, 1), i2 = le(e2, t, 8), n3 = mf(e2, t, 7), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function A0(e2, t) { - var r = ce(e2, t, 19), i2 = ce(t, e2, 29), n3 = gf(e2, t, 6), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - function b0(e2, t) { - var r = le(e2, t, 19), i2 = le(t, e2, 29), n3 = mf(e2, t, 6), o2 = r ^ i2 ^ n3; - return o2 < 0 && (o2 += 4294967296), o2; - } - var Pi = V; - var yf = bf; - function ye() { - if (!(this instanceof ye)) - return new ye(); - yf.call(this), this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]; - } - Pi.inherits(ye, yf); - var y0 = ye; - ye.blockSize = 1024, ye.outSize = 384, ye.hmacStrength = 192, ye.padLength = 128, ye.prototype._digest = function(t) { - return t === "hex" ? Pi.toHex32(this.h.slice(0, 12), "big") : Pi.split32(this.h.slice(0, 12), "big"); - }, sr.sha1 = La, sr.sha224 = t0, sr.sha256 = pf, sr.sha384 = y0, sr.sha512 = bf; - var wf = {}; - var We = V; - var w0 = or2; - var Ur = We.rotl32; - var xf = We.sum32; - var Mr = We.sum32_3; - var Mf = We.sum32_4; - var Ef = w0.BlockHash; - function de() { - if (!(this instanceof de)) - return new de(); - Ef.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.endian = "little"; - } - We.inherits(de, Ef), wf.ripemd160 = de, de.blockSize = 512, de.outSize = 160, de.hmacStrength = 192, de.padLength = 64, de.prototype._update = function(t, r) { - for (var i2 = this.h[0], n3 = this.h[1], o2 = this.h[2], h5 = this.h[3], p3 = this.h[4], b4 = i2, g3 = n3, w4 = o2, y4 = h5, S4 = p3, I2 = 0; I2 < 80; I2++) { - var N10 = xf(Ur(Mf(i2, Sf(I2, n3, o2, h5), t[E0[I2] + r], x0(I2)), N0[I2]), p3); - i2 = p3, p3 = h5, h5 = Ur(o2, 10), o2 = n3, n3 = N10, N10 = xf(Ur(Mf(b4, Sf(79 - I2, g3, w4, y4), t[S0[I2] + r], M0(I2)), I0[I2]), S4), b4 = S4, S4 = y4, y4 = Ur(w4, 10), w4 = g3, g3 = N10; - } - N10 = Mr(this.h[1], o2, y4), this.h[1] = Mr(this.h[2], h5, S4), this.h[2] = Mr(this.h[3], p3, b4), this.h[3] = Mr(this.h[4], i2, g3), this.h[4] = Mr(this.h[0], n3, w4), this.h[0] = N10; - }, de.prototype._digest = function(t) { - return t === "hex" ? We.toHex32(this.h, "little") : We.split32(this.h, "little"); - }; - function Sf(e2, t, r, i2) { - return e2 <= 15 ? t ^ r ^ i2 : e2 <= 31 ? t & r | ~t & i2 : e2 <= 47 ? (t | ~r) ^ i2 : e2 <= 63 ? t & i2 | r & ~i2 : t ^ (r | ~i2); - } - function x0(e2) { - return e2 <= 15 ? 0 : e2 <= 31 ? 1518500249 : e2 <= 47 ? 1859775393 : e2 <= 63 ? 2400959708 : 2840853838; - } - function M0(e2) { - return e2 <= 15 ? 1352829926 : e2 <= 31 ? 1548603684 : e2 <= 47 ? 1836072691 : e2 <= 63 ? 2053994217 : 0; - } - var E0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]; - var S0 = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]; - var N0 = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]; - var I0 = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; - var _0 = V; - var B0 = wr; - function cr(e2, t, r) { - if (!(this instanceof cr)) - return new cr(e2, t, r); - this.Hash = e2, this.blockSize = e2.blockSize / 8, this.outSize = e2.outSize / 8, this.inner = null, this.outer = null, this._init(_0.toArray(t, r)); - } - var R0 = cr; - cr.prototype._init = function(t) { - t.length > this.blockSize && (t = new this.Hash().update(t).digest()), B0(t.length <= this.blockSize); - for (var r = t.length; r < this.blockSize; r++) - t.push(0); - for (r = 0; r < t.length; r++) - t[r] ^= 54; - for (this.inner = new this.Hash().update(t), r = 0; r < t.length; r++) - t[r] ^= 106; - this.outer = new this.Hash().update(t); - }, cr.prototype.update = function(t, r) { - return this.inner.update(t, r), this; - }, cr.prototype.digest = function(t) { - return this.outer.update(this.inner.digest()), this.outer.digest(t); - }, function(e2) { - var t = e2; - t.utils = V, t.common = or2, t.sha = sr, t.ripemd = wf, t.hmac = R0, t.sha1 = t.sha.sha1, t.sha256 = t.sha.sha256, t.sha224 = t.sha.sha224, t.sha384 = t.sha.sha384, t.sha512 = t.sha.sha512, t.ripemd160 = t.ripemd.ripemd160; - }(oe); - function lr(e2, t, r) { - return r = { path: t, exports: {}, require: function(i2, n3) { - return C0(i2, n3 ?? r.path); - } }, e2(r, r.exports), r.exports; - } - function C0() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); - } - var Ti = Nf; - function Nf(e2, t) { - if (!e2) - throw new Error(t || "Assertion failed"); - } - Nf.equal = function(t, r, i2) { - if (t != r) - throw new Error(i2 || "Assertion failed: " + t + " != " + r); - }; - var ne = lr(function(e2, t) { - var r = t; - function i2(h5, p3) { - if (Array.isArray(h5)) - return h5.slice(); - if (!h5) - return []; - var b4 = []; - if (typeof h5 != "string") { - for (var g3 = 0; g3 < h5.length; g3++) - b4[g3] = h5[g3] | 0; - return b4; - } - if (p3 === "hex") { - h5 = h5.replace(/[^a-z0-9]+/ig, ""), h5.length % 2 !== 0 && (h5 = "0" + h5); - for (var g3 = 0; g3 < h5.length; g3 += 2) - b4.push(parseInt(h5[g3] + h5[g3 + 1], 16)); - } else - for (var g3 = 0; g3 < h5.length; g3++) { - var w4 = h5.charCodeAt(g3), y4 = w4 >> 8, S4 = w4 & 255; - y4 ? b4.push(y4, S4) : b4.push(S4); - } - return b4; - } - r.toArray = i2; - function n3(h5) { - return h5.length === 1 ? "0" + h5 : h5; - } - r.zero2 = n3; - function o2(h5) { - for (var p3 = "", b4 = 0; b4 < h5.length; b4++) - p3 += n3(h5[b4].toString(16)); - return p3; - } - r.toHex = o2, r.encode = function(p3, b4) { - return b4 === "hex" ? o2(p3) : p3; - }; - }); - var Jt = lr(function(e2, t) { - var r = t; - r.assert = Ti, r.toArray = ne.toArray, r.zero2 = ne.zero2, r.toHex = ne.toHex, r.encode = ne.encode; - function i2(b4, g3, w4) { - var y4 = new Array(Math.max(b4.bitLength(), w4) + 1); - y4.fill(0); - for (var S4 = 1 << g3 + 1, I2 = b4.clone(), N10 = 0; N10 < y4.length; N10++) { - var R2, F = I2.andln(S4 - 1); - I2.isOdd() ? (F > (S4 >> 1) - 1 ? R2 = (S4 >> 1) - F : R2 = F, I2.isubn(R2)) : R2 = 0, y4[N10] = R2, I2.iushrn(1); - } - return y4; - } - r.getNAF = i2; - function n3(b4, g3) { - var w4 = [[], []]; - b4 = b4.clone(), g3 = g3.clone(); - for (var y4 = 0, S4 = 0, I2; b4.cmpn(-y4) > 0 || g3.cmpn(-S4) > 0; ) { - var N10 = b4.andln(3) + y4 & 3, R2 = g3.andln(3) + S4 & 3; - N10 === 3 && (N10 = -1), R2 === 3 && (R2 = -1); - var F; - N10 & 1 ? (I2 = b4.andln(7) + y4 & 7, (I2 === 3 || I2 === 5) && R2 === 2 ? F = -N10 : F = N10) : F = 0, w4[0].push(F); - var U2; - R2 & 1 ? (I2 = g3.andln(7) + S4 & 7, (I2 === 3 || I2 === 5) && N10 === 2 ? U2 = -R2 : U2 = R2) : U2 = 0, w4[1].push(U2), 2 * y4 === F + 1 && (y4 = 1 - y4), 2 * S4 === U2 + 1 && (S4 = 1 - S4), b4.iushrn(1), g3.iushrn(1); - } - return w4; - } - r.getJSF = n3; - function o2(b4, g3, w4) { - var y4 = "_" + g3; - b4.prototype[g3] = function() { - return this[y4] !== void 0 ? this[y4] : this[y4] = w4.call(this); - }; - } - r.cachedProperty = o2; - function h5(b4) { - return typeof b4 == "string" ? r.toArray(b4, "hex") : b4; - } - r.parseBytes = h5; - function p3(b4) { - return new K2(b4, "hex", "le"); - } - r.intFromLE = p3; - }); - var kr = Jt.getNAF; - var O0 = Jt.getJSF; - var qr = Jt.assert; - function Be(e2, t) { - this.type = e2, this.p = new K2(t.p, 16), this.red = t.prime ? K2.red(t.prime) : K2.mont(this.p), this.zero = new K2(0).toRed(this.red), this.one = new K2(1).toRed(this.red), this.two = new K2(2).toRed(this.red), this.n = t.n && new K2(t.n, 16), this.g = t.g && this.pointFromJSON(t.g, t.gRed), this._wnafT1 = new Array(4), this._wnafT2 = new Array(4), this._wnafT3 = new Array(4), this._wnafT4 = new Array(4), this._bitLength = this.n ? this.n.bitLength() : 0; - var r = this.n && this.p.div(this.n); - !r || r.cmpn(100) > 0 ? this.redN = null : (this._maxwellTrick = true, this.redN = this.n.toRed(this.red)); - } - var Xe = Be; - Be.prototype.point = function() { - throw new Error("Not implemented"); - }, Be.prototype.validate = function() { - throw new Error("Not implemented"); - }, Be.prototype._fixedNafMul = function(t, r) { - qr(t.precomputed); - var i2 = t._getDoubles(), n3 = kr(r, 1, this._bitLength), o2 = (1 << i2.step + 1) - (i2.step % 2 === 0 ? 2 : 1); - o2 /= 3; - var h5 = [], p3, b4; - for (p3 = 0; p3 < n3.length; p3 += i2.step) { - b4 = 0; - for (var g3 = p3 + i2.step - 1; g3 >= p3; g3--) - b4 = (b4 << 1) + n3[g3]; - h5.push(b4); - } - for (var w4 = this.jpoint(null, null, null), y4 = this.jpoint(null, null, null), S4 = o2; S4 > 0; S4--) { - for (p3 = 0; p3 < h5.length; p3++) - b4 = h5[p3], b4 === S4 ? y4 = y4.mixedAdd(i2.points[p3]) : b4 === -S4 && (y4 = y4.mixedAdd(i2.points[p3].neg())); - w4 = w4.add(y4); - } - return w4.toP(); - }, Be.prototype._wnafMul = function(t, r) { - var i2 = 4, n3 = t._getNAFPoints(i2); - i2 = n3.wnd; - for (var o2 = n3.points, h5 = kr(r, i2, this._bitLength), p3 = this.jpoint(null, null, null), b4 = h5.length - 1; b4 >= 0; b4--) { - for (var g3 = 0; b4 >= 0 && h5[b4] === 0; b4--) - g3++; - if (b4 >= 0 && g3++, p3 = p3.dblp(g3), b4 < 0) - break; - var w4 = h5[b4]; - qr(w4 !== 0), t.type === "affine" ? w4 > 0 ? p3 = p3.mixedAdd(o2[w4 - 1 >> 1]) : p3 = p3.mixedAdd(o2[-w4 - 1 >> 1].neg()) : w4 > 0 ? p3 = p3.add(o2[w4 - 1 >> 1]) : p3 = p3.add(o2[-w4 - 1 >> 1].neg()); - } - return t.type === "affine" ? p3.toP() : p3; - }, Be.prototype._wnafMulAdd = function(t, r, i2, n3, o2) { - var h5 = this._wnafT1, p3 = this._wnafT2, b4 = this._wnafT3, g3 = 0, w4, y4, S4; - for (w4 = 0; w4 < n3; w4++) { - S4 = r[w4]; - var I2 = S4._getNAFPoints(t); - h5[w4] = I2.wnd, p3[w4] = I2.points; - } - for (w4 = n3 - 1; w4 >= 1; w4 -= 2) { - var N10 = w4 - 1, R2 = w4; - if (h5[N10] !== 1 || h5[R2] !== 1) { - b4[N10] = kr(i2[N10], h5[N10], this._bitLength), b4[R2] = kr(i2[R2], h5[R2], this._bitLength), g3 = Math.max(b4[N10].length, g3), g3 = Math.max(b4[R2].length, g3); - continue; - } - var F = [r[N10], null, null, r[R2]]; - r[N10].y.cmp(r[R2].y) === 0 ? (F[1] = r[N10].add(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())) : r[N10].y.cmp(r[R2].y.redNeg()) === 0 ? (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].add(r[R2].neg())) : (F[1] = r[N10].toJ().mixedAdd(r[R2]), F[2] = r[N10].toJ().mixedAdd(r[R2].neg())); - var U2 = [-3, -1, -5, -7, 0, 7, 5, 1, 3], Q = O0(i2[N10], i2[R2]); - for (g3 = Math.max(Q[0].length, g3), b4[N10] = new Array(g3), b4[R2] = new Array(g3), y4 = 0; y4 < g3; y4++) { - var Bt = Q[0][y4] | 0, J = Q[1][y4] | 0; - b4[N10][y4] = U2[(Bt + 1) * 3 + (J + 1)], b4[R2][y4] = 0, p3[N10] = F; - } - } - var H = this.jpoint(null, null, null), L2 = this._wnafT4; - for (w4 = g3; w4 >= 0; w4--) { - for (var Tt = 0; w4 >= 0; ) { - var W = true; - for (y4 = 0; y4 < n3; y4++) - L2[y4] = b4[y4][w4] | 0, L2[y4] !== 0 && (W = false); - if (!W) - break; - Tt++, w4--; - } - if (w4 >= 0 && Tt++, H = H.dblp(Tt), w4 < 0) - break; - for (y4 = 0; y4 < n3; y4++) { - var Ot = L2[y4]; - Ot !== 0 && (Ot > 0 ? S4 = p3[y4][Ot - 1 >> 1] : Ot < 0 && (S4 = p3[y4][-Ot - 1 >> 1].neg()), S4.type === "affine" ? H = H.mixedAdd(S4) : H = H.add(S4)); - } - } - for (w4 = 0; w4 < n3; w4++) - p3[w4] = null; - return o2 ? H : H.toP(); - }; - function Zt(e2, t) { - this.curve = e2, this.type = t, this.precomputed = null; - } - Be.BasePoint = Zt, Zt.prototype.eq = function() { - throw new Error("Not implemented"); - }, Zt.prototype.validate = function() { - return this.curve.validate(this); - }, Be.prototype.decodePoint = function(t, r) { - t = Jt.toArray(t, r); - var i2 = this.p.byteLength(); - if ((t[0] === 4 || t[0] === 6 || t[0] === 7) && t.length - 1 === 2 * i2) { - t[0] === 6 ? qr(t[t.length - 1] % 2 === 0) : t[0] === 7 && qr(t[t.length - 1] % 2 === 1); - var n3 = this.point(t.slice(1, 1 + i2), t.slice(1 + i2, 1 + 2 * i2)); - return n3; - } else if ((t[0] === 2 || t[0] === 3) && t.length - 1 === i2) - return this.pointFromX(t.slice(1, 1 + i2), t[0] === 3); - throw new Error("Unknown point format"); - }, Zt.prototype.encodeCompressed = function(t) { - return this.encode(t, true); - }, Zt.prototype._encode = function(t) { - var r = this.curve.p.byteLength(), i2 = this.getX().toArray("be", r); - return t ? [this.getY().isEven() ? 2 : 3].concat(i2) : [4].concat(i2, this.getY().toArray("be", r)); - }, Zt.prototype.encode = function(t, r) { - return Jt.encode(this._encode(r), t); - }, Zt.prototype.precompute = function(t) { - if (this.precomputed) - return this; - var r = { doubles: null, naf: null, beta: null }; - return r.naf = this._getNAFPoints(8), r.doubles = this._getDoubles(4, t), r.beta = this._getBeta(), this.precomputed = r, this; - }, Zt.prototype._hasDoubles = function(t) { - if (!this.precomputed) - return false; - var r = this.precomputed.doubles; - return r ? r.points.length >= Math.ceil((t.bitLength() + 1) / r.step) : false; - }, Zt.prototype._getDoubles = function(t, r) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - for (var i2 = [this], n3 = this, o2 = 0; o2 < r; o2 += t) { - for (var h5 = 0; h5 < t; h5++) - n3 = n3.dbl(); - i2.push(n3); - } - return { step: t, points: i2 }; - }, Zt.prototype._getNAFPoints = function(t) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - for (var r = [this], i2 = (1 << t) - 1, n3 = i2 === 1 ? null : this.dbl(), o2 = 1; o2 < i2; o2++) - r[o2] = r[o2 - 1].add(n3); - return { wnd: t, points: r }; - }, Zt.prototype._getBeta = function() { - return null; - }, Zt.prototype.dblp = function(t) { - for (var r = this, i2 = 0; i2 < t; i2++) - r = r.dbl(); - return r; - }; - var Fi = lr(function(e2) { - typeof Object.create == "function" ? e2.exports = function(r, i2) { - i2 && (r.super_ = i2, r.prototype = Object.create(i2.prototype, { constructor: { value: r, enumerable: false, writable: true, configurable: true } })); - } : e2.exports = function(r, i2) { - if (i2) { - r.super_ = i2; - var n3 = function() { - }; - n3.prototype = i2.prototype, r.prototype = new n3(), r.prototype.constructor = r; - } - }; - }); - var P0 = Jt.assert; - function $t(e2) { - Xe.call(this, "short", e2), this.a = new K2(e2.a, 16).toRed(this.red), this.b = new K2(e2.b, 16).toRed(this.red), this.tinv = this.two.redInvm(), this.zeroA = this.a.fromRed().cmpn(0) === 0, this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0, this.endo = this._getEndomorphism(e2), this._endoWnafT1 = new Array(4), this._endoWnafT2 = new Array(4); - } - Fi($t, Xe); - var T0 = $t; - $t.prototype._getEndomorphism = function(t) { - if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { - var r, i2; - if (t.beta) - r = new K2(t.beta, 16).toRed(this.red); - else { - var n3 = this._getEndoRoots(this.p); - r = n3[0].cmp(n3[1]) < 0 ? n3[0] : n3[1], r = r.toRed(this.red); - } - if (t.lambda) - i2 = new K2(t.lambda, 16); - else { - var o2 = this._getEndoRoots(this.n); - this.g.mul(o2[0]).x.cmp(this.g.x.redMul(r)) === 0 ? i2 = o2[0] : (i2 = o2[1], P0(this.g.mul(i2).x.cmp(this.g.x.redMul(r)) === 0)); - } - var h5; - return t.basis ? h5 = t.basis.map(function(p3) { - return { a: new K2(p3.a, 16), b: new K2(p3.b, 16) }; - }) : h5 = this._getEndoBasis(i2), { beta: r, lambda: i2, basis: h5 }; - } - }, $t.prototype._getEndoRoots = function(t) { - var r = t === this.p ? this.red : K2.mont(t), i2 = new K2(2).toRed(r).redInvm(), n3 = i2.redNeg(), o2 = new K2(3).toRed(r).redNeg().redSqrt().redMul(i2), h5 = n3.redAdd(o2).fromRed(), p3 = n3.redSub(o2).fromRed(); - return [h5, p3]; - }, $t.prototype._getEndoBasis = function(t) { - for (var r = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), i2 = t, n3 = this.n.clone(), o2 = new K2(1), h5 = new K2(0), p3 = new K2(0), b4 = new K2(1), g3, w4, y4, S4, I2, N10, R2, F = 0, U2, Q; i2.cmpn(0) !== 0; ) { - var Bt = n3.div(i2); - U2 = n3.sub(Bt.mul(i2)), Q = p3.sub(Bt.mul(o2)); - var J = b4.sub(Bt.mul(h5)); - if (!y4 && U2.cmp(r) < 0) - g3 = R2.neg(), w4 = o2, y4 = U2.neg(), S4 = Q; - else if (y4 && ++F === 2) - break; - R2 = U2, n3 = i2, i2 = U2, p3 = o2, o2 = Q, b4 = h5, h5 = J; - } - I2 = U2.neg(), N10 = Q; - var H = y4.sqr().add(S4.sqr()), L2 = I2.sqr().add(N10.sqr()); - return L2.cmp(H) >= 0 && (I2 = g3, N10 = w4), y4.negative && (y4 = y4.neg(), S4 = S4.neg()), I2.negative && (I2 = I2.neg(), N10 = N10.neg()), [{ a: y4, b: S4 }, { a: I2, b: N10 }]; - }, $t.prototype._endoSplit = function(t) { - var r = this.endo.basis, i2 = r[0], n3 = r[1], o2 = n3.b.mul(t).divRound(this.n), h5 = i2.b.neg().mul(t).divRound(this.n), p3 = o2.mul(i2.a), b4 = h5.mul(n3.a), g3 = o2.mul(i2.b), w4 = h5.mul(n3.b), y4 = t.sub(p3).sub(b4), S4 = g3.add(w4).neg(); - return { k1: y4, k2: S4 }; - }, $t.prototype.pointFromX = function(t, r) { - t = new K2(t, 16), t.red || (t = t.toRed(this.red)); - var i2 = t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b), n3 = i2.redSqrt(); - if (n3.redSqr().redSub(i2).cmp(this.zero) !== 0) - throw new Error("invalid point"); - var o2 = n3.fromRed().isOdd(); - return (r && !o2 || !r && o2) && (n3 = n3.redNeg()), this.point(t, n3); - }, $t.prototype.validate = function(t) { - if (t.inf) - return true; - var r = t.x, i2 = t.y, n3 = this.a.redMul(r), o2 = r.redSqr().redMul(r).redIAdd(n3).redIAdd(this.b); - return i2.redSqr().redISub(o2).cmpn(0) === 0; - }, $t.prototype._endoWnafMulAdd = function(t, r, i2) { - for (var n3 = this._endoWnafT1, o2 = this._endoWnafT2, h5 = 0; h5 < t.length; h5++) { - var p3 = this._endoSplit(r[h5]), b4 = t[h5], g3 = b4._getBeta(); - p3.k1.negative && (p3.k1.ineg(), b4 = b4.neg(true)), p3.k2.negative && (p3.k2.ineg(), g3 = g3.neg(true)), n3[h5 * 2] = b4, n3[h5 * 2 + 1] = g3, o2[h5 * 2] = p3.k1, o2[h5 * 2 + 1] = p3.k2; - } - for (var w4 = this._wnafMulAdd(1, n3, o2, h5 * 2, i2), y4 = 0; y4 < h5 * 2; y4++) - n3[y4] = null, o2[y4] = null; - return w4; - }; - function Dt(e2, t, r, i2) { - Xe.BasePoint.call(this, e2, "affine"), t === null && r === null ? (this.x = null, this.y = null, this.inf = true) : (this.x = new K2(t, 16), this.y = new K2(r, 16), i2 && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.inf = false); - } - Fi(Dt, Xe.BasePoint), $t.prototype.point = function(t, r, i2) { - return new Dt(this, t, r, i2); - }, $t.prototype.pointFromJSON = function(t, r) { - return Dt.fromJSON(this, t, r); - }, Dt.prototype._getBeta = function() { - if (this.curve.endo) { - var t = this.precomputed; - if (t && t.beta) - return t.beta; - var r = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (t) { - var i2 = this.curve, n3 = function(o2) { - return i2.point(o2.x.redMul(i2.endo.beta), o2.y); - }; - t.beta = r, r.precomputed = { beta: null, naf: t.naf && { wnd: t.naf.wnd, points: t.naf.points.map(n3) }, doubles: t.doubles && { step: t.doubles.step, points: t.doubles.points.map(n3) } }; - } - return r; - } - }, Dt.prototype.toJSON = function() { - return this.precomputed ? [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }] : [this.x, this.y]; - }, Dt.fromJSON = function(t, r, i2) { - typeof r == "string" && (r = JSON.parse(r)); - var n3 = t.point(r[0], r[1], i2); - if (!r[2]) - return n3; - function o2(p3) { - return t.point(p3[0], p3[1], i2); - } - var h5 = r[2]; - return n3.precomputed = { beta: null, doubles: h5.doubles && { step: h5.doubles.step, points: [n3].concat(h5.doubles.points.map(o2)) }, naf: h5.naf && { wnd: h5.naf.wnd, points: [n3].concat(h5.naf.points.map(o2)) } }, n3; - }, Dt.prototype.inspect = function() { - return this.isInfinity() ? "" : ""; - }, Dt.prototype.isInfinity = function() { - return this.inf; - }, Dt.prototype.add = function(t) { - if (this.inf) - return t; - if (t.inf) - return this; - if (this.eq(t)) - return this.dbl(); - if (this.neg().eq(t)) - return this.curve.point(null, null); - if (this.x.cmp(t.x) === 0) - return this.curve.point(null, null); - var r = this.y.redSub(t.y); - r.cmpn(0) !== 0 && (r = r.redMul(this.x.redSub(t.x).redInvm())); - var i2 = r.redSqr().redISub(this.x).redISub(t.x), n3 = r.redMul(this.x.redSub(i2)).redISub(this.y); - return this.curve.point(i2, n3); - }, Dt.prototype.dbl = function() { - if (this.inf) - return this; - var t = this.y.redAdd(this.y); - if (t.cmpn(0) === 0) - return this.curve.point(null, null); - var r = this.curve.a, i2 = this.x.redSqr(), n3 = t.redInvm(), o2 = i2.redAdd(i2).redIAdd(i2).redIAdd(r).redMul(n3), h5 = o2.redSqr().redISub(this.x.redAdd(this.x)), p3 = o2.redMul(this.x.redSub(h5)).redISub(this.y); - return this.curve.point(h5, p3); - }, Dt.prototype.getX = function() { - return this.x.fromRed(); - }, Dt.prototype.getY = function() { - return this.y.fromRed(); - }, Dt.prototype.mul = function(t) { - return t = new K2(t, 16), this.isInfinity() ? this : this._hasDoubles(t) ? this.curve._fixedNafMul(this, t) : this.curve.endo ? this.curve._endoWnafMulAdd([this], [t]) : this.curve._wnafMul(this, t); - }, Dt.prototype.mulAdd = function(t, r, i2) { - var n3 = [this, r], o2 = [t, i2]; - return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2) : this.curve._wnafMulAdd(1, n3, o2, 2); - }, Dt.prototype.jmulAdd = function(t, r, i2) { - var n3 = [this, r], o2 = [t, i2]; - return this.curve.endo ? this.curve._endoWnafMulAdd(n3, o2, true) : this.curve._wnafMulAdd(1, n3, o2, 2, true); - }, Dt.prototype.eq = function(t) { - return this === t || this.inf === t.inf && (this.inf || this.x.cmp(t.x) === 0 && this.y.cmp(t.y) === 0); - }, Dt.prototype.neg = function(t) { - if (this.inf) - return this; - var r = this.curve.point(this.x, this.y.redNeg()); - if (t && this.precomputed) { - var i2 = this.precomputed, n3 = function(o2) { - return o2.neg(); - }; - r.precomputed = { naf: i2.naf && { wnd: i2.naf.wnd, points: i2.naf.points.map(n3) }, doubles: i2.doubles && { step: i2.doubles.step, points: i2.doubles.points.map(n3) } }; - } - return r; - }, Dt.prototype.toJ = function() { - if (this.inf) - return this.curve.jpoint(null, null, null); - var t = this.curve.jpoint(this.x, this.y, this.curve.one); - return t; - }; - function Ut(e2, t, r, i2) { - Xe.BasePoint.call(this, e2, "jacobian"), t === null && r === null && i2 === null ? (this.x = this.curve.one, this.y = this.curve.one, this.z = new K2(0)) : (this.x = new K2(t, 16), this.y = new K2(r, 16), this.z = new K2(i2, 16)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red)), this.zOne = this.z === this.curve.one; - } - Fi(Ut, Xe.BasePoint), $t.prototype.jpoint = function(t, r, i2) { - return new Ut(this, t, r, i2); - }, Ut.prototype.toP = function() { - if (this.isInfinity()) - return this.curve.point(null, null); - var t = this.z.redInvm(), r = t.redSqr(), i2 = this.x.redMul(r), n3 = this.y.redMul(r).redMul(t); - return this.curve.point(i2, n3); - }, Ut.prototype.neg = function() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }, Ut.prototype.add = function(t) { - if (this.isInfinity()) - return t; - if (t.isInfinity()) - return this; - var r = t.z.redSqr(), i2 = this.z.redSqr(), n3 = this.x.redMul(r), o2 = t.x.redMul(i2), h5 = this.y.redMul(r.redMul(t.z)), p3 = t.y.redMul(i2.redMul(this.z)), b4 = n3.redSub(o2), g3 = h5.redSub(p3); - if (b4.cmpn(0) === 0) - return g3.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); - var w4 = b4.redSqr(), y4 = w4.redMul(b4), S4 = n3.redMul(w4), I2 = g3.redSqr().redIAdd(y4).redISub(S4).redISub(S4), N10 = g3.redMul(S4.redISub(I2)).redISub(h5.redMul(y4)), R2 = this.z.redMul(t.z).redMul(b4); - return this.curve.jpoint(I2, N10, R2); - }, Ut.prototype.mixedAdd = function(t) { - if (this.isInfinity()) - return t.toJ(); - if (t.isInfinity()) - return this; - var r = this.z.redSqr(), i2 = this.x, n3 = t.x.redMul(r), o2 = this.y, h5 = t.y.redMul(r).redMul(this.z), p3 = i2.redSub(n3), b4 = o2.redSub(h5); - if (p3.cmpn(0) === 0) - return b4.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); - var g3 = p3.redSqr(), w4 = g3.redMul(p3), y4 = i2.redMul(g3), S4 = b4.redSqr().redIAdd(w4).redISub(y4).redISub(y4), I2 = b4.redMul(y4.redISub(S4)).redISub(o2.redMul(w4)), N10 = this.z.redMul(p3); - return this.curve.jpoint(S4, I2, N10); - }, Ut.prototype.dblp = function(t) { - if (t === 0) - return this; - if (this.isInfinity()) - return this; - if (!t) - return this.dbl(); - var r; - if (this.curve.zeroA || this.curve.threeA) { - var i2 = this; - for (r = 0; r < t; r++) - i2 = i2.dbl(); - return i2; - } - var n3 = this.curve.a, o2 = this.curve.tinv, h5 = this.x, p3 = this.y, b4 = this.z, g3 = b4.redSqr().redSqr(), w4 = p3.redAdd(p3); - for (r = 0; r < t; r++) { - var y4 = h5.redSqr(), S4 = w4.redSqr(), I2 = S4.redSqr(), N10 = y4.redAdd(y4).redIAdd(y4).redIAdd(n3.redMul(g3)), R2 = h5.redMul(S4), F = N10.redSqr().redISub(R2.redAdd(R2)), U2 = R2.redISub(F), Q = N10.redMul(U2); - Q = Q.redIAdd(Q).redISub(I2); - var Bt = w4.redMul(b4); - r + 1 < t && (g3 = g3.redMul(I2)), h5 = F, b4 = Bt, w4 = Q; - } - return this.curve.jpoint(h5, w4.redMul(o2), b4); - }, Ut.prototype.dbl = function() { - return this.isInfinity() ? this : this.curve.zeroA ? this._zeroDbl() : this.curve.threeA ? this._threeDbl() : this._dbl(); - }, Ut.prototype._zeroDbl = function() { - var t, r, i2; - if (this.zOne) { - var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); - p3 = p3.redIAdd(p3); - var b4 = n3.redAdd(n3).redIAdd(n3), g3 = b4.redSqr().redISub(p3).redISub(p3), w4 = h5.redIAdd(h5); - w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), t = g3, r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); - } else { - var y4 = this.x.redSqr(), S4 = this.y.redSqr(), I2 = S4.redSqr(), N10 = this.x.redAdd(S4).redSqr().redISub(y4).redISub(I2); - N10 = N10.redIAdd(N10); - var R2 = y4.redAdd(y4).redIAdd(y4), F = R2.redSqr(), U2 = I2.redIAdd(I2); - U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), t = F.redISub(N10).redISub(N10), r = R2.redMul(N10.redISub(t)).redISub(U2), i2 = this.y.redMul(this.z), i2 = i2.redIAdd(i2); - } - return this.curve.jpoint(t, r, i2); - }, Ut.prototype._threeDbl = function() { - var t, r, i2; - if (this.zOne) { - var n3 = this.x.redSqr(), o2 = this.y.redSqr(), h5 = o2.redSqr(), p3 = this.x.redAdd(o2).redSqr().redISub(n3).redISub(h5); - p3 = p3.redIAdd(p3); - var b4 = n3.redAdd(n3).redIAdd(n3).redIAdd(this.curve.a), g3 = b4.redSqr().redISub(p3).redISub(p3); - t = g3; - var w4 = h5.redIAdd(h5); - w4 = w4.redIAdd(w4), w4 = w4.redIAdd(w4), r = b4.redMul(p3.redISub(g3)).redISub(w4), i2 = this.y.redAdd(this.y); - } else { - var y4 = this.z.redSqr(), S4 = this.y.redSqr(), I2 = this.x.redMul(S4), N10 = this.x.redSub(y4).redMul(this.x.redAdd(y4)); - N10 = N10.redAdd(N10).redIAdd(N10); - var R2 = I2.redIAdd(I2); - R2 = R2.redIAdd(R2); - var F = R2.redAdd(R2); - t = N10.redSqr().redISub(F), i2 = this.y.redAdd(this.z).redSqr().redISub(S4).redISub(y4); - var U2 = S4.redSqr(); - U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), U2 = U2.redIAdd(U2), r = N10.redMul(R2.redISub(t)).redISub(U2); - } - return this.curve.jpoint(t, r, i2); - }, Ut.prototype._dbl = function() { - var t = this.curve.a, r = this.x, i2 = this.y, n3 = this.z, o2 = n3.redSqr().redSqr(), h5 = r.redSqr(), p3 = i2.redSqr(), b4 = h5.redAdd(h5).redIAdd(h5).redIAdd(t.redMul(o2)), g3 = r.redAdd(r); - g3 = g3.redIAdd(g3); - var w4 = g3.redMul(p3), y4 = b4.redSqr().redISub(w4.redAdd(w4)), S4 = w4.redISub(y4), I2 = p3.redSqr(); - I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); - var N10 = b4.redMul(S4).redISub(I2), R2 = i2.redAdd(i2).redMul(n3); - return this.curve.jpoint(y4, N10, R2); - }, Ut.prototype.trpl = function() { - if (!this.curve.zeroA) - return this.dbl().add(this); - var t = this.x.redSqr(), r = this.y.redSqr(), i2 = this.z.redSqr(), n3 = r.redSqr(), o2 = t.redAdd(t).redIAdd(t), h5 = o2.redSqr(), p3 = this.x.redAdd(r).redSqr().redISub(t).redISub(n3); - p3 = p3.redIAdd(p3), p3 = p3.redAdd(p3).redIAdd(p3), p3 = p3.redISub(h5); - var b4 = p3.redSqr(), g3 = n3.redIAdd(n3); - g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3), g3 = g3.redIAdd(g3); - var w4 = o2.redIAdd(p3).redSqr().redISub(h5).redISub(b4).redISub(g3), y4 = r.redMul(w4); - y4 = y4.redIAdd(y4), y4 = y4.redIAdd(y4); - var S4 = this.x.redMul(b4).redISub(y4); - S4 = S4.redIAdd(S4), S4 = S4.redIAdd(S4); - var I2 = this.y.redMul(w4.redMul(g3.redISub(w4)).redISub(p3.redMul(b4))); - I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2), I2 = I2.redIAdd(I2); - var N10 = this.z.redAdd(p3).redSqr().redISub(i2).redISub(b4); - return this.curve.jpoint(S4, I2, N10); - }, Ut.prototype.mul = function(t, r) { - return t = new K2(t, r), this.curve._wnafMul(this, t); - }, Ut.prototype.eq = function(t) { - if (t.type === "affine") - return this.eq(t.toJ()); - if (this === t) - return true; - var r = this.z.redSqr(), i2 = t.z.redSqr(); - if (this.x.redMul(i2).redISub(t.x.redMul(r)).cmpn(0) !== 0) - return false; - var n3 = r.redMul(this.z), o2 = i2.redMul(t.z); - return this.y.redMul(o2).redISub(t.y.redMul(n3)).cmpn(0) === 0; - }, Ut.prototype.eqXToP = function(t) { - var r = this.z.redSqr(), i2 = t.toRed(this.curve.red).redMul(r); - if (this.x.cmp(i2) === 0) - return true; - for (var n3 = t.clone(), o2 = this.curve.redN.redMul(r); ; ) { - if (n3.iadd(this.curve.n), n3.cmp(this.curve.p) >= 0) - return false; - if (i2.redIAdd(o2), this.x.cmp(i2) === 0) - return true; - } - }, Ut.prototype.inspect = function() { - return this.isInfinity() ? "" : ""; - }, Ut.prototype.isInfinity = function() { - return this.z.cmpn(0) === 0; - }; - var Kr = lr(function(e2, t) { - var r = t; - r.base = Xe, r.short = T0, r.mont = null, r.edwards = null; - }); - var Hr = lr(function(e2, t) { - var r = t, i2 = Jt.assert; - function n3(p3) { - p3.type === "short" ? this.curve = new Kr.short(p3) : p3.type === "edwards" ? this.curve = new Kr.edwards(p3) : this.curve = new Kr.mont(p3), this.g = this.curve.g, this.n = this.curve.n, this.hash = p3.hash, i2(this.g.validate(), "Invalid curve"), i2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); - } - r.PresetCurve = n3; - function o2(p3, b4) { - Object.defineProperty(r, p3, { configurable: true, enumerable: true, get: function() { - var g3 = new n3(b4); - return Object.defineProperty(r, p3, { configurable: true, enumerable: true, value: g3 }), g3; - } }); - } - o2("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: oe.sha256, gRed: false, g: ["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"] }), o2("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: oe.sha256, gRed: false, g: ["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"] }), o2("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: oe.sha256, gRed: false, g: ["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"] }), o2("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: oe.sha384, gRed: false, g: ["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"] }), o2("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: oe.sha512, gRed: false, g: ["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"] }), o2("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["9"] }), o2("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: oe.sha256, gRed: false, g: ["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", "6666666666666666666666666666666666666666666666666666666666666658"] }); - var h5; - try { - h5 = null.crash(); - } catch { - h5 = void 0; - } - o2("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: oe.sha256, beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [{ a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" }], gRed: false, g: ["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", h5] }); - }); - function Re(e2) { - if (!(this instanceof Re)) - return new Re(e2); - this.hash = e2.hash, this.predResist = !!e2.predResist, this.outLen = this.hash.outSize, this.minEntropy = e2.minEntropy || this.hash.hmacStrength, this._reseed = null, this.reseedInterval = null, this.K = null, this.V = null; - var t = ne.toArray(e2.entropy, e2.entropyEnc || "hex"), r = ne.toArray(e2.nonce, e2.nonceEnc || "hex"), i2 = ne.toArray(e2.pers, e2.persEnc || "hex"); - Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._init(t, r, i2); - } - var If = Re; - Re.prototype._init = function(t, r, i2) { - var n3 = t.concat(r).concat(i2); - this.K = new Array(this.outLen / 8), this.V = new Array(this.outLen / 8); - for (var o2 = 0; o2 < this.V.length; o2++) - this.K[o2] = 0, this.V[o2] = 1; - this._update(n3), this._reseed = 1, this.reseedInterval = 281474976710656; - }, Re.prototype._hmac = function() { - return new oe.hmac(this.hash, this.K); - }, Re.prototype._update = function(t) { - var r = this._hmac().update(this.V).update([0]); - t && (r = r.update(t)), this.K = r.digest(), this.V = this._hmac().update(this.V).digest(), t && (this.K = this._hmac().update(this.V).update([1]).update(t).digest(), this.V = this._hmac().update(this.V).digest()); - }, Re.prototype.reseed = function(t, r, i2, n3) { - typeof r != "string" && (n3 = i2, i2 = r, r = null), t = ne.toArray(t, r), i2 = ne.toArray(i2, n3), Ti(t.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._update(t.concat(i2 || [])), this._reseed = 1; - }, Re.prototype.generate = function(t, r, i2, n3) { - if (this._reseed > this.reseedInterval) - throw new Error("Reseed is required"); - typeof r != "string" && (n3 = i2, i2 = r, r = null), i2 && (i2 = ne.toArray(i2, n3 || "hex"), this._update(i2)); - for (var o2 = []; o2.length < t; ) - this.V = this._hmac().update(this.V).digest(), o2 = o2.concat(this.V); - var h5 = o2.slice(0, t); - return this._update(i2), this._reseed++, ne.encode(h5, r); - }; - var Di = Jt.assert; - function qt(e2, t) { - this.ec = e2, this.priv = null, this.pub = null, t.priv && this._importPrivate(t.priv, t.privEnc), t.pub && this._importPublic(t.pub, t.pubEnc); - } - var Ui = qt; - qt.fromPublic = function(t, r, i2) { - return r instanceof qt ? r : new qt(t, { pub: r, pubEnc: i2 }); - }, qt.fromPrivate = function(t, r, i2) { - return r instanceof qt ? r : new qt(t, { priv: r, privEnc: i2 }); - }, qt.prototype.validate = function() { - var t = this.getPublic(); - return t.isInfinity() ? { result: false, reason: "Invalid public key" } : t.validate() ? t.mul(this.ec.curve.n).isInfinity() ? { result: true, reason: null } : { result: false, reason: "Public key * N != O" } : { result: false, reason: "Public key is not a point" }; - }, qt.prototype.getPublic = function(t, r) { - return typeof t == "string" && (r = t, t = null), this.pub || (this.pub = this.ec.g.mul(this.priv)), r ? this.pub.encode(r, t) : this.pub; - }, qt.prototype.getPrivate = function(t) { - return t === "hex" ? this.priv.toString(16, 2) : this.priv; - }, qt.prototype._importPrivate = function(t, r) { - this.priv = new K2(t, r || 16), this.priv = this.priv.umod(this.ec.curve.n); - }, qt.prototype._importPublic = function(t, r) { - if (t.x || t.y) { - this.ec.curve.type === "mont" ? Di(t.x, "Need x coordinate") : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && Di(t.x && t.y, "Need both x and y coordinate"), this.pub = this.ec.curve.point(t.x, t.y); - return; - } - this.pub = this.ec.curve.decodePoint(t, r); - }, qt.prototype.derive = function(t) { - return t.validate() || Di(t.validate(), "public point not validated"), t.mul(this.priv).getX(); - }, qt.prototype.sign = function(t, r, i2) { - return this.ec.sign(t, this, r, i2); - }, qt.prototype.verify = function(t, r) { - return this.ec.verify(t, r, this); - }, qt.prototype.inspect = function() { - return ""; - }; - var F0 = Jt.assert; - function Lr(e2, t) { - if (e2 instanceof Lr) - return e2; - this._importDER(e2, t) || (F0(e2.r && e2.s, "Signature without r or s"), this.r = new K2(e2.r, 16), this.s = new K2(e2.s, 16), e2.recoveryParam === void 0 ? this.recoveryParam = null : this.recoveryParam = e2.recoveryParam); - } - var zr = Lr; - function D0() { - this.place = 0; - } - function ki(e2, t) { - var r = e2[t.place++]; - if (!(r & 128)) - return r; - var i2 = r & 15; - if (i2 === 0 || i2 > 4) - return false; - for (var n3 = 0, o2 = 0, h5 = t.place; o2 < i2; o2++, h5++) - n3 <<= 8, n3 |= e2[h5], n3 >>>= 0; - return n3 <= 127 ? false : (t.place = h5, n3); - } - function _f(e2) { - for (var t = 0, r = e2.length - 1; !e2[t] && !(e2[t + 1] & 128) && t < r; ) - t++; - return t === 0 ? e2 : e2.slice(t); - } - Lr.prototype._importDER = function(t, r) { - t = Jt.toArray(t, r); - var i2 = new D0(); - if (t[i2.place++] !== 48) - return false; - var n3 = ki(t, i2); - if (n3 === false || n3 + i2.place !== t.length || t[i2.place++] !== 2) - return false; - var o2 = ki(t, i2); - if (o2 === false) - return false; - var h5 = t.slice(i2.place, o2 + i2.place); - if (i2.place += o2, t[i2.place++] !== 2) - return false; - var p3 = ki(t, i2); - if (p3 === false || t.length !== p3 + i2.place) - return false; - var b4 = t.slice(i2.place, p3 + i2.place); - if (h5[0] === 0) - if (h5[1] & 128) - h5 = h5.slice(1); - else - return false; - if (b4[0] === 0) - if (b4[1] & 128) - b4 = b4.slice(1); - else - return false; - return this.r = new K2(h5), this.s = new K2(b4), this.recoveryParam = null, true; - }; - function qi(e2, t) { - if (t < 128) { - e2.push(t); - return; - } - var r = 1 + (Math.log(t) / Math.LN2 >>> 3); - for (e2.push(r | 128); --r; ) - e2.push(t >>> (r << 3) & 255); - e2.push(t); - } - Lr.prototype.toDER = function(t) { - var r = this.r.toArray(), i2 = this.s.toArray(); - for (r[0] & 128 && (r = [0].concat(r)), i2[0] & 128 && (i2 = [0].concat(i2)), r = _f(r), i2 = _f(i2); !i2[0] && !(i2[1] & 128); ) - i2 = i2.slice(1); - var n3 = [2]; - qi(n3, r.length), n3 = n3.concat(r), n3.push(2), qi(n3, i2.length); - var o2 = n3.concat(i2), h5 = [48]; - return qi(h5, o2.length), h5 = h5.concat(o2), Jt.encode(h5, t); - }; - var U0 = function() { - throw new Error("unsupported"); - }; - var Bf = Jt.assert; - function te(e2) { - if (!(this instanceof te)) - return new te(e2); - typeof e2 == "string" && (Bf(Object.prototype.hasOwnProperty.call(Hr, e2), "Unknown curve " + e2), e2 = Hr[e2]), e2 instanceof Hr.PresetCurve && (e2 = { curve: e2 }), this.curve = e2.curve.curve, this.n = this.curve.n, this.nh = this.n.ushrn(1), this.g = this.curve.g, this.g = e2.curve.g, this.g.precompute(e2.curve.n.bitLength() + 1), this.hash = e2.hash || e2.curve.hash; - } - var k0 = te; - te.prototype.keyPair = function(t) { - return new Ui(this, t); - }, te.prototype.keyFromPrivate = function(t, r) { - return Ui.fromPrivate(this, t, r); - }, te.prototype.keyFromPublic = function(t, r) { - return Ui.fromPublic(this, t, r); - }, te.prototype.genKeyPair = function(t) { - t || (t = {}); - for (var r = new If({ hash: this.hash, pers: t.pers, persEnc: t.persEnc || "utf8", entropy: t.entropy || U0(this.hash.hmacStrength), entropyEnc: t.entropy && t.entropyEnc || "utf8", nonce: this.n.toArray() }), i2 = this.n.byteLength(), n3 = this.n.sub(new K2(2)); ; ) { - var o2 = new K2(r.generate(i2)); - if (!(o2.cmp(n3) > 0)) - return o2.iaddn(1), this.keyFromPrivate(o2); - } - }, te.prototype._truncateToN = function(t, r) { - var i2 = t.byteLength() * 8 - this.n.bitLength(); - return i2 > 0 && (t = t.ushrn(i2)), !r && t.cmp(this.n) >= 0 ? t.sub(this.n) : t; - }, te.prototype.sign = function(t, r, i2, n3) { - typeof i2 == "object" && (n3 = i2, i2 = null), n3 || (n3 = {}), r = this.keyFromPrivate(r, i2), t = this._truncateToN(new K2(t, 16)); - for (var o2 = this.n.byteLength(), h5 = r.getPrivate().toArray("be", o2), p3 = t.toArray("be", o2), b4 = new If({ hash: this.hash, entropy: h5, nonce: p3, pers: n3.pers, persEnc: n3.persEnc || "utf8" }), g3 = this.n.sub(new K2(1)), w4 = 0; ; w4++) { - var y4 = n3.k ? n3.k(w4) : new K2(b4.generate(this.n.byteLength())); - if (y4 = this._truncateToN(y4, true), !(y4.cmpn(1) <= 0 || y4.cmp(g3) >= 0)) { - var S4 = this.g.mul(y4); - if (!S4.isInfinity()) { - var I2 = S4.getX(), N10 = I2.umod(this.n); - if (N10.cmpn(0) !== 0) { - var R2 = y4.invm(this.n).mul(N10.mul(r.getPrivate()).iadd(t)); - if (R2 = R2.umod(this.n), R2.cmpn(0) !== 0) { - var F = (S4.getY().isOdd() ? 1 : 0) | (I2.cmp(N10) !== 0 ? 2 : 0); - return n3.canonical && R2.cmp(this.nh) > 0 && (R2 = this.n.sub(R2), F ^= 1), new zr({ r: N10, s: R2, recoveryParam: F }); - } - } - } - } - } - }, te.prototype.verify = function(t, r, i2, n3) { - t = this._truncateToN(new K2(t, 16)), i2 = this.keyFromPublic(i2, n3), r = new zr(r, "hex"); - var o2 = r.r, h5 = r.s; - if (o2.cmpn(1) < 0 || o2.cmp(this.n) >= 0 || h5.cmpn(1) < 0 || h5.cmp(this.n) >= 0) - return false; - var p3 = h5.invm(this.n), b4 = p3.mul(t).umod(this.n), g3 = p3.mul(o2).umod(this.n), w4; - return this.curve._maxwellTrick ? (w4 = this.g.jmulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.eqXToP(o2)) : (w4 = this.g.mulAdd(b4, i2.getPublic(), g3), w4.isInfinity() ? false : w4.getX().umod(this.n).cmp(o2) === 0); - }, te.prototype.recoverPubKey = function(e2, t, r, i2) { - Bf((3 & r) === r, "The recovery param is more than two bits"), t = new zr(t, i2); - var n3 = this.n, o2 = new K2(e2), h5 = t.r, p3 = t.s, b4 = r & 1, g3 = r >> 1; - if (h5.cmp(this.curve.p.umod(this.curve.n)) >= 0 && g3) - throw new Error("Unable to find sencond key candinate"); - g3 ? h5 = this.curve.pointFromX(h5.add(this.curve.n), b4) : h5 = this.curve.pointFromX(h5, b4); - var w4 = t.r.invm(n3), y4 = n3.sub(o2).mul(w4).umod(n3), S4 = p3.mul(w4).umod(n3); - return this.g.mulAdd(y4, h5, S4); - }, te.prototype.getKeyRecoveryParam = function(e2, t, r, i2) { - if (t = new zr(t, i2), t.recoveryParam !== null) - return t.recoveryParam; - for (var n3 = 0; n3 < 4; n3++) { - var o2; - try { - o2 = this.recoverPubKey(e2, t, n3); - } catch { - continue; - } - if (o2.eq(r)) - return n3; - } - throw new Error("Unable to find valid recovery factor"); - }; - var q0 = lr(function(e2, t) { - var r = t; - r.version = "6.5.4", r.utils = Jt, r.rand = function() { - throw new Error("unsupported"); - }, r.curve = Kr, r.curves = Hr, r.ec = k0, r.eddsa = null; - }); - var K0 = q0.ec; - var H0 = "signing-key/5.7.0"; - var Ki = new z3(H0); - var Hi = null; - function pe() { - return Hi || (Hi = new K0("secp256k1")), Hi; - } - var L0 = class { - constructor(t) { - yr(this, "curve", "secp256k1"), yr(this, "privateKey", Ht(t)), xs(this.privateKey) !== 32 && Ki.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); - const r = pe().keyFromPrivate(Pt(this.privateKey)); - yr(this, "publicKey", "0x" + r.getPublic(false, "hex")), yr(this, "compressedPublicKey", "0x" + r.getPublic(true, "hex")), yr(this, "_isSigningKey", true); - } - _addPoint(t) { - const r = pe().keyFromPublic(Pt(this.publicKey)), i2 = pe().keyFromPublic(Pt(t)); - return "0x" + r.pub.add(i2.pub).encodeCompressed("hex"); - } - signDigest(t) { - const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = Pt(t); - i2.length !== 32 && Ki.throwArgumentError("bad digest length", "digest", t); - const n3 = r.sign(i2, { canonical: true }); - return kn({ recoveryParam: n3.recoveryParam, r: fe("0x" + n3.r.toString(16), 32), s: fe("0x" + n3.s.toString(16), 32) }); - } - computeSharedSecret(t) { - const r = pe().keyFromPrivate(Pt(this.privateKey)), i2 = pe().keyFromPublic(Pt(Rf(t))); - return fe("0x" + r.derive(i2.getPublic()).toString(16), 32); - } - static isSigningKey(t) { - return !!(t && t._isSigningKey); - } - }; - function z0(e2, t) { - const r = kn(t), i2 = { r: Pt(r.r), s: Pt(r.s) }; - return "0x" + pe().recoverPubKey(Pt(e2), i2, r.recoveryParam).encode("hex", false); - } - function Rf(e2, t) { - const r = Pt(e2); - if (r.length === 32) { - const i2 = new L0(r); - return t ? "0x" + pe().keyFromPrivate(r).getPublic(true, "hex") : i2.publicKey; - } else { - if (r.length === 33) - return t ? Ht(r) : "0x" + pe().keyFromPublic(r).getPublic(false, "hex"); - if (r.length === 65) - return t ? "0x" + pe().keyFromPublic(r).getPublic(true, "hex") : Ht(r); - } - return Ki.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); - } - var j0 = "transactions/5.7.0"; - new z3(j0); - var Cf; - (function(e2) { - e2[e2.legacy = 0] = "legacy", e2[e2.eip2930 = 1] = "eip2930", e2[e2.eip1559 = 2] = "eip1559"; - })(Cf || (Cf = {})); - function V0(e2) { - const t = Rf(e2); - return ta(Un(wi(Un(t, 1)), 12)); - } - function Q0(e2, t) { - return V0(z0(Pt(e2), t)); - } - var J0 = "https://rpc.walletconnect.com/v1"; - async function Of(e2, t, r, i2, n3, o2) { - switch (r.t) { - case "eip191": - return Pf(e2, t, r.s); - case "eip1271": - return await Tf(e2, t, r.s, i2, n3, o2); - default: - throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`); - } - } - function Pf(e2, t, r) { - return Q0(tf(t), r).toLowerCase() === e2.toLowerCase(); - } - async function Tf(e2, t, r, i2, n3, o2) { - try { - const h5 = "0x1626ba7e", p3 = "0000000000000000000000000000000000000000000000000000000000000040", b4 = "0000000000000000000000000000000000000000000000000000000000000041", g3 = r.substring(2), w4 = tf(t).substring(2), y4 = h5 + w4 + p3 + b4 + g3, S4 = await fetch(`${o2 || J0}/?chainId=${i2}&projectId=${n3}`, { method: "POST", body: JSON.stringify({ id: Y0(), jsonrpc: "2.0", method: "eth_call", params: [{ to: e2, data: y4 }, "latest"] }) }), { result: I2 } = await S4.json(); - return I2 ? I2.slice(0, h5.length).toLowerCase() === h5.toLowerCase() : false; - } catch (h5) { - return console.error("isValidEip1271Signature: ", h5), false; - } - } - function Y0() { - return Date.now() + Math.floor(Math.random() * 1e3); - } - var G0 = Object.defineProperty; - var W0 = Object.defineProperties; - var X0 = Object.getOwnPropertyDescriptors; - var Ff = Object.getOwnPropertySymbols; - var Z0 = Object.prototype.hasOwnProperty; - var $0 = Object.prototype.propertyIsEnumerable; - var Df = (e2, t, r) => t in e2 ? G0(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var Li = (e2, t) => { - for (var r in t || (t = {})) - Z0.call(t, r) && Df(e2, r, t[r]); - if (Ff) - for (var r of Ff(t)) - $0.call(t, r) && Df(e2, r, t[r]); - return e2; - }; - var Uf = (e2, t) => W0(e2, X0(t)); - var tu = "did:pkh:"; - var jr = (e2) => e2?.split(":"); - var zi = (e2) => { - const t = e2 && jr(e2); - if (t) - return e2.includes(tu) ? t[3] : t[1]; - }; - var eu = (e2) => { - const t = e2 && jr(e2); - if (t) - return t[2] + ":" + t[3]; - }; - var ji = (e2) => { - const t = e2 && jr(e2); - if (t) - return t.pop(); - }; - async function ru(e2) { - const { cacao: t, projectId: r } = e2, { s: i2, p: n3 } = t, o2 = kf(n3, n3.iss), h5 = ji(n3.iss); - return await Of(h5, o2, i2, zi(n3.iss), r); - } - var kf = (e2, t) => { - const r = `${e2.domain} wants you to sign in with your Ethereum account:`, i2 = ji(t); - if (!e2.aud && !e2.uri) - throw new Error("Either `aud` or `uri` is required to construct the message"); - let n3 = e2.statement || void 0; - const o2 = `URI: ${e2.aud || e2.uri}`, h5 = `Version: ${e2.version}`, p3 = `Chain ID: ${zi(t)}`, b4 = `Nonce: ${e2.nonce}`, g3 = `Issued At: ${e2.iat}`, w4 = e2.resources ? `Resources:${e2.resources.map((S4) => ` -- ${S4}`).join("")}` : void 0, y4 = Qr(e2.resources); - if (y4) { - const S4 = Ce(y4); - n3 = Ji(n3, S4); - } - return [r, i2, "", n3, "", o2, h5, p3, b4, g3, w4].filter((S4) => S4 != null).join(` -`); - }; - function iu(e2, t, r) { - return r.includes("did:pkh:") || (r = `did:pkh:${r}`), { h: { t: "caip122" }, p: { iss: r, domain: e2.domain, aud: e2.aud, version: e2.version, nonce: e2.nonce, iat: e2.iat, statement: e2.statement, requestId: e2.requestId, resources: e2.resources, nbf: e2.nbf, exp: e2.exp }, s: t }; - } - function nu(e2) { - var t; - const { authPayload: r, chains: i2, methods: n3 } = e2, o2 = r.statement || ""; - if (!(i2 != null && i2.length)) - return r; - const h5 = r.chains, p3 = mi(h5, i2); - if (!(p3 != null && p3.length)) - throw new Error("No supported chains"); - const b4 = qf(r.resources); - if (!b4) - return r; - ve(b4); - const g3 = Kf(b4, "eip155"); - let w4 = r?.resources || []; - if (g3 != null && g3.length) { - const y4 = Hf(g3), S4 = mi(y4, n3); - if (!(S4 != null && S4.length)) - throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(y4)}, supported: ${JSON.stringify(n3)}`); - const I2 = Vi("request", S4, { chains: p3 }), N10 = Vf(b4, "eip155", I2); - w4 = ((t = r?.resources) == null ? void 0 : t.slice(0, -1)) || [], w4.push(Vr(N10)); - } - return Uf(Li({}, r), { statement: Jf(o2, Qr(w4)), chains: p3, resources: r != null && r.resources || w4.length > 0 ? w4 : void 0 }); - } - function qf(e2) { - const t = Qr(e2); - if (t && Qi(t)) - return Ce(t); - } - function fu(e2, t) { - var r; - return (r = e2?.att) == null ? void 0 : r.hasOwnProperty(t); - } - function Kf(e2, t) { - var r, i2; - return (r = e2?.att) != null && r[t] ? Object.keys((i2 = e2?.att) == null ? void 0 : i2[t]) : []; - } - function ou(e2) { - return e2?.map((t) => Object.keys(t)) || []; - } - function Hf(e2) { - return e2?.map((t) => { - var r; - return (r = t.split("/")) == null ? void 0 : r[1]; - }) || []; - } - function Lf(e2) { - return import_buffer.Buffer.from(JSON.stringify(e2)).toString("base64"); - } - function zf(e2) { - return JSON.parse(import_buffer.Buffer.from(e2, "base64").toString("utf-8")); - } - function ve(e2) { - if (!e2) - throw new Error("No recap provided, value is undefined"); - if (!e2.att) - throw new Error("No `att` property found"); - const t = Object.keys(e2.att); - if (!(t != null && t.length)) - throw new Error("No resources found in `att` property"); - t.forEach((r) => { - const i2 = e2.att[r]; - if (Array.isArray(i2)) - throw new Error(`Resource must be an object: ${r}`); - if (typeof i2 != "object") - throw new Error(`Resource must be an object: ${r}`); - if (!Object.keys(i2).length) - throw new Error(`Resource object is empty: ${r}`); - Object.keys(i2).forEach((n3) => { - const o2 = i2[n3]; - if (!Array.isArray(o2)) - throw new Error(`Ability limits ${n3} must be an array of objects, found: ${o2}`); - if (!o2.length) - throw new Error(`Value of ${n3} is empty array, must be an array with objects`); - o2.forEach((h5) => { - if (typeof h5 != "object") - throw new Error(`Ability limits (${n3}) must be an array of objects, found: ${h5}`); - }); - }); - }); - } - function jf(e2, t, r, i2 = {}) { - return r?.sort((n3, o2) => n3.localeCompare(o2)), { att: { [e2]: Vi(t, r, i2) } }; - } - function Vf(e2, t, r) { - var i2; - return e2.att[t] = Li({}, r), ((i2 = Object.keys(e2.att)) == null ? void 0 : i2.sort((n3, o2) => n3.localeCompare(o2))).reduce((n3, o2) => (n3.att[o2] = e2.att[o2], n3), { att: {} }); - } - function Vi(e2, t, r = {}) { - t = t?.sort((n3, o2) => n3.localeCompare(o2)); - const i2 = t.map((n3) => ({ [`${e2}/${n3}`]: [r] })); - return Object.assign({}, ...i2); - } - function Vr(e2) { - return ve(e2), `urn:recap:${Lf(e2).replace(/=/g, "")}`; - } - function Ce(e2) { - const t = zf(e2.replace("urn:recap:", "")); - return ve(t), t; - } - function su(e2, t, r) { - const i2 = jf(e2, t, r); - return Vr(i2); - } - function Qi(e2) { - return e2 && e2.includes("urn:recap:"); - } - function au(e2, t) { - const r = Ce(e2), i2 = Ce(t), n3 = Qf(r, i2); - return Vr(n3); - } - function Qf(e2, t) { - ve(e2), ve(t); - const r = Object.keys(e2.att).concat(Object.keys(t.att)).sort((n3, o2) => n3.localeCompare(o2)), i2 = { att: {} }; - return r.forEach((n3) => { - var o2, h5; - Object.keys(((o2 = e2.att) == null ? void 0 : o2[n3]) || {}).concat(Object.keys(((h5 = t.att) == null ? void 0 : h5[n3]) || {})).sort((p3, b4) => p3.localeCompare(b4)).forEach((p3) => { - var b4, g3; - i2.att[n3] = Uf(Li({}, i2.att[n3]), { [p3]: ((b4 = e2.att[n3]) == null ? void 0 : b4[p3]) || ((g3 = t.att[n3]) == null ? void 0 : g3[p3]) }); - }); - }), i2; - } - function Ji(e2 = "", t) { - ve(t); - const r = "I further authorize the stated URI to perform the following actions on my behalf: "; - if (e2.includes(r)) - return e2; - const i2 = []; - let n3 = 0; - Object.keys(t.att).forEach((p3) => { - const b4 = Object.keys(t.att[p3]).map((y4) => ({ ability: y4.split("/")[0], action: y4.split("/")[1] })); - b4.sort((y4, S4) => y4.action.localeCompare(S4.action)); - const g3 = {}; - b4.forEach((y4) => { - g3[y4.ability] || (g3[y4.ability] = []), g3[y4.ability].push(y4.action); - }); - const w4 = Object.keys(g3).map((y4) => (n3++, `(${n3}) '${y4}': '${g3[y4].join("', '")}' for '${p3}'.`)); - i2.push(w4.join(", ").replace(".,", ".")); - }); - const o2 = i2.join(" "), h5 = `${r}${o2}`; - return `${e2 ? e2 + " " : ""}${h5}`; - } - function uu(e2) { - var t; - const r = Ce(e2); - ve(r); - const i2 = (t = r.att) == null ? void 0 : t.eip155; - return i2 ? Object.keys(i2).map((n3) => n3.split("/")[1]) : []; - } - function hu(e2) { - const t = Ce(e2); - ve(t); - const r = []; - return Object.values(t.att).forEach((i2) => { - Object.values(i2).forEach((n3) => { - var o2; - (o2 = n3?.[0]) != null && o2.chains && r.push(n3[0].chains); - }); - }), [...new Set(r.flat())]; - } - function Jf(e2, t) { - if (!t) - return e2; - const r = Ce(t); - return ve(r), Ji(e2, r); - } - function Qr(e2) { - if (!e2) - return; - const t = e2?.[e2.length - 1]; - return Qi(t) ? t : void 0; - } - var Yi = "base10"; - var zt = "base16"; - var Jr = "base64pad"; - var Yr = "utf8"; - var Gi = 0; - var dr = 1; - var cu = 0; - var Yf = 1; - var Wi = 12; - var Xi = 32; - function lu() { - const e2 = an.generateKeyPair(); - return { privateKey: Rt.toString(e2.secretKey, zt), publicKey: Rt.toString(e2.publicKey, zt) }; - } - function du() { - const e2 = on.randomBytes(Xi); - return Rt.toString(e2, zt); - } - function pu(e2, t) { - const r = an.sharedKey(Rt.fromString(e2, zt), Rt.fromString(t, zt), true), i2 = new Po.HKDF(ci.SHA256, r).expand(Xi); - return Rt.toString(i2, zt); - } - function vu(e2) { - const t = ci.hash(Rt.fromString(e2, zt)); - return Rt.toString(t, zt); - } - function gu(e2) { - const t = ci.hash(Rt.fromString(e2, Yr)); - return Rt.toString(t, zt); - } - function Gf(e2) { - return Rt.fromString(`${e2}`, Yi); - } - function Er(e2) { - return Number(Rt.toString(e2, Yi)); - } - function mu(e2) { - const t = Gf(typeof e2.type < "u" ? e2.type : Gi); - if (Er(t) === dr && typeof e2.senderPublicKey > "u") - throw new Error("Missing sender public key for type 1 envelope"); - const r = typeof e2.senderPublicKey < "u" ? Rt.fromString(e2.senderPublicKey, zt) : void 0, i2 = typeof e2.iv < "u" ? Rt.fromString(e2.iv, zt) : on.randomBytes(Wi), n3 = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)).seal(i2, Rt.fromString(e2.message, Yr)); - return Wf({ type: t, sealed: n3, iv: i2, senderPublicKey: r }); - } - function Au(e2) { - const t = new fn.ChaCha20Poly1305(Rt.fromString(e2.symKey, zt)), { sealed: r, iv: i2 } = Zi(e2.encoded), n3 = t.open(i2, r); - if (n3 === null) - throw new Error("Failed to decrypt"); - return Rt.toString(n3, Yr); - } - function Wf(e2) { - if (Er(e2.type) === dr) { - if (typeof e2.senderPublicKey > "u") - throw new Error("Missing sender public key for type 1 envelope"); - return Rt.toString(Rt.concat([e2.type, e2.senderPublicKey, e2.iv, e2.sealed]), Jr); - } - return Rt.toString(Rt.concat([e2.type, e2.iv, e2.sealed]), Jr); - } - function Zi(e2) { - const t = Rt.fromString(e2, Jr), r = t.slice(cu, Yf), i2 = Yf; - if (Er(r) === dr) { - const p3 = i2 + Xi, b4 = p3 + Wi, g3 = t.slice(i2, p3), w4 = t.slice(p3, b4), y4 = t.slice(b4); - return { type: r, sealed: y4, iv: w4, senderPublicKey: g3 }; - } - const n3 = i2 + Wi, o2 = t.slice(i2, n3), h5 = t.slice(n3); - return { type: r, sealed: h5, iv: o2 }; - } - function bu(e2, t) { - const r = Zi(e2); - return Xf({ type: Er(r.type), senderPublicKey: typeof r.senderPublicKey < "u" ? Rt.toString(r.senderPublicKey, zt) : void 0, receiverPublicKey: t?.receiverPublicKey }); - } - function Xf(e2) { - const t = e2?.type || Gi; - if (t === dr) { - if (typeof e2?.senderPublicKey > "u") - throw new Error("missing sender public key"); - if (typeof e2?.receiverPublicKey > "u") - throw new Error("missing receiver public key"); - } - return { type: t, senderPublicKey: e2?.senderPublicKey, receiverPublicKey: e2?.receiverPublicKey }; - } - function yu(e2) { - return e2.type === dr && typeof e2.senderPublicKey == "string" && typeof e2.receiverPublicKey == "string"; - } - var Zf = "irn"; - function wu(e2) { - return e2?.relay || { protocol: Zf }; - } - function xu(e2) { - const t = Fo.RELAY_JSONRPC[e2]; - if (typeof t > "u") - throw new Error(`Relay Protocol not supported: ${e2}`); - return t; - } - var Mu = Object.defineProperty; - var Eu = Object.defineProperties; - var Su = Object.getOwnPropertyDescriptors; - var $f = Object.getOwnPropertySymbols; - var Nu = Object.prototype.hasOwnProperty; - var Iu = Object.prototype.propertyIsEnumerable; - var to = (e2, t, r) => t in e2 ? Mu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var eo = (e2, t) => { - for (var r in t || (t = {})) - Nu.call(t, r) && to(e2, r, t[r]); - if ($f) - for (var r of $f(t)) - Iu.call(t, r) && to(e2, r, t[r]); - return e2; - }; - var _u = (e2, t) => Eu(e2, Su(t)); - function ro(e2, t = "-") { - const r = {}, i2 = "relay" + t; - return Object.keys(e2).forEach((n3) => { - if (n3.startsWith(i2)) { - const o2 = n3.replace(i2, ""), h5 = e2[n3]; - r[o2] = h5; - } - }), r; - } - function Bu(e2) { - e2 = e2.includes("wc://") ? e2.replace("wc://", "") : e2, e2 = e2.includes("wc:") ? e2.replace("wc:", "") : e2; - const t = e2.indexOf(":"), r = e2.indexOf("?") !== -1 ? e2.indexOf("?") : void 0, i2 = e2.substring(0, t), n3 = e2.substring(t + 1, r).split("@"), o2 = typeof r < "u" ? e2.substring(r) : "", h5 = Ir.parse(o2), p3 = typeof h5.methods == "string" ? h5.methods.split(",") : void 0; - return { protocol: i2, topic: io(n3[0]), version: parseInt(n3[1], 10), symKey: h5.symKey, relay: ro(h5), methods: p3, expiryTimestamp: h5.expiryTimestamp ? parseInt(h5.expiryTimestamp, 10) : void 0 }; - } - function io(e2) { - return e2.startsWith("//") ? e2.substring(2) : e2; - } - function no(e2, t = "-") { - const r = "relay", i2 = {}; - return Object.keys(e2).forEach((n3) => { - const o2 = r + t + n3; - e2[n3] && (i2[o2] = e2[n3]); - }), i2; - } - function Ru(e2) { - return `${e2.protocol}:${e2.topic}@${e2.version}?` + Ir.stringify(eo(_u(eo({ symKey: e2.symKey }, no(e2.relay)), { expiryTimestamp: e2.expiryTimestamp }), e2.methods ? { methods: e2.methods.join(",") } : {})); - } - var Cu = Object.defineProperty; - var Ou = Object.defineProperties; - var Pu = Object.getOwnPropertyDescriptors; - var fo = Object.getOwnPropertySymbols; - var Tu = Object.prototype.hasOwnProperty; - var Fu = Object.prototype.propertyIsEnumerable; - var oo = (e2, t, r) => t in e2 ? Cu(e2, t, { enumerable: true, configurable: true, writable: true, value: r }) : e2[t] = r; - var Du = (e2, t) => { - for (var r in t || (t = {})) - Tu.call(t, r) && oo(e2, r, t[r]); - if (fo) - for (var r of fo(t)) - Fu.call(t, r) && oo(e2, r, t[r]); - return e2; - }; - var Uu = (e2, t) => Ou(e2, Pu(t)); - function Ze(e2) { - const t = []; - return e2.forEach((r) => { - const [i2, n3] = r.split(":"); - t.push(`${i2}:${n3}`); - }), t; - } - function so(e2) { - const t = []; - return Object.values(e2).forEach((r) => { - t.push(...Ze(r.accounts)); - }), t; - } - function ao(e2, t) { - const r = []; - return Object.values(e2).forEach((i2) => { - Ze(i2.accounts).includes(t) && r.push(...i2.methods); - }), r; - } - function uo(e2, t) { - const r = []; - return Object.values(e2).forEach((i2) => { - Ze(i2.accounts).includes(t) && r.push(...i2.events); - }), r; - } - function ku(e2, t) { - const r = wo(e2, t); - if (r) - throw new Error(r.message); - const i2 = {}; - for (const [n3, o2] of Object.entries(e2)) - i2[n3] = { methods: o2.methods, events: o2.events, chains: o2.accounts.map((h5) => `${h5.split(":")[0]}:${h5.split(":")[1]}`) }; - return i2; - } - function qu(e2) { - const { proposal: { requiredNamespaces: t, optionalNamespaces: r = {} }, supportedNamespaces: i2 } = e2, n3 = tn(t), o2 = tn(r), h5 = {}; - Object.keys(i2).forEach((g3) => { - const w4 = i2[g3].chains, y4 = i2[g3].methods, S4 = i2[g3].events, I2 = i2[g3].accounts; - w4.forEach((N10) => { - if (!I2.some((R2) => R2.includes(N10))) - throw new Error(`No accounts provided for chain ${N10} in namespace ${g3}`); - }), h5[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; - }); - const p3 = Mo(t, h5, "approve()"); - if (p3) - throw new Error(p3.message); - const b4 = {}; - return !Object.keys(t).length && !Object.keys(r).length ? h5 : (Object.keys(n3).forEach((g3) => { - const w4 = i2[g3].chains.filter((N10) => { - var R2, F; - return (F = (R2 = n3[g3]) == null ? void 0 : R2.chains) == null ? void 0 : F.includes(N10); - }), y4 = i2[g3].methods.filter((N10) => { - var R2, F; - return (F = (R2 = n3[g3]) == null ? void 0 : R2.methods) == null ? void 0 : F.includes(N10); - }), S4 = i2[g3].events.filter((N10) => { - var R2, F; - return (F = (R2 = n3[g3]) == null ? void 0 : R2.events) == null ? void 0 : F.includes(N10); - }), I2 = w4.map((N10) => i2[g3].accounts.filter((R2) => R2.includes(`${N10}:`))).flat(); - b4[g3] = { chains: w4, methods: y4, events: S4, accounts: I2 }; - }), Object.keys(o2).forEach((g3) => { - var w4, y4, S4, I2, N10, R2; - if (!i2[g3]) - return; - const F = (y4 = (w4 = o2[g3]) == null ? void 0 : w4.chains) == null ? void 0 : y4.filter((J) => i2[g3].chains.includes(J)), U2 = i2[g3].methods.filter((J) => { - var H, L2; - return (L2 = (H = o2[g3]) == null ? void 0 : H.methods) == null ? void 0 : L2.includes(J); - }), Q = i2[g3].events.filter((J) => { - var H, L2; - return (L2 = (H = o2[g3]) == null ? void 0 : H.events) == null ? void 0 : L2.includes(J); - }), Bt = F?.map((J) => i2[g3].accounts.filter((H) => H.includes(`${J}:`))).flat(); - b4[g3] = { chains: ge((S4 = b4[g3]) == null ? void 0 : S4.chains, F), methods: ge((I2 = b4[g3]) == null ? void 0 : I2.methods, U2), events: ge((N10 = b4[g3]) == null ? void 0 : N10.events, Q), accounts: ge((R2 = b4[g3]) == null ? void 0 : R2.accounts, Bt) }; - }), b4); - } - function $i(e2) { - return e2.includes(":"); - } - function ho(e2) { - return $i(e2) ? e2.split(":")[0] : e2; - } - function tn(e2) { - var t, r, i2; - const n3 = {}; - if (!Gr(e2)) - return n3; - for (const [o2, h5] of Object.entries(e2)) { - const p3 = $i(o2) ? [o2] : h5.chains, b4 = h5.methods || [], g3 = h5.events || [], w4 = ho(o2); - n3[w4] = Uu(Du({}, n3[w4]), { chains: ge(p3, (t = n3[w4]) == null ? void 0 : t.chains), methods: ge(b4, (r = n3[w4]) == null ? void 0 : r.methods), events: ge(g3, (i2 = n3[w4]) == null ? void 0 : i2.events) }); - } - return n3; - } - function co(e2) { - const t = {}; - return e2?.forEach((r) => { - const [i2, n3] = r.split(":"); - t[i2] || (t[i2] = { accounts: [], chains: [], events: [] }), t[i2].accounts.push(r), t[i2].chains.push(`${i2}:${n3}`); - }), t; - } - function Ku(e2, t) { - t = t.map((i2) => i2.replace("did:pkh:", "")); - const r = co(t); - for (const [i2, n3] of Object.entries(r)) - n3.methods ? n3.methods = ge(n3.methods, e2) : n3.methods = e2, n3.events = ["chainChanged", "accountsChanged"]; - return r; - } - var lo = { INVALID_METHOD: { message: "Invalid method.", code: 1001 }, INVALID_EVENT: { message: "Invalid event.", code: 1002 }, INVALID_UPDATE_REQUEST: { message: "Invalid update request.", code: 1003 }, INVALID_EXTEND_REQUEST: { message: "Invalid extend request.", code: 1004 }, INVALID_SESSION_SETTLE_REQUEST: { message: "Invalid session settle request.", code: 1005 }, UNAUTHORIZED_METHOD: { message: "Unauthorized method.", code: 3001 }, UNAUTHORIZED_EVENT: { message: "Unauthorized event.", code: 3002 }, UNAUTHORIZED_UPDATE_REQUEST: { message: "Unauthorized update request.", code: 3003 }, UNAUTHORIZED_EXTEND_REQUEST: { message: "Unauthorized extend request.", code: 3004 }, USER_REJECTED: { message: "User rejected.", code: 5e3 }, USER_REJECTED_CHAINS: { message: "User rejected chains.", code: 5001 }, USER_REJECTED_METHODS: { message: "User rejected methods.", code: 5002 }, USER_REJECTED_EVENTS: { message: "User rejected events.", code: 5003 }, UNSUPPORTED_CHAINS: { message: "Unsupported chains.", code: 5100 }, UNSUPPORTED_METHODS: { message: "Unsupported methods.", code: 5101 }, UNSUPPORTED_EVENTS: { message: "Unsupported events.", code: 5102 }, UNSUPPORTED_ACCOUNTS: { message: "Unsupported accounts.", code: 5103 }, UNSUPPORTED_NAMESPACE_KEY: { message: "Unsupported namespace key.", code: 5104 }, USER_DISCONNECTED: { message: "User disconnected.", code: 6e3 }, SESSION_SETTLEMENT_FAILED: { message: "Session settlement failed.", code: 7e3 }, WC_METHOD_UNSUPPORTED: { message: "Unsupported wc_ method.", code: 10001 } }; - var po = { NOT_INITIALIZED: { message: "Not initialized.", code: 1 }, NO_MATCHING_KEY: { message: "No matching key.", code: 2 }, RESTORE_WILL_OVERRIDE: { message: "Restore will override.", code: 3 }, RESUBSCRIBED: { message: "Resubscribed.", code: 4 }, MISSING_OR_INVALID: { message: "Missing or invalid.", code: 5 }, EXPIRED: { message: "Expired.", code: 6 }, UNKNOWN_TYPE: { message: "Unknown type.", code: 7 }, MISMATCHED_TOPIC: { message: "Mismatched topic.", code: 8 }, NON_CONFORMING_NAMESPACES: { message: "Non conforming namespaces.", code: 9 } }; - function we(e2, t) { - const { message: r, code: i2 } = po[e2]; - return { message: t ? `${r} ${t}` : r, code: i2 }; - } - function $e(e2, t) { - const { message: r, code: i2 } = lo[e2]; - return { message: t ? `${r} ${t}` : r, code: i2 }; - } - function Sr(e2, t) { - return Array.isArray(e2) ? typeof t < "u" && e2.length ? e2.every(t) : true : false; - } - function Gr(e2) { - return Object.getPrototypeOf(e2) === Object.prototype && Object.keys(e2).length; - } - function Oe(e2) { - return typeof e2 > "u"; - } - function Yt(e2, t) { - return t && Oe(e2) ? true : typeof e2 == "string" && !!e2.trim().length; - } - function Wr(e2, t) { - return t && Oe(e2) ? true : typeof e2 == "number" && !isNaN(e2); - } - function Hu(e2, t) { - const { requiredNamespaces: r } = t, i2 = Object.keys(e2.namespaces), n3 = Object.keys(r); - let o2 = true; - return Ie(n3, i2) ? (i2.forEach((h5) => { - const { accounts: p3, methods: b4, events: g3 } = e2.namespaces[h5], w4 = Ze(p3), y4 = r[h5]; - (!Ie(Br(h5, y4), w4) || !Ie(y4.methods, b4) || !Ie(y4.events, g3)) && (o2 = false); - }), o2) : false; - } - function Nr(e2) { - return Yt(e2, false) && e2.includes(":") ? e2.split(":").length === 2 : false; - } - function vo(e2) { - if (Yt(e2, false) && e2.includes(":")) { - const t = e2.split(":"); - if (t.length === 3) { - const r = t[0] + ":" + t[1]; - return !!t[2] && Nr(r); - } - } - return false; - } - function Lu(e2) { - if (Yt(e2, false)) - try { - return typeof new URL(e2) < "u"; - } catch { - return false; - } - return false; - } - function zu(e2) { - var t; - return (t = e2?.proposer) == null ? void 0 : t.publicKey; - } - function ju(e2) { - return e2?.topic; - } - function Vu(e2, t) { - let r = null; - return Yt(e2?.publicKey, false) || (r = we("MISSING_OR_INVALID", `${t} controller public key should be a string`)), r; - } - function en(e2) { - let t = true; - return Sr(e2) ? e2.length && (t = e2.every((r) => Yt(r, false))) : t = false, t; - } - function go(e2, t, r) { - let i2 = null; - return Sr(t) && t.length ? t.forEach((n3) => { - i2 || Nr(n3) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chain ${n3} should be a string and conform to "namespace:chainId" format`)); - }) : Nr(e2) || (i2 = $e("UNSUPPORTED_CHAINS", `${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)), i2; - } - function mo(e2, t, r) { - let i2 = null; - return Object.entries(e2).forEach(([n3, o2]) => { - if (i2) - return; - const h5 = go(n3, Br(n3, o2), `${t} ${r}`); - h5 && (i2 = h5); - }), i2; - } - function Ao(e2, t) { - let r = null; - return Sr(e2) ? e2.forEach((i2) => { - r || vo(i2) || (r = $e("UNSUPPORTED_ACCOUNTS", `${t}, account ${i2} should be a string and conform to "namespace:chainId:address" format`)); - }) : r = $e("UNSUPPORTED_ACCOUNTS", `${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`), r; - } - function bo(e2, t) { - let r = null; - return Object.values(e2).forEach((i2) => { - if (r) - return; - const n3 = Ao(i2?.accounts, `${t} namespace`); - n3 && (r = n3); - }), r; - } - function yo(e2, t) { - let r = null; - return en(e2?.methods) ? en(e2?.events) || (r = $e("UNSUPPORTED_EVENTS", `${t}, events should be an array of strings or empty array for no events`)) : r = $e("UNSUPPORTED_METHODS", `${t}, methods should be an array of strings or empty array for no methods`), r; - } - function rn(e2, t) { - let r = null; - return Object.values(e2).forEach((i2) => { - if (r) - return; - const n3 = yo(i2, `${t}, namespace`); - n3 && (r = n3); - }), r; - } - function Qu(e2, t, r) { - let i2 = null; - if (e2 && Gr(e2)) { - const n3 = rn(e2, t); - n3 && (i2 = n3); - const o2 = mo(e2, t, r); - o2 && (i2 = o2); - } else - i2 = we("MISSING_OR_INVALID", `${t}, ${r} should be an object with data`); - return i2; - } - function wo(e2, t) { - let r = null; - if (e2 && Gr(e2)) { - const i2 = rn(e2, t); - i2 && (r = i2); - const n3 = bo(e2, t); - n3 && (r = n3); - } else - r = we("MISSING_OR_INVALID", `${t}, namespaces should be an object with data`); - return r; - } - function xo(e2) { - return Yt(e2.protocol, true); - } - function Ju(e2, t) { - let r = false; - return t && !e2 ? r = true : e2 && Sr(e2) && e2.length && e2.forEach((i2) => { - r = xo(i2); - }), r; - } - function Yu(e2) { - return typeof e2 == "number"; - } - function Gu(e2) { - return typeof e2 < "u" && typeof e2 !== null; - } - function Wu(e2) { - return !(!e2 || typeof e2 != "object" || !e2.code || !Wr(e2.code, false) || !e2.message || !Yt(e2.message, false)); - } - function Xu(e2) { - return !(Oe(e2) || !Yt(e2.method, false)); - } - function Zu(e2) { - return !(Oe(e2) || Oe(e2.result) && Oe(e2.error) || !Wr(e2.id, false) || !Yt(e2.jsonrpc, false)); - } - function $u(e2) { - return !(Oe(e2) || !Yt(e2.name, false)); - } - function th(e2, t) { - return !(!Nr(t) || !so(e2).includes(t)); - } - function eh(e2, t, r) { - return Yt(r, false) ? ao(e2, t).includes(r) : false; - } - function rh(e2, t, r) { - return Yt(r, false) ? uo(e2, t).includes(r) : false; - } - function Mo(e2, t, r) { - let i2 = null; - const n3 = ih(e2), o2 = nh(t), h5 = Object.keys(n3), p3 = Object.keys(o2), b4 = Eo(Object.keys(e2)), g3 = Eo(Object.keys(t)), w4 = b4.filter((y4) => !g3.includes(y4)); - return w4.length && (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces keys don't satisfy requiredNamespaces. - Required: ${w4.toString()} - Received: ${Object.keys(t).toString()}`)), Ie(h5, p3) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces chains don't satisfy required namespaces. - Required: ${h5.toString()} - Approved: ${p3.toString()}`)), Object.keys(t).forEach((y4) => { - if (!y4.includes(":") || i2) - return; - const S4 = Ze(t[y4].accounts); - S4.includes(y4) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces accounts don't satisfy namespace accounts for ${y4} - Required: ${y4} - Approved: ${S4.toString()}`)); - }), h5.forEach((y4) => { - i2 || (Ie(n3[y4].methods, o2[y4].methods) ? Ie(n3[y4].events, o2[y4].events) || (i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces events don't satisfy namespace events for ${y4}`)) : i2 = we("NON_CONFORMING_NAMESPACES", `${r} namespaces methods don't satisfy namespace methods for ${y4}`)); - }), i2; - } - function ih(e2) { - const t = {}; - return Object.keys(e2).forEach((r) => { - var i2; - r.includes(":") ? t[r] = e2[r] : (i2 = e2[r].chains) == null || i2.forEach((n3) => { - t[n3] = { methods: e2[r].methods, events: e2[r].events }; - }); - }), t; - } - function Eo(e2) { - return [...new Set(e2.map((t) => t.includes(":") ? t.split(":")[0] : t))]; - } - function nh(e2) { - const t = {}; - return Object.keys(e2).forEach((r) => { - if (r.includes(":")) - t[r] = e2[r]; - else { - const i2 = Ze(e2[r].accounts); - i2?.forEach((n3) => { - t[n3] = { accounts: e2[r].accounts.filter((o2) => o2.includes(`${n3}:`)), methods: e2[r].methods, events: e2[r].events }; - }); - } - }), t; - } - function fh(e2, t) { - return Wr(e2, false) && e2 <= t.max && e2 >= t.min; - } - function oh() { - const e2 = Ge(); - return new Promise((t) => { - switch (e2) { - case Kt.browser: - t(So()); - break; - case Kt.reactNative: - t(No()); - break; - case Kt.node: - t(Io()); - break; - default: - t(true); - } - }); - } - function So() { - return vr() && navigator?.onLine; - } - async function No() { - if (rr() && typeof global < "u" && global != null && global.NetInfo) { - const e2 = await (global == null ? void 0 : global.NetInfo.fetch()); - return e2?.isConnected; - } - return true; - } - function Io() { - return true; - } - function sh(e2) { - switch (Ge()) { - case Kt.browser: - _o(e2); - break; - case Kt.reactNative: - Bo(e2); - break; - case Kt.node: - break; - } - } - function _o(e2) { - !rr() && vr() && (window.addEventListener("online", () => e2(true)), window.addEventListener("offline", () => e2(false))); - } - function Bo(e2) { - rr() && typeof global < "u" && global != null && global.NetInfo && global?.NetInfo.addEventListener((t) => e2(t?.isConnected)); - } - var nn = {}; - var ah = class { - static get(t) { - return nn[t]; - } - static set(t, r) { - nn[t] = r; - } - static delete(t) { - delete nn[t]; - } - }; - exports2.BASE10 = Yi, exports2.BASE16 = zt, exports2.BASE64 = Jr, exports2.COLON = jo, exports2.DEFAULT_DEPTH = pi, exports2.EMPTY_SPACE = Rr, exports2.ENV_MAP = Kt, exports2.INTERNAL_ERRORS = po, exports2.MemoryStore = ah, exports2.ONE_THOUSAND = Vo, exports2.REACT_NATIVE_PRODUCT = An, exports2.RELAYER_DEFAULT_PROTOCOL = Zf, exports2.SDK_ERRORS = lo, exports2.SDK_TYPE = yn, exports2.SLASH = bn, exports2.TYPE_0 = Gi, exports2.TYPE_1 = dr, exports2.UTF8 = Yr, exports2.addResourceToRecap = Vf, exports2.appendToQueryString = wn, exports2.assertType = Xo, exports2.assignAbilityToActions = Vi, exports2.base64Decode = zf, exports2.base64Encode = Lf, exports2.buildApprovedNamespaces = qu, exports2.buildAuthObject = iu, exports2.buildNamespacesFromAuth = Ku, exports2.buildRecapStatement = Jf, exports2.calcExpiry = us, exports2.capitalize = is, exports2.capitalizeWord = In, exports2.createDelayedPromise = ns, exports2.createEncodedRecap = su, exports2.createExpiringPromise = fs, exports2.createRecap = jf, exports2.decodeRecap = Ce, exports2.decodeTypeByte = Er, exports2.decrypt = Au, exports2.deriveSymKey = pu, exports2.deserialize = Zi, exports2.encodeRecap = Vr, exports2.encodeTypeByte = Gf, exports2.encrypt = mu, exports2.engineEvent = cs, exports2.enumify = rs, exports2.formatAccountId = cn, exports2.formatAccountWithChain = Do, exports2.formatChainId = hn, exports2.formatExpirerTarget = gi, exports2.formatIdTarget = ss, exports2.formatMessage = kf, exports2.formatMessageContext = Zo, exports2.formatRelayParams = no, exports2.formatRelayRpcUrl = Go, exports2.formatStatementFromRecap = Ji, exports2.formatTopicTarget = os, exports2.formatUA = En, exports2.formatUri = Ru, exports2.generateKeyPair = lu, exports2.generateRandomBytes32 = du, exports2.getAccountsChains = Ze, exports2.getAccountsFromNamespaces = ko, exports2.getAddressFromAccount = ln, exports2.getAddressesFromAccounts = Uo, exports2.getAppMetadata = Jo, exports2.getBrowserOnlineStatus = So, exports2.getBundleId = Qo, exports2.getChainFromAccount = dn, exports2.getChainsFromAccounts = pn, exports2.getChainsFromNamespace = Br, exports2.getChainsFromNamespaces = qo, exports2.getChainsFromRecap = hu, exports2.getChainsFromRequiredNamespaces = Ko, exports2.getCommonValuesInArrays = mi, exports2.getDecodedRecapFromResources = qf, exports2.getDeepLink = ds, exports2.getDidAddress = ji, exports2.getDidAddressSegments = jr, exports2.getDidChainId = zi, exports2.getEnvironment = Ge, exports2.getHttpUrl = Wo, exports2.getInternalError = we, exports2.getJavascriptID = Mn, exports2.getJavascriptOS = xn, exports2.getLastItems = Nn, exports2.getMethodsFromRecap = uu, exports2.getNamespacedDidChainId = eu, exports2.getNamespacesChains = so, exports2.getNamespacesEventsForChainId = uo, exports2.getNamespacesFromAccounts = co, exports2.getNamespacesMethodsForChainId = ao, exports2.getNodeOnlineStatus = Io, exports2.getReCapActions = Hf, exports2.getReactNativeOnlineStatus = No, exports2.getRecapAbilitiesFromResource = ou, exports2.getRecapFromResources = Qr, exports2.getRecapResource = Kf, exports2.getRelayClientMetadata = Yo, exports2.getRelayProtocolApi = xu, exports2.getRelayProtocolName = wu, exports2.getRequiredNamespacesFromNamespaces = ku, exports2.getSdkError = $e, exports2.getUniqueValues = di, exports2.handleDeeplinkRedirect = ls2, exports2.hasOverlap = Ie, exports2.hashKey = vu, exports2.hashMessage = gu, exports2.isBrowser = vr, exports2.isCaipNamespace = $i, exports2.isConformingNamespaces = Mo, exports2.isExpired = hs, exports2.isNode = vi, exports2.isOnline = oh, exports2.isProposalStruct = zu, exports2.isReactNative = rr, exports2.isRecap = Qi, exports2.isSessionCompatible = Hu, exports2.isSessionStruct = ju, exports2.isTypeOneEnvelope = yu, exports2.isUndefined = Oe, exports2.isValidAccountId = vo, exports2.isValidAccounts = Ao, exports2.isValidActions = yo, exports2.isValidArray = Sr, exports2.isValidChainId = Nr, exports2.isValidChains = go, exports2.isValidController = Vu, exports2.isValidEip1271Signature = Tf, exports2.isValidEip191Signature = Pf, exports2.isValidErrorReason = Wu, exports2.isValidEvent = $u, exports2.isValidId = Yu, exports2.isValidNamespaceAccounts = bo, exports2.isValidNamespaceActions = rn, exports2.isValidNamespaceChains = mo, exports2.isValidNamespaceMethodsOrEvents = en, exports2.isValidNamespaces = wo, exports2.isValidNamespacesChainId = th, exports2.isValidNamespacesEvent = rh, exports2.isValidNamespacesRequest = eh, exports2.isValidNumber = Wr, exports2.isValidObject = Gr, exports2.isValidParams = Gu, exports2.isValidRecap = ve, exports2.isValidRelay = xo, exports2.isValidRelays = Ju, exports2.isValidRequest = Xu, exports2.isValidRequestExpiry = fh, exports2.isValidRequiredNamespaces = Qu, exports2.isValidResponse = Zu, exports2.isValidString = Yt, exports2.isValidUrl = Lu, exports2.mapEntries = es, exports2.mapToObj = $o, exports2.mergeArrays = ge, exports2.mergeEncodedRecaps = au, exports2.mergeRecaps = Qf, exports2.normalizeNamespaces = tn, exports2.objToMap = ts, exports2.parseAccountId = li, exports2.parseChainId = un, exports2.parseContextNames = Sn, exports2.parseExpirerTarget = as, exports2.parseNamespaceKey = ho, exports2.parseRelayParams = ro, exports2.parseTopic = io, exports2.parseUri = Bu, exports2.populateAuthPayload = nu, exports2.recapHasResource = fu, exports2.serialize = Wf, exports2.subscribeToBrowserNetworkChange = _o, exports2.subscribeToNetworkChange = sh, exports2.subscribeToReactNativeNetworkChange = Bo, exports2.validateDecoding = bu, exports2.validateEncoding = Xf, exports2.validateSignedCacao = ru, exports2.verifySignature = Of; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js -var PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR, SERVER_ERROR, RESERVED_ERROR_CODES, SERVER_ERROR_CODE_RANGE, STANDARD_ERROR_MAP, DEFAULT_ERROR; -var init_constants2 = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js"() { - init_shim(); - PARSE_ERROR = "PARSE_ERROR"; - INVALID_REQUEST = "INVALID_REQUEST"; - METHOD_NOT_FOUND = "METHOD_NOT_FOUND"; - INVALID_PARAMS = "INVALID_PARAMS"; - INTERNAL_ERROR = "INTERNAL_ERROR"; - SERVER_ERROR = "SERVER_ERROR"; - RESERVED_ERROR_CODES = [-32700, -32600, -32601, -32602, -32603]; - SERVER_ERROR_CODE_RANGE = [-32e3, -32099]; - STANDARD_ERROR_MAP = { - [PARSE_ERROR]: { code: -32700, message: "Parse error" }, - [INVALID_REQUEST]: { code: -32600, message: "Invalid Request" }, - [METHOD_NOT_FOUND]: { code: -32601, message: "Method not found" }, - [INVALID_PARAMS]: { code: -32602, message: "Invalid params" }, - [INTERNAL_ERROR]: { code: -32603, message: "Internal error" }, - [SERVER_ERROR]: { code: -32e3, message: "Server error" } - }; - DEFAULT_ERROR = SERVER_ERROR; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js -function isServerErrorCode(code2) { - return code2 <= SERVER_ERROR_CODE_RANGE[0] && code2 >= SERVER_ERROR_CODE_RANGE[1]; -} -function isReservedErrorCode(code2) { - return RESERVED_ERROR_CODES.includes(code2); -} -function isValidErrorCode(code2) { - return typeof code2 === "number"; -} -function getError(type) { - if (!Object.keys(STANDARD_ERROR_MAP).includes(type)) { - return STANDARD_ERROR_MAP[DEFAULT_ERROR]; - } - return STANDARD_ERROR_MAP[type]; -} -function getErrorByCode(code2) { - const match = Object.values(STANDARD_ERROR_MAP).find((e2) => e2.code === code2); - if (!match) { - return STANDARD_ERROR_MAP[DEFAULT_ERROR]; - } - return match; -} -function validateJsonRpcError(response) { - if (typeof response.error.code === "undefined") { - return { valid: false, error: "Missing code for JSON-RPC error" }; - } - if (typeof response.error.message === "undefined") { - return { valid: false, error: "Missing message for JSON-RPC error" }; - } - if (!isValidErrorCode(response.error.code)) { - return { - valid: false, - error: `Invalid error code type for JSON-RPC: ${response.error.code}` - }; - } - if (isReservedErrorCode(response.error.code)) { - const error = getErrorByCode(response.error.code); - if (error.message !== STANDARD_ERROR_MAP[DEFAULT_ERROR].message && response.error.message === error.message) { - return { - valid: false, - error: `Invalid error code message for JSON-RPC: ${response.error.code}` - }; - } - } - return { valid: true }; -} -function parseConnectionError(e2, url, type) { - return e2.message.includes("getaddrinfo ENOTFOUND") || e2.message.includes("connect ECONNREFUSED") ? new Error(`Unavailable ${type} RPC url at ${url}`) : e2; -} -var init_error = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js"() { - init_shim(); - init_constants2(); - } -}); - -// node_modules/@walletconnect/environment/dist/cjs/crypto.js -var require_crypto2 = __commonJS({ - "node_modules/@walletconnect/environment/dist/cjs/crypto.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isBrowserCryptoAvailable = exports2.getSubtleCrypto = exports2.getBrowerCrypto = void 0; - function getBrowerCrypto() { - return (global === null || global === void 0 ? void 0 : global.crypto) || (global === null || global === void 0 ? void 0 : global.msCrypto) || {}; - } - exports2.getBrowerCrypto = getBrowerCrypto; - function getSubtleCrypto() { - const browserCrypto = getBrowerCrypto(); - return browserCrypto.subtle || browserCrypto.webkitSubtle; - } - exports2.getSubtleCrypto = getSubtleCrypto; - function isBrowserCryptoAvailable() { - return !!getBrowerCrypto() && !!getSubtleCrypto(); - } - exports2.isBrowserCryptoAvailable = isBrowserCryptoAvailable; - } -}); - -// node_modules/@walletconnect/environment/dist/cjs/env.js -var require_env = __commonJS({ - "node_modules/@walletconnect/environment/dist/cjs/env.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.isBrowser = exports2.isNode = exports2.isReactNative = void 0; - function isReactNative() { - return typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative"; - } - exports2.isReactNative = isReactNative; - function isNode2() { - return typeof import_process.default !== "undefined" && typeof import_process.default.versions !== "undefined" && typeof import_process.default.versions.node !== "undefined"; - } - exports2.isNode = isNode2; - function isBrowser() { - return !isReactNative() && !isNode2(); - } - exports2.isBrowser = isBrowser; - } -}); - -// node_modules/@walletconnect/environment/dist/cjs/index.js -var require_cjs5 = __commonJS({ - "node_modules/@walletconnect/environment/dist/cjs/index.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - tslib_1.__exportStar(require_crypto2(), exports2); - tslib_1.__exportStar(require_env(), exports2); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js -var env_exports = {}; -__export(env_exports, { - isNodeJs: () => isNodeJs -}); -var import_environment, isNodeJs; -var init_env = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js"() { - init_shim(); - import_environment = __toESM(require_cjs5()); - __reExport(env_exports, __toESM(require_cjs5())); - isNodeJs = import_environment.isNode; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js -function payloadId(entropy = 3) { - const date = Date.now() * Math.pow(10, entropy); - const extra = Math.floor(Math.random() * Math.pow(10, entropy)); - return date + extra; -} -function getBigIntRpcId(entropy = 6) { - return BigInt(payloadId(entropy)); -} -function formatJsonRpcRequest(method, params, id) { - return { - id: id || payloadId(), - jsonrpc: "2.0", - method, - params - }; -} -function formatJsonRpcResult(id, result) { - return { - id, - jsonrpc: "2.0", - result - }; -} -function formatJsonRpcError(id, error, data) { - return { - id, - jsonrpc: "2.0", - error: formatErrorMessage(error, data) - }; -} -function formatErrorMessage(error, data) { - if (typeof error === "undefined") { - return getError(INTERNAL_ERROR); - } - if (typeof error === "string") { - error = Object.assign(Object.assign({}, getError(SERVER_ERROR)), { message: error }); - } - if (typeof data !== "undefined") { - error.data = data; - } - if (isReservedErrorCode(error.code)) { - error = getErrorByCode(error.code); - } - return error; -} -var init_format = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js"() { - init_shim(); - init_error(); - init_constants2(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js -function isValidRoute(route) { - if (route.includes("*")) { - return isValidWildcardRoute(route); - } - if (/\W/g.test(route)) { - return false; - } - return true; -} -function isValidDefaultRoute(route) { - return route === "*"; -} -function isValidWildcardRoute(route) { - if (isValidDefaultRoute(route)) { - return true; - } - if (!route.includes("*")) { - return false; - } - if (route.split("*").length !== 2) { - return false; - } - if (route.split("*").filter((x3) => x3.trim() === "").length !== 1) { - return false; - } - return true; -} -function isValidLeadingWildcardRoute(route) { - return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[0].trim(); -} -function isValidTrailingWildcardRoute(route) { - return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[1].trim(); -} -var init_routing = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js -var init_jsonrpc = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/jsonrpc.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js -var IEvents2; -var init_misc = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/misc.js"() { - init_shim(); - IEvents2 = class { - }; - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js -var IJsonRpcConnection, IBaseJsonRpcProvider, IJsonRpcProvider; -var init_provider = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/provider.js"() { - init_shim(); - init_misc(); - IJsonRpcConnection = class extends IEvents2 { - constructor(opts) { - super(); - } - }; - IBaseJsonRpcProvider = class extends IEvents2 { - constructor() { - super(); - } - }; - IJsonRpcProvider = class extends IBaseJsonRpcProvider { - constructor(connection) { - super(); - } - }; - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js -var init_validator = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/validator.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js -var init_esm4 = __esm({ - "node_modules/@walletconnect/jsonrpc-types/dist/esm/index.js"() { - init_shim(); - init_jsonrpc(); - init_misc(); - init_provider(); - init_validator(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js -var init_types2 = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/types.js"() { - init_shim(); - init_esm4(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js -function getUrlProtocol(url) { - const matches = url.match(new RegExp(/^\w+:/, "gi")); - if (!matches || !matches.length) - return; - return matches[0]; -} -function matchRegexProtocol(url, regex) { - const protocol = getUrlProtocol(url); - if (typeof protocol === "undefined") - return false; - return new RegExp(regex).test(protocol); -} -function isHttpUrl(url) { - return matchRegexProtocol(url, HTTP_REGEX); -} -function isWsUrl(url) { - return matchRegexProtocol(url, WS_REGEX); -} -function isLocalhostUrl(url) { - return new RegExp("wss?://localhost(:d{2,5})?").test(url); -} -var HTTP_REGEX, WS_REGEX; -var init_url = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js"() { - init_shim(); - HTTP_REGEX = "^https?:"; - WS_REGEX = "^wss?:"; - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js -function isJsonRpcPayload(payload) { - return typeof payload === "object" && "id" in payload && "jsonrpc" in payload && payload.jsonrpc === "2.0"; -} -function isJsonRpcRequest(payload) { - return isJsonRpcPayload(payload) && "method" in payload; -} -function isJsonRpcResponse(payload) { - return isJsonRpcPayload(payload) && (isJsonRpcResult(payload) || isJsonRpcError(payload)); -} -function isJsonRpcResult(payload) { - return "result" in payload; -} -function isJsonRpcError(payload) { - return "error" in payload; -} -function isJsonRpcValidationInvalid(validation) { - return "error" in validation && validation.valid === false; -} -var init_validators = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js"() { - init_shim(); - } -}); - -// node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js -var esm_exports4 = {}; -__export(esm_exports4, { - DEFAULT_ERROR: () => DEFAULT_ERROR, - IBaseJsonRpcProvider: () => IBaseJsonRpcProvider, - IEvents: () => IEvents2, - IJsonRpcConnection: () => IJsonRpcConnection, - IJsonRpcProvider: () => IJsonRpcProvider, - INTERNAL_ERROR: () => INTERNAL_ERROR, - INVALID_PARAMS: () => INVALID_PARAMS, - INVALID_REQUEST: () => INVALID_REQUEST, - METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, - PARSE_ERROR: () => PARSE_ERROR, - RESERVED_ERROR_CODES: () => RESERVED_ERROR_CODES, - SERVER_ERROR: () => SERVER_ERROR, - SERVER_ERROR_CODE_RANGE: () => SERVER_ERROR_CODE_RANGE, - STANDARD_ERROR_MAP: () => STANDARD_ERROR_MAP, - formatErrorMessage: () => formatErrorMessage, - formatJsonRpcError: () => formatJsonRpcError, - formatJsonRpcRequest: () => formatJsonRpcRequest, - formatJsonRpcResult: () => formatJsonRpcResult, - getBigIntRpcId: () => getBigIntRpcId, - getError: () => getError, - getErrorByCode: () => getErrorByCode, - isHttpUrl: () => isHttpUrl, - isJsonRpcError: () => isJsonRpcError, - isJsonRpcPayload: () => isJsonRpcPayload, - isJsonRpcRequest: () => isJsonRpcRequest, - isJsonRpcResponse: () => isJsonRpcResponse, - isJsonRpcResult: () => isJsonRpcResult, - isJsonRpcValidationInvalid: () => isJsonRpcValidationInvalid, - isLocalhostUrl: () => isLocalhostUrl, - isNodeJs: () => isNodeJs, - isReservedErrorCode: () => isReservedErrorCode, - isServerErrorCode: () => isServerErrorCode, - isValidDefaultRoute: () => isValidDefaultRoute, - isValidErrorCode: () => isValidErrorCode, - isValidLeadingWildcardRoute: () => isValidLeadingWildcardRoute, - isValidRoute: () => isValidRoute, - isValidTrailingWildcardRoute: () => isValidTrailingWildcardRoute, - isValidWildcardRoute: () => isValidWildcardRoute, - isWsUrl: () => isWsUrl, - parseConnectionError: () => parseConnectionError, - payloadId: () => payloadId, - validateJsonRpcError: () => validateJsonRpcError -}); -var init_esm5 = __esm({ - "node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js"() { - init_shim(); - init_constants2(); - init_error(); - init_env(); - __reExport(esm_exports4, env_exports); - init_format(); - init_routing(); - init_types2(); - init_url(); - init_validators(); - } -}); - -// node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js -var import_events, JsonRpcProvider, provider_default; -var init_provider2 = __esm({ - "node_modules/@walletconnect/jsonrpc-provider/dist/esm/provider.js"() { - init_shim(); - import_events = __toESM(require_events()); - init_esm5(); - JsonRpcProvider = class extends IJsonRpcProvider { - constructor(connection) { - super(connection); - this.events = new import_events.EventEmitter(); - this.hasRegisteredEventListeners = false; - this.connection = this.setConnection(connection); - if (this.connection.connected) { - this.registerEventListeners(); - } - } - async connect(connection = this.connection) { - await this.open(connection); - } - async disconnect() { - await this.close(); - } - on(event, listener) { - this.events.on(event, listener); - } - once(event, listener) { - this.events.once(event, listener); - } - off(event, listener) { - this.events.off(event, listener); - } - removeListener(event, listener) { - this.events.removeListener(event, listener); - } - async request(request, context) { - return this.requestStrict(formatJsonRpcRequest(request.method, request.params || [], request.id || getBigIntRpcId().toString()), context); - } - async requestStrict(request, context) { - return new Promise(async (resolve, reject) => { - if (!this.connection.connected) { - try { - await this.open(); - } catch (e2) { - reject(e2); - } - } - this.events.on(`${request.id}`, (response) => { - if (isJsonRpcError(response)) { - reject(response.error); - } else { - resolve(response.result); - } - }); - try { - await this.connection.send(request, context); - } catch (e2) { - reject(e2); - } - }); - } - setConnection(connection = this.connection) { - return connection; - } - onPayload(payload) { - this.events.emit("payload", payload); - if (isJsonRpcResponse(payload)) { - this.events.emit(`${payload.id}`, payload); - } else { - this.events.emit("message", { - type: payload.method, - data: payload.params - }); - } - } - onClose(event) { - if (event && event.code === 3e3) { - this.events.emit("error", new Error(`WebSocket connection closed abnormally with code: ${event.code} ${event.reason ? `(${event.reason})` : ""}`)); - } - this.events.emit("disconnect"); - } - async open(connection = this.connection) { - if (this.connection === connection && this.connection.connected) - return; - if (this.connection.connected) - this.close(); - if (typeof connection === "string") { - await this.connection.open(connection); - connection = this.connection; - } - this.connection = this.setConnection(connection); - await this.connection.open(); - this.registerEventListeners(); - this.events.emit("connect"); - } - async close() { - await this.connection.close(); - } - registerEventListeners() { - if (this.hasRegisteredEventListeners) - return; - this.connection.on("payload", (payload) => this.onPayload(payload)); - this.connection.on("close", (event) => this.onClose(event)); - this.connection.on("error", (error) => this.events.emit("error", error)); - this.connection.on("register_error", (error) => this.onClose()); - this.hasRegisteredEventListeners = true; - } - }; - provider_default = JsonRpcProvider; - } -}); - -// node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js -var esm_exports5 = {}; -__export(esm_exports5, { - JsonRpcProvider: () => JsonRpcProvider, - default: () => esm_default -}); -var esm_default; -var init_esm6 = __esm({ - "node_modules/@walletconnect/jsonrpc-provider/dist/esm/index.js"() { - init_shim(); - init_provider2(); - init_provider2(); - esm_default = provider_default; - } -}); - -// node_modules/ws/browser.js -var require_browser5 = __commonJS({ - "node_modules/ws/browser.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function() { - throw new Error( - "ws does not work in the browser. Browser clients must use the native WebSocket object" - ); - }; - } -}); - -// node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js -var index_es_exports4 = {}; -__export(index_es_exports4, { - WsConnection: () => f3, - default: () => f3 -}); -var import_events2, w3, b3, a2, h4, S3, f3; -var init_index_es4 = __esm({ - "node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js"() { - init_shim(); - import_events2 = __toESM(require_events()); - init_esm(); - init_esm5(); - w3 = () => typeof WebSocket < "u" ? WebSocket : typeof global < "u" && typeof global.WebSocket < "u" ? global.WebSocket : typeof window < "u" && typeof window.WebSocket < "u" ? window.WebSocket : typeof self < "u" && typeof self.WebSocket < "u" ? self.WebSocket : require_browser5(); - b3 = () => typeof WebSocket < "u" || typeof global < "u" && typeof global.WebSocket < "u" || typeof window < "u" && typeof window.WebSocket < "u" || typeof self < "u" && typeof self.WebSocket < "u"; - a2 = (c4) => c4.split("?")[0]; - h4 = 10; - S3 = w3(); - f3 = class { - constructor(e2) { - if (this.url = e2, this.events = new import_events2.EventEmitter(), this.registering = false, !isWsUrl(e2)) - throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); - this.url = e2; - } - get connected() { - return typeof this.socket < "u"; - } - get connecting() { - return this.registering; - } - on(e2, t) { - this.events.on(e2, t); - } - once(e2, t) { - this.events.once(e2, t); - } - off(e2, t) { - this.events.off(e2, t); - } - removeListener(e2, t) { - this.events.removeListener(e2, t); - } - async open(e2 = this.url) { - await this.register(e2); - } - async close() { - return new Promise((e2, t) => { - if (typeof this.socket > "u") { - t(new Error("Connection already closed")); - return; - } - this.socket.onclose = (n3) => { - this.onClose(n3), e2(); - }, this.socket.close(); - }); - } - async send(e2) { - typeof this.socket > "u" && (this.socket = await this.register()); - try { - this.socket.send(safeJsonStringify(e2)); - } catch (t) { - this.onError(e2.id, t); - } - } - register(e2 = this.url) { - if (!isWsUrl(e2)) - throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); - if (this.registering) { - const t = this.events.getMaxListeners(); - return (this.events.listenerCount("register_error") >= t || this.events.listenerCount("open") >= t) && this.events.setMaxListeners(t + 1), new Promise((n3, o2) => { - this.events.once("register_error", (s2) => { - this.resetMaxListeners(), o2(s2); - }), this.events.once("open", () => { - if (this.resetMaxListeners(), typeof this.socket > "u") - return o2(new Error("WebSocket connection is missing or invalid")); - n3(this.socket); - }); - }); - } - return this.url = e2, this.registering = true, new Promise((t, n3) => { - const o2 = new URLSearchParams(e2).get("origin"), s2 = (0, esm_exports4.isReactNative)() ? { headers: { origin: o2 } } : { rejectUnauthorized: !isLocalhostUrl(e2) }, i2 = new S3(e2, [], s2); - b3() ? i2.onerror = (r) => { - const l4 = r; - n3(this.emitError(l4.error)); - } : i2.on("error", (r) => { - n3(this.emitError(r)); - }), i2.onopen = () => { - this.onOpen(i2), t(i2); - }; - }); - } - onOpen(e2) { - e2.onmessage = (t) => this.onPayload(t), e2.onclose = (t) => this.onClose(t), this.socket = e2, this.registering = false, this.events.emit("open"); - } - onClose(e2) { - this.socket = void 0, this.registering = false, this.events.emit("close", e2); - } - onPayload(e2) { - if (typeof e2.data > "u") - return; - const t = typeof e2.data == "string" ? safeJsonParse(e2.data) : e2.data; - this.events.emit("payload", t); - } - onError(e2, t) { - const n3 = this.parseError(t), o2 = n3.message || n3.toString(), s2 = formatJsonRpcError(e2, o2); - this.events.emit("payload", s2); - } - parseError(e2, t = this.url) { - return parseConnectionError(e2, a2(t), "WS"); - } - resetMaxListeners() { - this.events.getMaxListeners() > h4 && this.events.setMaxListeners(h4); - } - emitError(e2) { - const t = this.parseError(new Error(e2?.message || `WebSocket connection failed for host: ${a2(this.url)}`)); - return this.events.emit("register_error", t), t; - } - }; - } -}); - -// node_modules/lodash.isequal/index.js -var require_lodash = __commonJS({ - "node_modules/lodash.isequal/index.js"(exports2, module2) { - init_shim(); - var LARGE_ARRAY_SIZE = 200; - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - var COMPARE_PARTIAL_FLAG = 1; - var COMPARE_UNORDERED_FLAG = 2; - var MAX_SAFE_INTEGER2 = 9007199254740991; - var argsTag = "[object Arguments]"; - var arrayTag = "[object Array]"; - var asyncTag = "[object AsyncFunction]"; - var boolTag = "[object Boolean]"; - var dateTag = "[object Date]"; - var errorTag = "[object Error]"; - var funcTag = "[object Function]"; - var genTag = "[object GeneratorFunction]"; - var mapTag = "[object Map]"; - var numberTag = "[object Number]"; - var nullTag = "[object Null]"; - var objectTag = "[object Object]"; - var promiseTag = "[object Promise]"; - var proxyTag = "[object Proxy]"; - var regexpTag = "[object RegExp]"; - var setTag = "[object Set]"; - var stringTag = "[object String]"; - var symbolTag = "[object Symbol]"; - var undefinedTag = "[object Undefined]"; - var weakMapTag = "[object WeakMap]"; - var arrayBufferTag = "[object ArrayBuffer]"; - var dataViewTag = "[object DataView]"; - var float32Tag = "[object Float32Array]"; - var float64Tag = "[object Float64Array]"; - var int8Tag = "[object Int8Array]"; - var int16Tag = "[object Int16Array]"; - var int32Tag = "[object Int32Array]"; - var uint8Tag = "[object Uint8Array]"; - var uint8ClampedTag = "[object Uint8ClampedArray]"; - var uint16Tag = "[object Uint16Array]"; - var uint32Tag = "[object Uint32Array]"; - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - var reIsHostCtor = /^\[object .+?Constructor\]$/; - var reIsUint = /^(?:0|[1-9]\d*)$/; - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2; - var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = function() { - try { - return freeProcess && freeProcess.binding && freeProcess.binding("util"); - } catch (e2) { - } - }(); - var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - function arrayFilter(array, predicate) { - var index = -1, length2 = array == null ? 0 : array.length, resIndex = 0, result = []; - while (++index < length2) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - function arrayPush(array, values) { - var index = -1, length2 = values.length, offset = array.length; - while (++index < length2) { - array[offset + index] = values[index]; - } - return array; - } - function arraySome(array, predicate) { - var index = -1, length2 = array == null ? 0 : array.length; - while (++index < length2) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - function baseTimes(n3, iteratee) { - var index = -1, result = Array(n3); - while (++index < n3) { - result[index] = iteratee(index); - } - return result; - } - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - function cacheHas(cache, key) { - return cache.has(key); - } - function getValue(object, key) { - return object == null ? void 0 : object[key]; - } - function mapToArray(map) { - var index = -1, result = Array(map.size); - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - function setToArray(set2) { - var index = -1, result = Array(set2.size); - set2.forEach(function(value) { - result[++index] = value; - }); - return result; - } - var arrayProto = Array.prototype; - var funcProto = Function.prototype; - var objectProto = Object.prototype; - var coreJsData = root["__core-js_shared__"]; - var funcToString = funcProto.toString; - var hasOwnProperty = objectProto.hasOwnProperty; - var maskSrcKey = function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); - return uid ? "Symbol(src)_1." + uid : ""; - }(); - var nativeObjectToString = objectProto.toString; - var reIsNative = RegExp( - "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" - ); - var Buffer2 = moduleExports ? root.Buffer : void 0; - var Symbol2 = root.Symbol; - var Uint8Array2 = root.Uint8Array; - var propertyIsEnumerable = objectProto.propertyIsEnumerable; - var splice = arrayProto.splice; - var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; - var nativeGetSymbols = Object.getOwnPropertySymbols; - var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; - var nativeKeys = overArg(Object.keys, Object); - var DataView2 = getNative(root, "DataView"); - var Map2 = getNative(root, "Map"); - var Promise2 = getNative(root, "Promise"); - var Set2 = getNative(root, "Set"); - var WeakMap2 = getNative(root, "WeakMap"); - var nativeCreate = getNative(Object, "create"); - var dataViewCtorString = toSource(DataView2); - var mapCtorString = toSource(Map2); - var promiseCtorString = toSource(Promise2); - var setCtorString = toSource(Set2); - var weakMapCtorString = toSource(WeakMap2); - var symbolProto = Symbol2 ? Symbol2.prototype : void 0; - var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; - function Hash(entries) { - var index = -1, length2 = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length2) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? void 0 : result; - } - return hasOwnProperty.call(data, key) ? data[key] : void 0; - } - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); - } - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; - return this; - } - Hash.prototype.clear = hashClear; - Hash.prototype["delete"] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - function ListCache(entries) { - var index = -1, length2 = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length2) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - function listCacheDelete(key) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - function listCacheGet(key) { - var data = this.__data__, index = assocIndexOf(data, key); - return index < 0 ? void 0 : data[index][1]; - } - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - function listCacheSet(key, value) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - ListCache.prototype.clear = listCacheClear; - ListCache.prototype["delete"] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - function MapCache(entries) { - var index = -1, length2 = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length2) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function mapCacheClear() { - this.size = 0; - this.__data__ = { - "hash": new Hash(), - "map": new (Map2 || ListCache)(), - "string": new Hash() - }; - } - function mapCacheDelete(key) { - var result = getMapData(this, key)["delete"](key); - this.size -= result ? 1 : 0; - return result; - } - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - function mapCacheSet(key, value) { - var data = getMapData(this, key), size = data.size; - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype["delete"] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - function SetCache(values) { - var index = -1, length2 = values == null ? 0 : values.length; - this.__data__ = new MapCache(); - while (++index < length2) { - this.add(values[index]); - } - } - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - function setCacheHas(value) { - return this.__data__.has(value); - } - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - function stackClear() { - this.__data__ = new ListCache(); - this.size = 0; - } - function stackDelete(key) { - var data = this.__data__, result = data["delete"](key); - this.size = data.size; - return result; - } - function stackGet(key) { - return this.__data__.get(key); - } - function stackHas(key) { - return this.__data__.has(key); - } - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - Stack.prototype.clear = stackClear; - Stack.prototype["delete"] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length2 = result.length; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. - (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. - isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. - isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. - isIndex(key, length2)))) { - result.push(key); - } - } - return result; - } - function assocIndexOf(array, key) { - var length2 = array.length; - while (length2--) { - if (eq(array[length2][0], key)) { - return length2; - } - } - return -1; - } - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - function baseGetTag(value) { - if (value == null) { - return value === void 0 ? undefinedTag : nullTag; - } - return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); - } - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack()); - return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack()); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack()); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - function baseIsTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != "constructor") { - result.push(key); - } - } - return result; - } - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; - } - var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0; - stack.set(array, other); - stack.set(other, array); - while (++index < arrLength) { - var arrValue = array[index], othValue = other[index]; - if (customizer) { - var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== void 0) { - if (compared) { - continue; - } - result = false; - break; - } - if (seen) { - if (!arraySome(other, function(othValue2, othIndex) { - if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - result = false; - break; - } - } - stack["delete"](array); - stack["delete"](other); - return result; - } - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { - return false; - } - object = object.buffer; - other = other.buffer; - case arrayBufferTag: - if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { - return false; - } - return true; - case boolTag: - case dateTag: - case numberTag: - return eq(+object, +other); - case errorTag: - return object.name == other.name && object.message == other.message; - case regexpTag: - case stringTag: - return object == other + ""; - case mapTag: - var convert = mapToArray; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - if (object.size != other.size && !isPartial) { - return false; - } - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack["delete"](object); - return result; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], othValue = other[key]; - if (customizer) { - var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); - } - if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { - result = false; - break; - } - skipCtor || (skipCtor = key == "constructor"); - } - if (result && !skipCtor) { - var objCtor = object.constructor, othCtor = other.constructor; - if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { - result = false; - } - } - stack["delete"](object); - stack["delete"](other); - return result; - } - function getAllKeys(object) { - return baseGetAllKeys(object, keys2, getSymbols); - } - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; - } - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : void 0; - } - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; - try { - value[symToStringTag] = void 0; - var unmasked = true; - } catch (e2) { - } - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - var getTag = baseGetTag; - if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) { - getTag = function(value) { - var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: - return dataViewTag; - case mapCtorString: - return mapTag; - case promiseCtorString: - return promiseTag; - case setCtorString: - return setTag; - case weakMapCtorString: - return weakMapTag; - } - } - return result; - }; - } - function isIndex(value, length2) { - length2 = length2 == null ? MAX_SAFE_INTEGER2 : length2; - return !!length2 && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length2); - } - function isKeyable(value) { - var type = typeof value; - return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; - } - function isMasked(func) { - return !!maskSrcKey && maskSrcKey in func; - } - function isPrototype(value) { - var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; - return value === proto; - } - function objectToString(value) { - return nativeObjectToString.call(value); - } - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e2) { - } - try { - return func + ""; - } catch (e2) { - } - } - return ""; - } - function eq(value, other) { - return value === other || value !== value && other !== other; - } - var isArguments = baseIsArguments(/* @__PURE__ */ function() { - return arguments; - }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); - }; - var isArray = Array.isArray; - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - var isBuffer = nativeIsBuffer || stubFalse; - function isEqual(value, other) { - return baseIsEqual(value, other); - } - function isFunction(value) { - if (!isObject(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - function isLength(value) { - return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; - } - function isObject(value) { - var type = typeof value; - return value != null && (type == "object" || type == "function"); - } - function isObjectLike(value) { - return value != null && typeof value == "object"; - } - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - function keys2(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - function stubArray() { - return []; - } - function stubFalse() { - return false; - } - module2.exports = isEqual; - } -}); - -// node_modules/unfetch/dist/unfetch.js -var require_unfetch = __commonJS({ - "node_modules/unfetch/dist/unfetch.js"(exports2, module2) { - init_shim(); - module2.exports = function(e2, n3) { - return n3 = n3 || {}, new Promise(function(t, r) { - var s2 = new XMLHttpRequest(), o2 = [], u3 = [], i2 = {}, a3 = function() { - return { ok: 2 == (s2.status / 100 | 0), statusText: s2.statusText, status: s2.status, url: s2.responseURL, text: function() { - return Promise.resolve(s2.responseText); - }, json: function() { - return Promise.resolve(s2.responseText).then(JSON.parse); - }, blob: function() { - return Promise.resolve(new Blob([s2.response])); - }, clone: a3, headers: { keys: function() { - return o2; - }, entries: function() { - return u3; - }, get: function(e3) { - return i2[e3.toLowerCase()]; - }, has: function(e3) { - return e3.toLowerCase() in i2; - } } }; - }; - for (var l4 in s2.open(n3.method || "get", e2, true), s2.onload = function() { - s2.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function(e3, n4, t2) { - o2.push(n4 = n4.toLowerCase()), u3.push([n4, t2]), i2[n4] = i2[n4] ? i2[n4] + "," + t2 : t2; - }), t(a3()); - }, s2.onerror = r, s2.withCredentials = "include" == n3.credentials, n3.headers) - s2.setRequestHeader(l4, n3.headers[l4]); - s2.send(n3.body || null); - }); - }; - } -}); - -// node_modules/isomorphic-unfetch/browser.js -var require_browser6 = __commonJS({ - "node_modules/isomorphic-unfetch/browser.js"(exports2, module2) { - init_shim(); - module2.exports = self.fetch || (self.fetch = require_unfetch().default || require_unfetch()); - } -}); - -// node_modules/@walletconnect/core/dist/index.cjs.js -var require_index_cjs3 = __commonJS({ - "node_modules/@walletconnect/core/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var z3 = require_events(); - var It = (init_index_es(), __toCommonJS(index_es_exports)); - var $ = require_cjs2(); - var g3 = (init_index_es2(), __toCommonJS(index_es_exports2)); - var x3 = require_index_cjs(); - var oe = (init_esm(), __toCommonJS(esm_exports)); - var Rt = (init_esm3(), __toCommonJS(esm_exports3)); - var a3 = require_index_cjs2(); - var _t = (init_src2(), __toCommonJS(src_exports)); - var l4 = require_cjs(); - var Ct = (init_esm6(), __toCommonJS(esm_exports5)); - var f4 = (init_esm5(), __toCommonJS(esm_exports4)); - var Tt = (init_index_es4(), __toCommonJS(index_es_exports4)); - var St = require_lodash(); - var Ot = require_browser6(); - function k4(n3) { - return n3 && typeof n3 == "object" && "default" in n3 ? n3 : { default: n3 }; - } - function Pt(n3) { - if (n3 && n3.__esModule) - return n3; - var e2 = /* @__PURE__ */ Object.create(null); - return n3 && Object.keys(n3).forEach(function(t) { - if (t !== "default") { - var i2 = Object.getOwnPropertyDescriptor(n3, t); - Object.defineProperty(e2, t, i2.get ? i2 : { enumerable: true, get: function() { - return n3[t]; - } }); - } - }), e2.default = n3, Object.freeze(e2); - } - var At = k4(z3); - var xt = k4(It); - var j2 = Pt(Rt); - var Nt = k4(Tt); - var Lt = k4(St); - var Ut = k4(Ot); - function zt(n3, e2) { - if (n3.length >= 255) - throw new TypeError("Alphabet too long"); - for (var t = new Uint8Array(256), i2 = 0; i2 < t.length; i2++) - t[i2] = 255; - for (var s2 = 0; s2 < n3.length; s2++) { - var r = n3.charAt(s2), o2 = r.charCodeAt(0); - if (t[o2] !== 255) - throw new TypeError(r + " is ambiguous"); - t[o2] = s2; - } - var h5 = n3.length, c4 = n3.charAt(0), u3 = Math.log(h5) / Math.log(256), p3 = Math.log(256) / Math.log(h5); - function D2(d3) { - if (d3 instanceof Uint8Array || (ArrayBuffer.isView(d3) ? d3 = new Uint8Array(d3.buffer, d3.byteOffset, d3.byteLength) : Array.isArray(d3) && (d3 = Uint8Array.from(d3))), !(d3 instanceof Uint8Array)) - throw new TypeError("Expected Uint8Array"); - if (d3.length === 0) - return ""; - for (var y4 = 0, C3 = 0, E4 = 0, O3 = d3.length; E4 !== O3 && d3[E4] === 0; ) - E4++, y4++; - for (var P2 = (O3 - E4) * p3 + 1 >>> 0, v2 = new Uint8Array(P2); E4 !== O3; ) { - for (var A2 = d3[E4], U2 = 0, T2 = P2 - 1; (A2 !== 0 || U2 < C3) && T2 !== -1; T2--, U2++) - A2 += 256 * v2[T2] >>> 0, v2[T2] = A2 % h5 >>> 0, A2 = A2 / h5 >>> 0; - if (A2 !== 0) - throw new Error("Non-zero carry"); - C3 = U2, E4++; - } - for (var N10 = P2 - C3; N10 !== P2 && v2[N10] === 0; ) - N10++; - for (var Y = c4.repeat(y4); N10 < P2; ++N10) - Y += n3.charAt(v2[N10]); - return Y; - } - function b4(d3) { - if (typeof d3 != "string") - throw new TypeError("Expected String"); - if (d3.length === 0) - return new Uint8Array(); - var y4 = 0; - if (d3[y4] !== " ") { - for (var C3 = 0, E4 = 0; d3[y4] === c4; ) - C3++, y4++; - for (var O3 = (d3.length - y4) * u3 + 1 >>> 0, P2 = new Uint8Array(O3); d3[y4]; ) { - var v2 = t[d3.charCodeAt(y4)]; - if (v2 === 255) - return; - for (var A2 = 0, U2 = O3 - 1; (v2 !== 0 || A2 < E4) && U2 !== -1; U2--, A2++) - v2 += h5 * P2[U2] >>> 0, P2[U2] = v2 % 256 >>> 0, v2 = v2 / 256 >>> 0; - if (v2 !== 0) - throw new Error("Non-zero carry"); - E4 = A2, y4++; - } - if (d3[y4] !== " ") { - for (var T2 = O3 - E4; T2 !== O3 && P2[T2] === 0; ) - T2++; - for (var N10 = new Uint8Array(C3 + (O3 - T2)), Y = C3; T2 !== O3; ) - N10[Y++] = P2[T2++]; - return N10; - } - } - } - function F(d3) { - var y4 = b4(d3); - if (y4) - return y4; - throw new Error(`Non-${e2} character`); - } - return { encode: D2, decodeUnsafe: b4, decode: F }; - } - var Ft = zt; - var Mt = Ft; - var ae = (n3) => { - if (n3 instanceof Uint8Array && n3.constructor.name === "Uint8Array") - return n3; - if (n3 instanceof ArrayBuffer) - return new Uint8Array(n3); - if (ArrayBuffer.isView(n3)) - return new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength); - throw new Error("Unknown type, must be binary type"); - }; - var Bt = (n3) => new TextEncoder().encode(n3); - var $t = (n3) => new TextDecoder().decode(n3); - var kt = class { - constructor(e2, t, i2) { - this.name = e2, this.prefix = t, this.baseEncode = i2; - } - encode(e2) { - if (e2 instanceof Uint8Array) - return `${this.prefix}${this.baseEncode(e2)}`; - throw Error("Unknown type, must be binary type"); - } - }; - var Vt = class { - constructor(e2, t, i2) { - if (this.name = e2, this.prefix = t, t.codePointAt(0) === void 0) - throw new Error("Invalid prefix character"); - this.prefixCodePoint = t.codePointAt(0), this.baseDecode = i2; - } - decode(e2) { - if (typeof e2 == "string") { - if (e2.codePointAt(0) !== this.prefixCodePoint) - throw Error(`Unable to decode multibase string ${JSON.stringify(e2)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); - return this.baseDecode(e2.slice(this.prefix.length)); - } else - throw Error("Can only multibase decode strings"); - } - or(e2) { - return he(this, e2); - } - }; - var Kt = class { - constructor(e2) { - this.decoders = e2; - } - or(e2) { - return he(this, e2); - } - decode(e2) { - const t = e2[0], i2 = this.decoders[t]; - if (i2) - return i2.decode(e2); - throw RangeError(`Unable to decode multibase string ${JSON.stringify(e2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); - } - }; - var he = (n3, e2) => new Kt({ ...n3.decoders || { [n3.prefix]: n3 }, ...e2.decoders || { [e2.prefix]: e2 } }); - var qt = class { - constructor(e2, t, i2, s2) { - this.name = e2, this.prefix = t, this.baseEncode = i2, this.baseDecode = s2, this.encoder = new kt(e2, t, i2), this.decoder = new Vt(e2, t, s2); - } - encode(e2) { - return this.encoder.encode(e2); - } - decode(e2) { - return this.decoder.decode(e2); - } - }; - var G = ({ name: n3, prefix: e2, encode: t, decode: i2 }) => new qt(n3, e2, t, i2); - var V = ({ prefix: n3, name: e2, alphabet: t }) => { - const { encode: i2, decode: s2 } = Mt(t, e2); - return G({ prefix: n3, name: e2, encode: i2, decode: (r) => ae(s2(r)) }); - }; - var Yt = (n3, e2, t, i2) => { - const s2 = {}; - for (let p3 = 0; p3 < e2.length; ++p3) - s2[e2[p3]] = p3; - let r = n3.length; - for (; n3[r - 1] === "="; ) - --r; - const o2 = new Uint8Array(r * t / 8 | 0); - let h5 = 0, c4 = 0, u3 = 0; - for (let p3 = 0; p3 < r; ++p3) { - const D2 = s2[n3[p3]]; - if (D2 === void 0) - throw new SyntaxError(`Non-${i2} character`); - c4 = c4 << t | D2, h5 += t, h5 >= 8 && (h5 -= 8, o2[u3++] = 255 & c4 >> h5); - } - if (h5 >= t || 255 & c4 << 8 - h5) - throw new SyntaxError("Unexpected end of data"); - return o2; - }; - var jt = (n3, e2, t) => { - const i2 = e2[e2.length - 1] === "=", s2 = (1 << t) - 1; - let r = "", o2 = 0, h5 = 0; - for (let c4 = 0; c4 < n3.length; ++c4) - for (h5 = h5 << 8 | n3[c4], o2 += 8; o2 > t; ) - o2 -= t, r += e2[s2 & h5 >> o2]; - if (o2 && (r += e2[s2 & h5 << t - o2]), i2) - for (; r.length * t & 7; ) - r += "="; - return r; - }; - var m3 = ({ name: n3, prefix: e2, bitsPerChar: t, alphabet: i2 }) => G({ prefix: e2, name: n3, encode(s2) { - return jt(s2, i2, t); - }, decode(s2) { - return Yt(s2, i2, t, n3); - } }); - var Gt = G({ prefix: "\0", name: "identity", encode: (n3) => $t(n3), decode: (n3) => Bt(n3) }); - var Ht = Object.freeze({ __proto__: null, identity: Gt }); - var Xt = m3({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); - var Jt = Object.freeze({ __proto__: null, base2: Xt }); - var Wt = m3({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); - var Qt = Object.freeze({ __proto__: null, base8: Wt }); - var Zt = V({ prefix: "9", name: "base10", alphabet: "0123456789" }); - var ei = Object.freeze({ __proto__: null, base10: Zt }); - var ti = m3({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); - var ii = m3({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); - var si = Object.freeze({ __proto__: null, base16: ti, base16upper: ii }); - var ri = m3({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); - var ni = m3({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); - var oi = m3({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); - var ai = m3({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); - var hi = m3({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); - var ci = m3({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); - var li = m3({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); - var ui = m3({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); - var gi = m3({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); - var di = Object.freeze({ __proto__: null, base32: ri, base32upper: ni, base32pad: oi, base32padupper: ai, base32hex: hi, base32hexupper: ci, base32hexpad: li, base32hexpadupper: ui, base32z: gi }); - var pi = V({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); - var Di = V({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); - var yi = Object.freeze({ __proto__: null, base36: pi, base36upper: Di }); - var Ei = V({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); - var mi = V({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); - var bi = Object.freeze({ __proto__: null, base58btc: Ei, base58flickr: mi }); - var fi = m3({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); - var wi = m3({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); - var vi = m3({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); - var Ii = m3({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); - var Ri = Object.freeze({ __proto__: null, base64: fi, base64pad: wi, base64url: vi, base64urlpad: Ii }); - var ce = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); - var _i = ce.reduce((n3, e2, t) => (n3[t] = e2, n3), []); - var Ci = ce.reduce((n3, e2, t) => (n3[e2.codePointAt(0)] = t, n3), []); - function Ti(n3) { - return n3.reduce((e2, t) => (e2 += _i[t], e2), ""); - } - function Si(n3) { - const e2 = []; - for (const t of n3) { - const i2 = Ci[t.codePointAt(0)]; - if (i2 === void 0) - throw new Error(`Non-base256emoji character: ${t}`); - e2.push(i2); - } - return new Uint8Array(e2); - } - var Oi = G({ prefix: "\u{1F680}", name: "base256emoji", encode: Ti, decode: Si }); - var Pi = Object.freeze({ __proto__: null, base256emoji: Oi }); - var Ai = ue; - var le = 128; - var xi = 127; - var Ni = ~xi; - var Li = Math.pow(2, 31); - function ue(n3, e2, t) { - e2 = e2 || [], t = t || 0; - for (var i2 = t; n3 >= Li; ) - e2[t++] = n3 & 255 | le, n3 /= 128; - for (; n3 & Ni; ) - e2[t++] = n3 & 255 | le, n3 >>>= 7; - return e2[t] = n3 | 0, ue.bytes = t - i2 + 1, e2; - } - var Ui = Q; - var zi = 128; - var ge = 127; - function Q(n3, i2) { - var t = 0, i2 = i2 || 0, s2 = 0, r = i2, o2, h5 = n3.length; - do { - if (r >= h5) - throw Q.bytes = 0, new RangeError("Could not decode varint"); - o2 = n3[r++], t += s2 < 28 ? (o2 & ge) << s2 : (o2 & ge) * Math.pow(2, s2), s2 += 7; - } while (o2 >= zi); - return Q.bytes = r - i2, t; - } - var Fi = Math.pow(2, 7); - var Mi = Math.pow(2, 14); - var Bi = Math.pow(2, 21); - var $i = Math.pow(2, 28); - var ki = Math.pow(2, 35); - var Vi = Math.pow(2, 42); - var Ki = Math.pow(2, 49); - var qi = Math.pow(2, 56); - var Yi = Math.pow(2, 63); - var ji = function(n3) { - return n3 < Fi ? 1 : n3 < Mi ? 2 : n3 < Bi ? 3 : n3 < $i ? 4 : n3 < ki ? 5 : n3 < Vi ? 6 : n3 < Ki ? 7 : n3 < qi ? 8 : n3 < Yi ? 9 : 10; - }; - var Gi = { encode: Ai, decode: Ui, encodingLength: ji }; - var de = Gi; - var pe = (n3, e2, t = 0) => (de.encode(n3, e2, t), e2); - var De = (n3) => de.encodingLength(n3); - var Z = (n3, e2) => { - const t = e2.byteLength, i2 = De(n3), s2 = i2 + De(t), r = new Uint8Array(s2 + t); - return pe(n3, r, 0), pe(t, r, i2), r.set(e2, s2), new Hi(n3, t, e2, r); - }; - var Hi = class { - constructor(e2, t, i2, s2) { - this.code = e2, this.size = t, this.digest = i2, this.bytes = s2; - } - }; - var ye = ({ name: n3, code: e2, encode: t }) => new Xi(n3, e2, t); - var Xi = class { - constructor(e2, t, i2) { - this.name = e2, this.code = t, this.encode = i2; - } - digest(e2) { - if (e2 instanceof Uint8Array) { - const t = this.encode(e2); - return t instanceof Uint8Array ? Z(this.code, t) : t.then((i2) => Z(this.code, i2)); - } else - throw Error("Unknown type, must be binary type"); - } - }; - var Ee = (n3) => async (e2) => new Uint8Array(await crypto.subtle.digest(n3, e2)); - var Ji = ye({ name: "sha2-256", code: 18, encode: Ee("SHA-256") }); - var Wi = ye({ name: "sha2-512", code: 19, encode: Ee("SHA-512") }); - var Qi = Object.freeze({ __proto__: null, sha256: Ji, sha512: Wi }); - var me = 0; - var Zi = "identity"; - var be = ae; - var es = (n3) => Z(me, be(n3)); - var ts = { code: me, name: Zi, encode: be, digest: es }; - var is = Object.freeze({ __proto__: null, identity: ts }); - new TextEncoder(), new TextDecoder(); - var fe = { ...Ht, ...Jt, ...Qt, ...ei, ...si, ...di, ...yi, ...bi, ...Ri, ...Pi }; - ({ ...Qi, ...is }); - function we(n3) { - return globalThis.Buffer != null ? new Uint8Array(n3.buffer, n3.byteOffset, n3.byteLength) : n3; - } - function ss(n3 = 0) { - return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? we(globalThis.Buffer.allocUnsafe(n3)) : new Uint8Array(n3); - } - function ve(n3, e2, t, i2) { - return { name: n3, prefix: e2, encoder: { name: n3, prefix: e2, encode: t }, decoder: { decode: i2 } }; - } - var Ie = ve("utf8", "u", (n3) => "u" + new TextDecoder("utf8").decode(n3), (n3) => new TextEncoder().encode(n3.substring(1))); - var ee = ve("ascii", "a", (n3) => { - let e2 = "a"; - for (let t = 0; t < n3.length; t++) - e2 += String.fromCharCode(n3[t]); - return e2; - }, (n3) => { - n3 = n3.substring(1); - const e2 = ss(n3.length); - for (let t = 0; t < n3.length; t++) - e2[t] = n3.charCodeAt(t); - return e2; - }); - var rs = { utf8: Ie, "utf-8": Ie, hex: fe.base16, latin1: ee, ascii: ee, binary: ee, ...fe }; - function ns(n3, e2 = "utf8") { - const t = rs[e2]; - if (!t) - throw new Error(`Unsupported encoding "${e2}"`); - return (e2 === "utf8" || e2 === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? we(globalThis.Buffer.from(n3, "utf-8")) : t.decoder.decode(`${t.prefix}${n3}`); - } - var te = "wc"; - var Re = 2; - var H = "core"; - var L2 = `${te}@2:${H}:`; - var _e = { name: H, logger: "error" }; - var Ce = { database: ":memory:" }; - var Te = "crypto"; - var ie = "client_ed25519_seed"; - var Se = l4.ONE_DAY; - var Oe = "keychain"; - var Pe = "0.3"; - var Ae = "messages"; - var xe = "0.3"; - var Ne = l4.SIX_HOURS; - var Le = "publisher"; - var Ue = "irn"; - var ze = "error"; - var se = "wss://relay.walletconnect.com"; - var re = "wss://relay.walletconnect.org"; - var Fe = "relayer"; - var I2 = { message: "relayer_message", message_ack: "relayer_message_ack", connect: "relayer_connect", disconnect: "relayer_disconnect", error: "relayer_error", connection_stalled: "relayer_connection_stalled", transport_closed: "relayer_transport_closed", publish: "relayer_publish" }; - var Me = "_subscription"; - var w4 = { payload: "payload", connect: "connect", disconnect: "disconnect", error: "error" }; - var Be = l4.ONE_SECOND; - var os = { database: ":memory:" }; - var $e = "2.12.2"; - var ke = 1e4; - var Ve = "0.3"; - var Ke = "WALLETCONNECT_CLIENT_ID"; - var S4 = { created: "subscription_created", deleted: "subscription_deleted", expired: "subscription_expired", disabled: "subscription_disabled", sync: "subscription_sync", resubscribed: "subscription_resubscribed" }; - var as = l4.THIRTY_DAYS; - var qe = "subscription"; - var Ye = "0.3"; - var je = l4.FIVE_SECONDS * 1e3; - var Ge = "pairing"; - var He = "0.3"; - var hs = l4.THIRTY_DAYS; - var M = { wc_pairingDelete: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 1e3 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 1001 } }, wc_pairingPing: { req: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1002 }, res: { ttl: l4.THIRTY_SECONDS, prompt: false, tag: 1003 } }, unregistered_method: { req: { ttl: l4.ONE_DAY, prompt: false, tag: 0 }, res: { ttl: l4.ONE_DAY, prompt: false, tag: 0 } } }; - var K2 = { create: "pairing_create", expire: "pairing_expire", delete: "pairing_delete", ping: "pairing_ping" }; - var R2 = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; - var Xe = "history"; - var Je = "0.3"; - var We = "expirer"; - var _4 = { created: "expirer_created", deleted: "expirer_deleted", expired: "expirer_expired", sync: "expirer_sync" }; - var Qe = "0.3"; - var cs = l4.ONE_DAY; - var X = "verify-api"; - var B2 = "https://verify.walletconnect.com"; - var J = "https://verify.walletconnect.org"; - var Ze = [B2, J]; - var et = "echo"; - var tt = "https://echo.walletconnect.com"; - var it = class { - constructor(e2, t) { - this.core = e2, this.logger = t, this.keychain = /* @__PURE__ */ new Map(), this.name = Oe, this.version = Pe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { - if (!this.initialized) { - const i2 = await this.getKeyChain(); - typeof i2 < "u" && (this.keychain = i2), this.initialized = true; - } - }, this.has = (i2) => (this.isInitialized(), this.keychain.has(i2)), this.set = async (i2, s2) => { - this.isInitialized(), this.keychain.set(i2, s2), await this.persist(); - }, this.get = (i2) => { - this.isInitialized(); - const s2 = this.keychain.get(i2); - if (typeof s2 > "u") { - const { message: r } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${i2}`); - throw new Error(r); - } - return s2; - }, this.del = async (i2) => { - this.isInitialized(), this.keychain.delete(i2), await this.persist(); - }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - async setKeyChain(e2) { - await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); - } - async getKeyChain() { - const e2 = await this.core.storage.getItem(this.storageKey); - return typeof e2 < "u" ? a3.objToMap(e2) : void 0; - } - async persist() { - await this.setKeyChain(this.keychain); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var st = class { - constructor(e2, t, i2) { - this.core = e2, this.logger = t, this.name = Te, this.initialized = false, this.init = async () => { - this.initialized || (await this.keychain.init(), this.initialized = true); - }, this.hasKeys = (s2) => (this.isInitialized(), this.keychain.has(s2)), this.getClientId = async () => { - this.isInitialized(); - const s2 = await this.getClientSeed(), r = j2.generateKeyPair(s2); - return j2.encodeIss(r.publicKey); - }, this.generateKeyPair = () => { - this.isInitialized(); - const s2 = a3.generateKeyPair(); - return this.setPrivateKey(s2.publicKey, s2.privateKey); - }, this.signJWT = async (s2) => { - this.isInitialized(); - const r = await this.getClientSeed(), o2 = j2.generateKeyPair(r), h5 = a3.generateRandomBytes32(), c4 = Se; - return await j2.signJWT(h5, s2, c4, o2); - }, this.generateSharedKey = (s2, r, o2) => { - this.isInitialized(); - const h5 = this.getPrivateKey(s2), c4 = a3.deriveSymKey(h5, r); - return this.setSymKey(c4, o2); - }, this.setSymKey = async (s2, r) => { - this.isInitialized(); - const o2 = r || a3.hashKey(s2); - return await this.keychain.set(o2, s2), o2; - }, this.deleteKeyPair = async (s2) => { - this.isInitialized(), await this.keychain.del(s2); - }, this.deleteSymKey = async (s2) => { - this.isInitialized(), await this.keychain.del(s2); - }, this.encode = async (s2, r, o2) => { - this.isInitialized(); - const h5 = a3.validateEncoding(o2), c4 = oe.safeJsonStringify(r); - if (a3.isTypeOneEnvelope(h5)) { - const b4 = h5.senderPublicKey, F = h5.receiverPublicKey; - s2 = await this.generateSharedKey(b4, F); - } - const u3 = this.getSymKey(s2), { type: p3, senderPublicKey: D2 } = h5; - return a3.encrypt({ type: p3, symKey: u3, message: c4, senderPublicKey: D2 }); - }, this.decode = async (s2, r, o2) => { - this.isInitialized(); - const h5 = a3.validateDecoding(r, o2); - if (a3.isTypeOneEnvelope(h5)) { - const c4 = h5.receiverPublicKey, u3 = h5.senderPublicKey; - s2 = await this.generateSharedKey(c4, u3); - } - try { - const c4 = this.getSymKey(s2), u3 = a3.decrypt({ symKey: c4, encoded: r }); - return oe.safeJsonParse(u3); - } catch (c4) { - this.logger.error(`Failed to decode message from topic: '${s2}', clientId: '${await this.getClientId()}'`), this.logger.error(c4); - } - }, this.getPayloadType = (s2) => { - const r = a3.deserialize(s2); - return a3.decodeTypeByte(r.type); - }, this.getPayloadSenderPublicKey = (s2) => { - const r = a3.deserialize(s2); - return r.senderPublicKey ? _t.toString(r.senderPublicKey, a3.BASE16) : void 0; - }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.keychain = i2 || new it(this.core, this.logger); - } - get context() { - return g3.getLoggerContext(this.logger); - } - async setPrivateKey(e2, t) { - return await this.keychain.set(e2, t), e2; - } - getPrivateKey(e2) { - return this.keychain.get(e2); - } - async getClientSeed() { - let e2 = ""; - try { - e2 = this.keychain.get(ie); - } catch { - e2 = a3.generateRandomBytes32(), await this.keychain.set(ie, e2); - } - return ns(e2, "base16"); - } - getSymKey(e2) { - return this.keychain.get(e2); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var rt = class extends x3.IMessageTracker { - constructor(e2, t) { - super(e2, t), this.logger = e2, this.core = t, this.messages = /* @__PURE__ */ new Map(), this.name = Ae, this.version = xe, this.initialized = false, this.storagePrefix = L2, this.init = async () => { - if (!this.initialized) { - this.logger.trace("Initialized"); - try { - const i2 = await this.getRelayerMessages(); - typeof i2 < "u" && (this.messages = i2), this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", size: this.messages.size }); - } catch (i2) { - this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(i2); - } finally { - this.initialized = true; - } - } - }, this.set = async (i2, s2) => { - this.isInitialized(); - const r = a3.hashMessage(s2); - let o2 = this.messages.get(i2); - return typeof o2 > "u" && (o2 = {}), typeof o2[r] < "u" || (o2[r] = s2, this.messages.set(i2, o2), await this.persist()), r; - }, this.get = (i2) => { - this.isInitialized(); - let s2 = this.messages.get(i2); - return typeof s2 > "u" && (s2 = {}), s2; - }, this.has = (i2, s2) => { - this.isInitialized(); - const r = this.get(i2), o2 = a3.hashMessage(s2); - return typeof r[o2] < "u"; - }, this.del = async (i2) => { - this.isInitialized(), this.messages.delete(i2), await this.persist(); - }, this.logger = g3.generateChildLogger(e2, this.name), this.core = t; - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - async setRelayerMessages(e2) { - await this.core.storage.setItem(this.storageKey, a3.mapToObj(e2)); - } - async getRelayerMessages() { - const e2 = await this.core.storage.getItem(this.storageKey); - return typeof e2 < "u" ? a3.objToMap(e2) : void 0; - } - async persist() { - await this.setRelayerMessages(this.messages); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var ls2 = class extends x3.IPublisher { - constructor(e2, t) { - super(e2, t), this.relayer = e2, this.logger = t, this.events = new z3.EventEmitter(), this.name = Le, this.queue = /* @__PURE__ */ new Map(), this.publishTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.failedPublishTimeout = l4.toMiliseconds(l4.ONE_SECOND), this.needsTransportRestart = false, this.publish = async (i2, s2, r) => { - var o2; - this.logger.debug("Publishing Payload"), this.logger.trace({ type: "method", method: "publish", params: { topic: i2, message: s2, opts: r } }); - const h5 = r?.ttl || Ne, c4 = a3.getRelayProtocolName(r), u3 = r?.prompt || false, p3 = r?.tag || 0, D2 = r?.id || f4.getBigIntRpcId().toString(), b4 = { topic: i2, message: s2, opts: { ttl: h5, relay: c4, prompt: u3, tag: p3, id: D2 } }, F = `Failed to publish payload, please try again. id:${D2} tag:${p3}`, d3 = Date.now(); - let y4, C3 = 1; - try { - for (; y4 === void 0; ) { - if (Date.now() - d3 > this.publishTimeout) - throw new Error(F); - this.logger.trace({ id: D2, attempts: C3 }, `publisher.publish - attempt ${C3}`), y4 = await await a3.createExpiringPromise(this.rpcPublish(i2, s2, h5, c4, u3, p3, D2).catch((E4) => this.logger.warn(E4)), this.publishTimeout, F), C3++, y4 || await new Promise((E4) => setTimeout(E4, this.failedPublishTimeout)); - } - this.relayer.events.emit(I2.publish, b4), this.logger.debug("Successfully Published Payload"), this.logger.trace({ type: "method", method: "publish", params: { id: D2, topic: i2, message: s2, opts: r } }); - } catch (E4) { - if (this.logger.debug("Failed to Publish Payload"), this.logger.error(E4), (o2 = r?.internal) != null && o2.throwOnFailedPublish) - throw E4; - this.queue.set(D2, b4); - } - }, this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.registerEventListeners(); - } - get context() { - return g3.getLoggerContext(this.logger); - } - rpcPublish(e2, t, i2, s2, r, o2, h5) { - var c4, u3, p3, D2; - const b4 = { method: a3.getRelayProtocolApi(s2.protocol).publish, params: { topic: e2, message: t, ttl: i2, prompt: r, tag: o2 }, id: h5 }; - return a3.isUndefined((c4 = b4.params) == null ? void 0 : c4.prompt) && ((u3 = b4.params) == null || delete u3.prompt), a3.isUndefined((p3 = b4.params) == null ? void 0 : p3.tag) && ((D2 = b4.params) == null || delete D2.tag), this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "message", direction: "outgoing", request: b4 }), this.relayer.request(b4); - } - removeRequestFromQueue(e2) { - this.queue.delete(e2); - } - checkQueue() { - this.queue.forEach(async (e2) => { - const { topic: t, message: i2, opts: s2 } = e2; - await this.publish(t, i2, s2); - }); - } - registerEventListeners() { - this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { - if (this.needsTransportRestart) { - this.needsTransportRestart = false, this.relayer.events.emit(I2.connection_stalled); - return; - } - this.checkQueue(); - }), this.relayer.on(I2.message_ack, (e2) => { - this.removeRequestFromQueue(e2.id.toString()); - }); - } - }; - var us = class { - constructor() { - this.map = /* @__PURE__ */ new Map(), this.set = (e2, t) => { - const i2 = this.get(e2); - this.exists(e2, t) || this.map.set(e2, [...i2, t]); - }, this.get = (e2) => this.map.get(e2) || [], this.exists = (e2, t) => this.get(e2).includes(t), this.delete = (e2, t) => { - if (typeof t > "u") { - this.map.delete(e2); - return; - } - if (!this.map.has(e2)) - return; - const i2 = this.get(e2); - if (!this.exists(e2, t)) - return; - const s2 = i2.filter((r) => r !== t); - if (!s2.length) { - this.map.delete(e2); - return; - } - this.map.set(e2, s2); - }, this.clear = () => { - this.map.clear(); - }; - } - get topics() { - return Array.from(this.map.keys()); - } - }; - var gs = Object.defineProperty; - var ds = Object.defineProperties; - var ps = Object.getOwnPropertyDescriptors; - var nt = Object.getOwnPropertySymbols; - var Ds = Object.prototype.hasOwnProperty; - var ys = Object.prototype.propertyIsEnumerable; - var ot = (n3, e2, t) => e2 in n3 ? gs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var q2 = (n3, e2) => { - for (var t in e2 || (e2 = {})) - Ds.call(e2, t) && ot(n3, t, e2[t]); - if (nt) - for (var t of nt(e2)) - ys.call(e2, t) && ot(n3, t, e2[t]); - return n3; - }; - var ne = (n3, e2) => ds(n3, ps(e2)); - var at = class extends x3.ISubscriber { - constructor(e2, t) { - super(e2, t), this.relayer = e2, this.logger = t, this.subscriptions = /* @__PURE__ */ new Map(), this.topicMap = new us(), this.events = new z3.EventEmitter(), this.name = qe, this.version = Ye, this.pending = /* @__PURE__ */ new Map(), this.cached = [], this.initialized = false, this.pendingSubscriptionWatchLabel = "pending_sub_watch_label", this.pollingInterval = 20, this.storagePrefix = L2, this.subscribeTimeout = l4.toMiliseconds(l4.ONE_MINUTE), this.restartInProgress = false, this.batchSubscribeTopicsLimit = 500, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), this.registerEventListeners(), this.clientId = await this.relayer.core.crypto.getClientId()); - }, this.subscribe = async (i2, s2) => { - await this.restartToComplete(), this.isInitialized(), this.logger.debug("Subscribing Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } }); - try { - const r = a3.getRelayProtocolName(s2), o2 = { topic: i2, relay: r }; - this.pending.set(i2, o2); - const h5 = await this.rpcSubscribe(i2, r); - return typeof h5 == "string" && (this.onSubscribe(h5, o2), this.logger.debug("Successfully Subscribed Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: i2, opts: s2 } })), h5; - } catch (r) { - throw this.logger.debug("Failed to Subscribe Topic"), this.logger.error(r), r; - } - }, this.unsubscribe = async (i2, s2) => { - await this.restartToComplete(), this.isInitialized(), typeof s2?.id < "u" ? await this.unsubscribeById(i2, s2.id, s2) : await this.unsubscribeByTopic(i2, s2); - }, this.isSubscribed = async (i2) => { - if (this.topics.includes(i2)) - return true; - const s2 = `${this.pendingSubscriptionWatchLabel}_${i2}`; - return await new Promise((r, o2) => { - const h5 = new l4.Watch(); - h5.start(s2); - const c4 = setInterval(() => { - !this.pending.has(i2) && this.topics.includes(i2) && (clearInterval(c4), h5.stop(s2), r(true)), h5.elapsed(s2) >= je && (clearInterval(c4), h5.stop(s2), o2(new Error("Subscription resolution timeout"))); - }, this.pollingInterval); - }).catch(() => false); - }, this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.start = async () => { - await this.onConnect(); - }, this.stop = async () => { - await this.onDisconnect(); - }, this.restart = async () => { - this.restartInProgress = true, await this.restore(), await this.reset(), this.restartInProgress = false; - }, this.relayer = e2, this.logger = g3.generateChildLogger(t, this.name), this.clientId = ""; - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.relayer.core.customStoragePrefix + "//" + this.name; - } - get length() { - return this.subscriptions.size; - } - get ids() { - return Array.from(this.subscriptions.keys()); - } - get values() { - return Array.from(this.subscriptions.values()); - } - get topics() { - return this.topicMap.topics; - } - hasSubscription(e2, t) { - let i2 = false; - try { - i2 = this.getSubscription(e2).topic === t; - } catch { - } - return i2; - } - onEnable() { - this.cached = [], this.initialized = true; - } - onDisable() { - this.cached = this.values, this.subscriptions.clear(), this.topicMap.clear(); - } - async unsubscribeByTopic(e2, t) { - const i2 = this.topicMap.get(e2); - await Promise.all(i2.map(async (s2) => await this.unsubscribeById(e2, s2, t))); - } - async unsubscribeById(e2, t, i2) { - this.logger.debug("Unsubscribing Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); - try { - const s2 = a3.getRelayProtocolName(i2); - await this.rpcUnsubscribe(e2, t, s2); - const r = a3.getSdkError("USER_DISCONNECTED", `${this.name}, ${e2}`); - await this.onUnsubscribe(e2, t, r), this.logger.debug("Successfully Unsubscribed Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: i2 } }); - } catch (s2) { - throw this.logger.debug("Failed to Unsubscribe Topic"), this.logger.error(s2), s2; - } - } - async rpcSubscribe(e2, t) { - const i2 = { method: a3.getRelayProtocolApi(t.protocol).subscribe, params: { topic: e2 } }; - this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); - try { - return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout) ? a3.hashMessage(e2 + this.clientId) : null; - } catch { - this.logger.debug("Outgoing Relay Subscribe Payload stalled"), this.relayer.events.emit(I2.connection_stalled); - } - return null; - } - async rpcBatchSubscribe(e2) { - if (!e2.length) - return; - const t = e2[0].relay, i2 = { method: a3.getRelayProtocolApi(t.protocol).batchSubscribe, params: { topics: e2.map((s2) => s2.topic) } }; - this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i2 }); - try { - return await await a3.createExpiringPromise(this.relayer.request(i2).catch((s2) => this.logger.warn(s2)), this.subscribeTimeout); - } catch { - this.relayer.events.emit(I2.connection_stalled); - } - } - rpcUnsubscribe(e2, t, i2) { - const s2 = { method: a3.getRelayProtocolApi(i2.protocol).unsubscribe, params: { topic: e2, id: t } }; - return this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s2 }), this.relayer.request(s2); - } - onSubscribe(e2, t) { - this.setSubscription(e2, ne(q2({}, t), { id: e2 })), this.pending.delete(t.topic); - } - onBatchSubscribe(e2) { - e2.length && e2.forEach((t) => { - this.setSubscription(t.id, q2({}, t)), this.pending.delete(t.topic); - }); - } - async onUnsubscribe(e2, t, i2) { - this.events.removeAllListeners(t), this.hasSubscription(t, e2) && this.deleteSubscription(t, i2), await this.relayer.messages.del(e2); - } - async setRelayerSubscriptions(e2) { - await this.relayer.core.storage.setItem(this.storageKey, e2); - } - async getRelayerSubscriptions() { - return await this.relayer.core.storage.getItem(this.storageKey); - } - setSubscription(e2, t) { - this.logger.debug("Setting subscription"), this.logger.trace({ type: "method", method: "setSubscription", id: e2, subscription: t }), this.addSubscription(e2, t); - } - addSubscription(e2, t) { - this.subscriptions.set(e2, q2({}, t)), this.topicMap.set(t.topic, e2), this.events.emit(S4.created, t); - } - getSubscription(e2) { - this.logger.debug("Getting subscription"), this.logger.trace({ type: "method", method: "getSubscription", id: e2 }); - const t = this.subscriptions.get(e2); - if (!t) { - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw new Error(i2); - } - return t; - } - deleteSubscription(e2, t) { - this.logger.debug("Deleting subscription"), this.logger.trace({ type: "method", method: "deleteSubscription", id: e2, reason: t }); - const i2 = this.getSubscription(e2); - this.subscriptions.delete(e2), this.topicMap.delete(i2.topic, e2), this.events.emit(S4.deleted, ne(q2({}, i2), { reason: t })); - } - async persist() { - await this.setRelayerSubscriptions(this.values), this.events.emit(S4.sync); - } - async reset() { - if (this.cached.length) { - const e2 = Math.ceil(this.cached.length / this.batchSubscribeTopicsLimit); - for (let t = 0; t < e2; t++) { - const i2 = this.cached.splice(0, this.batchSubscribeTopicsLimit); - await this.batchSubscribe(i2); - } - } - this.events.emit(S4.resubscribed); - } - async restore() { - try { - const e2 = await this.getRelayerSubscriptions(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.subscriptions.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored subscriptions for ${this.name}`), this.logger.trace({ type: "method", method: "restore", subscriptions: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore subscriptions for ${this.name}`), this.logger.error(e2); - } - } - async batchSubscribe(e2) { - if (!e2.length) - return; - const t = await this.rpcBatchSubscribe(e2); - a3.isValidArray(t) && this.onBatchSubscribe(t.map((i2, s2) => ne(q2({}, e2[s2]), { id: i2 }))); - } - async onConnect() { - await this.restart(), this.onEnable(); - } - onDisconnect() { - this.onDisable(); - } - async checkPending() { - if (!this.initialized || !this.relayer.connected) - return; - const e2 = []; - this.pending.forEach((t) => { - e2.push(t); - }), await this.batchSubscribe(e2); - } - registerEventListeners() { - this.relayer.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, async () => { - await this.checkPending(); - }), this.events.on(S4.created, async (e2) => { - const t = S4.created; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); - }), this.events.on(S4.deleted, async (e2) => { - const t = S4.deleted; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); - }); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - async restartToComplete() { - this.restartInProgress && await new Promise((e2) => { - const t = setInterval(() => { - this.restartInProgress || (clearInterval(t), e2()); - }, this.pollingInterval); - }); - } - }; - var Es = Object.defineProperty; - var ht = Object.getOwnPropertySymbols; - var ms = Object.prototype.hasOwnProperty; - var bs = Object.prototype.propertyIsEnumerable; - var ct = (n3, e2, t) => e2 in n3 ? Es(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var fs = (n3, e2) => { - for (var t in e2 || (e2 = {})) - ms.call(e2, t) && ct(n3, t, e2[t]); - if (ht) - for (var t of ht(e2)) - bs.call(e2, t) && ct(n3, t, e2[t]); - return n3; - }; - var lt = class extends x3.IRelayer { - constructor(e2) { - super(e2), this.protocol = "wc", this.version = 2, this.events = new z3.EventEmitter(), this.name = Fe, this.transportExplicitlyClosed = false, this.initialized = false, this.connectionAttemptInProgress = false, this.connectionStatusPollingInterval = 20, this.staleConnectionErrors = ["socket hang up", "socket stalled", "interrupted"], this.hasExperiencedNetworkDisruption = false, this.requestsInFlight = /* @__PURE__ */ new Map(), this.heartBeatTimeout = l4.toMiliseconds(l4.THIRTY_SECONDS + l4.ONE_SECOND), this.request = async (t) => { - var i2, s2; - this.logger.debug("Publishing Request Payload"); - const r = t.id || f4.getBigIntRpcId().toString(); - await this.toEstablishConnection(); - try { - const o2 = this.provider.request(t); - this.requestsInFlight.set(r, { promise: o2, request: t }), this.logger.trace({ id: r, method: t.method, topic: (i2 = t.params) == null ? void 0 : i2.topic }, "relayer.request - attempt to publish..."); - const h5 = await new Promise(async (c4, u3) => { - const p3 = () => { - u3(new Error(`relayer.request - publish interrupted, id: ${r}`)); - }; - this.provider.on(w4.disconnect, p3); - const D2 = await o2; - this.provider.off(w4.disconnect, p3), c4(D2); - }); - return this.logger.trace({ id: r, method: t.method, topic: (s2 = t.params) == null ? void 0 : s2.topic }, "relayer.request - published"), h5; - } catch (o2) { - throw this.logger.debug(`Failed to Publish Request: ${r}`), o2; - } finally { - this.requestsInFlight.delete(r); - } - }, this.resetPingTimeout = () => { - if (a3.isNode()) - try { - clearTimeout(this.pingTimeout), this.pingTimeout = setTimeout(() => { - var t, i2, s2; - (s2 = (i2 = (t = this.provider) == null ? void 0 : t.connection) == null ? void 0 : i2.socket) == null || s2.terminate(); - }, this.heartBeatTimeout); - } catch (t) { - this.logger.warn(t); - } - }, this.onPayloadHandler = (t) => { - this.onProviderPayload(t), this.resetPingTimeout(); - }, this.onConnectHandler = () => { - this.startPingTimeout(), this.events.emit(I2.connect); - }, this.onDisconnectHandler = () => { - this.onProviderDisconnect(); - }, this.onProviderErrorHandler = (t) => { - this.logger.error(t), this.events.emit(I2.error, t), this.logger.info("Fatal socket error received, closing transport"), this.transportClose(); - }, this.registerProviderListeners = () => { - this.provider.on(w4.payload, this.onPayloadHandler), this.provider.on(w4.connect, this.onConnectHandler), this.provider.on(w4.disconnect, this.onDisconnectHandler), this.provider.on(w4.error, this.onProviderErrorHandler); - }, this.core = e2.core, this.logger = typeof e2.logger < "u" && typeof e2.logger != "string" ? g3.generateChildLogger(e2.logger, this.name) : g3.pino(g3.getDefaultLoggerOptions({ level: e2.logger || ze })), this.messages = new rt(this.logger, e2.core), this.subscriber = new at(this, this.logger), this.publisher = new ls2(this, this.logger), this.relayUrl = e2?.relayUrl || se, this.projectId = e2.projectId, this.bundleId = a3.getBundleId(), this.provider = {}; - } - async init() { - this.logger.trace("Initialized"), this.registerEventListeners(), await this.createProvider(), await Promise.all([this.messages.init(), this.subscriber.init()]); - try { - await this.transportOpen(); - } catch { - this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${re}...`), await this.restartTransport(re); - } - this.initialized = true, setTimeout(async () => { - this.subscriber.topics.length === 0 && this.subscriber.pending.size === 0 && (this.logger.info("No topics subscribed to after init, closing transport"), await this.transportClose(), this.transportExplicitlyClosed = false); - }, ke); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get connected() { - var e2, t, i2; - return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 1; - } - get connecting() { - var e2, t, i2; - return ((i2 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : i2.readyState) === 0; - } - async publish(e2, t, i2) { - this.isInitialized(), await this.publisher.publish(e2, t, i2), await this.recordMessageEvent({ topic: e2, message: t, publishedAt: Date.now() }); - } - async subscribe(e2, t) { - var i2; - this.isInitialized(); - let s2 = ((i2 = this.subscriber.topicMap.get(e2)) == null ? void 0 : i2[0]) || "", r; - const o2 = (h5) => { - h5.topic === e2 && (this.subscriber.off(S4.created, o2), r()); - }; - return await Promise.all([new Promise((h5) => { - r = h5, this.subscriber.on(S4.created, o2); - }), new Promise(async (h5) => { - s2 = await this.subscriber.subscribe(e2, t) || s2, h5(); - })]), s2; - } - async unsubscribe(e2, t) { - this.isInitialized(), await this.subscriber.unsubscribe(e2, t); - } - on(e2, t) { - this.events.on(e2, t); - } - once(e2, t) { - this.events.once(e2, t); - } - off(e2, t) { - this.events.off(e2, t); - } - removeListener(e2, t) { - this.events.removeListener(e2, t); - } - async transportDisconnect() { - if (!this.hasExperiencedNetworkDisruption && this.connected && this.requestsInFlight.size > 0) - try { - await Promise.all(Array.from(this.requestsInFlight.values()).map((e2) => e2.promise)); - } catch (e2) { - this.logger.warn(e2); - } - this.hasExperiencedNetworkDisruption || this.connected ? await a3.createExpiringPromise(this.provider.disconnect(), 2e3, "provider.disconnect()").catch(() => this.onProviderDisconnect()) : this.onProviderDisconnect(); - } - async transportClose() { - this.transportExplicitlyClosed = true, await this.transportDisconnect(); - } - async transportOpen(e2) { - await this.confirmOnlineStateOrThrow(), e2 && e2 !== this.relayUrl && (this.relayUrl = e2, await this.transportDisconnect(), await this.createProvider()), this.connectionAttemptInProgress = true, this.transportExplicitlyClosed = false; - try { - await new Promise(async (t, i2) => { - const s2 = () => { - this.provider.off(w4.disconnect, s2), i2(new Error("Connection interrupted while trying to subscribe")); - }; - this.provider.on(w4.disconnect, s2), await a3.createExpiringPromise(this.provider.connect(), l4.toMiliseconds(l4.ONE_MINUTE), `Socket stalled when trying to connect to ${this.relayUrl}`).catch((r) => { - i2(r); - }), await this.subscriber.start(), this.hasExperiencedNetworkDisruption = false, t(); - }); - } catch (t) { - this.logger.error(t); - const i2 = t; - if (!this.isConnectionStalled(i2.message)) - throw t; - } finally { - this.connectionAttemptInProgress = false; - } - } - async restartTransport(e2) { - this.connectionAttemptInProgress || (this.relayUrl = e2 || this.relayUrl, await this.confirmOnlineStateOrThrow(), await this.transportClose(), await this.createProvider(), await this.transportOpen()); - } - async confirmOnlineStateOrThrow() { - if (!await a3.isOnline()) - throw new Error("No internet connection detected. Please restart your network and try again."); - } - startPingTimeout() { - var e2, t, i2, s2, r; - if (a3.isNode()) - try { - (t = (e2 = this.provider) == null ? void 0 : e2.connection) != null && t.socket && ((r = (s2 = (i2 = this.provider) == null ? void 0 : i2.connection) == null ? void 0 : s2.socket) == null || r.once("ping", () => { - this.resetPingTimeout(); - })), this.resetPingTimeout(); - } catch (o2) { - this.logger.warn(o2); - } - } - isConnectionStalled(e2) { - return this.staleConnectionErrors.some((t) => e2.includes(t)); - } - async createProvider() { - this.provider.connection && this.unregisterProviderListeners(); - const e2 = await this.core.crypto.signJWT(this.relayUrl); - this.provider = new Ct.JsonRpcProvider(new Nt.default(a3.formatRelayRpcUrl({ sdkVersion: $e, protocol: this.protocol, version: this.version, relayUrl: this.relayUrl, projectId: this.projectId, auth: e2, useOnCloseEvent: true, bundleId: this.bundleId }))), this.registerProviderListeners(); - } - async recordMessageEvent(e2) { - const { topic: t, message: i2 } = e2; - await this.messages.set(t, i2); - } - async shouldIgnoreMessageEvent(e2) { - const { topic: t, message: i2 } = e2; - if (!i2 || i2.length === 0) - return this.logger.debug(`Ignoring invalid/empty message: ${i2}`), true; - if (!await this.subscriber.isSubscribed(t)) - return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`), true; - const s2 = this.messages.has(t, i2); - return s2 && this.logger.debug(`Ignoring duplicate message: ${i2}`), s2; - } - async onProviderPayload(e2) { - if (this.logger.debug("Incoming Relay Payload"), this.logger.trace({ type: "payload", direction: "incoming", payload: e2 }), f4.isJsonRpcRequest(e2)) { - if (!e2.method.endsWith(Me)) - return; - const t = e2.params, { topic: i2, message: s2, publishedAt: r } = t.data, o2 = { topic: i2, message: s2, publishedAt: r }; - this.logger.debug("Emitting Relayer Payload"), this.logger.trace(fs({ type: "event", event: t.id }, o2)), this.events.emit(t.id, o2), await this.acknowledgePayload(e2), await this.onMessageEvent(o2); - } else - f4.isJsonRpcResponse(e2) && this.events.emit(I2.message_ack, e2); - } - async onMessageEvent(e2) { - await this.shouldIgnoreMessageEvent(e2) || (this.events.emit(I2.message, e2), await this.recordMessageEvent(e2)); - } - async acknowledgePayload(e2) { - const t = f4.formatJsonRpcResult(e2.id, true); - await this.provider.connection.send(t); - } - unregisterProviderListeners() { - this.provider.off(w4.payload, this.onPayloadHandler), this.provider.off(w4.connect, this.onConnectHandler), this.provider.off(w4.disconnect, this.onDisconnectHandler), this.provider.off(w4.error, this.onProviderErrorHandler); - } - async registerEventListeners() { - let e2 = await a3.isOnline(); - a3.subscribeToNetworkChange(async (t) => { - e2 !== t && (e2 = t, t ? await this.restartTransport().catch((i2) => this.logger.error(i2)) : (this.hasExperiencedNetworkDisruption = true, await this.transportDisconnect(), this.transportExplicitlyClosed = false)); - }); - } - async onProviderDisconnect() { - await this.subscriber.stop(), this.events.emit(I2.disconnect), this.connectionAttemptInProgress = false, !this.transportExplicitlyClosed && setTimeout(async () => { - await this.transportOpen().catch((e2) => this.logger.error(e2)); - }, l4.toMiliseconds(Be)); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - async toEstablishConnection() { - await this.confirmOnlineStateOrThrow(), !this.connected && (this.connectionAttemptInProgress && await new Promise((e2) => { - const t = setInterval(() => { - this.connected && (clearInterval(t), e2()); - }, this.connectionStatusPollingInterval); - }), await this.transportOpen()); - } - }; - var ws = Object.defineProperty; - var ut = Object.getOwnPropertySymbols; - var vs = Object.prototype.hasOwnProperty; - var Is = Object.prototype.propertyIsEnumerable; - var gt = (n3, e2, t) => e2 in n3 ? ws(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var dt = (n3, e2) => { - for (var t in e2 || (e2 = {})) - vs.call(e2, t) && gt(n3, t, e2[t]); - if (ut) - for (var t of ut(e2)) - Is.call(e2, t) && gt(n3, t, e2[t]); - return n3; - }; - var pt = class extends x3.IStore { - constructor(e2, t, i2, s2 = L2, r = void 0) { - super(e2, t, i2, s2), this.core = e2, this.logger = t, this.name = i2, this.map = /* @__PURE__ */ new Map(), this.version = Ve, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.recentlyDeleted = [], this.recentlyDeletedLimit = 200, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((o2) => { - this.getKey && o2 !== null && !a3.isUndefined(o2) ? this.map.set(this.getKey(o2), o2) : a3.isProposalStruct(o2) ? this.map.set(o2.id, o2) : a3.isSessionStruct(o2) && this.map.set(o2.topic, o2); - }), this.cached = [], this.initialized = true); - }, this.set = async (o2, h5) => { - this.isInitialized(), this.map.has(o2) ? await this.update(o2, h5) : (this.logger.debug("Setting value"), this.logger.trace({ type: "method", method: "set", key: o2, value: h5 }), this.map.set(o2, h5), await this.persist()); - }, this.get = (o2) => (this.isInitialized(), this.logger.debug("Getting value"), this.logger.trace({ type: "method", method: "get", key: o2 }), this.getData(o2)), this.getAll = (o2) => (this.isInitialized(), o2 ? this.values.filter((h5) => Object.keys(o2).every((c4) => Lt.default(h5[c4], o2[c4]))) : this.values), this.update = async (o2, h5) => { - this.isInitialized(), this.logger.debug("Updating value"), this.logger.trace({ type: "method", method: "update", key: o2, update: h5 }); - const c4 = dt(dt({}, this.getData(o2)), h5); - this.map.set(o2, c4), await this.persist(); - }, this.delete = async (o2, h5) => { - this.isInitialized(), this.map.has(o2) && (this.logger.debug("Deleting value"), this.logger.trace({ type: "method", method: "delete", key: o2, reason: h5 }), this.map.delete(o2), this.addToRecentlyDeleted(o2), await this.persist()); - }, this.logger = g3.generateChildLogger(t, this.name), this.storagePrefix = s2, this.getKey = r; - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - get length() { - return this.map.size; - } - get keys() { - return Array.from(this.map.keys()); - } - get values() { - return Array.from(this.map.values()); - } - addToRecentlyDeleted(e2) { - this.recentlyDeleted.push(e2), this.recentlyDeleted.length >= this.recentlyDeletedLimit && this.recentlyDeleted.splice(0, this.recentlyDeletedLimit / 2); - } - async setDataStore(e2) { - await this.core.storage.setItem(this.storageKey, e2); - } - async getDataStore() { - return await this.core.storage.getItem(this.storageKey); - } - getData(e2) { - const t = this.map.get(e2); - if (!t) { - if (this.recentlyDeleted.includes(e2)) { - const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${this.name}: ${e2}`); - throw this.logger.error(s2), new Error(s2); - } - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw this.logger.error(i2), new Error(i2); - } - return t; - } - async persist() { - await this.setDataStore(this.values); - } - async restore() { - try { - const e2 = await this.getDataStore(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.map.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored value for ${this.name}`), this.logger.trace({ type: "method", method: "restore", value: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore value for ${this.name}`), this.logger.error(e2); - } - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var Dt = class { - constructor(e2, t) { - this.core = e2, this.logger = t, this.name = Ge, this.version = He, this.events = new At.default(), this.initialized = false, this.storagePrefix = L2, this.ignoredPayloadTypes = [a3.TYPE_1], this.registeredMethods = [], this.init = async () => { - this.initialized || (await this.pairings.init(), await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.initialized = true, this.logger.trace("Initialized")); - }, this.register = ({ methods: i2 }) => { - this.isInitialized(), this.registeredMethods = [.../* @__PURE__ */ new Set([...this.registeredMethods, ...i2])]; - }, this.create = async (i2) => { - this.isInitialized(); - const s2 = a3.generateRandomBytes32(), r = await this.core.crypto.setSymKey(s2), o2 = a3.calcExpiry(l4.FIVE_MINUTES), h5 = { protocol: Ue }, c4 = { topic: r, expiry: o2, relay: h5, active: false }, u3 = a3.formatUri({ protocol: this.core.protocol, version: this.core.version, topic: r, symKey: s2, relay: h5, expiryTimestamp: o2, methods: i2?.methods }); - return await this.pairings.set(r, c4), await this.core.relayer.subscribe(r), this.core.expirer.set(r, o2), { topic: r, uri: u3 }; - }, this.pair = async (i2) => { - this.isInitialized(), this.isValidPair(i2); - const { topic: s2, symKey: r, relay: o2, expiryTimestamp: h5, methods: c4 } = a3.parseUri(i2.uri); - let u3; - if (this.pairings.keys.includes(s2) && (u3 = this.pairings.get(s2), u3.active)) - throw new Error(`Pairing already exists: ${s2}. Please try again with a new connection URI.`); - const p3 = h5 || a3.calcExpiry(l4.FIVE_MINUTES), D2 = { topic: s2, relay: o2, expiry: p3, active: false, methods: c4 }; - return await this.pairings.set(s2, D2), this.core.expirer.set(s2, p3), i2.activatePairing && await this.activate({ topic: s2 }), this.events.emit(K2.create, D2), this.core.crypto.keychain.has(s2) || await this.core.crypto.setSymKey(r, s2), await this.core.relayer.subscribe(s2, { relay: o2 }), D2; - }, this.activate = async ({ topic: i2 }) => { - this.isInitialized(); - const s2 = a3.calcExpiry(l4.THIRTY_DAYS); - await this.pairings.update(i2, { active: true, expiry: s2 }), this.core.expirer.set(i2, s2); - }, this.ping = async (i2) => { - this.isInitialized(), await this.isValidPing(i2); - const { topic: s2 } = i2; - if (this.pairings.keys.includes(s2)) { - const r = await this.sendRequest(s2, "wc_pairingPing", {}), { done: o2, resolve: h5, reject: c4 } = a3.createDelayedPromise(); - this.events.once(a3.engineEvent("pairing_ping", r), ({ error: u3 }) => { - u3 ? c4(u3) : h5(); - }), await o2(); - } - }, this.updateExpiry = async ({ topic: i2, expiry: s2 }) => { - this.isInitialized(), await this.pairings.update(i2, { expiry: s2 }); - }, this.updateMetadata = async ({ topic: i2, metadata: s2 }) => { - this.isInitialized(), await this.pairings.update(i2, { peerMetadata: s2 }); - }, this.getPairings = () => (this.isInitialized(), this.pairings.values), this.disconnect = async (i2) => { - this.isInitialized(), await this.isValidDisconnect(i2); - const { topic: s2 } = i2; - this.pairings.keys.includes(s2) && (await this.sendRequest(s2, "wc_pairingDelete", a3.getSdkError("USER_DISCONNECTED")), await this.deletePairing(s2)); - }, this.sendRequest = async (i2, s2, r) => { - const o2 = f4.formatJsonRpcRequest(s2, r), h5 = await this.core.crypto.encode(i2, o2), c4 = M[s2].req; - return this.core.history.set(i2, o2), this.core.relayer.publish(i2, h5, c4), o2.id; - }, this.sendResult = async (i2, s2, r) => { - const o2 = f4.formatJsonRpcResult(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method].res; - await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); - }, this.sendError = async (i2, s2, r) => { - const o2 = f4.formatJsonRpcError(i2, r), h5 = await this.core.crypto.encode(s2, o2), c4 = await this.core.history.get(s2, i2), u3 = M[c4.request.method] ? M[c4.request.method].res : M.unregistered_method.res; - await this.core.relayer.publish(s2, h5, u3), await this.core.history.resolve(o2); - }, this.deletePairing = async (i2, s2) => { - await this.core.relayer.unsubscribe(i2), await Promise.all([this.pairings.delete(i2, a3.getSdkError("USER_DISCONNECTED")), this.core.crypto.deleteSymKey(i2), s2 ? Promise.resolve() : this.core.expirer.del(i2)]); - }, this.cleanup = async () => { - const i2 = this.pairings.getAll().filter((s2) => a3.isExpired(s2.expiry)); - await Promise.all(i2.map((s2) => this.deletePairing(s2.topic))); - }, this.onRelayEventRequest = (i2) => { - const { topic: s2, payload: r } = i2; - switch (r.method) { - case "wc_pairingPing": - return this.onPairingPingRequest(s2, r); - case "wc_pairingDelete": - return this.onPairingDeleteRequest(s2, r); - default: - return this.onUnknownRpcMethodRequest(s2, r); - } - }, this.onRelayEventResponse = async (i2) => { - const { topic: s2, payload: r } = i2, o2 = (await this.core.history.get(s2, r.id)).request.method; - switch (o2) { - case "wc_pairingPing": - return this.onPairingPingResponse(s2, r); - default: - return this.onUnknownRpcMethodResponse(o2); - } - }, this.onPairingPingRequest = async (i2, s2) => { - const { id: r } = s2; - try { - this.isValidPing({ topic: i2 }), await this.sendResult(r, i2, true), this.events.emit(K2.ping, { id: r, topic: i2 }); - } catch (o2) { - await this.sendError(r, i2, o2), this.logger.error(o2); - } - }, this.onPairingPingResponse = (i2, s2) => { - const { id: r } = s2; - setTimeout(() => { - f4.isJsonRpcResult(s2) ? this.events.emit(a3.engineEvent("pairing_ping", r), {}) : f4.isJsonRpcError(s2) && this.events.emit(a3.engineEvent("pairing_ping", r), { error: s2.error }); - }, 500); - }, this.onPairingDeleteRequest = async (i2, s2) => { - const { id: r } = s2; - try { - this.isValidDisconnect({ topic: i2 }), await this.deletePairing(i2), this.events.emit(K2.delete, { id: r, topic: i2 }); - } catch (o2) { - await this.sendError(r, i2, o2), this.logger.error(o2); - } - }, this.onUnknownRpcMethodRequest = async (i2, s2) => { - const { id: r, method: o2 } = s2; - try { - if (this.registeredMethods.includes(o2)) - return; - const h5 = a3.getSdkError("WC_METHOD_UNSUPPORTED", o2); - await this.sendError(r, i2, h5), this.logger.error(h5); - } catch (h5) { - await this.sendError(r, i2, h5), this.logger.error(h5); - } - }, this.onUnknownRpcMethodResponse = (i2) => { - this.registeredMethods.includes(i2) || this.logger.error(a3.getSdkError("WC_METHOD_UNSUPPORTED", i2)); - }, this.isValidPair = (i2) => { - var s2; - if (!a3.isValidParams(i2)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() params: ${i2}`); - throw new Error(o2); - } - if (!a3.isValidUrl(i2.uri)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", `pair() uri: ${i2.uri}`); - throw new Error(o2); - } - const r = a3.parseUri(i2.uri); - if (!((s2 = r?.relay) != null && s2.protocol)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#relay-protocol"); - throw new Error(o2); - } - if (!(r != null && r.symKey)) { - const { message: o2 } = a3.getInternalError("MISSING_OR_INVALID", "pair() uri#symKey"); - throw new Error(o2); - } - if (r != null && r.expiryTimestamp && l4.toMiliseconds(r?.expiryTimestamp) < Date.now()) { - const { message: o2 } = a3.getInternalError("EXPIRED", "pair() URI has expired. Please try again with a new connection URI."); - throw new Error(o2); - } - }, this.isValidPing = async (i2) => { - if (!a3.isValidParams(i2)) { - const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `ping() params: ${i2}`); - throw new Error(r); - } - const { topic: s2 } = i2; - await this.isValidPairingTopic(s2); - }, this.isValidDisconnect = async (i2) => { - if (!a3.isValidParams(i2)) { - const { message: r } = a3.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${i2}`); - throw new Error(r); - } - const { topic: s2 } = i2; - await this.isValidPairingTopic(s2); - }, this.isValidPairingTopic = async (i2) => { - if (!a3.isValidString(i2, false)) { - const { message: s2 } = a3.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${i2}`); - throw new Error(s2); - } - if (!this.pairings.keys.includes(i2)) { - const { message: s2 } = a3.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${i2}`); - throw new Error(s2); - } - if (a3.isExpired(this.pairings.get(i2).expiry)) { - await this.deletePairing(i2); - const { message: s2 } = a3.getInternalError("EXPIRED", `pairing topic: ${i2}`); - throw new Error(s2); - } - }, this.core = e2, this.logger = g3.generateChildLogger(t, this.name), this.pairings = new pt(this.core, this.logger, this.name, this.storagePrefix); - } - get context() { - return g3.getLoggerContext(this.logger); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - registerRelayerEvents() { - this.core.relayer.on(I2.message, async (e2) => { - const { topic: t, message: i2 } = e2; - if (!this.pairings.keys.includes(t) || this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i2))) - return; - const s2 = await this.core.crypto.decode(t, i2); - try { - f4.isJsonRpcRequest(s2) ? (this.core.history.set(t, s2), this.onRelayEventRequest({ topic: t, payload: s2 })) : f4.isJsonRpcResponse(s2) && (await this.core.history.resolve(s2), await this.onRelayEventResponse({ topic: t, payload: s2 }), this.core.history.delete(t, s2.id)); - } catch (r) { - this.logger.error(r); - } - }); - } - registerExpirerEvents() { - this.core.expirer.on(_4.expired, async (e2) => { - const { topic: t } = a3.parseExpirerTarget(e2.target); - t && this.pairings.keys.includes(t) && (await this.deletePairing(t, true), this.events.emit(K2.expire, { topic: t })); - }); - } - }; - var yt = class extends x3.IJsonRpcHistory { - constructor(e2, t) { - super(e2, t), this.core = e2, this.logger = t, this.records = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = Xe, this.version = Je, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.records.set(i2.id, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); - }, this.set = (i2, s2, r) => { - if (this.isInitialized(), this.logger.debug("Setting JSON-RPC request history record"), this.logger.trace({ type: "method", method: "set", topic: i2, request: s2, chainId: r }), this.records.has(s2.id)) - return; - const o2 = { id: s2.id, topic: i2, request: { method: s2.method, params: s2.params || null }, chainId: r, expiry: a3.calcExpiry(l4.THIRTY_DAYS) }; - this.records.set(o2.id, o2), this.persist(), this.events.emit(R2.created, o2); - }, this.resolve = async (i2) => { - if (this.isInitialized(), this.logger.debug("Updating JSON-RPC response history record"), this.logger.trace({ type: "method", method: "update", response: i2 }), !this.records.has(i2.id)) - return; - const s2 = await this.getRecord(i2.id); - typeof s2.response > "u" && (s2.response = f4.isJsonRpcError(i2) ? { error: i2.error } : { result: i2.result }, this.records.set(s2.id, s2), this.persist(), this.events.emit(R2.updated, s2)); - }, this.get = async (i2, s2) => (this.isInitialized(), this.logger.debug("Getting record"), this.logger.trace({ type: "method", method: "get", topic: i2, id: s2 }), await this.getRecord(s2)), this.delete = (i2, s2) => { - this.isInitialized(), this.logger.debug("Deleting record"), this.logger.trace({ type: "method", method: "delete", id: s2 }), this.values.forEach((r) => { - if (r.topic === i2) { - if (typeof s2 < "u" && r.id !== s2) - return; - this.records.delete(r.id), this.events.emit(R2.deleted, r); - } - }), this.persist(); - }, this.exists = async (i2, s2) => (this.isInitialized(), this.records.has(s2) ? (await this.getRecord(s2)).topic === i2 : false), this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.logger = g3.generateChildLogger(t, this.name); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - get size() { - return this.records.size; - } - get keys() { - return Array.from(this.records.keys()); - } - get values() { - return Array.from(this.records.values()); - } - get pending() { - const e2 = []; - return this.values.forEach((t) => { - if (typeof t.response < "u") - return; - const i2 = { topic: t.topic, request: f4.formatJsonRpcRequest(t.request.method, t.request.params, t.id), chainId: t.chainId }; - return e2.push(i2); - }), e2; - } - async setJsonRpcRecords(e2) { - await this.core.storage.setItem(this.storageKey, e2); - } - async getJsonRpcRecords() { - return await this.core.storage.getItem(this.storageKey); - } - getRecord(e2) { - this.isInitialized(); - const t = this.records.get(e2); - if (!t) { - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw new Error(i2); - } - return t; - } - async persist() { - await this.setJsonRpcRecords(this.values), this.events.emit(R2.sync); - } - async restore() { - try { - const e2 = await this.getJsonRpcRecords(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.records.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", records: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(e2); - } - } - registerEventListeners() { - this.events.on(R2.created, (e2) => { - const t = R2.created; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); - }), this.events.on(R2.updated, (e2) => { - const t = R2.updated; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); - }), this.events.on(R2.deleted, (e2) => { - const t = R2.deleted; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); - }), this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => { - this.cleanup(); - }); - } - cleanup() { - try { - this.isInitialized(); - let e2 = false; - this.records.forEach((t) => { - l4.toMiliseconds(t.expiry || 0) - Date.now() <= 0 && (this.logger.info(`Deleting expired history log: ${t.id}`), this.records.delete(t.id), this.events.emit(R2.deleted, t, false), e2 = true); - }), e2 && this.persist(); - } catch (e2) { - this.logger.warn(e2); - } - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var Et = class extends x3.IExpirer { - constructor(e2, t) { - super(e2, t), this.core = e2, this.logger = t, this.expirations = /* @__PURE__ */ new Map(), this.events = new z3.EventEmitter(), this.name = We, this.version = Qe, this.cached = [], this.initialized = false, this.storagePrefix = L2, this.init = async () => { - this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((i2) => this.expirations.set(i2.target, i2)), this.cached = [], this.registerEventListeners(), this.initialized = true); - }, this.has = (i2) => { - try { - const s2 = this.formatTarget(i2); - return typeof this.getExpiration(s2) < "u"; - } catch { - return false; - } - }, this.set = (i2, s2) => { - this.isInitialized(); - const r = this.formatTarget(i2), o2 = { target: r, expiry: s2 }; - this.expirations.set(r, o2), this.checkExpiry(r, o2), this.events.emit(_4.created, { target: r, expiration: o2 }); - }, this.get = (i2) => { - this.isInitialized(); - const s2 = this.formatTarget(i2); - return this.getExpiration(s2); - }, this.del = (i2) => { - if (this.isInitialized(), this.has(i2)) { - const s2 = this.formatTarget(i2), r = this.getExpiration(s2); - this.expirations.delete(s2), this.events.emit(_4.deleted, { target: s2, expiration: r }); - } - }, this.on = (i2, s2) => { - this.events.on(i2, s2); - }, this.once = (i2, s2) => { - this.events.once(i2, s2); - }, this.off = (i2, s2) => { - this.events.off(i2, s2); - }, this.removeListener = (i2, s2) => { - this.events.removeListener(i2, s2); - }, this.logger = g3.generateChildLogger(t, this.name); - } - get context() { - return g3.getLoggerContext(this.logger); - } - get storageKey() { - return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; - } - get length() { - return this.expirations.size; - } - get keys() { - return Array.from(this.expirations.keys()); - } - get values() { - return Array.from(this.expirations.values()); - } - formatTarget(e2) { - if (typeof e2 == "string") - return a3.formatTopicTarget(e2); - if (typeof e2 == "number") - return a3.formatIdTarget(e2); - const { message: t } = a3.getInternalError("UNKNOWN_TYPE", `Target type: ${typeof e2}`); - throw new Error(t); - } - async setExpirations(e2) { - await this.core.storage.setItem(this.storageKey, e2); - } - async getExpirations() { - return await this.core.storage.getItem(this.storageKey); - } - async persist() { - await this.setExpirations(this.values), this.events.emit(_4.sync); - } - async restore() { - try { - const e2 = await this.getExpirations(); - if (typeof e2 > "u" || !e2.length) - return; - if (this.expirations.size) { - const { message: t } = a3.getInternalError("RESTORE_WILL_OVERRIDE", this.name); - throw this.logger.error(t), new Error(t); - } - this.cached = e2, this.logger.debug(`Successfully Restored expirations for ${this.name}`), this.logger.trace({ type: "method", method: "restore", expirations: this.values }); - } catch (e2) { - this.logger.debug(`Failed to Restore expirations for ${this.name}`), this.logger.error(e2); - } - } - getExpiration(e2) { - const t = this.expirations.get(e2); - if (!t) { - const { message: i2 } = a3.getInternalError("NO_MATCHING_KEY", `${this.name}: ${e2}`); - throw this.logger.warn(i2), new Error(i2); - } - return t; - } - checkExpiry(e2, t) { - const { expiry: i2 } = t; - l4.toMiliseconds(i2) - Date.now() <= 0 && this.expire(e2, t); - } - expire(e2, t) { - this.expirations.delete(e2), this.events.emit(_4.expired, { target: e2, expiration: t }); - } - checkExpirations() { - this.core.relayer.connected && this.expirations.forEach((e2, t) => this.checkExpiry(t, e2)); - } - registerEventListeners() { - this.core.heartbeat.on($.HEARTBEAT_EVENTS.pulse, () => this.checkExpirations()), this.events.on(_4.created, (e2) => { - const t = _4.created; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); - }), this.events.on(_4.expired, (e2) => { - const t = _4.expired; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); - }), this.events.on(_4.deleted, (e2) => { - const t = _4.deleted; - this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); - }); - } - isInitialized() { - if (!this.initialized) { - const { message: e2 } = a3.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(e2); - } - } - }; - var mt = class extends x3.IVerify { - constructor(e2, t) { - super(e2, t), this.projectId = e2, this.logger = t, this.name = X, this.initialized = false, this.queue = [], this.verifyDisabled = false, this.init = async (i2) => { - if (this.verifyDisabled || a3.isReactNative() || !a3.isBrowser()) - return; - const s2 = this.getVerifyUrl(i2?.verifyUrl); - this.verifyUrl !== s2 && this.removeIframe(), this.verifyUrl = s2; - try { - await this.createIframe(); - } catch (r) { - this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r); - } - if (!this.initialized) { - this.removeIframe(), this.verifyUrl = J; - try { - await this.createIframe(); - } catch (r) { - this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`), this.logger.info(r), this.verifyDisabled = true; - } - } - }, this.register = async (i2) => { - this.initialized ? this.sendPost(i2.attestationId) : (this.addToQueue(i2.attestationId), await this.init()); - }, this.resolve = async (i2) => { - if (this.isDevEnv) - return ""; - const s2 = this.getVerifyUrl(i2?.verifyUrl); - let r; - try { - r = await this.fetchAttestation(i2.attestationId, s2); - } catch (o2) { - this.logger.info(`failed to resolve attestation: ${i2.attestationId} from url: ${s2}`), this.logger.info(o2), r = await this.fetchAttestation(i2.attestationId, J); - } - return r; - }, this.fetchAttestation = async (i2, s2) => { - this.logger.info(`resolving attestation: ${i2} from url: ${s2}`); - const r = this.startAbortTimer(l4.ONE_SECOND * 2), o2 = await fetch(`${s2}/attestation/${i2}`, { signal: this.abortController.signal }); - return clearTimeout(r), o2.status === 200 ? await o2.json() : void 0; - }, this.addToQueue = (i2) => { - this.queue.push(i2); - }, this.processQueue = () => { - this.queue.length !== 0 && (this.queue.forEach((i2) => this.sendPost(i2)), this.queue = []); - }, this.sendPost = (i2) => { - var s2; - try { - if (!this.iframe) - return; - (s2 = this.iframe.contentWindow) == null || s2.postMessage(i2, "*"), this.logger.info(`postMessage sent: ${i2} ${this.verifyUrl}`); - } catch { - } - }, this.createIframe = async () => { - let i2; - const s2 = (r) => { - r.data === "verify_ready" && (this.onInit(), window.removeEventListener("message", s2), i2()); - }; - await Promise.race([new Promise((r) => { - const o2 = document.getElementById(X); - if (o2) - return this.iframe = o2, this.onInit(), r(); - window.addEventListener("message", s2); - const h5 = document.createElement("iframe"); - h5.id = X, h5.src = `${this.verifyUrl}/${this.projectId}`, h5.style.display = "none", document.body.append(h5), this.iframe = h5, i2 = r; - }), new Promise((r, o2) => setTimeout(() => { - window.removeEventListener("message", s2), o2("verify iframe load timeout"); - }, l4.toMiliseconds(l4.FIVE_SECONDS)))]); - }, this.onInit = () => { - this.initialized = true, this.processQueue(); - }, this.removeIframe = () => { - this.iframe && (this.iframe.remove(), this.iframe = void 0, this.initialized = false); - }, this.getVerifyUrl = (i2) => { - let s2 = i2 || B2; - return Ze.includes(s2) || (this.logger.info(`verify url: ${s2}, not included in trusted list, assigning default: ${B2}`), s2 = B2), s2; - }, this.logger = g3.generateChildLogger(t, this.name), this.verifyUrl = B2, this.abortController = new AbortController(), this.isDevEnv = a3.isNode() && import_process.default.env.IS_VITEST; - } - get context() { - return g3.getLoggerContext(this.logger); - } - startAbortTimer(e2) { - return this.abortController = new AbortController(), setTimeout(() => this.abortController.abort(), l4.toMiliseconds(e2)); - } - }; - var bt = class extends x3.IEchoClient { - constructor(e2, t) { - super(e2, t), this.projectId = e2, this.logger = t, this.context = et, this.registerDeviceToken = async (i2) => { - const { clientId: s2, token: r, notificationType: o2, enableEncrypted: h5 = false } = i2, c4 = `${tt}/${this.projectId}/clients`; - await Ut.default(c4, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: s2, type: o2, token: r, always_raw: h5 }) }); - }, this.logger = g3.generateChildLogger(t, this.context); - } - }; - var Rs = Object.defineProperty; - var ft = Object.getOwnPropertySymbols; - var _s = Object.prototype.hasOwnProperty; - var Cs = Object.prototype.propertyIsEnumerable; - var wt = (n3, e2, t) => e2 in n3 ? Rs(n3, e2, { enumerable: true, configurable: true, writable: true, value: t }) : n3[e2] = t; - var vt = (n3, e2) => { - for (var t in e2 || (e2 = {})) - _s.call(e2, t) && wt(n3, t, e2[t]); - if (ft) - for (var t of ft(e2)) - Cs.call(e2, t) && wt(n3, t, e2[t]); - return n3; - }; - var W = class _W extends x3.ICore { - constructor(e2) { - var t; - super(e2), this.protocol = te, this.version = Re, this.name = H, this.events = new z3.EventEmitter(), this.initialized = false, this.on = (o2, h5) => this.events.on(o2, h5), this.once = (o2, h5) => this.events.once(o2, h5), this.off = (o2, h5) => this.events.off(o2, h5), this.removeListener = (o2, h5) => this.events.removeListener(o2, h5), this.projectId = e2?.projectId, this.relayUrl = e2?.relayUrl || se, this.customStoragePrefix = e2 != null && e2.customStoragePrefix ? `:${e2.customStoragePrefix}` : ""; - const i2 = g3.getDefaultLoggerOptions({ level: typeof e2?.logger == "string" && e2.logger ? e2.logger : _e.logger }), { logger: s2, chunkLoggerController: r } = g3.generatePlatformLogger({ opts: i2, maxSizeInBytes: e2?.maxLogBlobSizeInBytes, loggerOverride: e2?.logger }); - this.logChunkController = r, (t = this.logChunkController) != null && t.downloadLogsBlobInBrowser && (window.downloadLogsBlobInBrowser = async () => { - var o2, h5; - (o2 = this.logChunkController) != null && o2.downloadLogsBlobInBrowser && ((h5 = this.logChunkController) == null || h5.downloadLogsBlobInBrowser({ clientId: await this.crypto.getClientId() })); - }), this.logger = g3.generateChildLogger(s2, this.name), this.heartbeat = new $.HeartBeat(), this.crypto = new st(this, this.logger, e2?.keychain), this.history = new yt(this, this.logger), this.expirer = new Et(this, this.logger), this.storage = e2 != null && e2.storage ? e2.storage : new xt.default(vt(vt({}, Ce), e2?.storageOptions)), this.relayer = new lt({ core: this, logger: this.logger, relayUrl: this.relayUrl, projectId: this.projectId }), this.pairing = new Dt(this, this.logger), this.verify = new mt(this.projectId || "", this.logger), this.echoClient = new bt(this.projectId || "", this.logger); - } - static async init(e2) { - const t = new _W(e2); - await t.initialize(); - const i2 = await t.crypto.getClientId(); - return await t.storage.setItem(Ke, i2), t; - } - get context() { - return g3.getLoggerContext(this.logger); - } - async start() { - this.initialized || await this.initialize(); - } - async getLogsBlob() { - var e2; - return (e2 = this.logChunkController) == null ? void 0 : e2.logsToBlob({ clientId: await this.crypto.getClientId() }); - } - async initialize() { - this.logger.trace("Initialized"); - try { - await this.crypto.init(), await this.history.init(), await this.expirer.init(), await this.relayer.init(), await this.heartbeat.init(), await this.pairing.init(), this.initialized = true, this.logger.info("Core Initialization Success"); - } catch (e2) { - throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`, e2), this.logger.error(e2.message), e2; - } - } - }; - var Ts = W; - exports2.CORE_CONTEXT = H, exports2.CORE_DEFAULT = _e, exports2.CORE_PROTOCOL = te, exports2.CORE_STORAGE_OPTIONS = Ce, exports2.CORE_STORAGE_PREFIX = L2, exports2.CORE_VERSION = Re, exports2.CRYPTO_CLIENT_SEED = ie, exports2.CRYPTO_CONTEXT = Te, exports2.CRYPTO_JWT_TTL = Se, exports2.Core = Ts, exports2.Crypto = st, exports2.ECHO_CONTEXT = et, exports2.ECHO_URL = tt, exports2.EXPIRER_CONTEXT = We, exports2.EXPIRER_DEFAULT_TTL = cs, exports2.EXPIRER_EVENTS = _4, exports2.EXPIRER_STORAGE_VERSION = Qe, exports2.EchoClient = bt, exports2.Expirer = Et, exports2.HISTORY_CONTEXT = Xe, exports2.HISTORY_EVENTS = R2, exports2.HISTORY_STORAGE_VERSION = Je, exports2.JsonRpcHistory = yt, exports2.KEYCHAIN_CONTEXT = Oe, exports2.KEYCHAIN_STORAGE_VERSION = Pe, exports2.KeyChain = it, exports2.MESSAGES_CONTEXT = Ae, exports2.MESSAGES_STORAGE_VERSION = xe, exports2.MessageTracker = rt, exports2.PAIRING_CONTEXT = Ge, exports2.PAIRING_DEFAULT_TTL = hs, exports2.PAIRING_EVENTS = K2, exports2.PAIRING_RPC_OPTS = M, exports2.PAIRING_STORAGE_VERSION = He, exports2.PENDING_SUB_RESOLUTION_TIMEOUT = je, exports2.PUBLISHER_CONTEXT = Le, exports2.PUBLISHER_DEFAULT_TTL = Ne, exports2.Pairing = Dt, exports2.RELAYER_CONTEXT = Fe, exports2.RELAYER_DEFAULT_LOGGER = ze, exports2.RELAYER_DEFAULT_PROTOCOL = Ue, exports2.RELAYER_DEFAULT_RELAY_URL = se, exports2.RELAYER_EVENTS = I2, exports2.RELAYER_FAILOVER_RELAY_URL = re, exports2.RELAYER_PROVIDER_EVENTS = w4, exports2.RELAYER_RECONNECT_TIMEOUT = Be, exports2.RELAYER_SDK_VERSION = $e, exports2.RELAYER_STORAGE_OPTIONS = os, exports2.RELAYER_SUBSCRIBER_SUFFIX = Me, exports2.RELAYER_TRANSPORT_CUTOFF = ke, exports2.Relayer = lt, exports2.STORE_STORAGE_VERSION = Ve, exports2.SUBSCRIBER_CONTEXT = qe, exports2.SUBSCRIBER_DEFAULT_TTL = as, exports2.SUBSCRIBER_EVENTS = S4, exports2.SUBSCRIBER_STORAGE_VERSION = Ye, exports2.Store = pt, exports2.Subscriber = at, exports2.TRUSTED_VERIFY_URLS = Ze, exports2.VERIFY_CONTEXT = X, exports2.VERIFY_FALLBACK_SERVER = J, exports2.VERIFY_SERVER = B2, exports2.Verify = mt, exports2.WALLETCONNECT_CLIENT_ID = Ke, exports2.default = W; - } -}); - -// node_modules/@walletconnect/sign-client/dist/index.cjs.js -var require_index_cjs4 = __commonJS({ - "node_modules/@walletconnect/sign-client/dist/index.cjs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - var N10 = require_index_cjs3(); - var k4 = (init_index_es2(), __toCommonJS(index_es_exports2)); - var oe = require_index_cjs(); - var s2 = require_index_cjs2(); - var ae = require_events(); - var w4 = require_cjs(); - var u3 = (init_esm5(), __toCommonJS(esm_exports4)); - function fe(y4) { - return y4 && typeof y4 == "object" && "default" in y4 ? y4 : { default: y4 }; - } - var qe = fe(ae); - var ee = "wc"; - var te = 2; - var ie = "client"; - var F = `${ee}@${te}:${ie}:`; - var Y = { name: ie, logger: "error", controller: false, relayUrl: "wss://relay.walletconnect.com" }; - var Pe = { session_proposal: "session_proposal", session_update: "session_update", session_extend: "session_extend", session_ping: "session_ping", session_delete: "session_delete", session_expire: "session_expire", session_request: "session_request", session_request_sent: "session_request_sent", session_event: "session_event", proposal_expire: "proposal_expire", session_authenticate: "session_authenticate", session_request_expire: "session_request_expire" }; - var Te = { database: ":memory:" }; - var se = "WALLETCONNECT_DEEPLINK_CHOICE"; - var ve = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; - var Oe = "history"; - var Ae = "0.3"; - var ce = "proposal"; - var Ve = w4.THIRTY_DAYS; - var le = "Proposal expired"; - var he = "session"; - var V = w4.SEVEN_DAYS; - var pe = "engine"; - var q2 = { wc_sessionPropose: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1100 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1101 } }, wc_sessionSettle: { req: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1102 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1103 } }, wc_sessionUpdate: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1104 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1105 } }, wc_sessionExtend: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1106 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1107 } }, wc_sessionRequest: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1108 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1109 } }, wc_sessionEvent: { req: { ttl: w4.FIVE_MINUTES, prompt: true, tag: 1110 }, res: { ttl: w4.FIVE_MINUTES, prompt: false, tag: 1111 } }, wc_sessionDelete: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1112 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1113 } }, wc_sessionPing: { req: { ttl: w4.ONE_DAY, prompt: false, tag: 1114 }, res: { ttl: w4.ONE_DAY, prompt: false, tag: 1115 } }, wc_sessionAuthenticate: { req: { ttl: w4.ONE_HOUR, prompt: true, tag: 1116 }, res: { ttl: w4.ONE_HOUR, prompt: false, tag: 1117 } } }; - var H = { min: w4.FIVE_MINUTES, max: w4.SEVEN_DAYS }; - var A2 = { idle: "IDLE", active: "ACTIVE" }; - var de = "request"; - var ue = ["wc_sessionPropose", "wc_sessionRequest", "wc_authRequest"]; - var ge = "wc"; - var De = 1.5; - var Ee = "auth"; - var we = "authKeys"; - var ye = "pairingTopics"; - var me = "requests"; - var L2 = `${ge}@${1.5}:${Ee}:`; - var U2 = `${L2}:PUB_KEY`; - var Ce = Object.defineProperty; - var xe = Object.defineProperties; - var be = Object.getOwnPropertyDescriptors; - var Se = Object.getOwnPropertySymbols; - var Me = Object.prototype.hasOwnProperty; - var Le = Object.prototype.propertyIsEnumerable; - var Ie = (y4, o2, t) => o2 in y4 ? Ce(y4, o2, { enumerable: true, configurable: true, writable: true, value: t }) : y4[o2] = t; - var S4 = (y4, o2) => { - for (var t in o2 || (o2 = {})) - Me.call(o2, t) && Ie(y4, t, o2[t]); - if (Se) - for (var t of Se(o2)) - Le.call(o2, t) && Ie(y4, t, o2[t]); - return y4; - }; - var C3 = (y4, o2) => xe(y4, be(o2)); - var Ue = class extends oe.IEngine { - constructor(o2) { - super(o2), this.name = pe, this.events = new qe.default(), this.initialized = false, this.requestQueue = { state: A2.idle, queue: [] }, this.sessionRequestQueue = { state: A2.idle, queue: [] }, this.requestQueueDelay = w4.ONE_SECOND, this.expectedPairingMethodMap = /* @__PURE__ */ new Map(), this.recentlyDeletedMap = /* @__PURE__ */ new Map(), this.recentlyDeletedLimit = 200, this.init = async () => { - this.initialized || (await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.registerPairingEvents(), this.client.core.pairing.register({ methods: Object.keys(q2) }), this.initialized = true, setTimeout(() => { - this.sessionRequestQueue.queue = this.getPendingSessionRequests(), this.processSessionRequestQueue(); - }, w4.toMiliseconds(this.requestQueueDelay))); - }, this.connect = async (t) => { - await this.isInitialized(); - const e2 = C3(S4({}, t), { requiredNamespaces: t.requiredNamespaces || {}, optionalNamespaces: t.optionalNamespaces || {} }); - await this.isValidConnect(e2); - const { pairingTopic: i2, requiredNamespaces: r, optionalNamespaces: n3, sessionProperties: a3, relays: c4 } = e2; - let l4 = i2, d3, p3 = false; - try { - l4 && (p3 = this.client.core.pairing.pairings.get(l4).active); - } catch (f4) { - throw this.client.logger.error(`connect() -> pairing.get(${l4}) failed`), f4; - } - if (!l4 || !p3) { - const { topic: f4, uri: T2 } = await this.client.core.pairing.create(); - l4 = f4, d3 = T2; - } - if (!l4) { - const { message: f4 } = s2.getInternalError("NO_MATCHING_KEY", `connect() pairing topic: ${l4}`); - throw new Error(f4); - } - const g3 = await this.client.core.crypto.generateKeyPair(), h5 = q2.wc_sessionPropose.req.ttl || w4.FIVE_MINUTES, m3 = s2.calcExpiry(h5), E4 = S4({ requiredNamespaces: r, optionalNamespaces: n3, relays: c4 ?? [{ protocol: N10.RELAYER_DEFAULT_PROTOCOL }], proposer: { publicKey: g3, metadata: this.client.metadata }, expiryTimestamp: m3 }, a3 && { sessionProperties: a3 }), { reject: R2, resolve: O3, done: I2 } = s2.createDelayedPromise(h5, le); - this.events.once(s2.engineEvent("session_connect"), async ({ error: f4, session: T2 }) => { - if (f4) - R2(f4); - else if (T2) { - T2.self.publicKey = g3; - const x3 = C3(S4({}, T2), { requiredNamespaces: E4.requiredNamespaces, optionalNamespaces: E4.optionalNamespaces }); - await this.client.session.set(T2.topic, x3), await this.setExpiry(T2.topic, T2.expiry), l4 && await this.client.core.pairing.updateMetadata({ topic: l4, metadata: T2.peer.metadata }), O3(x3); - } - }); - const P2 = await this.sendRequest({ topic: l4, method: "wc_sessionPropose", params: E4, throwOnFailedPublish: true }); - return await this.setProposal(P2, S4({ id: P2 }, E4)), { uri: d3, approval: I2 }; - }, this.pair = async (t) => { - await this.isInitialized(); - try { - return await this.client.core.pairing.pair(t); - } catch (e2) { - throw this.client.logger.error("pair() failed"), e2; - } - }, this.approve = async (t) => { - await this.isInitialized(); - try { - await this.isValidApprove(t); - } catch (I2) { - throw this.client.logger.error("approve() -> isValidApprove() failed"), I2; - } - const { id: e2, relayProtocol: i2, namespaces: r, sessionProperties: n3, sessionConfig: a3 } = t; - let c4; - try { - c4 = this.client.proposal.get(e2); - } catch (I2) { - throw this.client.logger.error(`approve() -> proposal.get(${e2}) failed`), I2; - } - let { pairingTopic: l4, proposer: d3, requiredNamespaces: p3, optionalNamespaces: g3 } = c4; - l4 = l4 || ""; - const h5 = await this.client.core.crypto.generateKeyPair(), m3 = d3.publicKey, E4 = await this.client.core.crypto.generateSharedKey(h5, m3), R2 = S4(S4({ relay: { protocol: i2 ?? "irn" }, namespaces: r, pairingTopic: l4, controller: { publicKey: h5, metadata: this.client.metadata }, expiry: s2.calcExpiry(V) }, n3 && { sessionProperties: n3 }), a3 && { sessionConfig: a3 }); - await this.client.core.relayer.subscribe(E4); - const O3 = C3(S4({}, R2), { topic: E4, requiredNamespaces: p3, optionalNamespaces: g3, pairingTopic: l4, acknowledged: false, self: R2.controller, peer: { publicKey: d3.publicKey, metadata: d3.metadata }, controller: h5 }); - await this.client.session.set(E4, O3); - try { - await this.sendResult({ id: e2, topic: l4, result: { relay: { protocol: i2 ?? "irn" }, responderPublicKey: h5 }, throwOnFailedPublish: true }), await this.sendRequest({ topic: E4, method: "wc_sessionSettle", params: R2, throwOnFailedPublish: true }); - } catch (I2) { - throw this.client.logger.error(I2), this.client.session.delete(E4, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.relayer.unsubscribe(E4), I2; - } - return await this.client.core.pairing.updateMetadata({ topic: l4, metadata: d3.metadata }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")), await this.client.core.pairing.activate({ topic: l4 }), await this.setExpiry(E4, s2.calcExpiry(V)), { topic: E4, acknowledged: () => new Promise((I2) => setTimeout(() => I2(this.client.session.get(E4)), 500)) }; - }, this.reject = async (t) => { - await this.isInitialized(); - try { - await this.isValidReject(t); - } catch (n3) { - throw this.client.logger.error("reject() -> isValidReject() failed"), n3; - } - const { id: e2, reason: i2 } = t; - let r; - try { - r = this.client.proposal.get(e2).pairingTopic; - } catch (n3) { - throw this.client.logger.error(`reject() -> proposal.get(${e2}) failed`), n3; - } - r && (await this.sendError({ id: e2, topic: r, error: i2 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED"))); - }, this.update = async (t) => { - await this.isInitialized(); - try { - await this.isValidUpdate(t); - } catch (p3) { - throw this.client.logger.error("update() -> isValidUpdate() failed"), p3; - } - const { topic: e2, namespaces: i2 } = t, { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), d3 = this.client.session.get(e2).namespaces; - return this.events.once(s2.engineEvent("session_update", c4), ({ error: p3 }) => { - p3 ? a3(p3) : n3(); - }), await this.client.session.update(e2, { namespaces: i2 }), this.sendRequest({ topic: e2, method: "wc_sessionUpdate", params: { namespaces: i2 }, throwOnFailedPublish: true, clientRpcId: c4, relayRpcId: l4 }).catch((p3) => { - this.client.logger.error(p3), this.client.session.update(e2, { namespaces: d3 }), a3(p3); - }), { acknowledged: r }; - }, this.extend = async (t) => { - await this.isInitialized(); - try { - await this.isValidExtend(t); - } catch (c4) { - throw this.client.logger.error("extend() -> isValidExtend() failed"), c4; - } - const { topic: e2 } = t, i2 = u3.payloadId(), { done: r, resolve: n3, reject: a3 } = s2.createDelayedPromise(); - return this.events.once(s2.engineEvent("session_extend", i2), ({ error: c4 }) => { - c4 ? a3(c4) : n3(); - }), await this.setExpiry(e2, s2.calcExpiry(V)), this.sendRequest({ topic: e2, method: "wc_sessionExtend", params: {}, clientRpcId: i2, throwOnFailedPublish: true }).catch((c4) => { - a3(c4); - }), { acknowledged: r }; - }, this.request = async (t) => { - await this.isInitialized(); - try { - await this.isValidRequest(t); - } catch (h5) { - throw this.client.logger.error("request() -> isValidRequest() failed"), h5; - } - const { chainId: e2, request: i2, topic: r, expiry: n3 = q2.wc_sessionRequest.req.ttl } = t, a3 = this.client.session.get(r), c4 = u3.payloadId(), l4 = u3.getBigIntRpcId().toString(), { done: d3, resolve: p3, reject: g3 } = s2.createDelayedPromise(n3, "Request expired. Please try again."); - return this.events.once(s2.engineEvent("session_request", c4), ({ error: h5, result: m3 }) => { - h5 ? g3(h5) : p3(m3); - }), await Promise.all([new Promise(async (h5) => { - await this.sendRequest({ clientRpcId: c4, relayRpcId: l4, topic: r, method: "wc_sessionRequest", params: { request: C3(S4({}, i2), { expiryTimestamp: s2.calcExpiry(n3) }), chainId: e2 }, expiry: n3, throwOnFailedPublish: true }).catch((m3) => g3(m3)), this.client.events.emit("session_request_sent", { topic: r, request: i2, chainId: e2, id: c4 }), h5(); - }), new Promise(async (h5) => { - var m3; - if (!((m3 = a3.sessionConfig) != null && m3.disableDeepLink)) { - const E4 = await s2.getDeepLink(this.client.core.storage, se); - s2.handleDeeplinkRedirect({ id: c4, topic: r, wcDeepLink: E4 }); - } - h5(); - }), d3()]).then((h5) => h5[2]); - }, this.respond = async (t) => { - await this.isInitialized(), await this.isValidRespond(t); - const { topic: e2, response: i2 } = t, { id: r } = i2; - u3.isJsonRpcResult(i2) ? await this.sendResult({ id: r, topic: e2, result: i2.result, throwOnFailedPublish: true }) : u3.isJsonRpcError(i2) && await this.sendError({ id: r, topic: e2, error: i2.error }), this.cleanupAfterResponse(t); - }, this.ping = async (t) => { - await this.isInitialized(); - try { - await this.isValidPing(t); - } catch (i2) { - throw this.client.logger.error("ping() -> isValidPing() failed"), i2; - } - const { topic: e2 } = t; - if (this.client.session.keys.includes(e2)) { - const i2 = u3.payloadId(), r = u3.getBigIntRpcId().toString(), { done: n3, resolve: a3, reject: c4 } = s2.createDelayedPromise(); - this.events.once(s2.engineEvent("session_ping", i2), ({ error: l4 }) => { - l4 ? c4(l4) : a3(); - }), await Promise.all([this.sendRequest({ topic: e2, method: "wc_sessionPing", params: {}, throwOnFailedPublish: true, clientRpcId: i2, relayRpcId: r }), n3()]); - } else - this.client.core.pairing.pairings.keys.includes(e2) && await this.client.core.pairing.ping({ topic: e2 }); - }, this.emit = async (t) => { - await this.isInitialized(), await this.isValidEmit(t); - const { topic: e2, event: i2, chainId: r } = t, n3 = u3.getBigIntRpcId().toString(); - await this.sendRequest({ topic: e2, method: "wc_sessionEvent", params: { event: i2, chainId: r }, throwOnFailedPublish: true, relayRpcId: n3 }); - }, this.disconnect = async (t) => { - await this.isInitialized(), await this.isValidDisconnect(t); - const { topic: e2 } = t; - if (this.client.session.keys.includes(e2)) - await this.sendRequest({ topic: e2, method: "wc_sessionDelete", params: s2.getSdkError("USER_DISCONNECTED"), throwOnFailedPublish: true }), await this.deleteSession({ topic: e2, emitEvent: false }); - else if (this.client.core.pairing.pairings.keys.includes(e2)) - await this.client.core.pairing.disconnect({ topic: e2 }); - else { - const { message: i2 } = s2.getInternalError("MISMATCHED_TOPIC", `Session or pairing topic not found: ${e2}`); - throw new Error(i2); - } - }, this.find = (t) => (this.isInitialized(), this.client.session.getAll().filter((e2) => s2.isSessionCompatible(e2, t))), this.getPendingSessionRequests = () => this.client.pendingRequest.getAll(), this.authenticate = async (t) => { - this.isInitialized(), this.isValidAuthenticate(t); - const { chains: e2, statement: i2 = "", uri: r, domain: n3, nonce: a3, type: c4, exp: l4, nbf: d3, methods: p3 = [] } = t, g3 = [...t.resources || []], { topic: h5, uri: m3 } = await this.client.core.pairing.create({ methods: ["wc_sessionAuthenticate"] }); - this.client.logger.info({ message: "Generated new pairing", pairing: { topic: h5, uri: m3 } }); - const E4 = await this.client.core.crypto.generateKeyPair(), R2 = s2.hashKey(E4); - if (await Promise.all([this.client.auth.authKeys.set(U2, { responseTopic: R2, publicKey: E4 }), this.client.auth.pairingTopics.set(R2, { topic: R2, pairingTopic: h5 })]), await this.client.core.relayer.subscribe(R2), this.client.logger.info(`sending request to new pairing topic: ${h5}`), p3.length > 0) { - const { namespace: v2 } = s2.parseChainId(e2[0]); - let _4 = s2.createEncodedRecap(v2, "request", p3); - s2.getRecapFromResources(g3) && (_4 = s2.mergeEncodedRecaps(_4, g3.pop())), g3.push(_4); - } - const O3 = s2.calcExpiry(q2.wc_sessionPropose.req.ttl), I2 = { authPayload: { type: c4 ?? "caip122", chains: e2, statement: i2, aud: r, domain: n3, version: "1", nonce: a3, iat: (/* @__PURE__ */ new Date()).toISOString(), exp: l4, nbf: d3, resources: g3 }, requester: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, P2 = { eip155: { chains: e2, methods: [.../* @__PURE__ */ new Set(["personal_sign", ...p3])], events: ["chainChanged", "accountsChanged"] } }, f4 = { requiredNamespaces: {}, optionalNamespaces: P2, relays: [{ protocol: "irn" }], proposer: { publicKey: E4, metadata: this.client.metadata }, expiryTimestamp: O3 }, { done: T2, resolve: x3, reject: Q } = s2.createDelayedPromise(q2.wc_sessionAuthenticate.req.ttl, "Request expired"), $ = async ({ error: v2, session: _4 }) => { - if (this.events.off(s2.engineEvent("session_request", D2), X), v2) - Q(v2); - else if (_4) { - _4.self.publicKey = E4, await this.client.session.set(_4.topic, _4), await this.setExpiry(_4.topic, _4.expiry), h5 && await this.client.core.pairing.updateMetadata({ topic: h5, metadata: _4.peer.metadata }); - const b4 = this.client.session.get(_4.topic); - x3({ session: b4 }); - } - }, X = async (v2) => { - if (v2.error) { - const M = s2.getSdkError("WC_METHOD_UNSUPPORTED", "wc_sessionAuthenticate"); - return v2.error.code === M.code ? void 0 : (this.events.off(s2.engineEvent("session_connect"), $), Q(v2.error.message)); - } - this.events.off(s2.engineEvent("session_connect"), $); - const { cacaos: _4, responder: b4 } = v2.result, z3 = [], re = []; - for (const M of _4) { - await s2.validateSignedCacao({ cacao: M, projectId: this.client.core.projectId }) || (this.client.logger.error(M, "Signature verification failed"), Q(s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"))); - const { p: B2 } = M, W = s2.getRecapFromResources(B2.resources), ne = [s2.getNamespacedDidChainId(B2.iss)], Re = s2.getDidAddress(B2.iss); - if (W) { - const Z = s2.getMethodsFromRecap(W), Ne = s2.getChainsFromRecap(W); - z3.push(...Z), ne.push(...Ne); - } - for (const Z of ne) - re.push(`${Z}:${Re}`); - } - const G = await this.client.core.crypto.generateSharedKey(E4, b4.publicKey); - let K2; - z3.length > 0 && (K2 = { topic: G, acknowledged: true, self: { publicKey: E4, metadata: this.client.metadata }, peer: b4, controller: b4.publicKey, expiry: s2.calcExpiry(V), requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: h5, namespaces: s2.buildNamespacesFromAuth([...new Set(z3)], [...new Set(re)]) }, await this.client.core.relayer.subscribe(G), await this.client.session.set(G, K2), K2 = this.client.session.get(G)), x3({ auths: _4, session: K2 }); - }, D2 = u3.payloadId(), J = u3.payloadId(); - this.events.once(s2.engineEvent("session_connect"), $), this.events.once(s2.engineEvent("session_request", D2), X); - try { - await Promise.all([this.sendRequest({ topic: h5, method: "wc_sessionAuthenticate", params: I2, expiry: t.expiry, throwOnFailedPublish: true, clientRpcId: D2 }), this.sendRequest({ topic: h5, method: "wc_sessionPropose", params: f4, expiry: q2.wc_sessionPropose.req.ttl, throwOnFailedPublish: true, clientRpcId: J })]); - } catch (v2) { - throw this.events.off(s2.engineEvent("session_connect"), $), this.events.off(s2.engineEvent("session_request", D2), X), v2; - } - return await this.setProposal(J, S4({ id: J }, f4)), await this.client.auth.requests.set(D2, { authPayload: I2.authPayload, requester: I2.requester, expiryTimestamp: O3, id: D2, pairingTopic: h5, verifyContext: {} }), { uri: m3, response: T2 }; - }, this.approveSessionAuthenticate = async (t) => { - this.isInitialized(); - const { id: e2, auths: i2 } = t, r = this.getPendingAuthRequest(e2); - if (!r) - throw new Error(`Could not find pending auth request with id ${e2}`); - const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }, d3 = [], p3 = []; - for (const m3 of i2) { - if (!await s2.validateSignedCacao({ cacao: m3, projectId: this.client.core.projectId })) { - const P2 = s2.getSdkError("SESSION_SETTLEMENT_FAILED", "Signature verification failed"); - throw await this.sendError({ id: e2, topic: c4, error: P2, encodeOpts: l4 }), new Error(P2.message); - } - const { p: E4 } = m3, R2 = s2.getRecapFromResources(E4.resources), O3 = [s2.getNamespacedDidChainId(E4.iss)], I2 = s2.getDidAddress(E4.iss); - if (R2) { - const P2 = s2.getMethodsFromRecap(R2), f4 = s2.getChainsFromRecap(R2); - d3.push(...P2), O3.push(...f4); - } - for (const P2 of O3) - p3.push(`${P2}:${I2}`); - } - const g3 = await this.client.core.crypto.generateSharedKey(a3, n3); - let h5; - return d3?.length > 0 && (h5 = { topic: g3, acknowledged: true, self: { publicKey: a3, metadata: this.client.metadata }, peer: { publicKey: n3, metadata: r.requester.metadata }, controller: n3, expiry: s2.calcExpiry(V), authentication: i2, requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: "", namespaces: s2.buildNamespacesFromAuth([...new Set(d3)], [...new Set(p3)]) }, await this.client.core.relayer.subscribe(g3), await this.client.session.set(g3, h5)), await this.sendResult({ topic: c4, id: e2, result: { cacaos: i2, responder: { publicKey: a3, metadata: this.client.metadata } }, encodeOpts: l4, throwOnFailedPublish: true }), await this.client.auth.requests.delete(e2, { message: "fullfilled", code: 0 }), await this.client.core.pairing.activate({ topic: r.pairingTopic }), { session: h5 }; - }, this.rejectSessionAuthenticate = async (t) => { - await this.isInitialized(); - const { id: e2, reason: i2 } = t, r = this.getPendingAuthRequest(e2); - if (!r) - throw new Error(`Could not find pending auth request with id ${e2}`); - const n3 = r.requester.publicKey, a3 = await this.client.core.crypto.generateKeyPair(), c4 = s2.hashKey(n3), l4 = { type: s2.TYPE_1, receiverPublicKey: n3, senderPublicKey: a3 }; - await this.sendError({ id: e2, topic: c4, error: i2, encodeOpts: l4 }), await this.client.auth.requests.delete(e2, { message: "rejected", code: 0 }), await this.client.proposal.delete(e2, s2.getSdkError("USER_DISCONNECTED")); - }, this.formatAuthMessage = (t) => { - this.isInitialized(); - const { request: e2, iss: i2 } = t; - return s2.formatMessage(e2, i2); - }, this.cleanupDuplicatePairings = async (t) => { - if (t.pairingTopic) - try { - const e2 = this.client.core.pairing.pairings.get(t.pairingTopic), i2 = this.client.core.pairing.pairings.getAll().filter((r) => { - var n3, a3; - return ((n3 = r.peerMetadata) == null ? void 0 : n3.url) && ((a3 = r.peerMetadata) == null ? void 0 : a3.url) === t.peer.metadata.url && r.topic && r.topic !== e2.topic; - }); - if (i2.length === 0) - return; - this.client.logger.info(`Cleaning up ${i2.length} duplicate pairing(s)`), await Promise.all(i2.map((r) => this.client.core.pairing.disconnect({ topic: r.topic }))), this.client.logger.info("Duplicate pairings clean up finished"); - } catch (e2) { - this.client.logger.error(e2); - } - }, this.deleteSession = async (t) => { - const { topic: e2, expirerHasDeleted: i2 = false, emitEvent: r = true, id: n3 = 0 } = t, { self: a3 } = this.client.session.get(e2); - await this.client.core.relayer.unsubscribe(e2), await this.client.session.delete(e2, s2.getSdkError("USER_DISCONNECTED")), this.addToRecentlyDeleted(e2, "session"), this.client.core.crypto.keychain.has(a3.publicKey) && await this.client.core.crypto.deleteKeyPair(a3.publicKey), this.client.core.crypto.keychain.has(e2) && await this.client.core.crypto.deleteSymKey(e2), i2 || this.client.core.expirer.del(e2), this.client.core.storage.removeItem(se).catch((c4) => this.client.logger.warn(c4)), this.getPendingSessionRequests().forEach((c4) => { - c4.topic === e2 && this.deletePendingSessionRequest(c4.id, s2.getSdkError("USER_DISCONNECTED")); - }), r && this.client.events.emit("session_delete", { id: n3, topic: e2 }); - }, this.deleteProposal = async (t, e2) => { - await Promise.all([this.client.proposal.delete(t, s2.getSdkError("USER_DISCONNECTED")), e2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "proposal"); - }, this.deletePendingSessionRequest = async (t, e2, i2 = false) => { - await Promise.all([this.client.pendingRequest.delete(t, e2), i2 ? Promise.resolve() : this.client.core.expirer.del(t)]), this.addToRecentlyDeleted(t, "request"), this.sessionRequestQueue.queue = this.sessionRequestQueue.queue.filter((r) => r.id !== t), i2 && (this.sessionRequestQueue.state = A2.idle, this.client.events.emit("session_request_expire", { id: t })); - }, this.setExpiry = async (t, e2) => { - this.client.session.keys.includes(t) && await this.client.session.update(t, { expiry: e2 }), this.client.core.expirer.set(t, e2); - }, this.setProposal = async (t, e2) => { - await this.client.proposal.set(t, e2), this.client.core.expirer.set(t, s2.calcExpiry(q2.wc_sessionPropose.req.ttl)); - }, this.setPendingSessionRequest = async (t) => { - const { id: e2, topic: i2, params: r, verifyContext: n3 } = t, a3 = r.request.expiryTimestamp || s2.calcExpiry(q2.wc_sessionRequest.req.ttl); - await this.client.pendingRequest.set(e2, { id: e2, topic: i2, params: r, verifyContext: n3 }), a3 && this.client.core.expirer.set(e2, a3); - }, this.sendRequest = async (t) => { - const { topic: e2, method: i2, params: r, expiry: n3, relayRpcId: a3, clientRpcId: c4, throwOnFailedPublish: l4 } = t, d3 = u3.formatJsonRpcRequest(i2, r, c4); - if (s2.isBrowser() && ue.includes(i2)) { - const h5 = s2.hashMessage(JSON.stringify(d3)); - this.client.core.verify.register({ attestationId: h5 }); - } - let p3; - try { - p3 = await this.client.core.crypto.encode(e2, d3); - } catch (h5) { - throw await this.cleanup(), this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${e2} failed`), h5; - } - const g3 = q2[i2].req; - return n3 && (g3.ttl = n3), a3 && (g3.id = a3), this.client.core.history.set(e2, d3), l4 ? (g3.internal = C3(S4({}, g3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(e2, p3, g3)) : this.client.core.relayer.publish(e2, p3, g3).catch((h5) => this.client.logger.error(h5)), d3.id; - }, this.sendResult = async (t) => { - const { id: e2, topic: i2, result: r, throwOnFailedPublish: n3, encodeOpts: a3 } = t, c4 = u3.formatJsonRpcResult(e2, r); - let l4; - try { - l4 = await this.client.core.crypto.encode(i2, c4, a3); - } catch (g3) { - throw await this.cleanup(), this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i2} failed`), g3; - } - let d3; - try { - d3 = await this.client.core.history.get(i2, e2); - } catch (g3) { - throw this.client.logger.error(`sendResult() -> history.get(${i2}, ${e2}) failed`), g3; - } - const p3 = q2[d3.request.method].res; - n3 ? (p3.internal = C3(S4({}, p3.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(i2, l4, p3)) : this.client.core.relayer.publish(i2, l4, p3).catch((g3) => this.client.logger.error(g3)), await this.client.core.history.resolve(c4); - }, this.sendError = async (t) => { - const { id: e2, topic: i2, error: r, encodeOpts: n3 } = t, a3 = u3.formatJsonRpcError(e2, r); - let c4; - try { - c4 = await this.client.core.crypto.encode(i2, a3, n3); - } catch (p3) { - throw await this.cleanup(), this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i2} failed`), p3; - } - let l4; - try { - l4 = await this.client.core.history.get(i2, e2); - } catch (p3) { - throw this.client.logger.error(`sendError() -> history.get(${i2}, ${e2}) failed`), p3; - } - const d3 = q2[l4.request.method].res; - this.client.core.relayer.publish(i2, c4, d3), await this.client.core.history.resolve(a3); - }, this.cleanup = async () => { - const t = [], e2 = []; - this.client.session.getAll().forEach((i2) => { - let r = false; - s2.isExpired(i2.expiry) && (r = true), this.client.core.crypto.keychain.has(i2.topic) || (r = true), r && t.push(i2.topic); - }), this.client.proposal.getAll().forEach((i2) => { - s2.isExpired(i2.expiryTimestamp) && e2.push(i2.id); - }), await Promise.all([...t.map((i2) => this.deleteSession({ topic: i2 })), ...e2.map((i2) => this.deleteProposal(i2))]); - }, this.onRelayEventRequest = async (t) => { - this.requestQueue.queue.push(t), await this.processRequestsQueue(); - }, this.processRequestsQueue = async () => { - if (this.requestQueue.state === A2.active) { - this.client.logger.info("Request queue already active, skipping..."); - return; - } - for (this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`); this.requestQueue.queue.length > 0; ) { - this.requestQueue.state = A2.active; - const t = this.requestQueue.queue.shift(); - if (t) - try { - this.processRequest(t), await new Promise((e2) => setTimeout(e2, 300)); - } catch (e2) { - this.client.logger.warn(e2); - } - } - this.requestQueue.state = A2.idle; - }, this.processRequest = (t) => { - const { topic: e2, payload: i2 } = t, r = i2.method; - if (!this.shouldIgnorePairingRequest({ topic: e2, requestMethod: r })) - switch (r) { - case "wc_sessionPropose": - return this.onSessionProposeRequest(e2, i2); - case "wc_sessionSettle": - return this.onSessionSettleRequest(e2, i2); - case "wc_sessionUpdate": - return this.onSessionUpdateRequest(e2, i2); - case "wc_sessionExtend": - return this.onSessionExtendRequest(e2, i2); - case "wc_sessionPing": - return this.onSessionPingRequest(e2, i2); - case "wc_sessionDelete": - return this.onSessionDeleteRequest(e2, i2); - case "wc_sessionRequest": - return this.onSessionRequest(e2, i2); - case "wc_sessionEvent": - return this.onSessionEventRequest(e2, i2); - case "wc_sessionAuthenticate": - return this.onSessionAuthenticateRequest(e2, i2); - default: - return this.client.logger.info(`Unsupported request method ${r}`); - } - }, this.onRelayEventResponse = async (t) => { - const { topic: e2, payload: i2 } = t, r = (await this.client.core.history.get(e2, i2.id)).request.method; - switch (r) { - case "wc_sessionPropose": - return this.onSessionProposeResponse(e2, i2); - case "wc_sessionSettle": - return this.onSessionSettleResponse(e2, i2); - case "wc_sessionUpdate": - return this.onSessionUpdateResponse(e2, i2); - case "wc_sessionExtend": - return this.onSessionExtendResponse(e2, i2); - case "wc_sessionPing": - return this.onSessionPingResponse(e2, i2); - case "wc_sessionRequest": - return this.onSessionRequestResponse(e2, i2); - case "wc_sessionAuthenticate": - return this.onSessionAuthenticateResponse(e2, i2); - default: - return this.client.logger.info(`Unsupported response method ${r}`); - } - }, this.onRelayEventUnknownPayload = (t) => { - const { topic: e2 } = t, { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Decoded payload on topic ${e2} is not identifiable as a JSON-RPC request or a response.`); - throw new Error(i2); - }, this.shouldIgnorePairingRequest = (t) => { - const { topic: e2, requestMethod: i2 } = t, r = this.expectedPairingMethodMap.get(e2); - return !r || r.includes(i2) ? false : !!(r.includes("wc_sessionAuthenticate") && this.client.events.listenerCount("session_authenticate") > 0); - }, this.onSessionProposeRequest = async (t, e2) => { - const { params: i2, id: r } = e2; - try { - this.isValidConnect(S4({}, e2.params)); - const n3 = i2.expiryTimestamp || s2.calcExpiry(q2.wc_sessionPropose.req.ttl), a3 = S4({ id: r, pairingTopic: t, expiryTimestamp: n3 }, i2); - await this.setProposal(r, a3); - const c4 = s2.hashMessage(JSON.stringify(e2)), l4 = await this.getVerifyContext(c4, a3.proposer.metadata); - this.client.events.emit("session_proposal", { id: r, params: a3, verifyContext: l4 }); - } catch (n3) { - await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionProposeResponse = async (t, e2) => { - const { id: i2 } = e2; - if (u3.isJsonRpcResult(e2)) { - const { result: r } = e2; - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", result: r }); - const n3 = this.client.proposal.get(i2); - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", proposal: n3 }); - const a3 = n3.proposer.publicKey; - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", selfPublicKey: a3 }); - const c4 = r.responderPublicKey; - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", peerPublicKey: c4 }); - const l4 = await this.client.core.crypto.generateSharedKey(a3, c4); - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", sessionTopic: l4 }); - const d3 = await this.client.core.relayer.subscribe(l4); - this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", subscriptionId: d3 }), await this.client.core.pairing.activate({ topic: t }); - } else if (u3.isJsonRpcError(e2)) { - await this.client.proposal.delete(i2, s2.getSdkError("USER_DISCONNECTED")); - const r = s2.engineEvent("session_connect"); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners, 954`); - this.events.emit(s2.engineEvent("session_connect"), { error: e2.error }); - } - }, this.onSessionSettleRequest = async (t, e2) => { - const { id: i2, params: r } = e2; - try { - this.isValidSessionSettleRequest(r); - const { relay: n3, controller: a3, expiry: c4, namespaces: l4, sessionProperties: d3, pairingTopic: p3, sessionConfig: g3 } = e2.params, h5 = S4(S4({ topic: t, relay: n3, expiry: c4, namespaces: l4, acknowledged: true, pairingTopic: p3, requiredNamespaces: {}, optionalNamespaces: {}, controller: a3.publicKey, self: { publicKey: "", metadata: this.client.metadata }, peer: { publicKey: a3.publicKey, metadata: a3.metadata } }, d3 && { sessionProperties: d3 }), g3 && { sessionConfig: g3 }); - await this.sendResult({ id: e2.id, topic: t, result: true, throwOnFailedPublish: true }); - const m3 = s2.engineEvent("session_connect"); - if (this.events.listenerCount(m3) === 0) - throw new Error(`emitting ${m3} without any listeners 997`); - this.events.emit(s2.engineEvent("session_connect"), { session: h5 }), this.cleanupDuplicatePairings(h5); - } catch (n3) { - await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionSettleResponse = async (t, e2) => { - const { id: i2 } = e2; - u3.isJsonRpcResult(e2) ? (await this.client.session.update(t, { acknowledged: true }), this.events.emit(s2.engineEvent("session_approve", i2), {})) : u3.isJsonRpcError(e2) && (await this.client.session.delete(t, s2.getSdkError("USER_DISCONNECTED")), this.events.emit(s2.engineEvent("session_approve", i2), { error: e2.error })); - }, this.onSessionUpdateRequest = async (t, e2) => { - const { params: i2, id: r } = e2; - try { - const n3 = `${t}_session_update`, a3 = s2.MemoryStore.get(n3); - if (a3 && this.isRequestOutOfSync(a3, r)) { - this.client.logger.info(`Discarding out of sync request - ${r}`), this.sendError({ id: r, topic: t, error: s2.getSdkError("INVALID_UPDATE_REQUEST") }); - return; - } - this.isValidUpdate(S4({ topic: t }, i2)); - try { - s2.MemoryStore.set(n3, r), await this.client.session.update(t, { namespaces: i2.namespaces }), await this.sendResult({ id: r, topic: t, result: true, throwOnFailedPublish: true }); - } catch (c4) { - throw s2.MemoryStore.delete(n3), c4; - } - this.client.events.emit("session_update", { id: r, topic: t, params: i2 }); - } catch (n3) { - await this.sendError({ id: r, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.isRequestOutOfSync = (t, e2) => parseInt(e2.toString().slice(0, -3)) <= parseInt(t.toString().slice(0, -3)), this.onSessionUpdateResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_update", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_update", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_update", i2), { error: e2.error }); - }, this.onSessionExtendRequest = async (t, e2) => { - const { id: i2 } = e2; - try { - this.isValidExtend({ topic: t }), await this.setExpiry(t, s2.calcExpiry(V)), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_extend", { id: i2, topic: t }); - } catch (r) { - await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); - } - }, this.onSessionExtendResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_extend", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_extend", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_extend", i2), { error: e2.error }); - }, this.onSessionPingRequest = async (t, e2) => { - const { id: i2 } = e2; - try { - this.isValidPing({ topic: t }), await this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_ping", { id: i2, topic: t }); - } catch (r) { - await this.sendError({ id: i2, topic: t, error: r }), this.client.logger.error(r); - } - }, this.onSessionPingResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_ping", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - setTimeout(() => { - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_ping", i2), {}) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_ping", i2), { error: e2.error }); - }, 500); - }, this.onSessionDeleteRequest = async (t, e2) => { - const { id: i2 } = e2; - try { - this.isValidDisconnect({ topic: t, reason: e2.params }), await Promise.all([new Promise((r) => { - this.client.core.relayer.once(N10.RELAYER_EVENTS.publish, async () => { - r(await this.deleteSession({ topic: t, id: i2 })); - }); - }), this.sendResult({ id: i2, topic: t, result: true, throwOnFailedPublish: true }), this.cleanupPendingSentRequestsForTopic({ topic: t, error: s2.getSdkError("USER_DISCONNECTED") })]); - } catch (r) { - this.client.logger.error(r); - } - }, this.onSessionRequest = async (t, e2) => { - const { id: i2, params: r } = e2; - try { - await this.isValidRequest(S4({ topic: t }, r)); - const n3 = s2.hashMessage(JSON.stringify(u3.formatJsonRpcRequest("wc_sessionRequest", r, i2))), a3 = this.client.session.get(t), c4 = await this.getVerifyContext(n3, a3.peer.metadata), l4 = { id: i2, topic: t, params: r, verifyContext: c4 }; - await this.setPendingSessionRequest(l4), this.addSessionRequestToSessionRequestQueue(l4), this.processSessionRequestQueue(); - } catch (n3) { - await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionRequestResponse = (t, e2) => { - const { id: i2 } = e2, r = s2.engineEvent("session_request", i2); - if (this.events.listenerCount(r) === 0) - throw new Error(`emitting ${r} without any listeners`); - u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); - }, this.onSessionEventRequest = async (t, e2) => { - const { id: i2, params: r } = e2; - try { - const n3 = `${t}_session_event_${r.event.name}`, a3 = s2.MemoryStore.get(n3); - if (a3 && this.isRequestOutOfSync(a3, i2)) { - this.client.logger.info(`Discarding out of sync request - ${i2}`); - return; - } - this.isValidEmit(S4({ topic: t }, r)), this.client.events.emit("session_event", { id: i2, topic: t, params: r }), s2.MemoryStore.set(n3, i2); - } catch (n3) { - await this.sendError({ id: i2, topic: t, error: n3 }), this.client.logger.error(n3); - } - }, this.onSessionAuthenticateResponse = (t, e2) => { - const { id: i2 } = e2; - this.client.logger.trace({ type: "method", method: "onSessionAuthenticateResponse", topic: t, payload: e2 }), u3.isJsonRpcResult(e2) ? this.events.emit(s2.engineEvent("session_request", i2), { result: e2.result }) : u3.isJsonRpcError(e2) && this.events.emit(s2.engineEvent("session_request", i2), { error: e2.error }); - }, this.onSessionAuthenticateRequest = async (t, e2) => { - const { requester: i2, authPayload: r, expiryTimestamp: n3 } = e2.params, a3 = s2.hashMessage(JSON.stringify(e2)), c4 = await this.getVerifyContext(a3, this.client.metadata), l4 = { requester: i2, pairingTopic: t, id: e2.id, authPayload: r, verifyContext: c4, expiryTimestamp: n3 }; - await this.client.auth.requests.set(e2.id, l4), this.client.events.emit("session_authenticate", { topic: t, params: e2.params, id: e2.id }); - }, this.addSessionRequestToSessionRequestQueue = (t) => { - this.sessionRequestQueue.queue.push(t); - }, this.cleanupAfterResponse = (t) => { - this.deletePendingSessionRequest(t.response.id, { message: "fulfilled", code: 0 }), setTimeout(() => { - this.sessionRequestQueue.state = A2.idle, this.processSessionRequestQueue(); - }, w4.toMiliseconds(this.requestQueueDelay)); - }, this.cleanupPendingSentRequestsForTopic = ({ topic: t, error: e2 }) => { - const i2 = this.client.core.history.pending; - i2.length > 0 && i2.filter((r) => r.topic === t && r.request.method === "wc_sessionRequest").forEach((r) => { - const n3 = r.request.id, a3 = s2.engineEvent("session_request", n3); - if (this.events.listenerCount(a3) === 0) - throw new Error(`emitting ${a3} without any listeners`); - this.events.emit(s2.engineEvent("session_request", r.request.id), { error: e2 }); - }); - }, this.processSessionRequestQueue = () => { - if (this.sessionRequestQueue.state === A2.active) { - this.client.logger.info("session request queue is already active."); - return; - } - const t = this.sessionRequestQueue.queue[0]; - if (!t) { - this.client.logger.info("session request queue is empty."); - return; - } - try { - this.sessionRequestQueue.state = A2.active, this.client.events.emit("session_request", t); - } catch (e2) { - this.client.logger.error(e2); - } - }, this.onPairingCreated = (t) => { - if (t.methods && this.expectedPairingMethodMap.set(t.topic, t.methods), t.active) - return; - const e2 = this.client.proposal.getAll().find((i2) => i2.pairingTopic === t.topic); - e2 && this.onSessionProposeRequest(t.topic, u3.formatJsonRpcRequest("wc_sessionPropose", { requiredNamespaces: e2.requiredNamespaces, optionalNamespaces: e2.optionalNamespaces, relays: e2.relays, proposer: e2.proposer, sessionProperties: e2.sessionProperties }, e2.id)); - }, this.isValidConnect = async (t) => { - if (!s2.isValidParams(t)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() params: ${JSON.stringify(t)}`); - throw new Error(c4); - } - const { pairingTopic: e2, requiredNamespaces: i2, optionalNamespaces: r, sessionProperties: n3, relays: a3 } = t; - if (s2.isUndefined(e2) || await this.isValidPairingTopic(e2), !s2.isValidRelays(a3, true)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `connect() relays: ${a3}`); - throw new Error(c4); - } - !s2.isUndefined(i2) && s2.isValidObject(i2) !== 0 && this.validateNamespaces(i2, "requiredNamespaces"), !s2.isUndefined(r) && s2.isValidObject(r) !== 0 && this.validateNamespaces(r, "optionalNamespaces"), s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); - }, this.validateNamespaces = (t, e2) => { - const i2 = s2.isValidRequiredNamespaces(t, "connect()", e2); - if (i2) - throw new Error(i2.message); - }, this.isValidApprove = async (t) => { - if (!s2.isValidParams(t)) - throw new Error(s2.getInternalError("MISSING_OR_INVALID", `approve() params: ${t}`).message); - const { id: e2, namespaces: i2, relayProtocol: r, sessionProperties: n3 } = t; - this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2); - const a3 = this.client.proposal.get(e2), c4 = s2.isValidNamespaces(i2, "approve()"); - if (c4) - throw new Error(c4.message); - const l4 = s2.isConformingNamespaces(a3.requiredNamespaces, i2, "approve()"); - if (l4) - throw new Error(l4.message); - if (!s2.isValidString(r, true)) { - const { message: d3 } = s2.getInternalError("MISSING_OR_INVALID", `approve() relayProtocol: ${r}`); - throw new Error(d3); - } - s2.isUndefined(n3) || this.validateSessionProps(n3, "sessionProperties"); - }, this.isValidReject = async (t) => { - if (!s2.isValidParams(t)) { - const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() params: ${t}`); - throw new Error(r); - } - const { id: e2, reason: i2 } = t; - if (this.checkRecentlyDeleted(e2), await this.isValidProposalId(e2), !s2.isValidErrorReason(i2)) { - const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `reject() reason: ${JSON.stringify(i2)}`); - throw new Error(r); - } - }, this.isValidSessionSettleRequest = (t) => { - if (!s2.isValidParams(t)) { - const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", `onSessionSettleRequest() params: ${t}`); - throw new Error(l4); - } - const { relay: e2, controller: i2, namespaces: r, expiry: n3 } = t; - if (!s2.isValidRelay(e2)) { - const { message: l4 } = s2.getInternalError("MISSING_OR_INVALID", "onSessionSettleRequest() relay protocol should be a string"); - throw new Error(l4); - } - const a3 = s2.isValidController(i2, "onSessionSettleRequest()"); - if (a3) - throw new Error(a3.message); - const c4 = s2.isValidNamespaces(r, "onSessionSettleRequest()"); - if (c4) - throw new Error(c4.message); - if (s2.isExpired(n3)) { - const { message: l4 } = s2.getInternalError("EXPIRED", "onSessionSettleRequest()"); - throw new Error(l4); - } - }, this.isValidUpdate = async (t) => { - if (!s2.isValidParams(t)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `update() params: ${t}`); - throw new Error(c4); - } - const { topic: e2, namespaces: i2 } = t; - this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); - const r = this.client.session.get(e2), n3 = s2.isValidNamespaces(i2, "update()"); - if (n3) - throw new Error(n3.message); - const a3 = s2.isConformingNamespaces(r.requiredNamespaces, i2, "update()"); - if (a3) - throw new Error(a3.message); - }, this.isValidExtend = async (t) => { - if (!s2.isValidParams(t)) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `extend() params: ${t}`); - throw new Error(i2); - } - const { topic: e2 } = t; - this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); - }, this.isValidRequest = async (t) => { - if (!s2.isValidParams(t)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() params: ${t}`); - throw new Error(c4); - } - const { topic: e2, request: i2, chainId: r, expiry: n3 } = t; - this.checkRecentlyDeleted(e2), await this.isValidSessionTopic(e2); - const { namespaces: a3 } = this.client.session.get(e2); - if (!s2.isValidNamespacesChainId(a3, r)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() chainId: ${r}`); - throw new Error(c4); - } - if (!s2.isValidRequest(i2)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() ${JSON.stringify(i2)}`); - throw new Error(c4); - } - if (!s2.isValidNamespacesRequest(a3, r, i2.method)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() method: ${i2.method}`); - throw new Error(c4); - } - if (n3 && !s2.isValidRequestExpiry(n3, H)) { - const { message: c4 } = s2.getInternalError("MISSING_OR_INVALID", `request() expiry: ${n3}. Expiry must be a number (in seconds) between ${H.min} and ${H.max}`); - throw new Error(c4); - } - }, this.isValidRespond = async (t) => { - var e2; - if (!s2.isValidParams(t)) { - const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() params: ${t}`); - throw new Error(n3); - } - const { topic: i2, response: r } = t; - try { - await this.isValidSessionTopic(i2); - } catch (n3) { - throw (e2 = t?.response) != null && e2.id && this.cleanupAfterResponse(t), n3; - } - if (!s2.isValidResponse(r)) { - const { message: n3 } = s2.getInternalError("MISSING_OR_INVALID", `respond() response: ${JSON.stringify(r)}`); - throw new Error(n3); - } - }, this.isValidPing = async (t) => { - if (!s2.isValidParams(t)) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `ping() params: ${t}`); - throw new Error(i2); - } - const { topic: e2 } = t; - await this.isValidSessionOrPairingTopic(e2); - }, this.isValidEmit = async (t) => { - if (!s2.isValidParams(t)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() params: ${t}`); - throw new Error(a3); - } - const { topic: e2, event: i2, chainId: r } = t; - await this.isValidSessionTopic(e2); - const { namespaces: n3 } = this.client.session.get(e2); - if (!s2.isValidNamespacesChainId(n3, r)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() chainId: ${r}`); - throw new Error(a3); - } - if (!s2.isValidEvent(i2)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); - throw new Error(a3); - } - if (!s2.isValidNamespacesEvent(n3, r, i2.name)) { - const { message: a3 } = s2.getInternalError("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(i2)}`); - throw new Error(a3); - } - }, this.isValidDisconnect = async (t) => { - if (!s2.isValidParams(t)) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `disconnect() params: ${t}`); - throw new Error(i2); - } - const { topic: e2 } = t; - await this.isValidSessionOrPairingTopic(e2); - }, this.isValidAuthenticate = (t) => { - const { chains: e2, uri: i2, domain: r, nonce: n3 } = t; - if (!Array.isArray(e2) || e2.length === 0) - throw new Error("chains is required and must be a non-empty array"); - if (!s2.isValidString(i2, false)) - throw new Error("uri is required parameter"); - if (!s2.isValidString(r, false)) - throw new Error("domain is required parameter"); - if (!s2.isValidString(n3, false)) - throw new Error("nonce is required parameter"); - if ([...new Set(e2.map((c4) => s2.parseChainId(c4).namespace))].length > 1) - throw new Error("Multi-namespace requests are not supported. Please request single namespace only."); - const { namespace: a3 } = s2.parseChainId(e2[0]); - if (a3 !== "eip155") - throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains."); - }, this.getVerifyContext = async (t, e2) => { - const i2 = { verified: { verifyUrl: e2.verifyUrl || N10.VERIFY_SERVER, validation: "UNKNOWN", origin: e2.url || "" } }; - try { - const r = await this.client.core.verify.resolve({ attestationId: t, verifyUrl: e2.verifyUrl }); - r && (i2.verified.origin = r.origin, i2.verified.isScam = r.isScam, i2.verified.validation = r.origin === new URL(e2.url).origin ? "VALID" : "INVALID"); - } catch (r) { - this.client.logger.info(r); - } - return this.client.logger.info(`Verify context: ${JSON.stringify(i2)}`), i2; - }, this.validateSessionProps = (t, e2) => { - Object.values(t).forEach((i2) => { - if (!s2.isValidString(i2, false)) { - const { message: r } = s2.getInternalError("MISSING_OR_INVALID", `${e2} must be in Record format. Received: ${JSON.stringify(i2)}`); - throw new Error(r); - } - }); - }, this.getPendingAuthRequest = (t) => { - const e2 = this.client.auth.requests.get(t); - return typeof e2 == "object" ? e2 : void 0; - }, this.addToRecentlyDeleted = (t, e2) => { - if (this.recentlyDeletedMap.set(t, e2), this.recentlyDeletedMap.size >= this.recentlyDeletedLimit) { - let i2 = 0; - const r = this.recentlyDeletedLimit / 2; - for (const n3 of this.recentlyDeletedMap.keys()) { - if (i2++ >= r) - break; - this.recentlyDeletedMap.delete(n3); - } - } - }, this.checkRecentlyDeleted = (t) => { - const e2 = this.recentlyDeletedMap.get(t); - if (e2) { - const { message: i2 } = s2.getInternalError("MISSING_OR_INVALID", `Record was recently deleted - ${e2}: ${t}`); - throw new Error(i2); - } - }; - } - async isInitialized() { - if (!this.initialized) { - const { message: o2 } = s2.getInternalError("NOT_INITIALIZED", this.name); - throw new Error(o2); - } - await this.client.core.relayer.confirmOnlineStateOrThrow(); - } - registerRelayerEvents() { - this.client.core.relayer.on(N10.RELAYER_EVENTS.message, async (o2) => { - const { topic: t, message: e2 } = o2, { publicKey: i2 } = this.client.auth.authKeys.keys.includes(U2) ? this.client.auth.authKeys.get(U2) : { responseTopic: void 0, publicKey: void 0 }, r = await this.client.core.crypto.decode(t, e2, { receiverPublicKey: i2 }); - try { - u3.isJsonRpcRequest(r) ? (this.client.core.history.set(t, r), this.onRelayEventRequest({ topic: t, payload: r })) : u3.isJsonRpcResponse(r) ? (await this.client.core.history.resolve(r), await this.onRelayEventResponse({ topic: t, payload: r }), this.client.core.history.delete(t, r.id)) : this.onRelayEventUnknownPayload({ topic: t, payload: r }); - } catch (n3) { - this.client.logger.error(n3); - } - }); - } - registerExpirerEvents() { - this.client.core.expirer.on(N10.EXPIRER_EVENTS.expired, async (o2) => { - const { topic: t, id: e2 } = s2.parseExpirerTarget(o2.target); - if (e2 && this.client.pendingRequest.keys.includes(e2)) - return await this.deletePendingSessionRequest(e2, s2.getInternalError("EXPIRED"), true); - t ? this.client.session.keys.includes(t) && (await this.deleteSession({ topic: t, expirerHasDeleted: true }), this.client.events.emit("session_expire", { topic: t })) : e2 && (await this.deleteProposal(e2, true), this.client.events.emit("proposal_expire", { id: e2 })); - }); - } - registerPairingEvents() { - this.client.core.pairing.events.on(N10.PAIRING_EVENTS.create, (o2) => this.onPairingCreated(o2)), this.client.core.pairing.events.on(N10.PAIRING_EVENTS.delete, (o2) => { - this.addToRecentlyDeleted(o2.topic, "pairing"); - }); - } - isValidPairingTopic(o2) { - if (!s2.isValidString(o2, false)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `pairing topic should be a string: ${o2}`); - throw new Error(t); - } - if (!this.client.core.pairing.pairings.keys.includes(o2)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `pairing topic doesn't exist: ${o2}`); - throw new Error(t); - } - if (s2.isExpired(this.client.core.pairing.pairings.get(o2).expiry)) { - const { message: t } = s2.getInternalError("EXPIRED", `pairing topic: ${o2}`); - throw new Error(t); - } - } - async isValidSessionTopic(o2) { - if (!s2.isValidString(o2, false)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic should be a string: ${o2}`); - throw new Error(t); - } - if (this.checkRecentlyDeleted(o2), !this.client.session.keys.includes(o2)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session topic doesn't exist: ${o2}`); - throw new Error(t); - } - if (s2.isExpired(this.client.session.get(o2).expiry)) { - await this.deleteSession({ topic: o2 }); - const { message: t } = s2.getInternalError("EXPIRED", `session topic: ${o2}`); - throw new Error(t); - } - if (!this.client.core.crypto.keychain.has(o2)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session topic does not exist in keychain: ${o2}`); - throw await this.deleteSession({ topic: o2 }), new Error(t); - } - } - async isValidSessionOrPairingTopic(o2) { - if (this.checkRecentlyDeleted(o2), this.client.session.keys.includes(o2)) - await this.isValidSessionTopic(o2); - else if (this.client.core.pairing.pairings.keys.includes(o2)) - this.isValidPairingTopic(o2); - else if (s2.isValidString(o2, false)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `session or pairing topic doesn't exist: ${o2}`); - throw new Error(t); - } else { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `session or pairing topic should be a string: ${o2}`); - throw new Error(t); - } - } - async isValidProposalId(o2) { - if (!s2.isValidId(o2)) { - const { message: t } = s2.getInternalError("MISSING_OR_INVALID", `proposal id should be a number: ${o2}`); - throw new Error(t); - } - if (!this.client.proposal.keys.includes(o2)) { - const { message: t } = s2.getInternalError("NO_MATCHING_KEY", `proposal id doesn't exist: ${o2}`); - throw new Error(t); - } - if (s2.isExpired(this.client.proposal.get(o2).expiryTimestamp)) { - await this.deleteProposal(o2); - const { message: t } = s2.getInternalError("EXPIRED", `proposal id: ${o2}`); - throw new Error(t); - } - } - }; - var $e = class extends N10.Store { - constructor(o2, t) { - super(o2, t, ce, F), this.core = o2, this.logger = t; - } - }; - var _e = class extends N10.Store { - constructor(o2, t) { - super(o2, t, he, F), this.core = o2, this.logger = t; - } - }; - var Ge = class extends N10.Store { - constructor(o2, t) { - super(o2, t, de, F, (e2) => e2.id), this.core = o2, this.logger = t; - } - }; - var Ke = class extends N10.Store { - constructor(o2, t) { - super(o2, t, we, L2, () => U2), this.core = o2, this.logger = t; - } - }; - var ke = class extends N10.Store { - constructor(o2, t) { - super(o2, t, ye, L2), this.core = o2, this.logger = t; - } - }; - var Fe = class extends N10.Store { - constructor(o2, t) { - super(o2, t, me, L2, (e2) => e2.id), this.core = o2, this.logger = t; - } - }; - var Ye = class { - constructor(o2, t) { - this.core = o2, this.logger = t, this.authKeys = new Ke(this.core, this.logger), this.pairingTopics = new ke(this.core, this.logger), this.requests = new Fe(this.core, this.logger); - } - async init() { - await this.authKeys.init(), await this.pairingTopics.init(), await this.requests.init(); - } - }; - var j2 = class _j extends oe.ISignClient { - constructor(o2) { - super(o2), this.protocol = ee, this.version = te, this.name = Y.name, this.events = new ae.EventEmitter(), this.on = (e2, i2) => this.events.on(e2, i2), this.once = (e2, i2) => this.events.once(e2, i2), this.off = (e2, i2) => this.events.off(e2, i2), this.removeListener = (e2, i2) => this.events.removeListener(e2, i2), this.removeAllListeners = (e2) => this.events.removeAllListeners(e2), this.connect = async (e2) => { - try { - return await this.engine.connect(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.pair = async (e2) => { - try { - return await this.engine.pair(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.approve = async (e2) => { - try { - return await this.engine.approve(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.reject = async (e2) => { - try { - return await this.engine.reject(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.update = async (e2) => { - try { - return await this.engine.update(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.extend = async (e2) => { - try { - return await this.engine.extend(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.request = async (e2) => { - try { - return await this.engine.request(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.respond = async (e2) => { - try { - return await this.engine.respond(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.ping = async (e2) => { - try { - return await this.engine.ping(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.emit = async (e2) => { - try { - return await this.engine.emit(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.disconnect = async (e2) => { - try { - return await this.engine.disconnect(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.find = (e2) => { - try { - return this.engine.find(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.getPendingSessionRequests = () => { - try { - return this.engine.getPendingSessionRequests(); - } catch (e2) { - throw this.logger.error(e2.message), e2; - } - }, this.authenticate = async (e2) => { - try { - return await this.engine.authenticate(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.formatAuthMessage = (e2) => { - try { - return this.engine.formatAuthMessage(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.approveSessionAuthenticate = async (e2) => { - try { - return await this.engine.approveSessionAuthenticate(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.rejectSessionAuthenticate = async (e2) => { - try { - return await this.engine.rejectSessionAuthenticate(e2); - } catch (i2) { - throw this.logger.error(i2.message), i2; - } - }, this.name = o2?.name || Y.name, this.metadata = o2?.metadata || s2.getAppMetadata(); - const t = typeof o2?.logger < "u" && typeof o2?.logger != "string" ? o2.logger : k4.pino(k4.getDefaultLoggerOptions({ level: o2?.logger || Y.logger })); - this.core = o2?.core || new N10.Core(o2), this.logger = k4.generateChildLogger(t, this.name), this.session = new _e(this.core, this.logger), this.proposal = new $e(this.core, this.logger), this.pendingRequest = new Ge(this.core, this.logger), this.engine = new Ue(this), this.auth = new Ye(this.core, this.logger); - } - static async init(o2) { - const t = new _j(o2); - return await t.initialize(), t; - } - get context() { - return k4.getLoggerContext(this.logger); - } - get pairing() { - return this.core.pairing.pairings; - } - async initialize() { - this.logger.trace("Initialized"); - try { - await this.core.start(), await this.session.init(), await this.proposal.init(), await this.pendingRequest.init(), await this.engine.init(), await this.auth.init(), this.core.verify.init({ verifyUrl: this.metadata.verifyUrl }), this.logger.info("SignClient Initialization Success"); - } catch (o2) { - throw this.logger.info("SignClient Initialization Failure"), this.logger.error(o2.message), o2; - } - } - }; - var He = _e; - var je = j2; - exports2.AUTH_CONTEXT = Ee, exports2.AUTH_KEYS_CONTEXT = we, exports2.AUTH_PAIRING_TOPIC_CONTEXT = ye, exports2.AUTH_PROTOCOL = ge, exports2.AUTH_PUBLIC_KEY_NAME = U2, exports2.AUTH_REQUEST_CONTEXT = me, exports2.AUTH_STORAGE_PREFIX = L2, exports2.AUTH_VERSION = De, exports2.ENGINE_CONTEXT = pe, exports2.ENGINE_QUEUE_STATES = A2, exports2.ENGINE_RPC_OPTS = q2, exports2.HISTORY_CONTEXT = Oe, exports2.HISTORY_EVENTS = ve, exports2.HISTORY_STORAGE_VERSION = Ae, exports2.METHODS_TO_VERIFY = ue, exports2.PROPOSAL_CONTEXT = ce, exports2.PROPOSAL_EXPIRY = Ve, exports2.PROPOSAL_EXPIRY_MESSAGE = le, exports2.REQUEST_CONTEXT = de, exports2.SESSION_CONTEXT = he, exports2.SESSION_EXPIRY = V, exports2.SESSION_REQUEST_EXPIRY_BOUNDARIES = H, exports2.SIGN_CLIENT_CONTEXT = ie, exports2.SIGN_CLIENT_DEFAULT = Y, exports2.SIGN_CLIENT_EVENTS = Pe, exports2.SIGN_CLIENT_PROTOCOL = ee, exports2.SIGN_CLIENT_STORAGE_OPTIONS = Te, exports2.SIGN_CLIENT_STORAGE_PREFIX = F, exports2.SIGN_CLIENT_VERSION = te, exports2.SessionStore = He, exports2.SignClient = je, exports2.WALLETCONNECT_DEEPLINK_CHOICE = se, exports2.default = j2; - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js -var require_operation2 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/operation.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.OptionalOperation = exports2.Operation = void 0; - var Operation; - (function(Operation2) { - Operation2["SIGN_TRANSACTION"] = "mvx_signTransaction"; - Operation2["SIGN_TRANSACTIONS"] = "mvx_signTransactions"; - Operation2["SIGN_MESSAGE"] = "mvx_signMessage"; - })(Operation = exports2.Operation || (exports2.Operation = {})); - var OptionalOperation; - (function(OptionalOperation2) { - OptionalOperation2["SIGN_LOGIN_TOKEN"] = "mvx_signLoginToken"; - OptionalOperation2["SIGN_NATIVE_AUTH_TOKEN"] = "mvx_signNativeAuthToken"; - OptionalOperation2["CANCEL_ACTION"] = "mvx_cancelAction"; - })(OptionalOperation = exports2.OptionalOperation || (exports2.OptionalOperation = {})); - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js -var require_constants6 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = exports2.WALLETCONNECT_MULTIVERSX_METHODS = exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = void 0; - var operation_1 = require_operation2(); - exports2.WALLETCONNECT_MULTIVERSX_NAMESPACE = "mvx"; - exports2.WALLETCONNECT_MULTIVERSX_METHODS = Object.values(operation_1.Operation); - exports2.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS = Object.values(operation_1.OptionalOperation); - exports2.WALLETCONNECT_SIGN_LOGIN_DELAY = 500; - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js -var require_errors3 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WalletConnectV2ProviderErrorMessagesEnum = exports2.ErrBadAddress = exports2.ErrNotImplemented = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - }; - exports2.Err = Err; - var ErrNotImplemented = class extends Err { - constructor() { - super("Method not yet implemented"); - } - }; - exports2.ErrNotImplemented = ErrNotImplemented; - var ErrBadAddress = class extends Err { - constructor(value, inner) { - super(`Bad address: ${value}`, inner); - } - }; - exports2.ErrBadAddress = ErrBadAddress; - var WalletConnectV2ProviderErrorMessagesEnum; - (function(WalletConnectV2ProviderErrorMessagesEnum2) { - WalletConnectV2ProviderErrorMessagesEnum2["unableToInit"] = "WalletConnect is unable to init"; - WalletConnectV2ProviderErrorMessagesEnum2["notInitialized"] = "WalletConnect is not initialized"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToConnect"] = "WalletConnect is unable to connect"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToConnectExisting"] = "WalletConnect is unable to connect to existing pairing"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToSignLoginToken"] = "WalletConnect could not sign login token"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToSign"] = "WalletConnect could not sign the message"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToLogin"] = "WalletConnect is unable to login"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleTopic"] = "WalletConnect: Unable to handle topic update"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleEvent"] = "WalletConnect: Unable to handle events"; - WalletConnectV2ProviderErrorMessagesEnum2["unableToHandleCleanup"] = "WalletConnect: Unable to handle cleanup"; - WalletConnectV2ProviderErrorMessagesEnum2["sessionNotConnected"] = "WalletConnect Session is not connected"; - WalletConnectV2ProviderErrorMessagesEnum2["sessionDeleted"] = "WalletConnect Session Deleted"; - WalletConnectV2ProviderErrorMessagesEnum2["sessionExpired"] = "WalletConnect Session Expired"; - WalletConnectV2ProviderErrorMessagesEnum2["alreadyLoggedOut"] = "WalletConnect: Already logged out"; - WalletConnectV2ProviderErrorMessagesEnum2["pingFailed"] = "WalletConnect Ping Failed"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidAddress"] = "WalletConnect: Invalid address"; - WalletConnectV2ProviderErrorMessagesEnum2["requestDifferentChain"] = "WalletConnect: Request Chain Id different than Connection Chain Id"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageResponse"] = "WalletConnect could not sign the message"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidMessageSignature"] = "WalletConnect: Invalid message signature"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidTransactionResponse"] = "WalletConnect could not sign the transactions. Invalid signatures"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidCustomRequestResponse"] = "WalletConnect could not send the custom request"; - WalletConnectV2ProviderErrorMessagesEnum2["transactionError"] = "Transaction canceled"; - WalletConnectV2ProviderErrorMessagesEnum2["connectionError"] = "WalletConnect could not establish a connection"; - WalletConnectV2ProviderErrorMessagesEnum2["invalidGuardian"] = "WalletConnect: Invalid Guardian"; - })(WalletConnectV2ProviderErrorMessagesEnum = exports2.WalletConnectV2ProviderErrorMessagesEnum || (exports2.WalletConnectV2ProviderErrorMessagesEnum = {})); - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js -var require_logger2 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/logger.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Logger = void 0; - var Logger = class { - static error(message) { - console.error(message); - } - static trace(message) { - console.trace(message); - } - }; - exports2.Logger = Logger; - } -}); - -// node_modules/@multiversx/sdk-core/out/globals.js -var require_globals = __commonJS({ - "node_modules/@multiversx/sdk-core/out/globals.js"() { - "use strict"; - init_shim(); - if (!global.Buffer) { - global.Buffer = require_buffer2().Buffer; - } - } -}); - -// node_modules/@multiversx/sdk-core/out/smartContractQuery.js -var require_smartContractQuery = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartContractQuery.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractQueryResponse = exports2.SmartContractQuery = void 0; - var SmartContractQuery = class { - constructor(options) { - this.contract = options.contract; - this.caller = options.caller; - this.value = options.value; - this.function = options.function; - this.arguments = options.arguments; - } - }; - exports2.SmartContractQuery = SmartContractQuery; - var SmartContractQueryResponse = class { - constructor(obj) { - this.function = obj.function; - this.returnCode = obj.returnCode; - this.returnMessage = obj.returnMessage; - this.returnDataParts = obj.returnDataParts; - } - }; - exports2.SmartContractQueryResponse = SmartContractQueryResponse; - } -}); - -// node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js -var require_queryRunnerAdapter = __commonJS({ - "node_modules/@multiversx/sdk-core/out/adapters/queryRunnerAdapter.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.QueryRunnerAdapter = void 0; - var address_1 = require_address(); - var smartContractQuery_1 = require_smartContractQuery(); - var QueryRunnerAdapter = class { - constructor(options) { - this.networkProvider = options.networkProvider; - } - async runQuery(query) { - const adaptedQuery = { - address: address_1.Address.fromBech32(query.contract), - caller: query.caller ? address_1.Address.fromBech32(query.caller) : void 0, - func: query.function, - value: query.value, - getEncodedArguments: () => query.arguments.map((arg) => import_buffer.Buffer.from(arg).toString("hex")) - }; - const adaptedQueryResponse = await this.networkProvider.queryContract(adaptedQuery); - return new smartContractQuery_1.SmartContractQueryResponse({ - function: query.function, - returnCode: adaptedQueryResponse.returnCode.toString(), - returnMessage: adaptedQueryResponse.returnMessage, - returnDataParts: adaptedQueryResponse.getReturnDataParts() - }); - } - }; - exports2.QueryRunnerAdapter = QueryRunnerAdapter; - } -}); - -// node_modules/@multiversx/sdk-core/out/adapters/index.js -var require_adapters = __commonJS({ - "node_modules/@multiversx/sdk-core/out/adapters/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_queryRunnerAdapter(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/converters/index.js -var require_converters = __commonJS({ - "node_modules/@multiversx/sdk-core/out/converters/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_transactionsConverter(), exports2); - } -}); - -// node_modules/@multiversx/sdk-core/out/gasEstimator.js -var require_gasEstimator = __commonJS({ - "node_modules/@multiversx/sdk-core/out/gasEstimator.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.GasEstimator = exports2.DefaultGasConfiguration = void 0; - exports2.DefaultGasConfiguration = { - minGasLimit: 5e4, - gasPerDataByte: 1500, - gasCostESDTTransfer: 2e5, - gasCostESDTNFTTransfer: 2e5, - gasCostESDTNFTMultiTransfer: 2e5 - }; - var ADDITIONAL_GAS_FOR_ESDT_TRANSFER = 1e5; - var ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER = 8e5; - var GasEstimator = class { - constructor(gasConfiguration) { - this.gasConfiguration = gasConfiguration || exports2.DefaultGasConfiguration; - } - forEGLDTransfer(dataLength) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasPerDataByte * dataLength; - return gasLimit; - } - forESDTTransfer(dataLength) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_TRANSFER; - return gasLimit; - } - forESDTNFTTransfer(dataLength) { - const gasLimit = this.gasConfiguration.minGasLimit + this.gasConfiguration.gasCostESDTNFTTransfer + this.gasConfiguration.gasPerDataByte * dataLength + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER; - return gasLimit; - } - forMultiESDTNFTTransfer(dataLength, numTransfers) { - const gasLimit = this.gasConfiguration.minGasLimit + (this.gasConfiguration.gasCostESDTNFTMultiTransfer + ADDITIONAL_GAS_FOR_ESDT_NFT_TRANSFER) * numTransfers + this.gasConfiguration.gasPerDataByte * dataLength; - return gasLimit; - } - }; - exports2.GasEstimator = GasEstimator; - } -}); - -// node_modules/@multiversx/sdk-core/out/interface.js -var require_interface2 = __commonJS({ - "node_modules/@multiversx/sdk-core/out/interface.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js -var require_interfaceOfNetwork = __commonJS({ - "node_modules/@multiversx/sdk-core/out/interfaceOfNetwork.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js -var require_relayedTransactionV1Builder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/relayedTransactionV1Builder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RelayedTransactionV1Builder = void 0; - var address_1 = require_address(); - var errors_1 = require_errors(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var JSONbig = require_json_bigint(); - var RelayedTransactionV1Builder = class { - /** - * Sets the inner transaction to be used. It has to be already signed. - * - * @param {Transaction} transaction The inner transaction to be used - */ - setInnerTransaction(transaction) { - this.innerTransaction = transaction; - return this; - } - /** - * Sets the network config to be used for building the relayed v1 transaction - * - * @param {INetworkConfig} netConfig The network configuration to be used - */ - setNetworkConfig(netConfig) { - this.netConfig = netConfig; - return this; - } - /** - * Sets the address of the relayer (the one that will actually pay the fee) - * - * @param relayerAddress - */ - setRelayerAddress(relayerAddress) { - this.relayerAddress = relayerAddress; - return this; - } - /** - * (optional) Sets the nonce of the relayer - * - * @param relayerNonce - */ - setRelayerNonce(relayerNonce) { - this.relayerNonce = relayerNonce; - return this; - } - /** - * (optional) Sets the version of the relayed transaction - * - * @param relayedTxVersion - */ - setRelayedTransactionVersion(relayedTxVersion) { - this.relayedTransactionVersion = relayedTxVersion; - return this; - } - /** - * (optional) Sets the options of the relayed transaction - * - * @param relayedTxOptions - */ - setRelayedTransactionOptions(relayedTxOptions) { - this.relayedTransactionOptions = relayedTxOptions; - return this; - } - /** - * (optional) Sets the guardian of the relayed transaction - * - * @param relayedTxGuardian - */ - setRelayedTransactionGuardian(relayedTxGuardian) { - this.relayedTransactionGuardian = relayedTxGuardian; - return this; - } - /** - * Tries to build the relayed v1 transaction based on the previously set fields - * - * @throws ErrInvalidRelayedV1BuilderArguments - * @return Transaction - */ - build() { - if (!this.innerTransaction || !this.netConfig || !this.relayerAddress || !this.innerTransaction.getSignature()) { - throw new errors_1.ErrInvalidRelayedV1BuilderArguments(); - } - const serializedTransaction = this.prepareInnerTransaction(); - const data = `relayedTx@${import_buffer.Buffer.from(serializedTransaction).toString("hex")}`; - const payload = new transactionPayload_1.TransactionPayload(data); - const gasLimit = this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length() + this.innerTransaction.getGasLimit().valueOf(); - let relayedTransaction = new transaction_1.Transaction({ - nonce: this.relayerNonce, - sender: this.relayerAddress, - receiver: this.innerTransaction.getSender(), - value: 0, - gasLimit, - data: payload, - chainID: this.netConfig.ChainID, - version: this.relayedTransactionVersion, - options: this.relayedTransactionOptions, - guardian: this.relayedTransactionGuardian - }); - if (this.relayerNonce) { - relayedTransaction.setNonce(this.relayerNonce); - } - return relayedTransaction; - } - prepareInnerTransaction() { - if (!this.innerTransaction) { - return ""; - } - const txObject = { - nonce: this.innerTransaction.getNonce().valueOf(), - sender: new address_1.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"), - receiver: new address_1.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"), - value: BigInt(this.innerTransaction.getValue().toString()), - gasPrice: this.innerTransaction.getGasPrice().valueOf(), - gasLimit: this.innerTransaction.getGasLimit().valueOf(), - data: this.innerTransaction.getData().valueOf().toString("base64"), - signature: this.innerTransaction.getSignature().toString("base64"), - chainID: import_buffer.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"), - version: this.innerTransaction.getVersion().valueOf(), - options: this.innerTransaction.getOptions().valueOf() == 0 ? void 0 : this.innerTransaction.getOptions().valueOf(), - guardian: this.innerTransaction.getGuardian().bech32() ? new address_1.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64") : void 0, - guardianSignature: this.innerTransaction.getGuardianSignature().toString("hex") ? this.innerTransaction.getGuardianSignature().toString("base64") : void 0, - sndUserName: this.innerTransaction.getSenderUsername() ? import_buffer.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64") : void 0, - rcvUserName: this.innerTransaction.getReceiverUsername() ? import_buffer.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64") : void 0 - }; - return JSONbig.stringify(txObject); - } - }; - exports2.RelayedTransactionV1Builder = RelayedTransactionV1Builder; - } -}); - -// node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js -var require_relayedTransactionV2Builder = __commonJS({ - "node_modules/@multiversx/sdk-core/out/relayedTransactionV2Builder.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.RelayedTransactionV2Builder = void 0; - var errors_1 = require_errors(); - var smartcontracts_1 = require_smartcontracts(); - var transaction_1 = require_transaction(); - var transactionPayload_1 = require_transactionPayload(); - var RelayedTransactionV2Builder = class { - /** - * Sets the inner transaction to be used. It has to be already signed and with gasLimit set to 0. These checks - * are performed on the build() method - * - * @param {Transaction} transaction The inner transaction to be used - */ - setInnerTransaction(transaction) { - this.innerTransaction = transaction; - return this; - } - /** - * Sets the gas limit to be used for the SC Call inside the inner transaction - * - * @param {IGasLimit} gasLimit The gas limit to be used. The inner transaction needs to have the gas limit set to 0, - * so this field will specify the gas to be used for the SC call of the inner transaction - */ - setInnerTransactionGasLimit(gasLimit) { - this.innerTransactionGasLimit = gasLimit; - return this; - } - /** - * Sets the network config to be used for building the relayed v2 transaction - * - * @param {INetworkConfig} netConfig The network configuration to be used - */ - setNetworkConfig(netConfig) { - this.netConfig = netConfig; - return this; - } - /** - * Sets the address of the relayer (the one that will actually pay the fee) - * - * @param relayerAddress - */ - setRelayerAddress(relayerAddress) { - this.relayerAddress = relayerAddress; - return this; - } - /** - * (optional) Sets the nonce of the relayer - * - * @param relayerNonce - */ - setRelayerNonce(relayerNonce) { - this.relayerNonce = relayerNonce; - return this; - } - /** - * Tries to build the relayed v2 transaction based on the previously set fields. - * It returns a transaction that isn't signed - * - * @throws ErrInvalidRelayedV2BuilderArguments - * @throws ErrGasLimitShouldBe0ForInnerTransaction - * @return Transaction - */ - build() { - if (!this.innerTransaction || !this.innerTransactionGasLimit || !this.relayerAddress || !this.netConfig || !this.innerTransaction.getSignature()) { - throw new errors_1.ErrInvalidRelayedV2BuilderArguments(); - } - if (this.innerTransaction.getGasLimit() != 0) { - throw new errors_1.ErrGasLimitShouldBe0ForInnerTransaction(); - } - const { argumentsString } = new smartcontracts_1.ArgSerializer().valuesToString([ - new smartcontracts_1.AddressValue(this.innerTransaction.getReceiver()), - new smartcontracts_1.U64Value(this.innerTransaction.getNonce().valueOf()), - new smartcontracts_1.BytesValue(this.innerTransaction.getData().valueOf()), - new smartcontracts_1.BytesValue(this.innerTransaction.getSignature()) - ]); - const data = `relayedTxV2@${argumentsString}`; - const payload = new transactionPayload_1.TransactionPayload(data); - let relayedTransaction = new transaction_1.Transaction({ - sender: this.relayerAddress, - receiver: this.innerTransaction.getSender(), - value: 0, - gasLimit: this.innerTransactionGasLimit.valueOf() + this.netConfig.MinGasLimit + this.netConfig.GasPerDataByte * payload.length(), - data: payload, - chainID: this.netConfig.ChainID, - version: this.innerTransaction.getVersion(), - options: this.innerTransaction.getOptions() - }); - if (this.relayerNonce) { - relayedTransaction.setNonce(this.relayerNonce); - } - return relayedTransaction; - } - }; - exports2.RelayedTransactionV2Builder = RelayedTransactionV2Builder; - } -}); - -// node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js -var require_smartContractQueriesController = __commonJS({ - "node_modules/@multiversx/sdk-core/out/smartContractQueriesController.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.SmartContractQueriesController = void 0; - var errors_1 = require_errors(); - var smartContractQuery_1 = require_smartContractQuery(); - var smartcontracts_1 = require_smartcontracts(); - var SmartContractQueriesController = class { - constructor(options) { - this.abi = options.abi; - this.queryRunner = options.queryRunner; - this.legacyResultsParser = new smartcontracts_1.ResultsParser(); - } - createQuery(options) { - const preparedArguments = this.encodeArguments(options.function, options.arguments); - return new smartContractQuery_1.SmartContractQuery({ - contract: options.contract, - caller: options.caller, - function: options.function, - arguments: preparedArguments, - value: options.value - }); - } - encodeArguments(functionName, args) { - const endpoint = this.abi?.getEndpoint(functionName); - if (endpoint) { - const typedArgs = smartcontracts_1.NativeSerializer.nativeToTypedValues(args, endpoint); - return new smartcontracts_1.ArgSerializer().valuesToBuffers(typedArgs); - } - if (this.areArgsOfTypedValue(args)) { - return new smartcontracts_1.ArgSerializer().valuesToBuffers(args); - } - if (this.areArgsBuffers(args)) { - return args.map((arg) => import_buffer.Buffer.from(arg)); - } - throw new errors_1.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers"); - } - areArgsOfTypedValue(args) { - for (const arg of args) { - if (!arg.belongsToTypesystem) { - return false; - } - } - return true; - } - areArgsBuffers(args) { - for (const arg of args) { - if (!ArrayBuffer.isView(arg)) { - return false; - } - } - return true; - } - async runQuery(query) { - const queryResponse = await this.queryRunner.runQuery(query); - return queryResponse; - } - parseQueryResponse(response) { - if (!this.abi) { - return response.returnDataParts; - } - const legacyQueryResponse = { - returnCode: response.returnCode, - returnMessage: response.returnMessage, - getReturnDataParts: () => response.returnDataParts.map((part) => import_buffer.Buffer.from(part)) - }; - const functionName = response.function; - const endpoint = this.abi.getEndpoint(functionName); - const legacyBundle = this.legacyResultsParser.parseQueryResponse(legacyQueryResponse, endpoint); - const nativeValues = legacyBundle.values.map((value) => value.valueOf()); - return nativeValues; - } - }; - exports2.SmartContractQueriesController = SmartContractQueriesController; - } -}); - -// node_modules/@multiversx/sdk-core/out/index.js -var require_out = __commonJS({ - "node_modules/@multiversx/sdk-core/out/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - require_globals(); - __exportStar2(require_account(), exports2); - __exportStar2(require_adapters(), exports2); - __exportStar2(require_address(), exports2); - __exportStar2(require_asyncTimer(), exports2); - __exportStar2(require_converters(), exports2); - __exportStar2(require_errors(), exports2); - __exportStar2(require_gasEstimator(), exports2); - __exportStar2(require_interface2(), exports2); - __exportStar2(require_interfaceOfNetwork(), exports2); - __exportStar2(require_logger(), exports2); - __exportStar2(require_message(), exports2); - __exportStar2(require_networkParams(), exports2); - __exportStar2(require_relayedTransactionV1Builder(), exports2); - __exportStar2(require_relayedTransactionV2Builder(), exports2); - __exportStar2(require_signableMessage(), exports2); - __exportStar2(require_smartContractQueriesController(), exports2); - __exportStar2(require_smartcontracts(), exports2); - __exportStar2(require_tokenOperations(), exports2); - __exportStar2(require_tokens(), exports2); - __exportStar2(require_transaction(), exports2); - __exportStar2(require_transactionComputer(), exports2); - __exportStar2(require_transactionPayload(), exports2); - __exportStar2(require_transactionWatcher(), exports2); - __exportStar2(require_transactionsFactories(), exports2); - __exportStar2(require_transactionsOutcomeParsers(), exports2); - __exportStar2(require_utils2(), exports2); - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js -var require_utils4 = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/utils.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.sleep = exports2.getMetadata = exports2.applyTransactionSignature = exports2.getAddressFromSession = exports2.addressIsValid = exports2.getConnectionParams = exports2.getCurrentTopic = exports2.getCurrentSession = void 0; - var sdk_core_1 = require_out(); - var signature_1 = require_signature(); - var utils_1 = require_index_cjs2(); - var constants_1 = require_constants6(); - var errors_1 = require_errors3(); - var logger_1 = require_logger2(); - var operation_1 = require_operation2(); - function getCurrentSession(chainId, client) { - if (!client) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - const acknowledgedSessions = client.find(getConnectionParams(chainId)).filter((s2) => s2.acknowledged); - if (acknowledgedSessions.length > 0) { - const lastKeyIndex = acknowledgedSessions.length - 1; - const session = acknowledgedSessions[lastKeyIndex]; - return session; - } - if (client.session.length > 0) { - const lastKeyIndex = client.session.keys.length - 1; - const session = client.session.get(client.session.keys[lastKeyIndex]); - return session; - } - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - exports2.getCurrentSession = getCurrentSession; - function getCurrentTopic(chainId, client) { - if (!client) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - const session = getCurrentSession(chainId, client); - if (!(session === null || session === void 0 ? void 0 : session.topic)) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - return session.topic; - } - exports2.getCurrentTopic = getCurrentTopic; - function getConnectionParams(chainId, options) { - var _a, _b, _c; - const methods = [ - ...constants_1.WALLETCONNECT_MULTIVERSX_METHODS, - ...(_a = options === null || options === void 0 ? void 0 : options.methods) !== null && _a !== void 0 ? _a : [] - ]; - if (!((_b = options === null || options === void 0 ? void 0 : options.methods) === null || _b === void 0 ? void 0 : _b.includes(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN))) { - methods.push(operation_1.OptionalOperation.SIGN_LOGIN_TOKEN); - } - const chains = [`${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${chainId}`]; - const events = (_c = options === null || options === void 0 ? void 0 : options.events) !== null && _c !== void 0 ? _c : []; - return { - requiredNamespaces: { - [constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]: { - methods, - chains, - events - } - } - }; - } - exports2.getConnectionParams = getConnectionParams; - function addressIsValid(destinationAddress) { - try { - const address = sdk_core_1.Address.fromBech32(destinationAddress); - return !address.isEmpty(); - } catch (_a) { - return false; - } - } - exports2.addressIsValid = addressIsValid; - function getAddressFromSession(session) { - const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; - if (selectedNamespace && selectedNamespace.accounts) { - const currentSession = selectedNamespace.accounts[0]; - const [namespace, reference, address] = currentSession.split(":"); - return address; - } - return ""; - } - exports2.getAddressFromSession = getAddressFromSession; - function applyTransactionSignature({ transaction, response }) { - if (!response) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - } - const { signature, guardianSignature, version: version2, options, guardian } = response; - const transactionGuardian = transaction.getGuardian().bech32(); - if (transactionGuardian && transactionGuardian !== guardian) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian); - } - if (guardian) { - transaction.setGuardian(sdk_core_1.Address.fromBech32(guardian)); - } - if (version2) { - transaction.setVersion(version2); - } - if (options != null) { - transaction.setOptions(options); - } - transaction.applySignature(new signature_1.Signature(signature)); - if (guardianSignature) { - transaction.applyGuardianSignature(new signature_1.Signature(guardianSignature)); - } - return transaction; - } - exports2.applyTransactionSignature = applyTransactionSignature; - function getMetadata(metadata) { - if (metadata) { - return Object.assign(Object.assign({}, metadata), { url: utils_1.getAppMetadata().url }); - } - return; - } - exports2.getMetadata = getMetadata; - function sleep(timeout) { - return __awaiter2(this, void 0, void 0, function* () { - return yield new Promise((resolve) => setTimeout(() => { - resolve(); - }, timeout)); - }); - } - exports2.sleep = sleep; - } -}); - -// node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js -var require_walletConnectV2Provider = __commonJS({ - "node_modules/@multiversx/sdk-wallet-connect-provider/out/walletConnectV2Provider.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WalletConnectV2Provider = exports2.OptionalOperation = exports2.Operation = exports2.WalletConnectV2ProviderErrorMessagesEnum = void 0; - var signature_1 = require_signature(); - var sign_client_1 = __importDefault2(require_index_cjs4()); - var utils_1 = require_index_cjs2(); - var constants_1 = require_constants6(); - var errors_1 = require_errors3(); - Object.defineProperty(exports2, "WalletConnectV2ProviderErrorMessagesEnum", { enumerable: true, get: function() { - return errors_1.WalletConnectV2ProviderErrorMessagesEnum; - } }); - var logger_1 = require_logger2(); - var operation_1 = require_operation2(); - Object.defineProperty(exports2, "Operation", { enumerable: true, get: function() { - return operation_1.Operation; - } }); - Object.defineProperty(exports2, "OptionalOperation", { enumerable: true, get: function() { - return operation_1.OptionalOperation; - } }); - var utils_2 = require_utils4(); - var WalletConnectV2Provider5 = class { - constructor(onClientConnect, chainId, walletConnectV2Relay, walletConnectV2ProjectId, options) { - this.chainId = ""; - this.address = ""; - this.signature = ""; - this.isInitializing = false; - this.processingTopic = ""; - this.options = {}; - this.onClientConnect = onClientConnect; - this.chainId = chainId; - this.walletConnectV2Relay = walletConnectV2Relay; - this.walletConnectV2ProjectId = walletConnectV2ProjectId; - this.options = options; - } - reset() { - this.address = ""; - this.signature = ""; - this.walletConnector = void 0; - this.session = void 0; - this.pairings = void 0; - } - /** - * Initiates WalletConnect client. - */ - init() { - var _a, _b; - return __awaiter2(this, void 0, void 0, function* () { - if (this.isInitialized()) { - return this.isInitialized(); - } else { - try { - if (!this.isInitializing) { - this.isInitializing = true; - this.reset(); - const metadata = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.metadata) ? { - metadata: utils_2.getMetadata((_b = this.options) === null || _b === void 0 ? void 0 : _b.metadata) - } : {}; - const client = yield sign_client_1.default.init(Object.assign(Object.assign(Object.assign({}, this.options), { relayUrl: this.walletConnectV2Relay, projectId: this.walletConnectV2ProjectId }), metadata)); - this.walletConnector = client; - this.isInitializing = false; - yield this.subscribeToEvents(client); - yield this.checkPersistedState(client); - } - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToInit); - } finally { - this.isInitializing = false; - return this.isInitialized(); - } - } - }); - } - /** - * Returns true if init() was previously called successfully - */ - isInitialized() { - return !!this.walletConnector && !this.isInitializing; - } - /** - * Returns true if provider is initialized and a valid session is set - */ - isConnected() { - return new Promise((resolve, _4) => resolve(Boolean(this.isInitialized() && typeof this.session !== "undefined"))); - } - connect(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - const connectParams = utils_2.getConnectionParams(this.chainId, options); - try { - const response = yield this.walletConnector.connect(Object.assign({ pairingTopic: options === null || options === void 0 ? void 0 : options.topic }, connectParams)); - return response; - } catch (error) { - this.reset(); - logger_1.Logger.error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); - throw new Error((options === null || options === void 0 ? void 0 : options.topic) ? errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting : errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect); - } - }); - } - login(options) { - var _a; - return __awaiter2(this, void 0, void 0, function* () { - this.isInitializing = true; - if (typeof this.walletConnector === "undefined") { - yield this.connect(); - } - if (typeof this.walletConnector === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session !== "undefined") { - yield this.logout({ topic: (_a = this.session) === null || _a === void 0 ? void 0 : _a.topic }); - } - try { - if (options && options.approval) { - const session = yield options.approval(); - if (options.token) { - yield utils_2.sleep(constants_1.WALLETCONNECT_SIGN_LOGIN_DELAY); - const address = utils_2.getAddressFromSession(session); - const selectedNamespace = session.namespaces[constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE]; - const method = selectedNamespace.methods.includes(operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN) ? operation_1.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN : operation_1.OptionalOperation.SIGN_LOGIN_TOKEN; - const { signature } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: session.topic, - request: { - method, - params: { - token: options.token, - address - } - } - }); - if (!signature) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken); - } - return yield this.onSessionConnected({ - session, - signature - }); - } - return yield this.onSessionConnected({ - session, - signature: "" - }); - } - } catch (error) { - this.reset(); - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin); - } finally { - this.isInitializing = false; - } - return ""; - }); - } - /** - * Mocks a logout request by returning true - */ - logout(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - try { - if (this.processingTopic === ((options === null || options === void 0 ? void 0 : options.topic) || utils_2.getCurrentTopic(this.chainId, this.walletConnector))) { - return true; - } - if (options === null || options === void 0 ? void 0 : options.topic) { - this.processingTopic = options.topic; - yield this.walletConnector.disconnect({ - topic: options.topic, - reason: utils_1.getSdkError("USER_DISCONNECTED") - }); - } else { - const currentSessionTopic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); - this.processingTopic = currentSessionTopic; - yield this.walletConnector.disconnect({ - topic: currentSessionTopic, - reason: utils_1.getSdkError("USER_DISCONNECTED") - }); - this.reset(); - yield this.cleanupPendingPairings({ deletePairings: true }); - } - } catch (_a) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut); - } finally { - this.processingTopic = ""; - } - return true; - }); - } - /** - * Fetches the WalletConnect address - */ - getAddress() { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - return this.address; - }); - } - /** - * Fetches the WalletConnect signature - */ - getSignature() { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - return this.signature; - }); - } - /** - * Fetches the WalletConnect pairings - */ - getPairings() { - var _a, _b, _c, _d, _e; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - return (_e = (_d = (_c = (_b = (_a = this.walletConnector) === null || _a === void 0 ? void 0 : _a.core) === null || _b === void 0 ? void 0 : _b.pairing) === null || _c === void 0 ? void 0 : _c.pairings) === null || _d === void 0 ? void 0 : _d.getAll({ active: true })) !== null && _e !== void 0 ? _e : []; - }); - } - /** - * Signs a message and returns it signed - * @param message - */ - signMessage(message) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - try { - const address = yield this.getAddress(); - const { signature } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: { - method: operation_1.Operation.SIGN_MESSAGE, - params: { - address, - message: message.message.toString() - } - } - }); - if (!signature) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse); - } - try { - message.applySignature(new signature_1.Signature(signature)); - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature); - } - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToSign); - } - return message; - }); - } - /** - * Signs a transaction and returns it signed - * @param transaction - */ - signTransaction(transaction) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - const plainTransaction = transaction.toPlainObject(); - if (this.chainId !== transaction.getChainID().valueOf()) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - } - try { - const response = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: { - method: operation_1.Operation.SIGN_TRANSACTION, - params: { - transaction: plainTransaction - } - } - }); - return utils_2.applyTransactionSignature({ transaction, response }); - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); - } - }); - } - /** - * Signs an array of transactions and returns it signed - * @param transactions - */ - signTransactions(transactions) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - const plainTransactions = transactions.map((transaction) => { - if (this.chainId !== transaction.getChainID().valueOf()) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain); - } - return transaction.toPlainObject(); - }); - try { - const { signatures } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: { - method: operation_1.Operation.SIGN_TRANSACTIONS, - params: { - transactions: plainTransactions - } - } - }); - if (!signatures) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - } - if (!Array.isArray(signatures) || transactions.length !== signatures.length) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse); - } - for (const [index, transaction] of transactions.entries()) { - const response = signatures[index]; - utils_2.applyTransactionSignature({ transaction, response }); - } - return transactions; - } catch (error) { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.transactionError); - } - }); - } - /** - * Sends a custom request - * @param request - */ - sendCustomRequest(options) { - var _a; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - this.onClientConnect.onClientLogout(); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - if ((_a = options === null || options === void 0 ? void 0 : options.request) === null || _a === void 0 ? void 0 : _a.method) { - try { - const request = Object.assign({}, options.request); - let { method } = request; - const { response } = yield this.walletConnector.request({ - chainId: `${constants_1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`, - topic: utils_2.getCurrentTopic(this.chainId, this.walletConnector), - request: Object.assign(Object.assign({}, request), { method }) - }); - if (!response) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); - } - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse); - } - return; - } - }); - } - /** - * Ping helper - */ - ping() { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (typeof this.session === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected); - } - try { - const topic = utils_2.getCurrentTopic(this.chainId, this.walletConnector); - yield this.walletConnector.ping({ - topic - }); - return true; - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.pingFailed); - return false; - } - }); - } - loginAccount(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (!options) { - return ""; - } - if (utils_2.addressIsValid(options.address)) { - this.address = options.address; - if (options.signature) { - this.signature = options.signature; - } - this.onClientConnect.onClientLogin(); - return this.address; - } - logger_1.Logger.error(`${errors_1.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${options.address}`); - if (this.walletConnector) { - yield this.logout(); - } - return ""; - }); - } - onSessionConnected(options) { - return __awaiter2(this, void 0, void 0, function* () { - if (!options) { - return ""; - } - this.session = options.session; - const address = utils_2.getAddressFromSession(options.session); - if (address) { - yield this.loginAccount({ address, signature: options.signature }); - return address; - } - return ""; - }); - } - handleTopicUpdateEvent({ topic }) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - return; - } - try { - const existingPairings = yield this.getPairings(); - if (this.address && !this.isInitializing && existingPairings) { - if ((existingPairings === null || existingPairings === void 0 ? void 0 : existingPairings.length) === 0) { - this.onClientConnect.onClientLogout(); - } else { - const lastActivePairing = existingPairings[existingPairings.length - 1]; - if ((lastActivePairing === null || lastActivePairing === void 0 ? void 0 : lastActivePairing.topic) === topic) { - this.onClientConnect.onClientLogout(); - } - } - } - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic); - } finally { - this.pairings = yield this.getPairings(); - } - }); - } - handleSessionEvents({ topic, params }) { - var _a; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - if (this.session && ((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) !== topic) { - return; - } - const { event } = params; - if ((event === null || event === void 0 ? void 0 : event.name) && utils_2.getCurrentTopic(this.chainId, this.walletConnector) === topic) { - const eventData = event.data; - this.onClientConnect.onClientEvent(eventData); - } - }); - } - subscribeToEvents(client) { - var _a, _b, _c, _d; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof client === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - try { - client.on("session_update", ({ topic, params }) => { - var _a2; - if (!this.session || ((_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.topic) !== topic) { - return; - } - const { namespaces } = params; - const _session = client.session.get(topic); - const updatedSession = Object.assign(Object.assign({}, _session), { namespaces }); - this.onSessionConnected({ session: updatedSession }); - }); - client.on("session_event", this.handleSessionEvents.bind(this)); - client.on("session_delete", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { - var _e; - if (this.isInitializing) { - this.onClientConnect.onClientLogout(); - this.reset(); - } - if (!this.session || ((_e = this.session) === null || _e === void 0 ? void 0 : _e.topic) !== topic) { - return; - } - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted); - this.onClientConnect.onClientLogout(); - this.reset(); - yield this.cleanupPendingPairings({ deletePairings: true }); - })); - client.on("session_expire", ({ topic }) => __awaiter2(this, void 0, void 0, function* () { - var _f; - if (!this.session || ((_f = this.session) === null || _f === void 0 ? void 0 : _f.topic) !== topic) { - return; - } - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired); - this.onClientConnect.onClientLogout(); - this.reset(); - yield this.cleanupPendingPairings({ deletePairings: true }); - })); - (_b = (_a = client.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.events.on("pairing_delete", this.handleTopicUpdateEvent.bind(this)); - (_d = (_c = client.core) === null || _c === void 0 ? void 0 : _c.pairing) === null || _d === void 0 ? void 0 : _d.events.on("pairing_expire", this.handleTopicUpdateEvent.bind(this)); - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent); - } - }); - } - checkPersistedState(client) { - return __awaiter2(this, void 0, void 0, function* () { - if (typeof client === "undefined") { - throw new Error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.notInitialized); - } - this.pairings = yield this.getPairings(); - if (typeof this.session !== "undefined") { - return; - } - if (client.session.length && !this.address && !this.isInitializing) { - const session = utils_2.getCurrentSession(this.chainId, client); - if (session) { - yield this.onSessionConnected({ session }); - return session; - } - } - return; - }); - } - cleanupPendingPairings(options = {}) { - var _a, _b, _c, _d, _e, _f, _g, _h; - return __awaiter2(this, void 0, void 0, function* () { - if (typeof this.walletConnector === "undefined") { - return; - } - try { - const inactivePairings = (_c = (_b = (_a = this.walletConnector.core) === null || _a === void 0 ? void 0 : _a.pairing) === null || _b === void 0 ? void 0 : _b.pairings) === null || _c === void 0 ? void 0 : _c.getAll({ active: false }); - if (!utils_1.isValidArray(inactivePairings)) { - return; - } - for (const pairing of inactivePairings) { - if (options.deletePairings) { - (_e = (_d = this.walletConnector.core) === null || _d === void 0 ? void 0 : _d.expirer) === null || _e === void 0 ? void 0 : _e.set(pairing.topic, 0); - } else { - try { - yield (_h = (_g = (_f = this.walletConnector.core) === null || _f === void 0 ? void 0 : _f.relayer) === null || _g === void 0 ? void 0 : _g.subscriber) === null || _h === void 0 ? void 0 : _h.unsubscribe(pairing.topic); - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); - } - } - } - } catch (error) { - logger_1.Logger.error(errors_1.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup); - } - }); - } - }; - exports2.WalletConnectV2Provider = WalletConnectV2Provider5; - } -}); - -// node_modules/has-symbols/shams.js -var require_shams = __commonJS({ - "node_modules/has-symbols/shams.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function hasSymbols() { - if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { - return false; - } - if (typeof Symbol.iterator === "symbol") { - return true; - } - var obj = {}; - var sym = Symbol("test"); - var symObj = Object(sym); - if (typeof sym === "string") { - return false; - } - if (Object.prototype.toString.call(sym) !== "[object Symbol]") { - return false; - } - if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { - return false; - } - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { - return false; - } - if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { - return false; - } - if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { - return false; - } - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { - return false; - } - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { - return false; - } - if (typeof Object.getOwnPropertyDescriptor === "function") { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/has-symbols/index.js -var require_has_symbols = __commonJS({ - "node_modules/has-symbols/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var origSymbol = typeof Symbol !== "undefined" && Symbol; - var hasSymbolSham = require_shams(); - module2.exports = function hasNativeSymbols() { - if (typeof origSymbol !== "function") { - return false; - } - if (typeof Symbol !== "function") { - return false; - } - if (typeof origSymbol("foo") !== "symbol") { - return false; - } - if (typeof Symbol("bar") !== "symbol") { - return false; - } - return hasSymbolSham(); - }; - } -}); - -// node_modules/has-proto/index.js -var require_has_proto = __commonJS({ - "node_modules/has-proto/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var test = { - foo: {} - }; - var $Object = Object; - module2.exports = function hasProto() { - return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); - }; - } -}); - -// node_modules/function-bind/implementation.js -var require_implementation = __commonJS({ - "node_modules/function-bind/implementation.js"(exports2, module2) { - "use strict"; - init_shim(); - var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; - var toStr = Object.prototype.toString; - var max = Math.max; - var funcType = "[object Function]"; - var concatty = function concatty2(a3, b4) { - var arr = []; - for (var i2 = 0; i2 < a3.length; i2 += 1) { - arr[i2] = a3[i2]; - } - for (var j2 = 0; j2 < b4.length; j2 += 1) { - arr[j2 + a3.length] = b4[j2]; - } - return arr; - }; - var slicy = function slicy2(arrLike, offset) { - var arr = []; - for (var i2 = offset || 0, j2 = 0; i2 < arrLike.length; i2 += 1, j2 += 1) { - arr[j2] = arrLike[i2]; - } - return arr; - }; - var joiny = function(arr, joiner) { - var str = ""; - for (var i2 = 0; i2 < arr.length; i2 += 1) { - str += arr[i2]; - if (i2 + 1 < arr.length) { - str += joiner; - } - } - return str; - }; - module2.exports = function bind(that) { - var target = this; - if (typeof target !== "function" || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - var bound; - var binder = function() { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - }; - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i2 = 0; i2 < boundLength; i2++) { - boundArgs[i2] = "$" + i2; - } - bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); - if (target.prototype) { - var Empty = function Empty2() { - }; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - return bound; - }; - } -}); - -// node_modules/function-bind/index.js -var require_function_bind = __commonJS({ - "node_modules/function-bind/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var implementation = require_implementation(); - module2.exports = Function.prototype.bind || implementation; - } -}); - -// node_modules/hasown/index.js -var require_hasown = __commonJS({ - "node_modules/hasown/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var call = Function.prototype.call; - var $hasOwn = Object.prototype.hasOwnProperty; - var bind = require_function_bind(); - module2.exports = bind.call(call, $hasOwn); - } -}); - -// node_modules/get-intrinsic/index.js -var require_get_intrinsic = __commonJS({ - "node_modules/get-intrinsic/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var undefined2; - var $SyntaxError = SyntaxError; - var $Function = Function; - var $TypeError = TypeError; - var getEvalledConstructor = function(expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); - } catch (e2) { - } - }; - var $gOPD = Object.getOwnPropertyDescriptor; - if ($gOPD) { - try { - $gOPD({}, ""); - } catch (e2) { - $gOPD = null; - } - } - var throwTypeError = function() { - throw new $TypeError(); - }; - var ThrowTypeError = $gOPD ? function() { - try { - arguments.callee; - return throwTypeError; - } catch (calleeThrows) { - try { - return $gOPD(arguments, "callee").get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }() : throwTypeError; - var hasSymbols = require_has_symbols()(); - var hasProto = require_has_proto()(); - var getProto = Object.getPrototypeOf || (hasProto ? function(x3) { - return x3.__proto__; - } : null); - var needsEval = {}; - var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); - var INTRINSICS = { - "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, - "%Array%": Array, - "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, - "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, - "%AsyncFromSyncIteratorPrototype%": undefined2, - "%AsyncFunction%": needsEval, - "%AsyncGenerator%": needsEval, - "%AsyncGeneratorFunction%": needsEval, - "%AsyncIteratorPrototype%": needsEval, - "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, - "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, - "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, - "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, - "%Boolean%": Boolean, - "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, - "%Date%": Date, - "%decodeURI%": decodeURI, - "%decodeURIComponent%": decodeURIComponent, - "%encodeURI%": encodeURI, - "%encodeURIComponent%": encodeURIComponent, - "%Error%": Error, - "%eval%": eval, - // eslint-disable-line no-eval - "%EvalError%": EvalError, - "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, - "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, - "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, - "%Function%": $Function, - "%GeneratorFunction%": needsEval, - "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, - "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, - "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, - "%isFinite%": isFinite, - "%isNaN%": isNaN, - "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, - "%JSON%": typeof JSON === "object" ? JSON : undefined2, - "%Map%": typeof Map === "undefined" ? undefined2 : Map, - "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), - "%Math%": Math, - "%Number%": Number, - "%Object%": Object, - "%parseFloat%": parseFloat, - "%parseInt%": parseInt, - "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, - "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, - "%RangeError%": RangeError, - "%ReferenceError%": ReferenceError, - "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, - "%RegExp%": RegExp, - "%Set%": typeof Set === "undefined" ? undefined2 : Set, - "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), - "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, - "%String%": String, - "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, - "%Symbol%": hasSymbols ? Symbol : undefined2, - "%SyntaxError%": $SyntaxError, - "%ThrowTypeError%": ThrowTypeError, - "%TypedArray%": TypedArray, - "%TypeError%": $TypeError, - "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, - "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, - "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, - "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, - "%URIError%": URIError, - "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, - "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, - "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet - }; - if (getProto) { - try { - null.error; - } catch (e2) { - errorProto = getProto(getProto(e2)); - INTRINSICS["%Error.prototype%"] = errorProto; - } - } - var errorProto; - var doEval = function doEval2(name2) { - var value; - if (name2 === "%AsyncFunction%") { - value = getEvalledConstructor("async function () {}"); - } else if (name2 === "%GeneratorFunction%") { - value = getEvalledConstructor("function* () {}"); - } else if (name2 === "%AsyncGeneratorFunction%") { - value = getEvalledConstructor("async function* () {}"); - } else if (name2 === "%AsyncGenerator%") { - var fn = doEval2("%AsyncGeneratorFunction%"); - if (fn) { - value = fn.prototype; - } - } else if (name2 === "%AsyncIteratorPrototype%") { - var gen = doEval2("%AsyncGenerator%"); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } - INTRINSICS[name2] = value; - return value; - }; - var LEGACY_ALIASES = { - "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], - "%ArrayPrototype%": ["Array", "prototype"], - "%ArrayProto_entries%": ["Array", "prototype", "entries"], - "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], - "%ArrayProto_keys%": ["Array", "prototype", "keys"], - "%ArrayProto_values%": ["Array", "prototype", "values"], - "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], - "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], - "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], - "%BooleanPrototype%": ["Boolean", "prototype"], - "%DataViewPrototype%": ["DataView", "prototype"], - "%DatePrototype%": ["Date", "prototype"], - "%ErrorPrototype%": ["Error", "prototype"], - "%EvalErrorPrototype%": ["EvalError", "prototype"], - "%Float32ArrayPrototype%": ["Float32Array", "prototype"], - "%Float64ArrayPrototype%": ["Float64Array", "prototype"], - "%FunctionPrototype%": ["Function", "prototype"], - "%Generator%": ["GeneratorFunction", "prototype"], - "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], - "%Int8ArrayPrototype%": ["Int8Array", "prototype"], - "%Int16ArrayPrototype%": ["Int16Array", "prototype"], - "%Int32ArrayPrototype%": ["Int32Array", "prototype"], - "%JSONParse%": ["JSON", "parse"], - "%JSONStringify%": ["JSON", "stringify"], - "%MapPrototype%": ["Map", "prototype"], - "%NumberPrototype%": ["Number", "prototype"], - "%ObjectPrototype%": ["Object", "prototype"], - "%ObjProto_toString%": ["Object", "prototype", "toString"], - "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], - "%PromisePrototype%": ["Promise", "prototype"], - "%PromiseProto_then%": ["Promise", "prototype", "then"], - "%Promise_all%": ["Promise", "all"], - "%Promise_reject%": ["Promise", "reject"], - "%Promise_resolve%": ["Promise", "resolve"], - "%RangeErrorPrototype%": ["RangeError", "prototype"], - "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], - "%RegExpPrototype%": ["RegExp", "prototype"], - "%SetPrototype%": ["Set", "prototype"], - "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], - "%StringPrototype%": ["String", "prototype"], - "%SymbolPrototype%": ["Symbol", "prototype"], - "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], - "%TypedArrayPrototype%": ["TypedArray", "prototype"], - "%TypeErrorPrototype%": ["TypeError", "prototype"], - "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], - "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], - "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], - "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], - "%URIErrorPrototype%": ["URIError", "prototype"], - "%WeakMapPrototype%": ["WeakMap", "prototype"], - "%WeakSetPrototype%": ["WeakSet", "prototype"] - }; - var bind = require_function_bind(); - var hasOwn = require_hasown(); - var $concat = bind.call(Function.call, Array.prototype.concat); - var $spliceApply = bind.call(Function.apply, Array.prototype.splice); - var $replace = bind.call(Function.call, String.prototype.replace); - var $strSlice = bind.call(Function.call, String.prototype.slice); - var $exec = bind.call(Function.call, RegExp.prototype.exec); - var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; - var reEscapeChar = /\\(\\)?/g; - var stringToPath = function stringToPath2(string2) { - var first = $strSlice(string2, 0, 1); - var last = $strSlice(string2, -1); - if (first === "%" && last !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); - } else if (last === "%" && first !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); - } - var result = []; - $replace(string2, rePropName, function(match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; - }); - return result; - }; - var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) { - var intrinsicName = name2; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = "%" + alias[0] + "%"; - } - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === "undefined" && !allowMissing) { - throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!"); - } - return { - alias, - name: intrinsicName, - value - }; - } - throw new $SyntaxError("intrinsic " + name2 + " does not exist!"); - }; - module2.exports = function GetIntrinsic(name2, allowMissing) { - if (typeof name2 !== "string" || name2.length === 0) { - throw new $TypeError("intrinsic name must be a non-empty string"); - } - if (arguments.length > 1 && typeof allowMissing !== "boolean") { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - if ($exec(/^%?[^%]*%?$/, name2) === null) { - throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); - } - var parts = stringToPath(name2); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; - var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - for (var i2 = 1, isOwn = true; i2 < parts.length; i2 += 1) { - var part = parts[i2]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { - throw new $SyntaxError("property names with quotes must have matching quotes"); - } - if (part === "constructor" || !isOwn) { - skipFurtherCaching = true; - } - intrinsicBaseName += "." + part; - intrinsicRealName = "%" + intrinsicBaseName + "%"; - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available."); - } - return void 0; - } - if ($gOPD && i2 + 1 >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - if (isOwn && "get" in desc && !("originalValue" in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; - }; - } -}); - -// node_modules/has-property-descriptors/index.js -var require_has_property_descriptors = __commonJS({ - "node_modules/has-property-descriptors/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); - var hasPropertyDescriptors = function hasPropertyDescriptors2() { - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - return true; - } catch (e2) { - return false; - } - } - return false; - }; - hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { - if (!hasPropertyDescriptors()) { - return null; - } - try { - return $defineProperty([], "length", { value: 1 }).length !== 1; - } catch (e2) { - return true; - } - }; - module2.exports = hasPropertyDescriptors; - } -}); - -// node_modules/gopd/index.js -var require_gopd = __commonJS({ - "node_modules/gopd/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); - if ($gOPD) { - try { - $gOPD([], "length"); - } catch (e2) { - $gOPD = null; - } - } - module2.exports = $gOPD; - } -}); - -// node_modules/define-data-property/index.js -var require_define_data_property = __commonJS({ - "node_modules/define-data-property/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var hasPropertyDescriptors = require_has_property_descriptors()(); - var GetIntrinsic = require_get_intrinsic(); - var $defineProperty = hasPropertyDescriptors && GetIntrinsic("%Object.defineProperty%", true); - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - } catch (e2) { - $defineProperty = false; - } - } - var $SyntaxError = GetIntrinsic("%SyntaxError%"); - var $TypeError = GetIntrinsic("%TypeError%"); - var gopd = require_gopd(); - module2.exports = function defineDataProperty(obj, property, value) { - if (!obj || typeof obj !== "object" && typeof obj !== "function") { - throw new $TypeError("`obj` must be an object or a function`"); - } - if (typeof property !== "string" && typeof property !== "symbol") { - throw new $TypeError("`property` must be a string or a symbol`"); - } - if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) { - throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null"); - } - if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) { - throw new $TypeError("`nonWritable`, if provided, must be a boolean or null"); - } - if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) { - throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null"); - } - if (arguments.length > 6 && typeof arguments[6] !== "boolean") { - throw new $TypeError("`loose`, if provided, must be a boolean"); - } - var nonEnumerable = arguments.length > 3 ? arguments[3] : null; - var nonWritable = arguments.length > 4 ? arguments[4] : null; - var nonConfigurable = arguments.length > 5 ? arguments[5] : null; - var loose = arguments.length > 6 ? arguments[6] : false; - var desc = !!gopd && gopd(obj, property); - if ($defineProperty) { - $defineProperty(obj, property, { - configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, - enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, - value, - writable: nonWritable === null && desc ? desc.writable : !nonWritable - }); - } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) { - obj[property] = value; - } else { - throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable."); - } - }; - } -}); - -// node_modules/set-function-length/index.js -var require_set_function_length = __commonJS({ - "node_modules/set-function-length/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var define2 = require_define_data_property(); - var hasDescriptors = require_has_property_descriptors()(); - var gOPD = require_gopd(); - var $TypeError = GetIntrinsic("%TypeError%"); - var $floor = GetIntrinsic("%Math.floor%"); - module2.exports = function setFunctionLength(fn, length2) { - if (typeof fn !== "function") { - throw new $TypeError("`fn` is not a function"); - } - if (typeof length2 !== "number" || length2 < 0 || length2 > 4294967295 || $floor(length2) !== length2) { - throw new $TypeError("`length` must be a positive 32-bit integer"); - } - var loose = arguments.length > 2 && !!arguments[2]; - var functionLengthIsConfigurable = true; - var functionLengthIsWritable = true; - if ("length" in fn && gOPD) { - var desc = gOPD(fn, "length"); - if (desc && !desc.configurable) { - functionLengthIsConfigurable = false; - } - if (desc && !desc.writable) { - functionLengthIsWritable = false; - } - } - if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { - if (hasDescriptors) { - define2( - /** @type {Parameters[0]} */ - fn, - "length", - length2, - true, - true - ); - } else { - define2( - /** @type {Parameters[0]} */ - fn, - "length", - length2 - ); - } - } - return fn; - }; - } -}); - -// node_modules/call-bind/index.js -var require_call_bind = __commonJS({ - "node_modules/call-bind/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var bind = require_function_bind(); - var GetIntrinsic = require_get_intrinsic(); - var setFunctionLength = require_set_function_length(); - var $TypeError = GetIntrinsic("%TypeError%"); - var $apply = GetIntrinsic("%Function.prototype.apply%"); - var $call = GetIntrinsic("%Function.prototype.call%"); - var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind.call($call, $apply); - var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); - var $max = GetIntrinsic("%Math.max%"); - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - } catch (e2) { - $defineProperty = null; - } - } - module2.exports = function callBind(originalFunction) { - if (typeof originalFunction !== "function") { - throw new $TypeError("a function is required"); - } - var func = $reflectApply(bind, $call, arguments); - return setFunctionLength( - func, - 1 + $max(0, originalFunction.length - (arguments.length - 1)), - true - ); - }; - var applyBind = function applyBind2() { - return $reflectApply(bind, $apply, arguments); - }; - if ($defineProperty) { - $defineProperty(module2.exports, "apply", { value: applyBind }); - } else { - module2.exports.apply = applyBind; - } - } -}); - -// node_modules/call-bind/callBound.js -var require_callBound = __commonJS({ - "node_modules/call-bind/callBound.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var callBind = require_call_bind(); - var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf")); - module2.exports = function callBoundIntrinsic(name2, allowMissing) { - var intrinsic = GetIntrinsic(name2, !!allowMissing); - if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) { - return callBind(intrinsic); - } - return intrinsic; - }; - } -}); - -// (disabled):node_modules/object-inspect/util.inspect -var require_util2 = __commonJS({ - "(disabled):node_modules/object-inspect/util.inspect"() { - init_shim(); - } -}); - -// node_modules/object-inspect/index.js -var require_object_inspect = __commonJS({ - "node_modules/object-inspect/index.js"(exports2, module2) { - init_shim(); - var hasMap = typeof Map === "function" && Map.prototype; - var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; - var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; - var mapForEach = hasMap && Map.prototype.forEach; - var hasSet = typeof Set === "function" && Set.prototype; - var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; - var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; - var setForEach = hasSet && Set.prototype.forEach; - var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; - var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; - var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; - var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; - var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; - var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; - var booleanValueOf = Boolean.prototype.valueOf; - var objectToString = Object.prototype.toString; - var functionToString = Function.prototype.toString; - var $match = String.prototype.match; - var $slice = String.prototype.slice; - var $replace = String.prototype.replace; - var $toUpperCase = String.prototype.toUpperCase; - var $toLowerCase = String.prototype.toLowerCase; - var $test = RegExp.prototype.test; - var $concat = Array.prototype.concat; - var $join = Array.prototype.join; - var $arrSlice = Array.prototype.slice; - var $floor = Math.floor; - var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; - var gOPS = Object.getOwnPropertySymbols; - var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; - var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; - var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; - var isEnumerable = Object.prototype.propertyIsEnumerable; - var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O3) { - return O3.__proto__; - } : null); - function addNumericSeparator(num, str) { - if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { - return str; - } - var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; - if (typeof num === "number") { - var int = num < 0 ? -$floor(-num) : $floor(num); - if (int !== num) { - var intStr = String(int); - var dec = $slice.call(str, intStr.length + 1); - return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); - } - } - return $replace.call(str, sepRegex, "$&_"); - } - var utilInspect = require_util2(); - var inspectCustom = utilInspect.custom; - var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; - module2.exports = function inspect_(obj, options, depth, seen) { - var opts = options || {}; - if (has(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) { - throw new TypeError('option "quoteStyle" must be "single" or "double"'); - } - if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { - throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); - } - var customInspect = has(opts, "customInspect") ? opts.customInspect : true; - if (typeof customInspect !== "boolean" && customInspect !== "symbol") { - throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); - } - if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { - throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); - } - if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { - throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); - } - var numericSeparator = opts.numericSeparator; - if (typeof obj === "undefined") { - return "undefined"; - } - if (obj === null) { - return "null"; - } - if (typeof obj === "boolean") { - return obj ? "true" : "false"; - } - if (typeof obj === "string") { - return inspectString(obj, opts); - } - if (typeof obj === "number") { - if (obj === 0) { - return Infinity / obj > 0 ? "0" : "-0"; - } - var str = String(obj); - return numericSeparator ? addNumericSeparator(obj, str) : str; - } - if (typeof obj === "bigint") { - var bigIntStr = String(obj) + "n"; - return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; - } - var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; - if (typeof depth === "undefined") { - depth = 0; - } - if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { - return isArray(obj) ? "[Array]" : "[Object]"; - } - var indent = getIndent(opts, depth); - if (typeof seen === "undefined") { - seen = []; - } else if (indexOf(seen, obj) >= 0) { - return "[Circular]"; - } - function inspect(value, from3, noIndent) { - if (from3) { - seen = $arrSlice.call(seen); - seen.push(from3); - } - if (noIndent) { - var newOpts = { - depth: opts.depth - }; - if (has(opts, "quoteStyle")) { - newOpts.quoteStyle = opts.quoteStyle; - } - return inspect_(value, newOpts, depth + 1, seen); - } - return inspect_(value, opts, depth + 1, seen); - } - if (typeof obj === "function" && !isRegExp(obj)) { - var name2 = nameOf(obj); - var keys2 = arrObjKeys(obj, inspect); - return "[Function" + (name2 ? ": " + name2 : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : ""); - } - if (isSymbol(obj)) { - var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); - return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; - } - if (isElement(obj)) { - var s2 = "<" + $toLowerCase.call(String(obj.nodeName)); - var attrs = obj.attributes || []; - for (var i2 = 0; i2 < attrs.length; i2++) { - s2 += " " + attrs[i2].name + "=" + wrapQuotes(quote(attrs[i2].value), "double", opts); - } - s2 += ">"; - if (obj.childNodes && obj.childNodes.length) { - s2 += "..."; - } - s2 += ""; - return s2; - } - if (isArray(obj)) { - if (obj.length === 0) { - return "[]"; - } - var xs = arrObjKeys(obj, inspect); - if (indent && !singleLineValues(xs)) { - return "[" + indentedJoin(xs, indent) + "]"; - } - return "[ " + $join.call(xs, ", ") + " ]"; - } - if (isError(obj)) { - var parts = arrObjKeys(obj, inspect); - if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { - return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; - } - if (parts.length === 0) { - return "[" + String(obj) + "]"; - } - return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; - } - if (typeof obj === "object" && customInspect) { - if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { - return utilInspect(obj, { depth: maxDepth - depth }); - } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { - return obj.inspect(); - } - } - if (isMap(obj)) { - var mapParts = []; - if (mapForEach) { - mapForEach.call(obj, function(value, key) { - mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); - }); - } - return collectionOf("Map", mapSize.call(obj), mapParts, indent); - } - if (isSet(obj)) { - var setParts = []; - if (setForEach) { - setForEach.call(obj, function(value) { - setParts.push(inspect(value, obj)); - }); - } - return collectionOf("Set", setSize.call(obj), setParts, indent); - } - if (isWeakMap(obj)) { - return weakCollectionOf("WeakMap"); - } - if (isWeakSet(obj)) { - return weakCollectionOf("WeakSet"); - } - if (isWeakRef(obj)) { - return weakCollectionOf("WeakRef"); - } - if (isNumber(obj)) { - return markBoxed(inspect(Number(obj))); - } - if (isBigInt(obj)) { - return markBoxed(inspect(bigIntValueOf.call(obj))); - } - if (isBoolean(obj)) { - return markBoxed(booleanValueOf.call(obj)); - } - if (isString2(obj)) { - return markBoxed(inspect(String(obj))); - } - if (typeof window !== "undefined" && obj === window) { - return "{ [object Window] }"; - } - if (obj === global) { - return "{ [object globalThis] }"; - } - if (!isDate(obj) && !isRegExp(obj)) { - var ys = arrObjKeys(obj, inspect); - var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; - var protoTag = obj instanceof Object ? "" : "null prototype"; - var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; - var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; - var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); - if (ys.length === 0) { - return tag + "{}"; - } - if (indent) { - return tag + "{" + indentedJoin(ys, indent) + "}"; - } - return tag + "{ " + $join.call(ys, ", ") + " }"; - } - return String(obj); - }; - function wrapQuotes(s2, defaultStyle, opts) { - var quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'"; - return quoteChar + s2 + quoteChar; - } - function quote(s2) { - return $replace.call(String(s2), /"/g, """); - } - function isArray(obj) { - return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isDate(obj) { - return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isRegExp(obj) { - return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isError(obj) { - return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isString2(obj) { - return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isNumber(obj) { - return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isBoolean(obj) { - return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj)); - } - function isSymbol(obj) { - if (hasShammedSymbols) { - return obj && typeof obj === "object" && obj instanceof Symbol; - } - if (typeof obj === "symbol") { - return true; - } - if (!obj || typeof obj !== "object" || !symToString) { - return false; - } - try { - symToString.call(obj); - return true; - } catch (e2) { - } - return false; - } - function isBigInt(obj) { - if (!obj || typeof obj !== "object" || !bigIntValueOf) { - return false; - } - try { - bigIntValueOf.call(obj); - return true; - } catch (e2) { - } - return false; - } - var hasOwn = Object.prototype.hasOwnProperty || function(key) { - return key in this; - }; - function has(obj, key) { - return hasOwn.call(obj, key); - } - function toStr(obj) { - return objectToString.call(obj); - } - function nameOf(f4) { - if (f4.name) { - return f4.name; - } - var m3 = $match.call(functionToString.call(f4), /^function\s*([\w$]+)/); - if (m3) { - return m3[1]; - } - return null; - } - function indexOf(xs, x3) { - if (xs.indexOf) { - return xs.indexOf(x3); - } - for (var i2 = 0, l4 = xs.length; i2 < l4; i2++) { - if (xs[i2] === x3) { - return i2; - } - } - return -1; - } - function isMap(x3) { - if (!mapSize || !x3 || typeof x3 !== "object") { - return false; - } - try { - mapSize.call(x3); - try { - setSize.call(x3); - } catch (s2) { - return true; - } - return x3 instanceof Map; - } catch (e2) { - } - return false; - } - function isWeakMap(x3) { - if (!weakMapHas || !x3 || typeof x3 !== "object") { - return false; - } - try { - weakMapHas.call(x3, weakMapHas); - try { - weakSetHas.call(x3, weakSetHas); - } catch (s2) { - return true; - } - return x3 instanceof WeakMap; - } catch (e2) { - } - return false; - } - function isWeakRef(x3) { - if (!weakRefDeref || !x3 || typeof x3 !== "object") { - return false; - } - try { - weakRefDeref.call(x3); - return true; - } catch (e2) { - } - return false; - } - function isSet(x3) { - if (!setSize || !x3 || typeof x3 !== "object") { - return false; - } - try { - setSize.call(x3); - try { - mapSize.call(x3); - } catch (m3) { - return true; - } - return x3 instanceof Set; - } catch (e2) { - } - return false; - } - function isWeakSet(x3) { - if (!weakSetHas || !x3 || typeof x3 !== "object") { - return false; - } - try { - weakSetHas.call(x3, weakSetHas); - try { - weakMapHas.call(x3, weakMapHas); - } catch (s2) { - return true; - } - return x3 instanceof WeakSet; - } catch (e2) { - } - return false; - } - function isElement(x3) { - if (!x3 || typeof x3 !== "object") { - return false; - } - if (typeof HTMLElement !== "undefined" && x3 instanceof HTMLElement) { - return true; - } - return typeof x3.nodeName === "string" && typeof x3.getAttribute === "function"; - } - function inspectString(str, opts) { - if (str.length > opts.maxStringLength) { - var remaining = str.length - opts.maxStringLength; - var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); - return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; - } - var s2 = $replace.call($replace.call(str, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte); - return wrapQuotes(s2, "single", opts); - } - function lowbyte(c4) { - var n3 = c4.charCodeAt(0); - var x3 = { - 8: "b", - 9: "t", - 10: "n", - 12: "f", - 13: "r" - }[n3]; - if (x3) { - return "\\" + x3; - } - return "\\x" + (n3 < 16 ? "0" : "") + $toUpperCase.call(n3.toString(16)); - } - function markBoxed(str) { - return "Object(" + str + ")"; - } - function weakCollectionOf(type) { - return type + " { ? }"; - } - function collectionOf(type, size, entries, indent) { - var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", "); - return type + " (" + size + ") {" + joinedEntries + "}"; - } - function singleLineValues(xs) { - for (var i2 = 0; i2 < xs.length; i2++) { - if (indexOf(xs[i2], "\n") >= 0) { - return false; - } - } - return true; - } - function getIndent(opts, depth) { - var baseIndent; - if (opts.indent === " ") { - baseIndent = " "; - } else if (typeof opts.indent === "number" && opts.indent > 0) { - baseIndent = $join.call(Array(opts.indent + 1), " "); - } else { - return null; - } - return { - base: baseIndent, - prev: $join.call(Array(depth + 1), baseIndent) - }; - } - function indentedJoin(xs, indent) { - if (xs.length === 0) { - return ""; - } - var lineJoiner = "\n" + indent.prev + indent.base; - return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; - } - function arrObjKeys(obj, inspect) { - var isArr = isArray(obj); - var xs = []; - if (isArr) { - xs.length = obj.length; - for (var i2 = 0; i2 < obj.length; i2++) { - xs[i2] = has(obj, i2) ? inspect(obj[i2], obj) : ""; - } - } - var syms = typeof gOPS === "function" ? gOPS(obj) : []; - var symMap; - if (hasShammedSymbols) { - symMap = {}; - for (var k4 = 0; k4 < syms.length; k4++) { - symMap["$" + syms[k4]] = syms[k4]; - } - } - for (var key in obj) { - if (!has(obj, key)) { - continue; - } - if (isArr && String(Number(key)) === key && key < obj.length) { - continue; - } - if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { - continue; - } else if ($test.call(/[^\w$]/, key)) { - xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); - } else { - xs.push(key + ": " + inspect(obj[key], obj)); - } - } - if (typeof gOPS === "function") { - for (var j2 = 0; j2 < syms.length; j2++) { - if (isEnumerable.call(obj, syms[j2])) { - xs.push("[" + inspect(syms[j2]) + "]: " + inspect(obj[syms[j2]], obj)); - } - } - } - return xs; - } - } -}); - -// node_modules/side-channel/index.js -var require_side_channel = __commonJS({ - "node_modules/side-channel/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var GetIntrinsic = require_get_intrinsic(); - var callBound = require_callBound(); - var inspect = require_object_inspect(); - var $TypeError = GetIntrinsic("%TypeError%"); - var $WeakMap = GetIntrinsic("%WeakMap%", true); - var $Map = GetIntrinsic("%Map%", true); - var $weakMapGet = callBound("WeakMap.prototype.get", true); - var $weakMapSet = callBound("WeakMap.prototype.set", true); - var $weakMapHas = callBound("WeakMap.prototype.has", true); - var $mapGet = callBound("Map.prototype.get", true); - var $mapSet = callBound("Map.prototype.set", true); - var $mapHas = callBound("Map.prototype.has", true); - var listGetNode = function(list, key) { - for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { - if (curr.key === key) { - prev.next = curr.next; - curr.next = list.next; - list.next = curr; - return curr; - } - } - }; - var listGet = function(objects, key) { - var node = listGetNode(objects, key); - return node && node.value; - }; - var listSet = function(objects, key, value) { - var node = listGetNode(objects, key); - if (node) { - node.value = value; - } else { - objects.next = { - // eslint-disable-line no-param-reassign - key, - next: objects.next, - value - }; - } - }; - var listHas = function(objects, key) { - return !!listGetNode(objects, key); - }; - module2.exports = function getSideChannel() { - var $wm; - var $m; - var $o; - var channel = { - assert: function(key) { - if (!channel.has(key)) { - throw new $TypeError("Side channel does not contain " + inspect(key)); - } - }, - get: function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapGet($wm, key); - } - } else if ($Map) { - if ($m) { - return $mapGet($m, key); - } - } else { - if ($o) { - return listGet($o, key); - } - } - }, - has: function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapHas($wm, key); - } - } else if ($Map) { - if ($m) { - return $mapHas($m, key); - } - } else { - if ($o) { - return listHas($o, key); - } - } - return false; - }, - set: function(key, value) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if (!$wm) { - $wm = new $WeakMap(); - } - $weakMapSet($wm, key, value); - } else if ($Map) { - if (!$m) { - $m = new $Map(); - } - $mapSet($m, key, value); - } else { - if (!$o) { - $o = { key: {}, next: null }; - } - listSet($o, key, value); - } - } - }; - return channel; - }; - } -}); - -// node_modules/qs/lib/formats.js -var require_formats = __commonJS({ - "node_modules/qs/lib/formats.js"(exports2, module2) { - "use strict"; - init_shim(); - var replace = String.prototype.replace; - var percentTwenties = /%20/g; - var Format = { - RFC1738: "RFC1738", - RFC3986: "RFC3986" - }; - module2.exports = { - "default": Format.RFC3986, - formatters: { - RFC1738: function(value) { - return replace.call(value, percentTwenties, "+"); - }, - RFC3986: function(value) { - return String(value); - } - }, - RFC1738: Format.RFC1738, - RFC3986: Format.RFC3986 - }; - } -}); - -// node_modules/qs/lib/utils.js -var require_utils5 = __commonJS({ - "node_modules/qs/lib/utils.js"(exports2, module2) { - "use strict"; - init_shim(); - var formats = require_formats(); - var has = Object.prototype.hasOwnProperty; - var isArray = Array.isArray; - var hexTable = function() { - var array = []; - for (var i2 = 0; i2 < 256; ++i2) { - array.push("%" + ((i2 < 16 ? "0" : "") + i2.toString(16)).toUpperCase()); - } - return array; - }(); - var compactQueue = function compactQueue2(queue) { - while (queue.length > 1) { - var item = queue.pop(); - var obj = item.obj[item.prop]; - if (isArray(obj)) { - var compacted = []; - for (var j2 = 0; j2 < obj.length; ++j2) { - if (typeof obj[j2] !== "undefined") { - compacted.push(obj[j2]); - } - } - item.obj[item.prop] = compacted; - } - } - }; - var arrayToObject = function arrayToObject2(source, options) { - var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - for (var i2 = 0; i2 < source.length; ++i2) { - if (typeof source[i2] !== "undefined") { - obj[i2] = source[i2]; - } - } - return obj; - }; - var merge = function merge2(target, source, options) { - if (!source) { - return target; - } - if (typeof source !== "object") { - if (isArray(target)) { - target.push(source); - } else if (target && typeof target === "object") { - if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; - } - return target; - } - if (!target || typeof target !== "object") { - return [target].concat(source); - } - var mergeTarget = target; - if (isArray(target) && !isArray(source)) { - mergeTarget = arrayToObject(target, options); - } - if (isArray(target) && isArray(source)) { - source.forEach(function(item, i2) { - if (has.call(target, i2)) { - var targetItem = target[i2]; - if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { - target[i2] = merge2(targetItem, item, options); - } else { - target.push(item); - } - } else { - target[i2] = item; - } - }); - return target; - } - return Object.keys(source).reduce(function(acc, key) { - var value = source[key]; - if (has.call(acc, key)) { - acc[key] = merge2(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); - }; - var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function(acc, key) { - acc[key] = source[key]; - return acc; - }, target); - }; - var decode6 = function(str, decoder, charset) { - var strWithoutPlus = str.replace(/\+/g, " "); - if (charset === "iso-8859-1") { - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - try { - return decodeURIComponent(strWithoutPlus); - } catch (e2) { - return strWithoutPlus; - } - }; - var encode5 = function encode6(str, defaultEncoder, charset, kind, format) { - if (str.length === 0) { - return str; - } - var string2 = str; - if (typeof str === "symbol") { - string2 = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string2 = String(str); - } - if (charset === "iso-8859-1") { - return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - var out = ""; - for (var i2 = 0; i2 < string2.length; ++i2) { - var c4 = string2.charCodeAt(i2); - if (c4 === 45 || c4 === 46 || c4 === 95 || c4 === 126 || c4 >= 48 && c4 <= 57 || c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122 || format === formats.RFC1738 && (c4 === 40 || c4 === 41)) { - out += string2.charAt(i2); - continue; - } - if (c4 < 128) { - out = out + hexTable[c4]; - continue; - } - if (c4 < 2048) { - out = out + (hexTable[192 | c4 >> 6] + hexTable[128 | c4 & 63]); - continue; - } - if (c4 < 55296 || c4 >= 57344) { - out = out + (hexTable[224 | c4 >> 12] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]); - continue; - } - i2 += 1; - c4 = 65536 + ((c4 & 1023) << 10 | string2.charCodeAt(i2) & 1023); - out += hexTable[240 | c4 >> 18] + hexTable[128 | c4 >> 12 & 63] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]; - } - return out; - }; - var compact = function compact2(value) { - var queue = [{ obj: { o: value }, prop: "o" }]; - var refs = []; - for (var i2 = 0; i2 < queue.length; ++i2) { - var item = queue[i2]; - var obj = item.obj[item.prop]; - var keys2 = Object.keys(obj); - for (var j2 = 0; j2 < keys2.length; ++j2) { - var key = keys2[j2]; - var val = obj[key]; - if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj, prop: key }); - refs.push(val); - } - } - } - compactQueue(queue); - return value; - }; - var isRegExp = function isRegExp2(obj) { - return Object.prototype.toString.call(obj) === "[object RegExp]"; - }; - var isBuffer = function isBuffer2(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); - }; - var combine = function combine2(a3, b4) { - return [].concat(a3, b4); - }; - var maybeMap = function maybeMap2(val, fn) { - if (isArray(val)) { - var mapped = []; - for (var i2 = 0; i2 < val.length; i2 += 1) { - mapped.push(fn(val[i2])); - } - return mapped; - } - return fn(val); - }; - module2.exports = { - arrayToObject, - assign, - combine, - compact, - decode: decode6, - encode: encode5, - isBuffer, - isRegExp, - maybeMap, - merge - }; - } -}); - -// node_modules/qs/lib/stringify.js -var require_stringify2 = __commonJS({ - "node_modules/qs/lib/stringify.js"(exports2, module2) { - "use strict"; - init_shim(); - var getSideChannel = require_side_channel(); - var utils = require_utils5(); - var formats = require_formats(); - var has = Object.prototype.hasOwnProperty; - var arrayPrefixGenerators = { - brackets: function brackets(prefix) { - return prefix + "[]"; - }, - comma: "comma", - indices: function indices(prefix, key) { - return prefix + "[" + key + "]"; - }, - repeat: function repeat(prefix) { - return prefix; - } - }; - var isArray = Array.isArray; - var split = String.prototype.split; - var push = Array.prototype.push; - var pushToArray = function(arr, valueOrArray) { - push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); - }; - var toISO = Date.prototype.toISOString; - var defaultFormat = formats["default"]; - var defaults = { - addQueryPrefix: false, - allowDots: false, - charset: "utf-8", - charsetSentinel: false, - delimiter: "&", - encode: true, - encoder: utils.encode, - encodeValuesOnly: false, - format: defaultFormat, - formatter: formats.formatters[defaultFormat], - // deprecated - indices: false, - serializeDate: function serializeDate(date) { - return toISO.call(date); - }, - skipNulls: false, - strictNullHandling: false - }; - var isNonNullishPrimitive = function isNonNullishPrimitive2(v2) { - return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean" || typeof v2 === "symbol" || typeof v2 === "bigint"; - }; - var sentinel = {}; - var stringify2 = function stringify3(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - var obj = object; - var tmpSc = sideChannel; - var step = 0; - var findFlag = false; - while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { - var pos = tmpSc.get(object); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - findFlag = true; - } - } - if (typeof tmpSc.get(sentinel) === "undefined") { - step = 0; - } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate(obj); - } else if (generateArrayPrefix === "comma" && isArray(obj)) { - obj = utils.maybeMap(obj, function(value2) { - if (value2 instanceof Date) { - return serializeDate(value2); - } - return value2; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; - } - obj = ""; - } - if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { - if (encoder) { - var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); - if (generateArrayPrefix === "comma" && encodeValuesOnly) { - var valuesArray = split.call(String(obj), ","); - var valuesJoined = ""; - for (var i2 = 0; i2 < valuesArray.length; ++i2) { - valuesJoined += (i2 === 0 ? "" : ",") + formatter(encoder(valuesArray[i2], defaults.encoder, charset, "value", format)); - } - return [formatter(keyValue) + "=" + valuesJoined]; - } - return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults.encoder, charset, "value", format))]; - } - return [formatter(prefix) + "=" + formatter(String(obj))]; - } - var values = []; - if (typeof obj === "undefined") { - return values; - } - var objKeys; - if (generateArrayPrefix === "comma" && isArray(obj)) { - objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray(filter)) { - objKeys = filter; - } else { - var keys2 = Object.keys(obj); - objKeys = sort ? keys2.sort(sort) : keys2; - } - for (var j2 = 0; j2 < objKeys.length; ++j2) { - var key = objKeys[j2]; - var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; - if (skipNulls && value === null) { - continue; - } - var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? "." + key : "[" + key + "]"); - sideChannel.set(object, step); - var valueSideChannel = getSideChannel(); - valueSideChannel.set(sentinel, sideChannel); - pushToArray(values, stringify3( - value, - keyPrefix, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - format, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values; - }; - var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { - if (!opts) { - return defaults; - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - var charset = opts.charset || defaults.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - var format = formats["default"]; - if (typeof opts.format !== "undefined") { - if (!has.call(formats.formatters, opts.format)) { - throw new TypeError("Unknown format option provided."); - } - format = opts.format; - } - var formatter = formats.formatters[format]; - var filter = defaults.filter; - if (typeof opts.filter === "function" || isArray(opts.filter)) { - filter = opts.filter; - } - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, - allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter, - format, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; - }; - module2.exports = function(object, opts) { - var obj = object; - var options = normalizeStringifyOptions(opts); - var objKeys; - var filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray(options.filter)) { - filter = options.filter; - objKeys = filter; - } - var keys2 = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - var arrayFormat; - if (opts && opts.arrayFormat in arrayPrefixGenerators) { - arrayFormat = opts.arrayFormat; - } else if (opts && "indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = "indices"; - } - var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; - if (!objKeys) { - objKeys = Object.keys(obj); - } - if (options.sort) { - objKeys.sort(options.sort); - } - var sideChannel = getSideChannel(); - for (var i2 = 0; i2 < objKeys.length; ++i2) { - var key = objKeys[i2]; - if (options.skipNulls && obj[key] === null) { - continue; - } - pushToArray(keys2, stringify2( - obj[key], - key, - generateArrayPrefix, - options.strictNullHandling, - options.skipNulls, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - var joined = keys2.join(options.delimiter); - var prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; - } - } - return joined.length > 0 ? prefix + joined : ""; - }; - } -}); - -// node_modules/qs/lib/parse.js -var require_parse2 = __commonJS({ - "node_modules/qs/lib/parse.js"(exports2, module2) { - "use strict"; - init_shim(); - var utils = require_utils5(); - var has = Object.prototype.hasOwnProperty; - var isArray = Array.isArray; - var defaults = { - allowDots: false, - allowPrototypes: false, - allowSparse: false, - arrayLimit: 20, - charset: "utf-8", - charsetSentinel: false, - comma: false, - decoder: utils.decode, - delimiter: "&", - depth: 5, - ignoreQueryPrefix: false, - interpretNumericEntities: false, - parameterLimit: 1e3, - parseArrays: true, - plainObjects: false, - strictNullHandling: false - }; - var interpretNumericEntities = function(str) { - return str.replace(/&#(\d+);/g, function($0, numberStr) { - return String.fromCharCode(parseInt(numberStr, 10)); - }); - }; - var parseArrayValue = function(val, options) { - if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { - return val.split(","); - } - return val; - }; - var isoSentinel = "utf8=%26%2310003%3B"; - var charsetSentinel = "utf8=%E2%9C%93"; - var parseValues = function parseQueryStringValues(str, options) { - var obj = {}; - var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; - var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; - var parts = cleanStr.split(options.delimiter, limit); - var skipIndex = -1; - var i2; - var charset = options.charset; - if (options.charsetSentinel) { - for (i2 = 0; i2 < parts.length; ++i2) { - if (parts[i2].indexOf("utf8=") === 0) { - if (parts[i2] === charsetSentinel) { - charset = "utf-8"; - } else if (parts[i2] === isoSentinel) { - charset = "iso-8859-1"; - } - skipIndex = i2; - i2 = parts.length; - } - } - } - for (i2 = 0; i2 < parts.length; ++i2) { - if (i2 === skipIndex) { - continue; - } - var part = parts[i2]; - var bracketEqualsPos = part.indexOf("]="); - var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; - var key, val; - if (pos === -1) { - key = options.decoder(part, defaults.decoder, charset, "key"); - val = options.strictNullHandling ? null : ""; - } else { - key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); - val = utils.maybeMap( - parseArrayValue(part.slice(pos + 1), options), - function(encodedVal) { - return options.decoder(encodedVal, defaults.decoder, charset, "value"); - } - ); - } - if (val && options.interpretNumericEntities && charset === "iso-8859-1") { - val = interpretNumericEntities(val); - } - if (part.indexOf("[]=") > -1) { - val = isArray(val) ? [val] : val; - } - if (has.call(obj, key)) { - obj[key] = utils.combine(obj[key], val); - } else { - obj[key] = val; - } - } - return obj; - }; - var parseObject = function(chain, val, options, valuesParsed) { - var leaf = valuesParsed ? val : parseArrayValue(val, options); - for (var i2 = chain.length - 1; i2 >= 0; --i2) { - var obj; - var root = chain[i2]; - if (root === "[]" && options.parseArrays) { - obj = [].concat(leaf); - } else { - obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; - var index = parseInt(cleanRoot, 10); - if (!options.parseArrays && cleanRoot === "") { - obj = { 0: leaf }; - } else if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) { - obj = []; - obj[index] = leaf; - } else if (cleanRoot !== "__proto__") { - obj[cleanRoot] = leaf; - } - } - leaf = obj; - } - return leaf; - }; - var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { - if (!givenKey) { - return; - } - var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; - var brackets = /(\[[^[\]]*])/; - var child = /(\[[^[\]]*])/g; - var segment = options.depth > 0 && brackets.exec(key); - var parent = segment ? key.slice(0, segment.index) : key; - var keys2 = []; - if (parent) { - if (!options.plainObjects && has.call(Object.prototype, parent)) { - if (!options.allowPrototypes) { - return; - } - } - keys2.push(parent); - } - var i2 = 0; - while (options.depth > 0 && (segment = child.exec(key)) !== null && i2 < options.depth) { - i2 += 1; - if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { - if (!options.allowPrototypes) { - return; - } - } - keys2.push(segment[1]); - } - if (segment) { - keys2.push("[" + key.slice(segment.index) + "]"); - } - return parseObject(keys2, val, options, valuesParsed); - }; - var normalizeParseOptions = function normalizeParseOptions2(opts) { - if (!opts) { - return defaults; - } - if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") { - throw new TypeError("Decoder has to be a function."); - } - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; - return { - allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots, - allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, - allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, - arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, - decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, - delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, - // eslint-disable-next-line no-implicit-coercion, no-extra-parens - depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, - ignoreQueryPrefix: opts.ignoreQueryPrefix === true, - interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, - parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, - parseArrays: opts.parseArrays !== false, - plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; - }; - module2.exports = function(str, opts) { - var options = normalizeParseOptions(opts); - if (str === "" || str === null || typeof str === "undefined") { - return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - } - var tempObj = typeof str === "string" ? parseValues(str, options) : str; - var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {}; - var keys2 = Object.keys(tempObj); - for (var i2 = 0; i2 < keys2.length; ++i2) { - var key = keys2[i2]; - var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); - obj = utils.merge(obj, newObj, options); - } - if (options.allowSparse === true) { - return obj; - } - return utils.compact(obj); - }; - } -}); - -// node_modules/qs/lib/index.js -var require_lib = __commonJS({ - "node_modules/qs/lib/index.js"(exports2, module2) { - "use strict"; - init_shim(); - var stringify2 = require_stringify2(); - var parse = require_parse2(); - var formats = require_formats(); - module2.exports = { - formats, - parse, - stringify: stringify2 - }; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js -var require_constants7 = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/constants.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = exports2.WALLET_PROVIDER_CALLBACK_PARAM = exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = exports2.WALLET_PROVIDER_DISCONNECT_URL = exports2.WALLET_PROVIDER_CONNECT_URL = exports2.XALIAS_PROVIDER_TESTNET = exports2.XALIAS_PROVIDER_DEVNET = exports2.XALIAS_PROVIDER_MAINNET = exports2.WALLET_PROVIDER_TESTNET = exports2.WALLET_PROVIDER_DEVNET = exports2.WALLET_PROVIDER_MAINNET = void 0; - exports2.WALLET_PROVIDER_MAINNET = "https://wallet.multiversx.com/dapp/init"; - exports2.WALLET_PROVIDER_DEVNET = "https://devnet-wallet.multiversx.com/dapp/init"; - exports2.WALLET_PROVIDER_TESTNET = "https://testnet-wallet.multiversx.com/dapp/init"; - exports2.XALIAS_PROVIDER_MAINNET = "https://xalias.com"; - exports2.XALIAS_PROVIDER_DEVNET = "https://devnet.xalias.com"; - exports2.XALIAS_PROVIDER_TESTNET = "https://testnet.xalias.com"; - exports2.WALLET_PROVIDER_CONNECT_URL = "hook/login"; - exports2.WALLET_PROVIDER_DISCONNECT_URL = "hook/logout"; - exports2.WALLET_PROVIDER_SEND_TRANSACTION_URL = "hook/transaction"; - exports2.WALLET_PROVIDER_SIGN_TRANSACTION_URL = "hook/sign"; - exports2.WALLET_PROVIDER_GUARD_TRANSACTION_URL = "hook/2fa"; - exports2.WALLET_PROVIDER_SIGN_MESSAGE_URL = "hook/sign-message"; - exports2.WALLET_PROVIDER_CALLBACK_PARAM = "walletProviderStatus"; - exports2.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED = "transactionsSigned"; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js -var require_errors4 = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrCannotSignedMessage = exports2.ErrCannotGetSignedTransactions = void 0; - var ErrCannotGetSignedTransactions = class extends Error { - constructor() { - super("Cannot get signed transaction(s)"); - } - }; - exports2.ErrCannotGetSignedTransactions = ErrCannotGetSignedTransactions; - var ErrCannotSignedMessage = class extends Error { - constructor() { - super("Cannot get signed message"); - } - }; - exports2.ErrCannotSignedMessage = ErrCannotSignedMessage; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js -var require_plainSignedTransaction = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/plainSignedTransaction.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.PlainSignedTransaction = void 0; - var PlainSignedTransaction = class { - constructor(init) { - this.nonce = 0; - this.value = ""; - this.receiver = ""; - this.sender = ""; - this.gasPrice = 0; - this.gasLimit = 0; - this.data = ""; - this.chainID = ""; - this.version = 0; - this.signature = ""; - Object.assign(this, init); - } - }; - exports2.PlainSignedTransaction = PlainSignedTransaction; - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js -var require_walletProvider = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/walletProvider.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __importDefault2 = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WalletProvider = void 0; - var qs_1 = __importDefault2(require_lib()); - var constants_1 = require_constants7(); - var errors_1 = require_errors4(); - var plainSignedTransaction_1 = require_plainSignedTransaction(); - var WalletProvider6 = class _WalletProvider { - /** - * Creates a new WalletProvider - * @param walletURL - */ - constructor(walletURL) { - this.walletUrl = walletURL; - } - /** - * Fetches the login hook url and redirects the client to the wallet login. - */ - login(options) { - return __awaiter2(this, void 0, void 0, function* () { - const redirectUrl = this.buildWalletUrl({ - endpoint: constants_1.WALLET_PROVIDER_CONNECT_URL, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, - params: { - token: options === null || options === void 0 ? void 0 : options.token - } - }); - yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); - return redirectUrl; - }); - } - redirect(url, delayMilliseconds) { - return __awaiter2(this, void 0, void 0, function* () { - if (delayMilliseconds) { - yield this.redirectLater(url, delayMilliseconds); - } else { - this.redirectImmediately(url); - } - }); - } - redirectImmediately(url) { - window.location.href = url; - } - redirectLater(url, delayMilliseconds) { - return __awaiter2(this, void 0, void 0, function* () { - yield new Promise((resolve) => { - setTimeout(() => { - window.location.href = url; - resolve(true); - }, delayMilliseconds); - }); - }); - } - /** - * Fetches the logout hook url and redirects the client to the wallet logout. - */ - logout(options) { - return __awaiter2(this, void 0, void 0, function* () { - const redirectUrl = this.buildWalletUrl({ - endpoint: constants_1.WALLET_PROVIDER_DISCONNECT_URL, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl - }); - yield this.redirect(redirectUrl, options === null || options === void 0 ? void 0 : options.redirectDelayMilliseconds); - return true; - }); - } - /** - * Packs a {@link SignMessage} and fetches correct redirect URL from the wallet API. Then redirects - * the client to the sign message hook - * @param message - * @param options - */ - signMessage(message, options) { - return __awaiter2(this, void 0, void 0, function* () { - const redirectUrl = this.buildWalletUrl({ - endpoint: constants_1.WALLET_PROVIDER_SIGN_MESSAGE_URL, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, - params: { - message: message.message.toString() - } - }); - yield this.redirect(redirectUrl); - return redirectUrl; - }); - } - getMessageSignatureFromWalletUrl() { - var _a, _b; - const url = window.location.search.slice(1); - console.info("getMessageSignatureFromWalletUrl(), url:", url); - const urlParams = qs_1.default.parse(url); - const status = ((_a = urlParams.status) === null || _a === void 0 ? void 0 : _a.toString()) || ""; - const expectedStatus = "signed"; - if (status !== expectedStatus) { - throw new errors_1.ErrCannotSignedMessage(); - } - const signature = ((_b = urlParams.signature) === null || _b === void 0 ? void 0 : _b.toString()) || ""; - return signature; - } - /** - * Packs an array of {$link Transaction} and redirects to the 2fa hook - * - * @param transactions - * @param options - */ - guardTransactions(transactions, options) { - return __awaiter2(this, void 0, void 0, function* () { - this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_GUARD_TRANSACTION_URL, transactions, options); - }); - } - /** - * Packs an array of {$link Transaction} and redirects to the correct transaction sigining hook - * - * @param transactions - * @param options - */ - signTransactions(transactions, options) { - return __awaiter2(this, void 0, void 0, function* () { - this.redirectTransactionsToEndpoint(constants_1.WALLET_PROVIDER_SIGN_TRANSACTION_URL, transactions, options); - }); - } - /** - * Packs a {@link Transaction} and fetches correct redirect URL from the wallet API. Then redirects - * the client to the sign transaction hook - * @param transaction - * @param options - */ - signTransaction(transaction, options) { - return __awaiter2(this, void 0, void 0, function* () { - yield this.signTransactions([transaction], options); - }); - } - getTransactionsFromWalletUrl(search = window.location.search) { - const urlParams = qs_1.default.parse(search.slice(1)); - if (!_WalletProvider.isTxSignReturnSuccess(urlParams)) { - return []; - } - return this.getTxSignReturnValue(urlParams); - } - static isTxSignReturnSuccess(urlParams) { - return urlParams.hasOwnProperty(constants_1.WALLET_PROVIDER_CALLBACK_PARAM) && urlParams[constants_1.WALLET_PROVIDER_CALLBACK_PARAM] === constants_1.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED; - } - getTxSignReturnValue(urlParams) { - console.info("getTxSignReturnValue(), urlParams:", urlParams); - const expectedProps = [ - "nonce", - "value", - "receiver", - "sender", - "gasPrice", - "gasLimit", - "chainID", - "version", - "signature" - ]; - for (let txProp of expectedProps) { - if (!urlParams[txProp] || !Array.isArray(urlParams[txProp])) { - throw new errors_1.ErrCannotGetSignedTransactions(); - } - } - const expectedLength = urlParams["nonce"].length; - for (let txProp of expectedProps) { - if (urlParams[txProp].length !== expectedLength) { - throw new errors_1.ErrCannotGetSignedTransactions(); - } - } - const transactions = []; - for (let i2 = 0; i2 < expectedLength; i2++) { - let plainSignedTransaction = new plainSignedTransaction_1.PlainSignedTransaction(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ - nonce: parseInt(urlParams["nonce"][i2]), - value: urlParams["value"][i2], - receiver: urlParams["receiver"][i2], - sender: urlParams["sender"][i2], - gasPrice: parseInt(urlParams["gasPrice"][i2]), - gasLimit: parseInt(urlParams["gasLimit"][i2]), - // Handle the optional "data" property. - data: urlParams["data"] && urlParams["data"][i2] ? urlParams["data"][i2] : "", - chainID: urlParams["chainID"][i2], - version: parseInt(urlParams["version"][i2]) - }, urlParams["guardian"] && urlParams["guardian"][i2] ? { guardian: urlParams["guardian"][i2] } : {}), urlParams["guardianSignature"] && urlParams["guardianSignature"][i2] ? { guardianSignature: urlParams["guardianSignature"][i2] } : {}), urlParams["options"] && urlParams["options"][i2] ? { - options: parseInt(urlParams["options"][i2]) - } : {}), urlParams["senderUsername"] && urlParams["senderUsername"][i2] ? { senderUsername: urlParams["senderUsername"][i2] } : {}), urlParams["receiverUsername"] && urlParams["receiverUsername"][i2] ? { receiverUsername: urlParams["receiverUsername"][i2] } : {}), { signature: urlParams["signature"][i2] })); - transactions.push(plainSignedTransaction); - } - return transactions; - } - static prepareWalletTransaction(transaction) { - let plainTransaction = transaction.toPlainObject(); - if (plainTransaction.data) { - plainTransaction.data = import_buffer.Buffer.from(plainTransaction.data, "base64").toString(); - } else { - plainTransaction.data = ""; - } - return plainTransaction; - } - buildWalletUrl(options) { - const callbackUrl = (options === null || options === void 0 ? void 0 : options.callbackUrl) || window.location.href; - const partialQueryString = qs_1.default.stringify(options.params || {}); - const fullQueryString = partialQueryString ? `${partialQueryString}&callbackUrl=${callbackUrl}` : `callbackUrl=${callbackUrl}`; - const url = `${this.baseWalletUrl()}/${options.endpoint}?${fullQueryString}`; - console.info(`Redirecting to Wallet URL: ${decodeURI(url)}`); - return url; - } - baseWalletUrl() { - const pathArray = this.walletUrl.split("/"); - const protocol = pathArray[0]; - const host = pathArray[2]; - return protocol + "//" + host; - } - /** - * Packs an array of {$link Transaction} and redirects to the specified wallet hook - * - * @param transactions - * @param options - */ - redirectTransactionsToEndpoint(endpoint, transactions, options) { - const jsonToSend = {}; - transactions.map((tx) => { - let plainTx = _WalletProvider.prepareWalletTransaction(tx); - for (let txProp in plainTx) { - if (plainTx.hasOwnProperty(txProp) && !jsonToSend.hasOwnProperty(txProp)) { - jsonToSend[txProp] = []; - } - jsonToSend[txProp].push(plainTx[txProp]); - } - }); - const redirectUrl = this.buildWalletUrl({ - endpoint, - callbackUrl: options === null || options === void 0 ? void 0 : options.callbackUrl, - params: jsonToSend - }); - window.location.href = redirectUrl; - } - }; - exports2.WalletProvider = WalletProvider6; - } -}); - -// node_modules/axios/dist/browser/axios.cjs -var require_axios = __commonJS({ - "node_modules/axios/dist/browser/axios.cjs"(exports2, module2) { - "use strict"; - init_shim(); - function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; - } - var { toString: toString3 } = Object.prototype; - var { getPrototypeOf } = Object; - var kindOf = /* @__PURE__ */ ((cache) => (thing) => { - const str = toString3.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - })(/* @__PURE__ */ Object.create(null)); - var kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type; - }; - var typeOfTest = (type) => (thing) => typeof thing === type; - var { isArray } = Array; - var isUndefined = typeOfTest("undefined"); - function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); - } - var isArrayBuffer = kindOfTest("ArrayBuffer"); - function isArrayBufferView(val) { - let result; - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && isArrayBuffer(val.buffer); - } - return result; - } - var isString2 = typeOfTest("string"); - var isFunction = typeOfTest("function"); - var isNumber = typeOfTest("number"); - var isObject = (thing) => thing !== null && typeof thing === "object"; - var isBoolean = (thing) => thing === true || thing === false; - var isPlainObject = (val) => { - if (kindOf(val) !== "object") { - return false; - } - const prototype2 = getPrototypeOf(val); - return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); - }; - var isDate = kindOfTest("Date"); - var isFile = kindOfTest("File"); - var isBlob = kindOfTest("Blob"); - var isFileList = kindOfTest("FileList"); - var isStream = (val) => isObject(val) && isFunction(val.pipe); - var isFormData = (thing) => { - let kind; - return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance - kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); - }; - var isURLSearchParams = kindOfTest("URLSearchParams"); - var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); - function forEach(obj, fn, { allOwnKeys = false } = {}) { - if (obj === null || typeof obj === "undefined") { - return; - } - let i2; - let l4; - if (typeof obj !== "object") { - obj = [obj]; - } - if (isArray(obj)) { - for (i2 = 0, l4 = obj.length; i2 < l4; i2++) { - fn.call(null, obj[i2], i2, obj); - } - } else { - const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys2.length; - let key; - for (i2 = 0; i2 < len; i2++) { - key = keys2[i2]; - fn.call(null, obj[key], key, obj); - } - } - } - function findKey(obj, key) { - key = key.toLowerCase(); - const keys2 = Object.keys(obj); - let i2 = keys2.length; - let _key; - while (i2-- > 0) { - _key = keys2[i2]; - if (key === _key.toLowerCase()) { - return _key; - } - } - return null; - } - var _global = (() => { - if (typeof globalThis !== "undefined") - return globalThis; - return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; - })(); - var isContextDefined = (context) => !isUndefined(context) && context !== _global; - function merge() { - const { caseless } = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; - } - }; - for (let i2 = 0, l4 = arguments.length; i2 < l4; i2++) { - arguments[i2] && forEach(arguments[i2], assignValue); - } - return result; - } - var extend = (a3, b4, thisArg, { allOwnKeys } = {}) => { - forEach(b4, (val, key) => { - if (thisArg && isFunction(val)) { - a3[key] = bind(val, thisArg); - } else { - a3[key] = val; - } - }, { allOwnKeys }); - return a3; - }; - var stripBOM = (content) => { - if (content.charCodeAt(0) === 65279) { - content = content.slice(1); - } - return content; - }; - var inherits = (constructor, superConstructor, props, descriptors2) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors2); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, "super", { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); - }; - var toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i2; - let prop; - const merged = {}; - destObj = destObj || {}; - if (sourceObj == null) - return destObj; - do { - props = Object.getOwnPropertyNames(sourceObj); - i2 = props.length; - while (i2-- > 0) { - prop = props[i2]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - return destObj; - }; - var endsWith = (str, searchString, position) => { - str = String(str); - if (position === void 0 || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; - }; - var toArray = (thing) => { - if (!thing) - return null; - if (isArray(thing)) - return thing; - let i2 = thing.length; - if (!isNumber(i2)) - return null; - const arr = new Array(i2); - while (i2-- > 0) { - arr[i2] = thing[i2]; - } - return arr; - }; - var isTypedArray = /* @__PURE__ */ ((TypedArray) => { - return (thing) => { - return TypedArray && thing instanceof TypedArray; - }; - })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); - var forEachEntry = (obj, fn) => { - const generator = obj && obj[Symbol.iterator]; - const iterator = generator.call(obj); - let result; - while ((result = iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); - } - }; - var matchAll = (regExp, str) => { - let matches; - const arr = []; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } - return arr; - }; - var isHTMLForm = kindOfTest("HTMLFormElement"); - var toCamelCase = (str) => { - return str.toLowerCase().replace( - /[-_\s]([a-z\d])(\w*)/g, - function replacer(m3, p1, p22) { - return p1.toUpperCase() + p22; - } - ); - }; - var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); - var isRegExp = kindOfTest("RegExp"); - var reduceDescriptors = (obj, reducer) => { - const descriptors2 = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - forEach(descriptors2, (descriptor, name2) => { - let ret; - if ((ret = reducer(descriptor, name2, obj)) !== false) { - reducedDescriptors[name2] = ret || descriptor; - } - }); - Object.defineProperties(obj, reducedDescriptors); - }; - var freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name2) => { - if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) { - return false; - } - const value = obj[name2]; - if (!isFunction(value)) - return; - descriptor.enumerable = false; - if ("writable" in descriptor) { - descriptor.writable = false; - return; - } - if (!descriptor.set) { - descriptor.set = () => { - throw Error("Can not rewrite read-only method '" + name2 + "'"); - }; - } - }); - }; - var toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - const define2 = (arr) => { - arr.forEach((value) => { - obj[value] = true; - }); - }; - isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); - return obj; - }; - var noop = () => { - }; - var toFiniteNumber = (value, defaultValue) => { - value = +value; - return Number.isFinite(value) ? value : defaultValue; - }; - var ALPHA = "abcdefghijklmnopqrstuvwxyz"; - var DIGIT = "0123456789"; - var ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT - }; - var generateString = (size = 16, alphabet2 = ALPHABET.ALPHA_DIGIT) => { - let str = ""; - const { length: length2 } = alphabet2; - while (size--) { - str += alphabet2[Math.random() * length2 | 0]; - } - return str; - }; - function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); - } - var toJSONObject = (obj) => { - const stack = new Array(10); - const visit = (source, i2) => { - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - if (!("toJSON" in source)) { - stack[i2] = source; - const target = isArray(source) ? [] : {}; - forEach(source, (value, key) => { - const reducedValue = visit(value, i2 + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); - stack[i2] = void 0; - return target; - } - } - return source; - }; - return visit(obj, 0); - }; - var isAsyncFn = kindOfTest("AsyncFunction"); - var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); - var utils$1 = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString: isString2, - isNumber, - isBoolean, - isObject, - isPlainObject, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, - // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - ALPHABET, - generateString, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable - }; - function AxiosError(message, code2, config, request, response) { - Error.call(this); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error().stack; - } - this.message = message; - this.name = "AxiosError"; - code2 && (this.code = code2); - config && (this.config = config); - request && (this.request = request); - response && (this.response = response); - } - utils$1.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - } - }); - var prototype$1 = AxiosError.prototype; - var descriptors = {}; - [ - "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" - // eslint-disable-next-line func-names - ].forEach((code2) => { - descriptors[code2] = { value: code2 }; - }); - Object.defineProperties(AxiosError, descriptors); - Object.defineProperty(prototype$1, "isAxiosError", { value: true }); - AxiosError.from = (error, code2, config, request, response, customProps) => { - const axiosError = Object.create(prototype$1); - utils$1.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, (prop) => { - return prop !== "isAxiosError"; - }); - AxiosError.call(axiosError, error.message, code2, config, request, response); - axiosError.cause = error; - axiosError.name = error.name; - customProps && Object.assign(axiosError, customProps); - return axiosError; - }; - var httpAdapter = null; - function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); - } - function removeBrackets(key) { - return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; - } - function renderKey(path, key, dots) { - if (!path) - return key; - return path.concat(key).map(function each(token, i2) { - token = removeBrackets(token); - return !dots && i2 ? "[" + token + "]" : token; - }).join(dots ? "." : ""); - } - function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); - } - var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); - }); - function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { - throw new TypeError("target must be an object"); - } - formData = formData || new FormData(); - options = utils$1.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - return !utils$1.isUndefined(source[option]); - }); - const metaTokens = options.metaTokens; - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); - if (!utils$1.isFunction(visitor)) { - throw new TypeError("visitor must be a function"); - } - function convertValue(value) { - if (value === null) - return ""; - if (utils$1.isDate(value)) { - return value.toISOString(); - } - if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError("Blob is not supported. Use a Buffer instead."); - } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === "function" ? new Blob([value]) : import_buffer.Buffer.from(value); - } - return value; - } - function defaultVisitor(value, key, path) { - let arr = value; - if (value && !path && typeof value === "object") { - if (utils$1.endsWith(key, "{}")) { - key = metaTokens ? key : key.slice(0, -2); - value = JSON.stringify(value); - } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { - key = removeBrackets(key); - arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", - convertValue(el) - ); - }); - return false; - } - } - if (isVisitable(value)) { - return true; - } - formData.append(renderKey(path, key, dots), convertValue(value)); - return false; - } - const stack = []; - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); - function build(value, path) { - if (utils$1.isUndefined(value)) - return; - if (stack.indexOf(value) !== -1) { - throw Error("Circular reference detected in " + path.join(".")); - } - stack.push(value); - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, - el, - utils$1.isString(key) ? key.trim() : key, - path, - exposedHelpers - ); - if (result === true) { - build(el, path ? path.concat(key) : [key]); - } - }); - stack.pop(); - } - if (!utils$1.isObject(obj)) { - throw new TypeError("data must be an object"); - } - build(obj); - return formData; - } - function encode$1(str) { - const charMap = { - "!": "%21", - "'": "%27", - "(": "%28", - ")": "%29", - "~": "%7E", - "%20": "+", - "%00": "\0" - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); - } - function AxiosURLSearchParams(params, options) { - this._pairs = []; - params && toFormData(params, this, options); - } - var prototype = AxiosURLSearchParams.prototype; - prototype.append = function append(name2, value) { - this._pairs.push([name2, value]); - }; - prototype.toString = function toString4(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode$1); - } : encode$1; - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + "=" + _encode(pair[1]); - }, "").join("&"); - }; - function encode5(val) { - return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); - } - function buildURL(url, params, options) { - if (!params) { - return url; - } - const _encode = options && options.encode || encode5; - const serializeFn = options && options.serialize; - let serializedParams; - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode); - } - if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; - } - return url; - } - var InterceptorManager = class { - constructor() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise - */ - eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - } - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; - } - } - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h5) { - if (h5 !== null) { - fn(h5); - } - }); - } - }; - var InterceptorManager$1 = InterceptorManager; - var transitionalDefaults = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }; - var URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams; - var FormData$1 = typeof FormData !== "undefined" ? FormData : null; - var Blob$1 = typeof Blob !== "undefined" ? Blob : null; - var platform$1 = { - isBrowser: true, - classes: { - URLSearchParams: URLSearchParams$1, - FormData: FormData$1, - Blob: Blob$1 - }, - protocols: ["http", "https", "file", "blob", "url", "data"] - }; - var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; - var hasStandardBrowserEnv = ((product) => { - return hasBrowserEnv && ["ReactNative", "NativeScript", "NS"].indexOf(product) < 0; - })(typeof navigator !== "undefined" && navigator.product); - var hasStandardBrowserWebWorkerEnv = (() => { - return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; - })(); - var utils = /* @__PURE__ */ Object.freeze({ - __proto__: null, - hasBrowserEnv, - hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv - }); - var platform = { - ...utils, - ...platform$1 - }; - function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ - visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { - this.append(key, value.toString("base64")); - return false; - } - return helpers.defaultVisitor.apply(this, arguments); - } - }, options)); - } - function parsePropPath(name2) { - return utils$1.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => { - return match[0] === "[]" ? "" : match[1] || match[0]; - }); - } - function arrayToObject(arr) { - const obj = {}; - const keys2 = Object.keys(arr); - let i2; - const len = keys2.length; - let key; - for (i2 = 0; i2 < len; i2++) { - key = keys2[i2]; - obj[key] = arr[key]; - } - return obj; - } - function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - let name2 = path[index++]; - if (name2 === "__proto__") - return true; - const isNumericKey = Number.isFinite(+name2); - const isLast = index >= path.length; - name2 = !name2 && utils$1.isArray(target) ? target.length : name2; - if (isLast) { - if (utils$1.hasOwnProp(target, name2)) { - target[name2] = [target[name2], value]; - } else { - target[name2] = value; - } - return !isNumericKey; - } - if (!target[name2] || !utils$1.isObject(target[name2])) { - target[name2] = []; - } - const result = buildPath(path, value, target[name2], index); - if (result && utils$1.isArray(target[name2])) { - target[name2] = arrayToObject(target[name2]); - } - return !isNumericKey; - } - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { - const obj = {}; - utils$1.forEachEntry(formData, (name2, value) => { - buildPath(parsePropPath(name2), value, obj, 0); - }); - return obj; - } - return null; - } - function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); - } catch (e2) { - if (e2.name !== "SyntaxError") { - throw e2; - } - } - } - return (encoder || JSON.stringify)(rawValue); - } - var defaults = { - transitional: transitionalDefaults, - adapter: ["xhr", "http"], - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ""; - const hasJSONContentType = contentType.indexOf("application/json") > -1; - const isObjectPayload = utils$1.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { - data = new FormData(data); - } - const isFormData2 = utils$1.isFormData(data); - if (isFormData2) { - return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; - } - if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data)) { - return data; - } - if (utils$1.isArrayBufferView(data)) { - return data.buffer; - } - if (utils$1.isURLSearchParams(data)) { - headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); - return data.toString(); - } - let isFileList2; - if (isObjectPayload) { - if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { - const _FormData = this.env && this.env.FormData; - return toFormData( - isFileList2 ? { "files[]": data } : data, - _FormData && new _FormData(), - this.formSerializer - ); - } - } - if (isObjectPayload || hasJSONContentType) { - headers.setContentType("application/json", false); - return stringifySafely(data); - } - return data; - }], - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === "json"; - if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - try { - return JSON.parse(data); - } catch (e2) { - if (strictJSONParsing) { - if (e2.name === "SyntaxError") { - throw AxiosError.from(e2, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e2; - } - } - } - return data; - }], - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: "XSRF-TOKEN", - xsrfHeaderName: "X-XSRF-TOKEN", - maxContentLength: -1, - maxBodyLength: -1, - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob - }, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - "Accept": "application/json, text/plain, */*", - "Content-Type": void 0 - } - } - }; - utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { - defaults.headers[method] = {}; - }); - var defaults$1 = defaults; - var ignoreDuplicateOf = utils$1.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" - ]); - var parseHeaders = (rawHeaders) => { - const parsed = {}; - let key; - let val; - let i2; - rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { - i2 = line.indexOf(":"); - key = line.substring(0, i2).trim().toLowerCase(); - val = line.substring(i2 + 1).trim(); - if (!key || parsed[key] && ignoreDuplicateOf[key]) { - return; - } - if (key === "set-cookie") { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; - } - }); - return parsed; - }; - var $internals = Symbol("internals"); - function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); - } - function normalizeValue(value) { - if (value === false || value == null) { - return value; - } - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); - } - function parseTokens(str) { - const tokens = /* @__PURE__ */ Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - while (match = tokensRE.exec(str)) { - tokens[match[1]] = match[2]; - } - return tokens; - } - var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); - function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { - return filter.call(this, value, header); - } - if (isHeaderNameFilter) { - value = header; - } - if (!utils$1.isString(value)) - return; - if (utils$1.isString(filter)) { - return value.indexOf(filter) !== -1; - } - if (utils$1.isRegExp(filter)) { - return filter.test(value); - } - } - function formatHeader(header) { - return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w4, char, str) => { - return char.toUpperCase() + str; - }); - } - function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(" " + header); - ["get", "set", "has"].forEach((methodName) => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); - } - var AxiosHeaders = class { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self2 = this; - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); - if (!lHeader) { - throw new Error("header name must be a non-empty string"); - } - const key = utils$1.findKey(self2, lHeader); - if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { - self2[key || _header] = normalizeValue(_value); - } - } - const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); - } - return this; - } - get(header, parser) { - header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); - if (key) { - const value = this[key]; - if (!parser) { - return value; - } - if (parser === true) { - return parseTokens(value); - } - if (utils$1.isFunction(parser)) { - return parser.call(this, value, key); - } - if (utils$1.isRegExp(parser)) { - return parser.exec(value); - } - throw new TypeError("parser must be boolean|regexp|function"); - } - } - } - has(header, matcher) { - header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); - return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); - } - return false; - } - delete(header, matcher) { - const self2 = this; - let deleted = false; - function deleteHeader(_header) { - _header = normalizeHeader(_header); - if (_header) { - const key = utils$1.findKey(self2, _header); - if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { - delete self2[key]; - deleted = true; - } - } - } - if (utils$1.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); - } - return deleted; - } - clear(matcher) { - const keys2 = Object.keys(this); - let i2 = keys2.length; - let deleted = false; - while (i2--) { - const key = keys2[i2]; - if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } - return deleted; - } - normalize(format) { - const self2 = this; - const headers = {}; - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); - if (key) { - self2[key] = normalizeValue(value); - delete self2[header]; - return; - } - const normalized = format ? formatHeader(header) : String(header).trim(); - if (normalized !== header) { - delete self2[header]; - } - self2[normalized] = normalizeValue(value); - headers[normalized] = true; - }); - return this; - } - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - toJSON(asStrings) { - const obj = /* @__PURE__ */ Object.create(null); - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); - }); - return obj; - } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); - } - get [Symbol.toStringTag]() { - return "AxiosHeaders"; - } - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } - static concat(first, ...targets) { - const computed = new this(first); - targets.forEach((target) => computed.set(target)); - return computed; - } - static accessor(header) { - const internals = this[$internals] = this[$internals] = { - accessors: {} - }; - const accessors = internals.accessors; - const prototype2 = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); - if (!accessors[lHeader]) { - buildAccessors(prototype2, _header); - accessors[lHeader] = true; - } - } - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - return this; - } - }; - AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); - utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; - } - }; - }); - utils$1.freezeMethods(AxiosHeaders); - var AxiosHeaders$1 = AxiosHeaders; - function transformData(fns, response) { - const config = this || defaults$1; - const context = response || config; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; - utils$1.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); - }); - headers.normalize(); - return data; - } - function isCancel(value) { - return !!(value && value.__CANCEL__); - } - function CanceledError(message, config, request) { - AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request); - this.name = "CanceledError"; - } - utils$1.inherits(CanceledError, AxiosError, { - __CANCEL__: true - }); - function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - "Request failed with status code " + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } - } - var cookies = platform.hasStandardBrowserEnv ? ( - // Standard browser envs support document.cookie - { - write(name2, value, expires, path, domain, secure) { - const cookie = [name2 + "=" + encodeURIComponent(value)]; - utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); - utils$1.isString(path) && cookie.push("path=" + path); - utils$1.isString(domain) && cookie.push("domain=" + domain); - secure === true && cookie.push("secure"); - document.cookie = cookie.join("; "); - }, - read(name2) { - const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name2 + ")=([^;]*)")); - return match ? decodeURIComponent(match[3]) : null; - }, - remove(name2) { - this.write(name2, "", Date.now() - 864e5); - } - } - ) : ( - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() { - }, - read() { - return null; - }, - remove() { - } - } - ); - function isAbsoluteURL(url) { - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); - } - function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; - } - function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; - } - var isURLSameOrigin = platform.hasStandardBrowserEnv ? ( - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - function standardBrowserEnv() { - const msie = /(msie|trident)/i.test(navigator.userAgent); - const urlParsingNode = document.createElement("a"); - let originURL; - function resolveURL(url) { - let href = url; - if (msie) { - urlParsingNode.setAttribute("href", href); - href = urlParsingNode.href; - } - urlParsingNode.setAttribute("href", href); - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname - }; - } - originURL = resolveURL(window.location.href); - return function isURLSameOrigin2(requestURL) { - const parsed = utils$1.isString(requestURL) ? resolveURL(requestURL) : requestURL; - return parsed.protocol === originURL.protocol && parsed.host === originURL.host; - }; - }() - ) : ( - // Non standard browser envs (web workers, react-native) lack needed support. - /* @__PURE__ */ function nonStandardBrowserEnv() { - return function isURLSameOrigin2() { - return true; - }; - }() - ); - function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ""; - } - function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - min = min !== void 0 ? min : 1e3; - return function push(chunkLength) { - const now = Date.now(); - const startedAt = timestamps[tail]; - if (!firstSampleTS) { - firstSampleTS = now; - } - bytes[head] = chunkLength; - timestamps[head] = now; - let i2 = tail; - let bytesCount = 0; - while (i2 !== head) { - bytesCount += bytes[i2++]; - i2 = i2 % samplesCount; - } - head = (head + 1) % samplesCount; - if (head === tail) { - tail = (tail + 1) % samplesCount; - } - if (now - firstSampleTS < min) { - return; - } - const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; - }; - } - function progressEventReducer(listener, isDownloadStream) { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); - return (e2) => { - const loaded = e2.loaded; - const total = e2.lengthComputable ? e2.total : void 0; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; - bytesNotified = loaded; - const data = { - loaded, - total, - progress: total ? loaded / total : void 0, - bytes: progressBytes, - rate: rate ? rate : void 0, - estimated: rate && total && inRange ? (total - loaded) / rate : void 0, - event: e2 - }; - data[isDownloadStream ? "download" : "upload"] = true; - listener(data); - }; - } - var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; - var xhrAdapter = isXHRAdapterSupported && function(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - let requestData = config.data; - const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); - let { responseType, withXSRFToken } = config; - let onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - if (config.signal) { - config.signal.removeEventListener("abort", onCanceled); - } - } - let contentType; - if (utils$1.isFormData(requestData)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - requestHeaders.setContentType(false); - } else if ((contentType = requestHeaders.getContentType()) !== false) { - const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; - requestHeaders.setContentType([type || "multipart/form-data", ...tokens].join("; ")); - } - } - let request = new XMLHttpRequest(); - if (config.auth) { - const username = config.auth.username || ""; - const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; - requestHeaders.set("Authorization", "Basic " + btoa(username + ":" + password)); - } - const fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - request.timeout = config.timeout; - function onloadend() { - if (!request) { - return; - } - const responseHeaders = AxiosHeaders$1.from( - "getAllResponseHeaders" in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - request = null; - } - if ("onloadend" in request) { - request.onloadend = onloadend; - } else { - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { - return; - } - setTimeout(onloadend); - }; - } - request.onabort = function handleAbort() { - if (!request) { - return; - } - reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request)); - request = null; - }; - request.onerror = function handleError() { - reject(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request)); - request = null; - }; - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; - const transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request - )); - request = null; - }; - if (platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config)); - if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(fullPath)) { - const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName); - if (xsrfValue) { - requestHeaders.set(config.xsrfHeaderName, xsrfValue); - } - } - } - requestData === void 0 && requestHeaders.setContentType(null); - if ("setRequestHeader" in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - } - if (!utils$1.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } - if (responseType && responseType !== "json") { - request.responseType = config.responseType; - } - if (typeof config.onDownloadProgress === "function") { - request.addEventListener("progress", progressEventReducer(config.onDownloadProgress, true)); - } - if (typeof config.onUploadProgress === "function" && request.upload) { - request.upload.addEventListener("progress", progressEventReducer(config.onUploadProgress)); - } - if (config.cancelToken || config.signal) { - onCanceled = (cancel) => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); - request = null; - }; - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); - } - } - const protocol = parseProtocol(fullPath); - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config)); - return; - } - request.send(requestData || null); - }); - }; - var knownAdapters = { - http: httpAdapter, - xhr: xhrAdapter - }; - utils$1.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, "name", { value }); - } catch (e2) { - } - Object.defineProperty(fn, "adapterName", { value }); - } - }); - var renderReason = (reason) => `- ${reason}`; - var isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; - var adapters = { - getAdapter: (adapters2) => { - adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; - const { length: length2 } = adapters2; - let nameOrAdapter; - let adapter; - const rejectedReasons = {}; - for (let i2 = 0; i2 < length2; i2++) { - nameOrAdapter = adapters2[i2]; - let id; - adapter = nameOrAdapter; - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; - if (adapter === void 0) { - throw new AxiosError(`Unknown adapter '${id}'`); - } - } - if (adapter) { - break; - } - rejectedReasons[id || "#" + i2] = adapter; - } - if (!adapter) { - const reasons = Object.entries(rejectedReasons).map( - ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build") - ); - let s2 = length2 ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; - throw new AxiosError( - `There is no suitable adapter to dispatch the request ` + s2, - "ERR_NOT_SUPPORT" - ); - } - return adapter; - }, - adapters: knownAdapters - }; - function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); - } - } - function dispatchRequest(config) { - throwIfCancellationRequested(config); - config.headers = AxiosHeaders$1.from(config.headers); - config.data = transformData.call( - config, - config.transformRequest - ); - if (["post", "put", "patch"].indexOf(config.method) !== -1) { - config.headers.setContentType("application/x-www-form-urlencoded", false); - } - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - response.data = transformData.call( - config, - config.transformResponse, - response - ); - response.headers = AxiosHeaders$1.from(response.headers); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); - } - } - return Promise.reject(reason); - }); - } - var headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; - function mergeConfig(config1, config2) { - config2 = config2 || {}; - const config = {}; - function getMergedValue(target, source, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({ caseless }, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; - } - function mergeDeepProperties(a3, b4, caseless) { - if (!utils$1.isUndefined(b4)) { - return getMergedValue(a3, b4, caseless); - } else if (!utils$1.isUndefined(a3)) { - return getMergedValue(void 0, a3, caseless); - } - } - function valueFromConfig2(a3, b4) { - if (!utils$1.isUndefined(b4)) { - return getMergedValue(void 0, b4); - } - } - function defaultToConfig2(a3, b4) { - if (!utils$1.isUndefined(b4)) { - return getMergedValue(void 0, b4); - } else if (!utils$1.isUndefined(a3)) { - return getMergedValue(void 0, a3); - } - } - function mergeDirectKeys(a3, b4, prop) { - if (prop in config2) { - return getMergedValue(a3, b4); - } else if (prop in config1) { - return getMergedValue(void 0, a3); - } - } - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a3, b4) => mergeDeepProperties(headersToObject(a3), headersToObject(b4), true) - }; - utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { - const merge2 = mergeMap[prop] || mergeDeepProperties; - const configValue = merge2(config1[prop], config2[prop], prop); - utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue); - }); - return config; - } - var VERSION = "1.6.8"; - var validators$1 = {}; - ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => { - validators$1[type] = function validator2(thing) { - return typeof thing === type || "a" + (i2 < 1 ? "n " : " ") + type; - }; - }); - var deprecatedWarnings = {}; - validators$1.transitional = function transitional(validator2, version2, message) { - function formatMessage(opt, desc) { - return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); - } - return (value, opt, opts) => { - if (validator2 === false) { - throw new AxiosError( - formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")), - AxiosError.ERR_DEPRECATED - ); - } - if (version2 && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - console.warn( - formatMessage( - opt, - " has been deprecated since v" + version2 + " and will be removed in the near future" - ) - ); - } - return validator2 ? validator2(value, opt, opts) : true; - }; - }; - function assertOptions(options, schema, allowUnknown) { - if (typeof options !== "object") { - throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE); - } - const keys2 = Object.keys(options); - let i2 = keys2.length; - while (i2-- > 0) { - const opt = keys2[i2]; - const validator2 = schema[opt]; - if (validator2) { - const value = options[opt]; - const result = value === void 0 || validator2(value, opt, options); - if (result !== true) { - throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE); - } - continue; - } - if (allowUnknown !== true) { - throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION); - } - } - } - var validator = { - assertOptions, - validators: validators$1 - }; - var validators = validator.validators; - var Axios = class { - constructor(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() - }; - } - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy; - Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : dummy = new Error(); - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; - if (!err.stack) { - err.stack = stack; - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { - err.stack += "\n" + stack; - } - } - throw err; - } - } - _request(configOrUrl, config) { - if (typeof configOrUrl === "string") { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; - } - config = mergeConfig(this.defaults, config); - const { transitional, paramsSerializer, headers } = config; - if (transitional !== void 0) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } - if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { - config.paramsSerializer = { - serialize: paramsSerializer - }; - } else { - validator.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); - } - } - config.method = (config.method || this.defaults.method || "get").toLowerCase(); - let contextHeaders = headers && utils$1.merge( - headers.common, - headers[config.method] - ); - headers && utils$1.forEach( - ["delete", "get", "head", "post", "put", "patch", "common"], - (method) => { - delete headers[method]; - } - ); - config.headers = AxiosHeaders$1.concat(contextHeaders, headers); - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { - return; - } - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - let promise; - let i2 = 0; - let len; - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), void 0]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); - len = chain.length; - promise = Promise.resolve(config); - while (i2 < len) { - promise = promise.then(chain[i2++], chain[i2++]); - } - return promise; - } - len = requestInterceptorChain.length; - let newConfig = config; - i2 = 0; - while (i2 < len) { - const onFulfilled = requestInterceptorChain[i2++]; - const onRejected = requestInterceptorChain[i2++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; - } - } - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); - } - i2 = 0; - len = responseInterceptorChain.length; - while (i2 < len) { - promise = promise.then(responseInterceptorChain[i2++], responseInterceptorChain[i2++]); - } - return promise; - } - getUri(config) { - config = mergeConfig(this.defaults, config); - const fullPath = buildFullPath(config.baseURL, config.url); - return buildURL(fullPath, config.params, config.paramsSerializer); - } - }; - utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: (config || {}).data - })); - }; - }); - utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - "Content-Type": "multipart/form-data" - } : {}, - url, - data - })); - }; - } - Axios.prototype[method] = generateHTTPMethod(); - Axios.prototype[method + "Form"] = generateHTTPMethod(true); - }); - var Axios$1 = Axios; - var CancelToken = class _CancelToken { - constructor(executor) { - if (typeof executor !== "function") { - throw new TypeError("executor must be a function."); - } - let resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - const token = this; - this.promise.then((cancel) => { - if (!token._listeners) - return; - let i2 = token._listeners.length; - while (i2-- > 0) { - token._listeners[i2](cancel); - } - token._listeners = null; - }); - this.promise.then = (onfulfilled) => { - let _resolve; - const promise = new Promise((resolve) => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - return promise; - }; - executor(function cancel(message, config, request) { - if (token.reason) { - return; - } - token.reason = new CanceledError(message, config, request); - resolvePromise(token.reason); - }); - } - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) { - throw this.reason; - } - } - /** - * Subscribe to the cancel signal - */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - } - /** - * Unsubscribe from the cancel signal - */ - unsubscribe(listener) { - if (!this._listeners) { - return; - } - const index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); - } - } - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - const token = new _CancelToken(function executor(c4) { - cancel = c4; - }); - return { - token, - cancel - }; - } - }; - var CancelToken$1 = CancelToken; - function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - } - function isAxiosError(payload) { - return utils$1.isObject(payload) && payload.isAxiosError === true; - } - var HttpStatusCode = { - 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(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; - }); - var HttpStatusCode$1 = HttpStatusCode; - function createInstance(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind(Axios$1.prototype.request, context); - utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); - utils$1.extend(instance, context, null, { allOwnKeys: true }); - instance.create = function create2(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - return instance; - } - var axios = createInstance(defaults$1); - axios.Axios = Axios$1; - axios.CanceledError = CanceledError; - axios.CancelToken = CancelToken$1; - axios.isCancel = isCancel; - axios.VERSION = VERSION; - axios.toFormData = toFormData; - axios.AxiosError = AxiosError; - axios.Cancel = axios.CanceledError; - axios.all = function all(promises) { - return Promise.all(promises); - }; - axios.spread = spread; - axios.isAxiosError = isAxiosError; - axios.mergeConfig = mergeConfig; - axios.AxiosHeaders = AxiosHeaders$1; - axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); - axios.getAdapter = adapters.getAdapter; - axios.HttpStatusCode = HttpStatusCode$1; - axios.default = axios; - module2.exports = axios; - } -}); - -// node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js -var require_native_auth_client_config = __commonJS({ - "node_modules/@multiversx/sdk-native-auth-client/lib/src/entities/native.auth.client.config.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NativeAuthClientConfig = void 0; - var NativeAuthClientConfig = class { - constructor() { - this.origin = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.hostname : ""; - this.apiUrl = "https://api.multiversx.com"; - this.expirySeconds = 60 * 60 * 24; - } - }; - exports2.NativeAuthClientConfig = NativeAuthClientConfig; - } -}); - -// node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js -var require_native_auth_client = __commonJS({ - "node_modules/@multiversx/sdk-native-auth-client/lib/src/native.auth.client.js"(exports2) { - "use strict"; - init_shim(); - var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); - } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e2) { - reject(e2); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e2) { - reject(e2); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.NativeAuthClient = void 0; - var axios_1 = require_axios(); - var native_auth_client_config_1 = require_native_auth_client_config(); - var NativeAuthClient3 = class { - constructor(config) { - this.config = Object.assign(new native_auth_client_config_1.NativeAuthClientConfig(), config); - } - getToken(address, token, signature) { - const encodedAddress = this.encodeValue(address); - const encodedToken = this.encodeValue(token); - const accessToken = `${encodedAddress}.${encodedToken}.${signature}`; - return accessToken; - } - initialize(extraInfo = {}) { - return __awaiter2(this, void 0, void 0, function* () { - const blockHash = yield this.getCurrentBlockHash(); - const encodedExtraInfo = this.encodeValue(JSON.stringify(extraInfo)); - const origin = this.encodeValue(this.config.origin); - return `${origin}.${blockHash}.${this.config.expirySeconds}.${encodedExtraInfo}`; - }); - } - getCurrentBlockHash() { - return __awaiter2(this, void 0, void 0, function* () { - if (this.config.gatewayUrl) { - return yield this.getCurrentBlockHashWithGateway(); - } - return yield this.getCurrentBlockHashWithApi(); - }); - } - getCurrentBlockHashWithGateway() { - return __awaiter2(this, void 0, void 0, function* () { - const round = yield this.getCurrentRound(); - const url = `${this.config.gatewayUrl}/blocks/by-round/${round}`; - const response = yield this.get(url); - const blocks = response.data.data.blocks; - const block = blocks.filter((block2) => block2.shard === this.config.blockHashShard)[0]; - return block.hash; - }); - } - getCurrentRound() { - return __awaiter2(this, void 0, void 0, function* () { - if (!this.config.gatewayUrl) { - throw new Error("Gateway URL not set"); - } - if (!this.config.blockHashShard) { - throw new Error("Blockhash shard not set"); - } - const url = `${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`; - const response = yield this.get(url); - const status = response.data.data.status; - return status.erd_current_round; - }); - } - getCurrentBlockHashWithApi() { - return __awaiter2(this, void 0, void 0, function* () { - try { - const url = `${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`; - const response = yield this.get(url); - if (response.data[0].hash !== void 0) { - return response.data[0].hash; - } - } catch (error) { - } - return this.getCurrentBlockHashWithApiFallback(); - }); - } - getCurrentBlockHashWithApiFallback() { - return __awaiter2(this, void 0, void 0, function* () { - let url = `${this.config.apiUrl}/blocks?size=1&fields=hash`; - if (this.config.blockHashShard !== void 0) { - url += `&shard=${this.config.blockHashShard}`; - } - const response = yield this.get(url); - return response.data[0].hash; - }); - } - encodeValue(str) { - return this.escape(import_buffer.Buffer.from(str, "utf8").toString("base64")); - } - escape(str) { - return str.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - } - get(url) { - return __awaiter2(this, void 0, void 0, function* () { - return yield axios_1.default.get(url, { headers: this.config.extraRequestHeaders }); - }); - } - }; - exports2.NativeAuthClient = NativeAuthClient3; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js -var require_transactionStatus = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionStatus.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionStatus = void 0; - var TransactionStatus2 = class _TransactionStatus { - /** - * Creates a new TransactionStatus object. - */ - constructor(status) { - this.status = (status || "").toLowerCase(); - } - /** - * Creates an unknown status. - */ - static createUnknown() { - return new _TransactionStatus("unknown"); - } - /** - * Returns whether the transaction is pending (e.g. in mempool). - */ - isPending() { - return this.status == "received" || this.status == "pending"; - } - /** - * Returns whether the transaction has been executed (not necessarily with success). - */ - isExecuted() { - return this.isSuccessful() || this.isFailed() || this.isInvalid(); - } - /** - * Returns whether the transaction has been executed successfully. - */ - isSuccessful() { - return this.status == "executed" || this.status == "success" || this.status == "successful"; - } - /** - * Returns whether the transaction has been executed, but with a failure. - */ - isFailed() { - return this.status == "fail" || this.status == "failed" || this.status == "unsuccessful" || this.isInvalid(); - } - /** - * Returns whether the transaction has been executed, but marked as invalid (e.g. due to "insufficient funds"). - */ - isInvalid() { - return this.status == "invalid"; - } - toString() { - return this.status; - } - valueOf() { - return this.status; - } - equals(other) { - if (!other) { - return false; - } - return this.status == other.status; - } - }; - exports2.TransactionStatus = TransactionStatus2; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js -var require_transactionReceipt = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionReceipt.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionReceipt = void 0; - var primitives_1 = require_primitives(); - var TransactionReceipt2 = class _TransactionReceipt { - constructor() { - this.value = ""; - this.sender = new primitives_1.Address(""); - this.data = ""; - this.hash = ""; - } - static fromHttpResponse(response) { - let receipt = new _TransactionReceipt(); - receipt.value = (response.value || 0).toString(); - receipt.sender = new primitives_1.Address(response.sender); - receipt.data = response.data; - receipt.hash = response.txHash; - return receipt; - } - }; - exports2.TransactionReceipt = TransactionReceipt2; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/errors.js -var require_errors5 = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/errors.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrContractQuery = exports2.ErrNetworkProvider = exports2.ErrUnexpectedCondition = exports2.Err = void 0; - var Err = class extends Error { - constructor(message, inner) { - super(message); - this.inner = void 0; - this.inner = inner; - } - }; - exports2.Err = Err; - var ErrUnexpectedCondition = class extends Err { - constructor(message) { - super(`Unexpected condition: [${message}]`); - } - }; - exports2.ErrUnexpectedCondition = ErrUnexpectedCondition; - var ErrNetworkProvider = class extends Err { - constructor(url, error, inner) { - let message = `Request error on url [${url}]: [${error}]`; - super(message, inner); - } - }; - exports2.ErrNetworkProvider = ErrNetworkProvider; - var ErrContractQuery = class extends Err { - constructor(originalError) { - super(originalError.message.replace("executeQuery:", "")); - } - }; - exports2.ErrContractQuery = ErrContractQuery; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js -var require_transactionEvents = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionEvents.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionEventTopic = exports2.TransactionEventData = exports2.TransactionEvent = void 0; - var primitives_1 = require_primitives(); - var TransactionEvent = class _TransactionEvent { - constructor(init) { - this.address = new primitives_1.Address(""); - this.identifier = ""; - this.topics = []; - this.data = ""; - this.dataPayload = new TransactionEventData(import_buffer.Buffer.from("", "utf8")); - this.additionalData = []; - Object.assign(this, init); - } - static fromHttpResponse(responsePart) { - let result = new _TransactionEvent(); - result.address = new primitives_1.Address(responsePart.address); - result.identifier = responsePart.identifier || ""; - result.topics = (responsePart.topics || []).map((topic) => new TransactionEventTopic(topic)); - result.dataPayload = TransactionEventData.fromBase64(responsePart.data); - result.additionalData = (responsePart.additionalData || []).map(TransactionEventData.fromBase64); - result.data = result.dataPayload.toString(); - return result; - } - findFirstOrNoneTopic(predicate) { - return this.topics.filter((topic) => predicate(topic))[0]; - } - getLastTopic() { - return this.topics[this.topics.length - 1]; - } - }; - exports2.TransactionEvent = TransactionEvent; - var TransactionEventData = class _TransactionEventData { - constructor(data) { - this.raw = data; - } - static fromBase64(str) { - return new _TransactionEventData(import_buffer.Buffer.from(str || "", "base64")); - } - toString() { - return this.raw.toString("utf8"); - } - hex() { - return this.raw.toString("hex"); - } - valueOf() { - return this.raw; - } - }; - exports2.TransactionEventData = TransactionEventData; - var TransactionEventTopic = class { - constructor(topic) { - this.raw = import_buffer.Buffer.from(topic || "", "base64"); - } - toString() { - return this.raw.toString("utf8"); - } - hex() { - return this.raw.toString("hex"); - } - valueOf() { - return this.raw; - } - }; - exports2.TransactionEventTopic = TransactionEventTopic; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js -var require_transactionLogs = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/transactionLogs.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.TransactionLogs = void 0; - var errors_1 = require_errors5(); - var primitives_1 = require_primitives(); - var transactionEvents_1 = require_transactionEvents(); - var TransactionLogs2 = class _TransactionLogs { - constructor(init) { - this.address = new primitives_1.Address(""); - this.events = []; - Object.assign(this, init); - } - static fromHttpResponse(logs) { - let result = new _TransactionLogs(); - result.address = new primitives_1.Address(logs.address); - result.events = (logs.events || []).map((event) => transactionEvents_1.TransactionEvent.fromHttpResponse(event)); - return result; - } - findSingleOrNoneEvent(identifier, predicate) { - let events = this.findEvents(identifier, predicate); - if (events.length > 1) { - throw new errors_1.ErrUnexpectedCondition(`more than one event of type ${identifier}`); - } - return events[0]; - } - findFirstOrNoneEvent(identifier, predicate) { - return this.findEvents(identifier, predicate)[0]; - } - findEvents(identifier, predicate) { - let events = this.events.filter((event) => event.identifier == identifier); - if (predicate) { - events = events.filter((event) => predicate(event)); - } - return events; - } - }; - exports2.TransactionLogs = TransactionLogs2; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/contractResults.js -var require_contractResults = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/contractResults.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractResultItem = exports2.ContractResults = void 0; - var transactionLogs_1 = require_transactionLogs(); - var primitives_1 = require_primitives(); - var ContractResults2 = class _ContractResults { - constructor(items) { - this.items = items; - this.items.sort(function(a3, b4) { - return a3.nonce.valueOf() - b4.nonce.valueOf(); - }); - } - static fromProxyHttpResponse(results) { - let items = results.map((item) => ContractResultItem.fromProxyHttpResponse(item)); - return new _ContractResults(items); - } - static fromApiHttpResponse(results) { - let items = results.map((item) => ContractResultItem.fromApiHttpResponse(item)); - return new _ContractResults(items); - } - }; - exports2.ContractResults = ContractResults2; - var ContractResultItem = class _ContractResultItem { - constructor(init) { - this.hash = ""; - this.nonce = 0; - this.value = ""; - this.receiver = new primitives_1.Address(""); - this.sender = new primitives_1.Address(""); - this.data = ""; - this.previousHash = ""; - this.originalHash = ""; - this.gasLimit = 0; - this.gasPrice = 0; - this.callType = 0; - this.returnMessage = ""; - this.logs = new transactionLogs_1.TransactionLogs(); - Object.assign(this, init); - } - static fromProxyHttpResponse(response) { - let item = _ContractResultItem.fromHttpResponse(response); - return item; - } - static fromApiHttpResponse(response) { - let item = _ContractResultItem.fromHttpResponse(response); - item.data = import_buffer.Buffer.from(item.data, "base64").toString(); - item.callType = Number(item.callType); - return item; - } - static fromHttpResponse(response) { - let item = new _ContractResultItem(); - item.hash = response.hash; - item.nonce = Number(response.nonce || 0); - item.value = (response.value || 0).toString(); - item.receiver = new primitives_1.Address(response.receiver); - item.sender = new primitives_1.Address(response.sender); - item.previousHash = response.prevTxHash; - item.originalHash = response.originalTxHash; - item.gasLimit = Number(response.gasLimit || 0); - item.gasPrice = Number(response.gasPrice || 0); - item.data = response.data || ""; - item.callType = response.callType; - item.returnMessage = response.returnMessage; - item.logs = transactionLogs_1.TransactionLogs.fromHttpResponse(response.logs || {}); - return item; - } - }; - exports2.ContractResultItem = ContractResultItem; - } -}); - -// node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js -var require_contractQueryRequest = __commonJS({ - "node_modules/@multiversx/sdk-network-providers/out/contractQueryRequest.js"(exports2) { - "use strict"; - init_shim(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ContractQueryRequest = void 0; - var ContractQueryRequest2 = class { - constructor(query) { - this.query = query; - } - toHttpRequest() { - var _a; - let request = {}; - let query = this.query; - request.scAddress = query.address.bech32(); - request.caller = ((_a = query.caller) === null || _a === void 0 ? void 0 : _a.bech32()) ? query.caller.bech32() : void 0; - request.funcName = query.func.toString(); - request.value = query.value ? query.value.toString() : void 0; - request.args = query.getEncodedArguments(); - return request; - } - }; - exports2.ContractQueryRequest = ContractQueryRequest2; - } -}); - -// node_modules/qrcode/lib/can-promise.js -var require_can_promise = __commonJS({ - "node_modules/qrcode/lib/can-promise.js"(exports2, module2) { - init_shim(); - module2.exports = function() { - return typeof Promise === "function" && Promise.prototype && Promise.prototype.then; - }; - } -}); - -// node_modules/qrcode/lib/core/utils.js -var require_utils6 = __commonJS({ - "node_modules/qrcode/lib/core/utils.js"(exports2) { - init_shim(); - var toSJISFunction; - var CODEWORDS_COUNT = [ - 0, - // Not used - 26, - 44, - 70, - 100, - 134, - 172, - 196, - 242, - 292, - 346, - 404, - 466, - 532, - 581, - 655, - 733, - 815, - 901, - 991, - 1085, - 1156, - 1258, - 1364, - 1474, - 1588, - 1706, - 1828, - 1921, - 2051, - 2185, - 2323, - 2465, - 2611, - 2761, - 2876, - 3034, - 3196, - 3362, - 3532, - 3706 - ]; - exports2.getSymbolSize = function getSymbolSize(version2) { - if (!version2) - throw new Error('"version" cannot be null or undefined'); - if (version2 < 1 || version2 > 40) - throw new Error('"version" should be in range from 1 to 40'); - return version2 * 4 + 17; - }; - exports2.getSymbolTotalCodewords = function getSymbolTotalCodewords(version2) { - return CODEWORDS_COUNT[version2]; - }; - exports2.getBCHDigit = function(data) { - let digit = 0; - while (data !== 0) { - digit++; - data >>>= 1; - } - return digit; - }; - exports2.setToSJISFunction = function setToSJISFunction(f4) { - if (typeof f4 !== "function") { - throw new Error('"toSJISFunc" is not a valid function.'); - } - toSJISFunction = f4; - }; - exports2.isKanjiModeEnabled = function() { - return typeof toSJISFunction !== "undefined"; - }; - exports2.toSJIS = function toSJIS(kanji) { - return toSJISFunction(kanji); - }; - } -}); - -// node_modules/qrcode/lib/core/error-correction-level.js -var require_error_correction_level = __commonJS({ - "node_modules/qrcode/lib/core/error-correction-level.js"(exports2) { - init_shim(); - exports2.L = { bit: 1 }; - exports2.M = { bit: 0 }; - exports2.Q = { bit: 3 }; - exports2.H = { bit: 2 }; - function fromString3(string2) { - if (typeof string2 !== "string") { - throw new Error("Param is not a string"); - } - const lcStr = string2.toLowerCase(); - switch (lcStr) { - case "l": - case "low": - return exports2.L; - case "m": - case "medium": - return exports2.M; - case "q": - case "quartile": - return exports2.Q; - case "h": - case "high": - return exports2.H; - default: - throw new Error("Unknown EC Level: " + string2); - } - } - exports2.isValid = function isValid(level) { - return level && typeof level.bit !== "undefined" && level.bit >= 0 && level.bit < 4; - }; - exports2.from = function from3(value, defaultValue) { - if (exports2.isValid(value)) { - return value; - } - try { - return fromString3(value); - } catch (e2) { - return defaultValue; - } - }; - } -}); - -// node_modules/qrcode/lib/core/bit-buffer.js -var require_bit_buffer = __commonJS({ - "node_modules/qrcode/lib/core/bit-buffer.js"(exports2, module2) { - init_shim(); - function BitBuffer() { - this.buffer = []; - this.length = 0; - } - BitBuffer.prototype = { - get: function(index) { - const bufIndex = Math.floor(index / 8); - return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1; - }, - put: function(num, length2) { - for (let i2 = 0; i2 < length2; i2++) { - this.putBit((num >>> length2 - i2 - 1 & 1) === 1); - } - }, - getLengthInBits: function() { - return this.length; - }, - putBit: function(bit) { - const bufIndex = Math.floor(this.length / 8); - if (this.buffer.length <= bufIndex) { - this.buffer.push(0); - } - if (bit) { - this.buffer[bufIndex] |= 128 >>> this.length % 8; - } - this.length++; - } - }; - module2.exports = BitBuffer; - } -}); - -// node_modules/qrcode/lib/core/bit-matrix.js -var require_bit_matrix = __commonJS({ - "node_modules/qrcode/lib/core/bit-matrix.js"(exports2, module2) { - init_shim(); - function BitMatrix(size) { - if (!size || size < 1) { - throw new Error("BitMatrix size must be defined and greater than 0"); - } - this.size = size; - this.data = new Uint8Array(size * size); - this.reservedBit = new Uint8Array(size * size); - } - BitMatrix.prototype.set = function(row, col, value, reserved) { - const index = row * this.size + col; - this.data[index] = value; - if (reserved) - this.reservedBit[index] = true; - }; - BitMatrix.prototype.get = function(row, col) { - return this.data[row * this.size + col]; - }; - BitMatrix.prototype.xor = function(row, col, value) { - this.data[row * this.size + col] ^= value; - }; - BitMatrix.prototype.isReserved = function(row, col) { - return this.reservedBit[row * this.size + col]; - }; - module2.exports = BitMatrix; - } -}); - -// node_modules/qrcode/lib/core/alignment-pattern.js -var require_alignment_pattern = __commonJS({ - "node_modules/qrcode/lib/core/alignment-pattern.js"(exports2) { - init_shim(); - var getSymbolSize = require_utils6().getSymbolSize; - exports2.getRowColCoords = function getRowColCoords(version2) { - if (version2 === 1) - return []; - const posCount = Math.floor(version2 / 7) + 2; - const size = getSymbolSize(version2); - const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2; - const positions = [size - 7]; - for (let i2 = 1; i2 < posCount - 1; i2++) { - positions[i2] = positions[i2 - 1] - intervals; - } - positions.push(6); - return positions.reverse(); - }; - exports2.getPositions = function getPositions(version2) { - const coords = []; - const pos = exports2.getRowColCoords(version2); - const posLength = pos.length; - for (let i2 = 0; i2 < posLength; i2++) { - for (let j2 = 0; j2 < posLength; j2++) { - if (i2 === 0 && j2 === 0 || // top-left - i2 === 0 && j2 === posLength - 1 || // bottom-left - i2 === posLength - 1 && j2 === 0) { - continue; - } - coords.push([pos[i2], pos[j2]]); - } - } - return coords; - }; - } -}); - -// node_modules/qrcode/lib/core/finder-pattern.js -var require_finder_pattern = __commonJS({ - "node_modules/qrcode/lib/core/finder-pattern.js"(exports2) { - init_shim(); - var getSymbolSize = require_utils6().getSymbolSize; - var FINDER_PATTERN_SIZE = 7; - exports2.getPositions = function getPositions(version2) { - const size = getSymbolSize(version2); - return [ - // top-left - [0, 0], - // top-right - [size - FINDER_PATTERN_SIZE, 0], - // bottom-left - [0, size - FINDER_PATTERN_SIZE] - ]; - }; - } -}); - -// node_modules/qrcode/lib/core/mask-pattern.js -var require_mask_pattern = __commonJS({ - "node_modules/qrcode/lib/core/mask-pattern.js"(exports2) { - init_shim(); - exports2.Patterns = { - PATTERN000: 0, - PATTERN001: 1, - PATTERN010: 2, - PATTERN011: 3, - PATTERN100: 4, - PATTERN101: 5, - PATTERN110: 6, - PATTERN111: 7 - }; - var PenaltyScores = { - N1: 3, - N2: 3, - N3: 40, - N4: 10 - }; - exports2.isValid = function isValid(mask) { - return mask != null && mask !== "" && !isNaN(mask) && mask >= 0 && mask <= 7; - }; - exports2.from = function from3(value) { - return exports2.isValid(value) ? parseInt(value, 10) : void 0; - }; - exports2.getPenaltyN1 = function getPenaltyN1(data) { - const size = data.size; - let points = 0; - let sameCountCol = 0; - let sameCountRow = 0; - let lastCol = null; - let lastRow = null; - for (let row = 0; row < size; row++) { - sameCountCol = sameCountRow = 0; - lastCol = lastRow = null; - for (let col = 0; col < size; col++) { - let module3 = data.get(row, col); - if (module3 === lastCol) { - sameCountCol++; - } else { - if (sameCountCol >= 5) - points += PenaltyScores.N1 + (sameCountCol - 5); - lastCol = module3; - sameCountCol = 1; - } - module3 = data.get(col, row); - if (module3 === lastRow) { - sameCountRow++; - } else { - if (sameCountRow >= 5) - points += PenaltyScores.N1 + (sameCountRow - 5); - lastRow = module3; - sameCountRow = 1; - } - } - if (sameCountCol >= 5) - points += PenaltyScores.N1 + (sameCountCol - 5); - if (sameCountRow >= 5) - points += PenaltyScores.N1 + (sameCountRow - 5); - } - return points; - }; - exports2.getPenaltyN2 = function getPenaltyN2(data) { - const size = data.size; - let points = 0; - for (let row = 0; row < size - 1; row++) { - for (let col = 0; col < size - 1; col++) { - const last = data.get(row, col) + data.get(row, col + 1) + data.get(row + 1, col) + data.get(row + 1, col + 1); - if (last === 4 || last === 0) - points++; - } - } - return points * PenaltyScores.N2; - }; - exports2.getPenaltyN3 = function getPenaltyN3(data) { - const size = data.size; - let points = 0; - let bitsCol = 0; - let bitsRow = 0; - for (let row = 0; row < size; row++) { - bitsCol = bitsRow = 0; - for (let col = 0; col < size; col++) { - bitsCol = bitsCol << 1 & 2047 | data.get(row, col); - if (col >= 10 && (bitsCol === 1488 || bitsCol === 93)) - points++; - bitsRow = bitsRow << 1 & 2047 | data.get(col, row); - if (col >= 10 && (bitsRow === 1488 || bitsRow === 93)) - points++; - } - } - return points * PenaltyScores.N3; - }; - exports2.getPenaltyN4 = function getPenaltyN4(data) { - let darkCount = 0; - const modulesCount = data.data.length; - for (let i2 = 0; i2 < modulesCount; i2++) - darkCount += data.data[i2]; - const k4 = Math.abs(Math.ceil(darkCount * 100 / modulesCount / 5) - 10); - return k4 * PenaltyScores.N4; - }; - function getMaskAt(maskPattern, i2, j2) { - switch (maskPattern) { - case exports2.Patterns.PATTERN000: - return (i2 + j2) % 2 === 0; - case exports2.Patterns.PATTERN001: - return i2 % 2 === 0; - case exports2.Patterns.PATTERN010: - return j2 % 3 === 0; - case exports2.Patterns.PATTERN011: - return (i2 + j2) % 3 === 0; - case exports2.Patterns.PATTERN100: - return (Math.floor(i2 / 2) + Math.floor(j2 / 3)) % 2 === 0; - case exports2.Patterns.PATTERN101: - return i2 * j2 % 2 + i2 * j2 % 3 === 0; - case exports2.Patterns.PATTERN110: - return (i2 * j2 % 2 + i2 * j2 % 3) % 2 === 0; - case exports2.Patterns.PATTERN111: - return (i2 * j2 % 3 + (i2 + j2) % 2) % 2 === 0; - default: - throw new Error("bad maskPattern:" + maskPattern); - } - } - exports2.applyMask = function applyMask(pattern, data) { - const size = data.size; - for (let col = 0; col < size; col++) { - for (let row = 0; row < size; row++) { - if (data.isReserved(row, col)) - continue; - data.xor(row, col, getMaskAt(pattern, row, col)); - } - } - }; - exports2.getBestMask = function getBestMask(data, setupFormatFunc) { - const numPatterns = Object.keys(exports2.Patterns).length; - let bestPattern = 0; - let lowerPenalty = Infinity; - for (let p3 = 0; p3 < numPatterns; p3++) { - setupFormatFunc(p3); - exports2.applyMask(p3, data); - const penalty = exports2.getPenaltyN1(data) + exports2.getPenaltyN2(data) + exports2.getPenaltyN3(data) + exports2.getPenaltyN4(data); - exports2.applyMask(p3, data); - if (penalty < lowerPenalty) { - lowerPenalty = penalty; - bestPattern = p3; - } - } - return bestPattern; - }; - } -}); - -// node_modules/qrcode/lib/core/error-correction-code.js -var require_error_correction_code = __commonJS({ - "node_modules/qrcode/lib/core/error-correction-code.js"(exports2) { - init_shim(); - var ECLevel = require_error_correction_level(); - var EC_BLOCKS_TABLE = [ - // L M Q H - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 2, - 2, - 1, - 2, - 2, - 4, - 1, - 2, - 4, - 4, - 2, - 4, - 4, - 4, - 2, - 4, - 6, - 5, - 2, - 4, - 6, - 6, - 2, - 5, - 8, - 8, - 4, - 5, - 8, - 8, - 4, - 5, - 8, - 11, - 4, - 8, - 10, - 11, - 4, - 9, - 12, - 16, - 4, - 9, - 16, - 16, - 6, - 10, - 12, - 18, - 6, - 10, - 17, - 16, - 6, - 11, - 16, - 19, - 6, - 13, - 18, - 21, - 7, - 14, - 21, - 25, - 8, - 16, - 20, - 25, - 8, - 17, - 23, - 25, - 9, - 17, - 23, - 34, - 9, - 18, - 25, - 30, - 10, - 20, - 27, - 32, - 12, - 21, - 29, - 35, - 12, - 23, - 34, - 37, - 12, - 25, - 34, - 40, - 13, - 26, - 35, - 42, - 14, - 28, - 38, - 45, - 15, - 29, - 40, - 48, - 16, - 31, - 43, - 51, - 17, - 33, - 45, - 54, - 18, - 35, - 48, - 57, - 19, - 37, - 51, - 60, - 19, - 38, - 53, - 63, - 20, - 40, - 56, - 66, - 21, - 43, - 59, - 70, - 22, - 45, - 62, - 74, - 24, - 47, - 65, - 77, - 25, - 49, - 68, - 81 - ]; - var EC_CODEWORDS_TABLE = [ - // L M Q H - 7, - 10, - 13, - 17, - 10, - 16, - 22, - 28, - 15, - 26, - 36, - 44, - 20, - 36, - 52, - 64, - 26, - 48, - 72, - 88, - 36, - 64, - 96, - 112, - 40, - 72, - 108, - 130, - 48, - 88, - 132, - 156, - 60, - 110, - 160, - 192, - 72, - 130, - 192, - 224, - 80, - 150, - 224, - 264, - 96, - 176, - 260, - 308, - 104, - 198, - 288, - 352, - 120, - 216, - 320, - 384, - 132, - 240, - 360, - 432, - 144, - 280, - 408, - 480, - 168, - 308, - 448, - 532, - 180, - 338, - 504, - 588, - 196, - 364, - 546, - 650, - 224, - 416, - 600, - 700, - 224, - 442, - 644, - 750, - 252, - 476, - 690, - 816, - 270, - 504, - 750, - 900, - 300, - 560, - 810, - 960, - 312, - 588, - 870, - 1050, - 336, - 644, - 952, - 1110, - 360, - 700, - 1020, - 1200, - 390, - 728, - 1050, - 1260, - 420, - 784, - 1140, - 1350, - 450, - 812, - 1200, - 1440, - 480, - 868, - 1290, - 1530, - 510, - 924, - 1350, - 1620, - 540, - 980, - 1440, - 1710, - 570, - 1036, - 1530, - 1800, - 570, - 1064, - 1590, - 1890, - 600, - 1120, - 1680, - 1980, - 630, - 1204, - 1770, - 2100, - 660, - 1260, - 1860, - 2220, - 720, - 1316, - 1950, - 2310, - 750, - 1372, - 2040, - 2430 - ]; - exports2.getBlocksCount = function getBlocksCount(version2, errorCorrectionLevel) { - switch (errorCorrectionLevel) { - case ECLevel.L: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 0]; - case ECLevel.M: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 1]; - case ECLevel.Q: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 2]; - case ECLevel.H: - return EC_BLOCKS_TABLE[(version2 - 1) * 4 + 3]; - default: - return void 0; - } - }; - exports2.getTotalCodewordsCount = function getTotalCodewordsCount(version2, errorCorrectionLevel) { - switch (errorCorrectionLevel) { - case ECLevel.L: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 0]; - case ECLevel.M: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 1]; - case ECLevel.Q: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 2]; - case ECLevel.H: - return EC_CODEWORDS_TABLE[(version2 - 1) * 4 + 3]; - default: - return void 0; - } - }; - } -}); - -// node_modules/qrcode/lib/core/galois-field.js -var require_galois_field = __commonJS({ - "node_modules/qrcode/lib/core/galois-field.js"(exports2) { - init_shim(); - var EXP_TABLE = new Uint8Array(512); - var LOG_TABLE = new Uint8Array(256); - (function initTables() { - let x3 = 1; - for (let i2 = 0; i2 < 255; i2++) { - EXP_TABLE[i2] = x3; - LOG_TABLE[x3] = i2; - x3 <<= 1; - if (x3 & 256) { - x3 ^= 285; - } - } - for (let i2 = 255; i2 < 512; i2++) { - EXP_TABLE[i2] = EXP_TABLE[i2 - 255]; - } - })(); - exports2.log = function log(n3) { - if (n3 < 1) - throw new Error("log(" + n3 + ")"); - return LOG_TABLE[n3]; - }; - exports2.exp = function exp(n3) { - return EXP_TABLE[n3]; - }; - exports2.mul = function mul(x3, y4) { - if (x3 === 0 || y4 === 0) - return 0; - return EXP_TABLE[LOG_TABLE[x3] + LOG_TABLE[y4]]; - }; - } -}); - -// node_modules/qrcode/lib/core/polynomial.js -var require_polynomial = __commonJS({ - "node_modules/qrcode/lib/core/polynomial.js"(exports2) { - init_shim(); - var GF = require_galois_field(); - exports2.mul = function mul(p1, p22) { - const coeff = new Uint8Array(p1.length + p22.length - 1); - for (let i2 = 0; i2 < p1.length; i2++) { - for (let j2 = 0; j2 < p22.length; j2++) { - coeff[i2 + j2] ^= GF.mul(p1[i2], p22[j2]); - } - } - return coeff; - }; - exports2.mod = function mod2(divident, divisor) { - let result = new Uint8Array(divident); - while (result.length - divisor.length >= 0) { - const coeff = result[0]; - for (let i2 = 0; i2 < divisor.length; i2++) { - result[i2] ^= GF.mul(divisor[i2], coeff); - } - let offset = 0; - while (offset < result.length && result[offset] === 0) - offset++; - result = result.slice(offset); - } - return result; - }; - exports2.generateECPolynomial = function generateECPolynomial(degree) { - let poly = new Uint8Array([1]); - for (let i2 = 0; i2 < degree; i2++) { - poly = exports2.mul(poly, new Uint8Array([1, GF.exp(i2)])); - } - return poly; - }; - } -}); - -// node_modules/qrcode/lib/core/reed-solomon-encoder.js -var require_reed_solomon_encoder = __commonJS({ - "node_modules/qrcode/lib/core/reed-solomon-encoder.js"(exports2, module2) { - init_shim(); - var Polynomial = require_polynomial(); - function ReedSolomonEncoder(degree) { - this.genPoly = void 0; - this.degree = degree; - if (this.degree) - this.initialize(this.degree); - } - ReedSolomonEncoder.prototype.initialize = function initialize(degree) { - this.degree = degree; - this.genPoly = Polynomial.generateECPolynomial(this.degree); - }; - ReedSolomonEncoder.prototype.encode = function encode5(data) { - if (!this.genPoly) { - throw new Error("Encoder not initialized"); - } - const paddedData = new Uint8Array(data.length + this.degree); - paddedData.set(data); - const remainder = Polynomial.mod(paddedData, this.genPoly); - const start = this.degree - remainder.length; - if (start > 0) { - const buff = new Uint8Array(this.degree); - buff.set(remainder, start); - return buff; - } - return remainder; - }; - module2.exports = ReedSolomonEncoder; - } -}); - -// node_modules/qrcode/lib/core/version-check.js -var require_version_check = __commonJS({ - "node_modules/qrcode/lib/core/version-check.js"(exports2) { - init_shim(); - exports2.isValid = function isValid(version2) { - return !isNaN(version2) && version2 >= 1 && version2 <= 40; - }; - } -}); - -// node_modules/qrcode/lib/core/regex.js -var require_regex = __commonJS({ - "node_modules/qrcode/lib/core/regex.js"(exports2) { - init_shim(); - var numeric = "[0-9]+"; - var alphanumeric = "[A-Z $%*+\\-./:]+"; - var kanji = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+"; - kanji = kanji.replace(/u/g, "\\u"); - var byte = "(?:(?![A-Z0-9 $%*+\\-./:]|" + kanji + ")(?:.|[\r\n]))+"; - exports2.KANJI = new RegExp(kanji, "g"); - exports2.BYTE_KANJI = new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g"); - exports2.BYTE = new RegExp(byte, "g"); - exports2.NUMERIC = new RegExp(numeric, "g"); - exports2.ALPHANUMERIC = new RegExp(alphanumeric, "g"); - var TEST_KANJI = new RegExp("^" + kanji + "$"); - var TEST_NUMERIC = new RegExp("^" + numeric + "$"); - var TEST_ALPHANUMERIC = new RegExp("^[A-Z0-9 $%*+\\-./:]+$"); - exports2.testKanji = function testKanji(str) { - return TEST_KANJI.test(str); - }; - exports2.testNumeric = function testNumeric(str) { - return TEST_NUMERIC.test(str); - }; - exports2.testAlphanumeric = function testAlphanumeric(str) { - return TEST_ALPHANUMERIC.test(str); - }; - } -}); - -// node_modules/qrcode/lib/core/mode.js -var require_mode = __commonJS({ - "node_modules/qrcode/lib/core/mode.js"(exports2) { - init_shim(); - var VersionCheck = require_version_check(); - var Regex = require_regex(); - exports2.NUMERIC = { - id: "Numeric", - bit: 1 << 0, - ccBits: [10, 12, 14] - }; - exports2.ALPHANUMERIC = { - id: "Alphanumeric", - bit: 1 << 1, - ccBits: [9, 11, 13] - }; - exports2.BYTE = { - id: "Byte", - bit: 1 << 2, - ccBits: [8, 16, 16] - }; - exports2.KANJI = { - id: "Kanji", - bit: 1 << 3, - ccBits: [8, 10, 12] - }; - exports2.MIXED = { - bit: -1 - }; - exports2.getCharCountIndicator = function getCharCountIndicator(mode, version2) { - if (!mode.ccBits) - throw new Error("Invalid mode: " + mode); - if (!VersionCheck.isValid(version2)) { - throw new Error("Invalid version: " + version2); - } - if (version2 >= 1 && version2 < 10) - return mode.ccBits[0]; - else if (version2 < 27) - return mode.ccBits[1]; - return mode.ccBits[2]; - }; - exports2.getBestModeForData = function getBestModeForData(dataStr) { - if (Regex.testNumeric(dataStr)) - return exports2.NUMERIC; - else if (Regex.testAlphanumeric(dataStr)) - return exports2.ALPHANUMERIC; - else if (Regex.testKanji(dataStr)) - return exports2.KANJI; - else - return exports2.BYTE; - }; - exports2.toString = function toString3(mode) { - if (mode && mode.id) - return mode.id; - throw new Error("Invalid mode"); - }; - exports2.isValid = function isValid(mode) { - return mode && mode.bit && mode.ccBits; - }; - function fromString3(string2) { - if (typeof string2 !== "string") { - throw new Error("Param is not a string"); - } - const lcStr = string2.toLowerCase(); - switch (lcStr) { - case "numeric": - return exports2.NUMERIC; - case "alphanumeric": - return exports2.ALPHANUMERIC; - case "kanji": - return exports2.KANJI; - case "byte": - return exports2.BYTE; - default: - throw new Error("Unknown mode: " + string2); - } - } - exports2.from = function from3(value, defaultValue) { - if (exports2.isValid(value)) { - return value; - } - try { - return fromString3(value); - } catch (e2) { - return defaultValue; - } - }; - } -}); - -// node_modules/qrcode/lib/core/version.js -var require_version = __commonJS({ - "node_modules/qrcode/lib/core/version.js"(exports2) { - init_shim(); - var Utils = require_utils6(); - var ECCode = require_error_correction_code(); - var ECLevel = require_error_correction_level(); - var Mode = require_mode(); - var VersionCheck = require_version_check(); - var G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0; - var G18_BCH = Utils.getBCHDigit(G18); - function getBestVersionForDataLength(mode, length2, errorCorrectionLevel) { - for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { - if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, mode)) { - return currentVersion; - } - } - return void 0; - } - function getReservedBitsCount(mode, version2) { - return Mode.getCharCountIndicator(mode, version2) + 4; - } - function getTotalBitsFromDataArray(segments, version2) { - let totalBits = 0; - segments.forEach(function(data) { - const reservedBits = getReservedBitsCount(data.mode, version2); - totalBits += reservedBits + data.getBitsLength(); - }); - return totalBits; - } - function getBestVersionForMixedData(segments, errorCorrectionLevel) { - for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { - const length2 = getTotalBitsFromDataArray(segments, currentVersion); - if (length2 <= exports2.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { - return currentVersion; - } - } - return void 0; - } - exports2.from = function from3(value, defaultValue) { - if (VersionCheck.isValid(value)) { - return parseInt(value, 10); - } - return defaultValue; - }; - exports2.getCapacity = function getCapacity(version2, errorCorrectionLevel, mode) { - if (!VersionCheck.isValid(version2)) { - throw new Error("Invalid QR Code version"); - } - if (typeof mode === "undefined") - mode = Mode.BYTE; - const totalCodewords = Utils.getSymbolTotalCodewords(version2); - const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); - const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; - if (mode === Mode.MIXED) - return dataTotalCodewordsBits; - const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version2); - switch (mode) { - case Mode.NUMERIC: - return Math.floor(usableBits / 10 * 3); - case Mode.ALPHANUMERIC: - return Math.floor(usableBits / 11 * 2); - case Mode.KANJI: - return Math.floor(usableBits / 13); - case Mode.BYTE: - default: - return Math.floor(usableBits / 8); - } - }; - exports2.getBestVersionForData = function getBestVersionForData(data, errorCorrectionLevel) { - let seg; - const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M); - if (Array.isArray(data)) { - if (data.length > 1) { - return getBestVersionForMixedData(data, ecl); - } - if (data.length === 0) { - return 1; - } - seg = data[0]; - } else { - seg = data; - } - return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl); - }; - exports2.getEncodedBits = function getEncodedBits(version2) { - if (!VersionCheck.isValid(version2) || version2 < 7) { - throw new Error("Invalid QR Code version"); - } - let d3 = version2 << 12; - while (Utils.getBCHDigit(d3) - G18_BCH >= 0) { - d3 ^= G18 << Utils.getBCHDigit(d3) - G18_BCH; - } - return version2 << 12 | d3; - }; - } -}); - -// node_modules/qrcode/lib/core/format-info.js -var require_format_info = __commonJS({ - "node_modules/qrcode/lib/core/format-info.js"(exports2) { - init_shim(); - var Utils = require_utils6(); - var G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0; - var G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1; - var G15_BCH = Utils.getBCHDigit(G15); - exports2.getEncodedBits = function getEncodedBits(errorCorrectionLevel, mask) { - const data = errorCorrectionLevel.bit << 3 | mask; - let d3 = data << 10; - while (Utils.getBCHDigit(d3) - G15_BCH >= 0) { - d3 ^= G15 << Utils.getBCHDigit(d3) - G15_BCH; - } - return (data << 10 | d3) ^ G15_MASK; - }; - } -}); - -// node_modules/qrcode/lib/core/numeric-data.js -var require_numeric_data = __commonJS({ - "node_modules/qrcode/lib/core/numeric-data.js"(exports2, module2) { - init_shim(); - var Mode = require_mode(); - function NumericData(data) { - this.mode = Mode.NUMERIC; - this.data = data.toString(); - } - NumericData.getBitsLength = function getBitsLength(length2) { - return 10 * Math.floor(length2 / 3) + (length2 % 3 ? length2 % 3 * 3 + 1 : 0); - }; - NumericData.prototype.getLength = function getLength() { - return this.data.length; - }; - NumericData.prototype.getBitsLength = function getBitsLength() { - return NumericData.getBitsLength(this.data.length); - }; - NumericData.prototype.write = function write(bitBuffer) { - let i2, group, value; - for (i2 = 0; i2 + 3 <= this.data.length; i2 += 3) { - group = this.data.substr(i2, 3); - value = parseInt(group, 10); - bitBuffer.put(value, 10); - } - const remainingNum = this.data.length - i2; - if (remainingNum > 0) { - group = this.data.substr(i2); - value = parseInt(group, 10); - bitBuffer.put(value, remainingNum * 3 + 1); - } - }; - module2.exports = NumericData; - } -}); - -// node_modules/qrcode/lib/core/alphanumeric-data.js -var require_alphanumeric_data = __commonJS({ - "node_modules/qrcode/lib/core/alphanumeric-data.js"(exports2, module2) { - init_shim(); - var Mode = require_mode(); - var ALPHA_NUM_CHARS = [ - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "A", - "B", - "C", - "D", - "E", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "N", - "O", - "P", - "Q", - "R", - "S", - "T", - "U", - "V", - "W", - "X", - "Y", - "Z", - " ", - "$", - "%", - "*", - "+", - "-", - ".", - "/", - ":" - ]; - function AlphanumericData(data) { - this.mode = Mode.ALPHANUMERIC; - this.data = data; - } - AlphanumericData.getBitsLength = function getBitsLength(length2) { - return 11 * Math.floor(length2 / 2) + 6 * (length2 % 2); - }; - AlphanumericData.prototype.getLength = function getLength() { - return this.data.length; - }; - AlphanumericData.prototype.getBitsLength = function getBitsLength() { - return AlphanumericData.getBitsLength(this.data.length); - }; - AlphanumericData.prototype.write = function write(bitBuffer) { - let i2; - for (i2 = 0; i2 + 2 <= this.data.length; i2 += 2) { - let value = ALPHA_NUM_CHARS.indexOf(this.data[i2]) * 45; - value += ALPHA_NUM_CHARS.indexOf(this.data[i2 + 1]); - bitBuffer.put(value, 11); - } - if (this.data.length % 2) { - bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i2]), 6); - } - }; - module2.exports = AlphanumericData; - } -}); - -// node_modules/encode-utf8/index.js -var require_encode_utf8 = __commonJS({ - "node_modules/encode-utf8/index.js"(exports2, module2) { - "use strict"; - init_shim(); - module2.exports = function encodeUtf8(input) { - var result = []; - var size = input.length; - for (var index = 0; index < size; index++) { - var point = input.charCodeAt(index); - if (point >= 55296 && point <= 56319 && size > index + 1) { - var second = input.charCodeAt(index + 1); - if (second >= 56320 && second <= 57343) { - point = (point - 55296) * 1024 + second - 56320 + 65536; - index += 1; - } - } - if (point < 128) { - result.push(point); - continue; - } - if (point < 2048) { - result.push(point >> 6 | 192); - result.push(point & 63 | 128); - continue; - } - if (point < 55296 || point >= 57344 && point < 65536) { - result.push(point >> 12 | 224); - result.push(point >> 6 & 63 | 128); - result.push(point & 63 | 128); - continue; - } - if (point >= 65536 && point <= 1114111) { - result.push(point >> 18 | 240); - result.push(point >> 12 & 63 | 128); - result.push(point >> 6 & 63 | 128); - result.push(point & 63 | 128); - continue; - } - result.push(239, 191, 189); - } - return new Uint8Array(result).buffer; - }; - } -}); - -// node_modules/qrcode/lib/core/byte-data.js -var require_byte_data = __commonJS({ - "node_modules/qrcode/lib/core/byte-data.js"(exports2, module2) { - init_shim(); - var encodeUtf8 = require_encode_utf8(); - var Mode = require_mode(); - function ByteData(data) { - this.mode = Mode.BYTE; - if (typeof data === "string") { - data = encodeUtf8(data); - } - this.data = new Uint8Array(data); - } - ByteData.getBitsLength = function getBitsLength(length2) { - return length2 * 8; - }; - ByteData.prototype.getLength = function getLength() { - return this.data.length; - }; - ByteData.prototype.getBitsLength = function getBitsLength() { - return ByteData.getBitsLength(this.data.length); - }; - ByteData.prototype.write = function(bitBuffer) { - for (let i2 = 0, l4 = this.data.length; i2 < l4; i2++) { - bitBuffer.put(this.data[i2], 8); - } - }; - module2.exports = ByteData; - } -}); - -// node_modules/qrcode/lib/core/kanji-data.js -var require_kanji_data = __commonJS({ - "node_modules/qrcode/lib/core/kanji-data.js"(exports2, module2) { - init_shim(); - var Mode = require_mode(); - var Utils = require_utils6(); - function KanjiData(data) { - this.mode = Mode.KANJI; - this.data = data; - } - KanjiData.getBitsLength = function getBitsLength(length2) { - return length2 * 13; - }; - KanjiData.prototype.getLength = function getLength() { - return this.data.length; - }; - KanjiData.prototype.getBitsLength = function getBitsLength() { - return KanjiData.getBitsLength(this.data.length); - }; - KanjiData.prototype.write = function(bitBuffer) { - let i2; - for (i2 = 0; i2 < this.data.length; i2++) { - let value = Utils.toSJIS(this.data[i2]); - if (value >= 33088 && value <= 40956) { - value -= 33088; - } else if (value >= 57408 && value <= 60351) { - value -= 49472; - } else { - throw new Error( - "Invalid SJIS character: " + this.data[i2] + "\nMake sure your charset is UTF-8" - ); - } - value = (value >>> 8 & 255) * 192 + (value & 255); - bitBuffer.put(value, 13); - } - }; - module2.exports = KanjiData; - } -}); - -// node_modules/dijkstrajs/dijkstra.js -var require_dijkstra = __commonJS({ - "node_modules/dijkstrajs/dijkstra.js"(exports2, module2) { - "use strict"; - init_shim(); - var dijkstra = { - single_source_shortest_paths: function(graph, s2, d3) { - var predecessors = {}; - var costs = {}; - costs[s2] = 0; - var open = dijkstra.PriorityQueue.make(); - open.push(s2, 0); - var closest, u3, v2, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit; - while (!open.empty()) { - closest = open.pop(); - u3 = closest.value; - cost_of_s_to_u = closest.cost; - adjacent_nodes = graph[u3] || {}; - for (v2 in adjacent_nodes) { - if (adjacent_nodes.hasOwnProperty(v2)) { - cost_of_e = adjacent_nodes[v2]; - cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; - cost_of_s_to_v = costs[v2]; - first_visit = typeof costs[v2] === "undefined"; - if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { - costs[v2] = cost_of_s_to_u_plus_cost_of_e; - open.push(v2, cost_of_s_to_u_plus_cost_of_e); - predecessors[v2] = u3; - } - } - } - } - if (typeof d3 !== "undefined" && typeof costs[d3] === "undefined") { - var msg = ["Could not find a path from ", s2, " to ", d3, "."].join(""); - throw new Error(msg); - } - return predecessors; - }, - extract_shortest_path_from_predecessor_list: function(predecessors, d3) { - var nodes = []; - var u3 = d3; - var predecessor; - while (u3) { - nodes.push(u3); - predecessor = predecessors[u3]; - u3 = predecessors[u3]; - } - nodes.reverse(); - return nodes; - }, - find_path: function(graph, s2, d3) { - var predecessors = dijkstra.single_source_shortest_paths(graph, s2, d3); - return dijkstra.extract_shortest_path_from_predecessor_list( - predecessors, - d3 - ); - }, - /** - * A very naive priority queue implementation. - */ - PriorityQueue: { - make: function(opts) { - var T2 = dijkstra.PriorityQueue, t = {}, key; - opts = opts || {}; - for (key in T2) { - if (T2.hasOwnProperty(key)) { - t[key] = T2[key]; - } - } - t.queue = []; - t.sorter = opts.sorter || T2.default_sorter; - return t; - }, - default_sorter: function(a3, b4) { - return a3.cost - b4.cost; - }, - /** - * Add a new item to the queue and ensure the highest priority element - * is at the front of the queue. - */ - push: function(value, cost) { - var item = { value, cost }; - this.queue.push(item); - this.queue.sort(this.sorter); - }, - /** - * Return the highest priority element in the queue. - */ - pop: function() { - return this.queue.shift(); - }, - empty: function() { - return this.queue.length === 0; - } - } - }; - if (typeof module2 !== "undefined") { - module2.exports = dijkstra; - } - } -}); - -// node_modules/qrcode/lib/core/segments.js -var require_segments = __commonJS({ - "node_modules/qrcode/lib/core/segments.js"(exports2) { - init_shim(); - var Mode = require_mode(); - var NumericData = require_numeric_data(); - var AlphanumericData = require_alphanumeric_data(); - var ByteData = require_byte_data(); - var KanjiData = require_kanji_data(); - var Regex = require_regex(); - var Utils = require_utils6(); - var dijkstra = require_dijkstra(); - function getStringByteLength(str) { - return unescape(encodeURIComponent(str)).length; - } - function getSegments(regex, mode, str) { - const segments = []; - let result; - while ((result = regex.exec(str)) !== null) { - segments.push({ - data: result[0], - index: result.index, - mode, - length: result[0].length - }); - } - return segments; - } - function getSegmentsFromString(dataStr) { - const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr); - const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr); - let byteSegs; - let kanjiSegs; - if (Utils.isKanjiModeEnabled()) { - byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr); - kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr); - } else { - byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr); - kanjiSegs = []; - } - const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs); - return segs.sort(function(s1, s2) { - return s1.index - s2.index; - }).map(function(obj) { - return { - data: obj.data, - mode: obj.mode, - length: obj.length - }; - }); - } - function getSegmentBitsLength(length2, mode) { - switch (mode) { - case Mode.NUMERIC: - return NumericData.getBitsLength(length2); - case Mode.ALPHANUMERIC: - return AlphanumericData.getBitsLength(length2); - case Mode.KANJI: - return KanjiData.getBitsLength(length2); - case Mode.BYTE: - return ByteData.getBitsLength(length2); - } - } - function mergeSegments(segs) { - return segs.reduce(function(acc, curr) { - const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null; - if (prevSeg && prevSeg.mode === curr.mode) { - acc[acc.length - 1].data += curr.data; - return acc; - } - acc.push(curr); - return acc; - }, []); - } - function buildNodes(segs) { - const nodes = []; - for (let i2 = 0; i2 < segs.length; i2++) { - const seg = segs[i2]; - switch (seg.mode) { - case Mode.NUMERIC: - nodes.push([ - seg, - { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, - { data: seg.data, mode: Mode.BYTE, length: seg.length } - ]); - break; - case Mode.ALPHANUMERIC: - nodes.push([ - seg, - { data: seg.data, mode: Mode.BYTE, length: seg.length } - ]); - break; - case Mode.KANJI: - nodes.push([ - seg, - { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } - ]); - break; - case Mode.BYTE: - nodes.push([ - { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } - ]); - } - } - return nodes; - } - function buildGraph(nodes, version2) { - const table = {}; - const graph = { start: {} }; - let prevNodeIds = ["start"]; - for (let i2 = 0; i2 < nodes.length; i2++) { - const nodeGroup = nodes[i2]; - const currentNodeIds = []; - for (let j2 = 0; j2 < nodeGroup.length; j2++) { - const node = nodeGroup[j2]; - const key = "" + i2 + j2; - currentNodeIds.push(key); - table[key] = { node, lastCount: 0 }; - graph[key] = {}; - for (let n3 = 0; n3 < prevNodeIds.length; n3++) { - const prevNodeId = prevNodeIds[n3]; - if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { - graph[prevNodeId][key] = getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - getSegmentBitsLength(table[prevNodeId].lastCount, node.mode); - table[prevNodeId].lastCount += node.length; - } else { - if (table[prevNodeId]) - table[prevNodeId].lastCount = node.length; - graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + 4 + Mode.getCharCountIndicator(node.mode, version2); - } - } - } - prevNodeIds = currentNodeIds; - } - for (let n3 = 0; n3 < prevNodeIds.length; n3++) { - graph[prevNodeIds[n3]].end = 0; - } - return { map: graph, table }; - } - function buildSingleSegment(data, modesHint) { - let mode; - const bestMode = Mode.getBestModeForData(data); - mode = Mode.from(modesHint, bestMode); - if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { - throw new Error('"' + data + '" cannot be encoded with mode ' + Mode.toString(mode) + ".\n Suggested mode is: " + Mode.toString(bestMode)); - } - if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { - mode = Mode.BYTE; - } - switch (mode) { - case Mode.NUMERIC: - return new NumericData(data); - case Mode.ALPHANUMERIC: - return new AlphanumericData(data); - case Mode.KANJI: - return new KanjiData(data); - case Mode.BYTE: - return new ByteData(data); - } - } - exports2.fromArray = function fromArray(array) { - return array.reduce(function(acc, seg) { - if (typeof seg === "string") { - acc.push(buildSingleSegment(seg, null)); - } else if (seg.data) { - acc.push(buildSingleSegment(seg.data, seg.mode)); - } - return acc; - }, []); - }; - exports2.fromString = function fromString3(data, version2) { - const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()); - const nodes = buildNodes(segs); - const graph = buildGraph(nodes, version2); - const path = dijkstra.find_path(graph.map, "start", "end"); - const optimizedSegs = []; - for (let i2 = 1; i2 < path.length - 1; i2++) { - optimizedSegs.push(graph.table[path[i2]].node); - } - return exports2.fromArray(mergeSegments(optimizedSegs)); - }; - exports2.rawSplit = function rawSplit(data) { - return exports2.fromArray( - getSegmentsFromString(data, Utils.isKanjiModeEnabled()) - ); - }; - } -}); - -// node_modules/qrcode/lib/core/qrcode.js -var require_qrcode = __commonJS({ - "node_modules/qrcode/lib/core/qrcode.js"(exports2) { - init_shim(); - var Utils = require_utils6(); - var ECLevel = require_error_correction_level(); - var BitBuffer = require_bit_buffer(); - var BitMatrix = require_bit_matrix(); - var AlignmentPattern = require_alignment_pattern(); - var FinderPattern = require_finder_pattern(); - var MaskPattern = require_mask_pattern(); - var ECCode = require_error_correction_code(); - var ReedSolomonEncoder = require_reed_solomon_encoder(); - var Version = require_version(); - var FormatInfo = require_format_info(); - var Mode = require_mode(); - var Segments = require_segments(); - function setupFinderPattern(matrix, version2) { - const size = matrix.size; - const pos = FinderPattern.getPositions(version2); - for (let i2 = 0; i2 < pos.length; i2++) { - const row = pos[i2][0]; - const col = pos[i2][1]; - for (let r = -1; r <= 7; r++) { - if (row + r <= -1 || size <= row + r) - continue; - for (let c4 = -1; c4 <= 7; c4++) { - if (col + c4 <= -1 || size <= col + c4) - continue; - if (r >= 0 && r <= 6 && (c4 === 0 || c4 === 6) || c4 >= 0 && c4 <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c4 >= 2 && c4 <= 4) { - matrix.set(row + r, col + c4, true, true); - } else { - matrix.set(row + r, col + c4, false, true); - } - } - } - } - } - function setupTimingPattern(matrix) { - const size = matrix.size; - for (let r = 8; r < size - 8; r++) { - const value = r % 2 === 0; - matrix.set(r, 6, value, true); - matrix.set(6, r, value, true); - } - } - function setupAlignmentPattern(matrix, version2) { - const pos = AlignmentPattern.getPositions(version2); - for (let i2 = 0; i2 < pos.length; i2++) { - const row = pos[i2][0]; - const col = pos[i2][1]; - for (let r = -2; r <= 2; r++) { - for (let c4 = -2; c4 <= 2; c4++) { - if (r === -2 || r === 2 || c4 === -2 || c4 === 2 || r === 0 && c4 === 0) { - matrix.set(row + r, col + c4, true, true); - } else { - matrix.set(row + r, col + c4, false, true); - } - } - } - } - } - function setupVersionInfo(matrix, version2) { - const size = matrix.size; - const bits = Version.getEncodedBits(version2); - let row, col, mod2; - for (let i2 = 0; i2 < 18; i2++) { - row = Math.floor(i2 / 3); - col = i2 % 3 + size - 8 - 3; - mod2 = (bits >> i2 & 1) === 1; - matrix.set(row, col, mod2, true); - matrix.set(col, row, mod2, true); - } - } - function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) { - const size = matrix.size; - const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern); - let i2, mod2; - for (i2 = 0; i2 < 15; i2++) { - mod2 = (bits >> i2 & 1) === 1; - if (i2 < 6) { - matrix.set(i2, 8, mod2, true); - } else if (i2 < 8) { - matrix.set(i2 + 1, 8, mod2, true); - } else { - matrix.set(size - 15 + i2, 8, mod2, true); - } - if (i2 < 8) { - matrix.set(8, size - i2 - 1, mod2, true); - } else if (i2 < 9) { - matrix.set(8, 15 - i2 - 1 + 1, mod2, true); - } else { - matrix.set(8, 15 - i2 - 1, mod2, true); - } - } - matrix.set(size - 8, 8, 1, true); - } - function setupData(matrix, data) { - const size = matrix.size; - let inc = -1; - let row = size - 1; - let bitIndex = 7; - let byteIndex = 0; - for (let col = size - 1; col > 0; col -= 2) { - if (col === 6) - col--; - while (true) { - for (let c4 = 0; c4 < 2; c4++) { - if (!matrix.isReserved(row, col - c4)) { - let dark = false; - if (byteIndex < data.length) { - dark = (data[byteIndex] >>> bitIndex & 1) === 1; - } - matrix.set(row, col - c4, dark); - bitIndex--; - if (bitIndex === -1) { - byteIndex++; - bitIndex = 7; - } - } - } - row += inc; - if (row < 0 || size <= row) { - row -= inc; - inc = -inc; - break; - } - } - } - } - function createData(version2, errorCorrectionLevel, segments) { - const buffer = new BitBuffer(); - segments.forEach(function(data) { - buffer.put(data.mode.bit, 4); - buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version2)); - data.write(buffer); - }); - const totalCodewords = Utils.getSymbolTotalCodewords(version2); - const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); - const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8; - if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) { - buffer.put(0, 4); - } - while (buffer.getLengthInBits() % 8 !== 0) { - buffer.putBit(0); - } - const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8; - for (let i2 = 0; i2 < remainingByte; i2++) { - buffer.put(i2 % 2 ? 17 : 236, 8); - } - return createCodewords(buffer, version2, errorCorrectionLevel); - } - function createCodewords(bitBuffer, version2, errorCorrectionLevel) { - const totalCodewords = Utils.getSymbolTotalCodewords(version2); - const ecTotalCodewords = ECCode.getTotalCodewordsCount(version2, errorCorrectionLevel); - const dataTotalCodewords = totalCodewords - ecTotalCodewords; - const ecTotalBlocks = ECCode.getBlocksCount(version2, errorCorrectionLevel); - const blocksInGroup2 = totalCodewords % ecTotalBlocks; - const blocksInGroup1 = ecTotalBlocks - blocksInGroup2; - const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks); - const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks); - const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1; - const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1; - const rs = new ReedSolomonEncoder(ecCount); - let offset = 0; - const dcData = new Array(ecTotalBlocks); - const ecData = new Array(ecTotalBlocks); - let maxDataSize = 0; - const buffer = new Uint8Array(bitBuffer.buffer); - for (let b4 = 0; b4 < ecTotalBlocks; b4++) { - const dataSize = b4 < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2; - dcData[b4] = buffer.slice(offset, offset + dataSize); - ecData[b4] = rs.encode(dcData[b4]); - offset += dataSize; - maxDataSize = Math.max(maxDataSize, dataSize); - } - const data = new Uint8Array(totalCodewords); - let index = 0; - let i2, r; - for (i2 = 0; i2 < maxDataSize; i2++) { - for (r = 0; r < ecTotalBlocks; r++) { - if (i2 < dcData[r].length) { - data[index++] = dcData[r][i2]; - } - } - } - for (i2 = 0; i2 < ecCount; i2++) { - for (r = 0; r < ecTotalBlocks; r++) { - data[index++] = ecData[r][i2]; - } - } - return data; - } - function createSymbol(data, version2, errorCorrectionLevel, maskPattern) { - let segments; - if (Array.isArray(data)) { - segments = Segments.fromArray(data); - } else if (typeof data === "string") { - let estimatedVersion = version2; - if (!estimatedVersion) { - const rawSegments = Segments.rawSplit(data); - estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel); - } - segments = Segments.fromString(data, estimatedVersion || 40); - } else { - throw new Error("Invalid data"); - } - const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel); - if (!bestVersion) { - throw new Error("The amount of data is too big to be stored in a QR Code"); - } - if (!version2) { - version2 = bestVersion; - } else if (version2 < bestVersion) { - throw new Error( - "\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: " + bestVersion + ".\n" - ); - } - const dataBits = createData(version2, errorCorrectionLevel, segments); - const moduleCount = Utils.getSymbolSize(version2); - const modules = new BitMatrix(moduleCount); - setupFinderPattern(modules, version2); - setupTimingPattern(modules); - setupAlignmentPattern(modules, version2); - setupFormatInfo(modules, errorCorrectionLevel, 0); - if (version2 >= 7) { - setupVersionInfo(modules, version2); - } - setupData(modules, dataBits); - if (isNaN(maskPattern)) { - maskPattern = MaskPattern.getBestMask( - modules, - setupFormatInfo.bind(null, modules, errorCorrectionLevel) - ); - } - MaskPattern.applyMask(maskPattern, modules); - setupFormatInfo(modules, errorCorrectionLevel, maskPattern); - return { - modules, - version: version2, - errorCorrectionLevel, - maskPattern, - segments - }; - } - exports2.create = function create2(data, options) { - if (typeof data === "undefined" || data === "") { - throw new Error("No input text"); - } - let errorCorrectionLevel = ECLevel.M; - let version2; - let mask; - if (typeof options !== "undefined") { - errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M); - version2 = Version.from(options.version); - mask = MaskPattern.from(options.maskPattern); - if (options.toSJISFunc) { - Utils.setToSJISFunction(options.toSJISFunc); - } - } - return createSymbol(data, version2, errorCorrectionLevel, mask); - }; - } -}); - -// node_modules/qrcode/lib/renderer/utils.js -var require_utils7 = __commonJS({ - "node_modules/qrcode/lib/renderer/utils.js"(exports2) { - init_shim(); - function hex2rgba(hex) { - if (typeof hex === "number") { - hex = hex.toString(); - } - if (typeof hex !== "string") { - throw new Error("Color should be defined as hex string"); - } - let hexCode = hex.slice().replace("#", "").split(""); - if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { - throw new Error("Invalid hex color: " + hex); - } - if (hexCode.length === 3 || hexCode.length === 4) { - hexCode = Array.prototype.concat.apply([], hexCode.map(function(c4) { - return [c4, c4]; - })); - } - if (hexCode.length === 6) - hexCode.push("F", "F"); - const hexValue = parseInt(hexCode.join(""), 16); - return { - r: hexValue >> 24 & 255, - g: hexValue >> 16 & 255, - b: hexValue >> 8 & 255, - a: hexValue & 255, - hex: "#" + hexCode.slice(0, 6).join("") - }; - } - exports2.getOptions = function getOptions(options) { - if (!options) - options = {}; - if (!options.color) - options.color = {}; - const margin = typeof options.margin === "undefined" || options.margin === null || options.margin < 0 ? 4 : options.margin; - const width = options.width && options.width >= 21 ? options.width : void 0; - const scale = options.scale || 4; - return { - width, - scale: width ? 4 : scale, - margin, - color: { - dark: hex2rgba(options.color.dark || "#000000ff"), - light: hex2rgba(options.color.light || "#ffffffff") - }, - type: options.type, - rendererOpts: options.rendererOpts || {} - }; - }; - exports2.getScale = function getScale(qrSize, opts) { - return opts.width && opts.width >= qrSize + opts.margin * 2 ? opts.width / (qrSize + opts.margin * 2) : opts.scale; - }; - exports2.getImageWidth = function getImageWidth(qrSize, opts) { - const scale = exports2.getScale(qrSize, opts); - return Math.floor((qrSize + opts.margin * 2) * scale); - }; - exports2.qrToImageData = function qrToImageData(imgData, qr, opts) { - const size = qr.modules.size; - const data = qr.modules.data; - const scale = exports2.getScale(size, opts); - const symbolSize = Math.floor((size + opts.margin * 2) * scale); - const scaledMargin = opts.margin * scale; - const palette = [opts.color.light, opts.color.dark]; - for (let i2 = 0; i2 < symbolSize; i2++) { - for (let j2 = 0; j2 < symbolSize; j2++) { - let posDst = (i2 * symbolSize + j2) * 4; - let pxColor = opts.color.light; - if (i2 >= scaledMargin && j2 >= scaledMargin && i2 < symbolSize - scaledMargin && j2 < symbolSize - scaledMargin) { - const iSrc = Math.floor((i2 - scaledMargin) / scale); - const jSrc = Math.floor((j2 - scaledMargin) / scale); - pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]; - } - imgData[posDst++] = pxColor.r; - imgData[posDst++] = pxColor.g; - imgData[posDst++] = pxColor.b; - imgData[posDst] = pxColor.a; - } - } - }; - } -}); - -// node_modules/qrcode/lib/renderer/canvas.js -var require_canvas = __commonJS({ - "node_modules/qrcode/lib/renderer/canvas.js"(exports2) { - init_shim(); - var Utils = require_utils7(); - function clearCanvas(ctx, canvas, size) { - ctx.clearRect(0, 0, canvas.width, canvas.height); - if (!canvas.style) - canvas.style = {}; - canvas.height = size; - canvas.width = size; - canvas.style.height = size + "px"; - canvas.style.width = size + "px"; - } - function getCanvasElement() { - try { - return document.createElement("canvas"); - } catch (e2) { - throw new Error("You need to specify a canvas element"); - } - } - exports2.render = function render(qrData, canvas, options) { - let opts = options; - let canvasEl = canvas; - if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { - opts = canvas; - canvas = void 0; - } - if (!canvas) { - canvasEl = getCanvasElement(); - } - opts = Utils.getOptions(opts); - const size = Utils.getImageWidth(qrData.modules.size, opts); - const ctx = canvasEl.getContext("2d"); - const image = ctx.createImageData(size, size); - Utils.qrToImageData(image.data, qrData, opts); - clearCanvas(ctx, canvasEl, size); - ctx.putImageData(image, 0, 0); - return canvasEl; - }; - exports2.renderToDataURL = function renderToDataURL(qrData, canvas, options) { - let opts = options; - if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) { - opts = canvas; - canvas = void 0; - } - if (!opts) - opts = {}; - const canvasEl = exports2.render(qrData, canvas, opts); - const type = opts.type || "image/png"; - const rendererOpts = opts.rendererOpts || {}; - return canvasEl.toDataURL(type, rendererOpts.quality); - }; - } -}); - -// node_modules/qrcode/lib/renderer/svg-tag.js -var require_svg_tag = __commonJS({ - "node_modules/qrcode/lib/renderer/svg-tag.js"(exports2) { - init_shim(); - var Utils = require_utils7(); - function getColorAttrib(color, attrib) { - const alpha = color.a / 255; - const str = attrib + '="' + color.hex + '"'; - return alpha < 1 ? str + " " + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' : str; - } - function svgCmd(cmd, x3, y4) { - let str = cmd + x3; - if (typeof y4 !== "undefined") - str += " " + y4; - return str; - } - function qrToPath(data, size, margin) { - let path = ""; - let moveBy = 0; - let newRow = false; - let lineLength = 0; - for (let i2 = 0; i2 < data.length; i2++) { - const col = Math.floor(i2 % size); - const row = Math.floor(i2 / size); - if (!col && !newRow) - newRow = true; - if (data[i2]) { - lineLength++; - if (!(i2 > 0 && col > 0 && data[i2 - 1])) { - path += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0); - moveBy = 0; - newRow = false; - } - if (!(col + 1 < size && data[i2 + 1])) { - path += svgCmd("h", lineLength); - lineLength = 0; - } - } else { - moveBy++; - } - } - return path; - } - exports2.render = function render(qrData, options, cb) { - const opts = Utils.getOptions(options); - const size = qrData.modules.size; - const data = qrData.modules.data; - const qrcodesize = size + opts.margin * 2; - const bg = !opts.color.light.a ? "" : "'; - const path = "'; - const viewBox = 'viewBox="0 0 ' + qrcodesize + " " + qrcodesize + '"'; - const width = !opts.width ? "" : 'width="' + opts.width + '" height="' + opts.width + '" '; - const svgTag = '' + bg + path + "\n"; - if (typeof cb === "function") { - cb(null, svgTag); - } - return svgTag; - }; - } -}); - -// node_modules/qrcode/lib/browser.js -var require_browser7 = __commonJS({ - "node_modules/qrcode/lib/browser.js"(exports2) { - init_shim(); - var canPromise = require_can_promise(); - var QRCode2 = require_qrcode(); - var CanvasRenderer = require_canvas(); - var SvgRenderer = require_svg_tag(); - function renderCanvas(renderFunc, canvas, text, opts, cb) { - const args = [].slice.call(arguments, 1); - const argsNum = args.length; - const isLastArgCb = typeof args[argsNum - 1] === "function"; - if (!isLastArgCb && !canPromise()) { - throw new Error("Callback required as last argument"); - } - if (isLastArgCb) { - if (argsNum < 2) { - throw new Error("Too few arguments provided"); - } - if (argsNum === 2) { - cb = text; - text = canvas; - canvas = opts = void 0; - } else if (argsNum === 3) { - if (canvas.getContext && typeof cb === "undefined") { - cb = opts; - opts = void 0; - } else { - cb = opts; - opts = text; - text = canvas; - canvas = void 0; - } - } - } else { - if (argsNum < 1) { - throw new Error("Too few arguments provided"); - } - if (argsNum === 1) { - text = canvas; - canvas = opts = void 0; - } else if (argsNum === 2 && !canvas.getContext) { - opts = text; - text = canvas; - canvas = void 0; - } - return new Promise(function(resolve, reject) { - try { - const data = QRCode2.create(text, opts); - resolve(renderFunc(data, canvas, opts)); - } catch (e2) { - reject(e2); - } - }); - } - try { - const data = QRCode2.create(text, opts); - cb(null, renderFunc(data, canvas, opts)); - } catch (e2) { - cb(e2); - } - } - exports2.create = QRCode2.create; - exports2.toCanvas = renderCanvas.bind(null, CanvasRenderer.render); - exports2.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL); - exports2.toString = renderCanvas.bind(null, function(data, _4, opts) { - return SvgRenderer.render(data, opts); - }); - } -}); - -// node_modules/@multiversx/sdk-web-wallet-provider/out/index.js -var require_out2 = __commonJS({ - "node_modules/@multiversx/sdk-web-wallet-provider/out/index.js"(exports2) { - "use strict"; - init_shim(); - var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m3[k4]; - } }); - } : function(o2, m3, k4, k22) { - if (k22 === void 0) - k22 = k4; - o2[k22] = m3[k4]; - }); - var __exportStar2 = exports2 && exports2.__exportStar || function(m3, exports3) { - for (var p3 in m3) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) - __createBinding2(exports3, m3, p3); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar2(require_walletProvider(), exports2); - __exportStar2(require_constants7(), exports2); - } -}); - -// src/elven.ts -init_shim(); -var import_tokens = __toESM(require_tokens(), 1); -var import_tokenOperations = __toESM(require_tokenOperations(), 1); -var import_transactionsFactories = __toESM(require_transactionsFactories(), 1); -var import_transactionsOutcomeParsers = __toESM(require_transactionsOutcomeParsers(), 1); -var import_address4 = __toESM(require_address(), 1); -var import_account4 = __toESM(require_account(), 1); -var import_transaction3 = __toESM(require_transaction(), 1); -var import_transactionComputer = __toESM(require_transactionComputer(), 1); -var import_message = __toESM(require_message(), 1); -var import_transactionWatcher2 = __toESM(require_transactionWatcher(), 1); -var import_signableMessage2 = __toESM(require_signableMessage(), 1); -var import_bytes7 = __toESM(require_bytes(), 1); -var import_numerical = __toESM(require_numerical(), 1); -var import_boolean = __toESM(require_boolean(), 1); -var import_address5 = __toESM(require_address2(), 1); -var import_interface = __toESM(require_interface(), 1); -var import_contractQueryResponse2 = __toESM(require_contractQueryResponse(), 1); - -// src/main.ts -init_shim(); - -// src/auth/init-extension-provider.ts -init_shim(); -var import_extensionProvider = __toESM(require_extensionProvider(), 1); - -// src/utils/ls-helpers.ts -init_shim(); - -// src/utils/constants.ts -init_shim(); -var LOCAL_STORAGE_KEY = "elvenjs_state"; -var defaultApiEndpoint = "https://devnet-api.multiversx.com"; -var DAPP_INIT_ROUTE = "/dapp/init"; -var defaultChainTypeConfig = "devnet"; -var walletConnectDeepLink = "https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/"; -var defaultWalletConnectV2RelayAddresses = [ - "wss://relay.walletconnect.com" -]; -var networkConfig = { - devnet: { - id: "devnet", - shortId: "D", - name: "Devnet", - egldLabel: "xEGLD", - egldDenomination: "18", - decimals: "4", - gasPerDataByte: "1500", - walletAddress: "https://devnet-wallet.multiversx.com", - xAliasAddress: "https://devnet.xalias.com", - apiAddress: "https://devnet-api.multiversx.com", - explorerAddress: "https://devnet-explorer.multiversx.com", - apiTimeout: 1e4 - }, - testnet: { - id: "testnet", - shortId: "T", - name: "Testnet", - egldLabel: "xEGLD", - egldDenomination: "18", - decimals: "4", - gasPerDataByte: "1500", - walletAddress: "https://testnet-wallet.multiversx.com", - xAliasAddress: "https://testnet.xalias.com", - apiAddress: "https://testnet-api.multiversx.com", - explorerAddress: "https://testnet-explorer.multiversx.com", - apiTimeout: 1e4 - }, - mainnet: { - id: "mainnet", - shortId: "1", - name: "Mainnet", - egldLabel: "EGLD", - egldDenomination: "18", - decimals: "4", - gasPerDataByte: "1500", - walletAddress: "https://wallet.multiversx.com", - xAliasAddress: "https://xalias.com", - apiAddress: "https://api.multiversx.com", - explorerAddress: "https://explorer.multiversx.com", - apiTimeout: 1e4 - } -}; - -// src/utils/ls-helpers.ts -var ls = { - get(key) { - const state = localStorage.getItem(LOCAL_STORAGE_KEY); - if (!state) - return {}; - const parsedState = JSON.parse(state); - if (key) { - return parsedState[key]; - } - return parsedState; - }, - set(key, value) { - const currentState = this.get(); - currentState[key] = value; - localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(currentState)); - }, - clear() { - localStorage.removeItem(LOCAL_STORAGE_KEY); - } -}; - -// src/auth/init-extension-provider.ts -var initExtensionProvider = async () => { - const dappProvider = import_extensionProvider.ExtensionProvider.getInstance(); - try { - const isSuccessfullyInitialized = await dappProvider.init(); - const currentState = ls.get(); - if (currentState?.address) { - dappProvider.setAddress(currentState.address); - } - if (!isSuccessfullyInitialized) { - console.warn( - "Something went wrong when trying to initialize the ExtensionProvider.." - ); - return; - } - return dappProvider; - } catch (e2) { - console.warn("Can't initialize the Dapp Provider!"); - } -}; - -// src/main.ts -var import_extensionProvider2 = __toESM(require_extensionProvider(), 1); -var import_walletConnectV2Provider4 = __toESM(require_walletConnectV2Provider(), 1); -var import_walletProvider4 = __toESM(require_walletProvider(), 1); -var import_native_auth2 = __toESM(require_native_auth_client(), 1); -var import_signableMessage = __toESM(require_signableMessage(), 1); - -// src/auth/init-mobile-provider.ts -init_shim(); -var import_walletConnectV2Provider = __toESM(require_walletConnectV2Provider(), 1); - -// src/auth/logout.ts -init_shim(); - -// src/events-store.ts -init_shim(); -var EventsStore = class { - static set(name2, fn) { - if (!name2) - return; - const eventsObj = { ...this.events, [name2]: fn }; - this.events = eventsObj; - } - static get(name2) { - if (!name2 || !this.events) - return; - return this.events[name2]; - } - static run(name2, ...args) { - if (!name2 || !this.events) - return; - this.events[name2]?.(...args); - } - static clear() { - this.events = void 0; - } -}; - -// src/types.ts -init_shim(); -var EventStoreEvents = /* @__PURE__ */ ((EventStoreEvents2) => { - EventStoreEvents2["onLoginStart"] = "onLoginStart"; - EventStoreEvents2["onLoginSuccess"] = "onLoginSuccess"; - EventStoreEvents2["onLoginFailure"] = "onLoginFailure"; - EventStoreEvents2["onLogoutStart"] = "onLogoutStart"; - EventStoreEvents2["onLogoutSuccess"] = "onLogoutSuccess"; - EventStoreEvents2["onLogoutFailure"] = "onLogoutFailure"; - EventStoreEvents2["onQrPending"] = "onQrPending"; - EventStoreEvents2["onQrLoaded"] = "onQrLoaded"; - EventStoreEvents2["onTxStart"] = "onTxStart"; - EventStoreEvents2["onTxSent"] = "onTxSent"; - EventStoreEvents2["onTxFinalized"] = "onTxFinalized"; - EventStoreEvents2["onTxFailure"] = "onTxFailure"; - EventStoreEvents2["onSignMsgStart"] = "onSignMsgStart"; - EventStoreEvents2["onSignMsgFinalized"] = "onSignMsgFinalized"; - EventStoreEvents2["onSignMsgFailure"] = "onSignMsgFailure"; - EventStoreEvents2["onQueryStart"] = "onQueryStart"; - EventStoreEvents2["onQueryFinalized"] = "onQueryFinalized"; - EventStoreEvents2["onQueryFailure"] = "onQueryFailure"; - return EventStoreEvents2; -})(EventStoreEvents || {}); -var LoginMethodsEnum = /* @__PURE__ */ ((LoginMethodsEnum2) => { - LoginMethodsEnum2["ledger"] = "ledger"; - LoginMethodsEnum2["mobile"] = "mobile"; - LoginMethodsEnum2["webWallet"] = "web-wallet"; - LoginMethodsEnum2["browserExtension"] = "browser-extension"; - LoginMethodsEnum2["xAlias"] = "x-alias"; - LoginMethodsEnum2["xPortalHub"] = "x-portal-hub"; - return LoginMethodsEnum2; -})(LoginMethodsEnum || {}); -var DappCoreWCV2CustomMethodsEnum = /* @__PURE__ */ ((DappCoreWCV2CustomMethodsEnum2) => { - DappCoreWCV2CustomMethodsEnum2["mvx_cancelAction"] = "mvx_cancelAction"; - DappCoreWCV2CustomMethodsEnum2["mvx_signNativeAuthToken"] = "mvx_signNativeAuthToken"; - return DappCoreWCV2CustomMethodsEnum2; -})(DappCoreWCV2CustomMethodsEnum || {}); -var WebWalletUrlParamsEnum = /* @__PURE__ */ ((WebWalletUrlParamsEnum2) => { - WebWalletUrlParamsEnum2["hasWebWalletGuardianSign"] = "hasWebWalletGuardianSign"; - return WebWalletUrlParamsEnum2; -})(WebWalletUrlParamsEnum || {}); - -// src/utils/error-parse.ts -init_shim(); -var errorParse = (err) => { - if (typeof err === "string") { - return err.toUpperCase(); - } else if (err instanceof Error) { - return err.message; - } - return JSON.stringify(err); -}; - -// src/auth/logout.ts -var logout = async (elven) => { - if (!elven.dappProvider) { - throw new Error("Logout failed: There is no active session!"); - } - EventsStore.run("onLogoutStart" /* onLogoutStart */); - try { - const isLoggedOut = await elven.dappProvider.logout(); - if (isLoggedOut) { - ls.clear(); - EventsStore.run("onLogoutSuccess" /* onLogoutSuccess */); - } - return isLoggedOut; - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to logout the user: ${err}`); - EventsStore.run("onLogoutFailure" /* onLogoutFailure */, err); - } -}; - -// src/utils/get-random-address-from-network.ts -init_shim(); -function getRandomAddressFromNetwork(addresses) { - return addresses[Math.floor(Math.random() * addresses.length)]; -} - -// src/auth/init-mobile-provider.ts -var initMobileProvider = async (elven) => { - if (!elven.initOptions.walletConnectV2ProjectId || !elven.initOptions.chainType) { - return void 0; - } - const providerHandlers = { - onClientLogin: () => { - }, - onClientLogout: () => logout(elven), - onClientEvent: (event) => { - console.log("wc2 session event: ", event); - } - }; - const relayAddress = getRandomAddressFromNetwork( - elven.initOptions.walletConnectV2RelayAddresses - ); - const dappProviderInstance = new import_walletConnectV2Provider.WalletConnectV2Provider( - providerHandlers, - networkConfig[elven.initOptions.chainType].shortId, - relayAddress, - elven.initOptions.walletConnectV2ProjectId - ); - try { - await dappProviderInstance.init(); - return dappProviderInstance; - } catch { - console.warn("Can't initialize the Dapp Provider!"); - } -}; - -// src/network-provider.ts -init_shim(); -var import_address = __toESM(require_address(), 1); -var import_transactionStatus = __toESM(require_transactionStatus(), 1); -var import_transactionReceipt = __toESM(require_transactionReceipt(), 1); -var import_transactionLogs = __toESM(require_transactionLogs(), 1); -var import_contractResults = __toESM(require_contractResults(), 1); -var import_contractQueryResponse = __toESM(require_contractQueryResponse(), 1); -var import_contractQueryRequest = __toESM(require_contractQueryRequest(), 1); -var import_query = __toESM(require_query(), 1); -var ApiNetworkProvider = class { - constructor({ apiUrl, chainType, apiTimeout }) { - this.chainType = chainType || defaultChainTypeConfig; - this.apiUrl = apiUrl || networkConfig[this.chainType]?.apiAddress; - this.apiTimeout = apiTimeout || networkConfig[this.chainType]?.apiTimeout; - } - async apiGet(endpoint, options) { - if (typeof fetch !== "undefined") { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); - const defaultOptions = { - method: "GET", - headers: { - "Content-Type": "application/json", - Accept: "application/json" - }, - signal: controller.signal - }; - try { - const response = await fetch( - this.apiUrl + "/" + endpoint, - Object.assign(defaultOptions, options || {}) - ); - const result = await response.json(); - if (!response.ok) { - const error = result?.error || response.status; - clearTimeout(timeoutId); - return Promise.reject(error); - } - clearTimeout(timeoutId); - return result; - } catch (e2) { - this.handleApiError(e2, endpoint); - } - } - } - async apiPost(endpoint, payload, options) { - if (typeof fetch !== "undefined") { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.apiTimeout); - const defaultOptions = { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json" - }, - body: JSON.stringify(payload || {}), - signal: controller.signal - }; - try { - const response = await fetch( - this.apiUrl + "/" + endpoint, - Object.assign(defaultOptions, options || {}) - ); - const result = await response.json(); - if (!response.ok) { - const error = result?.error || response.status; - clearTimeout(timeoutId); - return Promise.reject(error); - } - clearTimeout(timeoutId); - return result; - } catch (e2) { - this.handleApiError(e2, endpoint); - } - } - } - handleApiError(error, resourceUrl) { - if (!error.response) { - throw new Error( - `Request error on url [${resourceUrl}]: [${error.toString()}]` - ); - } - const errorData = error.response.data; - const originalErrorMessage = errorData.error || errorData.message || JSON.stringify(errorData); - throw new Error(originalErrorMessage); - } - async sendTransaction(tx) { - const response = await this.apiPost("transactions", tx.toSendable()); - return response.txHash; - } - async getAccount(address) { - const responsePayload = await this.apiGet(`accounts/${address.bech32()}`); - const account = { - address: new import_address.Address(responsePayload?.address || ""), - nonce: Number(responsePayload?.nonce || 0), - balance: BigInt(responsePayload?.balance || 0), - code: responsePayload?.code || "", - userName: responsePayload?.username || "" - }; - return account; - } - async getGuardianData(address) { - const response = await this.apiGet( - `address/${address.bech32()}/guardian-data` - ); - const accountGuardian = { - guarded: response?.data?.guardianData?.guarded || false, - activeGuardian: response?.data?.guardianData?.activeGuardian, - pendingGuardian: response?.data?.guardianData?.pendingGuardian - }; - return accountGuardian; - } - async getTransaction(txHash) { - const payload = await this.apiGet(`transactions/${txHash}`); - const status = new import_transactionStatus.TransactionStatus(payload.status); - const transaction = { - hash: txHash, - type: payload.type || "", - nonce: payload.nonce || 0, - round: payload.round, - epoch: payload.epoch || 0, - value: (payload.value || 0).toString(), - sender: new import_address.Address(payload.sender), - receiver: new import_address.Address(payload.receiver), - gasPrice: payload.gasPrice || 0, - gasLimit: payload.gasLimit || 0, - data: import_buffer.Buffer.from(payload.data || "", "base64"), - status, - timestamp: payload.timestamp || 0, - blockNonce: payload.blockNonce || 0, - hyperblockNonce: payload.hyperblockNonce || 0, - hyperblockHash: payload.hyperblockHash || "", - receipt: import_transactionReceipt.TransactionReceipt.fromHttpResponse(payload.receipt || {}), - logs: import_transactionLogs.TransactionLogs.fromHttpResponse(payload.logs || {}), - contractResults: import_contractResults.ContractResults.fromApiHttpResponse( - payload.results || [] - ), - isCompleted: !status.isPending() - }; - return transaction; - } - async queryContract({ - address, - func, - args, - value, - caller - }) { - try { - const query = new import_query.Query({ - address, - func, - args, - value, - caller - }); - const request = new import_contractQueryRequest.ContractQueryRequest(query).toHttpRequest(); - const response = await this.apiPost("query", request); - return import_contractQueryResponse.ContractQueryResponse.fromHttpResponse(response); - } catch (e2) { - this.handleApiError(e2, "query"); - } - } -}; - -// src/auth/login-with-extension.ts -init_shim(); - -// src/auth/expires-at.ts -init_shim(); -var getNewLoginExpiresTimestamp = () => { - return (/* @__PURE__ */ new Date()).setHours((/* @__PURE__ */ new Date()).getHours() + 24); -}; -var isLoginExpired = (expirationTimestamp) => { - return Date.now() > expirationTimestamp; -}; - -// src/auth/account-sync.ts -init_shim(); -var import_address2 = __toESM(require_address(), 1); -var import_account = __toESM(require_account(), 1); -var accountSync = async (elven) => { - const address = ls.get("address"); - const loginExpires = ls.get("expires"); - const loginExpired = loginExpires && isLoginExpired(loginExpires); - if (!loginExpired && address && elven.networkProvider) { - const userAddressInstance = new import_address2.Address(address); - const userAccountInstance = new import_account.Account(userAddressInstance); - try { - const userAccountOnNetwork = await elven.networkProvider.getAccount(userAddressInstance); - const userGuardianOnNetwork = await elven.networkProvider.getGuardianData(userAddressInstance); - ls.set("address", address); - ls.set( - "activeGuardian", - userGuardianOnNetwork.guarded && userGuardianOnNetwork.activeGuardian?.address ? userGuardianOnNetwork.activeGuardian.address : "" - ); - ls.set("nonce", userAccountOnNetwork.nonce.valueOf()); - ls.set("balance", userAccountOnNetwork.balance.toString()); - userAccountInstance.update(userAccountOnNetwork); - } catch (e2) { - const err = errorParse(e2); - console.warn( - `Something went wrong trying to synchronize the user account: ${err}` - ); - } - } -}; - -// src/auth/login-with-extension.ts -var loginWithExtension = async (elven, loginToken, nativeAuthClient, callbackRoute = "/") => { - const dappProvider = await initExtensionProvider(); - const callbackUrl = encodeURIComponent( - `${window.location.origin}${callbackRoute}` - ); - const providerLoginData = { - callbackUrl, - token: loginToken - }; - try { - if (dappProvider) { - const address = await dappProvider.login(providerLoginData); - if (!address) { - throw new Error("There were problems while logging in!"); - } - } - } catch (e2) { - const err = errorParse(e2); - throw new Error(err); - } - if (!dappProvider) { - throw new Error("There were problems with auth provider initialization!"); - } - const { signature } = dappProvider.account; - ls.set("loginToken", loginToken); - if (signature) { - ls.set("signature", signature); - } - if (elven.networkProvider && signature) { - try { - const address = await dappProvider.getAddress(); - if (!address) { - throw new Error("Canceled!"); - } - ls.set("address", address); - ls.set("loginMethod", "browser-extension" /* browserExtension */); - ls.set("expires", getNewLoginExpiresTimestamp()); - await accountSync(elven); - const accessToken = nativeAuthClient.getToken( - address, - loginToken, - signature - ); - ls.set("accessToken", accessToken); - EventsStore.run("onLoginSuccess" /* onLoginSuccess */); - return dappProvider; - } catch (e2) { - throw new Error( - `Something went wrong trying to synchronize the user account: ${e2?.message}` - ); - } - } -}; - -// src/auth/login-with-mobile.ts -init_shim(); - -// src/auth/qr-code-and-pairings-builder.ts -init_shim(); -var import_qrcode = __toESM(require_browser7(), 1); -var import_walletConnectV2Provider2 = __toESM(require_walletConnectV2Provider(), 1); -var htmlStringToElement = (htmlString) => { - const template = document.createElement("template"); - template.innerHTML = htmlString.trim(); - return template.content.firstChild?.cloneNode(true); -}; -var buildDeepLink = (walletConnectUri) => { - const hrefVal = `${walletConnectDeepLink}?wallet-connect=${encodeURIComponent( - walletConnectUri - )}`; - const aElem = document.createElement("a"); - aElem.setAttribute("href", hrefVal); - aElem.setAttribute("rel", "noopener noreferrer nofollow"); - aElem.setAttribute("target", "_blank"); - aElem.textContent = "xPortal login"; - aElem.classList.add("elven-qr-code-deep-link"); - return aElem; -}; -var buildPairingsContainer = () => { - const container = document.createElement("div"); - container.classList.add("elven-wc-pairings"); - return container; -}; -var buildPairingsHeader = () => { - const headerElem = document.createElement("div"); - headerElem.textContent = "Existing WalletConnect pairings:"; - headerElem.classList.add("elven-wc-pairings-header"); - return headerElem; -}; -var pairingRemoveControllers = {}; -var buildPairingsRemoveButton = (pairing, removeExistingPairing) => { - const btn = document.createElement("button"); - btn.classList.add("elven-wc-pairings-remove-btn"); - btn.textContent = "\u2716"; - pairingRemoveControllers[pairing.topic] = new AbortController(); - btn.addEventListener( - "click", - (e2) => { - e2.stopImmediatePropagation(); - removeExistingPairing(pairing.topic); - }, - { - signal: pairingRemoveControllers[pairing.topic].signal - } - ); - return btn; -}; -var pairingLoginControllers = {}; -var buildPairingItem = (pairing, removeExistingPairing, loginThroughExistingPairing) => { - const itemElem = document.createElement("div"); - const itemTextWrapper = document.createElement("div"); - itemElem.classList.add("elven-wc-pairing-item"); - itemElem.setAttribute("id", pairing.topic); - itemTextWrapper.classList.add("elven-wc-pairing-item-description"); - itemTextWrapper.textContent = `${pairing.peerMetadata?.description} (${pairing.peerMetadata?.url})`; - itemElem.appendChild(itemTextWrapper); - const button = buildPairingsRemoveButton(pairing, removeExistingPairing); - itemElem.appendChild(button); - pairingLoginControllers[pairing.topic] = new AbortController(); - itemElem.addEventListener( - "click", - () => loginThroughExistingPairing(pairing.topic), - { signal: pairingLoginControllers[pairing.topic].signal } - ); - return itemElem; -}; -var buildPairingItemConfirmMessage = () => { - const itemElem = document.createElement("div"); - itemElem.classList.add("elven-wc-pairing-item-confirm-msessage"); - itemElem.setAttribute("id", "elven-wc-pairing-item-confirm-msessage"); - itemElem.innerText = "Confirm on xPortal app!"; - return itemElem; -}; -var removePairingItem = (topic) => { - if (!topic) - return; - const pairingElement = document.getElementById(topic); - pairingElement?.remove(); -}; -var isMobile = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( - navigator.userAgent -); -var generateQRCode = async (walletConnectUri) => { - if (!walletConnectUri) { - return; - } - const svg = await import_qrcode.default.toString(walletConnectUri, { - type: "svg" - }); - return svg; -}; -var qrCodeAndPairingsBuilder = async (qrCodeContainer, walletConnectUri, dappProvider, token) => { - if (!qrCodeContainer) - throw new Error( - "Please provide the QR Code and WalletConnect Pairings container id!" - ); - let containerElem = null; - if (typeof qrCodeContainer === "string") { - containerElem = document.getElementById(qrCodeContainer); - } else if (qrCodeContainer instanceof HTMLElement) { - containerElem = qrCodeContainer; - } - const qrCodeElementString = await generateQRCode(walletConnectUri); - let qrCodeSvg; - if (qrCodeElementString) { - qrCodeSvg = htmlStringToElement(qrCodeElementString); - } - if (containerElem && qrCodeSvg) { - containerElem.replaceChildren(); - containerElem.appendChild(qrCodeSvg); - if (isMobile()) { - containerElem.appendChild(buildDeepLink(walletConnectUri)); - } - } - if (containerElem && dappProvider instanceof import_walletConnectV2Provider2.WalletConnectV2Provider) { - const wcPairings = dappProvider.pairings; - const removeExistingPairing = async (topic) => { - try { - if (topic) { - await dappProvider.logout({ - topic - }); - removePairingItem(topic); - } - } catch (e2) { - const err = errorParse(e2); - console.warn( - `Something went wrong trying to remove the existing pairing: ${err}` - ); - } finally { - pairingLoginControllers[topic].abort(); - } - }; - const loginThroughExistingPairing = async (topic) => { - try { - const { approval } = await dappProvider.connect({ - topic, - methods: [ - "mvx_cancelAction" /* mvx_cancelAction */, - "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ - ] - }); - const pairingItemConfirmation = document.getElementById( - "elven-wc-pairing-item-confirm-msessage" - ); - if (!pairingItemConfirmation) { - const pairingItemElement = document.getElementById(topic); - pairingItemElement?.after(buildPairingItemConfirmMessage()); - } - await dappProvider.login({ - approval, - token - }); - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - } finally { - for (const abortController of Object.values(pairingLoginControllers)) { - abortController?.abort(); - } - for (const abortController of Object.values(pairingRemoveControllers)) { - abortController?.abort(); - } - } - }; - if (wcPairings && wcPairings.length > 0) { - const container = buildPairingsContainer(); - containerElem.appendChild(container); - const headerElem = buildPairingsHeader(); - container.appendChild(headerElem); - for (const pairing of wcPairings) { - const itemElem = buildPairingItem( - pairing, - removeExistingPairing, - loginThroughExistingPairing - ); - container.appendChild(itemElem); - } - } - } - return containerElem; -}; - -// src/auth/login-with-mobile.ts -var import_walletConnectV2Provider3 = __toESM(require_walletConnectV2Provider(), 1); -var loginWithMobile = async (elven, loginToken, nativeAuthClient, qrCodeContainer) => { - if (!qrCodeContainer) { - throw new Error( - "You haven't provided the QR code container DOM element id" - ); - } - const relayAddress = getRandomAddressFromNetwork( - elven.initOptions.walletConnectV2RelayAddresses - ); - if (!relayAddress || !elven.networkProvider) { - throw new Error( - "Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!" - ); - } - if (!elven.initOptions.walletConnectV2ProjectId) { - throw new Error( - "Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)" - ); - } - if (!elven.initOptions.chainType) { - throw new Error("Please provide the chain type in ElvenJS.init function!"); - } - let qrCodeElement; - const providerHandlers = { - onClientLogin: async () => { - if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { - const address = await elven.dappProvider.getAddress(); - const signature = await elven.dappProvider.getSignature(); - ls.set("address", address); - ls.set("loginMethod", "mobile" /* mobile */); - ls.set("expires", getNewLoginExpiresTimestamp()); - await accountSync(elven); - if (signature) { - ls.set("signature", signature); - } - ls.set("loginToken", loginToken); - const accessToken = nativeAuthClient.getToken( - address, - loginToken, - signature - ); - ls.set("accessToken", accessToken); - EventsStore.run("onLoginSuccess" /* onLoginSuccess */); - qrCodeElement?.replaceChildren(); - } - }, - onClientLogout: async () => { - if (elven.dappProvider instanceof import_walletConnectV2Provider3.WalletConnectV2Provider) { - await logout(elven); - } - }, - onClientEvent: (event) => { - console.log("wc2 session event: ", event); - } - }; - const dappProvider = new import_walletConnectV2Provider3.WalletConnectV2Provider( - providerHandlers, - networkConfig[elven.initOptions.chainType].shortId, - relayAddress, - elven.initOptions.walletConnectV2ProjectId - ); - try { - if (dappProvider) { - elven.dappProvider = dappProvider; - EventsStore.run("onQrPending" /* onQrPending */); - await dappProvider.init(); - const { uri: walletConnectUri, approval } = await dappProvider.connect({ - methods: [ - "mvx_cancelAction" /* mvx_cancelAction */, - "mvx_signNativeAuthToken" /* mvx_signNativeAuthToken */ - ] - }); - const wCUri = loginToken ? `${walletConnectUri}&token=${loginToken}` : walletConnectUri; - if (qrCodeContainer && wCUri) { - qrCodeElement = await qrCodeAndPairingsBuilder( - qrCodeContainer, - wCUri, - dappProvider, - loginToken - ); - EventsStore.run("onQrLoaded" /* onQrLoaded */); - } - await dappProvider.login({ - approval, - token: loginToken - }); - return dappProvider; - } - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - EventsStore.run("onLoginFailure" /* onLoginFailure */, err); - } -}; - -// src/auth/login-with-web-wallet.ts -init_shim(); -var import_walletProvider = __toESM(require_walletProvider(), 1); -var loginWithWebWallet = async (urlAddress, loginToken, chainType, callbackRoute) => { - const dappProvider = new import_walletProvider.WalletProvider(`${urlAddress}${DAPP_INIT_ROUTE}`); - const callbackUrl = typeof window !== "undefined" ? encodeURIComponent(`${window.location.origin}${callbackRoute || "/"}`) : "/"; - const providerLoginData = { - callbackUrl, - token: loginToken - }; - try { - ls.set( - "loginMethod", - networkConfig[chainType].xAliasAddress === urlAddress ? "x-alias" /* xAlias */ : "web-wallet" /* webWallet */ - ); - await dappProvider.login(providerLoginData); - ls.set("expires", getNewLoginExpiresTimestamp()); - ls.set("loginToken", loginToken); - return dappProvider; - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - ls.set("loginMethod", ""); - EventsStore.run("onLoginFailure" /* onLoginFailure */, err); - } -}; - -// src/utils/get-param-from-url.ts -init_shim(); -var getParamFromUrl = (paramName) => { - if (typeof window !== "undefined") { - const url = new URL(window.location.href); - const params = new URLSearchParams(url.search); - return params.get(paramName); - } -}; - -// src/auth/init-web-wallet-provider.ts -init_shim(); -var import_walletProvider2 = __toESM(require_walletProvider(), 1); -var import_native_auth = __toESM(require_native_auth_client(), 1); -var initWebWalletProvider = async (webWalletAddress, apiUrl) => { - const signature = getParamFromUrl("signature"); - const urlAddress = getParamFromUrl("address"); - const lsAddress = ls.get("address"); - const loginToken = ls.get("loginToken"); - if (signature) { - ls.set("signature", signature); - } - if (urlAddress || lsAddress) { - if (urlAddress) { - ls.set("address", urlAddress); - window.history.replaceState(null, "", window.location.pathname); - } - const dappProvider = new import_walletProvider2.WalletProvider( - `${webWalletAddress}${DAPP_INIT_ROUTE}` - ); - if (signature && apiUrl && urlAddress) { - const nativeAuthClient = new import_native_auth.NativeAuthClient({ - apiUrl, - origin: window.location.origin - }); - const accessToken = nativeAuthClient.getToken( - urlAddress, - loginToken, - signature - ); - ls.set("accessToken", accessToken); - } - return dappProvider; - } -}; - -// src/interaction/post-send-tx.ts -init_shim(); -var import_account2 = __toESM(require_account(), 1); -var import_transactionWatcher = __toESM(require_transactionWatcher(), 1); -var postSendTx = async (transaction, networkProvider) => { - EventsStore.run("onTxSent" /* onTxSent */, transaction); - const transactionWatcher = new import_transactionWatcher.TransactionWatcher(networkProvider); - const transactionOnNetwork = await transactionWatcher.awaitCompleted(transaction); - const sender = transactionOnNetwork.sender; - const senderAccount = new import_account2.Account(sender); - const userAccountOnNetwork = await networkProvider.getAccount(sender); - senderAccount.update(userAccountOnNetwork); - ls.set("address", senderAccount.address.bech32()); - ls.set("balance", senderAccount.balance.toString()); - EventsStore.run("onTxFinalized" /* onTxFinalized */, transactionOnNetwork); -}; - -// src/interaction/web-wallet-tx-finalize.ts -init_shim(); -var import_out = __toESM(require_out2(), 1); -var import_transaction = __toESM(require_transaction(), 1); - -// src/interaction/pre-send-tx.ts -init_shim(); -var import_account3 = __toESM(require_account(), 1); -var preSendTx = (tx) => { - const sender = tx.getSender(); - const senderAccount = new import_account3.Account(sender); - const currentNonce = tx.nonce.valueOf(); - senderAccount.incrementNonce(); - ls.set("nonce", (currentNonce + 1n).toString()); -}; - -// src/interaction/web-wallet-tx-finalize.ts -var webWalletTxFinalize = async (dappProvider, networkProvider, urlAddress, nonce) => { - const walletProviderStatus = getParamFromUrl(import_out.WALLET_PROVIDER_CALLBACK_PARAM); - if (walletProviderStatus === import_out.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED && dappProvider && networkProvider) { - const guardian = ls.get("activeGuardian"); - const loginMethod = ls.get("loginMethod"); - const hasWebWalletGuardianSign = getParamFromUrl( - "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */ - ); - let transactionObj; - if ("getTransactionsFromWalletUrl" in dappProvider) { - const txs = dappProvider.getTransactionsFromWalletUrl(); - transactionObj = txs?.[0]; - if (!transactionObj) - return; - if (loginMethod === "web-wallet" /* webWallet */) { - transactionObj.data = import_buffer.Buffer.from(transactionObj.data).toString( - "base64" - ); - } - } else if (guardian && loginMethod !== "web-wallet" /* webWallet */ && loginMethod !== "x-alias" /* xAlias */ && hasWebWalletGuardianSign) { - const webWalletProvider = new import_out.WalletProvider( - `${urlAddress}${DAPP_INIT_ROUTE}` - ); - const txs = webWalletProvider.getTransactionsFromWalletUrl(); - transactionObj = txs?.[0]; - } - if (transactionObj) { - const transaction = import_transaction.Transaction.fromPlainObject(transactionObj); - transaction.nonce = BigInt(nonce); - preSendTx(transaction); - try { - EventsStore.run("onTxStart" /* onTxStart */, transaction); - await networkProvider.sendTransaction(transaction); - await postSendTx(transaction, networkProvider); - } catch (e2) { - const err = errorParse(e2); - const errMsg = `Getting transaction information failed! ${err}`; - EventsStore.run("onTxFailure" /* onTxFailure */, transaction, errMsg); - throw new Error(errMsg); - } finally { - window.history.replaceState(null, "", window.location.pathname); - } - } - window.history.replaceState(null, "", window.location.pathname); - } -}; - -// src/interaction/guardian-operations.ts -init_shim(); -var import_networkParams = __toESM(require_networkParams(), 1); -var import_address3 = __toESM(require_address(), 1); -var import_walletProvider3 = __toESM(require_walletProvider(), 1); -var guardianPreSignTxOperations = (tx) => { - const guardian = ls.get("activeGuardian"); - if (guardian) { - const options = { - guarded: true - }; - tx.setVersion(import_networkParams.TransactionVersion.withTxOptions()); - tx.setOptions(import_networkParams.TransactionOptions.withOptions(options)); - tx.setGuardian(import_address3.Address.fromBech32(guardian)); - } - return tx; -}; -var sendTxToGuardian = async (signedTx, walletAddress) => { - const webWalletProvider = new import_walletProvider3.WalletProvider( - `${walletAddress}${DAPP_INIT_ROUTE}` - ); - const currentUrl = window?.location.href; - const alteredCallbackUrl = new URL(currentUrl); - alteredCallbackUrl.searchParams.set( - "hasWebWalletGuardianSign" /* hasWebWalletGuardianSign */, - "true" - ); - await webWalletProvider.guardTransactions([signedTx], { - callbackUrl: encodeURIComponent(alteredCallbackUrl.toString()) - }); -}; -var checkNeedsGuardianSigning = (signedTx) => { - const guardian = ls.get("activeGuardian"); - const address = ls.get("address"); - if (!address || !guardian) { - return false; - } - if (signedTx.isGuardedTransaction()) { - return false; - } - return true; -}; - -// src/interaction/web-wallet-sign-message-finalize.ts -init_shim(); -var webWalletSignMessageFinalize = () => { - const isNotTransaction = !getParamFromUrl("walletProviderStatus"); - const isSigned = getParamFromUrl("status") === "signed"; - const message = getParamFromUrl("message"); - const signature = getParamFromUrl("signature"); - if (isNotTransaction && isSigned && message && signature) { - EventsStore.run("onSignMsgFinalized" /* onSignMsgFinalized */, message, signature); - window.history.replaceState(null, "", window.location.pathname); - } -}; - -// src/webview-provider/webview-provider.ts -init_shim(); -var import_transaction2 = __toESM(require_transaction(), 1); - -// src/webview-provider/types.ts -init_shim(); -var WebViewProviderResponseBaseEnums = /* @__PURE__ */ ((WebViewProviderResponseBaseEnums2) => { - WebViewProviderResponseBaseEnums2["reloginResponse"] = "RELOGIN_RESPONSE"; - return WebViewProviderResponseBaseEnums2; -})(WebViewProviderResponseBaseEnums || {}); -var CrossWindowProviderResponseEnums = /* @__PURE__ */ ((CrossWindowProviderResponseEnums2) => { - CrossWindowProviderResponseEnums2["handshakeResponse"] = "HANDSHAKE_RESPONSE"; - CrossWindowProviderResponseEnums2["loginResponse"] = "LOGIN_RESPONSE"; - CrossWindowProviderResponseEnums2["disconnectResponse"] = "DISCONNECT_RESPONSE"; - CrossWindowProviderResponseEnums2["cancelResponse"] = "CANCEL_RESPONSE"; - CrossWindowProviderResponseEnums2["signTransactionsResponse"] = "SIGN_TRANSACTIONS_RESPONSE"; - CrossWindowProviderResponseEnums2["signMessageResponse"] = "SIGN_MESSAGE_RESPONSE"; - CrossWindowProviderResponseEnums2["noneResponse"] = "NONE_RESPONSE"; - return CrossWindowProviderResponseEnums2; -})(CrossWindowProviderResponseEnums || {}); -var WebViewProviderResponseEnums = { - ...CrossWindowProviderResponseEnums, - ...WebViewProviderResponseBaseEnums -}; -var WebViewProviderRequestBaseEnums = /* @__PURE__ */ ((WebViewProviderRequestBaseEnums2) => { - WebViewProviderRequestBaseEnums2["signTransactionsWithGuardianResponse"] = "SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE"; - WebViewProviderRequestBaseEnums2["reloginRequest"] = "RELOGIN_REQUEST"; - return WebViewProviderRequestBaseEnums2; -})(WebViewProviderRequestBaseEnums || {}); -var CrossWindowProviderRequestEnums = /* @__PURE__ */ ((CrossWindowProviderRequestEnums2) => { - CrossWindowProviderRequestEnums2["signTransactionsRequest"] = "SIGN_TRANSACTIONS_REQUEST"; - CrossWindowProviderRequestEnums2["signMessageRequest"] = "SIGN_MESSAGE_REQUEST"; - CrossWindowProviderRequestEnums2["loginRequest"] = "LOGIN_REQUEST"; - CrossWindowProviderRequestEnums2["logoutRequest"] = "LOGOUT_REQUEST"; - CrossWindowProviderRequestEnums2["cancelAction"] = "CANCEL_ACTION_REQUEST"; - CrossWindowProviderRequestEnums2["finalizeHandshakeRequest"] = "FINALIZE_HANDSHAKE_REQUEST"; - return CrossWindowProviderRequestEnums2; -})(CrossWindowProviderRequestEnums || {}); -var WebViewProviderRequestEnums = { - ...CrossWindowProviderRequestEnums, - ...WebViewProviderRequestBaseEnums -}; - -// src/webview-provider/utils.ts -init_shim(); -var safeWindow = typeof window !== "undefined" ? window : {}; -var detectCurrentPlatform = () => { - if (safeWindow.ReactNativeWebView) { - return "reactNative" /* reactNative */; - } - if (safeWindow.webkit) { - return "ios" /* ios */; - } - return "web" /* web */; -}; -var getTargetOrigin = () => { - return typeof window != "undefined" && typeof window?.location != "undefined" ? window?.parent?.origin ?? "*" : "*"; -}; -var isString = (x3) => { - return Object.prototype.toString.call(x3) === "[object String]"; -}; - -// src/webview-provider/request-methods.ts -init_shim(); -var requestMethods = { - signTransactions: { - ["ios" /* ios */]: (transactions) => window.webkit.messageHandlers.signTransactions.postMessage( - transactions, - getTargetOrigin() - ), - ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signTransactionsRequest, - message - }) - ), - ["web" /* web */]: (message) => window?.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signTransactionsRequest, - message - }), - getTargetOrigin() - ) - }, - signMessage: { - ["ios" /* ios */]: (message) => window.webkit.messageHandlers.signMessage.postMessage(message), - ["reactNative" /* reactNative */]: (message) => window?.ReactNativeWebView.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signMessageRequest, - message - }) - ), - ["web" /* web */]: (message) => window?.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.signMessageRequest, - message - }), - getTargetOrigin() - ) - }, - logout: { - ["ios" /* ios */]: () => window.webkit.messageHandlers.logout.postMessage(), - ["reactNative" /* reactNative */]: () => window?.ReactNativeWebView.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.logoutRequest - }) - ), - ["web" /* web */]: () => window?.postMessage( - JSON.stringify({ - type: WebViewProviderRequestEnums.logoutRequest - }), - getTargetOrigin() - ) - } -}; - -// src/webview-provider/webview-provider.ts -var currentPlatform = detectCurrentPlatform(); -var messageType = "message"; -var handleWaitForMessage = (cb) => { - const handleMessageReceived = (event) => { - let eventData = event.data; - if (event.target.origin != getTargetOrigin() && currentPlatform != "reactNative" /* reactNative */) { - return; - } - try { - eventData = JSON.parse(eventData); - cb(eventData); - } catch (err) { - console.error("error parsing response"); - } - }; - if (document) { - document.addEventListener(messageType, handleMessageReceived); - } - if (window) { - window.addEventListener(messageType, handleMessageReceived); - } -}; -var WebviewProvider = class { - constructor() { - } - async logout() { - requestMethods.logout[currentPlatform](); - return new Promise((resolve) => { - resolve(true); - }); - } - async signMessage(message) { - try { - requestMethods.signMessage[currentPlatform](message); - const waitForSignedMessageResponse = new Promise( - (resolve, reject) => { - window.signMessageResponse = (signedMessage, error) => { - if (error) { - reject(error); - window.signMessageResponse = null; - return; - } - resolve(signedMessage); - window.signMessageResponse = null; - }; - function handleSignMessageResponse(eventData) { - const { message: message2, type } = eventData; - if (type === WebViewProviderResponseEnums.signMessageResponse && message2 != null) { - const { signedMessage, error } = message2; - if (!error) { - resolve(signedMessage); - } else { - reject(error); - } - } - document?.removeEventListener( - messageType, - handleSignMessageResponse - ); - } - handleWaitForMessage(handleSignMessageResponse); - } - ); - return await waitForSignedMessageResponse; - } catch (err) { - console.error("error sending transaction", err); - throw err; - } - } - async signTransactions(transactions) { - try { - const plainTransactions = transactions.map((tx) => tx.toPlainObject()); - requestMethods.signTransactions[currentPlatform](plainTransactions); - const waitForSignedTransactionsResponse = new Promise((resolve, reject) => { - window.transactionsSigned = (txs, error) => { - txs = JSON.parse(txs); - if (error) { - reject(error); - window.transactionsSigned = null; - return; - } - resolve(txs.map((tx) => import_transaction2.Transaction.fromPlainObject(tx))); - window.transactionsSigned = null; - }; - function handleSignTransactionResponse(eventData) { - const { message, type } = eventData; - if (type === WebViewProviderResponseEnums.signTransactionsResponse) { - const { transactions: transactions2, error } = message; - try { - if (!error) { - resolve( - transactions2.map( - (tx) => import_transaction2.Transaction.fromPlainObject(tx) - ) - ); - } else { - reject(error); - } - } catch (err) { - reject("Unable to sign"); - } - } - if (document) { - document.removeEventListener( - messageType, - handleSignTransactionResponse - ); - } - } - handleWaitForMessage(handleSignTransactionResponse); - }); - return await waitForSignedTransactionsResponse; - } catch (err) { - console.error("error sending transaction", err); - throw err; - } - } - async signTransaction(transaction) { - const response = await this.signTransactions([transaction]); - return response[0]; - } -}; - -// src/auth/login-with-native-auth-token.ts -init_shim(); - -// src/webview-provider/decode-native-auth-token.ts -init_shim(); - -// src/webview-provider/base64-utils.ts -init_shim(); -function isStringBase64(str) { - try { - const atobDecoded = atob(str); - const btoaEncoded = btoa(atobDecoded); - const bufferFromDecoded = import_buffer.Buffer.from(str, "base64").toString(); - const bufferFromEncoded = import_buffer.Buffer.from(bufferFromDecoded).toString("base64"); - const isEqualToInitialString = str === btoaEncoded && str === bufferFromEncoded; - const isAtobEqualToBufferFrom = atobDecoded === bufferFromDecoded; - if (isEqualToInitialString || isAtobEqualToBufferFrom) { - return true; - } - } catch (e2) { - return false; - } - return false; -} -function decodeBase64(string2) { - if (!isStringBase64(string2)) { - return string2; - } - return atob(string2); -} - -// src/webview-provider/decode-login-token.ts -init_shim(); -var decodeLoginToken = (loginToken) => { - if (!loginToken || !isString(loginToken)) { - return null; - } - const parts = loginToken.split("."); - if (parts.length !== 4) { - return null; - } - try { - const [origin, blockHash, ttl, extraInfo] = parts; - const parsedExtraInfo = JSON.parse(decodeBase64(extraInfo)); - const parsedOrigin = decodeBase64(origin); - return { - ttl: Number(ttl), - extraInfo: parsedExtraInfo, - origin: parsedOrigin, - blockHash - }; - } catch (e2) { - console.error(`Error trying to decode ${loginToken}:`, e2); - return null; - } -}; - -// src/webview-provider/decode-native-auth-token.ts -var decodeNativeAuthToken = (accessToken) => { - if (!accessToken || !isString(accessToken)) { - return null; - } - const parts = accessToken.split("."); - if (parts.length !== 3) { - console.error( - "Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead" - ); - return null; - } - try { - const [address, body, signature] = parts; - const parsedAddress = decodeBase64(address); - const parsedBody = decodeBase64(body); - const parsedInitToken = decodeLoginToken(parsedBody); - if (!parsedInitToken) { - return { - address: parsedAddress, - body: parsedBody, - signature, - blockHash: "", - origin: "", - ttl: 0 - }; - } - const result = { - ...parsedInitToken, - address: parsedAddress, - body: parsedBody, - signature - }; - if (!parsedInitToken.extraInfo?.timestamp) { - delete result.extraInfo; - } - return result; - } catch (err) { - return null; - } -}; - -// src/auth/login-with-native-auth-token.ts -function loginWithNativeAuthToken(token, elven) { - const nativeAuthInfo = decodeNativeAuthToken(token); - if (nativeAuthInfo == null) { - return; - } - const { signature, address, body } = nativeAuthInfo; - if (signature && token && address) { - ls.set("loginToken", body); - ls.set("accessToken", token); - ls.set("signature", signature); - ls.set("address", address); - ls.set("loginMethod", "x-portal-hub" /* xPortalHub */); - elven.dappProvider = new WebviewProvider(); - } -} - -// src/initialize-events-store.ts -init_shim(); -var initializeEventsStore = (initOptions) => { - if (initOptions.onLoginStart) { - EventsStore.set("onLoginStart" /* onLoginStart */, initOptions.onLoginStart); - } - if (initOptions.onLoginSuccess) { - EventsStore.set( - "onLoginSuccess" /* onLoginSuccess */, - initOptions.onLoginSuccess - ); - } - if (initOptions.onLoginFailure) { - EventsStore.set( - "onLoginFailure" /* onLoginFailure */, - initOptions.onLoginFailure - ); - } - if (initOptions.onLogoutStart) { - EventsStore.set("onLogoutStart" /* onLogoutStart */, initOptions.onLogoutStart); - } - if (initOptions.onLogoutSuccess) { - EventsStore.set( - "onLogoutSuccess" /* onLogoutSuccess */, - initOptions.onLogoutSuccess - ); - } - if (initOptions.onLogoutFailure) { - EventsStore.set( - "onLogoutFailure" /* onLogoutFailure */, - initOptions.onLogoutFailure - ); - } - if (initOptions.onQrPending) { - EventsStore.set("onQrPending" /* onQrPending */, initOptions.onQrPending); - } - if (initOptions.onQrLoaded) { - EventsStore.set("onQrLoaded" /* onQrLoaded */, initOptions.onQrLoaded); - } - if (initOptions.onTxStart) { - EventsStore.set("onTxStart" /* onTxStart */, initOptions.onTxStart); - } - if (initOptions.onTxSent) { - EventsStore.set("onTxSent" /* onTxSent */, initOptions.onTxSent); - } - if (initOptions.onTxFinalized) { - EventsStore.set("onTxFinalized" /* onTxFinalized */, initOptions.onTxFinalized); - } - if (initOptions.onTxFailure) { - EventsStore.set("onTxFailure" /* onTxFailure */, initOptions.onTxFailure); - } - if (initOptions.onSignMsgStart) { - EventsStore.set( - "onSignMsgStart" /* onSignMsgStart */, - initOptions.onSignMsgStart - ); - } - if (initOptions.onSignMsgFinalized) { - EventsStore.set( - "onSignMsgFinalized" /* onSignMsgFinalized */, - initOptions.onSignMsgFinalized - ); - } - if (initOptions.onSignMsgFailure) { - EventsStore.set( - "onSignMsgFailure" /* onSignMsgFailure */, - initOptions.onSignMsgFailure - ); - } - if (initOptions.onQueryStart) { - EventsStore.set("onQueryStart" /* onQueryStart */, initOptions.onQueryStart); - } - if (initOptions.onQueryFinalized) { - EventsStore.set( - "onQueryFinalized" /* onQueryFinalized */, - initOptions.onQueryFinalized - ); - } - if (initOptions.onQueryFailure) { - EventsStore.set( - "onQueryFailure" /* onQueryFailure */, - initOptions.onQueryFailure - ); - } -}; - -// src/utils/with-login-events.ts -init_shim(); -var withLoginEvents = async (fn) => { - EventsStore.run("onLoginStart" /* onLoginStart */); - try { - await fn(() => { - EventsStore.run("onLoginSuccess" /* onLoginSuccess */); - }); - } catch (e2) { - const err = errorParse(e2); - console.warn(`Something went wrong trying to login the user: ${err}`); - EventsStore.run("onLoginFailure" /* onLoginFailure */, err); - } -}; - -// src/main.ts -var ElvenJS = class { - /** - * Initialization of the Elven.js - */ - static async init(options) { - const state = ls.get(); - if (state.expires && isLoginExpired(state.expires)) { - ls.clear(); - this.dappProvider = void 0; - return; - } - this.initOptions = { - chainType: defaultChainTypeConfig, - apiUrl: defaultApiEndpoint, - apiTimeout: 1e4, - walletConnectV2ProjectId: "", - walletConnectV2RelayAddresses: defaultWalletConnectV2RelayAddresses, - ...options - }; - this.networkProvider = new ApiNetworkProvider(this.initOptions); - initializeEventsStore(this.initOptions); - const nativeAuthTokenFromUrl = getParamFromUrl("accessToken"); - if (nativeAuthTokenFromUrl) { - await withLoginEvents(async (onLoginSuccess) => { - loginWithNativeAuthToken(nativeAuthTokenFromUrl, this); - await accountSync(this); - onLoginSuccess(); - }); - } - const isAddress = state?.address || (state.loginMethod === "web-wallet" /* webWallet */ || state.loginMethod === "x-alias" /* xAlias */) && getParamFromUrl("address"); - if (isAddress && state?.loginMethod) { - await withLoginEvents(async (onLoginSuccess) => { - if (state.loginMethod === "browser-extension" /* browserExtension */) { - this.dappProvider = await initExtensionProvider(); - } - if (state.loginMethod === "mobile" /* mobile */) { - this.dappProvider = await initMobileProvider(this); - } - if (state.loginMethod === "x-portal-hub" /* xPortalHub */) { - this.dappProvider = new WebviewProvider(); - } - if (state.loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { - this.dappProvider = await initWebWalletProvider( - networkConfig[this.initOptions.chainType].walletAddress, - this.initOptions.apiUrl - ); - } - if (state.loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { - this.dappProvider = await initWebWalletProvider( - networkConfig[this.initOptions.chainType].xAliasAddress, - this.initOptions.apiUrl - ); - } - await accountSync(this); - onLoginSuccess(); - }); - if (this.initOptions?.chainType) { - await webWalletTxFinalize( - this.dappProvider, - this.networkProvider, - networkConfig[this.initOptions.chainType][state.loginMethod === "x-alias" /* xAlias */ ? "xAliasAddress" : "walletAddress"], - state.nonce - ); - webWalletSignMessageFinalize(); - } - } - } - /** - * Login function - */ - static async login(loginMethod, options) { - const isProperLoginMethod = Object.values(LoginMethodsEnum).includes(loginMethod); - if (!isProperLoginMethod) { - const error = "Wrong login method!"; - EventsStore.run("onLoginFailure" /* onLoginFailure */, error); - throw new Error(error); - } - if (!this.networkProvider) { - const error = "Login failed: Use ElvenJs.init() first!"; - EventsStore.run("onLoginFailure" /* onLoginFailure */, error); - throw new Error(error); - } - await withLoginEvents(async () => { - const nativeAuthClient = new import_native_auth2.NativeAuthClient({ - apiUrl: this.initOptions?.apiUrl, - origin: window.location.origin - }); - const loginToken = await nativeAuthClient.initialize(); - if (loginMethod === "browser-extension" /* browserExtension */) { - const dappProvider = await loginWithExtension( - this, - loginToken, - nativeAuthClient, - options?.callbackRoute - ); - this.dappProvider = dappProvider; - } - if (loginMethod === "mobile" /* mobile */) { - const dappProvider = await loginWithMobile( - this, - loginToken, - nativeAuthClient, - options?.qrCodeContainer - ); - this.dappProvider = dappProvider; - } - if (loginMethod === "web-wallet" /* webWallet */ && this.initOptions?.chainType) { - const dappProvider = await loginWithWebWallet( - networkConfig[this.initOptions.chainType].walletAddress, - loginToken, - this.initOptions?.chainType, - options?.callbackRoute - ); - this.dappProvider = dappProvider; - } - if (loginMethod === "x-alias" /* xAlias */ && this.initOptions?.chainType) { - const dappProvider = await loginWithWebWallet( - networkConfig[this.initOptions.chainType].xAliasAddress, - loginToken, - this.initOptions?.chainType, - options?.callbackRoute - ); - this.dappProvider = dappProvider; - } - }); - } - /** - * Logout function - */ - static async logout() { - try { - const isLoggedOut = await logout(this); - this.dappProvider = void 0; - return isLoggedOut; - } catch (e2) { - const err = errorParse(e2); - console.warn("Something went wrong when logging out: ", err); - } - } - /** - * Sign and send function - */ - static async signAndSendTransaction(transaction) { - if (!this.dappProvider) { - const error = "Transaction signing failed: There is no active session!"; - EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); - throw new Error(error); - } - if (!this.networkProvider) { - const error = "Transaction signing failed: There is no active network provider!"; - EventsStore.run("onTxFailure" /* onTxFailure */, transaction, error); - throw new Error(error); - } - let signedTx = guardianPreSignTxOperations(transaction); - try { - EventsStore.run("onTxStart" /* onTxStart */, transaction); - const currentState = ls.get(); - transaction.nonce = currentState.nonce; - if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { - signedTx = await this.dappProvider.signTransaction(transaction); - } - if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { - signedTx = await this.dappProvider.signTransaction(transaction); - } - if (this.dappProvider instanceof WebviewProvider) { - signedTx = await this.dappProvider.signTransaction(transaction); - } - if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { - await this.dappProvider.signTransaction(transaction); - } - if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { - const needsGuardianSign = checkNeedsGuardianSigning(signedTx); - if (!needsGuardianSign) { - preSendTx(signedTx); - } - if (needsGuardianSign && this.initOptions?.chainType) { - await sendTxToGuardian( - signedTx, - networkConfig[this.initOptions.chainType].walletAddress - ); - return; - } - await this.networkProvider.sendTransaction(signedTx); - await postSendTx(signedTx, this.networkProvider); - } - } catch (e2) { - const err = errorParse(e2); - EventsStore.run( - "onTxFailure" /* onTxFailure */, - signedTx, - `Getting transaction information failed! ${err}` - ); - throw new Error(`Getting transaction information failed! ${err}`); - } - return signedTx; - } - /** - * Sign a single message - */ - static async signMessage(message, options) { - if (!this.dappProvider) { - const error = "Message signing failed: There is no active session!"; - EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); - throw new Error(error); - } - if (!this.networkProvider) { - const error = "Message signing failed: There is no active network provider!"; - EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, error); - throw new Error(error); - } - let messageSignature = ""; - try { - EventsStore.run("onSignMsgStart" /* onSignMsgStart */, message); - if (this.dappProvider instanceof import_extensionProvider2.ExtensionProvider) { - const signedMessage = await this.dappProvider.signMessage( - new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) - ); - messageSignature = signedMessage.getSignature().toString("hex"); - } - if (this.dappProvider instanceof import_walletConnectV2Provider4.WalletConnectV2Provider) { - const signedMessage = await this.dappProvider.signMessage( - new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }) - ); - messageSignature = signedMessage.getSignature().toString("hex"); - } - if (this.dappProvider instanceof WebviewProvider) { - messageSignature = await this.dappProvider.signMessage(message); - } - if (this.dappProvider instanceof import_walletProvider4.WalletProvider) { - const encodeRFC3986URIComponent = (str) => { - return encodeURIComponent(str).replace( - /[!'()*]/g, - (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}` - ); - }; - const url = options?.callbackUrl || window.location.origin; - await this.dappProvider.signMessage( - new import_signableMessage.SignableMessage({ message: import_buffer.Buffer.from(message) }), - { - callbackUrl: encodeURIComponent( - `${url}${url.includes("?") ? "&" : "?"}message=${encodeRFC3986URIComponent(message)}` - ) - } - ); - } - const currentState = ls.get(); - if (currentState.loginMethod !== "web-wallet" /* webWallet */ && currentState.loginMethod !== "x-alias" /* xAlias */) { - EventsStore.run( - "onSignMsgFinalized" /* onSignMsgFinalized */, - message, - messageSignature - ); - } - return { message, messageSignature }; - } catch (e2) { - const err = errorParse(e2); - EventsStore.run("onSignMsgFailure" /* onSignMsgFailure */, message, err); - throw new Error(`Message signing failed! ${err}`); - } - } - /** - * Query Smart Contracts - */ - static async queryContract({ - address, - func, - args = [], - value = 0, - caller - }) { - if (!this.networkProvider) { - throw new Error("Query failed: There is no active network provider!"); - } - if (!address || !func) { - throw new Error( - "Query failed: The Query arguments are not valid! Address and func required" - ); - } - const queryArgs = { - address, - func, - args, - value, - caller - }; - try { - EventsStore.run("onQueryStart" /* onQueryStart */, queryArgs); - const response = await this.networkProvider.queryContract(queryArgs); - EventsStore.run("onQueryFinalized" /* onQueryFinalized */, response); - return response; - } catch (e2) { - const err = errorParse(e2); - EventsStore.run("onQueryFinalized" /* onQueryFinalized */, queryArgs, err); - throw new Error(`Smart contract query failed! ${err}`); - } - } - static { - /** - * Main storage - */ - this.storage = ls; - } - static { - /** - * Destroy and cleanup if needed - */ - this.destroy = () => { - this.networkProvider = void 0; - this.dappProvider = void 0; - this.initOptions = void 0; - EventsStore.clear(); - }; - } -}; - -// src/utils/amount.ts -init_shim(); - -// node_modules/bignumber.js/bignumber.mjs -init_shim(); -var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; -var mathceil = Math.ceil; -var mathfloor = Math.floor; -var bignumberError = "[BigNumber Error] "; -var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; -var BASE = 1e14; -var LOG_BASE = 14; -var MAX_SAFE_INTEGER = 9007199254740991; -var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13]; -var SQRT_BASE = 1e7; -var MAX = 1e9; -function clone(configObject) { - var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - // non-breaking space - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber2(v2, b4) { - var alphabet2, c4, caseChanged, e2, i2, isNum, len, str, x3 = this; - if (!(x3 instanceof BigNumber2)) - return new BigNumber2(v2, b4); - if (b4 == null) { - if (v2 && v2._isBigNumber === true) { - x3.s = v2.s; - if (!v2.c || v2.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (v2.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = v2.e; - x3.c = v2.c.slice(); - } - return; - } - if ((isNum = typeof v2 == "number") && v2 * 0 == 0) { - x3.s = 1 / v2 < 0 ? (v2 = -v2, -1) : 1; - if (v2 === ~~v2) { - for (e2 = 0, i2 = v2; i2 >= 10; i2 /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x3.c = x3.e = null; - } else { - x3.e = e2; - x3.c = [v2]; - } - return; - } - str = String(v2); - } else { - if (!isNumeric.test(str = String(v2))) - return parseNumeric(x3, str, isNum); - x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i2 = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i2; - e2 += +str.slice(i2 + 1); - str = str.substring(0, i2); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck(b4, 2, ALPHABET.length, "Base"); - if (b4 == 10 && alphabetHasNormalDecimalDigits) { - x3 = new BigNumber2(v2); - return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); - } - str = String(v2); - if (isNum = typeof v2 == "number") { - if (v2 * 0 != 0) - return parseNumeric(x3, str, isNum, b4); - x3.s = 1 / v2 < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits + v2); - } - } else { - x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b4); - e2 = i2 = 0; - for (len = str.length; i2 < len; i2++) { - if (alphabet2.indexOf(c4 = str.charAt(i2)) < 0) { - if (c4 == ".") { - if (i2 > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i2 = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x3, String(v2), isNum, b4); - } - } - isNum = false; - str = convertBase(str, b4, 10, x3.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i2 = 0; str.charCodeAt(i2) === 48; i2++) - ; - for (len = str.length; str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i2, ++len)) { - len -= i2; - if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) { - throw Error(tooManyDigits + x3.s * v2); - } - if ((e2 = e2 - i2 - 1) > MAX_EXP) { - x3.c = x3.e = null; - } else if (e2 < MIN_EXP) { - x3.c = [x3.e = 0]; - } else { - x3.e = e2; - x3.c = []; - i2 = (e2 + 1) % LOG_BASE; - if (e2 < 0) - i2 += LOG_BASE; - if (i2 < len) { - if (i2) - x3.c.push(+str.slice(0, i2)); - for (len -= LOG_BASE; i2 < len; ) { - x3.c.push(+str.slice(i2, i2 += LOG_BASE)); - } - i2 = LOG_BASE - (str = str.slice(i2)).length; - } else { - i2 -= len; - } - for (; i2--; str += "0") - ; - x3.c.push(+str); - } - } else { - x3.c = [x3.e = 0]; - } - } - BigNumber2.clone = clone; - BigNumber2.ROUND_UP = 0; - BigNumber2.ROUND_DOWN = 1; - BigNumber2.ROUND_CEIL = 2; - BigNumber2.ROUND_FLOOR = 3; - BigNumber2.ROUND_HALF_UP = 4; - BigNumber2.ROUND_HALF_DOWN = 5; - BigNumber2.ROUND_HALF_EVEN = 6; - BigNumber2.ROUND_HALF_CEIL = 7; - BigNumber2.ROUND_HALF_FLOOR = 8; - BigNumber2.EUCLID = 9; - BigNumber2.config = BigNumber2.set = function(obj) { - var p3, v2; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p3 = "DECIMAL_PLACES")) { - v2 = obj[p3]; - intCheck(v2, 0, MAX, p3); - DECIMAL_PLACES = v2; - } - if (obj.hasOwnProperty(p3 = "ROUNDING_MODE")) { - v2 = obj[p3]; - intCheck(v2, 0, 8, p3); - ROUNDING_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "EXPONENTIAL_AT")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck(v2[0], -MAX, 0, p3); - intCheck(v2[1], 0, MAX, p3); - TO_EXP_NEG = v2[0]; - TO_EXP_POS = v2[1]; - } else { - intCheck(v2, -MAX, MAX, p3); - TO_EXP_NEG = -(TO_EXP_POS = v2 < 0 ? -v2 : v2); - } - } - if (obj.hasOwnProperty(p3 = "RANGE")) { - v2 = obj[p3]; - if (v2 && v2.pop) { - intCheck(v2[0], -MAX, -1, p3); - intCheck(v2[1], 1, MAX, p3); - MIN_EXP = v2[0]; - MAX_EXP = v2[1]; - } else { - intCheck(v2, -MAX, MAX, p3); - if (v2) { - MIN_EXP = -(MAX_EXP = v2 < 0 ? -v2 : v2); - } else { - throw Error(bignumberError + p3 + " cannot be zero: " + v2); - } - } - } - if (obj.hasOwnProperty(p3 = "CRYPTO")) { - v2 = obj[p3]; - if (v2 === !!v2) { - if (v2) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v2; - } else { - CRYPTO = !v2; - throw Error(bignumberError + "crypto unavailable"); - } - } else { - CRYPTO = v2; - } - } else { - throw Error(bignumberError + p3 + " not true or false: " + v2); - } - } - if (obj.hasOwnProperty(p3 = "MODULO_MODE")) { - v2 = obj[p3]; - intCheck(v2, 0, 9, p3); - MODULO_MODE = v2; - } - if (obj.hasOwnProperty(p3 = "POW_PRECISION")) { - v2 = obj[p3]; - intCheck(v2, 0, MAX, p3); - POW_PRECISION = v2; - } - if (obj.hasOwnProperty(p3 = "FORMAT")) { - v2 = obj[p3]; - if (typeof v2 == "object") - FORMAT = v2; - else - throw Error(bignumberError + p3 + " not an object: " + v2); - } - if (obj.hasOwnProperty(p3 = "ALPHABET")) { - v2 = obj[p3]; - if (typeof v2 == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v2)) { - alphabetHasNormalDecimalDigits = v2.slice(0, 10) == "0123456789"; - ALPHABET = v2; - } else { - throw Error(bignumberError + p3 + " invalid: " + v2); - } - } - } else { - throw Error(bignumberError + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber2.isBigNumber = function(v2) { - if (!v2 || v2._isBigNumber !== true) - return false; - if (!BigNumber2.DEBUG) - return true; - var i2, n3, c4 = v2.c, e2 = v2.e, s2 = v2.s; - out: - if ({}.toString.call(c4) == "[object Array]") { - if ((s2 === 1 || s2 === -1) && e2 >= -MAX && e2 <= MAX && e2 === mathfloor(e2)) { - if (c4[0] === 0) { - if (e2 === 0 && c4.length === 1) - return true; - break out; - } - i2 = (e2 + 1) % LOG_BASE; - if (i2 < 1) - i2 += LOG_BASE; - if (String(c4[0]).length == i2) { - for (i2 = 0; i2 < c4.length; i2++) { - n3 = c4[i2]; - if (n3 < 0 || n3 >= BASE || n3 !== mathfloor(n3)) - break out; - } - if (n3 !== 0) - return true; - } - } - } else if (c4 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { - return true; - } - throw Error(bignumberError + "Invalid BigNumber: " + v2); - }; - BigNumber2.maximum = BigNumber2.max = function() { - return maxOrMin(arguments, -1); - }; - BigNumber2.minimum = BigNumber2.min = function() { - return maxOrMin(arguments, 1); - }; - BigNumber2.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a3, b4, e2, k4, v2, i2 = 0, c4 = [], rand = new BigNumber2(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck(dp, 0, MAX); - k4 = mathceil(dp / LOG_BASE); - if (CRYPTO) { - if (crypto.getRandomValues) { - a3 = crypto.getRandomValues(new Uint32Array(k4 *= 2)); - for (; i2 < k4; ) { - v2 = a3[i2] * 131072 + (a3[i2 + 1] >>> 11); - if (v2 >= 9e15) { - b4 = crypto.getRandomValues(new Uint32Array(2)); - a3[i2] = b4[0]; - a3[i2 + 1] = b4[1]; - } else { - c4.push(v2 % 1e14); - i2 += 2; - } - } - i2 = k4 / 2; - } else if (crypto.randomBytes) { - a3 = crypto.randomBytes(k4 *= 7); - for (; i2 < k4; ) { - v2 = (a3[i2] & 31) * 281474976710656 + a3[i2 + 1] * 1099511627776 + a3[i2 + 2] * 4294967296 + a3[i2 + 3] * 16777216 + (a3[i2 + 4] << 16) + (a3[i2 + 5] << 8) + a3[i2 + 6]; - if (v2 >= 9e15) { - crypto.randomBytes(7).copy(a3, i2); - } else { - c4.push(v2 % 1e14); - i2 += 7; - } - } - i2 = k4 / 7; - } else { - CRYPTO = false; - throw Error(bignumberError + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (; i2 < k4; ) { - v2 = random53bitInt(); - if (v2 < 9e15) - c4[i2++] = v2 % 1e14; - } - } - k4 = c4[--i2]; - dp %= LOG_BASE; - if (k4 && dp) { - v2 = POWS_TEN[LOG_BASE - dp]; - c4[i2] = mathfloor(k4 / v2) * v2; - } - for (; c4[i2] === 0; c4.pop(), i2--) - ; - if (i2 < 0) { - c4 = [e2 = 0]; - } else { - for (e2 = -1; c4[0] === 0; c4.splice(0, 1), e2 -= LOG_BASE) - ; - for (i2 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i2++) - ; - if (i2 < LOG_BASE) - e2 -= LOG_BASE - i2; - } - rand.e = e2; - rand.c = c4; - return rand; - }; - }(); - BigNumber2.sum = function() { - var i2 = 1, args = arguments, sum = new BigNumber2(args[0]); - for (; i2 < args.length; ) - sum = sum.plus(args[i2++]); - return sum; - }; - convertBase = /* @__PURE__ */ function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j2, arr = [0], arrL, i2 = 0, len = str.length; - for (; i2 < len; ) { - for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i2++)); - for (j2 = 0; j2 < arr.length; j2++) { - if (arr[j2] > baseOut - 1) { - if (arr[j2 + 1] == null) - arr[j2 + 1] = 0; - arr[j2 + 1] += arr[j2] / baseOut | 0; - arr[j2] %= baseOut; - } - } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign2, callerIsToString) { - var alphabet2, d3, e2, k4, r, x3, xc, y4, i2 = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i2 >= 0) { - k4 = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y4 = new BigNumber2(baseIn); - x3 = y4.pow(str.length - i2); - POW_PRECISION = k4; - y4.c = toBaseOut( - toFixedPoint(coeffToString(x3.c), x3.e, "0"), - 10, - baseOut, - decimal - ); - y4.e = y4.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k4 = xc.length; - for (; xc[--k4] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i2 < 0) { - --e2; - } else { - x3.c = xc; - x3.e = e2; - x3.s = sign2; - x3 = div(x3, y4, dp, rm, baseOut); - xc = x3.c; - r = x3.r; - e2 = x3.e; - } - d3 = e2 + dp + 1; - i2 = xc[d3]; - k4 = baseOut / 2; - r = r || d3 < 0 || xc[d3 + 1] != null; - r = rm < 4 ? (i2 != null || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : i2 > k4 || i2 == k4 && (rm == 4 || r || rm == 6 && xc[d3 - 1] & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (d3 < 1 || !xc[0]) { - str = r ? toFixedPoint(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d3; - if (r) { - for (--baseOut; ++xc[--d3] > baseOut; ) { - xc[d3] = 0; - if (!d3) { - ++e2; - xc = [1].concat(xc); - } - } - } - for (k4 = xc.length; !xc[--k4]; ) - ; - for (i2 = 0, str = ""; i2 <= k4; str += alphabet2.charAt(xc[i2++])) - ; - str = toFixedPoint(str, e2, alphabet2.charAt(0)); - } - return str; - }; - }(); - div = /* @__PURE__ */ function() { - function multiply(x3, k4, base3) { - var m3, temp, xlo, xhi, carry = 0, i2 = x3.length, klo = k4 % SQRT_BASE, khi = k4 / SQRT_BASE | 0; - for (x3 = x3.slice(); i2--; ) { - xlo = x3[i2] % SQRT_BASE; - xhi = x3[i2] / SQRT_BASE | 0; - m3 = khi * xlo + xhi * klo; - temp = klo * xlo + m3 % SQRT_BASE * SQRT_BASE + carry; - carry = (temp / base3 | 0) + (m3 / SQRT_BASE | 0) + khi * xhi; - x3[i2] = temp % base3; - } - if (carry) - x3 = [carry].concat(x3); - return x3; - } - function compare3(a3, b4, aL, bL) { - var i2, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i2 = cmp = 0; i2 < aL; i2++) { - if (a3[i2] != b4[i2]) { - cmp = a3[i2] > b4[i2] ? 1 : -1; - break; - } - } - } - return cmp; - } - function subtract(a3, b4, aL, base3) { - var i2 = 0; - for (; aL--; ) { - a3[aL] -= i2; - i2 = a3[aL] < b4[aL] ? 1 : 0; - a3[aL] = i2 * base3 + a3[aL] - b4[aL]; - } - for (; !a3[0] && a3.length > 1; a3.splice(0, 1)) - ; - } - return function(x3, y4, dp, rm, base3) { - var cmp, e2, i2, more, n3, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y4.s ? 1 : -1, xc = x3.c, yc = y4.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber2( - // Return NaN if either NaN, or both Infinity or 0. - !x3.s || !y4.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : ( - // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. - xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0 - ) - ); - } - q2 = new BigNumber2(s2); - qc = q2.c = []; - e2 = x3.e - y4.e; - s2 = dp + e2 + 1; - if (!base3) { - base3 = BASE; - e2 = bitFloor(x3.e / LOG_BASE) - bitFloor(y4.e / LOG_BASE); - s2 = s2 / LOG_BASE | 0; - } - for (i2 = 0; yc[i2] == (xc[i2] || 0); i2++) - ; - if (yc[i2] > (xc[i2] || 0)) - e2--; - if (s2 < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i2 = 0; - s2 += 2; - n3 = mathfloor(base3 / (yc[0] + 1)); - if (n3 > 1) { - yc = multiply(yc, n3, base3); - xc = multiply(xc, n3, base3); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (; remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base3 / 2) - yc0++; - do { - n3 = 0; - cmp = compare3(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base3 + (rem[1] || 0); - n3 = mathfloor(rem0 / yc0); - if (n3 > 1) { - if (n3 >= base3) - n3 = base3 - 1; - prod = multiply(yc, n3, base3); - prodL = prod.length; - remL = rem.length; - while (compare3(prod, rem, prodL, remL) == 1) { - n3--; - subtract(prod, yL < prodL ? yz : yc, prodL, base3); - prodL = prod.length; - cmp = 1; - } - } else { - if (n3 == 0) { - cmp = n3 = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base3); - remL = rem.length; - if (cmp == -1) { - while (compare3(yc, rem, yL, remL) < 1) { - n3++; - subtract(rem, yL < remL ? yz : yc, remL, base3); - remL = rem.length; - } - } - } else if (cmp === 0) { - n3++; - rem = [0]; - } - qc[i2++] = n3; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s2--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base3 == BASE) { - for (i2 = 1, s2 = qc[0]; s2 >= 10; s2 /= 10, i2++) - ; - round(q2, dp + (q2.e = i2 + e2 * LOG_BASE - 1) + 1, rm, more); - } else { - q2.e = e2; - q2.r = +more; - } - return q2; - }; - }(); - function format(n3, i2, rm, id) { - var c0, e2, ne, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - if (!n3.c) - return n3.toString(); - c0 = n3.c[0]; - ne = n3.e; - if (i2 == null) { - str = coeffToString(n3.c); - str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0"); - } else { - n3 = round(new BigNumber2(n3), i2, rm); - e2 = n3.e; - str = coeffToString(n3.c); - len = str.length; - if (id == 1 || id == 2 && (i2 <= e2 || e2 <= TO_EXP_NEG)) { - for (; len < i2; str += "0", len++) - ; - str = toExponential(str, e2); - } else { - i2 -= ne; - str = toFixedPoint(str, e2, "0"); - if (e2 + 1 > len) { - if (--i2 > 0) - for (str += "."; i2--; str += "0") - ; - } else { - i2 += e2 - len; - if (i2 > 0) { - if (e2 + 1 == len) - str += "."; - for (; i2--; str += "0") - ; - } - } - } - } - return n3.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, n3) { - var k4, y4, i2 = 1, x3 = new BigNumber2(args[0]); - for (; i2 < args.length; i2++) { - y4 = new BigNumber2(args[i2]); - if (!y4.s || (k4 = compare2(x3, y4)) === n3 || k4 === 0 && x3.s === n3) { - x3 = y4; - } - } - return x3; - } - function normalise(n3, c4, e2) { - var i2 = 1, j2 = c4.length; - for (; !c4[--j2]; c4.pop()) - ; - for (j2 = c4[0]; j2 >= 10; j2 /= 10, i2++) - ; - if ((e2 = i2 + e2 * LOG_BASE - 1) > MAX_EXP) { - n3.c = n3.e = null; - } else if (e2 < MIN_EXP) { - n3.c = [n3.e = 0]; - } else { - n3.e = e2; - n3.c = c4; - } - return n3; - } - parseNumeric = /* @__PURE__ */ function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x3, str, isNum, b4) { - var base3, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s2)) { - x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; - } else { - if (!isNum) { - s2 = s2.replace(basePrefix, function(m3, p1, p22) { - base3 = (p22 = p22.toLowerCase()) == "x" ? 16 : p22 == "b" ? 2 : 8; - return !b4 || b4 == base3 ? p1 : m3; - }); - if (b4) { - base3 = b4; - s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s2) - return new BigNumber2(s2, base3); - } - if (BigNumber2.DEBUG) { - throw Error(bignumberError + "Not a" + (b4 ? " base " + b4 : "") + " number: " + str); - } - x3.s = null; - } - x3.c = x3.e = null; - }; - }(); - function round(x3, sd, rm, r) { - var d3, i2, j2, k4, n3, ni, rd, xc = x3.c, pows10 = POWS_TEN; - if (xc) { - out: { - for (d3 = 1, k4 = xc[0]; k4 >= 10; k4 /= 10, d3++) - ; - i2 = sd - d3; - if (i2 < 0) { - i2 += LOG_BASE; - j2 = sd; - n3 = xc[ni = 0]; - rd = mathfloor(n3 / pows10[d3 - j2 - 1] % 10); - } else { - ni = mathceil((i2 + 1) / LOG_BASE); - if (ni >= xc.length) { - if (r) { - for (; xc.length <= ni; xc.push(0)) - ; - n3 = rd = 0; - d3 = 1; - i2 %= LOG_BASE; - j2 = i2 - LOG_BASE + 1; - } else { - break out; - } - } else { - n3 = k4 = xc[ni]; - for (d3 = 1; k4 >= 10; k4 /= 10, d3++) - ; - i2 %= LOG_BASE; - j2 = i2 - LOG_BASE + d3; - rd = j2 < 0 ? 0 : mathfloor(n3 / pows10[d3 - j2 - 1] % 10); - } - } - r = r || sd < 0 || // Are there any non-zero digits after the rounding digit? - // The expression n % pows10[d - j - 1] returns all digits of n to the right - // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. - xc[ni + 1] != null || (j2 < 0 ? n3 : n3 % pows10[d3 - j2 - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd. - (i2 > 0 ? j2 > 0 ? n3 / pows10[d3 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x3.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x3.e + 1; - xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; - x3.e = -sd || 0; - } else { - xc[0] = x3.e = 0; - } - return x3; - } - if (i2 == 0) { - xc.length = ni; - k4 = 1; - ni--; - } else { - xc.length = ni + 1; - k4 = pows10[LOG_BASE - i2]; - xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d3 - j2] % pows10[j2]) * k4 : 0; - } - if (r) { - for (; ; ) { - if (ni == 0) { - for (i2 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i2++) - ; - j2 = xc[0] += k4; - for (k4 = 1; j2 >= 10; j2 /= 10, k4++) - ; - if (i2 != k4) { - x3.e++; - if (xc[0] == BASE) - xc[0] = 1; - } - break; - } else { - xc[ni] += k4; - if (xc[ni] != BASE) - break; - xc[ni--] = 0; - k4 = 1; - } - } - } - for (i2 = xc.length; xc[--i2] === 0; xc.pop()) - ; - } - if (x3.e > MAX_EXP) { - x3.c = x3.e = null; - } else if (x3.e < MIN_EXP) { - x3.c = [x3.e = 0]; - } - } - return x3; - } - function valueOf(n3) { - var str, e2 = n3.e; - if (e2 === null) - return n3.toString(); - str = coeffToString(n3.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); - return n3.s < 0 ? "-" + str : str; - } - P2.absoluteValue = P2.abs = function() { - var x3 = new BigNumber2(this); - if (x3.s < 0) - x3.s = 1; - return x3; - }; - P2.comparedTo = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)); - }; - P2.decimalPlaces = P2.dp = function(dp, rm) { - var c4, n3, v2, x3 = this; - if (dp != null) { - intCheck(dp, 0, MAX); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - return round(new BigNumber2(x3), dp + x3.e + 1, rm); - } - if (!(c4 = x3.c)) - return null; - n3 = ((v2 = c4.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; - if (v2 = c4[v2]) - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - if (n3 < 0) - n3 = 0; - return n3; - }; - P2.dividedBy = P2.div = function(y4, b4) { - return div(this, new BigNumber2(y4, b4), DECIMAL_PLACES, ROUNDING_MODE); - }; - P2.dividedToIntegerBy = P2.idiv = function(y4, b4) { - return div(this, new BigNumber2(y4, b4), 0, 1); - }; - P2.exponentiatedBy = P2.pow = function(n3, m3) { - var half, isModExp, i2, k4, more, nIsBig, nIsNeg, nIsOdd, y4, x3 = this; - n3 = new BigNumber2(n3); - if (n3.c && !n3.isInteger()) { - throw Error(bignumberError + "Exponent not an integer: " + valueOf(n3)); - } - if (m3 != null) - m3 = new BigNumber2(m3); - nIsBig = n3.e > 14; - if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n3.c || !n3.c[0]) { - y4 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n3.s * (2 - isOdd(n3)) : +valueOf(n3))); - return m3 ? y4.mod(m3) : y4; - } - nIsNeg = n3.s < 0; - if (m3) { - if (m3.c ? !m3.c[0] : !m3.s) - return new BigNumber2(NaN); - isModExp = !nIsNeg && x3.isInteger() && m3.isInteger(); - if (isModExp) - x3 = x3.mod(m3); - } else if (n3.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 24e7 : x3.c[0] < 8e13 || nIsBig && x3.c[0] <= 9999975e7))) { - k4 = x3.s < 0 && isOdd(n3) ? -0 : 0; - if (x3.e > -1) - k4 = 1 / k4; - return new BigNumber2(nIsNeg ? 1 / k4 : k4); - } else if (POW_PRECISION) { - k4 = mathceil(POW_PRECISION / LOG_BASE + 2); - } - if (nIsBig) { - half = new BigNumber2(0.5); - if (nIsNeg) - n3.s = 1; - nIsOdd = isOdd(n3); - } else { - i2 = Math.abs(+valueOf(n3)); - nIsOdd = i2 % 2; - } - y4 = new BigNumber2(ONE); - for (; ; ) { - if (nIsOdd) { - y4 = y4.times(x3); - if (!y4.c) - break; - if (k4) { - if (y4.c.length > k4) - y4.c.length = k4; - } else if (isModExp) { - y4 = y4.mod(m3); - } - } - if (i2) { - i2 = mathfloor(i2 / 2); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } else { - n3 = n3.times(half); - round(n3, n3.e + 1, 1); - if (n3.e > 14) { - nIsOdd = isOdd(n3); - } else { - i2 = +valueOf(n3); - if (i2 === 0) - break; - nIsOdd = i2 % 2; - } - } - x3 = x3.times(x3); - if (k4) { - if (x3.c && x3.c.length > k4) - x3.c.length = k4; - } else if (isModExp) { - x3 = x3.mod(m3); - } - } - if (isModExp) - return y4; - if (nIsNeg) - y4 = ONE.div(y4); - return m3 ? y4.mod(m3) : k4 ? round(y4, POW_PRECISION, ROUNDING_MODE, more) : y4; - }; - P2.integerValue = function(rm) { - var n3 = new BigNumber2(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - return round(n3, n3.e + 1, rm); - }; - P2.isEqualTo = P2.eq = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)) === 0; - }; - P2.isFinite = function() { - return !!this.c; - }; - P2.isGreaterThan = P2.gt = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)) > 0; - }; - P2.isGreaterThanOrEqualTo = P2.gte = function(y4, b4) { - return (b4 = compare2(this, new BigNumber2(y4, b4))) === 1 || b4 === 0; - }; - P2.isInteger = function() { - return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; - }; - P2.isLessThan = P2.lt = function(y4, b4) { - return compare2(this, new BigNumber2(y4, b4)) < 0; - }; - P2.isLessThanOrEqualTo = P2.lte = function(y4, b4) { - return (b4 = compare2(this, new BigNumber2(y4, b4))) === -1 || b4 === 0; - }; - P2.isNaN = function() { - return !this.s; - }; - P2.isNegative = function() { - return this.s < 0; - }; - P2.isPositive = function() { - return this.s > 0; - }; - P2.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P2.minus = function(y4, b4) { - var i2, j2, t, xLTy, x3 = this, a3 = x3.s; - y4 = new BigNumber2(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber2(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.plus(y4); - } - var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y4.s = -b4, y4) : new BigNumber2(yc ? x3 : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y4.s = -b4, y4) : new BigNumber2(xc[0] ? x3 : ( - // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity - ROUNDING_MODE == 3 ? -0 : 0 - )); - } - } - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (xLTy = a3 < 0) { - a3 = -a3; - t = xc; - } else { - ye = xe; - t = yc; - } - t.reverse(); - for (b4 = a3; b4--; t.push(0)) - ; - t.reverse(); - } else { - j2 = (xLTy = (a3 = xc.length) < (b4 = yc.length)) ? a3 : b4; - for (a3 = b4 = 0; b4 < j2; b4++) { - if (xc[b4] != yc[b4]) { - xLTy = xc[b4] < yc[b4]; - break; - } - } - } - if (xLTy) { - t = xc; - xc = yc; - yc = t; - y4.s = -y4.s; - } - b4 = (j2 = yc.length) - (i2 = xc.length); - if (b4 > 0) - for (; b4--; xc[i2++] = 0) - ; - b4 = BASE - 1; - for (; j2 > a3; ) { - if (xc[--j2] < yc[j2]) { - for (i2 = j2; i2 && !xc[--i2]; xc[i2] = b4) - ; - --xc[i2]; - xc[j2] += BASE; - } - xc[j2] -= yc[j2]; - } - for (; xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y4.s = ROUNDING_MODE == 3 ? -1 : 1; - y4.c = [y4.e = 0]; - return y4; - } - return normalise(y4, xc, ye); - }; - P2.modulo = P2.mod = function(y4, b4) { - var q2, s2, x3 = this; - y4 = new BigNumber2(y4, b4); - if (!x3.c || !y4.s || y4.c && !y4.c[0]) { - return new BigNumber2(NaN); - } else if (!y4.c || x3.c && !x3.c[0]) { - return new BigNumber2(x3); - } - if (MODULO_MODE == 9) { - s2 = y4.s; - y4.s = 1; - q2 = div(x3, y4, 0, 3); - y4.s = s2; - q2.s *= s2; - } else { - q2 = div(x3, y4, 0, MODULO_MODE); - } - y4 = x3.minus(q2.times(y4)); - if (!y4.c[0] && MODULO_MODE == 1) - y4.s = x3.s; - return y4; - }; - P2.multipliedBy = P2.times = function(y4, b4) { - var c4, e2, i2, j2, k4, m3, xcL, xlo, xhi, ycL, ylo, yhi, zc, base3, sqrtBase, x3 = this, xc = x3.c, yc = (y4 = new BigNumber2(y4, b4)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x3.s || !y4.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y4.c = y4.e = y4.s = null; - } else { - y4.s *= x3.s; - if (!xc || !yc) { - y4.c = y4.e = null; - } else { - y4.c = [0]; - y4.e = 0; - } - } - return y4; - } - e2 = bitFloor(x3.e / LOG_BASE) + bitFloor(y4.e / LOG_BASE); - y4.s *= x3.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) { - zc = xc; - xc = yc; - yc = zc; - i2 = xcL; - xcL = ycL; - ycL = i2; - } - for (i2 = xcL + ycL, zc = []; i2--; zc.push(0)) - ; - base3 = BASE; - sqrtBase = SQRT_BASE; - for (i2 = ycL; --i2 >= 0; ) { - c4 = 0; - ylo = yc[i2] % sqrtBase; - yhi = yc[i2] / sqrtBase | 0; - for (k4 = xcL, j2 = i2 + k4; j2 > i2; ) { - xlo = xc[--k4] % sqrtBase; - xhi = xc[k4] / sqrtBase | 0; - m3 = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m3 % sqrtBase * sqrtBase + zc[j2] + c4; - c4 = (xlo / base3 | 0) + (m3 / sqrtBase | 0) + yhi * xhi; - zc[j2--] = xlo % base3; - } - zc[j2] = c4; - } - if (c4) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y4, zc, e2); - }; - P2.negated = function() { - var x3 = new BigNumber2(this); - x3.s = -x3.s || null; - return x3; - }; - P2.plus = function(y4, b4) { - var t, x3 = this, a3 = x3.s; - y4 = new BigNumber2(y4, b4); - b4 = y4.s; - if (!a3 || !b4) - return new BigNumber2(NaN); - if (a3 != b4) { - y4.s = -b4; - return x3.minus(y4); - } - var xe = x3.e / LOG_BASE, ye = y4.e / LOG_BASE, xc = x3.c, yc = y4.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber2(a3 / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y4 : new BigNumber2(xc[0] ? x3 : a3 * 0); - } - xe = bitFloor(xe); - ye = bitFloor(ye); - xc = xc.slice(); - if (a3 = xe - ye) { - if (a3 > 0) { - ye = xe; - t = yc; - } else { - a3 = -a3; - t = xc; - } - t.reverse(); - for (; a3--; t.push(0)) - ; - t.reverse(); - } - a3 = xc.length; - b4 = yc.length; - if (a3 - b4 < 0) { - t = yc; - yc = xc; - xc = t; - b4 = a3; - } - for (a3 = 0; b4; ) { - a3 = (xc[--b4] = xc[b4] + yc[b4] + a3) / BASE | 0; - xc[b4] = BASE === xc[b4] ? 0 : xc[b4] % BASE; - } - if (a3) { - xc = [a3].concat(xc); - ++ye; - } - return normalise(y4, xc, ye); - }; - P2.precision = P2.sd = function(sd, rm) { - var c4, n3, v2, x3 = this; - if (sd != null && sd !== !!sd) { - intCheck(sd, 1, MAX); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck(rm, 0, 8); - return round(new BigNumber2(x3), sd, rm); - } - if (!(c4 = x3.c)) - return null; - v2 = c4.length - 1; - n3 = v2 * LOG_BASE + 1; - if (v2 = c4[v2]) { - for (; v2 % 10 == 0; v2 /= 10, n3--) - ; - for (v2 = c4[0]; v2 >= 10; v2 /= 10, n3++) - ; - } - if (sd && x3.e + 1 > n3) - n3 = x3.e + 1; - return n3; - }; - P2.shiftedBy = function(k4) { - intCheck(k4, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); - return this.times("1e" + k4); - }; - P2.squareRoot = P2.sqrt = function() { - var m3, n3, r, rep, t, x3 = this, c4 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); - if (s2 !== 1 || !c4 || !c4[0]) { - return new BigNumber2(!s2 || s2 < 0 && (!c4 || c4[0]) ? NaN : c4 ? x3 : 1 / 0); - } - s2 = Math.sqrt(+valueOf(x3)); - if (s2 == 0 || s2 == 1 / 0) { - n3 = coeffToString(c4); - if ((n3.length + e2) % 2 == 0) - n3 += "0"; - s2 = Math.sqrt(+n3); - e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s2 == 1 / 0) { - n3 = "5e" + e2; - } else { - n3 = s2.toExponential(); - n3 = n3.slice(0, n3.indexOf("e") + 1) + e2; - } - r = new BigNumber2(n3); - } else { - r = new BigNumber2(s2 + ""); - } - if (r.c[0]) { - e2 = r.e; - s2 = e2 + dp; - if (s2 < 3) - s2 = 0; - for (; ; ) { - t = r; - r = half.times(t.plus(div(x3, t, dp, 1))); - if (coeffToString(t.c).slice(0, s2) === (n3 = coeffToString(r.c)).slice(0, s2)) { - if (r.e < e2) - --s2; - n3 = n3.slice(s2 - 3, s2 + 1); - if (n3 == "9999" || !rep && n3 == "4999") { - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - if (t.times(t).eq(x3)) { - r = t; - break; - } - } - dp += 4; - s2 += 4; - rep = 1; - } else { - if (!+n3 || !+n3.slice(1) && n3.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m3 = !r.times(r).eq(x3); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m3); - }; - P2.toExponential = function(dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp++; - } - return format(this, dp, rm, 1); - }; - P2.toFixed = function(dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P2.toFormat = function(dp, rm, format2) { - var str, x3 = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError + "Argument not an object: " + format2); - } - str = x3.toFixed(dp, rm); - if (x3.c) { - var i2, arr = str.split("."), g1 = +format2.groupSize, g22 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g22) { - i2 = g1; - g1 = g22; - g22 = i2; - len -= i2; - } - if (g1 > 0 && len > 0) { - i2 = len % g1 || g1; - intPart = intDigits.substr(0, i2); - for (; i2 < len; i2 += g1) - intPart += groupSeparator + intDigits.substr(i2, g1); - if (g22 > 0) - intPart += groupSeparator + intDigits.slice(i2); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g22 = +format2.fractionGroupSize) ? fractionPart.replace( - new RegExp("\\d{" + g22 + "}\\B", "g"), - "$&" + (format2.fractionGroupSeparator || "") - ) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P2.toFraction = function(md) { - var d3, d0, d1, d22, e2, exp, n3, n0, n1, q2, r, s2, x3 = this, xc = x3.c; - if (md != null) { - n3 = new BigNumber2(md); - if (!n3.isInteger() && (n3.c || n3.s !== 1) || n3.lt(ONE)) { - throw Error(bignumberError + "Argument " + (n3.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n3)); - } - } - if (!xc) - return new BigNumber2(x3); - d3 = new BigNumber2(ONE); - n1 = d0 = new BigNumber2(ONE); - d1 = n0 = new BigNumber2(ONE); - s2 = coeffToString(xc); - e2 = d3.e = s2.length - x3.e - 1; - d3.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; - md = !md || n3.comparedTo(d3) > 0 ? e2 > 0 ? d3 : n1 : n3; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n3 = new BigNumber2(s2); - n0.c[0] = 0; - for (; ; ) { - q2 = div(n3, d3, 0, 1); - d22 = d0.plus(q2.times(d1)); - if (d22.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d22; - n1 = n0.plus(q2.times(d22 = n1)); - n0 = d22; - d3 = n3.minus(q2.times(d22 = d3)); - n3 = d22; - } - d22 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d22.times(n1)); - d0 = d0.plus(d22.times(d1)); - n0.s = n1.s = x3.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo( - div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs() - ) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P2.toNumber = function() { - return +valueOf(this); - }; - P2.toPrecision = function(sd, rm) { - if (sd != null) - intCheck(sd, 1, MAX); - return format(this, sd, rm, 2); - }; - P2.toString = function(b4) { - var str, n3 = this, s2 = n3.s, e2 = n3.e; - if (e2 === null) { - if (s2) { - str = "Infinity"; - if (s2 < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b4 == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n3.c), e2) : toFixedPoint(coeffToString(n3.c), e2, "0"); - } else if (b4 === 10 && alphabetHasNormalDecimalDigits) { - n3 = round(new BigNumber2(n3), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n3.c), n3.e, "0"); - } else { - intCheck(b4, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint(coeffToString(n3.c), e2, "0"), 10, b4, s2, true); - } - if (s2 < 0 && n3.c[0]) - str = "-" + str; - } - return str; - }; - P2.valueOf = P2.toJSON = function() { - return valueOf(this); - }; - P2._isBigNumber = true; - P2[Symbol.toStringTag] = "BigNumber"; - P2[Symbol.for("nodejs.util.inspect.custom")] = P2.valueOf; - if (configObject != null) - BigNumber2.set(configObject); - return BigNumber2; -} -function bitFloor(n3) { - var i2 = n3 | 0; - return n3 > 0 || n3 === i2 ? i2 : i2 - 1; -} -function coeffToString(a3) { - var s2, z3, i2 = 1, j2 = a3.length, r = a3[0] + ""; - for (; i2 < j2; ) { - s2 = a3[i2++] + ""; - z3 = LOG_BASE - s2.length; - for (; z3--; s2 = "0" + s2) - ; - r += s2; - } - for (j2 = r.length; r.charCodeAt(--j2) === 48; ) - ; - return r.slice(0, j2 + 1 || 1); -} -function compare2(x3, y4) { - var a3, b4, xc = x3.c, yc = y4.c, i2 = x3.s, j2 = y4.s, k4 = x3.e, l4 = y4.e; - if (!i2 || !j2) - return null; - a3 = xc && !xc[0]; - b4 = yc && !yc[0]; - if (a3 || b4) - return a3 ? b4 ? 0 : -j2 : i2; - if (i2 != j2) - return i2; - a3 = i2 < 0; - b4 = k4 == l4; - if (!xc || !yc) - return b4 ? 0 : !xc ^ a3 ? 1 : -1; - if (!b4) - return k4 > l4 ^ a3 ? 1 : -1; - j2 = (k4 = xc.length) < (l4 = yc.length) ? k4 : l4; - for (i2 = 0; i2 < j2; i2++) - if (xc[i2] != yc[i2]) - return xc[i2] > yc[i2] ^ a3 ? 1 : -1; - return k4 == l4 ? 0 : k4 > l4 ^ a3 ? 1 : -1; -} -function intCheck(n3, min, max, name2) { - if (n3 < min || n3 > max || n3 !== mathfloor(n3)) { - throw Error(bignumberError + (name2 || "Argument") + (typeof n3 == "number" ? n3 < min || n3 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n3)); - } -} -function isOdd(n3) { - var k4 = n3.c.length - 1; - return bitFloor(n3.e / LOG_BASE) == k4 && n3.c[k4] % 2 != 0; -} -function toExponential(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; -} -function toFixedPoint(str, e2, z3) { - var len, zs; - if (e2 < 0) { - for (zs = z3 + "."; ++e2; zs += z3) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z3, e2 -= len; --e2; zs += z3) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } - } - return str; -} -var BigNumber = clone(); -var bignumber_default = BigNumber; - -// src/utils/amount.ts -bignumber_default.config({ ROUNDING_MODE: bignumber_default.ROUND_FLOOR }); -var parseAmount = ({ - amount, - decimals -}) => { - if (decimals < 0) - throw new Error("Decimal places shouldn't be negative number!"); - return BigInt(new bignumber_default(amount).shiftedBy(decimals).toFixed()); -}; -var formatAmount = ({ - amount, - decimals, - rounding = decimals -}) => { - if (decimals < 0) - throw new Error("Decimal places shouldn't be negative number!"); - return new bignumber_default(amount).shiftedBy(-decimals).decimalPlaces(rounding).toFixed(); -}; -var export_Account = import_account4.Account; -var export_Address = import_address4.Address; -var export_AddressType = import_address5.AddressType; -var export_AddressValue = import_address5.AddressValue; -var export_BigUIntType = import_numerical.BigUIntType; -var export_BigUIntValue = import_numerical.BigUIntValue; -var export_BooleanType = import_boolean.BooleanType; -var export_BooleanValue = import_boolean.BooleanValue; -var export_BytesType = import_bytes7.BytesType; -var export_BytesValue = import_bytes7.BytesValue; -var export_ContractQueryResponse = import_contractQueryResponse2.ContractQueryResponse; -var export_Message = import_message.Message; -var export_MessageComputer = import_message.MessageComputer; -var export_QueryArguments = import_interface.QueryArguments; -var export_SignableMessage = import_signableMessage2.SignableMessage; -var export_SmartContractTransactionsFactory = import_transactionsFactories.SmartContractTransactionsFactory; -var export_SmartContractTransactionsOutcomeParser = import_transactionsOutcomeParsers.SmartContractTransactionsOutcomeParser; -var export_Token = import_tokens.Token; -var export_TokenComputer = import_tokens.TokenComputer; -var export_TokenManagementTransactionsFactory = import_transactionsFactories.TokenManagementTransactionsFactory; -var export_TokenManagementTransactionsOutcomeParser = import_transactionsOutcomeParsers.TokenManagementTransactionsOutcomeParser; -var export_TokenOperationsFactory = import_tokenOperations.TokenOperationsFactory; -var export_TokenOperationsFactoryConfig = import_tokenOperations.TokenOperationsFactoryConfig; -var export_TokenOperationsOutcomeParser = import_tokenOperations.TokenOperationsOutcomeParser; -var export_TokenTransfer = import_tokens.TokenTransfer; -var export_Transaction = import_transaction3.Transaction; -var export_TransactionComputer = import_transactionComputer.TransactionComputer; -var export_TransactionEventsParser = import_transactionsOutcomeParsers.TransactionEventsParser; -var export_TransactionWatcher = import_transactionWatcher2.TransactionWatcher; -var export_TransactionsFactoryConfig = import_transactionsFactories.TransactionsFactoryConfig; -var export_TransferTransactionsFactory = import_transactionsFactories.TransferTransactionsFactory; -var export_U16Type = import_numerical.U16Type; -var export_U16Value = import_numerical.U16Value; -var export_U32Type = import_numerical.U32Type; -var export_U32Value = import_numerical.U32Value; -var export_U64Type = import_numerical.U64Type; -var export_U64Value = import_numerical.U64Value; -var export_U8Type = import_numerical.U8Type; -var export_U8Value = import_numerical.U8Value; -export { - export_Account as Account, - export_Address as Address, - export_AddressType as AddressType, - export_AddressValue as AddressValue, - export_BigUIntType as BigUIntType, - export_BigUIntValue as BigUIntValue, - export_BooleanType as BooleanType, - export_BooleanValue as BooleanValue, - export_BytesType as BytesType, - export_BytesValue as BytesValue, - export_ContractQueryResponse as ContractQueryResponse, - DappCoreWCV2CustomMethodsEnum, - ElvenJS, - EventStoreEvents, - LoginMethodsEnum, - export_Message as Message, - export_MessageComputer as MessageComputer, - export_QueryArguments as QueryArguments, - export_SignableMessage as SignableMessage, - export_SmartContractTransactionsFactory as SmartContractTransactionsFactory, - export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser, - export_Token as Token, - export_TokenComputer as TokenComputer, - export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory, - export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser, - export_TokenOperationsFactory as TokenOperationsFactory, - export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig, - export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser, - export_TokenTransfer as TokenTransfer, - export_Transaction as Transaction, - export_TransactionComputer as TransactionComputer, - export_TransactionEventsParser as TransactionEventsParser, - export_TransactionWatcher as TransactionWatcher, - export_TransactionsFactoryConfig as TransactionsFactoryConfig, - export_TransferTransactionsFactory as TransferTransactionsFactory, - export_U16Type as U16Type, - export_U16Value as U16Value, - export_U32Type as U32Type, - export_U32Value as U32Value, - export_U64Type as U64Type, - export_U64Value as U64Value, - export_U8Type as U8Type, - export_U8Value as U8Value, - WebWalletUrlParamsEnum, - formatAmount, - parseAmount -}; -/*! Bundled license information: +`});var YR=fe(()=>{h();$R();Tm();Lo();OI();Th()});var RI,abe,JR=fe(()=>{h();IR();TR();_R();CR();NR();EI();xR();II();OR();PR();kR();jR();zR();QR();YR();RI={...pI,...mI,...yI,...wI,...vI,...AI,...bI,...SI,...TI,..._I},abe={...DI,...PI}});function ZR(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var XR,BI,SZ,xm,MI=fe(()=>{h();JR();bm();XR=ZR("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),BI=ZR("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=jc(t.length);for(let r=0;r{h();MI()});function ns(t,e="utf8"){let r=xm[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var FI=fe(()=>{h();MI();Eh()});function Ch(t){return Ro(ks(ns(t,Hc),pm))}function Nh(t){return ks(ns(Ai(t),pm),Hc)}function UI(t){let e=ns(Am,Gc),r=vm+ks(Sm([e,t]),Gc);return[ym,wm,r].join(mm)}function qI(t){let[e,r,n]=t.split(mm);if(e!==ym||r!==wm)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==vm)throw new Error("Issuer must be a key in mulicodec format");let s=ns(n.slice(1),Gc);if(ks(s.slice(0,2),Gc)!==Am)throw new Error('Issuer must be a public key with type "Ed25519"');let u=s.slice(2);if(u.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return u}function eB(t){return ks(t,Hc)}function tB(t){return ns(t,Hc)}function VI(t){return ns([Nh(t.header),Nh(t.payload)].join(Ya),Ah)}function IZ(t){let e=ks(t,Ah).split(Ya),r=Ch(e[0]),n=Ch(e[1]);return{header:r,payload:n}}function kI(t){return[Nh(t.header),Nh(t.payload),eB(t.signature)].join(Ya)}function HI(t){let e=t.split(Ya),r=Ch(e[0]),n=Ch(e[1]),i=tB(e[2]),s=ns(e.slice(0,2).join(Ya),Ah);return{header:r,payload:n,signature:i,data:s}}var GI=fe(()=>{h();lI();LI();FI();xc();Em()});function TZ(t=(0,rB.randomBytes)(32)){return Yc.generateKeyPairFromSeed(t)}async function _Z(t,e,r,n,i=(0,nB.fromMiliseconds)(Date.now())){let s={alg:dm,typ:gm},o=UI(n.publicKey),u=i+r,a={iss:o,sub:t,aud:e,iat:i,exp:u},c=VI({header:s,payload:a}),f=Yc.sign(n.secretKey,c);return kI({header:s,payload:a,signature:f})}async function CZ(t){let{header:e,payload:r,data:n,signature:i}=HI(t);if(e.alg!==dm||e.typ!==gm)throw new Error("JWT must use EdDSA algorithm");let s=qI(r.iss);return Yc.verify(s,n,i)}var Yc,rB,nB,iB=fe(()=>{h();Yc=pe(gR()),rB=pe(yh()),nB=pe(Qa());Em();GI()});var sB=fe(()=>{h()});var oB={};Bt(oB,{DATA_ENCODING:()=>Ah,DID_DELIMITER:()=>mm,DID_METHOD:()=>wm,DID_PREFIX:()=>ym,JSON_ENCODING:()=>pm,JWT_DELIMITER:()=>Ya,JWT_ENCODING:()=>Hc,JWT_IRIDIUM_ALG:()=>dm,JWT_IRIDIUM_TYP:()=>gm,KEY_PAIR_SEED_LENGTH:()=>mR,MULTICODEC_ED25519_BASE:()=>vm,MULTICODEC_ED25519_ENCODING:()=>Gc,MULTICODEC_ED25519_HEADER:()=>Am,MULTICODEC_ED25519_LENGTH:()=>pR,decodeData:()=>IZ,decodeIss:()=>qI,decodeJSON:()=>Ch,decodeJWT:()=>HI,decodeSig:()=>tB,encodeData:()=>VI,encodeIss:()=>UI,encodeJSON:()=>Nh,encodeJWT:()=>kI,encodeSig:()=>eB,generateKeyPair:()=>TZ,signJWT:()=>_Z,verifyJWT:()=>CZ});var aB=fe(()=>{h();iB();Em();sB();GI()});var vB=B(qt=>{"use strict";h();var uB=qt&&qt.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new pB:typeof navigator<"u"?jI(navigator.userAgent):wB()}qt.detect=DZ;function mB(t){return t!==""&&OZ.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function PZ(t){var e=mB(t);return e?e[0]:null}qt.browserName=PZ;function jI(t){var e=mB(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new gB;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getLocalStorage=Ot.getLocalStorageOrThrow=Ot.getCrypto=Ot.getCryptoOrThrow=Ot.getLocation=Ot.getLocationOrThrow=Ot.getNavigator=Ot.getNavigatorOrThrow=Ot.getDocument=Ot.getDocumentOrThrow=Ot.getFromWindowOrThrow=Ot.getFromWindow=void 0;function Xa(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}Ot.getFromWindow=Xa;function Jc(t){let e=Xa(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}Ot.getFromWindowOrThrow=Jc;function BZ(){return Jc("document")}Ot.getDocumentOrThrow=BZ;function MZ(){return Xa("document")}Ot.getDocument=MZ;function LZ(){return Jc("navigator")}Ot.getNavigatorOrThrow=LZ;function FZ(){return Xa("navigator")}Ot.getNavigator=FZ;function UZ(){return Jc("location")}Ot.getLocationOrThrow=UZ;function qZ(){return Xa("location")}Ot.getLocation=qZ;function VZ(){return Jc("crypto")}Ot.getCryptoOrThrow=VZ;function kZ(){return Xa("crypto")}Ot.getCrypto=kZ;function HZ(){return Jc("localStorage")}Ot.getLocalStorageOrThrow=HZ;function GZ(){return Xa("localStorage")}Ot.getLocalStorage=GZ});var EB=B(Om=>{"use strict";h();Object.defineProperty(Om,"__esModule",{value:!0});Om.getWindowMetadata=void 0;var AB=zI();function jZ(){let t,e;try{t=AB.getDocumentOrThrow(),e=AB.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),w=[];for(let A=0;A-1){let R=T.getAttribute("href");if(R)if(R.toLowerCase().indexOf("https:")===-1&&R.toLowerCase().indexOf("http:")===-1&&R.indexOf("//")!==0){let V=e.protocol+"//"+e.host;if(R.indexOf("/")===0)V+=R;else{let U=e.pathname.split("/");U.pop();let Q=U.join("/");V+=Q+"/"+R}w.push(V)}else if(R.indexOf("//")===0){let V=e.protocol+R;w.push(V)}else w.push(R)}}return w}function n(...d){let w=t.getElementsByTagName("meta");for(let A=0;AT.getAttribute(R)).filter(R=>R?d.includes(R):!1);if(x.length&&x){let R=T.getAttribute("content");if(R)return R}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),u=s(),a=e.origin,c=r();return{description:u,url:a,icons:c,name:o}}Om.getWindowMetadata=jZ});var SB=B((jbe,bB)=>{"use strict";h();bB.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var NB=B((Qbe,CB)=>{"use strict";h();var _B="%[a-f0-9]{2}",IB=new RegExp("("+_B+")|([^%]+?)","gi"),TB=new RegExp("("+_B+")+","gi");function QI(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],QI(r),QI(n))}function zZ(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(IB)||[],r=1;r{"use strict";h();xB.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var PB=B((Ybe,DB)=>{"use strict";h();DB.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";h();var KZ=SB(),WZ=NB(),BB=OB(),$Z=PB(),YZ=t=>t==null,KI=Symbol("encodeFragmentIdentifier");function JZ(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[",i,"]"].join("")]:[...r,[Zt(e,t),"[",Zt(i,t),"]=",Zt(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[]"].join("")]:[...r,[Zt(e,t),"[]=",Zt(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),":list="].join("")]:[...r,[Zt(e,t),":list=",Zt(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[Zt(r,t),e,Zt(i,t)].join("")]:[[n,Zt(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,Zt(e,t)]:[...r,[Zt(e,t),"=",Zt(n,t)].join("")]}}function XZ(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&Hs(n,t).includes(t.arrayFormatSeparator);n=o?Hs(n,t):n;let u=s||o?n.split(t.arrayFormatSeparator).map(a=>Hs(a,t)):n===null?n:Hs(n,t);i[r]=u};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&Hs(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(u=>Hs(u,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function MB(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Zt(t,e){return e.encode?e.strict?KZ(t):encodeURIComponent(t):t}function Hs(t,e){return e.decode?WZ(t):t}function LB(t){return Array.isArray(t)?t.sort():typeof t=="object"?LB(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function FB(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function ZZ(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function UB(t){t=FB(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function RB(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function qB(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),MB(e.arrayFormatSeparator);let r=XZ(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=BB(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:Hs(o,e),r(Hs(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=RB(s[o],e);else n[i]=RB(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=LB(o):i[s]=o,i},Object.create(null))}nn.extract=UB;nn.parse=qB;nn.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),MB(e.arrayFormatSeparator);let r=o=>e.skipNull&&YZ(t[o])||e.skipEmptyString&&t[o]==="",n=JZ(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let u=t[o];return u===void 0?"":u===null?Zt(o,e):Array.isArray(u)?u.length===0&&e.arrayFormat==="bracket-separator"?Zt(o,e)+"[]":u.reduce(n(o),[]).join("&"):Zt(o,e)+"="+Zt(u,e)}).filter(o=>o.length>0).join("&")};nn.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=BB(t,"#");return Object.assign({url:r.split("?")[0]||"",query:qB(UB(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:Hs(n,e)}:{})};nn.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[KI]:!0},e);let r=FB(t.url).split("?")[0]||"",n=nn.extract(t.url),i=nn.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=nn.stringify(s,e);o&&(o=`?${o}`);let u=ZZ(t.url);return t.fragmentIdentifier&&(u=`#${e[KI]?Zt(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${u}`};nn.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[KI]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=nn.parseUrl(t,r);return nn.stringifyUrl({url:n,query:$Z(i,e),fragmentIdentifier:s},r)};nn.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return nn.pick(t,n,r)}});var HB=B(Dm=>{"use strict";h();Object.defineProperty(Dm,"__esModule",{value:!0});var Mr=Uc(),WI=Qn(),eee=20;function tee(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,u=r[3]<<24|r[2]<<16|r[1]<<8|r[0],a=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],w=r[23]<<24|r[22]<<16|r[21]<<8|r[20],A=r[27]<<24|r[26]<<16|r[25]<<8|r[24],T=r[31]<<24|r[30]<<16|r[29]<<8|r[28],x=e[3]<<24|e[2]<<16|e[1]<<8|e[0],R=e[7]<<24|e[6]<<16|e[5]<<8|e[4],V=e[11]<<24|e[10]<<16|e[9]<<8|e[8],U=e[15]<<24|e[14]<<16|e[13]<<8|e[12],Q=n,L=i,k=s,H=o,q=u,v=a,C=c,D=f,F=d,P=w,l=A,g=T,y=x,E=R,S=V,_=U,M=0;M>>16|y<<16,F=F+y|0,q^=F,q=q>>>20|q<<12,L=L+v|0,E^=L,E=E>>>16|E<<16,P=P+E|0,v^=P,v=v>>>20|v<<12,k=k+C|0,S^=k,S=S>>>16|S<<16,l=l+S|0,C^=l,C=C>>>20|C<<12,H=H+D|0,_^=H,_=_>>>16|_<<16,g=g+_|0,D^=g,D=D>>>20|D<<12,k=k+C|0,S^=k,S=S>>>24|S<<8,l=l+S|0,C^=l,C=C>>>25|C<<7,H=H+D|0,_^=H,_=_>>>24|_<<8,g=g+_|0,D^=g,D=D>>>25|D<<7,L=L+v|0,E^=L,E=E>>>24|E<<8,P=P+E|0,v^=P,v=v>>>25|v<<7,Q=Q+q|0,y^=Q,y=y>>>24|y<<8,F=F+y|0,q^=F,q=q>>>25|q<<7,Q=Q+v|0,_^=Q,_=_>>>16|_<<16,l=l+_|0,v^=l,v=v>>>20|v<<12,L=L+C|0,y^=L,y=y>>>16|y<<16,g=g+y|0,C^=g,C=C>>>20|C<<12,k=k+D|0,E^=k,E=E>>>16|E<<16,F=F+E|0,D^=F,D=D>>>20|D<<12,H=H+q|0,S^=H,S=S>>>16|S<<16,P=P+S|0,q^=P,q=q>>>20|q<<12,k=k+D|0,E^=k,E=E>>>24|E<<8,F=F+E|0,D^=F,D=D>>>25|D<<7,H=H+q|0,S^=H,S=S>>>24|S<<8,P=P+S|0,q^=P,q=q>>>25|q<<7,L=L+C|0,y^=L,y=y>>>24|y<<8,g=g+y|0,C^=g,C=C>>>25|C<<7,Q=Q+v|0,_^=Q,_=_>>>24|_<<8,l=l+_|0,v^=l,v=v>>>25|v<<7;Mr.writeUint32LE(Q+n|0,t,0),Mr.writeUint32LE(L+i|0,t,4),Mr.writeUint32LE(k+s|0,t,8),Mr.writeUint32LE(H+o|0,t,12),Mr.writeUint32LE(q+u|0,t,16),Mr.writeUint32LE(v+a|0,t,20),Mr.writeUint32LE(C+c|0,t,24),Mr.writeUint32LE(D+f|0,t,28),Mr.writeUint32LE(F+d|0,t,32),Mr.writeUint32LE(P+w|0,t,36),Mr.writeUint32LE(l+A|0,t,40),Mr.writeUint32LE(g+T|0,t,44),Mr.writeUint32LE(y+x|0,t,48),Mr.writeUint32LE(E+R|0,t,52),Mr.writeUint32LE(S+V|0,t,56),Mr.writeUint32LE(_+U|0,t,60)}function kB(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Pm=B(Xc=>{"use strict";h();Object.defineProperty(Xc,"__esModule",{value:!0});function iee(t,e,r){return~(t-1)&e|t-1&r}Xc.select=iee;function see(t,e){return(t|0)-(e|0)-1>>>31&1}Xc.lessOrEqual=see;function GB(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xc.compare=GB;function oee(t,e){return t.length===0||e.length===0?!1:GB(t,e)!==0}Xc.equal=oee});var zB=B(Gs=>{"use strict";h();Object.defineProperty(Gs,"__esModule",{value:!0});var aee=Pm(),Rm=Qn();Gs.DIGEST_LENGTH=16;var jB=function(){function t(e){this.digestLength=Gs.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var u=e[10]|e[11]<<8;this._r[6]=(o>>>14|u<<2)&8191;var a=e[12]|e[13]<<8;this._r[7]=(u>>>11|a<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(a>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],u=this._h[2],a=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],w=this._h[7],A=this._h[8],T=this._h[9],x=this._r[0],R=this._r[1],V=this._r[2],U=this._r[3],Q=this._r[4],L=this._r[5],k=this._r[6],H=this._r[7],q=this._r[8],v=this._r[9];n>=16;){var C=e[r+0]|e[r+1]<<8;s+=C&8191;var D=e[r+2]|e[r+3]<<8;o+=(C>>>13|D<<3)&8191;var F=e[r+4]|e[r+5]<<8;u+=(D>>>10|F<<6)&8191;var P=e[r+6]|e[r+7]<<8;a+=(F>>>7|P<<9)&8191;var l=e[r+8]|e[r+9]<<8;c+=(P>>>4|l<<12)&8191,f+=l>>>1&8191;var g=e[r+10]|e[r+11]<<8;d+=(l>>>14|g<<2)&8191;var y=e[r+12]|e[r+13]<<8;w+=(g>>>11|y<<5)&8191;var E=e[r+14]|e[r+15]<<8;A+=(y>>>8|E<<8)&8191,T+=E>>>5|i;var S=0,_=S;_+=s*x,_+=o*(5*v),_+=u*(5*q),_+=a*(5*H),_+=c*(5*k),S=_>>>13,_&=8191,_+=f*(5*L),_+=d*(5*Q),_+=w*(5*U),_+=A*(5*V),_+=T*(5*R),S+=_>>>13,_&=8191;var M=S;M+=s*R,M+=o*x,M+=u*(5*v),M+=a*(5*q),M+=c*(5*H),S=M>>>13,M&=8191,M+=f*(5*k),M+=d*(5*L),M+=w*(5*Q),M+=A*(5*U),M+=T*(5*V),S+=M>>>13,M&=8191;var N=S;N+=s*V,N+=o*R,N+=u*x,N+=a*(5*v),N+=c*(5*q),S=N>>>13,N&=8191,N+=f*(5*H),N+=d*(5*k),N+=w*(5*L),N+=A*(5*Q),N+=T*(5*U),S+=N>>>13,N&=8191;var m=S;m+=s*U,m+=o*V,m+=u*R,m+=a*x,m+=c*(5*v),S=m>>>13,m&=8191,m+=f*(5*q),m+=d*(5*H),m+=w*(5*k),m+=A*(5*L),m+=T*(5*Q),S+=m>>>13,m&=8191;var O=S;O+=s*Q,O+=o*U,O+=u*V,O+=a*R,O+=c*x,S=O>>>13,O&=8191,O+=f*(5*v),O+=d*(5*q),O+=w*(5*H),O+=A*(5*k),O+=T*(5*L),S+=O>>>13,O&=8191;var Y=S;Y+=s*L,Y+=o*Q,Y+=u*U,Y+=a*V,Y+=c*R,S=Y>>>13,Y&=8191,Y+=f*x,Y+=d*(5*v),Y+=w*(5*q),Y+=A*(5*H),Y+=T*(5*k),S+=Y>>>13,Y&=8191;var $=S;$+=s*k,$+=o*L,$+=u*Q,$+=a*U,$+=c*V,S=$>>>13,$&=8191,$+=f*R,$+=d*x,$+=w*(5*v),$+=A*(5*q),$+=T*(5*H),S+=$>>>13,$&=8191;var b=S;b+=s*H,b+=o*k,b+=u*L,b+=a*Q,b+=c*U,S=b>>>13,b&=8191,b+=f*V,b+=d*R,b+=w*x,b+=A*(5*v),b+=T*(5*q),S+=b>>>13,b&=8191;var j=S;j+=s*q,j+=o*H,j+=u*k,j+=a*L,j+=c*Q,S=j>>>13,j&=8191,j+=f*U,j+=d*V,j+=w*R,j+=A*x,j+=T*(5*v),S+=j>>>13,j&=8191;var z=S;z+=s*v,z+=o*q,z+=u*H,z+=a*k,z+=c*L,S=z>>>13,z&=8191,z+=f*Q,z+=d*U,z+=w*V,z+=A*R,z+=T*x,S+=z>>>13,z&=8191,S=(S<<2)+S|0,S=S+_|0,_=S&8191,S=S>>>13,M+=S,s=_,o=M,u=N,a=m,c=O,f=Y,d=$,w=b,A=j,T=z,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=u,this._h[3]=a,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=w,this._h[8]=A,this._h[9]=T},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,u;if(this._leftover){for(u=this._leftover,this._buffer[u++]=1;u<16;u++)this._buffer[u]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,u=2;u<10;u++)this._h[u]+=i,i=this._h[u]>>>13,this._h[u]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,u=1;u<10;u++)n[u]=this._h[u]+i,i=n[u]>>>13,n[u]&=8191;for(n[9]-=8192,s=(i^1)-1,u=0;u<10;u++)n[u]&=s;for(s=~s,u=0;u<10;u++)this._h[u]=this._h[u]&s|n[u];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,u=1;u<8;u++)o=(this._h[u]+this._pad[u]|0)+(o>>>16)|0,this._h[u]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";h();Object.defineProperty(js,"__esModule",{value:!0});var Bm=HB(),lee=zB(),xh=Qn(),QB=Uc(),fee=Pm();js.KEY_LENGTH=32;js.NONCE_LENGTH=12;js.TAG_LENGTH=16;var KB=new Uint8Array(16),hee=function(){function t(e){if(this.nonceLength=js.NONCE_LENGTH,this.tagLength=js.TAG_LENGTH,e.length!==js.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Bm.stream(this._key,s,o,4);var u=r.length+this.tagLength,a;if(i){if(i.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");a=i}else a=new Uint8Array(u);return Bm.streamXOR(this._key,s,r,a,4),this._authenticate(a.subarray(a.length-this.tagLength,a.length),o,a.subarray(0,a.length-this.tagLength),n),xh.wipe(s),a},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(KB.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(KB.subarray(n.length%16));var o=new Uint8Array(8);i&&QB.writeUint64LE(i.length,o),s.update(o),QB.writeUint64LE(n.length,o),s.update(o);for(var u=s.digest(),a=0;a{"use strict";h();Object.defineProperty($I,"__esModule",{value:!0});function dee(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}$I.isSerializableHash=dee});var JB=B(Oh=>{"use strict";h();Object.defineProperty(Oh,"__esModule",{value:!0});var is=$B(),gee=Pm(),pee=Qn(),YB=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";h();Object.defineProperty(YI,"__esModule",{value:!0});var XB=JB(),ZB=Qn(),yee=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=XB.hmac(this._hash,n,r);this._hmac=new XB.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";h();Object.defineProperty(Uo,"__esModule",{value:!0});var Lm=Uc(),Mm=Qn();Uo.DIGEST_LENGTH=32;Uo.BLOCK_SIZE=64;var tM=function(){function t(){this.digestLength=Uo.DIGEST_LENGTH,this.blockSize=Uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Mm.wipe(this._buffer),Mm.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(JI(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=JI(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Mm.wipe(e.state),e.buffer&&Mm.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Uo.SHA256=tM;var wee=new Int32Array([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]);function JI(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],u=e[2],a=e[3],c=e[4],f=e[5],d=e[6],w=e[7],A=0;A<16;A++){var T=n+A*4;t[A]=Lm.readUint32BE(r,T)}for(var A=16;A<64;A++){var x=t[A-2],R=(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10;x=t[A-15];var V=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3;t[A]=(R+t[A-7]|0)+(V+t[A-16]|0)}for(var A=0;A<64;A++){var R=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(w+(wee[A]+t[A]|0)|0)|0,V=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&u^o&u)|0;w=d,d=f,f=c,c=a+R|0,a=u,u=o,o=s,s=R+V|0}e[0]+=s,e[1]+=o,e[2]+=u,e[3]+=a,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=w,n+=64,i-=64}return n}function vee(t){var e=new tM;e.update(t);var r=e.digest();return e.clean(),r}Uo.hash=vee});var oM=B(zt=>{"use strict";h();Object.defineProperty(zt,"__esModule",{value:!0});zt.sharedKey=zt.generateKeyPair=zt.generateKeyPairFromSeed=zt.scalarMultBase=zt.scalarMult=zt.SHARED_KEY_LENGTH=zt.SECRET_KEY_LENGTH=zt.PUBLIC_KEY_LENGTH=void 0;var Aee=yh(),Eee=Qn();zt.PUBLIC_KEY_LENGTH=32;zt.SECRET_KEY_LENGTH=32;zt.SHARED_KEY_LENGTH=32;function ss(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Dh(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function Iee(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Fm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Um(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function zs(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ph(t,e){zs(t,e,e)}function Tee(t,e){let r=ss();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)Ph(r,r),n!==2&&n!==4&&zs(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function ZI(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=ss(),s=ss(),o=ss(),u=ss(),a=ss(),c=ss();for(let A=0;A<31;A++)r[A]=t[A];r[31]=t[31]&127|64,r[0]&=248,Iee(n,e);for(let A=0;A<16;A++)s[A]=n[A];i[0]=u[0]=1;for(let A=254;A>=0;--A){let T=r[A>>>3]>>>(A&7)&1;Dh(i,s,T),Dh(o,u,T),Fm(a,i,o),Um(i,i,o),Fm(o,s,u),Um(s,s,u),Ph(u,a),Ph(c,i),zs(i,o,i),zs(o,s,a),Fm(a,i,o),Um(i,i,o),Ph(s,i),Um(o,u,c),zs(i,o,bee),Fm(i,i,u),zs(o,o,i),zs(i,u,c),zs(u,s,n),Ph(s,a),Dh(i,s,T),Dh(o,u,T)}for(let A=0;A<16;A++)n[A+16]=i[A],n[A+32]=o[A],n[A+48]=s[A],n[A+64]=u[A];let f=n.subarray(32),d=n.subarray(16);Tee(f,f),zs(d,d,f);let w=new Uint8Array(32);return See(w,d),w}zt.scalarMult=ZI;function iM(t){return ZI(t,nM)}zt.scalarMultBase=iM;function sM(t){if(t.length!==zt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${zt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:iM(e),secretKey:e}}zt.generateKeyPairFromSeed=sM;function _ee(t){let e=(0,Aee.randomBytes)(32,t),r=sM(e);return(0,Eee.wipe)(e),r}zt.generateKeyPair=_ee;function Cee(t,e,r=!1){if(t.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=ZI(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{h()});function cM(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{h()});function fM(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=jc(t.length);for(let n=0;n{h();bm();Eh()});var eT={};Bt(eT,{compare:()=>aM,concat:()=>Sm,equals:()=>cM,fromString:()=>ns,toString:()=>ks,xor:()=>fM});var tT=fe(()=>{h();uM();lI();lM();FI();LI();hM()});var dM={};Bt(dM,{RELAY_JSONRPC:()=>qee,isPublishMethod:()=>iT,isPublishParams:()=>sT,isPublishRequest:()=>Pee,isSubscribeMethod:()=>rT,isSubscribeParams:()=>nT,isSubscribeRequest:()=>Dee,isSubscriptionMethod:()=>uT,isSubscriptionParams:()=>cT,isSubscriptionRequest:()=>Bee,isUnsubscribeMethod:()=>oT,isUnsubscribeParams:()=>aT,isUnsubscribeRequest:()=>Ree,parsePublishRequest:()=>Lee,parseSubscribeRequest:()=>Mee,parseSubscriptionRequest:()=>Uee,parseUnsubscribeRequest:()=>Fee});function Za(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function Nee(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function xee(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function Oee(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function qm(t,e,r){return(r.length?Oee(t,e.length):xee(t,e.length))?Nee(t,e):!1}function Vm(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}function Dee(t){return rT(t.method)&&nT(t.params)}function rT(t){return Vm(t,"subscribe")}function nT(t){return qm(t,["topic"],[])}function Pee(t){return iT(t.method)&&sT(t.params)}function iT(t){return Vm(t,"publish")}function sT(t){return qm(t,["message","topic","ttl"],["prompt","tag"])}function Ree(t){return oT(t.method)&&aT(t.params)}function oT(t){return Vm(t,"unsubscribe")}function aT(t){return qm(t,["id","topic"],[])}function Bee(t){return uT(t.method)&&cT(t.params)}function uT(t){return Vm(t,"subscription")}function cT(t){return qm(t,["id","data"],[])}function Mee(t){if(!rT(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!nT(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Za(e,"topic"),e}function Lee(t){if(!iT(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!sT(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Za(e,"topic"),Za(e,"message"),Za(e,"ttl","number"),e}function Fee(t){if(!oT(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!aT(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Za(e,"id"),e}function Uee(t){if(!uT(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!cT(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Za(e,"id"),Za(e,"data"),e}var qee,gM=fe(()=>{h();qee={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var Qh=B(K=>{"use strict";h();Object.defineProperty(K,"__esModule",{value:!0});var Vee=vB(),el=Qa(),il=zI(),kee=EB(),Hee=VB(),WM=WB(),Gee=eM(),$M=yh(),LT=rM(),jee=oM(),Vt=(tT(),_e(eT)),zee=(gM(),_e(dM));function YM(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var $m=YM(Hee),JM=YM(jee),ny=":";function XM(t){let[e,r]=t.split(ny);return{namespace:e,reference:r}}function ZM(t){let{namespace:e,reference:r}=t;return[e,r].join(ny)}function FT(t){let[e,r,n]=t.split(ny);return{namespace:e,reference:r,address:n}}function e4(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(ny)}function UT(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function t4(t){let{address:e}=FT(t);return e}function r4(t){let{namespace:e,reference:r}=FT(t);return ZM({namespace:e,reference:r})}function Qee(t,e){let{namespace:r,reference:n}=XM(e);return e4({namespace:r,reference:n,address:t})}function Kee(t){return UT(t,t4)}function n4(t){return UT(t,r4)}function Wee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function $ee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...n4(i.accounts))}),r}function Yee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...iy(n,i))}),r}function iy(t,e){return t.includes(":")?[t]:e.chains||[]}var Jee=Object.defineProperty,pM=Object.getOwnPropertySymbols,Xee=Object.prototype.hasOwnProperty,Zee=Object.prototype.propertyIsEnumerable,mM=(t,e,r)=>e in t?Jee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yM=(t,e)=>{for(var r in e||(e={}))Xee.call(e,r)&&mM(t,r,e[r]);if(pM)for(var r of pM(e))Zee.call(e,r)&&mM(t,r,e[r]);return t},i4="ReactNative",Gr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Ym=" ",ete=":",s4="/",qT=2,tte=1e3,o4="js";function VT(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}function al(){return!il.getDocument()&&!!il.getNavigator()&&navigator.product===i4}function Hh(){return!VT()&&!!il.getNavigator()&&!!il.getDocument()}function ru(){return al()?Gr.reactNative:VT()?Gr.node:Hh()?Gr.browser:Gr.unknown}function rte(){var t;try{return al()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function a4(t,e){let r=$m.parse(t);return r=yM(yM({},r),e),t=$m.stringify(r),t}function nte(){return kee.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function ite(t,e){var r;let n=ru(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=il.getLocation())==null?void 0:r.host)||"unknown"),i}function u4(){if(ru()===Gr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=Vee.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function c4(){var t;let e=ru();return e===Gr.browser?[e,((t=il.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function l4(t,e,r){let n=u4(),i=c4();return[[t,e].join("-"),[o4,r].join("-"),n,i].join("/")}function ste({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:u}){let a=r.split("?"),c=l4(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:u||void 0},d=a4(a[1]||"",f);return a[0]+"?"+d}function ote(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function ate(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function f4(t,e=qT){return h4(t.split(s4),e)}function ute(t){return f4(t).join(Ym)}function Ho(t,e){return t.filter(r=>e.includes(r)).length===t.length}function h4(t,e=qT){return t.slice(Math.max(t.length-e,0))}function cte(t){return Object.fromEntries(t.entries())}function lte(t){return new Map(Object.entries(t))}function fte(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var hte=t=>t;function d4(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function dte(t){return t.split(Ym).map(e=>d4(e)).join(Ym)}function gte(t=el.FIVE_MINUTES,e){let r=el.toMiliseconds(t||el.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,u)=>{s=setTimeout(()=>{u(new Error(e))},r),n=o,i=u})}}function pte(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function kT(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function mte(t){return kT("topic",t)}function yte(t){return kT("id",t)}function wte(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function vte(t,e){return el.fromMiliseconds((e||Date.now())+el.toMiliseconds(t))}function Ate(t){return Date.now()>=el.toMiliseconds(t)}function Ete(t,e){return`${t}${e?`:${e}`:""}`}function Js(t=[],e=[]){return[...new Set([...t,...e])]}async function bte({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=ru();o===Gr.browser?s.startsWith("https://")||s.startsWith("http://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===Gr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function Ste(t,e){try{return await t.getItem(e)||(Hh()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}function TT(t,e){return t.filter(r=>e.includes(r))}var g4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ite(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var p4={exports:{}};(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!i.JS_SHA3_NO_NODE_JS&&typeof I.default=="object"&&I.default.versions&&I.default.versions.node;o?i=g4:s&&(i=self);var u=!i.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),f=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],w=[1,256,65536,16777216],A=[6,1536,393216,100663296],T=[0,8,16,24],x=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],R=[224,256,384,512],V=[128,256],U=["hex","buffer","arrayBuffer","array","digest"],Q={128:168,256:136};(i.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(b){return Object.prototype.toString.call(b)==="[object Array]"}),a&&(i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(b){return typeof b=="object"&&b.buffer&&b.buffer.constructor===ArrayBuffer});for(var L=function(b,j,z){return function(W){return new O(b,j,b).update(W)[z]()}},k=function(b,j,z){return function(W,ie){return new O(b,j,ie).update(W)[z]()}},H=function(b,j,z){return function(W,ie,te,ee){return g["cshake"+b].update(W,ie,te,ee)[z]()}},q=function(b,j,z){return function(W,ie,te,ee){return g["kmac"+b].update(W,ie,te,ee)[z]()}},v=function(b,j,z,W){for(var ie=0;ie>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var W=0;W<50;++W)this.s[W]=0}O.prototype.update=function(b){if(this.finalized)throw new Error(r);var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}for(var W=this.blocks,ie=this.byteCount,te=b.length,ee=this.blockCount,se=0,oe=this.s,J,ue;se>2]|=b[se]<>2]|=ue<>2]|=(192|ue>>6)<>2]|=(128|ue&63)<=57344?(W[J>>2]|=(224|ue>>12)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<>2]|=(240|ue>>18)<>2]|=(128|ue>>12&63)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<=ie){for(this.start=J-ie,this.block=W[ee],J=0;J>8,z=b&255;z>0;)ie.unshift(z),b=b>>8,z=b&255,++W;return j?ie.push(W):ie.unshift(W),this.update(ie),ie.length},O.prototype.encodeString=function(b){var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}var W=0,ie=b.length;if(j)W=ie;else for(var te=0;te=57344?W+=3:(ee=65536+((ee&1023)<<10|b.charCodeAt(++te)&1023),W+=4)}return W+=this.encode(W*8),this.update(b),W},O.prototype.bytepad=function(b,j){for(var z=this.encode(j),W=0;W>2]|=this.padding[j&3],this.lastByteIndex===this.byteCount)for(b[0]=b[z],j=1;j>4&15]+c[se&15]+c[se>>12&15]+c[se>>8&15]+c[se>>20&15]+c[se>>16&15]+c[se>>28&15]+c[se>>24&15];te%b===0&&($(j),ie=0)}return W&&(se=j[ie],ee+=c[se>>4&15]+c[se&15],W>1&&(ee+=c[se>>12&15]+c[se>>8&15]),W>2&&(ee+=c[se>>20&15]+c[se>>16&15])),ee},O.prototype.arrayBuffer=function(){this.finalize();var b=this.blockCount,j=this.s,z=this.outputBlocks,W=this.extraBytes,ie=0,te=0,ee=this.outputBits>>3,se;W?se=new ArrayBuffer(z+1<<2):se=new ArrayBuffer(ee);for(var oe=new Uint32Array(se);te>8&255,ee[se+2]=oe>>16&255,ee[se+3]=oe>>24&255;te%b===0&&$(j)}return W&&(se=te<<2,oe=j[ie],ee[se]=oe&255,W>1&&(ee[se+1]=oe>>8&255),W>2&&(ee[se+2]=oe>>16&255)),ee};function Y(b,j,z){O.call(this,b,j,z)}Y.prototype=new O,Y.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var $=function(b){var j,z,W,ie,te,ee,se,oe,J,ue,wt,vt,Ni,At,Et,xi,bt,St,Oi,It,Tt,Di,Qe,Ke,ri,We,$e,ni,Ye,Je,ii,Xe,Ze,si,et,tt,oi,rt,nt,ai,it,st,ui,ot,at,ci,ut,ct,li,lt,ft,fi,ht,dt,hi,gt,pt,vn,An,En,bn,Sn,In;for(W=0;W<48;W+=2)ie=b[0]^b[10]^b[20]^b[30]^b[40],te=b[1]^b[11]^b[21]^b[31]^b[41],ee=b[2]^b[12]^b[22]^b[32]^b[42],se=b[3]^b[13]^b[23]^b[33]^b[43],oe=b[4]^b[14]^b[24]^b[34]^b[44],J=b[5]^b[15]^b[25]^b[35]^b[45],ue=b[6]^b[16]^b[26]^b[36]^b[46],wt=b[7]^b[17]^b[27]^b[37]^b[47],vt=b[8]^b[18]^b[28]^b[38]^b[48],Ni=b[9]^b[19]^b[29]^b[39]^b[49],j=vt^(ee<<1|se>>>31),z=Ni^(se<<1|ee>>>31),b[0]^=j,b[1]^=z,b[10]^=j,b[11]^=z,b[20]^=j,b[21]^=z,b[30]^=j,b[31]^=z,b[40]^=j,b[41]^=z,j=ie^(oe<<1|J>>>31),z=te^(J<<1|oe>>>31),b[2]^=j,b[3]^=z,b[12]^=j,b[13]^=z,b[22]^=j,b[23]^=z,b[32]^=j,b[33]^=z,b[42]^=j,b[43]^=z,j=ee^(ue<<1|wt>>>31),z=se^(wt<<1|ue>>>31),b[4]^=j,b[5]^=z,b[14]^=j,b[15]^=z,b[24]^=j,b[25]^=z,b[34]^=j,b[35]^=z,b[44]^=j,b[45]^=z,j=oe^(vt<<1|Ni>>>31),z=J^(Ni<<1|vt>>>31),b[6]^=j,b[7]^=z,b[16]^=j,b[17]^=z,b[26]^=j,b[27]^=z,b[36]^=j,b[37]^=z,b[46]^=j,b[47]^=z,j=ue^(ie<<1|te>>>31),z=wt^(te<<1|ie>>>31),b[8]^=j,b[9]^=z,b[18]^=j,b[19]^=z,b[28]^=j,b[29]^=z,b[38]^=j,b[39]^=z,b[48]^=j,b[49]^=z,At=b[0],Et=b[1],ci=b[11]<<4|b[10]>>>28,ut=b[10]<<4|b[11]>>>28,ni=b[20]<<3|b[21]>>>29,Ye=b[21]<<3|b[20]>>>29,En=b[31]<<9|b[30]>>>23,bn=b[30]<<9|b[31]>>>23,st=b[40]<<18|b[41]>>>14,ui=b[41]<<18|b[40]>>>14,si=b[2]<<1|b[3]>>>31,et=b[3]<<1|b[2]>>>31,xi=b[13]<<12|b[12]>>>20,bt=b[12]<<12|b[13]>>>20,ct=b[22]<<10|b[23]>>>22,li=b[23]<<10|b[22]>>>22,Je=b[33]<<13|b[32]>>>19,ii=b[32]<<13|b[33]>>>19,Sn=b[42]<<2|b[43]>>>30,In=b[43]<<2|b[42]>>>30,dt=b[5]<<30|b[4]>>>2,hi=b[4]<<30|b[5]>>>2,tt=b[14]<<6|b[15]>>>26,oi=b[15]<<6|b[14]>>>26,St=b[25]<<11|b[24]>>>21,Oi=b[24]<<11|b[25]>>>21,lt=b[34]<<15|b[35]>>>17,ft=b[35]<<15|b[34]>>>17,Xe=b[45]<<29|b[44]>>>3,Ze=b[44]<<29|b[45]>>>3,Ke=b[6]<<28|b[7]>>>4,ri=b[7]<<28|b[6]>>>4,gt=b[17]<<23|b[16]>>>9,pt=b[16]<<23|b[17]>>>9,rt=b[26]<<25|b[27]>>>7,nt=b[27]<<25|b[26]>>>7,It=b[36]<<21|b[37]>>>11,Tt=b[37]<<21|b[36]>>>11,fi=b[47]<<24|b[46]>>>8,ht=b[46]<<24|b[47]>>>8,ot=b[8]<<27|b[9]>>>5,at=b[9]<<27|b[8]>>>5,We=b[18]<<20|b[19]>>>12,$e=b[19]<<20|b[18]>>>12,vn=b[29]<<7|b[28]>>>25,An=b[28]<<7|b[29]>>>25,ai=b[38]<<8|b[39]>>>24,it=b[39]<<8|b[38]>>>24,Di=b[48]<<14|b[49]>>>18,Qe=b[49]<<14|b[48]>>>18,b[0]=At^~xi&St,b[1]=Et^~bt&Oi,b[10]=Ke^~We&ni,b[11]=ri^~$e&Ye,b[20]=si^~tt&rt,b[21]=et^~oi&nt,b[30]=ot^~ci&ct,b[31]=at^~ut&li,b[40]=dt^~gt&vn,b[41]=hi^~pt&An,b[2]=xi^~St&It,b[3]=bt^~Oi&Tt,b[12]=We^~ni&Je,b[13]=$e^~Ye&ii,b[22]=tt^~rt&ai,b[23]=oi^~nt&it,b[32]=ci^~ct<,b[33]=ut^~li&ft,b[42]=gt^~vn&En,b[43]=pt^~An&bn,b[4]=St^~It&Di,b[5]=Oi^~Tt&Qe,b[14]=ni^~Je&Xe,b[15]=Ye^~ii&Ze,b[24]=rt^~ai&st,b[25]=nt^~it&ui,b[34]=ct^~lt&fi,b[35]=li^~ft&ht,b[44]=vn^~En&Sn,b[45]=An^~bn&In,b[6]=It^~Di&At,b[7]=Tt^~Qe&Et,b[16]=Je^~Xe&Ke,b[17]=ii^~Ze&ri,b[26]=ai^~st&si,b[27]=it^~ui&et,b[36]=lt^~fi&ot,b[37]=ft^~ht&at,b[46]=En^~Sn&dt,b[47]=bn^~In&hi,b[8]=Di^~At&xi,b[9]=Qe^~Et&bt,b[18]=Xe^~Ke&We,b[19]=Ze^~ri&$e,b[28]=st^~si&tt,b[29]=ui^~et&oi,b[38]=fi^~ot&ci,b[39]=ht^~at&ut,b[48]=Sn^~dt>,b[49]=In^~hi&pt,b[0]^=x[W],b[1]^=x[W+1]};if(u)t.exports=g;else for(E=0;E{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken implementation")}catch(t){return t.message}return null}var EM=Cte(),_T;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(_T||(_T={}));var Si;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Si||(Si={}));var bM="0123456789abcdef",kt=class t{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){let n=e.toLowerCase();Qm[n]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(AM>Qm[n])&&console.log.apply(console,r)}debug(...e){this._log(t.levels.DEBUG,e)}info(...e){this._log(t.levels.INFO,e)}warn(...e){this._log(t.levels.WARNING,e)}makeError(e,r,n){if(vM)return this.makeError("censored error",r,{});r||(r=t.errors.UNKNOWN_ERROR),n||(n={});let i=[];Object.keys(n).forEach(a=>{let c=n[a];try{if(c instanceof Uint8Array){let f="";for(let d=0;d>4],f+=bM[c[d]&15];i.push(a+"=Uint8Array(0x"+f+")")}else i.push(a+"="+JSON.stringify(c))}catch{i.push(a+"="+JSON.stringify(n[a].toString()))}}),i.push(`code=${r}`),i.push(`version=${this.version}`);let s=e,o="";switch(r){case Si.NUMERIC_FAULT:{o="NUMERIC_FAULT";let a=e;switch(a){case"overflow":case"underflow":case"division-by-zero":o+="-"+a;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Si.CALL_EXCEPTION:case Si.INSUFFICIENT_FUNDS:case Si.MISSING_NEW:case Si.NONCE_EXPIRED:case Si.REPLACEMENT_UNDERPRICED:case Si.TRANSACTION_REPLACED:case Si.UNPREDICTABLE_GAS_LIMIT:o=r;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),i.length&&(e+=" ("+i.join(", ")+")");let u=new Error(e);return u.reason=s,u.code=r,Object.keys(n).forEach(function(a){u[a]=n[a]}),u}throwError(e,r,n){throw this.makeError(e,r,n)}throwArgumentError(e,r,n){return this.throwError(e,t.errors.INVALID_ARGUMENT,{argument:r,value:n})}assert(e,r,n,i){e||this.throwError(r,n,i)}assertArgument(e,r,n,i){e||this.throwArgumentError(r,n,i)}checkNormalize(e){EM&&this.throwError("platform missing String.prototype.normalize",t.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:EM})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,n){n?n=": "+n:n="",er&&this.throwError("too many arguments"+n,t.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",t.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return lT||(lT=new t(_te)),lT}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),wM){if(!e)return;this.globalLogger().throwError("error censorship permanent",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}vM=!!e,wM=!!r}static setLogLevel(e){let r=Qm[e.toLowerCase()];if(r==null){t.globalLogger().warn("invalid log level - "+e);return}AM=r}static from(e){return new t(e)}};kt.errors=Si,kt.levels=_T;var Nte="bytes/5.7.0",er=new kt(Nte);function m4(t){return!!t.toHexString}function tl(t){return t.slice||(t.slice=function(){let e=Array.prototype.slice.call(arguments);return tl(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function xte(t){return gn(t)&&!(t.length%2)||ul(t)}function SM(t){return typeof t=="number"&&t==t&&t%1===0}function ul(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!SM(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function Qt(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid arrayify value");let r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),tl(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t)&&(t=t.toHexString()),gn(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":er.throwArgumentError("hex data is odd-length","value",t));let n=[];for(let i=0;iQt(i)),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);return e.reduce((i,s)=>(n.set(s,i),i+s.length),0),tl(n)}function Dte(t,e){t=Qt(t),t.length>e&&er.throwArgumentError("value out of range","value",arguments[0]);let r=new Uint8Array(e);return r.set(t,e-t.length),tl(r)}function gn(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}var fT="0123456789abcdef";function kr(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=fT[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t))return t.toHexString();if(gn(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":er.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(ul(t)){let r="0x";for(let n=0;n>4]+fT[i&15]}return r}return er.throwArgumentError("invalid hexlify value","value",t)}function Pte(t){if(typeof t!="string")t=kr(t);else if(!gn(t)||t.length%2)return null;return(t.length-2)/2}function IM(t,e,r){return typeof t!="string"?t=kr(t):(!gn(t)||t.length%2)&&er.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function fs(t,e){for(typeof t!="string"?t=kr(t):gn(t)||er.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&er.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function y4(t){let e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(xte(t)){let r=Qt(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64))):r.length===65?(e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64)),e.v=r[64]):er.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:er.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=kr(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){let i=Dte(Qt(e._vs),32);e._vs=kr(i);let s=i[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&er.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),i[0]&=127;let o=kr(i);e.s==null?e.s=o:e.s!==o&&er.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?er.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{let i=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==i&&er.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!gn(e.r)?er.throwArgumentError("signature missing or invalid r","signature",t):e.r=fs(e.r,32),e.s==null||!gn(e.s)?er.throwArgumentError("signature missing or invalid s","signature",t):e.s=fs(e.s,32);let r=Qt(e.s);r[0]>=128&&er.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);let n=kr(r);e._vs&&(gn(e._vs)||er.throwArgumentError("signature invalid _vs","signature",t),e._vs=fs(e._vs,32)),e._vs==null?e._vs=n:e._vs!==n&&er.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function HT(t){return"0x"+Tte.keccak_256(Qt(t))}var w4={exports:{}},Rte={},Bte=Object.freeze({__proto__:null,default:Rte}),Mte=Ite(Bte);(function(t){(function(e,r){function n(l,g){if(!l)throw new Error(g||"Assertion failed")}function i(l,g){l.super_=g;var y=function(){};y.prototype=g.prototype,l.prototype=new y,l.prototype.constructor=l}function s(l,g,y){if(s.isBN(l))return l;this.negative=0,this.words=null,this.length=0,this.red=null,l!==null&&((g==="le"||g==="be")&&(y=g,g=10),this._init(l||0,g||10,y||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Mte.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,g){return l.cmp(g)>0?l:g},s.min=function(l,g){return l.cmp(g)<0?l:g},s.prototype._init=function(l,g,y){if(typeof l=="number")return this._initNumber(l,g,y);if(typeof l=="object")return this._initArray(l,g,y);g==="hex"&&(g=16),n(g===(g|0)&&g>=2&&g<=36),l=l.toString().replace(/\s+/g,"");var E=0;l[0]==="-"&&(E++,this.negative=1),E=0;E-=3)_=l[E]|l[E-1]<<8|l[E-2]<<16,this.words[S]|=_<>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);else if(y==="le")for(E=0,S=0;E>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);return this._strip()};function u(l,g){var y=l.charCodeAt(g);if(y>=48&&y<=57)return y-48;if(y>=65&&y<=70)return y-55;if(y>=97&&y<=102)return y-87;n(!1,"Invalid character in "+l)}function a(l,g,y){var E=u(l,y);return y-1>=g&&(E|=u(l,y-1)<<4),E}s.prototype._parseHex=function(l,g,y){this.length=Math.ceil((l.length-g)/6),this.words=new Array(this.length);for(var E=0;E=g;E-=2)M=a(l,g,E)<=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8;else{var N=l.length-g;for(E=N%2===0?g+1:g;E=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8}this._strip()};function c(l,g,y,E){for(var S=0,_=0,M=Math.min(l.length,y),N=g;N=49?_=m-49+10:m>=17?_=m-17+10:_=m,n(m>=0&&_1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch{s.prototype.inspect=d}else s.prototype.inspect=d;function d(){return(this.red?""}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],A=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(l,g){l=l||10,g=g|0||1;var y;if(l===16||l==="hex"){y="";for(var E=0,S=0,_=0;_>>24-E&16777215,E+=2,E>=26&&(E-=26,_--),S!==0||_!==this.length-1?y=w[6-N.length]+N+y:y=N+y}for(S!==0&&(y=S.toString(16)+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var m=A[l],O=T[l];y="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var $=Y.modrn(O).toString(l);Y=Y.idivn(O),Y.isZero()?y=$+y:y=w[m-$.length]+$+y}for(this.isZero()&&(y="0"+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(l,g){return this.toArrayLike(o,l,g)}),s.prototype.toArray=function(l,g){return this.toArrayLike(Array,l,g)};var x=function(l,g){return l.allocUnsafe?l.allocUnsafe(g):new l(g)};s.prototype.toArrayLike=function(l,g,y){this._strip();var E=this.byteLength(),S=y||Math.max(1,E);n(E<=S,"byte array longer than desired length"),n(S>0,"Requested array length <= 0");var _=x(l,S),M=g==="le"?"LE":"BE";return this["_toArrayLike"+M](_,E),_},s.prototype._toArrayLikeLE=function(l,g){for(var y=0,E=0,S=0,_=0;S>8&255),y>16&255),_===6?(y>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y=0&&(l[y--]=M>>8&255),y>=0&&(l[y--]=M>>16&255),_===6?(y>=0&&(l[y--]=M>>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y>=0)for(l[y--]=E;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var g=l,y=0;return g>=4096&&(y+=13,g>>>=13),g>=64&&(y+=7,g>>>=7),g>=8&&(y+=4,g>>>=4),g>=2&&(y+=2,g>>>=2),y+g},s.prototype._zeroBits=function(l){if(l===0)return 26;var g=l,y=0;return g&8191||(y+=13,g>>>=13),g&127||(y+=7,g>>>=7),g&15||(y+=4,g>>>=4),g&3||(y+=2,g>>>=2),g&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],g=this._countBits(l);return(this.length-1)*26+g};function R(l){for(var g=new Array(l.bitLength()),y=0;y>>S&1}return g}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,g=0;gl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var g;this.length>l.length?g=l:g=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var g,y;this.length>l.length?(g=this,y=l):(g=l,y=this);for(var E=0;El.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var g=Math.ceil(l/26)|0,y=l%26;this._expand(g),y>0&&g--;for(var E=0;E0&&(this.words[E]=~this.words[E]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,g){n(typeof l=="number"&&l>=0);var y=l/26|0,E=l%26;return this._expand(y+1),g?this.words[y]=this.words[y]|1<l.length?(y=this,E=l):(y=l,E=this);for(var S=0,_=0;_>>26;for(;S!==0&&_>>26;if(this.length=y.length,S!==0)this.words[this.length]=S,this.length++;else if(y!==this)for(;_l.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var g=this.iadd(l);return l.negative=1,g._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,S;y>0?(E=this,S=l):(E=l,S=this);for(var _=0,M=0;M>26,this.words[M]=g&67108863;for(;_!==0&&M>26,this.words[M]=g&67108863;if(_===0&&M>>26,$=m&67108863,b=Math.min(O,g.length-1),j=Math.max(0,O-l.length+1);j<=b;j++){var z=O-j|0;S=l.words[z]|0,_=g.words[j]|0,M=S*_+$,Y+=M/67108864|0,$=M&67108863}y.words[O]=$|0,m=Y|0}return m!==0?y.words[O]=m|0:y.length--,y._strip()}var U=function(l,g,y){var E=l.words,S=g.words,_=y.words,M=0,N,m,O,Y=E[0]|0,$=Y&8191,b=Y>>>13,j=E[1]|0,z=j&8191,W=j>>>13,ie=E[2]|0,te=ie&8191,ee=ie>>>13,se=E[3]|0,oe=se&8191,J=se>>>13,ue=E[4]|0,wt=ue&8191,vt=ue>>>13,Ni=E[5]|0,At=Ni&8191,Et=Ni>>>13,xi=E[6]|0,bt=xi&8191,St=xi>>>13,Oi=E[7]|0,It=Oi&8191,Tt=Oi>>>13,Di=E[8]|0,Qe=Di&8191,Ke=Di>>>13,ri=E[9]|0,We=ri&8191,$e=ri>>>13,ni=S[0]|0,Ye=ni&8191,Je=ni>>>13,ii=S[1]|0,Xe=ii&8191,Ze=ii>>>13,si=S[2]|0,et=si&8191,tt=si>>>13,oi=S[3]|0,rt=oi&8191,nt=oi>>>13,ai=S[4]|0,it=ai&8191,st=ai>>>13,ui=S[5]|0,ot=ui&8191,at=ui>>>13,ci=S[6]|0,ut=ci&8191,ct=ci>>>13,li=S[7]|0,lt=li&8191,ft=li>>>13,fi=S[8]|0,ht=fi&8191,dt=fi>>>13,hi=S[9]|0,gt=hi&8191,pt=hi>>>13;y.negative=l.negative^g.negative,y.length=19,N=Math.imul($,Ye),m=Math.imul($,Je),m=m+Math.imul(b,Ye)|0,O=Math.imul(b,Je);var vn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(vn>>>26)|0,vn&=67108863,N=Math.imul(z,Ye),m=Math.imul(z,Je),m=m+Math.imul(W,Ye)|0,O=Math.imul(W,Je),N=N+Math.imul($,Xe)|0,m=m+Math.imul($,Ze)|0,m=m+Math.imul(b,Xe)|0,O=O+Math.imul(b,Ze)|0;var An=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(An>>>26)|0,An&=67108863,N=Math.imul(te,Ye),m=Math.imul(te,Je),m=m+Math.imul(ee,Ye)|0,O=Math.imul(ee,Je),N=N+Math.imul(z,Xe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(W,Xe)|0,O=O+Math.imul(W,Ze)|0,N=N+Math.imul($,et)|0,m=m+Math.imul($,tt)|0,m=m+Math.imul(b,et)|0,O=O+Math.imul(b,tt)|0;var En=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(En>>>26)|0,En&=67108863,N=Math.imul(oe,Ye),m=Math.imul(oe,Je),m=m+Math.imul(J,Ye)|0,O=Math.imul(J,Je),N=N+Math.imul(te,Xe)|0,m=m+Math.imul(te,Ze)|0,m=m+Math.imul(ee,Xe)|0,O=O+Math.imul(ee,Ze)|0,N=N+Math.imul(z,et)|0,m=m+Math.imul(z,tt)|0,m=m+Math.imul(W,et)|0,O=O+Math.imul(W,tt)|0,N=N+Math.imul($,rt)|0,m=m+Math.imul($,nt)|0,m=m+Math.imul(b,rt)|0,O=O+Math.imul(b,nt)|0;var bn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(bn>>>26)|0,bn&=67108863,N=Math.imul(wt,Ye),m=Math.imul(wt,Je),m=m+Math.imul(vt,Ye)|0,O=Math.imul(vt,Je),N=N+Math.imul(oe,Xe)|0,m=m+Math.imul(oe,Ze)|0,m=m+Math.imul(J,Xe)|0,O=O+Math.imul(J,Ze)|0,N=N+Math.imul(te,et)|0,m=m+Math.imul(te,tt)|0,m=m+Math.imul(ee,et)|0,O=O+Math.imul(ee,tt)|0,N=N+Math.imul(z,rt)|0,m=m+Math.imul(z,nt)|0,m=m+Math.imul(W,rt)|0,O=O+Math.imul(W,nt)|0,N=N+Math.imul($,it)|0,m=m+Math.imul($,st)|0,m=m+Math.imul(b,it)|0,O=O+Math.imul(b,st)|0;var Sn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Sn>>>26)|0,Sn&=67108863,N=Math.imul(At,Ye),m=Math.imul(At,Je),m=m+Math.imul(Et,Ye)|0,O=Math.imul(Et,Je),N=N+Math.imul(wt,Xe)|0,m=m+Math.imul(wt,Ze)|0,m=m+Math.imul(vt,Xe)|0,O=O+Math.imul(vt,Ze)|0,N=N+Math.imul(oe,et)|0,m=m+Math.imul(oe,tt)|0,m=m+Math.imul(J,et)|0,O=O+Math.imul(J,tt)|0,N=N+Math.imul(te,rt)|0,m=m+Math.imul(te,nt)|0,m=m+Math.imul(ee,rt)|0,O=O+Math.imul(ee,nt)|0,N=N+Math.imul(z,it)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(W,it)|0,O=O+Math.imul(W,st)|0,N=N+Math.imul($,ot)|0,m=m+Math.imul($,at)|0,m=m+Math.imul(b,ot)|0,O=O+Math.imul(b,at)|0;var In=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(In>>>26)|0,In&=67108863,N=Math.imul(bt,Ye),m=Math.imul(bt,Je),m=m+Math.imul(St,Ye)|0,O=Math.imul(St,Je),N=N+Math.imul(At,Xe)|0,m=m+Math.imul(At,Ze)|0,m=m+Math.imul(Et,Xe)|0,O=O+Math.imul(Et,Ze)|0,N=N+Math.imul(wt,et)|0,m=m+Math.imul(wt,tt)|0,m=m+Math.imul(vt,et)|0,O=O+Math.imul(vt,tt)|0,N=N+Math.imul(oe,rt)|0,m=m+Math.imul(oe,nt)|0,m=m+Math.imul(J,rt)|0,O=O+Math.imul(J,nt)|0,N=N+Math.imul(te,it)|0,m=m+Math.imul(te,st)|0,m=m+Math.imul(ee,it)|0,O=O+Math.imul(ee,st)|0,N=N+Math.imul(z,ot)|0,m=m+Math.imul(z,at)|0,m=m+Math.imul(W,ot)|0,O=O+Math.imul(W,at)|0,N=N+Math.imul($,ut)|0,m=m+Math.imul($,ct)|0,m=m+Math.imul(b,ut)|0,O=O+Math.imul(b,ct)|0;var da=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(da>>>26)|0,da&=67108863,N=Math.imul(It,Ye),m=Math.imul(It,Je),m=m+Math.imul(Tt,Ye)|0,O=Math.imul(Tt,Je),N=N+Math.imul(bt,Xe)|0,m=m+Math.imul(bt,Ze)|0,m=m+Math.imul(St,Xe)|0,O=O+Math.imul(St,Ze)|0,N=N+Math.imul(At,et)|0,m=m+Math.imul(At,tt)|0,m=m+Math.imul(Et,et)|0,O=O+Math.imul(Et,tt)|0,N=N+Math.imul(wt,rt)|0,m=m+Math.imul(wt,nt)|0,m=m+Math.imul(vt,rt)|0,O=O+Math.imul(vt,nt)|0,N=N+Math.imul(oe,it)|0,m=m+Math.imul(oe,st)|0,m=m+Math.imul(J,it)|0,O=O+Math.imul(J,st)|0,N=N+Math.imul(te,ot)|0,m=m+Math.imul(te,at)|0,m=m+Math.imul(ee,ot)|0,O=O+Math.imul(ee,at)|0,N=N+Math.imul(z,ut)|0,m=m+Math.imul(z,ct)|0,m=m+Math.imul(W,ut)|0,O=O+Math.imul(W,ct)|0,N=N+Math.imul($,lt)|0,m=m+Math.imul($,ft)|0,m=m+Math.imul(b,lt)|0,O=O+Math.imul(b,ft)|0;var ga=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ga>>>26)|0,ga&=67108863,N=Math.imul(Qe,Ye),m=Math.imul(Qe,Je),m=m+Math.imul(Ke,Ye)|0,O=Math.imul(Ke,Je),N=N+Math.imul(It,Xe)|0,m=m+Math.imul(It,Ze)|0,m=m+Math.imul(Tt,Xe)|0,O=O+Math.imul(Tt,Ze)|0,N=N+Math.imul(bt,et)|0,m=m+Math.imul(bt,tt)|0,m=m+Math.imul(St,et)|0,O=O+Math.imul(St,tt)|0,N=N+Math.imul(At,rt)|0,m=m+Math.imul(At,nt)|0,m=m+Math.imul(Et,rt)|0,O=O+Math.imul(Et,nt)|0,N=N+Math.imul(wt,it)|0,m=m+Math.imul(wt,st)|0,m=m+Math.imul(vt,it)|0,O=O+Math.imul(vt,st)|0,N=N+Math.imul(oe,ot)|0,m=m+Math.imul(oe,at)|0,m=m+Math.imul(J,ot)|0,O=O+Math.imul(J,at)|0,N=N+Math.imul(te,ut)|0,m=m+Math.imul(te,ct)|0,m=m+Math.imul(ee,ut)|0,O=O+Math.imul(ee,ct)|0,N=N+Math.imul(z,lt)|0,m=m+Math.imul(z,ft)|0,m=m+Math.imul(W,lt)|0,O=O+Math.imul(W,ft)|0,N=N+Math.imul($,ht)|0,m=m+Math.imul($,dt)|0,m=m+Math.imul(b,ht)|0,O=O+Math.imul(b,dt)|0;var pa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pa>>>26)|0,pa&=67108863,N=Math.imul(We,Ye),m=Math.imul(We,Je),m=m+Math.imul($e,Ye)|0,O=Math.imul($e,Je),N=N+Math.imul(Qe,Xe)|0,m=m+Math.imul(Qe,Ze)|0,m=m+Math.imul(Ke,Xe)|0,O=O+Math.imul(Ke,Ze)|0,N=N+Math.imul(It,et)|0,m=m+Math.imul(It,tt)|0,m=m+Math.imul(Tt,et)|0,O=O+Math.imul(Tt,tt)|0,N=N+Math.imul(bt,rt)|0,m=m+Math.imul(bt,nt)|0,m=m+Math.imul(St,rt)|0,O=O+Math.imul(St,nt)|0,N=N+Math.imul(At,it)|0,m=m+Math.imul(At,st)|0,m=m+Math.imul(Et,it)|0,O=O+Math.imul(Et,st)|0,N=N+Math.imul(wt,ot)|0,m=m+Math.imul(wt,at)|0,m=m+Math.imul(vt,ot)|0,O=O+Math.imul(vt,at)|0,N=N+Math.imul(oe,ut)|0,m=m+Math.imul(oe,ct)|0,m=m+Math.imul(J,ut)|0,O=O+Math.imul(J,ct)|0,N=N+Math.imul(te,lt)|0,m=m+Math.imul(te,ft)|0,m=m+Math.imul(ee,lt)|0,O=O+Math.imul(ee,ft)|0,N=N+Math.imul(z,ht)|0,m=m+Math.imul(z,dt)|0,m=m+Math.imul(W,ht)|0,O=O+Math.imul(W,dt)|0,N=N+Math.imul($,gt)|0,m=m+Math.imul($,pt)|0,m=m+Math.imul(b,gt)|0,O=O+Math.imul(b,pt)|0;var ma=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ma>>>26)|0,ma&=67108863,N=Math.imul(We,Xe),m=Math.imul(We,Ze),m=m+Math.imul($e,Xe)|0,O=Math.imul($e,Ze),N=N+Math.imul(Qe,et)|0,m=m+Math.imul(Qe,tt)|0,m=m+Math.imul(Ke,et)|0,O=O+Math.imul(Ke,tt)|0,N=N+Math.imul(It,rt)|0,m=m+Math.imul(It,nt)|0,m=m+Math.imul(Tt,rt)|0,O=O+Math.imul(Tt,nt)|0,N=N+Math.imul(bt,it)|0,m=m+Math.imul(bt,st)|0,m=m+Math.imul(St,it)|0,O=O+Math.imul(St,st)|0,N=N+Math.imul(At,ot)|0,m=m+Math.imul(At,at)|0,m=m+Math.imul(Et,ot)|0,O=O+Math.imul(Et,at)|0,N=N+Math.imul(wt,ut)|0,m=m+Math.imul(wt,ct)|0,m=m+Math.imul(vt,ut)|0,O=O+Math.imul(vt,ct)|0,N=N+Math.imul(oe,lt)|0,m=m+Math.imul(oe,ft)|0,m=m+Math.imul(J,lt)|0,O=O+Math.imul(J,ft)|0,N=N+Math.imul(te,ht)|0,m=m+Math.imul(te,dt)|0,m=m+Math.imul(ee,ht)|0,O=O+Math.imul(ee,dt)|0,N=N+Math.imul(z,gt)|0,m=m+Math.imul(z,pt)|0,m=m+Math.imul(W,gt)|0,O=O+Math.imul(W,pt)|0;var ya=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ya>>>26)|0,ya&=67108863,N=Math.imul(We,et),m=Math.imul(We,tt),m=m+Math.imul($e,et)|0,O=Math.imul($e,tt),N=N+Math.imul(Qe,rt)|0,m=m+Math.imul(Qe,nt)|0,m=m+Math.imul(Ke,rt)|0,O=O+Math.imul(Ke,nt)|0,N=N+Math.imul(It,it)|0,m=m+Math.imul(It,st)|0,m=m+Math.imul(Tt,it)|0,O=O+Math.imul(Tt,st)|0,N=N+Math.imul(bt,ot)|0,m=m+Math.imul(bt,at)|0,m=m+Math.imul(St,ot)|0,O=O+Math.imul(St,at)|0,N=N+Math.imul(At,ut)|0,m=m+Math.imul(At,ct)|0,m=m+Math.imul(Et,ut)|0,O=O+Math.imul(Et,ct)|0,N=N+Math.imul(wt,lt)|0,m=m+Math.imul(wt,ft)|0,m=m+Math.imul(vt,lt)|0,O=O+Math.imul(vt,ft)|0,N=N+Math.imul(oe,ht)|0,m=m+Math.imul(oe,dt)|0,m=m+Math.imul(J,ht)|0,O=O+Math.imul(J,dt)|0,N=N+Math.imul(te,gt)|0,m=m+Math.imul(te,pt)|0,m=m+Math.imul(ee,gt)|0,O=O+Math.imul(ee,pt)|0;var wa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(wa>>>26)|0,wa&=67108863,N=Math.imul(We,rt),m=Math.imul(We,nt),m=m+Math.imul($e,rt)|0,O=Math.imul($e,nt),N=N+Math.imul(Qe,it)|0,m=m+Math.imul(Qe,st)|0,m=m+Math.imul(Ke,it)|0,O=O+Math.imul(Ke,st)|0,N=N+Math.imul(It,ot)|0,m=m+Math.imul(It,at)|0,m=m+Math.imul(Tt,ot)|0,O=O+Math.imul(Tt,at)|0,N=N+Math.imul(bt,ut)|0,m=m+Math.imul(bt,ct)|0,m=m+Math.imul(St,ut)|0,O=O+Math.imul(St,ct)|0,N=N+Math.imul(At,lt)|0,m=m+Math.imul(At,ft)|0,m=m+Math.imul(Et,lt)|0,O=O+Math.imul(Et,ft)|0,N=N+Math.imul(wt,ht)|0,m=m+Math.imul(wt,dt)|0,m=m+Math.imul(vt,ht)|0,O=O+Math.imul(vt,dt)|0,N=N+Math.imul(oe,gt)|0,m=m+Math.imul(oe,pt)|0,m=m+Math.imul(J,gt)|0,O=O+Math.imul(J,pt)|0;var va=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(va>>>26)|0,va&=67108863,N=Math.imul(We,it),m=Math.imul(We,st),m=m+Math.imul($e,it)|0,O=Math.imul($e,st),N=N+Math.imul(Qe,ot)|0,m=m+Math.imul(Qe,at)|0,m=m+Math.imul(Ke,ot)|0,O=O+Math.imul(Ke,at)|0,N=N+Math.imul(It,ut)|0,m=m+Math.imul(It,ct)|0,m=m+Math.imul(Tt,ut)|0,O=O+Math.imul(Tt,ct)|0,N=N+Math.imul(bt,lt)|0,m=m+Math.imul(bt,ft)|0,m=m+Math.imul(St,lt)|0,O=O+Math.imul(St,ft)|0,N=N+Math.imul(At,ht)|0,m=m+Math.imul(At,dt)|0,m=m+Math.imul(Et,ht)|0,O=O+Math.imul(Et,dt)|0,N=N+Math.imul(wt,gt)|0,m=m+Math.imul(wt,pt)|0,m=m+Math.imul(vt,gt)|0,O=O+Math.imul(vt,pt)|0;var Aa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,N=Math.imul(We,ot),m=Math.imul(We,at),m=m+Math.imul($e,ot)|0,O=Math.imul($e,at),N=N+Math.imul(Qe,ut)|0,m=m+Math.imul(Qe,ct)|0,m=m+Math.imul(Ke,ut)|0,O=O+Math.imul(Ke,ct)|0,N=N+Math.imul(It,lt)|0,m=m+Math.imul(It,ft)|0,m=m+Math.imul(Tt,lt)|0,O=O+Math.imul(Tt,ft)|0,N=N+Math.imul(bt,ht)|0,m=m+Math.imul(bt,dt)|0,m=m+Math.imul(St,ht)|0,O=O+Math.imul(St,dt)|0,N=N+Math.imul(At,gt)|0,m=m+Math.imul(At,pt)|0,m=m+Math.imul(Et,gt)|0,O=O+Math.imul(Et,pt)|0;var Ea=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Ea>>>26)|0,Ea&=67108863,N=Math.imul(We,ut),m=Math.imul(We,ct),m=m+Math.imul($e,ut)|0,O=Math.imul($e,ct),N=N+Math.imul(Qe,lt)|0,m=m+Math.imul(Qe,ft)|0,m=m+Math.imul(Ke,lt)|0,O=O+Math.imul(Ke,ft)|0,N=N+Math.imul(It,ht)|0,m=m+Math.imul(It,dt)|0,m=m+Math.imul(Tt,ht)|0,O=O+Math.imul(Tt,dt)|0,N=N+Math.imul(bt,gt)|0,m=m+Math.imul(bt,pt)|0,m=m+Math.imul(St,gt)|0,O=O+Math.imul(St,pt)|0;var hw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(hw>>>26)|0,hw&=67108863,N=Math.imul(We,lt),m=Math.imul(We,ft),m=m+Math.imul($e,lt)|0,O=Math.imul($e,ft),N=N+Math.imul(Qe,ht)|0,m=m+Math.imul(Qe,dt)|0,m=m+Math.imul(Ke,ht)|0,O=O+Math.imul(Ke,dt)|0,N=N+Math.imul(It,gt)|0,m=m+Math.imul(It,pt)|0,m=m+Math.imul(Tt,gt)|0,O=O+Math.imul(Tt,pt)|0;var dw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(dw>>>26)|0,dw&=67108863,N=Math.imul(We,ht),m=Math.imul(We,dt),m=m+Math.imul($e,ht)|0,O=Math.imul($e,dt),N=N+Math.imul(Qe,gt)|0,m=m+Math.imul(Qe,pt)|0,m=m+Math.imul(Ke,gt)|0,O=O+Math.imul(Ke,pt)|0;var gw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(gw>>>26)|0,gw&=67108863,N=Math.imul(We,gt),m=Math.imul(We,pt),m=m+Math.imul($e,gt)|0,O=Math.imul($e,pt);var pw=(M+N|0)+((m&8191)<<13)|0;return M=(O+(m>>>13)|0)+(pw>>>26)|0,pw&=67108863,_[0]=vn,_[1]=An,_[2]=En,_[3]=bn,_[4]=Sn,_[5]=In,_[6]=da,_[7]=ga,_[8]=pa,_[9]=ma,_[10]=ya,_[11]=wa,_[12]=va,_[13]=Aa,_[14]=Ea,_[15]=hw,_[16]=dw,_[17]=gw,_[18]=pw,M!==0&&(_[19]=M,y.length++),y};Math.imul||(U=V);function Q(l,g,y){y.negative=g.negative^l.negative,y.length=l.length+g.length;for(var E=0,S=0,_=0;_>>26)|0,S+=M>>>26,M&=67108863}y.words[_]=N,E=M,M=S}return E!==0?y.words[_]=E:y.length--,y._strip()}function L(l,g,y){return Q(l,g,y)}s.prototype.mulTo=function(l,g){var y,E=this.length+l.length;return this.length===10&&l.length===10?y=U(this,l,g):E<63?y=V(this,l,g):E<1024?y=Q(this,l,g):y=L(this,l,g),y},s.prototype.mul=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),this.mulTo(l,g)},s.prototype.mulf=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),L(this,l,g)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var g=l<0;g&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var y=0,E=0;E>=26,y+=S/67108864|0,y+=_>>>26,this.words[E]=_&67108863}return y!==0&&(this.words[E]=y,this.length++),g?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var g=R(l);if(g.length===0)return new s(1);for(var y=this,E=0;E=0);var g=l%26,y=(l-g)/26,E=67108863>>>26-g<<26-g,S;if(g!==0){var _=0;for(S=0;S>>26-g}_&&(this.words[S]=_,this.length++)}if(y!==0){for(S=this.length-1;S>=0;S--)this.words[S+y]=this.words[S];for(S=0;S=0);var E;g?E=(g-g%26)/26:E=0;var S=l%26,_=Math.min((l-S)/26,this.length),M=67108863^67108863>>>S<_)for(this.length-=_,m=0;m=0&&(O!==0||m>=E);m--){var Y=this.words[m]|0;this.words[m]=O<<26-S|Y>>>S,O=Y&M}return N&&O!==0&&(N.words[N.length++]=O),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,g,y){return n(this.negative===0),this.iushrn(l,g,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var g=l%26,y=(l-g)/26,E=1<=0);var g=l%26,y=(l-g)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(g!==0&&y++,this.length=Math.min(y,this.length),g!==0){var E=67108863^67108863>>>g<=67108864;g++)this.words[g]-=67108864,g===this.length-1?this.words[g+1]=1:this.words[g+1]++;return this.length=Math.max(this.length,g+1),this},s.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var g=0;g>26)-(N/67108864|0),this.words[S+y]=_&67108863}for(;S>26,this.words[S+y]=_&67108863;if(M===0)return this._strip();for(n(M===-1),M=0,S=0;S>26,this.words[S]=_&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,g){var y=this.length-l.length,E=this.clone(),S=l,_=S.words[S.length-1]|0,M=this._countBits(_);y=26-M,y!==0&&(S=S.ushln(y),E.iushln(y),_=S.words[S.length-1]|0);var N=E.length-S.length,m;if(g!=="mod"){m=new s(null),m.length=N+1,m.words=new Array(m.length);for(var O=0;O=0;$--){var b=(E.words[S.length+$]|0)*67108864+(E.words[S.length+$-1]|0);for(b=Math.min(b/_|0,67108863),E._ishlnsubmul(S,b,$);E.negative!==0;)b--,E.negative=0,E._ishlnsubmul(S,1,$),E.isZero()||(E.negative^=1);m&&(m.words[$]=b)}return m&&m._strip(),E._strip(),g!=="div"&&y!==0&&E.iushrn(y),{div:m||null,mod:E}},s.prototype.divmod=function(l,g,y){if(n(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,S,_;return this.negative!==0&&l.negative===0?(_=this.neg().divmod(l,g),g!=="mod"&&(E=_.div.neg()),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.iadd(l)),{div:E,mod:S}):this.negative===0&&l.negative!==0?(_=this.divmod(l.neg(),g),g!=="mod"&&(E=_.div.neg()),{div:E,mod:_.mod}):this.negative&l.negative?(_=this.neg().divmod(l.neg(),g),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.isub(l)),{div:_.div,mod:S}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?g==="div"?{div:this.divn(l.words[0]),mod:null}:g==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,g)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var g=this.divmod(l);if(g.mod.isZero())return g.div;var y=g.div.negative!==0?g.mod.isub(l):g.mod,E=l.ushrn(1),S=l.andln(1),_=y.cmp(E);return _<0||S===1&&_===0?g.div:g.div.negative!==0?g.div.isubn(1):g.div.iaddn(1)},s.prototype.modrn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=(1<<26)%l,E=0,S=this.length-1;S>=0;S--)E=(y*E+(this.words[S]|0))%l;return g?-E:E},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=0,E=this.length-1;E>=0;E--){var S=(this.words[E]|0)+y*67108864;this.words[E]=S/l|0,y=S%l}return this._strip(),g?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=new s(0),M=new s(1),N=0;g.isEven()&&y.isEven();)g.iushrn(1),y.iushrn(1),++N;for(var m=y.clone(),O=g.clone();!g.isZero();){for(var Y=0,$=1;!(g.words[0]&$)&&Y<26;++Y,$<<=1);if(Y>0)for(g.iushrn(Y);Y-- >0;)(E.isOdd()||S.isOdd())&&(E.iadd(m),S.isub(O)),E.iushrn(1),S.iushrn(1);for(var b=0,j=1;!(y.words[0]&j)&&b<26;++b,j<<=1);if(b>0)for(y.iushrn(b);b-- >0;)(_.isOdd()||M.isOdd())&&(_.iadd(m),M.isub(O)),_.iushrn(1),M.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(_),S.isub(M)):(y.isub(g),_.isub(E),M.isub(S))}return{a:_,b:M,gcd:y.iushln(N)}},s.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=y.clone();g.cmpn(1)>0&&y.cmpn(1)>0;){for(var M=0,N=1;!(g.words[0]&N)&&M<26;++M,N<<=1);if(M>0)for(g.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(_),E.iushrn(1);for(var m=0,O=1;!(y.words[0]&O)&&m<26;++m,O<<=1);if(m>0)for(y.iushrn(m);m-- >0;)S.isOdd()&&S.iadd(_),S.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(S)):(y.isub(g),S.isub(E))}var Y;return g.cmpn(1)===0?Y=E:Y=S,Y.cmpn(0)<0&&Y.iadd(l),Y},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var g=this.clone(),y=l.clone();g.negative=0,y.negative=0;for(var E=0;g.isEven()&&y.isEven();E++)g.iushrn(1),y.iushrn(1);do{for(;g.isEven();)g.iushrn(1);for(;y.isEven();)y.iushrn(1);var S=g.cmp(y);if(S<0){var _=g;g=y,y=_}else if(S===0||y.cmpn(1)===0)break;g.isub(y)}while(!0);return y.iushln(E)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){n(typeof l=="number");var g=l%26,y=(l-g)/26,E=1<>>26,M&=67108863,this.words[_]=M}return S!==0&&(this.words[_]=S,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var g=l<0;if(this.negative!==0&&!g)return-1;if(this.negative===0&&g)return 1;this._strip();var y;if(this.length>1)y=1;else{g&&(l=-l),n(l<=67108863,"Number is too big");var E=this.words[0]|0;y=E===l?0:El.length)return 1;if(this.length=0;y--){var E=this.words[y]|0,S=l.words[y]|0;if(E!==S){ES&&(g=1);break}}return g},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new F(l)},s.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var k={k256:null,p224:null,p192:null,p25519:null};function H(l,g){this.name=l,this.p=new s(g,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},H.prototype.ireduce=function(l){var g=l,y;do this.split(g,this.tmp),g=this.imulK(g),g=g.iadd(this.tmp),y=g.bitLength();while(y>this.n);var E=y0?g.isub(this.p):g.strip!==void 0?g.strip():g._strip(),g},H.prototype.split=function(l,g){l.iushrn(this.n,0,g)},H.prototype.imulK=function(l){return l.imul(this.k)};function q(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(q,H),q.prototype.split=function(l,g){for(var y=4194303,E=Math.min(l.length,9),S=0;S>>22,_=M}_>>>=22,l.words[S-10]=_,_===0&&l.length>10?l.length-=10:l.length-=9},q.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var g=0,y=0;y>>=26,l.words[y]=S,g=E}return g!==0&&(l.words[l.length++]=g),l},s._prime=function(l){if(k[l])return k[l];var g;if(l==="k256")g=new q;else if(l==="p224")g=new v;else if(l==="p192")g=new C;else if(l==="p25519")g=new D;else throw new Error("Unknown prime "+l);return k[l]=g,g};function F(l){if(typeof l=="string"){var g=s._prime(l);this.m=g.p,this.prime=g}else n(l.gtn(1),"modulus must be greater than 1"),this.m=l,this.prime=null}F.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},F.prototype._verify2=function(l,g){n((l.negative|g.negative)===0,"red works only with positives"),n(l.red&&l.red===g.red,"red works only with red numbers")},F.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(f(l,l.umod(this.m)._forceRed(this)),l)},F.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},F.prototype.add=function(l,g){this._verify2(l,g);var y=l.add(g);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},F.prototype.iadd=function(l,g){this._verify2(l,g);var y=l.iadd(g);return y.cmp(this.m)>=0&&y.isub(this.m),y},F.prototype.sub=function(l,g){this._verify2(l,g);var y=l.sub(g);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},F.prototype.isub=function(l,g){this._verify2(l,g);var y=l.isub(g);return y.cmpn(0)<0&&y.iadd(this.m),y},F.prototype.shl=function(l,g){return this._verify1(l),this.imod(l.ushln(g))},F.prototype.imul=function(l,g){return this._verify2(l,g),this.imod(l.imul(g))},F.prototype.mul=function(l,g){return this._verify2(l,g),this.imod(l.mul(g))},F.prototype.isqr=function(l){return this.imul(l,l.clone())},F.prototype.sqr=function(l){return this.mul(l,l)},F.prototype.sqrt=function(l){if(l.isZero())return l.clone();var g=this.m.andln(3);if(n(g%2===1),g===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var E=this.m.subn(1),S=0;!E.isZero()&&E.andln(1)===0;)S++,E.iushrn(1);n(!E.isZero());var _=new s(1).toRed(this),M=_.redNeg(),N=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,N).cmp(M)!==0;)m.redIAdd(M);for(var O=this.pow(m,E),Y=this.pow(l,E.addn(1).iushrn(1)),$=this.pow(l,E),b=S;$.cmp(_)!==0;){for(var j=$,z=0;j.cmp(_)!==0;z++)j=j.redSqr();n(z=0;S--){for(var O=g.words[S],Y=m-1;Y>=0;Y--){var $=O>>Y&1;if(_!==E[0]&&(_=this.sqr(_)),$===0&&M===0){N=0;continue}M<<=1,M|=$,N++,!(N!==y&&(S!==0||Y!==0))&&(_=this.mul(_,E[M]),N=0,M=0)}m=26}return _},F.prototype.convertTo=function(l){var g=l.umod(this.m);return g===l?g.clone():g},F.prototype.convertFrom=function(l){var g=l.clone();return g.red=null,g},s.mont=function(l){return new P(l)};function P(l){F.call(this,l),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(P,F),P.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},P.prototype.convertFrom=function(l){var g=this.imod(l.mul(this.rinv));return g.red=null,g},P.prototype.imul=function(l,g){if(l.isZero()||g.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.mul=function(l,g){if(l.isZero()||g.isZero())return new s(0)._forceRed(this);var y=l.mul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.invm=function(l){var g=this.imod(l._invmp(this.m).mul(this.r2));return g._forceRed(this)}})(t,g4)})(w4);var Se=w4.exports,v4="bignumber/5.7.0",Jm=Se.BN,Ks=new kt(v4),hT={},TM=9007199254740991;function Lte(t){return t!=null&&(Cr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||gn(t)||typeof t=="bigint"||ul(t))}var _M=!1,Cr=class t{constructor(e,r){e!==hT&&Ks.throwError("cannot call constructor directly; use BigNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return sn(De(this).fromTwos(e))}toTwos(e){return sn(De(this).toTwos(e))}abs(){return this._hex[0]==="-"?t.from(this._hex.substring(1)):this}add(e){return sn(De(this).add(De(e)))}sub(e){return sn(De(this).sub(De(e)))}div(e){return t.from(e).isZero()&&Kn("division-by-zero","div"),sn(De(this).div(De(e)))}mul(e){return sn(De(this).mul(De(e)))}mod(e){let r=De(e);return r.isNeg()&&Kn("division-by-zero","mod"),sn(De(this).umod(r))}pow(e){let r=De(e);return r.isNeg()&&Kn("negative-power","pow"),sn(De(this).pow(r))}and(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","and"),sn(De(this).and(r))}or(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","or"),sn(De(this).or(r))}xor(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","xor"),sn(De(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Kn("negative-width","mask"),sn(De(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Kn("negative-width","shl"),sn(De(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Kn("negative-width","shr"),sn(De(this).shrn(e))}eq(e){return De(this).eq(De(e))}lt(e){return De(this).lt(De(e))}lte(e){return De(this).lte(De(e))}gt(e){return De(this).gt(De(e))}gte(e){return De(this).gte(De(e))}isNegative(){return this._hex[0]==="-"}isZero(){return De(this).isZero()}toNumber(){try{return De(this).toNumber()}catch{Kn("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ks.throwError("this platform does not support BigInt",kt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?_M||(_M=!0,Ks.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ks.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",kt.errors.UNEXPECTED_ARGUMENT,{}):Ks.throwError("BigNumber.toString does not accept parameters",kt.errors.UNEXPECTED_ARGUMENT,{})),De(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof t)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new t(hT,Vh(e)):e.match(/^-?[0-9]+$/)?new t(hT,Vh(new Jm(e))):Ks.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Kn("underflow","BigNumber.from",e),(e>=TM||e<=-TM)&&Kn("overflow","BigNumber.from",e),t.from(String(e));let r=e;if(typeof r=="bigint")return t.from(r.toString());if(ul(r))return t.from(kr(r));if(r)if(r.toHexString){let n=r.toHexString();if(typeof n=="string")return t.from(n)}else{let n=r._hex;if(n==null&&r.type==="BigNumber"&&(n=r.hex),typeof n=="string"&&(gn(n)||n[0]==="-"&&gn(n.substring(1))))return t.from(n)}return Ks.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}};function Vh(t){if(typeof t!="string")return Vh(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ks.throwArgumentError("invalid hex","value",t),t=Vh(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function sn(t){return Cr.from(Vh(t))}function De(t){let e=Cr.from(t).toHexString();return e[0]==="-"?new Jm("-"+e.substring(3),16):new Jm(e.substring(2),16)}function Kn(t,e,r){let n={fault:t,operation:e};return r!=null&&(n.value=r),Ks.throwError(t,kt.errors.NUMERIC_FAULT,n)}function Fte(t){return new Jm(t,36).toString(16)}var Hr=new kt(v4),Fh={},A4=Cr.from(0),E4=Cr.from(-1);function b4(t,e,r,n){let i={fault:e,operation:r};return n!==void 0&&(i.value=n),Hr.throwError(t,kt.errors.NUMERIC_FAULT,i)}var Uh="0";for(;Uh.length<256;)Uh+=Uh;function GT(t){if(typeof t!="number")try{t=Cr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+Uh.substring(0,t):Hr.throwArgumentError("invalid decimal size","decimals",t)}function dT(t,e){e==null&&(e=0);let r=GT(e);t=Cr.from(t);let n=t.lt(A4);n&&(t=t.mul(E4));let i=t.mod(r).toString();for(;i.length2&&Hr.throwArgumentError("too many decimal points","value",t);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");o[o.length-1]==="0";)o=o.substring(0,o.length-1);for(o.length>r.length-1&&b4("fractional component exceeds decimals","underflow","parseFixed"),o===""&&(o="0");o.lengthe[o]==null?a:(typeof e[o]!==u&&Hr.throwArgumentError("invalid fixed format ("+o+" not "+u+")","format."+o,e[o]),e[o]);r=s("signed","boolean",r),n=s("width","number",n),i=s("decimals","number",i)}return n%8&&Hr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),i>80&&Hr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",i),new t(Fh,r,n,i)}},Xm=class t{constructor(e,r,n,i){e!==Fh&&Hr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=r,this._value=n,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Hr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.add(n),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.sub(n),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return this.isNegative()&&n&&(r=r.subUnsafe(CM.toFormat(r.format))),r}ceiling(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return!this.isNegative()&&n&&(r=r.addUnsafe(CM.toFormat(r.format))),r}round(e){e==null&&(e=0);let r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&Hr.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;let n=t.from("1"+Uh.substring(0,e),this.format),i=Ute.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(i).floor().divUnsafe(n)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Hr.throwArgumentError("invalid byte width","width",e);let r=Cr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return fs(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return t.fromString(this._value,e)}static fromValue(e,r,n){return n==null&&r!=null&&!Lte(r)&&(n=r,r=null),r==null&&(r=0),n==null&&(n="fixed"),t.fromString(dT(e,r),qh.from(n))}static fromString(e,r){r==null&&(r="fixed");let n=qh.from(r),i=Qs(e,n.decimals);!n.signed&&i.lt(A4)&&b4("unsigned value cannot be negative","overflow","value",e);let s=null;n.signed?s=i.toTwos(n.width).toHexString():(s=i.toHexString(),s=fs(s,n.width/8));let o=dT(i,n.decimals);return new t(Fh,s,o,n)}static fromBytes(e,r){r==null&&(r="fixed");let n=qh.from(r);if(Qt(e).length>n.width/8)throw new Error("overflow");let i=Cr.from(e);n.signed&&(i=i.fromTwos(n.width));let s=i.toTwos((n.signed?0:1)+n.width).toHexString(),o=dT(i,n.decimals);return new t(Fh,s,o,n)}static from(e,r){if(typeof e=="string")return t.fromString(e,r);if(ul(e))return t.fromBytes(e,r);try{return t.fromValue(e,0,r)}catch(n){if(n.code!==kt.errors.INVALID_ARGUMENT)throw n}return Hr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}},CM=Xm.from(1),Ute=Xm.from("0.5"),qte="strings/5.7.0",S4=new kt(qte),Zm;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(Zm||(Zm={}));var rl;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(rl||(rl={}));function Vte(t,e,r,n,i){return S4.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function I4(t,e,r,n,i){if(t===rl.BAD_PREFIX||t===rl.UNEXPECTED_CONTINUE){let s=0;for(let o=e+1;o>6===2;o++)s++;return s}return t===rl.OVERRUN?r.length-e-1:0}function kte(t,e,r,n,i){return t===rl.OVERLONG?(n.push(i),0):(n.push(65533),I4(t,e,r))}Object.freeze({error:Vte,ignore:I4,replace:kte});function gT(t,e=Zm.current){e!=Zm.current&&(S4.checkNormalize(),t=t.normalize(e));let r=[];for(let n=0;n>6|192),r.push(i&63|128);else if((i&64512)==55296){n++;let s=t.charCodeAt(n);if(n>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");let o=65536+((i&1023)<<10)+(s&1023);r.push(o>>18|240),r.push(o>>12&63|128),r.push(o>>6&63|128),r.push(o&63|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(i&63|128)}return Qt(r)}function Hte(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r{let s=i.split(":");r+=parseInt(s[0],16),n[r]=e(s[1])}),n}function NM(t){let e=0;return t.split(",").map(r=>{let n=r.split("-");n.length===1?n[1]="0":n[1]===""&&(n[1]="1");let i=e+parseInt(n[0],16);return e=parseInt(n[1],16),{l:i,h:e}})}NM("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),pT("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),pT("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),pT("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",Hte),NM("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");var T4="hash/5.7.0";function Gte(t){t=atob(t);let e=[];for(let r=0;r0&&Array.isArray(u)?i(u,o-1):r.push(u)})};return i(t,e),r}function jte(t){let e={};for(let r=0;r>--a&1}let d=31,w=Math.pow(2,d),A=w>>>1,T=A>>1,x=w-1,R=0;for(let k=0;k1;){let D=H+q>>>1;k>>1|f(),v=v<<1^A,C=(C^A)<<1|A|1;U=v,Q=1+C-v}let L=n-4;return V.map(k=>{switch(k-L){case 3:return L+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return L+256+(t[u++]<<8|t[u++]);case 1:return L+t[u++];default:return k-1}})}function Qte(t){let e=0;return()=>t[e++]}function Kte(t){return Qte(zte(t))}function Wte(t){return t&1?~t>>1:t>>1}function $te(t,e){let r=Array(t);for(let n=0;ne[o]):r}function Jte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(Zte(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(ere(r,t))}return jte(_4(e))}function Xte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function C4(t,e,r){let n=Array(t).fill(void 0).map(()=>[]);for(let i=0;in[o].push(s));return n}function Zte(t,e){let r=1+e(),n=e(),i=Xte(e),s=C4(i.length,1+t,e);return _4(s.map((o,u)=>{let a=o[0],c=o.slice(1);return Array(i[u]).fill(void 0).map((f,d)=>{let w=d*n;return[a+d*r,c.map(A=>A+w)]})}))}function ere(t,e){let r=1+e();return C4(r,1+t,e).map(n=>[n[0],n.slice(1)])}function tre(t){let e=ey(t).sort((n,i)=>n-i);return r();function r(){let n=[];for(;;){let c=ey(t,e);if(c.length==0)break;n.push({set:new Set(c),node:r()})}n.sort((c,f)=>f.set.size-c.set.size);let i=t(),s=i%3;i=i/3|0;let o=!!(i&1);i>>=1;let u=i==1,a=i==2;return{branches:n,valid:s,fe0f:o,save:u,check:a}}}function rre(){return Kte(Gte("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}var km=rre();new Set(ey(km)),new Set(ey(km)),Jte(km),tre(km),new kt(T4);var nre=new Uint8Array(32);nre.fill(0);var ire=`Ethereum Signed Message: +`;function N4(t){return typeof t=="string"&&(t=gT(t)),HT(Ote([gT(ire),gT(String(t.length)),t]))}var sre="rlp/5.7.0";new kt(sre);var ore="address/5.7.0",Lh=new kt(ore);function OM(t){gn(t,20)||Lh.throwArgumentError("invalid address","address",t),t=t.toLowerCase();let e=t.substring(2).split(""),r=new Uint8Array(40);for(let i=0;i<40;i++)r[i]=e[i].charCodeAt(0);let n=Qt(HT(r));for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&(e[i]=e[i].toUpperCase()),(n[i>>1]&15)>=8&&(e[i+1]=e[i+1].toUpperCase());return"0x"+e.join("")}var are=9007199254740991;function ure(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}var jT={};for(let t=0;t<10;t++)jT[String(t)]=String(t);for(let t=0;t<26;t++)jT[String.fromCharCode(65+t)]=String(10+t);var DM=Math.floor(ure(are));function cre(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(n=>jT[n]).join("");for(;e.length>=DM;){let n=e.substring(0,DM);e=parseInt(n,10)%97+e.substring(n.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function lre(t){let e=null;if(typeof t!="string"&&Lh.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=OM(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&Lh.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==cre(t)&&Lh.throwArgumentError("bad icap checksum","address",t),e=Fte(t.substring(4));e.length<40;)e="0"+e;e=OM("0x"+e)}else Lh.throwArgumentError("invalid address","address",t);return e}var fre="properties/5.7.0";new kt(fre);function Rh(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new kt(T4);var hre=new Uint8Array(32);hre.fill(0),Cr.from(-1);var dre=Cr.from(0),gre=Cr.from(1);Cr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fs(gre.toHexString(),32),fs(dre.toHexString(),32);var os={},Pe={},Gh=x4;function x4(t,e){if(!t)throw new Error(e||"Assertion failed")}x4.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var CT={exports:{}};typeof Object.create=="function"?CT.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:CT.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var pre=Gh,mre=CT.exports;Pe.inherits=mre;function yre(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function wre(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),i=0;i>6|192,r[n++]=s&63|128):yre(t,i)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023),r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128)}else for(i=0;i>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Pe.htonl=O4;function Are(t,e){for(var r="",n=0;n>>0}return s}Pe.join32=Ere;function bre(t,e){for(var r=new Array(t.length*4),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=s&255):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=s&255)}return r}Pe.split32=bre;function Sre(t,e){return t>>>e|t<<32-e}Pe.rotr32=Sre;function Ire(t,e){return t<>>32-e}Pe.rotl32=Ire;function Tre(t,e){return t+e>>>0}Pe.sum32=Tre;function _re(t,e,r){return t+e+r>>>0}Pe.sum32_3=_re;function Cre(t,e,r,n){return t+e+r+n>>>0}Pe.sum32_4=Cre;function Nre(t,e,r,n,i){return t+e+r+n+i>>>0}Pe.sum32_5=Nre;function xre(t,e,r,n){var i=t[e],s=t[e+1],o=n+s>>>0,u=(o>>0,t[e+1]=o}Pe.sum64=xre;function Ore(t,e,r,n){var i=e+n>>>0,s=(i>>0}Pe.sum64_hi=Ore;function Dre(t,e,r,n){var i=e+n;return i>>>0}Pe.sum64_lo=Dre;function Pre(t,e,r,n,i,s,o,u){var a=0,c=e;c=c+n>>>0,a+=c>>0,a+=c>>0,a+=c>>0}Pe.sum64_4_hi=Pre;function Rre(t,e,r,n,i,s,o,u){var a=e+n+s+u;return a>>>0}Pe.sum64_4_lo=Rre;function Bre(t,e,r,n,i,s,o,u,a,c){var f=0,d=e;d=d+n>>>0,f+=d>>0,f+=d>>0,f+=d>>0,f+=d>>0}Pe.sum64_5_hi=Bre;function Mre(t,e,r,n,i,s,o,u,a,c){var f=e+n+s+u+c;return f>>>0}Pe.sum64_5_lo=Mre;function Lre(t,e,r){var n=e<<32-r|t>>>r;return n>>>0}Pe.rotr64_hi=Lre;function Fre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.rotr64_lo=Fre;function Ure(t,e,r){return t>>>r}Pe.shr64_hi=Ure;function qre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.shr64_lo=qre;var cl={},PM=Pe,Vre=Gh;function Hm(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}cl.BlockHash=Hm,Hm.prototype.update=function(t,e){if(t=PM.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=PM.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=t&255}else for(n[i++]=t&255,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s>>3}ms.g0_256=zre;function Qre(t){return hs(t,17)^hs(t,19)^t>>>10}ms.g1_256=Qre;var sl=Pe,Kre=cl,Wre=ms,mT=sl.rotl32,Bh=sl.sum32,$re=sl.sum32_5,Yre=Wre.ft_1,L4=Kre.BlockHash,Jre=[1518500249,1859775393,2400959708,3395469782];function us(){if(!(this instanceof us))return new us;L4.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}sl.inherits(us,L4);var Xre=us;us.blockSize=512,us.outSize=160,us.hmacStrength=80,us.padLength=64,us.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=new this.Hash().update(t).digest()),qne(t.length<=this.blockSize);for(var e=t.length;e>8,w=f&255;d?a.push(d,w):a.push(w)}return a}r.toArray=n;function i(o){return o.length===1?"0"+o:o}r.zero2=i;function s(o){for(var u="",a=0;a(w>>1)-1?x=(w>>1)-R:x=R,A.isubn(x)):x=0,d[T]=x,A.iushrn(1)}return d}r.getNAF=n;function i(a,c){var f=[[],[]];a=a.clone(),c=c.clone();for(var d=0,w=0,A;a.cmpn(-d)>0||c.cmpn(-w)>0;){var T=a.andln(3)+d&3,x=c.andln(3)+w&3;T===3&&(T=-1),x===3&&(x=-1);var R;T&1?(A=a.andln(7)+d&7,(A===3||A===5)&&x===2?R=-T:R=T):R=0,f[0].push(R);var V;x&1?(A=c.andln(7)+w&7,(A===3||A===5)&&T===2?V=-x:V=x):V=0,f[1].push(V),2*d===R+1&&(d=1-d),2*w===V+1&&(w=1-w),a.iushrn(1),c.iushrn(1)}return f}r.getJSF=i;function s(a,c,f){var d="_"+c;a.prototype[c]=function(){return this[d]!==void 0?this[d]:this[d]=f.call(this)}}r.cachedProperty=s;function o(a){return typeof a=="string"?r.toArray(a,"hex"):a}r.parseBytes=o;function u(a){return new Se(a,"hex","le")}r.intFromLE=u}),jm=pn.getNAF,Hne=pn.getJSF,ty=pn.assert;function Vo(t,e){this.type=t,this.p=new Se(e.p,16),this.red=e.prime?Se.red(e.prime):Se.mont(this.p),this.zero=new Se(0).toRed(this.red),this.one=new Se(1).toRed(this.red),this.two=new Se(2).toRed(this.red),this.n=e.n&&new Se(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var nu=Vo;Vo.prototype.point=function(){throw new Error("Not implemented")},Vo.prototype.validate=function(){throw new Error("Not implemented")},Vo.prototype._fixedNafMul=function(t,e){ty(t.precomputed);var r=t._getDoubles(),n=jm(e,1,this._bitLength),i=(1<=o;a--)u=(u<<1)+n[a];s.push(u)}for(var c=this.jpoint(null,null,null),f=this.jpoint(null,null,null),d=i;d>0;d--){for(o=0;o=0;u--){for(var a=0;u>=0&&s[u]===0;u--)a++;if(u>=0&&a++,o=o.dblp(a),u<0)break;var c=s[u];ty(c!==0),t.type==="affine"?c>0?o=o.mixedAdd(i[c-1>>1]):o=o.mixedAdd(i[-c-1>>1].neg()):c>0?o=o.add(i[c-1>>1]):o=o.add(i[-c-1>>1].neg())}return t.type==="affine"?o.toP():o},Vo.prototype._wnafMulAdd=function(t,e,r,n,i){var s=this._wnafT1,o=this._wnafT2,u=this._wnafT3,a=0,c,f,d;for(c=0;c=1;c-=2){var A=c-1,T=c;if(s[A]!==1||s[T]!==1){u[A]=jm(r[A],s[A],this._bitLength),u[T]=jm(r[T],s[T],this._bitLength),a=Math.max(u[A].length,a),a=Math.max(u[T].length,a);continue}var x=[e[A],null,null,e[T]];e[A].y.cmp(e[T].y)===0?(x[1]=e[A].add(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg())):e[A].y.cmp(e[T].y.redNeg())===0?(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].add(e[T].neg())):(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg()));var R=[-3,-1,-5,-7,0,7,5,1,3],V=Hne(r[A],r[T]);for(a=Math.max(V[0].length,a),u[A]=new Array(a),u[T]=new Array(a),f=0;f=0;c--){for(var H=0;c>=0;){var q=!0;for(f=0;f=0&&H++,L=L.dblp(H),c<0)break;for(f=0;f0?d=o[f][v-1>>1]:v<0&&(d=o[f][-v-1>>1].neg()),d.type==="affine"?L=L.mixedAdd(d):L=L.add(d))}}for(c=0;c=Math.ceil((t.bitLength()+1)/e.step):!1},Wn.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(w=a,A=c),f.negative&&(f=f.neg(),d=d.neg()),w.negative&&(w=w.neg(),A=A.neg()),[{a:f,b:d},{a:w,b:A}]},Yn.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),u=s.mul(n.a),a=i.mul(r.b),c=s.mul(n.b),f=t.sub(o).sub(u),d=a.add(c).neg();return{k1:f,k2:d}},Yn.prototype.pointFromX=function(t,e){t=new Se(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(n.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},Yn.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return r.redSqr().redISub(i).cmpn(0)===0},Yn.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Ar.prototype.isInfinity=function(){return this.inf},Ar.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Ar.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Ar.prototype.getX=function(){return this.x.fromRed()},Ar.prototype.getY=function(){return this.y.fromRed()},Ar.prototype.mul=function(t){return t=new Se(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Ar.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Ar.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Ar.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Ar.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(i){return i.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Ar.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function _r(t,e,r,n){nu.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&n===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Se(0)):(this.x=new Se(e,16),this.y=new Se(r,16),this.z=new Se(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}QT(_r,nu.BasePoint),Yn.prototype.jpoint=function(t,e,r){return new _r(this,t,e,r)},_r.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},_r.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_r.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=s.redSub(o);if(u.cmpn(0)===0)return a.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var c=u.redSqr(),f=c.redMul(u),d=n.redMul(c),w=a.redSqr().redIAdd(f).redISub(d).redISub(d),A=a.redMul(d.redISub(w)).redISub(s.redMul(f)),T=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(w,A,T)},_r.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),u=i.redSub(s);if(o.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),c=a.redMul(o),f=r.redMul(a),d=u.redSqr().redIAdd(c).redISub(f).redISub(f),w=u.redMul(f.redISub(d)).redISub(i.redMul(c)),A=this.z.redMul(o);return this.curve.jpoint(d,w,A)},_r.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),this.x.cmp(r)===0)return!0}},_r.prototype.inspect=function(){return this.isInfinity()?"":""},_r.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Km=fl(function(t,e){var r=e;r.base=nu,r.short=jne,r.mont=null,r.edwards=null}),Wm=fl(function(t,e){var r=e,n=pn.assert;function i(u){u.type==="short"?this.curve=new Km.short(u):u.type==="edwards"?this.curve=new Km.edwards(u):this.curve=new Km.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=i;function s(u,a){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var c=new i(a);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:c}),c}})}s("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:os.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:os.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:os.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:os.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),s("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:os.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var o;try{o=null.crash()}catch{o=void 0}s("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:os.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",o]})});function ko(t){if(!(this instanceof ko))return new ko(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Ti.toArray(t.entropy,t.entropyEnc||"hex"),r=Ti.toArray(t.nonce,t.nonceEnc||"hex"),n=Ti.toArray(t.pers,t.persEnc||"hex");zT(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var LM=ko;ko.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},ko.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(n=r,r=e,e=null),r&&(r=Ti.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var zne=pn.assert;function sy(t,e){if(t instanceof sy)return t;this._importDER(t,e)||(zne(t.r&&t.s,"Signature without r or s"),this.r=new Se(t.r,16),this.s=new Se(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var zm=sy;function Qne(){this.place=0}function ET(t,e){var r=t[e.place++];if(!(r&128))return r;var n=r&15;if(n===0||n>4)return!1;for(var i=0,s=0,o=e.place;s>>=0;return i<=127?!1:(e.place=o,i)}function FM(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}sy.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=FM(e),r=FM(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var n=[2];bT(n,e.length),n=n.concat(e),n.push(2),bT(n,r.length);var i=n.concat(r),s=[48];return bT(s,i.length),s=s.concat(i),pn.encode(s,t)};var Kne=function(){throw new Error("unsupported")},W4=pn.assert;function $n(t){if(!(this instanceof $n))return new $n(t);typeof t=="string"&&(W4(Object.prototype.hasOwnProperty.call(Wm,t),"Unknown curve "+t),t=Wm[t]),t instanceof Wm.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Wne=$n;$n.prototype.keyPair=function(t){return new AT(this,t)},$n.prototype.keyFromPrivate=function(t,e){return AT.fromPrivate(this,t,e)},$n.prototype.keyFromPublic=function(t,e){return AT.fromPublic(this,t,e)},$n.prototype.genKeyPair=function(t){t||(t={});for(var e=new LM({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Kne(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Se(2));;){var i=new Se(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},$n.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},$n.prototype.sign=function(t,e,r,n){typeof r=="object"&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Se(t,16));for(var i=this.n.byteLength(),s=e.getPrivate().toArray("be",i),o=t.toArray("be",i),u=new LM({hash:this.hash,entropy:s,nonce:o,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Se(1)),c=0;;c++){var f=n.k?n.k(c):new Se(u.generate(this.n.byteLength()));if(f=this._truncateToN(f,!0),!(f.cmpn(1)<=0||f.cmp(a)>=0)){var d=this.g.mul(f);if(!d.isInfinity()){var w=d.getX(),A=w.umod(this.n);if(A.cmpn(0)!==0){var T=f.invm(this.n).mul(A.mul(e.getPrivate()).iadd(t));if(T=T.umod(this.n),T.cmpn(0)!==0){var x=(d.getY().isOdd()?1:0)|(w.cmp(A)!==0?2:0);return n.canonical&&T.cmp(this.nh)>0&&(T=this.n.sub(T),x^=1),new zm({r:A,s:T,recoveryParam:x})}}}}}},$n.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Se(t,16)),r=this.keyFromPublic(r,n),e=new zm(e,"hex");var i=e.r,s=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o=s.invm(this.n),u=o.mul(t).umod(this.n),a=o.mul(i).umod(this.n),c;return this.curve._maxwellTrick?(c=this.g.jmulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.eqXToP(i)):(c=this.g.mulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.getX().umod(this.n).cmp(i)===0)},$n.prototype.recoverPubKey=function(t,e,r,n){W4((3&r)===r,"The recovery param is more than two bits"),e=new zm(e,n);var i=this.n,s=new Se(t),o=e.r,u=e.s,a=r&1,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");c?o=this.curve.pointFromX(o.add(this.curve.n),a):o=this.curve.pointFromX(o,a);var f=e.r.invm(i),d=i.sub(s).mul(f).umod(i),w=u.mul(f).umod(i);return this.g.mulAdd(d,o,w)},$n.prototype.getKeyRecoveryParam=function(t,e,r,n){if(e=new zm(e,n),e.recoveryParam!==null)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch{continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var $ne=fl(function(t,e){var r=e;r.version="6.5.4",r.utils=pn,r.rand=function(){throw new Error("unsupported")},r.curve=Km,r.curves=Wm,r.ec=Wne,r.eddsa=null}),Yne=$ne.ec,Jne="signing-key/5.7.0",OT=new kt(Jne),ST=null;function ls(){return ST||(ST=new Yne("secp256k1")),ST}var DT=class{constructor(e){Rh(this,"curve","secp256k1"),Rh(this,"privateKey",kr(e)),Pte(this.privateKey)!==32&&OT.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");let r=ls().keyFromPrivate(Qt(this.privateKey));Rh(this,"publicKey","0x"+r.getPublic(!1,"hex")),Rh(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),Rh(this,"_isSigningKey",!0)}_addPoint(e){let r=ls().keyFromPublic(Qt(this.publicKey)),n=ls().keyFromPublic(Qt(e));return"0x"+r.pub.add(n.pub).encodeCompressed("hex")}signDigest(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=Qt(e);n.length!==32&&OT.throwArgumentError("bad digest length","digest",e);let i=r.sign(n,{canonical:!0});return y4({recoveryParam:i.recoveryParam,r:fs("0x"+i.r.toString(16),32),s:fs("0x"+i.s.toString(16),32)})}computeSharedSecret(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=ls().keyFromPublic(Qt($4(e)));return fs("0x"+r.derive(n.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}};function Xne(t,e){let r=y4(e),n={r:Qt(r.r),s:Qt(r.s)};return"0x"+ls().recoverPubKey(Qt(t),n,r.recoveryParam).encode("hex",!1)}function $4(t,e){let r=Qt(t);if(r.length===32){let n=new DT(r);return e?"0x"+ls().keyFromPrivate(r).getPublic(!0,"hex"):n.publicKey}else{if(r.length===33)return e?kr(r):"0x"+ls().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+ls().keyFromPublic(r).getPublic(!0,"hex"):kr(r)}return OT.throwArgumentError("invalid public or private key","key","[REDACTED]")}var Zne="transactions/5.7.0";new kt(Zne);var UM;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(UM||(UM={}));function eie(t){let e=$4(t);return lre(IM(HT(IM(e,1)),12))}function tie(t,e){return eie(Xne(Qt(t),e))}var rie="https://rpc.walletconnect.com/v1";async function Y4(t,e,r,n,i,s){switch(r.t){case"eip191":return J4(t,e,r.s);case"eip1271":return await X4(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function J4(t,e,r){return tie(N4(e),r).toLowerCase()===t.toLowerCase()}async function X4(t,e,r,n,i,s){try{let o="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",c=r.substring(2),f=N4(e).substring(2),d=o+f+u+a+c,w=await fetch(`${s||rie}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:nie(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:A}=await w.json();return A?A.slice(0,o.length).toLowerCase()===o.toLowerCase():!1}catch(o){return console.error("isValidEip1271Signature: ",o),!1}}function nie(){return Date.now()+Math.floor(Math.random()*1e3)}var iie=Object.defineProperty,sie=Object.defineProperties,oie=Object.getOwnPropertyDescriptors,qM=Object.getOwnPropertySymbols,aie=Object.prototype.hasOwnProperty,uie=Object.prototype.propertyIsEnumerable,VM=(t,e,r)=>e in t?iie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KT=(t,e)=>{for(var r in e||(e={}))aie.call(e,r)&&VM(t,r,e[r]);if(qM)for(var r of qM(e))uie.call(e,r)&&VM(t,r,e[r]);return t},Z4=(t,e)=>sie(t,oie(e)),cie="did:pkh:",oy=t=>t?.split(":"),WT=t=>{let e=t&&oy(t);if(e)return t.includes(cie)?e[3]:e[1]},lie=t=>{let e=t&&oy(t);if(e)return e[2]+":"+e[3]},$T=t=>{let e=t&&oy(t);if(e)return e.pop()};async function fie(t){let{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=e5(i,i.iss),o=$T(i.iss);return await Y4(o,s,n,WT(i.iss),r)}var e5=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=$T(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0,s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,u=`Chain ID: ${WT(e)}`,a=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources?`Resources:${t.resources.map(w=>` +- ${w}`).join("")}`:void 0,d=uy(t.resources);if(d){let w=jo(d);i=XT(i,w)}return[r,n,"",i,"",s,o,u,a,c,f].filter(w=>w!=null).join(` +`)};function hie(t,e,r){return r.includes("did:pkh:")||(r=`did:pkh:${r}`),{h:{t:"caip122"},p:{iss:r,domain:t.domain,aud:t.aud,version:t.version,nonce:t.nonce,iat:t.iat,statement:t.statement,requestId:t.requestId,resources:t.resources,nbf:t.nbf,exp:t.exp},s:e}}function die(t){var e;let{authPayload:r,chains:n,methods:i}=t,s=r.statement||"";if(!(n!=null&&n.length))return r;let o=r.chains,u=TT(o,n);if(!(u!=null&&u.length))throw new Error("No supported chains");let a=t5(r.resources);if(!a)return r;ps(a);let c=r5(a,"eip155"),f=r?.resources||[];if(c!=null&&c.length){let d=n5(c),w=TT(d,i);if(!(w!=null&&w.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(d)}, supported: ${JSON.stringify(i)}`);let A=YT("request",w,{chains:u}),T=a5(a,"eip155",A);f=((e=r?.resources)==null?void 0:e.slice(0,-1))||[],f.push(ay(T))}return Z4(KT({},r),{statement:c5(s,uy(f)),chains:u,resources:r!=null&&r.resources||f.length>0?f:void 0})}function t5(t){let e=uy(t);if(e&&JT(e))return jo(e)}function gie(t,e){var r;return(r=t?.att)==null?void 0:r.hasOwnProperty(e)}function r5(t,e){var r,n;return(r=t?.att)!=null&&r[e]?Object.keys((n=t?.att)==null?void 0:n[e]):[]}function pie(t){return t?.map(e=>Object.keys(e))||[]}function n5(t){return t?.map(e=>{var r;return(r=e.split("/"))==null?void 0:r[1]})||[]}function i5(t){return p.Buffer.from(JSON.stringify(t)).toString("base64")}function s5(t){return JSON.parse(p.Buffer.from(t,"base64").toString("utf-8"))}function ps(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");let e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{let n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{let s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function o5(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:YT(e,r,n)}}}function a5(t,e,r){var n;return t.att[e]=KT({},r),((n=Object.keys(t.att))==null?void 0:n.sort((i,s)=>i.localeCompare(s))).reduce((i,s)=>(i.att[s]=t.att[s],i),{att:{}})}function YT(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));let n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function ay(t){return ps(t),`urn:recap:${i5(t).replace(/=/g,"")}`}function jo(t){let e=s5(t.replace("urn:recap:",""));return ps(e),e}function mie(t,e,r){let n=o5(t,e,r);return ay(n)}function JT(t){return t&&t.includes("urn:recap:")}function yie(t,e){let r=jo(t),n=jo(e),i=u5(r,n);return ay(i)}function u5(t,e){ps(t),ps(e);let r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((u,a)=>u.localeCompare(a)).forEach(u=>{var a,c;n.att[i]=Z4(KT({},n.att[i]),{[u]:((a=t.att[i])==null?void 0:a[u])||((c=e.att[i])==null?void 0:c[u])})})}),n}function XT(t="",e){ps(e);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;let n=[],i=0;Object.keys(e.att).forEach(u=>{let a=Object.keys(e.att[u]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));a.sort((d,w)=>d.action.localeCompare(w.action));let c={};a.forEach(d=>{c[d.ability]||(c[d.ability]=[]),c[d.ability].push(d.action)});let f=Object.keys(c).map(d=>(i++,`(${i}) '${d}': '${c[d].join("', '")}' for '${u}'.`));n.push(f.join(", ").replace(".,","."))});let s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function wie(t){var e;let r=jo(t);ps(r);let n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function vie(t){let e=jo(t);ps(e);let r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function c5(t,e){if(!e)return t;let r=jo(e);return ps(r),XT(t,r)}function uy(t){if(!t)return;let e=t?.[t.length-1];return JT(e)?e:void 0}var ZT="base10",jr="base16",ry="base64pad",cy="utf8",e_=0,hl=1,Aie=0,kM=1,PT=12,t_=32;function Eie(){let t=JM.generateKeyPair();return{privateKey:Vt.toString(t.secretKey,jr),publicKey:Vt.toString(t.publicKey,jr)}}function bie(){let t=$M.randomBytes(t_);return Vt.toString(t,jr)}function Sie(t,e){let r=JM.sharedKey(Vt.fromString(t,jr),Vt.fromString(e,jr),!0),n=new Gee.HKDF(LT.SHA256,r).expand(t_);return Vt.toString(n,jr)}function Iie(t){let e=LT.hash(Vt.fromString(t,jr));return Vt.toString(e,jr)}function Tie(t){let e=LT.hash(Vt.fromString(t,cy));return Vt.toString(e,jr)}function l5(t){return Vt.fromString(`${t}`,ZT)}function jh(t){return Number(Vt.toString(t,ZT))}function _ie(t){let e=l5(typeof t.type<"u"?t.type:e_);if(jh(e)===hl&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?Vt.fromString(t.senderPublicKey,jr):void 0,n=typeof t.iv<"u"?Vt.fromString(t.iv,jr):$M.randomBytes(PT),i=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)).seal(n,Vt.fromString(t.message,cy));return f5({type:e,sealed:i,iv:n,senderPublicKey:r})}function Cie(t){let e=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)),{sealed:r,iv:n}=r_(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Vt.toString(i,cy)}function f5(t){if(jh(t.type)===hl){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Vt.toString(Vt.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),ry)}return Vt.toString(Vt.concat([t.type,t.iv,t.sealed]),ry)}function r_(t){let e=Vt.fromString(t,ry),r=e.slice(Aie,kM),n=kM;if(jh(r)===hl){let u=n+t_,a=u+PT,c=e.slice(n,u),f=e.slice(u,a),d=e.slice(a);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+PT,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Nie(t,e){let r=r_(t);return h5({type:jh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Vt.toString(r.senderPublicKey,jr):void 0,receiverPublicKey:e?.receiverPublicKey})}function h5(t){let e=t?.type||e_;if(e===hl){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function xie(t){return t.type===hl&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var d5="irn";function Oie(t){return t?.relay||{protocol:d5}}function Die(t){let e=zee.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Pie=Object.defineProperty,Rie=Object.defineProperties,Bie=Object.getOwnPropertyDescriptors,HM=Object.getOwnPropertySymbols,Mie=Object.prototype.hasOwnProperty,Lie=Object.prototype.propertyIsEnumerable,GM=(t,e,r)=>e in t?Pie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jM=(t,e)=>{for(var r in e||(e={}))Mie.call(e,r)&&GM(t,r,e[r]);if(HM)for(var r of HM(e))Lie.call(e,r)&&GM(t,r,e[r]);return t},Fie=(t,e)=>Rie(t,Bie(e));function g5(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Uie(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=$m.parse(s),u=typeof o.methods=="string"?o.methods.split(","):void 0;return{protocol:n,topic:p5(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:g5(o),methods:u,expiryTimestamp:o.expiryTimestamp?parseInt(o.expiryTimestamp,10):void 0}}function p5(t){return t.startsWith("//")?t.substring(2):t}function m5(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function qie(t){return`${t.protocol}:${t.topic}@${t.version}?`+$m.stringify(jM(Fie(jM({symKey:t.symKey},m5(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}var Vie=Object.defineProperty,kie=Object.defineProperties,Hie=Object.getOwnPropertyDescriptors,zM=Object.getOwnPropertySymbols,Gie=Object.prototype.hasOwnProperty,jie=Object.prototype.propertyIsEnumerable,QM=(t,e,r)=>e in t?Vie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zie=(t,e)=>{for(var r in e||(e={}))Gie.call(e,r)&&QM(t,r,e[r]);if(zM)for(var r of zM(e))jie.call(e,r)&&QM(t,r,e[r]);return t},Qie=(t,e)=>kie(t,Hie(e));function iu(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function y5(t){let e=[];return Object.values(t).forEach(r=>{e.push(...iu(r.accounts))}),e}function w5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.methods)}),r}function v5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.events)}),r}function Kie(t,e){let r=O5(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function Wie(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=RT(e),s=RT(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,w=n[c].events,A=n[c].accounts;f.forEach(T=>{if(!A.some(x=>x.includes(T)))throw new Error(`No accounts provided for chain ${T} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:w,accounts:A}});let u=P5(e,o,"approve()");if(u)throw new Error(u.message);let a={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.chains)==null?void 0:R.includes(T)}),d=n[c].methods.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.methods)==null?void 0:R.includes(T)}),w=n[c].events.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.events)==null?void 0:R.includes(T)}),A=f.map(T=>n[c].accounts.filter(x=>x.includes(`${T}:`))).flat();a[c]={chains:f,methods:d,events:w,accounts:A}}),Object.keys(s).forEach(c=>{var f,d,w,A,T,x;if(!n[c])return;let R=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(L=>n[c].chains.includes(L)),V=n[c].methods.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.methods)==null?void 0:H.includes(L)}),U=n[c].events.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.events)==null?void 0:H.includes(L)}),Q=R?.map(L=>n[c].accounts.filter(k=>k.includes(`${L}:`))).flat();a[c]={chains:Js((w=a[c])==null?void 0:w.chains,R),methods:Js((A=a[c])==null?void 0:A.methods,V),events:Js((T=a[c])==null?void 0:T.events,U),accounts:Js((x=a[c])==null?void 0:x.accounts,Q)}}),a)}function n_(t){return t.includes(":")}function A5(t){return n_(t)?t.split(":")[0]:t}function RT(t){var e,r,n;let i={};if(!ly(t))return i;for(let[s,o]of Object.entries(t)){let u=n_(s)?[s]:o.chains,a=o.methods||[],c=o.events||[],f=A5(s);i[f]=Qie(zie({},i[f]),{chains:Js(u,(e=i[f])==null?void 0:e.chains),methods:Js(a,(r=i[f])==null?void 0:r.methods),events:Js(c,(n=i[f])==null?void 0:n.events)})}return i}function E5(t){let e={};return t?.forEach(r=>{let[n,i]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[]}),e[n].accounts.push(r),e[n].chains.push(`${n}:${i}`)}),e}function $ie(t,e){e=e.map(n=>n.replace("did:pkh:",""));let r=E5(e);for(let[n,i]of Object.entries(r))i.methods?i.methods=Js(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}var b5={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},S5={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ys(t,e){let{message:r,code:n}=S5[t];return{message:e?`${r} ${e}`:r,code:n}}function tu(t,e){let{message:r,code:n}=b5[t];return{message:e?`${r} ${e}`:r,code:n}}function zh(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function ly(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Go(t){return typeof t>"u"}function mn(t,e){return e&&Go(t)?!0:typeof t=="string"&&!!t.trim().length}function fy(t,e){return e&&Go(t)?!0:typeof t=="number"&&!isNaN(t)}function Yie(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Ho(i,n)?(n.forEach(o=>{let{accounts:u,methods:a,events:c}=t.namespaces[o],f=iu(u),d=r[o];(!Ho(iy(o,d),f)||!Ho(d.methods,a)||!Ho(d.events,c))&&(s=!1)}),s):!1}function kh(t){return mn(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function I5(t){if(mn(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&kh(r)}}return!1}function Jie(t){if(mn(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function Xie(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function Zie(t){return t?.topic}function ese(t,e){let r=null;return mn(t?.publicKey,!1)||(r=Ys("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function BT(t){let e=!0;return zh(t)?t.length&&(e=t.every(r=>mn(r,!1))):e=!1,e}function T5(t,e,r){let n=null;return zh(e)&&e.length?e.forEach(i=>{n||kh(i)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):kh(t)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function _5(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=T5(i,iy(i,s),`${e} ${r}`);o&&(n=o)}),n}function C5(t,e){let r=null;return zh(t)?t.forEach(n=>{r||I5(n)||(r=tu("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=tu("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function N5(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=C5(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function x5(t,e){let r=null;return BT(t?.methods)?BT(t?.events)||(r=tu("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=tu("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function i_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=x5(n,`${e}, namespace`);i&&(r=i)}),r}function tse(t,e,r){let n=null;if(t&&ly(t)){let i=i_(t,e);i&&(n=i);let s=_5(t,e,r);s&&(n=s)}else n=Ys("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function O5(t,e){let r=null;if(t&&ly(t)){let n=i_(t,e);n&&(r=n);let i=N5(t,e);i&&(r=i)}else r=Ys("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function D5(t){return mn(t.protocol,!0)}function rse(t,e){let r=!1;return e&&!t?r=!0:t&&zh(t)&&t.length&&t.forEach(n=>{r=D5(n)}),r}function nse(t){return typeof t=="number"}function ise(t){return typeof t<"u"&&typeof t!==null}function sse(t){return!(!t||typeof t!="object"||!t.code||!fy(t.code,!1)||!t.message||!mn(t.message,!1))}function ose(t){return!(Go(t)||!mn(t.method,!1))}function ase(t){return!(Go(t)||Go(t.result)&&Go(t.error)||!fy(t.id,!1)||!mn(t.jsonrpc,!1))}function use(t){return!(Go(t)||!mn(t.name,!1))}function cse(t,e){return!(!kh(e)||!y5(t).includes(e))}function lse(t,e,r){return mn(r,!1)?w5(t,e).includes(r):!1}function fse(t,e,r){return mn(r,!1)?v5(t,e).includes(r):!1}function P5(t,e,r){let n=null,i=hse(t),s=dse(e),o=Object.keys(i),u=Object.keys(s),a=KM(Object.keys(t)),c=KM(Object.keys(e)),f=a.filter(d=>!c.includes(d));return f.length&&(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. + Required: ${f.toString()} + Received: ${Object.keys(e).toString()}`)),Ho(o,u)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. + Required: ${o.toString()} + Approved: ${u.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let w=iu(e[d].accounts);w.includes(d)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} + Required: ${d} + Approved: ${w.toString()}`))}),o.forEach(d=>{n||(Ho(i[d].methods,s[d].methods)?Ho(i[d].events,s[d].events)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function hse(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function KM(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dse(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:iu(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function gse(t,e){return fy(t,!1)&&t<=e.max&&t>=e.min}function pse(){let t=ru();return new Promise(e=>{switch(t){case Gr.browser:e(R5());break;case Gr.reactNative:e(B5());break;case Gr.node:e(M5());break;default:e(!0)}})}function R5(){return Hh()&&navigator?.onLine}async function B5(){return al()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function M5(){return!0}function mse(t){switch(ru()){case Gr.browser:L5(t);break;case Gr.reactNative:F5(t);break;case Gr.node:break}}function L5(t){!al()&&Hh()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function F5(t){al()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var IT={},MT=class{static get(e){return IT[e]}static set(e,r){IT[e]=r}static delete(e){delete IT[e]}};K.BASE10=ZT,K.BASE16=jr,K.BASE64=ry,K.COLON=ete,K.DEFAULT_DEPTH=qT,K.EMPTY_SPACE=Ym,K.ENV_MAP=Gr,K.INTERNAL_ERRORS=S5,K.MemoryStore=MT,K.ONE_THOUSAND=tte,K.REACT_NATIVE_PRODUCT=i4,K.RELAYER_DEFAULT_PROTOCOL=d5,K.SDK_ERRORS=b5,K.SDK_TYPE=o4,K.SLASH=s4,K.TYPE_0=e_,K.TYPE_1=hl,K.UTF8=cy,K.addResourceToRecap=a5,K.appendToQueryString=a4,K.assertType=ate,K.assignAbilityToActions=YT,K.base64Decode=s5,K.base64Encode=i5,K.buildApprovedNamespaces=Wie,K.buildAuthObject=hie,K.buildNamespacesFromAuth=$ie,K.buildRecapStatement=c5,K.calcExpiry=vte,K.capitalize=dte,K.capitalizeWord=d4,K.createDelayedPromise=gte,K.createEncodedRecap=mie,K.createExpiringPromise=pte,K.createRecap=o5,K.decodeRecap=jo,K.decodeTypeByte=jh,K.decrypt=Cie,K.deriveSymKey=Sie,K.deserialize=r_,K.encodeRecap=ay,K.encodeTypeByte=l5,K.encrypt=_ie,K.engineEvent=Ete,K.enumify=hte,K.formatAccountId=e4,K.formatAccountWithChain=Qee,K.formatChainId=ZM,K.formatExpirerTarget=kT,K.formatIdTarget=yte,K.formatMessage=e5,K.formatMessageContext=ute,K.formatRelayParams=m5,K.formatRelayRpcUrl=ste,K.formatStatementFromRecap=XT,K.formatTopicTarget=mte,K.formatUA=l4,K.formatUri=qie,K.generateKeyPair=Eie,K.generateRandomBytes32=bie,K.getAccountsChains=iu,K.getAccountsFromNamespaces=Wee,K.getAddressFromAccount=t4,K.getAddressesFromAccounts=Kee,K.getAppMetadata=nte,K.getBrowserOnlineStatus=R5,K.getBundleId=rte,K.getChainFromAccount=r4,K.getChainsFromAccounts=n4,K.getChainsFromNamespace=iy,K.getChainsFromNamespaces=$ee,K.getChainsFromRecap=vie,K.getChainsFromRequiredNamespaces=Yee,K.getCommonValuesInArrays=TT,K.getDecodedRecapFromResources=t5,K.getDeepLink=Ste,K.getDidAddress=$T,K.getDidAddressSegments=oy,K.getDidChainId=WT,K.getEnvironment=ru,K.getHttpUrl=ote,K.getInternalError=Ys,K.getJavascriptID=c4,K.getJavascriptOS=u4,K.getLastItems=h4,K.getMethodsFromRecap=wie,K.getNamespacedDidChainId=lie,K.getNamespacesChains=y5,K.getNamespacesEventsForChainId=v5,K.getNamespacesFromAccounts=E5,K.getNamespacesMethodsForChainId=w5,K.getNodeOnlineStatus=M5,K.getReCapActions=n5,K.getReactNativeOnlineStatus=B5,K.getRecapAbilitiesFromResource=pie,K.getRecapFromResources=uy,K.getRecapResource=r5,K.getRelayClientMetadata=ite,K.getRelayProtocolApi=Die,K.getRelayProtocolName=Oie,K.getRequiredNamespacesFromNamespaces=Kie,K.getSdkError=tu,K.getUniqueValues=UT,K.handleDeeplinkRedirect=bte,K.hasOverlap=Ho,K.hashKey=Iie,K.hashMessage=Tie,K.isBrowser=Hh,K.isCaipNamespace=n_,K.isConformingNamespaces=P5,K.isExpired=Ate,K.isNode=VT,K.isOnline=pse,K.isProposalStruct=Xie,K.isReactNative=al,K.isRecap=JT,K.isSessionCompatible=Yie,K.isSessionStruct=Zie,K.isTypeOneEnvelope=xie,K.isUndefined=Go,K.isValidAccountId=I5,K.isValidAccounts=C5,K.isValidActions=x5,K.isValidArray=zh,K.isValidChainId=kh,K.isValidChains=T5,K.isValidController=ese,K.isValidEip1271Signature=X4,K.isValidEip191Signature=J4,K.isValidErrorReason=sse,K.isValidEvent=use,K.isValidId=nse,K.isValidNamespaceAccounts=N5,K.isValidNamespaceActions=i_,K.isValidNamespaceChains=_5,K.isValidNamespaceMethodsOrEvents=BT,K.isValidNamespaces=O5,K.isValidNamespacesChainId=cse,K.isValidNamespacesEvent=fse,K.isValidNamespacesRequest=lse,K.isValidNumber=fy,K.isValidObject=ly,K.isValidParams=ise,K.isValidRecap=ps,K.isValidRelay=D5,K.isValidRelays=rse,K.isValidRequest=ose,K.isValidRequestExpiry=gse,K.isValidRequiredNamespaces=tse,K.isValidResponse=ase,K.isValidString=mn,K.isValidUrl=Jie,K.mapEntries=fte,K.mapToObj=cte,K.mergeArrays=Js,K.mergeEncodedRecaps=yie,K.mergeRecaps=u5,K.normalizeNamespaces=RT,K.objToMap=lte,K.parseAccountId=FT,K.parseChainId=XM,K.parseContextNames=f4,K.parseExpirerTarget=wte,K.parseNamespaceKey=A5,K.parseRelayParams=g5,K.parseTopic=p5,K.parseUri=Uie,K.populateAuthPayload=die,K.recapHasResource=gie,K.serialize=f5,K.subscribeToBrowserNetworkChange=L5,K.subscribeToNetworkChange=mse,K.subscribeToReactNativeNetworkChange=F5,K.validateDecoding=Nie,K.validateEncoding=h5,K.validateSignedCacao=fie,K.verifySignature=Y4});var U5,q5,V5,k5,hy,Kh,s_,dy,zo,Wh,gy=fe(()=>{h();U5="PARSE_ERROR",q5="INVALID_REQUEST",V5="METHOD_NOT_FOUND",k5="INVALID_PARAMS",hy="INTERNAL_ERROR",Kh="SERVER_ERROR",s_=[-32700,-32600,-32601,-32602,-32603],dy=[-32e3,-32099],zo={[U5]:{code:-32700,message:"Parse error"},[q5]:{code:-32600,message:"Invalid Request"},[V5]:{code:-32601,message:"Method not found"},[k5]:{code:-32602,message:"Invalid params"},[hy]:{code:-32603,message:"Internal error"},[Kh]:{code:-32e3,message:"Server error"}},Wh=Kh});function yse(t){return t<=dy[0]&&t>=dy[1]}function py(t){return s_.includes(t)}function H5(t){return typeof t=="number"}function my(t){return Object.keys(zo).includes(t)?zo[t]:zo[Wh]}function yy(t){let e=Object.values(zo).find(r=>r.code===t);return e||zo[Wh]}function wse(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!H5(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(py(t.error.code)){let e=yy(t.error.code);if(e.message!==zo[Wh].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function o_(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var a_=fe(()=>{h();gy()});var j5=B(Qo=>{"use strict";h();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.isBrowserCryptoAvailable=Qo.getSubtleCrypto=Qo.getBrowerCrypto=void 0;function u_(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}Qo.getBrowerCrypto=u_;function G5(){let t=u_();return t.subtle||t.webkitSubtle}Qo.getSubtleCrypto=G5;function vse(){return!!u_()&&!!G5()}Qo.isBrowserCryptoAvailable=vse});var K5=B(Ko=>{"use strict";h();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.isBrowser=Ko.isNode=Ko.isReactNative=void 0;function z5(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ko.isReactNative=z5;function Q5(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}Ko.isNode=Q5;function Ase(){return!z5()&&!Q5()}Ko.isBrowser=Ase});var c_=B(wy=>{"use strict";h();Object.defineProperty(wy,"__esModule",{value:!0});var W5=(es(),_e(Zi));W5.__exportStar(j5(),wy);W5.__exportStar(K5(),wy)});var Er={};Bt(Er,{isNodeJs:()=>Y5});var $5,Y5,J5=fe(()=>{h();$5=pe(c_());Tr(Er,pe(c_()));Y5=$5.isNode});function l_(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function f_(t=6){return BigInt(l_(t))}function h_(t,e,r){return{id:r||l_(),jsonrpc:"2.0",method:t,params:e}}function Ese(t,e){return{id:t,jsonrpc:"2.0",result:e}}function d_(t,e,r){return{id:t,jsonrpc:"2.0",error:X5(e,r)}}function X5(t,e){return typeof t>"u"?my(hy):(typeof t=="string"&&(t=Object.assign(Object.assign({},my(Kh)),{message:t})),typeof e<"u"&&(t.data=e),py(t.code)&&(t=yy(t.code)),t)}var Z5=fe(()=>{h();a_();gy()});function bse(t){return t.includes("*")?Ay(t):!/\W/g.test(t)}function vy(t){return t==="*"}function Ay(t){return vy(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function Sse(t){return!vy(t)&&Ay(t)&&!t.split("*")[0].trim()}function Ise(t){return!vy(t)&&Ay(t)&&!t.split("*")[1].trim()}var eL=fe(()=>{h()});var tL=fe(()=>{h()});var dl,g_=fe(()=>{h();dl=class{}});var p_,Ey,$h,rL=fe(()=>{h();g_();p_=class extends dl{constructor(e){super()}},Ey=class extends dl{constructor(){super()}},$h=class extends Ey{constructor(e){super()}}});var nL=fe(()=>{h()});var iL=fe(()=>{h();tL();g_();rL();nL()});var sL=fe(()=>{h();iL()});function Cse(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function oL(t,e){let r=Cse(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Nse(t){return oL(t,Tse)}function by(t){return oL(t,_se)}function m_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var Tse,_se,aL=fe(()=>{h();Tse="^https?:",_se="^wss?:"});function y_(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function xse(t){return y_(t)&&"method"in t}function w_(t){return y_(t)&&(uL(t)||Sy(t))}function uL(t){return"result"in t}function Sy(t){return"error"in t}function Ose(t){return"error"in t&&t.valid===!1}var cL=fe(()=>{h()});var Fr={};Bt(Fr,{DEFAULT_ERROR:()=>Wh,IBaseJsonRpcProvider:()=>Ey,IEvents:()=>dl,IJsonRpcConnection:()=>p_,IJsonRpcProvider:()=>$h,INTERNAL_ERROR:()=>hy,INVALID_PARAMS:()=>k5,INVALID_REQUEST:()=>q5,METHOD_NOT_FOUND:()=>V5,PARSE_ERROR:()=>U5,RESERVED_ERROR_CODES:()=>s_,SERVER_ERROR:()=>Kh,SERVER_ERROR_CODE_RANGE:()=>dy,STANDARD_ERROR_MAP:()=>zo,formatErrorMessage:()=>X5,formatJsonRpcError:()=>d_,formatJsonRpcRequest:()=>h_,formatJsonRpcResult:()=>Ese,getBigIntRpcId:()=>f_,getError:()=>my,getErrorByCode:()=>yy,isHttpUrl:()=>Nse,isJsonRpcError:()=>Sy,isJsonRpcPayload:()=>y_,isJsonRpcRequest:()=>xse,isJsonRpcResponse:()=>w_,isJsonRpcResult:()=>uL,isJsonRpcValidationInvalid:()=>Ose,isLocalhostUrl:()=>m_,isNodeJs:()=>Y5,isReservedErrorCode:()=>py,isServerErrorCode:()=>yse,isValidDefaultRoute:()=>vy,isValidErrorCode:()=>H5,isValidLeadingWildcardRoute:()=>Sse,isValidRoute:()=>bse,isValidTrailingWildcardRoute:()=>Ise,isValidWildcardRoute:()=>Ay,isWsUrl:()=>by,parseConnectionError:()=>o_,payloadId:()=>l_,validateJsonRpcError:()=>wse});var Yh=fe(()=>{h();gy();a_();J5();Tr(Fr,Er);Z5();eL();sL();aL();cL()});var lL,Iy,fL,v_=fe(()=>{h();lL=pe(Ds());Yh();Iy=class extends $h{constructor(e){super(e),this.events=new lL.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(h_(e.method,e.params||[],e.id||f_().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Sy(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),w_(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},fL=Iy});var hL={};Bt(hL,{JsonRpcProvider:()=>Iy,default:()=>Dse});var Dse,dL=fe(()=>{h();v_();v_();Dse=fL});var pL=B((LIe,gL)=>{"use strict";h();gL.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var vL={};Bt(vL,{WsConnection:()=>A_,default:()=>A_});var wL,Pse,Rse,mL,yL,Bse,A_,AL=fe(()=>{h();wL=pe(Ds());xc();Yh();Pse=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:pL(),Rse=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",mL=t=>t.split("?")[0],yL=10,Bse=Pse(),A_=class{constructor(e){if(this.url=e,this.events=new wL.EventEmitter,this.registering=!1,!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ai(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,Fr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!m_(e)},o=new Bse(e,[],s);Rse()?o.onerror=u=>{let a=u;n(this.emitError(a.error))}:o.on("error",u=>{n(this.emitError(u))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?Ro(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=d_(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return o_(e,mL(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>yL&&this.events.setMaxListeners(yL)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${mL(this.url)}`));return this.events.emit("register_error",r),r}}});var tF=B((Jh,pl)=>{h();var Mse=200,D_="__lodash_hash_undefined__",Py=1,PL=2,RL=9007199254740991,Ty="[object Arguments]",I_="[object Array]",Lse="[object AsyncFunction]",BL="[object Boolean]",ML="[object Date]",LL="[object Error]",FL="[object Function]",Fse="[object GeneratorFunction]",_y="[object Map]",UL="[object Number]",Use="[object Null]",gl="[object Object]",EL="[object Promise]",qse="[object Proxy]",qL="[object RegExp]",Cy="[object Set]",VL="[object String]",Vse="[object Symbol]",kse="[object Undefined]",T_="[object WeakMap]",kL="[object ArrayBuffer]",Ny="[object DataView]",Hse="[object Float32Array]",Gse="[object Float64Array]",jse="[object Int8Array]",zse="[object Int16Array]",Qse="[object Int32Array]",Kse="[object Uint8Array]",Wse="[object Uint8ClampedArray]",$se="[object Uint16Array]",Yse="[object Uint32Array]",Jse=/[\\^$.*+?()[\]{}|]/g,Xse=/^\[object .+?Constructor\]$/,Zse=/^(?:0|[1-9]\d*)$/,Mt={};Mt[Hse]=Mt[Gse]=Mt[jse]=Mt[zse]=Mt[Qse]=Mt[Kse]=Mt[Wse]=Mt[$se]=Mt[Yse]=!0;Mt[Ty]=Mt[I_]=Mt[kL]=Mt[BL]=Mt[Ny]=Mt[ML]=Mt[LL]=Mt[FL]=Mt[_y]=Mt[UL]=Mt[gl]=Mt[qL]=Mt[Cy]=Mt[VL]=Mt[T_]=!1;var HL=typeof global=="object"&&global&&global.Object===Object&&global,eoe=typeof self=="object"&&self&&self.Object===Object&&self,Xs=HL||eoe||Function("return this")(),GL=typeof Jh=="object"&&Jh&&!Jh.nodeType&&Jh,bL=GL&&typeof pl=="object"&&pl&&!pl.nodeType&&pl,jL=bL&&bL.exports===GL,E_=jL&&HL.process,SL=function(){try{return E_&&E_.binding&&E_.binding("util")}catch{}}(),IL=SL&&SL.isTypedArray;function toe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function Doe(t,e){var r=this.__data__,n=By(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}Zs.prototype.clear=Coe;Zs.prototype.delete=Noe;Zs.prototype.get=xoe;Zs.prototype.has=Ooe;Zs.prototype.set=Doe;function au(t){var e=-1,r=t==null?0:t.length;for(this.clear();++eu))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,w=r&PL?new Oy:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=RL}function ZL(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ed(t){return t!=null&&typeof t=="object"}var eF=IL?soe(IL):Woe;function uae(t){return oae(t)?joe(t):$oe(t)}function cae(){return[]}function lae(){return!1}pl.exports=aae});var P_=B((HIe,rF)=>{h();rF.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},a=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:a,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return u[f.toLowerCase()]},has:function(f){return f.toLowerCase()in u}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,w){s.push(d=d.toLowerCase()),o.push([d,w]),u[d]=u[d]?u[d]+","+w:w}),r(a())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var iF=B((jIe,nF)=>{h();nF.exports=self.fetch||(self.fetch=P_().default||P_())});var fU=B(de=>{"use strict";h();Object.defineProperty(de,"__esModule",{value:!0});var cu=Ds(),fae=(nP(),_e(rP)),id=AP(),yt=(CS(),_e(_S)),ws=QS(),sF=(xc(),_e(eP)),hae=(aB(),_e(oB)),ne=Qh(),dae=(tT(),_e(eT)),Oe=Qa(),gae=(dL(),_e(hL)),an=(Yh(),_e(Fr)),pae=(AL(),_e(vL)),mae=tF(),yae=iF();function sd(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function wae(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var vae=sd(cu),Aae=sd(fae),Ly=wae(hae),Eae=sd(pae),bae=sd(mae),Sae=sd(yae);function Iae(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var Tae=Iae,_ae=Tae,bF=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Cae=t=>new TextEncoder().encode(t),Nae=t=>new TextDecoder().decode(t),M_=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},L_=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SF(this,e)}},F_=class{constructor(e){this.decoders=e}or(e){return SF(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SF=(t,e)=>new F_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),U_=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new M_(e,r,n),this.decoder=new L_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Jy=({name:t,prefix:e,encode:r,decode:n})=>new U_(t,e,r,n),od=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=_ae(r,e);return Jy({prefix:t,name:e,encode:n,decode:s=>bF(i(s))})},xae=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},Oae=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<Jy({prefix:e,name:t,encode(i){return Oae(i,n,r)},decode(i){return xae(i,n,r,t)}}),Dae=Jy({prefix:"\0",name:"identity",encode:t=>Nae(t),decode:t=>Cae(t)}),Pae=Object.freeze({__proto__:null,identity:Dae}),Rae=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Bae=Object.freeze({__proto__:null,base2:Rae}),Mae=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Lae=Object.freeze({__proto__:null,base8:Mae}),Fae=od({prefix:"9",name:"base10",alphabet:"0123456789"}),Uae=Object.freeze({__proto__:null,base10:Fae}),qae=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vae=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),kae=Object.freeze({__proto__:null,base16:qae,base16upper:Vae}),Hae=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gae=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jae=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zae=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qae=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kae=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wae=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$ae=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yae=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Jae=Object.freeze({__proto__:null,base32:Hae,base32upper:Gae,base32pad:jae,base32padupper:zae,base32hex:Qae,base32hexupper:Kae,base32hexpad:Wae,base32hexpadupper:$ae,base32z:Yae}),Xae=od({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zae=od({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),eue=Object.freeze({__proto__:null,base36:Xae,base36upper:Zae}),tue=od({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rue=od({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),nue=Object.freeze({__proto__:null,base58btc:tue,base58flickr:rue}),iue=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sue=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oue=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aue=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),uue=Object.freeze({__proto__:null,base64:iue,base64pad:sue,base64url:oue,base64urlpad:aue}),IF=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),cue=IF.reduce((t,e,r)=>(t[r]=e,t),[]),lue=IF.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fue(t){return t.reduce((e,r)=>(e+=cue[r],e),"")}function hue(t){let e=[];for(let r of t){let n=lue[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var due=Jy({prefix:"\u{1F680}",name:"base256emoji",encode:fue,decode:hue}),gue=Object.freeze({__proto__:null,base256emoji:due}),pue=TF,oF=128,mue=127,yue=~mue,wue=Math.pow(2,31);function TF(t,e,r){e=e||[],r=r||0;for(var n=r;t>=wue;)e[r++]=t&255|oF,t/=128;for(;t&yue;)e[r++]=t&255|oF,t>>>=7;return e[r]=t|0,TF.bytes=r-n+1,e}var vue=q_,Aue=128,aF=127;function q_(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw q_.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&aF)<=Aue);return q_.bytes=s-n,r}var Eue=Math.pow(2,7),bue=Math.pow(2,14),Sue=Math.pow(2,21),Iue=Math.pow(2,28),Tue=Math.pow(2,35),_ue=Math.pow(2,42),Cue=Math.pow(2,49),Nue=Math.pow(2,56),xue=Math.pow(2,63),Oue=function(t){return t(_F.encode(t,e,r),e),cF=t=>_F.encodingLength(t),V_=(t,e)=>{let r=e.byteLength,n=cF(t),i=n+cF(r),s=new Uint8Array(i+r);return uF(t,s,0),uF(r,s,n),s.set(e,i),new k_(t,r,e,s)},k_=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},CF=({name:t,code:e,encode:r})=>new H_(t,e,r),H_=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?V_(this.code,r):r.then(n=>V_(this.code,n))}else throw Error("Unknown type, must be binary type")}},NF=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pue=CF({name:"sha2-256",code:18,encode:NF("SHA-256")}),Rue=CF({name:"sha2-512",code:19,encode:NF("SHA-512")}),Bue=Object.freeze({__proto__:null,sha256:Pue,sha512:Rue}),xF=0,Mue="identity",OF=bF,Lue=t=>V_(xF,OF(t)),Fue={code:xF,name:Mue,encode:OF,digest:Lue},Uue=Object.freeze({__proto__:null,identity:Fue});new TextEncoder,new TextDecoder;var lF={...Pae,...Bae,...Lae,...Uae,...kae,...Jae,...eue,...nue,...uue,...gue};({...Bue,...Uue});function DF(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function que(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?DF(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function PF(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var fF=PF("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),R_=PF("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=que(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Vy=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=LF,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=Ly.generateKeyPair(i);return Ly.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=ne.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=Ly.generateKeyPair(s),u=ne.generateRandomBytes32(),a=FF;return await Ly.signJWT(u,i,a,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let u=this.getPrivateKey(i),a=ne.deriveSymKey(u,s);return this.setSymKey(a,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||ne.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let u=ne.validateEncoding(o),a=sF.safeJsonStringify(s);if(ne.isTypeOneEnvelope(u)){let w=u.senderPublicKey,A=u.receiverPublicKey;i=await this.generateSharedKey(w,A)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=u;return ne.encrypt({type:f,symKey:c,message:a,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let u=ne.validateDecoding(s,o);if(ne.isTypeOneEnvelope(u)){let a=u.receiverPublicKey,c=u.senderPublicKey;i=await this.generateSharedKey(a,c)}try{let a=this.getSymKey(i),c=ne.decrypt({symKey:a,encoded:s});return sF.safeJsonParse(c)}catch(a){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(a)}},this.getPayloadType=i=>{let s=ne.deserialize(i);return ne.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=ne.deserialize(i);return s.senderPublicKey?dae.toString(s.senderPublicKey,ne.BASE16):void 0},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.keychain=n||new qy(this.core,this.logger)}get context(){return yt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(G_)}catch{e=ne.generateRandomBytes32(),await this.keychain.set(G_,e)}return kue(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},ky=class extends ws.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=VF,this.version=kF,this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=ne.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=ne.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=yt.generateChildLogger(e,this.name),this.core=r}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},z_=class extends ws.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new cu.EventEmitter,this.name=GF,this.queue=new Map,this.publishTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.failedPublishTimeout=Oe.toMiliseconds(Oe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});let u=s?.ttl||HF,a=ne.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||an.getBigIntRpcId().toString(),w={topic:n,message:i,opts:{ttl:u,relay:a,prompt:c,tag:f,id:d}},A=`Failed to publish payload, please try again. id:${d} tag:${f}`,T=Date.now(),x,R=1;try{for(;x===void 0;){if(Date.now()-T>this.publishTimeout)throw new Error(A);this.logger.trace({id:d,attempts:R},`publisher.publish - attempt ${R}`),x=await await ne.createExpiringPromise(this.rpcPublish(n,i,u,a,c,f,d).catch(V=>this.logger.warn(V)),this.publishTimeout,A),R++,x||await new Promise(V=>setTimeout(V,this.failedPublishTimeout))}this.relayer.events.emit(Zn.publish,w),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}})}catch(V){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(V),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw V;this.queue.set(d,w)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return yt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,u){var a,c,f,d;let w={method:ne.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:u};return ne.isUndefined((a=w.params)==null?void 0:a.prompt)&&((c=w.params)==null||delete c.prompt),ne.isUndefined((f=w.params)==null?void 0:f.tag)&&((d=w.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w}),this.relayer.request(w)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Zn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Zn.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},Q_=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Que=Object.defineProperty,Kue=Object.defineProperties,Wue=Object.getOwnPropertyDescriptors,hF=Object.getOwnPropertySymbols,$ue=Object.prototype.hasOwnProperty,Yue=Object.prototype.propertyIsEnumerable,dF=(t,e,r)=>e in t?Que(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rd=(t,e)=>{for(var r in e||(e={}))$ue.call(e,r)&&dF(t,r,e[r]);if(hF)for(var r of hF(e))Yue.call(e,r)&&dF(t,r,e[r]);return t},B_=(t,e)=>Kue(t,Wue(e)),Hy=class extends ws.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new Q_,this.events=new cu.EventEmitter,this.name=ZF,this.version=eU,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=eo,this.subscribeTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=ne.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let u=await this.rpcSubscribe(n,s);return typeof u=="string"&&(this.onSubscribe(u,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;let i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((s,o)=>{let u=new Oe.Watch;u.start(i);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),u.stop(i),s(!0)),u.elapsed(i)>=tU&&(clearInterval(a),u.stop(i),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.clientId=""}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=ne.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=ne.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:ne.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?ne.hashMessage(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Zn.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:ne.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(Zn.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:ne.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,B_(rd({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rd({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rd({},r)),this.topicMap.set(r.topic,e),this.events.emit(_i.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(_i.deleted,B_(rd({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_i.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);ne.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>B_(rd({},e[i]),{id:n})))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(_i.created,async e=>{let r=_i.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(_i.deleted,async e=>{let r=_i.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},Jue=Object.defineProperty,gF=Object.getOwnPropertySymbols,Xue=Object.prototype.hasOwnProperty,Zue=Object.prototype.propertyIsEnumerable,pF=(t,e,r)=>e in t?Jue(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ece=(t,e)=>{for(var r in e||(e={}))Xue.call(e,r)&&pF(t,r,e[r]);if(gF)for(var r of gF(e))Zue.call(e,r)&&pF(t,r,e[r]);return t},Gy=class extends ws.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new cu.EventEmitter,this.name=QF,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Oe.toMiliseconds(Oe.THIRTY_SECONDS+Oe.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");let s=r.id||an.getBigIntRpcId().toString();await this.toEstablishConnection();try{let o=this.provider.request(r);this.requestsInFlight.set(s,{promise:o,request:r}),this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");let u=await new Promise(async(a,c)=>{let f=()=>{c(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(yn.disconnect,f);let d=await o;this.provider.off(yn.disconnect,f),a(d)});return this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),u}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(ne.isNode())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(Zn.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Zn.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(yn.payload,this.onPayloadHandler),this.provider.on(yn.connect,this.onConnectHandler),this.provider.on(yn.disconnect,this.onDisconnectHandler),this.provider.on(yn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?yt.generateChildLogger(e.logger,this.name):yt.pino(yt.getDefaultLoggerOptions({level:e.logger||zF})),this.messages=new ky(this.logger,e.core),this.subscriber=new Hy(this,this.logger),this.publisher=new z_(this,this.logger),this.relayUrl=e?.relayUrl||W_,this.projectId=e.projectId,this.bundleId=ne.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${j_}...`),await this.restartTransport(j_)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},YF)}get context(){return yt.getLoggerContext(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",s,o=u=>{u.topic===e&&(this.subscriber.off(_i.created,o),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(_i.created,o)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,r)||i,u()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await ne.createExpiringPromise(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect(),await this.createProvider()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{let i=()=>{this.provider.off(yn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(yn.disconnect,i),await ne.createExpiringPromise(this.provider.connect(),Oe.toMiliseconds(Oe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{n(s)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ne.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}startPingTimeout(){var e,r,n,i,s;if(ne.isNode())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new gae.JsonRpcProvider(new Eae.default(ne.formatRelayRpcUrl({sdkVersion:$F,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),an.isJsonRpcRequest(e)){if(!e.method.endsWith(KF))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ece({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else an.isJsonRpcResponse(e)&&this.events.emit(Zn.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Zn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=an.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(yn.payload,this.onPayloadHandler),this.provider.off(yn.connect,this.onConnectHandler),this.provider.off(yn.disconnect,this.onDisconnectHandler),this.provider.off(yn.error,this.onProviderErrorHandler)}async registerEventListeners(){let e=await ne.isOnline();ne.subscribeToNetworkChange(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.events.emit(Zn.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Oe.toMiliseconds(WF))}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}},tce=Object.defineProperty,mF=Object.getOwnPropertySymbols,rce=Object.prototype.hasOwnProperty,nce=Object.prototype.propertyIsEnumerable,yF=(t,e,r)=>e in t?tce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wF=(t,e)=>{for(var r in e||(e={}))rce.call(e,r)&&yF(t,r,e[r]);if(mF)for(var r of mF(e))nce.call(e,r)&&yF(t,r,e[r]);return t},jy=class extends ws.IStore{constructor(e,r,n,i=eo,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=JF,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ne.isUndefined(o)?this.map.set(this.getKey(o),o):ne.isProposalStruct(o)?this.map.set(o.id,o):ne.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,u)=>{this.isInitialized(),this.map.has(o)?await this.update(o,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:u}),this.map.set(o,u),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(u=>Object.keys(o).every(a=>bae.default(u[a],o[a]))):this.values),this.update=async(o,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:u});let a=wF(wF({},this.getData(o)),u);this.map.set(o,a),await this.persist()},this.delete=async(o,u)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:u}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())},this.logger=yt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},zy=class{constructor(e,r){this.core=e,this.logger=r,this.name=rU,this.version=nU,this.events=new vae.default,this.initialized=!1,this.storagePrefix=eo,this.ignoredPayloadTypes=[ne.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let i=ne.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),o=ne.calcExpiry(Oe.FIVE_MINUTES),u={protocol:jF},a={topic:s,expiry:o,relay:u,active:!1},c=ne.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:u,expiryTimestamp:o,methods:n?.methods});return await this.pairings.set(s,a),await this.core.relayer.subscribe(s),this.core.expirer.set(s,o),{topic:s,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o,expiryTimestamp:u,methods:a}=ne.parseUri(n.uri),c;if(this.pairings.keys.includes(i)&&(c=this.pairings.get(i),c.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let f=u||ne.calcExpiry(Oe.FIVE_MINUTES),d={topic:i,relay:o,expiry:f,active:!1,methods:a};return await this.pairings.set(i,d),this.core.expirer.set(i,f),n.activatePairing&&await this.activate({topic:i}),this.events.emit(nd.create,d),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),d},this.activate=async({topic:n})=>{this.isInitialized();let i=ne.calcExpiry(Oe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:u,reject:a}=ne.createDelayedPromise();this.events.once(ne.engineEvent("pairing_ping",s),({error:c})=>{c?a(c):u()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ne.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=an.formatJsonRpcRequest(i,s),u=await this.core.crypto.encode(n,o),a=yl[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,u,a),o.id},this.sendResult=async(n,i,s)=>{let o=an.formatJsonRpcResult(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method].res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=an.formatJsonRpcError(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method]?yl[a.request.method].res:yl.unregistered_method.res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,ne.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>ne.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(nd.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{an.isJsonRpcResult(i)?this.events.emit(ne.engineEvent("pairing_ping",s),{}):an.isJsonRpcError(i)&&this.events.emit(ne.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(nd.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let u=ne.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,u),this.logger.error(u)}catch(u){await this.sendError(s,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(ne.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!ne.isValidParams(n)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!ne.isValidUrl(n.uri)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=ne.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(s!=null&&s.expiryTimestamp&&Oe.toMiliseconds(s?.expiryTimestamp){if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ne.isValidString(n,!1)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=ne.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ne.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=ne.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.pairings=new jy(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Zn.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{an.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):an.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Xn.expired,async e=>{let{topic:r}=ne.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(nd.expire,{topic:r}))})}},Qy=class extends ws.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new cu.EventEmitter,this.name=iU,this.version=sU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:ne.calcExpiry(Oe.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=an.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Jn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Jn.deleted,s)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:an.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jn.created,e=>{let r=Jn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.updated,e=>{let r=Jn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.deleted,e=>{let r=Jn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Oe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Jn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ky=class extends ws.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new cu.EventEmitter,this.name=oU,this.version=aU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Xn.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Xn.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ne.formatTopicTarget(e);if(typeof e=="number")return ne.formatIdTarget(e);let{message:r}=ne.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Xn.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Oe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Xn.created,e=>{let r=Xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.expired,e=>{let r=Xn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.deleted,e=>{let r=Xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wy=class extends ws.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=Fy,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||ne.isReactNative()||!ne.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Uy;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,Uy)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Oe.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{let o=document.getElementById(Fy);if(o)return this.iframe=o,this.onInit(),s();window.addEventListener("message",i);let u=document.createElement("iframe");u.id=Fy,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Oe.toMiliseconds(Oe.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||wl;return uU.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${wl}`),i=wl),i},this.logger=yt.generateChildLogger(r,this.name),this.verifyUrl=wl,this.abortController=new AbortController,this.isDevEnv=ne.isNode()&&I.default.env.IS_VITEST}get context(){return yt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Oe.toMiliseconds(e))}},$y=class extends ws.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=cU,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:u=!1}=n,a=`${lU}/${this.projectId}/clients`;await Sae.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:u})})},this.logger=yt.generateChildLogger(r,this.context)}},ice=Object.defineProperty,vF=Object.getOwnPropertySymbols,sce=Object.prototype.hasOwnProperty,oce=Object.prototype.propertyIsEnumerable,AF=(t,e,r)=>e in t?ice(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,EF=(t,e)=>{for(var r in e||(e={}))sce.call(e,r)&&AF(t,r,e[r]);if(vF)for(var r of vF(e))oce.call(e,r)&&AF(t,r,e[r]);return t},Yy=class t extends ws.ICore{constructor(e){var r;super(e),this.protocol=K_,this.version=RF,this.name=Xy,this.events=new cu.EventEmitter,this.initialized=!1,this.on=(o,u)=>this.events.on(o,u),this.once=(o,u)=>this.events.once(o,u),this.off=(o,u)=>this.events.off(o,u),this.removeListener=(o,u)=>this.events.removeListener(o,u),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||W_,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let n=yt.getDefaultLoggerOptions({level:typeof e?.logger=="string"&&e.logger?e.logger:BF.logger}),{logger:i,chunkLoggerController:s}=yt.generatePlatformLogger({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,u;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=yt.generateChildLogger(i,this.name),this.heartbeat=new id.HeartBeat,this.crypto=new Vy(this,this.logger,e?.keychain),this.history=new Qy(this,this.logger),this.expirer=new Ky(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Aae.default(EF(EF({},MF),e?.storageOptions)),this.relayer=new Gy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new zy(this,this.logger),this.verify=new Wy(this.projectId||"",this.logger),this.echoClient=new $y(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(XF,n),r}get context(){return yt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},ace=Yy;de.CORE_CONTEXT=Xy,de.CORE_DEFAULT=BF,de.CORE_PROTOCOL=K_,de.CORE_STORAGE_OPTIONS=MF,de.CORE_STORAGE_PREFIX=eo,de.CORE_VERSION=RF,de.CRYPTO_CLIENT_SEED=G_,de.CRYPTO_CONTEXT=LF,de.CRYPTO_JWT_TTL=FF,de.Core=ace,de.Crypto=Vy,de.ECHO_CONTEXT=cU,de.ECHO_URL=lU,de.EXPIRER_CONTEXT=oU,de.EXPIRER_DEFAULT_TTL=zue,de.EXPIRER_EVENTS=Xn,de.EXPIRER_STORAGE_VERSION=aU,de.EchoClient=$y,de.Expirer=Ky,de.HISTORY_CONTEXT=iU,de.HISTORY_EVENTS=Jn,de.HISTORY_STORAGE_VERSION=sU,de.JsonRpcHistory=Qy,de.KEYCHAIN_CONTEXT=UF,de.KEYCHAIN_STORAGE_VERSION=qF,de.KeyChain=qy,de.MESSAGES_CONTEXT=VF,de.MESSAGES_STORAGE_VERSION=kF,de.MessageTracker=ky,de.PAIRING_CONTEXT=rU,de.PAIRING_DEFAULT_TTL=jue,de.PAIRING_EVENTS=nd,de.PAIRING_RPC_OPTS=yl,de.PAIRING_STORAGE_VERSION=nU,de.PENDING_SUB_RESOLUTION_TIMEOUT=tU,de.PUBLISHER_CONTEXT=GF,de.PUBLISHER_DEFAULT_TTL=HF,de.Pairing=zy,de.RELAYER_CONTEXT=QF,de.RELAYER_DEFAULT_LOGGER=zF,de.RELAYER_DEFAULT_PROTOCOL=jF,de.RELAYER_DEFAULT_RELAY_URL=W_,de.RELAYER_EVENTS=Zn,de.RELAYER_FAILOVER_RELAY_URL=j_,de.RELAYER_PROVIDER_EVENTS=yn,de.RELAYER_RECONNECT_TIMEOUT=WF,de.RELAYER_SDK_VERSION=$F,de.RELAYER_STORAGE_OPTIONS=Hue,de.RELAYER_SUBSCRIBER_SUFFIX=KF,de.RELAYER_TRANSPORT_CUTOFF=YF,de.Relayer=Gy,de.STORE_STORAGE_VERSION=JF,de.SUBSCRIBER_CONTEXT=ZF,de.SUBSCRIBER_DEFAULT_TTL=Gue,de.SUBSCRIBER_EVENTS=_i,de.SUBSCRIBER_STORAGE_VERSION=eU,de.Store=jy,de.Subscriber=Hy,de.TRUSTED_VERIFY_URLS=uU,de.VERIFY_CONTEXT=Fy,de.VERIFY_FALLBACK_SERVER=Uy,de.VERIFY_SERVER=wl,de.Verify=Wy,de.WALLETCONNECT_CLIENT_ID=XF,de.default=Yy});var CU=B(Be=>{"use strict";h();Object.defineProperty(Be,"__esModule",{value:!0});var un=fU(),Zy=(CS(),_e(_S)),gU=QS(),G=Qh(),pU=Ds(),Dt=Qa(),qe=(Yh(),_e(Fr));function uce(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var cce=uce(pU),n2="wc",i2=2,s2="client",i1=`${n2}@${i2}:${s2}:`,e1={name:s2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},lce={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},fce={database:":memory:"},$_="WALLETCONNECT_DEEPLINK_CHOICE",hce={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},dce="history",gce="0.3",mU="proposal",pce=Dt.THIRTY_DAYS,yU="Proposal expired",wU="session",lu=Dt.SEVEN_DAYS,vU="engine",wn={wc_sessionPropose:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Dt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Dt.ONE_HOUR,prompt:!1,tag:1117}}},t1={min:Dt.FIVE_MINUTES,max:Dt.SEVEN_DAYS},vs={idle:"IDLE",active:"ACTIVE"},AU="request",EU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],bU="wc",mce=1.5,SU="auth",IU="authKeys",TU="pairingTopics",_U="requests",ud=`${bU}@${1.5}:${SU}:`,ad=`${ud}:PUB_KEY`,yce=Object.defineProperty,wce=Object.defineProperties,vce=Object.getOwnPropertyDescriptors,hU=Object.getOwnPropertySymbols,Ace=Object.prototype.hasOwnProperty,Ece=Object.prototype.propertyIsEnumerable,dU=(t,e,r)=>e in t?yce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e)=>{for(var r in e||(e={}))Ace.call(e,r)&&dU(t,r,e[r]);if(hU)for(var r of hU(e))Ece.call(e,r)&&dU(t,r,e[r]);return t},vl=(t,e)=>wce(t,vce(e)),Y_=class extends gU.IEngine{constructor(e){super(e),this.name=vU,this.events=new cce.default,this.initialized=!1,this.requestQueue={state:vs.idle,queue:[]},this.sessionRequestQueue={state:vs.idle,queue:[]},this.requestQueueDelay=Dt.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=vl(br({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:u,relays:a}=n,c=i,f,d=!1;try{c&&(d=this.client.core.pairing.pairings.get(c).active)}catch(L){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),L}if(!c||!d){let{topic:L,uri:k}=await this.client.core.pairing.create();c=L,f=k}if(!c){let{message:L}=G.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(L)}let w=await this.client.core.crypto.generateKeyPair(),A=wn.wc_sessionPropose.req.ttl||Dt.FIVE_MINUTES,T=G.calcExpiry(A),x=br({requiredNamespaces:s,optionalNamespaces:o,relays:a??[{protocol:un.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:T},u&&{sessionProperties:u}),{reject:R,resolve:V,done:U}=G.createDelayedPromise(A,yU);this.events.once(G.engineEvent("session_connect"),async({error:L,session:k})=>{if(L)R(L);else if(k){k.self.publicKey=w;let H=vl(br({},k),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:k.peer.metadata}),V(H)}});let Q=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:x,throwOnFailedPublish:!0});return await this.setProposal(Q,br({id:Q},x)),{uri:f,approval:U}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),U}let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o,sessionConfig:u}=r,a;try{a=this.client.proposal.get(n)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),U}let{pairingTopic:c,proposer:f,requiredNamespaces:d,optionalNamespaces:w}=a;c=c||"";let A=await this.client.core.crypto.generateKeyPair(),T=f.publicKey,x=await this.client.core.crypto.generateSharedKey(A,T),R=br(br({relay:{protocol:i??"irn"},namespaces:s,pairingTopic:c,controller:{publicKey:A,metadata:this.client.metadata},expiry:G.calcExpiry(lu)},o&&{sessionProperties:o}),u&&{sessionConfig:u});await this.client.core.relayer.subscribe(x);let V=vl(br({},R),{topic:x,requiredNamespaces:d,optionalNamespaces:w,pairingTopic:c,acknowledged:!1,self:R.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A});await this.client.session.set(x,V);try{await this.sendResult({id:n,topic:c,result:{relay:{protocol:i??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:R,throwOnFailedPublish:!0})}catch(U){throw this.client.logger.error(U),this.client.session.delete(x,G.getSdkError("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),U}return await this.client.core.pairing.updateMetadata({topic:c,metadata:f.metadata}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}),await this.setExpiry(x,G.calcExpiry(lu)),{topic:x,acknowledged:()=>new Promise(U=>setTimeout(()=>U(this.client.session.get(x)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}let{id:n,reason:i}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}let{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:u}=G.createDelayedPromise(),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),f=this.client.session.get(n).namespaces;return this.events.once(G.engineEvent("session_update",a),({error:d})=>{d?u(d):o()}),await this.client.session.update(n,{namespaces:i}),this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:f}),u(d)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}let{topic:n}=r,i=qe.payloadId(),{done:s,resolve:o,reject:u}=G.createDelayedPromise();return this.events.once(G.engineEvent("session_extend",i),({error:a})=>{a?u(a):o()}),await this.setExpiry(n,G.calcExpiry(lu)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(a=>{u(a)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(A){throw this.client.logger.error("request() -> isValidRequest() failed"),A}let{chainId:n,request:i,topic:s,expiry:o=wn.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),{done:f,resolve:d,reject:w}=G.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(G.engineEvent("session_request",a),({error:A,result:T})=>{A?w(A):d(T)}),await Promise.all([new Promise(async A=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:s,method:"wc_sessionRequest",params:{request:vl(br({},i),{expiryTimestamp:G.calcExpiry(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(T=>w(T)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),A()}),new Promise(async A=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){let x=await G.getDeepLink(this.client.core.storage,$_);G.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:x})}A()}),f()]).then(A=>A[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;qe.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):qe.isJsonRpcError(i)&&await this.sendError({id:s,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=qe.payloadId(),s=qe.getBigIntRpcId().toString(),{done:o,resolve:u,reject:a}=G.createDelayedPromise();this.events.once(G.engineEvent("session_ping",i),({error:c})=>{c?a(c):u()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r,o=qe.getBigIntRpcId().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:G.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:i}=G.getInternalError("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>G.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);let{chains:n,statement:i="",uri:s,domain:o,nonce:u,type:a,exp:c,nbf:f,methods:d=[]}=r,w=[...r.resources||[]],{topic:A,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:T}});let x=await this.client.core.crypto.generateKeyPair(),R=G.hashKey(x);if(await Promise.all([this.client.auth.authKeys.set(ad,{responseTopic:R,publicKey:x}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:A})]),await this.client.core.relayer.subscribe(R),this.client.logger.info(`sending request to new pairing topic: ${A}`),d.length>0){let{namespace:P}=G.parseChainId(n[0]),l=G.createEncodedRecap(P,"request",d);G.getRecapFromResources(w)&&(l=G.mergeEncodedRecaps(l,w.pop())),w.push(l)}let V=G.calcExpiry(wn.wc_sessionPropose.req.ttl),U={authPayload:{type:a??"caip122",chains:n,statement:i,aud:s,domain:o,version:"1",nonce:u,iat:new Date().toISOString(),exp:c,nbf:f,resources:w},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},Q={eip155:{chains:n,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},L={requiredNamespaces:{},optionalNamespaces:Q,relays:[{protocol:"irn"}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},{done:k,resolve:H,reject:q}=G.createDelayedPromise(wn.wc_sessionAuthenticate.req.ttl,"Request expired"),v=async({error:P,session:l})=>{if(this.events.off(G.engineEvent("session_request",D),C),P)q(P);else if(l){l.self.publicKey=x,await this.client.session.set(l.topic,l),await this.setExpiry(l.topic,l.expiry),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:l.peer.metadata});let g=this.client.session.get(l.topic);H({session:g})}},C=async P=>{if(P.error){let M=G.getSdkError("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===M.code?void 0:(this.events.off(G.engineEvent("session_connect"),v),q(P.error.message))}this.events.off(G.engineEvent("session_connect"),v);let{cacaos:l,responder:g}=P.result,y=[],E=[];for(let M of l){await G.validateSignedCacao({cacao:M,projectId:this.client.core.projectId})||(this.client.logger.error(M,"Signature verification failed"),q(G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:N}=M,m=G.getRecapFromResources(N.resources),O=[G.getNamespacedDidChainId(N.iss)],Y=G.getDidAddress(N.iss);if(m){let $=G.getMethodsFromRecap(m),b=G.getChainsFromRecap(m);y.push(...$),O.push(...b)}for(let $ of O)E.push(`${$}:${Y}`)}let S=await this.client.core.crypto.generateSharedKey(x,g.publicKey),_;y.length>0&&(_={topic:S,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:g,controller:g.publicKey,expiry:G.calcExpiry(lu),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:G.buildNamespacesFromAuth([...new Set(y)],[...new Set(E)])},await this.client.core.relayer.subscribe(S),await this.client.session.set(S,_),_=this.client.session.get(S)),H({auths:l,session:_})},D=qe.payloadId(),F=qe.payloadId();this.events.once(G.engineEvent("session_connect"),v),this.events.once(G.engineEvent("session_request",D),C);try{await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:D}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:L,expiry:wn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:F})])}catch(P){throw this.events.off(G.engineEvent("session_connect"),v),this.events.off(G.engineEvent("session_request",D),C),P}return await this.setProposal(F,br({id:F},L)),await this.client.auth.requests.set(D,{authPayload:U.authPayload,requester:U.requester,expiryTimestamp:V,id:D,pairingTopic:A,verifyContext:{}}),{uri:T,response:k}},this.approveSessionAuthenticate=async r=>{this.isInitialized();let{id:n,auths:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u},f=[],d=[];for(let T of i){if(!await G.validateSignedCacao({cacao:T,projectId:this.client.core.projectId})){let Q=G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:a,error:Q,encodeOpts:c}),new Error(Q.message)}let{p:x}=T,R=G.getRecapFromResources(x.resources),V=[G.getNamespacedDidChainId(x.iss)],U=G.getDidAddress(x.iss);if(R){let Q=G.getMethodsFromRecap(R),L=G.getChainsFromRecap(R);f.push(...Q),V.push(...L)}for(let Q of V)d.push(`${Q}:${U}`)}let w=await this.client.core.crypto.generateSharedKey(u,o),A;return f?.length>0&&(A={topic:w,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:o,metadata:s.requester.metadata},controller:o,expiry:G.calcExpiry(lu),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:G.buildNamespacesFromAuth([...new Set(f)],[...new Set(d)])},await this.client.core.relayer.subscribe(w),await this.client.session.set(w,A)),await this.sendResult({topic:a,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:c,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fullfilled",code:0}),await this.client.core.pairing.activate({topic:s.pairingTopic}),{session:A}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();let{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u};await this.sendError({id:n,topic:a,error:i,encodeOpts:c}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:i}=r;return G.formatMessage(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,u;return((o=s.peerMetadata)==null?void 0:o.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:i=!1,emitEvent:s=!0,id:o=0}=r,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,G.getSdkError("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem($_).catch(a=>this.client.logger.warn(a)),this.getPendingSessionRequests().forEach(a=>{a.topic===n&&this.deletePendingSessionRequest(a.id,G.getSdkError("USER_DISCONNECTED"))}),s&&this.client.events.emit("session_delete",{id:o,topic:n})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,G.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=vs.idle,this.client.events.emit("session_request_expire",{id:r}))},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,G.calcExpiry(wn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async r=>{let{id:n,topic:i,params:s,verifyContext:o}=r,u=s.request.expiryTimestamp||G.calcExpiry(wn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:u,clientRpcId:a,throwOnFailedPublish:c}=r,f=qe.formatJsonRpcRequest(i,s,a);if(G.isBrowser()&&EU.includes(i)){let A=G.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:A})}let d;try{d=await this.client.core.crypto.encode(n,f)}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let w=wn[i].req;return o&&(w.ttl=o),u&&(w.id=u),this.client.core.history.set(n,f),c?(w.internal=vl(br({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(A=>this.client.logger.error(A)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:u}=r,a=qe.formatJsonRpcResult(n,s),c;try{c=await this.client.core.crypto.encode(i,a,u)}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let f;try{f=await this.client.core.history.get(i,n)}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),w}let d=wn[f.request.method].res;o?(d.internal=vl(br({},d.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,c,d)):this.client.core.relayer.publish(i,c,d).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(a)},this.sendError=async r=>{let{id:n,topic:i,error:s,encodeOpts:o}=r,u=qe.formatJsonRpcError(n,s),a;try{a=await this.client.core.crypto.encode(i,u,o)}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let c;try{c=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}let f=wn[c.request.method].res;this.client.core.relayer.publish(i,a,f),await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;G.isExpired(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{G.isExpired(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===vs.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vs.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=vs.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:s}))switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=G.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(br({},n.params));let o=i.expiryTimestamp||G.calcExpiry(wn.wc_sessionPropose.req.ttl),u=br({id:s,pairingTopic:r,expiryTimestamp:o},i);await this.setProposal(s,u);let a=G.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(a,u.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:u,verifyContext:c})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(qe.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let u=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});let a=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});let c=await this.client.core.crypto.generateSharedKey(u,a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(qe.isJsonRpcError(n)){await this.client.proposal.delete(i,G.getSdkError("USER_DISCONNECTED"));let s=G.engineEvent("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners, 954`);this.events.emit(G.engineEvent("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:u,expiry:a,namespaces:c,sessionProperties:f,pairingTopic:d,sessionConfig:w}=n.params,A=br(br({topic:r,relay:o,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:d,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},f&&{sessionProperties:f}),w&&{sessionConfig:w});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});let T=G.engineEvent("session_connect");if(this.events.listenerCount(T)===0)throw new Error(`emitting ${T} without any listeners 997`);this.events.emit(G.engineEvent("session_connect"),{session:A}),this.cleanupDuplicatePairings(A)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;qe.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(G.engineEvent("session_approve",i),{})):qe.isJsonRpcError(n)&&(await this.client.session.delete(r,G.getSdkError("USER_DISCONNECTED")),this.events.emit(G.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:G.getSdkError("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(br({topic:r},i));try{G.MemoryStore.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){throw G.MemoryStore.delete(o),a}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_update",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,G.calcExpiry(lu)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_extend",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_ping",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_ping",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(un.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:G.getSdkError("USER_DISCONNECTED")})])}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{await this.isValidRequest(br({topic:r},s));let o=G.hashMessage(JSON.stringify(qe.formatJsonRpcRequest("wc_sessionRequest",s,i))),u=this.client.session.get(r),a=await this.getVerifyContext(o,u.peer.metadata),c={id:i,topic:r,params:s,verifyContext:a};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(br({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),G.MemoryStore.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{let{requester:i,authPayload:s,expiryTimestamp:o}=n.params,u=G.hashMessage(JSON.stringify(n)),a=await this.getVerifyContext(u,this.client.metadata),c={requester:i,pairingTopic:r,id:n.id,authPayload:s,verifyContext:a,expiryTimestamp:o};await this.client.auth.requests.set(n.id,c),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vs.idle,this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{let o=s.request.id,u=G.engineEvent("session_request",o);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(G.engineEvent("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===vs.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vs.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,qe.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(a)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:u}=r;if(G.isUndefined(n)||await this.isValidPairingTopic(n),!G.isValidRelays(u,!0)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(a)}!G.isUndefined(i)&&G.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!G.isUndefined(s)&&G.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=G.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!G.isValidParams(r))throw new Error(G.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let u=this.client.proposal.get(n),a=G.isValidNamespaces(i,"approve()");if(a)throw new Error(a.message);let c=G.isConformingNamespaces(u.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!G.isValidString(s,!0)){let{message:f}=G.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!G.isValidParams(r)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!G.isValidErrorReason(i)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!G.isValidParams(r)){let{message:c}=G.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!G.isValidRelay(n)){let{message:c}=G.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let u=G.isValidController(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);let a=G.isValidNamespaces(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(G.isExpired(o)){let{message:c}=G.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(a)}let{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=G.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let u=G.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(a)}let{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:u}=this.client.session.get(n);if(!G.isValidNamespacesChainId(u,s)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(a)}if(!G.isValidRequest(i)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(a)}if(!G.isValidNamespacesRequest(u,s,i.method)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(a)}if(o&&!G.isValidRequestExpiry(o,t1)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${t1.min} and ${t1.max}`);throw new Error(a)}},this.isValidRespond=async r=>{var n;if(!G.isValidParams(r)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!G.isValidResponse(s)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!G.isValidParams(r)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!G.isValidNamespacesChainId(o,s)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!G.isValidEvent(i)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!G.isValidNamespacesEvent(o,s,i.name)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!G.isValidString(i,!1))throw new Error("uri is required parameter");if(!G.isValidString(s,!1))throw new Error("domain is required parameter");if(!G.isValidString(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(a=>G.parseChainId(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:u}=G.parseChainId(n[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||un.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!G.isValidString(i,!1)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0,s=this.recentlyDeletedLimit/2;for(let o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){let{message:e}=G.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(un.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(ad)?this.client.auth.authKeys.get(ad):{responseTopic:void 0,publicKey:void 0},s=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{qe.isJsonRpcRequest(s)?(this.client.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):qe.isJsonRpcResponse(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.client.core.history.delete(r,s.id)):this.onRelayEventUnknownPayload({topic:r,payload:s})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(un.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=G.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,G.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(un.PAIRING_EVENTS.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(un.PAIRING_EVENTS.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=G.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:r}=G.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(G.isValidString(e,!1)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!G.isValidId(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:r}=G.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},J_=class extends un.Store{constructor(e,r){super(e,r,mU,i1),this.core=e,this.logger=r}},r1=class extends un.Store{constructor(e,r){super(e,r,wU,i1),this.core=e,this.logger=r}},X_=class extends un.Store{constructor(e,r){super(e,r,AU,i1,n=>n.id),this.core=e,this.logger=r}},Z_=class extends un.Store{constructor(e,r){super(e,r,IU,ud,()=>ad),this.core=e,this.logger=r}},e2=class extends un.Store{constructor(e,r){super(e,r,TU,ud),this.core=e,this.logger=r}},t2=class extends un.Store{constructor(e,r){super(e,r,_U,ud,n=>n.id),this.core=e,this.logger=r}},r2=class{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new Z_(this.core,this.logger),this.pairingTopics=new e2(this.core,this.logger),this.requests=new t2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},n1=class t extends gU.ISignClient{constructor(e){super(e),this.protocol=n2,this.version=i2,this.name=e1.name,this.events=new pU.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||e1.name,this.metadata=e?.metadata||G.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zy.pino(Zy.getDefaultLoggerOptions({level:e?.logger||e1.logger}));this.core=e?.core||new un.Core(e),this.logger=Zy.generateChildLogger(r,this.name),this.session=new r1(this.core,this.logger),this.proposal=new J_(this.core,this.logger),this.pendingRequest=new X_(this.core,this.logger),this.engine=new Y_(this),this.auth=new r2(this.core,this.logger)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Zy.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},bce=r1,Sce=n1;Be.AUTH_CONTEXT=SU,Be.AUTH_KEYS_CONTEXT=IU,Be.AUTH_PAIRING_TOPIC_CONTEXT=TU,Be.AUTH_PROTOCOL=bU,Be.AUTH_PUBLIC_KEY_NAME=ad,Be.AUTH_REQUEST_CONTEXT=_U,Be.AUTH_STORAGE_PREFIX=ud,Be.AUTH_VERSION=mce,Be.ENGINE_CONTEXT=vU,Be.ENGINE_QUEUE_STATES=vs,Be.ENGINE_RPC_OPTS=wn,Be.HISTORY_CONTEXT=dce,Be.HISTORY_EVENTS=hce,Be.HISTORY_STORAGE_VERSION=gce,Be.METHODS_TO_VERIFY=EU,Be.PROPOSAL_CONTEXT=mU,Be.PROPOSAL_EXPIRY=pce,Be.PROPOSAL_EXPIRY_MESSAGE=yU,Be.REQUEST_CONTEXT=AU,Be.SESSION_CONTEXT=wU,Be.SESSION_EXPIRY=lu,Be.SESSION_REQUEST_EXPIRY_BOUNDARIES=t1,Be.SIGN_CLIENT_CONTEXT=s2,Be.SIGN_CLIENT_DEFAULT=e1,Be.SIGN_CLIENT_EVENTS=lce,Be.SIGN_CLIENT_PROTOCOL=n2,Be.SIGN_CLIENT_STORAGE_OPTIONS=fce,Be.SIGN_CLIENT_STORAGE_PREFIX=i1,Be.SIGN_CLIENT_VERSION=i2,Be.SessionStore=bce,Be.SignClient=Sce,Be.WALLETCONNECT_DEEPLINK_CHOICE=$_,Be.default=n1});var s1=B(Yo=>{"use strict";h();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.OptionalOperation=Yo.Operation=void 0;var Ice;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(Ice=Yo.Operation||(Yo.Operation={}));var Tce;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(Tce=Yo.OptionalOperation||(Yo.OptionalOperation={}))});var o2=B(As=>{"use strict";h();Object.defineProperty(As,"__esModule",{value:!0});As.WALLETCONNECT_SIGN_LOGIN_DELAY=As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=As.WALLETCONNECT_MULTIVERSX_METHODS=As.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var NU=s1();As.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";As.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(NU.Operation);As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(NU.OptionalOperation);As.WALLETCONNECT_SIGN_LOGIN_DELAY=500});var c2=B(Ci=>{"use strict";h();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WalletConnectV2ProviderErrorMessagesEnum=Ci.ErrBadAddress=Ci.ErrNotImplemented=Ci.Err=void 0;var cd=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ci.Err=cd;var a2=class extends cd{constructor(){super("Method not yet implemented")}};Ci.ErrNotImplemented=a2;var u2=class extends cd{constructor(e,r){super(`Bad address: ${e}`,r)}};Ci.ErrBadAddress=u2;var _ce;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(_ce=Ci.WalletConnectV2ProviderErrorMessagesEnum||(Ci.WalletConnectV2ProviderErrorMessagesEnum={}))});var f2=B(o1=>{"use strict";h();Object.defineProperty(o1,"__esModule",{value:!0});o1.Logger=void 0;var l2=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};o1.Logger=l2});var xU=B(()=>{"use strict";h();global.Buffer||(global.Buffer=io().Buffer)});var g2=B(Al=>{"use strict";h();Object.defineProperty(Al,"__esModule",{value:!0});Al.SmartContractQueryResponse=Al.SmartContractQuery=void 0;var h2=class{constructor(e){this.contract=e.contract,this.caller=e.caller,this.value=e.value,this.function=e.function,this.arguments=e.arguments}};Al.SmartContractQuery=h2;var d2=class{constructor(e){this.function=e.function,this.returnCode=e.returnCode,this.returnMessage=e.returnMessage,this.returnDataParts=e.returnDataParts}};Al.SmartContractQueryResponse=d2});var DU=B(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});a1.QueryRunnerAdapter=void 0;var OU=Ve(),Cce=g2(),p2=class{constructor(e){this.networkProvider=e.networkProvider}async runQuery(e){let r={address:OU.Address.fromBech32(e.contract),caller:e.caller?OU.Address.fromBech32(e.caller):void 0,func:e.function,value:e.value,getEncodedArguments:()=>e.arguments.map(i=>p.Buffer.from(i).toString("hex"))},n=await this.networkProvider.queryContract(r);return new Cce.SmartContractQueryResponse({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.getReturnDataParts()})}};a1.QueryRunnerAdapter=p2});var PU=B(fu=>{"use strict";h();var Nce=fu&&fu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xce=fu&&fu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Nce(e,t,r)};Object.defineProperty(fu,"__esModule",{value:!0});xce(DU(),fu)});var RU=B(hu=>{"use strict";h();var Oce=hu&&hu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dce=hu&&hu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Oce(e,t,r)};Object.defineProperty(hu,"__esModule",{value:!0});Dce(JE(),hu)});var MU=B(du=>{"use strict";h();Object.defineProperty(du,"__esModule",{value:!0});du.GasEstimator=du.DefaultGasConfiguration=void 0;du.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Pce=1e5,BU=8e5,m2=class{constructor(e){this.gasConfiguration=e||du.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Pce}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+BU}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+BU)*r+this.gasConfiguration.gasPerDataByte*e}};du.GasEstimator=m2});var FU=B(LU=>{"use strict";h();Object.defineProperty(LU,"__esModule",{value:!0})});var qU=B(UU=>{"use strict";h();Object.defineProperty(UU,"__esModule",{value:!0})});var VU=B(u1=>{"use strict";h();Object.defineProperty(u1,"__esModule",{value:!0});u1.RelayedTransactionV1Builder=void 0;var y2=Ve(),Rce=Ie(),Bce=Xr(),Mce=Ms(),Lce=oE(),w2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new Rce.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${p.Buffer.from(e).toString("hex")}`,n=new Mce.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new Bce.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new y2.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new y2.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:BigInt(this.innerTransaction.getValue().toString()),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:p.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new y2.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?p.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?p.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return Lce.stringify(e)}};u1.RelayedTransactionV1Builder=w2});var HU=B(c1=>{"use strict";h();Object.defineProperty(c1,"__esModule",{value:!0});c1.RelayedTransactionV2Builder=void 0;var kU=Ie(),ld=qn(),Fce=Xr(),Uce=Ms(),v2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new kU.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new kU.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new ld.ArgSerializer().valuesToString([new ld.AddressValue(this.innerTransaction.getReceiver()),new ld.U64Value(this.innerTransaction.getNonce().valueOf()),new ld.BytesValue(this.innerTransaction.getData().valueOf()),new ld.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Uce.TransactionPayload(r),i=new Fce.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID,version:this.innerTransaction.getVersion(),options:this.innerTransaction.getOptions()});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};c1.RelayedTransactionV2Builder=v2});var GU=B(f1=>{"use strict";h();Object.defineProperty(f1,"__esModule",{value:!0});f1.SmartContractQueriesController=void 0;var qce=Ie(),Vce=g2(),l1=qn(),A2=class{constructor(e){this.abi=e.abi,this.queryRunner=e.queryRunner,this.legacyResultsParser=new l1.ResultsParser}createQuery(e){let r=this.encodeArguments(e.function,e.arguments);return new Vce.SmartContractQuery({contract:e.contract,caller:e.caller,function:e.function,arguments:r,value:e.value})}encodeArguments(e,r){let n=this.abi?.getEndpoint(e);if(n){let i=l1.NativeSerializer.nativeToTypedValues(r,n);return new l1.ArgSerializer().valuesToBuffers(i)}if(this.areArgsOfTypedValue(r))return new l1.ArgSerializer().valuesToBuffers(r);if(this.areArgsBuffers(r))return r.map(i=>p.Buffer.from(i));throw new qce.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}areArgsBuffers(e){for(let r of e)if(!ArrayBuffer.isView(r))return!1;return!0}async runQuery(e){return await this.queryRunner.runQuery(e)}parseQueryResponse(e){if(!this.abi)return e.returnDataParts;let r={returnCode:e.returnCode,returnMessage:e.returnMessage,getReturnDataParts:()=>e.returnDataParts.map(u=>p.Buffer.from(u))},n=e.function,i=this.abi.getEndpoint(n);return this.legacyResultsParser.parseQueryResponse(r,i).values.map(u=>u.valueOf())}};f1.SmartContractQueriesController=A2});var jU=B(ke=>{"use strict";h();var kce=ke&&ke.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pt=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kce(e,t,r)};Object.defineProperty(ke,"__esModule",{value:!0});xU();Pt(Ic(),ke);Pt(PU(),ke);Pt(Ve(),ke);Pt(Fb(),ke);Pt(RU(),ke);Pt(Ie(),ke);Pt(MU(),ke);Pt(FU(),ke);Pt(qU(),ke);Pt(oo(),ke);Pt(Bb(),ke);Pt($l(),ke);Pt(VU(),ke);Pt(HU(),ke);Pt(H0(),ke);Pt(GU(),ke);Pt(qn(),ke);Pt(_b(),ke);Pt(Ca(),ke);Pt(Xr(),ke);Pt(N0(),ke);Pt(Ms(),ke);Pt(V0(),ke);Pt(d0(),ke);Pt(Db(),ke);Pt(Rn(),ke)});var YU=B(ur=>{"use strict";h();var Hce=ur&&ur.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ur,"__esModule",{value:!0});ur.sleep=ur.getMetadata=ur.applyTransactionSignature=ur.getAddressFromSession=ur.addressIsValid=ur.getConnectionParams=ur.getCurrentTopic=ur.getCurrentSession=void 0;var KU=jU(),zU=Yf(),Gce=Qh(),h1=o2(),to=c2(),E2=f2(),QU=s1();function WU(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find($U(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}ur.getCurrentSession=WU;function jce(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=WU(t,e);if(!r?.topic)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}ur.getCurrentTopic=jce;function $U(t,e){var r,n,i;let s=[...h1.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(QU.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(QU.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${h1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],u=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:u}}}}ur.getConnectionParams=$U;function zce(t){try{return!KU.Address.fromBech32(t).isEmpty()}catch{return!1}}ur.addressIsValid=zce;function Qce(t){let e=t.namespaces[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}ur.getAddressFromSession=Qce;function Kce({transaction:t,response:e}){if(!e)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,u=t.getGuardian().bech32();if(u&&u!==o)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(KU.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new zU.Signature(r)),n&&t.applyGuardianSignature(new zU.Signature(n)),t}ur.applyTransactionSignature=Kce;function Wce(t){if(t)return Object.assign(Object.assign({},t),{url:Gce.getAppMetadata().url})}ur.getMetadata=Wce;function $ce(t){return Hce(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}ur.sleep=$ce});var fd=B(cn=>{"use strict";h();var tr=cn&&cn.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Yce=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WalletConnectV2Provider=cn.OptionalOperation=cn.Operation=cn.WalletConnectV2ProviderErrorMessagesEnum=void 0;var Jce=Yf(),Xce=Yce(CU()),b2=Qh(),gu=o2(),he=c2();Object.defineProperty(cn,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return he.WalletConnectV2ProviderErrorMessagesEnum}});var Me=f2(),Jo=s1();Object.defineProperty(cn,"Operation",{enumerable:!0,get:function(){return Jo.Operation}});Object.defineProperty(cn,"OptionalOperation",{enumerable:!0,get:function(){return Jo.OptionalOperation}});var xr=YU(),S2=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return tr(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:xr.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield Xce.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=xr.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Me.Logger.error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return tr(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield xr.sleep(gu.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=xr.getAddressFromSession(n),o=n.namespaces[gu.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:Jo.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:u}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!u)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:u})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||xr.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:b2.getSdkError("USER_DISCONNECTED")});else{let r=xr.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:b2.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new Jce.Signature(n))}catch{throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return xr.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];xr.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=xr.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return tr(this,void 0,void 0,function*(){return e?xr.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Me.Logger.error(`${he.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return tr(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=xr.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&xr.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:u})=>{var a;if(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)return;let{namespaces:c}=u,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>tr(this,void 0,void 0,function*(){var u;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)&&(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>tr(this,void 0,void 0,function*(){var u;!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o||(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=xr.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,u,a,c;return tr(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!b2.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(a=(u=this.walletConnector.core)===null||u===void 0?void 0:u.relayer)===null||a===void 0?void 0:a.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};cn.WalletConnectV2Provider=S2});var XU=B((RTe,JU)=>{"use strict";h();JU.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var tq=B((MTe,eq)=>{"use strict";h();var ZU=typeof Symbol<"u"&&Symbol,Zce=XU();eq.exports=function(){return typeof ZU!="function"||typeof Symbol!="function"||typeof ZU("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Zce()}});var iq=B((FTe,nq)=>{"use strict";h();var rq={foo:{}},ele=Object;nq.exports=function(){return{__proto__:rq}.foo===rq.foo&&!({__proto__:null}instanceof ele)}});var aq=B((qTe,oq)=>{"use strict";h();var tle="Function.prototype.bind called on incompatible ",rle=Object.prototype.toString,nle=Math.max,ile="[object Function]",sq=function(e,r){for(var n=[],i=0;i{"use strict";h();var ale=aq();uq.exports=Function.prototype.bind||ale});var lq=B((GTe,cq)=>{"use strict";h();var ule=Function.prototype.call,cle=Object.prototype.hasOwnProperty,lle=d1();cq.exports=lle.call(ule,cle)});var Xo=B((zTe,pq)=>{"use strict";h();var Re,Il=SyntaxError,gq=Function,Sl=TypeError,I2=function(t){try{return gq('"use strict"; return ('+t+").constructor;")()}catch{}},pu=Object.getOwnPropertyDescriptor;if(pu)try{pu({},"")}catch{pu=null}var T2=function(){throw new Sl},fle=pu?function(){try{return arguments.callee,T2}catch{try{return pu(arguments,"callee").get}catch{return T2}}}():T2,El=tq()(),hle=iq()(),Sr=Object.getPrototypeOf||(hle?function(t){return t.__proto__}:null),bl={},dle=typeof Uint8Array>"u"||!Sr?Re:Sr(Uint8Array),mu={"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":El&&Sr?Sr([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":bl,"%AsyncGenerator%":bl,"%AsyncGeneratorFunction%":bl,"%AsyncIteratorPrototype%":bl,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":gq,"%GeneratorFunction%":bl,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":El&&Sr?Sr(Sr([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!El||!Sr?Re:Sr(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!El||!Sr?Re:Sr(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":El&&Sr?Sr(""[Symbol.iterator]()):Re,"%Symbol%":El?Symbol:Re,"%SyntaxError%":Il,"%ThrowTypeError%":fle,"%TypedArray%":dle,"%TypeError%":Sl,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Sr)try{null.error}catch(t){fq=Sr(Sr(t)),mu["%Error.prototype%"]=fq}var fq,gle=function t(e){var r;if(e==="%AsyncFunction%")r=I2("async function () {}");else if(e==="%GeneratorFunction%")r=I2("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=I2("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Sr&&(r=Sr(i.prototype))}return mu[e]=r,r},hq={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},hd=d1(),g1=lq(),ple=hd.call(Function.call,Array.prototype.concat),mle=hd.call(Function.apply,Array.prototype.splice),dq=hd.call(Function.call,String.prototype.replace),p1=hd.call(Function.call,String.prototype.slice),yle=hd.call(Function.call,RegExp.prototype.exec),wle=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,vle=/\\(\\)?/g,Ale=function(e){var r=p1(e,0,1),n=p1(e,-1);if(r==="%"&&n!=="%")throw new Il("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Il("invalid intrinsic syntax, expected opening `%`");var i=[];return dq(e,wle,function(s,o,u,a){i[i.length]=u?dq(a,vle,"$1"):o||s}),i},Ele=function(e,r){var n=e,i;if(g1(hq,n)&&(i=hq[n],n="%"+i[0]+"%"),g1(mu,n)){var s=mu[n];if(s===bl&&(s=gle(n)),typeof s>"u"&&!r)throw new Sl("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Il("intrinsic "+e+" does not exist!")};pq.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Sl("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Sl('"allowMissing" argument must be a boolean');if(yle(/^%?[^%]*%?$/,e)===null)throw new Il("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Ale(e),i=n.length>0?n[0]:"",s=Ele("%"+i+"%",r),o=s.name,u=s.value,a=!1,c=s.alias;c&&(i=c[0],mle(n,ple([0,1],c)));for(var f=1,d=!0;f=n.length){var x=pu(u,w);d=!!x,d&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[w]}else d=g1(u,w),u=u[w];d&&!a&&(mu[o]=u)}}return u}});var N2=B((KTe,mq)=>{"use strict";h();var ble=Xo(),_2=ble("%Object.defineProperty%",!0),C2=function(){if(_2)try{return _2({},"a",{value:1}),!0}catch{return!1}return!1};C2.hasArrayLengthDefineBug=function(){if(!C2())return null;try{return _2([],"length",{value:1}).length!==1}catch{return!0}};mq.exports=C2});var x2=B(($Te,yq)=>{"use strict";h();var Sle=Xo(),m1=Sle("%Object.getOwnPropertyDescriptor%",!0);if(m1)try{m1([],"length")}catch{m1=null}yq.exports=m1});var Aq=B((JTe,vq)=>{"use strict";h();var Ile=N2()(),O2=Xo(),dd=Ile&&O2("%Object.defineProperty%",!0);if(dd)try{dd({},"a",{value:1})}catch{dd=!1}var Tle=O2("%SyntaxError%"),Tl=O2("%TypeError%"),wq=x2();vq.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Tl("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Tl("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Tl("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Tl("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Tl("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Tl("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,a=!!wq&&wq(e,r);if(dd)dd(e,r,{configurable:o===null&&a?a.configurable:!o,enumerable:i===null&&a?a.enumerable:!i,value:n,writable:s===null&&a?a.writable:!s});else if(u||!i&&!s&&!o)e[r]=n;else throw new Tle("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var _q=B((ZTe,Tq)=>{"use strict";h();var Iq=Xo(),Eq=Aq(),_le=N2()(),bq=x2(),Sq=Iq("%TypeError%"),Cle=Iq("%Math.floor%");Tq.exports=function(e,r){if(typeof e!="function")throw new Sq("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Cle(r)!==r)throw new Sq("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&bq){var o=bq(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(_le?Eq(e,"length",r,!0,!0):Eq(e,"length",r)),e}});var Dq=B((t_e,y1)=>{"use strict";h();var D2=d1(),_l=Xo(),Nle=_q(),xle=_l("%TypeError%"),Nq=_l("%Function.prototype.apply%"),xq=_l("%Function.prototype.call%"),Oq=_l("%Reflect.apply%",!0)||D2.call(xq,Nq),gd=_l("%Object.defineProperty%",!0),Ole=_l("%Math.max%");if(gd)try{gd({},"a",{value:1})}catch{gd=null}y1.exports=function(e){if(typeof e!="function")throw new xle("a function is required");var r=Oq(D2,xq,arguments);return Nle(r,1+Ole(0,e.length-(arguments.length-1)),!0)};var Cq=function(){return Oq(D2,Nq,arguments)};gd?gd(y1.exports,"apply",{value:Cq}):y1.exports.apply=Cq});var Mq=B((n_e,Bq)=>{"use strict";h();var Pq=Xo(),Rq=Dq(),Dle=Rq(Pq("String.prototype.indexOf"));Bq.exports=function(e,r){var n=Pq(e,!!r);return typeof n=="function"&&Dle(e,".prototype.")>-1?Rq(n):n}});var Lq=B(()=>{h()});var r7=B((u_e,t7)=>{h();var k2=typeof Map=="function"&&Map.prototype,P2=Object.getOwnPropertyDescriptor&&k2?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,v1=k2&&P2&&typeof P2.get=="function"?P2.get:null,Fq=k2&&Map.prototype.forEach,H2=typeof Set=="function"&&Set.prototype,R2=Object.getOwnPropertyDescriptor&&H2?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,A1=H2&&R2&&typeof R2.get=="function"?R2.get:null,Uq=H2&&Set.prototype.forEach,Ple=typeof WeakMap=="function"&&WeakMap.prototype,md=Ple?WeakMap.prototype.has:null,Rle=typeof WeakSet=="function"&&WeakSet.prototype,yd=Rle?WeakSet.prototype.has:null,Ble=typeof WeakRef=="function"&&WeakRef.prototype,qq=Ble?WeakRef.prototype.deref:null,Mle=Boolean.prototype.valueOf,Lle=Object.prototype.toString,Fle=Function.prototype.toString,Ule=String.prototype.match,G2=String.prototype.slice,ea=String.prototype.replace,qle=String.prototype.toUpperCase,Vq=String.prototype.toLowerCase,$q=RegExp.prototype.test,kq=Array.prototype.concat,Es=Array.prototype.join,Vle=Array.prototype.slice,Hq=Math.floor,L2=typeof BigInt=="function"?BigInt.prototype.valueOf:null,B2=Object.getOwnPropertySymbols,F2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,Cl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Ur=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Cl||!0)?Symbol.toStringTag:null,Yq=Object.prototype.propertyIsEnumerable,Gq=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function jq(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||$q.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-Hq(-t):Hq(t);if(n!==t){var i=String(n),s=G2.call(e,i.length+1);return ea.call(i,r,"$&_")+"."+ea.call(ea.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return ea.call(e,r,"$&_")}var U2=Lq(),zq=U2.custom,Qq=Xq(zq)?zq:null;t7.exports=function t(e,r,n,i){var s=r||{};if(Zo(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Zo(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=Zo(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Zo(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Zo(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var u=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return e7(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var a=String(e);return u?jq(e,a):a}if(typeof e=="bigint"){var c=String(e)+"n";return u?jq(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return q2(e)?"[Array]":"[Object]";var d=ife(s,n);if(typeof i>"u")i=[];else if(Zq(i,e)>=0)return"[Circular]";function w(l,g,y){if(g&&(i=Vle.call(i),i.push(g)),y){var E={depth:s.depth};return Zo(s,"quoteStyle")&&(E.quoteStyle=s.quoteStyle),t(l,E,n+1,i)}return t(l,s,n+1,i)}if(typeof e=="function"&&!Kq(e)){var A=$le(e),T=w1(e,w);return"[Function"+(A?": "+A:" (anonymous)")+"]"+(T.length>0?" { "+Es.call(T,", ")+" }":"")}if(Xq(e)){var x=Cl?ea.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):F2.call(e);return typeof e=="object"&&!Cl?pd(x):x}if(tfe(e)){for(var R="<"+Vq.call(String(e.nodeName)),V=e.attributes||[],U=0;U",R}if(q2(e)){if(e.length===0)return"[]";var Q=w1(e,w);return d&&!nfe(Q)?"["+V2(Q,d)+"]":"[ "+Es.call(Q,", ")+" ]"}if(Gle(e)){var L=w1(e,w);return!("cause"in Error.prototype)&&"cause"in e&&!Yq.call(e,"cause")?"{ ["+String(e)+"] "+Es.call(kq.call("[cause]: "+w(e.cause),L),", ")+" }":L.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+Es.call(L,", ")+" }"}if(typeof e=="object"&&o){if(Qq&&typeof e[Qq]=="function"&&U2)return U2(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(Yle(e)){var k=[];return Fq&&Fq.call(e,function(l,g){k.push(w(g,e,!0)+" => "+w(l,e))}),Wq("Map",v1.call(e),k,d)}if(Zle(e)){var H=[];return Uq&&Uq.call(e,function(l){H.push(w(l,e))}),Wq("Set",A1.call(e),H,d)}if(Jle(e))return M2("WeakMap");if(efe(e))return M2("WeakSet");if(Xle(e))return M2("WeakRef");if(zle(e))return pd(w(Number(e)));if(Kle(e))return pd(w(L2.call(e)));if(Qle(e))return pd(Mle.call(e));if(jle(e))return pd(w(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!Hle(e)&&!Kq(e)){var q=w1(e,w),v=Gq?Gq(e)===Object.prototype:e instanceof Object||e.constructor===Object,C=e instanceof Object?"":"null prototype",D=!v&&Ur&&Object(e)===e&&Ur in e?G2.call(ta(e),8,-1):C?"Object":"",F=v||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",P=F+(D||C?"["+Es.call(kq.call([],D||[],C||[]),": ")+"] ":"");return q.length===0?P+"{}":d?P+"{"+V2(q,d)+"}":P+"{ "+Es.call(q,", ")+" }"}return String(e)};function Jq(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function kle(t){return ea.call(String(t),/"/g,""")}function q2(t){return ta(t)==="[object Array]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Hle(t){return ta(t)==="[object Date]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Kq(t){return ta(t)==="[object RegExp]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Gle(t){return ta(t)==="[object Error]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function jle(t){return ta(t)==="[object String]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function zle(t){return ta(t)==="[object Number]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Qle(t){return ta(t)==="[object Boolean]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Xq(t){if(Cl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!F2)return!1;try{return F2.call(t),!0}catch{}return!1}function Kle(t){if(!t||typeof t!="object"||!L2)return!1;try{return L2.call(t),!0}catch{}return!1}var Wle=Object.prototype.hasOwnProperty||function(t){return t in this};function Zo(t,e){return Wle.call(t,e)}function ta(t){return Lle.call(t)}function $le(t){if(t.name)return t.name;var e=Ule.call(Fle.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function Zq(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return e7(G2.call(t,0,e.maxStringLength),e)+n}var i=ea.call(ea.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,rfe);return Jq(i,"single",e)}function rfe(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+qle.call(e.toString(16))}function pd(t){return"Object("+t+")"}function M2(t){return t+" { ? }"}function Wq(t,e,r,n){var i=n?V2(r,n):Es.call(r,", ");return t+" ("+e+") {"+i+"}"}function nfe(t){for(var e=0;e=0)return!1;return!0}function ife(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Es.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Es.call(Array(e+1),r)}}function V2(t,e){if(t.length===0)return"";var r=` +`+e.prev+e.base;return r+Es.call(t,","+r)+` +`+e.prev}function w1(t,e){var r=q2(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";h();var j2=Xo(),Nl=Mq(),sfe=r7(),ofe=j2("%TypeError%"),E1=j2("%WeakMap%",!0),b1=j2("%Map%",!0),afe=Nl("WeakMap.prototype.get",!0),ufe=Nl("WeakMap.prototype.set",!0),cfe=Nl("WeakMap.prototype.has",!0),lfe=Nl("Map.prototype.get",!0),ffe=Nl("Map.prototype.set",!0),hfe=Nl("Map.prototype.has",!0),z2=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},dfe=function(t,e){var r=z2(t,e);return r&&r.value},gfe=function(t,e,r){var n=z2(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},pfe=function(t,e){return!!z2(t,e)};n7.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new ofe("Side channel does not contain "+sfe(s))},get:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return afe(e,s)}else if(b1){if(r)return lfe(r,s)}else if(n)return dfe(n,s)},has:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return cfe(e,s)}else if(b1){if(r)return hfe(r,s)}else if(n)return pfe(n,s);return!1},set:function(s,o){E1&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new E1),ufe(e,s,o)):b1?(r||(r=new b1),ffe(r,s,o)):(n||(n={key:{},next:null}),gfe(n,s,o))}};return i}});var S1=B((h_e,s7)=>{"use strict";h();var mfe=String.prototype.replace,yfe=/%20/g,Q2={RFC1738:"RFC1738",RFC3986:"RFC3986"};s7.exports={default:Q2.RFC3986,formatters:{RFC1738:function(t){return mfe.call(t,yfe,"+")},RFC3986:function(t){return String(t)}},RFC1738:Q2.RFC1738,RFC3986:Q2.RFC3986}});var W2=B((g_e,a7)=>{"use strict";h();var wfe=S1(),K2=Object.prototype.hasOwnProperty,yu=Array.isArray,bs=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),vfe=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(yu(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===wfe.RFC1738&&(c===40||c===41)){u+=o.charAt(a);continue}if(c<128){u=u+bs[c];continue}if(c<2048){u=u+(bs[192|c>>6]+bs[128|c&63]);continue}if(c<55296||c>=57344){u=u+(bs[224|c>>12]+bs[128|c>>6&63]+bs[128|c&63]);continue}a+=1,c=65536+((c&1023)<<10|o.charCodeAt(a)&1023),u+=bs[240|c>>18]+bs[128|c>>12&63]+bs[128|c>>6&63]+bs[128|c&63]}return u},Ife=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";h();var l7=i7(),Y2=W2(),wd=S1(),xfe=Object.prototype.hasOwnProperty,u7={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},wu=Array.isArray,Ofe=String.prototype.split,Dfe=Array.prototype.push,f7=function(t,e){Dfe.apply(t,wu(e)?e:[e])},Pfe=Date.prototype.toISOString,c7=wd.default,Or={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Y2.encode,encodeValuesOnly:!1,format:c7,formatter:wd.formatters[c7],indices:!1,serializeDate:function(e){return Pfe.call(e)},skipNulls:!1,strictNullHandling:!1},Rfe=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},$2={},Bfe=function t(e,r,n,i,s,o,u,a,c,f,d,w,A,T,x){for(var R=e,V=x,U=0,Q=!1;(V=V.get($2))!==void 0&&!Q;){var L=V.get(e);if(U+=1,typeof L<"u"){if(L===U)throw new RangeError("Cyclic object value");Q=!0}typeof V.get($2)>"u"&&(U=0)}if(typeof u=="function"?R=u(r,R):R instanceof Date?R=f(R):n==="comma"&&wu(R)&&(R=Y2.maybeMap(R,function(S){return S instanceof Date?f(S):S})),R===null){if(i)return o&&!A?o(r,Or.encoder,T,"key",d):r;R=""}if(Rfe(R)||Y2.isBuffer(R)){if(o){var k=A?r:o(r,Or.encoder,T,"key",d);if(n==="comma"&&A){for(var H=Ofe.call(String(R),","),q="",v=0;v"u")return C;var D;if(n==="comma"&&wu(R))D=[{value:R.length>0?R.join(",")||null:void 0}];else if(wu(u))D=u;else{var F=Object.keys(R);D=a?F.sort(a):F}for(var P=0;P"u"?Or.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Or.charsetSentinel,delimiter:typeof e.delimiter>"u"?Or.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Or.encode,encoder:typeof e.encoder=="function"?e.encoder:Or.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Or.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Or.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Or.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Or.strictNullHandling}};h7.exports=function(t,e){var r=t,n=Mfe(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):wu(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var u;e&&e.arrayFormat in u7?u=e.arrayFormat:e&&"indices"in e?u=e.indices?"indices":"repeat":u="indices";var a=u7[u];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=l7(),f=0;f0?A+w:""}});var m7=B((w_e,p7)=>{"use strict";h();var xl=W2(),J2=Object.prototype.hasOwnProperty,Lfe=Array.isArray,Ir={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:xl.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Ffe=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},g7=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},Ufe="utf8=%26%2310003%3B",qfe="utf8=%E2%9C%93",Vfe=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),u=-1,a,c=r.charset;if(r.charsetSentinel)for(a=0;a-1&&(T=Lfe(T)?[T]:T),J2.call(n,A)?n[A]=xl.combine(n[A],T):n[A]=T}return n},kfe=function(t,e,r,n){for(var i=n?e:g7(e,r),s=t.length-1;s>=0;--s){var o,u=t[s];if(u==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var a=u.charAt(0)==="["&&u.charAt(u.length-1)==="]"?u.slice(1,-1):u,c=parseInt(a,10);!r.parseArrays&&a===""?o={0:i}:!isNaN(c)&&u!==a&&String(c)===a&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):a!=="__proto__"&&(o[a]=i)}i=o}return i},Hfe=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,u=/(\[[^[\]]*])/g,a=n.depth>0&&o.exec(s),c=a?s.slice(0,a.index):s,f=[];if(c){if(!n.plainObjects&&J2.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(a=u.exec(s))!==null&&d"u"?Ir.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?Ir.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:Ir.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:Ir.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:Ir.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ir.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:Ir.comma,decoder:typeof e.decoder=="function"?e.decoder:Ir.decoder,delimiter:typeof e.delimiter=="string"||xl.isRegExp(e.delimiter)?e.delimiter:Ir.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:Ir.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:Ir.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:Ir.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:Ir.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ir.strictNullHandling}};p7.exports=function(t,e){var r=Gfe(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?Vfe(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";h();var jfe=d7(),zfe=m7(),Qfe=S1();y7.exports={formats:Qfe,parse:zfe,stringify:jfe}});var X2=B(je=>{"use strict";h();Object.defineProperty(je,"__esModule",{value:!0});je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=je.WALLET_PROVIDER_CALLBACK_PARAM=je.WALLET_PROVIDER_SIGN_MESSAGE_URL=je.WALLET_PROVIDER_GUARD_TRANSACTION_URL=je.WALLET_PROVIDER_SIGN_TRANSACTION_URL=je.WALLET_PROVIDER_SEND_TRANSACTION_URL=je.WALLET_PROVIDER_DISCONNECT_URL=je.WALLET_PROVIDER_CONNECT_URL=je.XALIAS_PROVIDER_TESTNET=je.XALIAS_PROVIDER_DEVNET=je.XALIAS_PROVIDER_MAINNET=je.WALLET_PROVIDER_TESTNET=je.WALLET_PROVIDER_DEVNET=je.WALLET_PROVIDER_MAINNET=void 0;je.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";je.XALIAS_PROVIDER_MAINNET="https://xalias.com";je.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";je.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";je.WALLET_PROVIDER_CONNECT_URL="hook/login";je.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";je.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";je.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";je.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";je.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";je.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var v7=B(Ol=>{"use strict";h();Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrCannotSignedMessage=Ol.ErrCannotGetSignedTransactions=void 0;var Z2=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Ol.ErrCannotGetSignedTransactions=Z2;var eC=class extends Error{constructor(){super("Cannot get signed message")}};Ol.ErrCannotSignedMessage=eC});var A7=B(I1=>{"use strict";h();Object.defineProperty(I1,"__esModule",{value:!0});I1.PlainSignedTransaction=void 0;var tC=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};I1.PlainSignedTransaction=tC});var Dl=B(ia=>{"use strict";h();var ra=ia&&ia.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Kfe=ia&&ia.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ia,"__esModule",{value:!0});ia.WalletProvider=void 0;var rC=Kfe(w7()),na=X2(),nC=v7(),Wfe=A7(),iC=class t{constructor(e){this.walletUrl=e}login(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return ra(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return ra(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return ra(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=rC.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new nC.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return ra(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(e=window.location.search){let r=rC.default.parse(e.slice(1));return t.isTxSignReturnSuccess(r)?this.getTxSignReturnValue(r):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(na.WALLET_PROVIDER_CALLBACK_PARAM)&&e[na.WALLET_PROVIDER_CALLBACK_PARAM]===na.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new nC.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new nC.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let u=t.prepareWalletTransaction(o);for(let a in u)u.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(i[a]=[]),i[a].push(u[a])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};ia.WalletProvider=iC});var e9=B((O_e,Z7)=>{"use strict";h();function P7(t,e){return function(){return t.apply(e,arguments)}}var{toString:$fe}=Object.prototype,{getPrototypeOf:mC}=Object,N1=(t=>e=>{let r=$fe.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Is=t=>(t=t.toLowerCase(),e=>N1(e)===t),x1=t=>e=>typeof e===t,{isArray:Ml}=Array,Ad=x1("undefined");function Yfe(t){return t!==null&&!Ad(t)&&t.constructor!==null&&!Ad(t.constructor)&&ei(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var R7=Is("ArrayBuffer");function Jfe(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&R7(t.buffer),e}var Xfe=x1("string"),ei=x1("function"),B7=x1("number"),O1=t=>t!==null&&typeof t=="object",Zfe=t=>t===!0||t===!1,T1=t=>{if(N1(t)!=="object")return!1;let e=mC(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ehe=Is("Date"),the=Is("File"),rhe=Is("Blob"),nhe=Is("FileList"),ihe=t=>O1(t)&&ei(t.pipe),she=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ei(t.append)&&((e=N1(t))==="formdata"||e==="object"&&ei(t.toString)&&t.toString()==="[object FormData]"))},ohe=Is("URLSearchParams"),ahe=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ed(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ml(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var L7=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F7=t=>!Ad(t)&&t!==L7;function cC(){let{caseless:t}=F7(this)&&this||{},e={},r=(n,i)=>{let s=t&&M7(e,i)||i;T1(e[s])&&T1(n)?e[s]=cC(e[s],n):T1(n)?e[s]=cC({},n):Ml(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(Ed(e,(i,s)=>{r&&ei(i)?t[s]=P7(i,r):t[s]=i},{allOwnKeys:n}),t),che=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),lhe=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},fhe=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&mC(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},hhe=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},dhe=t=>{if(!t)return null;if(Ml(t))return t;let e=t.length;if(!B7(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},ghe=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&mC(Uint8Array)),phe=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},mhe=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},yhe=Is("HTMLFormElement"),whe=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),E7=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),vhe=Is("RegExp"),U7=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};Ed(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},Ahe=t=>{U7(t,(e,r)=>{if(ei(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(ei(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Ehe=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ml(t)?n(t):n(String(t).split(e)),r},bhe=()=>{},She=(t,e)=>(t=+t,Number.isFinite(t)?t:e),sC="abcdefghijklmnopqrstuvwxyz",b7="0123456789",q7={DIGIT:b7,ALPHA:sC,ALPHA_DIGIT:sC+sC.toUpperCase()+b7},Ihe=(t=16,e=q7.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function The(t){return!!(t&&ei(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var _he=t=>{let e=new Array(10),r=(n,i)=>{if(O1(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ml(n)?[]:{};return Ed(n,(o,u)=>{let a=r(o,i+1);!Ad(a)&&(s[u]=a)}),e[i]=void 0,s}}return n};return r(t,0)},Che=Is("AsyncFunction"),Nhe=t=>t&&(O1(t)||ei(t))&&ei(t.then)&&ei(t.catch),re={isArray:Ml,isArrayBuffer:R7,isBuffer:Yfe,isFormData:she,isArrayBufferView:Jfe,isString:Xfe,isNumber:B7,isBoolean:Zfe,isObject:O1,isPlainObject:T1,isUndefined:Ad,isDate:ehe,isFile:the,isBlob:rhe,isRegExp:vhe,isFunction:ei,isStream:ihe,isURLSearchParams:ohe,isTypedArray:ghe,isFileList:nhe,forEach:Ed,merge:cC,extend:uhe,trim:ahe,stripBOM:che,inherits:lhe,toFlatObject:fhe,kindOf:N1,kindOfTest:Is,endsWith:hhe,toArray:dhe,forEachEntry:phe,matchAll:mhe,isHTMLForm:yhe,hasOwnProperty:E7,hasOwnProp:E7,reduceDescriptors:U7,freezeMethods:Ahe,toObjectSet:Ehe,toCamelCase:whe,noop:bhe,toFiniteNumber:She,findKey:M7,global:L7,isContextDefined:F7,ALPHABET:q7,generateString:Ihe,isSpecCompliantForm:The,toJSONObject:_he,isAsyncFn:Che,isThenable:Nhe};function Le(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}re.inherits(Le,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:re.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var V7=Le.prototype,k7={};["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(t=>{k7[t]={value:t}});Object.defineProperties(Le,k7);Object.defineProperty(V7,"isAxiosError",{value:!0});Le.from=(t,e,r,n,i,s)=>{let o=Object.create(V7);return re.toFlatObject(t,o,function(a){return a!==Error.prototype},u=>u!=="isAxiosError"),Le.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var xhe=null;function lC(t){return re.isPlainObject(t)||re.isArray(t)}function H7(t){return re.endsWith(t,"[]")?t.slice(0,-2):t}function S7(t,e,r){return t?t.concat(e).map(function(i,s){return i=H7(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Ohe(t){return re.isArray(t)&&!t.some(lC)}var Dhe=re.toFlatObject(re,{},null,function(e){return/^is[A-Z]/.test(e)});function D1(t,e,r){if(!re.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=re.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,R){return!re.isUndefined(R[x])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,a=(r.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function c(T){if(T===null)return"";if(re.isDate(T))return T.toISOString();if(!a&&re.isBlob(T))throw new Le("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(T)||re.isTypedArray(T)?a&&typeof Blob=="function"?new Blob([T]):p.Buffer.from(T):T}function f(T,x,R){let V=T;if(T&&!R&&typeof T=="object"){if(re.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=JSON.stringify(T);else if(re.isArray(T)&&Ohe(T)||(re.isFileList(T)||re.endsWith(x,"[]"))&&(V=re.toArray(T)))return x=H7(x),V.forEach(function(Q,L){!(re.isUndefined(Q)||Q===null)&&e.append(o===!0?S7([x],L,s):o===null?x:x+"[]",c(Q))}),!1}return lC(T)?!0:(e.append(S7(R,x,s),c(T)),!1)}let d=[],w=Object.assign(Dhe,{defaultVisitor:f,convertValue:c,isVisitable:lC});function A(T,x){if(!re.isUndefined(T)){if(d.indexOf(T)!==-1)throw Error("Circular reference detected in "+x.join("."));d.push(T),re.forEach(T,function(V,U){(!(re.isUndefined(V)||V===null)&&i.call(e,V,re.isString(U)?U.trim():U,x,w))===!0&&A(V,x?x.concat(U):[U])}),d.pop()}}if(!re.isObject(t))throw new TypeError("data must be an object");return A(t),e}function I7(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function yC(t,e){this._pairs=[],t&&D1(t,this,e)}var G7=yC.prototype;G7.append=function(e,r){this._pairs.push([e,r])};G7.toString=function(e){let r=e?function(n){return e.call(this,n,I7)}:I7;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Phe(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function j7(t,e,r){if(!e)return t;let n=r&&r.encode||Phe,i=r&&r.serialize,s;if(i?s=i(e,r):s=re.isURLSearchParams(e)?e.toString():new yC(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var fC=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(n){n!==null&&e(n)})}},T7=fC,z7={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Rhe=typeof URLSearchParams<"u"?URLSearchParams:yC,Bhe=typeof FormData<"u"?FormData:null,Mhe=typeof Blob<"u"?Blob:null,Lhe={isBrowser:!0,classes:{URLSearchParams:Rhe,FormData:Bhe,Blob:Mhe},protocols:["http","https","file","blob","url","data"]},Q7=typeof window<"u"&&typeof document<"u",Fhe=(t=>Q7&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),Uhe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",qhe=Object.freeze({__proto__:null,hasBrowserEnv:Q7,hasStandardBrowserWebWorkerEnv:Uhe,hasStandardBrowserEnv:Fhe}),Ss={...qhe,...Lhe};function Vhe(t,e){return D1(t,new Ss.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Ss.isNode&&re.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function khe(t){return re.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Hhe(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&re.isArray(i)?i.length:o,a?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&re.isArray(i[o])&&(i[o]=Hhe(i[o])),!u)}if(re.isFormData(t)&&re.isFunction(t.entries)){let r={};return re.forEachEntry(t,(n,i)=>{e(khe(n),i,r,0)}),r}return null}function Ghe(t,e,r){if(re.isString(t))try{return(e||JSON.parse)(t),re.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var wC={transitional:z7,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=re.isObject(e);if(s&&re.isHTMLForm(e)&&(e=new FormData(e)),re.isFormData(e))return i?JSON.stringify(K7(e)):e;if(re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e))return e;if(re.isArrayBufferView(e))return e.buffer;if(re.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Vhe(e,this.formSerializer).toString();if((u=re.isFileList(e))||n.indexOf("multipart/form-data")>-1){let a=this.env&&this.env.FormData;return D1(u?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Ghe(e)):e}],transformResponse:[function(e){let r=this.transitional||wC.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&re.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?Le.from(u,Le.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ss.classes.FormData,Blob:Ss.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],t=>{wC.headers[t]={}});var vC=wC,jhe=re.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"]),zhe=t=>{let e={},r,n,i;return t&&t.split(` +`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&jhe[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},_7=Symbol("internals");function vd(t){return t&&String(t).trim().toLowerCase()}function _1(t){return t===!1||t==null?t:re.isArray(t)?t.map(_1):String(t)}function Qhe(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Khe=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function oC(t,e,r,n,i){if(re.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function Whe(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function $he(t,e){let r=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Pl=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,a,c){let f=vd(a);if(!f)throw new Error("header name must be a non-empty string");let d=re.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||a]=_1(u))}let o=(u,a)=>re.forEach(u,(c,f)=>s(c,f,a));return re.isPlainObject(e)||e instanceof this.constructor?o(e,r):re.isString(e)&&(e=e.trim())&&!Khe(e)?o(zhe(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=vd(e),e){let n=re.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Qhe(i);if(re.isFunction(r))return r.call(this,i,n);if(re.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=vd(e),e){let n=re.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||oC(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=vd(o),o){let u=re.findKey(n,o);u&&(!r||oC(n,n[u],u,r))&&(delete n[u],i=!0)}}return re.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||oC(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return re.forEach(this,(i,s)=>{let o=re.findKey(n,s);if(o){r[o]=_1(i),delete r[s];return}let u=e?Whe(s):String(s).trim();u!==s&&delete r[s],r[u]=_1(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return re.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&re.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[_7]=this[_7]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=vd(o);n[u]||($he(i,o),n[u]=!0)}return re.isArray(e)?e.forEach(s):s(e),this}};Pl.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);re.reduceDescriptors(Pl.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});re.freezeMethods(Pl);var ro=Pl;function aC(t,e){let r=this||vC,n=e||r,i=ro.from(n.headers),s=n.data;return re.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function W7(t){return!!(t&&t.__CANCEL__)}function bd(t,e,r){Le.call(this,t??"canceled",Le.ERR_CANCELED,e,r),this.name="CanceledError"}re.inherits(bd,Le,{__CANCEL__:!0});function Yhe(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Le("Request failed with status code "+r.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var Jhe=Ss.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];re.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),re.isString(n)&&o.push("path="+n),re.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Xhe(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Zhe(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function $7(t,e){return t&&!Xhe(e)?Zhe(t,e):e}var ede=Ss.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=re.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function tde(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function rde(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(a){let c=Date.now(),f=n[s];o||(o=c),r[i]=a,n[i]=c;let d=s,w=0;for(;d!==i;)w+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,a=n(u),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:a||void 0,estimated:a&&o&&c?(o-s)/a:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var nde=typeof XMLHttpRequest<"u",ide=nde&&function(t){return new Promise(function(r,n){let i=t.data,s=ro.from(t.headers).normalize(),{responseType:o,withXSRFToken:u}=t,a;function c(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}let f;if(re.isFormData(i)){if(Ss.hasStandardBrowserEnv||Ss.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[x,...R]=f?f.split(";").map(V=>V.trim()).filter(Boolean):[];s.setContentType([x||"multipart/form-data",...R].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let x=t.auth.username||"",R=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(x+":"+R))}let w=$7(t.baseURL,t.url);d.open(t.method.toUpperCase(),j7(w,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function A(){if(!d)return;let x=ro.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),V={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:x,config:t,request:d};Yhe(function(Q){r(Q),c()},function(Q){n(Q),c()},V),d=null}if("onloadend"in d?d.onloadend=A:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(A)},d.onabort=function(){d&&(n(new Le("Request aborted",Le.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Le("Network Error",Le.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let R=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||z7;t.timeoutErrorMessage&&(R=t.timeoutErrorMessage),n(new Le(R,V.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,t,d)),d=null},Ss.hasStandardBrowserEnv&&(u&&re.isFunction(u)&&(u=u(t)),u||u!==!1&&ede(w))){let x=t.xsrfHeaderName&&t.xsrfCookieName&&Jhe.read(t.xsrfCookieName);x&&s.set(t.xsrfHeaderName,x)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&re.forEach(s.toJSON(),function(R,V){d.setRequestHeader(V,R)}),re.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",C7(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",C7(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=x=>{d&&(n(!x||x.type?new bd(null,t,d):x),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));let T=tde(w);if(T&&Ss.protocols.indexOf(T)===-1){n(new Le("Unsupported protocol "+T+":",Le.ERR_BAD_REQUEST,t));return}d.send(i||null)})},hC={http:xhe,xhr:ide};re.forEach(hC,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var N7=t=>`- ${t}`,sde=t=>re.isFunction(t)||t===null||t===!1,Y7={getAdapter:t=>{t=re.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${u} `+(a===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : +`+s.map(N7).join(` +`):" "+N7(s[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:hC};function uC(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new bd(null,t)}function x7(t){return uC(t),t.headers=ro.from(t.headers),t.data=aC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Y7.getAdapter(t.adapter||vC.adapter)(t).then(function(n){return uC(t),n.data=aC.call(t,t.transformResponse,n),n.headers=ro.from(n.headers),n},function(n){return W7(n)||(uC(t),n&&n.response&&(n.response.data=aC.call(t,t.transformResponse,n.response),n.response.headers=ro.from(n.response.headers))),Promise.reject(n)})}var O7=t=>t instanceof ro?{...t}:t;function Rl(t,e){e=e||{};let r={};function n(c,f,d){return re.isPlainObject(c)&&re.isPlainObject(f)?re.merge.call({caseless:d},c,f):re.isPlainObject(f)?re.merge({},f):re.isArray(f)?f.slice():f}function i(c,f,d){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!re.isUndefined(f))return n(void 0,f)}function o(c,f){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function u(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let 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:u,headers:(c,f)=>i(O7(c),O7(f),!0)};return re.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=a[f]||i,w=d(t[f],e[f],f);re.isUndefined(w)&&d!==u||(r[f]=w)}),r}var J7="1.6.8",AC={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{AC[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var D7={};AC.transitional=function(e,r,n){function i(s,o){return"[Axios v"+J7+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new Le(i(o," has been removed"+(r?" in "+r:"")),Le.ERR_DEPRECATED);return r&&!D7[o]&&(D7[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function ode(t,e,r){if(typeof t!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],a=u===void 0||o(u,s,t);if(a!==!0)throw new Le("option "+s+" must be "+a,Le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}var dC={assertOptions:ode,validators:AC},sa=dC.validators,Bl=class{constructor(e){this.defaults=e,this.interceptors={request:new T7,response:new T7}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` +`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Rl(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&dC.assertOptions(n,{silentJSONParsing:sa.transitional(sa.boolean),forcedJSONParsing:sa.transitional(sa.boolean),clarifyTimeoutError:sa.transitional(sa.boolean)},!1),i!=null&&(re.isFunction(i)?r.paramsSerializer={serialize:i}:dC.assertOptions(i,{encode:sa.function,serialize:sa.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&re.merge(s.common,s[r.method]);s&&re.forEach(["delete","get","head","post","put","patch","common"],T=>{delete s[T]}),r.headers=ro.concat(o,s);let u=[],a=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(r)===!1||(a=a&&x.synchronous,u.unshift(x.fulfilled,x.rejected))});let c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let f,d=0,w;if(!a){let T=[x7.bind(this),void 0];for(T.unshift.apply(T,u),T.push.apply(T,c),w=T.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new bd(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},ade=gC;function ude(t){return function(r){return t.apply(null,r)}}function cde(t){return re.isObject(t)&&t.isAxiosError===!0}var pC={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(pC).forEach(([t,e])=>{pC[e]=t});var lde=pC;function X7(t){let e=new C1(t),r=P7(C1.prototype.request,e);return re.extend(r,C1.prototype,e,{allOwnKeys:!0}),re.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return X7(Rl(t,i))},r}var cr=X7(vC);cr.Axios=C1;cr.CanceledError=bd;cr.CancelToken=ade;cr.isCancel=W7;cr.VERSION=J7;cr.toFormData=D1;cr.AxiosError=Le;cr.Cancel=cr.CanceledError;cr.all=function(e){return Promise.all(e)};cr.spread=ude;cr.isAxiosError=cde;cr.mergeConfig=Rl;cr.AxiosHeaders=ro;cr.formToJSON=t=>K7(re.isHTMLForm(t)?new FormData(t):t);cr.getAdapter=Y7.getAdapter;cr.HttpStatusCode=lde;cr.default=cr;Z7.exports=cr});var t9=B(P1=>{"use strict";h();Object.defineProperty(P1,"__esModule",{value:!0});P1.NativeAuthClientConfig=void 0;var EC=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};P1.NativeAuthClientConfig=EC});var SC=B(Ll=>{"use strict";h();var vu=Ll&&Ll.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.NativeAuthClient=void 0;var fde=e9(),hde=t9(),bC=class{constructor(e){this.config=Object.assign(new hde.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vu(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vu(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vu(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vu(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vu(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vu(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(p.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vu(this,void 0,void 0,function*(){return yield fde.default.get(e,{headers:this.config.extraRequestHeaders})})}};Ll.NativeAuthClient=bC});var s9=B(B1=>{"use strict";h();Object.defineProperty(B1,"__esModule",{value:!0});B1.TransactionStatus=void 0;var TC=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};B1.TransactionStatus=TC});var a9=B(M1=>{"use strict";h();Object.defineProperty(M1,"__esModule",{value:!0});M1.TransactionReceipt=void 0;var o9=_c(),_C=class t{constructor(){this.value="",this.sender=new o9.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new o9.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};M1.TransactionReceipt=_C});var u9=B(Ts=>{"use strict";h();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ErrContractQuery=Ts.ErrNetworkProvider=Ts.ErrUnexpectedCondition=Ts.Err=void 0;var Ul=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ts.Err=Ul;var CC=class extends Ul{constructor(e){super(`Unexpected condition: [${e}]`)}};Ts.ErrUnexpectedCondition=CC;var NC=class extends Ul{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Ts.ErrNetworkProvider=NC;var xC=class extends Ul{constructor(e){super(e.message.replace("executeQuery:",""))}};Ts.ErrContractQuery=xC});var l9=B(oa=>{"use strict";h();Object.defineProperty(oa,"__esModule",{value:!0});oa.TransactionEventTopic=oa.TransactionEventData=oa.TransactionEvent=void 0;var c9=_c(),OC=class t{constructor(e){this.address=new c9.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new ql(p.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new c9.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new L1(n)),r.dataPayload=ql.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(ql.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};oa.TransactionEvent=OC;var ql=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(p.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventData=ql;var L1=class{constructor(e){this.raw=p.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventTopic=L1});var PC=B(F1=>{"use strict";h();Object.defineProperty(F1,"__esModule",{value:!0});F1.TransactionLogs=void 0;var pde=u9(),f9=_c(),mde=l9(),DC=class t{constructor(e){this.address=new f9.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new f9.Address(e.address),r.events=(e.events||[]).map(n=>mde.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new pde.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};F1.TransactionLogs=DC});var d9=B(Vl=>{"use strict";h();Object.defineProperty(Vl,"__esModule",{value:!0});Vl.ContractResultItem=Vl.ContractResults=void 0;var h9=PC(),U1=_c(),RC=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>Sd.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>Sd.fromApiHttpResponse(n));return new t(r)}};Vl.ContractResults=RC;var Sd=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new U1.Address(""),this.sender=new U1.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new h9.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=p.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new U1.Address(e.receiver),r.sender=new U1.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=h9.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Vl.ContractResultItem=Sd});var g9=B(q1=>{"use strict";h();Object.defineProperty(q1,"__esModule",{value:!0});q1.ContractQueryRequest=void 0;var BC=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};q1.ContractQueryRequest=BC});var _9=B((R2e,T9)=>{h();T9.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var aa=B(Eu=>{h();var MC,yde=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Eu.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Eu.getSymbolTotalCodewords=function(e){return yde[e]};Eu.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Eu.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');MC=e};Eu.isKanjiModeEnabled=function(){return typeof MC<"u"};Eu.toSJIS=function(e){return MC(e)}});var G1=B(ti=>{h();ti.L={bit:1};ti.M={bit:0};ti.Q={bit:3};ti.H={bit:2};function wde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ti.L;case"m":case"medium":return ti.M;case"q":case"quartile":return ti.Q;case"h":case"high":return ti.H;default:throw new Error("Unknown EC Level: "+t)}}ti.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ti.from=function(e,r){if(ti.isValid(e))return e;try{return wde(e)}catch{return r}}});var x9=B((q2e,N9)=>{h();function C9(){this.buffer=[],this.length=0}C9.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};N9.exports=C9});var D9=B((k2e,O9)=>{h();function Id(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Id.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};Id.prototype.get=function(t,e){return this.data[t*this.size+e]};Id.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Id.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};O9.exports=Id});var P9=B(j1=>{h();var vde=aa().getSymbolSize;j1.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=vde(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{h();var Ade=aa().getSymbolSize,R9=7;B9.getPositions=function(e){let r=Ade(e);return[[0,0],[r-R9,0],[0,r-R9]]}});var L9=B(Rt=>{h();Rt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bu={N1:3,N2:3,N3:40,N4:10};Rt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Rt.from=function(e){return Rt.isValid(e)?parseInt(e,10):void 0};Rt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,u=null;for(let a=0;a=5&&(n+=bu.N1+(i-5)),o=f,i=1),f=e.get(c,a),f===u?s++:(s>=5&&(n+=bu.N1+(s-5)),u=f,s=1)}i>=5&&(n+=bu.N1+(i-5)),s>=5&&(n+=bu.N1+(s-5))}return n};Rt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(u,o),u>=10&&(s===1488||s===93)&&n++}return n*bu.N3};Rt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{h();var ua=G1(),z1=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Q1=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];LC.getBlocksCount=function(e,r){switch(r){case ua.L:return z1[(e-1)*4+0];case ua.M:return z1[(e-1)*4+1];case ua.Q:return z1[(e-1)*4+2];case ua.H:return z1[(e-1)*4+3];default:return}};LC.getTotalCodewordsCount=function(e,r){switch(r){case ua.L:return Q1[(e-1)*4+0];case ua.M:return Q1[(e-1)*4+1];case ua.Q:return Q1[(e-1)*4+2];case ua.H:return Q1[(e-1)*4+3];default:return}}});var F9=B(W1=>{h();var Td=new Uint8Array(512),K1=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Td[r]=e,K1[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Td[r]=Td[r-255]})();W1.log=function(e){if(e<1)throw new Error("log("+e+")");return K1[e]};W1.exp=function(e){return Td[e]};W1.mul=function(e,r){return e===0||r===0?0:Td[K1[e]+K1[r]]}});var U9=B(_d=>{h();var UC=F9();_d.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{h();var q9=U9();function qC(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}qC.prototype.initialize=function(e){this.degree=e,this.genPoly=q9.generateECPolynomial(this.degree)};qC.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=q9.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};V9.exports=qC});var VC=B(H9=>{h();H9.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var kC=B(no=>{h();var G9="[0-9]+",bde="[A-Z $%*+\\-./:]+",Cd="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Cd=Cd.replace(/u/g,"\\u");var Sde="(?:(?![A-Z0-9 $%*+\\-./:]|"+Cd+`)(?:.|[\r +]))+`;no.KANJI=new RegExp(Cd,"g");no.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");no.BYTE=new RegExp(Sde,"g");no.NUMERIC=new RegExp(G9,"g");no.ALPHANUMERIC=new RegExp(bde,"g");var Ide=new RegExp("^"+Cd+"$"),Tde=new RegExp("^"+G9+"$"),_de=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");no.testKanji=function(e){return Ide.test(e)};no.testNumeric=function(e){return Tde.test(e)};no.testAlphanumeric=function(e){return _de.test(e)}});var ca=B(lr=>{h();var Cde=VC(),HC=kC();lr.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};lr.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};lr.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};lr.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};lr.MIXED={bit:-1};lr.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Cde.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};lr.getBestModeForData=function(e){return HC.testNumeric(e)?lr.NUMERIC:HC.testAlphanumeric(e)?lr.ALPHANUMERIC:HC.testKanji(e)?lr.KANJI:lr.BYTE};lr.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};lr.isValid=function(e){return e&&e.bit&&e.ccBits};function Nde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return lr.NUMERIC;case"alphanumeric":return lr.ALPHANUMERIC;case"kanji":return lr.KANJI;case"byte":return lr.BYTE;default:throw new Error("Unknown mode: "+t)}}lr.from=function(e,r){if(lr.isValid(e))return e;try{return Nde(e)}catch{return r}}});var W9=B(Su=>{h();var $1=aa(),xde=FC(),j9=G1(),la=ca(),GC=VC(),Q9=7973,z9=$1.getBCHDigit(Q9);function Ode(t,e,r){for(let n=1;n<=40;n++)if(e<=Su.getCapacity(n,r,t))return n}function K9(t,e){return la.getCharCountIndicator(t,e)+4}function Dde(t,e){let r=0;return t.forEach(function(n){let i=K9(n.mode,e);r+=i+n.getBitsLength()}),r}function Pde(t,e){for(let r=1;r<=40;r++)if(Dde(t,r)<=Su.getCapacity(r,e,la.MIXED))return r}Su.from=function(e,r){return GC.isValid(e)?parseInt(e,10):r};Su.getCapacity=function(e,r,n){if(!GC.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=la.BYTE);let i=$1.getSymbolTotalCodewords(e),s=xde.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===la.MIXED)return o;let u=o-K9(n,e);switch(n){case la.NUMERIC:return Math.floor(u/10*3);case la.ALPHANUMERIC:return Math.floor(u/11*2);case la.KANJI:return Math.floor(u/13);case la.BYTE:default:return Math.floor(u/8)}};Su.getBestVersionForData=function(e,r){let n,i=j9.from(r,j9.M);if(Array.isArray(e)){if(e.length>1)return Pde(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Ode(n.mode,n.getLength(),i)};Su.getEncodedBits=function(e){if(!GC.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;$1.getBCHDigit(r)-z9>=0;)r^=Q9<<$1.getBCHDigit(r)-z9;return e<<12|r}});var X9=B(J9=>{h();var jC=aa(),Y9=1335,Rde=21522,$9=jC.getBCHDigit(Y9);J9.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;jC.getBCHDigit(i)-$9>=0;)i^=Y9<{h();var Bde=ca();function Hl(t){this.mode=Bde.NUMERIC,this.data=t.toString()}Hl.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Hl.prototype.getLength=function(){return this.data.length};Hl.prototype.getBitsLength=function(){return Hl.getBitsLength(this.data.length)};Hl.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};Z9.exports=Hl});var rV=B((pCe,tV)=>{h();var Mde=ca(),zC=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Gl(t){this.mode=Mde.ALPHANUMERIC,this.data=t}Gl.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Gl.prototype.getLength=function(){return this.data.length};Gl.prototype.getBitsLength=function(){return Gl.getBitsLength(this.data.length)};Gl.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=zC.indexOf(this.data[r])*45;n+=zC.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(zC.indexOf(this.data[r]),6)};tV.exports=Gl});var iV=B((yCe,nV)=>{"use strict";h();nV.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var oV=B((vCe,sV)=>{h();var Lde=iV(),Fde=ca();function jl(t){this.mode=Fde.BYTE,typeof t=="string"&&(t=Lde(t)),this.data=new Uint8Array(t)}jl.getBitsLength=function(e){return e*8};jl.prototype.getLength=function(){return this.data.length};jl.prototype.getBitsLength=function(){return jl.getBitsLength(this.data.length)};jl.prototype.write=function(t){for(let e=0,r=this.data.length;e{h();var Ude=ca(),qde=aa();function zl(t){this.mode=Ude.KANJI,this.data=t}zl.getBitsLength=function(e){return e*13};zl.prototype.getLength=function(){return this.data.length};zl.prototype.getBitsLength=function(){return zl.getBitsLength(this.data.length)};zl.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` +Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};aV.exports=zl});var cV=B((SCe,QC)=>{"use strict";h();var Nd={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=Nd.PriorityQueue.make();s.push(e,0);for(var o,u,a,c,f,d,w,A,T;!s.empty();){o=s.pop(),u=o.value,c=o.cost,f=t[u]||{};for(a in f)f.hasOwnProperty(a)&&(d=f[a],w=c+d,A=i[a],T=typeof i[a]>"u",(T||A>w)&&(i[a]=w,s.push(a,w),n[a]=u))}if(typeof r<"u"&&typeof i[r]>"u"){var x=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(x)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=Nd.single_source_shortest_paths(t,e,r);return Nd.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Nd.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof QC<"u"&&(QC.exports=Nd)});var yV=B(Ql=>{h();var ze=ca(),hV=eV(),dV=rV(),gV=oV(),pV=uV(),xd=kC(),Y1=aa(),Vde=cV();function lV(t){return unescape(encodeURIComponent(t)).length}function Od(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function mV(t){let e=Od(xd.NUMERIC,ze.NUMERIC,t),r=Od(xd.ALPHANUMERIC,ze.ALPHANUMERIC,t),n,i;return Y1.isKanjiModeEnabled()?(n=Od(xd.BYTE,ze.BYTE,t),i=Od(xd.KANJI,ze.KANJI,t)):(n=Od(xd.BYTE_KANJI,ze.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,u){return o.index-u.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function KC(t,e){switch(e){case ze.NUMERIC:return hV.getBitsLength(t);case ze.ALPHANUMERIC:return dV.getBitsLength(t);case ze.KANJI:return pV.getBitsLength(t);case ze.BYTE:return gV.getBitsLength(t)}}function kde(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Hde(t){let e=[];for(let r=0;r{h();var X1=aa(),WC=G1(),jde=x9(),zde=D9(),Qde=P9(),Kde=M9(),JC=L9(),XC=FC(),Wde=k9(),J1=W9(),$de=X9(),Yde=ca(),$C=yV();function Jde(t,e){let r=t.size,n=Kde.getPositions(e);for(let i=0;i=0&&u<=6&&(a===0||a===6)||a>=0&&a<=6&&(u===0||u===6)||u>=2&&u<=4&&a>=2&&a<=4?t.set(s+u,o+a,!0,!0):t.set(s+u,o+a,!1,!0))}}function Xde(t){let e=t.size;for(let r=8;r>u&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function YC(t,e,r){let n=t.size,i=$de.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function tge(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let u=r-1;u>0;u-=2)for(u===6&&u--;;){for(let a=0;a<2;a++)if(!t.isReserved(i,u-a)){let c=!1;o>>s&1)===1),t.set(i,u-a,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function rge(t,e,r){let n=new jde;r.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),Yde.getCharCountIndicator(a.mode,t)),a.write(n)});let i=X1.getSymbolTotalCodewords(t),s=XC.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let u=(o-n.getLengthInBits())/8;for(let a=0;a=7&&ege(a,e),tge(a,o),isNaN(n)&&(n=JC.getBestMask(a,YC.bind(null,a,r))),JC.applyMask(n,a),YC(a,r,n),{modules:a,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}wV.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=WC.M,i,s;return typeof r<"u"&&(n=WC.from(r.errorCorrectionLevel,WC.M),i=J1.from(r.version),s=JC.from(r.maskPattern),r.toSJISFunc&&X1.setToSJISFunction(r.toSJISFunc)),ige(e,i,n,s)}});var ZC=B(Iu=>{h();function AV(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Iu.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:AV(e.color.dark||"#000000ff"),light:AV(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Iu.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Iu.getImageWidth=function(e,r){let n=Iu.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Iu.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Iu.getScale(i,n),u=Math.floor((i+n.margin*2)*o),a=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=a&&d>=a&&f{h();var e3=ZC();function sge(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function oge(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Z1.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=oge()),i=e3.getOptions(i);let o=e3.getImageWidth(e.modules.size,i),u=s.getContext("2d"),a=u.createImageData(o,o);return e3.qrToImageData(a.data,e,i),sge(u,s,o),u.putImageData(a,0,0),s};Z1.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Z1.render(e,r,i),o=i.type||"image/png",u=i.rendererOpts||{};return s.toDataURL(o,u.quality)}});var IV=B(SV=>{h();var age=ZC();function bV(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function t3(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function uge(t,e,r){let n="",i=0,s=!1,o=0;for(let u=0;u0&&a>0&&t[u-1]||(n+=s?t3("M",a+r,.5+c+r):t3("m",i,0),i=0,s=!1),a+1':"",c="',f='viewBox="0 0 '+u+" "+u+'"',w=''+a+c+` +`;return typeof n=="function"&&n(null,w),w}});var _V=B(Dd=>{h();var cge=_9(),r3=vV(),TV=EV(),lge=IV();function n3(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,u=typeof s[o-1]=="function";if(!u&&!cge())throw new Error("Callback required as last argument");if(u){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(a,c){try{let f=r3.create(r,n);a(t(f,e,n))}catch(f){c(f)}})}try{let a=r3.create(r,n);i(null,t(a,e,n))}catch(a){i(a)}}Dd.create=r3.create;Dd.toCanvas=n3.bind(null,TV.render);Dd.toDataURL=n3.bind(null,TV.renderToDataURL);Dd.toString=n3.bind(null,function(t,e,r){return lge.render(t,r)})});var FV=B(fa=>{"use strict";h();var Ege=fa&&fa.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LV=fa&&fa.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ege(e,t,r)};Object.defineProperty(fa,"__esModule",{value:!0});LV(Dl(),fa);LV(X2(),fa)});h();var d3=pe(Ca(),1),g3=pe(_b(),1),fw=pe(d0(),1),p3=pe(Db(),1),_ge=pe(Ve(),1),Cge=pe(Ic(),1),Nge=pe(Xr(),1),xge=pe(N0(),1),sk=pe(Bb(),1),Oge=pe(V0(),1),Dge=pe(H0(),1),ok=pe(po(),1),_s=pe(Mf(),1),ak=pe(yf(),1),uk=pe(Yu(),1),Pge=pe(CE(),1),Rge=pe(jb(),1);h();h();var U8=pe(Kb(),1);h();h();var G0="elvenjs_state",M8="https://devnet-api.multiversx.com";var Po="/dapp/init",j0="devnet",L8="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",F8=["wss://relay.walletconnect.com"],Rr={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var me={get(t){let e=localStorage.getItem(G0);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem(G0,JSON.stringify(r))},clear(){localStorage.removeItem(G0)}};var z0=async()=>{let t=U8.ExtensionProvider.getInstance();try{let e=await t.init(),r=me.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var c3=pe(Kb(),1),l3=pe(fd(),1),f3=pe(Dl(),1),ik=pe(SC(),1),lw=pe(H0(),1);h();var n9=pe(fd(),1);h();h();var ge=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};h();var r9=(U=>(U.onLoginStart="onLoginStart",U.onLoginSuccess="onLoginSuccess",U.onLoginFailure="onLoginFailure",U.onLogoutStart="onLogoutStart",U.onLogoutSuccess="onLogoutSuccess",U.onLogoutFailure="onLogoutFailure",U.onQrPending="onQrPending",U.onQrLoaded="onQrLoaded",U.onTxStart="onTxStart",U.onTxSent="onTxSent",U.onTxFinalized="onTxFinalized",U.onTxFailure="onTxFailure",U.onSignMsgStart="onSignMsgStart",U.onSignMsgFinalized="onSignMsgFinalized",U.onSignMsgFailure="onSignMsgFailure",U.onQueryStart="onQueryStart",U.onQueryFinalized="onQueryFinalized",U.onQueryFailure="onQueryFailure",U))(r9||{}),IC=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(IC||{}),dde=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(dde||{}),gde=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(gde||{});h();var Kt=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Fl=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");ge.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(me.clear(),ge.run("onLogoutSuccess")),e}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to logout the user: ${r}`),ge.run("onLogoutFailure",r)}};h();function R1(t){return t[Math.floor(Math.random()*t.length)]}var i9=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Fl(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=R1(t.initOptions.walletConnectV2RelayAddresses),n=new n9.WalletConnectV2Provider(e,Rr[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};h();var V1=pe(Ve(),1),p9=pe(s9(),1),m9=pe(a9(),1),y9=pe(PC(),1),w9=pe(d9(),1),v9=pe(jb(),1),A9=pe(g9(),1),E9=pe(Wf(),1);var k1=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||j0,this.apiUrl=e||Rr[this.chainType]?.apiAddress,this.apiTimeout=n||Rr[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),u=await o.json();if(!o.ok){let a=u?.error||o.status;return clearTimeout(i),Promise.reject(a)}return clearTimeout(i),u}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let u=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),a=await u.json();if(!u.ok){let c=a?.error||u.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),a}catch(u){this.handleApiError(u,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new V1.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new p9.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new V1.Address(r.sender),receiver:new V1.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:p.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:m9.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:y9.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:w9.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new E9.Query({address:e,func:r,args:n,value:i,caller:s}),u=new A9.ContractQueryRequest(o).toHttpRequest(),a=await this.apiPost("query",u);return v9.ContractQueryResponse.fromHttpResponse(a)}catch(o){this.handleApiError(o,"query")}}};h();h();var kl=()=>new Date().setHours(new Date().getHours()+24),H1=t=>Date.now()>t;h();var b9=pe(Ve(),1),S9=pe(Ic(),1);var Au=async t=>{let e=me.get("address"),r=me.get("expires");if(!(r&&H1(r))&&e&&t.networkProvider){let i=new b9.Address(e),s=new S9.Account(i);try{let o=await t.networkProvider.getAccount(i),u=await t.networkProvider.getGuardianData(i);me.set("address",e),me.set("activeGuardian",u.guarded&&u.activeGuardian?.address?u.activeGuardian.address:""),me.set("nonce",o.nonce.valueOf()),me.set("balance",o.balance.toString()),s.update(o)}catch(o){let u=Kt(o);console.warn(`Something went wrong trying to synchronize the user account: ${u}`)}}};var I9=async(t,e,r,n="/")=>{let i=await z0(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(a){let c=Kt(a);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:u}=i.account;if(me.set("loginToken",e),u&&me.set("signature",u),t.networkProvider&&u)try{let a=await i.getAddress();if(!a)throw new Error("Canceled!");me.set("address",a),me.set("loginMethod","browser-extension"),me.set("expires",kl()),await Au(t);let c=r.getToken(a,e,u);return me.set("accessToken",c),ge.run("onLoginSuccess"),i}catch(a){throw new Error(`Something went wrong trying to synchronize the user account: ${a?.message}`)}};h();h();var CV=pe(_V(),1),NV=pe(fd(),1);var fge=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},hge=t=>{let e=`${L8}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},dge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},gge=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},i3={},pge=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",i3[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:i3[t.topic].signal}),r},ew={},mge=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=pge(t,e);return n.appendChild(s),ew[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:ew[t.topic].signal}),n},yge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},wge=t=>{if(!t)return;document.getElementById(t)?.remove()},vge=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),Age=async t=>t?await CV.default.toString(t,{type:"svg"}):void 0,xV=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await Age(e),o;if(s&&(o=fge(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),vge()&&i.appendChild(hge(e))),i&&r instanceof NV.WalletConnectV2Provider){let u=r.pairings,a=async f=>{try{f&&(await r.logout({topic:f}),wge(f))}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to remove the existing pairing: ${w}`)}finally{ew[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(yge()),await r.login({approval:d,token:n})}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to login the user: ${w}`)}finally{for(let d of Object.values(ew))d?.abort();for(let d of Object.values(i3))d?.abort()}};if(u&&u.length>0){let f=dge();i.appendChild(f);let d=gge();f.appendChild(d);for(let w of u){let A=mge(w,a,c);f.appendChild(A)}}}return i};var tw=pe(fd(),1);var OV=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=R1(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof tw.WalletConnectV2Provider){let a=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();me.set("address",a),me.set("loginMethod","mobile"),me.set("expires",kl()),await Au(t),c&&me.set("signature",c),me.set("loginToken",e);let f=r.getToken(a,e,c);me.set("accessToken",f),ge.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof tw.WalletConnectV2Provider&&await Fl(t)},onClientEvent:a=>{console.log("wc2 session event: ",a)}},u=new tw.WalletConnectV2Provider(o,Rr[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(u){t.dappProvider=u,ge.run("onQrPending"),await u.init();let{uri:a,approval:c}=await u.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${a}&token=${e}`:a;return n&&f&&(s=await xV(n,f,u,e),ge.run("onQrLoaded")),await u.login({approval:c,token:e}),u}}catch(a){let c=Kt(a);console.warn(`Something went wrong trying to login the user: ${c}`),ge.run("onLoginFailure",c)}};h();var DV=pe(Dl(),1);var s3=async(t,e,r,n)=>{let i=new DV.WalletProvider(`${t}${Po}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return me.set("loginMethod",Rr[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),me.set("expires",kl()),me.set("loginToken",e),i}catch(u){let a=Kt(u);console.warn(`Something went wrong trying to login the user: ${a}`),me.set("loginMethod",""),ge.run("onLoginFailure",a)}};h();var ln=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};h();var PV=pe(Dl(),1);var RV=pe(SC(),1),o3=async(t,e)=>{let r=ln("signature"),n=ln("address"),i=me.get("address"),s=me.get("loginToken");if(r&&me.set("signature",r),n||i){n&&(me.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new PV.WalletProvider(`${t}${Po}`);if(r&&e&&n){let a=new RV.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);me.set("accessToken",a)}return o}};h();var BV=pe(Ic(),1),MV=pe(V0(),1);var rw=async(t,e)=>{ge.run("onTxSent",t);let n=await new MV.TransactionWatcher(e).awaitCompleted(t),i=n.sender,s=new BV.Account(i),o=await e.getAccount(i);s.update(o),me.set("address",s.address.bech32()),me.set("balance",s.balance.toString()),ge.run("onTxFinalized",n)};h();var Kl=pe(FV(),1),qV=pe(Xr(),1);h();var UV=pe(Ic(),1);var nw=t=>{let e=t.getSender(),r=new UV.Account(e),n=t.nonce.valueOf();r.incrementNonce(),me.set("nonce",(n+1n).toString())};var VV=async(t,e,r,n)=>{if(ln(Kl.WALLET_PROVIDER_CALLBACK_PARAM)===Kl.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=me.get("activeGuardian"),o=me.get("loginMethod"),u=ln("hasWebWalletGuardianSign"),a;if("getTransactionsFromWalletUrl"in t){if(a=t.getTransactionsFromWalletUrl()?.[0],!a)return;o==="web-wallet"&&(a.data=p.Buffer.from(a.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&u&&(a=new Kl.WalletProvider(`${r}${Po}`).getTransactionsFromWalletUrl()?.[0]);if(a){let c=qV.Transaction.fromPlainObject(a);c.nonce=BigInt(n),nw(c);try{ge.run("onTxStart",c),await e.sendTransaction(c),await rw(c,e)}catch(f){let w=`Getting transaction information failed! ${Kt(f)}`;throw ge.run("onTxFailure",c,w),new Error(w)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};h();var iw=pe($l(),1),kV=pe(Ve(),1),HV=pe(Dl(),1);var GV=t=>{let e=me.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(iw.TransactionVersion.withTxOptions()),t.setOptions(iw.TransactionOptions.withOptions(r)),t.setGuardian(kV.Address.fromBech32(e))}return t},jV=async(t,e)=>{let r=new HV.WalletProvider(`${e}${Po}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},zV=t=>{let e=me.get("activeGuardian");return!(!me.get("address")||!e||t.isGuardedTransaction())};h();var QV=()=>{let t=!ln("walletProviderStatus"),e=ln("status")==="signed",r=ln("message"),n=ln("signature");t&&e&&r&&n&&(ge.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};h();var u3=pe(Xr(),1);h();var KV=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(KV||{}),WV=(u=>(u.handshakeResponse="HANDSHAKE_RESPONSE",u.loginResponse="LOGIN_RESPONSE",u.disconnectResponse="DISCONNECT_RESPONSE",u.cancelResponse="CANCEL_RESPONSE",u.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",u.signMessageResponse="SIGN_MESSAGE_RESPONSE",u.noneResponse="NONE_RESPONSE",u))(WV||{}),a3={...WV,...KV},$V=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))($V||{}),YV=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(YV||{}),Tu={...YV,...$V};h();var JV=typeof window<"u"?window:{},XV=()=>JV.ReactNativeWebView?"reactNative":JV.webkit?"ios":"web",_u=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",sw=t=>Object.prototype.toString.call(t)==="[object String]";h();var ow={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,_u()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t}),_u())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t}),_u())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:Tu.logoutRequest}),_u())}};var aw=XV(),uw="message",ZV=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=_u()&&aw!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(uw,e),window&&window.addEventListener(uw,e)},ha=class{constructor(){}async logout(){return ow.logout[aw](),new Promise(e=>{e(!0)})}async signMessage(e){try{return ow.signMessage[aw](e),await new Promise((n,i)=>{window.signMessageResponse=(o,u)=>{if(u){i(u),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:u,type:a}=o;if(a===a3.signMessageResponse&&u!=null){let{signedMessage:c,error:f}=u;f?i(f):n(c)}document?.removeEventListener(uw,s)}ZV(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return ow.signTransactions[aw](r),await new Promise((i,s)=>{window.transactionsSigned=(u,a)=>{if(u=JSON.parse(u),a){s(a),window.transactionsSigned=null;return}i(u.map(c=>u3.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(u){let{message:a,type:c}=u;if(c===a3.signTransactionsResponse){let{transactions:f,error:d}=a;try{d?s(d):i(f.map(w=>u3.Transaction.fromPlainObject(w)))}catch{s("Unable to sign")}}document&&document.removeEventListener(uw,o)}ZV(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};h();h();h();function Sge(t){try{let e=atob(t),r=btoa(e),n=p.Buffer.from(t,"base64").toString(),i=p.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Wl(t){return Sge(t)?atob(t):t}h();var ek=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Wl(s)),u=Wl(r);return{ttl:Number(i),extraInfo:o,origin:u,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var tk=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Wl(r),o=Wl(n),u=ek(o);if(!u)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let a={...u,address:s,body:o,signature:i};return u.extraInfo?.timestamp||delete a.extraInfo,a}catch{return null}};function rk(t,e){let r=tk(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(me.set("loginToken",s),me.set("accessToken",t),me.set("signature",n),me.set("address",i),me.set("loginMethod","x-portal-hub"),e.dappProvider=new ha)}h();var nk=t=>{t.onLoginStart&&ge.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&ge.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&ge.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&ge.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&ge.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&ge.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&ge.set("onQrPending",t.onQrPending),t.onQrLoaded&&ge.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&ge.set("onTxStart",t.onTxStart),t.onTxSent&&ge.set("onTxSent",t.onTxSent),t.onTxFinalized&&ge.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&ge.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&ge.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&ge.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&ge.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&ge.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&ge.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&ge.set("onQueryFailure",t.onQueryFailure)};h();var cw=async t=>{ge.run("onLoginStart");try{await t(()=>{ge.run("onLoginSuccess")})}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to login the user: ${r}`),ge.run("onLoginFailure",r)}};var h3=class{static async init(e){let r=me.get();if(r.expires&&H1(r.expires)){me.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:j0,apiUrl:M8,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:F8,...e},this.networkProvider=new k1(this.initOptions),nk(this.initOptions);let n=ln("accessToken");n&&await cw(async s=>{rk(n,this),await Au(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&ln("address"))&&r?.loginMethod&&(await cw(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await z0()),r.loginMethod==="mobile"&&(this.dappProvider=await i9(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new ha),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Au(this),s()}),this.initOptions?.chainType&&(await VV(this.dappProvider,this.networkProvider,Rr[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),QV()))}static async login(e,r){if(!Object.values(IC).includes(e)){let i="Wrong login method!";throw ge.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw ge.run("onLoginFailure",i),new Error(i)}await cw(async()=>{let i=new ik.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await I9(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await OV(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Fl(this);return this.dappProvider=void 0,e}catch(e){let r=Kt(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw ge.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw ge.run("onTxFailure",e,n),new Error(n)}let r=GV(e);try{ge.run("onTxStart",e);let n=me.get();if(e.nonce=n.nonce,this.dappProvider instanceof c3.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof l3.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof ha&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof f3.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=zV(r);if(i||nw(r),i&&this.initOptions?.chainType){await jV(r,Rr[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await rw(r,this.networkProvider)}}catch(n){let i=Kt(n);throw ge.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(ge.run("onSignMsgStart",e),this.dappProvider instanceof c3.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof l3.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof ha&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof f3.WalletProvider){let s=u=>encodeURIComponent(u).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=me.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&ge.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Kt(i);throw ge.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{ge.run("onQueryStart",o);let u=await this.networkProvider.queryContract(o);return ge.run("onQueryFinalized",u),u}catch(u){let a=Kt(u);throw ge.run("onQueryFinalized",o,a),new Error(`Smart contract query failed! ${a}`)}}static{this.storage=me}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,ge.clear()}}};h();rr();Ou.config({ROUNDING_MODE:Ou.ROUND_FLOOR});var Ige=({amount:t,decimals:e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return BigInt(new Ou(t).shiftedBy(e).toFixed())},Tge=({amount:t,decimals:e,rounding:r=e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return new Ou(t).shiftedBy(-e).decimalPlaces(r).toFixed()};var export_Account=Cge.Account;var export_Address=_ge.Address;var export_AddressType=uk.AddressType;var export_AddressValue=uk.AddressValue;var export_BigUIntType=_s.BigUIntType;var export_BigUIntValue=_s.BigUIntValue;var export_BooleanType=ak.BooleanType;var export_BooleanValue=ak.BooleanValue;var export_BytesType=ok.BytesType;var export_BytesValue=ok.BytesValue;var export_ContractQueryResponse=Rge.ContractQueryResponse;var export_Message=sk.Message;var export_MessageComputer=sk.MessageComputer;var export_QueryArguments=Pge.QueryArguments;var export_SignableMessage=Dge.SignableMessage;var export_SmartContractTransactionsFactory=fw.SmartContractTransactionsFactory;var export_SmartContractTransactionsOutcomeParser=p3.SmartContractTransactionsOutcomeParser;var export_Token=d3.Token;var export_TokenComputer=d3.TokenComputer;var export_TokenManagementTransactionsFactory=fw.TokenManagementTransactionsFactory;var export_TokenManagementTransactionsOutcomeParser=p3.TokenManagementTransactionsOutcomeParser;var export_TokenOperationsFactory=g3.TokenOperationsFactory;var export_TokenOperationsFactoryConfig=g3.TokenOperationsFactoryConfig;var export_TokenOperationsOutcomeParser=g3.TokenOperationsOutcomeParser;var export_TokenTransfer=d3.TokenTransfer;var export_Transaction=Nge.Transaction;var export_TransactionComputer=xge.TransactionComputer;var export_TransactionEventsParser=p3.TransactionEventsParser;var export_TransactionWatcher=Oge.TransactionWatcher;var export_TransactionsFactoryConfig=fw.TransactionsFactoryConfig;var export_TransferTransactionsFactory=fw.TransferTransactionsFactory;var export_U16Type=_s.U16Type;var export_U16Value=_s.U16Value;var export_U32Type=_s.U32Type;var export_U32Value=_s.U32Value;var export_U64Type=_s.U64Type;var export_U64Value=_s.U64Value;var export_U8Type=_s.U8Type;var export_U8Value=_s.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractQueryResponse as ContractQueryResponse,dde as DappCoreWCV2CustomMethodsEnum,h3 as ElvenJS,r9 as EventStoreEvents,IC as LoginMethodsEnum,export_Message as Message,export_MessageComputer as MessageComputer,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContractTransactionsFactory as SmartContractTransactionsFactory,export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser,export_Token as Token,export_TokenComputer as TokenComputer,export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory,export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser,export_TokenOperationsFactory as TokenOperationsFactory,export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig,export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionComputer as TransactionComputer,export_TransactionEventsParser as TransactionEventsParser,export_TransactionWatcher as TransactionWatcher,export_TransactionsFactoryConfig as TransactionsFactoryConfig,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,gde as WebWalletUrlParamsEnum,Tge as formatAmount,Ige as parseAmount}; +/*! Bundled license information: ieee754/index.js: (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) @@ -54994,14 +72,6 @@ buffer/index.js: * @license MIT *) -buffer/index.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) - safe-buffer/index.js: (*! safe-buffer. MIT License. Feross Aboukhadijeh *) diff --git a/package-lock.json b/package-lock.json index a56bc3b..d408761 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,8 +19,9 @@ "@types/serve-handler": "6.1.4", "@typescript-eslint/eslint-plugin": "7.7.0", "@typescript-eslint/parser": "7.7.0", - "bignumber.js": "^9.1.2", + "bignumber.js": "9.1.2", "esbuild": "0.20.2", + "esbuild-plugin-alias": "^0.2.1", "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", "eslint-plugin-prettier": "5.1.3", @@ -2778,6 +2779,12 @@ "@esbuild/win32-x64": "0.20.2" } }, + "node_modules/esbuild-plugin-alias": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/esbuild-plugin-alias/-/esbuild-plugin-alias-0.2.1.tgz", + "integrity": "sha512-jyfL/pwPqaFXyKnj8lP8iLk6Z0m099uXR45aSN8Av1XD4vhvQutxxPzgA2bTcAwQpa1zCXDcWOlhFgyP3GKqhQ==", + "dev": true + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", diff --git a/package.json b/package.json index 6341fc0..42ae351 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "@typescript-eslint/parser": "7.7.0", "bignumber.js": "9.1.2", "esbuild": "0.20.2", + "esbuild-plugin-alias": "^0.2.1", "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", "eslint-plugin-prettier": "5.1.3", From 4584787a803d417f124715fc76644e3414a5fec6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20=C4=86wirko?= Date: Sun, 28 Apr 2024 15:54:31 +0200 Subject: [PATCH 3/5] updat dependencies --- build/elven.js | 58 +++--- example/elven.js | 58 +++--- package-lock.json | 468 ++++++++++++++++++++++++++++------------------ package.json | 5 +- 4 files changed, 341 insertions(+), 248 deletions(-) diff --git a/build/elven.js b/build/elven.js index ec95d64..d1317cb 100644 --- a/build/elven.js +++ b/build/elven.js @@ -1,26 +1,26 @@ -var ck=Object.create;var Rd=Object.defineProperty;var lk=Object.getOwnPropertyDescriptor;var fk=Object.getOwnPropertyNames;var hk=Object.getPrototypeOf,dk=Object.prototype.hasOwnProperty;var Bd=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)Rd(t,r,{get:e[r],enumerable:!0})},Pd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fk(e))!dk.call(t,i)&&i!==r&&Rd(t,i,{get:()=>e[i],enumerable:!(n=lk(e,i))||n.enumerable});return t},Tr=(t,e,r)=>(Pd(t,e,"default"),r&&Pd(r,e,"default")),pe=(t,e,r)=>(r=t!=null?ck(hk(t)):{},Pd(e||!t||!t.__esModule?Rd(r,"default",{value:t,enumerable:!0}):r,t)),_e=t=>Pd(Rd({},"__esModule",{value:!0}),t);var w3=B(Md=>{"use strict";h();Md.byteLength=pk;Md.toByteArray=yk;Md.fromByteArray=Ak;var Pi=[],Tn=[],gk=typeof Uint8Array<"u"?Uint8Array:Array,mw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ba=0,m3=mw.length;ba0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function pk(t){var e=y3(t),r=e[0],n=e[1];return(r+n)*3/4-n}function mk(t,e,r){return(e+r)*3/4-r}function yk(t){var e,r=y3(t),n=r[0],i=r[1],s=new gk(mk(t,n,i)),o=0,u=i>0?n-4:n,a;for(a=0;a>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tn[t.charCodeAt(a)]<<2|Tn[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=Tn[t.charCodeAt(a)]<<10|Tn[t.charCodeAt(a+1)]<<4|Tn[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function wk(t){return Pi[t>>18&63]+Pi[t>>12&63]+Pi[t>>6&63]+Pi[t&63]}function vk(t,e,r){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=t[r-1],i.push(Pi[e>>2]+Pi[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Pi[e>>10]+Pi[e>>4&63]+Pi[e<<2&63]+"=")),i.join("")}});var v3=B(yw=>{h();yw.read=function(t,e,r,n,i){var s,o,u=i*8-n-1,a=(1<>1,f=-7,d=r?i-1:0,w=r?-1:1,A=t[e+d];for(d+=w,s=A&(1<<-f)-1,A>>=-f,f+=u;f>0;s=s*256+t[e+d],d+=w,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=w,f-=8);if(s===0)s=1-c;else{if(s===a)return o?NaN:(A?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(A?-1:1)*o*Math.pow(2,s-n)};yw.write=function(t,e,r,n,i,s){var o,u,a,c=s*8-i-1,f=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:s-1,T=n?1:-1,x=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=w/a:e+=w*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=f?(u=0,o=f):o+d>=1?(u=(e*a-1)*Math.pow(2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+A]=u&255,A+=T,u/=256,i-=8);for(o=o<0;t[r+A]=o&255,A+=T,o/=256,c-=8);t[r+A-T]|=x*128}});var io=B(Nu=>{"use strict";h();var ww=w3(),Cu=v3(),A3=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nu.Buffer=X;Nu.SlowBuffer=_k;Nu.INSPECT_MAX_BYTES=50;var Ld=2147483647;Nu.kMaxLength=Ld;X.TYPED_ARRAY_SUPPORT=Ek();!X.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 Ek(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(X.prototype,"parent",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.buffer}});Object.defineProperty(X.prototype,"offset",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.byteOffset}});function Cs(t){if(t>Ld)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,X.prototype),e}function X(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return bw(t)}return S3(t,e,r)}X.poolSize=8192;function S3(t,e,r){if(typeof t=="string")return Sk(t,e);if(ArrayBuffer.isView(t))return Ik(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Ri(t,ArrayBuffer)||t&&Ri(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ri(t,SharedArrayBuffer)||t&&Ri(t.buffer,SharedArrayBuffer)))return Aw(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return X.from(n,e,r);var i=Tk(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return X.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}X.from=function(t,e,r){return S3(t,e,r)};Object.setPrototypeOf(X.prototype,Uint8Array.prototype);Object.setPrototypeOf(X,Uint8Array);function I3(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function bk(t,e,r){return I3(t),t<=0?Cs(t):e!==void 0?typeof r=="string"?Cs(t).fill(e,r):Cs(t).fill(e):Cs(t)}X.alloc=function(t,e,r){return bk(t,e,r)};function bw(t){return I3(t),Cs(t<0?0:Sw(t)|0)}X.allocUnsafe=function(t){return bw(t)};X.allocUnsafeSlow=function(t){return bw(t)};function Sk(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!X.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=T3(t,e)|0,n=Cs(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function vw(t){for(var e=t.length<0?0:Sw(t.length)|0,r=Cs(e),n=0;n=Ld)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ld.toString(16)+" bytes");return t|0}function _k(t){return+t!=t&&(t=0),X.alloc(+t)}X.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==X.prototype};X.compare=function(e,r){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),Ri(r,Uint8Array)&&(r=X.from(r,r.offset,r.byteLength)),!X.isBuffer(e)||!X.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?X.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(X.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function T3(t,e){if(X.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ri(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Ew(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return D3(t).length;default:if(i)return n?-1:Ew(t).length;e=(""+e).toLowerCase(),i=!0}}X.byteLength=T3;function Ck(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return Fk(this,e,r);case"utf8":case"utf-8":return C3(this,e,r);case"ascii":return Mk(this,e,r);case"latin1":case"binary":return Lk(this,e,r);case"base64":return Rk(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Uk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}X.prototype._isBuffer=!0;function Sa(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}X.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};A3&&(X.prototype[A3]=X.prototype.inspect);X.prototype.compare=function(e,r,n,i,s){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),!X.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=n-r,a=Math.min(o,u),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Iw(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=X.from(e,n)),X.isBuffer(e))return e.length===0?-1:E3(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):E3(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function E3(t,e,r,n,i){var s=1,o=t.length,u=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,u/=2,r/=2}function a(A,T){return s===1?A[T]:A.readUInt16BE(T*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-u),c=r;c>=0;c--){for(var d=!0,w=0;wi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Nk(this,e,r,n);case"utf8":case"utf-8":return xk(this,e,r,n);case"ascii":case"latin1":case"binary":return Ok(this,e,r,n);case"base64":return Dk(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Pk(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Rk(t,e,r){return e===0&&r===t.length?ww.fromByteArray(t):ww.fromByteArray(t.slice(e,r))}function C3(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+u<=r){var a,c,f,d;switch(u){case 1:s<128&&(o=s);break;case 2:a=t[i+1],(a&192)===128&&(d=(s&31)<<6|a&63,d>127&&(o=d));break;case 3:a=t[i+1],c=t[i+2],(a&192)===128&&(c&192)===128&&(d=(s&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:a=t[i+1],c=t[i+2],f=t[i+3],(a&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(a&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=u}return Bk(n)}var b3=4096;function Bk(t){var e=t.length;if(e<=b3)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}X.prototype.readUintLE=X.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};X.prototype.readUint8=X.prototype.readUInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]};X.prototype.readUint16LE=X.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]|this[e+1]<<8};X.prototype.readUint16BE=X.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]<<8|this[e+1]};X.prototype.readUint32LE=X.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};X.prototype.readUint32BE=X.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};X.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};X.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};X.prototype.readInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};X.prototype.readInt16LE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};X.prototype.readInt16BE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};X.prototype.readInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};X.prototype.readInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};X.prototype.readFloatLE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!0,23,4)};X.prototype.readFloatBE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!1,23,4)};X.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!0,52,8)};X.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!1,52,8)};function zr(t,e,r,n,i,s){if(!X.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}X.prototype.writeUintLE=X.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=1,u=0;for(this[r]=e&255;++u>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=n-1,u=1;for(this[r+o]=e&255;--o>=0&&(u*=256);)this[r+o]=e/u&255;return r+n};X.prototype.writeUint8=X.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,255,0),this[r]=e&255,r+1};X.prototype.writeUint16LE=X.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeUint16BE=X.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeUint32LE=X.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};X.prototype.writeUint32BE=X.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};X.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=0,u=1,a=0;for(this[r]=e&255;++o>0)-a&255;return r+n};X.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=n-1,u=1,a=0;for(this[r+o]=e&255;--o>=0&&(u*=256);)e<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(e/u>>0)-a&255;return r+n};X.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};X.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};X.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function N3(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function x3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,4,34028234663852886e22,-34028234663852886e22),Cu.write(t,e,r,n,23,4),r+4}X.prototype.writeFloatLE=function(e,r,n){return x3(this,e,r,!0,n)};X.prototype.writeFloatBE=function(e,r,n){return x3(this,e,r,!1,n)};function O3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,8,17976931348623157e292,-17976931348623157e292),Cu.write(t,e,r,n,52,8),r+8}X.prototype.writeDoubleLE=function(e,r,n){return O3(this,e,r,!0,n)};X.prototype.writeDoubleBE=function(e,r,n){return O3(this,e,r,!1,n)};X.prototype.copy=function(e,r,n,i){if(!X.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function kk(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function D3(t){return ww.toByteArray(Vk(t))}function Fd(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Ri(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Iw(t){return t!==t}var Gk=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var L3=B((kge,M3)=>{h();var Wt=M3.exports={},Bi,Mi;function Tw(){throw new Error("setTimeout has not been defined")}function _w(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Bi=setTimeout:Bi=Tw}catch{Bi=Tw}try{typeof clearTimeout=="function"?Mi=clearTimeout:Mi=_w}catch{Mi=_w}})();function P3(t){if(Bi===setTimeout)return setTimeout(t,0);if((Bi===Tw||!Bi)&&setTimeout)return Bi=setTimeout,setTimeout(t,0);try{return Bi(t,0)}catch{try{return Bi.call(null,t,0)}catch{return Bi.call(this,t,0)}}}function jk(t){if(Mi===clearTimeout)return clearTimeout(t);if((Mi===_w||!Mi)&&clearTimeout)return Mi=clearTimeout,clearTimeout(t);try{return Mi(t)}catch{try{return Mi.call(null,t)}catch{return Mi.call(this,t)}}}var Ns=[],xu=!1,Ia,Ud=-1;function zk(){!xu||!Ia||(xu=!1,Ia.length?Ns=Ia.concat(Ns):Ud=-1,Ns.length&&R3())}function R3(){if(!xu){var t=P3(zk);xu=!0;for(var e=Ns.length;e;){for(Ia=Ns,Ns=[];++Ud1)for(var r=1;r{p=pe(io()),I=pe(L3()),Qk=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=Qk});var fr={};Bt(fr,{BigNumber:()=>q3,default:()=>Ou});function U3(t){var e,r,n,i=U.prototype={constructor:U,toString:null,valueOf:null},s=new U(1),o=20,u=4,a=-7,c=21,f=-1e7,d=1e7,w=!1,A=1,T=0,x={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},R="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function U(v,C){var D,F,P,l,g,y,E,S,_=this;if(!(_ instanceof U))return new U(v,C);if(C==null){if(v&&v._isBigNumber===!0){_.s=v.s,!v.c||v.e>d?_.c=_.e=null:v.e=10;g/=10,l++);l>d?_.c=_.e=null:(_.e=l,_.c=[v]);return}S=String(v)}else{if(!Kk.test(S=String(v)))return n(_,S,y);_.s=S.charCodeAt(0)==45?(S=S.slice(1),-1):1}(l=S.indexOf("."))>-1&&(S=S.replace(".","")),(g=S.search(/e/i))>0?(l<0&&(l=g),l+=+S.slice(g+1),S=S.substring(0,g)):l<0&&(l=S.length)}else{if(Ht(C,2,R.length,"Base"),C==10&&V)return _=new U(v),H(_,o+_.e+1,u);if(S=String(v),y=typeof v=="number"){if(v*0!=0)return n(_,S,y,C);if(_.s=1/v<0?(S=S.slice(1),-1):1,U.DEBUG&&S.replace(/^0\.0*|\./,"").length>15)throw Error(F3+v)}else _.s=S.charCodeAt(0)===45?(S=S.slice(1),-1):1;for(D=R.slice(0,C),l=g=0,E=S.length;gl){l=E;continue}}else if(!P&&(S==S.toUpperCase()&&(S=S.toLowerCase())||S==S.toLowerCase()&&(S=S.toUpperCase()))){P=!0,g=-1,l=0;continue}return n(_,String(v),y,C)}y=!1,S=r(S,C,10,_.s),(l=S.indexOf("."))>-1?S=S.replace(".",""):l=S.length}for(g=0;S.charCodeAt(g)===48;g++);for(E=S.length;S.charCodeAt(--E)===48;);if(S=S.slice(g,++E)){if(E-=g,y&&U.DEBUG&&E>15&&(v>Nw||v!==Cn(v)))throw Error(F3+_.s*v);if((l=l-g-1)>d)_.c=_.e=null;else if(l=-mr&&P<=mr&&P===Cn(P)){if(F[0]===0){if(P===0&&F.length===1)return!0;break e}if(C=(P+1)%be,C<1&&(C+=be),String(F[0]).length==C){for(C=0;C=di||D!==Cn(D))break e;if(D!==0)return!0}}}else if(F===null&&P===null&&(l===null||l===1||l===-1))return!0;throw Error(Qr+"Invalid BigNumber: "+v)},U.maximum=U.max=function(){return L(arguments,-1)},U.minimum=U.min=function(){return L(arguments,1)},U.random=function(){var v=9007199254740992,C=Math.random()*v&2097151?function(){return Cn(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var F,P,l,g,y,E=0,S=[],_=new U(s);if(D==null?D=o:Ht(D,0,mr),g=Cw(D/be),w)if(crypto.getRandomValues){for(F=crypto.getRandomValues(new Uint32Array(g*=2));E>>11),y>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),F[E]=P[0],F[E+1]=P[1]):(S.push(y%1e14),E+=2);E=g/2}else if(crypto.randomBytes){for(F=crypto.randomBytes(g*=7);E=9e15?crypto.randomBytes(7).copy(F,E):(S.push(y%1e14),E+=7);E=g/7}else throw w=!1,Error(Qr+"crypto unavailable");if(!w)for(;E=10;y/=10,E++);EP-1&&(y[g+1]==null&&(y[g+1]=0),y[g+1]+=y[g]/P|0,y[g]%=P)}return y.reverse()}return function(D,F,P,l,g){var y,E,S,_,M,N,m,O,Y=D.indexOf("."),$=o,b=u;for(Y>=0&&(_=T,T=0,D=D.replace(".",""),O=new U(F),N=O.pow(D.length-Y),T=_,O.c=C(Os(_n(N.c),N.e,"0"),10,P,v),O.e=O.c.length),m=C(D,F,P,g?(y=R,v):(y=v,R)),S=_=m.length;m[--_]==0;m.pop());if(!m[0])return y.charAt(0);if(Y<0?--S:(N.c=m,N.e=S,N.s=l,N=e(N,O,$,b,P),m=N.c,M=N.r,S=N.e),E=S+$+1,Y=m[E],_=P/2,M=M||E<0||m[E+1]!=null,M=b<4?(Y!=null||M)&&(b==0||b==(N.s<0?3:2)):Y>_||Y==_&&(b==4||M||b==6&&m[E-1]&1||b==(N.s<0?8:7)),E<1||!m[0])D=M?Os(y.charAt(1),-$,y.charAt(0)):y.charAt(0);else{if(m.length=E,M)for(--P;++m[--E]>P;)m[E]=0,E||(++S,m=[1].concat(m));for(_=m.length;!m[--_];);for(Y=0,D="";Y<=_;D+=y.charAt(m[Y++]));D=Os(D,S,y.charAt(0))}return D}}(),e=function(){function v(F,P,l){var g,y,E,S,_=0,M=F.length,N=P%so,m=P/so|0;for(F=F.slice();M--;)E=F[M]%so,S=F[M]/so|0,g=m*E+S*N,y=N*E+g%so*so+_,_=(y/l|0)+(g/so|0)+m*S,F[M]=y%l;return _&&(F=[_].concat(F)),F}function C(F,P,l,g){var y,E;if(l!=g)E=l>g?1:-1;else for(y=E=0;yP[y]?1:-1;break}return E}function D(F,P,l,g){for(var y=0;l--;)F[l]-=y,y=F[l]1;F.splice(0,1));}return function(F,P,l,g,y){var E,S,_,M,N,m,O,Y,$,b,j,z,W,ie,te,ee,se,oe=F.s==P.s?1:-1,J=F.c,ue=P.c;if(!J||!J[0]||!ue||!ue[0])return new U(!F.s||!P.s||(J?ue&&J[0]==ue[0]:!ue)?NaN:J&&J[0]==0||!ue?oe*0:oe/0);for(Y=new U(oe),$=Y.c=[],S=F.e-P.e,oe=l+S+1,y||(y=di,S=Nn(F.e/be)-Nn(P.e/be),oe=oe/be|0),_=0;ue[_]==(J[_]||0);_++);if(ue[_]>(J[_]||0)&&S--,oe<0)$.push(1),M=!0;else{for(ie=J.length,ee=ue.length,_=0,oe+=2,N=Cn(y/(ue[0]+1)),N>1&&(ue=v(ue,N,y),J=v(J,N,y),ee=ue.length,ie=J.length),W=ee,b=J.slice(0,ee),j=b.length;j=y/2&&te++;do{if(N=0,E=C(ue,b,ee,j),E<0){if(z=b[0],ee!=j&&(z=z*y+(b[1]||0)),N=Cn(z/te),N>1)for(N>=y&&(N=y-1),m=v(ue,N,y),O=m.length,j=b.length;C(m,b,O,j)==1;)N--,D(m,ee=10;oe/=10,_++);H(Y,l+(Y.e=_+S*be-1)+1,g,M)}else Y.e=S,Y.r=+M;return Y}}();function Q(v,C,D,F){var P,l,g,y,E;if(D==null?D=u:Ht(D,0,8),!v.c)return v.toString();if(P=v.c[0],g=v.e,C==null)E=_n(v.c),E=F==1||F==2&&(g<=a||g>=c)?Vd(E,g):Os(E,g,"0");else if(v=H(new U(v),C,D),l=v.e,E=_n(v.c),y=E.length,F==1||F==2&&(C<=l||l<=a)){for(;yy){if(--C>0)for(E+=".";C--;E+="0");}else if(C+=l-y,C>0)for(l+1==y&&(E+=".");C--;E+="0");return v.s<0&&P?"-"+E:E}function L(v,C){for(var D,F,P=1,l=new U(v[0]);P=10;P/=10,F++);return(D=F+D*be-1)>d?v.c=v.e=null:D=10;y/=10,P++);if(l=C-P,l<0)l+=be,g=C,E=M[S=0],_=Cn(E/N[P-g-1]%10);else if(S=Cw((l+1)/be),S>=M.length)if(F){for(;M.length<=S;M.push(0));E=_=0,P=1,l%=be,g=l-be+1}else break e;else{for(E=y=M[S],P=1;y>=10;y/=10,P++);l%=be,g=l-be+P,_=g<0?0:Cn(E/N[P-g-1]%10)}if(F=F||C<0||M[S+1]!=null||(g<0?E:E%N[P-g-1]),F=D<4?(_||F)&&(D==0||D==(v.s<0?3:2)):_>5||_==5&&(D==4||F||D==6&&(l>0?g>0?E/N[P-g]:0:M[S-1])%10&1||D==(v.s<0?8:7)),C<1||!M[0])return M.length=0,F?(C-=v.e+1,M[0]=N[(be-C%be)%be],v.e=-C||0):M[0]=v.e=0,v;if(l==0?(M.length=S,y=1,S--):(M.length=S+1,y=N[be-l],M[S]=g>0?Cn(E/N[P-g]%N[g])*y:0),F)for(;;)if(S==0){for(l=1,g=M[0];g>=10;g/=10,l++);for(g=M[0]+=y,y=1;g>=10;g/=10,y++);l!=y&&(v.e++,M[0]==di&&(M[0]=1));break}else{if(M[S]+=y,M[S]!=di)break;M[S--]=0,y=1}for(l=M.length;M[--l]===0;M.pop());}v.e>d?v.c=v.e=null:v.e=c?Vd(C,D):Os(C,D,"0"),v.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var v=new U(this);return v.s<0&&(v.s=1),v},i.comparedTo=function(v,C){return Ta(this,new U(v,C))},i.decimalPlaces=i.dp=function(v,C){var D,F,P,l=this;if(v!=null)return Ht(v,0,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v+l.e+1,C);if(!(D=l.c))return null;if(F=((P=D.length-1)-Nn(this.e/be))*be,P=D[P])for(;P%10==0;P/=10,F--);return F<0&&(F=0),F},i.dividedBy=i.div=function(v,C){return e(this,new U(v,C),o,u)},i.dividedToIntegerBy=i.idiv=function(v,C){return e(this,new U(v,C),0,1)},i.exponentiatedBy=i.pow=function(v,C){var D,F,P,l,g,y,E,S,_,M=this;if(v=new U(v),v.c&&!v.isInteger())throw Error(Qr+"Exponent not an integer: "+q(v));if(C!=null&&(C=new U(C)),y=v.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!v.c||!v.c[0])return _=new U(Math.pow(+q(M),y?v.s*(2-qd(v)):+q(v))),C?_.mod(C):_;if(E=v.s<0,C){if(C.c?!C.c[0]:!C.s)return new U(NaN);F=!E&&M.isInteger()&&C.isInteger(),F&&(M=M.mod(C))}else{if(v.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||y&&M.c[1]>=24e7:M.c[0]<8e13||y&&M.c[0]<=9999975e7)))return l=M.s<0&&qd(v)?-0:0,M.e>-1&&(l=1/l),new U(E?1/l:l);T&&(l=Cw(T/be+2))}for(y?(D=new U(.5),E&&(v.s=1),S=qd(v)):(P=Math.abs(+q(v)),S=P%2),_=new U(s);;){if(S){if(_=_.times(M),!_.c)break;l?_.c.length>l&&(_.c.length=l):F&&(_=_.mod(C))}if(P){if(P=Cn(P/2),P===0)break;S=P%2}else if(v=v.times(D),H(v,v.e+1,1),v.e>14)S=qd(v);else{if(P=+q(v),P===0)break;S=P%2}M=M.times(M),l?M.c&&M.c.length>l&&(M.c.length=l):F&&(M=M.mod(C))}return F?_:(E&&(_=s.div(_)),C?_.mod(C):l?H(_,T,u,g):_)},i.integerValue=function(v){var C=new U(this);return v==null?v=u:Ht(v,0,8),H(C,C.e+1,v)},i.isEqualTo=i.eq=function(v,C){return Ta(this,new U(v,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(v,C){return Ta(this,new U(v,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(v,C){return(C=Ta(this,new U(v,C)))===1||C===0},i.isInteger=function(){return!!this.c&&Nn(this.e/be)>this.c.length-2},i.isLessThan=i.lt=function(v,C){return Ta(this,new U(v,C))<0},i.isLessThanOrEqualTo=i.lte=function(v,C){return(C=Ta(this,new U(v,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(v,C){var D,F,P,l,g=this,y=g.s;if(v=new U(v,C),C=v.s,!y||!C)return new U(NaN);if(y!=C)return v.s=-C,g.plus(v);var E=g.e/be,S=v.e/be,_=g.c,M=v.c;if(!E||!S){if(!_||!M)return _?(v.s=-C,v):new U(M?g:NaN);if(!_[0]||!M[0])return M[0]?(v.s=-C,v):new U(_[0]?g:u==3?-0:0)}if(E=Nn(E),S=Nn(S),_=_.slice(),y=E-S){for((l=y<0)?(y=-y,P=_):(S=E,P=M),P.reverse(),C=y;C--;P.push(0));P.reverse()}else for(F=(l=(y=_.length)<(C=M.length))?y:C,y=C=0;C0)for(;C--;_[D++]=0);for(C=di-1;F>y;){if(_[--F]=0;){for(D=0,N=z[P]%$,m=z[P]/$|0,g=E,l=P+g;l>P;)S=j[--g]%$,_=j[g]/$|0,y=m*S+_*N,S=N*S+y%$*$+O[l]+D,D=(S/Y|0)+(y/$|0)+m*_,O[l--]=S%Y;O[l]=D}return D?++F:O.splice(0,1),k(v,O,F)},i.negated=function(){var v=new U(this);return v.s=-v.s||null,v},i.plus=function(v,C){var D,F=this,P=F.s;if(v=new U(v,C),C=v.s,!P||!C)return new U(NaN);if(P!=C)return v.s=-C,F.minus(v);var l=F.e/be,g=v.e/be,y=F.c,E=v.c;if(!l||!g){if(!y||!E)return new U(P/0);if(!y[0]||!E[0])return E[0]?v:new U(y[0]?F:P*0)}if(l=Nn(l),g=Nn(g),y=y.slice(),P=l-g){for(P>0?(g=l,D=E):(P=-P,D=y),D.reverse();P--;D.push(0));D.reverse()}for(P=y.length,C=E.length,P-C<0&&(D=E,E=y,y=D,C=P),P=0;C;)P=(y[--C]=y[C]+E[C]+P)/di|0,y[C]=di===y[C]?0:y[C]%di;return P&&(y=[P].concat(y),++g),k(v,y,g)},i.precision=i.sd=function(v,C){var D,F,P,l=this;if(v!=null&&v!==!!v)return Ht(v,1,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v,C);if(!(D=l.c))return null;if(P=D.length-1,F=P*be+1,P=D[P]){for(;P%10==0;P/=10,F--);for(P=D[0];P>=10;P/=10,F++);}return v&&l.e+1>F&&(F=l.e+1),F},i.shiftedBy=function(v){return Ht(v,-Nw,Nw),this.times("1e"+v)},i.squareRoot=i.sqrt=function(){var v,C,D,F,P,l=this,g=l.c,y=l.s,E=l.e,S=o+4,_=new U("0.5");if(y!==1||!g||!g[0])return new U(!y||y<0&&(!g||g[0])?NaN:g?l:1/0);if(y=Math.sqrt(+q(l)),y==0||y==1/0?(C=_n(g),(C.length+E)%2==0&&(C+="0"),y=Math.sqrt(+C),E=Nn((E+1)/2)-(E<0||E%2),y==1/0?C="5e"+E:(C=y.toExponential(),C=C.slice(0,C.indexOf("e")+1)+E),D=new U(C)):D=new U(y+""),D.c[0]){for(E=D.e,y=E+S,y<3&&(y=0);;)if(P=D,D=_.times(P.plus(e(l,P,S,1))),_n(P.c).slice(0,y)===(C=_n(D.c)).slice(0,y))if(D.e0&&O>0){for(l=O%y||y,_=m.substr(0,l);l0&&(_+=S+m.slice(l)),N&&(_="-"+_)}F=M?_+(D.decimalSeparator||"")+((E=+D.fractionGroupSize)?M.replace(new RegExp("\\d{"+E+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):M):_}return(D.prefix||"")+F+(D.suffix||"")},i.toFraction=function(v){var C,D,F,P,l,g,y,E,S,_,M,N,m=this,O=m.c;if(v!=null&&(y=new U(v),!y.isInteger()&&(y.c||y.s!==1)||y.lt(s)))throw Error(Qr+"Argument "+(y.isInteger()?"out of range: ":"not an integer: ")+q(y));if(!O)return new U(m);for(C=new U(s),S=D=new U(s),F=E=new U(s),N=_n(O),l=C.e=N.length-m.e-1,C.c[0]=xw[(g=l%be)<0?be+g:g],v=!v||y.comparedTo(C)>0?l>0?C:S:y,g=d,d=1/0,y=new U(N),E.c[0]=0;_=e(y,C,0,1),P=D.plus(_.times(F)),P.comparedTo(v)!=1;)D=F,F=P,S=E.plus(_.times(P=S)),E=P,C=y.minus(_.times(P=C)),y=P;return P=e(v.minus(D),F,0,1),E=E.plus(P.times(S)),D=D.plus(P.times(F)),E.s=S.s=m.s,l=l*2,M=e(S,F,l,u).minus(m).abs().comparedTo(e(E,D,l,u).minus(m).abs())<1?[S,F]:[E,D],d=g,M},i.toNumber=function(){return+q(this)},i.toPrecision=function(v,C){return v!=null&&Ht(v,1,mr),Q(this,v,C,2)},i.toString=function(v){var C,D=this,F=D.s,P=D.e;return P===null?F?(C="Infinity",F<0&&(C="-"+C)):C="NaN":(v==null?C=P<=a||P>=c?Vd(_n(D.c),P):Os(_n(D.c),P,"0"):v===10&&V?(D=H(new U(D),o+P+1,u),C=Os(_n(D.c),D.e,"0")):(Ht(v,2,R.length,"Base"),C=r(Os(_n(D.c),P,"0"),10,v,F,!0)),F<0&&D.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return q(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&U.set(t),U}function Nn(t){var e=t|0;return t>0||t===e?e:e-1}function _n(t){for(var e,r,n=1,i=t.length,s=t[0]+"";nc^r?1:-1;for(u=(a=i.length)<(c=s.length)?a:c,o=0;os[o]^r?1:-1;return a==c?0:a>c^r?1:-1}function Ht(t,e,r,n){if(tr||t!==Cn(t))throw Error(Qr+(n||"Argument")+(typeof t=="number"?tr?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function qd(t){var e=t.c.length-1;return Nn(t.e/be)==e&&t.c[e]%2!=0}function Vd(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Os(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e{h();Kk=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Cw=Math.ceil,Cn=Math.floor,Qr="[BigNumber Error] ",F3=Qr+"Number primitive has more than 15 significant digits: ",di=1e14,be=14,Nw=9007199254740991,xw=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],so=1e7,mr=1e9;q3=U3(),Ou=q3});var Ie=B(ce=>{"use strict";h();Object.defineProperty(ce,"__esModule",{value:!0});ce.ErrParseTransactionOutcome=ce.ErrInvalidInnerTransaction=ce.ErrBadUsage=ce.ErrInvalidTokenIdentifier=ce.ErrIsCompletedFieldIsMissingOnTransaction=ce.ErrGasLimitShouldBe0ForInnerTransaction=ce.ErrInvalidRelayedV2BuilderArguments=ce.ErrInvalidRelayedV1BuilderArguments=ce.ErrNotImplemented=ce.ErrContractInteraction=ce.ErrCodec=ce.ErrCannotParseTransactionOutcome=ce.ErrCannotParseContractResults=ce.ErrMissingFieldOnEnum=ce.ErrMissingFieldOnStruct=ce.ErrTypingSystem=ce.ErrMock=ce.ErrContractHasNoAddress=ce.ErrContract=ce.ErrExpectedTransactionEventsNotFound=ce.ErrExpectedTransactionStatusNotReached=ce.ErrTransactionWatcherTimeout=ce.ErrAsyncTimerAborted=ce.ErrAsyncTimerAlreadyRunning=ce.ErrInvalidFunctionName=ce.ErrSignatureCannotCreate=ce.ErrTransactionOptionsInvalid=ce.ErrTransactionVersionInvalid=ce.ErrNonceInvalid=ce.ErrNotEnoughGas=ce.ErrAddressEmpty=ce.ErrAddressBadHrp=ce.ErrAddressCannotCreate=ce.ErrUnexpectedCondition=ce.ErrInvariantFailed=ce.ErrBadType=ce.ErrUnsupportedOperation=ce.ErrInvalidArgument=ce.Err=void 0;var Ce=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};ce.Err=Ce;var Ow=class extends Ce{constructor(e,r){super(`Invalid argument: ${e}`,r)}};ce.ErrInvalidArgument=Ow;var Dw=class extends Ce{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};ce.ErrUnsupportedOperation=Dw;var Pw=class extends Ce{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};ce.ErrBadType=Pw;var Rw=class extends Ce{constructor(e){super(`Invariant failed: [${e}]`)}};ce.ErrInvariantFailed=Rw;var Bw=class extends Ce{constructor(e){super(`Unexpected condition: [${e}]`)}};ce.ErrUnexpectedCondition=Bw;var Mw=class extends Ce{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};ce.ErrAddressCannotCreate=Mw;var Lw=class extends Ce{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};ce.ErrAddressBadHrp=Lw;var Fw=class extends Ce{constructor(){super("Address is empty")}};ce.ErrAddressEmpty=Fw;var Uw=class extends Ce{constructor(e){super(`Not enough gas provided: ${e}`)}};ce.ErrNotEnoughGas=Uw;var qw=class extends Ce{constructor(e){super(`Invalid nonce: ${e}`)}};ce.ErrNonceInvalid=qw;var Vw=class extends Ce{constructor(e){super(`Invalid transaction version: ${e}`)}};ce.ErrTransactionVersionInvalid=Vw;var kw=class extends Ce{constructor(e){super(`Invalid transaction options: ${e}`)}};ce.ErrTransactionOptionsInvalid=kw;var Hw=class extends Ce{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};ce.ErrSignatureCannotCreate=Hw;var Gw=class extends Ce{constructor(){super("Invalid function name")}};ce.ErrInvalidFunctionName=Gw;var jw=class extends Ce{constructor(){super("Async timer already running")}};ce.ErrAsyncTimerAlreadyRunning=jw;var zw=class extends Ce{constructor(){super("Async timer aborted")}};ce.ErrAsyncTimerAborted=zw;var Qw=class extends Ce{constructor(){super("TransactionWatcher has timed out")}};ce.ErrTransactionWatcherTimeout=Qw;var Kw=class extends Ce{constructor(){super("Expected transaction status not reached")}};ce.ErrExpectedTransactionStatusNotReached=Kw;var Ww=class extends Ce{constructor(){super("Expected transaction events not found")}};ce.ErrExpectedTransactionEventsNotFound=Ww;var kd=class extends Ce{constructor(e){super(e)}};ce.ErrContract=kd;var $w=class extends kd{constructor(){super(` +var Ik=Object.create;var Dd=Object.defineProperty;var Tk=Object.getOwnPropertyDescriptor;var _k=Object.getOwnPropertyNames;var Ck=Object.getPrototypeOf,Nk=Object.prototype.hasOwnProperty;var Pd=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)Dd(t,r,{get:e[r],enumerable:!0})},Od=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _k(e))!Nk.call(t,i)&&i!==r&&Dd(t,i,{get:()=>e[i],enumerable:!(n=Tk(e,i))||n.enumerable});return t},Tr=(t,e,r)=>(Od(t,e,"default"),r&&Od(r,e,"default")),pe=(t,e,r)=>(r=t!=null?Ik(Ck(t)):{},Od(e||!t||!t.__esModule?Dd(r,"default",{value:t,enumerable:!0}):r,t)),_e=t=>Od(Dd({},"__esModule",{value:!0}),t);var y3=D(Rd=>{"use strict";h();Rd.byteLength=Ok;Rd.toByteArray=Pk;Rd.fromByteArray=Mk;var Pi=[],Tn=[],xk=typeof Uint8Array<"u"?Uint8Array:Array,yw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ea=0,p3=yw.length;Ea0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Ok(t){var e=m3(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Dk(t,e,r){return(e+r)*3/4-r}function Pk(t){var e,r=m3(t),n=r[0],i=r[1],s=new xk(Dk(t,n,i)),o=0,u=i>0?n-4:n,a;for(a=0;a>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tn[t.charCodeAt(a)]<<2|Tn[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=Tn[t.charCodeAt(a)]<<10|Tn[t.charCodeAt(a+1)]<<4|Tn[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Rk(t){return Pi[t>>18&63]+Pi[t>>12&63]+Pi[t>>6&63]+Pi[t&63]}function Bk(t,e,r){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=t[r-1],i.push(Pi[e>>2]+Pi[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Pi[e>>10]+Pi[e>>4&63]+Pi[e<<2&63]+"=")),i.join("")}});var w3=D(ww=>{h();ww.read=function(t,e,r,n,i){var s,o,u=i*8-n-1,a=(1<>1,f=-7,d=r?i-1:0,w=r?-1:1,A=t[e+d];for(d+=w,s=A&(1<<-f)-1,A>>=-f,f+=u;f>0;s=s*256+t[e+d],d+=w,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=w,f-=8);if(s===0)s=1-c;else{if(s===a)return o?NaN:(A?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(A?-1:1)*o*Math.pow(2,s-n)};ww.write=function(t,e,r,n,i,s){var o,u,a,c=s*8-i-1,f=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:s-1,T=n?1:-1,x=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=w/a:e+=w*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=f?(u=0,o=f):o+d>=1?(u=(e*a-1)*Math.pow(2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+A]=u&255,A+=T,u/=256,i-=8);for(o=o<0;t[r+A]=o&255,A+=T,o/=256,c-=8);t[r+A-T]|=x*128}});var io=D(Nu=>{"use strict";h();var vw=y3(),Cu=w3(),v3=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nu.Buffer=X;Nu.SlowBuffer=kk;Nu.INSPECT_MAX_BYTES=50;var Bd=2147483647;Nu.kMaxLength=Bd;X.TYPED_ARRAY_SUPPORT=Lk();!X.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 Lk(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(X.prototype,"parent",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.buffer}});Object.defineProperty(X.prototype,"offset",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.byteOffset}});function Cs(t){if(t>Bd)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,X.prototype),e}function X(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Sw(t)}return b3(t,e,r)}X.poolSize=8192;function b3(t,e,r){if(typeof t=="string")return Uk(t,e);if(ArrayBuffer.isView(t))return qk(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Ri(t,ArrayBuffer)||t&&Ri(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ri(t,SharedArrayBuffer)||t&&Ri(t.buffer,SharedArrayBuffer)))return Ew(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return X.from(n,e,r);var i=Vk(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return X.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}X.from=function(t,e,r){return b3(t,e,r)};Object.setPrototypeOf(X.prototype,Uint8Array.prototype);Object.setPrototypeOf(X,Uint8Array);function S3(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function Fk(t,e,r){return S3(t),t<=0?Cs(t):e!==void 0?typeof r=="string"?Cs(t).fill(e,r):Cs(t).fill(e):Cs(t)}X.alloc=function(t,e,r){return Fk(t,e,r)};function Sw(t){return S3(t),Cs(t<0?0:Iw(t)|0)}X.allocUnsafe=function(t){return Sw(t)};X.allocUnsafeSlow=function(t){return Sw(t)};function Uk(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!X.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=I3(t,e)|0,n=Cs(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function Aw(t){for(var e=t.length<0?0:Iw(t.length)|0,r=Cs(e),n=0;n=Bd)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Bd.toString(16)+" bytes");return t|0}function kk(t){return+t!=t&&(t=0),X.alloc(+t)}X.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==X.prototype};X.compare=function(e,r){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),Ri(r,Uint8Array)&&(r=X.from(r,r.offset,r.byteLength)),!X.isBuffer(e)||!X.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?X.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(X.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function I3(t,e){if(X.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ri(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return bw(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return O3(t).length;default:if(i)return n?-1:bw(t).length;e=(""+e).toLowerCase(),i=!0}}X.byteLength=I3;function Hk(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return Xk(this,e,r);case"utf8":case"utf-8":return _3(this,e,r);case"ascii":return Yk(this,e,r);case"latin1":case"binary":return Jk(this,e,r);case"base64":return Wk(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Zk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}X.prototype._isBuffer=!0;function ba(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}X.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};v3&&(X.prototype[v3]=X.prototype.inspect);X.prototype.compare=function(e,r,n,i,s){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),!X.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=n-r,a=Math.min(o,u),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Tw(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=X.from(e,n)),X.isBuffer(e))return e.length===0?-1:A3(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):A3(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function A3(t,e,r,n,i){var s=1,o=t.length,u=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,u/=2,r/=2}function a(A,T){return s===1?A[T]:A.readUInt16BE(T*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-u),c=r;c>=0;c--){for(var d=!0,w=0;wi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Gk(this,e,r,n);case"utf8":case"utf-8":return jk(this,e,r,n);case"ascii":case"latin1":case"binary":return zk(this,e,r,n);case"base64":return Qk(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Kk(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Wk(t,e,r){return e===0&&r===t.length?vw.fromByteArray(t):vw.fromByteArray(t.slice(e,r))}function _3(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+u<=r){var a,c,f,d;switch(u){case 1:s<128&&(o=s);break;case 2:a=t[i+1],(a&192)===128&&(d=(s&31)<<6|a&63,d>127&&(o=d));break;case 3:a=t[i+1],c=t[i+2],(a&192)===128&&(c&192)===128&&(d=(s&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:a=t[i+1],c=t[i+2],f=t[i+3],(a&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(a&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=u}return $k(n)}var E3=4096;function $k(t){var e=t.length;if(e<=E3)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}X.prototype.readUintLE=X.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};X.prototype.readUint8=X.prototype.readUInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]};X.prototype.readUint16LE=X.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]|this[e+1]<<8};X.prototype.readUint16BE=X.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]<<8|this[e+1]};X.prototype.readUint32LE=X.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};X.prototype.readUint32BE=X.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};X.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};X.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};X.prototype.readInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};X.prototype.readInt16LE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};X.prototype.readInt16BE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};X.prototype.readInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};X.prototype.readInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};X.prototype.readFloatLE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!0,23,4)};X.prototype.readFloatBE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!1,23,4)};X.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!0,52,8)};X.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!1,52,8)};function zr(t,e,r,n,i,s){if(!X.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}X.prototype.writeUintLE=X.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=1,u=0;for(this[r]=e&255;++u>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=n-1,u=1;for(this[r+o]=e&255;--o>=0&&(u*=256);)this[r+o]=e/u&255;return r+n};X.prototype.writeUint8=X.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,255,0),this[r]=e&255,r+1};X.prototype.writeUint16LE=X.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeUint16BE=X.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeUint32LE=X.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};X.prototype.writeUint32BE=X.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};X.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=0,u=1,a=0;for(this[r]=e&255;++o>0)-a&255;return r+n};X.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=n-1,u=1,a=0;for(this[r+o]=e&255;--o>=0&&(u*=256);)e<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(e/u>>0)-a&255;return r+n};X.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};X.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};X.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function C3(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function N3(t,e,r,n,i){return e=+e,r=r>>>0,i||C3(t,e,r,4,34028234663852886e22,-34028234663852886e22),Cu.write(t,e,r,n,23,4),r+4}X.prototype.writeFloatLE=function(e,r,n){return N3(this,e,r,!0,n)};X.prototype.writeFloatBE=function(e,r,n){return N3(this,e,r,!1,n)};function x3(t,e,r,n,i){return e=+e,r=r>>>0,i||C3(t,e,r,8,17976931348623157e292,-17976931348623157e292),Cu.write(t,e,r,n,52,8),r+8}X.prototype.writeDoubleLE=function(e,r,n){return x3(this,e,r,!0,n)};X.prototype.writeDoubleBE=function(e,r,n){return x3(this,e,r,!1,n)};X.prototype.copy=function(e,r,n,i){if(!X.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function rH(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function O3(t){return vw.toByteArray(tH(t))}function Md(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Ri(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Tw(t){return t!==t}var iH=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var M3=D((ape,B3)=>{h();var Wt=B3.exports={},Bi,Mi;function _w(){throw new Error("setTimeout has not been defined")}function Cw(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Bi=setTimeout:Bi=_w}catch{Bi=_w}try{typeof clearTimeout=="function"?Mi=clearTimeout:Mi=Cw}catch{Mi=Cw}})();function D3(t){if(Bi===setTimeout)return setTimeout(t,0);if((Bi===_w||!Bi)&&setTimeout)return Bi=setTimeout,setTimeout(t,0);try{return Bi(t,0)}catch{try{return Bi.call(null,t,0)}catch{return Bi.call(this,t,0)}}}function sH(t){if(Mi===clearTimeout)return clearTimeout(t);if((Mi===Cw||!Mi)&&clearTimeout)return Mi=clearTimeout,clearTimeout(t);try{return Mi(t)}catch{try{return Mi.call(null,t)}catch{return Mi.call(this,t)}}}var Ns=[],xu=!1,Sa,Ld=-1;function oH(){!xu||!Sa||(xu=!1,Sa.length?Ns=Sa.concat(Ns):Ld=-1,Ns.length&&P3())}function P3(){if(!xu){var t=D3(oH);xu=!0;for(var e=Ns.length;e;){for(Sa=Ns,Ns=[];++Ld1)for(var r=1;r{p=pe(io()),S=pe(M3()),aH=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=aH});var fr={};Bt(fr,{BigNumber:()=>U3,default:()=>Ou});function F3(t){var e,r,n,i=U.prototype={constructor:U,toString:null,valueOf:null},s=new U(1),o=20,u=4,a=-7,c=21,f=-1e7,d=1e7,w=!1,A=1,T=0,x={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},B="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function U(v,C){var P,F,R,l,g,y,E,I,_=this;if(!(_ instanceof U))return new U(v,C);if(C==null){if(v&&v._isBigNumber===!0){_.s=v.s,!v.c||v.e>d?_.c=_.e=null:v.e=10;g/=10,l++);l>d?_.c=_.e=null:(_.e=l,_.c=[v]);return}I=String(v)}else{if(!uH.test(I=String(v)))return n(_,I,y);_.s=I.charCodeAt(0)==45?(I=I.slice(1),-1):1}(l=I.indexOf("."))>-1&&(I=I.replace(".","")),(g=I.search(/e/i))>0?(l<0&&(l=g),l+=+I.slice(g+1),I=I.substring(0,g)):l<0&&(l=I.length)}else{if(Ht(C,2,B.length,"Base"),C==10&&V)return _=new U(v),H(_,o+_.e+1,u);if(I=String(v),y=typeof v=="number"){if(v*0!=0)return n(_,I,y,C);if(_.s=1/v<0?(I=I.slice(1),-1):1,U.DEBUG&&I.replace(/^0\.0*|\./,"").length>15)throw Error(L3+v)}else _.s=I.charCodeAt(0)===45?(I=I.slice(1),-1):1;for(P=B.slice(0,C),l=g=0,E=I.length;gl){l=E;continue}}else if(!R&&(I==I.toUpperCase()&&(I=I.toLowerCase())||I==I.toLowerCase()&&(I=I.toUpperCase()))){R=!0,g=-1,l=0;continue}return n(_,String(v),y,C)}y=!1,I=r(I,C,10,_.s),(l=I.indexOf("."))>-1?I=I.replace(".",""):l=I.length}for(g=0;I.charCodeAt(g)===48;g++);for(E=I.length;I.charCodeAt(--E)===48;);if(I=I.slice(g,++E)){if(E-=g,y&&U.DEBUG&&E>15&&(v>xw||v!==Cn(v)))throw Error(L3+_.s*v);if((l=l-g-1)>d)_.c=_.e=null;else if(l=-mr&&R<=mr&&R===Cn(R)){if(F[0]===0){if(R===0&&F.length===1)return!0;break e}if(C=(R+1)%be,C<1&&(C+=be),String(F[0]).length==C){for(C=0;C=di||P!==Cn(P))break e;if(P!==0)return!0}}}else if(F===null&&R===null&&(l===null||l===1||l===-1))return!0;throw Error(Qr+"Invalid BigNumber: "+v)},U.maximum=U.max=function(){return L(arguments,-1)},U.minimum=U.min=function(){return L(arguments,1)},U.random=function(){var v=9007199254740992,C=Math.random()*v&2097151?function(){return Cn(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(P){var F,R,l,g,y,E=0,I=[],_=new U(s);if(P==null?P=o:Ht(P,0,mr),g=Nw(P/be),w)if(crypto.getRandomValues){for(F=crypto.getRandomValues(new Uint32Array(g*=2));E>>11),y>=9e15?(R=crypto.getRandomValues(new Uint32Array(2)),F[E]=R[0],F[E+1]=R[1]):(I.push(y%1e14),E+=2);E=g/2}else if(crypto.randomBytes){for(F=crypto.randomBytes(g*=7);E=9e15?crypto.randomBytes(7).copy(F,E):(I.push(y%1e14),E+=7);E=g/7}else throw w=!1,Error(Qr+"crypto unavailable");if(!w)for(;E=10;y/=10,E++);ER-1&&(y[g+1]==null&&(y[g+1]=0),y[g+1]+=y[g]/R|0,y[g]%=R)}return y.reverse()}return function(P,F,R,l,g){var y,E,I,_,M,N,m,O,Y=P.indexOf("."),$=o,b=u;for(Y>=0&&(_=T,T=0,P=P.replace(".",""),O=new U(F),N=O.pow(P.length-Y),T=_,O.c=C(Os(_n(N.c),N.e,"0"),10,R,v),O.e=O.c.length),m=C(P,F,R,g?(y=B,v):(y=v,B)),I=_=m.length;m[--_]==0;m.pop());if(!m[0])return y.charAt(0);if(Y<0?--I:(N.c=m,N.e=I,N.s=l,N=e(N,O,$,b,R),m=N.c,M=N.r,I=N.e),E=I+$+1,Y=m[E],_=R/2,M=M||E<0||m[E+1]!=null,M=b<4?(Y!=null||M)&&(b==0||b==(N.s<0?3:2)):Y>_||Y==_&&(b==4||M||b==6&&m[E-1]&1||b==(N.s<0?8:7)),E<1||!m[0])P=M?Os(y.charAt(1),-$,y.charAt(0)):y.charAt(0);else{if(m.length=E,M)for(--R;++m[--E]>R;)m[E]=0,E||(++I,m=[1].concat(m));for(_=m.length;!m[--_];);for(Y=0,P="";Y<=_;P+=y.charAt(m[Y++]));P=Os(P,I,y.charAt(0))}return P}}(),e=function(){function v(F,R,l){var g,y,E,I,_=0,M=F.length,N=R%so,m=R/so|0;for(F=F.slice();M--;)E=F[M]%so,I=F[M]/so|0,g=m*E+I*N,y=N*E+g%so*so+_,_=(y/l|0)+(g/so|0)+m*I,F[M]=y%l;return _&&(F=[_].concat(F)),F}function C(F,R,l,g){var y,E;if(l!=g)E=l>g?1:-1;else for(y=E=0;yR[y]?1:-1;break}return E}function P(F,R,l,g){for(var y=0;l--;)F[l]-=y,y=F[l]1;F.splice(0,1));}return function(F,R,l,g,y){var E,I,_,M,N,m,O,Y,$,b,j,z,W,ie,te,ee,se,oe=F.s==R.s?1:-1,J=F.c,ue=R.c;if(!J||!J[0]||!ue||!ue[0])return new U(!F.s||!R.s||(J?ue&&J[0]==ue[0]:!ue)?NaN:J&&J[0]==0||!ue?oe*0:oe/0);for(Y=new U(oe),$=Y.c=[],I=F.e-R.e,oe=l+I+1,y||(y=di,I=Nn(F.e/be)-Nn(R.e/be),oe=oe/be|0),_=0;ue[_]==(J[_]||0);_++);if(ue[_]>(J[_]||0)&&I--,oe<0)$.push(1),M=!0;else{for(ie=J.length,ee=ue.length,_=0,oe+=2,N=Cn(y/(ue[0]+1)),N>1&&(ue=v(ue,N,y),J=v(J,N,y),ee=ue.length,ie=J.length),W=ee,b=J.slice(0,ee),j=b.length;j=y/2&&te++;do{if(N=0,E=C(ue,b,ee,j),E<0){if(z=b[0],ee!=j&&(z=z*y+(b[1]||0)),N=Cn(z/te),N>1)for(N>=y&&(N=y-1),m=v(ue,N,y),O=m.length,j=b.length;C(m,b,O,j)==1;)N--,P(m,ee=10;oe/=10,_++);H(Y,l+(Y.e=_+I*be-1)+1,g,M)}else Y.e=I,Y.r=+M;return Y}}();function Q(v,C,P,F){var R,l,g,y,E;if(P==null?P=u:Ht(P,0,8),!v.c)return v.toString();if(R=v.c[0],g=v.e,C==null)E=_n(v.c),E=F==1||F==2&&(g<=a||g>=c)?Ud(E,g):Os(E,g,"0");else if(v=H(new U(v),C,P),l=v.e,E=_n(v.c),y=E.length,F==1||F==2&&(C<=l||l<=a)){for(;yy){if(--C>0)for(E+=".";C--;E+="0");}else if(C+=l-y,C>0)for(l+1==y&&(E+=".");C--;E+="0");return v.s<0&&R?"-"+E:E}function L(v,C){for(var P,F,R=1,l=new U(v[0]);R=10;R/=10,F++);return(P=F+P*be-1)>d?v.c=v.e=null:P=10;y/=10,R++);if(l=C-R,l<0)l+=be,g=C,E=M[I=0],_=Cn(E/N[R-g-1]%10);else if(I=Nw((l+1)/be),I>=M.length)if(F){for(;M.length<=I;M.push(0));E=_=0,R=1,l%=be,g=l-be+1}else break e;else{for(E=y=M[I],R=1;y>=10;y/=10,R++);l%=be,g=l-be+R,_=g<0?0:Cn(E/N[R-g-1]%10)}if(F=F||C<0||M[I+1]!=null||(g<0?E:E%N[R-g-1]),F=P<4?(_||F)&&(P==0||P==(v.s<0?3:2)):_>5||_==5&&(P==4||F||P==6&&(l>0?g>0?E/N[R-g]:0:M[I-1])%10&1||P==(v.s<0?8:7)),C<1||!M[0])return M.length=0,F?(C-=v.e+1,M[0]=N[(be-C%be)%be],v.e=-C||0):M[0]=v.e=0,v;if(l==0?(M.length=I,y=1,I--):(M.length=I+1,y=N[be-l],M[I]=g>0?Cn(E/N[R-g]%N[g])*y:0),F)for(;;)if(I==0){for(l=1,g=M[0];g>=10;g/=10,l++);for(g=M[0]+=y,y=1;g>=10;g/=10,y++);l!=y&&(v.e++,M[0]==di&&(M[0]=1));break}else{if(M[I]+=y,M[I]!=di)break;M[I--]=0,y=1}for(l=M.length;M[--l]===0;M.pop());}v.e>d?v.c=v.e=null:v.e=c?Ud(C,P):Os(C,P,"0"),v.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var v=new U(this);return v.s<0&&(v.s=1),v},i.comparedTo=function(v,C){return Ia(this,new U(v,C))},i.decimalPlaces=i.dp=function(v,C){var P,F,R,l=this;if(v!=null)return Ht(v,0,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v+l.e+1,C);if(!(P=l.c))return null;if(F=((R=P.length-1)-Nn(this.e/be))*be,R=P[R])for(;R%10==0;R/=10,F--);return F<0&&(F=0),F},i.dividedBy=i.div=function(v,C){return e(this,new U(v,C),o,u)},i.dividedToIntegerBy=i.idiv=function(v,C){return e(this,new U(v,C),0,1)},i.exponentiatedBy=i.pow=function(v,C){var P,F,R,l,g,y,E,I,_,M=this;if(v=new U(v),v.c&&!v.isInteger())throw Error(Qr+"Exponent not an integer: "+q(v));if(C!=null&&(C=new U(C)),y=v.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!v.c||!v.c[0])return _=new U(Math.pow(+q(M),y?v.s*(2-Fd(v)):+q(v))),C?_.mod(C):_;if(E=v.s<0,C){if(C.c?!C.c[0]:!C.s)return new U(NaN);F=!E&&M.isInteger()&&C.isInteger(),F&&(M=M.mod(C))}else{if(v.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||y&&M.c[1]>=24e7:M.c[0]<8e13||y&&M.c[0]<=9999975e7)))return l=M.s<0&&Fd(v)?-0:0,M.e>-1&&(l=1/l),new U(E?1/l:l);T&&(l=Nw(T/be+2))}for(y?(P=new U(.5),E&&(v.s=1),I=Fd(v)):(R=Math.abs(+q(v)),I=R%2),_=new U(s);;){if(I){if(_=_.times(M),!_.c)break;l?_.c.length>l&&(_.c.length=l):F&&(_=_.mod(C))}if(R){if(R=Cn(R/2),R===0)break;I=R%2}else if(v=v.times(P),H(v,v.e+1,1),v.e>14)I=Fd(v);else{if(R=+q(v),R===0)break;I=R%2}M=M.times(M),l?M.c&&M.c.length>l&&(M.c.length=l):F&&(M=M.mod(C))}return F?_:(E&&(_=s.div(_)),C?_.mod(C):l?H(_,T,u,g):_)},i.integerValue=function(v){var C=new U(this);return v==null?v=u:Ht(v,0,8),H(C,C.e+1,v)},i.isEqualTo=i.eq=function(v,C){return Ia(this,new U(v,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(v,C){return Ia(this,new U(v,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(v,C){return(C=Ia(this,new U(v,C)))===1||C===0},i.isInteger=function(){return!!this.c&&Nn(this.e/be)>this.c.length-2},i.isLessThan=i.lt=function(v,C){return Ia(this,new U(v,C))<0},i.isLessThanOrEqualTo=i.lte=function(v,C){return(C=Ia(this,new U(v,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(v,C){var P,F,R,l,g=this,y=g.s;if(v=new U(v,C),C=v.s,!y||!C)return new U(NaN);if(y!=C)return v.s=-C,g.plus(v);var E=g.e/be,I=v.e/be,_=g.c,M=v.c;if(!E||!I){if(!_||!M)return _?(v.s=-C,v):new U(M?g:NaN);if(!_[0]||!M[0])return M[0]?(v.s=-C,v):new U(_[0]?g:u==3?-0:0)}if(E=Nn(E),I=Nn(I),_=_.slice(),y=E-I){for((l=y<0)?(y=-y,R=_):(I=E,R=M),R.reverse(),C=y;C--;R.push(0));R.reverse()}else for(F=(l=(y=_.length)<(C=M.length))?y:C,y=C=0;C0)for(;C--;_[P++]=0);for(C=di-1;F>y;){if(_[--F]=0;){for(P=0,N=z[R]%$,m=z[R]/$|0,g=E,l=R+g;l>R;)I=j[--g]%$,_=j[g]/$|0,y=m*I+_*N,I=N*I+y%$*$+O[l]+P,P=(I/Y|0)+(y/$|0)+m*_,O[l--]=I%Y;O[l]=P}return P?++F:O.splice(0,1),k(v,O,F)},i.negated=function(){var v=new U(this);return v.s=-v.s||null,v},i.plus=function(v,C){var P,F=this,R=F.s;if(v=new U(v,C),C=v.s,!R||!C)return new U(NaN);if(R!=C)return v.s=-C,F.minus(v);var l=F.e/be,g=v.e/be,y=F.c,E=v.c;if(!l||!g){if(!y||!E)return new U(R/0);if(!y[0]||!E[0])return E[0]?v:new U(y[0]?F:R*0)}if(l=Nn(l),g=Nn(g),y=y.slice(),R=l-g){for(R>0?(g=l,P=E):(R=-R,P=y),P.reverse();R--;P.push(0));P.reverse()}for(R=y.length,C=E.length,R-C<0&&(P=E,E=y,y=P,C=R),R=0;C;)R=(y[--C]=y[C]+E[C]+R)/di|0,y[C]=di===y[C]?0:y[C]%di;return R&&(y=[R].concat(y),++g),k(v,y,g)},i.precision=i.sd=function(v,C){var P,F,R,l=this;if(v!=null&&v!==!!v)return Ht(v,1,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v,C);if(!(P=l.c))return null;if(R=P.length-1,F=R*be+1,R=P[R]){for(;R%10==0;R/=10,F--);for(R=P[0];R>=10;R/=10,F++);}return v&&l.e+1>F&&(F=l.e+1),F},i.shiftedBy=function(v){return Ht(v,-xw,xw),this.times("1e"+v)},i.squareRoot=i.sqrt=function(){var v,C,P,F,R,l=this,g=l.c,y=l.s,E=l.e,I=o+4,_=new U("0.5");if(y!==1||!g||!g[0])return new U(!y||y<0&&(!g||g[0])?NaN:g?l:1/0);if(y=Math.sqrt(+q(l)),y==0||y==1/0?(C=_n(g),(C.length+E)%2==0&&(C+="0"),y=Math.sqrt(+C),E=Nn((E+1)/2)-(E<0||E%2),y==1/0?C="5e"+E:(C=y.toExponential(),C=C.slice(0,C.indexOf("e")+1)+E),P=new U(C)):P=new U(y+""),P.c[0]){for(E=P.e,y=E+I,y<3&&(y=0);;)if(R=P,P=_.times(R.plus(e(l,R,I,1))),_n(R.c).slice(0,y)===(C=_n(P.c)).slice(0,y))if(P.e0&&O>0){for(l=O%y||y,_=m.substr(0,l);l0&&(_+=I+m.slice(l)),N&&(_="-"+_)}F=M?_+(P.decimalSeparator||"")+((E=+P.fractionGroupSize)?M.replace(new RegExp("\\d{"+E+"}\\B","g"),"$&"+(P.fractionGroupSeparator||"")):M):_}return(P.prefix||"")+F+(P.suffix||"")},i.toFraction=function(v){var C,P,F,R,l,g,y,E,I,_,M,N,m=this,O=m.c;if(v!=null&&(y=new U(v),!y.isInteger()&&(y.c||y.s!==1)||y.lt(s)))throw Error(Qr+"Argument "+(y.isInteger()?"out of range: ":"not an integer: ")+q(y));if(!O)return new U(m);for(C=new U(s),I=P=new U(s),F=E=new U(s),N=_n(O),l=C.e=N.length-m.e-1,C.c[0]=Ow[(g=l%be)<0?be+g:g],v=!v||y.comparedTo(C)>0?l>0?C:I:y,g=d,d=1/0,y=new U(N),E.c[0]=0;_=e(y,C,0,1),R=P.plus(_.times(F)),R.comparedTo(v)!=1;)P=F,F=R,I=E.plus(_.times(R=I)),E=R,C=y.minus(_.times(R=C)),y=R;return R=e(v.minus(P),F,0,1),E=E.plus(R.times(I)),P=P.plus(R.times(F)),E.s=I.s=m.s,l=l*2,M=e(I,F,l,u).minus(m).abs().comparedTo(e(E,P,l,u).minus(m).abs())<1?[I,F]:[E,P],d=g,M},i.toNumber=function(){return+q(this)},i.toPrecision=function(v,C){return v!=null&&Ht(v,1,mr),Q(this,v,C,2)},i.toString=function(v){var C,P=this,F=P.s,R=P.e;return R===null?F?(C="Infinity",F<0&&(C="-"+C)):C="NaN":(v==null?C=R<=a||R>=c?Ud(_n(P.c),R):Os(_n(P.c),R,"0"):v===10&&V?(P=H(new U(P),o+R+1,u),C=Os(_n(P.c),P.e,"0")):(Ht(v,2,B.length,"Base"),C=r(Os(_n(P.c),R,"0"),10,v,F,!0)),F<0&&P.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return q(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&U.set(t),U}function Nn(t){var e=t|0;return t>0||t===e?e:e-1}function _n(t){for(var e,r,n=1,i=t.length,s=t[0]+"";nc^r?1:-1;for(u=(a=i.length)<(c=s.length)?a:c,o=0;os[o]^r?1:-1;return a==c?0:a>c^r?1:-1}function Ht(t,e,r,n){if(tr||t!==Cn(t))throw Error(Qr+(n||"Argument")+(typeof t=="number"?tr?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Fd(t){var e=t.c.length-1;return Nn(t.e/be)==e&&t.c[e]%2!=0}function Ud(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Os(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e{h();uH=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Nw=Math.ceil,Cn=Math.floor,Qr="[BigNumber Error] ",L3=Qr+"Number primitive has more than 15 significant digits: ",di=1e14,be=14,xw=9007199254740991,Ow=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],so=1e7,mr=1e9;U3=F3(),Ou=U3});var Ie=D(ce=>{"use strict";h();Object.defineProperty(ce,"__esModule",{value:!0});ce.ErrParseTransactionOutcome=ce.ErrInvalidInnerTransaction=ce.ErrBadUsage=ce.ErrInvalidTokenIdentifier=ce.ErrIsCompletedFieldIsMissingOnTransaction=ce.ErrGasLimitShouldBe0ForInnerTransaction=ce.ErrInvalidRelayedV2BuilderArguments=ce.ErrInvalidRelayedV1BuilderArguments=ce.ErrNotImplemented=ce.ErrContractInteraction=ce.ErrCodec=ce.ErrCannotParseTransactionOutcome=ce.ErrCannotParseContractResults=ce.ErrMissingFieldOnEnum=ce.ErrMissingFieldOnStruct=ce.ErrTypingSystem=ce.ErrMock=ce.ErrContractHasNoAddress=ce.ErrContract=ce.ErrExpectedTransactionEventsNotFound=ce.ErrExpectedTransactionStatusNotReached=ce.ErrTransactionWatcherTimeout=ce.ErrAsyncTimerAborted=ce.ErrAsyncTimerAlreadyRunning=ce.ErrInvalidFunctionName=ce.ErrSignatureCannotCreate=ce.ErrTransactionOptionsInvalid=ce.ErrTransactionVersionInvalid=ce.ErrNonceInvalid=ce.ErrNotEnoughGas=ce.ErrAddressEmpty=ce.ErrAddressBadHrp=ce.ErrAddressCannotCreate=ce.ErrUnexpectedCondition=ce.ErrInvariantFailed=ce.ErrBadType=ce.ErrUnsupportedOperation=ce.ErrInvalidArgument=ce.Err=void 0;var Ce=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};ce.Err=Ce;var Dw=class extends Ce{constructor(e,r){super(`Invalid argument: ${e}`,r)}};ce.ErrInvalidArgument=Dw;var Pw=class extends Ce{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};ce.ErrUnsupportedOperation=Pw;var Rw=class extends Ce{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};ce.ErrBadType=Rw;var Bw=class extends Ce{constructor(e){super(`Invariant failed: [${e}]`)}};ce.ErrInvariantFailed=Bw;var Mw=class extends Ce{constructor(e){super(`Unexpected condition: [${e}]`)}};ce.ErrUnexpectedCondition=Mw;var Lw=class extends Ce{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};ce.ErrAddressCannotCreate=Lw;var Fw=class extends Ce{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};ce.ErrAddressBadHrp=Fw;var Uw=class extends Ce{constructor(){super("Address is empty")}};ce.ErrAddressEmpty=Uw;var qw=class extends Ce{constructor(e){super(`Not enough gas provided: ${e}`)}};ce.ErrNotEnoughGas=qw;var Vw=class extends Ce{constructor(e){super(`Invalid nonce: ${e}`)}};ce.ErrNonceInvalid=Vw;var kw=class extends Ce{constructor(e){super(`Invalid transaction version: ${e}`)}};ce.ErrTransactionVersionInvalid=kw;var Hw=class extends Ce{constructor(e){super(`Invalid transaction options: ${e}`)}};ce.ErrTransactionOptionsInvalid=Hw;var Gw=class extends Ce{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};ce.ErrSignatureCannotCreate=Gw;var jw=class extends Ce{constructor(){super("Invalid function name")}};ce.ErrInvalidFunctionName=jw;var zw=class extends Ce{constructor(){super("Async timer already running")}};ce.ErrAsyncTimerAlreadyRunning=zw;var Qw=class extends Ce{constructor(){super("Async timer aborted")}};ce.ErrAsyncTimerAborted=Qw;var Kw=class extends Ce{constructor(){super("TransactionWatcher has timed out")}};ce.ErrTransactionWatcherTimeout=Kw;var Ww=class extends Ce{constructor(){super("Expected transaction status not reached")}};ce.ErrExpectedTransactionStatusNotReached=Ww;var $w=class extends Ce{constructor(){super("Expected transaction events not found")}};ce.ErrExpectedTransactionEventsNotFound=$w;var qd=class extends Ce{constructor(e){super(e)}};ce.ErrContract=qd;var Yw=class extends qd{constructor(){super(` The smart contract has no address set. Make sure you provide the address in the constructor, or call setAddress() appropriately. If you need to recompute the address of the contract, make use of SmartContract.computeAddress() (static method). -`)}};ce.ErrContractHasNoAddress=$w;var Yw=class extends Ce{constructor(e){super(e)}};ce.ErrMock=Yw;var Jw=class extends Ce{constructor(e){super(e)}};ce.ErrTypingSystem=Jw;var Xw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on struct ${r}`)}};ce.ErrMissingFieldOnStruct=Xw;var Zw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on enum ${r}`)}};ce.ErrMissingFieldOnEnum=Zw;var ev=class extends Ce{constructor(e){super(`cannot parse contract results: ${e}`)}};ce.ErrCannotParseContractResults=ev;var tv=class extends Ce{constructor(e,r){super(`cannot parse outcome of transaction ${e}: ${r}`)}};ce.ErrCannotParseTransactionOutcome=tv;var rv=class extends Ce{constructor(e){super(e)}};ce.ErrCodec=rv;var nv=class extends Ce{constructor(e){super(e)}};ce.ErrContractInteraction=nv;var iv=class extends Ce{constructor(){super("Method not yet implemented")}};ce.ErrNotImplemented=iv;var sv=class extends Ce{constructor(){super("invalid arguments for relayed v1 builder")}};ce.ErrInvalidRelayedV1BuilderArguments=sv;var ov=class extends Ce{constructor(){super("invalid arguments for relayed v2 builder")}};ce.ErrInvalidRelayedV2BuilderArguments=ov;var av=class extends Ce{constructor(){super("gas limit must be 0 for the inner transaction for relayed v2")}};ce.ErrGasLimitShouldBe0ForInnerTransaction=av;var uv=class extends Ce{constructor(){super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`.")}};ce.ErrIsCompletedFieldIsMissingOnTransaction=uv;var cv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidTokenIdentifier=cv;var lv=class extends Ce{constructor(e){super(e)}};ce.ErrBadUsage=lv;var fv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidInnerTransaction=fv;var hv=class extends Ce{constructor(e){super(e)}};ce.ErrParseTransactionOutcome=hv});var Ca=B(xn=>{"use strict";h();var Wk=xn&&xn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xn,"__esModule",{value:!0});xn.TokenPayment=xn.TokenComputer=xn.TokenTransfer=xn.Token=void 0;var _a=Wk((rr(),_e(fr))),Du=Ie(),V3="EGLD",k3=18;_a.default.set({ROUNDING_MODE:1});var Hd=class{constructor(e){this.identifier=e.identifier,this.nonce=e.nonce||0n}};xn.Token=Hd;var Gd=class t{constructor(e){if(this.isLegacyTokenTransferOptions(e)){let r=new _a.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new Du.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0,this.token=new Hd({identifier:e.tokenIdentifier,nonce:BigInt(e.nonce)}),this.amount=BigInt(this.amountAsBigInteger.toFixed(0))}else this.token=e.token,this.amount=e.amount,this.tokenIdentifier=e.token.identifier,this.nonce=Number(e.token.nonce),this.amountAsBigInteger=new _a.default(this.amount.toString()),this.numDecimals=0}isLegacyTokenTransferOptions(e){return e.tokenIdentifier!==void 0}static egldFromAmount(e){let r=new _a.default(e).shiftedBy(k3).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:V3,nonce:0,amountAsBigInteger:e,numDecimals:k3})}static fungibleFromAmount(e,r,n){let i=new _a.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new _a.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amount.toString()}valueOf(){return new _a.default(this.amount.toString())}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.token.identifier==V3}isFungible(){return this.token.nonce==0n}};xn.TokenTransfer=Gd;var dv=class{constructor(){}isFungible(e){return e.nonce===0n}extractNonceFromExtendedIdentifier(e){let r=e.split("-");if(this.checkIfExtendedIdentifierWasProvided(r),this.checkLengthOfRandomSequence(r[1]),r.length==2)return 0;let n=p.Buffer.from(r[2],"hex");return $k(n)}extractIdentifierFromExtendedIdentifier(e){let r=e.split("-");return this.checkIfExtendedIdentifierWasProvided(r),this.ensureTokenTickerValidity(r[0]),this.checkLengthOfRandomSequence(r[1]),r[0]+"-"+r[1]}checkIfExtendedIdentifierWasProvided(e){if(e.length<2||e.length>3)throw new Du.ErrInvalidTokenIdentifier("Invalid extended token identifier provided")}checkLengthOfRandomSequence(e){if(e.length!==6)throw new Du.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length")}ensureTokenTickerValidity(e){if(e.length<3||e.length>10)throw new Du.ErrInvalidTokenIdentifier("The token ticker should be between 3 and 10 characters");if(!e.match(/^[a-zA-Z0-9]+$/))throw new Du.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters");if(e!=e.toUpperCase())throw new Du.ErrInvalidTokenIdentifier("The token ticker should be upper case")}};xn.TokenComputer=dv;function $k(t){return t.readUIntBE(0,t.length)}var gv=class extends Gd{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};xn.TokenPayment=gv});var hr=B(Ae=>{"use strict";h();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.UNKNOWN_SIGNER=Ae.SDK_JS_SIGNER=Ae.METACHAIN_ID=Ae.WasmVirtualMachine=Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=Ae.BECH32_ADDRESS_LENGTH=Ae.HEX_TRANSACTION_HASH_LENGTH=Ae.MESSAGE_PREFIX=Ae.DEFAULT_MESSAGE_VERSION=Ae.ESDT_CONTRACT_ADDRESS=Ae.DEFAULT_HRP=Ae.DELEGATION_MANAGER_SC_ADDRESS=Ae.CONTRACT_DEPLOY_ADDRESS=Ae.VM_TYPE_WASM_VM=Ae.ARGUMENTS_SEPARATOR=Ae.ESDT_TRANSFER_VALUE=Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_GAS_LIMIT=Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=Ae.TRANSACTION_VERSION_DEFAULT=Ae.TRANSACTION_OPTIONS_TX_GUARDED=Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=Ae.TRANSACTION_OPTIONS_DEFAULT=Ae.TRANSACTION_MIN_GAS_PRICE=void 0;Ae.TRANSACTION_MIN_GAS_PRICE=1e9;Ae.TRANSACTION_OPTIONS_DEFAULT=0;Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Ae.TRANSACTION_OPTIONS_TX_GUARDED=2;Ae.TRANSACTION_VERSION_DEFAULT=2;Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=2;Ae.ESDT_TRANSFER_GAS_LIMIT=5e5;Ae.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Ae.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Ae.ESDT_TRANSFER_VALUE="0";Ae.ARGUMENTS_SEPARATOR="@";Ae.VM_TYPE_WASM_VM=new Uint8Array([5,0]);Ae.CONTRACT_DEPLOY_ADDRESS="erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu";Ae.DELEGATION_MANAGER_SC_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6";Ae.DEFAULT_HRP="erd";Ae.ESDT_CONTRACT_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u";Ae.DEFAULT_MESSAGE_VERSION=1;Ae.MESSAGE_PREFIX=`Elrond Signed Message: -`;Ae.HEX_TRANSACTION_HASH_LENGTH=64;Ae.BECH32_ADDRESS_LENGTH=62;Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=3;Ae.WasmVirtualMachine="0500";Ae.METACHAIN_ID=4294967295;Ae.SDK_JS_SIGNER="sdk-js";Ae.UNKNOWN_SIGNER="unknown"});var oo=B(xa=>{"use strict";h();Object.defineProperty(xa,"__esModule",{value:!0});xa.Logger=xa.LogLevel=void 0;var Na;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Na=xa.LogLevel||(xa.LogLevel={}));var jd=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Na.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Na.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Na.Error||console.error(e,r)}};xa.Logger=jd;jd.logLevel=Na.Debug});var $l=B(On=>{"use strict";h();var Yk=On&&On.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Jk=On&&On.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xk=On&&On.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yk(e,t,r);return Jk(e,t),e};Object.defineProperty(On,"__esModule",{value:!0});On.TransactionOptions=On.TransactionVersion=void 0;var gi=hr(),H3=Xk(Ie()),pv=class t{constructor(e){if(e=Number(e),e<1)throw new H3.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}valueOf(){return this.value}};On.TransactionVersion=pv;var mv=class t{constructor(e){if(e=Number(e),e<0)throw new H3.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(gi.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=gi.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&gi.TRANSACTION_OPTIONS_TX_HASH_SIGN)==gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&gi.TRANSACTION_OPTIONS_TX_GUARDED)==gi.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=gi.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};On.TransactionOptions=mv});var wv=B((tpe,z3)=>{"use strict";h();var Qd="qpzry9x8gf2tvdw0s3jn54khce6mua7l",yv={};for(Yl=0;Yl>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function G3(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=G3(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Pu(n)^o,i+=Qd.charAt(o)}for(s=0;s<6;++s)n=Pu(n);for(n^=1,s=0;s<6;++s){var u=n>>(5-s)*5&31;i+=Qd.charAt(u)}return i}function j3(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var u=G3(s);if(typeof u=="string")return u;for(var a=[],c=0;c=o.length)&&a.push(d)}return u!==1?"Invalid checksum for "+t:{prefix:s,words:a}}function eH(){var t=j3.apply(null,arguments);if(typeof t=="object")return t}function tH(t){var e=j3.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function Kd(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<{"use strict";h();var oH=Nt&&Nt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),aH=Nt&&Nt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uH=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oH(e,t,r);return aH(e,t),e},cH=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.addressToHex=Nt.bigIntToHex=Nt.byteArrayToHex=Nt.boolToHex=Nt.utf8ToHex=Nt.zeroPadStringIfOddLength=Nt.isPaddedHex=Nt.numberToPaddedHex=void 0;var lH=cH((rr(),_e(fr))),fH=Ve(),hH=uH(Bu());function dH(t){let e;typeof t=="bigint"||typeof t=="number"?e=t:e=new lH.default(t);let r=e.toString(16);return Wd(r)}Nt.numberToPaddedHex=dH;function gH(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Nt.isPaddedHex=gH;function Wd(t){return t=t||"",t.length%2==1?"0"+t:t}Nt.zeroPadStringIfOddLength=Wd;function Q3(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.utf8ToHex=Q3;function pH(t){return Q3(t.toString())}Nt.boolToHex=pH;function mH(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.byteArrayToHex=mH;function yH(t){return t==0?"":hH.getHexMagnitudeOfBigInt(t)}Nt.bigIntToHex=yH;function wH(t){return fH.Address.fromBech32(t.toString()).pubkey().toString("hex")}Nt.addressToHex=wH});var Bu=B(nr=>{"use strict";h();var vH=nr&&nr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nr,"__esModule",{value:!0});nr.prependByteToBuffer=nr.flipBufferBitsInPlace=nr.getHexMagnitudeOfBigInt=nr.bigIntToBuffer=nr.bufferToBigInt=nr.cloneBuffer=nr.isMsbZero=nr.isMsbOne=void 0;var vv=vH((rr(),_e(fr))),AH=Ru();function K3(t,e=0){return t[e]>>7==1}nr.isMsbOne=K3;function EH(t,e=0){return!K3(t,e)}nr.isMsbZero=EH;function bH(t){let e=p.Buffer.alloc(t.length);return t.copy(e),e}nr.cloneBuffer=bH;function SH(t){let e=t.toString("hex");return new vv.default(`0x${e}`,16)}nr.bufferToBigInt=SH;function IH(t){let e=W3(t);return p.Buffer.from(e,"hex")}nr.bigIntToBuffer=IH;function W3(t){return t=new vv.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new vv.default(-1))),AH.numberToPaddedHex(t)):""}nr.getHexMagnitudeOfBigInt=W3;function TH(t){for(let e=0;e{"use strict";h();var CH=Lt&&Lt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NH=Lt&&Lt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$3=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&CH(e,t,r);return NH(e,t),e},xH=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.bufferToHex=Lt.addressToHex=Lt.bigIntToHex=Lt.utf8ToHex=Lt.bigIntToBuffer=Lt.bufferToBigInt=Lt.stringToBuffer=void 0;var OH=xH((rr(),_e(fr))),Y3=$3(Bu()),DH=$3(Ru());function PH(t){return p.Buffer.from(t)}Lt.stringToBuffer=PH;function RH(t){return t.length==0?new OH.default(0):Y3.bufferToBigInt(t)}Lt.bufferToBigInt=RH;function BH(t){return t==0?p.Buffer.from([]):Y3.bigIntToBuffer(t)}Lt.bigIntToBuffer=BH;var Av=Ru();Object.defineProperty(Lt,"utf8ToHex",{enumerable:!0,get:function(){return Av.utf8ToHex}});Object.defineProperty(Lt,"bigIntToHex",{enumerable:!0,get:function(){return Av.bigIntToHex}});Object.defineProperty(Lt,"addressToHex",{enumerable:!0,get:function(){return Av.addressToHex}});function MH(t){let e=t.toString("hex");return DH.zeroPadStringIfOddLength(e)}Lt.bufferToHex=MH});var Ds=B((cpe,Ev)=>{"use strict";h();var Mu=typeof Reflect=="object"?Reflect:null,J3=Mu&&typeof Mu.apply=="function"?Mu.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Yd;Mu&&typeof Mu.ownKeys=="function"?Yd=Mu.ownKeys:Object.getOwnPropertySymbols?Yd=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Yd=function(e){return Object.getOwnPropertyNames(e)};function LH(t){console&&console.warn&&console.warn(t)}var Z3=Number.isNaN||function(e){return e!==e};function _t(){_t.init.call(this)}Ev.exports=_t;Ev.exports.once=VH;_t.EventEmitter=_t;_t.prototype._events=void 0;_t.prototype._eventsCount=0;_t.prototype._maxListeners=void 0;var X3=10;function Jd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_t,"defaultMaxListeners",{enumerable:!0,get:function(){return X3},set:function(t){if(typeof t!="number"||t<0||Z3(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");X3=t}});_t.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_t.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Z3(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function eN(t){return t._maxListeners===void 0?_t.defaultMaxListeners:t._maxListeners}_t.prototype.getMaxListeners=function(){return eN(this)};_t.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var u=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw u.context=o,u}var a=s[e];if(a===void 0)return!1;if(typeof a=="function")J3(a,this,r);else for(var c=a.length,f=sN(a,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=o.length,LH(u)}return t}_t.prototype.addListener=function(e,r){return tN(this,e,r,!1)};_t.prototype.on=_t.prototype.addListener;_t.prototype.prependListener=function(e,r){return tN(this,e,r,!0)};function FH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function rN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=FH.bind(n);return i.listener=r,n.wrapFn=i,i}_t.prototype.once=function(e,r){return Jd(r),this.on(e,rN(this,e,r)),this};_t.prototype.prependOnceListener=function(e,r){return Jd(r),this.prependListener(e,rN(this,e,r)),this};_t.prototype.removeListener=function(e,r){var n,i,s,o,u;if(Jd(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){u=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():UH(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||r)}return this};_t.prototype.off=_t.prototype.removeListener;_t.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function nN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?qH(i):sN(i,i.length)}_t.prototype.listeners=function(e){return nN(this,e,!0)};_t.prototype.rawListeners=function(e){return nN(this,e,!1)};_t.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):iN.call(t,e)};_t.prototype.listenerCount=iN;function iN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_t.prototype.eventNames=function(){return this._eventsCount>0?Yd(this._events):[]};function sN(t,e){for(var r=new Array(e),n=0;n{h();aN.exports=Ds().EventEmitter});var Sv=B(()=>{h()});var dN=B((mpe,hN)=>{"use strict";h();function uN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function cN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Xd.alloc(0);for(var n=Xd.allocUnsafe(r>>>0),i=this.head,s=0;i;)$H(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(u===o.length?s+=o:s+=o.slice(0,r),r-=u,r===0){u===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(u));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Xd.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,u=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,u),r-=u,r===0){u===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(u));break}++s}return this.length-=s,n}},{key:WH,value:function(r,n){return Iv(this,cN(cN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var _v=B((wpe,pN)=>{"use strict";h();function YH(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,I.default.nextTick(Tv,this,t)):I.default.nextTick(Tv,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?I.default.nextTick(Zd,r):(r._writableState.errorEmitted=!0,I.default.nextTick(gN,r,s)):I.default.nextTick(gN,r,s):e?(I.default.nextTick(Zd,r),e(s)):I.default.nextTick(Zd,r)}),this)}function gN(t,e){Tv(t,e),Zd(t)}function Zd(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function JH(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Tv(t,e){t.emit("error",e)}function XH(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}pN.exports={destroy:YH,undestroy:JH,errorOrDestroy:XH}});var Oa=B((Ape,wN)=>{"use strict";h();function ZH(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var yN={};function Dn(t,e,r){r||(r=Error);function n(s,o,u){return typeof e=="string"?e:e(s,o,u)}var i=function(s){ZH(o,s);function o(u,a,c){return s.call(this,n(u,a,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,yN[t]=i}function mN(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function eG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function tG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function rG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}Dn("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);Dn("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&eG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(tG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(mN(e,"type"));else{var s=rG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(mN(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);Dn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");Dn("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});Dn("ERR_STREAM_PREMATURE_CLOSE","Premature close");Dn("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});Dn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");Dn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");Dn("ERR_STREAM_WRITE_AFTER_END","write after end");Dn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Dn("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);Dn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");wN.exports.codes=yN});var Cv=B((bpe,vN)=>{"use strict";h();var nG=Oa().codes.ERR_INVALID_OPT_VALUE;function iG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function sG(t,e,r,n){var i=iG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new nG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}vN.exports={getHighWaterMark:sG}});var Lu=B((Ipe,Nv)=>{h();typeof Object.create=="function"?Nv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Nv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var EN=B((_pe,AN)=>{h();AN.exports=oG;function oG(t,e){if(xv("noDeprecation"))return t;var r=!1;function n(){if(!r){if(xv("throwDeprecation"))throw new Error(e);xv("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function xv(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var Pv=B((Npe,CN)=>{"use strict";h();CN.exports=Gt;function SN(t){var e=this;this.next=null,this.entry=null,this.finish=function(){RG(e,t)}}var Fu;Gt.WritableState=Xl;var aG={deprecate:EN()},IN=bv(),tg=io().Buffer,uG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cG(t){return tg.from(t)}function lG(t){return tg.isBuffer(t)||t instanceof uG}var Dv=_v(),fG=Cv(),hG=fG.getHighWaterMark,ao=Oa().codes,dG=ao.ERR_INVALID_ARG_TYPE,gG=ao.ERR_METHOD_NOT_IMPLEMENTED,pG=ao.ERR_MULTIPLE_CALLBACK,mG=ao.ERR_STREAM_CANNOT_PIPE,yG=ao.ERR_STREAM_DESTROYED,wG=ao.ERR_STREAM_NULL_VALUES,vG=ao.ERR_STREAM_WRITE_AFTER_END,AG=ao.ERR_UNKNOWN_ENCODING,Uu=Dv.errorOrDestroy;Lu()(Gt,IN);function EG(){}function Xl(t,e,r){Fu=Fu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof Fu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=hG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){NG(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new SN(this)}Xl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(Xl.prototype,"buffer",{get:aG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var eg;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(eg=Function.prototype[Symbol.hasInstance],Object.defineProperty(Gt,Symbol.hasInstance,{value:function(e){return eg.call(this,e)?!0:this!==Gt?!1:e&&e._writableState instanceof Xl}})):eg=function(e){return e instanceof this};function Gt(t){Fu=Fu||Da();var e=this instanceof Fu;if(!e&&!eg.call(Gt,this))return new Gt(t);this._writableState=new Xl(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),IN.call(this)}Gt.prototype.pipe=function(){Uu(this,new mG)};function bG(t,e){var r=new vG;Uu(t,r),I.default.nextTick(e,r)}function SG(t,e,r,n){var i;return r===null?i=new wG:typeof r!="string"&&!e.objectMode&&(i=new dG("chunk",["string","Buffer"],r)),i?(Uu(t,i),I.default.nextTick(n,i),!1):!0}Gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&lG(t);return s&&!tg.isBuffer(t)&&(t=cG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=EG),n.ending?bG(this,r):(s||SG(this,n,t,r))&&(n.pendingcb++,i=TG(this,n,s,t,e,r)),i};Gt.prototype.cork=function(){this._writableState.corked++};Gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&TN(this,t))};Gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new AG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function IG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=tg.from(e,r)),e}Object.defineProperty(Gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function TG(t,e,r,n,i,s){if(!r){var o=IG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length{"use strict";h();var BG=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};xN.exports=Li;var NN=Mv(),Bv=Pv();Lu()(Li,NN);for(Rv=BG(Bv.prototype),rg=0;rg{h();var ig=io(),Fi=ig.Buffer;function ON(t,e){for(var r in t)e[r]=t[r]}Fi.from&&Fi.alloc&&Fi.allocUnsafe&&Fi.allocUnsafeSlow?DN.exports=ig:(ON(ig,Lv),Lv.Buffer=Pa);function Pa(t,e,r){return Fi(t,e,r)}Pa.prototype=Object.create(Fi.prototype);ON(Fi,Pa);Pa.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Fi(t,e,r)};Pa.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Fi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Pa.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fi(t)};Pa.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ig.SlowBuffer(t)}});var qv=B(BN=>{"use strict";h();var Uv=PN().Buffer,RN=Uv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function FG(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function UG(t){var e=FG(t);if(typeof e!="string"&&(Uv.isEncoding===RN||!RN(t)))throw new Error("Unknown encoding: "+t);return e||t}BN.StringDecoder=Zl;function Zl(t){this.encoding=UG(t);var e;switch(this.encoding){case"utf16le":this.text=jG,this.end=zG,e=4;break;case"utf8":this.fillLast=kG,e=4;break;case"base64":this.text=QG,this.end=KG,e=3;break;default:this.write=WG,this.end=$G;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Uv.allocUnsafe(e)}Zl.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function qG(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function VG(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function kG(t){var e=this.lastTotal-this.lastNeed,r=VG(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function HG(t,e){var r=qG(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function GG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function jG(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function zG(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function QG(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function KG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function WG(t){return t.toString(this.encoding)}function $G(t){return t&&t.length?this.write(t):""}});var sg=B((Mpe,FN)=>{"use strict";h();var MN=Oa().codes.ERR_STREAM_PREMATURE_CLOSE;function YG(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";h();var og;function uo(t,e,r){return e=ZG(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ZG(t){var e=ej(t,"string");return typeof e=="symbol"?e:String(e)}function ej(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var tj=sg(),co=Symbol("lastResolve"),Ra=Symbol("lastReject"),ef=Symbol("error"),ag=Symbol("ended"),Ba=Symbol("lastPromise"),Vv=Symbol("handlePromise"),Ma=Symbol("stream");function lo(t,e){return{value:t,done:e}}function rj(t){var e=t[co];if(e!==null){var r=t[Ma].read();r!==null&&(t[Ba]=null,t[co]=null,t[Ra]=null,e(lo(r,!1)))}}function nj(t){I.default.nextTick(rj,t)}function ij(t,e){return function(r,n){t.then(function(){if(e[ag]){r(lo(void 0,!0));return}e[Vv](r,n)},n)}}var sj=Object.getPrototypeOf(function(){}),oj=Object.setPrototypeOf((og={get stream(){return this[Ma]},next:function(){var e=this,r=this[ef];if(r!==null)return Promise.reject(r);if(this[ag])return Promise.resolve(lo(void 0,!0));if(this[Ma].destroyed)return new Promise(function(o,u){I.default.nextTick(function(){e[ef]?u(e[ef]):o(lo(void 0,!0))})});var n=this[Ba],i;if(n)i=new Promise(ij(n,this));else{var s=this[Ma].read();if(s!==null)return Promise.resolve(lo(s,!1));i=new Promise(this[Vv])}return this[Ba]=i,i}},uo(og,Symbol.asyncIterator,function(){return this}),uo(og,"return",function(){var e=this;return new Promise(function(r,n){e[Ma].destroy(null,function(i){if(i){n(i);return}r(lo(void 0,!0))})})}),og),sj),aj=function(e){var r,n=Object.create(oj,(r={},uo(r,Ma,{value:e,writable:!0}),uo(r,co,{value:null,writable:!0}),uo(r,Ra,{value:null,writable:!0}),uo(r,ef,{value:null,writable:!0}),uo(r,ag,{value:e._readableState.endEmitted,writable:!0}),uo(r,Vv,{value:function(s,o){var u=n[Ma].read();u?(n[Ba]=null,n[co]=null,n[Ra]=null,s(lo(u,!1))):(n[co]=s,n[Ra]=o)},writable:!0}),r));return n[Ba]=null,tj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Ra];s!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,s(i)),n[ef]=i;return}var o=n[co];o!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,o(lo(void 0,!0))),n[ag]=!0}),e.on("readable",nj.bind(null,n)),n};UN.exports=aj});var kN=B((qpe,VN)=>{h();VN.exports=function(){throw new Error("Readable.from is not available in the browser")}});var Mv=B((Hpe,JN)=>{"use strict";h();JN.exports=Fe;var qu;Fe.ReadableState=zN;var kpe=Ds().EventEmitter,jN=function(e,r){return e.listeners(r).length},rf=bv(),ug=io().Buffer,uj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cj(t){return ug.from(t)}function lj(t){return ug.isBuffer(t)||t instanceof uj}var kv=Sv(),Ne;kv&&kv.debuglog?Ne=kv.debuglog("stream"):Ne=function(){};var fj=dN(),Wv=_v(),hj=Cv(),dj=hj.getHighWaterMark,cg=Oa().codes,gj=cg.ERR_INVALID_ARG_TYPE,pj=cg.ERR_STREAM_PUSH_AFTER_EOF,mj=cg.ERR_METHOD_NOT_IMPLEMENTED,yj=cg.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Vu,Hv,Gv;Lu()(Fe,rf);var tf=Wv.errorOrDestroy,jv=["error","close","destroy","pause","resume"];function wj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function zN(t,e,r){qu=qu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof qu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=dj(this,t,"readableHighWaterMark",r),this.buffer=new fj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Vu||(Vu=qv().StringDecoder),this.decoder=new Vu(t.encoding),this.encoding=t.encoding)}function Fe(t){if(qu=qu||Da(),!(this instanceof Fe))return new Fe(t);var e=this instanceof qu;this._readableState=new zN(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),rf.call(this)}Object.defineProperty(Fe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Fe.prototype.destroy=Wv.destroy;Fe.prototype._undestroy=Wv.undestroy;Fe.prototype._destroy=function(t,e){e(t)};Fe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=ug.from(t,e),e=""),n=!0),QN(this,t,e,!1,n)};Fe.prototype.unshift=function(t){return QN(this,t,null,!0,!1)};function QN(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Ej(t,s);else{var o;if(i||(o=vj(s,e)),o)tf(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==ug.prototype&&(e=cj(e)),n)s.endEmitted?tf(t,new yj):zv(t,s,e,!0);else if(s.ended)tf(t,new pj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?zv(t,s,e,!1):Kv(t,s)):zv(t,s,e,!1)}else n||(s.reading=!1,Kv(t,s))}return!s.ended&&(s.length=HN?t=HN:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function GN(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=Aj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}Fe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Qv(this):lg(this),null;if(t=GN(t,e),t===0&&e.ended)return e.length===0&&Qv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=$N(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Qv(this)),i!==null&&this.emit("data",i),i};function Ej(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?lg(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,KN(t)))}}function lg(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,I.default.nextTick(KN,t))}function KN(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,$v(t)}function Kv(t,e){e.readingMore||(e.readingMore=!0,I.default.nextTick(bj,t,e))}function bj(t,e){for(;!e.reading&&!e.ended&&(e.length1&&YN(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function w(R){Ne("onerror",R),x(),t.removeListener("error",w),jN(t,"error")===0&&tf(t,R)}wj(t,"error",w);function A(){t.removeListener("finish",T),x()}t.once("close",A);function T(){Ne("onfinish"),t.removeListener("close",A),x()}t.once("finish",T);function x(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Sj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&jN(t,"data")&&(r.flowing=!0,$v(t))}}Fe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?lg(this):n.reading||I.default.nextTick(Ij,this)),r};Fe.prototype.addListener=Fe.prototype.on;Fe.prototype.removeListener=function(t,e){var r=rf.prototype.removeListener.call(this,t,e);return t==="readable"&&I.default.nextTick(WN,this),r};Fe.prototype.removeAllListeners=function(t){var e=rf.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&I.default.nextTick(WN,this),e};function WN(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Ij(t){Ne("readable nexttick read 0"),t.read(0)}Fe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Tj(this,t)),t.paused=!1,this};function Tj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,I.default.nextTick(_j,t,e))}function _j(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),$v(t),e.flowing&&!e.reading&&t.read(0)}Fe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function $v(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}Fe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var u=e.push(o);u||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(u){return function(){return t[u].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Qv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,I.default.nextTick(Cj,e,t))}function Cj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(Fe.from=function(t,e){return Gv===void 0&&(Gv=kN()),Gv(Fe,t,e)});function YN(t,e){for(var r=0,n=t.length;r{"use strict";h();ZN.exports=Ps;var fg=Oa().codes,Nj=fg.ERR_METHOD_NOT_IMPLEMENTED,xj=fg.ERR_MULTIPLE_CALLBACK,Oj=fg.ERR_TRANSFORM_ALREADY_TRANSFORMING,Dj=fg.ERR_TRANSFORM_WITH_LENGTH_0,hg=Da();Lu()(Ps,hg);function Pj(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new xj);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";h();tx.exports=nf;var ex=Yv();Lu()(nf,ex);function nf(t){if(!(this instanceof nf))return new nf(t);ex.call(this,t)}nf.prototype._transform=function(t,e,r){r(null,t)}});var ax=B((Wpe,ox)=>{"use strict";h();var Jv;function Bj(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var sx=Oa().codes,Mj=sx.ERR_MISSING_ARGS,Lj=sx.ERR_STREAM_DESTROYED;function nx(t){if(t)throw t}function Fj(t){return t.setHeader&&typeof t.abort=="function"}function Uj(t,e,r,n){n=Bj(n);var i=!1;t.on("close",function(){i=!0}),Jv===void 0&&(Jv=sg()),Jv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Fj(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new Lj("pipe"))}}}function ix(t){t()}function qj(t,e){return t.pipe(e)}function Vj(t){return!t.length||typeof t[t.length-1]!="function"?nx:t.pop()}function kj(){for(var t=arguments.length,e=new Array(t),r=0;r0;return Uj(o,a,c,function(f){i||(i=f),f&&s.forEach(ix),!a&&(s.forEach(ix),n(i))})});return e.reduce(qj)}ox.exports=kj});var Xv=B((Pn,ux)=>{h();Pn=ux.exports=Mv();Pn.Stream=Pn;Pn.Readable=Pn;Pn.Writable=Pv();Pn.Duplex=Da();Pn.Transform=Yv();Pn.PassThrough=rx();Pn.finished=sg();Pn.pipeline=ax()});var fx=B((Jpe,lx)=>{h();var{Transform:Hj}=Xv();lx.exports=t=>class cx extends Hj{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new cx(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var gx=B((Zpe,dx)=>{h();var{Transform:Gj}=Xv();dx.exports=t=>class hx extends Gj{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new hx(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var mx=B((t0e,px)=>{h();var jj=fx(),zj=gx();px.exports=function(t){let e=jj(t),r=zj(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var vx=B(wx=>{h();var yx=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];wx.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],u=t[5]^t[15]^t[25]^t[35]^t[45],a=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],w=f^(i<<1|s>>>31),A=d^(s<<1|i>>>31),T=t[0]^w,x=t[1]^A,R=t[10]^w,V=t[11]^A,U=t[20]^w,Q=t[21]^A,L=t[30]^w,k=t[31]^A,H=t[40]^w,q=t[41]^A;w=r^(o<<1|u>>>31),A=n^(u<<1|o>>>31);let v=t[2]^w,C=t[3]^A,D=t[12]^w,F=t[13]^A,P=t[22]^w,l=t[23]^A,g=t[32]^w,y=t[33]^A,E=t[42]^w,S=t[43]^A;w=i^(a<<1|c>>>31),A=s^(c<<1|a>>>31);let _=t[4]^w,M=t[5]^A,N=t[14]^w,m=t[15]^A,O=t[24]^w,Y=t[25]^A,$=t[34]^w,b=t[35]^A,j=t[44]^w,z=t[45]^A;w=o^(f<<1|d>>>31),A=u^(d<<1|f>>>31);let W=t[6]^w,ie=t[7]^A,te=t[16]^w,ee=t[17]^A,se=t[26]^w,oe=t[27]^A,J=t[36]^w,ue=t[37]^A,wt=t[46]^w,vt=t[47]^A;w=a^(r<<1|n>>>31),A=c^(n<<1|r>>>31);let Ni=t[8]^w,At=t[9]^A,Et=t[18]^w,xi=t[19]^A,bt=t[28]^w,St=t[29]^A,Oi=t[38]^w,It=t[39]^A,Tt=t[48]^w,Di=t[49]^A,Qe=T,Ke=x,ri=V<<4|R>>>28,We=R<<4|V>>>28,$e=U<<3|Q>>>29,ni=Q<<3|U>>>29,Ye=k<<9|L>>>23,Je=L<<9|k>>>23,ii=H<<18|q>>>14,Xe=q<<18|H>>>14,Ze=v<<1|C>>>31,si=C<<1|v>>>31,et=F<<12|D>>>20,tt=D<<12|F>>>20,oi=P<<10|l>>>22,rt=l<<10|P>>>22,nt=y<<13|g>>>19,ai=g<<13|y>>>19,it=E<<2|S>>>30,st=S<<2|E>>>30,ui=M<<30|_>>>2,ot=_<<30|M>>>2,at=N<<6|m>>>26,ci=m<<6|N>>>26,ut=Y<<11|O>>>21,ct=O<<11|Y>>>21,li=$<<15|b>>>17,lt=b<<15|$>>>17,ft=z<<29|j>>>3,fi=j<<29|z>>>3,ht=W<<28|ie>>>4,dt=ie<<28|W>>>4,hi=ee<<23|te>>>9,gt=te<<23|ee>>>9,pt=se<<25|oe>>>7,vn=oe<<25|se>>>7,An=J<<21|ue>>>11,En=ue<<21|J>>>11,bn=vt<<24|wt>>>8,Sn=wt<<24|vt>>>8,In=Ni<<27|At>>>5,da=At<<27|Ni>>>5,ga=Et<<20|xi>>>12,pa=xi<<20|Et>>>12,ma=St<<7|bt>>>25,ya=bt<<7|St>>>25,wa=Oi<<8|It>>>24,va=It<<8|Oi>>>24,Aa=Tt<<14|Di>>>18,Ea=Di<<14|Tt>>>18;t[0]=Qe^~et&ut,t[1]=Ke^~tt&ct,t[10]=ht^~ga&$e,t[11]=dt^~pa&ni,t[20]=Ze^~at&pt,t[21]=si^~ci&vn,t[30]=In^~ri&oi,t[31]=da^~We&rt,t[40]=ui^~hi&ma,t[41]=ot^~gt&ya,t[2]=et^~ut&An,t[3]=tt^~ct&En,t[12]=ga^~$e&nt,t[13]=pa^~ni&ai,t[22]=at^~pt&wa,t[23]=ci^~vn&va,t[32]=ri^~oi&li,t[33]=We^~rt<,t[42]=hi^~ma&Ye,t[43]=gt^~ya&Je,t[4]=ut^~An&Aa,t[5]=ct^~En&Ea,t[14]=$e^~nt&ft,t[15]=ni^~ai&fi,t[24]=pt^~wa&ii,t[25]=vn^~va&Xe,t[34]=oi^~li&bn,t[35]=rt^~lt&Sn,t[44]=ma^~Ye&it,t[45]=ya^~Je&st,t[6]=An^~Aa&Qe,t[7]=En^~Ea&Ke,t[16]=nt^~ft&ht,t[17]=ai^~fi&dt,t[26]=wa^~ii&Ze,t[27]=va^~Xe&si,t[36]=li^~bn&In,t[37]=lt^~Sn&da,t[46]=Ye^~it&ui,t[47]=Je^~st&ot,t[8]=Aa^~Qe&et,t[9]=Ea^~Ke&tt,t[18]=ft^~ht&ga,t[19]=fi^~dt&pa,t[28]=ii^~Ze&at,t[29]=Xe^~si&ci,t[38]=bn^~In&ri,t[39]=Sn^~da&We,t[48]=it^~ui&hi,t[49]=st^~ot>,t[0]^=yx[e*2],t[1]^=yx[e*2+1]}}});var Ex=B((s0e,Ax)=>{h();var dg=vx();function ku(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}ku.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};ku.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(dg.p1600(this.state),this.count=0);return e};ku.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};Ax.exports=ku});var sf=B((a0e,bx)=>{h();bx.exports=mx()(Ex())});var Ve=B(Kr=>{"use strict";h();var Qj=Kr&&Kr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Kj=Kr&&Kr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Sx=Kr&&Kr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qj(e,t,r);return Kj(e,t),e},Wj=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.AddressComputer=Kr.Address=void 0;var Hu=Sx(wv()),$j=Wj((rr(),_e(fr))),Zv=hr(),Gu=Sx(Ie()),Yj=$d(),Jj=sf(),of="erd",gg=32,Xj="0".repeat(16),pg=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(ArrayBuffer.isView(e))return t.fromBuffer(p.Buffer.from(e));if(typeof e=="string")return t.fromString(e);throw new Gu.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=t.empty();return r.valueHex=e,r}static fromBuffer(e){if(e.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==gg}static fromHex(e){if(!t.isValidHex(e))throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t("")}static fromBech32(e){let r;try{r=Hu.decode(e)}catch(s){throw new Gu.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=of)throw new Gu.ErrAddressBadHrp(of,n);let i=p.Buffer.from(Hu.fromWords(r.words));if(i.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=Hu.decodeUnsafe(e),n=r?.prefix,i=r?p.Buffer.from(Hu.fromWords(r.words)):void 0;return!(n!==of||i?.length!==gg)}hex(){return this.toHex()}toHex(){return this.isEmpty()?"":this.valueHex}bech32(){return this.toBech32()}toBech32(){if(this.isEmpty())return"";let e=Hu.toWords(this.pubkey());return Hu.encode(of,e)}pubkey(){return this.getPublicKey()}getPublicKey(){return this.isEmpty()?p.Buffer.from([]):p.Buffer.from(this.valueHex,"hex")}getHrp(){return of}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.toBech32()}toJSON(){return{bech32:this.toBech32(),pubkey:this.toHex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.isSmartContract()}isSmartContract(){return this.toHex().startsWith(Xj)}};Kr.Address=pg;var eA=class{constructor(e){this.numberOfShardsWithoutMeta=e||Zv.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META}computeContractAddress(e,r){let n=p.Buffer.alloc(8,0),i=e.getPublicKey(),s=i.slice(30),o=p.Buffer.alloc(8),u=new $j.default(r.toString()),a=Yj.bigIntToBuffer(u);o.write(a.reverse().toString("hex"),"hex");let c=p.Buffer.concat([i,o]),f=Jj("keccak256").update(c).digest(),d=p.Buffer.from(Zv.WasmVirtualMachine,"hex"),w=p.Buffer.concat([n,d,f.slice(10,30),s]);return new pg(w)}getShardOfAddress(e){return this.getShardOfPubkey(e.getPublicKey(),this.numberOfShardsWithoutMeta)}getShardOfPubkey(e,r){let n=parseInt("11",2),i=parseInt("01",2),s=e[31];if(this.isPubkeyOfMetachain(e))return Zv.METACHAIN_ID;let o=s&n;return o>r-1&&(o=s&i),o}isPubkeyOfMetachain(e){let r=p.Buffer.from([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n=p.Buffer.from(e).slice(0,r.length);return!!(r.equals(n)||p.Buffer.alloc(32).equals(p.Buffer.from(e)))}};Kr.AddressComputer=eA});var Rn=B(Ft=>{"use strict";h();var Zj=Ft&&Ft.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ez=Ft&&Ft.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tz=Ft&&Ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zj(e,t,r);return ez(e,t),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.isEmpty=Ft.guardEmpty=Ft.guardNotEmpty=Ft.guardLength=Ft.guardSameLength=Ft.guardValueIsSetWithMessage=Ft.guardValueIsSet=Ft.guardTrue=void 0;var ju=tz(Ie());function rz(t,e){if(!t)throw new ju.ErrInvariantFailed(`[<${e}>] isn't true`)}Ft.guardTrue=rz;function nz(t,e){Ix(`${t} isn't set (null or undefined)`,e)}Ft.guardValueIsSet=nz;function Ix(t,e){if(e==null||e===void 0)throw new ju.ErrInvariantFailed(t)}Ft.guardValueIsSetWithMessage=Ix;function iz(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new ju.ErrInvariantFailed("arrays do not have the same length")}Ft.guardSameLength=iz;function sz(t,e){let r=t.length||0;if(r!=e)throw new ju.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}Ft.guardLength=sz;function oz(t,e){if(tA(t))throw new ju.ErrInvariantFailed(`${e} is empty`)}Ft.guardNotEmpty=oz;function az(t,e){if(!tA(t))throw new ju.ErrInvariantFailed(`${e} is not empty`)}Ft.guardEmpty=az;function tA(t){return t.isEmpty?t.isEmpty():t.length===0}Ft.isEmpty=tA});var Tx=B(mg=>{"use strict";h();Object.defineProperty(mg,"__esModule",{value:!0});mg.TypeFormula=void 0;var rA=class{constructor(e,r){this.name=e,this.typeParameters=r}toString(){if(this.typeParameters.length>0){let e=this.typeParameters.map(r=>r.toString()).join(", ");return`${this.name}<${e}>`}else return this.name}};mg.TypeFormula=rA});var _x=B(yg=>{"use strict";h();Object.defineProperty(yg,"__esModule",{value:!0});yg.TypeFormulaParser=void 0;var af=Tx(),Ui=class t{parseExpression(e){e=e.trim();let r=this.tokenizeExpression(e).filter(s=>s!==t.COMMA),n=[];for(let s of r)if(this.isPunctuation(s))if(this.isEndOfTypeParameters(s)){let o=this.acquireTypeWithParameters(n);n.push(o)}else if(this.isBeginningOfTypeParameters(s))n.push(s);else throw new Error(`Unexpected token (punctuation): ${s}`);else n.push(s);if(n.length!==1)throw new Error(`Unexpected stack length at end of parsing: ${n.length}`);if(t.PUNCTUATION.includes(n[0]))throw new Error("Unexpected root element.");let i=n[0];if(i instanceof af.TypeFormula)return i;if(typeof i=="string")return new af.TypeFormula(i,[]);throw new Error(`Unexpected item on stack: ${i}`)}tokenizeExpression(e){let r=[],n="";for(let i of e)this.isPunctuation(i)?(n&&(r.push(n.trim()),n=""),r.push(i)):n+=i;return n&&r.push(n.trim()),r}acquireTypeWithParameters(e){let r=this.acquireTypeParameters(e),n=e.pop();return new af.TypeFormula(n,r.reverse())}acquireTypeParameters(e){let r=[];for(;;){let n=e.pop();if(n===void 0)throw new Error("Badly specified type parameters");if(this.isBeginningOfTypeParameters(n))break;if(n instanceof af.TypeFormula)r.push(n);else if(typeof n=="string")r.push(new af.TypeFormula(n,[]));else throw new Error(`Unexpected type parameter object in stack: ${n}`)}return r}isPunctuation(e){return t.PUNCTUATION.includes(e)}isEndOfTypeParameters(e){return e===t.END_TYPE_PARAMETERS}isBeginningOfTypeParameters(e){return e===t.BEGIN_TYPE_PARAMETERS}};yg.TypeFormulaParser=Ui;Ui.BEGIN_TYPE_PARAMETERS="<";Ui.END_TYPE_PARAMETERS=">";Ui.COMMA=",";Ui.PUNCTUATION=[Ui.COMMA,Ui.BEGIN_TYPE_PARAMETERS,Ui.END_TYPE_PARAMETERS]});var Cx=B(wg=>{"use strict";h();Object.defineProperty(wg,"__esModule",{value:!0});wg.getJavascriptPrototypesInHierarchy=void 0;function uz(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}wg.getJavascriptPrototypesInHierarchy=uz});var sr=B(ir=>{"use strict";h();Object.defineProperty(ir,"__esModule",{value:!0});ir.NullType=ir.TypePlaceholder=ir.isTyped=ir.PrimitiveValue=ir.TypedValue=ir.CustomType=ir.PrimitiveType=ir.TypeCardinality=ir.Type=void 0;var nA=Cx(),Nx=Rn(),fo=class t{constructor(e,r=[],n=uf.fixed(1)){Nx.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return Nx.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return nA.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};ir.Type=fo;fo.ClassName="Type";var uf=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};ir.TypeCardinality=uf;uf.MaxCardinality=4096;var vg=class t extends fo{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveType=vg;vg.ClassName="PrimitiveType";var Ag=class t extends fo{getClassName(){return t.ClassName}};ir.CustomType=Ag;Ag.ClassName="CustomType";var cf=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};ir.TypedValue=cf;cf.ClassName="TypedValue";var Eg=class t extends cf{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveValue=Eg;Eg.ClassName="PrimitiveValue";function cz(t){return t.belongsToTypesystem!==void 0}ir.isTyped=cz;var bg=class t extends fo{constructor(){super("...")}getClassName(){return t.ClassName}};ir.TypePlaceholder=bg;bg.ClassName="TypePlaceholder";var Sg=class t extends fo{constructor(){super("?")}getClassName(){return t.ClassName}};ir.NullType=Sg;Sg.ClassName="NullType"});var lf=B(Ig=>{"use strict";h();Object.defineProperty(Ig,"__esModule",{value:!0});Ig.TypeExpressionParser=void 0;var lz=_x(),fz=Ie(),hz=sr(),iA=class{constructor(){this.backingTypeFormulaParser=new lz.TypeFormulaParser}parse(e){try{return this.doParse(e)}catch(r){throw new fz.ErrTypingSystem(`Failed to parse type expression: ${e}. Error: ${r}`)}}doParse(e){let r=this.backingTypeFormulaParser.parseExpression(e);return this.typeFormulaToType(r)}typeFormulaToType(e){let r=e.typeParameters.map(n=>this.typeFormulaToType(n));return new hz.Type(e.name,r)}};Ig.TypeExpressionParser=iA});var oA=B(ho=>{"use strict";h();Object.defineProperty(ho,"__esModule",{value:!0});ho.EndpointParameterDefinition=ho.EndpointModifiers=ho.EndpointDefinition=void 0;var dz=lf(),xx="?",gz="N / A",sA=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?xx:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>ff.fromJSON(s)),n=e.outputs.map(s=>ff.fromJSON(s)),i=new Tg(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};ho.EndpointDefinition=sA;var Tg=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};ho.EndpointModifiers=Tg;var ff=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new dz.TypeExpressionParser().parse(e.type);return new t(e.name||xx,e.description||gz,r)}};ho.EndpointParameterDefinition=ff});var zu=B(Wr=>{"use strict";h();var pz=Wr&&Wr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),mz=Wr&&Wr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yz=Wr&&Wr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&pz(e,t,r);return mz(e,t),e};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Fields=Wr.Field=Wr.FieldDefinition=void 0;var aA=yz(Ie()),wz=lf(),uA=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new wz.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};Wr.FieldDefinition=uA;var cA=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new aA.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new aA.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};Wr.Field=cA;var lA=class{static checkTyping(e,r){if(e.length!=r.length)throw new aA.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";h();Object.defineProperty(go,"__esModule",{value:!0});go.EnumValue=go.EnumVariantDefinition=go.EnumType=void 0;var vz=Ie(),fA=Rn(),_g=zu(),Dx=sr(),Ox=256,Cg=class t extends Dx.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>Ng.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>({...n,discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return fA.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return fA.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};go.EnumType=Cg;Cg.ClassName="EnumType";var Ng=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],fA.guardTrue(r_g.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return _g.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};go.EnumVariantDefinition=Ng;var xg=class t extends Dx.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();_g.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=_g.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new vz.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};go.EnumValue=xg;xg.ClassName="EnumValue"});var Rx=B(Qu=>{"use strict";h();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.EventTopicDefinition=Qu.EventDefinition=void 0;var Az=lf(),Px="?",hA=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?Px:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>Og.fromJSON(n));return new t(e.identifier,r)}};Qu.EventDefinition=hA;var Og=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Az.TypeExpressionParser().parse(e.type);return new t({name:e.name||Px,type:r,indexed:e.indexed})}};Qu.EventTopicDefinition=Og});var Wu=B(Ku=>{"use strict";h();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.Struct=Ku.StructType=void 0;var Ez=Ie(),Dg=zu(),Bx=sr(),Pg=class t extends Bx.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>Dg.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Dg.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Ku.StructType=Pg;Pg.ClassName="StructType";var Rg=class t extends Bx.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();Dg.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Ez.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return Dg.Fields.equals(r,n)}};Ku.Struct=Rg;Rg.ClassName="Struct"});var Yu=B($u=>{"use strict";h();Object.defineProperty($u,"__esModule",{value:!0});$u.AddressValue=$u.AddressType=void 0;var bz=Ve(),Mx=sr(),df=class t extends Mx.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};$u.AddressType=df;df.ClassName="AddressType";var Bg=class t extends Mx.PrimitiveValue{constructor(e){super(new df),this.value=new bz.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};$u.AddressValue=Bg;Bg.ClassName="AddressValue"});var Lg=B(Ju=>{"use strict";h();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.OptionalValue=Ju.OptionalType=void 0;var Sz=Rn(),gf=sr(),pf=class t extends gf.Type{constructor(e){super("Optional",[e],gf.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(gf.NullType.ClassName);return r||n}};Ju.OptionalType=pf;pf.ClassName="OptionalType";var Mg=class t extends gf.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new pf(new gf.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return Sz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};Ju.OptionalValue=Mg;Mg.ClassName="OptionalValue"});var yf=B(Xu=>{"use strict";h();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.BooleanValue=Xu.BooleanType=void 0;var Lx=sr(),mf=class t extends Lx.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};Xu.BooleanType=mf;mf.ClassName="BooleanType";var Fg=class t extends Lx.PrimitiveValue{constructor(e){super(new mf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};Xu.BooleanValue=Fg;Fg.ClassName="BooleanValue"});var po=B(Zu=>{"use strict";h();Object.defineProperty(Zu,"__esModule",{value:!0});Zu.BytesValue=Zu.BytesType=void 0;var Fx=sr(),wf=class t extends Fx.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Zu.BytesType=wf;wf.ClassName="BytesType";var Ug=class t extends Fx.PrimitiveValue{constructor(e){super(new wf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=p.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=p.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Zu.BytesValue=Ug;Ug.ClassName="BytesValue"});var qx=B(ec=>{"use strict";h();Object.defineProperty(ec,"__esModule",{value:!0});ec.CodeMetadataValue=ec.CodeMetadataType=void 0;var Ux=sr(),qg=class extends Ux.PrimitiveType{constructor(){super("CodeMetadata")}};ec.CodeMetadataType=qg;var dA=class extends Ux.PrimitiveValue{constructor(e){super(new qg),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};ec.CodeMetadataValue=dA});var kg=B(tc=>{"use strict";h();Object.defineProperty(tc,"__esModule",{value:!0});tc.CompositeValue=tc.CompositeType=void 0;var Iz=Rn(),gA=sr(),vf=class t extends gA.Type{constructor(...e){super("Composite",e,gA.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};tc.CompositeType=vf;vf.ClassName="CompositeType";var Vg=class t extends gA.TypedValue{constructor(e,r){super(e),Iz.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new vf(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();Object.defineProperty(Hg,"__esModule",{value:!0});Hg.CollectionOfTypedValues=void 0;var pA=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";h();Object.defineProperty(qi,"__esModule",{value:!0});qi.List=qi.OptionValue=qi.ListType=qi.OptionType=void 0;var Tz=Rn(),_z=mA(),Fa=sr(),La=class t extends Fa.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Fa.NullType.ClassName);return r||n}};qi.OptionType=La;La.ClassName="OptionType";var Af=class t extends Fa.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};qi.ListType=Af;Af.ClassName="ListType";var Gg=class t extends Fa.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new La(new Fa.NullType);return new t(e)}static newMissingTyped(e){return new t(new La(e))}static newProvided(e){let r=new La(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return Tz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};qi.OptionValue=Gg;Gg.ClassName="OptionValue";var jg=class t extends Fa.TypedValue{constructor(e,r){super(e),this.backingCollection=new _z.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new Fa.TypePlaceholder,[]);let r=e[0].getType(),n=new Af(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};qi.List=jg;jg.ClassName="List"});var Kg=B(rc=>{"use strict";h();Object.defineProperty(rc,"__esModule",{value:!0});rc.ArrayVec=rc.ArrayVecType=void 0;var Vx=Rn(),Cz=mA(),kx=sr(),zg=class t extends kx.Type{constructor(e,r){super("Array",[r]),Vx.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};rc.ArrayVecType=zg;zg.ClassName="ArrayVecType";var Qg=class t extends kx.TypedValue{constructor(e,r){super(e),Vx.guardLength(r,e.length),this.backingCollection=new Cz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};rc.ArrayVec=Qg;Qg.ClassName="ArrayVec"});var Sf=B(nc=>{"use strict";h();Object.defineProperty(nc,"__esModule",{value:!0});nc.H256Value=nc.H256Type=void 0;var Hx=sr(),bf=class t extends Hx.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};nc.H256Type=bf;bf.ClassName="H256Type";var Wg=class t extends Hx.PrimitiveValue{constructor(e){super(new bf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};nc.H256Value=Wg;Wg.ClassName="H256Value"});var Yg=B(ic=>{"use strict";h();Object.defineProperty(ic,"__esModule",{value:!0});ic.NothingValue=ic.NothingType=void 0;var Gx=sr(),If=class t extends Gx.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};ic.NothingType=If;If.ClassName="NothingType";var $g=class t extends Gx.PrimitiveValue{constructor(){super(new If)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};ic.NothingValue=$g;$g.ClassName="NothingValue"});var Mf=B(Ee=>{"use strict";h();var Nz=Ee&&Ee.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xz=Ee&&Ee.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oz=Ee&&Ee.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nz(e,t,r);return xz(e,t),e},Dz=Ee&&Ee.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.BigIntValue=Ee.BigUIntValue=Ee.I64Value=Ee.U64Value=Ee.I32Value=Ee.U32Value=Ee.I16Value=Ee.U16Value=Ee.I8Value=Ee.U8Value=Ee.NumericalValue=Ee.BigIntType=Ee.BigUIntType=Ee.I64Type=Ee.U64Type=Ee.I32Type=Ee.U32Type=Ee.I16Type=Ee.U16Type=Ee.I8Type=Ee.U8Type=Ee.NumericalType=void 0;var Pz=Dz((rr(),_e(fr))),jx=Oz(Ie()),zx=sr(),$r=class t extends zx.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ee.NumericalType=$r;$r.ClassName="NumericalType";var Tf=class t extends $r{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ee.U8Type=Tf;Tf.ClassName="U8Type";var _f=class t extends $r{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ee.I8Type=_f;_f.ClassName="I8Type";var Cf=class t extends $r{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ee.U16Type=Cf;Cf.ClassName="U16Type";var Nf=class t extends $r{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ee.I16Type=Nf;Nf.ClassName="I16Type";var xf=class t extends $r{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ee.U32Type=xf;xf.ClassName="U32Type";var Of=class t extends $r{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ee.I32Type=Of;Of.ClassName="I32Type";var Df=class t extends $r{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ee.U64Type=Df;Df.ClassName="U64Type";var Pf=class t extends $r{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ee.I64Type=Pf;Pf.ClassName="I64Type";var Rf=class t extends $r{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ee.BigUIntType=Rf;Rf.ClassName="BigUIntType";var Bf=class t extends $r{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ee.BigIntType=Bf;Bf.ClassName="BigIntType";var Yr=class t extends zx.PrimitiveValue{constructor(e,r){if(super(e),typeof r=="bigint"&&(r=r.toString()),this.value=new Pz.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new jx.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new jx.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ee.NumericalValue=Yr;Yr.ClassName="NumericalValue";var Jg=class t extends Yr{constructor(e){super(new Tf,e)}getClassName(){return t.ClassName}};Ee.U8Value=Jg;Jg.ClassName="U8Value";var Xg=class t extends Yr{constructor(e){super(new _f,e)}getClassName(){return t.ClassName}};Ee.I8Value=Xg;Xg.ClassName="I8Value";var Zg=class t extends Yr{constructor(e){super(new Cf,e)}getClassName(){return t.ClassName}};Ee.U16Value=Zg;Zg.ClassName="U16Value";var ep=class t extends Yr{constructor(e){super(new Nf,e)}getClassName(){return t.ClassName}};Ee.I16Value=ep;ep.ClassName="I16Value";var tp=class t extends Yr{constructor(e){super(new xf,e)}getClassName(){return t.ClassName}};Ee.U32Value=tp;tp.ClassName="U32Value";var rp=class t extends Yr{constructor(e){super(new Of,e)}getClassName(){return t.ClassName}};Ee.I32Value=rp;rp.ClassName="I32Value";var np=class t extends Yr{constructor(e){super(new Df,e)}getClassName(){return t.ClassName}};Ee.U64Value=np;np.ClassName="U64Value";var ip=class t extends Yr{constructor(e){super(new Pf,e)}getClassName(){return t.ClassName}};Ee.I64Value=ip;ip.ClassName="I64Value";var sp=class t extends Yr{constructor(e){super(new Rf,e)}getClassName(){return t.ClassName}};Ee.BigUIntValue=sp;sp.ClassName="BigUIntValue";var op=class t extends Yr{constructor(e){super(new Bf,e)}getClassName(){return t.ClassName}};Ee.BigIntValue=op;op.ClassName="BigIntValue"});var up=B(sc=>{"use strict";h();Object.defineProperty(sc,"__esModule",{value:!0});sc.StringValue=sc.StringType=void 0;var Qx=sr(),Lf=class t extends Qx.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};sc.StringType=Lf;Lf.ClassName="StringType";var ap=class t extends Qx.PrimitiveValue{constructor(e){super(new Lf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=p.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};sc.StringValue=ap;ap.ClassName="StringValue"});var ac=B(oc=>{"use strict";h();Object.defineProperty(oc,"__esModule",{value:!0});oc.TokenIdentifierValue=oc.TokenIdentifierType=void 0;var Kx=sr(),Rz="EGLD",Ff=class t extends Kx.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};oc.TokenIdentifierType=Ff;Ff.ClassName="TokenIdentifierType";var cp=class t extends Kx.PrimitiveValue{constructor(e){super(new Ff),this.value=e}static egld(){return new t(Rz)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};oc.TokenIdentifierValue=cp;cp.ClassName="TokenIdentifierValue"});var fp=B(Bn=>{"use strict";h();var Bz=Bn&&Bn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Mz=Bn&&Bn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Lz=Bn&&Bn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bz(e,t,r);return Mz(e,t),e};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Tuple=Bn.TupleType=void 0;var Fz=Lz(Ie()),Wx=zu(),$x=Wu(),Uf=class t extends $x.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new Wx.FieldDefinition(Yx(i),"anonymous tuple field",n))}};Bn.TupleType=Uf;Uf.ClassName="TupleType";function Yx(t){return`field${t}`}var lp=class t extends $x.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Fz.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new Uf(...r),i=e.map((s,o)=>new Wx.Field(s,Yx(o)));return new t(n,i)}};Bn.Tuple=lp;lp.ClassName="Tuple"});var gp=B(mo=>{"use strict";h();Object.defineProperty(mo,"__esModule",{value:!0});mo.VariadicValue=mo.CountedVariadicType=mo.VariadicType=void 0;var uc=sr(),Ua=class t extends uc.Type{constructor(e,r=!1){super("Variadic",[e],uc.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};mo.VariadicType=Ua;Ua.ClassName="VariadicType";var hp=class extends uc.Type{constructor(e){super("Variadic",[e],uc.TypeCardinality.variable())}getClassName(){return Ua.ClassName}};mo.CountedVariadicType=hp;hp.ClassName="VariadicType";var dp=class t extends uc.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Ua(new uc.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Ua(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();var Uz=ki&&ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qz=ki&&ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vz=ki&&ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Uz(e,t,r);return qz(e,t),e};Object.defineProperty(ki,"__esModule",{value:!0});ki.TypeMapper=void 0;var Jx=Vz(Ie()),kz=Yu(),yA=Lg(),Hz=yf(),Gz=po(),jz=qx(),pp=kg(),wA=hf(),zz=zu(),Xx=Ef(),Vi=Kg(),Qz=Sf(),Zx=Yg(),Mn=Mf(),Kz=up(),e6=Wu(),t6=ac(),yo=fp(),mp=gp(),vA=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new Xx.OptionType(r[0])],["List",(...r)=>new Xx.ListType(r[0])],["VarArgs",(...r)=>new mp.VariadicType(r[0])],["MultiResultVec",(...r)=>new mp.VariadicType(r[0])],["variadic",(...r)=>new mp.VariadicType(r[0])],["counted-variadic",(...r)=>new mp.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new yA.OptionalType(r[0])],["optional",(...r)=>new yA.OptionalType(r[0])],["OptionalResult",(...r)=>new yA.OptionalType(r[0])],["multi",(...r)=>new pp.CompositeType(...r)],["MultiArg",(...r)=>new pp.CompositeType(...r)],["MultiResult",(...r)=>new pp.CompositeType(...r)],["multi",(...r)=>new pp.CompositeType(...r)],["tuple",(...r)=>new yo.TupleType(...r)],["tuple2",(...r)=>new yo.TupleType(...r)],["tuple3",(...r)=>new yo.TupleType(...r)],["tuple4",(...r)=>new yo.TupleType(...r)],["tuple5",(...r)=>new yo.TupleType(...r)],["tuple6",(...r)=>new yo.TupleType(...r)],["tuple7",(...r)=>new yo.TupleType(...r)],["tuple8",(...r)=>new yo.TupleType(...r)],["array2",(...r)=>new Vi.ArrayVecType(2,r[0])],["array8",(...r)=>new Vi.ArrayVecType(8,r[0])],["array16",(...r)=>new Vi.ArrayVecType(16,r[0])],["array20",(...r)=>new Vi.ArrayVecType(20,r[0])],["array32",(...r)=>new Vi.ArrayVecType(32,r[0])],["array46",(...r)=>new Vi.ArrayVecType(46,r[0])],["array48",(...r)=>new Vi.ArrayVecType(48,r[0])],["array64",(...r)=>new Vi.ArrayVecType(64,r[0])],["array128",(...r)=>new Vi.ArrayVecType(128,r[0])],["array256",(...r)=>new Vi.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new Mn.U8Type],["u16",new Mn.U16Type],["u32",new Mn.U32Type],["u64",new Mn.U64Type],["U64",new Mn.U64Type],["BigUint",new Mn.BigUIntType],["i8",new Mn.I8Type],["i16",new Mn.I16Type],["i32",new Mn.I32Type],["i64",new Mn.I64Type],["Bigint",new Mn.BigIntType],["BigInt",new Mn.BigIntType],["bool",new Hz.BooleanType],["bytes",new Gz.BytesType],["Address",new kz.AddressType],["H256",new Qz.H256Type],["utf-8 string",new Kz.StringType],["TokenIdentifier",new t6.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new t6.TokenIdentifierType],["CodeMetadata",new jz.CodeMetadataType],["nothing",new Zx.NothingType],["AsyncCall",new Zx.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new Jx.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(wA.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(e6.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new e6.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new wA.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new wA.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new zz.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new Jx.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};ki.TypeMapper=vA});var o6=B(Hi=>{"use strict";h();var Wz=Hi&&Hi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),$z=Hi&&Hi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yz=Hi&&Hi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wz(e,t,r);return $z(e,t),e};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.AbiRegistry=void 0;var r6=Yz(Ie()),qf=Rn(),Vf=oA(),n6=hf(),EA=Rx(),i6=Wu(),Jz=AA(),Xz="?",bA=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||Xz,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],u=Vf.EndpointDefinition.fromJSON({name:"constructor",...n}),a=i.map(A=>Vf.EndpointDefinition.fromJSON(A)),c=[];for(let A in s){let T=s[A];if(T.type=="struct")c.push(i6.StructType.fromJSON({name:A,fields:T.fields}));else if(T.type=="enum"||T.type=="explicit-enum")c.push(n6.EnumType.fromJSON({name:A,variants:T.variants}));else throw new r6.ErrTypingSystem(`Cannot handle custom type: ${A}`)}let f=o.map(A=>EA.EventDefinition.fromJSON(A));return new t({name:r,constructorDefinition:u,endpoints:a,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return qf.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(i6.StructType.ClassName));return qf.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(n6.EnumType.ClassName));return qf.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return qf.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return qf.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new Jz.TypeMapper([]),r=[];for(let u of this.customTypes)this.mapCustomTypeDepthFirst(u,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new r6.ErrTypingSystem("Did not re-map all custom types");let n=s6(this.constructorDefinition,e),i=[];for(let u of this.endpoints)i.push(s6(u,e));let s=this.events.map(u=>Zz(u,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(u=>u.getName()==e.getName())>=0)return;for(let u of e.getNamesOfDependencies()){let a=r.find(c=>c.getName()==u);a&&this.mapCustomTypeDepthFirst(a,r,n,i)}let o=n.mapType(e);i.push(o)}};Hi.AbiRegistry=bA;function s6(t,e){let r=t.input.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new Vf.EndpointDefinition(t.name,r,n,t.modifiers)}function Zz(t,e){let r=t.inputs.map(n=>new EA.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new EA.EventDefinition(t.identifier,r)}});var u6=B(cc=>{"use strict";h();Object.defineProperty(cc,"__esModule",{value:!0});cc.createListOfTokenIdentifiers=cc.createListOfAddresses=void 0;var eQ=Yu(),a6=Ef(),tQ=ac();function rQ(t){let e=t.map(n=>new eQ.AddressValue(n));return a6.List.fromItems(e)}cc.createListOfAddresses=rQ;function nQ(t){let e=t.map(n=>new tQ.TokenIdentifierValue(n));return a6.List.fromItems(e)}cc.createListOfTokenIdentifiers=nQ});var b6=B(Dr=>{"use strict";h();var iQ=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sQ=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oQ=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iQ(e,t,r);return sQ(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.onPrimitiveTypeSelect=Dr.onPrimitiveValueSelect=Dr.onTypedValueSelect=Dr.onTypeSelect=void 0;var wp=oQ(Ie()),c6=Yu(),l6=yf(),f6=po(),h6=hf(),yp=Ef(),d6=Sf(),g6=Mf(),p6=Yg(),m6=Wu(),y6=ac(),w6=fp(),v6=sr(),A6=Kg(),E6=up();function aQ(t,e){if(t.hasExactClass(yp.OptionType.ClassName))return e.onOption();if(t.hasExactClass(yp.ListType.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(v6.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(m6.StructType.ClassName))return e.onStruct();if(t.hasExactClass(w6.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't known: ${t}`)}Dr.onTypeSelect=aQ;function uQ(t,e){if(t.hasClassOrSuperclass(v6.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(yp.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(yp.List.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(m6.Struct.ClassName))return e.onStruct();if(t.hasExactClass(w6.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't typed: ${t}`)}Dr.onTypedValueSelect=uQ;function cQ(t,e){if(t.hasExactClass(l6.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringValue.ClassName))return e.onString();if(t.hasExactClass(d6.H256Value.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(p6.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Dr.onPrimitiveValueSelect=cQ;function lQ(t,e){if(t.hasExactClass(l6.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringType.ClassName))return e.onString();if(t.hasExactClass(d6.H256Type.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(p6.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Dr.onPrimitiveTypeSelect=lQ});var dr=B(He=>{"use strict";h();var fQ=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ut=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fQ(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});Ut(o6(),He);Ut(Yu(),He);Ut(Lg(),He);Ut(yf(),He);Ut(po(),He);Ut(kg(),He);Ut(oA(),He);Ut(hf(),He);Ut(u6(),He);Ut(zu(),He);Ut(Ef(),He);Ut(Kg(),He);Ut(Sf(),He);Ut(b6(),He);Ut(Yg(),He);Ut(Mf(),He);Ut(up(),He);Ut(Wu(),He);Ut(ac(),He);Ut(fp(),He);Ut(lf(),He);Ut(AA(),He);Ut(sr(),He);Ut(gp(),He)});var I6=B(Gi=>{"use strict";h();var hQ=Gi&&Gi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),dQ=Gi&&Gi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gQ=Gi&&Gi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hQ(e,t,r);return dQ(e,t),e};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.OptionValueBinaryCodec=void 0;var S6=gQ(Ie()),vp=dr(),SA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[vp.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[vp.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new vp.OptionValue(r);if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new vp.OptionValue(r,n)}encodeNested(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([])}};Gi.OptionValueBinaryCodec=SA});var T6=B(Ap=>{"use strict";h();Object.defineProperty(Ap,"__esModule",{value:!0});Ap.AddressBinaryCodec=void 0;var pQ=Ve(),mQ=dr(),IA=class{decodeNested(e){let r=e.slice(0,32),n=new pQ.Address(r);return[new mQ.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};Ap.AddressBinaryCodec=IA});var C6=B(ji=>{"use strict";h();var yQ=ji&&ji.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wQ=ji&&ji.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vQ=ji&&ji.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yQ(e,t,r);return wQ(e,t),e};Object.defineProperty(ji,"__esModule",{value:!0});ji.BooleanBinaryCodec=void 0;var AQ=vQ(Ie()),_6=dr(),kf=class t{decodeNested(e){let r=e.readUInt8(0);return[new _6.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new AQ.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new _6.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([])}};ji.BooleanBinaryCodec=kf;kf.TRUE=1;kf.FALSE=0});var bp=B(Ep=>{"use strict";h();Object.defineProperty(Ep,"__esModule",{value:!0});Ep.SizeOfU32=void 0;Ep.SizeOfU32=4});var x6=B(lc=>{"use strict";h();var EQ=lc&&lc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lc,"__esModule",{value:!0});lc.NumericalBinaryCodec=void 0;var Hf=EQ((rr(),_e(fr))),TA=dr(),N6=bp(),$t=Bu(),_A=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=N6.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),u=i+n;return[o,u]}decodeTopLevel(e,r){let n=$t.cloneBuffer(e);if(e.length==0)return new TA.NumericalValue(r,new Hf.default(0));if(!r.withSign||$t.isMsbZero(n)){let c=$t.bufferToBigInt(n);return new TA.NumericalValue(r,c)}$t.flipBufferBitsInPlace(n);let a=$t.bufferToBigInt(n).multipliedBy(new Hf.default(-1)).minus(new Hf.default(1));return new TA.NumericalValue(r,a)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=p.Buffer.alloc(N6.SizeOfU32);return n.writeUInt32BE(r.length),p.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return p.Buffer.alloc(r,0);if(!e.withSign){let o=$t.bigIntToBuffer(e.value),u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}if(e.value.isPositive()){let o=$t.bigIntToBuffer(e.value);$t.isMsbOne(o)&&(o=$t.prependByteToBuffer(o,0));let u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}let n=e.value.plus(new Hf.default(1)),i=$t.bigIntToBuffer(n);$t.flipBufferBitsInPlace(i),$t.isMsbZero(i)&&(i=$t.prependByteToBuffer(i,255));let s=p.Buffer.alloc(r-i.length,255);return p.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?p.Buffer.alloc(0):r?this.encodePrimitive(e):$t.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=$t.bigIntToBuffer(e.value);return $t.isMsbOne(i)&&(i=$t.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Hf.default(1)),n=$t.bigIntToBuffer(r);return $t.flipBufferBitsInPlace(n),$t.isMsbZero(n)&&(n=$t.prependByteToBuffer(n,255)),n}};lc.NumericalBinaryCodec=_A});var O6=B(Sp=>{"use strict";h();Object.defineProperty(Sp,"__esModule",{value:!0});Sp.H256BinaryCodec=void 0;var bQ=Sf(),CA=class{decodeNested(e){let r=e.slice(0,32);return[new bQ.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Sp.H256BinaryCodec=CA});var _p=B(Tp=>{"use strict";h();Object.defineProperty(Tp,"__esModule",{value:!0});Tp.BytesBinaryCodec=void 0;var D6=po(),Ip=bp(),NA=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(Ip.SizeOfU32,Ip.SizeOfU32+r);return[new D6.BytesValue(n),Ip.SizeOfU32+r]}decodeTopLevel(e){return new D6.BytesValue(e)}encodeNested(e){let r=p.Buffer.alloc(Ip.SizeOfU32);return r.writeUInt32BE(e.getLength()),p.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Tp.BytesBinaryCodec=NA});var R6=B(Cp=>{"use strict";h();Object.defineProperty(Cp,"__esModule",{value:!0});Cp.TokenIdentifierCodec=void 0;var SQ=po(),P6=ac(),IQ=_p(),xA=class{constructor(){this.bytesCodec=new IQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new P6.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new P6.TokenIdentifierValue(r.toString())}encodeNested(e){let r=SQ.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Cp.TokenIdentifierCodec=xA});var M6=B(Np=>{"use strict";h();Object.defineProperty(Np,"__esModule",{value:!0});Np.NothingCodec=void 0;var B6=dr(),OA=class{decodeNested(){return[new B6.NothingValue,0]}decodeTopLevel(){return new B6.NothingValue}encodeNested(){return p.Buffer.from([])}encodeTopLevel(){return p.Buffer.from([])}};Np.NothingCodec=OA});var F6=B(xp=>{"use strict";h();Object.defineProperty(xp,"__esModule",{value:!0});xp.StringBinaryCodec=void 0;var L6=dr(),TQ=po(),_Q=_p(),DA=class{constructor(){this.bytesBinaryCodec=new _Q.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new L6.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new L6.StringValue(e.toString())}encodeNested(e){let r=TQ.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};xp.StringBinaryCodec=DA});var U6=B(Dp=>{"use strict";h();Object.defineProperty(Dp,"__esModule",{value:!0});Dp.PrimitiveBinaryCodec=void 0;var Op=dr(),CQ=T6(),NQ=C6(),xQ=x6(),OQ=O6(),DQ=_p(),PQ=R6(),RQ=M6(),BQ=F6(),PA=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new NQ.BooleanBinaryCodec,this.numericalCodec=new xQ.NumericalBinaryCodec,this.addressCodec=new CQ.AddressBinaryCodec,this.h256Codec=new OQ.H256BinaryCodec,this.bytesCodec=new DQ.BytesBinaryCodec,this.stringCodec=new BQ.StringBinaryCodec,this.tokenIdentifierCodec=new PQ.TokenIdentifierCodec,this.nothingCodec=new RQ.NothingCodec}decodeNested(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};Dp.PrimitiveBinaryCodec=PA});var k6=B(Pp=>{"use strict";h();Object.defineProperty(Pp,"__esModule",{value:!0});Pp.ListBinaryCodec=void 0;var q6=dr(),V6=bp(),RA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,u=V6.SizeOfU32;e=o.slice(u);for(let a=0;a0;){let[u,a]=this.binaryCodec.decodeNested(e,n);i.push(u),o+=a,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new q6.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=p.Buffer.alloc(V6.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return p.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return p.Buffer.concat(r)}};Pp.ListBinaryCodec=RA});var MA=B(Rp=>{"use strict";h();Object.defineProperty(Rp,"__esModule",{value:!0});Rp.FieldsBinaryCodec=void 0;var MQ=dr(),BA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,u]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(u),i+=u;let a=new MQ.Field(o,s.name);n.push(a)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return p.Buffer.concat(r)}};Rp.FieldsBinaryCodec=BA});var FA=B(Bp=>{"use strict";h();Object.defineProperty(Bp,"__esModule",{value:!0});Bp.StructBinaryCodec=void 0;var LQ=dr(),FQ=MA(),LA=class{constructor(e){this.fieldsCodec=new FQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new LQ.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Bp.StructBinaryCodec=LA});var H6=B(Lp=>{"use strict";h();Object.defineProperty(Lp,"__esModule",{value:!0});Lp.EnumBinaryCodec=void 0;var Mp=dr(),UQ=MA(),UA=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new UQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[u,a]=this.fieldsCodec.decodeNested(e,o);return[new Mp.EnumValue(r,s,u),i+a]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Mp.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Mp.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return p.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Mp.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return p.Buffer.concat([o,i])}};Lp.EnumBinaryCodec=UA});var G6=B(Fp=>{"use strict";h();Object.defineProperty(Fp,"__esModule",{value:!0});Fp.TupleBinaryCodec=void 0;var qQ=FA(),qA=class{constructor(e){this.structCodec=new qQ.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Fp.TupleBinaryCodec=qA});var j6=B(Up=>{"use strict";h();Object.defineProperty(Up,"__esModule",{value:!0});Up.ArrayVecBinaryCodec=void 0;var VQ=dr(),VA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let u=0;u{"use strict";h();var kQ=Ln&&Ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),HQ=Ln&&Ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GQ=Ln&&Ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&kQ(e,t,r);return HQ(e,t),e};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BinaryCodecConstraints=Ln.BinaryCodec=void 0;var z6=GQ(Ie()),qp=dr(),Q6=Rn(),jQ=I6(),zQ=U6(),QQ=k6(),KQ=FA(),WQ=H6(),$Q=G6(),YQ=j6(),kA=class{constructor(e=null){this.constraints=e||new Vp,this.optionCodec=new jQ.OptionValueBinaryCodec(this),this.listCodec=new QQ.ListBinaryCodec(this),this.arrayCodec=new YQ.ArrayVecBinaryCodec(this),this.primitiveCodec=new zQ.PrimitiveBinaryCodec(this),this.structCodec=new KQ.StructBinaryCodec(this),this.tupleCodec=new $Q.TupleBinaryCodec(this),this.enumCodec=new WQ.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Ln.BinaryCodec=kA;var Vp=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new z6.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new z6.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Ln.BinaryCodecConstraints=Vp});var K6=B(Fn=>{"use strict";h();var JQ=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decodeBigNumber=Fn.decodeString=Fn.decodeBool=Fn.decodeUnsignedNumber=void 0;var XQ=JQ((rr(),_e(fr))),kp=dr(),ZQ=HA(),Hp=new ZQ.BinaryCodec;function eK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return Number(e.valueOf())}Fn.decodeUnsignedNumber=eK;function tK(t){return!!Hp.decodeTopLevel(t,new kp.BooleanType).valueOf()}Fn.decodeBool=tK;function rK(t){let e=Hp.decodeTopLevel(t,new kp.BytesType);return String(e.valueOf())}Fn.decodeString=rK;function nK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return new XQ.default(e.valueOf())}Fn.decodeBigNumber=nK});var GA=B(wo=>{"use strict";h();var iK=wo&&wo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),W6=wo&&wo.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&iK(e,t,r)};Object.defineProperty(wo,"__esModule",{value:!0});W6(HA(),wo);W6(K6(),wo)});var fc=B(Gp=>{"use strict";h();Object.defineProperty(Gp,"__esModule",{value:!0});Gp.ArgSerializer=void 0;var $6=hr(),sK=GA(),Y6=dr(),jA=Lg(),zA=kg(),QA=gp(),oK={codec:new sK.BinaryCodec},KA=class{constructor(e){e={...oK,...e},this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split($6.ARGUMENTS_SEPARATOR).map(r=>p.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join($6.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(jA.OptionalValue.ClassName)){let a=o;a.isSet()&&i(a.getTypedValue());return}if(o.hasExactClass(QA.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(zA.CompositeValue.ClassName)){let a=o;for(let c of a.getItems())i(c);return}let u=r.codec.encodeTopLevel(o);n.push(u)}function s(o){if(o.getType().isCounted){let a=new Y6.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(a))}for(let a of o.getItems())i(a)}return n}};Gp.ArgSerializer=KA});var WA=B((cye,J6)=>{h();Rs.notEqual=uK;Rs.notOk=cK;Rs.equal=aK;Rs.ok=Rs;J6.exports=Rs;function aK(t,e,r){Rs(t==e,r)}function uK(t,e,r){Rs(t!=e,r)}function cK(t,e){Rs(!t,e)}function Rs(t,e){if(!t)throw new Error(e||"AssertionError")}});var Z6=B((fye,X6)=>{h();X6.exports=$A;$A.supported=typeof WebAssembly<"u";function $A(t){if(!$A.supported)return null;var e=t&&t.imports,r=lK("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(a){i.exports.memory.grow(Math.ceil(Math.abs(a-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(a){if(i.exports)return a();if(n){n.then(a.bind(null,null)).catch(a);return}try{if(t&&t.async)throw new Error("async");u({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(u)}o(a)}function u(a){i.exports=a.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function lK(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(fK)):new(io()).Buffer(t,"base64")}function fK(t){return t.charCodeAt(0)}});var oO=B((pye,Qi)=>{h();var zi=WA(),xt=Z6()(),Bs=64,jp=[];Qi.exports=Un;var eO=Qi.exports.BYTES_MIN=16,tO=Qi.exports.BYTES_MAX=64,dye=Qi.exports.BYTES=32,rO=Qi.exports.KEYBYTES_MIN=16,nO=Qi.exports.KEYBYTES_MAX=64,gye=Qi.exports.KEYBYTES=32,iO=Qi.exports.SALTBYTES=16,sO=Qi.exports.PERSONALBYTES=16;function Un(t,e,r,n,i){if(!(this instanceof Un))return new Un(t,e,r,n,i);if(!(xt&&xt.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(zi(t>=eO,"digestLength must be at least "+eO+", was given "+t),zi(t<=tO,"digestLength must be at most "+tO+", was given "+t),e!=null&&zi(e.length>=rO,"key must be at least "+rO+", was given "+e.length),e!=null&&zi(e.length<=nO,"key must be at least "+nO+", was given "+e.length),r!=null&&zi(r.length===iO,"salt must be exactly "+iO+", was given "+r.length),n!=null&&zi(n.length===sO,"personal must be exactly "+sO+", was given "+n.length)),jp.length||(jp.push(Bs),Bs+=216),this.digestLength=t,this.finalized=!1,this.pointer=jp.pop(),xt.memory.fill(0,0,64),xt.memory[0]=this.digestLength,xt.memory[1]=e?e.length:0,xt.memory[2]=1,xt.memory[3]=1,r&&xt.memory.set(r,32),n&&xt.memory.set(n,48),this.pointer+216>xt.memory.length&&xt.realloc(this.pointer+216),xt.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),xt.memory.fill(0,Bs,Bs+e.length),xt.memory[this.pointer+200]=128)}Un.prototype.update=function(t){return zi(this.finalized===!1,"Hash instance finalized"),zi(t,"input must be TypedArray or Buffer"),Bs+t.length>xt.memory.length&&xt.realloc(Bs+t.length),xt.memory.set(t,Bs),xt.exports.blake2b_update(this.pointer,Bs,Bs+t.length),this};Un.prototype.digest=function(t){if(zi(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,jp.push(this.pointer),xt.exports.blake2b_final(this.pointer),!t||t==="binary")return xt.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return dK(xt.memory,this.pointer+128,this.digestLength);zi(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{h();var Eo=WA(),jf=oO();function zp(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function aO(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function gO(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vo(t,e,r,n,i,s){var o=Gf[i],u=Gf[i+1],a=Gf[s],c=Gf[s+1];zp(Te,t,e),aO(Te,t,o,u);var f=Te[n]^Te[t],d=Te[n+1]^Te[t+1];Te[n]=d,Te[n+1]=f,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=f>>>24^d<<8,Te[e+1]=d>>>24^f<<8,zp(Te,t,e),aO(Te,t,a,c),f=Te[n]^Te[t],d=Te[n+1]^Te[t+1],Te[n]=f>>>16^d<<16,Te[n+1]=d>>>16^f<<16,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=d>>>31^f<<1,Te[e+1]=f>>>31^d<<1}var pO=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),pK=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Pr=new Uint8Array(pK.map(function(t){return t*2})),Te=new Uint32Array(32),Gf=new Uint32Array(32);function mO(t,e){var r=0;for(r=0;r<16;r++)Te[r]=t.h[r],Te[r+16]=pO[r];for(Te[24]=Te[24]^t.t,Te[25]=Te[25]^t.t/4294967296,e&&(Te[28]=~Te[28],Te[29]=~Te[29]),r=0;r<32;r++)Gf[r]=gO(t.b,4*r);for(r=0;r<12;r++)vo(0,8,16,24,Pr[r*16+0],Pr[r*16+1]),vo(2,10,18,26,Pr[r*16+2],Pr[r*16+3]),vo(4,12,20,28,Pr[r*16+4],Pr[r*16+5]),vo(6,14,22,30,Pr[r*16+6],Pr[r*16+7]),vo(0,10,20,30,Pr[r*16+8],Pr[r*16+9]),vo(2,12,22,24,Pr[r*16+10],Pr[r*16+11]),vo(4,14,16,26,Pr[r*16+12],Pr[r*16+13]),vo(6,8,18,28,Pr[r*16+14],Pr[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Te[r]^Te[r+16]}var Ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hc(t,e,r,n){Ao.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Ao[0]=t,e&&(Ao[1]=e.length),Ao[2]=1,Ao[3]=1,r&&Ao.set(r,32),n&&Ao.set(n,48);for(var i=0;i<16;i++)this.h[i]=pO[i]^gO(Ao,i*4);e&&(yO(this,e),this.c=128)}hc.prototype.update=function(t){return Eo(t!=null,"input must be Uint8Array or Buffer"),yO(this,t),this};hc.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Eo(e.length>=this.outlen,"out must have at least outlen bytes of space"),mK(this,e),t==="hex"?yK(e):e};hc.prototype.final=hc.prototype.digest;hc.ready=function(t){jf.ready(function(){t()})};function yO(t,e){for(var r=0;r>2]>>8*(r&3);return e}function yK(t){for(var e="",r=0;r=uO,"outlen must be at least "+uO+", was given "+e),Eo(e<=cO,"outlen must be at most "+cO+", was given "+e),r!=null&&Eo(r.length>=lO,"key must be at least "+lO+", was given "+r.length),r!=null&&Eo(r.length<=fO,"key must be at most "+fO+", was given "+r.length),n!=null&&Eo(n.length===hO,"salt must be exactly "+hO+", was given "+n.length),i!=null&&Eo(i.length===dO,"personal must be exactly "+dO+", was given "+i.length)),new wO(e,r,n,i)};Jr.exports.ready=function(t){jf.ready(function(){t()})};Jr.exports.WASM_SUPPORTED=jf.SUPPORTED;Jr.exports.WASM_LOADED=!1;var uO=Jr.exports.BYTES_MIN=16,cO=Jr.exports.BYTES_MAX=64,yye=Jr.exports.BYTES=32,lO=Jr.exports.KEYBYTES_MIN=16,fO=Jr.exports.KEYBYTES_MAX=64,wye=Jr.exports.KEYBYTES=32,hO=Jr.exports.SALTBYTES=16,dO=Jr.exports.PERSONALBYTES=16;jf.ready(function(t){t||(Jr.exports.WASM_LOADED=!0,wO=jf)})});var vO=B(Qp=>{"use strict";h();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.Code=void 0;var vK=YA(),AK=32,JA=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return p.Buffer.from(this.hex,"hex")}computeHash(){let e=vK(AK).update(this.valueOf()).digest();return p.Buffer.from(e)}};Qp.Code=JA});var XA=B(Kp=>{"use strict";h();Object.defineProperty(Kp,"__esModule",{value:!0});Kp.CodeMetadata=void 0;var dc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBytes(e){return t.fromBuffer(p.Buffer.from(e))}static fromBuffer(e){if(e.length{"use strict";h();var EK=Ki&&Ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bK=Ki&&Ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SK=Ki&&Ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EK(e,t,r);return bK(e,t),e};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ContractFunction=void 0;var IK=SK(Ie()),ZA=class t{constructor(e){if(this.name=e,e==null)throw new IK.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Ki.ContractFunction=ZA});var rE=B(Wp=>{"use strict";h();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.Compatibility=void 0;var TK=Ve(),tE=class{static guardAddressIsSetAndNonZero(e,r,n){!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==TK.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`)}};Wp.Compatibility=tE});var Ms=B($p=>{"use strict";h();Object.defineProperty($p,"__esModule",{value:!0});$p.TransactionPayload=void 0;var nE=class t{constructor(e){this.data=p.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=p.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>p.Buffer.from(e,"hex"))}length(){return p.Buffer.from(this.data).length}};$p.TransactionPayload=nE});var gc=B(Yp=>{"use strict";h();Object.defineProperty(Yp,"__esModule",{value:!0});Yp.TransactionBuilder=void 0;var _K=hr(),CK=Xr(),NK=Ms(),iE=class{constructor(e){this.config=e.config,this.sender=e.sender,this.receiver=e.receiver,this.dataParts=e.dataParts,this.providedGasLimit=e.gasLimit,this.addDataMovementGas=e.addDataMovementGas,this.amount=e.amount}computeGasLimit(e){return this.addDataMovementGas?this.config.minGasLimit+this.config.gasLimitPerByte*BigInt(e.length())+this.providedGasLimit:this.providedGasLimit}buildTransactionPayload(){let e=this.dataParts.join(_K.ARGUMENTS_SEPARATOR);return new NK.TransactionPayload(e)}build(){let e=this.buildTransactionPayload(),r=this.computeGasLimit(e);return new CK.Transaction({sender:this.sender.bech32(),receiver:this.receiver.bech32(),gasLimit:r,value:this.amount||0n,data:e.valueOf(),chainID:this.config.chainID})}};Yp.TransactionBuilder=iE});var AO=B(Jp=>{"use strict";h();Object.defineProperty(Jp,"__esModule",{value:!0});Jp.DelegationTransactionsFactory=void 0;var xK=Ve(),OK=hr(),DK=Ie(),fn=qn(),Zr=gc(),sE=class{constructor(e){this.config=e.config,this.argSerializer=new fn.ArgSerializer}createTransactionForNewDelegationContract(e){let r=["createNewDelegationContract",...this.argSerializer.valuesToStrings([new fn.BigUIntValue(e.totalDelegationCap),new fn.BigUIntValue(e.serviceFee)])],n=this.config.gasLimitCreateDelegationContract+this.config.additionalGasLimitForDelegationOperations;return new Zr.TransactionBuilder({config:this.config,sender:e.sender,receiver:xK.Address.fromBech32(OK.DELEGATION_MANAGER_SC_ADDRESS),dataParts:r,gasLimit:n,addDataMovementGas:!0,amount:e.amount}).build()}createTransactionForAddingNodes(e){if(e.publicKeys.length!==e.signedMessages.length)throw new DK.Err("The number of public keys should match the number of signed messages");let r=e.signedMessages.map(o=>new fn.BytesValue(p.Buffer.from(o))),n=this.argSerializer.valuesToStrings(r),i=e.publicKeys.length,s=["addNodes"];for(let o=0;o{h();var EO=(rr(),_e(fr)),bO=SO.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function u(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(f){var d=s[f];return typeof d=="string"?d:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function a(c,f){var d,w,A,T,x=n,R,V=f[c],U=V!=null&&(V instanceof EO||EO.isBigNumber(V));switch(V&&typeof V=="object"&&typeof V.toJSON=="function"&&(V=V.toJSON(c)),typeof o=="function"&&(V=o.call(f,c,V)),typeof V){case"string":return U?V:u(V);case"number":return isFinite(V)?String(V):"null";case"boolean":case"null":case"bigint":return String(V);case"object":if(!V)return"null";if(n+=i,R=[],Object.prototype.toString.apply(V)==="[object Array]"){for(T=V.length,d=0;d{"use strict";h();var cH=xn&&xn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xn,"__esModule",{value:!0});xn.TokenPayment=xn.TokenComputer=xn.TokenTransfer=xn.Token=void 0;var Ta=cH((rr(),_e(fr))),Du=Ie(),q3="EGLD",V3=18;Ta.default.set({ROUNDING_MODE:1});var Vd=class{constructor(e){this.identifier=e.identifier,this.nonce=e.nonce||0n}};xn.Token=Vd;var kd=class t{constructor(e){if(this.isLegacyTokenTransferOptions(e)){let r=new Ta.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new Du.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0,this.token=new Vd({identifier:e.tokenIdentifier,nonce:BigInt(e.nonce)}),this.amount=BigInt(this.amountAsBigInteger.toFixed(0))}else this.token=e.token,this.amount=e.amount,this.tokenIdentifier=e.token.identifier,this.nonce=Number(e.token.nonce),this.amountAsBigInteger=new Ta.default(this.amount.toString()),this.numDecimals=0}isLegacyTokenTransferOptions(e){return e.tokenIdentifier!==void 0}static egldFromAmount(e){let r=new Ta.default(e).shiftedBy(V3).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:q3,nonce:0,amountAsBigInteger:e,numDecimals:V3})}static fungibleFromAmount(e,r,n){let i=new Ta.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new Ta.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amount.toString()}valueOf(){return new Ta.default(this.amount.toString())}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.token.identifier==q3}isFungible(){return this.token.nonce==0n}};xn.TokenTransfer=kd;var gv=class{constructor(){}isFungible(e){return e.nonce===0n}extractNonceFromExtendedIdentifier(e){let r=e.split("-");if(this.checkIfExtendedIdentifierWasProvided(r),this.checkLengthOfRandomSequence(r[1]),r.length==2)return 0;let n=p.Buffer.from(r[2],"hex");return lH(n)}extractIdentifierFromExtendedIdentifier(e){let r=e.split("-");return this.checkIfExtendedIdentifierWasProvided(r),this.ensureTokenTickerValidity(r[0]),this.checkLengthOfRandomSequence(r[1]),r[0]+"-"+r[1]}checkIfExtendedIdentifierWasProvided(e){if(e.length<2||e.length>3)throw new Du.ErrInvalidTokenIdentifier("Invalid extended token identifier provided")}checkLengthOfRandomSequence(e){if(e.length!==6)throw new Du.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length")}ensureTokenTickerValidity(e){if(e.length<3||e.length>10)throw new Du.ErrInvalidTokenIdentifier("The token ticker should be between 3 and 10 characters");if(!e.match(/^[a-zA-Z0-9]+$/))throw new Du.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters");if(e!=e.toUpperCase())throw new Du.ErrInvalidTokenIdentifier("The token ticker should be upper case")}};xn.TokenComputer=gv;function lH(t){return t.readUIntBE(0,t.length)}var pv=class extends kd{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};xn.TokenPayment=pv});var hr=D(Ae=>{"use strict";h();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.UNKNOWN_SIGNER=Ae.SDK_JS_SIGNER=Ae.METACHAIN_ID=Ae.WasmVirtualMachine=Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=Ae.BECH32_ADDRESS_LENGTH=Ae.HEX_TRANSACTION_HASH_LENGTH=Ae.MESSAGE_PREFIX=Ae.DEFAULT_MESSAGE_VERSION=Ae.ESDT_CONTRACT_ADDRESS=Ae.DEFAULT_HRP=Ae.DELEGATION_MANAGER_SC_ADDRESS=Ae.CONTRACT_DEPLOY_ADDRESS=Ae.VM_TYPE_WASM_VM=Ae.ARGUMENTS_SEPARATOR=Ae.ESDT_TRANSFER_VALUE=Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_GAS_LIMIT=Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=Ae.TRANSACTION_VERSION_DEFAULT=Ae.TRANSACTION_OPTIONS_TX_GUARDED=Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=Ae.TRANSACTION_OPTIONS_DEFAULT=Ae.TRANSACTION_MIN_GAS_PRICE=void 0;Ae.TRANSACTION_MIN_GAS_PRICE=1e9;Ae.TRANSACTION_OPTIONS_DEFAULT=0;Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Ae.TRANSACTION_OPTIONS_TX_GUARDED=2;Ae.TRANSACTION_VERSION_DEFAULT=2;Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=2;Ae.ESDT_TRANSFER_GAS_LIMIT=5e5;Ae.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Ae.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Ae.ESDT_TRANSFER_VALUE="0";Ae.ARGUMENTS_SEPARATOR="@";Ae.VM_TYPE_WASM_VM=new Uint8Array([5,0]);Ae.CONTRACT_DEPLOY_ADDRESS="erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu";Ae.DELEGATION_MANAGER_SC_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6";Ae.DEFAULT_HRP="erd";Ae.ESDT_CONTRACT_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u";Ae.DEFAULT_MESSAGE_VERSION=1;Ae.MESSAGE_PREFIX=`Elrond Signed Message: +`;Ae.HEX_TRANSACTION_HASH_LENGTH=64;Ae.BECH32_ADDRESS_LENGTH=62;Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=3;Ae.WasmVirtualMachine="0500";Ae.METACHAIN_ID=4294967295;Ae.SDK_JS_SIGNER="sdk-js";Ae.UNKNOWN_SIGNER="unknown"});var oo=D(Na=>{"use strict";h();Object.defineProperty(Na,"__esModule",{value:!0});Na.Logger=Na.LogLevel=void 0;var Ca;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Ca=Na.LogLevel||(Na.LogLevel={}));var Hd=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Ca.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Ca.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Ca.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Ca.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Ca.Error||console.error(e,r)}};Na.Logger=Hd;Hd.logLevel=Ca.Debug});var $l=D(On=>{"use strict";h();var fH=On&&On.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),hH=On&&On.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dH=On&&On.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fH(e,t,r);return hH(e,t),e};Object.defineProperty(On,"__esModule",{value:!0});On.TransactionOptions=On.TransactionVersion=void 0;var gi=hr(),k3=dH(Ie()),mv=class t{constructor(e){if(e=Number(e),e<1)throw new k3.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}valueOf(){return this.value}};On.TransactionVersion=mv;var yv=class t{constructor(e){if(e=Number(e),e<0)throw new k3.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(gi.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=gi.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&gi.TRANSACTION_OPTIONS_TX_HASH_SIGN)==gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&gi.TRANSACTION_OPTIONS_TX_GUARDED)==gi.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=gi.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};On.TransactionOptions=yv});var vv=D((Epe,j3)=>{"use strict";h();var jd="qpzry9x8gf2tvdw0s3jn54khce6mua7l",wv={};for(Yl=0;Yl>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function H3(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=H3(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Pu(n)^o,i+=jd.charAt(o)}for(s=0;s<6;++s)n=Pu(n);for(n^=1,s=0;s<6;++s){var u=n>>(5-s)*5&31;i+=jd.charAt(u)}return i}function G3(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var u=H3(s);if(typeof u=="string")return u;for(var a=[],c=0;c=o.length)&&a.push(d)}return u!==1?"Invalid checksum for "+t:{prefix:s,words:a}}function pH(){var t=G3.apply(null,arguments);if(typeof t=="object")return t}function mH(t){var e=G3.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function zd(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<{"use strict";h();var EH=Nt&&Nt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bH=Nt&&Nt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SH=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EH(e,t,r);return bH(e,t),e},IH=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.addressToHex=Nt.bigIntToHex=Nt.byteArrayToHex=Nt.boolToHex=Nt.utf8ToHex=Nt.zeroPadStringIfOddLength=Nt.isPaddedHex=Nt.numberToPaddedHex=void 0;var TH=IH((rr(),_e(fr))),_H=Ve(),CH=SH(Bu());function NH(t){let e;typeof t=="bigint"||typeof t=="number"?e=t:e=new TH.default(t);let r=e.toString(16);return Qd(r)}Nt.numberToPaddedHex=NH;function xH(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Nt.isPaddedHex=xH;function Qd(t){return t=t||"",t.length%2==1?"0"+t:t}Nt.zeroPadStringIfOddLength=Qd;function z3(t){let e=p.Buffer.from(t).toString("hex");return Qd(e)}Nt.utf8ToHex=z3;function OH(t){return z3(t.toString())}Nt.boolToHex=OH;function DH(t){let e=p.Buffer.from(t).toString("hex");return Qd(e)}Nt.byteArrayToHex=DH;function PH(t){return t==0?"":CH.getHexMagnitudeOfBigInt(t)}Nt.bigIntToHex=PH;function RH(t){return _H.Address.fromBech32(t.toString()).pubkey().toString("hex")}Nt.addressToHex=RH});var Bu=D(nr=>{"use strict";h();var BH=nr&&nr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nr,"__esModule",{value:!0});nr.prependByteToBuffer=nr.flipBufferBitsInPlace=nr.getHexMagnitudeOfBigInt=nr.bigIntToBuffer=nr.bufferToBigInt=nr.cloneBuffer=nr.isMsbZero=nr.isMsbOne=void 0;var Av=BH((rr(),_e(fr))),MH=Ru();function Q3(t,e=0){return t[e]>>7==1}nr.isMsbOne=Q3;function LH(t,e=0){return!Q3(t,e)}nr.isMsbZero=LH;function FH(t){let e=p.Buffer.alloc(t.length);return t.copy(e),e}nr.cloneBuffer=FH;function UH(t){let e=t.toString("hex");return new Av.default(`0x${e}`,16)}nr.bufferToBigInt=UH;function qH(t){let e=K3(t);return p.Buffer.from(e,"hex")}nr.bigIntToBuffer=qH;function K3(t){return t=new Av.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new Av.default(-1))),MH.numberToPaddedHex(t)):""}nr.getHexMagnitudeOfBigInt=K3;function VH(t){for(let e=0;e{"use strict";h();var HH=Lt&&Lt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),GH=Lt&&Lt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),W3=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&HH(e,t,r);return GH(e,t),e},jH=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.bufferToHex=Lt.addressToHex=Lt.bigIntToHex=Lt.utf8ToHex=Lt.bigIntToBuffer=Lt.bufferToBigInt=Lt.stringToBuffer=void 0;var zH=jH((rr(),_e(fr))),$3=W3(Bu()),QH=W3(Ru());function KH(t){return p.Buffer.from(t)}Lt.stringToBuffer=KH;function WH(t){return t.length==0?new zH.default(0):$3.bufferToBigInt(t)}Lt.bufferToBigInt=WH;function $H(t){return t==0?p.Buffer.from([]):$3.bigIntToBuffer(t)}Lt.bigIntToBuffer=$H;var Ev=Ru();Object.defineProperty(Lt,"utf8ToHex",{enumerable:!0,get:function(){return Ev.utf8ToHex}});Object.defineProperty(Lt,"bigIntToHex",{enumerable:!0,get:function(){return Ev.bigIntToHex}});Object.defineProperty(Lt,"addressToHex",{enumerable:!0,get:function(){return Ev.addressToHex}});function YH(t){let e=t.toString("hex");return QH.zeroPadStringIfOddLength(e)}Lt.bufferToHex=YH});var Ds=D((xpe,bv)=>{"use strict";h();var Mu=typeof Reflect=="object"?Reflect:null,Y3=Mu&&typeof Mu.apply=="function"?Mu.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Wd;Mu&&typeof Mu.ownKeys=="function"?Wd=Mu.ownKeys:Object.getOwnPropertySymbols?Wd=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Wd=function(e){return Object.getOwnPropertyNames(e)};function JH(t){console&&console.warn&&console.warn(t)}var X3=Number.isNaN||function(e){return e!==e};function _t(){_t.init.call(this)}bv.exports=_t;bv.exports.once=tG;_t.EventEmitter=_t;_t.prototype._events=void 0;_t.prototype._eventsCount=0;_t.prototype._maxListeners=void 0;var J3=10;function $d(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_t,"defaultMaxListeners",{enumerable:!0,get:function(){return J3},set:function(t){if(typeof t!="number"||t<0||X3(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");J3=t}});_t.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_t.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||X3(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Z3(t){return t._maxListeners===void 0?_t.defaultMaxListeners:t._maxListeners}_t.prototype.getMaxListeners=function(){return Z3(this)};_t.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var u=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw u.context=o,u}var a=s[e];if(a===void 0)return!1;if(typeof a=="function")Y3(a,this,r);else for(var c=a.length,f=iN(a,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=o.length,JH(u)}return t}_t.prototype.addListener=function(e,r){return eN(this,e,r,!1)};_t.prototype.on=_t.prototype.addListener;_t.prototype.prependListener=function(e,r){return eN(this,e,r,!0)};function XH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function tN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=XH.bind(n);return i.listener=r,n.wrapFn=i,i}_t.prototype.once=function(e,r){return $d(r),this.on(e,tN(this,e,r)),this};_t.prototype.prependOnceListener=function(e,r){return $d(r),this.prependListener(e,tN(this,e,r)),this};_t.prototype.removeListener=function(e,r){var n,i,s,o,u;if($d(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){u=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():ZH(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||r)}return this};_t.prototype.off=_t.prototype.removeListener;_t.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function rN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?eG(i):iN(i,i.length)}_t.prototype.listeners=function(e){return rN(this,e,!0)};_t.prototype.rawListeners=function(e){return rN(this,e,!1)};_t.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):nN.call(t,e)};_t.prototype.listenerCount=nN;function nN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_t.prototype.eventNames=function(){return this._eventsCount>0?Wd(this._events):[]};function iN(t,e){for(var r=new Array(e),n=0;n{h();oN.exports=Ds().EventEmitter});var Iv=D(()=>{h()});var hN=D((Lpe,fN)=>{"use strict";h();function aN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function uN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Yd.alloc(0);for(var n=Yd.allocUnsafe(r>>>0),i=this.head,s=0;i;)lG(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(u===o.length?s+=o:s+=o.slice(0,r),r-=u,r===0){u===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(u));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Yd.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,u=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,u),r-=u,r===0){u===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(u));break}++s}return this.length-=s,n}},{key:cG,value:function(r,n){return Tv(this,uN(uN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var Cv=D((Upe,gN)=>{"use strict";h();function fG(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,S.default.nextTick(_v,this,t)):S.default.nextTick(_v,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?S.default.nextTick(Jd,r):(r._writableState.errorEmitted=!0,S.default.nextTick(dN,r,s)):S.default.nextTick(dN,r,s):e?(S.default.nextTick(Jd,r),e(s)):S.default.nextTick(Jd,r)}),this)}function dN(t,e){_v(t,e),Jd(t)}function Jd(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function hG(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function _v(t,e){t.emit("error",e)}function dG(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}gN.exports={destroy:fG,undestroy:hG,errorOrDestroy:dG}});var xa=D((Vpe,yN)=>{"use strict";h();function gG(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var mN={};function Dn(t,e,r){r||(r=Error);function n(s,o,u){return typeof e=="string"?e:e(s,o,u)}var i=function(s){gG(o,s);function o(u,a,c){return s.call(this,n(u,a,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,mN[t]=i}function pN(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function pG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function mG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function yG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}Dn("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);Dn("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&pG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(mG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(pN(e,"type"));else{var s=yG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(pN(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);Dn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");Dn("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});Dn("ERR_STREAM_PREMATURE_CLOSE","Premature close");Dn("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});Dn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");Dn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");Dn("ERR_STREAM_WRITE_AFTER_END","write after end");Dn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Dn("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);Dn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");yN.exports.codes=mN});var Nv=D((Hpe,wN)=>{"use strict";h();var wG=xa().codes.ERR_INVALID_OPT_VALUE;function vG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function AG(t,e,r,n){var i=vG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new wG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}wN.exports={getHighWaterMark:AG}});var Lu=D((jpe,xv)=>{h();typeof Object.create=="function"?xv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:xv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var AN=D((Qpe,vN)=>{h();vN.exports=EG;function EG(t,e){if(Ov("noDeprecation"))return t;var r=!1;function n(){if(!r){if(Ov("throwDeprecation"))throw new Error(e);Ov("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function Ov(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var Rv=D((Wpe,_N)=>{"use strict";h();_N.exports=Gt;function bN(t){var e=this;this.next=null,this.entry=null,this.finish=function(){WG(e,t)}}var Fu;Gt.WritableState=Xl;var bG={deprecate:AN()},SN=Sv(),Zd=io().Buffer,SG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function IG(t){return Zd.from(t)}function TG(t){return Zd.isBuffer(t)||t instanceof SG}var Pv=Cv(),_G=Nv(),CG=_G.getHighWaterMark,ao=xa().codes,NG=ao.ERR_INVALID_ARG_TYPE,xG=ao.ERR_METHOD_NOT_IMPLEMENTED,OG=ao.ERR_MULTIPLE_CALLBACK,DG=ao.ERR_STREAM_CANNOT_PIPE,PG=ao.ERR_STREAM_DESTROYED,RG=ao.ERR_STREAM_NULL_VALUES,BG=ao.ERR_STREAM_WRITE_AFTER_END,MG=ao.ERR_UNKNOWN_ENCODING,Uu=Pv.errorOrDestroy;Lu()(Gt,SN);function LG(){}function Xl(t,e,r){Fu=Fu||Oa(),t=t||{},typeof r!="boolean"&&(r=e instanceof Fu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=CG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){GG(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new bN(this)}Xl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(Xl.prototype,"buffer",{get:bG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var Xd;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Xd=Function.prototype[Symbol.hasInstance],Object.defineProperty(Gt,Symbol.hasInstance,{value:function(e){return Xd.call(this,e)?!0:this!==Gt?!1:e&&e._writableState instanceof Xl}})):Xd=function(e){return e instanceof this};function Gt(t){Fu=Fu||Oa();var e=this instanceof Fu;if(!e&&!Xd.call(Gt,this))return new Gt(t);this._writableState=new Xl(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),SN.call(this)}Gt.prototype.pipe=function(){Uu(this,new DG)};function FG(t,e){var r=new BG;Uu(t,r),S.default.nextTick(e,r)}function UG(t,e,r,n){var i;return r===null?i=new RG:typeof r!="string"&&!e.objectMode&&(i=new NG("chunk",["string","Buffer"],r)),i?(Uu(t,i),S.default.nextTick(n,i),!1):!0}Gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&TG(t);return s&&!Zd.isBuffer(t)&&(t=IG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=LG),n.ending?FG(this,r):(s||UG(this,n,t,r))&&(n.pendingcb++,i=VG(this,n,s,t,e,r)),i};Gt.prototype.cork=function(){this._writableState.corked++};Gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&IN(this,t))};Gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new MG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function qG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=Zd.from(e,r)),e}Object.defineProperty(Gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function VG(t,e,r,n,i,s){if(!r){var o=qG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length{"use strict";h();var $G=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};NN.exports=Li;var CN=Lv(),Mv=Rv();Lu()(Li,CN);for(Bv=$G(Mv.prototype),eg=0;eg{h();var rg=io(),Fi=rg.Buffer;function xN(t,e){for(var r in t)e[r]=t[r]}Fi.from&&Fi.alloc&&Fi.allocUnsafe&&Fi.allocUnsafeSlow?ON.exports=rg:(xN(rg,Fv),Fv.Buffer=Da);function Da(t,e,r){return Fi(t,e,r)}Da.prototype=Object.create(Fi.prototype);xN(Fi,Da);Da.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Fi(t,e,r)};Da.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Fi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Da.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fi(t)};Da.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rg.SlowBuffer(t)}});var Vv=D(RN=>{"use strict";h();var qv=DN().Buffer,PN=qv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function XG(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function ZG(t){var e=XG(t);if(typeof e!="string"&&(qv.isEncoding===PN||!PN(t)))throw new Error("Unknown encoding: "+t);return e||t}RN.StringDecoder=Zl;function Zl(t){this.encoding=ZG(t);var e;switch(this.encoding){case"utf16le":this.text=sj,this.end=oj,e=4;break;case"utf8":this.fillLast=rj,e=4;break;case"base64":this.text=aj,this.end=uj,e=3;break;default:this.write=cj,this.end=lj;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=qv.allocUnsafe(e)}Zl.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function ej(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function tj(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function rj(t){var e=this.lastTotal-this.lastNeed,r=tj(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function nj(t,e){var r=ej(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function ij(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function sj(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function oj(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function aj(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function uj(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function cj(t){return t.toString(this.encoding)}function lj(t){return t&&t.length?this.write(t):""}});var ng=D((t0e,LN)=>{"use strict";h();var BN=xa().codes.ERR_STREAM_PREMATURE_CLOSE;function fj(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";h();var ig;function uo(t,e,r){return e=gj(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gj(t){var e=pj(t,"string");return typeof e=="symbol"?e:String(e)}function pj(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var mj=ng(),co=Symbol("lastResolve"),Pa=Symbol("lastReject"),ef=Symbol("error"),sg=Symbol("ended"),Ra=Symbol("lastPromise"),kv=Symbol("handlePromise"),Ba=Symbol("stream");function lo(t,e){return{value:t,done:e}}function yj(t){var e=t[co];if(e!==null){var r=t[Ba].read();r!==null&&(t[Ra]=null,t[co]=null,t[Pa]=null,e(lo(r,!1)))}}function wj(t){S.default.nextTick(yj,t)}function vj(t,e){return function(r,n){t.then(function(){if(e[sg]){r(lo(void 0,!0));return}e[kv](r,n)},n)}}var Aj=Object.getPrototypeOf(function(){}),Ej=Object.setPrototypeOf((ig={get stream(){return this[Ba]},next:function(){var e=this,r=this[ef];if(r!==null)return Promise.reject(r);if(this[sg])return Promise.resolve(lo(void 0,!0));if(this[Ba].destroyed)return new Promise(function(o,u){S.default.nextTick(function(){e[ef]?u(e[ef]):o(lo(void 0,!0))})});var n=this[Ra],i;if(n)i=new Promise(vj(n,this));else{var s=this[Ba].read();if(s!==null)return Promise.resolve(lo(s,!1));i=new Promise(this[kv])}return this[Ra]=i,i}},uo(ig,Symbol.asyncIterator,function(){return this}),uo(ig,"return",function(){var e=this;return new Promise(function(r,n){e[Ba].destroy(null,function(i){if(i){n(i);return}r(lo(void 0,!0))})})}),ig),Aj),bj=function(e){var r,n=Object.create(Ej,(r={},uo(r,Ba,{value:e,writable:!0}),uo(r,co,{value:null,writable:!0}),uo(r,Pa,{value:null,writable:!0}),uo(r,ef,{value:null,writable:!0}),uo(r,sg,{value:e._readableState.endEmitted,writable:!0}),uo(r,kv,{value:function(s,o){var u=n[Ba].read();u?(n[Ra]=null,n[co]=null,n[Pa]=null,s(lo(u,!1))):(n[co]=s,n[Pa]=o)},writable:!0}),r));return n[Ra]=null,mj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Pa];s!==null&&(n[Ra]=null,n[co]=null,n[Pa]=null,s(i)),n[ef]=i;return}var o=n[co];o!==null&&(n[Ra]=null,n[co]=null,n[Pa]=null,o(lo(void 0,!0))),n[sg]=!0}),e.on("readable",wj.bind(null,n)),n};FN.exports=bj});var VN=D((s0e,qN)=>{h();qN.exports=function(){throw new Error("Readable.from is not available in the browser")}});var Lv=D((u0e,YN)=>{"use strict";h();YN.exports=Fe;var qu;Fe.ReadableState=jN;var a0e=Ds().EventEmitter,GN=function(e,r){return e.listeners(r).length},rf=Sv(),og=io().Buffer,Sj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function Ij(t){return og.from(t)}function Tj(t){return og.isBuffer(t)||t instanceof Sj}var Hv=Iv(),Ne;Hv&&Hv.debuglog?Ne=Hv.debuglog("stream"):Ne=function(){};var _j=hN(),$v=Cv(),Cj=Nv(),Nj=Cj.getHighWaterMark,ag=xa().codes,xj=ag.ERR_INVALID_ARG_TYPE,Oj=ag.ERR_STREAM_PUSH_AFTER_EOF,Dj=ag.ERR_METHOD_NOT_IMPLEMENTED,Pj=ag.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Vu,Gv,jv;Lu()(Fe,rf);var tf=$v.errorOrDestroy,zv=["error","close","destroy","pause","resume"];function Rj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function jN(t,e,r){qu=qu||Oa(),t=t||{},typeof r!="boolean"&&(r=e instanceof qu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=Nj(this,t,"readableHighWaterMark",r),this.buffer=new _j,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Vu||(Vu=Vv().StringDecoder),this.decoder=new Vu(t.encoding),this.encoding=t.encoding)}function Fe(t){if(qu=qu||Oa(),!(this instanceof Fe))return new Fe(t);var e=this instanceof qu;this._readableState=new jN(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),rf.call(this)}Object.defineProperty(Fe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Fe.prototype.destroy=$v.destroy;Fe.prototype._undestroy=$v.undestroy;Fe.prototype._destroy=function(t,e){e(t)};Fe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=og.from(t,e),e=""),n=!0),zN(this,t,e,!1,n)};Fe.prototype.unshift=function(t){return zN(this,t,null,!0,!1)};function zN(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Lj(t,s);else{var o;if(i||(o=Bj(s,e)),o)tf(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==og.prototype&&(e=Ij(e)),n)s.endEmitted?tf(t,new Pj):Qv(t,s,e,!0);else if(s.ended)tf(t,new Oj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?Qv(t,s,e,!1):Wv(t,s)):Qv(t,s,e,!1)}else n||(s.reading=!1,Wv(t,s))}return!s.ended&&(s.length=kN?t=kN:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function HN(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=Mj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}Fe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Kv(this):ug(this),null;if(t=HN(t,e),t===0&&e.ended)return e.length===0&&Kv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=WN(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Kv(this)),i!==null&&this.emit("data",i),i};function Lj(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?ug(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,QN(t)))}}function ug(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,S.default.nextTick(QN,t))}function QN(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,Yv(t)}function Wv(t,e){e.readingMore||(e.readingMore=!0,S.default.nextTick(Fj,t,e))}function Fj(t,e){for(;!e.reading&&!e.ended&&(e.length1&&$N(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function w(B){Ne("onerror",B),x(),t.removeListener("error",w),GN(t,"error")===0&&tf(t,B)}Rj(t,"error",w);function A(){t.removeListener("finish",T),x()}t.once("close",A);function T(){Ne("onfinish"),t.removeListener("close",A),x()}t.once("finish",T);function x(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Uj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&GN(t,"data")&&(r.flowing=!0,Yv(t))}}Fe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?ug(this):n.reading||S.default.nextTick(qj,this)),r};Fe.prototype.addListener=Fe.prototype.on;Fe.prototype.removeListener=function(t,e){var r=rf.prototype.removeListener.call(this,t,e);return t==="readable"&&S.default.nextTick(KN,this),r};Fe.prototype.removeAllListeners=function(t){var e=rf.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&S.default.nextTick(KN,this),e};function KN(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function qj(t){Ne("readable nexttick read 0"),t.read(0)}Fe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Vj(this,t)),t.paused=!1,this};function Vj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,S.default.nextTick(kj,t,e))}function kj(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),Yv(t),e.flowing&&!e.reading&&t.read(0)}Fe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Yv(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}Fe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var u=e.push(o);u||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(u){return function(){return t[u].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Kv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,S.default.nextTick(Hj,e,t))}function Hj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(Fe.from=function(t,e){return jv===void 0&&(jv=VN()),jv(Fe,t,e)});function $N(t,e){for(var r=0,n=t.length;r{"use strict";h();XN.exports=Ps;var cg=xa().codes,Gj=cg.ERR_METHOD_NOT_IMPLEMENTED,jj=cg.ERR_MULTIPLE_CALLBACK,zj=cg.ERR_TRANSFORM_ALREADY_TRANSFORMING,Qj=cg.ERR_TRANSFORM_WITH_LENGTH_0,lg=Oa();Lu()(Ps,lg);function Kj(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new jj);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";h();ex.exports=nf;var ZN=Jv();Lu()(nf,ZN);function nf(t){if(!(this instanceof nf))return new nf(t);ZN.call(this,t)}nf.prototype._transform=function(t,e,r){r(null,t)}});var ox=D((g0e,sx)=>{"use strict";h();var Xv;function $j(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var ix=xa().codes,Yj=ix.ERR_MISSING_ARGS,Jj=ix.ERR_STREAM_DESTROYED;function rx(t){if(t)throw t}function Xj(t){return t.setHeader&&typeof t.abort=="function"}function Zj(t,e,r,n){n=$j(n);var i=!1;t.on("close",function(){i=!0}),Xv===void 0&&(Xv=ng()),Xv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Xj(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new Jj("pipe"))}}}function nx(t){t()}function ez(t,e){return t.pipe(e)}function tz(t){return!t.length||typeof t[t.length-1]!="function"?rx:t.pop()}function rz(){for(var t=arguments.length,e=new Array(t),r=0;r0;return Zj(o,a,c,function(f){i||(i=f),f&&s.forEach(nx),!a&&(s.forEach(nx),n(i))})});return e.reduce(ez)}sx.exports=rz});var Zv=D((Pn,ax)=>{h();Pn=ax.exports=Lv();Pn.Stream=Pn;Pn.Readable=Pn;Pn.Writable=Rv();Pn.Duplex=Oa();Pn.Transform=Jv();Pn.PassThrough=tx();Pn.finished=ng();Pn.pipeline=ox()});var lx=D((y0e,cx)=>{h();var{Transform:nz}=Zv();cx.exports=t=>class ux extends nz{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new ux(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var dx=D((v0e,hx)=>{h();var{Transform:iz}=Zv();hx.exports=t=>class fx extends iz{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new fx(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var px=D((E0e,gx)=>{h();var sz=lx(),oz=dx();gx.exports=function(t){let e=sz(t),r=oz(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var wx=D(yx=>{h();var mx=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];yx.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],u=t[5]^t[15]^t[25]^t[35]^t[45],a=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],w=f^(i<<1|s>>>31),A=d^(s<<1|i>>>31),T=t[0]^w,x=t[1]^A,B=t[10]^w,V=t[11]^A,U=t[20]^w,Q=t[21]^A,L=t[30]^w,k=t[31]^A,H=t[40]^w,q=t[41]^A;w=r^(o<<1|u>>>31),A=n^(u<<1|o>>>31);let v=t[2]^w,C=t[3]^A,P=t[12]^w,F=t[13]^A,R=t[22]^w,l=t[23]^A,g=t[32]^w,y=t[33]^A,E=t[42]^w,I=t[43]^A;w=i^(a<<1|c>>>31),A=s^(c<<1|a>>>31);let _=t[4]^w,M=t[5]^A,N=t[14]^w,m=t[15]^A,O=t[24]^w,Y=t[25]^A,$=t[34]^w,b=t[35]^A,j=t[44]^w,z=t[45]^A;w=o^(f<<1|d>>>31),A=u^(d<<1|f>>>31);let W=t[6]^w,ie=t[7]^A,te=t[16]^w,ee=t[17]^A,se=t[26]^w,oe=t[27]^A,J=t[36]^w,ue=t[37]^A,wt=t[46]^w,vt=t[47]^A;w=a^(r<<1|n>>>31),A=c^(n<<1|r>>>31);let Ni=t[8]^w,At=t[9]^A,Et=t[18]^w,xi=t[19]^A,bt=t[28]^w,St=t[29]^A,Oi=t[38]^w,It=t[39]^A,Tt=t[48]^w,Di=t[49]^A,Qe=T,Ke=x,ri=V<<4|B>>>28,We=B<<4|V>>>28,$e=U<<3|Q>>>29,ni=Q<<3|U>>>29,Ye=k<<9|L>>>23,Je=L<<9|k>>>23,ii=H<<18|q>>>14,Xe=q<<18|H>>>14,Ze=v<<1|C>>>31,si=C<<1|v>>>31,et=F<<12|P>>>20,tt=P<<12|F>>>20,oi=R<<10|l>>>22,rt=l<<10|R>>>22,nt=y<<13|g>>>19,ai=g<<13|y>>>19,it=E<<2|I>>>30,st=I<<2|E>>>30,ui=M<<30|_>>>2,ot=_<<30|M>>>2,at=N<<6|m>>>26,ci=m<<6|N>>>26,ut=Y<<11|O>>>21,ct=O<<11|Y>>>21,li=$<<15|b>>>17,lt=b<<15|$>>>17,ft=z<<29|j>>>3,fi=j<<29|z>>>3,ht=W<<28|ie>>>4,dt=ie<<28|W>>>4,hi=ee<<23|te>>>9,gt=te<<23|ee>>>9,pt=se<<25|oe>>>7,vn=oe<<25|se>>>7,An=J<<21|ue>>>11,En=ue<<21|J>>>11,bn=vt<<24|wt>>>8,Sn=wt<<24|vt>>>8,In=Ni<<27|At>>>5,ha=At<<27|Ni>>>5,da=Et<<20|xi>>>12,ga=xi<<20|Et>>>12,pa=St<<7|bt>>>25,ma=bt<<7|St>>>25,ya=Oi<<8|It>>>24,wa=It<<8|Oi>>>24,va=Tt<<14|Di>>>18,Aa=Di<<14|Tt>>>18;t[0]=Qe^~et&ut,t[1]=Ke^~tt&ct,t[10]=ht^~da&$e,t[11]=dt^~ga&ni,t[20]=Ze^~at&pt,t[21]=si^~ci&vn,t[30]=In^~ri&oi,t[31]=ha^~We&rt,t[40]=ui^~hi&pa,t[41]=ot^~gt&ma,t[2]=et^~ut&An,t[3]=tt^~ct&En,t[12]=da^~$e&nt,t[13]=ga^~ni&ai,t[22]=at^~pt&ya,t[23]=ci^~vn&wa,t[32]=ri^~oi&li,t[33]=We^~rt<,t[42]=hi^~pa&Ye,t[43]=gt^~ma&Je,t[4]=ut^~An&va,t[5]=ct^~En&Aa,t[14]=$e^~nt&ft,t[15]=ni^~ai&fi,t[24]=pt^~ya&ii,t[25]=vn^~wa&Xe,t[34]=oi^~li&bn,t[35]=rt^~lt&Sn,t[44]=pa^~Ye&it,t[45]=ma^~Je&st,t[6]=An^~va&Qe,t[7]=En^~Aa&Ke,t[16]=nt^~ft&ht,t[17]=ai^~fi&dt,t[26]=ya^~ii&Ze,t[27]=wa^~Xe&si,t[36]=li^~bn&In,t[37]=lt^~Sn&ha,t[46]=Ye^~it&ui,t[47]=Je^~st&ot,t[8]=va^~Qe&et,t[9]=Aa^~Ke&tt,t[18]=ft^~ht&da,t[19]=fi^~dt&ga,t[28]=ii^~Ze&at,t[29]=Xe^~si&ci,t[38]=bn^~In&ri,t[39]=Sn^~ha&We,t[48]=it^~ui&hi,t[49]=st^~ot>,t[0]^=mx[e*2],t[1]^=mx[e*2+1]}}});var Ax=D((T0e,vx)=>{h();var fg=wx();function ku(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}ku.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};ku.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(fg.p1600(this.state),this.count=0);return e};ku.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};vx.exports=ku});var sf=D((C0e,Ex)=>{h();Ex.exports=px()(Ax())});var Ve=D(Kr=>{"use strict";h();var az=Kr&&Kr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),uz=Kr&&Kr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bx=Kr&&Kr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&az(e,t,r);return uz(e,t),e},cz=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.AddressComputer=Kr.Address=void 0;var Hu=bx(vv()),lz=cz((rr(),_e(fr))),eA=hr(),Gu=bx(Ie()),fz=Kd(),hz=sf(),of="erd",hg=32,dz="0".repeat(16),dg=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(ArrayBuffer.isView(e))return t.fromBuffer(p.Buffer.from(e));if(typeof e=="string")return t.fromString(e);throw new Gu.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=t.empty();return r.valueHex=e,r}static fromBuffer(e){if(e.length!=hg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==hg}static fromHex(e){if(!t.isValidHex(e))throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t("")}static fromBech32(e){let r;try{r=Hu.decode(e)}catch(s){throw new Gu.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=of)throw new Gu.ErrAddressBadHrp(of,n);let i=p.Buffer.from(Hu.fromWords(r.words));if(i.length!=hg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=Hu.decodeUnsafe(e),n=r?.prefix,i=r?p.Buffer.from(Hu.fromWords(r.words)):void 0;return!(n!==of||i?.length!==hg)}hex(){return this.toHex()}toHex(){return this.isEmpty()?"":this.valueHex}bech32(){return this.toBech32()}toBech32(){if(this.isEmpty())return"";let e=Hu.toWords(this.pubkey());return Hu.encode(of,e)}pubkey(){return this.getPublicKey()}getPublicKey(){return this.isEmpty()?p.Buffer.from([]):p.Buffer.from(this.valueHex,"hex")}getHrp(){return of}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.toBech32()}toJSON(){return{bech32:this.toBech32(),pubkey:this.toHex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.isSmartContract()}isSmartContract(){return this.toHex().startsWith(dz)}};Kr.Address=dg;var tA=class{constructor(e){this.numberOfShardsWithoutMeta=e||eA.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META}computeContractAddress(e,r){let n=p.Buffer.alloc(8,0),i=e.getPublicKey(),s=i.slice(30),o=p.Buffer.alloc(8),u=new lz.default(r.toString()),a=fz.bigIntToBuffer(u);o.write(a.reverse().toString("hex"),"hex");let c=p.Buffer.concat([i,o]),f=hz("keccak256").update(c).digest(),d=p.Buffer.from(eA.WasmVirtualMachine,"hex"),w=p.Buffer.concat([n,d,f.slice(10,30),s]);return new dg(w)}getShardOfAddress(e){return this.getShardOfPubkey(e.getPublicKey(),this.numberOfShardsWithoutMeta)}getShardOfPubkey(e,r){let n=parseInt("11",2),i=parseInt("01",2),s=e[31];if(this.isPubkeyOfMetachain(e))return eA.METACHAIN_ID;let o=s&n;return o>r-1&&(o=s&i),o}isPubkeyOfMetachain(e){let r=p.Buffer.from([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n=p.Buffer.from(e).slice(0,r.length);return!!(r.equals(n)||p.Buffer.alloc(32).equals(p.Buffer.from(e)))}};Kr.AddressComputer=tA});var Rn=D(Ft=>{"use strict";h();var gz=Ft&&Ft.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),pz=Ft&&Ft.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),mz=Ft&&Ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&gz(e,t,r);return pz(e,t),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.isEmpty=Ft.guardEmpty=Ft.guardNotEmpty=Ft.guardLength=Ft.guardSameLength=Ft.guardValueIsSetWithMessage=Ft.guardValueIsSet=Ft.guardTrue=void 0;var ju=mz(Ie());function yz(t,e){if(!t)throw new ju.ErrInvariantFailed(`[<${e}>] isn't true`)}Ft.guardTrue=yz;function wz(t,e){Sx(`${t} isn't set (null or undefined)`,e)}Ft.guardValueIsSet=wz;function Sx(t,e){if(e==null||e===void 0)throw new ju.ErrInvariantFailed(t)}Ft.guardValueIsSetWithMessage=Sx;function vz(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new ju.ErrInvariantFailed("arrays do not have the same length")}Ft.guardSameLength=vz;function Az(t,e){let r=t.length||0;if(r!=e)throw new ju.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}Ft.guardLength=Az;function Ez(t,e){if(rA(t))throw new ju.ErrInvariantFailed(`${e} is empty`)}Ft.guardNotEmpty=Ez;function bz(t,e){if(!rA(t))throw new ju.ErrInvariantFailed(`${e} is not empty`)}Ft.guardEmpty=bz;function rA(t){return t.isEmpty?t.isEmpty():t.length===0}Ft.isEmpty=rA});var Ix=D(gg=>{"use strict";h();Object.defineProperty(gg,"__esModule",{value:!0});gg.TypeFormula=void 0;var nA=class{constructor(e,r){this.name=e,this.typeParameters=r}toString(){if(this.typeParameters.length>0){let e=this.typeParameters.map(r=>r.toString()).join(", ");return`${this.name}<${e}>`}else return this.name}};gg.TypeFormula=nA});var Tx=D(pg=>{"use strict";h();Object.defineProperty(pg,"__esModule",{value:!0});pg.TypeFormulaParser=void 0;var af=Ix(),Ui=class t{parseExpression(e){e=e.trim();let r=this.tokenizeExpression(e).filter(s=>s!==t.COMMA),n=[];for(let s of r)if(this.isPunctuation(s))if(this.isEndOfTypeParameters(s)){let o=this.acquireTypeWithParameters(n);n.push(o)}else if(this.isBeginningOfTypeParameters(s))n.push(s);else throw new Error(`Unexpected token (punctuation): ${s}`);else n.push(s);if(n.length!==1)throw new Error(`Unexpected stack length at end of parsing: ${n.length}`);if(t.PUNCTUATION.includes(n[0]))throw new Error("Unexpected root element.");let i=n[0];if(i instanceof af.TypeFormula)return i;if(typeof i=="string")return new af.TypeFormula(i,[]);throw new Error(`Unexpected item on stack: ${i}`)}tokenizeExpression(e){let r=[],n="";for(let i of e)this.isPunctuation(i)?(n&&(r.push(n.trim()),n=""),r.push(i)):n+=i;return n&&r.push(n.trim()),r}acquireTypeWithParameters(e){let r=this.acquireTypeParameters(e),n=e.pop();return new af.TypeFormula(n,r.reverse())}acquireTypeParameters(e){let r=[];for(;;){let n=e.pop();if(n===void 0)throw new Error("Badly specified type parameters");if(this.isBeginningOfTypeParameters(n))break;if(n instanceof af.TypeFormula)r.push(n);else if(typeof n=="string")r.push(new af.TypeFormula(n,[]));else throw new Error(`Unexpected type parameter object in stack: ${n}`)}return r}isPunctuation(e){return t.PUNCTUATION.includes(e)}isEndOfTypeParameters(e){return e===t.END_TYPE_PARAMETERS}isBeginningOfTypeParameters(e){return e===t.BEGIN_TYPE_PARAMETERS}};pg.TypeFormulaParser=Ui;Ui.BEGIN_TYPE_PARAMETERS="<";Ui.END_TYPE_PARAMETERS=">";Ui.COMMA=",";Ui.PUNCTUATION=[Ui.COMMA,Ui.BEGIN_TYPE_PARAMETERS,Ui.END_TYPE_PARAMETERS]});var _x=D(mg=>{"use strict";h();Object.defineProperty(mg,"__esModule",{value:!0});mg.getJavascriptPrototypesInHierarchy=void 0;function Sz(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}mg.getJavascriptPrototypesInHierarchy=Sz});var sr=D(ir=>{"use strict";h();Object.defineProperty(ir,"__esModule",{value:!0});ir.NullType=ir.TypePlaceholder=ir.isTyped=ir.PrimitiveValue=ir.TypedValue=ir.CustomType=ir.PrimitiveType=ir.TypeCardinality=ir.Type=void 0;var iA=_x(),Cx=Rn(),fo=class t{constructor(e,r=[],n=uf.fixed(1)){Cx.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return iA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return Cx.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return iA.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};ir.Type=fo;fo.ClassName="Type";var uf=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};ir.TypeCardinality=uf;uf.MaxCardinality=4096;var yg=class t extends fo{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveType=yg;yg.ClassName="PrimitiveType";var wg=class t extends fo{getClassName(){return t.ClassName}};ir.CustomType=wg;wg.ClassName="CustomType";var cf=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return iA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};ir.TypedValue=cf;cf.ClassName="TypedValue";var vg=class t extends cf{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveValue=vg;vg.ClassName="PrimitiveValue";function Iz(t){return t.belongsToTypesystem!==void 0}ir.isTyped=Iz;var Ag=class t extends fo{constructor(){super("...")}getClassName(){return t.ClassName}};ir.TypePlaceholder=Ag;Ag.ClassName="TypePlaceholder";var Eg=class t extends fo{constructor(){super("?")}getClassName(){return t.ClassName}};ir.NullType=Eg;Eg.ClassName="NullType"});var lf=D(bg=>{"use strict";h();Object.defineProperty(bg,"__esModule",{value:!0});bg.TypeExpressionParser=void 0;var Tz=Tx(),_z=Ie(),Cz=sr(),sA=class{constructor(){this.backingTypeFormulaParser=new Tz.TypeFormulaParser}parse(e){try{return this.doParse(e)}catch(r){throw new _z.ErrTypingSystem(`Failed to parse type expression: ${e}. Error: ${r}`)}}doParse(e){let r=this.backingTypeFormulaParser.parseExpression(e);return this.typeFormulaToType(r)}typeFormulaToType(e){let r=e.typeParameters.map(n=>this.typeFormulaToType(n));return new Cz.Type(e.name,r)}};bg.TypeExpressionParser=sA});var aA=D(ho=>{"use strict";h();Object.defineProperty(ho,"__esModule",{value:!0});ho.EndpointParameterDefinition=ho.EndpointModifiers=ho.EndpointDefinition=void 0;var Nz=lf(),Nx="?",xz="N / A",oA=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?Nx:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>ff.fromJSON(s)),n=e.outputs.map(s=>ff.fromJSON(s)),i=new Sg(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};ho.EndpointDefinition=oA;var Sg=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};ho.EndpointModifiers=Sg;var ff=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new Nz.TypeExpressionParser().parse(e.type);return new t(e.name||Nx,e.description||xz,r)}};ho.EndpointParameterDefinition=ff});var zu=D(Wr=>{"use strict";h();var Oz=Wr&&Wr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dz=Wr&&Wr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pz=Wr&&Wr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Oz(e,t,r);return Dz(e,t),e};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Fields=Wr.Field=Wr.FieldDefinition=void 0;var uA=Pz(Ie()),Rz=lf(),cA=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new Rz.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};Wr.FieldDefinition=cA;var lA=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new uA.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new uA.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};Wr.Field=lA;var fA=class{static checkTyping(e,r){if(e.length!=r.length)throw new uA.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";h();Object.defineProperty(go,"__esModule",{value:!0});go.EnumValue=go.EnumVariantDefinition=go.EnumType=void 0;var Bz=Ie(),hA=Rn(),Ig=zu(),Ox=sr(),xx=256,Tg=class t extends Ox.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>_g.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>({...n,discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return hA.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return hA.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};go.EnumType=Tg;Tg.ClassName="EnumType";var _g=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],hA.guardTrue(rIg.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Ig.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};go.EnumVariantDefinition=_g;var Cg=class t extends Ox.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();Ig.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=Ig.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Bz.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};go.EnumValue=Cg;Cg.ClassName="EnumValue"});var Px=D(Qu=>{"use strict";h();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.EventTopicDefinition=Qu.EventDefinition=void 0;var Mz=lf(),Dx="?",dA=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?Dx:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>Ng.fromJSON(n));return new t(e.identifier,r)}};Qu.EventDefinition=dA;var Ng=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Mz.TypeExpressionParser().parse(e.type);return new t({name:e.name||Dx,type:r,indexed:e.indexed})}};Qu.EventTopicDefinition=Ng});var Wu=D(Ku=>{"use strict";h();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.Struct=Ku.StructType=void 0;var Lz=Ie(),xg=zu(),Rx=sr(),Og=class t extends Rx.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>xg.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return xg.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Ku.StructType=Og;Og.ClassName="StructType";var Dg=class t extends Rx.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();xg.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Lz.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return xg.Fields.equals(r,n)}};Ku.Struct=Dg;Dg.ClassName="Struct"});var Yu=D($u=>{"use strict";h();Object.defineProperty($u,"__esModule",{value:!0});$u.AddressValue=$u.AddressType=void 0;var Fz=Ve(),Bx=sr(),df=class t extends Bx.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};$u.AddressType=df;df.ClassName="AddressType";var Pg=class t extends Bx.PrimitiveValue{constructor(e){super(new df),this.value=new Fz.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};$u.AddressValue=Pg;Pg.ClassName="AddressValue"});var Bg=D(Ju=>{"use strict";h();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.OptionalValue=Ju.OptionalType=void 0;var Uz=Rn(),gf=sr(),pf=class t extends gf.Type{constructor(e){super("Optional",[e],gf.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(gf.NullType.ClassName);return r||n}};Ju.OptionalType=pf;pf.ClassName="OptionalType";var Rg=class t extends gf.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new pf(new gf.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return Uz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};Ju.OptionalValue=Rg;Rg.ClassName="OptionalValue"});var yf=D(Xu=>{"use strict";h();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.BooleanValue=Xu.BooleanType=void 0;var Mx=sr(),mf=class t extends Mx.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};Xu.BooleanType=mf;mf.ClassName="BooleanType";var Mg=class t extends Mx.PrimitiveValue{constructor(e){super(new mf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};Xu.BooleanValue=Mg;Mg.ClassName="BooleanValue"});var po=D(Zu=>{"use strict";h();Object.defineProperty(Zu,"__esModule",{value:!0});Zu.BytesValue=Zu.BytesType=void 0;var Lx=sr(),wf=class t extends Lx.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Zu.BytesType=wf;wf.ClassName="BytesType";var Lg=class t extends Lx.PrimitiveValue{constructor(e){super(new wf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=p.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=p.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Zu.BytesValue=Lg;Lg.ClassName="BytesValue"});var Ux=D(ec=>{"use strict";h();Object.defineProperty(ec,"__esModule",{value:!0});ec.CodeMetadataValue=ec.CodeMetadataType=void 0;var Fx=sr(),Fg=class extends Fx.PrimitiveType{constructor(){super("CodeMetadata")}};ec.CodeMetadataType=Fg;var gA=class extends Fx.PrimitiveValue{constructor(e){super(new Fg),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};ec.CodeMetadataValue=gA});var qg=D(tc=>{"use strict";h();Object.defineProperty(tc,"__esModule",{value:!0});tc.CompositeValue=tc.CompositeType=void 0;var qz=Rn(),pA=sr(),vf=class t extends pA.Type{constructor(...e){super("Composite",e,pA.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};tc.CompositeType=vf;vf.ClassName="CompositeType";var Ug=class t extends pA.TypedValue{constructor(e,r){super(e),qz.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new vf(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();Object.defineProperty(Vg,"__esModule",{value:!0});Vg.CollectionOfTypedValues=void 0;var mA=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";h();Object.defineProperty(qi,"__esModule",{value:!0});qi.List=qi.OptionValue=qi.ListType=qi.OptionType=void 0;var Vz=Rn(),kz=yA(),La=sr(),Ma=class t extends La.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(La.NullType.ClassName);return r||n}};qi.OptionType=Ma;Ma.ClassName="OptionType";var Af=class t extends La.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};qi.ListType=Af;Af.ClassName="ListType";var kg=class t extends La.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new Ma(new La.NullType);return new t(e)}static newMissingTyped(e){return new t(new Ma(e))}static newProvided(e){let r=new Ma(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return Vz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};qi.OptionValue=kg;kg.ClassName="OptionValue";var Hg=class t extends La.TypedValue{constructor(e,r){super(e),this.backingCollection=new kz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new La.TypePlaceholder,[]);let r=e[0].getType(),n=new Af(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};qi.List=Hg;Hg.ClassName="List"});var zg=D(rc=>{"use strict";h();Object.defineProperty(rc,"__esModule",{value:!0});rc.ArrayVec=rc.ArrayVecType=void 0;var qx=Rn(),Hz=yA(),Vx=sr(),Gg=class t extends Vx.Type{constructor(e,r){super("Array",[r]),qx.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};rc.ArrayVecType=Gg;Gg.ClassName="ArrayVecType";var jg=class t extends Vx.TypedValue{constructor(e,r){super(e),qx.guardLength(r,e.length),this.backingCollection=new Hz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};rc.ArrayVec=jg;jg.ClassName="ArrayVec"});var Sf=D(nc=>{"use strict";h();Object.defineProperty(nc,"__esModule",{value:!0});nc.H256Value=nc.H256Type=void 0;var kx=sr(),bf=class t extends kx.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};nc.H256Type=bf;bf.ClassName="H256Type";var Qg=class t extends kx.PrimitiveValue{constructor(e){super(new bf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};nc.H256Value=Qg;Qg.ClassName="H256Value"});var Wg=D(ic=>{"use strict";h();Object.defineProperty(ic,"__esModule",{value:!0});ic.NothingValue=ic.NothingType=void 0;var Hx=sr(),If=class t extends Hx.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};ic.NothingType=If;If.ClassName="NothingType";var Kg=class t extends Hx.PrimitiveValue{constructor(){super(new If)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};ic.NothingValue=Kg;Kg.ClassName="NothingValue"});var Mf=D(Ee=>{"use strict";h();var Gz=Ee&&Ee.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),jz=Ee&&Ee.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zz=Ee&&Ee.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Gz(e,t,r);return jz(e,t),e},Qz=Ee&&Ee.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.BigIntValue=Ee.BigUIntValue=Ee.I64Value=Ee.U64Value=Ee.I32Value=Ee.U32Value=Ee.I16Value=Ee.U16Value=Ee.I8Value=Ee.U8Value=Ee.NumericalValue=Ee.BigIntType=Ee.BigUIntType=Ee.I64Type=Ee.U64Type=Ee.I32Type=Ee.U32Type=Ee.I16Type=Ee.U16Type=Ee.I8Type=Ee.U8Type=Ee.NumericalType=void 0;var Kz=Qz((rr(),_e(fr))),Gx=zz(Ie()),jx=sr(),$r=class t extends jx.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ee.NumericalType=$r;$r.ClassName="NumericalType";var Tf=class t extends $r{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ee.U8Type=Tf;Tf.ClassName="U8Type";var _f=class t extends $r{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ee.I8Type=_f;_f.ClassName="I8Type";var Cf=class t extends $r{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ee.U16Type=Cf;Cf.ClassName="U16Type";var Nf=class t extends $r{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ee.I16Type=Nf;Nf.ClassName="I16Type";var xf=class t extends $r{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ee.U32Type=xf;xf.ClassName="U32Type";var Of=class t extends $r{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ee.I32Type=Of;Of.ClassName="I32Type";var Df=class t extends $r{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ee.U64Type=Df;Df.ClassName="U64Type";var Pf=class t extends $r{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ee.I64Type=Pf;Pf.ClassName="I64Type";var Rf=class t extends $r{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ee.BigUIntType=Rf;Rf.ClassName="BigUIntType";var Bf=class t extends $r{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ee.BigIntType=Bf;Bf.ClassName="BigIntType";var Yr=class t extends jx.PrimitiveValue{constructor(e,r){if(super(e),typeof r=="bigint"&&(r=r.toString()),this.value=new Kz.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new Gx.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new Gx.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ee.NumericalValue=Yr;Yr.ClassName="NumericalValue";var $g=class t extends Yr{constructor(e){super(new Tf,e)}getClassName(){return t.ClassName}};Ee.U8Value=$g;$g.ClassName="U8Value";var Yg=class t extends Yr{constructor(e){super(new _f,e)}getClassName(){return t.ClassName}};Ee.I8Value=Yg;Yg.ClassName="I8Value";var Jg=class t extends Yr{constructor(e){super(new Cf,e)}getClassName(){return t.ClassName}};Ee.U16Value=Jg;Jg.ClassName="U16Value";var Xg=class t extends Yr{constructor(e){super(new Nf,e)}getClassName(){return t.ClassName}};Ee.I16Value=Xg;Xg.ClassName="I16Value";var Zg=class t extends Yr{constructor(e){super(new xf,e)}getClassName(){return t.ClassName}};Ee.U32Value=Zg;Zg.ClassName="U32Value";var ep=class t extends Yr{constructor(e){super(new Of,e)}getClassName(){return t.ClassName}};Ee.I32Value=ep;ep.ClassName="I32Value";var tp=class t extends Yr{constructor(e){super(new Df,e)}getClassName(){return t.ClassName}};Ee.U64Value=tp;tp.ClassName="U64Value";var rp=class t extends Yr{constructor(e){super(new Pf,e)}getClassName(){return t.ClassName}};Ee.I64Value=rp;rp.ClassName="I64Value";var np=class t extends Yr{constructor(e){super(new Rf,e)}getClassName(){return t.ClassName}};Ee.BigUIntValue=np;np.ClassName="BigUIntValue";var ip=class t extends Yr{constructor(e){super(new Bf,e)}getClassName(){return t.ClassName}};Ee.BigIntValue=ip;ip.ClassName="BigIntValue"});var op=D(sc=>{"use strict";h();Object.defineProperty(sc,"__esModule",{value:!0});sc.StringValue=sc.StringType=void 0;var zx=sr(),Lf=class t extends zx.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};sc.StringType=Lf;Lf.ClassName="StringType";var sp=class t extends zx.PrimitiveValue{constructor(e){super(new Lf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=p.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};sc.StringValue=sp;sp.ClassName="StringValue"});var ac=D(oc=>{"use strict";h();Object.defineProperty(oc,"__esModule",{value:!0});oc.TokenIdentifierValue=oc.TokenIdentifierType=void 0;var Qx=sr(),Wz="EGLD",Ff=class t extends Qx.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};oc.TokenIdentifierType=Ff;Ff.ClassName="TokenIdentifierType";var ap=class t extends Qx.PrimitiveValue{constructor(e){super(new Ff),this.value=e}static egld(){return new t(Wz)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};oc.TokenIdentifierValue=ap;ap.ClassName="TokenIdentifierValue"});var cp=D(Bn=>{"use strict";h();var $z=Bn&&Bn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Yz=Bn&&Bn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Jz=Bn&&Bn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$z(e,t,r);return Yz(e,t),e};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Tuple=Bn.TupleType=void 0;var Xz=Jz(Ie()),Kx=zu(),Wx=Wu(),Uf=class t extends Wx.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new Kx.FieldDefinition($x(i),"anonymous tuple field",n))}};Bn.TupleType=Uf;Uf.ClassName="TupleType";function $x(t){return`field${t}`}var up=class t extends Wx.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Xz.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new Uf(...r),i=e.map((s,o)=>new Kx.Field(s,$x(o)));return new t(n,i)}};Bn.Tuple=up;up.ClassName="Tuple"});var hp=D(mo=>{"use strict";h();Object.defineProperty(mo,"__esModule",{value:!0});mo.VariadicValue=mo.CountedVariadicType=mo.VariadicType=void 0;var uc=sr(),Fa=class t extends uc.Type{constructor(e,r=!1){super("Variadic",[e],uc.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};mo.VariadicType=Fa;Fa.ClassName="VariadicType";var lp=class extends uc.Type{constructor(e){super("Variadic",[e],uc.TypeCardinality.variable())}getClassName(){return Fa.ClassName}};mo.CountedVariadicType=lp;lp.ClassName="VariadicType";var fp=class t extends uc.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Fa(new uc.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Fa(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();var Zz=ki&&ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),eQ=ki&&ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tQ=ki&&ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zz(e,t,r);return eQ(e,t),e};Object.defineProperty(ki,"__esModule",{value:!0});ki.TypeMapper=void 0;var Yx=tQ(Ie()),rQ=Yu(),wA=Bg(),nQ=yf(),iQ=po(),sQ=Ux(),dp=qg(),vA=hf(),oQ=zu(),Jx=Ef(),Vi=zg(),aQ=Sf(),Xx=Wg(),Mn=Mf(),uQ=op(),Zx=Wu(),e6=ac(),yo=cp(),gp=hp(),AA=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new Jx.OptionType(r[0])],["List",(...r)=>new Jx.ListType(r[0])],["VarArgs",(...r)=>new gp.VariadicType(r[0])],["MultiResultVec",(...r)=>new gp.VariadicType(r[0])],["variadic",(...r)=>new gp.VariadicType(r[0])],["counted-variadic",(...r)=>new gp.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new wA.OptionalType(r[0])],["optional",(...r)=>new wA.OptionalType(r[0])],["OptionalResult",(...r)=>new wA.OptionalType(r[0])],["multi",(...r)=>new dp.CompositeType(...r)],["MultiArg",(...r)=>new dp.CompositeType(...r)],["MultiResult",(...r)=>new dp.CompositeType(...r)],["multi",(...r)=>new dp.CompositeType(...r)],["tuple",(...r)=>new yo.TupleType(...r)],["tuple2",(...r)=>new yo.TupleType(...r)],["tuple3",(...r)=>new yo.TupleType(...r)],["tuple4",(...r)=>new yo.TupleType(...r)],["tuple5",(...r)=>new yo.TupleType(...r)],["tuple6",(...r)=>new yo.TupleType(...r)],["tuple7",(...r)=>new yo.TupleType(...r)],["tuple8",(...r)=>new yo.TupleType(...r)],["array2",(...r)=>new Vi.ArrayVecType(2,r[0])],["array8",(...r)=>new Vi.ArrayVecType(8,r[0])],["array16",(...r)=>new Vi.ArrayVecType(16,r[0])],["array20",(...r)=>new Vi.ArrayVecType(20,r[0])],["array32",(...r)=>new Vi.ArrayVecType(32,r[0])],["array46",(...r)=>new Vi.ArrayVecType(46,r[0])],["array48",(...r)=>new Vi.ArrayVecType(48,r[0])],["array64",(...r)=>new Vi.ArrayVecType(64,r[0])],["array128",(...r)=>new Vi.ArrayVecType(128,r[0])],["array256",(...r)=>new Vi.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new Mn.U8Type],["u16",new Mn.U16Type],["u32",new Mn.U32Type],["u64",new Mn.U64Type],["U64",new Mn.U64Type],["BigUint",new Mn.BigUIntType],["i8",new Mn.I8Type],["i16",new Mn.I16Type],["i32",new Mn.I32Type],["i64",new Mn.I64Type],["Bigint",new Mn.BigIntType],["BigInt",new Mn.BigIntType],["bool",new nQ.BooleanType],["bytes",new iQ.BytesType],["Address",new rQ.AddressType],["H256",new aQ.H256Type],["utf-8 string",new uQ.StringType],["TokenIdentifier",new e6.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new e6.TokenIdentifierType],["CodeMetadata",new sQ.CodeMetadataType],["nothing",new Xx.NothingType],["AsyncCall",new Xx.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new Yx.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(vA.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(Zx.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new Zx.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new vA.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new vA.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new oQ.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new Yx.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};ki.TypeMapper=AA});var s6=D(Hi=>{"use strict";h();var cQ=Hi&&Hi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),lQ=Hi&&Hi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),fQ=Hi&&Hi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cQ(e,t,r);return lQ(e,t),e};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.AbiRegistry=void 0;var t6=fQ(Ie()),qf=Rn(),Vf=aA(),r6=hf(),bA=Px(),n6=Wu(),hQ=EA(),dQ="?",SA=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||dQ,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],u=Vf.EndpointDefinition.fromJSON({name:"constructor",...n}),a=i.map(A=>Vf.EndpointDefinition.fromJSON(A)),c=[];for(let A in s){let T=s[A];if(T.type=="struct")c.push(n6.StructType.fromJSON({name:A,fields:T.fields}));else if(T.type=="enum"||T.type=="explicit-enum")c.push(r6.EnumType.fromJSON({name:A,variants:T.variants}));else throw new t6.ErrTypingSystem(`Cannot handle custom type: ${A}`)}let f=o.map(A=>bA.EventDefinition.fromJSON(A));return new t({name:r,constructorDefinition:u,endpoints:a,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return qf.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(n6.StructType.ClassName));return qf.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(r6.EnumType.ClassName));return qf.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return qf.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return qf.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new hQ.TypeMapper([]),r=[];for(let u of this.customTypes)this.mapCustomTypeDepthFirst(u,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new t6.ErrTypingSystem("Did not re-map all custom types");let n=i6(this.constructorDefinition,e),i=[];for(let u of this.endpoints)i.push(i6(u,e));let s=this.events.map(u=>gQ(u,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(u=>u.getName()==e.getName())>=0)return;for(let u of e.getNamesOfDependencies()){let a=r.find(c=>c.getName()==u);a&&this.mapCustomTypeDepthFirst(a,r,n,i)}let o=n.mapType(e);i.push(o)}};Hi.AbiRegistry=SA;function i6(t,e){let r=t.input.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new Vf.EndpointDefinition(t.name,r,n,t.modifiers)}function gQ(t,e){let r=t.inputs.map(n=>new bA.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new bA.EventDefinition(t.identifier,r)}});var a6=D(cc=>{"use strict";h();Object.defineProperty(cc,"__esModule",{value:!0});cc.createListOfTokenIdentifiers=cc.createListOfAddresses=void 0;var pQ=Yu(),o6=Ef(),mQ=ac();function yQ(t){let e=t.map(n=>new pQ.AddressValue(n));return o6.List.fromItems(e)}cc.createListOfAddresses=yQ;function wQ(t){let e=t.map(n=>new mQ.TokenIdentifierValue(n));return o6.List.fromItems(e)}cc.createListOfTokenIdentifiers=wQ});var E6=D(Dr=>{"use strict";h();var vQ=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),AQ=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),EQ=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vQ(e,t,r);return AQ(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.onPrimitiveTypeSelect=Dr.onPrimitiveValueSelect=Dr.onTypedValueSelect=Dr.onTypeSelect=void 0;var mp=EQ(Ie()),u6=Yu(),c6=yf(),l6=po(),f6=hf(),pp=Ef(),h6=Sf(),d6=Mf(),g6=Wg(),p6=Wu(),m6=ac(),y6=cp(),w6=sr(),v6=zg(),A6=op();function bQ(t,e){if(t.hasExactClass(pp.OptionType.ClassName))return e.onOption();if(t.hasExactClass(pp.ListType.ClassName))return e.onList();if(t.hasExactClass(v6.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(w6.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(p6.StructType.ClassName))return e.onStruct();if(t.hasExactClass(y6.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(f6.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`type isn't known: ${t}`)}Dr.onTypeSelect=bQ;function SQ(t,e){if(t.hasClassOrSuperclass(w6.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(pp.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(pp.List.ClassName))return e.onList();if(t.hasExactClass(v6.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(p6.Struct.ClassName))return e.onStruct();if(t.hasExactClass(y6.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(f6.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`value isn't typed: ${t}`)}Dr.onTypedValueSelect=SQ;function IQ(t,e){if(t.hasExactClass(c6.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(d6.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(u6.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(l6.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(A6.StringValue.ClassName))return e.onString();if(t.hasExactClass(h6.H256Value.ClassName))return e.onH256();if(t.hasExactClass(m6.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(g6.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Dr.onPrimitiveValueSelect=IQ;function TQ(t,e){if(t.hasExactClass(c6.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(d6.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(u6.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(l6.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(A6.StringType.ClassName))return e.onString();if(t.hasExactClass(h6.H256Type.ClassName))return e.onH256();if(t.hasExactClass(m6.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(g6.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Dr.onPrimitiveTypeSelect=TQ});var dr=D(He=>{"use strict";h();var _Q=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ut=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_Q(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});Ut(s6(),He);Ut(Yu(),He);Ut(Bg(),He);Ut(yf(),He);Ut(po(),He);Ut(qg(),He);Ut(aA(),He);Ut(hf(),He);Ut(a6(),He);Ut(zu(),He);Ut(Ef(),He);Ut(zg(),He);Ut(Sf(),He);Ut(E6(),He);Ut(Wg(),He);Ut(Mf(),He);Ut(op(),He);Ut(Wu(),He);Ut(ac(),He);Ut(cp(),He);Ut(lf(),He);Ut(EA(),He);Ut(sr(),He);Ut(hp(),He)});var S6=D(Gi=>{"use strict";h();var CQ=Gi&&Gi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NQ=Gi&&Gi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xQ=Gi&&Gi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&CQ(e,t,r);return NQ(e,t),e};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.OptionValueBinaryCodec=void 0;var b6=xQ(Ie()),yp=dr(),IA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[yp.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new b6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[yp.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new yp.OptionValue(r);if(e[0]!=1)throw new b6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new yp.OptionValue(r,n)}encodeNested(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([])}};Gi.OptionValueBinaryCodec=IA});var I6=D(wp=>{"use strict";h();Object.defineProperty(wp,"__esModule",{value:!0});wp.AddressBinaryCodec=void 0;var OQ=Ve(),DQ=dr(),TA=class{decodeNested(e){let r=e.slice(0,32),n=new OQ.Address(r);return[new DQ.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};wp.AddressBinaryCodec=TA});var _6=D(ji=>{"use strict";h();var PQ=ji&&ji.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RQ=ji&&ji.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BQ=ji&&ji.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PQ(e,t,r);return RQ(e,t),e};Object.defineProperty(ji,"__esModule",{value:!0});ji.BooleanBinaryCodec=void 0;var MQ=BQ(Ie()),T6=dr(),kf=class t{decodeNested(e){let r=e.readUInt8(0);return[new T6.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new MQ.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new T6.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([])}};ji.BooleanBinaryCodec=kf;kf.TRUE=1;kf.FALSE=0});var Ap=D(vp=>{"use strict";h();Object.defineProperty(vp,"__esModule",{value:!0});vp.SizeOfU32=void 0;vp.SizeOfU32=4});var N6=D(lc=>{"use strict";h();var LQ=lc&&lc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lc,"__esModule",{value:!0});lc.NumericalBinaryCodec=void 0;var Hf=LQ((rr(),_e(fr))),_A=dr(),C6=Ap(),$t=Bu(),CA=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=C6.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),u=i+n;return[o,u]}decodeTopLevel(e,r){let n=$t.cloneBuffer(e);if(e.length==0)return new _A.NumericalValue(r,new Hf.default(0));if(!r.withSign||$t.isMsbZero(n)){let c=$t.bufferToBigInt(n);return new _A.NumericalValue(r,c)}$t.flipBufferBitsInPlace(n);let a=$t.bufferToBigInt(n).multipliedBy(new Hf.default(-1)).minus(new Hf.default(1));return new _A.NumericalValue(r,a)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=p.Buffer.alloc(C6.SizeOfU32);return n.writeUInt32BE(r.length),p.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return p.Buffer.alloc(r,0);if(!e.withSign){let o=$t.bigIntToBuffer(e.value),u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}if(e.value.isPositive()){let o=$t.bigIntToBuffer(e.value);$t.isMsbOne(o)&&(o=$t.prependByteToBuffer(o,0));let u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}let n=e.value.plus(new Hf.default(1)),i=$t.bigIntToBuffer(n);$t.flipBufferBitsInPlace(i),$t.isMsbZero(i)&&(i=$t.prependByteToBuffer(i,255));let s=p.Buffer.alloc(r-i.length,255);return p.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?p.Buffer.alloc(0):r?this.encodePrimitive(e):$t.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=$t.bigIntToBuffer(e.value);return $t.isMsbOne(i)&&(i=$t.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Hf.default(1)),n=$t.bigIntToBuffer(r);return $t.flipBufferBitsInPlace(n),$t.isMsbZero(n)&&(n=$t.prependByteToBuffer(n,255)),n}};lc.NumericalBinaryCodec=CA});var x6=D(Ep=>{"use strict";h();Object.defineProperty(Ep,"__esModule",{value:!0});Ep.H256BinaryCodec=void 0;var FQ=Sf(),NA=class{decodeNested(e){let r=e.slice(0,32);return[new FQ.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Ep.H256BinaryCodec=NA});var Ip=D(Sp=>{"use strict";h();Object.defineProperty(Sp,"__esModule",{value:!0});Sp.BytesBinaryCodec=void 0;var O6=po(),bp=Ap(),xA=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(bp.SizeOfU32,bp.SizeOfU32+r);return[new O6.BytesValue(n),bp.SizeOfU32+r]}decodeTopLevel(e){return new O6.BytesValue(e)}encodeNested(e){let r=p.Buffer.alloc(bp.SizeOfU32);return r.writeUInt32BE(e.getLength()),p.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Sp.BytesBinaryCodec=xA});var P6=D(Tp=>{"use strict";h();Object.defineProperty(Tp,"__esModule",{value:!0});Tp.TokenIdentifierCodec=void 0;var UQ=po(),D6=ac(),qQ=Ip(),OA=class{constructor(){this.bytesCodec=new qQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new D6.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new D6.TokenIdentifierValue(r.toString())}encodeNested(e){let r=UQ.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Tp.TokenIdentifierCodec=OA});var B6=D(_p=>{"use strict";h();Object.defineProperty(_p,"__esModule",{value:!0});_p.NothingCodec=void 0;var R6=dr(),DA=class{decodeNested(){return[new R6.NothingValue,0]}decodeTopLevel(){return new R6.NothingValue}encodeNested(){return p.Buffer.from([])}encodeTopLevel(){return p.Buffer.from([])}};_p.NothingCodec=DA});var L6=D(Cp=>{"use strict";h();Object.defineProperty(Cp,"__esModule",{value:!0});Cp.StringBinaryCodec=void 0;var M6=dr(),VQ=po(),kQ=Ip(),PA=class{constructor(){this.bytesBinaryCodec=new kQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new M6.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new M6.StringValue(e.toString())}encodeNested(e){let r=VQ.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Cp.StringBinaryCodec=PA});var F6=D(xp=>{"use strict";h();Object.defineProperty(xp,"__esModule",{value:!0});xp.PrimitiveBinaryCodec=void 0;var Np=dr(),HQ=I6(),GQ=_6(),jQ=N6(),zQ=x6(),QQ=Ip(),KQ=P6(),WQ=B6(),$Q=L6(),RA=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new GQ.BooleanBinaryCodec,this.numericalCodec=new jQ.NumericalBinaryCodec,this.addressCodec=new HQ.AddressBinaryCodec,this.h256Codec=new zQ.H256BinaryCodec,this.bytesCodec=new QQ.BytesBinaryCodec,this.stringCodec=new $Q.StringBinaryCodec,this.tokenIdentifierCodec=new KQ.TokenIdentifierCodec,this.nothingCodec=new WQ.NothingCodec}decodeNested(e,r){return Np.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Np.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Np.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Np.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};xp.PrimitiveBinaryCodec=RA});var V6=D(Op=>{"use strict";h();Object.defineProperty(Op,"__esModule",{value:!0});Op.ListBinaryCodec=void 0;var U6=dr(),q6=Ap(),BA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,u=q6.SizeOfU32;e=o.slice(u);for(let a=0;a0;){let[u,a]=this.binaryCodec.decodeNested(e,n);i.push(u),o+=a,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new U6.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=p.Buffer.alloc(q6.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return p.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return p.Buffer.concat(r)}};Op.ListBinaryCodec=BA});var LA=D(Dp=>{"use strict";h();Object.defineProperty(Dp,"__esModule",{value:!0});Dp.FieldsBinaryCodec=void 0;var YQ=dr(),MA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,u]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(u),i+=u;let a=new YQ.Field(o,s.name);n.push(a)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return p.Buffer.concat(r)}};Dp.FieldsBinaryCodec=MA});var UA=D(Pp=>{"use strict";h();Object.defineProperty(Pp,"__esModule",{value:!0});Pp.StructBinaryCodec=void 0;var JQ=dr(),XQ=LA(),FA=class{constructor(e){this.fieldsCodec=new XQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new JQ.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Pp.StructBinaryCodec=FA});var k6=D(Bp=>{"use strict";h();Object.defineProperty(Bp,"__esModule",{value:!0});Bp.EnumBinaryCodec=void 0;var Rp=dr(),ZQ=LA(),qA=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new ZQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[u,a]=this.fieldsCodec.decodeNested(e,o);return[new Rp.EnumValue(r,s,u),i+a]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Rp.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Rp.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return p.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Rp.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return p.Buffer.concat([o,i])}};Bp.EnumBinaryCodec=qA});var H6=D(Mp=>{"use strict";h();Object.defineProperty(Mp,"__esModule",{value:!0});Mp.TupleBinaryCodec=void 0;var eK=UA(),VA=class{constructor(e){this.structCodec=new eK.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Mp.TupleBinaryCodec=VA});var G6=D(Lp=>{"use strict";h();Object.defineProperty(Lp,"__esModule",{value:!0});Lp.ArrayVecBinaryCodec=void 0;var tK=dr(),kA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let u=0;u{"use strict";h();var rK=Ln&&Ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),nK=Ln&&Ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),iK=Ln&&Ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rK(e,t,r);return nK(e,t),e};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BinaryCodecConstraints=Ln.BinaryCodec=void 0;var j6=iK(Ie()),Fp=dr(),z6=Rn(),sK=S6(),oK=F6(),aK=V6(),uK=UA(),cK=k6(),lK=H6(),fK=G6(),HA=class{constructor(e=null){this.constraints=e||new Up,this.optionCodec=new sK.OptionValueBinaryCodec(this),this.listCodec=new aK.ListBinaryCodec(this),this.arrayCodec=new fK.ArrayVecBinaryCodec(this),this.primitiveCodec=new oK.PrimitiveBinaryCodec(this),this.structCodec=new uK.StructBinaryCodec(this),this.tupleCodec=new lK.TupleBinaryCodec(this),this.enumCodec=new cK.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),Fp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=Fp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return z6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),Fp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return z6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),Fp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Ln.BinaryCodec=HA;var Up=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new j6.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new j6.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Ln.BinaryCodecConstraints=Up});var Q6=D(Fn=>{"use strict";h();var hK=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decodeBigNumber=Fn.decodeString=Fn.decodeBool=Fn.decodeUnsignedNumber=void 0;var dK=hK((rr(),_e(fr))),qp=dr(),gK=GA(),Vp=new gK.BinaryCodec;function pK(t){let e=Vp.decodeTopLevel(t,new qp.BigUIntType);return Number(e.valueOf())}Fn.decodeUnsignedNumber=pK;function mK(t){return!!Vp.decodeTopLevel(t,new qp.BooleanType).valueOf()}Fn.decodeBool=mK;function yK(t){let e=Vp.decodeTopLevel(t,new qp.BytesType);return String(e.valueOf())}Fn.decodeString=yK;function wK(t){let e=Vp.decodeTopLevel(t,new qp.BigUIntType);return new dK.default(e.valueOf())}Fn.decodeBigNumber=wK});var jA=D(wo=>{"use strict";h();var vK=wo&&wo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),K6=wo&&wo.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&vK(e,t,r)};Object.defineProperty(wo,"__esModule",{value:!0});K6(GA(),wo);K6(Q6(),wo)});var fc=D(kp=>{"use strict";h();Object.defineProperty(kp,"__esModule",{value:!0});kp.ArgSerializer=void 0;var W6=hr(),AK=jA(),$6=dr(),zA=Bg(),QA=qg(),KA=hp(),EK={codec:new AK.BinaryCodec},WA=class{constructor(e){e={...EK,...e},this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split(W6.ARGUMENTS_SEPARATOR).map(r=>p.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join(W6.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(zA.OptionalValue.ClassName)){let a=o;a.isSet()&&i(a.getTypedValue());return}if(o.hasExactClass(KA.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(QA.CompositeValue.ClassName)){let a=o;for(let c of a.getItems())i(c);return}let u=r.codec.encodeTopLevel(o);n.push(u)}function s(o){if(o.getType().isCounted){let a=new $6.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(a))}for(let a of o.getItems())i(a)}return n}};kp.ArgSerializer=WA});var $A=D((xye,Y6)=>{h();Rs.notEqual=SK;Rs.notOk=IK;Rs.equal=bK;Rs.ok=Rs;Y6.exports=Rs;function bK(t,e,r){Rs(t==e,r)}function SK(t,e,r){Rs(t!=e,r)}function IK(t,e){Rs(!t,e)}function Rs(t,e){if(!t)throw new Error(e||"AssertionError")}});var X6=D((Dye,J6)=>{h();J6.exports=YA;YA.supported=typeof WebAssembly<"u";function YA(t){if(!YA.supported)return null;var e=t&&t.imports,r=TK("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(a){i.exports.memory.grow(Math.ceil(Math.abs(a-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(a){if(i.exports)return a();if(n){n.then(a.bind(null,null)).catch(a);return}try{if(t&&t.async)throw new Error("async");u({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(u)}o(a)}function u(a){i.exports=a.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function TK(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(_K)):new(io()).Buffer(t,"base64")}function _K(t){return t.charCodeAt(0)}});var sO=D((Mye,Qi)=>{h();var zi=$A(),xt=X6()(),Bs=64,Hp=[];Qi.exports=Un;var Z6=Qi.exports.BYTES_MIN=16,eO=Qi.exports.BYTES_MAX=64,Rye=Qi.exports.BYTES=32,tO=Qi.exports.KEYBYTES_MIN=16,rO=Qi.exports.KEYBYTES_MAX=64,Bye=Qi.exports.KEYBYTES=32,nO=Qi.exports.SALTBYTES=16,iO=Qi.exports.PERSONALBYTES=16;function Un(t,e,r,n,i){if(!(this instanceof Un))return new Un(t,e,r,n,i);if(!(xt&&xt.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(zi(t>=Z6,"digestLength must be at least "+Z6+", was given "+t),zi(t<=eO,"digestLength must be at most "+eO+", was given "+t),e!=null&&zi(e.length>=tO,"key must be at least "+tO+", was given "+e.length),e!=null&&zi(e.length<=rO,"key must be at least "+rO+", was given "+e.length),r!=null&&zi(r.length===nO,"salt must be exactly "+nO+", was given "+r.length),n!=null&&zi(n.length===iO,"personal must be exactly "+iO+", was given "+n.length)),Hp.length||(Hp.push(Bs),Bs+=216),this.digestLength=t,this.finalized=!1,this.pointer=Hp.pop(),xt.memory.fill(0,0,64),xt.memory[0]=this.digestLength,xt.memory[1]=e?e.length:0,xt.memory[2]=1,xt.memory[3]=1,r&&xt.memory.set(r,32),n&&xt.memory.set(n,48),this.pointer+216>xt.memory.length&&xt.realloc(this.pointer+216),xt.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),xt.memory.fill(0,Bs,Bs+e.length),xt.memory[this.pointer+200]=128)}Un.prototype.update=function(t){return zi(this.finalized===!1,"Hash instance finalized"),zi(t,"input must be TypedArray or Buffer"),Bs+t.length>xt.memory.length&&xt.realloc(Bs+t.length),xt.memory.set(t,Bs),xt.exports.blake2b_update(this.pointer,Bs,Bs+t.length),this};Un.prototype.digest=function(t){if(zi(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,Hp.push(this.pointer),xt.exports.blake2b_final(this.pointer),!t||t==="binary")return xt.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return NK(xt.memory,this.pointer+128,this.digestLength);zi(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{h();var Eo=$A(),jf=sO();function Gp(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function oO(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function dO(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vo(t,e,r,n,i,s){var o=Gf[i],u=Gf[i+1],a=Gf[s],c=Gf[s+1];Gp(Te,t,e),oO(Te,t,o,u);var f=Te[n]^Te[t],d=Te[n+1]^Te[t+1];Te[n]=d,Te[n+1]=f,Gp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=f>>>24^d<<8,Te[e+1]=d>>>24^f<<8,Gp(Te,t,e),oO(Te,t,a,c),f=Te[n]^Te[t],d=Te[n+1]^Te[t+1],Te[n]=f>>>16^d<<16,Te[n+1]=d>>>16^f<<16,Gp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=d>>>31^f<<1,Te[e+1]=f>>>31^d<<1}var gO=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),OK=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Pr=new Uint8Array(OK.map(function(t){return t*2})),Te=new Uint32Array(32),Gf=new Uint32Array(32);function pO(t,e){var r=0;for(r=0;r<16;r++)Te[r]=t.h[r],Te[r+16]=gO[r];for(Te[24]=Te[24]^t.t,Te[25]=Te[25]^t.t/4294967296,e&&(Te[28]=~Te[28],Te[29]=~Te[29]),r=0;r<32;r++)Gf[r]=dO(t.b,4*r);for(r=0;r<12;r++)vo(0,8,16,24,Pr[r*16+0],Pr[r*16+1]),vo(2,10,18,26,Pr[r*16+2],Pr[r*16+3]),vo(4,12,20,28,Pr[r*16+4],Pr[r*16+5]),vo(6,14,22,30,Pr[r*16+6],Pr[r*16+7]),vo(0,10,20,30,Pr[r*16+8],Pr[r*16+9]),vo(2,12,22,24,Pr[r*16+10],Pr[r*16+11]),vo(4,14,16,26,Pr[r*16+12],Pr[r*16+13]),vo(6,8,18,28,Pr[r*16+14],Pr[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Te[r]^Te[r+16]}var Ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hc(t,e,r,n){Ao.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Ao[0]=t,e&&(Ao[1]=e.length),Ao[2]=1,Ao[3]=1,r&&Ao.set(r,32),n&&Ao.set(n,48);for(var i=0;i<16;i++)this.h[i]=gO[i]^dO(Ao,i*4);e&&(mO(this,e),this.c=128)}hc.prototype.update=function(t){return Eo(t!=null,"input must be Uint8Array or Buffer"),mO(this,t),this};hc.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Eo(e.length>=this.outlen,"out must have at least outlen bytes of space"),DK(this,e),t==="hex"?PK(e):e};hc.prototype.final=hc.prototype.digest;hc.ready=function(t){jf.ready(function(){t()})};function mO(t,e){for(var r=0;r>2]>>8*(r&3);return e}function PK(t){for(var e="",r=0;r=aO,"outlen must be at least "+aO+", was given "+e),Eo(e<=uO,"outlen must be at most "+uO+", was given "+e),r!=null&&Eo(r.length>=cO,"key must be at least "+cO+", was given "+r.length),r!=null&&Eo(r.length<=lO,"key must be at most "+lO+", was given "+r.length),n!=null&&Eo(n.length===fO,"salt must be exactly "+fO+", was given "+n.length),i!=null&&Eo(i.length===hO,"personal must be exactly "+hO+", was given "+i.length)),new yO(e,r,n,i)};Jr.exports.ready=function(t){jf.ready(function(){t()})};Jr.exports.WASM_SUPPORTED=jf.SUPPORTED;Jr.exports.WASM_LOADED=!1;var aO=Jr.exports.BYTES_MIN=16,uO=Jr.exports.BYTES_MAX=64,Fye=Jr.exports.BYTES=32,cO=Jr.exports.KEYBYTES_MIN=16,lO=Jr.exports.KEYBYTES_MAX=64,Uye=Jr.exports.KEYBYTES=32,fO=Jr.exports.SALTBYTES=16,hO=Jr.exports.PERSONALBYTES=16;jf.ready(function(t){t||(Jr.exports.WASM_LOADED=!0,yO=jf)})});var wO=D(jp=>{"use strict";h();Object.defineProperty(jp,"__esModule",{value:!0});jp.Code=void 0;var BK=JA(),MK=32,XA=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return p.Buffer.from(this.hex,"hex")}computeHash(){let e=BK(MK).update(this.valueOf()).digest();return p.Buffer.from(e)}};jp.Code=XA});var ZA=D(zp=>{"use strict";h();Object.defineProperty(zp,"__esModule",{value:!0});zp.CodeMetadata=void 0;var dc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBytes(e){return t.fromBuffer(p.Buffer.from(e))}static fromBuffer(e){if(e.length{"use strict";h();var LK=Ki&&Ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FK=Ki&&Ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),UK=Ki&&Ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LK(e,t,r);return FK(e,t),e};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ContractFunction=void 0;var qK=UK(Ie()),eE=class t{constructor(e){if(this.name=e,e==null)throw new qK.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Ki.ContractFunction=eE});var nE=D(Qp=>{"use strict";h();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.Compatibility=void 0;var VK=Ve(),rE=class{static guardAddressIsSetAndNonZero(e,r,n){!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==VK.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`)}};Qp.Compatibility=rE});var Ms=D(Kp=>{"use strict";h();Object.defineProperty(Kp,"__esModule",{value:!0});Kp.TransactionPayload=void 0;var iE=class t{constructor(e){this.data=p.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=p.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>p.Buffer.from(e,"hex"))}length(){return p.Buffer.from(this.data).length}};Kp.TransactionPayload=iE});var gc=D(Wp=>{"use strict";h();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.TransactionBuilder=void 0;var kK=hr(),HK=Xr(),GK=Ms(),sE=class{constructor(e){this.config=e.config,this.sender=e.sender,this.receiver=e.receiver,this.dataParts=e.dataParts,this.providedGasLimit=e.gasLimit,this.addDataMovementGas=e.addDataMovementGas,this.amount=e.amount}computeGasLimit(e){return this.addDataMovementGas?this.config.minGasLimit+this.config.gasLimitPerByte*BigInt(e.length())+this.providedGasLimit:this.providedGasLimit}buildTransactionPayload(){let e=this.dataParts.join(kK.ARGUMENTS_SEPARATOR);return new GK.TransactionPayload(e)}build(){let e=this.buildTransactionPayload(),r=this.computeGasLimit(e);return new HK.Transaction({sender:this.sender.bech32(),receiver:this.receiver.bech32(),gasLimit:r,value:this.amount||0n,data:e.valueOf(),chainID:this.config.chainID})}};Wp.TransactionBuilder=sE});var vO=D($p=>{"use strict";h();Object.defineProperty($p,"__esModule",{value:!0});$p.DelegationTransactionsFactory=void 0;var jK=Ve(),zK=hr(),QK=Ie(),fn=qn(),Zr=gc(),oE=class{constructor(e){this.config=e.config,this.argSerializer=new fn.ArgSerializer}createTransactionForNewDelegationContract(e){let r=["createNewDelegationContract",...this.argSerializer.valuesToStrings([new fn.BigUIntValue(e.totalDelegationCap),new fn.BigUIntValue(e.serviceFee)])],n=this.config.gasLimitCreateDelegationContract+this.config.additionalGasLimitForDelegationOperations;return new Zr.TransactionBuilder({config:this.config,sender:e.sender,receiver:jK.Address.fromBech32(zK.DELEGATION_MANAGER_SC_ADDRESS),dataParts:r,gasLimit:n,addDataMovementGas:!0,amount:e.amount}).build()}createTransactionForAddingNodes(e){if(e.publicKeys.length!==e.signedMessages.length)throw new QK.Err("The number of public keys should match the number of signed messages");let r=e.signedMessages.map(o=>new fn.BytesValue(p.Buffer.from(o))),n=this.argSerializer.valuesToStrings(r),i=e.publicKeys.length,s=["addNodes"];for(let o=0;o{h();var AO=(rr(),_e(fr)),EO=bO.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function u(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(f){var d=s[f];return typeof d=="string"?d:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function a(c,f){var d,w,A,T,x=n,B,V=f[c],U=V!=null&&(V instanceof AO||AO.isBigNumber(V));switch(V&&typeof V=="object"&&typeof V.toJSON=="function"&&(V=V.toJSON(c)),typeof o=="function"&&(V=o.call(f,c,V)),typeof V){case"string":return U?V:u(V);case"number":return isFinite(V)?String(V):"null";case"boolean":case"null":case"bigint":return String(V);case"object":if(!V)return"null";if(n+=i,B=[],Object.prototype.toString.apply(V)==="[object Array]"){for(T=V.length,d=0;d{h();var Xp=null,PK=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,RK=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,BK=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` -`,r:"\r",t:" "},s,o=function(x){throw{name:"SyntaxError",message:x,at:r,text:s}},u=function(x){return x&&x!==n&&o("Expected '"+x+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},a=function(){var x,R="";for(n==="-"&&(R="-",u("-"));n>="0"&&n<="9";)R+=n,u();if(n===".")for(R+=".";u()&&n>="0"&&n<="9";)R+=n;if(n==="e"||n==="E")for(R+=n,u(),(n==="-"||n==="+")&&(R+=n,u());n>="0"&&n<="9";)R+=n,u();if(x=+R,!isFinite(x))o("Bad number");else return Xp==null&&(Xp=(rr(),_e(fr))),R.length>15?e.storeAsString?R:e.useNativeBigInt?BigInt(R):new Xp(R):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(x):new Xp(x):x},c=function(){var x,R,V="",U;if(n==='"')for(var Q=r;u();){if(n==='"')return r-1>Q&&(V+=s.substring(Q,r-1)),u(),V;if(n==="\\"){if(r-1>Q&&(V+=s.substring(Q,r-1)),u(),n==="u"){for(U=0,R=0;R<4&&(x=parseInt(u(),16),!!isFinite(x));R+=1)U=U*16+x;V+=String.fromCharCode(U)}else if(typeof i[n]=="string")V+=i[n];else break;Q=r}}o("Bad string")},f=function(){for(;n&&n<=" ";)u()},d=function(){switch(n){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}o("Unexpected '"+n+"'")},w,A=function(){var x=[];if(n==="["){if(u("["),f(),n==="]")return u("]"),x;for(;n;){if(x.push(w()),f(),n==="]")return u("]"),x;u(","),f()}}o("Bad array")},T=function(){var x,R=Object.create(null);if(n==="{"){if(u("{"),f(),n==="}")return u("}"),R;for(;n;){if(x=c(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(R,x)&&o('Duplicate key "'+x+'"'),PK.test(x)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():R[x]=w():RK.test(x)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():R[x]=w():R[x]=w(),f(),n==="}")return u("}"),R;u(","),f()}}o("Bad object")};return w=function(){switch(f(),n){case"{":return T();case"[":return A();case'"':return c();case"-":return a();default:return n>="0"&&n<="9"?a():d()}},function(x,R){var V;return s=x+"",r=0,n=" ",V=w(),f(),n&&o("Syntax error"),typeof R=="function"?function U(Q,L){var k,H,q=Q[L];return q&&typeof q=="object"&&Object.keys(q).forEach(function(v){H=U(q,v),H!==void 0?q[v]=H:delete q[v]}),R.call(Q,L,q)}({"":V},""):V}};TO.exports=BK});var oE=B((qye,Zp)=>{h();var CO=IO().stringify,NO=_O();Zp.exports=function(t){return{parse:NO(t),stringify:CO}};Zp.exports.parse=NO();Zp.exports.stringify=CO});var OO=B(pc=>{"use strict";h();var MK=pc&&pc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pc,"__esModule",{value:!0});pc.RelayedTransactionsFactory=void 0;var LK=MK((rr(),_e(fr))),e0=Ve(),t0=Ie(),zf=qn(),xO=Xr(),FK=oE(),aE=class{constructor(e){this.config=e.config}createRelayedV1Transaction(e){if(!e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let r=this.prepareInnerTransactionForRelayedV1(e.innerTransaction),n=`relayedTx@${p.Buffer.from(r).toString("hex")}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=this.config.minGasLimit+i+e.innerTransaction.gasLimit;return new xO.Transaction({chainID:this.config.chainID,sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,gasLimit:s,data:p.Buffer.from(n)})}createRelayedV2Transaction(e){if(e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let{argumentsString:r}=new zf.ArgSerializer().valuesToString([new zf.AddressValue(e0.Address.fromBech32(e.innerTransaction.receiver)),new zf.U64Value(new LK.default(e.innerTransaction.nonce.toString())),new zf.BytesValue(p.Buffer.from(e.innerTransaction.data)),new zf.BytesValue(p.Buffer.from(e.innerTransaction.signature))]),n=`relayedTxV2@${r}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=e.innerTransactionGasLimit+this.config.minGasLimit+i;return new xO.Transaction({sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,value:0n,gasLimit:s,chainID:this.config.chainID,data:p.Buffer.from(n),version:e.innerTransaction.version,options:e.innerTransaction.options})}prepareInnerTransactionForRelayedV1(e){let r={nonce:e.nonce,sender:e0.Address.fromBech32(e.sender).pubkey().toString("base64"),receiver:e0.Address.fromBech32(e.receiver).pubkey().toString("base64"),value:e.value,gasPrice:e.gasPrice,gasLimit:e.gasLimit,data:p.Buffer.from(e.data).toString("base64"),signature:p.Buffer.from(e.signature).toString("base64"),chainID:p.Buffer.from(e.chainID).toString("base64"),version:e.version,options:e.options.valueOf()==0?void 0:e.options,guardian:e.guardian?e0.Address.fromBech32(e.guardian).pubkey().toString("base64"):void 0,guardianSignature:e.guardianSignature.length?p.Buffer.from(e.guardianSignature).toString("base64"):void 0,sndUserName:e.senderUsername?p.Buffer.from(e.senderUsername).toString("base64"):void 0,rcvUserName:e.receiverUsername?p.Buffer.from(e.receiverUsername).toString("base64"):void 0};return FK.stringify(r)}};pc.RelayedTransactionsFactory=aE});var DO=B(r0=>{"use strict";h();Object.defineProperty(r0,"__esModule",{value:!0});r0.ArgumentErrorContext=void 0;var UK=Ie(),uE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new UK.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) -Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};r0.ArgumentErrorContext=uE});var n0=B(qa=>{"use strict";h();var qK=qa&&qa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qa,"__esModule",{value:!0});qa.NativeSerializer=void 0;var VK=qK((rr(),_e(fr))),kK=Ve(),cE=Ie(),HK=Ru(),GK=DO(),ye=dr(),jK;(function(t){function e(L,k){L=L||[],r(L,k),n(k)&&(L=i(L,k));let H=k.input,q=[];for(let v=0;v0&&k[0].type.getCardinality().isComposite()&&(q=1/0,v=!0);for(let C of k){if(C.type.getCardinality().isSingular())break;H-=1}return{min:H,max:q,variadic:v}}t.getArgumentsCardinality=s;function o(L,k,H){if(L&&L.belongsToTypesystem)return L;if(k instanceof ye.OptionType)return u(L,k,H);if(k instanceof ye.OptionalType)return a(L,k,H);if(k instanceof ye.VariadicType)return c(L,k,H);if(k instanceof ye.CompositeType)return d(L,k,H);if(k instanceof ye.TupleType)return w(L,k,H);if(k instanceof ye.StructType)return A(L,k,H);if(k instanceof ye.ListType)return f(L,k,H);if(k instanceof ye.PrimitiveType)return T(L,k,H);if(k instanceof ye.EnumType)return x(L,k,H);H.throwError(`convertToTypedValue: unhandled type ${k}`)}function u(L,k,H){if(L==null)return ye.OptionValue.newMissing();let q=o(L,k.getFirstTypeParameter(),H);return ye.OptionValue.newProvided(q)}function a(L,k,H){if(L==null)return new ye.OptionalValue(k);let q=o(L,k.getFirstTypeParameter(),H);return new ye.OptionalValue(k,q)}function c(L,k,H){if(k.isCounted)throw new cE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');L==null&&(L=[]),L.map===void 0&&H.convertError(L,"Variadic");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.VariadicValue(k,q)}function f(L,k,H){L.map===void 0&&H.convertError(L,"List");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.List(k,q)}function d(L,k,H){let q=[],v=k.getTypeParameters();H.guardSameLength(L,v);for(let C=0;C{"use strict";h();Object.defineProperty(i0,"__esModule",{value:!0});i0.TokenTransfersDataBuilder=void 0;var zK=fc(),pi=dr(),QK=Ca(),lE=class{constructor(){this.tokenComputer=new QK.TokenComputer,this.argsSerializer=new zK.ArgSerializer}buildDataPartsForESDTTransfer(e){return["ESDTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(e.token.identifier),new pi.BigUIntValue(e.amount)])]}buildDataPartsForSingleESDTNFTTransfer(e,r){let n=e.token,i=this.tokenComputer.extractIdentifierFromExtendedIdentifier(n.identifier);return["ESDTNFTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(i),new pi.BigUIntValue(n.nonce),new pi.BigUIntValue(e.amount),new pi.AddressValue(r)])]}buildDataPartsForMultiESDTNFTTransfer(e,r){let n=[new pi.AddressValue(e),new pi.U32Value(r.length)];for(let s of r){let o=this.tokenComputer.extractIdentifierFromExtendedIdentifier(s.token.identifier);n.push(new pi.TokenIdentifierValue(o),new pi.BigUIntValue(s.token.nonce),new pi.BigUIntValue(s.amount))}return["MultiESDTNFTTransfer",...this.argsSerializer.valuesToStrings(n)]}};i0.TokenTransfersDataBuilder=lE});var dE=B(a0=>{"use strict";h();Object.defineProperty(a0,"__esModule",{value:!0});a0.SmartContractTransactionsFactory=void 0;var PO=Ve(),RO=hr(),BO=Ie(),KK=oo(),s0=qn(),WK=n0(),$K=Ca(),o0=Ru(),YK=fE(),Qf=gc(),hE=class{constructor(e){this.config=e.config,this.abi=e.abi,this.tokenComputer=new $K.TokenComputer,this.dataArgsBuilder=new YK.TokenTransfersDataBuilder}createTransactionForDeploy(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=[o0.byteArrayToHex(e.bytecode),o0.byteArrayToHex(RO.VM_TYPE_WASM_VM),a.toString()],f=this.abi?.constructorDefinition,d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:PO.Address.fromBech32(RO.CONTRACT_DEPLOY_ADDRESS),dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}createTransactionForExecute(e){let r=e.arguments||[],n=e.tokenTransfers||[],i=e.nativeTransferAmount??0n,s=n.length;if(i&&s)throw new BO.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)");let o=e.contract,u=[];if(s===1){let f=n[0];this.tokenComputer.isFungible(f.token)?u=this.dataArgsBuilder.buildDataPartsForESDTTransfer(f):(u=this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(f,o),o=e.sender)}else s>1&&(u=this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(o,n),o=e.sender);u.push(u.length?o0.utf8ToHex(e.function):e.function);let a=this.abi?.getEndpoint(e.function),c=this.argsToDataParts(r,a);return u.push(...c),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:o,dataParts:u,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:i}).build()}createTransactionForUpgrade(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=["upgradeContract",o0.byteArrayToHex(e.bytecode),a.toString()],f=this.getEndpointForUpgrade(),d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}getEndpointForUpgrade(){if(this.abi)try{return this.abi.getEndpoint("upgrade")}catch{return KK.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."),this.abi.constructorDefinition}}createTransactionForClaimingDeveloperRewards(e){let r=["ClaimDeveloperRewards"];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitClaimDeveloperRewards,addDataMovementGas:!1}).build()}createTransactionForChangingOwnerAddress(e){let r=["ChangeOwnerAddress",PO.Address.fromBech32(e.newOwner.bech32()).toHex()];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitChangeOwnerAddress,addDataMovementGas:!1}).build()}argsToDataParts(e,r){if(r){let n=WK.NativeSerializer.nativeToTypedValues(e,r);return new s0.ArgSerializer().valuesToStrings(n)}if(this.areArgsOfTypedValue(e))return new s0.ArgSerializer().valuesToStrings(e);throw new BO.Err("Can't convert args to TypedValues")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}};a0.SmartContractTransactionsFactory=hE});var MO=B(u0=>{"use strict";h();Object.defineProperty(u0,"__esModule",{value:!0});u0.TokenManagementTransactionsFactory=void 0;var Wi=Ve(),$i=hr(),JK=oo(),Z=qn(),Yt=gc(),gE=class{constructor(e){this.config=e.config,this.argSerializer=new Z.ArgSerializer,this.trueAsString="true",this.falseAsString="false"}createTransactionForIssuingFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.initialSupply),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issue",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueSemiFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueNonFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["registerMetaESDT",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringAndSettingRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue(e.tokenType),new Z.BigUIntValue(e.numDecimals)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForSettingBurnRoleGlobally(e){let r=["setBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForUnsettingBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleLocalMint&&r.push(new Z.StringValue("ESDTRoleLocalMint")),e.addRoleLocalBurn&&r.push(new Z.StringValue("ESDTRoleLocalBurn")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnSemiFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTAddQuantity&&r.push(new Z.StringValue("ESDTRoleNFTAddQuantity")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnMetaESDT(e){return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(e)}createTransactionForSettingSpecialRoleOnNonFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTUpdateAttributes&&r.push(new Z.StringValue("ESDTRoleNFTUpdateAttributes")),e.addRoleNFTAddURI&&r.push(new Z.StringValue("ESDTRoleNFTAddURI")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForCreatingNFT(e){let r=["ESDTNFTCreate",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.initialQuantity),new Z.StringValue(e.name),new Z.BigUIntValue(e.royalties),new Z.StringValue(e.hash),new Z.BytesValue(p.Buffer.from(e.attributes)),...e.uris.map(s=>new Z.StringValue(s))])],n=e.name+e.hash+e.attributes+e.uris.join(""),i=this.config.gasLimitStorePerByte+BigInt(n.length);return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftCreate+i,addDataMovementGas:!0}).build()}createTransactionForPausing(e){let r=["pause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForUnpausing(e){let r=["unPause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForFreezing(e){let r=["freeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForUnfreezing(e){let r=["UnFreeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForWiping(e){let r=["wipe",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitWiping,addDataMovementGas:!0}).build()}createTransactionForLocalMint(e){let r=["ESDTLocalMint",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToMint)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalMint,addDataMovementGas:!0}).build()}createTransactionForLocalBurning(e){let r=["ESDTLocalBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalBurn,addDataMovementGas:!0}).build()}createTransactionForUpdatingAttributes(e){let r=["ESDTNFTUpdateAttributes",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BytesValue(p.Buffer.from(e.attributes))])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftUpdateAttributes,addDataMovementGas:!0}).build()}createTransactionForAddingQuantity(e){let r=["ESDTNFTAddQuantity",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToAdd)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftAddQuantity,addDataMovementGas:!0}).build()}createTransactionForBurningQuantity(e){let r=["ESDTNFTBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftBurn,addDataMovementGas:!0}).build()}notifyAboutUnsettingBurnRoleGlobally(){JK.Logger.info(` +`+x+"}":"{"+B.join(",")+"}",n=x,A}}typeof EO.stringify!="function"&&(EO.stringify=function(c,f,d){var w;if(n="",i="",typeof d=="number")for(w=0;w{h();var Yp=null,KK=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,WK=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,$K=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},s,o=function(x){throw{name:"SyntaxError",message:x,at:r,text:s}},u=function(x){return x&&x!==n&&o("Expected '"+x+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},a=function(){var x,B="";for(n==="-"&&(B="-",u("-"));n>="0"&&n<="9";)B+=n,u();if(n===".")for(B+=".";u()&&n>="0"&&n<="9";)B+=n;if(n==="e"||n==="E")for(B+=n,u(),(n==="-"||n==="+")&&(B+=n,u());n>="0"&&n<="9";)B+=n,u();if(x=+B,!isFinite(x))o("Bad number");else return Yp==null&&(Yp=(rr(),_e(fr))),B.length>15?e.storeAsString?B:e.useNativeBigInt?BigInt(B):new Yp(B):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(x):new Yp(x):x},c=function(){var x,B,V="",U;if(n==='"')for(var Q=r;u();){if(n==='"')return r-1>Q&&(V+=s.substring(Q,r-1)),u(),V;if(n==="\\"){if(r-1>Q&&(V+=s.substring(Q,r-1)),u(),n==="u"){for(U=0,B=0;B<4&&(x=parseInt(u(),16),!!isFinite(x));B+=1)U=U*16+x;V+=String.fromCharCode(U)}else if(typeof i[n]=="string")V+=i[n];else break;Q=r}}o("Bad string")},f=function(){for(;n&&n<=" ";)u()},d=function(){switch(n){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}o("Unexpected '"+n+"'")},w,A=function(){var x=[];if(n==="["){if(u("["),f(),n==="]")return u("]"),x;for(;n;){if(x.push(w()),f(),n==="]")return u("]"),x;u(","),f()}}o("Bad array")},T=function(){var x,B=Object.create(null);if(n==="{"){if(u("{"),f(),n==="}")return u("}"),B;for(;n;){if(x=c(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(B,x)&&o('Duplicate key "'+x+'"'),KK.test(x)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():B[x]=w():WK.test(x)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():B[x]=w():B[x]=w(),f(),n==="}")return u("}"),B;u(","),f()}}o("Bad object")};return w=function(){switch(f(),n){case"{":return T();case"[":return A();case'"':return c();case"-":return a();default:return n>="0"&&n<="9"?a():d()}},function(x,B){var V;return s=x+"",r=0,n=" ",V=w(),f(),n&&o("Syntax error"),typeof B=="function"?function U(Q,L){var k,H,q=Q[L];return q&&typeof q=="object"&&Object.keys(q).forEach(function(v){H=U(q,v),H!==void 0?q[v]=H:delete q[v]}),B.call(Q,L,q)}({"":V},""):V}};IO.exports=$K});var aE=D((s1e,Jp)=>{h();var _O=SO().stringify,CO=TO();Jp.exports=function(t){return{parse:CO(t),stringify:_O}};Jp.exports.parse=CO();Jp.exports.stringify=_O});var xO=D(pc=>{"use strict";h();var YK=pc&&pc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pc,"__esModule",{value:!0});pc.RelayedTransactionsFactory=void 0;var JK=YK((rr(),_e(fr))),Xp=Ve(),Zp=Ie(),zf=qn(),NO=Xr(),XK=aE(),uE=class{constructor(e){this.config=e.config}createRelayedV1Transaction(e){if(!e.innerTransaction.gasLimit)throw new Zp.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction");if(!e.innerTransaction.signature.length)throw new Zp.ErrInvalidInnerTransaction("The inner transaction is not signed");let r=this.prepareInnerTransactionForRelayedV1(e.innerTransaction),n=`relayedTx@${p.Buffer.from(r).toString("hex")}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=this.config.minGasLimit+i+e.innerTransaction.gasLimit;return new NO.Transaction({chainID:this.config.chainID,sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,gasLimit:s,data:p.Buffer.from(n)})}createRelayedV2Transaction(e){if(e.innerTransaction.gasLimit)throw new Zp.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction");if(!e.innerTransaction.signature.length)throw new Zp.ErrInvalidInnerTransaction("The inner transaction is not signed");let{argumentsString:r}=new zf.ArgSerializer().valuesToString([new zf.AddressValue(Xp.Address.fromBech32(e.innerTransaction.receiver)),new zf.U64Value(new JK.default(e.innerTransaction.nonce.toString())),new zf.BytesValue(p.Buffer.from(e.innerTransaction.data)),new zf.BytesValue(p.Buffer.from(e.innerTransaction.signature))]),n=`relayedTxV2@${r}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=e.innerTransactionGasLimit+this.config.minGasLimit+i;return new NO.Transaction({sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,value:0n,gasLimit:s,chainID:this.config.chainID,data:p.Buffer.from(n),version:e.innerTransaction.version,options:e.innerTransaction.options})}prepareInnerTransactionForRelayedV1(e){let r={nonce:e.nonce,sender:Xp.Address.fromBech32(e.sender).pubkey().toString("base64"),receiver:Xp.Address.fromBech32(e.receiver).pubkey().toString("base64"),value:e.value,gasPrice:e.gasPrice,gasLimit:e.gasLimit,data:p.Buffer.from(e.data).toString("base64"),signature:p.Buffer.from(e.signature).toString("base64"),chainID:p.Buffer.from(e.chainID).toString("base64"),version:e.version,options:e.options.valueOf()==0?void 0:e.options,guardian:e.guardian?Xp.Address.fromBech32(e.guardian).pubkey().toString("base64"):void 0,guardianSignature:e.guardianSignature.length?p.Buffer.from(e.guardianSignature).toString("base64"):void 0,sndUserName:e.senderUsername?p.Buffer.from(e.senderUsername).toString("base64"):void 0,rcvUserName:e.receiverUsername?p.Buffer.from(e.receiverUsername).toString("base64"):void 0};return XK.stringify(r)}};pc.RelayedTransactionsFactory=uE});var OO=D(e0=>{"use strict";h();Object.defineProperty(e0,"__esModule",{value:!0});e0.ArgumentErrorContext=void 0;var ZK=Ie(),cE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new ZK.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) +Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};e0.ArgumentErrorContext=cE});var t0=D(Ua=>{"use strict";h();var eW=Ua&&Ua.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ua,"__esModule",{value:!0});Ua.NativeSerializer=void 0;var tW=eW((rr(),_e(fr))),rW=Ve(),lE=Ie(),nW=Ru(),iW=OO(),ye=dr(),sW;(function(t){function e(L,k){L=L||[],r(L,k),n(k)&&(L=i(L,k));let H=k.input,q=[];for(let v=0;v0&&k[0].type.getCardinality().isComposite()&&(q=1/0,v=!0);for(let C of k){if(C.type.getCardinality().isSingular())break;H-=1}return{min:H,max:q,variadic:v}}t.getArgumentsCardinality=s;function o(L,k,H){if(L&&L.belongsToTypesystem)return L;if(k instanceof ye.OptionType)return u(L,k,H);if(k instanceof ye.OptionalType)return a(L,k,H);if(k instanceof ye.VariadicType)return c(L,k,H);if(k instanceof ye.CompositeType)return d(L,k,H);if(k instanceof ye.TupleType)return w(L,k,H);if(k instanceof ye.StructType)return A(L,k,H);if(k instanceof ye.ListType)return f(L,k,H);if(k instanceof ye.PrimitiveType)return T(L,k,H);if(k instanceof ye.EnumType)return x(L,k,H);H.throwError(`convertToTypedValue: unhandled type ${k}`)}function u(L,k,H){if(L==null)return ye.OptionValue.newMissing();let q=o(L,k.getFirstTypeParameter(),H);return ye.OptionValue.newProvided(q)}function a(L,k,H){if(L==null)return new ye.OptionalValue(k);let q=o(L,k.getFirstTypeParameter(),H);return new ye.OptionalValue(k,q)}function c(L,k,H){if(k.isCounted)throw new lE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');L==null&&(L=[]),L.map===void 0&&H.convertError(L,"Variadic");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.VariadicValue(k,q)}function f(L,k,H){L.map===void 0&&H.convertError(L,"List");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.List(k,q)}function d(L,k,H){let q=[],v=k.getTypeParameters();H.guardSameLength(L,v);for(let C=0;C{"use strict";h();Object.defineProperty(r0,"__esModule",{value:!0});r0.TokenTransfersDataBuilder=void 0;var oW=fc(),pi=dr(),aW=_a(),fE=class{constructor(){this.tokenComputer=new aW.TokenComputer,this.argsSerializer=new oW.ArgSerializer}buildDataPartsForESDTTransfer(e){return["ESDTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(e.token.identifier),new pi.BigUIntValue(e.amount)])]}buildDataPartsForSingleESDTNFTTransfer(e,r){let n=e.token,i=this.tokenComputer.extractIdentifierFromExtendedIdentifier(n.identifier);return["ESDTNFTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(i),new pi.BigUIntValue(n.nonce),new pi.BigUIntValue(e.amount),new pi.AddressValue(r)])]}buildDataPartsForMultiESDTNFTTransfer(e,r){let n=[new pi.AddressValue(e),new pi.U32Value(r.length)];for(let s of r){let o=this.tokenComputer.extractIdentifierFromExtendedIdentifier(s.token.identifier);n.push(new pi.TokenIdentifierValue(o),new pi.BigUIntValue(s.token.nonce),new pi.BigUIntValue(s.amount))}return["MultiESDTNFTTransfer",...this.argsSerializer.valuesToStrings(n)]}};r0.TokenTransfersDataBuilder=fE});var gE=D(s0=>{"use strict";h();Object.defineProperty(s0,"__esModule",{value:!0});s0.SmartContractTransactionsFactory=void 0;var DO=Ve(),PO=hr(),RO=Ie(),uW=oo(),n0=qn(),cW=t0(),lW=_a(),i0=Ru(),fW=hE(),Qf=gc(),dE=class{constructor(e){this.config=e.config,this.abi=e.abi,this.tokenComputer=new lW.TokenComputer,this.dataArgsBuilder=new fW.TokenTransfersDataBuilder}createTransactionForDeploy(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new n0.CodeMetadata(n,i,s,o),c=[i0.byteArrayToHex(e.bytecode),i0.byteArrayToHex(PO.VM_TYPE_WASM_VM),a.toString()],f=this.abi?.constructorDefinition,d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:DO.Address.fromBech32(PO.CONTRACT_DEPLOY_ADDRESS),dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}createTransactionForExecute(e){let r=e.arguments||[],n=e.tokenTransfers||[],i=e.nativeTransferAmount??0n,s=n.length;if(i&&s)throw new RO.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)");let o=e.contract,u=[];if(s===1){let f=n[0];this.tokenComputer.isFungible(f.token)?u=this.dataArgsBuilder.buildDataPartsForESDTTransfer(f):(u=this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(f,o),o=e.sender)}else s>1&&(u=this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(o,n),o=e.sender);u.push(u.length?i0.utf8ToHex(e.function):e.function);let a=this.abi?.getEndpoint(e.function),c=this.argsToDataParts(r,a);return u.push(...c),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:o,dataParts:u,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:i}).build()}createTransactionForUpgrade(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new n0.CodeMetadata(n,i,s,o),c=["upgradeContract",i0.byteArrayToHex(e.bytecode),a.toString()],f=this.getEndpointForUpgrade(),d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}getEndpointForUpgrade(){if(this.abi)try{return this.abi.getEndpoint("upgrade")}catch{return uW.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."),this.abi.constructorDefinition}}createTransactionForClaimingDeveloperRewards(e){let r=["ClaimDeveloperRewards"];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitClaimDeveloperRewards,addDataMovementGas:!1}).build()}createTransactionForChangingOwnerAddress(e){let r=["ChangeOwnerAddress",DO.Address.fromBech32(e.newOwner.bech32()).toHex()];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitChangeOwnerAddress,addDataMovementGas:!1}).build()}argsToDataParts(e,r){if(r){let n=cW.NativeSerializer.nativeToTypedValues(e,r);return new n0.ArgSerializer().valuesToStrings(n)}if(this.areArgsOfTypedValue(e))return new n0.ArgSerializer().valuesToStrings(e);throw new RO.Err("Can't convert args to TypedValues")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}};s0.SmartContractTransactionsFactory=dE});var BO=D(o0=>{"use strict";h();Object.defineProperty(o0,"__esModule",{value:!0});o0.TokenManagementTransactionsFactory=void 0;var Wi=Ve(),$i=hr(),hW=oo(),Z=qn(),Yt=gc(),pE=class{constructor(e){this.config=e.config,this.argSerializer=new Z.ArgSerializer,this.trueAsString="true",this.falseAsString="false"}createTransactionForIssuingFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.initialSupply),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issue",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueSemiFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueNonFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["registerMetaESDT",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringAndSettingRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue(e.tokenType),new Z.BigUIntValue(e.numDecimals)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForSettingBurnRoleGlobally(e){let r=["setBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForUnsettingBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleLocalMint&&r.push(new Z.StringValue("ESDTRoleLocalMint")),e.addRoleLocalBurn&&r.push(new Z.StringValue("ESDTRoleLocalBurn")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnSemiFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTAddQuantity&&r.push(new Z.StringValue("ESDTRoleNFTAddQuantity")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnMetaESDT(e){return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(e)}createTransactionForSettingSpecialRoleOnNonFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTUpdateAttributes&&r.push(new Z.StringValue("ESDTRoleNFTUpdateAttributes")),e.addRoleNFTAddURI&&r.push(new Z.StringValue("ESDTRoleNFTAddURI")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForCreatingNFT(e){let r=["ESDTNFTCreate",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.initialQuantity),new Z.StringValue(e.name),new Z.BigUIntValue(e.royalties),new Z.StringValue(e.hash),new Z.BytesValue(p.Buffer.from(e.attributes)),...e.uris.map(s=>new Z.StringValue(s))])],n=e.name+e.hash+e.attributes+e.uris.join(""),i=this.config.gasLimitStorePerByte+BigInt(n.length);return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftCreate+i,addDataMovementGas:!0}).build()}createTransactionForPausing(e){let r=["pause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForUnpausing(e){let r=["unPause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForFreezing(e){let r=["freeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForUnfreezing(e){let r=["UnFreeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForWiping(e){let r=["wipe",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitWiping,addDataMovementGas:!0}).build()}createTransactionForLocalMint(e){let r=["ESDTLocalMint",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToMint)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalMint,addDataMovementGas:!0}).build()}createTransactionForLocalBurning(e){let r=["ESDTLocalBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalBurn,addDataMovementGas:!0}).build()}createTransactionForUpdatingAttributes(e){let r=["ESDTNFTUpdateAttributes",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BytesValue(p.Buffer.from(e.attributes))])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftUpdateAttributes,addDataMovementGas:!0}).build()}createTransactionForAddingQuantity(e){let r=["ESDTNFTAddQuantity",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToAdd)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftAddQuantity,addDataMovementGas:!0}).build()}createTransactionForBurningQuantity(e){let r=["ESDTNFTBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftBurn,addDataMovementGas:!0}).build()}notifyAboutUnsettingBurnRoleGlobally(){hW.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}boolToString(e){return e?this.trueAsString:this.falseAsString}};u0.TokenManagementTransactionsFactory=gE});var mE=B(c0=>{"use strict";h();Object.defineProperty(c0,"__esModule",{value:!0});c0.TransactionsFactoryConfig=void 0;var XK=hr(),pE=class{constructor(e){this.chainID=e.chainID,this.addressHrp=XK.DEFAULT_HRP,this.minGasLimit=50000n,this.gasLimitPerByte=1500n,this.gasLimitIssue=60000000n,this.gasLimitToggleBurnRoleGlobally=60000000n,this.gasLimitEsdtLocalMint=300000n,this.gasLimitEsdtLocalBurn=300000n,this.gasLimitSetSpecialRole=60000000n,this.gasLimitPausing=60000000n,this.gasLimitFreezing=60000000n,this.gasLimitWiping=60000000n,this.gasLimitEsdtNftCreate=3000000n,this.gasLimitEsdtNftUpdateAttributes=1000000n,this.gasLimitEsdtNftAddQuantity=1000000n,this.gasLimitEsdtNftBurn=1000000n,this.gasLimitStorePerByte=10000n,this.issueCost=50000000000000000n,this.gasLimitStake=5000000n,this.gasLimitUnstake=5000000n,this.gasLimitUnbond=5000000n,this.gasLimitCreateDelegationContract=50000000n,this.gasLimitDelegationOperations=1000000n,this.additionalGasLimitPerValidatorNode=6000000n,this.additionalGasLimitForDelegationOperations=10000000n,this.gasLimitSaveKeyValue=100000n,this.gasLimitPersistPerByte=1000n,this.gasLimitSetGuardian=250000n,this.gasLimitGuardAccount=250000n,this.gasLimitUnguardAccount=250000n,this.gasLimitESDTTransfer=200000n,this.gasLimitESDTNFTTransfer=200000n,this.gasLimitMultiESDTNFTTransfer=200000n,this.gasLimitClaimDeveloperRewards=6000000n,this.gasLimitChangeOwnerAddress=6000000n}};c0.TransactionsFactoryConfig=pE});var UO=B(l0=>{"use strict";h();Object.defineProperty(l0,"__esModule",{value:!0});l0.TransferTransactionsFactory=void 0;var bo=Ie(),en=qn(),ZK=Ca(),Kf=Xr(),yE=Ms(),eW=fE(),LO=gc(),tW=1e5,FO=8e5,wE=class{constructor(e){this.isGasEstimator(e)?this.gasEstimator=e:(this.config=e.config,this.tokenComputer=new ZK.TokenComputer,this.tokenTransfersDataBuilder=new eW.TokenTransfersDataBuilder)}isGasEstimator(e){return typeof e=="object"&&typeof e.forEGLDTransfer=="function"&&typeof e.forESDTTransfer=="function"&&typeof e.forESDTNFTTransfer=="function"&&typeof e.forMultiESDTNFTTransfer=="function"}isGasEstimatorDefined(){return this.gasEstimator!==void 0}ensureMembersAreDefined(){if(this.config===void 0)throw new bo.Err("'config' is not defined");if(this.tokenTransfersDataBuilder===void 0)throw new bo.Err("`dataArgsBuilder is not defined`");if(this.tokenComputer===void 0)throw new bo.Err("`tokenComputer is not defined`")}createTransactionForNativeTokenTransfer(e){this.ensureMembersAreDefined();let r=e.data||new Uint8Array;return new Kf.Transaction({sender:e.sender.bech32(),receiver:e.receiver.bech32(),chainID:this.config.chainID,gasLimit:this.computeGasForMoveBalance(this.config,r),data:r,value:e.nativeAmount})}createTransactionForESDTTokenTransfer(e){this.ensureMembersAreDefined();let r=e.tokenTransfers.length;if(r===0)throw new bo.ErrBadUsage("No token transfer has been provided");if(r===1)return this.createSingleESDTTransferTransaction(e);let n=this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(e.receiver,e.tokenTransfers),i=this.config.gasLimitMultiESDTNFTTransfer*BigInt(r)+BigInt(FO);return new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:n,gasLimit:i,addDataMovementGas:!0}).build()}createEGLDTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.");let r=e.data?.length()||0,n=this.gasEstimator.forEGLDTransfer(r);return new Kf.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||n,data:e.data,chainID:e.chainID})}createESDTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.U64Value(e.tokenTransfer.nonce),new en.BigUIntValue(e.tokenTransfer.valueOf()),new en.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let r=[new en.AddressValue(e.destination),new en.U16Value(e.tokenTransfers.length)];for(let a of e.tokenTransfers)r.push(en.BytesValue.fromUTF8(a.tokenIdentifier),new en.U64Value(a.nonce),new en.BigUIntValue(a.valueOf()));let{argumentsString:n}=new en.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new yE.TransactionPayload(i),o=s.length()||0,u=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||u,data:s,chainID:e.chainID})}createSingleESDTTransferTransaction(e){this.ensureMembersAreDefined();let r=[],n=e.tokenTransfers[0],i=0n,s=e.receiver;return this.tokenComputer.isFungible(n.token)?(r=this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(n),i=this.config.gasLimitESDTTransfer+BigInt(tW)):(r=this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(n,s),i=this.config.gasLimitESDTNFTTransfer+BigInt(FO),s=e.sender),new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:s,dataParts:r,gasLimit:i,addDataMovementGas:!0}).build()}computeGasForMoveBalance(e,r){return e.minGasLimit+e.gasLimitPerByte*BigInt(r.length)}};l0.TransferTransactionsFactory=wE});var qO=B(h0=>{"use strict";h();Object.defineProperty(h0,"__esModule",{value:!0});h0.AccountTransactionsFactory=void 0;var rW=Ve(),f0=gc(),vE=class{constructor(e){this.config=e.config}createTransactionForSavingKeyValue(e){let r="SaveKeyValue",n=this.computeDataPartsForSavingKeyValue(e.keyValuePairs),i=[r,...n],s=this.computeExtraGasForSavingKeyValue(e.keyValuePairs);return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:i,gasLimit:s,addDataMovementGas:!0}).build()}computeExtraGasForSavingKeyValue(e){let r=0n;return e.forEach((n,i)=>{r+=this.config.gasLimitPersistPerByte*BigInt(i.length+n.length)+this.config.gasLimitStorePerByte*BigInt(n.length)}),r+this.config.gasLimitSaveKeyValue}computeDataPartsForSavingKeyValue(e){let r=[];return e.forEach((n,i)=>{r.push(p.Buffer.from(i).toString("hex"),p.Buffer.from(n).toString("hex"))}),r}createTransactionForSettingGuardian(e){let r=["SetGuardian",rW.Address.fromBech32(e.guardianAddress.bech32()).toHex(),p.Buffer.from(e.serviceID).toString("hex")];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitSetGuardian,addDataMovementGas:!0}).build()}createTransactionForGuardingAccount(e){let r=["GuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitGuardAccount,addDataMovementGas:!0}).build()}createTransactionForUnguardingAccount(e){let r=["UnGuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitUnguardAccount,addDataMovementGas:!0}).build()}};h0.AccountTransactionsFactory=vE});var d0=B(hn=>{"use strict";h();var nW=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Va=hn&&hn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&nW(e,t,r)};Object.defineProperty(hn,"__esModule",{value:!0});Va(AO(),hn);Va(OO(),hn);Va(dE(),hn);Va(MO(),hn);Va(mE(),hn);Va(UO(),hn);Va(qO(),hn)});var bE=B(Vn=>{"use strict";h();var iW=Vn&&Vn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sW=Vn&&Vn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oW=Vn&&Vn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iW(e,t,r);return sW(e,t),e},aW=Vn&&Vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.InteractionChecker=void 0;var AE=oW(Ie()),uW=aW((rr(),_e(fr))),EE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new uW.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new AE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new AE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let u=0;u{"use strict";h();Object.defineProperty(g0,"__esModule",{value:!0});g0.Query=void 0;var cW=Ve(),lW=fc(),SE=class{constructor(e){this.caller=e.caller||cW.Address.empty(),this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new lW.ArgSerializer().valuesToStrings(this.args)}};g0.Query=SE});var _E=B(p0=>{"use strict";h();Object.defineProperty(p0,"__esModule",{value:!0});p0.Interaction=void 0;var VO=Ve(),fW=rE(),hW=hr(),IE=Ca(),kO=d0(),dW=bE(),gW=Wf(),TE=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=VO.Address.empty(),this.sender=VO.Address.empty(),this.version=hW.TRANSACTION_VERSION_DEFAULT,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=[]}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){fW.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=new kO.TransactionsFactoryConfig({chainID:this.chainID.valueOf()}),n=new kO.SmartContractTransactionsFactory({config:e}).createTransactionForExecute({sender:this.sender,contract:this.contract.getAddress(),function:this.function.valueOf(),gasLimit:BigInt(this.gasLimit.valueOf()),arguments:this.args,nativeTransferAmount:BigInt(this.value.toString()),tokenTransfers:this.tokenTransfers});return n.chainID=this.chainID.valueOf(),n.nonce=BigInt(this.nonce.valueOf()),n.version=this.version,this.gasPrice&&(n.gasPrice=BigInt(this.gasPrice.valueOf())),n}buildQuery(){return new gW.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withSingleESDTNFTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withMultiESDTNFTTransfer(e){return this.tokenTransfers=e.map(r=>new IE.TokenTransfer(r)),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withVersion(e){return this.version=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new dW.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};p0.Interaction=TE});var CE=B(HO=>{"use strict";h();Object.defineProperty(HO,"__esModule",{value:!0})});var QO=B(yc=>{"use strict";h();Object.defineProperty(yc,"__esModule",{value:!0});yc.bech32m=yc.bech32=void 0;var m0="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jO={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function GO(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=mc(e)^n>>5}e=mc(e);for(let r=0;r=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<a)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=GO(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=mc(c)^w,f+=m0.charAt(w)}for(let d=0;d<6;++d)c=mc(c);c^=e;for(let d=0;d<6;++d){let w=c>>(5-d)*5&31;f+=m0.charAt(w)}return f}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";let a=o.toLowerCase(),c=o.toUpperCase();if(o!==a&&o!==c)return"Mixed-case string "+o;o=a;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),w=o.slice(f+1);if(w.length<6)return"Data too short";let A=GO(d);if(typeof A=="string")return A;let T=[];for(let x=0;x=w.length)&&T.push(V)}return A!==e?"Invalid checksum for "+o:{prefix:d,words:T}}function i(o,u){let a=n(o,u);if(typeof a=="object")return a}function s(o,u){let a=n(o,u);if(typeof a=="object")return a;throw new Error(a)}return{decodeUnsafe:i,decode:s,encode:r,toWords:pW,fromWordsUnsafe:mW,fromWords:yW}}yc.bech32=zO("bech32");yc.bech32m=zO("bech32m")});var WO=B(kn=>{"use strict";h();Object.defineProperty(kn,"__esModule",{value:!0});kn.TokenTransferProperties=kn.TransactionMetadataTransfer=kn.TransactionMetadata=kn.TransactionToDecode=kn.TransactionDecoder=void 0;var KO=QO(),xE=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new ka;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new y0;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new ka;s.transfers||(s.transfers=[]);let o=2;for(let u=0;uo&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),u=new ka;return u.sender=e.sender,u.receiver=o,u.value=s,r.length>4&&(u.functionName=this.hexToString(r[4]),u.functionArgs=r.slice(5)),u.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],u}base64Encode(e){return p.Buffer.from(e).toString("base64")}base64Decode(e){return p.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new ka;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=p.Buffer.from(e,"hex"),n=KO.bech32.toWords(r);return KO.bech32.encode("erd",n)}isAddressValid(e){return p.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return p.Buffer.from(e,"base64").toString("hex")}hexToString(e){return p.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};kn.TransactionDecoder=xE;var y0=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};kn.TransactionToDecode=y0;var ka=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};kn.TransactionMetadata=ka;var OE=class{constructor(){this.value=BigInt(0)}};kn.TransactionMetadataTransfer=OE;var DE=class{};kn.TokenTransferProperties=DE});var PE=B(w0=>{"use strict";h();Object.defineProperty(w0,"__esModule",{value:!0});w0.ReturnCode=void 0;var mt=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};w0.ReturnCode=mt;mt.None=new mt("");mt.Ok=new mt("ok");mt.FunctionNotFound=new mt("function not found");mt.FunctionWrongSignature=new mt("wrong signature for function");mt.ContractNotFound=new mt("contract not found");mt.UserError=new mt("user error");mt.OutOfGas=new mt("out of gas");mt.AccountCollision=new mt("account collision");mt.OutOfFunds=new mt("out of funds");mt.CallStackOverFlow=new mt("call stack overflow");mt.ContractInvalid=new mt("contract invalid");mt.ExecutionFailed=new mt("execution failed");mt.Unknown=new mt("unknown")});var JO=B(v0=>{"use strict";h();Object.defineProperty(v0,"__esModule",{value:!0});v0.ResultsParser=void 0;var wW=WO(),$O=Ve(),YO=Ie(),So=oo(),vW=fc(),wc=PE(),vc;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(vc||(vc={}));var RE;(function(t){t.TooMuchGas="@too much gas provided for processing"})(RE||(RE={}));var AW={argsSerializer:new vW.ArgSerializer},BE=class{constructor(e){e={...AW,...e},this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e);return this.parseOutcomeFromUntypedBundle(n,r)}parseOutcomeFromUntypedBundle(e,r){let n=this.argsSerializer.buffersToValues(e.values,r.output);return{returnCode:e.returnCode,returnMessage:e.returnMessage,values:n,firstValue:n[0],secondValue:n[1],thirdValue:n[2],lastValue:n[n.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return So.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return So.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return So.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return So.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new YO.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new wW.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:wc.ReturnCode.None,returnMessage:wc.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:wc.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(vc.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(vc.OnWriteLog,u=>u.findFirstOrNoneTopic(a=>a.toString().startsWith(RE.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new $O.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(vc.OnWriteLog,a=>a.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),u=s.toString();return{returnCode:s,returnMessage:u,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new $O.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(vc.OnWriteLog,o=>{let u=o.address.bech32()==e.sender.bech32(),a=o.topics[0]?.hex()==n.hex();return u&&a});if(s){let{returnCode:o,returnDataParts:u}=this.sliceDataFieldInParts(s.data),a=o.toString();return{returnCode:o,returnMessage:a,values:u}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||p.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new YO.ErrCannotParseContractResults("no return code");return{returnCode:wc.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){let n=e.topics.map(o=>p.Buffer.from(o.valueOf())).slice(1),i=e.dataPayload?.valueOf()||p.Buffer.from([]),s=e.additionalData?.map(o=>p.Buffer.from(o.valueOf()))||[];return s.length===0&&i.length&&s.push(p.Buffer.from(i)),this.doParseEvent({topics:n,dataItems:s,eventDefinition:r})}doParseEvent(e){let r={},n=e.eventDefinition.inputs.filter(u=>u.indexed),i=this.argsSerializer.buffersToValues(e.topics,n);for(let u=0;u!u.indexed),o=this.argsSerializer.buffersToValues(e.dataItems,s);for(let u=0;u{"use strict";h();Object.defineProperty(E0,"__esModule",{value:!0});E0.SmartContract=void 0;var A0=Ve(),ME=rE(),LE=hr(),EW=Ie(),FE=dE(),UE=mE(),bW=Rn(),XO=XA(),ZO=eE(),eD=_E(),SW=n0(),IW=Wf(),qE=class{constructor(e={}){this.address=A0.Address.empty(),this.methodsExplicit={},this.methods={},this.address=e.address||A0.Address.empty(),this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new ZO.ContractFunction(i);return new eD.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new ZO.ContractFunction(i),u=SW.NativeSerializer.nativeToTypedValues(s||[],n);return new eD.Interaction(e,o,u||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return bW.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()");let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=p.Buffer.from(r.toString(),"hex"),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForDeploy({sender:e,bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}getMetadataPropertiesAsObject(e){let r;return e?r=XO.CodeMetadata.fromBytes(p.Buffer.from(e.toString(),"hex")):r=new XO.CodeMetadata,r.toJSON()}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=Uint8Array.from(p.Buffer.from(r.toString(),"hex")),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForUpgrade({sender:e,contract:this.getAddress(),bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:u,caller:a}){ME.Compatibility.guardAddressIsSetAndNonZero(a,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:u.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi});r=r||[],n=n||0;let d=f.createTransactionForExecute({sender:a,contract:s||this.getAddress(),function:e.toString(),gasLimit:BigInt(i.valueOf()),arguments:r});return d.setChainID(u),d.setValue(n),d.setGasPrice(o??LE.TRANSACTION_MIN_GAS_PRICE),d}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new IW.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new EW.ErrContractHasNoAddress}static computeAddress(e,r){let n=A0.Address.fromBech32(e.bech32());return new A0.AddressComputer().computeContractAddress(n,BigInt(r.valueOf()))}};E0.SmartContract=qE});var rD=B(Io=>{"use strict";h();Object.defineProperty(Io,"__esModule",{value:!0});Io.ContractCallPayloadBuilder=Io.ContractUpgradePayloadBuilder=Io.ContractDeployPayloadBuilder=void 0;var TW=hr(),GE=Ms(),jE=Rn(),_W=fc(),VE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${TW.WasmVirtualMachine}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractDeployPayloadBuilder=VE;var kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractUpgradePayloadBuilder=kE;var HE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=zE(e,this.arguments),new GE.TransactionPayload(e)}};Io.ContractCallPayloadBuilder=HE;function zE(t,e){let{argumentsString:r,count:n}=new _W.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var qn=B(Jt=>{"use strict";h();var CW=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qr=Jt&&Jt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&CW(e,t,r)};Object.defineProperty(Jt,"__esModule",{value:!0});qr(fc(),Jt);qr(vO(),Jt);qr(GA(),Jt);qr(XA(),Jt);qr(eE(),Jt);qr(_E(),Jt);qr(bE(),Jt);qr(CE(),Jt);qr(n0(),Jt);qr(Wf(),Jt);qr(JO(),Jt);qr(PE(),Jt);qr(tD(),Jt);qr(rD(),Jt);qr(dr(),Jt)});var Ac=B(or=>{"use strict";h();Object.defineProperty(or,"__esModule",{value:!0});or.gatherAllEvents=or.findEventsByFirstTopic=or.findEventsByIdentifier=or.findEventsByPredicate=or.SmartContractCallOutcome=or.TransactionOutcome=or.SmartContractResult=or.TransactionLogs=or.TransactionEvent=void 0;var QE=class{constructor(e){this.address="",this.identifier="",this.topics=[],this.dataItems=[],Object.assign(this,e)}};or.TransactionEvent=QE;var $f=class{constructor(e){this.address="",this.events=[],Object.assign(this,e)}};or.TransactionLogs=$f;var KE=class{constructor(e){this.sender="",this.receiver="",this.data=new Uint8Array,this.logs=new $f({}),Object.assign(this,e)}};or.SmartContractResult=KE;var WE=class{constructor(e){this.directSmartContractCallOutcome=new b0({}),this.smartContractResults=[],this.logs=new $f({}),Object.assign(this,e)}};or.TransactionOutcome=WE;var b0=class{constructor(e){this.function="",this.returnDataParts=[],this.returnMessage="",this.returnCode="",Object.assign(this,e)}};or.SmartContractCallOutcome=b0;function $E(t,e){return nD(t).filter(e)}or.findEventsByPredicate=$E;function NW(t,e){return $E(t,r=>r.identifier==e)}or.findEventsByIdentifier=NW;function xW(t,e){return $E(t,r=>r.topics[0]?.toString()==e)}or.findEventsByFirstTopic=xW;function nD(t){let e=[];e.push(...t.logs.events);for(let r of t.smartContractResults)e.push(...r.logs.events);return e}or.gatherAllEvents=nD});var JE=B(S0=>{"use strict";h();Object.defineProperty(S0,"__esModule",{value:!0});S0.TransactionsConverter=void 0;var OW=qn(),DW=Xr(),Ec=Ac(),YE=class{transactionToPlainObject(e){return{nonce:Number(e.nonce),value:e.value.toString(),receiver:e.receiver,sender:e.sender,senderUsername:this.toBase64OrUndefined(e.senderUsername),receiverUsername:this.toBase64OrUndefined(e.receiverUsername),gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:this.toBase64OrUndefined(e.data),chainID:e.chainID.valueOf(),version:e.version,options:e.options==0?void 0:e.options,guardian:e.guardian?e.guardian:void 0,signature:this.toHexOrUndefined(e.signature),guardianSignature:this.toHexOrUndefined(e.guardianSignature)}}toBase64OrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("base64"):void 0}toHexOrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("hex"):void 0}plainObjectToTransaction(e){return new DW.Transaction({nonce:BigInt(e.nonce),value:BigInt(e.value||""),receiver:e.receiver,receiverUsername:this.bufferFromBase64(e.receiverUsername).toString(),sender:e.sender,senderUsername:this.bufferFromBase64(e.senderUsername).toString(),guardian:e.guardian,gasPrice:BigInt(e.gasPrice),gasLimit:BigInt(e.gasLimit),data:this.bufferFromBase64(e.data),chainID:String(e.chainID),version:Number(e.version),options:Number(e.options),signature:this.bufferFromHex(e.signature),guardianSignature:this.bufferFromHex(e.guardianSignature)})}bufferFromBase64(e){return p.Buffer.from(e||"","base64")}bufferFromHex(e){return p.Buffer.from(e||"","hex")}transactionOnNetworkToOutcome(e){let n=new OW.ResultsParser().parseUntypedOutcome(e),i=new Ec.SmartContractCallOutcome({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.values}),s=e.contractResults.items.map(u=>this.smartContractResultOnNetworkToSmartContractResult(u)),o=new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(u=>this.eventOnNetworkToEvent(u))});return new Ec.TransactionOutcome({logs:o,smartContractResults:s,directSmartContractCallOutcome:i})}smartContractResultOnNetworkToSmartContractResult(e){return new Ec.SmartContractResult({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:p.Buffer.from(e.data),logs:new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(r=>this.eventOnNetworkToEvent(r))})})}eventOnNetworkToEvent(e){let r=e.dataPayload?.valueOf()||p.Buffer.from(e.data||""),n=e.additionalData?.map(i=>p.Buffer.from(i.valueOf()))||[];return n.length===0&&r.length&&n.push(p.Buffer.from(r)),new Ec.TransactionEvent({address:e.address.bech32(),identifier:e.identifier,topics:e.topics.map(i=>p.Buffer.from(i.hex(),"hex")),dataItems:n})}};S0.TransactionsConverter=YE});var iD=B(Yi=>{"use strict";h();var PW=Yi&&Yi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RW=Yi&&Yi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BW=Yi&&Yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PW(e,t,r);return RW(e,t),e};Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Hash=void 0;var MW=BW(Ie()),XE=class t{constructor(e){if(!e)this.hash=p.Buffer.from([]);else if(e instanceof p.Buffer)this.hash=e;else if(typeof e=="string")this.hash=p.Buffer.from(e,"hex");else throw new MW.ErrBadType("hash","buffer | string",e)}static empty(){return new t(p.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};Yi.Hash=XE});var Yf=B(Hn=>{"use strict";h();var LW=Hn&&Hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FW=Hn&&Hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),UW=Hn&&Hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LW(e,t,r);return FW(e,t),e};Object.defineProperty(Hn,"__esModule",{value:!0});Hn.interpretSignatureAsBuffer=Hn.Signature=void 0;var sD=UW(Ie()),oD=64,ZE=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof p.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==oD}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=oD)throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Hn.Signature=ZE;function qW(t){if(ArrayBuffer.isView(t))return p.Buffer.from(t);if(t.hex!=null)return p.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Hn.interpretSignatureAsBuffer=qW});var uD=B((F1e,aD)=>{"use strict";h();aD.exports=VW;function VW(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";h();var I0=fD;I0.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bc=new Array(64),lD=new Array(123);for(mi=0;mi<64;)lD[bc[mi]=mi<26?mi+65:mi<52?mi+71:mi<62?mi-4:mi-59|43]=mi++;var mi;I0.encode=function(e,r,n){for(var i=null,s=[],o=0,u=0,a;r>2],a=(c&3)<<4,u=1;break;case 1:s[o++]=bc[a|c>>4],a=(c&15)<<2,u=2;break;case 2:s[o++]=bc[a|c>>6],s[o++]=bc[c&63],u=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return u&&(s[o++]=bc[a],s[o++]=61,u===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var cD="invalid encoding";I0.decode=function(e,r,n){for(var i=n,s=0,o,u=0;u1)break;if((a=lD[a])===void 0)throw Error(cD);switch(s){case 0:o=a,s=1;break;case 1:r[n++]=o<<2|(a&48)>>4,o=a,s=2;break;case 2:r[n++]=(o&15)<<4|(a&60)>>2,o=a,s=3;break;case 3:r[n++]=(o&3)<<6|a,s=0;break}}if(s===1)throw Error(cD);return n-i};I0.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var gD=B((k1e,dD)=>{"use strict";h();dD.exports=T0;function T0(){this._listeners={}}T0.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};T0.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";h();AD.exports=pD(pD);function pD(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(a,c,f){e[0]=a,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],e[0]}function u(a,c){return r[3]=a[c],r[2]=a[c+1],r[1]=a[c+2],r[0]=a[c+3],e[0]}t.readFloatLE=n?o:u,t.readFloatBE=n?u:o}():function(){function e(n,i,s,o){var u=i<0?1:0;if(u&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((u<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((u<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var a=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-a)*8388608)&8388607;n((u<<31|a+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,mD),t.writeFloatBE=e.bind(null,yD);function r(n,i,s){var o=n(i,s),u=(o>>31)*2+1,a=o>>>23&255,c=o&8388607;return a===255?c?NaN:u*(1/0):a===0?u*1401298464324817e-60*c:u*Math.pow(2,a-150)*(c+8388608)}t.readFloatLE=r.bind(null,wD),t.readFloatBE=r.bind(null,vD)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(a,c,f){e[0]=a,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],r[4]=a[c+4],r[5]=a[c+5],r[6]=a[c+6],r[7]=a[c+7],e[0]}function u(a,c){return r[7]=a[c],r[6]=a[c+1],r[5]=a[c+2],r[4]=a[c+3],r[3]=a[c+4],r[2]=a[c+5],r[1]=a[c+6],r[0]=a[c+7],e[0]}t.readDoubleLE=n?o:u,t.readDoubleBE=n?u:o}():function(){function e(n,i,s,o,u,a){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,u,a+i),n(1/o>0?0:2147483648,u,a+s);else if(isNaN(o))n(0,u,a+i),n(2146959360,u,a+s);else if(o>17976931348623157e292)n(0,u,a+i),n((c<<31|2146435072)>>>0,u,a+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,u,a+i),n((c<<31|f/4294967296)>>>0,u,a+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,u,a+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,u,a+s)}}}t.writeDoubleLE=e.bind(null,mD,0,4),t.writeDoubleBE=e.bind(null,yD,4,0);function r(n,i,s,o,u){var a=n(o,u+i),c=n(o,u+s),f=(c>>31)*2+1,d=c>>>20&2047,w=4294967296*(c&1048575)+a;return d===2047?w?NaN:f*(1/0):d===0?f*5e-324*w:f*Math.pow(2,d-1075)*(w+4503599627370496)}t.readDoubleLE=r.bind(null,wD,0,4),t.readDoubleBE=r.bind(null,vD,4,0)}(),t}function mD(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function yD(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function wD(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function vD(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var bD=B((exports,module)=>{"use strict";h();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var ID=B(SD=>{"use strict";h();var eb=SD;eb.length=function(e){for(var r=0,n=0,i=0;i191&&a<224?o[u++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[u++]=55296+(a>>10),o[u++]=56320+(a&1023)):o[u++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,u>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),u=0);return s?(u&&s.push(String.fromCharCode.apply(String,o.slice(0,u))),s.join("")):String.fromCharCode.apply(String,o.slice(0,u))};eb.write=function(e,r,n){for(var i=n,s,o,u=0;u>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(u+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++u,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var _D=B((W1e,TD)=>{"use strict";h();TD.exports=kW;function kW(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);var c=e.call(s,o,o+=a);return o&7&&(o=(o|7)+1),c}}});var ND=B((Y1e,CD)=>{"use strict";h();CD.exports=yr;var Jf=_o();function yr(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ha=yr.zero=new yr(0,0);Ha.toNumber=function(){return 0};Ha.zzEncode=Ha.zzDecode=function(){return this};Ha.length=function(){return 1};var HW=yr.zeroHash="\0\0\0\0\0\0\0\0";yr.fromNumber=function(e){if(e===0)return Ha;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new yr(n,i)};yr.from=function(e){if(typeof e=="number")return yr.fromNumber(e);if(Jf.isString(e))if(Jf.Long)e=Jf.Long.fromString(e);else return yr.fromNumber(parseInt(e,10));return e.low||e.high?new yr(e.low>>>0,e.high>>>0):Ha};yr.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};yr.prototype.toLong=function(e){return Jf.Long?new Jf.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var To=String.prototype.charCodeAt;yr.fromHash=function(e){return e===HW?Ha:new yr((To.call(e,0)|To.call(e,1)<<8|To.call(e,2)<<16|To.call(e,3)<<24)>>>0,(To.call(e,4)|To.call(e,5)<<8|To.call(e,6)<<16|To.call(e,7)<<24)>>>0)};yr.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};yr.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};yr.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};yr.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var _o=B(tb=>{"use strict";h();var we=tb;we.asPromise=uD();we.base64=hD();we.EventEmitter=gD();we.float=ED();we.inquire=bD();we.utf8=ID();we.pool=_D();we.LongBits=ND();we.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);we.global=we.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||tb;we.emptyArray=Object.freeze?Object.freeze([]):[];we.emptyObject=Object.freeze?Object.freeze({}):{};we.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};we.isString=function(e){return typeof e=="string"||e instanceof String};we.isObject=function(e){return e&&typeof e=="object"};we.isset=we.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};we.Buffer=function(){try{var t=we.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();we._Buffer_from=null;we._Buffer_allocUnsafe=null;we.newBuffer=function(e){return typeof e=="number"?we.Buffer?we._Buffer_allocUnsafe(e):new we.Array(e):we.Buffer?we._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};we.Array=typeof Uint8Array<"u"?Uint8Array:Array;we.Long=we.global.dcodeIO&&we.global.dcodeIO.Long||we.global.Long||we.inquire("long");we.key2Re=/^true|false|0|1$/;we.key32Re=/^-?(?:0|[1-9][0-9]*)$/;we.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;we.longToHash=function(e){return e?we.LongBits.from(e).toHash():we.LongBits.zeroHash};we.longFromHash=function(e,r){var n=we.LongBits.fromHash(e);return we.Long?we.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function xD(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};we.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";h();BD.exports=Ue;var Gn=_o(),rb,_0=Gn.LongBits,DD=Gn.base64,PD=Gn.utf8;function Xf(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function ib(){}function GW(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Xf(ib,0,0),this.tail=this.head,this.states=null}var RD=function(){return Gn.Buffer?function(){return(Ue.create=function(){return new rb})()}:function(){return new Ue}};Ue.create=RD();Ue.alloc=function(e){return new Gn.Array(e)};Gn.Array!==Array&&(Ue.alloc=Gn.pool(Ue.alloc,Gn.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Xf(e,r,n),this.len+=r,this};function sb(t,e,r){e[r]=t&255}function jW(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function ob(t,e){this.len=t,this.next=void 0,this.val=e}ob.prototype=Object.create(Xf.prototype);ob.prototype.fn=jW;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ob((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(ab,10,_0.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ab(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=_0.from(e);return this._push(ab,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=_0.from(e).zzEncode();return this._push(ab,r.length(),r)};Ue.prototype.bool=function(e){return this._push(sb,1,e?1:0)};function nb(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(nb,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=_0.from(e);return this._push(nb,4,r.lo)._push(nb,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Gn.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Gn.float.writeDoubleLE,8,e)};var zW=Gn.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(sb,1,0);if(Gn.isString(e)){var n=Ue.alloc(r=DD.length(e));DD.decode(e,n,0),e=n}return this.uint32(r)._push(zW,r,e)};Ue.prototype.string=function(e){var r=PD.length(e);return r?this.uint32(r)._push(PD.write,r,e):this._push(sb,1,0)};Ue.prototype.fork=function(){return this.states=new GW(this),this.head=this.tail=new Xf(ib,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xf(ib,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){rb=t,Ue.create=RD(),rb._configure()}});var FD=B((rwe,LD)=>{"use strict";h();LD.exports=Ji;var MD=ub();(Ji.prototype=Object.create(MD.prototype)).constructor=Ji;var Co=_o();function Ji(){MD.call(this)}Ji._configure=function(){Ji.alloc=Co._Buffer_allocUnsafe,Ji.writeBytesBuffer=Co.Buffer&&Co.Buffer.prototype instanceof Uint8Array&&Co.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Ji.writeBytesBuffer,r,e),this};function QW(t,e,r){t.length<40?Co.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ji.prototype.string=function(e){var r=Co.Buffer.byteLength(e);return this.uint32(r),r&&this._push(QW,r,e),this};Ji._configure()});var fb=B((iwe,HD)=>{"use strict";h();HD.exports=Xt;var yi=_o(),lb,VD=yi.LongBits,KW=yi.utf8;function wi(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Xt(t){this.buf=t,this.pos=0,this.len=t.length}var UD=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Xt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Xt(e);throw Error("illegal buffer")},kD=function(){return yi.Buffer?function(r){return(Xt.create=function(i){return yi.Buffer.isBuffer(i)?new lb(i):UD(i)})(r)}:UD};Xt.create=kD();Xt.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Xt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wi(this,10);return e}}();Xt.prototype.int32=function(){return this.uint32()|0};Xt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function cb(){var t=new VD(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw wi(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw wi(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Xt.prototype.bool=function(){return this.uint32()!==0};function C0(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Xt.prototype.fixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)};Xt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)|0};function qD(){if(this.pos+8>this.len)throw wi(this,8);return new VD(C0(this.buf,this.pos+=4),C0(this.buf,this.pos+=4))}Xt.prototype.float=function(){if(this.pos+4>this.len)throw wi(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Xt.prototype.double=function(){if(this.pos+8>this.len)throw wi(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Xt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw wi(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var i=yi.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Xt.prototype.string=function(){var e=this.bytes();return KW.read(e,0,e.length)};Xt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wi(this);while(this.buf[this.pos++]&128);return this};Xt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Xt._configure=function(t){lb=t,Xt.create=kD(),lb._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Xt.prototype,{int64:function(){return cb.call(this)[e](!1)},uint64:function(){return cb.call(this)[e](!0)},sint64:function(){return cb.call(this).zzDecode()[e](!1)},fixed64:function(){return qD.call(this)[e](!0)},sfixed64:function(){return qD.call(this)[e](!1)}})}});var QD=B((owe,zD)=>{"use strict";h();zD.exports=Ga;var jD=fb();(Ga.prototype=Object.create(jD.prototype)).constructor=Ga;var GD=_o();function Ga(t){jD.call(this,t)}Ga._configure=function(){GD.Buffer&&(Ga.prototype._slice=GD.Buffer.prototype.slice)};Ga.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ga._configure()});var WD=B((uwe,KD)=>{"use strict";h();KD.exports=Zf;var hb=_o();(Zf.prototype=Object.create(hb.EventEmitter.prototype)).constructor=Zf;function Zf(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");hb.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Zf.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return hb.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(a,c){if(a)return o.emit("error",a,e),s(a);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(u){o.emit("error",u,e),setTimeout(function(){s(u)},0);return}};Zf.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var YD=B($D=>{"use strict";h();var WW=$D;WW.Service=WD()});var XD=B((hwe,JD)=>{"use strict";h();JD.exports={}});var t8=B(e8=>{"use strict";h();var tn=e8;tn.build="minimal";tn.Writer=ub();tn.BufferWriter=FD();tn.Reader=fb();tn.BufferReader=QD();tn.util=_o();tn.rpc=YD();tn.roots=XD();tn.configure=ZD;function ZD(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}ZD()});var n8=B((mwe,r8)=>{"use strict";h();r8.exports=t8()});var s8=B((i8,eh)=>{"use strict";h();(function(t,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof Bd=="function"&&typeof eh=="object"&&eh&&eh.exports&&(eh.exports=e(n8()))})(i8,function(t){"use strict";var e=t.Reader,r=t.Writer,n=t.util,i=t.roots.default||(t.roots.default={});return i.proto=function(){var s={};return s.Transaction=function(){function o(u){if(u)for(var a=Object.keys(u),c=0;c>>3){case 1:{d.Nonce=a.uint64();break}case 2:{d.Value=a.bytes();break}case 3:{d.RcvAddr=a.bytes();break}case 4:{d.RcvUserName=a.bytes();break}case 5:{d.SndAddr=a.bytes();break}case 6:{d.SndUserName=a.bytes();break}case 7:{d.GasPrice=a.uint64();break}case 8:{d.GasLimit=a.uint64();break}case 9:{d.Data=a.bytes();break}case 10:{d.ChainID=a.bytes();break}case 11:{d.Version=a.uint32();break}case 12:{d.Signature=a.bytes();break}case 13:{d.Options=a.uint32();break}case 14:{d.GuardianAddr=a.bytes();break}case 15:{d.GuardianSignature=a.bytes();break}default:a.skipType(w&7);break}}return d},o.decodeDelimited=function(a){return a instanceof e||(a=new e(a)),this.decode(a,a.uint32())},o.verify=function(a){return typeof a!="object"||a===null?"object expected":a.Nonce!=null&&a.hasOwnProperty("Nonce")&&!n.isInteger(a.Nonce)&&!(a.Nonce&&n.isInteger(a.Nonce.low)&&n.isInteger(a.Nonce.high))?"Nonce: integer|Long expected":a.Value!=null&&a.hasOwnProperty("Value")&&!(a.Value&&typeof a.Value.length=="number"||n.isString(a.Value))?"Value: buffer expected":a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&!(a.RcvAddr&&typeof a.RcvAddr.length=="number"||n.isString(a.RcvAddr))?"RcvAddr: buffer expected":a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&!(a.RcvUserName&&typeof a.RcvUserName.length=="number"||n.isString(a.RcvUserName))?"RcvUserName: buffer expected":a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&!(a.SndAddr&&typeof a.SndAddr.length=="number"||n.isString(a.SndAddr))?"SndAddr: buffer expected":a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&!(a.SndUserName&&typeof a.SndUserName.length=="number"||n.isString(a.SndUserName))?"SndUserName: buffer expected":a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&!n.isInteger(a.GasPrice)&&!(a.GasPrice&&n.isInteger(a.GasPrice.low)&&n.isInteger(a.GasPrice.high))?"GasPrice: integer|Long expected":a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&!n.isInteger(a.GasLimit)&&!(a.GasLimit&&n.isInteger(a.GasLimit.low)&&n.isInteger(a.GasLimit.high))?"GasLimit: integer|Long expected":a.Data!=null&&a.hasOwnProperty("Data")&&!(a.Data&&typeof a.Data.length=="number"||n.isString(a.Data))?"Data: buffer expected":a.ChainID!=null&&a.hasOwnProperty("ChainID")&&!(a.ChainID&&typeof a.ChainID.length=="number"||n.isString(a.ChainID))?"ChainID: buffer expected":a.Version!=null&&a.hasOwnProperty("Version")&&!n.isInteger(a.Version)?"Version: integer expected":a.Signature!=null&&a.hasOwnProperty("Signature")&&!(a.Signature&&typeof a.Signature.length=="number"||n.isString(a.Signature))?"Signature: buffer expected":a.Options!=null&&a.hasOwnProperty("Options")&&!n.isInteger(a.Options)?"Options: integer expected":a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&!(a.GuardianAddr&&typeof a.GuardianAddr.length=="number"||n.isString(a.GuardianAddr))?"GuardianAddr: buffer expected":a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&!(a.GuardianSignature&&typeof a.GuardianSignature.length=="number"||n.isString(a.GuardianSignature))?"GuardianSignature: buffer expected":null},o.fromObject=function(a){if(a instanceof i.proto.Transaction)return a;var c=new i.proto.Transaction;return a.Nonce!=null&&(n.Long?(c.Nonce=n.Long.fromValue(a.Nonce)).unsigned=!0:typeof a.Nonce=="string"?c.Nonce=parseInt(a.Nonce,10):typeof a.Nonce=="number"?c.Nonce=a.Nonce:typeof a.Nonce=="object"&&(c.Nonce=new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0))),a.Value!=null&&(typeof a.Value=="string"?n.base64.decode(a.Value,c.Value=n.newBuffer(n.base64.length(a.Value)),0):a.Value.length>=0&&(c.Value=a.Value)),a.RcvAddr!=null&&(typeof a.RcvAddr=="string"?n.base64.decode(a.RcvAddr,c.RcvAddr=n.newBuffer(n.base64.length(a.RcvAddr)),0):a.RcvAddr.length>=0&&(c.RcvAddr=a.RcvAddr)),a.RcvUserName!=null&&(typeof a.RcvUserName=="string"?n.base64.decode(a.RcvUserName,c.RcvUserName=n.newBuffer(n.base64.length(a.RcvUserName)),0):a.RcvUserName.length>=0&&(c.RcvUserName=a.RcvUserName)),a.SndAddr!=null&&(typeof a.SndAddr=="string"?n.base64.decode(a.SndAddr,c.SndAddr=n.newBuffer(n.base64.length(a.SndAddr)),0):a.SndAddr.length>=0&&(c.SndAddr=a.SndAddr)),a.SndUserName!=null&&(typeof a.SndUserName=="string"?n.base64.decode(a.SndUserName,c.SndUserName=n.newBuffer(n.base64.length(a.SndUserName)),0):a.SndUserName.length>=0&&(c.SndUserName=a.SndUserName)),a.GasPrice!=null&&(n.Long?(c.GasPrice=n.Long.fromValue(a.GasPrice)).unsigned=!0:typeof a.GasPrice=="string"?c.GasPrice=parseInt(a.GasPrice,10):typeof a.GasPrice=="number"?c.GasPrice=a.GasPrice:typeof a.GasPrice=="object"&&(c.GasPrice=new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0))),a.GasLimit!=null&&(n.Long?(c.GasLimit=n.Long.fromValue(a.GasLimit)).unsigned=!0:typeof a.GasLimit=="string"?c.GasLimit=parseInt(a.GasLimit,10):typeof a.GasLimit=="number"?c.GasLimit=a.GasLimit:typeof a.GasLimit=="object"&&(c.GasLimit=new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0))),a.Data!=null&&(typeof a.Data=="string"?n.base64.decode(a.Data,c.Data=n.newBuffer(n.base64.length(a.Data)),0):a.Data.length>=0&&(c.Data=a.Data)),a.ChainID!=null&&(typeof a.ChainID=="string"?n.base64.decode(a.ChainID,c.ChainID=n.newBuffer(n.base64.length(a.ChainID)),0):a.ChainID.length>=0&&(c.ChainID=a.ChainID)),a.Version!=null&&(c.Version=a.Version>>>0),a.Signature!=null&&(typeof a.Signature=="string"?n.base64.decode(a.Signature,c.Signature=n.newBuffer(n.base64.length(a.Signature)),0):a.Signature.length>=0&&(c.Signature=a.Signature)),a.Options!=null&&(c.Options=a.Options>>>0),a.GuardianAddr!=null&&(typeof a.GuardianAddr=="string"?n.base64.decode(a.GuardianAddr,c.GuardianAddr=n.newBuffer(n.base64.length(a.GuardianAddr)),0):a.GuardianAddr.length>=0&&(c.GuardianAddr=a.GuardianAddr)),a.GuardianSignature!=null&&(typeof a.GuardianSignature=="string"?n.base64.decode(a.GuardianSignature,c.GuardianSignature=n.newBuffer(n.base64.length(a.GuardianSignature)),0):a.GuardianSignature.length>=0&&(c.GuardianSignature=a.GuardianSignature)),c},o.toObject=function(a,c){c||(c={});var f={};if(c.defaults){if(n.Long){var d=new n.Long(0,0,!0);f.Nonce=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.Nonce=c.longs===String?"0":0;if(c.bytes===String?f.Value="":(f.Value=[],c.bytes!==Array&&(f.Value=n.newBuffer(f.Value))),c.bytes===String?f.RcvAddr="":(f.RcvAddr=[],c.bytes!==Array&&(f.RcvAddr=n.newBuffer(f.RcvAddr))),c.bytes===String?f.RcvUserName="":(f.RcvUserName=[],c.bytes!==Array&&(f.RcvUserName=n.newBuffer(f.RcvUserName))),c.bytes===String?f.SndAddr="":(f.SndAddr=[],c.bytes!==Array&&(f.SndAddr=n.newBuffer(f.SndAddr))),c.bytes===String?f.SndUserName="":(f.SndUserName=[],c.bytes!==Array&&(f.SndUserName=n.newBuffer(f.SndUserName))),n.Long){var d=new n.Long(0,0,!0);f.GasPrice=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasPrice=c.longs===String?"0":0;if(n.Long){var d=new n.Long(0,0,!0);f.GasLimit=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasLimit=c.longs===String?"0":0;c.bytes===String?f.Data="":(f.Data=[],c.bytes!==Array&&(f.Data=n.newBuffer(f.Data))),c.bytes===String?f.ChainID="":(f.ChainID=[],c.bytes!==Array&&(f.ChainID=n.newBuffer(f.ChainID))),f.Version=0,c.bytes===String?f.Signature="":(f.Signature=[],c.bytes!==Array&&(f.Signature=n.newBuffer(f.Signature))),f.Options=0,c.bytes===String?f.GuardianAddr="":(f.GuardianAddr=[],c.bytes!==Array&&(f.GuardianAddr=n.newBuffer(f.GuardianAddr))),c.bytes===String?f.GuardianSignature="":(f.GuardianSignature=[],c.bytes!==Array&&(f.GuardianSignature=n.newBuffer(f.GuardianSignature)))}return a.Nonce!=null&&a.hasOwnProperty("Nonce")&&(typeof a.Nonce=="number"?f.Nonce=c.longs===String?String(a.Nonce):a.Nonce:f.Nonce=c.longs===String?n.Long.prototype.toString.call(a.Nonce):c.longs===Number?new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0):a.Nonce),a.Value!=null&&a.hasOwnProperty("Value")&&(f.Value=c.bytes===String?n.base64.encode(a.Value,0,a.Value.length):c.bytes===Array?Array.prototype.slice.call(a.Value):a.Value),a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&(f.RcvAddr=c.bytes===String?n.base64.encode(a.RcvAddr,0,a.RcvAddr.length):c.bytes===Array?Array.prototype.slice.call(a.RcvAddr):a.RcvAddr),a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&(f.RcvUserName=c.bytes===String?n.base64.encode(a.RcvUserName,0,a.RcvUserName.length):c.bytes===Array?Array.prototype.slice.call(a.RcvUserName):a.RcvUserName),a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&(f.SndAddr=c.bytes===String?n.base64.encode(a.SndAddr,0,a.SndAddr.length):c.bytes===Array?Array.prototype.slice.call(a.SndAddr):a.SndAddr),a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&(f.SndUserName=c.bytes===String?n.base64.encode(a.SndUserName,0,a.SndUserName.length):c.bytes===Array?Array.prototype.slice.call(a.SndUserName):a.SndUserName),a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&(typeof a.GasPrice=="number"?f.GasPrice=c.longs===String?String(a.GasPrice):a.GasPrice:f.GasPrice=c.longs===String?n.Long.prototype.toString.call(a.GasPrice):c.longs===Number?new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0):a.GasPrice),a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&(typeof a.GasLimit=="number"?f.GasLimit=c.longs===String?String(a.GasLimit):a.GasLimit:f.GasLimit=c.longs===String?n.Long.prototype.toString.call(a.GasLimit):c.longs===Number?new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0):a.GasLimit),a.Data!=null&&a.hasOwnProperty("Data")&&(f.Data=c.bytes===String?n.base64.encode(a.Data,0,a.Data.length):c.bytes===Array?Array.prototype.slice.call(a.Data):a.Data),a.ChainID!=null&&a.hasOwnProperty("ChainID")&&(f.ChainID=c.bytes===String?n.base64.encode(a.ChainID,0,a.ChainID.length):c.bytes===Array?Array.prototype.slice.call(a.ChainID):a.ChainID),a.Version!=null&&a.hasOwnProperty("Version")&&(f.Version=a.Version),a.Signature!=null&&a.hasOwnProperty("Signature")&&(f.Signature=c.bytes===String?n.base64.encode(a.Signature,0,a.Signature.length):c.bytes===Array?Array.prototype.slice.call(a.Signature):a.Signature),a.Options!=null&&a.hasOwnProperty("Options")&&(f.Options=a.Options),a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&(f.GuardianAddr=c.bytes===String?n.base64.encode(a.GuardianAddr,0,a.GuardianAddr.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianAddr):a.GuardianAddr),a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&(f.GuardianSignature=c.bytes===String?n.base64.encode(a.GuardianSignature,0,a.GuardianSignature.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianSignature):a.GuardianSignature),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,t.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Transaction"},o}(),s}(),i})});var o8=B(jn=>{"use strict";h();var $W=jn&&jn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),YW=jn&&jn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),JW=jn&&jn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$W(e,t,r);return YW(e,t),e},XW=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.ProtoSerializer=void 0;var ZW=XW((rr(),_e(fr))),db=Ve(),e$=hr(),t$=JW(Ie()),r$=Bu(),gb=class{serializeTransaction(e){let r=s8().proto,n=new db.Address(e.getReceiver().bech32()).pubkey(),i=new db.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?p.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?p.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:p.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==e$.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let a=e.getGuardian();s.GuardianAddr=new db.Address(a.bech32()).pubkey(),s.GuardianSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return p.Buffer.from(o)}serializeTransactionValue(e){let r=new ZW.default(e.toString());if(r.isZero())return p.Buffer.from([0,0]);let n=r$.bigIntToBuffer(r);return n=p.Buffer.concat([p.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new t$.ErrUnsupportedOperation("deserializeTransaction")}};jn.ProtoSerializer=gb});var a8=B(ja=>{"use strict";h();var n$=ja&&ja.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),i$=ja&&ja.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&n$(e,t,r)};Object.defineProperty(ja,"__esModule",{value:!0});i$(o8(),ja)});var N0=B(zn=>{"use strict";h();var s$=zn&&zn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),o$=zn&&zn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a$=zn&&zn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&s$(e,t,r);return o$(e,t),e},u$=zn&&zn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zn,"__esModule",{value:!0});zn.TransactionComputer=void 0;var th=a$(Ie()),u8=u$((rr(),_e(fr))),c$=a8(),l$=Xr(),rn=hr(),f$=YA(),h$=sf(),d$=32,pb=class{constructor(){}computeTransactionFee(e,r){let n=BigInt(r.MinGasLimit+e.data.length*r.GasPerDataByte);if(n>e.gasLimit)throw new th.ErrNotEnoughGas(parseInt(e.gasLimit.toString(),10));let i=e.gasPrice,s=n*i;if(n===e.gasLimit)return s;let o=e.gasLimit-n,u=BigInt(new u8.default(i.toString()).multipliedBy(new u8.default(r.GasPriceModifier)).toFixed(0)),a=o*u;return s+a}computeBytesForSigning(e){this.ensureValidTransactionFields(e);let r=this.toPlainObjectForSigning(e),n=JSON.stringify(r);return new Uint8Array(p.Buffer.from(n))}computeBytesForVerifying(e){return this.hasOptionsSetForHashSigning(e)?this.computeHashForSigning(e):this.computeBytesForSigning(e)}computeHashForSigning(e){let r=this.toPlainObjectForSigning(e),n=p.Buffer.from(JSON.stringify(r));return h$("keccak256").update(n).digest()}computeTransactionHash(e){let n=new c$.ProtoSerializer().serializeTransaction(new l$.Transaction(e)),i=f$(d$).update(n).digest("hex");return p.Buffer.from(i,"hex")}hasOptionsSetForGuardedTransaction(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_GUARDED)==rn.TRANSACTION_OPTIONS_TX_GUARDED}hasOptionsSetForHashSigning(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_HASH_SIGN)==rn.TRANSACTION_OPTIONS_TX_HASH_SIGN}applyGuardian(e,r){e.version= ${rn.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`)}};zn.TransactionComputer=pb});var Xr=B(Sc=>{"use strict";h();Object.defineProperty(Sc,"__esModule",{value:!0});Sc.TransactionHash=Sc.Transaction=void 0;var c8=(rr(),_e(fr)),mb=Ve(),yb=hr(),l8=JE(),g$=iD(),f8=$l(),h8=Yf(),p$=Ms(),wb=N0(),vb=class{constructor(e){this.nonce=BigInt(e.nonce?.valueOf()||0n),this.value=e.value?BigInt(new c8.BigNumber(e.value.toString()).toFixed(0)):0n,this.sender=this.addressAsBech32(e.sender),this.receiver=this.addressAsBech32(e.receiver),this.senderUsername=e.senderUsername||"",this.receiverUsername=e.receiverUsername||"",this.gasPrice=BigInt(e.gasPrice?.valueOf()||yb.TRANSACTION_MIN_GAS_PRICE),this.gasLimit=BigInt(e.gasLimit.valueOf()),this.data=e.data?.valueOf()||new Uint8Array,this.chainID=e.chainID.valueOf(),this.version=Number(e.version?.valueOf()||yb.TRANSACTION_VERSION_DEFAULT),this.options=Number(e.options?.valueOf()||yb.TRANSACTION_OPTIONS_DEFAULT),this.guardian=e.guardian?this.addressAsBech32(e.guardian):"",this.signature=e.signature||p.Buffer.from([]),this.guardianSignature=e.guardianSignature||p.Buffer.from([])}addressAsBech32(e){return typeof e=="string"?e:e.bech32()}getNonce(){return Number(this.nonce)}setNonce(e){this.nonce=BigInt(e.valueOf())}getValue(){return this.value}setValue(e){this.value=BigInt(e.toString())}getSender(){return mb.Address.fromBech32(this.sender)}setSender(e){this.sender=typeof e=="string"?e:e.bech32()}getReceiver(){return mb.Address.fromBech32(this.receiver)}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return new mb.Address(this.guardian)}getGasPrice(){return Number(this.gasPrice)}setGasPrice(e){this.gasPrice=BigInt(e.valueOf())}getGasLimit(){return Number(this.gasLimit)}setGasLimit(e){this.gasLimit=BigInt(e.valueOf())}getData(){return new p$.TransactionPayload(p.Buffer.from(this.data))}getChainID(){return this.chainID}setChainID(e){this.chainID=e.valueOf()}getVersion(){return new f8.TransactionVersion(this.version)}setVersion(e){this.version=e.valueOf()}getOptions(){return new f8.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=e.valueOf()}getSignature(){return p.Buffer.from(this.signature)}getGuardianSignature(){return p.Buffer.from(this.guardianSignature)}setGuardian(e){this.guardian=typeof e=="string"?e:e.bech32()}getHash(){return x0.compute(this)}serializeForSigning(){let r=new wb.TransactionComputer().computeBytesForSigning(this);return p.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){return new l8.TransactionsConverter().transactionToPlainObject(this)}static fromPlainObject(e){return new l8.TransactionsConverter().plainObjectToTransaction(e)}applySignature(e){this.signature=h8.interpretSignatureAsBuffer(e)}applyGuardianSignature(e){this.guardianSignature=h8.interpretSignatureAsBuffer(e)}toSendable(){return this.toPlainObject()}computeFee(e){let n=new wb.TransactionComputer().computeTransactionFee(this,e);return new c8.BigNumber(n.toString())}};Sc.Transaction=vb;var x0=class t extends g$.Hash{constructor(e){super(e)}static compute(e){let n=new wb.TransactionComputer().computeTransactionHash(e);return new t(p.Buffer.from(n).toString("hex"))}};Sc.TransactionHash=x0});var g8=B(O0=>{"use strict";h();Object.defineProperty(O0,"__esModule",{value:!0});O0.TokenOperationsFactory=void 0;var Ab=hr(),m$=oo(),d8=$l(),y$=Xr(),w$=Ms(),ae=$d(),Eb=class{constructor(e){this.config=e,this.trueAsHex=ae.utf8ToHex("true"),this.falseAsHex=ae.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.initialSupply),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){m$.Logger.info(` +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}boolToString(e){return e?this.trueAsString:this.falseAsString}};o0.TokenManagementTransactionsFactory=pE});var yE=D(a0=>{"use strict";h();Object.defineProperty(a0,"__esModule",{value:!0});a0.TransactionsFactoryConfig=void 0;var dW=hr(),mE=class{constructor(e){this.chainID=e.chainID,this.addressHrp=dW.DEFAULT_HRP,this.minGasLimit=50000n,this.gasLimitPerByte=1500n,this.gasLimitIssue=60000000n,this.gasLimitToggleBurnRoleGlobally=60000000n,this.gasLimitEsdtLocalMint=300000n,this.gasLimitEsdtLocalBurn=300000n,this.gasLimitSetSpecialRole=60000000n,this.gasLimitPausing=60000000n,this.gasLimitFreezing=60000000n,this.gasLimitWiping=60000000n,this.gasLimitEsdtNftCreate=3000000n,this.gasLimitEsdtNftUpdateAttributes=1000000n,this.gasLimitEsdtNftAddQuantity=1000000n,this.gasLimitEsdtNftBurn=1000000n,this.gasLimitStorePerByte=10000n,this.issueCost=50000000000000000n,this.gasLimitStake=5000000n,this.gasLimitUnstake=5000000n,this.gasLimitUnbond=5000000n,this.gasLimitCreateDelegationContract=50000000n,this.gasLimitDelegationOperations=1000000n,this.additionalGasLimitPerValidatorNode=6000000n,this.additionalGasLimitForDelegationOperations=10000000n,this.gasLimitSaveKeyValue=100000n,this.gasLimitPersistPerByte=1000n,this.gasLimitSetGuardian=250000n,this.gasLimitGuardAccount=250000n,this.gasLimitUnguardAccount=250000n,this.gasLimitESDTTransfer=200000n,this.gasLimitESDTNFTTransfer=200000n,this.gasLimitMultiESDTNFTTransfer=200000n,this.gasLimitClaimDeveloperRewards=6000000n,this.gasLimitChangeOwnerAddress=6000000n}};a0.TransactionsFactoryConfig=mE});var FO=D(u0=>{"use strict";h();Object.defineProperty(u0,"__esModule",{value:!0});u0.TransferTransactionsFactory=void 0;var bo=Ie(),en=qn(),gW=_a(),Kf=Xr(),wE=Ms(),pW=hE(),MO=gc(),mW=1e5,LO=8e5,vE=class{constructor(e){this.isGasEstimator(e)?this.gasEstimator=e:(this.config=e.config,this.tokenComputer=new gW.TokenComputer,this.tokenTransfersDataBuilder=new pW.TokenTransfersDataBuilder)}isGasEstimator(e){return typeof e=="object"&&typeof e.forEGLDTransfer=="function"&&typeof e.forESDTTransfer=="function"&&typeof e.forESDTNFTTransfer=="function"&&typeof e.forMultiESDTNFTTransfer=="function"}isGasEstimatorDefined(){return this.gasEstimator!==void 0}ensureMembersAreDefined(){if(this.config===void 0)throw new bo.Err("'config' is not defined");if(this.tokenTransfersDataBuilder===void 0)throw new bo.Err("`dataArgsBuilder is not defined`");if(this.tokenComputer===void 0)throw new bo.Err("`tokenComputer is not defined`")}createTransactionForNativeTokenTransfer(e){this.ensureMembersAreDefined();let r=e.data||new Uint8Array;return new Kf.Transaction({sender:e.sender.bech32(),receiver:e.receiver.bech32(),chainID:this.config.chainID,gasLimit:this.computeGasForMoveBalance(this.config,r),data:r,value:e.nativeAmount})}createTransactionForESDTTokenTransfer(e){this.ensureMembersAreDefined();let r=e.tokenTransfers.length;if(r===0)throw new bo.ErrBadUsage("No token transfer has been provided");if(r===1)return this.createSingleESDTTransferTransaction(e);let n=this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(e.receiver,e.tokenTransfers),i=this.config.gasLimitMultiESDTNFTTransfer*BigInt(r)+BigInt(LO);return new MO.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:n,gasLimit:i,addDataMovementGas:!0}).build()}createEGLDTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.");let r=e.data?.length()||0,n=this.gasEstimator.forEGLDTransfer(r);return new Kf.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||n,data:e.data,chainID:e.chainID})}createESDTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.U64Value(e.tokenTransfer.nonce),new en.BigUIntValue(e.tokenTransfer.valueOf()),new en.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let r=[new en.AddressValue(e.destination),new en.U16Value(e.tokenTransfers.length)];for(let a of e.tokenTransfers)r.push(en.BytesValue.fromUTF8(a.tokenIdentifier),new en.U64Value(a.nonce),new en.BigUIntValue(a.valueOf()));let{argumentsString:n}=new en.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new wE.TransactionPayload(i),o=s.length()||0,u=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||u,data:s,chainID:e.chainID})}createSingleESDTTransferTransaction(e){this.ensureMembersAreDefined();let r=[],n=e.tokenTransfers[0],i=0n,s=e.receiver;return this.tokenComputer.isFungible(n.token)?(r=this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(n),i=this.config.gasLimitESDTTransfer+BigInt(mW)):(r=this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(n,s),i=this.config.gasLimitESDTNFTTransfer+BigInt(LO),s=e.sender),new MO.TransactionBuilder({config:this.config,sender:e.sender,receiver:s,dataParts:r,gasLimit:i,addDataMovementGas:!0}).build()}computeGasForMoveBalance(e,r){return e.minGasLimit+e.gasLimitPerByte*BigInt(r.length)}};u0.TransferTransactionsFactory=vE});var UO=D(l0=>{"use strict";h();Object.defineProperty(l0,"__esModule",{value:!0});l0.AccountTransactionsFactory=void 0;var yW=Ve(),c0=gc(),AE=class{constructor(e){this.config=e.config}createTransactionForSavingKeyValue(e){let r="SaveKeyValue",n=this.computeDataPartsForSavingKeyValue(e.keyValuePairs),i=[r,...n],s=this.computeExtraGasForSavingKeyValue(e.keyValuePairs);return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:i,gasLimit:s,addDataMovementGas:!0}).build()}computeExtraGasForSavingKeyValue(e){let r=0n;return e.forEach((n,i)=>{r+=this.config.gasLimitPersistPerByte*BigInt(i.length+n.length)+this.config.gasLimitStorePerByte*BigInt(n.length)}),r+this.config.gasLimitSaveKeyValue}computeDataPartsForSavingKeyValue(e){let r=[];return e.forEach((n,i)=>{r.push(p.Buffer.from(i).toString("hex"),p.Buffer.from(n).toString("hex"))}),r}createTransactionForSettingGuardian(e){let r=["SetGuardian",yW.Address.fromBech32(e.guardianAddress.bech32()).toHex(),p.Buffer.from(e.serviceID).toString("hex")];return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitSetGuardian,addDataMovementGas:!0}).build()}createTransactionForGuardingAccount(e){let r=["GuardAccount"];return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitGuardAccount,addDataMovementGas:!0}).build()}createTransactionForUnguardingAccount(e){let r=["UnGuardAccount"];return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitUnguardAccount,addDataMovementGas:!0}).build()}};l0.AccountTransactionsFactory=AE});var f0=D(hn=>{"use strict";h();var wW=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qa=hn&&hn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wW(e,t,r)};Object.defineProperty(hn,"__esModule",{value:!0});qa(vO(),hn);qa(xO(),hn);qa(gE(),hn);qa(BO(),hn);qa(yE(),hn);qa(FO(),hn);qa(UO(),hn)});var SE=D(Vn=>{"use strict";h();var vW=Vn&&Vn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),AW=Vn&&Vn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),EW=Vn&&Vn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vW(e,t,r);return AW(e,t),e},bW=Vn&&Vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.InteractionChecker=void 0;var EE=EW(Ie()),SW=bW((rr(),_e(fr))),bE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new SW.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new EE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new EE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let u=0;u{"use strict";h();Object.defineProperty(h0,"__esModule",{value:!0});h0.Query=void 0;var IW=Ve(),TW=fc(),IE=class{constructor(e){this.caller=e.caller||IW.Address.empty(),this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new TW.ArgSerializer().valuesToStrings(this.args)}};h0.Query=IE});var CE=D(d0=>{"use strict";h();Object.defineProperty(d0,"__esModule",{value:!0});d0.Interaction=void 0;var qO=Ve(),_W=nE(),CW=hr(),TE=_a(),VO=f0(),NW=SE(),xW=Wf(),_E=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=qO.Address.empty(),this.sender=qO.Address.empty(),this.version=CW.TRANSACTION_VERSION_DEFAULT,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=[]}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){_W.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=new VO.TransactionsFactoryConfig({chainID:this.chainID.valueOf()}),n=new VO.SmartContractTransactionsFactory({config:e}).createTransactionForExecute({sender:this.sender,contract:this.contract.getAddress(),function:this.function.valueOf(),gasLimit:BigInt(this.gasLimit.valueOf()),arguments:this.args,nativeTransferAmount:BigInt(this.value.toString()),tokenTransfers:this.tokenTransfers});return n.chainID=this.chainID.valueOf(),n.nonce=BigInt(this.nonce.valueOf()),n.version=this.version,this.gasPrice&&(n.gasPrice=BigInt(this.gasPrice.valueOf())),n}buildQuery(){return new xW.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.tokenTransfers=[e].map(r=>new TE.TokenTransfer(r)),this}withSingleESDTNFTTransfer(e){return this.tokenTransfers=[e].map(r=>new TE.TokenTransfer(r)),this}withMultiESDTNFTTransfer(e){return this.tokenTransfers=e.map(r=>new TE.TokenTransfer(r)),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withVersion(e){return this.version=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new NW.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};d0.Interaction=_E});var NE=D(kO=>{"use strict";h();Object.defineProperty(kO,"__esModule",{value:!0})});var zO=D(yc=>{"use strict";h();Object.defineProperty(yc,"__esModule",{value:!0});yc.bech32m=yc.bech32=void 0;var g0="qpzry9x8gf2tvdw0s3jn54khce6mua7l",GO={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function HO(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=mc(e)^n>>5}e=mc(e);for(let r=0;r=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<a)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=HO(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=mc(c)^w,f+=g0.charAt(w)}for(let d=0;d<6;++d)c=mc(c);c^=e;for(let d=0;d<6;++d){let w=c>>(5-d)*5&31;f+=g0.charAt(w)}return f}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";let a=o.toLowerCase(),c=o.toUpperCase();if(o!==a&&o!==c)return"Mixed-case string "+o;o=a;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),w=o.slice(f+1);if(w.length<6)return"Data too short";let A=HO(d);if(typeof A=="string")return A;let T=[];for(let x=0;x=w.length)&&T.push(V)}return A!==e?"Invalid checksum for "+o:{prefix:d,words:T}}function i(o,u){let a=n(o,u);if(typeof a=="object")return a}function s(o,u){let a=n(o,u);if(typeof a=="object")return a;throw new Error(a)}return{decodeUnsafe:i,decode:s,encode:r,toWords:OW,fromWordsUnsafe:DW,fromWords:PW}}yc.bech32=jO("bech32");yc.bech32m=jO("bech32m")});var KO=D(kn=>{"use strict";h();Object.defineProperty(kn,"__esModule",{value:!0});kn.TokenTransferProperties=kn.TransactionMetadataTransfer=kn.TransactionMetadata=kn.TransactionToDecode=kn.TransactionDecoder=void 0;var QO=zO(),OE=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new Va;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new p0;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new Va;s.transfers||(s.transfers=[]);let o=2;for(let u=0;uo&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),u=new Va;return u.sender=e.sender,u.receiver=o,u.value=s,r.length>4&&(u.functionName=this.hexToString(r[4]),u.functionArgs=r.slice(5)),u.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],u}base64Encode(e){return p.Buffer.from(e).toString("base64")}base64Decode(e){return p.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new Va;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=p.Buffer.from(e,"hex"),n=QO.bech32.toWords(r);return QO.bech32.encode("erd",n)}isAddressValid(e){return p.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return p.Buffer.from(e,"base64").toString("hex")}hexToString(e){return p.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};kn.TransactionDecoder=OE;var p0=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};kn.TransactionToDecode=p0;var Va=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};kn.TransactionMetadata=Va;var DE=class{constructor(){this.value=BigInt(0)}};kn.TransactionMetadataTransfer=DE;var PE=class{};kn.TokenTransferProperties=PE});var RE=D(m0=>{"use strict";h();Object.defineProperty(m0,"__esModule",{value:!0});m0.ReturnCode=void 0;var mt=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};m0.ReturnCode=mt;mt.None=new mt("");mt.Ok=new mt("ok");mt.FunctionNotFound=new mt("function not found");mt.FunctionWrongSignature=new mt("wrong signature for function");mt.ContractNotFound=new mt("contract not found");mt.UserError=new mt("user error");mt.OutOfGas=new mt("out of gas");mt.AccountCollision=new mt("account collision");mt.OutOfFunds=new mt("out of funds");mt.CallStackOverFlow=new mt("call stack overflow");mt.ContractInvalid=new mt("contract invalid");mt.ExecutionFailed=new mt("execution failed");mt.Unknown=new mt("unknown")});var YO=D(y0=>{"use strict";h();Object.defineProperty(y0,"__esModule",{value:!0});y0.ResultsParser=void 0;var RW=KO(),WO=Ve(),$O=Ie(),So=oo(),BW=fc(),wc=RE(),vc;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(vc||(vc={}));var BE;(function(t){t.TooMuchGas="@too much gas provided for processing"})(BE||(BE={}));var MW={argsSerializer:new BW.ArgSerializer},ME=class{constructor(e){e={...MW,...e},this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e);return this.parseOutcomeFromUntypedBundle(n,r)}parseOutcomeFromUntypedBundle(e,r){let n=this.argsSerializer.buffersToValues(e.values,r.output);return{returnCode:e.returnCode,returnMessage:e.returnMessage,values:n,firstValue:n[0],secondValue:n[1],thirdValue:n[2],lastValue:n[n.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return So.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return So.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return So.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return So.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new $O.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new RW.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:wc.ReturnCode.None,returnMessage:wc.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:wc.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(vc.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(vc.OnWriteLog,u=>u.findFirstOrNoneTopic(a=>a.toString().startsWith(BE.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new WO.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(vc.OnWriteLog,a=>a.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),u=s.toString();return{returnCode:s,returnMessage:u,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new WO.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(vc.OnWriteLog,o=>{let u=o.address.bech32()==e.sender.bech32(),a=o.topics[0]?.hex()==n.hex();return u&&a});if(s){let{returnCode:o,returnDataParts:u}=this.sliceDataFieldInParts(s.data),a=o.toString();return{returnCode:o,returnMessage:a,values:u}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||p.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new $O.ErrCannotParseContractResults("no return code");return{returnCode:wc.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){let n=e.topics.map(o=>p.Buffer.from(o.valueOf())).slice(1),i=e.dataPayload?.valueOf()||p.Buffer.from([]),s=e.additionalData?.map(o=>p.Buffer.from(o.valueOf()))||[];return s.length===0&&i.length&&s.push(p.Buffer.from(i)),this.doParseEvent({topics:n,dataItems:s,eventDefinition:r})}doParseEvent(e){let r={},n=e.eventDefinition.inputs.filter(u=>u.indexed),i=this.argsSerializer.buffersToValues(e.topics,n);for(let u=0;u!u.indexed),o=this.argsSerializer.buffersToValues(e.dataItems,s);for(let u=0;u{"use strict";h();Object.defineProperty(v0,"__esModule",{value:!0});v0.SmartContract=void 0;var w0=Ve(),LE=nE(),FE=hr(),LW=Ie(),UE=gE(),qE=yE(),FW=Rn(),JO=ZA(),XO=tE(),ZO=CE(),UW=t0(),qW=Wf(),VE=class{constructor(e={}){this.address=w0.Address.empty(),this.methodsExplicit={},this.methods={},this.address=e.address||w0.Address.empty(),this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new XO.ContractFunction(i);return new ZO.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new XO.ContractFunction(i),u=UW.NativeSerializer.nativeToTypedValues(s||[],n);return new ZO.Interaction(e,o,u||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return FW.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){LE.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()");let c=new qE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new UE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=p.Buffer.from(r.toString(),"hex"),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForDeploy({sender:e,bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??FE.TRANSACTION_MIN_GAS_PRICE),A}getMetadataPropertiesAsObject(e){let r;return e?r=JO.CodeMetadata.fromBytes(p.Buffer.from(e.toString(),"hex")):r=new JO.CodeMetadata,r.toJSON()}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){LE.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress();let c=new qE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new UE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=Uint8Array.from(p.Buffer.from(r.toString(),"hex")),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForUpgrade({sender:e,contract:this.getAddress(),bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??FE.TRANSACTION_MIN_GAS_PRICE),A}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:u,caller:a}){LE.Compatibility.guardAddressIsSetAndNonZero(a,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress();let c=new qE.TransactionsFactoryConfig({chainID:u.valueOf()}),f=new UE.SmartContractTransactionsFactory({config:c,abi:this.abi});r=r||[],n=n||0;let d=f.createTransactionForExecute({sender:a,contract:s||this.getAddress(),function:e.toString(),gasLimit:BigInt(i.valueOf()),arguments:r});return d.setChainID(u),d.setValue(n),d.setGasPrice(o??FE.TRANSACTION_MIN_GAS_PRICE),d}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new qW.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new LW.ErrContractHasNoAddress}static computeAddress(e,r){let n=w0.Address.fromBech32(e.bech32());return new w0.AddressComputer().computeContractAddress(n,BigInt(r.valueOf()))}};v0.SmartContract=VE});var tD=D(Io=>{"use strict";h();Object.defineProperty(Io,"__esModule",{value:!0});Io.ContractCallPayloadBuilder=Io.ContractUpgradePayloadBuilder=Io.ContractDeployPayloadBuilder=void 0;var VW=hr(),jE=Ms(),zE=Rn(),kW=fc(),kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${VW.WasmVirtualMachine}@${r}`;return n=QE(n,this.arguments),new jE.TransactionPayload(n)}};Io.ContractDeployPayloadBuilder=kE;var HE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=QE(n,this.arguments),new jE.TransactionPayload(n)}};Io.ContractUpgradePayloadBuilder=HE;var GE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=QE(e,this.arguments),new jE.TransactionPayload(e)}};Io.ContractCallPayloadBuilder=GE;function QE(t,e){let{argumentsString:r,count:n}=new kW.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var qn=D(Jt=>{"use strict";h();var HW=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qr=Jt&&Jt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&HW(e,t,r)};Object.defineProperty(Jt,"__esModule",{value:!0});qr(fc(),Jt);qr(wO(),Jt);qr(jA(),Jt);qr(ZA(),Jt);qr(tE(),Jt);qr(CE(),Jt);qr(SE(),Jt);qr(NE(),Jt);qr(t0(),Jt);qr(Wf(),Jt);qr(YO(),Jt);qr(RE(),Jt);qr(eD(),Jt);qr(tD(),Jt);qr(dr(),Jt)});var Ac=D(or=>{"use strict";h();Object.defineProperty(or,"__esModule",{value:!0});or.gatherAllEvents=or.findEventsByFirstTopic=or.findEventsByIdentifier=or.findEventsByPredicate=or.SmartContractCallOutcome=or.TransactionOutcome=or.SmartContractResult=or.TransactionLogs=or.TransactionEvent=void 0;var KE=class{constructor(e){this.address="",this.identifier="",this.topics=[],this.dataItems=[],Object.assign(this,e)}};or.TransactionEvent=KE;var $f=class{constructor(e){this.address="",this.events=[],Object.assign(this,e)}};or.TransactionLogs=$f;var WE=class{constructor(e){this.sender="",this.receiver="",this.data=new Uint8Array,this.logs=new $f({}),Object.assign(this,e)}};or.SmartContractResult=WE;var $E=class{constructor(e){this.directSmartContractCallOutcome=new A0({}),this.smartContractResults=[],this.logs=new $f({}),Object.assign(this,e)}};or.TransactionOutcome=$E;var A0=class{constructor(e){this.function="",this.returnDataParts=[],this.returnMessage="",this.returnCode="",Object.assign(this,e)}};or.SmartContractCallOutcome=A0;function YE(t,e){return rD(t).filter(e)}or.findEventsByPredicate=YE;function GW(t,e){return YE(t,r=>r.identifier==e)}or.findEventsByIdentifier=GW;function jW(t,e){return YE(t,r=>r.topics[0]?.toString()==e)}or.findEventsByFirstTopic=jW;function rD(t){let e=[];e.push(...t.logs.events);for(let r of t.smartContractResults)e.push(...r.logs.events);return e}or.gatherAllEvents=rD});var XE=D(E0=>{"use strict";h();Object.defineProperty(E0,"__esModule",{value:!0});E0.TransactionsConverter=void 0;var zW=qn(),QW=Xr(),Ec=Ac(),JE=class{transactionToPlainObject(e){return{nonce:Number(e.nonce),value:e.value.toString(),receiver:e.receiver,sender:e.sender,senderUsername:this.toBase64OrUndefined(e.senderUsername),receiverUsername:this.toBase64OrUndefined(e.receiverUsername),gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:this.toBase64OrUndefined(e.data),chainID:e.chainID.valueOf(),version:e.version,options:e.options==0?void 0:e.options,guardian:e.guardian?e.guardian:void 0,signature:this.toHexOrUndefined(e.signature),guardianSignature:this.toHexOrUndefined(e.guardianSignature)}}toBase64OrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("base64"):void 0}toHexOrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("hex"):void 0}plainObjectToTransaction(e){return new QW.Transaction({nonce:BigInt(e.nonce),value:BigInt(e.value||""),receiver:e.receiver,receiverUsername:this.bufferFromBase64(e.receiverUsername).toString(),sender:e.sender,senderUsername:this.bufferFromBase64(e.senderUsername).toString(),guardian:e.guardian,gasPrice:BigInt(e.gasPrice),gasLimit:BigInt(e.gasLimit),data:this.bufferFromBase64(e.data),chainID:String(e.chainID),version:Number(e.version),options:Number(e.options),signature:this.bufferFromHex(e.signature),guardianSignature:this.bufferFromHex(e.guardianSignature)})}bufferFromBase64(e){return p.Buffer.from(e||"","base64")}bufferFromHex(e){return p.Buffer.from(e||"","hex")}transactionOnNetworkToOutcome(e){let n=new zW.ResultsParser().parseUntypedOutcome(e),i=new Ec.SmartContractCallOutcome({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.values}),s=e.contractResults.items.map(u=>this.smartContractResultOnNetworkToSmartContractResult(u)),o=new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(u=>this.eventOnNetworkToEvent(u))});return new Ec.TransactionOutcome({logs:o,smartContractResults:s,directSmartContractCallOutcome:i})}smartContractResultOnNetworkToSmartContractResult(e){return new Ec.SmartContractResult({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:p.Buffer.from(e.data),logs:new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(r=>this.eventOnNetworkToEvent(r))})})}eventOnNetworkToEvent(e){let r=e.dataPayload?.valueOf()||p.Buffer.from(e.data||""),n=e.additionalData?.map(i=>p.Buffer.from(i.valueOf()))||[];return n.length===0&&r.length&&n.push(p.Buffer.from(r)),new Ec.TransactionEvent({address:e.address.bech32(),identifier:e.identifier,topics:e.topics.map(i=>p.Buffer.from(i.hex(),"hex")),dataItems:n})}};E0.TransactionsConverter=JE});var nD=D(Yi=>{"use strict";h();var KW=Yi&&Yi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),WW=Yi&&Yi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$W=Yi&&Yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&KW(e,t,r);return WW(e,t),e};Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Hash=void 0;var YW=$W(Ie()),ZE=class t{constructor(e){if(!e)this.hash=p.Buffer.from([]);else if(e instanceof p.Buffer)this.hash=e;else if(typeof e=="string")this.hash=p.Buffer.from(e,"hex");else throw new YW.ErrBadType("hash","buffer | string",e)}static empty(){return new t(p.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};Yi.Hash=ZE});var Yf=D(Hn=>{"use strict";h();var JW=Hn&&Hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),XW=Hn&&Hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ZW=Hn&&Hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&JW(e,t,r);return XW(e,t),e};Object.defineProperty(Hn,"__esModule",{value:!0});Hn.interpretSignatureAsBuffer=Hn.Signature=void 0;var iD=ZW(Ie()),sD=64,eb=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof p.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new iD.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==sD}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=sD)throw new iD.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Hn.Signature=eb;function e$(t){if(ArrayBuffer.isView(t))return p.Buffer.from(t);if(t.hex!=null)return p.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Hn.interpretSignatureAsBuffer=e$});var aD=D((nwe,oD)=>{"use strict";h();oD.exports=t$;function t$(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";h();var b0=lD;b0.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bc=new Array(64),cD=new Array(123);for(mi=0;mi<64;)cD[bc[mi]=mi<26?mi+65:mi<52?mi+71:mi<62?mi-4:mi-59|43]=mi++;var mi;b0.encode=function(e,r,n){for(var i=null,s=[],o=0,u=0,a;r>2],a=(c&3)<<4,u=1;break;case 1:s[o++]=bc[a|c>>4],a=(c&15)<<2,u=2;break;case 2:s[o++]=bc[a|c>>6],s[o++]=bc[c&63],u=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return u&&(s[o++]=bc[a],s[o++]=61,u===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var uD="invalid encoding";b0.decode=function(e,r,n){for(var i=n,s=0,o,u=0;u1)break;if((a=cD[a])===void 0)throw Error(uD);switch(s){case 0:o=a,s=1;break;case 1:r[n++]=o<<2|(a&48)>>4,o=a,s=2;break;case 2:r[n++]=(o&15)<<4|(a&60)>>2,o=a,s=3;break;case 3:r[n++]=(o&3)<<6|a,s=0;break}}if(s===1)throw Error(uD);return n-i};b0.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var dD=D((awe,hD)=>{"use strict";h();hD.exports=S0;function S0(){this._listeners={}}S0.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};S0.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";h();vD.exports=gD(gD);function gD(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(a,c,f){e[0]=a,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],e[0]}function u(a,c){return r[3]=a[c],r[2]=a[c+1],r[1]=a[c+2],r[0]=a[c+3],e[0]}t.readFloatLE=n?o:u,t.readFloatBE=n?u:o}():function(){function e(n,i,s,o){var u=i<0?1:0;if(u&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((u<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((u<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var a=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-a)*8388608)&8388607;n((u<<31|a+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,pD),t.writeFloatBE=e.bind(null,mD);function r(n,i,s){var o=n(i,s),u=(o>>31)*2+1,a=o>>>23&255,c=o&8388607;return a===255?c?NaN:u*(1/0):a===0?u*1401298464324817e-60*c:u*Math.pow(2,a-150)*(c+8388608)}t.readFloatLE=r.bind(null,yD),t.readFloatBE=r.bind(null,wD)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(a,c,f){e[0]=a,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],r[4]=a[c+4],r[5]=a[c+5],r[6]=a[c+6],r[7]=a[c+7],e[0]}function u(a,c){return r[7]=a[c],r[6]=a[c+1],r[5]=a[c+2],r[4]=a[c+3],r[3]=a[c+4],r[2]=a[c+5],r[1]=a[c+6],r[0]=a[c+7],e[0]}t.readDoubleLE=n?o:u,t.readDoubleBE=n?u:o}():function(){function e(n,i,s,o,u,a){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,u,a+i),n(1/o>0?0:2147483648,u,a+s);else if(isNaN(o))n(0,u,a+i),n(2146959360,u,a+s);else if(o>17976931348623157e292)n(0,u,a+i),n((c<<31|2146435072)>>>0,u,a+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,u,a+i),n((c<<31|f/4294967296)>>>0,u,a+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,u,a+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,u,a+s)}}}t.writeDoubleLE=e.bind(null,pD,0,4),t.writeDoubleBE=e.bind(null,mD,4,0);function r(n,i,s,o,u){var a=n(o,u+i),c=n(o,u+s),f=(c>>31)*2+1,d=c>>>20&2047,w=4294967296*(c&1048575)+a;return d===2047?w?NaN:f*(1/0):d===0?f*5e-324*w:f*Math.pow(2,d-1075)*(w+4503599627370496)}t.readDoubleLE=r.bind(null,yD,0,4),t.readDoubleBE=r.bind(null,wD,4,0)}(),t}function pD(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function mD(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function yD(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function wD(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var ED=D((exports,module)=>{"use strict";h();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var SD=D(bD=>{"use strict";h();var tb=bD;tb.length=function(e){for(var r=0,n=0,i=0;i191&&a<224?o[u++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[u++]=55296+(a>>10),o[u++]=56320+(a&1023)):o[u++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,u>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),u=0);return s?(u&&s.push(String.fromCharCode.apply(String,o.slice(0,u))),s.join("")):String.fromCharCode.apply(String,o.slice(0,u))};tb.write=function(e,r,n){for(var i=n,s,o,u=0;u>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(u+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++u,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var TD=D((gwe,ID)=>{"use strict";h();ID.exports=r$;function r$(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);var c=e.call(s,o,o+=a);return o&7&&(o=(o|7)+1),c}}});var CD=D((mwe,_D)=>{"use strict";h();_D.exports=yr;var Jf=_o();function yr(t,e){this.lo=t>>>0,this.hi=e>>>0}var ka=yr.zero=new yr(0,0);ka.toNumber=function(){return 0};ka.zzEncode=ka.zzDecode=function(){return this};ka.length=function(){return 1};var n$=yr.zeroHash="\0\0\0\0\0\0\0\0";yr.fromNumber=function(e){if(e===0)return ka;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new yr(n,i)};yr.from=function(e){if(typeof e=="number")return yr.fromNumber(e);if(Jf.isString(e))if(Jf.Long)e=Jf.Long.fromString(e);else return yr.fromNumber(parseInt(e,10));return e.low||e.high?new yr(e.low>>>0,e.high>>>0):ka};yr.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};yr.prototype.toLong=function(e){return Jf.Long?new Jf.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var To=String.prototype.charCodeAt;yr.fromHash=function(e){return e===n$?ka:new yr((To.call(e,0)|To.call(e,1)<<8|To.call(e,2)<<16|To.call(e,3)<<24)>>>0,(To.call(e,4)|To.call(e,5)<<8|To.call(e,6)<<16|To.call(e,7)<<24)>>>0)};yr.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};yr.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};yr.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};yr.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var _o=D(rb=>{"use strict";h();var we=rb;we.asPromise=aD();we.base64=fD();we.EventEmitter=dD();we.float=AD();we.inquire=ED();we.utf8=SD();we.pool=TD();we.LongBits=CD();we.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);we.global=we.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||rb;we.emptyArray=Object.freeze?Object.freeze([]):[];we.emptyObject=Object.freeze?Object.freeze({}):{};we.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};we.isString=function(e){return typeof e=="string"||e instanceof String};we.isObject=function(e){return e&&typeof e=="object"};we.isset=we.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};we.Buffer=function(){try{var t=we.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();we._Buffer_from=null;we._Buffer_allocUnsafe=null;we.newBuffer=function(e){return typeof e=="number"?we.Buffer?we._Buffer_allocUnsafe(e):new we.Array(e):we.Buffer?we._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};we.Array=typeof Uint8Array<"u"?Uint8Array:Array;we.Long=we.global.dcodeIO&&we.global.dcodeIO.Long||we.global.Long||we.inquire("long");we.key2Re=/^true|false|0|1$/;we.key32Re=/^-?(?:0|[1-9][0-9]*)$/;we.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;we.longToHash=function(e){return e?we.LongBits.from(e).toHash():we.LongBits.zeroHash};we.longFromHash=function(e,r){var n=we.LongBits.fromHash(e);return we.Long?we.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function ND(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};we.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";h();RD.exports=Ue;var Gn=_o(),nb,I0=Gn.LongBits,OD=Gn.base64,DD=Gn.utf8;function Xf(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function sb(){}function i$(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Xf(sb,0,0),this.tail=this.head,this.states=null}var PD=function(){return Gn.Buffer?function(){return(Ue.create=function(){return new nb})()}:function(){return new Ue}};Ue.create=PD();Ue.alloc=function(e){return new Gn.Array(e)};Gn.Array!==Array&&(Ue.alloc=Gn.pool(Ue.alloc,Gn.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Xf(e,r,n),this.len+=r,this};function ob(t,e,r){e[r]=t&255}function s$(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function ab(t,e){this.len=t,this.next=void 0,this.val=e}ab.prototype=Object.create(Xf.prototype);ab.prototype.fn=s$;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ab((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(ub,10,I0.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ub(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=I0.from(e);return this._push(ub,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=I0.from(e).zzEncode();return this._push(ub,r.length(),r)};Ue.prototype.bool=function(e){return this._push(ob,1,e?1:0)};function ib(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(ib,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=I0.from(e);return this._push(ib,4,r.lo)._push(ib,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Gn.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Gn.float.writeDoubleLE,8,e)};var o$=Gn.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(ob,1,0);if(Gn.isString(e)){var n=Ue.alloc(r=OD.length(e));OD.decode(e,n,0),e=n}return this.uint32(r)._push(o$,r,e)};Ue.prototype.string=function(e){var r=DD.length(e);return r?this.uint32(r)._push(DD.write,r,e):this._push(ob,1,0)};Ue.prototype.fork=function(){return this.states=new i$(this),this.head=this.tail=new Xf(sb,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xf(sb,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){nb=t,Ue.create=PD(),nb._configure()}});var LD=D((bwe,MD)=>{"use strict";h();MD.exports=Ji;var BD=cb();(Ji.prototype=Object.create(BD.prototype)).constructor=Ji;var Co=_o();function Ji(){BD.call(this)}Ji._configure=function(){Ji.alloc=Co._Buffer_allocUnsafe,Ji.writeBytesBuffer=Co.Buffer&&Co.Buffer.prototype instanceof Uint8Array&&Co.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Ji.writeBytesBuffer,r,e),this};function a$(t,e,r){t.length<40?Co.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ji.prototype.string=function(e){var r=Co.Buffer.byteLength(e);return this.uint32(r),r&&this._push(a$,r,e),this};Ji._configure()});var hb=D((Iwe,kD)=>{"use strict";h();kD.exports=Xt;var yi=_o(),fb,qD=yi.LongBits,u$=yi.utf8;function wi(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Xt(t){this.buf=t,this.pos=0,this.len=t.length}var FD=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Xt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Xt(e);throw Error("illegal buffer")},VD=function(){return yi.Buffer?function(r){return(Xt.create=function(i){return yi.Buffer.isBuffer(i)?new fb(i):FD(i)})(r)}:FD};Xt.create=VD();Xt.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Xt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wi(this,10);return e}}();Xt.prototype.int32=function(){return this.uint32()|0};Xt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function lb(){var t=new qD(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw wi(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw wi(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Xt.prototype.bool=function(){return this.uint32()!==0};function T0(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Xt.prototype.fixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return T0(this.buf,this.pos+=4)};Xt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return T0(this.buf,this.pos+=4)|0};function UD(){if(this.pos+8>this.len)throw wi(this,8);return new qD(T0(this.buf,this.pos+=4),T0(this.buf,this.pos+=4))}Xt.prototype.float=function(){if(this.pos+4>this.len)throw wi(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Xt.prototype.double=function(){if(this.pos+8>this.len)throw wi(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Xt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw wi(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var i=yi.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Xt.prototype.string=function(){var e=this.bytes();return u$.read(e,0,e.length)};Xt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wi(this);while(this.buf[this.pos++]&128);return this};Xt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Xt._configure=function(t){fb=t,Xt.create=VD(),fb._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Xt.prototype,{int64:function(){return lb.call(this)[e](!1)},uint64:function(){return lb.call(this)[e](!0)},sint64:function(){return lb.call(this).zzDecode()[e](!1)},fixed64:function(){return UD.call(this)[e](!0)},sfixed64:function(){return UD.call(this)[e](!1)}})}});var zD=D((_we,jD)=>{"use strict";h();jD.exports=Ha;var GD=hb();(Ha.prototype=Object.create(GD.prototype)).constructor=Ha;var HD=_o();function Ha(t){GD.call(this,t)}Ha._configure=function(){HD.Buffer&&(Ha.prototype._slice=HD.Buffer.prototype.slice)};Ha.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ha._configure()});var KD=D((Nwe,QD)=>{"use strict";h();QD.exports=Zf;var db=_o();(Zf.prototype=Object.create(db.EventEmitter.prototype)).constructor=Zf;function Zf(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");db.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Zf.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return db.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(a,c){if(a)return o.emit("error",a,e),s(a);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(u){o.emit("error",u,e),setTimeout(function(){s(u)},0);return}};Zf.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var $D=D(WD=>{"use strict";h();var c$=WD;c$.Service=KD()});var JD=D((Pwe,YD)=>{"use strict";h();YD.exports={}});var e8=D(ZD=>{"use strict";h();var tn=ZD;tn.build="minimal";tn.Writer=cb();tn.BufferWriter=LD();tn.Reader=hb();tn.BufferReader=zD();tn.util=_o();tn.rpc=$D();tn.roots=JD();tn.configure=XD;function XD(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}XD()});var r8=D((Lwe,t8)=>{"use strict";h();t8.exports=e8()});var i8=D((n8,eh)=>{"use strict";h();(function(t,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof Pd=="function"&&typeof eh=="object"&&eh&&eh.exports&&(eh.exports=e(r8()))})(n8,function(t){"use strict";var e=t.Reader,r=t.Writer,n=t.util,i=t.roots.default||(t.roots.default={});return i.proto=function(){var s={};return s.Transaction=function(){function o(u){if(u)for(var a=Object.keys(u),c=0;c>>3){case 1:{d.Nonce=a.uint64();break}case 2:{d.Value=a.bytes();break}case 3:{d.RcvAddr=a.bytes();break}case 4:{d.RcvUserName=a.bytes();break}case 5:{d.SndAddr=a.bytes();break}case 6:{d.SndUserName=a.bytes();break}case 7:{d.GasPrice=a.uint64();break}case 8:{d.GasLimit=a.uint64();break}case 9:{d.Data=a.bytes();break}case 10:{d.ChainID=a.bytes();break}case 11:{d.Version=a.uint32();break}case 12:{d.Signature=a.bytes();break}case 13:{d.Options=a.uint32();break}case 14:{d.GuardianAddr=a.bytes();break}case 15:{d.GuardianSignature=a.bytes();break}default:a.skipType(w&7);break}}return d},o.decodeDelimited=function(a){return a instanceof e||(a=new e(a)),this.decode(a,a.uint32())},o.verify=function(a){return typeof a!="object"||a===null?"object expected":a.Nonce!=null&&a.hasOwnProperty("Nonce")&&!n.isInteger(a.Nonce)&&!(a.Nonce&&n.isInteger(a.Nonce.low)&&n.isInteger(a.Nonce.high))?"Nonce: integer|Long expected":a.Value!=null&&a.hasOwnProperty("Value")&&!(a.Value&&typeof a.Value.length=="number"||n.isString(a.Value))?"Value: buffer expected":a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&!(a.RcvAddr&&typeof a.RcvAddr.length=="number"||n.isString(a.RcvAddr))?"RcvAddr: buffer expected":a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&!(a.RcvUserName&&typeof a.RcvUserName.length=="number"||n.isString(a.RcvUserName))?"RcvUserName: buffer expected":a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&!(a.SndAddr&&typeof a.SndAddr.length=="number"||n.isString(a.SndAddr))?"SndAddr: buffer expected":a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&!(a.SndUserName&&typeof a.SndUserName.length=="number"||n.isString(a.SndUserName))?"SndUserName: buffer expected":a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&!n.isInteger(a.GasPrice)&&!(a.GasPrice&&n.isInteger(a.GasPrice.low)&&n.isInteger(a.GasPrice.high))?"GasPrice: integer|Long expected":a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&!n.isInteger(a.GasLimit)&&!(a.GasLimit&&n.isInteger(a.GasLimit.low)&&n.isInteger(a.GasLimit.high))?"GasLimit: integer|Long expected":a.Data!=null&&a.hasOwnProperty("Data")&&!(a.Data&&typeof a.Data.length=="number"||n.isString(a.Data))?"Data: buffer expected":a.ChainID!=null&&a.hasOwnProperty("ChainID")&&!(a.ChainID&&typeof a.ChainID.length=="number"||n.isString(a.ChainID))?"ChainID: buffer expected":a.Version!=null&&a.hasOwnProperty("Version")&&!n.isInteger(a.Version)?"Version: integer expected":a.Signature!=null&&a.hasOwnProperty("Signature")&&!(a.Signature&&typeof a.Signature.length=="number"||n.isString(a.Signature))?"Signature: buffer expected":a.Options!=null&&a.hasOwnProperty("Options")&&!n.isInteger(a.Options)?"Options: integer expected":a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&!(a.GuardianAddr&&typeof a.GuardianAddr.length=="number"||n.isString(a.GuardianAddr))?"GuardianAddr: buffer expected":a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&!(a.GuardianSignature&&typeof a.GuardianSignature.length=="number"||n.isString(a.GuardianSignature))?"GuardianSignature: buffer expected":null},o.fromObject=function(a){if(a instanceof i.proto.Transaction)return a;var c=new i.proto.Transaction;return a.Nonce!=null&&(n.Long?(c.Nonce=n.Long.fromValue(a.Nonce)).unsigned=!0:typeof a.Nonce=="string"?c.Nonce=parseInt(a.Nonce,10):typeof a.Nonce=="number"?c.Nonce=a.Nonce:typeof a.Nonce=="object"&&(c.Nonce=new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0))),a.Value!=null&&(typeof a.Value=="string"?n.base64.decode(a.Value,c.Value=n.newBuffer(n.base64.length(a.Value)),0):a.Value.length>=0&&(c.Value=a.Value)),a.RcvAddr!=null&&(typeof a.RcvAddr=="string"?n.base64.decode(a.RcvAddr,c.RcvAddr=n.newBuffer(n.base64.length(a.RcvAddr)),0):a.RcvAddr.length>=0&&(c.RcvAddr=a.RcvAddr)),a.RcvUserName!=null&&(typeof a.RcvUserName=="string"?n.base64.decode(a.RcvUserName,c.RcvUserName=n.newBuffer(n.base64.length(a.RcvUserName)),0):a.RcvUserName.length>=0&&(c.RcvUserName=a.RcvUserName)),a.SndAddr!=null&&(typeof a.SndAddr=="string"?n.base64.decode(a.SndAddr,c.SndAddr=n.newBuffer(n.base64.length(a.SndAddr)),0):a.SndAddr.length>=0&&(c.SndAddr=a.SndAddr)),a.SndUserName!=null&&(typeof a.SndUserName=="string"?n.base64.decode(a.SndUserName,c.SndUserName=n.newBuffer(n.base64.length(a.SndUserName)),0):a.SndUserName.length>=0&&(c.SndUserName=a.SndUserName)),a.GasPrice!=null&&(n.Long?(c.GasPrice=n.Long.fromValue(a.GasPrice)).unsigned=!0:typeof a.GasPrice=="string"?c.GasPrice=parseInt(a.GasPrice,10):typeof a.GasPrice=="number"?c.GasPrice=a.GasPrice:typeof a.GasPrice=="object"&&(c.GasPrice=new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0))),a.GasLimit!=null&&(n.Long?(c.GasLimit=n.Long.fromValue(a.GasLimit)).unsigned=!0:typeof a.GasLimit=="string"?c.GasLimit=parseInt(a.GasLimit,10):typeof a.GasLimit=="number"?c.GasLimit=a.GasLimit:typeof a.GasLimit=="object"&&(c.GasLimit=new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0))),a.Data!=null&&(typeof a.Data=="string"?n.base64.decode(a.Data,c.Data=n.newBuffer(n.base64.length(a.Data)),0):a.Data.length>=0&&(c.Data=a.Data)),a.ChainID!=null&&(typeof a.ChainID=="string"?n.base64.decode(a.ChainID,c.ChainID=n.newBuffer(n.base64.length(a.ChainID)),0):a.ChainID.length>=0&&(c.ChainID=a.ChainID)),a.Version!=null&&(c.Version=a.Version>>>0),a.Signature!=null&&(typeof a.Signature=="string"?n.base64.decode(a.Signature,c.Signature=n.newBuffer(n.base64.length(a.Signature)),0):a.Signature.length>=0&&(c.Signature=a.Signature)),a.Options!=null&&(c.Options=a.Options>>>0),a.GuardianAddr!=null&&(typeof a.GuardianAddr=="string"?n.base64.decode(a.GuardianAddr,c.GuardianAddr=n.newBuffer(n.base64.length(a.GuardianAddr)),0):a.GuardianAddr.length>=0&&(c.GuardianAddr=a.GuardianAddr)),a.GuardianSignature!=null&&(typeof a.GuardianSignature=="string"?n.base64.decode(a.GuardianSignature,c.GuardianSignature=n.newBuffer(n.base64.length(a.GuardianSignature)),0):a.GuardianSignature.length>=0&&(c.GuardianSignature=a.GuardianSignature)),c},o.toObject=function(a,c){c||(c={});var f={};if(c.defaults){if(n.Long){var d=new n.Long(0,0,!0);f.Nonce=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.Nonce=c.longs===String?"0":0;if(c.bytes===String?f.Value="":(f.Value=[],c.bytes!==Array&&(f.Value=n.newBuffer(f.Value))),c.bytes===String?f.RcvAddr="":(f.RcvAddr=[],c.bytes!==Array&&(f.RcvAddr=n.newBuffer(f.RcvAddr))),c.bytes===String?f.RcvUserName="":(f.RcvUserName=[],c.bytes!==Array&&(f.RcvUserName=n.newBuffer(f.RcvUserName))),c.bytes===String?f.SndAddr="":(f.SndAddr=[],c.bytes!==Array&&(f.SndAddr=n.newBuffer(f.SndAddr))),c.bytes===String?f.SndUserName="":(f.SndUserName=[],c.bytes!==Array&&(f.SndUserName=n.newBuffer(f.SndUserName))),n.Long){var d=new n.Long(0,0,!0);f.GasPrice=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasPrice=c.longs===String?"0":0;if(n.Long){var d=new n.Long(0,0,!0);f.GasLimit=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasLimit=c.longs===String?"0":0;c.bytes===String?f.Data="":(f.Data=[],c.bytes!==Array&&(f.Data=n.newBuffer(f.Data))),c.bytes===String?f.ChainID="":(f.ChainID=[],c.bytes!==Array&&(f.ChainID=n.newBuffer(f.ChainID))),f.Version=0,c.bytes===String?f.Signature="":(f.Signature=[],c.bytes!==Array&&(f.Signature=n.newBuffer(f.Signature))),f.Options=0,c.bytes===String?f.GuardianAddr="":(f.GuardianAddr=[],c.bytes!==Array&&(f.GuardianAddr=n.newBuffer(f.GuardianAddr))),c.bytes===String?f.GuardianSignature="":(f.GuardianSignature=[],c.bytes!==Array&&(f.GuardianSignature=n.newBuffer(f.GuardianSignature)))}return a.Nonce!=null&&a.hasOwnProperty("Nonce")&&(typeof a.Nonce=="number"?f.Nonce=c.longs===String?String(a.Nonce):a.Nonce:f.Nonce=c.longs===String?n.Long.prototype.toString.call(a.Nonce):c.longs===Number?new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0):a.Nonce),a.Value!=null&&a.hasOwnProperty("Value")&&(f.Value=c.bytes===String?n.base64.encode(a.Value,0,a.Value.length):c.bytes===Array?Array.prototype.slice.call(a.Value):a.Value),a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&(f.RcvAddr=c.bytes===String?n.base64.encode(a.RcvAddr,0,a.RcvAddr.length):c.bytes===Array?Array.prototype.slice.call(a.RcvAddr):a.RcvAddr),a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&(f.RcvUserName=c.bytes===String?n.base64.encode(a.RcvUserName,0,a.RcvUserName.length):c.bytes===Array?Array.prototype.slice.call(a.RcvUserName):a.RcvUserName),a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&(f.SndAddr=c.bytes===String?n.base64.encode(a.SndAddr,0,a.SndAddr.length):c.bytes===Array?Array.prototype.slice.call(a.SndAddr):a.SndAddr),a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&(f.SndUserName=c.bytes===String?n.base64.encode(a.SndUserName,0,a.SndUserName.length):c.bytes===Array?Array.prototype.slice.call(a.SndUserName):a.SndUserName),a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&(typeof a.GasPrice=="number"?f.GasPrice=c.longs===String?String(a.GasPrice):a.GasPrice:f.GasPrice=c.longs===String?n.Long.prototype.toString.call(a.GasPrice):c.longs===Number?new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0):a.GasPrice),a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&(typeof a.GasLimit=="number"?f.GasLimit=c.longs===String?String(a.GasLimit):a.GasLimit:f.GasLimit=c.longs===String?n.Long.prototype.toString.call(a.GasLimit):c.longs===Number?new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0):a.GasLimit),a.Data!=null&&a.hasOwnProperty("Data")&&(f.Data=c.bytes===String?n.base64.encode(a.Data,0,a.Data.length):c.bytes===Array?Array.prototype.slice.call(a.Data):a.Data),a.ChainID!=null&&a.hasOwnProperty("ChainID")&&(f.ChainID=c.bytes===String?n.base64.encode(a.ChainID,0,a.ChainID.length):c.bytes===Array?Array.prototype.slice.call(a.ChainID):a.ChainID),a.Version!=null&&a.hasOwnProperty("Version")&&(f.Version=a.Version),a.Signature!=null&&a.hasOwnProperty("Signature")&&(f.Signature=c.bytes===String?n.base64.encode(a.Signature,0,a.Signature.length):c.bytes===Array?Array.prototype.slice.call(a.Signature):a.Signature),a.Options!=null&&a.hasOwnProperty("Options")&&(f.Options=a.Options),a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&(f.GuardianAddr=c.bytes===String?n.base64.encode(a.GuardianAddr,0,a.GuardianAddr.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianAddr):a.GuardianAddr),a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&(f.GuardianSignature=c.bytes===String?n.base64.encode(a.GuardianSignature,0,a.GuardianSignature.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianSignature):a.GuardianSignature),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,t.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Transaction"},o}(),s}(),i})});var s8=D(jn=>{"use strict";h();var l$=jn&&jn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),f$=jn&&jn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),h$=jn&&jn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&l$(e,t,r);return f$(e,t),e},d$=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.ProtoSerializer=void 0;var g$=d$((rr(),_e(fr))),gb=Ve(),p$=hr(),m$=h$(Ie()),y$=Bu(),pb=class{serializeTransaction(e){let r=i8().proto,n=new gb.Address(e.getReceiver().bech32()).pubkey(),i=new gb.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?p.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?p.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:p.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==p$.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let a=e.getGuardian();s.GuardianAddr=new gb.Address(a.bech32()).pubkey(),s.GuardianSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return p.Buffer.from(o)}serializeTransactionValue(e){let r=new g$.default(e.toString());if(r.isZero())return p.Buffer.from([0,0]);let n=y$.bigIntToBuffer(r);return n=p.Buffer.concat([p.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new m$.ErrUnsupportedOperation("deserializeTransaction")}};jn.ProtoSerializer=pb});var o8=D(Ga=>{"use strict";h();var w$=Ga&&Ga.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),v$=Ga&&Ga.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&w$(e,t,r)};Object.defineProperty(Ga,"__esModule",{value:!0});v$(s8(),Ga)});var _0=D(zn=>{"use strict";h();var A$=zn&&zn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),E$=zn&&zn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),b$=zn&&zn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&A$(e,t,r);return E$(e,t),e},S$=zn&&zn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zn,"__esModule",{value:!0});zn.TransactionComputer=void 0;var th=b$(Ie()),a8=S$((rr(),_e(fr))),I$=o8(),T$=Xr(),rn=hr(),_$=JA(),C$=sf(),N$=32,mb=class{constructor(){}computeTransactionFee(e,r){let n=BigInt(r.MinGasLimit+e.data.length*r.GasPerDataByte);if(n>e.gasLimit)throw new th.ErrNotEnoughGas(parseInt(e.gasLimit.toString(),10));let i=e.gasPrice,s=n*i;if(n===e.gasLimit)return s;let o=e.gasLimit-n,u=BigInt(new a8.default(i.toString()).multipliedBy(new a8.default(r.GasPriceModifier)).toFixed(0)),a=o*u;return s+a}computeBytesForSigning(e){this.ensureValidTransactionFields(e);let r=this.toPlainObjectForSigning(e),n=JSON.stringify(r);return new Uint8Array(p.Buffer.from(n))}computeBytesForVerifying(e){return this.hasOptionsSetForHashSigning(e)?this.computeHashForSigning(e):this.computeBytesForSigning(e)}computeHashForSigning(e){let r=this.toPlainObjectForSigning(e),n=p.Buffer.from(JSON.stringify(r));return C$("keccak256").update(n).digest()}computeTransactionHash(e){let n=new I$.ProtoSerializer().serializeTransaction(new T$.Transaction(e)),i=_$(N$).update(n).digest("hex");return p.Buffer.from(i,"hex")}hasOptionsSetForGuardedTransaction(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_GUARDED)==rn.TRANSACTION_OPTIONS_TX_GUARDED}hasOptionsSetForHashSigning(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_HASH_SIGN)==rn.TRANSACTION_OPTIONS_TX_HASH_SIGN}applyGuardian(e,r){e.version= ${rn.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`)}};zn.TransactionComputer=mb});var Xr=D(Sc=>{"use strict";h();Object.defineProperty(Sc,"__esModule",{value:!0});Sc.TransactionHash=Sc.Transaction=void 0;var u8=(rr(),_e(fr)),yb=Ve(),wb=hr(),c8=XE(),x$=nD(),l8=$l(),f8=Yf(),O$=Ms(),vb=_0(),Ab=class{constructor(e){this.nonce=BigInt(e.nonce?.valueOf()||0n),this.value=e.value?BigInt(new u8.BigNumber(e.value.toString()).toFixed(0)):0n,this.sender=this.addressAsBech32(e.sender),this.receiver=this.addressAsBech32(e.receiver),this.senderUsername=e.senderUsername||"",this.receiverUsername=e.receiverUsername||"",this.gasPrice=BigInt(e.gasPrice?.valueOf()||wb.TRANSACTION_MIN_GAS_PRICE),this.gasLimit=BigInt(e.gasLimit.valueOf()),this.data=e.data?.valueOf()||new Uint8Array,this.chainID=e.chainID.valueOf(),this.version=Number(e.version?.valueOf()||wb.TRANSACTION_VERSION_DEFAULT),this.options=Number(e.options?.valueOf()||wb.TRANSACTION_OPTIONS_DEFAULT),this.guardian=e.guardian?this.addressAsBech32(e.guardian):"",this.signature=e.signature||p.Buffer.from([]),this.guardianSignature=e.guardianSignature||p.Buffer.from([])}addressAsBech32(e){return typeof e=="string"?e:e.bech32()}getNonce(){return Number(this.nonce)}setNonce(e){this.nonce=BigInt(e.valueOf())}getValue(){return this.value}setValue(e){this.value=BigInt(e.toString())}getSender(){return yb.Address.fromBech32(this.sender)}setSender(e){this.sender=typeof e=="string"?e:e.bech32()}getReceiver(){return yb.Address.fromBech32(this.receiver)}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return new yb.Address(this.guardian)}getGasPrice(){return Number(this.gasPrice)}setGasPrice(e){this.gasPrice=BigInt(e.valueOf())}getGasLimit(){return Number(this.gasLimit)}setGasLimit(e){this.gasLimit=BigInt(e.valueOf())}getData(){return new O$.TransactionPayload(p.Buffer.from(this.data))}getChainID(){return this.chainID}setChainID(e){this.chainID=e.valueOf()}getVersion(){return new l8.TransactionVersion(this.version)}setVersion(e){this.version=e.valueOf()}getOptions(){return new l8.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=e.valueOf()}getSignature(){return p.Buffer.from(this.signature)}getGuardianSignature(){return p.Buffer.from(this.guardianSignature)}setGuardian(e){this.guardian=typeof e=="string"?e:e.bech32()}getHash(){return C0.compute(this)}serializeForSigning(){let r=new vb.TransactionComputer().computeBytesForSigning(this);return p.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){return new c8.TransactionsConverter().transactionToPlainObject(this)}static fromPlainObject(e){return new c8.TransactionsConverter().plainObjectToTransaction(e)}applySignature(e){this.signature=f8.interpretSignatureAsBuffer(e)}applyGuardianSignature(e){this.guardianSignature=f8.interpretSignatureAsBuffer(e)}toSendable(){return this.toPlainObject()}computeFee(e){let n=new vb.TransactionComputer().computeTransactionFee(this,e);return new u8.BigNumber(n.toString())}};Sc.Transaction=Ab;var C0=class t extends x$.Hash{constructor(e){super(e)}static compute(e){let n=new vb.TransactionComputer().computeTransactionHash(e);return new t(p.Buffer.from(n).toString("hex"))}};Sc.TransactionHash=C0});var d8=D(N0=>{"use strict";h();Object.defineProperty(N0,"__esModule",{value:!0});N0.TokenOperationsFactory=void 0;var Eb=hr(),D$=oo(),h8=$l(),P$=Xr(),R$=Ms(),ae=Kd(),bb=class{constructor(e){this.config=e,this.trueAsHex=ae.utf8ToHex("true"),this.falseAsHex=ae.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.initialSupply),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){D$.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex(e.tokenType),ae.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleLocalMint?[ae.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ae.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ae.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ae.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ae.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.initialQuantity),ae.utf8ToHex(e.name),ae.bigIntToHex(e.royalties),ae.utf8ToHex(e.hash),ae.bufferToHex(e.attributes),...e.uris.map(ae.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:u,dataParts:a}){let c=this.buildTransactionPayload(a),f=o||this.computeGasLimit(c,u),d=new d8.TransactionVersion(Ab.TRANSACTION_VERSION_DEFAULT),w=new d8.TransactionOptions(Ab.TRANSACTION_OPTIONS_DEFAULT);return new y$.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:w})}buildTransactionPayload(e){let r=e.join(Ab.ARGUMENTS_SEPARATOR);return new w$.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};O0.TokenOperationsFactory=Eb});var p8=B(D0=>{"use strict";h();Object.defineProperty(D0,"__esModule",{value:!0});D0.TokenOperationsFactoryConfig=void 0;var v$=Ve(),bb=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=v$.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};D0.TokenOperationsFactoryConfig=bb});var y8=B(P0=>{"use strict";h();Object.defineProperty(P0,"__esModule",{value:!0});P0.TokenOperationsOutcomeParser=void 0;var A$=Ve(),Sb=Ie(),m8=$d(),Ib=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=r.topics[3]?.valueOf();return{tokenIdentifier:n,nonce:i,attributes:s}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){for(let r of e.logs.events)if(r.identifier=="signalError"){let n=p.Buffer.from(r.data.substring(1),"hex").toString(),i=r.topics[1]?.valueOf().toString();throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${i} (${n})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){return e.topics[0]?.valueOf().toString()}extractNonce(e){return m8.bufferToBigInt(e.topics[1]?.valueOf()).toFixed(0)}extractAmount(e){return m8.bufferToBigInt(e.topics[2]?.valueOf()).toFixed(0)}extractAddress(e){return A$.Address.fromBuffer(e.topics[3]?.valueOf()).toString()}};P0.TokenOperationsOutcomeParser=Ib});var _b=B(Ls=>{"use strict";h();var E$=Ls&&Ls.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Tb=Ls&&Ls.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&E$(e,t,r)};Object.defineProperty(Ls,"__esModule",{value:!0});Tb(g8(),Ls);Tb(p8(),Ls);Tb(y8(),Ls)});var w8=B(R0=>{"use strict";h();Object.defineProperty(R0,"__esModule",{value:!0});R0.DelegationTransactionsOutcomeParser=void 0;var b$=Ve(),S$=Ie(),I$=Ac(),Cb=class{constructor(){}parseCreateNewDelegationContract(e){return this.ensureNoError(e.logs.events),I$.findEventsByIdentifier(e,"SCDeploy").map(n=>({contractAddress:this.extractContractAddress(n)}))}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new S$.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractContractAddress(e){if(!e.topics[0]?.length)return"";let r=p.Buffer.from(e.topics[0]);return b$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};R0.DelegationTransactionsOutcomeParser=Cb});var E8=B(B0=>{"use strict";h();Object.defineProperty(B0,"__esModule",{value:!0});B0.SmartContractTransactionsOutcomeParser=void 0;var v8=Ve(),T$=Ie(),A8=qn(),_$=Ac(),Nb=class{constructor(e){this.abi=e?.abi,this.legacyResultsParser=e?.legacyResultsParser||new A8.ResultsParser}parseDeploy(e){let r=e.transactionOutcome.directSmartContractCallOutcome,i=_$.findEventsByIdentifier(e.transactionOutcome,"SCDeploy").map(s=>this.parseScDeployEvent(s));return{returnCode:r.returnCode,returnMessage:r.returnMessage,contracts:i}}parseScDeployEvent(e){let r=e.topics[0],n=e.topics[1],i=e.topics[2],s=r?.length?new v8.Address(r).toBech32():"",o=n?.length?new v8.Address(n).toBech32():"";return{address:s,ownerAddress:o,codeHash:i}}parseExecute(e){let r=e.transactionOutcome.directSmartContractCallOutcome;if(!this.abi)return{values:r.returnDataParts,returnCode:r.returnCode,returnMessage:r.returnMessage};let n=e.function||r.function;if(!n)throw new T$.Err('Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?');let i=this.abi.getEndpoint(n),s={returnCode:new A8.ReturnCode(r.returnCode),returnMessage:r.returnMessage,values:r.returnDataParts.map(u=>p.Buffer.from(u))},o=this.legacyResultsParser.parseOutcomeFromUntypedBundle(s,i);return{values:o.values.map(u=>u.valueOf()),returnCode:o.returnCode.toString(),returnMessage:o.returnMessage}}};B0.SmartContractTransactionsOutcomeParser=Nb});var I8=B(M0=>{"use strict";h();Object.defineProperty(M0,"__esModule",{value:!0});M0.TokenManagementTransactionsOutcomeParser=void 0;var C$=Ve(),b8=Ie(),S8=Bu(),wr=Ac(),xb=class{constructor(){}parseIssueFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issue").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueNonFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueNonFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueSemiFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueSemiFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterMetaEsdt(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"registerMetaESDT").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterAndSetAllRoles(e){this.ensureNoError(e.logs.events);let r=wr.findEventsByIdentifier(e,"registerAndSetAllRoles"),n=wr.findEventsByIdentifier(e,"ESDTSetRole");if(r.length!==n.length)throw new b8.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events.");return r.map((i,s)=>{let o=this.extractTokenIdentifier(i),a=n[s].topics.slice(3).map(c=>this.decodeTopicAsString(c));return{tokenIdentifier:o,roles:a}})}parseSetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseUnsetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseSetSpecialRole(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTSetRole").map(n=>this.getOutputForSetSpecialRoleEvent(n))}getOutputForSetSpecialRoleEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),s=e.topics.slice(3).map(o=>this.decodeTopicAsString(o));return{userAddress:r,tokenIdentifier:n,roles:s}}parseNftCreate(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTCreate").map(n=>this.getOutputForNftCreateEvent(n))}getOutputForNftCreateEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,initialQuantity:i}}parseLocalMint(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalMint").map(n=>this.getOutputForLocalMintEvent(n))}getOutputForLocalMintEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,mintedSupply:s}}parseLocalBurn(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalBurn").map(n=>this.getOutputForLocalBurnEvent(n))}getOutputForLocalBurnEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,burntSupply:s}}parsePause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseUnpause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseFreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTFreeze").map(n=>this.getOutputForFreezeEvent(n))}getOutputForFreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnFreeze").map(n=>this.getOutputForUnfreezeEvent(n))}getOutputForUnfreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTWipe").map(n=>this.getOutputForWipeEvent(n))}getOutputForWipeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTUpdateAttributes").map(n=>this.getOutputForUpdateAttributesEvent(n))}getOutputForUpdateAttributesEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=e.topics[3]?e.topics[3]:new Uint8Array;return{tokenIdentifier:r,nonce:n,attributes:i}}parseAddQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTAddQuantity").map(n=>this.getOutputForAddQuantityEvent(n))}getOutputForAddQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,addedQuantity:i}}parseBurnQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTBurn").map(n=>this.getOutputForBurnQuantityEvent(n))}getOutputForBurnQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,burntQuantity:i}}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new b8.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractTokenIdentifier(e){return e.topics[0]?.length?this.decodeTopicAsString(e.topics[0]):""}extractNonce(e){if(!e.topics[1]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[1]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAmount(e){if(!e.topics[2]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[2]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAddress(e){if(!e.topics[3]?.length)return"";let r=p.Buffer.from(e.topics[3]);return C$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};M0.TokenManagementTransactionsOutcomeParser=xb});var T8=B(L0=>{"use strict";h();Object.defineProperty(L0,"__esModule",{value:!0});L0.TransactionEventsParser=void 0;var N$=qn(),Ob=class{constructor(e){this.legacyResultsParser=new N$.ResultsParser,this.abi=e.abi,this.firstTopicIsIdentifier=e.firstTopicIsIdentifier??!0}parseEvents(e){let r=[];for(let n of e.events){let i=this.parseEvent({event:n});r.push(i)}return r}parseEvent(e){let r=e.event.topics.map(u=>p.Buffer.from(u)),n=this.firstTopicIsIdentifier?r[0]?.toString():e.event.identifier;this.firstTopicIsIdentifier&&r.shift();let i=e.event.dataItems.map(u=>p.Buffer.from(u)),s=this.abi.getEvent(n);return this.legacyResultsParser.doParseEvent({topics:r,dataItems:i,eventDefinition:s})}};L0.TransactionEventsParser=Ob});var Db=B(vi=>{"use strict";h();var x$=vi&&vi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=vi&&vi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&x$(e,t,r)};Object.defineProperty(vi,"__esModule",{value:!0});rh(w8(),vi);rh(Ac(),vi);rh(E8(),vi);rh(I8(),vi);rh(T8(),vi)});var Ic=B(F0=>{"use strict";h();Object.defineProperty(F0,"__esModule",{value:!0});F0.Account=void 0;var O$=Ve(),Pb=class{constructor(e){this.address=O$.Address.empty(),this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};F0.Account=Pb});var Bb=B(Tc=>{"use strict";h();Object.defineProperty(Tc,"__esModule",{value:!0});Tc.MessageComputer=Tc.Message=void 0;var nh=hr(),D$=Ve(),P$=sf(),U0=class{constructor(e){this.data=e.data,this.signature=e.signature,this.address=e.address,this.version=e.version||nh.DEFAULT_MESSAGE_VERSION,this.signer=e.signer||nh.SDK_JS_SIGNER}};Tc.Message=U0;var Rb=class{constructor(){}computeBytesForSigning(e){let r=p.Buffer.from(e.data.length.toString()),n=p.Buffer.concat([r,e.data]),i=p.Buffer.concat([p.Buffer.from(nh.MESSAGE_PREFIX),n]);return P$("keccak256").update(i).digest()}computeBytesForVerifying(e){return this.computeBytesForSigning(e)}packMessage(e){return{message:p.Buffer.from(e.data).toString("hex"),signature:e.signature?p.Buffer.from(e.signature).toString("hex"):"",address:e.address?e.address.bech32():"",version:e.version,signer:e.signer}}unpackMessage(e){let r=this.trimHexPrefix(e.message),n=p.Buffer.from(r,"hex"),i=this.trimHexPrefix(e.signature||""),s=p.Buffer.from(i,"hex"),o;e.address&&(o=D$.Address.fromBech32(e.address));let u=e.version||nh.DEFAULT_MESSAGE_VERSION,a=e.signer||nh.UNKNOWN_SIGNER;return new U0({data:n,signature:s,address:o,version:u,signer:a})}trimHexPrefix(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}};Tc.MessageComputer=Rb});var Fb=B(Xi=>{"use strict";h();var R$=Xi&&Xi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),B$=Xi&&Xi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Xi&&Xi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&R$(e,t,r);return B$(e,t),e};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AsyncTimer=void 0;var L$=M$(Ie()),F$=Ie(),Mb=oo(),Lb=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new L$.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new F$.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};Xi.AsyncTimer=Lb});var V0=B(q0=>{"use strict";h();Object.defineProperty(q0,"__esModule",{value:!0});q0.TransactionWatcher=void 0;var Ub=Fb(),_8=hr(),Fs=Ie(),C8=oo(),No=class t{constructor(e,r={}){this.fetcher=new qb(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}async awaitPending(e){let r=s=>s.status.isPending(),n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitCompleted(e){let r=s=>{if(s.isCompleted===void 0)throw new Fs.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitAllEvents(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>u.includes(c))},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitAnyEvent(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>u.includes(c))!=null},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitOnCondition(e,r){let n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}transactionOrTxHashToTxHash(e){let r=typeof e=="string"?e:e.getHash().hex();if(r.length!==_8.HEX_TRANSACTION_HASH_LENGTH)throw new Fs.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${_8.HEX_TRANSACTION_HASH_LENGTH}.`);return r}async awaitConditionally(e,r,n){let i=new Ub.AsyncTimer("watcher:periodic"),s=new Ub.AsyncTimer("watcher:patience"),o=new Ub.AsyncTimer("watcher:timeout"),u=!1,a,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),u=!0});!u;){await i.start(this.pollingIntervalMilliseconds);try{if(a=await r(),c=e(a),c||u)break}catch(f){if(C8.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Fs.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Fs.Err))throw f}}if(c&&await s.start(this.patienceMilliseconds),o.isStopped()||o.stop(),!a||!c)throw n();return a}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};q0.TransactionWatcher=No;No.DefaultPollingInterval=6e3;No.DefaultTimeout=No.DefaultPollingInterval*15;No.DefaultPatience=0;No.NoopOnStatusReceived=t=>{};var qb=class{constructor(e){this.fetcher=e}async getTransaction(e){return C8.Logger.debug(`transactionWatcher, getTransaction(${e})`),await this.fetcher.getTransaction(e)}}});var H0=B(k0=>{"use strict";h();Object.defineProperty(k0,"__esModule",{value:!0});k0.SignableMessage=void 0;var U$=Ve(),q$=Yf(),V$=hr(),k$=sf(),Vb=class{constructor(e){this.message=p.Buffer.from([]),this.signature=p.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=U$.Address.empty(),Object.assign(this,e)}serializeForSigning(){let e=p.Buffer.from(this.message.length.toString()),r=p.Buffer.concat([e,this.message]),n=p.Buffer.concat([p.Buffer.from(V$.MESSAGE_PREFIX),r]);return k$("keccak256").update(n).digest()}serializeForSigningRaw(){return p.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=q$.interpretSignatureAsBuffer(e)}getMessageSize(){let e=p.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};k0.SignableMessage=Vb});var _c=B(vr=>{"use strict";h();var H$=vr&&vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),G$=vr&&vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),j$=vr&&vr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H$(e,t,r);return G$(e,t),e};Object.defineProperty(vr,"__esModule",{value:!0});vr.zeroPadStringIfOddLength=vr.isPaddedHex=vr.numberToPaddedHex=vr.Nonce=vr.Address=void 0;var N8=j$(wv()),z$="erd",kb=class t{constructor(e){this.value=e}static fromPubkey(e){let r=N8.toWords(e),n=N8.encode(z$,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};vr.Address=kb;var Hb=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return x8(this.value)}};vr.Nonce=Hb;function x8(t){let e=t.toString(16);return O8(e)}vr.numberToPaddedHex=x8;function Q$(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}vr.isPaddedHex=Q$;function O8(t){return t=t||"",t.length%2==1?"0"+t:t}vr.zeroPadStringIfOddLength=O8});var D8=B(xo=>{"use strict";h();var K$=xo&&xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xo,"__esModule",{value:!0});xo.EsdtContractAddress=xo.MaxUint64AsBigNumber=void 0;var W$=K$((rr(),_e(fr))),$$=_c();xo.MaxUint64AsBigNumber=new W$.default("18446744073709551615");xo.EsdtContractAddress=new $$.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var jb=B(Cc=>{"use strict";h();var Y$=Cc&&Cc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ContractQueryResponse=void 0;var J$=Y$((rr(),_e(fr))),X$=D8(),Gb=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new J$.default(e.gasRemaining||e.GasRemaining||0),o=X$.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>p.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Cc.ContractQueryResponse=Gb});var P8=B(Oo=>{"use strict";h();Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ErrAccountNotConnected=Oo.ErrCannotSignSingleTransaction=Oo.Err=void 0;var ih=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Oo.Err=ih;var zb=class extends ih{constructor(){super("Cannot sign single transaction.")}};Oo.ErrCannotSignSingleTransaction=zb;var Qb=class extends ih{constructor(){super("Account is not connected.")}};Oo.ErrAccountNotConnected=Qb});var R8=B(sh=>{"use strict";h();Object.defineProperty(sh,"__esModule",{value:!0});sh.Operation=void 0;var Z$;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(Z$=sh.Operation||(sh.Operation={}))});var Kb=B(Nc=>{"use strict";h();var Do=Nc&&Nc.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Nc,"__esModule",{value:!0});Nc.ExtensionProvider=void 0;var eY=Xr(),B8=P8(),oh=R8(),ah=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return Do(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(oh.Operation.Connect,n),this.account.address})}logout(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(oh.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return Do(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new B8.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new B8.ErrAccountNotConnected}signTransactions(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(oh.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>eY.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(oh.Operation.SignMessage,r)).signature,s=p.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(oh.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};Nc.ExtensionProvider=ah;ah._instance=new ah});function iY(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){sY(t);return}return e}function sY(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function uh(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!nY.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(tY.test(t)||rY.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,iY)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var tY,rY,nY,q8=fe(()=>{h();tY=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,rY=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,nY=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function oY(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function gr(t,...e){try{return oY(t(...e))}catch(r){return Promise.reject(r)}}function aY(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function uY(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ch(t){if(aY(t))return String(t);if(uY(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ch(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function V8(){if(typeof p.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function k8(t){if(typeof t=="string")return t;V8();let e=p.Buffer.from(t).toString("base64");return Wb+e}function H8(t){return typeof t!="string"||!t.startsWith(Wb)?t:(V8(),p.Buffer.from(t.slice(Wb.length),"base64"))}function Vr(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function G8(...t){return Vr(t.join(":"))}function lh(t){return t=Vr(t),t?t+":":""}var Wb,j8=fe(()=>{h();Wb="base64:"});function K8(t={}){let e={mounts:{"":t.driver||lY()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=Vr(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await z8(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},u=(c,f,d)=>{let w=new Map,A=T=>{let x=w.get(T.base);return x||(x={driver:T.driver,base:T.base,items:[]},w.set(T.base,x)),x};for(let T of c){let x=typeof T=="string",R=Vr(x?T:T.key),V=x?void 0:T.value,U=x||!T.options?f:{...f,...T.options},Q=r(R);A(Q).items.push({key:R,value:V,relativeKey:Q.relativeKey,options:U})}return Promise.all([...w.values()].map(T=>d(T))).then(T=>T.flat())},a={hasItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.hasItem,d,f)},getItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.getItem,d,f).then(A=>uh(A))},getItems(c,f){return u(c,f,d=>d.driver.getItems?gr(d.driver.getItems,d.items.map(w=>({key:w.relativeKey,options:w.options})),f).then(w=>w.map(A=>({key:G8(d.base,A.key),value:uh(A.value)}))):Promise.all(d.items.map(w=>gr(d.driver.getItem,w.relativeKey,w.options).then(A=>({key:w.key,value:uh(A)})))))},getItemRaw(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return w.getItemRaw?gr(w.getItemRaw,d,f):gr(w.getItem,d,f).then(A=>H8(A))},async setItem(c,f,d={}){if(f===void 0)return a.removeItem(c);c=Vr(c);let{relativeKey:w,driver:A}=r(c);A.setItem&&(await gr(A.setItem,w,ch(f),d),A.watch||i("update",c))},async setItems(c,f){await u(c,f,async d=>{if(d.driver.setItems)return gr(d.driver.setItems,d.items.map(w=>({key:w.relativeKey,value:ch(w.value),options:w.options})),f);d.driver.setItem&&await Promise.all(d.items.map(w=>gr(d.driver.setItem,w.relativeKey,ch(w.value),w.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return a.removeItem(c,d);c=Vr(c);let{relativeKey:w,driver:A}=r(c);if(A.setItemRaw)await gr(A.setItemRaw,w,f,d);else if(A.setItem)await gr(A.setItem,w,k8(f),d);else return;A.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c);w.removeItem&&(await gr(w.removeItem,d,f),(f.removeMeta||f.removeMata)&&await gr(w.removeItem,d+"$",f),w.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c),A=Object.create(null);if(w.getMeta&&Object.assign(A,await gr(w.getMeta,d,f)),!f.nativeOnly){let T=await gr(w.getItem,d+"$",f).then(x=>uh(x));T&&typeof T=="object"&&(typeof T.atime=="string"&&(T.atime=new Date(T.atime)),typeof T.mtime=="string"&&(T.mtime=new Date(T.mtime)),Object.assign(A,T))}return A},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=lh(c);let d=n(c,!0),w=[],A=[];for(let T of d){let R=(await gr(T.driver.getKeys,T.relativeBase,f)).map(V=>T.mountpoint+Vr(V)).filter(V=>!w.some(U=>V.startsWith(U)));A.push(...R),w=[T.mountpoint,...w.filter(V=>!V.startsWith(T.mountpoint))]}return c?A.filter(T=>T.startsWith(c)&&!T.endsWith("$")):A.filter(T=>!T.endsWith("$"))},async clear(c,f={}){c=lh(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return gr(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let w=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(w.map(A=>d.driver.removeItem(A,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>Q8(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=lh(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,w)=>w.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(z8(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),a},async unmount(c,f=!0){c=lh(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await Q8(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=Vr(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=Vr(c),n(c,f.parents).map(w=>({driver:w.driver,base:w.mountpoint}))}};return a}function z8(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function Q8(t){typeof t.dispose=="function"&&await gr(t.dispose)}var cY,lY,W8=fe(()=>{h();q8();j8();cY="memory",lY=()=>{let t=new Map;return{name:cY,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function za(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Yb(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=za(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function fh(){return $b||($b=Yb("keyval-store","keyval")),$b}function Jb(t,e=fh()){return e("readonly",r=>za(r.get(t)))}function $8(t,e,r=fh()){return r("readwrite",n=>(n.put(e,t),za(n.transaction)))}function Y8(t,e=fh()){return e("readwrite",r=>(r.delete(t),za(r.transaction)))}function J8(t=fh()){return t("readwrite",e=>(e.clear(),za(e.transaction)))}function fY(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},za(t.transaction)}function X8(t=fh()){return t("readonly",e=>{if(e.getAllKeys)return za(e.getAllKeys());let r=[];return fY(e,n=>r.push(n.key)).then(()=>r)})}var $b,Z8=fe(()=>{h()});var eP={};Bt(eP,{safeJsonParse:()=>Ro,safeJsonStringify:()=>Ai});function Ro(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return dY(t)}catch{return t}}function Ai(t){return typeof t=="string"?t:hY(t)||""}var hY,dY,xc=fe(()=>{h();hY=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),dY=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var rP={};Bt(rP,{KeyValueStorage:()=>tS,default:()=>tS});function wY(t){var e;return[t[0],Ro((e=t[1])!=null?e:"")]}var gY,pY,mY,yY,Zb,Xb,Q0,eS,vY,tP,AY,EY,tS,nP=fe(()=>{h();W8();Z8();xc();gY="idb-keyval",pY=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Yb(t.dbName,t.storeName)),{name:gY,options:t,async hasItem(i){return!(typeof await Jb(r(i),n)>"u")},async getItem(i){return await Jb(r(i),n)??null},setItem(i,s){return $8(r(i),s,n)},removeItem(i){return Y8(r(i),n)},getKeys(){return X8(n)},clear(){return J8(n)}}},mY="WALLET_CONNECT_V2_INDEXED_DB",yY="keyvaluestorage",Zb=class{constructor(){this.indexedDb=K8({driver:pY({dbName:mY,storeName:yY})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ai(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Xb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Q0={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Xb<"u"&&Xb.localStorage?Q0.exports=Xb.localStorage:typeof window<"u"&&window.localStorage?Q0.exports=window.localStorage:Q0.exports=new e})();eS=class{constructor(){this.localStorage=Q0.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(wY)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return Ro(r)}async setItem(e,r){this.localStorage.setItem(e,Ai(r))}async removeItem(e){this.localStorage.removeItem(e)}},vY="wc_storage_version",tP=1,AY=async(t,e,r)=>{let n=vY,i=await e.getItem(n);if(i&&i>=tP){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let u=s.shift();if(!u)continue;let a=u.toLowerCase();if(a.includes("wc@")||a.includes("walletconnect")||a.includes("wc_")||a.includes("wallet_connect")){let c=await t.getItem(u);await e.setItem(u,c),o.push(u)}}await e.setItem(n,tP),r(e),EY(t,o)},EY=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},tS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new eS;this.storage=e;try{let r=new Zb;AY(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zi={};Bt(Zi,{__assign:()=>nS,__asyncDelegator:()=>BY,__asyncGenerator:()=>RY,__asyncValues:()=>MY,__await:()=>hh,__awaiter:()=>CY,__classPrivateFieldGet:()=>qY,__classPrivateFieldSet:()=>VY,__createBinding:()=>xY,__decorate:()=>IY,__exportStar:()=>OY,__extends:()=>bY,__generator:()=>NY,__importDefault:()=>UY,__importStar:()=>FY,__makeTemplateObject:()=>LY,__metadata:()=>_Y,__param:()=>TY,__read:()=>iP,__rest:()=>SY,__spread:()=>DY,__spreadArrays:()=>PY,__values:()=>iS});function bY(t,e){rS(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function SY(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;u--)(o=t[u])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function TY(t,e){return function(r,n){e(r,n,t)}}function _Y(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function CY(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})}function NY(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(c){return function(f){return a([c,f])}}function a(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function iP(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function DY(){for(var t=[],e=0;e1||u(w,A)})})}function u(w,A){try{a(n[w](A))}catch(T){d(s[0][3],T)}}function a(w){w.value instanceof hh?Promise.resolve(w.value.v).then(c,f):d(s[0][2],w)}function c(w){u("next",w)}function f(w){u("throw",w)}function d(w,A){w(A),s.shift(),s.length&&u(s[0][0],s[0][1])}}function BY(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:hh(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function MY(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof iS=="function"?iS(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(u,a){o=t[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(c){s({value:c,done:u})},o)}}function LY(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function FY(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function UY(t){return t&&t.__esModule?t:{default:t}}function qY(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function VY(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rS,nS,es=fe(()=>{h();rS=function(t,e){return rS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},rS(t,e)};nS=function(){return nS=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";h();Object.defineProperty(K0,"__esModule",{value:!0});K0.delay=void 0;function kY(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}K0.delay=kY});var oP=B(Oc=>{"use strict";h();Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ONE_THOUSAND=Oc.ONE_HUNDRED=void 0;Oc.ONE_HUNDRED=100;Oc.ONE_THOUSAND=1e3});var aP=B(le=>{"use strict";h();Object.defineProperty(le,"__esModule",{value:!0});le.ONE_YEAR=le.FOUR_WEEKS=le.THREE_WEEKS=le.TWO_WEEKS=le.ONE_WEEK=le.THIRTY_DAYS=le.SEVEN_DAYS=le.FIVE_DAYS=le.THREE_DAYS=le.ONE_DAY=le.TWENTY_FOUR_HOURS=le.TWELVE_HOURS=le.SIX_HOURS=le.THREE_HOURS=le.ONE_HOUR=le.SIXTY_MINUTES=le.THIRTY_MINUTES=le.TEN_MINUTES=le.FIVE_MINUTES=le.ONE_MINUTE=le.SIXTY_SECONDS=le.THIRTY_SECONDS=le.TEN_SECONDS=le.FIVE_SECONDS=le.ONE_SECOND=void 0;le.ONE_SECOND=1;le.FIVE_SECONDS=5;le.TEN_SECONDS=10;le.THIRTY_SECONDS=30;le.SIXTY_SECONDS=60;le.ONE_MINUTE=le.SIXTY_SECONDS;le.FIVE_MINUTES=le.ONE_MINUTE*5;le.TEN_MINUTES=le.ONE_MINUTE*10;le.THIRTY_MINUTES=le.ONE_MINUTE*30;le.SIXTY_MINUTES=le.ONE_MINUTE*60;le.ONE_HOUR=le.SIXTY_MINUTES;le.THREE_HOURS=le.ONE_HOUR*3;le.SIX_HOURS=le.ONE_HOUR*6;le.TWELVE_HOURS=le.ONE_HOUR*12;le.TWENTY_FOUR_HOURS=le.ONE_HOUR*24;le.ONE_DAY=le.TWENTY_FOUR_HOURS;le.THREE_DAYS=le.ONE_DAY*3;le.FIVE_DAYS=le.ONE_DAY*5;le.SEVEN_DAYS=le.ONE_DAY*7;le.THIRTY_DAYS=le.ONE_DAY*30;le.ONE_WEEK=le.SEVEN_DAYS;le.TWO_WEEKS=le.ONE_WEEK*2;le.THREE_WEEKS=le.ONE_WEEK*3;le.FOUR_WEEKS=le.ONE_WEEK*4;le.ONE_YEAR=le.ONE_DAY*365});var sS=B(W0=>{"use strict";h();Object.defineProperty(W0,"__esModule",{value:!0});var uP=(es(),_e(Zi));uP.__exportStar(oP(),W0);uP.__exportStar(aP(),W0)});var lP=B(Dc=>{"use strict";h();Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromMiliseconds=Dc.toMiliseconds=void 0;var cP=sS();function HY(t){return t*cP.ONE_THOUSAND}Dc.toMiliseconds=HY;function GY(t){return Math.floor(t/cP.ONE_THOUSAND)}Dc.fromMiliseconds=GY});var hP=B($0=>{"use strict";h();Object.defineProperty($0,"__esModule",{value:!0});var fP=(es(),_e(Zi));fP.__exportStar(sP(),$0);fP.__exportStar(lP(),$0)});var dP=B(dh=>{"use strict";h();Object.defineProperty(dh,"__esModule",{value:!0});dh.Watch=void 0;var Y0=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};dh.Watch=Y0;dh.default=Y0});var gP=B(J0=>{"use strict";h();Object.defineProperty(J0,"__esModule",{value:!0});J0.IWatch=void 0;var oS=class{};J0.IWatch=oS});var pP=B(aS=>{"use strict";h();Object.defineProperty(aS,"__esModule",{value:!0});var jY=(es(),_e(Zi));jY.__exportStar(gP(),aS)});var Qa=B(Pc=>{"use strict";h();Object.defineProperty(Pc,"__esModule",{value:!0});var X0=(es(),_e(Zi));X0.__exportStar(hP(),Pc);X0.__exportStar(dP(),Pc);X0.__exportStar(pP(),Pc);X0.__exportStar(sS(),Pc)});var uS,mP=fe(()=>{h();uS=class{}});var cS={};Bt(cS,{IEvents:()=>uS});var lS=fe(()=>{h();mP()});var yP=B(Z0=>{"use strict";h();Object.defineProperty(Z0,"__esModule",{value:!0});Z0.IHeartBeat=void 0;var zY=(lS(),_e(cS)),fS=class extends zY.IEvents{constructor(e){super()}};Z0.IHeartBeat=fS});var dS=B(hS=>{"use strict";h();Object.defineProperty(hS,"__esModule",{value:!0});var QY=(es(),_e(Zi));QY.__exportStar(yP(),hS)});var wP=B(Rc=>{"use strict";h();Object.defineProperty(Rc,"__esModule",{value:!0});Rc.HEARTBEAT_EVENTS=Rc.HEARTBEAT_INTERVAL=void 0;var KY=Qa();Rc.HEARTBEAT_INTERVAL=KY.FIVE_SECONDS;Rc.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var pS=B(gS=>{"use strict";h();Object.defineProperty(gS,"__esModule",{value:!0});var WY=(es(),_e(Zi));WY.__exportStar(wP(),gS)});var vP=B(em=>{"use strict";h();Object.defineProperty(em,"__esModule",{value:!0});em.HeartBeat=void 0;var mS=(es(),_e(Zi)),$Y=Ds(),YY=Qa(),JY=dS(),yS=pS(),wS=class t extends JY.IHeartBeat{constructor(e){super(e),this.events=new $Y.EventEmitter,this.interval=yS.HEARTBEAT_INTERVAL,this.interval=e?.interval||yS.HEARTBEAT_INTERVAL}static init(e){return mS.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return mS.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return mS.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),YY.toMiliseconds(this.interval))})}pulse(){this.events.emit(yS.HEARTBEAT_EVENTS.pulse)}};em.HeartBeat=wS});var AP=B(gh=>{"use strict";h();Object.defineProperty(gh,"__esModule",{value:!0});var vS=(es(),_e(Zi));vS.__exportStar(vP(),gh);vS.__exportStar(dS(),gh);vS.__exportStar(pS(),gh)});var bP=B((AAe,EP)=>{"use strict";h();function XY(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}EP.exports=ZY;function ZY(t,e,r){var n=r&&r.stringify||XY,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var u=1;u-1?d:0,t.charCodeAt(A+1)){case 100:case 102:if(f>=a||e[f]==null)break;d=a||e[f]==null)break;d=a||e[f]===void 0)break;d",d=A+2,A++;break}c+=n(e[f]),d=A+2,A++;break;case 115:if(f>=a)break;d{"use strict";h();var SP=bP();_P.exports=ts;var ph=cJ().console||{},eJ={mapHttpRequest:tm,mapHttpResponse:tm,wrapRequestSerializer:AS,wrapResponseSerializer:AS,wrapErrorSerializer:AS,req:tm,res:tm,err:sJ};function tJ(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ts(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||ph;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=tJ(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let u=t.level||"info",a=Object.create(r);a.log||(a.log=mh),Object.defineProperty(a,"levelVal",{get:f}),Object.defineProperty(a,"level",{get:d,set:w});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:oJ(t)};a.levels=ts.levels,a.level=u,a.setMaxListeners=a.getMaxListeners=a.emit=a.addListener=a.on=a.prependListener=a.once=a.prependOnceListener=a.removeListener=a.removeAllListeners=a.listeners=a.listenerCount=a.eventNames=a.write=a.flush=mh,a.serializers=n,a._serialize=i,a._stdErrSerialize=s,a.child=A,e&&(a._logEvent=ES());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function w(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,Bc(c,a,"error","log"),Bc(c,a,"fatal","error"),Bc(c,a,"warn","error"),Bc(c,a,"info","log"),Bc(c,a,"debug","log"),Bc(c,a,"trace","log")}function A(T,x){if(!T)throw new Error("missing bindings for child Pino");x=x||{},i&&T.serializers&&(x.serializers=T.serializers);let R=x.serializers;if(i&&R){var V=Object.assign({},n,R),U=t.browser.serialize===!0?Object.keys(V):i;delete T.serializers,rm([T],U,V,this._stdErrSerialize)}function Q(L){this._childLevel=(L._childLevel|0)+1,this.error=Mc(L,T,"error"),this.fatal=Mc(L,T,"fatal"),this.warn=Mc(L,T,"warn"),this.info=Mc(L,T,"info"),this.debug=Mc(L,T,"debug"),this.trace=Mc(L,T,"trace"),V&&(this.serializers=V,this._serialize=U),e&&(this._logEvent=ES([].concat(L._logEvent.bindings,T)))}return Q.prototype=this,new Q(this)}return a}ts.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};ts.stdSerializers=eJ;ts.stdTimeFunctions=Object.assign({},{nullTime:IP,epochTime:TP,unixTime:aJ,isoTime:uJ});function Bc(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mh:i[r]?i[r]:ph[r]||ph[n]||mh,rJ(t,e,r)}function rJ(t,e,r){!t.transmit&&e[r]===mh||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ph?ph:this;for(var a=0;a-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Mc(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;iam,PINO_CUSTOM_CONTEXT_KEY:()=>Lc,PINO_LOGGER_DEFAULTS:()=>OP,formatChildLoggerContext:()=>BP,generateChildLogger:()=>mJ,generateClientLogger:()=>MP,generatePlatformLogger:()=>yJ,generateServerLogger:()=>LP,getBrowserLoggerContext:()=>DP,getDefaultLoggerOptions:()=>pJ,getLoggerContext:()=>RP,pino:()=>xP.default,setBrowserLoggerContext:()=>PP});function pJ(t){return om(sm({},t),{level:t?.level||OP.level})}function DP(t,e=Lc){return t[e]||""}function PP(t,e,r=Lc){return t[r]=e,t}function RP(t,e=Lc){let r="";return typeof t.bindings>"u"?r=DP(t,e):r=t.bindings().context||"",r}function BP(t,e,r=Lc){let n=RP(t,r);return n.trim()?`${n}/${e}`:e}function mJ(t,e,r=Lc){let n=BP(t,e,r),i=t.child({context:n});return PP(i,n,r)}function MP(t){var e,r;let n=new IS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace",browser:om(sm({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function LP(t){var e;let r=new TS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function yJ(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?MP(t):LP(t)}var Us,xP,OP,Lc,am,SS,nm,im,IS,TS,lJ,fJ,hJ,CP,dJ,gJ,NP,sm,om,CS=fe(()=>{h();Us=pe(bS()),xP=pe(bS());xc();OP={level:"info"},Lc="custom_context",am=1e3*1024,SS=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},nm=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let r=new SS(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let r=e.value;return e=e.next,{done:!1,value:r}}}}},im=class{constructor(e,r=am){this.level=e??"error",this.levelValue=Us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Us.levels.values.error?console.error(e):r===Us.levels.values.warn?console.warn(e):r===Us.levels.values.debug?console.debug(e):r===Us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ai({timestamp:new Date().toISOString(),log:e}));let r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let r=this.getLogArray();return r.push(Ai({extraMetadata:e})),new Blob(r,{type:"application/json"})}},IS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},TS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}},lJ=Object.defineProperty,fJ=Object.defineProperties,hJ=Object.getOwnPropertyDescriptors,CP=Object.getOwnPropertySymbols,dJ=Object.prototype.hasOwnProperty,gJ=Object.prototype.propertyIsEnumerable,NP=(t,e,r)=>e in t?lJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sm=(t,e)=>{for(var r in e||(e={}))dJ.call(e,r)&&NP(t,r,e[r]);if(CP)for(var r of CP(e))gJ.call(e,r)&&NP(t,r,e[r]);return t},om=(t,e)=>fJ(t,hJ(e))});var QS=B(ar=>{"use strict";h();Object.defineProperty(ar,"__esModule",{value:!0});var Fc=(lS(),_e(cS)),FP=Ds();function wJ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var vJ=wJ(FP),NS=class extends Fc.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},xS=class{constructor(e,r,n){this.core=e,this.logger=r}},OS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},DS=class{constructor(e,r){this.logger=e,this.core=r}},PS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},RS=class extends Fc.IEvents{constructor(e){super()}},BS=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},MS=class{constructor(){this.map=new Map}},LS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},FS=class{constructor(e,r){this.core=e,this.logger=r}},US=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},qS=class{constructor(e,r){this.logger=e,this.core=r}},VS=class{constructor(e,r){this.projectId=e,this.logger=r}},kS=class{constructor(e,r){this.projectId=e,this.logger=r}},HS=class extends vJ.default{constructor(){super()}},GS=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},jS=class extends FP.EventEmitter{constructor(){super()}},zS=class{constructor(e){this.client=e}};ar.ICore=NS,ar.ICrypto=xS,ar.IEchoClient=kS,ar.IEngine=zS,ar.IEngineEvents=jS,ar.IExpirer=US,ar.IJsonRpcHistory=OS,ar.IKeyChain=FS,ar.IMessageTracker=DS,ar.IPairing=qS,ar.IPublisher=PS,ar.IRelayer=RS,ar.ISignClient=GS,ar.ISignClientEvents=HS,ar.IStore=BS,ar.ISubscriber=LS,ar.ISubscriberTopicMap=MS,ar.IVerify=VS});var qP=B(um=>{"use strict";h();Object.defineProperty(um,"__esModule",{value:!0});um.BrowserRandomSource=void 0;var UP=65536,KS=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";h();Object.defineProperty(WS,"__esModule",{value:!0});function AJ(t){for(var e=0;e{h()});var kP=B(cm=>{"use strict";h();Object.defineProperty(cm,"__esModule",{value:!0});cm.NodeRandomSource=void 0;var EJ=Qn(),$S=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof Bd<"u"){let e=VP();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";h();Object.defineProperty(lm,"__esModule",{value:!0});lm.SystemRandomSource=void 0;var bJ=qP(),SJ=kP(),YS=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new bJ.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new SJ.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};lm.SystemRandomSource=YS});var GP=B(dn=>{"use strict";h();Object.defineProperty(dn,"__esModule",{value:!0});function IJ(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}dn.mul=Math.imul||IJ;function TJ(t,e){return t+e|0}dn.add=TJ;function _J(t,e){return t-e|0}dn.sub=_J;function CJ(t,e){return t<>>32-e}dn.rotl=CJ;function NJ(t,e){return t<<32-e|t>>>e}dn.rotr=NJ;function xJ(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}dn.isInteger=Number.isInteger||xJ;dn.MAX_SAFE_INTEGER=9007199254740991;dn.isSafeInteger=function(t){return dn.isInteger(t)&&t>=-dn.MAX_SAFE_INTEGER&&t<=dn.MAX_SAFE_INTEGER}});var Uc=B(xe=>{"use strict";h();Object.defineProperty(xe,"__esModule",{value:!0});var jP=GP();function OJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}xe.readInt16BE=OJ;function DJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}xe.readUint16BE=DJ;function PJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}xe.readInt16LE=PJ;function RJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}xe.readUint16LE=RJ;function zP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}xe.writeUint16BE=zP;xe.writeInt16BE=zP;function QP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}xe.writeUint16LE=QP;xe.writeInt16LE=QP;function JS(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}xe.readInt32BE=JS;function XS(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}xe.readUint32BE=XS;function ZS(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}xe.readInt32LE=ZS;function eI(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}xe.readUint32LE=eI;function fm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}xe.writeUint32BE=fm;xe.writeInt32BE=fm;function hm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}xe.writeUint32LE=hm;xe.writeInt32LE=hm;function BJ(t,e){e===void 0&&(e=0);var r=JS(t,e),n=JS(t,e+4);return r*4294967296+n-(n>>31)*4294967296}xe.readInt64BE=BJ;function MJ(t,e){e===void 0&&(e=0);var r=XS(t,e),n=XS(t,e+4);return r*4294967296+n}xe.readUint64BE=MJ;function LJ(t,e){e===void 0&&(e=0);var r=ZS(t,e),n=ZS(t,e+4);return n*4294967296+r-(r>>31)*4294967296}xe.readInt64LE=LJ;function FJ(t,e){e===void 0&&(e=0);var r=eI(t,e),n=eI(t,e+4);return n*4294967296+r}xe.readUint64LE=FJ;function KP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),fm(t/4294967296>>>0,e,r),fm(t>>>0,e,r+4),e}xe.writeUint64BE=KP;xe.writeInt64BE=KP;function WP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),hm(t>>>0,e,r),hm(t/4294967296>>>0,e,r+4),e}xe.writeUint64LE=WP;xe.writeInt64LE=WP;function UJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}xe.readUintBE=UJ;function qJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}xe.writeUintBE=VJ;function kJ(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!jP.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";h();Object.defineProperty(Br,"__esModule",{value:!0});Br.randomStringForEntropy=Br.randomString=Br.randomUint32=Br.randomBytes=Br.defaultRandomSource=void 0;var YJ=HP(),JJ=Uc(),$P=Qn();Br.defaultRandomSource=new YJ.SystemRandomSource;function tI(t,e=Br.defaultRandomSource){return e.randomBytes(t)}Br.randomBytes=tI;function XJ(t=Br.defaultRandomSource){let e=tI(4,t),r=(0,JJ.readUint32LE)(e);return(0,$P.wipe)(e),r}Br.randomUint32=XJ;var YP="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function JP(t,e=YP,r=Br.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=tI(Math.ceil(t*256/s),r);for(let u=0;u0;u++){let a=o[u];a{"use strict";h();Object.defineProperty(qs,"__esModule",{value:!0});var Vc=Uc(),qc=Qn();qs.DIGEST_LENGTH=64;qs.BLOCK_SIZE=128;var ZP=function(){function t(){this.digestLength=qs.DIGEST_LENGTH,this.blockSize=qs.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){qc.wipe(this._buffer),qc.wipe(this._tempHi),qc.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){qc.wipe(e.stateHi),qc.wipe(e.stateLo),e.buffer&&qc.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();qs.SHA512=ZP;var XP=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function rI(t,e,r,n,i,s,o){for(var u=r[0],a=r[1],c=r[2],f=r[3],d=r[4],w=r[5],A=r[6],T=r[7],x=n[0],R=n[1],V=n[2],U=n[3],Q=n[4],L=n[5],k=n[6],H=n[7],q,v,C,D,F,P,l,g;o>=128;){for(var y=0;y<16;y++){var E=8*y+s;t[y]=Vc.readUint32BE(i,E),e[y]=Vc.readUint32BE(i,E+4)}for(var y=0;y<80;y++){var S=u,_=a,M=c,N=f,m=d,O=w,Y=A,$=T,b=x,j=R,z=V,W=U,ie=Q,te=L,ee=k,se=H;if(q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(d>>>14|Q<<18)^(d>>>18|Q<<14)^(Q>>>9|d<<23),v=(Q>>>14|d<<18)^(Q>>>18|d<<14)^(d>>>9|Q<<23),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=d&w^~d&A,v=Q&L^~Q&k,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=XP[y*2],v=XP[y*2+1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=t[y%16],v=e[y%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,C=l&65535|g<<16,D=F&65535|P<<16,q=C,v=D,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(u>>>28|x<<4)^(x>>>2|u<<30)^(x>>>7|u<<25),v=(x>>>28|u<<4)^(u>>>2|x<<30)^(u>>>7|x<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=u&a^u&c^a&c,v=x&R^x&V^R&V,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,$=l&65535|g<<16,se=F&65535|P<<16,q=N,v=W,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=C,v=D,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,N=l&65535|g<<16,W=F&65535|P<<16,a=S,c=_,f=M,d=N,w=m,A=O,T=Y,u=$,R=b,V=j,U=z,Q=W,L=ie,k=te,H=ee,x=se,y%16===15)for(var E=0;E<16;E++)q=t[E],v=e[E],F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=t[(E+9)%16],v=e[(E+9)%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+1)%16],D=e[(E+1)%16],q=(C>>>1|D<<31)^(C>>>8|D<<24)^C>>>7,v=(D>>>1|C<<31)^(D>>>8|C<<24)^(D>>>7|C<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+14)%16],D=e[(E+14)%16],q=(C>>>19|D<<13)^(D>>>29|C<<3)^C>>>6,v=(D>>>19|C<<13)^(C>>>29|D<<3)^(D>>>6|C<<26),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,t[E]=l&65535|g<<16,e[E]=F&65535|P<<16}q=u,v=x,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[0],v=n[0],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[0]=u=l&65535|g<<16,n[0]=x=F&65535|P<<16,q=a,v=R,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[1],v=n[1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[1]=a=l&65535|g<<16,n[1]=R=F&65535|P<<16,q=c,v=V,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[2],v=n[2],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[2]=c=l&65535|g<<16,n[2]=V=F&65535|P<<16,q=f,v=U,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[3],v=n[3],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[3]=f=l&65535|g<<16,n[3]=U=F&65535|P<<16,q=d,v=Q,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[4],v=n[4],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[4]=d=l&65535|g<<16,n[4]=Q=F&65535|P<<16,q=w,v=L,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[5],v=n[5],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[5]=w=l&65535|g<<16,n[5]=L=F&65535|P<<16,q=A,v=k,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[6],v=n[6],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[6]=A=l&65535|g<<16,n[6]=k=F&65535|P<<16,q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[7],v=n[7],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[7]=T=l&65535|g<<16,n[7]=H=F&65535|P<<16,s+=128,o-=128}return s}function eX(t){var e=new ZP;e.update(t);var r=e.digest();return e.clean(),r}qs.hash=eX});var gR=B(Ge=>{"use strict";h();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.convertSecretKeyToX25519=Ge.convertPublicKeyToX25519=Ge.verify=Ge.sign=Ge.extractPublicKeyFromSecretKey=Ge.generateKeyPair=Ge.generateKeyPairFromSeed=Ge.SEED_LENGTH=Ge.SECRET_KEY_LENGTH=Ge.PUBLIC_KEY_LENGTH=Ge.SIGNATURE_LENGTH=void 0;var tX=yh(),wh=eR(),sR=Qn();Ge.SIGNATURE_LENGTH=64;Ge.PUBLIC_KEY_LENGTH=32;Ge.SECRET_KEY_LENGTH=64;Ge.SEED_LENGTH=32;function ve(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,oR(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function aR(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function nR(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return vh(r,t),vh(n,e),aR(r,n)}function uR(t){let e=new Uint8Array(32);return vh(e,t),e[0]&1}function oX(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Ka(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function $a(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function Ct(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Wa(t,e){Ct(t,e,e)}function cR(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)Wa(r,r),n!==2&&n!==4&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function aX(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)Wa(r,r),n!==1&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function oI(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve(),c=ve(),f=ve();$a(r,t[1],t[0]),$a(f,e[1],e[0]),Ct(r,r,f),Ka(n,t[0],t[1]),Ka(f,e[0],e[1]),Ct(n,n,f),Ct(i,t[3],e[3]),Ct(i,i,iX),Ct(s,t[2],e[2]),Ka(s,s,s),$a(o,n,r),$a(u,s,i),Ka(a,s,i),Ka(c,n,r),Ct(t[0],o,u),Ct(t[1],c,a),Ct(t[2],a,u),Ct(t[3],o,c)}function iR(t,e,r){for(let n=0;n<4;n++)oR(t[n],e[n],r)}function uI(t,e){let r=ve(),n=ve(),i=ve();cR(i,e[2]),Ct(r,e[0],i),Ct(n,e[1],i),vh(t,n),t[31]^=uR(r)<<7}function lR(t,e,r){Bo(t[0],sI),Bo(t[1],kc),Bo(t[2],kc),Bo(t[3],sI);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;iR(t,e,i),oI(e,t),oI(t,t),iR(t,e,i)}}function cI(t,e){let r=[ve(),ve(),ve(),ve()];Bo(r[0],tR),Bo(r[1],rR),Bo(r[2],kc),Ct(r[3],tR,rR),lR(t,r,e)}function fR(t){if(t.length!==Ge.SEED_LENGTH)throw new Error(`ed25519: seed must be ${Ge.SEED_LENGTH} bytes`);let e=(0,wh.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[ve(),ve(),ve(),ve()];cI(n,e),uI(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}Ge.generateKeyPairFromSeed=fR;function uX(t){let e=(0,tX.randomBytes)(32,t),r=fR(e);return(0,sR.wipe)(e),r}Ge.generateKeyPair=uX;function cX(t){if(t.length!==Ge.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${Ge.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}Ge.extractPublicKeyFromSecretKey=cX;var iI=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function hR(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*iI[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*iI[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function aI(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;hR(t,e)}function lX(t,e){let r=new Float64Array(64),n=[ve(),ve(),ve(),ve()],i=(0,wh.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new wh.SHA512;o.update(s.subarray(32)),o.update(e);let u=o.digest();o.clean(),aI(u),cI(n,u),uI(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let a=o.digest();aI(a);for(let c=0;c<32;c++)r[c]=u[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=a[c]*i[f];return hR(s.subarray(32),r),s}Ge.sign=lX;function dR(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve();return Bo(t[2],kc),oX(t[1],e),Wa(i,t[1]),Ct(s,i,nX),$a(i,i,t[2]),Ka(s,t[2],s),Wa(o,s),Wa(u,o),Ct(a,u,o),Ct(r,a,i),Ct(r,r,s),aX(r,r),Ct(r,r,i),Ct(r,r,s),Ct(r,r,s),Ct(t[0],r,s),Wa(n,t[0]),Ct(n,n,s),nR(n,i)&&Ct(t[0],t[0],sX),Wa(n,t[0]),Ct(n,n,s),nR(n,i)?-1:(uR(t[0])===e[31]>>7&&$a(t[0],sI,t[0]),Ct(t[3],t[0],t[1]),0)}function fX(t,e,r){let n=new Uint8Array(32),i=[ve(),ve(),ve(),ve()],s=[ve(),ve(),ve(),ve()];if(r.length!==Ge.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${Ge.SIGNATURE_LENGTH} bytes`);if(dR(s,t))return!1;let o=new wh.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let u=o.digest();return aI(u),lR(i,s,u),cI(s,r.subarray(32)),oI(i,s),uI(n,i),!aR(r,n)}Ge.verify=fX;function hX(t){let e=[ve(),ve(),ve(),ve()];if(dR(e,t))throw new Error("Ed25519: invalid public key");let r=ve(),n=ve(),i=e[1];Ka(r,kc,i),$a(n,kc,i),cR(n,n),Ct(r,r,n);let s=new Uint8Array(32);return vh(s,r),s}Ge.convertPublicKeyToX25519=hX;function dX(t){let e=(0,wh.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,sR.wipe)(e),r}Ge.convertSecretKeyToX25519=dX});var dm,gm,Ya,Hc,pm,Ah,mm,ym,wm,Gc,vm,Am,pR,mR,Em=fe(()=>{h();dm="EdDSA",gm="JWT",Ya=".",Hc="base64url",pm="utf8",Ah="utf8",mm=":",ym="did",wm="key",Gc="base58btc",vm="z",Am="K36",pR=32,mR=32});function Mo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var Eh=fe(()=>{h()});function jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var bm=fe(()=>{h();Eh()});function Sm(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=jc(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Mo(r)}var lI=fe(()=>{h();bm();Eh()});function gX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var pX,mX,yR,wR=fe(()=>{h();pX=gX,mX=pX,yR=mX});var cEe,vR,Vs,AR,ER,Lo=fe(()=>{h();cEe=new Uint8Array(0),vR=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},AR=t=>new TextEncoder().encode(t),ER=t=>new TextDecoder().decode(t)});var fI,hI,dI,SR,gI,zc,Fo,yX,wX,jt,Ei=fe(()=>{h();wR();Lo();fI=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},hI=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SR(this,e)}},dI=class{constructor(e){this.decoders=e}or(e){return SR(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SR=(t,e)=>new dI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),gI=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new fI(e,r,n),this.decoder=new hI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zc=({name:t,prefix:e,encode:r,decode:n})=>new gI(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=yR(r,e);return zc({prefix:t,name:e,encode:n,decode:s=>Vs(i(s))})},yX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},wX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<zc({prefix:e,name:t,encode(i){return wX(i,n,r)},decode(i){return yX(i,n,r,t)}})});var pI={};Bt(pI,{identity:()=>vX});var vX,IR=fe(()=>{h();Ei();Lo();vX=zc({prefix:"\0",name:"identity",encode:t=>ER(t),decode:t=>AR(t)})});var mI={};Bt(mI,{base2:()=>AX});var AX,TR=fe(()=>{h();Ei();AX=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var yI={};Bt(yI,{base8:()=>EX});var EX,_R=fe(()=>{h();Ei();EX=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var wI={};Bt(wI,{base10:()=>bX});var bX,CR=fe(()=>{h();Ei();bX=Fo({prefix:"9",name:"base10",alphabet:"0123456789"})});var vI={};Bt(vI,{base16:()=>SX,base16upper:()=>IX});var SX,IX,NR=fe(()=>{h();Ei();SX=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),IX=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var AI={};Bt(AI,{base32:()=>Qc,base32hex:()=>NX,base32hexpad:()=>OX,base32hexpadupper:()=>DX,base32hexupper:()=>xX,base32pad:()=>_X,base32padupper:()=>CX,base32upper:()=>TX,base32z:()=>PX});var Qc,TX,_X,CX,NX,xX,OX,DX,PX,EI=fe(()=>{h();Ei();Qc=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),TX=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_X=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),CX=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),NX=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xX=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),OX=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DX=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PX=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bI={};Bt(bI,{base36:()=>RX,base36upper:()=>BX});var RX,BX,xR=fe(()=>{h();Ei();RX=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BX=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var SI={};Bt(SI,{base58btc:()=>rs,base58flickr:()=>MX});var rs,MX,II=fe(()=>{h();Ei();rs=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),MX=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var TI={};Bt(TI,{base64:()=>LX,base64pad:()=>FX,base64url:()=>UX,base64urlpad:()=>qX});var LX,FX,UX,qX,OR=fe(()=>{h();Ei();LX=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FX=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),UX=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qX=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var _I={};Bt(_I,{base256emoji:()=>jX});function HX(t){return t.reduce((e,r)=>(e+=VX[r],e),"")}function GX(t){let e=[];for(let r of t){let n=kX[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var DR,VX,kX,jX,PR=fe(()=>{h();Ei();DR=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VX=DR.reduce((t,e,r)=>(t[r]=e,t),[]),kX=DR.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);jX=zc({prefix:"\u{1F680}",name:"base256emoji",encode:HX,decode:GX})});function MR(t,e,r){e=e||[],r=r||0;for(var n=r;t>=WX;)e[r++]=t&255|RR,t/=128;for(;t&KX;)e[r++]=t&255|RR,t>>>=7;return e[r]=t|0,MR.bytes=r-n+1,e}function CI(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw CI.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&BR)<=YX);return CI.bytes=s-n,r}var zX,RR,QX,KX,WX,$X,YX,BR,JX,XX,ZX,eZ,tZ,rZ,nZ,iZ,sZ,oZ,aZ,uZ,bh,LR=fe(()=>{h();zX=MR,RR=128,QX=127,KX=~QX,WX=Math.pow(2,31);$X=CI,YX=128,BR=127;JX=Math.pow(2,7),XX=Math.pow(2,14),ZX=Math.pow(2,21),eZ=Math.pow(2,28),tZ=Math.pow(2,35),rZ=Math.pow(2,42),nZ=Math.pow(2,49),iZ=Math.pow(2,56),sZ=Math.pow(2,63),oZ=function(t){return t{h();LR();Sh=(t,e=0)=>[bh.decode(t,e),bh.decode.bytes],Kc=(t,e,r=0)=>(bh.encode(t,e,r),e),Wc=t=>bh.encodingLength(t)});var Ja,FR,UR,$c,Th=fe(()=>{h();Lo();Tm();Ja=(t,e)=>{let r=e.byteLength,n=Wc(t),i=n+Wc(r),s=new Uint8Array(i+r);return Kc(t,s,0),Kc(r,s,n),s.set(e,i),new $c(t,r,e,s)},FR=t=>{let e=Vs(t),[r,n]=Sh(e),[i,s]=Sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $c(r,i,o,e)},UR=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&vR(t.bytes,e.bytes),$c=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var xI,NI,OI=fe(()=>{h();Th();xI=({name:t,code:e,encode:r})=>new NI(t,e,r),NI=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ja(this.code,r):r.then(n=>Ja(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var DI={};Bt(DI,{sha256:()=>cZ,sha512:()=>lZ});var VR,cZ,lZ,kR=fe(()=>{h();OI();VR=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),cZ=xI({name:"sha2-256",code:18,encode:VR("SHA-256")}),lZ=xI({name:"sha2-512",code:19,encode:VR("SHA-512")})});var PI={};Bt(PI,{identity:()=>dZ});var HR,fZ,GR,hZ,dZ,jR=fe(()=>{h();Lo();Th();HR=0,fZ="identity",GR=Vs,hZ=t=>Ja(HR,GR(t)),dZ={code:HR,name:fZ,encode:GR,digest:hZ}});var zR=fe(()=>{h();Lo()});var $Ee,YEe,QR=fe(()=>{h();$Ee=new TextEncoder,YEe=new TextDecoder});var Nm,mZ,yZ,wZ,_h,vZ,KR,WR,_m,Cm,AZ,EZ,bZ,$R=fe(()=>{h();Tm();Th();II();EI();Lo();Nm=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Cm,byteLength:Cm,code:_m,version:_m,multihash:_m,bytes:_m,_baseCache:Cm,asCID:Cm})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==_h)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==vZ)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ja(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&UR(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return yZ(r,i,e||rs.encoder);default:return wZ(r,i,e||Qc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return EZ(/^0\.0/,bZ),!!(e&&(e[WR]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||KR(r,n,i.bytes))}else if(e!=null&&e[WR]===!0){let{version:r,multihash:n,code:i}=e,s=FR(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==_h)throw new Error(`Version 0 CID must use dag-pb (code: ${_h}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=KR(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_h,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Vs(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $c(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,w]=Sh(e.subarray(r));return r+=w,d},i=n(),s=_h;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,u=n(),a=n(),c=r+a,f=c-o;return{version:i,codec:s,multihashCode:u,digestSize:a,multihashSize:f,size:c}}static parse(e,r){let[n,i]=mZ(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},mZ=(t,e)=>{switch(t[0]){case"Q":{let r=e||rs;return[rs.prefix,r.decode(`${rs.prefix}${t}`)]}case rs.prefix:{let r=e||rs;return[rs.prefix,r.decode(t)]}case Qc.prefix:{let r=e||Qc;return[Qc.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},yZ=(t,e,r)=>{let{prefix:n}=r;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},wZ=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},_h=112,vZ=18,KR=(t,e,r)=>{let n=Wc(t),i=n+Wc(e),s=new Uint8Array(i+r.byteLength);return Kc(t,s,0),Kc(e,s,n),s.set(r,i),s},WR=Symbol.for("@ipld/js-cid/CID"),_m={writable:!1,configurable:!1,enumerable:!0},Cm={writable:!1,enumerable:!1,configurable:!1},AZ="0.0.0-dev",EZ=(t,e)=>{if(t.test(AZ))console.warn(e);else throw new Error(e)},bZ=`CID.isCID(v) is deprecated and will be removed in the next major release. +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex(e.tokenType),ae.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleLocalMint?[ae.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ae.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ae.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ae.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ae.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.initialQuantity),ae.utf8ToHex(e.name),ae.bigIntToHex(e.royalties),ae.utf8ToHex(e.hash),ae.bufferToHex(e.attributes),...e.uris.map(ae.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:u,dataParts:a}){let c=this.buildTransactionPayload(a),f=o||this.computeGasLimit(c,u),d=new h8.TransactionVersion(Eb.TRANSACTION_VERSION_DEFAULT),w=new h8.TransactionOptions(Eb.TRANSACTION_OPTIONS_DEFAULT);return new P$.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:w})}buildTransactionPayload(e){let r=e.join(Eb.ARGUMENTS_SEPARATOR);return new R$.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};N0.TokenOperationsFactory=bb});var g8=D(x0=>{"use strict";h();Object.defineProperty(x0,"__esModule",{value:!0});x0.TokenOperationsFactoryConfig=void 0;var B$=Ve(),Sb=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=B$.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};x0.TokenOperationsFactoryConfig=Sb});var m8=D(O0=>{"use strict";h();Object.defineProperty(O0,"__esModule",{value:!0});O0.TokenOperationsOutcomeParser=void 0;var M$=Ve(),Ib=Ie(),p8=Kd(),Tb=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=r.topics[3]?.valueOf();return{tokenIdentifier:n,nonce:i,attributes:s}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){for(let r of e.logs.events)if(r.identifier=="signalError"){let n=p.Buffer.from(r.data.substring(1),"hex").toString(),i=r.topics[1]?.valueOf().toString();throw new Ib.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${i} (${n})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new Ib.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new Ib.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){return e.topics[0]?.valueOf().toString()}extractNonce(e){return p8.bufferToBigInt(e.topics[1]?.valueOf()).toFixed(0)}extractAmount(e){return p8.bufferToBigInt(e.topics[2]?.valueOf()).toFixed(0)}extractAddress(e){return M$.Address.fromBuffer(e.topics[3]?.valueOf()).toString()}};O0.TokenOperationsOutcomeParser=Tb});var Cb=D(Ls=>{"use strict";h();var L$=Ls&&Ls.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),_b=Ls&&Ls.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&L$(e,t,r)};Object.defineProperty(Ls,"__esModule",{value:!0});_b(d8(),Ls);_b(g8(),Ls);_b(m8(),Ls)});var y8=D(D0=>{"use strict";h();Object.defineProperty(D0,"__esModule",{value:!0});D0.DelegationTransactionsOutcomeParser=void 0;var F$=Ve(),U$=Ie(),q$=Ac(),Nb=class{constructor(){}parseCreateNewDelegationContract(e){return this.ensureNoError(e.logs.events),q$.findEventsByIdentifier(e,"SCDeploy").map(n=>({contractAddress:this.extractContractAddress(n)}))}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new U$.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractContractAddress(e){if(!e.topics[0]?.length)return"";let r=p.Buffer.from(e.topics[0]);return F$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};D0.DelegationTransactionsOutcomeParser=Nb});var A8=D(P0=>{"use strict";h();Object.defineProperty(P0,"__esModule",{value:!0});P0.SmartContractTransactionsOutcomeParser=void 0;var w8=Ve(),V$=Ie(),v8=qn(),k$=Ac(),xb=class{constructor(e){this.abi=e?.abi,this.legacyResultsParser=e?.legacyResultsParser||new v8.ResultsParser}parseDeploy(e){let r=e.transactionOutcome.directSmartContractCallOutcome,i=k$.findEventsByIdentifier(e.transactionOutcome,"SCDeploy").map(s=>this.parseScDeployEvent(s));return{returnCode:r.returnCode,returnMessage:r.returnMessage,contracts:i}}parseScDeployEvent(e){let r=e.topics[0],n=e.topics[1],i=e.topics[2],s=r?.length?new w8.Address(r).toBech32():"",o=n?.length?new w8.Address(n).toBech32():"";return{address:s,ownerAddress:o,codeHash:i}}parseExecute(e){let r=e.transactionOutcome.directSmartContractCallOutcome;if(!this.abi)return{values:r.returnDataParts,returnCode:r.returnCode,returnMessage:r.returnMessage};let n=e.function||r.function;if(!n)throw new V$.Err('Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?');let i=this.abi.getEndpoint(n),s={returnCode:new v8.ReturnCode(r.returnCode),returnMessage:r.returnMessage,values:r.returnDataParts.map(u=>p.Buffer.from(u))},o=this.legacyResultsParser.parseOutcomeFromUntypedBundle(s,i);return{values:o.values.map(u=>u.valueOf()),returnCode:o.returnCode.toString(),returnMessage:o.returnMessage}}};P0.SmartContractTransactionsOutcomeParser=xb});var S8=D(R0=>{"use strict";h();Object.defineProperty(R0,"__esModule",{value:!0});R0.TokenManagementTransactionsOutcomeParser=void 0;var H$=Ve(),E8=Ie(),b8=Bu(),wr=Ac(),Ob=class{constructor(){}parseIssueFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issue").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueNonFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueNonFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueSemiFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueSemiFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterMetaEsdt(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"registerMetaESDT").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterAndSetAllRoles(e){this.ensureNoError(e.logs.events);let r=wr.findEventsByIdentifier(e,"registerAndSetAllRoles"),n=wr.findEventsByIdentifier(e,"ESDTSetRole");if(r.length!==n.length)throw new E8.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events.");return r.map((i,s)=>{let o=this.extractTokenIdentifier(i),a=n[s].topics.slice(3).map(c=>this.decodeTopicAsString(c));return{tokenIdentifier:o,roles:a}})}parseSetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseUnsetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseSetSpecialRole(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTSetRole").map(n=>this.getOutputForSetSpecialRoleEvent(n))}getOutputForSetSpecialRoleEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),s=e.topics.slice(3).map(o=>this.decodeTopicAsString(o));return{userAddress:r,tokenIdentifier:n,roles:s}}parseNftCreate(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTCreate").map(n=>this.getOutputForNftCreateEvent(n))}getOutputForNftCreateEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,initialQuantity:i}}parseLocalMint(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalMint").map(n=>this.getOutputForLocalMintEvent(n))}getOutputForLocalMintEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,mintedSupply:s}}parseLocalBurn(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalBurn").map(n=>this.getOutputForLocalBurnEvent(n))}getOutputForLocalBurnEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,burntSupply:s}}parsePause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseUnpause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseFreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTFreeze").map(n=>this.getOutputForFreezeEvent(n))}getOutputForFreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnFreeze").map(n=>this.getOutputForUnfreezeEvent(n))}getOutputForUnfreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTWipe").map(n=>this.getOutputForWipeEvent(n))}getOutputForWipeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTUpdateAttributes").map(n=>this.getOutputForUpdateAttributesEvent(n))}getOutputForUpdateAttributesEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=e.topics[3]?e.topics[3]:new Uint8Array;return{tokenIdentifier:r,nonce:n,attributes:i}}parseAddQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTAddQuantity").map(n=>this.getOutputForAddQuantityEvent(n))}getOutputForAddQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,addedQuantity:i}}parseBurnQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTBurn").map(n=>this.getOutputForBurnQuantityEvent(n))}getOutputForBurnQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,burntQuantity:i}}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new E8.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractTokenIdentifier(e){return e.topics[0]?.length?this.decodeTopicAsString(e.topics[0]):""}extractNonce(e){if(!e.topics[1]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[1]);return BigInt(b8.bufferToBigInt(r).toFixed(0))}extractAmount(e){if(!e.topics[2]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[2]);return BigInt(b8.bufferToBigInt(r).toFixed(0))}extractAddress(e){if(!e.topics[3]?.length)return"";let r=p.Buffer.from(e.topics[3]);return H$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};R0.TokenManagementTransactionsOutcomeParser=Ob});var I8=D(B0=>{"use strict";h();Object.defineProperty(B0,"__esModule",{value:!0});B0.TransactionEventsParser=void 0;var G$=qn(),Db=class{constructor(e){this.legacyResultsParser=new G$.ResultsParser,this.abi=e.abi,this.firstTopicIsIdentifier=e.firstTopicIsIdentifier??!0}parseEvents(e){let r=[];for(let n of e.events){let i=this.parseEvent({event:n});r.push(i)}return r}parseEvent(e){let r=e.event.topics.map(u=>p.Buffer.from(u)),n=this.firstTopicIsIdentifier?r[0]?.toString():e.event.identifier;this.firstTopicIsIdentifier&&r.shift();let i=e.event.dataItems.map(u=>p.Buffer.from(u)),s=this.abi.getEvent(n);return this.legacyResultsParser.doParseEvent({topics:r,dataItems:i,eventDefinition:s})}};B0.TransactionEventsParser=Db});var Pb=D(vi=>{"use strict";h();var j$=vi&&vi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=vi&&vi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&j$(e,t,r)};Object.defineProperty(vi,"__esModule",{value:!0});rh(y8(),vi);rh(Ac(),vi);rh(A8(),vi);rh(S8(),vi);rh(I8(),vi)});var Ic=D(M0=>{"use strict";h();Object.defineProperty(M0,"__esModule",{value:!0});M0.Account=void 0;var z$=Ve(),Rb=class{constructor(e){this.address=z$.Address.empty(),this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};M0.Account=Rb});var Mb=D(Tc=>{"use strict";h();Object.defineProperty(Tc,"__esModule",{value:!0});Tc.MessageComputer=Tc.Message=void 0;var nh=hr(),Q$=Ve(),K$=sf(),L0=class{constructor(e){this.data=e.data,this.signature=e.signature,this.address=e.address,this.version=e.version||nh.DEFAULT_MESSAGE_VERSION,this.signer=e.signer||nh.SDK_JS_SIGNER}};Tc.Message=L0;var Bb=class{constructor(){}computeBytesForSigning(e){let r=p.Buffer.from(e.data.length.toString()),n=p.Buffer.concat([r,e.data]),i=p.Buffer.concat([p.Buffer.from(nh.MESSAGE_PREFIX),n]);return K$("keccak256").update(i).digest()}computeBytesForVerifying(e){return this.computeBytesForSigning(e)}packMessage(e){return{message:p.Buffer.from(e.data).toString("hex"),signature:e.signature?p.Buffer.from(e.signature).toString("hex"):"",address:e.address?e.address.bech32():"",version:e.version,signer:e.signer}}unpackMessage(e){let r=this.trimHexPrefix(e.message),n=p.Buffer.from(r,"hex"),i=this.trimHexPrefix(e.signature||""),s=p.Buffer.from(i,"hex"),o;e.address&&(o=Q$.Address.fromBech32(e.address));let u=e.version||nh.DEFAULT_MESSAGE_VERSION,a=e.signer||nh.UNKNOWN_SIGNER;return new L0({data:n,signature:s,address:o,version:u,signer:a})}trimHexPrefix(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}};Tc.MessageComputer=Bb});var Ub=D(Xi=>{"use strict";h();var W$=Xi&&Xi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),$$=Xi&&Xi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Y$=Xi&&Xi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&W$(e,t,r);return $$(e,t),e};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AsyncTimer=void 0;var J$=Y$(Ie()),X$=Ie(),Lb=oo(),Fb=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new J$.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,Lb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){Lb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new X$.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(Lb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};Xi.AsyncTimer=Fb});var U0=D(F0=>{"use strict";h();Object.defineProperty(F0,"__esModule",{value:!0});F0.TransactionWatcher=void 0;var qb=Ub(),T8=hr(),Fs=Ie(),_8=oo(),No=class t{constructor(e,r={}){this.fetcher=new Vb(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}async awaitPending(e){let r=s=>s.status.isPending(),n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitCompleted(e){let r=s=>{if(s.isCompleted===void 0)throw new Fs.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitAllEvents(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>u.includes(c))},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitAnyEvent(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>u.includes(c))!=null},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitOnCondition(e,r){let n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}transactionOrTxHashToTxHash(e){let r=typeof e=="string"?e:e.getHash().hex();if(r.length!==T8.HEX_TRANSACTION_HASH_LENGTH)throw new Fs.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${T8.HEX_TRANSACTION_HASH_LENGTH}.`);return r}async awaitConditionally(e,r,n){let i=new qb.AsyncTimer("watcher:periodic"),s=new qb.AsyncTimer("watcher:patience"),o=new qb.AsyncTimer("watcher:timeout"),u=!1,a,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),u=!0});!u;){await i.start(this.pollingIntervalMilliseconds);try{if(a=await r(),c=e(a),c||u)break}catch(f){if(_8.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Fs.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Fs.Err))throw f}}if(c&&await s.start(this.patienceMilliseconds),o.isStopped()||o.stop(),!a||!c)throw n();return a}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};F0.TransactionWatcher=No;No.DefaultPollingInterval=6e3;No.DefaultTimeout=No.DefaultPollingInterval*15;No.DefaultPatience=0;No.NoopOnStatusReceived=t=>{};var Vb=class{constructor(e){this.fetcher=e}async getTransaction(e){return _8.Logger.debug(`transactionWatcher, getTransaction(${e})`),await this.fetcher.getTransaction(e)}}});var V0=D(q0=>{"use strict";h();Object.defineProperty(q0,"__esModule",{value:!0});q0.SignableMessage=void 0;var Z$=Ve(),eY=Yf(),tY=hr(),rY=sf(),kb=class{constructor(e){this.message=p.Buffer.from([]),this.signature=p.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=Z$.Address.empty(),Object.assign(this,e)}serializeForSigning(){let e=p.Buffer.from(this.message.length.toString()),r=p.Buffer.concat([e,this.message]),n=p.Buffer.concat([p.Buffer.from(tY.MESSAGE_PREFIX),r]);return rY("keccak256").update(n).digest()}serializeForSigningRaw(){return p.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=eY.interpretSignatureAsBuffer(e)}getMessageSize(){let e=p.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};q0.SignableMessage=kb});var _c=D(vr=>{"use strict";h();var nY=vr&&vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),iY=vr&&vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sY=vr&&vr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&nY(e,t,r);return iY(e,t),e};Object.defineProperty(vr,"__esModule",{value:!0});vr.zeroPadStringIfOddLength=vr.isPaddedHex=vr.numberToPaddedHex=vr.Nonce=vr.Address=void 0;var C8=sY(vv()),oY="erd",Hb=class t{constructor(e){this.value=e}static fromPubkey(e){let r=C8.toWords(e),n=C8.encode(oY,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};vr.Address=Hb;var Gb=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return N8(this.value)}};vr.Nonce=Gb;function N8(t){let e=t.toString(16);return x8(e)}vr.numberToPaddedHex=N8;function aY(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}vr.isPaddedHex=aY;function x8(t){return t=t||"",t.length%2==1?"0"+t:t}vr.zeroPadStringIfOddLength=x8});var O8=D(xo=>{"use strict";h();var uY=xo&&xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xo,"__esModule",{value:!0});xo.EsdtContractAddress=xo.MaxUint64AsBigNumber=void 0;var cY=uY((rr(),_e(fr))),lY=_c();xo.MaxUint64AsBigNumber=new cY.default("18446744073709551615");xo.EsdtContractAddress=new lY.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var zb=D(Cc=>{"use strict";h();var fY=Cc&&Cc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ContractQueryResponse=void 0;var hY=fY((rr(),_e(fr))),dY=O8(),jb=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new hY.default(e.gasRemaining||e.GasRemaining||0),o=dY.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>p.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Cc.ContractQueryResponse=jb});var D8=D(Oo=>{"use strict";h();Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ErrAccountNotConnected=Oo.ErrCannotSignSingleTransaction=Oo.Err=void 0;var ih=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Oo.Err=ih;var Qb=class extends ih{constructor(){super("Cannot sign single transaction.")}};Oo.ErrCannotSignSingleTransaction=Qb;var Kb=class extends ih{constructor(){super("Account is not connected.")}};Oo.ErrAccountNotConnected=Kb});var P8=D(sh=>{"use strict";h();Object.defineProperty(sh,"__esModule",{value:!0});sh.Operation=void 0;var gY;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(gY=sh.Operation||(sh.Operation={}))});var Wb=D(Nc=>{"use strict";h();var Do=Nc&&Nc.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Nc,"__esModule",{value:!0});Nc.ExtensionProvider=void 0;var pY=Xr(),R8=D8(),oh=P8(),ah=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return Do(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(oh.Operation.Connect,n),this.account.address})}logout(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(oh.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return Do(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new R8.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new R8.ErrAccountNotConnected}signTransactions(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(oh.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>pY.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(oh.Operation.SignMessage,r)).signature,s=p.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(oh.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};Nc.ExtensionProvider=ah;ah._instance=new ah});function vY(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){AY(t);return}return e}function AY(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function uh(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!wY.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(mY.test(t)||yY.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,vY)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var mY,yY,wY,U8=fe(()=>{h();mY=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,yY=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,wY=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function EY(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function gr(t,...e){try{return EY(t(...e))}catch(r){return Promise.reject(r)}}function bY(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function SY(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ch(t){if(bY(t))return String(t);if(SY(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ch(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function q8(){if(typeof p.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function V8(t){if(typeof t=="string")return t;q8();let e=p.Buffer.from(t).toString("base64");return $b+e}function k8(t){return typeof t!="string"||!t.startsWith($b)?t:(q8(),p.Buffer.from(t.slice($b.length),"base64"))}function Vr(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function H8(...t){return Vr(t.join(":"))}function lh(t){return t=Vr(t),t?t+":":""}var $b,G8=fe(()=>{h();$b="base64:"});function Q8(t={}){let e={mounts:{"":t.driver||TY()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=Vr(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await j8(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},u=(c,f,d)=>{let w=new Map,A=T=>{let x=w.get(T.base);return x||(x={driver:T.driver,base:T.base,items:[]},w.set(T.base,x)),x};for(let T of c){let x=typeof T=="string",B=Vr(x?T:T.key),V=x?void 0:T.value,U=x||!T.options?f:{...f,...T.options},Q=r(B);A(Q).items.push({key:B,value:V,relativeKey:Q.relativeKey,options:U})}return Promise.all([...w.values()].map(T=>d(T))).then(T=>T.flat())},a={hasItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.hasItem,d,f)},getItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.getItem,d,f).then(A=>uh(A))},getItems(c,f){return u(c,f,d=>d.driver.getItems?gr(d.driver.getItems,d.items.map(w=>({key:w.relativeKey,options:w.options})),f).then(w=>w.map(A=>({key:H8(d.base,A.key),value:uh(A.value)}))):Promise.all(d.items.map(w=>gr(d.driver.getItem,w.relativeKey,w.options).then(A=>({key:w.key,value:uh(A)})))))},getItemRaw(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return w.getItemRaw?gr(w.getItemRaw,d,f):gr(w.getItem,d,f).then(A=>k8(A))},async setItem(c,f,d={}){if(f===void 0)return a.removeItem(c);c=Vr(c);let{relativeKey:w,driver:A}=r(c);A.setItem&&(await gr(A.setItem,w,ch(f),d),A.watch||i("update",c))},async setItems(c,f){await u(c,f,async d=>{if(d.driver.setItems)return gr(d.driver.setItems,d.items.map(w=>({key:w.relativeKey,value:ch(w.value),options:w.options})),f);d.driver.setItem&&await Promise.all(d.items.map(w=>gr(d.driver.setItem,w.relativeKey,ch(w.value),w.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return a.removeItem(c,d);c=Vr(c);let{relativeKey:w,driver:A}=r(c);if(A.setItemRaw)await gr(A.setItemRaw,w,f,d);else if(A.setItem)await gr(A.setItem,w,V8(f),d);else return;A.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c);w.removeItem&&(await gr(w.removeItem,d,f),(f.removeMeta||f.removeMata)&&await gr(w.removeItem,d+"$",f),w.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c),A=Object.create(null);if(w.getMeta&&Object.assign(A,await gr(w.getMeta,d,f)),!f.nativeOnly){let T=await gr(w.getItem,d+"$",f).then(x=>uh(x));T&&typeof T=="object"&&(typeof T.atime=="string"&&(T.atime=new Date(T.atime)),typeof T.mtime=="string"&&(T.mtime=new Date(T.mtime)),Object.assign(A,T))}return A},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=lh(c);let d=n(c,!0),w=[],A=[];for(let T of d){let B=(await gr(T.driver.getKeys,T.relativeBase,f)).map(V=>T.mountpoint+Vr(V)).filter(V=>!w.some(U=>V.startsWith(U)));A.push(...B),w=[T.mountpoint,...w.filter(V=>!V.startsWith(T.mountpoint))]}return c?A.filter(T=>T.startsWith(c)&&!T.endsWith("$")):A.filter(T=>!T.endsWith("$"))},async clear(c,f={}){c=lh(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return gr(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let w=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(w.map(A=>d.driver.removeItem(A,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>z8(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=lh(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,w)=>w.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(j8(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),a},async unmount(c,f=!0){c=lh(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await z8(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=Vr(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=Vr(c),n(c,f.parents).map(w=>({driver:w.driver,base:w.mountpoint}))}};return a}function j8(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function z8(t){typeof t.dispose=="function"&&await gr(t.dispose)}var IY,TY,K8=fe(()=>{h();U8();G8();IY="memory",TY=()=>{let t=new Map;return{name:IY,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function ja(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Jb(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=ja(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function fh(){return Yb||(Yb=Jb("keyval-store","keyval")),Yb}function Xb(t,e=fh()){return e("readonly",r=>ja(r.get(t)))}function W8(t,e,r=fh()){return r("readwrite",n=>(n.put(e,t),ja(n.transaction)))}function $8(t,e=fh()){return e("readwrite",r=>(r.delete(t),ja(r.transaction)))}function Y8(t=fh()){return t("readwrite",e=>(e.clear(),ja(e.transaction)))}function _Y(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},ja(t.transaction)}function J8(t=fh()){return t("readonly",e=>{if(e.getAllKeys)return ja(e.getAllKeys());let r=[];return _Y(e,n=>r.push(n.key)).then(()=>r)})}var Yb,X8=fe(()=>{h()});var Z8={};Bt(Z8,{safeJsonParse:()=>Ro,safeJsonStringify:()=>Ai});function Ro(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return NY(t)}catch{return t}}function Ai(t){return typeof t=="string"?t:CY(t)||""}var CY,NY,xc=fe(()=>{h();CY=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),NY=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var tP={};Bt(tP,{KeyValueStorage:()=>rS,default:()=>rS});function RY(t){var e;return[t[0],Ro((e=t[1])!=null?e:"")]}var xY,OY,DY,PY,eS,Zb,j0,tS,BY,eP,MY,LY,rS,rP=fe(()=>{h();K8();X8();xc();xY="idb-keyval",OY=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Jb(t.dbName,t.storeName)),{name:xY,options:t,async hasItem(i){return!(typeof await Xb(r(i),n)>"u")},async getItem(i){return await Xb(r(i),n)??null},setItem(i,s){return W8(r(i),s,n)},removeItem(i){return $8(r(i),n)},getKeys(){return J8(n)},clear(){return Y8(n)}}},DY="WALLET_CONNECT_V2_INDEXED_DB",PY="keyvaluestorage",eS=class{constructor(){this.indexedDb=Q8({driver:OY({dbName:DY,storeName:PY})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ai(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Zb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},j0={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Zb<"u"&&Zb.localStorage?j0.exports=Zb.localStorage:typeof window<"u"&&window.localStorage?j0.exports=window.localStorage:j0.exports=new e})();tS=class{constructor(){this.localStorage=j0.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(RY)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return Ro(r)}async setItem(e,r){this.localStorage.setItem(e,Ai(r))}async removeItem(e){this.localStorage.removeItem(e)}},BY="wc_storage_version",eP=1,MY=async(t,e,r)=>{let n=BY,i=await e.getItem(n);if(i&&i>=eP){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let u=s.shift();if(!u)continue;let a=u.toLowerCase();if(a.includes("wc@")||a.includes("walletconnect")||a.includes("wc_")||a.includes("wallet_connect")){let c=await t.getItem(u);await e.setItem(u,c),o.push(u)}}await e.setItem(n,eP),r(e),LY(t,o)},LY=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},rS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new tS;this.storage=e;try{let r=new eS;MY(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zi={};Bt(Zi,{__assign:()=>iS,__asyncDelegator:()=>$Y,__asyncGenerator:()=>WY,__asyncValues:()=>YY,__await:()=>hh,__awaiter:()=>HY,__classPrivateFieldGet:()=>eJ,__classPrivateFieldSet:()=>tJ,__createBinding:()=>jY,__decorate:()=>qY,__exportStar:()=>zY,__extends:()=>FY,__generator:()=>GY,__importDefault:()=>ZY,__importStar:()=>XY,__makeTemplateObject:()=>JY,__metadata:()=>kY,__param:()=>VY,__read:()=>nP,__rest:()=>UY,__spread:()=>QY,__spreadArrays:()=>KY,__values:()=>sS});function FY(t,e){nS(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function UY(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;u--)(o=t[u])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function VY(t,e){return function(r,n){e(r,n,t)}}function kY(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function HY(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})}function GY(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(c){return function(f){return a([c,f])}}function a(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function nP(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function QY(){for(var t=[],e=0;e1||u(w,A)})})}function u(w,A){try{a(n[w](A))}catch(T){d(s[0][3],T)}}function a(w){w.value instanceof hh?Promise.resolve(w.value.v).then(c,f):d(s[0][2],w)}function c(w){u("next",w)}function f(w){u("throw",w)}function d(w,A){w(A),s.shift(),s.length&&u(s[0][0],s[0][1])}}function $Y(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:hh(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function YY(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof sS=="function"?sS(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(u,a){o=t[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(c){s({value:c,done:u})},o)}}function JY(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function XY(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function ZY(t){return t&&t.__esModule?t:{default:t}}function eJ(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function tJ(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var nS,iS,es=fe(()=>{h();nS=function(t,e){return nS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},nS(t,e)};iS=function(){return iS=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";h();Object.defineProperty(z0,"__esModule",{value:!0});z0.delay=void 0;function rJ(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}z0.delay=rJ});var sP=D(Oc=>{"use strict";h();Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ONE_THOUSAND=Oc.ONE_HUNDRED=void 0;Oc.ONE_HUNDRED=100;Oc.ONE_THOUSAND=1e3});var oP=D(le=>{"use strict";h();Object.defineProperty(le,"__esModule",{value:!0});le.ONE_YEAR=le.FOUR_WEEKS=le.THREE_WEEKS=le.TWO_WEEKS=le.ONE_WEEK=le.THIRTY_DAYS=le.SEVEN_DAYS=le.FIVE_DAYS=le.THREE_DAYS=le.ONE_DAY=le.TWENTY_FOUR_HOURS=le.TWELVE_HOURS=le.SIX_HOURS=le.THREE_HOURS=le.ONE_HOUR=le.SIXTY_MINUTES=le.THIRTY_MINUTES=le.TEN_MINUTES=le.FIVE_MINUTES=le.ONE_MINUTE=le.SIXTY_SECONDS=le.THIRTY_SECONDS=le.TEN_SECONDS=le.FIVE_SECONDS=le.ONE_SECOND=void 0;le.ONE_SECOND=1;le.FIVE_SECONDS=5;le.TEN_SECONDS=10;le.THIRTY_SECONDS=30;le.SIXTY_SECONDS=60;le.ONE_MINUTE=le.SIXTY_SECONDS;le.FIVE_MINUTES=le.ONE_MINUTE*5;le.TEN_MINUTES=le.ONE_MINUTE*10;le.THIRTY_MINUTES=le.ONE_MINUTE*30;le.SIXTY_MINUTES=le.ONE_MINUTE*60;le.ONE_HOUR=le.SIXTY_MINUTES;le.THREE_HOURS=le.ONE_HOUR*3;le.SIX_HOURS=le.ONE_HOUR*6;le.TWELVE_HOURS=le.ONE_HOUR*12;le.TWENTY_FOUR_HOURS=le.ONE_HOUR*24;le.ONE_DAY=le.TWENTY_FOUR_HOURS;le.THREE_DAYS=le.ONE_DAY*3;le.FIVE_DAYS=le.ONE_DAY*5;le.SEVEN_DAYS=le.ONE_DAY*7;le.THIRTY_DAYS=le.ONE_DAY*30;le.ONE_WEEK=le.SEVEN_DAYS;le.TWO_WEEKS=le.ONE_WEEK*2;le.THREE_WEEKS=le.ONE_WEEK*3;le.FOUR_WEEKS=le.ONE_WEEK*4;le.ONE_YEAR=le.ONE_DAY*365});var oS=D(Q0=>{"use strict";h();Object.defineProperty(Q0,"__esModule",{value:!0});var aP=(es(),_e(Zi));aP.__exportStar(sP(),Q0);aP.__exportStar(oP(),Q0)});var cP=D(Dc=>{"use strict";h();Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromMiliseconds=Dc.toMiliseconds=void 0;var uP=oS();function nJ(t){return t*uP.ONE_THOUSAND}Dc.toMiliseconds=nJ;function iJ(t){return Math.floor(t/uP.ONE_THOUSAND)}Dc.fromMiliseconds=iJ});var fP=D(K0=>{"use strict";h();Object.defineProperty(K0,"__esModule",{value:!0});var lP=(es(),_e(Zi));lP.__exportStar(iP(),K0);lP.__exportStar(cP(),K0)});var hP=D(dh=>{"use strict";h();Object.defineProperty(dh,"__esModule",{value:!0});dh.Watch=void 0;var W0=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};dh.Watch=W0;dh.default=W0});var dP=D($0=>{"use strict";h();Object.defineProperty($0,"__esModule",{value:!0});$0.IWatch=void 0;var aS=class{};$0.IWatch=aS});var gP=D(uS=>{"use strict";h();Object.defineProperty(uS,"__esModule",{value:!0});var sJ=(es(),_e(Zi));sJ.__exportStar(dP(),uS)});var za=D(Pc=>{"use strict";h();Object.defineProperty(Pc,"__esModule",{value:!0});var Y0=(es(),_e(Zi));Y0.__exportStar(fP(),Pc);Y0.__exportStar(hP(),Pc);Y0.__exportStar(gP(),Pc);Y0.__exportStar(oS(),Pc)});var cS,pP=fe(()=>{h();cS=class{}});var lS={};Bt(lS,{IEvents:()=>cS});var fS=fe(()=>{h();pP()});var mP=D(J0=>{"use strict";h();Object.defineProperty(J0,"__esModule",{value:!0});J0.IHeartBeat=void 0;var oJ=(fS(),_e(lS)),hS=class extends oJ.IEvents{constructor(e){super()}};J0.IHeartBeat=hS});var gS=D(dS=>{"use strict";h();Object.defineProperty(dS,"__esModule",{value:!0});var aJ=(es(),_e(Zi));aJ.__exportStar(mP(),dS)});var yP=D(Rc=>{"use strict";h();Object.defineProperty(Rc,"__esModule",{value:!0});Rc.HEARTBEAT_EVENTS=Rc.HEARTBEAT_INTERVAL=void 0;var uJ=za();Rc.HEARTBEAT_INTERVAL=uJ.FIVE_SECONDS;Rc.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var mS=D(pS=>{"use strict";h();Object.defineProperty(pS,"__esModule",{value:!0});var cJ=(es(),_e(Zi));cJ.__exportStar(yP(),pS)});var wP=D(X0=>{"use strict";h();Object.defineProperty(X0,"__esModule",{value:!0});X0.HeartBeat=void 0;var yS=(es(),_e(Zi)),lJ=Ds(),fJ=za(),hJ=gS(),wS=mS(),vS=class t extends hJ.IHeartBeat{constructor(e){super(e),this.events=new lJ.EventEmitter,this.interval=wS.HEARTBEAT_INTERVAL,this.interval=e?.interval||wS.HEARTBEAT_INTERVAL}static init(e){return yS.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return yS.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return yS.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),fJ.toMiliseconds(this.interval))})}pulse(){this.events.emit(wS.HEARTBEAT_EVENTS.pulse)}};X0.HeartBeat=vS});var vP=D(gh=>{"use strict";h();Object.defineProperty(gh,"__esModule",{value:!0});var AS=(es(),_e(Zi));AS.__exportStar(wP(),gh);AS.__exportStar(gS(),gh);AS.__exportStar(mS(),gh)});var EP=D((VAe,AP)=>{"use strict";h();function dJ(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}AP.exports=gJ;function gJ(t,e,r){var n=r&&r.stringify||dJ,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var u=1;u-1?d:0,t.charCodeAt(A+1)){case 100:case 102:if(f>=a||e[f]==null)break;d=a||e[f]==null)break;d=a||e[f]===void 0)break;d",d=A+2,A++;break}c+=n(e[f]),d=A+2,A++;break;case 115:if(f>=a)break;d{"use strict";h();var bP=EP();TP.exports=ts;var ph=IJ().console||{},pJ={mapHttpRequest:Z0,mapHttpResponse:Z0,wrapRequestSerializer:ES,wrapResponseSerializer:ES,wrapErrorSerializer:ES,req:Z0,res:Z0,err:AJ};function mJ(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ts(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||ph;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=mJ(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let u=t.level||"info",a=Object.create(r);a.log||(a.log=mh),Object.defineProperty(a,"levelVal",{get:f}),Object.defineProperty(a,"level",{get:d,set:w});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:EJ(t)};a.levels=ts.levels,a.level=u,a.setMaxListeners=a.getMaxListeners=a.emit=a.addListener=a.on=a.prependListener=a.once=a.prependOnceListener=a.removeListener=a.removeAllListeners=a.listeners=a.listenerCount=a.eventNames=a.write=a.flush=mh,a.serializers=n,a._serialize=i,a._stdErrSerialize=s,a.child=A,e&&(a._logEvent=bS());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function w(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,Bc(c,a,"error","log"),Bc(c,a,"fatal","error"),Bc(c,a,"warn","error"),Bc(c,a,"info","log"),Bc(c,a,"debug","log"),Bc(c,a,"trace","log")}function A(T,x){if(!T)throw new Error("missing bindings for child Pino");x=x||{},i&&T.serializers&&(x.serializers=T.serializers);let B=x.serializers;if(i&&B){var V=Object.assign({},n,B),U=t.browser.serialize===!0?Object.keys(V):i;delete T.serializers,em([T],U,V,this._stdErrSerialize)}function Q(L){this._childLevel=(L._childLevel|0)+1,this.error=Mc(L,T,"error"),this.fatal=Mc(L,T,"fatal"),this.warn=Mc(L,T,"warn"),this.info=Mc(L,T,"info"),this.debug=Mc(L,T,"debug"),this.trace=Mc(L,T,"trace"),V&&(this.serializers=V,this._serialize=U),e&&(this._logEvent=bS([].concat(L._logEvent.bindings,T)))}return Q.prototype=this,new Q(this)}return a}ts.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};ts.stdSerializers=pJ;ts.stdTimeFunctions=Object.assign({},{nullTime:SP,epochTime:IP,unixTime:bJ,isoTime:SJ});function Bc(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mh:i[r]?i[r]:ph[r]||ph[n]||mh,yJ(t,e,r)}function yJ(t,e,r){!t.transmit&&e[r]===mh||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ph?ph:this;for(var a=0;a-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Mc(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;ism,PINO_CUSTOM_CONTEXT_KEY:()=>Lc,PINO_LOGGER_DEFAULTS:()=>xP,formatChildLoggerContext:()=>RP,generateChildLogger:()=>DJ,generateClientLogger:()=>BP,generatePlatformLogger:()=>PJ,generateServerLogger:()=>MP,getBrowserLoggerContext:()=>OP,getDefaultLoggerOptions:()=>OJ,getLoggerContext:()=>PP,pino:()=>NP.default,setBrowserLoggerContext:()=>DP});function OJ(t){return im(nm({},t),{level:t?.level||xP.level})}function OP(t,e=Lc){return t[e]||""}function DP(t,e,r=Lc){return t[r]=e,t}function PP(t,e=Lc){let r="";return typeof t.bindings>"u"?r=OP(t,e):r=t.bindings().context||"",r}function RP(t,e,r=Lc){let n=PP(t,r);return n.trim()?`${n}/${e}`:e}function DJ(t,e,r=Lc){let n=RP(t,e,r),i=t.child({context:n});return DP(i,n,r)}function BP(t){var e,r;let n=new TS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(im(nm({},t.opts),{level:"trace",browser:im(nm({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function MP(t){var e;let r=new _S((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(im(nm({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function PJ(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?BP(t):MP(t)}var Us,NP,xP,Lc,sm,IS,tm,rm,TS,_S,TJ,_J,CJ,_P,NJ,xJ,CP,nm,im,NS=fe(()=>{h();Us=pe(SS()),NP=pe(SS());xc();xP={level:"info"},Lc="custom_context",sm=1e3*1024,IS=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},tm=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let r=new IS(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let r=e.value;return e=e.next,{done:!1,value:r}}}}},rm=class{constructor(e,r=sm){this.level=e??"error",this.levelValue=Us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new tm(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Us.levels.values.error?console.error(e):r===Us.levels.values.warn?console.warn(e):r===Us.levels.values.debug?console.debug(e):r===Us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ai({timestamp:new Date().toISOString(),log:e}));let r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new tm(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let r=this.getLogArray();return r.push(Ai({extraMetadata:e})),new Blob(r,{type:"application/json"})}},TS=class{constructor(e,r=sm){this.baseChunkLogger=new rm(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},_S=class{constructor(e,r=sm){this.baseChunkLogger=new rm(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}},TJ=Object.defineProperty,_J=Object.defineProperties,CJ=Object.getOwnPropertyDescriptors,_P=Object.getOwnPropertySymbols,NJ=Object.prototype.hasOwnProperty,xJ=Object.prototype.propertyIsEnumerable,CP=(t,e,r)=>e in t?TJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nm=(t,e)=>{for(var r in e||(e={}))NJ.call(e,r)&&CP(t,r,e[r]);if(_P)for(var r of _P(e))xJ.call(e,r)&&CP(t,r,e[r]);return t},im=(t,e)=>_J(t,CJ(e))});var KS=D(ar=>{"use strict";h();Object.defineProperty(ar,"__esModule",{value:!0});var Fc=(fS(),_e(lS)),LP=Ds();function RJ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var BJ=RJ(LP),xS=class extends Fc.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},OS=class{constructor(e,r,n){this.core=e,this.logger=r}},DS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},PS=class{constructor(e,r){this.logger=e,this.core=r}},RS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},BS=class extends Fc.IEvents{constructor(e){super()}},MS=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},LS=class{constructor(){this.map=new Map}},FS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},US=class{constructor(e,r){this.core=e,this.logger=r}},qS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},VS=class{constructor(e,r){this.logger=e,this.core=r}},kS=class{constructor(e,r){this.projectId=e,this.logger=r}},HS=class{constructor(e,r){this.projectId=e,this.logger=r}},GS=class extends BJ.default{constructor(){super()}},jS=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},zS=class extends LP.EventEmitter{constructor(){super()}},QS=class{constructor(e){this.client=e}};ar.ICore=xS,ar.ICrypto=OS,ar.IEchoClient=HS,ar.IEngine=QS,ar.IEngineEvents=zS,ar.IExpirer=qS,ar.IJsonRpcHistory=DS,ar.IKeyChain=US,ar.IMessageTracker=PS,ar.IPairing=VS,ar.IPublisher=RS,ar.IRelayer=BS,ar.ISignClient=jS,ar.ISignClientEvents=GS,ar.IStore=MS,ar.ISubscriber=FS,ar.ISubscriberTopicMap=LS,ar.IVerify=kS});var UP=D(om=>{"use strict";h();Object.defineProperty(om,"__esModule",{value:!0});om.BrowserRandomSource=void 0;var FP=65536,WS=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";h();Object.defineProperty($S,"__esModule",{value:!0});function MJ(t){for(var e=0;e{h()});var VP=D(am=>{"use strict";h();Object.defineProperty(am,"__esModule",{value:!0});am.NodeRandomSource=void 0;var LJ=Qn(),YS=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof Pd<"u"){let e=qP();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";h();Object.defineProperty(um,"__esModule",{value:!0});um.SystemRandomSource=void 0;var FJ=UP(),UJ=VP(),JS=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new FJ.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new UJ.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};um.SystemRandomSource=JS});var HP=D(dn=>{"use strict";h();Object.defineProperty(dn,"__esModule",{value:!0});function qJ(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}dn.mul=Math.imul||qJ;function VJ(t,e){return t+e|0}dn.add=VJ;function kJ(t,e){return t-e|0}dn.sub=kJ;function HJ(t,e){return t<>>32-e}dn.rotl=HJ;function GJ(t,e){return t<<32-e|t>>>e}dn.rotr=GJ;function jJ(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}dn.isInteger=Number.isInteger||jJ;dn.MAX_SAFE_INTEGER=9007199254740991;dn.isSafeInteger=function(t){return dn.isInteger(t)&&t>=-dn.MAX_SAFE_INTEGER&&t<=dn.MAX_SAFE_INTEGER}});var Uc=D(xe=>{"use strict";h();Object.defineProperty(xe,"__esModule",{value:!0});var GP=HP();function zJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}xe.readInt16BE=zJ;function QJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}xe.readUint16BE=QJ;function KJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}xe.readInt16LE=KJ;function WJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}xe.readUint16LE=WJ;function jP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}xe.writeUint16BE=jP;xe.writeInt16BE=jP;function zP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}xe.writeUint16LE=zP;xe.writeInt16LE=zP;function XS(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}xe.readInt32BE=XS;function ZS(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}xe.readUint32BE=ZS;function eI(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}xe.readInt32LE=eI;function tI(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}xe.readUint32LE=tI;function cm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}xe.writeUint32BE=cm;xe.writeInt32BE=cm;function lm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}xe.writeUint32LE=lm;xe.writeInt32LE=lm;function $J(t,e){e===void 0&&(e=0);var r=XS(t,e),n=XS(t,e+4);return r*4294967296+n-(n>>31)*4294967296}xe.readInt64BE=$J;function YJ(t,e){e===void 0&&(e=0);var r=ZS(t,e),n=ZS(t,e+4);return r*4294967296+n}xe.readUint64BE=YJ;function JJ(t,e){e===void 0&&(e=0);var r=eI(t,e),n=eI(t,e+4);return n*4294967296+r-(r>>31)*4294967296}xe.readInt64LE=JJ;function XJ(t,e){e===void 0&&(e=0);var r=tI(t,e),n=tI(t,e+4);return n*4294967296+r}xe.readUint64LE=XJ;function QP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),cm(t/4294967296>>>0,e,r),cm(t>>>0,e,r+4),e}xe.writeUint64BE=QP;xe.writeInt64BE=QP;function KP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),lm(t>>>0,e,r),lm(t/4294967296>>>0,e,r+4),e}xe.writeUint64LE=KP;xe.writeInt64LE=KP;function ZJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}xe.readUintBE=ZJ;function eX(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}xe.writeUintBE=tX;function rX(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!GP.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";h();Object.defineProperty(Br,"__esModule",{value:!0});Br.randomStringForEntropy=Br.randomString=Br.randomUint32=Br.randomBytes=Br.defaultRandomSource=void 0;var fX=kP(),hX=Uc(),WP=Qn();Br.defaultRandomSource=new fX.SystemRandomSource;function rI(t,e=Br.defaultRandomSource){return e.randomBytes(t)}Br.randomBytes=rI;function dX(t=Br.defaultRandomSource){let e=rI(4,t),r=(0,hX.readUint32LE)(e);return(0,WP.wipe)(e),r}Br.randomUint32=dX;var $P="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function YP(t,e=$P,r=Br.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=rI(Math.ceil(t*256/s),r);for(let u=0;u0;u++){let a=o[u];a{"use strict";h();Object.defineProperty(qs,"__esModule",{value:!0});var Vc=Uc(),qc=Qn();qs.DIGEST_LENGTH=64;qs.BLOCK_SIZE=128;var XP=function(){function t(){this.digestLength=qs.DIGEST_LENGTH,this.blockSize=qs.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){qc.wipe(this._buffer),qc.wipe(this._tempHi),qc.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(nI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=nI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){qc.wipe(e.stateHi),qc.wipe(e.stateLo),e.buffer&&qc.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();qs.SHA512=XP;var JP=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function nI(t,e,r,n,i,s,o){for(var u=r[0],a=r[1],c=r[2],f=r[3],d=r[4],w=r[5],A=r[6],T=r[7],x=n[0],B=n[1],V=n[2],U=n[3],Q=n[4],L=n[5],k=n[6],H=n[7],q,v,C,P,F,R,l,g;o>=128;){for(var y=0;y<16;y++){var E=8*y+s;t[y]=Vc.readUint32BE(i,E),e[y]=Vc.readUint32BE(i,E+4)}for(var y=0;y<80;y++){var I=u,_=a,M=c,N=f,m=d,O=w,Y=A,$=T,b=x,j=B,z=V,W=U,ie=Q,te=L,ee=k,se=H;if(q=T,v=H,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=(d>>>14|Q<<18)^(d>>>18|Q<<14)^(Q>>>9|d<<23),v=(Q>>>14|d<<18)^(Q>>>18|d<<14)^(d>>>9|Q<<23),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=d&w^~d&A,v=Q&L^~Q&k,F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=JP[y*2],v=JP[y*2+1],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=t[y%16],v=e[y%16],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,C=l&65535|g<<16,P=F&65535|R<<16,q=C,v=P,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=(u>>>28|x<<4)^(x>>>2|u<<30)^(x>>>7|u<<25),v=(x>>>28|u<<4)^(u>>>2|x<<30)^(u>>>7|x<<25),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=u&a^u&c^a&c,v=x&B^x&V^B&V,F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,$=l&65535|g<<16,se=F&65535|R<<16,q=N,v=W,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=C,v=P,F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,N=l&65535|g<<16,W=F&65535|R<<16,a=I,c=_,f=M,d=N,w=m,A=O,T=Y,u=$,B=b,V=j,U=z,Q=W,L=ie,k=te,H=ee,x=se,y%16===15)for(var E=0;E<16;E++)q=t[E],v=e[E],F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=t[(E+9)%16],v=e[(E+9)%16],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+1)%16],P=e[(E+1)%16],q=(C>>>1|P<<31)^(C>>>8|P<<24)^C>>>7,v=(P>>>1|C<<31)^(P>>>8|C<<24)^(P>>>7|C<<25),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+14)%16],P=e[(E+14)%16],q=(C>>>19|P<<13)^(P>>>29|C<<3)^C>>>6,v=(P>>>19|C<<13)^(C>>>29|P<<3)^(P>>>6|C<<26),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,t[E]=l&65535|g<<16,e[E]=F&65535|R<<16}q=u,v=x,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[0],v=n[0],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[0]=u=l&65535|g<<16,n[0]=x=F&65535|R<<16,q=a,v=B,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[1],v=n[1],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[1]=a=l&65535|g<<16,n[1]=B=F&65535|R<<16,q=c,v=V,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[2],v=n[2],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[2]=c=l&65535|g<<16,n[2]=V=F&65535|R<<16,q=f,v=U,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[3],v=n[3],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[3]=f=l&65535|g<<16,n[3]=U=F&65535|R<<16,q=d,v=Q,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[4],v=n[4],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[4]=d=l&65535|g<<16,n[4]=Q=F&65535|R<<16,q=w,v=L,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[5],v=n[5],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[5]=w=l&65535|g<<16,n[5]=L=F&65535|R<<16,q=A,v=k,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[6],v=n[6],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[6]=A=l&65535|g<<16,n[6]=k=F&65535|R<<16,q=T,v=H,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[7],v=n[7],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[7]=T=l&65535|g<<16,n[7]=H=F&65535|R<<16,s+=128,o-=128}return s}function pX(t){var e=new XP;e.update(t);var r=e.digest();return e.clean(),r}qs.hash=pX});var dR=D(Ge=>{"use strict";h();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.convertSecretKeyToX25519=Ge.convertPublicKeyToX25519=Ge.verify=Ge.sign=Ge.extractPublicKeyFromSecretKey=Ge.generateKeyPair=Ge.generateKeyPairFromSeed=Ge.SEED_LENGTH=Ge.SECRET_KEY_LENGTH=Ge.PUBLIC_KEY_LENGTH=Ge.SIGNATURE_LENGTH=void 0;var mX=yh(),wh=ZP(),iR=Qn();Ge.SIGNATURE_LENGTH=64;Ge.PUBLIC_KEY_LENGTH=32;Ge.SECRET_KEY_LENGTH=64;Ge.SEED_LENGTH=32;function ve(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,sR(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function oR(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function rR(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return vh(r,t),vh(n,e),oR(r,n)}function aR(t){let e=new Uint8Array(32);return vh(e,t),e[0]&1}function EX(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Qa(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Wa(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function Ct(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,B=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,P=0,F=0,R=0,l=0,g=0,y=0,E=0,I=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,B+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,B+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,B+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,B+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,B+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,B+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,B+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,P+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,B+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,P+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,B+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,P+=n*oe,F+=n*J,R+=n*ue,n=e[9],T+=n*N,x+=n*m,B+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,P+=n*se,F+=n*oe,R+=n*J,l+=n*ue,n=e[10],x+=n*N,B+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,P+=n*ee,F+=n*se,R+=n*oe,l+=n*J,g+=n*ue,n=e[11],B+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,P+=n*te,F+=n*ee,R+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,P+=n*ie,F+=n*te,R+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,P+=n*W,F+=n*ie,R+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,I+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,P+=n*z,F+=n*W,R+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,I+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,P+=n*j,F+=n*z,R+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,I+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*P,d+=38*F,w+=38*R,A+=38*l,T+=38*g,x+=38*y,B+=38*E,V+=38*I,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=B,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ka(t,e){Ct(t,e,e)}function uR(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)Ka(r,r),n!==2&&n!==4&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function bX(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)Ka(r,r),n!==1&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function aI(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve(),c=ve(),f=ve();Wa(r,t[1],t[0]),Wa(f,e[1],e[0]),Ct(r,r,f),Qa(n,t[0],t[1]),Qa(f,e[0],e[1]),Ct(n,n,f),Ct(i,t[3],e[3]),Ct(i,i,vX),Ct(s,t[2],e[2]),Qa(s,s,s),Wa(o,n,r),Wa(u,s,i),Qa(a,s,i),Qa(c,n,r),Ct(t[0],o,u),Ct(t[1],c,a),Ct(t[2],a,u),Ct(t[3],o,c)}function nR(t,e,r){for(let n=0;n<4;n++)sR(t[n],e[n],r)}function cI(t,e){let r=ve(),n=ve(),i=ve();uR(i,e[2]),Ct(r,e[0],i),Ct(n,e[1],i),vh(t,n),t[31]^=aR(r)<<7}function cR(t,e,r){Bo(t[0],oI),Bo(t[1],kc),Bo(t[2],kc),Bo(t[3],oI);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;nR(t,e,i),aI(e,t),aI(t,t),nR(t,e,i)}}function lI(t,e){let r=[ve(),ve(),ve(),ve()];Bo(r[0],eR),Bo(r[1],tR),Bo(r[2],kc),Ct(r[3],eR,tR),cR(t,r,e)}function lR(t){if(t.length!==Ge.SEED_LENGTH)throw new Error(`ed25519: seed must be ${Ge.SEED_LENGTH} bytes`);let e=(0,wh.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[ve(),ve(),ve(),ve()];lI(n,e),cI(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}Ge.generateKeyPairFromSeed=lR;function SX(t){let e=(0,mX.randomBytes)(32,t),r=lR(e);return(0,iR.wipe)(e),r}Ge.generateKeyPair=SX;function IX(t){if(t.length!==Ge.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${Ge.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}Ge.extractPublicKeyFromSecretKey=IX;var sI=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function fR(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*sI[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*sI[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function uI(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;fR(t,e)}function TX(t,e){let r=new Float64Array(64),n=[ve(),ve(),ve(),ve()],i=(0,wh.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new wh.SHA512;o.update(s.subarray(32)),o.update(e);let u=o.digest();o.clean(),uI(u),lI(n,u),cI(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let a=o.digest();uI(a);for(let c=0;c<32;c++)r[c]=u[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=a[c]*i[f];return fR(s.subarray(32),r),s}Ge.sign=TX;function hR(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve();return Bo(t[2],kc),EX(t[1],e),Ka(i,t[1]),Ct(s,i,wX),Wa(i,i,t[2]),Qa(s,t[2],s),Ka(o,s),Ka(u,o),Ct(a,u,o),Ct(r,a,i),Ct(r,r,s),bX(r,r),Ct(r,r,i),Ct(r,r,s),Ct(r,r,s),Ct(t[0],r,s),Ka(n,t[0]),Ct(n,n,s),rR(n,i)&&Ct(t[0],t[0],AX),Ka(n,t[0]),Ct(n,n,s),rR(n,i)?-1:(aR(t[0])===e[31]>>7&&Wa(t[0],oI,t[0]),Ct(t[3],t[0],t[1]),0)}function _X(t,e,r){let n=new Uint8Array(32),i=[ve(),ve(),ve(),ve()],s=[ve(),ve(),ve(),ve()];if(r.length!==Ge.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${Ge.SIGNATURE_LENGTH} bytes`);if(hR(s,t))return!1;let o=new wh.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let u=o.digest();return uI(u),cR(i,s,u),lI(s,r.subarray(32)),aI(i,s),cI(n,i),!oR(r,n)}Ge.verify=_X;function CX(t){let e=[ve(),ve(),ve(),ve()];if(hR(e,t))throw new Error("Ed25519: invalid public key");let r=ve(),n=ve(),i=e[1];Qa(r,kc,i),Wa(n,kc,i),uR(n,n),Ct(r,r,n);let s=new Uint8Array(32);return vh(s,r),s}Ge.convertPublicKeyToX25519=CX;function NX(t){let e=(0,wh.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,iR.wipe)(e),r}Ge.convertSecretKeyToX25519=NX});var fm,hm,$a,Hc,dm,Ah,gm,pm,mm,Gc,ym,wm,gR,pR,vm=fe(()=>{h();fm="EdDSA",hm="JWT",$a=".",Hc="base64url",dm="utf8",Ah="utf8",gm=":",pm="did",mm="key",Gc="base58btc",ym="z",wm="K36",gR=32,pR=32});function Mo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var Eh=fe(()=>{h()});function jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var Am=fe(()=>{h();Eh()});function Em(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=jc(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Mo(r)}var fI=fe(()=>{h();Am();Eh()});function xX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");B=H,V++}for(var v=Q-B;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(B+(U-q)),C=B;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var OX,DX,mR,yR=fe(()=>{h();OX=xX,DX=OX,mR=DX});var xEe,wR,Vs,vR,AR,Lo=fe(()=>{h();xEe=new Uint8Array(0),wR=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},vR=t=>new TextEncoder().encode(t),AR=t=>new TextDecoder().decode(t)});var hI,dI,gI,bR,pI,zc,Fo,PX,RX,jt,Ei=fe(()=>{h();yR();Lo();hI=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},dI=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bR(this,e)}},gI=class{constructor(e){this.decoders=e}or(e){return bR(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},bR=(t,e)=>new gI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),pI=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new hI(e,r,n),this.decoder=new dI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zc=({name:t,prefix:e,encode:r,decode:n})=>new pI(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=mR(r,e);return zc({prefix:t,name:e,encode:n,decode:s=>Vs(i(s))})},PX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},RX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<zc({prefix:e,name:t,encode(i){return RX(i,n,r)},decode(i){return PX(i,n,r,t)}})});var mI={};Bt(mI,{identity:()=>BX});var BX,SR=fe(()=>{h();Ei();Lo();BX=zc({prefix:"\0",name:"identity",encode:t=>AR(t),decode:t=>vR(t)})});var yI={};Bt(yI,{base2:()=>MX});var MX,IR=fe(()=>{h();Ei();MX=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var wI={};Bt(wI,{base8:()=>LX});var LX,TR=fe(()=>{h();Ei();LX=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var vI={};Bt(vI,{base10:()=>FX});var FX,_R=fe(()=>{h();Ei();FX=Fo({prefix:"9",name:"base10",alphabet:"0123456789"})});var AI={};Bt(AI,{base16:()=>UX,base16upper:()=>qX});var UX,qX,CR=fe(()=>{h();Ei();UX=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qX=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var EI={};Bt(EI,{base32:()=>Qc,base32hex:()=>GX,base32hexpad:()=>zX,base32hexpadupper:()=>QX,base32hexupper:()=>jX,base32pad:()=>kX,base32padupper:()=>HX,base32upper:()=>VX,base32z:()=>KX});var Qc,VX,kX,HX,GX,jX,zX,QX,KX,bI=fe(()=>{h();Ei();Qc=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),VX=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kX=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),HX=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),GX=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jX=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zX=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),QX=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),KX=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var SI={};Bt(SI,{base36:()=>WX,base36upper:()=>$X});var WX,$X,NR=fe(()=>{h();Ei();WX=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$X=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var II={};Bt(II,{base58btc:()=>rs,base58flickr:()=>YX});var rs,YX,TI=fe(()=>{h();Ei();rs=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YX=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var _I={};Bt(_I,{base64:()=>JX,base64pad:()=>XX,base64url:()=>ZX,base64urlpad:()=>eZ});var JX,XX,ZX,eZ,xR=fe(()=>{h();Ei();JX=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XX=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ZX=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eZ=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var CI={};Bt(CI,{base256emoji:()=>sZ});function nZ(t){return t.reduce((e,r)=>(e+=tZ[r],e),"")}function iZ(t){let e=[];for(let r of t){let n=rZ[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var OR,tZ,rZ,sZ,DR=fe(()=>{h();Ei();OR=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),tZ=OR.reduce((t,e,r)=>(t[r]=e,t),[]),rZ=OR.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);sZ=zc({prefix:"\u{1F680}",name:"base256emoji",encode:nZ,decode:iZ})});function BR(t,e,r){e=e||[],r=r||0;for(var n=r;t>=cZ;)e[r++]=t&255|PR,t/=128;for(;t&uZ;)e[r++]=t&255|PR,t>>>=7;return e[r]=t|0,BR.bytes=r-n+1,e}function NI(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw NI.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&RR)<=fZ);return NI.bytes=s-n,r}var oZ,PR,aZ,uZ,cZ,lZ,fZ,RR,hZ,dZ,gZ,pZ,mZ,yZ,wZ,vZ,AZ,EZ,bZ,SZ,bh,MR=fe(()=>{h();oZ=BR,PR=128,aZ=127,uZ=~aZ,cZ=Math.pow(2,31);lZ=NI,fZ=128,RR=127;hZ=Math.pow(2,7),dZ=Math.pow(2,14),gZ=Math.pow(2,21),pZ=Math.pow(2,28),mZ=Math.pow(2,35),yZ=Math.pow(2,42),wZ=Math.pow(2,49),vZ=Math.pow(2,56),AZ=Math.pow(2,63),EZ=function(t){return t{h();MR();Sh=(t,e=0)=>[bh.decode(t,e),bh.decode.bytes],Kc=(t,e,r=0)=>(bh.encode(t,e,r),e),Wc=t=>bh.encodingLength(t)});var Ya,LR,FR,$c,Th=fe(()=>{h();Lo();Sm();Ya=(t,e)=>{let r=e.byteLength,n=Wc(t),i=n+Wc(r),s=new Uint8Array(i+r);return Kc(t,s,0),Kc(r,s,n),s.set(e,i),new $c(t,r,e,s)},LR=t=>{let e=Vs(t),[r,n]=Sh(e),[i,s]=Sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $c(r,i,o,e)},FR=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&wR(t.bytes,e.bytes),$c=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var OI,xI,DI=fe(()=>{h();Th();OI=({name:t,code:e,encode:r})=>new xI(t,e,r),xI=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ya(this.code,r):r.then(n=>Ya(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var PI={};Bt(PI,{sha256:()=>IZ,sha512:()=>TZ});var qR,IZ,TZ,VR=fe(()=>{h();DI();qR=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),IZ=OI({name:"sha2-256",code:18,encode:qR("SHA-256")}),TZ=OI({name:"sha2-512",code:19,encode:qR("SHA-512")})});var RI={};Bt(RI,{identity:()=>NZ});var kR,_Z,HR,CZ,NZ,GR=fe(()=>{h();Lo();Th();kR=0,_Z="identity",HR=Vs,CZ=t=>Ya(kR,HR(t)),NZ={code:kR,name:_Z,encode:HR,digest:CZ}});var jR=fe(()=>{h();Lo()});var pbe,mbe,zR=fe(()=>{h();pbe=new TextEncoder,mbe=new TextDecoder});var _m,DZ,PZ,RZ,_h,BZ,QR,KR,Im,Tm,MZ,LZ,FZ,WR=fe(()=>{h();Sm();Th();TI();bI();Lo();_m=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Tm,byteLength:Tm,code:Im,version:Im,multihash:Im,bytes:Im,_baseCache:Tm,asCID:Tm})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==_h)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==BZ)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ya(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&FR(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return PZ(r,i,e||rs.encoder);default:return RZ(r,i,e||Qc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return LZ(/^0\.0/,FZ),!!(e&&(e[KR]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||QR(r,n,i.bytes))}else if(e!=null&&e[KR]===!0){let{version:r,multihash:n,code:i}=e,s=LR(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==_h)throw new Error(`Version 0 CID must use dag-pb (code: ${_h}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=QR(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_h,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Vs(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $c(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,w]=Sh(e.subarray(r));return r+=w,d},i=n(),s=_h;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,u=n(),a=n(),c=r+a,f=c-o;return{version:i,codec:s,multihashCode:u,digestSize:a,multihashSize:f,size:c}}static parse(e,r){let[n,i]=DZ(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},DZ=(t,e)=>{switch(t[0]){case"Q":{let r=e||rs;return[rs.prefix,r.decode(`${rs.prefix}${t}`)]}case rs.prefix:{let r=e||rs;return[rs.prefix,r.decode(t)]}case Qc.prefix:{let r=e||Qc;return[Qc.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},PZ=(t,e,r)=>{let{prefix:n}=r;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},RZ=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},_h=112,BZ=18,QR=(t,e,r)=>{let n=Wc(t),i=n+Wc(e),s=new Uint8Array(i+r.byteLength);return Kc(t,s,0),Kc(e,s,n),s.set(r,i),s},KR=Symbol.for("@ipld/js-cid/CID"),Im={writable:!1,configurable:!1,enumerable:!0},Tm={writable:!1,enumerable:!1,configurable:!1},MZ="0.0.0-dev",LZ=(t,e)=>{if(t.test(MZ))console.warn(e);else throw new Error(e)},FZ=`CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: if (CID.isCID(value)) { @@ -34,31 +34,31 @@ if (cid) { // Make sure to use cid instead of value doSomethingWithCID(cid) } -`});var YR=fe(()=>{h();$R();Tm();Lo();OI();Th()});var RI,abe,JR=fe(()=>{h();IR();TR();_R();CR();NR();EI();xR();II();OR();PR();kR();jR();zR();QR();YR();RI={...pI,...mI,...yI,...wI,...vI,...AI,...bI,...SI,...TI,..._I},abe={...DI,...PI}});function ZR(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var XR,BI,SZ,xm,MI=fe(()=>{h();JR();bm();XR=ZR("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),BI=ZR("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=jc(t.length);for(let r=0;r{h();MI()});function ns(t,e="utf8"){let r=xm[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var FI=fe(()=>{h();MI();Eh()});function Ch(t){return Ro(ks(ns(t,Hc),pm))}function Nh(t){return ks(ns(Ai(t),pm),Hc)}function UI(t){let e=ns(Am,Gc),r=vm+ks(Sm([e,t]),Gc);return[ym,wm,r].join(mm)}function qI(t){let[e,r,n]=t.split(mm);if(e!==ym||r!==wm)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==vm)throw new Error("Issuer must be a key in mulicodec format");let s=ns(n.slice(1),Gc);if(ks(s.slice(0,2),Gc)!==Am)throw new Error('Issuer must be a public key with type "Ed25519"');let u=s.slice(2);if(u.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return u}function eB(t){return ks(t,Hc)}function tB(t){return ns(t,Hc)}function VI(t){return ns([Nh(t.header),Nh(t.payload)].join(Ya),Ah)}function IZ(t){let e=ks(t,Ah).split(Ya),r=Ch(e[0]),n=Ch(e[1]);return{header:r,payload:n}}function kI(t){return[Nh(t.header),Nh(t.payload),eB(t.signature)].join(Ya)}function HI(t){let e=t.split(Ya),r=Ch(e[0]),n=Ch(e[1]),i=tB(e[2]),s=ns(e.slice(0,2).join(Ya),Ah);return{header:r,payload:n,signature:i,data:s}}var GI=fe(()=>{h();lI();LI();FI();xc();Em()});function TZ(t=(0,rB.randomBytes)(32)){return Yc.generateKeyPairFromSeed(t)}async function _Z(t,e,r,n,i=(0,nB.fromMiliseconds)(Date.now())){let s={alg:dm,typ:gm},o=UI(n.publicKey),u=i+r,a={iss:o,sub:t,aud:e,iat:i,exp:u},c=VI({header:s,payload:a}),f=Yc.sign(n.secretKey,c);return kI({header:s,payload:a,signature:f})}async function CZ(t){let{header:e,payload:r,data:n,signature:i}=HI(t);if(e.alg!==dm||e.typ!==gm)throw new Error("JWT must use EdDSA algorithm");let s=qI(r.iss);return Yc.verify(s,n,i)}var Yc,rB,nB,iB=fe(()=>{h();Yc=pe(gR()),rB=pe(yh()),nB=pe(Qa());Em();GI()});var sB=fe(()=>{h()});var oB={};Bt(oB,{DATA_ENCODING:()=>Ah,DID_DELIMITER:()=>mm,DID_METHOD:()=>wm,DID_PREFIX:()=>ym,JSON_ENCODING:()=>pm,JWT_DELIMITER:()=>Ya,JWT_ENCODING:()=>Hc,JWT_IRIDIUM_ALG:()=>dm,JWT_IRIDIUM_TYP:()=>gm,KEY_PAIR_SEED_LENGTH:()=>mR,MULTICODEC_ED25519_BASE:()=>vm,MULTICODEC_ED25519_ENCODING:()=>Gc,MULTICODEC_ED25519_HEADER:()=>Am,MULTICODEC_ED25519_LENGTH:()=>pR,decodeData:()=>IZ,decodeIss:()=>qI,decodeJSON:()=>Ch,decodeJWT:()=>HI,decodeSig:()=>tB,encodeData:()=>VI,encodeIss:()=>UI,encodeJSON:()=>Nh,encodeJWT:()=>kI,encodeSig:()=>eB,generateKeyPair:()=>TZ,signJWT:()=>_Z,verifyJWT:()=>CZ});var aB=fe(()=>{h();iB();Em();sB();GI()});var vB=B(qt=>{"use strict";h();var uB=qt&&qt.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new pB:typeof navigator<"u"?jI(navigator.userAgent):wB()}qt.detect=DZ;function mB(t){return t!==""&&OZ.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function PZ(t){var e=mB(t);return e?e[0]:null}qt.browserName=PZ;function jI(t){var e=mB(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new gB;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getLocalStorage=Ot.getLocalStorageOrThrow=Ot.getCrypto=Ot.getCryptoOrThrow=Ot.getLocation=Ot.getLocationOrThrow=Ot.getNavigator=Ot.getNavigatorOrThrow=Ot.getDocument=Ot.getDocumentOrThrow=Ot.getFromWindowOrThrow=Ot.getFromWindow=void 0;function Xa(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}Ot.getFromWindow=Xa;function Jc(t){let e=Xa(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}Ot.getFromWindowOrThrow=Jc;function BZ(){return Jc("document")}Ot.getDocumentOrThrow=BZ;function MZ(){return Xa("document")}Ot.getDocument=MZ;function LZ(){return Jc("navigator")}Ot.getNavigatorOrThrow=LZ;function FZ(){return Xa("navigator")}Ot.getNavigator=FZ;function UZ(){return Jc("location")}Ot.getLocationOrThrow=UZ;function qZ(){return Xa("location")}Ot.getLocation=qZ;function VZ(){return Jc("crypto")}Ot.getCryptoOrThrow=VZ;function kZ(){return Xa("crypto")}Ot.getCrypto=kZ;function HZ(){return Jc("localStorage")}Ot.getLocalStorageOrThrow=HZ;function GZ(){return Xa("localStorage")}Ot.getLocalStorage=GZ});var EB=B(Om=>{"use strict";h();Object.defineProperty(Om,"__esModule",{value:!0});Om.getWindowMetadata=void 0;var AB=zI();function jZ(){let t,e;try{t=AB.getDocumentOrThrow(),e=AB.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),w=[];for(let A=0;A-1){let R=T.getAttribute("href");if(R)if(R.toLowerCase().indexOf("https:")===-1&&R.toLowerCase().indexOf("http:")===-1&&R.indexOf("//")!==0){let V=e.protocol+"//"+e.host;if(R.indexOf("/")===0)V+=R;else{let U=e.pathname.split("/");U.pop();let Q=U.join("/");V+=Q+"/"+R}w.push(V)}else if(R.indexOf("//")===0){let V=e.protocol+R;w.push(V)}else w.push(R)}}return w}function n(...d){let w=t.getElementsByTagName("meta");for(let A=0;AT.getAttribute(R)).filter(R=>R?d.includes(R):!1);if(x.length&&x){let R=T.getAttribute("content");if(R)return R}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),u=s(),a=e.origin,c=r();return{description:u,url:a,icons:c,name:o}}Om.getWindowMetadata=jZ});var SB=B((jbe,bB)=>{"use strict";h();bB.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var NB=B((Qbe,CB)=>{"use strict";h();var _B="%[a-f0-9]{2}",IB=new RegExp("("+_B+")|([^%]+?)","gi"),TB=new RegExp("("+_B+")+","gi");function QI(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],QI(r),QI(n))}function zZ(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(IB)||[],r=1;r{"use strict";h();xB.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var PB=B((Ybe,DB)=>{"use strict";h();DB.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";h();var KZ=SB(),WZ=NB(),BB=OB(),$Z=PB(),YZ=t=>t==null,KI=Symbol("encodeFragmentIdentifier");function JZ(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[",i,"]"].join("")]:[...r,[Zt(e,t),"[",Zt(i,t),"]=",Zt(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[]"].join("")]:[...r,[Zt(e,t),"[]=",Zt(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),":list="].join("")]:[...r,[Zt(e,t),":list=",Zt(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[Zt(r,t),e,Zt(i,t)].join("")]:[[n,Zt(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,Zt(e,t)]:[...r,[Zt(e,t),"=",Zt(n,t)].join("")]}}function XZ(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&Hs(n,t).includes(t.arrayFormatSeparator);n=o?Hs(n,t):n;let u=s||o?n.split(t.arrayFormatSeparator).map(a=>Hs(a,t)):n===null?n:Hs(n,t);i[r]=u};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&Hs(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(u=>Hs(u,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function MB(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Zt(t,e){return e.encode?e.strict?KZ(t):encodeURIComponent(t):t}function Hs(t,e){return e.decode?WZ(t):t}function LB(t){return Array.isArray(t)?t.sort():typeof t=="object"?LB(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function FB(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function ZZ(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function UB(t){t=FB(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function RB(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function qB(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),MB(e.arrayFormatSeparator);let r=XZ(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=BB(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:Hs(o,e),r(Hs(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=RB(s[o],e);else n[i]=RB(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=LB(o):i[s]=o,i},Object.create(null))}nn.extract=UB;nn.parse=qB;nn.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),MB(e.arrayFormatSeparator);let r=o=>e.skipNull&&YZ(t[o])||e.skipEmptyString&&t[o]==="",n=JZ(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let u=t[o];return u===void 0?"":u===null?Zt(o,e):Array.isArray(u)?u.length===0&&e.arrayFormat==="bracket-separator"?Zt(o,e)+"[]":u.reduce(n(o),[]).join("&"):Zt(o,e)+"="+Zt(u,e)}).filter(o=>o.length>0).join("&")};nn.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=BB(t,"#");return Object.assign({url:r.split("?")[0]||"",query:qB(UB(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:Hs(n,e)}:{})};nn.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[KI]:!0},e);let r=FB(t.url).split("?")[0]||"",n=nn.extract(t.url),i=nn.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=nn.stringify(s,e);o&&(o=`?${o}`);let u=ZZ(t.url);return t.fragmentIdentifier&&(u=`#${e[KI]?Zt(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${u}`};nn.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[KI]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=nn.parseUrl(t,r);return nn.stringifyUrl({url:n,query:$Z(i,e),fragmentIdentifier:s},r)};nn.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return nn.pick(t,n,r)}});var HB=B(Dm=>{"use strict";h();Object.defineProperty(Dm,"__esModule",{value:!0});var Mr=Uc(),WI=Qn(),eee=20;function tee(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,u=r[3]<<24|r[2]<<16|r[1]<<8|r[0],a=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],w=r[23]<<24|r[22]<<16|r[21]<<8|r[20],A=r[27]<<24|r[26]<<16|r[25]<<8|r[24],T=r[31]<<24|r[30]<<16|r[29]<<8|r[28],x=e[3]<<24|e[2]<<16|e[1]<<8|e[0],R=e[7]<<24|e[6]<<16|e[5]<<8|e[4],V=e[11]<<24|e[10]<<16|e[9]<<8|e[8],U=e[15]<<24|e[14]<<16|e[13]<<8|e[12],Q=n,L=i,k=s,H=o,q=u,v=a,C=c,D=f,F=d,P=w,l=A,g=T,y=x,E=R,S=V,_=U,M=0;M>>16|y<<16,F=F+y|0,q^=F,q=q>>>20|q<<12,L=L+v|0,E^=L,E=E>>>16|E<<16,P=P+E|0,v^=P,v=v>>>20|v<<12,k=k+C|0,S^=k,S=S>>>16|S<<16,l=l+S|0,C^=l,C=C>>>20|C<<12,H=H+D|0,_^=H,_=_>>>16|_<<16,g=g+_|0,D^=g,D=D>>>20|D<<12,k=k+C|0,S^=k,S=S>>>24|S<<8,l=l+S|0,C^=l,C=C>>>25|C<<7,H=H+D|0,_^=H,_=_>>>24|_<<8,g=g+_|0,D^=g,D=D>>>25|D<<7,L=L+v|0,E^=L,E=E>>>24|E<<8,P=P+E|0,v^=P,v=v>>>25|v<<7,Q=Q+q|0,y^=Q,y=y>>>24|y<<8,F=F+y|0,q^=F,q=q>>>25|q<<7,Q=Q+v|0,_^=Q,_=_>>>16|_<<16,l=l+_|0,v^=l,v=v>>>20|v<<12,L=L+C|0,y^=L,y=y>>>16|y<<16,g=g+y|0,C^=g,C=C>>>20|C<<12,k=k+D|0,E^=k,E=E>>>16|E<<16,F=F+E|0,D^=F,D=D>>>20|D<<12,H=H+q|0,S^=H,S=S>>>16|S<<16,P=P+S|0,q^=P,q=q>>>20|q<<12,k=k+D|0,E^=k,E=E>>>24|E<<8,F=F+E|0,D^=F,D=D>>>25|D<<7,H=H+q|0,S^=H,S=S>>>24|S<<8,P=P+S|0,q^=P,q=q>>>25|q<<7,L=L+C|0,y^=L,y=y>>>24|y<<8,g=g+y|0,C^=g,C=C>>>25|C<<7,Q=Q+v|0,_^=Q,_=_>>>24|_<<8,l=l+_|0,v^=l,v=v>>>25|v<<7;Mr.writeUint32LE(Q+n|0,t,0),Mr.writeUint32LE(L+i|0,t,4),Mr.writeUint32LE(k+s|0,t,8),Mr.writeUint32LE(H+o|0,t,12),Mr.writeUint32LE(q+u|0,t,16),Mr.writeUint32LE(v+a|0,t,20),Mr.writeUint32LE(C+c|0,t,24),Mr.writeUint32LE(D+f|0,t,28),Mr.writeUint32LE(F+d|0,t,32),Mr.writeUint32LE(P+w|0,t,36),Mr.writeUint32LE(l+A|0,t,40),Mr.writeUint32LE(g+T|0,t,44),Mr.writeUint32LE(y+x|0,t,48),Mr.writeUint32LE(E+R|0,t,52),Mr.writeUint32LE(S+V|0,t,56),Mr.writeUint32LE(_+U|0,t,60)}function kB(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Pm=B(Xc=>{"use strict";h();Object.defineProperty(Xc,"__esModule",{value:!0});function iee(t,e,r){return~(t-1)&e|t-1&r}Xc.select=iee;function see(t,e){return(t|0)-(e|0)-1>>>31&1}Xc.lessOrEqual=see;function GB(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xc.compare=GB;function oee(t,e){return t.length===0||e.length===0?!1:GB(t,e)!==0}Xc.equal=oee});var zB=B(Gs=>{"use strict";h();Object.defineProperty(Gs,"__esModule",{value:!0});var aee=Pm(),Rm=Qn();Gs.DIGEST_LENGTH=16;var jB=function(){function t(e){this.digestLength=Gs.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var u=e[10]|e[11]<<8;this._r[6]=(o>>>14|u<<2)&8191;var a=e[12]|e[13]<<8;this._r[7]=(u>>>11|a<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(a>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],u=this._h[2],a=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],w=this._h[7],A=this._h[8],T=this._h[9],x=this._r[0],R=this._r[1],V=this._r[2],U=this._r[3],Q=this._r[4],L=this._r[5],k=this._r[6],H=this._r[7],q=this._r[8],v=this._r[9];n>=16;){var C=e[r+0]|e[r+1]<<8;s+=C&8191;var D=e[r+2]|e[r+3]<<8;o+=(C>>>13|D<<3)&8191;var F=e[r+4]|e[r+5]<<8;u+=(D>>>10|F<<6)&8191;var P=e[r+6]|e[r+7]<<8;a+=(F>>>7|P<<9)&8191;var l=e[r+8]|e[r+9]<<8;c+=(P>>>4|l<<12)&8191,f+=l>>>1&8191;var g=e[r+10]|e[r+11]<<8;d+=(l>>>14|g<<2)&8191;var y=e[r+12]|e[r+13]<<8;w+=(g>>>11|y<<5)&8191;var E=e[r+14]|e[r+15]<<8;A+=(y>>>8|E<<8)&8191,T+=E>>>5|i;var S=0,_=S;_+=s*x,_+=o*(5*v),_+=u*(5*q),_+=a*(5*H),_+=c*(5*k),S=_>>>13,_&=8191,_+=f*(5*L),_+=d*(5*Q),_+=w*(5*U),_+=A*(5*V),_+=T*(5*R),S+=_>>>13,_&=8191;var M=S;M+=s*R,M+=o*x,M+=u*(5*v),M+=a*(5*q),M+=c*(5*H),S=M>>>13,M&=8191,M+=f*(5*k),M+=d*(5*L),M+=w*(5*Q),M+=A*(5*U),M+=T*(5*V),S+=M>>>13,M&=8191;var N=S;N+=s*V,N+=o*R,N+=u*x,N+=a*(5*v),N+=c*(5*q),S=N>>>13,N&=8191,N+=f*(5*H),N+=d*(5*k),N+=w*(5*L),N+=A*(5*Q),N+=T*(5*U),S+=N>>>13,N&=8191;var m=S;m+=s*U,m+=o*V,m+=u*R,m+=a*x,m+=c*(5*v),S=m>>>13,m&=8191,m+=f*(5*q),m+=d*(5*H),m+=w*(5*k),m+=A*(5*L),m+=T*(5*Q),S+=m>>>13,m&=8191;var O=S;O+=s*Q,O+=o*U,O+=u*V,O+=a*R,O+=c*x,S=O>>>13,O&=8191,O+=f*(5*v),O+=d*(5*q),O+=w*(5*H),O+=A*(5*k),O+=T*(5*L),S+=O>>>13,O&=8191;var Y=S;Y+=s*L,Y+=o*Q,Y+=u*U,Y+=a*V,Y+=c*R,S=Y>>>13,Y&=8191,Y+=f*x,Y+=d*(5*v),Y+=w*(5*q),Y+=A*(5*H),Y+=T*(5*k),S+=Y>>>13,Y&=8191;var $=S;$+=s*k,$+=o*L,$+=u*Q,$+=a*U,$+=c*V,S=$>>>13,$&=8191,$+=f*R,$+=d*x,$+=w*(5*v),$+=A*(5*q),$+=T*(5*H),S+=$>>>13,$&=8191;var b=S;b+=s*H,b+=o*k,b+=u*L,b+=a*Q,b+=c*U,S=b>>>13,b&=8191,b+=f*V,b+=d*R,b+=w*x,b+=A*(5*v),b+=T*(5*q),S+=b>>>13,b&=8191;var j=S;j+=s*q,j+=o*H,j+=u*k,j+=a*L,j+=c*Q,S=j>>>13,j&=8191,j+=f*U,j+=d*V,j+=w*R,j+=A*x,j+=T*(5*v),S+=j>>>13,j&=8191;var z=S;z+=s*v,z+=o*q,z+=u*H,z+=a*k,z+=c*L,S=z>>>13,z&=8191,z+=f*Q,z+=d*U,z+=w*V,z+=A*R,z+=T*x,S+=z>>>13,z&=8191,S=(S<<2)+S|0,S=S+_|0,_=S&8191,S=S>>>13,M+=S,s=_,o=M,u=N,a=m,c=O,f=Y,d=$,w=b,A=j,T=z,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=u,this._h[3]=a,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=w,this._h[8]=A,this._h[9]=T},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,u;if(this._leftover){for(u=this._leftover,this._buffer[u++]=1;u<16;u++)this._buffer[u]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,u=2;u<10;u++)this._h[u]+=i,i=this._h[u]>>>13,this._h[u]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,u=1;u<10;u++)n[u]=this._h[u]+i,i=n[u]>>>13,n[u]&=8191;for(n[9]-=8192,s=(i^1)-1,u=0;u<10;u++)n[u]&=s;for(s=~s,u=0;u<10;u++)this._h[u]=this._h[u]&s|n[u];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,u=1;u<8;u++)o=(this._h[u]+this._pad[u]|0)+(o>>>16)|0,this._h[u]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";h();Object.defineProperty(js,"__esModule",{value:!0});var Bm=HB(),lee=zB(),xh=Qn(),QB=Uc(),fee=Pm();js.KEY_LENGTH=32;js.NONCE_LENGTH=12;js.TAG_LENGTH=16;var KB=new Uint8Array(16),hee=function(){function t(e){if(this.nonceLength=js.NONCE_LENGTH,this.tagLength=js.TAG_LENGTH,e.length!==js.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Bm.stream(this._key,s,o,4);var u=r.length+this.tagLength,a;if(i){if(i.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");a=i}else a=new Uint8Array(u);return Bm.streamXOR(this._key,s,r,a,4),this._authenticate(a.subarray(a.length-this.tagLength,a.length),o,a.subarray(0,a.length-this.tagLength),n),xh.wipe(s),a},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(KB.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(KB.subarray(n.length%16));var o=new Uint8Array(8);i&&QB.writeUint64LE(i.length,o),s.update(o),QB.writeUint64LE(n.length,o),s.update(o);for(var u=s.digest(),a=0;a{"use strict";h();Object.defineProperty($I,"__esModule",{value:!0});function dee(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}$I.isSerializableHash=dee});var JB=B(Oh=>{"use strict";h();Object.defineProperty(Oh,"__esModule",{value:!0});var is=$B(),gee=Pm(),pee=Qn(),YB=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";h();Object.defineProperty(YI,"__esModule",{value:!0});var XB=JB(),ZB=Qn(),yee=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=XB.hmac(this._hash,n,r);this._hmac=new XB.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";h();Object.defineProperty(Uo,"__esModule",{value:!0});var Lm=Uc(),Mm=Qn();Uo.DIGEST_LENGTH=32;Uo.BLOCK_SIZE=64;var tM=function(){function t(){this.digestLength=Uo.DIGEST_LENGTH,this.blockSize=Uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Mm.wipe(this._buffer),Mm.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(JI(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=JI(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Mm.wipe(e.state),e.buffer&&Mm.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Uo.SHA256=tM;var wee=new Int32Array([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]);function JI(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],u=e[2],a=e[3],c=e[4],f=e[5],d=e[6],w=e[7],A=0;A<16;A++){var T=n+A*4;t[A]=Lm.readUint32BE(r,T)}for(var A=16;A<64;A++){var x=t[A-2],R=(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10;x=t[A-15];var V=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3;t[A]=(R+t[A-7]|0)+(V+t[A-16]|0)}for(var A=0;A<64;A++){var R=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(w+(wee[A]+t[A]|0)|0)|0,V=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&u^o&u)|0;w=d,d=f,f=c,c=a+R|0,a=u,u=o,o=s,s=R+V|0}e[0]+=s,e[1]+=o,e[2]+=u,e[3]+=a,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=w,n+=64,i-=64}return n}function vee(t){var e=new tM;e.update(t);var r=e.digest();return e.clean(),r}Uo.hash=vee});var oM=B(zt=>{"use strict";h();Object.defineProperty(zt,"__esModule",{value:!0});zt.sharedKey=zt.generateKeyPair=zt.generateKeyPairFromSeed=zt.scalarMultBase=zt.scalarMult=zt.SHARED_KEY_LENGTH=zt.SECRET_KEY_LENGTH=zt.PUBLIC_KEY_LENGTH=void 0;var Aee=yh(),Eee=Qn();zt.PUBLIC_KEY_LENGTH=32;zt.SECRET_KEY_LENGTH=32;zt.SHARED_KEY_LENGTH=32;function ss(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Dh(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function Iee(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Fm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Um(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function zs(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ph(t,e){zs(t,e,e)}function Tee(t,e){let r=ss();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)Ph(r,r),n!==2&&n!==4&&zs(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function ZI(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=ss(),s=ss(),o=ss(),u=ss(),a=ss(),c=ss();for(let A=0;A<31;A++)r[A]=t[A];r[31]=t[31]&127|64,r[0]&=248,Iee(n,e);for(let A=0;A<16;A++)s[A]=n[A];i[0]=u[0]=1;for(let A=254;A>=0;--A){let T=r[A>>>3]>>>(A&7)&1;Dh(i,s,T),Dh(o,u,T),Fm(a,i,o),Um(i,i,o),Fm(o,s,u),Um(s,s,u),Ph(u,a),Ph(c,i),zs(i,o,i),zs(o,s,a),Fm(a,i,o),Um(i,i,o),Ph(s,i),Um(o,u,c),zs(i,o,bee),Fm(i,i,u),zs(o,o,i),zs(i,u,c),zs(u,s,n),Ph(s,a),Dh(i,s,T),Dh(o,u,T)}for(let A=0;A<16;A++)n[A+16]=i[A],n[A+32]=o[A],n[A+48]=s[A],n[A+64]=u[A];let f=n.subarray(32),d=n.subarray(16);Tee(f,f),zs(d,d,f);let w=new Uint8Array(32);return See(w,d),w}zt.scalarMult=ZI;function iM(t){return ZI(t,nM)}zt.scalarMultBase=iM;function sM(t){if(t.length!==zt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${zt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:iM(e),secretKey:e}}zt.generateKeyPairFromSeed=sM;function _ee(t){let e=(0,Aee.randomBytes)(32,t),r=sM(e);return(0,Eee.wipe)(e),r}zt.generateKeyPair=_ee;function Cee(t,e,r=!1){if(t.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=ZI(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{h()});function cM(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{h()});function fM(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=jc(t.length);for(let n=0;n{h();bm();Eh()});var eT={};Bt(eT,{compare:()=>aM,concat:()=>Sm,equals:()=>cM,fromString:()=>ns,toString:()=>ks,xor:()=>fM});var tT=fe(()=>{h();uM();lI();lM();FI();LI();hM()});var dM={};Bt(dM,{RELAY_JSONRPC:()=>qee,isPublishMethod:()=>iT,isPublishParams:()=>sT,isPublishRequest:()=>Pee,isSubscribeMethod:()=>rT,isSubscribeParams:()=>nT,isSubscribeRequest:()=>Dee,isSubscriptionMethod:()=>uT,isSubscriptionParams:()=>cT,isSubscriptionRequest:()=>Bee,isUnsubscribeMethod:()=>oT,isUnsubscribeParams:()=>aT,isUnsubscribeRequest:()=>Ree,parsePublishRequest:()=>Lee,parseSubscribeRequest:()=>Mee,parseSubscriptionRequest:()=>Uee,parseUnsubscribeRequest:()=>Fee});function Za(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function Nee(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function xee(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function Oee(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function qm(t,e,r){return(r.length?Oee(t,e.length):xee(t,e.length))?Nee(t,e):!1}function Vm(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}function Dee(t){return rT(t.method)&&nT(t.params)}function rT(t){return Vm(t,"subscribe")}function nT(t){return qm(t,["topic"],[])}function Pee(t){return iT(t.method)&&sT(t.params)}function iT(t){return Vm(t,"publish")}function sT(t){return qm(t,["message","topic","ttl"],["prompt","tag"])}function Ree(t){return oT(t.method)&&aT(t.params)}function oT(t){return Vm(t,"unsubscribe")}function aT(t){return qm(t,["id","topic"],[])}function Bee(t){return uT(t.method)&&cT(t.params)}function uT(t){return Vm(t,"subscription")}function cT(t){return qm(t,["id","data"],[])}function Mee(t){if(!rT(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!nT(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Za(e,"topic"),e}function Lee(t){if(!iT(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!sT(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Za(e,"topic"),Za(e,"message"),Za(e,"ttl","number"),e}function Fee(t){if(!oT(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!aT(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Za(e,"id"),e}function Uee(t){if(!uT(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!cT(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Za(e,"id"),Za(e,"data"),e}var qee,gM=fe(()=>{h();qee={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var Qh=B(K=>{"use strict";h();Object.defineProperty(K,"__esModule",{value:!0});var Vee=vB(),el=Qa(),il=zI(),kee=EB(),Hee=VB(),WM=WB(),Gee=eM(),$M=yh(),LT=rM(),jee=oM(),Vt=(tT(),_e(eT)),zee=(gM(),_e(dM));function YM(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var $m=YM(Hee),JM=YM(jee),ny=":";function XM(t){let[e,r]=t.split(ny);return{namespace:e,reference:r}}function ZM(t){let{namespace:e,reference:r}=t;return[e,r].join(ny)}function FT(t){let[e,r,n]=t.split(ny);return{namespace:e,reference:r,address:n}}function e4(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(ny)}function UT(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function t4(t){let{address:e}=FT(t);return e}function r4(t){let{namespace:e,reference:r}=FT(t);return ZM({namespace:e,reference:r})}function Qee(t,e){let{namespace:r,reference:n}=XM(e);return e4({namespace:r,reference:n,address:t})}function Kee(t){return UT(t,t4)}function n4(t){return UT(t,r4)}function Wee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function $ee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...n4(i.accounts))}),r}function Yee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...iy(n,i))}),r}function iy(t,e){return t.includes(":")?[t]:e.chains||[]}var Jee=Object.defineProperty,pM=Object.getOwnPropertySymbols,Xee=Object.prototype.hasOwnProperty,Zee=Object.prototype.propertyIsEnumerable,mM=(t,e,r)=>e in t?Jee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yM=(t,e)=>{for(var r in e||(e={}))Xee.call(e,r)&&mM(t,r,e[r]);if(pM)for(var r of pM(e))Zee.call(e,r)&&mM(t,r,e[r]);return t},i4="ReactNative",Gr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Ym=" ",ete=":",s4="/",qT=2,tte=1e3,o4="js";function VT(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}function al(){return!il.getDocument()&&!!il.getNavigator()&&navigator.product===i4}function Hh(){return!VT()&&!!il.getNavigator()&&!!il.getDocument()}function ru(){return al()?Gr.reactNative:VT()?Gr.node:Hh()?Gr.browser:Gr.unknown}function rte(){var t;try{return al()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function a4(t,e){let r=$m.parse(t);return r=yM(yM({},r),e),t=$m.stringify(r),t}function nte(){return kee.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function ite(t,e){var r;let n=ru(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=il.getLocation())==null?void 0:r.host)||"unknown"),i}function u4(){if(ru()===Gr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=Vee.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function c4(){var t;let e=ru();return e===Gr.browser?[e,((t=il.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function l4(t,e,r){let n=u4(),i=c4();return[[t,e].join("-"),[o4,r].join("-"),n,i].join("/")}function ste({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:u}){let a=r.split("?"),c=l4(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:u||void 0},d=a4(a[1]||"",f);return a[0]+"?"+d}function ote(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function ate(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function f4(t,e=qT){return h4(t.split(s4),e)}function ute(t){return f4(t).join(Ym)}function Ho(t,e){return t.filter(r=>e.includes(r)).length===t.length}function h4(t,e=qT){return t.slice(Math.max(t.length-e,0))}function cte(t){return Object.fromEntries(t.entries())}function lte(t){return new Map(Object.entries(t))}function fte(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var hte=t=>t;function d4(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function dte(t){return t.split(Ym).map(e=>d4(e)).join(Ym)}function gte(t=el.FIVE_MINUTES,e){let r=el.toMiliseconds(t||el.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,u)=>{s=setTimeout(()=>{u(new Error(e))},r),n=o,i=u})}}function pte(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function kT(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function mte(t){return kT("topic",t)}function yte(t){return kT("id",t)}function wte(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function vte(t,e){return el.fromMiliseconds((e||Date.now())+el.toMiliseconds(t))}function Ate(t){return Date.now()>=el.toMiliseconds(t)}function Ete(t,e){return`${t}${e?`:${e}`:""}`}function Js(t=[],e=[]){return[...new Set([...t,...e])]}async function bte({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=ru();o===Gr.browser?s.startsWith("https://")||s.startsWith("http://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===Gr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function Ste(t,e){try{return await t.getItem(e)||(Hh()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}function TT(t,e){return t.filter(r=>e.includes(r))}var g4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ite(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var p4={exports:{}};(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!i.JS_SHA3_NO_NODE_JS&&typeof I.default=="object"&&I.default.versions&&I.default.versions.node;o?i=g4:s&&(i=self);var u=!i.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),f=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],w=[1,256,65536,16777216],A=[6,1536,393216,100663296],T=[0,8,16,24],x=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],R=[224,256,384,512],V=[128,256],U=["hex","buffer","arrayBuffer","array","digest"],Q={128:168,256:136};(i.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(b){return Object.prototype.toString.call(b)==="[object Array]"}),a&&(i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(b){return typeof b=="object"&&b.buffer&&b.buffer.constructor===ArrayBuffer});for(var L=function(b,j,z){return function(W){return new O(b,j,b).update(W)[z]()}},k=function(b,j,z){return function(W,ie){return new O(b,j,ie).update(W)[z]()}},H=function(b,j,z){return function(W,ie,te,ee){return g["cshake"+b].update(W,ie,te,ee)[z]()}},q=function(b,j,z){return function(W,ie,te,ee){return g["kmac"+b].update(W,ie,te,ee)[z]()}},v=function(b,j,z,W){for(var ie=0;ie>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var W=0;W<50;++W)this.s[W]=0}O.prototype.update=function(b){if(this.finalized)throw new Error(r);var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}for(var W=this.blocks,ie=this.byteCount,te=b.length,ee=this.blockCount,se=0,oe=this.s,J,ue;se>2]|=b[se]<>2]|=ue<>2]|=(192|ue>>6)<>2]|=(128|ue&63)<=57344?(W[J>>2]|=(224|ue>>12)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<>2]|=(240|ue>>18)<>2]|=(128|ue>>12&63)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<=ie){for(this.start=J-ie,this.block=W[ee],J=0;J>8,z=b&255;z>0;)ie.unshift(z),b=b>>8,z=b&255,++W;return j?ie.push(W):ie.unshift(W),this.update(ie),ie.length},O.prototype.encodeString=function(b){var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}var W=0,ie=b.length;if(j)W=ie;else for(var te=0;te=57344?W+=3:(ee=65536+((ee&1023)<<10|b.charCodeAt(++te)&1023),W+=4)}return W+=this.encode(W*8),this.update(b),W},O.prototype.bytepad=function(b,j){for(var z=this.encode(j),W=0;W>2]|=this.padding[j&3],this.lastByteIndex===this.byteCount)for(b[0]=b[z],j=1;j>4&15]+c[se&15]+c[se>>12&15]+c[se>>8&15]+c[se>>20&15]+c[se>>16&15]+c[se>>28&15]+c[se>>24&15];te%b===0&&($(j),ie=0)}return W&&(se=j[ie],ee+=c[se>>4&15]+c[se&15],W>1&&(ee+=c[se>>12&15]+c[se>>8&15]),W>2&&(ee+=c[se>>20&15]+c[se>>16&15])),ee},O.prototype.arrayBuffer=function(){this.finalize();var b=this.blockCount,j=this.s,z=this.outputBlocks,W=this.extraBytes,ie=0,te=0,ee=this.outputBits>>3,se;W?se=new ArrayBuffer(z+1<<2):se=new ArrayBuffer(ee);for(var oe=new Uint32Array(se);te>8&255,ee[se+2]=oe>>16&255,ee[se+3]=oe>>24&255;te%b===0&&$(j)}return W&&(se=te<<2,oe=j[ie],ee[se]=oe&255,W>1&&(ee[se+1]=oe>>8&255),W>2&&(ee[se+2]=oe>>16&255)),ee};function Y(b,j,z){O.call(this,b,j,z)}Y.prototype=new O,Y.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var $=function(b){var j,z,W,ie,te,ee,se,oe,J,ue,wt,vt,Ni,At,Et,xi,bt,St,Oi,It,Tt,Di,Qe,Ke,ri,We,$e,ni,Ye,Je,ii,Xe,Ze,si,et,tt,oi,rt,nt,ai,it,st,ui,ot,at,ci,ut,ct,li,lt,ft,fi,ht,dt,hi,gt,pt,vn,An,En,bn,Sn,In;for(W=0;W<48;W+=2)ie=b[0]^b[10]^b[20]^b[30]^b[40],te=b[1]^b[11]^b[21]^b[31]^b[41],ee=b[2]^b[12]^b[22]^b[32]^b[42],se=b[3]^b[13]^b[23]^b[33]^b[43],oe=b[4]^b[14]^b[24]^b[34]^b[44],J=b[5]^b[15]^b[25]^b[35]^b[45],ue=b[6]^b[16]^b[26]^b[36]^b[46],wt=b[7]^b[17]^b[27]^b[37]^b[47],vt=b[8]^b[18]^b[28]^b[38]^b[48],Ni=b[9]^b[19]^b[29]^b[39]^b[49],j=vt^(ee<<1|se>>>31),z=Ni^(se<<1|ee>>>31),b[0]^=j,b[1]^=z,b[10]^=j,b[11]^=z,b[20]^=j,b[21]^=z,b[30]^=j,b[31]^=z,b[40]^=j,b[41]^=z,j=ie^(oe<<1|J>>>31),z=te^(J<<1|oe>>>31),b[2]^=j,b[3]^=z,b[12]^=j,b[13]^=z,b[22]^=j,b[23]^=z,b[32]^=j,b[33]^=z,b[42]^=j,b[43]^=z,j=ee^(ue<<1|wt>>>31),z=se^(wt<<1|ue>>>31),b[4]^=j,b[5]^=z,b[14]^=j,b[15]^=z,b[24]^=j,b[25]^=z,b[34]^=j,b[35]^=z,b[44]^=j,b[45]^=z,j=oe^(vt<<1|Ni>>>31),z=J^(Ni<<1|vt>>>31),b[6]^=j,b[7]^=z,b[16]^=j,b[17]^=z,b[26]^=j,b[27]^=z,b[36]^=j,b[37]^=z,b[46]^=j,b[47]^=z,j=ue^(ie<<1|te>>>31),z=wt^(te<<1|ie>>>31),b[8]^=j,b[9]^=z,b[18]^=j,b[19]^=z,b[28]^=j,b[29]^=z,b[38]^=j,b[39]^=z,b[48]^=j,b[49]^=z,At=b[0],Et=b[1],ci=b[11]<<4|b[10]>>>28,ut=b[10]<<4|b[11]>>>28,ni=b[20]<<3|b[21]>>>29,Ye=b[21]<<3|b[20]>>>29,En=b[31]<<9|b[30]>>>23,bn=b[30]<<9|b[31]>>>23,st=b[40]<<18|b[41]>>>14,ui=b[41]<<18|b[40]>>>14,si=b[2]<<1|b[3]>>>31,et=b[3]<<1|b[2]>>>31,xi=b[13]<<12|b[12]>>>20,bt=b[12]<<12|b[13]>>>20,ct=b[22]<<10|b[23]>>>22,li=b[23]<<10|b[22]>>>22,Je=b[33]<<13|b[32]>>>19,ii=b[32]<<13|b[33]>>>19,Sn=b[42]<<2|b[43]>>>30,In=b[43]<<2|b[42]>>>30,dt=b[5]<<30|b[4]>>>2,hi=b[4]<<30|b[5]>>>2,tt=b[14]<<6|b[15]>>>26,oi=b[15]<<6|b[14]>>>26,St=b[25]<<11|b[24]>>>21,Oi=b[24]<<11|b[25]>>>21,lt=b[34]<<15|b[35]>>>17,ft=b[35]<<15|b[34]>>>17,Xe=b[45]<<29|b[44]>>>3,Ze=b[44]<<29|b[45]>>>3,Ke=b[6]<<28|b[7]>>>4,ri=b[7]<<28|b[6]>>>4,gt=b[17]<<23|b[16]>>>9,pt=b[16]<<23|b[17]>>>9,rt=b[26]<<25|b[27]>>>7,nt=b[27]<<25|b[26]>>>7,It=b[36]<<21|b[37]>>>11,Tt=b[37]<<21|b[36]>>>11,fi=b[47]<<24|b[46]>>>8,ht=b[46]<<24|b[47]>>>8,ot=b[8]<<27|b[9]>>>5,at=b[9]<<27|b[8]>>>5,We=b[18]<<20|b[19]>>>12,$e=b[19]<<20|b[18]>>>12,vn=b[29]<<7|b[28]>>>25,An=b[28]<<7|b[29]>>>25,ai=b[38]<<8|b[39]>>>24,it=b[39]<<8|b[38]>>>24,Di=b[48]<<14|b[49]>>>18,Qe=b[49]<<14|b[48]>>>18,b[0]=At^~xi&St,b[1]=Et^~bt&Oi,b[10]=Ke^~We&ni,b[11]=ri^~$e&Ye,b[20]=si^~tt&rt,b[21]=et^~oi&nt,b[30]=ot^~ci&ct,b[31]=at^~ut&li,b[40]=dt^~gt&vn,b[41]=hi^~pt&An,b[2]=xi^~St&It,b[3]=bt^~Oi&Tt,b[12]=We^~ni&Je,b[13]=$e^~Ye&ii,b[22]=tt^~rt&ai,b[23]=oi^~nt&it,b[32]=ci^~ct<,b[33]=ut^~li&ft,b[42]=gt^~vn&En,b[43]=pt^~An&bn,b[4]=St^~It&Di,b[5]=Oi^~Tt&Qe,b[14]=ni^~Je&Xe,b[15]=Ye^~ii&Ze,b[24]=rt^~ai&st,b[25]=nt^~it&ui,b[34]=ct^~lt&fi,b[35]=li^~ft&ht,b[44]=vn^~En&Sn,b[45]=An^~bn&In,b[6]=It^~Di&At,b[7]=Tt^~Qe&Et,b[16]=Je^~Xe&Ke,b[17]=ii^~Ze&ri,b[26]=ai^~st&si,b[27]=it^~ui&et,b[36]=lt^~fi&ot,b[37]=ft^~ht&at,b[46]=En^~Sn&dt,b[47]=bn^~In&hi,b[8]=Di^~At&xi,b[9]=Qe^~Et&bt,b[18]=Xe^~Ke&We,b[19]=Ze^~ri&$e,b[28]=st^~si&tt,b[29]=ui^~et&oi,b[38]=fi^~ot&ci,b[39]=ht^~at&ut,b[48]=Sn^~dt>,b[49]=In^~hi&pt,b[0]^=x[W],b[1]^=x[W+1]};if(u)t.exports=g;else for(E=0;E{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken implementation")}catch(t){return t.message}return null}var EM=Cte(),_T;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(_T||(_T={}));var Si;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Si||(Si={}));var bM="0123456789abcdef",kt=class t{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){let n=e.toLowerCase();Qm[n]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(AM>Qm[n])&&console.log.apply(console,r)}debug(...e){this._log(t.levels.DEBUG,e)}info(...e){this._log(t.levels.INFO,e)}warn(...e){this._log(t.levels.WARNING,e)}makeError(e,r,n){if(vM)return this.makeError("censored error",r,{});r||(r=t.errors.UNKNOWN_ERROR),n||(n={});let i=[];Object.keys(n).forEach(a=>{let c=n[a];try{if(c instanceof Uint8Array){let f="";for(let d=0;d>4],f+=bM[c[d]&15];i.push(a+"=Uint8Array(0x"+f+")")}else i.push(a+"="+JSON.stringify(c))}catch{i.push(a+"="+JSON.stringify(n[a].toString()))}}),i.push(`code=${r}`),i.push(`version=${this.version}`);let s=e,o="";switch(r){case Si.NUMERIC_FAULT:{o="NUMERIC_FAULT";let a=e;switch(a){case"overflow":case"underflow":case"division-by-zero":o+="-"+a;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Si.CALL_EXCEPTION:case Si.INSUFFICIENT_FUNDS:case Si.MISSING_NEW:case Si.NONCE_EXPIRED:case Si.REPLACEMENT_UNDERPRICED:case Si.TRANSACTION_REPLACED:case Si.UNPREDICTABLE_GAS_LIMIT:o=r;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),i.length&&(e+=" ("+i.join(", ")+")");let u=new Error(e);return u.reason=s,u.code=r,Object.keys(n).forEach(function(a){u[a]=n[a]}),u}throwError(e,r,n){throw this.makeError(e,r,n)}throwArgumentError(e,r,n){return this.throwError(e,t.errors.INVALID_ARGUMENT,{argument:r,value:n})}assert(e,r,n,i){e||this.throwError(r,n,i)}assertArgument(e,r,n,i){e||this.throwArgumentError(r,n,i)}checkNormalize(e){EM&&this.throwError("platform missing String.prototype.normalize",t.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:EM})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,n){n?n=": "+n:n="",er&&this.throwError("too many arguments"+n,t.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",t.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return lT||(lT=new t(_te)),lT}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),wM){if(!e)return;this.globalLogger().throwError("error censorship permanent",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}vM=!!e,wM=!!r}static setLogLevel(e){let r=Qm[e.toLowerCase()];if(r==null){t.globalLogger().warn("invalid log level - "+e);return}AM=r}static from(e){return new t(e)}};kt.errors=Si,kt.levels=_T;var Nte="bytes/5.7.0",er=new kt(Nte);function m4(t){return!!t.toHexString}function tl(t){return t.slice||(t.slice=function(){let e=Array.prototype.slice.call(arguments);return tl(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function xte(t){return gn(t)&&!(t.length%2)||ul(t)}function SM(t){return typeof t=="number"&&t==t&&t%1===0}function ul(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!SM(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function Qt(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid arrayify value");let r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),tl(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t)&&(t=t.toHexString()),gn(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":er.throwArgumentError("hex data is odd-length","value",t));let n=[];for(let i=0;iQt(i)),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);return e.reduce((i,s)=>(n.set(s,i),i+s.length),0),tl(n)}function Dte(t,e){t=Qt(t),t.length>e&&er.throwArgumentError("value out of range","value",arguments[0]);let r=new Uint8Array(e);return r.set(t,e-t.length),tl(r)}function gn(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}var fT="0123456789abcdef";function kr(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=fT[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t))return t.toHexString();if(gn(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":er.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(ul(t)){let r="0x";for(let n=0;n>4]+fT[i&15]}return r}return er.throwArgumentError("invalid hexlify value","value",t)}function Pte(t){if(typeof t!="string")t=kr(t);else if(!gn(t)||t.length%2)return null;return(t.length-2)/2}function IM(t,e,r){return typeof t!="string"?t=kr(t):(!gn(t)||t.length%2)&&er.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function fs(t,e){for(typeof t!="string"?t=kr(t):gn(t)||er.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&er.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function y4(t){let e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(xte(t)){let r=Qt(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64))):r.length===65?(e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64)),e.v=r[64]):er.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:er.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=kr(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){let i=Dte(Qt(e._vs),32);e._vs=kr(i);let s=i[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&er.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),i[0]&=127;let o=kr(i);e.s==null?e.s=o:e.s!==o&&er.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?er.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{let i=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==i&&er.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!gn(e.r)?er.throwArgumentError("signature missing or invalid r","signature",t):e.r=fs(e.r,32),e.s==null||!gn(e.s)?er.throwArgumentError("signature missing or invalid s","signature",t):e.s=fs(e.s,32);let r=Qt(e.s);r[0]>=128&&er.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);let n=kr(r);e._vs&&(gn(e._vs)||er.throwArgumentError("signature invalid _vs","signature",t),e._vs=fs(e._vs,32)),e._vs==null?e._vs=n:e._vs!==n&&er.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function HT(t){return"0x"+Tte.keccak_256(Qt(t))}var w4={exports:{}},Rte={},Bte=Object.freeze({__proto__:null,default:Rte}),Mte=Ite(Bte);(function(t){(function(e,r){function n(l,g){if(!l)throw new Error(g||"Assertion failed")}function i(l,g){l.super_=g;var y=function(){};y.prototype=g.prototype,l.prototype=new y,l.prototype.constructor=l}function s(l,g,y){if(s.isBN(l))return l;this.negative=0,this.words=null,this.length=0,this.red=null,l!==null&&((g==="le"||g==="be")&&(y=g,g=10),this._init(l||0,g||10,y||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Mte.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,g){return l.cmp(g)>0?l:g},s.min=function(l,g){return l.cmp(g)<0?l:g},s.prototype._init=function(l,g,y){if(typeof l=="number")return this._initNumber(l,g,y);if(typeof l=="object")return this._initArray(l,g,y);g==="hex"&&(g=16),n(g===(g|0)&&g>=2&&g<=36),l=l.toString().replace(/\s+/g,"");var E=0;l[0]==="-"&&(E++,this.negative=1),E=0;E-=3)_=l[E]|l[E-1]<<8|l[E-2]<<16,this.words[S]|=_<>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);else if(y==="le")for(E=0,S=0;E>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);return this._strip()};function u(l,g){var y=l.charCodeAt(g);if(y>=48&&y<=57)return y-48;if(y>=65&&y<=70)return y-55;if(y>=97&&y<=102)return y-87;n(!1,"Invalid character in "+l)}function a(l,g,y){var E=u(l,y);return y-1>=g&&(E|=u(l,y-1)<<4),E}s.prototype._parseHex=function(l,g,y){this.length=Math.ceil((l.length-g)/6),this.words=new Array(this.length);for(var E=0;E=g;E-=2)M=a(l,g,E)<=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8;else{var N=l.length-g;for(E=N%2===0?g+1:g;E=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8}this._strip()};function c(l,g,y,E){for(var S=0,_=0,M=Math.min(l.length,y),N=g;N=49?_=m-49+10:m>=17?_=m-17+10:_=m,n(m>=0&&_1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch{s.prototype.inspect=d}else s.prototype.inspect=d;function d(){return(this.red?""}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],A=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(l,g){l=l||10,g=g|0||1;var y;if(l===16||l==="hex"){y="";for(var E=0,S=0,_=0;_>>24-E&16777215,E+=2,E>=26&&(E-=26,_--),S!==0||_!==this.length-1?y=w[6-N.length]+N+y:y=N+y}for(S!==0&&(y=S.toString(16)+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var m=A[l],O=T[l];y="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var $=Y.modrn(O).toString(l);Y=Y.idivn(O),Y.isZero()?y=$+y:y=w[m-$.length]+$+y}for(this.isZero()&&(y="0"+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(l,g){return this.toArrayLike(o,l,g)}),s.prototype.toArray=function(l,g){return this.toArrayLike(Array,l,g)};var x=function(l,g){return l.allocUnsafe?l.allocUnsafe(g):new l(g)};s.prototype.toArrayLike=function(l,g,y){this._strip();var E=this.byteLength(),S=y||Math.max(1,E);n(E<=S,"byte array longer than desired length"),n(S>0,"Requested array length <= 0");var _=x(l,S),M=g==="le"?"LE":"BE";return this["_toArrayLike"+M](_,E),_},s.prototype._toArrayLikeLE=function(l,g){for(var y=0,E=0,S=0,_=0;S>8&255),y>16&255),_===6?(y>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y=0&&(l[y--]=M>>8&255),y>=0&&(l[y--]=M>>16&255),_===6?(y>=0&&(l[y--]=M>>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y>=0)for(l[y--]=E;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var g=l,y=0;return g>=4096&&(y+=13,g>>>=13),g>=64&&(y+=7,g>>>=7),g>=8&&(y+=4,g>>>=4),g>=2&&(y+=2,g>>>=2),y+g},s.prototype._zeroBits=function(l){if(l===0)return 26;var g=l,y=0;return g&8191||(y+=13,g>>>=13),g&127||(y+=7,g>>>=7),g&15||(y+=4,g>>>=4),g&3||(y+=2,g>>>=2),g&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],g=this._countBits(l);return(this.length-1)*26+g};function R(l){for(var g=new Array(l.bitLength()),y=0;y>>S&1}return g}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,g=0;gl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var g;this.length>l.length?g=l:g=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var g,y;this.length>l.length?(g=this,y=l):(g=l,y=this);for(var E=0;El.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var g=Math.ceil(l/26)|0,y=l%26;this._expand(g),y>0&&g--;for(var E=0;E0&&(this.words[E]=~this.words[E]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,g){n(typeof l=="number"&&l>=0);var y=l/26|0,E=l%26;return this._expand(y+1),g?this.words[y]=this.words[y]|1<l.length?(y=this,E=l):(y=l,E=this);for(var S=0,_=0;_>>26;for(;S!==0&&_>>26;if(this.length=y.length,S!==0)this.words[this.length]=S,this.length++;else if(y!==this)for(;_l.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var g=this.iadd(l);return l.negative=1,g._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,S;y>0?(E=this,S=l):(E=l,S=this);for(var _=0,M=0;M>26,this.words[M]=g&67108863;for(;_!==0&&M>26,this.words[M]=g&67108863;if(_===0&&M>>26,$=m&67108863,b=Math.min(O,g.length-1),j=Math.max(0,O-l.length+1);j<=b;j++){var z=O-j|0;S=l.words[z]|0,_=g.words[j]|0,M=S*_+$,Y+=M/67108864|0,$=M&67108863}y.words[O]=$|0,m=Y|0}return m!==0?y.words[O]=m|0:y.length--,y._strip()}var U=function(l,g,y){var E=l.words,S=g.words,_=y.words,M=0,N,m,O,Y=E[0]|0,$=Y&8191,b=Y>>>13,j=E[1]|0,z=j&8191,W=j>>>13,ie=E[2]|0,te=ie&8191,ee=ie>>>13,se=E[3]|0,oe=se&8191,J=se>>>13,ue=E[4]|0,wt=ue&8191,vt=ue>>>13,Ni=E[5]|0,At=Ni&8191,Et=Ni>>>13,xi=E[6]|0,bt=xi&8191,St=xi>>>13,Oi=E[7]|0,It=Oi&8191,Tt=Oi>>>13,Di=E[8]|0,Qe=Di&8191,Ke=Di>>>13,ri=E[9]|0,We=ri&8191,$e=ri>>>13,ni=S[0]|0,Ye=ni&8191,Je=ni>>>13,ii=S[1]|0,Xe=ii&8191,Ze=ii>>>13,si=S[2]|0,et=si&8191,tt=si>>>13,oi=S[3]|0,rt=oi&8191,nt=oi>>>13,ai=S[4]|0,it=ai&8191,st=ai>>>13,ui=S[5]|0,ot=ui&8191,at=ui>>>13,ci=S[6]|0,ut=ci&8191,ct=ci>>>13,li=S[7]|0,lt=li&8191,ft=li>>>13,fi=S[8]|0,ht=fi&8191,dt=fi>>>13,hi=S[9]|0,gt=hi&8191,pt=hi>>>13;y.negative=l.negative^g.negative,y.length=19,N=Math.imul($,Ye),m=Math.imul($,Je),m=m+Math.imul(b,Ye)|0,O=Math.imul(b,Je);var vn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(vn>>>26)|0,vn&=67108863,N=Math.imul(z,Ye),m=Math.imul(z,Je),m=m+Math.imul(W,Ye)|0,O=Math.imul(W,Je),N=N+Math.imul($,Xe)|0,m=m+Math.imul($,Ze)|0,m=m+Math.imul(b,Xe)|0,O=O+Math.imul(b,Ze)|0;var An=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(An>>>26)|0,An&=67108863,N=Math.imul(te,Ye),m=Math.imul(te,Je),m=m+Math.imul(ee,Ye)|0,O=Math.imul(ee,Je),N=N+Math.imul(z,Xe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(W,Xe)|0,O=O+Math.imul(W,Ze)|0,N=N+Math.imul($,et)|0,m=m+Math.imul($,tt)|0,m=m+Math.imul(b,et)|0,O=O+Math.imul(b,tt)|0;var En=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(En>>>26)|0,En&=67108863,N=Math.imul(oe,Ye),m=Math.imul(oe,Je),m=m+Math.imul(J,Ye)|0,O=Math.imul(J,Je),N=N+Math.imul(te,Xe)|0,m=m+Math.imul(te,Ze)|0,m=m+Math.imul(ee,Xe)|0,O=O+Math.imul(ee,Ze)|0,N=N+Math.imul(z,et)|0,m=m+Math.imul(z,tt)|0,m=m+Math.imul(W,et)|0,O=O+Math.imul(W,tt)|0,N=N+Math.imul($,rt)|0,m=m+Math.imul($,nt)|0,m=m+Math.imul(b,rt)|0,O=O+Math.imul(b,nt)|0;var bn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(bn>>>26)|0,bn&=67108863,N=Math.imul(wt,Ye),m=Math.imul(wt,Je),m=m+Math.imul(vt,Ye)|0,O=Math.imul(vt,Je),N=N+Math.imul(oe,Xe)|0,m=m+Math.imul(oe,Ze)|0,m=m+Math.imul(J,Xe)|0,O=O+Math.imul(J,Ze)|0,N=N+Math.imul(te,et)|0,m=m+Math.imul(te,tt)|0,m=m+Math.imul(ee,et)|0,O=O+Math.imul(ee,tt)|0,N=N+Math.imul(z,rt)|0,m=m+Math.imul(z,nt)|0,m=m+Math.imul(W,rt)|0,O=O+Math.imul(W,nt)|0,N=N+Math.imul($,it)|0,m=m+Math.imul($,st)|0,m=m+Math.imul(b,it)|0,O=O+Math.imul(b,st)|0;var Sn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Sn>>>26)|0,Sn&=67108863,N=Math.imul(At,Ye),m=Math.imul(At,Je),m=m+Math.imul(Et,Ye)|0,O=Math.imul(Et,Je),N=N+Math.imul(wt,Xe)|0,m=m+Math.imul(wt,Ze)|0,m=m+Math.imul(vt,Xe)|0,O=O+Math.imul(vt,Ze)|0,N=N+Math.imul(oe,et)|0,m=m+Math.imul(oe,tt)|0,m=m+Math.imul(J,et)|0,O=O+Math.imul(J,tt)|0,N=N+Math.imul(te,rt)|0,m=m+Math.imul(te,nt)|0,m=m+Math.imul(ee,rt)|0,O=O+Math.imul(ee,nt)|0,N=N+Math.imul(z,it)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(W,it)|0,O=O+Math.imul(W,st)|0,N=N+Math.imul($,ot)|0,m=m+Math.imul($,at)|0,m=m+Math.imul(b,ot)|0,O=O+Math.imul(b,at)|0;var In=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(In>>>26)|0,In&=67108863,N=Math.imul(bt,Ye),m=Math.imul(bt,Je),m=m+Math.imul(St,Ye)|0,O=Math.imul(St,Je),N=N+Math.imul(At,Xe)|0,m=m+Math.imul(At,Ze)|0,m=m+Math.imul(Et,Xe)|0,O=O+Math.imul(Et,Ze)|0,N=N+Math.imul(wt,et)|0,m=m+Math.imul(wt,tt)|0,m=m+Math.imul(vt,et)|0,O=O+Math.imul(vt,tt)|0,N=N+Math.imul(oe,rt)|0,m=m+Math.imul(oe,nt)|0,m=m+Math.imul(J,rt)|0,O=O+Math.imul(J,nt)|0,N=N+Math.imul(te,it)|0,m=m+Math.imul(te,st)|0,m=m+Math.imul(ee,it)|0,O=O+Math.imul(ee,st)|0,N=N+Math.imul(z,ot)|0,m=m+Math.imul(z,at)|0,m=m+Math.imul(W,ot)|0,O=O+Math.imul(W,at)|0,N=N+Math.imul($,ut)|0,m=m+Math.imul($,ct)|0,m=m+Math.imul(b,ut)|0,O=O+Math.imul(b,ct)|0;var da=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(da>>>26)|0,da&=67108863,N=Math.imul(It,Ye),m=Math.imul(It,Je),m=m+Math.imul(Tt,Ye)|0,O=Math.imul(Tt,Je),N=N+Math.imul(bt,Xe)|0,m=m+Math.imul(bt,Ze)|0,m=m+Math.imul(St,Xe)|0,O=O+Math.imul(St,Ze)|0,N=N+Math.imul(At,et)|0,m=m+Math.imul(At,tt)|0,m=m+Math.imul(Et,et)|0,O=O+Math.imul(Et,tt)|0,N=N+Math.imul(wt,rt)|0,m=m+Math.imul(wt,nt)|0,m=m+Math.imul(vt,rt)|0,O=O+Math.imul(vt,nt)|0,N=N+Math.imul(oe,it)|0,m=m+Math.imul(oe,st)|0,m=m+Math.imul(J,it)|0,O=O+Math.imul(J,st)|0,N=N+Math.imul(te,ot)|0,m=m+Math.imul(te,at)|0,m=m+Math.imul(ee,ot)|0,O=O+Math.imul(ee,at)|0,N=N+Math.imul(z,ut)|0,m=m+Math.imul(z,ct)|0,m=m+Math.imul(W,ut)|0,O=O+Math.imul(W,ct)|0,N=N+Math.imul($,lt)|0,m=m+Math.imul($,ft)|0,m=m+Math.imul(b,lt)|0,O=O+Math.imul(b,ft)|0;var ga=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ga>>>26)|0,ga&=67108863,N=Math.imul(Qe,Ye),m=Math.imul(Qe,Je),m=m+Math.imul(Ke,Ye)|0,O=Math.imul(Ke,Je),N=N+Math.imul(It,Xe)|0,m=m+Math.imul(It,Ze)|0,m=m+Math.imul(Tt,Xe)|0,O=O+Math.imul(Tt,Ze)|0,N=N+Math.imul(bt,et)|0,m=m+Math.imul(bt,tt)|0,m=m+Math.imul(St,et)|0,O=O+Math.imul(St,tt)|0,N=N+Math.imul(At,rt)|0,m=m+Math.imul(At,nt)|0,m=m+Math.imul(Et,rt)|0,O=O+Math.imul(Et,nt)|0,N=N+Math.imul(wt,it)|0,m=m+Math.imul(wt,st)|0,m=m+Math.imul(vt,it)|0,O=O+Math.imul(vt,st)|0,N=N+Math.imul(oe,ot)|0,m=m+Math.imul(oe,at)|0,m=m+Math.imul(J,ot)|0,O=O+Math.imul(J,at)|0,N=N+Math.imul(te,ut)|0,m=m+Math.imul(te,ct)|0,m=m+Math.imul(ee,ut)|0,O=O+Math.imul(ee,ct)|0,N=N+Math.imul(z,lt)|0,m=m+Math.imul(z,ft)|0,m=m+Math.imul(W,lt)|0,O=O+Math.imul(W,ft)|0,N=N+Math.imul($,ht)|0,m=m+Math.imul($,dt)|0,m=m+Math.imul(b,ht)|0,O=O+Math.imul(b,dt)|0;var pa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pa>>>26)|0,pa&=67108863,N=Math.imul(We,Ye),m=Math.imul(We,Je),m=m+Math.imul($e,Ye)|0,O=Math.imul($e,Je),N=N+Math.imul(Qe,Xe)|0,m=m+Math.imul(Qe,Ze)|0,m=m+Math.imul(Ke,Xe)|0,O=O+Math.imul(Ke,Ze)|0,N=N+Math.imul(It,et)|0,m=m+Math.imul(It,tt)|0,m=m+Math.imul(Tt,et)|0,O=O+Math.imul(Tt,tt)|0,N=N+Math.imul(bt,rt)|0,m=m+Math.imul(bt,nt)|0,m=m+Math.imul(St,rt)|0,O=O+Math.imul(St,nt)|0,N=N+Math.imul(At,it)|0,m=m+Math.imul(At,st)|0,m=m+Math.imul(Et,it)|0,O=O+Math.imul(Et,st)|0,N=N+Math.imul(wt,ot)|0,m=m+Math.imul(wt,at)|0,m=m+Math.imul(vt,ot)|0,O=O+Math.imul(vt,at)|0,N=N+Math.imul(oe,ut)|0,m=m+Math.imul(oe,ct)|0,m=m+Math.imul(J,ut)|0,O=O+Math.imul(J,ct)|0,N=N+Math.imul(te,lt)|0,m=m+Math.imul(te,ft)|0,m=m+Math.imul(ee,lt)|0,O=O+Math.imul(ee,ft)|0,N=N+Math.imul(z,ht)|0,m=m+Math.imul(z,dt)|0,m=m+Math.imul(W,ht)|0,O=O+Math.imul(W,dt)|0,N=N+Math.imul($,gt)|0,m=m+Math.imul($,pt)|0,m=m+Math.imul(b,gt)|0,O=O+Math.imul(b,pt)|0;var ma=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ma>>>26)|0,ma&=67108863,N=Math.imul(We,Xe),m=Math.imul(We,Ze),m=m+Math.imul($e,Xe)|0,O=Math.imul($e,Ze),N=N+Math.imul(Qe,et)|0,m=m+Math.imul(Qe,tt)|0,m=m+Math.imul(Ke,et)|0,O=O+Math.imul(Ke,tt)|0,N=N+Math.imul(It,rt)|0,m=m+Math.imul(It,nt)|0,m=m+Math.imul(Tt,rt)|0,O=O+Math.imul(Tt,nt)|0,N=N+Math.imul(bt,it)|0,m=m+Math.imul(bt,st)|0,m=m+Math.imul(St,it)|0,O=O+Math.imul(St,st)|0,N=N+Math.imul(At,ot)|0,m=m+Math.imul(At,at)|0,m=m+Math.imul(Et,ot)|0,O=O+Math.imul(Et,at)|0,N=N+Math.imul(wt,ut)|0,m=m+Math.imul(wt,ct)|0,m=m+Math.imul(vt,ut)|0,O=O+Math.imul(vt,ct)|0,N=N+Math.imul(oe,lt)|0,m=m+Math.imul(oe,ft)|0,m=m+Math.imul(J,lt)|0,O=O+Math.imul(J,ft)|0,N=N+Math.imul(te,ht)|0,m=m+Math.imul(te,dt)|0,m=m+Math.imul(ee,ht)|0,O=O+Math.imul(ee,dt)|0,N=N+Math.imul(z,gt)|0,m=m+Math.imul(z,pt)|0,m=m+Math.imul(W,gt)|0,O=O+Math.imul(W,pt)|0;var ya=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ya>>>26)|0,ya&=67108863,N=Math.imul(We,et),m=Math.imul(We,tt),m=m+Math.imul($e,et)|0,O=Math.imul($e,tt),N=N+Math.imul(Qe,rt)|0,m=m+Math.imul(Qe,nt)|0,m=m+Math.imul(Ke,rt)|0,O=O+Math.imul(Ke,nt)|0,N=N+Math.imul(It,it)|0,m=m+Math.imul(It,st)|0,m=m+Math.imul(Tt,it)|0,O=O+Math.imul(Tt,st)|0,N=N+Math.imul(bt,ot)|0,m=m+Math.imul(bt,at)|0,m=m+Math.imul(St,ot)|0,O=O+Math.imul(St,at)|0,N=N+Math.imul(At,ut)|0,m=m+Math.imul(At,ct)|0,m=m+Math.imul(Et,ut)|0,O=O+Math.imul(Et,ct)|0,N=N+Math.imul(wt,lt)|0,m=m+Math.imul(wt,ft)|0,m=m+Math.imul(vt,lt)|0,O=O+Math.imul(vt,ft)|0,N=N+Math.imul(oe,ht)|0,m=m+Math.imul(oe,dt)|0,m=m+Math.imul(J,ht)|0,O=O+Math.imul(J,dt)|0,N=N+Math.imul(te,gt)|0,m=m+Math.imul(te,pt)|0,m=m+Math.imul(ee,gt)|0,O=O+Math.imul(ee,pt)|0;var wa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(wa>>>26)|0,wa&=67108863,N=Math.imul(We,rt),m=Math.imul(We,nt),m=m+Math.imul($e,rt)|0,O=Math.imul($e,nt),N=N+Math.imul(Qe,it)|0,m=m+Math.imul(Qe,st)|0,m=m+Math.imul(Ke,it)|0,O=O+Math.imul(Ke,st)|0,N=N+Math.imul(It,ot)|0,m=m+Math.imul(It,at)|0,m=m+Math.imul(Tt,ot)|0,O=O+Math.imul(Tt,at)|0,N=N+Math.imul(bt,ut)|0,m=m+Math.imul(bt,ct)|0,m=m+Math.imul(St,ut)|0,O=O+Math.imul(St,ct)|0,N=N+Math.imul(At,lt)|0,m=m+Math.imul(At,ft)|0,m=m+Math.imul(Et,lt)|0,O=O+Math.imul(Et,ft)|0,N=N+Math.imul(wt,ht)|0,m=m+Math.imul(wt,dt)|0,m=m+Math.imul(vt,ht)|0,O=O+Math.imul(vt,dt)|0,N=N+Math.imul(oe,gt)|0,m=m+Math.imul(oe,pt)|0,m=m+Math.imul(J,gt)|0,O=O+Math.imul(J,pt)|0;var va=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(va>>>26)|0,va&=67108863,N=Math.imul(We,it),m=Math.imul(We,st),m=m+Math.imul($e,it)|0,O=Math.imul($e,st),N=N+Math.imul(Qe,ot)|0,m=m+Math.imul(Qe,at)|0,m=m+Math.imul(Ke,ot)|0,O=O+Math.imul(Ke,at)|0,N=N+Math.imul(It,ut)|0,m=m+Math.imul(It,ct)|0,m=m+Math.imul(Tt,ut)|0,O=O+Math.imul(Tt,ct)|0,N=N+Math.imul(bt,lt)|0,m=m+Math.imul(bt,ft)|0,m=m+Math.imul(St,lt)|0,O=O+Math.imul(St,ft)|0,N=N+Math.imul(At,ht)|0,m=m+Math.imul(At,dt)|0,m=m+Math.imul(Et,ht)|0,O=O+Math.imul(Et,dt)|0,N=N+Math.imul(wt,gt)|0,m=m+Math.imul(wt,pt)|0,m=m+Math.imul(vt,gt)|0,O=O+Math.imul(vt,pt)|0;var Aa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,N=Math.imul(We,ot),m=Math.imul(We,at),m=m+Math.imul($e,ot)|0,O=Math.imul($e,at),N=N+Math.imul(Qe,ut)|0,m=m+Math.imul(Qe,ct)|0,m=m+Math.imul(Ke,ut)|0,O=O+Math.imul(Ke,ct)|0,N=N+Math.imul(It,lt)|0,m=m+Math.imul(It,ft)|0,m=m+Math.imul(Tt,lt)|0,O=O+Math.imul(Tt,ft)|0,N=N+Math.imul(bt,ht)|0,m=m+Math.imul(bt,dt)|0,m=m+Math.imul(St,ht)|0,O=O+Math.imul(St,dt)|0,N=N+Math.imul(At,gt)|0,m=m+Math.imul(At,pt)|0,m=m+Math.imul(Et,gt)|0,O=O+Math.imul(Et,pt)|0;var Ea=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Ea>>>26)|0,Ea&=67108863,N=Math.imul(We,ut),m=Math.imul(We,ct),m=m+Math.imul($e,ut)|0,O=Math.imul($e,ct),N=N+Math.imul(Qe,lt)|0,m=m+Math.imul(Qe,ft)|0,m=m+Math.imul(Ke,lt)|0,O=O+Math.imul(Ke,ft)|0,N=N+Math.imul(It,ht)|0,m=m+Math.imul(It,dt)|0,m=m+Math.imul(Tt,ht)|0,O=O+Math.imul(Tt,dt)|0,N=N+Math.imul(bt,gt)|0,m=m+Math.imul(bt,pt)|0,m=m+Math.imul(St,gt)|0,O=O+Math.imul(St,pt)|0;var hw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(hw>>>26)|0,hw&=67108863,N=Math.imul(We,lt),m=Math.imul(We,ft),m=m+Math.imul($e,lt)|0,O=Math.imul($e,ft),N=N+Math.imul(Qe,ht)|0,m=m+Math.imul(Qe,dt)|0,m=m+Math.imul(Ke,ht)|0,O=O+Math.imul(Ke,dt)|0,N=N+Math.imul(It,gt)|0,m=m+Math.imul(It,pt)|0,m=m+Math.imul(Tt,gt)|0,O=O+Math.imul(Tt,pt)|0;var dw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(dw>>>26)|0,dw&=67108863,N=Math.imul(We,ht),m=Math.imul(We,dt),m=m+Math.imul($e,ht)|0,O=Math.imul($e,dt),N=N+Math.imul(Qe,gt)|0,m=m+Math.imul(Qe,pt)|0,m=m+Math.imul(Ke,gt)|0,O=O+Math.imul(Ke,pt)|0;var gw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(gw>>>26)|0,gw&=67108863,N=Math.imul(We,gt),m=Math.imul(We,pt),m=m+Math.imul($e,gt)|0,O=Math.imul($e,pt);var pw=(M+N|0)+((m&8191)<<13)|0;return M=(O+(m>>>13)|0)+(pw>>>26)|0,pw&=67108863,_[0]=vn,_[1]=An,_[2]=En,_[3]=bn,_[4]=Sn,_[5]=In,_[6]=da,_[7]=ga,_[8]=pa,_[9]=ma,_[10]=ya,_[11]=wa,_[12]=va,_[13]=Aa,_[14]=Ea,_[15]=hw,_[16]=dw,_[17]=gw,_[18]=pw,M!==0&&(_[19]=M,y.length++),y};Math.imul||(U=V);function Q(l,g,y){y.negative=g.negative^l.negative,y.length=l.length+g.length;for(var E=0,S=0,_=0;_>>26)|0,S+=M>>>26,M&=67108863}y.words[_]=N,E=M,M=S}return E!==0?y.words[_]=E:y.length--,y._strip()}function L(l,g,y){return Q(l,g,y)}s.prototype.mulTo=function(l,g){var y,E=this.length+l.length;return this.length===10&&l.length===10?y=U(this,l,g):E<63?y=V(this,l,g):E<1024?y=Q(this,l,g):y=L(this,l,g),y},s.prototype.mul=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),this.mulTo(l,g)},s.prototype.mulf=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),L(this,l,g)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var g=l<0;g&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var y=0,E=0;E>=26,y+=S/67108864|0,y+=_>>>26,this.words[E]=_&67108863}return y!==0&&(this.words[E]=y,this.length++),g?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var g=R(l);if(g.length===0)return new s(1);for(var y=this,E=0;E=0);var g=l%26,y=(l-g)/26,E=67108863>>>26-g<<26-g,S;if(g!==0){var _=0;for(S=0;S>>26-g}_&&(this.words[S]=_,this.length++)}if(y!==0){for(S=this.length-1;S>=0;S--)this.words[S+y]=this.words[S];for(S=0;S=0);var E;g?E=(g-g%26)/26:E=0;var S=l%26,_=Math.min((l-S)/26,this.length),M=67108863^67108863>>>S<_)for(this.length-=_,m=0;m=0&&(O!==0||m>=E);m--){var Y=this.words[m]|0;this.words[m]=O<<26-S|Y>>>S,O=Y&M}return N&&O!==0&&(N.words[N.length++]=O),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,g,y){return n(this.negative===0),this.iushrn(l,g,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var g=l%26,y=(l-g)/26,E=1<=0);var g=l%26,y=(l-g)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(g!==0&&y++,this.length=Math.min(y,this.length),g!==0){var E=67108863^67108863>>>g<=67108864;g++)this.words[g]-=67108864,g===this.length-1?this.words[g+1]=1:this.words[g+1]++;return this.length=Math.max(this.length,g+1),this},s.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var g=0;g>26)-(N/67108864|0),this.words[S+y]=_&67108863}for(;S>26,this.words[S+y]=_&67108863;if(M===0)return this._strip();for(n(M===-1),M=0,S=0;S>26,this.words[S]=_&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,g){var y=this.length-l.length,E=this.clone(),S=l,_=S.words[S.length-1]|0,M=this._countBits(_);y=26-M,y!==0&&(S=S.ushln(y),E.iushln(y),_=S.words[S.length-1]|0);var N=E.length-S.length,m;if(g!=="mod"){m=new s(null),m.length=N+1,m.words=new Array(m.length);for(var O=0;O=0;$--){var b=(E.words[S.length+$]|0)*67108864+(E.words[S.length+$-1]|0);for(b=Math.min(b/_|0,67108863),E._ishlnsubmul(S,b,$);E.negative!==0;)b--,E.negative=0,E._ishlnsubmul(S,1,$),E.isZero()||(E.negative^=1);m&&(m.words[$]=b)}return m&&m._strip(),E._strip(),g!=="div"&&y!==0&&E.iushrn(y),{div:m||null,mod:E}},s.prototype.divmod=function(l,g,y){if(n(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,S,_;return this.negative!==0&&l.negative===0?(_=this.neg().divmod(l,g),g!=="mod"&&(E=_.div.neg()),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.iadd(l)),{div:E,mod:S}):this.negative===0&&l.negative!==0?(_=this.divmod(l.neg(),g),g!=="mod"&&(E=_.div.neg()),{div:E,mod:_.mod}):this.negative&l.negative?(_=this.neg().divmod(l.neg(),g),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.isub(l)),{div:_.div,mod:S}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?g==="div"?{div:this.divn(l.words[0]),mod:null}:g==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,g)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var g=this.divmod(l);if(g.mod.isZero())return g.div;var y=g.div.negative!==0?g.mod.isub(l):g.mod,E=l.ushrn(1),S=l.andln(1),_=y.cmp(E);return _<0||S===1&&_===0?g.div:g.div.negative!==0?g.div.isubn(1):g.div.iaddn(1)},s.prototype.modrn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=(1<<26)%l,E=0,S=this.length-1;S>=0;S--)E=(y*E+(this.words[S]|0))%l;return g?-E:E},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=0,E=this.length-1;E>=0;E--){var S=(this.words[E]|0)+y*67108864;this.words[E]=S/l|0,y=S%l}return this._strip(),g?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=new s(0),M=new s(1),N=0;g.isEven()&&y.isEven();)g.iushrn(1),y.iushrn(1),++N;for(var m=y.clone(),O=g.clone();!g.isZero();){for(var Y=0,$=1;!(g.words[0]&$)&&Y<26;++Y,$<<=1);if(Y>0)for(g.iushrn(Y);Y-- >0;)(E.isOdd()||S.isOdd())&&(E.iadd(m),S.isub(O)),E.iushrn(1),S.iushrn(1);for(var b=0,j=1;!(y.words[0]&j)&&b<26;++b,j<<=1);if(b>0)for(y.iushrn(b);b-- >0;)(_.isOdd()||M.isOdd())&&(_.iadd(m),M.isub(O)),_.iushrn(1),M.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(_),S.isub(M)):(y.isub(g),_.isub(E),M.isub(S))}return{a:_,b:M,gcd:y.iushln(N)}},s.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=y.clone();g.cmpn(1)>0&&y.cmpn(1)>0;){for(var M=0,N=1;!(g.words[0]&N)&&M<26;++M,N<<=1);if(M>0)for(g.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(_),E.iushrn(1);for(var m=0,O=1;!(y.words[0]&O)&&m<26;++m,O<<=1);if(m>0)for(y.iushrn(m);m-- >0;)S.isOdd()&&S.iadd(_),S.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(S)):(y.isub(g),S.isub(E))}var Y;return g.cmpn(1)===0?Y=E:Y=S,Y.cmpn(0)<0&&Y.iadd(l),Y},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var g=this.clone(),y=l.clone();g.negative=0,y.negative=0;for(var E=0;g.isEven()&&y.isEven();E++)g.iushrn(1),y.iushrn(1);do{for(;g.isEven();)g.iushrn(1);for(;y.isEven();)y.iushrn(1);var S=g.cmp(y);if(S<0){var _=g;g=y,y=_}else if(S===0||y.cmpn(1)===0)break;g.isub(y)}while(!0);return y.iushln(E)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){n(typeof l=="number");var g=l%26,y=(l-g)/26,E=1<>>26,M&=67108863,this.words[_]=M}return S!==0&&(this.words[_]=S,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var g=l<0;if(this.negative!==0&&!g)return-1;if(this.negative===0&&g)return 1;this._strip();var y;if(this.length>1)y=1;else{g&&(l=-l),n(l<=67108863,"Number is too big");var E=this.words[0]|0;y=E===l?0:El.length)return 1;if(this.length=0;y--){var E=this.words[y]|0,S=l.words[y]|0;if(E!==S){ES&&(g=1);break}}return g},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new F(l)},s.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var k={k256:null,p224:null,p192:null,p25519:null};function H(l,g){this.name=l,this.p=new s(g,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},H.prototype.ireduce=function(l){var g=l,y;do this.split(g,this.tmp),g=this.imulK(g),g=g.iadd(this.tmp),y=g.bitLength();while(y>this.n);var E=y0?g.isub(this.p):g.strip!==void 0?g.strip():g._strip(),g},H.prototype.split=function(l,g){l.iushrn(this.n,0,g)},H.prototype.imulK=function(l){return l.imul(this.k)};function q(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(q,H),q.prototype.split=function(l,g){for(var y=4194303,E=Math.min(l.length,9),S=0;S>>22,_=M}_>>>=22,l.words[S-10]=_,_===0&&l.length>10?l.length-=10:l.length-=9},q.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var g=0,y=0;y>>=26,l.words[y]=S,g=E}return g!==0&&(l.words[l.length++]=g),l},s._prime=function(l){if(k[l])return k[l];var g;if(l==="k256")g=new q;else if(l==="p224")g=new v;else if(l==="p192")g=new C;else if(l==="p25519")g=new D;else throw new Error("Unknown prime "+l);return k[l]=g,g};function F(l){if(typeof l=="string"){var g=s._prime(l);this.m=g.p,this.prime=g}else n(l.gtn(1),"modulus must be greater than 1"),this.m=l,this.prime=null}F.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},F.prototype._verify2=function(l,g){n((l.negative|g.negative)===0,"red works only with positives"),n(l.red&&l.red===g.red,"red works only with red numbers")},F.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(f(l,l.umod(this.m)._forceRed(this)),l)},F.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},F.prototype.add=function(l,g){this._verify2(l,g);var y=l.add(g);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},F.prototype.iadd=function(l,g){this._verify2(l,g);var y=l.iadd(g);return y.cmp(this.m)>=0&&y.isub(this.m),y},F.prototype.sub=function(l,g){this._verify2(l,g);var y=l.sub(g);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},F.prototype.isub=function(l,g){this._verify2(l,g);var y=l.isub(g);return y.cmpn(0)<0&&y.iadd(this.m),y},F.prototype.shl=function(l,g){return this._verify1(l),this.imod(l.ushln(g))},F.prototype.imul=function(l,g){return this._verify2(l,g),this.imod(l.imul(g))},F.prototype.mul=function(l,g){return this._verify2(l,g),this.imod(l.mul(g))},F.prototype.isqr=function(l){return this.imul(l,l.clone())},F.prototype.sqr=function(l){return this.mul(l,l)},F.prototype.sqrt=function(l){if(l.isZero())return l.clone();var g=this.m.andln(3);if(n(g%2===1),g===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var E=this.m.subn(1),S=0;!E.isZero()&&E.andln(1)===0;)S++,E.iushrn(1);n(!E.isZero());var _=new s(1).toRed(this),M=_.redNeg(),N=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,N).cmp(M)!==0;)m.redIAdd(M);for(var O=this.pow(m,E),Y=this.pow(l,E.addn(1).iushrn(1)),$=this.pow(l,E),b=S;$.cmp(_)!==0;){for(var j=$,z=0;j.cmp(_)!==0;z++)j=j.redSqr();n(z=0;S--){for(var O=g.words[S],Y=m-1;Y>=0;Y--){var $=O>>Y&1;if(_!==E[0]&&(_=this.sqr(_)),$===0&&M===0){N=0;continue}M<<=1,M|=$,N++,!(N!==y&&(S!==0||Y!==0))&&(_=this.mul(_,E[M]),N=0,M=0)}m=26}return _},F.prototype.convertTo=function(l){var g=l.umod(this.m);return g===l?g.clone():g},F.prototype.convertFrom=function(l){var g=l.clone();return g.red=null,g},s.mont=function(l){return new P(l)};function P(l){F.call(this,l),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(P,F),P.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},P.prototype.convertFrom=function(l){var g=this.imod(l.mul(this.rinv));return g.red=null,g},P.prototype.imul=function(l,g){if(l.isZero()||g.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.mul=function(l,g){if(l.isZero()||g.isZero())return new s(0)._forceRed(this);var y=l.mul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.invm=function(l){var g=this.imod(l._invmp(this.m).mul(this.r2));return g._forceRed(this)}})(t,g4)})(w4);var Se=w4.exports,v4="bignumber/5.7.0",Jm=Se.BN,Ks=new kt(v4),hT={},TM=9007199254740991;function Lte(t){return t!=null&&(Cr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||gn(t)||typeof t=="bigint"||ul(t))}var _M=!1,Cr=class t{constructor(e,r){e!==hT&&Ks.throwError("cannot call constructor directly; use BigNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return sn(De(this).fromTwos(e))}toTwos(e){return sn(De(this).toTwos(e))}abs(){return this._hex[0]==="-"?t.from(this._hex.substring(1)):this}add(e){return sn(De(this).add(De(e)))}sub(e){return sn(De(this).sub(De(e)))}div(e){return t.from(e).isZero()&&Kn("division-by-zero","div"),sn(De(this).div(De(e)))}mul(e){return sn(De(this).mul(De(e)))}mod(e){let r=De(e);return r.isNeg()&&Kn("division-by-zero","mod"),sn(De(this).umod(r))}pow(e){let r=De(e);return r.isNeg()&&Kn("negative-power","pow"),sn(De(this).pow(r))}and(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","and"),sn(De(this).and(r))}or(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","or"),sn(De(this).or(r))}xor(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","xor"),sn(De(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Kn("negative-width","mask"),sn(De(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Kn("negative-width","shl"),sn(De(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Kn("negative-width","shr"),sn(De(this).shrn(e))}eq(e){return De(this).eq(De(e))}lt(e){return De(this).lt(De(e))}lte(e){return De(this).lte(De(e))}gt(e){return De(this).gt(De(e))}gte(e){return De(this).gte(De(e))}isNegative(){return this._hex[0]==="-"}isZero(){return De(this).isZero()}toNumber(){try{return De(this).toNumber()}catch{Kn("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ks.throwError("this platform does not support BigInt",kt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?_M||(_M=!0,Ks.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ks.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",kt.errors.UNEXPECTED_ARGUMENT,{}):Ks.throwError("BigNumber.toString does not accept parameters",kt.errors.UNEXPECTED_ARGUMENT,{})),De(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof t)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new t(hT,Vh(e)):e.match(/^-?[0-9]+$/)?new t(hT,Vh(new Jm(e))):Ks.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Kn("underflow","BigNumber.from",e),(e>=TM||e<=-TM)&&Kn("overflow","BigNumber.from",e),t.from(String(e));let r=e;if(typeof r=="bigint")return t.from(r.toString());if(ul(r))return t.from(kr(r));if(r)if(r.toHexString){let n=r.toHexString();if(typeof n=="string")return t.from(n)}else{let n=r._hex;if(n==null&&r.type==="BigNumber"&&(n=r.hex),typeof n=="string"&&(gn(n)||n[0]==="-"&&gn(n.substring(1))))return t.from(n)}return Ks.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}};function Vh(t){if(typeof t!="string")return Vh(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ks.throwArgumentError("invalid hex","value",t),t=Vh(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function sn(t){return Cr.from(Vh(t))}function De(t){let e=Cr.from(t).toHexString();return e[0]==="-"?new Jm("-"+e.substring(3),16):new Jm(e.substring(2),16)}function Kn(t,e,r){let n={fault:t,operation:e};return r!=null&&(n.value=r),Ks.throwError(t,kt.errors.NUMERIC_FAULT,n)}function Fte(t){return new Jm(t,36).toString(16)}var Hr=new kt(v4),Fh={},A4=Cr.from(0),E4=Cr.from(-1);function b4(t,e,r,n){let i={fault:e,operation:r};return n!==void 0&&(i.value=n),Hr.throwError(t,kt.errors.NUMERIC_FAULT,i)}var Uh="0";for(;Uh.length<256;)Uh+=Uh;function GT(t){if(typeof t!="number")try{t=Cr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+Uh.substring(0,t):Hr.throwArgumentError("invalid decimal size","decimals",t)}function dT(t,e){e==null&&(e=0);let r=GT(e);t=Cr.from(t);let n=t.lt(A4);n&&(t=t.mul(E4));let i=t.mod(r).toString();for(;i.length2&&Hr.throwArgumentError("too many decimal points","value",t);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");o[o.length-1]==="0";)o=o.substring(0,o.length-1);for(o.length>r.length-1&&b4("fractional component exceeds decimals","underflow","parseFixed"),o===""&&(o="0");o.lengthe[o]==null?a:(typeof e[o]!==u&&Hr.throwArgumentError("invalid fixed format ("+o+" not "+u+")","format."+o,e[o]),e[o]);r=s("signed","boolean",r),n=s("width","number",n),i=s("decimals","number",i)}return n%8&&Hr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),i>80&&Hr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",i),new t(Fh,r,n,i)}},Xm=class t{constructor(e,r,n,i){e!==Fh&&Hr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=r,this._value=n,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Hr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.add(n),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.sub(n),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return this.isNegative()&&n&&(r=r.subUnsafe(CM.toFormat(r.format))),r}ceiling(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return!this.isNegative()&&n&&(r=r.addUnsafe(CM.toFormat(r.format))),r}round(e){e==null&&(e=0);let r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&Hr.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;let n=t.from("1"+Uh.substring(0,e),this.format),i=Ute.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(i).floor().divUnsafe(n)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Hr.throwArgumentError("invalid byte width","width",e);let r=Cr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return fs(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return t.fromString(this._value,e)}static fromValue(e,r,n){return n==null&&r!=null&&!Lte(r)&&(n=r,r=null),r==null&&(r=0),n==null&&(n="fixed"),t.fromString(dT(e,r),qh.from(n))}static fromString(e,r){r==null&&(r="fixed");let n=qh.from(r),i=Qs(e,n.decimals);!n.signed&&i.lt(A4)&&b4("unsigned value cannot be negative","overflow","value",e);let s=null;n.signed?s=i.toTwos(n.width).toHexString():(s=i.toHexString(),s=fs(s,n.width/8));let o=dT(i,n.decimals);return new t(Fh,s,o,n)}static fromBytes(e,r){r==null&&(r="fixed");let n=qh.from(r);if(Qt(e).length>n.width/8)throw new Error("overflow");let i=Cr.from(e);n.signed&&(i=i.fromTwos(n.width));let s=i.toTwos((n.signed?0:1)+n.width).toHexString(),o=dT(i,n.decimals);return new t(Fh,s,o,n)}static from(e,r){if(typeof e=="string")return t.fromString(e,r);if(ul(e))return t.fromBytes(e,r);try{return t.fromValue(e,0,r)}catch(n){if(n.code!==kt.errors.INVALID_ARGUMENT)throw n}return Hr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}},CM=Xm.from(1),Ute=Xm.from("0.5"),qte="strings/5.7.0",S4=new kt(qte),Zm;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(Zm||(Zm={}));var rl;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(rl||(rl={}));function Vte(t,e,r,n,i){return S4.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function I4(t,e,r,n,i){if(t===rl.BAD_PREFIX||t===rl.UNEXPECTED_CONTINUE){let s=0;for(let o=e+1;o>6===2;o++)s++;return s}return t===rl.OVERRUN?r.length-e-1:0}function kte(t,e,r,n,i){return t===rl.OVERLONG?(n.push(i),0):(n.push(65533),I4(t,e,r))}Object.freeze({error:Vte,ignore:I4,replace:kte});function gT(t,e=Zm.current){e!=Zm.current&&(S4.checkNormalize(),t=t.normalize(e));let r=[];for(let n=0;n>6|192),r.push(i&63|128);else if((i&64512)==55296){n++;let s=t.charCodeAt(n);if(n>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");let o=65536+((i&1023)<<10)+(s&1023);r.push(o>>18|240),r.push(o>>12&63|128),r.push(o>>6&63|128),r.push(o&63|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(i&63|128)}return Qt(r)}function Hte(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r{let s=i.split(":");r+=parseInt(s[0],16),n[r]=e(s[1])}),n}function NM(t){let e=0;return t.split(",").map(r=>{let n=r.split("-");n.length===1?n[1]="0":n[1]===""&&(n[1]="1");let i=e+parseInt(n[0],16);return e=parseInt(n[1],16),{l:i,h:e}})}NM("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),pT("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),pT("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),pT("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",Hte),NM("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");var T4="hash/5.7.0";function Gte(t){t=atob(t);let e=[];for(let r=0;r0&&Array.isArray(u)?i(u,o-1):r.push(u)})};return i(t,e),r}function jte(t){let e={};for(let r=0;r>--a&1}let d=31,w=Math.pow(2,d),A=w>>>1,T=A>>1,x=w-1,R=0;for(let k=0;k1;){let D=H+q>>>1;k>>1|f(),v=v<<1^A,C=(C^A)<<1|A|1;U=v,Q=1+C-v}let L=n-4;return V.map(k=>{switch(k-L){case 3:return L+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return L+256+(t[u++]<<8|t[u++]);case 1:return L+t[u++];default:return k-1}})}function Qte(t){let e=0;return()=>t[e++]}function Kte(t){return Qte(zte(t))}function Wte(t){return t&1?~t>>1:t>>1}function $te(t,e){let r=Array(t);for(let n=0;ne[o]):r}function Jte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(Zte(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(ere(r,t))}return jte(_4(e))}function Xte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function C4(t,e,r){let n=Array(t).fill(void 0).map(()=>[]);for(let i=0;in[o].push(s));return n}function Zte(t,e){let r=1+e(),n=e(),i=Xte(e),s=C4(i.length,1+t,e);return _4(s.map((o,u)=>{let a=o[0],c=o.slice(1);return Array(i[u]).fill(void 0).map((f,d)=>{let w=d*n;return[a+d*r,c.map(A=>A+w)]})}))}function ere(t,e){let r=1+e();return C4(r,1+t,e).map(n=>[n[0],n.slice(1)])}function tre(t){let e=ey(t).sort((n,i)=>n-i);return r();function r(){let n=[];for(;;){let c=ey(t,e);if(c.length==0)break;n.push({set:new Set(c),node:r()})}n.sort((c,f)=>f.set.size-c.set.size);let i=t(),s=i%3;i=i/3|0;let o=!!(i&1);i>>=1;let u=i==1,a=i==2;return{branches:n,valid:s,fe0f:o,save:u,check:a}}}function rre(){return Kte(Gte("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}var km=rre();new Set(ey(km)),new Set(ey(km)),Jte(km),tre(km),new kt(T4);var nre=new Uint8Array(32);nre.fill(0);var ire=`Ethereum Signed Message: -`;function N4(t){return typeof t=="string"&&(t=gT(t)),HT(Ote([gT(ire),gT(String(t.length)),t]))}var sre="rlp/5.7.0";new kt(sre);var ore="address/5.7.0",Lh=new kt(ore);function OM(t){gn(t,20)||Lh.throwArgumentError("invalid address","address",t),t=t.toLowerCase();let e=t.substring(2).split(""),r=new Uint8Array(40);for(let i=0;i<40;i++)r[i]=e[i].charCodeAt(0);let n=Qt(HT(r));for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&(e[i]=e[i].toUpperCase()),(n[i>>1]&15)>=8&&(e[i+1]=e[i+1].toUpperCase());return"0x"+e.join("")}var are=9007199254740991;function ure(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}var jT={};for(let t=0;t<10;t++)jT[String(t)]=String(t);for(let t=0;t<26;t++)jT[String.fromCharCode(65+t)]=String(10+t);var DM=Math.floor(ure(are));function cre(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(n=>jT[n]).join("");for(;e.length>=DM;){let n=e.substring(0,DM);e=parseInt(n,10)%97+e.substring(n.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function lre(t){let e=null;if(typeof t!="string"&&Lh.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=OM(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&Lh.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==cre(t)&&Lh.throwArgumentError("bad icap checksum","address",t),e=Fte(t.substring(4));e.length<40;)e="0"+e;e=OM("0x"+e)}else Lh.throwArgumentError("invalid address","address",t);return e}var fre="properties/5.7.0";new kt(fre);function Rh(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new kt(T4);var hre=new Uint8Array(32);hre.fill(0),Cr.from(-1);var dre=Cr.from(0),gre=Cr.from(1);Cr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fs(gre.toHexString(),32),fs(dre.toHexString(),32);var os={},Pe={},Gh=x4;function x4(t,e){if(!t)throw new Error(e||"Assertion failed")}x4.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var CT={exports:{}};typeof Object.create=="function"?CT.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:CT.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var pre=Gh,mre=CT.exports;Pe.inherits=mre;function yre(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function wre(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),i=0;i>6|192,r[n++]=s&63|128):yre(t,i)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023),r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128)}else for(i=0;i>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Pe.htonl=O4;function Are(t,e){for(var r="",n=0;n>>0}return s}Pe.join32=Ere;function bre(t,e){for(var r=new Array(t.length*4),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=s&255):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=s&255)}return r}Pe.split32=bre;function Sre(t,e){return t>>>e|t<<32-e}Pe.rotr32=Sre;function Ire(t,e){return t<>>32-e}Pe.rotl32=Ire;function Tre(t,e){return t+e>>>0}Pe.sum32=Tre;function _re(t,e,r){return t+e+r>>>0}Pe.sum32_3=_re;function Cre(t,e,r,n){return t+e+r+n>>>0}Pe.sum32_4=Cre;function Nre(t,e,r,n,i){return t+e+r+n+i>>>0}Pe.sum32_5=Nre;function xre(t,e,r,n){var i=t[e],s=t[e+1],o=n+s>>>0,u=(o>>0,t[e+1]=o}Pe.sum64=xre;function Ore(t,e,r,n){var i=e+n>>>0,s=(i>>0}Pe.sum64_hi=Ore;function Dre(t,e,r,n){var i=e+n;return i>>>0}Pe.sum64_lo=Dre;function Pre(t,e,r,n,i,s,o,u){var a=0,c=e;c=c+n>>>0,a+=c>>0,a+=c>>0,a+=c>>0}Pe.sum64_4_hi=Pre;function Rre(t,e,r,n,i,s,o,u){var a=e+n+s+u;return a>>>0}Pe.sum64_4_lo=Rre;function Bre(t,e,r,n,i,s,o,u,a,c){var f=0,d=e;d=d+n>>>0,f+=d>>0,f+=d>>0,f+=d>>0,f+=d>>0}Pe.sum64_5_hi=Bre;function Mre(t,e,r,n,i,s,o,u,a,c){var f=e+n+s+u+c;return f>>>0}Pe.sum64_5_lo=Mre;function Lre(t,e,r){var n=e<<32-r|t>>>r;return n>>>0}Pe.rotr64_hi=Lre;function Fre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.rotr64_lo=Fre;function Ure(t,e,r){return t>>>r}Pe.shr64_hi=Ure;function qre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.shr64_lo=qre;var cl={},PM=Pe,Vre=Gh;function Hm(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}cl.BlockHash=Hm,Hm.prototype.update=function(t,e){if(t=PM.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=PM.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=t&255}else for(n[i++]=t&255,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s>>3}ms.g0_256=zre;function Qre(t){return hs(t,17)^hs(t,19)^t>>>10}ms.g1_256=Qre;var sl=Pe,Kre=cl,Wre=ms,mT=sl.rotl32,Bh=sl.sum32,$re=sl.sum32_5,Yre=Wre.ft_1,L4=Kre.BlockHash,Jre=[1518500249,1859775393,2400959708,3395469782];function us(){if(!(this instanceof us))return new us;L4.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}sl.inherits(us,L4);var Xre=us;us.blockSize=512,us.outSize=160,us.hmacStrength=80,us.padLength=64,us.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=new this.Hash().update(t).digest()),qne(t.length<=this.blockSize);for(var e=t.length;e>8,w=f&255;d?a.push(d,w):a.push(w)}return a}r.toArray=n;function i(o){return o.length===1?"0"+o:o}r.zero2=i;function s(o){for(var u="",a=0;a(w>>1)-1?x=(w>>1)-R:x=R,A.isubn(x)):x=0,d[T]=x,A.iushrn(1)}return d}r.getNAF=n;function i(a,c){var f=[[],[]];a=a.clone(),c=c.clone();for(var d=0,w=0,A;a.cmpn(-d)>0||c.cmpn(-w)>0;){var T=a.andln(3)+d&3,x=c.andln(3)+w&3;T===3&&(T=-1),x===3&&(x=-1);var R;T&1?(A=a.andln(7)+d&7,(A===3||A===5)&&x===2?R=-T:R=T):R=0,f[0].push(R);var V;x&1?(A=c.andln(7)+w&7,(A===3||A===5)&&T===2?V=-x:V=x):V=0,f[1].push(V),2*d===R+1&&(d=1-d),2*w===V+1&&(w=1-w),a.iushrn(1),c.iushrn(1)}return f}r.getJSF=i;function s(a,c,f){var d="_"+c;a.prototype[c]=function(){return this[d]!==void 0?this[d]:this[d]=f.call(this)}}r.cachedProperty=s;function o(a){return typeof a=="string"?r.toArray(a,"hex"):a}r.parseBytes=o;function u(a){return new Se(a,"hex","le")}r.intFromLE=u}),jm=pn.getNAF,Hne=pn.getJSF,ty=pn.assert;function Vo(t,e){this.type=t,this.p=new Se(e.p,16),this.red=e.prime?Se.red(e.prime):Se.mont(this.p),this.zero=new Se(0).toRed(this.red),this.one=new Se(1).toRed(this.red),this.two=new Se(2).toRed(this.red),this.n=e.n&&new Se(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var nu=Vo;Vo.prototype.point=function(){throw new Error("Not implemented")},Vo.prototype.validate=function(){throw new Error("Not implemented")},Vo.prototype._fixedNafMul=function(t,e){ty(t.precomputed);var r=t._getDoubles(),n=jm(e,1,this._bitLength),i=(1<=o;a--)u=(u<<1)+n[a];s.push(u)}for(var c=this.jpoint(null,null,null),f=this.jpoint(null,null,null),d=i;d>0;d--){for(o=0;o=0;u--){for(var a=0;u>=0&&s[u]===0;u--)a++;if(u>=0&&a++,o=o.dblp(a),u<0)break;var c=s[u];ty(c!==0),t.type==="affine"?c>0?o=o.mixedAdd(i[c-1>>1]):o=o.mixedAdd(i[-c-1>>1].neg()):c>0?o=o.add(i[c-1>>1]):o=o.add(i[-c-1>>1].neg())}return t.type==="affine"?o.toP():o},Vo.prototype._wnafMulAdd=function(t,e,r,n,i){var s=this._wnafT1,o=this._wnafT2,u=this._wnafT3,a=0,c,f,d;for(c=0;c=1;c-=2){var A=c-1,T=c;if(s[A]!==1||s[T]!==1){u[A]=jm(r[A],s[A],this._bitLength),u[T]=jm(r[T],s[T],this._bitLength),a=Math.max(u[A].length,a),a=Math.max(u[T].length,a);continue}var x=[e[A],null,null,e[T]];e[A].y.cmp(e[T].y)===0?(x[1]=e[A].add(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg())):e[A].y.cmp(e[T].y.redNeg())===0?(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].add(e[T].neg())):(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg()));var R=[-3,-1,-5,-7,0,7,5,1,3],V=Hne(r[A],r[T]);for(a=Math.max(V[0].length,a),u[A]=new Array(a),u[T]=new Array(a),f=0;f=0;c--){for(var H=0;c>=0;){var q=!0;for(f=0;f=0&&H++,L=L.dblp(H),c<0)break;for(f=0;f0?d=o[f][v-1>>1]:v<0&&(d=o[f][-v-1>>1].neg()),d.type==="affine"?L=L.mixedAdd(d):L=L.add(d))}}for(c=0;c=Math.ceil((t.bitLength()+1)/e.step):!1},Wn.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(w=a,A=c),f.negative&&(f=f.neg(),d=d.neg()),w.negative&&(w=w.neg(),A=A.neg()),[{a:f,b:d},{a:w,b:A}]},Yn.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),u=s.mul(n.a),a=i.mul(r.b),c=s.mul(n.b),f=t.sub(o).sub(u),d=a.add(c).neg();return{k1:f,k2:d}},Yn.prototype.pointFromX=function(t,e){t=new Se(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(n.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},Yn.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return r.redSqr().redISub(i).cmpn(0)===0},Yn.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Ar.prototype.isInfinity=function(){return this.inf},Ar.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Ar.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Ar.prototype.getX=function(){return this.x.fromRed()},Ar.prototype.getY=function(){return this.y.fromRed()},Ar.prototype.mul=function(t){return t=new Se(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Ar.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Ar.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Ar.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Ar.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(i){return i.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Ar.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function _r(t,e,r,n){nu.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&n===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Se(0)):(this.x=new Se(e,16),this.y=new Se(r,16),this.z=new Se(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}QT(_r,nu.BasePoint),Yn.prototype.jpoint=function(t,e,r){return new _r(this,t,e,r)},_r.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},_r.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_r.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=s.redSub(o);if(u.cmpn(0)===0)return a.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var c=u.redSqr(),f=c.redMul(u),d=n.redMul(c),w=a.redSqr().redIAdd(f).redISub(d).redISub(d),A=a.redMul(d.redISub(w)).redISub(s.redMul(f)),T=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(w,A,T)},_r.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),u=i.redSub(s);if(o.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),c=a.redMul(o),f=r.redMul(a),d=u.redSqr().redIAdd(c).redISub(f).redISub(f),w=u.redMul(f.redISub(d)).redISub(i.redMul(c)),A=this.z.redMul(o);return this.curve.jpoint(d,w,A)},_r.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),this.x.cmp(r)===0)return!0}},_r.prototype.inspect=function(){return this.isInfinity()?"":""},_r.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Km=fl(function(t,e){var r=e;r.base=nu,r.short=jne,r.mont=null,r.edwards=null}),Wm=fl(function(t,e){var r=e,n=pn.assert;function i(u){u.type==="short"?this.curve=new Km.short(u):u.type==="edwards"?this.curve=new Km.edwards(u):this.curve=new Km.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=i;function s(u,a){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var c=new i(a);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:c}),c}})}s("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:os.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:os.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:os.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:os.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),s("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:os.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var o;try{o=null.crash()}catch{o=void 0}s("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:os.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",o]})});function ko(t){if(!(this instanceof ko))return new ko(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Ti.toArray(t.entropy,t.entropyEnc||"hex"),r=Ti.toArray(t.nonce,t.nonceEnc||"hex"),n=Ti.toArray(t.pers,t.persEnc||"hex");zT(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var LM=ko;ko.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},ko.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(n=r,r=e,e=null),r&&(r=Ti.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var zne=pn.assert;function sy(t,e){if(t instanceof sy)return t;this._importDER(t,e)||(zne(t.r&&t.s,"Signature without r or s"),this.r=new Se(t.r,16),this.s=new Se(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var zm=sy;function Qne(){this.place=0}function ET(t,e){var r=t[e.place++];if(!(r&128))return r;var n=r&15;if(n===0||n>4)return!1;for(var i=0,s=0,o=e.place;s>>=0;return i<=127?!1:(e.place=o,i)}function FM(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}sy.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=FM(e),r=FM(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var n=[2];bT(n,e.length),n=n.concat(e),n.push(2),bT(n,r.length);var i=n.concat(r),s=[48];return bT(s,i.length),s=s.concat(i),pn.encode(s,t)};var Kne=function(){throw new Error("unsupported")},W4=pn.assert;function $n(t){if(!(this instanceof $n))return new $n(t);typeof t=="string"&&(W4(Object.prototype.hasOwnProperty.call(Wm,t),"Unknown curve "+t),t=Wm[t]),t instanceof Wm.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Wne=$n;$n.prototype.keyPair=function(t){return new AT(this,t)},$n.prototype.keyFromPrivate=function(t,e){return AT.fromPrivate(this,t,e)},$n.prototype.keyFromPublic=function(t,e){return AT.fromPublic(this,t,e)},$n.prototype.genKeyPair=function(t){t||(t={});for(var e=new LM({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Kne(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Se(2));;){var i=new Se(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},$n.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},$n.prototype.sign=function(t,e,r,n){typeof r=="object"&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Se(t,16));for(var i=this.n.byteLength(),s=e.getPrivate().toArray("be",i),o=t.toArray("be",i),u=new LM({hash:this.hash,entropy:s,nonce:o,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Se(1)),c=0;;c++){var f=n.k?n.k(c):new Se(u.generate(this.n.byteLength()));if(f=this._truncateToN(f,!0),!(f.cmpn(1)<=0||f.cmp(a)>=0)){var d=this.g.mul(f);if(!d.isInfinity()){var w=d.getX(),A=w.umod(this.n);if(A.cmpn(0)!==0){var T=f.invm(this.n).mul(A.mul(e.getPrivate()).iadd(t));if(T=T.umod(this.n),T.cmpn(0)!==0){var x=(d.getY().isOdd()?1:0)|(w.cmp(A)!==0?2:0);return n.canonical&&T.cmp(this.nh)>0&&(T=this.n.sub(T),x^=1),new zm({r:A,s:T,recoveryParam:x})}}}}}},$n.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Se(t,16)),r=this.keyFromPublic(r,n),e=new zm(e,"hex");var i=e.r,s=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o=s.invm(this.n),u=o.mul(t).umod(this.n),a=o.mul(i).umod(this.n),c;return this.curve._maxwellTrick?(c=this.g.jmulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.eqXToP(i)):(c=this.g.mulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.getX().umod(this.n).cmp(i)===0)},$n.prototype.recoverPubKey=function(t,e,r,n){W4((3&r)===r,"The recovery param is more than two bits"),e=new zm(e,n);var i=this.n,s=new Se(t),o=e.r,u=e.s,a=r&1,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");c?o=this.curve.pointFromX(o.add(this.curve.n),a):o=this.curve.pointFromX(o,a);var f=e.r.invm(i),d=i.sub(s).mul(f).umod(i),w=u.mul(f).umod(i);return this.g.mulAdd(d,o,w)},$n.prototype.getKeyRecoveryParam=function(t,e,r,n){if(e=new zm(e,n),e.recoveryParam!==null)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch{continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var $ne=fl(function(t,e){var r=e;r.version="6.5.4",r.utils=pn,r.rand=function(){throw new Error("unsupported")},r.curve=Km,r.curves=Wm,r.ec=Wne,r.eddsa=null}),Yne=$ne.ec,Jne="signing-key/5.7.0",OT=new kt(Jne),ST=null;function ls(){return ST||(ST=new Yne("secp256k1")),ST}var DT=class{constructor(e){Rh(this,"curve","secp256k1"),Rh(this,"privateKey",kr(e)),Pte(this.privateKey)!==32&&OT.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");let r=ls().keyFromPrivate(Qt(this.privateKey));Rh(this,"publicKey","0x"+r.getPublic(!1,"hex")),Rh(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),Rh(this,"_isSigningKey",!0)}_addPoint(e){let r=ls().keyFromPublic(Qt(this.publicKey)),n=ls().keyFromPublic(Qt(e));return"0x"+r.pub.add(n.pub).encodeCompressed("hex")}signDigest(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=Qt(e);n.length!==32&&OT.throwArgumentError("bad digest length","digest",e);let i=r.sign(n,{canonical:!0});return y4({recoveryParam:i.recoveryParam,r:fs("0x"+i.r.toString(16),32),s:fs("0x"+i.s.toString(16),32)})}computeSharedSecret(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=ls().keyFromPublic(Qt($4(e)));return fs("0x"+r.derive(n.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}};function Xne(t,e){let r=y4(e),n={r:Qt(r.r),s:Qt(r.s)};return"0x"+ls().recoverPubKey(Qt(t),n,r.recoveryParam).encode("hex",!1)}function $4(t,e){let r=Qt(t);if(r.length===32){let n=new DT(r);return e?"0x"+ls().keyFromPrivate(r).getPublic(!0,"hex"):n.publicKey}else{if(r.length===33)return e?kr(r):"0x"+ls().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+ls().keyFromPublic(r).getPublic(!0,"hex"):kr(r)}return OT.throwArgumentError("invalid public or private key","key","[REDACTED]")}var Zne="transactions/5.7.0";new kt(Zne);var UM;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(UM||(UM={}));function eie(t){let e=$4(t);return lre(IM(HT(IM(e,1)),12))}function tie(t,e){return eie(Xne(Qt(t),e))}var rie="https://rpc.walletconnect.com/v1";async function Y4(t,e,r,n,i,s){switch(r.t){case"eip191":return J4(t,e,r.s);case"eip1271":return await X4(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function J4(t,e,r){return tie(N4(e),r).toLowerCase()===t.toLowerCase()}async function X4(t,e,r,n,i,s){try{let o="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",c=r.substring(2),f=N4(e).substring(2),d=o+f+u+a+c,w=await fetch(`${s||rie}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:nie(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:A}=await w.json();return A?A.slice(0,o.length).toLowerCase()===o.toLowerCase():!1}catch(o){return console.error("isValidEip1271Signature: ",o),!1}}function nie(){return Date.now()+Math.floor(Math.random()*1e3)}var iie=Object.defineProperty,sie=Object.defineProperties,oie=Object.getOwnPropertyDescriptors,qM=Object.getOwnPropertySymbols,aie=Object.prototype.hasOwnProperty,uie=Object.prototype.propertyIsEnumerable,VM=(t,e,r)=>e in t?iie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KT=(t,e)=>{for(var r in e||(e={}))aie.call(e,r)&&VM(t,r,e[r]);if(qM)for(var r of qM(e))uie.call(e,r)&&VM(t,r,e[r]);return t},Z4=(t,e)=>sie(t,oie(e)),cie="did:pkh:",oy=t=>t?.split(":"),WT=t=>{let e=t&&oy(t);if(e)return t.includes(cie)?e[3]:e[1]},lie=t=>{let e=t&&oy(t);if(e)return e[2]+":"+e[3]},$T=t=>{let e=t&&oy(t);if(e)return e.pop()};async function fie(t){let{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=e5(i,i.iss),o=$T(i.iss);return await Y4(o,s,n,WT(i.iss),r)}var e5=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=$T(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0,s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,u=`Chain ID: ${WT(e)}`,a=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources?`Resources:${t.resources.map(w=>` -- ${w}`).join("")}`:void 0,d=uy(t.resources);if(d){let w=jo(d);i=XT(i,w)}return[r,n,"",i,"",s,o,u,a,c,f].filter(w=>w!=null).join(` -`)};function hie(t,e,r){return r.includes("did:pkh:")||(r=`did:pkh:${r}`),{h:{t:"caip122"},p:{iss:r,domain:t.domain,aud:t.aud,version:t.version,nonce:t.nonce,iat:t.iat,statement:t.statement,requestId:t.requestId,resources:t.resources,nbf:t.nbf,exp:t.exp},s:e}}function die(t){var e;let{authPayload:r,chains:n,methods:i}=t,s=r.statement||"";if(!(n!=null&&n.length))return r;let o=r.chains,u=TT(o,n);if(!(u!=null&&u.length))throw new Error("No supported chains");let a=t5(r.resources);if(!a)return r;ps(a);let c=r5(a,"eip155"),f=r?.resources||[];if(c!=null&&c.length){let d=n5(c),w=TT(d,i);if(!(w!=null&&w.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(d)}, supported: ${JSON.stringify(i)}`);let A=YT("request",w,{chains:u}),T=a5(a,"eip155",A);f=((e=r?.resources)==null?void 0:e.slice(0,-1))||[],f.push(ay(T))}return Z4(KT({},r),{statement:c5(s,uy(f)),chains:u,resources:r!=null&&r.resources||f.length>0?f:void 0})}function t5(t){let e=uy(t);if(e&&JT(e))return jo(e)}function gie(t,e){var r;return(r=t?.att)==null?void 0:r.hasOwnProperty(e)}function r5(t,e){var r,n;return(r=t?.att)!=null&&r[e]?Object.keys((n=t?.att)==null?void 0:n[e]):[]}function pie(t){return t?.map(e=>Object.keys(e))||[]}function n5(t){return t?.map(e=>{var r;return(r=e.split("/"))==null?void 0:r[1]})||[]}function i5(t){return p.Buffer.from(JSON.stringify(t)).toString("base64")}function s5(t){return JSON.parse(p.Buffer.from(t,"base64").toString("utf-8"))}function ps(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");let e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{let n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{let s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function o5(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:YT(e,r,n)}}}function a5(t,e,r){var n;return t.att[e]=KT({},r),((n=Object.keys(t.att))==null?void 0:n.sort((i,s)=>i.localeCompare(s))).reduce((i,s)=>(i.att[s]=t.att[s],i),{att:{}})}function YT(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));let n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function ay(t){return ps(t),`urn:recap:${i5(t).replace(/=/g,"")}`}function jo(t){let e=s5(t.replace("urn:recap:",""));return ps(e),e}function mie(t,e,r){let n=o5(t,e,r);return ay(n)}function JT(t){return t&&t.includes("urn:recap:")}function yie(t,e){let r=jo(t),n=jo(e),i=u5(r,n);return ay(i)}function u5(t,e){ps(t),ps(e);let r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((u,a)=>u.localeCompare(a)).forEach(u=>{var a,c;n.att[i]=Z4(KT({},n.att[i]),{[u]:((a=t.att[i])==null?void 0:a[u])||((c=e.att[i])==null?void 0:c[u])})})}),n}function XT(t="",e){ps(e);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;let n=[],i=0;Object.keys(e.att).forEach(u=>{let a=Object.keys(e.att[u]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));a.sort((d,w)=>d.action.localeCompare(w.action));let c={};a.forEach(d=>{c[d.ability]||(c[d.ability]=[]),c[d.ability].push(d.action)});let f=Object.keys(c).map(d=>(i++,`(${i}) '${d}': '${c[d].join("', '")}' for '${u}'.`));n.push(f.join(", ").replace(".,","."))});let s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function wie(t){var e;let r=jo(t);ps(r);let n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function vie(t){let e=jo(t);ps(e);let r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function c5(t,e){if(!e)return t;let r=jo(e);return ps(r),XT(t,r)}function uy(t){if(!t)return;let e=t?.[t.length-1];return JT(e)?e:void 0}var ZT="base10",jr="base16",ry="base64pad",cy="utf8",e_=0,hl=1,Aie=0,kM=1,PT=12,t_=32;function Eie(){let t=JM.generateKeyPair();return{privateKey:Vt.toString(t.secretKey,jr),publicKey:Vt.toString(t.publicKey,jr)}}function bie(){let t=$M.randomBytes(t_);return Vt.toString(t,jr)}function Sie(t,e){let r=JM.sharedKey(Vt.fromString(t,jr),Vt.fromString(e,jr),!0),n=new Gee.HKDF(LT.SHA256,r).expand(t_);return Vt.toString(n,jr)}function Iie(t){let e=LT.hash(Vt.fromString(t,jr));return Vt.toString(e,jr)}function Tie(t){let e=LT.hash(Vt.fromString(t,cy));return Vt.toString(e,jr)}function l5(t){return Vt.fromString(`${t}`,ZT)}function jh(t){return Number(Vt.toString(t,ZT))}function _ie(t){let e=l5(typeof t.type<"u"?t.type:e_);if(jh(e)===hl&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?Vt.fromString(t.senderPublicKey,jr):void 0,n=typeof t.iv<"u"?Vt.fromString(t.iv,jr):$M.randomBytes(PT),i=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)).seal(n,Vt.fromString(t.message,cy));return f5({type:e,sealed:i,iv:n,senderPublicKey:r})}function Cie(t){let e=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)),{sealed:r,iv:n}=r_(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Vt.toString(i,cy)}function f5(t){if(jh(t.type)===hl){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Vt.toString(Vt.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),ry)}return Vt.toString(Vt.concat([t.type,t.iv,t.sealed]),ry)}function r_(t){let e=Vt.fromString(t,ry),r=e.slice(Aie,kM),n=kM;if(jh(r)===hl){let u=n+t_,a=u+PT,c=e.slice(n,u),f=e.slice(u,a),d=e.slice(a);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+PT,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Nie(t,e){let r=r_(t);return h5({type:jh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Vt.toString(r.senderPublicKey,jr):void 0,receiverPublicKey:e?.receiverPublicKey})}function h5(t){let e=t?.type||e_;if(e===hl){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function xie(t){return t.type===hl&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var d5="irn";function Oie(t){return t?.relay||{protocol:d5}}function Die(t){let e=zee.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Pie=Object.defineProperty,Rie=Object.defineProperties,Bie=Object.getOwnPropertyDescriptors,HM=Object.getOwnPropertySymbols,Mie=Object.prototype.hasOwnProperty,Lie=Object.prototype.propertyIsEnumerable,GM=(t,e,r)=>e in t?Pie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jM=(t,e)=>{for(var r in e||(e={}))Mie.call(e,r)&&GM(t,r,e[r]);if(HM)for(var r of HM(e))Lie.call(e,r)&&GM(t,r,e[r]);return t},Fie=(t,e)=>Rie(t,Bie(e));function g5(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Uie(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=$m.parse(s),u=typeof o.methods=="string"?o.methods.split(","):void 0;return{protocol:n,topic:p5(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:g5(o),methods:u,expiryTimestamp:o.expiryTimestamp?parseInt(o.expiryTimestamp,10):void 0}}function p5(t){return t.startsWith("//")?t.substring(2):t}function m5(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function qie(t){return`${t.protocol}:${t.topic}@${t.version}?`+$m.stringify(jM(Fie(jM({symKey:t.symKey},m5(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}var Vie=Object.defineProperty,kie=Object.defineProperties,Hie=Object.getOwnPropertyDescriptors,zM=Object.getOwnPropertySymbols,Gie=Object.prototype.hasOwnProperty,jie=Object.prototype.propertyIsEnumerable,QM=(t,e,r)=>e in t?Vie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zie=(t,e)=>{for(var r in e||(e={}))Gie.call(e,r)&&QM(t,r,e[r]);if(zM)for(var r of zM(e))jie.call(e,r)&&QM(t,r,e[r]);return t},Qie=(t,e)=>kie(t,Hie(e));function iu(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function y5(t){let e=[];return Object.values(t).forEach(r=>{e.push(...iu(r.accounts))}),e}function w5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.methods)}),r}function v5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.events)}),r}function Kie(t,e){let r=O5(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function Wie(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=RT(e),s=RT(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,w=n[c].events,A=n[c].accounts;f.forEach(T=>{if(!A.some(x=>x.includes(T)))throw new Error(`No accounts provided for chain ${T} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:w,accounts:A}});let u=P5(e,o,"approve()");if(u)throw new Error(u.message);let a={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.chains)==null?void 0:R.includes(T)}),d=n[c].methods.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.methods)==null?void 0:R.includes(T)}),w=n[c].events.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.events)==null?void 0:R.includes(T)}),A=f.map(T=>n[c].accounts.filter(x=>x.includes(`${T}:`))).flat();a[c]={chains:f,methods:d,events:w,accounts:A}}),Object.keys(s).forEach(c=>{var f,d,w,A,T,x;if(!n[c])return;let R=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(L=>n[c].chains.includes(L)),V=n[c].methods.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.methods)==null?void 0:H.includes(L)}),U=n[c].events.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.events)==null?void 0:H.includes(L)}),Q=R?.map(L=>n[c].accounts.filter(k=>k.includes(`${L}:`))).flat();a[c]={chains:Js((w=a[c])==null?void 0:w.chains,R),methods:Js((A=a[c])==null?void 0:A.methods,V),events:Js((T=a[c])==null?void 0:T.events,U),accounts:Js((x=a[c])==null?void 0:x.accounts,Q)}}),a)}function n_(t){return t.includes(":")}function A5(t){return n_(t)?t.split(":")[0]:t}function RT(t){var e,r,n;let i={};if(!ly(t))return i;for(let[s,o]of Object.entries(t)){let u=n_(s)?[s]:o.chains,a=o.methods||[],c=o.events||[],f=A5(s);i[f]=Qie(zie({},i[f]),{chains:Js(u,(e=i[f])==null?void 0:e.chains),methods:Js(a,(r=i[f])==null?void 0:r.methods),events:Js(c,(n=i[f])==null?void 0:n.events)})}return i}function E5(t){let e={};return t?.forEach(r=>{let[n,i]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[]}),e[n].accounts.push(r),e[n].chains.push(`${n}:${i}`)}),e}function $ie(t,e){e=e.map(n=>n.replace("did:pkh:",""));let r=E5(e);for(let[n,i]of Object.entries(r))i.methods?i.methods=Js(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}var b5={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},S5={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ys(t,e){let{message:r,code:n}=S5[t];return{message:e?`${r} ${e}`:r,code:n}}function tu(t,e){let{message:r,code:n}=b5[t];return{message:e?`${r} ${e}`:r,code:n}}function zh(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function ly(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Go(t){return typeof t>"u"}function mn(t,e){return e&&Go(t)?!0:typeof t=="string"&&!!t.trim().length}function fy(t,e){return e&&Go(t)?!0:typeof t=="number"&&!isNaN(t)}function Yie(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Ho(i,n)?(n.forEach(o=>{let{accounts:u,methods:a,events:c}=t.namespaces[o],f=iu(u),d=r[o];(!Ho(iy(o,d),f)||!Ho(d.methods,a)||!Ho(d.events,c))&&(s=!1)}),s):!1}function kh(t){return mn(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function I5(t){if(mn(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&kh(r)}}return!1}function Jie(t){if(mn(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function Xie(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function Zie(t){return t?.topic}function ese(t,e){let r=null;return mn(t?.publicKey,!1)||(r=Ys("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function BT(t){let e=!0;return zh(t)?t.length&&(e=t.every(r=>mn(r,!1))):e=!1,e}function T5(t,e,r){let n=null;return zh(e)&&e.length?e.forEach(i=>{n||kh(i)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):kh(t)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function _5(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=T5(i,iy(i,s),`${e} ${r}`);o&&(n=o)}),n}function C5(t,e){let r=null;return zh(t)?t.forEach(n=>{r||I5(n)||(r=tu("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=tu("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function N5(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=C5(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function x5(t,e){let r=null;return BT(t?.methods)?BT(t?.events)||(r=tu("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=tu("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function i_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=x5(n,`${e}, namespace`);i&&(r=i)}),r}function tse(t,e,r){let n=null;if(t&&ly(t)){let i=i_(t,e);i&&(n=i);let s=_5(t,e,r);s&&(n=s)}else n=Ys("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function O5(t,e){let r=null;if(t&&ly(t)){let n=i_(t,e);n&&(r=n);let i=N5(t,e);i&&(r=i)}else r=Ys("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function D5(t){return mn(t.protocol,!0)}function rse(t,e){let r=!1;return e&&!t?r=!0:t&&zh(t)&&t.length&&t.forEach(n=>{r=D5(n)}),r}function nse(t){return typeof t=="number"}function ise(t){return typeof t<"u"&&typeof t!==null}function sse(t){return!(!t||typeof t!="object"||!t.code||!fy(t.code,!1)||!t.message||!mn(t.message,!1))}function ose(t){return!(Go(t)||!mn(t.method,!1))}function ase(t){return!(Go(t)||Go(t.result)&&Go(t.error)||!fy(t.id,!1)||!mn(t.jsonrpc,!1))}function use(t){return!(Go(t)||!mn(t.name,!1))}function cse(t,e){return!(!kh(e)||!y5(t).includes(e))}function lse(t,e,r){return mn(r,!1)?w5(t,e).includes(r):!1}function fse(t,e,r){return mn(r,!1)?v5(t,e).includes(r):!1}function P5(t,e,r){let n=null,i=hse(t),s=dse(e),o=Object.keys(i),u=Object.keys(s),a=KM(Object.keys(t)),c=KM(Object.keys(e)),f=a.filter(d=>!c.includes(d));return f.length&&(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. +`});var $R=fe(()=>{h();WR();Sm();Lo();DI();Th()});var BI,Cbe,YR=fe(()=>{h();SR();IR();TR();_R();CR();bI();NR();TI();xR();DR();VR();GR();jR();zR();$R();BI={...mI,...yI,...wI,...vI,...AI,...EI,...SI,...II,..._I,...CI},Cbe={...PI,...RI}});function XR(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var JR,MI,UZ,Cm,LI=fe(()=>{h();YR();Am();JR=XR("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),MI=XR("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=jc(t.length);for(let r=0;r{h();LI()});function ns(t,e="utf8"){let r=Cm[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var UI=fe(()=>{h();LI();Eh()});function Ch(t){return Ro(ks(ns(t,Hc),dm))}function Nh(t){return ks(ns(Ai(t),dm),Hc)}function qI(t){let e=ns(wm,Gc),r=ym+ks(Em([e,t]),Gc);return[pm,mm,r].join(gm)}function VI(t){let[e,r,n]=t.split(gm);if(e!==pm||r!==mm)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==ym)throw new Error("Issuer must be a key in mulicodec format");let s=ns(n.slice(1),Gc);if(ks(s.slice(0,2),Gc)!==wm)throw new Error('Issuer must be a public key with type "Ed25519"');let u=s.slice(2);if(u.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return u}function ZR(t){return ks(t,Hc)}function eB(t){return ns(t,Hc)}function kI(t){return ns([Nh(t.header),Nh(t.payload)].join($a),Ah)}function qZ(t){let e=ks(t,Ah).split($a),r=Ch(e[0]),n=Ch(e[1]);return{header:r,payload:n}}function HI(t){return[Nh(t.header),Nh(t.payload),ZR(t.signature)].join($a)}function GI(t){let e=t.split($a),r=Ch(e[0]),n=Ch(e[1]),i=eB(e[2]),s=ns(e.slice(0,2).join($a),Ah);return{header:r,payload:n,signature:i,data:s}}var jI=fe(()=>{h();fI();FI();UI();xc();vm()});function VZ(t=(0,tB.randomBytes)(32)){return Yc.generateKeyPairFromSeed(t)}async function kZ(t,e,r,n,i=(0,rB.fromMiliseconds)(Date.now())){let s={alg:fm,typ:hm},o=qI(n.publicKey),u=i+r,a={iss:o,sub:t,aud:e,iat:i,exp:u},c=kI({header:s,payload:a}),f=Yc.sign(n.secretKey,c);return HI({header:s,payload:a,signature:f})}async function HZ(t){let{header:e,payload:r,data:n,signature:i}=GI(t);if(e.alg!==fm||e.typ!==hm)throw new Error("JWT must use EdDSA algorithm");let s=VI(r.iss);return Yc.verify(s,n,i)}var Yc,tB,rB,nB=fe(()=>{h();Yc=pe(dR()),tB=pe(yh()),rB=pe(za());vm();jI()});var iB=fe(()=>{h()});var sB={};Bt(sB,{DATA_ENCODING:()=>Ah,DID_DELIMITER:()=>gm,DID_METHOD:()=>mm,DID_PREFIX:()=>pm,JSON_ENCODING:()=>dm,JWT_DELIMITER:()=>$a,JWT_ENCODING:()=>Hc,JWT_IRIDIUM_ALG:()=>fm,JWT_IRIDIUM_TYP:()=>hm,KEY_PAIR_SEED_LENGTH:()=>pR,MULTICODEC_ED25519_BASE:()=>ym,MULTICODEC_ED25519_ENCODING:()=>Gc,MULTICODEC_ED25519_HEADER:()=>wm,MULTICODEC_ED25519_LENGTH:()=>gR,decodeData:()=>qZ,decodeIss:()=>VI,decodeJSON:()=>Ch,decodeJWT:()=>GI,decodeSig:()=>eB,encodeData:()=>kI,encodeIss:()=>qI,encodeJSON:()=>Nh,encodeJWT:()=>HI,encodeSig:()=>ZR,generateKeyPair:()=>VZ,signJWT:()=>kZ,verifyJWT:()=>HZ});var oB=fe(()=>{h();nB();vm();iB();jI()});var wB=D(qt=>{"use strict";h();var aB=qt&&qt.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new gB:typeof navigator<"u"?zI(navigator.userAgent):yB()}qt.detect=QZ;function pB(t){return t!==""&&zZ.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function KZ(t){var e=pB(t);return e?e[0]:null}qt.browserName=KZ;function zI(t){var e=pB(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new dB;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getLocalStorage=Ot.getLocalStorageOrThrow=Ot.getCrypto=Ot.getCryptoOrThrow=Ot.getLocation=Ot.getLocationOrThrow=Ot.getNavigator=Ot.getNavigatorOrThrow=Ot.getDocument=Ot.getDocumentOrThrow=Ot.getFromWindowOrThrow=Ot.getFromWindow=void 0;function Ja(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}Ot.getFromWindow=Ja;function Jc(t){let e=Ja(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}Ot.getFromWindowOrThrow=Jc;function $Z(){return Jc("document")}Ot.getDocumentOrThrow=$Z;function YZ(){return Ja("document")}Ot.getDocument=YZ;function JZ(){return Jc("navigator")}Ot.getNavigatorOrThrow=JZ;function XZ(){return Ja("navigator")}Ot.getNavigator=XZ;function ZZ(){return Jc("location")}Ot.getLocationOrThrow=ZZ;function eee(){return Ja("location")}Ot.getLocation=eee;function tee(){return Jc("crypto")}Ot.getCryptoOrThrow=tee;function ree(){return Ja("crypto")}Ot.getCrypto=ree;function nee(){return Jc("localStorage")}Ot.getLocalStorageOrThrow=nee;function iee(){return Ja("localStorage")}Ot.getLocalStorage=iee});var AB=D(Nm=>{"use strict";h();Object.defineProperty(Nm,"__esModule",{value:!0});Nm.getWindowMetadata=void 0;var vB=QI();function see(){let t,e;try{t=vB.getDocumentOrThrow(),e=vB.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),w=[];for(let A=0;A-1){let B=T.getAttribute("href");if(B)if(B.toLowerCase().indexOf("https:")===-1&&B.toLowerCase().indexOf("http:")===-1&&B.indexOf("//")!==0){let V=e.protocol+"//"+e.host;if(B.indexOf("/")===0)V+=B;else{let U=e.pathname.split("/");U.pop();let Q=U.join("/");V+=Q+"/"+B}w.push(V)}else if(B.indexOf("//")===0){let V=e.protocol+B;w.push(V)}else w.push(B)}}return w}function n(...d){let w=t.getElementsByTagName("meta");for(let A=0;AT.getAttribute(B)).filter(B=>B?d.includes(B):!1);if(x.length&&x){let B=T.getAttribute("content");if(B)return B}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),u=s(),a=e.origin,c=r();return{description:u,url:a,icons:c,name:o}}Nm.getWindowMetadata=see});var bB=D((lSe,EB)=>{"use strict";h();EB.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var CB=D((hSe,_B)=>{"use strict";h();var TB="%[a-f0-9]{2}",SB=new RegExp("("+TB+")|([^%]+?)","gi"),IB=new RegExp("("+TB+")+","gi");function KI(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],KI(r),KI(n))}function oee(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(SB)||[],r=1;r{"use strict";h();NB.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var DB=D((mSe,OB)=>{"use strict";h();OB.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";h();var uee=bB(),cee=CB(),RB=xB(),lee=DB(),fee=t=>t==null,WI=Symbol("encodeFragmentIdentifier");function hee(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[",i,"]"].join("")]:[...r,[Zt(e,t),"[",Zt(i,t),"]=",Zt(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[]"].join("")]:[...r,[Zt(e,t),"[]=",Zt(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),":list="].join("")]:[...r,[Zt(e,t),":list=",Zt(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[Zt(r,t),e,Zt(i,t)].join("")]:[[n,Zt(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,Zt(e,t)]:[...r,[Zt(e,t),"=",Zt(n,t)].join("")]}}function dee(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&Hs(n,t).includes(t.arrayFormatSeparator);n=o?Hs(n,t):n;let u=s||o?n.split(t.arrayFormatSeparator).map(a=>Hs(a,t)):n===null?n:Hs(n,t);i[r]=u};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&Hs(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(u=>Hs(u,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function BB(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Zt(t,e){return e.encode?e.strict?uee(t):encodeURIComponent(t):t}function Hs(t,e){return e.decode?cee(t):t}function MB(t){return Array.isArray(t)?t.sort():typeof t=="object"?MB(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function LB(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function gee(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function FB(t){t=LB(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function PB(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function UB(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),BB(e.arrayFormatSeparator);let r=dee(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=RB(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:Hs(o,e),r(Hs(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=PB(s[o],e);else n[i]=PB(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=MB(o):i[s]=o,i},Object.create(null))}nn.extract=FB;nn.parse=UB;nn.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),BB(e.arrayFormatSeparator);let r=o=>e.skipNull&&fee(t[o])||e.skipEmptyString&&t[o]==="",n=hee(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let u=t[o];return u===void 0?"":u===null?Zt(o,e):Array.isArray(u)?u.length===0&&e.arrayFormat==="bracket-separator"?Zt(o,e)+"[]":u.reduce(n(o),[]).join("&"):Zt(o,e)+"="+Zt(u,e)}).filter(o=>o.length>0).join("&")};nn.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=RB(t,"#");return Object.assign({url:r.split("?")[0]||"",query:UB(FB(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:Hs(n,e)}:{})};nn.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[WI]:!0},e);let r=LB(t.url).split("?")[0]||"",n=nn.extract(t.url),i=nn.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=nn.stringify(s,e);o&&(o=`?${o}`);let u=gee(t.url);return t.fragmentIdentifier&&(u=`#${e[WI]?Zt(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${u}`};nn.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[WI]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=nn.parseUrl(t,r);return nn.stringifyUrl({url:n,query:lee(i,e),fragmentIdentifier:s},r)};nn.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return nn.pick(t,n,r)}});var kB=D(xm=>{"use strict";h();Object.defineProperty(xm,"__esModule",{value:!0});var Mr=Uc(),$I=Qn(),pee=20;function mee(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,u=r[3]<<24|r[2]<<16|r[1]<<8|r[0],a=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],w=r[23]<<24|r[22]<<16|r[21]<<8|r[20],A=r[27]<<24|r[26]<<16|r[25]<<8|r[24],T=r[31]<<24|r[30]<<16|r[29]<<8|r[28],x=e[3]<<24|e[2]<<16|e[1]<<8|e[0],B=e[7]<<24|e[6]<<16|e[5]<<8|e[4],V=e[11]<<24|e[10]<<16|e[9]<<8|e[8],U=e[15]<<24|e[14]<<16|e[13]<<8|e[12],Q=n,L=i,k=s,H=o,q=u,v=a,C=c,P=f,F=d,R=w,l=A,g=T,y=x,E=B,I=V,_=U,M=0;M>>16|y<<16,F=F+y|0,q^=F,q=q>>>20|q<<12,L=L+v|0,E^=L,E=E>>>16|E<<16,R=R+E|0,v^=R,v=v>>>20|v<<12,k=k+C|0,I^=k,I=I>>>16|I<<16,l=l+I|0,C^=l,C=C>>>20|C<<12,H=H+P|0,_^=H,_=_>>>16|_<<16,g=g+_|0,P^=g,P=P>>>20|P<<12,k=k+C|0,I^=k,I=I>>>24|I<<8,l=l+I|0,C^=l,C=C>>>25|C<<7,H=H+P|0,_^=H,_=_>>>24|_<<8,g=g+_|0,P^=g,P=P>>>25|P<<7,L=L+v|0,E^=L,E=E>>>24|E<<8,R=R+E|0,v^=R,v=v>>>25|v<<7,Q=Q+q|0,y^=Q,y=y>>>24|y<<8,F=F+y|0,q^=F,q=q>>>25|q<<7,Q=Q+v|0,_^=Q,_=_>>>16|_<<16,l=l+_|0,v^=l,v=v>>>20|v<<12,L=L+C|0,y^=L,y=y>>>16|y<<16,g=g+y|0,C^=g,C=C>>>20|C<<12,k=k+P|0,E^=k,E=E>>>16|E<<16,F=F+E|0,P^=F,P=P>>>20|P<<12,H=H+q|0,I^=H,I=I>>>16|I<<16,R=R+I|0,q^=R,q=q>>>20|q<<12,k=k+P|0,E^=k,E=E>>>24|E<<8,F=F+E|0,P^=F,P=P>>>25|P<<7,H=H+q|0,I^=H,I=I>>>24|I<<8,R=R+I|0,q^=R,q=q>>>25|q<<7,L=L+C|0,y^=L,y=y>>>24|y<<8,g=g+y|0,C^=g,C=C>>>25|C<<7,Q=Q+v|0,_^=Q,_=_>>>24|_<<8,l=l+_|0,v^=l,v=v>>>25|v<<7;Mr.writeUint32LE(Q+n|0,t,0),Mr.writeUint32LE(L+i|0,t,4),Mr.writeUint32LE(k+s|0,t,8),Mr.writeUint32LE(H+o|0,t,12),Mr.writeUint32LE(q+u|0,t,16),Mr.writeUint32LE(v+a|0,t,20),Mr.writeUint32LE(C+c|0,t,24),Mr.writeUint32LE(P+f|0,t,28),Mr.writeUint32LE(F+d|0,t,32),Mr.writeUint32LE(R+w|0,t,36),Mr.writeUint32LE(l+A|0,t,40),Mr.writeUint32LE(g+T|0,t,44),Mr.writeUint32LE(y+x|0,t,48),Mr.writeUint32LE(E+B|0,t,52),Mr.writeUint32LE(I+V|0,t,56),Mr.writeUint32LE(_+U|0,t,60)}function VB(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Om=D(Xc=>{"use strict";h();Object.defineProperty(Xc,"__esModule",{value:!0});function vee(t,e,r){return~(t-1)&e|t-1&r}Xc.select=vee;function Aee(t,e){return(t|0)-(e|0)-1>>>31&1}Xc.lessOrEqual=Aee;function HB(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xc.compare=HB;function Eee(t,e){return t.length===0||e.length===0?!1:HB(t,e)!==0}Xc.equal=Eee});var jB=D(Gs=>{"use strict";h();Object.defineProperty(Gs,"__esModule",{value:!0});var bee=Om(),Dm=Qn();Gs.DIGEST_LENGTH=16;var GB=function(){function t(e){this.digestLength=Gs.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var u=e[10]|e[11]<<8;this._r[6]=(o>>>14|u<<2)&8191;var a=e[12]|e[13]<<8;this._r[7]=(u>>>11|a<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(a>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],u=this._h[2],a=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],w=this._h[7],A=this._h[8],T=this._h[9],x=this._r[0],B=this._r[1],V=this._r[2],U=this._r[3],Q=this._r[4],L=this._r[5],k=this._r[6],H=this._r[7],q=this._r[8],v=this._r[9];n>=16;){var C=e[r+0]|e[r+1]<<8;s+=C&8191;var P=e[r+2]|e[r+3]<<8;o+=(C>>>13|P<<3)&8191;var F=e[r+4]|e[r+5]<<8;u+=(P>>>10|F<<6)&8191;var R=e[r+6]|e[r+7]<<8;a+=(F>>>7|R<<9)&8191;var l=e[r+8]|e[r+9]<<8;c+=(R>>>4|l<<12)&8191,f+=l>>>1&8191;var g=e[r+10]|e[r+11]<<8;d+=(l>>>14|g<<2)&8191;var y=e[r+12]|e[r+13]<<8;w+=(g>>>11|y<<5)&8191;var E=e[r+14]|e[r+15]<<8;A+=(y>>>8|E<<8)&8191,T+=E>>>5|i;var I=0,_=I;_+=s*x,_+=o*(5*v),_+=u*(5*q),_+=a*(5*H),_+=c*(5*k),I=_>>>13,_&=8191,_+=f*(5*L),_+=d*(5*Q),_+=w*(5*U),_+=A*(5*V),_+=T*(5*B),I+=_>>>13,_&=8191;var M=I;M+=s*B,M+=o*x,M+=u*(5*v),M+=a*(5*q),M+=c*(5*H),I=M>>>13,M&=8191,M+=f*(5*k),M+=d*(5*L),M+=w*(5*Q),M+=A*(5*U),M+=T*(5*V),I+=M>>>13,M&=8191;var N=I;N+=s*V,N+=o*B,N+=u*x,N+=a*(5*v),N+=c*(5*q),I=N>>>13,N&=8191,N+=f*(5*H),N+=d*(5*k),N+=w*(5*L),N+=A*(5*Q),N+=T*(5*U),I+=N>>>13,N&=8191;var m=I;m+=s*U,m+=o*V,m+=u*B,m+=a*x,m+=c*(5*v),I=m>>>13,m&=8191,m+=f*(5*q),m+=d*(5*H),m+=w*(5*k),m+=A*(5*L),m+=T*(5*Q),I+=m>>>13,m&=8191;var O=I;O+=s*Q,O+=o*U,O+=u*V,O+=a*B,O+=c*x,I=O>>>13,O&=8191,O+=f*(5*v),O+=d*(5*q),O+=w*(5*H),O+=A*(5*k),O+=T*(5*L),I+=O>>>13,O&=8191;var Y=I;Y+=s*L,Y+=o*Q,Y+=u*U,Y+=a*V,Y+=c*B,I=Y>>>13,Y&=8191,Y+=f*x,Y+=d*(5*v),Y+=w*(5*q),Y+=A*(5*H),Y+=T*(5*k),I+=Y>>>13,Y&=8191;var $=I;$+=s*k,$+=o*L,$+=u*Q,$+=a*U,$+=c*V,I=$>>>13,$&=8191,$+=f*B,$+=d*x,$+=w*(5*v),$+=A*(5*q),$+=T*(5*H),I+=$>>>13,$&=8191;var b=I;b+=s*H,b+=o*k,b+=u*L,b+=a*Q,b+=c*U,I=b>>>13,b&=8191,b+=f*V,b+=d*B,b+=w*x,b+=A*(5*v),b+=T*(5*q),I+=b>>>13,b&=8191;var j=I;j+=s*q,j+=o*H,j+=u*k,j+=a*L,j+=c*Q,I=j>>>13,j&=8191,j+=f*U,j+=d*V,j+=w*B,j+=A*x,j+=T*(5*v),I+=j>>>13,j&=8191;var z=I;z+=s*v,z+=o*q,z+=u*H,z+=a*k,z+=c*L,I=z>>>13,z&=8191,z+=f*Q,z+=d*U,z+=w*V,z+=A*B,z+=T*x,I+=z>>>13,z&=8191,I=(I<<2)+I|0,I=I+_|0,_=I&8191,I=I>>>13,M+=I,s=_,o=M,u=N,a=m,c=O,f=Y,d=$,w=b,A=j,T=z,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=u,this._h[3]=a,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=w,this._h[8]=A,this._h[9]=T},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,u;if(this._leftover){for(u=this._leftover,this._buffer[u++]=1;u<16;u++)this._buffer[u]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,u=2;u<10;u++)this._h[u]+=i,i=this._h[u]>>>13,this._h[u]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,u=1;u<10;u++)n[u]=this._h[u]+i,i=n[u]>>>13,n[u]&=8191;for(n[9]-=8192,s=(i^1)-1,u=0;u<10;u++)n[u]&=s;for(s=~s,u=0;u<10;u++)this._h[u]=this._h[u]&s|n[u];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,u=1;u<8;u++)o=(this._h[u]+this._pad[u]|0)+(o>>>16)|0,this._h[u]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";h();Object.defineProperty(js,"__esModule",{value:!0});var Pm=kB(),Tee=jB(),xh=Qn(),zB=Uc(),_ee=Om();js.KEY_LENGTH=32;js.NONCE_LENGTH=12;js.TAG_LENGTH=16;var QB=new Uint8Array(16),Cee=function(){function t(e){if(this.nonceLength=js.NONCE_LENGTH,this.tagLength=js.TAG_LENGTH,e.length!==js.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Pm.stream(this._key,s,o,4);var u=r.length+this.tagLength,a;if(i){if(i.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");a=i}else a=new Uint8Array(u);return Pm.streamXOR(this._key,s,r,a,4),this._authenticate(a.subarray(a.length-this.tagLength,a.length),o,a.subarray(0,a.length-this.tagLength),n),xh.wipe(s),a},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(QB.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(QB.subarray(n.length%16));var o=new Uint8Array(8);i&&zB.writeUint64LE(i.length,o),s.update(o),zB.writeUint64LE(n.length,o),s.update(o);for(var u=s.digest(),a=0;a{"use strict";h();Object.defineProperty(YI,"__esModule",{value:!0});function Nee(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}YI.isSerializableHash=Nee});var YB=D(Oh=>{"use strict";h();Object.defineProperty(Oh,"__esModule",{value:!0});var is=WB(),xee=Om(),Oee=Qn(),$B=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";h();Object.defineProperty(JI,"__esModule",{value:!0});var JB=YB(),XB=Qn(),Pee=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=JB.hmac(this._hash,n,r);this._hmac=new JB.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";h();Object.defineProperty(Uo,"__esModule",{value:!0});var Bm=Uc(),Rm=Qn();Uo.DIGEST_LENGTH=32;Uo.BLOCK_SIZE=64;var eM=function(){function t(){this.digestLength=Uo.DIGEST_LENGTH,this.blockSize=Uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Rm.wipe(this._buffer),Rm.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(XI(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=XI(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Rm.wipe(e.state),e.buffer&&Rm.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Uo.SHA256=eM;var Ree=new Int32Array([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]);function XI(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],u=e[2],a=e[3],c=e[4],f=e[5],d=e[6],w=e[7],A=0;A<16;A++){var T=n+A*4;t[A]=Bm.readUint32BE(r,T)}for(var A=16;A<64;A++){var x=t[A-2],B=(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10;x=t[A-15];var V=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3;t[A]=(B+t[A-7]|0)+(V+t[A-16]|0)}for(var A=0;A<64;A++){var B=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(w+(Ree[A]+t[A]|0)|0)|0,V=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&u^o&u)|0;w=d,d=f,f=c,c=a+B|0,a=u,u=o,o=s,s=B+V|0}e[0]+=s,e[1]+=o,e[2]+=u,e[3]+=a,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=w,n+=64,i-=64}return n}function Bee(t){var e=new eM;e.update(t);var r=e.digest();return e.clean(),r}Uo.hash=Bee});var sM=D(zt=>{"use strict";h();Object.defineProperty(zt,"__esModule",{value:!0});zt.sharedKey=zt.generateKeyPair=zt.generateKeyPairFromSeed=zt.scalarMultBase=zt.scalarMult=zt.SHARED_KEY_LENGTH=zt.SECRET_KEY_LENGTH=zt.PUBLIC_KEY_LENGTH=void 0;var Mee=yh(),Lee=Qn();zt.PUBLIC_KEY_LENGTH=32;zt.SECRET_KEY_LENGTH=32;zt.SHARED_KEY_LENGTH=32;function ss(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Dh(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function qee(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Mm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Lm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function zs(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,B=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,P=0,F=0,R=0,l=0,g=0,y=0,E=0,I=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,B+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,B+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,B+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,B+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,B+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,B+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,B+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,P+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,B+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,P+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,B+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,P+=n*oe,F+=n*J,R+=n*ue,n=e[9],T+=n*N,x+=n*m,B+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,P+=n*se,F+=n*oe,R+=n*J,l+=n*ue,n=e[10],x+=n*N,B+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,P+=n*ee,F+=n*se,R+=n*oe,l+=n*J,g+=n*ue,n=e[11],B+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,P+=n*te,F+=n*ee,R+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,P+=n*ie,F+=n*te,R+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,P+=n*W,F+=n*ie,R+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,I+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,P+=n*z,F+=n*W,R+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,I+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,P+=n*j,F+=n*z,R+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,I+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*P,d+=38*F,w+=38*R,A+=38*l,T+=38*g,x+=38*y,B+=38*E,V+=38*I,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=B,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ph(t,e){zs(t,e,e)}function Vee(t,e){let r=ss();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)Ph(r,r),n!==2&&n!==4&&zs(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function eT(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=ss(),s=ss(),o=ss(),u=ss(),a=ss(),c=ss();for(let A=0;A<31;A++)r[A]=t[A];r[31]=t[31]&127|64,r[0]&=248,qee(n,e);for(let A=0;A<16;A++)s[A]=n[A];i[0]=u[0]=1;for(let A=254;A>=0;--A){let T=r[A>>>3]>>>(A&7)&1;Dh(i,s,T),Dh(o,u,T),Mm(a,i,o),Lm(i,i,o),Mm(o,s,u),Lm(s,s,u),Ph(u,a),Ph(c,i),zs(i,o,i),zs(o,s,a),Mm(a,i,o),Lm(i,i,o),Ph(s,i),Lm(o,u,c),zs(i,o,Fee),Mm(i,i,u),zs(o,o,i),zs(i,u,c),zs(u,s,n),Ph(s,a),Dh(i,s,T),Dh(o,u,T)}for(let A=0;A<16;A++)n[A+16]=i[A],n[A+32]=o[A],n[A+48]=s[A],n[A+64]=u[A];let f=n.subarray(32),d=n.subarray(16);Vee(f,f),zs(d,d,f);let w=new Uint8Array(32);return Uee(w,d),w}zt.scalarMult=eT;function nM(t){return eT(t,rM)}zt.scalarMultBase=nM;function iM(t){if(t.length!==zt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${zt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:nM(e),secretKey:e}}zt.generateKeyPairFromSeed=iM;function kee(t){let e=(0,Mee.randomBytes)(32,t),r=iM(e);return(0,Lee.wipe)(e),r}zt.generateKeyPair=kee;function Hee(t,e,r=!1){if(t.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=eT(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{h()});function uM(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{h()});function lM(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=jc(t.length);for(let n=0;n{h();Am();Eh()});var tT={};Bt(tT,{compare:()=>oM,concat:()=>Em,equals:()=>uM,fromString:()=>ns,toString:()=>ks,xor:()=>lM});var rT=fe(()=>{h();aM();fI();cM();UI();FI();fM()});var hM={};Bt(hM,{RELAY_JSONRPC:()=>ete,isPublishMethod:()=>sT,isPublishParams:()=>oT,isPublishRequest:()=>Kee,isSubscribeMethod:()=>nT,isSubscribeParams:()=>iT,isSubscribeRequest:()=>Qee,isSubscriptionMethod:()=>cT,isSubscriptionParams:()=>lT,isSubscriptionRequest:()=>$ee,isUnsubscribeMethod:()=>aT,isUnsubscribeParams:()=>uT,isUnsubscribeRequest:()=>Wee,parsePublishRequest:()=>Jee,parseSubscribeRequest:()=>Yee,parseSubscriptionRequest:()=>Zee,parseUnsubscribeRequest:()=>Xee});function Xa(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function Gee(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function jee(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function zee(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function Fm(t,e,r){return(r.length?zee(t,e.length):jee(t,e.length))?Gee(t,e):!1}function Um(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}function Qee(t){return nT(t.method)&&iT(t.params)}function nT(t){return Um(t,"subscribe")}function iT(t){return Fm(t,["topic"],[])}function Kee(t){return sT(t.method)&&oT(t.params)}function sT(t){return Um(t,"publish")}function oT(t){return Fm(t,["message","topic","ttl"],["prompt","tag"])}function Wee(t){return aT(t.method)&&uT(t.params)}function aT(t){return Um(t,"unsubscribe")}function uT(t){return Fm(t,["id","topic"],[])}function $ee(t){return cT(t.method)&&lT(t.params)}function cT(t){return Um(t,"subscription")}function lT(t){return Fm(t,["id","data"],[])}function Yee(t){if(!nT(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!iT(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Xa(e,"topic"),e}function Jee(t){if(!sT(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!oT(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Xa(e,"topic"),Xa(e,"message"),Xa(e,"ttl","number"),e}function Xee(t){if(!aT(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!uT(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Xa(e,"id"),e}function Zee(t){if(!cT(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!lT(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Xa(e,"id"),Xa(e,"data"),e}var ete,dM=fe(()=>{h();ete={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var Qh=D(K=>{"use strict";h();Object.defineProperty(K,"__esModule",{value:!0});var tte=wB(),el=za(),il=QI(),rte=AB(),nte=qB(),KM=KB(),ite=ZB(),WM=yh(),FT=tM(),ste=sM(),Vt=(rT(),_e(tT)),ote=(dM(),_e(hM));function $M(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var Km=$M(nte),YM=$M(ste),ty=":";function JM(t){let[e,r]=t.split(ty);return{namespace:e,reference:r}}function XM(t){let{namespace:e,reference:r}=t;return[e,r].join(ty)}function UT(t){let[e,r,n]=t.split(ty);return{namespace:e,reference:r,address:n}}function ZM(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(ty)}function qT(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function e4(t){let{address:e}=UT(t);return e}function t4(t){let{namespace:e,reference:r}=UT(t);return XM({namespace:e,reference:r})}function ate(t,e){let{namespace:r,reference:n}=JM(e);return ZM({namespace:r,reference:n,address:t})}function ute(t){return qT(t,e4)}function r4(t){return qT(t,t4)}function cte(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function lte(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...r4(i.accounts))}),r}function fte(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...ry(n,i))}),r}function ry(t,e){return t.includes(":")?[t]:e.chains||[]}var hte=Object.defineProperty,gM=Object.getOwnPropertySymbols,dte=Object.prototype.hasOwnProperty,gte=Object.prototype.propertyIsEnumerable,pM=(t,e,r)=>e in t?hte(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mM=(t,e)=>{for(var r in e||(e={}))dte.call(e,r)&&pM(t,r,e[r]);if(gM)for(var r of gM(e))gte.call(e,r)&&pM(t,r,e[r]);return t},n4="ReactNative",Gr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wm=" ",pte=":",i4="/",VT=2,mte=1e3,s4="js";function kT(){return typeof S.default<"u"&&typeof S.default.versions<"u"&&typeof S.default.versions.node<"u"}function al(){return!il.getDocument()&&!!il.getNavigator()&&navigator.product===n4}function Hh(){return!kT()&&!!il.getNavigator()&&!!il.getDocument()}function tu(){return al()?Gr.reactNative:kT()?Gr.node:Hh()?Gr.browser:Gr.unknown}function yte(){var t;try{return al()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function o4(t,e){let r=Km.parse(t);return r=mM(mM({},r),e),t=Km.stringify(r),t}function wte(){return rte.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function vte(t,e){var r;let n=tu(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=il.getLocation())==null?void 0:r.host)||"unknown"),i}function a4(){if(tu()===Gr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=tte.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function u4(){var t;let e=tu();return e===Gr.browser?[e,((t=il.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function c4(t,e,r){let n=a4(),i=u4();return[[t,e].join("-"),[s4,r].join("-"),n,i].join("/")}function Ate({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:u}){let a=r.split("?"),c=c4(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:u||void 0},d=o4(a[1]||"",f);return a[0]+"?"+d}function Ete(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function bte(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function l4(t,e=VT){return f4(t.split(i4),e)}function Ste(t){return l4(t).join(Wm)}function Ho(t,e){return t.filter(r=>e.includes(r)).length===t.length}function f4(t,e=VT){return t.slice(Math.max(t.length-e,0))}function Ite(t){return Object.fromEntries(t.entries())}function Tte(t){return new Map(Object.entries(t))}function _te(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var Cte=t=>t;function h4(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function Nte(t){return t.split(Wm).map(e=>h4(e)).join(Wm)}function xte(t=el.FIVE_MINUTES,e){let r=el.toMiliseconds(t||el.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,u)=>{s=setTimeout(()=>{u(new Error(e))},r),n=o,i=u})}}function Ote(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function HT(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Dte(t){return HT("topic",t)}function Pte(t){return HT("id",t)}function Rte(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function Bte(t,e){return el.fromMiliseconds((e||Date.now())+el.toMiliseconds(t))}function Mte(t){return Date.now()>=el.toMiliseconds(t)}function Lte(t,e){return`${t}${e?`:${e}`:""}`}function Js(t=[],e=[]){return[...new Set([...t,...e])]}async function Fte({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=tu();o===Gr.browser?s.startsWith("https://")||s.startsWith("http://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===Gr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function Ute(t,e){try{return await t.getItem(e)||(Hh()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}function _T(t,e){return t.filter(r=>e.includes(r))}var d4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qte(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var g4={exports:{}};(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!i.JS_SHA3_NO_NODE_JS&&typeof S.default=="object"&&S.default.versions&&S.default.versions.node;o?i=d4:s&&(i=self);var u=!i.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),f=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],w=[1,256,65536,16777216],A=[6,1536,393216,100663296],T=[0,8,16,24],x=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],B=[224,256,384,512],V=[128,256],U=["hex","buffer","arrayBuffer","array","digest"],Q={128:168,256:136};(i.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(b){return Object.prototype.toString.call(b)==="[object Array]"}),a&&(i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(b){return typeof b=="object"&&b.buffer&&b.buffer.constructor===ArrayBuffer});for(var L=function(b,j,z){return function(W){return new O(b,j,b).update(W)[z]()}},k=function(b,j,z){return function(W,ie){return new O(b,j,ie).update(W)[z]()}},H=function(b,j,z){return function(W,ie,te,ee){return g["cshake"+b].update(W,ie,te,ee)[z]()}},q=function(b,j,z){return function(W,ie,te,ee){return g["kmac"+b].update(W,ie,te,ee)[z]()}},v=function(b,j,z,W){for(var ie=0;ie>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var W=0;W<50;++W)this.s[W]=0}O.prototype.update=function(b){if(this.finalized)throw new Error(r);var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}for(var W=this.blocks,ie=this.byteCount,te=b.length,ee=this.blockCount,se=0,oe=this.s,J,ue;se>2]|=b[se]<>2]|=ue<>2]|=(192|ue>>6)<>2]|=(128|ue&63)<=57344?(W[J>>2]|=(224|ue>>12)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<>2]|=(240|ue>>18)<>2]|=(128|ue>>12&63)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<=ie){for(this.start=J-ie,this.block=W[ee],J=0;J>8,z=b&255;z>0;)ie.unshift(z),b=b>>8,z=b&255,++W;return j?ie.push(W):ie.unshift(W),this.update(ie),ie.length},O.prototype.encodeString=function(b){var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}var W=0,ie=b.length;if(j)W=ie;else for(var te=0;te=57344?W+=3:(ee=65536+((ee&1023)<<10|b.charCodeAt(++te)&1023),W+=4)}return W+=this.encode(W*8),this.update(b),W},O.prototype.bytepad=function(b,j){for(var z=this.encode(j),W=0;W>2]|=this.padding[j&3],this.lastByteIndex===this.byteCount)for(b[0]=b[z],j=1;j>4&15]+c[se&15]+c[se>>12&15]+c[se>>8&15]+c[se>>20&15]+c[se>>16&15]+c[se>>28&15]+c[se>>24&15];te%b===0&&($(j),ie=0)}return W&&(se=j[ie],ee+=c[se>>4&15]+c[se&15],W>1&&(ee+=c[se>>12&15]+c[se>>8&15]),W>2&&(ee+=c[se>>20&15]+c[se>>16&15])),ee},O.prototype.arrayBuffer=function(){this.finalize();var b=this.blockCount,j=this.s,z=this.outputBlocks,W=this.extraBytes,ie=0,te=0,ee=this.outputBits>>3,se;W?se=new ArrayBuffer(z+1<<2):se=new ArrayBuffer(ee);for(var oe=new Uint32Array(se);te>8&255,ee[se+2]=oe>>16&255,ee[se+3]=oe>>24&255;te%b===0&&$(j)}return W&&(se=te<<2,oe=j[ie],ee[se]=oe&255,W>1&&(ee[se+1]=oe>>8&255),W>2&&(ee[se+2]=oe>>16&255)),ee};function Y(b,j,z){O.call(this,b,j,z)}Y.prototype=new O,Y.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var $=function(b){var j,z,W,ie,te,ee,se,oe,J,ue,wt,vt,Ni,At,Et,xi,bt,St,Oi,It,Tt,Di,Qe,Ke,ri,We,$e,ni,Ye,Je,ii,Xe,Ze,si,et,tt,oi,rt,nt,ai,it,st,ui,ot,at,ci,ut,ct,li,lt,ft,fi,ht,dt,hi,gt,pt,vn,An,En,bn,Sn,In;for(W=0;W<48;W+=2)ie=b[0]^b[10]^b[20]^b[30]^b[40],te=b[1]^b[11]^b[21]^b[31]^b[41],ee=b[2]^b[12]^b[22]^b[32]^b[42],se=b[3]^b[13]^b[23]^b[33]^b[43],oe=b[4]^b[14]^b[24]^b[34]^b[44],J=b[5]^b[15]^b[25]^b[35]^b[45],ue=b[6]^b[16]^b[26]^b[36]^b[46],wt=b[7]^b[17]^b[27]^b[37]^b[47],vt=b[8]^b[18]^b[28]^b[38]^b[48],Ni=b[9]^b[19]^b[29]^b[39]^b[49],j=vt^(ee<<1|se>>>31),z=Ni^(se<<1|ee>>>31),b[0]^=j,b[1]^=z,b[10]^=j,b[11]^=z,b[20]^=j,b[21]^=z,b[30]^=j,b[31]^=z,b[40]^=j,b[41]^=z,j=ie^(oe<<1|J>>>31),z=te^(J<<1|oe>>>31),b[2]^=j,b[3]^=z,b[12]^=j,b[13]^=z,b[22]^=j,b[23]^=z,b[32]^=j,b[33]^=z,b[42]^=j,b[43]^=z,j=ee^(ue<<1|wt>>>31),z=se^(wt<<1|ue>>>31),b[4]^=j,b[5]^=z,b[14]^=j,b[15]^=z,b[24]^=j,b[25]^=z,b[34]^=j,b[35]^=z,b[44]^=j,b[45]^=z,j=oe^(vt<<1|Ni>>>31),z=J^(Ni<<1|vt>>>31),b[6]^=j,b[7]^=z,b[16]^=j,b[17]^=z,b[26]^=j,b[27]^=z,b[36]^=j,b[37]^=z,b[46]^=j,b[47]^=z,j=ue^(ie<<1|te>>>31),z=wt^(te<<1|ie>>>31),b[8]^=j,b[9]^=z,b[18]^=j,b[19]^=z,b[28]^=j,b[29]^=z,b[38]^=j,b[39]^=z,b[48]^=j,b[49]^=z,At=b[0],Et=b[1],ci=b[11]<<4|b[10]>>>28,ut=b[10]<<4|b[11]>>>28,ni=b[20]<<3|b[21]>>>29,Ye=b[21]<<3|b[20]>>>29,En=b[31]<<9|b[30]>>>23,bn=b[30]<<9|b[31]>>>23,st=b[40]<<18|b[41]>>>14,ui=b[41]<<18|b[40]>>>14,si=b[2]<<1|b[3]>>>31,et=b[3]<<1|b[2]>>>31,xi=b[13]<<12|b[12]>>>20,bt=b[12]<<12|b[13]>>>20,ct=b[22]<<10|b[23]>>>22,li=b[23]<<10|b[22]>>>22,Je=b[33]<<13|b[32]>>>19,ii=b[32]<<13|b[33]>>>19,Sn=b[42]<<2|b[43]>>>30,In=b[43]<<2|b[42]>>>30,dt=b[5]<<30|b[4]>>>2,hi=b[4]<<30|b[5]>>>2,tt=b[14]<<6|b[15]>>>26,oi=b[15]<<6|b[14]>>>26,St=b[25]<<11|b[24]>>>21,Oi=b[24]<<11|b[25]>>>21,lt=b[34]<<15|b[35]>>>17,ft=b[35]<<15|b[34]>>>17,Xe=b[45]<<29|b[44]>>>3,Ze=b[44]<<29|b[45]>>>3,Ke=b[6]<<28|b[7]>>>4,ri=b[7]<<28|b[6]>>>4,gt=b[17]<<23|b[16]>>>9,pt=b[16]<<23|b[17]>>>9,rt=b[26]<<25|b[27]>>>7,nt=b[27]<<25|b[26]>>>7,It=b[36]<<21|b[37]>>>11,Tt=b[37]<<21|b[36]>>>11,fi=b[47]<<24|b[46]>>>8,ht=b[46]<<24|b[47]>>>8,ot=b[8]<<27|b[9]>>>5,at=b[9]<<27|b[8]>>>5,We=b[18]<<20|b[19]>>>12,$e=b[19]<<20|b[18]>>>12,vn=b[29]<<7|b[28]>>>25,An=b[28]<<7|b[29]>>>25,ai=b[38]<<8|b[39]>>>24,it=b[39]<<8|b[38]>>>24,Di=b[48]<<14|b[49]>>>18,Qe=b[49]<<14|b[48]>>>18,b[0]=At^~xi&St,b[1]=Et^~bt&Oi,b[10]=Ke^~We&ni,b[11]=ri^~$e&Ye,b[20]=si^~tt&rt,b[21]=et^~oi&nt,b[30]=ot^~ci&ct,b[31]=at^~ut&li,b[40]=dt^~gt&vn,b[41]=hi^~pt&An,b[2]=xi^~St&It,b[3]=bt^~Oi&Tt,b[12]=We^~ni&Je,b[13]=$e^~Ye&ii,b[22]=tt^~rt&ai,b[23]=oi^~nt&it,b[32]=ci^~ct<,b[33]=ut^~li&ft,b[42]=gt^~vn&En,b[43]=pt^~An&bn,b[4]=St^~It&Di,b[5]=Oi^~Tt&Qe,b[14]=ni^~Je&Xe,b[15]=Ye^~ii&Ze,b[24]=rt^~ai&st,b[25]=nt^~it&ui,b[34]=ct^~lt&fi,b[35]=li^~ft&ht,b[44]=vn^~En&Sn,b[45]=An^~bn&In,b[6]=It^~Di&At,b[7]=Tt^~Qe&Et,b[16]=Je^~Xe&Ke,b[17]=ii^~Ze&ri,b[26]=ai^~st&si,b[27]=it^~ui&et,b[36]=lt^~fi&ot,b[37]=ft^~ht&at,b[46]=En^~Sn&dt,b[47]=bn^~In&hi,b[8]=Di^~At&xi,b[9]=Qe^~Et&bt,b[18]=Xe^~Ke&We,b[19]=Ze^~ri&$e,b[28]=st^~si&tt,b[29]=ui^~et&oi,b[38]=fi^~ot&ci,b[39]=ht^~at&ut,b[48]=Sn^~dt>,b[49]=In^~hi&pt,b[0]^=x[W],b[1]^=x[W+1]};if(u)t.exports=g;else for(E=0;E{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken implementation")}catch(t){return t.message}return null}var AM=Hte(),CT;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(CT||(CT={}));var Si;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Si||(Si={}));var EM="0123456789abcdef",kt=class t{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){let n=e.toLowerCase();jm[n]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(vM>jm[n])&&console.log.apply(console,r)}debug(...e){this._log(t.levels.DEBUG,e)}info(...e){this._log(t.levels.INFO,e)}warn(...e){this._log(t.levels.WARNING,e)}makeError(e,r,n){if(wM)return this.makeError("censored error",r,{});r||(r=t.errors.UNKNOWN_ERROR),n||(n={});let i=[];Object.keys(n).forEach(a=>{let c=n[a];try{if(c instanceof Uint8Array){let f="";for(let d=0;d>4],f+=EM[c[d]&15];i.push(a+"=Uint8Array(0x"+f+")")}else i.push(a+"="+JSON.stringify(c))}catch{i.push(a+"="+JSON.stringify(n[a].toString()))}}),i.push(`code=${r}`),i.push(`version=${this.version}`);let s=e,o="";switch(r){case Si.NUMERIC_FAULT:{o="NUMERIC_FAULT";let a=e;switch(a){case"overflow":case"underflow":case"division-by-zero":o+="-"+a;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Si.CALL_EXCEPTION:case Si.INSUFFICIENT_FUNDS:case Si.MISSING_NEW:case Si.NONCE_EXPIRED:case Si.REPLACEMENT_UNDERPRICED:case Si.TRANSACTION_REPLACED:case Si.UNPREDICTABLE_GAS_LIMIT:o=r;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),i.length&&(e+=" ("+i.join(", ")+")");let u=new Error(e);return u.reason=s,u.code=r,Object.keys(n).forEach(function(a){u[a]=n[a]}),u}throwError(e,r,n){throw this.makeError(e,r,n)}throwArgumentError(e,r,n){return this.throwError(e,t.errors.INVALID_ARGUMENT,{argument:r,value:n})}assert(e,r,n,i){e||this.throwError(r,n,i)}assertArgument(e,r,n,i){e||this.throwArgumentError(r,n,i)}checkNormalize(e){AM&&this.throwError("platform missing String.prototype.normalize",t.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:AM})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,n){n?n=": "+n:n="",er&&this.throwError("too many arguments"+n,t.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",t.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return fT||(fT=new t(kte)),fT}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),yM){if(!e)return;this.globalLogger().throwError("error censorship permanent",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}wM=!!e,yM=!!r}static setLogLevel(e){let r=jm[e.toLowerCase()];if(r==null){t.globalLogger().warn("invalid log level - "+e);return}vM=r}static from(e){return new t(e)}};kt.errors=Si,kt.levels=CT;var Gte="bytes/5.7.0",er=new kt(Gte);function p4(t){return!!t.toHexString}function tl(t){return t.slice||(t.slice=function(){let e=Array.prototype.slice.call(arguments);return tl(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function jte(t){return gn(t)&&!(t.length%2)||ul(t)}function bM(t){return typeof t=="number"&&t==t&&t%1===0}function ul(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!bM(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function Qt(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid arrayify value");let r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),tl(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),p4(t)&&(t=t.toHexString()),gn(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":er.throwArgumentError("hex data is odd-length","value",t));let n=[];for(let i=0;iQt(i)),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);return e.reduce((i,s)=>(n.set(s,i),i+s.length),0),tl(n)}function Qte(t,e){t=Qt(t),t.length>e&&er.throwArgumentError("value out of range","value",arguments[0]);let r=new Uint8Array(e);return r.set(t,e-t.length),tl(r)}function gn(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}var hT="0123456789abcdef";function kr(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=hT[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),p4(t))return t.toHexString();if(gn(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":er.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(ul(t)){let r="0x";for(let n=0;n>4]+hT[i&15]}return r}return er.throwArgumentError("invalid hexlify value","value",t)}function Kte(t){if(typeof t!="string")t=kr(t);else if(!gn(t)||t.length%2)return null;return(t.length-2)/2}function SM(t,e,r){return typeof t!="string"?t=kr(t):(!gn(t)||t.length%2)&&er.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function fs(t,e){for(typeof t!="string"?t=kr(t):gn(t)||er.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&er.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function m4(t){let e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(jte(t)){let r=Qt(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64))):r.length===65?(e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64)),e.v=r[64]):er.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:er.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=kr(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){let i=Qte(Qt(e._vs),32);e._vs=kr(i);let s=i[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&er.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),i[0]&=127;let o=kr(i);e.s==null?e.s=o:e.s!==o&&er.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?er.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{let i=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==i&&er.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!gn(e.r)?er.throwArgumentError("signature missing or invalid r","signature",t):e.r=fs(e.r,32),e.s==null||!gn(e.s)?er.throwArgumentError("signature missing or invalid s","signature",t):e.s=fs(e.s,32);let r=Qt(e.s);r[0]>=128&&er.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);let n=kr(r);e._vs&&(gn(e._vs)||er.throwArgumentError("signature invalid _vs","signature",t),e._vs=fs(e._vs,32)),e._vs==null?e._vs=n:e._vs!==n&&er.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function GT(t){return"0x"+Vte.keccak_256(Qt(t))}var y4={exports:{}},Wte={},$te=Object.freeze({__proto__:null,default:Wte}),Yte=qte($te);(function(t){(function(e,r){function n(l,g){if(!l)throw new Error(g||"Assertion failed")}function i(l,g){l.super_=g;var y=function(){};y.prototype=g.prototype,l.prototype=new y,l.prototype.constructor=l}function s(l,g,y){if(s.isBN(l))return l;this.negative=0,this.words=null,this.length=0,this.red=null,l!==null&&((g==="le"||g==="be")&&(y=g,g=10),this._init(l||0,g||10,y||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Yte.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,g){return l.cmp(g)>0?l:g},s.min=function(l,g){return l.cmp(g)<0?l:g},s.prototype._init=function(l,g,y){if(typeof l=="number")return this._initNumber(l,g,y);if(typeof l=="object")return this._initArray(l,g,y);g==="hex"&&(g=16),n(g===(g|0)&&g>=2&&g<=36),l=l.toString().replace(/\s+/g,"");var E=0;l[0]==="-"&&(E++,this.negative=1),E=0;E-=3)_=l[E]|l[E-1]<<8|l[E-2]<<16,this.words[I]|=_<>>26-M&67108863,M+=24,M>=26&&(M-=26,I++);else if(y==="le")for(E=0,I=0;E>>26-M&67108863,M+=24,M>=26&&(M-=26,I++);return this._strip()};function u(l,g){var y=l.charCodeAt(g);if(y>=48&&y<=57)return y-48;if(y>=65&&y<=70)return y-55;if(y>=97&&y<=102)return y-87;n(!1,"Invalid character in "+l)}function a(l,g,y){var E=u(l,y);return y-1>=g&&(E|=u(l,y-1)<<4),E}s.prototype._parseHex=function(l,g,y){this.length=Math.ceil((l.length-g)/6),this.words=new Array(this.length);for(var E=0;E=g;E-=2)M=a(l,g,E)<=18?(I-=18,_+=1,this.words[_]|=M>>>26):I+=8;else{var N=l.length-g;for(E=N%2===0?g+1:g;E=18?(I-=18,_+=1,this.words[_]|=M>>>26):I+=8}this._strip()};function c(l,g,y,E){for(var I=0,_=0,M=Math.min(l.length,y),N=g;N=49?_=m-49+10:m>=17?_=m-17+10:_=m,n(m>=0&&_1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch{s.prototype.inspect=d}else s.prototype.inspect=d;function d(){return(this.red?""}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],A=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(l,g){l=l||10,g=g|0||1;var y;if(l===16||l==="hex"){y="";for(var E=0,I=0,_=0;_>>24-E&16777215,E+=2,E>=26&&(E-=26,_--),I!==0||_!==this.length-1?y=w[6-N.length]+N+y:y=N+y}for(I!==0&&(y=I.toString(16)+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var m=A[l],O=T[l];y="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var $=Y.modrn(O).toString(l);Y=Y.idivn(O),Y.isZero()?y=$+y:y=w[m-$.length]+$+y}for(this.isZero()&&(y="0"+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(l,g){return this.toArrayLike(o,l,g)}),s.prototype.toArray=function(l,g){return this.toArrayLike(Array,l,g)};var x=function(l,g){return l.allocUnsafe?l.allocUnsafe(g):new l(g)};s.prototype.toArrayLike=function(l,g,y){this._strip();var E=this.byteLength(),I=y||Math.max(1,E);n(E<=I,"byte array longer than desired length"),n(I>0,"Requested array length <= 0");var _=x(l,I),M=g==="le"?"LE":"BE";return this["_toArrayLike"+M](_,E),_},s.prototype._toArrayLikeLE=function(l,g){for(var y=0,E=0,I=0,_=0;I>8&255),y>16&255),_===6?(y>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y=0&&(l[y--]=M>>8&255),y>=0&&(l[y--]=M>>16&255),_===6?(y>=0&&(l[y--]=M>>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y>=0)for(l[y--]=E;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var g=l,y=0;return g>=4096&&(y+=13,g>>>=13),g>=64&&(y+=7,g>>>=7),g>=8&&(y+=4,g>>>=4),g>=2&&(y+=2,g>>>=2),y+g},s.prototype._zeroBits=function(l){if(l===0)return 26;var g=l,y=0;return g&8191||(y+=13,g>>>=13),g&127||(y+=7,g>>>=7),g&15||(y+=4,g>>>=4),g&3||(y+=2,g>>>=2),g&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],g=this._countBits(l);return(this.length-1)*26+g};function B(l){for(var g=new Array(l.bitLength()),y=0;y>>I&1}return g}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,g=0;gl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var g;this.length>l.length?g=l:g=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var g,y;this.length>l.length?(g=this,y=l):(g=l,y=this);for(var E=0;El.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var g=Math.ceil(l/26)|0,y=l%26;this._expand(g),y>0&&g--;for(var E=0;E0&&(this.words[E]=~this.words[E]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,g){n(typeof l=="number"&&l>=0);var y=l/26|0,E=l%26;return this._expand(y+1),g?this.words[y]=this.words[y]|1<l.length?(y=this,E=l):(y=l,E=this);for(var I=0,_=0;_>>26;for(;I!==0&&_>>26;if(this.length=y.length,I!==0)this.words[this.length]=I,this.length++;else if(y!==this)for(;_l.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var g=this.iadd(l);return l.negative=1,g._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,I;y>0?(E=this,I=l):(E=l,I=this);for(var _=0,M=0;M>26,this.words[M]=g&67108863;for(;_!==0&&M>26,this.words[M]=g&67108863;if(_===0&&M>>26,$=m&67108863,b=Math.min(O,g.length-1),j=Math.max(0,O-l.length+1);j<=b;j++){var z=O-j|0;I=l.words[z]|0,_=g.words[j]|0,M=I*_+$,Y+=M/67108864|0,$=M&67108863}y.words[O]=$|0,m=Y|0}return m!==0?y.words[O]=m|0:y.length--,y._strip()}var U=function(l,g,y){var E=l.words,I=g.words,_=y.words,M=0,N,m,O,Y=E[0]|0,$=Y&8191,b=Y>>>13,j=E[1]|0,z=j&8191,W=j>>>13,ie=E[2]|0,te=ie&8191,ee=ie>>>13,se=E[3]|0,oe=se&8191,J=se>>>13,ue=E[4]|0,wt=ue&8191,vt=ue>>>13,Ni=E[5]|0,At=Ni&8191,Et=Ni>>>13,xi=E[6]|0,bt=xi&8191,St=xi>>>13,Oi=E[7]|0,It=Oi&8191,Tt=Oi>>>13,Di=E[8]|0,Qe=Di&8191,Ke=Di>>>13,ri=E[9]|0,We=ri&8191,$e=ri>>>13,ni=I[0]|0,Ye=ni&8191,Je=ni>>>13,ii=I[1]|0,Xe=ii&8191,Ze=ii>>>13,si=I[2]|0,et=si&8191,tt=si>>>13,oi=I[3]|0,rt=oi&8191,nt=oi>>>13,ai=I[4]|0,it=ai&8191,st=ai>>>13,ui=I[5]|0,ot=ui&8191,at=ui>>>13,ci=I[6]|0,ut=ci&8191,ct=ci>>>13,li=I[7]|0,lt=li&8191,ft=li>>>13,fi=I[8]|0,ht=fi&8191,dt=fi>>>13,hi=I[9]|0,gt=hi&8191,pt=hi>>>13;y.negative=l.negative^g.negative,y.length=19,N=Math.imul($,Ye),m=Math.imul($,Je),m=m+Math.imul(b,Ye)|0,O=Math.imul(b,Je);var vn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(vn>>>26)|0,vn&=67108863,N=Math.imul(z,Ye),m=Math.imul(z,Je),m=m+Math.imul(W,Ye)|0,O=Math.imul(W,Je),N=N+Math.imul($,Xe)|0,m=m+Math.imul($,Ze)|0,m=m+Math.imul(b,Xe)|0,O=O+Math.imul(b,Ze)|0;var An=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(An>>>26)|0,An&=67108863,N=Math.imul(te,Ye),m=Math.imul(te,Je),m=m+Math.imul(ee,Ye)|0,O=Math.imul(ee,Je),N=N+Math.imul(z,Xe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(W,Xe)|0,O=O+Math.imul(W,Ze)|0,N=N+Math.imul($,et)|0,m=m+Math.imul($,tt)|0,m=m+Math.imul(b,et)|0,O=O+Math.imul(b,tt)|0;var En=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(En>>>26)|0,En&=67108863,N=Math.imul(oe,Ye),m=Math.imul(oe,Je),m=m+Math.imul(J,Ye)|0,O=Math.imul(J,Je),N=N+Math.imul(te,Xe)|0,m=m+Math.imul(te,Ze)|0,m=m+Math.imul(ee,Xe)|0,O=O+Math.imul(ee,Ze)|0,N=N+Math.imul(z,et)|0,m=m+Math.imul(z,tt)|0,m=m+Math.imul(W,et)|0,O=O+Math.imul(W,tt)|0,N=N+Math.imul($,rt)|0,m=m+Math.imul($,nt)|0,m=m+Math.imul(b,rt)|0,O=O+Math.imul(b,nt)|0;var bn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(bn>>>26)|0,bn&=67108863,N=Math.imul(wt,Ye),m=Math.imul(wt,Je),m=m+Math.imul(vt,Ye)|0,O=Math.imul(vt,Je),N=N+Math.imul(oe,Xe)|0,m=m+Math.imul(oe,Ze)|0,m=m+Math.imul(J,Xe)|0,O=O+Math.imul(J,Ze)|0,N=N+Math.imul(te,et)|0,m=m+Math.imul(te,tt)|0,m=m+Math.imul(ee,et)|0,O=O+Math.imul(ee,tt)|0,N=N+Math.imul(z,rt)|0,m=m+Math.imul(z,nt)|0,m=m+Math.imul(W,rt)|0,O=O+Math.imul(W,nt)|0,N=N+Math.imul($,it)|0,m=m+Math.imul($,st)|0,m=m+Math.imul(b,it)|0,O=O+Math.imul(b,st)|0;var Sn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Sn>>>26)|0,Sn&=67108863,N=Math.imul(At,Ye),m=Math.imul(At,Je),m=m+Math.imul(Et,Ye)|0,O=Math.imul(Et,Je),N=N+Math.imul(wt,Xe)|0,m=m+Math.imul(wt,Ze)|0,m=m+Math.imul(vt,Xe)|0,O=O+Math.imul(vt,Ze)|0,N=N+Math.imul(oe,et)|0,m=m+Math.imul(oe,tt)|0,m=m+Math.imul(J,et)|0,O=O+Math.imul(J,tt)|0,N=N+Math.imul(te,rt)|0,m=m+Math.imul(te,nt)|0,m=m+Math.imul(ee,rt)|0,O=O+Math.imul(ee,nt)|0,N=N+Math.imul(z,it)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(W,it)|0,O=O+Math.imul(W,st)|0,N=N+Math.imul($,ot)|0,m=m+Math.imul($,at)|0,m=m+Math.imul(b,ot)|0,O=O+Math.imul(b,at)|0;var In=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(In>>>26)|0,In&=67108863,N=Math.imul(bt,Ye),m=Math.imul(bt,Je),m=m+Math.imul(St,Ye)|0,O=Math.imul(St,Je),N=N+Math.imul(At,Xe)|0,m=m+Math.imul(At,Ze)|0,m=m+Math.imul(Et,Xe)|0,O=O+Math.imul(Et,Ze)|0,N=N+Math.imul(wt,et)|0,m=m+Math.imul(wt,tt)|0,m=m+Math.imul(vt,et)|0,O=O+Math.imul(vt,tt)|0,N=N+Math.imul(oe,rt)|0,m=m+Math.imul(oe,nt)|0,m=m+Math.imul(J,rt)|0,O=O+Math.imul(J,nt)|0,N=N+Math.imul(te,it)|0,m=m+Math.imul(te,st)|0,m=m+Math.imul(ee,it)|0,O=O+Math.imul(ee,st)|0,N=N+Math.imul(z,ot)|0,m=m+Math.imul(z,at)|0,m=m+Math.imul(W,ot)|0,O=O+Math.imul(W,at)|0,N=N+Math.imul($,ut)|0,m=m+Math.imul($,ct)|0,m=m+Math.imul(b,ut)|0,O=O+Math.imul(b,ct)|0;var ha=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ha>>>26)|0,ha&=67108863,N=Math.imul(It,Ye),m=Math.imul(It,Je),m=m+Math.imul(Tt,Ye)|0,O=Math.imul(Tt,Je),N=N+Math.imul(bt,Xe)|0,m=m+Math.imul(bt,Ze)|0,m=m+Math.imul(St,Xe)|0,O=O+Math.imul(St,Ze)|0,N=N+Math.imul(At,et)|0,m=m+Math.imul(At,tt)|0,m=m+Math.imul(Et,et)|0,O=O+Math.imul(Et,tt)|0,N=N+Math.imul(wt,rt)|0,m=m+Math.imul(wt,nt)|0,m=m+Math.imul(vt,rt)|0,O=O+Math.imul(vt,nt)|0,N=N+Math.imul(oe,it)|0,m=m+Math.imul(oe,st)|0,m=m+Math.imul(J,it)|0,O=O+Math.imul(J,st)|0,N=N+Math.imul(te,ot)|0,m=m+Math.imul(te,at)|0,m=m+Math.imul(ee,ot)|0,O=O+Math.imul(ee,at)|0,N=N+Math.imul(z,ut)|0,m=m+Math.imul(z,ct)|0,m=m+Math.imul(W,ut)|0,O=O+Math.imul(W,ct)|0,N=N+Math.imul($,lt)|0,m=m+Math.imul($,ft)|0,m=m+Math.imul(b,lt)|0,O=O+Math.imul(b,ft)|0;var da=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(da>>>26)|0,da&=67108863,N=Math.imul(Qe,Ye),m=Math.imul(Qe,Je),m=m+Math.imul(Ke,Ye)|0,O=Math.imul(Ke,Je),N=N+Math.imul(It,Xe)|0,m=m+Math.imul(It,Ze)|0,m=m+Math.imul(Tt,Xe)|0,O=O+Math.imul(Tt,Ze)|0,N=N+Math.imul(bt,et)|0,m=m+Math.imul(bt,tt)|0,m=m+Math.imul(St,et)|0,O=O+Math.imul(St,tt)|0,N=N+Math.imul(At,rt)|0,m=m+Math.imul(At,nt)|0,m=m+Math.imul(Et,rt)|0,O=O+Math.imul(Et,nt)|0,N=N+Math.imul(wt,it)|0,m=m+Math.imul(wt,st)|0,m=m+Math.imul(vt,it)|0,O=O+Math.imul(vt,st)|0,N=N+Math.imul(oe,ot)|0,m=m+Math.imul(oe,at)|0,m=m+Math.imul(J,ot)|0,O=O+Math.imul(J,at)|0,N=N+Math.imul(te,ut)|0,m=m+Math.imul(te,ct)|0,m=m+Math.imul(ee,ut)|0,O=O+Math.imul(ee,ct)|0,N=N+Math.imul(z,lt)|0,m=m+Math.imul(z,ft)|0,m=m+Math.imul(W,lt)|0,O=O+Math.imul(W,ft)|0,N=N+Math.imul($,ht)|0,m=m+Math.imul($,dt)|0,m=m+Math.imul(b,ht)|0,O=O+Math.imul(b,dt)|0;var ga=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ga>>>26)|0,ga&=67108863,N=Math.imul(We,Ye),m=Math.imul(We,Je),m=m+Math.imul($e,Ye)|0,O=Math.imul($e,Je),N=N+Math.imul(Qe,Xe)|0,m=m+Math.imul(Qe,Ze)|0,m=m+Math.imul(Ke,Xe)|0,O=O+Math.imul(Ke,Ze)|0,N=N+Math.imul(It,et)|0,m=m+Math.imul(It,tt)|0,m=m+Math.imul(Tt,et)|0,O=O+Math.imul(Tt,tt)|0,N=N+Math.imul(bt,rt)|0,m=m+Math.imul(bt,nt)|0,m=m+Math.imul(St,rt)|0,O=O+Math.imul(St,nt)|0,N=N+Math.imul(At,it)|0,m=m+Math.imul(At,st)|0,m=m+Math.imul(Et,it)|0,O=O+Math.imul(Et,st)|0,N=N+Math.imul(wt,ot)|0,m=m+Math.imul(wt,at)|0,m=m+Math.imul(vt,ot)|0,O=O+Math.imul(vt,at)|0,N=N+Math.imul(oe,ut)|0,m=m+Math.imul(oe,ct)|0,m=m+Math.imul(J,ut)|0,O=O+Math.imul(J,ct)|0,N=N+Math.imul(te,lt)|0,m=m+Math.imul(te,ft)|0,m=m+Math.imul(ee,lt)|0,O=O+Math.imul(ee,ft)|0,N=N+Math.imul(z,ht)|0,m=m+Math.imul(z,dt)|0,m=m+Math.imul(W,ht)|0,O=O+Math.imul(W,dt)|0,N=N+Math.imul($,gt)|0,m=m+Math.imul($,pt)|0,m=m+Math.imul(b,gt)|0,O=O+Math.imul(b,pt)|0;var pa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pa>>>26)|0,pa&=67108863,N=Math.imul(We,Xe),m=Math.imul(We,Ze),m=m+Math.imul($e,Xe)|0,O=Math.imul($e,Ze),N=N+Math.imul(Qe,et)|0,m=m+Math.imul(Qe,tt)|0,m=m+Math.imul(Ke,et)|0,O=O+Math.imul(Ke,tt)|0,N=N+Math.imul(It,rt)|0,m=m+Math.imul(It,nt)|0,m=m+Math.imul(Tt,rt)|0,O=O+Math.imul(Tt,nt)|0,N=N+Math.imul(bt,it)|0,m=m+Math.imul(bt,st)|0,m=m+Math.imul(St,it)|0,O=O+Math.imul(St,st)|0,N=N+Math.imul(At,ot)|0,m=m+Math.imul(At,at)|0,m=m+Math.imul(Et,ot)|0,O=O+Math.imul(Et,at)|0,N=N+Math.imul(wt,ut)|0,m=m+Math.imul(wt,ct)|0,m=m+Math.imul(vt,ut)|0,O=O+Math.imul(vt,ct)|0,N=N+Math.imul(oe,lt)|0,m=m+Math.imul(oe,ft)|0,m=m+Math.imul(J,lt)|0,O=O+Math.imul(J,ft)|0,N=N+Math.imul(te,ht)|0,m=m+Math.imul(te,dt)|0,m=m+Math.imul(ee,ht)|0,O=O+Math.imul(ee,dt)|0,N=N+Math.imul(z,gt)|0,m=m+Math.imul(z,pt)|0,m=m+Math.imul(W,gt)|0,O=O+Math.imul(W,pt)|0;var ma=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ma>>>26)|0,ma&=67108863,N=Math.imul(We,et),m=Math.imul(We,tt),m=m+Math.imul($e,et)|0,O=Math.imul($e,tt),N=N+Math.imul(Qe,rt)|0,m=m+Math.imul(Qe,nt)|0,m=m+Math.imul(Ke,rt)|0,O=O+Math.imul(Ke,nt)|0,N=N+Math.imul(It,it)|0,m=m+Math.imul(It,st)|0,m=m+Math.imul(Tt,it)|0,O=O+Math.imul(Tt,st)|0,N=N+Math.imul(bt,ot)|0,m=m+Math.imul(bt,at)|0,m=m+Math.imul(St,ot)|0,O=O+Math.imul(St,at)|0,N=N+Math.imul(At,ut)|0,m=m+Math.imul(At,ct)|0,m=m+Math.imul(Et,ut)|0,O=O+Math.imul(Et,ct)|0,N=N+Math.imul(wt,lt)|0,m=m+Math.imul(wt,ft)|0,m=m+Math.imul(vt,lt)|0,O=O+Math.imul(vt,ft)|0,N=N+Math.imul(oe,ht)|0,m=m+Math.imul(oe,dt)|0,m=m+Math.imul(J,ht)|0,O=O+Math.imul(J,dt)|0,N=N+Math.imul(te,gt)|0,m=m+Math.imul(te,pt)|0,m=m+Math.imul(ee,gt)|0,O=O+Math.imul(ee,pt)|0;var ya=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ya>>>26)|0,ya&=67108863,N=Math.imul(We,rt),m=Math.imul(We,nt),m=m+Math.imul($e,rt)|0,O=Math.imul($e,nt),N=N+Math.imul(Qe,it)|0,m=m+Math.imul(Qe,st)|0,m=m+Math.imul(Ke,it)|0,O=O+Math.imul(Ke,st)|0,N=N+Math.imul(It,ot)|0,m=m+Math.imul(It,at)|0,m=m+Math.imul(Tt,ot)|0,O=O+Math.imul(Tt,at)|0,N=N+Math.imul(bt,ut)|0,m=m+Math.imul(bt,ct)|0,m=m+Math.imul(St,ut)|0,O=O+Math.imul(St,ct)|0,N=N+Math.imul(At,lt)|0,m=m+Math.imul(At,ft)|0,m=m+Math.imul(Et,lt)|0,O=O+Math.imul(Et,ft)|0,N=N+Math.imul(wt,ht)|0,m=m+Math.imul(wt,dt)|0,m=m+Math.imul(vt,ht)|0,O=O+Math.imul(vt,dt)|0,N=N+Math.imul(oe,gt)|0,m=m+Math.imul(oe,pt)|0,m=m+Math.imul(J,gt)|0,O=O+Math.imul(J,pt)|0;var wa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(wa>>>26)|0,wa&=67108863,N=Math.imul(We,it),m=Math.imul(We,st),m=m+Math.imul($e,it)|0,O=Math.imul($e,st),N=N+Math.imul(Qe,ot)|0,m=m+Math.imul(Qe,at)|0,m=m+Math.imul(Ke,ot)|0,O=O+Math.imul(Ke,at)|0,N=N+Math.imul(It,ut)|0,m=m+Math.imul(It,ct)|0,m=m+Math.imul(Tt,ut)|0,O=O+Math.imul(Tt,ct)|0,N=N+Math.imul(bt,lt)|0,m=m+Math.imul(bt,ft)|0,m=m+Math.imul(St,lt)|0,O=O+Math.imul(St,ft)|0,N=N+Math.imul(At,ht)|0,m=m+Math.imul(At,dt)|0,m=m+Math.imul(Et,ht)|0,O=O+Math.imul(Et,dt)|0,N=N+Math.imul(wt,gt)|0,m=m+Math.imul(wt,pt)|0,m=m+Math.imul(vt,gt)|0,O=O+Math.imul(vt,pt)|0;var va=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(va>>>26)|0,va&=67108863,N=Math.imul(We,ot),m=Math.imul(We,at),m=m+Math.imul($e,ot)|0,O=Math.imul($e,at),N=N+Math.imul(Qe,ut)|0,m=m+Math.imul(Qe,ct)|0,m=m+Math.imul(Ke,ut)|0,O=O+Math.imul(Ke,ct)|0,N=N+Math.imul(It,lt)|0,m=m+Math.imul(It,ft)|0,m=m+Math.imul(Tt,lt)|0,O=O+Math.imul(Tt,ft)|0,N=N+Math.imul(bt,ht)|0,m=m+Math.imul(bt,dt)|0,m=m+Math.imul(St,ht)|0,O=O+Math.imul(St,dt)|0,N=N+Math.imul(At,gt)|0,m=m+Math.imul(At,pt)|0,m=m+Math.imul(Et,gt)|0,O=O+Math.imul(Et,pt)|0;var Aa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,N=Math.imul(We,ut),m=Math.imul(We,ct),m=m+Math.imul($e,ut)|0,O=Math.imul($e,ct),N=N+Math.imul(Qe,lt)|0,m=m+Math.imul(Qe,ft)|0,m=m+Math.imul(Ke,lt)|0,O=O+Math.imul(Ke,ft)|0,N=N+Math.imul(It,ht)|0,m=m+Math.imul(It,dt)|0,m=m+Math.imul(Tt,ht)|0,O=O+Math.imul(Tt,dt)|0,N=N+Math.imul(bt,gt)|0,m=m+Math.imul(bt,pt)|0,m=m+Math.imul(St,gt)|0,O=O+Math.imul(St,pt)|0;var dw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(dw>>>26)|0,dw&=67108863,N=Math.imul(We,lt),m=Math.imul(We,ft),m=m+Math.imul($e,lt)|0,O=Math.imul($e,ft),N=N+Math.imul(Qe,ht)|0,m=m+Math.imul(Qe,dt)|0,m=m+Math.imul(Ke,ht)|0,O=O+Math.imul(Ke,dt)|0,N=N+Math.imul(It,gt)|0,m=m+Math.imul(It,pt)|0,m=m+Math.imul(Tt,gt)|0,O=O+Math.imul(Tt,pt)|0;var gw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(gw>>>26)|0,gw&=67108863,N=Math.imul(We,ht),m=Math.imul(We,dt),m=m+Math.imul($e,ht)|0,O=Math.imul($e,dt),N=N+Math.imul(Qe,gt)|0,m=m+Math.imul(Qe,pt)|0,m=m+Math.imul(Ke,gt)|0,O=O+Math.imul(Ke,pt)|0;var pw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pw>>>26)|0,pw&=67108863,N=Math.imul(We,gt),m=Math.imul(We,pt),m=m+Math.imul($e,gt)|0,O=Math.imul($e,pt);var mw=(M+N|0)+((m&8191)<<13)|0;return M=(O+(m>>>13)|0)+(mw>>>26)|0,mw&=67108863,_[0]=vn,_[1]=An,_[2]=En,_[3]=bn,_[4]=Sn,_[5]=In,_[6]=ha,_[7]=da,_[8]=ga,_[9]=pa,_[10]=ma,_[11]=ya,_[12]=wa,_[13]=va,_[14]=Aa,_[15]=dw,_[16]=gw,_[17]=pw,_[18]=mw,M!==0&&(_[19]=M,y.length++),y};Math.imul||(U=V);function Q(l,g,y){y.negative=g.negative^l.negative,y.length=l.length+g.length;for(var E=0,I=0,_=0;_>>26)|0,I+=M>>>26,M&=67108863}y.words[_]=N,E=M,M=I}return E!==0?y.words[_]=E:y.length--,y._strip()}function L(l,g,y){return Q(l,g,y)}s.prototype.mulTo=function(l,g){var y,E=this.length+l.length;return this.length===10&&l.length===10?y=U(this,l,g):E<63?y=V(this,l,g):E<1024?y=Q(this,l,g):y=L(this,l,g),y},s.prototype.mul=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),this.mulTo(l,g)},s.prototype.mulf=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),L(this,l,g)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var g=l<0;g&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var y=0,E=0;E>=26,y+=I/67108864|0,y+=_>>>26,this.words[E]=_&67108863}return y!==0&&(this.words[E]=y,this.length++),g?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var g=B(l);if(g.length===0)return new s(1);for(var y=this,E=0;E=0);var g=l%26,y=(l-g)/26,E=67108863>>>26-g<<26-g,I;if(g!==0){var _=0;for(I=0;I>>26-g}_&&(this.words[I]=_,this.length++)}if(y!==0){for(I=this.length-1;I>=0;I--)this.words[I+y]=this.words[I];for(I=0;I=0);var E;g?E=(g-g%26)/26:E=0;var I=l%26,_=Math.min((l-I)/26,this.length),M=67108863^67108863>>>I<_)for(this.length-=_,m=0;m=0&&(O!==0||m>=E);m--){var Y=this.words[m]|0;this.words[m]=O<<26-I|Y>>>I,O=Y&M}return N&&O!==0&&(N.words[N.length++]=O),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,g,y){return n(this.negative===0),this.iushrn(l,g,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var g=l%26,y=(l-g)/26,E=1<=0);var g=l%26,y=(l-g)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(g!==0&&y++,this.length=Math.min(y,this.length),g!==0){var E=67108863^67108863>>>g<=67108864;g++)this.words[g]-=67108864,g===this.length-1?this.words[g+1]=1:this.words[g+1]++;return this.length=Math.max(this.length,g+1),this},s.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var g=0;g>26)-(N/67108864|0),this.words[I+y]=_&67108863}for(;I>26,this.words[I+y]=_&67108863;if(M===0)return this._strip();for(n(M===-1),M=0,I=0;I>26,this.words[I]=_&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,g){var y=this.length-l.length,E=this.clone(),I=l,_=I.words[I.length-1]|0,M=this._countBits(_);y=26-M,y!==0&&(I=I.ushln(y),E.iushln(y),_=I.words[I.length-1]|0);var N=E.length-I.length,m;if(g!=="mod"){m=new s(null),m.length=N+1,m.words=new Array(m.length);for(var O=0;O=0;$--){var b=(E.words[I.length+$]|0)*67108864+(E.words[I.length+$-1]|0);for(b=Math.min(b/_|0,67108863),E._ishlnsubmul(I,b,$);E.negative!==0;)b--,E.negative=0,E._ishlnsubmul(I,1,$),E.isZero()||(E.negative^=1);m&&(m.words[$]=b)}return m&&m._strip(),E._strip(),g!=="div"&&y!==0&&E.iushrn(y),{div:m||null,mod:E}},s.prototype.divmod=function(l,g,y){if(n(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,I,_;return this.negative!==0&&l.negative===0?(_=this.neg().divmod(l,g),g!=="mod"&&(E=_.div.neg()),g!=="div"&&(I=_.mod.neg(),y&&I.negative!==0&&I.iadd(l)),{div:E,mod:I}):this.negative===0&&l.negative!==0?(_=this.divmod(l.neg(),g),g!=="mod"&&(E=_.div.neg()),{div:E,mod:_.mod}):this.negative&l.negative?(_=this.neg().divmod(l.neg(),g),g!=="div"&&(I=_.mod.neg(),y&&I.negative!==0&&I.isub(l)),{div:_.div,mod:I}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?g==="div"?{div:this.divn(l.words[0]),mod:null}:g==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,g)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var g=this.divmod(l);if(g.mod.isZero())return g.div;var y=g.div.negative!==0?g.mod.isub(l):g.mod,E=l.ushrn(1),I=l.andln(1),_=y.cmp(E);return _<0||I===1&&_===0?g.div:g.div.negative!==0?g.div.isubn(1):g.div.iaddn(1)},s.prototype.modrn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=(1<<26)%l,E=0,I=this.length-1;I>=0;I--)E=(y*E+(this.words[I]|0))%l;return g?-E:E},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=0,E=this.length-1;E>=0;E--){var I=(this.words[E]|0)+y*67108864;this.words[E]=I/l|0,y=I%l}return this._strip(),g?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),I=new s(0),_=new s(0),M=new s(1),N=0;g.isEven()&&y.isEven();)g.iushrn(1),y.iushrn(1),++N;for(var m=y.clone(),O=g.clone();!g.isZero();){for(var Y=0,$=1;!(g.words[0]&$)&&Y<26;++Y,$<<=1);if(Y>0)for(g.iushrn(Y);Y-- >0;)(E.isOdd()||I.isOdd())&&(E.iadd(m),I.isub(O)),E.iushrn(1),I.iushrn(1);for(var b=0,j=1;!(y.words[0]&j)&&b<26;++b,j<<=1);if(b>0)for(y.iushrn(b);b-- >0;)(_.isOdd()||M.isOdd())&&(_.iadd(m),M.isub(O)),_.iushrn(1),M.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(_),I.isub(M)):(y.isub(g),_.isub(E),M.isub(I))}return{a:_,b:M,gcd:y.iushln(N)}},s.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),I=new s(0),_=y.clone();g.cmpn(1)>0&&y.cmpn(1)>0;){for(var M=0,N=1;!(g.words[0]&N)&&M<26;++M,N<<=1);if(M>0)for(g.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(_),E.iushrn(1);for(var m=0,O=1;!(y.words[0]&O)&&m<26;++m,O<<=1);if(m>0)for(y.iushrn(m);m-- >0;)I.isOdd()&&I.iadd(_),I.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(I)):(y.isub(g),I.isub(E))}var Y;return g.cmpn(1)===0?Y=E:Y=I,Y.cmpn(0)<0&&Y.iadd(l),Y},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var g=this.clone(),y=l.clone();g.negative=0,y.negative=0;for(var E=0;g.isEven()&&y.isEven();E++)g.iushrn(1),y.iushrn(1);do{for(;g.isEven();)g.iushrn(1);for(;y.isEven();)y.iushrn(1);var I=g.cmp(y);if(I<0){var _=g;g=y,y=_}else if(I===0||y.cmpn(1)===0)break;g.isub(y)}while(!0);return y.iushln(E)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){n(typeof l=="number");var g=l%26,y=(l-g)/26,E=1<>>26,M&=67108863,this.words[_]=M}return I!==0&&(this.words[_]=I,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var g=l<0;if(this.negative!==0&&!g)return-1;if(this.negative===0&&g)return 1;this._strip();var y;if(this.length>1)y=1;else{g&&(l=-l),n(l<=67108863,"Number is too big");var E=this.words[0]|0;y=E===l?0:El.length)return 1;if(this.length=0;y--){var E=this.words[y]|0,I=l.words[y]|0;if(E!==I){EI&&(g=1);break}}return g},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new F(l)},s.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var k={k256:null,p224:null,p192:null,p25519:null};function H(l,g){this.name=l,this.p=new s(g,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},H.prototype.ireduce=function(l){var g=l,y;do this.split(g,this.tmp),g=this.imulK(g),g=g.iadd(this.tmp),y=g.bitLength();while(y>this.n);var E=y0?g.isub(this.p):g.strip!==void 0?g.strip():g._strip(),g},H.prototype.split=function(l,g){l.iushrn(this.n,0,g)},H.prototype.imulK=function(l){return l.imul(this.k)};function q(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(q,H),q.prototype.split=function(l,g){for(var y=4194303,E=Math.min(l.length,9),I=0;I>>22,_=M}_>>>=22,l.words[I-10]=_,_===0&&l.length>10?l.length-=10:l.length-=9},q.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var g=0,y=0;y>>=26,l.words[y]=I,g=E}return g!==0&&(l.words[l.length++]=g),l},s._prime=function(l){if(k[l])return k[l];var g;if(l==="k256")g=new q;else if(l==="p224")g=new v;else if(l==="p192")g=new C;else if(l==="p25519")g=new P;else throw new Error("Unknown prime "+l);return k[l]=g,g};function F(l){if(typeof l=="string"){var g=s._prime(l);this.m=g.p,this.prime=g}else n(l.gtn(1),"modulus must be greater than 1"),this.m=l,this.prime=null}F.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},F.prototype._verify2=function(l,g){n((l.negative|g.negative)===0,"red works only with positives"),n(l.red&&l.red===g.red,"red works only with red numbers")},F.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(f(l,l.umod(this.m)._forceRed(this)),l)},F.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},F.prototype.add=function(l,g){this._verify2(l,g);var y=l.add(g);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},F.prototype.iadd=function(l,g){this._verify2(l,g);var y=l.iadd(g);return y.cmp(this.m)>=0&&y.isub(this.m),y},F.prototype.sub=function(l,g){this._verify2(l,g);var y=l.sub(g);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},F.prototype.isub=function(l,g){this._verify2(l,g);var y=l.isub(g);return y.cmpn(0)<0&&y.iadd(this.m),y},F.prototype.shl=function(l,g){return this._verify1(l),this.imod(l.ushln(g))},F.prototype.imul=function(l,g){return this._verify2(l,g),this.imod(l.imul(g))},F.prototype.mul=function(l,g){return this._verify2(l,g),this.imod(l.mul(g))},F.prototype.isqr=function(l){return this.imul(l,l.clone())},F.prototype.sqr=function(l){return this.mul(l,l)},F.prototype.sqrt=function(l){if(l.isZero())return l.clone();var g=this.m.andln(3);if(n(g%2===1),g===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var E=this.m.subn(1),I=0;!E.isZero()&&E.andln(1)===0;)I++,E.iushrn(1);n(!E.isZero());var _=new s(1).toRed(this),M=_.redNeg(),N=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,N).cmp(M)!==0;)m.redIAdd(M);for(var O=this.pow(m,E),Y=this.pow(l,E.addn(1).iushrn(1)),$=this.pow(l,E),b=I;$.cmp(_)!==0;){for(var j=$,z=0;j.cmp(_)!==0;z++)j=j.redSqr();n(z=0;I--){for(var O=g.words[I],Y=m-1;Y>=0;Y--){var $=O>>Y&1;if(_!==E[0]&&(_=this.sqr(_)),$===0&&M===0){N=0;continue}M<<=1,M|=$,N++,!(N!==y&&(I!==0||Y!==0))&&(_=this.mul(_,E[M]),N=0,M=0)}m=26}return _},F.prototype.convertTo=function(l){var g=l.umod(this.m);return g===l?g.clone():g},F.prototype.convertFrom=function(l){var g=l.clone();return g.red=null,g},s.mont=function(l){return new R(l)};function R(l){F.call(this,l),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(R,F),R.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},R.prototype.convertFrom=function(l){var g=this.imod(l.mul(this.rinv));return g.red=null,g},R.prototype.imul=function(l,g){if(l.isZero()||g.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=y.isub(E).iushrn(this.shift),_=I;return I.cmp(this.m)>=0?_=I.isub(this.m):I.cmpn(0)<0&&(_=I.iadd(this.m)),_._forceRed(this)},R.prototype.mul=function(l,g){if(l.isZero()||g.isZero())return new s(0)._forceRed(this);var y=l.mul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=y.isub(E).iushrn(this.shift),_=I;return I.cmp(this.m)>=0?_=I.isub(this.m):I.cmpn(0)<0&&(_=I.iadd(this.m)),_._forceRed(this)},R.prototype.invm=function(l){var g=this.imod(l._invmp(this.m).mul(this.r2));return g._forceRed(this)}})(t,d4)})(y4);var Se=y4.exports,w4="bignumber/5.7.0",$m=Se.BN,Ks=new kt(w4),dT={},IM=9007199254740991;function Jte(t){return t!=null&&(Cr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||gn(t)||typeof t=="bigint"||ul(t))}var TM=!1,Cr=class t{constructor(e,r){e!==dT&&Ks.throwError("cannot call constructor directly; use BigNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return sn(De(this).fromTwos(e))}toTwos(e){return sn(De(this).toTwos(e))}abs(){return this._hex[0]==="-"?t.from(this._hex.substring(1)):this}add(e){return sn(De(this).add(De(e)))}sub(e){return sn(De(this).sub(De(e)))}div(e){return t.from(e).isZero()&&Kn("division-by-zero","div"),sn(De(this).div(De(e)))}mul(e){return sn(De(this).mul(De(e)))}mod(e){let r=De(e);return r.isNeg()&&Kn("division-by-zero","mod"),sn(De(this).umod(r))}pow(e){let r=De(e);return r.isNeg()&&Kn("negative-power","pow"),sn(De(this).pow(r))}and(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","and"),sn(De(this).and(r))}or(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","or"),sn(De(this).or(r))}xor(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","xor"),sn(De(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Kn("negative-width","mask"),sn(De(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Kn("negative-width","shl"),sn(De(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Kn("negative-width","shr"),sn(De(this).shrn(e))}eq(e){return De(this).eq(De(e))}lt(e){return De(this).lt(De(e))}lte(e){return De(this).lte(De(e))}gt(e){return De(this).gt(De(e))}gte(e){return De(this).gte(De(e))}isNegative(){return this._hex[0]==="-"}isZero(){return De(this).isZero()}toNumber(){try{return De(this).toNumber()}catch{Kn("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ks.throwError("this platform does not support BigInt",kt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?TM||(TM=!0,Ks.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ks.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",kt.errors.UNEXPECTED_ARGUMENT,{}):Ks.throwError("BigNumber.toString does not accept parameters",kt.errors.UNEXPECTED_ARGUMENT,{})),De(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof t)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new t(dT,Vh(e)):e.match(/^-?[0-9]+$/)?new t(dT,Vh(new $m(e))):Ks.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Kn("underflow","BigNumber.from",e),(e>=IM||e<=-IM)&&Kn("overflow","BigNumber.from",e),t.from(String(e));let r=e;if(typeof r=="bigint")return t.from(r.toString());if(ul(r))return t.from(kr(r));if(r)if(r.toHexString){let n=r.toHexString();if(typeof n=="string")return t.from(n)}else{let n=r._hex;if(n==null&&r.type==="BigNumber"&&(n=r.hex),typeof n=="string"&&(gn(n)||n[0]==="-"&&gn(n.substring(1))))return t.from(n)}return Ks.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}};function Vh(t){if(typeof t!="string")return Vh(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ks.throwArgumentError("invalid hex","value",t),t=Vh(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function sn(t){return Cr.from(Vh(t))}function De(t){let e=Cr.from(t).toHexString();return e[0]==="-"?new $m("-"+e.substring(3),16):new $m(e.substring(2),16)}function Kn(t,e,r){let n={fault:t,operation:e};return r!=null&&(n.value=r),Ks.throwError(t,kt.errors.NUMERIC_FAULT,n)}function Xte(t){return new $m(t,36).toString(16)}var Hr=new kt(w4),Fh={},v4=Cr.from(0),A4=Cr.from(-1);function E4(t,e,r,n){let i={fault:e,operation:r};return n!==void 0&&(i.value=n),Hr.throwError(t,kt.errors.NUMERIC_FAULT,i)}var Uh="0";for(;Uh.length<256;)Uh+=Uh;function jT(t){if(typeof t!="number")try{t=Cr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+Uh.substring(0,t):Hr.throwArgumentError("invalid decimal size","decimals",t)}function gT(t,e){e==null&&(e=0);let r=jT(e);t=Cr.from(t);let n=t.lt(v4);n&&(t=t.mul(A4));let i=t.mod(r).toString();for(;i.length2&&Hr.throwArgumentError("too many decimal points","value",t);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");o[o.length-1]==="0";)o=o.substring(0,o.length-1);for(o.length>r.length-1&&E4("fractional component exceeds decimals","underflow","parseFixed"),o===""&&(o="0");o.lengthe[o]==null?a:(typeof e[o]!==u&&Hr.throwArgumentError("invalid fixed format ("+o+" not "+u+")","format."+o,e[o]),e[o]);r=s("signed","boolean",r),n=s("width","number",n),i=s("decimals","number",i)}return n%8&&Hr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),i>80&&Hr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",i),new t(Fh,r,n,i)}},Ym=class t{constructor(e,r,n,i){e!==Fh&&Hr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=r,this._value=n,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Hr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.add(n),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.sub(n),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return this.isNegative()&&n&&(r=r.subUnsafe(_M.toFormat(r.format))),r}ceiling(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return!this.isNegative()&&n&&(r=r.addUnsafe(_M.toFormat(r.format))),r}round(e){e==null&&(e=0);let r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&Hr.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;let n=t.from("1"+Uh.substring(0,e),this.format),i=Zte.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(i).floor().divUnsafe(n)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Hr.throwArgumentError("invalid byte width","width",e);let r=Cr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return fs(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return t.fromString(this._value,e)}static fromValue(e,r,n){return n==null&&r!=null&&!Jte(r)&&(n=r,r=null),r==null&&(r=0),n==null&&(n="fixed"),t.fromString(gT(e,r),qh.from(n))}static fromString(e,r){r==null&&(r="fixed");let n=qh.from(r),i=Qs(e,n.decimals);!n.signed&&i.lt(v4)&&E4("unsigned value cannot be negative","overflow","value",e);let s=null;n.signed?s=i.toTwos(n.width).toHexString():(s=i.toHexString(),s=fs(s,n.width/8));let o=gT(i,n.decimals);return new t(Fh,s,o,n)}static fromBytes(e,r){r==null&&(r="fixed");let n=qh.from(r);if(Qt(e).length>n.width/8)throw new Error("overflow");let i=Cr.from(e);n.signed&&(i=i.fromTwos(n.width));let s=i.toTwos((n.signed?0:1)+n.width).toHexString(),o=gT(i,n.decimals);return new t(Fh,s,o,n)}static from(e,r){if(typeof e=="string")return t.fromString(e,r);if(ul(e))return t.fromBytes(e,r);try{return t.fromValue(e,0,r)}catch(n){if(n.code!==kt.errors.INVALID_ARGUMENT)throw n}return Hr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}},_M=Ym.from(1),Zte=Ym.from("0.5"),ere="strings/5.7.0",b4=new kt(ere),Jm;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(Jm||(Jm={}));var rl;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(rl||(rl={}));function tre(t,e,r,n,i){return b4.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function S4(t,e,r,n,i){if(t===rl.BAD_PREFIX||t===rl.UNEXPECTED_CONTINUE){let s=0;for(let o=e+1;o>6===2;o++)s++;return s}return t===rl.OVERRUN?r.length-e-1:0}function rre(t,e,r,n,i){return t===rl.OVERLONG?(n.push(i),0):(n.push(65533),S4(t,e,r))}Object.freeze({error:tre,ignore:S4,replace:rre});function pT(t,e=Jm.current){e!=Jm.current&&(b4.checkNormalize(),t=t.normalize(e));let r=[];for(let n=0;n>6|192),r.push(i&63|128);else if((i&64512)==55296){n++;let s=t.charCodeAt(n);if(n>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");let o=65536+((i&1023)<<10)+(s&1023);r.push(o>>18|240),r.push(o>>12&63|128),r.push(o>>6&63|128),r.push(o&63|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(i&63|128)}return Qt(r)}function nre(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r{let s=i.split(":");r+=parseInt(s[0],16),n[r]=e(s[1])}),n}function CM(t){let e=0;return t.split(",").map(r=>{let n=r.split("-");n.length===1?n[1]="0":n[1]===""&&(n[1]="1");let i=e+parseInt(n[0],16);return e=parseInt(n[1],16),{l:i,h:e}})}CM("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),mT("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),mT("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),mT("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",nre),CM("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");var I4="hash/5.7.0";function ire(t){t=atob(t);let e=[];for(let r=0;r0&&Array.isArray(u)?i(u,o-1):r.push(u)})};return i(t,e),r}function sre(t){let e={};for(let r=0;r>--a&1}let d=31,w=Math.pow(2,d),A=w>>>1,T=A>>1,x=w-1,B=0;for(let k=0;k1;){let P=H+q>>>1;k>>1|f(),v=v<<1^A,C=(C^A)<<1|A|1;U=v,Q=1+C-v}let L=n-4;return V.map(k=>{switch(k-L){case 3:return L+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return L+256+(t[u++]<<8|t[u++]);case 1:return L+t[u++];default:return k-1}})}function are(t){let e=0;return()=>t[e++]}function ure(t){return are(ore(t))}function cre(t){return t&1?~t>>1:t>>1}function lre(t,e){let r=Array(t);for(let n=0;ne[o]):r}function hre(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(gre(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(pre(r,t))}return sre(T4(e))}function dre(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function _4(t,e,r){let n=Array(t).fill(void 0).map(()=>[]);for(let i=0;in[o].push(s));return n}function gre(t,e){let r=1+e(),n=e(),i=dre(e),s=_4(i.length,1+t,e);return T4(s.map((o,u)=>{let a=o[0],c=o.slice(1);return Array(i[u]).fill(void 0).map((f,d)=>{let w=d*n;return[a+d*r,c.map(A=>A+w)]})}))}function pre(t,e){let r=1+e();return _4(r,1+t,e).map(n=>[n[0],n.slice(1)])}function mre(t){let e=Xm(t).sort((n,i)=>n-i);return r();function r(){let n=[];for(;;){let c=Xm(t,e);if(c.length==0)break;n.push({set:new Set(c),node:r()})}n.sort((c,f)=>f.set.size-c.set.size);let i=t(),s=i%3;i=i/3|0;let o=!!(i&1);i>>=1;let u=i==1,a=i==2;return{branches:n,valid:s,fe0f:o,save:u,check:a}}}function yre(){return ure(ire("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}var qm=yre();new Set(Xm(qm)),new Set(Xm(qm)),hre(qm),mre(qm),new kt(I4);var wre=new Uint8Array(32);wre.fill(0);var vre=`Ethereum Signed Message: +`;function C4(t){return typeof t=="string"&&(t=pT(t)),GT(zte([pT(vre),pT(String(t.length)),t]))}var Are="rlp/5.7.0";new kt(Are);var Ere="address/5.7.0",Lh=new kt(Ere);function xM(t){gn(t,20)||Lh.throwArgumentError("invalid address","address",t),t=t.toLowerCase();let e=t.substring(2).split(""),r=new Uint8Array(40);for(let i=0;i<40;i++)r[i]=e[i].charCodeAt(0);let n=Qt(GT(r));for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&(e[i]=e[i].toUpperCase()),(n[i>>1]&15)>=8&&(e[i+1]=e[i+1].toUpperCase());return"0x"+e.join("")}var bre=9007199254740991;function Sre(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}var zT={};for(let t=0;t<10;t++)zT[String(t)]=String(t);for(let t=0;t<26;t++)zT[String.fromCharCode(65+t)]=String(10+t);var OM=Math.floor(Sre(bre));function Ire(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(n=>zT[n]).join("");for(;e.length>=OM;){let n=e.substring(0,OM);e=parseInt(n,10)%97+e.substring(n.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function Tre(t){let e=null;if(typeof t!="string"&&Lh.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=xM(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&Lh.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==Ire(t)&&Lh.throwArgumentError("bad icap checksum","address",t),e=Xte(t.substring(4));e.length<40;)e="0"+e;e=xM("0x"+e)}else Lh.throwArgumentError("invalid address","address",t);return e}var _re="properties/5.7.0";new kt(_re);function Rh(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new kt(I4);var Cre=new Uint8Array(32);Cre.fill(0),Cr.from(-1);var Nre=Cr.from(0),xre=Cr.from(1);Cr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fs(xre.toHexString(),32),fs(Nre.toHexString(),32);var os={},Pe={},Gh=N4;function N4(t,e){if(!t)throw new Error(e||"Assertion failed")}N4.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var NT={exports:{}};typeof Object.create=="function"?NT.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:NT.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var Ore=Gh,Dre=NT.exports;Pe.inherits=Dre;function Pre(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function Rre(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),i=0;i>6|192,r[n++]=s&63|128):Pre(t,i)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023),r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128)}else for(i=0;i>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Pe.htonl=x4;function Mre(t,e){for(var r="",n=0;n>>0}return s}Pe.join32=Lre;function Fre(t,e){for(var r=new Array(t.length*4),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=s&255):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=s&255)}return r}Pe.split32=Fre;function Ure(t,e){return t>>>e|t<<32-e}Pe.rotr32=Ure;function qre(t,e){return t<>>32-e}Pe.rotl32=qre;function Vre(t,e){return t+e>>>0}Pe.sum32=Vre;function kre(t,e,r){return t+e+r>>>0}Pe.sum32_3=kre;function Hre(t,e,r,n){return t+e+r+n>>>0}Pe.sum32_4=Hre;function Gre(t,e,r,n,i){return t+e+r+n+i>>>0}Pe.sum32_5=Gre;function jre(t,e,r,n){var i=t[e],s=t[e+1],o=n+s>>>0,u=(o>>0,t[e+1]=o}Pe.sum64=jre;function zre(t,e,r,n){var i=e+n>>>0,s=(i>>0}Pe.sum64_hi=zre;function Qre(t,e,r,n){var i=e+n;return i>>>0}Pe.sum64_lo=Qre;function Kre(t,e,r,n,i,s,o,u){var a=0,c=e;c=c+n>>>0,a+=c>>0,a+=c>>0,a+=c>>0}Pe.sum64_4_hi=Kre;function Wre(t,e,r,n,i,s,o,u){var a=e+n+s+u;return a>>>0}Pe.sum64_4_lo=Wre;function $re(t,e,r,n,i,s,o,u,a,c){var f=0,d=e;d=d+n>>>0,f+=d>>0,f+=d>>0,f+=d>>0,f+=d>>0}Pe.sum64_5_hi=$re;function Yre(t,e,r,n,i,s,o,u,a,c){var f=e+n+s+u+c;return f>>>0}Pe.sum64_5_lo=Yre;function Jre(t,e,r){var n=e<<32-r|t>>>r;return n>>>0}Pe.rotr64_hi=Jre;function Xre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.rotr64_lo=Xre;function Zre(t,e,r){return t>>>r}Pe.shr64_hi=Zre;function ene(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.shr64_lo=ene;var cl={},DM=Pe,tne=Gh;function Vm(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}cl.BlockHash=Vm,Vm.prototype.update=function(t,e){if(t=DM.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=DM.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=t&255}else for(n[i++]=t&255,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s>>3}ms.g0_256=one;function ane(t){return hs(t,17)^hs(t,19)^t>>>10}ms.g1_256=ane;var sl=Pe,une=cl,cne=ms,yT=sl.rotl32,Bh=sl.sum32,lne=sl.sum32_5,fne=cne.ft_1,M4=une.BlockHash,hne=[1518500249,1859775393,2400959708,3395469782];function us(){if(!(this instanceof us))return new us;M4.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}sl.inherits(us,M4);var dne=us;us.blockSize=512,us.outSize=160,us.hmacStrength=80,us.padLength=64,us.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=new this.Hash().update(t).digest()),eie(t.length<=this.blockSize);for(var e=t.length;e>8,w=f&255;d?a.push(d,w):a.push(w)}return a}r.toArray=n;function i(o){return o.length===1?"0"+o:o}r.zero2=i;function s(o){for(var u="",a=0;a(w>>1)-1?x=(w>>1)-B:x=B,A.isubn(x)):x=0,d[T]=x,A.iushrn(1)}return d}r.getNAF=n;function i(a,c){var f=[[],[]];a=a.clone(),c=c.clone();for(var d=0,w=0,A;a.cmpn(-d)>0||c.cmpn(-w)>0;){var T=a.andln(3)+d&3,x=c.andln(3)+w&3;T===3&&(T=-1),x===3&&(x=-1);var B;T&1?(A=a.andln(7)+d&7,(A===3||A===5)&&x===2?B=-T:B=T):B=0,f[0].push(B);var V;x&1?(A=c.andln(7)+w&7,(A===3||A===5)&&T===2?V=-x:V=x):V=0,f[1].push(V),2*d===B+1&&(d=1-d),2*w===V+1&&(w=1-w),a.iushrn(1),c.iushrn(1)}return f}r.getJSF=i;function s(a,c,f){var d="_"+c;a.prototype[c]=function(){return this[d]!==void 0?this[d]:this[d]=f.call(this)}}r.cachedProperty=s;function o(a){return typeof a=="string"?r.toArray(a,"hex"):a}r.parseBytes=o;function u(a){return new Se(a,"hex","le")}r.intFromLE=u}),Hm=pn.getNAF,nie=pn.getJSF,Zm=pn.assert;function Vo(t,e){this.type=t,this.p=new Se(e.p,16),this.red=e.prime?Se.red(e.prime):Se.mont(this.p),this.zero=new Se(0).toRed(this.red),this.one=new Se(1).toRed(this.red),this.two=new Se(2).toRed(this.red),this.n=e.n&&new Se(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ru=Vo;Vo.prototype.point=function(){throw new Error("Not implemented")},Vo.prototype.validate=function(){throw new Error("Not implemented")},Vo.prototype._fixedNafMul=function(t,e){Zm(t.precomputed);var r=t._getDoubles(),n=Hm(e,1,this._bitLength),i=(1<=o;a--)u=(u<<1)+n[a];s.push(u)}for(var c=this.jpoint(null,null,null),f=this.jpoint(null,null,null),d=i;d>0;d--){for(o=0;o=0;u--){for(var a=0;u>=0&&s[u]===0;u--)a++;if(u>=0&&a++,o=o.dblp(a),u<0)break;var c=s[u];Zm(c!==0),t.type==="affine"?c>0?o=o.mixedAdd(i[c-1>>1]):o=o.mixedAdd(i[-c-1>>1].neg()):c>0?o=o.add(i[c-1>>1]):o=o.add(i[-c-1>>1].neg())}return t.type==="affine"?o.toP():o},Vo.prototype._wnafMulAdd=function(t,e,r,n,i){var s=this._wnafT1,o=this._wnafT2,u=this._wnafT3,a=0,c,f,d;for(c=0;c=1;c-=2){var A=c-1,T=c;if(s[A]!==1||s[T]!==1){u[A]=Hm(r[A],s[A],this._bitLength),u[T]=Hm(r[T],s[T],this._bitLength),a=Math.max(u[A].length,a),a=Math.max(u[T].length,a);continue}var x=[e[A],null,null,e[T]];e[A].y.cmp(e[T].y)===0?(x[1]=e[A].add(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg())):e[A].y.cmp(e[T].y.redNeg())===0?(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].add(e[T].neg())):(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg()));var B=[-3,-1,-5,-7,0,7,5,1,3],V=nie(r[A],r[T]);for(a=Math.max(V[0].length,a),u[A]=new Array(a),u[T]=new Array(a),f=0;f=0;c--){for(var H=0;c>=0;){var q=!0;for(f=0;f=0&&H++,L=L.dblp(H),c<0)break;for(f=0;f0?d=o[f][v-1>>1]:v<0&&(d=o[f][-v-1>>1].neg()),d.type==="affine"?L=L.mixedAdd(d):L=L.add(d))}}for(c=0;c=Math.ceil((t.bitLength()+1)/e.step):!1},Wn.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(w=a,A=c),f.negative&&(f=f.neg(),d=d.neg()),w.negative&&(w=w.neg(),A=A.neg()),[{a:f,b:d},{a:w,b:A}]},Yn.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),u=s.mul(n.a),a=i.mul(r.b),c=s.mul(n.b),f=t.sub(o).sub(u),d=a.add(c).neg();return{k1:f,k2:d}},Yn.prototype.pointFromX=function(t,e){t=new Se(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(n.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},Yn.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return r.redSqr().redISub(i).cmpn(0)===0},Yn.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Ar.prototype.isInfinity=function(){return this.inf},Ar.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Ar.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Ar.prototype.getX=function(){return this.x.fromRed()},Ar.prototype.getY=function(){return this.y.fromRed()},Ar.prototype.mul=function(t){return t=new Se(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Ar.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Ar.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Ar.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Ar.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(i){return i.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Ar.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function _r(t,e,r,n){ru.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&n===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Se(0)):(this.x=new Se(e,16),this.y=new Se(r,16),this.z=new Se(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}KT(_r,ru.BasePoint),Yn.prototype.jpoint=function(t,e,r){return new _r(this,t,e,r)},_r.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},_r.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_r.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=s.redSub(o);if(u.cmpn(0)===0)return a.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var c=u.redSqr(),f=c.redMul(u),d=n.redMul(c),w=a.redSqr().redIAdd(f).redISub(d).redISub(d),A=a.redMul(d.redISub(w)).redISub(s.redMul(f)),T=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(w,A,T)},_r.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),u=i.redSub(s);if(o.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),c=a.redMul(o),f=r.redMul(a),d=u.redSqr().redIAdd(c).redISub(f).redISub(f),w=u.redMul(f.redISub(d)).redISub(i.redMul(c)),A=this.z.redMul(o);return this.curve.jpoint(d,w,A)},_r.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),this.x.cmp(r)===0)return!0}},_r.prototype.inspect=function(){return this.isInfinity()?"":""},_r.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var zm=fl(function(t,e){var r=e;r.base=ru,r.short=sie,r.mont=null,r.edwards=null}),Qm=fl(function(t,e){var r=e,n=pn.assert;function i(u){u.type==="short"?this.curve=new zm.short(u):u.type==="edwards"?this.curve=new zm.edwards(u):this.curve=new zm.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=i;function s(u,a){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var c=new i(a);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:c}),c}})}s("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:os.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:os.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:os.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:os.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),s("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:os.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var o;try{o=null.crash()}catch{o=void 0}s("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:os.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",o]})});function ko(t){if(!(this instanceof ko))return new ko(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Ti.toArray(t.entropy,t.entropyEnc||"hex"),r=Ti.toArray(t.nonce,t.nonceEnc||"hex"),n=Ti.toArray(t.pers,t.persEnc||"hex");QT(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var MM=ko;ko.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},ko.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(n=r,r=e,e=null),r&&(r=Ti.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var oie=pn.assert;function ny(t,e){if(t instanceof ny)return t;this._importDER(t,e)||(oie(t.r&&t.s,"Signature without r or s"),this.r=new Se(t.r,16),this.s=new Se(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Gm=ny;function aie(){this.place=0}function bT(t,e){var r=t[e.place++];if(!(r&128))return r;var n=r&15;if(n===0||n>4)return!1;for(var i=0,s=0,o=e.place;s>>=0;return i<=127?!1:(e.place=o,i)}function LM(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}ny.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=LM(e),r=LM(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var n=[2];ST(n,e.length),n=n.concat(e),n.push(2),ST(n,r.length);var i=n.concat(r),s=[48];return ST(s,i.length),s=s.concat(i),pn.encode(s,t)};var uie=function(){throw new Error("unsupported")},K4=pn.assert;function $n(t){if(!(this instanceof $n))return new $n(t);typeof t=="string"&&(K4(Object.prototype.hasOwnProperty.call(Qm,t),"Unknown curve "+t),t=Qm[t]),t instanceof Qm.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var cie=$n;$n.prototype.keyPair=function(t){return new ET(this,t)},$n.prototype.keyFromPrivate=function(t,e){return ET.fromPrivate(this,t,e)},$n.prototype.keyFromPublic=function(t,e){return ET.fromPublic(this,t,e)},$n.prototype.genKeyPair=function(t){t||(t={});for(var e=new MM({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||uie(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Se(2));;){var i=new Se(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},$n.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},$n.prototype.sign=function(t,e,r,n){typeof r=="object"&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Se(t,16));for(var i=this.n.byteLength(),s=e.getPrivate().toArray("be",i),o=t.toArray("be",i),u=new MM({hash:this.hash,entropy:s,nonce:o,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Se(1)),c=0;;c++){var f=n.k?n.k(c):new Se(u.generate(this.n.byteLength()));if(f=this._truncateToN(f,!0),!(f.cmpn(1)<=0||f.cmp(a)>=0)){var d=this.g.mul(f);if(!d.isInfinity()){var w=d.getX(),A=w.umod(this.n);if(A.cmpn(0)!==0){var T=f.invm(this.n).mul(A.mul(e.getPrivate()).iadd(t));if(T=T.umod(this.n),T.cmpn(0)!==0){var x=(d.getY().isOdd()?1:0)|(w.cmp(A)!==0?2:0);return n.canonical&&T.cmp(this.nh)>0&&(T=this.n.sub(T),x^=1),new Gm({r:A,s:T,recoveryParam:x})}}}}}},$n.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Se(t,16)),r=this.keyFromPublic(r,n),e=new Gm(e,"hex");var i=e.r,s=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o=s.invm(this.n),u=o.mul(t).umod(this.n),a=o.mul(i).umod(this.n),c;return this.curve._maxwellTrick?(c=this.g.jmulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.eqXToP(i)):(c=this.g.mulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.getX().umod(this.n).cmp(i)===0)},$n.prototype.recoverPubKey=function(t,e,r,n){K4((3&r)===r,"The recovery param is more than two bits"),e=new Gm(e,n);var i=this.n,s=new Se(t),o=e.r,u=e.s,a=r&1,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");c?o=this.curve.pointFromX(o.add(this.curve.n),a):o=this.curve.pointFromX(o,a);var f=e.r.invm(i),d=i.sub(s).mul(f).umod(i),w=u.mul(f).umod(i);return this.g.mulAdd(d,o,w)},$n.prototype.getKeyRecoveryParam=function(t,e,r,n){if(e=new Gm(e,n),e.recoveryParam!==null)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch{continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var lie=fl(function(t,e){var r=e;r.version="6.5.4",r.utils=pn,r.rand=function(){throw new Error("unsupported")},r.curve=zm,r.curves=Qm,r.ec=cie,r.eddsa=null}),fie=lie.ec,hie="signing-key/5.7.0",DT=new kt(hie),IT=null;function ls(){return IT||(IT=new fie("secp256k1")),IT}var PT=class{constructor(e){Rh(this,"curve","secp256k1"),Rh(this,"privateKey",kr(e)),Kte(this.privateKey)!==32&&DT.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");let r=ls().keyFromPrivate(Qt(this.privateKey));Rh(this,"publicKey","0x"+r.getPublic(!1,"hex")),Rh(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),Rh(this,"_isSigningKey",!0)}_addPoint(e){let r=ls().keyFromPublic(Qt(this.publicKey)),n=ls().keyFromPublic(Qt(e));return"0x"+r.pub.add(n.pub).encodeCompressed("hex")}signDigest(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=Qt(e);n.length!==32&&DT.throwArgumentError("bad digest length","digest",e);let i=r.sign(n,{canonical:!0});return m4({recoveryParam:i.recoveryParam,r:fs("0x"+i.r.toString(16),32),s:fs("0x"+i.s.toString(16),32)})}computeSharedSecret(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=ls().keyFromPublic(Qt(W4(e)));return fs("0x"+r.derive(n.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}};function die(t,e){let r=m4(e),n={r:Qt(r.r),s:Qt(r.s)};return"0x"+ls().recoverPubKey(Qt(t),n,r.recoveryParam).encode("hex",!1)}function W4(t,e){let r=Qt(t);if(r.length===32){let n=new PT(r);return e?"0x"+ls().keyFromPrivate(r).getPublic(!0,"hex"):n.publicKey}else{if(r.length===33)return e?kr(r):"0x"+ls().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+ls().keyFromPublic(r).getPublic(!0,"hex"):kr(r)}return DT.throwArgumentError("invalid public or private key","key","[REDACTED]")}var gie="transactions/5.7.0";new kt(gie);var FM;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(FM||(FM={}));function pie(t){let e=W4(t);return Tre(SM(GT(SM(e,1)),12))}function mie(t,e){return pie(die(Qt(t),e))}var yie="https://rpc.walletconnect.com/v1";async function $4(t,e,r,n,i,s){switch(r.t){case"eip191":return Y4(t,e,r.s);case"eip1271":return await J4(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Y4(t,e,r){return mie(C4(e),r).toLowerCase()===t.toLowerCase()}async function J4(t,e,r,n,i,s){try{let o="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",c=r.substring(2),f=C4(e).substring(2),d=o+f+u+a+c,w=await fetch(`${s||yie}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:wie(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:A}=await w.json();return A?A.slice(0,o.length).toLowerCase()===o.toLowerCase():!1}catch(o){return console.error("isValidEip1271Signature: ",o),!1}}function wie(){return Date.now()+Math.floor(Math.random()*1e3)}var vie=Object.defineProperty,Aie=Object.defineProperties,Eie=Object.getOwnPropertyDescriptors,UM=Object.getOwnPropertySymbols,bie=Object.prototype.hasOwnProperty,Sie=Object.prototype.propertyIsEnumerable,qM=(t,e,r)=>e in t?vie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,WT=(t,e)=>{for(var r in e||(e={}))bie.call(e,r)&&qM(t,r,e[r]);if(UM)for(var r of UM(e))Sie.call(e,r)&&qM(t,r,e[r]);return t},X4=(t,e)=>Aie(t,Eie(e)),Iie="did:pkh:",iy=t=>t?.split(":"),$T=t=>{let e=t&&iy(t);if(e)return t.includes(Iie)?e[3]:e[1]},Tie=t=>{let e=t&&iy(t);if(e)return e[2]+":"+e[3]},YT=t=>{let e=t&&iy(t);if(e)return e.pop()};async function _ie(t){let{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=Z4(i,i.iss),o=YT(i.iss);return await $4(o,s,n,$T(i.iss),r)}var Z4=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=YT(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0,s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,u=`Chain ID: ${$T(e)}`,a=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources?`Resources:${t.resources.map(w=>` +- ${w}`).join("")}`:void 0,d=oy(t.resources);if(d){let w=jo(d);i=ZT(i,w)}return[r,n,"",i,"",s,o,u,a,c,f].filter(w=>w!=null).join(` +`)};function Cie(t,e,r){return r.includes("did:pkh:")||(r=`did:pkh:${r}`),{h:{t:"caip122"},p:{iss:r,domain:t.domain,aud:t.aud,version:t.version,nonce:t.nonce,iat:t.iat,statement:t.statement,requestId:t.requestId,resources:t.resources,nbf:t.nbf,exp:t.exp},s:e}}function Nie(t){var e;let{authPayload:r,chains:n,methods:i}=t,s=r.statement||"";if(!(n!=null&&n.length))return r;let o=r.chains,u=_T(o,n);if(!(u!=null&&u.length))throw new Error("No supported chains");let a=e5(r.resources);if(!a)return r;ps(a);let c=t5(a,"eip155"),f=r?.resources||[];if(c!=null&&c.length){let d=r5(c),w=_T(d,i);if(!(w!=null&&w.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(d)}, supported: ${JSON.stringify(i)}`);let A=JT("request",w,{chains:u}),T=o5(a,"eip155",A);f=((e=r?.resources)==null?void 0:e.slice(0,-1))||[],f.push(sy(T))}return X4(WT({},r),{statement:u5(s,oy(f)),chains:u,resources:r!=null&&r.resources||f.length>0?f:void 0})}function e5(t){let e=oy(t);if(e&&XT(e))return jo(e)}function xie(t,e){var r;return(r=t?.att)==null?void 0:r.hasOwnProperty(e)}function t5(t,e){var r,n;return(r=t?.att)!=null&&r[e]?Object.keys((n=t?.att)==null?void 0:n[e]):[]}function Oie(t){return t?.map(e=>Object.keys(e))||[]}function r5(t){return t?.map(e=>{var r;return(r=e.split("/"))==null?void 0:r[1]})||[]}function n5(t){return p.Buffer.from(JSON.stringify(t)).toString("base64")}function i5(t){return JSON.parse(p.Buffer.from(t,"base64").toString("utf-8"))}function ps(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");let e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{let n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{let s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function s5(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:JT(e,r,n)}}}function o5(t,e,r){var n;return t.att[e]=WT({},r),((n=Object.keys(t.att))==null?void 0:n.sort((i,s)=>i.localeCompare(s))).reduce((i,s)=>(i.att[s]=t.att[s],i),{att:{}})}function JT(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));let n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function sy(t){return ps(t),`urn:recap:${n5(t).replace(/=/g,"")}`}function jo(t){let e=i5(t.replace("urn:recap:",""));return ps(e),e}function Die(t,e,r){let n=s5(t,e,r);return sy(n)}function XT(t){return t&&t.includes("urn:recap:")}function Pie(t,e){let r=jo(t),n=jo(e),i=a5(r,n);return sy(i)}function a5(t,e){ps(t),ps(e);let r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((u,a)=>u.localeCompare(a)).forEach(u=>{var a,c;n.att[i]=X4(WT({},n.att[i]),{[u]:((a=t.att[i])==null?void 0:a[u])||((c=e.att[i])==null?void 0:c[u])})})}),n}function ZT(t="",e){ps(e);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;let n=[],i=0;Object.keys(e.att).forEach(u=>{let a=Object.keys(e.att[u]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));a.sort((d,w)=>d.action.localeCompare(w.action));let c={};a.forEach(d=>{c[d.ability]||(c[d.ability]=[]),c[d.ability].push(d.action)});let f=Object.keys(c).map(d=>(i++,`(${i}) '${d}': '${c[d].join("', '")}' for '${u}'.`));n.push(f.join(", ").replace(".,","."))});let s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function Rie(t){var e;let r=jo(t);ps(r);let n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Bie(t){let e=jo(t);ps(e);let r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function u5(t,e){if(!e)return t;let r=jo(e);return ps(r),ZT(t,r)}function oy(t){if(!t)return;let e=t?.[t.length-1];return XT(e)?e:void 0}var e_="base10",jr="base16",ey="base64pad",ay="utf8",t_=0,hl=1,Mie=0,VM=1,RT=12,r_=32;function Lie(){let t=YM.generateKeyPair();return{privateKey:Vt.toString(t.secretKey,jr),publicKey:Vt.toString(t.publicKey,jr)}}function Fie(){let t=WM.randomBytes(r_);return Vt.toString(t,jr)}function Uie(t,e){let r=YM.sharedKey(Vt.fromString(t,jr),Vt.fromString(e,jr),!0),n=new ite.HKDF(FT.SHA256,r).expand(r_);return Vt.toString(n,jr)}function qie(t){let e=FT.hash(Vt.fromString(t,jr));return Vt.toString(e,jr)}function Vie(t){let e=FT.hash(Vt.fromString(t,ay));return Vt.toString(e,jr)}function c5(t){return Vt.fromString(`${t}`,e_)}function jh(t){return Number(Vt.toString(t,e_))}function kie(t){let e=c5(typeof t.type<"u"?t.type:t_);if(jh(e)===hl&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?Vt.fromString(t.senderPublicKey,jr):void 0,n=typeof t.iv<"u"?Vt.fromString(t.iv,jr):WM.randomBytes(RT),i=new KM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)).seal(n,Vt.fromString(t.message,ay));return l5({type:e,sealed:i,iv:n,senderPublicKey:r})}function Hie(t){let e=new KM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)),{sealed:r,iv:n}=n_(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Vt.toString(i,ay)}function l5(t){if(jh(t.type)===hl){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Vt.toString(Vt.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),ey)}return Vt.toString(Vt.concat([t.type,t.iv,t.sealed]),ey)}function n_(t){let e=Vt.fromString(t,ey),r=e.slice(Mie,VM),n=VM;if(jh(r)===hl){let u=n+r_,a=u+RT,c=e.slice(n,u),f=e.slice(u,a),d=e.slice(a);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+RT,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Gie(t,e){let r=n_(t);return f5({type:jh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Vt.toString(r.senderPublicKey,jr):void 0,receiverPublicKey:e?.receiverPublicKey})}function f5(t){let e=t?.type||t_;if(e===hl){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function jie(t){return t.type===hl&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var h5="irn";function zie(t){return t?.relay||{protocol:h5}}function Qie(t){let e=ote.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Kie=Object.defineProperty,Wie=Object.defineProperties,$ie=Object.getOwnPropertyDescriptors,kM=Object.getOwnPropertySymbols,Yie=Object.prototype.hasOwnProperty,Jie=Object.prototype.propertyIsEnumerable,HM=(t,e,r)=>e in t?Kie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,GM=(t,e)=>{for(var r in e||(e={}))Yie.call(e,r)&&HM(t,r,e[r]);if(kM)for(var r of kM(e))Jie.call(e,r)&&HM(t,r,e[r]);return t},Xie=(t,e)=>Wie(t,$ie(e));function d5(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Zie(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=Km.parse(s),u=typeof o.methods=="string"?o.methods.split(","):void 0;return{protocol:n,topic:g5(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:d5(o),methods:u,expiryTimestamp:o.expiryTimestamp?parseInt(o.expiryTimestamp,10):void 0}}function g5(t){return t.startsWith("//")?t.substring(2):t}function p5(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function ese(t){return`${t.protocol}:${t.topic}@${t.version}?`+Km.stringify(GM(Xie(GM({symKey:t.symKey},p5(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}var tse=Object.defineProperty,rse=Object.defineProperties,nse=Object.getOwnPropertyDescriptors,jM=Object.getOwnPropertySymbols,ise=Object.prototype.hasOwnProperty,sse=Object.prototype.propertyIsEnumerable,zM=(t,e,r)=>e in t?tse(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ose=(t,e)=>{for(var r in e||(e={}))ise.call(e,r)&&zM(t,r,e[r]);if(jM)for(var r of jM(e))sse.call(e,r)&&zM(t,r,e[r]);return t},ase=(t,e)=>rse(t,nse(e));function nu(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function m5(t){let e=[];return Object.values(t).forEach(r=>{e.push(...nu(r.accounts))}),e}function y5(t,e){let r=[];return Object.values(t).forEach(n=>{nu(n.accounts).includes(e)&&r.push(...n.methods)}),r}function w5(t,e){let r=[];return Object.values(t).forEach(n=>{nu(n.accounts).includes(e)&&r.push(...n.events)}),r}function use(t,e){let r=x5(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function cse(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=BT(e),s=BT(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,w=n[c].events,A=n[c].accounts;f.forEach(T=>{if(!A.some(x=>x.includes(T)))throw new Error(`No accounts provided for chain ${T} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:w,accounts:A}});let u=D5(e,o,"approve()");if(u)throw new Error(u.message);let a={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(T=>{var x,B;return(B=(x=i[c])==null?void 0:x.chains)==null?void 0:B.includes(T)}),d=n[c].methods.filter(T=>{var x,B;return(B=(x=i[c])==null?void 0:x.methods)==null?void 0:B.includes(T)}),w=n[c].events.filter(T=>{var x,B;return(B=(x=i[c])==null?void 0:x.events)==null?void 0:B.includes(T)}),A=f.map(T=>n[c].accounts.filter(x=>x.includes(`${T}:`))).flat();a[c]={chains:f,methods:d,events:w,accounts:A}}),Object.keys(s).forEach(c=>{var f,d,w,A,T,x;if(!n[c])return;let B=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(L=>n[c].chains.includes(L)),V=n[c].methods.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.methods)==null?void 0:H.includes(L)}),U=n[c].events.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.events)==null?void 0:H.includes(L)}),Q=B?.map(L=>n[c].accounts.filter(k=>k.includes(`${L}:`))).flat();a[c]={chains:Js((w=a[c])==null?void 0:w.chains,B),methods:Js((A=a[c])==null?void 0:A.methods,V),events:Js((T=a[c])==null?void 0:T.events,U),accounts:Js((x=a[c])==null?void 0:x.accounts,Q)}}),a)}function i_(t){return t.includes(":")}function v5(t){return i_(t)?t.split(":")[0]:t}function BT(t){var e,r,n;let i={};if(!uy(t))return i;for(let[s,o]of Object.entries(t)){let u=i_(s)?[s]:o.chains,a=o.methods||[],c=o.events||[],f=v5(s);i[f]=ase(ose({},i[f]),{chains:Js(u,(e=i[f])==null?void 0:e.chains),methods:Js(a,(r=i[f])==null?void 0:r.methods),events:Js(c,(n=i[f])==null?void 0:n.events)})}return i}function A5(t){let e={};return t?.forEach(r=>{let[n,i]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[]}),e[n].accounts.push(r),e[n].chains.push(`${n}:${i}`)}),e}function lse(t,e){e=e.map(n=>n.replace("did:pkh:",""));let r=A5(e);for(let[n,i]of Object.entries(r))i.methods?i.methods=Js(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}var E5={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},b5={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ys(t,e){let{message:r,code:n}=b5[t];return{message:e?`${r} ${e}`:r,code:n}}function eu(t,e){let{message:r,code:n}=E5[t];return{message:e?`${r} ${e}`:r,code:n}}function zh(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function uy(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Go(t){return typeof t>"u"}function mn(t,e){return e&&Go(t)?!0:typeof t=="string"&&!!t.trim().length}function cy(t,e){return e&&Go(t)?!0:typeof t=="number"&&!isNaN(t)}function fse(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Ho(i,n)?(n.forEach(o=>{let{accounts:u,methods:a,events:c}=t.namespaces[o],f=nu(u),d=r[o];(!Ho(ry(o,d),f)||!Ho(d.methods,a)||!Ho(d.events,c))&&(s=!1)}),s):!1}function kh(t){return mn(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function S5(t){if(mn(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&kh(r)}}return!1}function hse(t){if(mn(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function dse(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function gse(t){return t?.topic}function pse(t,e){let r=null;return mn(t?.publicKey,!1)||(r=Ys("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function MT(t){let e=!0;return zh(t)?t.length&&(e=t.every(r=>mn(r,!1))):e=!1,e}function I5(t,e,r){let n=null;return zh(e)&&e.length?e.forEach(i=>{n||kh(i)||(n=eu("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):kh(t)||(n=eu("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function T5(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=I5(i,ry(i,s),`${e} ${r}`);o&&(n=o)}),n}function _5(t,e){let r=null;return zh(t)?t.forEach(n=>{r||S5(n)||(r=eu("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=eu("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function C5(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=_5(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function N5(t,e){let r=null;return MT(t?.methods)?MT(t?.events)||(r=eu("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=eu("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function s_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=N5(n,`${e}, namespace`);i&&(r=i)}),r}function mse(t,e,r){let n=null;if(t&&uy(t)){let i=s_(t,e);i&&(n=i);let s=T5(t,e,r);s&&(n=s)}else n=Ys("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function x5(t,e){let r=null;if(t&&uy(t)){let n=s_(t,e);n&&(r=n);let i=C5(t,e);i&&(r=i)}else r=Ys("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function O5(t){return mn(t.protocol,!0)}function yse(t,e){let r=!1;return e&&!t?r=!0:t&&zh(t)&&t.length&&t.forEach(n=>{r=O5(n)}),r}function wse(t){return typeof t=="number"}function vse(t){return typeof t<"u"&&typeof t!==null}function Ase(t){return!(!t||typeof t!="object"||!t.code||!cy(t.code,!1)||!t.message||!mn(t.message,!1))}function Ese(t){return!(Go(t)||!mn(t.method,!1))}function bse(t){return!(Go(t)||Go(t.result)&&Go(t.error)||!cy(t.id,!1)||!mn(t.jsonrpc,!1))}function Sse(t){return!(Go(t)||!mn(t.name,!1))}function Ise(t,e){return!(!kh(e)||!m5(t).includes(e))}function Tse(t,e,r){return mn(r,!1)?y5(t,e).includes(r):!1}function _se(t,e,r){return mn(r,!1)?w5(t,e).includes(r):!1}function D5(t,e,r){let n=null,i=Cse(t),s=Nse(e),o=Object.keys(i),u=Object.keys(s),a=QM(Object.keys(t)),c=QM(Object.keys(e)),f=a.filter(d=>!c.includes(d));return f.length&&(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. Required: ${f.toString()} Received: ${Object.keys(e).toString()}`)),Ho(o,u)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. Required: ${o.toString()} - Approved: ${u.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let w=iu(e[d].accounts);w.includes(d)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} + Approved: ${u.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let w=nu(e[d].accounts);w.includes(d)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} Required: ${d} - Approved: ${w.toString()}`))}),o.forEach(d=>{n||(Ho(i[d].methods,s[d].methods)?Ho(i[d].events,s[d].events)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function hse(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function KM(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dse(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:iu(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function gse(t,e){return fy(t,!1)&&t<=e.max&&t>=e.min}function pse(){let t=ru();return new Promise(e=>{switch(t){case Gr.browser:e(R5());break;case Gr.reactNative:e(B5());break;case Gr.node:e(M5());break;default:e(!0)}})}function R5(){return Hh()&&navigator?.onLine}async function B5(){return al()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function M5(){return!0}function mse(t){switch(ru()){case Gr.browser:L5(t);break;case Gr.reactNative:F5(t);break;case Gr.node:break}}function L5(t){!al()&&Hh()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function F5(t){al()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var IT={},MT=class{static get(e){return IT[e]}static set(e,r){IT[e]=r}static delete(e){delete IT[e]}};K.BASE10=ZT,K.BASE16=jr,K.BASE64=ry,K.COLON=ete,K.DEFAULT_DEPTH=qT,K.EMPTY_SPACE=Ym,K.ENV_MAP=Gr,K.INTERNAL_ERRORS=S5,K.MemoryStore=MT,K.ONE_THOUSAND=tte,K.REACT_NATIVE_PRODUCT=i4,K.RELAYER_DEFAULT_PROTOCOL=d5,K.SDK_ERRORS=b5,K.SDK_TYPE=o4,K.SLASH=s4,K.TYPE_0=e_,K.TYPE_1=hl,K.UTF8=cy,K.addResourceToRecap=a5,K.appendToQueryString=a4,K.assertType=ate,K.assignAbilityToActions=YT,K.base64Decode=s5,K.base64Encode=i5,K.buildApprovedNamespaces=Wie,K.buildAuthObject=hie,K.buildNamespacesFromAuth=$ie,K.buildRecapStatement=c5,K.calcExpiry=vte,K.capitalize=dte,K.capitalizeWord=d4,K.createDelayedPromise=gte,K.createEncodedRecap=mie,K.createExpiringPromise=pte,K.createRecap=o5,K.decodeRecap=jo,K.decodeTypeByte=jh,K.decrypt=Cie,K.deriveSymKey=Sie,K.deserialize=r_,K.encodeRecap=ay,K.encodeTypeByte=l5,K.encrypt=_ie,K.engineEvent=Ete,K.enumify=hte,K.formatAccountId=e4,K.formatAccountWithChain=Qee,K.formatChainId=ZM,K.formatExpirerTarget=kT,K.formatIdTarget=yte,K.formatMessage=e5,K.formatMessageContext=ute,K.formatRelayParams=m5,K.formatRelayRpcUrl=ste,K.formatStatementFromRecap=XT,K.formatTopicTarget=mte,K.formatUA=l4,K.formatUri=qie,K.generateKeyPair=Eie,K.generateRandomBytes32=bie,K.getAccountsChains=iu,K.getAccountsFromNamespaces=Wee,K.getAddressFromAccount=t4,K.getAddressesFromAccounts=Kee,K.getAppMetadata=nte,K.getBrowserOnlineStatus=R5,K.getBundleId=rte,K.getChainFromAccount=r4,K.getChainsFromAccounts=n4,K.getChainsFromNamespace=iy,K.getChainsFromNamespaces=$ee,K.getChainsFromRecap=vie,K.getChainsFromRequiredNamespaces=Yee,K.getCommonValuesInArrays=TT,K.getDecodedRecapFromResources=t5,K.getDeepLink=Ste,K.getDidAddress=$T,K.getDidAddressSegments=oy,K.getDidChainId=WT,K.getEnvironment=ru,K.getHttpUrl=ote,K.getInternalError=Ys,K.getJavascriptID=c4,K.getJavascriptOS=u4,K.getLastItems=h4,K.getMethodsFromRecap=wie,K.getNamespacedDidChainId=lie,K.getNamespacesChains=y5,K.getNamespacesEventsForChainId=v5,K.getNamespacesFromAccounts=E5,K.getNamespacesMethodsForChainId=w5,K.getNodeOnlineStatus=M5,K.getReCapActions=n5,K.getReactNativeOnlineStatus=B5,K.getRecapAbilitiesFromResource=pie,K.getRecapFromResources=uy,K.getRecapResource=r5,K.getRelayClientMetadata=ite,K.getRelayProtocolApi=Die,K.getRelayProtocolName=Oie,K.getRequiredNamespacesFromNamespaces=Kie,K.getSdkError=tu,K.getUniqueValues=UT,K.handleDeeplinkRedirect=bte,K.hasOverlap=Ho,K.hashKey=Iie,K.hashMessage=Tie,K.isBrowser=Hh,K.isCaipNamespace=n_,K.isConformingNamespaces=P5,K.isExpired=Ate,K.isNode=VT,K.isOnline=pse,K.isProposalStruct=Xie,K.isReactNative=al,K.isRecap=JT,K.isSessionCompatible=Yie,K.isSessionStruct=Zie,K.isTypeOneEnvelope=xie,K.isUndefined=Go,K.isValidAccountId=I5,K.isValidAccounts=C5,K.isValidActions=x5,K.isValidArray=zh,K.isValidChainId=kh,K.isValidChains=T5,K.isValidController=ese,K.isValidEip1271Signature=X4,K.isValidEip191Signature=J4,K.isValidErrorReason=sse,K.isValidEvent=use,K.isValidId=nse,K.isValidNamespaceAccounts=N5,K.isValidNamespaceActions=i_,K.isValidNamespaceChains=_5,K.isValidNamespaceMethodsOrEvents=BT,K.isValidNamespaces=O5,K.isValidNamespacesChainId=cse,K.isValidNamespacesEvent=fse,K.isValidNamespacesRequest=lse,K.isValidNumber=fy,K.isValidObject=ly,K.isValidParams=ise,K.isValidRecap=ps,K.isValidRelay=D5,K.isValidRelays=rse,K.isValidRequest=ose,K.isValidRequestExpiry=gse,K.isValidRequiredNamespaces=tse,K.isValidResponse=ase,K.isValidString=mn,K.isValidUrl=Jie,K.mapEntries=fte,K.mapToObj=cte,K.mergeArrays=Js,K.mergeEncodedRecaps=yie,K.mergeRecaps=u5,K.normalizeNamespaces=RT,K.objToMap=lte,K.parseAccountId=FT,K.parseChainId=XM,K.parseContextNames=f4,K.parseExpirerTarget=wte,K.parseNamespaceKey=A5,K.parseRelayParams=g5,K.parseTopic=p5,K.parseUri=Uie,K.populateAuthPayload=die,K.recapHasResource=gie,K.serialize=f5,K.subscribeToBrowserNetworkChange=L5,K.subscribeToNetworkChange=mse,K.subscribeToReactNativeNetworkChange=F5,K.validateDecoding=Nie,K.validateEncoding=h5,K.validateSignedCacao=fie,K.verifySignature=Y4});var U5,q5,V5,k5,hy,Kh,s_,dy,zo,Wh,gy=fe(()=>{h();U5="PARSE_ERROR",q5="INVALID_REQUEST",V5="METHOD_NOT_FOUND",k5="INVALID_PARAMS",hy="INTERNAL_ERROR",Kh="SERVER_ERROR",s_=[-32700,-32600,-32601,-32602,-32603],dy=[-32e3,-32099],zo={[U5]:{code:-32700,message:"Parse error"},[q5]:{code:-32600,message:"Invalid Request"},[V5]:{code:-32601,message:"Method not found"},[k5]:{code:-32602,message:"Invalid params"},[hy]:{code:-32603,message:"Internal error"},[Kh]:{code:-32e3,message:"Server error"}},Wh=Kh});function yse(t){return t<=dy[0]&&t>=dy[1]}function py(t){return s_.includes(t)}function H5(t){return typeof t=="number"}function my(t){return Object.keys(zo).includes(t)?zo[t]:zo[Wh]}function yy(t){let e=Object.values(zo).find(r=>r.code===t);return e||zo[Wh]}function wse(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!H5(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(py(t.error.code)){let e=yy(t.error.code);if(e.message!==zo[Wh].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function o_(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var a_=fe(()=>{h();gy()});var j5=B(Qo=>{"use strict";h();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.isBrowserCryptoAvailable=Qo.getSubtleCrypto=Qo.getBrowerCrypto=void 0;function u_(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}Qo.getBrowerCrypto=u_;function G5(){let t=u_();return t.subtle||t.webkitSubtle}Qo.getSubtleCrypto=G5;function vse(){return!!u_()&&!!G5()}Qo.isBrowserCryptoAvailable=vse});var K5=B(Ko=>{"use strict";h();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.isBrowser=Ko.isNode=Ko.isReactNative=void 0;function z5(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ko.isReactNative=z5;function Q5(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}Ko.isNode=Q5;function Ase(){return!z5()&&!Q5()}Ko.isBrowser=Ase});var c_=B(wy=>{"use strict";h();Object.defineProperty(wy,"__esModule",{value:!0});var W5=(es(),_e(Zi));W5.__exportStar(j5(),wy);W5.__exportStar(K5(),wy)});var Er={};Bt(Er,{isNodeJs:()=>Y5});var $5,Y5,J5=fe(()=>{h();$5=pe(c_());Tr(Er,pe(c_()));Y5=$5.isNode});function l_(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function f_(t=6){return BigInt(l_(t))}function h_(t,e,r){return{id:r||l_(),jsonrpc:"2.0",method:t,params:e}}function Ese(t,e){return{id:t,jsonrpc:"2.0",result:e}}function d_(t,e,r){return{id:t,jsonrpc:"2.0",error:X5(e,r)}}function X5(t,e){return typeof t>"u"?my(hy):(typeof t=="string"&&(t=Object.assign(Object.assign({},my(Kh)),{message:t})),typeof e<"u"&&(t.data=e),py(t.code)&&(t=yy(t.code)),t)}var Z5=fe(()=>{h();a_();gy()});function bse(t){return t.includes("*")?Ay(t):!/\W/g.test(t)}function vy(t){return t==="*"}function Ay(t){return vy(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function Sse(t){return!vy(t)&&Ay(t)&&!t.split("*")[0].trim()}function Ise(t){return!vy(t)&&Ay(t)&&!t.split("*")[1].trim()}var eL=fe(()=>{h()});var tL=fe(()=>{h()});var dl,g_=fe(()=>{h();dl=class{}});var p_,Ey,$h,rL=fe(()=>{h();g_();p_=class extends dl{constructor(e){super()}},Ey=class extends dl{constructor(){super()}},$h=class extends Ey{constructor(e){super()}}});var nL=fe(()=>{h()});var iL=fe(()=>{h();tL();g_();rL();nL()});var sL=fe(()=>{h();iL()});function Cse(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function oL(t,e){let r=Cse(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Nse(t){return oL(t,Tse)}function by(t){return oL(t,_se)}function m_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var Tse,_se,aL=fe(()=>{h();Tse="^https?:",_se="^wss?:"});function y_(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function xse(t){return y_(t)&&"method"in t}function w_(t){return y_(t)&&(uL(t)||Sy(t))}function uL(t){return"result"in t}function Sy(t){return"error"in t}function Ose(t){return"error"in t&&t.valid===!1}var cL=fe(()=>{h()});var Fr={};Bt(Fr,{DEFAULT_ERROR:()=>Wh,IBaseJsonRpcProvider:()=>Ey,IEvents:()=>dl,IJsonRpcConnection:()=>p_,IJsonRpcProvider:()=>$h,INTERNAL_ERROR:()=>hy,INVALID_PARAMS:()=>k5,INVALID_REQUEST:()=>q5,METHOD_NOT_FOUND:()=>V5,PARSE_ERROR:()=>U5,RESERVED_ERROR_CODES:()=>s_,SERVER_ERROR:()=>Kh,SERVER_ERROR_CODE_RANGE:()=>dy,STANDARD_ERROR_MAP:()=>zo,formatErrorMessage:()=>X5,formatJsonRpcError:()=>d_,formatJsonRpcRequest:()=>h_,formatJsonRpcResult:()=>Ese,getBigIntRpcId:()=>f_,getError:()=>my,getErrorByCode:()=>yy,isHttpUrl:()=>Nse,isJsonRpcError:()=>Sy,isJsonRpcPayload:()=>y_,isJsonRpcRequest:()=>xse,isJsonRpcResponse:()=>w_,isJsonRpcResult:()=>uL,isJsonRpcValidationInvalid:()=>Ose,isLocalhostUrl:()=>m_,isNodeJs:()=>Y5,isReservedErrorCode:()=>py,isServerErrorCode:()=>yse,isValidDefaultRoute:()=>vy,isValidErrorCode:()=>H5,isValidLeadingWildcardRoute:()=>Sse,isValidRoute:()=>bse,isValidTrailingWildcardRoute:()=>Ise,isValidWildcardRoute:()=>Ay,isWsUrl:()=>by,parseConnectionError:()=>o_,payloadId:()=>l_,validateJsonRpcError:()=>wse});var Yh=fe(()=>{h();gy();a_();J5();Tr(Fr,Er);Z5();eL();sL();aL();cL()});var lL,Iy,fL,v_=fe(()=>{h();lL=pe(Ds());Yh();Iy=class extends $h{constructor(e){super(e),this.events=new lL.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(h_(e.method,e.params||[],e.id||f_().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Sy(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),w_(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},fL=Iy});var hL={};Bt(hL,{JsonRpcProvider:()=>Iy,default:()=>Dse});var Dse,dL=fe(()=>{h();v_();v_();Dse=fL});var pL=B((LIe,gL)=>{"use strict";h();gL.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var vL={};Bt(vL,{WsConnection:()=>A_,default:()=>A_});var wL,Pse,Rse,mL,yL,Bse,A_,AL=fe(()=>{h();wL=pe(Ds());xc();Yh();Pse=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:pL(),Rse=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",mL=t=>t.split("?")[0],yL=10,Bse=Pse(),A_=class{constructor(e){if(this.url=e,this.events=new wL.EventEmitter,this.registering=!1,!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ai(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,Fr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!m_(e)},o=new Bse(e,[],s);Rse()?o.onerror=u=>{let a=u;n(this.emitError(a.error))}:o.on("error",u=>{n(this.emitError(u))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?Ro(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=d_(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return o_(e,mL(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>yL&&this.events.setMaxListeners(yL)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${mL(this.url)}`));return this.events.emit("register_error",r),r}}});var tF=B((Jh,pl)=>{h();var Mse=200,D_="__lodash_hash_undefined__",Py=1,PL=2,RL=9007199254740991,Ty="[object Arguments]",I_="[object Array]",Lse="[object AsyncFunction]",BL="[object Boolean]",ML="[object Date]",LL="[object Error]",FL="[object Function]",Fse="[object GeneratorFunction]",_y="[object Map]",UL="[object Number]",Use="[object Null]",gl="[object Object]",EL="[object Promise]",qse="[object Proxy]",qL="[object RegExp]",Cy="[object Set]",VL="[object String]",Vse="[object Symbol]",kse="[object Undefined]",T_="[object WeakMap]",kL="[object ArrayBuffer]",Ny="[object DataView]",Hse="[object Float32Array]",Gse="[object Float64Array]",jse="[object Int8Array]",zse="[object Int16Array]",Qse="[object Int32Array]",Kse="[object Uint8Array]",Wse="[object Uint8ClampedArray]",$se="[object Uint16Array]",Yse="[object Uint32Array]",Jse=/[\\^$.*+?()[\]{}|]/g,Xse=/^\[object .+?Constructor\]$/,Zse=/^(?:0|[1-9]\d*)$/,Mt={};Mt[Hse]=Mt[Gse]=Mt[jse]=Mt[zse]=Mt[Qse]=Mt[Kse]=Mt[Wse]=Mt[$se]=Mt[Yse]=!0;Mt[Ty]=Mt[I_]=Mt[kL]=Mt[BL]=Mt[Ny]=Mt[ML]=Mt[LL]=Mt[FL]=Mt[_y]=Mt[UL]=Mt[gl]=Mt[qL]=Mt[Cy]=Mt[VL]=Mt[T_]=!1;var HL=typeof global=="object"&&global&&global.Object===Object&&global,eoe=typeof self=="object"&&self&&self.Object===Object&&self,Xs=HL||eoe||Function("return this")(),GL=typeof Jh=="object"&&Jh&&!Jh.nodeType&&Jh,bL=GL&&typeof pl=="object"&&pl&&!pl.nodeType&&pl,jL=bL&&bL.exports===GL,E_=jL&&HL.process,SL=function(){try{return E_&&E_.binding&&E_.binding("util")}catch{}}(),IL=SL&&SL.isTypedArray;function toe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function Doe(t,e){var r=this.__data__,n=By(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}Zs.prototype.clear=Coe;Zs.prototype.delete=Noe;Zs.prototype.get=xoe;Zs.prototype.has=Ooe;Zs.prototype.set=Doe;function au(t){var e=-1,r=t==null?0:t.length;for(this.clear();++eu))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,w=r&PL?new Oy:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=RL}function ZL(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ed(t){return t!=null&&typeof t=="object"}var eF=IL?soe(IL):Woe;function uae(t){return oae(t)?joe(t):$oe(t)}function cae(){return[]}function lae(){return!1}pl.exports=aae});var P_=B((HIe,rF)=>{h();rF.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},a=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:a,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return u[f.toLowerCase()]},has:function(f){return f.toLowerCase()in u}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,w){s.push(d=d.toLowerCase()),o.push([d,w]),u[d]=u[d]?u[d]+","+w:w}),r(a())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var iF=B((jIe,nF)=>{h();nF.exports=self.fetch||(self.fetch=P_().default||P_())});var fU=B(de=>{"use strict";h();Object.defineProperty(de,"__esModule",{value:!0});var cu=Ds(),fae=(nP(),_e(rP)),id=AP(),yt=(CS(),_e(_S)),ws=QS(),sF=(xc(),_e(eP)),hae=(aB(),_e(oB)),ne=Qh(),dae=(tT(),_e(eT)),Oe=Qa(),gae=(dL(),_e(hL)),an=(Yh(),_e(Fr)),pae=(AL(),_e(vL)),mae=tF(),yae=iF();function sd(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function wae(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var vae=sd(cu),Aae=sd(fae),Ly=wae(hae),Eae=sd(pae),bae=sd(mae),Sae=sd(yae);function Iae(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var Tae=Iae,_ae=Tae,bF=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Cae=t=>new TextEncoder().encode(t),Nae=t=>new TextDecoder().decode(t),M_=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},L_=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SF(this,e)}},F_=class{constructor(e){this.decoders=e}or(e){return SF(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SF=(t,e)=>new F_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),U_=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new M_(e,r,n),this.decoder=new L_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Jy=({name:t,prefix:e,encode:r,decode:n})=>new U_(t,e,r,n),od=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=_ae(r,e);return Jy({prefix:t,name:e,encode:n,decode:s=>bF(i(s))})},xae=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},Oae=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<Jy({prefix:e,name:t,encode(i){return Oae(i,n,r)},decode(i){return xae(i,n,r,t)}}),Dae=Jy({prefix:"\0",name:"identity",encode:t=>Nae(t),decode:t=>Cae(t)}),Pae=Object.freeze({__proto__:null,identity:Dae}),Rae=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Bae=Object.freeze({__proto__:null,base2:Rae}),Mae=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Lae=Object.freeze({__proto__:null,base8:Mae}),Fae=od({prefix:"9",name:"base10",alphabet:"0123456789"}),Uae=Object.freeze({__proto__:null,base10:Fae}),qae=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vae=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),kae=Object.freeze({__proto__:null,base16:qae,base16upper:Vae}),Hae=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gae=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jae=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zae=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qae=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kae=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wae=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$ae=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yae=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Jae=Object.freeze({__proto__:null,base32:Hae,base32upper:Gae,base32pad:jae,base32padupper:zae,base32hex:Qae,base32hexupper:Kae,base32hexpad:Wae,base32hexpadupper:$ae,base32z:Yae}),Xae=od({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zae=od({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),eue=Object.freeze({__proto__:null,base36:Xae,base36upper:Zae}),tue=od({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rue=od({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),nue=Object.freeze({__proto__:null,base58btc:tue,base58flickr:rue}),iue=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sue=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oue=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aue=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),uue=Object.freeze({__proto__:null,base64:iue,base64pad:sue,base64url:oue,base64urlpad:aue}),IF=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),cue=IF.reduce((t,e,r)=>(t[r]=e,t),[]),lue=IF.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fue(t){return t.reduce((e,r)=>(e+=cue[r],e),"")}function hue(t){let e=[];for(let r of t){let n=lue[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var due=Jy({prefix:"\u{1F680}",name:"base256emoji",encode:fue,decode:hue}),gue=Object.freeze({__proto__:null,base256emoji:due}),pue=TF,oF=128,mue=127,yue=~mue,wue=Math.pow(2,31);function TF(t,e,r){e=e||[],r=r||0;for(var n=r;t>=wue;)e[r++]=t&255|oF,t/=128;for(;t&yue;)e[r++]=t&255|oF,t>>>=7;return e[r]=t|0,TF.bytes=r-n+1,e}var vue=q_,Aue=128,aF=127;function q_(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw q_.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&aF)<=Aue);return q_.bytes=s-n,r}var Eue=Math.pow(2,7),bue=Math.pow(2,14),Sue=Math.pow(2,21),Iue=Math.pow(2,28),Tue=Math.pow(2,35),_ue=Math.pow(2,42),Cue=Math.pow(2,49),Nue=Math.pow(2,56),xue=Math.pow(2,63),Oue=function(t){return t(_F.encode(t,e,r),e),cF=t=>_F.encodingLength(t),V_=(t,e)=>{let r=e.byteLength,n=cF(t),i=n+cF(r),s=new Uint8Array(i+r);return uF(t,s,0),uF(r,s,n),s.set(e,i),new k_(t,r,e,s)},k_=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},CF=({name:t,code:e,encode:r})=>new H_(t,e,r),H_=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?V_(this.code,r):r.then(n=>V_(this.code,n))}else throw Error("Unknown type, must be binary type")}},NF=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pue=CF({name:"sha2-256",code:18,encode:NF("SHA-256")}),Rue=CF({name:"sha2-512",code:19,encode:NF("SHA-512")}),Bue=Object.freeze({__proto__:null,sha256:Pue,sha512:Rue}),xF=0,Mue="identity",OF=bF,Lue=t=>V_(xF,OF(t)),Fue={code:xF,name:Mue,encode:OF,digest:Lue},Uue=Object.freeze({__proto__:null,identity:Fue});new TextEncoder,new TextDecoder;var lF={...Pae,...Bae,...Lae,...Uae,...kae,...Jae,...eue,...nue,...uue,...gue};({...Bue,...Uue});function DF(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function que(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?DF(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function PF(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var fF=PF("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),R_=PF("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=que(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Vy=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=LF,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=Ly.generateKeyPair(i);return Ly.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=ne.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=Ly.generateKeyPair(s),u=ne.generateRandomBytes32(),a=FF;return await Ly.signJWT(u,i,a,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let u=this.getPrivateKey(i),a=ne.deriveSymKey(u,s);return this.setSymKey(a,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||ne.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let u=ne.validateEncoding(o),a=sF.safeJsonStringify(s);if(ne.isTypeOneEnvelope(u)){let w=u.senderPublicKey,A=u.receiverPublicKey;i=await this.generateSharedKey(w,A)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=u;return ne.encrypt({type:f,symKey:c,message:a,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let u=ne.validateDecoding(s,o);if(ne.isTypeOneEnvelope(u)){let a=u.receiverPublicKey,c=u.senderPublicKey;i=await this.generateSharedKey(a,c)}try{let a=this.getSymKey(i),c=ne.decrypt({symKey:a,encoded:s});return sF.safeJsonParse(c)}catch(a){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(a)}},this.getPayloadType=i=>{let s=ne.deserialize(i);return ne.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=ne.deserialize(i);return s.senderPublicKey?dae.toString(s.senderPublicKey,ne.BASE16):void 0},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.keychain=n||new qy(this.core,this.logger)}get context(){return yt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(G_)}catch{e=ne.generateRandomBytes32(),await this.keychain.set(G_,e)}return kue(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},ky=class extends ws.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=VF,this.version=kF,this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=ne.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=ne.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=yt.generateChildLogger(e,this.name),this.core=r}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},z_=class extends ws.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new cu.EventEmitter,this.name=GF,this.queue=new Map,this.publishTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.failedPublishTimeout=Oe.toMiliseconds(Oe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});let u=s?.ttl||HF,a=ne.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||an.getBigIntRpcId().toString(),w={topic:n,message:i,opts:{ttl:u,relay:a,prompt:c,tag:f,id:d}},A=`Failed to publish payload, please try again. id:${d} tag:${f}`,T=Date.now(),x,R=1;try{for(;x===void 0;){if(Date.now()-T>this.publishTimeout)throw new Error(A);this.logger.trace({id:d,attempts:R},`publisher.publish - attempt ${R}`),x=await await ne.createExpiringPromise(this.rpcPublish(n,i,u,a,c,f,d).catch(V=>this.logger.warn(V)),this.publishTimeout,A),R++,x||await new Promise(V=>setTimeout(V,this.failedPublishTimeout))}this.relayer.events.emit(Zn.publish,w),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}})}catch(V){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(V),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw V;this.queue.set(d,w)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return yt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,u){var a,c,f,d;let w={method:ne.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:u};return ne.isUndefined((a=w.params)==null?void 0:a.prompt)&&((c=w.params)==null||delete c.prompt),ne.isUndefined((f=w.params)==null?void 0:f.tag)&&((d=w.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w}),this.relayer.request(w)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Zn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Zn.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},Q_=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Que=Object.defineProperty,Kue=Object.defineProperties,Wue=Object.getOwnPropertyDescriptors,hF=Object.getOwnPropertySymbols,$ue=Object.prototype.hasOwnProperty,Yue=Object.prototype.propertyIsEnumerable,dF=(t,e,r)=>e in t?Que(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rd=(t,e)=>{for(var r in e||(e={}))$ue.call(e,r)&&dF(t,r,e[r]);if(hF)for(var r of hF(e))Yue.call(e,r)&&dF(t,r,e[r]);return t},B_=(t,e)=>Kue(t,Wue(e)),Hy=class extends ws.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new Q_,this.events=new cu.EventEmitter,this.name=ZF,this.version=eU,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=eo,this.subscribeTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=ne.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let u=await this.rpcSubscribe(n,s);return typeof u=="string"&&(this.onSubscribe(u,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;let i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((s,o)=>{let u=new Oe.Watch;u.start(i);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),u.stop(i),s(!0)),u.elapsed(i)>=tU&&(clearInterval(a),u.stop(i),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.clientId=""}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=ne.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=ne.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:ne.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?ne.hashMessage(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Zn.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:ne.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(Zn.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:ne.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,B_(rd({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rd({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rd({},r)),this.topicMap.set(r.topic,e),this.events.emit(_i.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(_i.deleted,B_(rd({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_i.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);ne.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>B_(rd({},e[i]),{id:n})))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(_i.created,async e=>{let r=_i.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(_i.deleted,async e=>{let r=_i.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},Jue=Object.defineProperty,gF=Object.getOwnPropertySymbols,Xue=Object.prototype.hasOwnProperty,Zue=Object.prototype.propertyIsEnumerable,pF=(t,e,r)=>e in t?Jue(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ece=(t,e)=>{for(var r in e||(e={}))Xue.call(e,r)&&pF(t,r,e[r]);if(gF)for(var r of gF(e))Zue.call(e,r)&&pF(t,r,e[r]);return t},Gy=class extends ws.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new cu.EventEmitter,this.name=QF,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Oe.toMiliseconds(Oe.THIRTY_SECONDS+Oe.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");let s=r.id||an.getBigIntRpcId().toString();await this.toEstablishConnection();try{let o=this.provider.request(r);this.requestsInFlight.set(s,{promise:o,request:r}),this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");let u=await new Promise(async(a,c)=>{let f=()=>{c(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(yn.disconnect,f);let d=await o;this.provider.off(yn.disconnect,f),a(d)});return this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),u}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(ne.isNode())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(Zn.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Zn.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(yn.payload,this.onPayloadHandler),this.provider.on(yn.connect,this.onConnectHandler),this.provider.on(yn.disconnect,this.onDisconnectHandler),this.provider.on(yn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?yt.generateChildLogger(e.logger,this.name):yt.pino(yt.getDefaultLoggerOptions({level:e.logger||zF})),this.messages=new ky(this.logger,e.core),this.subscriber=new Hy(this,this.logger),this.publisher=new z_(this,this.logger),this.relayUrl=e?.relayUrl||W_,this.projectId=e.projectId,this.bundleId=ne.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${j_}...`),await this.restartTransport(j_)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},YF)}get context(){return yt.getLoggerContext(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",s,o=u=>{u.topic===e&&(this.subscriber.off(_i.created,o),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(_i.created,o)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,r)||i,u()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await ne.createExpiringPromise(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect(),await this.createProvider()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{let i=()=>{this.provider.off(yn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(yn.disconnect,i),await ne.createExpiringPromise(this.provider.connect(),Oe.toMiliseconds(Oe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{n(s)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ne.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}startPingTimeout(){var e,r,n,i,s;if(ne.isNode())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new gae.JsonRpcProvider(new Eae.default(ne.formatRelayRpcUrl({sdkVersion:$F,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),an.isJsonRpcRequest(e)){if(!e.method.endsWith(KF))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ece({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else an.isJsonRpcResponse(e)&&this.events.emit(Zn.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Zn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=an.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(yn.payload,this.onPayloadHandler),this.provider.off(yn.connect,this.onConnectHandler),this.provider.off(yn.disconnect,this.onDisconnectHandler),this.provider.off(yn.error,this.onProviderErrorHandler)}async registerEventListeners(){let e=await ne.isOnline();ne.subscribeToNetworkChange(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.events.emit(Zn.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Oe.toMiliseconds(WF))}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}},tce=Object.defineProperty,mF=Object.getOwnPropertySymbols,rce=Object.prototype.hasOwnProperty,nce=Object.prototype.propertyIsEnumerable,yF=(t,e,r)=>e in t?tce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wF=(t,e)=>{for(var r in e||(e={}))rce.call(e,r)&&yF(t,r,e[r]);if(mF)for(var r of mF(e))nce.call(e,r)&&yF(t,r,e[r]);return t},jy=class extends ws.IStore{constructor(e,r,n,i=eo,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=JF,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ne.isUndefined(o)?this.map.set(this.getKey(o),o):ne.isProposalStruct(o)?this.map.set(o.id,o):ne.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,u)=>{this.isInitialized(),this.map.has(o)?await this.update(o,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:u}),this.map.set(o,u),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(u=>Object.keys(o).every(a=>bae.default(u[a],o[a]))):this.values),this.update=async(o,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:u});let a=wF(wF({},this.getData(o)),u);this.map.set(o,a),await this.persist()},this.delete=async(o,u)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:u}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())},this.logger=yt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},zy=class{constructor(e,r){this.core=e,this.logger=r,this.name=rU,this.version=nU,this.events=new vae.default,this.initialized=!1,this.storagePrefix=eo,this.ignoredPayloadTypes=[ne.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let i=ne.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),o=ne.calcExpiry(Oe.FIVE_MINUTES),u={protocol:jF},a={topic:s,expiry:o,relay:u,active:!1},c=ne.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:u,expiryTimestamp:o,methods:n?.methods});return await this.pairings.set(s,a),await this.core.relayer.subscribe(s),this.core.expirer.set(s,o),{topic:s,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o,expiryTimestamp:u,methods:a}=ne.parseUri(n.uri),c;if(this.pairings.keys.includes(i)&&(c=this.pairings.get(i),c.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let f=u||ne.calcExpiry(Oe.FIVE_MINUTES),d={topic:i,relay:o,expiry:f,active:!1,methods:a};return await this.pairings.set(i,d),this.core.expirer.set(i,f),n.activatePairing&&await this.activate({topic:i}),this.events.emit(nd.create,d),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),d},this.activate=async({topic:n})=>{this.isInitialized();let i=ne.calcExpiry(Oe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:u,reject:a}=ne.createDelayedPromise();this.events.once(ne.engineEvent("pairing_ping",s),({error:c})=>{c?a(c):u()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ne.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=an.formatJsonRpcRequest(i,s),u=await this.core.crypto.encode(n,o),a=yl[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,u,a),o.id},this.sendResult=async(n,i,s)=>{let o=an.formatJsonRpcResult(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method].res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=an.formatJsonRpcError(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method]?yl[a.request.method].res:yl.unregistered_method.res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,ne.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>ne.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(nd.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{an.isJsonRpcResult(i)?this.events.emit(ne.engineEvent("pairing_ping",s),{}):an.isJsonRpcError(i)&&this.events.emit(ne.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(nd.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let u=ne.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,u),this.logger.error(u)}catch(u){await this.sendError(s,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(ne.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!ne.isValidParams(n)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!ne.isValidUrl(n.uri)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=ne.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(s!=null&&s.expiryTimestamp&&Oe.toMiliseconds(s?.expiryTimestamp){if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ne.isValidString(n,!1)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=ne.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ne.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=ne.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.pairings=new jy(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Zn.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{an.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):an.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Xn.expired,async e=>{let{topic:r}=ne.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(nd.expire,{topic:r}))})}},Qy=class extends ws.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new cu.EventEmitter,this.name=iU,this.version=sU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:ne.calcExpiry(Oe.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=an.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Jn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Jn.deleted,s)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:an.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jn.created,e=>{let r=Jn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.updated,e=>{let r=Jn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.deleted,e=>{let r=Jn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Oe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Jn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ky=class extends ws.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new cu.EventEmitter,this.name=oU,this.version=aU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Xn.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Xn.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ne.formatTopicTarget(e);if(typeof e=="number")return ne.formatIdTarget(e);let{message:r}=ne.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Xn.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Oe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Xn.created,e=>{let r=Xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.expired,e=>{let r=Xn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.deleted,e=>{let r=Xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wy=class extends ws.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=Fy,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||ne.isReactNative()||!ne.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Uy;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,Uy)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Oe.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{let o=document.getElementById(Fy);if(o)return this.iframe=o,this.onInit(),s();window.addEventListener("message",i);let u=document.createElement("iframe");u.id=Fy,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Oe.toMiliseconds(Oe.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||wl;return uU.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${wl}`),i=wl),i},this.logger=yt.generateChildLogger(r,this.name),this.verifyUrl=wl,this.abortController=new AbortController,this.isDevEnv=ne.isNode()&&I.default.env.IS_VITEST}get context(){return yt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Oe.toMiliseconds(e))}},$y=class extends ws.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=cU,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:u=!1}=n,a=`${lU}/${this.projectId}/clients`;await Sae.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:u})})},this.logger=yt.generateChildLogger(r,this.context)}},ice=Object.defineProperty,vF=Object.getOwnPropertySymbols,sce=Object.prototype.hasOwnProperty,oce=Object.prototype.propertyIsEnumerable,AF=(t,e,r)=>e in t?ice(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,EF=(t,e)=>{for(var r in e||(e={}))sce.call(e,r)&&AF(t,r,e[r]);if(vF)for(var r of vF(e))oce.call(e,r)&&AF(t,r,e[r]);return t},Yy=class t extends ws.ICore{constructor(e){var r;super(e),this.protocol=K_,this.version=RF,this.name=Xy,this.events=new cu.EventEmitter,this.initialized=!1,this.on=(o,u)=>this.events.on(o,u),this.once=(o,u)=>this.events.once(o,u),this.off=(o,u)=>this.events.off(o,u),this.removeListener=(o,u)=>this.events.removeListener(o,u),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||W_,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let n=yt.getDefaultLoggerOptions({level:typeof e?.logger=="string"&&e.logger?e.logger:BF.logger}),{logger:i,chunkLoggerController:s}=yt.generatePlatformLogger({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,u;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=yt.generateChildLogger(i,this.name),this.heartbeat=new id.HeartBeat,this.crypto=new Vy(this,this.logger,e?.keychain),this.history=new Qy(this,this.logger),this.expirer=new Ky(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Aae.default(EF(EF({},MF),e?.storageOptions)),this.relayer=new Gy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new zy(this,this.logger),this.verify=new Wy(this.projectId||"",this.logger),this.echoClient=new $y(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(XF,n),r}get context(){return yt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},ace=Yy;de.CORE_CONTEXT=Xy,de.CORE_DEFAULT=BF,de.CORE_PROTOCOL=K_,de.CORE_STORAGE_OPTIONS=MF,de.CORE_STORAGE_PREFIX=eo,de.CORE_VERSION=RF,de.CRYPTO_CLIENT_SEED=G_,de.CRYPTO_CONTEXT=LF,de.CRYPTO_JWT_TTL=FF,de.Core=ace,de.Crypto=Vy,de.ECHO_CONTEXT=cU,de.ECHO_URL=lU,de.EXPIRER_CONTEXT=oU,de.EXPIRER_DEFAULT_TTL=zue,de.EXPIRER_EVENTS=Xn,de.EXPIRER_STORAGE_VERSION=aU,de.EchoClient=$y,de.Expirer=Ky,de.HISTORY_CONTEXT=iU,de.HISTORY_EVENTS=Jn,de.HISTORY_STORAGE_VERSION=sU,de.JsonRpcHistory=Qy,de.KEYCHAIN_CONTEXT=UF,de.KEYCHAIN_STORAGE_VERSION=qF,de.KeyChain=qy,de.MESSAGES_CONTEXT=VF,de.MESSAGES_STORAGE_VERSION=kF,de.MessageTracker=ky,de.PAIRING_CONTEXT=rU,de.PAIRING_DEFAULT_TTL=jue,de.PAIRING_EVENTS=nd,de.PAIRING_RPC_OPTS=yl,de.PAIRING_STORAGE_VERSION=nU,de.PENDING_SUB_RESOLUTION_TIMEOUT=tU,de.PUBLISHER_CONTEXT=GF,de.PUBLISHER_DEFAULT_TTL=HF,de.Pairing=zy,de.RELAYER_CONTEXT=QF,de.RELAYER_DEFAULT_LOGGER=zF,de.RELAYER_DEFAULT_PROTOCOL=jF,de.RELAYER_DEFAULT_RELAY_URL=W_,de.RELAYER_EVENTS=Zn,de.RELAYER_FAILOVER_RELAY_URL=j_,de.RELAYER_PROVIDER_EVENTS=yn,de.RELAYER_RECONNECT_TIMEOUT=WF,de.RELAYER_SDK_VERSION=$F,de.RELAYER_STORAGE_OPTIONS=Hue,de.RELAYER_SUBSCRIBER_SUFFIX=KF,de.RELAYER_TRANSPORT_CUTOFF=YF,de.Relayer=Gy,de.STORE_STORAGE_VERSION=JF,de.SUBSCRIBER_CONTEXT=ZF,de.SUBSCRIBER_DEFAULT_TTL=Gue,de.SUBSCRIBER_EVENTS=_i,de.SUBSCRIBER_STORAGE_VERSION=eU,de.Store=jy,de.Subscriber=Hy,de.TRUSTED_VERIFY_URLS=uU,de.VERIFY_CONTEXT=Fy,de.VERIFY_FALLBACK_SERVER=Uy,de.VERIFY_SERVER=wl,de.Verify=Wy,de.WALLETCONNECT_CLIENT_ID=XF,de.default=Yy});var CU=B(Be=>{"use strict";h();Object.defineProperty(Be,"__esModule",{value:!0});var un=fU(),Zy=(CS(),_e(_S)),gU=QS(),G=Qh(),pU=Ds(),Dt=Qa(),qe=(Yh(),_e(Fr));function uce(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var cce=uce(pU),n2="wc",i2=2,s2="client",i1=`${n2}@${i2}:${s2}:`,e1={name:s2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},lce={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},fce={database:":memory:"},$_="WALLETCONNECT_DEEPLINK_CHOICE",hce={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},dce="history",gce="0.3",mU="proposal",pce=Dt.THIRTY_DAYS,yU="Proposal expired",wU="session",lu=Dt.SEVEN_DAYS,vU="engine",wn={wc_sessionPropose:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Dt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Dt.ONE_HOUR,prompt:!1,tag:1117}}},t1={min:Dt.FIVE_MINUTES,max:Dt.SEVEN_DAYS},vs={idle:"IDLE",active:"ACTIVE"},AU="request",EU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],bU="wc",mce=1.5,SU="auth",IU="authKeys",TU="pairingTopics",_U="requests",ud=`${bU}@${1.5}:${SU}:`,ad=`${ud}:PUB_KEY`,yce=Object.defineProperty,wce=Object.defineProperties,vce=Object.getOwnPropertyDescriptors,hU=Object.getOwnPropertySymbols,Ace=Object.prototype.hasOwnProperty,Ece=Object.prototype.propertyIsEnumerable,dU=(t,e,r)=>e in t?yce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e)=>{for(var r in e||(e={}))Ace.call(e,r)&&dU(t,r,e[r]);if(hU)for(var r of hU(e))Ece.call(e,r)&&dU(t,r,e[r]);return t},vl=(t,e)=>wce(t,vce(e)),Y_=class extends gU.IEngine{constructor(e){super(e),this.name=vU,this.events=new cce.default,this.initialized=!1,this.requestQueue={state:vs.idle,queue:[]},this.sessionRequestQueue={state:vs.idle,queue:[]},this.requestQueueDelay=Dt.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=vl(br({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:u,relays:a}=n,c=i,f,d=!1;try{c&&(d=this.client.core.pairing.pairings.get(c).active)}catch(L){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),L}if(!c||!d){let{topic:L,uri:k}=await this.client.core.pairing.create();c=L,f=k}if(!c){let{message:L}=G.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(L)}let w=await this.client.core.crypto.generateKeyPair(),A=wn.wc_sessionPropose.req.ttl||Dt.FIVE_MINUTES,T=G.calcExpiry(A),x=br({requiredNamespaces:s,optionalNamespaces:o,relays:a??[{protocol:un.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:T},u&&{sessionProperties:u}),{reject:R,resolve:V,done:U}=G.createDelayedPromise(A,yU);this.events.once(G.engineEvent("session_connect"),async({error:L,session:k})=>{if(L)R(L);else if(k){k.self.publicKey=w;let H=vl(br({},k),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:k.peer.metadata}),V(H)}});let Q=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:x,throwOnFailedPublish:!0});return await this.setProposal(Q,br({id:Q},x)),{uri:f,approval:U}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),U}let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o,sessionConfig:u}=r,a;try{a=this.client.proposal.get(n)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),U}let{pairingTopic:c,proposer:f,requiredNamespaces:d,optionalNamespaces:w}=a;c=c||"";let A=await this.client.core.crypto.generateKeyPair(),T=f.publicKey,x=await this.client.core.crypto.generateSharedKey(A,T),R=br(br({relay:{protocol:i??"irn"},namespaces:s,pairingTopic:c,controller:{publicKey:A,metadata:this.client.metadata},expiry:G.calcExpiry(lu)},o&&{sessionProperties:o}),u&&{sessionConfig:u});await this.client.core.relayer.subscribe(x);let V=vl(br({},R),{topic:x,requiredNamespaces:d,optionalNamespaces:w,pairingTopic:c,acknowledged:!1,self:R.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A});await this.client.session.set(x,V);try{await this.sendResult({id:n,topic:c,result:{relay:{protocol:i??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:R,throwOnFailedPublish:!0})}catch(U){throw this.client.logger.error(U),this.client.session.delete(x,G.getSdkError("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),U}return await this.client.core.pairing.updateMetadata({topic:c,metadata:f.metadata}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}),await this.setExpiry(x,G.calcExpiry(lu)),{topic:x,acknowledged:()=>new Promise(U=>setTimeout(()=>U(this.client.session.get(x)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}let{id:n,reason:i}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}let{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:u}=G.createDelayedPromise(),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),f=this.client.session.get(n).namespaces;return this.events.once(G.engineEvent("session_update",a),({error:d})=>{d?u(d):o()}),await this.client.session.update(n,{namespaces:i}),this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:f}),u(d)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}let{topic:n}=r,i=qe.payloadId(),{done:s,resolve:o,reject:u}=G.createDelayedPromise();return this.events.once(G.engineEvent("session_extend",i),({error:a})=>{a?u(a):o()}),await this.setExpiry(n,G.calcExpiry(lu)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(a=>{u(a)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(A){throw this.client.logger.error("request() -> isValidRequest() failed"),A}let{chainId:n,request:i,topic:s,expiry:o=wn.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),{done:f,resolve:d,reject:w}=G.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(G.engineEvent("session_request",a),({error:A,result:T})=>{A?w(A):d(T)}),await Promise.all([new Promise(async A=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:s,method:"wc_sessionRequest",params:{request:vl(br({},i),{expiryTimestamp:G.calcExpiry(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(T=>w(T)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),A()}),new Promise(async A=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){let x=await G.getDeepLink(this.client.core.storage,$_);G.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:x})}A()}),f()]).then(A=>A[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;qe.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):qe.isJsonRpcError(i)&&await this.sendError({id:s,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=qe.payloadId(),s=qe.getBigIntRpcId().toString(),{done:o,resolve:u,reject:a}=G.createDelayedPromise();this.events.once(G.engineEvent("session_ping",i),({error:c})=>{c?a(c):u()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r,o=qe.getBigIntRpcId().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:G.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:i}=G.getInternalError("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>G.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);let{chains:n,statement:i="",uri:s,domain:o,nonce:u,type:a,exp:c,nbf:f,methods:d=[]}=r,w=[...r.resources||[]],{topic:A,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:T}});let x=await this.client.core.crypto.generateKeyPair(),R=G.hashKey(x);if(await Promise.all([this.client.auth.authKeys.set(ad,{responseTopic:R,publicKey:x}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:A})]),await this.client.core.relayer.subscribe(R),this.client.logger.info(`sending request to new pairing topic: ${A}`),d.length>0){let{namespace:P}=G.parseChainId(n[0]),l=G.createEncodedRecap(P,"request",d);G.getRecapFromResources(w)&&(l=G.mergeEncodedRecaps(l,w.pop())),w.push(l)}let V=G.calcExpiry(wn.wc_sessionPropose.req.ttl),U={authPayload:{type:a??"caip122",chains:n,statement:i,aud:s,domain:o,version:"1",nonce:u,iat:new Date().toISOString(),exp:c,nbf:f,resources:w},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},Q={eip155:{chains:n,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},L={requiredNamespaces:{},optionalNamespaces:Q,relays:[{protocol:"irn"}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},{done:k,resolve:H,reject:q}=G.createDelayedPromise(wn.wc_sessionAuthenticate.req.ttl,"Request expired"),v=async({error:P,session:l})=>{if(this.events.off(G.engineEvent("session_request",D),C),P)q(P);else if(l){l.self.publicKey=x,await this.client.session.set(l.topic,l),await this.setExpiry(l.topic,l.expiry),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:l.peer.metadata});let g=this.client.session.get(l.topic);H({session:g})}},C=async P=>{if(P.error){let M=G.getSdkError("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===M.code?void 0:(this.events.off(G.engineEvent("session_connect"),v),q(P.error.message))}this.events.off(G.engineEvent("session_connect"),v);let{cacaos:l,responder:g}=P.result,y=[],E=[];for(let M of l){await G.validateSignedCacao({cacao:M,projectId:this.client.core.projectId})||(this.client.logger.error(M,"Signature verification failed"),q(G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:N}=M,m=G.getRecapFromResources(N.resources),O=[G.getNamespacedDidChainId(N.iss)],Y=G.getDidAddress(N.iss);if(m){let $=G.getMethodsFromRecap(m),b=G.getChainsFromRecap(m);y.push(...$),O.push(...b)}for(let $ of O)E.push(`${$}:${Y}`)}let S=await this.client.core.crypto.generateSharedKey(x,g.publicKey),_;y.length>0&&(_={topic:S,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:g,controller:g.publicKey,expiry:G.calcExpiry(lu),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:G.buildNamespacesFromAuth([...new Set(y)],[...new Set(E)])},await this.client.core.relayer.subscribe(S),await this.client.session.set(S,_),_=this.client.session.get(S)),H({auths:l,session:_})},D=qe.payloadId(),F=qe.payloadId();this.events.once(G.engineEvent("session_connect"),v),this.events.once(G.engineEvent("session_request",D),C);try{await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:D}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:L,expiry:wn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:F})])}catch(P){throw this.events.off(G.engineEvent("session_connect"),v),this.events.off(G.engineEvent("session_request",D),C),P}return await this.setProposal(F,br({id:F},L)),await this.client.auth.requests.set(D,{authPayload:U.authPayload,requester:U.requester,expiryTimestamp:V,id:D,pairingTopic:A,verifyContext:{}}),{uri:T,response:k}},this.approveSessionAuthenticate=async r=>{this.isInitialized();let{id:n,auths:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u},f=[],d=[];for(let T of i){if(!await G.validateSignedCacao({cacao:T,projectId:this.client.core.projectId})){let Q=G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:a,error:Q,encodeOpts:c}),new Error(Q.message)}let{p:x}=T,R=G.getRecapFromResources(x.resources),V=[G.getNamespacedDidChainId(x.iss)],U=G.getDidAddress(x.iss);if(R){let Q=G.getMethodsFromRecap(R),L=G.getChainsFromRecap(R);f.push(...Q),V.push(...L)}for(let Q of V)d.push(`${Q}:${U}`)}let w=await this.client.core.crypto.generateSharedKey(u,o),A;return f?.length>0&&(A={topic:w,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:o,metadata:s.requester.metadata},controller:o,expiry:G.calcExpiry(lu),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:G.buildNamespacesFromAuth([...new Set(f)],[...new Set(d)])},await this.client.core.relayer.subscribe(w),await this.client.session.set(w,A)),await this.sendResult({topic:a,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:c,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fullfilled",code:0}),await this.client.core.pairing.activate({topic:s.pairingTopic}),{session:A}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();let{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u};await this.sendError({id:n,topic:a,error:i,encodeOpts:c}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:i}=r;return G.formatMessage(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,u;return((o=s.peerMetadata)==null?void 0:o.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:i=!1,emitEvent:s=!0,id:o=0}=r,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,G.getSdkError("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem($_).catch(a=>this.client.logger.warn(a)),this.getPendingSessionRequests().forEach(a=>{a.topic===n&&this.deletePendingSessionRequest(a.id,G.getSdkError("USER_DISCONNECTED"))}),s&&this.client.events.emit("session_delete",{id:o,topic:n})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,G.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=vs.idle,this.client.events.emit("session_request_expire",{id:r}))},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,G.calcExpiry(wn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async r=>{let{id:n,topic:i,params:s,verifyContext:o}=r,u=s.request.expiryTimestamp||G.calcExpiry(wn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:u,clientRpcId:a,throwOnFailedPublish:c}=r,f=qe.formatJsonRpcRequest(i,s,a);if(G.isBrowser()&&EU.includes(i)){let A=G.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:A})}let d;try{d=await this.client.core.crypto.encode(n,f)}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let w=wn[i].req;return o&&(w.ttl=o),u&&(w.id=u),this.client.core.history.set(n,f),c?(w.internal=vl(br({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(A=>this.client.logger.error(A)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:u}=r,a=qe.formatJsonRpcResult(n,s),c;try{c=await this.client.core.crypto.encode(i,a,u)}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let f;try{f=await this.client.core.history.get(i,n)}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),w}let d=wn[f.request.method].res;o?(d.internal=vl(br({},d.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,c,d)):this.client.core.relayer.publish(i,c,d).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(a)},this.sendError=async r=>{let{id:n,topic:i,error:s,encodeOpts:o}=r,u=qe.formatJsonRpcError(n,s),a;try{a=await this.client.core.crypto.encode(i,u,o)}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let c;try{c=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}let f=wn[c.request.method].res;this.client.core.relayer.publish(i,a,f),await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;G.isExpired(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{G.isExpired(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===vs.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vs.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=vs.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:s}))switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=G.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(br({},n.params));let o=i.expiryTimestamp||G.calcExpiry(wn.wc_sessionPropose.req.ttl),u=br({id:s,pairingTopic:r,expiryTimestamp:o},i);await this.setProposal(s,u);let a=G.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(a,u.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:u,verifyContext:c})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(qe.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let u=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});let a=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});let c=await this.client.core.crypto.generateSharedKey(u,a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(qe.isJsonRpcError(n)){await this.client.proposal.delete(i,G.getSdkError("USER_DISCONNECTED"));let s=G.engineEvent("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners, 954`);this.events.emit(G.engineEvent("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:u,expiry:a,namespaces:c,sessionProperties:f,pairingTopic:d,sessionConfig:w}=n.params,A=br(br({topic:r,relay:o,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:d,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},f&&{sessionProperties:f}),w&&{sessionConfig:w});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});let T=G.engineEvent("session_connect");if(this.events.listenerCount(T)===0)throw new Error(`emitting ${T} without any listeners 997`);this.events.emit(G.engineEvent("session_connect"),{session:A}),this.cleanupDuplicatePairings(A)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;qe.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(G.engineEvent("session_approve",i),{})):qe.isJsonRpcError(n)&&(await this.client.session.delete(r,G.getSdkError("USER_DISCONNECTED")),this.events.emit(G.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:G.getSdkError("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(br({topic:r},i));try{G.MemoryStore.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){throw G.MemoryStore.delete(o),a}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_update",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,G.calcExpiry(lu)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_extend",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_ping",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_ping",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(un.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:G.getSdkError("USER_DISCONNECTED")})])}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{await this.isValidRequest(br({topic:r},s));let o=G.hashMessage(JSON.stringify(qe.formatJsonRpcRequest("wc_sessionRequest",s,i))),u=this.client.session.get(r),a=await this.getVerifyContext(o,u.peer.metadata),c={id:i,topic:r,params:s,verifyContext:a};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(br({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),G.MemoryStore.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{let{requester:i,authPayload:s,expiryTimestamp:o}=n.params,u=G.hashMessage(JSON.stringify(n)),a=await this.getVerifyContext(u,this.client.metadata),c={requester:i,pairingTopic:r,id:n.id,authPayload:s,verifyContext:a,expiryTimestamp:o};await this.client.auth.requests.set(n.id,c),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vs.idle,this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{let o=s.request.id,u=G.engineEvent("session_request",o);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(G.engineEvent("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===vs.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vs.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,qe.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(a)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:u}=r;if(G.isUndefined(n)||await this.isValidPairingTopic(n),!G.isValidRelays(u,!0)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(a)}!G.isUndefined(i)&&G.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!G.isUndefined(s)&&G.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=G.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!G.isValidParams(r))throw new Error(G.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let u=this.client.proposal.get(n),a=G.isValidNamespaces(i,"approve()");if(a)throw new Error(a.message);let c=G.isConformingNamespaces(u.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!G.isValidString(s,!0)){let{message:f}=G.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!G.isValidParams(r)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!G.isValidErrorReason(i)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!G.isValidParams(r)){let{message:c}=G.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!G.isValidRelay(n)){let{message:c}=G.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let u=G.isValidController(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);let a=G.isValidNamespaces(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(G.isExpired(o)){let{message:c}=G.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(a)}let{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=G.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let u=G.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(a)}let{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:u}=this.client.session.get(n);if(!G.isValidNamespacesChainId(u,s)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(a)}if(!G.isValidRequest(i)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(a)}if(!G.isValidNamespacesRequest(u,s,i.method)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(a)}if(o&&!G.isValidRequestExpiry(o,t1)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${t1.min} and ${t1.max}`);throw new Error(a)}},this.isValidRespond=async r=>{var n;if(!G.isValidParams(r)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!G.isValidResponse(s)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!G.isValidParams(r)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!G.isValidNamespacesChainId(o,s)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!G.isValidEvent(i)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!G.isValidNamespacesEvent(o,s,i.name)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!G.isValidString(i,!1))throw new Error("uri is required parameter");if(!G.isValidString(s,!1))throw new Error("domain is required parameter");if(!G.isValidString(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(a=>G.parseChainId(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:u}=G.parseChainId(n[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||un.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!G.isValidString(i,!1)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0,s=this.recentlyDeletedLimit/2;for(let o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){let{message:e}=G.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(un.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(ad)?this.client.auth.authKeys.get(ad):{responseTopic:void 0,publicKey:void 0},s=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{qe.isJsonRpcRequest(s)?(this.client.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):qe.isJsonRpcResponse(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.client.core.history.delete(r,s.id)):this.onRelayEventUnknownPayload({topic:r,payload:s})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(un.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=G.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,G.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(un.PAIRING_EVENTS.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(un.PAIRING_EVENTS.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=G.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:r}=G.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(G.isValidString(e,!1)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!G.isValidId(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:r}=G.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},J_=class extends un.Store{constructor(e,r){super(e,r,mU,i1),this.core=e,this.logger=r}},r1=class extends un.Store{constructor(e,r){super(e,r,wU,i1),this.core=e,this.logger=r}},X_=class extends un.Store{constructor(e,r){super(e,r,AU,i1,n=>n.id),this.core=e,this.logger=r}},Z_=class extends un.Store{constructor(e,r){super(e,r,IU,ud,()=>ad),this.core=e,this.logger=r}},e2=class extends un.Store{constructor(e,r){super(e,r,TU,ud),this.core=e,this.logger=r}},t2=class extends un.Store{constructor(e,r){super(e,r,_U,ud,n=>n.id),this.core=e,this.logger=r}},r2=class{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new Z_(this.core,this.logger),this.pairingTopics=new e2(this.core,this.logger),this.requests=new t2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},n1=class t extends gU.ISignClient{constructor(e){super(e),this.protocol=n2,this.version=i2,this.name=e1.name,this.events=new pU.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||e1.name,this.metadata=e?.metadata||G.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zy.pino(Zy.getDefaultLoggerOptions({level:e?.logger||e1.logger}));this.core=e?.core||new un.Core(e),this.logger=Zy.generateChildLogger(r,this.name),this.session=new r1(this.core,this.logger),this.proposal=new J_(this.core,this.logger),this.pendingRequest=new X_(this.core,this.logger),this.engine=new Y_(this),this.auth=new r2(this.core,this.logger)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Zy.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},bce=r1,Sce=n1;Be.AUTH_CONTEXT=SU,Be.AUTH_KEYS_CONTEXT=IU,Be.AUTH_PAIRING_TOPIC_CONTEXT=TU,Be.AUTH_PROTOCOL=bU,Be.AUTH_PUBLIC_KEY_NAME=ad,Be.AUTH_REQUEST_CONTEXT=_U,Be.AUTH_STORAGE_PREFIX=ud,Be.AUTH_VERSION=mce,Be.ENGINE_CONTEXT=vU,Be.ENGINE_QUEUE_STATES=vs,Be.ENGINE_RPC_OPTS=wn,Be.HISTORY_CONTEXT=dce,Be.HISTORY_EVENTS=hce,Be.HISTORY_STORAGE_VERSION=gce,Be.METHODS_TO_VERIFY=EU,Be.PROPOSAL_CONTEXT=mU,Be.PROPOSAL_EXPIRY=pce,Be.PROPOSAL_EXPIRY_MESSAGE=yU,Be.REQUEST_CONTEXT=AU,Be.SESSION_CONTEXT=wU,Be.SESSION_EXPIRY=lu,Be.SESSION_REQUEST_EXPIRY_BOUNDARIES=t1,Be.SIGN_CLIENT_CONTEXT=s2,Be.SIGN_CLIENT_DEFAULT=e1,Be.SIGN_CLIENT_EVENTS=lce,Be.SIGN_CLIENT_PROTOCOL=n2,Be.SIGN_CLIENT_STORAGE_OPTIONS=fce,Be.SIGN_CLIENT_STORAGE_PREFIX=i1,Be.SIGN_CLIENT_VERSION=i2,Be.SessionStore=bce,Be.SignClient=Sce,Be.WALLETCONNECT_DEEPLINK_CHOICE=$_,Be.default=n1});var s1=B(Yo=>{"use strict";h();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.OptionalOperation=Yo.Operation=void 0;var Ice;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(Ice=Yo.Operation||(Yo.Operation={}));var Tce;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(Tce=Yo.OptionalOperation||(Yo.OptionalOperation={}))});var o2=B(As=>{"use strict";h();Object.defineProperty(As,"__esModule",{value:!0});As.WALLETCONNECT_SIGN_LOGIN_DELAY=As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=As.WALLETCONNECT_MULTIVERSX_METHODS=As.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var NU=s1();As.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";As.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(NU.Operation);As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(NU.OptionalOperation);As.WALLETCONNECT_SIGN_LOGIN_DELAY=500});var c2=B(Ci=>{"use strict";h();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WalletConnectV2ProviderErrorMessagesEnum=Ci.ErrBadAddress=Ci.ErrNotImplemented=Ci.Err=void 0;var cd=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ci.Err=cd;var a2=class extends cd{constructor(){super("Method not yet implemented")}};Ci.ErrNotImplemented=a2;var u2=class extends cd{constructor(e,r){super(`Bad address: ${e}`,r)}};Ci.ErrBadAddress=u2;var _ce;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(_ce=Ci.WalletConnectV2ProviderErrorMessagesEnum||(Ci.WalletConnectV2ProviderErrorMessagesEnum={}))});var f2=B(o1=>{"use strict";h();Object.defineProperty(o1,"__esModule",{value:!0});o1.Logger=void 0;var l2=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};o1.Logger=l2});var xU=B(()=>{"use strict";h();global.Buffer||(global.Buffer=io().Buffer)});var g2=B(Al=>{"use strict";h();Object.defineProperty(Al,"__esModule",{value:!0});Al.SmartContractQueryResponse=Al.SmartContractQuery=void 0;var h2=class{constructor(e){this.contract=e.contract,this.caller=e.caller,this.value=e.value,this.function=e.function,this.arguments=e.arguments}};Al.SmartContractQuery=h2;var d2=class{constructor(e){this.function=e.function,this.returnCode=e.returnCode,this.returnMessage=e.returnMessage,this.returnDataParts=e.returnDataParts}};Al.SmartContractQueryResponse=d2});var DU=B(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});a1.QueryRunnerAdapter=void 0;var OU=Ve(),Cce=g2(),p2=class{constructor(e){this.networkProvider=e.networkProvider}async runQuery(e){let r={address:OU.Address.fromBech32(e.contract),caller:e.caller?OU.Address.fromBech32(e.caller):void 0,func:e.function,value:e.value,getEncodedArguments:()=>e.arguments.map(i=>p.Buffer.from(i).toString("hex"))},n=await this.networkProvider.queryContract(r);return new Cce.SmartContractQueryResponse({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.getReturnDataParts()})}};a1.QueryRunnerAdapter=p2});var PU=B(fu=>{"use strict";h();var Nce=fu&&fu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xce=fu&&fu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Nce(e,t,r)};Object.defineProperty(fu,"__esModule",{value:!0});xce(DU(),fu)});var RU=B(hu=>{"use strict";h();var Oce=hu&&hu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dce=hu&&hu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Oce(e,t,r)};Object.defineProperty(hu,"__esModule",{value:!0});Dce(JE(),hu)});var MU=B(du=>{"use strict";h();Object.defineProperty(du,"__esModule",{value:!0});du.GasEstimator=du.DefaultGasConfiguration=void 0;du.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Pce=1e5,BU=8e5,m2=class{constructor(e){this.gasConfiguration=e||du.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Pce}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+BU}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+BU)*r+this.gasConfiguration.gasPerDataByte*e}};du.GasEstimator=m2});var FU=B(LU=>{"use strict";h();Object.defineProperty(LU,"__esModule",{value:!0})});var qU=B(UU=>{"use strict";h();Object.defineProperty(UU,"__esModule",{value:!0})});var VU=B(u1=>{"use strict";h();Object.defineProperty(u1,"__esModule",{value:!0});u1.RelayedTransactionV1Builder=void 0;var y2=Ve(),Rce=Ie(),Bce=Xr(),Mce=Ms(),Lce=oE(),w2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new Rce.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${p.Buffer.from(e).toString("hex")}`,n=new Mce.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new Bce.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new y2.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new y2.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:BigInt(this.innerTransaction.getValue().toString()),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:p.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new y2.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?p.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?p.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return Lce.stringify(e)}};u1.RelayedTransactionV1Builder=w2});var HU=B(c1=>{"use strict";h();Object.defineProperty(c1,"__esModule",{value:!0});c1.RelayedTransactionV2Builder=void 0;var kU=Ie(),ld=qn(),Fce=Xr(),Uce=Ms(),v2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new kU.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new kU.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new ld.ArgSerializer().valuesToString([new ld.AddressValue(this.innerTransaction.getReceiver()),new ld.U64Value(this.innerTransaction.getNonce().valueOf()),new ld.BytesValue(this.innerTransaction.getData().valueOf()),new ld.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Uce.TransactionPayload(r),i=new Fce.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID,version:this.innerTransaction.getVersion(),options:this.innerTransaction.getOptions()});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};c1.RelayedTransactionV2Builder=v2});var GU=B(f1=>{"use strict";h();Object.defineProperty(f1,"__esModule",{value:!0});f1.SmartContractQueriesController=void 0;var qce=Ie(),Vce=g2(),l1=qn(),A2=class{constructor(e){this.abi=e.abi,this.queryRunner=e.queryRunner,this.legacyResultsParser=new l1.ResultsParser}createQuery(e){let r=this.encodeArguments(e.function,e.arguments);return new Vce.SmartContractQuery({contract:e.contract,caller:e.caller,function:e.function,arguments:r,value:e.value})}encodeArguments(e,r){let n=this.abi?.getEndpoint(e);if(n){let i=l1.NativeSerializer.nativeToTypedValues(r,n);return new l1.ArgSerializer().valuesToBuffers(i)}if(this.areArgsOfTypedValue(r))return new l1.ArgSerializer().valuesToBuffers(r);if(this.areArgsBuffers(r))return r.map(i=>p.Buffer.from(i));throw new qce.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}areArgsBuffers(e){for(let r of e)if(!ArrayBuffer.isView(r))return!1;return!0}async runQuery(e){return await this.queryRunner.runQuery(e)}parseQueryResponse(e){if(!this.abi)return e.returnDataParts;let r={returnCode:e.returnCode,returnMessage:e.returnMessage,getReturnDataParts:()=>e.returnDataParts.map(u=>p.Buffer.from(u))},n=e.function,i=this.abi.getEndpoint(n);return this.legacyResultsParser.parseQueryResponse(r,i).values.map(u=>u.valueOf())}};f1.SmartContractQueriesController=A2});var jU=B(ke=>{"use strict";h();var kce=ke&&ke.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pt=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kce(e,t,r)};Object.defineProperty(ke,"__esModule",{value:!0});xU();Pt(Ic(),ke);Pt(PU(),ke);Pt(Ve(),ke);Pt(Fb(),ke);Pt(RU(),ke);Pt(Ie(),ke);Pt(MU(),ke);Pt(FU(),ke);Pt(qU(),ke);Pt(oo(),ke);Pt(Bb(),ke);Pt($l(),ke);Pt(VU(),ke);Pt(HU(),ke);Pt(H0(),ke);Pt(GU(),ke);Pt(qn(),ke);Pt(_b(),ke);Pt(Ca(),ke);Pt(Xr(),ke);Pt(N0(),ke);Pt(Ms(),ke);Pt(V0(),ke);Pt(d0(),ke);Pt(Db(),ke);Pt(Rn(),ke)});var YU=B(ur=>{"use strict";h();var Hce=ur&&ur.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ur,"__esModule",{value:!0});ur.sleep=ur.getMetadata=ur.applyTransactionSignature=ur.getAddressFromSession=ur.addressIsValid=ur.getConnectionParams=ur.getCurrentTopic=ur.getCurrentSession=void 0;var KU=jU(),zU=Yf(),Gce=Qh(),h1=o2(),to=c2(),E2=f2(),QU=s1();function WU(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find($U(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}ur.getCurrentSession=WU;function jce(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=WU(t,e);if(!r?.topic)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}ur.getCurrentTopic=jce;function $U(t,e){var r,n,i;let s=[...h1.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(QU.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(QU.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${h1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],u=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:u}}}}ur.getConnectionParams=$U;function zce(t){try{return!KU.Address.fromBech32(t).isEmpty()}catch{return!1}}ur.addressIsValid=zce;function Qce(t){let e=t.namespaces[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}ur.getAddressFromSession=Qce;function Kce({transaction:t,response:e}){if(!e)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,u=t.getGuardian().bech32();if(u&&u!==o)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(KU.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new zU.Signature(r)),n&&t.applyGuardianSignature(new zU.Signature(n)),t}ur.applyTransactionSignature=Kce;function Wce(t){if(t)return Object.assign(Object.assign({},t),{url:Gce.getAppMetadata().url})}ur.getMetadata=Wce;function $ce(t){return Hce(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}ur.sleep=$ce});var fd=B(cn=>{"use strict";h();var tr=cn&&cn.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Yce=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WalletConnectV2Provider=cn.OptionalOperation=cn.Operation=cn.WalletConnectV2ProviderErrorMessagesEnum=void 0;var Jce=Yf(),Xce=Yce(CU()),b2=Qh(),gu=o2(),he=c2();Object.defineProperty(cn,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return he.WalletConnectV2ProviderErrorMessagesEnum}});var Me=f2(),Jo=s1();Object.defineProperty(cn,"Operation",{enumerable:!0,get:function(){return Jo.Operation}});Object.defineProperty(cn,"OptionalOperation",{enumerable:!0,get:function(){return Jo.OptionalOperation}});var xr=YU(),S2=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return tr(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:xr.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield Xce.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=xr.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Me.Logger.error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return tr(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield xr.sleep(gu.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=xr.getAddressFromSession(n),o=n.namespaces[gu.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:Jo.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:u}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!u)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:u})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||xr.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:b2.getSdkError("USER_DISCONNECTED")});else{let r=xr.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:b2.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new Jce.Signature(n))}catch{throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return xr.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];xr.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=xr.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return tr(this,void 0,void 0,function*(){return e?xr.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Me.Logger.error(`${he.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return tr(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=xr.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&xr.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:u})=>{var a;if(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)return;let{namespaces:c}=u,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>tr(this,void 0,void 0,function*(){var u;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)&&(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>tr(this,void 0,void 0,function*(){var u;!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o||(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=xr.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,u,a,c;return tr(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!b2.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(a=(u=this.walletConnector.core)===null||u===void 0?void 0:u.relayer)===null||a===void 0?void 0:a.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};cn.WalletConnectV2Provider=S2});var XU=B((RTe,JU)=>{"use strict";h();JU.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var tq=B((MTe,eq)=>{"use strict";h();var ZU=typeof Symbol<"u"&&Symbol,Zce=XU();eq.exports=function(){return typeof ZU!="function"||typeof Symbol!="function"||typeof ZU("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Zce()}});var iq=B((FTe,nq)=>{"use strict";h();var rq={foo:{}},ele=Object;nq.exports=function(){return{__proto__:rq}.foo===rq.foo&&!({__proto__:null}instanceof ele)}});var aq=B((qTe,oq)=>{"use strict";h();var tle="Function.prototype.bind called on incompatible ",rle=Object.prototype.toString,nle=Math.max,ile="[object Function]",sq=function(e,r){for(var n=[],i=0;i{"use strict";h();var ale=aq();uq.exports=Function.prototype.bind||ale});var lq=B((GTe,cq)=>{"use strict";h();var ule=Function.prototype.call,cle=Object.prototype.hasOwnProperty,lle=d1();cq.exports=lle.call(ule,cle)});var Xo=B((zTe,pq)=>{"use strict";h();var Re,Il=SyntaxError,gq=Function,Sl=TypeError,I2=function(t){try{return gq('"use strict"; return ('+t+").constructor;")()}catch{}},pu=Object.getOwnPropertyDescriptor;if(pu)try{pu({},"")}catch{pu=null}var T2=function(){throw new Sl},fle=pu?function(){try{return arguments.callee,T2}catch{try{return pu(arguments,"callee").get}catch{return T2}}}():T2,El=tq()(),hle=iq()(),Sr=Object.getPrototypeOf||(hle?function(t){return t.__proto__}:null),bl={},dle=typeof Uint8Array>"u"||!Sr?Re:Sr(Uint8Array),mu={"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":El&&Sr?Sr([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":bl,"%AsyncGenerator%":bl,"%AsyncGeneratorFunction%":bl,"%AsyncIteratorPrototype%":bl,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":gq,"%GeneratorFunction%":bl,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":El&&Sr?Sr(Sr([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!El||!Sr?Re:Sr(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!El||!Sr?Re:Sr(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":El&&Sr?Sr(""[Symbol.iterator]()):Re,"%Symbol%":El?Symbol:Re,"%SyntaxError%":Il,"%ThrowTypeError%":fle,"%TypedArray%":dle,"%TypeError%":Sl,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Sr)try{null.error}catch(t){fq=Sr(Sr(t)),mu["%Error.prototype%"]=fq}var fq,gle=function t(e){var r;if(e==="%AsyncFunction%")r=I2("async function () {}");else if(e==="%GeneratorFunction%")r=I2("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=I2("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Sr&&(r=Sr(i.prototype))}return mu[e]=r,r},hq={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},hd=d1(),g1=lq(),ple=hd.call(Function.call,Array.prototype.concat),mle=hd.call(Function.apply,Array.prototype.splice),dq=hd.call(Function.call,String.prototype.replace),p1=hd.call(Function.call,String.prototype.slice),yle=hd.call(Function.call,RegExp.prototype.exec),wle=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,vle=/\\(\\)?/g,Ale=function(e){var r=p1(e,0,1),n=p1(e,-1);if(r==="%"&&n!=="%")throw new Il("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Il("invalid intrinsic syntax, expected opening `%`");var i=[];return dq(e,wle,function(s,o,u,a){i[i.length]=u?dq(a,vle,"$1"):o||s}),i},Ele=function(e,r){var n=e,i;if(g1(hq,n)&&(i=hq[n],n="%"+i[0]+"%"),g1(mu,n)){var s=mu[n];if(s===bl&&(s=gle(n)),typeof s>"u"&&!r)throw new Sl("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Il("intrinsic "+e+" does not exist!")};pq.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Sl("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Sl('"allowMissing" argument must be a boolean');if(yle(/^%?[^%]*%?$/,e)===null)throw new Il("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Ale(e),i=n.length>0?n[0]:"",s=Ele("%"+i+"%",r),o=s.name,u=s.value,a=!1,c=s.alias;c&&(i=c[0],mle(n,ple([0,1],c)));for(var f=1,d=!0;f=n.length){var x=pu(u,w);d=!!x,d&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[w]}else d=g1(u,w),u=u[w];d&&!a&&(mu[o]=u)}}return u}});var N2=B((KTe,mq)=>{"use strict";h();var ble=Xo(),_2=ble("%Object.defineProperty%",!0),C2=function(){if(_2)try{return _2({},"a",{value:1}),!0}catch{return!1}return!1};C2.hasArrayLengthDefineBug=function(){if(!C2())return null;try{return _2([],"length",{value:1}).length!==1}catch{return!0}};mq.exports=C2});var x2=B(($Te,yq)=>{"use strict";h();var Sle=Xo(),m1=Sle("%Object.getOwnPropertyDescriptor%",!0);if(m1)try{m1([],"length")}catch{m1=null}yq.exports=m1});var Aq=B((JTe,vq)=>{"use strict";h();var Ile=N2()(),O2=Xo(),dd=Ile&&O2("%Object.defineProperty%",!0);if(dd)try{dd({},"a",{value:1})}catch{dd=!1}var Tle=O2("%SyntaxError%"),Tl=O2("%TypeError%"),wq=x2();vq.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Tl("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Tl("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Tl("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Tl("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Tl("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Tl("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,a=!!wq&&wq(e,r);if(dd)dd(e,r,{configurable:o===null&&a?a.configurable:!o,enumerable:i===null&&a?a.enumerable:!i,value:n,writable:s===null&&a?a.writable:!s});else if(u||!i&&!s&&!o)e[r]=n;else throw new Tle("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var _q=B((ZTe,Tq)=>{"use strict";h();var Iq=Xo(),Eq=Aq(),_le=N2()(),bq=x2(),Sq=Iq("%TypeError%"),Cle=Iq("%Math.floor%");Tq.exports=function(e,r){if(typeof e!="function")throw new Sq("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Cle(r)!==r)throw new Sq("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&bq){var o=bq(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(_le?Eq(e,"length",r,!0,!0):Eq(e,"length",r)),e}});var Dq=B((t_e,y1)=>{"use strict";h();var D2=d1(),_l=Xo(),Nle=_q(),xle=_l("%TypeError%"),Nq=_l("%Function.prototype.apply%"),xq=_l("%Function.prototype.call%"),Oq=_l("%Reflect.apply%",!0)||D2.call(xq,Nq),gd=_l("%Object.defineProperty%",!0),Ole=_l("%Math.max%");if(gd)try{gd({},"a",{value:1})}catch{gd=null}y1.exports=function(e){if(typeof e!="function")throw new xle("a function is required");var r=Oq(D2,xq,arguments);return Nle(r,1+Ole(0,e.length-(arguments.length-1)),!0)};var Cq=function(){return Oq(D2,Nq,arguments)};gd?gd(y1.exports,"apply",{value:Cq}):y1.exports.apply=Cq});var Mq=B((n_e,Bq)=>{"use strict";h();var Pq=Xo(),Rq=Dq(),Dle=Rq(Pq("String.prototype.indexOf"));Bq.exports=function(e,r){var n=Pq(e,!!r);return typeof n=="function"&&Dle(e,".prototype.")>-1?Rq(n):n}});var Lq=B(()=>{h()});var r7=B((u_e,t7)=>{h();var k2=typeof Map=="function"&&Map.prototype,P2=Object.getOwnPropertyDescriptor&&k2?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,v1=k2&&P2&&typeof P2.get=="function"?P2.get:null,Fq=k2&&Map.prototype.forEach,H2=typeof Set=="function"&&Set.prototype,R2=Object.getOwnPropertyDescriptor&&H2?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,A1=H2&&R2&&typeof R2.get=="function"?R2.get:null,Uq=H2&&Set.prototype.forEach,Ple=typeof WeakMap=="function"&&WeakMap.prototype,md=Ple?WeakMap.prototype.has:null,Rle=typeof WeakSet=="function"&&WeakSet.prototype,yd=Rle?WeakSet.prototype.has:null,Ble=typeof WeakRef=="function"&&WeakRef.prototype,qq=Ble?WeakRef.prototype.deref:null,Mle=Boolean.prototype.valueOf,Lle=Object.prototype.toString,Fle=Function.prototype.toString,Ule=String.prototype.match,G2=String.prototype.slice,ea=String.prototype.replace,qle=String.prototype.toUpperCase,Vq=String.prototype.toLowerCase,$q=RegExp.prototype.test,kq=Array.prototype.concat,Es=Array.prototype.join,Vle=Array.prototype.slice,Hq=Math.floor,L2=typeof BigInt=="function"?BigInt.prototype.valueOf:null,B2=Object.getOwnPropertySymbols,F2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,Cl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Ur=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Cl||!0)?Symbol.toStringTag:null,Yq=Object.prototype.propertyIsEnumerable,Gq=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function jq(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||$q.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-Hq(-t):Hq(t);if(n!==t){var i=String(n),s=G2.call(e,i.length+1);return ea.call(i,r,"$&_")+"."+ea.call(ea.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return ea.call(e,r,"$&_")}var U2=Lq(),zq=U2.custom,Qq=Xq(zq)?zq:null;t7.exports=function t(e,r,n,i){var s=r||{};if(Zo(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Zo(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=Zo(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Zo(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Zo(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var u=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return e7(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var a=String(e);return u?jq(e,a):a}if(typeof e=="bigint"){var c=String(e)+"n";return u?jq(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return q2(e)?"[Array]":"[Object]";var d=ife(s,n);if(typeof i>"u")i=[];else if(Zq(i,e)>=0)return"[Circular]";function w(l,g,y){if(g&&(i=Vle.call(i),i.push(g)),y){var E={depth:s.depth};return Zo(s,"quoteStyle")&&(E.quoteStyle=s.quoteStyle),t(l,E,n+1,i)}return t(l,s,n+1,i)}if(typeof e=="function"&&!Kq(e)){var A=$le(e),T=w1(e,w);return"[Function"+(A?": "+A:" (anonymous)")+"]"+(T.length>0?" { "+Es.call(T,", ")+" }":"")}if(Xq(e)){var x=Cl?ea.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):F2.call(e);return typeof e=="object"&&!Cl?pd(x):x}if(tfe(e)){for(var R="<"+Vq.call(String(e.nodeName)),V=e.attributes||[],U=0;U",R}if(q2(e)){if(e.length===0)return"[]";var Q=w1(e,w);return d&&!nfe(Q)?"["+V2(Q,d)+"]":"[ "+Es.call(Q,", ")+" ]"}if(Gle(e)){var L=w1(e,w);return!("cause"in Error.prototype)&&"cause"in e&&!Yq.call(e,"cause")?"{ ["+String(e)+"] "+Es.call(kq.call("[cause]: "+w(e.cause),L),", ")+" }":L.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+Es.call(L,", ")+" }"}if(typeof e=="object"&&o){if(Qq&&typeof e[Qq]=="function"&&U2)return U2(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(Yle(e)){var k=[];return Fq&&Fq.call(e,function(l,g){k.push(w(g,e,!0)+" => "+w(l,e))}),Wq("Map",v1.call(e),k,d)}if(Zle(e)){var H=[];return Uq&&Uq.call(e,function(l){H.push(w(l,e))}),Wq("Set",A1.call(e),H,d)}if(Jle(e))return M2("WeakMap");if(efe(e))return M2("WeakSet");if(Xle(e))return M2("WeakRef");if(zle(e))return pd(w(Number(e)));if(Kle(e))return pd(w(L2.call(e)));if(Qle(e))return pd(Mle.call(e));if(jle(e))return pd(w(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!Hle(e)&&!Kq(e)){var q=w1(e,w),v=Gq?Gq(e)===Object.prototype:e instanceof Object||e.constructor===Object,C=e instanceof Object?"":"null prototype",D=!v&&Ur&&Object(e)===e&&Ur in e?G2.call(ta(e),8,-1):C?"Object":"",F=v||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",P=F+(D||C?"["+Es.call(kq.call([],D||[],C||[]),": ")+"] ":"");return q.length===0?P+"{}":d?P+"{"+V2(q,d)+"}":P+"{ "+Es.call(q,", ")+" }"}return String(e)};function Jq(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function kle(t){return ea.call(String(t),/"/g,""")}function q2(t){return ta(t)==="[object Array]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Hle(t){return ta(t)==="[object Date]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Kq(t){return ta(t)==="[object RegExp]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Gle(t){return ta(t)==="[object Error]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function jle(t){return ta(t)==="[object String]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function zle(t){return ta(t)==="[object Number]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Qle(t){return ta(t)==="[object Boolean]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Xq(t){if(Cl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!F2)return!1;try{return F2.call(t),!0}catch{}return!1}function Kle(t){if(!t||typeof t!="object"||!L2)return!1;try{return L2.call(t),!0}catch{}return!1}var Wle=Object.prototype.hasOwnProperty||function(t){return t in this};function Zo(t,e){return Wle.call(t,e)}function ta(t){return Lle.call(t)}function $le(t){if(t.name)return t.name;var e=Ule.call(Fle.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function Zq(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return e7(G2.call(t,0,e.maxStringLength),e)+n}var i=ea.call(ea.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,rfe);return Jq(i,"single",e)}function rfe(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+qle.call(e.toString(16))}function pd(t){return"Object("+t+")"}function M2(t){return t+" { ? }"}function Wq(t,e,r,n){var i=n?V2(r,n):Es.call(r,", ");return t+" ("+e+") {"+i+"}"}function nfe(t){for(var e=0;e=0)return!1;return!0}function ife(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Es.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Es.call(Array(e+1),r)}}function V2(t,e){if(t.length===0)return"";var r=` + Approved: ${w.toString()}`))}),o.forEach(d=>{n||(Ho(i[d].methods,s[d].methods)?Ho(i[d].events,s[d].events)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function Cse(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function QM(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Nse(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:nu(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function xse(t,e){return cy(t,!1)&&t<=e.max&&t>=e.min}function Ose(){let t=tu();return new Promise(e=>{switch(t){case Gr.browser:e(P5());break;case Gr.reactNative:e(R5());break;case Gr.node:e(B5());break;default:e(!0)}})}function P5(){return Hh()&&navigator?.onLine}async function R5(){return al()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function B5(){return!0}function Dse(t){switch(tu()){case Gr.browser:M5(t);break;case Gr.reactNative:L5(t);break;case Gr.node:break}}function M5(t){!al()&&Hh()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function L5(t){al()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var TT={},LT=class{static get(e){return TT[e]}static set(e,r){TT[e]=r}static delete(e){delete TT[e]}};K.BASE10=e_,K.BASE16=jr,K.BASE64=ey,K.COLON=pte,K.DEFAULT_DEPTH=VT,K.EMPTY_SPACE=Wm,K.ENV_MAP=Gr,K.INTERNAL_ERRORS=b5,K.MemoryStore=LT,K.ONE_THOUSAND=mte,K.REACT_NATIVE_PRODUCT=n4,K.RELAYER_DEFAULT_PROTOCOL=h5,K.SDK_ERRORS=E5,K.SDK_TYPE=s4,K.SLASH=i4,K.TYPE_0=t_,K.TYPE_1=hl,K.UTF8=ay,K.addResourceToRecap=o5,K.appendToQueryString=o4,K.assertType=bte,K.assignAbilityToActions=JT,K.base64Decode=i5,K.base64Encode=n5,K.buildApprovedNamespaces=cse,K.buildAuthObject=Cie,K.buildNamespacesFromAuth=lse,K.buildRecapStatement=u5,K.calcExpiry=Bte,K.capitalize=Nte,K.capitalizeWord=h4,K.createDelayedPromise=xte,K.createEncodedRecap=Die,K.createExpiringPromise=Ote,K.createRecap=s5,K.decodeRecap=jo,K.decodeTypeByte=jh,K.decrypt=Hie,K.deriveSymKey=Uie,K.deserialize=n_,K.encodeRecap=sy,K.encodeTypeByte=c5,K.encrypt=kie,K.engineEvent=Lte,K.enumify=Cte,K.formatAccountId=ZM,K.formatAccountWithChain=ate,K.formatChainId=XM,K.formatExpirerTarget=HT,K.formatIdTarget=Pte,K.formatMessage=Z4,K.formatMessageContext=Ste,K.formatRelayParams=p5,K.formatRelayRpcUrl=Ate,K.formatStatementFromRecap=ZT,K.formatTopicTarget=Dte,K.formatUA=c4,K.formatUri=ese,K.generateKeyPair=Lie,K.generateRandomBytes32=Fie,K.getAccountsChains=nu,K.getAccountsFromNamespaces=cte,K.getAddressFromAccount=e4,K.getAddressesFromAccounts=ute,K.getAppMetadata=wte,K.getBrowserOnlineStatus=P5,K.getBundleId=yte,K.getChainFromAccount=t4,K.getChainsFromAccounts=r4,K.getChainsFromNamespace=ry,K.getChainsFromNamespaces=lte,K.getChainsFromRecap=Bie,K.getChainsFromRequiredNamespaces=fte,K.getCommonValuesInArrays=_T,K.getDecodedRecapFromResources=e5,K.getDeepLink=Ute,K.getDidAddress=YT,K.getDidAddressSegments=iy,K.getDidChainId=$T,K.getEnvironment=tu,K.getHttpUrl=Ete,K.getInternalError=Ys,K.getJavascriptID=u4,K.getJavascriptOS=a4,K.getLastItems=f4,K.getMethodsFromRecap=Rie,K.getNamespacedDidChainId=Tie,K.getNamespacesChains=m5,K.getNamespacesEventsForChainId=w5,K.getNamespacesFromAccounts=A5,K.getNamespacesMethodsForChainId=y5,K.getNodeOnlineStatus=B5,K.getReCapActions=r5,K.getReactNativeOnlineStatus=R5,K.getRecapAbilitiesFromResource=Oie,K.getRecapFromResources=oy,K.getRecapResource=t5,K.getRelayClientMetadata=vte,K.getRelayProtocolApi=Qie,K.getRelayProtocolName=zie,K.getRequiredNamespacesFromNamespaces=use,K.getSdkError=eu,K.getUniqueValues=qT,K.handleDeeplinkRedirect=Fte,K.hasOverlap=Ho,K.hashKey=qie,K.hashMessage=Vie,K.isBrowser=Hh,K.isCaipNamespace=i_,K.isConformingNamespaces=D5,K.isExpired=Mte,K.isNode=kT,K.isOnline=Ose,K.isProposalStruct=dse,K.isReactNative=al,K.isRecap=XT,K.isSessionCompatible=fse,K.isSessionStruct=gse,K.isTypeOneEnvelope=jie,K.isUndefined=Go,K.isValidAccountId=S5,K.isValidAccounts=_5,K.isValidActions=N5,K.isValidArray=zh,K.isValidChainId=kh,K.isValidChains=I5,K.isValidController=pse,K.isValidEip1271Signature=J4,K.isValidEip191Signature=Y4,K.isValidErrorReason=Ase,K.isValidEvent=Sse,K.isValidId=wse,K.isValidNamespaceAccounts=C5,K.isValidNamespaceActions=s_,K.isValidNamespaceChains=T5,K.isValidNamespaceMethodsOrEvents=MT,K.isValidNamespaces=x5,K.isValidNamespacesChainId=Ise,K.isValidNamespacesEvent=_se,K.isValidNamespacesRequest=Tse,K.isValidNumber=cy,K.isValidObject=uy,K.isValidParams=vse,K.isValidRecap=ps,K.isValidRelay=O5,K.isValidRelays=yse,K.isValidRequest=Ese,K.isValidRequestExpiry=xse,K.isValidRequiredNamespaces=mse,K.isValidResponse=bse,K.isValidString=mn,K.isValidUrl=hse,K.mapEntries=_te,K.mapToObj=Ite,K.mergeArrays=Js,K.mergeEncodedRecaps=Pie,K.mergeRecaps=a5,K.normalizeNamespaces=BT,K.objToMap=Tte,K.parseAccountId=UT,K.parseChainId=JM,K.parseContextNames=l4,K.parseExpirerTarget=Rte,K.parseNamespaceKey=v5,K.parseRelayParams=d5,K.parseTopic=g5,K.parseUri=Zie,K.populateAuthPayload=Nie,K.recapHasResource=xie,K.serialize=l5,K.subscribeToBrowserNetworkChange=M5,K.subscribeToNetworkChange=Dse,K.subscribeToReactNativeNetworkChange=L5,K.validateDecoding=Gie,K.validateEncoding=f5,K.validateSignedCacao=_ie,K.verifySignature=$4});var F5,U5,q5,V5,ly,Kh,o_,fy,zo,Wh,hy=fe(()=>{h();F5="PARSE_ERROR",U5="INVALID_REQUEST",q5="METHOD_NOT_FOUND",V5="INVALID_PARAMS",ly="INTERNAL_ERROR",Kh="SERVER_ERROR",o_=[-32700,-32600,-32601,-32602,-32603],fy=[-32e3,-32099],zo={[F5]:{code:-32700,message:"Parse error"},[U5]:{code:-32600,message:"Invalid Request"},[q5]:{code:-32601,message:"Method not found"},[V5]:{code:-32602,message:"Invalid params"},[ly]:{code:-32603,message:"Internal error"},[Kh]:{code:-32e3,message:"Server error"}},Wh=Kh});function Pse(t){return t<=fy[0]&&t>=fy[1]}function dy(t){return o_.includes(t)}function k5(t){return typeof t=="number"}function gy(t){return Object.keys(zo).includes(t)?zo[t]:zo[Wh]}function py(t){let e=Object.values(zo).find(r=>r.code===t);return e||zo[Wh]}function Rse(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!k5(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(dy(t.error.code)){let e=py(t.error.code);if(e.message!==zo[Wh].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function a_(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var u_=fe(()=>{h();hy()});var G5=D(Qo=>{"use strict";h();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.isBrowserCryptoAvailable=Qo.getSubtleCrypto=Qo.getBrowerCrypto=void 0;function c_(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}Qo.getBrowerCrypto=c_;function H5(){let t=c_();return t.subtle||t.webkitSubtle}Qo.getSubtleCrypto=H5;function Bse(){return!!c_()&&!!H5()}Qo.isBrowserCryptoAvailable=Bse});var Q5=D(Ko=>{"use strict";h();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.isBrowser=Ko.isNode=Ko.isReactNative=void 0;function j5(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ko.isReactNative=j5;function z5(){return typeof S.default<"u"&&typeof S.default.versions<"u"&&typeof S.default.versions.node<"u"}Ko.isNode=z5;function Mse(){return!j5()&&!z5()}Ko.isBrowser=Mse});var l_=D(my=>{"use strict";h();Object.defineProperty(my,"__esModule",{value:!0});var K5=(es(),_e(Zi));K5.__exportStar(G5(),my);K5.__exportStar(Q5(),my)});var Er={};Bt(Er,{isNodeJs:()=>$5});var W5,$5,Y5=fe(()=>{h();W5=pe(l_());Tr(Er,pe(l_()));$5=W5.isNode});function f_(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function h_(t=6){return BigInt(f_(t))}function d_(t,e,r){return{id:r||f_(),jsonrpc:"2.0",method:t,params:e}}function Lse(t,e){return{id:t,jsonrpc:"2.0",result:e}}function g_(t,e,r){return{id:t,jsonrpc:"2.0",error:J5(e,r)}}function J5(t,e){return typeof t>"u"?gy(ly):(typeof t=="string"&&(t=Object.assign(Object.assign({},gy(Kh)),{message:t})),typeof e<"u"&&(t.data=e),dy(t.code)&&(t=py(t.code)),t)}var X5=fe(()=>{h();u_();hy()});function Fse(t){return t.includes("*")?wy(t):!/\W/g.test(t)}function yy(t){return t==="*"}function wy(t){return yy(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function Use(t){return!yy(t)&&wy(t)&&!t.split("*")[0].trim()}function qse(t){return!yy(t)&&wy(t)&&!t.split("*")[1].trim()}var Z5=fe(()=>{h()});var eL=fe(()=>{h()});var dl,p_=fe(()=>{h();dl=class{}});var m_,vy,$h,tL=fe(()=>{h();p_();m_=class extends dl{constructor(e){super()}},vy=class extends dl{constructor(){super()}},$h=class extends vy{constructor(e){super()}}});var rL=fe(()=>{h()});var nL=fe(()=>{h();eL();p_();tL();rL()});var iL=fe(()=>{h();nL()});function Hse(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function sL(t,e){let r=Hse(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Gse(t){return sL(t,Vse)}function Ay(t){return sL(t,kse)}function y_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var Vse,kse,oL=fe(()=>{h();Vse="^https?:",kse="^wss?:"});function w_(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function jse(t){return w_(t)&&"method"in t}function v_(t){return w_(t)&&(aL(t)||Ey(t))}function aL(t){return"result"in t}function Ey(t){return"error"in t}function zse(t){return"error"in t&&t.valid===!1}var uL=fe(()=>{h()});var Fr={};Bt(Fr,{DEFAULT_ERROR:()=>Wh,IBaseJsonRpcProvider:()=>vy,IEvents:()=>dl,IJsonRpcConnection:()=>m_,IJsonRpcProvider:()=>$h,INTERNAL_ERROR:()=>ly,INVALID_PARAMS:()=>V5,INVALID_REQUEST:()=>U5,METHOD_NOT_FOUND:()=>q5,PARSE_ERROR:()=>F5,RESERVED_ERROR_CODES:()=>o_,SERVER_ERROR:()=>Kh,SERVER_ERROR_CODE_RANGE:()=>fy,STANDARD_ERROR_MAP:()=>zo,formatErrorMessage:()=>J5,formatJsonRpcError:()=>g_,formatJsonRpcRequest:()=>d_,formatJsonRpcResult:()=>Lse,getBigIntRpcId:()=>h_,getError:()=>gy,getErrorByCode:()=>py,isHttpUrl:()=>Gse,isJsonRpcError:()=>Ey,isJsonRpcPayload:()=>w_,isJsonRpcRequest:()=>jse,isJsonRpcResponse:()=>v_,isJsonRpcResult:()=>aL,isJsonRpcValidationInvalid:()=>zse,isLocalhostUrl:()=>y_,isNodeJs:()=>$5,isReservedErrorCode:()=>dy,isServerErrorCode:()=>Pse,isValidDefaultRoute:()=>yy,isValidErrorCode:()=>k5,isValidLeadingWildcardRoute:()=>Use,isValidRoute:()=>Fse,isValidTrailingWildcardRoute:()=>qse,isValidWildcardRoute:()=>wy,isWsUrl:()=>Ay,parseConnectionError:()=>a_,payloadId:()=>f_,validateJsonRpcError:()=>Rse});var Yh=fe(()=>{h();hy();u_();Y5();Tr(Fr,Er);X5();Z5();iL();oL();uL()});var cL,by,lL,A_=fe(()=>{h();cL=pe(Ds());Yh();by=class extends $h{constructor(e){super(e),this.events=new cL.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(d_(e.method,e.params||[],e.id||h_().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Ey(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),v_(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},lL=by});var fL={};Bt(fL,{JsonRpcProvider:()=>by,default:()=>Qse});var Qse,hL=fe(()=>{h();A_();A_();Qse=lL});var gL=D((rTe,dL)=>{"use strict";h();dL.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var wL={};Bt(wL,{WsConnection:()=>E_,default:()=>E_});var yL,Kse,Wse,pL,mL,$se,E_,vL=fe(()=>{h();yL=pe(Ds());xc();Yh();Kse=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:gL(),Wse=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",pL=t=>t.split("?")[0],mL=10,$se=Kse(),E_=class{constructor(e){if(this.url=e,this.events=new yL.EventEmitter,this.registering=!1,!Ay(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ai(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Ay(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,Fr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!y_(e)},o=new $se(e,[],s);Wse()?o.onerror=u=>{let a=u;n(this.emitError(a.error))}:o.on("error",u=>{n(this.emitError(u))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?Ro(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=g_(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return a_(e,pL(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>mL&&this.events.setMaxListeners(mL)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${pL(this.url)}`));return this.events.emit("register_error",r),r}}});var eF=D((Jh,pl)=>{h();var Yse=200,P_="__lodash_hash_undefined__",Oy=1,DL=2,PL=9007199254740991,Sy="[object Arguments]",T_="[object Array]",Jse="[object AsyncFunction]",RL="[object Boolean]",BL="[object Date]",ML="[object Error]",LL="[object Function]",Xse="[object GeneratorFunction]",Iy="[object Map]",FL="[object Number]",Zse="[object Null]",gl="[object Object]",AL="[object Promise]",eoe="[object Proxy]",UL="[object RegExp]",Ty="[object Set]",qL="[object String]",toe="[object Symbol]",roe="[object Undefined]",__="[object WeakMap]",VL="[object ArrayBuffer]",_y="[object DataView]",noe="[object Float32Array]",ioe="[object Float64Array]",soe="[object Int8Array]",ooe="[object Int16Array]",aoe="[object Int32Array]",uoe="[object Uint8Array]",coe="[object Uint8ClampedArray]",loe="[object Uint16Array]",foe="[object Uint32Array]",hoe=/[\\^$.*+?()[\]{}|]/g,doe=/^\[object .+?Constructor\]$/,goe=/^(?:0|[1-9]\d*)$/,Mt={};Mt[noe]=Mt[ioe]=Mt[soe]=Mt[ooe]=Mt[aoe]=Mt[uoe]=Mt[coe]=Mt[loe]=Mt[foe]=!0;Mt[Sy]=Mt[T_]=Mt[VL]=Mt[RL]=Mt[_y]=Mt[BL]=Mt[ML]=Mt[LL]=Mt[Iy]=Mt[FL]=Mt[gl]=Mt[UL]=Mt[Ty]=Mt[qL]=Mt[__]=!1;var kL=typeof global=="object"&&global&&global.Object===Object&&global,poe=typeof self=="object"&&self&&self.Object===Object&&self,Xs=kL||poe||Function("return this")(),HL=typeof Jh=="object"&&Jh&&!Jh.nodeType&&Jh,EL=HL&&typeof pl=="object"&&pl&&!pl.nodeType&&pl,GL=EL&&EL.exports===HL,b_=GL&&kL.process,bL=function(){try{return b_&&b_.binding&&b_.binding("util")}catch{}}(),SL=bL&&bL.isTypedArray;function moe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function Qoe(t,e){var r=this.__data__,n=Py(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}Zs.prototype.clear=Hoe;Zs.prototype.delete=Goe;Zs.prototype.get=joe;Zs.prototype.has=zoe;Zs.prototype.set=Qoe;function ou(t){var e=-1,r=t==null?0:t.length;for(this.clear();++eu))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,w=r&DL?new Ny:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=PL}function XL(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ed(t){return t!=null&&typeof t=="object"}var ZL=SL?Aoe(SL):cae;function Sae(t){return Eae(t)?sae(t):lae(t)}function Iae(){return[]}function Tae(){return!1}pl.exports=bae});var R_=D((uTe,tF)=>{h();tF.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},a=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:a,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return u[f.toLowerCase()]},has:function(f){return f.toLowerCase()in u}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,w){s.push(d=d.toLowerCase()),o.push([d,w]),u[d]=u[d]?u[d]+","+w:w}),r(a())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var nF=D((lTe,rF)=>{h();rF.exports=self.fetch||(self.fetch=R_().default||R_())});var lU=D(de=>{"use strict";h();Object.defineProperty(de,"__esModule",{value:!0});var uu=Ds(),_ae=(rP(),_e(tP)),id=vP(),yt=(NS(),_e(CS)),ws=KS(),iF=(xc(),_e(Z8)),Cae=(oB(),_e(sB)),ne=Qh(),Nae=(rT(),_e(tT)),Oe=za(),xae=(hL(),_e(fL)),an=(Yh(),_e(Fr)),Oae=(vL(),_e(wL)),Dae=eF(),Pae=nF();function sd(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function Rae(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var Bae=sd(uu),Mae=sd(_ae),By=Rae(Cae),Lae=sd(Oae),Fae=sd(Dae),Uae=sd(Pae);function qae(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");B=H,V++}for(var v=Q-B;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(B+(U-q)),C=B;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var Vae=qae,kae=Vae,EF=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Hae=t=>new TextEncoder().encode(t),Gae=t=>new TextDecoder().decode(t),L_=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},F_=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bF(this,e)}},U_=class{constructor(e){this.decoders=e}or(e){return bF(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},bF=(t,e)=>new U_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),q_=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new L_(e,r,n),this.decoder=new F_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},$y=({name:t,prefix:e,encode:r,decode:n})=>new q_(t,e,r,n),od=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=kae(r,e);return $y({prefix:t,name:e,encode:n,decode:s=>EF(i(s))})},jae=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},zae=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<$y({prefix:e,name:t,encode(i){return zae(i,n,r)},decode(i){return jae(i,n,r,t)}}),Qae=$y({prefix:"\0",name:"identity",encode:t=>Gae(t),decode:t=>Hae(t)}),Kae=Object.freeze({__proto__:null,identity:Qae}),Wae=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),$ae=Object.freeze({__proto__:null,base2:Wae}),Yae=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Jae=Object.freeze({__proto__:null,base8:Yae}),Xae=od({prefix:"9",name:"base10",alphabet:"0123456789"}),Zae=Object.freeze({__proto__:null,base10:Xae}),eue=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tue=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),rue=Object.freeze({__proto__:null,base16:eue,base16upper:tue}),nue=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),iue=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),sue=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oue=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),aue=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),uue=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cue=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lue=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fue=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),hue=Object.freeze({__proto__:null,base32:nue,base32upper:iue,base32pad:sue,base32padupper:oue,base32hex:aue,base32hexupper:uue,base32hexpad:cue,base32hexpadupper:lue,base32z:fue}),due=od({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),gue=od({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),pue=Object.freeze({__proto__:null,base36:due,base36upper:gue}),mue=od({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yue=od({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),wue=Object.freeze({__proto__:null,base58btc:mue,base58flickr:yue}),vue=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Aue=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Eue=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bue=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Sue=Object.freeze({__proto__:null,base64:vue,base64pad:Aue,base64url:Eue,base64urlpad:bue}),SF=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Iue=SF.reduce((t,e,r)=>(t[r]=e,t),[]),Tue=SF.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function _ue(t){return t.reduce((e,r)=>(e+=Iue[r],e),"")}function Cue(t){let e=[];for(let r of t){let n=Tue[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var Nue=$y({prefix:"\u{1F680}",name:"base256emoji",encode:_ue,decode:Cue}),xue=Object.freeze({__proto__:null,base256emoji:Nue}),Oue=IF,sF=128,Due=127,Pue=~Due,Rue=Math.pow(2,31);function IF(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Rue;)e[r++]=t&255|sF,t/=128;for(;t&Pue;)e[r++]=t&255|sF,t>>>=7;return e[r]=t|0,IF.bytes=r-n+1,e}var Bue=V_,Mue=128,oF=127;function V_(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw V_.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&oF)<=Mue);return V_.bytes=s-n,r}var Lue=Math.pow(2,7),Fue=Math.pow(2,14),Uue=Math.pow(2,21),que=Math.pow(2,28),Vue=Math.pow(2,35),kue=Math.pow(2,42),Hue=Math.pow(2,49),Gue=Math.pow(2,56),jue=Math.pow(2,63),zue=function(t){return t(TF.encode(t,e,r),e),uF=t=>TF.encodingLength(t),k_=(t,e)=>{let r=e.byteLength,n=uF(t),i=n+uF(r),s=new Uint8Array(i+r);return aF(t,s,0),aF(r,s,n),s.set(e,i),new H_(t,r,e,s)},H_=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},_F=({name:t,code:e,encode:r})=>new G_(t,e,r),G_=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?k_(this.code,r):r.then(n=>k_(this.code,n))}else throw Error("Unknown type, must be binary type")}},CF=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Kue=_F({name:"sha2-256",code:18,encode:CF("SHA-256")}),Wue=_F({name:"sha2-512",code:19,encode:CF("SHA-512")}),$ue=Object.freeze({__proto__:null,sha256:Kue,sha512:Wue}),NF=0,Yue="identity",xF=EF,Jue=t=>k_(NF,xF(t)),Xue={code:NF,name:Yue,encode:xF,digest:Jue},Zue=Object.freeze({__proto__:null,identity:Xue});new TextEncoder,new TextDecoder;var cF={...Kae,...$ae,...Jae,...Zae,...rue,...hue,...pue,...wue,...Sue,...xue};({...$ue,...Zue});function OF(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function ece(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?OF(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function DF(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var lF=DF("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),B_=DF("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=ece(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Uy=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=MF,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=By.generateKeyPair(i);return By.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=ne.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=By.generateKeyPair(s),u=ne.generateRandomBytes32(),a=LF;return await By.signJWT(u,i,a,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let u=this.getPrivateKey(i),a=ne.deriveSymKey(u,s);return this.setSymKey(a,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||ne.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let u=ne.validateEncoding(o),a=iF.safeJsonStringify(s);if(ne.isTypeOneEnvelope(u)){let w=u.senderPublicKey,A=u.receiverPublicKey;i=await this.generateSharedKey(w,A)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=u;return ne.encrypt({type:f,symKey:c,message:a,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let u=ne.validateDecoding(s,o);if(ne.isTypeOneEnvelope(u)){let a=u.receiverPublicKey,c=u.senderPublicKey;i=await this.generateSharedKey(a,c)}try{let a=this.getSymKey(i),c=ne.decrypt({symKey:a,encoded:s});return iF.safeJsonParse(c)}catch(a){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(a)}},this.getPayloadType=i=>{let s=ne.deserialize(i);return ne.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=ne.deserialize(i);return s.senderPublicKey?Nae.toString(s.senderPublicKey,ne.BASE16):void 0},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.keychain=n||new Fy(this.core,this.logger)}get context(){return yt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(j_)}catch{e=ne.generateRandomBytes32(),await this.keychain.set(j_,e)}return rce(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},qy=class extends ws.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=qF,this.version=VF,this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=ne.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=ne.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=yt.generateChildLogger(e,this.name),this.core=r}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Q_=class extends ws.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new uu.EventEmitter,this.name=HF,this.queue=new Map,this.publishTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.failedPublishTimeout=Oe.toMiliseconds(Oe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});let u=s?.ttl||kF,a=ne.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||an.getBigIntRpcId().toString(),w={topic:n,message:i,opts:{ttl:u,relay:a,prompt:c,tag:f,id:d}},A=`Failed to publish payload, please try again. id:${d} tag:${f}`,T=Date.now(),x,B=1;try{for(;x===void 0;){if(Date.now()-T>this.publishTimeout)throw new Error(A);this.logger.trace({id:d,attempts:B},`publisher.publish - attempt ${B}`),x=await await ne.createExpiringPromise(this.rpcPublish(n,i,u,a,c,f,d).catch(V=>this.logger.warn(V)),this.publishTimeout,A),B++,x||await new Promise(V=>setTimeout(V,this.failedPublishTimeout))}this.relayer.events.emit(Zn.publish,w),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}})}catch(V){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(V),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw V;this.queue.set(d,w)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return yt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,u){var a,c,f,d;let w={method:ne.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:u};return ne.isUndefined((a=w.params)==null?void 0:a.prompt)&&((c=w.params)==null||delete c.prompt),ne.isUndefined((f=w.params)==null?void 0:f.tag)&&((d=w.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w}),this.relayer.request(w)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Zn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Zn.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},K_=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},ace=Object.defineProperty,uce=Object.defineProperties,cce=Object.getOwnPropertyDescriptors,fF=Object.getOwnPropertySymbols,lce=Object.prototype.hasOwnProperty,fce=Object.prototype.propertyIsEnumerable,hF=(t,e,r)=>e in t?ace(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rd=(t,e)=>{for(var r in e||(e={}))lce.call(e,r)&&hF(t,r,e[r]);if(fF)for(var r of fF(e))fce.call(e,r)&&hF(t,r,e[r]);return t},M_=(t,e)=>uce(t,cce(e)),Vy=class extends ws.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new K_,this.events=new uu.EventEmitter,this.name=XF,this.version=ZF,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=eo,this.subscribeTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=ne.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let u=await this.rpcSubscribe(n,s);return typeof u=="string"&&(this.onSubscribe(u,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;let i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((s,o)=>{let u=new Oe.Watch;u.start(i);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),u.stop(i),s(!0)),u.elapsed(i)>=eU&&(clearInterval(a),u.stop(i),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.clientId=""}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=ne.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=ne.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:ne.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?ne.hashMessage(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Zn.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:ne.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(Zn.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:ne.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,M_(rd({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rd({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rd({},r)),this.topicMap.set(r.topic,e),this.events.emit(_i.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(_i.deleted,M_(rd({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_i.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);ne.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>M_(rd({},e[i]),{id:n})))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(_i.created,async e=>{let r=_i.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(_i.deleted,async e=>{let r=_i.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},hce=Object.defineProperty,dF=Object.getOwnPropertySymbols,dce=Object.prototype.hasOwnProperty,gce=Object.prototype.propertyIsEnumerable,gF=(t,e,r)=>e in t?hce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pce=(t,e)=>{for(var r in e||(e={}))dce.call(e,r)&&gF(t,r,e[r]);if(dF)for(var r of dF(e))gce.call(e,r)&&gF(t,r,e[r]);return t},ky=class extends ws.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new uu.EventEmitter,this.name=zF,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Oe.toMiliseconds(Oe.THIRTY_SECONDS+Oe.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");let s=r.id||an.getBigIntRpcId().toString();await this.toEstablishConnection();try{let o=this.provider.request(r);this.requestsInFlight.set(s,{promise:o,request:r}),this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");let u=await new Promise(async(a,c)=>{let f=()=>{c(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(yn.disconnect,f);let d=await o;this.provider.off(yn.disconnect,f),a(d)});return this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),u}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(ne.isNode())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(Zn.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Zn.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(yn.payload,this.onPayloadHandler),this.provider.on(yn.connect,this.onConnectHandler),this.provider.on(yn.disconnect,this.onDisconnectHandler),this.provider.on(yn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?yt.generateChildLogger(e.logger,this.name):yt.pino(yt.getDefaultLoggerOptions({level:e.logger||jF})),this.messages=new qy(this.logger,e.core),this.subscriber=new Vy(this,this.logger),this.publisher=new Q_(this,this.logger),this.relayUrl=e?.relayUrl||$_,this.projectId=e.projectId,this.bundleId=ne.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${z_}...`),await this.restartTransport(z_)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},$F)}get context(){return yt.getLoggerContext(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",s,o=u=>{u.topic===e&&(this.subscriber.off(_i.created,o),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(_i.created,o)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,r)||i,u()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await ne.createExpiringPromise(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect(),await this.createProvider()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{let i=()=>{this.provider.off(yn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(yn.disconnect,i),await ne.createExpiringPromise(this.provider.connect(),Oe.toMiliseconds(Oe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{n(s)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ne.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}startPingTimeout(){var e,r,n,i,s;if(ne.isNode())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xae.JsonRpcProvider(new Lae.default(ne.formatRelayRpcUrl({sdkVersion:WF,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),an.isJsonRpcRequest(e)){if(!e.method.endsWith(QF))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(pce({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else an.isJsonRpcResponse(e)&&this.events.emit(Zn.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Zn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=an.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(yn.payload,this.onPayloadHandler),this.provider.off(yn.connect,this.onConnectHandler),this.provider.off(yn.disconnect,this.onDisconnectHandler),this.provider.off(yn.error,this.onProviderErrorHandler)}async registerEventListeners(){let e=await ne.isOnline();ne.subscribeToNetworkChange(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.events.emit(Zn.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Oe.toMiliseconds(KF))}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}},mce=Object.defineProperty,pF=Object.getOwnPropertySymbols,yce=Object.prototype.hasOwnProperty,wce=Object.prototype.propertyIsEnumerable,mF=(t,e,r)=>e in t?mce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yF=(t,e)=>{for(var r in e||(e={}))yce.call(e,r)&&mF(t,r,e[r]);if(pF)for(var r of pF(e))wce.call(e,r)&&mF(t,r,e[r]);return t},Hy=class extends ws.IStore{constructor(e,r,n,i=eo,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=YF,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ne.isUndefined(o)?this.map.set(this.getKey(o),o):ne.isProposalStruct(o)?this.map.set(o.id,o):ne.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,u)=>{this.isInitialized(),this.map.has(o)?await this.update(o,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:u}),this.map.set(o,u),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(u=>Object.keys(o).every(a=>Fae.default(u[a],o[a]))):this.values),this.update=async(o,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:u});let a=yF(yF({},this.getData(o)),u);this.map.set(o,a),await this.persist()},this.delete=async(o,u)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:u}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())},this.logger=yt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Gy=class{constructor(e,r){this.core=e,this.logger=r,this.name=tU,this.version=rU,this.events=new Bae.default,this.initialized=!1,this.storagePrefix=eo,this.ignoredPayloadTypes=[ne.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let i=ne.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),o=ne.calcExpiry(Oe.FIVE_MINUTES),u={protocol:GF},a={topic:s,expiry:o,relay:u,active:!1},c=ne.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:u,expiryTimestamp:o,methods:n?.methods});return await this.pairings.set(s,a),await this.core.relayer.subscribe(s),this.core.expirer.set(s,o),{topic:s,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o,expiryTimestamp:u,methods:a}=ne.parseUri(n.uri),c;if(this.pairings.keys.includes(i)&&(c=this.pairings.get(i),c.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let f=u||ne.calcExpiry(Oe.FIVE_MINUTES),d={topic:i,relay:o,expiry:f,active:!1,methods:a};return await this.pairings.set(i,d),this.core.expirer.set(i,f),n.activatePairing&&await this.activate({topic:i}),this.events.emit(nd.create,d),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),d},this.activate=async({topic:n})=>{this.isInitialized();let i=ne.calcExpiry(Oe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:u,reject:a}=ne.createDelayedPromise();this.events.once(ne.engineEvent("pairing_ping",s),({error:c})=>{c?a(c):u()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ne.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=an.formatJsonRpcRequest(i,s),u=await this.core.crypto.encode(n,o),a=yl[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,u,a),o.id},this.sendResult=async(n,i,s)=>{let o=an.formatJsonRpcResult(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method].res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=an.formatJsonRpcError(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method]?yl[a.request.method].res:yl.unregistered_method.res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,ne.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>ne.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(nd.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{an.isJsonRpcResult(i)?this.events.emit(ne.engineEvent("pairing_ping",s),{}):an.isJsonRpcError(i)&&this.events.emit(ne.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(nd.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let u=ne.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,u),this.logger.error(u)}catch(u){await this.sendError(s,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(ne.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!ne.isValidParams(n)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!ne.isValidUrl(n.uri)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=ne.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(s!=null&&s.expiryTimestamp&&Oe.toMiliseconds(s?.expiryTimestamp){if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ne.isValidString(n,!1)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=ne.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ne.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=ne.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.pairings=new Hy(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Zn.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{an.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):an.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Xn.expired,async e=>{let{topic:r}=ne.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(nd.expire,{topic:r}))})}},jy=class extends ws.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new uu.EventEmitter,this.name=nU,this.version=iU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:ne.calcExpiry(Oe.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=an.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Jn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Jn.deleted,s)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:an.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jn.created,e=>{let r=Jn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.updated,e=>{let r=Jn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.deleted,e=>{let r=Jn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Oe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Jn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},zy=class extends ws.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new uu.EventEmitter,this.name=sU,this.version=oU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Xn.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Xn.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ne.formatTopicTarget(e);if(typeof e=="number")return ne.formatIdTarget(e);let{message:r}=ne.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Xn.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Oe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Xn.created,e=>{let r=Xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.expired,e=>{let r=Xn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.deleted,e=>{let r=Xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Qy=class extends ws.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=My,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||ne.isReactNative()||!ne.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Ly;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,Ly)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Oe.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{let o=document.getElementById(My);if(o)return this.iframe=o,this.onInit(),s();window.addEventListener("message",i);let u=document.createElement("iframe");u.id=My,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Oe.toMiliseconds(Oe.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||wl;return aU.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${wl}`),i=wl),i},this.logger=yt.generateChildLogger(r,this.name),this.verifyUrl=wl,this.abortController=new AbortController,this.isDevEnv=ne.isNode()&&S.default.env.IS_VITEST}get context(){return yt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Oe.toMiliseconds(e))}},Ky=class extends ws.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=uU,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:u=!1}=n,a=`${cU}/${this.projectId}/clients`;await Uae.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:u})})},this.logger=yt.generateChildLogger(r,this.context)}},vce=Object.defineProperty,wF=Object.getOwnPropertySymbols,Ace=Object.prototype.hasOwnProperty,Ece=Object.prototype.propertyIsEnumerable,vF=(t,e,r)=>e in t?vce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,AF=(t,e)=>{for(var r in e||(e={}))Ace.call(e,r)&&vF(t,r,e[r]);if(wF)for(var r of wF(e))Ece.call(e,r)&&vF(t,r,e[r]);return t},Wy=class t extends ws.ICore{constructor(e){var r;super(e),this.protocol=W_,this.version=PF,this.name=Yy,this.events=new uu.EventEmitter,this.initialized=!1,this.on=(o,u)=>this.events.on(o,u),this.once=(o,u)=>this.events.once(o,u),this.off=(o,u)=>this.events.off(o,u),this.removeListener=(o,u)=>this.events.removeListener(o,u),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||$_,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let n=yt.getDefaultLoggerOptions({level:typeof e?.logger=="string"&&e.logger?e.logger:RF.logger}),{logger:i,chunkLoggerController:s}=yt.generatePlatformLogger({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,u;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=yt.generateChildLogger(i,this.name),this.heartbeat=new id.HeartBeat,this.crypto=new Uy(this,this.logger,e?.keychain),this.history=new jy(this,this.logger),this.expirer=new zy(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Mae.default(AF(AF({},BF),e?.storageOptions)),this.relayer=new ky({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Gy(this,this.logger),this.verify=new Qy(this.projectId||"",this.logger),this.echoClient=new Ky(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(JF,n),r}get context(){return yt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},bce=Wy;de.CORE_CONTEXT=Yy,de.CORE_DEFAULT=RF,de.CORE_PROTOCOL=W_,de.CORE_STORAGE_OPTIONS=BF,de.CORE_STORAGE_PREFIX=eo,de.CORE_VERSION=PF,de.CRYPTO_CLIENT_SEED=j_,de.CRYPTO_CONTEXT=MF,de.CRYPTO_JWT_TTL=LF,de.Core=bce,de.Crypto=Uy,de.ECHO_CONTEXT=uU,de.ECHO_URL=cU,de.EXPIRER_CONTEXT=sU,de.EXPIRER_DEFAULT_TTL=oce,de.EXPIRER_EVENTS=Xn,de.EXPIRER_STORAGE_VERSION=oU,de.EchoClient=Ky,de.Expirer=zy,de.HISTORY_CONTEXT=nU,de.HISTORY_EVENTS=Jn,de.HISTORY_STORAGE_VERSION=iU,de.JsonRpcHistory=jy,de.KEYCHAIN_CONTEXT=FF,de.KEYCHAIN_STORAGE_VERSION=UF,de.KeyChain=Fy,de.MESSAGES_CONTEXT=qF,de.MESSAGES_STORAGE_VERSION=VF,de.MessageTracker=qy,de.PAIRING_CONTEXT=tU,de.PAIRING_DEFAULT_TTL=sce,de.PAIRING_EVENTS=nd,de.PAIRING_RPC_OPTS=yl,de.PAIRING_STORAGE_VERSION=rU,de.PENDING_SUB_RESOLUTION_TIMEOUT=eU,de.PUBLISHER_CONTEXT=HF,de.PUBLISHER_DEFAULT_TTL=kF,de.Pairing=Gy,de.RELAYER_CONTEXT=zF,de.RELAYER_DEFAULT_LOGGER=jF,de.RELAYER_DEFAULT_PROTOCOL=GF,de.RELAYER_DEFAULT_RELAY_URL=$_,de.RELAYER_EVENTS=Zn,de.RELAYER_FAILOVER_RELAY_URL=z_,de.RELAYER_PROVIDER_EVENTS=yn,de.RELAYER_RECONNECT_TIMEOUT=KF,de.RELAYER_SDK_VERSION=WF,de.RELAYER_STORAGE_OPTIONS=nce,de.RELAYER_SUBSCRIBER_SUFFIX=QF,de.RELAYER_TRANSPORT_CUTOFF=$F,de.Relayer=ky,de.STORE_STORAGE_VERSION=YF,de.SUBSCRIBER_CONTEXT=XF,de.SUBSCRIBER_DEFAULT_TTL=ice,de.SUBSCRIBER_EVENTS=_i,de.SUBSCRIBER_STORAGE_VERSION=ZF,de.Store=Hy,de.Subscriber=Vy,de.TRUSTED_VERIFY_URLS=aU,de.VERIFY_CONTEXT=My,de.VERIFY_FALLBACK_SERVER=Ly,de.VERIFY_SERVER=wl,de.Verify=Qy,de.WALLETCONNECT_CLIENT_ID=JF,de.default=Wy});var _U=D(Be=>{"use strict";h();Object.defineProperty(Be,"__esModule",{value:!0});var un=lU(),Jy=(NS(),_e(CS)),dU=KS(),G=Qh(),gU=Ds(),Dt=za(),qe=(Yh(),_e(Fr));function Sce(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var Ice=Sce(gU),i2="wc",s2=2,o2="client",r1=`${i2}@${s2}:${o2}:`,Xy={name:o2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},Tce={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},_ce={database:":memory:"},Y_="WALLETCONNECT_DEEPLINK_CHOICE",Cce={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Nce="history",xce="0.3",pU="proposal",Oce=Dt.THIRTY_DAYS,mU="Proposal expired",yU="session",cu=Dt.SEVEN_DAYS,wU="engine",wn={wc_sessionPropose:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Dt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Dt.ONE_HOUR,prompt:!1,tag:1117}}},Zy={min:Dt.FIVE_MINUTES,max:Dt.SEVEN_DAYS},vs={idle:"IDLE",active:"ACTIVE"},vU="request",AU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],EU="wc",Dce=1.5,bU="auth",SU="authKeys",IU="pairingTopics",TU="requests",ud=`${EU}@${1.5}:${bU}:`,ad=`${ud}:PUB_KEY`,Pce=Object.defineProperty,Rce=Object.defineProperties,Bce=Object.getOwnPropertyDescriptors,fU=Object.getOwnPropertySymbols,Mce=Object.prototype.hasOwnProperty,Lce=Object.prototype.propertyIsEnumerable,hU=(t,e,r)=>e in t?Pce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e)=>{for(var r in e||(e={}))Mce.call(e,r)&&hU(t,r,e[r]);if(fU)for(var r of fU(e))Lce.call(e,r)&&hU(t,r,e[r]);return t},vl=(t,e)=>Rce(t,Bce(e)),J_=class extends dU.IEngine{constructor(e){super(e),this.name=wU,this.events=new Ice.default,this.initialized=!1,this.requestQueue={state:vs.idle,queue:[]},this.sessionRequestQueue={state:vs.idle,queue:[]},this.requestQueueDelay=Dt.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=vl(br({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:u,relays:a}=n,c=i,f,d=!1;try{c&&(d=this.client.core.pairing.pairings.get(c).active)}catch(L){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),L}if(!c||!d){let{topic:L,uri:k}=await this.client.core.pairing.create();c=L,f=k}if(!c){let{message:L}=G.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(L)}let w=await this.client.core.crypto.generateKeyPair(),A=wn.wc_sessionPropose.req.ttl||Dt.FIVE_MINUTES,T=G.calcExpiry(A),x=br({requiredNamespaces:s,optionalNamespaces:o,relays:a??[{protocol:un.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:T},u&&{sessionProperties:u}),{reject:B,resolve:V,done:U}=G.createDelayedPromise(A,mU);this.events.once(G.engineEvent("session_connect"),async({error:L,session:k})=>{if(L)B(L);else if(k){k.self.publicKey=w;let H=vl(br({},k),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:k.peer.metadata}),V(H)}});let Q=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:x,throwOnFailedPublish:!0});return await this.setProposal(Q,br({id:Q},x)),{uri:f,approval:U}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),U}let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o,sessionConfig:u}=r,a;try{a=this.client.proposal.get(n)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),U}let{pairingTopic:c,proposer:f,requiredNamespaces:d,optionalNamespaces:w}=a;c=c||"";let A=await this.client.core.crypto.generateKeyPair(),T=f.publicKey,x=await this.client.core.crypto.generateSharedKey(A,T),B=br(br({relay:{protocol:i??"irn"},namespaces:s,pairingTopic:c,controller:{publicKey:A,metadata:this.client.metadata},expiry:G.calcExpiry(cu)},o&&{sessionProperties:o}),u&&{sessionConfig:u});await this.client.core.relayer.subscribe(x);let V=vl(br({},B),{topic:x,requiredNamespaces:d,optionalNamespaces:w,pairingTopic:c,acknowledged:!1,self:B.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A});await this.client.session.set(x,V);try{await this.sendResult({id:n,topic:c,result:{relay:{protocol:i??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:B,throwOnFailedPublish:!0})}catch(U){throw this.client.logger.error(U),this.client.session.delete(x,G.getSdkError("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),U}return await this.client.core.pairing.updateMetadata({topic:c,metadata:f.metadata}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}),await this.setExpiry(x,G.calcExpiry(cu)),{topic:x,acknowledged:()=>new Promise(U=>setTimeout(()=>U(this.client.session.get(x)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}let{id:n,reason:i}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}let{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:u}=G.createDelayedPromise(),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),f=this.client.session.get(n).namespaces;return this.events.once(G.engineEvent("session_update",a),({error:d})=>{d?u(d):o()}),await this.client.session.update(n,{namespaces:i}),this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:f}),u(d)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}let{topic:n}=r,i=qe.payloadId(),{done:s,resolve:o,reject:u}=G.createDelayedPromise();return this.events.once(G.engineEvent("session_extend",i),({error:a})=>{a?u(a):o()}),await this.setExpiry(n,G.calcExpiry(cu)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(a=>{u(a)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(A){throw this.client.logger.error("request() -> isValidRequest() failed"),A}let{chainId:n,request:i,topic:s,expiry:o=wn.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),{done:f,resolve:d,reject:w}=G.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(G.engineEvent("session_request",a),({error:A,result:T})=>{A?w(A):d(T)}),await Promise.all([new Promise(async A=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:s,method:"wc_sessionRequest",params:{request:vl(br({},i),{expiryTimestamp:G.calcExpiry(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(T=>w(T)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),A()}),new Promise(async A=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){let x=await G.getDeepLink(this.client.core.storage,Y_);G.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:x})}A()}),f()]).then(A=>A[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;qe.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):qe.isJsonRpcError(i)&&await this.sendError({id:s,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=qe.payloadId(),s=qe.getBigIntRpcId().toString(),{done:o,resolve:u,reject:a}=G.createDelayedPromise();this.events.once(G.engineEvent("session_ping",i),({error:c})=>{c?a(c):u()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r,o=qe.getBigIntRpcId().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:G.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:i}=G.getInternalError("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>G.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);let{chains:n,statement:i="",uri:s,domain:o,nonce:u,type:a,exp:c,nbf:f,methods:d=[]}=r,w=[...r.resources||[]],{topic:A,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:T}});let x=await this.client.core.crypto.generateKeyPair(),B=G.hashKey(x);if(await Promise.all([this.client.auth.authKeys.set(ad,{responseTopic:B,publicKey:x}),this.client.auth.pairingTopics.set(B,{topic:B,pairingTopic:A})]),await this.client.core.relayer.subscribe(B),this.client.logger.info(`sending request to new pairing topic: ${A}`),d.length>0){let{namespace:R}=G.parseChainId(n[0]),l=G.createEncodedRecap(R,"request",d);G.getRecapFromResources(w)&&(l=G.mergeEncodedRecaps(l,w.pop())),w.push(l)}let V=G.calcExpiry(wn.wc_sessionPropose.req.ttl),U={authPayload:{type:a??"caip122",chains:n,statement:i,aud:s,domain:o,version:"1",nonce:u,iat:new Date().toISOString(),exp:c,nbf:f,resources:w},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},Q={eip155:{chains:n,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},L={requiredNamespaces:{},optionalNamespaces:Q,relays:[{protocol:"irn"}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},{done:k,resolve:H,reject:q}=G.createDelayedPromise(wn.wc_sessionAuthenticate.req.ttl,"Request expired"),v=async({error:R,session:l})=>{if(this.events.off(G.engineEvent("session_request",P),C),R)q(R);else if(l){l.self.publicKey=x,await this.client.session.set(l.topic,l),await this.setExpiry(l.topic,l.expiry),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:l.peer.metadata});let g=this.client.session.get(l.topic);H({session:g})}},C=async R=>{if(R.error){let M=G.getSdkError("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return R.error.code===M.code?void 0:(this.events.off(G.engineEvent("session_connect"),v),q(R.error.message))}this.events.off(G.engineEvent("session_connect"),v);let{cacaos:l,responder:g}=R.result,y=[],E=[];for(let M of l){await G.validateSignedCacao({cacao:M,projectId:this.client.core.projectId})||(this.client.logger.error(M,"Signature verification failed"),q(G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:N}=M,m=G.getRecapFromResources(N.resources),O=[G.getNamespacedDidChainId(N.iss)],Y=G.getDidAddress(N.iss);if(m){let $=G.getMethodsFromRecap(m),b=G.getChainsFromRecap(m);y.push(...$),O.push(...b)}for(let $ of O)E.push(`${$}:${Y}`)}let I=await this.client.core.crypto.generateSharedKey(x,g.publicKey),_;y.length>0&&(_={topic:I,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:g,controller:g.publicKey,expiry:G.calcExpiry(cu),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:G.buildNamespacesFromAuth([...new Set(y)],[...new Set(E)])},await this.client.core.relayer.subscribe(I),await this.client.session.set(I,_),_=this.client.session.get(I)),H({auths:l,session:_})},P=qe.payloadId(),F=qe.payloadId();this.events.once(G.engineEvent("session_connect"),v),this.events.once(G.engineEvent("session_request",P),C);try{await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:L,expiry:wn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:F})])}catch(R){throw this.events.off(G.engineEvent("session_connect"),v),this.events.off(G.engineEvent("session_request",P),C),R}return await this.setProposal(F,br({id:F},L)),await this.client.auth.requests.set(P,{authPayload:U.authPayload,requester:U.requester,expiryTimestamp:V,id:P,pairingTopic:A,verifyContext:{}}),{uri:T,response:k}},this.approveSessionAuthenticate=async r=>{this.isInitialized();let{id:n,auths:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u},f=[],d=[];for(let T of i){if(!await G.validateSignedCacao({cacao:T,projectId:this.client.core.projectId})){let Q=G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:a,error:Q,encodeOpts:c}),new Error(Q.message)}let{p:x}=T,B=G.getRecapFromResources(x.resources),V=[G.getNamespacedDidChainId(x.iss)],U=G.getDidAddress(x.iss);if(B){let Q=G.getMethodsFromRecap(B),L=G.getChainsFromRecap(B);f.push(...Q),V.push(...L)}for(let Q of V)d.push(`${Q}:${U}`)}let w=await this.client.core.crypto.generateSharedKey(u,o),A;return f?.length>0&&(A={topic:w,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:o,metadata:s.requester.metadata},controller:o,expiry:G.calcExpiry(cu),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:G.buildNamespacesFromAuth([...new Set(f)],[...new Set(d)])},await this.client.core.relayer.subscribe(w),await this.client.session.set(w,A)),await this.sendResult({topic:a,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:c,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fullfilled",code:0}),await this.client.core.pairing.activate({topic:s.pairingTopic}),{session:A}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();let{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u};await this.sendError({id:n,topic:a,error:i,encodeOpts:c}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:i}=r;return G.formatMessage(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,u;return((o=s.peerMetadata)==null?void 0:o.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:i=!1,emitEvent:s=!0,id:o=0}=r,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,G.getSdkError("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Y_).catch(a=>this.client.logger.warn(a)),this.getPendingSessionRequests().forEach(a=>{a.topic===n&&this.deletePendingSessionRequest(a.id,G.getSdkError("USER_DISCONNECTED"))}),s&&this.client.events.emit("session_delete",{id:o,topic:n})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,G.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=vs.idle,this.client.events.emit("session_request_expire",{id:r}))},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,G.calcExpiry(wn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async r=>{let{id:n,topic:i,params:s,verifyContext:o}=r,u=s.request.expiryTimestamp||G.calcExpiry(wn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:u,clientRpcId:a,throwOnFailedPublish:c}=r,f=qe.formatJsonRpcRequest(i,s,a);if(G.isBrowser()&&AU.includes(i)){let A=G.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:A})}let d;try{d=await this.client.core.crypto.encode(n,f)}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let w=wn[i].req;return o&&(w.ttl=o),u&&(w.id=u),this.client.core.history.set(n,f),c?(w.internal=vl(br({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(A=>this.client.logger.error(A)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:u}=r,a=qe.formatJsonRpcResult(n,s),c;try{c=await this.client.core.crypto.encode(i,a,u)}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let f;try{f=await this.client.core.history.get(i,n)}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),w}let d=wn[f.request.method].res;o?(d.internal=vl(br({},d.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,c,d)):this.client.core.relayer.publish(i,c,d).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(a)},this.sendError=async r=>{let{id:n,topic:i,error:s,encodeOpts:o}=r,u=qe.formatJsonRpcError(n,s),a;try{a=await this.client.core.crypto.encode(i,u,o)}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let c;try{c=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}let f=wn[c.request.method].res;this.client.core.relayer.publish(i,a,f),await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;G.isExpired(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{G.isExpired(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===vs.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vs.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=vs.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:s}))switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=G.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(br({},n.params));let o=i.expiryTimestamp||G.calcExpiry(wn.wc_sessionPropose.req.ttl),u=br({id:s,pairingTopic:r,expiryTimestamp:o},i);await this.setProposal(s,u);let a=G.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(a,u.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:u,verifyContext:c})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(qe.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let u=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});let a=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});let c=await this.client.core.crypto.generateSharedKey(u,a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(qe.isJsonRpcError(n)){await this.client.proposal.delete(i,G.getSdkError("USER_DISCONNECTED"));let s=G.engineEvent("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners, 954`);this.events.emit(G.engineEvent("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:u,expiry:a,namespaces:c,sessionProperties:f,pairingTopic:d,sessionConfig:w}=n.params,A=br(br({topic:r,relay:o,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:d,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},f&&{sessionProperties:f}),w&&{sessionConfig:w});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});let T=G.engineEvent("session_connect");if(this.events.listenerCount(T)===0)throw new Error(`emitting ${T} without any listeners 997`);this.events.emit(G.engineEvent("session_connect"),{session:A}),this.cleanupDuplicatePairings(A)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;qe.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(G.engineEvent("session_approve",i),{})):qe.isJsonRpcError(n)&&(await this.client.session.delete(r,G.getSdkError("USER_DISCONNECTED")),this.events.emit(G.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:G.getSdkError("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(br({topic:r},i));try{G.MemoryStore.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){throw G.MemoryStore.delete(o),a}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_update",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,G.calcExpiry(cu)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_extend",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_ping",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_ping",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(un.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:G.getSdkError("USER_DISCONNECTED")})])}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{await this.isValidRequest(br({topic:r},s));let o=G.hashMessage(JSON.stringify(qe.formatJsonRpcRequest("wc_sessionRequest",s,i))),u=this.client.session.get(r),a=await this.getVerifyContext(o,u.peer.metadata),c={id:i,topic:r,params:s,verifyContext:a};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(br({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),G.MemoryStore.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{let{requester:i,authPayload:s,expiryTimestamp:o}=n.params,u=G.hashMessage(JSON.stringify(n)),a=await this.getVerifyContext(u,this.client.metadata),c={requester:i,pairingTopic:r,id:n.id,authPayload:s,verifyContext:a,expiryTimestamp:o};await this.client.auth.requests.set(n.id,c),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vs.idle,this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{let o=s.request.id,u=G.engineEvent("session_request",o);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(G.engineEvent("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===vs.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vs.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,qe.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(a)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:u}=r;if(G.isUndefined(n)||await this.isValidPairingTopic(n),!G.isValidRelays(u,!0)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(a)}!G.isUndefined(i)&&G.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!G.isUndefined(s)&&G.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=G.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!G.isValidParams(r))throw new Error(G.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let u=this.client.proposal.get(n),a=G.isValidNamespaces(i,"approve()");if(a)throw new Error(a.message);let c=G.isConformingNamespaces(u.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!G.isValidString(s,!0)){let{message:f}=G.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!G.isValidParams(r)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!G.isValidErrorReason(i)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!G.isValidParams(r)){let{message:c}=G.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!G.isValidRelay(n)){let{message:c}=G.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let u=G.isValidController(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);let a=G.isValidNamespaces(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(G.isExpired(o)){let{message:c}=G.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(a)}let{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=G.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let u=G.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(a)}let{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:u}=this.client.session.get(n);if(!G.isValidNamespacesChainId(u,s)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(a)}if(!G.isValidRequest(i)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(a)}if(!G.isValidNamespacesRequest(u,s,i.method)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(a)}if(o&&!G.isValidRequestExpiry(o,Zy)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Zy.min} and ${Zy.max}`);throw new Error(a)}},this.isValidRespond=async r=>{var n;if(!G.isValidParams(r)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!G.isValidResponse(s)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!G.isValidParams(r)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!G.isValidNamespacesChainId(o,s)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!G.isValidEvent(i)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!G.isValidNamespacesEvent(o,s,i.name)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!G.isValidString(i,!1))throw new Error("uri is required parameter");if(!G.isValidString(s,!1))throw new Error("domain is required parameter");if(!G.isValidString(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(a=>G.parseChainId(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:u}=G.parseChainId(n[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||un.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!G.isValidString(i,!1)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0,s=this.recentlyDeletedLimit/2;for(let o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){let{message:e}=G.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(un.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(ad)?this.client.auth.authKeys.get(ad):{responseTopic:void 0,publicKey:void 0},s=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{qe.isJsonRpcRequest(s)?(this.client.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):qe.isJsonRpcResponse(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.client.core.history.delete(r,s.id)):this.onRelayEventUnknownPayload({topic:r,payload:s})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(un.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=G.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,G.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(un.PAIRING_EVENTS.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(un.PAIRING_EVENTS.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=G.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:r}=G.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(G.isValidString(e,!1)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!G.isValidId(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:r}=G.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},X_=class extends un.Store{constructor(e,r){super(e,r,pU,r1),this.core=e,this.logger=r}},e1=class extends un.Store{constructor(e,r){super(e,r,yU,r1),this.core=e,this.logger=r}},Z_=class extends un.Store{constructor(e,r){super(e,r,vU,r1,n=>n.id),this.core=e,this.logger=r}},e2=class extends un.Store{constructor(e,r){super(e,r,SU,ud,()=>ad),this.core=e,this.logger=r}},t2=class extends un.Store{constructor(e,r){super(e,r,IU,ud),this.core=e,this.logger=r}},r2=class extends un.Store{constructor(e,r){super(e,r,TU,ud,n=>n.id),this.core=e,this.logger=r}},n2=class{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new e2(this.core,this.logger),this.pairingTopics=new t2(this.core,this.logger),this.requests=new r2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},t1=class t extends dU.ISignClient{constructor(e){super(e),this.protocol=i2,this.version=s2,this.name=Xy.name,this.events=new gU.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||Xy.name,this.metadata=e?.metadata||G.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Jy.pino(Jy.getDefaultLoggerOptions({level:e?.logger||Xy.logger}));this.core=e?.core||new un.Core(e),this.logger=Jy.generateChildLogger(r,this.name),this.session=new e1(this.core,this.logger),this.proposal=new X_(this.core,this.logger),this.pendingRequest=new Z_(this.core,this.logger),this.engine=new J_(this),this.auth=new n2(this.core,this.logger)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Jy.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},Fce=e1,Uce=t1;Be.AUTH_CONTEXT=bU,Be.AUTH_KEYS_CONTEXT=SU,Be.AUTH_PAIRING_TOPIC_CONTEXT=IU,Be.AUTH_PROTOCOL=EU,Be.AUTH_PUBLIC_KEY_NAME=ad,Be.AUTH_REQUEST_CONTEXT=TU,Be.AUTH_STORAGE_PREFIX=ud,Be.AUTH_VERSION=Dce,Be.ENGINE_CONTEXT=wU,Be.ENGINE_QUEUE_STATES=vs,Be.ENGINE_RPC_OPTS=wn,Be.HISTORY_CONTEXT=Nce,Be.HISTORY_EVENTS=Cce,Be.HISTORY_STORAGE_VERSION=xce,Be.METHODS_TO_VERIFY=AU,Be.PROPOSAL_CONTEXT=pU,Be.PROPOSAL_EXPIRY=Oce,Be.PROPOSAL_EXPIRY_MESSAGE=mU,Be.REQUEST_CONTEXT=vU,Be.SESSION_CONTEXT=yU,Be.SESSION_EXPIRY=cu,Be.SESSION_REQUEST_EXPIRY_BOUNDARIES=Zy,Be.SIGN_CLIENT_CONTEXT=o2,Be.SIGN_CLIENT_DEFAULT=Xy,Be.SIGN_CLIENT_EVENTS=Tce,Be.SIGN_CLIENT_PROTOCOL=i2,Be.SIGN_CLIENT_STORAGE_OPTIONS=_ce,Be.SIGN_CLIENT_STORAGE_PREFIX=r1,Be.SIGN_CLIENT_VERSION=s2,Be.SessionStore=Fce,Be.SignClient=Uce,Be.WALLETCONNECT_DEEPLINK_CHOICE=Y_,Be.default=t1});var n1=D(Yo=>{"use strict";h();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.OptionalOperation=Yo.Operation=void 0;var qce;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(qce=Yo.Operation||(Yo.Operation={}));var Vce;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(Vce=Yo.OptionalOperation||(Yo.OptionalOperation={}))});var a2=D(As=>{"use strict";h();Object.defineProperty(As,"__esModule",{value:!0});As.WALLETCONNECT_SIGN_LOGIN_DELAY=As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=As.WALLETCONNECT_MULTIVERSX_METHODS=As.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var CU=n1();As.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";As.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(CU.Operation);As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(CU.OptionalOperation);As.WALLETCONNECT_SIGN_LOGIN_DELAY=500});var l2=D(Ci=>{"use strict";h();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WalletConnectV2ProviderErrorMessagesEnum=Ci.ErrBadAddress=Ci.ErrNotImplemented=Ci.Err=void 0;var cd=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ci.Err=cd;var u2=class extends cd{constructor(){super("Method not yet implemented")}};Ci.ErrNotImplemented=u2;var c2=class extends cd{constructor(e,r){super(`Bad address: ${e}`,r)}};Ci.ErrBadAddress=c2;var kce;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(kce=Ci.WalletConnectV2ProviderErrorMessagesEnum||(Ci.WalletConnectV2ProviderErrorMessagesEnum={}))});var h2=D(i1=>{"use strict";h();Object.defineProperty(i1,"__esModule",{value:!0});i1.Logger=void 0;var f2=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};i1.Logger=f2});var NU=D(()=>{"use strict";h();global.Buffer||(global.Buffer=io().Buffer)});var p2=D(Al=>{"use strict";h();Object.defineProperty(Al,"__esModule",{value:!0});Al.SmartContractQueryResponse=Al.SmartContractQuery=void 0;var d2=class{constructor(e){this.contract=e.contract,this.caller=e.caller,this.value=e.value,this.function=e.function,this.arguments=e.arguments}};Al.SmartContractQuery=d2;var g2=class{constructor(e){this.function=e.function,this.returnCode=e.returnCode,this.returnMessage=e.returnMessage,this.returnDataParts=e.returnDataParts}};Al.SmartContractQueryResponse=g2});var OU=D(s1=>{"use strict";h();Object.defineProperty(s1,"__esModule",{value:!0});s1.QueryRunnerAdapter=void 0;var xU=Ve(),Hce=p2(),m2=class{constructor(e){this.networkProvider=e.networkProvider}async runQuery(e){let r={address:xU.Address.fromBech32(e.contract),caller:e.caller?xU.Address.fromBech32(e.caller):void 0,func:e.function,value:e.value,getEncodedArguments:()=>e.arguments.map(i=>p.Buffer.from(i).toString("hex"))},n=await this.networkProvider.queryContract(r);return new Hce.SmartContractQueryResponse({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.getReturnDataParts()})}};s1.QueryRunnerAdapter=m2});var DU=D(lu=>{"use strict";h();var Gce=lu&&lu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),jce=lu&&lu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Gce(e,t,r)};Object.defineProperty(lu,"__esModule",{value:!0});jce(OU(),lu)});var PU=D(fu=>{"use strict";h();var zce=fu&&fu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Qce=fu&&fu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&zce(e,t,r)};Object.defineProperty(fu,"__esModule",{value:!0});Qce(XE(),fu)});var BU=D(hu=>{"use strict";h();Object.defineProperty(hu,"__esModule",{value:!0});hu.GasEstimator=hu.DefaultGasConfiguration=void 0;hu.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Kce=1e5,RU=8e5,y2=class{constructor(e){this.gasConfiguration=e||hu.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Kce}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+RU}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+RU)*r+this.gasConfiguration.gasPerDataByte*e}};hu.GasEstimator=y2});var LU=D(MU=>{"use strict";h();Object.defineProperty(MU,"__esModule",{value:!0})});var UU=D(FU=>{"use strict";h();Object.defineProperty(FU,"__esModule",{value:!0})});var qU=D(o1=>{"use strict";h();Object.defineProperty(o1,"__esModule",{value:!0});o1.RelayedTransactionV1Builder=void 0;var w2=Ve(),Wce=Ie(),$ce=Xr(),Yce=Ms(),Jce=aE(),v2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new Wce.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${p.Buffer.from(e).toString("hex")}`,n=new Yce.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new $ce.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new w2.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new w2.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:BigInt(this.innerTransaction.getValue().toString()),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:p.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new w2.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?p.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?p.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return Jce.stringify(e)}};o1.RelayedTransactionV1Builder=v2});var kU=D(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});a1.RelayedTransactionV2Builder=void 0;var VU=Ie(),ld=qn(),Xce=Xr(),Zce=Ms(),A2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new VU.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new VU.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new ld.ArgSerializer().valuesToString([new ld.AddressValue(this.innerTransaction.getReceiver()),new ld.U64Value(this.innerTransaction.getNonce().valueOf()),new ld.BytesValue(this.innerTransaction.getData().valueOf()),new ld.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Zce.TransactionPayload(r),i=new Xce.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID,version:this.innerTransaction.getVersion(),options:this.innerTransaction.getOptions()});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};a1.RelayedTransactionV2Builder=A2});var HU=D(c1=>{"use strict";h();Object.defineProperty(c1,"__esModule",{value:!0});c1.SmartContractQueriesController=void 0;var ele=Ie(),tle=p2(),u1=qn(),E2=class{constructor(e){this.abi=e.abi,this.queryRunner=e.queryRunner,this.legacyResultsParser=new u1.ResultsParser}createQuery(e){let r=this.encodeArguments(e.function,e.arguments);return new tle.SmartContractQuery({contract:e.contract,caller:e.caller,function:e.function,arguments:r,value:e.value})}encodeArguments(e,r){let n=this.abi?.getEndpoint(e);if(n){let i=u1.NativeSerializer.nativeToTypedValues(r,n);return new u1.ArgSerializer().valuesToBuffers(i)}if(this.areArgsOfTypedValue(r))return new u1.ArgSerializer().valuesToBuffers(r);if(this.areArgsBuffers(r))return r.map(i=>p.Buffer.from(i));throw new ele.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}areArgsBuffers(e){for(let r of e)if(!ArrayBuffer.isView(r))return!1;return!0}async runQuery(e){return await this.queryRunner.runQuery(e)}parseQueryResponse(e){if(!this.abi)return e.returnDataParts;let r={returnCode:e.returnCode,returnMessage:e.returnMessage,getReturnDataParts:()=>e.returnDataParts.map(u=>p.Buffer.from(u))},n=e.function,i=this.abi.getEndpoint(n);return this.legacyResultsParser.parseQueryResponse(r,i).values.map(u=>u.valueOf())}};c1.SmartContractQueriesController=E2});var GU=D(ke=>{"use strict";h();var rle=ke&&ke.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pt=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&rle(e,t,r)};Object.defineProperty(ke,"__esModule",{value:!0});NU();Pt(Ic(),ke);Pt(DU(),ke);Pt(Ve(),ke);Pt(Ub(),ke);Pt(PU(),ke);Pt(Ie(),ke);Pt(BU(),ke);Pt(LU(),ke);Pt(UU(),ke);Pt(oo(),ke);Pt(Mb(),ke);Pt($l(),ke);Pt(qU(),ke);Pt(kU(),ke);Pt(V0(),ke);Pt(HU(),ke);Pt(qn(),ke);Pt(Cb(),ke);Pt(_a(),ke);Pt(Xr(),ke);Pt(_0(),ke);Pt(Ms(),ke);Pt(U0(),ke);Pt(f0(),ke);Pt(Pb(),ke);Pt(Rn(),ke)});var $U=D(ur=>{"use strict";h();var nle=ur&&ur.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ur,"__esModule",{value:!0});ur.sleep=ur.getMetadata=ur.applyTransactionSignature=ur.getAddressFromSession=ur.addressIsValid=ur.getConnectionParams=ur.getCurrentTopic=ur.getCurrentSession=void 0;var QU=GU(),jU=Yf(),ile=Qh(),l1=a2(),to=l2(),b2=h2(),zU=n1();function KU(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find(WU(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw b2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}ur.getCurrentSession=KU;function sle(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=KU(t,e);if(!r?.topic)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}ur.getCurrentTopic=sle;function WU(t,e){var r,n,i;let s=[...l1.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(zU.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(zU.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${l1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],u=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[l1.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:u}}}}ur.getConnectionParams=WU;function ole(t){try{return!QU.Address.fromBech32(t).isEmpty()}catch{return!1}}ur.addressIsValid=ole;function ale(t){let e=t.namespaces[l1.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}ur.getAddressFromSession=ale;function ule({transaction:t,response:e}){if(!e)throw b2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,u=t.getGuardian().bech32();if(u&&u!==o)throw b2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(QU.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new jU.Signature(r)),n&&t.applyGuardianSignature(new jU.Signature(n)),t}ur.applyTransactionSignature=ule;function cle(t){if(t)return Object.assign(Object.assign({},t),{url:ile.getAppMetadata().url})}ur.getMetadata=cle;function lle(t){return nle(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}ur.sleep=lle});var fd=D(cn=>{"use strict";h();var tr=cn&&cn.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},fle=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WalletConnectV2Provider=cn.OptionalOperation=cn.Operation=cn.WalletConnectV2ProviderErrorMessagesEnum=void 0;var hle=Yf(),dle=fle(_U()),S2=Qh(),du=a2(),he=l2();Object.defineProperty(cn,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return he.WalletConnectV2ProviderErrorMessagesEnum}});var Me=h2(),Jo=n1();Object.defineProperty(cn,"Operation",{enumerable:!0,get:function(){return Jo.Operation}});Object.defineProperty(cn,"OptionalOperation",{enumerable:!0,get:function(){return Jo.OptionalOperation}});var xr=$U(),I2=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return tr(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:xr.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield dle.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=xr.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Me.Logger.error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return tr(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield xr.sleep(du.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=xr.getAddressFromSession(n),o=n.namespaces[du.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:Jo.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:u}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!u)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:u})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||xr.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:S2.getSdkError("USER_DISCONNECTED")});else{let r=xr.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:S2.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new hle.Signature(n))}catch{throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return xr.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];xr.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=xr.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return tr(this,void 0,void 0,function*(){return e?xr.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Me.Logger.error(`${he.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return tr(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=xr.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&xr.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:u})=>{var a;if(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)return;let{namespaces:c}=u,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>tr(this,void 0,void 0,function*(){var u;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)&&(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>tr(this,void 0,void 0,function*(){var u;!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o||(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=xr.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,u,a,c;return tr(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!S2.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(a=(u=this.walletConnector.core)===null||u===void 0?void 0:u.relayer)===null||a===void 0?void 0:a.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};cn.WalletConnectV2Provider=I2});var JU=D((ZTe,YU)=>{"use strict";h();YU.exports=Error});var ZU=D((t_e,XU)=>{"use strict";h();XU.exports=EvalError});var tq=D((n_e,eq)=>{"use strict";h();eq.exports=RangeError});var nq=D((s_e,rq)=>{"use strict";h();rq.exports=ReferenceError});var T2=D((a_e,iq)=>{"use strict";h();iq.exports=SyntaxError});var El=D((c_e,sq)=>{"use strict";h();sq.exports=TypeError});var aq=D((f_e,oq)=>{"use strict";h();oq.exports=URIError});var cq=D((d_e,uq)=>{"use strict";h();uq.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var hq=D((p_e,fq)=>{"use strict";h();var lq=typeof Symbol<"u"&&Symbol,gle=cq();fq.exports=function(){return typeof lq!="function"||typeof Symbol!="function"||typeof lq("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:gle()}});var gq=D((y_e,dq)=>{"use strict";h();var _2={__proto__:null,foo:{}},ple=Object;dq.exports=function(){return{__proto__:_2}.foo===_2.foo&&!(_2 instanceof ple)}});var yq=D((v_e,mq)=>{"use strict";h();var mle="Function.prototype.bind called on incompatible ",yle=Object.prototype.toString,wle=Math.max,vle="[object Function]",pq=function(e,r){for(var n=[],i=0;i{"use strict";h();var ble=yq();wq.exports=Function.prototype.bind||ble});var Aq=D((S_e,vq)=>{"use strict";h();var Sle=Function.prototype.call,Ile=Object.prototype.hasOwnProperty,Tle=f1();vq.exports=Tle.call(Sle,Ile)});var mu=D((T_e,Tq)=>{"use strict";h();var Re,_le=JU(),Cle=ZU(),Nle=tq(),xle=nq(),Tl=T2(),Il=El(),Ole=aq(),Iq=Function,C2=function(t){try{return Iq('"use strict"; return ('+t+").constructor;")()}catch{}},gu=Object.getOwnPropertyDescriptor;if(gu)try{gu({},"")}catch{gu=null}var N2=function(){throw new Il},Dle=gu?function(){try{return arguments.callee,N2}catch{try{return gu(arguments,"callee").get}catch{return N2}}}():N2,bl=hq()(),Ple=gq()(),Sr=Object.getPrototypeOf||(Ple?function(t){return t.__proto__}:null),Sl={},Rle=typeof Uint8Array>"u"||!Sr?Re:Sr(Uint8Array),pu={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":bl&&Sr?Sr([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":Sl,"%AsyncGenerator%":Sl,"%AsyncGeneratorFunction%":Sl,"%AsyncIteratorPrototype%":Sl,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":_le,"%eval%":eval,"%EvalError%":Cle,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":Iq,"%GeneratorFunction%":Sl,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":bl&&Sr?Sr(Sr([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!bl||!Sr?Re:Sr(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":Nle,"%ReferenceError%":xle,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!bl||!Sr?Re:Sr(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":bl&&Sr?Sr(""[Symbol.iterator]()):Re,"%Symbol%":bl?Symbol:Re,"%SyntaxError%":Tl,"%ThrowTypeError%":Dle,"%TypedArray%":Rle,"%TypeError%":Il,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":Ole,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Sr)try{null.error}catch(t){Eq=Sr(Sr(t)),pu["%Error.prototype%"]=Eq}var Eq,Ble=function t(e){var r;if(e==="%AsyncFunction%")r=C2("async function () {}");else if(e==="%GeneratorFunction%")r=C2("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=C2("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Sr&&(r=Sr(i.prototype))}return pu[e]=r,r},bq={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},hd=f1(),h1=Aq(),Mle=hd.call(Function.call,Array.prototype.concat),Lle=hd.call(Function.apply,Array.prototype.splice),Sq=hd.call(Function.call,String.prototype.replace),d1=hd.call(Function.call,String.prototype.slice),Fle=hd.call(Function.call,RegExp.prototype.exec),Ule=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,qle=/\\(\\)?/g,Vle=function(e){var r=d1(e,0,1),n=d1(e,-1);if(r==="%"&&n!=="%")throw new Tl("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Tl("invalid intrinsic syntax, expected opening `%`");var i=[];return Sq(e,Ule,function(s,o,u,a){i[i.length]=u?Sq(a,qle,"$1"):o||s}),i},kle=function(e,r){var n=e,i;if(h1(bq,n)&&(i=bq[n],n="%"+i[0]+"%"),h1(pu,n)){var s=pu[n];if(s===Sl&&(s=Ble(n)),typeof s>"u"&&!r)throw new Il("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Tl("intrinsic "+e+" does not exist!")};Tq.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Il("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Il('"allowMissing" argument must be a boolean');if(Fle(/^%?[^%]*%?$/,e)===null)throw new Tl("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Vle(e),i=n.length>0?n[0]:"",s=kle("%"+i+"%",r),o=s.name,u=s.value,a=!1,c=s.alias;c&&(i=c[0],Lle(n,Mle([0,1],c)));for(var f=1,d=!0;f=n.length){var x=gu(u,w);d=!!x,d&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[w]}else d=h1(u,w),u=u[w];d&&!a&&(pu[o]=u)}}return u}});var p1=D((C_e,_q)=>{"use strict";h();var Hle=mu(),g1=Hle("%Object.defineProperty%",!0)||!1;if(g1)try{g1({},"a",{value:1})}catch{g1=!1}_q.exports=g1});var x2=D((x_e,Cq)=>{"use strict";h();var Gle=mu(),m1=Gle("%Object.getOwnPropertyDescriptor%",!0);if(m1)try{m1([],"length")}catch{m1=null}Cq.exports=m1});var Dq=D((D_e,Oq)=>{"use strict";h();var Nq=p1(),jle=T2(),_l=El(),xq=x2();Oq.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new _l("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new _l("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new _l("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new _l("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new _l("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new _l("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,a=!!xq&&xq(e,r);if(Nq)Nq(e,r,{configurable:o===null&&a?a.configurable:!o,enumerable:i===null&&a?a.enumerable:!i,value:n,writable:s===null&&a?a.writable:!s});else if(u||!i&&!s&&!o)e[r]=n;else throw new jle("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var Bq=D((R_e,Rq)=>{"use strict";h();var O2=p1(),Pq=function(){return!!O2};Pq.hasArrayLengthDefineBug=function(){if(!O2)return null;try{return O2([],"length",{value:1}).length!==1}catch{return!0}};Rq.exports=Pq});var qq=D((M_e,Uq)=>{"use strict";h();var zle=mu(),Mq=Dq(),Qle=Bq()(),Lq=x2(),Fq=El(),Kle=zle("%Math.floor%");Uq.exports=function(e,r){if(typeof e!="function")throw new Fq("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Kle(r)!==r)throw new Fq("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&Lq){var o=Lq(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(Qle?Mq(e,"length",r,!0,!0):Mq(e,"length",r)),e}});var zq=D((F_e,y1)=>{"use strict";h();var D2=f1(),w1=mu(),Wle=qq(),$le=El(),Hq=w1("%Function.prototype.apply%"),Gq=w1("%Function.prototype.call%"),jq=w1("%Reflect.apply%",!0)||D2.call(Gq,Hq),Vq=p1(),Yle=w1("%Math.max%");y1.exports=function(e){if(typeof e!="function")throw new $le("a function is required");var r=jq(D2,Gq,arguments);return Wle(r,1+Yle(0,e.length-(arguments.length-1)),!0)};var kq=function(){return jq(D2,Hq,arguments)};Vq?Vq(y1.exports,"apply",{value:kq}):y1.exports.apply=kq});var $q=D((q_e,Wq)=>{"use strict";h();var Qq=mu(),Kq=zq(),Jle=Kq(Qq("String.prototype.indexOf"));Wq.exports=function(e,r){var n=Qq(e,!!r);return typeof n=="function"&&Jle(e,".prototype.")>-1?Kq(n):n}});var Yq=D(()=>{h()});var m7=D((j_e,p7)=>{h();var k2=typeof Map=="function"&&Map.prototype,P2=Object.getOwnPropertyDescriptor&&k2?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,A1=k2&&P2&&typeof P2.get=="function"?P2.get:null,Jq=k2&&Map.prototype.forEach,H2=typeof Set=="function"&&Set.prototype,R2=Object.getOwnPropertyDescriptor&&H2?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,E1=H2&&R2&&typeof R2.get=="function"?R2.get:null,Xq=H2&&Set.prototype.forEach,Xle=typeof WeakMap=="function"&&WeakMap.prototype,gd=Xle?WeakMap.prototype.has:null,Zle=typeof WeakSet=="function"&&WeakSet.prototype,pd=Zle?WeakSet.prototype.has:null,efe=typeof WeakRef=="function"&&WeakRef.prototype,Zq=efe?WeakRef.prototype.deref:null,tfe=Boolean.prototype.valueOf,rfe=Object.prototype.toString,nfe=Function.prototype.toString,ife=String.prototype.match,G2=String.prototype.slice,Zo=String.prototype.replace,sfe=String.prototype.toUpperCase,e7=String.prototype.toLowerCase,c7=RegExp.prototype.test,t7=Array.prototype.concat,Es=Array.prototype.join,ofe=Array.prototype.slice,r7=Math.floor,L2=typeof BigInt=="function"?BigInt.prototype.valueOf:null,B2=Object.getOwnPropertySymbols,F2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,Cl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Ur=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Cl||!0)?Symbol.toStringTag:null,l7=Object.prototype.propertyIsEnumerable,n7=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function i7(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||c7.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-r7(-t):r7(t);if(n!==t){var i=String(n),s=G2.call(e,i.length+1);return Zo.call(i,r,"$&_")+"."+Zo.call(Zo.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return Zo.call(e,r,"$&_")}var U2=Yq(),s7=U2.custom,o7=h7(s7)?s7:null;p7.exports=function t(e,r,n,i){var s=r||{};if(Xo(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Xo(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=Xo(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Xo(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Xo(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var u=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return g7(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var a=String(e);return u?i7(e,a):a}if(typeof e=="bigint"){var c=String(e)+"n";return u?i7(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return q2(e)?"[Array]":"[Object]";var d=Ife(s,n);if(typeof i>"u")i=[];else if(d7(i,e)>=0)return"[Circular]";function w(l,g,y){if(g&&(i=ofe.call(i),i.push(g)),y){var E={depth:s.depth};return Xo(s,"quoteStyle")&&(E.quoteStyle=s.quoteStyle),t(l,E,n+1,i)}return t(l,s,n+1,i)}if(typeof e=="function"&&!a7(e)){var A=pfe(e),T=v1(e,w);return"[Function"+(A?": "+A:" (anonymous)")+"]"+(T.length>0?" { "+Es.call(T,", ")+" }":"")}if(h7(e)){var x=Cl?Zo.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):F2.call(e);return typeof e=="object"&&!Cl?dd(x):x}if(Efe(e)){for(var B="<"+e7.call(String(e.nodeName)),V=e.attributes||[],U=0;U",B}if(q2(e)){if(e.length===0)return"[]";var Q=v1(e,w);return d&&!Sfe(Q)?"["+V2(Q,d)+"]":"[ "+Es.call(Q,", ")+" ]"}if(cfe(e)){var L=v1(e,w);return!("cause"in Error.prototype)&&"cause"in e&&!l7.call(e,"cause")?"{ ["+String(e)+"] "+Es.call(t7.call("[cause]: "+w(e.cause),L),", ")+" }":L.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+Es.call(L,", ")+" }"}if(typeof e=="object"&&o){if(o7&&typeof e[o7]=="function"&&U2)return U2(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(mfe(e)){var k=[];return Jq&&Jq.call(e,function(l,g){k.push(w(g,e,!0)+" => "+w(l,e))}),u7("Map",A1.call(e),k,d)}if(vfe(e)){var H=[];return Xq&&Xq.call(e,function(l){H.push(w(l,e))}),u7("Set",E1.call(e),H,d)}if(yfe(e))return M2("WeakMap");if(Afe(e))return M2("WeakSet");if(wfe(e))return M2("WeakRef");if(ffe(e))return dd(w(Number(e)));if(dfe(e))return dd(w(L2.call(e)));if(hfe(e))return dd(tfe.call(e));if(lfe(e))return dd(w(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!ufe(e)&&!a7(e)){var q=v1(e,w),v=n7?n7(e)===Object.prototype:e instanceof Object||e.constructor===Object,C=e instanceof Object?"":"null prototype",P=!v&&Ur&&Object(e)===e&&Ur in e?G2.call(ea(e),8,-1):C?"Object":"",F=v||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",R=F+(P||C?"["+Es.call(t7.call([],P||[],C||[]),": ")+"] ":"");return q.length===0?R+"{}":d?R+"{"+V2(q,d)+"}":R+"{ "+Es.call(q,", ")+" }"}return String(e)};function f7(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function afe(t){return Zo.call(String(t),/"/g,""")}function q2(t){return ea(t)==="[object Array]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function ufe(t){return ea(t)==="[object Date]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function a7(t){return ea(t)==="[object RegExp]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function cfe(t){return ea(t)==="[object Error]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function lfe(t){return ea(t)==="[object String]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function ffe(t){return ea(t)==="[object Number]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function hfe(t){return ea(t)==="[object Boolean]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function h7(t){if(Cl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!F2)return!1;try{return F2.call(t),!0}catch{}return!1}function dfe(t){if(!t||typeof t!="object"||!L2)return!1;try{return L2.call(t),!0}catch{}return!1}var gfe=Object.prototype.hasOwnProperty||function(t){return t in this};function Xo(t,e){return gfe.call(t,e)}function ea(t){return rfe.call(t)}function pfe(t){if(t.name)return t.name;var e=ife.call(nfe.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function d7(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return g7(G2.call(t,0,e.maxStringLength),e)+n}var i=Zo.call(Zo.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,bfe);return f7(i,"single",e)}function bfe(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+sfe.call(e.toString(16))}function dd(t){return"Object("+t+")"}function M2(t){return t+" { ? }"}function u7(t,e,r,n){var i=n?V2(r,n):Es.call(r,", ");return t+" ("+e+") {"+i+"}"}function Sfe(t){for(var e=0;e=0)return!1;return!0}function Ife(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Es.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Es.call(Array(e+1),r)}}function V2(t,e){if(t.length===0)return"";var r=` `+e.prev+e.base;return r+Es.call(t,","+r)+` -`+e.prev}function w1(t,e){var r=q2(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";h();var j2=Xo(),Nl=Mq(),sfe=r7(),ofe=j2("%TypeError%"),E1=j2("%WeakMap%",!0),b1=j2("%Map%",!0),afe=Nl("WeakMap.prototype.get",!0),ufe=Nl("WeakMap.prototype.set",!0),cfe=Nl("WeakMap.prototype.has",!0),lfe=Nl("Map.prototype.get",!0),ffe=Nl("Map.prototype.set",!0),hfe=Nl("Map.prototype.has",!0),z2=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},dfe=function(t,e){var r=z2(t,e);return r&&r.value},gfe=function(t,e,r){var n=z2(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},pfe=function(t,e){return!!z2(t,e)};n7.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new ofe("Side channel does not contain "+sfe(s))},get:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return afe(e,s)}else if(b1){if(r)return lfe(r,s)}else if(n)return dfe(n,s)},has:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return cfe(e,s)}else if(b1){if(r)return hfe(r,s)}else if(n)return pfe(n,s);return!1},set:function(s,o){E1&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new E1),ufe(e,s,o)):b1?(r||(r=new b1),ffe(r,s,o)):(n||(n={key:{},next:null}),gfe(n,s,o))}};return i}});var S1=B((h_e,s7)=>{"use strict";h();var mfe=String.prototype.replace,yfe=/%20/g,Q2={RFC1738:"RFC1738",RFC3986:"RFC3986"};s7.exports={default:Q2.RFC3986,formatters:{RFC1738:function(t){return mfe.call(t,yfe,"+")},RFC3986:function(t){return String(t)}},RFC1738:Q2.RFC1738,RFC3986:Q2.RFC3986}});var W2=B((g_e,a7)=>{"use strict";h();var wfe=S1(),K2=Object.prototype.hasOwnProperty,yu=Array.isArray,bs=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),vfe=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(yu(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===wfe.RFC1738&&(c===40||c===41)){u+=o.charAt(a);continue}if(c<128){u=u+bs[c];continue}if(c<2048){u=u+(bs[192|c>>6]+bs[128|c&63]);continue}if(c<55296||c>=57344){u=u+(bs[224|c>>12]+bs[128|c>>6&63]+bs[128|c&63]);continue}a+=1,c=65536+((c&1023)<<10|o.charCodeAt(a)&1023),u+=bs[240|c>>18]+bs[128|c>>12&63]+bs[128|c>>6&63]+bs[128|c&63]}return u},Ife=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";h();var l7=i7(),Y2=W2(),wd=S1(),xfe=Object.prototype.hasOwnProperty,u7={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},wu=Array.isArray,Ofe=String.prototype.split,Dfe=Array.prototype.push,f7=function(t,e){Dfe.apply(t,wu(e)?e:[e])},Pfe=Date.prototype.toISOString,c7=wd.default,Or={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Y2.encode,encodeValuesOnly:!1,format:c7,formatter:wd.formatters[c7],indices:!1,serializeDate:function(e){return Pfe.call(e)},skipNulls:!1,strictNullHandling:!1},Rfe=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},$2={},Bfe=function t(e,r,n,i,s,o,u,a,c,f,d,w,A,T,x){for(var R=e,V=x,U=0,Q=!1;(V=V.get($2))!==void 0&&!Q;){var L=V.get(e);if(U+=1,typeof L<"u"){if(L===U)throw new RangeError("Cyclic object value");Q=!0}typeof V.get($2)>"u"&&(U=0)}if(typeof u=="function"?R=u(r,R):R instanceof Date?R=f(R):n==="comma"&&wu(R)&&(R=Y2.maybeMap(R,function(S){return S instanceof Date?f(S):S})),R===null){if(i)return o&&!A?o(r,Or.encoder,T,"key",d):r;R=""}if(Rfe(R)||Y2.isBuffer(R)){if(o){var k=A?r:o(r,Or.encoder,T,"key",d);if(n==="comma"&&A){for(var H=Ofe.call(String(R),","),q="",v=0;v"u")return C;var D;if(n==="comma"&&wu(R))D=[{value:R.length>0?R.join(",")||null:void 0}];else if(wu(u))D=u;else{var F=Object.keys(R);D=a?F.sort(a):F}for(var P=0;P"u"?Or.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Or.charsetSentinel,delimiter:typeof e.delimiter>"u"?Or.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Or.encode,encoder:typeof e.encoder=="function"?e.encoder:Or.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Or.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Or.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Or.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Or.strictNullHandling}};h7.exports=function(t,e){var r=t,n=Mfe(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):wu(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var u;e&&e.arrayFormat in u7?u=e.arrayFormat:e&&"indices"in e?u=e.indices?"indices":"repeat":u="indices";var a=u7[u];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=l7(),f=0;f0?A+w:""}});var m7=B((w_e,p7)=>{"use strict";h();var xl=W2(),J2=Object.prototype.hasOwnProperty,Lfe=Array.isArray,Ir={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:xl.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Ffe=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},g7=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},Ufe="utf8=%26%2310003%3B",qfe="utf8=%E2%9C%93",Vfe=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),u=-1,a,c=r.charset;if(r.charsetSentinel)for(a=0;a-1&&(T=Lfe(T)?[T]:T),J2.call(n,A)?n[A]=xl.combine(n[A],T):n[A]=T}return n},kfe=function(t,e,r,n){for(var i=n?e:g7(e,r),s=t.length-1;s>=0;--s){var o,u=t[s];if(u==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var a=u.charAt(0)==="["&&u.charAt(u.length-1)==="]"?u.slice(1,-1):u,c=parseInt(a,10);!r.parseArrays&&a===""?o={0:i}:!isNaN(c)&&u!==a&&String(c)===a&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):a!=="__proto__"&&(o[a]=i)}i=o}return i},Hfe=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,u=/(\[[^[\]]*])/g,a=n.depth>0&&o.exec(s),c=a?s.slice(0,a.index):s,f=[];if(c){if(!n.plainObjects&&J2.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(a=u.exec(s))!==null&&d"u"?Ir.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?Ir.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:Ir.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:Ir.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:Ir.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ir.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:Ir.comma,decoder:typeof e.decoder=="function"?e.decoder:Ir.decoder,delimiter:typeof e.delimiter=="string"||xl.isRegExp(e.delimiter)?e.delimiter:Ir.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:Ir.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:Ir.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:Ir.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:Ir.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ir.strictNullHandling}};p7.exports=function(t,e){var r=Gfe(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?Vfe(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";h();var jfe=d7(),zfe=m7(),Qfe=S1();y7.exports={formats:Qfe,parse:zfe,stringify:jfe}});var X2=B(je=>{"use strict";h();Object.defineProperty(je,"__esModule",{value:!0});je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=je.WALLET_PROVIDER_CALLBACK_PARAM=je.WALLET_PROVIDER_SIGN_MESSAGE_URL=je.WALLET_PROVIDER_GUARD_TRANSACTION_URL=je.WALLET_PROVIDER_SIGN_TRANSACTION_URL=je.WALLET_PROVIDER_SEND_TRANSACTION_URL=je.WALLET_PROVIDER_DISCONNECT_URL=je.WALLET_PROVIDER_CONNECT_URL=je.XALIAS_PROVIDER_TESTNET=je.XALIAS_PROVIDER_DEVNET=je.XALIAS_PROVIDER_MAINNET=je.WALLET_PROVIDER_TESTNET=je.WALLET_PROVIDER_DEVNET=je.WALLET_PROVIDER_MAINNET=void 0;je.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";je.XALIAS_PROVIDER_MAINNET="https://xalias.com";je.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";je.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";je.WALLET_PROVIDER_CONNECT_URL="hook/login";je.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";je.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";je.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";je.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";je.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";je.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var v7=B(Ol=>{"use strict";h();Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrCannotSignedMessage=Ol.ErrCannotGetSignedTransactions=void 0;var Z2=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Ol.ErrCannotGetSignedTransactions=Z2;var eC=class extends Error{constructor(){super("Cannot get signed message")}};Ol.ErrCannotSignedMessage=eC});var A7=B(I1=>{"use strict";h();Object.defineProperty(I1,"__esModule",{value:!0});I1.PlainSignedTransaction=void 0;var tC=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};I1.PlainSignedTransaction=tC});var Dl=B(ia=>{"use strict";h();var ra=ia&&ia.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Kfe=ia&&ia.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ia,"__esModule",{value:!0});ia.WalletProvider=void 0;var rC=Kfe(w7()),na=X2(),nC=v7(),Wfe=A7(),iC=class t{constructor(e){this.walletUrl=e}login(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return ra(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return ra(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return ra(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=rC.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new nC.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return ra(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(e=window.location.search){let r=rC.default.parse(e.slice(1));return t.isTxSignReturnSuccess(r)?this.getTxSignReturnValue(r):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(na.WALLET_PROVIDER_CALLBACK_PARAM)&&e[na.WALLET_PROVIDER_CALLBACK_PARAM]===na.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new nC.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new nC.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let u=t.prepareWalletTransaction(o);for(let a in u)u.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(i[a]=[]),i[a].push(u[a])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};ia.WalletProvider=iC});var e9=B((O_e,Z7)=>{"use strict";h();function P7(t,e){return function(){return t.apply(e,arguments)}}var{toString:$fe}=Object.prototype,{getPrototypeOf:mC}=Object,N1=(t=>e=>{let r=$fe.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Is=t=>(t=t.toLowerCase(),e=>N1(e)===t),x1=t=>e=>typeof e===t,{isArray:Ml}=Array,Ad=x1("undefined");function Yfe(t){return t!==null&&!Ad(t)&&t.constructor!==null&&!Ad(t.constructor)&&ei(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var R7=Is("ArrayBuffer");function Jfe(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&R7(t.buffer),e}var Xfe=x1("string"),ei=x1("function"),B7=x1("number"),O1=t=>t!==null&&typeof t=="object",Zfe=t=>t===!0||t===!1,T1=t=>{if(N1(t)!=="object")return!1;let e=mC(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ehe=Is("Date"),the=Is("File"),rhe=Is("Blob"),nhe=Is("FileList"),ihe=t=>O1(t)&&ei(t.pipe),she=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ei(t.append)&&((e=N1(t))==="formdata"||e==="object"&&ei(t.toString)&&t.toString()==="[object FormData]"))},ohe=Is("URLSearchParams"),ahe=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ed(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ml(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var L7=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F7=t=>!Ad(t)&&t!==L7;function cC(){let{caseless:t}=F7(this)&&this||{},e={},r=(n,i)=>{let s=t&&M7(e,i)||i;T1(e[s])&&T1(n)?e[s]=cC(e[s],n):T1(n)?e[s]=cC({},n):Ml(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(Ed(e,(i,s)=>{r&&ei(i)?t[s]=P7(i,r):t[s]=i},{allOwnKeys:n}),t),che=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),lhe=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},fhe=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&mC(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},hhe=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},dhe=t=>{if(!t)return null;if(Ml(t))return t;let e=t.length;if(!B7(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},ghe=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&mC(Uint8Array)),phe=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},mhe=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},yhe=Is("HTMLFormElement"),whe=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),E7=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),vhe=Is("RegExp"),U7=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};Ed(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},Ahe=t=>{U7(t,(e,r)=>{if(ei(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(ei(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Ehe=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ml(t)?n(t):n(String(t).split(e)),r},bhe=()=>{},She=(t,e)=>(t=+t,Number.isFinite(t)?t:e),sC="abcdefghijklmnopqrstuvwxyz",b7="0123456789",q7={DIGIT:b7,ALPHA:sC,ALPHA_DIGIT:sC+sC.toUpperCase()+b7},Ihe=(t=16,e=q7.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function The(t){return!!(t&&ei(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var _he=t=>{let e=new Array(10),r=(n,i)=>{if(O1(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ml(n)?[]:{};return Ed(n,(o,u)=>{let a=r(o,i+1);!Ad(a)&&(s[u]=a)}),e[i]=void 0,s}}return n};return r(t,0)},Che=Is("AsyncFunction"),Nhe=t=>t&&(O1(t)||ei(t))&&ei(t.then)&&ei(t.catch),re={isArray:Ml,isArrayBuffer:R7,isBuffer:Yfe,isFormData:she,isArrayBufferView:Jfe,isString:Xfe,isNumber:B7,isBoolean:Zfe,isObject:O1,isPlainObject:T1,isUndefined:Ad,isDate:ehe,isFile:the,isBlob:rhe,isRegExp:vhe,isFunction:ei,isStream:ihe,isURLSearchParams:ohe,isTypedArray:ghe,isFileList:nhe,forEach:Ed,merge:cC,extend:uhe,trim:ahe,stripBOM:che,inherits:lhe,toFlatObject:fhe,kindOf:N1,kindOfTest:Is,endsWith:hhe,toArray:dhe,forEachEntry:phe,matchAll:mhe,isHTMLForm:yhe,hasOwnProperty:E7,hasOwnProp:E7,reduceDescriptors:U7,freezeMethods:Ahe,toObjectSet:Ehe,toCamelCase:whe,noop:bhe,toFiniteNumber:She,findKey:M7,global:L7,isContextDefined:F7,ALPHABET:q7,generateString:Ihe,isSpecCompliantForm:The,toJSONObject:_he,isAsyncFn:Che,isThenable:Nhe};function Le(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}re.inherits(Le,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:re.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var V7=Le.prototype,k7={};["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(t=>{k7[t]={value:t}});Object.defineProperties(Le,k7);Object.defineProperty(V7,"isAxiosError",{value:!0});Le.from=(t,e,r,n,i,s)=>{let o=Object.create(V7);return re.toFlatObject(t,o,function(a){return a!==Error.prototype},u=>u!=="isAxiosError"),Le.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var xhe=null;function lC(t){return re.isPlainObject(t)||re.isArray(t)}function H7(t){return re.endsWith(t,"[]")?t.slice(0,-2):t}function S7(t,e,r){return t?t.concat(e).map(function(i,s){return i=H7(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Ohe(t){return re.isArray(t)&&!t.some(lC)}var Dhe=re.toFlatObject(re,{},null,function(e){return/^is[A-Z]/.test(e)});function D1(t,e,r){if(!re.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=re.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,R){return!re.isUndefined(R[x])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,a=(r.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function c(T){if(T===null)return"";if(re.isDate(T))return T.toISOString();if(!a&&re.isBlob(T))throw new Le("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(T)||re.isTypedArray(T)?a&&typeof Blob=="function"?new Blob([T]):p.Buffer.from(T):T}function f(T,x,R){let V=T;if(T&&!R&&typeof T=="object"){if(re.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=JSON.stringify(T);else if(re.isArray(T)&&Ohe(T)||(re.isFileList(T)||re.endsWith(x,"[]"))&&(V=re.toArray(T)))return x=H7(x),V.forEach(function(Q,L){!(re.isUndefined(Q)||Q===null)&&e.append(o===!0?S7([x],L,s):o===null?x:x+"[]",c(Q))}),!1}return lC(T)?!0:(e.append(S7(R,x,s),c(T)),!1)}let d=[],w=Object.assign(Dhe,{defaultVisitor:f,convertValue:c,isVisitable:lC});function A(T,x){if(!re.isUndefined(T)){if(d.indexOf(T)!==-1)throw Error("Circular reference detected in "+x.join("."));d.push(T),re.forEach(T,function(V,U){(!(re.isUndefined(V)||V===null)&&i.call(e,V,re.isString(U)?U.trim():U,x,w))===!0&&A(V,x?x.concat(U):[U])}),d.pop()}}if(!re.isObject(t))throw new TypeError("data must be an object");return A(t),e}function I7(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function yC(t,e){this._pairs=[],t&&D1(t,this,e)}var G7=yC.prototype;G7.append=function(e,r){this._pairs.push([e,r])};G7.toString=function(e){let r=e?function(n){return e.call(this,n,I7)}:I7;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Phe(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function j7(t,e,r){if(!e)return t;let n=r&&r.encode||Phe,i=r&&r.serialize,s;if(i?s=i(e,r):s=re.isURLSearchParams(e)?e.toString():new yC(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var fC=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(n){n!==null&&e(n)})}},T7=fC,z7={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Rhe=typeof URLSearchParams<"u"?URLSearchParams:yC,Bhe=typeof FormData<"u"?FormData:null,Mhe=typeof Blob<"u"?Blob:null,Lhe={isBrowser:!0,classes:{URLSearchParams:Rhe,FormData:Bhe,Blob:Mhe},protocols:["http","https","file","blob","url","data"]},Q7=typeof window<"u"&&typeof document<"u",Fhe=(t=>Q7&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),Uhe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",qhe=Object.freeze({__proto__:null,hasBrowserEnv:Q7,hasStandardBrowserWebWorkerEnv:Uhe,hasStandardBrowserEnv:Fhe}),Ss={...qhe,...Lhe};function Vhe(t,e){return D1(t,new Ss.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Ss.isNode&&re.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function khe(t){return re.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Hhe(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&re.isArray(i)?i.length:o,a?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&re.isArray(i[o])&&(i[o]=Hhe(i[o])),!u)}if(re.isFormData(t)&&re.isFunction(t.entries)){let r={};return re.forEachEntry(t,(n,i)=>{e(khe(n),i,r,0)}),r}return null}function Ghe(t,e,r){if(re.isString(t))try{return(e||JSON.parse)(t),re.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var wC={transitional:z7,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=re.isObject(e);if(s&&re.isHTMLForm(e)&&(e=new FormData(e)),re.isFormData(e))return i?JSON.stringify(K7(e)):e;if(re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e))return e;if(re.isArrayBufferView(e))return e.buffer;if(re.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Vhe(e,this.formSerializer).toString();if((u=re.isFileList(e))||n.indexOf("multipart/form-data")>-1){let a=this.env&&this.env.FormData;return D1(u?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Ghe(e)):e}],transformResponse:[function(e){let r=this.transitional||wC.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&re.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?Le.from(u,Le.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ss.classes.FormData,Blob:Ss.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],t=>{wC.headers[t]={}});var vC=wC,jhe=re.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"]),zhe=t=>{let e={},r,n,i;return t&&t.split(` -`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&jhe[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},_7=Symbol("internals");function vd(t){return t&&String(t).trim().toLowerCase()}function _1(t){return t===!1||t==null?t:re.isArray(t)?t.map(_1):String(t)}function Qhe(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Khe=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function oC(t,e,r,n,i){if(re.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function Whe(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function $he(t,e){let r=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Pl=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,a,c){let f=vd(a);if(!f)throw new Error("header name must be a non-empty string");let d=re.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||a]=_1(u))}let o=(u,a)=>re.forEach(u,(c,f)=>s(c,f,a));return re.isPlainObject(e)||e instanceof this.constructor?o(e,r):re.isString(e)&&(e=e.trim())&&!Khe(e)?o(zhe(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=vd(e),e){let n=re.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Qhe(i);if(re.isFunction(r))return r.call(this,i,n);if(re.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=vd(e),e){let n=re.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||oC(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=vd(o),o){let u=re.findKey(n,o);u&&(!r||oC(n,n[u],u,r))&&(delete n[u],i=!0)}}return re.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||oC(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return re.forEach(this,(i,s)=>{let o=re.findKey(n,s);if(o){r[o]=_1(i),delete r[s];return}let u=e?Whe(s):String(s).trim();u!==s&&delete r[s],r[u]=_1(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return re.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&re.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[_7]=this[_7]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=vd(o);n[u]||($he(i,o),n[u]=!0)}return re.isArray(e)?e.forEach(s):s(e),this}};Pl.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);re.reduceDescriptors(Pl.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});re.freezeMethods(Pl);var ro=Pl;function aC(t,e){let r=this||vC,n=e||r,i=ro.from(n.headers),s=n.data;return re.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function W7(t){return!!(t&&t.__CANCEL__)}function bd(t,e,r){Le.call(this,t??"canceled",Le.ERR_CANCELED,e,r),this.name="CanceledError"}re.inherits(bd,Le,{__CANCEL__:!0});function Yhe(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Le("Request failed with status code "+r.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var Jhe=Ss.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];re.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),re.isString(n)&&o.push("path="+n),re.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Xhe(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Zhe(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function $7(t,e){return t&&!Xhe(e)?Zhe(t,e):e}var ede=Ss.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=re.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function tde(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function rde(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(a){let c=Date.now(),f=n[s];o||(o=c),r[i]=a,n[i]=c;let d=s,w=0;for(;d!==i;)w+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,a=n(u),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:a||void 0,estimated:a&&o&&c?(o-s)/a:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var nde=typeof XMLHttpRequest<"u",ide=nde&&function(t){return new Promise(function(r,n){let i=t.data,s=ro.from(t.headers).normalize(),{responseType:o,withXSRFToken:u}=t,a;function c(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}let f;if(re.isFormData(i)){if(Ss.hasStandardBrowserEnv||Ss.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[x,...R]=f?f.split(";").map(V=>V.trim()).filter(Boolean):[];s.setContentType([x||"multipart/form-data",...R].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let x=t.auth.username||"",R=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(x+":"+R))}let w=$7(t.baseURL,t.url);d.open(t.method.toUpperCase(),j7(w,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function A(){if(!d)return;let x=ro.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),V={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:x,config:t,request:d};Yhe(function(Q){r(Q),c()},function(Q){n(Q),c()},V),d=null}if("onloadend"in d?d.onloadend=A:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(A)},d.onabort=function(){d&&(n(new Le("Request aborted",Le.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Le("Network Error",Le.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let R=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||z7;t.timeoutErrorMessage&&(R=t.timeoutErrorMessage),n(new Le(R,V.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,t,d)),d=null},Ss.hasStandardBrowserEnv&&(u&&re.isFunction(u)&&(u=u(t)),u||u!==!1&&ede(w))){let x=t.xsrfHeaderName&&t.xsrfCookieName&&Jhe.read(t.xsrfCookieName);x&&s.set(t.xsrfHeaderName,x)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&re.forEach(s.toJSON(),function(R,V){d.setRequestHeader(V,R)}),re.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",C7(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",C7(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=x=>{d&&(n(!x||x.type?new bd(null,t,d):x),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));let T=tde(w);if(T&&Ss.protocols.indexOf(T)===-1){n(new Le("Unsupported protocol "+T+":",Le.ERR_BAD_REQUEST,t));return}d.send(i||null)})},hC={http:xhe,xhr:ide};re.forEach(hC,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var N7=t=>`- ${t}`,sde=t=>re.isFunction(t)||t===null||t===!1,Y7={getAdapter:t=>{t=re.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${u} `+(a===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : -`+s.map(N7).join(` -`):" "+N7(s[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:hC};function uC(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new bd(null,t)}function x7(t){return uC(t),t.headers=ro.from(t.headers),t.data=aC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Y7.getAdapter(t.adapter||vC.adapter)(t).then(function(n){return uC(t),n.data=aC.call(t,t.transformResponse,n),n.headers=ro.from(n.headers),n},function(n){return W7(n)||(uC(t),n&&n.response&&(n.response.data=aC.call(t,t.transformResponse,n.response),n.response.headers=ro.from(n.response.headers))),Promise.reject(n)})}var O7=t=>t instanceof ro?{...t}:t;function Rl(t,e){e=e||{};let r={};function n(c,f,d){return re.isPlainObject(c)&&re.isPlainObject(f)?re.merge.call({caseless:d},c,f):re.isPlainObject(f)?re.merge({},f):re.isArray(f)?f.slice():f}function i(c,f,d){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!re.isUndefined(f))return n(void 0,f)}function o(c,f){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function u(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let 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:u,headers:(c,f)=>i(O7(c),O7(f),!0)};return re.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=a[f]||i,w=d(t[f],e[f],f);re.isUndefined(w)&&d!==u||(r[f]=w)}),r}var J7="1.6.8",AC={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{AC[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var D7={};AC.transitional=function(e,r,n){function i(s,o){return"[Axios v"+J7+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new Le(i(o," has been removed"+(r?" in "+r:"")),Le.ERR_DEPRECATED);return r&&!D7[o]&&(D7[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function ode(t,e,r){if(typeof t!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],a=u===void 0||o(u,s,t);if(a!==!0)throw new Le("option "+s+" must be "+a,Le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}var dC={assertOptions:ode,validators:AC},sa=dC.validators,Bl=class{constructor(e){this.defaults=e,this.interceptors={request:new T7,response:new T7}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` -`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Rl(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&dC.assertOptions(n,{silentJSONParsing:sa.transitional(sa.boolean),forcedJSONParsing:sa.transitional(sa.boolean),clarifyTimeoutError:sa.transitional(sa.boolean)},!1),i!=null&&(re.isFunction(i)?r.paramsSerializer={serialize:i}:dC.assertOptions(i,{encode:sa.function,serialize:sa.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&re.merge(s.common,s[r.method]);s&&re.forEach(["delete","get","head","post","put","patch","common"],T=>{delete s[T]}),r.headers=ro.concat(o,s);let u=[],a=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(r)===!1||(a=a&&x.synchronous,u.unshift(x.fulfilled,x.rejected))});let c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let f,d=0,w;if(!a){let T=[x7.bind(this),void 0];for(T.unshift.apply(T,u),T.push.apply(T,c),w=T.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new bd(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},ade=gC;function ude(t){return function(r){return t.apply(null,r)}}function cde(t){return re.isObject(t)&&t.isAxiosError===!0}var pC={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(pC).forEach(([t,e])=>{pC[e]=t});var lde=pC;function X7(t){let e=new C1(t),r=P7(C1.prototype.request,e);return re.extend(r,C1.prototype,e,{allOwnKeys:!0}),re.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return X7(Rl(t,i))},r}var cr=X7(vC);cr.Axios=C1;cr.CanceledError=bd;cr.CancelToken=ade;cr.isCancel=W7;cr.VERSION=J7;cr.toFormData=D1;cr.AxiosError=Le;cr.Cancel=cr.CanceledError;cr.all=function(e){return Promise.all(e)};cr.spread=ude;cr.isAxiosError=cde;cr.mergeConfig=Rl;cr.AxiosHeaders=ro;cr.formToJSON=t=>K7(re.isHTMLForm(t)?new FormData(t):t);cr.getAdapter=Y7.getAdapter;cr.HttpStatusCode=lde;cr.default=cr;Z7.exports=cr});var t9=B(P1=>{"use strict";h();Object.defineProperty(P1,"__esModule",{value:!0});P1.NativeAuthClientConfig=void 0;var EC=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};P1.NativeAuthClientConfig=EC});var SC=B(Ll=>{"use strict";h();var vu=Ll&&Ll.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.NativeAuthClient=void 0;var fde=e9(),hde=t9(),bC=class{constructor(e){this.config=Object.assign(new hde.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vu(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vu(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vu(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vu(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vu(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vu(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(p.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vu(this,void 0,void 0,function*(){return yield fde.default.get(e,{headers:this.config.extraRequestHeaders})})}};Ll.NativeAuthClient=bC});var s9=B(B1=>{"use strict";h();Object.defineProperty(B1,"__esModule",{value:!0});B1.TransactionStatus=void 0;var TC=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};B1.TransactionStatus=TC});var a9=B(M1=>{"use strict";h();Object.defineProperty(M1,"__esModule",{value:!0});M1.TransactionReceipt=void 0;var o9=_c(),_C=class t{constructor(){this.value="",this.sender=new o9.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new o9.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};M1.TransactionReceipt=_C});var u9=B(Ts=>{"use strict";h();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ErrContractQuery=Ts.ErrNetworkProvider=Ts.ErrUnexpectedCondition=Ts.Err=void 0;var Ul=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ts.Err=Ul;var CC=class extends Ul{constructor(e){super(`Unexpected condition: [${e}]`)}};Ts.ErrUnexpectedCondition=CC;var NC=class extends Ul{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Ts.ErrNetworkProvider=NC;var xC=class extends Ul{constructor(e){super(e.message.replace("executeQuery:",""))}};Ts.ErrContractQuery=xC});var l9=B(oa=>{"use strict";h();Object.defineProperty(oa,"__esModule",{value:!0});oa.TransactionEventTopic=oa.TransactionEventData=oa.TransactionEvent=void 0;var c9=_c(),OC=class t{constructor(e){this.address=new c9.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new ql(p.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new c9.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new L1(n)),r.dataPayload=ql.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(ql.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};oa.TransactionEvent=OC;var ql=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(p.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventData=ql;var L1=class{constructor(e){this.raw=p.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventTopic=L1});var PC=B(F1=>{"use strict";h();Object.defineProperty(F1,"__esModule",{value:!0});F1.TransactionLogs=void 0;var pde=u9(),f9=_c(),mde=l9(),DC=class t{constructor(e){this.address=new f9.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new f9.Address(e.address),r.events=(e.events||[]).map(n=>mde.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new pde.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};F1.TransactionLogs=DC});var d9=B(Vl=>{"use strict";h();Object.defineProperty(Vl,"__esModule",{value:!0});Vl.ContractResultItem=Vl.ContractResults=void 0;var h9=PC(),U1=_c(),RC=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>Sd.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>Sd.fromApiHttpResponse(n));return new t(r)}};Vl.ContractResults=RC;var Sd=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new U1.Address(""),this.sender=new U1.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new h9.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=p.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new U1.Address(e.receiver),r.sender=new U1.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=h9.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Vl.ContractResultItem=Sd});var g9=B(q1=>{"use strict";h();Object.defineProperty(q1,"__esModule",{value:!0});q1.ContractQueryRequest=void 0;var BC=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};q1.ContractQueryRequest=BC});var _9=B((R2e,T9)=>{h();T9.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var aa=B(Eu=>{h();var MC,yde=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Eu.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Eu.getSymbolTotalCodewords=function(e){return yde[e]};Eu.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Eu.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');MC=e};Eu.isKanjiModeEnabled=function(){return typeof MC<"u"};Eu.toSJIS=function(e){return MC(e)}});var G1=B(ti=>{h();ti.L={bit:1};ti.M={bit:0};ti.Q={bit:3};ti.H={bit:2};function wde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ti.L;case"m":case"medium":return ti.M;case"q":case"quartile":return ti.Q;case"h":case"high":return ti.H;default:throw new Error("Unknown EC Level: "+t)}}ti.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ti.from=function(e,r){if(ti.isValid(e))return e;try{return wde(e)}catch{return r}}});var x9=B((q2e,N9)=>{h();function C9(){this.buffer=[],this.length=0}C9.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};N9.exports=C9});var D9=B((k2e,O9)=>{h();function Id(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Id.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};Id.prototype.get=function(t,e){return this.data[t*this.size+e]};Id.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Id.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};O9.exports=Id});var P9=B(j1=>{h();var vde=aa().getSymbolSize;j1.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=vde(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{h();var Ade=aa().getSymbolSize,R9=7;B9.getPositions=function(e){let r=Ade(e);return[[0,0],[r-R9,0],[0,r-R9]]}});var L9=B(Rt=>{h();Rt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bu={N1:3,N2:3,N3:40,N4:10};Rt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Rt.from=function(e){return Rt.isValid(e)?parseInt(e,10):void 0};Rt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,u=null;for(let a=0;a=5&&(n+=bu.N1+(i-5)),o=f,i=1),f=e.get(c,a),f===u?s++:(s>=5&&(n+=bu.N1+(s-5)),u=f,s=1)}i>=5&&(n+=bu.N1+(i-5)),s>=5&&(n+=bu.N1+(s-5))}return n};Rt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(u,o),u>=10&&(s===1488||s===93)&&n++}return n*bu.N3};Rt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{h();var ua=G1(),z1=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Q1=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];LC.getBlocksCount=function(e,r){switch(r){case ua.L:return z1[(e-1)*4+0];case ua.M:return z1[(e-1)*4+1];case ua.Q:return z1[(e-1)*4+2];case ua.H:return z1[(e-1)*4+3];default:return}};LC.getTotalCodewordsCount=function(e,r){switch(r){case ua.L:return Q1[(e-1)*4+0];case ua.M:return Q1[(e-1)*4+1];case ua.Q:return Q1[(e-1)*4+2];case ua.H:return Q1[(e-1)*4+3];default:return}}});var F9=B(W1=>{h();var Td=new Uint8Array(512),K1=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Td[r]=e,K1[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Td[r]=Td[r-255]})();W1.log=function(e){if(e<1)throw new Error("log("+e+")");return K1[e]};W1.exp=function(e){return Td[e]};W1.mul=function(e,r){return e===0||r===0?0:Td[K1[e]+K1[r]]}});var U9=B(_d=>{h();var UC=F9();_d.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{h();var q9=U9();function qC(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}qC.prototype.initialize=function(e){this.degree=e,this.genPoly=q9.generateECPolynomial(this.degree)};qC.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=q9.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};V9.exports=qC});var VC=B(H9=>{h();H9.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var kC=B(no=>{h();var G9="[0-9]+",bde="[A-Z $%*+\\-./:]+",Cd="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Cd=Cd.replace(/u/g,"\\u");var Sde="(?:(?![A-Z0-9 $%*+\\-./:]|"+Cd+`)(?:.|[\r -]))+`;no.KANJI=new RegExp(Cd,"g");no.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");no.BYTE=new RegExp(Sde,"g");no.NUMERIC=new RegExp(G9,"g");no.ALPHANUMERIC=new RegExp(bde,"g");var Ide=new RegExp("^"+Cd+"$"),Tde=new RegExp("^"+G9+"$"),_de=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");no.testKanji=function(e){return Ide.test(e)};no.testNumeric=function(e){return Tde.test(e)};no.testAlphanumeric=function(e){return _de.test(e)}});var ca=B(lr=>{h();var Cde=VC(),HC=kC();lr.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};lr.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};lr.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};lr.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};lr.MIXED={bit:-1};lr.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Cde.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};lr.getBestModeForData=function(e){return HC.testNumeric(e)?lr.NUMERIC:HC.testAlphanumeric(e)?lr.ALPHANUMERIC:HC.testKanji(e)?lr.KANJI:lr.BYTE};lr.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};lr.isValid=function(e){return e&&e.bit&&e.ccBits};function Nde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return lr.NUMERIC;case"alphanumeric":return lr.ALPHANUMERIC;case"kanji":return lr.KANJI;case"byte":return lr.BYTE;default:throw new Error("Unknown mode: "+t)}}lr.from=function(e,r){if(lr.isValid(e))return e;try{return Nde(e)}catch{return r}}});var W9=B(Su=>{h();var $1=aa(),xde=FC(),j9=G1(),la=ca(),GC=VC(),Q9=7973,z9=$1.getBCHDigit(Q9);function Ode(t,e,r){for(let n=1;n<=40;n++)if(e<=Su.getCapacity(n,r,t))return n}function K9(t,e){return la.getCharCountIndicator(t,e)+4}function Dde(t,e){let r=0;return t.forEach(function(n){let i=K9(n.mode,e);r+=i+n.getBitsLength()}),r}function Pde(t,e){for(let r=1;r<=40;r++)if(Dde(t,r)<=Su.getCapacity(r,e,la.MIXED))return r}Su.from=function(e,r){return GC.isValid(e)?parseInt(e,10):r};Su.getCapacity=function(e,r,n){if(!GC.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=la.BYTE);let i=$1.getSymbolTotalCodewords(e),s=xde.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===la.MIXED)return o;let u=o-K9(n,e);switch(n){case la.NUMERIC:return Math.floor(u/10*3);case la.ALPHANUMERIC:return Math.floor(u/11*2);case la.KANJI:return Math.floor(u/13);case la.BYTE:default:return Math.floor(u/8)}};Su.getBestVersionForData=function(e,r){let n,i=j9.from(r,j9.M);if(Array.isArray(e)){if(e.length>1)return Pde(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Ode(n.mode,n.getLength(),i)};Su.getEncodedBits=function(e){if(!GC.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;$1.getBCHDigit(r)-z9>=0;)r^=Q9<<$1.getBCHDigit(r)-z9;return e<<12|r}});var X9=B(J9=>{h();var jC=aa(),Y9=1335,Rde=21522,$9=jC.getBCHDigit(Y9);J9.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;jC.getBCHDigit(i)-$9>=0;)i^=Y9<{h();var Bde=ca();function Hl(t){this.mode=Bde.NUMERIC,this.data=t.toString()}Hl.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Hl.prototype.getLength=function(){return this.data.length};Hl.prototype.getBitsLength=function(){return Hl.getBitsLength(this.data.length)};Hl.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};Z9.exports=Hl});var rV=B((pCe,tV)=>{h();var Mde=ca(),zC=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Gl(t){this.mode=Mde.ALPHANUMERIC,this.data=t}Gl.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Gl.prototype.getLength=function(){return this.data.length};Gl.prototype.getBitsLength=function(){return Gl.getBitsLength(this.data.length)};Gl.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=zC.indexOf(this.data[r])*45;n+=zC.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(zC.indexOf(this.data[r]),6)};tV.exports=Gl});var iV=B((yCe,nV)=>{"use strict";h();nV.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var oV=B((vCe,sV)=>{h();var Lde=iV(),Fde=ca();function jl(t){this.mode=Fde.BYTE,typeof t=="string"&&(t=Lde(t)),this.data=new Uint8Array(t)}jl.getBitsLength=function(e){return e*8};jl.prototype.getLength=function(){return this.data.length};jl.prototype.getBitsLength=function(){return jl.getBitsLength(this.data.length)};jl.prototype.write=function(t){for(let e=0,r=this.data.length;e{h();var Ude=ca(),qde=aa();function zl(t){this.mode=Ude.KANJI,this.data=t}zl.getBitsLength=function(e){return e*13};zl.prototype.getLength=function(){return this.data.length};zl.prototype.getBitsLength=function(){return zl.getBitsLength(this.data.length)};zl.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` -Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};aV.exports=zl});var cV=B((SCe,QC)=>{"use strict";h();var Nd={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=Nd.PriorityQueue.make();s.push(e,0);for(var o,u,a,c,f,d,w,A,T;!s.empty();){o=s.pop(),u=o.value,c=o.cost,f=t[u]||{};for(a in f)f.hasOwnProperty(a)&&(d=f[a],w=c+d,A=i[a],T=typeof i[a]>"u",(T||A>w)&&(i[a]=w,s.push(a,w),n[a]=u))}if(typeof r<"u"&&typeof i[r]>"u"){var x=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(x)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=Nd.single_source_shortest_paths(t,e,r);return Nd.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Nd.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof QC<"u"&&(QC.exports=Nd)});var yV=B(Ql=>{h();var ze=ca(),hV=eV(),dV=rV(),gV=oV(),pV=uV(),xd=kC(),Y1=aa(),Vde=cV();function lV(t){return unescape(encodeURIComponent(t)).length}function Od(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function mV(t){let e=Od(xd.NUMERIC,ze.NUMERIC,t),r=Od(xd.ALPHANUMERIC,ze.ALPHANUMERIC,t),n,i;return Y1.isKanjiModeEnabled()?(n=Od(xd.BYTE,ze.BYTE,t),i=Od(xd.KANJI,ze.KANJI,t)):(n=Od(xd.BYTE_KANJI,ze.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,u){return o.index-u.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function KC(t,e){switch(e){case ze.NUMERIC:return hV.getBitsLength(t);case ze.ALPHANUMERIC:return dV.getBitsLength(t);case ze.KANJI:return pV.getBitsLength(t);case ze.BYTE:return gV.getBitsLength(t)}}function kde(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Hde(t){let e=[];for(let r=0;r{h();var X1=aa(),WC=G1(),jde=x9(),zde=D9(),Qde=P9(),Kde=M9(),JC=L9(),XC=FC(),Wde=k9(),J1=W9(),$de=X9(),Yde=ca(),$C=yV();function Jde(t,e){let r=t.size,n=Kde.getPositions(e);for(let i=0;i=0&&u<=6&&(a===0||a===6)||a>=0&&a<=6&&(u===0||u===6)||u>=2&&u<=4&&a>=2&&a<=4?t.set(s+u,o+a,!0,!0):t.set(s+u,o+a,!1,!0))}}function Xde(t){let e=t.size;for(let r=8;r>u&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function YC(t,e,r){let n=t.size,i=$de.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function tge(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let u=r-1;u>0;u-=2)for(u===6&&u--;;){for(let a=0;a<2;a++)if(!t.isReserved(i,u-a)){let c=!1;o>>s&1)===1),t.set(i,u-a,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function rge(t,e,r){let n=new jde;r.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),Yde.getCharCountIndicator(a.mode,t)),a.write(n)});let i=X1.getSymbolTotalCodewords(t),s=XC.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let u=(o-n.getLengthInBits())/8;for(let a=0;a{"use strict";h();var y7=mu(),Nl=$q(),Tfe=m7(),_fe=El(),b1=y7("%WeakMap%",!0),S1=y7("%Map%",!0),Cfe=Nl("WeakMap.prototype.get",!0),Nfe=Nl("WeakMap.prototype.set",!0),xfe=Nl("WeakMap.prototype.has",!0),Ofe=Nl("Map.prototype.get",!0),Dfe=Nl("Map.prototype.set",!0),Pfe=Nl("Map.prototype.has",!0),j2=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},Rfe=function(t,e){var r=j2(t,e);return r&&r.value},Bfe=function(t,e,r){var n=j2(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},Mfe=function(t,e){return!!j2(t,e)};w7.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new _fe("Side channel does not contain "+Tfe(s))},get:function(s){if(b1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return Cfe(e,s)}else if(S1){if(r)return Ofe(r,s)}else if(n)return Rfe(n,s)},has:function(s){if(b1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return xfe(e,s)}else if(S1){if(r)return Pfe(r,s)}else if(n)return Mfe(n,s);return!1},set:function(s,o){b1&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new b1),Nfe(e,s,o)):S1?(r||(r=new S1),Dfe(r,s,o)):(n||(n={key:{},next:null}),Bfe(n,s,o))}};return i}});var I1=D((W_e,A7)=>{"use strict";h();var Lfe=String.prototype.replace,Ffe=/%20/g,z2={RFC1738:"RFC1738",RFC3986:"RFC3986"};A7.exports={default:z2.RFC3986,formatters:{RFC1738:function(t){return Lfe.call(t,Ffe,"+")},RFC3986:function(t){return String(t)}},RFC1738:z2.RFC1738,RFC3986:z2.RFC3986}});var K2=D((Y_e,b7)=>{"use strict";h();var Ufe=I1(),Q2=Object.prototype.hasOwnProperty,yu=Array.isArray,bs=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),qfe=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(yu(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===Ufe.RFC1738&&(c===40||c===41)){u+=o.charAt(a);continue}if(c<128){u=u+bs[c];continue}if(c<2048){u=u+(bs[192|c>>6]+bs[128|c&63]);continue}if(c<55296||c>=57344){u=u+(bs[224|c>>12]+bs[128|c>>6&63]+bs[128|c&63]);continue}a+=1,c=65536+((c&1023)<<10|o.charCodeAt(a)&1023),u+=bs[240|c>>18]+bs[128|c>>12&63]+bs[128|c>>6&63]+bs[128|c&63]}return u},jfe=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";h();var T7=v7(),$2=K2(),md=I1(),$fe=Object.prototype.hasOwnProperty,S7={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},wu=Array.isArray,Yfe=String.prototype.split,Jfe=Array.prototype.push,_7=function(t,e){Jfe.apply(t,wu(e)?e:[e])},Xfe=Date.prototype.toISOString,I7=md.default,Or={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:$2.encode,encodeValuesOnly:!1,format:I7,formatter:md.formatters[I7],indices:!1,serializeDate:function(e){return Xfe.call(e)},skipNulls:!1,strictNullHandling:!1},Zfe=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},W2={},ehe=function t(e,r,n,i,s,o,u,a,c,f,d,w,A,T,x){for(var B=e,V=x,U=0,Q=!1;(V=V.get(W2))!==void 0&&!Q;){var L=V.get(e);if(U+=1,typeof L<"u"){if(L===U)throw new RangeError("Cyclic object value");Q=!0}typeof V.get(W2)>"u"&&(U=0)}if(typeof u=="function"?B=u(r,B):B instanceof Date?B=f(B):n==="comma"&&wu(B)&&(B=$2.maybeMap(B,function(I){return I instanceof Date?f(I):I})),B===null){if(i)return o&&!A?o(r,Or.encoder,T,"key",d):r;B=""}if(Zfe(B)||$2.isBuffer(B)){if(o){var k=A?r:o(r,Or.encoder,T,"key",d);if(n==="comma"&&A){for(var H=Yfe.call(String(B),","),q="",v=0;v"u")return C;var P;if(n==="comma"&&wu(B))P=[{value:B.length>0?B.join(",")||null:void 0}];else if(wu(u))P=u;else{var F=Object.keys(B);P=a?F.sort(a):F}for(var R=0;R"u"?Or.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Or.charsetSentinel,delimiter:typeof e.delimiter>"u"?Or.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Or.encode,encoder:typeof e.encoder=="function"?e.encoder:Or.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Or.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Or.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Or.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Or.strictNullHandling}};C7.exports=function(t,e){var r=t,n=the(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):wu(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var u;e&&e.arrayFormat in S7?u=e.arrayFormat:e&&"indices"in e?u=e.indices?"indices":"repeat":u="indices";var a=S7[u];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=T7(),f=0;f0?A+w:""}});var D7=D((e2e,O7)=>{"use strict";h();var xl=K2(),Y2=Object.prototype.hasOwnProperty,rhe=Array.isArray,Ir={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:xl.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},nhe=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},x7=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},ihe="utf8=%26%2310003%3B",she="utf8=%E2%9C%93",ohe=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),u=-1,a,c=r.charset;if(r.charsetSentinel)for(a=0;a-1&&(T=rhe(T)?[T]:T),Y2.call(n,A)?n[A]=xl.combine(n[A],T):n[A]=T}return n},ahe=function(t,e,r,n){for(var i=n?e:x7(e,r),s=t.length-1;s>=0;--s){var o,u=t[s];if(u==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var a=u.charAt(0)==="["&&u.charAt(u.length-1)==="]"?u.slice(1,-1):u,c=parseInt(a,10);!r.parseArrays&&a===""?o={0:i}:!isNaN(c)&&u!==a&&String(c)===a&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):a!=="__proto__"&&(o[a]=i)}i=o}return i},uhe=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,u=/(\[[^[\]]*])/g,a=n.depth>0&&o.exec(s),c=a?s.slice(0,a.index):s,f=[];if(c){if(!n.plainObjects&&Y2.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(a=u.exec(s))!==null&&d"u"?Ir.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?Ir.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:Ir.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:Ir.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:Ir.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ir.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:Ir.comma,decoder:typeof e.decoder=="function"?e.decoder:Ir.decoder,delimiter:typeof e.delimiter=="string"||xl.isRegExp(e.delimiter)?e.delimiter:Ir.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:Ir.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:Ir.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:Ir.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:Ir.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ir.strictNullHandling}};O7.exports=function(t,e){var r=che(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?ohe(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";h();var lhe=N7(),fhe=D7(),hhe=I1();P7.exports={formats:hhe,parse:fhe,stringify:lhe}});var J2=D(je=>{"use strict";h();Object.defineProperty(je,"__esModule",{value:!0});je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=je.WALLET_PROVIDER_CALLBACK_PARAM=je.WALLET_PROVIDER_SIGN_MESSAGE_URL=je.WALLET_PROVIDER_GUARD_TRANSACTION_URL=je.WALLET_PROVIDER_SIGN_TRANSACTION_URL=je.WALLET_PROVIDER_SEND_TRANSACTION_URL=je.WALLET_PROVIDER_DISCONNECT_URL=je.WALLET_PROVIDER_CONNECT_URL=je.XALIAS_PROVIDER_TESTNET=je.XALIAS_PROVIDER_DEVNET=je.XALIAS_PROVIDER_MAINNET=je.WALLET_PROVIDER_TESTNET=je.WALLET_PROVIDER_DEVNET=je.WALLET_PROVIDER_MAINNET=void 0;je.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";je.XALIAS_PROVIDER_MAINNET="https://xalias.com";je.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";je.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";je.WALLET_PROVIDER_CONNECT_URL="hook/login";je.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";je.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";je.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";je.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";je.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";je.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var B7=D(Ol=>{"use strict";h();Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrCannotSignedMessage=Ol.ErrCannotGetSignedTransactions=void 0;var X2=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Ol.ErrCannotGetSignedTransactions=X2;var Z2=class extends Error{constructor(){super("Cannot get signed message")}};Ol.ErrCannotSignedMessage=Z2});var M7=D(T1=>{"use strict";h();Object.defineProperty(T1,"__esModule",{value:!0});T1.PlainSignedTransaction=void 0;var eC=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};T1.PlainSignedTransaction=eC});var Dl=D(na=>{"use strict";h();var ta=na&&na.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},dhe=na&&na.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(na,"__esModule",{value:!0});na.WalletProvider=void 0;var tC=dhe(R7()),ra=J2(),rC=B7(),ghe=M7(),nC=class t{constructor(e){this.walletUrl=e}login(e){return ta(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ra.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return ta(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return ta(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return ta(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ra.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return ta(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:ra.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=tC.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new rC.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return ta(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ra.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return ta(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ra.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return ta(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(e=window.location.search){let r=tC.default.parse(e.slice(1));return t.isTxSignReturnSuccess(r)?this.getTxSignReturnValue(r):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(ra.WALLET_PROVIDER_CALLBACK_PARAM)&&e[ra.WALLET_PROVIDER_CALLBACK_PARAM]===ra.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new rC.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new rC.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let u=t.prepareWalletTransaction(o);for(let a in u)u.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(i[a]=[]),i[a].push(u[a])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};na.WalletProvider=nC});var p9=D((h2e,g9)=>{"use strict";h();function K7(t,e){return function(){return t.apply(e,arguments)}}var{toString:phe}=Object.prototype,{getPrototypeOf:pC}=Object,x1=(t=>e=>{let r=phe.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Is=t=>(t=t.toLowerCase(),e=>x1(e)===t),O1=t=>e=>typeof e===t,{isArray:Ml}=Array,wd=O1("undefined");function mhe(t){return t!==null&&!wd(t)&&t.constructor!==null&&!wd(t.constructor)&&ei(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var W7=Is("ArrayBuffer");function yhe(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&W7(t.buffer),e}var whe=O1("string"),ei=O1("function"),$7=O1("number"),D1=t=>t!==null&&typeof t=="object",vhe=t=>t===!0||t===!1,_1=t=>{if(x1(t)!=="object")return!1;let e=pC(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Ahe=Is("Date"),Ehe=Is("File"),bhe=Is("Blob"),She=Is("FileList"),Ihe=t=>D1(t)&&ei(t.pipe),The=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ei(t.append)&&((e=x1(t))==="formdata"||e==="object"&&ei(t.toString)&&t.toString()==="[object FormData]"))},_he=Is("URLSearchParams"),Che=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function vd(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ml(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var J7=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,X7=t=>!wd(t)&&t!==J7;function uC(){let{caseless:t}=X7(this)&&this||{},e={},r=(n,i)=>{let s=t&&Y7(e,i)||i;_1(e[s])&&_1(n)?e[s]=uC(e[s],n):_1(n)?e[s]=uC({},n):Ml(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(vd(e,(i,s)=>{r&&ei(i)?t[s]=K7(i,r):t[s]=i},{allOwnKeys:n}),t),xhe=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ohe=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},Dhe=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&pC(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},Phe=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},Rhe=t=>{if(!t)return null;if(Ml(t))return t;let e=t.length;if(!$7(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Bhe=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&pC(Uint8Array)),Mhe=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},Lhe=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Fhe=Is("HTMLFormElement"),Uhe=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),L7=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),qhe=Is("RegExp"),Z7=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};vd(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},Vhe=t=>{Z7(t,(e,r)=>{if(ei(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(ei(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},khe=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ml(t)?n(t):n(String(t).split(e)),r},Hhe=()=>{},Ghe=(t,e)=>(t=+t,Number.isFinite(t)?t:e),iC="abcdefghijklmnopqrstuvwxyz",F7="0123456789",e9={DIGIT:F7,ALPHA:iC,ALPHA_DIGIT:iC+iC.toUpperCase()+F7},jhe=(t=16,e=e9.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function zhe(t){return!!(t&&ei(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var Qhe=t=>{let e=new Array(10),r=(n,i)=>{if(D1(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ml(n)?[]:{};return vd(n,(o,u)=>{let a=r(o,i+1);!wd(a)&&(s[u]=a)}),e[i]=void 0,s}}return n};return r(t,0)},Khe=Is("AsyncFunction"),Whe=t=>t&&(D1(t)||ei(t))&&ei(t.then)&&ei(t.catch),re={isArray:Ml,isArrayBuffer:W7,isBuffer:mhe,isFormData:The,isArrayBufferView:yhe,isString:whe,isNumber:$7,isBoolean:vhe,isObject:D1,isPlainObject:_1,isUndefined:wd,isDate:Ahe,isFile:Ehe,isBlob:bhe,isRegExp:qhe,isFunction:ei,isStream:Ihe,isURLSearchParams:_he,isTypedArray:Bhe,isFileList:She,forEach:vd,merge:uC,extend:Nhe,trim:Che,stripBOM:xhe,inherits:Ohe,toFlatObject:Dhe,kindOf:x1,kindOfTest:Is,endsWith:Phe,toArray:Rhe,forEachEntry:Mhe,matchAll:Lhe,isHTMLForm:Fhe,hasOwnProperty:L7,hasOwnProp:L7,reduceDescriptors:Z7,freezeMethods:Vhe,toObjectSet:khe,toCamelCase:Uhe,noop:Hhe,toFiniteNumber:Ghe,findKey:Y7,global:J7,isContextDefined:X7,ALPHABET:e9,generateString:jhe,isSpecCompliantForm:zhe,toJSONObject:Qhe,isAsyncFn:Khe,isThenable:Whe};function Le(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}re.inherits(Le,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:re.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var t9=Le.prototype,r9={};["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(t=>{r9[t]={value:t}});Object.defineProperties(Le,r9);Object.defineProperty(t9,"isAxiosError",{value:!0});Le.from=(t,e,r,n,i,s)=>{let o=Object.create(t9);return re.toFlatObject(t,o,function(a){return a!==Error.prototype},u=>u!=="isAxiosError"),Le.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var $he=null;function cC(t){return re.isPlainObject(t)||re.isArray(t)}function n9(t){return re.endsWith(t,"[]")?t.slice(0,-2):t}function U7(t,e,r){return t?t.concat(e).map(function(i,s){return i=n9(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Yhe(t){return re.isArray(t)&&!t.some(cC)}var Jhe=re.toFlatObject(re,{},null,function(e){return/^is[A-Z]/.test(e)});function P1(t,e,r){if(!re.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=re.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,B){return!re.isUndefined(B[x])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,a=(r.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function c(T){if(T===null)return"";if(re.isDate(T))return T.toISOString();if(!a&&re.isBlob(T))throw new Le("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(T)||re.isTypedArray(T)?a&&typeof Blob=="function"?new Blob([T]):p.Buffer.from(T):T}function f(T,x,B){let V=T;if(T&&!B&&typeof T=="object"){if(re.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=JSON.stringify(T);else if(re.isArray(T)&&Yhe(T)||(re.isFileList(T)||re.endsWith(x,"[]"))&&(V=re.toArray(T)))return x=n9(x),V.forEach(function(Q,L){!(re.isUndefined(Q)||Q===null)&&e.append(o===!0?U7([x],L,s):o===null?x:x+"[]",c(Q))}),!1}return cC(T)?!0:(e.append(U7(B,x,s),c(T)),!1)}let d=[],w=Object.assign(Jhe,{defaultVisitor:f,convertValue:c,isVisitable:cC});function A(T,x){if(!re.isUndefined(T)){if(d.indexOf(T)!==-1)throw Error("Circular reference detected in "+x.join("."));d.push(T),re.forEach(T,function(V,U){(!(re.isUndefined(V)||V===null)&&i.call(e,V,re.isString(U)?U.trim():U,x,w))===!0&&A(V,x?x.concat(U):[U])}),d.pop()}}if(!re.isObject(t))throw new TypeError("data must be an object");return A(t),e}function q7(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function mC(t,e){this._pairs=[],t&&P1(t,this,e)}var i9=mC.prototype;i9.append=function(e,r){this._pairs.push([e,r])};i9.toString=function(e){let r=e?function(n){return e.call(this,n,q7)}:q7;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Xhe(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function s9(t,e,r){if(!e)return t;let n=r&&r.encode||Xhe,i=r&&r.serialize,s;if(i?s=i(e,r):s=re.isURLSearchParams(e)?e.toString():new mC(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var lC=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(n){n!==null&&e(n)})}},V7=lC,o9={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zhe=typeof URLSearchParams<"u"?URLSearchParams:mC,ede=typeof FormData<"u"?FormData:null,tde=typeof Blob<"u"?Blob:null,rde={isBrowser:!0,classes:{URLSearchParams:Zhe,FormData:ede,Blob:tde},protocols:["http","https","file","blob","url","data"]},a9=typeof window<"u"&&typeof document<"u",nde=(t=>a9&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),ide=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sde=Object.freeze({__proto__:null,hasBrowserEnv:a9,hasStandardBrowserWebWorkerEnv:ide,hasStandardBrowserEnv:nde}),Ss={...sde,...rde};function ode(t,e){return P1(t,new Ss.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Ss.isNode&&re.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function ade(t){return re.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function ude(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&re.isArray(i)?i.length:o,a?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&re.isArray(i[o])&&(i[o]=ude(i[o])),!u)}if(re.isFormData(t)&&re.isFunction(t.entries)){let r={};return re.forEachEntry(t,(n,i)=>{e(ade(n),i,r,0)}),r}return null}function cde(t,e,r){if(re.isString(t))try{return(e||JSON.parse)(t),re.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var yC={transitional:o9,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=re.isObject(e);if(s&&re.isHTMLForm(e)&&(e=new FormData(e)),re.isFormData(e))return i?JSON.stringify(u9(e)):e;if(re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e))return e;if(re.isArrayBufferView(e))return e.buffer;if(re.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return ode(e,this.formSerializer).toString();if((u=re.isFileList(e))||n.indexOf("multipart/form-data")>-1){let a=this.env&&this.env.FormData;return P1(u?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),cde(e)):e}],transformResponse:[function(e){let r=this.transitional||yC.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&re.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?Le.from(u,Le.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ss.classes.FormData,Blob:Ss.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],t=>{yC.headers[t]={}});var wC=yC,lde=re.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"]),fde=t=>{let e={},r,n,i;return t&&t.split(` +`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&lde[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},k7=Symbol("internals");function yd(t){return t&&String(t).trim().toLowerCase()}function C1(t){return t===!1||t==null?t:re.isArray(t)?t.map(C1):String(t)}function hde(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var dde=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function sC(t,e,r,n,i){if(re.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function gde(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function pde(t,e){let r=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Pl=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,a,c){let f=yd(a);if(!f)throw new Error("header name must be a non-empty string");let d=re.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||a]=C1(u))}let o=(u,a)=>re.forEach(u,(c,f)=>s(c,f,a));return re.isPlainObject(e)||e instanceof this.constructor?o(e,r):re.isString(e)&&(e=e.trim())&&!dde(e)?o(fde(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=yd(e),e){let n=re.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return hde(i);if(re.isFunction(r))return r.call(this,i,n);if(re.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=yd(e),e){let n=re.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||sC(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=yd(o),o){let u=re.findKey(n,o);u&&(!r||sC(n,n[u],u,r))&&(delete n[u],i=!0)}}return re.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||sC(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return re.forEach(this,(i,s)=>{let o=re.findKey(n,s);if(o){r[o]=C1(i),delete r[s];return}let u=e?gde(s):String(s).trim();u!==s&&delete r[s],r[u]=C1(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return re.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&re.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[k7]=this[k7]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=yd(o);n[u]||(pde(i,o),n[u]=!0)}return re.isArray(e)?e.forEach(s):s(e),this}};Pl.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);re.reduceDescriptors(Pl.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});re.freezeMethods(Pl);var ro=Pl;function oC(t,e){let r=this||wC,n=e||r,i=ro.from(n.headers),s=n.data;return re.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function c9(t){return!!(t&&t.__CANCEL__)}function Ad(t,e,r){Le.call(this,t??"canceled",Le.ERR_CANCELED,e,r),this.name="CanceledError"}re.inherits(Ad,Le,{__CANCEL__:!0});function mde(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Le("Request failed with status code "+r.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var yde=Ss.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];re.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),re.isString(n)&&o.push("path="+n),re.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function wde(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function vde(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function l9(t,e){return t&&!wde(e)?vde(t,e):e}var Ade=Ss.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=re.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function Ede(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function bde(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(a){let c=Date.now(),f=n[s];o||(o=c),r[i]=a,n[i]=c;let d=s,w=0;for(;d!==i;)w+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,a=n(u),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:a||void 0,estimated:a&&o&&c?(o-s)/a:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var Sde=typeof XMLHttpRequest<"u",Ide=Sde&&function(t){return new Promise(function(r,n){let i=t.data,s=ro.from(t.headers).normalize(),{responseType:o,withXSRFToken:u}=t,a;function c(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}let f;if(re.isFormData(i)){if(Ss.hasStandardBrowserEnv||Ss.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[x,...B]=f?f.split(";").map(V=>V.trim()).filter(Boolean):[];s.setContentType([x||"multipart/form-data",...B].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let x=t.auth.username||"",B=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(x+":"+B))}let w=l9(t.baseURL,t.url);d.open(t.method.toUpperCase(),s9(w,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function A(){if(!d)return;let x=ro.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),V={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:x,config:t,request:d};mde(function(Q){r(Q),c()},function(Q){n(Q),c()},V),d=null}if("onloadend"in d?d.onloadend=A:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(A)},d.onabort=function(){d&&(n(new Le("Request aborted",Le.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Le("Network Error",Le.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let B=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||o9;t.timeoutErrorMessage&&(B=t.timeoutErrorMessage),n(new Le(B,V.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,t,d)),d=null},Ss.hasStandardBrowserEnv&&(u&&re.isFunction(u)&&(u=u(t)),u||u!==!1&&Ade(w))){let x=t.xsrfHeaderName&&t.xsrfCookieName&&yde.read(t.xsrfCookieName);x&&s.set(t.xsrfHeaderName,x)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&re.forEach(s.toJSON(),function(B,V){d.setRequestHeader(V,B)}),re.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",H7(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",H7(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=x=>{d&&(n(!x||x.type?new Ad(null,t,d):x),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));let T=Ede(w);if(T&&Ss.protocols.indexOf(T)===-1){n(new Le("Unsupported protocol "+T+":",Le.ERR_BAD_REQUEST,t));return}d.send(i||null)})},fC={http:$he,xhr:Ide};re.forEach(fC,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var G7=t=>`- ${t}`,Tde=t=>re.isFunction(t)||t===null||t===!1,f9={getAdapter:t=>{t=re.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${u} `+(a===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : +`+s.map(G7).join(` +`):" "+G7(s[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:fC};function aC(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Ad(null,t)}function j7(t){return aC(t),t.headers=ro.from(t.headers),t.data=oC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),f9.getAdapter(t.adapter||wC.adapter)(t).then(function(n){return aC(t),n.data=oC.call(t,t.transformResponse,n),n.headers=ro.from(n.headers),n},function(n){return c9(n)||(aC(t),n&&n.response&&(n.response.data=oC.call(t,t.transformResponse,n.response),n.response.headers=ro.from(n.response.headers))),Promise.reject(n)})}var z7=t=>t instanceof ro?{...t}:t;function Rl(t,e){e=e||{};let r={};function n(c,f,d){return re.isPlainObject(c)&&re.isPlainObject(f)?re.merge.call({caseless:d},c,f):re.isPlainObject(f)?re.merge({},f):re.isArray(f)?f.slice():f}function i(c,f,d){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!re.isUndefined(f))return n(void 0,f)}function o(c,f){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function u(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let 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:u,headers:(c,f)=>i(z7(c),z7(f),!0)};return re.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=a[f]||i,w=d(t[f],e[f],f);re.isUndefined(w)&&d!==u||(r[f]=w)}),r}var h9="1.6.8",vC={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{vC[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var Q7={};vC.transitional=function(e,r,n){function i(s,o){return"[Axios v"+h9+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new Le(i(o," has been removed"+(r?" in "+r:"")),Le.ERR_DEPRECATED);return r&&!Q7[o]&&(Q7[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function _de(t,e,r){if(typeof t!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],a=u===void 0||o(u,s,t);if(a!==!0)throw new Le("option "+s+" must be "+a,Le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}var hC={assertOptions:_de,validators:vC},ia=hC.validators,Bl=class{constructor(e){this.defaults=e,this.interceptors={request:new V7,response:new V7}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` +`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Rl(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&hC.assertOptions(n,{silentJSONParsing:ia.transitional(ia.boolean),forcedJSONParsing:ia.transitional(ia.boolean),clarifyTimeoutError:ia.transitional(ia.boolean)},!1),i!=null&&(re.isFunction(i)?r.paramsSerializer={serialize:i}:hC.assertOptions(i,{encode:ia.function,serialize:ia.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&re.merge(s.common,s[r.method]);s&&re.forEach(["delete","get","head","post","put","patch","common"],T=>{delete s[T]}),r.headers=ro.concat(o,s);let u=[],a=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(r)===!1||(a=a&&x.synchronous,u.unshift(x.fulfilled,x.rejected))});let c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let f,d=0,w;if(!a){let T=[j7.bind(this),void 0];for(T.unshift.apply(T,u),T.push.apply(T,c),w=T.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new Ad(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},Cde=dC;function Nde(t){return function(r){return t.apply(null,r)}}function xde(t){return re.isObject(t)&&t.isAxiosError===!0}var gC={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(gC).forEach(([t,e])=>{gC[e]=t});var Ode=gC;function d9(t){let e=new N1(t),r=K7(N1.prototype.request,e);return re.extend(r,N1.prototype,e,{allOwnKeys:!0}),re.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return d9(Rl(t,i))},r}var cr=d9(wC);cr.Axios=N1;cr.CanceledError=Ad;cr.CancelToken=Cde;cr.isCancel=c9;cr.VERSION=h9;cr.toFormData=P1;cr.AxiosError=Le;cr.Cancel=cr.CanceledError;cr.all=function(e){return Promise.all(e)};cr.spread=Nde;cr.isAxiosError=xde;cr.mergeConfig=Rl;cr.AxiosHeaders=ro;cr.formToJSON=t=>u9(re.isHTMLForm(t)?new FormData(t):t);cr.getAdapter=f9.getAdapter;cr.HttpStatusCode=Ode;cr.default=cr;g9.exports=cr});var m9=D(R1=>{"use strict";h();Object.defineProperty(R1,"__esModule",{value:!0});R1.NativeAuthClientConfig=void 0;var AC=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};R1.NativeAuthClientConfig=AC});var bC=D(Ll=>{"use strict";h();var vu=Ll&&Ll.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.NativeAuthClient=void 0;var Dde=p9(),Pde=m9(),EC=class{constructor(e){this.config=Object.assign(new Pde.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vu(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vu(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vu(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vu(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vu(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vu(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(p.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vu(this,void 0,void 0,function*(){return yield Dde.default.get(e,{headers:this.config.extraRequestHeaders})})}};Ll.NativeAuthClient=EC});var A9=D(M1=>{"use strict";h();Object.defineProperty(M1,"__esModule",{value:!0});M1.TransactionStatus=void 0;var IC=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};M1.TransactionStatus=IC});var b9=D(L1=>{"use strict";h();Object.defineProperty(L1,"__esModule",{value:!0});L1.TransactionReceipt=void 0;var E9=_c(),TC=class t{constructor(){this.value="",this.sender=new E9.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new E9.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};L1.TransactionReceipt=TC});var S9=D(Ts=>{"use strict";h();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ErrContractQuery=Ts.ErrNetworkProvider=Ts.ErrUnexpectedCondition=Ts.Err=void 0;var Ul=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ts.Err=Ul;var _C=class extends Ul{constructor(e){super(`Unexpected condition: [${e}]`)}};Ts.ErrUnexpectedCondition=_C;var CC=class extends Ul{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Ts.ErrNetworkProvider=CC;var NC=class extends Ul{constructor(e){super(e.message.replace("executeQuery:",""))}};Ts.ErrContractQuery=NC});var T9=D(sa=>{"use strict";h();Object.defineProperty(sa,"__esModule",{value:!0});sa.TransactionEventTopic=sa.TransactionEventData=sa.TransactionEvent=void 0;var I9=_c(),xC=class t{constructor(e){this.address=new I9.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new ql(p.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new I9.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new F1(n)),r.dataPayload=ql.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(ql.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};sa.TransactionEvent=xC;var ql=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(p.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};sa.TransactionEventData=ql;var F1=class{constructor(e){this.raw=p.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};sa.TransactionEventTopic=F1});var DC=D(U1=>{"use strict";h();Object.defineProperty(U1,"__esModule",{value:!0});U1.TransactionLogs=void 0;var Mde=S9(),_9=_c(),Lde=T9(),OC=class t{constructor(e){this.address=new _9.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new _9.Address(e.address),r.events=(e.events||[]).map(n=>Lde.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new Mde.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};U1.TransactionLogs=OC});var N9=D(Vl=>{"use strict";h();Object.defineProperty(Vl,"__esModule",{value:!0});Vl.ContractResultItem=Vl.ContractResults=void 0;var C9=DC(),q1=_c(),PC=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>Ed.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>Ed.fromApiHttpResponse(n));return new t(r)}};Vl.ContractResults=PC;var Ed=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new q1.Address(""),this.sender=new q1.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new C9.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=p.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new q1.Address(e.receiver),r.sender=new q1.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=C9.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Vl.ContractResultItem=Ed});var x9=D(V1=>{"use strict";h();Object.defineProperty(V1,"__esModule",{value:!0});V1.ContractQueryRequest=void 0;var RC=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};V1.ContractQueryRequest=RC});var k9=D((pCe,V9)=>{h();V9.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var oa=D(Eu=>{h();var BC,Fde=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Eu.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Eu.getSymbolTotalCodewords=function(e){return Fde[e]};Eu.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Eu.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');BC=e};Eu.isKanjiModeEnabled=function(){return typeof BC<"u"};Eu.toSJIS=function(e){return BC(e)}});var j1=D(ti=>{h();ti.L={bit:1};ti.M={bit:0};ti.Q={bit:3};ti.H={bit:2};function Ude(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ti.L;case"m":case"medium":return ti.M;case"q":case"quartile":return ti.Q;case"h":case"high":return ti.H;default:throw new Error("Unknown EC Level: "+t)}}ti.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ti.from=function(e,r){if(ti.isValid(e))return e;try{return Ude(e)}catch{return r}}});var j9=D((ECe,G9)=>{h();function H9(){this.buffer=[],this.length=0}H9.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};G9.exports=H9});var Q9=D((SCe,z9)=>{h();function bd(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}bd.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};bd.prototype.get=function(t,e){return this.data[t*this.size+e]};bd.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};bd.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};z9.exports=bd});var K9=D(z1=>{h();var qde=oa().getSymbolSize;z1.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=qde(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{h();var Vde=oa().getSymbolSize,W9=7;$9.getPositions=function(e){let r=Vde(e);return[[0,0],[r-W9,0],[0,r-W9]]}});var J9=D(Rt=>{h();Rt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bu={N1:3,N2:3,N3:40,N4:10};Rt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Rt.from=function(e){return Rt.isValid(e)?parseInt(e,10):void 0};Rt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,u=null;for(let a=0;a=5&&(n+=bu.N1+(i-5)),o=f,i=1),f=e.get(c,a),f===u?s++:(s>=5&&(n+=bu.N1+(s-5)),u=f,s=1)}i>=5&&(n+=bu.N1+(i-5)),s>=5&&(n+=bu.N1+(s-5))}return n};Rt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(u,o),u>=10&&(s===1488||s===93)&&n++}return n*bu.N3};Rt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{h();var aa=j1(),Q1=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],K1=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];MC.getBlocksCount=function(e,r){switch(r){case aa.L:return Q1[(e-1)*4+0];case aa.M:return Q1[(e-1)*4+1];case aa.Q:return Q1[(e-1)*4+2];case aa.H:return Q1[(e-1)*4+3];default:return}};MC.getTotalCodewordsCount=function(e,r){switch(r){case aa.L:return K1[(e-1)*4+0];case aa.M:return K1[(e-1)*4+1];case aa.Q:return K1[(e-1)*4+2];case aa.H:return K1[(e-1)*4+3];default:return}}});var X9=D($1=>{h();var Sd=new Uint8Array(512),W1=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Sd[r]=e,W1[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Sd[r]=Sd[r-255]})();$1.log=function(e){if(e<1)throw new Error("log("+e+")");return W1[e]};$1.exp=function(e){return Sd[e]};$1.mul=function(e,r){return e===0||r===0?0:Sd[W1[e]+W1[r]]}});var Z9=D(Id=>{h();var FC=X9();Id.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{h();var eV=Z9();function UC(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}UC.prototype.initialize=function(e){this.degree=e,this.genPoly=eV.generateECPolynomial(this.degree)};UC.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=eV.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};tV.exports=UC});var qC=D(nV=>{h();nV.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var VC=D(no=>{h();var iV="[0-9]+",Hde="[A-Z $%*+\\-./:]+",Td="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Td=Td.replace(/u/g,"\\u");var Gde="(?:(?![A-Z0-9 $%*+\\-./:]|"+Td+`)(?:.|[\r +]))+`;no.KANJI=new RegExp(Td,"g");no.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");no.BYTE=new RegExp(Gde,"g");no.NUMERIC=new RegExp(iV,"g");no.ALPHANUMERIC=new RegExp(Hde,"g");var jde=new RegExp("^"+Td+"$"),zde=new RegExp("^"+iV+"$"),Qde=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");no.testKanji=function(e){return jde.test(e)};no.testNumeric=function(e){return zde.test(e)};no.testAlphanumeric=function(e){return Qde.test(e)}});var ua=D(lr=>{h();var Kde=qC(),kC=VC();lr.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};lr.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};lr.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};lr.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};lr.MIXED={bit:-1};lr.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Kde.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};lr.getBestModeForData=function(e){return kC.testNumeric(e)?lr.NUMERIC:kC.testAlphanumeric(e)?lr.ALPHANUMERIC:kC.testKanji(e)?lr.KANJI:lr.BYTE};lr.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};lr.isValid=function(e){return e&&e.bit&&e.ccBits};function Wde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return lr.NUMERIC;case"alphanumeric":return lr.ALPHANUMERIC;case"kanji":return lr.KANJI;case"byte":return lr.BYTE;default:throw new Error("Unknown mode: "+t)}}lr.from=function(e,r){if(lr.isValid(e))return e;try{return Wde(e)}catch{return r}}});var cV=D(Su=>{h();var Y1=oa(),$de=LC(),sV=j1(),ca=ua(),HC=qC(),aV=7973,oV=Y1.getBCHDigit(aV);function Yde(t,e,r){for(let n=1;n<=40;n++)if(e<=Su.getCapacity(n,r,t))return n}function uV(t,e){return ca.getCharCountIndicator(t,e)+4}function Jde(t,e){let r=0;return t.forEach(function(n){let i=uV(n.mode,e);r+=i+n.getBitsLength()}),r}function Xde(t,e){for(let r=1;r<=40;r++)if(Jde(t,r)<=Su.getCapacity(r,e,ca.MIXED))return r}Su.from=function(e,r){return HC.isValid(e)?parseInt(e,10):r};Su.getCapacity=function(e,r,n){if(!HC.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=ca.BYTE);let i=Y1.getSymbolTotalCodewords(e),s=$de.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===ca.MIXED)return o;let u=o-uV(n,e);switch(n){case ca.NUMERIC:return Math.floor(u/10*3);case ca.ALPHANUMERIC:return Math.floor(u/11*2);case ca.KANJI:return Math.floor(u/13);case ca.BYTE:default:return Math.floor(u/8)}};Su.getBestVersionForData=function(e,r){let n,i=sV.from(r,sV.M);if(Array.isArray(e)){if(e.length>1)return Xde(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Yde(n.mode,n.getLength(),i)};Su.getEncodedBits=function(e){if(!HC.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Y1.getBCHDigit(r)-oV>=0;)r^=aV<{h();var GC=oa(),fV=1335,Zde=21522,lV=GC.getBCHDigit(fV);hV.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;GC.getBCHDigit(i)-lV>=0;)i^=fV<{h();var ege=ua();function Hl(t){this.mode=ege.NUMERIC,this.data=t.toString()}Hl.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Hl.prototype.getLength=function(){return this.data.length};Hl.prototype.getBitsLength=function(){return Hl.getBitsLength(this.data.length)};Hl.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};gV.exports=Hl});var yV=D((JCe,mV)=>{h();var tge=ua(),jC=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Gl(t){this.mode=tge.ALPHANUMERIC,this.data=t}Gl.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Gl.prototype.getLength=function(){return this.data.length};Gl.prototype.getBitsLength=function(){return Gl.getBitsLength(this.data.length)};Gl.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=jC.indexOf(this.data[r])*45;n+=jC.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(jC.indexOf(this.data[r]),6)};mV.exports=Gl});var vV=D((ZCe,wV)=>{"use strict";h();wV.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var EV=D((t3e,AV)=>{h();var rge=vV(),nge=ua();function jl(t){this.mode=nge.BYTE,typeof t=="string"&&(t=rge(t)),this.data=new Uint8Array(t)}jl.getBitsLength=function(e){return e*8};jl.prototype.getLength=function(){return this.data.length};jl.prototype.getBitsLength=function(){return jl.getBitsLength(this.data.length)};jl.prototype.write=function(t){for(let e=0,r=this.data.length;e{h();var ige=ua(),sge=oa();function zl(t){this.mode=ige.KANJI,this.data=t}zl.getBitsLength=function(e){return e*13};zl.prototype.getLength=function(){return this.data.length};zl.prototype.getBitsLength=function(){return zl.getBitsLength(this.data.length)};zl.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` +Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};bV.exports=zl});var IV=D((s3e,zC)=>{"use strict";h();var _d={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=_d.PriorityQueue.make();s.push(e,0);for(var o,u,a,c,f,d,w,A,T;!s.empty();){o=s.pop(),u=o.value,c=o.cost,f=t[u]||{};for(a in f)f.hasOwnProperty(a)&&(d=f[a],w=c+d,A=i[a],T=typeof i[a]>"u",(T||A>w)&&(i[a]=w,s.push(a,w),n[a]=u))}if(typeof r<"u"&&typeof i[r]>"u"){var x=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(x)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=_d.single_source_shortest_paths(t,e,r);return _d.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=_d.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof zC<"u"&&(zC.exports=_d)});var PV=D(Ql=>{h();var ze=ua(),CV=pV(),NV=yV(),xV=EV(),OV=SV(),Cd=VC(),J1=oa(),oge=IV();function TV(t){return unescape(encodeURIComponent(t)).length}function Nd(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function DV(t){let e=Nd(Cd.NUMERIC,ze.NUMERIC,t),r=Nd(Cd.ALPHANUMERIC,ze.ALPHANUMERIC,t),n,i;return J1.isKanjiModeEnabled()?(n=Nd(Cd.BYTE,ze.BYTE,t),i=Nd(Cd.KANJI,ze.KANJI,t)):(n=Nd(Cd.BYTE_KANJI,ze.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,u){return o.index-u.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function QC(t,e){switch(e){case ze.NUMERIC:return CV.getBitsLength(t);case ze.ALPHANUMERIC:return NV.getBitsLength(t);case ze.KANJI:return OV.getBitsLength(t);case ze.BYTE:return xV.getBitsLength(t)}}function age(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function uge(t){let e=[];for(let r=0;r{h();var Z1=oa(),KC=j1(),lge=j9(),fge=Q9(),hge=K9(),dge=Y9(),YC=J9(),JC=LC(),gge=rV(),X1=cV(),pge=dV(),mge=ua(),WC=PV();function yge(t,e){let r=t.size,n=dge.getPositions(e);for(let i=0;i=0&&u<=6&&(a===0||a===6)||a>=0&&a<=6&&(u===0||u===6)||u>=2&&u<=4&&a>=2&&a<=4?t.set(s+u,o+a,!0,!0):t.set(s+u,o+a,!1,!0))}}function wge(t){let e=t.size;for(let r=8;r>u&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function $C(t,e,r){let n=t.size,i=pge.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function Ege(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let u=r-1;u>0;u-=2)for(u===6&&u--;;){for(let a=0;a<2;a++)if(!t.isReserved(i,u-a)){let c=!1;o>>s&1)===1),t.set(i,u-a,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function bge(t,e,r){let n=new lge;r.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),mge.getCharCountIndicator(a.mode,t)),a.write(n)});let i=Z1.getSymbolTotalCodewords(t),s=JC.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let u=(o-n.getLengthInBits())/8;for(let a=0;a=7&&ege(a,e),tge(a,o),isNaN(n)&&(n=JC.getBestMask(a,YC.bind(null,a,r))),JC.applyMask(n,a),YC(a,r,n),{modules:a,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}wV.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=WC.M,i,s;return typeof r<"u"&&(n=WC.from(r.errorCorrectionLevel,WC.M),i=J1.from(r.version),s=JC.from(r.maskPattern),r.toSJISFunc&&X1.setToSJISFunction(r.toSJISFunc)),ige(e,i,n,s)}});var ZC=B(Iu=>{h();function AV(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Iu.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:AV(e.color.dark||"#000000ff"),light:AV(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Iu.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Iu.getImageWidth=function(e,r){let n=Iu.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Iu.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Iu.getScale(i,n),u=Math.floor((i+n.margin*2)*o),a=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=a&&d>=a&&f{h();var e3=ZC();function sge(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function oge(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Z1.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=oge()),i=e3.getOptions(i);let o=e3.getImageWidth(e.modules.size,i),u=s.getContext("2d"),a=u.createImageData(o,o);return e3.qrToImageData(a.data,e,i),sge(u,s,o),u.putImageData(a,0,0),s};Z1.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Z1.render(e,r,i),o=i.type||"image/png",u=i.rendererOpts||{};return s.toDataURL(o,u.quality)}});var IV=B(SV=>{h();var age=ZC();function bV(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function t3(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function uge(t,e,r){let n="",i=0,s=!1,o=0;for(let u=0;u0&&a>0&&t[u-1]||(n+=s?t3("M",a+r,.5+c+r):t3("m",i,0),i=0,s=!1),a+1':"",c="',f='viewBox="0 0 '+u+" "+u+'"',w=''+a+c+` -`;return typeof n=="function"&&n(null,w),w}});var _V=B(Dd=>{h();var cge=_9(),r3=vV(),TV=EV(),lge=IV();function n3(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,u=typeof s[o-1]=="function";if(!u&&!cge())throw new Error("Callback required as last argument");if(u){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(a,c){try{let f=r3.create(r,n);a(t(f,e,n))}catch(f){c(f)}})}try{let a=r3.create(r,n);i(null,t(a,e,n))}catch(a){i(a)}}Dd.create=r3.create;Dd.toCanvas=n3.bind(null,TV.render);Dd.toDataURL=n3.bind(null,TV.renderToDataURL);Dd.toString=n3.bind(null,function(t,e,r){return lge.render(t,r)})});var FV=B(fa=>{"use strict";h();var Ege=fa&&fa.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LV=fa&&fa.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ege(e,t,r)};Object.defineProperty(fa,"__esModule",{value:!0});LV(Dl(),fa);LV(X2(),fa)});h();var d3=pe(Ca(),1),g3=pe(_b(),1),fw=pe(d0(),1),p3=pe(Db(),1),_ge=pe(Ve(),1),Cge=pe(Ic(),1),Nge=pe(Xr(),1),xge=pe(N0(),1),sk=pe(Bb(),1),Oge=pe(V0(),1),Dge=pe(H0(),1),ok=pe(po(),1),_s=pe(Mf(),1),ak=pe(yf(),1),uk=pe(Yu(),1),Pge=pe(CE(),1),Rge=pe(jb(),1);h();h();var U8=pe(Kb(),1);h();h();var G0="elvenjs_state",M8="https://devnet-api.multiversx.com";var Po="/dapp/init",j0="devnet",L8="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",F8=["wss://relay.walletconnect.com"],Rr={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var me={get(t){let e=localStorage.getItem(G0);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem(G0,JSON.stringify(r))},clear(){localStorage.removeItem(G0)}};var z0=async()=>{let t=U8.ExtensionProvider.getInstance();try{let e=await t.init(),r=me.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var c3=pe(Kb(),1),l3=pe(fd(),1),f3=pe(Dl(),1),ik=pe(SC(),1),lw=pe(H0(),1);h();var n9=pe(fd(),1);h();h();var ge=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};h();var r9=(U=>(U.onLoginStart="onLoginStart",U.onLoginSuccess="onLoginSuccess",U.onLoginFailure="onLoginFailure",U.onLogoutStart="onLogoutStart",U.onLogoutSuccess="onLogoutSuccess",U.onLogoutFailure="onLogoutFailure",U.onQrPending="onQrPending",U.onQrLoaded="onQrLoaded",U.onTxStart="onTxStart",U.onTxSent="onTxSent",U.onTxFinalized="onTxFinalized",U.onTxFailure="onTxFailure",U.onSignMsgStart="onSignMsgStart",U.onSignMsgFinalized="onSignMsgFinalized",U.onSignMsgFailure="onSignMsgFailure",U.onQueryStart="onQueryStart",U.onQueryFinalized="onQueryFinalized",U.onQueryFailure="onQueryFailure",U))(r9||{}),IC=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(IC||{}),dde=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(dde||{}),gde=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(gde||{});h();var Kt=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Fl=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");ge.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(me.clear(),ge.run("onLogoutSuccess")),e}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to logout the user: ${r}`),ge.run("onLogoutFailure",r)}};h();function R1(t){return t[Math.floor(Math.random()*t.length)]}var i9=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Fl(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=R1(t.initOptions.walletConnectV2RelayAddresses),n=new n9.WalletConnectV2Provider(e,Rr[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};h();var V1=pe(Ve(),1),p9=pe(s9(),1),m9=pe(a9(),1),y9=pe(PC(),1),w9=pe(d9(),1),v9=pe(jb(),1),A9=pe(g9(),1),E9=pe(Wf(),1);var k1=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||j0,this.apiUrl=e||Rr[this.chainType]?.apiAddress,this.apiTimeout=n||Rr[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),u=await o.json();if(!o.ok){let a=u?.error||o.status;return clearTimeout(i),Promise.reject(a)}return clearTimeout(i),u}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let u=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),a=await u.json();if(!u.ok){let c=a?.error||u.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),a}catch(u){this.handleApiError(u,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new V1.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new p9.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new V1.Address(r.sender),receiver:new V1.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:p.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:m9.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:y9.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:w9.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new E9.Query({address:e,func:r,args:n,value:i,caller:s}),u=new A9.ContractQueryRequest(o).toHttpRequest(),a=await this.apiPost("query",u);return v9.ContractQueryResponse.fromHttpResponse(a)}catch(o){this.handleApiError(o,"query")}}};h();h();var kl=()=>new Date().setHours(new Date().getHours()+24),H1=t=>Date.now()>t;h();var b9=pe(Ve(),1),S9=pe(Ic(),1);var Au=async t=>{let e=me.get("address"),r=me.get("expires");if(!(r&&H1(r))&&e&&t.networkProvider){let i=new b9.Address(e),s=new S9.Account(i);try{let o=await t.networkProvider.getAccount(i),u=await t.networkProvider.getGuardianData(i);me.set("address",e),me.set("activeGuardian",u.guarded&&u.activeGuardian?.address?u.activeGuardian.address:""),me.set("nonce",o.nonce.valueOf()),me.set("balance",o.balance.toString()),s.update(o)}catch(o){let u=Kt(o);console.warn(`Something went wrong trying to synchronize the user account: ${u}`)}}};var I9=async(t,e,r,n="/")=>{let i=await z0(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(a){let c=Kt(a);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:u}=i.account;if(me.set("loginToken",e),u&&me.set("signature",u),t.networkProvider&&u)try{let a=await i.getAddress();if(!a)throw new Error("Canceled!");me.set("address",a),me.set("loginMethod","browser-extension"),me.set("expires",kl()),await Au(t);let c=r.getToken(a,e,u);return me.set("accessToken",c),ge.run("onLoginSuccess"),i}catch(a){throw new Error(`Something went wrong trying to synchronize the user account: ${a?.message}`)}};h();h();var CV=pe(_V(),1),NV=pe(fd(),1);var fge=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},hge=t=>{let e=`${L8}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},dge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},gge=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},i3={},pge=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",i3[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:i3[t.topic].signal}),r},ew={},mge=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=pge(t,e);return n.appendChild(s),ew[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:ew[t.topic].signal}),n},yge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},wge=t=>{if(!t)return;document.getElementById(t)?.remove()},vge=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),Age=async t=>t?await CV.default.toString(t,{type:"svg"}):void 0,xV=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await Age(e),o;if(s&&(o=fge(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),vge()&&i.appendChild(hge(e))),i&&r instanceof NV.WalletConnectV2Provider){let u=r.pairings,a=async f=>{try{f&&(await r.logout({topic:f}),wge(f))}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to remove the existing pairing: ${w}`)}finally{ew[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(yge()),await r.login({approval:d,token:n})}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to login the user: ${w}`)}finally{for(let d of Object.values(ew))d?.abort();for(let d of Object.values(i3))d?.abort()}};if(u&&u.length>0){let f=dge();i.appendChild(f);let d=gge();f.appendChild(d);for(let w of u){let A=mge(w,a,c);f.appendChild(A)}}}return i};var tw=pe(fd(),1);var OV=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=R1(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof tw.WalletConnectV2Provider){let a=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();me.set("address",a),me.set("loginMethod","mobile"),me.set("expires",kl()),await Au(t),c&&me.set("signature",c),me.set("loginToken",e);let f=r.getToken(a,e,c);me.set("accessToken",f),ge.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof tw.WalletConnectV2Provider&&await Fl(t)},onClientEvent:a=>{console.log("wc2 session event: ",a)}},u=new tw.WalletConnectV2Provider(o,Rr[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(u){t.dappProvider=u,ge.run("onQrPending"),await u.init();let{uri:a,approval:c}=await u.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${a}&token=${e}`:a;return n&&f&&(s=await xV(n,f,u,e),ge.run("onQrLoaded")),await u.login({approval:c,token:e}),u}}catch(a){let c=Kt(a);console.warn(`Something went wrong trying to login the user: ${c}`),ge.run("onLoginFailure",c)}};h();var DV=pe(Dl(),1);var s3=async(t,e,r,n)=>{let i=new DV.WalletProvider(`${t}${Po}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return me.set("loginMethod",Rr[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),me.set("expires",kl()),me.set("loginToken",e),i}catch(u){let a=Kt(u);console.warn(`Something went wrong trying to login the user: ${a}`),me.set("loginMethod",""),ge.run("onLoginFailure",a)}};h();var ln=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};h();var PV=pe(Dl(),1);var RV=pe(SC(),1),o3=async(t,e)=>{let r=ln("signature"),n=ln("address"),i=me.get("address"),s=me.get("loginToken");if(r&&me.set("signature",r),n||i){n&&(me.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new PV.WalletProvider(`${t}${Po}`);if(r&&e&&n){let a=new RV.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);me.set("accessToken",a)}return o}};h();var BV=pe(Ic(),1),MV=pe(V0(),1);var rw=async(t,e)=>{ge.run("onTxSent",t);let n=await new MV.TransactionWatcher(e).awaitCompleted(t),i=n.sender,s=new BV.Account(i),o=await e.getAccount(i);s.update(o),me.set("address",s.address.bech32()),me.set("balance",s.balance.toString()),ge.run("onTxFinalized",n)};h();var Kl=pe(FV(),1),qV=pe(Xr(),1);h();var UV=pe(Ic(),1);var nw=t=>{let e=t.getSender(),r=new UV.Account(e),n=t.nonce.valueOf();r.incrementNonce(),me.set("nonce",(n+1n).toString())};var VV=async(t,e,r,n)=>{if(ln(Kl.WALLET_PROVIDER_CALLBACK_PARAM)===Kl.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=me.get("activeGuardian"),o=me.get("loginMethod"),u=ln("hasWebWalletGuardianSign"),a;if("getTransactionsFromWalletUrl"in t){if(a=t.getTransactionsFromWalletUrl()?.[0],!a)return;o==="web-wallet"&&(a.data=p.Buffer.from(a.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&u&&(a=new Kl.WalletProvider(`${r}${Po}`).getTransactionsFromWalletUrl()?.[0]);if(a){let c=qV.Transaction.fromPlainObject(a);c.nonce=BigInt(n),nw(c);try{ge.run("onTxStart",c),await e.sendTransaction(c),await rw(c,e)}catch(f){let w=`Getting transaction information failed! ${Kt(f)}`;throw ge.run("onTxFailure",c,w),new Error(w)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};h();var iw=pe($l(),1),kV=pe(Ve(),1),HV=pe(Dl(),1);var GV=t=>{let e=me.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(iw.TransactionVersion.withTxOptions()),t.setOptions(iw.TransactionOptions.withOptions(r)),t.setGuardian(kV.Address.fromBech32(e))}return t},jV=async(t,e)=>{let r=new HV.WalletProvider(`${e}${Po}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},zV=t=>{let e=me.get("activeGuardian");return!(!me.get("address")||!e||t.isGuardedTransaction())};h();var QV=()=>{let t=!ln("walletProviderStatus"),e=ln("status")==="signed",r=ln("message"),n=ln("signature");t&&e&&r&&n&&(ge.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};h();var u3=pe(Xr(),1);h();var KV=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(KV||{}),WV=(u=>(u.handshakeResponse="HANDSHAKE_RESPONSE",u.loginResponse="LOGIN_RESPONSE",u.disconnectResponse="DISCONNECT_RESPONSE",u.cancelResponse="CANCEL_RESPONSE",u.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",u.signMessageResponse="SIGN_MESSAGE_RESPONSE",u.noneResponse="NONE_RESPONSE",u))(WV||{}),a3={...WV,...KV},$V=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))($V||{}),YV=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(YV||{}),Tu={...YV,...$V};h();var JV=typeof window<"u"?window:{},XV=()=>JV.ReactNativeWebView?"reactNative":JV.webkit?"ios":"web",_u=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",sw=t=>Object.prototype.toString.call(t)==="[object String]";h();var ow={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,_u()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t}),_u())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t}),_u())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:Tu.logoutRequest}),_u())}};var aw=XV(),uw="message",ZV=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=_u()&&aw!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(uw,e),window&&window.addEventListener(uw,e)},ha=class{constructor(){}async logout(){return ow.logout[aw](),new Promise(e=>{e(!0)})}async signMessage(e){try{return ow.signMessage[aw](e),await new Promise((n,i)=>{window.signMessageResponse=(o,u)=>{if(u){i(u),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:u,type:a}=o;if(a===a3.signMessageResponse&&u!=null){let{signedMessage:c,error:f}=u;f?i(f):n(c)}document?.removeEventListener(uw,s)}ZV(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return ow.signTransactions[aw](r),await new Promise((i,s)=>{window.transactionsSigned=(u,a)=>{if(u=JSON.parse(u),a){s(a),window.transactionsSigned=null;return}i(u.map(c=>u3.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(u){let{message:a,type:c}=u;if(c===a3.signTransactionsResponse){let{transactions:f,error:d}=a;try{d?s(d):i(f.map(w=>u3.Transaction.fromPlainObject(w)))}catch{s("Unable to sign")}}document&&document.removeEventListener(uw,o)}ZV(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};h();h();h();function Sge(t){try{let e=atob(t),r=btoa(e),n=p.Buffer.from(t,"base64").toString(),i=p.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Wl(t){return Sge(t)?atob(t):t}h();var ek=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Wl(s)),u=Wl(r);return{ttl:Number(i),extraInfo:o,origin:u,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var tk=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Wl(r),o=Wl(n),u=ek(o);if(!u)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let a={...u,address:s,body:o,signature:i};return u.extraInfo?.timestamp||delete a.extraInfo,a}catch{return null}};function rk(t,e){let r=tk(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(me.set("loginToken",s),me.set("accessToken",t),me.set("signature",n),me.set("address",i),me.set("loginMethod","x-portal-hub"),e.dappProvider=new ha)}h();var nk=t=>{t.onLoginStart&&ge.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&ge.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&ge.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&ge.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&ge.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&ge.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&ge.set("onQrPending",t.onQrPending),t.onQrLoaded&&ge.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&ge.set("onTxStart",t.onTxStart),t.onTxSent&&ge.set("onTxSent",t.onTxSent),t.onTxFinalized&&ge.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&ge.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&ge.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&ge.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&ge.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&ge.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&ge.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&ge.set("onQueryFailure",t.onQueryFailure)};h();var cw=async t=>{ge.run("onLoginStart");try{await t(()=>{ge.run("onLoginSuccess")})}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to login the user: ${r}`),ge.run("onLoginFailure",r)}};var h3=class{static async init(e){let r=me.get();if(r.expires&&H1(r.expires)){me.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:j0,apiUrl:M8,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:F8,...e},this.networkProvider=new k1(this.initOptions),nk(this.initOptions);let n=ln("accessToken");n&&await cw(async s=>{rk(n,this),await Au(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&ln("address"))&&r?.loginMethod&&(await cw(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await z0()),r.loginMethod==="mobile"&&(this.dappProvider=await i9(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new ha),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Au(this),s()}),this.initOptions?.chainType&&(await VV(this.dappProvider,this.networkProvider,Rr[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),QV()))}static async login(e,r){if(!Object.values(IC).includes(e)){let i="Wrong login method!";throw ge.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw ge.run("onLoginFailure",i),new Error(i)}await cw(async()=>{let i=new ik.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await I9(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await OV(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Fl(this);return this.dappProvider=void 0,e}catch(e){let r=Kt(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw ge.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw ge.run("onTxFailure",e,n),new Error(n)}let r=GV(e);try{ge.run("onTxStart",e);let n=me.get();if(e.nonce=n.nonce,this.dappProvider instanceof c3.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof l3.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof ha&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof f3.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=zV(r);if(i||nw(r),i&&this.initOptions?.chainType){await jV(r,Rr[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await rw(r,this.networkProvider)}}catch(n){let i=Kt(n);throw ge.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(ge.run("onSignMsgStart",e),this.dappProvider instanceof c3.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof l3.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof ha&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof f3.WalletProvider){let s=u=>encodeURIComponent(u).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=me.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&ge.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Kt(i);throw ge.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{ge.run("onQueryStart",o);let u=await this.networkProvider.queryContract(o);return ge.run("onQueryFinalized",u),u}catch(u){let a=Kt(u);throw ge.run("onQueryFinalized",o,a),new Error(`Smart contract query failed! ${a}`)}}static{this.storage=me}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,ge.clear()}}};h();rr();Ou.config({ROUNDING_MODE:Ou.ROUND_FLOOR});var Ige=({amount:t,decimals:e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return BigInt(new Ou(t).shiftedBy(e).toFixed())},Tge=({amount:t,decimals:e,rounding:r=e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return new Ou(t).shiftedBy(-e).decimalPlaces(r).toFixed()};var export_Account=Cge.Account;var export_Address=_ge.Address;var export_AddressType=uk.AddressType;var export_AddressValue=uk.AddressValue;var export_BigUIntType=_s.BigUIntType;var export_BigUIntValue=_s.BigUIntValue;var export_BooleanType=ak.BooleanType;var export_BooleanValue=ak.BooleanValue;var export_BytesType=ok.BytesType;var export_BytesValue=ok.BytesValue;var export_ContractQueryResponse=Rge.ContractQueryResponse;var export_Message=sk.Message;var export_MessageComputer=sk.MessageComputer;var export_QueryArguments=Pge.QueryArguments;var export_SignableMessage=Dge.SignableMessage;var export_SmartContractTransactionsFactory=fw.SmartContractTransactionsFactory;var export_SmartContractTransactionsOutcomeParser=p3.SmartContractTransactionsOutcomeParser;var export_Token=d3.Token;var export_TokenComputer=d3.TokenComputer;var export_TokenManagementTransactionsFactory=fw.TokenManagementTransactionsFactory;var export_TokenManagementTransactionsOutcomeParser=p3.TokenManagementTransactionsOutcomeParser;var export_TokenOperationsFactory=g3.TokenOperationsFactory;var export_TokenOperationsFactoryConfig=g3.TokenOperationsFactoryConfig;var export_TokenOperationsOutcomeParser=g3.TokenOperationsOutcomeParser;var export_TokenTransfer=d3.TokenTransfer;var export_Transaction=Nge.Transaction;var export_TransactionComputer=xge.TransactionComputer;var export_TransactionEventsParser=p3.TransactionEventsParser;var export_TransactionWatcher=Oge.TransactionWatcher;var export_TransactionsFactoryConfig=fw.TransactionsFactoryConfig;var export_TransferTransactionsFactory=fw.TransferTransactionsFactory;var export_U16Type=_s.U16Type;var export_U16Value=_s.U16Value;var export_U32Type=_s.U32Type;var export_U32Value=_s.U32Value;var export_U64Type=_s.U64Type;var export_U64Value=_s.U64Value;var export_U8Type=_s.U8Type;var export_U8Value=_s.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractQueryResponse as ContractQueryResponse,dde as DappCoreWCV2CustomMethodsEnum,h3 as ElvenJS,r9 as EventStoreEvents,IC as LoginMethodsEnum,export_Message as Message,export_MessageComputer as MessageComputer,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContractTransactionsFactory as SmartContractTransactionsFactory,export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser,export_Token as Token,export_TokenComputer as TokenComputer,export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory,export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser,export_TokenOperationsFactory as TokenOperationsFactory,export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig,export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionComputer as TransactionComputer,export_TransactionEventsParser as TransactionEventsParser,export_TransactionWatcher as TransactionWatcher,export_TransactionsFactoryConfig as TransactionsFactoryConfig,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,gde as WebWalletUrlParamsEnum,Tge as formatAmount,Ige as parseAmount}; +`);let o=bge(e,r,i),u=Z1.getSymbolSize(e),a=new fge(u);return yge(a,e),wge(a),vge(a,e),$C(a,r,0),e>=7&&Age(a,e),Ege(a,o),isNaN(n)&&(n=YC.getBestMask(a,$C.bind(null,a,r))),YC.applyMask(n,a),$C(a,r,n),{modules:a,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}RV.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=KC.M,i,s;return typeof r<"u"&&(n=KC.from(r.errorCorrectionLevel,KC.M),i=X1.from(r.version),s=YC.from(r.maskPattern),r.toSJISFunc&&Z1.setToSJISFunction(r.toSJISFunc)),Ige(e,i,n,s)}});var XC=D(Iu=>{h();function MV(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Iu.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:MV(e.color.dark||"#000000ff"),light:MV(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Iu.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Iu.getImageWidth=function(e,r){let n=Iu.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Iu.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Iu.getScale(i,n),u=Math.floor((i+n.margin*2)*o),a=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=a&&d>=a&&f{h();var ZC=XC();function Tge(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function _ge(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}ew.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=_ge()),i=ZC.getOptions(i);let o=ZC.getImageWidth(e.modules.size,i),u=s.getContext("2d"),a=u.createImageData(o,o);return ZC.qrToImageData(a.data,e,i),Tge(u,s,o),u.putImageData(a,0,0),s};ew.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=ew.render(e,r,i),o=i.type||"image/png",u=i.rendererOpts||{};return s.toDataURL(o,u.quality)}});var qV=D(UV=>{h();var Cge=XC();function FV(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function e3(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function Nge(t,e,r){let n="",i=0,s=!1,o=0;for(let u=0;u0&&a>0&&t[u-1]||(n+=s?e3("M",a+r,.5+c+r):e3("m",i,0),i=0,s=!1),a+1':"",c="',f='viewBox="0 0 '+u+" "+u+'"',w=''+a+c+` +`;return typeof n=="function"&&n(null,w),w}});var kV=D(xd=>{h();var xge=k9(),t3=BV(),VV=LV(),Oge=qV();function r3(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,u=typeof s[o-1]=="function";if(!u&&!xge())throw new Error("Callback required as last argument");if(u){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(a,c){try{let f=t3.create(r,n);a(t(f,e,n))}catch(f){c(f)}})}try{let a=t3.create(r,n);i(null,t(a,e,n))}catch(a){i(a)}}xd.create=t3.create;xd.toCanvas=r3.bind(null,VV.render);xd.toDataURL=r3.bind(null,VV.renderToDataURL);xd.toString=r3.bind(null,function(t,e,r){return Oge.render(t,r)})});var XV=D(la=>{"use strict";h();var kge=la&&la.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),JV=la&&la.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kge(e,t,r)};Object.defineProperty(la,"__esModule",{value:!0});JV(Dl(),la);JV(J2(),la)});h();var h3=pe(_a(),1),d3=pe(Cb(),1),hw=pe(f0(),1),g3=pe(Pb(),1),Qge=pe(Ve(),1),Kge=pe(Ic(),1),Wge=pe(Xr(),1),$ge=pe(_0(),1),Ak=pe(Mb(),1),Yge=pe(U0(),1),Jge=pe(V0(),1),Ek=pe(po(),1),_s=pe(Mf(),1),bk=pe(yf(),1),Sk=pe(Yu(),1),Xge=pe(NE(),1),Zge=pe(zb(),1);h();h();var F8=pe(Wb(),1);h();h();var k0="elvenjs_state",B8="https://devnet-api.multiversx.com";var Po="/dapp/init",H0="devnet",M8="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",L8=["wss://relay.walletconnect.com"],Rr={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var me={get(t){let e=localStorage.getItem(k0);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem(k0,JSON.stringify(r))},clear(){localStorage.removeItem(k0)}};var G0=async()=>{let t=F8.ExtensionProvider.getInstance();try{let e=await t.init(),r=me.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var u3=pe(Wb(),1),c3=pe(fd(),1),l3=pe(Dl(),1),vk=pe(bC(),1),fw=pe(V0(),1);h();var w9=pe(fd(),1);h();h();var ge=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};h();var y9=(U=>(U.onLoginStart="onLoginStart",U.onLoginSuccess="onLoginSuccess",U.onLoginFailure="onLoginFailure",U.onLogoutStart="onLogoutStart",U.onLogoutSuccess="onLogoutSuccess",U.onLogoutFailure="onLogoutFailure",U.onQrPending="onQrPending",U.onQrLoaded="onQrLoaded",U.onTxStart="onTxStart",U.onTxSent="onTxSent",U.onTxFinalized="onTxFinalized",U.onTxFailure="onTxFailure",U.onSignMsgStart="onSignMsgStart",U.onSignMsgFinalized="onSignMsgFinalized",U.onSignMsgFailure="onSignMsgFailure",U.onQueryStart="onQueryStart",U.onQueryFinalized="onQueryFinalized",U.onQueryFailure="onQueryFailure",U))(y9||{}),SC=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(SC||{}),Rde=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(Rde||{}),Bde=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(Bde||{});h();var Kt=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Fl=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");ge.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(me.clear(),ge.run("onLogoutSuccess")),e}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to logout the user: ${r}`),ge.run("onLogoutFailure",r)}};h();function B1(t){return t[Math.floor(Math.random()*t.length)]}var v9=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Fl(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=B1(t.initOptions.walletConnectV2RelayAddresses),n=new w9.WalletConnectV2Provider(e,Rr[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};h();var k1=pe(Ve(),1),O9=pe(A9(),1),D9=pe(b9(),1),P9=pe(DC(),1),R9=pe(N9(),1),B9=pe(zb(),1),M9=pe(x9(),1),L9=pe(Wf(),1);var H1=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||H0,this.apiUrl=e||Rr[this.chainType]?.apiAddress,this.apiTimeout=n||Rr[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),u=await o.json();if(!o.ok){let a=u?.error||o.status;return clearTimeout(i),Promise.reject(a)}return clearTimeout(i),u}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let u=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),a=await u.json();if(!u.ok){let c=a?.error||u.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),a}catch(u){this.handleApiError(u,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new k1.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new O9.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new k1.Address(r.sender),receiver:new k1.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:p.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:D9.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:P9.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:R9.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new L9.Query({address:e,func:r,args:n,value:i,caller:s}),u=new M9.ContractQueryRequest(o).toHttpRequest(),a=await this.apiPost("query",u);return B9.ContractQueryResponse.fromHttpResponse(a)}catch(o){this.handleApiError(o,"query")}}};h();h();var kl=()=>new Date().setHours(new Date().getHours()+24),G1=t=>Date.now()>t;h();var F9=pe(Ve(),1),U9=pe(Ic(),1);var Au=async t=>{let e=me.get("address"),r=me.get("expires");if(!(r&&G1(r))&&e&&t.networkProvider){let i=new F9.Address(e),s=new U9.Account(i);try{let o=await t.networkProvider.getAccount(i),u=await t.networkProvider.getGuardianData(i);me.set("address",e),me.set("activeGuardian",u.guarded&&u.activeGuardian?.address?u.activeGuardian.address:""),me.set("nonce",o.nonce.valueOf()),me.set("balance",o.balance.toString()),s.update(o)}catch(o){let u=Kt(o);console.warn(`Something went wrong trying to synchronize the user account: ${u}`)}}};var q9=async(t,e,r,n="/")=>{let i=await G0(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(a){let c=Kt(a);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:u}=i.account;if(me.set("loginToken",e),u&&me.set("signature",u),t.networkProvider&&u)try{let a=await i.getAddress();if(!a)throw new Error("Canceled!");me.set("address",a),me.set("loginMethod","browser-extension"),me.set("expires",kl()),await Au(t);let c=r.getToken(a,e,u);return me.set("accessToken",c),ge.run("onLoginSuccess"),i}catch(a){throw new Error(`Something went wrong trying to synchronize the user account: ${a?.message}`)}};h();h();var HV=pe(kV(),1),GV=pe(fd(),1);var Dge=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},Pge=t=>{let e=`${M8}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},Rge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},Bge=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},n3={},Mge=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",n3[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:n3[t.topic].signal}),r},tw={},Lge=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=Mge(t,e);return n.appendChild(s),tw[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:tw[t.topic].signal}),n},Fge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},Uge=t=>{if(!t)return;document.getElementById(t)?.remove()},qge=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),Vge=async t=>t?await HV.default.toString(t,{type:"svg"}):void 0,jV=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await Vge(e),o;if(s&&(o=Dge(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),qge()&&i.appendChild(Pge(e))),i&&r instanceof GV.WalletConnectV2Provider){let u=r.pairings,a=async f=>{try{f&&(await r.logout({topic:f}),Uge(f))}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to remove the existing pairing: ${w}`)}finally{tw[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(Fge()),await r.login({approval:d,token:n})}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to login the user: ${w}`)}finally{for(let d of Object.values(tw))d?.abort();for(let d of Object.values(n3))d?.abort()}};if(u&&u.length>0){let f=Rge();i.appendChild(f);let d=Bge();f.appendChild(d);for(let w of u){let A=Lge(w,a,c);f.appendChild(A)}}}return i};var rw=pe(fd(),1);var zV=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=B1(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof rw.WalletConnectV2Provider){let a=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();me.set("address",a),me.set("loginMethod","mobile"),me.set("expires",kl()),await Au(t),c&&me.set("signature",c),me.set("loginToken",e);let f=r.getToken(a,e,c);me.set("accessToken",f),ge.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof rw.WalletConnectV2Provider&&await Fl(t)},onClientEvent:a=>{console.log("wc2 session event: ",a)}},u=new rw.WalletConnectV2Provider(o,Rr[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(u){t.dappProvider=u,ge.run("onQrPending"),await u.init();let{uri:a,approval:c}=await u.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${a}&token=${e}`:a;return n&&f&&(s=await jV(n,f,u,e),ge.run("onQrLoaded")),await u.login({approval:c,token:e}),u}}catch(a){let c=Kt(a);console.warn(`Something went wrong trying to login the user: ${c}`),ge.run("onLoginFailure",c)}};h();var QV=pe(Dl(),1);var i3=async(t,e,r,n)=>{let i=new QV.WalletProvider(`${t}${Po}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return me.set("loginMethod",Rr[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),me.set("expires",kl()),me.set("loginToken",e),i}catch(u){let a=Kt(u);console.warn(`Something went wrong trying to login the user: ${a}`),me.set("loginMethod",""),ge.run("onLoginFailure",a)}};h();var ln=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};h();var KV=pe(Dl(),1);var WV=pe(bC(),1),s3=async(t,e)=>{let r=ln("signature"),n=ln("address"),i=me.get("address"),s=me.get("loginToken");if(r&&me.set("signature",r),n||i){n&&(me.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new KV.WalletProvider(`${t}${Po}`);if(r&&e&&n){let a=new WV.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);me.set("accessToken",a)}return o}};h();var $V=pe(Ic(),1),YV=pe(U0(),1);var nw=async(t,e)=>{ge.run("onTxSent",t);let n=await new YV.TransactionWatcher(e).awaitCompleted(t),i=n.sender,s=new $V.Account(i),o=await e.getAccount(i);s.update(o),me.set("address",s.address.bech32()),me.set("balance",s.balance.toString()),ge.run("onTxFinalized",n)};h();var Kl=pe(XV(),1),ek=pe(Xr(),1);h();var ZV=pe(Ic(),1);var iw=t=>{let e=t.getSender(),r=new ZV.Account(e),n=t.nonce.valueOf();r.incrementNonce(),me.set("nonce",(n+1n).toString())};var tk=async(t,e,r,n)=>{if(ln(Kl.WALLET_PROVIDER_CALLBACK_PARAM)===Kl.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=me.get("activeGuardian"),o=me.get("loginMethod"),u=ln("hasWebWalletGuardianSign"),a;if("getTransactionsFromWalletUrl"in t){if(a=t.getTransactionsFromWalletUrl()?.[0],!a)return;o==="web-wallet"&&(a.data=p.Buffer.from(a.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&u&&(a=new Kl.WalletProvider(`${r}${Po}`).getTransactionsFromWalletUrl()?.[0]);if(a){let c=ek.Transaction.fromPlainObject(a);c.nonce=BigInt(n),iw(c);try{ge.run("onTxStart",c),await e.sendTransaction(c),await nw(c,e)}catch(f){let w=`Getting transaction information failed! ${Kt(f)}`;throw ge.run("onTxFailure",c,w),new Error(w)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};h();var sw=pe($l(),1),rk=pe(Ve(),1),nk=pe(Dl(),1);var ik=t=>{let e=me.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(sw.TransactionVersion.withTxOptions()),t.setOptions(sw.TransactionOptions.withOptions(r)),t.setGuardian(rk.Address.fromBech32(e))}return t},sk=async(t,e)=>{let r=new nk.WalletProvider(`${e}${Po}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},ok=t=>{let e=me.get("activeGuardian");return!(!me.get("address")||!e||t.isGuardedTransaction())};h();var ak=()=>{let t=!ln("walletProviderStatus"),e=ln("status")==="signed",r=ln("message"),n=ln("signature");t&&e&&r&&n&&(ge.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};h();var a3=pe(Xr(),1);h();var uk=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(uk||{}),ck=(u=>(u.handshakeResponse="HANDSHAKE_RESPONSE",u.loginResponse="LOGIN_RESPONSE",u.disconnectResponse="DISCONNECT_RESPONSE",u.cancelResponse="CANCEL_RESPONSE",u.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",u.signMessageResponse="SIGN_MESSAGE_RESPONSE",u.noneResponse="NONE_RESPONSE",u))(ck||{}),o3={...ck,...uk},lk=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))(lk||{}),fk=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(fk||{}),Tu={...fk,...lk};h();var hk=typeof window<"u"?window:{},dk=()=>hk.ReactNativeWebView?"reactNative":hk.webkit?"ios":"web",_u=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",ow=t=>Object.prototype.toString.call(t)==="[object String]";h();var aw={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,_u()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t}),_u())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t}),_u())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:Tu.logoutRequest}),_u())}};var uw=dk(),cw="message",gk=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=_u()&&uw!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(cw,e),window&&window.addEventListener(cw,e)},fa=class{constructor(){}async logout(){return aw.logout[uw](),new Promise(e=>{e(!0)})}async signMessage(e){try{return aw.signMessage[uw](e),await new Promise((n,i)=>{window.signMessageResponse=(o,u)=>{if(u){i(u),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:u,type:a}=o;if(a===o3.signMessageResponse&&u!=null){let{signedMessage:c,error:f}=u;f?i(f):n(c)}document?.removeEventListener(cw,s)}gk(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return aw.signTransactions[uw](r),await new Promise((i,s)=>{window.transactionsSigned=(u,a)=>{if(u=JSON.parse(u),a){s(a),window.transactionsSigned=null;return}i(u.map(c=>a3.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(u){let{message:a,type:c}=u;if(c===o3.signTransactionsResponse){let{transactions:f,error:d}=a;try{d?s(d):i(f.map(w=>a3.Transaction.fromPlainObject(w)))}catch{s("Unable to sign")}}document&&document.removeEventListener(cw,o)}gk(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};h();h();h();function Gge(t){try{let e=atob(t),r=btoa(e),n=p.Buffer.from(t,"base64").toString(),i=p.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Wl(t){return Gge(t)?atob(t):t}h();var pk=t=>{if(!t||!ow(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Wl(s)),u=Wl(r);return{ttl:Number(i),extraInfo:o,origin:u,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var mk=t=>{if(!t||!ow(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Wl(r),o=Wl(n),u=pk(o);if(!u)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let a={...u,address:s,body:o,signature:i};return u.extraInfo?.timestamp||delete a.extraInfo,a}catch{return null}};function yk(t,e){let r=mk(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(me.set("loginToken",s),me.set("accessToken",t),me.set("signature",n),me.set("address",i),me.set("loginMethod","x-portal-hub"),e.dappProvider=new fa)}h();var wk=t=>{t.onLoginStart&&ge.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&ge.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&ge.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&ge.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&ge.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&ge.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&ge.set("onQrPending",t.onQrPending),t.onQrLoaded&&ge.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&ge.set("onTxStart",t.onTxStart),t.onTxSent&&ge.set("onTxSent",t.onTxSent),t.onTxFinalized&&ge.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&ge.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&ge.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&ge.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&ge.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&ge.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&ge.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&ge.set("onQueryFailure",t.onQueryFailure)};h();var lw=async t=>{ge.run("onLoginStart");try{await t(()=>{ge.run("onLoginSuccess")})}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to login the user: ${r}`),ge.run("onLoginFailure",r)}};var f3=class{static async init(e){let r=me.get();if(r.expires&&G1(r.expires)){me.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:H0,apiUrl:B8,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:L8,...e},this.networkProvider=new H1(this.initOptions),wk(this.initOptions);let n=ln("accessToken");n&&await lw(async s=>{yk(n,this),await Au(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&ln("address"))&&r?.loginMethod&&(await lw(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await G0()),r.loginMethod==="mobile"&&(this.dappProvider=await v9(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new fa),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await s3(Rr[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await s3(Rr[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Au(this),s()}),this.initOptions?.chainType&&(await tk(this.dappProvider,this.networkProvider,Rr[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),ak()))}static async login(e,r){if(!Object.values(SC).includes(e)){let i="Wrong login method!";throw ge.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw ge.run("onLoginFailure",i),new Error(i)}await lw(async()=>{let i=new vk.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await q9(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await zV(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await i3(Rr[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await i3(Rr[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Fl(this);return this.dappProvider=void 0,e}catch(e){let r=Kt(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw ge.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw ge.run("onTxFailure",e,n),new Error(n)}let r=ik(e);try{ge.run("onTxStart",e);let n=me.get();if(e.nonce=n.nonce,this.dappProvider instanceof u3.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof c3.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof fa&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof l3.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=ok(r);if(i||iw(r),i&&this.initOptions?.chainType){await sk(r,Rr[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await nw(r,this.networkProvider)}}catch(n){let i=Kt(n);throw ge.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(ge.run("onSignMsgStart",e),this.dappProvider instanceof u3.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new fw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof c3.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new fw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof fa&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof l3.WalletProvider){let s=u=>encodeURIComponent(u).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new fw.SignableMessage({message:p.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=me.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&ge.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Kt(i);throw ge.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{ge.run("onQueryStart",o);let u=await this.networkProvider.queryContract(o);return ge.run("onQueryFinalized",u),u}catch(u){let a=Kt(u);throw ge.run("onQueryFinalized",o,a),new Error(`Smart contract query failed! ${a}`)}}static{this.storage=me}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,ge.clear()}}};h();rr();Ou.config({ROUNDING_MODE:Ou.ROUND_FLOOR});var jge=({amount:t,decimals:e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return BigInt(new Ou(t).shiftedBy(e).toFixed())},zge=({amount:t,decimals:e,rounding:r=e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return new Ou(t).shiftedBy(-e).decimalPlaces(r).toFixed()};var export_Account=Kge.Account;var export_Address=Qge.Address;var export_AddressType=Sk.AddressType;var export_AddressValue=Sk.AddressValue;var export_BigUIntType=_s.BigUIntType;var export_BigUIntValue=_s.BigUIntValue;var export_BooleanType=bk.BooleanType;var export_BooleanValue=bk.BooleanValue;var export_BytesType=Ek.BytesType;var export_BytesValue=Ek.BytesValue;var export_ContractQueryResponse=Zge.ContractQueryResponse;var export_Message=Ak.Message;var export_MessageComputer=Ak.MessageComputer;var export_QueryArguments=Xge.QueryArguments;var export_SignableMessage=Jge.SignableMessage;var export_SmartContractTransactionsFactory=hw.SmartContractTransactionsFactory;var export_SmartContractTransactionsOutcomeParser=g3.SmartContractTransactionsOutcomeParser;var export_Token=h3.Token;var export_TokenComputer=h3.TokenComputer;var export_TokenManagementTransactionsFactory=hw.TokenManagementTransactionsFactory;var export_TokenManagementTransactionsOutcomeParser=g3.TokenManagementTransactionsOutcomeParser;var export_TokenOperationsFactory=d3.TokenOperationsFactory;var export_TokenOperationsFactoryConfig=d3.TokenOperationsFactoryConfig;var export_TokenOperationsOutcomeParser=d3.TokenOperationsOutcomeParser;var export_TokenTransfer=h3.TokenTransfer;var export_Transaction=Wge.Transaction;var export_TransactionComputer=$ge.TransactionComputer;var export_TransactionEventsParser=g3.TransactionEventsParser;var export_TransactionWatcher=Yge.TransactionWatcher;var export_TransactionsFactoryConfig=hw.TransactionsFactoryConfig;var export_TransferTransactionsFactory=hw.TransferTransactionsFactory;var export_U16Type=_s.U16Type;var export_U16Value=_s.U16Value;var export_U32Type=_s.U32Type;var export_U32Value=_s.U32Value;var export_U64Type=_s.U64Type;var export_U64Value=_s.U64Value;var export_U8Type=_s.U8Type;var export_U8Value=_s.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractQueryResponse as ContractQueryResponse,Rde as DappCoreWCV2CustomMethodsEnum,f3 as ElvenJS,y9 as EventStoreEvents,SC as LoginMethodsEnum,export_Message as Message,export_MessageComputer as MessageComputer,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContractTransactionsFactory as SmartContractTransactionsFactory,export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser,export_Token as Token,export_TokenComputer as TokenComputer,export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory,export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser,export_TokenOperationsFactory as TokenOperationsFactory,export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig,export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionComputer as TransactionComputer,export_TransactionEventsParser as TransactionEventsParser,export_TransactionWatcher as TransactionWatcher,export_TransactionsFactoryConfig as TransactionsFactoryConfig,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,Bde as WebWalletUrlParamsEnum,zge as formatAmount,jge as parseAmount}; /*! Bundled license information: ieee754/index.js: diff --git a/example/elven.js b/example/elven.js index ec95d64..d1317cb 100644 --- a/example/elven.js +++ b/example/elven.js @@ -1,26 +1,26 @@ -var ck=Object.create;var Rd=Object.defineProperty;var lk=Object.getOwnPropertyDescriptor;var fk=Object.getOwnPropertyNames;var hk=Object.getPrototypeOf,dk=Object.prototype.hasOwnProperty;var Bd=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)Rd(t,r,{get:e[r],enumerable:!0})},Pd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fk(e))!dk.call(t,i)&&i!==r&&Rd(t,i,{get:()=>e[i],enumerable:!(n=lk(e,i))||n.enumerable});return t},Tr=(t,e,r)=>(Pd(t,e,"default"),r&&Pd(r,e,"default")),pe=(t,e,r)=>(r=t!=null?ck(hk(t)):{},Pd(e||!t||!t.__esModule?Rd(r,"default",{value:t,enumerable:!0}):r,t)),_e=t=>Pd(Rd({},"__esModule",{value:!0}),t);var w3=B(Md=>{"use strict";h();Md.byteLength=pk;Md.toByteArray=yk;Md.fromByteArray=Ak;var Pi=[],Tn=[],gk=typeof Uint8Array<"u"?Uint8Array:Array,mw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ba=0,m3=mw.length;ba0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function pk(t){var e=y3(t),r=e[0],n=e[1];return(r+n)*3/4-n}function mk(t,e,r){return(e+r)*3/4-r}function yk(t){var e,r=y3(t),n=r[0],i=r[1],s=new gk(mk(t,n,i)),o=0,u=i>0?n-4:n,a;for(a=0;a>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tn[t.charCodeAt(a)]<<2|Tn[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=Tn[t.charCodeAt(a)]<<10|Tn[t.charCodeAt(a+1)]<<4|Tn[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function wk(t){return Pi[t>>18&63]+Pi[t>>12&63]+Pi[t>>6&63]+Pi[t&63]}function vk(t,e,r){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=t[r-1],i.push(Pi[e>>2]+Pi[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Pi[e>>10]+Pi[e>>4&63]+Pi[e<<2&63]+"=")),i.join("")}});var v3=B(yw=>{h();yw.read=function(t,e,r,n,i){var s,o,u=i*8-n-1,a=(1<>1,f=-7,d=r?i-1:0,w=r?-1:1,A=t[e+d];for(d+=w,s=A&(1<<-f)-1,A>>=-f,f+=u;f>0;s=s*256+t[e+d],d+=w,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=w,f-=8);if(s===0)s=1-c;else{if(s===a)return o?NaN:(A?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(A?-1:1)*o*Math.pow(2,s-n)};yw.write=function(t,e,r,n,i,s){var o,u,a,c=s*8-i-1,f=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:s-1,T=n?1:-1,x=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=w/a:e+=w*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=f?(u=0,o=f):o+d>=1?(u=(e*a-1)*Math.pow(2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+A]=u&255,A+=T,u/=256,i-=8);for(o=o<0;t[r+A]=o&255,A+=T,o/=256,c-=8);t[r+A-T]|=x*128}});var io=B(Nu=>{"use strict";h();var ww=w3(),Cu=v3(),A3=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nu.Buffer=X;Nu.SlowBuffer=_k;Nu.INSPECT_MAX_BYTES=50;var Ld=2147483647;Nu.kMaxLength=Ld;X.TYPED_ARRAY_SUPPORT=Ek();!X.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 Ek(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(X.prototype,"parent",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.buffer}});Object.defineProperty(X.prototype,"offset",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.byteOffset}});function Cs(t){if(t>Ld)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,X.prototype),e}function X(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return bw(t)}return S3(t,e,r)}X.poolSize=8192;function S3(t,e,r){if(typeof t=="string")return Sk(t,e);if(ArrayBuffer.isView(t))return Ik(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Ri(t,ArrayBuffer)||t&&Ri(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ri(t,SharedArrayBuffer)||t&&Ri(t.buffer,SharedArrayBuffer)))return Aw(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return X.from(n,e,r);var i=Tk(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return X.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}X.from=function(t,e,r){return S3(t,e,r)};Object.setPrototypeOf(X.prototype,Uint8Array.prototype);Object.setPrototypeOf(X,Uint8Array);function I3(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function bk(t,e,r){return I3(t),t<=0?Cs(t):e!==void 0?typeof r=="string"?Cs(t).fill(e,r):Cs(t).fill(e):Cs(t)}X.alloc=function(t,e,r){return bk(t,e,r)};function bw(t){return I3(t),Cs(t<0?0:Sw(t)|0)}X.allocUnsafe=function(t){return bw(t)};X.allocUnsafeSlow=function(t){return bw(t)};function Sk(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!X.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=T3(t,e)|0,n=Cs(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function vw(t){for(var e=t.length<0?0:Sw(t.length)|0,r=Cs(e),n=0;n=Ld)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ld.toString(16)+" bytes");return t|0}function _k(t){return+t!=t&&(t=0),X.alloc(+t)}X.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==X.prototype};X.compare=function(e,r){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),Ri(r,Uint8Array)&&(r=X.from(r,r.offset,r.byteLength)),!X.isBuffer(e)||!X.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?X.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(X.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function T3(t,e){if(X.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ri(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Ew(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return D3(t).length;default:if(i)return n?-1:Ew(t).length;e=(""+e).toLowerCase(),i=!0}}X.byteLength=T3;function Ck(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return Fk(this,e,r);case"utf8":case"utf-8":return C3(this,e,r);case"ascii":return Mk(this,e,r);case"latin1":case"binary":return Lk(this,e,r);case"base64":return Rk(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Uk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}X.prototype._isBuffer=!0;function Sa(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}X.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};A3&&(X.prototype[A3]=X.prototype.inspect);X.prototype.compare=function(e,r,n,i,s){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),!X.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=n-r,a=Math.min(o,u),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Iw(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=X.from(e,n)),X.isBuffer(e))return e.length===0?-1:E3(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):E3(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function E3(t,e,r,n,i){var s=1,o=t.length,u=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,u/=2,r/=2}function a(A,T){return s===1?A[T]:A.readUInt16BE(T*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-u),c=r;c>=0;c--){for(var d=!0,w=0;wi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Nk(this,e,r,n);case"utf8":case"utf-8":return xk(this,e,r,n);case"ascii":case"latin1":case"binary":return Ok(this,e,r,n);case"base64":return Dk(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Pk(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Rk(t,e,r){return e===0&&r===t.length?ww.fromByteArray(t):ww.fromByteArray(t.slice(e,r))}function C3(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+u<=r){var a,c,f,d;switch(u){case 1:s<128&&(o=s);break;case 2:a=t[i+1],(a&192)===128&&(d=(s&31)<<6|a&63,d>127&&(o=d));break;case 3:a=t[i+1],c=t[i+2],(a&192)===128&&(c&192)===128&&(d=(s&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:a=t[i+1],c=t[i+2],f=t[i+3],(a&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(a&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=u}return Bk(n)}var b3=4096;function Bk(t){var e=t.length;if(e<=b3)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}X.prototype.readUintLE=X.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};X.prototype.readUint8=X.prototype.readUInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]};X.prototype.readUint16LE=X.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]|this[e+1]<<8};X.prototype.readUint16BE=X.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]<<8|this[e+1]};X.prototype.readUint32LE=X.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};X.prototype.readUint32BE=X.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};X.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};X.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};X.prototype.readInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};X.prototype.readInt16LE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};X.prototype.readInt16BE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};X.prototype.readInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};X.prototype.readInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};X.prototype.readFloatLE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!0,23,4)};X.prototype.readFloatBE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!1,23,4)};X.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!0,52,8)};X.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!1,52,8)};function zr(t,e,r,n,i,s){if(!X.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}X.prototype.writeUintLE=X.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=1,u=0;for(this[r]=e&255;++u>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=n-1,u=1;for(this[r+o]=e&255;--o>=0&&(u*=256);)this[r+o]=e/u&255;return r+n};X.prototype.writeUint8=X.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,255,0),this[r]=e&255,r+1};X.prototype.writeUint16LE=X.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeUint16BE=X.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeUint32LE=X.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};X.prototype.writeUint32BE=X.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};X.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=0,u=1,a=0;for(this[r]=e&255;++o>0)-a&255;return r+n};X.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=n-1,u=1,a=0;for(this[r+o]=e&255;--o>=0&&(u*=256);)e<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(e/u>>0)-a&255;return r+n};X.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};X.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};X.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function N3(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function x3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,4,34028234663852886e22,-34028234663852886e22),Cu.write(t,e,r,n,23,4),r+4}X.prototype.writeFloatLE=function(e,r,n){return x3(this,e,r,!0,n)};X.prototype.writeFloatBE=function(e,r,n){return x3(this,e,r,!1,n)};function O3(t,e,r,n,i){return e=+e,r=r>>>0,i||N3(t,e,r,8,17976931348623157e292,-17976931348623157e292),Cu.write(t,e,r,n,52,8),r+8}X.prototype.writeDoubleLE=function(e,r,n){return O3(this,e,r,!0,n)};X.prototype.writeDoubleBE=function(e,r,n){return O3(this,e,r,!1,n)};X.prototype.copy=function(e,r,n,i){if(!X.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function kk(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function D3(t){return ww.toByteArray(Vk(t))}function Fd(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Ri(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Iw(t){return t!==t}var Gk=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var L3=B((kge,M3)=>{h();var Wt=M3.exports={},Bi,Mi;function Tw(){throw new Error("setTimeout has not been defined")}function _w(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Bi=setTimeout:Bi=Tw}catch{Bi=Tw}try{typeof clearTimeout=="function"?Mi=clearTimeout:Mi=_w}catch{Mi=_w}})();function P3(t){if(Bi===setTimeout)return setTimeout(t,0);if((Bi===Tw||!Bi)&&setTimeout)return Bi=setTimeout,setTimeout(t,0);try{return Bi(t,0)}catch{try{return Bi.call(null,t,0)}catch{return Bi.call(this,t,0)}}}function jk(t){if(Mi===clearTimeout)return clearTimeout(t);if((Mi===_w||!Mi)&&clearTimeout)return Mi=clearTimeout,clearTimeout(t);try{return Mi(t)}catch{try{return Mi.call(null,t)}catch{return Mi.call(this,t)}}}var Ns=[],xu=!1,Ia,Ud=-1;function zk(){!xu||!Ia||(xu=!1,Ia.length?Ns=Ia.concat(Ns):Ud=-1,Ns.length&&R3())}function R3(){if(!xu){var t=P3(zk);xu=!0;for(var e=Ns.length;e;){for(Ia=Ns,Ns=[];++Ud1)for(var r=1;r{p=pe(io()),I=pe(L3()),Qk=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=Qk});var fr={};Bt(fr,{BigNumber:()=>q3,default:()=>Ou});function U3(t){var e,r,n,i=U.prototype={constructor:U,toString:null,valueOf:null},s=new U(1),o=20,u=4,a=-7,c=21,f=-1e7,d=1e7,w=!1,A=1,T=0,x={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},R="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function U(v,C){var D,F,P,l,g,y,E,S,_=this;if(!(_ instanceof U))return new U(v,C);if(C==null){if(v&&v._isBigNumber===!0){_.s=v.s,!v.c||v.e>d?_.c=_.e=null:v.e=10;g/=10,l++);l>d?_.c=_.e=null:(_.e=l,_.c=[v]);return}S=String(v)}else{if(!Kk.test(S=String(v)))return n(_,S,y);_.s=S.charCodeAt(0)==45?(S=S.slice(1),-1):1}(l=S.indexOf("."))>-1&&(S=S.replace(".","")),(g=S.search(/e/i))>0?(l<0&&(l=g),l+=+S.slice(g+1),S=S.substring(0,g)):l<0&&(l=S.length)}else{if(Ht(C,2,R.length,"Base"),C==10&&V)return _=new U(v),H(_,o+_.e+1,u);if(S=String(v),y=typeof v=="number"){if(v*0!=0)return n(_,S,y,C);if(_.s=1/v<0?(S=S.slice(1),-1):1,U.DEBUG&&S.replace(/^0\.0*|\./,"").length>15)throw Error(F3+v)}else _.s=S.charCodeAt(0)===45?(S=S.slice(1),-1):1;for(D=R.slice(0,C),l=g=0,E=S.length;gl){l=E;continue}}else if(!P&&(S==S.toUpperCase()&&(S=S.toLowerCase())||S==S.toLowerCase()&&(S=S.toUpperCase()))){P=!0,g=-1,l=0;continue}return n(_,String(v),y,C)}y=!1,S=r(S,C,10,_.s),(l=S.indexOf("."))>-1?S=S.replace(".",""):l=S.length}for(g=0;S.charCodeAt(g)===48;g++);for(E=S.length;S.charCodeAt(--E)===48;);if(S=S.slice(g,++E)){if(E-=g,y&&U.DEBUG&&E>15&&(v>Nw||v!==Cn(v)))throw Error(F3+_.s*v);if((l=l-g-1)>d)_.c=_.e=null;else if(l=-mr&&P<=mr&&P===Cn(P)){if(F[0]===0){if(P===0&&F.length===1)return!0;break e}if(C=(P+1)%be,C<1&&(C+=be),String(F[0]).length==C){for(C=0;C=di||D!==Cn(D))break e;if(D!==0)return!0}}}else if(F===null&&P===null&&(l===null||l===1||l===-1))return!0;throw Error(Qr+"Invalid BigNumber: "+v)},U.maximum=U.max=function(){return L(arguments,-1)},U.minimum=U.min=function(){return L(arguments,1)},U.random=function(){var v=9007199254740992,C=Math.random()*v&2097151?function(){return Cn(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(D){var F,P,l,g,y,E=0,S=[],_=new U(s);if(D==null?D=o:Ht(D,0,mr),g=Cw(D/be),w)if(crypto.getRandomValues){for(F=crypto.getRandomValues(new Uint32Array(g*=2));E>>11),y>=9e15?(P=crypto.getRandomValues(new Uint32Array(2)),F[E]=P[0],F[E+1]=P[1]):(S.push(y%1e14),E+=2);E=g/2}else if(crypto.randomBytes){for(F=crypto.randomBytes(g*=7);E=9e15?crypto.randomBytes(7).copy(F,E):(S.push(y%1e14),E+=7);E=g/7}else throw w=!1,Error(Qr+"crypto unavailable");if(!w)for(;E=10;y/=10,E++);EP-1&&(y[g+1]==null&&(y[g+1]=0),y[g+1]+=y[g]/P|0,y[g]%=P)}return y.reverse()}return function(D,F,P,l,g){var y,E,S,_,M,N,m,O,Y=D.indexOf("."),$=o,b=u;for(Y>=0&&(_=T,T=0,D=D.replace(".",""),O=new U(F),N=O.pow(D.length-Y),T=_,O.c=C(Os(_n(N.c),N.e,"0"),10,P,v),O.e=O.c.length),m=C(D,F,P,g?(y=R,v):(y=v,R)),S=_=m.length;m[--_]==0;m.pop());if(!m[0])return y.charAt(0);if(Y<0?--S:(N.c=m,N.e=S,N.s=l,N=e(N,O,$,b,P),m=N.c,M=N.r,S=N.e),E=S+$+1,Y=m[E],_=P/2,M=M||E<0||m[E+1]!=null,M=b<4?(Y!=null||M)&&(b==0||b==(N.s<0?3:2)):Y>_||Y==_&&(b==4||M||b==6&&m[E-1]&1||b==(N.s<0?8:7)),E<1||!m[0])D=M?Os(y.charAt(1),-$,y.charAt(0)):y.charAt(0);else{if(m.length=E,M)for(--P;++m[--E]>P;)m[E]=0,E||(++S,m=[1].concat(m));for(_=m.length;!m[--_];);for(Y=0,D="";Y<=_;D+=y.charAt(m[Y++]));D=Os(D,S,y.charAt(0))}return D}}(),e=function(){function v(F,P,l){var g,y,E,S,_=0,M=F.length,N=P%so,m=P/so|0;for(F=F.slice();M--;)E=F[M]%so,S=F[M]/so|0,g=m*E+S*N,y=N*E+g%so*so+_,_=(y/l|0)+(g/so|0)+m*S,F[M]=y%l;return _&&(F=[_].concat(F)),F}function C(F,P,l,g){var y,E;if(l!=g)E=l>g?1:-1;else for(y=E=0;yP[y]?1:-1;break}return E}function D(F,P,l,g){for(var y=0;l--;)F[l]-=y,y=F[l]1;F.splice(0,1));}return function(F,P,l,g,y){var E,S,_,M,N,m,O,Y,$,b,j,z,W,ie,te,ee,se,oe=F.s==P.s?1:-1,J=F.c,ue=P.c;if(!J||!J[0]||!ue||!ue[0])return new U(!F.s||!P.s||(J?ue&&J[0]==ue[0]:!ue)?NaN:J&&J[0]==0||!ue?oe*0:oe/0);for(Y=new U(oe),$=Y.c=[],S=F.e-P.e,oe=l+S+1,y||(y=di,S=Nn(F.e/be)-Nn(P.e/be),oe=oe/be|0),_=0;ue[_]==(J[_]||0);_++);if(ue[_]>(J[_]||0)&&S--,oe<0)$.push(1),M=!0;else{for(ie=J.length,ee=ue.length,_=0,oe+=2,N=Cn(y/(ue[0]+1)),N>1&&(ue=v(ue,N,y),J=v(J,N,y),ee=ue.length,ie=J.length),W=ee,b=J.slice(0,ee),j=b.length;j=y/2&&te++;do{if(N=0,E=C(ue,b,ee,j),E<0){if(z=b[0],ee!=j&&(z=z*y+(b[1]||0)),N=Cn(z/te),N>1)for(N>=y&&(N=y-1),m=v(ue,N,y),O=m.length,j=b.length;C(m,b,O,j)==1;)N--,D(m,ee=10;oe/=10,_++);H(Y,l+(Y.e=_+S*be-1)+1,g,M)}else Y.e=S,Y.r=+M;return Y}}();function Q(v,C,D,F){var P,l,g,y,E;if(D==null?D=u:Ht(D,0,8),!v.c)return v.toString();if(P=v.c[0],g=v.e,C==null)E=_n(v.c),E=F==1||F==2&&(g<=a||g>=c)?Vd(E,g):Os(E,g,"0");else if(v=H(new U(v),C,D),l=v.e,E=_n(v.c),y=E.length,F==1||F==2&&(C<=l||l<=a)){for(;yy){if(--C>0)for(E+=".";C--;E+="0");}else if(C+=l-y,C>0)for(l+1==y&&(E+=".");C--;E+="0");return v.s<0&&P?"-"+E:E}function L(v,C){for(var D,F,P=1,l=new U(v[0]);P=10;P/=10,F++);return(D=F+D*be-1)>d?v.c=v.e=null:D=10;y/=10,P++);if(l=C-P,l<0)l+=be,g=C,E=M[S=0],_=Cn(E/N[P-g-1]%10);else if(S=Cw((l+1)/be),S>=M.length)if(F){for(;M.length<=S;M.push(0));E=_=0,P=1,l%=be,g=l-be+1}else break e;else{for(E=y=M[S],P=1;y>=10;y/=10,P++);l%=be,g=l-be+P,_=g<0?0:Cn(E/N[P-g-1]%10)}if(F=F||C<0||M[S+1]!=null||(g<0?E:E%N[P-g-1]),F=D<4?(_||F)&&(D==0||D==(v.s<0?3:2)):_>5||_==5&&(D==4||F||D==6&&(l>0?g>0?E/N[P-g]:0:M[S-1])%10&1||D==(v.s<0?8:7)),C<1||!M[0])return M.length=0,F?(C-=v.e+1,M[0]=N[(be-C%be)%be],v.e=-C||0):M[0]=v.e=0,v;if(l==0?(M.length=S,y=1,S--):(M.length=S+1,y=N[be-l],M[S]=g>0?Cn(E/N[P-g]%N[g])*y:0),F)for(;;)if(S==0){for(l=1,g=M[0];g>=10;g/=10,l++);for(g=M[0]+=y,y=1;g>=10;g/=10,y++);l!=y&&(v.e++,M[0]==di&&(M[0]=1));break}else{if(M[S]+=y,M[S]!=di)break;M[S--]=0,y=1}for(l=M.length;M[--l]===0;M.pop());}v.e>d?v.c=v.e=null:v.e=c?Vd(C,D):Os(C,D,"0"),v.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var v=new U(this);return v.s<0&&(v.s=1),v},i.comparedTo=function(v,C){return Ta(this,new U(v,C))},i.decimalPlaces=i.dp=function(v,C){var D,F,P,l=this;if(v!=null)return Ht(v,0,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v+l.e+1,C);if(!(D=l.c))return null;if(F=((P=D.length-1)-Nn(this.e/be))*be,P=D[P])for(;P%10==0;P/=10,F--);return F<0&&(F=0),F},i.dividedBy=i.div=function(v,C){return e(this,new U(v,C),o,u)},i.dividedToIntegerBy=i.idiv=function(v,C){return e(this,new U(v,C),0,1)},i.exponentiatedBy=i.pow=function(v,C){var D,F,P,l,g,y,E,S,_,M=this;if(v=new U(v),v.c&&!v.isInteger())throw Error(Qr+"Exponent not an integer: "+q(v));if(C!=null&&(C=new U(C)),y=v.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!v.c||!v.c[0])return _=new U(Math.pow(+q(M),y?v.s*(2-qd(v)):+q(v))),C?_.mod(C):_;if(E=v.s<0,C){if(C.c?!C.c[0]:!C.s)return new U(NaN);F=!E&&M.isInteger()&&C.isInteger(),F&&(M=M.mod(C))}else{if(v.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||y&&M.c[1]>=24e7:M.c[0]<8e13||y&&M.c[0]<=9999975e7)))return l=M.s<0&&qd(v)?-0:0,M.e>-1&&(l=1/l),new U(E?1/l:l);T&&(l=Cw(T/be+2))}for(y?(D=new U(.5),E&&(v.s=1),S=qd(v)):(P=Math.abs(+q(v)),S=P%2),_=new U(s);;){if(S){if(_=_.times(M),!_.c)break;l?_.c.length>l&&(_.c.length=l):F&&(_=_.mod(C))}if(P){if(P=Cn(P/2),P===0)break;S=P%2}else if(v=v.times(D),H(v,v.e+1,1),v.e>14)S=qd(v);else{if(P=+q(v),P===0)break;S=P%2}M=M.times(M),l?M.c&&M.c.length>l&&(M.c.length=l):F&&(M=M.mod(C))}return F?_:(E&&(_=s.div(_)),C?_.mod(C):l?H(_,T,u,g):_)},i.integerValue=function(v){var C=new U(this);return v==null?v=u:Ht(v,0,8),H(C,C.e+1,v)},i.isEqualTo=i.eq=function(v,C){return Ta(this,new U(v,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(v,C){return Ta(this,new U(v,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(v,C){return(C=Ta(this,new U(v,C)))===1||C===0},i.isInteger=function(){return!!this.c&&Nn(this.e/be)>this.c.length-2},i.isLessThan=i.lt=function(v,C){return Ta(this,new U(v,C))<0},i.isLessThanOrEqualTo=i.lte=function(v,C){return(C=Ta(this,new U(v,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(v,C){var D,F,P,l,g=this,y=g.s;if(v=new U(v,C),C=v.s,!y||!C)return new U(NaN);if(y!=C)return v.s=-C,g.plus(v);var E=g.e/be,S=v.e/be,_=g.c,M=v.c;if(!E||!S){if(!_||!M)return _?(v.s=-C,v):new U(M?g:NaN);if(!_[0]||!M[0])return M[0]?(v.s=-C,v):new U(_[0]?g:u==3?-0:0)}if(E=Nn(E),S=Nn(S),_=_.slice(),y=E-S){for((l=y<0)?(y=-y,P=_):(S=E,P=M),P.reverse(),C=y;C--;P.push(0));P.reverse()}else for(F=(l=(y=_.length)<(C=M.length))?y:C,y=C=0;C0)for(;C--;_[D++]=0);for(C=di-1;F>y;){if(_[--F]=0;){for(D=0,N=z[P]%$,m=z[P]/$|0,g=E,l=P+g;l>P;)S=j[--g]%$,_=j[g]/$|0,y=m*S+_*N,S=N*S+y%$*$+O[l]+D,D=(S/Y|0)+(y/$|0)+m*_,O[l--]=S%Y;O[l]=D}return D?++F:O.splice(0,1),k(v,O,F)},i.negated=function(){var v=new U(this);return v.s=-v.s||null,v},i.plus=function(v,C){var D,F=this,P=F.s;if(v=new U(v,C),C=v.s,!P||!C)return new U(NaN);if(P!=C)return v.s=-C,F.minus(v);var l=F.e/be,g=v.e/be,y=F.c,E=v.c;if(!l||!g){if(!y||!E)return new U(P/0);if(!y[0]||!E[0])return E[0]?v:new U(y[0]?F:P*0)}if(l=Nn(l),g=Nn(g),y=y.slice(),P=l-g){for(P>0?(g=l,D=E):(P=-P,D=y),D.reverse();P--;D.push(0));D.reverse()}for(P=y.length,C=E.length,P-C<0&&(D=E,E=y,y=D,C=P),P=0;C;)P=(y[--C]=y[C]+E[C]+P)/di|0,y[C]=di===y[C]?0:y[C]%di;return P&&(y=[P].concat(y),++g),k(v,y,g)},i.precision=i.sd=function(v,C){var D,F,P,l=this;if(v!=null&&v!==!!v)return Ht(v,1,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v,C);if(!(D=l.c))return null;if(P=D.length-1,F=P*be+1,P=D[P]){for(;P%10==0;P/=10,F--);for(P=D[0];P>=10;P/=10,F++);}return v&&l.e+1>F&&(F=l.e+1),F},i.shiftedBy=function(v){return Ht(v,-Nw,Nw),this.times("1e"+v)},i.squareRoot=i.sqrt=function(){var v,C,D,F,P,l=this,g=l.c,y=l.s,E=l.e,S=o+4,_=new U("0.5");if(y!==1||!g||!g[0])return new U(!y||y<0&&(!g||g[0])?NaN:g?l:1/0);if(y=Math.sqrt(+q(l)),y==0||y==1/0?(C=_n(g),(C.length+E)%2==0&&(C+="0"),y=Math.sqrt(+C),E=Nn((E+1)/2)-(E<0||E%2),y==1/0?C="5e"+E:(C=y.toExponential(),C=C.slice(0,C.indexOf("e")+1)+E),D=new U(C)):D=new U(y+""),D.c[0]){for(E=D.e,y=E+S,y<3&&(y=0);;)if(P=D,D=_.times(P.plus(e(l,P,S,1))),_n(P.c).slice(0,y)===(C=_n(D.c)).slice(0,y))if(D.e0&&O>0){for(l=O%y||y,_=m.substr(0,l);l0&&(_+=S+m.slice(l)),N&&(_="-"+_)}F=M?_+(D.decimalSeparator||"")+((E=+D.fractionGroupSize)?M.replace(new RegExp("\\d{"+E+"}\\B","g"),"$&"+(D.fractionGroupSeparator||"")):M):_}return(D.prefix||"")+F+(D.suffix||"")},i.toFraction=function(v){var C,D,F,P,l,g,y,E,S,_,M,N,m=this,O=m.c;if(v!=null&&(y=new U(v),!y.isInteger()&&(y.c||y.s!==1)||y.lt(s)))throw Error(Qr+"Argument "+(y.isInteger()?"out of range: ":"not an integer: ")+q(y));if(!O)return new U(m);for(C=new U(s),S=D=new U(s),F=E=new U(s),N=_n(O),l=C.e=N.length-m.e-1,C.c[0]=xw[(g=l%be)<0?be+g:g],v=!v||y.comparedTo(C)>0?l>0?C:S:y,g=d,d=1/0,y=new U(N),E.c[0]=0;_=e(y,C,0,1),P=D.plus(_.times(F)),P.comparedTo(v)!=1;)D=F,F=P,S=E.plus(_.times(P=S)),E=P,C=y.minus(_.times(P=C)),y=P;return P=e(v.minus(D),F,0,1),E=E.plus(P.times(S)),D=D.plus(P.times(F)),E.s=S.s=m.s,l=l*2,M=e(S,F,l,u).minus(m).abs().comparedTo(e(E,D,l,u).minus(m).abs())<1?[S,F]:[E,D],d=g,M},i.toNumber=function(){return+q(this)},i.toPrecision=function(v,C){return v!=null&&Ht(v,1,mr),Q(this,v,C,2)},i.toString=function(v){var C,D=this,F=D.s,P=D.e;return P===null?F?(C="Infinity",F<0&&(C="-"+C)):C="NaN":(v==null?C=P<=a||P>=c?Vd(_n(D.c),P):Os(_n(D.c),P,"0"):v===10&&V?(D=H(new U(D),o+P+1,u),C=Os(_n(D.c),D.e,"0")):(Ht(v,2,R.length,"Base"),C=r(Os(_n(D.c),P,"0"),10,v,F,!0)),F<0&&D.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return q(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&U.set(t),U}function Nn(t){var e=t|0;return t>0||t===e?e:e-1}function _n(t){for(var e,r,n=1,i=t.length,s=t[0]+"";nc^r?1:-1;for(u=(a=i.length)<(c=s.length)?a:c,o=0;os[o]^r?1:-1;return a==c?0:a>c^r?1:-1}function Ht(t,e,r,n){if(tr||t!==Cn(t))throw Error(Qr+(n||"Argument")+(typeof t=="number"?tr?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function qd(t){var e=t.c.length-1;return Nn(t.e/be)==e&&t.c[e]%2!=0}function Vd(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Os(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e{h();Kk=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Cw=Math.ceil,Cn=Math.floor,Qr="[BigNumber Error] ",F3=Qr+"Number primitive has more than 15 significant digits: ",di=1e14,be=14,Nw=9007199254740991,xw=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],so=1e7,mr=1e9;q3=U3(),Ou=q3});var Ie=B(ce=>{"use strict";h();Object.defineProperty(ce,"__esModule",{value:!0});ce.ErrParseTransactionOutcome=ce.ErrInvalidInnerTransaction=ce.ErrBadUsage=ce.ErrInvalidTokenIdentifier=ce.ErrIsCompletedFieldIsMissingOnTransaction=ce.ErrGasLimitShouldBe0ForInnerTransaction=ce.ErrInvalidRelayedV2BuilderArguments=ce.ErrInvalidRelayedV1BuilderArguments=ce.ErrNotImplemented=ce.ErrContractInteraction=ce.ErrCodec=ce.ErrCannotParseTransactionOutcome=ce.ErrCannotParseContractResults=ce.ErrMissingFieldOnEnum=ce.ErrMissingFieldOnStruct=ce.ErrTypingSystem=ce.ErrMock=ce.ErrContractHasNoAddress=ce.ErrContract=ce.ErrExpectedTransactionEventsNotFound=ce.ErrExpectedTransactionStatusNotReached=ce.ErrTransactionWatcherTimeout=ce.ErrAsyncTimerAborted=ce.ErrAsyncTimerAlreadyRunning=ce.ErrInvalidFunctionName=ce.ErrSignatureCannotCreate=ce.ErrTransactionOptionsInvalid=ce.ErrTransactionVersionInvalid=ce.ErrNonceInvalid=ce.ErrNotEnoughGas=ce.ErrAddressEmpty=ce.ErrAddressBadHrp=ce.ErrAddressCannotCreate=ce.ErrUnexpectedCondition=ce.ErrInvariantFailed=ce.ErrBadType=ce.ErrUnsupportedOperation=ce.ErrInvalidArgument=ce.Err=void 0;var Ce=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};ce.Err=Ce;var Ow=class extends Ce{constructor(e,r){super(`Invalid argument: ${e}`,r)}};ce.ErrInvalidArgument=Ow;var Dw=class extends Ce{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};ce.ErrUnsupportedOperation=Dw;var Pw=class extends Ce{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};ce.ErrBadType=Pw;var Rw=class extends Ce{constructor(e){super(`Invariant failed: [${e}]`)}};ce.ErrInvariantFailed=Rw;var Bw=class extends Ce{constructor(e){super(`Unexpected condition: [${e}]`)}};ce.ErrUnexpectedCondition=Bw;var Mw=class extends Ce{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};ce.ErrAddressCannotCreate=Mw;var Lw=class extends Ce{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};ce.ErrAddressBadHrp=Lw;var Fw=class extends Ce{constructor(){super("Address is empty")}};ce.ErrAddressEmpty=Fw;var Uw=class extends Ce{constructor(e){super(`Not enough gas provided: ${e}`)}};ce.ErrNotEnoughGas=Uw;var qw=class extends Ce{constructor(e){super(`Invalid nonce: ${e}`)}};ce.ErrNonceInvalid=qw;var Vw=class extends Ce{constructor(e){super(`Invalid transaction version: ${e}`)}};ce.ErrTransactionVersionInvalid=Vw;var kw=class extends Ce{constructor(e){super(`Invalid transaction options: ${e}`)}};ce.ErrTransactionOptionsInvalid=kw;var Hw=class extends Ce{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};ce.ErrSignatureCannotCreate=Hw;var Gw=class extends Ce{constructor(){super("Invalid function name")}};ce.ErrInvalidFunctionName=Gw;var jw=class extends Ce{constructor(){super("Async timer already running")}};ce.ErrAsyncTimerAlreadyRunning=jw;var zw=class extends Ce{constructor(){super("Async timer aborted")}};ce.ErrAsyncTimerAborted=zw;var Qw=class extends Ce{constructor(){super("TransactionWatcher has timed out")}};ce.ErrTransactionWatcherTimeout=Qw;var Kw=class extends Ce{constructor(){super("Expected transaction status not reached")}};ce.ErrExpectedTransactionStatusNotReached=Kw;var Ww=class extends Ce{constructor(){super("Expected transaction events not found")}};ce.ErrExpectedTransactionEventsNotFound=Ww;var kd=class extends Ce{constructor(e){super(e)}};ce.ErrContract=kd;var $w=class extends kd{constructor(){super(` +var Ik=Object.create;var Dd=Object.defineProperty;var Tk=Object.getOwnPropertyDescriptor;var _k=Object.getOwnPropertyNames;var Ck=Object.getPrototypeOf,Nk=Object.prototype.hasOwnProperty;var Pd=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bt=(t,e)=>{for(var r in e)Dd(t,r,{get:e[r],enumerable:!0})},Od=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _k(e))!Nk.call(t,i)&&i!==r&&Dd(t,i,{get:()=>e[i],enumerable:!(n=Tk(e,i))||n.enumerable});return t},Tr=(t,e,r)=>(Od(t,e,"default"),r&&Od(r,e,"default")),pe=(t,e,r)=>(r=t!=null?Ik(Ck(t)):{},Od(e||!t||!t.__esModule?Dd(r,"default",{value:t,enumerable:!0}):r,t)),_e=t=>Od(Dd({},"__esModule",{value:!0}),t);var y3=D(Rd=>{"use strict";h();Rd.byteLength=Ok;Rd.toByteArray=Pk;Rd.fromByteArray=Mk;var Pi=[],Tn=[],xk=typeof Uint8Array<"u"?Uint8Array:Array,yw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ea=0,p3=yw.length;Ea0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Ok(t){var e=m3(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Dk(t,e,r){return(e+r)*3/4-r}function Pk(t){var e,r=m3(t),n=r[0],i=r[1],s=new xk(Dk(t,n,i)),o=0,u=i>0?n-4:n,a;for(a=0;a>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Tn[t.charCodeAt(a)]<<2|Tn[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=Tn[t.charCodeAt(a)]<<10|Tn[t.charCodeAt(a+1)]<<4|Tn[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Rk(t){return Pi[t>>18&63]+Pi[t>>12&63]+Pi[t>>6&63]+Pi[t&63]}function Bk(t,e,r){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=t[r-1],i.push(Pi[e>>2]+Pi[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Pi[e>>10]+Pi[e>>4&63]+Pi[e<<2&63]+"=")),i.join("")}});var w3=D(ww=>{h();ww.read=function(t,e,r,n,i){var s,o,u=i*8-n-1,a=(1<>1,f=-7,d=r?i-1:0,w=r?-1:1,A=t[e+d];for(d+=w,s=A&(1<<-f)-1,A>>=-f,f+=u;f>0;s=s*256+t[e+d],d+=w,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=n;f>0;o=o*256+t[e+d],d+=w,f-=8);if(s===0)s=1-c;else{if(s===a)return o?NaN:(A?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-c}return(A?-1:1)*o*Math.pow(2,s-n)};ww.write=function(t,e,r,n,i,s){var o,u,a,c=s*8-i-1,f=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:s-1,T=n?1:-1,x=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=f):(o=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+d>=1?e+=w/a:e+=w*Math.pow(2,1-d),e*a>=2&&(o++,a/=2),o+d>=f?(u=0,o=f):o+d>=1?(u=(e*a-1)*Math.pow(2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+A]=u&255,A+=T,u/=256,i-=8);for(o=o<0;t[r+A]=o&255,A+=T,o/=256,c-=8);t[r+A-T]|=x*128}});var io=D(Nu=>{"use strict";h();var vw=y3(),Cu=w3(),v3=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Nu.Buffer=X;Nu.SlowBuffer=kk;Nu.INSPECT_MAX_BYTES=50;var Bd=2147483647;Nu.kMaxLength=Bd;X.TYPED_ARRAY_SUPPORT=Lk();!X.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 Lk(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(X.prototype,"parent",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.buffer}});Object.defineProperty(X.prototype,"offset",{enumerable:!0,get:function(){if(X.isBuffer(this))return this.byteOffset}});function Cs(t){if(t>Bd)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,X.prototype),e}function X(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Sw(t)}return b3(t,e,r)}X.poolSize=8192;function b3(t,e,r){if(typeof t=="string")return Uk(t,e);if(ArrayBuffer.isView(t))return qk(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Ri(t,ArrayBuffer)||t&&Ri(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ri(t,SharedArrayBuffer)||t&&Ri(t.buffer,SharedArrayBuffer)))return Ew(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return X.from(n,e,r);var i=Vk(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return X.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}X.from=function(t,e,r){return b3(t,e,r)};Object.setPrototypeOf(X.prototype,Uint8Array.prototype);Object.setPrototypeOf(X,Uint8Array);function S3(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function Fk(t,e,r){return S3(t),t<=0?Cs(t):e!==void 0?typeof r=="string"?Cs(t).fill(e,r):Cs(t).fill(e):Cs(t)}X.alloc=function(t,e,r){return Fk(t,e,r)};function Sw(t){return S3(t),Cs(t<0?0:Iw(t)|0)}X.allocUnsafe=function(t){return Sw(t)};X.allocUnsafeSlow=function(t){return Sw(t)};function Uk(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!X.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=I3(t,e)|0,n=Cs(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function Aw(t){for(var e=t.length<0?0:Iw(t.length)|0,r=Cs(e),n=0;n=Bd)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Bd.toString(16)+" bytes");return t|0}function kk(t){return+t!=t&&(t=0),X.alloc(+t)}X.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==X.prototype};X.compare=function(e,r){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),Ri(r,Uint8Array)&&(r=X.from(r,r.offset,r.byteLength)),!X.isBuffer(e)||!X.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,s=0,o=Math.min(n,i);si.length?X.from(o).copy(i,s):Uint8Array.prototype.set.call(i,o,s);else if(X.isBuffer(o))o.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=o.length}return i};function I3(t,e){if(X.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ri(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return bw(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return O3(t).length;default:if(i)return n?-1:bw(t).length;e=(""+e).toLowerCase(),i=!0}}X.byteLength=I3;function Hk(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return Xk(this,e,r);case"utf8":case"utf-8":return _3(this,e,r);case"ascii":return Yk(this,e,r);case"latin1":case"binary":return Jk(this,e,r);case"base64":return Wk(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Zk(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}X.prototype._isBuffer=!0;function ba(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}X.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;rr&&(e+=" ... "),""};v3&&(X.prototype[v3]=X.prototype.inspect);X.prototype.compare=function(e,r,n,i,s){if(Ri(e,Uint8Array)&&(e=X.from(e,e.offset,e.byteLength)),!X.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;for(var o=s-i,u=n-r,a=Math.min(o,u),c=this.slice(i,s),f=e.slice(r,n),d=0;d2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Tw(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=X.from(e,n)),X.isBuffer(e))return e.length===0?-1:A3(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):A3(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function A3(t,e,r,n,i){var s=1,o=t.length,u=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,o/=2,u/=2,r/=2}function a(A,T){return s===1?A[T]:A.readUInt16BE(T*s)}var c;if(i){var f=-1;for(c=r;co&&(r=o-u),c=r;c>=0;c--){for(var d=!0,w=0;wi&&(n=i)):n=i;var s=e.length;n>s/2&&(n=s/2);for(var o=0;o>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return Gk(this,e,r,n);case"utf8":case"utf-8":return jk(this,e,r,n);case"ascii":case"latin1":case"binary":return zk(this,e,r,n);case"base64":return Qk(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Kk(this,e,r,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}};X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Wk(t,e,r){return e===0&&r===t.length?vw.fromByteArray(t):vw.fromByteArray(t.slice(e,r))}function _3(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:s>223?3:s>191?2:1;if(i+u<=r){var a,c,f,d;switch(u){case 1:s<128&&(o=s);break;case 2:a=t[i+1],(a&192)===128&&(d=(s&31)<<6|a&63,d>127&&(o=d));break;case 3:a=t[i+1],c=t[i+2],(a&192)===128&&(c&192)===128&&(d=(s&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(o=d));break;case 4:a=t[i+1],c=t[i+2],f=t[i+3],(a&192)===128&&(c&192)===128&&(f&192)===128&&(d=(s&15)<<18|(a&63)<<12|(c&63)<<6|f&63,d>65535&&d<1114112&&(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),i+=u}return $k(n)}var E3=4096;function $k(t){var e=t.length;if(e<=E3)return String.fromCharCode.apply(String,t);for(var r="",n=0;nn)&&(r=n);for(var i="",s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}X.prototype.readUintLE=X.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e+--r],s=1;r>0&&(s*=256);)i+=this[e+--r]*s;return i};X.prototype.readUint8=X.prototype.readUInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]};X.prototype.readUint16LE=X.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]|this[e+1]<<8};X.prototype.readUint16BE=X.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||pr(e,2,this.length),this[e]<<8|this[e+1]};X.prototype.readUint32LE=X.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};X.prototype.readUint32BE=X.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};X.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=this[e],s=1,o=0;++o=s&&(i-=Math.pow(2,8*r)),i};X.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||pr(e,r,this.length);for(var i=r,s=1,o=this[e+--i];i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*r)),o};X.prototype.readInt8=function(e,r){return e=e>>>0,r||pr(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};X.prototype.readInt16LE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};X.prototype.readInt16BE=function(e,r){e=e>>>0,r||pr(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};X.prototype.readInt32LE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};X.prototype.readInt32BE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};X.prototype.readFloatLE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!0,23,4)};X.prototype.readFloatBE=function(e,r){return e=e>>>0,r||pr(e,4,this.length),Cu.read(this,e,!1,23,4)};X.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!0,52,8)};X.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||pr(e,8,this.length),Cu.read(this,e,!1,52,8)};function zr(t,e,r,n,i,s){if(!X.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}X.prototype.writeUintLE=X.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=1,u=0;for(this[r]=e&255;++u>>0,n=n>>>0,!i){var s=Math.pow(2,8*n)-1;zr(this,e,r,n,s,0)}var o=n-1,u=1;for(this[r+o]=e&255;--o>=0&&(u*=256);)this[r+o]=e/u&255;return r+n};X.prototype.writeUint8=X.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,255,0),this[r]=e&255,r+1};X.prototype.writeUint16LE=X.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeUint16BE=X.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeUint32LE=X.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};X.prototype.writeUint32BE=X.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};X.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=0,u=1,a=0;for(this[r]=e&255;++o>0)-a&255;return r+n};X.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var s=Math.pow(2,8*n-1);zr(this,e,r,n,s-1,-s)}var o=n-1,u=1,a=0;for(this[r+o]=e&255;--o>=0&&(u*=256);)e<0&&a===0&&this[r+o+1]!==0&&(a=1),this[r+o]=(e/u>>0)-a&255;return r+n};X.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};X.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};X.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};X.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};X.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||zr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function C3(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function N3(t,e,r,n,i){return e=+e,r=r>>>0,i||C3(t,e,r,4,34028234663852886e22,-34028234663852886e22),Cu.write(t,e,r,n,23,4),r+4}X.prototype.writeFloatLE=function(e,r,n){return N3(this,e,r,!0,n)};X.prototype.writeFloatBE=function(e,r,n){return N3(this,e,r,!1,n)};function x3(t,e,r,n,i){return e=+e,r=r>>>0,i||C3(t,e,r,8,17976931348623157e292,-17976931348623157e292),Cu.write(t,e,r,n,52,8),r+8}X.prototype.writeDoubleLE=function(e,r,n){return x3(this,e,r,!0,n)};X.prototype.writeDoubleBE=function(e,r,n){return x3(this,e,r,!1,n)};X.prototype.copy=function(e,r,n,i){if(!X.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=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),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var o;if(typeof e=="number")for(o=r;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function rH(t){for(var e=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function O3(t){return vw.toByteArray(tH(t))}function Md(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Ri(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function Tw(t){return t!==t}var iH=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var M3=D((ape,B3)=>{h();var Wt=B3.exports={},Bi,Mi;function _w(){throw new Error("setTimeout has not been defined")}function Cw(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Bi=setTimeout:Bi=_w}catch{Bi=_w}try{typeof clearTimeout=="function"?Mi=clearTimeout:Mi=Cw}catch{Mi=Cw}})();function D3(t){if(Bi===setTimeout)return setTimeout(t,0);if((Bi===_w||!Bi)&&setTimeout)return Bi=setTimeout,setTimeout(t,0);try{return Bi(t,0)}catch{try{return Bi.call(null,t,0)}catch{return Bi.call(this,t,0)}}}function sH(t){if(Mi===clearTimeout)return clearTimeout(t);if((Mi===Cw||!Mi)&&clearTimeout)return Mi=clearTimeout,clearTimeout(t);try{return Mi(t)}catch{try{return Mi.call(null,t)}catch{return Mi.call(this,t)}}}var Ns=[],xu=!1,Sa,Ld=-1;function oH(){!xu||!Sa||(xu=!1,Sa.length?Ns=Sa.concat(Ns):Ld=-1,Ns.length&&P3())}function P3(){if(!xu){var t=D3(oH);xu=!0;for(var e=Ns.length;e;){for(Sa=Ns,Ns=[];++Ld1)for(var r=1;r{p=pe(io()),S=pe(M3()),aH=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object),global=aH});var fr={};Bt(fr,{BigNumber:()=>U3,default:()=>Ou});function F3(t){var e,r,n,i=U.prototype={constructor:U,toString:null,valueOf:null},s=new U(1),o=20,u=4,a=-7,c=21,f=-1e7,d=1e7,w=!1,A=1,T=0,x={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},B="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function U(v,C){var P,F,R,l,g,y,E,I,_=this;if(!(_ instanceof U))return new U(v,C);if(C==null){if(v&&v._isBigNumber===!0){_.s=v.s,!v.c||v.e>d?_.c=_.e=null:v.e=10;g/=10,l++);l>d?_.c=_.e=null:(_.e=l,_.c=[v]);return}I=String(v)}else{if(!uH.test(I=String(v)))return n(_,I,y);_.s=I.charCodeAt(0)==45?(I=I.slice(1),-1):1}(l=I.indexOf("."))>-1&&(I=I.replace(".","")),(g=I.search(/e/i))>0?(l<0&&(l=g),l+=+I.slice(g+1),I=I.substring(0,g)):l<0&&(l=I.length)}else{if(Ht(C,2,B.length,"Base"),C==10&&V)return _=new U(v),H(_,o+_.e+1,u);if(I=String(v),y=typeof v=="number"){if(v*0!=0)return n(_,I,y,C);if(_.s=1/v<0?(I=I.slice(1),-1):1,U.DEBUG&&I.replace(/^0\.0*|\./,"").length>15)throw Error(L3+v)}else _.s=I.charCodeAt(0)===45?(I=I.slice(1),-1):1;for(P=B.slice(0,C),l=g=0,E=I.length;gl){l=E;continue}}else if(!R&&(I==I.toUpperCase()&&(I=I.toLowerCase())||I==I.toLowerCase()&&(I=I.toUpperCase()))){R=!0,g=-1,l=0;continue}return n(_,String(v),y,C)}y=!1,I=r(I,C,10,_.s),(l=I.indexOf("."))>-1?I=I.replace(".",""):l=I.length}for(g=0;I.charCodeAt(g)===48;g++);for(E=I.length;I.charCodeAt(--E)===48;);if(I=I.slice(g,++E)){if(E-=g,y&&U.DEBUG&&E>15&&(v>xw||v!==Cn(v)))throw Error(L3+_.s*v);if((l=l-g-1)>d)_.c=_.e=null;else if(l=-mr&&R<=mr&&R===Cn(R)){if(F[0]===0){if(R===0&&F.length===1)return!0;break e}if(C=(R+1)%be,C<1&&(C+=be),String(F[0]).length==C){for(C=0;C=di||P!==Cn(P))break e;if(P!==0)return!0}}}else if(F===null&&R===null&&(l===null||l===1||l===-1))return!0;throw Error(Qr+"Invalid BigNumber: "+v)},U.maximum=U.max=function(){return L(arguments,-1)},U.minimum=U.min=function(){return L(arguments,1)},U.random=function(){var v=9007199254740992,C=Math.random()*v&2097151?function(){return Cn(Math.random()*v)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(P){var F,R,l,g,y,E=0,I=[],_=new U(s);if(P==null?P=o:Ht(P,0,mr),g=Nw(P/be),w)if(crypto.getRandomValues){for(F=crypto.getRandomValues(new Uint32Array(g*=2));E>>11),y>=9e15?(R=crypto.getRandomValues(new Uint32Array(2)),F[E]=R[0],F[E+1]=R[1]):(I.push(y%1e14),E+=2);E=g/2}else if(crypto.randomBytes){for(F=crypto.randomBytes(g*=7);E=9e15?crypto.randomBytes(7).copy(F,E):(I.push(y%1e14),E+=7);E=g/7}else throw w=!1,Error(Qr+"crypto unavailable");if(!w)for(;E=10;y/=10,E++);ER-1&&(y[g+1]==null&&(y[g+1]=0),y[g+1]+=y[g]/R|0,y[g]%=R)}return y.reverse()}return function(P,F,R,l,g){var y,E,I,_,M,N,m,O,Y=P.indexOf("."),$=o,b=u;for(Y>=0&&(_=T,T=0,P=P.replace(".",""),O=new U(F),N=O.pow(P.length-Y),T=_,O.c=C(Os(_n(N.c),N.e,"0"),10,R,v),O.e=O.c.length),m=C(P,F,R,g?(y=B,v):(y=v,B)),I=_=m.length;m[--_]==0;m.pop());if(!m[0])return y.charAt(0);if(Y<0?--I:(N.c=m,N.e=I,N.s=l,N=e(N,O,$,b,R),m=N.c,M=N.r,I=N.e),E=I+$+1,Y=m[E],_=R/2,M=M||E<0||m[E+1]!=null,M=b<4?(Y!=null||M)&&(b==0||b==(N.s<0?3:2)):Y>_||Y==_&&(b==4||M||b==6&&m[E-1]&1||b==(N.s<0?8:7)),E<1||!m[0])P=M?Os(y.charAt(1),-$,y.charAt(0)):y.charAt(0);else{if(m.length=E,M)for(--R;++m[--E]>R;)m[E]=0,E||(++I,m=[1].concat(m));for(_=m.length;!m[--_];);for(Y=0,P="";Y<=_;P+=y.charAt(m[Y++]));P=Os(P,I,y.charAt(0))}return P}}(),e=function(){function v(F,R,l){var g,y,E,I,_=0,M=F.length,N=R%so,m=R/so|0;for(F=F.slice();M--;)E=F[M]%so,I=F[M]/so|0,g=m*E+I*N,y=N*E+g%so*so+_,_=(y/l|0)+(g/so|0)+m*I,F[M]=y%l;return _&&(F=[_].concat(F)),F}function C(F,R,l,g){var y,E;if(l!=g)E=l>g?1:-1;else for(y=E=0;yR[y]?1:-1;break}return E}function P(F,R,l,g){for(var y=0;l--;)F[l]-=y,y=F[l]1;F.splice(0,1));}return function(F,R,l,g,y){var E,I,_,M,N,m,O,Y,$,b,j,z,W,ie,te,ee,se,oe=F.s==R.s?1:-1,J=F.c,ue=R.c;if(!J||!J[0]||!ue||!ue[0])return new U(!F.s||!R.s||(J?ue&&J[0]==ue[0]:!ue)?NaN:J&&J[0]==0||!ue?oe*0:oe/0);for(Y=new U(oe),$=Y.c=[],I=F.e-R.e,oe=l+I+1,y||(y=di,I=Nn(F.e/be)-Nn(R.e/be),oe=oe/be|0),_=0;ue[_]==(J[_]||0);_++);if(ue[_]>(J[_]||0)&&I--,oe<0)$.push(1),M=!0;else{for(ie=J.length,ee=ue.length,_=0,oe+=2,N=Cn(y/(ue[0]+1)),N>1&&(ue=v(ue,N,y),J=v(J,N,y),ee=ue.length,ie=J.length),W=ee,b=J.slice(0,ee),j=b.length;j=y/2&&te++;do{if(N=0,E=C(ue,b,ee,j),E<0){if(z=b[0],ee!=j&&(z=z*y+(b[1]||0)),N=Cn(z/te),N>1)for(N>=y&&(N=y-1),m=v(ue,N,y),O=m.length,j=b.length;C(m,b,O,j)==1;)N--,P(m,ee=10;oe/=10,_++);H(Y,l+(Y.e=_+I*be-1)+1,g,M)}else Y.e=I,Y.r=+M;return Y}}();function Q(v,C,P,F){var R,l,g,y,E;if(P==null?P=u:Ht(P,0,8),!v.c)return v.toString();if(R=v.c[0],g=v.e,C==null)E=_n(v.c),E=F==1||F==2&&(g<=a||g>=c)?Ud(E,g):Os(E,g,"0");else if(v=H(new U(v),C,P),l=v.e,E=_n(v.c),y=E.length,F==1||F==2&&(C<=l||l<=a)){for(;yy){if(--C>0)for(E+=".";C--;E+="0");}else if(C+=l-y,C>0)for(l+1==y&&(E+=".");C--;E+="0");return v.s<0&&R?"-"+E:E}function L(v,C){for(var P,F,R=1,l=new U(v[0]);R=10;R/=10,F++);return(P=F+P*be-1)>d?v.c=v.e=null:P=10;y/=10,R++);if(l=C-R,l<0)l+=be,g=C,E=M[I=0],_=Cn(E/N[R-g-1]%10);else if(I=Nw((l+1)/be),I>=M.length)if(F){for(;M.length<=I;M.push(0));E=_=0,R=1,l%=be,g=l-be+1}else break e;else{for(E=y=M[I],R=1;y>=10;y/=10,R++);l%=be,g=l-be+R,_=g<0?0:Cn(E/N[R-g-1]%10)}if(F=F||C<0||M[I+1]!=null||(g<0?E:E%N[R-g-1]),F=P<4?(_||F)&&(P==0||P==(v.s<0?3:2)):_>5||_==5&&(P==4||F||P==6&&(l>0?g>0?E/N[R-g]:0:M[I-1])%10&1||P==(v.s<0?8:7)),C<1||!M[0])return M.length=0,F?(C-=v.e+1,M[0]=N[(be-C%be)%be],v.e=-C||0):M[0]=v.e=0,v;if(l==0?(M.length=I,y=1,I--):(M.length=I+1,y=N[be-l],M[I]=g>0?Cn(E/N[R-g]%N[g])*y:0),F)for(;;)if(I==0){for(l=1,g=M[0];g>=10;g/=10,l++);for(g=M[0]+=y,y=1;g>=10;g/=10,y++);l!=y&&(v.e++,M[0]==di&&(M[0]=1));break}else{if(M[I]+=y,M[I]!=di)break;M[I--]=0,y=1}for(l=M.length;M[--l]===0;M.pop());}v.e>d?v.c=v.e=null:v.e=c?Ud(C,P):Os(C,P,"0"),v.s<0?"-"+C:C)}return i.absoluteValue=i.abs=function(){var v=new U(this);return v.s<0&&(v.s=1),v},i.comparedTo=function(v,C){return Ia(this,new U(v,C))},i.decimalPlaces=i.dp=function(v,C){var P,F,R,l=this;if(v!=null)return Ht(v,0,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v+l.e+1,C);if(!(P=l.c))return null;if(F=((R=P.length-1)-Nn(this.e/be))*be,R=P[R])for(;R%10==0;R/=10,F--);return F<0&&(F=0),F},i.dividedBy=i.div=function(v,C){return e(this,new U(v,C),o,u)},i.dividedToIntegerBy=i.idiv=function(v,C){return e(this,new U(v,C),0,1)},i.exponentiatedBy=i.pow=function(v,C){var P,F,R,l,g,y,E,I,_,M=this;if(v=new U(v),v.c&&!v.isInteger())throw Error(Qr+"Exponent not an integer: "+q(v));if(C!=null&&(C=new U(C)),y=v.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!v.c||!v.c[0])return _=new U(Math.pow(+q(M),y?v.s*(2-Fd(v)):+q(v))),C?_.mod(C):_;if(E=v.s<0,C){if(C.c?!C.c[0]:!C.s)return new U(NaN);F=!E&&M.isInteger()&&C.isInteger(),F&&(M=M.mod(C))}else{if(v.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||y&&M.c[1]>=24e7:M.c[0]<8e13||y&&M.c[0]<=9999975e7)))return l=M.s<0&&Fd(v)?-0:0,M.e>-1&&(l=1/l),new U(E?1/l:l);T&&(l=Nw(T/be+2))}for(y?(P=new U(.5),E&&(v.s=1),I=Fd(v)):(R=Math.abs(+q(v)),I=R%2),_=new U(s);;){if(I){if(_=_.times(M),!_.c)break;l?_.c.length>l&&(_.c.length=l):F&&(_=_.mod(C))}if(R){if(R=Cn(R/2),R===0)break;I=R%2}else if(v=v.times(P),H(v,v.e+1,1),v.e>14)I=Fd(v);else{if(R=+q(v),R===0)break;I=R%2}M=M.times(M),l?M.c&&M.c.length>l&&(M.c.length=l):F&&(M=M.mod(C))}return F?_:(E&&(_=s.div(_)),C?_.mod(C):l?H(_,T,u,g):_)},i.integerValue=function(v){var C=new U(this);return v==null?v=u:Ht(v,0,8),H(C,C.e+1,v)},i.isEqualTo=i.eq=function(v,C){return Ia(this,new U(v,C))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(v,C){return Ia(this,new U(v,C))>0},i.isGreaterThanOrEqualTo=i.gte=function(v,C){return(C=Ia(this,new U(v,C)))===1||C===0},i.isInteger=function(){return!!this.c&&Nn(this.e/be)>this.c.length-2},i.isLessThan=i.lt=function(v,C){return Ia(this,new U(v,C))<0},i.isLessThanOrEqualTo=i.lte=function(v,C){return(C=Ia(this,new U(v,C)))===-1||C===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(v,C){var P,F,R,l,g=this,y=g.s;if(v=new U(v,C),C=v.s,!y||!C)return new U(NaN);if(y!=C)return v.s=-C,g.plus(v);var E=g.e/be,I=v.e/be,_=g.c,M=v.c;if(!E||!I){if(!_||!M)return _?(v.s=-C,v):new U(M?g:NaN);if(!_[0]||!M[0])return M[0]?(v.s=-C,v):new U(_[0]?g:u==3?-0:0)}if(E=Nn(E),I=Nn(I),_=_.slice(),y=E-I){for((l=y<0)?(y=-y,R=_):(I=E,R=M),R.reverse(),C=y;C--;R.push(0));R.reverse()}else for(F=(l=(y=_.length)<(C=M.length))?y:C,y=C=0;C0)for(;C--;_[P++]=0);for(C=di-1;F>y;){if(_[--F]=0;){for(P=0,N=z[R]%$,m=z[R]/$|0,g=E,l=R+g;l>R;)I=j[--g]%$,_=j[g]/$|0,y=m*I+_*N,I=N*I+y%$*$+O[l]+P,P=(I/Y|0)+(y/$|0)+m*_,O[l--]=I%Y;O[l]=P}return P?++F:O.splice(0,1),k(v,O,F)},i.negated=function(){var v=new U(this);return v.s=-v.s||null,v},i.plus=function(v,C){var P,F=this,R=F.s;if(v=new U(v,C),C=v.s,!R||!C)return new U(NaN);if(R!=C)return v.s=-C,F.minus(v);var l=F.e/be,g=v.e/be,y=F.c,E=v.c;if(!l||!g){if(!y||!E)return new U(R/0);if(!y[0]||!E[0])return E[0]?v:new U(y[0]?F:R*0)}if(l=Nn(l),g=Nn(g),y=y.slice(),R=l-g){for(R>0?(g=l,P=E):(R=-R,P=y),P.reverse();R--;P.push(0));P.reverse()}for(R=y.length,C=E.length,R-C<0&&(P=E,E=y,y=P,C=R),R=0;C;)R=(y[--C]=y[C]+E[C]+R)/di|0,y[C]=di===y[C]?0:y[C]%di;return R&&(y=[R].concat(y),++g),k(v,y,g)},i.precision=i.sd=function(v,C){var P,F,R,l=this;if(v!=null&&v!==!!v)return Ht(v,1,mr),C==null?C=u:Ht(C,0,8),H(new U(l),v,C);if(!(P=l.c))return null;if(R=P.length-1,F=R*be+1,R=P[R]){for(;R%10==0;R/=10,F--);for(R=P[0];R>=10;R/=10,F++);}return v&&l.e+1>F&&(F=l.e+1),F},i.shiftedBy=function(v){return Ht(v,-xw,xw),this.times("1e"+v)},i.squareRoot=i.sqrt=function(){var v,C,P,F,R,l=this,g=l.c,y=l.s,E=l.e,I=o+4,_=new U("0.5");if(y!==1||!g||!g[0])return new U(!y||y<0&&(!g||g[0])?NaN:g?l:1/0);if(y=Math.sqrt(+q(l)),y==0||y==1/0?(C=_n(g),(C.length+E)%2==0&&(C+="0"),y=Math.sqrt(+C),E=Nn((E+1)/2)-(E<0||E%2),y==1/0?C="5e"+E:(C=y.toExponential(),C=C.slice(0,C.indexOf("e")+1)+E),P=new U(C)):P=new U(y+""),P.c[0]){for(E=P.e,y=E+I,y<3&&(y=0);;)if(R=P,P=_.times(R.plus(e(l,R,I,1))),_n(R.c).slice(0,y)===(C=_n(P.c)).slice(0,y))if(P.e0&&O>0){for(l=O%y||y,_=m.substr(0,l);l0&&(_+=I+m.slice(l)),N&&(_="-"+_)}F=M?_+(P.decimalSeparator||"")+((E=+P.fractionGroupSize)?M.replace(new RegExp("\\d{"+E+"}\\B","g"),"$&"+(P.fractionGroupSeparator||"")):M):_}return(P.prefix||"")+F+(P.suffix||"")},i.toFraction=function(v){var C,P,F,R,l,g,y,E,I,_,M,N,m=this,O=m.c;if(v!=null&&(y=new U(v),!y.isInteger()&&(y.c||y.s!==1)||y.lt(s)))throw Error(Qr+"Argument "+(y.isInteger()?"out of range: ":"not an integer: ")+q(y));if(!O)return new U(m);for(C=new U(s),I=P=new U(s),F=E=new U(s),N=_n(O),l=C.e=N.length-m.e-1,C.c[0]=Ow[(g=l%be)<0?be+g:g],v=!v||y.comparedTo(C)>0?l>0?C:I:y,g=d,d=1/0,y=new U(N),E.c[0]=0;_=e(y,C,0,1),R=P.plus(_.times(F)),R.comparedTo(v)!=1;)P=F,F=R,I=E.plus(_.times(R=I)),E=R,C=y.minus(_.times(R=C)),y=R;return R=e(v.minus(P),F,0,1),E=E.plus(R.times(I)),P=P.plus(R.times(F)),E.s=I.s=m.s,l=l*2,M=e(I,F,l,u).minus(m).abs().comparedTo(e(E,P,l,u).minus(m).abs())<1?[I,F]:[E,P],d=g,M},i.toNumber=function(){return+q(this)},i.toPrecision=function(v,C){return v!=null&&Ht(v,1,mr),Q(this,v,C,2)},i.toString=function(v){var C,P=this,F=P.s,R=P.e;return R===null?F?(C="Infinity",F<0&&(C="-"+C)):C="NaN":(v==null?C=R<=a||R>=c?Ud(_n(P.c),R):Os(_n(P.c),R,"0"):v===10&&V?(P=H(new U(P),o+R+1,u),C=Os(_n(P.c),P.e,"0")):(Ht(v,2,B.length,"Base"),C=r(Os(_n(P.c),R,"0"),10,v,F,!0)),F<0&&P.c[0]&&(C="-"+C)),C},i.valueOf=i.toJSON=function(){return q(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&U.set(t),U}function Nn(t){var e=t|0;return t>0||t===e?e:e-1}function _n(t){for(var e,r,n=1,i=t.length,s=t[0]+"";nc^r?1:-1;for(u=(a=i.length)<(c=s.length)?a:c,o=0;os[o]^r?1:-1;return a==c?0:a>c^r?1:-1}function Ht(t,e,r,n){if(tr||t!==Cn(t))throw Error(Qr+(n||"Argument")+(typeof t=="number"?tr?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function Fd(t){var e=t.c.length-1;return Nn(t.e/be)==e&&t.c[e]%2!=0}function Ud(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function Os(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e{h();uH=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Nw=Math.ceil,Cn=Math.floor,Qr="[BigNumber Error] ",L3=Qr+"Number primitive has more than 15 significant digits: ",di=1e14,be=14,xw=9007199254740991,Ow=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],so=1e7,mr=1e9;U3=F3(),Ou=U3});var Ie=D(ce=>{"use strict";h();Object.defineProperty(ce,"__esModule",{value:!0});ce.ErrParseTransactionOutcome=ce.ErrInvalidInnerTransaction=ce.ErrBadUsage=ce.ErrInvalidTokenIdentifier=ce.ErrIsCompletedFieldIsMissingOnTransaction=ce.ErrGasLimitShouldBe0ForInnerTransaction=ce.ErrInvalidRelayedV2BuilderArguments=ce.ErrInvalidRelayedV1BuilderArguments=ce.ErrNotImplemented=ce.ErrContractInteraction=ce.ErrCodec=ce.ErrCannotParseTransactionOutcome=ce.ErrCannotParseContractResults=ce.ErrMissingFieldOnEnum=ce.ErrMissingFieldOnStruct=ce.ErrTypingSystem=ce.ErrMock=ce.ErrContractHasNoAddress=ce.ErrContract=ce.ErrExpectedTransactionEventsNotFound=ce.ErrExpectedTransactionStatusNotReached=ce.ErrTransactionWatcherTimeout=ce.ErrAsyncTimerAborted=ce.ErrAsyncTimerAlreadyRunning=ce.ErrInvalidFunctionName=ce.ErrSignatureCannotCreate=ce.ErrTransactionOptionsInvalid=ce.ErrTransactionVersionInvalid=ce.ErrNonceInvalid=ce.ErrNotEnoughGas=ce.ErrAddressEmpty=ce.ErrAddressBadHrp=ce.ErrAddressCannotCreate=ce.ErrUnexpectedCondition=ce.ErrInvariantFailed=ce.ErrBadType=ce.ErrUnsupportedOperation=ce.ErrInvalidArgument=ce.Err=void 0;var Ce=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}summary(){let e=[];e.push({name:this.name,message:this.message});let r=this.inner;for(;r;)e.push({name:r.name,message:r.message}),r=r.inner;return e}};ce.Err=Ce;var Dw=class extends Ce{constructor(e,r){super(`Invalid argument: ${e}`,r)}};ce.ErrInvalidArgument=Dw;var Pw=class extends Ce{constructor(e,r="not specified"){super(`Operation "${e}" not supported. Reason: ${r}`)}};ce.ErrUnsupportedOperation=Pw;var Rw=class extends Ce{constructor(e,r,n){super(`Bad type of "${e}": ${n}. Expected type: ${r}`)}};ce.ErrBadType=Rw;var Bw=class extends Ce{constructor(e){super(`Invariant failed: [${e}]`)}};ce.ErrInvariantFailed=Bw;var Mw=class extends Ce{constructor(e){super(`Unexpected condition: [${e}]`)}};ce.ErrUnexpectedCondition=Mw;var Lw=class extends Ce{constructor(e,r){let n=`Cannot create address from: ${e}`;super(n,r)}};ce.ErrAddressCannotCreate=Lw;var Fw=class extends Ce{constructor(e,r){super(`Wrong address HRP. Expected: ${e}, got ${r}`)}};ce.ErrAddressBadHrp=Fw;var Uw=class extends Ce{constructor(){super("Address is empty")}};ce.ErrAddressEmpty=Uw;var qw=class extends Ce{constructor(e){super(`Not enough gas provided: ${e}`)}};ce.ErrNotEnoughGas=qw;var Vw=class extends Ce{constructor(e){super(`Invalid nonce: ${e}`)}};ce.ErrNonceInvalid=Vw;var kw=class extends Ce{constructor(e){super(`Invalid transaction version: ${e}`)}};ce.ErrTransactionVersionInvalid=kw;var Hw=class extends Ce{constructor(e){super(`Invalid transaction options: ${e}`)}};ce.ErrTransactionOptionsInvalid=Hw;var Gw=class extends Ce{constructor(e,r){let n=`Cannot create signature from: ${e}`;super(n,r)}};ce.ErrSignatureCannotCreate=Gw;var jw=class extends Ce{constructor(){super("Invalid function name")}};ce.ErrInvalidFunctionName=jw;var zw=class extends Ce{constructor(){super("Async timer already running")}};ce.ErrAsyncTimerAlreadyRunning=zw;var Qw=class extends Ce{constructor(){super("Async timer aborted")}};ce.ErrAsyncTimerAborted=Qw;var Kw=class extends Ce{constructor(){super("TransactionWatcher has timed out")}};ce.ErrTransactionWatcherTimeout=Kw;var Ww=class extends Ce{constructor(){super("Expected transaction status not reached")}};ce.ErrExpectedTransactionStatusNotReached=Ww;var $w=class extends Ce{constructor(){super("Expected transaction events not found")}};ce.ErrExpectedTransactionEventsNotFound=$w;var qd=class extends Ce{constructor(e){super(e)}};ce.ErrContract=qd;var Yw=class extends qd{constructor(){super(` The smart contract has no address set. Make sure you provide the address in the constructor, or call setAddress() appropriately. If you need to recompute the address of the contract, make use of SmartContract.computeAddress() (static method). -`)}};ce.ErrContractHasNoAddress=$w;var Yw=class extends Ce{constructor(e){super(e)}};ce.ErrMock=Yw;var Jw=class extends Ce{constructor(e){super(e)}};ce.ErrTypingSystem=Jw;var Xw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on struct ${r}`)}};ce.ErrMissingFieldOnStruct=Xw;var Zw=class extends Ce{constructor(e,r){super(`field ${e} does not exist on enum ${r}`)}};ce.ErrMissingFieldOnEnum=Zw;var ev=class extends Ce{constructor(e){super(`cannot parse contract results: ${e}`)}};ce.ErrCannotParseContractResults=ev;var tv=class extends Ce{constructor(e,r){super(`cannot parse outcome of transaction ${e}: ${r}`)}};ce.ErrCannotParseTransactionOutcome=tv;var rv=class extends Ce{constructor(e){super(e)}};ce.ErrCodec=rv;var nv=class extends Ce{constructor(e){super(e)}};ce.ErrContractInteraction=nv;var iv=class extends Ce{constructor(){super("Method not yet implemented")}};ce.ErrNotImplemented=iv;var sv=class extends Ce{constructor(){super("invalid arguments for relayed v1 builder")}};ce.ErrInvalidRelayedV1BuilderArguments=sv;var ov=class extends Ce{constructor(){super("invalid arguments for relayed v2 builder")}};ce.ErrInvalidRelayedV2BuilderArguments=ov;var av=class extends Ce{constructor(){super("gas limit must be 0 for the inner transaction for relayed v2")}};ce.ErrGasLimitShouldBe0ForInnerTransaction=av;var uv=class extends Ce{constructor(){super("The transaction watcher requires the `isCompleted` property to be defined on the transaction object. Perhaps you've used the sdk-network-provider's `ProxyNetworkProvider.getTransaction()` and in that case you should also pass `withProcessStatus=true`.")}};ce.ErrIsCompletedFieldIsMissingOnTransaction=uv;var cv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidTokenIdentifier=cv;var lv=class extends Ce{constructor(e){super(e)}};ce.ErrBadUsage=lv;var fv=class extends Ce{constructor(e){super(e)}};ce.ErrInvalidInnerTransaction=fv;var hv=class extends Ce{constructor(e){super(e)}};ce.ErrParseTransactionOutcome=hv});var Ca=B(xn=>{"use strict";h();var Wk=xn&&xn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xn,"__esModule",{value:!0});xn.TokenPayment=xn.TokenComputer=xn.TokenTransfer=xn.Token=void 0;var _a=Wk((rr(),_e(fr))),Du=Ie(),V3="EGLD",k3=18;_a.default.set({ROUNDING_MODE:1});var Hd=class{constructor(e){this.identifier=e.identifier,this.nonce=e.nonce||0n}};xn.Token=Hd;var Gd=class t{constructor(e){if(this.isLegacyTokenTransferOptions(e)){let r=new _a.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new Du.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0,this.token=new Hd({identifier:e.tokenIdentifier,nonce:BigInt(e.nonce)}),this.amount=BigInt(this.amountAsBigInteger.toFixed(0))}else this.token=e.token,this.amount=e.amount,this.tokenIdentifier=e.token.identifier,this.nonce=Number(e.token.nonce),this.amountAsBigInteger=new _a.default(this.amount.toString()),this.numDecimals=0}isLegacyTokenTransferOptions(e){return e.tokenIdentifier!==void 0}static egldFromAmount(e){let r=new _a.default(e).shiftedBy(k3).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:V3,nonce:0,amountAsBigInteger:e,numDecimals:k3})}static fungibleFromAmount(e,r,n){let i=new _a.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new _a.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amount.toString()}valueOf(){return new _a.default(this.amount.toString())}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.token.identifier==V3}isFungible(){return this.token.nonce==0n}};xn.TokenTransfer=Gd;var dv=class{constructor(){}isFungible(e){return e.nonce===0n}extractNonceFromExtendedIdentifier(e){let r=e.split("-");if(this.checkIfExtendedIdentifierWasProvided(r),this.checkLengthOfRandomSequence(r[1]),r.length==2)return 0;let n=p.Buffer.from(r[2],"hex");return $k(n)}extractIdentifierFromExtendedIdentifier(e){let r=e.split("-");return this.checkIfExtendedIdentifierWasProvided(r),this.ensureTokenTickerValidity(r[0]),this.checkLengthOfRandomSequence(r[1]),r[0]+"-"+r[1]}checkIfExtendedIdentifierWasProvided(e){if(e.length<2||e.length>3)throw new Du.ErrInvalidTokenIdentifier("Invalid extended token identifier provided")}checkLengthOfRandomSequence(e){if(e.length!==6)throw new Du.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length")}ensureTokenTickerValidity(e){if(e.length<3||e.length>10)throw new Du.ErrInvalidTokenIdentifier("The token ticker should be between 3 and 10 characters");if(!e.match(/^[a-zA-Z0-9]+$/))throw new Du.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters");if(e!=e.toUpperCase())throw new Du.ErrInvalidTokenIdentifier("The token ticker should be upper case")}};xn.TokenComputer=dv;function $k(t){return t.readUIntBE(0,t.length)}var gv=class extends Gd{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};xn.TokenPayment=gv});var hr=B(Ae=>{"use strict";h();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.UNKNOWN_SIGNER=Ae.SDK_JS_SIGNER=Ae.METACHAIN_ID=Ae.WasmVirtualMachine=Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=Ae.BECH32_ADDRESS_LENGTH=Ae.HEX_TRANSACTION_HASH_LENGTH=Ae.MESSAGE_PREFIX=Ae.DEFAULT_MESSAGE_VERSION=Ae.ESDT_CONTRACT_ADDRESS=Ae.DEFAULT_HRP=Ae.DELEGATION_MANAGER_SC_ADDRESS=Ae.CONTRACT_DEPLOY_ADDRESS=Ae.VM_TYPE_WASM_VM=Ae.ARGUMENTS_SEPARATOR=Ae.ESDT_TRANSFER_VALUE=Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_GAS_LIMIT=Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=Ae.TRANSACTION_VERSION_DEFAULT=Ae.TRANSACTION_OPTIONS_TX_GUARDED=Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=Ae.TRANSACTION_OPTIONS_DEFAULT=Ae.TRANSACTION_MIN_GAS_PRICE=void 0;Ae.TRANSACTION_MIN_GAS_PRICE=1e9;Ae.TRANSACTION_OPTIONS_DEFAULT=0;Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Ae.TRANSACTION_OPTIONS_TX_GUARDED=2;Ae.TRANSACTION_VERSION_DEFAULT=2;Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=2;Ae.ESDT_TRANSFER_GAS_LIMIT=5e5;Ae.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Ae.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Ae.ESDT_TRANSFER_VALUE="0";Ae.ARGUMENTS_SEPARATOR="@";Ae.VM_TYPE_WASM_VM=new Uint8Array([5,0]);Ae.CONTRACT_DEPLOY_ADDRESS="erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu";Ae.DELEGATION_MANAGER_SC_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6";Ae.DEFAULT_HRP="erd";Ae.ESDT_CONTRACT_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u";Ae.DEFAULT_MESSAGE_VERSION=1;Ae.MESSAGE_PREFIX=`Elrond Signed Message: -`;Ae.HEX_TRANSACTION_HASH_LENGTH=64;Ae.BECH32_ADDRESS_LENGTH=62;Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=3;Ae.WasmVirtualMachine="0500";Ae.METACHAIN_ID=4294967295;Ae.SDK_JS_SIGNER="sdk-js";Ae.UNKNOWN_SIGNER="unknown"});var oo=B(xa=>{"use strict";h();Object.defineProperty(xa,"__esModule",{value:!0});xa.Logger=xa.LogLevel=void 0;var Na;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Na=xa.LogLevel||(xa.LogLevel={}));var jd=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Na.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Na.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Na.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Na.Error||console.error(e,r)}};xa.Logger=jd;jd.logLevel=Na.Debug});var $l=B(On=>{"use strict";h();var Yk=On&&On.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Jk=On&&On.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xk=On&&On.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yk(e,t,r);return Jk(e,t),e};Object.defineProperty(On,"__esModule",{value:!0});On.TransactionOptions=On.TransactionVersion=void 0;var gi=hr(),H3=Xk(Ie()),pv=class t{constructor(e){if(e=Number(e),e<1)throw new H3.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}valueOf(){return this.value}};On.TransactionVersion=pv;var mv=class t{constructor(e){if(e=Number(e),e<0)throw new H3.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(gi.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=gi.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&gi.TRANSACTION_OPTIONS_TX_HASH_SIGN)==gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&gi.TRANSACTION_OPTIONS_TX_GUARDED)==gi.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=gi.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};On.TransactionOptions=mv});var wv=B((tpe,z3)=>{"use strict";h();var Qd="qpzry9x8gf2tvdw0s3jn54khce6mua7l",yv={};for(Yl=0;Yl>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function G3(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=G3(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Pu(n)^o,i+=Qd.charAt(o)}for(s=0;s<6;++s)n=Pu(n);for(n^=1,s=0;s<6;++s){var u=n>>(5-s)*5&31;i+=Qd.charAt(u)}return i}function j3(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var u=G3(s);if(typeof u=="string")return u;for(var a=[],c=0;c=o.length)&&a.push(d)}return u!==1?"Invalid checksum for "+t:{prefix:s,words:a}}function eH(){var t=j3.apply(null,arguments);if(typeof t=="object")return t}function tH(t){var e=j3.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function Kd(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<{"use strict";h();var oH=Nt&&Nt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),aH=Nt&&Nt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uH=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&oH(e,t,r);return aH(e,t),e},cH=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.addressToHex=Nt.bigIntToHex=Nt.byteArrayToHex=Nt.boolToHex=Nt.utf8ToHex=Nt.zeroPadStringIfOddLength=Nt.isPaddedHex=Nt.numberToPaddedHex=void 0;var lH=cH((rr(),_e(fr))),fH=Ve(),hH=uH(Bu());function dH(t){let e;typeof t=="bigint"||typeof t=="number"?e=t:e=new lH.default(t);let r=e.toString(16);return Wd(r)}Nt.numberToPaddedHex=dH;function gH(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Nt.isPaddedHex=gH;function Wd(t){return t=t||"",t.length%2==1?"0"+t:t}Nt.zeroPadStringIfOddLength=Wd;function Q3(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.utf8ToHex=Q3;function pH(t){return Q3(t.toString())}Nt.boolToHex=pH;function mH(t){let e=p.Buffer.from(t).toString("hex");return Wd(e)}Nt.byteArrayToHex=mH;function yH(t){return t==0?"":hH.getHexMagnitudeOfBigInt(t)}Nt.bigIntToHex=yH;function wH(t){return fH.Address.fromBech32(t.toString()).pubkey().toString("hex")}Nt.addressToHex=wH});var Bu=B(nr=>{"use strict";h();var vH=nr&&nr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nr,"__esModule",{value:!0});nr.prependByteToBuffer=nr.flipBufferBitsInPlace=nr.getHexMagnitudeOfBigInt=nr.bigIntToBuffer=nr.bufferToBigInt=nr.cloneBuffer=nr.isMsbZero=nr.isMsbOne=void 0;var vv=vH((rr(),_e(fr))),AH=Ru();function K3(t,e=0){return t[e]>>7==1}nr.isMsbOne=K3;function EH(t,e=0){return!K3(t,e)}nr.isMsbZero=EH;function bH(t){let e=p.Buffer.alloc(t.length);return t.copy(e),e}nr.cloneBuffer=bH;function SH(t){let e=t.toString("hex");return new vv.default(`0x${e}`,16)}nr.bufferToBigInt=SH;function IH(t){let e=W3(t);return p.Buffer.from(e,"hex")}nr.bigIntToBuffer=IH;function W3(t){return t=new vv.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new vv.default(-1))),AH.numberToPaddedHex(t)):""}nr.getHexMagnitudeOfBigInt=W3;function TH(t){for(let e=0;e{"use strict";h();var CH=Lt&&Lt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NH=Lt&&Lt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$3=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&CH(e,t,r);return NH(e,t),e},xH=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.bufferToHex=Lt.addressToHex=Lt.bigIntToHex=Lt.utf8ToHex=Lt.bigIntToBuffer=Lt.bufferToBigInt=Lt.stringToBuffer=void 0;var OH=xH((rr(),_e(fr))),Y3=$3(Bu()),DH=$3(Ru());function PH(t){return p.Buffer.from(t)}Lt.stringToBuffer=PH;function RH(t){return t.length==0?new OH.default(0):Y3.bufferToBigInt(t)}Lt.bufferToBigInt=RH;function BH(t){return t==0?p.Buffer.from([]):Y3.bigIntToBuffer(t)}Lt.bigIntToBuffer=BH;var Av=Ru();Object.defineProperty(Lt,"utf8ToHex",{enumerable:!0,get:function(){return Av.utf8ToHex}});Object.defineProperty(Lt,"bigIntToHex",{enumerable:!0,get:function(){return Av.bigIntToHex}});Object.defineProperty(Lt,"addressToHex",{enumerable:!0,get:function(){return Av.addressToHex}});function MH(t){let e=t.toString("hex");return DH.zeroPadStringIfOddLength(e)}Lt.bufferToHex=MH});var Ds=B((cpe,Ev)=>{"use strict";h();var Mu=typeof Reflect=="object"?Reflect:null,J3=Mu&&typeof Mu.apply=="function"?Mu.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Yd;Mu&&typeof Mu.ownKeys=="function"?Yd=Mu.ownKeys:Object.getOwnPropertySymbols?Yd=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Yd=function(e){return Object.getOwnPropertyNames(e)};function LH(t){console&&console.warn&&console.warn(t)}var Z3=Number.isNaN||function(e){return e!==e};function _t(){_t.init.call(this)}Ev.exports=_t;Ev.exports.once=VH;_t.EventEmitter=_t;_t.prototype._events=void 0;_t.prototype._eventsCount=0;_t.prototype._maxListeners=void 0;var X3=10;function Jd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_t,"defaultMaxListeners",{enumerable:!0,get:function(){return X3},set:function(t){if(typeof t!="number"||t<0||Z3(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");X3=t}});_t.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_t.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Z3(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function eN(t){return t._maxListeners===void 0?_t.defaultMaxListeners:t._maxListeners}_t.prototype.getMaxListeners=function(){return eN(this)};_t.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var u=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw u.context=o,u}var a=s[e];if(a===void 0)return!1;if(typeof a=="function")J3(a,this,r);else for(var c=a.length,f=sN(a,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=o.length,LH(u)}return t}_t.prototype.addListener=function(e,r){return tN(this,e,r,!1)};_t.prototype.on=_t.prototype.addListener;_t.prototype.prependListener=function(e,r){return tN(this,e,r,!0)};function FH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function rN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=FH.bind(n);return i.listener=r,n.wrapFn=i,i}_t.prototype.once=function(e,r){return Jd(r),this.on(e,rN(this,e,r)),this};_t.prototype.prependOnceListener=function(e,r){return Jd(r),this.prependListener(e,rN(this,e,r)),this};_t.prototype.removeListener=function(e,r){var n,i,s,o,u;if(Jd(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){u=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():UH(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||r)}return this};_t.prototype.off=_t.prototype.removeListener;_t.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function nN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?qH(i):sN(i,i.length)}_t.prototype.listeners=function(e){return nN(this,e,!0)};_t.prototype.rawListeners=function(e){return nN(this,e,!1)};_t.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):iN.call(t,e)};_t.prototype.listenerCount=iN;function iN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_t.prototype.eventNames=function(){return this._eventsCount>0?Yd(this._events):[]};function sN(t,e){for(var r=new Array(e),n=0;n{h();aN.exports=Ds().EventEmitter});var Sv=B(()=>{h()});var dN=B((mpe,hN)=>{"use strict";h();function uN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function cN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Xd.alloc(0);for(var n=Xd.allocUnsafe(r>>>0),i=this.head,s=0;i;)$H(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(u===o.length?s+=o:s+=o.slice(0,r),r-=u,r===0){u===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(u));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Xd.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,u=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,u),r-=u,r===0){u===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(u));break}++s}return this.length-=s,n}},{key:WH,value:function(r,n){return Iv(this,cN(cN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var _v=B((wpe,pN)=>{"use strict";h();function YH(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,I.default.nextTick(Tv,this,t)):I.default.nextTick(Tv,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?I.default.nextTick(Zd,r):(r._writableState.errorEmitted=!0,I.default.nextTick(gN,r,s)):I.default.nextTick(gN,r,s):e?(I.default.nextTick(Zd,r),e(s)):I.default.nextTick(Zd,r)}),this)}function gN(t,e){Tv(t,e),Zd(t)}function Zd(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function JH(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Tv(t,e){t.emit("error",e)}function XH(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}pN.exports={destroy:YH,undestroy:JH,errorOrDestroy:XH}});var Oa=B((Ape,wN)=>{"use strict";h();function ZH(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var yN={};function Dn(t,e,r){r||(r=Error);function n(s,o,u){return typeof e=="string"?e:e(s,o,u)}var i=function(s){ZH(o,s);function o(u,a,c){return s.call(this,n(u,a,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,yN[t]=i}function mN(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function eG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function tG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function rG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}Dn("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);Dn("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&eG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(tG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(mN(e,"type"));else{var s=rG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(mN(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);Dn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");Dn("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});Dn("ERR_STREAM_PREMATURE_CLOSE","Premature close");Dn("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});Dn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");Dn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");Dn("ERR_STREAM_WRITE_AFTER_END","write after end");Dn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Dn("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);Dn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");wN.exports.codes=yN});var Cv=B((bpe,vN)=>{"use strict";h();var nG=Oa().codes.ERR_INVALID_OPT_VALUE;function iG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function sG(t,e,r,n){var i=iG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new nG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}vN.exports={getHighWaterMark:sG}});var Lu=B((Ipe,Nv)=>{h();typeof Object.create=="function"?Nv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Nv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var EN=B((_pe,AN)=>{h();AN.exports=oG;function oG(t,e){if(xv("noDeprecation"))return t;var r=!1;function n(){if(!r){if(xv("throwDeprecation"))throw new Error(e);xv("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function xv(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var Pv=B((Npe,CN)=>{"use strict";h();CN.exports=Gt;function SN(t){var e=this;this.next=null,this.entry=null,this.finish=function(){RG(e,t)}}var Fu;Gt.WritableState=Xl;var aG={deprecate:EN()},IN=bv(),tg=io().Buffer,uG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cG(t){return tg.from(t)}function lG(t){return tg.isBuffer(t)||t instanceof uG}var Dv=_v(),fG=Cv(),hG=fG.getHighWaterMark,ao=Oa().codes,dG=ao.ERR_INVALID_ARG_TYPE,gG=ao.ERR_METHOD_NOT_IMPLEMENTED,pG=ao.ERR_MULTIPLE_CALLBACK,mG=ao.ERR_STREAM_CANNOT_PIPE,yG=ao.ERR_STREAM_DESTROYED,wG=ao.ERR_STREAM_NULL_VALUES,vG=ao.ERR_STREAM_WRITE_AFTER_END,AG=ao.ERR_UNKNOWN_ENCODING,Uu=Dv.errorOrDestroy;Lu()(Gt,IN);function EG(){}function Xl(t,e,r){Fu=Fu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof Fu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=hG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){NG(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new SN(this)}Xl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(Xl.prototype,"buffer",{get:aG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var eg;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(eg=Function.prototype[Symbol.hasInstance],Object.defineProperty(Gt,Symbol.hasInstance,{value:function(e){return eg.call(this,e)?!0:this!==Gt?!1:e&&e._writableState instanceof Xl}})):eg=function(e){return e instanceof this};function Gt(t){Fu=Fu||Da();var e=this instanceof Fu;if(!e&&!eg.call(Gt,this))return new Gt(t);this._writableState=new Xl(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),IN.call(this)}Gt.prototype.pipe=function(){Uu(this,new mG)};function bG(t,e){var r=new vG;Uu(t,r),I.default.nextTick(e,r)}function SG(t,e,r,n){var i;return r===null?i=new wG:typeof r!="string"&&!e.objectMode&&(i=new dG("chunk",["string","Buffer"],r)),i?(Uu(t,i),I.default.nextTick(n,i),!1):!0}Gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&lG(t);return s&&!tg.isBuffer(t)&&(t=cG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=EG),n.ending?bG(this,r):(s||SG(this,n,t,r))&&(n.pendingcb++,i=TG(this,n,s,t,e,r)),i};Gt.prototype.cork=function(){this._writableState.corked++};Gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&TN(this,t))};Gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new AG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function IG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=tg.from(e,r)),e}Object.defineProperty(Gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function TG(t,e,r,n,i,s){if(!r){var o=IG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length{"use strict";h();var BG=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};xN.exports=Li;var NN=Mv(),Bv=Pv();Lu()(Li,NN);for(Rv=BG(Bv.prototype),rg=0;rg{h();var ig=io(),Fi=ig.Buffer;function ON(t,e){for(var r in t)e[r]=t[r]}Fi.from&&Fi.alloc&&Fi.allocUnsafe&&Fi.allocUnsafeSlow?DN.exports=ig:(ON(ig,Lv),Lv.Buffer=Pa);function Pa(t,e,r){return Fi(t,e,r)}Pa.prototype=Object.create(Fi.prototype);ON(Fi,Pa);Pa.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Fi(t,e,r)};Pa.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Fi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Pa.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fi(t)};Pa.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ig.SlowBuffer(t)}});var qv=B(BN=>{"use strict";h();var Uv=PN().Buffer,RN=Uv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function FG(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function UG(t){var e=FG(t);if(typeof e!="string"&&(Uv.isEncoding===RN||!RN(t)))throw new Error("Unknown encoding: "+t);return e||t}BN.StringDecoder=Zl;function Zl(t){this.encoding=UG(t);var e;switch(this.encoding){case"utf16le":this.text=jG,this.end=zG,e=4;break;case"utf8":this.fillLast=kG,e=4;break;case"base64":this.text=QG,this.end=KG,e=3;break;default:this.write=WG,this.end=$G;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Uv.allocUnsafe(e)}Zl.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function qG(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function VG(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function kG(t){var e=this.lastTotal-this.lastNeed,r=VG(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function HG(t,e){var r=qG(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function GG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function jG(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function zG(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function QG(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function KG(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function WG(t){return t.toString(this.encoding)}function $G(t){return t&&t.length?this.write(t):""}});var sg=B((Mpe,FN)=>{"use strict";h();var MN=Oa().codes.ERR_STREAM_PREMATURE_CLOSE;function YG(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";h();var og;function uo(t,e,r){return e=ZG(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ZG(t){var e=ej(t,"string");return typeof e=="symbol"?e:String(e)}function ej(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var tj=sg(),co=Symbol("lastResolve"),Ra=Symbol("lastReject"),ef=Symbol("error"),ag=Symbol("ended"),Ba=Symbol("lastPromise"),Vv=Symbol("handlePromise"),Ma=Symbol("stream");function lo(t,e){return{value:t,done:e}}function rj(t){var e=t[co];if(e!==null){var r=t[Ma].read();r!==null&&(t[Ba]=null,t[co]=null,t[Ra]=null,e(lo(r,!1)))}}function nj(t){I.default.nextTick(rj,t)}function ij(t,e){return function(r,n){t.then(function(){if(e[ag]){r(lo(void 0,!0));return}e[Vv](r,n)},n)}}var sj=Object.getPrototypeOf(function(){}),oj=Object.setPrototypeOf((og={get stream(){return this[Ma]},next:function(){var e=this,r=this[ef];if(r!==null)return Promise.reject(r);if(this[ag])return Promise.resolve(lo(void 0,!0));if(this[Ma].destroyed)return new Promise(function(o,u){I.default.nextTick(function(){e[ef]?u(e[ef]):o(lo(void 0,!0))})});var n=this[Ba],i;if(n)i=new Promise(ij(n,this));else{var s=this[Ma].read();if(s!==null)return Promise.resolve(lo(s,!1));i=new Promise(this[Vv])}return this[Ba]=i,i}},uo(og,Symbol.asyncIterator,function(){return this}),uo(og,"return",function(){var e=this;return new Promise(function(r,n){e[Ma].destroy(null,function(i){if(i){n(i);return}r(lo(void 0,!0))})})}),og),sj),aj=function(e){var r,n=Object.create(oj,(r={},uo(r,Ma,{value:e,writable:!0}),uo(r,co,{value:null,writable:!0}),uo(r,Ra,{value:null,writable:!0}),uo(r,ef,{value:null,writable:!0}),uo(r,ag,{value:e._readableState.endEmitted,writable:!0}),uo(r,Vv,{value:function(s,o){var u=n[Ma].read();u?(n[Ba]=null,n[co]=null,n[Ra]=null,s(lo(u,!1))):(n[co]=s,n[Ra]=o)},writable:!0}),r));return n[Ba]=null,tj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Ra];s!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,s(i)),n[ef]=i;return}var o=n[co];o!==null&&(n[Ba]=null,n[co]=null,n[Ra]=null,o(lo(void 0,!0))),n[ag]=!0}),e.on("readable",nj.bind(null,n)),n};UN.exports=aj});var kN=B((qpe,VN)=>{h();VN.exports=function(){throw new Error("Readable.from is not available in the browser")}});var Mv=B((Hpe,JN)=>{"use strict";h();JN.exports=Fe;var qu;Fe.ReadableState=zN;var kpe=Ds().EventEmitter,jN=function(e,r){return e.listeners(r).length},rf=bv(),ug=io().Buffer,uj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function cj(t){return ug.from(t)}function lj(t){return ug.isBuffer(t)||t instanceof uj}var kv=Sv(),Ne;kv&&kv.debuglog?Ne=kv.debuglog("stream"):Ne=function(){};var fj=dN(),Wv=_v(),hj=Cv(),dj=hj.getHighWaterMark,cg=Oa().codes,gj=cg.ERR_INVALID_ARG_TYPE,pj=cg.ERR_STREAM_PUSH_AFTER_EOF,mj=cg.ERR_METHOD_NOT_IMPLEMENTED,yj=cg.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Vu,Hv,Gv;Lu()(Fe,rf);var tf=Wv.errorOrDestroy,jv=["error","close","destroy","pause","resume"];function wj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function zN(t,e,r){qu=qu||Da(),t=t||{},typeof r!="boolean"&&(r=e instanceof qu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=dj(this,t,"readableHighWaterMark",r),this.buffer=new fj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Vu||(Vu=qv().StringDecoder),this.decoder=new Vu(t.encoding),this.encoding=t.encoding)}function Fe(t){if(qu=qu||Da(),!(this instanceof Fe))return new Fe(t);var e=this instanceof qu;this._readableState=new zN(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),rf.call(this)}Object.defineProperty(Fe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Fe.prototype.destroy=Wv.destroy;Fe.prototype._undestroy=Wv.undestroy;Fe.prototype._destroy=function(t,e){e(t)};Fe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=ug.from(t,e),e=""),n=!0),QN(this,t,e,!1,n)};Fe.prototype.unshift=function(t){return QN(this,t,null,!0,!1)};function QN(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Ej(t,s);else{var o;if(i||(o=vj(s,e)),o)tf(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==ug.prototype&&(e=cj(e)),n)s.endEmitted?tf(t,new yj):zv(t,s,e,!0);else if(s.ended)tf(t,new pj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?zv(t,s,e,!1):Kv(t,s)):zv(t,s,e,!1)}else n||(s.reading=!1,Kv(t,s))}return!s.ended&&(s.length=HN?t=HN:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function GN(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=Aj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}Fe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Qv(this):lg(this),null;if(t=GN(t,e),t===0&&e.ended)return e.length===0&&Qv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=$N(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Qv(this)),i!==null&&this.emit("data",i),i};function Ej(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?lg(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,KN(t)))}}function lg(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,I.default.nextTick(KN,t))}function KN(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,$v(t)}function Kv(t,e){e.readingMore||(e.readingMore=!0,I.default.nextTick(bj,t,e))}function bj(t,e){for(;!e.reading&&!e.ended&&(e.length1&&YN(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function w(R){Ne("onerror",R),x(),t.removeListener("error",w),jN(t,"error")===0&&tf(t,R)}wj(t,"error",w);function A(){t.removeListener("finish",T),x()}t.once("close",A);function T(){Ne("onfinish"),t.removeListener("close",A),x()}t.once("finish",T);function x(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Sj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&jN(t,"data")&&(r.flowing=!0,$v(t))}}Fe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?lg(this):n.reading||I.default.nextTick(Ij,this)),r};Fe.prototype.addListener=Fe.prototype.on;Fe.prototype.removeListener=function(t,e){var r=rf.prototype.removeListener.call(this,t,e);return t==="readable"&&I.default.nextTick(WN,this),r};Fe.prototype.removeAllListeners=function(t){var e=rf.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&I.default.nextTick(WN,this),e};function WN(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Ij(t){Ne("readable nexttick read 0"),t.read(0)}Fe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Tj(this,t)),t.paused=!1,this};function Tj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,I.default.nextTick(_j,t,e))}function _j(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),$v(t),e.flowing&&!e.reading&&t.read(0)}Fe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function $v(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}Fe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var u=e.push(o);u||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(u){return function(){return t[u].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Qv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,I.default.nextTick(Cj,e,t))}function Cj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(Fe.from=function(t,e){return Gv===void 0&&(Gv=kN()),Gv(Fe,t,e)});function YN(t,e){for(var r=0,n=t.length;r{"use strict";h();ZN.exports=Ps;var fg=Oa().codes,Nj=fg.ERR_METHOD_NOT_IMPLEMENTED,xj=fg.ERR_MULTIPLE_CALLBACK,Oj=fg.ERR_TRANSFORM_ALREADY_TRANSFORMING,Dj=fg.ERR_TRANSFORM_WITH_LENGTH_0,hg=Da();Lu()(Ps,hg);function Pj(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new xj);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";h();tx.exports=nf;var ex=Yv();Lu()(nf,ex);function nf(t){if(!(this instanceof nf))return new nf(t);ex.call(this,t)}nf.prototype._transform=function(t,e,r){r(null,t)}});var ax=B((Wpe,ox)=>{"use strict";h();var Jv;function Bj(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var sx=Oa().codes,Mj=sx.ERR_MISSING_ARGS,Lj=sx.ERR_STREAM_DESTROYED;function nx(t){if(t)throw t}function Fj(t){return t.setHeader&&typeof t.abort=="function"}function Uj(t,e,r,n){n=Bj(n);var i=!1;t.on("close",function(){i=!0}),Jv===void 0&&(Jv=sg()),Jv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Fj(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new Lj("pipe"))}}}function ix(t){t()}function qj(t,e){return t.pipe(e)}function Vj(t){return!t.length||typeof t[t.length-1]!="function"?nx:t.pop()}function kj(){for(var t=arguments.length,e=new Array(t),r=0;r0;return Uj(o,a,c,function(f){i||(i=f),f&&s.forEach(ix),!a&&(s.forEach(ix),n(i))})});return e.reduce(qj)}ox.exports=kj});var Xv=B((Pn,ux)=>{h();Pn=ux.exports=Mv();Pn.Stream=Pn;Pn.Readable=Pn;Pn.Writable=Pv();Pn.Duplex=Da();Pn.Transform=Yv();Pn.PassThrough=rx();Pn.finished=sg();Pn.pipeline=ax()});var fx=B((Jpe,lx)=>{h();var{Transform:Hj}=Xv();lx.exports=t=>class cx extends Hj{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new cx(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var gx=B((Zpe,dx)=>{h();var{Transform:Gj}=Xv();dx.exports=t=>class hx extends Gj{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new hx(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var mx=B((t0e,px)=>{h();var jj=fx(),zj=gx();px.exports=function(t){let e=jj(t),r=zj(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var vx=B(wx=>{h();var yx=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];wx.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],u=t[5]^t[15]^t[25]^t[35]^t[45],a=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],w=f^(i<<1|s>>>31),A=d^(s<<1|i>>>31),T=t[0]^w,x=t[1]^A,R=t[10]^w,V=t[11]^A,U=t[20]^w,Q=t[21]^A,L=t[30]^w,k=t[31]^A,H=t[40]^w,q=t[41]^A;w=r^(o<<1|u>>>31),A=n^(u<<1|o>>>31);let v=t[2]^w,C=t[3]^A,D=t[12]^w,F=t[13]^A,P=t[22]^w,l=t[23]^A,g=t[32]^w,y=t[33]^A,E=t[42]^w,S=t[43]^A;w=i^(a<<1|c>>>31),A=s^(c<<1|a>>>31);let _=t[4]^w,M=t[5]^A,N=t[14]^w,m=t[15]^A,O=t[24]^w,Y=t[25]^A,$=t[34]^w,b=t[35]^A,j=t[44]^w,z=t[45]^A;w=o^(f<<1|d>>>31),A=u^(d<<1|f>>>31);let W=t[6]^w,ie=t[7]^A,te=t[16]^w,ee=t[17]^A,se=t[26]^w,oe=t[27]^A,J=t[36]^w,ue=t[37]^A,wt=t[46]^w,vt=t[47]^A;w=a^(r<<1|n>>>31),A=c^(n<<1|r>>>31);let Ni=t[8]^w,At=t[9]^A,Et=t[18]^w,xi=t[19]^A,bt=t[28]^w,St=t[29]^A,Oi=t[38]^w,It=t[39]^A,Tt=t[48]^w,Di=t[49]^A,Qe=T,Ke=x,ri=V<<4|R>>>28,We=R<<4|V>>>28,$e=U<<3|Q>>>29,ni=Q<<3|U>>>29,Ye=k<<9|L>>>23,Je=L<<9|k>>>23,ii=H<<18|q>>>14,Xe=q<<18|H>>>14,Ze=v<<1|C>>>31,si=C<<1|v>>>31,et=F<<12|D>>>20,tt=D<<12|F>>>20,oi=P<<10|l>>>22,rt=l<<10|P>>>22,nt=y<<13|g>>>19,ai=g<<13|y>>>19,it=E<<2|S>>>30,st=S<<2|E>>>30,ui=M<<30|_>>>2,ot=_<<30|M>>>2,at=N<<6|m>>>26,ci=m<<6|N>>>26,ut=Y<<11|O>>>21,ct=O<<11|Y>>>21,li=$<<15|b>>>17,lt=b<<15|$>>>17,ft=z<<29|j>>>3,fi=j<<29|z>>>3,ht=W<<28|ie>>>4,dt=ie<<28|W>>>4,hi=ee<<23|te>>>9,gt=te<<23|ee>>>9,pt=se<<25|oe>>>7,vn=oe<<25|se>>>7,An=J<<21|ue>>>11,En=ue<<21|J>>>11,bn=vt<<24|wt>>>8,Sn=wt<<24|vt>>>8,In=Ni<<27|At>>>5,da=At<<27|Ni>>>5,ga=Et<<20|xi>>>12,pa=xi<<20|Et>>>12,ma=St<<7|bt>>>25,ya=bt<<7|St>>>25,wa=Oi<<8|It>>>24,va=It<<8|Oi>>>24,Aa=Tt<<14|Di>>>18,Ea=Di<<14|Tt>>>18;t[0]=Qe^~et&ut,t[1]=Ke^~tt&ct,t[10]=ht^~ga&$e,t[11]=dt^~pa&ni,t[20]=Ze^~at&pt,t[21]=si^~ci&vn,t[30]=In^~ri&oi,t[31]=da^~We&rt,t[40]=ui^~hi&ma,t[41]=ot^~gt&ya,t[2]=et^~ut&An,t[3]=tt^~ct&En,t[12]=ga^~$e&nt,t[13]=pa^~ni&ai,t[22]=at^~pt&wa,t[23]=ci^~vn&va,t[32]=ri^~oi&li,t[33]=We^~rt<,t[42]=hi^~ma&Ye,t[43]=gt^~ya&Je,t[4]=ut^~An&Aa,t[5]=ct^~En&Ea,t[14]=$e^~nt&ft,t[15]=ni^~ai&fi,t[24]=pt^~wa&ii,t[25]=vn^~va&Xe,t[34]=oi^~li&bn,t[35]=rt^~lt&Sn,t[44]=ma^~Ye&it,t[45]=ya^~Je&st,t[6]=An^~Aa&Qe,t[7]=En^~Ea&Ke,t[16]=nt^~ft&ht,t[17]=ai^~fi&dt,t[26]=wa^~ii&Ze,t[27]=va^~Xe&si,t[36]=li^~bn&In,t[37]=lt^~Sn&da,t[46]=Ye^~it&ui,t[47]=Je^~st&ot,t[8]=Aa^~Qe&et,t[9]=Ea^~Ke&tt,t[18]=ft^~ht&ga,t[19]=fi^~dt&pa,t[28]=ii^~Ze&at,t[29]=Xe^~si&ci,t[38]=bn^~In&ri,t[39]=Sn^~da&We,t[48]=it^~ui&hi,t[49]=st^~ot>,t[0]^=yx[e*2],t[1]^=yx[e*2+1]}}});var Ex=B((s0e,Ax)=>{h();var dg=vx();function ku(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}ku.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};ku.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(dg.p1600(this.state),this.count=0);return e};ku.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};Ax.exports=ku});var sf=B((a0e,bx)=>{h();bx.exports=mx()(Ex())});var Ve=B(Kr=>{"use strict";h();var Qj=Kr&&Kr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Kj=Kr&&Kr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Sx=Kr&&Kr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Qj(e,t,r);return Kj(e,t),e},Wj=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.AddressComputer=Kr.Address=void 0;var Hu=Sx(wv()),$j=Wj((rr(),_e(fr))),Zv=hr(),Gu=Sx(Ie()),Yj=$d(),Jj=sf(),of="erd",gg=32,Xj="0".repeat(16),pg=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(ArrayBuffer.isView(e))return t.fromBuffer(p.Buffer.from(e));if(typeof e=="string")return t.fromString(e);throw new Gu.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=t.empty();return r.valueHex=e,r}static fromBuffer(e){if(e.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==gg}static fromHex(e){if(!t.isValidHex(e))throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t("")}static fromBech32(e){let r;try{r=Hu.decode(e)}catch(s){throw new Gu.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=of)throw new Gu.ErrAddressBadHrp(of,n);let i=p.Buffer.from(Hu.fromWords(r.words));if(i.length!=gg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=Hu.decodeUnsafe(e),n=r?.prefix,i=r?p.Buffer.from(Hu.fromWords(r.words)):void 0;return!(n!==of||i?.length!==gg)}hex(){return this.toHex()}toHex(){return this.isEmpty()?"":this.valueHex}bech32(){return this.toBech32()}toBech32(){if(this.isEmpty())return"";let e=Hu.toWords(this.pubkey());return Hu.encode(of,e)}pubkey(){return this.getPublicKey()}getPublicKey(){return this.isEmpty()?p.Buffer.from([]):p.Buffer.from(this.valueHex,"hex")}getHrp(){return of}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.toBech32()}toJSON(){return{bech32:this.toBech32(),pubkey:this.toHex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.isSmartContract()}isSmartContract(){return this.toHex().startsWith(Xj)}};Kr.Address=pg;var eA=class{constructor(e){this.numberOfShardsWithoutMeta=e||Zv.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META}computeContractAddress(e,r){let n=p.Buffer.alloc(8,0),i=e.getPublicKey(),s=i.slice(30),o=p.Buffer.alloc(8),u=new $j.default(r.toString()),a=Yj.bigIntToBuffer(u);o.write(a.reverse().toString("hex"),"hex");let c=p.Buffer.concat([i,o]),f=Jj("keccak256").update(c).digest(),d=p.Buffer.from(Zv.WasmVirtualMachine,"hex"),w=p.Buffer.concat([n,d,f.slice(10,30),s]);return new pg(w)}getShardOfAddress(e){return this.getShardOfPubkey(e.getPublicKey(),this.numberOfShardsWithoutMeta)}getShardOfPubkey(e,r){let n=parseInt("11",2),i=parseInt("01",2),s=e[31];if(this.isPubkeyOfMetachain(e))return Zv.METACHAIN_ID;let o=s&n;return o>r-1&&(o=s&i),o}isPubkeyOfMetachain(e){let r=p.Buffer.from([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n=p.Buffer.from(e).slice(0,r.length);return!!(r.equals(n)||p.Buffer.alloc(32).equals(p.Buffer.from(e)))}};Kr.AddressComputer=eA});var Rn=B(Ft=>{"use strict";h();var Zj=Ft&&Ft.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ez=Ft&&Ft.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tz=Ft&&Ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zj(e,t,r);return ez(e,t),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.isEmpty=Ft.guardEmpty=Ft.guardNotEmpty=Ft.guardLength=Ft.guardSameLength=Ft.guardValueIsSetWithMessage=Ft.guardValueIsSet=Ft.guardTrue=void 0;var ju=tz(Ie());function rz(t,e){if(!t)throw new ju.ErrInvariantFailed(`[<${e}>] isn't true`)}Ft.guardTrue=rz;function nz(t,e){Ix(`${t} isn't set (null or undefined)`,e)}Ft.guardValueIsSet=nz;function Ix(t,e){if(e==null||e===void 0)throw new ju.ErrInvariantFailed(t)}Ft.guardValueIsSetWithMessage=Ix;function iz(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new ju.ErrInvariantFailed("arrays do not have the same length")}Ft.guardSameLength=iz;function sz(t,e){let r=t.length||0;if(r!=e)throw new ju.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}Ft.guardLength=sz;function oz(t,e){if(tA(t))throw new ju.ErrInvariantFailed(`${e} is empty`)}Ft.guardNotEmpty=oz;function az(t,e){if(!tA(t))throw new ju.ErrInvariantFailed(`${e} is not empty`)}Ft.guardEmpty=az;function tA(t){return t.isEmpty?t.isEmpty():t.length===0}Ft.isEmpty=tA});var Tx=B(mg=>{"use strict";h();Object.defineProperty(mg,"__esModule",{value:!0});mg.TypeFormula=void 0;var rA=class{constructor(e,r){this.name=e,this.typeParameters=r}toString(){if(this.typeParameters.length>0){let e=this.typeParameters.map(r=>r.toString()).join(", ");return`${this.name}<${e}>`}else return this.name}};mg.TypeFormula=rA});var _x=B(yg=>{"use strict";h();Object.defineProperty(yg,"__esModule",{value:!0});yg.TypeFormulaParser=void 0;var af=Tx(),Ui=class t{parseExpression(e){e=e.trim();let r=this.tokenizeExpression(e).filter(s=>s!==t.COMMA),n=[];for(let s of r)if(this.isPunctuation(s))if(this.isEndOfTypeParameters(s)){let o=this.acquireTypeWithParameters(n);n.push(o)}else if(this.isBeginningOfTypeParameters(s))n.push(s);else throw new Error(`Unexpected token (punctuation): ${s}`);else n.push(s);if(n.length!==1)throw new Error(`Unexpected stack length at end of parsing: ${n.length}`);if(t.PUNCTUATION.includes(n[0]))throw new Error("Unexpected root element.");let i=n[0];if(i instanceof af.TypeFormula)return i;if(typeof i=="string")return new af.TypeFormula(i,[]);throw new Error(`Unexpected item on stack: ${i}`)}tokenizeExpression(e){let r=[],n="";for(let i of e)this.isPunctuation(i)?(n&&(r.push(n.trim()),n=""),r.push(i)):n+=i;return n&&r.push(n.trim()),r}acquireTypeWithParameters(e){let r=this.acquireTypeParameters(e),n=e.pop();return new af.TypeFormula(n,r.reverse())}acquireTypeParameters(e){let r=[];for(;;){let n=e.pop();if(n===void 0)throw new Error("Badly specified type parameters");if(this.isBeginningOfTypeParameters(n))break;if(n instanceof af.TypeFormula)r.push(n);else if(typeof n=="string")r.push(new af.TypeFormula(n,[]));else throw new Error(`Unexpected type parameter object in stack: ${n}`)}return r}isPunctuation(e){return t.PUNCTUATION.includes(e)}isEndOfTypeParameters(e){return e===t.END_TYPE_PARAMETERS}isBeginningOfTypeParameters(e){return e===t.BEGIN_TYPE_PARAMETERS}};yg.TypeFormulaParser=Ui;Ui.BEGIN_TYPE_PARAMETERS="<";Ui.END_TYPE_PARAMETERS=">";Ui.COMMA=",";Ui.PUNCTUATION=[Ui.COMMA,Ui.BEGIN_TYPE_PARAMETERS,Ui.END_TYPE_PARAMETERS]});var Cx=B(wg=>{"use strict";h();Object.defineProperty(wg,"__esModule",{value:!0});wg.getJavascriptPrototypesInHierarchy=void 0;function uz(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}wg.getJavascriptPrototypesInHierarchy=uz});var sr=B(ir=>{"use strict";h();Object.defineProperty(ir,"__esModule",{value:!0});ir.NullType=ir.TypePlaceholder=ir.isTyped=ir.PrimitiveValue=ir.TypedValue=ir.CustomType=ir.PrimitiveType=ir.TypeCardinality=ir.Type=void 0;var nA=Cx(),Nx=Rn(),fo=class t{constructor(e,r=[],n=uf.fixed(1)){Nx.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return Nx.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return nA.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};ir.Type=fo;fo.ClassName="Type";var uf=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};ir.TypeCardinality=uf;uf.MaxCardinality=4096;var vg=class t extends fo{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveType=vg;vg.ClassName="PrimitiveType";var Ag=class t extends fo{getClassName(){return t.ClassName}};ir.CustomType=Ag;Ag.ClassName="CustomType";var cf=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return nA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};ir.TypedValue=cf;cf.ClassName="TypedValue";var Eg=class t extends cf{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveValue=Eg;Eg.ClassName="PrimitiveValue";function cz(t){return t.belongsToTypesystem!==void 0}ir.isTyped=cz;var bg=class t extends fo{constructor(){super("...")}getClassName(){return t.ClassName}};ir.TypePlaceholder=bg;bg.ClassName="TypePlaceholder";var Sg=class t extends fo{constructor(){super("?")}getClassName(){return t.ClassName}};ir.NullType=Sg;Sg.ClassName="NullType"});var lf=B(Ig=>{"use strict";h();Object.defineProperty(Ig,"__esModule",{value:!0});Ig.TypeExpressionParser=void 0;var lz=_x(),fz=Ie(),hz=sr(),iA=class{constructor(){this.backingTypeFormulaParser=new lz.TypeFormulaParser}parse(e){try{return this.doParse(e)}catch(r){throw new fz.ErrTypingSystem(`Failed to parse type expression: ${e}. Error: ${r}`)}}doParse(e){let r=this.backingTypeFormulaParser.parseExpression(e);return this.typeFormulaToType(r)}typeFormulaToType(e){let r=e.typeParameters.map(n=>this.typeFormulaToType(n));return new hz.Type(e.name,r)}};Ig.TypeExpressionParser=iA});var oA=B(ho=>{"use strict";h();Object.defineProperty(ho,"__esModule",{value:!0});ho.EndpointParameterDefinition=ho.EndpointModifiers=ho.EndpointDefinition=void 0;var dz=lf(),xx="?",gz="N / A",sA=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?xx:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>ff.fromJSON(s)),n=e.outputs.map(s=>ff.fromJSON(s)),i=new Tg(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};ho.EndpointDefinition=sA;var Tg=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};ho.EndpointModifiers=Tg;var ff=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new dz.TypeExpressionParser().parse(e.type);return new t(e.name||xx,e.description||gz,r)}};ho.EndpointParameterDefinition=ff});var zu=B(Wr=>{"use strict";h();var pz=Wr&&Wr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),mz=Wr&&Wr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),yz=Wr&&Wr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&pz(e,t,r);return mz(e,t),e};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Fields=Wr.Field=Wr.FieldDefinition=void 0;var aA=yz(Ie()),wz=lf(),uA=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new wz.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};Wr.FieldDefinition=uA;var cA=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new aA.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new aA.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};Wr.Field=cA;var lA=class{static checkTyping(e,r){if(e.length!=r.length)throw new aA.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";h();Object.defineProperty(go,"__esModule",{value:!0});go.EnumValue=go.EnumVariantDefinition=go.EnumType=void 0;var vz=Ie(),fA=Rn(),_g=zu(),Dx=sr(),Ox=256,Cg=class t extends Dx.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>Ng.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>({...n,discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return fA.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return fA.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};go.EnumType=Cg;Cg.ClassName="EnumType";var Ng=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],fA.guardTrue(r_g.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return _g.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};go.EnumVariantDefinition=Ng;var xg=class t extends Dx.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();_g.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=_g.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new vz.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};go.EnumValue=xg;xg.ClassName="EnumValue"});var Rx=B(Qu=>{"use strict";h();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.EventTopicDefinition=Qu.EventDefinition=void 0;var Az=lf(),Px="?",hA=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?Px:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>Og.fromJSON(n));return new t(e.identifier,r)}};Qu.EventDefinition=hA;var Og=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Az.TypeExpressionParser().parse(e.type);return new t({name:e.name||Px,type:r,indexed:e.indexed})}};Qu.EventTopicDefinition=Og});var Wu=B(Ku=>{"use strict";h();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.Struct=Ku.StructType=void 0;var Ez=Ie(),Dg=zu(),Bx=sr(),Pg=class t extends Bx.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>Dg.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Dg.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Ku.StructType=Pg;Pg.ClassName="StructType";var Rg=class t extends Bx.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();Dg.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Ez.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return Dg.Fields.equals(r,n)}};Ku.Struct=Rg;Rg.ClassName="Struct"});var Yu=B($u=>{"use strict";h();Object.defineProperty($u,"__esModule",{value:!0});$u.AddressValue=$u.AddressType=void 0;var bz=Ve(),Mx=sr(),df=class t extends Mx.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};$u.AddressType=df;df.ClassName="AddressType";var Bg=class t extends Mx.PrimitiveValue{constructor(e){super(new df),this.value=new bz.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};$u.AddressValue=Bg;Bg.ClassName="AddressValue"});var Lg=B(Ju=>{"use strict";h();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.OptionalValue=Ju.OptionalType=void 0;var Sz=Rn(),gf=sr(),pf=class t extends gf.Type{constructor(e){super("Optional",[e],gf.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(gf.NullType.ClassName);return r||n}};Ju.OptionalType=pf;pf.ClassName="OptionalType";var Mg=class t extends gf.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new pf(new gf.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return Sz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};Ju.OptionalValue=Mg;Mg.ClassName="OptionalValue"});var yf=B(Xu=>{"use strict";h();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.BooleanValue=Xu.BooleanType=void 0;var Lx=sr(),mf=class t extends Lx.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};Xu.BooleanType=mf;mf.ClassName="BooleanType";var Fg=class t extends Lx.PrimitiveValue{constructor(e){super(new mf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};Xu.BooleanValue=Fg;Fg.ClassName="BooleanValue"});var po=B(Zu=>{"use strict";h();Object.defineProperty(Zu,"__esModule",{value:!0});Zu.BytesValue=Zu.BytesType=void 0;var Fx=sr(),wf=class t extends Fx.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Zu.BytesType=wf;wf.ClassName="BytesType";var Ug=class t extends Fx.PrimitiveValue{constructor(e){super(new wf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=p.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=p.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Zu.BytesValue=Ug;Ug.ClassName="BytesValue"});var qx=B(ec=>{"use strict";h();Object.defineProperty(ec,"__esModule",{value:!0});ec.CodeMetadataValue=ec.CodeMetadataType=void 0;var Ux=sr(),qg=class extends Ux.PrimitiveType{constructor(){super("CodeMetadata")}};ec.CodeMetadataType=qg;var dA=class extends Ux.PrimitiveValue{constructor(e){super(new qg),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};ec.CodeMetadataValue=dA});var kg=B(tc=>{"use strict";h();Object.defineProperty(tc,"__esModule",{value:!0});tc.CompositeValue=tc.CompositeType=void 0;var Iz=Rn(),gA=sr(),vf=class t extends gA.Type{constructor(...e){super("Composite",e,gA.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};tc.CompositeType=vf;vf.ClassName="CompositeType";var Vg=class t extends gA.TypedValue{constructor(e,r){super(e),Iz.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new vf(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();Object.defineProperty(Hg,"__esModule",{value:!0});Hg.CollectionOfTypedValues=void 0;var pA=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";h();Object.defineProperty(qi,"__esModule",{value:!0});qi.List=qi.OptionValue=qi.ListType=qi.OptionType=void 0;var Tz=Rn(),_z=mA(),Fa=sr(),La=class t extends Fa.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(Fa.NullType.ClassName);return r||n}};qi.OptionType=La;La.ClassName="OptionType";var Af=class t extends Fa.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};qi.ListType=Af;Af.ClassName="ListType";var Gg=class t extends Fa.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new La(new Fa.NullType);return new t(e)}static newMissingTyped(e){return new t(new La(e))}static newProvided(e){let r=new La(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return Tz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};qi.OptionValue=Gg;Gg.ClassName="OptionValue";var jg=class t extends Fa.TypedValue{constructor(e,r){super(e),this.backingCollection=new _z.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new Fa.TypePlaceholder,[]);let r=e[0].getType(),n=new Af(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};qi.List=jg;jg.ClassName="List"});var Kg=B(rc=>{"use strict";h();Object.defineProperty(rc,"__esModule",{value:!0});rc.ArrayVec=rc.ArrayVecType=void 0;var Vx=Rn(),Cz=mA(),kx=sr(),zg=class t extends kx.Type{constructor(e,r){super("Array",[r]),Vx.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};rc.ArrayVecType=zg;zg.ClassName="ArrayVecType";var Qg=class t extends kx.TypedValue{constructor(e,r){super(e),Vx.guardLength(r,e.length),this.backingCollection=new Cz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};rc.ArrayVec=Qg;Qg.ClassName="ArrayVec"});var Sf=B(nc=>{"use strict";h();Object.defineProperty(nc,"__esModule",{value:!0});nc.H256Value=nc.H256Type=void 0;var Hx=sr(),bf=class t extends Hx.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};nc.H256Type=bf;bf.ClassName="H256Type";var Wg=class t extends Hx.PrimitiveValue{constructor(e){super(new bf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};nc.H256Value=Wg;Wg.ClassName="H256Value"});var Yg=B(ic=>{"use strict";h();Object.defineProperty(ic,"__esModule",{value:!0});ic.NothingValue=ic.NothingType=void 0;var Gx=sr(),If=class t extends Gx.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};ic.NothingType=If;If.ClassName="NothingType";var $g=class t extends Gx.PrimitiveValue{constructor(){super(new If)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};ic.NothingValue=$g;$g.ClassName="NothingValue"});var Mf=B(Ee=>{"use strict";h();var Nz=Ee&&Ee.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xz=Ee&&Ee.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Oz=Ee&&Ee.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Nz(e,t,r);return xz(e,t),e},Dz=Ee&&Ee.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.BigIntValue=Ee.BigUIntValue=Ee.I64Value=Ee.U64Value=Ee.I32Value=Ee.U32Value=Ee.I16Value=Ee.U16Value=Ee.I8Value=Ee.U8Value=Ee.NumericalValue=Ee.BigIntType=Ee.BigUIntType=Ee.I64Type=Ee.U64Type=Ee.I32Type=Ee.U32Type=Ee.I16Type=Ee.U16Type=Ee.I8Type=Ee.U8Type=Ee.NumericalType=void 0;var Pz=Dz((rr(),_e(fr))),jx=Oz(Ie()),zx=sr(),$r=class t extends zx.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ee.NumericalType=$r;$r.ClassName="NumericalType";var Tf=class t extends $r{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ee.U8Type=Tf;Tf.ClassName="U8Type";var _f=class t extends $r{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ee.I8Type=_f;_f.ClassName="I8Type";var Cf=class t extends $r{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ee.U16Type=Cf;Cf.ClassName="U16Type";var Nf=class t extends $r{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ee.I16Type=Nf;Nf.ClassName="I16Type";var xf=class t extends $r{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ee.U32Type=xf;xf.ClassName="U32Type";var Of=class t extends $r{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ee.I32Type=Of;Of.ClassName="I32Type";var Df=class t extends $r{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ee.U64Type=Df;Df.ClassName="U64Type";var Pf=class t extends $r{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ee.I64Type=Pf;Pf.ClassName="I64Type";var Rf=class t extends $r{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ee.BigUIntType=Rf;Rf.ClassName="BigUIntType";var Bf=class t extends $r{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ee.BigIntType=Bf;Bf.ClassName="BigIntType";var Yr=class t extends zx.PrimitiveValue{constructor(e,r){if(super(e),typeof r=="bigint"&&(r=r.toString()),this.value=new Pz.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new jx.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new jx.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ee.NumericalValue=Yr;Yr.ClassName="NumericalValue";var Jg=class t extends Yr{constructor(e){super(new Tf,e)}getClassName(){return t.ClassName}};Ee.U8Value=Jg;Jg.ClassName="U8Value";var Xg=class t extends Yr{constructor(e){super(new _f,e)}getClassName(){return t.ClassName}};Ee.I8Value=Xg;Xg.ClassName="I8Value";var Zg=class t extends Yr{constructor(e){super(new Cf,e)}getClassName(){return t.ClassName}};Ee.U16Value=Zg;Zg.ClassName="U16Value";var ep=class t extends Yr{constructor(e){super(new Nf,e)}getClassName(){return t.ClassName}};Ee.I16Value=ep;ep.ClassName="I16Value";var tp=class t extends Yr{constructor(e){super(new xf,e)}getClassName(){return t.ClassName}};Ee.U32Value=tp;tp.ClassName="U32Value";var rp=class t extends Yr{constructor(e){super(new Of,e)}getClassName(){return t.ClassName}};Ee.I32Value=rp;rp.ClassName="I32Value";var np=class t extends Yr{constructor(e){super(new Df,e)}getClassName(){return t.ClassName}};Ee.U64Value=np;np.ClassName="U64Value";var ip=class t extends Yr{constructor(e){super(new Pf,e)}getClassName(){return t.ClassName}};Ee.I64Value=ip;ip.ClassName="I64Value";var sp=class t extends Yr{constructor(e){super(new Rf,e)}getClassName(){return t.ClassName}};Ee.BigUIntValue=sp;sp.ClassName="BigUIntValue";var op=class t extends Yr{constructor(e){super(new Bf,e)}getClassName(){return t.ClassName}};Ee.BigIntValue=op;op.ClassName="BigIntValue"});var up=B(sc=>{"use strict";h();Object.defineProperty(sc,"__esModule",{value:!0});sc.StringValue=sc.StringType=void 0;var Qx=sr(),Lf=class t extends Qx.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};sc.StringType=Lf;Lf.ClassName="StringType";var ap=class t extends Qx.PrimitiveValue{constructor(e){super(new Lf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=p.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};sc.StringValue=ap;ap.ClassName="StringValue"});var ac=B(oc=>{"use strict";h();Object.defineProperty(oc,"__esModule",{value:!0});oc.TokenIdentifierValue=oc.TokenIdentifierType=void 0;var Kx=sr(),Rz="EGLD",Ff=class t extends Kx.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};oc.TokenIdentifierType=Ff;Ff.ClassName="TokenIdentifierType";var cp=class t extends Kx.PrimitiveValue{constructor(e){super(new Ff),this.value=e}static egld(){return new t(Rz)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};oc.TokenIdentifierValue=cp;cp.ClassName="TokenIdentifierValue"});var fp=B(Bn=>{"use strict";h();var Bz=Bn&&Bn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Mz=Bn&&Bn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Lz=Bn&&Bn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Bz(e,t,r);return Mz(e,t),e};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Tuple=Bn.TupleType=void 0;var Fz=Lz(Ie()),Wx=zu(),$x=Wu(),Uf=class t extends $x.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new Wx.FieldDefinition(Yx(i),"anonymous tuple field",n))}};Bn.TupleType=Uf;Uf.ClassName="TupleType";function Yx(t){return`field${t}`}var lp=class t extends $x.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Fz.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new Uf(...r),i=e.map((s,o)=>new Wx.Field(s,Yx(o)));return new t(n,i)}};Bn.Tuple=lp;lp.ClassName="Tuple"});var gp=B(mo=>{"use strict";h();Object.defineProperty(mo,"__esModule",{value:!0});mo.VariadicValue=mo.CountedVariadicType=mo.VariadicType=void 0;var uc=sr(),Ua=class t extends uc.Type{constructor(e,r=!1){super("Variadic",[e],uc.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};mo.VariadicType=Ua;Ua.ClassName="VariadicType";var hp=class extends uc.Type{constructor(e){super("Variadic",[e],uc.TypeCardinality.variable())}getClassName(){return Ua.ClassName}};mo.CountedVariadicType=hp;hp.ClassName="VariadicType";var dp=class t extends uc.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Ua(new uc.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Ua(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();var Uz=ki&&ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qz=ki&&ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Vz=ki&&ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Uz(e,t,r);return qz(e,t),e};Object.defineProperty(ki,"__esModule",{value:!0});ki.TypeMapper=void 0;var Jx=Vz(Ie()),kz=Yu(),yA=Lg(),Hz=yf(),Gz=po(),jz=qx(),pp=kg(),wA=hf(),zz=zu(),Xx=Ef(),Vi=Kg(),Qz=Sf(),Zx=Yg(),Mn=Mf(),Kz=up(),e6=Wu(),t6=ac(),yo=fp(),mp=gp(),vA=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new Xx.OptionType(r[0])],["List",(...r)=>new Xx.ListType(r[0])],["VarArgs",(...r)=>new mp.VariadicType(r[0])],["MultiResultVec",(...r)=>new mp.VariadicType(r[0])],["variadic",(...r)=>new mp.VariadicType(r[0])],["counted-variadic",(...r)=>new mp.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new yA.OptionalType(r[0])],["optional",(...r)=>new yA.OptionalType(r[0])],["OptionalResult",(...r)=>new yA.OptionalType(r[0])],["multi",(...r)=>new pp.CompositeType(...r)],["MultiArg",(...r)=>new pp.CompositeType(...r)],["MultiResult",(...r)=>new pp.CompositeType(...r)],["multi",(...r)=>new pp.CompositeType(...r)],["tuple",(...r)=>new yo.TupleType(...r)],["tuple2",(...r)=>new yo.TupleType(...r)],["tuple3",(...r)=>new yo.TupleType(...r)],["tuple4",(...r)=>new yo.TupleType(...r)],["tuple5",(...r)=>new yo.TupleType(...r)],["tuple6",(...r)=>new yo.TupleType(...r)],["tuple7",(...r)=>new yo.TupleType(...r)],["tuple8",(...r)=>new yo.TupleType(...r)],["array2",(...r)=>new Vi.ArrayVecType(2,r[0])],["array8",(...r)=>new Vi.ArrayVecType(8,r[0])],["array16",(...r)=>new Vi.ArrayVecType(16,r[0])],["array20",(...r)=>new Vi.ArrayVecType(20,r[0])],["array32",(...r)=>new Vi.ArrayVecType(32,r[0])],["array46",(...r)=>new Vi.ArrayVecType(46,r[0])],["array48",(...r)=>new Vi.ArrayVecType(48,r[0])],["array64",(...r)=>new Vi.ArrayVecType(64,r[0])],["array128",(...r)=>new Vi.ArrayVecType(128,r[0])],["array256",(...r)=>new Vi.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new Mn.U8Type],["u16",new Mn.U16Type],["u32",new Mn.U32Type],["u64",new Mn.U64Type],["U64",new Mn.U64Type],["BigUint",new Mn.BigUIntType],["i8",new Mn.I8Type],["i16",new Mn.I16Type],["i32",new Mn.I32Type],["i64",new Mn.I64Type],["Bigint",new Mn.BigIntType],["BigInt",new Mn.BigIntType],["bool",new Hz.BooleanType],["bytes",new Gz.BytesType],["Address",new kz.AddressType],["H256",new Qz.H256Type],["utf-8 string",new Kz.StringType],["TokenIdentifier",new t6.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new t6.TokenIdentifierType],["CodeMetadata",new jz.CodeMetadataType],["nothing",new Zx.NothingType],["AsyncCall",new Zx.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new Jx.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(wA.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(e6.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new e6.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new wA.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new wA.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new zz.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new Jx.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};ki.TypeMapper=vA});var o6=B(Hi=>{"use strict";h();var Wz=Hi&&Hi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),$z=Hi&&Hi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yz=Hi&&Hi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wz(e,t,r);return $z(e,t),e};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.AbiRegistry=void 0;var r6=Yz(Ie()),qf=Rn(),Vf=oA(),n6=hf(),EA=Rx(),i6=Wu(),Jz=AA(),Xz="?",bA=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||Xz,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],u=Vf.EndpointDefinition.fromJSON({name:"constructor",...n}),a=i.map(A=>Vf.EndpointDefinition.fromJSON(A)),c=[];for(let A in s){let T=s[A];if(T.type=="struct")c.push(i6.StructType.fromJSON({name:A,fields:T.fields}));else if(T.type=="enum"||T.type=="explicit-enum")c.push(n6.EnumType.fromJSON({name:A,variants:T.variants}));else throw new r6.ErrTypingSystem(`Cannot handle custom type: ${A}`)}let f=o.map(A=>EA.EventDefinition.fromJSON(A));return new t({name:r,constructorDefinition:u,endpoints:a,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return qf.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(i6.StructType.ClassName));return qf.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(n6.EnumType.ClassName));return qf.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return qf.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return qf.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new Jz.TypeMapper([]),r=[];for(let u of this.customTypes)this.mapCustomTypeDepthFirst(u,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new r6.ErrTypingSystem("Did not re-map all custom types");let n=s6(this.constructorDefinition,e),i=[];for(let u of this.endpoints)i.push(s6(u,e));let s=this.events.map(u=>Zz(u,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(u=>u.getName()==e.getName())>=0)return;for(let u of e.getNamesOfDependencies()){let a=r.find(c=>c.getName()==u);a&&this.mapCustomTypeDepthFirst(a,r,n,i)}let o=n.mapType(e);i.push(o)}};Hi.AbiRegistry=bA;function s6(t,e){let r=t.input.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new Vf.EndpointDefinition(t.name,r,n,t.modifiers)}function Zz(t,e){let r=t.inputs.map(n=>new EA.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new EA.EventDefinition(t.identifier,r)}});var u6=B(cc=>{"use strict";h();Object.defineProperty(cc,"__esModule",{value:!0});cc.createListOfTokenIdentifiers=cc.createListOfAddresses=void 0;var eQ=Yu(),a6=Ef(),tQ=ac();function rQ(t){let e=t.map(n=>new eQ.AddressValue(n));return a6.List.fromItems(e)}cc.createListOfAddresses=rQ;function nQ(t){let e=t.map(n=>new tQ.TokenIdentifierValue(n));return a6.List.fromItems(e)}cc.createListOfTokenIdentifiers=nQ});var b6=B(Dr=>{"use strict";h();var iQ=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sQ=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oQ=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iQ(e,t,r);return sQ(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.onPrimitiveTypeSelect=Dr.onPrimitiveValueSelect=Dr.onTypedValueSelect=Dr.onTypeSelect=void 0;var wp=oQ(Ie()),c6=Yu(),l6=yf(),f6=po(),h6=hf(),yp=Ef(),d6=Sf(),g6=Mf(),p6=Yg(),m6=Wu(),y6=ac(),w6=fp(),v6=sr(),A6=Kg(),E6=up();function aQ(t,e){if(t.hasExactClass(yp.OptionType.ClassName))return e.onOption();if(t.hasExactClass(yp.ListType.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(v6.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(m6.StructType.ClassName))return e.onStruct();if(t.hasExactClass(w6.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't known: ${t}`)}Dr.onTypeSelect=aQ;function uQ(t,e){if(t.hasClassOrSuperclass(v6.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(yp.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(yp.List.ClassName))return e.onList();if(t.hasExactClass(A6.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(m6.Struct.ClassName))return e.onStruct();if(t.hasExactClass(w6.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(h6.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't typed: ${t}`)}Dr.onTypedValueSelect=uQ;function cQ(t,e){if(t.hasExactClass(l6.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringValue.ClassName))return e.onString();if(t.hasExactClass(d6.H256Value.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(p6.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Dr.onPrimitiveValueSelect=cQ;function lQ(t,e){if(t.hasExactClass(l6.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(g6.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(c6.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(f6.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(E6.StringType.ClassName))return e.onString();if(t.hasExactClass(d6.H256Type.ClassName))return e.onH256();if(t.hasExactClass(y6.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(p6.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new wp.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Dr.onPrimitiveTypeSelect=lQ});var dr=B(He=>{"use strict";h();var fQ=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ut=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fQ(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});Ut(o6(),He);Ut(Yu(),He);Ut(Lg(),He);Ut(yf(),He);Ut(po(),He);Ut(kg(),He);Ut(oA(),He);Ut(hf(),He);Ut(u6(),He);Ut(zu(),He);Ut(Ef(),He);Ut(Kg(),He);Ut(Sf(),He);Ut(b6(),He);Ut(Yg(),He);Ut(Mf(),He);Ut(up(),He);Ut(Wu(),He);Ut(ac(),He);Ut(fp(),He);Ut(lf(),He);Ut(AA(),He);Ut(sr(),He);Ut(gp(),He)});var I6=B(Gi=>{"use strict";h();var hQ=Gi&&Gi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),dQ=Gi&&Gi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gQ=Gi&&Gi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hQ(e,t,r);return dQ(e,t),e};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.OptionValueBinaryCodec=void 0;var S6=gQ(Ie()),vp=dr(),SA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[vp.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[vp.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new vp.OptionValue(r);if(e[0]!=1)throw new S6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new vp.OptionValue(r,n)}encodeNested(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([])}};Gi.OptionValueBinaryCodec=SA});var T6=B(Ap=>{"use strict";h();Object.defineProperty(Ap,"__esModule",{value:!0});Ap.AddressBinaryCodec=void 0;var pQ=Ve(),mQ=dr(),IA=class{decodeNested(e){let r=e.slice(0,32),n=new pQ.Address(r);return[new mQ.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};Ap.AddressBinaryCodec=IA});var C6=B(ji=>{"use strict";h();var yQ=ji&&ji.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),wQ=ji&&ji.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vQ=ji&&ji.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yQ(e,t,r);return wQ(e,t),e};Object.defineProperty(ji,"__esModule",{value:!0});ji.BooleanBinaryCodec=void 0;var AQ=vQ(Ie()),_6=dr(),kf=class t{decodeNested(e){let r=e.readUInt8(0);return[new _6.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new AQ.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new _6.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([])}};ji.BooleanBinaryCodec=kf;kf.TRUE=1;kf.FALSE=0});var bp=B(Ep=>{"use strict";h();Object.defineProperty(Ep,"__esModule",{value:!0});Ep.SizeOfU32=void 0;Ep.SizeOfU32=4});var x6=B(lc=>{"use strict";h();var EQ=lc&&lc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lc,"__esModule",{value:!0});lc.NumericalBinaryCodec=void 0;var Hf=EQ((rr(),_e(fr))),TA=dr(),N6=bp(),$t=Bu(),_A=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=N6.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),u=i+n;return[o,u]}decodeTopLevel(e,r){let n=$t.cloneBuffer(e);if(e.length==0)return new TA.NumericalValue(r,new Hf.default(0));if(!r.withSign||$t.isMsbZero(n)){let c=$t.bufferToBigInt(n);return new TA.NumericalValue(r,c)}$t.flipBufferBitsInPlace(n);let a=$t.bufferToBigInt(n).multipliedBy(new Hf.default(-1)).minus(new Hf.default(1));return new TA.NumericalValue(r,a)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=p.Buffer.alloc(N6.SizeOfU32);return n.writeUInt32BE(r.length),p.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return p.Buffer.alloc(r,0);if(!e.withSign){let o=$t.bigIntToBuffer(e.value),u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}if(e.value.isPositive()){let o=$t.bigIntToBuffer(e.value);$t.isMsbOne(o)&&(o=$t.prependByteToBuffer(o,0));let u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}let n=e.value.plus(new Hf.default(1)),i=$t.bigIntToBuffer(n);$t.flipBufferBitsInPlace(i),$t.isMsbZero(i)&&(i=$t.prependByteToBuffer(i,255));let s=p.Buffer.alloc(r-i.length,255);return p.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?p.Buffer.alloc(0):r?this.encodePrimitive(e):$t.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=$t.bigIntToBuffer(e.value);return $t.isMsbOne(i)&&(i=$t.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Hf.default(1)),n=$t.bigIntToBuffer(r);return $t.flipBufferBitsInPlace(n),$t.isMsbZero(n)&&(n=$t.prependByteToBuffer(n,255)),n}};lc.NumericalBinaryCodec=_A});var O6=B(Sp=>{"use strict";h();Object.defineProperty(Sp,"__esModule",{value:!0});Sp.H256BinaryCodec=void 0;var bQ=Sf(),CA=class{decodeNested(e){let r=e.slice(0,32);return[new bQ.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Sp.H256BinaryCodec=CA});var _p=B(Tp=>{"use strict";h();Object.defineProperty(Tp,"__esModule",{value:!0});Tp.BytesBinaryCodec=void 0;var D6=po(),Ip=bp(),NA=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(Ip.SizeOfU32,Ip.SizeOfU32+r);return[new D6.BytesValue(n),Ip.SizeOfU32+r]}decodeTopLevel(e){return new D6.BytesValue(e)}encodeNested(e){let r=p.Buffer.alloc(Ip.SizeOfU32);return r.writeUInt32BE(e.getLength()),p.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Tp.BytesBinaryCodec=NA});var R6=B(Cp=>{"use strict";h();Object.defineProperty(Cp,"__esModule",{value:!0});Cp.TokenIdentifierCodec=void 0;var SQ=po(),P6=ac(),IQ=_p(),xA=class{constructor(){this.bytesCodec=new IQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new P6.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new P6.TokenIdentifierValue(r.toString())}encodeNested(e){let r=SQ.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Cp.TokenIdentifierCodec=xA});var M6=B(Np=>{"use strict";h();Object.defineProperty(Np,"__esModule",{value:!0});Np.NothingCodec=void 0;var B6=dr(),OA=class{decodeNested(){return[new B6.NothingValue,0]}decodeTopLevel(){return new B6.NothingValue}encodeNested(){return p.Buffer.from([])}encodeTopLevel(){return p.Buffer.from([])}};Np.NothingCodec=OA});var F6=B(xp=>{"use strict";h();Object.defineProperty(xp,"__esModule",{value:!0});xp.StringBinaryCodec=void 0;var L6=dr(),TQ=po(),_Q=_p(),DA=class{constructor(){this.bytesBinaryCodec=new _Q.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new L6.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new L6.StringValue(e.toString())}encodeNested(e){let r=TQ.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};xp.StringBinaryCodec=DA});var U6=B(Dp=>{"use strict";h();Object.defineProperty(Dp,"__esModule",{value:!0});Dp.PrimitiveBinaryCodec=void 0;var Op=dr(),CQ=T6(),NQ=C6(),xQ=x6(),OQ=O6(),DQ=_p(),PQ=R6(),RQ=M6(),BQ=F6(),PA=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new NQ.BooleanBinaryCodec,this.numericalCodec=new xQ.NumericalBinaryCodec,this.addressCodec=new CQ.AddressBinaryCodec,this.h256Codec=new OQ.H256BinaryCodec,this.bytesCodec=new DQ.BytesBinaryCodec,this.stringCodec=new BQ.StringBinaryCodec,this.tokenIdentifierCodec=new PQ.TokenIdentifierCodec,this.nothingCodec=new RQ.NothingCodec}decodeNested(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Op.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Op.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};Dp.PrimitiveBinaryCodec=PA});var k6=B(Pp=>{"use strict";h();Object.defineProperty(Pp,"__esModule",{value:!0});Pp.ListBinaryCodec=void 0;var q6=dr(),V6=bp(),RA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,u=V6.SizeOfU32;e=o.slice(u);for(let a=0;a0;){let[u,a]=this.binaryCodec.decodeNested(e,n);i.push(u),o+=a,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new q6.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=p.Buffer.alloc(V6.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return p.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return p.Buffer.concat(r)}};Pp.ListBinaryCodec=RA});var MA=B(Rp=>{"use strict";h();Object.defineProperty(Rp,"__esModule",{value:!0});Rp.FieldsBinaryCodec=void 0;var MQ=dr(),BA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,u]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(u),i+=u;let a=new MQ.Field(o,s.name);n.push(a)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return p.Buffer.concat(r)}};Rp.FieldsBinaryCodec=BA});var FA=B(Bp=>{"use strict";h();Object.defineProperty(Bp,"__esModule",{value:!0});Bp.StructBinaryCodec=void 0;var LQ=dr(),FQ=MA(),LA=class{constructor(e){this.fieldsCodec=new FQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new LQ.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Bp.StructBinaryCodec=LA});var H6=B(Lp=>{"use strict";h();Object.defineProperty(Lp,"__esModule",{value:!0});Lp.EnumBinaryCodec=void 0;var Mp=dr(),UQ=MA(),UA=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new UQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[u,a]=this.fieldsCodec.decodeNested(e,o);return[new Mp.EnumValue(r,s,u),i+a]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Mp.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Mp.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return p.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Mp.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return p.Buffer.concat([o,i])}};Lp.EnumBinaryCodec=UA});var G6=B(Fp=>{"use strict";h();Object.defineProperty(Fp,"__esModule",{value:!0});Fp.TupleBinaryCodec=void 0;var qQ=FA(),qA=class{constructor(e){this.structCodec=new qQ.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Fp.TupleBinaryCodec=qA});var j6=B(Up=>{"use strict";h();Object.defineProperty(Up,"__esModule",{value:!0});Up.ArrayVecBinaryCodec=void 0;var VQ=dr(),VA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let u=0;u{"use strict";h();var kQ=Ln&&Ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),HQ=Ln&&Ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),GQ=Ln&&Ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&kQ(e,t,r);return HQ(e,t),e};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BinaryCodecConstraints=Ln.BinaryCodec=void 0;var z6=GQ(Ie()),qp=dr(),Q6=Rn(),jQ=I6(),zQ=U6(),QQ=k6(),KQ=FA(),WQ=H6(),$Q=G6(),YQ=j6(),kA=class{constructor(e=null){this.constraints=e||new Vp,this.optionCodec=new jQ.OptionValueBinaryCodec(this),this.listCodec=new QQ.ListBinaryCodec(this),this.arrayCodec=new YQ.ArrayVecBinaryCodec(this),this.primitiveCodec=new zQ.PrimitiveBinaryCodec(this),this.structCodec=new KQ.StructBinaryCodec(this),this.tupleCodec=new $Q.TupleBinaryCodec(this),this.enumCodec=new WQ.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=qp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return Q6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),qp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Ln.BinaryCodec=kA;var Vp=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new z6.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new z6.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Ln.BinaryCodecConstraints=Vp});var K6=B(Fn=>{"use strict";h();var JQ=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decodeBigNumber=Fn.decodeString=Fn.decodeBool=Fn.decodeUnsignedNumber=void 0;var XQ=JQ((rr(),_e(fr))),kp=dr(),ZQ=HA(),Hp=new ZQ.BinaryCodec;function eK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return Number(e.valueOf())}Fn.decodeUnsignedNumber=eK;function tK(t){return!!Hp.decodeTopLevel(t,new kp.BooleanType).valueOf()}Fn.decodeBool=tK;function rK(t){let e=Hp.decodeTopLevel(t,new kp.BytesType);return String(e.valueOf())}Fn.decodeString=rK;function nK(t){let e=Hp.decodeTopLevel(t,new kp.BigUIntType);return new XQ.default(e.valueOf())}Fn.decodeBigNumber=nK});var GA=B(wo=>{"use strict";h();var iK=wo&&wo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),W6=wo&&wo.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&iK(e,t,r)};Object.defineProperty(wo,"__esModule",{value:!0});W6(HA(),wo);W6(K6(),wo)});var fc=B(Gp=>{"use strict";h();Object.defineProperty(Gp,"__esModule",{value:!0});Gp.ArgSerializer=void 0;var $6=hr(),sK=GA(),Y6=dr(),jA=Lg(),zA=kg(),QA=gp(),oK={codec:new sK.BinaryCodec},KA=class{constructor(e){e={...oK,...e},this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split($6.ARGUMENTS_SEPARATOR).map(r=>p.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join($6.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(jA.OptionalValue.ClassName)){let a=o;a.isSet()&&i(a.getTypedValue());return}if(o.hasExactClass(QA.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(zA.CompositeValue.ClassName)){let a=o;for(let c of a.getItems())i(c);return}let u=r.codec.encodeTopLevel(o);n.push(u)}function s(o){if(o.getType().isCounted){let a=new Y6.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(a))}for(let a of o.getItems())i(a)}return n}};Gp.ArgSerializer=KA});var WA=B((cye,J6)=>{h();Rs.notEqual=uK;Rs.notOk=cK;Rs.equal=aK;Rs.ok=Rs;J6.exports=Rs;function aK(t,e,r){Rs(t==e,r)}function uK(t,e,r){Rs(t!=e,r)}function cK(t,e){Rs(!t,e)}function Rs(t,e){if(!t)throw new Error(e||"AssertionError")}});var Z6=B((fye,X6)=>{h();X6.exports=$A;$A.supported=typeof WebAssembly<"u";function $A(t){if(!$A.supported)return null;var e=t&&t.imports,r=lK("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(a){i.exports.memory.grow(Math.ceil(Math.abs(a-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(a){if(i.exports)return a();if(n){n.then(a.bind(null,null)).catch(a);return}try{if(t&&t.async)throw new Error("async");u({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(u)}o(a)}function u(a){i.exports=a.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function lK(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(fK)):new(io()).Buffer(t,"base64")}function fK(t){return t.charCodeAt(0)}});var oO=B((pye,Qi)=>{h();var zi=WA(),xt=Z6()(),Bs=64,jp=[];Qi.exports=Un;var eO=Qi.exports.BYTES_MIN=16,tO=Qi.exports.BYTES_MAX=64,dye=Qi.exports.BYTES=32,rO=Qi.exports.KEYBYTES_MIN=16,nO=Qi.exports.KEYBYTES_MAX=64,gye=Qi.exports.KEYBYTES=32,iO=Qi.exports.SALTBYTES=16,sO=Qi.exports.PERSONALBYTES=16;function Un(t,e,r,n,i){if(!(this instanceof Un))return new Un(t,e,r,n,i);if(!(xt&&xt.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(zi(t>=eO,"digestLength must be at least "+eO+", was given "+t),zi(t<=tO,"digestLength must be at most "+tO+", was given "+t),e!=null&&zi(e.length>=rO,"key must be at least "+rO+", was given "+e.length),e!=null&&zi(e.length<=nO,"key must be at least "+nO+", was given "+e.length),r!=null&&zi(r.length===iO,"salt must be exactly "+iO+", was given "+r.length),n!=null&&zi(n.length===sO,"personal must be exactly "+sO+", was given "+n.length)),jp.length||(jp.push(Bs),Bs+=216),this.digestLength=t,this.finalized=!1,this.pointer=jp.pop(),xt.memory.fill(0,0,64),xt.memory[0]=this.digestLength,xt.memory[1]=e?e.length:0,xt.memory[2]=1,xt.memory[3]=1,r&&xt.memory.set(r,32),n&&xt.memory.set(n,48),this.pointer+216>xt.memory.length&&xt.realloc(this.pointer+216),xt.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),xt.memory.fill(0,Bs,Bs+e.length),xt.memory[this.pointer+200]=128)}Un.prototype.update=function(t){return zi(this.finalized===!1,"Hash instance finalized"),zi(t,"input must be TypedArray or Buffer"),Bs+t.length>xt.memory.length&&xt.realloc(Bs+t.length),xt.memory.set(t,Bs),xt.exports.blake2b_update(this.pointer,Bs,Bs+t.length),this};Un.prototype.digest=function(t){if(zi(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,jp.push(this.pointer),xt.exports.blake2b_final(this.pointer),!t||t==="binary")return xt.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return dK(xt.memory,this.pointer+128,this.digestLength);zi(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{h();var Eo=WA(),jf=oO();function zp(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function aO(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function gO(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vo(t,e,r,n,i,s){var o=Gf[i],u=Gf[i+1],a=Gf[s],c=Gf[s+1];zp(Te,t,e),aO(Te,t,o,u);var f=Te[n]^Te[t],d=Te[n+1]^Te[t+1];Te[n]=d,Te[n+1]=f,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=f>>>24^d<<8,Te[e+1]=d>>>24^f<<8,zp(Te,t,e),aO(Te,t,a,c),f=Te[n]^Te[t],d=Te[n+1]^Te[t+1],Te[n]=f>>>16^d<<16,Te[n+1]=d>>>16^f<<16,zp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=d>>>31^f<<1,Te[e+1]=f>>>31^d<<1}var pO=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),pK=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Pr=new Uint8Array(pK.map(function(t){return t*2})),Te=new Uint32Array(32),Gf=new Uint32Array(32);function mO(t,e){var r=0;for(r=0;r<16;r++)Te[r]=t.h[r],Te[r+16]=pO[r];for(Te[24]=Te[24]^t.t,Te[25]=Te[25]^t.t/4294967296,e&&(Te[28]=~Te[28],Te[29]=~Te[29]),r=0;r<32;r++)Gf[r]=gO(t.b,4*r);for(r=0;r<12;r++)vo(0,8,16,24,Pr[r*16+0],Pr[r*16+1]),vo(2,10,18,26,Pr[r*16+2],Pr[r*16+3]),vo(4,12,20,28,Pr[r*16+4],Pr[r*16+5]),vo(6,14,22,30,Pr[r*16+6],Pr[r*16+7]),vo(0,10,20,30,Pr[r*16+8],Pr[r*16+9]),vo(2,12,22,24,Pr[r*16+10],Pr[r*16+11]),vo(4,14,16,26,Pr[r*16+12],Pr[r*16+13]),vo(6,8,18,28,Pr[r*16+14],Pr[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Te[r]^Te[r+16]}var Ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hc(t,e,r,n){Ao.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Ao[0]=t,e&&(Ao[1]=e.length),Ao[2]=1,Ao[3]=1,r&&Ao.set(r,32),n&&Ao.set(n,48);for(var i=0;i<16;i++)this.h[i]=pO[i]^gO(Ao,i*4);e&&(yO(this,e),this.c=128)}hc.prototype.update=function(t){return Eo(t!=null,"input must be Uint8Array or Buffer"),yO(this,t),this};hc.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Eo(e.length>=this.outlen,"out must have at least outlen bytes of space"),mK(this,e),t==="hex"?yK(e):e};hc.prototype.final=hc.prototype.digest;hc.ready=function(t){jf.ready(function(){t()})};function yO(t,e){for(var r=0;r>2]>>8*(r&3);return e}function yK(t){for(var e="",r=0;r=uO,"outlen must be at least "+uO+", was given "+e),Eo(e<=cO,"outlen must be at most "+cO+", was given "+e),r!=null&&Eo(r.length>=lO,"key must be at least "+lO+", was given "+r.length),r!=null&&Eo(r.length<=fO,"key must be at most "+fO+", was given "+r.length),n!=null&&Eo(n.length===hO,"salt must be exactly "+hO+", was given "+n.length),i!=null&&Eo(i.length===dO,"personal must be exactly "+dO+", was given "+i.length)),new wO(e,r,n,i)};Jr.exports.ready=function(t){jf.ready(function(){t()})};Jr.exports.WASM_SUPPORTED=jf.SUPPORTED;Jr.exports.WASM_LOADED=!1;var uO=Jr.exports.BYTES_MIN=16,cO=Jr.exports.BYTES_MAX=64,yye=Jr.exports.BYTES=32,lO=Jr.exports.KEYBYTES_MIN=16,fO=Jr.exports.KEYBYTES_MAX=64,wye=Jr.exports.KEYBYTES=32,hO=Jr.exports.SALTBYTES=16,dO=Jr.exports.PERSONALBYTES=16;jf.ready(function(t){t||(Jr.exports.WASM_LOADED=!0,wO=jf)})});var vO=B(Qp=>{"use strict";h();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.Code=void 0;var vK=YA(),AK=32,JA=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return p.Buffer.from(this.hex,"hex")}computeHash(){let e=vK(AK).update(this.valueOf()).digest();return p.Buffer.from(e)}};Qp.Code=JA});var XA=B(Kp=>{"use strict";h();Object.defineProperty(Kp,"__esModule",{value:!0});Kp.CodeMetadata=void 0;var dc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBytes(e){return t.fromBuffer(p.Buffer.from(e))}static fromBuffer(e){if(e.length{"use strict";h();var EK=Ki&&Ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bK=Ki&&Ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SK=Ki&&Ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EK(e,t,r);return bK(e,t),e};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ContractFunction=void 0;var IK=SK(Ie()),ZA=class t{constructor(e){if(this.name=e,e==null)throw new IK.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Ki.ContractFunction=ZA});var rE=B(Wp=>{"use strict";h();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.Compatibility=void 0;var TK=Ve(),tE=class{static guardAddressIsSetAndNonZero(e,r,n){!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==TK.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`)}};Wp.Compatibility=tE});var Ms=B($p=>{"use strict";h();Object.defineProperty($p,"__esModule",{value:!0});$p.TransactionPayload=void 0;var nE=class t{constructor(e){this.data=p.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=p.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>p.Buffer.from(e,"hex"))}length(){return p.Buffer.from(this.data).length}};$p.TransactionPayload=nE});var gc=B(Yp=>{"use strict";h();Object.defineProperty(Yp,"__esModule",{value:!0});Yp.TransactionBuilder=void 0;var _K=hr(),CK=Xr(),NK=Ms(),iE=class{constructor(e){this.config=e.config,this.sender=e.sender,this.receiver=e.receiver,this.dataParts=e.dataParts,this.providedGasLimit=e.gasLimit,this.addDataMovementGas=e.addDataMovementGas,this.amount=e.amount}computeGasLimit(e){return this.addDataMovementGas?this.config.minGasLimit+this.config.gasLimitPerByte*BigInt(e.length())+this.providedGasLimit:this.providedGasLimit}buildTransactionPayload(){let e=this.dataParts.join(_K.ARGUMENTS_SEPARATOR);return new NK.TransactionPayload(e)}build(){let e=this.buildTransactionPayload(),r=this.computeGasLimit(e);return new CK.Transaction({sender:this.sender.bech32(),receiver:this.receiver.bech32(),gasLimit:r,value:this.amount||0n,data:e.valueOf(),chainID:this.config.chainID})}};Yp.TransactionBuilder=iE});var AO=B(Jp=>{"use strict";h();Object.defineProperty(Jp,"__esModule",{value:!0});Jp.DelegationTransactionsFactory=void 0;var xK=Ve(),OK=hr(),DK=Ie(),fn=qn(),Zr=gc(),sE=class{constructor(e){this.config=e.config,this.argSerializer=new fn.ArgSerializer}createTransactionForNewDelegationContract(e){let r=["createNewDelegationContract",...this.argSerializer.valuesToStrings([new fn.BigUIntValue(e.totalDelegationCap),new fn.BigUIntValue(e.serviceFee)])],n=this.config.gasLimitCreateDelegationContract+this.config.additionalGasLimitForDelegationOperations;return new Zr.TransactionBuilder({config:this.config,sender:e.sender,receiver:xK.Address.fromBech32(OK.DELEGATION_MANAGER_SC_ADDRESS),dataParts:r,gasLimit:n,addDataMovementGas:!0,amount:e.amount}).build()}createTransactionForAddingNodes(e){if(e.publicKeys.length!==e.signedMessages.length)throw new DK.Err("The number of public keys should match the number of signed messages");let r=e.signedMessages.map(o=>new fn.BytesValue(p.Buffer.from(o))),n=this.argSerializer.valuesToStrings(r),i=e.publicKeys.length,s=["addNodes"];for(let o=0;o{h();var EO=(rr(),_e(fr)),bO=SO.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function u(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(f){var d=s[f];return typeof d=="string"?d:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function a(c,f){var d,w,A,T,x=n,R,V=f[c],U=V!=null&&(V instanceof EO||EO.isBigNumber(V));switch(V&&typeof V=="object"&&typeof V.toJSON=="function"&&(V=V.toJSON(c)),typeof o=="function"&&(V=o.call(f,c,V)),typeof V){case"string":return U?V:u(V);case"number":return isFinite(V)?String(V):"null";case"boolean":case"null":case"bigint":return String(V);case"object":if(!V)return"null";if(n+=i,R=[],Object.prototype.toString.apply(V)==="[object Array]"){for(T=V.length,d=0;d{"use strict";h();var cH=xn&&xn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xn,"__esModule",{value:!0});xn.TokenPayment=xn.TokenComputer=xn.TokenTransfer=xn.Token=void 0;var Ta=cH((rr(),_e(fr))),Du=Ie(),q3="EGLD",V3=18;Ta.default.set({ROUNDING_MODE:1});var Vd=class{constructor(e){this.identifier=e.identifier,this.nonce=e.nonce||0n}};xn.Token=Vd;var kd=class t{constructor(e){if(this.isLegacyTokenTransferOptions(e)){let r=new Ta.default(e.amountAsBigInteger);if(!r.isInteger()||r.isNegative())throw new Du.ErrInvalidArgument(`bad amountAsBigInteger: ${e.amountAsBigInteger}`);this.tokenIdentifier=e.tokenIdentifier,this.nonce=e.nonce,this.amountAsBigInteger=r,this.numDecimals=e.numDecimals||0,this.token=new Vd({identifier:e.tokenIdentifier,nonce:BigInt(e.nonce)}),this.amount=BigInt(this.amountAsBigInteger.toFixed(0))}else this.token=e.token,this.amount=e.amount,this.tokenIdentifier=e.token.identifier,this.nonce=Number(e.token.nonce),this.amountAsBigInteger=new Ta.default(this.amount.toString()),this.numDecimals=0}isLegacyTokenTransferOptions(e){return e.tokenIdentifier!==void 0}static egldFromAmount(e){let r=new Ta.default(e).shiftedBy(V3).decimalPlaces(0);return this.egldFromBigInteger(r)}static egldFromBigInteger(e){return new t({tokenIdentifier:q3,nonce:0,amountAsBigInteger:e,numDecimals:V3})}static fungibleFromAmount(e,r,n){let i=new Ta.default(r).shiftedBy(n).decimalPlaces(0);return this.fungibleFromBigInteger(e,i,n)}static fungibleFromBigInteger(e,r,n=0){return new t({tokenIdentifier:e,nonce:0,amountAsBigInteger:r,numDecimals:n})}static nonFungible(e,r){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:1,numDecimals:0})}static semiFungible(e,r,n){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:0})}static metaEsdtFromAmount(e,r,n,i){let s=new Ta.default(n).shiftedBy(i).decimalPlaces(0);return this.metaEsdtFromBigInteger(e,r,s,i)}static metaEsdtFromBigInteger(e,r,n,i=0){return new t({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}toString(){return this.amount.toString()}valueOf(){return new Ta.default(this.amount.toString())}toPrettyString(){return`${this.toAmount()} ${this.tokenIdentifier}`}toAmount(){return this.amountAsBigInteger.shiftedBy(-this.numDecimals).toFixed(this.numDecimals)}isEgld(){return this.token.identifier==q3}isFungible(){return this.token.nonce==0n}};xn.TokenTransfer=kd;var gv=class{constructor(){}isFungible(e){return e.nonce===0n}extractNonceFromExtendedIdentifier(e){let r=e.split("-");if(this.checkIfExtendedIdentifierWasProvided(r),this.checkLengthOfRandomSequence(r[1]),r.length==2)return 0;let n=p.Buffer.from(r[2],"hex");return lH(n)}extractIdentifierFromExtendedIdentifier(e){let r=e.split("-");return this.checkIfExtendedIdentifierWasProvided(r),this.ensureTokenTickerValidity(r[0]),this.checkLengthOfRandomSequence(r[1]),r[0]+"-"+r[1]}checkIfExtendedIdentifierWasProvided(e){if(e.length<2||e.length>3)throw new Du.ErrInvalidTokenIdentifier("Invalid extended token identifier provided")}checkLengthOfRandomSequence(e){if(e.length!==6)throw new Du.ErrInvalidTokenIdentifier("The identifier is not valid. The random sequence does not have the right length")}ensureTokenTickerValidity(e){if(e.length<3||e.length>10)throw new Du.ErrInvalidTokenIdentifier("The token ticker should be between 3 and 10 characters");if(!e.match(/^[a-zA-Z0-9]+$/))throw new Du.ErrInvalidTokenIdentifier("The token ticker should only contain alphanumeric characters");if(e!=e.toUpperCase())throw new Du.ErrInvalidTokenIdentifier("The token ticker should be upper case")}};xn.TokenComputer=gv;function lH(t){return t.readUIntBE(0,t.length)}var pv=class extends kd{constructor(e,r,n,i){super({tokenIdentifier:e,nonce:r,amountAsBigInteger:n,numDecimals:i})}};xn.TokenPayment=pv});var hr=D(Ae=>{"use strict";h();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.UNKNOWN_SIGNER=Ae.SDK_JS_SIGNER=Ae.METACHAIN_ID=Ae.WasmVirtualMachine=Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=Ae.BECH32_ADDRESS_LENGTH=Ae.HEX_TRANSACTION_HASH_LENGTH=Ae.MESSAGE_PREFIX=Ae.DEFAULT_MESSAGE_VERSION=Ae.ESDT_CONTRACT_ADDRESS=Ae.DEFAULT_HRP=Ae.DELEGATION_MANAGER_SC_ADDRESS=Ae.CONTRACT_DEPLOY_ADDRESS=Ae.VM_TYPE_WASM_VM=Ae.ARGUMENTS_SEPARATOR=Ae.ESDT_TRANSFER_VALUE=Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDTNFT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_FUNCTION_NAME=Ae.ESDT_TRANSFER_GAS_LIMIT=Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=Ae.TRANSACTION_VERSION_DEFAULT=Ae.TRANSACTION_OPTIONS_TX_GUARDED=Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=Ae.TRANSACTION_OPTIONS_DEFAULT=Ae.TRANSACTION_MIN_GAS_PRICE=void 0;Ae.TRANSACTION_MIN_GAS_PRICE=1e9;Ae.TRANSACTION_OPTIONS_DEFAULT=0;Ae.TRANSACTION_OPTIONS_TX_HASH_SIGN=1;Ae.TRANSACTION_OPTIONS_TX_GUARDED=2;Ae.TRANSACTION_VERSION_DEFAULT=2;Ae.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS=2;Ae.ESDT_TRANSFER_GAS_LIMIT=5e5;Ae.ESDT_TRANSFER_FUNCTION_NAME="ESDTTransfer";Ae.ESDTNFT_TRANSFER_FUNCTION_NAME="ESDTNFTTransfer";Ae.MULTI_ESDTNFT_TRANSFER_FUNCTION_NAME="MultiESDTNFTTransfer";Ae.ESDT_TRANSFER_VALUE="0";Ae.ARGUMENTS_SEPARATOR="@";Ae.VM_TYPE_WASM_VM=new Uint8Array([5,0]);Ae.CONTRACT_DEPLOY_ADDRESS="erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu";Ae.DELEGATION_MANAGER_SC_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6";Ae.DEFAULT_HRP="erd";Ae.ESDT_CONTRACT_ADDRESS="erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u";Ae.DEFAULT_MESSAGE_VERSION=1;Ae.MESSAGE_PREFIX=`Elrond Signed Message: +`;Ae.HEX_TRANSACTION_HASH_LENGTH=64;Ae.BECH32_ADDRESS_LENGTH=62;Ae.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META=3;Ae.WasmVirtualMachine="0500";Ae.METACHAIN_ID=4294967295;Ae.SDK_JS_SIGNER="sdk-js";Ae.UNKNOWN_SIGNER="unknown"});var oo=D(Na=>{"use strict";h();Object.defineProperty(Na,"__esModule",{value:!0});Na.Logger=Na.LogLevel=void 0;var Ca;(function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.None=5]="None"})(Ca=Na.LogLevel||(Na.LogLevel={}));var Hd=class t{static setLevel(e){t.logLevel=e}static trace(e,...r){t.logLevel>=Ca.Debug||console.debug(e,r)}static debug(e,...r){t.logLevel>=Ca.Debug||console.debug(e,r)}static info(e,...r){t.logLevel>=Ca.Info||console.log(e,r)}static warn(e,...r){t.logLevel>=Ca.Warn||console.warn(e,r)}static error(e,...r){t.logLevel>=Ca.Error||console.error(e,r)}};Na.Logger=Hd;Hd.logLevel=Ca.Debug});var $l=D(On=>{"use strict";h();var fH=On&&On.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),hH=On&&On.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dH=On&&On.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fH(e,t,r);return hH(e,t),e};Object.defineProperty(On,"__esModule",{value:!0});On.TransactionOptions=On.TransactionVersion=void 0;var gi=hr(),k3=dH(Ie()),mv=class t{constructor(e){if(e=Number(e),e<1)throw new k3.ErrTransactionVersionInvalid(e);this.value=e}static withDefaultVersion(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}static withTxOptions(){return new t(gi.TRANSACTION_VERSION_DEFAULT)}valueOf(){return this.value}};On.TransactionVersion=mv;var yv=class t{constructor(e){if(e=Number(e),e<0)throw new k3.ErrTransactionOptionsInvalid(e);this.value=e}static withDefaultOptions(){return new t(gi.TRANSACTION_OPTIONS_DEFAULT)}static withOptions(e){let r=0;return e.hashSign&&(r|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN),e.guarded&&(r|=gi.TRANSACTION_OPTIONS_TX_GUARDED),new t(r)}isWithHashSign(){return(this.value&gi.TRANSACTION_OPTIONS_TX_HASH_SIGN)==gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}isWithGuardian(){return(this.value&gi.TRANSACTION_OPTIONS_TX_GUARDED)==gi.TRANSACTION_OPTIONS_TX_GUARDED}setWithHashSign(){this.value|=gi.TRANSACTION_OPTIONS_TX_HASH_SIGN}setWithGuardian(){this.value|=gi.TRANSACTION_OPTIONS_TX_GUARDED}valueOf(){return this.value}};On.TransactionOptions=yv});var vv=D((Epe,j3)=>{"use strict";h();var jd="qpzry9x8gf2tvdw0s3jn54khce6mua7l",wv={};for(Yl=0;Yl>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function H3(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;rr)throw new TypeError("Exceeds length limit");t=t.toLowerCase();var n=H3(t);if(typeof n=="string")throw new Error(n);for(var i=t+"1",s=0;s>5)throw new Error("Non 5-bit word");n=Pu(n)^o,i+=jd.charAt(o)}for(s=0;s<6;++s)n=Pu(n);for(n^=1,s=0;s<6;++s){var u=n>>(5-s)*5&31;i+=jd.charAt(u)}return i}function G3(t,e){if(e=e||90,t.length<8)return t+" too short";if(t.length>e)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;t=r;var i=t.lastIndexOf("1");if(i===-1)return"No separator character for "+t;if(i===0)return"Missing prefix for "+t;var s=t.slice(0,i),o=t.slice(i+1);if(o.length<6)return"Data too short";var u=H3(s);if(typeof u=="string")return u;for(var a=[],c=0;c=o.length)&&a.push(d)}return u!==1?"Invalid checksum for "+t:{prefix:s,words:a}}function pH(){var t=G3.apply(null,arguments);if(typeof t=="object")return t}function mH(t){var e=G3.apply(null,arguments);if(typeof e=="object")return e;throw new Error(e)}function zd(t,e,r,n){for(var i=0,s=0,o=(1<=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<{"use strict";h();var EH=Nt&&Nt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bH=Nt&&Nt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SH=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&EH(e,t,r);return bH(e,t),e},IH=Nt&&Nt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.addressToHex=Nt.bigIntToHex=Nt.byteArrayToHex=Nt.boolToHex=Nt.utf8ToHex=Nt.zeroPadStringIfOddLength=Nt.isPaddedHex=Nt.numberToPaddedHex=void 0;var TH=IH((rr(),_e(fr))),_H=Ve(),CH=SH(Bu());function NH(t){let e;typeof t=="bigint"||typeof t=="number"?e=t:e=new TH.default(t);let r=e.toString(16);return Qd(r)}Nt.numberToPaddedHex=NH;function xH(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}Nt.isPaddedHex=xH;function Qd(t){return t=t||"",t.length%2==1?"0"+t:t}Nt.zeroPadStringIfOddLength=Qd;function z3(t){let e=p.Buffer.from(t).toString("hex");return Qd(e)}Nt.utf8ToHex=z3;function OH(t){return z3(t.toString())}Nt.boolToHex=OH;function DH(t){let e=p.Buffer.from(t).toString("hex");return Qd(e)}Nt.byteArrayToHex=DH;function PH(t){return t==0?"":CH.getHexMagnitudeOfBigInt(t)}Nt.bigIntToHex=PH;function RH(t){return _H.Address.fromBech32(t.toString()).pubkey().toString("hex")}Nt.addressToHex=RH});var Bu=D(nr=>{"use strict";h();var BH=nr&&nr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nr,"__esModule",{value:!0});nr.prependByteToBuffer=nr.flipBufferBitsInPlace=nr.getHexMagnitudeOfBigInt=nr.bigIntToBuffer=nr.bufferToBigInt=nr.cloneBuffer=nr.isMsbZero=nr.isMsbOne=void 0;var Av=BH((rr(),_e(fr))),MH=Ru();function Q3(t,e=0){return t[e]>>7==1}nr.isMsbOne=Q3;function LH(t,e=0){return!Q3(t,e)}nr.isMsbZero=LH;function FH(t){let e=p.Buffer.alloc(t.length);return t.copy(e),e}nr.cloneBuffer=FH;function UH(t){let e=t.toString("hex");return new Av.default(`0x${e}`,16)}nr.bufferToBigInt=UH;function qH(t){let e=K3(t);return p.Buffer.from(e,"hex")}nr.bigIntToBuffer=qH;function K3(t){return t=new Av.default(t),t?(t.isNegative()&&(t=t.multipliedBy(new Av.default(-1))),MH.numberToPaddedHex(t)):""}nr.getHexMagnitudeOfBigInt=K3;function VH(t){for(let e=0;e{"use strict";h();var HH=Lt&&Lt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),GH=Lt&&Lt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),W3=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&HH(e,t,r);return GH(e,t),e},jH=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.bufferToHex=Lt.addressToHex=Lt.bigIntToHex=Lt.utf8ToHex=Lt.bigIntToBuffer=Lt.bufferToBigInt=Lt.stringToBuffer=void 0;var zH=jH((rr(),_e(fr))),$3=W3(Bu()),QH=W3(Ru());function KH(t){return p.Buffer.from(t)}Lt.stringToBuffer=KH;function WH(t){return t.length==0?new zH.default(0):$3.bufferToBigInt(t)}Lt.bufferToBigInt=WH;function $H(t){return t==0?p.Buffer.from([]):$3.bigIntToBuffer(t)}Lt.bigIntToBuffer=$H;var Ev=Ru();Object.defineProperty(Lt,"utf8ToHex",{enumerable:!0,get:function(){return Ev.utf8ToHex}});Object.defineProperty(Lt,"bigIntToHex",{enumerable:!0,get:function(){return Ev.bigIntToHex}});Object.defineProperty(Lt,"addressToHex",{enumerable:!0,get:function(){return Ev.addressToHex}});function YH(t){let e=t.toString("hex");return QH.zeroPadStringIfOddLength(e)}Lt.bufferToHex=YH});var Ds=D((xpe,bv)=>{"use strict";h();var Mu=typeof Reflect=="object"?Reflect:null,Y3=Mu&&typeof Mu.apply=="function"?Mu.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Wd;Mu&&typeof Mu.ownKeys=="function"?Wd=Mu.ownKeys:Object.getOwnPropertySymbols?Wd=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Wd=function(e){return Object.getOwnPropertyNames(e)};function JH(t){console&&console.warn&&console.warn(t)}var X3=Number.isNaN||function(e){return e!==e};function _t(){_t.init.call(this)}bv.exports=_t;bv.exports.once=tG;_t.EventEmitter=_t;_t.prototype._events=void 0;_t.prototype._eventsCount=0;_t.prototype._maxListeners=void 0;var J3=10;function $d(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_t,"defaultMaxListeners",{enumerable:!0,get:function(){return J3},set:function(t){if(typeof t!="number"||t<0||X3(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");J3=t}});_t.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_t.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||X3(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Z3(t){return t._maxListeners===void 0?_t.defaultMaxListeners:t._maxListeners}_t.prototype.getMaxListeners=function(){return Z3(this)};_t.prototype.emit=function(e){for(var r=[],n=1;n0&&(o=r[0]),o instanceof Error)throw o;var u=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw u.context=o,u}var a=s[e];if(a===void 0)return!1;if(typeof a=="function")Y3(a,this,r);else for(var c=a.length,f=iN(a,c),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=o.length,JH(u)}return t}_t.prototype.addListener=function(e,r){return eN(this,e,r,!1)};_t.prototype.on=_t.prototype.addListener;_t.prototype.prependListener=function(e,r){return eN(this,e,r,!0)};function XH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function tN(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=XH.bind(n);return i.listener=r,n.wrapFn=i,i}_t.prototype.once=function(e,r){return $d(r),this.on(e,tN(this,e,r)),this};_t.prototype.prependOnceListener=function(e,r){return $d(r),this.prependListener(e,tN(this,e,r)),this};_t.prototype.removeListener=function(e,r){var n,i,s,o,u;if($d(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){u=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():ZH(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||r)}return this};_t.prototype.off=_t.prototype.removeListener;_t.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,r[i]);return this};function rN(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?eG(i):iN(i,i.length)}_t.prototype.listeners=function(e){return rN(this,e,!0)};_t.prototype.rawListeners=function(e){return rN(this,e,!1)};_t.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):nN.call(t,e)};_t.prototype.listenerCount=nN;function nN(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_t.prototype.eventNames=function(){return this._eventsCount>0?Wd(this._events):[]};function iN(t,e){for(var r=new Array(e),n=0;n{h();oN.exports=Ds().EventEmitter});var Iv=D(()=>{h()});var hN=D((Lpe,fN)=>{"use strict";h();function aN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function uN(t){for(var e=1;e0?this.tail.next=n:this.head=n,this.tail=n,++this.length}},{key:"unshift",value:function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var n=this.head,i=""+n.data;n=n.next;)i+=r+n.data;return i}},{key:"concat",value:function(r){if(this.length===0)return Yd.alloc(0);for(var n=Yd.allocUnsafe(r>>>0),i=this.head,s=0;i;)lG(i.data,n,s),s+=i.data.length,i=i.next;return n}},{key:"consume",value:function(r,n){var i;return ro.length?o.length:r;if(u===o.length?s+=o:s+=o.slice(0,r),r-=u,r===0){u===o.length?(++i,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(u));break}++i}return this.length-=i,s}},{key:"_getBuffer",value:function(r){var n=Yd.allocUnsafe(r),i=this.head,s=1;for(i.data.copy(n),r-=i.data.length;i=i.next;){var o=i.data,u=r>o.length?o.length:r;if(o.copy(n,n.length-r,0,u),r-=u,r===0){u===o.length?(++s,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=o.slice(u));break}++s}return this.length-=s,n}},{key:cG,value:function(r,n){return Tv(this,uN(uN({},n),{},{depth:0,customInspect:!1}))}}]),t}()});var Cv=D((Upe,gN)=>{"use strict";h();function fG(t,e){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,S.default.nextTick(_v,this,t)):S.default.nextTick(_v,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(s){!e&&s?r._writableState?r._writableState.errorEmitted?S.default.nextTick(Jd,r):(r._writableState.errorEmitted=!0,S.default.nextTick(dN,r,s)):S.default.nextTick(dN,r,s):e?(S.default.nextTick(Jd,r),e(s)):S.default.nextTick(Jd,r)}),this)}function dN(t,e){_v(t,e),Jd(t)}function Jd(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function hG(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function _v(t,e){t.emit("error",e)}function dG(t,e){var r=t._readableState,n=t._writableState;r&&r.autoDestroy||n&&n.autoDestroy?t.destroy(e):t.emit("error",e)}gN.exports={destroy:fG,undestroy:hG,errorOrDestroy:dG}});var xa=D((Vpe,yN)=>{"use strict";h();function gG(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}var mN={};function Dn(t,e,r){r||(r=Error);function n(s,o,u){return typeof e=="string"?e:e(s,o,u)}var i=function(s){gG(o,s);function o(u,a,c){return s.call(this,n(u,a,c))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=t,mN[t]=i}function pN(t,e){if(Array.isArray(t)){var r=t.length;return t=t.map(function(n){return String(n)}),r>2?"one of ".concat(e," ").concat(t.slice(0,r-1).join(", "),", or ")+t[r-1]:r===2?"one of ".concat(e," ").concat(t[0]," or ").concat(t[1]):"of ".concat(e," ").concat(t[0])}else return"of ".concat(e," ").concat(String(t))}function pG(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function mG(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function yG(t,e,r){return typeof r!="number"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}Dn("ERR_INVALID_OPT_VALUE",function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'},TypeError);Dn("ERR_INVALID_ARG_TYPE",function(t,e,r){var n;typeof e=="string"&&pG(e,"not ")?(n="must not be",e=e.replace(/^not /,"")):n="must be";var i;if(mG(t," argument"))i="The ".concat(t," ").concat(n," ").concat(pN(e,"type"));else{var s=yG(t,".")?"property":"argument";i='The "'.concat(t,'" ').concat(s," ").concat(n," ").concat(pN(e,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);Dn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");Dn("ERR_METHOD_NOT_IMPLEMENTED",function(t){return"The "+t+" method is not implemented"});Dn("ERR_STREAM_PREMATURE_CLOSE","Premature close");Dn("ERR_STREAM_DESTROYED",function(t){return"Cannot call "+t+" after a stream was destroyed"});Dn("ERR_MULTIPLE_CALLBACK","Callback called multiple times");Dn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");Dn("ERR_STREAM_WRITE_AFTER_END","write after end");Dn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Dn("ERR_UNKNOWN_ENCODING",function(t){return"Unknown encoding: "+t},TypeError);Dn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");yN.exports.codes=mN});var Nv=D((Hpe,wN)=>{"use strict";h();var wG=xa().codes.ERR_INVALID_OPT_VALUE;function vG(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function AG(t,e,r,n){var i=vG(e,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new wG(s,i)}return Math.floor(i)}return t.objectMode?16:16*1024}wN.exports={getHighWaterMark:AG}});var Lu=D((jpe,xv)=>{h();typeof Object.create=="function"?xv.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:xv.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var AN=D((Qpe,vN)=>{h();vN.exports=EG;function EG(t,e){if(Ov("noDeprecation"))return t;var r=!1;function n(){if(!r){if(Ov("throwDeprecation"))throw new Error(e);Ov("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}return n}function Ov(t){try{if(!global.localStorage)return!1}catch{return!1}var e=global.localStorage[t];return e==null?!1:String(e).toLowerCase()==="true"}});var Rv=D((Wpe,_N)=>{"use strict";h();_N.exports=Gt;function bN(t){var e=this;this.next=null,this.entry=null,this.finish=function(){WG(e,t)}}var Fu;Gt.WritableState=Xl;var bG={deprecate:AN()},SN=Sv(),Zd=io().Buffer,SG=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function IG(t){return Zd.from(t)}function TG(t){return Zd.isBuffer(t)||t instanceof SG}var Pv=Cv(),_G=Nv(),CG=_G.getHighWaterMark,ao=xa().codes,NG=ao.ERR_INVALID_ARG_TYPE,xG=ao.ERR_METHOD_NOT_IMPLEMENTED,OG=ao.ERR_MULTIPLE_CALLBACK,DG=ao.ERR_STREAM_CANNOT_PIPE,PG=ao.ERR_STREAM_DESTROYED,RG=ao.ERR_STREAM_NULL_VALUES,BG=ao.ERR_STREAM_WRITE_AFTER_END,MG=ao.ERR_UNKNOWN_ENCODING,Uu=Pv.errorOrDestroy;Lu()(Gt,SN);function LG(){}function Xl(t,e,r){Fu=Fu||Oa(),t=t||{},typeof r!="boolean"&&(r=e instanceof Fu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=CG(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=t.decodeStrings===!1;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(i){GG(e,i)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new bN(this)}Xl.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty(Xl.prototype,"buffer",{get:bG.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var Xd;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Xd=Function.prototype[Symbol.hasInstance],Object.defineProperty(Gt,Symbol.hasInstance,{value:function(e){return Xd.call(this,e)?!0:this!==Gt?!1:e&&e._writableState instanceof Xl}})):Xd=function(e){return e instanceof this};function Gt(t){Fu=Fu||Oa();var e=this instanceof Fu;if(!e&&!Xd.call(Gt,this))return new Gt(t);this._writableState=new Xl(t,this,e),this.writable=!0,t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final)),SN.call(this)}Gt.prototype.pipe=function(){Uu(this,new DG)};function FG(t,e){var r=new BG;Uu(t,r),S.default.nextTick(e,r)}function UG(t,e,r,n){var i;return r===null?i=new RG:typeof r!="string"&&!e.objectMode&&(i=new NG("chunk",["string","Buffer"],r)),i?(Uu(t,i),S.default.nextTick(n,i),!1):!0}Gt.prototype.write=function(t,e,r){var n=this._writableState,i=!1,s=!n.objectMode&&TG(t);return s&&!Zd.isBuffer(t)&&(t=IG(t)),typeof e=="function"&&(r=e,e=null),s?e="buffer":e||(e=n.defaultEncoding),typeof r!="function"&&(r=LG),n.ending?FG(this,r):(s||UG(this,n,t,r))&&(n.pendingcb++,i=VG(this,n,s,t,e,r)),i};Gt.prototype.cork=function(){this._writableState.corked++};Gt.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&IN(this,t))};Gt.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new MG(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Gt.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function qG(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e=="string"&&(e=Zd.from(e,r)),e}Object.defineProperty(Gt.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function VG(t,e,r,n,i,s){if(!r){var o=qG(e,n,i);n!==o&&(r=!0,i="buffer",n=o)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length{"use strict";h();var $G=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};NN.exports=Li;var CN=Lv(),Mv=Rv();Lu()(Li,CN);for(Bv=$G(Mv.prototype),eg=0;eg{h();var rg=io(),Fi=rg.Buffer;function xN(t,e){for(var r in t)e[r]=t[r]}Fi.from&&Fi.alloc&&Fi.allocUnsafe&&Fi.allocUnsafeSlow?ON.exports=rg:(xN(rg,Fv),Fv.Buffer=Da);function Da(t,e,r){return Fi(t,e,r)}Da.prototype=Object.create(Fi.prototype);xN(Fi,Da);Da.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Fi(t,e,r)};Da.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=Fi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Da.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Fi(t)};Da.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return rg.SlowBuffer(t)}});var Vv=D(RN=>{"use strict";h();var qv=DN().Buffer,PN=qv.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function XG(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function ZG(t){var e=XG(t);if(typeof e!="string"&&(qv.isEncoding===PN||!PN(t)))throw new Error("Unknown encoding: "+t);return e||t}RN.StringDecoder=Zl;function Zl(t){this.encoding=ZG(t);var e;switch(this.encoding){case"utf16le":this.text=sj,this.end=oj,e=4;break;case"utf8":this.fillLast=rj,e=4;break;case"base64":this.text=aj,this.end=uj,e=3;break;default:this.write=cj,this.end=lj;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=qv.allocUnsafe(e)}Zl.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function ej(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function tj(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function rj(t){var e=this.lastTotal-this.lastNeed,r=tj(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function nj(t,e){var r=ej(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function ij(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function sj(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function oj(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function aj(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function uj(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function cj(t){return t.toString(this.encoding)}function lj(t){return t&&t.length?this.write(t):""}});var ng=D((t0e,LN)=>{"use strict";h();var BN=xa().codes.ERR_STREAM_PREMATURE_CLOSE;function fj(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i{"use strict";h();var ig;function uo(t,e,r){return e=gj(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gj(t){var e=pj(t,"string");return typeof e=="symbol"?e:String(e)}function pj(t,e){if(typeof t!="object"||t===null)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var mj=ng(),co=Symbol("lastResolve"),Pa=Symbol("lastReject"),ef=Symbol("error"),sg=Symbol("ended"),Ra=Symbol("lastPromise"),kv=Symbol("handlePromise"),Ba=Symbol("stream");function lo(t,e){return{value:t,done:e}}function yj(t){var e=t[co];if(e!==null){var r=t[Ba].read();r!==null&&(t[Ra]=null,t[co]=null,t[Pa]=null,e(lo(r,!1)))}}function wj(t){S.default.nextTick(yj,t)}function vj(t,e){return function(r,n){t.then(function(){if(e[sg]){r(lo(void 0,!0));return}e[kv](r,n)},n)}}var Aj=Object.getPrototypeOf(function(){}),Ej=Object.setPrototypeOf((ig={get stream(){return this[Ba]},next:function(){var e=this,r=this[ef];if(r!==null)return Promise.reject(r);if(this[sg])return Promise.resolve(lo(void 0,!0));if(this[Ba].destroyed)return new Promise(function(o,u){S.default.nextTick(function(){e[ef]?u(e[ef]):o(lo(void 0,!0))})});var n=this[Ra],i;if(n)i=new Promise(vj(n,this));else{var s=this[Ba].read();if(s!==null)return Promise.resolve(lo(s,!1));i=new Promise(this[kv])}return this[Ra]=i,i}},uo(ig,Symbol.asyncIterator,function(){return this}),uo(ig,"return",function(){var e=this;return new Promise(function(r,n){e[Ba].destroy(null,function(i){if(i){n(i);return}r(lo(void 0,!0))})})}),ig),Aj),bj=function(e){var r,n=Object.create(Ej,(r={},uo(r,Ba,{value:e,writable:!0}),uo(r,co,{value:null,writable:!0}),uo(r,Pa,{value:null,writable:!0}),uo(r,ef,{value:null,writable:!0}),uo(r,sg,{value:e._readableState.endEmitted,writable:!0}),uo(r,kv,{value:function(s,o){var u=n[Ba].read();u?(n[Ra]=null,n[co]=null,n[Pa]=null,s(lo(u,!1))):(n[co]=s,n[Pa]=o)},writable:!0}),r));return n[Ra]=null,mj(e,function(i){if(i&&i.code!=="ERR_STREAM_PREMATURE_CLOSE"){var s=n[Pa];s!==null&&(n[Ra]=null,n[co]=null,n[Pa]=null,s(i)),n[ef]=i;return}var o=n[co];o!==null&&(n[Ra]=null,n[co]=null,n[Pa]=null,o(lo(void 0,!0))),n[sg]=!0}),e.on("readable",wj.bind(null,n)),n};FN.exports=bj});var VN=D((s0e,qN)=>{h();qN.exports=function(){throw new Error("Readable.from is not available in the browser")}});var Lv=D((u0e,YN)=>{"use strict";h();YN.exports=Fe;var qu;Fe.ReadableState=jN;var a0e=Ds().EventEmitter,GN=function(e,r){return e.listeners(r).length},rf=Sv(),og=io().Buffer,Sj=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function Ij(t){return og.from(t)}function Tj(t){return og.isBuffer(t)||t instanceof Sj}var Hv=Iv(),Ne;Hv&&Hv.debuglog?Ne=Hv.debuglog("stream"):Ne=function(){};var _j=hN(),$v=Cv(),Cj=Nv(),Nj=Cj.getHighWaterMark,ag=xa().codes,xj=ag.ERR_INVALID_ARG_TYPE,Oj=ag.ERR_STREAM_PUSH_AFTER_EOF,Dj=ag.ERR_METHOD_NOT_IMPLEMENTED,Pj=ag.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,Vu,Gv,jv;Lu()(Fe,rf);var tf=$v.errorOrDestroy,zv=["error","close","destroy","pause","resume"];function Rj(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function jN(t,e,r){qu=qu||Oa(),t=t||{},typeof r!="boolean"&&(r=e instanceof qu),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=Nj(this,t,"readableHighWaterMark",r),this.buffer=new _j,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(Vu||(Vu=Vv().StringDecoder),this.decoder=new Vu(t.encoding),this.encoding=t.encoding)}function Fe(t){if(qu=qu||Oa(),!(this instanceof Fe))return new Fe(t);var e=this instanceof qu;this._readableState=new jN(t,this,e),this.readable=!0,t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy)),rf.call(this)}Object.defineProperty(Fe.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});Fe.prototype.destroy=$v.destroy;Fe.prototype._undestroy=$v.undestroy;Fe.prototype._destroy=function(t,e){e(t)};Fe.prototype.push=function(t,e){var r=this._readableState,n;return r.objectMode?n=!0:typeof t=="string"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=og.from(t,e),e=""),n=!0),zN(this,t,e,!1,n)};Fe.prototype.unshift=function(t){return zN(this,t,null,!0,!1)};function zN(t,e,r,n,i){Ne("readableAddChunk",e);var s=t._readableState;if(e===null)s.reading=!1,Lj(t,s);else{var o;if(i||(o=Bj(s,e)),o)tf(t,o);else if(s.objectMode||e&&e.length>0)if(typeof e!="string"&&!s.objectMode&&Object.getPrototypeOf(e)!==og.prototype&&(e=Ij(e)),n)s.endEmitted?tf(t,new Pj):Qv(t,s,e,!0);else if(s.ended)tf(t,new Oj);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||e.length!==0?Qv(t,s,e,!1):Wv(t,s)):Qv(t,s,e,!1)}else n||(s.reading=!1,Wv(t,s))}return!s.ended&&(s.length=kN?t=kN:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function HN(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=Mj(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}Fe.prototype.read=function(t){Ne("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ne("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Kv(this):ug(this),null;if(t=HN(t,e),t===0&&e.ended)return e.length===0&&Kv(this),null;var n=e.needReadable;Ne("need readable",n),(e.length===0||e.length-t0?i=WN(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Kv(this)),i!==null&&this.emit("data",i),i};function Lj(t,e){if(Ne("onEofChunk"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?ug(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,QN(t)))}}function ug(t){var e=t._readableState;Ne("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ne("emitReadable",e.flowing),e.emittedReadable=!0,S.default.nextTick(QN,t))}function QN(t){var e=t._readableState;Ne("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,Yv(t)}function Wv(t,e){e.readingMore||(e.readingMore=!0,S.default.nextTick(Fj,t,e))}function Fj(t,e){for(;!e.reading&&!e.ended&&(e.length1&&$N(n.pipes,t)!==-1)&&!c&&(Ne("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function w(B){Ne("onerror",B),x(),t.removeListener("error",w),GN(t,"error")===0&&tf(t,B)}Rj(t,"error",w);function A(){t.removeListener("finish",T),x()}t.once("close",A);function T(){Ne("onfinish"),t.removeListener("close",A),x()}t.once("finish",T);function x(){Ne("unpipe"),r.unpipe(t)}return t.emit("pipe",r),n.flowing||(Ne("pipe resume"),r.resume()),t};function Uj(t){return function(){var r=t._readableState;Ne("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&GN(t,"data")&&(r.flowing=!0,Yv(t))}}Fe.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ne("on readable",n.length,n.reading),n.length?ug(this):n.reading||S.default.nextTick(qj,this)),r};Fe.prototype.addListener=Fe.prototype.on;Fe.prototype.removeListener=function(t,e){var r=rf.prototype.removeListener.call(this,t,e);return t==="readable"&&S.default.nextTick(KN,this),r};Fe.prototype.removeAllListeners=function(t){var e=rf.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&S.default.nextTick(KN,this),e};function KN(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function qj(t){Ne("readable nexttick read 0"),t.read(0)}Fe.prototype.resume=function(){var t=this._readableState;return t.flowing||(Ne("resume"),t.flowing=!t.readableListening,Vj(this,t)),t.paused=!1,this};function Vj(t,e){e.resumeScheduled||(e.resumeScheduled=!0,S.default.nextTick(kj,t,e))}function kj(t,e){Ne("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),Yv(t),e.flowing&&!e.reading&&t.read(0)}Fe.prototype.pause=function(){return Ne("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ne("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function Yv(t){var e=t._readableState;for(Ne("flow",e.flowing);e.flowing&&t.read()!==null;);}Fe.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;t.on("end",function(){if(Ne("wrapped end"),r.decoder&&!r.ended){var o=r.decoder.end();o&&o.length&&e.push(o)}e.push(null)}),t.on("data",function(o){if(Ne("wrapped data"),r.decoder&&(o=r.decoder.write(o)),!(r.objectMode&&o==null)&&!(!r.objectMode&&(!o||!o.length))){var u=e.push(o);u||(n=!0,t.pause())}});for(var i in t)this[i]===void 0&&typeof t[i]=="function"&&(this[i]=function(u){return function(){return t[u].apply(t,arguments)}}(i));for(var s=0;s=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Kv(t){var e=t._readableState;Ne("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,S.default.nextTick(Hj,e,t))}function Hj(t,e){if(Ne("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol=="function"&&(Fe.from=function(t,e){return jv===void 0&&(jv=VN()),jv(Fe,t,e)});function $N(t,e){for(var r=0,n=t.length;r{"use strict";h();XN.exports=Ps;var cg=xa().codes,Gj=cg.ERR_METHOD_NOT_IMPLEMENTED,jj=cg.ERR_MULTIPLE_CALLBACK,zj=cg.ERR_TRANSFORM_ALREADY_TRANSFORMING,Qj=cg.ERR_TRANSFORM_WITH_LENGTH_0,lg=Oa();Lu()(Ps,lg);function Kj(t,e){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new jj);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length{"use strict";h();ex.exports=nf;var ZN=Jv();Lu()(nf,ZN);function nf(t){if(!(this instanceof nf))return new nf(t);ZN.call(this,t)}nf.prototype._transform=function(t,e,r){r(null,t)}});var ox=D((g0e,sx)=>{"use strict";h();var Xv;function $j(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var ix=xa().codes,Yj=ix.ERR_MISSING_ARGS,Jj=ix.ERR_STREAM_DESTROYED;function rx(t){if(t)throw t}function Xj(t){return t.setHeader&&typeof t.abort=="function"}function Zj(t,e,r,n){n=$j(n);var i=!1;t.on("close",function(){i=!0}),Xv===void 0&&(Xv=ng()),Xv(t,{readable:e,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Xj(t))return t.abort();if(typeof t.destroy=="function")return t.destroy();n(o||new Jj("pipe"))}}}function nx(t){t()}function ez(t,e){return t.pipe(e)}function tz(t){return!t.length||typeof t[t.length-1]!="function"?rx:t.pop()}function rz(){for(var t=arguments.length,e=new Array(t),r=0;r0;return Zj(o,a,c,function(f){i||(i=f),f&&s.forEach(nx),!a&&(s.forEach(nx),n(i))})});return e.reduce(ez)}sx.exports=rz});var Zv=D((Pn,ax)=>{h();Pn=ax.exports=Lv();Pn.Stream=Pn;Pn.Readable=Pn;Pn.Writable=Rv();Pn.Duplex=Oa();Pn.Transform=Jv();Pn.PassThrough=tx();Pn.finished=ng();Pn.pipeline=ox()});var lx=D((y0e,cx)=>{h();var{Transform:nz}=Zv();cx.exports=t=>class ux extends nz{constructor(r,n,i,s,o){super(o),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._hashBitLength=s,this._options=o,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(r){let n=null;try{this.push(this.digest())}catch(i){n=i}r(n)}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Digest already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}digest(r){if(this._finalized)throw new Error("Digest already called");this._finalized=!0,this._delimitedSuffix&&this._state.absorbLastFewBits(this._delimitedSuffix);let n=this._state.squeeze(this._hashBitLength/8);return r!==void 0&&(n=n.toString(r)),this._resetState(),n}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new ux(this._rate,this._capacity,this._delimitedSuffix,this._hashBitLength,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var dx=D((v0e,hx)=>{h();var{Transform:iz}=Zv();hx.exports=t=>class fx extends iz{constructor(r,n,i,s){super(s),this._rate=r,this._capacity=n,this._delimitedSuffix=i,this._options=s,this._state=new t,this._state.initialize(r,n),this._finalized=!1}_transform(r,n,i){let s=null;try{this.update(r,n)}catch(o){s=o}i(s)}_flush(){}_read(r){this.push(this.squeeze(r))}update(r,n){if(!p.Buffer.isBuffer(r)&&typeof r!="string")throw new TypeError("Data must be a string or a buffer");if(this._finalized)throw new Error("Squeeze already called");return p.Buffer.isBuffer(r)||(r=p.Buffer.from(r,n)),this._state.absorb(r),this}squeeze(r,n){this._finalized||(this._finalized=!0,this._state.absorbLastFewBits(this._delimitedSuffix));let i=this._state.squeeze(r);return n!==void 0&&(i=i.toString(n)),i}_resetState(){return this._state.initialize(this._rate,this._capacity),this}_clone(){let r=new fx(this._rate,this._capacity,this._delimitedSuffix,this._options);return this._state.copy(r._state),r._finalized=this._finalized,r}}});var px=D((E0e,gx)=>{h();var sz=lx(),oz=dx();gx.exports=function(t){let e=sz(t),r=oz(t);return function(n,i){switch(typeof n=="string"?n.toLowerCase():n){case"keccak224":return new e(1152,448,null,224,i);case"keccak256":return new e(1088,512,null,256,i);case"keccak384":return new e(832,768,null,384,i);case"keccak512":return new e(576,1024,null,512,i);case"sha3-224":return new e(1152,448,6,224,i);case"sha3-256":return new e(1088,512,6,256,i);case"sha3-384":return new e(832,768,6,384,i);case"sha3-512":return new e(576,1024,6,512,i);case"shake128":return new r(1344,256,31,i);case"shake256":return new r(1088,512,31,i);default:throw new Error("Invald algorithm: "+n)}}}});var wx=D(yx=>{h();var mx=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648];yx.p1600=function(t){for(let e=0;e<24;++e){let r=t[0]^t[10]^t[20]^t[30]^t[40],n=t[1]^t[11]^t[21]^t[31]^t[41],i=t[2]^t[12]^t[22]^t[32]^t[42],s=t[3]^t[13]^t[23]^t[33]^t[43],o=t[4]^t[14]^t[24]^t[34]^t[44],u=t[5]^t[15]^t[25]^t[35]^t[45],a=t[6]^t[16]^t[26]^t[36]^t[46],c=t[7]^t[17]^t[27]^t[37]^t[47],f=t[8]^t[18]^t[28]^t[38]^t[48],d=t[9]^t[19]^t[29]^t[39]^t[49],w=f^(i<<1|s>>>31),A=d^(s<<1|i>>>31),T=t[0]^w,x=t[1]^A,B=t[10]^w,V=t[11]^A,U=t[20]^w,Q=t[21]^A,L=t[30]^w,k=t[31]^A,H=t[40]^w,q=t[41]^A;w=r^(o<<1|u>>>31),A=n^(u<<1|o>>>31);let v=t[2]^w,C=t[3]^A,P=t[12]^w,F=t[13]^A,R=t[22]^w,l=t[23]^A,g=t[32]^w,y=t[33]^A,E=t[42]^w,I=t[43]^A;w=i^(a<<1|c>>>31),A=s^(c<<1|a>>>31);let _=t[4]^w,M=t[5]^A,N=t[14]^w,m=t[15]^A,O=t[24]^w,Y=t[25]^A,$=t[34]^w,b=t[35]^A,j=t[44]^w,z=t[45]^A;w=o^(f<<1|d>>>31),A=u^(d<<1|f>>>31);let W=t[6]^w,ie=t[7]^A,te=t[16]^w,ee=t[17]^A,se=t[26]^w,oe=t[27]^A,J=t[36]^w,ue=t[37]^A,wt=t[46]^w,vt=t[47]^A;w=a^(r<<1|n>>>31),A=c^(n<<1|r>>>31);let Ni=t[8]^w,At=t[9]^A,Et=t[18]^w,xi=t[19]^A,bt=t[28]^w,St=t[29]^A,Oi=t[38]^w,It=t[39]^A,Tt=t[48]^w,Di=t[49]^A,Qe=T,Ke=x,ri=V<<4|B>>>28,We=B<<4|V>>>28,$e=U<<3|Q>>>29,ni=Q<<3|U>>>29,Ye=k<<9|L>>>23,Je=L<<9|k>>>23,ii=H<<18|q>>>14,Xe=q<<18|H>>>14,Ze=v<<1|C>>>31,si=C<<1|v>>>31,et=F<<12|P>>>20,tt=P<<12|F>>>20,oi=R<<10|l>>>22,rt=l<<10|R>>>22,nt=y<<13|g>>>19,ai=g<<13|y>>>19,it=E<<2|I>>>30,st=I<<2|E>>>30,ui=M<<30|_>>>2,ot=_<<30|M>>>2,at=N<<6|m>>>26,ci=m<<6|N>>>26,ut=Y<<11|O>>>21,ct=O<<11|Y>>>21,li=$<<15|b>>>17,lt=b<<15|$>>>17,ft=z<<29|j>>>3,fi=j<<29|z>>>3,ht=W<<28|ie>>>4,dt=ie<<28|W>>>4,hi=ee<<23|te>>>9,gt=te<<23|ee>>>9,pt=se<<25|oe>>>7,vn=oe<<25|se>>>7,An=J<<21|ue>>>11,En=ue<<21|J>>>11,bn=vt<<24|wt>>>8,Sn=wt<<24|vt>>>8,In=Ni<<27|At>>>5,ha=At<<27|Ni>>>5,da=Et<<20|xi>>>12,ga=xi<<20|Et>>>12,pa=St<<7|bt>>>25,ma=bt<<7|St>>>25,ya=Oi<<8|It>>>24,wa=It<<8|Oi>>>24,va=Tt<<14|Di>>>18,Aa=Di<<14|Tt>>>18;t[0]=Qe^~et&ut,t[1]=Ke^~tt&ct,t[10]=ht^~da&$e,t[11]=dt^~ga&ni,t[20]=Ze^~at&pt,t[21]=si^~ci&vn,t[30]=In^~ri&oi,t[31]=ha^~We&rt,t[40]=ui^~hi&pa,t[41]=ot^~gt&ma,t[2]=et^~ut&An,t[3]=tt^~ct&En,t[12]=da^~$e&nt,t[13]=ga^~ni&ai,t[22]=at^~pt&ya,t[23]=ci^~vn&wa,t[32]=ri^~oi&li,t[33]=We^~rt<,t[42]=hi^~pa&Ye,t[43]=gt^~ma&Je,t[4]=ut^~An&va,t[5]=ct^~En&Aa,t[14]=$e^~nt&ft,t[15]=ni^~ai&fi,t[24]=pt^~ya&ii,t[25]=vn^~wa&Xe,t[34]=oi^~li&bn,t[35]=rt^~lt&Sn,t[44]=pa^~Ye&it,t[45]=ma^~Je&st,t[6]=An^~va&Qe,t[7]=En^~Aa&Ke,t[16]=nt^~ft&ht,t[17]=ai^~fi&dt,t[26]=ya^~ii&Ze,t[27]=wa^~Xe&si,t[36]=li^~bn&In,t[37]=lt^~Sn&ha,t[46]=Ye^~it&ui,t[47]=Je^~st&ot,t[8]=va^~Qe&et,t[9]=Aa^~Ke&tt,t[18]=ft^~ht&da,t[19]=fi^~dt&ga,t[28]=ii^~Ze&at,t[29]=Xe^~si&ci,t[38]=bn^~In&ri,t[39]=Sn^~ha&We,t[48]=it^~ui&hi,t[49]=st^~ot>,t[0]^=mx[e*2],t[1]^=mx[e*2+1]}}});var Ax=D((T0e,vx)=>{h();var fg=wx();function ku(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}ku.prototype.initialize=function(t,e){for(let r=0;r<50;++r)this.state[r]=0;this.blockSize=t/8,this.count=0,this.squeezing=!1};ku.prototype.absorb=function(t){for(let e=0;e>>8*(this.count%4)&255,this.count+=1,this.count===this.blockSize&&(fg.p1600(this.state),this.count=0);return e};ku.prototype.copy=function(t){for(let e=0;e<50;++e)t.state[e]=this.state[e];t.blockSize=this.blockSize,t.count=this.count,t.squeezing=this.squeezing};vx.exports=ku});var sf=D((C0e,Ex)=>{h();Ex.exports=px()(Ax())});var Ve=D(Kr=>{"use strict";h();var az=Kr&&Kr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),uz=Kr&&Kr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bx=Kr&&Kr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&az(e,t,r);return uz(e,t),e},cz=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.AddressComputer=Kr.Address=void 0;var Hu=bx(vv()),lz=cz((rr(),_e(fr))),eA=hr(),Gu=bx(Ie()),fz=Kd(),hz=sf(),of="erd",hg=32,dz="0".repeat(16),dg=class t{constructor(e){if(this.valueHex="",!!e){if(e instanceof t)return t.fromAddress(e);if(ArrayBuffer.isView(e))return t.fromBuffer(p.Buffer.from(e));if(typeof e=="string")return t.fromString(e);throw new Gu.ErrAddressCannotCreate(e)}}static fromAddress(e){return t.fromValidHex(e.valueHex)}static fromValidHex(e){let r=t.empty();return r.valueHex=e,r}static fromBuffer(e){if(e.length!=hg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e.toString("hex"))}static fromString(e){return t.isValidHex(e)?t.fromValidHex(e):t.fromBech32(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==hg}static fromHex(e){if(!t.isValidHex(e))throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(e)}static empty(){return new t("")}static fromBech32(e){let r;try{r=Hu.decode(e)}catch(s){throw new Gu.ErrAddressCannotCreate(e,s)}let n=r.prefix;if(n!=of)throw new Gu.ErrAddressBadHrp(of,n);let i=p.Buffer.from(Hu.fromWords(r.words));if(i.length!=hg)throw new Gu.ErrAddressCannotCreate(e);return t.fromValidHex(i.toString("hex"))}static isValid(e){let r=Hu.decodeUnsafe(e),n=r?.prefix,i=r?p.Buffer.from(Hu.fromWords(r.words)):void 0;return!(n!==of||i?.length!==hg)}hex(){return this.toHex()}toHex(){return this.isEmpty()?"":this.valueHex}bech32(){return this.toBech32()}toBech32(){if(this.isEmpty())return"";let e=Hu.toWords(this.pubkey());return Hu.encode(of,e)}pubkey(){return this.getPublicKey()}getPublicKey(){return this.isEmpty()?p.Buffer.from([]):p.Buffer.from(this.valueHex,"hex")}getHrp(){return of}isEmpty(){return!this.valueHex}equals(e){return e?this.valueHex==e.valueHex:!1}toString(){return this.toBech32()}toJSON(){return{bech32:this.toBech32(),pubkey:this.toHex()}}static Zero(){return new t("0".repeat(64))}isContractAddress(){return this.isSmartContract()}isSmartContract(){return this.toHex().startsWith(dz)}};Kr.Address=dg;var tA=class{constructor(e){this.numberOfShardsWithoutMeta=e||eA.CURRENT_NUMBER_OF_SHARDS_WITHOUT_META}computeContractAddress(e,r){let n=p.Buffer.alloc(8,0),i=e.getPublicKey(),s=i.slice(30),o=p.Buffer.alloc(8),u=new lz.default(r.toString()),a=fz.bigIntToBuffer(u);o.write(a.reverse().toString("hex"),"hex");let c=p.Buffer.concat([i,o]),f=hz("keccak256").update(c).digest(),d=p.Buffer.from(eA.WasmVirtualMachine,"hex"),w=p.Buffer.concat([n,d,f.slice(10,30),s]);return new dg(w)}getShardOfAddress(e){return this.getShardOfPubkey(e.getPublicKey(),this.numberOfShardsWithoutMeta)}getShardOfPubkey(e,r){let n=parseInt("11",2),i=parseInt("01",2),s=e[31];if(this.isPubkeyOfMetachain(e))return eA.METACHAIN_ID;let o=s&n;return o>r-1&&(o=s&i),o}isPubkeyOfMetachain(e){let r=p.Buffer.from([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n=p.Buffer.from(e).slice(0,r.length);return!!(r.equals(n)||p.Buffer.alloc(32).equals(p.Buffer.from(e)))}};Kr.AddressComputer=tA});var Rn=D(Ft=>{"use strict";h();var gz=Ft&&Ft.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),pz=Ft&&Ft.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),mz=Ft&&Ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&gz(e,t,r);return pz(e,t),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.isEmpty=Ft.guardEmpty=Ft.guardNotEmpty=Ft.guardLength=Ft.guardSameLength=Ft.guardValueIsSetWithMessage=Ft.guardValueIsSet=Ft.guardTrue=void 0;var ju=mz(Ie());function yz(t,e){if(!t)throw new ju.ErrInvariantFailed(`[<${e}>] isn't true`)}Ft.guardTrue=yz;function wz(t,e){Sx(`${t} isn't set (null or undefined)`,e)}Ft.guardValueIsSet=wz;function Sx(t,e){if(e==null||e===void 0)throw new ju.ErrInvariantFailed(t)}Ft.guardValueIsSetWithMessage=Sx;function vz(t,e){if(t=t||[],e=e||[],t.length!=e.length)throw new ju.ErrInvariantFailed("arrays do not have the same length")}Ft.guardSameLength=vz;function Az(t,e){let r=t.length||0;if(r!=e)throw new ju.ErrInvariantFailed(`wrong length, expected: ${e}, actual: ${r}`)}Ft.guardLength=Az;function Ez(t,e){if(rA(t))throw new ju.ErrInvariantFailed(`${e} is empty`)}Ft.guardNotEmpty=Ez;function bz(t,e){if(!rA(t))throw new ju.ErrInvariantFailed(`${e} is not empty`)}Ft.guardEmpty=bz;function rA(t){return t.isEmpty?t.isEmpty():t.length===0}Ft.isEmpty=rA});var Ix=D(gg=>{"use strict";h();Object.defineProperty(gg,"__esModule",{value:!0});gg.TypeFormula=void 0;var nA=class{constructor(e,r){this.name=e,this.typeParameters=r}toString(){if(this.typeParameters.length>0){let e=this.typeParameters.map(r=>r.toString()).join(", ");return`${this.name}<${e}>`}else return this.name}};gg.TypeFormula=nA});var Tx=D(pg=>{"use strict";h();Object.defineProperty(pg,"__esModule",{value:!0});pg.TypeFormulaParser=void 0;var af=Ix(),Ui=class t{parseExpression(e){e=e.trim();let r=this.tokenizeExpression(e).filter(s=>s!==t.COMMA),n=[];for(let s of r)if(this.isPunctuation(s))if(this.isEndOfTypeParameters(s)){let o=this.acquireTypeWithParameters(n);n.push(o)}else if(this.isBeginningOfTypeParameters(s))n.push(s);else throw new Error(`Unexpected token (punctuation): ${s}`);else n.push(s);if(n.length!==1)throw new Error(`Unexpected stack length at end of parsing: ${n.length}`);if(t.PUNCTUATION.includes(n[0]))throw new Error("Unexpected root element.");let i=n[0];if(i instanceof af.TypeFormula)return i;if(typeof i=="string")return new af.TypeFormula(i,[]);throw new Error(`Unexpected item on stack: ${i}`)}tokenizeExpression(e){let r=[],n="";for(let i of e)this.isPunctuation(i)?(n&&(r.push(n.trim()),n=""),r.push(i)):n+=i;return n&&r.push(n.trim()),r}acquireTypeWithParameters(e){let r=this.acquireTypeParameters(e),n=e.pop();return new af.TypeFormula(n,r.reverse())}acquireTypeParameters(e){let r=[];for(;;){let n=e.pop();if(n===void 0)throw new Error("Badly specified type parameters");if(this.isBeginningOfTypeParameters(n))break;if(n instanceof af.TypeFormula)r.push(n);else if(typeof n=="string")r.push(new af.TypeFormula(n,[]));else throw new Error(`Unexpected type parameter object in stack: ${n}`)}return r}isPunctuation(e){return t.PUNCTUATION.includes(e)}isEndOfTypeParameters(e){return e===t.END_TYPE_PARAMETERS}isBeginningOfTypeParameters(e){return e===t.BEGIN_TYPE_PARAMETERS}};pg.TypeFormulaParser=Ui;Ui.BEGIN_TYPE_PARAMETERS="<";Ui.END_TYPE_PARAMETERS=">";Ui.COMMA=",";Ui.PUNCTUATION=[Ui.COMMA,Ui.BEGIN_TYPE_PARAMETERS,Ui.END_TYPE_PARAMETERS]});var _x=D(mg=>{"use strict";h();Object.defineProperty(mg,"__esModule",{value:!0});mg.getJavascriptPrototypesInHierarchy=void 0;function Sz(t,e){let r=[],n=Object.getPrototypeOf(t);for(;n&&e(n);)r.push(n),n=Object.getPrototypeOf(n);return r}mg.getJavascriptPrototypesInHierarchy=Sz});var sr=D(ir=>{"use strict";h();Object.defineProperty(ir,"__esModule",{value:!0});ir.NullType=ir.TypePlaceholder=ir.isTyped=ir.PrimitiveValue=ir.TypedValue=ir.CustomType=ir.PrimitiveType=ir.TypeCardinality=ir.Type=void 0;var iA=_x(),Cx=Rn(),fo=class t{constructor(e,r=[],n=uf.fixed(1)){Cx.guardValueIsSet("name",e),this.name=e,this.typeParameters=r,this.cardinality=n}getName(){return this.name}getClassName(){return t.ClassName}getClassHierarchy(){return iA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getFullyQualifiedName(){let e=this.getTypeParameters().map(r=>r.getFullyQualifiedName()).join(", ");return this.isGenericType()?`multiversx:types:${this.getName()}<${e}>`:`multiversx:types:${this.getName()}`}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}getTypeParameters(){return this.typeParameters}isGenericType(){return this.typeParameters.length>0}getFirstTypeParameter(){return Cx.guardTrue(this.typeParameters.length>0,"type parameters length > 0"),this.typeParameters[0]}toString(){let e=this.getTypeParameters().map(n=>n.toString()).join(", "),r=e?`<${e}>`:"";return`${this.name}${r}`}equals(e){return t.equals(this,e)}static equals(e,r){return e.getFullyQualifiedName()==r.getFullyQualifiedName()}static equalsMany(e,r){return e.every((n,i)=>n.equals(r[i]))}static isAssignableFromMany(e,r){return e.every((n,i)=>n.isAssignableFrom(r[i]))}differs(e){return!this.equals(e)}valueOf(){return this.name}isAssignableFrom(e){if(!t.equalsMany(this.getTypeParameters(),e.getTypeParameters()))return!1;let n=this.getFullyQualifiedName();return t.getFullyQualifiedNamesInHierarchy(e).includes(n)?!0:e.hasClassOrSuperclass(this.getClassName())}static getFullyQualifiedNamesInHierarchy(e){return iA.getJavascriptPrototypesInHierarchy(e,i=>i.belongsToTypesystem).map(i=>i.getFullyQualifiedName.call(e))}getNamesOfDependencies(){let e=[];for(let r of this.typeParameters)e.push(r.getName()),e.push(...r.getNamesOfDependencies());return[...new Set(e)]}toJSON(){return{name:this.name,typeParameters:this.typeParameters.map(e=>e.toJSON())}}getCardinality(){return this.cardinality}belongsToTypesystem(){}};ir.Type=fo;fo.ClassName="Type";var uf=class t{constructor(e,r){this.lowerBound=e,this.upperBound=r}static fixed(e){return new t(e,e)}static variable(e){return new t(0,e)}isSingular(){return this.lowerBound==1&&this.upperBound==1}isSingularOrNone(){return this.lowerBound==0&&this.upperBound==1}isComposite(){return this.upperBound!=1}isFixed(){return this.lowerBound==this.upperBound}getLowerBound(){return this.lowerBound}getUpperBound(){return this.upperBound||t.MaxCardinality}};ir.TypeCardinality=uf;uf.MaxCardinality=4096;var yg=class t extends fo{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveType=yg;yg.ClassName="PrimitiveType";var wg=class t extends fo{getClassName(){return t.ClassName}};ir.CustomType=wg;wg.ClassName="CustomType";var cf=class t{constructor(e){this.type=e}getClassName(){return t.ClassName}getClassHierarchy(){return iA.getJavascriptPrototypesInHierarchy(this,n=>n.belongsToTypesystem).map(n=>n.getClassName()).reverse()}getType(){return this.type}hasExactClass(e){return this.getClassName()==e}hasClassOrSuperclass(e){return this.getClassHierarchy().includes(e)}belongsToTypesystem(){}};ir.TypedValue=cf;cf.ClassName="TypedValue";var vg=class t extends cf{constructor(e){super(e)}getClassName(){return t.ClassName}};ir.PrimitiveValue=vg;vg.ClassName="PrimitiveValue";function Iz(t){return t.belongsToTypesystem!==void 0}ir.isTyped=Iz;var Ag=class t extends fo{constructor(){super("...")}getClassName(){return t.ClassName}};ir.TypePlaceholder=Ag;Ag.ClassName="TypePlaceholder";var Eg=class t extends fo{constructor(){super("?")}getClassName(){return t.ClassName}};ir.NullType=Eg;Eg.ClassName="NullType"});var lf=D(bg=>{"use strict";h();Object.defineProperty(bg,"__esModule",{value:!0});bg.TypeExpressionParser=void 0;var Tz=Tx(),_z=Ie(),Cz=sr(),sA=class{constructor(){this.backingTypeFormulaParser=new Tz.TypeFormulaParser}parse(e){try{return this.doParse(e)}catch(r){throw new _z.ErrTypingSystem(`Failed to parse type expression: ${e}. Error: ${r}`)}}doParse(e){let r=this.backingTypeFormulaParser.parseExpression(e);return this.typeFormulaToType(r)}typeFormulaToType(e){let r=e.typeParameters.map(n=>this.typeFormulaToType(n));return new Cz.Type(e.name,r)}};bg.TypeExpressionParser=sA});var aA=D(ho=>{"use strict";h();Object.defineProperty(ho,"__esModule",{value:!0});ho.EndpointParameterDefinition=ho.EndpointModifiers=ho.EndpointDefinition=void 0;var Nz=lf(),Nx="?",xz="N / A",oA=class t{constructor(e,r,n,i){this.input=[],this.output=[],this.name=e,this.input=r||[],this.output=n||[],this.modifiers=i}isConstructor(){return this.name=="constructor"}static fromJSON(e){e.name=e.name==null?Nx:e.name,e.onlyOwner=e.onlyOwner||!1,e.payableInTokens=e.payableInTokens||[],e.inputs=e.inputs||[],e.outputs=e.outputs||[];let r=e.inputs.map(s=>ff.fromJSON(s)),n=e.outputs.map(s=>ff.fromJSON(s)),i=new Sg(e.mutability,e.payableInTokens,e.onlyOwner);return new t(e.name,r,n,i)}};ho.EndpointDefinition=oA;var Sg=class{constructor(e,r,n){this.mutability=e||"",this.payableInTokens=r||[],this.onlyOwner=n||!1}isPayableInEGLD(){return this.isPayableInToken("EGLD")}isPayableInToken(e){return this.payableInTokens.includes(e)?!0:this.payableInTokens.includes(`!${e}`)?!1:!!this.payableInTokens.includes("*")}isPayable(){return this.payableInTokens.length!=0}isReadonly(){return this.mutability=="readonly"}isOnlyOwner(){return this.onlyOwner}};ho.EndpointModifiers=Sg;var ff=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new Nz.TypeExpressionParser().parse(e.type);return new t(e.name||Nx,e.description||xz,r)}};ho.EndpointParameterDefinition=ff});var zu=D(Wr=>{"use strict";h();var Oz=Wr&&Wr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dz=Wr&&Wr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pz=Wr&&Wr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Oz(e,t,r);return Dz(e,t),e};Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Fields=Wr.Field=Wr.FieldDefinition=void 0;var uA=Pz(Ie()),Rz=lf(),cA=class t{constructor(e,r,n){this.name=e,this.description=r,this.type=n}static fromJSON(e){let r=new Rz.TypeExpressionParser().parse(e.type);return new t(e.name,e.description,r)}};Wr.FieldDefinition=cA;var lA=class{constructor(e,r=""){this.value=e,this.name=r}checkTyping(e){let r=this.value.getType();if(!r.equals(e.type))throw new uA.ErrTypingSystem(`check type of field "${e.name}; expected: ${e.type}, actual: ${r}"`);if(this.name!=e.name)throw new uA.ErrTypingSystem(`check name of field "${e.name}"`)}equals(e){return this.name==e.name&&this.value.equals(e.value)}};Wr.Field=lA;var fA=class{static checkTyping(e,r){if(e.length!=r.length)throw new uA.ErrTypingSystem("fields length vs. field definitions length");for(let n=0;n{"use strict";h();Object.defineProperty(go,"__esModule",{value:!0});go.EnumValue=go.EnumVariantDefinition=go.EnumType=void 0;var Bz=Ie(),hA=Rn(),Ig=zu(),Ox=sr(),xx=256,Tg=class t extends Ox.CustomType{constructor(e,r){super(e),this.variants=[],this.variants=r}getClassName(){return t.ClassName}static fromJSON(e){let n=t.assignMissingDiscriminants(e.variants||[]).map(i=>_g.fromJSON(i));return new t(e.name,n)}static assignMissingDiscriminants(e){return e.every(n=>n.discriminant==null)?e.map((n,i)=>({...n,discriminant:i})):e}getVariantByDiscriminant(e){let r=this.variants.find(n=>n.discriminant==e);return hA.guardValueIsSet(`variant by discriminant (${e})`,r),r}getVariantByName(e){let r=this.variants.find(n=>n.name==e);return hA.guardValueIsSet(`variant by name (${e})`,r),r}getNamesOfDependencies(){let e=[];for(let r of this.variants)e.push(...r.getNamesOfDependencies());return[...new Set(e)]}};go.EnumType=Tg;Tg.ClassName="EnumType";var _g=class t{constructor(e,r,n=[]){this.fieldsDefinitions=[],hA.guardTrue(rIg.FieldDefinition.fromJSON(n));return new t(e.name,e.discriminant,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return Ig.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};go.EnumVariantDefinition=_g;var Cg=class t extends Ox.TypedValue{constructor(e,r,n){super(e),this.fields=[],this.name=r.name,this.discriminant=r.discriminant,this.fields=n,this.fieldsByName=new Map(n.map(s=>[s.name,s]));let i=r.getFieldsDefinitions();Ig.Fields.checkTyping(this.fields,i)}getClassName(){return t.ClassName}static fromName(e,r){let n=e.getVariantByName(r);return new t(e,n,[])}static fromDiscriminant(e,r){let n=e.getVariantByDiscriminant(r);return new t(e,n,[])}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields(),i=this.name==e.name,s=this.discriminant==e.discriminant,o=Ig.Fields.equals(r,n);return i&&s&&o}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Bz.ErrMissingFieldOnEnum(e,this.getType().getName())}valueOf(){let e={name:this.name,fields:[]};return this.fields.forEach((r,n)=>e.fields[n]=r.value.valueOf()),e}};go.EnumValue=Cg;Cg.ClassName="EnumValue"});var Px=D(Qu=>{"use strict";h();Object.defineProperty(Qu,"__esModule",{value:!0});Qu.EventTopicDefinition=Qu.EventDefinition=void 0;var Mz=lf(),Dx="?",dA=class t{constructor(e,r){this.inputs=[],this.identifier=e,this.inputs=r||[]}static fromJSON(e){e.identifier=e.identifier==null?Dx:e.identifier,e.inputs=e.inputs||[];let r=e.inputs.map(n=>Ng.fromJSON(n));return new t(e.identifier,r)}};Qu.EventDefinition=dA;var Ng=class t{constructor(e){this.name=e.name,this.type=e.type,this.indexed=e.indexed}static fromJSON(e){let r=new Mz.TypeExpressionParser().parse(e.type);return new t({name:e.name||Dx,type:r,indexed:e.indexed})}};Qu.EventTopicDefinition=Ng});var Wu=D(Ku=>{"use strict";h();Object.defineProperty(Ku,"__esModule",{value:!0});Ku.Struct=Ku.StructType=void 0;var Lz=Ie(),xg=zu(),Rx=sr(),Og=class t extends Rx.CustomType{constructor(e,r){super(e),this.fieldsDefinitions=[],this.fieldsDefinitions=r}getClassName(){return t.ClassName}static fromJSON(e){let r=(e.fields||[]).map(n=>xg.FieldDefinition.fromJSON(n));return new t(e.name,r)}getFieldsDefinitions(){return this.fieldsDefinitions}getFieldDefinition(e){return this.fieldsDefinitions.find(r=>r.name==e)}getNamesOfDependencies(){return xg.Fields.getNamesOfTypeDependencies(this.fieldsDefinitions)}};Ku.StructType=Og;Og.ClassName="StructType";var Dg=class t extends Rx.TypedValue{constructor(e,r){super(e),this.fields=r,this.fieldsByName=new Map(r.map(n=>[n.name,n])),this.checkTyping()}getClassName(){return t.ClassName}checkTyping(){let r=this.getType().getFieldsDefinitions();xg.Fields.checkTyping(this.fields,r)}getFields(){return this.fields}getFieldValue(e){let r=this.fieldsByName.get(e);if(r)return r.value.valueOf();throw new Lz.ErrMissingFieldOnStruct(e,this.getType().getName())}valueOf(){let e={};for(let r of this.fields)e[r.name]=r.value.valueOf();return e}equals(e){if(!this.getType().equals(e.getType()))return!1;let r=this.getFields(),n=e.getFields();return xg.Fields.equals(r,n)}};Ku.Struct=Dg;Dg.ClassName="Struct"});var Yu=D($u=>{"use strict";h();Object.defineProperty($u,"__esModule",{value:!0});$u.AddressValue=$u.AddressType=void 0;var Fz=Ve(),Bx=sr(),df=class t extends Bx.PrimitiveType{constructor(){super("Address")}getClassName(){return t.ClassName}};$u.AddressType=df;df.ClassName="AddressType";var Pg=class t extends Bx.PrimitiveValue{constructor(e){super(new df),this.value=new Fz.Address(e.bech32())}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};$u.AddressValue=Pg;Pg.ClassName="AddressValue"});var Bg=D(Ju=>{"use strict";h();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.OptionalValue=Ju.OptionalType=void 0;var Uz=Rn(),gf=sr(),pf=class t extends gf.Type{constructor(e){super("Optional",[e],gf.TypeCardinality.variable(1))}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(gf.NullType.ClassName);return r||n}};Ju.OptionalType=pf;pf.ClassName="OptionalType";var Rg=class t extends gf.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new pf(new gf.NullType);return new t(e)}isSet(){return!!this.value}getTypedValue(){return Uz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};Ju.OptionalValue=Rg;Rg.ClassName="OptionalValue"});var yf=D(Xu=>{"use strict";h();Object.defineProperty(Xu,"__esModule",{value:!0});Xu.BooleanValue=Xu.BooleanType=void 0;var Mx=sr(),mf=class t extends Mx.PrimitiveType{constructor(){super("bool")}getClassName(){return t.ClassName}};Xu.BooleanType=mf;mf.ClassName="BooleanType";var Mg=class t extends Mx.PrimitiveValue{constructor(e){super(new mf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value===e.value}isTrue(){return this.value===!0}isFalse(){return!this.isTrue()}valueOf(){return this.value}};Xu.BooleanValue=Mg;Mg.ClassName="BooleanValue"});var po=D(Zu=>{"use strict";h();Object.defineProperty(Zu,"__esModule",{value:!0});Zu.BytesValue=Zu.BytesType=void 0;var Lx=sr(),wf=class t extends Lx.PrimitiveType{constructor(){super("bytes")}getClassName(){return t.ClassName}};Zu.BytesType=wf;wf.ClassName="BytesType";var Lg=class t extends Lx.PrimitiveValue{constructor(e){super(new wf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){let r=p.Buffer.from(e,"utf-8");return new t(r)}static fromHex(e){let r=p.Buffer.from(e,"hex");return new t(r)}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value.equals(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Zu.BytesValue=Lg;Lg.ClassName="BytesValue"});var Ux=D(ec=>{"use strict";h();Object.defineProperty(ec,"__esModule",{value:!0});ec.CodeMetadataValue=ec.CodeMetadataType=void 0;var Fx=sr(),Fg=class extends Fx.PrimitiveType{constructor(){super("CodeMetadata")}};ec.CodeMetadataType=Fg;var gA=class extends Fx.PrimitiveValue{constructor(e){super(new Fg),this.value=e}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};ec.CodeMetadataValue=gA});var qg=D(tc=>{"use strict";h();Object.defineProperty(tc,"__esModule",{value:!0});tc.CompositeValue=tc.CompositeType=void 0;var qz=Rn(),pA=sr(),vf=class t extends pA.Type{constructor(...e){super("Composite",e,pA.TypeCardinality.variable(e.length))}getClassName(){return t.ClassName}};tc.CompositeType=vf;vf.ClassName="CompositeType";var Ug=class t extends pA.TypedValue{constructor(e,r){super(e),qz.guardLength(r,e.getTypeParameters().length),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){let r=e.map(i=>i.getType()),n=new vf(...r);return new t(n,e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e?.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();Object.defineProperty(Vg,"__esModule",{value:!0});Vg.CollectionOfTypedValues=void 0;var mA=class{constructor(e){this.items=e}getLength(){return this.items.length}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getLength()!=e.getLength())return!1;for(let r=0;r{"use strict";h();Object.defineProperty(qi,"__esModule",{value:!0});qi.List=qi.OptionValue=qi.ListType=qi.OptionType=void 0;var Vz=Rn(),kz=yA(),La=sr(),Ma=class t extends La.Type{constructor(e){super("Option",[e])}getClassName(){return t.ClassName}isAssignableFrom(e){if(!e.hasExactClass(t.ClassName))return!1;let r=this.getFirstTypeParameter().equals(e.getFirstTypeParameter()),n=e.getFirstTypeParameter().hasExactClass(La.NullType.ClassName);return r||n}};qi.OptionType=Ma;Ma.ClassName="OptionType";var Af=class t extends La.Type{constructor(e){super("List",[e])}getClassName(){return t.ClassName}};qi.ListType=Af;Af.ClassName="ListType";var kg=class t extends La.TypedValue{constructor(e,r=null){super(e),this.value=r}getClassName(){return t.ClassName}static newMissing(){let e=new Ma(new La.NullType);return new t(e)}static newMissingTyped(e){return new t(new Ma(e))}static newProvided(e){let r=new Ma(e.getType());return new t(r,e)}isSet(){return!!this.value}getTypedValue(){return Vz.guardValueIsSet("value",this.value),this.value}valueOf(){return this.value?this.value.valueOf():null}equals(e){return this.value?.equals(e.value)||!1}};qi.OptionValue=kg;kg.ClassName="OptionValue";var Hg=class t extends La.TypedValue{constructor(e,r){super(e),this.backingCollection=new kz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length==0)return new t(new La.TypePlaceholder,[]);let r=e[0].getType(),n=new Af(r);return new t(n,e)}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};qi.List=Hg;Hg.ClassName="List"});var zg=D(rc=>{"use strict";h();Object.defineProperty(rc,"__esModule",{value:!0});rc.ArrayVec=rc.ArrayVecType=void 0;var qx=Rn(),Hz=yA(),Vx=sr(),Gg=class t extends Vx.Type{constructor(e,r){super("Array",[r]),qx.guardTrue(e>0,"array length > 0"),this.length=e}getClassName(){return t.ClassName}};rc.ArrayVecType=Gg;Gg.ClassName="ArrayVecType";var jg=class t extends Vx.TypedValue{constructor(e,r){super(e),qx.guardLength(r,e.length),this.backingCollection=new Hz.CollectionOfTypedValues(r)}getClassName(){return t.ClassName}getLength(){return this.backingCollection.getLength()}getItems(){return this.backingCollection.getItems()}valueOf(){return this.backingCollection.valueOf()}equals(e){return this.backingCollection.equals(e.backingCollection)}};rc.ArrayVec=jg;jg.ClassName="ArrayVec"});var Sf=D(nc=>{"use strict";h();Object.defineProperty(nc,"__esModule",{value:!0});nc.H256Value=nc.H256Type=void 0;var kx=sr(),bf=class t extends kx.PrimitiveType{constructor(){super("H256")}getClassName(){return t.ClassName}};nc.H256Type=bf;bf.ClassName="H256Type";var Qg=class t extends kx.PrimitiveValue{constructor(e){super(new bf),this.value=e}getClassName(){return t.ClassName}equals(e){return this.value.equals(e.value)}valueOf(){return this.value}};nc.H256Value=Qg;Qg.ClassName="H256Value"});var Wg=D(ic=>{"use strict";h();Object.defineProperty(ic,"__esModule",{value:!0});ic.NothingValue=ic.NothingType=void 0;var Hx=sr(),If=class t extends Hx.PrimitiveType{constructor(){super("nothing")}getClassName(){return t.ClassName}};ic.NothingType=If;If.ClassName="NothingType";var Kg=class t extends Hx.PrimitiveValue{constructor(){super(new If)}getClassName(){return t.ClassName}equals(e){return!1}valueOf(){return{}}};ic.NothingValue=Kg;Kg.ClassName="NothingValue"});var Mf=D(Ee=>{"use strict";h();var Gz=Ee&&Ee.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),jz=Ee&&Ee.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),zz=Ee&&Ee.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Gz(e,t,r);return jz(e,t),e},Qz=Ee&&Ee.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ee,"__esModule",{value:!0});Ee.BigIntValue=Ee.BigUIntValue=Ee.I64Value=Ee.U64Value=Ee.I32Value=Ee.U32Value=Ee.I16Value=Ee.U16Value=Ee.I8Value=Ee.U8Value=Ee.NumericalValue=Ee.BigIntType=Ee.BigUIntType=Ee.I64Type=Ee.U64Type=Ee.I32Type=Ee.U32Type=Ee.I16Type=Ee.U16Type=Ee.I8Type=Ee.U8Type=Ee.NumericalType=void 0;var Kz=Qz((rr(),_e(fr))),Gx=zz(Ie()),jx=sr(),$r=class t extends jx.PrimitiveType{constructor(e,r,n){super(e),this.sizeInBytes=r,this.withSign=n}getClassName(){return t.ClassName}hasFixedSize(){return!!this.sizeInBytes}hasArbitrarySize(){return!this.hasFixedSize()}};Ee.NumericalType=$r;$r.ClassName="NumericalType";var Tf=class t extends $r{constructor(){super("u8",1,!1)}getClassName(){return t.ClassName}};Ee.U8Type=Tf;Tf.ClassName="U8Type";var _f=class t extends $r{constructor(){super("i8",1,!0)}getClassName(){return t.ClassName}};Ee.I8Type=_f;_f.ClassName="I8Type";var Cf=class t extends $r{constructor(){super("u16",2,!1)}getClassName(){return t.ClassName}};Ee.U16Type=Cf;Cf.ClassName="U16Type";var Nf=class t extends $r{constructor(){super("i16",2,!0)}getClassName(){return t.ClassName}};Ee.I16Type=Nf;Nf.ClassName="I16Type";var xf=class t extends $r{constructor(){super("u32",4,!1)}getClassName(){return t.ClassName}};Ee.U32Type=xf;xf.ClassName="U32Type";var Of=class t extends $r{constructor(){super("i32",4,!0)}getClassName(){return t.ClassName}};Ee.I32Type=Of;Of.ClassName="I32Type";var Df=class t extends $r{constructor(){super("u64",8,!1)}getClassName(){return t.ClassName}};Ee.U64Type=Df;Df.ClassName="U64Type";var Pf=class t extends $r{constructor(){super("i64",8,!0)}getClassName(){return t.ClassName}};Ee.I64Type=Pf;Pf.ClassName="I64Type";var Rf=class t extends $r{constructor(){super("BigUint",0,!1)}getClassName(){return t.ClassName}};Ee.BigUIntType=Rf;Rf.ClassName="BigUIntType";var Bf=class t extends $r{constructor(){super("Bigint",0,!0)}getClassName(){return t.ClassName}};Ee.BigIntType=Bf;Bf.ClassName="BigIntType";var Yr=class t extends jx.PrimitiveValue{constructor(e,r){if(super(e),typeof r=="bigint"&&(r=r.toString()),this.value=new Kz.default(r),this.sizeInBytes=e.sizeInBytes,this.withSign=e.withSign,this.value.isNaN())throw new Gx.ErrInvalidArgument(`not a number: ${r}`);if(!this.withSign&&this.value.isNegative())throw new Gx.ErrInvalidArgument(`negative, but type is unsigned: ${r}`)}getClassName(){return t.ClassName}equals(e){return this.value.isEqualTo(e.value)}valueOf(){return this.value}toString(){return this.value.toString()}};Ee.NumericalValue=Yr;Yr.ClassName="NumericalValue";var $g=class t extends Yr{constructor(e){super(new Tf,e)}getClassName(){return t.ClassName}};Ee.U8Value=$g;$g.ClassName="U8Value";var Yg=class t extends Yr{constructor(e){super(new _f,e)}getClassName(){return t.ClassName}};Ee.I8Value=Yg;Yg.ClassName="I8Value";var Jg=class t extends Yr{constructor(e){super(new Cf,e)}getClassName(){return t.ClassName}};Ee.U16Value=Jg;Jg.ClassName="U16Value";var Xg=class t extends Yr{constructor(e){super(new Nf,e)}getClassName(){return t.ClassName}};Ee.I16Value=Xg;Xg.ClassName="I16Value";var Zg=class t extends Yr{constructor(e){super(new xf,e)}getClassName(){return t.ClassName}};Ee.U32Value=Zg;Zg.ClassName="U32Value";var ep=class t extends Yr{constructor(e){super(new Of,e)}getClassName(){return t.ClassName}};Ee.I32Value=ep;ep.ClassName="I32Value";var tp=class t extends Yr{constructor(e){super(new Df,e)}getClassName(){return t.ClassName}};Ee.U64Value=tp;tp.ClassName="U64Value";var rp=class t extends Yr{constructor(e){super(new Pf,e)}getClassName(){return t.ClassName}};Ee.I64Value=rp;rp.ClassName="I64Value";var np=class t extends Yr{constructor(e){super(new Rf,e)}getClassName(){return t.ClassName}};Ee.BigUIntValue=np;np.ClassName="BigUIntValue";var ip=class t extends Yr{constructor(e){super(new Bf,e)}getClassName(){return t.ClassName}};Ee.BigIntValue=ip;ip.ClassName="BigIntValue"});var op=D(sc=>{"use strict";h();Object.defineProperty(sc,"__esModule",{value:!0});sc.StringValue=sc.StringType=void 0;var zx=sr(),Lf=class t extends zx.PrimitiveType{constructor(){super("utf-8 string")}getClassName(){return t.ClassName}};sc.StringType=Lf;Lf.ClassName="StringType";var sp=class t extends zx.PrimitiveValue{constructor(e){super(new Lf),this.value=e}getClassName(){return t.ClassName}static fromUTF8(e){return new t(e)}static fromHex(e){let r=p.Buffer.from(e,"hex").toString();return new t(r)}getLength(){return this.value.length}equals(e){return this.value===e.value}valueOf(){return this.value}};sc.StringValue=sp;sp.ClassName="StringValue"});var ac=D(oc=>{"use strict";h();Object.defineProperty(oc,"__esModule",{value:!0});oc.TokenIdentifierValue=oc.TokenIdentifierType=void 0;var Qx=sr(),Wz="EGLD",Ff=class t extends Qx.PrimitiveType{constructor(){super("TokenIdentifier")}getClassName(){return t.ClassName}};oc.TokenIdentifierType=Ff;Ff.ClassName="TokenIdentifierType";var ap=class t extends Qx.PrimitiveValue{constructor(e){super(new Ff),this.value=e}static egld(){return new t(Wz)}static esdtTokenIdentifier(e){return new t(e)}getClassName(){return t.ClassName}getLength(){return this.value.length}equals(e){return this.getLength()!=e.getLength()?!1:this.value==e.value}valueOf(){return this.value}toString(){return this.value.toString()}};oc.TokenIdentifierValue=ap;ap.ClassName="TokenIdentifierValue"});var cp=D(Bn=>{"use strict";h();var $z=Bn&&Bn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Yz=Bn&&Bn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Jz=Bn&&Bn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$z(e,t,r);return Yz(e,t),e};Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Tuple=Bn.TupleType=void 0;var Xz=Jz(Ie()),Kx=zu(),Wx=Wu(),Uf=class t extends Wx.StructType{constructor(...e){super(t.prepareName(e),t.prepareFieldDefinitions(e))}getClassName(){return t.ClassName}static prepareName(e){return`tuple<${e.map(i=>i.toString()).join(", ")}>`}static prepareFieldDefinitions(e){return e.map((n,i)=>new Kx.FieldDefinition($x(i),"anonymous tuple field",n))}};Bn.TupleType=Uf;Uf.ClassName="TupleType";function $x(t){return`field${t}`}var up=class t extends Wx.Struct{constructor(e,r){super(e,r)}getClassName(){return t.ClassName}static fromItems(e){if(e.length<1)throw new Xz.ErrTypingSystem("bad tuple items");let r=e.map(s=>s.getType()),n=new Uf(...r),i=e.map((s,o)=>new Kx.Field(s,$x(o)));return new t(n,i)}};Bn.Tuple=up;up.ClassName="Tuple"});var hp=D(mo=>{"use strict";h();Object.defineProperty(mo,"__esModule",{value:!0});mo.VariadicValue=mo.CountedVariadicType=mo.VariadicType=void 0;var uc=sr(),Fa=class t extends uc.Type{constructor(e,r=!1){super("Variadic",[e],uc.TypeCardinality.variable()),this.isCounted=r}getClassName(){return t.ClassName}};mo.VariadicType=Fa;Fa.ClassName="VariadicType";var lp=class extends uc.Type{constructor(e){super("Variadic",[e],uc.TypeCardinality.variable())}getClassName(){return Fa.ClassName}};mo.CountedVariadicType=lp;lp.ClassName="VariadicType";var fp=class t extends uc.TypedValue{constructor(e,r){super(e),this.items=r}getClassName(){return t.ClassName}static fromItems(...e){return this.createFromItems(e,!1)}static fromItemsCounted(...e){return this.createFromItems(e,!0)}static createFromItems(e,r){if(e.length==0)return new t(new Fa(new uc.TypePlaceholder,r),[]);let n=e[0].getType();return new t(new Fa(n,r),e)}getItems(){return this.items}valueOf(){return this.items.map(e=>e.valueOf())}equals(e){if(this.getType().differs(e.getType()))return!1;for(let r=0;r{"use strict";h();var Zz=ki&&ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),eQ=ki&&ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tQ=ki&&ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zz(e,t,r);return eQ(e,t),e};Object.defineProperty(ki,"__esModule",{value:!0});ki.TypeMapper=void 0;var Yx=tQ(Ie()),rQ=Yu(),wA=Bg(),nQ=yf(),iQ=po(),sQ=Ux(),dp=qg(),vA=hf(),oQ=zu(),Jx=Ef(),Vi=zg(),aQ=Sf(),Xx=Wg(),Mn=Mf(),uQ=op(),Zx=Wu(),e6=ac(),yo=cp(),gp=hp(),AA=class{constructor(e=[]){this.openTypesFactories=new Map([["Option",(...r)=>new Jx.OptionType(r[0])],["List",(...r)=>new Jx.ListType(r[0])],["VarArgs",(...r)=>new gp.VariadicType(r[0])],["MultiResultVec",(...r)=>new gp.VariadicType(r[0])],["variadic",(...r)=>new gp.VariadicType(r[0])],["counted-variadic",(...r)=>new gp.VariadicType(r[0],!0)],["OptionalArg",(...r)=>new wA.OptionalType(r[0])],["optional",(...r)=>new wA.OptionalType(r[0])],["OptionalResult",(...r)=>new wA.OptionalType(r[0])],["multi",(...r)=>new dp.CompositeType(...r)],["MultiArg",(...r)=>new dp.CompositeType(...r)],["MultiResult",(...r)=>new dp.CompositeType(...r)],["multi",(...r)=>new dp.CompositeType(...r)],["tuple",(...r)=>new yo.TupleType(...r)],["tuple2",(...r)=>new yo.TupleType(...r)],["tuple3",(...r)=>new yo.TupleType(...r)],["tuple4",(...r)=>new yo.TupleType(...r)],["tuple5",(...r)=>new yo.TupleType(...r)],["tuple6",(...r)=>new yo.TupleType(...r)],["tuple7",(...r)=>new yo.TupleType(...r)],["tuple8",(...r)=>new yo.TupleType(...r)],["array2",(...r)=>new Vi.ArrayVecType(2,r[0])],["array8",(...r)=>new Vi.ArrayVecType(8,r[0])],["array16",(...r)=>new Vi.ArrayVecType(16,r[0])],["array20",(...r)=>new Vi.ArrayVecType(20,r[0])],["array32",(...r)=>new Vi.ArrayVecType(32,r[0])],["array46",(...r)=>new Vi.ArrayVecType(46,r[0])],["array48",(...r)=>new Vi.ArrayVecType(48,r[0])],["array64",(...r)=>new Vi.ArrayVecType(64,r[0])],["array128",(...r)=>new Vi.ArrayVecType(128,r[0])],["array256",(...r)=>new Vi.ArrayVecType(256,r[0])]]),this.closedTypesMap=new Map([["u8",new Mn.U8Type],["u16",new Mn.U16Type],["u32",new Mn.U32Type],["u64",new Mn.U64Type],["U64",new Mn.U64Type],["BigUint",new Mn.BigUIntType],["i8",new Mn.I8Type],["i16",new Mn.I16Type],["i32",new Mn.I32Type],["i64",new Mn.I64Type],["Bigint",new Mn.BigIntType],["BigInt",new Mn.BigIntType],["bool",new nQ.BooleanType],["bytes",new iQ.BytesType],["Address",new rQ.AddressType],["H256",new aQ.H256Type],["utf-8 string",new uQ.StringType],["TokenIdentifier",new e6.TokenIdentifierType],["EgldOrEsdtTokenIdentifier",new e6.TokenIdentifierType],["CodeMetadata",new sQ.CodeMetadataType],["nothing",new Xx.NothingType],["AsyncCall",new Xx.NothingType]]),this.learnedTypesMap=new Map;for(let r of e)this.learnedTypesMap.set(r.getName(),r)}mapType(e){let r=this.mapTypeRecursively(e);if(r)return r.isGenericType()||this.learnType(r),r;throw new Yx.ErrTypingSystem(`Cannot map the type "${e.getName()}" to a known type`)}mapTypeRecursively(e){let r=e.isGenericType(),n=this.learnedTypesMap.get(e.getName());if(n)return n;let i=this.closedTypesMap.get(e.getName());return i||(e.hasExactClass(vA.EnumType.ClassName)?this.mapEnumType(e):e.hasExactClass(Zx.StructType.ClassName)?this.mapStructType(e):r?this.mapGenericType(e):null)}learnType(e){this.learnedTypesMap.delete(e.getName()),this.learnedTypesMap.set(e.getName(),e)}mapStructType(e){let r=this.mappedFields(e.getFieldsDefinitions());return new Zx.StructType(e.getName(),r)}mapEnumType(e){let r=e.variants.map(i=>new vA.EnumVariantDefinition(i.name,i.discriminant,this.mappedFields(i.getFieldsDefinitions())));return new vA.EnumType(e.getName(),r)}mappedFields(e){return e.map(r=>new oQ.FieldDefinition(r.name,r.description,this.mapType(r.type)))}mapGenericType(e){let n=e.getTypeParameters().map(s=>this.mapType(s)),i=this.openTypesFactories.get(e.getName());if(!i)throw new Yx.ErrTypingSystem(`Cannot map the generic type "${e.getName()}" to a known type`);return i(...n)}};ki.TypeMapper=AA});var s6=D(Hi=>{"use strict";h();var cQ=Hi&&Hi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),lQ=Hi&&Hi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),fQ=Hi&&Hi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&cQ(e,t,r);return lQ(e,t),e};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.AbiRegistry=void 0;var t6=fQ(Ie()),qf=Rn(),Vf=aA(),r6=hf(),bA=Px(),n6=Wu(),hQ=EA(),dQ="?",SA=class t{constructor(e){this.endpoints=[],this.customTypes=[],this.events=[],this.name=e.name,this.constructorDefinition=e.constructorDefinition,this.endpoints=e.endpoints,this.customTypes=e.customTypes,this.events=e.events||[]}static create(e){let r=e.name||dQ,n=e.constructor||{},i=e.endpoints||[],s=e.types||{},o=e.events||[],u=Vf.EndpointDefinition.fromJSON({name:"constructor",...n}),a=i.map(A=>Vf.EndpointDefinition.fromJSON(A)),c=[];for(let A in s){let T=s[A];if(T.type=="struct")c.push(n6.StructType.fromJSON({name:A,fields:T.fields}));else if(T.type=="enum"||T.type=="explicit-enum")c.push(r6.EnumType.fromJSON({name:A,variants:T.variants}));else throw new t6.ErrTypingSystem(`Cannot handle custom type: ${A}`)}let f=o.map(A=>bA.EventDefinition.fromJSON(A));return new t({name:r,constructorDefinition:u,endpoints:a,customTypes:c,events:f}).remapToKnownTypes()}getCustomType(e){let r=this.customTypes.find(n=>n.getName()==e);return qf.guardValueIsSetWithMessage(`custom type [${e}] not found`,r),r}getStruct(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(n6.StructType.ClassName));return qf.guardValueIsSetWithMessage(`struct [${e}] not found`,r),r}getStructs(e){return e.map(r=>this.getStruct(r))}getEnum(e){let r=this.customTypes.find(n=>n.getName()==e&&n.hasExactClass(r6.EnumType.ClassName));return qf.guardValueIsSetWithMessage(`enum [${e}] not found`,r),r}getEnums(e){return e.map(r=>this.getEnum(r))}getEndpoints(){return this.endpoints}getEndpoint(e){let r=this.endpoints.find(n=>n.name==e);return qf.guardValueIsSetWithMessage(`endpoint [${e}] not found`,r),r}getEvent(e){let r=this.events.find(n=>n.identifier==e);return qf.guardValueIsSetWithMessage(`event [${e}] not found`,r),r}remapToKnownTypes(){let e=new hQ.TypeMapper([]),r=[];for(let u of this.customTypes)this.mapCustomTypeDepthFirst(u,this.customTypes,e,r);if(this.customTypes.length!=r.length)throw new t6.ErrTypingSystem("Did not re-map all custom types");let n=i6(this.constructorDefinition,e),i=[];for(let u of this.endpoints)i.push(i6(u,e));let s=this.events.map(u=>gQ(u,e));return new t({name:this.name,constructorDefinition:n,endpoints:i,customTypes:r,events:s})}mapCustomTypeDepthFirst(e,r,n,i){if(i.findIndex(u=>u.getName()==e.getName())>=0)return;for(let u of e.getNamesOfDependencies()){let a=r.find(c=>c.getName()==u);a&&this.mapCustomTypeDepthFirst(a,r,n,i)}let o=n.mapType(e);i.push(o)}};Hi.AbiRegistry=SA;function i6(t,e){let r=t.input.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type))),n=t.output.map(i=>new Vf.EndpointParameterDefinition(i.name,i.description,e.mapType(i.type)));return new Vf.EndpointDefinition(t.name,r,n,t.modifiers)}function gQ(t,e){let r=t.inputs.map(n=>new bA.EventTopicDefinition({name:n.name,type:e.mapType(n.type),indexed:n.indexed}));return new bA.EventDefinition(t.identifier,r)}});var a6=D(cc=>{"use strict";h();Object.defineProperty(cc,"__esModule",{value:!0});cc.createListOfTokenIdentifiers=cc.createListOfAddresses=void 0;var pQ=Yu(),o6=Ef(),mQ=ac();function yQ(t){let e=t.map(n=>new pQ.AddressValue(n));return o6.List.fromItems(e)}cc.createListOfAddresses=yQ;function wQ(t){let e=t.map(n=>new mQ.TokenIdentifierValue(n));return o6.List.fromItems(e)}cc.createListOfTokenIdentifiers=wQ});var E6=D(Dr=>{"use strict";h();var vQ=Dr&&Dr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),AQ=Dr&&Dr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),EQ=Dr&&Dr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vQ(e,t,r);return AQ(e,t),e};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.onPrimitiveTypeSelect=Dr.onPrimitiveValueSelect=Dr.onTypedValueSelect=Dr.onTypeSelect=void 0;var mp=EQ(Ie()),u6=Yu(),c6=yf(),l6=po(),f6=hf(),pp=Ef(),h6=Sf(),d6=Mf(),g6=Wg(),p6=Wu(),m6=ac(),y6=cp(),w6=sr(),v6=zg(),A6=op();function bQ(t,e){if(t.hasExactClass(pp.OptionType.ClassName))return e.onOption();if(t.hasExactClass(pp.ListType.ClassName))return e.onList();if(t.hasExactClass(v6.ArrayVecType.ClassName))return e.onArray();if(t.hasClassOrSuperclass(w6.PrimitiveType.ClassName))return e.onPrimitive();if(t.hasExactClass(p6.StructType.ClassName))return e.onStruct();if(t.hasExactClass(y6.TupleType.ClassName))return e.onTuple();if(t.hasExactClass(f6.EnumType.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`type isn't known: ${t}`)}Dr.onTypeSelect=bQ;function SQ(t,e){if(t.hasClassOrSuperclass(w6.PrimitiveValue.ClassName))return e.onPrimitive();if(t.hasExactClass(pp.OptionValue.ClassName))return e.onOption();if(t.hasExactClass(pp.List.ClassName))return e.onList();if(t.hasExactClass(v6.ArrayVec.ClassName))return e.onArray();if(t.hasExactClass(p6.Struct.ClassName))return e.onStruct();if(t.hasExactClass(y6.Tuple.ClassName))return e.onTuple();if(t.hasExactClass(f6.EnumValue.ClassName))return e.onEnum();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`value isn't typed: ${t}`)}Dr.onTypedValueSelect=SQ;function IQ(t,e){if(t.hasExactClass(c6.BooleanValue.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(d6.NumericalValue.ClassName))return e.onNumerical();if(t.hasExactClass(u6.AddressValue.ClassName))return e.onAddress();if(t.hasExactClass(l6.BytesValue.ClassName))return e.onBytes();if(t.hasExactClass(A6.StringValue.ClassName))return e.onString();if(t.hasExactClass(h6.H256Value.ClassName))return e.onH256();if(t.hasExactClass(m6.TokenIdentifierValue.ClassName))return e.onTypeIdentifier();if(t.hasExactClass(g6.NothingValue.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`value isn't a primitive: ${t.getType()}`)}Dr.onPrimitiveValueSelect=IQ;function TQ(t,e){if(t.hasExactClass(c6.BooleanType.ClassName))return e.onBoolean();if(t.hasClassOrSuperclass(d6.NumericalType.ClassName))return e.onNumerical();if(t.hasExactClass(u6.AddressType.ClassName))return e.onAddress();if(t.hasExactClass(l6.BytesType.ClassName))return e.onBytes();if(t.hasExactClass(A6.StringType.ClassName))return e.onString();if(t.hasExactClass(h6.H256Type.ClassName))return e.onH256();if(t.hasExactClass(m6.TokenIdentifierType.ClassName))return e.onTokenIndetifier();if(t.hasExactClass(g6.NothingType.ClassName))return e.onNothing();if(e.onOther)return e.onOther();throw new mp.ErrTypingSystem(`type isn't a known primitive: ${t}`)}Dr.onPrimitiveTypeSelect=TQ});var dr=D(He=>{"use strict";h();var _Q=He&&He.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ut=He&&He.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&_Q(e,t,r)};Object.defineProperty(He,"__esModule",{value:!0});Ut(s6(),He);Ut(Yu(),He);Ut(Bg(),He);Ut(yf(),He);Ut(po(),He);Ut(qg(),He);Ut(aA(),He);Ut(hf(),He);Ut(a6(),He);Ut(zu(),He);Ut(Ef(),He);Ut(zg(),He);Ut(Sf(),He);Ut(E6(),He);Ut(Wg(),He);Ut(Mf(),He);Ut(op(),He);Ut(Wu(),He);Ut(ac(),He);Ut(cp(),He);Ut(lf(),He);Ut(EA(),He);Ut(sr(),He);Ut(hp(),He)});var S6=D(Gi=>{"use strict";h();var CQ=Gi&&Gi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),NQ=Gi&&Gi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xQ=Gi&&Gi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&CQ(e,t,r);return NQ(e,t),e};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.OptionValueBinaryCodec=void 0;var b6=xQ(Ie()),yp=dr(),IA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){if(e[0]==0)return[yp.OptionValue.newMissingTyped(r),1];if(e[0]!=1)throw new b6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return[yp.OptionValue.newProvided(n),i+1]}decodeTopLevel(e,r){if(e.length==0)return new yp.OptionValue(r);if(e[0]!=1)throw new b6.ErrCodec("invalid buffer for optional value");let[n,i]=this.binaryCodec.decodeNested(e.slice(1),r);return new yp.OptionValue(r,n)}encodeNested(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([0])}encodeTopLevel(e){return e.isSet()?p.Buffer.concat([p.Buffer.from([1]),this.binaryCodec.encodeNested(e.getTypedValue())]):p.Buffer.from([])}};Gi.OptionValueBinaryCodec=IA});var I6=D(wp=>{"use strict";h();Object.defineProperty(wp,"__esModule",{value:!0});wp.AddressBinaryCodec=void 0;var OQ=Ve(),DQ=dr(),TA=class{decodeNested(e){let r=e.slice(0,32),n=new OQ.Address(r);return[new DQ.AddressValue(n),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf().pubkey()}encodeTopLevel(e){return e.valueOf().pubkey()}};wp.AddressBinaryCodec=TA});var _6=D(ji=>{"use strict";h();var PQ=ji&&ji.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RQ=ji&&ji.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BQ=ji&&ji.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PQ(e,t,r);return RQ(e,t),e};Object.defineProperty(ji,"__esModule",{value:!0});ji.BooleanBinaryCodec=void 0;var MQ=BQ(Ie()),T6=dr(),kf=class t{decodeNested(e){let r=e.readUInt8(0);return[new T6.BooleanValue(r==t.TRUE),1]}decodeTopLevel(e){if(e.length>1)throw new MQ.ErrInvalidArgument("buffer should be of size <= 1");let r=e[0];return new T6.BooleanValue(r==t.TRUE)}encodeNested(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([t.FALSE])}encodeTopLevel(e){return e.isTrue()?p.Buffer.from([t.TRUE]):p.Buffer.from([])}};ji.BooleanBinaryCodec=kf;kf.TRUE=1;kf.FALSE=0});var Ap=D(vp=>{"use strict";h();Object.defineProperty(vp,"__esModule",{value:!0});vp.SizeOfU32=void 0;vp.SizeOfU32=4});var N6=D(lc=>{"use strict";h();var LQ=lc&&lc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lc,"__esModule",{value:!0});lc.NumericalBinaryCodec=void 0;var Hf=LQ((rr(),_e(fr))),_A=dr(),C6=Ap(),$t=Bu(),CA=class{decodeNested(e,r){let n=0,i=r.sizeInBytes;i||(n=C6.SizeOfU32,i=e.readUInt32BE(0));let s=e.slice(n,n+i),o=this.decodeTopLevel(s,r),u=i+n;return[o,u]}decodeTopLevel(e,r){let n=$t.cloneBuffer(e);if(e.length==0)return new _A.NumericalValue(r,new Hf.default(0));if(!r.withSign||$t.isMsbZero(n)){let c=$t.bufferToBigInt(n);return new _A.NumericalValue(r,c)}$t.flipBufferBitsInPlace(n);let a=$t.bufferToBigInt(n).multipliedBy(new Hf.default(-1)).minus(new Hf.default(1));return new _A.NumericalValue(r,a)}encodeNested(e){if(e.sizeInBytes)return this.encodeNestedFixedSize(e,e.sizeInBytes);let r=this.encodeTopLevel(e),n=p.Buffer.alloc(C6.SizeOfU32);return n.writeUInt32BE(r.length),p.Buffer.concat([n,r])}encodeNestedFixedSize(e,r){if(e.value.isZero())return p.Buffer.alloc(r,0);if(!e.withSign){let o=$t.bigIntToBuffer(e.value),u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}if(e.value.isPositive()){let o=$t.bigIntToBuffer(e.value);$t.isMsbOne(o)&&(o=$t.prependByteToBuffer(o,0));let u=p.Buffer.alloc(r-o.length,0);return p.Buffer.concat([u,o])}let n=e.value.plus(new Hf.default(1)),i=$t.bigIntToBuffer(n);$t.flipBufferBitsInPlace(i),$t.isMsbZero(i)&&(i=$t.prependByteToBuffer(i,255));let s=p.Buffer.alloc(r-i.length,255);return p.Buffer.concat([s,i])}encodeTopLevel(e){let r=e.withSign;return e.value.isZero()?p.Buffer.alloc(0):r?this.encodePrimitive(e):$t.bigIntToBuffer(e.value)}encodePrimitive(e){if(e.value.isPositive()){let i=$t.bigIntToBuffer(e.value);return $t.isMsbOne(i)&&(i=$t.prependByteToBuffer(i,0)),i}let r=e.value.plus(new Hf.default(1)),n=$t.bigIntToBuffer(r);return $t.flipBufferBitsInPlace(n),$t.isMsbZero(n)&&(n=$t.prependByteToBuffer(n,255)),n}};lc.NumericalBinaryCodec=CA});var x6=D(Ep=>{"use strict";h();Object.defineProperty(Ep,"__esModule",{value:!0});Ep.H256BinaryCodec=void 0;var FQ=Sf(),NA=class{decodeNested(e){let r=e.slice(0,32);return[new FQ.H256Value(r),32]}decodeTopLevel(e){let[r,n]=this.decodeNested(e);return r}encodeNested(e){return e.valueOf()}encodeTopLevel(e){return e.valueOf()}};Ep.H256BinaryCodec=NA});var Ip=D(Sp=>{"use strict";h();Object.defineProperty(Sp,"__esModule",{value:!0});Sp.BytesBinaryCodec=void 0;var O6=po(),bp=Ap(),xA=class{decodeNested(e){let r=e.readUInt32BE(0),n=e.slice(bp.SizeOfU32,bp.SizeOfU32+r);return[new O6.BytesValue(n),bp.SizeOfU32+r]}decodeTopLevel(e){return new O6.BytesValue(e)}encodeNested(e){let r=p.Buffer.alloc(bp.SizeOfU32);return r.writeUInt32BE(e.getLength()),p.Buffer.concat([r,e.valueOf()])}encodeTopLevel(e){return e.valueOf()}};Sp.BytesBinaryCodec=xA});var P6=D(Tp=>{"use strict";h();Object.defineProperty(Tp,"__esModule",{value:!0});Tp.TokenIdentifierCodec=void 0;var UQ=po(),D6=ac(),qQ=Ip(),OA=class{constructor(){this.bytesCodec=new qQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesCodec.decodeNested(e);return[new D6.TokenIdentifierValue(r.toString()),n]}decodeTopLevel(e){let r=this.bytesCodec.decodeTopLevel(e);return new D6.TokenIdentifierValue(r.toString())}encodeNested(e){let r=UQ.BytesValue.fromUTF8(e.valueOf());return this.bytesCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Tp.TokenIdentifierCodec=OA});var B6=D(_p=>{"use strict";h();Object.defineProperty(_p,"__esModule",{value:!0});_p.NothingCodec=void 0;var R6=dr(),DA=class{decodeNested(){return[new R6.NothingValue,0]}decodeTopLevel(){return new R6.NothingValue}encodeNested(){return p.Buffer.from([])}encodeTopLevel(){return p.Buffer.from([])}};_p.NothingCodec=DA});var L6=D(Cp=>{"use strict";h();Object.defineProperty(Cp,"__esModule",{value:!0});Cp.StringBinaryCodec=void 0;var M6=dr(),VQ=po(),kQ=Ip(),PA=class{constructor(){this.bytesBinaryCodec=new kQ.BytesBinaryCodec}decodeNested(e){let[r,n]=this.bytesBinaryCodec.decodeNested(e);return[new M6.StringValue(r.valueOf().toString()),n]}decodeTopLevel(e){return new M6.StringValue(e.toString())}encodeNested(e){let r=VQ.BytesValue.fromUTF8(e.valueOf());return this.bytesBinaryCodec.encodeNested(r)}encodeTopLevel(e){return p.Buffer.from(e.valueOf())}};Cp.StringBinaryCodec=PA});var F6=D(xp=>{"use strict";h();Object.defineProperty(xp,"__esModule",{value:!0});xp.PrimitiveBinaryCodec=void 0;var Np=dr(),HQ=I6(),GQ=_6(),jQ=N6(),zQ=x6(),QQ=Ip(),KQ=P6(),WQ=B6(),$Q=L6(),RA=class{constructor(e){this.binaryCodec=e,this.booleanCodec=new GQ.BooleanBinaryCodec,this.numericalCodec=new jQ.NumericalBinaryCodec,this.addressCodec=new HQ.AddressBinaryCodec,this.h256Codec=new zQ.H256BinaryCodec,this.bytesCodec=new QQ.BytesBinaryCodec,this.stringCodec=new $Q.StringBinaryCodec,this.tokenIdentifierCodec=new KQ.TokenIdentifierCodec,this.nothingCodec=new WQ.NothingCodec}decodeNested(e,r){return Np.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeNested(e),onNumerical:()=>this.numericalCodec.decodeNested(e,r),onAddress:()=>this.addressCodec.decodeNested(e),onBytes:()=>this.bytesCodec.decodeNested(e),onString:()=>this.stringCodec.decodeNested(e),onH256:()=>this.h256Codec.decodeNested(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeNested(e),onNothing:()=>this.nothingCodec.decodeNested()})}decodeTopLevel(e,r){return Np.onPrimitiveTypeSelect(r,{onBoolean:()=>this.booleanCodec.decodeTopLevel(e),onNumerical:()=>this.numericalCodec.decodeTopLevel(e,r),onAddress:()=>this.addressCodec.decodeTopLevel(e),onBytes:()=>this.bytesCodec.decodeTopLevel(e),onString:()=>this.stringCodec.decodeTopLevel(e),onH256:()=>this.h256Codec.decodeTopLevel(e),onTokenIndetifier:()=>this.tokenIdentifierCodec.decodeTopLevel(e),onNothing:()=>this.nothingCodec.decodeTopLevel()})}encodeNested(e){return Np.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeNested(e),onNumerical:()=>this.numericalCodec.encodeNested(e),onAddress:()=>this.addressCodec.encodeNested(e),onBytes:()=>this.bytesCodec.encodeNested(e),onString:()=>this.stringCodec.encodeNested(e),onH256:()=>this.h256Codec.encodeNested(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeNested(e),onNothing:()=>this.nothingCodec.encodeNested()})}encodeTopLevel(e){return Np.onPrimitiveValueSelect(e,{onBoolean:()=>this.booleanCodec.encodeTopLevel(e),onNumerical:()=>this.numericalCodec.encodeTopLevel(e),onAddress:()=>this.addressCodec.encodeTopLevel(e),onBytes:()=>this.bytesCodec.encodeTopLevel(e),onString:()=>this.stringCodec.encodeTopLevel(e),onH256:()=>this.h256Codec.encodeTopLevel(e),onTypeIdentifier:()=>this.tokenIdentifierCodec.encodeTopLevel(e),onNothing:()=>this.nothingCodec.encodeTopLevel()})}};xp.PrimitiveBinaryCodec=RA});var V6=D(Op=>{"use strict";h();Object.defineProperty(Op,"__esModule",{value:!0});Op.ListBinaryCodec=void 0;var U6=dr(),q6=Ap(),BA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.getFirstTypeParameter(),i=[],s=e.readUInt32BE(0);this.binaryCodec.constraints.checkListLength(s);let o=e,u=q6.SizeOfU32;e=o.slice(u);for(let a=0;a0;){let[u,a]=this.binaryCodec.decodeNested(e,n);i.push(u),o+=a,e=s.slice(o),this.binaryCodec.constraints.checkListLength(i.length)}return new U6.List(r,i)}encodeNested(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=p.Buffer.alloc(q6.SizeOfU32);r.writeUInt32BE(e.getLength());let n=[];for(let s of e.getItems()){let o=this.binaryCodec.encodeNested(s);n.push(o)}return p.Buffer.concat([r,...n])}encodeTopLevel(e){this.binaryCodec.constraints.checkListLength(e.getLength());let r=[];for(let i of e.getItems()){let s=this.binaryCodec.encodeNested(i);r.push(s)}return p.Buffer.concat(r)}};Op.ListBinaryCodec=BA});var LA=D(Dp=>{"use strict";h();Object.defineProperty(Dp,"__esModule",{value:!0});Dp.FieldsBinaryCodec=void 0;var YQ=dr(),MA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=[],i=0;for(let s of r){let[o,u]=this.binaryCodec.decodeNested(e,s.type);e=e.slice(u),i+=u;let a=new YQ.Field(o,s.name);n.push(a)}return[n,i]}encodeNested(e){let r=[];for(let n of e){let i=this.binaryCodec.encodeNested(n.value);r.push(i)}return p.Buffer.concat(r)}};Dp.FieldsBinaryCodec=MA});var UA=D(Pp=>{"use strict";h();Object.defineProperty(Pp,"__esModule",{value:!0});Pp.StructBinaryCodec=void 0;var JQ=dr(),XQ=LA(),FA=class{constructor(e){this.fieldsCodec=new XQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let n=r.getFieldsDefinitions(),[i,s]=this.fieldsCodec.decodeNested(e,n);return[new JQ.Struct(r,i),s]}encodeNested(e){let r=e.getFields();return this.fieldsCodec.encodeNested(r)}encodeTopLevel(e){return this.encodeNested(e)}};Pp.StructBinaryCodec=FA});var k6=D(Bp=>{"use strict";h();Object.defineProperty(Bp,"__esModule",{value:!0});Bp.EnumBinaryCodec=void 0;var Rp=dr(),ZQ=LA(),qA=class{constructor(e){this.binaryCodec=e,this.fieldsCodec=new ZQ.FieldsBinaryCodec(e)}decodeTopLevel(e,r){let[n]=this.decodeNested(e,r);return n}decodeNested(e,r){let[n,i]=this.readDiscriminant(e);e=e.slice(i);let s=r.getVariantByDiscriminant(n),o=s.getFieldsDefinitions(),[u,a]=this.fieldsCodec.decodeNested(e,o);return[new Rp.EnumValue(r,s,u),i+a]}readDiscriminant(e){let[r,n]=this.binaryCodec.decodeNested(e,new Rp.U8Type);return[r.valueOf(),n]}encodeNested(e){let r=new Rp.U8Value(e.discriminant),n=this.binaryCodec.encodeNested(r),i=e.getFields(),s=this.fieldsCodec.encodeNested(i);return p.Buffer.concat([n,s])}encodeTopLevel(e){let r=e.getFields(),n=r.length>0,i=this.fieldsCodec.encodeNested(r),s=new Rp.U8Value(e.discriminant),o=n?this.binaryCodec.encodeNested(s):this.binaryCodec.encodeTopLevel(s);return p.Buffer.concat([o,i])}};Bp.EnumBinaryCodec=qA});var H6=D(Mp=>{"use strict";h();Object.defineProperty(Mp,"__esModule",{value:!0});Mp.TupleBinaryCodec=void 0;var eK=UA(),VA=class{constructor(e){this.structCodec=new eK.StructBinaryCodec(e)}decodeTopLevel(e,r){return this.structCodec.decodeTopLevel(e,r)}decodeNested(e,r){return this.structCodec.decodeNested(e,r)}encodeNested(e){return this.structCodec.encodeNested(e)}encodeTopLevel(e){return this.structCodec.encodeTopLevel(e)}};Mp.TupleBinaryCodec=VA});var G6=D(Lp=>{"use strict";h();Object.defineProperty(Lp,"__esModule",{value:!0});Lp.ArrayVecBinaryCodec=void 0;var tK=dr(),kA=class{constructor(e){this.binaryCodec=e}decodeNested(e,r){let n=r.length,i=r.getFirstTypeParameter(),s=[],o=0;for(let u=0;u{"use strict";h();var rK=Ln&&Ln.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),nK=Ln&&Ln.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),iK=Ln&&Ln.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rK(e,t,r);return nK(e,t),e};Object.defineProperty(Ln,"__esModule",{value:!0});Ln.BinaryCodecConstraints=Ln.BinaryCodec=void 0;var j6=iK(Ie()),Fp=dr(),z6=Rn(),sK=S6(),oK=F6(),aK=V6(),uK=UA(),cK=k6(),lK=H6(),fK=G6(),HA=class{constructor(e=null){this.constraints=e||new Up,this.optionCodec=new sK.OptionValueBinaryCodec(this),this.listCodec=new aK.ListBinaryCodec(this),this.arrayCodec=new fK.ArrayVecBinaryCodec(this),this.primitiveCodec=new oK.PrimitiveBinaryCodec(this),this.structCodec=new uK.StructBinaryCodec(this),this.tupleCodec=new lK.TupleBinaryCodec(this),this.enumCodec=new cK.EnumBinaryCodec(this)}decodeTopLevel(e,r){return this.constraints.checkBufferLength(e),Fp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeTopLevel(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeTopLevel(e,r),onArray:()=>this.arrayCodec.decodeTopLevel(e,r),onPrimitive:()=>this.primitiveCodec.decodeTopLevel(e,r),onStruct:()=>this.structCodec.decodeTopLevel(e,r),onTuple:()=>this.tupleCodec.decodeTopLevel(e,r),onEnum:()=>this.enumCodec.decodeTopLevel(e,r)})}decodeNested(e,r){this.constraints.checkBufferLength(e);let[n,i]=Fp.onTypeSelect(r,{onOption:()=>this.optionCodec.decodeNested(e,r.getFirstTypeParameter()),onList:()=>this.listCodec.decodeNested(e,r),onArray:()=>this.arrayCodec.decodeNested(e,r),onPrimitive:()=>this.primitiveCodec.decodeNested(e,r),onStruct:()=>this.structCodec.decodeNested(e,r),onTuple:()=>this.tupleCodec.decodeNested(e,r),onEnum:()=>this.enumCodec.decodeNested(e,r)});return[n,i]}encodeNested(e){return z6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),Fp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeNested(e),onOption:()=>this.optionCodec.encodeNested(e),onList:()=>this.listCodec.encodeNested(e),onArray:()=>this.arrayCodec.encodeNested(e),onStruct:()=>this.structCodec.encodeNested(e),onTuple:()=>this.tupleCodec.encodeNested(e),onEnum:()=>this.enumCodec.encodeNested(e)})}encodeTopLevel(e){return z6.guardTrue(e.getType().getCardinality().isSingular(),"singular cardinality, thus encodable type"),Fp.onTypedValueSelect(e,{onPrimitive:()=>this.primitiveCodec.encodeTopLevel(e),onOption:()=>this.optionCodec.encodeTopLevel(e),onList:()=>this.listCodec.encodeTopLevel(e),onArray:()=>this.arrayCodec.encodeTopLevel(e),onStruct:()=>this.structCodec.encodeTopLevel(e),onTuple:()=>this.tupleCodec.encodeTopLevel(e),onEnum:()=>this.enumCodec.encodeTopLevel(e)})}};Ln.BinaryCodec=HA;var Up=class{constructor(e){this.maxBufferLength=e?.maxBufferLength||256e3,this.maxListLength=e?.maxListLength||128e3}checkBufferLength(e){if(e.length>this.maxBufferLength)throw new j6.ErrCodec(`Buffer too large: ${e.length} > ${this.maxBufferLength}`)}checkListLength(e){if(e>this.maxListLength)throw new j6.ErrCodec(`List too large: ${e} > ${this.maxListLength}`)}};Ln.BinaryCodecConstraints=Up});var Q6=D(Fn=>{"use strict";h();var hK=Fn&&Fn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Fn,"__esModule",{value:!0});Fn.decodeBigNumber=Fn.decodeString=Fn.decodeBool=Fn.decodeUnsignedNumber=void 0;var dK=hK((rr(),_e(fr))),qp=dr(),gK=GA(),Vp=new gK.BinaryCodec;function pK(t){let e=Vp.decodeTopLevel(t,new qp.BigUIntType);return Number(e.valueOf())}Fn.decodeUnsignedNumber=pK;function mK(t){return!!Vp.decodeTopLevel(t,new qp.BooleanType).valueOf()}Fn.decodeBool=mK;function yK(t){let e=Vp.decodeTopLevel(t,new qp.BytesType);return String(e.valueOf())}Fn.decodeString=yK;function wK(t){let e=Vp.decodeTopLevel(t,new qp.BigUIntType);return new dK.default(e.valueOf())}Fn.decodeBigNumber=wK});var jA=D(wo=>{"use strict";h();var vK=wo&&wo.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),K6=wo&&wo.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&vK(e,t,r)};Object.defineProperty(wo,"__esModule",{value:!0});K6(GA(),wo);K6(Q6(),wo)});var fc=D(kp=>{"use strict";h();Object.defineProperty(kp,"__esModule",{value:!0});kp.ArgSerializer=void 0;var W6=hr(),AK=jA(),$6=dr(),zA=Bg(),QA=qg(),KA=hp(),EK={codec:new AK.BinaryCodec},WA=class{constructor(e){e={...EK,...e},this.codec=e.codec}stringToValues(e,r){let n=this.stringToBuffers(e);return this.buffersToValues(n,r)}stringToBuffers(e){return e.split(W6.ARGUMENTS_SEPARATOR).map(r=>p.Buffer.from(r,"hex"))}buffersToValues(e,r){let n=this;e=e||[];let i=[],s=0,o=e.length;for(let d=0;d=o}return i}valuesToString(e){let r=this.valuesToStrings(e),n=r.join(W6.ARGUMENTS_SEPARATOR),i=r.length;return{argumentsString:n,count:i}}valuesToStrings(e){return this.valuesToBuffers(e).map(i=>i.toString("hex"))}valuesToBuffers(e){let r=this,n=[];for(let o of e)i(o);function i(o){if(o.hasExactClass(zA.OptionalValue.ClassName)){let a=o;a.isSet()&&i(a.getTypedValue());return}if(o.hasExactClass(KA.VariadicValue.ClassName)){s(o);return}if(o.hasExactClass(QA.CompositeValue.ClassName)){let a=o;for(let c of a.getItems())i(c);return}let u=r.codec.encodeTopLevel(o);n.push(u)}function s(o){if(o.getType().isCounted){let a=new $6.U32Value(o.getItems().length);n.push(r.codec.encodeTopLevel(a))}for(let a of o.getItems())i(a)}return n}};kp.ArgSerializer=WA});var $A=D((xye,Y6)=>{h();Rs.notEqual=SK;Rs.notOk=IK;Rs.equal=bK;Rs.ok=Rs;Y6.exports=Rs;function bK(t,e,r){Rs(t==e,r)}function SK(t,e,r){Rs(t!=e,r)}function IK(t,e){Rs(!t,e)}function Rs(t,e){if(!t)throw new Error(e||"AssertionError")}});var X6=D((Dye,J6)=>{h();J6.exports=YA;YA.supported=typeof WebAssembly<"u";function YA(t){if(!YA.supported)return null;var e=t&&t.imports,r=TK("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMK00AElgMAIABCADcDACAAQQhqQgA3AwAgAEEQakIANwMAIABBGGpCADcDACAAQSBqQgA3AwAgAEEoakIANwMAIABBMGpCADcDACAAQThqQgA3AwAgAEHAAGpCADcDACAAQcgAakIANwMAIABB0ABqQgA3AwAgAEHYAGpCADcDACAAQeAAakIANwMAIABB6ABqQgA3AwAgAEHwAGpCADcDACAAQfgAakIANwMAIABBgAFqQoiS853/zPmE6gBBACkDAIU3AwAgAEGIAWpCu86qptjQ67O7f0EIKQMAhTcDACAAQZABakKr8NP0r+68tzxBECkDAIU3AwAgAEGYAWpC8e30+KWn/aelf0EYKQMAhTcDACAAQaABakLRhZrv+s+Uh9EAQSApAwCFNwMAIABBqAFqQp/Y+dnCkdqCm39BKCkDAIU3AwAgAEGwAWpC6/qG2r+19sEfQTApAwCFNwMAIABBuAFqQvnC+JuRo7Pw2wBBOCkDAIU3AwAgAEHAAWpCADcDACAAQcgBakIANwMAIABB0AFqQgA3AwALbQEDfyAAQcABaiEDIABByAFqIQQgBCkDAKchBQJAA0AgASACRg0BIAVBgAFGBEAgAyADKQMAIAWtfDcDAEEAIQUgABADCyAAIAVqIAEtAAA6AAAgBUEBaiEFIAFBAWohAQwACwsgBCAFrTcDAAtkAQN/IABBwAFqIQEgAEHIAWohAiABIAEpAwAgAikDAHw3AwAgAEHQAWpCfzcDACACKQMApyEDAkADQCADQYABRg0BIAAgA2pBADoAACADQQFqIQMMAAsLIAIgA603AwAgABADC+U7AiB+CX8gAEGAAWohISAAQYgBaiEiIABBkAFqISMgAEGYAWohJCAAQaABaiElIABBqAFqISYgAEGwAWohJyAAQbgBaiEoICEpAwAhASAiKQMAIQIgIykDACEDICQpAwAhBCAlKQMAIQUgJikDACEGICcpAwAhByAoKQMAIQhCiJLznf/M+YTqACEJQrvOqqbY0Ouzu38hCkKr8NP0r+68tzwhC0Lx7fT4paf9p6V/IQxC0YWa7/rPlIfRACENQp/Y+dnCkdqCm38hDkLr+obav7X2wR8hD0L5wvibkaOz8NsAIRAgACkDACERIABBCGopAwAhEiAAQRBqKQMAIRMgAEEYaikDACEUIABBIGopAwAhFSAAQShqKQMAIRYgAEEwaikDACEXIABBOGopAwAhGCAAQcAAaikDACEZIABByABqKQMAIRogAEHQAGopAwAhGyAAQdgAaikDACEcIABB4ABqKQMAIR0gAEHoAGopAwAhHiAAQfAAaikDACEfIABB+ABqKQMAISAgDSAAQcABaikDAIUhDSAPIABB0AFqKQMAhSEPIAEgBSARfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgEnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBN8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAUfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgFXx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBZ8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAXfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggGHx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBl8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAafHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgG3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBx8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAdfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHnx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB98fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAgfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBx8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAZfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgHXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBF8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAWfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgE3x8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIICB8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAefHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgG3x8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB98fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAUfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgF3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBh8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCASfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgGnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBV8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAYfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgGnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBR8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiASfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgHnx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB18fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAcfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggH3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBN8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAXfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgFnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBt8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAVfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggEXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFICB8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAZfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgGnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBF8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAWfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBN8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAVfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggG3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIICB8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAffHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBx8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAdfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggF3x8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBl8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAUfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgHnx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBN8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAdfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgF3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBt8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByARfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgHHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBl8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAUfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgFXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB58fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAYfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgFnx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIICB8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAffHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgEnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBp8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAdfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgFnx8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBJ8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAgfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgH3x8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIB58fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCAVfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggG3x8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGIBF8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAYfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgF3x8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIBR8fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAafHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggE3x8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIBl8fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSAcfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgHnx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBx8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAYfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgH3x8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIB18fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByASfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggFHx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBp8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAWfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgEXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHICB8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAVfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggGXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBd8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSATfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgG3x8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIBd8fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAgfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgH3x8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBp8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAcfHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgFHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIBF8fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAZfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgHXx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIBN8fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByAefHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgGHx8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBJ8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAVfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgG3x8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBZ8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFIAEgBSAbfHwhASANIAGFQiCKIQ0gCSANfCEJIAUgCYVCGIohBSABIAUgE3x8IQEgDSABhUIQiiENIAkgDXwhCSAFIAmFQj+KIQUgAiAGIBl8fCECIA4gAoVCIIohDiAKIA58IQogBiAKhUIYiiEGIAIgBiAVfHwhAiAOIAKFQhCKIQ4gCiAOfCEKIAYgCoVCP4ohBiADIAcgGHx8IQMgDyADhUIgiiEPIAsgD3whCyAHIAuFQhiKIQcgAyAHIBd8fCEDIA8gA4VCEIohDyALIA98IQsgByALhUI/iiEHIAQgCCASfHwhBCAQIASFQiCKIRAgDCAQfCEMIAggDIVCGIohCCAEIAggFnx8IQQgECAEhUIQiiEQIAwgEHwhDCAIIAyFQj+KIQggASAGICB8fCEBIBAgAYVCIIohECALIBB8IQsgBiALhUIYiiEGIAEgBiAcfHwhASAQIAGFQhCKIRAgCyAQfCELIAYgC4VCP4ohBiACIAcgGnx8IQIgDSAChUIgiiENIAwgDXwhDCAHIAyFQhiKIQcgAiAHIB98fCECIA0gAoVCEIohDSAMIA18IQwgByAMhUI/iiEHIAMgCCAUfHwhAyAOIAOFQiCKIQ4gCSAOfCEJIAggCYVCGIohCCADIAggHXx8IQMgDiADhUIQiiEOIAkgDnwhCSAIIAmFQj+KIQggBCAFIB58fCEEIA8gBIVCIIohDyAKIA98IQogBSAKhUIYiiEFIAQgBSARfHwhBCAPIASFQhCKIQ8gCiAPfCEKIAUgCoVCP4ohBSABIAUgEXx8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBJ8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiATfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgFHx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBV8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAWfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggF3x8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBh8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiAZfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgGnx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBt8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByAcfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHXx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIB58fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAffHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgIHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgASAFIB98fCEBIA0gAYVCIIohDSAJIA18IQkgBSAJhUIYiiEFIAEgBSAbfHwhASANIAGFQhCKIQ0gCSANfCEJIAUgCYVCP4ohBSACIAYgFXx8IQIgDiAChUIgiiEOIAogDnwhCiAGIAqFQhiKIQYgAiAGIBl8fCECIA4gAoVCEIohDiAKIA58IQogBiAKhUI/iiEGIAMgByAafHwhAyAPIAOFQiCKIQ8gCyAPfCELIAcgC4VCGIohByADIAcgIHx8IQMgDyADhUIQiiEPIAsgD3whCyAHIAuFQj+KIQcgBCAIIB58fCEEIBAgBIVCIIohECAMIBB8IQwgCCAMhUIYiiEIIAQgCCAXfHwhBCAQIASFQhCKIRAgDCAQfCEMIAggDIVCP4ohCCABIAYgEnx8IQEgECABhUIgiiEQIAsgEHwhCyAGIAuFQhiKIQYgASAGIB18fCEBIBAgAYVCEIohECALIBB8IQsgBiALhUI/iiEGIAIgByARfHwhAiANIAKFQiCKIQ0gDCANfCEMIAcgDIVCGIohByACIAcgE3x8IQIgDSAChUIQiiENIAwgDXwhDCAHIAyFQj+KIQcgAyAIIBx8fCEDIA4gA4VCIIohDiAJIA58IQkgCCAJhUIYiiEIIAMgCCAYfHwhAyAOIAOFQhCKIQ4gCSAOfCEJIAggCYVCP4ohCCAEIAUgFnx8IQQgDyAEhUIgiiEPIAogD3whCiAFIAqFQhiKIQUgBCAFIBR8fCEEIA8gBIVCEIohDyAKIA98IQogBSAKhUI/iiEFICEgISkDACABIAmFhTcDACAiICIpAwAgAiAKhYU3AwAgIyAjKQMAIAMgC4WFNwMAICQgJCkDACAEIAyFhTcDACAlICUpAwAgBSANhYU3AwAgJiAmKQMAIAYgDoWFNwMAICcgJykDACAHIA+FhTcDACAoICgpAwAgCCAQhYU3AwAL"),n=null,i={buffer:r,memory:null,exports:null,realloc:s,onload:o};return o(function(){}),i;function s(a){i.exports.memory.grow(Math.ceil(Math.abs(a-i.memory.length)/65536)),i.memory=new Uint8Array(i.exports.memory.buffer)}function o(a){if(i.exports)return a();if(n){n.then(a.bind(null,null)).catch(a);return}try{if(t&&t.async)throw new Error("async");u({instance:new WebAssembly.Instance(new WebAssembly.Module(r),e)})}catch{n=WebAssembly.instantiate(r,e).then(u)}o(a)}function u(a){i.exports=a.instance.exports,i.memory=i.exports.memory&&i.exports.memory.buffer&&new Uint8Array(i.exports.memory.buffer)}}function TK(t){return typeof atob=="function"?new Uint8Array(atob(t).split("").map(_K)):new(io()).Buffer(t,"base64")}function _K(t){return t.charCodeAt(0)}});var sO=D((Mye,Qi)=>{h();var zi=$A(),xt=X6()(),Bs=64,Hp=[];Qi.exports=Un;var Z6=Qi.exports.BYTES_MIN=16,eO=Qi.exports.BYTES_MAX=64,Rye=Qi.exports.BYTES=32,tO=Qi.exports.KEYBYTES_MIN=16,rO=Qi.exports.KEYBYTES_MAX=64,Bye=Qi.exports.KEYBYTES=32,nO=Qi.exports.SALTBYTES=16,iO=Qi.exports.PERSONALBYTES=16;function Un(t,e,r,n,i){if(!(this instanceof Un))return new Un(t,e,r,n,i);if(!(xt&&xt.exports))throw new Error("WASM not loaded. Wait for Blake2b.ready(cb)");t||(t=32),i!==!0&&(zi(t>=Z6,"digestLength must be at least "+Z6+", was given "+t),zi(t<=eO,"digestLength must be at most "+eO+", was given "+t),e!=null&&zi(e.length>=tO,"key must be at least "+tO+", was given "+e.length),e!=null&&zi(e.length<=rO,"key must be at least "+rO+", was given "+e.length),r!=null&&zi(r.length===nO,"salt must be exactly "+nO+", was given "+r.length),n!=null&&zi(n.length===iO,"personal must be exactly "+iO+", was given "+n.length)),Hp.length||(Hp.push(Bs),Bs+=216),this.digestLength=t,this.finalized=!1,this.pointer=Hp.pop(),xt.memory.fill(0,0,64),xt.memory[0]=this.digestLength,xt.memory[1]=e?e.length:0,xt.memory[2]=1,xt.memory[3]=1,r&&xt.memory.set(r,32),n&&xt.memory.set(n,48),this.pointer+216>xt.memory.length&&xt.realloc(this.pointer+216),xt.exports.blake2b_init(this.pointer,this.digestLength),e&&(this.update(e),xt.memory.fill(0,Bs,Bs+e.length),xt.memory[this.pointer+200]=128)}Un.prototype.update=function(t){return zi(this.finalized===!1,"Hash instance finalized"),zi(t,"input must be TypedArray or Buffer"),Bs+t.length>xt.memory.length&&xt.realloc(Bs+t.length),xt.memory.set(t,Bs),xt.exports.blake2b_update(this.pointer,Bs,Bs+t.length),this};Un.prototype.digest=function(t){if(zi(this.finalized===!1,"Hash instance finalized"),this.finalized=!0,Hp.push(this.pointer),xt.exports.blake2b_final(this.pointer),!t||t==="binary")return xt.memory.slice(this.pointer+128,this.pointer+128+this.digestLength);if(t==="hex")return NK(xt.memory,this.pointer+128,this.digestLength);zi(t.length>=this.digestLength,"input must be TypedArray or Buffer");for(var e=0;e{h();var Eo=$A(),jf=sO();function Gp(t,e,r){var n=t[e]+t[r],i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function oO(t,e,r,n){var i=t[e]+r;r<0&&(i+=4294967296);var s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function dO(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vo(t,e,r,n,i,s){var o=Gf[i],u=Gf[i+1],a=Gf[s],c=Gf[s+1];Gp(Te,t,e),oO(Te,t,o,u);var f=Te[n]^Te[t],d=Te[n+1]^Te[t+1];Te[n]=d,Te[n+1]=f,Gp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=f>>>24^d<<8,Te[e+1]=d>>>24^f<<8,Gp(Te,t,e),oO(Te,t,a,c),f=Te[n]^Te[t],d=Te[n+1]^Te[t+1],Te[n]=f>>>16^d<<16,Te[n+1]=d>>>16^f<<16,Gp(Te,r,n),f=Te[e]^Te[r],d=Te[e+1]^Te[r+1],Te[e]=d>>>31^f<<1,Te[e+1]=f>>>31^d<<1}var gO=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),OK=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Pr=new Uint8Array(OK.map(function(t){return t*2})),Te=new Uint32Array(32),Gf=new Uint32Array(32);function pO(t,e){var r=0;for(r=0;r<16;r++)Te[r]=t.h[r],Te[r+16]=gO[r];for(Te[24]=Te[24]^t.t,Te[25]=Te[25]^t.t/4294967296,e&&(Te[28]=~Te[28],Te[29]=~Te[29]),r=0;r<32;r++)Gf[r]=dO(t.b,4*r);for(r=0;r<12;r++)vo(0,8,16,24,Pr[r*16+0],Pr[r*16+1]),vo(2,10,18,26,Pr[r*16+2],Pr[r*16+3]),vo(4,12,20,28,Pr[r*16+4],Pr[r*16+5]),vo(6,14,22,30,Pr[r*16+6],Pr[r*16+7]),vo(0,10,20,30,Pr[r*16+8],Pr[r*16+9]),vo(2,12,22,24,Pr[r*16+10],Pr[r*16+11]),vo(4,14,16,26,Pr[r*16+12],Pr[r*16+13]),vo(6,8,18,28,Pr[r*16+14],Pr[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Te[r]^Te[r+16]}var Ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function hc(t,e,r,n){Ao.fill(0),this.b=new Uint8Array(128),this.h=new Uint32Array(16),this.t=0,this.c=0,this.outlen=t,Ao[0]=t,e&&(Ao[1]=e.length),Ao[2]=1,Ao[3]=1,r&&Ao.set(r,32),n&&Ao.set(n,48);for(var i=0;i<16;i++)this.h[i]=gO[i]^dO(Ao,i*4);e&&(mO(this,e),this.c=128)}hc.prototype.update=function(t){return Eo(t!=null,"input must be Uint8Array or Buffer"),mO(this,t),this};hc.prototype.digest=function(t){var e=!t||t==="binary"||t==="hex"?new Uint8Array(this.outlen):t;return Eo(e.length>=this.outlen,"out must have at least outlen bytes of space"),DK(this,e),t==="hex"?PK(e):e};hc.prototype.final=hc.prototype.digest;hc.ready=function(t){jf.ready(function(){t()})};function mO(t,e){for(var r=0;r>2]>>8*(r&3);return e}function PK(t){for(var e="",r=0;r=aO,"outlen must be at least "+aO+", was given "+e),Eo(e<=uO,"outlen must be at most "+uO+", was given "+e),r!=null&&Eo(r.length>=cO,"key must be at least "+cO+", was given "+r.length),r!=null&&Eo(r.length<=lO,"key must be at most "+lO+", was given "+r.length),n!=null&&Eo(n.length===fO,"salt must be exactly "+fO+", was given "+n.length),i!=null&&Eo(i.length===hO,"personal must be exactly "+hO+", was given "+i.length)),new yO(e,r,n,i)};Jr.exports.ready=function(t){jf.ready(function(){t()})};Jr.exports.WASM_SUPPORTED=jf.SUPPORTED;Jr.exports.WASM_LOADED=!1;var aO=Jr.exports.BYTES_MIN=16,uO=Jr.exports.BYTES_MAX=64,Fye=Jr.exports.BYTES=32,cO=Jr.exports.KEYBYTES_MIN=16,lO=Jr.exports.KEYBYTES_MAX=64,Uye=Jr.exports.KEYBYTES=32,fO=Jr.exports.SALTBYTES=16,hO=Jr.exports.PERSONALBYTES=16;jf.ready(function(t){t||(Jr.exports.WASM_LOADED=!0,yO=jf)})});var wO=D(jp=>{"use strict";h();Object.defineProperty(jp,"__esModule",{value:!0});jp.Code=void 0;var BK=JA(),MK=32,XA=class t{constructor(e){this.hex=e}static fromBuffer(e){return new t(e.toString("hex"))}static fromHex(e){return new t(e)}toString(){return this.hex}valueOf(){return p.Buffer.from(this.hex,"hex")}computeHash(){let e=BK(MK).update(this.valueOf()).digest();return p.Buffer.from(e)}};jp.Code=XA});var ZA=D(zp=>{"use strict";h();Object.defineProperty(zp,"__esModule",{value:!0});zp.CodeMetadata=void 0;var dc=class t{constructor(e=!0,r=!1,n=!1,i=!1){this.upgradeable=e,this.readable=r,this.payable=n,this.payableBySc=i}static fromBytes(e){return t.fromBuffer(p.Buffer.from(e))}static fromBuffer(e){if(e.length{"use strict";h();var LK=Ki&&Ki.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FK=Ki&&Ki.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),UK=Ki&&Ki.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LK(e,t,r);return FK(e,t),e};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.ContractFunction=void 0;var qK=UK(Ie()),eE=class t{constructor(e){if(this.name=e,e==null)throw new qK.ErrInvalidFunctionName}static none(){return new t("untitled")}toString(){return this.name}valueOf(){return this.name}};Ki.ContractFunction=eE});var nE=D(Qp=>{"use strict";h();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.Compatibility=void 0;var VK=Ve(),rE=class{static guardAddressIsSetAndNonZero(e,r,n){!e||e.bech32()==""?console.warn(`${r}: address should be set; ${n}. In the future, this will throw an exception instead of emitting a WARN.`):e.bech32()==VK.Address.Zero().bech32()&&console.warn(`${r}: address should not be the 'zero' address (also known as the 'contracts deployment address'); ${n}. In the future, this will throw an exception instead of emitting a WARN.`)}};Qp.Compatibility=rE});var Ms=D(Kp=>{"use strict";h();Object.defineProperty(Kp,"__esModule",{value:!0});Kp.TransactionPayload=void 0;var iE=class t{constructor(e){this.data=p.Buffer.from(e||[])}static fromEncoded(e){if(!e)return new t("");let r=p.Buffer.from(e,"base64").toString();return new t(r)}isEmpty(){return this.data.length==0}encoded(){return this.data.toString("base64")}valueOf(){return this.data}toString(){return this.data.toString()}getEncodedArguments(){return this.toString().split("@")}getRawArguments(){return this.getEncodedArguments().map(e=>p.Buffer.from(e,"hex"))}length(){return p.Buffer.from(this.data).length}};Kp.TransactionPayload=iE});var gc=D(Wp=>{"use strict";h();Object.defineProperty(Wp,"__esModule",{value:!0});Wp.TransactionBuilder=void 0;var kK=hr(),HK=Xr(),GK=Ms(),sE=class{constructor(e){this.config=e.config,this.sender=e.sender,this.receiver=e.receiver,this.dataParts=e.dataParts,this.providedGasLimit=e.gasLimit,this.addDataMovementGas=e.addDataMovementGas,this.amount=e.amount}computeGasLimit(e){return this.addDataMovementGas?this.config.minGasLimit+this.config.gasLimitPerByte*BigInt(e.length())+this.providedGasLimit:this.providedGasLimit}buildTransactionPayload(){let e=this.dataParts.join(kK.ARGUMENTS_SEPARATOR);return new GK.TransactionPayload(e)}build(){let e=this.buildTransactionPayload(),r=this.computeGasLimit(e);return new HK.Transaction({sender:this.sender.bech32(),receiver:this.receiver.bech32(),gasLimit:r,value:this.amount||0n,data:e.valueOf(),chainID:this.config.chainID})}};Wp.TransactionBuilder=sE});var vO=D($p=>{"use strict";h();Object.defineProperty($p,"__esModule",{value:!0});$p.DelegationTransactionsFactory=void 0;var jK=Ve(),zK=hr(),QK=Ie(),fn=qn(),Zr=gc(),oE=class{constructor(e){this.config=e.config,this.argSerializer=new fn.ArgSerializer}createTransactionForNewDelegationContract(e){let r=["createNewDelegationContract",...this.argSerializer.valuesToStrings([new fn.BigUIntValue(e.totalDelegationCap),new fn.BigUIntValue(e.serviceFee)])],n=this.config.gasLimitCreateDelegationContract+this.config.additionalGasLimitForDelegationOperations;return new Zr.TransactionBuilder({config:this.config,sender:e.sender,receiver:jK.Address.fromBech32(zK.DELEGATION_MANAGER_SC_ADDRESS),dataParts:r,gasLimit:n,addDataMovementGas:!0,amount:e.amount}).build()}createTransactionForAddingNodes(e){if(e.publicKeys.length!==e.signedMessages.length)throw new QK.Err("The number of public keys should match the number of signed messages");let r=e.signedMessages.map(o=>new fn.BytesValue(p.Buffer.from(o))),n=this.argSerializer.valuesToStrings(r),i=e.publicKeys.length,s=["addNodes"];for(let o=0;o{h();var AO=(rr(),_e(fr)),EO=bO.exports;(function(){"use strict";function t(c){return c<10?"0"+c:c}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,i,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},o;function u(c){return r.lastIndex=0,r.test(c)?'"'+c.replace(r,function(f){var d=s[f];return typeof d=="string"?d:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+c+'"'}function a(c,f){var d,w,A,T,x=n,B,V=f[c],U=V!=null&&(V instanceof AO||AO.isBigNumber(V));switch(V&&typeof V=="object"&&typeof V.toJSON=="function"&&(V=V.toJSON(c)),typeof o=="function"&&(V=o.call(f,c,V)),typeof V){case"string":return U?V:u(V);case"number":return isFinite(V)?String(V):"null";case"boolean":case"null":case"bigint":return String(V);case"object":if(!V)return"null";if(n+=i,B=[],Object.prototype.toString.apply(V)==="[object Array]"){for(T=V.length,d=0;d{h();var Xp=null,PK=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,RK=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,BK=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` -`,r:"\r",t:" "},s,o=function(x){throw{name:"SyntaxError",message:x,at:r,text:s}},u=function(x){return x&&x!==n&&o("Expected '"+x+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},a=function(){var x,R="";for(n==="-"&&(R="-",u("-"));n>="0"&&n<="9";)R+=n,u();if(n===".")for(R+=".";u()&&n>="0"&&n<="9";)R+=n;if(n==="e"||n==="E")for(R+=n,u(),(n==="-"||n==="+")&&(R+=n,u());n>="0"&&n<="9";)R+=n,u();if(x=+R,!isFinite(x))o("Bad number");else return Xp==null&&(Xp=(rr(),_e(fr))),R.length>15?e.storeAsString?R:e.useNativeBigInt?BigInt(R):new Xp(R):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(x):new Xp(x):x},c=function(){var x,R,V="",U;if(n==='"')for(var Q=r;u();){if(n==='"')return r-1>Q&&(V+=s.substring(Q,r-1)),u(),V;if(n==="\\"){if(r-1>Q&&(V+=s.substring(Q,r-1)),u(),n==="u"){for(U=0,R=0;R<4&&(x=parseInt(u(),16),!!isFinite(x));R+=1)U=U*16+x;V+=String.fromCharCode(U)}else if(typeof i[n]=="string")V+=i[n];else break;Q=r}}o("Bad string")},f=function(){for(;n&&n<=" ";)u()},d=function(){switch(n){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}o("Unexpected '"+n+"'")},w,A=function(){var x=[];if(n==="["){if(u("["),f(),n==="]")return u("]"),x;for(;n;){if(x.push(w()),f(),n==="]")return u("]"),x;u(","),f()}}o("Bad array")},T=function(){var x,R=Object.create(null);if(n==="{"){if(u("{"),f(),n==="}")return u("}"),R;for(;n;){if(x=c(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(R,x)&&o('Duplicate key "'+x+'"'),PK.test(x)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():R[x]=w():RK.test(x)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():R[x]=w():R[x]=w(),f(),n==="}")return u("}"),R;u(","),f()}}o("Bad object")};return w=function(){switch(f(),n){case"{":return T();case"[":return A();case'"':return c();case"-":return a();default:return n>="0"&&n<="9"?a():d()}},function(x,R){var V;return s=x+"",r=0,n=" ",V=w(),f(),n&&o("Syntax error"),typeof R=="function"?function U(Q,L){var k,H,q=Q[L];return q&&typeof q=="object"&&Object.keys(q).forEach(function(v){H=U(q,v),H!==void 0?q[v]=H:delete q[v]}),R.call(Q,L,q)}({"":V},""):V}};TO.exports=BK});var oE=B((qye,Zp)=>{h();var CO=IO().stringify,NO=_O();Zp.exports=function(t){return{parse:NO(t),stringify:CO}};Zp.exports.parse=NO();Zp.exports.stringify=CO});var OO=B(pc=>{"use strict";h();var MK=pc&&pc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pc,"__esModule",{value:!0});pc.RelayedTransactionsFactory=void 0;var LK=MK((rr(),_e(fr))),e0=Ve(),t0=Ie(),zf=qn(),xO=Xr(),FK=oE(),aE=class{constructor(e){this.config=e.config}createRelayedV1Transaction(e){if(!e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let r=this.prepareInnerTransactionForRelayedV1(e.innerTransaction),n=`relayedTx@${p.Buffer.from(r).toString("hex")}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=this.config.minGasLimit+i+e.innerTransaction.gasLimit;return new xO.Transaction({chainID:this.config.chainID,sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,gasLimit:s,data:p.Buffer.from(n)})}createRelayedV2Transaction(e){if(e.innerTransaction.gasLimit)throw new t0.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction");if(!e.innerTransaction.signature.length)throw new t0.ErrInvalidInnerTransaction("The inner transaction is not signed");let{argumentsString:r}=new zf.ArgSerializer().valuesToString([new zf.AddressValue(e0.Address.fromBech32(e.innerTransaction.receiver)),new zf.U64Value(new LK.default(e.innerTransaction.nonce.toString())),new zf.BytesValue(p.Buffer.from(e.innerTransaction.data)),new zf.BytesValue(p.Buffer.from(e.innerTransaction.signature))]),n=`relayedTxV2@${r}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=e.innerTransactionGasLimit+this.config.minGasLimit+i;return new xO.Transaction({sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,value:0n,gasLimit:s,chainID:this.config.chainID,data:p.Buffer.from(n),version:e.innerTransaction.version,options:e.innerTransaction.options})}prepareInnerTransactionForRelayedV1(e){let r={nonce:e.nonce,sender:e0.Address.fromBech32(e.sender).pubkey().toString("base64"),receiver:e0.Address.fromBech32(e.receiver).pubkey().toString("base64"),value:e.value,gasPrice:e.gasPrice,gasLimit:e.gasLimit,data:p.Buffer.from(e.data).toString("base64"),signature:p.Buffer.from(e.signature).toString("base64"),chainID:p.Buffer.from(e.chainID).toString("base64"),version:e.version,options:e.options.valueOf()==0?void 0:e.options,guardian:e.guardian?e0.Address.fromBech32(e.guardian).pubkey().toString("base64"):void 0,guardianSignature:e.guardianSignature.length?p.Buffer.from(e.guardianSignature).toString("base64"):void 0,sndUserName:e.senderUsername?p.Buffer.from(e.senderUsername).toString("base64"):void 0,rcvUserName:e.receiverUsername?p.Buffer.from(e.receiverUsername).toString("base64"):void 0};return FK.stringify(r)}};pc.RelayedTransactionsFactory=aE});var DO=B(r0=>{"use strict";h();Object.defineProperty(r0,"__esModule",{value:!0});r0.ArgumentErrorContext=void 0;var UK=Ie(),uE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new UK.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) -Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};r0.ArgumentErrorContext=uE});var n0=B(qa=>{"use strict";h();var qK=qa&&qa.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qa,"__esModule",{value:!0});qa.NativeSerializer=void 0;var VK=qK((rr(),_e(fr))),kK=Ve(),cE=Ie(),HK=Ru(),GK=DO(),ye=dr(),jK;(function(t){function e(L,k){L=L||[],r(L,k),n(k)&&(L=i(L,k));let H=k.input,q=[];for(let v=0;v0&&k[0].type.getCardinality().isComposite()&&(q=1/0,v=!0);for(let C of k){if(C.type.getCardinality().isSingular())break;H-=1}return{min:H,max:q,variadic:v}}t.getArgumentsCardinality=s;function o(L,k,H){if(L&&L.belongsToTypesystem)return L;if(k instanceof ye.OptionType)return u(L,k,H);if(k instanceof ye.OptionalType)return a(L,k,H);if(k instanceof ye.VariadicType)return c(L,k,H);if(k instanceof ye.CompositeType)return d(L,k,H);if(k instanceof ye.TupleType)return w(L,k,H);if(k instanceof ye.StructType)return A(L,k,H);if(k instanceof ye.ListType)return f(L,k,H);if(k instanceof ye.PrimitiveType)return T(L,k,H);if(k instanceof ye.EnumType)return x(L,k,H);H.throwError(`convertToTypedValue: unhandled type ${k}`)}function u(L,k,H){if(L==null)return ye.OptionValue.newMissing();let q=o(L,k.getFirstTypeParameter(),H);return ye.OptionValue.newProvided(q)}function a(L,k,H){if(L==null)return new ye.OptionalValue(k);let q=o(L,k.getFirstTypeParameter(),H);return new ye.OptionalValue(k,q)}function c(L,k,H){if(k.isCounted)throw new cE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');L==null&&(L=[]),L.map===void 0&&H.convertError(L,"Variadic");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.VariadicValue(k,q)}function f(L,k,H){L.map===void 0&&H.convertError(L,"List");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.List(k,q)}function d(L,k,H){let q=[],v=k.getTypeParameters();H.guardSameLength(L,v);for(let C=0;C{"use strict";h();Object.defineProperty(i0,"__esModule",{value:!0});i0.TokenTransfersDataBuilder=void 0;var zK=fc(),pi=dr(),QK=Ca(),lE=class{constructor(){this.tokenComputer=new QK.TokenComputer,this.argsSerializer=new zK.ArgSerializer}buildDataPartsForESDTTransfer(e){return["ESDTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(e.token.identifier),new pi.BigUIntValue(e.amount)])]}buildDataPartsForSingleESDTNFTTransfer(e,r){let n=e.token,i=this.tokenComputer.extractIdentifierFromExtendedIdentifier(n.identifier);return["ESDTNFTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(i),new pi.BigUIntValue(n.nonce),new pi.BigUIntValue(e.amount),new pi.AddressValue(r)])]}buildDataPartsForMultiESDTNFTTransfer(e,r){let n=[new pi.AddressValue(e),new pi.U32Value(r.length)];for(let s of r){let o=this.tokenComputer.extractIdentifierFromExtendedIdentifier(s.token.identifier);n.push(new pi.TokenIdentifierValue(o),new pi.BigUIntValue(s.token.nonce),new pi.BigUIntValue(s.amount))}return["MultiESDTNFTTransfer",...this.argsSerializer.valuesToStrings(n)]}};i0.TokenTransfersDataBuilder=lE});var dE=B(a0=>{"use strict";h();Object.defineProperty(a0,"__esModule",{value:!0});a0.SmartContractTransactionsFactory=void 0;var PO=Ve(),RO=hr(),BO=Ie(),KK=oo(),s0=qn(),WK=n0(),$K=Ca(),o0=Ru(),YK=fE(),Qf=gc(),hE=class{constructor(e){this.config=e.config,this.abi=e.abi,this.tokenComputer=new $K.TokenComputer,this.dataArgsBuilder=new YK.TokenTransfersDataBuilder}createTransactionForDeploy(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=[o0.byteArrayToHex(e.bytecode),o0.byteArrayToHex(RO.VM_TYPE_WASM_VM),a.toString()],f=this.abi?.constructorDefinition,d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:PO.Address.fromBech32(RO.CONTRACT_DEPLOY_ADDRESS),dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}createTransactionForExecute(e){let r=e.arguments||[],n=e.tokenTransfers||[],i=e.nativeTransferAmount??0n,s=n.length;if(i&&s)throw new BO.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)");let o=e.contract,u=[];if(s===1){let f=n[0];this.tokenComputer.isFungible(f.token)?u=this.dataArgsBuilder.buildDataPartsForESDTTransfer(f):(u=this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(f,o),o=e.sender)}else s>1&&(u=this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(o,n),o=e.sender);u.push(u.length?o0.utf8ToHex(e.function):e.function);let a=this.abi?.getEndpoint(e.function),c=this.argsToDataParts(r,a);return u.push(...c),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:o,dataParts:u,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:i}).build()}createTransactionForUpgrade(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new s0.CodeMetadata(n,i,s,o),c=["upgradeContract",o0.byteArrayToHex(e.bytecode),a.toString()],f=this.getEndpointForUpgrade(),d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}getEndpointForUpgrade(){if(this.abi)try{return this.abi.getEndpoint("upgrade")}catch{return KK.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."),this.abi.constructorDefinition}}createTransactionForClaimingDeveloperRewards(e){let r=["ClaimDeveloperRewards"];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitClaimDeveloperRewards,addDataMovementGas:!1}).build()}createTransactionForChangingOwnerAddress(e){let r=["ChangeOwnerAddress",PO.Address.fromBech32(e.newOwner.bech32()).toHex()];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitChangeOwnerAddress,addDataMovementGas:!1}).build()}argsToDataParts(e,r){if(r){let n=WK.NativeSerializer.nativeToTypedValues(e,r);return new s0.ArgSerializer().valuesToStrings(n)}if(this.areArgsOfTypedValue(e))return new s0.ArgSerializer().valuesToStrings(e);throw new BO.Err("Can't convert args to TypedValues")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}};a0.SmartContractTransactionsFactory=hE});var MO=B(u0=>{"use strict";h();Object.defineProperty(u0,"__esModule",{value:!0});u0.TokenManagementTransactionsFactory=void 0;var Wi=Ve(),$i=hr(),JK=oo(),Z=qn(),Yt=gc(),gE=class{constructor(e){this.config=e.config,this.argSerializer=new Z.ArgSerializer,this.trueAsString="true",this.falseAsString="false"}createTransactionForIssuingFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.initialSupply),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issue",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueSemiFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueNonFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["registerMetaESDT",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringAndSettingRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue(e.tokenType),new Z.BigUIntValue(e.numDecimals)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForSettingBurnRoleGlobally(e){let r=["setBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForUnsettingBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleLocalMint&&r.push(new Z.StringValue("ESDTRoleLocalMint")),e.addRoleLocalBurn&&r.push(new Z.StringValue("ESDTRoleLocalBurn")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnSemiFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTAddQuantity&&r.push(new Z.StringValue("ESDTRoleNFTAddQuantity")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnMetaESDT(e){return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(e)}createTransactionForSettingSpecialRoleOnNonFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTUpdateAttributes&&r.push(new Z.StringValue("ESDTRoleNFTUpdateAttributes")),e.addRoleNFTAddURI&&r.push(new Z.StringValue("ESDTRoleNFTAddURI")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForCreatingNFT(e){let r=["ESDTNFTCreate",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.initialQuantity),new Z.StringValue(e.name),new Z.BigUIntValue(e.royalties),new Z.StringValue(e.hash),new Z.BytesValue(p.Buffer.from(e.attributes)),...e.uris.map(s=>new Z.StringValue(s))])],n=e.name+e.hash+e.attributes+e.uris.join(""),i=this.config.gasLimitStorePerByte+BigInt(n.length);return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftCreate+i,addDataMovementGas:!0}).build()}createTransactionForPausing(e){let r=["pause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForUnpausing(e){let r=["unPause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForFreezing(e){let r=["freeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForUnfreezing(e){let r=["UnFreeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForWiping(e){let r=["wipe",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitWiping,addDataMovementGas:!0}).build()}createTransactionForLocalMint(e){let r=["ESDTLocalMint",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToMint)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalMint,addDataMovementGas:!0}).build()}createTransactionForLocalBurning(e){let r=["ESDTLocalBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalBurn,addDataMovementGas:!0}).build()}createTransactionForUpdatingAttributes(e){let r=["ESDTNFTUpdateAttributes",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BytesValue(p.Buffer.from(e.attributes))])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftUpdateAttributes,addDataMovementGas:!0}).build()}createTransactionForAddingQuantity(e){let r=["ESDTNFTAddQuantity",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToAdd)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftAddQuantity,addDataMovementGas:!0}).build()}createTransactionForBurningQuantity(e){let r=["ESDTNFTBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftBurn,addDataMovementGas:!0}).build()}notifyAboutUnsettingBurnRoleGlobally(){JK.Logger.info(` +`+x+"}":"{"+B.join(",")+"}",n=x,A}}typeof EO.stringify!="function"&&(EO.stringify=function(c,f,d){var w;if(n="",i="",typeof d=="number")for(w=0;w{h();var Yp=null,KK=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,WK=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,$K=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var r,n,i={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},s,o=function(x){throw{name:"SyntaxError",message:x,at:r,text:s}},u=function(x){return x&&x!==n&&o("Expected '"+x+"' instead of '"+n+"'"),n=s.charAt(r),r+=1,n},a=function(){var x,B="";for(n==="-"&&(B="-",u("-"));n>="0"&&n<="9";)B+=n,u();if(n===".")for(B+=".";u()&&n>="0"&&n<="9";)B+=n;if(n==="e"||n==="E")for(B+=n,u(),(n==="-"||n==="+")&&(B+=n,u());n>="0"&&n<="9";)B+=n,u();if(x=+B,!isFinite(x))o("Bad number");else return Yp==null&&(Yp=(rr(),_e(fr))),B.length>15?e.storeAsString?B:e.useNativeBigInt?BigInt(B):new Yp(B):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(x):new Yp(x):x},c=function(){var x,B,V="",U;if(n==='"')for(var Q=r;u();){if(n==='"')return r-1>Q&&(V+=s.substring(Q,r-1)),u(),V;if(n==="\\"){if(r-1>Q&&(V+=s.substring(Q,r-1)),u(),n==="u"){for(U=0,B=0;B<4&&(x=parseInt(u(),16),!!isFinite(x));B+=1)U=U*16+x;V+=String.fromCharCode(U)}else if(typeof i[n]=="string")V+=i[n];else break;Q=r}}o("Bad string")},f=function(){for(;n&&n<=" ";)u()},d=function(){switch(n){case"t":return u("t"),u("r"),u("u"),u("e"),!0;case"f":return u("f"),u("a"),u("l"),u("s"),u("e"),!1;case"n":return u("n"),u("u"),u("l"),u("l"),null}o("Unexpected '"+n+"'")},w,A=function(){var x=[];if(n==="["){if(u("["),f(),n==="]")return u("]"),x;for(;n;){if(x.push(w()),f(),n==="]")return u("]"),x;u(","),f()}}o("Bad array")},T=function(){var x,B=Object.create(null);if(n==="{"){if(u("{"),f(),n==="}")return u("}"),B;for(;n;){if(x=c(),f(),u(":"),e.strict===!0&&Object.hasOwnProperty.call(B,x)&&o('Duplicate key "'+x+'"'),KK.test(x)===!0?e.protoAction==="error"?o("Object contains forbidden prototype property"):e.protoAction==="ignore"?w():B[x]=w():WK.test(x)===!0?e.constructorAction==="error"?o("Object contains forbidden constructor property"):e.constructorAction==="ignore"?w():B[x]=w():B[x]=w(),f(),n==="}")return u("}"),B;u(","),f()}}o("Bad object")};return w=function(){switch(f(),n){case"{":return T();case"[":return A();case'"':return c();case"-":return a();default:return n>="0"&&n<="9"?a():d()}},function(x,B){var V;return s=x+"",r=0,n=" ",V=w(),f(),n&&o("Syntax error"),typeof B=="function"?function U(Q,L){var k,H,q=Q[L];return q&&typeof q=="object"&&Object.keys(q).forEach(function(v){H=U(q,v),H!==void 0?q[v]=H:delete q[v]}),B.call(Q,L,q)}({"":V},""):V}};IO.exports=$K});var aE=D((s1e,Jp)=>{h();var _O=SO().stringify,CO=TO();Jp.exports=function(t){return{parse:CO(t),stringify:_O}};Jp.exports.parse=CO();Jp.exports.stringify=_O});var xO=D(pc=>{"use strict";h();var YK=pc&&pc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pc,"__esModule",{value:!0});pc.RelayedTransactionsFactory=void 0;var JK=YK((rr(),_e(fr))),Xp=Ve(),Zp=Ie(),zf=qn(),NO=Xr(),XK=aE(),uE=class{constructor(e){this.config=e.config}createRelayedV1Transaction(e){if(!e.innerTransaction.gasLimit)throw new Zp.ErrInvalidInnerTransaction("The gas limit is not set for the inner transaction");if(!e.innerTransaction.signature.length)throw new Zp.ErrInvalidInnerTransaction("The inner transaction is not signed");let r=this.prepareInnerTransactionForRelayedV1(e.innerTransaction),n=`relayedTx@${p.Buffer.from(r).toString("hex")}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=this.config.minGasLimit+i+e.innerTransaction.gasLimit;return new NO.Transaction({chainID:this.config.chainID,sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,gasLimit:s,data:p.Buffer.from(n)})}createRelayedV2Transaction(e){if(e.innerTransaction.gasLimit)throw new Zp.ErrInvalidInnerTransaction("The gas limit should not be set for the inner transaction");if(!e.innerTransaction.signature.length)throw new Zp.ErrInvalidInnerTransaction("The inner transaction is not signed");let{argumentsString:r}=new zf.ArgSerializer().valuesToString([new zf.AddressValue(Xp.Address.fromBech32(e.innerTransaction.receiver)),new zf.U64Value(new JK.default(e.innerTransaction.nonce.toString())),new zf.BytesValue(p.Buffer.from(e.innerTransaction.data)),new zf.BytesValue(p.Buffer.from(e.innerTransaction.signature))]),n=`relayedTxV2@${r}`,i=this.config.gasLimitPerByte*BigInt(n.length),s=e.innerTransactionGasLimit+this.config.minGasLimit+i;return new NO.Transaction({sender:e.relayerAddress.bech32(),receiver:e.innerTransaction.sender,value:0n,gasLimit:s,chainID:this.config.chainID,data:p.Buffer.from(n),version:e.innerTransaction.version,options:e.innerTransaction.options})}prepareInnerTransactionForRelayedV1(e){let r={nonce:e.nonce,sender:Xp.Address.fromBech32(e.sender).pubkey().toString("base64"),receiver:Xp.Address.fromBech32(e.receiver).pubkey().toString("base64"),value:e.value,gasPrice:e.gasPrice,gasLimit:e.gasLimit,data:p.Buffer.from(e.data).toString("base64"),signature:p.Buffer.from(e.signature).toString("base64"),chainID:p.Buffer.from(e.chainID).toString("base64"),version:e.version,options:e.options.valueOf()==0?void 0:e.options,guardian:e.guardian?Xp.Address.fromBech32(e.guardian).pubkey().toString("base64"):void 0,guardianSignature:e.guardianSignature.length?p.Buffer.from(e.guardianSignature).toString("base64"):void 0,sndUserName:e.senderUsername?p.Buffer.from(e.senderUsername).toString("base64"):void 0,rcvUserName:e.receiverUsername?p.Buffer.from(e.receiverUsername).toString("base64"):void 0};return XK.stringify(r)}};pc.RelayedTransactionsFactory=uE});var OO=D(e0=>{"use strict";h();Object.defineProperty(e0,"__esModule",{value:!0});e0.ArgumentErrorContext=void 0;var ZK=Ie(),cE=class{constructor(e,r,n){this.endpointName=e,this.argumentIndex=r,this.parameterDefinition=n}throwError(e){throw new ZK.ErrInvalidArgument(`Error when converting arguments for endpoint (endpoint name: ${this.endpointName}, argument index: ${this.argumentIndex}, name: ${this.parameterDefinition.name}, type: ${this.parameterDefinition.type}) +Nested error: ${e}`)}convertError(e,r){this.throwError(`Can't convert argument (argument: ${e}, type ${typeof e}), wanted type: ${r})`)}unhandledType(e,r){this.throwError(`Unhandled type (function: ${e}, type: ${r})`)}guardSameLength(e,r){e=e||[],e.length!=r.length&&this.throwError(`Incorrect composite type length: have ${e.length}, expected ${r.length} (argument: ${e})`)}guardHasField(e,r){e=e||{},r in e||this.throwError(`Struct argument does not contain a field named "${r}" (argument: ${JSON.stringify(e)})`)}};e0.ArgumentErrorContext=cE});var t0=D(Ua=>{"use strict";h();var eW=Ua&&Ua.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ua,"__esModule",{value:!0});Ua.NativeSerializer=void 0;var tW=eW((rr(),_e(fr))),rW=Ve(),lE=Ie(),nW=Ru(),iW=OO(),ye=dr(),sW;(function(t){function e(L,k){L=L||[],r(L,k),n(k)&&(L=i(L,k));let H=k.input,q=[];for(let v=0;v0&&k[0].type.getCardinality().isComposite()&&(q=1/0,v=!0);for(let C of k){if(C.type.getCardinality().isSingular())break;H-=1}return{min:H,max:q,variadic:v}}t.getArgumentsCardinality=s;function o(L,k,H){if(L&&L.belongsToTypesystem)return L;if(k instanceof ye.OptionType)return u(L,k,H);if(k instanceof ye.OptionalType)return a(L,k,H);if(k instanceof ye.VariadicType)return c(L,k,H);if(k instanceof ye.CompositeType)return d(L,k,H);if(k instanceof ye.TupleType)return w(L,k,H);if(k instanceof ye.StructType)return A(L,k,H);if(k instanceof ye.ListType)return f(L,k,H);if(k instanceof ye.PrimitiveType)return T(L,k,H);if(k instanceof ye.EnumType)return x(L,k,H);H.throwError(`convertToTypedValue: unhandled type ${k}`)}function u(L,k,H){if(L==null)return ye.OptionValue.newMissing();let q=o(L,k.getFirstTypeParameter(),H);return ye.OptionValue.newProvided(q)}function a(L,k,H){if(L==null)return new ye.OptionalValue(k);let q=o(L,k.getFirstTypeParameter(),H);return new ye.OptionalValue(k,q)}function c(L,k,H){if(k.isCounted)throw new lE.ErrInvalidArgument('Counted variadic arguments must be explicitly typed. E.g. use "VariadicValue.fromItemsCounted()" or "new VariadicValue()"');L==null&&(L=[]),L.map===void 0&&H.convertError(L,"Variadic");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.VariadicValue(k,q)}function f(L,k,H){L.map===void 0&&H.convertError(L,"List");let q=L.map(function(v){return o(v,k.getFirstTypeParameter(),H)});return new ye.List(k,q)}function d(L,k,H){let q=[],v=k.getTypeParameters();H.guardSameLength(L,v);for(let C=0;C{"use strict";h();Object.defineProperty(r0,"__esModule",{value:!0});r0.TokenTransfersDataBuilder=void 0;var oW=fc(),pi=dr(),aW=_a(),fE=class{constructor(){this.tokenComputer=new aW.TokenComputer,this.argsSerializer=new oW.ArgSerializer}buildDataPartsForESDTTransfer(e){return["ESDTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(e.token.identifier),new pi.BigUIntValue(e.amount)])]}buildDataPartsForSingleESDTNFTTransfer(e,r){let n=e.token,i=this.tokenComputer.extractIdentifierFromExtendedIdentifier(n.identifier);return["ESDTNFTTransfer",...this.argsSerializer.valuesToStrings([new pi.TokenIdentifierValue(i),new pi.BigUIntValue(n.nonce),new pi.BigUIntValue(e.amount),new pi.AddressValue(r)])]}buildDataPartsForMultiESDTNFTTransfer(e,r){let n=[new pi.AddressValue(e),new pi.U32Value(r.length)];for(let s of r){let o=this.tokenComputer.extractIdentifierFromExtendedIdentifier(s.token.identifier);n.push(new pi.TokenIdentifierValue(o),new pi.BigUIntValue(s.token.nonce),new pi.BigUIntValue(s.amount))}return["MultiESDTNFTTransfer",...this.argsSerializer.valuesToStrings(n)]}};r0.TokenTransfersDataBuilder=fE});var gE=D(s0=>{"use strict";h();Object.defineProperty(s0,"__esModule",{value:!0});s0.SmartContractTransactionsFactory=void 0;var DO=Ve(),PO=hr(),RO=Ie(),uW=oo(),n0=qn(),cW=t0(),lW=_a(),i0=Ru(),fW=hE(),Qf=gc(),dE=class{constructor(e){this.config=e.config,this.abi=e.abi,this.tokenComputer=new lW.TokenComputer,this.dataArgsBuilder=new fW.TokenTransfersDataBuilder}createTransactionForDeploy(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new n0.CodeMetadata(n,i,s,o),c=[i0.byteArrayToHex(e.bytecode),i0.byteArrayToHex(PO.VM_TYPE_WASM_VM),a.toString()],f=this.abi?.constructorDefinition,d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:DO.Address.fromBech32(PO.CONTRACT_DEPLOY_ADDRESS),dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}createTransactionForExecute(e){let r=e.arguments||[],n=e.tokenTransfers||[],i=e.nativeTransferAmount??0n,s=n.length;if(i&&s)throw new RO.ErrBadUsage("Can't send both native tokens and custom tokens(ESDT/NFT)");let o=e.contract,u=[];if(s===1){let f=n[0];this.tokenComputer.isFungible(f.token)?u=this.dataArgsBuilder.buildDataPartsForESDTTransfer(f):(u=this.dataArgsBuilder.buildDataPartsForSingleESDTNFTTransfer(f,o),o=e.sender)}else s>1&&(u=this.dataArgsBuilder.buildDataPartsForMultiESDTNFTTransfer(o,n),o=e.sender);u.push(u.length?i0.utf8ToHex(e.function):e.function);let a=this.abi?.getEndpoint(e.function),c=this.argsToDataParts(r,a);return u.push(...c),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:o,dataParts:u,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:i}).build()}createTransactionForUpgrade(e){let r=e.nativeTransferAmount??0n,n=e.isUpgradeable??!0,i=e.isReadable??!0,s=e.isPayable??!1,o=e.isPayableBySmartContract??!0,u=e.arguments||[],a=new n0.CodeMetadata(n,i,s,o),c=["upgradeContract",i0.byteArrayToHex(e.bytecode),a.toString()],f=this.getEndpointForUpgrade(),d=this.argsToDataParts(u,f);return c.push(...d),new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:c,gasLimit:e.gasLimit,addDataMovementGas:!1,amount:r}).build()}getEndpointForUpgrade(){if(this.abi)try{return this.abi.getEndpoint("upgrade")}catch{return uW.Logger.warn("In the ABI, cannot find the 'upgrade' endpoint definition. Will use the constructor definition (fallback)."),this.abi.constructorDefinition}}createTransactionForClaimingDeveloperRewards(e){let r=["ClaimDeveloperRewards"];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitClaimDeveloperRewards,addDataMovementGas:!1}).build()}createTransactionForChangingOwnerAddress(e){let r=["ChangeOwnerAddress",DO.Address.fromBech32(e.newOwner.bech32()).toHex()];return new Qf.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.contract,dataParts:r,gasLimit:this.config.gasLimitChangeOwnerAddress,addDataMovementGas:!1}).build()}argsToDataParts(e,r){if(r){let n=cW.NativeSerializer.nativeToTypedValues(e,r);return new n0.ArgSerializer().valuesToStrings(n)}if(this.areArgsOfTypedValue(e))return new n0.ArgSerializer().valuesToStrings(e);throw new RO.Err("Can't convert args to TypedValues")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}};s0.SmartContractTransactionsFactory=dE});var BO=D(o0=>{"use strict";h();Object.defineProperty(o0,"__esModule",{value:!0});o0.TokenManagementTransactionsFactory=void 0;var Wi=Ve(),$i=hr(),hW=oo(),Z=qn(),Yt=gc(),pE=class{constructor(e){this.config=e.config,this.argSerializer=new Z.ArgSerializer,this.trueAsString="true",this.falseAsString="false"}createTransactionForIssuingFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.initialSupply),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issue",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueSemiFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForIssuingNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["issueNonFungible",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=[new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.BigUIntValue(e.numDecimals),new Z.StringValue("canFreeze"),new Z.StringValue(this.boolToString(e.canFreeze)),new Z.StringValue("canWipe"),new Z.StringValue(this.boolToString(e.canWipe)),new Z.StringValue("canPause"),new Z.StringValue(this.boolToString(e.canPause)),new Z.StringValue("canTransferNFTCreateRole"),new Z.StringValue(this.boolToString(e.canTransferNFTCreateRole)),new Z.StringValue("canChangeOwner"),new Z.StringValue(this.boolToString(e.canChangeOwner)),new Z.StringValue("canUpgrade"),new Z.StringValue(this.boolToString(e.canUpgrade)),new Z.StringValue("canAddSpecialRoles"),new Z.StringValue(this.boolToString(e.canAddSpecialRoles))],n=["registerMetaESDT",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForRegisteringAndSettingRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenName),new Z.StringValue(e.tokenTicker),new Z.StringValue(e.tokenType),new Z.BigUIntValue(e.numDecimals)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitIssue,addDataMovementGas:!0,amount:this.config.issueCost}).build()}createTransactionForSettingBurnRoleGlobally(e){let r=["setBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForUnsettingBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:r,gasLimit:this.config.gasLimitToggleBurnRoleGlobally,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleLocalMint&&r.push(new Z.StringValue("ESDTRoleLocalMint")),e.addRoleLocalBurn&&r.push(new Z.StringValue("ESDTRoleLocalBurn")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnSemiFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTAddQuantity&&r.push(new Z.StringValue("ESDTRoleNFTAddQuantity")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForSettingSpecialRoleOnMetaESDT(e){return this.createTransactionForSettingSpecialRoleOnSemiFungibleToken(e)}createTransactionForSettingSpecialRoleOnNonFungibleToken(e){let r=[new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)];e.addRoleNFTCreate&&r.push(new Z.StringValue("ESDTRoleNFTCreate")),e.addRoleNFTBurn&&r.push(new Z.StringValue("ESDTRoleNFTBurn")),e.addRoleNFTUpdateAttributes&&r.push(new Z.StringValue("ESDTRoleNFTUpdateAttributes")),e.addRoleNFTAddURI&&r.push(new Z.StringValue("ESDTRoleNFTAddURI")),e.addRoleESDTTransferRole&&r.push(new Z.StringValue("ESDTTransferRole"));let n=["setSpecialRole",...this.argSerializer.valuesToStrings(r)];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:Wi.Address.fromBech32($i.ESDT_CONTRACT_ADDRESS),dataParts:n,gasLimit:this.config.gasLimitSetSpecialRole,addDataMovementGas:!0}).build()}createTransactionForCreatingNFT(e){let r=["ESDTNFTCreate",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.initialQuantity),new Z.StringValue(e.name),new Z.BigUIntValue(e.royalties),new Z.StringValue(e.hash),new Z.BytesValue(p.Buffer.from(e.attributes)),...e.uris.map(s=>new Z.StringValue(s))])],n=e.name+e.hash+e.attributes+e.uris.join(""),i=this.config.gasLimitStorePerByte+BigInt(n.length);return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftCreate+i,addDataMovementGas:!0}).build()}createTransactionForPausing(e){let r=["pause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForUnpausing(e){let r=["unPause",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitPausing,addDataMovementGas:!0}).build()}createTransactionForFreezing(e){let r=["freeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForUnfreezing(e){let r=["UnFreeze",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitFreezing,addDataMovementGas:!0}).build()}createTransactionForWiping(e){let r=["wipe",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.AddressValue(e.user)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitWiping,addDataMovementGas:!0}).build()}createTransactionForLocalMint(e){let r=["ESDTLocalMint",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToMint)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalMint,addDataMovementGas:!0}).build()}createTransactionForLocalBurning(e){let r=["ESDTLocalBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.supplyToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtLocalBurn,addDataMovementGas:!0}).build()}createTransactionForUpdatingAttributes(e){let r=["ESDTNFTUpdateAttributes",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BytesValue(p.Buffer.from(e.attributes))])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftUpdateAttributes,addDataMovementGas:!0}).build()}createTransactionForAddingQuantity(e){let r=["ESDTNFTAddQuantity",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToAdd)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftAddQuantity,addDataMovementGas:!0}).build()}createTransactionForBurningQuantity(e){let r=["ESDTNFTBurn",...this.argSerializer.valuesToStrings([new Z.StringValue(e.tokenIdentifier),new Z.BigUIntValue(e.tokenNonce),new Z.BigUIntValue(e.quantityToBurn)])];return new Yt.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitEsdtNftBurn,addDataMovementGas:!0}).build()}notifyAboutUnsettingBurnRoleGlobally(){hW.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}boolToString(e){return e?this.trueAsString:this.falseAsString}};u0.TokenManagementTransactionsFactory=gE});var mE=B(c0=>{"use strict";h();Object.defineProperty(c0,"__esModule",{value:!0});c0.TransactionsFactoryConfig=void 0;var XK=hr(),pE=class{constructor(e){this.chainID=e.chainID,this.addressHrp=XK.DEFAULT_HRP,this.minGasLimit=50000n,this.gasLimitPerByte=1500n,this.gasLimitIssue=60000000n,this.gasLimitToggleBurnRoleGlobally=60000000n,this.gasLimitEsdtLocalMint=300000n,this.gasLimitEsdtLocalBurn=300000n,this.gasLimitSetSpecialRole=60000000n,this.gasLimitPausing=60000000n,this.gasLimitFreezing=60000000n,this.gasLimitWiping=60000000n,this.gasLimitEsdtNftCreate=3000000n,this.gasLimitEsdtNftUpdateAttributes=1000000n,this.gasLimitEsdtNftAddQuantity=1000000n,this.gasLimitEsdtNftBurn=1000000n,this.gasLimitStorePerByte=10000n,this.issueCost=50000000000000000n,this.gasLimitStake=5000000n,this.gasLimitUnstake=5000000n,this.gasLimitUnbond=5000000n,this.gasLimitCreateDelegationContract=50000000n,this.gasLimitDelegationOperations=1000000n,this.additionalGasLimitPerValidatorNode=6000000n,this.additionalGasLimitForDelegationOperations=10000000n,this.gasLimitSaveKeyValue=100000n,this.gasLimitPersistPerByte=1000n,this.gasLimitSetGuardian=250000n,this.gasLimitGuardAccount=250000n,this.gasLimitUnguardAccount=250000n,this.gasLimitESDTTransfer=200000n,this.gasLimitESDTNFTTransfer=200000n,this.gasLimitMultiESDTNFTTransfer=200000n,this.gasLimitClaimDeveloperRewards=6000000n,this.gasLimitChangeOwnerAddress=6000000n}};c0.TransactionsFactoryConfig=pE});var UO=B(l0=>{"use strict";h();Object.defineProperty(l0,"__esModule",{value:!0});l0.TransferTransactionsFactory=void 0;var bo=Ie(),en=qn(),ZK=Ca(),Kf=Xr(),yE=Ms(),eW=fE(),LO=gc(),tW=1e5,FO=8e5,wE=class{constructor(e){this.isGasEstimator(e)?this.gasEstimator=e:(this.config=e.config,this.tokenComputer=new ZK.TokenComputer,this.tokenTransfersDataBuilder=new eW.TokenTransfersDataBuilder)}isGasEstimator(e){return typeof e=="object"&&typeof e.forEGLDTransfer=="function"&&typeof e.forESDTTransfer=="function"&&typeof e.forESDTNFTTransfer=="function"&&typeof e.forMultiESDTNFTTransfer=="function"}isGasEstimatorDefined(){return this.gasEstimator!==void 0}ensureMembersAreDefined(){if(this.config===void 0)throw new bo.Err("'config' is not defined");if(this.tokenTransfersDataBuilder===void 0)throw new bo.Err("`dataArgsBuilder is not defined`");if(this.tokenComputer===void 0)throw new bo.Err("`tokenComputer is not defined`")}createTransactionForNativeTokenTransfer(e){this.ensureMembersAreDefined();let r=e.data||new Uint8Array;return new Kf.Transaction({sender:e.sender.bech32(),receiver:e.receiver.bech32(),chainID:this.config.chainID,gasLimit:this.computeGasForMoveBalance(this.config,r),data:r,value:e.nativeAmount})}createTransactionForESDTTokenTransfer(e){this.ensureMembersAreDefined();let r=e.tokenTransfers.length;if(r===0)throw new bo.ErrBadUsage("No token transfer has been provided");if(r===1)return this.createSingleESDTTransferTransaction(e);let n=this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(e.receiver,e.tokenTransfers),i=this.config.gasLimitMultiESDTNFTTransfer*BigInt(r)+BigInt(FO);return new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:n,gasLimit:i,addDataMovementGas:!0}).build()}createEGLDTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.");let r=e.data?.length()||0,n=this.gasEstimator.forEGLDTransfer(r);return new Kf.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||n,data:e.data,chainID:e.chainID})}createESDTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.U64Value(e.tokenTransfer.nonce),new en.BigUIntValue(e.tokenTransfer.valueOf()),new en.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new yE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let r=[new en.AddressValue(e.destination),new en.U16Value(e.tokenTransfers.length)];for(let a of e.tokenTransfers)r.push(en.BytesValue.fromUTF8(a.tokenIdentifier),new en.U64Value(a.nonce),new en.BigUIntValue(a.valueOf()));let{argumentsString:n}=new en.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new yE.TransactionPayload(i),o=s.length()||0,u=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||u,data:s,chainID:e.chainID})}createSingleESDTTransferTransaction(e){this.ensureMembersAreDefined();let r=[],n=e.tokenTransfers[0],i=0n,s=e.receiver;return this.tokenComputer.isFungible(n.token)?(r=this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(n),i=this.config.gasLimitESDTTransfer+BigInt(tW)):(r=this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(n,s),i=this.config.gasLimitESDTNFTTransfer+BigInt(FO),s=e.sender),new LO.TransactionBuilder({config:this.config,sender:e.sender,receiver:s,dataParts:r,gasLimit:i,addDataMovementGas:!0}).build()}computeGasForMoveBalance(e,r){return e.minGasLimit+e.gasLimitPerByte*BigInt(r.length)}};l0.TransferTransactionsFactory=wE});var qO=B(h0=>{"use strict";h();Object.defineProperty(h0,"__esModule",{value:!0});h0.AccountTransactionsFactory=void 0;var rW=Ve(),f0=gc(),vE=class{constructor(e){this.config=e.config}createTransactionForSavingKeyValue(e){let r="SaveKeyValue",n=this.computeDataPartsForSavingKeyValue(e.keyValuePairs),i=[r,...n],s=this.computeExtraGasForSavingKeyValue(e.keyValuePairs);return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:i,gasLimit:s,addDataMovementGas:!0}).build()}computeExtraGasForSavingKeyValue(e){let r=0n;return e.forEach((n,i)=>{r+=this.config.gasLimitPersistPerByte*BigInt(i.length+n.length)+this.config.gasLimitStorePerByte*BigInt(n.length)}),r+this.config.gasLimitSaveKeyValue}computeDataPartsForSavingKeyValue(e){let r=[];return e.forEach((n,i)=>{r.push(p.Buffer.from(i).toString("hex"),p.Buffer.from(n).toString("hex"))}),r}createTransactionForSettingGuardian(e){let r=["SetGuardian",rW.Address.fromBech32(e.guardianAddress.bech32()).toHex(),p.Buffer.from(e.serviceID).toString("hex")];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitSetGuardian,addDataMovementGas:!0}).build()}createTransactionForGuardingAccount(e){let r=["GuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitGuardAccount,addDataMovementGas:!0}).build()}createTransactionForUnguardingAccount(e){let r=["UnGuardAccount"];return new f0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitUnguardAccount,addDataMovementGas:!0}).build()}};h0.AccountTransactionsFactory=vE});var d0=B(hn=>{"use strict";h();var nW=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Va=hn&&hn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&nW(e,t,r)};Object.defineProperty(hn,"__esModule",{value:!0});Va(AO(),hn);Va(OO(),hn);Va(dE(),hn);Va(MO(),hn);Va(mE(),hn);Va(UO(),hn);Va(qO(),hn)});var bE=B(Vn=>{"use strict";h();var iW=Vn&&Vn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),sW=Vn&&Vn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),oW=Vn&&Vn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&iW(e,t,r);return sW(e,t),e},aW=Vn&&Vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.InteractionChecker=void 0;var AE=oW(Ie()),uW=aW((rr(),_e(fr))),EE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new uW.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new AE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new AE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let u=0;u{"use strict";h();Object.defineProperty(g0,"__esModule",{value:!0});g0.Query=void 0;var cW=Ve(),lW=fc(),SE=class{constructor(e){this.caller=e.caller||cW.Address.empty(),this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new lW.ArgSerializer().valuesToStrings(this.args)}};g0.Query=SE});var _E=B(p0=>{"use strict";h();Object.defineProperty(p0,"__esModule",{value:!0});p0.Interaction=void 0;var VO=Ve(),fW=rE(),hW=hr(),IE=Ca(),kO=d0(),dW=bE(),gW=Wf(),TE=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=VO.Address.empty(),this.sender=VO.Address.empty(),this.version=hW.TRANSACTION_VERSION_DEFAULT,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=[]}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){fW.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=new kO.TransactionsFactoryConfig({chainID:this.chainID.valueOf()}),n=new kO.SmartContractTransactionsFactory({config:e}).createTransactionForExecute({sender:this.sender,contract:this.contract.getAddress(),function:this.function.valueOf(),gasLimit:BigInt(this.gasLimit.valueOf()),arguments:this.args,nativeTransferAmount:BigInt(this.value.toString()),tokenTransfers:this.tokenTransfers});return n.chainID=this.chainID.valueOf(),n.nonce=BigInt(this.nonce.valueOf()),n.version=this.version,this.gasPrice&&(n.gasPrice=BigInt(this.gasPrice.valueOf())),n}buildQuery(){return new gW.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withSingleESDTNFTTransfer(e){return this.tokenTransfers=[e].map(r=>new IE.TokenTransfer(r)),this}withMultiESDTNFTTransfer(e){return this.tokenTransfers=e.map(r=>new IE.TokenTransfer(r)),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withVersion(e){return this.version=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new dW.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};p0.Interaction=TE});var CE=B(HO=>{"use strict";h();Object.defineProperty(HO,"__esModule",{value:!0})});var QO=B(yc=>{"use strict";h();Object.defineProperty(yc,"__esModule",{value:!0});yc.bech32m=yc.bech32=void 0;var m0="qpzry9x8gf2tvdw0s3jn54khce6mua7l",jO={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function GO(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=mc(e)^n>>5}e=mc(e);for(let r=0;r=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<a)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=GO(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=mc(c)^w,f+=m0.charAt(w)}for(let d=0;d<6;++d)c=mc(c);c^=e;for(let d=0;d<6;++d){let w=c>>(5-d)*5&31;f+=m0.charAt(w)}return f}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";let a=o.toLowerCase(),c=o.toUpperCase();if(o!==a&&o!==c)return"Mixed-case string "+o;o=a;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),w=o.slice(f+1);if(w.length<6)return"Data too short";let A=GO(d);if(typeof A=="string")return A;let T=[];for(let x=0;x=w.length)&&T.push(V)}return A!==e?"Invalid checksum for "+o:{prefix:d,words:T}}function i(o,u){let a=n(o,u);if(typeof a=="object")return a}function s(o,u){let a=n(o,u);if(typeof a=="object")return a;throw new Error(a)}return{decodeUnsafe:i,decode:s,encode:r,toWords:pW,fromWordsUnsafe:mW,fromWords:yW}}yc.bech32=zO("bech32");yc.bech32m=zO("bech32m")});var WO=B(kn=>{"use strict";h();Object.defineProperty(kn,"__esModule",{value:!0});kn.TokenTransferProperties=kn.TransactionMetadataTransfer=kn.TransactionMetadata=kn.TransactionToDecode=kn.TransactionDecoder=void 0;var KO=QO(),xE=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new ka;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new y0;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new ka;s.transfers||(s.transfers=[]);let o=2;for(let u=0;uo&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),u=new ka;return u.sender=e.sender,u.receiver=o,u.value=s,r.length>4&&(u.functionName=this.hexToString(r[4]),u.functionArgs=r.slice(5)),u.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],u}base64Encode(e){return p.Buffer.from(e).toString("base64")}base64Decode(e){return p.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new ka;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=p.Buffer.from(e,"hex"),n=KO.bech32.toWords(r);return KO.bech32.encode("erd",n)}isAddressValid(e){return p.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return p.Buffer.from(e,"base64").toString("hex")}hexToString(e){return p.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};kn.TransactionDecoder=xE;var y0=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};kn.TransactionToDecode=y0;var ka=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};kn.TransactionMetadata=ka;var OE=class{constructor(){this.value=BigInt(0)}};kn.TransactionMetadataTransfer=OE;var DE=class{};kn.TokenTransferProperties=DE});var PE=B(w0=>{"use strict";h();Object.defineProperty(w0,"__esModule",{value:!0});w0.ReturnCode=void 0;var mt=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};w0.ReturnCode=mt;mt.None=new mt("");mt.Ok=new mt("ok");mt.FunctionNotFound=new mt("function not found");mt.FunctionWrongSignature=new mt("wrong signature for function");mt.ContractNotFound=new mt("contract not found");mt.UserError=new mt("user error");mt.OutOfGas=new mt("out of gas");mt.AccountCollision=new mt("account collision");mt.OutOfFunds=new mt("out of funds");mt.CallStackOverFlow=new mt("call stack overflow");mt.ContractInvalid=new mt("contract invalid");mt.ExecutionFailed=new mt("execution failed");mt.Unknown=new mt("unknown")});var JO=B(v0=>{"use strict";h();Object.defineProperty(v0,"__esModule",{value:!0});v0.ResultsParser=void 0;var wW=WO(),$O=Ve(),YO=Ie(),So=oo(),vW=fc(),wc=PE(),vc;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(vc||(vc={}));var RE;(function(t){t.TooMuchGas="@too much gas provided for processing"})(RE||(RE={}));var AW={argsSerializer:new vW.ArgSerializer},BE=class{constructor(e){e={...AW,...e},this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e);return this.parseOutcomeFromUntypedBundle(n,r)}parseOutcomeFromUntypedBundle(e,r){let n=this.argsSerializer.buffersToValues(e.values,r.output);return{returnCode:e.returnCode,returnMessage:e.returnMessage,values:n,firstValue:n[0],secondValue:n[1],thirdValue:n[2],lastValue:n[n.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return So.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return So.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return So.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return So.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new YO.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new wW.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:wc.ReturnCode.None,returnMessage:wc.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:wc.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(vc.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(vc.OnWriteLog,u=>u.findFirstOrNoneTopic(a=>a.toString().startsWith(RE.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new $O.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(vc.OnWriteLog,a=>a.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),u=s.toString();return{returnCode:s,returnMessage:u,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new $O.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(vc.OnWriteLog,o=>{let u=o.address.bech32()==e.sender.bech32(),a=o.topics[0]?.hex()==n.hex();return u&&a});if(s){let{returnCode:o,returnDataParts:u}=this.sliceDataFieldInParts(s.data),a=o.toString();return{returnCode:o,returnMessage:a,values:u}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||p.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new YO.ErrCannotParseContractResults("no return code");return{returnCode:wc.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){let n=e.topics.map(o=>p.Buffer.from(o.valueOf())).slice(1),i=e.dataPayload?.valueOf()||p.Buffer.from([]),s=e.additionalData?.map(o=>p.Buffer.from(o.valueOf()))||[];return s.length===0&&i.length&&s.push(p.Buffer.from(i)),this.doParseEvent({topics:n,dataItems:s,eventDefinition:r})}doParseEvent(e){let r={},n=e.eventDefinition.inputs.filter(u=>u.indexed),i=this.argsSerializer.buffersToValues(e.topics,n);for(let u=0;u!u.indexed),o=this.argsSerializer.buffersToValues(e.dataItems,s);for(let u=0;u{"use strict";h();Object.defineProperty(E0,"__esModule",{value:!0});E0.SmartContract=void 0;var A0=Ve(),ME=rE(),LE=hr(),EW=Ie(),FE=dE(),UE=mE(),bW=Rn(),XO=XA(),ZO=eE(),eD=_E(),SW=n0(),IW=Wf(),qE=class{constructor(e={}){this.address=A0.Address.empty(),this.methodsExplicit={},this.methods={},this.address=e.address||A0.Address.empty(),this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new ZO.ContractFunction(i);return new eD.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new ZO.ContractFunction(i),u=SW.NativeSerializer.nativeToTypedValues(s||[],n);return new eD.Interaction(e,o,u||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return bW.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()");let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=p.Buffer.from(r.toString(),"hex"),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForDeploy({sender:e,bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}getMetadataPropertiesAsObject(e){let r;return e?r=XO.CodeMetadata.fromBytes(p.Buffer.from(e.toString(),"hex")):r=new XO.CodeMetadata,r.toJSON()}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){ME.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=Uint8Array.from(p.Buffer.from(r.toString(),"hex")),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForUpgrade({sender:e,contract:this.getAddress(),bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??LE.TRANSACTION_MIN_GAS_PRICE),A}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:u,caller:a}){ME.Compatibility.guardAddressIsSetAndNonZero(a,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress();let c=new UE.TransactionsFactoryConfig({chainID:u.valueOf()}),f=new FE.SmartContractTransactionsFactory({config:c,abi:this.abi});r=r||[],n=n||0;let d=f.createTransactionForExecute({sender:a,contract:s||this.getAddress(),function:e.toString(),gasLimit:BigInt(i.valueOf()),arguments:r});return d.setChainID(u),d.setValue(n),d.setGasPrice(o??LE.TRANSACTION_MIN_GAS_PRICE),d}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new IW.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new EW.ErrContractHasNoAddress}static computeAddress(e,r){let n=A0.Address.fromBech32(e.bech32());return new A0.AddressComputer().computeContractAddress(n,BigInt(r.valueOf()))}};E0.SmartContract=qE});var rD=B(Io=>{"use strict";h();Object.defineProperty(Io,"__esModule",{value:!0});Io.ContractCallPayloadBuilder=Io.ContractUpgradePayloadBuilder=Io.ContractDeployPayloadBuilder=void 0;var TW=hr(),GE=Ms(),jE=Rn(),_W=fc(),VE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${TW.WasmVirtualMachine}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractDeployPayloadBuilder=VE;var kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=zE(n,this.arguments),new GE.TransactionPayload(n)}};Io.ContractUpgradePayloadBuilder=kE;var HE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){jE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=zE(e,this.arguments),new GE.TransactionPayload(e)}};Io.ContractCallPayloadBuilder=HE;function zE(t,e){let{argumentsString:r,count:n}=new _W.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var qn=B(Jt=>{"use strict";h();var CW=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qr=Jt&&Jt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&CW(e,t,r)};Object.defineProperty(Jt,"__esModule",{value:!0});qr(fc(),Jt);qr(vO(),Jt);qr(GA(),Jt);qr(XA(),Jt);qr(eE(),Jt);qr(_E(),Jt);qr(bE(),Jt);qr(CE(),Jt);qr(n0(),Jt);qr(Wf(),Jt);qr(JO(),Jt);qr(PE(),Jt);qr(tD(),Jt);qr(rD(),Jt);qr(dr(),Jt)});var Ac=B(or=>{"use strict";h();Object.defineProperty(or,"__esModule",{value:!0});or.gatherAllEvents=or.findEventsByFirstTopic=or.findEventsByIdentifier=or.findEventsByPredicate=or.SmartContractCallOutcome=or.TransactionOutcome=or.SmartContractResult=or.TransactionLogs=or.TransactionEvent=void 0;var QE=class{constructor(e){this.address="",this.identifier="",this.topics=[],this.dataItems=[],Object.assign(this,e)}};or.TransactionEvent=QE;var $f=class{constructor(e){this.address="",this.events=[],Object.assign(this,e)}};or.TransactionLogs=$f;var KE=class{constructor(e){this.sender="",this.receiver="",this.data=new Uint8Array,this.logs=new $f({}),Object.assign(this,e)}};or.SmartContractResult=KE;var WE=class{constructor(e){this.directSmartContractCallOutcome=new b0({}),this.smartContractResults=[],this.logs=new $f({}),Object.assign(this,e)}};or.TransactionOutcome=WE;var b0=class{constructor(e){this.function="",this.returnDataParts=[],this.returnMessage="",this.returnCode="",Object.assign(this,e)}};or.SmartContractCallOutcome=b0;function $E(t,e){return nD(t).filter(e)}or.findEventsByPredicate=$E;function NW(t,e){return $E(t,r=>r.identifier==e)}or.findEventsByIdentifier=NW;function xW(t,e){return $E(t,r=>r.topics[0]?.toString()==e)}or.findEventsByFirstTopic=xW;function nD(t){let e=[];e.push(...t.logs.events);for(let r of t.smartContractResults)e.push(...r.logs.events);return e}or.gatherAllEvents=nD});var JE=B(S0=>{"use strict";h();Object.defineProperty(S0,"__esModule",{value:!0});S0.TransactionsConverter=void 0;var OW=qn(),DW=Xr(),Ec=Ac(),YE=class{transactionToPlainObject(e){return{nonce:Number(e.nonce),value:e.value.toString(),receiver:e.receiver,sender:e.sender,senderUsername:this.toBase64OrUndefined(e.senderUsername),receiverUsername:this.toBase64OrUndefined(e.receiverUsername),gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:this.toBase64OrUndefined(e.data),chainID:e.chainID.valueOf(),version:e.version,options:e.options==0?void 0:e.options,guardian:e.guardian?e.guardian:void 0,signature:this.toHexOrUndefined(e.signature),guardianSignature:this.toHexOrUndefined(e.guardianSignature)}}toBase64OrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("base64"):void 0}toHexOrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("hex"):void 0}plainObjectToTransaction(e){return new DW.Transaction({nonce:BigInt(e.nonce),value:BigInt(e.value||""),receiver:e.receiver,receiverUsername:this.bufferFromBase64(e.receiverUsername).toString(),sender:e.sender,senderUsername:this.bufferFromBase64(e.senderUsername).toString(),guardian:e.guardian,gasPrice:BigInt(e.gasPrice),gasLimit:BigInt(e.gasLimit),data:this.bufferFromBase64(e.data),chainID:String(e.chainID),version:Number(e.version),options:Number(e.options),signature:this.bufferFromHex(e.signature),guardianSignature:this.bufferFromHex(e.guardianSignature)})}bufferFromBase64(e){return p.Buffer.from(e||"","base64")}bufferFromHex(e){return p.Buffer.from(e||"","hex")}transactionOnNetworkToOutcome(e){let n=new OW.ResultsParser().parseUntypedOutcome(e),i=new Ec.SmartContractCallOutcome({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.values}),s=e.contractResults.items.map(u=>this.smartContractResultOnNetworkToSmartContractResult(u)),o=new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(u=>this.eventOnNetworkToEvent(u))});return new Ec.TransactionOutcome({logs:o,smartContractResults:s,directSmartContractCallOutcome:i})}smartContractResultOnNetworkToSmartContractResult(e){return new Ec.SmartContractResult({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:p.Buffer.from(e.data),logs:new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(r=>this.eventOnNetworkToEvent(r))})})}eventOnNetworkToEvent(e){let r=e.dataPayload?.valueOf()||p.Buffer.from(e.data||""),n=e.additionalData?.map(i=>p.Buffer.from(i.valueOf()))||[];return n.length===0&&r.length&&n.push(p.Buffer.from(r)),new Ec.TransactionEvent({address:e.address.bech32(),identifier:e.identifier,topics:e.topics.map(i=>p.Buffer.from(i.hex(),"hex")),dataItems:n})}};S0.TransactionsConverter=YE});var iD=B(Yi=>{"use strict";h();var PW=Yi&&Yi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RW=Yi&&Yi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BW=Yi&&Yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PW(e,t,r);return RW(e,t),e};Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Hash=void 0;var MW=BW(Ie()),XE=class t{constructor(e){if(!e)this.hash=p.Buffer.from([]);else if(e instanceof p.Buffer)this.hash=e;else if(typeof e=="string")this.hash=p.Buffer.from(e,"hex");else throw new MW.ErrBadType("hash","buffer | string",e)}static empty(){return new t(p.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};Yi.Hash=XE});var Yf=B(Hn=>{"use strict";h();var LW=Hn&&Hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FW=Hn&&Hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),UW=Hn&&Hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&LW(e,t,r);return FW(e,t),e};Object.defineProperty(Hn,"__esModule",{value:!0});Hn.interpretSignatureAsBuffer=Hn.Signature=void 0;var sD=UW(Ie()),oD=64,ZE=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof p.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==oD}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=oD)throw new sD.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Hn.Signature=ZE;function qW(t){if(ArrayBuffer.isView(t))return p.Buffer.from(t);if(t.hex!=null)return p.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Hn.interpretSignatureAsBuffer=qW});var uD=B((F1e,aD)=>{"use strict";h();aD.exports=VW;function VW(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";h();var I0=fD;I0.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bc=new Array(64),lD=new Array(123);for(mi=0;mi<64;)lD[bc[mi]=mi<26?mi+65:mi<52?mi+71:mi<62?mi-4:mi-59|43]=mi++;var mi;I0.encode=function(e,r,n){for(var i=null,s=[],o=0,u=0,a;r>2],a=(c&3)<<4,u=1;break;case 1:s[o++]=bc[a|c>>4],a=(c&15)<<2,u=2;break;case 2:s[o++]=bc[a|c>>6],s[o++]=bc[c&63],u=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return u&&(s[o++]=bc[a],s[o++]=61,u===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var cD="invalid encoding";I0.decode=function(e,r,n){for(var i=n,s=0,o,u=0;u1)break;if((a=lD[a])===void 0)throw Error(cD);switch(s){case 0:o=a,s=1;break;case 1:r[n++]=o<<2|(a&48)>>4,o=a,s=2;break;case 2:r[n++]=(o&15)<<4|(a&60)>>2,o=a,s=3;break;case 3:r[n++]=(o&3)<<6|a,s=0;break}}if(s===1)throw Error(cD);return n-i};I0.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var gD=B((k1e,dD)=>{"use strict";h();dD.exports=T0;function T0(){this._listeners={}}T0.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};T0.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";h();AD.exports=pD(pD);function pD(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(a,c,f){e[0]=a,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],e[0]}function u(a,c){return r[3]=a[c],r[2]=a[c+1],r[1]=a[c+2],r[0]=a[c+3],e[0]}t.readFloatLE=n?o:u,t.readFloatBE=n?u:o}():function(){function e(n,i,s,o){var u=i<0?1:0;if(u&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((u<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((u<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var a=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-a)*8388608)&8388607;n((u<<31|a+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,mD),t.writeFloatBE=e.bind(null,yD);function r(n,i,s){var o=n(i,s),u=(o>>31)*2+1,a=o>>>23&255,c=o&8388607;return a===255?c?NaN:u*(1/0):a===0?u*1401298464324817e-60*c:u*Math.pow(2,a-150)*(c+8388608)}t.readFloatLE=r.bind(null,wD),t.readFloatBE=r.bind(null,vD)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(a,c,f){e[0]=a,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],r[4]=a[c+4],r[5]=a[c+5],r[6]=a[c+6],r[7]=a[c+7],e[0]}function u(a,c){return r[7]=a[c],r[6]=a[c+1],r[5]=a[c+2],r[4]=a[c+3],r[3]=a[c+4],r[2]=a[c+5],r[1]=a[c+6],r[0]=a[c+7],e[0]}t.readDoubleLE=n?o:u,t.readDoubleBE=n?u:o}():function(){function e(n,i,s,o,u,a){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,u,a+i),n(1/o>0?0:2147483648,u,a+s);else if(isNaN(o))n(0,u,a+i),n(2146959360,u,a+s);else if(o>17976931348623157e292)n(0,u,a+i),n((c<<31|2146435072)>>>0,u,a+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,u,a+i),n((c<<31|f/4294967296)>>>0,u,a+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,u,a+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,u,a+s)}}}t.writeDoubleLE=e.bind(null,mD,0,4),t.writeDoubleBE=e.bind(null,yD,4,0);function r(n,i,s,o,u){var a=n(o,u+i),c=n(o,u+s),f=(c>>31)*2+1,d=c>>>20&2047,w=4294967296*(c&1048575)+a;return d===2047?w?NaN:f*(1/0):d===0?f*5e-324*w:f*Math.pow(2,d-1075)*(w+4503599627370496)}t.readDoubleLE=r.bind(null,wD,0,4),t.readDoubleBE=r.bind(null,vD,4,0)}(),t}function mD(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function yD(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function wD(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function vD(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var bD=B((exports,module)=>{"use strict";h();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var ID=B(SD=>{"use strict";h();var eb=SD;eb.length=function(e){for(var r=0,n=0,i=0;i191&&a<224?o[u++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[u++]=55296+(a>>10),o[u++]=56320+(a&1023)):o[u++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,u>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),u=0);return s?(u&&s.push(String.fromCharCode.apply(String,o.slice(0,u))),s.join("")):String.fromCharCode.apply(String,o.slice(0,u))};eb.write=function(e,r,n){for(var i=n,s,o,u=0;u>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(u+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++u,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var _D=B((W1e,TD)=>{"use strict";h();TD.exports=kW;function kW(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);var c=e.call(s,o,o+=a);return o&7&&(o=(o|7)+1),c}}});var ND=B((Y1e,CD)=>{"use strict";h();CD.exports=yr;var Jf=_o();function yr(t,e){this.lo=t>>>0,this.hi=e>>>0}var Ha=yr.zero=new yr(0,0);Ha.toNumber=function(){return 0};Ha.zzEncode=Ha.zzDecode=function(){return this};Ha.length=function(){return 1};var HW=yr.zeroHash="\0\0\0\0\0\0\0\0";yr.fromNumber=function(e){if(e===0)return Ha;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new yr(n,i)};yr.from=function(e){if(typeof e=="number")return yr.fromNumber(e);if(Jf.isString(e))if(Jf.Long)e=Jf.Long.fromString(e);else return yr.fromNumber(parseInt(e,10));return e.low||e.high?new yr(e.low>>>0,e.high>>>0):Ha};yr.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};yr.prototype.toLong=function(e){return Jf.Long?new Jf.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var To=String.prototype.charCodeAt;yr.fromHash=function(e){return e===HW?Ha:new yr((To.call(e,0)|To.call(e,1)<<8|To.call(e,2)<<16|To.call(e,3)<<24)>>>0,(To.call(e,4)|To.call(e,5)<<8|To.call(e,6)<<16|To.call(e,7)<<24)>>>0)};yr.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};yr.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};yr.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};yr.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var _o=B(tb=>{"use strict";h();var we=tb;we.asPromise=uD();we.base64=hD();we.EventEmitter=gD();we.float=ED();we.inquire=bD();we.utf8=ID();we.pool=_D();we.LongBits=ND();we.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);we.global=we.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||tb;we.emptyArray=Object.freeze?Object.freeze([]):[];we.emptyObject=Object.freeze?Object.freeze({}):{};we.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};we.isString=function(e){return typeof e=="string"||e instanceof String};we.isObject=function(e){return e&&typeof e=="object"};we.isset=we.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};we.Buffer=function(){try{var t=we.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();we._Buffer_from=null;we._Buffer_allocUnsafe=null;we.newBuffer=function(e){return typeof e=="number"?we.Buffer?we._Buffer_allocUnsafe(e):new we.Array(e):we.Buffer?we._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};we.Array=typeof Uint8Array<"u"?Uint8Array:Array;we.Long=we.global.dcodeIO&&we.global.dcodeIO.Long||we.global.Long||we.inquire("long");we.key2Re=/^true|false|0|1$/;we.key32Re=/^-?(?:0|[1-9][0-9]*)$/;we.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;we.longToHash=function(e){return e?we.LongBits.from(e).toHash():we.LongBits.zeroHash};we.longFromHash=function(e,r){var n=we.LongBits.fromHash(e);return we.Long?we.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function xD(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};we.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";h();BD.exports=Ue;var Gn=_o(),rb,_0=Gn.LongBits,DD=Gn.base64,PD=Gn.utf8;function Xf(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function ib(){}function GW(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Xf(ib,0,0),this.tail=this.head,this.states=null}var RD=function(){return Gn.Buffer?function(){return(Ue.create=function(){return new rb})()}:function(){return new Ue}};Ue.create=RD();Ue.alloc=function(e){return new Gn.Array(e)};Gn.Array!==Array&&(Ue.alloc=Gn.pool(Ue.alloc,Gn.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Xf(e,r,n),this.len+=r,this};function sb(t,e,r){e[r]=t&255}function jW(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function ob(t,e){this.len=t,this.next=void 0,this.val=e}ob.prototype=Object.create(Xf.prototype);ob.prototype.fn=jW;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ob((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(ab,10,_0.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ab(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=_0.from(e);return this._push(ab,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=_0.from(e).zzEncode();return this._push(ab,r.length(),r)};Ue.prototype.bool=function(e){return this._push(sb,1,e?1:0)};function nb(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(nb,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=_0.from(e);return this._push(nb,4,r.lo)._push(nb,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Gn.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Gn.float.writeDoubleLE,8,e)};var zW=Gn.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(sb,1,0);if(Gn.isString(e)){var n=Ue.alloc(r=DD.length(e));DD.decode(e,n,0),e=n}return this.uint32(r)._push(zW,r,e)};Ue.prototype.string=function(e){var r=PD.length(e);return r?this.uint32(r)._push(PD.write,r,e):this._push(sb,1,0)};Ue.prototype.fork=function(){return this.states=new GW(this),this.head=this.tail=new Xf(ib,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xf(ib,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){rb=t,Ue.create=RD(),rb._configure()}});var FD=B((rwe,LD)=>{"use strict";h();LD.exports=Ji;var MD=ub();(Ji.prototype=Object.create(MD.prototype)).constructor=Ji;var Co=_o();function Ji(){MD.call(this)}Ji._configure=function(){Ji.alloc=Co._Buffer_allocUnsafe,Ji.writeBytesBuffer=Co.Buffer&&Co.Buffer.prototype instanceof Uint8Array&&Co.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Ji.writeBytesBuffer,r,e),this};function QW(t,e,r){t.length<40?Co.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ji.prototype.string=function(e){var r=Co.Buffer.byteLength(e);return this.uint32(r),r&&this._push(QW,r,e),this};Ji._configure()});var fb=B((iwe,HD)=>{"use strict";h();HD.exports=Xt;var yi=_o(),lb,VD=yi.LongBits,KW=yi.utf8;function wi(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Xt(t){this.buf=t,this.pos=0,this.len=t.length}var UD=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Xt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Xt(e);throw Error("illegal buffer")},kD=function(){return yi.Buffer?function(r){return(Xt.create=function(i){return yi.Buffer.isBuffer(i)?new lb(i):UD(i)})(r)}:UD};Xt.create=kD();Xt.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Xt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wi(this,10);return e}}();Xt.prototype.int32=function(){return this.uint32()|0};Xt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function cb(){var t=new VD(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw wi(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw wi(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Xt.prototype.bool=function(){return this.uint32()!==0};function C0(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Xt.prototype.fixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)};Xt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return C0(this.buf,this.pos+=4)|0};function qD(){if(this.pos+8>this.len)throw wi(this,8);return new VD(C0(this.buf,this.pos+=4),C0(this.buf,this.pos+=4))}Xt.prototype.float=function(){if(this.pos+4>this.len)throw wi(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Xt.prototype.double=function(){if(this.pos+8>this.len)throw wi(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Xt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw wi(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var i=yi.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Xt.prototype.string=function(){var e=this.bytes();return KW.read(e,0,e.length)};Xt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wi(this);while(this.buf[this.pos++]&128);return this};Xt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Xt._configure=function(t){lb=t,Xt.create=kD(),lb._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Xt.prototype,{int64:function(){return cb.call(this)[e](!1)},uint64:function(){return cb.call(this)[e](!0)},sint64:function(){return cb.call(this).zzDecode()[e](!1)},fixed64:function(){return qD.call(this)[e](!0)},sfixed64:function(){return qD.call(this)[e](!1)}})}});var QD=B((owe,zD)=>{"use strict";h();zD.exports=Ga;var jD=fb();(Ga.prototype=Object.create(jD.prototype)).constructor=Ga;var GD=_o();function Ga(t){jD.call(this,t)}Ga._configure=function(){GD.Buffer&&(Ga.prototype._slice=GD.Buffer.prototype.slice)};Ga.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ga._configure()});var WD=B((uwe,KD)=>{"use strict";h();KD.exports=Zf;var hb=_o();(Zf.prototype=Object.create(hb.EventEmitter.prototype)).constructor=Zf;function Zf(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");hb.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Zf.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return hb.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(a,c){if(a)return o.emit("error",a,e),s(a);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(u){o.emit("error",u,e),setTimeout(function(){s(u)},0);return}};Zf.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var YD=B($D=>{"use strict";h();var WW=$D;WW.Service=WD()});var XD=B((hwe,JD)=>{"use strict";h();JD.exports={}});var t8=B(e8=>{"use strict";h();var tn=e8;tn.build="minimal";tn.Writer=ub();tn.BufferWriter=FD();tn.Reader=fb();tn.BufferReader=QD();tn.util=_o();tn.rpc=YD();tn.roots=XD();tn.configure=ZD;function ZD(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}ZD()});var n8=B((mwe,r8)=>{"use strict";h();r8.exports=t8()});var s8=B((i8,eh)=>{"use strict";h();(function(t,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof Bd=="function"&&typeof eh=="object"&&eh&&eh.exports&&(eh.exports=e(n8()))})(i8,function(t){"use strict";var e=t.Reader,r=t.Writer,n=t.util,i=t.roots.default||(t.roots.default={});return i.proto=function(){var s={};return s.Transaction=function(){function o(u){if(u)for(var a=Object.keys(u),c=0;c>>3){case 1:{d.Nonce=a.uint64();break}case 2:{d.Value=a.bytes();break}case 3:{d.RcvAddr=a.bytes();break}case 4:{d.RcvUserName=a.bytes();break}case 5:{d.SndAddr=a.bytes();break}case 6:{d.SndUserName=a.bytes();break}case 7:{d.GasPrice=a.uint64();break}case 8:{d.GasLimit=a.uint64();break}case 9:{d.Data=a.bytes();break}case 10:{d.ChainID=a.bytes();break}case 11:{d.Version=a.uint32();break}case 12:{d.Signature=a.bytes();break}case 13:{d.Options=a.uint32();break}case 14:{d.GuardianAddr=a.bytes();break}case 15:{d.GuardianSignature=a.bytes();break}default:a.skipType(w&7);break}}return d},o.decodeDelimited=function(a){return a instanceof e||(a=new e(a)),this.decode(a,a.uint32())},o.verify=function(a){return typeof a!="object"||a===null?"object expected":a.Nonce!=null&&a.hasOwnProperty("Nonce")&&!n.isInteger(a.Nonce)&&!(a.Nonce&&n.isInteger(a.Nonce.low)&&n.isInteger(a.Nonce.high))?"Nonce: integer|Long expected":a.Value!=null&&a.hasOwnProperty("Value")&&!(a.Value&&typeof a.Value.length=="number"||n.isString(a.Value))?"Value: buffer expected":a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&!(a.RcvAddr&&typeof a.RcvAddr.length=="number"||n.isString(a.RcvAddr))?"RcvAddr: buffer expected":a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&!(a.RcvUserName&&typeof a.RcvUserName.length=="number"||n.isString(a.RcvUserName))?"RcvUserName: buffer expected":a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&!(a.SndAddr&&typeof a.SndAddr.length=="number"||n.isString(a.SndAddr))?"SndAddr: buffer expected":a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&!(a.SndUserName&&typeof a.SndUserName.length=="number"||n.isString(a.SndUserName))?"SndUserName: buffer expected":a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&!n.isInteger(a.GasPrice)&&!(a.GasPrice&&n.isInteger(a.GasPrice.low)&&n.isInteger(a.GasPrice.high))?"GasPrice: integer|Long expected":a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&!n.isInteger(a.GasLimit)&&!(a.GasLimit&&n.isInteger(a.GasLimit.low)&&n.isInteger(a.GasLimit.high))?"GasLimit: integer|Long expected":a.Data!=null&&a.hasOwnProperty("Data")&&!(a.Data&&typeof a.Data.length=="number"||n.isString(a.Data))?"Data: buffer expected":a.ChainID!=null&&a.hasOwnProperty("ChainID")&&!(a.ChainID&&typeof a.ChainID.length=="number"||n.isString(a.ChainID))?"ChainID: buffer expected":a.Version!=null&&a.hasOwnProperty("Version")&&!n.isInteger(a.Version)?"Version: integer expected":a.Signature!=null&&a.hasOwnProperty("Signature")&&!(a.Signature&&typeof a.Signature.length=="number"||n.isString(a.Signature))?"Signature: buffer expected":a.Options!=null&&a.hasOwnProperty("Options")&&!n.isInteger(a.Options)?"Options: integer expected":a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&!(a.GuardianAddr&&typeof a.GuardianAddr.length=="number"||n.isString(a.GuardianAddr))?"GuardianAddr: buffer expected":a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&!(a.GuardianSignature&&typeof a.GuardianSignature.length=="number"||n.isString(a.GuardianSignature))?"GuardianSignature: buffer expected":null},o.fromObject=function(a){if(a instanceof i.proto.Transaction)return a;var c=new i.proto.Transaction;return a.Nonce!=null&&(n.Long?(c.Nonce=n.Long.fromValue(a.Nonce)).unsigned=!0:typeof a.Nonce=="string"?c.Nonce=parseInt(a.Nonce,10):typeof a.Nonce=="number"?c.Nonce=a.Nonce:typeof a.Nonce=="object"&&(c.Nonce=new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0))),a.Value!=null&&(typeof a.Value=="string"?n.base64.decode(a.Value,c.Value=n.newBuffer(n.base64.length(a.Value)),0):a.Value.length>=0&&(c.Value=a.Value)),a.RcvAddr!=null&&(typeof a.RcvAddr=="string"?n.base64.decode(a.RcvAddr,c.RcvAddr=n.newBuffer(n.base64.length(a.RcvAddr)),0):a.RcvAddr.length>=0&&(c.RcvAddr=a.RcvAddr)),a.RcvUserName!=null&&(typeof a.RcvUserName=="string"?n.base64.decode(a.RcvUserName,c.RcvUserName=n.newBuffer(n.base64.length(a.RcvUserName)),0):a.RcvUserName.length>=0&&(c.RcvUserName=a.RcvUserName)),a.SndAddr!=null&&(typeof a.SndAddr=="string"?n.base64.decode(a.SndAddr,c.SndAddr=n.newBuffer(n.base64.length(a.SndAddr)),0):a.SndAddr.length>=0&&(c.SndAddr=a.SndAddr)),a.SndUserName!=null&&(typeof a.SndUserName=="string"?n.base64.decode(a.SndUserName,c.SndUserName=n.newBuffer(n.base64.length(a.SndUserName)),0):a.SndUserName.length>=0&&(c.SndUserName=a.SndUserName)),a.GasPrice!=null&&(n.Long?(c.GasPrice=n.Long.fromValue(a.GasPrice)).unsigned=!0:typeof a.GasPrice=="string"?c.GasPrice=parseInt(a.GasPrice,10):typeof a.GasPrice=="number"?c.GasPrice=a.GasPrice:typeof a.GasPrice=="object"&&(c.GasPrice=new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0))),a.GasLimit!=null&&(n.Long?(c.GasLimit=n.Long.fromValue(a.GasLimit)).unsigned=!0:typeof a.GasLimit=="string"?c.GasLimit=parseInt(a.GasLimit,10):typeof a.GasLimit=="number"?c.GasLimit=a.GasLimit:typeof a.GasLimit=="object"&&(c.GasLimit=new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0))),a.Data!=null&&(typeof a.Data=="string"?n.base64.decode(a.Data,c.Data=n.newBuffer(n.base64.length(a.Data)),0):a.Data.length>=0&&(c.Data=a.Data)),a.ChainID!=null&&(typeof a.ChainID=="string"?n.base64.decode(a.ChainID,c.ChainID=n.newBuffer(n.base64.length(a.ChainID)),0):a.ChainID.length>=0&&(c.ChainID=a.ChainID)),a.Version!=null&&(c.Version=a.Version>>>0),a.Signature!=null&&(typeof a.Signature=="string"?n.base64.decode(a.Signature,c.Signature=n.newBuffer(n.base64.length(a.Signature)),0):a.Signature.length>=0&&(c.Signature=a.Signature)),a.Options!=null&&(c.Options=a.Options>>>0),a.GuardianAddr!=null&&(typeof a.GuardianAddr=="string"?n.base64.decode(a.GuardianAddr,c.GuardianAddr=n.newBuffer(n.base64.length(a.GuardianAddr)),0):a.GuardianAddr.length>=0&&(c.GuardianAddr=a.GuardianAddr)),a.GuardianSignature!=null&&(typeof a.GuardianSignature=="string"?n.base64.decode(a.GuardianSignature,c.GuardianSignature=n.newBuffer(n.base64.length(a.GuardianSignature)),0):a.GuardianSignature.length>=0&&(c.GuardianSignature=a.GuardianSignature)),c},o.toObject=function(a,c){c||(c={});var f={};if(c.defaults){if(n.Long){var d=new n.Long(0,0,!0);f.Nonce=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.Nonce=c.longs===String?"0":0;if(c.bytes===String?f.Value="":(f.Value=[],c.bytes!==Array&&(f.Value=n.newBuffer(f.Value))),c.bytes===String?f.RcvAddr="":(f.RcvAddr=[],c.bytes!==Array&&(f.RcvAddr=n.newBuffer(f.RcvAddr))),c.bytes===String?f.RcvUserName="":(f.RcvUserName=[],c.bytes!==Array&&(f.RcvUserName=n.newBuffer(f.RcvUserName))),c.bytes===String?f.SndAddr="":(f.SndAddr=[],c.bytes!==Array&&(f.SndAddr=n.newBuffer(f.SndAddr))),c.bytes===String?f.SndUserName="":(f.SndUserName=[],c.bytes!==Array&&(f.SndUserName=n.newBuffer(f.SndUserName))),n.Long){var d=new n.Long(0,0,!0);f.GasPrice=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasPrice=c.longs===String?"0":0;if(n.Long){var d=new n.Long(0,0,!0);f.GasLimit=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasLimit=c.longs===String?"0":0;c.bytes===String?f.Data="":(f.Data=[],c.bytes!==Array&&(f.Data=n.newBuffer(f.Data))),c.bytes===String?f.ChainID="":(f.ChainID=[],c.bytes!==Array&&(f.ChainID=n.newBuffer(f.ChainID))),f.Version=0,c.bytes===String?f.Signature="":(f.Signature=[],c.bytes!==Array&&(f.Signature=n.newBuffer(f.Signature))),f.Options=0,c.bytes===String?f.GuardianAddr="":(f.GuardianAddr=[],c.bytes!==Array&&(f.GuardianAddr=n.newBuffer(f.GuardianAddr))),c.bytes===String?f.GuardianSignature="":(f.GuardianSignature=[],c.bytes!==Array&&(f.GuardianSignature=n.newBuffer(f.GuardianSignature)))}return a.Nonce!=null&&a.hasOwnProperty("Nonce")&&(typeof a.Nonce=="number"?f.Nonce=c.longs===String?String(a.Nonce):a.Nonce:f.Nonce=c.longs===String?n.Long.prototype.toString.call(a.Nonce):c.longs===Number?new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0):a.Nonce),a.Value!=null&&a.hasOwnProperty("Value")&&(f.Value=c.bytes===String?n.base64.encode(a.Value,0,a.Value.length):c.bytes===Array?Array.prototype.slice.call(a.Value):a.Value),a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&(f.RcvAddr=c.bytes===String?n.base64.encode(a.RcvAddr,0,a.RcvAddr.length):c.bytes===Array?Array.prototype.slice.call(a.RcvAddr):a.RcvAddr),a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&(f.RcvUserName=c.bytes===String?n.base64.encode(a.RcvUserName,0,a.RcvUserName.length):c.bytes===Array?Array.prototype.slice.call(a.RcvUserName):a.RcvUserName),a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&(f.SndAddr=c.bytes===String?n.base64.encode(a.SndAddr,0,a.SndAddr.length):c.bytes===Array?Array.prototype.slice.call(a.SndAddr):a.SndAddr),a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&(f.SndUserName=c.bytes===String?n.base64.encode(a.SndUserName,0,a.SndUserName.length):c.bytes===Array?Array.prototype.slice.call(a.SndUserName):a.SndUserName),a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&(typeof a.GasPrice=="number"?f.GasPrice=c.longs===String?String(a.GasPrice):a.GasPrice:f.GasPrice=c.longs===String?n.Long.prototype.toString.call(a.GasPrice):c.longs===Number?new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0):a.GasPrice),a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&(typeof a.GasLimit=="number"?f.GasLimit=c.longs===String?String(a.GasLimit):a.GasLimit:f.GasLimit=c.longs===String?n.Long.prototype.toString.call(a.GasLimit):c.longs===Number?new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0):a.GasLimit),a.Data!=null&&a.hasOwnProperty("Data")&&(f.Data=c.bytes===String?n.base64.encode(a.Data,0,a.Data.length):c.bytes===Array?Array.prototype.slice.call(a.Data):a.Data),a.ChainID!=null&&a.hasOwnProperty("ChainID")&&(f.ChainID=c.bytes===String?n.base64.encode(a.ChainID,0,a.ChainID.length):c.bytes===Array?Array.prototype.slice.call(a.ChainID):a.ChainID),a.Version!=null&&a.hasOwnProperty("Version")&&(f.Version=a.Version),a.Signature!=null&&a.hasOwnProperty("Signature")&&(f.Signature=c.bytes===String?n.base64.encode(a.Signature,0,a.Signature.length):c.bytes===Array?Array.prototype.slice.call(a.Signature):a.Signature),a.Options!=null&&a.hasOwnProperty("Options")&&(f.Options=a.Options),a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&(f.GuardianAddr=c.bytes===String?n.base64.encode(a.GuardianAddr,0,a.GuardianAddr.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianAddr):a.GuardianAddr),a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&(f.GuardianSignature=c.bytes===String?n.base64.encode(a.GuardianSignature,0,a.GuardianSignature.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianSignature):a.GuardianSignature),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,t.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Transaction"},o}(),s}(),i})});var o8=B(jn=>{"use strict";h();var $W=jn&&jn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),YW=jn&&jn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),JW=jn&&jn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$W(e,t,r);return YW(e,t),e},XW=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.ProtoSerializer=void 0;var ZW=XW((rr(),_e(fr))),db=Ve(),e$=hr(),t$=JW(Ie()),r$=Bu(),gb=class{serializeTransaction(e){let r=s8().proto,n=new db.Address(e.getReceiver().bech32()).pubkey(),i=new db.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?p.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?p.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:p.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==e$.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let a=e.getGuardian();s.GuardianAddr=new db.Address(a.bech32()).pubkey(),s.GuardianSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return p.Buffer.from(o)}serializeTransactionValue(e){let r=new ZW.default(e.toString());if(r.isZero())return p.Buffer.from([0,0]);let n=r$.bigIntToBuffer(r);return n=p.Buffer.concat([p.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new t$.ErrUnsupportedOperation("deserializeTransaction")}};jn.ProtoSerializer=gb});var a8=B(ja=>{"use strict";h();var n$=ja&&ja.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),i$=ja&&ja.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&n$(e,t,r)};Object.defineProperty(ja,"__esModule",{value:!0});i$(o8(),ja)});var N0=B(zn=>{"use strict";h();var s$=zn&&zn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),o$=zn&&zn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a$=zn&&zn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&s$(e,t,r);return o$(e,t),e},u$=zn&&zn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zn,"__esModule",{value:!0});zn.TransactionComputer=void 0;var th=a$(Ie()),u8=u$((rr(),_e(fr))),c$=a8(),l$=Xr(),rn=hr(),f$=YA(),h$=sf(),d$=32,pb=class{constructor(){}computeTransactionFee(e,r){let n=BigInt(r.MinGasLimit+e.data.length*r.GasPerDataByte);if(n>e.gasLimit)throw new th.ErrNotEnoughGas(parseInt(e.gasLimit.toString(),10));let i=e.gasPrice,s=n*i;if(n===e.gasLimit)return s;let o=e.gasLimit-n,u=BigInt(new u8.default(i.toString()).multipliedBy(new u8.default(r.GasPriceModifier)).toFixed(0)),a=o*u;return s+a}computeBytesForSigning(e){this.ensureValidTransactionFields(e);let r=this.toPlainObjectForSigning(e),n=JSON.stringify(r);return new Uint8Array(p.Buffer.from(n))}computeBytesForVerifying(e){return this.hasOptionsSetForHashSigning(e)?this.computeHashForSigning(e):this.computeBytesForSigning(e)}computeHashForSigning(e){let r=this.toPlainObjectForSigning(e),n=p.Buffer.from(JSON.stringify(r));return h$("keccak256").update(n).digest()}computeTransactionHash(e){let n=new c$.ProtoSerializer().serializeTransaction(new l$.Transaction(e)),i=f$(d$).update(n).digest("hex");return p.Buffer.from(i,"hex")}hasOptionsSetForGuardedTransaction(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_GUARDED)==rn.TRANSACTION_OPTIONS_TX_GUARDED}hasOptionsSetForHashSigning(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_HASH_SIGN)==rn.TRANSACTION_OPTIONS_TX_HASH_SIGN}applyGuardian(e,r){e.version= ${rn.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`)}};zn.TransactionComputer=pb});var Xr=B(Sc=>{"use strict";h();Object.defineProperty(Sc,"__esModule",{value:!0});Sc.TransactionHash=Sc.Transaction=void 0;var c8=(rr(),_e(fr)),mb=Ve(),yb=hr(),l8=JE(),g$=iD(),f8=$l(),h8=Yf(),p$=Ms(),wb=N0(),vb=class{constructor(e){this.nonce=BigInt(e.nonce?.valueOf()||0n),this.value=e.value?BigInt(new c8.BigNumber(e.value.toString()).toFixed(0)):0n,this.sender=this.addressAsBech32(e.sender),this.receiver=this.addressAsBech32(e.receiver),this.senderUsername=e.senderUsername||"",this.receiverUsername=e.receiverUsername||"",this.gasPrice=BigInt(e.gasPrice?.valueOf()||yb.TRANSACTION_MIN_GAS_PRICE),this.gasLimit=BigInt(e.gasLimit.valueOf()),this.data=e.data?.valueOf()||new Uint8Array,this.chainID=e.chainID.valueOf(),this.version=Number(e.version?.valueOf()||yb.TRANSACTION_VERSION_DEFAULT),this.options=Number(e.options?.valueOf()||yb.TRANSACTION_OPTIONS_DEFAULT),this.guardian=e.guardian?this.addressAsBech32(e.guardian):"",this.signature=e.signature||p.Buffer.from([]),this.guardianSignature=e.guardianSignature||p.Buffer.from([])}addressAsBech32(e){return typeof e=="string"?e:e.bech32()}getNonce(){return Number(this.nonce)}setNonce(e){this.nonce=BigInt(e.valueOf())}getValue(){return this.value}setValue(e){this.value=BigInt(e.toString())}getSender(){return mb.Address.fromBech32(this.sender)}setSender(e){this.sender=typeof e=="string"?e:e.bech32()}getReceiver(){return mb.Address.fromBech32(this.receiver)}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return new mb.Address(this.guardian)}getGasPrice(){return Number(this.gasPrice)}setGasPrice(e){this.gasPrice=BigInt(e.valueOf())}getGasLimit(){return Number(this.gasLimit)}setGasLimit(e){this.gasLimit=BigInt(e.valueOf())}getData(){return new p$.TransactionPayload(p.Buffer.from(this.data))}getChainID(){return this.chainID}setChainID(e){this.chainID=e.valueOf()}getVersion(){return new f8.TransactionVersion(this.version)}setVersion(e){this.version=e.valueOf()}getOptions(){return new f8.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=e.valueOf()}getSignature(){return p.Buffer.from(this.signature)}getGuardianSignature(){return p.Buffer.from(this.guardianSignature)}setGuardian(e){this.guardian=typeof e=="string"?e:e.bech32()}getHash(){return x0.compute(this)}serializeForSigning(){let r=new wb.TransactionComputer().computeBytesForSigning(this);return p.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){return new l8.TransactionsConverter().transactionToPlainObject(this)}static fromPlainObject(e){return new l8.TransactionsConverter().plainObjectToTransaction(e)}applySignature(e){this.signature=h8.interpretSignatureAsBuffer(e)}applyGuardianSignature(e){this.guardianSignature=h8.interpretSignatureAsBuffer(e)}toSendable(){return this.toPlainObject()}computeFee(e){let n=new wb.TransactionComputer().computeTransactionFee(this,e);return new c8.BigNumber(n.toString())}};Sc.Transaction=vb;var x0=class t extends g$.Hash{constructor(e){super(e)}static compute(e){let n=new wb.TransactionComputer().computeTransactionHash(e);return new t(p.Buffer.from(n).toString("hex"))}};Sc.TransactionHash=x0});var g8=B(O0=>{"use strict";h();Object.defineProperty(O0,"__esModule",{value:!0});O0.TokenOperationsFactory=void 0;var Ab=hr(),m$=oo(),d8=$l(),y$=Xr(),w$=Ms(),ae=$d(),Eb=class{constructor(e){this.config=e,this.trueAsHex=ae.utf8ToHex("true"),this.falseAsHex=ae.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.initialSupply),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){m$.Logger.info(` +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}boolToString(e){return e?this.trueAsString:this.falseAsString}};o0.TokenManagementTransactionsFactory=pE});var yE=D(a0=>{"use strict";h();Object.defineProperty(a0,"__esModule",{value:!0});a0.TransactionsFactoryConfig=void 0;var dW=hr(),mE=class{constructor(e){this.chainID=e.chainID,this.addressHrp=dW.DEFAULT_HRP,this.minGasLimit=50000n,this.gasLimitPerByte=1500n,this.gasLimitIssue=60000000n,this.gasLimitToggleBurnRoleGlobally=60000000n,this.gasLimitEsdtLocalMint=300000n,this.gasLimitEsdtLocalBurn=300000n,this.gasLimitSetSpecialRole=60000000n,this.gasLimitPausing=60000000n,this.gasLimitFreezing=60000000n,this.gasLimitWiping=60000000n,this.gasLimitEsdtNftCreate=3000000n,this.gasLimitEsdtNftUpdateAttributes=1000000n,this.gasLimitEsdtNftAddQuantity=1000000n,this.gasLimitEsdtNftBurn=1000000n,this.gasLimitStorePerByte=10000n,this.issueCost=50000000000000000n,this.gasLimitStake=5000000n,this.gasLimitUnstake=5000000n,this.gasLimitUnbond=5000000n,this.gasLimitCreateDelegationContract=50000000n,this.gasLimitDelegationOperations=1000000n,this.additionalGasLimitPerValidatorNode=6000000n,this.additionalGasLimitForDelegationOperations=10000000n,this.gasLimitSaveKeyValue=100000n,this.gasLimitPersistPerByte=1000n,this.gasLimitSetGuardian=250000n,this.gasLimitGuardAccount=250000n,this.gasLimitUnguardAccount=250000n,this.gasLimitESDTTransfer=200000n,this.gasLimitESDTNFTTransfer=200000n,this.gasLimitMultiESDTNFTTransfer=200000n,this.gasLimitClaimDeveloperRewards=6000000n,this.gasLimitChangeOwnerAddress=6000000n}};a0.TransactionsFactoryConfig=mE});var FO=D(u0=>{"use strict";h();Object.defineProperty(u0,"__esModule",{value:!0});u0.TransferTransactionsFactory=void 0;var bo=Ie(),en=qn(),gW=_a(),Kf=Xr(),wE=Ms(),pW=hE(),MO=gc(),mW=1e5,LO=8e5,vE=class{constructor(e){this.isGasEstimator(e)?this.gasEstimator=e:(this.config=e.config,this.tokenComputer=new gW.TokenComputer,this.tokenTransfersDataBuilder=new pW.TokenTransfersDataBuilder)}isGasEstimator(e){return typeof e=="object"&&typeof e.forEGLDTransfer=="function"&&typeof e.forESDTTransfer=="function"&&typeof e.forESDTNFTTransfer=="function"&&typeof e.forMultiESDTNFTTransfer=="function"}isGasEstimatorDefined(){return this.gasEstimator!==void 0}ensureMembersAreDefined(){if(this.config===void 0)throw new bo.Err("'config' is not defined");if(this.tokenTransfersDataBuilder===void 0)throw new bo.Err("`dataArgsBuilder is not defined`");if(this.tokenComputer===void 0)throw new bo.Err("`tokenComputer is not defined`")}createTransactionForNativeTokenTransfer(e){this.ensureMembersAreDefined();let r=e.data||new Uint8Array;return new Kf.Transaction({sender:e.sender.bech32(),receiver:e.receiver.bech32(),chainID:this.config.chainID,gasLimit:this.computeGasForMoveBalance(this.config,r),data:r,value:e.nativeAmount})}createTransactionForESDTTokenTransfer(e){this.ensureMembersAreDefined();let r=e.tokenTransfers.length;if(r===0)throw new bo.ErrBadUsage("No token transfer has been provided");if(r===1)return this.createSingleESDTTransferTransaction(e);let n=this.tokenTransfersDataBuilder.buildDataPartsForMultiESDTNFTTransfer(e.receiver,e.tokenTransfers),i=this.config.gasLimitMultiESDTNFTTransfer*BigInt(r)+BigInt(LO);return new MO.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:n,gasLimit:i,addDataMovementGas:!0}).build()}createEGLDTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an EGLD transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForNativeTokenTransfer` method.");let r=e.data?.length()||0,n=this.gasEstimator.forEGLDTransfer(r);return new Kf.Transaction({nonce:e.nonce,value:e.value,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||n,data:e.data,chainID:e.chainID})}createESDTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.BigUIntValue(e.tokenTransfer.valueOf())]),n=`ESDTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.receiver,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create an ESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let{argumentsString:r}=new en.ArgSerializer().valuesToString([en.BytesValue.fromUTF8(e.tokenTransfer.tokenIdentifier),new en.U64Value(e.tokenTransfer.nonce),new en.BigUIntValue(e.tokenTransfer.valueOf()),new en.AddressValue(e.destination)]),n=`ESDTNFTTransfer@${r}`,i=new wE.TransactionPayload(n),s=i.length()||0,o=this.gasEstimator.forESDTNFTTransfer(s);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||o,data:i,chainID:e.chainID})}createMultiESDTNFTTransfer(e){if(!this.isGasEstimatorDefined())throw new bo.Err("You are calling a legacy function to create a MultiESDTNFT transfer transaction. If this is your intent, then instantiate the class using a `GasEstimator`. Or, instead, use the new, recommended `createTransactionForESDTTokenTransfer` method.");let r=[new en.AddressValue(e.destination),new en.U16Value(e.tokenTransfers.length)];for(let a of e.tokenTransfers)r.push(en.BytesValue.fromUTF8(a.tokenIdentifier),new en.U64Value(a.nonce),new en.BigUIntValue(a.valueOf()));let{argumentsString:n}=new en.ArgSerializer().valuesToString(r),i=`MultiESDTNFTTransfer@${n}`,s=new wE.TransactionPayload(i),o=s.length()||0,u=this.gasEstimator.forMultiESDTNFTTransfer(o,e.tokenTransfers.length);return new Kf.Transaction({nonce:e.nonce,receiver:e.sender,sender:e.sender,gasPrice:e.gasPrice,gasLimit:e.gasLimit||u,data:s,chainID:e.chainID})}createSingleESDTTransferTransaction(e){this.ensureMembersAreDefined();let r=[],n=e.tokenTransfers[0],i=0n,s=e.receiver;return this.tokenComputer.isFungible(n.token)?(r=this.tokenTransfersDataBuilder.buildDataPartsForESDTTransfer(n),i=this.config.gasLimitESDTTransfer+BigInt(mW)):(r=this.tokenTransfersDataBuilder.buildDataPartsForSingleESDTNFTTransfer(n,s),i=this.config.gasLimitESDTNFTTransfer+BigInt(LO),s=e.sender),new MO.TransactionBuilder({config:this.config,sender:e.sender,receiver:s,dataParts:r,gasLimit:i,addDataMovementGas:!0}).build()}computeGasForMoveBalance(e,r){return e.minGasLimit+e.gasLimitPerByte*BigInt(r.length)}};u0.TransferTransactionsFactory=vE});var UO=D(l0=>{"use strict";h();Object.defineProperty(l0,"__esModule",{value:!0});l0.AccountTransactionsFactory=void 0;var yW=Ve(),c0=gc(),AE=class{constructor(e){this.config=e.config}createTransactionForSavingKeyValue(e){let r="SaveKeyValue",n=this.computeDataPartsForSavingKeyValue(e.keyValuePairs),i=[r,...n],s=this.computeExtraGasForSavingKeyValue(e.keyValuePairs);return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:i,gasLimit:s,addDataMovementGas:!0}).build()}computeExtraGasForSavingKeyValue(e){let r=0n;return e.forEach((n,i)=>{r+=this.config.gasLimitPersistPerByte*BigInt(i.length+n.length)+this.config.gasLimitStorePerByte*BigInt(n.length)}),r+this.config.gasLimitSaveKeyValue}computeDataPartsForSavingKeyValue(e){let r=[];return e.forEach((n,i)=>{r.push(p.Buffer.from(i).toString("hex"),p.Buffer.from(n).toString("hex"))}),r}createTransactionForSettingGuardian(e){let r=["SetGuardian",yW.Address.fromBech32(e.guardianAddress.bech32()).toHex(),p.Buffer.from(e.serviceID).toString("hex")];return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitSetGuardian,addDataMovementGas:!0}).build()}createTransactionForGuardingAccount(e){let r=["GuardAccount"];return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitGuardAccount,addDataMovementGas:!0}).build()}createTransactionForUnguardingAccount(e){let r=["UnGuardAccount"];return new c0.TransactionBuilder({config:this.config,sender:e.sender,receiver:e.sender,dataParts:r,gasLimit:this.config.gasLimitUnguardAccount,addDataMovementGas:!0}).build()}};l0.AccountTransactionsFactory=AE});var f0=D(hn=>{"use strict";h();var wW=hn&&hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qa=hn&&hn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wW(e,t,r)};Object.defineProperty(hn,"__esModule",{value:!0});qa(vO(),hn);qa(xO(),hn);qa(gE(),hn);qa(BO(),hn);qa(yE(),hn);qa(FO(),hn);qa(UO(),hn)});var SE=D(Vn=>{"use strict";h();var vW=Vn&&Vn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),AW=Vn&&Vn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),EW=Vn&&Vn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vW(e,t,r);return AW(e,t),e},bW=Vn&&Vn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.InteractionChecker=void 0;var EE=EW(Ie()),SW=bW((rr(),_e(fr))),bE=class{checkInteraction(e,r){this.checkPayable(e,r),this.checkArguments(e,r)}checkPayable(e,r){let n=!new SW.default(e.getValue().toString()).isZero(),i=r.modifiers.isPayableInEGLD();if(n&&!i)throw new EE.ErrContractInteraction("cannot send EGLD value to non-payable")}checkArguments(e,r){let n=r.input,i=e.getArguments(),s=n.length,o=i.length;if(s!=o)throw new EE.ErrContractInteraction(`bad arguments, expected: ${s}, got: ${o}`);for(let u=0;u{"use strict";h();Object.defineProperty(h0,"__esModule",{value:!0});h0.Query=void 0;var IW=Ve(),TW=fc(),IE=class{constructor(e){this.caller=e.caller||IW.Address.empty(),this.address=e.address,this.func=e.func,this.args=e.args||[],this.value=e.value||0}getEncodedArguments(){return new TW.ArgSerializer().valuesToStrings(this.args)}};h0.Query=IE});var CE=D(d0=>{"use strict";h();Object.defineProperty(d0,"__esModule",{value:!0});d0.Interaction=void 0;var qO=Ve(),_W=nE(),CW=hr(),TE=_a(),VO=f0(),NW=SE(),xW=Wf(),_E=class{constructor(e,r,n){this.nonce=0,this.value="0",this.gasLimit=0,this.gasPrice=void 0,this.chainID="",this.querent=qO.Address.empty(),this.sender=qO.Address.empty(),this.version=CW.TRANSACTION_VERSION_DEFAULT,this.contract=e,this.function=r,this.args=n,this.tokenTransfers=[]}getContractAddress(){return this.contract.getAddress()}getFunction(){return this.function}getEndpoint(){return this.contract.getEndpoint(this.function)}getArguments(){return this.args}getValue(){return this.value}getTokenTransfers(){return this.tokenTransfers}getGasLimit(){return this.gasLimit}getExplicitReceiver(){return this.explicitReceiver}buildTransaction(){_W.Compatibility.guardAddressIsSetAndNonZero(this.sender,"'sender' of interaction","use interaction.withSender()");let e=new VO.TransactionsFactoryConfig({chainID:this.chainID.valueOf()}),n=new VO.SmartContractTransactionsFactory({config:e}).createTransactionForExecute({sender:this.sender,contract:this.contract.getAddress(),function:this.function.valueOf(),gasLimit:BigInt(this.gasLimit.valueOf()),arguments:this.args,nativeTransferAmount:BigInt(this.value.toString()),tokenTransfers:this.tokenTransfers});return n.chainID=this.chainID.valueOf(),n.nonce=BigInt(this.nonce.valueOf()),n.version=this.version,this.gasPrice&&(n.gasPrice=BigInt(this.gasPrice.valueOf())),n}buildQuery(){return new xW.Query({address:this.contract.getAddress(),func:this.function,args:this.args,value:this.value,caller:this.querent})}withValue(e){return this.value=e,this}withSingleESDTTransfer(e){return this.tokenTransfers=[e].map(r=>new TE.TokenTransfer(r)),this}withSingleESDTNFTTransfer(e){return this.tokenTransfers=[e].map(r=>new TE.TokenTransfer(r)),this}withMultiESDTNFTTransfer(e){return this.tokenTransfers=e.map(r=>new TE.TokenTransfer(r)),this}withGasLimit(e){return this.gasLimit=e,this}withGasPrice(e){return this.gasPrice=e,this}withNonce(e){return this.nonce=e,this}useThenIncrementNonceOf(e){return this.withNonce(e.getNonceThenIncrement())}withChainID(e){return this.chainID=e,this}withSender(e){return this.sender=e,this}withVersion(e){return this.version=e,this}withQuerent(e){return this.querent=e,this}withExplicitReceiver(e){return this.explicitReceiver=e,this}check(){return new NW.InteractionChecker().checkInteraction(this,this.getEndpoint()),this}};d0.Interaction=_E});var NE=D(kO=>{"use strict";h();Object.defineProperty(kO,"__esModule",{value:!0})});var zO=D(yc=>{"use strict";h();Object.defineProperty(yc,"__esModule",{value:!0});yc.bech32m=yc.bech32=void 0;var g0="qpzry9x8gf2tvdw0s3jn54khce6mua7l",GO={};for(let t=0;t>25;return(t&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function HO(t){let e=1;for(let r=0;r126)return"Invalid prefix ("+t+")";e=mc(e)^n>>5}e=mc(e);for(let r=0;r=r;)s-=r,u.push(i>>s&o);if(n)s>0&&u.push(i<=e)return"Excess padding";if(i<a)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let c=HO(o);if(typeof c=="string")throw new Error(c);let f=o+"1";for(let d=0;d>5)throw new Error("Non 5-bit word");c=mc(c)^w,f+=g0.charAt(w)}for(let d=0;d<6;++d)c=mc(c);c^=e;for(let d=0;d<6;++d){let w=c>>(5-d)*5&31;f+=g0.charAt(w)}return f}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";let a=o.toLowerCase(),c=o.toUpperCase();if(o!==a&&o!==c)return"Mixed-case string "+o;o=a;let f=o.lastIndexOf("1");if(f===-1)return"No separator character for "+o;if(f===0)return"Missing prefix for "+o;let d=o.slice(0,f),w=o.slice(f+1);if(w.length<6)return"Data too short";let A=HO(d);if(typeof A=="string")return A;let T=[];for(let x=0;x=w.length)&&T.push(V)}return A!==e?"Invalid checksum for "+o:{prefix:d,words:T}}function i(o,u){let a=n(o,u);if(typeof a=="object")return a}function s(o,u){let a=n(o,u);if(typeof a=="object")return a;throw new Error(a)}return{decodeUnsafe:i,decode:s,encode:r,toWords:OW,fromWordsUnsafe:DW,fromWords:PW}}yc.bech32=jO("bech32");yc.bech32m=jO("bech32m")});var KO=D(kn=>{"use strict";h();Object.defineProperty(kn,"__esModule",{value:!0});kn.TokenTransferProperties=kn.TransactionMetadataTransfer=kn.TransactionMetadata=kn.TransactionToDecode=kn.TransactionDecoder=void 0;var QO=zO(),OE=class{getTransactionMetadata(e){let r=this.getNormalTransactionMetadata(e),n=this.getEsdtTransactionMetadata(r);if(n)return n;let i=this.getNftTransferMetadata(r);if(i)return i;let s=this.getMultiTransferMetadata(r);return s||r}getNormalTransactionMetadata(e){let r=new Va;if(r.sender=e.sender,r.receiver=e.receiver,r.value=BigInt(e.value),e.data){let i=this.base64Decode(e.data).split("@"),s=i.slice(1);if(s.every(o=>this.isSmartContractArgument(o))&&(r.functionName=i[0],r.functionArgs=s),r.functionName==="relayedTx"&&r.functionArgs&&r.functionArgs.length===1)try{let o=JSON.parse(this.hexToString(r.functionArgs[0]));return o.value=o.value.toString(),o.sender=this.bech32Encode(this.base64ToHex(o.sender)),o.receiver=this.bech32Encode(this.base64ToHex(o.receiver)),this.getNormalTransactionMetadata(o)}catch{}if(r.functionName==="relayedTxV2"&&r.functionArgs&&r.functionArgs.length===4)try{let o=new p0;return o.sender=e.receiver,o.receiver=this.bech32Encode(r.functionArgs[0]),o.data=this.base64Encode(this.hexToString(r.functionArgs[2])),o.value="0",this.getNormalTransactionMetadata(o)}catch{}}return r}getMultiTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="MultiESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<3||!this.isAddressValid(r[0]))return;let n=this.bech32Encode(r[0]),i=this.hexToNumber(r[1]),s=new Va;s.transfers||(s.transfers=[]);let o=2;for(let u=0;uo&&(s.functionName=this.hexToString(r[o++]),s.functionArgs=r.slice(o++)),s}getNftTransferMetadata(e){if(e.sender!==e.receiver||e.functionName!=="ESDTNFTTransfer")return;let r=e.functionArgs;if(!r||r.length<4||!this.isAddressValid(r[3]))return;let n=this.hexToString(r[0]),i=r[1],s=this.hexToBigInt(r[2]),o=this.bech32Encode(r[3]),u=new Va;return u.sender=e.sender,u.receiver=o,u.value=s,r.length>4&&(u.functionName=this.hexToString(r[4]),u.functionArgs=r.slice(5)),u.transfers=[{value:s,properties:{collection:n,identifier:`${n}-${i}`}}],u}base64Encode(e){return p.Buffer.from(e).toString("base64")}base64Decode(e){return p.Buffer.from(e,"base64").toString("binary")}hexToNumber(e){return parseInt(e,16)}getEsdtTransactionMetadata(e){if(e.functionName!=="ESDTTransfer")return;let r=e.functionArgs;if(!r||r.length<2)return;let n=this.hexToString(r[0]),i=this.hexToBigInt(r[1]),s=new Va;return s.sender=e.sender,s.receiver=e.receiver,r.length>2&&(s.functionName=this.hexToString(r[2]),s.functionArgs=r.slice(3)),s.transfers=[{value:i,properties:{identifier:n}}],s.value=i,s}bech32Encode(e){let r=p.Buffer.from(e,"hex"),n=QO.bech32.toWords(r);return QO.bech32.encode("erd",n)}isAddressValid(e){return p.Buffer.from(e,"hex").length==32}isSmartContractArgument(e){return!(!this.isHex(e)||e.length%2!==0)}isHex(e){return new RegExp(/[^a-f0-9]/gi).test(e)===!1}base64ToHex(e){return p.Buffer.from(e,"base64").toString("hex")}hexToString(e){return p.Buffer.from(e,"hex").toString("ascii")}hexToBigInt(e){return BigInt(e?"0x"+e:0)}};kn.TransactionDecoder=OE;var p0=class{constructor(){this.sender="",this.receiver="",this.data="",this.value="0"}};kn.TransactionToDecode=p0;var Va=class{constructor(){this.sender="",this.receiver="",this.value=BigInt(0)}};kn.TransactionMetadata=Va;var DE=class{constructor(){this.value=BigInt(0)}};kn.TransactionMetadataTransfer=DE;var PE=class{};kn.TokenTransferProperties=PE});var RE=D(m0=>{"use strict";h();Object.defineProperty(m0,"__esModule",{value:!0});m0.ReturnCode=void 0;var mt=class t{constructor(e){this.text=e}static fromBuffer(e){let r=e.toString();return new t(r)}toString(){return this.text}valueOf(){return this.text}equals(e){return e?this.text==e.text:!1}isSuccess(){return this.equals(t.Ok)||this.equals(t.None)}};m0.ReturnCode=mt;mt.None=new mt("");mt.Ok=new mt("ok");mt.FunctionNotFound=new mt("function not found");mt.FunctionWrongSignature=new mt("wrong signature for function");mt.ContractNotFound=new mt("contract not found");mt.UserError=new mt("user error");mt.OutOfGas=new mt("out of gas");mt.AccountCollision=new mt("account collision");mt.OutOfFunds=new mt("out of funds");mt.CallStackOverFlow=new mt("call stack overflow");mt.ContractInvalid=new mt("contract invalid");mt.ExecutionFailed=new mt("execution failed");mt.Unknown=new mt("unknown")});var YO=D(y0=>{"use strict";h();Object.defineProperty(y0,"__esModule",{value:!0});y0.ResultsParser=void 0;var RW=KO(),WO=Ve(),$O=Ie(),So=oo(),BW=fc(),wc=RE(),vc;(function(t){t.OnTransactionCompleted="completedTxEvent",t.OnSignalError="signalError",t.OnWriteLog="writeLog"})(vc||(vc={}));var BE;(function(t){t.TooMuchGas="@too much gas provided for processing"})(BE||(BE={}));var MW={argsSerializer:new BW.ArgSerializer},ME=class{constructor(e){e={...MW,...e},this.argsSerializer=e.argsSerializer}parseQueryResponse(e,r){let n=e.getReturnDataParts(),i=this.argsSerializer.buffersToValues(n,r.output);return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:i,firstValue:i[0],secondValue:i[1],thirdValue:i[2],lastValue:i[i.length-1]}}parseUntypedQueryResponse(e){return{returnCode:new wc.ReturnCode(e.returnCode.toString()),returnMessage:e.returnMessage,values:e.getReturnDataParts()}}parseOutcome(e,r){let n=this.parseUntypedOutcome(e);return this.parseOutcomeFromUntypedBundle(n,r)}parseOutcomeFromUntypedBundle(e,r){let n=this.argsSerializer.buffersToValues(e.values,r.output);return{returnCode:e.returnCode,returnMessage:e.returnMessage,values:n,firstValue:n[0],secondValue:n[1],thirdValue:n[2],lastValue:n[n.length-1]}}parseUntypedOutcome(e){let r,n=this.parseTransactionMetadata(e);if(r=this.createBundleOnSimpleMoveBalance(e),r)return So.Logger.trace("parseUntypedOutcome(): on simple move balance"),r;if(r=this.createBundleOnInvalidTransaction(e),r)return So.Logger.trace("parseUntypedOutcome(): on invalid transaction"),r;if(r=this.createBundleOnEasilyFoundResultWithReturnData(e.contractResults),r)return So.Logger.trace("parseUntypedOutcome(): on easily found result with return data"),r;if(r=this.createBundleOnSignalError(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on signal error"),r;if(r=this.createBundleOnTooMuchGasWarning(e.logs),r)return So.Logger.trace("parseUntypedOutcome(): on 'too much gas' warning"),r;if(r=this.createBundleOnWriteLogWhereFirstTopicEqualsAddress(e.logs,e.sender),r)return So.Logger.trace("parseUntypedOutcome(): on writelog with topics[0] == tx.sender"),r;if(r=this.createBundleWithCustomHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with custom heuristics"),r;if(r=this.createBundleWithFallbackHeuristics(e,n),r)return So.Logger.trace("parseUntypedOutcome(): with fallback heuristics"),r;throw new $O.ErrCannotParseContractResults(`transaction ${e.hash.toString()}`)}parseTransactionMetadata(e){return new RW.TransactionDecoder().getTransactionMetadata({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:e.data.toString("base64"),value:e.value.toString()})}createBundleOnSimpleMoveBalance(e){let r=e.contractResults.items.length==0,n=e.logs.events.length==0;return r&&n?{returnCode:wc.ReturnCode.None,returnMessage:wc.ReturnCode.None.toString(),values:[]}:null}createBundleOnInvalidTransaction(e){return e.status.isInvalid()&&e.receipt.data?{returnCode:wc.ReturnCode.OutOfFunds,returnMessage:e.receipt.data,values:[]}:null}createBundleOnEasilyFoundResultWithReturnData(e){let r=e.items.find(o=>o.nonce.valueOf()!=0&&o.data.startsWith("@"));if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),s=r.returnMessage||n.toString();return{returnCode:n,returnMessage:s,values:i}}createBundleOnSignalError(e){let r=e.findSingleOrNoneEvent(vc.OnSignalError);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnTooMuchGasWarning(e){let r=e.findSingleOrNoneEvent(vc.OnWriteLog,u=>u.findFirstOrNoneTopic(a=>a.toString().startsWith(BE.TooMuchGas))!=null);if(!r)return null;let{returnCode:n,returnDataParts:i}=this.sliceDataFieldInParts(r.data),o=r.getLastTopic()?.toString()||n.toString();return{returnCode:n,returnMessage:o,values:i}}createBundleOnWriteLogWhereFirstTopicEqualsAddress(e,r){let n=new WO.Address(r.bech32()).hex(),i=e.findSingleOrNoneEvent(vc.OnWriteLog,a=>a.findFirstOrNoneTopic(c=>c.hex()==n)!=null);if(!i)return null;let{returnCode:s,returnDataParts:o}=this.sliceDataFieldInParts(i.data),u=s.toString();return{returnCode:s,returnMessage:u,values:o}}createBundleWithCustomHeuristics(e,r){return null}createBundleWithFallbackHeuristics(e,r){let n=new WO.Address(r.receiver);for(let i of e.contractResults.items){let s=i.logs.findSingleOrNoneEvent(vc.OnWriteLog,o=>{let u=o.address.bech32()==e.sender.bech32(),a=o.topics[0]?.hex()==n.hex();return u&&a});if(s){let{returnCode:o,returnDataParts:u}=this.sliceDataFieldInParts(s.data),a=o.toString();return{returnCode:o,returnMessage:a,values:u}}}return null}sliceDataFieldInParts(e){let r=1;e.startsWith("ESDTTransfer")&&(r=3);let n=this.argsSerializer.stringToBuffers(e),i=n[r]||p.Buffer.from([]),s=n.slice(r+1);if(i.length==0)throw new $O.ErrCannotParseContractResults("no return code");return{returnCode:wc.ReturnCode.fromBuffer(i),returnDataParts:s}}parseEvent(e,r){let n=e.topics.map(o=>p.Buffer.from(o.valueOf())).slice(1),i=e.dataPayload?.valueOf()||p.Buffer.from([]),s=e.additionalData?.map(o=>p.Buffer.from(o.valueOf()))||[];return s.length===0&&i.length&&s.push(p.Buffer.from(i)),this.doParseEvent({topics:n,dataItems:s,eventDefinition:r})}doParseEvent(e){let r={},n=e.eventDefinition.inputs.filter(u=>u.indexed),i=this.argsSerializer.buffersToValues(e.topics,n);for(let u=0;u!u.indexed),o=this.argsSerializer.buffersToValues(e.dataItems,s);for(let u=0;u{"use strict";h();Object.defineProperty(v0,"__esModule",{value:!0});v0.SmartContract=void 0;var w0=Ve(),LE=nE(),FE=hr(),LW=Ie(),UE=gE(),qE=yE(),FW=Rn(),JO=ZA(),XO=tE(),ZO=CE(),UW=t0(),qW=Wf(),VE=class{constructor(e={}){this.address=w0.Address.empty(),this.methodsExplicit={},this.methods={},this.address=e.address||w0.Address.empty(),this.abi=e.abi,this.abi&&this.setupMethods()}setupMethods(){let e=this,r=this.getAbi();for(let n of r.getEndpoints()){let i=n.name;this.methodsExplicit[i]=function(s){let o=new XO.ContractFunction(i);return new ZO.Interaction(e,o,s||[])},this.methods[i]=function(s){let o=new XO.ContractFunction(i),u=UW.NativeSerializer.nativeToTypedValues(s||[],n);return new ZO.Interaction(e,o,u||[])}}}setAddress(e){this.address=e}getAddress(){return this.address}getAbi(){return FW.guardValueIsSet("abi",this.abi),this.abi}getEndpoint(e){return this.getAbi().getEndpoint(e)}deploy({deployer:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){LE.Compatibility.guardAddressIsSetAndNonZero(e,"'deployer' of SmartContract.deploy()","pass the actual address to deploy()");let c=new qE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new UE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=p.Buffer.from(r.toString(),"hex"),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForDeploy({sender:e,bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??FE.TRANSACTION_MIN_GAS_PRICE),A}getMetadataPropertiesAsObject(e){let r;return e?r=JO.CodeMetadata.fromBytes(p.Buffer.from(e.toString(),"hex")):r=new JO.CodeMetadata,r.toJSON()}upgrade({caller:e,code:r,codeMetadata:n,initArguments:i,value:s,gasLimit:o,gasPrice:u,chainID:a}){LE.Compatibility.guardAddressIsSetAndNonZero(e,"'caller' of SmartContract.upgrade()","pass the actual address to upgrade()"),this.ensureHasAddress();let c=new qE.TransactionsFactoryConfig({chainID:a.valueOf()}),f=new UE.SmartContractTransactionsFactory({config:c,abi:this.abi}),d=Uint8Array.from(p.Buffer.from(r.toString(),"hex")),w=this.getMetadataPropertiesAsObject(n),A=f.createTransactionForUpgrade({sender:e,contract:this.getAddress(),bytecode:d,gasLimit:BigInt(o.valueOf()),arguments:i,isUpgradeable:w.upgradeable,isReadable:w.readable,isPayable:w.payable,isPayableBySmartContract:w.payableBySc});return A.setChainID(a),A.setValue(s??0),A.setGasPrice(u??FE.TRANSACTION_MIN_GAS_PRICE),A}call({func:e,args:r,value:n,gasLimit:i,receiver:s,gasPrice:o,chainID:u,caller:a}){LE.Compatibility.guardAddressIsSetAndNonZero(a,"'caller' of SmartContract.call()","pass the actual address to call()"),this.ensureHasAddress();let c=new qE.TransactionsFactoryConfig({chainID:u.valueOf()}),f=new UE.SmartContractTransactionsFactory({config:c,abi:this.abi});r=r||[],n=n||0;let d=f.createTransactionForExecute({sender:a,contract:s||this.getAddress(),function:e.toString(),gasLimit:BigInt(i.valueOf()),arguments:r});return d.setChainID(u),d.setValue(n),d.setGasPrice(o??FE.TRANSACTION_MIN_GAS_PRICE),d}createQuery({func:e,args:r,value:n,caller:i}){return this.ensureHasAddress(),new qW.Query({address:this.getAddress(),func:e,args:r,value:n,caller:i})}ensureHasAddress(){if(!this.getAddress().bech32())throw new LW.ErrContractHasNoAddress}static computeAddress(e,r){let n=w0.Address.fromBech32(e.bech32());return new w0.AddressComputer().computeContractAddress(n,BigInt(r.valueOf()))}};v0.SmartContract=VE});var tD=D(Io=>{"use strict";h();Object.defineProperty(Io,"__esModule",{value:!0});Io.ContractCallPayloadBuilder=Io.ContractUpgradePayloadBuilder=Io.ContractDeployPayloadBuilder=void 0;var VW=hr(),jE=Ms(),zE=Rn(),kW=fc(),kE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`${e}@${VW.WasmVirtualMachine}@${r}`;return n=QE(n,this.arguments),new jE.TransactionPayload(n)}};Io.ContractDeployPayloadBuilder=kE;var HE=class{constructor(){this.code=null,this.codeMetadata="",this.arguments=[]}setCode(e){return this.code=e,this}setCodeMetadata(e){return this.codeMetadata=e,this}addInitArg(e){return this.arguments.push(e),this}setInitArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("code",this.code);let e=this.code.toString(),r=this.codeMetadata.toString(),n=`upgradeContract@${e}@${r}`;return n=QE(n,this.arguments),new jE.TransactionPayload(n)}};Io.ContractUpgradePayloadBuilder=HE;var GE=class{constructor(){this.contractFunction=null,this.arguments=[]}setFunction(e){return this.contractFunction=e,this}addArg(e){return this.arguments.push(e),this}setArgs(e){return this.arguments=e,this}build(){zE.guardValueIsSet("calledFunction",this.contractFunction);let e=this.contractFunction.toString();return e=QE(e,this.arguments),new jE.TransactionPayload(e)}};Io.ContractCallPayloadBuilder=GE;function QE(t,e){let{argumentsString:r,count:n}=new kW.ArgSerializer().valuesToString(e);return n==0?t:`${t}@${r}`}});var qn=D(Jt=>{"use strict";h();var HW=Jt&&Jt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qr=Jt&&Jt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&HW(e,t,r)};Object.defineProperty(Jt,"__esModule",{value:!0});qr(fc(),Jt);qr(wO(),Jt);qr(jA(),Jt);qr(ZA(),Jt);qr(tE(),Jt);qr(CE(),Jt);qr(SE(),Jt);qr(NE(),Jt);qr(t0(),Jt);qr(Wf(),Jt);qr(YO(),Jt);qr(RE(),Jt);qr(eD(),Jt);qr(tD(),Jt);qr(dr(),Jt)});var Ac=D(or=>{"use strict";h();Object.defineProperty(or,"__esModule",{value:!0});or.gatherAllEvents=or.findEventsByFirstTopic=or.findEventsByIdentifier=or.findEventsByPredicate=or.SmartContractCallOutcome=or.TransactionOutcome=or.SmartContractResult=or.TransactionLogs=or.TransactionEvent=void 0;var KE=class{constructor(e){this.address="",this.identifier="",this.topics=[],this.dataItems=[],Object.assign(this,e)}};or.TransactionEvent=KE;var $f=class{constructor(e){this.address="",this.events=[],Object.assign(this,e)}};or.TransactionLogs=$f;var WE=class{constructor(e){this.sender="",this.receiver="",this.data=new Uint8Array,this.logs=new $f({}),Object.assign(this,e)}};or.SmartContractResult=WE;var $E=class{constructor(e){this.directSmartContractCallOutcome=new A0({}),this.smartContractResults=[],this.logs=new $f({}),Object.assign(this,e)}};or.TransactionOutcome=$E;var A0=class{constructor(e){this.function="",this.returnDataParts=[],this.returnMessage="",this.returnCode="",Object.assign(this,e)}};or.SmartContractCallOutcome=A0;function YE(t,e){return rD(t).filter(e)}or.findEventsByPredicate=YE;function GW(t,e){return YE(t,r=>r.identifier==e)}or.findEventsByIdentifier=GW;function jW(t,e){return YE(t,r=>r.topics[0]?.toString()==e)}or.findEventsByFirstTopic=jW;function rD(t){let e=[];e.push(...t.logs.events);for(let r of t.smartContractResults)e.push(...r.logs.events);return e}or.gatherAllEvents=rD});var XE=D(E0=>{"use strict";h();Object.defineProperty(E0,"__esModule",{value:!0});E0.TransactionsConverter=void 0;var zW=qn(),QW=Xr(),Ec=Ac(),JE=class{transactionToPlainObject(e){return{nonce:Number(e.nonce),value:e.value.toString(),receiver:e.receiver,sender:e.sender,senderUsername:this.toBase64OrUndefined(e.senderUsername),receiverUsername:this.toBase64OrUndefined(e.receiverUsername),gasPrice:Number(e.gasPrice),gasLimit:Number(e.gasLimit),data:this.toBase64OrUndefined(e.data),chainID:e.chainID.valueOf(),version:e.version,options:e.options==0?void 0:e.options,guardian:e.guardian?e.guardian:void 0,signature:this.toHexOrUndefined(e.signature),guardianSignature:this.toHexOrUndefined(e.guardianSignature)}}toBase64OrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("base64"):void 0}toHexOrUndefined(e){return e&&e.length?p.Buffer.from(e).toString("hex"):void 0}plainObjectToTransaction(e){return new QW.Transaction({nonce:BigInt(e.nonce),value:BigInt(e.value||""),receiver:e.receiver,receiverUsername:this.bufferFromBase64(e.receiverUsername).toString(),sender:e.sender,senderUsername:this.bufferFromBase64(e.senderUsername).toString(),guardian:e.guardian,gasPrice:BigInt(e.gasPrice),gasLimit:BigInt(e.gasLimit),data:this.bufferFromBase64(e.data),chainID:String(e.chainID),version:Number(e.version),options:Number(e.options),signature:this.bufferFromHex(e.signature),guardianSignature:this.bufferFromHex(e.guardianSignature)})}bufferFromBase64(e){return p.Buffer.from(e||"","base64")}bufferFromHex(e){return p.Buffer.from(e||"","hex")}transactionOnNetworkToOutcome(e){let n=new zW.ResultsParser().parseUntypedOutcome(e),i=new Ec.SmartContractCallOutcome({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.values}),s=e.contractResults.items.map(u=>this.smartContractResultOnNetworkToSmartContractResult(u)),o=new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(u=>this.eventOnNetworkToEvent(u))});return new Ec.TransactionOutcome({logs:o,smartContractResults:s,directSmartContractCallOutcome:i})}smartContractResultOnNetworkToSmartContractResult(e){return new Ec.SmartContractResult({sender:e.sender.bech32(),receiver:e.receiver.bech32(),data:p.Buffer.from(e.data),logs:new Ec.TransactionLogs({address:e.logs.address.bech32(),events:e.logs.events.map(r=>this.eventOnNetworkToEvent(r))})})}eventOnNetworkToEvent(e){let r=e.dataPayload?.valueOf()||p.Buffer.from(e.data||""),n=e.additionalData?.map(i=>p.Buffer.from(i.valueOf()))||[];return n.length===0&&r.length&&n.push(p.Buffer.from(r)),new Ec.TransactionEvent({address:e.address.bech32(),identifier:e.identifier,topics:e.topics.map(i=>p.Buffer.from(i.hex(),"hex")),dataItems:n})}};E0.TransactionsConverter=JE});var nD=D(Yi=>{"use strict";h();var KW=Yi&&Yi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),WW=Yi&&Yi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$W=Yi&&Yi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&KW(e,t,r);return WW(e,t),e};Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Hash=void 0;var YW=$W(Ie()),ZE=class t{constructor(e){if(!e)this.hash=p.Buffer.from([]);else if(e instanceof p.Buffer)this.hash=e;else if(typeof e=="string")this.hash=p.Buffer.from(e,"hex");else throw new YW.ErrBadType("hash","buffer | string",e)}static empty(){return new t(p.Buffer.from([]))}isEmpty(){return this.hash.length==0}toString(){return this.hex()}hex(){return this.hash.toString("hex")}valueOf(){return this.hash}};Yi.Hash=ZE});var Yf=D(Hn=>{"use strict";h();var JW=Hn&&Hn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),XW=Hn&&Hn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ZW=Hn&&Hn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&JW(e,t,r);return XW(e,t),e};Object.defineProperty(Hn,"__esModule",{value:!0});Hn.interpretSignatureAsBuffer=Hn.Signature=void 0;var iD=ZW(Ie()),sD=64,eb=class t{constructor(e){if(this.valueHex="",!!e){if(typeof e=="string")return t.fromHex(e);if(e instanceof p.Buffer)return t.fromBuffer(e)}}static empty(){return new t}static fromHex(e){if(e.startsWith("0x")&&(e=e.slice(2)),!t.isValidHex(e))throw new iD.ErrSignatureCannotCreate(e);return t.fromValidHex(e)}static isValidHex(e){return p.Buffer.from(e,"hex").length==sD}static fromValidHex(e){let r=new t;return r.valueHex=e,r}static fromBuffer(e){if(e.length!=sD)throw new iD.ErrSignatureCannotCreate(e);return t.fromValidHex(e.toString("hex"))}hex(){return this.valueHex}};Hn.Signature=eb;function e$(t){if(ArrayBuffer.isView(t))return p.Buffer.from(t);if(t.hex!=null)return p.Buffer.from(t.hex(),"hex");throw new Error(`Object cannot be interpreted as a signature: ${t}`)}Hn.interpretSignatureAsBuffer=e$});var aD=D((nwe,oD)=>{"use strict";h();oD.exports=t$;function t$(t,e){for(var r=new Array(arguments.length-1),n=0,i=2,s=!0;i{"use strict";h();var b0=lD;b0.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var bc=new Array(64),cD=new Array(123);for(mi=0;mi<64;)cD[bc[mi]=mi<26?mi+65:mi<52?mi+71:mi<62?mi-4:mi-59|43]=mi++;var mi;b0.encode=function(e,r,n){for(var i=null,s=[],o=0,u=0,a;r>2],a=(c&3)<<4,u=1;break;case 1:s[o++]=bc[a|c>>4],a=(c&15)<<2,u=2;break;case 2:s[o++]=bc[a|c>>6],s[o++]=bc[c&63],u=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),o=0)}return u&&(s[o++]=bc[a],s[o++]=61,u===1&&(s[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))};var uD="invalid encoding";b0.decode=function(e,r,n){for(var i=n,s=0,o,u=0;u1)break;if((a=cD[a])===void 0)throw Error(uD);switch(s){case 0:o=a,s=1;break;case 1:r[n++]=o<<2|(a&48)>>4,o=a,s=2;break;case 2:r[n++]=(o&15)<<4|(a&60)>>2,o=a,s=3;break;case 3:r[n++]=(o&3)<<6|a,s=0;break}}if(s===1)throw Error(uD);return n-i};b0.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var dD=D((awe,hD)=>{"use strict";h();hD.exports=S0;function S0(){this._listeners={}}S0.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};S0.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],i=0;i{"use strict";h();vD.exports=gD(gD);function gD(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3]}function s(a,c,f){e[0]=a,c[f]=r[3],c[f+1]=r[2],c[f+2]=r[1],c[f+3]=r[0]}t.writeFloatLE=n?i:s,t.writeFloatBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],e[0]}function u(a,c){return r[3]=a[c],r[2]=a[c+1],r[1]=a[c+2],r[0]=a[c+3],e[0]}t.readFloatLE=n?o:u,t.readFloatBE=n?u:o}():function(){function e(n,i,s,o){var u=i<0?1:0;if(u&&(i=-i),i===0)n(1/i>0?0:2147483648,s,o);else if(isNaN(i))n(2143289344,s,o);else if(i>34028234663852886e22)n((u<<31|2139095040)>>>0,s,o);else if(i<11754943508222875e-54)n((u<<31|Math.round(i/1401298464324817e-60))>>>0,s,o);else{var a=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-a)*8388608)&8388607;n((u<<31|a+127<<23|c)>>>0,s,o)}}t.writeFloatLE=e.bind(null,pD),t.writeFloatBE=e.bind(null,mD);function r(n,i,s){var o=n(i,s),u=(o>>31)*2+1,a=o>>>23&255,c=o&8388607;return a===255?c?NaN:u*(1/0):a===0?u*1401298464324817e-60*c:u*Math.pow(2,a-150)*(c+8388608)}t.readFloatLE=r.bind(null,yD),t.readFloatBE=r.bind(null,wD)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function i(a,c,f){e[0]=a,c[f]=r[0],c[f+1]=r[1],c[f+2]=r[2],c[f+3]=r[3],c[f+4]=r[4],c[f+5]=r[5],c[f+6]=r[6],c[f+7]=r[7]}function s(a,c,f){e[0]=a,c[f]=r[7],c[f+1]=r[6],c[f+2]=r[5],c[f+3]=r[4],c[f+4]=r[3],c[f+5]=r[2],c[f+6]=r[1],c[f+7]=r[0]}t.writeDoubleLE=n?i:s,t.writeDoubleBE=n?s:i;function o(a,c){return r[0]=a[c],r[1]=a[c+1],r[2]=a[c+2],r[3]=a[c+3],r[4]=a[c+4],r[5]=a[c+5],r[6]=a[c+6],r[7]=a[c+7],e[0]}function u(a,c){return r[7]=a[c],r[6]=a[c+1],r[5]=a[c+2],r[4]=a[c+3],r[3]=a[c+4],r[2]=a[c+5],r[1]=a[c+6],r[0]=a[c+7],e[0]}t.readDoubleLE=n?o:u,t.readDoubleBE=n?u:o}():function(){function e(n,i,s,o,u,a){var c=o<0?1:0;if(c&&(o=-o),o===0)n(0,u,a+i),n(1/o>0?0:2147483648,u,a+s);else if(isNaN(o))n(0,u,a+i),n(2146959360,u,a+s);else if(o>17976931348623157e292)n(0,u,a+i),n((c<<31|2146435072)>>>0,u,a+s);else{var f;if(o<22250738585072014e-324)f=o/5e-324,n(f>>>0,u,a+i),n((c<<31|f/4294967296)>>>0,u,a+s);else{var d=Math.floor(Math.log(o)/Math.LN2);d===1024&&(d=1023),f=o*Math.pow(2,-d),n(f*4503599627370496>>>0,u,a+i),n((c<<31|d+1023<<20|f*1048576&1048575)>>>0,u,a+s)}}}t.writeDoubleLE=e.bind(null,pD,0,4),t.writeDoubleBE=e.bind(null,mD,4,0);function r(n,i,s,o,u){var a=n(o,u+i),c=n(o,u+s),f=(c>>31)*2+1,d=c>>>20&2047,w=4294967296*(c&1048575)+a;return d===2047?w?NaN:f*(1/0):d===0?f*5e-324*w:f*Math.pow(2,d-1075)*(w+4503599627370496)}t.readDoubleLE=r.bind(null,yD,0,4),t.readDoubleBE=r.bind(null,wD,4,0)}(),t}function pD(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function mD(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function yD(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function wD(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var ED=D((exports,module)=>{"use strict";h();module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var SD=D(bD=>{"use strict";h();var tb=bD;tb.length=function(e){for(var r=0,n=0,i=0;i191&&a<224?o[u++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,o[u++]=55296+(a>>10),o[u++]=56320+(a&1023)):o[u++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,u>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),u=0);return s?(u&&s.push(String.fromCharCode.apply(String,o.slice(0,u))),s.join("")):String.fromCharCode.apply(String,o.slice(0,u))};tb.write=function(e,r,n){for(var i=n,s,o,u=0;u>6|192,r[n++]=s&63|128):(s&64512)===55296&&((o=e.charCodeAt(u+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++u,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-i}});var TD=D((gwe,ID)=>{"use strict";h();ID.exports=r$;function r$(t,e,r){var n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);var c=e.call(s,o,o+=a);return o&7&&(o=(o|7)+1),c}}});var CD=D((mwe,_D)=>{"use strict";h();_D.exports=yr;var Jf=_o();function yr(t,e){this.lo=t>>>0,this.hi=e>>>0}var ka=yr.zero=new yr(0,0);ka.toNumber=function(){return 0};ka.zzEncode=ka.zzDecode=function(){return this};ka.length=function(){return 1};var n$=yr.zeroHash="\0\0\0\0\0\0\0\0";yr.fromNumber=function(e){if(e===0)return ka;var r=e<0;r&&(e=-e);var n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new yr(n,i)};yr.from=function(e){if(typeof e=="number")return yr.fromNumber(e);if(Jf.isString(e))if(Jf.Long)e=Jf.Long.fromString(e);else return yr.fromNumber(parseInt(e,10));return e.low||e.high?new yr(e.low>>>0,e.high>>>0):ka};yr.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};yr.prototype.toLong=function(e){return Jf.Long?new Jf.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var To=String.prototype.charCodeAt;yr.fromHash=function(e){return e===n$?ka:new yr((To.call(e,0)|To.call(e,1)<<8|To.call(e,2)<<16|To.call(e,3)<<24)>>>0,(To.call(e,4)|To.call(e,5)<<8|To.call(e,6)<<16|To.call(e,7)<<24)>>>0)};yr.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};yr.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};yr.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};yr.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var _o=D(rb=>{"use strict";h();var we=rb;we.asPromise=aD();we.base64=fD();we.EventEmitter=dD();we.float=AD();we.inquire=ED();we.utf8=SD();we.pool=TD();we.LongBits=CD();we.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);we.global=we.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||rb;we.emptyArray=Object.freeze?Object.freeze([]):[];we.emptyObject=Object.freeze?Object.freeze({}):{};we.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};we.isString=function(e){return typeof e=="string"||e instanceof String};we.isObject=function(e){return e&&typeof e=="object"};we.isset=we.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};we.Buffer=function(){try{var t=we.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();we._Buffer_from=null;we._Buffer_allocUnsafe=null;we.newBuffer=function(e){return typeof e=="number"?we.Buffer?we._Buffer_allocUnsafe(e):new we.Array(e):we.Buffer?we._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};we.Array=typeof Uint8Array<"u"?Uint8Array:Array;we.Long=we.global.dcodeIO&&we.global.dcodeIO.Long||we.global.Long||we.inquire("long");we.key2Re=/^true|false|0|1$/;we.key32Re=/^-?(?:0|[1-9][0-9]*)$/;we.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;we.longToHash=function(e){return e?we.LongBits.from(e).toHash():we.LongBits.zeroHash};we.longFromHash=function(e,r){var n=we.LongBits.fromHash(e);return we.Long?we.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function ND(t,e,r){for(var n=Object.keys(e),i=0;i-1;--s)if(r[i[s]]===1&&this[i[s]]!==void 0&&this[i[s]]!==null)return i[s]}};we.oneOfSetter=function(e){return function(r){for(var n=0;n{"use strict";h();RD.exports=Ue;var Gn=_o(),nb,I0=Gn.LongBits,OD=Gn.base64,DD=Gn.utf8;function Xf(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function sb(){}function i$(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Ue(){this.len=0,this.head=new Xf(sb,0,0),this.tail=this.head,this.states=null}var PD=function(){return Gn.Buffer?function(){return(Ue.create=function(){return new nb})()}:function(){return new Ue}};Ue.create=PD();Ue.alloc=function(e){return new Gn.Array(e)};Gn.Array!==Array&&(Ue.alloc=Gn.pool(Ue.alloc,Gn.Array.prototype.subarray));Ue.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Xf(e,r,n),this.len+=r,this};function ob(t,e,r){e[r]=t&255}function s$(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function ab(t,e){this.len=t,this.next=void 0,this.val=e}ab.prototype=Object.create(Xf.prototype);ab.prototype.fn=s$;Ue.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ab((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};Ue.prototype.int32=function(e){return e<0?this._push(ub,10,I0.fromNumber(e)):this.uint32(e)};Ue.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function ub(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}Ue.prototype.uint64=function(e){var r=I0.from(e);return this._push(ub,r.length(),r)};Ue.prototype.int64=Ue.prototype.uint64;Ue.prototype.sint64=function(e){var r=I0.from(e).zzEncode();return this._push(ub,r.length(),r)};Ue.prototype.bool=function(e){return this._push(ob,1,e?1:0)};function ib(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}Ue.prototype.fixed32=function(e){return this._push(ib,4,e>>>0)};Ue.prototype.sfixed32=Ue.prototype.fixed32;Ue.prototype.fixed64=function(e){var r=I0.from(e);return this._push(ib,4,r.lo)._push(ib,4,r.hi)};Ue.prototype.sfixed64=Ue.prototype.fixed64;Ue.prototype.float=function(e){return this._push(Gn.float.writeFloatLE,4,e)};Ue.prototype.double=function(e){return this._push(Gn.float.writeDoubleLE,8,e)};var o$=Gn.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var i=0;i>>0;if(!r)return this._push(ob,1,0);if(Gn.isString(e)){var n=Ue.alloc(r=OD.length(e));OD.decode(e,n,0),e=n}return this.uint32(r)._push(o$,r,e)};Ue.prototype.string=function(e){var r=DD.length(e);return r?this.uint32(r)._push(DD.write,r,e):this._push(ob,1,0)};Ue.prototype.fork=function(){return this.states=new i$(this),this.head=this.tail=new Xf(sb,0,0),this.len=0,this};Ue.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xf(sb,0,0),this.len=0),this};Ue.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};Ue.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};Ue._configure=function(t){nb=t,Ue.create=PD(),nb._configure()}});var LD=D((bwe,MD)=>{"use strict";h();MD.exports=Ji;var BD=cb();(Ji.prototype=Object.create(BD.prototype)).constructor=Ji;var Co=_o();function Ji(){BD.call(this)}Ji._configure=function(){Ji.alloc=Co._Buffer_allocUnsafe,Ji.writeBytesBuffer=Co.Buffer&&Co.Buffer.prototype instanceof Uint8Array&&Co.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var i=0;i>>0;return this.uint32(r),r&&this._push(Ji.writeBytesBuffer,r,e),this};function a$(t,e,r){t.length<40?Co.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ji.prototype.string=function(e){var r=Co.Buffer.byteLength(e);return this.uint32(r),r&&this._push(a$,r,e),this};Ji._configure()});var hb=D((Iwe,kD)=>{"use strict";h();kD.exports=Xt;var yi=_o(),fb,qD=yi.LongBits,u$=yi.utf8;function wi(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function Xt(t){this.buf=t,this.pos=0,this.len=t.length}var FD=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Xt(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Xt(e);throw Error("illegal buffer")},VD=function(){return yi.Buffer?function(r){return(Xt.create=function(i){return yi.Buffer.isBuffer(i)?new fb(i):FD(i)})(r)}:FD};Xt.create=VD();Xt.prototype._slice=yi.Array.prototype.subarray||yi.Array.prototype.slice;Xt.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,wi(this,10);return e}}();Xt.prototype.int32=function(){return this.uint32()|0};Xt.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function lb(){var t=new qD(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw wi(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw wi(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}Xt.prototype.bool=function(){return this.uint32()!==0};function T0(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}Xt.prototype.fixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return T0(this.buf,this.pos+=4)};Xt.prototype.sfixed32=function(){if(this.pos+4>this.len)throw wi(this,4);return T0(this.buf,this.pos+=4)|0};function UD(){if(this.pos+8>this.len)throw wi(this,8);return new qD(T0(this.buf,this.pos+=4),T0(this.buf,this.pos+=4))}Xt.prototype.float=function(){if(this.pos+4>this.len)throw wi(this,4);var e=yi.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};Xt.prototype.double=function(){if(this.pos+8>this.len)throw wi(this,4);var e=yi.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};Xt.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw wi(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(r,n);if(r===n){var i=yi.Buffer;return i?i.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,r,n)};Xt.prototype.string=function(){var e=this.bytes();return u$.read(e,0,e.length)};Xt.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw wi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw wi(this);while(this.buf[this.pos++]&128);return this};Xt.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};Xt._configure=function(t){fb=t,Xt.create=VD(),fb._configure();var e=yi.Long?"toLong":"toNumber";yi.merge(Xt.prototype,{int64:function(){return lb.call(this)[e](!1)},uint64:function(){return lb.call(this)[e](!0)},sint64:function(){return lb.call(this).zzDecode()[e](!1)},fixed64:function(){return UD.call(this)[e](!0)},sfixed64:function(){return UD.call(this)[e](!1)}})}});var zD=D((_we,jD)=>{"use strict";h();jD.exports=Ha;var GD=hb();(Ha.prototype=Object.create(GD.prototype)).constructor=Ha;var HD=_o();function Ha(t){GD.call(this,t)}Ha._configure=function(){HD.Buffer&&(Ha.prototype._slice=HD.Buffer.prototype.slice)};Ha.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Ha._configure()});var KD=D((Nwe,QD)=>{"use strict";h();QD.exports=Zf;var db=_o();(Zf.prototype=Object.create(db.EventEmitter.prototype)).constructor=Zf;function Zf(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");db.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Zf.prototype.rpcCall=function t(e,r,n,i,s){if(!i)throw TypeError("request must be specified");var o=this;if(!s)return db.asPromise(t,o,e,r,n,i);if(!o.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return o.rpcImpl(e,r[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(a,c){if(a)return o.emit("error",a,e),s(a);if(c===null){o.end(!0);return}if(!(c instanceof n))try{c=n[o.responseDelimited?"decodeDelimited":"decode"](c)}catch(f){return o.emit("error",f,e),s(f)}return o.emit("data",c,e),s(null,c)})}catch(u){o.emit("error",u,e),setTimeout(function(){s(u)},0);return}};Zf.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var $D=D(WD=>{"use strict";h();var c$=WD;c$.Service=KD()});var JD=D((Pwe,YD)=>{"use strict";h();YD.exports={}});var e8=D(ZD=>{"use strict";h();var tn=ZD;tn.build="minimal";tn.Writer=cb();tn.BufferWriter=LD();tn.Reader=hb();tn.BufferReader=zD();tn.util=_o();tn.rpc=$D();tn.roots=JD();tn.configure=XD;function XD(){tn.util._configure(),tn.Writer._configure(tn.BufferWriter),tn.Reader._configure(tn.BufferReader)}XD()});var r8=D((Lwe,t8)=>{"use strict";h();t8.exports=e8()});var i8=D((n8,eh)=>{"use strict";h();(function(t,e){typeof define=="function"&&define.amd?define(["protobufjs/minimal"],e):typeof Pd=="function"&&typeof eh=="object"&&eh&&eh.exports&&(eh.exports=e(r8()))})(n8,function(t){"use strict";var e=t.Reader,r=t.Writer,n=t.util,i=t.roots.default||(t.roots.default={});return i.proto=function(){var s={};return s.Transaction=function(){function o(u){if(u)for(var a=Object.keys(u),c=0;c>>3){case 1:{d.Nonce=a.uint64();break}case 2:{d.Value=a.bytes();break}case 3:{d.RcvAddr=a.bytes();break}case 4:{d.RcvUserName=a.bytes();break}case 5:{d.SndAddr=a.bytes();break}case 6:{d.SndUserName=a.bytes();break}case 7:{d.GasPrice=a.uint64();break}case 8:{d.GasLimit=a.uint64();break}case 9:{d.Data=a.bytes();break}case 10:{d.ChainID=a.bytes();break}case 11:{d.Version=a.uint32();break}case 12:{d.Signature=a.bytes();break}case 13:{d.Options=a.uint32();break}case 14:{d.GuardianAddr=a.bytes();break}case 15:{d.GuardianSignature=a.bytes();break}default:a.skipType(w&7);break}}return d},o.decodeDelimited=function(a){return a instanceof e||(a=new e(a)),this.decode(a,a.uint32())},o.verify=function(a){return typeof a!="object"||a===null?"object expected":a.Nonce!=null&&a.hasOwnProperty("Nonce")&&!n.isInteger(a.Nonce)&&!(a.Nonce&&n.isInteger(a.Nonce.low)&&n.isInteger(a.Nonce.high))?"Nonce: integer|Long expected":a.Value!=null&&a.hasOwnProperty("Value")&&!(a.Value&&typeof a.Value.length=="number"||n.isString(a.Value))?"Value: buffer expected":a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&!(a.RcvAddr&&typeof a.RcvAddr.length=="number"||n.isString(a.RcvAddr))?"RcvAddr: buffer expected":a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&!(a.RcvUserName&&typeof a.RcvUserName.length=="number"||n.isString(a.RcvUserName))?"RcvUserName: buffer expected":a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&!(a.SndAddr&&typeof a.SndAddr.length=="number"||n.isString(a.SndAddr))?"SndAddr: buffer expected":a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&!(a.SndUserName&&typeof a.SndUserName.length=="number"||n.isString(a.SndUserName))?"SndUserName: buffer expected":a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&!n.isInteger(a.GasPrice)&&!(a.GasPrice&&n.isInteger(a.GasPrice.low)&&n.isInteger(a.GasPrice.high))?"GasPrice: integer|Long expected":a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&!n.isInteger(a.GasLimit)&&!(a.GasLimit&&n.isInteger(a.GasLimit.low)&&n.isInteger(a.GasLimit.high))?"GasLimit: integer|Long expected":a.Data!=null&&a.hasOwnProperty("Data")&&!(a.Data&&typeof a.Data.length=="number"||n.isString(a.Data))?"Data: buffer expected":a.ChainID!=null&&a.hasOwnProperty("ChainID")&&!(a.ChainID&&typeof a.ChainID.length=="number"||n.isString(a.ChainID))?"ChainID: buffer expected":a.Version!=null&&a.hasOwnProperty("Version")&&!n.isInteger(a.Version)?"Version: integer expected":a.Signature!=null&&a.hasOwnProperty("Signature")&&!(a.Signature&&typeof a.Signature.length=="number"||n.isString(a.Signature))?"Signature: buffer expected":a.Options!=null&&a.hasOwnProperty("Options")&&!n.isInteger(a.Options)?"Options: integer expected":a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&!(a.GuardianAddr&&typeof a.GuardianAddr.length=="number"||n.isString(a.GuardianAddr))?"GuardianAddr: buffer expected":a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&!(a.GuardianSignature&&typeof a.GuardianSignature.length=="number"||n.isString(a.GuardianSignature))?"GuardianSignature: buffer expected":null},o.fromObject=function(a){if(a instanceof i.proto.Transaction)return a;var c=new i.proto.Transaction;return a.Nonce!=null&&(n.Long?(c.Nonce=n.Long.fromValue(a.Nonce)).unsigned=!0:typeof a.Nonce=="string"?c.Nonce=parseInt(a.Nonce,10):typeof a.Nonce=="number"?c.Nonce=a.Nonce:typeof a.Nonce=="object"&&(c.Nonce=new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0))),a.Value!=null&&(typeof a.Value=="string"?n.base64.decode(a.Value,c.Value=n.newBuffer(n.base64.length(a.Value)),0):a.Value.length>=0&&(c.Value=a.Value)),a.RcvAddr!=null&&(typeof a.RcvAddr=="string"?n.base64.decode(a.RcvAddr,c.RcvAddr=n.newBuffer(n.base64.length(a.RcvAddr)),0):a.RcvAddr.length>=0&&(c.RcvAddr=a.RcvAddr)),a.RcvUserName!=null&&(typeof a.RcvUserName=="string"?n.base64.decode(a.RcvUserName,c.RcvUserName=n.newBuffer(n.base64.length(a.RcvUserName)),0):a.RcvUserName.length>=0&&(c.RcvUserName=a.RcvUserName)),a.SndAddr!=null&&(typeof a.SndAddr=="string"?n.base64.decode(a.SndAddr,c.SndAddr=n.newBuffer(n.base64.length(a.SndAddr)),0):a.SndAddr.length>=0&&(c.SndAddr=a.SndAddr)),a.SndUserName!=null&&(typeof a.SndUserName=="string"?n.base64.decode(a.SndUserName,c.SndUserName=n.newBuffer(n.base64.length(a.SndUserName)),0):a.SndUserName.length>=0&&(c.SndUserName=a.SndUserName)),a.GasPrice!=null&&(n.Long?(c.GasPrice=n.Long.fromValue(a.GasPrice)).unsigned=!0:typeof a.GasPrice=="string"?c.GasPrice=parseInt(a.GasPrice,10):typeof a.GasPrice=="number"?c.GasPrice=a.GasPrice:typeof a.GasPrice=="object"&&(c.GasPrice=new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0))),a.GasLimit!=null&&(n.Long?(c.GasLimit=n.Long.fromValue(a.GasLimit)).unsigned=!0:typeof a.GasLimit=="string"?c.GasLimit=parseInt(a.GasLimit,10):typeof a.GasLimit=="number"?c.GasLimit=a.GasLimit:typeof a.GasLimit=="object"&&(c.GasLimit=new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0))),a.Data!=null&&(typeof a.Data=="string"?n.base64.decode(a.Data,c.Data=n.newBuffer(n.base64.length(a.Data)),0):a.Data.length>=0&&(c.Data=a.Data)),a.ChainID!=null&&(typeof a.ChainID=="string"?n.base64.decode(a.ChainID,c.ChainID=n.newBuffer(n.base64.length(a.ChainID)),0):a.ChainID.length>=0&&(c.ChainID=a.ChainID)),a.Version!=null&&(c.Version=a.Version>>>0),a.Signature!=null&&(typeof a.Signature=="string"?n.base64.decode(a.Signature,c.Signature=n.newBuffer(n.base64.length(a.Signature)),0):a.Signature.length>=0&&(c.Signature=a.Signature)),a.Options!=null&&(c.Options=a.Options>>>0),a.GuardianAddr!=null&&(typeof a.GuardianAddr=="string"?n.base64.decode(a.GuardianAddr,c.GuardianAddr=n.newBuffer(n.base64.length(a.GuardianAddr)),0):a.GuardianAddr.length>=0&&(c.GuardianAddr=a.GuardianAddr)),a.GuardianSignature!=null&&(typeof a.GuardianSignature=="string"?n.base64.decode(a.GuardianSignature,c.GuardianSignature=n.newBuffer(n.base64.length(a.GuardianSignature)),0):a.GuardianSignature.length>=0&&(c.GuardianSignature=a.GuardianSignature)),c},o.toObject=function(a,c){c||(c={});var f={};if(c.defaults){if(n.Long){var d=new n.Long(0,0,!0);f.Nonce=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.Nonce=c.longs===String?"0":0;if(c.bytes===String?f.Value="":(f.Value=[],c.bytes!==Array&&(f.Value=n.newBuffer(f.Value))),c.bytes===String?f.RcvAddr="":(f.RcvAddr=[],c.bytes!==Array&&(f.RcvAddr=n.newBuffer(f.RcvAddr))),c.bytes===String?f.RcvUserName="":(f.RcvUserName=[],c.bytes!==Array&&(f.RcvUserName=n.newBuffer(f.RcvUserName))),c.bytes===String?f.SndAddr="":(f.SndAddr=[],c.bytes!==Array&&(f.SndAddr=n.newBuffer(f.SndAddr))),c.bytes===String?f.SndUserName="":(f.SndUserName=[],c.bytes!==Array&&(f.SndUserName=n.newBuffer(f.SndUserName))),n.Long){var d=new n.Long(0,0,!0);f.GasPrice=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasPrice=c.longs===String?"0":0;if(n.Long){var d=new n.Long(0,0,!0);f.GasLimit=c.longs===String?d.toString():c.longs===Number?d.toNumber():d}else f.GasLimit=c.longs===String?"0":0;c.bytes===String?f.Data="":(f.Data=[],c.bytes!==Array&&(f.Data=n.newBuffer(f.Data))),c.bytes===String?f.ChainID="":(f.ChainID=[],c.bytes!==Array&&(f.ChainID=n.newBuffer(f.ChainID))),f.Version=0,c.bytes===String?f.Signature="":(f.Signature=[],c.bytes!==Array&&(f.Signature=n.newBuffer(f.Signature))),f.Options=0,c.bytes===String?f.GuardianAddr="":(f.GuardianAddr=[],c.bytes!==Array&&(f.GuardianAddr=n.newBuffer(f.GuardianAddr))),c.bytes===String?f.GuardianSignature="":(f.GuardianSignature=[],c.bytes!==Array&&(f.GuardianSignature=n.newBuffer(f.GuardianSignature)))}return a.Nonce!=null&&a.hasOwnProperty("Nonce")&&(typeof a.Nonce=="number"?f.Nonce=c.longs===String?String(a.Nonce):a.Nonce:f.Nonce=c.longs===String?n.Long.prototype.toString.call(a.Nonce):c.longs===Number?new n.LongBits(a.Nonce.low>>>0,a.Nonce.high>>>0).toNumber(!0):a.Nonce),a.Value!=null&&a.hasOwnProperty("Value")&&(f.Value=c.bytes===String?n.base64.encode(a.Value,0,a.Value.length):c.bytes===Array?Array.prototype.slice.call(a.Value):a.Value),a.RcvAddr!=null&&a.hasOwnProperty("RcvAddr")&&(f.RcvAddr=c.bytes===String?n.base64.encode(a.RcvAddr,0,a.RcvAddr.length):c.bytes===Array?Array.prototype.slice.call(a.RcvAddr):a.RcvAddr),a.RcvUserName!=null&&a.hasOwnProperty("RcvUserName")&&(f.RcvUserName=c.bytes===String?n.base64.encode(a.RcvUserName,0,a.RcvUserName.length):c.bytes===Array?Array.prototype.slice.call(a.RcvUserName):a.RcvUserName),a.SndAddr!=null&&a.hasOwnProperty("SndAddr")&&(f.SndAddr=c.bytes===String?n.base64.encode(a.SndAddr,0,a.SndAddr.length):c.bytes===Array?Array.prototype.slice.call(a.SndAddr):a.SndAddr),a.SndUserName!=null&&a.hasOwnProperty("SndUserName")&&(f.SndUserName=c.bytes===String?n.base64.encode(a.SndUserName,0,a.SndUserName.length):c.bytes===Array?Array.prototype.slice.call(a.SndUserName):a.SndUserName),a.GasPrice!=null&&a.hasOwnProperty("GasPrice")&&(typeof a.GasPrice=="number"?f.GasPrice=c.longs===String?String(a.GasPrice):a.GasPrice:f.GasPrice=c.longs===String?n.Long.prototype.toString.call(a.GasPrice):c.longs===Number?new n.LongBits(a.GasPrice.low>>>0,a.GasPrice.high>>>0).toNumber(!0):a.GasPrice),a.GasLimit!=null&&a.hasOwnProperty("GasLimit")&&(typeof a.GasLimit=="number"?f.GasLimit=c.longs===String?String(a.GasLimit):a.GasLimit:f.GasLimit=c.longs===String?n.Long.prototype.toString.call(a.GasLimit):c.longs===Number?new n.LongBits(a.GasLimit.low>>>0,a.GasLimit.high>>>0).toNumber(!0):a.GasLimit),a.Data!=null&&a.hasOwnProperty("Data")&&(f.Data=c.bytes===String?n.base64.encode(a.Data,0,a.Data.length):c.bytes===Array?Array.prototype.slice.call(a.Data):a.Data),a.ChainID!=null&&a.hasOwnProperty("ChainID")&&(f.ChainID=c.bytes===String?n.base64.encode(a.ChainID,0,a.ChainID.length):c.bytes===Array?Array.prototype.slice.call(a.ChainID):a.ChainID),a.Version!=null&&a.hasOwnProperty("Version")&&(f.Version=a.Version),a.Signature!=null&&a.hasOwnProperty("Signature")&&(f.Signature=c.bytes===String?n.base64.encode(a.Signature,0,a.Signature.length):c.bytes===Array?Array.prototype.slice.call(a.Signature):a.Signature),a.Options!=null&&a.hasOwnProperty("Options")&&(f.Options=a.Options),a.GuardianAddr!=null&&a.hasOwnProperty("GuardianAddr")&&(f.GuardianAddr=c.bytes===String?n.base64.encode(a.GuardianAddr,0,a.GuardianAddr.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianAddr):a.GuardianAddr),a.GuardianSignature!=null&&a.hasOwnProperty("GuardianSignature")&&(f.GuardianSignature=c.bytes===String?n.base64.encode(a.GuardianSignature,0,a.GuardianSignature.length):c.bytes===Array?Array.prototype.slice.call(a.GuardianSignature):a.GuardianSignature),f},o.prototype.toJSON=function(){return this.constructor.toObject(this,t.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/proto.Transaction"},o}(),s}(),i})});var s8=D(jn=>{"use strict";h();var l$=jn&&jn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),f$=jn&&jn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),h$=jn&&jn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&l$(e,t,r);return f$(e,t),e},d$=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.ProtoSerializer=void 0;var g$=d$((rr(),_e(fr))),gb=Ve(),p$=hr(),m$=h$(Ie()),y$=Bu(),pb=class{serializeTransaction(e){let r=i8().proto,n=new gb.Address(e.getReceiver().bech32()).pubkey(),i=new gb.Address(e.getSender().bech32()).pubkey(),s=new r.Transaction({Nonce:e.getNonce().valueOf()?e.getNonce().valueOf():void 0,Value:this.serializeTransactionValue(e.getValue()),RcvAddr:n,RcvUserName:e.getReceiverUsername()?p.Buffer.from(e.getReceiverUsername()).toString("base64"):void 0,SndAddr:i,SndUserName:e.getSenderUsername()?p.Buffer.from(e.getSenderUsername()).toString("base64"):void 0,GasPrice:e.getGasPrice().valueOf(),GasLimit:e.getGasLimit().valueOf(),Data:e.getData().length()==0?null:e.getData().valueOf(),ChainID:p.Buffer.from(e.getChainID().valueOf()),Version:e.getVersion().valueOf(),Signature:e.getSignature()});if(e.getOptions().valueOf()!==p$.TRANSACTION_OPTIONS_DEFAULT&&(s.Options=e.getOptions().valueOf()),e.isGuardedTransaction()){let a=e.getGuardian();s.GuardianAddr=new gb.Address(a.bech32()).pubkey(),s.GuardianSignature=e.getGuardianSignature()}let o=r.Transaction.encode(s).finish();return p.Buffer.from(o)}serializeTransactionValue(e){let r=new g$.default(e.toString());if(r.isZero())return p.Buffer.from([0,0]);let n=y$.bigIntToBuffer(r);return n=p.Buffer.concat([p.Buffer.from([0]),n]),n}deserializeTransaction(e){throw new m$.ErrUnsupportedOperation("deserializeTransaction")}};jn.ProtoSerializer=pb});var o8=D(Ga=>{"use strict";h();var w$=Ga&&Ga.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),v$=Ga&&Ga.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&w$(e,t,r)};Object.defineProperty(Ga,"__esModule",{value:!0});v$(s8(),Ga)});var _0=D(zn=>{"use strict";h();var A$=zn&&zn.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),E$=zn&&zn.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),b$=zn&&zn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&A$(e,t,r);return E$(e,t),e},S$=zn&&zn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zn,"__esModule",{value:!0});zn.TransactionComputer=void 0;var th=b$(Ie()),a8=S$((rr(),_e(fr))),I$=o8(),T$=Xr(),rn=hr(),_$=JA(),C$=sf(),N$=32,mb=class{constructor(){}computeTransactionFee(e,r){let n=BigInt(r.MinGasLimit+e.data.length*r.GasPerDataByte);if(n>e.gasLimit)throw new th.ErrNotEnoughGas(parseInt(e.gasLimit.toString(),10));let i=e.gasPrice,s=n*i;if(n===e.gasLimit)return s;let o=e.gasLimit-n,u=BigInt(new a8.default(i.toString()).multipliedBy(new a8.default(r.GasPriceModifier)).toFixed(0)),a=o*u;return s+a}computeBytesForSigning(e){this.ensureValidTransactionFields(e);let r=this.toPlainObjectForSigning(e),n=JSON.stringify(r);return new Uint8Array(p.Buffer.from(n))}computeBytesForVerifying(e){return this.hasOptionsSetForHashSigning(e)?this.computeHashForSigning(e):this.computeBytesForSigning(e)}computeHashForSigning(e){let r=this.toPlainObjectForSigning(e),n=p.Buffer.from(JSON.stringify(r));return C$("keccak256").update(n).digest()}computeTransactionHash(e){let n=new I$.ProtoSerializer().serializeTransaction(new T$.Transaction(e)),i=_$(N$).update(n).digest("hex");return p.Buffer.from(i,"hex")}hasOptionsSetForGuardedTransaction(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_GUARDED)==rn.TRANSACTION_OPTIONS_TX_GUARDED}hasOptionsSetForHashSigning(e){return(e.options&rn.TRANSACTION_OPTIONS_TX_HASH_SIGN)==rn.TRANSACTION_OPTIONS_TX_HASH_SIGN}applyGuardian(e,r){e.version= ${rn.MIN_TRANSACTION_VERSION_THAT_SUPPORTS_OPTIONS}`)}};zn.TransactionComputer=mb});var Xr=D(Sc=>{"use strict";h();Object.defineProperty(Sc,"__esModule",{value:!0});Sc.TransactionHash=Sc.Transaction=void 0;var u8=(rr(),_e(fr)),yb=Ve(),wb=hr(),c8=XE(),x$=nD(),l8=$l(),f8=Yf(),O$=Ms(),vb=_0(),Ab=class{constructor(e){this.nonce=BigInt(e.nonce?.valueOf()||0n),this.value=e.value?BigInt(new u8.BigNumber(e.value.toString()).toFixed(0)):0n,this.sender=this.addressAsBech32(e.sender),this.receiver=this.addressAsBech32(e.receiver),this.senderUsername=e.senderUsername||"",this.receiverUsername=e.receiverUsername||"",this.gasPrice=BigInt(e.gasPrice?.valueOf()||wb.TRANSACTION_MIN_GAS_PRICE),this.gasLimit=BigInt(e.gasLimit.valueOf()),this.data=e.data?.valueOf()||new Uint8Array,this.chainID=e.chainID.valueOf(),this.version=Number(e.version?.valueOf()||wb.TRANSACTION_VERSION_DEFAULT),this.options=Number(e.options?.valueOf()||wb.TRANSACTION_OPTIONS_DEFAULT),this.guardian=e.guardian?this.addressAsBech32(e.guardian):"",this.signature=e.signature||p.Buffer.from([]),this.guardianSignature=e.guardianSignature||p.Buffer.from([])}addressAsBech32(e){return typeof e=="string"?e:e.bech32()}getNonce(){return Number(this.nonce)}setNonce(e){this.nonce=BigInt(e.valueOf())}getValue(){return this.value}setValue(e){this.value=BigInt(e.toString())}getSender(){return yb.Address.fromBech32(this.sender)}setSender(e){this.sender=typeof e=="string"?e:e.bech32()}getReceiver(){return yb.Address.fromBech32(this.receiver)}getSenderUsername(){return this.senderUsername}setSenderUsername(e){this.senderUsername=e}getReceiverUsername(){return this.receiverUsername}setReceiverUsername(e){this.receiverUsername=e}getGuardian(){return new yb.Address(this.guardian)}getGasPrice(){return Number(this.gasPrice)}setGasPrice(e){this.gasPrice=BigInt(e.valueOf())}getGasLimit(){return Number(this.gasLimit)}setGasLimit(e){this.gasLimit=BigInt(e.valueOf())}getData(){return new O$.TransactionPayload(p.Buffer.from(this.data))}getChainID(){return this.chainID}setChainID(e){this.chainID=e.valueOf()}getVersion(){return new l8.TransactionVersion(this.version)}setVersion(e){this.version=e.valueOf()}getOptions(){return new l8.TransactionOptions(this.options.valueOf())}setOptions(e){this.options=e.valueOf()}getSignature(){return p.Buffer.from(this.signature)}getGuardianSignature(){return p.Buffer.from(this.guardianSignature)}setGuardian(e){this.guardian=typeof e=="string"?e:e.bech32()}getHash(){return C0.compute(this)}serializeForSigning(){let r=new vb.TransactionComputer().computeBytesForSigning(this);return p.Buffer.from(r)}isGuardedTransaction(){let e=this.guardian.length>0,r=this.guardianSignature.length>0;return this.getOptions().isWithGuardian()&&e&&r}toPlainObject(){return new c8.TransactionsConverter().transactionToPlainObject(this)}static fromPlainObject(e){return new c8.TransactionsConverter().plainObjectToTransaction(e)}applySignature(e){this.signature=f8.interpretSignatureAsBuffer(e)}applyGuardianSignature(e){this.guardianSignature=f8.interpretSignatureAsBuffer(e)}toSendable(){return this.toPlainObject()}computeFee(e){let n=new vb.TransactionComputer().computeTransactionFee(this,e);return new u8.BigNumber(n.toString())}};Sc.Transaction=Ab;var C0=class t extends x$.Hash{constructor(e){super(e)}static compute(e){let n=new vb.TransactionComputer().computeTransactionHash(e);return new t(p.Buffer.from(n).toString("hex"))}};Sc.TransactionHash=C0});var d8=D(N0=>{"use strict";h();Object.defineProperty(N0,"__esModule",{value:!0});N0.TokenOperationsFactory=void 0;var Eb=hr(),D$=oo(),h8=$l(),P$=Xr(),R$=Ms(),ae=Kd(),bb=class{constructor(e){this.config=e,this.trueAsHex=ae.utf8ToHex("true"),this.falseAsHex=ae.utf8ToHex("false")}issueFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issue",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.initialSupply),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}notifyAboutUnsettingBurnRoleGlobally(){D$.Logger.info(` ========== IMPORTANT! ========== You are about to issue (register) a new token. This will set the role "ESDTRoleBurnForAll" (globally). -Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex(e.tokenType),ae.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleLocalMint?[ae.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ae.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ae.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ae.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ae.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.initialQuantity),ae.utf8ToHex(e.name),ae.bigIntToHex(e.royalties),ae.utf8ToHex(e.hash),ae.bufferToHex(e.attributes),...e.uris.map(ae.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:u,dataParts:a}){let c=this.buildTransactionPayload(a),f=o||this.computeGasLimit(c,u),d=new d8.TransactionVersion(Ab.TRANSACTION_VERSION_DEFAULT),w=new d8.TransactionOptions(Ab.TRANSACTION_OPTIONS_DEFAULT);return new y$.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:w})}buildTransactionPayload(e){let r=e.join(Ab.ARGUMENTS_SEPARATOR);return new w$.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};O0.TokenOperationsFactory=Eb});var p8=B(D0=>{"use strict";h();Object.defineProperty(D0,"__esModule",{value:!0});D0.TokenOperationsFactoryConfig=void 0;var v$=Ve(),bb=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=v$.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};D0.TokenOperationsFactoryConfig=bb});var y8=B(P0=>{"use strict";h();Object.defineProperty(P0,"__esModule",{value:!0});P0.TokenOperationsOutcomeParser=void 0;var A$=Ve(),Sb=Ie(),m8=$d(),Ib=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=r.topics[3]?.valueOf();return{tokenIdentifier:n,nonce:i,attributes:s}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){for(let r of e.logs.events)if(r.identifier=="signalError"){let n=p.Buffer.from(r.data.substring(1),"hex").toString(),i=r.topics[1]?.valueOf().toString();throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${i} (${n})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new Sb.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){return e.topics[0]?.valueOf().toString()}extractNonce(e){return m8.bufferToBigInt(e.topics[1]?.valueOf()).toFixed(0)}extractAmount(e){return m8.bufferToBigInt(e.topics[2]?.valueOf()).toFixed(0)}extractAddress(e){return A$.Address.fromBuffer(e.topics[3]?.valueOf()).toString()}};P0.TokenOperationsOutcomeParser=Ib});var _b=B(Ls=>{"use strict";h();var E$=Ls&&Ls.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Tb=Ls&&Ls.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&E$(e,t,r)};Object.defineProperty(Ls,"__esModule",{value:!0});Tb(g8(),Ls);Tb(p8(),Ls);Tb(y8(),Ls)});var w8=B(R0=>{"use strict";h();Object.defineProperty(R0,"__esModule",{value:!0});R0.DelegationTransactionsOutcomeParser=void 0;var b$=Ve(),S$=Ie(),I$=Ac(),Cb=class{constructor(){}parseCreateNewDelegationContract(e){return this.ensureNoError(e.logs.events),I$.findEventsByIdentifier(e,"SCDeploy").map(n=>({contractAddress:this.extractContractAddress(n)}))}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new S$.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractContractAddress(e){if(!e.topics[0]?.length)return"";let r=p.Buffer.from(e.topics[0]);return b$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};R0.DelegationTransactionsOutcomeParser=Cb});var E8=B(B0=>{"use strict";h();Object.defineProperty(B0,"__esModule",{value:!0});B0.SmartContractTransactionsOutcomeParser=void 0;var v8=Ve(),T$=Ie(),A8=qn(),_$=Ac(),Nb=class{constructor(e){this.abi=e?.abi,this.legacyResultsParser=e?.legacyResultsParser||new A8.ResultsParser}parseDeploy(e){let r=e.transactionOutcome.directSmartContractCallOutcome,i=_$.findEventsByIdentifier(e.transactionOutcome,"SCDeploy").map(s=>this.parseScDeployEvent(s));return{returnCode:r.returnCode,returnMessage:r.returnMessage,contracts:i}}parseScDeployEvent(e){let r=e.topics[0],n=e.topics[1],i=e.topics[2],s=r?.length?new v8.Address(r).toBech32():"",o=n?.length?new v8.Address(n).toBech32():"";return{address:s,ownerAddress:o,codeHash:i}}parseExecute(e){let r=e.transactionOutcome.directSmartContractCallOutcome;if(!this.abi)return{values:r.returnDataParts,returnCode:r.returnCode,returnMessage:r.returnMessage};let n=e.function||r.function;if(!n)throw new T$.Err('Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?');let i=this.abi.getEndpoint(n),s={returnCode:new A8.ReturnCode(r.returnCode),returnMessage:r.returnMessage,values:r.returnDataParts.map(u=>p.Buffer.from(u))},o=this.legacyResultsParser.parseOutcomeFromUntypedBundle(s,i);return{values:o.values.map(u=>u.valueOf()),returnCode:o.returnCode.toString(),returnMessage:o.returnMessage}}};B0.SmartContractTransactionsOutcomeParser=Nb});var I8=B(M0=>{"use strict";h();Object.defineProperty(M0,"__esModule",{value:!0});M0.TokenManagementTransactionsOutcomeParser=void 0;var C$=Ve(),b8=Ie(),S8=Bu(),wr=Ac(),xb=class{constructor(){}parseIssueFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issue").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueNonFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueNonFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueSemiFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueSemiFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterMetaEsdt(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"registerMetaESDT").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterAndSetAllRoles(e){this.ensureNoError(e.logs.events);let r=wr.findEventsByIdentifier(e,"registerAndSetAllRoles"),n=wr.findEventsByIdentifier(e,"ESDTSetRole");if(r.length!==n.length)throw new b8.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events.");return r.map((i,s)=>{let o=this.extractTokenIdentifier(i),a=n[s].topics.slice(3).map(c=>this.decodeTopicAsString(c));return{tokenIdentifier:o,roles:a}})}parseSetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseUnsetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseSetSpecialRole(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTSetRole").map(n=>this.getOutputForSetSpecialRoleEvent(n))}getOutputForSetSpecialRoleEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),s=e.topics.slice(3).map(o=>this.decodeTopicAsString(o));return{userAddress:r,tokenIdentifier:n,roles:s}}parseNftCreate(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTCreate").map(n=>this.getOutputForNftCreateEvent(n))}getOutputForNftCreateEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,initialQuantity:i}}parseLocalMint(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalMint").map(n=>this.getOutputForLocalMintEvent(n))}getOutputForLocalMintEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,mintedSupply:s}}parseLocalBurn(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalBurn").map(n=>this.getOutputForLocalBurnEvent(n))}getOutputForLocalBurnEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,burntSupply:s}}parsePause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseUnpause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseFreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTFreeze").map(n=>this.getOutputForFreezeEvent(n))}getOutputForFreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnFreeze").map(n=>this.getOutputForUnfreezeEvent(n))}getOutputForUnfreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTWipe").map(n=>this.getOutputForWipeEvent(n))}getOutputForWipeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTUpdateAttributes").map(n=>this.getOutputForUpdateAttributesEvent(n))}getOutputForUpdateAttributesEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=e.topics[3]?e.topics[3]:new Uint8Array;return{tokenIdentifier:r,nonce:n,attributes:i}}parseAddQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTAddQuantity").map(n=>this.getOutputForAddQuantityEvent(n))}getOutputForAddQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,addedQuantity:i}}parseBurnQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTBurn").map(n=>this.getOutputForBurnQuantityEvent(n))}getOutputForBurnQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,burntQuantity:i}}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new b8.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractTokenIdentifier(e){return e.topics[0]?.length?this.decodeTopicAsString(e.topics[0]):""}extractNonce(e){if(!e.topics[1]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[1]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAmount(e){if(!e.topics[2]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[2]);return BigInt(S8.bufferToBigInt(r).toFixed(0))}extractAddress(e){if(!e.topics[3]?.length)return"";let r=p.Buffer.from(e.topics[3]);return C$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};M0.TokenManagementTransactionsOutcomeParser=xb});var T8=B(L0=>{"use strict";h();Object.defineProperty(L0,"__esModule",{value:!0});L0.TransactionEventsParser=void 0;var N$=qn(),Ob=class{constructor(e){this.legacyResultsParser=new N$.ResultsParser,this.abi=e.abi,this.firstTopicIsIdentifier=e.firstTopicIsIdentifier??!0}parseEvents(e){let r=[];for(let n of e.events){let i=this.parseEvent({event:n});r.push(i)}return r}parseEvent(e){let r=e.event.topics.map(u=>p.Buffer.from(u)),n=this.firstTopicIsIdentifier?r[0]?.toString():e.event.identifier;this.firstTopicIsIdentifier&&r.shift();let i=e.event.dataItems.map(u=>p.Buffer.from(u)),s=this.abi.getEvent(n);return this.legacyResultsParser.doParseEvent({topics:r,dataItems:i,eventDefinition:s})}};L0.TransactionEventsParser=Ob});var Db=B(vi=>{"use strict";h();var x$=vi&&vi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=vi&&vi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&x$(e,t,r)};Object.defineProperty(vi,"__esModule",{value:!0});rh(w8(),vi);rh(Ac(),vi);rh(E8(),vi);rh(I8(),vi);rh(T8(),vi)});var Ic=B(F0=>{"use strict";h();Object.defineProperty(F0,"__esModule",{value:!0});F0.Account=void 0;var O$=Ve(),Pb=class{constructor(e){this.address=O$.Address.empty(),this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};F0.Account=Pb});var Bb=B(Tc=>{"use strict";h();Object.defineProperty(Tc,"__esModule",{value:!0});Tc.MessageComputer=Tc.Message=void 0;var nh=hr(),D$=Ve(),P$=sf(),U0=class{constructor(e){this.data=e.data,this.signature=e.signature,this.address=e.address,this.version=e.version||nh.DEFAULT_MESSAGE_VERSION,this.signer=e.signer||nh.SDK_JS_SIGNER}};Tc.Message=U0;var Rb=class{constructor(){}computeBytesForSigning(e){let r=p.Buffer.from(e.data.length.toString()),n=p.Buffer.concat([r,e.data]),i=p.Buffer.concat([p.Buffer.from(nh.MESSAGE_PREFIX),n]);return P$("keccak256").update(i).digest()}computeBytesForVerifying(e){return this.computeBytesForSigning(e)}packMessage(e){return{message:p.Buffer.from(e.data).toString("hex"),signature:e.signature?p.Buffer.from(e.signature).toString("hex"):"",address:e.address?e.address.bech32():"",version:e.version,signer:e.signer}}unpackMessage(e){let r=this.trimHexPrefix(e.message),n=p.Buffer.from(r,"hex"),i=this.trimHexPrefix(e.signature||""),s=p.Buffer.from(i,"hex"),o;e.address&&(o=D$.Address.fromBech32(e.address));let u=e.version||nh.DEFAULT_MESSAGE_VERSION,a=e.signer||nh.UNKNOWN_SIGNER;return new U0({data:n,signature:s,address:o,version:u,signer:a})}trimHexPrefix(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}};Tc.MessageComputer=Rb});var Fb=B(Xi=>{"use strict";h();var R$=Xi&&Xi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),B$=Xi&&Xi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Xi&&Xi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&R$(e,t,r);return B$(e,t),e};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AsyncTimer=void 0;var L$=M$(Ie()),F$=Ie(),Mb=oo(),Lb=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new L$.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new F$.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(Mb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};Xi.AsyncTimer=Lb});var V0=B(q0=>{"use strict";h();Object.defineProperty(q0,"__esModule",{value:!0});q0.TransactionWatcher=void 0;var Ub=Fb(),_8=hr(),Fs=Ie(),C8=oo(),No=class t{constructor(e,r={}){this.fetcher=new qb(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}async awaitPending(e){let r=s=>s.status.isPending(),n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitCompleted(e){let r=s=>{if(s.isCompleted===void 0)throw new Fs.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitAllEvents(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>u.includes(c))},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitAnyEvent(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>u.includes(c))!=null},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitOnCondition(e,r){let n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}transactionOrTxHashToTxHash(e){let r=typeof e=="string"?e:e.getHash().hex();if(r.length!==_8.HEX_TRANSACTION_HASH_LENGTH)throw new Fs.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${_8.HEX_TRANSACTION_HASH_LENGTH}.`);return r}async awaitConditionally(e,r,n){let i=new Ub.AsyncTimer("watcher:periodic"),s=new Ub.AsyncTimer("watcher:patience"),o=new Ub.AsyncTimer("watcher:timeout"),u=!1,a,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),u=!0});!u;){await i.start(this.pollingIntervalMilliseconds);try{if(a=await r(),c=e(a),c||u)break}catch(f){if(C8.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Fs.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Fs.Err))throw f}}if(c&&await s.start(this.patienceMilliseconds),o.isStopped()||o.stop(),!a||!c)throw n();return a}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};q0.TransactionWatcher=No;No.DefaultPollingInterval=6e3;No.DefaultTimeout=No.DefaultPollingInterval*15;No.DefaultPatience=0;No.NoopOnStatusReceived=t=>{};var qb=class{constructor(e){this.fetcher=e}async getTransaction(e){return C8.Logger.debug(`transactionWatcher, getTransaction(${e})`),await this.fetcher.getTransaction(e)}}});var H0=B(k0=>{"use strict";h();Object.defineProperty(k0,"__esModule",{value:!0});k0.SignableMessage=void 0;var U$=Ve(),q$=Yf(),V$=hr(),k$=sf(),Vb=class{constructor(e){this.message=p.Buffer.from([]),this.signature=p.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=U$.Address.empty(),Object.assign(this,e)}serializeForSigning(){let e=p.Buffer.from(this.message.length.toString()),r=p.Buffer.concat([e,this.message]),n=p.Buffer.concat([p.Buffer.from(V$.MESSAGE_PREFIX),r]);return k$("keccak256").update(n).digest()}serializeForSigningRaw(){return p.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=q$.interpretSignatureAsBuffer(e)}getMessageSize(){let e=p.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};k0.SignableMessage=Vb});var _c=B(vr=>{"use strict";h();var H$=vr&&vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),G$=vr&&vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),j$=vr&&vr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&H$(e,t,r);return G$(e,t),e};Object.defineProperty(vr,"__esModule",{value:!0});vr.zeroPadStringIfOddLength=vr.isPaddedHex=vr.numberToPaddedHex=vr.Nonce=vr.Address=void 0;var N8=j$(wv()),z$="erd",kb=class t{constructor(e){this.value=e}static fromPubkey(e){let r=N8.toWords(e),n=N8.encode(z$,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};vr.Address=kb;var Hb=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return x8(this.value)}};vr.Nonce=Hb;function x8(t){let e=t.toString(16);return O8(e)}vr.numberToPaddedHex=x8;function Q$(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}vr.isPaddedHex=Q$;function O8(t){return t=t||"",t.length%2==1?"0"+t:t}vr.zeroPadStringIfOddLength=O8});var D8=B(xo=>{"use strict";h();var K$=xo&&xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xo,"__esModule",{value:!0});xo.EsdtContractAddress=xo.MaxUint64AsBigNumber=void 0;var W$=K$((rr(),_e(fr))),$$=_c();xo.MaxUint64AsBigNumber=new W$.default("18446744073709551615");xo.EsdtContractAddress=new $$.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var jb=B(Cc=>{"use strict";h();var Y$=Cc&&Cc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ContractQueryResponse=void 0;var J$=Y$((rr(),_e(fr))),X$=D8(),Gb=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new J$.default(e.gasRemaining||e.GasRemaining||0),o=X$.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>p.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Cc.ContractQueryResponse=Gb});var P8=B(Oo=>{"use strict";h();Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ErrAccountNotConnected=Oo.ErrCannotSignSingleTransaction=Oo.Err=void 0;var ih=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Oo.Err=ih;var zb=class extends ih{constructor(){super("Cannot sign single transaction.")}};Oo.ErrCannotSignSingleTransaction=zb;var Qb=class extends ih{constructor(){super("Account is not connected.")}};Oo.ErrAccountNotConnected=Qb});var R8=B(sh=>{"use strict";h();Object.defineProperty(sh,"__esModule",{value:!0});sh.Operation=void 0;var Z$;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(Z$=sh.Operation||(sh.Operation={}))});var Kb=B(Nc=>{"use strict";h();var Do=Nc&&Nc.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Nc,"__esModule",{value:!0});Nc.ExtensionProvider=void 0;var eY=Xr(),B8=P8(),oh=R8(),ah=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return Do(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(oh.Operation.Connect,n),this.account.address})}logout(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(oh.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return Do(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new B8.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new B8.ErrAccountNotConnected}signTransactions(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(oh.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>eY.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(oh.Operation.SignMessage,r)).signature,s=p.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(oh.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};Nc.ExtensionProvider=ah;ah._instance=new ah});function iY(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){sY(t);return}return e}function sY(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function uh(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!nY.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(tY.test(t)||rY.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,iY)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var tY,rY,nY,q8=fe(()=>{h();tY=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,rY=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,nY=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function oY(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function gr(t,...e){try{return oY(t(...e))}catch(r){return Promise.reject(r)}}function aY(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function uY(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ch(t){if(aY(t))return String(t);if(uY(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ch(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function V8(){if(typeof p.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function k8(t){if(typeof t=="string")return t;V8();let e=p.Buffer.from(t).toString("base64");return Wb+e}function H8(t){return typeof t!="string"||!t.startsWith(Wb)?t:(V8(),p.Buffer.from(t.slice(Wb.length),"base64"))}function Vr(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function G8(...t){return Vr(t.join(":"))}function lh(t){return t=Vr(t),t?t+":":""}var Wb,j8=fe(()=>{h();Wb="base64:"});function K8(t={}){let e={mounts:{"":t.driver||lY()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=Vr(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await z8(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},u=(c,f,d)=>{let w=new Map,A=T=>{let x=w.get(T.base);return x||(x={driver:T.driver,base:T.base,items:[]},w.set(T.base,x)),x};for(let T of c){let x=typeof T=="string",R=Vr(x?T:T.key),V=x?void 0:T.value,U=x||!T.options?f:{...f,...T.options},Q=r(R);A(Q).items.push({key:R,value:V,relativeKey:Q.relativeKey,options:U})}return Promise.all([...w.values()].map(T=>d(T))).then(T=>T.flat())},a={hasItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.hasItem,d,f)},getItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.getItem,d,f).then(A=>uh(A))},getItems(c,f){return u(c,f,d=>d.driver.getItems?gr(d.driver.getItems,d.items.map(w=>({key:w.relativeKey,options:w.options})),f).then(w=>w.map(A=>({key:G8(d.base,A.key),value:uh(A.value)}))):Promise.all(d.items.map(w=>gr(d.driver.getItem,w.relativeKey,w.options).then(A=>({key:w.key,value:uh(A)})))))},getItemRaw(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return w.getItemRaw?gr(w.getItemRaw,d,f):gr(w.getItem,d,f).then(A=>H8(A))},async setItem(c,f,d={}){if(f===void 0)return a.removeItem(c);c=Vr(c);let{relativeKey:w,driver:A}=r(c);A.setItem&&(await gr(A.setItem,w,ch(f),d),A.watch||i("update",c))},async setItems(c,f){await u(c,f,async d=>{if(d.driver.setItems)return gr(d.driver.setItems,d.items.map(w=>({key:w.relativeKey,value:ch(w.value),options:w.options})),f);d.driver.setItem&&await Promise.all(d.items.map(w=>gr(d.driver.setItem,w.relativeKey,ch(w.value),w.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return a.removeItem(c,d);c=Vr(c);let{relativeKey:w,driver:A}=r(c);if(A.setItemRaw)await gr(A.setItemRaw,w,f,d);else if(A.setItem)await gr(A.setItem,w,k8(f),d);else return;A.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c);w.removeItem&&(await gr(w.removeItem,d,f),(f.removeMeta||f.removeMata)&&await gr(w.removeItem,d+"$",f),w.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c),A=Object.create(null);if(w.getMeta&&Object.assign(A,await gr(w.getMeta,d,f)),!f.nativeOnly){let T=await gr(w.getItem,d+"$",f).then(x=>uh(x));T&&typeof T=="object"&&(typeof T.atime=="string"&&(T.atime=new Date(T.atime)),typeof T.mtime=="string"&&(T.mtime=new Date(T.mtime)),Object.assign(A,T))}return A},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=lh(c);let d=n(c,!0),w=[],A=[];for(let T of d){let R=(await gr(T.driver.getKeys,T.relativeBase,f)).map(V=>T.mountpoint+Vr(V)).filter(V=>!w.some(U=>V.startsWith(U)));A.push(...R),w=[T.mountpoint,...w.filter(V=>!V.startsWith(T.mountpoint))]}return c?A.filter(T=>T.startsWith(c)&&!T.endsWith("$")):A.filter(T=>!T.endsWith("$"))},async clear(c,f={}){c=lh(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return gr(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let w=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(w.map(A=>d.driver.removeItem(A,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>Q8(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=lh(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,w)=>w.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(z8(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),a},async unmount(c,f=!0){c=lh(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await Q8(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=Vr(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=Vr(c),n(c,f.parents).map(w=>({driver:w.driver,base:w.mountpoint}))}};return a}function z8(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function Q8(t){typeof t.dispose=="function"&&await gr(t.dispose)}var cY,lY,W8=fe(()=>{h();q8();j8();cY="memory",lY=()=>{let t=new Map;return{name:cY,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function za(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Yb(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=za(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function fh(){return $b||($b=Yb("keyval-store","keyval")),$b}function Jb(t,e=fh()){return e("readonly",r=>za(r.get(t)))}function $8(t,e,r=fh()){return r("readwrite",n=>(n.put(e,t),za(n.transaction)))}function Y8(t,e=fh()){return e("readwrite",r=>(r.delete(t),za(r.transaction)))}function J8(t=fh()){return t("readwrite",e=>(e.clear(),za(e.transaction)))}function fY(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},za(t.transaction)}function X8(t=fh()){return t("readonly",e=>{if(e.getAllKeys)return za(e.getAllKeys());let r=[];return fY(e,n=>r.push(n.key)).then(()=>r)})}var $b,Z8=fe(()=>{h()});var eP={};Bt(eP,{safeJsonParse:()=>Ro,safeJsonStringify:()=>Ai});function Ro(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return dY(t)}catch{return t}}function Ai(t){return typeof t=="string"?t:hY(t)||""}var hY,dY,xc=fe(()=>{h();hY=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),dY=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var rP={};Bt(rP,{KeyValueStorage:()=>tS,default:()=>tS});function wY(t){var e;return[t[0],Ro((e=t[1])!=null?e:"")]}var gY,pY,mY,yY,Zb,Xb,Q0,eS,vY,tP,AY,EY,tS,nP=fe(()=>{h();W8();Z8();xc();gY="idb-keyval",pY=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Yb(t.dbName,t.storeName)),{name:gY,options:t,async hasItem(i){return!(typeof await Jb(r(i),n)>"u")},async getItem(i){return await Jb(r(i),n)??null},setItem(i,s){return $8(r(i),s,n)},removeItem(i){return Y8(r(i),n)},getKeys(){return X8(n)},clear(){return J8(n)}}},mY="WALLET_CONNECT_V2_INDEXED_DB",yY="keyvaluestorage",Zb=class{constructor(){this.indexedDb=K8({driver:pY({dbName:mY,storeName:yY})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ai(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Xb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Q0={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Xb<"u"&&Xb.localStorage?Q0.exports=Xb.localStorage:typeof window<"u"&&window.localStorage?Q0.exports=window.localStorage:Q0.exports=new e})();eS=class{constructor(){this.localStorage=Q0.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(wY)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return Ro(r)}async setItem(e,r){this.localStorage.setItem(e,Ai(r))}async removeItem(e){this.localStorage.removeItem(e)}},vY="wc_storage_version",tP=1,AY=async(t,e,r)=>{let n=vY,i=await e.getItem(n);if(i&&i>=tP){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let u=s.shift();if(!u)continue;let a=u.toLowerCase();if(a.includes("wc@")||a.includes("walletconnect")||a.includes("wc_")||a.includes("wallet_connect")){let c=await t.getItem(u);await e.setItem(u,c),o.push(u)}}await e.setItem(n,tP),r(e),EY(t,o)},EY=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},tS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new eS;this.storage=e;try{let r=new Zb;AY(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zi={};Bt(Zi,{__assign:()=>nS,__asyncDelegator:()=>BY,__asyncGenerator:()=>RY,__asyncValues:()=>MY,__await:()=>hh,__awaiter:()=>CY,__classPrivateFieldGet:()=>qY,__classPrivateFieldSet:()=>VY,__createBinding:()=>xY,__decorate:()=>IY,__exportStar:()=>OY,__extends:()=>bY,__generator:()=>NY,__importDefault:()=>UY,__importStar:()=>FY,__makeTemplateObject:()=>LY,__metadata:()=>_Y,__param:()=>TY,__read:()=>iP,__rest:()=>SY,__spread:()=>DY,__spreadArrays:()=>PY,__values:()=>iS});function bY(t,e){rS(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function SY(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;u--)(o=t[u])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function TY(t,e){return function(r,n){e(r,n,t)}}function _Y(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function CY(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})}function NY(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(c){return function(f){return a([c,f])}}function a(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function iP(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function DY(){for(var t=[],e=0;e1||u(w,A)})})}function u(w,A){try{a(n[w](A))}catch(T){d(s[0][3],T)}}function a(w){w.value instanceof hh?Promise.resolve(w.value.v).then(c,f):d(s[0][2],w)}function c(w){u("next",w)}function f(w){u("throw",w)}function d(w,A){w(A),s.shift(),s.length&&u(s[0][0],s[0][1])}}function BY(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:hh(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function MY(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof iS=="function"?iS(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(u,a){o=t[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(c){s({value:c,done:u})},o)}}function LY(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function FY(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function UY(t){return t&&t.__esModule?t:{default:t}}function qY(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function VY(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var rS,nS,es=fe(()=>{h();rS=function(t,e){return rS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},rS(t,e)};nS=function(){return nS=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";h();Object.defineProperty(K0,"__esModule",{value:!0});K0.delay=void 0;function kY(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}K0.delay=kY});var oP=B(Oc=>{"use strict";h();Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ONE_THOUSAND=Oc.ONE_HUNDRED=void 0;Oc.ONE_HUNDRED=100;Oc.ONE_THOUSAND=1e3});var aP=B(le=>{"use strict";h();Object.defineProperty(le,"__esModule",{value:!0});le.ONE_YEAR=le.FOUR_WEEKS=le.THREE_WEEKS=le.TWO_WEEKS=le.ONE_WEEK=le.THIRTY_DAYS=le.SEVEN_DAYS=le.FIVE_DAYS=le.THREE_DAYS=le.ONE_DAY=le.TWENTY_FOUR_HOURS=le.TWELVE_HOURS=le.SIX_HOURS=le.THREE_HOURS=le.ONE_HOUR=le.SIXTY_MINUTES=le.THIRTY_MINUTES=le.TEN_MINUTES=le.FIVE_MINUTES=le.ONE_MINUTE=le.SIXTY_SECONDS=le.THIRTY_SECONDS=le.TEN_SECONDS=le.FIVE_SECONDS=le.ONE_SECOND=void 0;le.ONE_SECOND=1;le.FIVE_SECONDS=5;le.TEN_SECONDS=10;le.THIRTY_SECONDS=30;le.SIXTY_SECONDS=60;le.ONE_MINUTE=le.SIXTY_SECONDS;le.FIVE_MINUTES=le.ONE_MINUTE*5;le.TEN_MINUTES=le.ONE_MINUTE*10;le.THIRTY_MINUTES=le.ONE_MINUTE*30;le.SIXTY_MINUTES=le.ONE_MINUTE*60;le.ONE_HOUR=le.SIXTY_MINUTES;le.THREE_HOURS=le.ONE_HOUR*3;le.SIX_HOURS=le.ONE_HOUR*6;le.TWELVE_HOURS=le.ONE_HOUR*12;le.TWENTY_FOUR_HOURS=le.ONE_HOUR*24;le.ONE_DAY=le.TWENTY_FOUR_HOURS;le.THREE_DAYS=le.ONE_DAY*3;le.FIVE_DAYS=le.ONE_DAY*5;le.SEVEN_DAYS=le.ONE_DAY*7;le.THIRTY_DAYS=le.ONE_DAY*30;le.ONE_WEEK=le.SEVEN_DAYS;le.TWO_WEEKS=le.ONE_WEEK*2;le.THREE_WEEKS=le.ONE_WEEK*3;le.FOUR_WEEKS=le.ONE_WEEK*4;le.ONE_YEAR=le.ONE_DAY*365});var sS=B(W0=>{"use strict";h();Object.defineProperty(W0,"__esModule",{value:!0});var uP=(es(),_e(Zi));uP.__exportStar(oP(),W0);uP.__exportStar(aP(),W0)});var lP=B(Dc=>{"use strict";h();Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromMiliseconds=Dc.toMiliseconds=void 0;var cP=sS();function HY(t){return t*cP.ONE_THOUSAND}Dc.toMiliseconds=HY;function GY(t){return Math.floor(t/cP.ONE_THOUSAND)}Dc.fromMiliseconds=GY});var hP=B($0=>{"use strict";h();Object.defineProperty($0,"__esModule",{value:!0});var fP=(es(),_e(Zi));fP.__exportStar(sP(),$0);fP.__exportStar(lP(),$0)});var dP=B(dh=>{"use strict";h();Object.defineProperty(dh,"__esModule",{value:!0});dh.Watch=void 0;var Y0=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};dh.Watch=Y0;dh.default=Y0});var gP=B(J0=>{"use strict";h();Object.defineProperty(J0,"__esModule",{value:!0});J0.IWatch=void 0;var oS=class{};J0.IWatch=oS});var pP=B(aS=>{"use strict";h();Object.defineProperty(aS,"__esModule",{value:!0});var jY=(es(),_e(Zi));jY.__exportStar(gP(),aS)});var Qa=B(Pc=>{"use strict";h();Object.defineProperty(Pc,"__esModule",{value:!0});var X0=(es(),_e(Zi));X0.__exportStar(hP(),Pc);X0.__exportStar(dP(),Pc);X0.__exportStar(pP(),Pc);X0.__exportStar(sS(),Pc)});var uS,mP=fe(()=>{h();uS=class{}});var cS={};Bt(cS,{IEvents:()=>uS});var lS=fe(()=>{h();mP()});var yP=B(Z0=>{"use strict";h();Object.defineProperty(Z0,"__esModule",{value:!0});Z0.IHeartBeat=void 0;var zY=(lS(),_e(cS)),fS=class extends zY.IEvents{constructor(e){super()}};Z0.IHeartBeat=fS});var dS=B(hS=>{"use strict";h();Object.defineProperty(hS,"__esModule",{value:!0});var QY=(es(),_e(Zi));QY.__exportStar(yP(),hS)});var wP=B(Rc=>{"use strict";h();Object.defineProperty(Rc,"__esModule",{value:!0});Rc.HEARTBEAT_EVENTS=Rc.HEARTBEAT_INTERVAL=void 0;var KY=Qa();Rc.HEARTBEAT_INTERVAL=KY.FIVE_SECONDS;Rc.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var pS=B(gS=>{"use strict";h();Object.defineProperty(gS,"__esModule",{value:!0});var WY=(es(),_e(Zi));WY.__exportStar(wP(),gS)});var vP=B(em=>{"use strict";h();Object.defineProperty(em,"__esModule",{value:!0});em.HeartBeat=void 0;var mS=(es(),_e(Zi)),$Y=Ds(),YY=Qa(),JY=dS(),yS=pS(),wS=class t extends JY.IHeartBeat{constructor(e){super(e),this.events=new $Y.EventEmitter,this.interval=yS.HEARTBEAT_INTERVAL,this.interval=e?.interval||yS.HEARTBEAT_INTERVAL}static init(e){return mS.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return mS.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return mS.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),YY.toMiliseconds(this.interval))})}pulse(){this.events.emit(yS.HEARTBEAT_EVENTS.pulse)}};em.HeartBeat=wS});var AP=B(gh=>{"use strict";h();Object.defineProperty(gh,"__esModule",{value:!0});var vS=(es(),_e(Zi));vS.__exportStar(vP(),gh);vS.__exportStar(dS(),gh);vS.__exportStar(pS(),gh)});var bP=B((AAe,EP)=>{"use strict";h();function XY(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}EP.exports=ZY;function ZY(t,e,r){var n=r&&r.stringify||XY,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var u=1;u-1?d:0,t.charCodeAt(A+1)){case 100:case 102:if(f>=a||e[f]==null)break;d=a||e[f]==null)break;d=a||e[f]===void 0)break;d",d=A+2,A++;break}c+=n(e[f]),d=A+2,A++;break;case 115:if(f>=a)break;d{"use strict";h();var SP=bP();_P.exports=ts;var ph=cJ().console||{},eJ={mapHttpRequest:tm,mapHttpResponse:tm,wrapRequestSerializer:AS,wrapResponseSerializer:AS,wrapErrorSerializer:AS,req:tm,res:tm,err:sJ};function tJ(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ts(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||ph;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=tJ(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let u=t.level||"info",a=Object.create(r);a.log||(a.log=mh),Object.defineProperty(a,"levelVal",{get:f}),Object.defineProperty(a,"level",{get:d,set:w});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:oJ(t)};a.levels=ts.levels,a.level=u,a.setMaxListeners=a.getMaxListeners=a.emit=a.addListener=a.on=a.prependListener=a.once=a.prependOnceListener=a.removeListener=a.removeAllListeners=a.listeners=a.listenerCount=a.eventNames=a.write=a.flush=mh,a.serializers=n,a._serialize=i,a._stdErrSerialize=s,a.child=A,e&&(a._logEvent=ES());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function w(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,Bc(c,a,"error","log"),Bc(c,a,"fatal","error"),Bc(c,a,"warn","error"),Bc(c,a,"info","log"),Bc(c,a,"debug","log"),Bc(c,a,"trace","log")}function A(T,x){if(!T)throw new Error("missing bindings for child Pino");x=x||{},i&&T.serializers&&(x.serializers=T.serializers);let R=x.serializers;if(i&&R){var V=Object.assign({},n,R),U=t.browser.serialize===!0?Object.keys(V):i;delete T.serializers,rm([T],U,V,this._stdErrSerialize)}function Q(L){this._childLevel=(L._childLevel|0)+1,this.error=Mc(L,T,"error"),this.fatal=Mc(L,T,"fatal"),this.warn=Mc(L,T,"warn"),this.info=Mc(L,T,"info"),this.debug=Mc(L,T,"debug"),this.trace=Mc(L,T,"trace"),V&&(this.serializers=V,this._serialize=U),e&&(this._logEvent=ES([].concat(L._logEvent.bindings,T)))}return Q.prototype=this,new Q(this)}return a}ts.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};ts.stdSerializers=eJ;ts.stdTimeFunctions=Object.assign({},{nullTime:IP,epochTime:TP,unixTime:aJ,isoTime:uJ});function Bc(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mh:i[r]?i[r]:ph[r]||ph[n]||mh,rJ(t,e,r)}function rJ(t,e,r){!t.transmit&&e[r]===mh||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ph?ph:this;for(var a=0;a-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Mc(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;iam,PINO_CUSTOM_CONTEXT_KEY:()=>Lc,PINO_LOGGER_DEFAULTS:()=>OP,formatChildLoggerContext:()=>BP,generateChildLogger:()=>mJ,generateClientLogger:()=>MP,generatePlatformLogger:()=>yJ,generateServerLogger:()=>LP,getBrowserLoggerContext:()=>DP,getDefaultLoggerOptions:()=>pJ,getLoggerContext:()=>RP,pino:()=>xP.default,setBrowserLoggerContext:()=>PP});function pJ(t){return om(sm({},t),{level:t?.level||OP.level})}function DP(t,e=Lc){return t[e]||""}function PP(t,e,r=Lc){return t[r]=e,t}function RP(t,e=Lc){let r="";return typeof t.bindings>"u"?r=DP(t,e):r=t.bindings().context||"",r}function BP(t,e,r=Lc){let n=RP(t,r);return n.trim()?`${n}/${e}`:e}function mJ(t,e,r=Lc){let n=BP(t,e,r),i=t.child({context:n});return PP(i,n,r)}function MP(t){var e,r;let n=new IS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace",browser:om(sm({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function LP(t){var e;let r=new TS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(om(sm({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function yJ(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?MP(t):LP(t)}var Us,xP,OP,Lc,am,SS,nm,im,IS,TS,lJ,fJ,hJ,CP,dJ,gJ,NP,sm,om,CS=fe(()=>{h();Us=pe(bS()),xP=pe(bS());xc();OP={level:"info"},Lc="custom_context",am=1e3*1024,SS=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},nm=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let r=new SS(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let r=e.value;return e=e.next,{done:!1,value:r}}}}},im=class{constructor(e,r=am){this.level=e??"error",this.levelValue=Us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Us.levels.values.error?console.error(e):r===Us.levels.values.warn?console.warn(e):r===Us.levels.values.debug?console.debug(e):r===Us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ai({timestamp:new Date().toISOString(),log:e}));let r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new nm(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let r=this.getLogArray();return r.push(Ai({extraMetadata:e})),new Blob(r,{type:"application/json"})}},IS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},TS=class{constructor(e,r=am){this.baseChunkLogger=new im(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}},lJ=Object.defineProperty,fJ=Object.defineProperties,hJ=Object.getOwnPropertyDescriptors,CP=Object.getOwnPropertySymbols,dJ=Object.prototype.hasOwnProperty,gJ=Object.prototype.propertyIsEnumerable,NP=(t,e,r)=>e in t?lJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sm=(t,e)=>{for(var r in e||(e={}))dJ.call(e,r)&&NP(t,r,e[r]);if(CP)for(var r of CP(e))gJ.call(e,r)&&NP(t,r,e[r]);return t},om=(t,e)=>fJ(t,hJ(e))});var QS=B(ar=>{"use strict";h();Object.defineProperty(ar,"__esModule",{value:!0});var Fc=(lS(),_e(cS)),FP=Ds();function wJ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var vJ=wJ(FP),NS=class extends Fc.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},xS=class{constructor(e,r,n){this.core=e,this.logger=r}},OS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},DS=class{constructor(e,r){this.logger=e,this.core=r}},PS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},RS=class extends Fc.IEvents{constructor(e){super()}},BS=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},MS=class{constructor(){this.map=new Map}},LS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},FS=class{constructor(e,r){this.core=e,this.logger=r}},US=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},qS=class{constructor(e,r){this.logger=e,this.core=r}},VS=class{constructor(e,r){this.projectId=e,this.logger=r}},kS=class{constructor(e,r){this.projectId=e,this.logger=r}},HS=class extends vJ.default{constructor(){super()}},GS=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},jS=class extends FP.EventEmitter{constructor(){super()}},zS=class{constructor(e){this.client=e}};ar.ICore=NS,ar.ICrypto=xS,ar.IEchoClient=kS,ar.IEngine=zS,ar.IEngineEvents=jS,ar.IExpirer=US,ar.IJsonRpcHistory=OS,ar.IKeyChain=FS,ar.IMessageTracker=DS,ar.IPairing=qS,ar.IPublisher=PS,ar.IRelayer=RS,ar.ISignClient=GS,ar.ISignClientEvents=HS,ar.IStore=BS,ar.ISubscriber=LS,ar.ISubscriberTopicMap=MS,ar.IVerify=VS});var qP=B(um=>{"use strict";h();Object.defineProperty(um,"__esModule",{value:!0});um.BrowserRandomSource=void 0;var UP=65536,KS=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";h();Object.defineProperty(WS,"__esModule",{value:!0});function AJ(t){for(var e=0;e{h()});var kP=B(cm=>{"use strict";h();Object.defineProperty(cm,"__esModule",{value:!0});cm.NodeRandomSource=void 0;var EJ=Qn(),$S=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof Bd<"u"){let e=VP();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";h();Object.defineProperty(lm,"__esModule",{value:!0});lm.SystemRandomSource=void 0;var bJ=qP(),SJ=kP(),YS=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new bJ.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new SJ.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};lm.SystemRandomSource=YS});var GP=B(dn=>{"use strict";h();Object.defineProperty(dn,"__esModule",{value:!0});function IJ(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}dn.mul=Math.imul||IJ;function TJ(t,e){return t+e|0}dn.add=TJ;function _J(t,e){return t-e|0}dn.sub=_J;function CJ(t,e){return t<>>32-e}dn.rotl=CJ;function NJ(t,e){return t<<32-e|t>>>e}dn.rotr=NJ;function xJ(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}dn.isInteger=Number.isInteger||xJ;dn.MAX_SAFE_INTEGER=9007199254740991;dn.isSafeInteger=function(t){return dn.isInteger(t)&&t>=-dn.MAX_SAFE_INTEGER&&t<=dn.MAX_SAFE_INTEGER}});var Uc=B(xe=>{"use strict";h();Object.defineProperty(xe,"__esModule",{value:!0});var jP=GP();function OJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}xe.readInt16BE=OJ;function DJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}xe.readUint16BE=DJ;function PJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}xe.readInt16LE=PJ;function RJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}xe.readUint16LE=RJ;function zP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}xe.writeUint16BE=zP;xe.writeInt16BE=zP;function QP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}xe.writeUint16LE=QP;xe.writeInt16LE=QP;function JS(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}xe.readInt32BE=JS;function XS(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}xe.readUint32BE=XS;function ZS(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}xe.readInt32LE=ZS;function eI(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}xe.readUint32LE=eI;function fm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}xe.writeUint32BE=fm;xe.writeInt32BE=fm;function hm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}xe.writeUint32LE=hm;xe.writeInt32LE=hm;function BJ(t,e){e===void 0&&(e=0);var r=JS(t,e),n=JS(t,e+4);return r*4294967296+n-(n>>31)*4294967296}xe.readInt64BE=BJ;function MJ(t,e){e===void 0&&(e=0);var r=XS(t,e),n=XS(t,e+4);return r*4294967296+n}xe.readUint64BE=MJ;function LJ(t,e){e===void 0&&(e=0);var r=ZS(t,e),n=ZS(t,e+4);return n*4294967296+r-(r>>31)*4294967296}xe.readInt64LE=LJ;function FJ(t,e){e===void 0&&(e=0);var r=eI(t,e),n=eI(t,e+4);return n*4294967296+r}xe.readUint64LE=FJ;function KP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),fm(t/4294967296>>>0,e,r),fm(t>>>0,e,r+4),e}xe.writeUint64BE=KP;xe.writeInt64BE=KP;function WP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),hm(t>>>0,e,r),hm(t/4294967296>>>0,e,r+4),e}xe.writeUint64LE=WP;xe.writeInt64LE=WP;function UJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}xe.readUintBE=UJ;function qJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}xe.writeUintBE=VJ;function kJ(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!jP.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";h();Object.defineProperty(Br,"__esModule",{value:!0});Br.randomStringForEntropy=Br.randomString=Br.randomUint32=Br.randomBytes=Br.defaultRandomSource=void 0;var YJ=HP(),JJ=Uc(),$P=Qn();Br.defaultRandomSource=new YJ.SystemRandomSource;function tI(t,e=Br.defaultRandomSource){return e.randomBytes(t)}Br.randomBytes=tI;function XJ(t=Br.defaultRandomSource){let e=tI(4,t),r=(0,JJ.readUint32LE)(e);return(0,$P.wipe)(e),r}Br.randomUint32=XJ;var YP="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function JP(t,e=YP,r=Br.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=tI(Math.ceil(t*256/s),r);for(let u=0;u0;u++){let a=o[u];a{"use strict";h();Object.defineProperty(qs,"__esModule",{value:!0});var Vc=Uc(),qc=Qn();qs.DIGEST_LENGTH=64;qs.BLOCK_SIZE=128;var ZP=function(){function t(){this.digestLength=qs.DIGEST_LENGTH,this.blockSize=qs.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){qc.wipe(this._buffer),qc.wipe(this._tempHi),qc.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=rI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){qc.wipe(e.stateHi),qc.wipe(e.stateLo),e.buffer&&qc.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();qs.SHA512=ZP;var XP=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function rI(t,e,r,n,i,s,o){for(var u=r[0],a=r[1],c=r[2],f=r[3],d=r[4],w=r[5],A=r[6],T=r[7],x=n[0],R=n[1],V=n[2],U=n[3],Q=n[4],L=n[5],k=n[6],H=n[7],q,v,C,D,F,P,l,g;o>=128;){for(var y=0;y<16;y++){var E=8*y+s;t[y]=Vc.readUint32BE(i,E),e[y]=Vc.readUint32BE(i,E+4)}for(var y=0;y<80;y++){var S=u,_=a,M=c,N=f,m=d,O=w,Y=A,$=T,b=x,j=R,z=V,W=U,ie=Q,te=L,ee=k,se=H;if(q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(d>>>14|Q<<18)^(d>>>18|Q<<14)^(Q>>>9|d<<23),v=(Q>>>14|d<<18)^(Q>>>18|d<<14)^(d>>>9|Q<<23),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=d&w^~d&A,v=Q&L^~Q&k,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=XP[y*2],v=XP[y*2+1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=t[y%16],v=e[y%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,C=l&65535|g<<16,D=F&65535|P<<16,q=C,v=D,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=(u>>>28|x<<4)^(x>>>2|u<<30)^(x>>>7|u<<25),v=(x>>>28|u<<4)^(u>>>2|x<<30)^(u>>>7|x<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,q=u&a^u&c^a&c,v=x&R^x&V^R&V,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,$=l&65535|g<<16,se=F&65535|P<<16,q=N,v=W,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=C,v=D,F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,N=l&65535|g<<16,W=F&65535|P<<16,a=S,c=_,f=M,d=N,w=m,A=O,T=Y,u=$,R=b,V=j,U=z,Q=W,L=ie,k=te,H=ee,x=se,y%16===15)for(var E=0;E<16;E++)q=t[E],v=e[E],F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=t[(E+9)%16],v=e[(E+9)%16],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+1)%16],D=e[(E+1)%16],q=(C>>>1|D<<31)^(C>>>8|D<<24)^C>>>7,v=(D>>>1|C<<31)^(D>>>8|C<<24)^(D>>>7|C<<25),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+14)%16],D=e[(E+14)%16],q=(C>>>19|D<<13)^(D>>>29|C<<3)^C>>>6,v=(D>>>19|C<<13)^(C>>>29|D<<3)^(D>>>6|C<<26),F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,t[E]=l&65535|g<<16,e[E]=F&65535|P<<16}q=u,v=x,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[0],v=n[0],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[0]=u=l&65535|g<<16,n[0]=x=F&65535|P<<16,q=a,v=R,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[1],v=n[1],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[1]=a=l&65535|g<<16,n[1]=R=F&65535|P<<16,q=c,v=V,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[2],v=n[2],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[2]=c=l&65535|g<<16,n[2]=V=F&65535|P<<16,q=f,v=U,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[3],v=n[3],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[3]=f=l&65535|g<<16,n[3]=U=F&65535|P<<16,q=d,v=Q,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[4],v=n[4],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[4]=d=l&65535|g<<16,n[4]=Q=F&65535|P<<16,q=w,v=L,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[5],v=n[5],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[5]=w=l&65535|g<<16,n[5]=L=F&65535|P<<16,q=A,v=k,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[6],v=n[6],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[6]=A=l&65535|g<<16,n[6]=k=F&65535|P<<16,q=T,v=H,F=v&65535,P=v>>>16,l=q&65535,g=q>>>16,q=r[7],v=n[7],F+=v&65535,P+=v>>>16,l+=q&65535,g+=q>>>16,P+=F>>>16,l+=P>>>16,g+=l>>>16,r[7]=T=l&65535|g<<16,n[7]=H=F&65535|P<<16,s+=128,o-=128}return s}function eX(t){var e=new ZP;e.update(t);var r=e.digest();return e.clean(),r}qs.hash=eX});var gR=B(Ge=>{"use strict";h();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.convertSecretKeyToX25519=Ge.convertPublicKeyToX25519=Ge.verify=Ge.sign=Ge.extractPublicKeyFromSecretKey=Ge.generateKeyPair=Ge.generateKeyPairFromSeed=Ge.SEED_LENGTH=Ge.SECRET_KEY_LENGTH=Ge.PUBLIC_KEY_LENGTH=Ge.SIGNATURE_LENGTH=void 0;var tX=yh(),wh=eR(),sR=Qn();Ge.SIGNATURE_LENGTH=64;Ge.PUBLIC_KEY_LENGTH=32;Ge.SECRET_KEY_LENGTH=64;Ge.SEED_LENGTH=32;function ve(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,oR(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function aR(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function nR(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return vh(r,t),vh(n,e),aR(r,n)}function uR(t){let e=new Uint8Array(32);return vh(e,t),e[0]&1}function oX(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Ka(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function $a(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function Ct(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Wa(t,e){Ct(t,e,e)}function cR(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)Wa(r,r),n!==2&&n!==4&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function aX(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)Wa(r,r),n!==1&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function oI(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve(),c=ve(),f=ve();$a(r,t[1],t[0]),$a(f,e[1],e[0]),Ct(r,r,f),Ka(n,t[0],t[1]),Ka(f,e[0],e[1]),Ct(n,n,f),Ct(i,t[3],e[3]),Ct(i,i,iX),Ct(s,t[2],e[2]),Ka(s,s,s),$a(o,n,r),$a(u,s,i),Ka(a,s,i),Ka(c,n,r),Ct(t[0],o,u),Ct(t[1],c,a),Ct(t[2],a,u),Ct(t[3],o,c)}function iR(t,e,r){for(let n=0;n<4;n++)oR(t[n],e[n],r)}function uI(t,e){let r=ve(),n=ve(),i=ve();cR(i,e[2]),Ct(r,e[0],i),Ct(n,e[1],i),vh(t,n),t[31]^=uR(r)<<7}function lR(t,e,r){Bo(t[0],sI),Bo(t[1],kc),Bo(t[2],kc),Bo(t[3],sI);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;iR(t,e,i),oI(e,t),oI(t,t),iR(t,e,i)}}function cI(t,e){let r=[ve(),ve(),ve(),ve()];Bo(r[0],tR),Bo(r[1],rR),Bo(r[2],kc),Ct(r[3],tR,rR),lR(t,r,e)}function fR(t){if(t.length!==Ge.SEED_LENGTH)throw new Error(`ed25519: seed must be ${Ge.SEED_LENGTH} bytes`);let e=(0,wh.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[ve(),ve(),ve(),ve()];cI(n,e),uI(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}Ge.generateKeyPairFromSeed=fR;function uX(t){let e=(0,tX.randomBytes)(32,t),r=fR(e);return(0,sR.wipe)(e),r}Ge.generateKeyPair=uX;function cX(t){if(t.length!==Ge.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${Ge.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}Ge.extractPublicKeyFromSecretKey=cX;var iI=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function hR(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*iI[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*iI[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function aI(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;hR(t,e)}function lX(t,e){let r=new Float64Array(64),n=[ve(),ve(),ve(),ve()],i=(0,wh.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new wh.SHA512;o.update(s.subarray(32)),o.update(e);let u=o.digest();o.clean(),aI(u),cI(n,u),uI(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let a=o.digest();aI(a);for(let c=0;c<32;c++)r[c]=u[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=a[c]*i[f];return hR(s.subarray(32),r),s}Ge.sign=lX;function dR(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve();return Bo(t[2],kc),oX(t[1],e),Wa(i,t[1]),Ct(s,i,nX),$a(i,i,t[2]),Ka(s,t[2],s),Wa(o,s),Wa(u,o),Ct(a,u,o),Ct(r,a,i),Ct(r,r,s),aX(r,r),Ct(r,r,i),Ct(r,r,s),Ct(r,r,s),Ct(t[0],r,s),Wa(n,t[0]),Ct(n,n,s),nR(n,i)&&Ct(t[0],t[0],sX),Wa(n,t[0]),Ct(n,n,s),nR(n,i)?-1:(uR(t[0])===e[31]>>7&&$a(t[0],sI,t[0]),Ct(t[3],t[0],t[1]),0)}function fX(t,e,r){let n=new Uint8Array(32),i=[ve(),ve(),ve(),ve()],s=[ve(),ve(),ve(),ve()];if(r.length!==Ge.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${Ge.SIGNATURE_LENGTH} bytes`);if(dR(s,t))return!1;let o=new wh.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let u=o.digest();return aI(u),lR(i,s,u),cI(s,r.subarray(32)),oI(i,s),uI(n,i),!aR(r,n)}Ge.verify=fX;function hX(t){let e=[ve(),ve(),ve(),ve()];if(dR(e,t))throw new Error("Ed25519: invalid public key");let r=ve(),n=ve(),i=e[1];Ka(r,kc,i),$a(n,kc,i),cR(n,n),Ct(r,r,n);let s=new Uint8Array(32);return vh(s,r),s}Ge.convertPublicKeyToX25519=hX;function dX(t){let e=(0,wh.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,sR.wipe)(e),r}Ge.convertSecretKeyToX25519=dX});var dm,gm,Ya,Hc,pm,Ah,mm,ym,wm,Gc,vm,Am,pR,mR,Em=fe(()=>{h();dm="EdDSA",gm="JWT",Ya=".",Hc="base64url",pm="utf8",Ah="utf8",mm=":",ym="did",wm="key",Gc="base58btc",vm="z",Am="K36",pR=32,mR=32});function Mo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var Eh=fe(()=>{h()});function jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var bm=fe(()=>{h();Eh()});function Sm(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=jc(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Mo(r)}var lI=fe(()=>{h();bm();Eh()});function gX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var pX,mX,yR,wR=fe(()=>{h();pX=gX,mX=pX,yR=mX});var cEe,vR,Vs,AR,ER,Lo=fe(()=>{h();cEe=new Uint8Array(0),vR=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},AR=t=>new TextEncoder().encode(t),ER=t=>new TextDecoder().decode(t)});var fI,hI,dI,SR,gI,zc,Fo,yX,wX,jt,Ei=fe(()=>{h();wR();Lo();fI=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},hI=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SR(this,e)}},dI=class{constructor(e){this.decoders=e}or(e){return SR(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SR=(t,e)=>new dI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),gI=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new fI(e,r,n),this.decoder=new hI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zc=({name:t,prefix:e,encode:r,decode:n})=>new gI(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=yR(r,e);return zc({prefix:t,name:e,encode:n,decode:s=>Vs(i(s))})},yX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},wX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<zc({prefix:e,name:t,encode(i){return wX(i,n,r)},decode(i){return yX(i,n,r,t)}})});var pI={};Bt(pI,{identity:()=>vX});var vX,IR=fe(()=>{h();Ei();Lo();vX=zc({prefix:"\0",name:"identity",encode:t=>ER(t),decode:t=>AR(t)})});var mI={};Bt(mI,{base2:()=>AX});var AX,TR=fe(()=>{h();Ei();AX=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var yI={};Bt(yI,{base8:()=>EX});var EX,_R=fe(()=>{h();Ei();EX=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var wI={};Bt(wI,{base10:()=>bX});var bX,CR=fe(()=>{h();Ei();bX=Fo({prefix:"9",name:"base10",alphabet:"0123456789"})});var vI={};Bt(vI,{base16:()=>SX,base16upper:()=>IX});var SX,IX,NR=fe(()=>{h();Ei();SX=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),IX=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var AI={};Bt(AI,{base32:()=>Qc,base32hex:()=>NX,base32hexpad:()=>OX,base32hexpadupper:()=>DX,base32hexupper:()=>xX,base32pad:()=>_X,base32padupper:()=>CX,base32upper:()=>TX,base32z:()=>PX});var Qc,TX,_X,CX,NX,xX,OX,DX,PX,EI=fe(()=>{h();Ei();Qc=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),TX=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_X=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),CX=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),NX=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xX=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),OX=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DX=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),PX=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bI={};Bt(bI,{base36:()=>RX,base36upper:()=>BX});var RX,BX,xR=fe(()=>{h();Ei();RX=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BX=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var SI={};Bt(SI,{base58btc:()=>rs,base58flickr:()=>MX});var rs,MX,II=fe(()=>{h();Ei();rs=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),MX=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var TI={};Bt(TI,{base64:()=>LX,base64pad:()=>FX,base64url:()=>UX,base64urlpad:()=>qX});var LX,FX,UX,qX,OR=fe(()=>{h();Ei();LX=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FX=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),UX=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qX=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var _I={};Bt(_I,{base256emoji:()=>jX});function HX(t){return t.reduce((e,r)=>(e+=VX[r],e),"")}function GX(t){let e=[];for(let r of t){let n=kX[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var DR,VX,kX,jX,PR=fe(()=>{h();Ei();DR=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VX=DR.reduce((t,e,r)=>(t[r]=e,t),[]),kX=DR.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);jX=zc({prefix:"\u{1F680}",name:"base256emoji",encode:HX,decode:GX})});function MR(t,e,r){e=e||[],r=r||0;for(var n=r;t>=WX;)e[r++]=t&255|RR,t/=128;for(;t&KX;)e[r++]=t&255|RR,t>>>=7;return e[r]=t|0,MR.bytes=r-n+1,e}function CI(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw CI.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&BR)<=YX);return CI.bytes=s-n,r}var zX,RR,QX,KX,WX,$X,YX,BR,JX,XX,ZX,eZ,tZ,rZ,nZ,iZ,sZ,oZ,aZ,uZ,bh,LR=fe(()=>{h();zX=MR,RR=128,QX=127,KX=~QX,WX=Math.pow(2,31);$X=CI,YX=128,BR=127;JX=Math.pow(2,7),XX=Math.pow(2,14),ZX=Math.pow(2,21),eZ=Math.pow(2,28),tZ=Math.pow(2,35),rZ=Math.pow(2,42),nZ=Math.pow(2,49),iZ=Math.pow(2,56),sZ=Math.pow(2,63),oZ=function(t){return t{h();LR();Sh=(t,e=0)=>[bh.decode(t,e),bh.decode.bytes],Kc=(t,e,r=0)=>(bh.encode(t,e,r),e),Wc=t=>bh.encodingLength(t)});var Ja,FR,UR,$c,Th=fe(()=>{h();Lo();Tm();Ja=(t,e)=>{let r=e.byteLength,n=Wc(t),i=n+Wc(r),s=new Uint8Array(i+r);return Kc(t,s,0),Kc(r,s,n),s.set(e,i),new $c(t,r,e,s)},FR=t=>{let e=Vs(t),[r,n]=Sh(e),[i,s]=Sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $c(r,i,o,e)},UR=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&vR(t.bytes,e.bytes),$c=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var xI,NI,OI=fe(()=>{h();Th();xI=({name:t,code:e,encode:r})=>new NI(t,e,r),NI=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ja(this.code,r):r.then(n=>Ja(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var DI={};Bt(DI,{sha256:()=>cZ,sha512:()=>lZ});var VR,cZ,lZ,kR=fe(()=>{h();OI();VR=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),cZ=xI({name:"sha2-256",code:18,encode:VR("SHA-256")}),lZ=xI({name:"sha2-512",code:19,encode:VR("SHA-512")})});var PI={};Bt(PI,{identity:()=>dZ});var HR,fZ,GR,hZ,dZ,jR=fe(()=>{h();Lo();Th();HR=0,fZ="identity",GR=Vs,hZ=t=>Ja(HR,GR(t)),dZ={code:HR,name:fZ,encode:GR,digest:hZ}});var zR=fe(()=>{h();Lo()});var $Ee,YEe,QR=fe(()=>{h();$Ee=new TextEncoder,YEe=new TextDecoder});var Nm,mZ,yZ,wZ,_h,vZ,KR,WR,_m,Cm,AZ,EZ,bZ,$R=fe(()=>{h();Tm();Th();II();EI();Lo();Nm=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Cm,byteLength:Cm,code:_m,version:_m,multihash:_m,bytes:_m,_baseCache:Cm,asCID:Cm})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==_h)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==vZ)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ja(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&UR(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return yZ(r,i,e||rs.encoder);default:return wZ(r,i,e||Qc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return EZ(/^0\.0/,bZ),!!(e&&(e[WR]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||KR(r,n,i.bytes))}else if(e!=null&&e[WR]===!0){let{version:r,multihash:n,code:i}=e,s=FR(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==_h)throw new Error(`Version 0 CID must use dag-pb (code: ${_h}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=KR(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_h,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Vs(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $c(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,w]=Sh(e.subarray(r));return r+=w,d},i=n(),s=_h;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,u=n(),a=n(),c=r+a,f=c-o;return{version:i,codec:s,multihashCode:u,digestSize:a,multihashSize:f,size:c}}static parse(e,r){let[n,i]=mZ(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},mZ=(t,e)=>{switch(t[0]){case"Q":{let r=e||rs;return[rs.prefix,r.decode(`${rs.prefix}${t}`)]}case rs.prefix:{let r=e||rs;return[rs.prefix,r.decode(t)]}case Qc.prefix:{let r=e||Qc;return[Qc.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},yZ=(t,e,r)=>{let{prefix:n}=r;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},wZ=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},_h=112,vZ=18,KR=(t,e,r)=>{let n=Wc(t),i=n+Wc(e),s=new Uint8Array(i+r.byteLength);return Kc(t,s,0),Kc(e,s,n),s.set(r,i),s},WR=Symbol.for("@ipld/js-cid/CID"),_m={writable:!1,configurable:!1,enumerable:!0},Cm={writable:!1,enumerable:!1,configurable:!1},AZ="0.0.0-dev",EZ=(t,e)=>{if(t.test(AZ))console.warn(e);else throw new Error(e)},bZ=`CID.isCID(v) is deprecated and will be removed in the next major release. +Once the token is registered, you can unset this role by calling "unsetBurnRoleGlobally" (in a separate transaction).`)}issueSemiFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueSemiFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}issueNonFungible(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["issueNonFungible",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerMetaESDT(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerMetaESDT",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.bigIntToHex(e.numDecimals),ae.utf8ToHex("canFreeze"),e.canFreeze?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canWipe"),e.canWipe?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canPause"),e.canPause?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canTransferNFTCreateRole"),e.canTransferNFTCreateRole?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canChangeOwner"),e.canChangeOwner?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canUpgrade"),e.canUpgrade?this.trueAsHex:this.falseAsHex,ae.utf8ToHex("canAddSpecialRoles"),e.canAddSpecialRoles?this.trueAsHex:this.falseAsHex];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}registerAndSetAllRoles(e){this.notifyAboutUnsettingBurnRoleGlobally();let r=["registerAndSetAllRoles",ae.utf8ToHex(e.tokenName),ae.utf8ToHex(e.tokenTicker),ae.utf8ToHex(e.tokenType),ae.bigIntToHex(e.numDecimals)];return this.createTransaction({sender:e.issuer,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,value:this.config.issueCost,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitIssue,dataParts:r})}setBurnRoleGlobally(e){let r=["setBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}unsetBurnRoleGlobally(e){let r=["unsetBurnRoleGlobally",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitToggleBurnRoleGlobally,dataParts:r})}setSpecialRoleOnFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleLocalMint?[ae.utf8ToHex("ESDTRoleLocalMint")]:[],...e.addRoleLocalBurn?[ae.utf8ToHex("ESDTRoleLocalBurn")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnSemiFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTAddQuantity?[ae.utf8ToHex("ESDTRoleNFTAddQuantity")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}setSpecialRoleOnMetaESDT(e){return this.setSpecialRoleOnSemiFungible(e)}setSpecialRoleOnNonFungible(e){let r=["setSpecialRole",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user),...e.addRoleNFTCreate?[ae.utf8ToHex("ESDTRoleNFTCreate")]:[],...e.addRoleNFTBurn?[ae.utf8ToHex("ESDTRoleNFTBurn")]:[],...e.addRoleNFTUpdateAttributes?[ae.utf8ToHex("ESDTRoleNFTUpdateAttributes")]:[],...e.addRoleNFTAddURI?[ae.utf8ToHex("ESDTRoleNFTAddURI")]:[],...e.addRoleESDTTransferRole?[ae.utf8ToHex("ESDTTransferRole")]:[]];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitSetSpecialRole,dataParts:r})}nftCreate(e){let r=["ESDTNFTCreate",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.initialQuantity),ae.utf8ToHex(e.name),ae.bigIntToHex(e.royalties),ae.utf8ToHex(e.hash),ae.bufferToHex(e.attributes),...e.uris.map(ae.utf8ToHex)],i=(e.name+e.hash+e.attributes+e.uris.join("")).length*this.config.gasLimitStorePerByte.valueOf();return this.createTransaction({sender:e.creator,receiver:e.creator,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTCreate.valueOf()+i.valueOf(),dataParts:r})}pause(e){let r=["pause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}unpause(e){let r=["unPause",ae.utf8ToHex(e.tokenIdentifier)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitPausing,dataParts:r})}freeze(e){let r=["freeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}unfreeze(e){let r=["unFreeze",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitFreezing,dataParts:r})}wipe(e){let r=["wipe",ae.utf8ToHex(e.tokenIdentifier),ae.addressToHex(e.user)];return this.createTransaction({sender:e.manager,receiver:this.config.esdtContractAddress,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitWiping,dataParts:r})}localMint(e){let r=["ESDTLocalMint",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToMint)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalMint,dataParts:r})}localBurn(e){let r=["ESDTLocalBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.supplyToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTLocalBurn,dataParts:r})}updateAttributes(e){let r=["ESDTNFTUpdateAttributes",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bufferToHex(e.attributes)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTUpdateAttributes,dataParts:r})}addQuantity(e){let r=["ESDTNFTAddQuantity",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToAdd)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTAddQuantity,dataParts:r})}burnQuantity(e){let r=["ESDTNFTBurn",ae.utf8ToHex(e.tokenIdentifier),ae.bigIntToHex(e.tokenNonce),ae.bigIntToHex(e.quantityToBurn)];return this.createTransaction({sender:e.manager,receiver:e.manager,nonce:e.transactionNonce,gasPrice:e.gasPrice,gasLimitHint:e.gasLimit,executionGasLimit:this.config.gasLimitESDTNFTBurn,dataParts:r})}createTransaction({sender:e,receiver:r,nonce:n,value:i,gasPrice:s,gasLimitHint:o,executionGasLimit:u,dataParts:a}){let c=this.buildTransactionPayload(a),f=o||this.computeGasLimit(c,u),d=new h8.TransactionVersion(Eb.TRANSACTION_VERSION_DEFAULT),w=new h8.TransactionOptions(Eb.TRANSACTION_OPTIONS_DEFAULT);return new P$.Transaction({chainID:this.config.chainID,sender:e,receiver:r,gasLimit:f,gasPrice:s,nonce:n||0,value:i||0,data:c,version:d,options:w})}buildTransactionPayload(e){let r=e.join(Eb.ARGUMENTS_SEPARATOR);return new R$.TransactionPayload(r)}computeGasLimit(e,r){return this.config.minGasLimit.valueOf()+this.config.gasLimitPerByte.valueOf()*e.length()+r.valueOf()}};N0.TokenOperationsFactory=bb});var g8=D(x0=>{"use strict";h();Object.defineProperty(x0,"__esModule",{value:!0});x0.TokenOperationsFactoryConfig=void 0;var B$=Ve(),Sb=class{constructor(e){this.minGasPrice=1e9,this.minGasLimit=5e4,this.gasLimitPerByte=1500,this.gasLimitIssue=6e7,this.gasLimitToggleBurnRoleGlobally=6e7,this.gasLimitESDTLocalMint=3e5,this.gasLimitESDTLocalBurn=3e5,this.gasLimitSetSpecialRole=6e7,this.gasLimitPausing=6e7,this.gasLimitFreezing=6e7,this.gasLimitWiping=6e7,this.gasLimitESDTNFTCreate=3e6,this.gasLimitESDTNFTUpdateAttributes=1e6,this.gasLimitESDTNFTAddQuantity=1e6,this.gasLimitESDTNFTBurn=1e6,this.gasLimitStorePerByte=5e4,this.issueCost="50000000000000000",this.esdtContractAddress=B$.Address.fromBech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u"),this.chainID=e}};x0.TokenOperationsFactoryConfig=Sb});var m8=D(O0=>{"use strict";h();Object.defineProperty(O0,"__esModule",{value:!0});O0.TokenOperationsOutcomeParser=void 0;var M$=Ve(),Ib=Ie(),p8=Kd(),Tb=class{parseIssueFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issue");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueNonFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueNonFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseIssueSemiFungible(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"issueSemiFungible");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterMetaESDT(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerMetaESDT");return{tokenIdentifier:this.extractTokenIdentifier(r)}}parseRegisterAndSetAllRoles(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"registerAndSetAllRoles"),n=this.extractTokenIdentifier(r),s=this.findSingleEventByIdentifier(e,"ESDTSetRole").topics.slice(3).map(o=>o.valueOf().toString());return{tokenIdentifier:n,roles:s}}parseSetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseUnsetBurnRoleGlobally(e){return this.ensureNoError(e),{}}parseSetSpecialRole(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTSetRole"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=r.topics.slice(3).map(o=>o.valueOf().toString());return{userAddress:n,tokenIdentifier:i,roles:s}}parseNFTCreate(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTCreate"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,initialQuantity:s}}parseLocalMint(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalMint"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,mintedSupply:o}}parseLocalBurn(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTLocalBurn"),n=r.address.toString(),i=this.extractTokenIdentifier(r),s=this.extractNonce(r),o=this.extractAmount(r);return{userAddress:n,tokenIdentifier:i,nonce:s,burntSupply:o}}parsePause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTPause");return{}}parseUnpause(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnPause");return{}}parseFreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTUnFreeze"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTWipe"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{userAddress:this.extractAddress(r),tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTUpdateAttributes"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=r.topics[3]?.valueOf();return{tokenIdentifier:n,nonce:i,attributes:s}}parseAddQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTAddQuantity"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,addedQuantity:s}}parseBurnQuantity(e){this.ensureNoError(e);let r=this.findSingleEventByIdentifier(e,"ESDTNFTBurn"),n=this.extractTokenIdentifier(r),i=this.extractNonce(r),s=this.extractAmount(r);return{tokenIdentifier:n,nonce:i,burntQuantity:s}}ensureNoError(e){for(let r of e.logs.events)if(r.identifier=="signalError"){let n=p.Buffer.from(r.data.substring(1),"hex").toString(),i=r.topics[1]?.valueOf().toString();throw new Ib.ErrCannotParseTransactionOutcome(e.hash,`encountered signalError: ${i} (${n})`)}}findSingleEventByIdentifier(e,r){let n=this.gatherAllEvents(e).filter(i=>i.identifier==r);if(n.length==0)throw new Ib.ErrCannotParseTransactionOutcome(e.hash,`cannot find event of type ${r}`);if(n.length>1)throw new Ib.ErrCannotParseTransactionOutcome(e.hash,`more than one event of type ${r}`);return n[0]}gatherAllEvents(e){let r=[];r.push(...e.logs.events);for(let n of e.contractResults.items)r.push(...n.logs.events);return r}extractTokenIdentifier(e){return e.topics[0]?.valueOf().toString()}extractNonce(e){return p8.bufferToBigInt(e.topics[1]?.valueOf()).toFixed(0)}extractAmount(e){return p8.bufferToBigInt(e.topics[2]?.valueOf()).toFixed(0)}extractAddress(e){return M$.Address.fromBuffer(e.topics[3]?.valueOf()).toString()}};O0.TokenOperationsOutcomeParser=Tb});var Cb=D(Ls=>{"use strict";h();var L$=Ls&&Ls.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),_b=Ls&&Ls.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&L$(e,t,r)};Object.defineProperty(Ls,"__esModule",{value:!0});_b(d8(),Ls);_b(g8(),Ls);_b(m8(),Ls)});var y8=D(D0=>{"use strict";h();Object.defineProperty(D0,"__esModule",{value:!0});D0.DelegationTransactionsOutcomeParser=void 0;var F$=Ve(),U$=Ie(),q$=Ac(),Nb=class{constructor(){}parseCreateNewDelegationContract(e){return this.ensureNoError(e.logs.events),q$.findEventsByIdentifier(e,"SCDeploy").map(n=>({contractAddress:this.extractContractAddress(n)}))}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new U$.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractContractAddress(e){if(!e.topics[0]?.length)return"";let r=p.Buffer.from(e.topics[0]);return F$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};D0.DelegationTransactionsOutcomeParser=Nb});var A8=D(P0=>{"use strict";h();Object.defineProperty(P0,"__esModule",{value:!0});P0.SmartContractTransactionsOutcomeParser=void 0;var w8=Ve(),V$=Ie(),v8=qn(),k$=Ac(),xb=class{constructor(e){this.abi=e?.abi,this.legacyResultsParser=e?.legacyResultsParser||new v8.ResultsParser}parseDeploy(e){let r=e.transactionOutcome.directSmartContractCallOutcome,i=k$.findEventsByIdentifier(e.transactionOutcome,"SCDeploy").map(s=>this.parseScDeployEvent(s));return{returnCode:r.returnCode,returnMessage:r.returnMessage,contracts:i}}parseScDeployEvent(e){let r=e.topics[0],n=e.topics[1],i=e.topics[2],s=r?.length?new w8.Address(r).toBech32():"",o=n?.length?new w8.Address(n).toBech32():"";return{address:s,ownerAddress:o,codeHash:i}}parseExecute(e){let r=e.transactionOutcome.directSmartContractCallOutcome;if(!this.abi)return{values:r.returnDataParts,returnCode:r.returnCode,returnMessage:r.returnMessage};let n=e.function||r.function;if(!n)throw new V$.Err('Function name is not available in the transaction outcome, thus endpoint definition (ABI) cannot be picked (for parsing). Maybe provide the "function" parameter explicitly?');let i=this.abi.getEndpoint(n),s={returnCode:new v8.ReturnCode(r.returnCode),returnMessage:r.returnMessage,values:r.returnDataParts.map(u=>p.Buffer.from(u))},o=this.legacyResultsParser.parseOutcomeFromUntypedBundle(s,i);return{values:o.values.map(u=>u.valueOf()),returnCode:o.returnCode.toString(),returnMessage:o.returnMessage}}};P0.SmartContractTransactionsOutcomeParser=xb});var S8=D(R0=>{"use strict";h();Object.defineProperty(R0,"__esModule",{value:!0});R0.TokenManagementTransactionsOutcomeParser=void 0;var H$=Ve(),E8=Ie(),b8=Bu(),wr=Ac(),Ob=class{constructor(){}parseIssueFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issue").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueNonFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueNonFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseIssueSemiFungible(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"issueSemiFungible").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterMetaEsdt(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"registerMetaESDT").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseRegisterAndSetAllRoles(e){this.ensureNoError(e.logs.events);let r=wr.findEventsByIdentifier(e,"registerAndSetAllRoles"),n=wr.findEventsByIdentifier(e,"ESDTSetRole");if(r.length!==n.length)throw new E8.ErrParseTransactionOutcome("Register Events and Set Role events mismatch. Should have the same number of events.");return r.map((i,s)=>{let o=this.extractTokenIdentifier(i),a=n[s].topics.slice(3).map(c=>this.decodeTopicAsString(c));return{tokenIdentifier:o,roles:a}})}parseSetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseUnsetBurnRoleGlobally(e){this.ensureNoError(e.logs.events)}parseSetSpecialRole(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTSetRole").map(n=>this.getOutputForSetSpecialRoleEvent(n))}getOutputForSetSpecialRoleEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),s=e.topics.slice(3).map(o=>this.decodeTopicAsString(o));return{userAddress:r,tokenIdentifier:n,roles:s}}parseNftCreate(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTCreate").map(n=>this.getOutputForNftCreateEvent(n))}getOutputForNftCreateEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,initialQuantity:i}}parseLocalMint(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalMint").map(n=>this.getOutputForLocalMintEvent(n))}getOutputForLocalMintEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,mintedSupply:s}}parseLocalBurn(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTLocalBurn").map(n=>this.getOutputForLocalBurnEvent(n))}getOutputForLocalBurnEvent(e){let r=e.address,n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,burntSupply:s}}parsePause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseUnpause(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnPause").map(n=>({tokenIdentifier:this.extractTokenIdentifier(n)}))}parseFreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTFreeze").map(n=>this.getOutputForFreezeEvent(n))}getOutputForFreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUnfreeze(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTUnFreeze").map(n=>this.getOutputForUnfreezeEvent(n))}getOutputForUnfreezeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseWipe(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTWipe").map(n=>this.getOutputForWipeEvent(n))}getOutputForWipeEvent(e){let r=this.extractAddress(e),n=this.extractTokenIdentifier(e),i=this.extractNonce(e),s=this.extractAmount(e);return{userAddress:r,tokenIdentifier:n,nonce:i,balance:s}}parseUpdateAttributes(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTUpdateAttributes").map(n=>this.getOutputForUpdateAttributesEvent(n))}getOutputForUpdateAttributesEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=e.topics[3]?e.topics[3]:new Uint8Array;return{tokenIdentifier:r,nonce:n,attributes:i}}parseAddQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTAddQuantity").map(n=>this.getOutputForAddQuantityEvent(n))}getOutputForAddQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,addedQuantity:i}}parseBurnQuantity(e){return this.ensureNoError(e.logs.events),wr.findEventsByIdentifier(e,"ESDTNFTBurn").map(n=>this.getOutputForBurnQuantityEvent(n))}getOutputForBurnQuantityEvent(e){let r=this.extractTokenIdentifier(e),n=this.extractNonce(e),i=this.extractAmount(e);return{tokenIdentifier:r,nonce:n,burntQuantity:i}}ensureNoError(e){for(let r of e)if(r.identifier=="signalError"){let n=p.Buffer.from(r.dataItems[0]?.toString().slice(1)).toString()||"",i=this.decodeTopicAsString(r.topics[1]);throw new E8.ErrParseTransactionOutcome(`encountered signalError: ${i} (${p.Buffer.from(n,"hex").toString()})`)}}extractTokenIdentifier(e){return e.topics[0]?.length?this.decodeTopicAsString(e.topics[0]):""}extractNonce(e){if(!e.topics[1]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[1]);return BigInt(b8.bufferToBigInt(r).toFixed(0))}extractAmount(e){if(!e.topics[2]?.length)return BigInt(0);let r=p.Buffer.from(e.topics[2]);return BigInt(b8.bufferToBigInt(r).toFixed(0))}extractAddress(e){if(!e.topics[3]?.length)return"";let r=p.Buffer.from(e.topics[3]);return H$.Address.fromBuffer(r).bech32()}decodeTopicAsString(e){return p.Buffer.from(e).toString()}};R0.TokenManagementTransactionsOutcomeParser=Ob});var I8=D(B0=>{"use strict";h();Object.defineProperty(B0,"__esModule",{value:!0});B0.TransactionEventsParser=void 0;var G$=qn(),Db=class{constructor(e){this.legacyResultsParser=new G$.ResultsParser,this.abi=e.abi,this.firstTopicIsIdentifier=e.firstTopicIsIdentifier??!0}parseEvents(e){let r=[];for(let n of e.events){let i=this.parseEvent({event:n});r.push(i)}return r}parseEvent(e){let r=e.event.topics.map(u=>p.Buffer.from(u)),n=this.firstTopicIsIdentifier?r[0]?.toString():e.event.identifier;this.firstTopicIsIdentifier&&r.shift();let i=e.event.dataItems.map(u=>p.Buffer.from(u)),s=this.abi.getEvent(n);return this.legacyResultsParser.doParseEvent({topics:r,dataItems:i,eventDefinition:s})}};B0.TransactionEventsParser=Db});var Pb=D(vi=>{"use strict";h();var j$=vi&&vi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),rh=vi&&vi.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&j$(e,t,r)};Object.defineProperty(vi,"__esModule",{value:!0});rh(y8(),vi);rh(Ac(),vi);rh(A8(),vi);rh(S8(),vi);rh(I8(),vi)});var Ic=D(M0=>{"use strict";h();Object.defineProperty(M0,"__esModule",{value:!0});M0.Account=void 0;var z$=Ve(),Rb=class{constructor(e){this.address=z$.Address.empty(),this.nonce=0,this.balance="0",this.address=e}update(e){this.nonce=e.nonce,this.balance=e.balance}incrementNonce(){this.nonce=this.nonce.valueOf()+1}getNonceThenIncrement(){let e=this.nonce;return this.nonce=this.nonce.valueOf()+1,e}toJSON(){return{address:this.address.bech32(),nonce:this.nonce.valueOf(),balance:this.balance.toString()}}};M0.Account=Rb});var Mb=D(Tc=>{"use strict";h();Object.defineProperty(Tc,"__esModule",{value:!0});Tc.MessageComputer=Tc.Message=void 0;var nh=hr(),Q$=Ve(),K$=sf(),L0=class{constructor(e){this.data=e.data,this.signature=e.signature,this.address=e.address,this.version=e.version||nh.DEFAULT_MESSAGE_VERSION,this.signer=e.signer||nh.SDK_JS_SIGNER}};Tc.Message=L0;var Bb=class{constructor(){}computeBytesForSigning(e){let r=p.Buffer.from(e.data.length.toString()),n=p.Buffer.concat([r,e.data]),i=p.Buffer.concat([p.Buffer.from(nh.MESSAGE_PREFIX),n]);return K$("keccak256").update(i).digest()}computeBytesForVerifying(e){return this.computeBytesForSigning(e)}packMessage(e){return{message:p.Buffer.from(e.data).toString("hex"),signature:e.signature?p.Buffer.from(e.signature).toString("hex"):"",address:e.address?e.address.bech32():"",version:e.version,signer:e.signer}}unpackMessage(e){let r=this.trimHexPrefix(e.message),n=p.Buffer.from(r,"hex"),i=this.trimHexPrefix(e.signature||""),s=p.Buffer.from(i,"hex"),o;e.address&&(o=Q$.Address.fromBech32(e.address));let u=e.version||nh.DEFAULT_MESSAGE_VERSION,a=e.signer||nh.UNKNOWN_SIGNER;return new L0({data:n,signature:s,address:o,version:u,signer:a})}trimHexPrefix(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}};Tc.MessageComputer=Bb});var Ub=D(Xi=>{"use strict";h();var W$=Xi&&Xi.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),$$=Xi&&Xi.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Y$=Xi&&Xi.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&W$(e,t,r);return $$(e,t),e};Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AsyncTimer=void 0;var J$=Y$(Ie()),X$=Ie(),Lb=oo(),Fb=class{constructor(e){this.timeoutHandle=null,this.rejectionFunc=null,this.name=e,this.correlationTag=0}start(e){if(this.timeoutHandle)throw new J$.ErrAsyncTimerAlreadyRunning;return this.correlationTag++,Lb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].start()`),new Promise((r,n)=>{this.rejectionFunc=n;let i=()=>{this.rejectionFunc=null,this.stop(),r()};this.timeoutHandle=setTimeout(i,e)})}abort(){Lb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].abort()`),this.rejectionFunc&&(this.rejectionFunc(new X$.ErrAsyncTimerAborted),this.rejectionFunc=null),this.stop()}stop(){this.isStopped()||(Lb.Logger.trace(`AsyncTimer[${this.name}'${this.correlationTag}].stop()`),this.timeoutHandle&&(clearTimeout(this.timeoutHandle),this.timeoutHandle=null))}isStopped(){return!this.timeoutHandle}};Xi.AsyncTimer=Fb});var U0=D(F0=>{"use strict";h();Object.defineProperty(F0,"__esModule",{value:!0});F0.TransactionWatcher=void 0;var qb=Ub(),T8=hr(),Fs=Ie(),_8=oo(),No=class t{constructor(e,r={}){this.fetcher=new Vb(e),this.pollingIntervalMilliseconds=r.pollingIntervalMilliseconds||t.DefaultPollingInterval,this.timeoutMilliseconds=r.timeoutMilliseconds||t.DefaultTimeout,this.patienceMilliseconds=r.patienceMilliseconds||t.DefaultPatience}async awaitPending(e){let r=s=>s.status.isPending(),n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitCompleted(e){let r=s=>{if(s.isCompleted===void 0)throw new Fs.ErrIsCompletedFieldIsMissingOnTransaction;return s.isCompleted},n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}async awaitAllEvents(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.every(c=>u.includes(c))},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitAnyEvent(e,r){let n=o=>{let u=this.getAllTransactionEvents(o).map(c=>c.identifier);return r.find(c=>u.includes(c))!=null},i=async()=>{let o=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(o)},s=()=>new Fs.ErrExpectedTransactionEventsNotFound;return this.awaitConditionally(n,i,s)}async awaitOnCondition(e,r){let n=async()=>{let s=this.transactionOrTxHashToTxHash(e);return await this.fetcher.getTransaction(s)},i=()=>new Fs.ErrExpectedTransactionStatusNotReached;return this.awaitConditionally(r,n,i)}transactionOrTxHashToTxHash(e){let r=typeof e=="string"?e:e.getHash().hex();if(r.length!==T8.HEX_TRANSACTION_HASH_LENGTH)throw new Fs.Err(`Invalid transaction hash length. The length of a hex encoded hash should be ${T8.HEX_TRANSACTION_HASH_LENGTH}.`);return r}async awaitConditionally(e,r,n){let i=new qb.AsyncTimer("watcher:periodic"),s=new qb.AsyncTimer("watcher:patience"),o=new qb.AsyncTimer("watcher:timeout"),u=!1,a,c=!1;for(o.start(this.timeoutMilliseconds).finally(()=>{o.stop(),u=!0});!u;){await i.start(this.pollingIntervalMilliseconds);try{if(a=await r(),c=e(a),c||u)break}catch(f){if(_8.Logger.debug("TransactionWatcher.awaitConditionally(): cannot (yet) fetch data."),f instanceof Fs.ErrIsCompletedFieldIsMissingOnTransaction||!(f instanceof Fs.Err))throw f}}if(c&&await s.start(this.patienceMilliseconds),o.isStopped()||o.stop(),!a||!c)throw n();return a}getAllTransactionEvents(e){let r=[...e.logs.events];for(let n of e.contractResults.items)r.push(...n.logs.events);return r}};F0.TransactionWatcher=No;No.DefaultPollingInterval=6e3;No.DefaultTimeout=No.DefaultPollingInterval*15;No.DefaultPatience=0;No.NoopOnStatusReceived=t=>{};var Vb=class{constructor(e){this.fetcher=e}async getTransaction(e){return _8.Logger.debug(`transactionWatcher, getTransaction(${e})`),await this.fetcher.getTransaction(e)}}});var V0=D(q0=>{"use strict";h();Object.defineProperty(q0,"__esModule",{value:!0});q0.SignableMessage=void 0;var Z$=Ve(),eY=Yf(),tY=hr(),rY=sf(),kb=class{constructor(e){this.message=p.Buffer.from([]),this.signature=p.Buffer.from([]),this.version=1,this.signer="ErdJS",this.address=Z$.Address.empty(),Object.assign(this,e)}serializeForSigning(){let e=p.Buffer.from(this.message.length.toString()),r=p.Buffer.concat([e,this.message]),n=p.Buffer.concat([p.Buffer.from(tY.MESSAGE_PREFIX),r]);return rY("keccak256").update(n).digest()}serializeForSigningRaw(){return p.Buffer.concat([this.getMessageSize(),this.message])}getSignature(){return this.signature}applySignature(e){this.signature=eY.interpretSignatureAsBuffer(e)}getMessageSize(){let e=p.Buffer.alloc(4);return e.writeUInt32BE(this.message.length,0),e}toJSON(){return{address:this.address.bech32(),message:"0x"+this.message.toString("hex"),signature:"0x"+this.signature.toString("hex"),version:this.version,signer:this.signer}}};q0.SignableMessage=kb});var _c=D(vr=>{"use strict";h();var nY=vr&&vr.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),iY=vr&&vr.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sY=vr&&vr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&nY(e,t,r);return iY(e,t),e};Object.defineProperty(vr,"__esModule",{value:!0});vr.zeroPadStringIfOddLength=vr.isPaddedHex=vr.numberToPaddedHex=vr.Nonce=vr.Address=void 0;var C8=sY(vv()),oY="erd",Hb=class t{constructor(e){this.value=e}static fromPubkey(e){let r=C8.toWords(e),n=C8.encode(oY,r);return new t(n)}bech32(){return this.value}toString(){return this.bech32()}};vr.Address=Hb;var Gb=class{constructor(e){this.value=e}valueOf(){return this.value}hex(){return N8(this.value)}};vr.Nonce=Gb;function N8(t){let e=t.toString(16);return x8(e)}vr.numberToPaddedHex=N8;function aY(t){t=t||"";let e=p.Buffer.from(t,"hex").toString("hex");return t.toUpperCase()==e.toUpperCase()}vr.isPaddedHex=aY;function x8(t){return t=t||"",t.length%2==1?"0"+t:t}vr.zeroPadStringIfOddLength=x8});var O8=D(xo=>{"use strict";h();var uY=xo&&xo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xo,"__esModule",{value:!0});xo.EsdtContractAddress=xo.MaxUint64AsBigNumber=void 0;var cY=uY((rr(),_e(fr))),lY=_c();xo.MaxUint64AsBigNumber=new cY.default("18446744073709551615");xo.EsdtContractAddress=new lY.Address("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")});var zb=D(Cc=>{"use strict";h();var fY=Cc&&Cc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cc,"__esModule",{value:!0});Cc.ContractQueryResponse=void 0;var hY=fY((rr(),_e(fr))),dY=O8(),jb=class t{constructor(e){this.returnData=e?.returnData||[],this.returnCode=e?.returnCode||"",this.returnMessage=e?.returnMessage||"",this.gasUsed=e?.gasUsed||0}static fromHttpResponse(e){let r=e.returnData||e.ReturnData,n=e.returnCode||e.ReturnCode,i=e.returnMessage||e.ReturnMessage,s=new hY.default(e.gasRemaining||e.GasRemaining||0),o=dY.MaxUint64AsBigNumber.minus(s).toNumber();return new t({returnData:r,returnCode:n,returnMessage:i,gasUsed:o})}getReturnDataParts(){return this.returnData.map(e=>p.Buffer.from(e||"","base64"))}toJSON(){return{returnData:this.returnData,returnCode:this.returnCode,returnMessage:this.returnMessage,gasUsed:this.gasUsed.valueOf()}}};Cc.ContractQueryResponse=jb});var D8=D(Oo=>{"use strict";h();Object.defineProperty(Oo,"__esModule",{value:!0});Oo.ErrAccountNotConnected=Oo.ErrCannotSignSingleTransaction=Oo.Err=void 0;var ih=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Oo.Err=ih;var Qb=class extends ih{constructor(){super("Cannot sign single transaction.")}};Oo.ErrCannotSignSingleTransaction=Qb;var Kb=class extends ih{constructor(){super("Account is not connected.")}};Oo.ErrAccountNotConnected=Kb});var P8=D(sh=>{"use strict";h();Object.defineProperty(sh,"__esModule",{value:!0});sh.Operation=void 0;var gY;(function(t){t.Connect="connect",t.Logout="logout",t.SignTransactions="signTransactions",t.SignMessage="signMessage",t.CancelAction="cancelAction"})(gY=sh.Operation||(sh.Operation={}))});var Wb=D(Nc=>{"use strict";h();var Do=Nc&&Nc.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Nc,"__esModule",{value:!0});Nc.ExtensionProvider=void 0;var pY=Xr(),R8=D8(),oh=P8(),ah=class t{constructor(){if(this.account={address:""},this.initialized=!1,t._instance)throw new Error("Error: Instantiation failed: Use ExtensionProvider.getInstance() instead of new.");t._instance=this}static getInstance(){return t._instance}setAddress(e){return this.account.address=e,t._instance}init(){return Do(this,void 0,void 0,function*(){return window&&window.elrondWallet&&(this.initialized=!0),this.initialized})}login(e={}){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");let{token:r}=e,n=r||"";return yield this.startBgrMsgChannel(oh.Operation.Connect,n),this.account.address})}logout(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");try{yield this.startBgrMsgChannel(oh.Operation.Logout,this.account.address),this.disconnect()}catch(e){console.warn("Extension origin url is already cleared!",e)}return!0})}disconnect(){this.account={address:""}}getAddress(){return Do(this,void 0,void 0,function*(){if(!this.initialized)throw new Error("Extension provider is not initialised, call init() first");return this.account?this.account.address:""})}isInitialized(){return this.initialized}isConnected(){return Do(this,void 0,void 0,function*(){return!!this.account.address})}signTransaction(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.signTransactions([e]);if(r.length!=1)throw new R8.ErrCannotSignSingleTransaction;return r[0]})}ensureConnected(){if(!this.account.address)throw new R8.ErrAccountNotConnected}signTransactions(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r=yield this.startBgrMsgChannel(oh.Operation.SignTransactions,{from:this.account.address,transactions:e.map(n=>n.toPlainObject())});try{return r.map(i=>pY.Transaction.fromPlainObject(i))}catch(n){throw new Error(`Transaction canceled: ${n.message}.`)}})}signMessage(e){return Do(this,void 0,void 0,function*(){this.ensureConnected();let r={account:this.account.address,message:e.message.toString()},i=(yield this.startBgrMsgChannel(oh.Operation.SignMessage,r)).signature,s=p.Buffer.from(i,"hex");return e.applySignature(s),e})}cancelAction(){return this.startBgrMsgChannel(oh.Operation.CancelAction,{})}startBgrMsgChannel(e,r){return new Promise(n=>{window.postMessage({target:"erdw-inpage",type:e,data:r},window.origin);let i=s=>{s.isTrusted&&s.data.target==="erdw-contentScript"&&(s.data.type==="connectResponse"?(s.data.data&&s.data.data.address&&(this.account=s.data.data),window.removeEventListener("message",i),n(s.data.data)):(window.removeEventListener("message",i),n(s.data.data)))};window.addEventListener("message",i,!1)})}};Nc.ExtensionProvider=ah;ah._instance=new ah});function vY(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){AY(t);return}return e}function AY(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function uh(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!wY.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(mY.test(t)||yY.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,vY)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}var mY,yY,wY,U8=fe(()=>{h();mY=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,yY=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,wY=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function EY(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function gr(t,...e){try{return EY(t(...e))}catch(r){return Promise.reject(r)}}function bY(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function SY(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ch(t){if(bY(t))return String(t);if(SY(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ch(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function q8(){if(typeof p.Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}function V8(t){if(typeof t=="string")return t;q8();let e=p.Buffer.from(t).toString("base64");return $b+e}function k8(t){return typeof t!="string"||!t.startsWith($b)?t:(q8(),p.Buffer.from(t.slice($b.length),"base64"))}function Vr(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function H8(...t){return Vr(t.join(":"))}function lh(t){return t=Vr(t),t?t+":":""}var $b,G8=fe(()=>{h();$b="base64:"});function Q8(t={}){let e={mounts:{"":t.driver||TY()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=c=>{for(let f of e.mountpoints)if(c.startsWith(f))return{base:f,relativeKey:c.slice(f.length),driver:e.mounts[f]};return{base:"",relativeKey:c,driver:e.mounts[""]}},n=(c,f)=>e.mountpoints.filter(d=>d.startsWith(c)||f&&c.startsWith(d)).map(d=>({relativeBase:c.length>d.length?c.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),i=(c,f)=>{if(e.watching){f=Vr(f);for(let d of e.watchListeners)d(c,f)}},s=async()=>{if(!e.watching){e.watching=!0;for(let c in e.mounts)e.unwatch[c]=await j8(e.mounts[c],i,c)}},o=async()=>{if(e.watching){for(let c in e.unwatch)await e.unwatch[c]();e.unwatch={},e.watching=!1}},u=(c,f,d)=>{let w=new Map,A=T=>{let x=w.get(T.base);return x||(x={driver:T.driver,base:T.base,items:[]},w.set(T.base,x)),x};for(let T of c){let x=typeof T=="string",B=Vr(x?T:T.key),V=x?void 0:T.value,U=x||!T.options?f:{...f,...T.options},Q=r(B);A(Q).items.push({key:B,value:V,relativeKey:Q.relativeKey,options:U})}return Promise.all([...w.values()].map(T=>d(T))).then(T=>T.flat())},a={hasItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.hasItem,d,f)},getItem(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return gr(w.getItem,d,f).then(A=>uh(A))},getItems(c,f){return u(c,f,d=>d.driver.getItems?gr(d.driver.getItems,d.items.map(w=>({key:w.relativeKey,options:w.options})),f).then(w=>w.map(A=>({key:H8(d.base,A.key),value:uh(A.value)}))):Promise.all(d.items.map(w=>gr(d.driver.getItem,w.relativeKey,w.options).then(A=>({key:w.key,value:uh(A)})))))},getItemRaw(c,f={}){c=Vr(c);let{relativeKey:d,driver:w}=r(c);return w.getItemRaw?gr(w.getItemRaw,d,f):gr(w.getItem,d,f).then(A=>k8(A))},async setItem(c,f,d={}){if(f===void 0)return a.removeItem(c);c=Vr(c);let{relativeKey:w,driver:A}=r(c);A.setItem&&(await gr(A.setItem,w,ch(f),d),A.watch||i("update",c))},async setItems(c,f){await u(c,f,async d=>{if(d.driver.setItems)return gr(d.driver.setItems,d.items.map(w=>({key:w.relativeKey,value:ch(w.value),options:w.options})),f);d.driver.setItem&&await Promise.all(d.items.map(w=>gr(d.driver.setItem,w.relativeKey,ch(w.value),w.options)))})},async setItemRaw(c,f,d={}){if(f===void 0)return a.removeItem(c,d);c=Vr(c);let{relativeKey:w,driver:A}=r(c);if(A.setItemRaw)await gr(A.setItemRaw,w,f,d);else if(A.setItem)await gr(A.setItem,w,V8(f),d);else return;A.watch||i("update",c)},async removeItem(c,f={}){typeof f=="boolean"&&(f={removeMeta:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c);w.removeItem&&(await gr(w.removeItem,d,f),(f.removeMeta||f.removeMata)&&await gr(w.removeItem,d+"$",f),w.watch||i("remove",c))},async getMeta(c,f={}){typeof f=="boolean"&&(f={nativeOnly:f}),c=Vr(c);let{relativeKey:d,driver:w}=r(c),A=Object.create(null);if(w.getMeta&&Object.assign(A,await gr(w.getMeta,d,f)),!f.nativeOnly){let T=await gr(w.getItem,d+"$",f).then(x=>uh(x));T&&typeof T=="object"&&(typeof T.atime=="string"&&(T.atime=new Date(T.atime)),typeof T.mtime=="string"&&(T.mtime=new Date(T.mtime)),Object.assign(A,T))}return A},setMeta(c,f,d={}){return this.setItem(c+"$",f,d)},removeMeta(c,f={}){return this.removeItem(c+"$",f)},async getKeys(c,f={}){c=lh(c);let d=n(c,!0),w=[],A=[];for(let T of d){let B=(await gr(T.driver.getKeys,T.relativeBase,f)).map(V=>T.mountpoint+Vr(V)).filter(V=>!w.some(U=>V.startsWith(U)));A.push(...B),w=[T.mountpoint,...w.filter(V=>!V.startsWith(T.mountpoint))]}return c?A.filter(T=>T.startsWith(c)&&!T.endsWith("$")):A.filter(T=>!T.endsWith("$"))},async clear(c,f={}){c=lh(c),await Promise.all(n(c,!1).map(async d=>{if(d.driver.clear)return gr(d.driver.clear,d.relativeBase,f);if(d.driver.removeItem){let w=await d.driver.getKeys(d.relativeBase||"",f);return Promise.all(w.map(A=>d.driver.removeItem(A,f)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(c=>z8(c)))},async watch(c){return await s(),e.watchListeners.push(c),async()=>{e.watchListeners=e.watchListeners.filter(f=>f!==c),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(c,f){if(c=lh(c),c&&e.mounts[c])throw new Error(`already mounted at ${c}`);return c&&(e.mountpoints.push(c),e.mountpoints.sort((d,w)=>w.length-d.length)),e.mounts[c]=f,e.watching&&Promise.resolve(j8(f,i,c)).then(d=>{e.unwatch[c]=d}).catch(console.error),a},async unmount(c,f=!0){c=lh(c),!(!c||!e.mounts[c])&&(e.watching&&c in e.unwatch&&(e.unwatch[c](),delete e.unwatch[c]),f&&await z8(e.mounts[c]),e.mountpoints=e.mountpoints.filter(d=>d!==c),delete e.mounts[c])},getMount(c=""){c=Vr(c)+":";let f=r(c);return{driver:f.driver,base:f.base}},getMounts(c="",f={}){return c=Vr(c),n(c,f.parents).map(w=>({driver:w.driver,base:w.mountpoint}))}};return a}function j8(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function z8(t){typeof t.dispose=="function"&&await gr(t.dispose)}var IY,TY,K8=fe(()=>{h();U8();G8();IY="memory",TY=()=>{let t=new Map;return{name:IY,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}}});function ja(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Jb(t,e){let r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);let n=ja(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}function fh(){return Yb||(Yb=Jb("keyval-store","keyval")),Yb}function Xb(t,e=fh()){return e("readonly",r=>ja(r.get(t)))}function W8(t,e,r=fh()){return r("readwrite",n=>(n.put(e,t),ja(n.transaction)))}function $8(t,e=fh()){return e("readwrite",r=>(r.delete(t),ja(r.transaction)))}function Y8(t=fh()){return t("readwrite",e=>(e.clear(),ja(e.transaction)))}function _Y(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},ja(t.transaction)}function J8(t=fh()){return t("readonly",e=>{if(e.getAllKeys)return ja(e.getAllKeys());let r=[];return _Y(e,n=>r.push(n.key)).then(()=>r)})}var Yb,X8=fe(()=>{h()});var Z8={};Bt(Z8,{safeJsonParse:()=>Ro,safeJsonStringify:()=>Ai});function Ro(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return NY(t)}catch{return t}}function Ai(t){return typeof t=="string"?t:CY(t)||""}var CY,NY,xc=fe(()=>{h();CY=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),NY=t=>{let e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)}});var tP={};Bt(tP,{KeyValueStorage:()=>rS,default:()=>rS});function RY(t){var e;return[t[0],Ro((e=t[1])!=null?e:"")]}var xY,OY,DY,PY,eS,Zb,j0,tS,BY,eP,MY,LY,rS,rP=fe(()=>{h();K8();X8();xc();xY="idb-keyval",OY=(t={})=>{let e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i,n;return t.dbName&&t.storeName&&(n=Jb(t.dbName,t.storeName)),{name:xY,options:t,async hasItem(i){return!(typeof await Xb(r(i),n)>"u")},async getItem(i){return await Xb(r(i),n)??null},setItem(i,s){return W8(r(i),s,n)},removeItem(i){return $8(r(i),n)},getKeys(){return J8(n)},clear(){return Y8(n)}}},DY="WALLET_CONNECT_V2_INDEXED_DB",PY="keyvaluestorage",eS=class{constructor(){this.indexedDb=Q8({driver:OY({dbName:DY,storeName:PY})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){let r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ai(r))}async removeItem(e){await this.indexedDb.removeItem(e)}},Zb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},j0={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Zb<"u"&&Zb.localStorage?j0.exports=Zb.localStorage:typeof window<"u"&&window.localStorage?j0.exports=window.localStorage:j0.exports=new e})();tS=class{constructor(){this.localStorage=j0.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(RY)}async getItem(e){let r=this.localStorage.getItem(e);if(r!==null)return Ro(r)}async setItem(e,r){this.localStorage.setItem(e,Ai(r))}async removeItem(e){this.localStorage.removeItem(e)}},BY="wc_storage_version",eP=1,MY=async(t,e,r)=>{let n=BY,i=await e.getItem(n);if(i&&i>=eP){r(e);return}let s=await t.getKeys();if(!s.length){r(e);return}let o=[];for(;s.length;){let u=s.shift();if(!u)continue;let a=u.toLowerCase();if(a.includes("wc@")||a.includes("walletconnect")||a.includes("wc_")||a.includes("wallet_connect")){let c=await t.getItem(u);await e.setItem(u,c),o.push(u)}}await e.setItem(n,eP),r(e),LY(t,o)},LY=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})},rS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let e=new tS;this.storage=e;try{let r=new eS;MY(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}});var Zi={};Bt(Zi,{__assign:()=>iS,__asyncDelegator:()=>$Y,__asyncGenerator:()=>WY,__asyncValues:()=>YY,__await:()=>hh,__awaiter:()=>HY,__classPrivateFieldGet:()=>eJ,__classPrivateFieldSet:()=>tJ,__createBinding:()=>jY,__decorate:()=>qY,__exportStar:()=>zY,__extends:()=>FY,__generator:()=>GY,__importDefault:()=>ZY,__importStar:()=>XY,__makeTemplateObject:()=>JY,__metadata:()=>kY,__param:()=>VY,__read:()=>nP,__rest:()=>UY,__spread:()=>QY,__spreadArrays:()=>KY,__values:()=>sS});function FY(t,e){nS(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function UY(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i=0;u--)(o=t[u])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function VY(t,e){return function(r,n){e(r,n,t)}}function kY(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function HY(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})}function GY(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(c){return function(f){return a([c,f])}}function a(c){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=c[0]&2?i.return:c[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,c[1])).done)return s;switch(i=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function nP(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function QY(){for(var t=[],e=0;e1||u(w,A)})})}function u(w,A){try{a(n[w](A))}catch(T){d(s[0][3],T)}}function a(w){w.value instanceof hh?Promise.resolve(w.value.v).then(c,f):d(s[0][2],w)}function c(w){u("next",w)}function f(w){u("throw",w)}function d(w,A){w(A),s.shift(),s.length&&u(s[0][0],s[0][1])}}function $Y(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:hh(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function YY(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof sS=="function"?sS(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(u,a){o=t[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(c){s({value:c,done:u})},o)}}function JY(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function XY(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function ZY(t){return t&&t.__esModule?t:{default:t}}function eJ(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function tJ(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var nS,iS,es=fe(()=>{h();nS=function(t,e){return nS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},nS(t,e)};iS=function(){return iS=Object.assign||function(e){for(var r,n=1,i=arguments.length;n{"use strict";h();Object.defineProperty(z0,"__esModule",{value:!0});z0.delay=void 0;function rJ(t){return new Promise(e=>{setTimeout(()=>{e(!0)},t)})}z0.delay=rJ});var sP=D(Oc=>{"use strict";h();Object.defineProperty(Oc,"__esModule",{value:!0});Oc.ONE_THOUSAND=Oc.ONE_HUNDRED=void 0;Oc.ONE_HUNDRED=100;Oc.ONE_THOUSAND=1e3});var oP=D(le=>{"use strict";h();Object.defineProperty(le,"__esModule",{value:!0});le.ONE_YEAR=le.FOUR_WEEKS=le.THREE_WEEKS=le.TWO_WEEKS=le.ONE_WEEK=le.THIRTY_DAYS=le.SEVEN_DAYS=le.FIVE_DAYS=le.THREE_DAYS=le.ONE_DAY=le.TWENTY_FOUR_HOURS=le.TWELVE_HOURS=le.SIX_HOURS=le.THREE_HOURS=le.ONE_HOUR=le.SIXTY_MINUTES=le.THIRTY_MINUTES=le.TEN_MINUTES=le.FIVE_MINUTES=le.ONE_MINUTE=le.SIXTY_SECONDS=le.THIRTY_SECONDS=le.TEN_SECONDS=le.FIVE_SECONDS=le.ONE_SECOND=void 0;le.ONE_SECOND=1;le.FIVE_SECONDS=5;le.TEN_SECONDS=10;le.THIRTY_SECONDS=30;le.SIXTY_SECONDS=60;le.ONE_MINUTE=le.SIXTY_SECONDS;le.FIVE_MINUTES=le.ONE_MINUTE*5;le.TEN_MINUTES=le.ONE_MINUTE*10;le.THIRTY_MINUTES=le.ONE_MINUTE*30;le.SIXTY_MINUTES=le.ONE_MINUTE*60;le.ONE_HOUR=le.SIXTY_MINUTES;le.THREE_HOURS=le.ONE_HOUR*3;le.SIX_HOURS=le.ONE_HOUR*6;le.TWELVE_HOURS=le.ONE_HOUR*12;le.TWENTY_FOUR_HOURS=le.ONE_HOUR*24;le.ONE_DAY=le.TWENTY_FOUR_HOURS;le.THREE_DAYS=le.ONE_DAY*3;le.FIVE_DAYS=le.ONE_DAY*5;le.SEVEN_DAYS=le.ONE_DAY*7;le.THIRTY_DAYS=le.ONE_DAY*30;le.ONE_WEEK=le.SEVEN_DAYS;le.TWO_WEEKS=le.ONE_WEEK*2;le.THREE_WEEKS=le.ONE_WEEK*3;le.FOUR_WEEKS=le.ONE_WEEK*4;le.ONE_YEAR=le.ONE_DAY*365});var oS=D(Q0=>{"use strict";h();Object.defineProperty(Q0,"__esModule",{value:!0});var aP=(es(),_e(Zi));aP.__exportStar(sP(),Q0);aP.__exportStar(oP(),Q0)});var cP=D(Dc=>{"use strict";h();Object.defineProperty(Dc,"__esModule",{value:!0});Dc.fromMiliseconds=Dc.toMiliseconds=void 0;var uP=oS();function nJ(t){return t*uP.ONE_THOUSAND}Dc.toMiliseconds=nJ;function iJ(t){return Math.floor(t/uP.ONE_THOUSAND)}Dc.fromMiliseconds=iJ});var fP=D(K0=>{"use strict";h();Object.defineProperty(K0,"__esModule",{value:!0});var lP=(es(),_e(Zi));lP.__exportStar(iP(),K0);lP.__exportStar(cP(),K0)});var hP=D(dh=>{"use strict";h();Object.defineProperty(dh,"__esModule",{value:!0});dh.Watch=void 0;var W0=class{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){let r=this.get(e);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${e}`);let n=Date.now()-r.started;this.timestamps.set(e,{started:r.started,elapsed:n})}get(e){let r=this.timestamps.get(e);if(typeof r>"u")throw new Error(`No timestamp found for label: ${e}`);return r}elapsed(e){let r=this.get(e);return r.elapsed||Date.now()-r.started}};dh.Watch=W0;dh.default=W0});var dP=D($0=>{"use strict";h();Object.defineProperty($0,"__esModule",{value:!0});$0.IWatch=void 0;var aS=class{};$0.IWatch=aS});var gP=D(uS=>{"use strict";h();Object.defineProperty(uS,"__esModule",{value:!0});var sJ=(es(),_e(Zi));sJ.__exportStar(dP(),uS)});var za=D(Pc=>{"use strict";h();Object.defineProperty(Pc,"__esModule",{value:!0});var Y0=(es(),_e(Zi));Y0.__exportStar(fP(),Pc);Y0.__exportStar(hP(),Pc);Y0.__exportStar(gP(),Pc);Y0.__exportStar(oS(),Pc)});var cS,pP=fe(()=>{h();cS=class{}});var lS={};Bt(lS,{IEvents:()=>cS});var fS=fe(()=>{h();pP()});var mP=D(J0=>{"use strict";h();Object.defineProperty(J0,"__esModule",{value:!0});J0.IHeartBeat=void 0;var oJ=(fS(),_e(lS)),hS=class extends oJ.IEvents{constructor(e){super()}};J0.IHeartBeat=hS});var gS=D(dS=>{"use strict";h();Object.defineProperty(dS,"__esModule",{value:!0});var aJ=(es(),_e(Zi));aJ.__exportStar(mP(),dS)});var yP=D(Rc=>{"use strict";h();Object.defineProperty(Rc,"__esModule",{value:!0});Rc.HEARTBEAT_EVENTS=Rc.HEARTBEAT_INTERVAL=void 0;var uJ=za();Rc.HEARTBEAT_INTERVAL=uJ.FIVE_SECONDS;Rc.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"}});var mS=D(pS=>{"use strict";h();Object.defineProperty(pS,"__esModule",{value:!0});var cJ=(es(),_e(Zi));cJ.__exportStar(yP(),pS)});var wP=D(X0=>{"use strict";h();Object.defineProperty(X0,"__esModule",{value:!0});X0.HeartBeat=void 0;var yS=(es(),_e(Zi)),lJ=Ds(),fJ=za(),hJ=gS(),wS=mS(),vS=class t extends hJ.IHeartBeat{constructor(e){super(e),this.events=new lJ.EventEmitter,this.interval=wS.HEARTBEAT_INTERVAL,this.interval=e?.interval||wS.HEARTBEAT_INTERVAL}static init(e){return yS.__awaiter(this,void 0,void 0,function*(){let r=new t(e);return yield r.init(),r})}init(){return yS.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}initialize(){return yS.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),fJ.toMiliseconds(this.interval))})}pulse(){this.events.emit(wS.HEARTBEAT_EVENTS.pulse)}};X0.HeartBeat=vS});var vP=D(gh=>{"use strict";h();Object.defineProperty(gh,"__esModule",{value:!0});var AS=(es(),_e(Zi));AS.__exportStar(wP(),gh);AS.__exportStar(gS(),gh);AS.__exportStar(mS(),gh)});var EP=D((VAe,AP)=>{"use strict";h();function dJ(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}AP.exports=gJ;function gJ(t,e,r){var n=r&&r.stringify||dJ,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var u=1;u-1?d:0,t.charCodeAt(A+1)){case 100:case 102:if(f>=a||e[f]==null)break;d=a||e[f]==null)break;d=a||e[f]===void 0)break;d",d=A+2,A++;break}c+=n(e[f]),d=A+2,A++;break;case 115:if(f>=a)break;d{"use strict";h();var bP=EP();TP.exports=ts;var ph=IJ().console||{},pJ={mapHttpRequest:Z0,mapHttpResponse:Z0,wrapRequestSerializer:ES,wrapResponseSerializer:ES,wrapErrorSerializer:ES,req:Z0,res:Z0,err:AJ};function mJ(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ts(t){t=t||{},t.browser=t.browser||{};let e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");let r=t.browser.write||ph;t.browser.write&&(t.browser.asObject=!0);let n=t.serializers||{},i=mJ(t.browser.serialize,n),s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");let u=t.level||"info",a=Object.create(r);a.log||(a.log=mh),Object.defineProperty(a,"levelVal",{get:f}),Object.defineProperty(a,"level",{get:d,set:w});let c={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:EJ(t)};a.levels=ts.levels,a.level=u,a.setMaxListeners=a.getMaxListeners=a.emit=a.addListener=a.on=a.prependListener=a.once=a.prependOnceListener=a.removeListener=a.removeAllListeners=a.listeners=a.listenerCount=a.eventNames=a.write=a.flush=mh,a.serializers=n,a._serialize=i,a._stdErrSerialize=s,a.child=A,e&&(a._logEvent=bS());function f(){return this.level==="silent"?1/0:this.levels.values[this.level]}function d(){return this._level}function w(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,Bc(c,a,"error","log"),Bc(c,a,"fatal","error"),Bc(c,a,"warn","error"),Bc(c,a,"info","log"),Bc(c,a,"debug","log"),Bc(c,a,"trace","log")}function A(T,x){if(!T)throw new Error("missing bindings for child Pino");x=x||{},i&&T.serializers&&(x.serializers=T.serializers);let B=x.serializers;if(i&&B){var V=Object.assign({},n,B),U=t.browser.serialize===!0?Object.keys(V):i;delete T.serializers,em([T],U,V,this._stdErrSerialize)}function Q(L){this._childLevel=(L._childLevel|0)+1,this.error=Mc(L,T,"error"),this.fatal=Mc(L,T,"fatal"),this.warn=Mc(L,T,"warn"),this.info=Mc(L,T,"info"),this.debug=Mc(L,T,"debug"),this.trace=Mc(L,T,"trace"),V&&(this.serializers=V,this._serialize=U),e&&(this._logEvent=bS([].concat(L._logEvent.bindings,T)))}return Q.prototype=this,new Q(this)}return a}ts.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};ts.stdSerializers=pJ;ts.stdTimeFunctions=Object.assign({},{nullTime:SP,epochTime:IP,unixTime:bJ,isoTime:SJ});function Bc(t,e,r,n){let i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mh:i[r]?i[r]:ph[r]||ph[n]||mh,yJ(t,e,r)}function yJ(t,e,r){!t.transmit&&e[r]===mh||(e[r]=function(n){return function(){let s=t.timestamp(),o=new Array(arguments.length),u=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ph?ph:this;for(var a=0;a-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Mc(t,e,r){return function(){let n=new Array(1+arguments.length);n[0]=e;for(var i=1;ism,PINO_CUSTOM_CONTEXT_KEY:()=>Lc,PINO_LOGGER_DEFAULTS:()=>xP,formatChildLoggerContext:()=>RP,generateChildLogger:()=>DJ,generateClientLogger:()=>BP,generatePlatformLogger:()=>PJ,generateServerLogger:()=>MP,getBrowserLoggerContext:()=>OP,getDefaultLoggerOptions:()=>OJ,getLoggerContext:()=>PP,pino:()=>NP.default,setBrowserLoggerContext:()=>DP});function OJ(t){return im(nm({},t),{level:t?.level||xP.level})}function OP(t,e=Lc){return t[e]||""}function DP(t,e,r=Lc){return t[r]=e,t}function PP(t,e=Lc){let r="";return typeof t.bindings>"u"?r=OP(t,e):r=t.bindings().context||"",r}function RP(t,e,r=Lc){let n=PP(t,r);return n.trim()?`${n}/${e}`:e}function DJ(t,e,r=Lc){let n=RP(t,e,r),i=t.child({context:n});return DP(i,n,r)}function BP(t){var e,r;let n=new TS((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(im(nm({},t.opts),{level:"trace",browser:im(nm({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function MP(t){var e;let r=new _S((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:(0,Us.default)(im(nm({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function PJ(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?BP(t):MP(t)}var Us,NP,xP,Lc,sm,IS,tm,rm,TS,_S,TJ,_J,CJ,_P,NJ,xJ,CP,nm,im,NS=fe(()=>{h();Us=pe(SS()),NP=pe(SS());xc();xP={level:"info"},Lc="custom_context",sm=1e3*1024,IS=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},tm=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){let r=new IS(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){let e=[],r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};let r=e.value;return e=e.next,{done:!1,value:r}}}}},rm=class{constructor(e,r=sm){this.level=e??"error",this.levelValue=Us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new tm(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Us.levels.values.error?console.error(e):r===Us.levels.values.warn?console.warn(e):r===Us.levels.values.debug?console.debug(e):r===Us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ai({timestamp:new Date().toISOString(),log:e}));let r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new tm(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){let r=this.getLogArray();return r.push(Ai({extraMetadata:e})),new Blob(r,{type:"application/json"})}},TS=class{constructor(e,r=sm){this.baseChunkLogger=new rm(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){let r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},_S=class{constructor(e,r=sm){this.baseChunkLogger=new rm(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}},TJ=Object.defineProperty,_J=Object.defineProperties,CJ=Object.getOwnPropertyDescriptors,_P=Object.getOwnPropertySymbols,NJ=Object.prototype.hasOwnProperty,xJ=Object.prototype.propertyIsEnumerable,CP=(t,e,r)=>e in t?TJ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nm=(t,e)=>{for(var r in e||(e={}))NJ.call(e,r)&&CP(t,r,e[r]);if(_P)for(var r of _P(e))xJ.call(e,r)&&CP(t,r,e[r]);return t},im=(t,e)=>_J(t,CJ(e))});var KS=D(ar=>{"use strict";h();Object.defineProperty(ar,"__esModule",{value:!0});var Fc=(fS(),_e(lS)),LP=Ds();function RJ(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var BJ=RJ(LP),xS=class extends Fc.IEvents{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}},OS=class{constructor(e,r,n){this.core=e,this.logger=r}},DS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r,this.records=new Map}},PS=class{constructor(e,r){this.logger=e,this.core=r}},RS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},BS=class extends Fc.IEvents{constructor(e){super()}},MS=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},LS=class{constructor(){this.map=new Map}},FS=class extends Fc.IEvents{constructor(e,r){super(),this.relayer=e,this.logger=r}},US=class{constructor(e,r){this.core=e,this.logger=r}},qS=class extends Fc.IEvents{constructor(e,r){super(),this.core=e,this.logger=r}},VS=class{constructor(e,r){this.logger=e,this.core=r}},kS=class{constructor(e,r){this.projectId=e,this.logger=r}},HS=class{constructor(e,r){this.projectId=e,this.logger=r}},GS=class extends BJ.default{constructor(){super()}},jS=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},zS=class extends LP.EventEmitter{constructor(){super()}},QS=class{constructor(e){this.client=e}};ar.ICore=xS,ar.ICrypto=OS,ar.IEchoClient=HS,ar.IEngine=QS,ar.IEngineEvents=zS,ar.IExpirer=qS,ar.IJsonRpcHistory=DS,ar.IKeyChain=US,ar.IMessageTracker=PS,ar.IPairing=VS,ar.IPublisher=RS,ar.IRelayer=BS,ar.ISignClient=jS,ar.ISignClientEvents=GS,ar.IStore=MS,ar.ISubscriber=FS,ar.ISubscriberTopicMap=LS,ar.IVerify=kS});var UP=D(om=>{"use strict";h();Object.defineProperty(om,"__esModule",{value:!0});om.BrowserRandomSource=void 0;var FP=65536,WS=class{constructor(){this.isAvailable=!1,this.isInstantiated=!1;let e=typeof self<"u"?self.crypto||self.msCrypto:null;e&&e.getRandomValues!==void 0&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Browser random byte generator is not available.");let r=new Uint8Array(e);for(let n=0;n{"use strict";h();Object.defineProperty($S,"__esModule",{value:!0});function MJ(t){for(var e=0;e{h()});var VP=D(am=>{"use strict";h();Object.defineProperty(am,"__esModule",{value:!0});am.NodeRandomSource=void 0;var LJ=Qn(),YS=class{constructor(){if(this.isAvailable=!1,this.isInstantiated=!1,typeof Pd<"u"){let e=qP();e&&e.randomBytes&&(this._crypto=e,this.isAvailable=!0,this.isInstantiated=!0)}}randomBytes(e){if(!this.isAvailable||!this._crypto)throw new Error("Node.js random byte generator is not available.");let r=this._crypto.randomBytes(e);if(r.length!==e)throw new Error("NodeRandomSource: got fewer bytes than requested");let n=new Uint8Array(e);for(let i=0;i{"use strict";h();Object.defineProperty(um,"__esModule",{value:!0});um.SystemRandomSource=void 0;var FJ=UP(),UJ=VP(),JS=class{constructor(){if(this.isAvailable=!1,this.name="",this._source=new FJ.BrowserRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Browser";return}if(this._source=new UJ.NodeRandomSource,this._source.isAvailable){this.isAvailable=!0,this.name="Node";return}}randomBytes(e){if(!this.isAvailable)throw new Error("System random byte generator is not available.");return this._source.randomBytes(e)}};um.SystemRandomSource=JS});var HP=D(dn=>{"use strict";h();Object.defineProperty(dn,"__esModule",{value:!0});function qJ(t,e){var r=t>>>16&65535,n=t&65535,i=e>>>16&65535,s=e&65535;return n*s+(r*s+n*i<<16>>>0)|0}dn.mul=Math.imul||qJ;function VJ(t,e){return t+e|0}dn.add=VJ;function kJ(t,e){return t-e|0}dn.sub=kJ;function HJ(t,e){return t<>>32-e}dn.rotl=HJ;function GJ(t,e){return t<<32-e|t>>>e}dn.rotr=GJ;function jJ(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t}dn.isInteger=Number.isInteger||jJ;dn.MAX_SAFE_INTEGER=9007199254740991;dn.isSafeInteger=function(t){return dn.isInteger(t)&&t>=-dn.MAX_SAFE_INTEGER&&t<=dn.MAX_SAFE_INTEGER}});var Uc=D(xe=>{"use strict";h();Object.defineProperty(xe,"__esModule",{value:!0});var GP=HP();function zJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])<<16>>16}xe.readInt16BE=zJ;function QJ(t,e){return e===void 0&&(e=0),(t[e+0]<<8|t[e+1])>>>0}xe.readUint16BE=QJ;function KJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])<<16>>16}xe.readInt16LE=KJ;function WJ(t,e){return e===void 0&&(e=0),(t[e+1]<<8|t[e])>>>0}xe.readUint16LE=WJ;function jP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>8,e[r+1]=t>>>0,e}xe.writeUint16BE=jP;xe.writeInt16BE=jP;function zP(t,e,r){return e===void 0&&(e=new Uint8Array(2)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e}xe.writeUint16LE=zP;xe.writeInt16LE=zP;function XS(t,e){return e===void 0&&(e=0),t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}xe.readInt32BE=XS;function ZS(t,e){return e===void 0&&(e=0),(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}xe.readUint32BE=ZS;function eI(t,e){return e===void 0&&(e=0),t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e]}xe.readInt32LE=eI;function tI(t,e){return e===void 0&&(e=0),(t[e+3]<<24|t[e+2]<<16|t[e+1]<<8|t[e])>>>0}xe.readUint32LE=tI;function cm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>24,e[r+1]=t>>>16,e[r+2]=t>>>8,e[r+3]=t>>>0,e}xe.writeUint32BE=cm;xe.writeInt32BE=cm;function lm(t,e,r){return e===void 0&&(e=new Uint8Array(4)),r===void 0&&(r=0),e[r+0]=t>>>0,e[r+1]=t>>>8,e[r+2]=t>>>16,e[r+3]=t>>>24,e}xe.writeUint32LE=lm;xe.writeInt32LE=lm;function $J(t,e){e===void 0&&(e=0);var r=XS(t,e),n=XS(t,e+4);return r*4294967296+n-(n>>31)*4294967296}xe.readInt64BE=$J;function YJ(t,e){e===void 0&&(e=0);var r=ZS(t,e),n=ZS(t,e+4);return r*4294967296+n}xe.readUint64BE=YJ;function JJ(t,e){e===void 0&&(e=0);var r=eI(t,e),n=eI(t,e+4);return n*4294967296+r-(r>>31)*4294967296}xe.readInt64LE=JJ;function XJ(t,e){e===void 0&&(e=0);var r=tI(t,e),n=tI(t,e+4);return n*4294967296+r}xe.readUint64LE=XJ;function QP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),cm(t/4294967296>>>0,e,r),cm(t>>>0,e,r+4),e}xe.writeUint64BE=QP;xe.writeInt64BE=QP;function KP(t,e,r){return e===void 0&&(e=new Uint8Array(8)),r===void 0&&(r=0),lm(t>>>0,e,r),lm(t/4294967296>>>0,e,r+4),e}xe.writeUint64LE=KP;xe.writeInt64LE=KP;function ZJ(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintBE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintBE: array is too short for the given bitLength");for(var n=0,i=1,s=t/8+r-1;s>=r;s--)n+=e[s]*i,i*=256;return n}xe.readUintBE=ZJ;function eX(t,e,r){if(r===void 0&&(r=0),t%8!==0)throw new Error("readUintLE supports only bitLengths divisible by 8");if(t/8>e.length-r)throw new Error("readUintLE: array is too short for the given bitLength");for(var n=0,i=1,s=r;s=n;s--)r[s]=e/i&255,i*=256;return r}xe.writeUintBE=tX;function rX(t,e,r,n){if(r===void 0&&(r=new Uint8Array(t/8)),n===void 0&&(n=0),t%8!==0)throw new Error("writeUintLE supports only bitLengths divisible by 8");if(!GP.isSafeInteger(e))throw new Error("writeUintLE value must be an integer");for(var i=1,s=n;s{"use strict";h();Object.defineProperty(Br,"__esModule",{value:!0});Br.randomStringForEntropy=Br.randomString=Br.randomUint32=Br.randomBytes=Br.defaultRandomSource=void 0;var fX=kP(),hX=Uc(),WP=Qn();Br.defaultRandomSource=new fX.SystemRandomSource;function rI(t,e=Br.defaultRandomSource){return e.randomBytes(t)}Br.randomBytes=rI;function dX(t=Br.defaultRandomSource){let e=rI(4,t),r=(0,hX.readUint32LE)(e);return(0,WP.wipe)(e),r}Br.randomUint32=dX;var $P="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function YP(t,e=$P,r=Br.defaultRandomSource){if(e.length<2)throw new Error("randomString charset is too short");if(e.length>256)throw new Error("randomString charset is too long");let n="",i=e.length,s=256-256%i;for(;t>0;){let o=rI(Math.ceil(t*256/s),r);for(let u=0;u0;u++){let a=o[u];a{"use strict";h();Object.defineProperty(qs,"__esModule",{value:!0});var Vc=Uc(),qc=Qn();qs.DIGEST_LENGTH=64;qs.BLOCK_SIZE=128;var XP=function(){function t(){this.digestLength=qs.DIGEST_LENGTH,this.blockSize=qs.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){qc.wipe(this._buffer),qc.wipe(this._tempHi),qc.wipe(this._tempLo),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(nI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=nI(this._tempHi,this._tempLo,this._stateHi,this._stateLo,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%128<112?128:256;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._stateHi.set(e.stateHi),this._stateLo.set(e.stateLo),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){qc.wipe(e.stateHi),qc.wipe(e.stateLo),e.buffer&&qc.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();qs.SHA512=XP;var JP=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function nI(t,e,r,n,i,s,o){for(var u=r[0],a=r[1],c=r[2],f=r[3],d=r[4],w=r[5],A=r[6],T=r[7],x=n[0],B=n[1],V=n[2],U=n[3],Q=n[4],L=n[5],k=n[6],H=n[7],q,v,C,P,F,R,l,g;o>=128;){for(var y=0;y<16;y++){var E=8*y+s;t[y]=Vc.readUint32BE(i,E),e[y]=Vc.readUint32BE(i,E+4)}for(var y=0;y<80;y++){var I=u,_=a,M=c,N=f,m=d,O=w,Y=A,$=T,b=x,j=B,z=V,W=U,ie=Q,te=L,ee=k,se=H;if(q=T,v=H,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=(d>>>14|Q<<18)^(d>>>18|Q<<14)^(Q>>>9|d<<23),v=(Q>>>14|d<<18)^(Q>>>18|d<<14)^(d>>>9|Q<<23),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=d&w^~d&A,v=Q&L^~Q&k,F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=JP[y*2],v=JP[y*2+1],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=t[y%16],v=e[y%16],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,C=l&65535|g<<16,P=F&65535|R<<16,q=C,v=P,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=(u>>>28|x<<4)^(x>>>2|u<<30)^(x>>>7|u<<25),v=(x>>>28|u<<4)^(u>>>2|x<<30)^(u>>>7|x<<25),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,q=u&a^u&c^a&c,v=x&B^x&V^B&V,F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,$=l&65535|g<<16,se=F&65535|R<<16,q=N,v=W,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=C,v=P,F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,N=l&65535|g<<16,W=F&65535|R<<16,a=I,c=_,f=M,d=N,w=m,A=O,T=Y,u=$,B=b,V=j,U=z,Q=W,L=ie,k=te,H=ee,x=se,y%16===15)for(var E=0;E<16;E++)q=t[E],v=e[E],F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=t[(E+9)%16],v=e[(E+9)%16],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+1)%16],P=e[(E+1)%16],q=(C>>>1|P<<31)^(C>>>8|P<<24)^C>>>7,v=(P>>>1|C<<31)^(P>>>8|C<<24)^(P>>>7|C<<25),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,C=t[(E+14)%16],P=e[(E+14)%16],q=(C>>>19|P<<13)^(P>>>29|C<<3)^C>>>6,v=(P>>>19|C<<13)^(C>>>29|P<<3)^(P>>>6|C<<26),F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,t[E]=l&65535|g<<16,e[E]=F&65535|R<<16}q=u,v=x,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[0],v=n[0],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[0]=u=l&65535|g<<16,n[0]=x=F&65535|R<<16,q=a,v=B,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[1],v=n[1],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[1]=a=l&65535|g<<16,n[1]=B=F&65535|R<<16,q=c,v=V,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[2],v=n[2],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[2]=c=l&65535|g<<16,n[2]=V=F&65535|R<<16,q=f,v=U,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[3],v=n[3],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[3]=f=l&65535|g<<16,n[3]=U=F&65535|R<<16,q=d,v=Q,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[4],v=n[4],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[4]=d=l&65535|g<<16,n[4]=Q=F&65535|R<<16,q=w,v=L,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[5],v=n[5],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[5]=w=l&65535|g<<16,n[5]=L=F&65535|R<<16,q=A,v=k,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[6],v=n[6],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[6]=A=l&65535|g<<16,n[6]=k=F&65535|R<<16,q=T,v=H,F=v&65535,R=v>>>16,l=q&65535,g=q>>>16,q=r[7],v=n[7],F+=v&65535,R+=v>>>16,l+=q&65535,g+=q>>>16,R+=F>>>16,l+=R>>>16,g+=l>>>16,r[7]=T=l&65535|g<<16,n[7]=H=F&65535|R<<16,s+=128,o-=128}return s}function pX(t){var e=new XP;e.update(t);var r=e.digest();return e.clean(),r}qs.hash=pX});var dR=D(Ge=>{"use strict";h();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.convertSecretKeyToX25519=Ge.convertPublicKeyToX25519=Ge.verify=Ge.sign=Ge.extractPublicKeyFromSecretKey=Ge.generateKeyPair=Ge.generateKeyPairFromSeed=Ge.SEED_LENGTH=Ge.SECRET_KEY_LENGTH=Ge.PUBLIC_KEY_LENGTH=Ge.SIGNATURE_LENGTH=void 0;var mX=yh(),wh=ZP(),iR=Qn();Ge.SIGNATURE_LENGTH=64;Ge.PUBLIC_KEY_LENGTH=32;Ge.SECRET_KEY_LENGTH=64;Ge.SEED_LENGTH=32;function ve(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,sR(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function oR(t,e){let r=0;for(let n=0;n<32;n++)r|=t[n]^e[n];return(1&r-1>>>8)-1}function rR(t,e){let r=new Uint8Array(32),n=new Uint8Array(32);return vh(r,t),vh(n,e),oR(r,n)}function aR(t){let e=new Uint8Array(32);return vh(e,t),e[0]&1}function EX(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Qa(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Wa(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function Ct(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,B=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,P=0,F=0,R=0,l=0,g=0,y=0,E=0,I=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,B+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,B+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,B+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,B+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,B+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,B+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,B+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,P+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,B+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,P+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,B+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,P+=n*oe,F+=n*J,R+=n*ue,n=e[9],T+=n*N,x+=n*m,B+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,P+=n*se,F+=n*oe,R+=n*J,l+=n*ue,n=e[10],x+=n*N,B+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,P+=n*ee,F+=n*se,R+=n*oe,l+=n*J,g+=n*ue,n=e[11],B+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,P+=n*te,F+=n*ee,R+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,P+=n*ie,F+=n*te,R+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,P+=n*W,F+=n*ie,R+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,I+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,P+=n*z,F+=n*W,R+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,I+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,P+=n*j,F+=n*z,R+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,I+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*P,d+=38*F,w+=38*R,A+=38*l,T+=38*g,x+=38*y,B+=38*E,V+=38*I,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=B,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ka(t,e){Ct(t,e,e)}function uR(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=253;n>=0;n--)Ka(r,r),n!==2&&n!==4&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function bX(t,e){let r=ve(),n;for(n=0;n<16;n++)r[n]=e[n];for(n=250;n>=0;n--)Ka(r,r),n!==1&&Ct(r,r,e);for(n=0;n<16;n++)t[n]=r[n]}function aI(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve(),c=ve(),f=ve();Wa(r,t[1],t[0]),Wa(f,e[1],e[0]),Ct(r,r,f),Qa(n,t[0],t[1]),Qa(f,e[0],e[1]),Ct(n,n,f),Ct(i,t[3],e[3]),Ct(i,i,vX),Ct(s,t[2],e[2]),Qa(s,s,s),Wa(o,n,r),Wa(u,s,i),Qa(a,s,i),Qa(c,n,r),Ct(t[0],o,u),Ct(t[1],c,a),Ct(t[2],a,u),Ct(t[3],o,c)}function nR(t,e,r){for(let n=0;n<4;n++)sR(t[n],e[n],r)}function cI(t,e){let r=ve(),n=ve(),i=ve();uR(i,e[2]),Ct(r,e[0],i),Ct(n,e[1],i),vh(t,n),t[31]^=aR(r)<<7}function cR(t,e,r){Bo(t[0],oI),Bo(t[1],kc),Bo(t[2],kc),Bo(t[3],oI);for(let n=255;n>=0;--n){let i=r[n/8|0]>>(n&7)&1;nR(t,e,i),aI(e,t),aI(t,t),nR(t,e,i)}}function lI(t,e){let r=[ve(),ve(),ve(),ve()];Bo(r[0],eR),Bo(r[1],tR),Bo(r[2],kc),Ct(r[3],eR,tR),cR(t,r,e)}function lR(t){if(t.length!==Ge.SEED_LENGTH)throw new Error(`ed25519: seed must be ${Ge.SEED_LENGTH} bytes`);let e=(0,wh.hash)(t);e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(32),n=[ve(),ve(),ve(),ve()];lI(n,e),cI(r,n);let i=new Uint8Array(64);return i.set(t),i.set(r,32),{publicKey:r,secretKey:i}}Ge.generateKeyPairFromSeed=lR;function SX(t){let e=(0,mX.randomBytes)(32,t),r=lR(e);return(0,iR.wipe)(e),r}Ge.generateKeyPair=SX;function IX(t){if(t.length!==Ge.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${Ge.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(t.subarray(32))}Ge.extractPublicKeyFromSecretKey=IX;var sI=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function fR(t,e){let r,n,i,s;for(n=63;n>=32;--n){for(r=0,i=n-32,s=n-12;i>4)*sI[i],r=e[i]>>8,e[i]&=255;for(i=0;i<32;i++)e[i]-=r*sI[i];for(n=0;n<32;n++)e[n+1]+=e[n]>>8,t[n]=e[n]&255}function uI(t){let e=new Float64Array(64);for(let r=0;r<64;r++)e[r]=t[r];for(let r=0;r<64;r++)t[r]=0;fR(t,e)}function TX(t,e){let r=new Float64Array(64),n=[ve(),ve(),ve(),ve()],i=(0,wh.hash)(t.subarray(0,32));i[0]&=248,i[31]&=127,i[31]|=64;let s=new Uint8Array(64);s.set(i.subarray(32),32);let o=new wh.SHA512;o.update(s.subarray(32)),o.update(e);let u=o.digest();o.clean(),uI(u),lI(n,u),cI(s,n),o.reset(),o.update(s.subarray(0,32)),o.update(t.subarray(32)),o.update(e);let a=o.digest();uI(a);for(let c=0;c<32;c++)r[c]=u[c];for(let c=0;c<32;c++)for(let f=0;f<32;f++)r[c+f]+=a[c]*i[f];return fR(s.subarray(32),r),s}Ge.sign=TX;function hR(t,e){let r=ve(),n=ve(),i=ve(),s=ve(),o=ve(),u=ve(),a=ve();return Bo(t[2],kc),EX(t[1],e),Ka(i,t[1]),Ct(s,i,wX),Wa(i,i,t[2]),Qa(s,t[2],s),Ka(o,s),Ka(u,o),Ct(a,u,o),Ct(r,a,i),Ct(r,r,s),bX(r,r),Ct(r,r,i),Ct(r,r,s),Ct(r,r,s),Ct(t[0],r,s),Ka(n,t[0]),Ct(n,n,s),rR(n,i)&&Ct(t[0],t[0],AX),Ka(n,t[0]),Ct(n,n,s),rR(n,i)?-1:(aR(t[0])===e[31]>>7&&Wa(t[0],oI,t[0]),Ct(t[3],t[0],t[1]),0)}function _X(t,e,r){let n=new Uint8Array(32),i=[ve(),ve(),ve(),ve()],s=[ve(),ve(),ve(),ve()];if(r.length!==Ge.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${Ge.SIGNATURE_LENGTH} bytes`);if(hR(s,t))return!1;let o=new wh.SHA512;o.update(r.subarray(0,32)),o.update(t),o.update(e);let u=o.digest();return uI(u),cR(i,s,u),lI(s,r.subarray(32)),aI(i,s),cI(n,i),!oR(r,n)}Ge.verify=_X;function CX(t){let e=[ve(),ve(),ve(),ve()];if(hR(e,t))throw new Error("Ed25519: invalid public key");let r=ve(),n=ve(),i=e[1];Qa(r,kc,i),Wa(n,kc,i),uR(n,n),Ct(r,r,n);let s=new Uint8Array(32);return vh(s,r),s}Ge.convertPublicKeyToX25519=CX;function NX(t){let e=(0,wh.hash)(t.subarray(0,32));e[0]&=248,e[31]&=127,e[31]|=64;let r=new Uint8Array(e.subarray(0,32));return(0,iR.wipe)(e),r}Ge.convertSecretKeyToX25519=NX});var fm,hm,$a,Hc,dm,Ah,gm,pm,mm,Gc,ym,wm,gR,pR,vm=fe(()=>{h();fm="EdDSA",hm="JWT",$a=".",Hc="base64url",dm="utf8",Ah="utf8",gm=":",pm="did",mm="key",Gc="base58btc",ym="z",wm="K36",gR=32,pR=32});function Mo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}var Eh=fe(()=>{h()});function jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}var Am=fe(()=>{h();Eh()});function Em(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=jc(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Mo(r)}var fI=fe(()=>{h();Am();Eh()});function xX(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");B=H,V++}for(var v=Q-B;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(B+(U-q)),C=B;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var OX,DX,mR,yR=fe(()=>{h();OX=xX,DX=OX,mR=DX});var xEe,wR,Vs,vR,AR,Lo=fe(()=>{h();xEe=new Uint8Array(0),wR=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},vR=t=>new TextEncoder().encode(t),AR=t=>new TextDecoder().decode(t)});var hI,dI,gI,bR,pI,zc,Fo,PX,RX,jt,Ei=fe(()=>{h();yR();Lo();hI=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},dI=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bR(this,e)}},gI=class{constructor(e){this.decoders=e}or(e){return bR(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},bR=(t,e)=>new gI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),pI=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new hI(e,r,n),this.decoder=new dI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zc=({name:t,prefix:e,encode:r,decode:n})=>new pI(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=mR(r,e);return zc({prefix:t,name:e,encode:n,decode:s=>Vs(i(s))})},PX=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},RX=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<zc({prefix:e,name:t,encode(i){return RX(i,n,r)},decode(i){return PX(i,n,r,t)}})});var mI={};Bt(mI,{identity:()=>BX});var BX,SR=fe(()=>{h();Ei();Lo();BX=zc({prefix:"\0",name:"identity",encode:t=>AR(t),decode:t=>vR(t)})});var yI={};Bt(yI,{base2:()=>MX});var MX,IR=fe(()=>{h();Ei();MX=jt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var wI={};Bt(wI,{base8:()=>LX});var LX,TR=fe(()=>{h();Ei();LX=jt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var vI={};Bt(vI,{base10:()=>FX});var FX,_R=fe(()=>{h();Ei();FX=Fo({prefix:"9",name:"base10",alphabet:"0123456789"})});var AI={};Bt(AI,{base16:()=>UX,base16upper:()=>qX});var UX,qX,CR=fe(()=>{h();Ei();UX=jt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qX=jt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var EI={};Bt(EI,{base32:()=>Qc,base32hex:()=>GX,base32hexpad:()=>zX,base32hexpadupper:()=>QX,base32hexupper:()=>jX,base32pad:()=>kX,base32padupper:()=>HX,base32upper:()=>VX,base32z:()=>KX});var Qc,VX,kX,HX,GX,jX,zX,QX,KX,bI=fe(()=>{h();Ei();Qc=jt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),VX=jt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kX=jt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),HX=jt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),GX=jt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jX=jt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zX=jt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),QX=jt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),KX=jt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var SI={};Bt(SI,{base36:()=>WX,base36upper:()=>$X});var WX,$X,NR=fe(()=>{h();Ei();WX=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$X=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var II={};Bt(II,{base58btc:()=>rs,base58flickr:()=>YX});var rs,YX,TI=fe(()=>{h();Ei();rs=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YX=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var _I={};Bt(_I,{base64:()=>JX,base64pad:()=>XX,base64url:()=>ZX,base64urlpad:()=>eZ});var JX,XX,ZX,eZ,xR=fe(()=>{h();Ei();JX=jt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XX=jt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ZX=jt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eZ=jt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var CI={};Bt(CI,{base256emoji:()=>sZ});function nZ(t){return t.reduce((e,r)=>(e+=tZ[r],e),"")}function iZ(t){let e=[];for(let r of t){let n=rZ[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var OR,tZ,rZ,sZ,DR=fe(()=>{h();Ei();OR=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),tZ=OR.reduce((t,e,r)=>(t[r]=e,t),[]),rZ=OR.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);sZ=zc({prefix:"\u{1F680}",name:"base256emoji",encode:nZ,decode:iZ})});function BR(t,e,r){e=e||[],r=r||0;for(var n=r;t>=cZ;)e[r++]=t&255|PR,t/=128;for(;t&uZ;)e[r++]=t&255|PR,t>>>=7;return e[r]=t|0,BR.bytes=r-n+1,e}function NI(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw NI.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&RR)<=fZ);return NI.bytes=s-n,r}var oZ,PR,aZ,uZ,cZ,lZ,fZ,RR,hZ,dZ,gZ,pZ,mZ,yZ,wZ,vZ,AZ,EZ,bZ,SZ,bh,MR=fe(()=>{h();oZ=BR,PR=128,aZ=127,uZ=~aZ,cZ=Math.pow(2,31);lZ=NI,fZ=128,RR=127;hZ=Math.pow(2,7),dZ=Math.pow(2,14),gZ=Math.pow(2,21),pZ=Math.pow(2,28),mZ=Math.pow(2,35),yZ=Math.pow(2,42),wZ=Math.pow(2,49),vZ=Math.pow(2,56),AZ=Math.pow(2,63),EZ=function(t){return t{h();MR();Sh=(t,e=0)=>[bh.decode(t,e),bh.decode.bytes],Kc=(t,e,r=0)=>(bh.encode(t,e,r),e),Wc=t=>bh.encodingLength(t)});var Ya,LR,FR,$c,Th=fe(()=>{h();Lo();Sm();Ya=(t,e)=>{let r=e.byteLength,n=Wc(t),i=n+Wc(r),s=new Uint8Array(i+r);return Kc(t,s,0),Kc(r,s,n),s.set(e,i),new $c(t,r,e,s)},LR=t=>{let e=Vs(t),[r,n]=Sh(e),[i,s]=Sh(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $c(r,i,o,e)},FR=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&wR(t.bytes,e.bytes),$c=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}});var OI,xI,DI=fe(()=>{h();Th();OI=({name:t,code:e,encode:r})=>new xI(t,e,r),xI=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ya(this.code,r):r.then(n=>Ya(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var PI={};Bt(PI,{sha256:()=>IZ,sha512:()=>TZ});var qR,IZ,TZ,VR=fe(()=>{h();DI();qR=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),IZ=OI({name:"sha2-256",code:18,encode:qR("SHA-256")}),TZ=OI({name:"sha2-512",code:19,encode:qR("SHA-512")})});var RI={};Bt(RI,{identity:()=>NZ});var kR,_Z,HR,CZ,NZ,GR=fe(()=>{h();Lo();Th();kR=0,_Z="identity",HR=Vs,CZ=t=>Ya(kR,HR(t)),NZ={code:kR,name:_Z,encode:HR,digest:CZ}});var jR=fe(()=>{h();Lo()});var pbe,mbe,zR=fe(()=>{h();pbe=new TextEncoder,mbe=new TextDecoder});var _m,DZ,PZ,RZ,_h,BZ,QR,KR,Im,Tm,MZ,LZ,FZ,WR=fe(()=>{h();Sm();Th();TI();bI();Lo();_m=class t{constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Tm,byteLength:Tm,code:Im,version:Im,multihash:Im,bytes:Im,_baseCache:Tm,asCID:Tm})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:r}=this;if(e!==_h)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==BZ)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ya(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&FR(this.multihash,e.multihash)}toString(e){let{bytes:r,version:n,_baseCache:i}=this;switch(n){case 0:return PZ(r,i,e||rs.encoder);default:return RZ(r,i,e||Qc.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return LZ(/^0\.0/,FZ),!!(e&&(e[KR]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof t)return e;if(e!=null&&e.asCID===e){let{version:r,code:n,multihash:i,bytes:s}=e;return new t(r,n,i,s||QR(r,n,i.bytes))}else if(e!=null&&e[KR]===!0){let{version:r,multihash:n,code:i}=e,s=LR(n);return t.create(r,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(r!==_h)throw new Error(`Version 0 CID must use dag-pb (code: ${_h}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=QR(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,_h,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=Vs(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $c(r.multihashCode,r.digestSize,s,i);return[r.version===0?t.createV0(o):t.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,w]=Sh(e.subarray(r));return r+=w,d},i=n(),s=_h;if(i===18?(i=0,r=0):i===1&&(s=n()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,u=n(),a=n(),c=r+a,f=c-o;return{version:i,codec:s,multihashCode:u,digestSize:a,multihashSize:f,size:c}}static parse(e,r){let[n,i]=DZ(e,r),s=t.decode(i);return s._baseCache.set(n,e),s}},DZ=(t,e)=>{switch(t[0]){case"Q":{let r=e||rs;return[rs.prefix,r.decode(`${rs.prefix}${t}`)]}case rs.prefix:{let r=e||rs;return[rs.prefix,r.decode(t)]}case Qc.prefix:{let r=e||Qc;return[Qc.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},PZ=(t,e,r)=>{let{prefix:n}=r;if(n!==rs.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},RZ=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},_h=112,BZ=18,QR=(t,e,r)=>{let n=Wc(t),i=n+Wc(e),s=new Uint8Array(i+r.byteLength);return Kc(t,s,0),Kc(e,s,n),s.set(r,i),s},KR=Symbol.for("@ipld/js-cid/CID"),Im={writable:!1,configurable:!1,enumerable:!0},Tm={writable:!1,enumerable:!1,configurable:!1},MZ="0.0.0-dev",LZ=(t,e)=>{if(t.test(MZ))console.warn(e);else throw new Error(e)},FZ=`CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: if (CID.isCID(value)) { @@ -34,31 +34,31 @@ if (cid) { // Make sure to use cid instead of value doSomethingWithCID(cid) } -`});var YR=fe(()=>{h();$R();Tm();Lo();OI();Th()});var RI,abe,JR=fe(()=>{h();IR();TR();_R();CR();NR();EI();xR();II();OR();PR();kR();jR();zR();QR();YR();RI={...pI,...mI,...yI,...wI,...vI,...AI,...bI,...SI,...TI,..._I},abe={...DI,...PI}});function ZR(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var XR,BI,SZ,xm,MI=fe(()=>{h();JR();bm();XR=ZR("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),BI=ZR("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=jc(t.length);for(let r=0;r{h();MI()});function ns(t,e="utf8"){let r=xm[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var FI=fe(()=>{h();MI();Eh()});function Ch(t){return Ro(ks(ns(t,Hc),pm))}function Nh(t){return ks(ns(Ai(t),pm),Hc)}function UI(t){let e=ns(Am,Gc),r=vm+ks(Sm([e,t]),Gc);return[ym,wm,r].join(mm)}function qI(t){let[e,r,n]=t.split(mm);if(e!==ym||r!==wm)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==vm)throw new Error("Issuer must be a key in mulicodec format");let s=ns(n.slice(1),Gc);if(ks(s.slice(0,2),Gc)!==Am)throw new Error('Issuer must be a public key with type "Ed25519"');let u=s.slice(2);if(u.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return u}function eB(t){return ks(t,Hc)}function tB(t){return ns(t,Hc)}function VI(t){return ns([Nh(t.header),Nh(t.payload)].join(Ya),Ah)}function IZ(t){let e=ks(t,Ah).split(Ya),r=Ch(e[0]),n=Ch(e[1]);return{header:r,payload:n}}function kI(t){return[Nh(t.header),Nh(t.payload),eB(t.signature)].join(Ya)}function HI(t){let e=t.split(Ya),r=Ch(e[0]),n=Ch(e[1]),i=tB(e[2]),s=ns(e.slice(0,2).join(Ya),Ah);return{header:r,payload:n,signature:i,data:s}}var GI=fe(()=>{h();lI();LI();FI();xc();Em()});function TZ(t=(0,rB.randomBytes)(32)){return Yc.generateKeyPairFromSeed(t)}async function _Z(t,e,r,n,i=(0,nB.fromMiliseconds)(Date.now())){let s={alg:dm,typ:gm},o=UI(n.publicKey),u=i+r,a={iss:o,sub:t,aud:e,iat:i,exp:u},c=VI({header:s,payload:a}),f=Yc.sign(n.secretKey,c);return kI({header:s,payload:a,signature:f})}async function CZ(t){let{header:e,payload:r,data:n,signature:i}=HI(t);if(e.alg!==dm||e.typ!==gm)throw new Error("JWT must use EdDSA algorithm");let s=qI(r.iss);return Yc.verify(s,n,i)}var Yc,rB,nB,iB=fe(()=>{h();Yc=pe(gR()),rB=pe(yh()),nB=pe(Qa());Em();GI()});var sB=fe(()=>{h()});var oB={};Bt(oB,{DATA_ENCODING:()=>Ah,DID_DELIMITER:()=>mm,DID_METHOD:()=>wm,DID_PREFIX:()=>ym,JSON_ENCODING:()=>pm,JWT_DELIMITER:()=>Ya,JWT_ENCODING:()=>Hc,JWT_IRIDIUM_ALG:()=>dm,JWT_IRIDIUM_TYP:()=>gm,KEY_PAIR_SEED_LENGTH:()=>mR,MULTICODEC_ED25519_BASE:()=>vm,MULTICODEC_ED25519_ENCODING:()=>Gc,MULTICODEC_ED25519_HEADER:()=>Am,MULTICODEC_ED25519_LENGTH:()=>pR,decodeData:()=>IZ,decodeIss:()=>qI,decodeJSON:()=>Ch,decodeJWT:()=>HI,decodeSig:()=>tB,encodeData:()=>VI,encodeIss:()=>UI,encodeJSON:()=>Nh,encodeJWT:()=>kI,encodeSig:()=>eB,generateKeyPair:()=>TZ,signJWT:()=>_Z,verifyJWT:()=>CZ});var aB=fe(()=>{h();iB();Em();sB();GI()});var vB=B(qt=>{"use strict";h();var uB=qt&&qt.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new pB:typeof navigator<"u"?jI(navigator.userAgent):wB()}qt.detect=DZ;function mB(t){return t!==""&&OZ.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function PZ(t){var e=mB(t);return e?e[0]:null}qt.browserName=PZ;function jI(t){var e=mB(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new gB;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getLocalStorage=Ot.getLocalStorageOrThrow=Ot.getCrypto=Ot.getCryptoOrThrow=Ot.getLocation=Ot.getLocationOrThrow=Ot.getNavigator=Ot.getNavigatorOrThrow=Ot.getDocument=Ot.getDocumentOrThrow=Ot.getFromWindowOrThrow=Ot.getFromWindow=void 0;function Xa(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}Ot.getFromWindow=Xa;function Jc(t){let e=Xa(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}Ot.getFromWindowOrThrow=Jc;function BZ(){return Jc("document")}Ot.getDocumentOrThrow=BZ;function MZ(){return Xa("document")}Ot.getDocument=MZ;function LZ(){return Jc("navigator")}Ot.getNavigatorOrThrow=LZ;function FZ(){return Xa("navigator")}Ot.getNavigator=FZ;function UZ(){return Jc("location")}Ot.getLocationOrThrow=UZ;function qZ(){return Xa("location")}Ot.getLocation=qZ;function VZ(){return Jc("crypto")}Ot.getCryptoOrThrow=VZ;function kZ(){return Xa("crypto")}Ot.getCrypto=kZ;function HZ(){return Jc("localStorage")}Ot.getLocalStorageOrThrow=HZ;function GZ(){return Xa("localStorage")}Ot.getLocalStorage=GZ});var EB=B(Om=>{"use strict";h();Object.defineProperty(Om,"__esModule",{value:!0});Om.getWindowMetadata=void 0;var AB=zI();function jZ(){let t,e;try{t=AB.getDocumentOrThrow(),e=AB.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),w=[];for(let A=0;A-1){let R=T.getAttribute("href");if(R)if(R.toLowerCase().indexOf("https:")===-1&&R.toLowerCase().indexOf("http:")===-1&&R.indexOf("//")!==0){let V=e.protocol+"//"+e.host;if(R.indexOf("/")===0)V+=R;else{let U=e.pathname.split("/");U.pop();let Q=U.join("/");V+=Q+"/"+R}w.push(V)}else if(R.indexOf("//")===0){let V=e.protocol+R;w.push(V)}else w.push(R)}}return w}function n(...d){let w=t.getElementsByTagName("meta");for(let A=0;AT.getAttribute(R)).filter(R=>R?d.includes(R):!1);if(x.length&&x){let R=T.getAttribute("content");if(R)return R}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),u=s(),a=e.origin,c=r();return{description:u,url:a,icons:c,name:o}}Om.getWindowMetadata=jZ});var SB=B((jbe,bB)=>{"use strict";h();bB.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var NB=B((Qbe,CB)=>{"use strict";h();var _B="%[a-f0-9]{2}",IB=new RegExp("("+_B+")|([^%]+?)","gi"),TB=new RegExp("("+_B+")+","gi");function QI(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],QI(r),QI(n))}function zZ(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(IB)||[],r=1;r{"use strict";h();xB.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var PB=B((Ybe,DB)=>{"use strict";h();DB.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";h();var KZ=SB(),WZ=NB(),BB=OB(),$Z=PB(),YZ=t=>t==null,KI=Symbol("encodeFragmentIdentifier");function JZ(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[",i,"]"].join("")]:[...r,[Zt(e,t),"[",Zt(i,t),"]=",Zt(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[]"].join("")]:[...r,[Zt(e,t),"[]=",Zt(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),":list="].join("")]:[...r,[Zt(e,t),":list=",Zt(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[Zt(r,t),e,Zt(i,t)].join("")]:[[n,Zt(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,Zt(e,t)]:[...r,[Zt(e,t),"=",Zt(n,t)].join("")]}}function XZ(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&Hs(n,t).includes(t.arrayFormatSeparator);n=o?Hs(n,t):n;let u=s||o?n.split(t.arrayFormatSeparator).map(a=>Hs(a,t)):n===null?n:Hs(n,t);i[r]=u};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&Hs(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(u=>Hs(u,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function MB(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Zt(t,e){return e.encode?e.strict?KZ(t):encodeURIComponent(t):t}function Hs(t,e){return e.decode?WZ(t):t}function LB(t){return Array.isArray(t)?t.sort():typeof t=="object"?LB(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function FB(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function ZZ(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function UB(t){t=FB(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function RB(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function qB(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),MB(e.arrayFormatSeparator);let r=XZ(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=BB(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:Hs(o,e),r(Hs(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=RB(s[o],e);else n[i]=RB(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=LB(o):i[s]=o,i},Object.create(null))}nn.extract=UB;nn.parse=qB;nn.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),MB(e.arrayFormatSeparator);let r=o=>e.skipNull&&YZ(t[o])||e.skipEmptyString&&t[o]==="",n=JZ(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let u=t[o];return u===void 0?"":u===null?Zt(o,e):Array.isArray(u)?u.length===0&&e.arrayFormat==="bracket-separator"?Zt(o,e)+"[]":u.reduce(n(o),[]).join("&"):Zt(o,e)+"="+Zt(u,e)}).filter(o=>o.length>0).join("&")};nn.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=BB(t,"#");return Object.assign({url:r.split("?")[0]||"",query:qB(UB(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:Hs(n,e)}:{})};nn.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[KI]:!0},e);let r=FB(t.url).split("?")[0]||"",n=nn.extract(t.url),i=nn.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=nn.stringify(s,e);o&&(o=`?${o}`);let u=ZZ(t.url);return t.fragmentIdentifier&&(u=`#${e[KI]?Zt(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${u}`};nn.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[KI]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=nn.parseUrl(t,r);return nn.stringifyUrl({url:n,query:$Z(i,e),fragmentIdentifier:s},r)};nn.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return nn.pick(t,n,r)}});var HB=B(Dm=>{"use strict";h();Object.defineProperty(Dm,"__esModule",{value:!0});var Mr=Uc(),WI=Qn(),eee=20;function tee(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,u=r[3]<<24|r[2]<<16|r[1]<<8|r[0],a=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],w=r[23]<<24|r[22]<<16|r[21]<<8|r[20],A=r[27]<<24|r[26]<<16|r[25]<<8|r[24],T=r[31]<<24|r[30]<<16|r[29]<<8|r[28],x=e[3]<<24|e[2]<<16|e[1]<<8|e[0],R=e[7]<<24|e[6]<<16|e[5]<<8|e[4],V=e[11]<<24|e[10]<<16|e[9]<<8|e[8],U=e[15]<<24|e[14]<<16|e[13]<<8|e[12],Q=n,L=i,k=s,H=o,q=u,v=a,C=c,D=f,F=d,P=w,l=A,g=T,y=x,E=R,S=V,_=U,M=0;M>>16|y<<16,F=F+y|0,q^=F,q=q>>>20|q<<12,L=L+v|0,E^=L,E=E>>>16|E<<16,P=P+E|0,v^=P,v=v>>>20|v<<12,k=k+C|0,S^=k,S=S>>>16|S<<16,l=l+S|0,C^=l,C=C>>>20|C<<12,H=H+D|0,_^=H,_=_>>>16|_<<16,g=g+_|0,D^=g,D=D>>>20|D<<12,k=k+C|0,S^=k,S=S>>>24|S<<8,l=l+S|0,C^=l,C=C>>>25|C<<7,H=H+D|0,_^=H,_=_>>>24|_<<8,g=g+_|0,D^=g,D=D>>>25|D<<7,L=L+v|0,E^=L,E=E>>>24|E<<8,P=P+E|0,v^=P,v=v>>>25|v<<7,Q=Q+q|0,y^=Q,y=y>>>24|y<<8,F=F+y|0,q^=F,q=q>>>25|q<<7,Q=Q+v|0,_^=Q,_=_>>>16|_<<16,l=l+_|0,v^=l,v=v>>>20|v<<12,L=L+C|0,y^=L,y=y>>>16|y<<16,g=g+y|0,C^=g,C=C>>>20|C<<12,k=k+D|0,E^=k,E=E>>>16|E<<16,F=F+E|0,D^=F,D=D>>>20|D<<12,H=H+q|0,S^=H,S=S>>>16|S<<16,P=P+S|0,q^=P,q=q>>>20|q<<12,k=k+D|0,E^=k,E=E>>>24|E<<8,F=F+E|0,D^=F,D=D>>>25|D<<7,H=H+q|0,S^=H,S=S>>>24|S<<8,P=P+S|0,q^=P,q=q>>>25|q<<7,L=L+C|0,y^=L,y=y>>>24|y<<8,g=g+y|0,C^=g,C=C>>>25|C<<7,Q=Q+v|0,_^=Q,_=_>>>24|_<<8,l=l+_|0,v^=l,v=v>>>25|v<<7;Mr.writeUint32LE(Q+n|0,t,0),Mr.writeUint32LE(L+i|0,t,4),Mr.writeUint32LE(k+s|0,t,8),Mr.writeUint32LE(H+o|0,t,12),Mr.writeUint32LE(q+u|0,t,16),Mr.writeUint32LE(v+a|0,t,20),Mr.writeUint32LE(C+c|0,t,24),Mr.writeUint32LE(D+f|0,t,28),Mr.writeUint32LE(F+d|0,t,32),Mr.writeUint32LE(P+w|0,t,36),Mr.writeUint32LE(l+A|0,t,40),Mr.writeUint32LE(g+T|0,t,44),Mr.writeUint32LE(y+x|0,t,48),Mr.writeUint32LE(E+R|0,t,52),Mr.writeUint32LE(S+V|0,t,56),Mr.writeUint32LE(_+U|0,t,60)}function kB(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Pm=B(Xc=>{"use strict";h();Object.defineProperty(Xc,"__esModule",{value:!0});function iee(t,e,r){return~(t-1)&e|t-1&r}Xc.select=iee;function see(t,e){return(t|0)-(e|0)-1>>>31&1}Xc.lessOrEqual=see;function GB(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xc.compare=GB;function oee(t,e){return t.length===0||e.length===0?!1:GB(t,e)!==0}Xc.equal=oee});var zB=B(Gs=>{"use strict";h();Object.defineProperty(Gs,"__esModule",{value:!0});var aee=Pm(),Rm=Qn();Gs.DIGEST_LENGTH=16;var jB=function(){function t(e){this.digestLength=Gs.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var u=e[10]|e[11]<<8;this._r[6]=(o>>>14|u<<2)&8191;var a=e[12]|e[13]<<8;this._r[7]=(u>>>11|a<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(a>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],u=this._h[2],a=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],w=this._h[7],A=this._h[8],T=this._h[9],x=this._r[0],R=this._r[1],V=this._r[2],U=this._r[3],Q=this._r[4],L=this._r[5],k=this._r[6],H=this._r[7],q=this._r[8],v=this._r[9];n>=16;){var C=e[r+0]|e[r+1]<<8;s+=C&8191;var D=e[r+2]|e[r+3]<<8;o+=(C>>>13|D<<3)&8191;var F=e[r+4]|e[r+5]<<8;u+=(D>>>10|F<<6)&8191;var P=e[r+6]|e[r+7]<<8;a+=(F>>>7|P<<9)&8191;var l=e[r+8]|e[r+9]<<8;c+=(P>>>4|l<<12)&8191,f+=l>>>1&8191;var g=e[r+10]|e[r+11]<<8;d+=(l>>>14|g<<2)&8191;var y=e[r+12]|e[r+13]<<8;w+=(g>>>11|y<<5)&8191;var E=e[r+14]|e[r+15]<<8;A+=(y>>>8|E<<8)&8191,T+=E>>>5|i;var S=0,_=S;_+=s*x,_+=o*(5*v),_+=u*(5*q),_+=a*(5*H),_+=c*(5*k),S=_>>>13,_&=8191,_+=f*(5*L),_+=d*(5*Q),_+=w*(5*U),_+=A*(5*V),_+=T*(5*R),S+=_>>>13,_&=8191;var M=S;M+=s*R,M+=o*x,M+=u*(5*v),M+=a*(5*q),M+=c*(5*H),S=M>>>13,M&=8191,M+=f*(5*k),M+=d*(5*L),M+=w*(5*Q),M+=A*(5*U),M+=T*(5*V),S+=M>>>13,M&=8191;var N=S;N+=s*V,N+=o*R,N+=u*x,N+=a*(5*v),N+=c*(5*q),S=N>>>13,N&=8191,N+=f*(5*H),N+=d*(5*k),N+=w*(5*L),N+=A*(5*Q),N+=T*(5*U),S+=N>>>13,N&=8191;var m=S;m+=s*U,m+=o*V,m+=u*R,m+=a*x,m+=c*(5*v),S=m>>>13,m&=8191,m+=f*(5*q),m+=d*(5*H),m+=w*(5*k),m+=A*(5*L),m+=T*(5*Q),S+=m>>>13,m&=8191;var O=S;O+=s*Q,O+=o*U,O+=u*V,O+=a*R,O+=c*x,S=O>>>13,O&=8191,O+=f*(5*v),O+=d*(5*q),O+=w*(5*H),O+=A*(5*k),O+=T*(5*L),S+=O>>>13,O&=8191;var Y=S;Y+=s*L,Y+=o*Q,Y+=u*U,Y+=a*V,Y+=c*R,S=Y>>>13,Y&=8191,Y+=f*x,Y+=d*(5*v),Y+=w*(5*q),Y+=A*(5*H),Y+=T*(5*k),S+=Y>>>13,Y&=8191;var $=S;$+=s*k,$+=o*L,$+=u*Q,$+=a*U,$+=c*V,S=$>>>13,$&=8191,$+=f*R,$+=d*x,$+=w*(5*v),$+=A*(5*q),$+=T*(5*H),S+=$>>>13,$&=8191;var b=S;b+=s*H,b+=o*k,b+=u*L,b+=a*Q,b+=c*U,S=b>>>13,b&=8191,b+=f*V,b+=d*R,b+=w*x,b+=A*(5*v),b+=T*(5*q),S+=b>>>13,b&=8191;var j=S;j+=s*q,j+=o*H,j+=u*k,j+=a*L,j+=c*Q,S=j>>>13,j&=8191,j+=f*U,j+=d*V,j+=w*R,j+=A*x,j+=T*(5*v),S+=j>>>13,j&=8191;var z=S;z+=s*v,z+=o*q,z+=u*H,z+=a*k,z+=c*L,S=z>>>13,z&=8191,z+=f*Q,z+=d*U,z+=w*V,z+=A*R,z+=T*x,S+=z>>>13,z&=8191,S=(S<<2)+S|0,S=S+_|0,_=S&8191,S=S>>>13,M+=S,s=_,o=M,u=N,a=m,c=O,f=Y,d=$,w=b,A=j,T=z,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=u,this._h[3]=a,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=w,this._h[8]=A,this._h[9]=T},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,u;if(this._leftover){for(u=this._leftover,this._buffer[u++]=1;u<16;u++)this._buffer[u]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,u=2;u<10;u++)this._h[u]+=i,i=this._h[u]>>>13,this._h[u]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,u=1;u<10;u++)n[u]=this._h[u]+i,i=n[u]>>>13,n[u]&=8191;for(n[9]-=8192,s=(i^1)-1,u=0;u<10;u++)n[u]&=s;for(s=~s,u=0;u<10;u++)this._h[u]=this._h[u]&s|n[u];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,u=1;u<8;u++)o=(this._h[u]+this._pad[u]|0)+(o>>>16)|0,this._h[u]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";h();Object.defineProperty(js,"__esModule",{value:!0});var Bm=HB(),lee=zB(),xh=Qn(),QB=Uc(),fee=Pm();js.KEY_LENGTH=32;js.NONCE_LENGTH=12;js.TAG_LENGTH=16;var KB=new Uint8Array(16),hee=function(){function t(e){if(this.nonceLength=js.NONCE_LENGTH,this.tagLength=js.TAG_LENGTH,e.length!==js.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Bm.stream(this._key,s,o,4);var u=r.length+this.tagLength,a;if(i){if(i.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");a=i}else a=new Uint8Array(u);return Bm.streamXOR(this._key,s,r,a,4),this._authenticate(a.subarray(a.length-this.tagLength,a.length),o,a.subarray(0,a.length-this.tagLength),n),xh.wipe(s),a},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(KB.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(KB.subarray(n.length%16));var o=new Uint8Array(8);i&&QB.writeUint64LE(i.length,o),s.update(o),QB.writeUint64LE(n.length,o),s.update(o);for(var u=s.digest(),a=0;a{"use strict";h();Object.defineProperty($I,"__esModule",{value:!0});function dee(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}$I.isSerializableHash=dee});var JB=B(Oh=>{"use strict";h();Object.defineProperty(Oh,"__esModule",{value:!0});var is=$B(),gee=Pm(),pee=Qn(),YB=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";h();Object.defineProperty(YI,"__esModule",{value:!0});var XB=JB(),ZB=Qn(),yee=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=XB.hmac(this._hash,n,r);this._hmac=new XB.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";h();Object.defineProperty(Uo,"__esModule",{value:!0});var Lm=Uc(),Mm=Qn();Uo.DIGEST_LENGTH=32;Uo.BLOCK_SIZE=64;var tM=function(){function t(){this.digestLength=Uo.DIGEST_LENGTH,this.blockSize=Uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Mm.wipe(this._buffer),Mm.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(JI(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=JI(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Mm.wipe(e.state),e.buffer&&Mm.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Uo.SHA256=tM;var wee=new Int32Array([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]);function JI(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],u=e[2],a=e[3],c=e[4],f=e[5],d=e[6],w=e[7],A=0;A<16;A++){var T=n+A*4;t[A]=Lm.readUint32BE(r,T)}for(var A=16;A<64;A++){var x=t[A-2],R=(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10;x=t[A-15];var V=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3;t[A]=(R+t[A-7]|0)+(V+t[A-16]|0)}for(var A=0;A<64;A++){var R=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(w+(wee[A]+t[A]|0)|0)|0,V=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&u^o&u)|0;w=d,d=f,f=c,c=a+R|0,a=u,u=o,o=s,s=R+V|0}e[0]+=s,e[1]+=o,e[2]+=u,e[3]+=a,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=w,n+=64,i-=64}return n}function vee(t){var e=new tM;e.update(t);var r=e.digest();return e.clean(),r}Uo.hash=vee});var oM=B(zt=>{"use strict";h();Object.defineProperty(zt,"__esModule",{value:!0});zt.sharedKey=zt.generateKeyPair=zt.generateKeyPairFromSeed=zt.scalarMultBase=zt.scalarMult=zt.SHARED_KEY_LENGTH=zt.SECRET_KEY_LENGTH=zt.PUBLIC_KEY_LENGTH=void 0;var Aee=yh(),Eee=Qn();zt.PUBLIC_KEY_LENGTH=32;zt.SECRET_KEY_LENGTH=32;zt.SHARED_KEY_LENGTH=32;function ss(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Dh(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function Iee(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Fm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Um(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function zs(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,R=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,D=0,F=0,P=0,l=0,g=0,y=0,E=0,S=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,R+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,R+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,R+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,R+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,R+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,R+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,R+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,D+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,R+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,D+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,R+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,D+=n*oe,F+=n*J,P+=n*ue,n=e[9],T+=n*N,x+=n*m,R+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,D+=n*se,F+=n*oe,P+=n*J,l+=n*ue,n=e[10],x+=n*N,R+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,D+=n*ee,F+=n*se,P+=n*oe,l+=n*J,g+=n*ue,n=e[11],R+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,D+=n*te,F+=n*ee,P+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,D+=n*ie,F+=n*te,P+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,D+=n*W,F+=n*ie,P+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,S+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,D+=n*z,F+=n*W,P+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,S+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,D+=n*j,F+=n*z,P+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,S+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*D,d+=38*F,w+=38*P,A+=38*l,T+=38*g,x+=38*y,R+=38*E,V+=38*S,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=R+i+65535,i=Math.floor(n/65536),R=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=R,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ph(t,e){zs(t,e,e)}function Tee(t,e){let r=ss();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)Ph(r,r),n!==2&&n!==4&&zs(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function ZI(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=ss(),s=ss(),o=ss(),u=ss(),a=ss(),c=ss();for(let A=0;A<31;A++)r[A]=t[A];r[31]=t[31]&127|64,r[0]&=248,Iee(n,e);for(let A=0;A<16;A++)s[A]=n[A];i[0]=u[0]=1;for(let A=254;A>=0;--A){let T=r[A>>>3]>>>(A&7)&1;Dh(i,s,T),Dh(o,u,T),Fm(a,i,o),Um(i,i,o),Fm(o,s,u),Um(s,s,u),Ph(u,a),Ph(c,i),zs(i,o,i),zs(o,s,a),Fm(a,i,o),Um(i,i,o),Ph(s,i),Um(o,u,c),zs(i,o,bee),Fm(i,i,u),zs(o,o,i),zs(i,u,c),zs(u,s,n),Ph(s,a),Dh(i,s,T),Dh(o,u,T)}for(let A=0;A<16;A++)n[A+16]=i[A],n[A+32]=o[A],n[A+48]=s[A],n[A+64]=u[A];let f=n.subarray(32),d=n.subarray(16);Tee(f,f),zs(d,d,f);let w=new Uint8Array(32);return See(w,d),w}zt.scalarMult=ZI;function iM(t){return ZI(t,nM)}zt.scalarMultBase=iM;function sM(t){if(t.length!==zt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${zt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:iM(e),secretKey:e}}zt.generateKeyPairFromSeed=sM;function _ee(t){let e=(0,Aee.randomBytes)(32,t),r=sM(e);return(0,Eee.wipe)(e),r}zt.generateKeyPair=_ee;function Cee(t,e,r=!1){if(t.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=ZI(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{h()});function cM(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{h()});function fM(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=jc(t.length);for(let n=0;n{h();bm();Eh()});var eT={};Bt(eT,{compare:()=>aM,concat:()=>Sm,equals:()=>cM,fromString:()=>ns,toString:()=>ks,xor:()=>fM});var tT=fe(()=>{h();uM();lI();lM();FI();LI();hM()});var dM={};Bt(dM,{RELAY_JSONRPC:()=>qee,isPublishMethod:()=>iT,isPublishParams:()=>sT,isPublishRequest:()=>Pee,isSubscribeMethod:()=>rT,isSubscribeParams:()=>nT,isSubscribeRequest:()=>Dee,isSubscriptionMethod:()=>uT,isSubscriptionParams:()=>cT,isSubscriptionRequest:()=>Bee,isUnsubscribeMethod:()=>oT,isUnsubscribeParams:()=>aT,isUnsubscribeRequest:()=>Ree,parsePublishRequest:()=>Lee,parseSubscribeRequest:()=>Mee,parseSubscriptionRequest:()=>Uee,parseUnsubscribeRequest:()=>Fee});function Za(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function Nee(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function xee(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function Oee(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function qm(t,e,r){return(r.length?Oee(t,e.length):xee(t,e.length))?Nee(t,e):!1}function Vm(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}function Dee(t){return rT(t.method)&&nT(t.params)}function rT(t){return Vm(t,"subscribe")}function nT(t){return qm(t,["topic"],[])}function Pee(t){return iT(t.method)&&sT(t.params)}function iT(t){return Vm(t,"publish")}function sT(t){return qm(t,["message","topic","ttl"],["prompt","tag"])}function Ree(t){return oT(t.method)&&aT(t.params)}function oT(t){return Vm(t,"unsubscribe")}function aT(t){return qm(t,["id","topic"],[])}function Bee(t){return uT(t.method)&&cT(t.params)}function uT(t){return Vm(t,"subscription")}function cT(t){return qm(t,["id","data"],[])}function Mee(t){if(!rT(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!nT(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Za(e,"topic"),e}function Lee(t){if(!iT(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!sT(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Za(e,"topic"),Za(e,"message"),Za(e,"ttl","number"),e}function Fee(t){if(!oT(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!aT(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Za(e,"id"),e}function Uee(t){if(!uT(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!cT(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Za(e,"id"),Za(e,"data"),e}var qee,gM=fe(()=>{h();qee={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var Qh=B(K=>{"use strict";h();Object.defineProperty(K,"__esModule",{value:!0});var Vee=vB(),el=Qa(),il=zI(),kee=EB(),Hee=VB(),WM=WB(),Gee=eM(),$M=yh(),LT=rM(),jee=oM(),Vt=(tT(),_e(eT)),zee=(gM(),_e(dM));function YM(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var $m=YM(Hee),JM=YM(jee),ny=":";function XM(t){let[e,r]=t.split(ny);return{namespace:e,reference:r}}function ZM(t){let{namespace:e,reference:r}=t;return[e,r].join(ny)}function FT(t){let[e,r,n]=t.split(ny);return{namespace:e,reference:r,address:n}}function e4(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(ny)}function UT(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function t4(t){let{address:e}=FT(t);return e}function r4(t){let{namespace:e,reference:r}=FT(t);return ZM({namespace:e,reference:r})}function Qee(t,e){let{namespace:r,reference:n}=XM(e);return e4({namespace:r,reference:n,address:t})}function Kee(t){return UT(t,t4)}function n4(t){return UT(t,r4)}function Wee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function $ee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...n4(i.accounts))}),r}function Yee(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...iy(n,i))}),r}function iy(t,e){return t.includes(":")?[t]:e.chains||[]}var Jee=Object.defineProperty,pM=Object.getOwnPropertySymbols,Xee=Object.prototype.hasOwnProperty,Zee=Object.prototype.propertyIsEnumerable,mM=(t,e,r)=>e in t?Jee(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yM=(t,e)=>{for(var r in e||(e={}))Xee.call(e,r)&&mM(t,r,e[r]);if(pM)for(var r of pM(e))Zee.call(e,r)&&mM(t,r,e[r]);return t},i4="ReactNative",Gr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Ym=" ",ete=":",s4="/",qT=2,tte=1e3,o4="js";function VT(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}function al(){return!il.getDocument()&&!!il.getNavigator()&&navigator.product===i4}function Hh(){return!VT()&&!!il.getNavigator()&&!!il.getDocument()}function ru(){return al()?Gr.reactNative:VT()?Gr.node:Hh()?Gr.browser:Gr.unknown}function rte(){var t;try{return al()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function a4(t,e){let r=$m.parse(t);return r=yM(yM({},r),e),t=$m.stringify(r),t}function nte(){return kee.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function ite(t,e){var r;let n=ru(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=il.getLocation())==null?void 0:r.host)||"unknown"),i}function u4(){if(ru()===Gr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=Vee.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function c4(){var t;let e=ru();return e===Gr.browser?[e,((t=il.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function l4(t,e,r){let n=u4(),i=c4();return[[t,e].join("-"),[o4,r].join("-"),n,i].join("/")}function ste({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:u}){let a=r.split("?"),c=l4(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:u||void 0},d=a4(a[1]||"",f);return a[0]+"?"+d}function ote(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function ate(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function f4(t,e=qT){return h4(t.split(s4),e)}function ute(t){return f4(t).join(Ym)}function Ho(t,e){return t.filter(r=>e.includes(r)).length===t.length}function h4(t,e=qT){return t.slice(Math.max(t.length-e,0))}function cte(t){return Object.fromEntries(t.entries())}function lte(t){return new Map(Object.entries(t))}function fte(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var hte=t=>t;function d4(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function dte(t){return t.split(Ym).map(e=>d4(e)).join(Ym)}function gte(t=el.FIVE_MINUTES,e){let r=el.toMiliseconds(t||el.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,u)=>{s=setTimeout(()=>{u(new Error(e))},r),n=o,i=u})}}function pte(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function kT(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function mte(t){return kT("topic",t)}function yte(t){return kT("id",t)}function wte(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function vte(t,e){return el.fromMiliseconds((e||Date.now())+el.toMiliseconds(t))}function Ate(t){return Date.now()>=el.toMiliseconds(t)}function Ete(t,e){return`${t}${e?`:${e}`:""}`}function Js(t=[],e=[]){return[...new Set([...t,...e])]}async function bte({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=ru();o===Gr.browser?s.startsWith("https://")||s.startsWith("http://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===Gr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function Ste(t,e){try{return await t.getItem(e)||(Hh()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}function TT(t,e){return t.filter(r=>e.includes(r))}var g4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ite(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var p4={exports:{}};(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!i.JS_SHA3_NO_NODE_JS&&typeof I.default=="object"&&I.default.versions&&I.default.versions.node;o?i=g4:s&&(i=self);var u=!i.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),f=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],w=[1,256,65536,16777216],A=[6,1536,393216,100663296],T=[0,8,16,24],x=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],R=[224,256,384,512],V=[128,256],U=["hex","buffer","arrayBuffer","array","digest"],Q={128:168,256:136};(i.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(b){return Object.prototype.toString.call(b)==="[object Array]"}),a&&(i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(b){return typeof b=="object"&&b.buffer&&b.buffer.constructor===ArrayBuffer});for(var L=function(b,j,z){return function(W){return new O(b,j,b).update(W)[z]()}},k=function(b,j,z){return function(W,ie){return new O(b,j,ie).update(W)[z]()}},H=function(b,j,z){return function(W,ie,te,ee){return g["cshake"+b].update(W,ie,te,ee)[z]()}},q=function(b,j,z){return function(W,ie,te,ee){return g["kmac"+b].update(W,ie,te,ee)[z]()}},v=function(b,j,z,W){for(var ie=0;ie>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var W=0;W<50;++W)this.s[W]=0}O.prototype.update=function(b){if(this.finalized)throw new Error(r);var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}for(var W=this.blocks,ie=this.byteCount,te=b.length,ee=this.blockCount,se=0,oe=this.s,J,ue;se>2]|=b[se]<>2]|=ue<>2]|=(192|ue>>6)<>2]|=(128|ue&63)<=57344?(W[J>>2]|=(224|ue>>12)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<>2]|=(240|ue>>18)<>2]|=(128|ue>>12&63)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<=ie){for(this.start=J-ie,this.block=W[ee],J=0;J>8,z=b&255;z>0;)ie.unshift(z),b=b>>8,z=b&255,++W;return j?ie.push(W):ie.unshift(W),this.update(ie),ie.length},O.prototype.encodeString=function(b){var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}var W=0,ie=b.length;if(j)W=ie;else for(var te=0;te=57344?W+=3:(ee=65536+((ee&1023)<<10|b.charCodeAt(++te)&1023),W+=4)}return W+=this.encode(W*8),this.update(b),W},O.prototype.bytepad=function(b,j){for(var z=this.encode(j),W=0;W>2]|=this.padding[j&3],this.lastByteIndex===this.byteCount)for(b[0]=b[z],j=1;j>4&15]+c[se&15]+c[se>>12&15]+c[se>>8&15]+c[se>>20&15]+c[se>>16&15]+c[se>>28&15]+c[se>>24&15];te%b===0&&($(j),ie=0)}return W&&(se=j[ie],ee+=c[se>>4&15]+c[se&15],W>1&&(ee+=c[se>>12&15]+c[se>>8&15]),W>2&&(ee+=c[se>>20&15]+c[se>>16&15])),ee},O.prototype.arrayBuffer=function(){this.finalize();var b=this.blockCount,j=this.s,z=this.outputBlocks,W=this.extraBytes,ie=0,te=0,ee=this.outputBits>>3,se;W?se=new ArrayBuffer(z+1<<2):se=new ArrayBuffer(ee);for(var oe=new Uint32Array(se);te>8&255,ee[se+2]=oe>>16&255,ee[se+3]=oe>>24&255;te%b===0&&$(j)}return W&&(se=te<<2,oe=j[ie],ee[se]=oe&255,W>1&&(ee[se+1]=oe>>8&255),W>2&&(ee[se+2]=oe>>16&255)),ee};function Y(b,j,z){O.call(this,b,j,z)}Y.prototype=new O,Y.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var $=function(b){var j,z,W,ie,te,ee,se,oe,J,ue,wt,vt,Ni,At,Et,xi,bt,St,Oi,It,Tt,Di,Qe,Ke,ri,We,$e,ni,Ye,Je,ii,Xe,Ze,si,et,tt,oi,rt,nt,ai,it,st,ui,ot,at,ci,ut,ct,li,lt,ft,fi,ht,dt,hi,gt,pt,vn,An,En,bn,Sn,In;for(W=0;W<48;W+=2)ie=b[0]^b[10]^b[20]^b[30]^b[40],te=b[1]^b[11]^b[21]^b[31]^b[41],ee=b[2]^b[12]^b[22]^b[32]^b[42],se=b[3]^b[13]^b[23]^b[33]^b[43],oe=b[4]^b[14]^b[24]^b[34]^b[44],J=b[5]^b[15]^b[25]^b[35]^b[45],ue=b[6]^b[16]^b[26]^b[36]^b[46],wt=b[7]^b[17]^b[27]^b[37]^b[47],vt=b[8]^b[18]^b[28]^b[38]^b[48],Ni=b[9]^b[19]^b[29]^b[39]^b[49],j=vt^(ee<<1|se>>>31),z=Ni^(se<<1|ee>>>31),b[0]^=j,b[1]^=z,b[10]^=j,b[11]^=z,b[20]^=j,b[21]^=z,b[30]^=j,b[31]^=z,b[40]^=j,b[41]^=z,j=ie^(oe<<1|J>>>31),z=te^(J<<1|oe>>>31),b[2]^=j,b[3]^=z,b[12]^=j,b[13]^=z,b[22]^=j,b[23]^=z,b[32]^=j,b[33]^=z,b[42]^=j,b[43]^=z,j=ee^(ue<<1|wt>>>31),z=se^(wt<<1|ue>>>31),b[4]^=j,b[5]^=z,b[14]^=j,b[15]^=z,b[24]^=j,b[25]^=z,b[34]^=j,b[35]^=z,b[44]^=j,b[45]^=z,j=oe^(vt<<1|Ni>>>31),z=J^(Ni<<1|vt>>>31),b[6]^=j,b[7]^=z,b[16]^=j,b[17]^=z,b[26]^=j,b[27]^=z,b[36]^=j,b[37]^=z,b[46]^=j,b[47]^=z,j=ue^(ie<<1|te>>>31),z=wt^(te<<1|ie>>>31),b[8]^=j,b[9]^=z,b[18]^=j,b[19]^=z,b[28]^=j,b[29]^=z,b[38]^=j,b[39]^=z,b[48]^=j,b[49]^=z,At=b[0],Et=b[1],ci=b[11]<<4|b[10]>>>28,ut=b[10]<<4|b[11]>>>28,ni=b[20]<<3|b[21]>>>29,Ye=b[21]<<3|b[20]>>>29,En=b[31]<<9|b[30]>>>23,bn=b[30]<<9|b[31]>>>23,st=b[40]<<18|b[41]>>>14,ui=b[41]<<18|b[40]>>>14,si=b[2]<<1|b[3]>>>31,et=b[3]<<1|b[2]>>>31,xi=b[13]<<12|b[12]>>>20,bt=b[12]<<12|b[13]>>>20,ct=b[22]<<10|b[23]>>>22,li=b[23]<<10|b[22]>>>22,Je=b[33]<<13|b[32]>>>19,ii=b[32]<<13|b[33]>>>19,Sn=b[42]<<2|b[43]>>>30,In=b[43]<<2|b[42]>>>30,dt=b[5]<<30|b[4]>>>2,hi=b[4]<<30|b[5]>>>2,tt=b[14]<<6|b[15]>>>26,oi=b[15]<<6|b[14]>>>26,St=b[25]<<11|b[24]>>>21,Oi=b[24]<<11|b[25]>>>21,lt=b[34]<<15|b[35]>>>17,ft=b[35]<<15|b[34]>>>17,Xe=b[45]<<29|b[44]>>>3,Ze=b[44]<<29|b[45]>>>3,Ke=b[6]<<28|b[7]>>>4,ri=b[7]<<28|b[6]>>>4,gt=b[17]<<23|b[16]>>>9,pt=b[16]<<23|b[17]>>>9,rt=b[26]<<25|b[27]>>>7,nt=b[27]<<25|b[26]>>>7,It=b[36]<<21|b[37]>>>11,Tt=b[37]<<21|b[36]>>>11,fi=b[47]<<24|b[46]>>>8,ht=b[46]<<24|b[47]>>>8,ot=b[8]<<27|b[9]>>>5,at=b[9]<<27|b[8]>>>5,We=b[18]<<20|b[19]>>>12,$e=b[19]<<20|b[18]>>>12,vn=b[29]<<7|b[28]>>>25,An=b[28]<<7|b[29]>>>25,ai=b[38]<<8|b[39]>>>24,it=b[39]<<8|b[38]>>>24,Di=b[48]<<14|b[49]>>>18,Qe=b[49]<<14|b[48]>>>18,b[0]=At^~xi&St,b[1]=Et^~bt&Oi,b[10]=Ke^~We&ni,b[11]=ri^~$e&Ye,b[20]=si^~tt&rt,b[21]=et^~oi&nt,b[30]=ot^~ci&ct,b[31]=at^~ut&li,b[40]=dt^~gt&vn,b[41]=hi^~pt&An,b[2]=xi^~St&It,b[3]=bt^~Oi&Tt,b[12]=We^~ni&Je,b[13]=$e^~Ye&ii,b[22]=tt^~rt&ai,b[23]=oi^~nt&it,b[32]=ci^~ct<,b[33]=ut^~li&ft,b[42]=gt^~vn&En,b[43]=pt^~An&bn,b[4]=St^~It&Di,b[5]=Oi^~Tt&Qe,b[14]=ni^~Je&Xe,b[15]=Ye^~ii&Ze,b[24]=rt^~ai&st,b[25]=nt^~it&ui,b[34]=ct^~lt&fi,b[35]=li^~ft&ht,b[44]=vn^~En&Sn,b[45]=An^~bn&In,b[6]=It^~Di&At,b[7]=Tt^~Qe&Et,b[16]=Je^~Xe&Ke,b[17]=ii^~Ze&ri,b[26]=ai^~st&si,b[27]=it^~ui&et,b[36]=lt^~fi&ot,b[37]=ft^~ht&at,b[46]=En^~Sn&dt,b[47]=bn^~In&hi,b[8]=Di^~At&xi,b[9]=Qe^~Et&bt,b[18]=Xe^~Ke&We,b[19]=Ze^~ri&$e,b[28]=st^~si&tt,b[29]=ui^~et&oi,b[38]=fi^~ot&ci,b[39]=ht^~at&ut,b[48]=Sn^~dt>,b[49]=In^~hi&pt,b[0]^=x[W],b[1]^=x[W+1]};if(u)t.exports=g;else for(E=0;E{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken implementation")}catch(t){return t.message}return null}var EM=Cte(),_T;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(_T||(_T={}));var Si;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Si||(Si={}));var bM="0123456789abcdef",kt=class t{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){let n=e.toLowerCase();Qm[n]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(AM>Qm[n])&&console.log.apply(console,r)}debug(...e){this._log(t.levels.DEBUG,e)}info(...e){this._log(t.levels.INFO,e)}warn(...e){this._log(t.levels.WARNING,e)}makeError(e,r,n){if(vM)return this.makeError("censored error",r,{});r||(r=t.errors.UNKNOWN_ERROR),n||(n={});let i=[];Object.keys(n).forEach(a=>{let c=n[a];try{if(c instanceof Uint8Array){let f="";for(let d=0;d>4],f+=bM[c[d]&15];i.push(a+"=Uint8Array(0x"+f+")")}else i.push(a+"="+JSON.stringify(c))}catch{i.push(a+"="+JSON.stringify(n[a].toString()))}}),i.push(`code=${r}`),i.push(`version=${this.version}`);let s=e,o="";switch(r){case Si.NUMERIC_FAULT:{o="NUMERIC_FAULT";let a=e;switch(a){case"overflow":case"underflow":case"division-by-zero":o+="-"+a;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Si.CALL_EXCEPTION:case Si.INSUFFICIENT_FUNDS:case Si.MISSING_NEW:case Si.NONCE_EXPIRED:case Si.REPLACEMENT_UNDERPRICED:case Si.TRANSACTION_REPLACED:case Si.UNPREDICTABLE_GAS_LIMIT:o=r;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),i.length&&(e+=" ("+i.join(", ")+")");let u=new Error(e);return u.reason=s,u.code=r,Object.keys(n).forEach(function(a){u[a]=n[a]}),u}throwError(e,r,n){throw this.makeError(e,r,n)}throwArgumentError(e,r,n){return this.throwError(e,t.errors.INVALID_ARGUMENT,{argument:r,value:n})}assert(e,r,n,i){e||this.throwError(r,n,i)}assertArgument(e,r,n,i){e||this.throwArgumentError(r,n,i)}checkNormalize(e){EM&&this.throwError("platform missing String.prototype.normalize",t.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:EM})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,n){n?n=": "+n:n="",er&&this.throwError("too many arguments"+n,t.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",t.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return lT||(lT=new t(_te)),lT}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),wM){if(!e)return;this.globalLogger().throwError("error censorship permanent",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}vM=!!e,wM=!!r}static setLogLevel(e){let r=Qm[e.toLowerCase()];if(r==null){t.globalLogger().warn("invalid log level - "+e);return}AM=r}static from(e){return new t(e)}};kt.errors=Si,kt.levels=_T;var Nte="bytes/5.7.0",er=new kt(Nte);function m4(t){return!!t.toHexString}function tl(t){return t.slice||(t.slice=function(){let e=Array.prototype.slice.call(arguments);return tl(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function xte(t){return gn(t)&&!(t.length%2)||ul(t)}function SM(t){return typeof t=="number"&&t==t&&t%1===0}function ul(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!SM(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function Qt(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid arrayify value");let r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),tl(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t)&&(t=t.toHexString()),gn(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":er.throwArgumentError("hex data is odd-length","value",t));let n=[];for(let i=0;iQt(i)),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);return e.reduce((i,s)=>(n.set(s,i),i+s.length),0),tl(n)}function Dte(t,e){t=Qt(t),t.length>e&&er.throwArgumentError("value out of range","value",arguments[0]);let r=new Uint8Array(e);return r.set(t,e-t.length),tl(r)}function gn(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}var fT="0123456789abcdef";function kr(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=fT[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),m4(t))return t.toHexString();if(gn(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":er.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(ul(t)){let r="0x";for(let n=0;n>4]+fT[i&15]}return r}return er.throwArgumentError("invalid hexlify value","value",t)}function Pte(t){if(typeof t!="string")t=kr(t);else if(!gn(t)||t.length%2)return null;return(t.length-2)/2}function IM(t,e,r){return typeof t!="string"?t=kr(t):(!gn(t)||t.length%2)&&er.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function fs(t,e){for(typeof t!="string"?t=kr(t):gn(t)||er.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&er.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function y4(t){let e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(xte(t)){let r=Qt(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64))):r.length===65?(e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64)),e.v=r[64]):er.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:er.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=kr(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){let i=Dte(Qt(e._vs),32);e._vs=kr(i);let s=i[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&er.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),i[0]&=127;let o=kr(i);e.s==null?e.s=o:e.s!==o&&er.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?er.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{let i=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==i&&er.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!gn(e.r)?er.throwArgumentError("signature missing or invalid r","signature",t):e.r=fs(e.r,32),e.s==null||!gn(e.s)?er.throwArgumentError("signature missing or invalid s","signature",t):e.s=fs(e.s,32);let r=Qt(e.s);r[0]>=128&&er.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);let n=kr(r);e._vs&&(gn(e._vs)||er.throwArgumentError("signature invalid _vs","signature",t),e._vs=fs(e._vs,32)),e._vs==null?e._vs=n:e._vs!==n&&er.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function HT(t){return"0x"+Tte.keccak_256(Qt(t))}var w4={exports:{}},Rte={},Bte=Object.freeze({__proto__:null,default:Rte}),Mte=Ite(Bte);(function(t){(function(e,r){function n(l,g){if(!l)throw new Error(g||"Assertion failed")}function i(l,g){l.super_=g;var y=function(){};y.prototype=g.prototype,l.prototype=new y,l.prototype.constructor=l}function s(l,g,y){if(s.isBN(l))return l;this.negative=0,this.words=null,this.length=0,this.red=null,l!==null&&((g==="le"||g==="be")&&(y=g,g=10),this._init(l||0,g||10,y||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Mte.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,g){return l.cmp(g)>0?l:g},s.min=function(l,g){return l.cmp(g)<0?l:g},s.prototype._init=function(l,g,y){if(typeof l=="number")return this._initNumber(l,g,y);if(typeof l=="object")return this._initArray(l,g,y);g==="hex"&&(g=16),n(g===(g|0)&&g>=2&&g<=36),l=l.toString().replace(/\s+/g,"");var E=0;l[0]==="-"&&(E++,this.negative=1),E=0;E-=3)_=l[E]|l[E-1]<<8|l[E-2]<<16,this.words[S]|=_<>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);else if(y==="le")for(E=0,S=0;E>>26-M&67108863,M+=24,M>=26&&(M-=26,S++);return this._strip()};function u(l,g){var y=l.charCodeAt(g);if(y>=48&&y<=57)return y-48;if(y>=65&&y<=70)return y-55;if(y>=97&&y<=102)return y-87;n(!1,"Invalid character in "+l)}function a(l,g,y){var E=u(l,y);return y-1>=g&&(E|=u(l,y-1)<<4),E}s.prototype._parseHex=function(l,g,y){this.length=Math.ceil((l.length-g)/6),this.words=new Array(this.length);for(var E=0;E=g;E-=2)M=a(l,g,E)<=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8;else{var N=l.length-g;for(E=N%2===0?g+1:g;E=18?(S-=18,_+=1,this.words[_]|=M>>>26):S+=8}this._strip()};function c(l,g,y,E){for(var S=0,_=0,M=Math.min(l.length,y),N=g;N=49?_=m-49+10:m>=17?_=m-17+10:_=m,n(m>=0&&_1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch{s.prototype.inspect=d}else s.prototype.inspect=d;function d(){return(this.red?""}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],A=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(l,g){l=l||10,g=g|0||1;var y;if(l===16||l==="hex"){y="";for(var E=0,S=0,_=0;_>>24-E&16777215,E+=2,E>=26&&(E-=26,_--),S!==0||_!==this.length-1?y=w[6-N.length]+N+y:y=N+y}for(S!==0&&(y=S.toString(16)+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var m=A[l],O=T[l];y="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var $=Y.modrn(O).toString(l);Y=Y.idivn(O),Y.isZero()?y=$+y:y=w[m-$.length]+$+y}for(this.isZero()&&(y="0"+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(l,g){return this.toArrayLike(o,l,g)}),s.prototype.toArray=function(l,g){return this.toArrayLike(Array,l,g)};var x=function(l,g){return l.allocUnsafe?l.allocUnsafe(g):new l(g)};s.prototype.toArrayLike=function(l,g,y){this._strip();var E=this.byteLength(),S=y||Math.max(1,E);n(E<=S,"byte array longer than desired length"),n(S>0,"Requested array length <= 0");var _=x(l,S),M=g==="le"?"LE":"BE";return this["_toArrayLike"+M](_,E),_},s.prototype._toArrayLikeLE=function(l,g){for(var y=0,E=0,S=0,_=0;S>8&255),y>16&255),_===6?(y>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y=0&&(l[y--]=M>>8&255),y>=0&&(l[y--]=M>>16&255),_===6?(y>=0&&(l[y--]=M>>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y>=0)for(l[y--]=E;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var g=l,y=0;return g>=4096&&(y+=13,g>>>=13),g>=64&&(y+=7,g>>>=7),g>=8&&(y+=4,g>>>=4),g>=2&&(y+=2,g>>>=2),y+g},s.prototype._zeroBits=function(l){if(l===0)return 26;var g=l,y=0;return g&8191||(y+=13,g>>>=13),g&127||(y+=7,g>>>=7),g&15||(y+=4,g>>>=4),g&3||(y+=2,g>>>=2),g&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],g=this._countBits(l);return(this.length-1)*26+g};function R(l){for(var g=new Array(l.bitLength()),y=0;y>>S&1}return g}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,g=0;gl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var g;this.length>l.length?g=l:g=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var g,y;this.length>l.length?(g=this,y=l):(g=l,y=this);for(var E=0;El.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var g=Math.ceil(l/26)|0,y=l%26;this._expand(g),y>0&&g--;for(var E=0;E0&&(this.words[E]=~this.words[E]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,g){n(typeof l=="number"&&l>=0);var y=l/26|0,E=l%26;return this._expand(y+1),g?this.words[y]=this.words[y]|1<l.length?(y=this,E=l):(y=l,E=this);for(var S=0,_=0;_>>26;for(;S!==0&&_>>26;if(this.length=y.length,S!==0)this.words[this.length]=S,this.length++;else if(y!==this)for(;_l.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var g=this.iadd(l);return l.negative=1,g._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,S;y>0?(E=this,S=l):(E=l,S=this);for(var _=0,M=0;M>26,this.words[M]=g&67108863;for(;_!==0&&M>26,this.words[M]=g&67108863;if(_===0&&M>>26,$=m&67108863,b=Math.min(O,g.length-1),j=Math.max(0,O-l.length+1);j<=b;j++){var z=O-j|0;S=l.words[z]|0,_=g.words[j]|0,M=S*_+$,Y+=M/67108864|0,$=M&67108863}y.words[O]=$|0,m=Y|0}return m!==0?y.words[O]=m|0:y.length--,y._strip()}var U=function(l,g,y){var E=l.words,S=g.words,_=y.words,M=0,N,m,O,Y=E[0]|0,$=Y&8191,b=Y>>>13,j=E[1]|0,z=j&8191,W=j>>>13,ie=E[2]|0,te=ie&8191,ee=ie>>>13,se=E[3]|0,oe=se&8191,J=se>>>13,ue=E[4]|0,wt=ue&8191,vt=ue>>>13,Ni=E[5]|0,At=Ni&8191,Et=Ni>>>13,xi=E[6]|0,bt=xi&8191,St=xi>>>13,Oi=E[7]|0,It=Oi&8191,Tt=Oi>>>13,Di=E[8]|0,Qe=Di&8191,Ke=Di>>>13,ri=E[9]|0,We=ri&8191,$e=ri>>>13,ni=S[0]|0,Ye=ni&8191,Je=ni>>>13,ii=S[1]|0,Xe=ii&8191,Ze=ii>>>13,si=S[2]|0,et=si&8191,tt=si>>>13,oi=S[3]|0,rt=oi&8191,nt=oi>>>13,ai=S[4]|0,it=ai&8191,st=ai>>>13,ui=S[5]|0,ot=ui&8191,at=ui>>>13,ci=S[6]|0,ut=ci&8191,ct=ci>>>13,li=S[7]|0,lt=li&8191,ft=li>>>13,fi=S[8]|0,ht=fi&8191,dt=fi>>>13,hi=S[9]|0,gt=hi&8191,pt=hi>>>13;y.negative=l.negative^g.negative,y.length=19,N=Math.imul($,Ye),m=Math.imul($,Je),m=m+Math.imul(b,Ye)|0,O=Math.imul(b,Je);var vn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(vn>>>26)|0,vn&=67108863,N=Math.imul(z,Ye),m=Math.imul(z,Je),m=m+Math.imul(W,Ye)|0,O=Math.imul(W,Je),N=N+Math.imul($,Xe)|0,m=m+Math.imul($,Ze)|0,m=m+Math.imul(b,Xe)|0,O=O+Math.imul(b,Ze)|0;var An=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(An>>>26)|0,An&=67108863,N=Math.imul(te,Ye),m=Math.imul(te,Je),m=m+Math.imul(ee,Ye)|0,O=Math.imul(ee,Je),N=N+Math.imul(z,Xe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(W,Xe)|0,O=O+Math.imul(W,Ze)|0,N=N+Math.imul($,et)|0,m=m+Math.imul($,tt)|0,m=m+Math.imul(b,et)|0,O=O+Math.imul(b,tt)|0;var En=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(En>>>26)|0,En&=67108863,N=Math.imul(oe,Ye),m=Math.imul(oe,Je),m=m+Math.imul(J,Ye)|0,O=Math.imul(J,Je),N=N+Math.imul(te,Xe)|0,m=m+Math.imul(te,Ze)|0,m=m+Math.imul(ee,Xe)|0,O=O+Math.imul(ee,Ze)|0,N=N+Math.imul(z,et)|0,m=m+Math.imul(z,tt)|0,m=m+Math.imul(W,et)|0,O=O+Math.imul(W,tt)|0,N=N+Math.imul($,rt)|0,m=m+Math.imul($,nt)|0,m=m+Math.imul(b,rt)|0,O=O+Math.imul(b,nt)|0;var bn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(bn>>>26)|0,bn&=67108863,N=Math.imul(wt,Ye),m=Math.imul(wt,Je),m=m+Math.imul(vt,Ye)|0,O=Math.imul(vt,Je),N=N+Math.imul(oe,Xe)|0,m=m+Math.imul(oe,Ze)|0,m=m+Math.imul(J,Xe)|0,O=O+Math.imul(J,Ze)|0,N=N+Math.imul(te,et)|0,m=m+Math.imul(te,tt)|0,m=m+Math.imul(ee,et)|0,O=O+Math.imul(ee,tt)|0,N=N+Math.imul(z,rt)|0,m=m+Math.imul(z,nt)|0,m=m+Math.imul(W,rt)|0,O=O+Math.imul(W,nt)|0,N=N+Math.imul($,it)|0,m=m+Math.imul($,st)|0,m=m+Math.imul(b,it)|0,O=O+Math.imul(b,st)|0;var Sn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Sn>>>26)|0,Sn&=67108863,N=Math.imul(At,Ye),m=Math.imul(At,Je),m=m+Math.imul(Et,Ye)|0,O=Math.imul(Et,Je),N=N+Math.imul(wt,Xe)|0,m=m+Math.imul(wt,Ze)|0,m=m+Math.imul(vt,Xe)|0,O=O+Math.imul(vt,Ze)|0,N=N+Math.imul(oe,et)|0,m=m+Math.imul(oe,tt)|0,m=m+Math.imul(J,et)|0,O=O+Math.imul(J,tt)|0,N=N+Math.imul(te,rt)|0,m=m+Math.imul(te,nt)|0,m=m+Math.imul(ee,rt)|0,O=O+Math.imul(ee,nt)|0,N=N+Math.imul(z,it)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(W,it)|0,O=O+Math.imul(W,st)|0,N=N+Math.imul($,ot)|0,m=m+Math.imul($,at)|0,m=m+Math.imul(b,ot)|0,O=O+Math.imul(b,at)|0;var In=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(In>>>26)|0,In&=67108863,N=Math.imul(bt,Ye),m=Math.imul(bt,Je),m=m+Math.imul(St,Ye)|0,O=Math.imul(St,Je),N=N+Math.imul(At,Xe)|0,m=m+Math.imul(At,Ze)|0,m=m+Math.imul(Et,Xe)|0,O=O+Math.imul(Et,Ze)|0,N=N+Math.imul(wt,et)|0,m=m+Math.imul(wt,tt)|0,m=m+Math.imul(vt,et)|0,O=O+Math.imul(vt,tt)|0,N=N+Math.imul(oe,rt)|0,m=m+Math.imul(oe,nt)|0,m=m+Math.imul(J,rt)|0,O=O+Math.imul(J,nt)|0,N=N+Math.imul(te,it)|0,m=m+Math.imul(te,st)|0,m=m+Math.imul(ee,it)|0,O=O+Math.imul(ee,st)|0,N=N+Math.imul(z,ot)|0,m=m+Math.imul(z,at)|0,m=m+Math.imul(W,ot)|0,O=O+Math.imul(W,at)|0,N=N+Math.imul($,ut)|0,m=m+Math.imul($,ct)|0,m=m+Math.imul(b,ut)|0,O=O+Math.imul(b,ct)|0;var da=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(da>>>26)|0,da&=67108863,N=Math.imul(It,Ye),m=Math.imul(It,Je),m=m+Math.imul(Tt,Ye)|0,O=Math.imul(Tt,Je),N=N+Math.imul(bt,Xe)|0,m=m+Math.imul(bt,Ze)|0,m=m+Math.imul(St,Xe)|0,O=O+Math.imul(St,Ze)|0,N=N+Math.imul(At,et)|0,m=m+Math.imul(At,tt)|0,m=m+Math.imul(Et,et)|0,O=O+Math.imul(Et,tt)|0,N=N+Math.imul(wt,rt)|0,m=m+Math.imul(wt,nt)|0,m=m+Math.imul(vt,rt)|0,O=O+Math.imul(vt,nt)|0,N=N+Math.imul(oe,it)|0,m=m+Math.imul(oe,st)|0,m=m+Math.imul(J,it)|0,O=O+Math.imul(J,st)|0,N=N+Math.imul(te,ot)|0,m=m+Math.imul(te,at)|0,m=m+Math.imul(ee,ot)|0,O=O+Math.imul(ee,at)|0,N=N+Math.imul(z,ut)|0,m=m+Math.imul(z,ct)|0,m=m+Math.imul(W,ut)|0,O=O+Math.imul(W,ct)|0,N=N+Math.imul($,lt)|0,m=m+Math.imul($,ft)|0,m=m+Math.imul(b,lt)|0,O=O+Math.imul(b,ft)|0;var ga=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ga>>>26)|0,ga&=67108863,N=Math.imul(Qe,Ye),m=Math.imul(Qe,Je),m=m+Math.imul(Ke,Ye)|0,O=Math.imul(Ke,Je),N=N+Math.imul(It,Xe)|0,m=m+Math.imul(It,Ze)|0,m=m+Math.imul(Tt,Xe)|0,O=O+Math.imul(Tt,Ze)|0,N=N+Math.imul(bt,et)|0,m=m+Math.imul(bt,tt)|0,m=m+Math.imul(St,et)|0,O=O+Math.imul(St,tt)|0,N=N+Math.imul(At,rt)|0,m=m+Math.imul(At,nt)|0,m=m+Math.imul(Et,rt)|0,O=O+Math.imul(Et,nt)|0,N=N+Math.imul(wt,it)|0,m=m+Math.imul(wt,st)|0,m=m+Math.imul(vt,it)|0,O=O+Math.imul(vt,st)|0,N=N+Math.imul(oe,ot)|0,m=m+Math.imul(oe,at)|0,m=m+Math.imul(J,ot)|0,O=O+Math.imul(J,at)|0,N=N+Math.imul(te,ut)|0,m=m+Math.imul(te,ct)|0,m=m+Math.imul(ee,ut)|0,O=O+Math.imul(ee,ct)|0,N=N+Math.imul(z,lt)|0,m=m+Math.imul(z,ft)|0,m=m+Math.imul(W,lt)|0,O=O+Math.imul(W,ft)|0,N=N+Math.imul($,ht)|0,m=m+Math.imul($,dt)|0,m=m+Math.imul(b,ht)|0,O=O+Math.imul(b,dt)|0;var pa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pa>>>26)|0,pa&=67108863,N=Math.imul(We,Ye),m=Math.imul(We,Je),m=m+Math.imul($e,Ye)|0,O=Math.imul($e,Je),N=N+Math.imul(Qe,Xe)|0,m=m+Math.imul(Qe,Ze)|0,m=m+Math.imul(Ke,Xe)|0,O=O+Math.imul(Ke,Ze)|0,N=N+Math.imul(It,et)|0,m=m+Math.imul(It,tt)|0,m=m+Math.imul(Tt,et)|0,O=O+Math.imul(Tt,tt)|0,N=N+Math.imul(bt,rt)|0,m=m+Math.imul(bt,nt)|0,m=m+Math.imul(St,rt)|0,O=O+Math.imul(St,nt)|0,N=N+Math.imul(At,it)|0,m=m+Math.imul(At,st)|0,m=m+Math.imul(Et,it)|0,O=O+Math.imul(Et,st)|0,N=N+Math.imul(wt,ot)|0,m=m+Math.imul(wt,at)|0,m=m+Math.imul(vt,ot)|0,O=O+Math.imul(vt,at)|0,N=N+Math.imul(oe,ut)|0,m=m+Math.imul(oe,ct)|0,m=m+Math.imul(J,ut)|0,O=O+Math.imul(J,ct)|0,N=N+Math.imul(te,lt)|0,m=m+Math.imul(te,ft)|0,m=m+Math.imul(ee,lt)|0,O=O+Math.imul(ee,ft)|0,N=N+Math.imul(z,ht)|0,m=m+Math.imul(z,dt)|0,m=m+Math.imul(W,ht)|0,O=O+Math.imul(W,dt)|0,N=N+Math.imul($,gt)|0,m=m+Math.imul($,pt)|0,m=m+Math.imul(b,gt)|0,O=O+Math.imul(b,pt)|0;var ma=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ma>>>26)|0,ma&=67108863,N=Math.imul(We,Xe),m=Math.imul(We,Ze),m=m+Math.imul($e,Xe)|0,O=Math.imul($e,Ze),N=N+Math.imul(Qe,et)|0,m=m+Math.imul(Qe,tt)|0,m=m+Math.imul(Ke,et)|0,O=O+Math.imul(Ke,tt)|0,N=N+Math.imul(It,rt)|0,m=m+Math.imul(It,nt)|0,m=m+Math.imul(Tt,rt)|0,O=O+Math.imul(Tt,nt)|0,N=N+Math.imul(bt,it)|0,m=m+Math.imul(bt,st)|0,m=m+Math.imul(St,it)|0,O=O+Math.imul(St,st)|0,N=N+Math.imul(At,ot)|0,m=m+Math.imul(At,at)|0,m=m+Math.imul(Et,ot)|0,O=O+Math.imul(Et,at)|0,N=N+Math.imul(wt,ut)|0,m=m+Math.imul(wt,ct)|0,m=m+Math.imul(vt,ut)|0,O=O+Math.imul(vt,ct)|0,N=N+Math.imul(oe,lt)|0,m=m+Math.imul(oe,ft)|0,m=m+Math.imul(J,lt)|0,O=O+Math.imul(J,ft)|0,N=N+Math.imul(te,ht)|0,m=m+Math.imul(te,dt)|0,m=m+Math.imul(ee,ht)|0,O=O+Math.imul(ee,dt)|0,N=N+Math.imul(z,gt)|0,m=m+Math.imul(z,pt)|0,m=m+Math.imul(W,gt)|0,O=O+Math.imul(W,pt)|0;var ya=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ya>>>26)|0,ya&=67108863,N=Math.imul(We,et),m=Math.imul(We,tt),m=m+Math.imul($e,et)|0,O=Math.imul($e,tt),N=N+Math.imul(Qe,rt)|0,m=m+Math.imul(Qe,nt)|0,m=m+Math.imul(Ke,rt)|0,O=O+Math.imul(Ke,nt)|0,N=N+Math.imul(It,it)|0,m=m+Math.imul(It,st)|0,m=m+Math.imul(Tt,it)|0,O=O+Math.imul(Tt,st)|0,N=N+Math.imul(bt,ot)|0,m=m+Math.imul(bt,at)|0,m=m+Math.imul(St,ot)|0,O=O+Math.imul(St,at)|0,N=N+Math.imul(At,ut)|0,m=m+Math.imul(At,ct)|0,m=m+Math.imul(Et,ut)|0,O=O+Math.imul(Et,ct)|0,N=N+Math.imul(wt,lt)|0,m=m+Math.imul(wt,ft)|0,m=m+Math.imul(vt,lt)|0,O=O+Math.imul(vt,ft)|0,N=N+Math.imul(oe,ht)|0,m=m+Math.imul(oe,dt)|0,m=m+Math.imul(J,ht)|0,O=O+Math.imul(J,dt)|0,N=N+Math.imul(te,gt)|0,m=m+Math.imul(te,pt)|0,m=m+Math.imul(ee,gt)|0,O=O+Math.imul(ee,pt)|0;var wa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(wa>>>26)|0,wa&=67108863,N=Math.imul(We,rt),m=Math.imul(We,nt),m=m+Math.imul($e,rt)|0,O=Math.imul($e,nt),N=N+Math.imul(Qe,it)|0,m=m+Math.imul(Qe,st)|0,m=m+Math.imul(Ke,it)|0,O=O+Math.imul(Ke,st)|0,N=N+Math.imul(It,ot)|0,m=m+Math.imul(It,at)|0,m=m+Math.imul(Tt,ot)|0,O=O+Math.imul(Tt,at)|0,N=N+Math.imul(bt,ut)|0,m=m+Math.imul(bt,ct)|0,m=m+Math.imul(St,ut)|0,O=O+Math.imul(St,ct)|0,N=N+Math.imul(At,lt)|0,m=m+Math.imul(At,ft)|0,m=m+Math.imul(Et,lt)|0,O=O+Math.imul(Et,ft)|0,N=N+Math.imul(wt,ht)|0,m=m+Math.imul(wt,dt)|0,m=m+Math.imul(vt,ht)|0,O=O+Math.imul(vt,dt)|0,N=N+Math.imul(oe,gt)|0,m=m+Math.imul(oe,pt)|0,m=m+Math.imul(J,gt)|0,O=O+Math.imul(J,pt)|0;var va=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(va>>>26)|0,va&=67108863,N=Math.imul(We,it),m=Math.imul(We,st),m=m+Math.imul($e,it)|0,O=Math.imul($e,st),N=N+Math.imul(Qe,ot)|0,m=m+Math.imul(Qe,at)|0,m=m+Math.imul(Ke,ot)|0,O=O+Math.imul(Ke,at)|0,N=N+Math.imul(It,ut)|0,m=m+Math.imul(It,ct)|0,m=m+Math.imul(Tt,ut)|0,O=O+Math.imul(Tt,ct)|0,N=N+Math.imul(bt,lt)|0,m=m+Math.imul(bt,ft)|0,m=m+Math.imul(St,lt)|0,O=O+Math.imul(St,ft)|0,N=N+Math.imul(At,ht)|0,m=m+Math.imul(At,dt)|0,m=m+Math.imul(Et,ht)|0,O=O+Math.imul(Et,dt)|0,N=N+Math.imul(wt,gt)|0,m=m+Math.imul(wt,pt)|0,m=m+Math.imul(vt,gt)|0,O=O+Math.imul(vt,pt)|0;var Aa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,N=Math.imul(We,ot),m=Math.imul(We,at),m=m+Math.imul($e,ot)|0,O=Math.imul($e,at),N=N+Math.imul(Qe,ut)|0,m=m+Math.imul(Qe,ct)|0,m=m+Math.imul(Ke,ut)|0,O=O+Math.imul(Ke,ct)|0,N=N+Math.imul(It,lt)|0,m=m+Math.imul(It,ft)|0,m=m+Math.imul(Tt,lt)|0,O=O+Math.imul(Tt,ft)|0,N=N+Math.imul(bt,ht)|0,m=m+Math.imul(bt,dt)|0,m=m+Math.imul(St,ht)|0,O=O+Math.imul(St,dt)|0,N=N+Math.imul(At,gt)|0,m=m+Math.imul(At,pt)|0,m=m+Math.imul(Et,gt)|0,O=O+Math.imul(Et,pt)|0;var Ea=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Ea>>>26)|0,Ea&=67108863,N=Math.imul(We,ut),m=Math.imul(We,ct),m=m+Math.imul($e,ut)|0,O=Math.imul($e,ct),N=N+Math.imul(Qe,lt)|0,m=m+Math.imul(Qe,ft)|0,m=m+Math.imul(Ke,lt)|0,O=O+Math.imul(Ke,ft)|0,N=N+Math.imul(It,ht)|0,m=m+Math.imul(It,dt)|0,m=m+Math.imul(Tt,ht)|0,O=O+Math.imul(Tt,dt)|0,N=N+Math.imul(bt,gt)|0,m=m+Math.imul(bt,pt)|0,m=m+Math.imul(St,gt)|0,O=O+Math.imul(St,pt)|0;var hw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(hw>>>26)|0,hw&=67108863,N=Math.imul(We,lt),m=Math.imul(We,ft),m=m+Math.imul($e,lt)|0,O=Math.imul($e,ft),N=N+Math.imul(Qe,ht)|0,m=m+Math.imul(Qe,dt)|0,m=m+Math.imul(Ke,ht)|0,O=O+Math.imul(Ke,dt)|0,N=N+Math.imul(It,gt)|0,m=m+Math.imul(It,pt)|0,m=m+Math.imul(Tt,gt)|0,O=O+Math.imul(Tt,pt)|0;var dw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(dw>>>26)|0,dw&=67108863,N=Math.imul(We,ht),m=Math.imul(We,dt),m=m+Math.imul($e,ht)|0,O=Math.imul($e,dt),N=N+Math.imul(Qe,gt)|0,m=m+Math.imul(Qe,pt)|0,m=m+Math.imul(Ke,gt)|0,O=O+Math.imul(Ke,pt)|0;var gw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(gw>>>26)|0,gw&=67108863,N=Math.imul(We,gt),m=Math.imul(We,pt),m=m+Math.imul($e,gt)|0,O=Math.imul($e,pt);var pw=(M+N|0)+((m&8191)<<13)|0;return M=(O+(m>>>13)|0)+(pw>>>26)|0,pw&=67108863,_[0]=vn,_[1]=An,_[2]=En,_[3]=bn,_[4]=Sn,_[5]=In,_[6]=da,_[7]=ga,_[8]=pa,_[9]=ma,_[10]=ya,_[11]=wa,_[12]=va,_[13]=Aa,_[14]=Ea,_[15]=hw,_[16]=dw,_[17]=gw,_[18]=pw,M!==0&&(_[19]=M,y.length++),y};Math.imul||(U=V);function Q(l,g,y){y.negative=g.negative^l.negative,y.length=l.length+g.length;for(var E=0,S=0,_=0;_>>26)|0,S+=M>>>26,M&=67108863}y.words[_]=N,E=M,M=S}return E!==0?y.words[_]=E:y.length--,y._strip()}function L(l,g,y){return Q(l,g,y)}s.prototype.mulTo=function(l,g){var y,E=this.length+l.length;return this.length===10&&l.length===10?y=U(this,l,g):E<63?y=V(this,l,g):E<1024?y=Q(this,l,g):y=L(this,l,g),y},s.prototype.mul=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),this.mulTo(l,g)},s.prototype.mulf=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),L(this,l,g)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var g=l<0;g&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var y=0,E=0;E>=26,y+=S/67108864|0,y+=_>>>26,this.words[E]=_&67108863}return y!==0&&(this.words[E]=y,this.length++),g?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var g=R(l);if(g.length===0)return new s(1);for(var y=this,E=0;E=0);var g=l%26,y=(l-g)/26,E=67108863>>>26-g<<26-g,S;if(g!==0){var _=0;for(S=0;S>>26-g}_&&(this.words[S]=_,this.length++)}if(y!==0){for(S=this.length-1;S>=0;S--)this.words[S+y]=this.words[S];for(S=0;S=0);var E;g?E=(g-g%26)/26:E=0;var S=l%26,_=Math.min((l-S)/26,this.length),M=67108863^67108863>>>S<_)for(this.length-=_,m=0;m=0&&(O!==0||m>=E);m--){var Y=this.words[m]|0;this.words[m]=O<<26-S|Y>>>S,O=Y&M}return N&&O!==0&&(N.words[N.length++]=O),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,g,y){return n(this.negative===0),this.iushrn(l,g,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var g=l%26,y=(l-g)/26,E=1<=0);var g=l%26,y=(l-g)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(g!==0&&y++,this.length=Math.min(y,this.length),g!==0){var E=67108863^67108863>>>g<=67108864;g++)this.words[g]-=67108864,g===this.length-1?this.words[g+1]=1:this.words[g+1]++;return this.length=Math.max(this.length,g+1),this},s.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var g=0;g>26)-(N/67108864|0),this.words[S+y]=_&67108863}for(;S>26,this.words[S+y]=_&67108863;if(M===0)return this._strip();for(n(M===-1),M=0,S=0;S>26,this.words[S]=_&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,g){var y=this.length-l.length,E=this.clone(),S=l,_=S.words[S.length-1]|0,M=this._countBits(_);y=26-M,y!==0&&(S=S.ushln(y),E.iushln(y),_=S.words[S.length-1]|0);var N=E.length-S.length,m;if(g!=="mod"){m=new s(null),m.length=N+1,m.words=new Array(m.length);for(var O=0;O=0;$--){var b=(E.words[S.length+$]|0)*67108864+(E.words[S.length+$-1]|0);for(b=Math.min(b/_|0,67108863),E._ishlnsubmul(S,b,$);E.negative!==0;)b--,E.negative=0,E._ishlnsubmul(S,1,$),E.isZero()||(E.negative^=1);m&&(m.words[$]=b)}return m&&m._strip(),E._strip(),g!=="div"&&y!==0&&E.iushrn(y),{div:m||null,mod:E}},s.prototype.divmod=function(l,g,y){if(n(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,S,_;return this.negative!==0&&l.negative===0?(_=this.neg().divmod(l,g),g!=="mod"&&(E=_.div.neg()),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.iadd(l)),{div:E,mod:S}):this.negative===0&&l.negative!==0?(_=this.divmod(l.neg(),g),g!=="mod"&&(E=_.div.neg()),{div:E,mod:_.mod}):this.negative&l.negative?(_=this.neg().divmod(l.neg(),g),g!=="div"&&(S=_.mod.neg(),y&&S.negative!==0&&S.isub(l)),{div:_.div,mod:S}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?g==="div"?{div:this.divn(l.words[0]),mod:null}:g==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,g)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var g=this.divmod(l);if(g.mod.isZero())return g.div;var y=g.div.negative!==0?g.mod.isub(l):g.mod,E=l.ushrn(1),S=l.andln(1),_=y.cmp(E);return _<0||S===1&&_===0?g.div:g.div.negative!==0?g.div.isubn(1):g.div.iaddn(1)},s.prototype.modrn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=(1<<26)%l,E=0,S=this.length-1;S>=0;S--)E=(y*E+(this.words[S]|0))%l;return g?-E:E},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=0,E=this.length-1;E>=0;E--){var S=(this.words[E]|0)+y*67108864;this.words[E]=S/l|0,y=S%l}return this._strip(),g?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=new s(0),M=new s(1),N=0;g.isEven()&&y.isEven();)g.iushrn(1),y.iushrn(1),++N;for(var m=y.clone(),O=g.clone();!g.isZero();){for(var Y=0,$=1;!(g.words[0]&$)&&Y<26;++Y,$<<=1);if(Y>0)for(g.iushrn(Y);Y-- >0;)(E.isOdd()||S.isOdd())&&(E.iadd(m),S.isub(O)),E.iushrn(1),S.iushrn(1);for(var b=0,j=1;!(y.words[0]&j)&&b<26;++b,j<<=1);if(b>0)for(y.iushrn(b);b-- >0;)(_.isOdd()||M.isOdd())&&(_.iadd(m),M.isub(O)),_.iushrn(1),M.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(_),S.isub(M)):(y.isub(g),_.isub(E),M.isub(S))}return{a:_,b:M,gcd:y.iushln(N)}},s.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),S=new s(0),_=y.clone();g.cmpn(1)>0&&y.cmpn(1)>0;){for(var M=0,N=1;!(g.words[0]&N)&&M<26;++M,N<<=1);if(M>0)for(g.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(_),E.iushrn(1);for(var m=0,O=1;!(y.words[0]&O)&&m<26;++m,O<<=1);if(m>0)for(y.iushrn(m);m-- >0;)S.isOdd()&&S.iadd(_),S.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(S)):(y.isub(g),S.isub(E))}var Y;return g.cmpn(1)===0?Y=E:Y=S,Y.cmpn(0)<0&&Y.iadd(l),Y},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var g=this.clone(),y=l.clone();g.negative=0,y.negative=0;for(var E=0;g.isEven()&&y.isEven();E++)g.iushrn(1),y.iushrn(1);do{for(;g.isEven();)g.iushrn(1);for(;y.isEven();)y.iushrn(1);var S=g.cmp(y);if(S<0){var _=g;g=y,y=_}else if(S===0||y.cmpn(1)===0)break;g.isub(y)}while(!0);return y.iushln(E)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){n(typeof l=="number");var g=l%26,y=(l-g)/26,E=1<>>26,M&=67108863,this.words[_]=M}return S!==0&&(this.words[_]=S,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var g=l<0;if(this.negative!==0&&!g)return-1;if(this.negative===0&&g)return 1;this._strip();var y;if(this.length>1)y=1;else{g&&(l=-l),n(l<=67108863,"Number is too big");var E=this.words[0]|0;y=E===l?0:El.length)return 1;if(this.length=0;y--){var E=this.words[y]|0,S=l.words[y]|0;if(E!==S){ES&&(g=1);break}}return g},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new F(l)},s.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var k={k256:null,p224:null,p192:null,p25519:null};function H(l,g){this.name=l,this.p=new s(g,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},H.prototype.ireduce=function(l){var g=l,y;do this.split(g,this.tmp),g=this.imulK(g),g=g.iadd(this.tmp),y=g.bitLength();while(y>this.n);var E=y0?g.isub(this.p):g.strip!==void 0?g.strip():g._strip(),g},H.prototype.split=function(l,g){l.iushrn(this.n,0,g)},H.prototype.imulK=function(l){return l.imul(this.k)};function q(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(q,H),q.prototype.split=function(l,g){for(var y=4194303,E=Math.min(l.length,9),S=0;S>>22,_=M}_>>>=22,l.words[S-10]=_,_===0&&l.length>10?l.length-=10:l.length-=9},q.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var g=0,y=0;y>>=26,l.words[y]=S,g=E}return g!==0&&(l.words[l.length++]=g),l},s._prime=function(l){if(k[l])return k[l];var g;if(l==="k256")g=new q;else if(l==="p224")g=new v;else if(l==="p192")g=new C;else if(l==="p25519")g=new D;else throw new Error("Unknown prime "+l);return k[l]=g,g};function F(l){if(typeof l=="string"){var g=s._prime(l);this.m=g.p,this.prime=g}else n(l.gtn(1),"modulus must be greater than 1"),this.m=l,this.prime=null}F.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},F.prototype._verify2=function(l,g){n((l.negative|g.negative)===0,"red works only with positives"),n(l.red&&l.red===g.red,"red works only with red numbers")},F.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(f(l,l.umod(this.m)._forceRed(this)),l)},F.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},F.prototype.add=function(l,g){this._verify2(l,g);var y=l.add(g);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},F.prototype.iadd=function(l,g){this._verify2(l,g);var y=l.iadd(g);return y.cmp(this.m)>=0&&y.isub(this.m),y},F.prototype.sub=function(l,g){this._verify2(l,g);var y=l.sub(g);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},F.prototype.isub=function(l,g){this._verify2(l,g);var y=l.isub(g);return y.cmpn(0)<0&&y.iadd(this.m),y},F.prototype.shl=function(l,g){return this._verify1(l),this.imod(l.ushln(g))},F.prototype.imul=function(l,g){return this._verify2(l,g),this.imod(l.imul(g))},F.prototype.mul=function(l,g){return this._verify2(l,g),this.imod(l.mul(g))},F.prototype.isqr=function(l){return this.imul(l,l.clone())},F.prototype.sqr=function(l){return this.mul(l,l)},F.prototype.sqrt=function(l){if(l.isZero())return l.clone();var g=this.m.andln(3);if(n(g%2===1),g===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var E=this.m.subn(1),S=0;!E.isZero()&&E.andln(1)===0;)S++,E.iushrn(1);n(!E.isZero());var _=new s(1).toRed(this),M=_.redNeg(),N=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,N).cmp(M)!==0;)m.redIAdd(M);for(var O=this.pow(m,E),Y=this.pow(l,E.addn(1).iushrn(1)),$=this.pow(l,E),b=S;$.cmp(_)!==0;){for(var j=$,z=0;j.cmp(_)!==0;z++)j=j.redSqr();n(z=0;S--){for(var O=g.words[S],Y=m-1;Y>=0;Y--){var $=O>>Y&1;if(_!==E[0]&&(_=this.sqr(_)),$===0&&M===0){N=0;continue}M<<=1,M|=$,N++,!(N!==y&&(S!==0||Y!==0))&&(_=this.mul(_,E[M]),N=0,M=0)}m=26}return _},F.prototype.convertTo=function(l){var g=l.umod(this.m);return g===l?g.clone():g},F.prototype.convertFrom=function(l){var g=l.clone();return g.red=null,g},s.mont=function(l){return new P(l)};function P(l){F.call(this,l),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(P,F),P.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},P.prototype.convertFrom=function(l){var g=this.imod(l.mul(this.rinv));return g.red=null,g},P.prototype.imul=function(l,g){if(l.isZero()||g.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.mul=function(l,g){if(l.isZero()||g.isZero())return new s(0)._forceRed(this);var y=l.mul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),S=y.isub(E).iushrn(this.shift),_=S;return S.cmp(this.m)>=0?_=S.isub(this.m):S.cmpn(0)<0&&(_=S.iadd(this.m)),_._forceRed(this)},P.prototype.invm=function(l){var g=this.imod(l._invmp(this.m).mul(this.r2));return g._forceRed(this)}})(t,g4)})(w4);var Se=w4.exports,v4="bignumber/5.7.0",Jm=Se.BN,Ks=new kt(v4),hT={},TM=9007199254740991;function Lte(t){return t!=null&&(Cr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||gn(t)||typeof t=="bigint"||ul(t))}var _M=!1,Cr=class t{constructor(e,r){e!==hT&&Ks.throwError("cannot call constructor directly; use BigNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return sn(De(this).fromTwos(e))}toTwos(e){return sn(De(this).toTwos(e))}abs(){return this._hex[0]==="-"?t.from(this._hex.substring(1)):this}add(e){return sn(De(this).add(De(e)))}sub(e){return sn(De(this).sub(De(e)))}div(e){return t.from(e).isZero()&&Kn("division-by-zero","div"),sn(De(this).div(De(e)))}mul(e){return sn(De(this).mul(De(e)))}mod(e){let r=De(e);return r.isNeg()&&Kn("division-by-zero","mod"),sn(De(this).umod(r))}pow(e){let r=De(e);return r.isNeg()&&Kn("negative-power","pow"),sn(De(this).pow(r))}and(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","and"),sn(De(this).and(r))}or(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","or"),sn(De(this).or(r))}xor(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","xor"),sn(De(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Kn("negative-width","mask"),sn(De(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Kn("negative-width","shl"),sn(De(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Kn("negative-width","shr"),sn(De(this).shrn(e))}eq(e){return De(this).eq(De(e))}lt(e){return De(this).lt(De(e))}lte(e){return De(this).lte(De(e))}gt(e){return De(this).gt(De(e))}gte(e){return De(this).gte(De(e))}isNegative(){return this._hex[0]==="-"}isZero(){return De(this).isZero()}toNumber(){try{return De(this).toNumber()}catch{Kn("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ks.throwError("this platform does not support BigInt",kt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?_M||(_M=!0,Ks.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ks.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",kt.errors.UNEXPECTED_ARGUMENT,{}):Ks.throwError("BigNumber.toString does not accept parameters",kt.errors.UNEXPECTED_ARGUMENT,{})),De(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof t)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new t(hT,Vh(e)):e.match(/^-?[0-9]+$/)?new t(hT,Vh(new Jm(e))):Ks.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Kn("underflow","BigNumber.from",e),(e>=TM||e<=-TM)&&Kn("overflow","BigNumber.from",e),t.from(String(e));let r=e;if(typeof r=="bigint")return t.from(r.toString());if(ul(r))return t.from(kr(r));if(r)if(r.toHexString){let n=r.toHexString();if(typeof n=="string")return t.from(n)}else{let n=r._hex;if(n==null&&r.type==="BigNumber"&&(n=r.hex),typeof n=="string"&&(gn(n)||n[0]==="-"&&gn(n.substring(1))))return t.from(n)}return Ks.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}};function Vh(t){if(typeof t!="string")return Vh(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ks.throwArgumentError("invalid hex","value",t),t=Vh(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function sn(t){return Cr.from(Vh(t))}function De(t){let e=Cr.from(t).toHexString();return e[0]==="-"?new Jm("-"+e.substring(3),16):new Jm(e.substring(2),16)}function Kn(t,e,r){let n={fault:t,operation:e};return r!=null&&(n.value=r),Ks.throwError(t,kt.errors.NUMERIC_FAULT,n)}function Fte(t){return new Jm(t,36).toString(16)}var Hr=new kt(v4),Fh={},A4=Cr.from(0),E4=Cr.from(-1);function b4(t,e,r,n){let i={fault:e,operation:r};return n!==void 0&&(i.value=n),Hr.throwError(t,kt.errors.NUMERIC_FAULT,i)}var Uh="0";for(;Uh.length<256;)Uh+=Uh;function GT(t){if(typeof t!="number")try{t=Cr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+Uh.substring(0,t):Hr.throwArgumentError("invalid decimal size","decimals",t)}function dT(t,e){e==null&&(e=0);let r=GT(e);t=Cr.from(t);let n=t.lt(A4);n&&(t=t.mul(E4));let i=t.mod(r).toString();for(;i.length2&&Hr.throwArgumentError("too many decimal points","value",t);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");o[o.length-1]==="0";)o=o.substring(0,o.length-1);for(o.length>r.length-1&&b4("fractional component exceeds decimals","underflow","parseFixed"),o===""&&(o="0");o.lengthe[o]==null?a:(typeof e[o]!==u&&Hr.throwArgumentError("invalid fixed format ("+o+" not "+u+")","format."+o,e[o]),e[o]);r=s("signed","boolean",r),n=s("width","number",n),i=s("decimals","number",i)}return n%8&&Hr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),i>80&&Hr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",i),new t(Fh,r,n,i)}},Xm=class t{constructor(e,r,n,i){e!==Fh&&Hr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=r,this._value=n,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Hr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.add(n),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.sub(n),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return this.isNegative()&&n&&(r=r.subUnsafe(CM.toFormat(r.format))),r}ceiling(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return!this.isNegative()&&n&&(r=r.addUnsafe(CM.toFormat(r.format))),r}round(e){e==null&&(e=0);let r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&Hr.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;let n=t.from("1"+Uh.substring(0,e),this.format),i=Ute.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(i).floor().divUnsafe(n)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Hr.throwArgumentError("invalid byte width","width",e);let r=Cr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return fs(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return t.fromString(this._value,e)}static fromValue(e,r,n){return n==null&&r!=null&&!Lte(r)&&(n=r,r=null),r==null&&(r=0),n==null&&(n="fixed"),t.fromString(dT(e,r),qh.from(n))}static fromString(e,r){r==null&&(r="fixed");let n=qh.from(r),i=Qs(e,n.decimals);!n.signed&&i.lt(A4)&&b4("unsigned value cannot be negative","overflow","value",e);let s=null;n.signed?s=i.toTwos(n.width).toHexString():(s=i.toHexString(),s=fs(s,n.width/8));let o=dT(i,n.decimals);return new t(Fh,s,o,n)}static fromBytes(e,r){r==null&&(r="fixed");let n=qh.from(r);if(Qt(e).length>n.width/8)throw new Error("overflow");let i=Cr.from(e);n.signed&&(i=i.fromTwos(n.width));let s=i.toTwos((n.signed?0:1)+n.width).toHexString(),o=dT(i,n.decimals);return new t(Fh,s,o,n)}static from(e,r){if(typeof e=="string")return t.fromString(e,r);if(ul(e))return t.fromBytes(e,r);try{return t.fromValue(e,0,r)}catch(n){if(n.code!==kt.errors.INVALID_ARGUMENT)throw n}return Hr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}},CM=Xm.from(1),Ute=Xm.from("0.5"),qte="strings/5.7.0",S4=new kt(qte),Zm;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(Zm||(Zm={}));var rl;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(rl||(rl={}));function Vte(t,e,r,n,i){return S4.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function I4(t,e,r,n,i){if(t===rl.BAD_PREFIX||t===rl.UNEXPECTED_CONTINUE){let s=0;for(let o=e+1;o>6===2;o++)s++;return s}return t===rl.OVERRUN?r.length-e-1:0}function kte(t,e,r,n,i){return t===rl.OVERLONG?(n.push(i),0):(n.push(65533),I4(t,e,r))}Object.freeze({error:Vte,ignore:I4,replace:kte});function gT(t,e=Zm.current){e!=Zm.current&&(S4.checkNormalize(),t=t.normalize(e));let r=[];for(let n=0;n>6|192),r.push(i&63|128);else if((i&64512)==55296){n++;let s=t.charCodeAt(n);if(n>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");let o=65536+((i&1023)<<10)+(s&1023);r.push(o>>18|240),r.push(o>>12&63|128),r.push(o>>6&63|128),r.push(o&63|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(i&63|128)}return Qt(r)}function Hte(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r{let s=i.split(":");r+=parseInt(s[0],16),n[r]=e(s[1])}),n}function NM(t){let e=0;return t.split(",").map(r=>{let n=r.split("-");n.length===1?n[1]="0":n[1]===""&&(n[1]="1");let i=e+parseInt(n[0],16);return e=parseInt(n[1],16),{l:i,h:e}})}NM("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),pT("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),pT("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),pT("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",Hte),NM("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");var T4="hash/5.7.0";function Gte(t){t=atob(t);let e=[];for(let r=0;r0&&Array.isArray(u)?i(u,o-1):r.push(u)})};return i(t,e),r}function jte(t){let e={};for(let r=0;r>--a&1}let d=31,w=Math.pow(2,d),A=w>>>1,T=A>>1,x=w-1,R=0;for(let k=0;k1;){let D=H+q>>>1;k>>1|f(),v=v<<1^A,C=(C^A)<<1|A|1;U=v,Q=1+C-v}let L=n-4;return V.map(k=>{switch(k-L){case 3:return L+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return L+256+(t[u++]<<8|t[u++]);case 1:return L+t[u++];default:return k-1}})}function Qte(t){let e=0;return()=>t[e++]}function Kte(t){return Qte(zte(t))}function Wte(t){return t&1?~t>>1:t>>1}function $te(t,e){let r=Array(t);for(let n=0;ne[o]):r}function Jte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(Zte(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(ere(r,t))}return jte(_4(e))}function Xte(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function C4(t,e,r){let n=Array(t).fill(void 0).map(()=>[]);for(let i=0;in[o].push(s));return n}function Zte(t,e){let r=1+e(),n=e(),i=Xte(e),s=C4(i.length,1+t,e);return _4(s.map((o,u)=>{let a=o[0],c=o.slice(1);return Array(i[u]).fill(void 0).map((f,d)=>{let w=d*n;return[a+d*r,c.map(A=>A+w)]})}))}function ere(t,e){let r=1+e();return C4(r,1+t,e).map(n=>[n[0],n.slice(1)])}function tre(t){let e=ey(t).sort((n,i)=>n-i);return r();function r(){let n=[];for(;;){let c=ey(t,e);if(c.length==0)break;n.push({set:new Set(c),node:r()})}n.sort((c,f)=>f.set.size-c.set.size);let i=t(),s=i%3;i=i/3|0;let o=!!(i&1);i>>=1;let u=i==1,a=i==2;return{branches:n,valid:s,fe0f:o,save:u,check:a}}}function rre(){return Kte(Gte("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}var km=rre();new Set(ey(km)),new Set(ey(km)),Jte(km),tre(km),new kt(T4);var nre=new Uint8Array(32);nre.fill(0);var ire=`Ethereum Signed Message: -`;function N4(t){return typeof t=="string"&&(t=gT(t)),HT(Ote([gT(ire),gT(String(t.length)),t]))}var sre="rlp/5.7.0";new kt(sre);var ore="address/5.7.0",Lh=new kt(ore);function OM(t){gn(t,20)||Lh.throwArgumentError("invalid address","address",t),t=t.toLowerCase();let e=t.substring(2).split(""),r=new Uint8Array(40);for(let i=0;i<40;i++)r[i]=e[i].charCodeAt(0);let n=Qt(HT(r));for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&(e[i]=e[i].toUpperCase()),(n[i>>1]&15)>=8&&(e[i+1]=e[i+1].toUpperCase());return"0x"+e.join("")}var are=9007199254740991;function ure(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}var jT={};for(let t=0;t<10;t++)jT[String(t)]=String(t);for(let t=0;t<26;t++)jT[String.fromCharCode(65+t)]=String(10+t);var DM=Math.floor(ure(are));function cre(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(n=>jT[n]).join("");for(;e.length>=DM;){let n=e.substring(0,DM);e=parseInt(n,10)%97+e.substring(n.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function lre(t){let e=null;if(typeof t!="string"&&Lh.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=OM(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&Lh.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==cre(t)&&Lh.throwArgumentError("bad icap checksum","address",t),e=Fte(t.substring(4));e.length<40;)e="0"+e;e=OM("0x"+e)}else Lh.throwArgumentError("invalid address","address",t);return e}var fre="properties/5.7.0";new kt(fre);function Rh(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new kt(T4);var hre=new Uint8Array(32);hre.fill(0),Cr.from(-1);var dre=Cr.from(0),gre=Cr.from(1);Cr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fs(gre.toHexString(),32),fs(dre.toHexString(),32);var os={},Pe={},Gh=x4;function x4(t,e){if(!t)throw new Error(e||"Assertion failed")}x4.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var CT={exports:{}};typeof Object.create=="function"?CT.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:CT.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var pre=Gh,mre=CT.exports;Pe.inherits=mre;function yre(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function wre(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),i=0;i>6|192,r[n++]=s&63|128):yre(t,i)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023),r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128)}else for(i=0;i>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Pe.htonl=O4;function Are(t,e){for(var r="",n=0;n>>0}return s}Pe.join32=Ere;function bre(t,e){for(var r=new Array(t.length*4),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=s&255):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=s&255)}return r}Pe.split32=bre;function Sre(t,e){return t>>>e|t<<32-e}Pe.rotr32=Sre;function Ire(t,e){return t<>>32-e}Pe.rotl32=Ire;function Tre(t,e){return t+e>>>0}Pe.sum32=Tre;function _re(t,e,r){return t+e+r>>>0}Pe.sum32_3=_re;function Cre(t,e,r,n){return t+e+r+n>>>0}Pe.sum32_4=Cre;function Nre(t,e,r,n,i){return t+e+r+n+i>>>0}Pe.sum32_5=Nre;function xre(t,e,r,n){var i=t[e],s=t[e+1],o=n+s>>>0,u=(o>>0,t[e+1]=o}Pe.sum64=xre;function Ore(t,e,r,n){var i=e+n>>>0,s=(i>>0}Pe.sum64_hi=Ore;function Dre(t,e,r,n){var i=e+n;return i>>>0}Pe.sum64_lo=Dre;function Pre(t,e,r,n,i,s,o,u){var a=0,c=e;c=c+n>>>0,a+=c>>0,a+=c>>0,a+=c>>0}Pe.sum64_4_hi=Pre;function Rre(t,e,r,n,i,s,o,u){var a=e+n+s+u;return a>>>0}Pe.sum64_4_lo=Rre;function Bre(t,e,r,n,i,s,o,u,a,c){var f=0,d=e;d=d+n>>>0,f+=d>>0,f+=d>>0,f+=d>>0,f+=d>>0}Pe.sum64_5_hi=Bre;function Mre(t,e,r,n,i,s,o,u,a,c){var f=e+n+s+u+c;return f>>>0}Pe.sum64_5_lo=Mre;function Lre(t,e,r){var n=e<<32-r|t>>>r;return n>>>0}Pe.rotr64_hi=Lre;function Fre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.rotr64_lo=Fre;function Ure(t,e,r){return t>>>r}Pe.shr64_hi=Ure;function qre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.shr64_lo=qre;var cl={},PM=Pe,Vre=Gh;function Hm(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}cl.BlockHash=Hm,Hm.prototype.update=function(t,e){if(t=PM.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=PM.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=t&255}else for(n[i++]=t&255,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s>>3}ms.g0_256=zre;function Qre(t){return hs(t,17)^hs(t,19)^t>>>10}ms.g1_256=Qre;var sl=Pe,Kre=cl,Wre=ms,mT=sl.rotl32,Bh=sl.sum32,$re=sl.sum32_5,Yre=Wre.ft_1,L4=Kre.BlockHash,Jre=[1518500249,1859775393,2400959708,3395469782];function us(){if(!(this instanceof us))return new us;L4.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}sl.inherits(us,L4);var Xre=us;us.blockSize=512,us.outSize=160,us.hmacStrength=80,us.padLength=64,us.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=new this.Hash().update(t).digest()),qne(t.length<=this.blockSize);for(var e=t.length;e>8,w=f&255;d?a.push(d,w):a.push(w)}return a}r.toArray=n;function i(o){return o.length===1?"0"+o:o}r.zero2=i;function s(o){for(var u="",a=0;a(w>>1)-1?x=(w>>1)-R:x=R,A.isubn(x)):x=0,d[T]=x,A.iushrn(1)}return d}r.getNAF=n;function i(a,c){var f=[[],[]];a=a.clone(),c=c.clone();for(var d=0,w=0,A;a.cmpn(-d)>0||c.cmpn(-w)>0;){var T=a.andln(3)+d&3,x=c.andln(3)+w&3;T===3&&(T=-1),x===3&&(x=-1);var R;T&1?(A=a.andln(7)+d&7,(A===3||A===5)&&x===2?R=-T:R=T):R=0,f[0].push(R);var V;x&1?(A=c.andln(7)+w&7,(A===3||A===5)&&T===2?V=-x:V=x):V=0,f[1].push(V),2*d===R+1&&(d=1-d),2*w===V+1&&(w=1-w),a.iushrn(1),c.iushrn(1)}return f}r.getJSF=i;function s(a,c,f){var d="_"+c;a.prototype[c]=function(){return this[d]!==void 0?this[d]:this[d]=f.call(this)}}r.cachedProperty=s;function o(a){return typeof a=="string"?r.toArray(a,"hex"):a}r.parseBytes=o;function u(a){return new Se(a,"hex","le")}r.intFromLE=u}),jm=pn.getNAF,Hne=pn.getJSF,ty=pn.assert;function Vo(t,e){this.type=t,this.p=new Se(e.p,16),this.red=e.prime?Se.red(e.prime):Se.mont(this.p),this.zero=new Se(0).toRed(this.red),this.one=new Se(1).toRed(this.red),this.two=new Se(2).toRed(this.red),this.n=e.n&&new Se(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var nu=Vo;Vo.prototype.point=function(){throw new Error("Not implemented")},Vo.prototype.validate=function(){throw new Error("Not implemented")},Vo.prototype._fixedNafMul=function(t,e){ty(t.precomputed);var r=t._getDoubles(),n=jm(e,1,this._bitLength),i=(1<=o;a--)u=(u<<1)+n[a];s.push(u)}for(var c=this.jpoint(null,null,null),f=this.jpoint(null,null,null),d=i;d>0;d--){for(o=0;o=0;u--){for(var a=0;u>=0&&s[u]===0;u--)a++;if(u>=0&&a++,o=o.dblp(a),u<0)break;var c=s[u];ty(c!==0),t.type==="affine"?c>0?o=o.mixedAdd(i[c-1>>1]):o=o.mixedAdd(i[-c-1>>1].neg()):c>0?o=o.add(i[c-1>>1]):o=o.add(i[-c-1>>1].neg())}return t.type==="affine"?o.toP():o},Vo.prototype._wnafMulAdd=function(t,e,r,n,i){var s=this._wnafT1,o=this._wnafT2,u=this._wnafT3,a=0,c,f,d;for(c=0;c=1;c-=2){var A=c-1,T=c;if(s[A]!==1||s[T]!==1){u[A]=jm(r[A],s[A],this._bitLength),u[T]=jm(r[T],s[T],this._bitLength),a=Math.max(u[A].length,a),a=Math.max(u[T].length,a);continue}var x=[e[A],null,null,e[T]];e[A].y.cmp(e[T].y)===0?(x[1]=e[A].add(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg())):e[A].y.cmp(e[T].y.redNeg())===0?(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].add(e[T].neg())):(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg()));var R=[-3,-1,-5,-7,0,7,5,1,3],V=Hne(r[A],r[T]);for(a=Math.max(V[0].length,a),u[A]=new Array(a),u[T]=new Array(a),f=0;f=0;c--){for(var H=0;c>=0;){var q=!0;for(f=0;f=0&&H++,L=L.dblp(H),c<0)break;for(f=0;f0?d=o[f][v-1>>1]:v<0&&(d=o[f][-v-1>>1].neg()),d.type==="affine"?L=L.mixedAdd(d):L=L.add(d))}}for(c=0;c=Math.ceil((t.bitLength()+1)/e.step):!1},Wn.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(w=a,A=c),f.negative&&(f=f.neg(),d=d.neg()),w.negative&&(w=w.neg(),A=A.neg()),[{a:f,b:d},{a:w,b:A}]},Yn.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),u=s.mul(n.a),a=i.mul(r.b),c=s.mul(n.b),f=t.sub(o).sub(u),d=a.add(c).neg();return{k1:f,k2:d}},Yn.prototype.pointFromX=function(t,e){t=new Se(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(n.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},Yn.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return r.redSqr().redISub(i).cmpn(0)===0},Yn.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Ar.prototype.isInfinity=function(){return this.inf},Ar.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Ar.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Ar.prototype.getX=function(){return this.x.fromRed()},Ar.prototype.getY=function(){return this.y.fromRed()},Ar.prototype.mul=function(t){return t=new Se(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Ar.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Ar.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Ar.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Ar.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(i){return i.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Ar.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function _r(t,e,r,n){nu.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&n===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Se(0)):(this.x=new Se(e,16),this.y=new Se(r,16),this.z=new Se(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}QT(_r,nu.BasePoint),Yn.prototype.jpoint=function(t,e,r){return new _r(this,t,e,r)},_r.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},_r.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_r.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=s.redSub(o);if(u.cmpn(0)===0)return a.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var c=u.redSqr(),f=c.redMul(u),d=n.redMul(c),w=a.redSqr().redIAdd(f).redISub(d).redISub(d),A=a.redMul(d.redISub(w)).redISub(s.redMul(f)),T=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(w,A,T)},_r.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),u=i.redSub(s);if(o.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),c=a.redMul(o),f=r.redMul(a),d=u.redSqr().redIAdd(c).redISub(f).redISub(f),w=u.redMul(f.redISub(d)).redISub(i.redMul(c)),A=this.z.redMul(o);return this.curve.jpoint(d,w,A)},_r.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),this.x.cmp(r)===0)return!0}},_r.prototype.inspect=function(){return this.isInfinity()?"":""},_r.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var Km=fl(function(t,e){var r=e;r.base=nu,r.short=jne,r.mont=null,r.edwards=null}),Wm=fl(function(t,e){var r=e,n=pn.assert;function i(u){u.type==="short"?this.curve=new Km.short(u):u.type==="edwards"?this.curve=new Km.edwards(u):this.curve=new Km.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=i;function s(u,a){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var c=new i(a);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:c}),c}})}s("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:os.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:os.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:os.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:os.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),s("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:os.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var o;try{o=null.crash()}catch{o=void 0}s("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:os.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",o]})});function ko(t){if(!(this instanceof ko))return new ko(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Ti.toArray(t.entropy,t.entropyEnc||"hex"),r=Ti.toArray(t.nonce,t.nonceEnc||"hex"),n=Ti.toArray(t.pers,t.persEnc||"hex");zT(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var LM=ko;ko.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},ko.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(n=r,r=e,e=null),r&&(r=Ti.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var zne=pn.assert;function sy(t,e){if(t instanceof sy)return t;this._importDER(t,e)||(zne(t.r&&t.s,"Signature without r or s"),this.r=new Se(t.r,16),this.s=new Se(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var zm=sy;function Qne(){this.place=0}function ET(t,e){var r=t[e.place++];if(!(r&128))return r;var n=r&15;if(n===0||n>4)return!1;for(var i=0,s=0,o=e.place;s>>=0;return i<=127?!1:(e.place=o,i)}function FM(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}sy.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=FM(e),r=FM(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var n=[2];bT(n,e.length),n=n.concat(e),n.push(2),bT(n,r.length);var i=n.concat(r),s=[48];return bT(s,i.length),s=s.concat(i),pn.encode(s,t)};var Kne=function(){throw new Error("unsupported")},W4=pn.assert;function $n(t){if(!(this instanceof $n))return new $n(t);typeof t=="string"&&(W4(Object.prototype.hasOwnProperty.call(Wm,t),"Unknown curve "+t),t=Wm[t]),t instanceof Wm.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Wne=$n;$n.prototype.keyPair=function(t){return new AT(this,t)},$n.prototype.keyFromPrivate=function(t,e){return AT.fromPrivate(this,t,e)},$n.prototype.keyFromPublic=function(t,e){return AT.fromPublic(this,t,e)},$n.prototype.genKeyPair=function(t){t||(t={});for(var e=new LM({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Kne(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Se(2));;){var i=new Se(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},$n.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},$n.prototype.sign=function(t,e,r,n){typeof r=="object"&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Se(t,16));for(var i=this.n.byteLength(),s=e.getPrivate().toArray("be",i),o=t.toArray("be",i),u=new LM({hash:this.hash,entropy:s,nonce:o,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Se(1)),c=0;;c++){var f=n.k?n.k(c):new Se(u.generate(this.n.byteLength()));if(f=this._truncateToN(f,!0),!(f.cmpn(1)<=0||f.cmp(a)>=0)){var d=this.g.mul(f);if(!d.isInfinity()){var w=d.getX(),A=w.umod(this.n);if(A.cmpn(0)!==0){var T=f.invm(this.n).mul(A.mul(e.getPrivate()).iadd(t));if(T=T.umod(this.n),T.cmpn(0)!==0){var x=(d.getY().isOdd()?1:0)|(w.cmp(A)!==0?2:0);return n.canonical&&T.cmp(this.nh)>0&&(T=this.n.sub(T),x^=1),new zm({r:A,s:T,recoveryParam:x})}}}}}},$n.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Se(t,16)),r=this.keyFromPublic(r,n),e=new zm(e,"hex");var i=e.r,s=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o=s.invm(this.n),u=o.mul(t).umod(this.n),a=o.mul(i).umod(this.n),c;return this.curve._maxwellTrick?(c=this.g.jmulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.eqXToP(i)):(c=this.g.mulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.getX().umod(this.n).cmp(i)===0)},$n.prototype.recoverPubKey=function(t,e,r,n){W4((3&r)===r,"The recovery param is more than two bits"),e=new zm(e,n);var i=this.n,s=new Se(t),o=e.r,u=e.s,a=r&1,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");c?o=this.curve.pointFromX(o.add(this.curve.n),a):o=this.curve.pointFromX(o,a);var f=e.r.invm(i),d=i.sub(s).mul(f).umod(i),w=u.mul(f).umod(i);return this.g.mulAdd(d,o,w)},$n.prototype.getKeyRecoveryParam=function(t,e,r,n){if(e=new zm(e,n),e.recoveryParam!==null)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch{continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var $ne=fl(function(t,e){var r=e;r.version="6.5.4",r.utils=pn,r.rand=function(){throw new Error("unsupported")},r.curve=Km,r.curves=Wm,r.ec=Wne,r.eddsa=null}),Yne=$ne.ec,Jne="signing-key/5.7.0",OT=new kt(Jne),ST=null;function ls(){return ST||(ST=new Yne("secp256k1")),ST}var DT=class{constructor(e){Rh(this,"curve","secp256k1"),Rh(this,"privateKey",kr(e)),Pte(this.privateKey)!==32&&OT.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");let r=ls().keyFromPrivate(Qt(this.privateKey));Rh(this,"publicKey","0x"+r.getPublic(!1,"hex")),Rh(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),Rh(this,"_isSigningKey",!0)}_addPoint(e){let r=ls().keyFromPublic(Qt(this.publicKey)),n=ls().keyFromPublic(Qt(e));return"0x"+r.pub.add(n.pub).encodeCompressed("hex")}signDigest(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=Qt(e);n.length!==32&&OT.throwArgumentError("bad digest length","digest",e);let i=r.sign(n,{canonical:!0});return y4({recoveryParam:i.recoveryParam,r:fs("0x"+i.r.toString(16),32),s:fs("0x"+i.s.toString(16),32)})}computeSharedSecret(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=ls().keyFromPublic(Qt($4(e)));return fs("0x"+r.derive(n.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}};function Xne(t,e){let r=y4(e),n={r:Qt(r.r),s:Qt(r.s)};return"0x"+ls().recoverPubKey(Qt(t),n,r.recoveryParam).encode("hex",!1)}function $4(t,e){let r=Qt(t);if(r.length===32){let n=new DT(r);return e?"0x"+ls().keyFromPrivate(r).getPublic(!0,"hex"):n.publicKey}else{if(r.length===33)return e?kr(r):"0x"+ls().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+ls().keyFromPublic(r).getPublic(!0,"hex"):kr(r)}return OT.throwArgumentError("invalid public or private key","key","[REDACTED]")}var Zne="transactions/5.7.0";new kt(Zne);var UM;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(UM||(UM={}));function eie(t){let e=$4(t);return lre(IM(HT(IM(e,1)),12))}function tie(t,e){return eie(Xne(Qt(t),e))}var rie="https://rpc.walletconnect.com/v1";async function Y4(t,e,r,n,i,s){switch(r.t){case"eip191":return J4(t,e,r.s);case"eip1271":return await X4(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function J4(t,e,r){return tie(N4(e),r).toLowerCase()===t.toLowerCase()}async function X4(t,e,r,n,i,s){try{let o="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",c=r.substring(2),f=N4(e).substring(2),d=o+f+u+a+c,w=await fetch(`${s||rie}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:nie(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:A}=await w.json();return A?A.slice(0,o.length).toLowerCase()===o.toLowerCase():!1}catch(o){return console.error("isValidEip1271Signature: ",o),!1}}function nie(){return Date.now()+Math.floor(Math.random()*1e3)}var iie=Object.defineProperty,sie=Object.defineProperties,oie=Object.getOwnPropertyDescriptors,qM=Object.getOwnPropertySymbols,aie=Object.prototype.hasOwnProperty,uie=Object.prototype.propertyIsEnumerable,VM=(t,e,r)=>e in t?iie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KT=(t,e)=>{for(var r in e||(e={}))aie.call(e,r)&&VM(t,r,e[r]);if(qM)for(var r of qM(e))uie.call(e,r)&&VM(t,r,e[r]);return t},Z4=(t,e)=>sie(t,oie(e)),cie="did:pkh:",oy=t=>t?.split(":"),WT=t=>{let e=t&&oy(t);if(e)return t.includes(cie)?e[3]:e[1]},lie=t=>{let e=t&&oy(t);if(e)return e[2]+":"+e[3]},$T=t=>{let e=t&&oy(t);if(e)return e.pop()};async function fie(t){let{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=e5(i,i.iss),o=$T(i.iss);return await Y4(o,s,n,WT(i.iss),r)}var e5=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=$T(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0,s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,u=`Chain ID: ${WT(e)}`,a=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources?`Resources:${t.resources.map(w=>` -- ${w}`).join("")}`:void 0,d=uy(t.resources);if(d){let w=jo(d);i=XT(i,w)}return[r,n,"",i,"",s,o,u,a,c,f].filter(w=>w!=null).join(` -`)};function hie(t,e,r){return r.includes("did:pkh:")||(r=`did:pkh:${r}`),{h:{t:"caip122"},p:{iss:r,domain:t.domain,aud:t.aud,version:t.version,nonce:t.nonce,iat:t.iat,statement:t.statement,requestId:t.requestId,resources:t.resources,nbf:t.nbf,exp:t.exp},s:e}}function die(t){var e;let{authPayload:r,chains:n,methods:i}=t,s=r.statement||"";if(!(n!=null&&n.length))return r;let o=r.chains,u=TT(o,n);if(!(u!=null&&u.length))throw new Error("No supported chains");let a=t5(r.resources);if(!a)return r;ps(a);let c=r5(a,"eip155"),f=r?.resources||[];if(c!=null&&c.length){let d=n5(c),w=TT(d,i);if(!(w!=null&&w.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(d)}, supported: ${JSON.stringify(i)}`);let A=YT("request",w,{chains:u}),T=a5(a,"eip155",A);f=((e=r?.resources)==null?void 0:e.slice(0,-1))||[],f.push(ay(T))}return Z4(KT({},r),{statement:c5(s,uy(f)),chains:u,resources:r!=null&&r.resources||f.length>0?f:void 0})}function t5(t){let e=uy(t);if(e&&JT(e))return jo(e)}function gie(t,e){var r;return(r=t?.att)==null?void 0:r.hasOwnProperty(e)}function r5(t,e){var r,n;return(r=t?.att)!=null&&r[e]?Object.keys((n=t?.att)==null?void 0:n[e]):[]}function pie(t){return t?.map(e=>Object.keys(e))||[]}function n5(t){return t?.map(e=>{var r;return(r=e.split("/"))==null?void 0:r[1]})||[]}function i5(t){return p.Buffer.from(JSON.stringify(t)).toString("base64")}function s5(t){return JSON.parse(p.Buffer.from(t,"base64").toString("utf-8"))}function ps(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");let e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{let n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{let s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function o5(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:YT(e,r,n)}}}function a5(t,e,r){var n;return t.att[e]=KT({},r),((n=Object.keys(t.att))==null?void 0:n.sort((i,s)=>i.localeCompare(s))).reduce((i,s)=>(i.att[s]=t.att[s],i),{att:{}})}function YT(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));let n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function ay(t){return ps(t),`urn:recap:${i5(t).replace(/=/g,"")}`}function jo(t){let e=s5(t.replace("urn:recap:",""));return ps(e),e}function mie(t,e,r){let n=o5(t,e,r);return ay(n)}function JT(t){return t&&t.includes("urn:recap:")}function yie(t,e){let r=jo(t),n=jo(e),i=u5(r,n);return ay(i)}function u5(t,e){ps(t),ps(e);let r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((u,a)=>u.localeCompare(a)).forEach(u=>{var a,c;n.att[i]=Z4(KT({},n.att[i]),{[u]:((a=t.att[i])==null?void 0:a[u])||((c=e.att[i])==null?void 0:c[u])})})}),n}function XT(t="",e){ps(e);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;let n=[],i=0;Object.keys(e.att).forEach(u=>{let a=Object.keys(e.att[u]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));a.sort((d,w)=>d.action.localeCompare(w.action));let c={};a.forEach(d=>{c[d.ability]||(c[d.ability]=[]),c[d.ability].push(d.action)});let f=Object.keys(c).map(d=>(i++,`(${i}) '${d}': '${c[d].join("', '")}' for '${u}'.`));n.push(f.join(", ").replace(".,","."))});let s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function wie(t){var e;let r=jo(t);ps(r);let n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function vie(t){let e=jo(t);ps(e);let r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function c5(t,e){if(!e)return t;let r=jo(e);return ps(r),XT(t,r)}function uy(t){if(!t)return;let e=t?.[t.length-1];return JT(e)?e:void 0}var ZT="base10",jr="base16",ry="base64pad",cy="utf8",e_=0,hl=1,Aie=0,kM=1,PT=12,t_=32;function Eie(){let t=JM.generateKeyPair();return{privateKey:Vt.toString(t.secretKey,jr),publicKey:Vt.toString(t.publicKey,jr)}}function bie(){let t=$M.randomBytes(t_);return Vt.toString(t,jr)}function Sie(t,e){let r=JM.sharedKey(Vt.fromString(t,jr),Vt.fromString(e,jr),!0),n=new Gee.HKDF(LT.SHA256,r).expand(t_);return Vt.toString(n,jr)}function Iie(t){let e=LT.hash(Vt.fromString(t,jr));return Vt.toString(e,jr)}function Tie(t){let e=LT.hash(Vt.fromString(t,cy));return Vt.toString(e,jr)}function l5(t){return Vt.fromString(`${t}`,ZT)}function jh(t){return Number(Vt.toString(t,ZT))}function _ie(t){let e=l5(typeof t.type<"u"?t.type:e_);if(jh(e)===hl&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?Vt.fromString(t.senderPublicKey,jr):void 0,n=typeof t.iv<"u"?Vt.fromString(t.iv,jr):$M.randomBytes(PT),i=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)).seal(n,Vt.fromString(t.message,cy));return f5({type:e,sealed:i,iv:n,senderPublicKey:r})}function Cie(t){let e=new WM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)),{sealed:r,iv:n}=r_(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Vt.toString(i,cy)}function f5(t){if(jh(t.type)===hl){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Vt.toString(Vt.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),ry)}return Vt.toString(Vt.concat([t.type,t.iv,t.sealed]),ry)}function r_(t){let e=Vt.fromString(t,ry),r=e.slice(Aie,kM),n=kM;if(jh(r)===hl){let u=n+t_,a=u+PT,c=e.slice(n,u),f=e.slice(u,a),d=e.slice(a);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+PT,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Nie(t,e){let r=r_(t);return h5({type:jh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Vt.toString(r.senderPublicKey,jr):void 0,receiverPublicKey:e?.receiverPublicKey})}function h5(t){let e=t?.type||e_;if(e===hl){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function xie(t){return t.type===hl&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var d5="irn";function Oie(t){return t?.relay||{protocol:d5}}function Die(t){let e=zee.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Pie=Object.defineProperty,Rie=Object.defineProperties,Bie=Object.getOwnPropertyDescriptors,HM=Object.getOwnPropertySymbols,Mie=Object.prototype.hasOwnProperty,Lie=Object.prototype.propertyIsEnumerable,GM=(t,e,r)=>e in t?Pie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jM=(t,e)=>{for(var r in e||(e={}))Mie.call(e,r)&&GM(t,r,e[r]);if(HM)for(var r of HM(e))Lie.call(e,r)&&GM(t,r,e[r]);return t},Fie=(t,e)=>Rie(t,Bie(e));function g5(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Uie(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=$m.parse(s),u=typeof o.methods=="string"?o.methods.split(","):void 0;return{protocol:n,topic:p5(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:g5(o),methods:u,expiryTimestamp:o.expiryTimestamp?parseInt(o.expiryTimestamp,10):void 0}}function p5(t){return t.startsWith("//")?t.substring(2):t}function m5(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function qie(t){return`${t.protocol}:${t.topic}@${t.version}?`+$m.stringify(jM(Fie(jM({symKey:t.symKey},m5(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}var Vie=Object.defineProperty,kie=Object.defineProperties,Hie=Object.getOwnPropertyDescriptors,zM=Object.getOwnPropertySymbols,Gie=Object.prototype.hasOwnProperty,jie=Object.prototype.propertyIsEnumerable,QM=(t,e,r)=>e in t?Vie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zie=(t,e)=>{for(var r in e||(e={}))Gie.call(e,r)&&QM(t,r,e[r]);if(zM)for(var r of zM(e))jie.call(e,r)&&QM(t,r,e[r]);return t},Qie=(t,e)=>kie(t,Hie(e));function iu(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function y5(t){let e=[];return Object.values(t).forEach(r=>{e.push(...iu(r.accounts))}),e}function w5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.methods)}),r}function v5(t,e){let r=[];return Object.values(t).forEach(n=>{iu(n.accounts).includes(e)&&r.push(...n.events)}),r}function Kie(t,e){let r=O5(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function Wie(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=RT(e),s=RT(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,w=n[c].events,A=n[c].accounts;f.forEach(T=>{if(!A.some(x=>x.includes(T)))throw new Error(`No accounts provided for chain ${T} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:w,accounts:A}});let u=P5(e,o,"approve()");if(u)throw new Error(u.message);let a={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.chains)==null?void 0:R.includes(T)}),d=n[c].methods.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.methods)==null?void 0:R.includes(T)}),w=n[c].events.filter(T=>{var x,R;return(R=(x=i[c])==null?void 0:x.events)==null?void 0:R.includes(T)}),A=f.map(T=>n[c].accounts.filter(x=>x.includes(`${T}:`))).flat();a[c]={chains:f,methods:d,events:w,accounts:A}}),Object.keys(s).forEach(c=>{var f,d,w,A,T,x;if(!n[c])return;let R=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(L=>n[c].chains.includes(L)),V=n[c].methods.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.methods)==null?void 0:H.includes(L)}),U=n[c].events.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.events)==null?void 0:H.includes(L)}),Q=R?.map(L=>n[c].accounts.filter(k=>k.includes(`${L}:`))).flat();a[c]={chains:Js((w=a[c])==null?void 0:w.chains,R),methods:Js((A=a[c])==null?void 0:A.methods,V),events:Js((T=a[c])==null?void 0:T.events,U),accounts:Js((x=a[c])==null?void 0:x.accounts,Q)}}),a)}function n_(t){return t.includes(":")}function A5(t){return n_(t)?t.split(":")[0]:t}function RT(t){var e,r,n;let i={};if(!ly(t))return i;for(let[s,o]of Object.entries(t)){let u=n_(s)?[s]:o.chains,a=o.methods||[],c=o.events||[],f=A5(s);i[f]=Qie(zie({},i[f]),{chains:Js(u,(e=i[f])==null?void 0:e.chains),methods:Js(a,(r=i[f])==null?void 0:r.methods),events:Js(c,(n=i[f])==null?void 0:n.events)})}return i}function E5(t){let e={};return t?.forEach(r=>{let[n,i]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[]}),e[n].accounts.push(r),e[n].chains.push(`${n}:${i}`)}),e}function $ie(t,e){e=e.map(n=>n.replace("did:pkh:",""));let r=E5(e);for(let[n,i]of Object.entries(r))i.methods?i.methods=Js(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}var b5={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},S5={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ys(t,e){let{message:r,code:n}=S5[t];return{message:e?`${r} ${e}`:r,code:n}}function tu(t,e){let{message:r,code:n}=b5[t];return{message:e?`${r} ${e}`:r,code:n}}function zh(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function ly(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Go(t){return typeof t>"u"}function mn(t,e){return e&&Go(t)?!0:typeof t=="string"&&!!t.trim().length}function fy(t,e){return e&&Go(t)?!0:typeof t=="number"&&!isNaN(t)}function Yie(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Ho(i,n)?(n.forEach(o=>{let{accounts:u,methods:a,events:c}=t.namespaces[o],f=iu(u),d=r[o];(!Ho(iy(o,d),f)||!Ho(d.methods,a)||!Ho(d.events,c))&&(s=!1)}),s):!1}function kh(t){return mn(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function I5(t){if(mn(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&kh(r)}}return!1}function Jie(t){if(mn(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function Xie(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function Zie(t){return t?.topic}function ese(t,e){let r=null;return mn(t?.publicKey,!1)||(r=Ys("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function BT(t){let e=!0;return zh(t)?t.length&&(e=t.every(r=>mn(r,!1))):e=!1,e}function T5(t,e,r){let n=null;return zh(e)&&e.length?e.forEach(i=>{n||kh(i)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):kh(t)||(n=tu("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function _5(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=T5(i,iy(i,s),`${e} ${r}`);o&&(n=o)}),n}function C5(t,e){let r=null;return zh(t)?t.forEach(n=>{r||I5(n)||(r=tu("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=tu("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function N5(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=C5(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function x5(t,e){let r=null;return BT(t?.methods)?BT(t?.events)||(r=tu("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=tu("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function i_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=x5(n,`${e}, namespace`);i&&(r=i)}),r}function tse(t,e,r){let n=null;if(t&&ly(t)){let i=i_(t,e);i&&(n=i);let s=_5(t,e,r);s&&(n=s)}else n=Ys("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function O5(t,e){let r=null;if(t&&ly(t)){let n=i_(t,e);n&&(r=n);let i=N5(t,e);i&&(r=i)}else r=Ys("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function D5(t){return mn(t.protocol,!0)}function rse(t,e){let r=!1;return e&&!t?r=!0:t&&zh(t)&&t.length&&t.forEach(n=>{r=D5(n)}),r}function nse(t){return typeof t=="number"}function ise(t){return typeof t<"u"&&typeof t!==null}function sse(t){return!(!t||typeof t!="object"||!t.code||!fy(t.code,!1)||!t.message||!mn(t.message,!1))}function ose(t){return!(Go(t)||!mn(t.method,!1))}function ase(t){return!(Go(t)||Go(t.result)&&Go(t.error)||!fy(t.id,!1)||!mn(t.jsonrpc,!1))}function use(t){return!(Go(t)||!mn(t.name,!1))}function cse(t,e){return!(!kh(e)||!y5(t).includes(e))}function lse(t,e,r){return mn(r,!1)?w5(t,e).includes(r):!1}function fse(t,e,r){return mn(r,!1)?v5(t,e).includes(r):!1}function P5(t,e,r){let n=null,i=hse(t),s=dse(e),o=Object.keys(i),u=Object.keys(s),a=KM(Object.keys(t)),c=KM(Object.keys(e)),f=a.filter(d=>!c.includes(d));return f.length&&(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. +`});var $R=fe(()=>{h();WR();Sm();Lo();DI();Th()});var BI,Cbe,YR=fe(()=>{h();SR();IR();TR();_R();CR();bI();NR();TI();xR();DR();VR();GR();jR();zR();$R();BI={...mI,...yI,...wI,...vI,...AI,...EI,...SI,...II,..._I,...CI},Cbe={...PI,...RI}});function XR(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var JR,MI,UZ,Cm,LI=fe(()=>{h();YR();Am();JR=XR("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),MI=XR("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=jc(t.length);for(let r=0;r{h();LI()});function ns(t,e="utf8"){let r=Cm[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var UI=fe(()=>{h();LI();Eh()});function Ch(t){return Ro(ks(ns(t,Hc),dm))}function Nh(t){return ks(ns(Ai(t),dm),Hc)}function qI(t){let e=ns(wm,Gc),r=ym+ks(Em([e,t]),Gc);return[pm,mm,r].join(gm)}function VI(t){let[e,r,n]=t.split(gm);if(e!==pm||r!==mm)throw new Error('Issuer must be a DID with method "key"');if(n.slice(0,1)!==ym)throw new Error("Issuer must be a key in mulicodec format");let s=ns(n.slice(1),Gc);if(ks(s.slice(0,2),Gc)!==wm)throw new Error('Issuer must be a public key with type "Ed25519"');let u=s.slice(2);if(u.length!==32)throw new Error("Issuer must be a public key with length 32 bytes");return u}function ZR(t){return ks(t,Hc)}function eB(t){return ns(t,Hc)}function kI(t){return ns([Nh(t.header),Nh(t.payload)].join($a),Ah)}function qZ(t){let e=ks(t,Ah).split($a),r=Ch(e[0]),n=Ch(e[1]);return{header:r,payload:n}}function HI(t){return[Nh(t.header),Nh(t.payload),ZR(t.signature)].join($a)}function GI(t){let e=t.split($a),r=Ch(e[0]),n=Ch(e[1]),i=eB(e[2]),s=ns(e.slice(0,2).join($a),Ah);return{header:r,payload:n,signature:i,data:s}}var jI=fe(()=>{h();fI();FI();UI();xc();vm()});function VZ(t=(0,tB.randomBytes)(32)){return Yc.generateKeyPairFromSeed(t)}async function kZ(t,e,r,n,i=(0,rB.fromMiliseconds)(Date.now())){let s={alg:fm,typ:hm},o=qI(n.publicKey),u=i+r,a={iss:o,sub:t,aud:e,iat:i,exp:u},c=kI({header:s,payload:a}),f=Yc.sign(n.secretKey,c);return HI({header:s,payload:a,signature:f})}async function HZ(t){let{header:e,payload:r,data:n,signature:i}=GI(t);if(e.alg!==fm||e.typ!==hm)throw new Error("JWT must use EdDSA algorithm");let s=VI(r.iss);return Yc.verify(s,n,i)}var Yc,tB,rB,nB=fe(()=>{h();Yc=pe(dR()),tB=pe(yh()),rB=pe(za());vm();jI()});var iB=fe(()=>{h()});var sB={};Bt(sB,{DATA_ENCODING:()=>Ah,DID_DELIMITER:()=>gm,DID_METHOD:()=>mm,DID_PREFIX:()=>pm,JSON_ENCODING:()=>dm,JWT_DELIMITER:()=>$a,JWT_ENCODING:()=>Hc,JWT_IRIDIUM_ALG:()=>fm,JWT_IRIDIUM_TYP:()=>hm,KEY_PAIR_SEED_LENGTH:()=>pR,MULTICODEC_ED25519_BASE:()=>ym,MULTICODEC_ED25519_ENCODING:()=>Gc,MULTICODEC_ED25519_HEADER:()=>wm,MULTICODEC_ED25519_LENGTH:()=>gR,decodeData:()=>qZ,decodeIss:()=>VI,decodeJSON:()=>Ch,decodeJWT:()=>GI,decodeSig:()=>eB,encodeData:()=>kI,encodeIss:()=>qI,encodeJSON:()=>Nh,encodeJWT:()=>HI,encodeSig:()=>ZR,generateKeyPair:()=>VZ,signJWT:()=>kZ,verifyJWT:()=>HZ});var oB=fe(()=>{h();nB();vm();iB();jI()});var wB=D(qt=>{"use strict";h();var aB=qt&&qt.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new gB:typeof navigator<"u"?zI(navigator.userAgent):yB()}qt.detect=QZ;function pB(t){return t!==""&&zZ.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function KZ(t){var e=pB(t);return e?e[0]:null}qt.browserName=KZ;function zI(t){var e=pB(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new dB;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length{"use strict";h();Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getLocalStorage=Ot.getLocalStorageOrThrow=Ot.getCrypto=Ot.getCryptoOrThrow=Ot.getLocation=Ot.getLocationOrThrow=Ot.getNavigator=Ot.getNavigatorOrThrow=Ot.getDocument=Ot.getDocumentOrThrow=Ot.getFromWindowOrThrow=Ot.getFromWindow=void 0;function Ja(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}Ot.getFromWindow=Ja;function Jc(t){let e=Ja(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}Ot.getFromWindowOrThrow=Jc;function $Z(){return Jc("document")}Ot.getDocumentOrThrow=$Z;function YZ(){return Ja("document")}Ot.getDocument=YZ;function JZ(){return Jc("navigator")}Ot.getNavigatorOrThrow=JZ;function XZ(){return Ja("navigator")}Ot.getNavigator=XZ;function ZZ(){return Jc("location")}Ot.getLocationOrThrow=ZZ;function eee(){return Ja("location")}Ot.getLocation=eee;function tee(){return Jc("crypto")}Ot.getCryptoOrThrow=tee;function ree(){return Ja("crypto")}Ot.getCrypto=ree;function nee(){return Jc("localStorage")}Ot.getLocalStorageOrThrow=nee;function iee(){return Ja("localStorage")}Ot.getLocalStorage=iee});var AB=D(Nm=>{"use strict";h();Object.defineProperty(Nm,"__esModule",{value:!0});Nm.getWindowMetadata=void 0;var vB=QI();function see(){let t,e;try{t=vB.getDocumentOrThrow(),e=vB.getLocationOrThrow()}catch{return null}function r(){let d=t.getElementsByTagName("link"),w=[];for(let A=0;A-1){let B=T.getAttribute("href");if(B)if(B.toLowerCase().indexOf("https:")===-1&&B.toLowerCase().indexOf("http:")===-1&&B.indexOf("//")!==0){let V=e.protocol+"//"+e.host;if(B.indexOf("/")===0)V+=B;else{let U=e.pathname.split("/");U.pop();let Q=U.join("/");V+=Q+"/"+B}w.push(V)}else if(B.indexOf("//")===0){let V=e.protocol+B;w.push(V)}else w.push(B)}}return w}function n(...d){let w=t.getElementsByTagName("meta");for(let A=0;AT.getAttribute(B)).filter(B=>B?d.includes(B):!1);if(x.length&&x){let B=T.getAttribute("content");if(B)return B}}return""}function i(){let d=n("name","og:site_name","og:title","twitter:title");return d||(d=t.title),d}function s(){return n("description","og:description","twitter:description","keywords")}let o=i(),u=s(),a=e.origin,c=r();return{description:u,url:a,icons:c,name:o}}Nm.getWindowMetadata=see});var bB=D((lSe,EB)=>{"use strict";h();EB.exports=t=>encodeURIComponent(t).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var CB=D((hSe,_B)=>{"use strict";h();var TB="%[a-f0-9]{2}",SB=new RegExp("("+TB+")|([^%]+?)","gi"),IB=new RegExp("("+TB+")+","gi");function KI(t,e){try{return[decodeURIComponent(t.join(""))]}catch{}if(t.length===1)return t;e=e||1;var r=t.slice(0,e),n=t.slice(e);return Array.prototype.concat.call([],KI(r),KI(n))}function oee(t){try{return decodeURIComponent(t)}catch{for(var e=t.match(SB)||[],r=1;r{"use strict";h();NB.exports=(t,e)=>{if(!(typeof t=="string"&&typeof e=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(e==="")return[t];let r=t.indexOf(e);return r===-1?[t]:[t.slice(0,r),t.slice(r+e.length)]}});var DB=D((mSe,OB)=>{"use strict";h();OB.exports=function(t,e){for(var r={},n=Object.keys(t),i=Array.isArray(e),s=0;s{"use strict";h();var uee=bB(),cee=CB(),RB=xB(),lee=DB(),fee=t=>t==null,WI=Symbol("encodeFragmentIdentifier");function hee(t){switch(t.arrayFormat){case"index":return e=>(r,n)=>{let i=r.length;return n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[",i,"]"].join("")]:[...r,[Zt(e,t),"[",Zt(i,t),"]=",Zt(n,t)].join("")]};case"bracket":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),"[]"].join("")]:[...r,[Zt(e,t),"[]=",Zt(n,t)].join("")];case"colon-list-separator":return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,[Zt(e,t),":list="].join("")]:[...r,[Zt(e,t),":list=",Zt(n,t)].join("")];case"comma":case"separator":case"bracket-separator":{let e=t.arrayFormat==="bracket-separator"?"[]=":"=";return r=>(n,i)=>i===void 0||t.skipNull&&i===null||t.skipEmptyString&&i===""?n:(i=i===null?"":i,n.length===0?[[Zt(r,t),e,Zt(i,t)].join("")]:[[n,Zt(i,t)].join(t.arrayFormatSeparator)])}default:return e=>(r,n)=>n===void 0||t.skipNull&&n===null||t.skipEmptyString&&n===""?r:n===null?[...r,Zt(e,t)]:[...r,[Zt(e,t),"=",Zt(n,t)].join("")]}}function dee(t){let e;switch(t.arrayFormat){case"index":return(r,n,i)=>{if(e=/\[(\d*)\]$/.exec(r),r=r.replace(/\[\d*\]$/,""),!e){i[r]=n;return}i[r]===void 0&&(i[r]={}),i[r][e[1]]=n};case"bracket":return(r,n,i)=>{if(e=/(\[\])$/.exec(r),r=r.replace(/\[\]$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"colon-list-separator":return(r,n,i)=>{if(e=/(:list)$/.exec(r),r=r.replace(/:list$/,""),!e){i[r]=n;return}if(i[r]===void 0){i[r]=[n];return}i[r]=[].concat(i[r],n)};case"comma":case"separator":return(r,n,i)=>{let s=typeof n=="string"&&n.includes(t.arrayFormatSeparator),o=typeof n=="string"&&!s&&Hs(n,t).includes(t.arrayFormatSeparator);n=o?Hs(n,t):n;let u=s||o?n.split(t.arrayFormatSeparator).map(a=>Hs(a,t)):n===null?n:Hs(n,t);i[r]=u};case"bracket-separator":return(r,n,i)=>{let s=/(\[\])$/.test(r);if(r=r.replace(/\[\]$/,""),!s){i[r]=n&&Hs(n,t);return}let o=n===null?[]:n.split(t.arrayFormatSeparator).map(u=>Hs(u,t));if(i[r]===void 0){i[r]=o;return}i[r]=[].concat(i[r],o)};default:return(r,n,i)=>{if(i[r]===void 0){i[r]=n;return}i[r]=[].concat(i[r],n)}}}function BB(t){if(typeof t!="string"||t.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function Zt(t,e){return e.encode?e.strict?uee(t):encodeURIComponent(t):t}function Hs(t,e){return e.decode?cee(t):t}function MB(t){return Array.isArray(t)?t.sort():typeof t=="object"?MB(Object.keys(t)).sort((e,r)=>Number(e)-Number(r)).map(e=>t[e]):t}function LB(t){let e=t.indexOf("#");return e!==-1&&(t=t.slice(0,e)),t}function gee(t){let e="",r=t.indexOf("#");return r!==-1&&(e=t.slice(r)),e}function FB(t){t=LB(t);let e=t.indexOf("?");return e===-1?"":t.slice(e+1)}function PB(t,e){return e.parseNumbers&&!Number.isNaN(Number(t))&&typeof t=="string"&&t.trim()!==""?t=Number(t):e.parseBooleans&&t!==null&&(t.toLowerCase()==="true"||t.toLowerCase()==="false")&&(t=t.toLowerCase()==="true"),t}function UB(t,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),BB(e.arrayFormatSeparator);let r=dee(e),n=Object.create(null);if(typeof t!="string"||(t=t.trim().replace(/^[?#&]/,""),!t))return n;for(let i of t.split("&")){if(i==="")continue;let[s,o]=RB(e.decode?i.replace(/\+/g," "):i,"=");o=o===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?o:Hs(o,e),r(Hs(s,e),o,n)}for(let i of Object.keys(n)){let s=n[i];if(typeof s=="object"&&s!==null)for(let o of Object.keys(s))s[o]=PB(s[o],e);else n[i]=PB(s,e)}return e.sort===!1?n:(e.sort===!0?Object.keys(n).sort():Object.keys(n).sort(e.sort)).reduce((i,s)=>{let o=n[s];return o&&typeof o=="object"&&!Array.isArray(o)?i[s]=MB(o):i[s]=o,i},Object.create(null))}nn.extract=FB;nn.parse=UB;nn.stringify=(t,e)=>{if(!t)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),BB(e.arrayFormatSeparator);let r=o=>e.skipNull&&fee(t[o])||e.skipEmptyString&&t[o]==="",n=hee(e),i={};for(let o of Object.keys(t))r(o)||(i[o]=t[o]);let s=Object.keys(i);return e.sort!==!1&&s.sort(e.sort),s.map(o=>{let u=t[o];return u===void 0?"":u===null?Zt(o,e):Array.isArray(u)?u.length===0&&e.arrayFormat==="bracket-separator"?Zt(o,e)+"[]":u.reduce(n(o),[]).join("&"):Zt(o,e)+"="+Zt(u,e)}).filter(o=>o.length>0).join("&")};nn.parseUrl=(t,e)=>{e=Object.assign({decode:!0},e);let[r,n]=RB(t,"#");return Object.assign({url:r.split("?")[0]||"",query:UB(FB(t),e)},e&&e.parseFragmentIdentifier&&n?{fragmentIdentifier:Hs(n,e)}:{})};nn.stringifyUrl=(t,e)=>{e=Object.assign({encode:!0,strict:!0,[WI]:!0},e);let r=LB(t.url).split("?")[0]||"",n=nn.extract(t.url),i=nn.parse(n,{sort:!1}),s=Object.assign(i,t.query),o=nn.stringify(s,e);o&&(o=`?${o}`);let u=gee(t.url);return t.fragmentIdentifier&&(u=`#${e[WI]?Zt(t.fragmentIdentifier,e):t.fragmentIdentifier}`),`${r}${o}${u}`};nn.pick=(t,e,r)=>{r=Object.assign({parseFragmentIdentifier:!0,[WI]:!1},r);let{url:n,query:i,fragmentIdentifier:s}=nn.parseUrl(t,r);return nn.stringifyUrl({url:n,query:lee(i,e),fragmentIdentifier:s},r)};nn.exclude=(t,e,r)=>{let n=Array.isArray(e)?i=>!e.includes(i):(i,s)=>!e(i,s);return nn.pick(t,n,r)}});var kB=D(xm=>{"use strict";h();Object.defineProperty(xm,"__esModule",{value:!0});var Mr=Uc(),$I=Qn(),pee=20;function mee(t,e,r){for(var n=1634760805,i=857760878,s=2036477234,o=1797285236,u=r[3]<<24|r[2]<<16|r[1]<<8|r[0],a=r[7]<<24|r[6]<<16|r[5]<<8|r[4],c=r[11]<<24|r[10]<<16|r[9]<<8|r[8],f=r[15]<<24|r[14]<<16|r[13]<<8|r[12],d=r[19]<<24|r[18]<<16|r[17]<<8|r[16],w=r[23]<<24|r[22]<<16|r[21]<<8|r[20],A=r[27]<<24|r[26]<<16|r[25]<<8|r[24],T=r[31]<<24|r[30]<<16|r[29]<<8|r[28],x=e[3]<<24|e[2]<<16|e[1]<<8|e[0],B=e[7]<<24|e[6]<<16|e[5]<<8|e[4],V=e[11]<<24|e[10]<<16|e[9]<<8|e[8],U=e[15]<<24|e[14]<<16|e[13]<<8|e[12],Q=n,L=i,k=s,H=o,q=u,v=a,C=c,P=f,F=d,R=w,l=A,g=T,y=x,E=B,I=V,_=U,M=0;M>>16|y<<16,F=F+y|0,q^=F,q=q>>>20|q<<12,L=L+v|0,E^=L,E=E>>>16|E<<16,R=R+E|0,v^=R,v=v>>>20|v<<12,k=k+C|0,I^=k,I=I>>>16|I<<16,l=l+I|0,C^=l,C=C>>>20|C<<12,H=H+P|0,_^=H,_=_>>>16|_<<16,g=g+_|0,P^=g,P=P>>>20|P<<12,k=k+C|0,I^=k,I=I>>>24|I<<8,l=l+I|0,C^=l,C=C>>>25|C<<7,H=H+P|0,_^=H,_=_>>>24|_<<8,g=g+_|0,P^=g,P=P>>>25|P<<7,L=L+v|0,E^=L,E=E>>>24|E<<8,R=R+E|0,v^=R,v=v>>>25|v<<7,Q=Q+q|0,y^=Q,y=y>>>24|y<<8,F=F+y|0,q^=F,q=q>>>25|q<<7,Q=Q+v|0,_^=Q,_=_>>>16|_<<16,l=l+_|0,v^=l,v=v>>>20|v<<12,L=L+C|0,y^=L,y=y>>>16|y<<16,g=g+y|0,C^=g,C=C>>>20|C<<12,k=k+P|0,E^=k,E=E>>>16|E<<16,F=F+E|0,P^=F,P=P>>>20|P<<12,H=H+q|0,I^=H,I=I>>>16|I<<16,R=R+I|0,q^=R,q=q>>>20|q<<12,k=k+P|0,E^=k,E=E>>>24|E<<8,F=F+E|0,P^=F,P=P>>>25|P<<7,H=H+q|0,I^=H,I=I>>>24|I<<8,R=R+I|0,q^=R,q=q>>>25|q<<7,L=L+C|0,y^=L,y=y>>>24|y<<8,g=g+y|0,C^=g,C=C>>>25|C<<7,Q=Q+v|0,_^=Q,_=_>>>24|_<<8,l=l+_|0,v^=l,v=v>>>25|v<<7;Mr.writeUint32LE(Q+n|0,t,0),Mr.writeUint32LE(L+i|0,t,4),Mr.writeUint32LE(k+s|0,t,8),Mr.writeUint32LE(H+o|0,t,12),Mr.writeUint32LE(q+u|0,t,16),Mr.writeUint32LE(v+a|0,t,20),Mr.writeUint32LE(C+c|0,t,24),Mr.writeUint32LE(P+f|0,t,28),Mr.writeUint32LE(F+d|0,t,32),Mr.writeUint32LE(R+w|0,t,36),Mr.writeUint32LE(l+A|0,t,40),Mr.writeUint32LE(g+T|0,t,44),Mr.writeUint32LE(y+x|0,t,48),Mr.writeUint32LE(E+B|0,t,52),Mr.writeUint32LE(I+V|0,t,56),Mr.writeUint32LE(_+U|0,t,60)}function VB(t,e,r,n,i){if(i===void 0&&(i=0),t.length!==32)throw new Error("ChaCha: key size must be 32 bytes");if(n.length>>=8,e++;if(n>0)throw new Error("ChaCha: counter overflow")}});var Om=D(Xc=>{"use strict";h();Object.defineProperty(Xc,"__esModule",{value:!0});function vee(t,e,r){return~(t-1)&e|t-1&r}Xc.select=vee;function Aee(t,e){return(t|0)-(e|0)-1>>>31&1}Xc.lessOrEqual=Aee;function HB(t,e){if(t.length!==e.length)return 0;for(var r=0,n=0;n>>8}Xc.compare=HB;function Eee(t,e){return t.length===0||e.length===0?!1:HB(t,e)!==0}Xc.equal=Eee});var jB=D(Gs=>{"use strict";h();Object.defineProperty(Gs,"__esModule",{value:!0});var bee=Om(),Dm=Qn();Gs.DIGEST_LENGTH=16;var GB=function(){function t(e){this.digestLength=Gs.DIGEST_LENGTH,this._buffer=new Uint8Array(16),this._r=new Uint16Array(10),this._h=new Uint16Array(10),this._pad=new Uint16Array(8),this._leftover=0,this._fin=0,this._finished=!1;var r=e[0]|e[1]<<8;this._r[0]=r&8191;var n=e[2]|e[3]<<8;this._r[1]=(r>>>13|n<<3)&8191;var i=e[4]|e[5]<<8;this._r[2]=(n>>>10|i<<6)&7939;var s=e[6]|e[7]<<8;this._r[3]=(i>>>7|s<<9)&8191;var o=e[8]|e[9]<<8;this._r[4]=(s>>>4|o<<12)&255,this._r[5]=o>>>1&8190;var u=e[10]|e[11]<<8;this._r[6]=(o>>>14|u<<2)&8191;var a=e[12]|e[13]<<8;this._r[7]=(u>>>11|a<<5)&8065;var c=e[14]|e[15]<<8;this._r[8]=(a>>>8|c<<8)&8191,this._r[9]=c>>>5&127,this._pad[0]=e[16]|e[17]<<8,this._pad[1]=e[18]|e[19]<<8,this._pad[2]=e[20]|e[21]<<8,this._pad[3]=e[22]|e[23]<<8,this._pad[4]=e[24]|e[25]<<8,this._pad[5]=e[26]|e[27]<<8,this._pad[6]=e[28]|e[29]<<8,this._pad[7]=e[30]|e[31]<<8}return t.prototype._blocks=function(e,r,n){for(var i=this._fin?0:2048,s=this._h[0],o=this._h[1],u=this._h[2],a=this._h[3],c=this._h[4],f=this._h[5],d=this._h[6],w=this._h[7],A=this._h[8],T=this._h[9],x=this._r[0],B=this._r[1],V=this._r[2],U=this._r[3],Q=this._r[4],L=this._r[5],k=this._r[6],H=this._r[7],q=this._r[8],v=this._r[9];n>=16;){var C=e[r+0]|e[r+1]<<8;s+=C&8191;var P=e[r+2]|e[r+3]<<8;o+=(C>>>13|P<<3)&8191;var F=e[r+4]|e[r+5]<<8;u+=(P>>>10|F<<6)&8191;var R=e[r+6]|e[r+7]<<8;a+=(F>>>7|R<<9)&8191;var l=e[r+8]|e[r+9]<<8;c+=(R>>>4|l<<12)&8191,f+=l>>>1&8191;var g=e[r+10]|e[r+11]<<8;d+=(l>>>14|g<<2)&8191;var y=e[r+12]|e[r+13]<<8;w+=(g>>>11|y<<5)&8191;var E=e[r+14]|e[r+15]<<8;A+=(y>>>8|E<<8)&8191,T+=E>>>5|i;var I=0,_=I;_+=s*x,_+=o*(5*v),_+=u*(5*q),_+=a*(5*H),_+=c*(5*k),I=_>>>13,_&=8191,_+=f*(5*L),_+=d*(5*Q),_+=w*(5*U),_+=A*(5*V),_+=T*(5*B),I+=_>>>13,_&=8191;var M=I;M+=s*B,M+=o*x,M+=u*(5*v),M+=a*(5*q),M+=c*(5*H),I=M>>>13,M&=8191,M+=f*(5*k),M+=d*(5*L),M+=w*(5*Q),M+=A*(5*U),M+=T*(5*V),I+=M>>>13,M&=8191;var N=I;N+=s*V,N+=o*B,N+=u*x,N+=a*(5*v),N+=c*(5*q),I=N>>>13,N&=8191,N+=f*(5*H),N+=d*(5*k),N+=w*(5*L),N+=A*(5*Q),N+=T*(5*U),I+=N>>>13,N&=8191;var m=I;m+=s*U,m+=o*V,m+=u*B,m+=a*x,m+=c*(5*v),I=m>>>13,m&=8191,m+=f*(5*q),m+=d*(5*H),m+=w*(5*k),m+=A*(5*L),m+=T*(5*Q),I+=m>>>13,m&=8191;var O=I;O+=s*Q,O+=o*U,O+=u*V,O+=a*B,O+=c*x,I=O>>>13,O&=8191,O+=f*(5*v),O+=d*(5*q),O+=w*(5*H),O+=A*(5*k),O+=T*(5*L),I+=O>>>13,O&=8191;var Y=I;Y+=s*L,Y+=o*Q,Y+=u*U,Y+=a*V,Y+=c*B,I=Y>>>13,Y&=8191,Y+=f*x,Y+=d*(5*v),Y+=w*(5*q),Y+=A*(5*H),Y+=T*(5*k),I+=Y>>>13,Y&=8191;var $=I;$+=s*k,$+=o*L,$+=u*Q,$+=a*U,$+=c*V,I=$>>>13,$&=8191,$+=f*B,$+=d*x,$+=w*(5*v),$+=A*(5*q),$+=T*(5*H),I+=$>>>13,$&=8191;var b=I;b+=s*H,b+=o*k,b+=u*L,b+=a*Q,b+=c*U,I=b>>>13,b&=8191,b+=f*V,b+=d*B,b+=w*x,b+=A*(5*v),b+=T*(5*q),I+=b>>>13,b&=8191;var j=I;j+=s*q,j+=o*H,j+=u*k,j+=a*L,j+=c*Q,I=j>>>13,j&=8191,j+=f*U,j+=d*V,j+=w*B,j+=A*x,j+=T*(5*v),I+=j>>>13,j&=8191;var z=I;z+=s*v,z+=o*q,z+=u*H,z+=a*k,z+=c*L,I=z>>>13,z&=8191,z+=f*Q,z+=d*U,z+=w*V,z+=A*B,z+=T*x,I+=z>>>13,z&=8191,I=(I<<2)+I|0,I=I+_|0,_=I&8191,I=I>>>13,M+=I,s=_,o=M,u=N,a=m,c=O,f=Y,d=$,w=b,A=j,T=z,r+=16,n-=16}this._h[0]=s,this._h[1]=o,this._h[2]=u,this._h[3]=a,this._h[4]=c,this._h[5]=f,this._h[6]=d,this._h[7]=w,this._h[8]=A,this._h[9]=T},t.prototype.finish=function(e,r){r===void 0&&(r=0);var n=new Uint16Array(10),i,s,o,u;if(this._leftover){for(u=this._leftover,this._buffer[u++]=1;u<16;u++)this._buffer[u]=0;this._fin=1,this._blocks(this._buffer,0,16)}for(i=this._h[1]>>>13,this._h[1]&=8191,u=2;u<10;u++)this._h[u]+=i,i=this._h[u]>>>13,this._h[u]&=8191;for(this._h[0]+=i*5,i=this._h[0]>>>13,this._h[0]&=8191,this._h[1]+=i,i=this._h[1]>>>13,this._h[1]&=8191,this._h[2]+=i,n[0]=this._h[0]+5,i=n[0]>>>13,n[0]&=8191,u=1;u<10;u++)n[u]=this._h[u]+i,i=n[u]>>>13,n[u]&=8191;for(n[9]-=8192,s=(i^1)-1,u=0;u<10;u++)n[u]&=s;for(s=~s,u=0;u<10;u++)this._h[u]=this._h[u]&s|n[u];for(this._h[0]=(this._h[0]|this._h[1]<<13)&65535,this._h[1]=(this._h[1]>>>3|this._h[2]<<10)&65535,this._h[2]=(this._h[2]>>>6|this._h[3]<<7)&65535,this._h[3]=(this._h[3]>>>9|this._h[4]<<4)&65535,this._h[4]=(this._h[4]>>>12|this._h[5]<<1|this._h[6]<<14)&65535,this._h[5]=(this._h[6]>>>2|this._h[7]<<11)&65535,this._h[6]=(this._h[7]>>>5|this._h[8]<<8)&65535,this._h[7]=(this._h[8]>>>8|this._h[9]<<5)&65535,o=this._h[0]+this._pad[0],this._h[0]=o&65535,u=1;u<8;u++)o=(this._h[u]+this._pad[u]|0)+(o>>>16)|0,this._h[u]=o&65535;return e[r+0]=this._h[0]>>>0,e[r+1]=this._h[0]>>>8,e[r+2]=this._h[1]>>>0,e[r+3]=this._h[1]>>>8,e[r+4]=this._h[2]>>>0,e[r+5]=this._h[2]>>>8,e[r+6]=this._h[3]>>>0,e[r+7]=this._h[3]>>>8,e[r+8]=this._h[4]>>>0,e[r+9]=this._h[4]>>>8,e[r+10]=this._h[5]>>>0,e[r+11]=this._h[5]>>>8,e[r+12]=this._h[6]>>>0,e[r+13]=this._h[6]>>>8,e[r+14]=this._h[7]>>>0,e[r+15]=this._h[7]>>>8,this._finished=!0,this},t.prototype.update=function(e){var r=0,n=e.length,i;if(this._leftover){i=16-this._leftover,i>n&&(i=n);for(var s=0;s=16&&(i=n-n%16,this._blocks(e,r,i),r+=i,n-=i),n){for(var s=0;s{"use strict";h();Object.defineProperty(js,"__esModule",{value:!0});var Pm=kB(),Tee=jB(),xh=Qn(),zB=Uc(),_ee=Om();js.KEY_LENGTH=32;js.NONCE_LENGTH=12;js.TAG_LENGTH=16;var QB=new Uint8Array(16),Cee=function(){function t(e){if(this.nonceLength=js.NONCE_LENGTH,this.tagLength=js.TAG_LENGTH,e.length!==js.KEY_LENGTH)throw new Error("ChaCha20Poly1305 needs 32-byte key");this._key=new Uint8Array(e)}return t.prototype.seal=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");var s=new Uint8Array(16);s.set(e,s.length-e.length);var o=new Uint8Array(32);Pm.stream(this._key,s,o,4);var u=r.length+this.tagLength,a;if(i){if(i.length!==u)throw new Error("ChaCha20Poly1305: incorrect destination length");a=i}else a=new Uint8Array(u);return Pm.streamXOR(this._key,s,r,a,4),this._authenticate(a.subarray(a.length-this.tagLength,a.length),o,a.subarray(0,a.length-this.tagLength),n),xh.wipe(s),a},t.prototype.open=function(e,r,n,i){if(e.length>16)throw new Error("ChaCha20Poly1305: incorrect nonce length");if(r.length0&&s.update(QB.subarray(i.length%16))),s.update(n),n.length%16>0&&s.update(QB.subarray(n.length%16));var o=new Uint8Array(8);i&&zB.writeUint64LE(i.length,o),s.update(o),zB.writeUint64LE(n.length,o),s.update(o);for(var u=s.digest(),a=0;a{"use strict";h();Object.defineProperty(YI,"__esModule",{value:!0});function Nee(t){return typeof t.saveState<"u"&&typeof t.restoreState<"u"&&typeof t.cleanSavedState<"u"}YI.isSerializableHash=Nee});var YB=D(Oh=>{"use strict";h();Object.defineProperty(Oh,"__esModule",{value:!0});var is=WB(),xee=Om(),Oee=Qn(),$B=function(){function t(e,r){this._finished=!1,this._inner=new e,this._outer=new e,this.blockSize=this._outer.blockSize,this.digestLength=this._outer.digestLength;var n=new Uint8Array(this.blockSize);r.length>this.blockSize?this._inner.update(r).finish(n).clean():n.set(r);for(var i=0;i{"use strict";h();Object.defineProperty(JI,"__esModule",{value:!0});var JB=YB(),XB=Qn(),Pee=function(){function t(e,r,n,i){n===void 0&&(n=new Uint8Array(0)),this._counter=new Uint8Array(1),this._hash=e,this._info=i;var s=JB.hmac(this._hash,n,r);this._hmac=new JB.HMAC(e,s),this._buffer=new Uint8Array(this._hmac.digestLength),this._bufpos=this._buffer.length}return t.prototype._fillBuffer=function(){this._counter[0]++;var e=this._counter[0];if(e===0)throw new Error("hkdf: cannot expand more");this._hmac.reset(),e>1&&this._hmac.update(this._buffer),this._info&&this._hmac.update(this._info),this._hmac.update(this._counter),this._hmac.finish(this._buffer),this._bufpos=0},t.prototype.expand=function(e){for(var r=new Uint8Array(e),n=0;n{"use strict";h();Object.defineProperty(Uo,"__esModule",{value:!0});var Bm=Uc(),Rm=Qn();Uo.DIGEST_LENGTH=32;Uo.BLOCK_SIZE=64;var eM=function(){function t(){this.digestLength=Uo.DIGEST_LENGTH,this.blockSize=Uo.BLOCK_SIZE,this._state=new Int32Array(8),this._temp=new Int32Array(64),this._buffer=new Uint8Array(128),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return t.prototype._initState=function(){this._state[0]=1779033703,this._state[1]=3144134277,this._state[2]=1013904242,this._state[3]=2773480762,this._state[4]=1359893119,this._state[5]=2600822924,this._state[6]=528734635,this._state[7]=1541459225},t.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},t.prototype.clean=function(){Rm.wipe(this._buffer),Rm.wipe(this._temp),this.reset()},t.prototype.update=function(e,r){if(r===void 0&&(r=e.length),this._finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this._bytesHashed+=r,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=e[n++],r--;this._bufferLength===this.blockSize&&(XI(this._temp,this._state,this._buffer,0,this.blockSize),this._bufferLength=0)}for(r>=this.blockSize&&(n=XI(this._temp,this._state,e,n,r),r%=this.blockSize);r>0;)this._buffer[this._bufferLength++]=e[n++],r--;return this},t.prototype.finish=function(e){if(!this._finished){var r=this._bytesHashed,n=this._bufferLength,i=r/536870912|0,s=r<<3,o=r%64<56?64:128;this._buffer[n]=128;for(var u=n+1;u0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},t.prototype.restoreState=function(e){return this._state.set(e.state),this._bufferLength=e.bufferLength,e.buffer&&this._buffer.set(e.buffer),this._bytesHashed=e.bytesHashed,this._finished=!1,this},t.prototype.cleanSavedState=function(e){Rm.wipe(e.state),e.buffer&&Rm.wipe(e.buffer),e.bufferLength=0,e.bytesHashed=0},t}();Uo.SHA256=eM;var Ree=new Int32Array([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]);function XI(t,e,r,n,i){for(;i>=64;){for(var s=e[0],o=e[1],u=e[2],a=e[3],c=e[4],f=e[5],d=e[6],w=e[7],A=0;A<16;A++){var T=n+A*4;t[A]=Bm.readUint32BE(r,T)}for(var A=16;A<64;A++){var x=t[A-2],B=(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10;x=t[A-15];var V=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3;t[A]=(B+t[A-7]|0)+(V+t[A-16]|0)}for(var A=0;A<64;A++){var B=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&d)|0)+(w+(Ree[A]+t[A]|0)|0)|0,V=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&o^s&u^o&u)|0;w=d,d=f,f=c,c=a+B|0,a=u,u=o,o=s,s=B+V|0}e[0]+=s,e[1]+=o,e[2]+=u,e[3]+=a,e[4]+=c,e[5]+=f,e[6]+=d,e[7]+=w,n+=64,i-=64}return n}function Bee(t){var e=new eM;e.update(t);var r=e.digest();return e.clean(),r}Uo.hash=Bee});var sM=D(zt=>{"use strict";h();Object.defineProperty(zt,"__esModule",{value:!0});zt.sharedKey=zt.generateKeyPair=zt.generateKeyPairFromSeed=zt.scalarMultBase=zt.scalarMult=zt.SHARED_KEY_LENGTH=zt.SECRET_KEY_LENGTH=zt.PUBLIC_KEY_LENGTH=void 0;var Mee=yh(),Lee=Qn();zt.PUBLIC_KEY_LENGTH=32;zt.SECRET_KEY_LENGTH=32;zt.SHARED_KEY_LENGTH=32;function ss(t){let e=new Float64Array(16);if(t)for(let r=0;r>16&1),r[o-1]&=65535;r[15]=n[15]-32767-(r[14]>>16&1);let s=r[15]>>16&1;r[14]&=65535,Dh(n,r,1-s)}for(let i=0;i<16;i++)t[2*i]=n[i]&255,t[2*i+1]=n[i]>>8}function qee(t,e){for(let r=0;r<16;r++)t[r]=e[2*r]+(e[2*r+1]<<8);t[15]&=32767}function Mm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]+r[n]}function Lm(t,e,r){for(let n=0;n<16;n++)t[n]=e[n]-r[n]}function zs(t,e,r){let n,i,s=0,o=0,u=0,a=0,c=0,f=0,d=0,w=0,A=0,T=0,x=0,B=0,V=0,U=0,Q=0,L=0,k=0,H=0,q=0,v=0,C=0,P=0,F=0,R=0,l=0,g=0,y=0,E=0,I=0,_=0,M=0,N=r[0],m=r[1],O=r[2],Y=r[3],$=r[4],b=r[5],j=r[6],z=r[7],W=r[8],ie=r[9],te=r[10],ee=r[11],se=r[12],oe=r[13],J=r[14],ue=r[15];n=e[0],s+=n*N,o+=n*m,u+=n*O,a+=n*Y,c+=n*$,f+=n*b,d+=n*j,w+=n*z,A+=n*W,T+=n*ie,x+=n*te,B+=n*ee,V+=n*se,U+=n*oe,Q+=n*J,L+=n*ue,n=e[1],o+=n*N,u+=n*m,a+=n*O,c+=n*Y,f+=n*$,d+=n*b,w+=n*j,A+=n*z,T+=n*W,x+=n*ie,B+=n*te,V+=n*ee,U+=n*se,Q+=n*oe,L+=n*J,k+=n*ue,n=e[2],u+=n*N,a+=n*m,c+=n*O,f+=n*Y,d+=n*$,w+=n*b,A+=n*j,T+=n*z,x+=n*W,B+=n*ie,V+=n*te,U+=n*ee,Q+=n*se,L+=n*oe,k+=n*J,H+=n*ue,n=e[3],a+=n*N,c+=n*m,f+=n*O,d+=n*Y,w+=n*$,A+=n*b,T+=n*j,x+=n*z,B+=n*W,V+=n*ie,U+=n*te,Q+=n*ee,L+=n*se,k+=n*oe,H+=n*J,q+=n*ue,n=e[4],c+=n*N,f+=n*m,d+=n*O,w+=n*Y,A+=n*$,T+=n*b,x+=n*j,B+=n*z,V+=n*W,U+=n*ie,Q+=n*te,L+=n*ee,k+=n*se,H+=n*oe,q+=n*J,v+=n*ue,n=e[5],f+=n*N,d+=n*m,w+=n*O,A+=n*Y,T+=n*$,x+=n*b,B+=n*j,V+=n*z,U+=n*W,Q+=n*ie,L+=n*te,k+=n*ee,H+=n*se,q+=n*oe,v+=n*J,C+=n*ue,n=e[6],d+=n*N,w+=n*m,A+=n*O,T+=n*Y,x+=n*$,B+=n*b,V+=n*j,U+=n*z,Q+=n*W,L+=n*ie,k+=n*te,H+=n*ee,q+=n*se,v+=n*oe,C+=n*J,P+=n*ue,n=e[7],w+=n*N,A+=n*m,T+=n*O,x+=n*Y,B+=n*$,V+=n*b,U+=n*j,Q+=n*z,L+=n*W,k+=n*ie,H+=n*te,q+=n*ee,v+=n*se,C+=n*oe,P+=n*J,F+=n*ue,n=e[8],A+=n*N,T+=n*m,x+=n*O,B+=n*Y,V+=n*$,U+=n*b,Q+=n*j,L+=n*z,k+=n*W,H+=n*ie,q+=n*te,v+=n*ee,C+=n*se,P+=n*oe,F+=n*J,R+=n*ue,n=e[9],T+=n*N,x+=n*m,B+=n*O,V+=n*Y,U+=n*$,Q+=n*b,L+=n*j,k+=n*z,H+=n*W,q+=n*ie,v+=n*te,C+=n*ee,P+=n*se,F+=n*oe,R+=n*J,l+=n*ue,n=e[10],x+=n*N,B+=n*m,V+=n*O,U+=n*Y,Q+=n*$,L+=n*b,k+=n*j,H+=n*z,q+=n*W,v+=n*ie,C+=n*te,P+=n*ee,F+=n*se,R+=n*oe,l+=n*J,g+=n*ue,n=e[11],B+=n*N,V+=n*m,U+=n*O,Q+=n*Y,L+=n*$,k+=n*b,H+=n*j,q+=n*z,v+=n*W,C+=n*ie,P+=n*te,F+=n*ee,R+=n*se,l+=n*oe,g+=n*J,y+=n*ue,n=e[12],V+=n*N,U+=n*m,Q+=n*O,L+=n*Y,k+=n*$,H+=n*b,q+=n*j,v+=n*z,C+=n*W,P+=n*ie,F+=n*te,R+=n*ee,l+=n*se,g+=n*oe,y+=n*J,E+=n*ue,n=e[13],U+=n*N,Q+=n*m,L+=n*O,k+=n*Y,H+=n*$,q+=n*b,v+=n*j,C+=n*z,P+=n*W,F+=n*ie,R+=n*te,l+=n*ee,g+=n*se,y+=n*oe,E+=n*J,I+=n*ue,n=e[14],Q+=n*N,L+=n*m,k+=n*O,H+=n*Y,q+=n*$,v+=n*b,C+=n*j,P+=n*z,F+=n*W,R+=n*ie,l+=n*te,g+=n*ee,y+=n*se,E+=n*oe,I+=n*J,_+=n*ue,n=e[15],L+=n*N,k+=n*m,H+=n*O,q+=n*Y,v+=n*$,C+=n*b,P+=n*j,F+=n*z,R+=n*W,l+=n*ie,g+=n*te,y+=n*ee,E+=n*se,I+=n*oe,_+=n*J,M+=n*ue,s+=38*k,o+=38*H,u+=38*q,a+=38*v,c+=38*C,f+=38*P,d+=38*F,w+=38*R,A+=38*l,T+=38*g,x+=38*y,B+=38*E,V+=38*I,U+=38*_,Q+=38*M,i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),i=1,n=s+i+65535,i=Math.floor(n/65536),s=n-i*65536,n=o+i+65535,i=Math.floor(n/65536),o=n-i*65536,n=u+i+65535,i=Math.floor(n/65536),u=n-i*65536,n=a+i+65535,i=Math.floor(n/65536),a=n-i*65536,n=c+i+65535,i=Math.floor(n/65536),c=n-i*65536,n=f+i+65535,i=Math.floor(n/65536),f=n-i*65536,n=d+i+65535,i=Math.floor(n/65536),d=n-i*65536,n=w+i+65535,i=Math.floor(n/65536),w=n-i*65536,n=A+i+65535,i=Math.floor(n/65536),A=n-i*65536,n=T+i+65535,i=Math.floor(n/65536),T=n-i*65536,n=x+i+65535,i=Math.floor(n/65536),x=n-i*65536,n=B+i+65535,i=Math.floor(n/65536),B=n-i*65536,n=V+i+65535,i=Math.floor(n/65536),V=n-i*65536,n=U+i+65535,i=Math.floor(n/65536),U=n-i*65536,n=Q+i+65535,i=Math.floor(n/65536),Q=n-i*65536,n=L+i+65535,i=Math.floor(n/65536),L=n-i*65536,s+=i-1+37*(i-1),t[0]=s,t[1]=o,t[2]=u,t[3]=a,t[4]=c,t[5]=f,t[6]=d,t[7]=w,t[8]=A,t[9]=T,t[10]=x,t[11]=B,t[12]=V,t[13]=U,t[14]=Q,t[15]=L}function Ph(t,e){zs(t,e,e)}function Vee(t,e){let r=ss();for(let n=0;n<16;n++)r[n]=e[n];for(let n=253;n>=0;n--)Ph(r,r),n!==2&&n!==4&&zs(r,r,e);for(let n=0;n<16;n++)t[n]=r[n]}function eT(t,e){let r=new Uint8Array(32),n=new Float64Array(80),i=ss(),s=ss(),o=ss(),u=ss(),a=ss(),c=ss();for(let A=0;A<31;A++)r[A]=t[A];r[31]=t[31]&127|64,r[0]&=248,qee(n,e);for(let A=0;A<16;A++)s[A]=n[A];i[0]=u[0]=1;for(let A=254;A>=0;--A){let T=r[A>>>3]>>>(A&7)&1;Dh(i,s,T),Dh(o,u,T),Mm(a,i,o),Lm(i,i,o),Mm(o,s,u),Lm(s,s,u),Ph(u,a),Ph(c,i),zs(i,o,i),zs(o,s,a),Mm(a,i,o),Lm(i,i,o),Ph(s,i),Lm(o,u,c),zs(i,o,Fee),Mm(i,i,u),zs(o,o,i),zs(i,u,c),zs(u,s,n),Ph(s,a),Dh(i,s,T),Dh(o,u,T)}for(let A=0;A<16;A++)n[A+16]=i[A],n[A+32]=o[A],n[A+48]=s[A],n[A+64]=u[A];let f=n.subarray(32),d=n.subarray(16);Vee(f,f),zs(d,d,f);let w=new Uint8Array(32);return Uee(w,d),w}zt.scalarMult=eT;function nM(t){return eT(t,rM)}zt.scalarMultBase=nM;function iM(t){if(t.length!==zt.SECRET_KEY_LENGTH)throw new Error(`x25519: seed must be ${zt.SECRET_KEY_LENGTH} bytes`);let e=new Uint8Array(t);return{publicKey:nM(e),secretKey:e}}zt.generateKeyPairFromSeed=iM;function kee(t){let e=(0,Mee.randomBytes)(32,t),r=iM(e);return(0,Lee.wipe)(e),r}zt.generateKeyPair=kee;function Hee(t,e,r=!1){if(t.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect secret key length");if(e.length!==zt.PUBLIC_KEY_LENGTH)throw new Error("X25519: incorrect public key length");let n=eT(t,e);if(r){let i=0;for(let s=0;se[r])return 1}return t.byteLength>e.byteLength?1:t.byteLength{h()});function uM(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r{h()});function lM(t,e){if(t.length!==e.length)throw new Error("Inputs should have the same length");let r=jc(t.length);for(let n=0;n{h();Am();Eh()});var tT={};Bt(tT,{compare:()=>oM,concat:()=>Em,equals:()=>uM,fromString:()=>ns,toString:()=>ks,xor:()=>lM});var rT=fe(()=>{h();aM();fI();cM();UI();FI();fM()});var hM={};Bt(hM,{RELAY_JSONRPC:()=>ete,isPublishMethod:()=>sT,isPublishParams:()=>oT,isPublishRequest:()=>Kee,isSubscribeMethod:()=>nT,isSubscribeParams:()=>iT,isSubscribeRequest:()=>Qee,isSubscriptionMethod:()=>cT,isSubscriptionParams:()=>lT,isSubscriptionRequest:()=>$ee,isUnsubscribeMethod:()=>aT,isUnsubscribeParams:()=>uT,isUnsubscribeRequest:()=>Wee,parsePublishRequest:()=>Jee,parseSubscribeRequest:()=>Yee,parseSubscriptionRequest:()=>Zee,parseUnsubscribeRequest:()=>Xee});function Xa(t,e,r="string"){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function Gee(t,e){let r=!0;return e.forEach(n=>{n in t||(r=!1)}),r}function jee(t,e){return Array.isArray(t)?t.length===e:Object.keys(t).length===e}function zee(t,e){return Array.isArray(t)?t.length>=e:Object.keys(t).length>=e}function Fm(t,e,r){return(r.length?zee(t,e.length):jee(t,e.length))?Gee(t,e):!1}function Um(t,e,r="_"){let n=t.split(r);return n[n.length-1].trim().toLowerCase()===e.trim().toLowerCase()}function Qee(t){return nT(t.method)&&iT(t.params)}function nT(t){return Um(t,"subscribe")}function iT(t){return Fm(t,["topic"],[])}function Kee(t){return sT(t.method)&&oT(t.params)}function sT(t){return Um(t,"publish")}function oT(t){return Fm(t,["message","topic","ttl"],["prompt","tag"])}function Wee(t){return aT(t.method)&&uT(t.params)}function aT(t){return Um(t,"unsubscribe")}function uT(t){return Fm(t,["id","topic"],[])}function $ee(t){return cT(t.method)&&lT(t.params)}function cT(t){return Um(t,"subscription")}function lT(t){return Fm(t,["id","data"],[])}function Yee(t){if(!nT(t.method))throw new Error("JSON-RPC Request has invalid subscribe method");if(!iT(t.params))throw new Error("JSON-RPC Request has invalid subscribe params");let e=t.params;return Xa(e,"topic"),e}function Jee(t){if(!sT(t.method))throw new Error("JSON-RPC Request has invalid publish method");if(!oT(t.params))throw new Error("JSON-RPC Request has invalid publish params");let e=t.params;return Xa(e,"topic"),Xa(e,"message"),Xa(e,"ttl","number"),e}function Xee(t){if(!aT(t.method))throw new Error("JSON-RPC Request has invalid unsubscribe method");if(!uT(t.params))throw new Error("JSON-RPC Request has invalid unsubscribe params");let e=t.params;return Xa(e,"id"),e}function Zee(t){if(!cT(t.method))throw new Error("JSON-RPC Request has invalid subscription method");if(!lT(t.params))throw new Error("JSON-RPC Request has invalid subscription params");let e=t.params;return Xa(e,"id"),Xa(e,"data"),e}var ete,dM=fe(()=>{h();ete={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var Qh=D(K=>{"use strict";h();Object.defineProperty(K,"__esModule",{value:!0});var tte=wB(),el=za(),il=QI(),rte=AB(),nte=qB(),KM=KB(),ite=ZB(),WM=yh(),FT=tM(),ste=sM(),Vt=(rT(),_e(tT)),ote=(dM(),_e(hM));function $M(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var Km=$M(nte),YM=$M(ste),ty=":";function JM(t){let[e,r]=t.split(ty);return{namespace:e,reference:r}}function XM(t){let{namespace:e,reference:r}=t;return[e,r].join(ty)}function UT(t){let[e,r,n]=t.split(ty);return{namespace:e,reference:r,address:n}}function ZM(t){let{namespace:e,reference:r,address:n}=t;return[e,r,n].join(ty)}function qT(t,e){let r=[];return t.forEach(n=>{let i=e(n);r.includes(i)||r.push(i)}),r}function e4(t){let{address:e}=UT(t);return e}function t4(t){let{namespace:e,reference:r}=UT(t);return XM({namespace:e,reference:r})}function ate(t,e){let{namespace:r,reference:n}=JM(e);return ZM({namespace:r,reference:n,address:t})}function ute(t){return qT(t,e4)}function r4(t){return qT(t,t4)}function cte(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...i.accounts)}),r}function lte(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...r4(i.accounts))}),r}function fte(t,e=[]){let r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;let i=t[n];r.push(...ry(n,i))}),r}function ry(t,e){return t.includes(":")?[t]:e.chains||[]}var hte=Object.defineProperty,gM=Object.getOwnPropertySymbols,dte=Object.prototype.hasOwnProperty,gte=Object.prototype.propertyIsEnumerable,pM=(t,e,r)=>e in t?hte(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mM=(t,e)=>{for(var r in e||(e={}))dte.call(e,r)&&pM(t,r,e[r]);if(gM)for(var r of gM(e))gte.call(e,r)&&pM(t,r,e[r]);return t},n4="ReactNative",Gr={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wm=" ",pte=":",i4="/",VT=2,mte=1e3,s4="js";function kT(){return typeof S.default<"u"&&typeof S.default.versions<"u"&&typeof S.default.versions.node<"u"}function al(){return!il.getDocument()&&!!il.getNavigator()&&navigator.product===n4}function Hh(){return!kT()&&!!il.getNavigator()&&!!il.getDocument()}function tu(){return al()?Gr.reactNative:kT()?Gr.node:Hh()?Gr.browser:Gr.unknown}function yte(){var t;try{return al()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function o4(t,e){let r=Km.parse(t);return r=mM(mM({},r),e),t=Km.stringify(r),t}function wte(){return rte.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function vte(t,e){var r;let n=tu(),i={protocol:t,version:e,env:n};return n==="browser"&&(i.host=((r=il.getLocation())==null?void 0:r.host)||"unknown"),i}function a4(){if(tu()===Gr.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let t=tte.detect();if(t===null)return"unknown";let e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function u4(){var t;let e=tu();return e===Gr.browser?[e,((t=il.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function c4(t,e,r){let n=a4(),i=u4();return[[t,e].join("-"),[s4,r].join("-"),n,i].join("/")}function Ate({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:u}){let a=r.split("?"),c=c4(t,e,n),f={auth:i,ua:c,projectId:s,useOnCloseEvent:o||void 0,origin:u||void 0},d=o4(a[1]||"",f);return a[0]+"?"+d}function Ete(t){let e=(t.match(/^[^:]+(?=:\/\/)/gi)||[])[0],r=typeof e<"u"?t.split("://")[1]:t;return e=e==="wss"?"https":"http",[e,r].join("://")}function bte(t,e,r){if(!t[e]||typeof t[e]!==r)throw new Error(`Missing or invalid "${e}" param`)}function l4(t,e=VT){return f4(t.split(i4),e)}function Ste(t){return l4(t).join(Wm)}function Ho(t,e){return t.filter(r=>e.includes(r)).length===t.length}function f4(t,e=VT){return t.slice(Math.max(t.length-e,0))}function Ite(t){return Object.fromEntries(t.entries())}function Tte(t){return new Map(Object.entries(t))}function _te(t,e){let r={};return Object.keys(t).forEach(n=>{r[n]=e(t[n])}),r}var Cte=t=>t;function h4(t){return t.trim().replace(/^\w/,e=>e.toUpperCase())}function Nte(t){return t.split(Wm).map(e=>h4(e)).join(Wm)}function xte(t=el.FIVE_MINUTES,e){let r=el.toMiliseconds(t||el.FIVE_MINUTES),n,i,s;return{resolve:o=>{s&&n&&(clearTimeout(s),n(o))},reject:o=>{s&&i&&(clearTimeout(s),i(o))},done:()=>new Promise((o,u)=>{s=setTimeout(()=>{u(new Error(e))},r),n=o,i=u})}}function Ote(t,e,r){return new Promise(async(n,i)=>{let s=setTimeout(()=>i(new Error(r)),e);try{let o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function HT(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Dte(t){return HT("topic",t)}function Pte(t){return HT("id",t)}function Rte(t){let[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function Bte(t,e){return el.fromMiliseconds((e||Date.now())+el.toMiliseconds(t))}function Mte(t){return Date.now()>=el.toMiliseconds(t)}function Lte(t,e){return`${t}${e?`:${e}`:""}`}function Js(t=[],e=[]){return[...new Set([...t,...e])]}async function Fte({id:t,topic:e,wcDeepLink:r}){try{if(!r)return;let i=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof i!="string")return;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}/wc?requestId=${t}&sessionTopic=${e}`,o=tu();o===Gr.browser?s.startsWith("https://")||s.startsWith("http://")?window.open(s,"_blank","noreferrer noopener"):window.open(s,"_self","noreferrer noopener"):o===Gr.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(s)}catch(n){console.error(n)}}async function Ute(t,e){try{return await t.getItem(e)||(Hh()?localStorage.getItem(e):void 0)}catch(r){console.error(r)}}function _T(t,e){return t.filter(r=>e.includes(r))}var d4=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qte(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var g4={exports:{}};(function(t){(function(){var e="input is invalid type",r="finalize already called",n=typeof window=="object",i=n?window:{};i.JS_SHA3_NO_WINDOW&&(n=!1);var s=!n&&typeof self=="object",o=!i.JS_SHA3_NO_NODE_JS&&typeof S.default=="object"&&S.default.versions&&S.default.versions.node;o?i=d4:s&&(i=self);var u=!i.JS_SHA3_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA3_NO_ARRAY_BUFFER&&typeof ArrayBuffer<"u",c="0123456789abcdef".split(""),f=[31,7936,2031616,520093696],d=[4,1024,262144,67108864],w=[1,256,65536,16777216],A=[6,1536,393216,100663296],T=[0,8,16,24],x=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],B=[224,256,384,512],V=[128,256],U=["hex","buffer","arrayBuffer","array","digest"],Q={128:168,256:136};(i.JS_SHA3_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(b){return Object.prototype.toString.call(b)==="[object Array]"}),a&&(i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(b){return typeof b=="object"&&b.buffer&&b.buffer.constructor===ArrayBuffer});for(var L=function(b,j,z){return function(W){return new O(b,j,b).update(W)[z]()}},k=function(b,j,z){return function(W,ie){return new O(b,j,ie).update(W)[z]()}},H=function(b,j,z){return function(W,ie,te,ee){return g["cshake"+b].update(W,ie,te,ee)[z]()}},q=function(b,j,z){return function(W,ie,te,ee){return g["kmac"+b].update(W,ie,te,ee)[z]()}},v=function(b,j,z,W){for(var ie=0;ie>5,this.byteCount=this.blockCount<<2,this.outputBlocks=z>>5,this.extraBytes=(z&31)>>3;for(var W=0;W<50;++W)this.s[W]=0}O.prototype.update=function(b){if(this.finalized)throw new Error(r);var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}for(var W=this.blocks,ie=this.byteCount,te=b.length,ee=this.blockCount,se=0,oe=this.s,J,ue;se>2]|=b[se]<>2]|=ue<>2]|=(192|ue>>6)<>2]|=(128|ue&63)<=57344?(W[J>>2]|=(224|ue>>12)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<>2]|=(240|ue>>18)<>2]|=(128|ue>>12&63)<>2]|=(128|ue>>6&63)<>2]|=(128|ue&63)<=ie){for(this.start=J-ie,this.block=W[ee],J=0;J>8,z=b&255;z>0;)ie.unshift(z),b=b>>8,z=b&255,++W;return j?ie.push(W):ie.unshift(W),this.update(ie),ie.length},O.prototype.encodeString=function(b){var j,z=typeof b;if(z!=="string"){if(z==="object"){if(b===null)throw new Error(e);if(a&&b.constructor===ArrayBuffer)b=new Uint8Array(b);else if(!Array.isArray(b)&&(!a||!ArrayBuffer.isView(b)))throw new Error(e)}else throw new Error(e);j=!0}var W=0,ie=b.length;if(j)W=ie;else for(var te=0;te=57344?W+=3:(ee=65536+((ee&1023)<<10|b.charCodeAt(++te)&1023),W+=4)}return W+=this.encode(W*8),this.update(b),W},O.prototype.bytepad=function(b,j){for(var z=this.encode(j),W=0;W>2]|=this.padding[j&3],this.lastByteIndex===this.byteCount)for(b[0]=b[z],j=1;j>4&15]+c[se&15]+c[se>>12&15]+c[se>>8&15]+c[se>>20&15]+c[se>>16&15]+c[se>>28&15]+c[se>>24&15];te%b===0&&($(j),ie=0)}return W&&(se=j[ie],ee+=c[se>>4&15]+c[se&15],W>1&&(ee+=c[se>>12&15]+c[se>>8&15]),W>2&&(ee+=c[se>>20&15]+c[se>>16&15])),ee},O.prototype.arrayBuffer=function(){this.finalize();var b=this.blockCount,j=this.s,z=this.outputBlocks,W=this.extraBytes,ie=0,te=0,ee=this.outputBits>>3,se;W?se=new ArrayBuffer(z+1<<2):se=new ArrayBuffer(ee);for(var oe=new Uint32Array(se);te>8&255,ee[se+2]=oe>>16&255,ee[se+3]=oe>>24&255;te%b===0&&$(j)}return W&&(se=te<<2,oe=j[ie],ee[se]=oe&255,W>1&&(ee[se+1]=oe>>8&255),W>2&&(ee[se+2]=oe>>16&255)),ee};function Y(b,j,z){O.call(this,b,j,z)}Y.prototype=new O,Y.prototype.finalize=function(){return this.encode(this.outputBits,!0),O.prototype.finalize.call(this)};var $=function(b){var j,z,W,ie,te,ee,se,oe,J,ue,wt,vt,Ni,At,Et,xi,bt,St,Oi,It,Tt,Di,Qe,Ke,ri,We,$e,ni,Ye,Je,ii,Xe,Ze,si,et,tt,oi,rt,nt,ai,it,st,ui,ot,at,ci,ut,ct,li,lt,ft,fi,ht,dt,hi,gt,pt,vn,An,En,bn,Sn,In;for(W=0;W<48;W+=2)ie=b[0]^b[10]^b[20]^b[30]^b[40],te=b[1]^b[11]^b[21]^b[31]^b[41],ee=b[2]^b[12]^b[22]^b[32]^b[42],se=b[3]^b[13]^b[23]^b[33]^b[43],oe=b[4]^b[14]^b[24]^b[34]^b[44],J=b[5]^b[15]^b[25]^b[35]^b[45],ue=b[6]^b[16]^b[26]^b[36]^b[46],wt=b[7]^b[17]^b[27]^b[37]^b[47],vt=b[8]^b[18]^b[28]^b[38]^b[48],Ni=b[9]^b[19]^b[29]^b[39]^b[49],j=vt^(ee<<1|se>>>31),z=Ni^(se<<1|ee>>>31),b[0]^=j,b[1]^=z,b[10]^=j,b[11]^=z,b[20]^=j,b[21]^=z,b[30]^=j,b[31]^=z,b[40]^=j,b[41]^=z,j=ie^(oe<<1|J>>>31),z=te^(J<<1|oe>>>31),b[2]^=j,b[3]^=z,b[12]^=j,b[13]^=z,b[22]^=j,b[23]^=z,b[32]^=j,b[33]^=z,b[42]^=j,b[43]^=z,j=ee^(ue<<1|wt>>>31),z=se^(wt<<1|ue>>>31),b[4]^=j,b[5]^=z,b[14]^=j,b[15]^=z,b[24]^=j,b[25]^=z,b[34]^=j,b[35]^=z,b[44]^=j,b[45]^=z,j=oe^(vt<<1|Ni>>>31),z=J^(Ni<<1|vt>>>31),b[6]^=j,b[7]^=z,b[16]^=j,b[17]^=z,b[26]^=j,b[27]^=z,b[36]^=j,b[37]^=z,b[46]^=j,b[47]^=z,j=ue^(ie<<1|te>>>31),z=wt^(te<<1|ie>>>31),b[8]^=j,b[9]^=z,b[18]^=j,b[19]^=z,b[28]^=j,b[29]^=z,b[38]^=j,b[39]^=z,b[48]^=j,b[49]^=z,At=b[0],Et=b[1],ci=b[11]<<4|b[10]>>>28,ut=b[10]<<4|b[11]>>>28,ni=b[20]<<3|b[21]>>>29,Ye=b[21]<<3|b[20]>>>29,En=b[31]<<9|b[30]>>>23,bn=b[30]<<9|b[31]>>>23,st=b[40]<<18|b[41]>>>14,ui=b[41]<<18|b[40]>>>14,si=b[2]<<1|b[3]>>>31,et=b[3]<<1|b[2]>>>31,xi=b[13]<<12|b[12]>>>20,bt=b[12]<<12|b[13]>>>20,ct=b[22]<<10|b[23]>>>22,li=b[23]<<10|b[22]>>>22,Je=b[33]<<13|b[32]>>>19,ii=b[32]<<13|b[33]>>>19,Sn=b[42]<<2|b[43]>>>30,In=b[43]<<2|b[42]>>>30,dt=b[5]<<30|b[4]>>>2,hi=b[4]<<30|b[5]>>>2,tt=b[14]<<6|b[15]>>>26,oi=b[15]<<6|b[14]>>>26,St=b[25]<<11|b[24]>>>21,Oi=b[24]<<11|b[25]>>>21,lt=b[34]<<15|b[35]>>>17,ft=b[35]<<15|b[34]>>>17,Xe=b[45]<<29|b[44]>>>3,Ze=b[44]<<29|b[45]>>>3,Ke=b[6]<<28|b[7]>>>4,ri=b[7]<<28|b[6]>>>4,gt=b[17]<<23|b[16]>>>9,pt=b[16]<<23|b[17]>>>9,rt=b[26]<<25|b[27]>>>7,nt=b[27]<<25|b[26]>>>7,It=b[36]<<21|b[37]>>>11,Tt=b[37]<<21|b[36]>>>11,fi=b[47]<<24|b[46]>>>8,ht=b[46]<<24|b[47]>>>8,ot=b[8]<<27|b[9]>>>5,at=b[9]<<27|b[8]>>>5,We=b[18]<<20|b[19]>>>12,$e=b[19]<<20|b[18]>>>12,vn=b[29]<<7|b[28]>>>25,An=b[28]<<7|b[29]>>>25,ai=b[38]<<8|b[39]>>>24,it=b[39]<<8|b[38]>>>24,Di=b[48]<<14|b[49]>>>18,Qe=b[49]<<14|b[48]>>>18,b[0]=At^~xi&St,b[1]=Et^~bt&Oi,b[10]=Ke^~We&ni,b[11]=ri^~$e&Ye,b[20]=si^~tt&rt,b[21]=et^~oi&nt,b[30]=ot^~ci&ct,b[31]=at^~ut&li,b[40]=dt^~gt&vn,b[41]=hi^~pt&An,b[2]=xi^~St&It,b[3]=bt^~Oi&Tt,b[12]=We^~ni&Je,b[13]=$e^~Ye&ii,b[22]=tt^~rt&ai,b[23]=oi^~nt&it,b[32]=ci^~ct<,b[33]=ut^~li&ft,b[42]=gt^~vn&En,b[43]=pt^~An&bn,b[4]=St^~It&Di,b[5]=Oi^~Tt&Qe,b[14]=ni^~Je&Xe,b[15]=Ye^~ii&Ze,b[24]=rt^~ai&st,b[25]=nt^~it&ui,b[34]=ct^~lt&fi,b[35]=li^~ft&ht,b[44]=vn^~En&Sn,b[45]=An^~bn&In,b[6]=It^~Di&At,b[7]=Tt^~Qe&Et,b[16]=Je^~Xe&Ke,b[17]=ii^~Ze&ri,b[26]=ai^~st&si,b[27]=it^~ui&et,b[36]=lt^~fi&ot,b[37]=ft^~ht&at,b[46]=En^~Sn&dt,b[47]=bn^~In&hi,b[8]=Di^~At&xi,b[9]=Qe^~Et&bt,b[18]=Xe^~Ke&We,b[19]=Ze^~ri&$e,b[28]=st^~si&tt,b[29]=ui^~et&oi,b[38]=fi^~ot&ci,b[39]=ht^~at&ut,b[48]=Sn^~dt>,b[49]=In^~hi&pt,b[0]^=x[W],b[1]^=x[W+1]};if(u)t.exports=g;else for(E=0;E{try{if("test".normalize(e)!=="test")throw new Error("bad normalize")}catch{t.push(e)}}),t.length)throw new Error("missing "+t.join(", "));if("\xE9".normalize("NFD")!=="e\u0301")throw new Error("broken implementation")}catch(t){return t.message}return null}var AM=Hte(),CT;(function(t){t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR",t.OFF="OFF"})(CT||(CT={}));var Si;(function(t){t.UNKNOWN_ERROR="UNKNOWN_ERROR",t.NOT_IMPLEMENTED="NOT_IMPLEMENTED",t.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.TIMEOUT="TIMEOUT",t.BUFFER_OVERRUN="BUFFER_OVERRUN",t.NUMERIC_FAULT="NUMERIC_FAULT",t.MISSING_NEW="MISSING_NEW",t.INVALID_ARGUMENT="INVALID_ARGUMENT",t.MISSING_ARGUMENT="MISSING_ARGUMENT",t.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",t.CALL_EXCEPTION="CALL_EXCEPTION",t.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",t.NONCE_EXPIRED="NONCE_EXPIRED",t.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",t.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",t.TRANSACTION_REPLACED="TRANSACTION_REPLACED",t.ACTION_REJECTED="ACTION_REJECTED"})(Si||(Si={}));var EM="0123456789abcdef",kt=class t{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,r){let n=e.toLowerCase();jm[n]==null&&this.throwArgumentError("invalid log level name","logLevel",e),!(vM>jm[n])&&console.log.apply(console,r)}debug(...e){this._log(t.levels.DEBUG,e)}info(...e){this._log(t.levels.INFO,e)}warn(...e){this._log(t.levels.WARNING,e)}makeError(e,r,n){if(wM)return this.makeError("censored error",r,{});r||(r=t.errors.UNKNOWN_ERROR),n||(n={});let i=[];Object.keys(n).forEach(a=>{let c=n[a];try{if(c instanceof Uint8Array){let f="";for(let d=0;d>4],f+=EM[c[d]&15];i.push(a+"=Uint8Array(0x"+f+")")}else i.push(a+"="+JSON.stringify(c))}catch{i.push(a+"="+JSON.stringify(n[a].toString()))}}),i.push(`code=${r}`),i.push(`version=${this.version}`);let s=e,o="";switch(r){case Si.NUMERIC_FAULT:{o="NUMERIC_FAULT";let a=e;switch(a){case"overflow":case"underflow":case"division-by-zero":o+="-"+a;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result";break}break}case Si.CALL_EXCEPTION:case Si.INSUFFICIENT_FUNDS:case Si.MISSING_NEW:case Si.NONCE_EXPIRED:case Si.REPLACEMENT_UNDERPRICED:case Si.TRANSACTION_REPLACED:case Si.UNPREDICTABLE_GAS_LIMIT:o=r;break}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),i.length&&(e+=" ("+i.join(", ")+")");let u=new Error(e);return u.reason=s,u.code=r,Object.keys(n).forEach(function(a){u[a]=n[a]}),u}throwError(e,r,n){throw this.makeError(e,r,n)}throwArgumentError(e,r,n){return this.throwError(e,t.errors.INVALID_ARGUMENT,{argument:r,value:n})}assert(e,r,n,i){e||this.throwError(r,n,i)}assertArgument(e,r,n,i){e||this.throwArgumentError(r,n,i)}checkNormalize(e){AM&&this.throwError("platform missing String.prototype.normalize",t.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:AM})}checkSafeUint53(e,r){typeof e=="number"&&(r==null&&(r="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(r,t.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,r,n){n?n=": "+n:n="",er&&this.throwError("too many arguments"+n,t.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:r})}checkNew(e,r){(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}checkAbstract(e,r){e===r?this.throwError("cannot instantiate abstract class "+JSON.stringify(r.name)+" directly; use a sub-class",t.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):(e===Object||e==null)&&this.throwError("missing new",t.errors.MISSING_NEW,{name:r.name})}static globalLogger(){return fT||(fT=new t(kte)),fT}static setCensorship(e,r){if(!e&&r&&this.globalLogger().throwError("cannot permanently disable censorship",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),yM){if(!e)return;this.globalLogger().throwError("error censorship permanent",t.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}wM=!!e,yM=!!r}static setLogLevel(e){let r=jm[e.toLowerCase()];if(r==null){t.globalLogger().warn("invalid log level - "+e);return}vM=r}static from(e){return new t(e)}};kt.errors=Si,kt.levels=CT;var Gte="bytes/5.7.0",er=new kt(Gte);function p4(t){return!!t.toHexString}function tl(t){return t.slice||(t.slice=function(){let e=Array.prototype.slice.call(arguments);return tl(new Uint8Array(Array.prototype.slice.apply(t,e)))}),t}function jte(t){return gn(t)&&!(t.length%2)||ul(t)}function bM(t){return typeof t=="number"&&t==t&&t%1===0}function ul(t){if(t==null)return!1;if(t.constructor===Uint8Array)return!0;if(typeof t=="string"||!bM(t.length)||t.length<0)return!1;for(let e=0;e=256)return!1}return!0}function Qt(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid arrayify value");let r=[];for(;t;)r.unshift(t&255),t=parseInt(String(t/256));return r.length===0&&r.push(0),tl(new Uint8Array(r))}if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),p4(t)&&(t=t.toHexString()),gn(t)){let r=t.substring(2);r.length%2&&(e.hexPad==="left"?r="0"+r:e.hexPad==="right"?r+="0":er.throwArgumentError("hex data is odd-length","value",t));let n=[];for(let i=0;iQt(i)),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r);return e.reduce((i,s)=>(n.set(s,i),i+s.length),0),tl(n)}function Qte(t,e){t=Qt(t),t.length>e&&er.throwArgumentError("value out of range","value",arguments[0]);let r=new Uint8Array(e);return r.set(t,e-t.length),tl(r)}function gn(t,e){return!(typeof t!="string"||!t.match(/^0x[0-9A-Fa-f]*$/)||e&&t.length!==2+2*e)}var hT="0123456789abcdef";function kr(t,e){if(e||(e={}),typeof t=="number"){er.checkSafeUint53(t,"invalid hexlify value");let r="";for(;t;)r=hT[t&15]+r,t=Math.floor(t/16);return r.length?(r.length%2&&(r="0"+r),"0x"+r):"0x00"}if(typeof t=="bigint")return t=t.toString(16),t.length%2?"0x0"+t:"0x"+t;if(e.allowMissingPrefix&&typeof t=="string"&&t.substring(0,2)!=="0x"&&(t="0x"+t),p4(t))return t.toHexString();if(gn(t))return t.length%2&&(e.hexPad==="left"?t="0x0"+t.substring(2):e.hexPad==="right"?t+="0":er.throwArgumentError("hex data is odd-length","value",t)),t.toLowerCase();if(ul(t)){let r="0x";for(let n=0;n>4]+hT[i&15]}return r}return er.throwArgumentError("invalid hexlify value","value",t)}function Kte(t){if(typeof t!="string")t=kr(t);else if(!gn(t)||t.length%2)return null;return(t.length-2)/2}function SM(t,e,r){return typeof t!="string"?t=kr(t):(!gn(t)||t.length%2)&&er.throwArgumentError("invalid hexData","value",t),e=2+2*e,r!=null?"0x"+t.substring(e,2+2*r):"0x"+t.substring(e)}function fs(t,e){for(typeof t!="string"?t=kr(t):gn(t)||er.throwArgumentError("invalid hex string","value",t),t.length>2*e+2&&er.throwArgumentError("value out of range","value",arguments[1]);t.length<2*e+2;)t="0x0"+t.substring(2);return t}function m4(t){let e={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(jte(t)){let r=Qt(t);r.length===64?(e.v=27+(r[32]>>7),r[32]&=127,e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64))):r.length===65?(e.r=kr(r.slice(0,32)),e.s=kr(r.slice(32,64)),e.v=r[64]):er.throwArgumentError("invalid signature string","signature",t),e.v<27&&(e.v===0||e.v===1?e.v+=27:er.throwArgumentError("signature invalid v byte","signature",t)),e.recoveryParam=1-e.v%2,e.recoveryParam&&(r[32]|=128),e._vs=kr(r.slice(32,64))}else{if(e.r=t.r,e.s=t.s,e.v=t.v,e.recoveryParam=t.recoveryParam,e._vs=t._vs,e._vs!=null){let i=Qte(Qt(e._vs),32);e._vs=kr(i);let s=i[0]>=128?1:0;e.recoveryParam==null?e.recoveryParam=s:e.recoveryParam!==s&&er.throwArgumentError("signature recoveryParam mismatch _vs","signature",t),i[0]&=127;let o=kr(i);e.s==null?e.s=o:e.s!==o&&er.throwArgumentError("signature v mismatch _vs","signature",t)}if(e.recoveryParam==null)e.v==null?er.throwArgumentError("signature missing v and recoveryParam","signature",t):e.v===0||e.v===1?e.recoveryParam=e.v:e.recoveryParam=1-e.v%2;else if(e.v==null)e.v=27+e.recoveryParam;else{let i=e.v===0||e.v===1?e.v:1-e.v%2;e.recoveryParam!==i&&er.throwArgumentError("signature recoveryParam mismatch v","signature",t)}e.r==null||!gn(e.r)?er.throwArgumentError("signature missing or invalid r","signature",t):e.r=fs(e.r,32),e.s==null||!gn(e.s)?er.throwArgumentError("signature missing or invalid s","signature",t):e.s=fs(e.s,32);let r=Qt(e.s);r[0]>=128&&er.throwArgumentError("signature s out of range","signature",t),e.recoveryParam&&(r[0]|=128);let n=kr(r);e._vs&&(gn(e._vs)||er.throwArgumentError("signature invalid _vs","signature",t),e._vs=fs(e._vs,32)),e._vs==null?e._vs=n:e._vs!==n&&er.throwArgumentError("signature _vs mismatch v and s","signature",t)}return e.yParityAndS=e._vs,e.compact=e.r+e.yParityAndS.substring(2),e}function GT(t){return"0x"+Vte.keccak_256(Qt(t))}var y4={exports:{}},Wte={},$te=Object.freeze({__proto__:null,default:Wte}),Yte=qte($te);(function(t){(function(e,r){function n(l,g){if(!l)throw new Error(g||"Assertion failed")}function i(l,g){l.super_=g;var y=function(){};y.prototype=g.prototype,l.prototype=new y,l.prototype.constructor=l}function s(l,g,y){if(s.isBN(l))return l;this.negative=0,this.words=null,this.length=0,this.red=null,l!==null&&((g==="le"||g==="be")&&(y=g,g=10),this._init(l||0,g||10,y||"be"))}typeof e=="object"?e.exports=s:r.BN=s,s.BN=s,s.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=Yte.Buffer}catch{}s.isBN=function(l){return l instanceof s?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===s.wordSize&&Array.isArray(l.words)},s.max=function(l,g){return l.cmp(g)>0?l:g},s.min=function(l,g){return l.cmp(g)<0?l:g},s.prototype._init=function(l,g,y){if(typeof l=="number")return this._initNumber(l,g,y);if(typeof l=="object")return this._initArray(l,g,y);g==="hex"&&(g=16),n(g===(g|0)&&g>=2&&g<=36),l=l.toString().replace(/\s+/g,"");var E=0;l[0]==="-"&&(E++,this.negative=1),E=0;E-=3)_=l[E]|l[E-1]<<8|l[E-2]<<16,this.words[I]|=_<>>26-M&67108863,M+=24,M>=26&&(M-=26,I++);else if(y==="le")for(E=0,I=0;E>>26-M&67108863,M+=24,M>=26&&(M-=26,I++);return this._strip()};function u(l,g){var y=l.charCodeAt(g);if(y>=48&&y<=57)return y-48;if(y>=65&&y<=70)return y-55;if(y>=97&&y<=102)return y-87;n(!1,"Invalid character in "+l)}function a(l,g,y){var E=u(l,y);return y-1>=g&&(E|=u(l,y-1)<<4),E}s.prototype._parseHex=function(l,g,y){this.length=Math.ceil((l.length-g)/6),this.words=new Array(this.length);for(var E=0;E=g;E-=2)M=a(l,g,E)<=18?(I-=18,_+=1,this.words[_]|=M>>>26):I+=8;else{var N=l.length-g;for(E=N%2===0?g+1:g;E=18?(I-=18,_+=1,this.words[_]|=M>>>26):I+=8}this._strip()};function c(l,g,y,E){for(var I=0,_=0,M=Math.min(l.length,y),N=g;N=49?_=m-49+10:m>=17?_=m-17+10:_=m,n(m>=0&&_1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},s.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{s.prototype[Symbol.for("nodejs.util.inspect.custom")]=d}catch{s.prototype.inspect=d}else s.prototype.inspect=d;function d(){return(this.red?""}var w=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],A=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],T=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];s.prototype.toString=function(l,g){l=l||10,g=g|0||1;var y;if(l===16||l==="hex"){y="";for(var E=0,I=0,_=0;_>>24-E&16777215,E+=2,E>=26&&(E-=26,_--),I!==0||_!==this.length-1?y=w[6-N.length]+N+y:y=N+y}for(I!==0&&(y=I.toString(16)+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(l===(l|0)&&l>=2&&l<=36){var m=A[l],O=T[l];y="";var Y=this.clone();for(Y.negative=0;!Y.isZero();){var $=Y.modrn(O).toString(l);Y=Y.idivn(O),Y.isZero()?y=$+y:y=w[m-$.length]+$+y}for(this.isZero()&&(y="0"+y);y.length%g!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}n(!1,"Base should be between 2 and 36")},s.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},s.prototype.toJSON=function(){return this.toString(16,2)},o&&(s.prototype.toBuffer=function(l,g){return this.toArrayLike(o,l,g)}),s.prototype.toArray=function(l,g){return this.toArrayLike(Array,l,g)};var x=function(l,g){return l.allocUnsafe?l.allocUnsafe(g):new l(g)};s.prototype.toArrayLike=function(l,g,y){this._strip();var E=this.byteLength(),I=y||Math.max(1,E);n(E<=I,"byte array longer than desired length"),n(I>0,"Requested array length <= 0");var _=x(l,I),M=g==="le"?"LE":"BE";return this["_toArrayLike"+M](_,E),_},s.prototype._toArrayLikeLE=function(l,g){for(var y=0,E=0,I=0,_=0;I>8&255),y>16&255),_===6?(y>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y=0&&(l[y--]=M>>8&255),y>=0&&(l[y--]=M>>16&255),_===6?(y>=0&&(l[y--]=M>>24&255),E=0,_=0):(E=M>>>24,_+=2)}if(y>=0)for(l[y--]=E;y>=0;)l[y--]=0},Math.clz32?s.prototype._countBits=function(l){return 32-Math.clz32(l)}:s.prototype._countBits=function(l){var g=l,y=0;return g>=4096&&(y+=13,g>>>=13),g>=64&&(y+=7,g>>>=7),g>=8&&(y+=4,g>>>=4),g>=2&&(y+=2,g>>>=2),y+g},s.prototype._zeroBits=function(l){if(l===0)return 26;var g=l,y=0;return g&8191||(y+=13,g>>>=13),g&127||(y+=7,g>>>=7),g&15||(y+=4,g>>>=4),g&3||(y+=2,g>>>=2),g&1||y++,y},s.prototype.bitLength=function(){var l=this.words[this.length-1],g=this._countBits(l);return(this.length-1)*26+g};function B(l){for(var g=new Array(l.bitLength()),y=0;y>>I&1}return g}s.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,g=0;gl.length?this.clone().ior(l):l.clone().ior(this)},s.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},s.prototype.iuand=function(l){var g;this.length>l.length?g=l:g=this;for(var y=0;yl.length?this.clone().iand(l):l.clone().iand(this)},s.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},s.prototype.iuxor=function(l){var g,y;this.length>l.length?(g=this,y=l):(g=l,y=this);for(var E=0;El.length?this.clone().ixor(l):l.clone().ixor(this)},s.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},s.prototype.inotn=function(l){n(typeof l=="number"&&l>=0);var g=Math.ceil(l/26)|0,y=l%26;this._expand(g),y>0&&g--;for(var E=0;E0&&(this.words[E]=~this.words[E]&67108863>>26-y),this._strip()},s.prototype.notn=function(l){return this.clone().inotn(l)},s.prototype.setn=function(l,g){n(typeof l=="number"&&l>=0);var y=l/26|0,E=l%26;return this._expand(y+1),g?this.words[y]=this.words[y]|1<l.length?(y=this,E=l):(y=l,E=this);for(var I=0,_=0;_>>26;for(;I!==0&&_>>26;if(this.length=y.length,I!==0)this.words[this.length]=I,this.length++;else if(y!==this)for(;_l.length?this.clone().iadd(l):l.clone().iadd(this)},s.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var g=this.iadd(l);return l.negative=1,g._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var y=this.cmp(l);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var E,I;y>0?(E=this,I=l):(E=l,I=this);for(var _=0,M=0;M>26,this.words[M]=g&67108863;for(;_!==0&&M>26,this.words[M]=g&67108863;if(_===0&&M>>26,$=m&67108863,b=Math.min(O,g.length-1),j=Math.max(0,O-l.length+1);j<=b;j++){var z=O-j|0;I=l.words[z]|0,_=g.words[j]|0,M=I*_+$,Y+=M/67108864|0,$=M&67108863}y.words[O]=$|0,m=Y|0}return m!==0?y.words[O]=m|0:y.length--,y._strip()}var U=function(l,g,y){var E=l.words,I=g.words,_=y.words,M=0,N,m,O,Y=E[0]|0,$=Y&8191,b=Y>>>13,j=E[1]|0,z=j&8191,W=j>>>13,ie=E[2]|0,te=ie&8191,ee=ie>>>13,se=E[3]|0,oe=se&8191,J=se>>>13,ue=E[4]|0,wt=ue&8191,vt=ue>>>13,Ni=E[5]|0,At=Ni&8191,Et=Ni>>>13,xi=E[6]|0,bt=xi&8191,St=xi>>>13,Oi=E[7]|0,It=Oi&8191,Tt=Oi>>>13,Di=E[8]|0,Qe=Di&8191,Ke=Di>>>13,ri=E[9]|0,We=ri&8191,$e=ri>>>13,ni=I[0]|0,Ye=ni&8191,Je=ni>>>13,ii=I[1]|0,Xe=ii&8191,Ze=ii>>>13,si=I[2]|0,et=si&8191,tt=si>>>13,oi=I[3]|0,rt=oi&8191,nt=oi>>>13,ai=I[4]|0,it=ai&8191,st=ai>>>13,ui=I[5]|0,ot=ui&8191,at=ui>>>13,ci=I[6]|0,ut=ci&8191,ct=ci>>>13,li=I[7]|0,lt=li&8191,ft=li>>>13,fi=I[8]|0,ht=fi&8191,dt=fi>>>13,hi=I[9]|0,gt=hi&8191,pt=hi>>>13;y.negative=l.negative^g.negative,y.length=19,N=Math.imul($,Ye),m=Math.imul($,Je),m=m+Math.imul(b,Ye)|0,O=Math.imul(b,Je);var vn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(vn>>>26)|0,vn&=67108863,N=Math.imul(z,Ye),m=Math.imul(z,Je),m=m+Math.imul(W,Ye)|0,O=Math.imul(W,Je),N=N+Math.imul($,Xe)|0,m=m+Math.imul($,Ze)|0,m=m+Math.imul(b,Xe)|0,O=O+Math.imul(b,Ze)|0;var An=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(An>>>26)|0,An&=67108863,N=Math.imul(te,Ye),m=Math.imul(te,Je),m=m+Math.imul(ee,Ye)|0,O=Math.imul(ee,Je),N=N+Math.imul(z,Xe)|0,m=m+Math.imul(z,Ze)|0,m=m+Math.imul(W,Xe)|0,O=O+Math.imul(W,Ze)|0,N=N+Math.imul($,et)|0,m=m+Math.imul($,tt)|0,m=m+Math.imul(b,et)|0,O=O+Math.imul(b,tt)|0;var En=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(En>>>26)|0,En&=67108863,N=Math.imul(oe,Ye),m=Math.imul(oe,Je),m=m+Math.imul(J,Ye)|0,O=Math.imul(J,Je),N=N+Math.imul(te,Xe)|0,m=m+Math.imul(te,Ze)|0,m=m+Math.imul(ee,Xe)|0,O=O+Math.imul(ee,Ze)|0,N=N+Math.imul(z,et)|0,m=m+Math.imul(z,tt)|0,m=m+Math.imul(W,et)|0,O=O+Math.imul(W,tt)|0,N=N+Math.imul($,rt)|0,m=m+Math.imul($,nt)|0,m=m+Math.imul(b,rt)|0,O=O+Math.imul(b,nt)|0;var bn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(bn>>>26)|0,bn&=67108863,N=Math.imul(wt,Ye),m=Math.imul(wt,Je),m=m+Math.imul(vt,Ye)|0,O=Math.imul(vt,Je),N=N+Math.imul(oe,Xe)|0,m=m+Math.imul(oe,Ze)|0,m=m+Math.imul(J,Xe)|0,O=O+Math.imul(J,Ze)|0,N=N+Math.imul(te,et)|0,m=m+Math.imul(te,tt)|0,m=m+Math.imul(ee,et)|0,O=O+Math.imul(ee,tt)|0,N=N+Math.imul(z,rt)|0,m=m+Math.imul(z,nt)|0,m=m+Math.imul(W,rt)|0,O=O+Math.imul(W,nt)|0,N=N+Math.imul($,it)|0,m=m+Math.imul($,st)|0,m=m+Math.imul(b,it)|0,O=O+Math.imul(b,st)|0;var Sn=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Sn>>>26)|0,Sn&=67108863,N=Math.imul(At,Ye),m=Math.imul(At,Je),m=m+Math.imul(Et,Ye)|0,O=Math.imul(Et,Je),N=N+Math.imul(wt,Xe)|0,m=m+Math.imul(wt,Ze)|0,m=m+Math.imul(vt,Xe)|0,O=O+Math.imul(vt,Ze)|0,N=N+Math.imul(oe,et)|0,m=m+Math.imul(oe,tt)|0,m=m+Math.imul(J,et)|0,O=O+Math.imul(J,tt)|0,N=N+Math.imul(te,rt)|0,m=m+Math.imul(te,nt)|0,m=m+Math.imul(ee,rt)|0,O=O+Math.imul(ee,nt)|0,N=N+Math.imul(z,it)|0,m=m+Math.imul(z,st)|0,m=m+Math.imul(W,it)|0,O=O+Math.imul(W,st)|0,N=N+Math.imul($,ot)|0,m=m+Math.imul($,at)|0,m=m+Math.imul(b,ot)|0,O=O+Math.imul(b,at)|0;var In=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(In>>>26)|0,In&=67108863,N=Math.imul(bt,Ye),m=Math.imul(bt,Je),m=m+Math.imul(St,Ye)|0,O=Math.imul(St,Je),N=N+Math.imul(At,Xe)|0,m=m+Math.imul(At,Ze)|0,m=m+Math.imul(Et,Xe)|0,O=O+Math.imul(Et,Ze)|0,N=N+Math.imul(wt,et)|0,m=m+Math.imul(wt,tt)|0,m=m+Math.imul(vt,et)|0,O=O+Math.imul(vt,tt)|0,N=N+Math.imul(oe,rt)|0,m=m+Math.imul(oe,nt)|0,m=m+Math.imul(J,rt)|0,O=O+Math.imul(J,nt)|0,N=N+Math.imul(te,it)|0,m=m+Math.imul(te,st)|0,m=m+Math.imul(ee,it)|0,O=O+Math.imul(ee,st)|0,N=N+Math.imul(z,ot)|0,m=m+Math.imul(z,at)|0,m=m+Math.imul(W,ot)|0,O=O+Math.imul(W,at)|0,N=N+Math.imul($,ut)|0,m=m+Math.imul($,ct)|0,m=m+Math.imul(b,ut)|0,O=O+Math.imul(b,ct)|0;var ha=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ha>>>26)|0,ha&=67108863,N=Math.imul(It,Ye),m=Math.imul(It,Je),m=m+Math.imul(Tt,Ye)|0,O=Math.imul(Tt,Je),N=N+Math.imul(bt,Xe)|0,m=m+Math.imul(bt,Ze)|0,m=m+Math.imul(St,Xe)|0,O=O+Math.imul(St,Ze)|0,N=N+Math.imul(At,et)|0,m=m+Math.imul(At,tt)|0,m=m+Math.imul(Et,et)|0,O=O+Math.imul(Et,tt)|0,N=N+Math.imul(wt,rt)|0,m=m+Math.imul(wt,nt)|0,m=m+Math.imul(vt,rt)|0,O=O+Math.imul(vt,nt)|0,N=N+Math.imul(oe,it)|0,m=m+Math.imul(oe,st)|0,m=m+Math.imul(J,it)|0,O=O+Math.imul(J,st)|0,N=N+Math.imul(te,ot)|0,m=m+Math.imul(te,at)|0,m=m+Math.imul(ee,ot)|0,O=O+Math.imul(ee,at)|0,N=N+Math.imul(z,ut)|0,m=m+Math.imul(z,ct)|0,m=m+Math.imul(W,ut)|0,O=O+Math.imul(W,ct)|0,N=N+Math.imul($,lt)|0,m=m+Math.imul($,ft)|0,m=m+Math.imul(b,lt)|0,O=O+Math.imul(b,ft)|0;var da=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(da>>>26)|0,da&=67108863,N=Math.imul(Qe,Ye),m=Math.imul(Qe,Je),m=m+Math.imul(Ke,Ye)|0,O=Math.imul(Ke,Je),N=N+Math.imul(It,Xe)|0,m=m+Math.imul(It,Ze)|0,m=m+Math.imul(Tt,Xe)|0,O=O+Math.imul(Tt,Ze)|0,N=N+Math.imul(bt,et)|0,m=m+Math.imul(bt,tt)|0,m=m+Math.imul(St,et)|0,O=O+Math.imul(St,tt)|0,N=N+Math.imul(At,rt)|0,m=m+Math.imul(At,nt)|0,m=m+Math.imul(Et,rt)|0,O=O+Math.imul(Et,nt)|0,N=N+Math.imul(wt,it)|0,m=m+Math.imul(wt,st)|0,m=m+Math.imul(vt,it)|0,O=O+Math.imul(vt,st)|0,N=N+Math.imul(oe,ot)|0,m=m+Math.imul(oe,at)|0,m=m+Math.imul(J,ot)|0,O=O+Math.imul(J,at)|0,N=N+Math.imul(te,ut)|0,m=m+Math.imul(te,ct)|0,m=m+Math.imul(ee,ut)|0,O=O+Math.imul(ee,ct)|0,N=N+Math.imul(z,lt)|0,m=m+Math.imul(z,ft)|0,m=m+Math.imul(W,lt)|0,O=O+Math.imul(W,ft)|0,N=N+Math.imul($,ht)|0,m=m+Math.imul($,dt)|0,m=m+Math.imul(b,ht)|0,O=O+Math.imul(b,dt)|0;var ga=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ga>>>26)|0,ga&=67108863,N=Math.imul(We,Ye),m=Math.imul(We,Je),m=m+Math.imul($e,Ye)|0,O=Math.imul($e,Je),N=N+Math.imul(Qe,Xe)|0,m=m+Math.imul(Qe,Ze)|0,m=m+Math.imul(Ke,Xe)|0,O=O+Math.imul(Ke,Ze)|0,N=N+Math.imul(It,et)|0,m=m+Math.imul(It,tt)|0,m=m+Math.imul(Tt,et)|0,O=O+Math.imul(Tt,tt)|0,N=N+Math.imul(bt,rt)|0,m=m+Math.imul(bt,nt)|0,m=m+Math.imul(St,rt)|0,O=O+Math.imul(St,nt)|0,N=N+Math.imul(At,it)|0,m=m+Math.imul(At,st)|0,m=m+Math.imul(Et,it)|0,O=O+Math.imul(Et,st)|0,N=N+Math.imul(wt,ot)|0,m=m+Math.imul(wt,at)|0,m=m+Math.imul(vt,ot)|0,O=O+Math.imul(vt,at)|0,N=N+Math.imul(oe,ut)|0,m=m+Math.imul(oe,ct)|0,m=m+Math.imul(J,ut)|0,O=O+Math.imul(J,ct)|0,N=N+Math.imul(te,lt)|0,m=m+Math.imul(te,ft)|0,m=m+Math.imul(ee,lt)|0,O=O+Math.imul(ee,ft)|0,N=N+Math.imul(z,ht)|0,m=m+Math.imul(z,dt)|0,m=m+Math.imul(W,ht)|0,O=O+Math.imul(W,dt)|0,N=N+Math.imul($,gt)|0,m=m+Math.imul($,pt)|0,m=m+Math.imul(b,gt)|0,O=O+Math.imul(b,pt)|0;var pa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pa>>>26)|0,pa&=67108863,N=Math.imul(We,Xe),m=Math.imul(We,Ze),m=m+Math.imul($e,Xe)|0,O=Math.imul($e,Ze),N=N+Math.imul(Qe,et)|0,m=m+Math.imul(Qe,tt)|0,m=m+Math.imul(Ke,et)|0,O=O+Math.imul(Ke,tt)|0,N=N+Math.imul(It,rt)|0,m=m+Math.imul(It,nt)|0,m=m+Math.imul(Tt,rt)|0,O=O+Math.imul(Tt,nt)|0,N=N+Math.imul(bt,it)|0,m=m+Math.imul(bt,st)|0,m=m+Math.imul(St,it)|0,O=O+Math.imul(St,st)|0,N=N+Math.imul(At,ot)|0,m=m+Math.imul(At,at)|0,m=m+Math.imul(Et,ot)|0,O=O+Math.imul(Et,at)|0,N=N+Math.imul(wt,ut)|0,m=m+Math.imul(wt,ct)|0,m=m+Math.imul(vt,ut)|0,O=O+Math.imul(vt,ct)|0,N=N+Math.imul(oe,lt)|0,m=m+Math.imul(oe,ft)|0,m=m+Math.imul(J,lt)|0,O=O+Math.imul(J,ft)|0,N=N+Math.imul(te,ht)|0,m=m+Math.imul(te,dt)|0,m=m+Math.imul(ee,ht)|0,O=O+Math.imul(ee,dt)|0,N=N+Math.imul(z,gt)|0,m=m+Math.imul(z,pt)|0,m=m+Math.imul(W,gt)|0,O=O+Math.imul(W,pt)|0;var ma=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ma>>>26)|0,ma&=67108863,N=Math.imul(We,et),m=Math.imul(We,tt),m=m+Math.imul($e,et)|0,O=Math.imul($e,tt),N=N+Math.imul(Qe,rt)|0,m=m+Math.imul(Qe,nt)|0,m=m+Math.imul(Ke,rt)|0,O=O+Math.imul(Ke,nt)|0,N=N+Math.imul(It,it)|0,m=m+Math.imul(It,st)|0,m=m+Math.imul(Tt,it)|0,O=O+Math.imul(Tt,st)|0,N=N+Math.imul(bt,ot)|0,m=m+Math.imul(bt,at)|0,m=m+Math.imul(St,ot)|0,O=O+Math.imul(St,at)|0,N=N+Math.imul(At,ut)|0,m=m+Math.imul(At,ct)|0,m=m+Math.imul(Et,ut)|0,O=O+Math.imul(Et,ct)|0,N=N+Math.imul(wt,lt)|0,m=m+Math.imul(wt,ft)|0,m=m+Math.imul(vt,lt)|0,O=O+Math.imul(vt,ft)|0,N=N+Math.imul(oe,ht)|0,m=m+Math.imul(oe,dt)|0,m=m+Math.imul(J,ht)|0,O=O+Math.imul(J,dt)|0,N=N+Math.imul(te,gt)|0,m=m+Math.imul(te,pt)|0,m=m+Math.imul(ee,gt)|0,O=O+Math.imul(ee,pt)|0;var ya=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(ya>>>26)|0,ya&=67108863,N=Math.imul(We,rt),m=Math.imul(We,nt),m=m+Math.imul($e,rt)|0,O=Math.imul($e,nt),N=N+Math.imul(Qe,it)|0,m=m+Math.imul(Qe,st)|0,m=m+Math.imul(Ke,it)|0,O=O+Math.imul(Ke,st)|0,N=N+Math.imul(It,ot)|0,m=m+Math.imul(It,at)|0,m=m+Math.imul(Tt,ot)|0,O=O+Math.imul(Tt,at)|0,N=N+Math.imul(bt,ut)|0,m=m+Math.imul(bt,ct)|0,m=m+Math.imul(St,ut)|0,O=O+Math.imul(St,ct)|0,N=N+Math.imul(At,lt)|0,m=m+Math.imul(At,ft)|0,m=m+Math.imul(Et,lt)|0,O=O+Math.imul(Et,ft)|0,N=N+Math.imul(wt,ht)|0,m=m+Math.imul(wt,dt)|0,m=m+Math.imul(vt,ht)|0,O=O+Math.imul(vt,dt)|0,N=N+Math.imul(oe,gt)|0,m=m+Math.imul(oe,pt)|0,m=m+Math.imul(J,gt)|0,O=O+Math.imul(J,pt)|0;var wa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(wa>>>26)|0,wa&=67108863,N=Math.imul(We,it),m=Math.imul(We,st),m=m+Math.imul($e,it)|0,O=Math.imul($e,st),N=N+Math.imul(Qe,ot)|0,m=m+Math.imul(Qe,at)|0,m=m+Math.imul(Ke,ot)|0,O=O+Math.imul(Ke,at)|0,N=N+Math.imul(It,ut)|0,m=m+Math.imul(It,ct)|0,m=m+Math.imul(Tt,ut)|0,O=O+Math.imul(Tt,ct)|0,N=N+Math.imul(bt,lt)|0,m=m+Math.imul(bt,ft)|0,m=m+Math.imul(St,lt)|0,O=O+Math.imul(St,ft)|0,N=N+Math.imul(At,ht)|0,m=m+Math.imul(At,dt)|0,m=m+Math.imul(Et,ht)|0,O=O+Math.imul(Et,dt)|0,N=N+Math.imul(wt,gt)|0,m=m+Math.imul(wt,pt)|0,m=m+Math.imul(vt,gt)|0,O=O+Math.imul(vt,pt)|0;var va=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(va>>>26)|0,va&=67108863,N=Math.imul(We,ot),m=Math.imul(We,at),m=m+Math.imul($e,ot)|0,O=Math.imul($e,at),N=N+Math.imul(Qe,ut)|0,m=m+Math.imul(Qe,ct)|0,m=m+Math.imul(Ke,ut)|0,O=O+Math.imul(Ke,ct)|0,N=N+Math.imul(It,lt)|0,m=m+Math.imul(It,ft)|0,m=m+Math.imul(Tt,lt)|0,O=O+Math.imul(Tt,ft)|0,N=N+Math.imul(bt,ht)|0,m=m+Math.imul(bt,dt)|0,m=m+Math.imul(St,ht)|0,O=O+Math.imul(St,dt)|0,N=N+Math.imul(At,gt)|0,m=m+Math.imul(At,pt)|0,m=m+Math.imul(Et,gt)|0,O=O+Math.imul(Et,pt)|0;var Aa=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(Aa>>>26)|0,Aa&=67108863,N=Math.imul(We,ut),m=Math.imul(We,ct),m=m+Math.imul($e,ut)|0,O=Math.imul($e,ct),N=N+Math.imul(Qe,lt)|0,m=m+Math.imul(Qe,ft)|0,m=m+Math.imul(Ke,lt)|0,O=O+Math.imul(Ke,ft)|0,N=N+Math.imul(It,ht)|0,m=m+Math.imul(It,dt)|0,m=m+Math.imul(Tt,ht)|0,O=O+Math.imul(Tt,dt)|0,N=N+Math.imul(bt,gt)|0,m=m+Math.imul(bt,pt)|0,m=m+Math.imul(St,gt)|0,O=O+Math.imul(St,pt)|0;var dw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(dw>>>26)|0,dw&=67108863,N=Math.imul(We,lt),m=Math.imul(We,ft),m=m+Math.imul($e,lt)|0,O=Math.imul($e,ft),N=N+Math.imul(Qe,ht)|0,m=m+Math.imul(Qe,dt)|0,m=m+Math.imul(Ke,ht)|0,O=O+Math.imul(Ke,dt)|0,N=N+Math.imul(It,gt)|0,m=m+Math.imul(It,pt)|0,m=m+Math.imul(Tt,gt)|0,O=O+Math.imul(Tt,pt)|0;var gw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(gw>>>26)|0,gw&=67108863,N=Math.imul(We,ht),m=Math.imul(We,dt),m=m+Math.imul($e,ht)|0,O=Math.imul($e,dt),N=N+Math.imul(Qe,gt)|0,m=m+Math.imul(Qe,pt)|0,m=m+Math.imul(Ke,gt)|0,O=O+Math.imul(Ke,pt)|0;var pw=(M+N|0)+((m&8191)<<13)|0;M=(O+(m>>>13)|0)+(pw>>>26)|0,pw&=67108863,N=Math.imul(We,gt),m=Math.imul(We,pt),m=m+Math.imul($e,gt)|0,O=Math.imul($e,pt);var mw=(M+N|0)+((m&8191)<<13)|0;return M=(O+(m>>>13)|0)+(mw>>>26)|0,mw&=67108863,_[0]=vn,_[1]=An,_[2]=En,_[3]=bn,_[4]=Sn,_[5]=In,_[6]=ha,_[7]=da,_[8]=ga,_[9]=pa,_[10]=ma,_[11]=ya,_[12]=wa,_[13]=va,_[14]=Aa,_[15]=dw,_[16]=gw,_[17]=pw,_[18]=mw,M!==0&&(_[19]=M,y.length++),y};Math.imul||(U=V);function Q(l,g,y){y.negative=g.negative^l.negative,y.length=l.length+g.length;for(var E=0,I=0,_=0;_>>26)|0,I+=M>>>26,M&=67108863}y.words[_]=N,E=M,M=I}return E!==0?y.words[_]=E:y.length--,y._strip()}function L(l,g,y){return Q(l,g,y)}s.prototype.mulTo=function(l,g){var y,E=this.length+l.length;return this.length===10&&l.length===10?y=U(this,l,g):E<63?y=V(this,l,g):E<1024?y=Q(this,l,g):y=L(this,l,g),y},s.prototype.mul=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),this.mulTo(l,g)},s.prototype.mulf=function(l){var g=new s(null);return g.words=new Array(this.length+l.length),L(this,l,g)},s.prototype.imul=function(l){return this.clone().mulTo(l,this)},s.prototype.imuln=function(l){var g=l<0;g&&(l=-l),n(typeof l=="number"),n(l<67108864);for(var y=0,E=0;E>=26,y+=I/67108864|0,y+=_>>>26,this.words[E]=_&67108863}return y!==0&&(this.words[E]=y,this.length++),g?this.ineg():this},s.prototype.muln=function(l){return this.clone().imuln(l)},s.prototype.sqr=function(){return this.mul(this)},s.prototype.isqr=function(){return this.imul(this.clone())},s.prototype.pow=function(l){var g=B(l);if(g.length===0)return new s(1);for(var y=this,E=0;E=0);var g=l%26,y=(l-g)/26,E=67108863>>>26-g<<26-g,I;if(g!==0){var _=0;for(I=0;I>>26-g}_&&(this.words[I]=_,this.length++)}if(y!==0){for(I=this.length-1;I>=0;I--)this.words[I+y]=this.words[I];for(I=0;I=0);var E;g?E=(g-g%26)/26:E=0;var I=l%26,_=Math.min((l-I)/26,this.length),M=67108863^67108863>>>I<_)for(this.length-=_,m=0;m=0&&(O!==0||m>=E);m--){var Y=this.words[m]|0;this.words[m]=O<<26-I|Y>>>I,O=Y&M}return N&&O!==0&&(N.words[N.length++]=O),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},s.prototype.ishrn=function(l,g,y){return n(this.negative===0),this.iushrn(l,g,y)},s.prototype.shln=function(l){return this.clone().ishln(l)},s.prototype.ushln=function(l){return this.clone().iushln(l)},s.prototype.shrn=function(l){return this.clone().ishrn(l)},s.prototype.ushrn=function(l){return this.clone().iushrn(l)},s.prototype.testn=function(l){n(typeof l=="number"&&l>=0);var g=l%26,y=(l-g)/26,E=1<=0);var g=l%26,y=(l-g)/26;if(n(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(g!==0&&y++,this.length=Math.min(y,this.length),g!==0){var E=67108863^67108863>>>g<=67108864;g++)this.words[g]-=67108864,g===this.length-1?this.words[g+1]=1:this.words[g+1]++;return this.length=Math.max(this.length,g+1),this},s.prototype.isubn=function(l){if(n(typeof l=="number"),n(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var g=0;g>26)-(N/67108864|0),this.words[I+y]=_&67108863}for(;I>26,this.words[I+y]=_&67108863;if(M===0)return this._strip();for(n(M===-1),M=0,I=0;I>26,this.words[I]=_&67108863;return this.negative=1,this._strip()},s.prototype._wordDiv=function(l,g){var y=this.length-l.length,E=this.clone(),I=l,_=I.words[I.length-1]|0,M=this._countBits(_);y=26-M,y!==0&&(I=I.ushln(y),E.iushln(y),_=I.words[I.length-1]|0);var N=E.length-I.length,m;if(g!=="mod"){m=new s(null),m.length=N+1,m.words=new Array(m.length);for(var O=0;O=0;$--){var b=(E.words[I.length+$]|0)*67108864+(E.words[I.length+$-1]|0);for(b=Math.min(b/_|0,67108863),E._ishlnsubmul(I,b,$);E.negative!==0;)b--,E.negative=0,E._ishlnsubmul(I,1,$),E.isZero()||(E.negative^=1);m&&(m.words[$]=b)}return m&&m._strip(),E._strip(),g!=="div"&&y!==0&&E.iushrn(y),{div:m||null,mod:E}},s.prototype.divmod=function(l,g,y){if(n(!l.isZero()),this.isZero())return{div:new s(0),mod:new s(0)};var E,I,_;return this.negative!==0&&l.negative===0?(_=this.neg().divmod(l,g),g!=="mod"&&(E=_.div.neg()),g!=="div"&&(I=_.mod.neg(),y&&I.negative!==0&&I.iadd(l)),{div:E,mod:I}):this.negative===0&&l.negative!==0?(_=this.divmod(l.neg(),g),g!=="mod"&&(E=_.div.neg()),{div:E,mod:_.mod}):this.negative&l.negative?(_=this.neg().divmod(l.neg(),g),g!=="div"&&(I=_.mod.neg(),y&&I.negative!==0&&I.isub(l)),{div:_.div,mod:I}):l.length>this.length||this.cmp(l)<0?{div:new s(0),mod:this}:l.length===1?g==="div"?{div:this.divn(l.words[0]),mod:null}:g==="mod"?{div:null,mod:new s(this.modrn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new s(this.modrn(l.words[0]))}:this._wordDiv(l,g)},s.prototype.div=function(l){return this.divmod(l,"div",!1).div},s.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},s.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},s.prototype.divRound=function(l){var g=this.divmod(l);if(g.mod.isZero())return g.div;var y=g.div.negative!==0?g.mod.isub(l):g.mod,E=l.ushrn(1),I=l.andln(1),_=y.cmp(E);return _<0||I===1&&_===0?g.div:g.div.negative!==0?g.div.isubn(1):g.div.iaddn(1)},s.prototype.modrn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=(1<<26)%l,E=0,I=this.length-1;I>=0;I--)E=(y*E+(this.words[I]|0))%l;return g?-E:E},s.prototype.modn=function(l){return this.modrn(l)},s.prototype.idivn=function(l){var g=l<0;g&&(l=-l),n(l<=67108863);for(var y=0,E=this.length-1;E>=0;E--){var I=(this.words[E]|0)+y*67108864;this.words[E]=I/l|0,y=I%l}return this._strip(),g?this.ineg():this},s.prototype.divn=function(l){return this.clone().idivn(l)},s.prototype.egcd=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),I=new s(0),_=new s(0),M=new s(1),N=0;g.isEven()&&y.isEven();)g.iushrn(1),y.iushrn(1),++N;for(var m=y.clone(),O=g.clone();!g.isZero();){for(var Y=0,$=1;!(g.words[0]&$)&&Y<26;++Y,$<<=1);if(Y>0)for(g.iushrn(Y);Y-- >0;)(E.isOdd()||I.isOdd())&&(E.iadd(m),I.isub(O)),E.iushrn(1),I.iushrn(1);for(var b=0,j=1;!(y.words[0]&j)&&b<26;++b,j<<=1);if(b>0)for(y.iushrn(b);b-- >0;)(_.isOdd()||M.isOdd())&&(_.iadd(m),M.isub(O)),_.iushrn(1),M.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(_),I.isub(M)):(y.isub(g),_.isub(E),M.isub(I))}return{a:_,b:M,gcd:y.iushln(N)}},s.prototype._invmp=function(l){n(l.negative===0),n(!l.isZero());var g=this,y=l.clone();g.negative!==0?g=g.umod(l):g=g.clone();for(var E=new s(1),I=new s(0),_=y.clone();g.cmpn(1)>0&&y.cmpn(1)>0;){for(var M=0,N=1;!(g.words[0]&N)&&M<26;++M,N<<=1);if(M>0)for(g.iushrn(M);M-- >0;)E.isOdd()&&E.iadd(_),E.iushrn(1);for(var m=0,O=1;!(y.words[0]&O)&&m<26;++m,O<<=1);if(m>0)for(y.iushrn(m);m-- >0;)I.isOdd()&&I.iadd(_),I.iushrn(1);g.cmp(y)>=0?(g.isub(y),E.isub(I)):(y.isub(g),I.isub(E))}var Y;return g.cmpn(1)===0?Y=E:Y=I,Y.cmpn(0)<0&&Y.iadd(l),Y},s.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var g=this.clone(),y=l.clone();g.negative=0,y.negative=0;for(var E=0;g.isEven()&&y.isEven();E++)g.iushrn(1),y.iushrn(1);do{for(;g.isEven();)g.iushrn(1);for(;y.isEven();)y.iushrn(1);var I=g.cmp(y);if(I<0){var _=g;g=y,y=_}else if(I===0||y.cmpn(1)===0)break;g.isub(y)}while(!0);return y.iushln(E)},s.prototype.invm=function(l){return this.egcd(l).a.umod(l)},s.prototype.isEven=function(){return(this.words[0]&1)===0},s.prototype.isOdd=function(){return(this.words[0]&1)===1},s.prototype.andln=function(l){return this.words[0]&l},s.prototype.bincn=function(l){n(typeof l=="number");var g=l%26,y=(l-g)/26,E=1<>>26,M&=67108863,this.words[_]=M}return I!==0&&(this.words[_]=I,this.length++),this},s.prototype.isZero=function(){return this.length===1&&this.words[0]===0},s.prototype.cmpn=function(l){var g=l<0;if(this.negative!==0&&!g)return-1;if(this.negative===0&&g)return 1;this._strip();var y;if(this.length>1)y=1;else{g&&(l=-l),n(l<=67108863,"Number is too big");var E=this.words[0]|0;y=E===l?0:El.length)return 1;if(this.length=0;y--){var E=this.words[y]|0,I=l.words[y]|0;if(E!==I){EI&&(g=1);break}}return g},s.prototype.gtn=function(l){return this.cmpn(l)===1},s.prototype.gt=function(l){return this.cmp(l)===1},s.prototype.gten=function(l){return this.cmpn(l)>=0},s.prototype.gte=function(l){return this.cmp(l)>=0},s.prototype.ltn=function(l){return this.cmpn(l)===-1},s.prototype.lt=function(l){return this.cmp(l)===-1},s.prototype.lten=function(l){return this.cmpn(l)<=0},s.prototype.lte=function(l){return this.cmp(l)<=0},s.prototype.eqn=function(l){return this.cmpn(l)===0},s.prototype.eq=function(l){return this.cmp(l)===0},s.red=function(l){return new F(l)},s.prototype.toRed=function(l){return n(!this.red,"Already a number in reduction context"),n(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},s.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},s.prototype._forceRed=function(l){return this.red=l,this},s.prototype.forceRed=function(l){return n(!this.red,"Already a number in reduction context"),this._forceRed(l)},s.prototype.redAdd=function(l){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},s.prototype.redIAdd=function(l){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},s.prototype.redSub=function(l){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},s.prototype.redISub=function(l){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},s.prototype.redShl=function(l){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},s.prototype.redMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},s.prototype.redIMul=function(l){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},s.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},s.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},s.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},s.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},s.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},s.prototype.redPow=function(l){return n(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var k={k256:null,p224:null,p192:null,p25519:null};function H(l,g){this.name=l,this.p=new s(g,16),this.n=this.p.bitLength(),this.k=new s(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}H.prototype._tmp=function(){var l=new s(null);return l.words=new Array(Math.ceil(this.n/13)),l},H.prototype.ireduce=function(l){var g=l,y;do this.split(g,this.tmp),g=this.imulK(g),g=g.iadd(this.tmp),y=g.bitLength();while(y>this.n);var E=y0?g.isub(this.p):g.strip!==void 0?g.strip():g._strip(),g},H.prototype.split=function(l,g){l.iushrn(this.n,0,g)},H.prototype.imulK=function(l){return l.imul(this.k)};function q(){H.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(q,H),q.prototype.split=function(l,g){for(var y=4194303,E=Math.min(l.length,9),I=0;I>>22,_=M}_>>>=22,l.words[I-10]=_,_===0&&l.length>10?l.length-=10:l.length-=9},q.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var g=0,y=0;y>>=26,l.words[y]=I,g=E}return g!==0&&(l.words[l.length++]=g),l},s._prime=function(l){if(k[l])return k[l];var g;if(l==="k256")g=new q;else if(l==="p224")g=new v;else if(l==="p192")g=new C;else if(l==="p25519")g=new P;else throw new Error("Unknown prime "+l);return k[l]=g,g};function F(l){if(typeof l=="string"){var g=s._prime(l);this.m=g.p,this.prime=g}else n(l.gtn(1),"modulus must be greater than 1"),this.m=l,this.prime=null}F.prototype._verify1=function(l){n(l.negative===0,"red works only with positives"),n(l.red,"red works only with red numbers")},F.prototype._verify2=function(l,g){n((l.negative|g.negative)===0,"red works only with positives"),n(l.red&&l.red===g.red,"red works only with red numbers")},F.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):(f(l,l.umod(this.m)._forceRed(this)),l)},F.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},F.prototype.add=function(l,g){this._verify2(l,g);var y=l.add(g);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},F.prototype.iadd=function(l,g){this._verify2(l,g);var y=l.iadd(g);return y.cmp(this.m)>=0&&y.isub(this.m),y},F.prototype.sub=function(l,g){this._verify2(l,g);var y=l.sub(g);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},F.prototype.isub=function(l,g){this._verify2(l,g);var y=l.isub(g);return y.cmpn(0)<0&&y.iadd(this.m),y},F.prototype.shl=function(l,g){return this._verify1(l),this.imod(l.ushln(g))},F.prototype.imul=function(l,g){return this._verify2(l,g),this.imod(l.imul(g))},F.prototype.mul=function(l,g){return this._verify2(l,g),this.imod(l.mul(g))},F.prototype.isqr=function(l){return this.imul(l,l.clone())},F.prototype.sqr=function(l){return this.mul(l,l)},F.prototype.sqrt=function(l){if(l.isZero())return l.clone();var g=this.m.andln(3);if(n(g%2===1),g===3){var y=this.m.add(new s(1)).iushrn(2);return this.pow(l,y)}for(var E=this.m.subn(1),I=0;!E.isZero()&&E.andln(1)===0;)I++,E.iushrn(1);n(!E.isZero());var _=new s(1).toRed(this),M=_.redNeg(),N=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new s(2*m*m).toRed(this);this.pow(m,N).cmp(M)!==0;)m.redIAdd(M);for(var O=this.pow(m,E),Y=this.pow(l,E.addn(1).iushrn(1)),$=this.pow(l,E),b=I;$.cmp(_)!==0;){for(var j=$,z=0;j.cmp(_)!==0;z++)j=j.redSqr();n(z=0;I--){for(var O=g.words[I],Y=m-1;Y>=0;Y--){var $=O>>Y&1;if(_!==E[0]&&(_=this.sqr(_)),$===0&&M===0){N=0;continue}M<<=1,M|=$,N++,!(N!==y&&(I!==0||Y!==0))&&(_=this.mul(_,E[M]),N=0,M=0)}m=26}return _},F.prototype.convertTo=function(l){var g=l.umod(this.m);return g===l?g.clone():g},F.prototype.convertFrom=function(l){var g=l.clone();return g.red=null,g},s.mont=function(l){return new R(l)};function R(l){F.call(this,l),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new s(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(R,F),R.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},R.prototype.convertFrom=function(l){var g=this.imod(l.mul(this.rinv));return g.red=null,g},R.prototype.imul=function(l,g){if(l.isZero()||g.isZero())return l.words[0]=0,l.length=1,l;var y=l.imul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=y.isub(E).iushrn(this.shift),_=I;return I.cmp(this.m)>=0?_=I.isub(this.m):I.cmpn(0)<0&&(_=I.iadd(this.m)),_._forceRed(this)},R.prototype.mul=function(l,g){if(l.isZero()||g.isZero())return new s(0)._forceRed(this);var y=l.mul(g),E=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=y.isub(E).iushrn(this.shift),_=I;return I.cmp(this.m)>=0?_=I.isub(this.m):I.cmpn(0)<0&&(_=I.iadd(this.m)),_._forceRed(this)},R.prototype.invm=function(l){var g=this.imod(l._invmp(this.m).mul(this.r2));return g._forceRed(this)}})(t,d4)})(y4);var Se=y4.exports,w4="bignumber/5.7.0",$m=Se.BN,Ks=new kt(w4),dT={},IM=9007199254740991;function Jte(t){return t!=null&&(Cr.isBigNumber(t)||typeof t=="number"&&t%1===0||typeof t=="string"&&!!t.match(/^-?[0-9]+$/)||gn(t)||typeof t=="bigint"||ul(t))}var TM=!1,Cr=class t{constructor(e,r){e!==dT&&Ks.throwError("cannot call constructor directly; use BigNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=r,this._isBigNumber=!0,Object.freeze(this)}fromTwos(e){return sn(De(this).fromTwos(e))}toTwos(e){return sn(De(this).toTwos(e))}abs(){return this._hex[0]==="-"?t.from(this._hex.substring(1)):this}add(e){return sn(De(this).add(De(e)))}sub(e){return sn(De(this).sub(De(e)))}div(e){return t.from(e).isZero()&&Kn("division-by-zero","div"),sn(De(this).div(De(e)))}mul(e){return sn(De(this).mul(De(e)))}mod(e){let r=De(e);return r.isNeg()&&Kn("division-by-zero","mod"),sn(De(this).umod(r))}pow(e){let r=De(e);return r.isNeg()&&Kn("negative-power","pow"),sn(De(this).pow(r))}and(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","and"),sn(De(this).and(r))}or(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","or"),sn(De(this).or(r))}xor(e){let r=De(e);return(this.isNegative()||r.isNeg())&&Kn("unbound-bitwise-result","xor"),sn(De(this).xor(r))}mask(e){return(this.isNegative()||e<0)&&Kn("negative-width","mask"),sn(De(this).maskn(e))}shl(e){return(this.isNegative()||e<0)&&Kn("negative-width","shl"),sn(De(this).shln(e))}shr(e){return(this.isNegative()||e<0)&&Kn("negative-width","shr"),sn(De(this).shrn(e))}eq(e){return De(this).eq(De(e))}lt(e){return De(this).lt(De(e))}lte(e){return De(this).lte(De(e))}gt(e){return De(this).gt(De(e))}gte(e){return De(this).gte(De(e))}isNegative(){return this._hex[0]==="-"}isZero(){return De(this).isZero()}toNumber(){try{return De(this).toNumber()}catch{Kn("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch{}return Ks.throwError("this platform does not support BigInt",kt.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(arguments[0]===10?TM||(TM=!0,Ks.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):arguments[0]===16?Ks.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",kt.errors.UNEXPECTED_ARGUMENT,{}):Ks.throwError("BigNumber.toString does not accept parameters",kt.errors.UNEXPECTED_ARGUMENT,{})),De(this).toString(10)}toHexString(){return this._hex}toJSON(e){return{type:"BigNumber",hex:this.toHexString()}}static from(e){if(e instanceof t)return e;if(typeof e=="string")return e.match(/^-?0x[0-9a-f]+$/i)?new t(dT,Vh(e)):e.match(/^-?[0-9]+$/)?new t(dT,Vh(new $m(e))):Ks.throwArgumentError("invalid BigNumber string","value",e);if(typeof e=="number")return e%1&&Kn("underflow","BigNumber.from",e),(e>=IM||e<=-IM)&&Kn("overflow","BigNumber.from",e),t.from(String(e));let r=e;if(typeof r=="bigint")return t.from(r.toString());if(ul(r))return t.from(kr(r));if(r)if(r.toHexString){let n=r.toHexString();if(typeof n=="string")return t.from(n)}else{let n=r._hex;if(n==null&&r.type==="BigNumber"&&(n=r.hex),typeof n=="string"&&(gn(n)||n[0]==="-"&&gn(n.substring(1))))return t.from(n)}return Ks.throwArgumentError("invalid BigNumber value","value",e)}static isBigNumber(e){return!!(e&&e._isBigNumber)}};function Vh(t){if(typeof t!="string")return Vh(t.toString(16));if(t[0]==="-")return t=t.substring(1),t[0]==="-"&&Ks.throwArgumentError("invalid hex","value",t),t=Vh(t),t==="0x00"?t:"-"+t;if(t.substring(0,2)!=="0x"&&(t="0x"+t),t==="0x")return"0x00";for(t.length%2&&(t="0x0"+t.substring(2));t.length>4&&t.substring(0,4)==="0x00";)t="0x"+t.substring(4);return t}function sn(t){return Cr.from(Vh(t))}function De(t){let e=Cr.from(t).toHexString();return e[0]==="-"?new $m("-"+e.substring(3),16):new $m(e.substring(2),16)}function Kn(t,e,r){let n={fault:t,operation:e};return r!=null&&(n.value=r),Ks.throwError(t,kt.errors.NUMERIC_FAULT,n)}function Xte(t){return new $m(t,36).toString(16)}var Hr=new kt(w4),Fh={},v4=Cr.from(0),A4=Cr.from(-1);function E4(t,e,r,n){let i={fault:e,operation:r};return n!==void 0&&(i.value=n),Hr.throwError(t,kt.errors.NUMERIC_FAULT,i)}var Uh="0";for(;Uh.length<256;)Uh+=Uh;function jT(t){if(typeof t!="number")try{t=Cr.from(t).toNumber()}catch{}return typeof t=="number"&&t>=0&&t<=256&&!(t%1)?"1"+Uh.substring(0,t):Hr.throwArgumentError("invalid decimal size","decimals",t)}function gT(t,e){e==null&&(e=0);let r=jT(e);t=Cr.from(t);let n=t.lt(v4);n&&(t=t.mul(A4));let i=t.mod(r).toString();for(;i.length2&&Hr.throwArgumentError("too many decimal points","value",t);let s=i[0],o=i[1];for(s||(s="0"),o||(o="0");o[o.length-1]==="0";)o=o.substring(0,o.length-1);for(o.length>r.length-1&&E4("fractional component exceeds decimals","underflow","parseFixed"),o===""&&(o="0");o.lengthe[o]==null?a:(typeof e[o]!==u&&Hr.throwArgumentError("invalid fixed format ("+o+" not "+u+")","format."+o,e[o]),e[o]);r=s("signed","boolean",r),n=s("width","number",n),i=s("decimals","number",i)}return n%8&&Hr.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",n),i>80&&Hr.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",i),new t(Fh,r,n,i)}},Ym=class t{constructor(e,r,n,i){e!==Fh&&Hr.throwError("cannot use FixedNumber constructor; use FixedNumber.from",kt.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=i,this._hex=r,this._value=n,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(e){this.format.name!==e.format.name&&Hr.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",e)}addUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.add(n),this.format.decimals,this.format)}subUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.sub(n),this.format.decimals,this.format)}mulUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(n).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(e){this._checkFormat(e);let r=Qs(this._value,this.format.decimals),n=Qs(e._value,e.format.decimals);return t.fromValue(r.mul(this.format._multiplier).div(n),this.format.decimals,this.format)}floor(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return this.isNegative()&&n&&(r=r.subUnsafe(_M.toFormat(r.format))),r}ceiling(){let e=this.toString().split(".");e.length===1&&e.push("0");let r=t.from(e[0],this.format),n=!e[1].match(/^(0*)$/);return!this.isNegative()&&n&&(r=r.addUnsafe(_M.toFormat(r.format))),r}round(e){e==null&&(e=0);let r=this.toString().split(".");if(r.length===1&&r.push("0"),(e<0||e>80||e%1)&&Hr.throwArgumentError("invalid decimal count","decimals",e),r[1].length<=e)return this;let n=t.from("1"+Uh.substring(0,e),this.format),i=Zte.toFormat(this.format);return this.mulUnsafe(n).addUnsafe(i).floor().divUnsafe(n)}isZero(){return this._value==="0.0"||this._value==="0"}isNegative(){return this._value[0]==="-"}toString(){return this._value}toHexString(e){if(e==null)return this._hex;e%8&&Hr.throwArgumentError("invalid byte width","width",e);let r=Cr.from(this._hex).fromTwos(this.format.width).toTwos(e).toHexString();return fs(r,e/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return t.fromString(this._value,e)}static fromValue(e,r,n){return n==null&&r!=null&&!Jte(r)&&(n=r,r=null),r==null&&(r=0),n==null&&(n="fixed"),t.fromString(gT(e,r),qh.from(n))}static fromString(e,r){r==null&&(r="fixed");let n=qh.from(r),i=Qs(e,n.decimals);!n.signed&&i.lt(v4)&&E4("unsigned value cannot be negative","overflow","value",e);let s=null;n.signed?s=i.toTwos(n.width).toHexString():(s=i.toHexString(),s=fs(s,n.width/8));let o=gT(i,n.decimals);return new t(Fh,s,o,n)}static fromBytes(e,r){r==null&&(r="fixed");let n=qh.from(r);if(Qt(e).length>n.width/8)throw new Error("overflow");let i=Cr.from(e);n.signed&&(i=i.fromTwos(n.width));let s=i.toTwos((n.signed?0:1)+n.width).toHexString(),o=gT(i,n.decimals);return new t(Fh,s,o,n)}static from(e,r){if(typeof e=="string")return t.fromString(e,r);if(ul(e))return t.fromBytes(e,r);try{return t.fromValue(e,0,r)}catch(n){if(n.code!==kt.errors.INVALID_ARGUMENT)throw n}return Hr.throwArgumentError("invalid FixedNumber value","value",e)}static isFixedNumber(e){return!!(e&&e._isFixedNumber)}},_M=Ym.from(1),Zte=Ym.from("0.5"),ere="strings/5.7.0",b4=new kt(ere),Jm;(function(t){t.current="",t.NFC="NFC",t.NFD="NFD",t.NFKC="NFKC",t.NFKD="NFKD"})(Jm||(Jm={}));var rl;(function(t){t.UNEXPECTED_CONTINUE="unexpected continuation byte",t.BAD_PREFIX="bad codepoint prefix",t.OVERRUN="string overrun",t.MISSING_CONTINUE="missing continuation byte",t.OUT_OF_RANGE="out of UTF-8 range",t.UTF16_SURROGATE="UTF-16 surrogate",t.OVERLONG="overlong representation"})(rl||(rl={}));function tre(t,e,r,n,i){return b4.throwArgumentError(`invalid codepoint at offset ${e}; ${t}`,"bytes",r)}function S4(t,e,r,n,i){if(t===rl.BAD_PREFIX||t===rl.UNEXPECTED_CONTINUE){let s=0;for(let o=e+1;o>6===2;o++)s++;return s}return t===rl.OVERRUN?r.length-e-1:0}function rre(t,e,r,n,i){return t===rl.OVERLONG?(n.push(i),0):(n.push(65533),S4(t,e,r))}Object.freeze({error:tre,ignore:S4,replace:rre});function pT(t,e=Jm.current){e!=Jm.current&&(b4.checkNormalize(),t=t.normalize(e));let r=[];for(let n=0;n>6|192),r.push(i&63|128);else if((i&64512)==55296){n++;let s=t.charCodeAt(n);if(n>=t.length||(s&64512)!==56320)throw new Error("invalid utf-8 string");let o=65536+((i&1023)<<10)+(s&1023);r.push(o>>18|240),r.push(o>>12&63|128),r.push(o>>6&63|128),r.push(o&63|128)}else r.push(i>>12|224),r.push(i>>6&63|128),r.push(i&63|128)}return Qt(r)}function nre(t){if(t.length%4!==0)throw new Error("bad data");let e=[];for(let r=0;r{let s=i.split(":");r+=parseInt(s[0],16),n[r]=e(s[1])}),n}function CM(t){let e=0;return t.split(",").map(r=>{let n=r.split("-");n.length===1?n[1]="0":n[1]===""&&(n[1]="1");let i=e+parseInt(n[0],16);return e=parseInt(n[1],16),{l:i,h:e}})}CM("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),"ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(t=>parseInt(t,16)),mT("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),mT("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),mT("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",nre),CM("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");var I4="hash/5.7.0";function ire(t){t=atob(t);let e=[];for(let r=0;r0&&Array.isArray(u)?i(u,o-1):r.push(u)})};return i(t,e),r}function sre(t){let e={};for(let r=0;r>--a&1}let d=31,w=Math.pow(2,d),A=w>>>1,T=A>>1,x=w-1,B=0;for(let k=0;k1;){let P=H+q>>>1;k>>1|f(),v=v<<1^A,C=(C^A)<<1|A|1;U=v,Q=1+C-v}let L=n-4;return V.map(k=>{switch(k-L){case 3:return L+65792+(t[u++]<<16|t[u++]<<8|t[u++]);case 2:return L+256+(t[u++]<<8|t[u++]);case 1:return L+t[u++];default:return k-1}})}function are(t){let e=0;return()=>t[e++]}function ure(t){return are(ore(t))}function cre(t){return t&1?~t>>1:t>>1}function lre(t,e){let r=Array(t);for(let n=0;ne[o]):r}function hre(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(gre(r,t))}for(;;){let r=t()-1;if(r<0)break;e.push(pre(r,t))}return sre(T4(e))}function dre(t){let e=[];for(;;){let r=t();if(r==0)break;e.push(r)}return e}function _4(t,e,r){let n=Array(t).fill(void 0).map(()=>[]);for(let i=0;in[o].push(s));return n}function gre(t,e){let r=1+e(),n=e(),i=dre(e),s=_4(i.length,1+t,e);return T4(s.map((o,u)=>{let a=o[0],c=o.slice(1);return Array(i[u]).fill(void 0).map((f,d)=>{let w=d*n;return[a+d*r,c.map(A=>A+w)]})}))}function pre(t,e){let r=1+e();return _4(r,1+t,e).map(n=>[n[0],n.slice(1)])}function mre(t){let e=Xm(t).sort((n,i)=>n-i);return r();function r(){let n=[];for(;;){let c=Xm(t,e);if(c.length==0)break;n.push({set:new Set(c),node:r()})}n.sort((c,f)=>f.set.size-c.set.size);let i=t(),s=i%3;i=i/3|0;let o=!!(i&1);i>>=1;let u=i==1,a=i==2;return{branches:n,valid:s,fe0f:o,save:u,check:a}}}function yre(){return ure(ire("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}var qm=yre();new Set(Xm(qm)),new Set(Xm(qm)),hre(qm),mre(qm),new kt(I4);var wre=new Uint8Array(32);wre.fill(0);var vre=`Ethereum Signed Message: +`;function C4(t){return typeof t=="string"&&(t=pT(t)),GT(zte([pT(vre),pT(String(t.length)),t]))}var Are="rlp/5.7.0";new kt(Are);var Ere="address/5.7.0",Lh=new kt(Ere);function xM(t){gn(t,20)||Lh.throwArgumentError("invalid address","address",t),t=t.toLowerCase();let e=t.substring(2).split(""),r=new Uint8Array(40);for(let i=0;i<40;i++)r[i]=e[i].charCodeAt(0);let n=Qt(GT(r));for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&(e[i]=e[i].toUpperCase()),(n[i>>1]&15)>=8&&(e[i+1]=e[i+1].toUpperCase());return"0x"+e.join("")}var bre=9007199254740991;function Sre(t){return Math.log10?Math.log10(t):Math.log(t)/Math.LN10}var zT={};for(let t=0;t<10;t++)zT[String(t)]=String(t);for(let t=0;t<26;t++)zT[String.fromCharCode(65+t)]=String(10+t);var OM=Math.floor(Sre(bre));function Ire(t){t=t.toUpperCase(),t=t.substring(4)+t.substring(0,2)+"00";let e=t.split("").map(n=>zT[n]).join("");for(;e.length>=OM;){let n=e.substring(0,OM);e=parseInt(n,10)%97+e.substring(n.length)}let r=String(98-parseInt(e,10)%97);for(;r.length<2;)r="0"+r;return r}function Tre(t){let e=null;if(typeof t!="string"&&Lh.throwArgumentError("invalid address","address",t),t.match(/^(0x)?[0-9a-fA-F]{40}$/))t.substring(0,2)!=="0x"&&(t="0x"+t),e=xM(t),t.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&e!==t&&Lh.throwArgumentError("bad address checksum","address",t);else if(t.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(t.substring(2,4)!==Ire(t)&&Lh.throwArgumentError("bad icap checksum","address",t),e=Xte(t.substring(4));e.length<40;)e="0"+e;e=xM("0x"+e)}else Lh.throwArgumentError("invalid address","address",t);return e}var _re="properties/5.7.0";new kt(_re);function Rh(t,e,r){Object.defineProperty(t,e,{enumerable:!0,value:r,writable:!1})}new kt(I4);var Cre=new Uint8Array(32);Cre.fill(0),Cr.from(-1);var Nre=Cr.from(0),xre=Cr.from(1);Cr.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fs(xre.toHexString(),32),fs(Nre.toHexString(),32);var os={},Pe={},Gh=N4;function N4(t,e){if(!t)throw new Error(e||"Assertion failed")}N4.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var NT={exports:{}};typeof Object.create=="function"?NT.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:NT.exports=function(t,e){if(e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}};var Ore=Gh,Dre=NT.exports;Pe.inherits=Dre;function Pre(t,e){return(t.charCodeAt(e)&64512)!==55296||e<0||e+1>=t.length?!1:(t.charCodeAt(e+1)&64512)===56320}function Rre(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if(typeof t=="string")if(e){if(e==="hex")for(t=t.replace(/[^a-z0-9]+/ig,""),t.length%2!==0&&(t="0"+t),i=0;i>6|192,r[n++]=s&63|128):Pre(t,i)?(s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023),r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128)}else for(i=0;i>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return e>>>0}Pe.htonl=x4;function Mre(t,e){for(var r="",n=0;n>>0}return s}Pe.join32=Lre;function Fre(t,e){for(var r=new Array(t.length*4),n=0,i=0;n>>24,r[i+1]=s>>>16&255,r[i+2]=s>>>8&255,r[i+3]=s&255):(r[i+3]=s>>>24,r[i+2]=s>>>16&255,r[i+1]=s>>>8&255,r[i]=s&255)}return r}Pe.split32=Fre;function Ure(t,e){return t>>>e|t<<32-e}Pe.rotr32=Ure;function qre(t,e){return t<>>32-e}Pe.rotl32=qre;function Vre(t,e){return t+e>>>0}Pe.sum32=Vre;function kre(t,e,r){return t+e+r>>>0}Pe.sum32_3=kre;function Hre(t,e,r,n){return t+e+r+n>>>0}Pe.sum32_4=Hre;function Gre(t,e,r,n,i){return t+e+r+n+i>>>0}Pe.sum32_5=Gre;function jre(t,e,r,n){var i=t[e],s=t[e+1],o=n+s>>>0,u=(o>>0,t[e+1]=o}Pe.sum64=jre;function zre(t,e,r,n){var i=e+n>>>0,s=(i>>0}Pe.sum64_hi=zre;function Qre(t,e,r,n){var i=e+n;return i>>>0}Pe.sum64_lo=Qre;function Kre(t,e,r,n,i,s,o,u){var a=0,c=e;c=c+n>>>0,a+=c>>0,a+=c>>0,a+=c>>0}Pe.sum64_4_hi=Kre;function Wre(t,e,r,n,i,s,o,u){var a=e+n+s+u;return a>>>0}Pe.sum64_4_lo=Wre;function $re(t,e,r,n,i,s,o,u,a,c){var f=0,d=e;d=d+n>>>0,f+=d>>0,f+=d>>0,f+=d>>0,f+=d>>0}Pe.sum64_5_hi=$re;function Yre(t,e,r,n,i,s,o,u,a,c){var f=e+n+s+u+c;return f>>>0}Pe.sum64_5_lo=Yre;function Jre(t,e,r){var n=e<<32-r|t>>>r;return n>>>0}Pe.rotr64_hi=Jre;function Xre(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.rotr64_lo=Xre;function Zre(t,e,r){return t>>>r}Pe.shr64_hi=Zre;function ene(t,e,r){var n=t<<32-r|e>>>r;return n>>>0}Pe.shr64_lo=ene;var cl={},DM=Pe,tne=Gh;function Vm(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}cl.BlockHash=Vm,Vm.prototype.update=function(t,e){if(t=DM.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){t=this.pending;var r=t.length%this._delta8;this.pending=t.slice(t.length-r,t.length),this.pending.length===0&&(this.pending=null),t=DM.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=t&255}else for(n[i++]=t&255,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,s=8;s>>3}ms.g0_256=one;function ane(t){return hs(t,17)^hs(t,19)^t>>>10}ms.g1_256=ane;var sl=Pe,une=cl,cne=ms,yT=sl.rotl32,Bh=sl.sum32,lne=sl.sum32_5,fne=cne.ft_1,M4=une.BlockHash,hne=[1518500249,1859775393,2400959708,3395469782];function us(){if(!(this instanceof us))return new us;M4.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}sl.inherits(us,M4);var dne=us;us.blockSize=512,us.outSize=160,us.hmacStrength=80,us.padLength=64,us.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=new this.Hash().update(t).digest()),eie(t.length<=this.blockSize);for(var e=t.length;e>8,w=f&255;d?a.push(d,w):a.push(w)}return a}r.toArray=n;function i(o){return o.length===1?"0"+o:o}r.zero2=i;function s(o){for(var u="",a=0;a(w>>1)-1?x=(w>>1)-B:x=B,A.isubn(x)):x=0,d[T]=x,A.iushrn(1)}return d}r.getNAF=n;function i(a,c){var f=[[],[]];a=a.clone(),c=c.clone();for(var d=0,w=0,A;a.cmpn(-d)>0||c.cmpn(-w)>0;){var T=a.andln(3)+d&3,x=c.andln(3)+w&3;T===3&&(T=-1),x===3&&(x=-1);var B;T&1?(A=a.andln(7)+d&7,(A===3||A===5)&&x===2?B=-T:B=T):B=0,f[0].push(B);var V;x&1?(A=c.andln(7)+w&7,(A===3||A===5)&&T===2?V=-x:V=x):V=0,f[1].push(V),2*d===B+1&&(d=1-d),2*w===V+1&&(w=1-w),a.iushrn(1),c.iushrn(1)}return f}r.getJSF=i;function s(a,c,f){var d="_"+c;a.prototype[c]=function(){return this[d]!==void 0?this[d]:this[d]=f.call(this)}}r.cachedProperty=s;function o(a){return typeof a=="string"?r.toArray(a,"hex"):a}r.parseBytes=o;function u(a){return new Se(a,"hex","le")}r.intFromLE=u}),Hm=pn.getNAF,nie=pn.getJSF,Zm=pn.assert;function Vo(t,e){this.type=t,this.p=new Se(e.p,16),this.red=e.prime?Se.red(e.prime):Se.mont(this.p),this.zero=new Se(0).toRed(this.red),this.one=new Se(1).toRed(this.red),this.two=new Se(2).toRed(this.red),this.n=e.n&&new Se(e.n,16),this.g=e.g&&this.pointFromJSON(e.g,e.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ru=Vo;Vo.prototype.point=function(){throw new Error("Not implemented")},Vo.prototype.validate=function(){throw new Error("Not implemented")},Vo.prototype._fixedNafMul=function(t,e){Zm(t.precomputed);var r=t._getDoubles(),n=Hm(e,1,this._bitLength),i=(1<=o;a--)u=(u<<1)+n[a];s.push(u)}for(var c=this.jpoint(null,null,null),f=this.jpoint(null,null,null),d=i;d>0;d--){for(o=0;o=0;u--){for(var a=0;u>=0&&s[u]===0;u--)a++;if(u>=0&&a++,o=o.dblp(a),u<0)break;var c=s[u];Zm(c!==0),t.type==="affine"?c>0?o=o.mixedAdd(i[c-1>>1]):o=o.mixedAdd(i[-c-1>>1].neg()):c>0?o=o.add(i[c-1>>1]):o=o.add(i[-c-1>>1].neg())}return t.type==="affine"?o.toP():o},Vo.prototype._wnafMulAdd=function(t,e,r,n,i){var s=this._wnafT1,o=this._wnafT2,u=this._wnafT3,a=0,c,f,d;for(c=0;c=1;c-=2){var A=c-1,T=c;if(s[A]!==1||s[T]!==1){u[A]=Hm(r[A],s[A],this._bitLength),u[T]=Hm(r[T],s[T],this._bitLength),a=Math.max(u[A].length,a),a=Math.max(u[T].length,a);continue}var x=[e[A],null,null,e[T]];e[A].y.cmp(e[T].y)===0?(x[1]=e[A].add(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg())):e[A].y.cmp(e[T].y.redNeg())===0?(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].add(e[T].neg())):(x[1]=e[A].toJ().mixedAdd(e[T]),x[2]=e[A].toJ().mixedAdd(e[T].neg()));var B=[-3,-1,-5,-7,0,7,5,1,3],V=nie(r[A],r[T]);for(a=Math.max(V[0].length,a),u[A]=new Array(a),u[T]=new Array(a),f=0;f=0;c--){for(var H=0;c>=0;){var q=!0;for(f=0;f=0&&H++,L=L.dblp(H),c<0)break;for(f=0;f0?d=o[f][v-1>>1]:v<0&&(d=o[f][-v-1>>1].neg()),d.type==="affine"?L=L.mixedAdd(d):L=L.add(d))}}for(c=0;c=Math.ceil((t.bitLength()+1)/e.step):!1},Wn.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(w=a,A=c),f.negative&&(f=f.neg(),d=d.neg()),w.negative&&(w=w.neg(),A=A.neg()),[{a:f,b:d},{a:w,b:A}]},Yn.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),s=r.b.neg().mul(t).divRound(this.n),o=i.mul(r.a),u=s.mul(n.a),a=i.mul(r.b),c=s.mul(n.b),f=t.sub(o).sub(u),d=a.add(c).neg();return{k1:f,k2:d}},Yn.prototype.pointFromX=function(t,e){t=new Se(t,16),t.red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(n.redSqr().redSub(r).cmp(this.zero)!==0)throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},Yn.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return r.redSqr().redISub(i).cmpn(0)===0},Yn.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,s=0;s":""},Ar.prototype.isInfinity=function(){return this.inf},Ar.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(this.x.cmp(t.x)===0)return this.curve.point(null,null);var e=this.y.redSub(t.y);e.cmpn(0)!==0&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},Ar.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(t.cmpn(0)===0)return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),s=i.redSqr().redISub(this.x.redAdd(this.x)),o=i.redMul(this.x.redSub(s)).redISub(this.y);return this.curve.point(s,o)},Ar.prototype.getX=function(){return this.x.fromRed()},Ar.prototype.getY=function(){return this.y.fromRed()},Ar.prototype.mul=function(t){return t=new Se(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},Ar.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},Ar.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},Ar.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||this.x.cmp(t.x)===0&&this.y.cmp(t.y)===0)},Ar.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(i){return i.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},Ar.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var t=this.curve.jpoint(this.x,this.y,this.curve.one);return t};function _r(t,e,r,n){ru.BasePoint.call(this,t,"jacobian"),e===null&&r===null&&n===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Se(0)):(this.x=new Se(e,16),this.y=new Se(r,16),this.z=new Se(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}KT(_r,ru.BasePoint),Yn.prototype.jpoint=function(t,e,r){return new _r(this,t,e,r)},_r.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},_r.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},_r.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),s=this.y.redMul(e.redMul(t.z)),o=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=s.redSub(o);if(u.cmpn(0)===0)return a.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var c=u.redSqr(),f=c.redMul(u),d=n.redMul(c),w=a.redSqr().redIAdd(f).redISub(d).redISub(d),A=a.redMul(d.redISub(w)).redISub(s.redMul(f)),T=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(w,A,T)},_r.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,s=t.y.redMul(e).redMul(this.z),o=r.redSub(n),u=i.redSub(s);if(o.cmpn(0)===0)return u.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var a=o.redSqr(),c=a.redMul(o),f=r.redMul(a),d=u.redSqr().redIAdd(c).redISub(f).redISub(f),w=u.redMul(f.redISub(d)).redISub(i.redMul(c)),A=this.z.redMul(o);return this.curve.jpoint(d,w,A)},_r.prototype.dblp=function(t){if(t===0)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),this.x.cmp(r)===0)return!0}},_r.prototype.inspect=function(){return this.isInfinity()?"":""},_r.prototype.isInfinity=function(){return this.z.cmpn(0)===0};var zm=fl(function(t,e){var r=e;r.base=ru,r.short=sie,r.mont=null,r.edwards=null}),Qm=fl(function(t,e){var r=e,n=pn.assert;function i(u){u.type==="short"?this.curve=new zm.short(u):u.type==="edwards"?this.curve=new zm.edwards(u):this.curve=new zm.mont(u),this.g=this.curve.g,this.n=this.curve.n,this.hash=u.hash,n(this.g.validate(),"Invalid curve"),n(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}r.PresetCurve=i;function s(u,a){Object.defineProperty(r,u,{configurable:!0,enumerable:!0,get:function(){var c=new i(a);return Object.defineProperty(r,u,{configurable:!0,enumerable:!0,value:c}),c}})}s("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:os.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),s("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:os.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),s("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:os.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),s("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:os.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),s("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:os.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),s("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["9"]}),s("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:os.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var o;try{o=null.crash()}catch{o=void 0}s("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:os.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",o]})});function ko(t){if(!(this instanceof ko))return new ko(t);this.hash=t.hash,this.predResist=!!t.predResist,this.outLen=this.hash.outSize,this.minEntropy=t.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var e=Ti.toArray(t.entropy,t.entropyEnc||"hex"),r=Ti.toArray(t.nonce,t.nonceEnc||"hex"),n=Ti.toArray(t.pers,t.persEnc||"hex");QT(e.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var MM=ko;ko.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},ko.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof e!="string"&&(n=r,r=e,e=null),r&&(r=Ti.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var oie=pn.assert;function ny(t,e){if(t instanceof ny)return t;this._importDER(t,e)||(oie(t.r&&t.s,"Signature without r or s"),this.r=new Se(t.r,16),this.s=new Se(t.s,16),t.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Gm=ny;function aie(){this.place=0}function bT(t,e){var r=t[e.place++];if(!(r&128))return r;var n=r&15;if(n===0||n>4)return!1;for(var i=0,s=0,o=e.place;s>>=0;return i<=127?!1:(e.place=o,i)}function LM(t){for(var e=0,r=t.length-1;!t[e]&&!(t[e+1]&128)&&e>>3);for(t.push(r|128);--r;)t.push(e>>>(r<<3)&255);t.push(e)}ny.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(e[0]&128&&(e=[0].concat(e)),r[0]&128&&(r=[0].concat(r)),e=LM(e),r=LM(r);!r[0]&&!(r[1]&128);)r=r.slice(1);var n=[2];ST(n,e.length),n=n.concat(e),n.push(2),ST(n,r.length);var i=n.concat(r),s=[48];return ST(s,i.length),s=s.concat(i),pn.encode(s,t)};var uie=function(){throw new Error("unsupported")},K4=pn.assert;function $n(t){if(!(this instanceof $n))return new $n(t);typeof t=="string"&&(K4(Object.prototype.hasOwnProperty.call(Qm,t),"Unknown curve "+t),t=Qm[t]),t instanceof Qm.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var cie=$n;$n.prototype.keyPair=function(t){return new ET(this,t)},$n.prototype.keyFromPrivate=function(t,e){return ET.fromPrivate(this,t,e)},$n.prototype.keyFromPublic=function(t,e){return ET.fromPublic(this,t,e)},$n.prototype.genKeyPair=function(t){t||(t={});for(var e=new MM({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||uie(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Se(2));;){var i=new Se(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},$n.prototype._truncateToN=function(t,e){var r=t.byteLength()*8-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},$n.prototype.sign=function(t,e,r,n){typeof r=="object"&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Se(t,16));for(var i=this.n.byteLength(),s=e.getPrivate().toArray("be",i),o=t.toArray("be",i),u=new MM({hash:this.hash,entropy:s,nonce:o,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Se(1)),c=0;;c++){var f=n.k?n.k(c):new Se(u.generate(this.n.byteLength()));if(f=this._truncateToN(f,!0),!(f.cmpn(1)<=0||f.cmp(a)>=0)){var d=this.g.mul(f);if(!d.isInfinity()){var w=d.getX(),A=w.umod(this.n);if(A.cmpn(0)!==0){var T=f.invm(this.n).mul(A.mul(e.getPrivate()).iadd(t));if(T=T.umod(this.n),T.cmpn(0)!==0){var x=(d.getY().isOdd()?1:0)|(w.cmp(A)!==0?2:0);return n.canonical&&T.cmp(this.nh)>0&&(T=this.n.sub(T),x^=1),new Gm({r:A,s:T,recoveryParam:x})}}}}}},$n.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Se(t,16)),r=this.keyFromPublic(r,n),e=new Gm(e,"hex");var i=e.r,s=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var o=s.invm(this.n),u=o.mul(t).umod(this.n),a=o.mul(i).umod(this.n),c;return this.curve._maxwellTrick?(c=this.g.jmulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.eqXToP(i)):(c=this.g.mulAdd(u,r.getPublic(),a),c.isInfinity()?!1:c.getX().umod(this.n).cmp(i)===0)},$n.prototype.recoverPubKey=function(t,e,r,n){K4((3&r)===r,"The recovery param is more than two bits"),e=new Gm(e,n);var i=this.n,s=new Se(t),o=e.r,u=e.s,a=r&1,c=r>>1;if(o.cmp(this.curve.p.umod(this.curve.n))>=0&&c)throw new Error("Unable to find sencond key candinate");c?o=this.curve.pointFromX(o.add(this.curve.n),a):o=this.curve.pointFromX(o,a);var f=e.r.invm(i),d=i.sub(s).mul(f).umod(i),w=u.mul(f).umod(i);return this.g.mulAdd(d,o,w)},$n.prototype.getKeyRecoveryParam=function(t,e,r,n){if(e=new Gm(e,n),e.recoveryParam!==null)return e.recoveryParam;for(var i=0;i<4;i++){var s;try{s=this.recoverPubKey(t,e,i)}catch{continue}if(s.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var lie=fl(function(t,e){var r=e;r.version="6.5.4",r.utils=pn,r.rand=function(){throw new Error("unsupported")},r.curve=zm,r.curves=Qm,r.ec=cie,r.eddsa=null}),fie=lie.ec,hie="signing-key/5.7.0",DT=new kt(hie),IT=null;function ls(){return IT||(IT=new fie("secp256k1")),IT}var PT=class{constructor(e){Rh(this,"curve","secp256k1"),Rh(this,"privateKey",kr(e)),Kte(this.privateKey)!==32&&DT.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");let r=ls().keyFromPrivate(Qt(this.privateKey));Rh(this,"publicKey","0x"+r.getPublic(!1,"hex")),Rh(this,"compressedPublicKey","0x"+r.getPublic(!0,"hex")),Rh(this,"_isSigningKey",!0)}_addPoint(e){let r=ls().keyFromPublic(Qt(this.publicKey)),n=ls().keyFromPublic(Qt(e));return"0x"+r.pub.add(n.pub).encodeCompressed("hex")}signDigest(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=Qt(e);n.length!==32&&DT.throwArgumentError("bad digest length","digest",e);let i=r.sign(n,{canonical:!0});return m4({recoveryParam:i.recoveryParam,r:fs("0x"+i.r.toString(16),32),s:fs("0x"+i.s.toString(16),32)})}computeSharedSecret(e){let r=ls().keyFromPrivate(Qt(this.privateKey)),n=ls().keyFromPublic(Qt(W4(e)));return fs("0x"+r.derive(n.getPublic()).toString(16),32)}static isSigningKey(e){return!!(e&&e._isSigningKey)}};function die(t,e){let r=m4(e),n={r:Qt(r.r),s:Qt(r.s)};return"0x"+ls().recoverPubKey(Qt(t),n,r.recoveryParam).encode("hex",!1)}function W4(t,e){let r=Qt(t);if(r.length===32){let n=new PT(r);return e?"0x"+ls().keyFromPrivate(r).getPublic(!0,"hex"):n.publicKey}else{if(r.length===33)return e?kr(r):"0x"+ls().keyFromPublic(r).getPublic(!1,"hex");if(r.length===65)return e?"0x"+ls().keyFromPublic(r).getPublic(!0,"hex"):kr(r)}return DT.throwArgumentError("invalid public or private key","key","[REDACTED]")}var gie="transactions/5.7.0";new kt(gie);var FM;(function(t){t[t.legacy=0]="legacy",t[t.eip2930=1]="eip2930",t[t.eip1559=2]="eip1559"})(FM||(FM={}));function pie(t){let e=W4(t);return Tre(SM(GT(SM(e,1)),12))}function mie(t,e){return pie(die(Qt(t),e))}var yie="https://rpc.walletconnect.com/v1";async function $4(t,e,r,n,i,s){switch(r.t){case"eip191":return Y4(t,e,r.s);case"eip1271":return await J4(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Y4(t,e,r){return mie(C4(e),r).toLowerCase()===t.toLowerCase()}async function J4(t,e,r,n,i,s){try{let o="0x1626ba7e",u="0000000000000000000000000000000000000000000000000000000000000040",a="0000000000000000000000000000000000000000000000000000000000000041",c=r.substring(2),f=C4(e).substring(2),d=o+f+u+a+c,w=await fetch(`${s||yie}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:wie(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:A}=await w.json();return A?A.slice(0,o.length).toLowerCase()===o.toLowerCase():!1}catch(o){return console.error("isValidEip1271Signature: ",o),!1}}function wie(){return Date.now()+Math.floor(Math.random()*1e3)}var vie=Object.defineProperty,Aie=Object.defineProperties,Eie=Object.getOwnPropertyDescriptors,UM=Object.getOwnPropertySymbols,bie=Object.prototype.hasOwnProperty,Sie=Object.prototype.propertyIsEnumerable,qM=(t,e,r)=>e in t?vie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,WT=(t,e)=>{for(var r in e||(e={}))bie.call(e,r)&&qM(t,r,e[r]);if(UM)for(var r of UM(e))Sie.call(e,r)&&qM(t,r,e[r]);return t},X4=(t,e)=>Aie(t,Eie(e)),Iie="did:pkh:",iy=t=>t?.split(":"),$T=t=>{let e=t&&iy(t);if(e)return t.includes(Iie)?e[3]:e[1]},Tie=t=>{let e=t&&iy(t);if(e)return e[2]+":"+e[3]},YT=t=>{let e=t&&iy(t);if(e)return e.pop()};async function _ie(t){let{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=Z4(i,i.iss),o=YT(i.iss);return await $4(o,s,n,$T(i.iss),r)}var Z4=(t,e)=>{let r=`${t.domain} wants you to sign in with your Ethereum account:`,n=YT(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0,s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,u=`Chain ID: ${$T(e)}`,a=`Nonce: ${t.nonce}`,c=`Issued At: ${t.iat}`,f=t.resources?`Resources:${t.resources.map(w=>` +- ${w}`).join("")}`:void 0,d=oy(t.resources);if(d){let w=jo(d);i=ZT(i,w)}return[r,n,"",i,"",s,o,u,a,c,f].filter(w=>w!=null).join(` +`)};function Cie(t,e,r){return r.includes("did:pkh:")||(r=`did:pkh:${r}`),{h:{t:"caip122"},p:{iss:r,domain:t.domain,aud:t.aud,version:t.version,nonce:t.nonce,iat:t.iat,statement:t.statement,requestId:t.requestId,resources:t.resources,nbf:t.nbf,exp:t.exp},s:e}}function Nie(t){var e;let{authPayload:r,chains:n,methods:i}=t,s=r.statement||"";if(!(n!=null&&n.length))return r;let o=r.chains,u=_T(o,n);if(!(u!=null&&u.length))throw new Error("No supported chains");let a=e5(r.resources);if(!a)return r;ps(a);let c=t5(a,"eip155"),f=r?.resources||[];if(c!=null&&c.length){let d=r5(c),w=_T(d,i);if(!(w!=null&&w.length))throw new Error(`Supported methods don't satisfy the requested: ${JSON.stringify(d)}, supported: ${JSON.stringify(i)}`);let A=JT("request",w,{chains:u}),T=o5(a,"eip155",A);f=((e=r?.resources)==null?void 0:e.slice(0,-1))||[],f.push(sy(T))}return X4(WT({},r),{statement:u5(s,oy(f)),chains:u,resources:r!=null&&r.resources||f.length>0?f:void 0})}function e5(t){let e=oy(t);if(e&&XT(e))return jo(e)}function xie(t,e){var r;return(r=t?.att)==null?void 0:r.hasOwnProperty(e)}function t5(t,e){var r,n;return(r=t?.att)!=null&&r[e]?Object.keys((n=t?.att)==null?void 0:n[e]):[]}function Oie(t){return t?.map(e=>Object.keys(e))||[]}function r5(t){return t?.map(e=>{var r;return(r=e.split("/"))==null?void 0:r[1]})||[]}function n5(t){return p.Buffer.from(JSON.stringify(t)).toString("base64")}function i5(t){return JSON.parse(p.Buffer.from(t,"base64").toString("utf-8"))}function ps(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");let e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{let n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{let s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function s5(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:JT(e,r,n)}}}function o5(t,e,r){var n;return t.att[e]=WT({},r),((n=Object.keys(t.att))==null?void 0:n.sort((i,s)=>i.localeCompare(s))).reduce((i,s)=>(i.att[s]=t.att[s],i),{att:{}})}function JT(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));let n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function sy(t){return ps(t),`urn:recap:${n5(t).replace(/=/g,"")}`}function jo(t){let e=i5(t.replace("urn:recap:",""));return ps(e),e}function Die(t,e,r){let n=s5(t,e,r);return sy(n)}function XT(t){return t&&t.includes("urn:recap:")}function Pie(t,e){let r=jo(t),n=jo(e),i=a5(r,n);return sy(i)}function a5(t,e){ps(t),ps(e);let r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((u,a)=>u.localeCompare(a)).forEach(u=>{var a,c;n.att[i]=X4(WT({},n.att[i]),{[u]:((a=t.att[i])==null?void 0:a[u])||((c=e.att[i])==null?void 0:c[u])})})}),n}function ZT(t="",e){ps(e);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;let n=[],i=0;Object.keys(e.att).forEach(u=>{let a=Object.keys(e.att[u]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));a.sort((d,w)=>d.action.localeCompare(w.action));let c={};a.forEach(d=>{c[d.ability]||(c[d.ability]=[]),c[d.ability].push(d.action)});let f=Object.keys(c).map(d=>(i++,`(${i}) '${d}': '${c[d].join("', '")}' for '${u}'.`));n.push(f.join(", ").replace(".,","."))});let s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function Rie(t){var e;let r=jo(t);ps(r);let n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Bie(t){let e=jo(t);ps(e);let r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function u5(t,e){if(!e)return t;let r=jo(e);return ps(r),ZT(t,r)}function oy(t){if(!t)return;let e=t?.[t.length-1];return XT(e)?e:void 0}var e_="base10",jr="base16",ey="base64pad",ay="utf8",t_=0,hl=1,Mie=0,VM=1,RT=12,r_=32;function Lie(){let t=YM.generateKeyPair();return{privateKey:Vt.toString(t.secretKey,jr),publicKey:Vt.toString(t.publicKey,jr)}}function Fie(){let t=WM.randomBytes(r_);return Vt.toString(t,jr)}function Uie(t,e){let r=YM.sharedKey(Vt.fromString(t,jr),Vt.fromString(e,jr),!0),n=new ite.HKDF(FT.SHA256,r).expand(r_);return Vt.toString(n,jr)}function qie(t){let e=FT.hash(Vt.fromString(t,jr));return Vt.toString(e,jr)}function Vie(t){let e=FT.hash(Vt.fromString(t,ay));return Vt.toString(e,jr)}function c5(t){return Vt.fromString(`${t}`,e_)}function jh(t){return Number(Vt.toString(t,e_))}function kie(t){let e=c5(typeof t.type<"u"?t.type:t_);if(jh(e)===hl&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof t.senderPublicKey<"u"?Vt.fromString(t.senderPublicKey,jr):void 0,n=typeof t.iv<"u"?Vt.fromString(t.iv,jr):WM.randomBytes(RT),i=new KM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)).seal(n,Vt.fromString(t.message,ay));return l5({type:e,sealed:i,iv:n,senderPublicKey:r})}function Hie(t){let e=new KM.ChaCha20Poly1305(Vt.fromString(t.symKey,jr)),{sealed:r,iv:n}=n_(t.encoded),i=e.open(n,r);if(i===null)throw new Error("Failed to decrypt");return Vt.toString(i,ay)}function l5(t){if(jh(t.type)===hl){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Vt.toString(Vt.concat([t.type,t.senderPublicKey,t.iv,t.sealed]),ey)}return Vt.toString(Vt.concat([t.type,t.iv,t.sealed]),ey)}function n_(t){let e=Vt.fromString(t,ey),r=e.slice(Mie,VM),n=VM;if(jh(r)===hl){let u=n+r_,a=u+RT,c=e.slice(n,u),f=e.slice(u,a),d=e.slice(a);return{type:r,sealed:d,iv:f,senderPublicKey:c}}let i=n+RT,s=e.slice(n,i),o=e.slice(i);return{type:r,sealed:o,iv:s}}function Gie(t,e){let r=n_(t);return f5({type:jh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Vt.toString(r.senderPublicKey,jr):void 0,receiverPublicKey:e?.receiverPublicKey})}function f5(t){let e=t?.type||t_;if(e===hl){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function jie(t){return t.type===hl&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}var h5="irn";function zie(t){return t?.relay||{protocol:h5}}function Qie(t){let e=ote.RELAY_JSONRPC[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Kie=Object.defineProperty,Wie=Object.defineProperties,$ie=Object.getOwnPropertyDescriptors,kM=Object.getOwnPropertySymbols,Yie=Object.prototype.hasOwnProperty,Jie=Object.prototype.propertyIsEnumerable,HM=(t,e,r)=>e in t?Kie(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,GM=(t,e)=>{for(var r in e||(e={}))Yie.call(e,r)&&HM(t,r,e[r]);if(kM)for(var r of kM(e))Jie.call(e,r)&&HM(t,r,e[r]);return t},Xie=(t,e)=>Wie(t,$ie(e));function d5(t,e="-"){let r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){let s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Zie(t){t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;let e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=Km.parse(s),u=typeof o.methods=="string"?o.methods.split(","):void 0;return{protocol:n,topic:g5(i[0]),version:parseInt(i[1],10),symKey:o.symKey,relay:d5(o),methods:u,expiryTimestamp:o.expiryTimestamp?parseInt(o.expiryTimestamp,10):void 0}}function g5(t){return t.startsWith("//")?t.substring(2):t}function p5(t,e="-"){let r="relay",n={};return Object.keys(t).forEach(i=>{let s=r+e+i;t[i]&&(n[s]=t[i])}),n}function ese(t){return`${t.protocol}:${t.topic}@${t.version}?`+Km.stringify(GM(Xie(GM({symKey:t.symKey},p5(t.relay)),{expiryTimestamp:t.expiryTimestamp}),t.methods?{methods:t.methods.join(",")}:{}))}var tse=Object.defineProperty,rse=Object.defineProperties,nse=Object.getOwnPropertyDescriptors,jM=Object.getOwnPropertySymbols,ise=Object.prototype.hasOwnProperty,sse=Object.prototype.propertyIsEnumerable,zM=(t,e,r)=>e in t?tse(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ose=(t,e)=>{for(var r in e||(e={}))ise.call(e,r)&&zM(t,r,e[r]);if(jM)for(var r of jM(e))sse.call(e,r)&&zM(t,r,e[r]);return t},ase=(t,e)=>rse(t,nse(e));function nu(t){let e=[];return t.forEach(r=>{let[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function m5(t){let e=[];return Object.values(t).forEach(r=>{e.push(...nu(r.accounts))}),e}function y5(t,e){let r=[];return Object.values(t).forEach(n=>{nu(n.accounts).includes(e)&&r.push(...n.methods)}),r}function w5(t,e){let r=[];return Object.values(t).forEach(n=>{nu(n.accounts).includes(e)&&r.push(...n.events)}),r}function use(t,e){let r=x5(t,e);if(r)throw new Error(r.message);let n={};for(let[i,s]of Object.entries(t))n[i]={methods:s.methods,events:s.events,chains:s.accounts.map(o=>`${o.split(":")[0]}:${o.split(":")[1]}`)};return n}function cse(t){let{proposal:{requiredNamespaces:e,optionalNamespaces:r={}},supportedNamespaces:n}=t,i=BT(e),s=BT(r),o={};Object.keys(n).forEach(c=>{let f=n[c].chains,d=n[c].methods,w=n[c].events,A=n[c].accounts;f.forEach(T=>{if(!A.some(x=>x.includes(T)))throw new Error(`No accounts provided for chain ${T} in namespace ${c}`)}),o[c]={chains:f,methods:d,events:w,accounts:A}});let u=D5(e,o,"approve()");if(u)throw new Error(u.message);let a={};return!Object.keys(e).length&&!Object.keys(r).length?o:(Object.keys(i).forEach(c=>{let f=n[c].chains.filter(T=>{var x,B;return(B=(x=i[c])==null?void 0:x.chains)==null?void 0:B.includes(T)}),d=n[c].methods.filter(T=>{var x,B;return(B=(x=i[c])==null?void 0:x.methods)==null?void 0:B.includes(T)}),w=n[c].events.filter(T=>{var x,B;return(B=(x=i[c])==null?void 0:x.events)==null?void 0:B.includes(T)}),A=f.map(T=>n[c].accounts.filter(x=>x.includes(`${T}:`))).flat();a[c]={chains:f,methods:d,events:w,accounts:A}}),Object.keys(s).forEach(c=>{var f,d,w,A,T,x;if(!n[c])return;let B=(d=(f=s[c])==null?void 0:f.chains)==null?void 0:d.filter(L=>n[c].chains.includes(L)),V=n[c].methods.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.methods)==null?void 0:H.includes(L)}),U=n[c].events.filter(L=>{var k,H;return(H=(k=s[c])==null?void 0:k.events)==null?void 0:H.includes(L)}),Q=B?.map(L=>n[c].accounts.filter(k=>k.includes(`${L}:`))).flat();a[c]={chains:Js((w=a[c])==null?void 0:w.chains,B),methods:Js((A=a[c])==null?void 0:A.methods,V),events:Js((T=a[c])==null?void 0:T.events,U),accounts:Js((x=a[c])==null?void 0:x.accounts,Q)}}),a)}function i_(t){return t.includes(":")}function v5(t){return i_(t)?t.split(":")[0]:t}function BT(t){var e,r,n;let i={};if(!uy(t))return i;for(let[s,o]of Object.entries(t)){let u=i_(s)?[s]:o.chains,a=o.methods||[],c=o.events||[],f=v5(s);i[f]=ase(ose({},i[f]),{chains:Js(u,(e=i[f])==null?void 0:e.chains),methods:Js(a,(r=i[f])==null?void 0:r.methods),events:Js(c,(n=i[f])==null?void 0:n.events)})}return i}function A5(t){let e={};return t?.forEach(r=>{let[n,i]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[]}),e[n].accounts.push(r),e[n].chains.push(`${n}:${i}`)}),e}function lse(t,e){e=e.map(n=>n.replace("did:pkh:",""));let r=A5(e);for(let[n,i]of Object.entries(r))i.methods?i.methods=Js(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}var E5={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},b5={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Ys(t,e){let{message:r,code:n}=b5[t];return{message:e?`${r} ${e}`:r,code:n}}function eu(t,e){let{message:r,code:n}=E5[t];return{message:e?`${r} ${e}`:r,code:n}}function zh(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function uy(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Go(t){return typeof t>"u"}function mn(t,e){return e&&Go(t)?!0:typeof t=="string"&&!!t.trim().length}function cy(t,e){return e&&Go(t)?!0:typeof t=="number"&&!isNaN(t)}function fse(t,e){let{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r),s=!0;return Ho(i,n)?(n.forEach(o=>{let{accounts:u,methods:a,events:c}=t.namespaces[o],f=nu(u),d=r[o];(!Ho(ry(o,d),f)||!Ho(d.methods,a)||!Ho(d.events,c))&&(s=!1)}),s):!1}function kh(t){return mn(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function S5(t){if(mn(t,!1)&&t.includes(":")){let e=t.split(":");if(e.length===3){let r=e[0]+":"+e[1];return!!e[2]&&kh(r)}}return!1}function hse(t){if(mn(t,!1))try{return typeof new URL(t)<"u"}catch{return!1}return!1}function dse(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function gse(t){return t?.topic}function pse(t,e){let r=null;return mn(t?.publicKey,!1)||(r=Ys("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function MT(t){let e=!0;return zh(t)?t.length&&(e=t.every(r=>mn(r,!1))):e=!1,e}function I5(t,e,r){let n=null;return zh(e)&&e.length?e.forEach(i=>{n||kh(i)||(n=eu("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):kh(t)||(n=eu("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function T5(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;let o=I5(i,ry(i,s),`${e} ${r}`);o&&(n=o)}),n}function _5(t,e){let r=null;return zh(t)?t.forEach(n=>{r||S5(n)||(r=eu("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=eu("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function C5(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=_5(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function N5(t,e){let r=null;return MT(t?.methods)?MT(t?.events)||(r=eu("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=eu("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function s_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;let i=N5(n,`${e}, namespace`);i&&(r=i)}),r}function mse(t,e,r){let n=null;if(t&&uy(t)){let i=s_(t,e);i&&(n=i);let s=T5(t,e,r);s&&(n=s)}else n=Ys("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function x5(t,e){let r=null;if(t&&uy(t)){let n=s_(t,e);n&&(r=n);let i=C5(t,e);i&&(r=i)}else r=Ys("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function O5(t){return mn(t.protocol,!0)}function yse(t,e){let r=!1;return e&&!t?r=!0:t&&zh(t)&&t.length&&t.forEach(n=>{r=O5(n)}),r}function wse(t){return typeof t=="number"}function vse(t){return typeof t<"u"&&typeof t!==null}function Ase(t){return!(!t||typeof t!="object"||!t.code||!cy(t.code,!1)||!t.message||!mn(t.message,!1))}function Ese(t){return!(Go(t)||!mn(t.method,!1))}function bse(t){return!(Go(t)||Go(t.result)&&Go(t.error)||!cy(t.id,!1)||!mn(t.jsonrpc,!1))}function Sse(t){return!(Go(t)||!mn(t.name,!1))}function Ise(t,e){return!(!kh(e)||!m5(t).includes(e))}function Tse(t,e,r){return mn(r,!1)?y5(t,e).includes(r):!1}function _se(t,e,r){return mn(r,!1)?w5(t,e).includes(r):!1}function D5(t,e,r){let n=null,i=Cse(t),s=Nse(e),o=Object.keys(i),u=Object.keys(s),a=QM(Object.keys(t)),c=QM(Object.keys(e)),f=a.filter(d=>!c.includes(d));return f.length&&(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. Required: ${f.toString()} Received: ${Object.keys(e).toString()}`)),Ho(o,u)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. Required: ${o.toString()} - Approved: ${u.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let w=iu(e[d].accounts);w.includes(d)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} + Approved: ${u.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;let w=nu(e[d].accounts);w.includes(d)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${d} Required: ${d} - Approved: ${w.toString()}`))}),o.forEach(d=>{n||(Ho(i[d].methods,s[d].methods)?Ho(i[d].events,s[d].events)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function hse(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function KM(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dse(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:iu(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function gse(t,e){return fy(t,!1)&&t<=e.max&&t>=e.min}function pse(){let t=ru();return new Promise(e=>{switch(t){case Gr.browser:e(R5());break;case Gr.reactNative:e(B5());break;case Gr.node:e(M5());break;default:e(!0)}})}function R5(){return Hh()&&navigator?.onLine}async function B5(){return al()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function M5(){return!0}function mse(t){switch(ru()){case Gr.browser:L5(t);break;case Gr.reactNative:F5(t);break;case Gr.node:break}}function L5(t){!al()&&Hh()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function F5(t){al()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var IT={},MT=class{static get(e){return IT[e]}static set(e,r){IT[e]=r}static delete(e){delete IT[e]}};K.BASE10=ZT,K.BASE16=jr,K.BASE64=ry,K.COLON=ete,K.DEFAULT_DEPTH=qT,K.EMPTY_SPACE=Ym,K.ENV_MAP=Gr,K.INTERNAL_ERRORS=S5,K.MemoryStore=MT,K.ONE_THOUSAND=tte,K.REACT_NATIVE_PRODUCT=i4,K.RELAYER_DEFAULT_PROTOCOL=d5,K.SDK_ERRORS=b5,K.SDK_TYPE=o4,K.SLASH=s4,K.TYPE_0=e_,K.TYPE_1=hl,K.UTF8=cy,K.addResourceToRecap=a5,K.appendToQueryString=a4,K.assertType=ate,K.assignAbilityToActions=YT,K.base64Decode=s5,K.base64Encode=i5,K.buildApprovedNamespaces=Wie,K.buildAuthObject=hie,K.buildNamespacesFromAuth=$ie,K.buildRecapStatement=c5,K.calcExpiry=vte,K.capitalize=dte,K.capitalizeWord=d4,K.createDelayedPromise=gte,K.createEncodedRecap=mie,K.createExpiringPromise=pte,K.createRecap=o5,K.decodeRecap=jo,K.decodeTypeByte=jh,K.decrypt=Cie,K.deriveSymKey=Sie,K.deserialize=r_,K.encodeRecap=ay,K.encodeTypeByte=l5,K.encrypt=_ie,K.engineEvent=Ete,K.enumify=hte,K.formatAccountId=e4,K.formatAccountWithChain=Qee,K.formatChainId=ZM,K.formatExpirerTarget=kT,K.formatIdTarget=yte,K.formatMessage=e5,K.formatMessageContext=ute,K.formatRelayParams=m5,K.formatRelayRpcUrl=ste,K.formatStatementFromRecap=XT,K.formatTopicTarget=mte,K.formatUA=l4,K.formatUri=qie,K.generateKeyPair=Eie,K.generateRandomBytes32=bie,K.getAccountsChains=iu,K.getAccountsFromNamespaces=Wee,K.getAddressFromAccount=t4,K.getAddressesFromAccounts=Kee,K.getAppMetadata=nte,K.getBrowserOnlineStatus=R5,K.getBundleId=rte,K.getChainFromAccount=r4,K.getChainsFromAccounts=n4,K.getChainsFromNamespace=iy,K.getChainsFromNamespaces=$ee,K.getChainsFromRecap=vie,K.getChainsFromRequiredNamespaces=Yee,K.getCommonValuesInArrays=TT,K.getDecodedRecapFromResources=t5,K.getDeepLink=Ste,K.getDidAddress=$T,K.getDidAddressSegments=oy,K.getDidChainId=WT,K.getEnvironment=ru,K.getHttpUrl=ote,K.getInternalError=Ys,K.getJavascriptID=c4,K.getJavascriptOS=u4,K.getLastItems=h4,K.getMethodsFromRecap=wie,K.getNamespacedDidChainId=lie,K.getNamespacesChains=y5,K.getNamespacesEventsForChainId=v5,K.getNamespacesFromAccounts=E5,K.getNamespacesMethodsForChainId=w5,K.getNodeOnlineStatus=M5,K.getReCapActions=n5,K.getReactNativeOnlineStatus=B5,K.getRecapAbilitiesFromResource=pie,K.getRecapFromResources=uy,K.getRecapResource=r5,K.getRelayClientMetadata=ite,K.getRelayProtocolApi=Die,K.getRelayProtocolName=Oie,K.getRequiredNamespacesFromNamespaces=Kie,K.getSdkError=tu,K.getUniqueValues=UT,K.handleDeeplinkRedirect=bte,K.hasOverlap=Ho,K.hashKey=Iie,K.hashMessage=Tie,K.isBrowser=Hh,K.isCaipNamespace=n_,K.isConformingNamespaces=P5,K.isExpired=Ate,K.isNode=VT,K.isOnline=pse,K.isProposalStruct=Xie,K.isReactNative=al,K.isRecap=JT,K.isSessionCompatible=Yie,K.isSessionStruct=Zie,K.isTypeOneEnvelope=xie,K.isUndefined=Go,K.isValidAccountId=I5,K.isValidAccounts=C5,K.isValidActions=x5,K.isValidArray=zh,K.isValidChainId=kh,K.isValidChains=T5,K.isValidController=ese,K.isValidEip1271Signature=X4,K.isValidEip191Signature=J4,K.isValidErrorReason=sse,K.isValidEvent=use,K.isValidId=nse,K.isValidNamespaceAccounts=N5,K.isValidNamespaceActions=i_,K.isValidNamespaceChains=_5,K.isValidNamespaceMethodsOrEvents=BT,K.isValidNamespaces=O5,K.isValidNamespacesChainId=cse,K.isValidNamespacesEvent=fse,K.isValidNamespacesRequest=lse,K.isValidNumber=fy,K.isValidObject=ly,K.isValidParams=ise,K.isValidRecap=ps,K.isValidRelay=D5,K.isValidRelays=rse,K.isValidRequest=ose,K.isValidRequestExpiry=gse,K.isValidRequiredNamespaces=tse,K.isValidResponse=ase,K.isValidString=mn,K.isValidUrl=Jie,K.mapEntries=fte,K.mapToObj=cte,K.mergeArrays=Js,K.mergeEncodedRecaps=yie,K.mergeRecaps=u5,K.normalizeNamespaces=RT,K.objToMap=lte,K.parseAccountId=FT,K.parseChainId=XM,K.parseContextNames=f4,K.parseExpirerTarget=wte,K.parseNamespaceKey=A5,K.parseRelayParams=g5,K.parseTopic=p5,K.parseUri=Uie,K.populateAuthPayload=die,K.recapHasResource=gie,K.serialize=f5,K.subscribeToBrowserNetworkChange=L5,K.subscribeToNetworkChange=mse,K.subscribeToReactNativeNetworkChange=F5,K.validateDecoding=Nie,K.validateEncoding=h5,K.validateSignedCacao=fie,K.verifySignature=Y4});var U5,q5,V5,k5,hy,Kh,s_,dy,zo,Wh,gy=fe(()=>{h();U5="PARSE_ERROR",q5="INVALID_REQUEST",V5="METHOD_NOT_FOUND",k5="INVALID_PARAMS",hy="INTERNAL_ERROR",Kh="SERVER_ERROR",s_=[-32700,-32600,-32601,-32602,-32603],dy=[-32e3,-32099],zo={[U5]:{code:-32700,message:"Parse error"},[q5]:{code:-32600,message:"Invalid Request"},[V5]:{code:-32601,message:"Method not found"},[k5]:{code:-32602,message:"Invalid params"},[hy]:{code:-32603,message:"Internal error"},[Kh]:{code:-32e3,message:"Server error"}},Wh=Kh});function yse(t){return t<=dy[0]&&t>=dy[1]}function py(t){return s_.includes(t)}function H5(t){return typeof t=="number"}function my(t){return Object.keys(zo).includes(t)?zo[t]:zo[Wh]}function yy(t){let e=Object.values(zo).find(r=>r.code===t);return e||zo[Wh]}function wse(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!H5(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(py(t.error.code)){let e=yy(t.error.code);if(e.message!==zo[Wh].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function o_(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var a_=fe(()=>{h();gy()});var j5=B(Qo=>{"use strict";h();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.isBrowserCryptoAvailable=Qo.getSubtleCrypto=Qo.getBrowerCrypto=void 0;function u_(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}Qo.getBrowerCrypto=u_;function G5(){let t=u_();return t.subtle||t.webkitSubtle}Qo.getSubtleCrypto=G5;function vse(){return!!u_()&&!!G5()}Qo.isBrowserCryptoAvailable=vse});var K5=B(Ko=>{"use strict";h();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.isBrowser=Ko.isNode=Ko.isReactNative=void 0;function z5(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ko.isReactNative=z5;function Q5(){return typeof I.default<"u"&&typeof I.default.versions<"u"&&typeof I.default.versions.node<"u"}Ko.isNode=Q5;function Ase(){return!z5()&&!Q5()}Ko.isBrowser=Ase});var c_=B(wy=>{"use strict";h();Object.defineProperty(wy,"__esModule",{value:!0});var W5=(es(),_e(Zi));W5.__exportStar(j5(),wy);W5.__exportStar(K5(),wy)});var Er={};Bt(Er,{isNodeJs:()=>Y5});var $5,Y5,J5=fe(()=>{h();$5=pe(c_());Tr(Er,pe(c_()));Y5=$5.isNode});function l_(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function f_(t=6){return BigInt(l_(t))}function h_(t,e,r){return{id:r||l_(),jsonrpc:"2.0",method:t,params:e}}function Ese(t,e){return{id:t,jsonrpc:"2.0",result:e}}function d_(t,e,r){return{id:t,jsonrpc:"2.0",error:X5(e,r)}}function X5(t,e){return typeof t>"u"?my(hy):(typeof t=="string"&&(t=Object.assign(Object.assign({},my(Kh)),{message:t})),typeof e<"u"&&(t.data=e),py(t.code)&&(t=yy(t.code)),t)}var Z5=fe(()=>{h();a_();gy()});function bse(t){return t.includes("*")?Ay(t):!/\W/g.test(t)}function vy(t){return t==="*"}function Ay(t){return vy(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function Sse(t){return!vy(t)&&Ay(t)&&!t.split("*")[0].trim()}function Ise(t){return!vy(t)&&Ay(t)&&!t.split("*")[1].trim()}var eL=fe(()=>{h()});var tL=fe(()=>{h()});var dl,g_=fe(()=>{h();dl=class{}});var p_,Ey,$h,rL=fe(()=>{h();g_();p_=class extends dl{constructor(e){super()}},Ey=class extends dl{constructor(){super()}},$h=class extends Ey{constructor(e){super()}}});var nL=fe(()=>{h()});var iL=fe(()=>{h();tL();g_();rL();nL()});var sL=fe(()=>{h();iL()});function Cse(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function oL(t,e){let r=Cse(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Nse(t){return oL(t,Tse)}function by(t){return oL(t,_se)}function m_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var Tse,_se,aL=fe(()=>{h();Tse="^https?:",_se="^wss?:"});function y_(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function xse(t){return y_(t)&&"method"in t}function w_(t){return y_(t)&&(uL(t)||Sy(t))}function uL(t){return"result"in t}function Sy(t){return"error"in t}function Ose(t){return"error"in t&&t.valid===!1}var cL=fe(()=>{h()});var Fr={};Bt(Fr,{DEFAULT_ERROR:()=>Wh,IBaseJsonRpcProvider:()=>Ey,IEvents:()=>dl,IJsonRpcConnection:()=>p_,IJsonRpcProvider:()=>$h,INTERNAL_ERROR:()=>hy,INVALID_PARAMS:()=>k5,INVALID_REQUEST:()=>q5,METHOD_NOT_FOUND:()=>V5,PARSE_ERROR:()=>U5,RESERVED_ERROR_CODES:()=>s_,SERVER_ERROR:()=>Kh,SERVER_ERROR_CODE_RANGE:()=>dy,STANDARD_ERROR_MAP:()=>zo,formatErrorMessage:()=>X5,formatJsonRpcError:()=>d_,formatJsonRpcRequest:()=>h_,formatJsonRpcResult:()=>Ese,getBigIntRpcId:()=>f_,getError:()=>my,getErrorByCode:()=>yy,isHttpUrl:()=>Nse,isJsonRpcError:()=>Sy,isJsonRpcPayload:()=>y_,isJsonRpcRequest:()=>xse,isJsonRpcResponse:()=>w_,isJsonRpcResult:()=>uL,isJsonRpcValidationInvalid:()=>Ose,isLocalhostUrl:()=>m_,isNodeJs:()=>Y5,isReservedErrorCode:()=>py,isServerErrorCode:()=>yse,isValidDefaultRoute:()=>vy,isValidErrorCode:()=>H5,isValidLeadingWildcardRoute:()=>Sse,isValidRoute:()=>bse,isValidTrailingWildcardRoute:()=>Ise,isValidWildcardRoute:()=>Ay,isWsUrl:()=>by,parseConnectionError:()=>o_,payloadId:()=>l_,validateJsonRpcError:()=>wse});var Yh=fe(()=>{h();gy();a_();J5();Tr(Fr,Er);Z5();eL();sL();aL();cL()});var lL,Iy,fL,v_=fe(()=>{h();lL=pe(Ds());Yh();Iy=class extends $h{constructor(e){super(e),this.events=new lL.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(h_(e.method,e.params||[],e.id||f_().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Sy(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),w_(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},fL=Iy});var hL={};Bt(hL,{JsonRpcProvider:()=>Iy,default:()=>Dse});var Dse,dL=fe(()=>{h();v_();v_();Dse=fL});var pL=B((LIe,gL)=>{"use strict";h();gL.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var vL={};Bt(vL,{WsConnection:()=>A_,default:()=>A_});var wL,Pse,Rse,mL,yL,Bse,A_,AL=fe(()=>{h();wL=pe(Ds());xc();Yh();Pse=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:pL(),Rse=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",mL=t=>t.split("?")[0],yL=10,Bse=Pse(),A_=class{constructor(e){if(this.url=e,this.events=new wL.EventEmitter,this.registering=!1,!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ai(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!by(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,Fr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!m_(e)},o=new Bse(e,[],s);Rse()?o.onerror=u=>{let a=u;n(this.emitError(a.error))}:o.on("error",u=>{n(this.emitError(u))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?Ro(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=d_(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return o_(e,mL(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>yL&&this.events.setMaxListeners(yL)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${mL(this.url)}`));return this.events.emit("register_error",r),r}}});var tF=B((Jh,pl)=>{h();var Mse=200,D_="__lodash_hash_undefined__",Py=1,PL=2,RL=9007199254740991,Ty="[object Arguments]",I_="[object Array]",Lse="[object AsyncFunction]",BL="[object Boolean]",ML="[object Date]",LL="[object Error]",FL="[object Function]",Fse="[object GeneratorFunction]",_y="[object Map]",UL="[object Number]",Use="[object Null]",gl="[object Object]",EL="[object Promise]",qse="[object Proxy]",qL="[object RegExp]",Cy="[object Set]",VL="[object String]",Vse="[object Symbol]",kse="[object Undefined]",T_="[object WeakMap]",kL="[object ArrayBuffer]",Ny="[object DataView]",Hse="[object Float32Array]",Gse="[object Float64Array]",jse="[object Int8Array]",zse="[object Int16Array]",Qse="[object Int32Array]",Kse="[object Uint8Array]",Wse="[object Uint8ClampedArray]",$se="[object Uint16Array]",Yse="[object Uint32Array]",Jse=/[\\^$.*+?()[\]{}|]/g,Xse=/^\[object .+?Constructor\]$/,Zse=/^(?:0|[1-9]\d*)$/,Mt={};Mt[Hse]=Mt[Gse]=Mt[jse]=Mt[zse]=Mt[Qse]=Mt[Kse]=Mt[Wse]=Mt[$se]=Mt[Yse]=!0;Mt[Ty]=Mt[I_]=Mt[kL]=Mt[BL]=Mt[Ny]=Mt[ML]=Mt[LL]=Mt[FL]=Mt[_y]=Mt[UL]=Mt[gl]=Mt[qL]=Mt[Cy]=Mt[VL]=Mt[T_]=!1;var HL=typeof global=="object"&&global&&global.Object===Object&&global,eoe=typeof self=="object"&&self&&self.Object===Object&&self,Xs=HL||eoe||Function("return this")(),GL=typeof Jh=="object"&&Jh&&!Jh.nodeType&&Jh,bL=GL&&typeof pl=="object"&&pl&&!pl.nodeType&&pl,jL=bL&&bL.exports===GL,E_=jL&&HL.process,SL=function(){try{return E_&&E_.binding&&E_.binding("util")}catch{}}(),IL=SL&&SL.isTypedArray;function toe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function Doe(t,e){var r=this.__data__,n=By(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}Zs.prototype.clear=Coe;Zs.prototype.delete=Noe;Zs.prototype.get=xoe;Zs.prototype.has=Ooe;Zs.prototype.set=Doe;function au(t){var e=-1,r=t==null?0:t.length;for(this.clear();++eu))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,w=r&PL?new Oy:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=RL}function ZL(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ed(t){return t!=null&&typeof t=="object"}var eF=IL?soe(IL):Woe;function uae(t){return oae(t)?joe(t):$oe(t)}function cae(){return[]}function lae(){return!1}pl.exports=aae});var P_=B((HIe,rF)=>{h();rF.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},a=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:a,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return u[f.toLowerCase()]},has:function(f){return f.toLowerCase()in u}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,w){s.push(d=d.toLowerCase()),o.push([d,w]),u[d]=u[d]?u[d]+","+w:w}),r(a())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var iF=B((jIe,nF)=>{h();nF.exports=self.fetch||(self.fetch=P_().default||P_())});var fU=B(de=>{"use strict";h();Object.defineProperty(de,"__esModule",{value:!0});var cu=Ds(),fae=(nP(),_e(rP)),id=AP(),yt=(CS(),_e(_S)),ws=QS(),sF=(xc(),_e(eP)),hae=(aB(),_e(oB)),ne=Qh(),dae=(tT(),_e(eT)),Oe=Qa(),gae=(dL(),_e(hL)),an=(Yh(),_e(Fr)),pae=(AL(),_e(vL)),mae=tF(),yae=iF();function sd(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function wae(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var vae=sd(cu),Aae=sd(fae),Ly=wae(hae),Eae=sd(pae),bae=sd(mae),Sae=sd(yae);function Iae(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");R=H,V++}for(var v=Q-R;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(R+(U-q)),C=R;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var Tae=Iae,_ae=Tae,bF=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Cae=t=>new TextEncoder().encode(t),Nae=t=>new TextDecoder().decode(t),M_=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},L_=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return SF(this,e)}},F_=class{constructor(e){this.decoders=e}or(e){return SF(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},SF=(t,e)=>new F_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),U_=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new M_(e,r,n),this.decoder=new L_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Jy=({name:t,prefix:e,encode:r,decode:n})=>new U_(t,e,r,n),od=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=_ae(r,e);return Jy({prefix:t,name:e,encode:n,decode:s=>bF(i(s))})},xae=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},Oae=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<Jy({prefix:e,name:t,encode(i){return Oae(i,n,r)},decode(i){return xae(i,n,r,t)}}),Dae=Jy({prefix:"\0",name:"identity",encode:t=>Nae(t),decode:t=>Cae(t)}),Pae=Object.freeze({__proto__:null,identity:Dae}),Rae=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Bae=Object.freeze({__proto__:null,base2:Rae}),Mae=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Lae=Object.freeze({__proto__:null,base8:Mae}),Fae=od({prefix:"9",name:"base10",alphabet:"0123456789"}),Uae=Object.freeze({__proto__:null,base10:Fae}),qae=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vae=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),kae=Object.freeze({__proto__:null,base16:qae,base16upper:Vae}),Hae=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gae=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jae=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zae=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qae=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kae=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wae=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$ae=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yae=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Jae=Object.freeze({__proto__:null,base32:Hae,base32upper:Gae,base32pad:jae,base32padupper:zae,base32hex:Qae,base32hexupper:Kae,base32hexpad:Wae,base32hexpadupper:$ae,base32z:Yae}),Xae=od({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zae=od({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),eue=Object.freeze({__proto__:null,base36:Xae,base36upper:Zae}),tue=od({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rue=od({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),nue=Object.freeze({__proto__:null,base58btc:tue,base58flickr:rue}),iue=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sue=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oue=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aue=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),uue=Object.freeze({__proto__:null,base64:iue,base64pad:sue,base64url:oue,base64urlpad:aue}),IF=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),cue=IF.reduce((t,e,r)=>(t[r]=e,t),[]),lue=IF.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fue(t){return t.reduce((e,r)=>(e+=cue[r],e),"")}function hue(t){let e=[];for(let r of t){let n=lue[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var due=Jy({prefix:"\u{1F680}",name:"base256emoji",encode:fue,decode:hue}),gue=Object.freeze({__proto__:null,base256emoji:due}),pue=TF,oF=128,mue=127,yue=~mue,wue=Math.pow(2,31);function TF(t,e,r){e=e||[],r=r||0;for(var n=r;t>=wue;)e[r++]=t&255|oF,t/=128;for(;t&yue;)e[r++]=t&255|oF,t>>>=7;return e[r]=t|0,TF.bytes=r-n+1,e}var vue=q_,Aue=128,aF=127;function q_(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw q_.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&aF)<=Aue);return q_.bytes=s-n,r}var Eue=Math.pow(2,7),bue=Math.pow(2,14),Sue=Math.pow(2,21),Iue=Math.pow(2,28),Tue=Math.pow(2,35),_ue=Math.pow(2,42),Cue=Math.pow(2,49),Nue=Math.pow(2,56),xue=Math.pow(2,63),Oue=function(t){return t(_F.encode(t,e,r),e),cF=t=>_F.encodingLength(t),V_=(t,e)=>{let r=e.byteLength,n=cF(t),i=n+cF(r),s=new Uint8Array(i+r);return uF(t,s,0),uF(r,s,n),s.set(e,i),new k_(t,r,e,s)},k_=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},CF=({name:t,code:e,encode:r})=>new H_(t,e,r),H_=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?V_(this.code,r):r.then(n=>V_(this.code,n))}else throw Error("Unknown type, must be binary type")}},NF=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Pue=CF({name:"sha2-256",code:18,encode:NF("SHA-256")}),Rue=CF({name:"sha2-512",code:19,encode:NF("SHA-512")}),Bue=Object.freeze({__proto__:null,sha256:Pue,sha512:Rue}),xF=0,Mue="identity",OF=bF,Lue=t=>V_(xF,OF(t)),Fue={code:xF,name:Mue,encode:OF,digest:Lue},Uue=Object.freeze({__proto__:null,identity:Fue});new TextEncoder,new TextDecoder;var lF={...Pae,...Bae,...Lae,...Uae,...kae,...Jae,...eue,...nue,...uue,...gue};({...Bue,...Uue});function DF(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function que(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?DF(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function PF(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var fF=PF("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),R_=PF("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=que(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Vy=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=LF,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=Ly.generateKeyPair(i);return Ly.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=ne.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=Ly.generateKeyPair(s),u=ne.generateRandomBytes32(),a=FF;return await Ly.signJWT(u,i,a,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let u=this.getPrivateKey(i),a=ne.deriveSymKey(u,s);return this.setSymKey(a,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||ne.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let u=ne.validateEncoding(o),a=sF.safeJsonStringify(s);if(ne.isTypeOneEnvelope(u)){let w=u.senderPublicKey,A=u.receiverPublicKey;i=await this.generateSharedKey(w,A)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=u;return ne.encrypt({type:f,symKey:c,message:a,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let u=ne.validateDecoding(s,o);if(ne.isTypeOneEnvelope(u)){let a=u.receiverPublicKey,c=u.senderPublicKey;i=await this.generateSharedKey(a,c)}try{let a=this.getSymKey(i),c=ne.decrypt({symKey:a,encoded:s});return sF.safeJsonParse(c)}catch(a){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(a)}},this.getPayloadType=i=>{let s=ne.deserialize(i);return ne.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=ne.deserialize(i);return s.senderPublicKey?dae.toString(s.senderPublicKey,ne.BASE16):void 0},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.keychain=n||new qy(this.core,this.logger)}get context(){return yt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(G_)}catch{e=ne.generateRandomBytes32(),await this.keychain.set(G_,e)}return kue(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},ky=class extends ws.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=VF,this.version=kF,this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=ne.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=ne.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=yt.generateChildLogger(e,this.name),this.core=r}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},z_=class extends ws.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new cu.EventEmitter,this.name=GF,this.queue=new Map,this.publishTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.failedPublishTimeout=Oe.toMiliseconds(Oe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});let u=s?.ttl||HF,a=ne.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||an.getBigIntRpcId().toString(),w={topic:n,message:i,opts:{ttl:u,relay:a,prompt:c,tag:f,id:d}},A=`Failed to publish payload, please try again. id:${d} tag:${f}`,T=Date.now(),x,R=1;try{for(;x===void 0;){if(Date.now()-T>this.publishTimeout)throw new Error(A);this.logger.trace({id:d,attempts:R},`publisher.publish - attempt ${R}`),x=await await ne.createExpiringPromise(this.rpcPublish(n,i,u,a,c,f,d).catch(V=>this.logger.warn(V)),this.publishTimeout,A),R++,x||await new Promise(V=>setTimeout(V,this.failedPublishTimeout))}this.relayer.events.emit(Zn.publish,w),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}})}catch(V){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(V),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw V;this.queue.set(d,w)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return yt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,u){var a,c,f,d;let w={method:ne.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:u};return ne.isUndefined((a=w.params)==null?void 0:a.prompt)&&((c=w.params)==null||delete c.prompt),ne.isUndefined((f=w.params)==null?void 0:f.tag)&&((d=w.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w}),this.relayer.request(w)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Zn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Zn.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},Q_=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Que=Object.defineProperty,Kue=Object.defineProperties,Wue=Object.getOwnPropertyDescriptors,hF=Object.getOwnPropertySymbols,$ue=Object.prototype.hasOwnProperty,Yue=Object.prototype.propertyIsEnumerable,dF=(t,e,r)=>e in t?Que(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rd=(t,e)=>{for(var r in e||(e={}))$ue.call(e,r)&&dF(t,r,e[r]);if(hF)for(var r of hF(e))Yue.call(e,r)&&dF(t,r,e[r]);return t},B_=(t,e)=>Kue(t,Wue(e)),Hy=class extends ws.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new Q_,this.events=new cu.EventEmitter,this.name=ZF,this.version=eU,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=eo,this.subscribeTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=ne.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let u=await this.rpcSubscribe(n,s);return typeof u=="string"&&(this.onSubscribe(u,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;let i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((s,o)=>{let u=new Oe.Watch;u.start(i);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),u.stop(i),s(!0)),u.elapsed(i)>=tU&&(clearInterval(a),u.stop(i),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.clientId=""}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=ne.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=ne.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:ne.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?ne.hashMessage(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Zn.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:ne.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(Zn.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:ne.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,B_(rd({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rd({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rd({},r)),this.topicMap.set(r.topic,e),this.events.emit(_i.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(_i.deleted,B_(rd({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_i.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);ne.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>B_(rd({},e[i]),{id:n})))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(_i.created,async e=>{let r=_i.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(_i.deleted,async e=>{let r=_i.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},Jue=Object.defineProperty,gF=Object.getOwnPropertySymbols,Xue=Object.prototype.hasOwnProperty,Zue=Object.prototype.propertyIsEnumerable,pF=(t,e,r)=>e in t?Jue(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ece=(t,e)=>{for(var r in e||(e={}))Xue.call(e,r)&&pF(t,r,e[r]);if(gF)for(var r of gF(e))Zue.call(e,r)&&pF(t,r,e[r]);return t},Gy=class extends ws.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new cu.EventEmitter,this.name=QF,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Oe.toMiliseconds(Oe.THIRTY_SECONDS+Oe.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");let s=r.id||an.getBigIntRpcId().toString();await this.toEstablishConnection();try{let o=this.provider.request(r);this.requestsInFlight.set(s,{promise:o,request:r}),this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");let u=await new Promise(async(a,c)=>{let f=()=>{c(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(yn.disconnect,f);let d=await o;this.provider.off(yn.disconnect,f),a(d)});return this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),u}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(ne.isNode())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(Zn.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Zn.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(yn.payload,this.onPayloadHandler),this.provider.on(yn.connect,this.onConnectHandler),this.provider.on(yn.disconnect,this.onDisconnectHandler),this.provider.on(yn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?yt.generateChildLogger(e.logger,this.name):yt.pino(yt.getDefaultLoggerOptions({level:e.logger||zF})),this.messages=new ky(this.logger,e.core),this.subscriber=new Hy(this,this.logger),this.publisher=new z_(this,this.logger),this.relayUrl=e?.relayUrl||W_,this.projectId=e.projectId,this.bundleId=ne.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${j_}...`),await this.restartTransport(j_)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},YF)}get context(){return yt.getLoggerContext(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",s,o=u=>{u.topic===e&&(this.subscriber.off(_i.created,o),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(_i.created,o)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,r)||i,u()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await ne.createExpiringPromise(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect(),await this.createProvider()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{let i=()=>{this.provider.off(yn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(yn.disconnect,i),await ne.createExpiringPromise(this.provider.connect(),Oe.toMiliseconds(Oe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{n(s)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ne.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}startPingTimeout(){var e,r,n,i,s;if(ne.isNode())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new gae.JsonRpcProvider(new Eae.default(ne.formatRelayRpcUrl({sdkVersion:$F,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),an.isJsonRpcRequest(e)){if(!e.method.endsWith(KF))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ece({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else an.isJsonRpcResponse(e)&&this.events.emit(Zn.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Zn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=an.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(yn.payload,this.onPayloadHandler),this.provider.off(yn.connect,this.onConnectHandler),this.provider.off(yn.disconnect,this.onDisconnectHandler),this.provider.off(yn.error,this.onProviderErrorHandler)}async registerEventListeners(){let e=await ne.isOnline();ne.subscribeToNetworkChange(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.events.emit(Zn.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Oe.toMiliseconds(WF))}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}},tce=Object.defineProperty,mF=Object.getOwnPropertySymbols,rce=Object.prototype.hasOwnProperty,nce=Object.prototype.propertyIsEnumerable,yF=(t,e,r)=>e in t?tce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wF=(t,e)=>{for(var r in e||(e={}))rce.call(e,r)&&yF(t,r,e[r]);if(mF)for(var r of mF(e))nce.call(e,r)&&yF(t,r,e[r]);return t},jy=class extends ws.IStore{constructor(e,r,n,i=eo,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=JF,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ne.isUndefined(o)?this.map.set(this.getKey(o),o):ne.isProposalStruct(o)?this.map.set(o.id,o):ne.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,u)=>{this.isInitialized(),this.map.has(o)?await this.update(o,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:u}),this.map.set(o,u),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(u=>Object.keys(o).every(a=>bae.default(u[a],o[a]))):this.values),this.update=async(o,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:u});let a=wF(wF({},this.getData(o)),u);this.map.set(o,a),await this.persist()},this.delete=async(o,u)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:u}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())},this.logger=yt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},zy=class{constructor(e,r){this.core=e,this.logger=r,this.name=rU,this.version=nU,this.events=new vae.default,this.initialized=!1,this.storagePrefix=eo,this.ignoredPayloadTypes=[ne.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let i=ne.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),o=ne.calcExpiry(Oe.FIVE_MINUTES),u={protocol:jF},a={topic:s,expiry:o,relay:u,active:!1},c=ne.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:u,expiryTimestamp:o,methods:n?.methods});return await this.pairings.set(s,a),await this.core.relayer.subscribe(s),this.core.expirer.set(s,o),{topic:s,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o,expiryTimestamp:u,methods:a}=ne.parseUri(n.uri),c;if(this.pairings.keys.includes(i)&&(c=this.pairings.get(i),c.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let f=u||ne.calcExpiry(Oe.FIVE_MINUTES),d={topic:i,relay:o,expiry:f,active:!1,methods:a};return await this.pairings.set(i,d),this.core.expirer.set(i,f),n.activatePairing&&await this.activate({topic:i}),this.events.emit(nd.create,d),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),d},this.activate=async({topic:n})=>{this.isInitialized();let i=ne.calcExpiry(Oe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:u,reject:a}=ne.createDelayedPromise();this.events.once(ne.engineEvent("pairing_ping",s),({error:c})=>{c?a(c):u()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ne.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=an.formatJsonRpcRequest(i,s),u=await this.core.crypto.encode(n,o),a=yl[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,u,a),o.id},this.sendResult=async(n,i,s)=>{let o=an.formatJsonRpcResult(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method].res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=an.formatJsonRpcError(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method]?yl[a.request.method].res:yl.unregistered_method.res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,ne.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>ne.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(nd.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{an.isJsonRpcResult(i)?this.events.emit(ne.engineEvent("pairing_ping",s),{}):an.isJsonRpcError(i)&&this.events.emit(ne.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(nd.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let u=ne.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,u),this.logger.error(u)}catch(u){await this.sendError(s,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(ne.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!ne.isValidParams(n)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!ne.isValidUrl(n.uri)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=ne.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(s!=null&&s.expiryTimestamp&&Oe.toMiliseconds(s?.expiryTimestamp){if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ne.isValidString(n,!1)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=ne.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ne.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=ne.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.pairings=new jy(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Zn.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{an.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):an.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Xn.expired,async e=>{let{topic:r}=ne.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(nd.expire,{topic:r}))})}},Qy=class extends ws.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new cu.EventEmitter,this.name=iU,this.version=sU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:ne.calcExpiry(Oe.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=an.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Jn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Jn.deleted,s)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:an.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jn.created,e=>{let r=Jn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.updated,e=>{let r=Jn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.deleted,e=>{let r=Jn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Oe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Jn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Ky=class extends ws.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new cu.EventEmitter,this.name=oU,this.version=aU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Xn.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Xn.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ne.formatTopicTarget(e);if(typeof e=="number")return ne.formatIdTarget(e);let{message:r}=ne.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Xn.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Oe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Xn.created,e=>{let r=Xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.expired,e=>{let r=Xn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.deleted,e=>{let r=Xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Wy=class extends ws.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=Fy,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||ne.isReactNative()||!ne.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Uy;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,Uy)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Oe.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{let o=document.getElementById(Fy);if(o)return this.iframe=o,this.onInit(),s();window.addEventListener("message",i);let u=document.createElement("iframe");u.id=Fy,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Oe.toMiliseconds(Oe.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||wl;return uU.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${wl}`),i=wl),i},this.logger=yt.generateChildLogger(r,this.name),this.verifyUrl=wl,this.abortController=new AbortController,this.isDevEnv=ne.isNode()&&I.default.env.IS_VITEST}get context(){return yt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Oe.toMiliseconds(e))}},$y=class extends ws.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=cU,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:u=!1}=n,a=`${lU}/${this.projectId}/clients`;await Sae.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:u})})},this.logger=yt.generateChildLogger(r,this.context)}},ice=Object.defineProperty,vF=Object.getOwnPropertySymbols,sce=Object.prototype.hasOwnProperty,oce=Object.prototype.propertyIsEnumerable,AF=(t,e,r)=>e in t?ice(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,EF=(t,e)=>{for(var r in e||(e={}))sce.call(e,r)&&AF(t,r,e[r]);if(vF)for(var r of vF(e))oce.call(e,r)&&AF(t,r,e[r]);return t},Yy=class t extends ws.ICore{constructor(e){var r;super(e),this.protocol=K_,this.version=RF,this.name=Xy,this.events=new cu.EventEmitter,this.initialized=!1,this.on=(o,u)=>this.events.on(o,u),this.once=(o,u)=>this.events.once(o,u),this.off=(o,u)=>this.events.off(o,u),this.removeListener=(o,u)=>this.events.removeListener(o,u),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||W_,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let n=yt.getDefaultLoggerOptions({level:typeof e?.logger=="string"&&e.logger?e.logger:BF.logger}),{logger:i,chunkLoggerController:s}=yt.generatePlatformLogger({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,u;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=yt.generateChildLogger(i,this.name),this.heartbeat=new id.HeartBeat,this.crypto=new Vy(this,this.logger,e?.keychain),this.history=new Qy(this,this.logger),this.expirer=new Ky(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Aae.default(EF(EF({},MF),e?.storageOptions)),this.relayer=new Gy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new zy(this,this.logger),this.verify=new Wy(this.projectId||"",this.logger),this.echoClient=new $y(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(XF,n),r}get context(){return yt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},ace=Yy;de.CORE_CONTEXT=Xy,de.CORE_DEFAULT=BF,de.CORE_PROTOCOL=K_,de.CORE_STORAGE_OPTIONS=MF,de.CORE_STORAGE_PREFIX=eo,de.CORE_VERSION=RF,de.CRYPTO_CLIENT_SEED=G_,de.CRYPTO_CONTEXT=LF,de.CRYPTO_JWT_TTL=FF,de.Core=ace,de.Crypto=Vy,de.ECHO_CONTEXT=cU,de.ECHO_URL=lU,de.EXPIRER_CONTEXT=oU,de.EXPIRER_DEFAULT_TTL=zue,de.EXPIRER_EVENTS=Xn,de.EXPIRER_STORAGE_VERSION=aU,de.EchoClient=$y,de.Expirer=Ky,de.HISTORY_CONTEXT=iU,de.HISTORY_EVENTS=Jn,de.HISTORY_STORAGE_VERSION=sU,de.JsonRpcHistory=Qy,de.KEYCHAIN_CONTEXT=UF,de.KEYCHAIN_STORAGE_VERSION=qF,de.KeyChain=qy,de.MESSAGES_CONTEXT=VF,de.MESSAGES_STORAGE_VERSION=kF,de.MessageTracker=ky,de.PAIRING_CONTEXT=rU,de.PAIRING_DEFAULT_TTL=jue,de.PAIRING_EVENTS=nd,de.PAIRING_RPC_OPTS=yl,de.PAIRING_STORAGE_VERSION=nU,de.PENDING_SUB_RESOLUTION_TIMEOUT=tU,de.PUBLISHER_CONTEXT=GF,de.PUBLISHER_DEFAULT_TTL=HF,de.Pairing=zy,de.RELAYER_CONTEXT=QF,de.RELAYER_DEFAULT_LOGGER=zF,de.RELAYER_DEFAULT_PROTOCOL=jF,de.RELAYER_DEFAULT_RELAY_URL=W_,de.RELAYER_EVENTS=Zn,de.RELAYER_FAILOVER_RELAY_URL=j_,de.RELAYER_PROVIDER_EVENTS=yn,de.RELAYER_RECONNECT_TIMEOUT=WF,de.RELAYER_SDK_VERSION=$F,de.RELAYER_STORAGE_OPTIONS=Hue,de.RELAYER_SUBSCRIBER_SUFFIX=KF,de.RELAYER_TRANSPORT_CUTOFF=YF,de.Relayer=Gy,de.STORE_STORAGE_VERSION=JF,de.SUBSCRIBER_CONTEXT=ZF,de.SUBSCRIBER_DEFAULT_TTL=Gue,de.SUBSCRIBER_EVENTS=_i,de.SUBSCRIBER_STORAGE_VERSION=eU,de.Store=jy,de.Subscriber=Hy,de.TRUSTED_VERIFY_URLS=uU,de.VERIFY_CONTEXT=Fy,de.VERIFY_FALLBACK_SERVER=Uy,de.VERIFY_SERVER=wl,de.Verify=Wy,de.WALLETCONNECT_CLIENT_ID=XF,de.default=Yy});var CU=B(Be=>{"use strict";h();Object.defineProperty(Be,"__esModule",{value:!0});var un=fU(),Zy=(CS(),_e(_S)),gU=QS(),G=Qh(),pU=Ds(),Dt=Qa(),qe=(Yh(),_e(Fr));function uce(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var cce=uce(pU),n2="wc",i2=2,s2="client",i1=`${n2}@${i2}:${s2}:`,e1={name:s2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},lce={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},fce={database:":memory:"},$_="WALLETCONNECT_DEEPLINK_CHOICE",hce={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},dce="history",gce="0.3",mU="proposal",pce=Dt.THIRTY_DAYS,yU="Proposal expired",wU="session",lu=Dt.SEVEN_DAYS,vU="engine",wn={wc_sessionPropose:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Dt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Dt.ONE_HOUR,prompt:!1,tag:1117}}},t1={min:Dt.FIVE_MINUTES,max:Dt.SEVEN_DAYS},vs={idle:"IDLE",active:"ACTIVE"},AU="request",EU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],bU="wc",mce=1.5,SU="auth",IU="authKeys",TU="pairingTopics",_U="requests",ud=`${bU}@${1.5}:${SU}:`,ad=`${ud}:PUB_KEY`,yce=Object.defineProperty,wce=Object.defineProperties,vce=Object.getOwnPropertyDescriptors,hU=Object.getOwnPropertySymbols,Ace=Object.prototype.hasOwnProperty,Ece=Object.prototype.propertyIsEnumerable,dU=(t,e,r)=>e in t?yce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e)=>{for(var r in e||(e={}))Ace.call(e,r)&&dU(t,r,e[r]);if(hU)for(var r of hU(e))Ece.call(e,r)&&dU(t,r,e[r]);return t},vl=(t,e)=>wce(t,vce(e)),Y_=class extends gU.IEngine{constructor(e){super(e),this.name=vU,this.events=new cce.default,this.initialized=!1,this.requestQueue={state:vs.idle,queue:[]},this.sessionRequestQueue={state:vs.idle,queue:[]},this.requestQueueDelay=Dt.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=vl(br({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:u,relays:a}=n,c=i,f,d=!1;try{c&&(d=this.client.core.pairing.pairings.get(c).active)}catch(L){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),L}if(!c||!d){let{topic:L,uri:k}=await this.client.core.pairing.create();c=L,f=k}if(!c){let{message:L}=G.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(L)}let w=await this.client.core.crypto.generateKeyPair(),A=wn.wc_sessionPropose.req.ttl||Dt.FIVE_MINUTES,T=G.calcExpiry(A),x=br({requiredNamespaces:s,optionalNamespaces:o,relays:a??[{protocol:un.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:T},u&&{sessionProperties:u}),{reject:R,resolve:V,done:U}=G.createDelayedPromise(A,yU);this.events.once(G.engineEvent("session_connect"),async({error:L,session:k})=>{if(L)R(L);else if(k){k.self.publicKey=w;let H=vl(br({},k),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:k.peer.metadata}),V(H)}});let Q=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:x,throwOnFailedPublish:!0});return await this.setProposal(Q,br({id:Q},x)),{uri:f,approval:U}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),U}let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o,sessionConfig:u}=r,a;try{a=this.client.proposal.get(n)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),U}let{pairingTopic:c,proposer:f,requiredNamespaces:d,optionalNamespaces:w}=a;c=c||"";let A=await this.client.core.crypto.generateKeyPair(),T=f.publicKey,x=await this.client.core.crypto.generateSharedKey(A,T),R=br(br({relay:{protocol:i??"irn"},namespaces:s,pairingTopic:c,controller:{publicKey:A,metadata:this.client.metadata},expiry:G.calcExpiry(lu)},o&&{sessionProperties:o}),u&&{sessionConfig:u});await this.client.core.relayer.subscribe(x);let V=vl(br({},R),{topic:x,requiredNamespaces:d,optionalNamespaces:w,pairingTopic:c,acknowledged:!1,self:R.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A});await this.client.session.set(x,V);try{await this.sendResult({id:n,topic:c,result:{relay:{protocol:i??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:R,throwOnFailedPublish:!0})}catch(U){throw this.client.logger.error(U),this.client.session.delete(x,G.getSdkError("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),U}return await this.client.core.pairing.updateMetadata({topic:c,metadata:f.metadata}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}),await this.setExpiry(x,G.calcExpiry(lu)),{topic:x,acknowledged:()=>new Promise(U=>setTimeout(()=>U(this.client.session.get(x)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}let{id:n,reason:i}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}let{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:u}=G.createDelayedPromise(),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),f=this.client.session.get(n).namespaces;return this.events.once(G.engineEvent("session_update",a),({error:d})=>{d?u(d):o()}),await this.client.session.update(n,{namespaces:i}),this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:f}),u(d)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}let{topic:n}=r,i=qe.payloadId(),{done:s,resolve:o,reject:u}=G.createDelayedPromise();return this.events.once(G.engineEvent("session_extend",i),({error:a})=>{a?u(a):o()}),await this.setExpiry(n,G.calcExpiry(lu)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(a=>{u(a)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(A){throw this.client.logger.error("request() -> isValidRequest() failed"),A}let{chainId:n,request:i,topic:s,expiry:o=wn.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),{done:f,resolve:d,reject:w}=G.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(G.engineEvent("session_request",a),({error:A,result:T})=>{A?w(A):d(T)}),await Promise.all([new Promise(async A=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:s,method:"wc_sessionRequest",params:{request:vl(br({},i),{expiryTimestamp:G.calcExpiry(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(T=>w(T)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),A()}),new Promise(async A=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){let x=await G.getDeepLink(this.client.core.storage,$_);G.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:x})}A()}),f()]).then(A=>A[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;qe.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):qe.isJsonRpcError(i)&&await this.sendError({id:s,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=qe.payloadId(),s=qe.getBigIntRpcId().toString(),{done:o,resolve:u,reject:a}=G.createDelayedPromise();this.events.once(G.engineEvent("session_ping",i),({error:c})=>{c?a(c):u()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r,o=qe.getBigIntRpcId().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:G.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:i}=G.getInternalError("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>G.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);let{chains:n,statement:i="",uri:s,domain:o,nonce:u,type:a,exp:c,nbf:f,methods:d=[]}=r,w=[...r.resources||[]],{topic:A,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:T}});let x=await this.client.core.crypto.generateKeyPair(),R=G.hashKey(x);if(await Promise.all([this.client.auth.authKeys.set(ad,{responseTopic:R,publicKey:x}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:A})]),await this.client.core.relayer.subscribe(R),this.client.logger.info(`sending request to new pairing topic: ${A}`),d.length>0){let{namespace:P}=G.parseChainId(n[0]),l=G.createEncodedRecap(P,"request",d);G.getRecapFromResources(w)&&(l=G.mergeEncodedRecaps(l,w.pop())),w.push(l)}let V=G.calcExpiry(wn.wc_sessionPropose.req.ttl),U={authPayload:{type:a??"caip122",chains:n,statement:i,aud:s,domain:o,version:"1",nonce:u,iat:new Date().toISOString(),exp:c,nbf:f,resources:w},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},Q={eip155:{chains:n,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},L={requiredNamespaces:{},optionalNamespaces:Q,relays:[{protocol:"irn"}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},{done:k,resolve:H,reject:q}=G.createDelayedPromise(wn.wc_sessionAuthenticate.req.ttl,"Request expired"),v=async({error:P,session:l})=>{if(this.events.off(G.engineEvent("session_request",D),C),P)q(P);else if(l){l.self.publicKey=x,await this.client.session.set(l.topic,l),await this.setExpiry(l.topic,l.expiry),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:l.peer.metadata});let g=this.client.session.get(l.topic);H({session:g})}},C=async P=>{if(P.error){let M=G.getSdkError("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===M.code?void 0:(this.events.off(G.engineEvent("session_connect"),v),q(P.error.message))}this.events.off(G.engineEvent("session_connect"),v);let{cacaos:l,responder:g}=P.result,y=[],E=[];for(let M of l){await G.validateSignedCacao({cacao:M,projectId:this.client.core.projectId})||(this.client.logger.error(M,"Signature verification failed"),q(G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:N}=M,m=G.getRecapFromResources(N.resources),O=[G.getNamespacedDidChainId(N.iss)],Y=G.getDidAddress(N.iss);if(m){let $=G.getMethodsFromRecap(m),b=G.getChainsFromRecap(m);y.push(...$),O.push(...b)}for(let $ of O)E.push(`${$}:${Y}`)}let S=await this.client.core.crypto.generateSharedKey(x,g.publicKey),_;y.length>0&&(_={topic:S,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:g,controller:g.publicKey,expiry:G.calcExpiry(lu),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:G.buildNamespacesFromAuth([...new Set(y)],[...new Set(E)])},await this.client.core.relayer.subscribe(S),await this.client.session.set(S,_),_=this.client.session.get(S)),H({auths:l,session:_})},D=qe.payloadId(),F=qe.payloadId();this.events.once(G.engineEvent("session_connect"),v),this.events.once(G.engineEvent("session_request",D),C);try{await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:D}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:L,expiry:wn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:F})])}catch(P){throw this.events.off(G.engineEvent("session_connect"),v),this.events.off(G.engineEvent("session_request",D),C),P}return await this.setProposal(F,br({id:F},L)),await this.client.auth.requests.set(D,{authPayload:U.authPayload,requester:U.requester,expiryTimestamp:V,id:D,pairingTopic:A,verifyContext:{}}),{uri:T,response:k}},this.approveSessionAuthenticate=async r=>{this.isInitialized();let{id:n,auths:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u},f=[],d=[];for(let T of i){if(!await G.validateSignedCacao({cacao:T,projectId:this.client.core.projectId})){let Q=G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:a,error:Q,encodeOpts:c}),new Error(Q.message)}let{p:x}=T,R=G.getRecapFromResources(x.resources),V=[G.getNamespacedDidChainId(x.iss)],U=G.getDidAddress(x.iss);if(R){let Q=G.getMethodsFromRecap(R),L=G.getChainsFromRecap(R);f.push(...Q),V.push(...L)}for(let Q of V)d.push(`${Q}:${U}`)}let w=await this.client.core.crypto.generateSharedKey(u,o),A;return f?.length>0&&(A={topic:w,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:o,metadata:s.requester.metadata},controller:o,expiry:G.calcExpiry(lu),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:G.buildNamespacesFromAuth([...new Set(f)],[...new Set(d)])},await this.client.core.relayer.subscribe(w),await this.client.session.set(w,A)),await this.sendResult({topic:a,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:c,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fullfilled",code:0}),await this.client.core.pairing.activate({topic:s.pairingTopic}),{session:A}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();let{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u};await this.sendError({id:n,topic:a,error:i,encodeOpts:c}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:i}=r;return G.formatMessage(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,u;return((o=s.peerMetadata)==null?void 0:o.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:i=!1,emitEvent:s=!0,id:o=0}=r,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,G.getSdkError("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem($_).catch(a=>this.client.logger.warn(a)),this.getPendingSessionRequests().forEach(a=>{a.topic===n&&this.deletePendingSessionRequest(a.id,G.getSdkError("USER_DISCONNECTED"))}),s&&this.client.events.emit("session_delete",{id:o,topic:n})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,G.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=vs.idle,this.client.events.emit("session_request_expire",{id:r}))},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,G.calcExpiry(wn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async r=>{let{id:n,topic:i,params:s,verifyContext:o}=r,u=s.request.expiryTimestamp||G.calcExpiry(wn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:u,clientRpcId:a,throwOnFailedPublish:c}=r,f=qe.formatJsonRpcRequest(i,s,a);if(G.isBrowser()&&EU.includes(i)){let A=G.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:A})}let d;try{d=await this.client.core.crypto.encode(n,f)}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let w=wn[i].req;return o&&(w.ttl=o),u&&(w.id=u),this.client.core.history.set(n,f),c?(w.internal=vl(br({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(A=>this.client.logger.error(A)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:u}=r,a=qe.formatJsonRpcResult(n,s),c;try{c=await this.client.core.crypto.encode(i,a,u)}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let f;try{f=await this.client.core.history.get(i,n)}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),w}let d=wn[f.request.method].res;o?(d.internal=vl(br({},d.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,c,d)):this.client.core.relayer.publish(i,c,d).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(a)},this.sendError=async r=>{let{id:n,topic:i,error:s,encodeOpts:o}=r,u=qe.formatJsonRpcError(n,s),a;try{a=await this.client.core.crypto.encode(i,u,o)}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let c;try{c=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}let f=wn[c.request.method].res;this.client.core.relayer.publish(i,a,f),await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;G.isExpired(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{G.isExpired(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===vs.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vs.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=vs.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:s}))switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=G.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(br({},n.params));let o=i.expiryTimestamp||G.calcExpiry(wn.wc_sessionPropose.req.ttl),u=br({id:s,pairingTopic:r,expiryTimestamp:o},i);await this.setProposal(s,u);let a=G.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(a,u.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:u,verifyContext:c})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(qe.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let u=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});let a=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});let c=await this.client.core.crypto.generateSharedKey(u,a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(qe.isJsonRpcError(n)){await this.client.proposal.delete(i,G.getSdkError("USER_DISCONNECTED"));let s=G.engineEvent("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners, 954`);this.events.emit(G.engineEvent("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:u,expiry:a,namespaces:c,sessionProperties:f,pairingTopic:d,sessionConfig:w}=n.params,A=br(br({topic:r,relay:o,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:d,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},f&&{sessionProperties:f}),w&&{sessionConfig:w});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});let T=G.engineEvent("session_connect");if(this.events.listenerCount(T)===0)throw new Error(`emitting ${T} without any listeners 997`);this.events.emit(G.engineEvent("session_connect"),{session:A}),this.cleanupDuplicatePairings(A)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;qe.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(G.engineEvent("session_approve",i),{})):qe.isJsonRpcError(n)&&(await this.client.session.delete(r,G.getSdkError("USER_DISCONNECTED")),this.events.emit(G.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:G.getSdkError("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(br({topic:r},i));try{G.MemoryStore.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){throw G.MemoryStore.delete(o),a}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_update",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,G.calcExpiry(lu)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_extend",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_ping",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_ping",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(un.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:G.getSdkError("USER_DISCONNECTED")})])}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{await this.isValidRequest(br({topic:r},s));let o=G.hashMessage(JSON.stringify(qe.formatJsonRpcRequest("wc_sessionRequest",s,i))),u=this.client.session.get(r),a=await this.getVerifyContext(o,u.peer.metadata),c={id:i,topic:r,params:s,verifyContext:a};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(br({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),G.MemoryStore.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{let{requester:i,authPayload:s,expiryTimestamp:o}=n.params,u=G.hashMessage(JSON.stringify(n)),a=await this.getVerifyContext(u,this.client.metadata),c={requester:i,pairingTopic:r,id:n.id,authPayload:s,verifyContext:a,expiryTimestamp:o};await this.client.auth.requests.set(n.id,c),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vs.idle,this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{let o=s.request.id,u=G.engineEvent("session_request",o);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(G.engineEvent("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===vs.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vs.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,qe.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(a)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:u}=r;if(G.isUndefined(n)||await this.isValidPairingTopic(n),!G.isValidRelays(u,!0)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(a)}!G.isUndefined(i)&&G.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!G.isUndefined(s)&&G.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=G.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!G.isValidParams(r))throw new Error(G.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let u=this.client.proposal.get(n),a=G.isValidNamespaces(i,"approve()");if(a)throw new Error(a.message);let c=G.isConformingNamespaces(u.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!G.isValidString(s,!0)){let{message:f}=G.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!G.isValidParams(r)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!G.isValidErrorReason(i)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!G.isValidParams(r)){let{message:c}=G.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!G.isValidRelay(n)){let{message:c}=G.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let u=G.isValidController(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);let a=G.isValidNamespaces(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(G.isExpired(o)){let{message:c}=G.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(a)}let{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=G.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let u=G.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(a)}let{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:u}=this.client.session.get(n);if(!G.isValidNamespacesChainId(u,s)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(a)}if(!G.isValidRequest(i)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(a)}if(!G.isValidNamespacesRequest(u,s,i.method)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(a)}if(o&&!G.isValidRequestExpiry(o,t1)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${t1.min} and ${t1.max}`);throw new Error(a)}},this.isValidRespond=async r=>{var n;if(!G.isValidParams(r)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!G.isValidResponse(s)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!G.isValidParams(r)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!G.isValidNamespacesChainId(o,s)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!G.isValidEvent(i)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!G.isValidNamespacesEvent(o,s,i.name)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!G.isValidString(i,!1))throw new Error("uri is required parameter");if(!G.isValidString(s,!1))throw new Error("domain is required parameter");if(!G.isValidString(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(a=>G.parseChainId(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:u}=G.parseChainId(n[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||un.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!G.isValidString(i,!1)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0,s=this.recentlyDeletedLimit/2;for(let o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){let{message:e}=G.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(un.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(ad)?this.client.auth.authKeys.get(ad):{responseTopic:void 0,publicKey:void 0},s=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{qe.isJsonRpcRequest(s)?(this.client.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):qe.isJsonRpcResponse(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.client.core.history.delete(r,s.id)):this.onRelayEventUnknownPayload({topic:r,payload:s})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(un.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=G.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,G.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(un.PAIRING_EVENTS.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(un.PAIRING_EVENTS.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=G.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:r}=G.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(G.isValidString(e,!1)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!G.isValidId(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:r}=G.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},J_=class extends un.Store{constructor(e,r){super(e,r,mU,i1),this.core=e,this.logger=r}},r1=class extends un.Store{constructor(e,r){super(e,r,wU,i1),this.core=e,this.logger=r}},X_=class extends un.Store{constructor(e,r){super(e,r,AU,i1,n=>n.id),this.core=e,this.logger=r}},Z_=class extends un.Store{constructor(e,r){super(e,r,IU,ud,()=>ad),this.core=e,this.logger=r}},e2=class extends un.Store{constructor(e,r){super(e,r,TU,ud),this.core=e,this.logger=r}},t2=class extends un.Store{constructor(e,r){super(e,r,_U,ud,n=>n.id),this.core=e,this.logger=r}},r2=class{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new Z_(this.core,this.logger),this.pairingTopics=new e2(this.core,this.logger),this.requests=new t2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},n1=class t extends gU.ISignClient{constructor(e){super(e),this.protocol=n2,this.version=i2,this.name=e1.name,this.events=new pU.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||e1.name,this.metadata=e?.metadata||G.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zy.pino(Zy.getDefaultLoggerOptions({level:e?.logger||e1.logger}));this.core=e?.core||new un.Core(e),this.logger=Zy.generateChildLogger(r,this.name),this.session=new r1(this.core,this.logger),this.proposal=new J_(this.core,this.logger),this.pendingRequest=new X_(this.core,this.logger),this.engine=new Y_(this),this.auth=new r2(this.core,this.logger)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Zy.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},bce=r1,Sce=n1;Be.AUTH_CONTEXT=SU,Be.AUTH_KEYS_CONTEXT=IU,Be.AUTH_PAIRING_TOPIC_CONTEXT=TU,Be.AUTH_PROTOCOL=bU,Be.AUTH_PUBLIC_KEY_NAME=ad,Be.AUTH_REQUEST_CONTEXT=_U,Be.AUTH_STORAGE_PREFIX=ud,Be.AUTH_VERSION=mce,Be.ENGINE_CONTEXT=vU,Be.ENGINE_QUEUE_STATES=vs,Be.ENGINE_RPC_OPTS=wn,Be.HISTORY_CONTEXT=dce,Be.HISTORY_EVENTS=hce,Be.HISTORY_STORAGE_VERSION=gce,Be.METHODS_TO_VERIFY=EU,Be.PROPOSAL_CONTEXT=mU,Be.PROPOSAL_EXPIRY=pce,Be.PROPOSAL_EXPIRY_MESSAGE=yU,Be.REQUEST_CONTEXT=AU,Be.SESSION_CONTEXT=wU,Be.SESSION_EXPIRY=lu,Be.SESSION_REQUEST_EXPIRY_BOUNDARIES=t1,Be.SIGN_CLIENT_CONTEXT=s2,Be.SIGN_CLIENT_DEFAULT=e1,Be.SIGN_CLIENT_EVENTS=lce,Be.SIGN_CLIENT_PROTOCOL=n2,Be.SIGN_CLIENT_STORAGE_OPTIONS=fce,Be.SIGN_CLIENT_STORAGE_PREFIX=i1,Be.SIGN_CLIENT_VERSION=i2,Be.SessionStore=bce,Be.SignClient=Sce,Be.WALLETCONNECT_DEEPLINK_CHOICE=$_,Be.default=n1});var s1=B(Yo=>{"use strict";h();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.OptionalOperation=Yo.Operation=void 0;var Ice;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(Ice=Yo.Operation||(Yo.Operation={}));var Tce;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(Tce=Yo.OptionalOperation||(Yo.OptionalOperation={}))});var o2=B(As=>{"use strict";h();Object.defineProperty(As,"__esModule",{value:!0});As.WALLETCONNECT_SIGN_LOGIN_DELAY=As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=As.WALLETCONNECT_MULTIVERSX_METHODS=As.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var NU=s1();As.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";As.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(NU.Operation);As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(NU.OptionalOperation);As.WALLETCONNECT_SIGN_LOGIN_DELAY=500});var c2=B(Ci=>{"use strict";h();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WalletConnectV2ProviderErrorMessagesEnum=Ci.ErrBadAddress=Ci.ErrNotImplemented=Ci.Err=void 0;var cd=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ci.Err=cd;var a2=class extends cd{constructor(){super("Method not yet implemented")}};Ci.ErrNotImplemented=a2;var u2=class extends cd{constructor(e,r){super(`Bad address: ${e}`,r)}};Ci.ErrBadAddress=u2;var _ce;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(_ce=Ci.WalletConnectV2ProviderErrorMessagesEnum||(Ci.WalletConnectV2ProviderErrorMessagesEnum={}))});var f2=B(o1=>{"use strict";h();Object.defineProperty(o1,"__esModule",{value:!0});o1.Logger=void 0;var l2=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};o1.Logger=l2});var xU=B(()=>{"use strict";h();global.Buffer||(global.Buffer=io().Buffer)});var g2=B(Al=>{"use strict";h();Object.defineProperty(Al,"__esModule",{value:!0});Al.SmartContractQueryResponse=Al.SmartContractQuery=void 0;var h2=class{constructor(e){this.contract=e.contract,this.caller=e.caller,this.value=e.value,this.function=e.function,this.arguments=e.arguments}};Al.SmartContractQuery=h2;var d2=class{constructor(e){this.function=e.function,this.returnCode=e.returnCode,this.returnMessage=e.returnMessage,this.returnDataParts=e.returnDataParts}};Al.SmartContractQueryResponse=d2});var DU=B(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});a1.QueryRunnerAdapter=void 0;var OU=Ve(),Cce=g2(),p2=class{constructor(e){this.networkProvider=e.networkProvider}async runQuery(e){let r={address:OU.Address.fromBech32(e.contract),caller:e.caller?OU.Address.fromBech32(e.caller):void 0,func:e.function,value:e.value,getEncodedArguments:()=>e.arguments.map(i=>p.Buffer.from(i).toString("hex"))},n=await this.networkProvider.queryContract(r);return new Cce.SmartContractQueryResponse({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.getReturnDataParts()})}};a1.QueryRunnerAdapter=p2});var PU=B(fu=>{"use strict";h();var Nce=fu&&fu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),xce=fu&&fu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Nce(e,t,r)};Object.defineProperty(fu,"__esModule",{value:!0});xce(DU(),fu)});var RU=B(hu=>{"use strict";h();var Oce=hu&&hu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Dce=hu&&hu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Oce(e,t,r)};Object.defineProperty(hu,"__esModule",{value:!0});Dce(JE(),hu)});var MU=B(du=>{"use strict";h();Object.defineProperty(du,"__esModule",{value:!0});du.GasEstimator=du.DefaultGasConfiguration=void 0;du.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Pce=1e5,BU=8e5,m2=class{constructor(e){this.gasConfiguration=e||du.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Pce}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+BU}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+BU)*r+this.gasConfiguration.gasPerDataByte*e}};du.GasEstimator=m2});var FU=B(LU=>{"use strict";h();Object.defineProperty(LU,"__esModule",{value:!0})});var qU=B(UU=>{"use strict";h();Object.defineProperty(UU,"__esModule",{value:!0})});var VU=B(u1=>{"use strict";h();Object.defineProperty(u1,"__esModule",{value:!0});u1.RelayedTransactionV1Builder=void 0;var y2=Ve(),Rce=Ie(),Bce=Xr(),Mce=Ms(),Lce=oE(),w2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new Rce.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${p.Buffer.from(e).toString("hex")}`,n=new Mce.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new Bce.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new y2.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new y2.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:BigInt(this.innerTransaction.getValue().toString()),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:p.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new y2.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?p.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?p.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return Lce.stringify(e)}};u1.RelayedTransactionV1Builder=w2});var HU=B(c1=>{"use strict";h();Object.defineProperty(c1,"__esModule",{value:!0});c1.RelayedTransactionV2Builder=void 0;var kU=Ie(),ld=qn(),Fce=Xr(),Uce=Ms(),v2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new kU.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new kU.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new ld.ArgSerializer().valuesToString([new ld.AddressValue(this.innerTransaction.getReceiver()),new ld.U64Value(this.innerTransaction.getNonce().valueOf()),new ld.BytesValue(this.innerTransaction.getData().valueOf()),new ld.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Uce.TransactionPayload(r),i=new Fce.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID,version:this.innerTransaction.getVersion(),options:this.innerTransaction.getOptions()});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};c1.RelayedTransactionV2Builder=v2});var GU=B(f1=>{"use strict";h();Object.defineProperty(f1,"__esModule",{value:!0});f1.SmartContractQueriesController=void 0;var qce=Ie(),Vce=g2(),l1=qn(),A2=class{constructor(e){this.abi=e.abi,this.queryRunner=e.queryRunner,this.legacyResultsParser=new l1.ResultsParser}createQuery(e){let r=this.encodeArguments(e.function,e.arguments);return new Vce.SmartContractQuery({contract:e.contract,caller:e.caller,function:e.function,arguments:r,value:e.value})}encodeArguments(e,r){let n=this.abi?.getEndpoint(e);if(n){let i=l1.NativeSerializer.nativeToTypedValues(r,n);return new l1.ArgSerializer().valuesToBuffers(i)}if(this.areArgsOfTypedValue(r))return new l1.ArgSerializer().valuesToBuffers(r);if(this.areArgsBuffers(r))return r.map(i=>p.Buffer.from(i));throw new qce.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}areArgsBuffers(e){for(let r of e)if(!ArrayBuffer.isView(r))return!1;return!0}async runQuery(e){return await this.queryRunner.runQuery(e)}parseQueryResponse(e){if(!this.abi)return e.returnDataParts;let r={returnCode:e.returnCode,returnMessage:e.returnMessage,getReturnDataParts:()=>e.returnDataParts.map(u=>p.Buffer.from(u))},n=e.function,i=this.abi.getEndpoint(n);return this.legacyResultsParser.parseQueryResponse(r,i).values.map(u=>u.valueOf())}};f1.SmartContractQueriesController=A2});var jU=B(ke=>{"use strict";h();var kce=ke&&ke.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pt=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kce(e,t,r)};Object.defineProperty(ke,"__esModule",{value:!0});xU();Pt(Ic(),ke);Pt(PU(),ke);Pt(Ve(),ke);Pt(Fb(),ke);Pt(RU(),ke);Pt(Ie(),ke);Pt(MU(),ke);Pt(FU(),ke);Pt(qU(),ke);Pt(oo(),ke);Pt(Bb(),ke);Pt($l(),ke);Pt(VU(),ke);Pt(HU(),ke);Pt(H0(),ke);Pt(GU(),ke);Pt(qn(),ke);Pt(_b(),ke);Pt(Ca(),ke);Pt(Xr(),ke);Pt(N0(),ke);Pt(Ms(),ke);Pt(V0(),ke);Pt(d0(),ke);Pt(Db(),ke);Pt(Rn(),ke)});var YU=B(ur=>{"use strict";h();var Hce=ur&&ur.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ur,"__esModule",{value:!0});ur.sleep=ur.getMetadata=ur.applyTransactionSignature=ur.getAddressFromSession=ur.addressIsValid=ur.getConnectionParams=ur.getCurrentTopic=ur.getCurrentSession=void 0;var KU=jU(),zU=Yf(),Gce=Qh(),h1=o2(),to=c2(),E2=f2(),QU=s1();function WU(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find($U(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}ur.getCurrentSession=WU;function jce(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=WU(t,e);if(!r?.topic)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}ur.getCurrentTopic=jce;function $U(t,e){var r,n,i;let s=[...h1.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(QU.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(QU.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${h1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],u=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:u}}}}ur.getConnectionParams=$U;function zce(t){try{return!KU.Address.fromBech32(t).isEmpty()}catch{return!1}}ur.addressIsValid=zce;function Qce(t){let e=t.namespaces[h1.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}ur.getAddressFromSession=Qce;function Kce({transaction:t,response:e}){if(!e)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,u=t.getGuardian().bech32();if(u&&u!==o)throw E2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(KU.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new zU.Signature(r)),n&&t.applyGuardianSignature(new zU.Signature(n)),t}ur.applyTransactionSignature=Kce;function Wce(t){if(t)return Object.assign(Object.assign({},t),{url:Gce.getAppMetadata().url})}ur.getMetadata=Wce;function $ce(t){return Hce(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}ur.sleep=$ce});var fd=B(cn=>{"use strict";h();var tr=cn&&cn.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Yce=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WalletConnectV2Provider=cn.OptionalOperation=cn.Operation=cn.WalletConnectV2ProviderErrorMessagesEnum=void 0;var Jce=Yf(),Xce=Yce(CU()),b2=Qh(),gu=o2(),he=c2();Object.defineProperty(cn,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return he.WalletConnectV2ProviderErrorMessagesEnum}});var Me=f2(),Jo=s1();Object.defineProperty(cn,"Operation",{enumerable:!0,get:function(){return Jo.Operation}});Object.defineProperty(cn,"OptionalOperation",{enumerable:!0,get:function(){return Jo.OptionalOperation}});var xr=YU(),S2=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return tr(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:xr.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield Xce.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=xr.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Me.Logger.error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return tr(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield xr.sleep(gu.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=xr.getAddressFromSession(n),o=n.namespaces[gu.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:Jo.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:u}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!u)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:u})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||xr.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:b2.getSdkError("USER_DISCONNECTED")});else{let r=xr.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:b2.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new Jce.Signature(n))}catch{throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return xr.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];xr.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${gu.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=xr.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return tr(this,void 0,void 0,function*(){return e?xr.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Me.Logger.error(`${he.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return tr(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=xr.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&xr.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:u})=>{var a;if(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)return;let{namespaces:c}=u,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>tr(this,void 0,void 0,function*(){var u;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)&&(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>tr(this,void 0,void 0,function*(){var u;!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o||(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=xr.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,u,a,c;return tr(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!b2.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(a=(u=this.walletConnector.core)===null||u===void 0?void 0:u.relayer)===null||a===void 0?void 0:a.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};cn.WalletConnectV2Provider=S2});var XU=B((RTe,JU)=>{"use strict";h();JU.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var tq=B((MTe,eq)=>{"use strict";h();var ZU=typeof Symbol<"u"&&Symbol,Zce=XU();eq.exports=function(){return typeof ZU!="function"||typeof Symbol!="function"||typeof ZU("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Zce()}});var iq=B((FTe,nq)=>{"use strict";h();var rq={foo:{}},ele=Object;nq.exports=function(){return{__proto__:rq}.foo===rq.foo&&!({__proto__:null}instanceof ele)}});var aq=B((qTe,oq)=>{"use strict";h();var tle="Function.prototype.bind called on incompatible ",rle=Object.prototype.toString,nle=Math.max,ile="[object Function]",sq=function(e,r){for(var n=[],i=0;i{"use strict";h();var ale=aq();uq.exports=Function.prototype.bind||ale});var lq=B((GTe,cq)=>{"use strict";h();var ule=Function.prototype.call,cle=Object.prototype.hasOwnProperty,lle=d1();cq.exports=lle.call(ule,cle)});var Xo=B((zTe,pq)=>{"use strict";h();var Re,Il=SyntaxError,gq=Function,Sl=TypeError,I2=function(t){try{return gq('"use strict"; return ('+t+").constructor;")()}catch{}},pu=Object.getOwnPropertyDescriptor;if(pu)try{pu({},"")}catch{pu=null}var T2=function(){throw new Sl},fle=pu?function(){try{return arguments.callee,T2}catch{try{return pu(arguments,"callee").get}catch{return T2}}}():T2,El=tq()(),hle=iq()(),Sr=Object.getPrototypeOf||(hle?function(t){return t.__proto__}:null),bl={},dle=typeof Uint8Array>"u"||!Sr?Re:Sr(Uint8Array),mu={"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":El&&Sr?Sr([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":bl,"%AsyncGenerator%":bl,"%AsyncGeneratorFunction%":bl,"%AsyncIteratorPrototype%":bl,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":gq,"%GeneratorFunction%":bl,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":El&&Sr?Sr(Sr([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!El||!Sr?Re:Sr(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!El||!Sr?Re:Sr(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":El&&Sr?Sr(""[Symbol.iterator]()):Re,"%Symbol%":El?Symbol:Re,"%SyntaxError%":Il,"%ThrowTypeError%":fle,"%TypedArray%":dle,"%TypeError%":Sl,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Sr)try{null.error}catch(t){fq=Sr(Sr(t)),mu["%Error.prototype%"]=fq}var fq,gle=function t(e){var r;if(e==="%AsyncFunction%")r=I2("async function () {}");else if(e==="%GeneratorFunction%")r=I2("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=I2("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Sr&&(r=Sr(i.prototype))}return mu[e]=r,r},hq={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},hd=d1(),g1=lq(),ple=hd.call(Function.call,Array.prototype.concat),mle=hd.call(Function.apply,Array.prototype.splice),dq=hd.call(Function.call,String.prototype.replace),p1=hd.call(Function.call,String.prototype.slice),yle=hd.call(Function.call,RegExp.prototype.exec),wle=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,vle=/\\(\\)?/g,Ale=function(e){var r=p1(e,0,1),n=p1(e,-1);if(r==="%"&&n!=="%")throw new Il("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Il("invalid intrinsic syntax, expected opening `%`");var i=[];return dq(e,wle,function(s,o,u,a){i[i.length]=u?dq(a,vle,"$1"):o||s}),i},Ele=function(e,r){var n=e,i;if(g1(hq,n)&&(i=hq[n],n="%"+i[0]+"%"),g1(mu,n)){var s=mu[n];if(s===bl&&(s=gle(n)),typeof s>"u"&&!r)throw new Sl("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Il("intrinsic "+e+" does not exist!")};pq.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Sl("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Sl('"allowMissing" argument must be a boolean');if(yle(/^%?[^%]*%?$/,e)===null)throw new Il("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Ale(e),i=n.length>0?n[0]:"",s=Ele("%"+i+"%",r),o=s.name,u=s.value,a=!1,c=s.alias;c&&(i=c[0],mle(n,ple([0,1],c)));for(var f=1,d=!0;f=n.length){var x=pu(u,w);d=!!x,d&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[w]}else d=g1(u,w),u=u[w];d&&!a&&(mu[o]=u)}}return u}});var N2=B((KTe,mq)=>{"use strict";h();var ble=Xo(),_2=ble("%Object.defineProperty%",!0),C2=function(){if(_2)try{return _2({},"a",{value:1}),!0}catch{return!1}return!1};C2.hasArrayLengthDefineBug=function(){if(!C2())return null;try{return _2([],"length",{value:1}).length!==1}catch{return!0}};mq.exports=C2});var x2=B(($Te,yq)=>{"use strict";h();var Sle=Xo(),m1=Sle("%Object.getOwnPropertyDescriptor%",!0);if(m1)try{m1([],"length")}catch{m1=null}yq.exports=m1});var Aq=B((JTe,vq)=>{"use strict";h();var Ile=N2()(),O2=Xo(),dd=Ile&&O2("%Object.defineProperty%",!0);if(dd)try{dd({},"a",{value:1})}catch{dd=!1}var Tle=O2("%SyntaxError%"),Tl=O2("%TypeError%"),wq=x2();vq.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Tl("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Tl("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Tl("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Tl("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Tl("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Tl("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,a=!!wq&&wq(e,r);if(dd)dd(e,r,{configurable:o===null&&a?a.configurable:!o,enumerable:i===null&&a?a.enumerable:!i,value:n,writable:s===null&&a?a.writable:!s});else if(u||!i&&!s&&!o)e[r]=n;else throw new Tle("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var _q=B((ZTe,Tq)=>{"use strict";h();var Iq=Xo(),Eq=Aq(),_le=N2()(),bq=x2(),Sq=Iq("%TypeError%"),Cle=Iq("%Math.floor%");Tq.exports=function(e,r){if(typeof e!="function")throw new Sq("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Cle(r)!==r)throw new Sq("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&bq){var o=bq(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(_le?Eq(e,"length",r,!0,!0):Eq(e,"length",r)),e}});var Dq=B((t_e,y1)=>{"use strict";h();var D2=d1(),_l=Xo(),Nle=_q(),xle=_l("%TypeError%"),Nq=_l("%Function.prototype.apply%"),xq=_l("%Function.prototype.call%"),Oq=_l("%Reflect.apply%",!0)||D2.call(xq,Nq),gd=_l("%Object.defineProperty%",!0),Ole=_l("%Math.max%");if(gd)try{gd({},"a",{value:1})}catch{gd=null}y1.exports=function(e){if(typeof e!="function")throw new xle("a function is required");var r=Oq(D2,xq,arguments);return Nle(r,1+Ole(0,e.length-(arguments.length-1)),!0)};var Cq=function(){return Oq(D2,Nq,arguments)};gd?gd(y1.exports,"apply",{value:Cq}):y1.exports.apply=Cq});var Mq=B((n_e,Bq)=>{"use strict";h();var Pq=Xo(),Rq=Dq(),Dle=Rq(Pq("String.prototype.indexOf"));Bq.exports=function(e,r){var n=Pq(e,!!r);return typeof n=="function"&&Dle(e,".prototype.")>-1?Rq(n):n}});var Lq=B(()=>{h()});var r7=B((u_e,t7)=>{h();var k2=typeof Map=="function"&&Map.prototype,P2=Object.getOwnPropertyDescriptor&&k2?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,v1=k2&&P2&&typeof P2.get=="function"?P2.get:null,Fq=k2&&Map.prototype.forEach,H2=typeof Set=="function"&&Set.prototype,R2=Object.getOwnPropertyDescriptor&&H2?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,A1=H2&&R2&&typeof R2.get=="function"?R2.get:null,Uq=H2&&Set.prototype.forEach,Ple=typeof WeakMap=="function"&&WeakMap.prototype,md=Ple?WeakMap.prototype.has:null,Rle=typeof WeakSet=="function"&&WeakSet.prototype,yd=Rle?WeakSet.prototype.has:null,Ble=typeof WeakRef=="function"&&WeakRef.prototype,qq=Ble?WeakRef.prototype.deref:null,Mle=Boolean.prototype.valueOf,Lle=Object.prototype.toString,Fle=Function.prototype.toString,Ule=String.prototype.match,G2=String.prototype.slice,ea=String.prototype.replace,qle=String.prototype.toUpperCase,Vq=String.prototype.toLowerCase,$q=RegExp.prototype.test,kq=Array.prototype.concat,Es=Array.prototype.join,Vle=Array.prototype.slice,Hq=Math.floor,L2=typeof BigInt=="function"?BigInt.prototype.valueOf:null,B2=Object.getOwnPropertySymbols,F2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,Cl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Ur=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Cl||!0)?Symbol.toStringTag:null,Yq=Object.prototype.propertyIsEnumerable,Gq=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function jq(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||$q.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-Hq(-t):Hq(t);if(n!==t){var i=String(n),s=G2.call(e,i.length+1);return ea.call(i,r,"$&_")+"."+ea.call(ea.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return ea.call(e,r,"$&_")}var U2=Lq(),zq=U2.custom,Qq=Xq(zq)?zq:null;t7.exports=function t(e,r,n,i){var s=r||{};if(Zo(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Zo(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=Zo(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Zo(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Zo(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var u=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return e7(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var a=String(e);return u?jq(e,a):a}if(typeof e=="bigint"){var c=String(e)+"n";return u?jq(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return q2(e)?"[Array]":"[Object]";var d=ife(s,n);if(typeof i>"u")i=[];else if(Zq(i,e)>=0)return"[Circular]";function w(l,g,y){if(g&&(i=Vle.call(i),i.push(g)),y){var E={depth:s.depth};return Zo(s,"quoteStyle")&&(E.quoteStyle=s.quoteStyle),t(l,E,n+1,i)}return t(l,s,n+1,i)}if(typeof e=="function"&&!Kq(e)){var A=$le(e),T=w1(e,w);return"[Function"+(A?": "+A:" (anonymous)")+"]"+(T.length>0?" { "+Es.call(T,", ")+" }":"")}if(Xq(e)){var x=Cl?ea.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):F2.call(e);return typeof e=="object"&&!Cl?pd(x):x}if(tfe(e)){for(var R="<"+Vq.call(String(e.nodeName)),V=e.attributes||[],U=0;U",R}if(q2(e)){if(e.length===0)return"[]";var Q=w1(e,w);return d&&!nfe(Q)?"["+V2(Q,d)+"]":"[ "+Es.call(Q,", ")+" ]"}if(Gle(e)){var L=w1(e,w);return!("cause"in Error.prototype)&&"cause"in e&&!Yq.call(e,"cause")?"{ ["+String(e)+"] "+Es.call(kq.call("[cause]: "+w(e.cause),L),", ")+" }":L.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+Es.call(L,", ")+" }"}if(typeof e=="object"&&o){if(Qq&&typeof e[Qq]=="function"&&U2)return U2(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(Yle(e)){var k=[];return Fq&&Fq.call(e,function(l,g){k.push(w(g,e,!0)+" => "+w(l,e))}),Wq("Map",v1.call(e),k,d)}if(Zle(e)){var H=[];return Uq&&Uq.call(e,function(l){H.push(w(l,e))}),Wq("Set",A1.call(e),H,d)}if(Jle(e))return M2("WeakMap");if(efe(e))return M2("WeakSet");if(Xle(e))return M2("WeakRef");if(zle(e))return pd(w(Number(e)));if(Kle(e))return pd(w(L2.call(e)));if(Qle(e))return pd(Mle.call(e));if(jle(e))return pd(w(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!Hle(e)&&!Kq(e)){var q=w1(e,w),v=Gq?Gq(e)===Object.prototype:e instanceof Object||e.constructor===Object,C=e instanceof Object?"":"null prototype",D=!v&&Ur&&Object(e)===e&&Ur in e?G2.call(ta(e),8,-1):C?"Object":"",F=v||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",P=F+(D||C?"["+Es.call(kq.call([],D||[],C||[]),": ")+"] ":"");return q.length===0?P+"{}":d?P+"{"+V2(q,d)+"}":P+"{ "+Es.call(q,", ")+" }"}return String(e)};function Jq(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function kle(t){return ea.call(String(t),/"/g,""")}function q2(t){return ta(t)==="[object Array]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Hle(t){return ta(t)==="[object Date]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Kq(t){return ta(t)==="[object RegExp]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Gle(t){return ta(t)==="[object Error]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function jle(t){return ta(t)==="[object String]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function zle(t){return ta(t)==="[object Number]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Qle(t){return ta(t)==="[object Boolean]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function Xq(t){if(Cl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!F2)return!1;try{return F2.call(t),!0}catch{}return!1}function Kle(t){if(!t||typeof t!="object"||!L2)return!1;try{return L2.call(t),!0}catch{}return!1}var Wle=Object.prototype.hasOwnProperty||function(t){return t in this};function Zo(t,e){return Wle.call(t,e)}function ta(t){return Lle.call(t)}function $le(t){if(t.name)return t.name;var e=Ule.call(Fle.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function Zq(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return e7(G2.call(t,0,e.maxStringLength),e)+n}var i=ea.call(ea.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,rfe);return Jq(i,"single",e)}function rfe(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+qle.call(e.toString(16))}function pd(t){return"Object("+t+")"}function M2(t){return t+" { ? }"}function Wq(t,e,r,n){var i=n?V2(r,n):Es.call(r,", ");return t+" ("+e+") {"+i+"}"}function nfe(t){for(var e=0;e=0)return!1;return!0}function ife(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Es.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Es.call(Array(e+1),r)}}function V2(t,e){if(t.length===0)return"";var r=` + Approved: ${w.toString()}`))}),o.forEach(d=>{n||(Ho(i[d].methods,s[d].methods)?Ho(i[d].events,s[d].events)||(n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${d}`)):n=Ys("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function Cse(t){let e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function QM(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Nse(t){let e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:nu(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function xse(t,e){return cy(t,!1)&&t<=e.max&&t>=e.min}function Ose(){let t=tu();return new Promise(e=>{switch(t){case Gr.browser:e(P5());break;case Gr.reactNative:e(R5());break;case Gr.node:e(B5());break;default:e(!0)}})}function P5(){return Hh()&&navigator?.onLine}async function R5(){return al()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function B5(){return!0}function Dse(t){switch(tu()){case Gr.browser:M5(t);break;case Gr.reactNative:L5(t);break;case Gr.node:break}}function M5(t){!al()&&Hh()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function L5(t){al()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}var TT={},LT=class{static get(e){return TT[e]}static set(e,r){TT[e]=r}static delete(e){delete TT[e]}};K.BASE10=e_,K.BASE16=jr,K.BASE64=ey,K.COLON=pte,K.DEFAULT_DEPTH=VT,K.EMPTY_SPACE=Wm,K.ENV_MAP=Gr,K.INTERNAL_ERRORS=b5,K.MemoryStore=LT,K.ONE_THOUSAND=mte,K.REACT_NATIVE_PRODUCT=n4,K.RELAYER_DEFAULT_PROTOCOL=h5,K.SDK_ERRORS=E5,K.SDK_TYPE=s4,K.SLASH=i4,K.TYPE_0=t_,K.TYPE_1=hl,K.UTF8=ay,K.addResourceToRecap=o5,K.appendToQueryString=o4,K.assertType=bte,K.assignAbilityToActions=JT,K.base64Decode=i5,K.base64Encode=n5,K.buildApprovedNamespaces=cse,K.buildAuthObject=Cie,K.buildNamespacesFromAuth=lse,K.buildRecapStatement=u5,K.calcExpiry=Bte,K.capitalize=Nte,K.capitalizeWord=h4,K.createDelayedPromise=xte,K.createEncodedRecap=Die,K.createExpiringPromise=Ote,K.createRecap=s5,K.decodeRecap=jo,K.decodeTypeByte=jh,K.decrypt=Hie,K.deriveSymKey=Uie,K.deserialize=n_,K.encodeRecap=sy,K.encodeTypeByte=c5,K.encrypt=kie,K.engineEvent=Lte,K.enumify=Cte,K.formatAccountId=ZM,K.formatAccountWithChain=ate,K.formatChainId=XM,K.formatExpirerTarget=HT,K.formatIdTarget=Pte,K.formatMessage=Z4,K.formatMessageContext=Ste,K.formatRelayParams=p5,K.formatRelayRpcUrl=Ate,K.formatStatementFromRecap=ZT,K.formatTopicTarget=Dte,K.formatUA=c4,K.formatUri=ese,K.generateKeyPair=Lie,K.generateRandomBytes32=Fie,K.getAccountsChains=nu,K.getAccountsFromNamespaces=cte,K.getAddressFromAccount=e4,K.getAddressesFromAccounts=ute,K.getAppMetadata=wte,K.getBrowserOnlineStatus=P5,K.getBundleId=yte,K.getChainFromAccount=t4,K.getChainsFromAccounts=r4,K.getChainsFromNamespace=ry,K.getChainsFromNamespaces=lte,K.getChainsFromRecap=Bie,K.getChainsFromRequiredNamespaces=fte,K.getCommonValuesInArrays=_T,K.getDecodedRecapFromResources=e5,K.getDeepLink=Ute,K.getDidAddress=YT,K.getDidAddressSegments=iy,K.getDidChainId=$T,K.getEnvironment=tu,K.getHttpUrl=Ete,K.getInternalError=Ys,K.getJavascriptID=u4,K.getJavascriptOS=a4,K.getLastItems=f4,K.getMethodsFromRecap=Rie,K.getNamespacedDidChainId=Tie,K.getNamespacesChains=m5,K.getNamespacesEventsForChainId=w5,K.getNamespacesFromAccounts=A5,K.getNamespacesMethodsForChainId=y5,K.getNodeOnlineStatus=B5,K.getReCapActions=r5,K.getReactNativeOnlineStatus=R5,K.getRecapAbilitiesFromResource=Oie,K.getRecapFromResources=oy,K.getRecapResource=t5,K.getRelayClientMetadata=vte,K.getRelayProtocolApi=Qie,K.getRelayProtocolName=zie,K.getRequiredNamespacesFromNamespaces=use,K.getSdkError=eu,K.getUniqueValues=qT,K.handleDeeplinkRedirect=Fte,K.hasOverlap=Ho,K.hashKey=qie,K.hashMessage=Vie,K.isBrowser=Hh,K.isCaipNamespace=i_,K.isConformingNamespaces=D5,K.isExpired=Mte,K.isNode=kT,K.isOnline=Ose,K.isProposalStruct=dse,K.isReactNative=al,K.isRecap=XT,K.isSessionCompatible=fse,K.isSessionStruct=gse,K.isTypeOneEnvelope=jie,K.isUndefined=Go,K.isValidAccountId=S5,K.isValidAccounts=_5,K.isValidActions=N5,K.isValidArray=zh,K.isValidChainId=kh,K.isValidChains=I5,K.isValidController=pse,K.isValidEip1271Signature=J4,K.isValidEip191Signature=Y4,K.isValidErrorReason=Ase,K.isValidEvent=Sse,K.isValidId=wse,K.isValidNamespaceAccounts=C5,K.isValidNamespaceActions=s_,K.isValidNamespaceChains=T5,K.isValidNamespaceMethodsOrEvents=MT,K.isValidNamespaces=x5,K.isValidNamespacesChainId=Ise,K.isValidNamespacesEvent=_se,K.isValidNamespacesRequest=Tse,K.isValidNumber=cy,K.isValidObject=uy,K.isValidParams=vse,K.isValidRecap=ps,K.isValidRelay=O5,K.isValidRelays=yse,K.isValidRequest=Ese,K.isValidRequestExpiry=xse,K.isValidRequiredNamespaces=mse,K.isValidResponse=bse,K.isValidString=mn,K.isValidUrl=hse,K.mapEntries=_te,K.mapToObj=Ite,K.mergeArrays=Js,K.mergeEncodedRecaps=Pie,K.mergeRecaps=a5,K.normalizeNamespaces=BT,K.objToMap=Tte,K.parseAccountId=UT,K.parseChainId=JM,K.parseContextNames=l4,K.parseExpirerTarget=Rte,K.parseNamespaceKey=v5,K.parseRelayParams=d5,K.parseTopic=g5,K.parseUri=Zie,K.populateAuthPayload=Nie,K.recapHasResource=xie,K.serialize=l5,K.subscribeToBrowserNetworkChange=M5,K.subscribeToNetworkChange=Dse,K.subscribeToReactNativeNetworkChange=L5,K.validateDecoding=Gie,K.validateEncoding=f5,K.validateSignedCacao=_ie,K.verifySignature=$4});var F5,U5,q5,V5,ly,Kh,o_,fy,zo,Wh,hy=fe(()=>{h();F5="PARSE_ERROR",U5="INVALID_REQUEST",q5="METHOD_NOT_FOUND",V5="INVALID_PARAMS",ly="INTERNAL_ERROR",Kh="SERVER_ERROR",o_=[-32700,-32600,-32601,-32602,-32603],fy=[-32e3,-32099],zo={[F5]:{code:-32700,message:"Parse error"},[U5]:{code:-32600,message:"Invalid Request"},[q5]:{code:-32601,message:"Method not found"},[V5]:{code:-32602,message:"Invalid params"},[ly]:{code:-32603,message:"Internal error"},[Kh]:{code:-32e3,message:"Server error"}},Wh=Kh});function Pse(t){return t<=fy[0]&&t>=fy[1]}function dy(t){return o_.includes(t)}function k5(t){return typeof t=="number"}function gy(t){return Object.keys(zo).includes(t)?zo[t]:zo[Wh]}function py(t){let e=Object.values(zo).find(r=>r.code===t);return e||zo[Wh]}function Rse(t){if(typeof t.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof t.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!k5(t.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${t.error.code}`};if(dy(t.error.code)){let e=py(t.error.code);if(e.message!==zo[Wh].message&&t.error.message===e.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${t.error.code}`}}return{valid:!0}}function a_(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var u_=fe(()=>{h();hy()});var G5=D(Qo=>{"use strict";h();Object.defineProperty(Qo,"__esModule",{value:!0});Qo.isBrowserCryptoAvailable=Qo.getSubtleCrypto=Qo.getBrowerCrypto=void 0;function c_(){return(global===null||global===void 0?void 0:global.crypto)||(global===null||global===void 0?void 0:global.msCrypto)||{}}Qo.getBrowerCrypto=c_;function H5(){let t=c_();return t.subtle||t.webkitSubtle}Qo.getSubtleCrypto=H5;function Bse(){return!!c_()&&!!H5()}Qo.isBrowserCryptoAvailable=Bse});var Q5=D(Ko=>{"use strict";h();Object.defineProperty(Ko,"__esModule",{value:!0});Ko.isBrowser=Ko.isNode=Ko.isReactNative=void 0;function j5(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ko.isReactNative=j5;function z5(){return typeof S.default<"u"&&typeof S.default.versions<"u"&&typeof S.default.versions.node<"u"}Ko.isNode=z5;function Mse(){return!j5()&&!z5()}Ko.isBrowser=Mse});var l_=D(my=>{"use strict";h();Object.defineProperty(my,"__esModule",{value:!0});var K5=(es(),_e(Zi));K5.__exportStar(G5(),my);K5.__exportStar(Q5(),my)});var Er={};Bt(Er,{isNodeJs:()=>$5});var W5,$5,Y5=fe(()=>{h();W5=pe(l_());Tr(Er,pe(l_()));$5=W5.isNode});function f_(t=3){let e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function h_(t=6){return BigInt(f_(t))}function d_(t,e,r){return{id:r||f_(),jsonrpc:"2.0",method:t,params:e}}function Lse(t,e){return{id:t,jsonrpc:"2.0",result:e}}function g_(t,e,r){return{id:t,jsonrpc:"2.0",error:J5(e,r)}}function J5(t,e){return typeof t>"u"?gy(ly):(typeof t=="string"&&(t=Object.assign(Object.assign({},gy(Kh)),{message:t})),typeof e<"u"&&(t.data=e),dy(t.code)&&(t=py(t.code)),t)}var X5=fe(()=>{h();u_();hy()});function Fse(t){return t.includes("*")?wy(t):!/\W/g.test(t)}function yy(t){return t==="*"}function wy(t){return yy(t)?!0:!(!t.includes("*")||t.split("*").length!==2||t.split("*").filter(e=>e.trim()==="").length!==1)}function Use(t){return!yy(t)&&wy(t)&&!t.split("*")[0].trim()}function qse(t){return!yy(t)&&wy(t)&&!t.split("*")[1].trim()}var Z5=fe(()=>{h()});var eL=fe(()=>{h()});var dl,p_=fe(()=>{h();dl=class{}});var m_,vy,$h,tL=fe(()=>{h();p_();m_=class extends dl{constructor(e){super()}},vy=class extends dl{constructor(){super()}},$h=class extends vy{constructor(e){super()}}});var rL=fe(()=>{h()});var nL=fe(()=>{h();eL();p_();tL();rL()});var iL=fe(()=>{h();nL()});function Hse(t){let e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function sL(t,e){let r=Hse(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Gse(t){return sL(t,Vse)}function Ay(t){return sL(t,kse)}function y_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}var Vse,kse,oL=fe(()=>{h();Vse="^https?:",kse="^wss?:"});function w_(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function jse(t){return w_(t)&&"method"in t}function v_(t){return w_(t)&&(aL(t)||Ey(t))}function aL(t){return"result"in t}function Ey(t){return"error"in t}function zse(t){return"error"in t&&t.valid===!1}var uL=fe(()=>{h()});var Fr={};Bt(Fr,{DEFAULT_ERROR:()=>Wh,IBaseJsonRpcProvider:()=>vy,IEvents:()=>dl,IJsonRpcConnection:()=>m_,IJsonRpcProvider:()=>$h,INTERNAL_ERROR:()=>ly,INVALID_PARAMS:()=>V5,INVALID_REQUEST:()=>U5,METHOD_NOT_FOUND:()=>q5,PARSE_ERROR:()=>F5,RESERVED_ERROR_CODES:()=>o_,SERVER_ERROR:()=>Kh,SERVER_ERROR_CODE_RANGE:()=>fy,STANDARD_ERROR_MAP:()=>zo,formatErrorMessage:()=>J5,formatJsonRpcError:()=>g_,formatJsonRpcRequest:()=>d_,formatJsonRpcResult:()=>Lse,getBigIntRpcId:()=>h_,getError:()=>gy,getErrorByCode:()=>py,isHttpUrl:()=>Gse,isJsonRpcError:()=>Ey,isJsonRpcPayload:()=>w_,isJsonRpcRequest:()=>jse,isJsonRpcResponse:()=>v_,isJsonRpcResult:()=>aL,isJsonRpcValidationInvalid:()=>zse,isLocalhostUrl:()=>y_,isNodeJs:()=>$5,isReservedErrorCode:()=>dy,isServerErrorCode:()=>Pse,isValidDefaultRoute:()=>yy,isValidErrorCode:()=>k5,isValidLeadingWildcardRoute:()=>Use,isValidRoute:()=>Fse,isValidTrailingWildcardRoute:()=>qse,isValidWildcardRoute:()=>wy,isWsUrl:()=>Ay,parseConnectionError:()=>a_,payloadId:()=>f_,validateJsonRpcError:()=>Rse});var Yh=fe(()=>{h();hy();u_();Y5();Tr(Fr,Er);X5();Z5();iL();oL();uL()});var cL,by,lL,A_=fe(()=>{h();cL=pe(Ds());Yh();by=class extends $h{constructor(e){super(e),this.events=new cL.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(d_(e.method,e.params||[],e.id||h_().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Ey(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),v_(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}},lL=by});var fL={};Bt(fL,{JsonRpcProvider:()=>by,default:()=>Qse});var Qse,hL=fe(()=>{h();A_();A_();Qse=lL});var gL=D((rTe,dL)=>{"use strict";h();dL.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var wL={};Bt(wL,{WsConnection:()=>E_,default:()=>E_});var yL,Kse,Wse,pL,mL,$se,E_,vL=fe(()=>{h();yL=pe(Ds());xc();Yh();Kse=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:gL(),Wse=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",pL=t=>t.split("?")[0],mL=10,$se=Kse(),E_=class{constructor(e){if(this.url=e,this.events=new yL.EventEmitter,this.registering=!1,!Ay(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ai(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Ay(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{let i=new URLSearchParams(e).get("origin"),s=(0,Fr.isReactNative)()?{headers:{origin:i}}:{rejectUnauthorized:!y_(e)},o=new $se(e,[],s);Wse()?o.onerror=u=>{let a=u;n(this.emitError(a.error))}:o.on("error",u=>{n(this.emitError(u))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;let r=typeof e.data=="string"?Ro(e.data):e.data;this.events.emit("payload",r)}onError(e,r){let n=this.parseError(r),i=n.message||n.toString(),s=g_(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return a_(e,pL(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>mL&&this.events.setMaxListeners(mL)}emitError(e){let r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${pL(this.url)}`));return this.events.emit("register_error",r),r}}});var eF=D((Jh,pl)=>{h();var Yse=200,P_="__lodash_hash_undefined__",Oy=1,DL=2,PL=9007199254740991,Sy="[object Arguments]",T_="[object Array]",Jse="[object AsyncFunction]",RL="[object Boolean]",BL="[object Date]",ML="[object Error]",LL="[object Function]",Xse="[object GeneratorFunction]",Iy="[object Map]",FL="[object Number]",Zse="[object Null]",gl="[object Object]",AL="[object Promise]",eoe="[object Proxy]",UL="[object RegExp]",Ty="[object Set]",qL="[object String]",toe="[object Symbol]",roe="[object Undefined]",__="[object WeakMap]",VL="[object ArrayBuffer]",_y="[object DataView]",noe="[object Float32Array]",ioe="[object Float64Array]",soe="[object Int8Array]",ooe="[object Int16Array]",aoe="[object Int32Array]",uoe="[object Uint8Array]",coe="[object Uint8ClampedArray]",loe="[object Uint16Array]",foe="[object Uint32Array]",hoe=/[\\^$.*+?()[\]{}|]/g,doe=/^\[object .+?Constructor\]$/,goe=/^(?:0|[1-9]\d*)$/,Mt={};Mt[noe]=Mt[ioe]=Mt[soe]=Mt[ooe]=Mt[aoe]=Mt[uoe]=Mt[coe]=Mt[loe]=Mt[foe]=!0;Mt[Sy]=Mt[T_]=Mt[VL]=Mt[RL]=Mt[_y]=Mt[BL]=Mt[ML]=Mt[LL]=Mt[Iy]=Mt[FL]=Mt[gl]=Mt[UL]=Mt[Ty]=Mt[qL]=Mt[__]=!1;var kL=typeof global=="object"&&global&&global.Object===Object&&global,poe=typeof self=="object"&&self&&self.Object===Object&&self,Xs=kL||poe||Function("return this")(),HL=typeof Jh=="object"&&Jh&&!Jh.nodeType&&Jh,EL=HL&&typeof pl=="object"&&pl&&!pl.nodeType&&pl,GL=EL&&EL.exports===HL,b_=GL&&kL.process,bL=function(){try{return b_&&b_.binding&&b_.binding("util")}catch{}}(),SL=bL&&bL.isTypedArray;function moe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r-1}function Qoe(t,e){var r=this.__data__,n=Py(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}Zs.prototype.clear=Hoe;Zs.prototype.delete=Goe;Zs.prototype.get=joe;Zs.prototype.has=zoe;Zs.prototype.set=Qoe;function ou(t){var e=-1,r=t==null?0:t.length;for(this.clear();++eu))return!1;var c=s.get(t);if(c&&s.get(e))return c==e;var f=-1,d=!0,w=r&DL?new Ny:void 0;for(s.set(t,e),s.set(e,t);++f-1&&t%1==0&&t-1&&t%1==0&&t<=PL}function XL(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function ed(t){return t!=null&&typeof t=="object"}var ZL=SL?Aoe(SL):cae;function Sae(t){return Eae(t)?sae(t):lae(t)}function Iae(){return[]}function Tae(){return!1}pl.exports=bae});var R_=D((uTe,tF)=>{h();tF.exports=function(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},a=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:a,headers:{keys:function(){return s},entries:function(){return o},get:function(f){return u[f.toLowerCase()]},has:function(f){return f.toLowerCase()in u}}}};for(var c in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(f,d,w){s.push(d=d.toLowerCase()),o.push([d,w]),u[d]=u[d]?u[d]+","+w:w}),r(a())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(c,e.headers[c]);i.send(e.body||null)})}});var nF=D((lTe,rF)=>{h();rF.exports=self.fetch||(self.fetch=R_().default||R_())});var lU=D(de=>{"use strict";h();Object.defineProperty(de,"__esModule",{value:!0});var uu=Ds(),_ae=(rP(),_e(tP)),id=vP(),yt=(NS(),_e(CS)),ws=KS(),iF=(xc(),_e(Z8)),Cae=(oB(),_e(sB)),ne=Qh(),Nae=(rT(),_e(tT)),Oe=za(),xae=(hL(),_e(fL)),an=(Yh(),_e(Fr)),Oae=(vL(),_e(wL)),Dae=eF(),Pae=nF();function sd(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}function Rae(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var Bae=sd(uu),Mae=sd(_ae),By=Rae(Cae),Lae=sd(Oae),Fae=sd(Dae),Uae=sd(Pae);function qae(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,L=new Uint8Array(Q);V!==U;){for(var k=T[V],H=0,q=Q-1;(k!==0||H>>0,L[q]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");B=H,V++}for(var v=Q-B;v!==Q&&L[v]===0;)v++;for(var C=a.repeat(x);v>>0,Q=new Uint8Array(U);T[x];){var L=r[T.charCodeAt(x)];if(L===255)return;for(var k=0,H=U-1;(L!==0||k>>0,Q[H]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");V=k,x++}if(T[x]!==" "){for(var q=U-V;q!==U&&Q[q]===0;)q++;for(var v=new Uint8Array(B+(U-q)),C=B;q!==U;)v[C++]=Q[q++];return v}}}function A(T){var x=w(T);if(x)return x;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:w,decode:A}}var Vae=qae,kae=Vae,EF=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Hae=t=>new TextEncoder().encode(t),Gae=t=>new TextDecoder().decode(t),L_=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},F_=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return bF(this,e)}},U_=class{constructor(e){this.decoders=e}or(e){return bF(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},bF=(t,e)=>new U_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),q_=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new L_(e,r,n),this.decoder=new F_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},$y=({name:t,prefix:e,encode:r,decode:n})=>new q_(t,e,r,n),od=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=kae(r,e);return $y({prefix:t,name:e,encode:n,decode:s=>EF(i(s))})},jae=(t,e,r,n)=>{let i={};for(let f=0;f=8&&(u-=8,o[c++]=255&a>>u)}if(u>=r||255&a<<8-u)throw new SyntaxError("Unexpected end of data");return o},zae=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<r;)o-=r,s+=e[i&u>>o];if(o&&(s+=e[i&u<$y({prefix:e,name:t,encode(i){return zae(i,n,r)},decode(i){return jae(i,n,r,t)}}),Qae=$y({prefix:"\0",name:"identity",encode:t=>Gae(t),decode:t=>Hae(t)}),Kae=Object.freeze({__proto__:null,identity:Qae}),Wae=Nr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),$ae=Object.freeze({__proto__:null,base2:Wae}),Yae=Nr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Jae=Object.freeze({__proto__:null,base8:Yae}),Xae=od({prefix:"9",name:"base10",alphabet:"0123456789"}),Zae=Object.freeze({__proto__:null,base10:Xae}),eue=Nr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tue=Nr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),rue=Object.freeze({__proto__:null,base16:eue,base16upper:tue}),nue=Nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),iue=Nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),sue=Nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oue=Nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),aue=Nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),uue=Nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cue=Nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lue=Nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fue=Nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),hue=Object.freeze({__proto__:null,base32:nue,base32upper:iue,base32pad:sue,base32padupper:oue,base32hex:aue,base32hexupper:uue,base32hexpad:cue,base32hexpadupper:lue,base32z:fue}),due=od({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),gue=od({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),pue=Object.freeze({__proto__:null,base36:due,base36upper:gue}),mue=od({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yue=od({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),wue=Object.freeze({__proto__:null,base58btc:mue,base58flickr:yue}),vue=Nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Aue=Nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Eue=Nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bue=Nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Sue=Object.freeze({__proto__:null,base64:vue,base64pad:Aue,base64url:Eue,base64urlpad:bue}),SF=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Iue=SF.reduce((t,e,r)=>(t[r]=e,t),[]),Tue=SF.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function _ue(t){return t.reduce((e,r)=>(e+=Iue[r],e),"")}function Cue(t){let e=[];for(let r of t){let n=Tue[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var Nue=$y({prefix:"\u{1F680}",name:"base256emoji",encode:_ue,decode:Cue}),xue=Object.freeze({__proto__:null,base256emoji:Nue}),Oue=IF,sF=128,Due=127,Pue=~Due,Rue=Math.pow(2,31);function IF(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Rue;)e[r++]=t&255|sF,t/=128;for(;t&Pue;)e[r++]=t&255|sF,t>>>=7;return e[r]=t|0,IF.bytes=r-n+1,e}var Bue=V_,Mue=128,oF=127;function V_(t,n){var r=0,n=n||0,i=0,s=n,o,u=t.length;do{if(s>=u)throw V_.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&oF)<=Mue);return V_.bytes=s-n,r}var Lue=Math.pow(2,7),Fue=Math.pow(2,14),Uue=Math.pow(2,21),que=Math.pow(2,28),Vue=Math.pow(2,35),kue=Math.pow(2,42),Hue=Math.pow(2,49),Gue=Math.pow(2,56),jue=Math.pow(2,63),zue=function(t){return t(TF.encode(t,e,r),e),uF=t=>TF.encodingLength(t),k_=(t,e)=>{let r=e.byteLength,n=uF(t),i=n+uF(r),s=new Uint8Array(i+r);return aF(t,s,0),aF(r,s,n),s.set(e,i),new H_(t,r,e,s)},H_=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}},_F=({name:t,code:e,encode:r})=>new G_(t,e,r),G_=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?k_(this.code,r):r.then(n=>k_(this.code,n))}else throw Error("Unknown type, must be binary type")}},CF=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Kue=_F({name:"sha2-256",code:18,encode:CF("SHA-256")}),Wue=_F({name:"sha2-512",code:19,encode:CF("SHA-512")}),$ue=Object.freeze({__proto__:null,sha256:Kue,sha512:Wue}),NF=0,Yue="identity",xF=EF,Jue=t=>k_(NF,xF(t)),Xue={code:NF,name:Yue,encode:xF,digest:Jue},Zue=Object.freeze({__proto__:null,identity:Xue});new TextEncoder,new TextDecoder;var cF={...Kae,...$ae,...Jae,...Zae,...rue,...hue,...pue,...wue,...Sue,...xue};({...$ue,...Zue});function OF(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function ece(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?OF(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function DF(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var lF=DF("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),B_=DF("ascii","a",t=>{let e="a";for(let r=0;r{t=t.substring(1);let e=ece(t.length);for(let r=0;r{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();let i=this.keychain.get(n);if(typeof i>"u"){let{message:s}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getKeyChain(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Uy=class{constructor(e,r,n){this.core=e,this.logger=r,this.name=MF,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();let i=await this.getClientSeed(),s=By.generateKeyPair(i);return By.encodeIss(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();let i=ne.generateKeyPair();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();let s=await this.getClientSeed(),o=By.generateKeyPair(s),u=ne.generateRandomBytes32(),a=LF;return await By.signJWT(u,i,a,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();let u=this.getPrivateKey(i),a=ne.deriveSymKey(u,s);return this.setSymKey(a,o)},this.setSymKey=async(i,s)=>{this.isInitialized();let o=s||ne.hashKey(i);return await this.keychain.set(o,i),o},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,s,o)=>{this.isInitialized();let u=ne.validateEncoding(o),a=iF.safeJsonStringify(s);if(ne.isTypeOneEnvelope(u)){let w=u.senderPublicKey,A=u.receiverPublicKey;i=await this.generateSharedKey(w,A)}let c=this.getSymKey(i),{type:f,senderPublicKey:d}=u;return ne.encrypt({type:f,symKey:c,message:a,senderPublicKey:d})},this.decode=async(i,s,o)=>{this.isInitialized();let u=ne.validateDecoding(s,o);if(ne.isTypeOneEnvelope(u)){let a=u.receiverPublicKey,c=u.senderPublicKey;i=await this.generateSharedKey(a,c)}try{let a=this.getSymKey(i),c=ne.decrypt({symKey:a,encoded:s});return iF.safeJsonParse(c)}catch(a){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(a)}},this.getPayloadType=i=>{let s=ne.deserialize(i);return ne.decodeTypeByte(s.type)},this.getPayloadSenderPublicKey=i=>{let s=ne.deserialize(i);return s.senderPublicKey?Nae.toString(s.senderPublicKey,ne.BASE16):void 0},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.keychain=n||new Fy(this.core,this.logger)}get context(){return yt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(j_)}catch{e=ne.generateRandomBytes32(),await this.keychain.set(j_,e)}return rce(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},qy=class extends ws.IMessageTracker{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=qF,this.version=VF,this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();let s=ne.hashMessage(i),o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();let s=this.get(n),o=ne.hashMessage(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=yt.generateChildLogger(e,this.name),this.core=r}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,ne.mapToObj(e))}async getRelayerMessages(){let e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ne.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Q_=class extends ws.IPublisher{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new uu.EventEmitter,this.name=HF,this.queue=new Map,this.publishTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.failedPublishTimeout=Oe.toMiliseconds(Oe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});let u=s?.ttl||kF,a=ne.getRelayProtocolName(s),c=s?.prompt||!1,f=s?.tag||0,d=s?.id||an.getBigIntRpcId().toString(),w={topic:n,message:i,opts:{ttl:u,relay:a,prompt:c,tag:f,id:d}},A=`Failed to publish payload, please try again. id:${d} tag:${f}`,T=Date.now(),x,B=1;try{for(;x===void 0;){if(Date.now()-T>this.publishTimeout)throw new Error(A);this.logger.trace({id:d,attempts:B},`publisher.publish - attempt ${B}`),x=await await ne.createExpiringPromise(this.rpcPublish(n,i,u,a,c,f,d).catch(V=>this.logger.warn(V)),this.publishTimeout,A),B++,x||await new Promise(V=>setTimeout(V,this.failedPublishTimeout))}this.relayer.events.emit(Zn.publish,w),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}})}catch(V){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(V),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw V;this.queue.set(d,w)}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return yt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o,u){var a,c,f,d;let w={method:ne.getRelayProtocolApi(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o},id:u};return ne.isUndefined((a=w.params)==null?void 0:a.prompt)&&((c=w.params)==null||delete c.prompt),ne.isUndefined((f=w.params)==null?void 0:f.tag)&&((d=w.params)==null||delete d.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w}),this.relayer.request(w)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{let{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Zn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Zn.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}},K_=class{constructor(){this.map=new Map,this.set=(e,r)=>{let n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;let n=this.get(e);if(!this.exists(e,r))return;let i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},ace=Object.defineProperty,uce=Object.defineProperties,cce=Object.getOwnPropertyDescriptors,fF=Object.getOwnPropertySymbols,lce=Object.prototype.hasOwnProperty,fce=Object.prototype.propertyIsEnumerable,hF=(t,e,r)=>e in t?ace(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rd=(t,e)=>{for(var r in e||(e={}))lce.call(e,r)&&hF(t,r,e[r]);if(fF)for(var r of fF(e))fce.call(e,r)&&hF(t,r,e[r]);return t},M_=(t,e)=>uce(t,cce(e)),Vy=class extends ws.ISubscriber{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new K_,this.events=new uu.EventEmitter,this.name=XF,this.version=ZF,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=eo,this.subscribeTimeout=Oe.toMiliseconds(Oe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{let s=ne.getRelayProtocolName(i),o={topic:n,relay:s};this.pending.set(n,o);let u=await this.rpcSubscribe(n,s);return typeof u=="string"&&(this.onSubscribe(u,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>{if(this.topics.includes(n))return!0;let i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((s,o)=>{let u=new Oe.Watch;u.start(i);let a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),u.stop(i),s(!0)),u.elapsed(i)>=eU&&(clearInterval(a),u.stop(i),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=yt.generateChildLogger(r,this.name),this.clientId=""}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){let n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{let i=ne.getRelayProtocolName(n);await this.rpcUnsubscribe(e,r,i);let s=ne.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){let n={method:ne.getRelayProtocolApi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)?ne.hashMessage(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Zn.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;let r=e[0].relay,n={method:ne.getRelayProtocolApi(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await ne.createExpiringPromise(this.relayer.request(n).catch(i=>this.logger.warn(i)),this.subscribeTimeout)}catch{this.relayer.events.emit(Zn.connection_stalled)}}rpcUnsubscribe(e,r,n){let i={method:ne.getRelayProtocolApi(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,M_(rd({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rd({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rd({},r)),this.topicMap.set(r.topic,e),this.events.emit(_i.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});let r=this.subscriptions.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});let n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(_i.deleted,M_(rd({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(_i.sync)}async reset(){if(this.cached.length){let e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!e.length)return;if(this.subscriptions.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;let r=await this.rpcBatchSubscribe(e);ne.isValidArray(r)&&this.onBatchSubscribe(r.map((n,i)=>M_(rd({},e[i]),{id:n})))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;let e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(_i.created,async e=>{let r=_i.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(_i.deleted,async e=>{let r=_i.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}},hce=Object.defineProperty,dF=Object.getOwnPropertySymbols,dce=Object.prototype.hasOwnProperty,gce=Object.prototype.propertyIsEnumerable,gF=(t,e,r)=>e in t?hce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pce=(t,e)=>{for(var r in e||(e={}))dce.call(e,r)&&gF(t,r,e[r]);if(dF)for(var r of dF(e))gce.call(e,r)&&gF(t,r,e[r]);return t},ky=class extends ws.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new uu.EventEmitter,this.name=zF,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=Oe.toMiliseconds(Oe.THIRTY_SECONDS+Oe.ONE_SECOND),this.request=async r=>{var n,i;this.logger.debug("Publishing Request Payload");let s=r.id||an.getBigIntRpcId().toString();await this.toEstablishConnection();try{let o=this.provider.request(r);this.requestsInFlight.set(s,{promise:o,request:r}),this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - attempt to publish...");let u=await new Promise(async(a,c)=>{let f=()=>{c(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(yn.disconnect,f);let d=await o;this.provider.off(yn.disconnect,f),a(d)});return this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - published"),u}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(ne.isNode())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i;(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.startPingTimeout(),this.events.emit(Zn.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Zn.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(yn.payload,this.onPayloadHandler),this.provider.on(yn.connect,this.onConnectHandler),this.provider.on(yn.disconnect,this.onDisconnectHandler),this.provider.on(yn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?yt.generateChildLogger(e.logger,this.name):yt.pino(yt.getDefaultLoggerOptions({level:e.logger||jF})),this.messages=new qy(this.logger,e.core),this.subscriber=new Vy(this,this.logger),this.publisher=new Q_(this,this.logger),this.relayUrl=e?.relayUrl||$_,this.projectId=e.projectId,this.bundleId=ne.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${z_}...`),await this.restartTransport(z_)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},$F)}get context(){return yt.getLoggerContext(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",s,o=u=>{u.topic===e&&(this.subscriber.off(_i.created,o),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(_i.created,o)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,r)||i,u()})]),i}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await ne.createExpiringPromise(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect(),await this.createProvider()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,n)=>{let i=()=>{this.provider.off(yn.disconnect,i),n(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(yn.disconnect,i),await ne.createExpiringPromise(this.provider.connect(),Oe.toMiliseconds(Oe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{n(s)}),await this.subscriber.start(),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);let n=r;if(!this.isConnectionStalled(n.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ne.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}startPingTimeout(){var e,r,n,i,s;if(ne.isNode())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xae.JsonRpcProvider(new Lae.default(ne.formatRelayRpcUrl({sdkVersion:WF,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){let{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){let{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;let i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),an.isJsonRpcRequest(e)){if(!e.method.endsWith(QF))return;let r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(pce({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else an.isJsonRpcResponse(e)&&this.events.emit(Zn.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Zn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){let r=an.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(yn.payload,this.onPayloadHandler),this.provider.off(yn.connect,this.onConnectHandler),this.provider.off(yn.disconnect,this.onDisconnectHandler),this.provider.off(yn.error,this.onProviderErrorHandler)}async registerEventListeners(){let e=await ne.isOnline();ne.subscribeToNetworkChange(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.events.emit(Zn.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Oe.toMiliseconds(KF))}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{let r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}},mce=Object.defineProperty,pF=Object.getOwnPropertySymbols,yce=Object.prototype.hasOwnProperty,wce=Object.prototype.propertyIsEnumerable,mF=(t,e,r)=>e in t?mce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yF=(t,e)=>{for(var r in e||(e={}))yce.call(e,r)&&mF(t,r,e[r]);if(pF)for(var r of pF(e))wce.call(e,r)&&mF(t,r,e[r]);return t},Hy=class extends ws.IStore{constructor(e,r,n,i=eo,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=YF,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ne.isUndefined(o)?this.map.set(this.getKey(o),o):ne.isProposalStruct(o)?this.map.set(o.id,o):ne.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,u)=>{this.isInitialized(),this.map.has(o)?await this.update(o,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:u}),this.map.set(o,u),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(u=>Object.keys(o).every(a=>Fae.default(u[a],o[a]))):this.values),this.update=async(o,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:u});let a=yF(yF({},this.getData(o)),u);this.map.set(o,a),await this.persist()},this.delete=async(o,u)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:u}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())},this.logger=yt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){let r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Gy=class{constructor(e,r){this.core=e,this.logger=r,this.name=tU,this.version=rU,this.events=new Bae.default,this.initialized=!1,this.storagePrefix=eo,this.ignoredPayloadTypes=[ne.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let i=ne.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),o=ne.calcExpiry(Oe.FIVE_MINUTES),u={protocol:GF},a={topic:s,expiry:o,relay:u,active:!1},c=ne.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:u,expiryTimestamp:o,methods:n?.methods});return await this.pairings.set(s,a),await this.core.relayer.subscribe(s),this.core.expirer.set(s,o),{topic:s,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);let{topic:i,symKey:s,relay:o,expiryTimestamp:u,methods:a}=ne.parseUri(n.uri),c;if(this.pairings.keys.includes(i)&&(c=this.pairings.get(i),c.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);let f=u||ne.calcExpiry(Oe.FIVE_MINUTES),d={topic:i,relay:o,expiry:f,active:!1,methods:a};return await this.pairings.set(i,d),this.core.expirer.set(i,f),n.activatePairing&&await this.activate({topic:i}),this.events.emit(nd.create,d),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),d},this.activate=async({topic:n})=>{this.isInitialized();let i=ne.calcExpiry(Oe.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);let{topic:i}=n;if(this.pairings.keys.includes(i)){let s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:u,reject:a}=ne.createDelayedPromise();this.events.once(ne.engineEvent("pairing_ping",s),({error:c})=>{c?a(c):u()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ne.getSdkError("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{let o=an.formatJsonRpcRequest(i,s),u=await this.core.crypto.encode(n,o),a=yl[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,u,a),o.id},this.sendResult=async(n,i,s)=>{let o=an.formatJsonRpcResult(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method].res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{let o=an.formatJsonRpcError(n,s),u=await this.core.crypto.encode(i,o),a=await this.core.history.get(i,n),c=yl[a.request.method]?yl[a.request.method].res:yl.unregistered_method.res;await this.core.relayer.publish(i,u,c),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,ne.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(i=>ne.isExpired(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{let{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{let{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{let{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(nd.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{let{id:s}=i;setTimeout(()=>{an.isJsonRpcResult(i)?this.events.emit(ne.engineEvent("pairing_ping",s),{}):an.isJsonRpcError(i)&&this.events.emit(ne.engineEvent("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{let{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(nd.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{let{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;let u=ne.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,u),this.logger.error(u)}catch(u){await this.sendError(s,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(ne.getSdkError("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!ne.isValidParams(n)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(o)}if(!ne.isValidUrl(n.uri)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(o)}let s=ne.parseUri(n.uri);if(!((i=s?.relay)!=null&&i.protocol)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(s!=null&&s.symKey)){let{message:o}=ne.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(s!=null&&s.expiryTimestamp&&Oe.toMiliseconds(s?.expiryTimestamp){if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!ne.isValidParams(n)){let{message:s}=ne.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ne.isValidString(n,!1)){let{message:i}=ne.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){let{message:i}=ne.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ne.isExpired(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:i}=ne.getInternalError("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=yt.generateChildLogger(r,this.name),this.pairings=new Hy(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Zn.message,async e=>{let{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;let i=await this.core.crypto.decode(r,n);try{an.isJsonRpcRequest(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):an.isJsonRpcResponse(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Xn.expired,async e=>{let{topic:r}=ne.parseExpirerTarget(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(nd.expire,{topic:r}))})}},jy=class extends ws.IJsonRpcHistory{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new uu.EventEmitter,this.name=nU,this.version=iU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;let o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:ne.calcExpiry(Oe.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jn.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=an.isJsonRpcError(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Jn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Jn.deleted,s)}}),this.persist()},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:an.formatJsonRpcRequest(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();let r=this.records.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jn.sync)}async restore(){try{let e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jn.created,e=>{let r=Jn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.updated,e=>{let r=Jn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Jn.deleted,e=>{let r=Jn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Oe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Jn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},zy=class extends ws.IExpirer{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new uu.EventEmitter,this.name=sU,this.version=oU,this.cached=[],this.initialized=!1,this.storagePrefix=eo,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();let s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Xn.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();let i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){let i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Xn.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=yt.generateChildLogger(r,this.name)}get context(){return yt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ne.formatTopicTarget(e);if(typeof e=="number")return ne.formatIdTarget(e);let{message:r}=ne.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Xn.sync)}async restore(){try{let e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){let{message:r}=ne.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){let r=this.expirations.get(e);if(!r){let{message:n}=ne.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){let{expiry:n}=r;Oe.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(id.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Xn.created,e=>{let r=Xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.expired,e=>{let r=Xn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xn.deleted,e=>{let r=Xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){let{message:e}=ne.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}},Qy=class extends ws.IVerify{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=My,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||ne.isReactNative()||!ne.isBrowser())return;let i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Ly;try{await this.createIframe()}catch(s){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(s),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";let i=this.getVerifyUrl(n?.verifyUrl),s;try{s=await this.fetchAttestation(n.attestationId,i)}catch(o){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(o),s=await this.fetchAttestation(n.attestationId,Ly)}return s},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);let s=this.startAbortTimer(Oe.ONE_SECOND*2),o=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(s),o.status===200?await o.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n,i=s=>{s.data==="verify_ready"&&(this.onInit(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(s=>{let o=document.getElementById(My);if(o)return this.iframe=o,this.onInit(),s();window.addEventListener("message",i);let u=document.createElement("iframe");u.id=My,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,n=s}),new Promise((s,o)=>setTimeout(()=>{window.removeEventListener("message",i),o("verify iframe load timeout")},Oe.toMiliseconds(Oe.FIVE_SECONDS)))])},this.onInit=()=>{this.initialized=!0,this.processQueue()},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||wl;return aU.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${wl}`),i=wl),i},this.logger=yt.generateChildLogger(r,this.name),this.verifyUrl=wl,this.abortController=new AbortController,this.isDevEnv=ne.isNode()&&S.default.env.IS_VITEST}get context(){return yt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Oe.toMiliseconds(e))}},Ky=class extends ws.IEchoClient{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=uU,this.registerDeviceToken=async n=>{let{clientId:i,token:s,notificationType:o,enableEncrypted:u=!1}=n,a=`${cU}/${this.projectId}/clients`;await Uae.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:u})})},this.logger=yt.generateChildLogger(r,this.context)}},vce=Object.defineProperty,wF=Object.getOwnPropertySymbols,Ace=Object.prototype.hasOwnProperty,Ece=Object.prototype.propertyIsEnumerable,vF=(t,e,r)=>e in t?vce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,AF=(t,e)=>{for(var r in e||(e={}))Ace.call(e,r)&&vF(t,r,e[r]);if(wF)for(var r of wF(e))Ece.call(e,r)&&vF(t,r,e[r]);return t},Wy=class t extends ws.ICore{constructor(e){var r;super(e),this.protocol=W_,this.version=PF,this.name=Yy,this.events=new uu.EventEmitter,this.initialized=!1,this.on=(o,u)=>this.events.on(o,u),this.once=(o,u)=>this.events.once(o,u),this.off=(o,u)=>this.events.off(o,u),this.removeListener=(o,u)=>this.events.removeListener(o,u),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||$_,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";let n=yt.getDefaultLoggerOptions({level:typeof e?.logger=="string"&&e.logger?e.logger:RF.logger}),{logger:i,chunkLoggerController:s}=yt.generatePlatformLogger({opts:n,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,u;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=yt.generateChildLogger(i,this.name),this.heartbeat=new id.HeartBeat,this.crypto=new Uy(this,this.logger,e?.keychain),this.history=new jy(this,this.logger),this.expirer=new zy(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Mae.default(AF(AF({},BF),e?.storageOptions)),this.relayer=new ky({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Gy(this,this.logger),this.verify=new Qy(this.projectId||"",this.logger),this.echoClient=new Ky(this.projectId||"",this.logger)}static async init(e){let r=new t(e);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(JF,n),r}get context(){return yt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}},bce=Wy;de.CORE_CONTEXT=Yy,de.CORE_DEFAULT=RF,de.CORE_PROTOCOL=W_,de.CORE_STORAGE_OPTIONS=BF,de.CORE_STORAGE_PREFIX=eo,de.CORE_VERSION=PF,de.CRYPTO_CLIENT_SEED=j_,de.CRYPTO_CONTEXT=MF,de.CRYPTO_JWT_TTL=LF,de.Core=bce,de.Crypto=Uy,de.ECHO_CONTEXT=uU,de.ECHO_URL=cU,de.EXPIRER_CONTEXT=sU,de.EXPIRER_DEFAULT_TTL=oce,de.EXPIRER_EVENTS=Xn,de.EXPIRER_STORAGE_VERSION=oU,de.EchoClient=Ky,de.Expirer=zy,de.HISTORY_CONTEXT=nU,de.HISTORY_EVENTS=Jn,de.HISTORY_STORAGE_VERSION=iU,de.JsonRpcHistory=jy,de.KEYCHAIN_CONTEXT=FF,de.KEYCHAIN_STORAGE_VERSION=UF,de.KeyChain=Fy,de.MESSAGES_CONTEXT=qF,de.MESSAGES_STORAGE_VERSION=VF,de.MessageTracker=qy,de.PAIRING_CONTEXT=tU,de.PAIRING_DEFAULT_TTL=sce,de.PAIRING_EVENTS=nd,de.PAIRING_RPC_OPTS=yl,de.PAIRING_STORAGE_VERSION=rU,de.PENDING_SUB_RESOLUTION_TIMEOUT=eU,de.PUBLISHER_CONTEXT=HF,de.PUBLISHER_DEFAULT_TTL=kF,de.Pairing=Gy,de.RELAYER_CONTEXT=zF,de.RELAYER_DEFAULT_LOGGER=jF,de.RELAYER_DEFAULT_PROTOCOL=GF,de.RELAYER_DEFAULT_RELAY_URL=$_,de.RELAYER_EVENTS=Zn,de.RELAYER_FAILOVER_RELAY_URL=z_,de.RELAYER_PROVIDER_EVENTS=yn,de.RELAYER_RECONNECT_TIMEOUT=KF,de.RELAYER_SDK_VERSION=WF,de.RELAYER_STORAGE_OPTIONS=nce,de.RELAYER_SUBSCRIBER_SUFFIX=QF,de.RELAYER_TRANSPORT_CUTOFF=$F,de.Relayer=ky,de.STORE_STORAGE_VERSION=YF,de.SUBSCRIBER_CONTEXT=XF,de.SUBSCRIBER_DEFAULT_TTL=ice,de.SUBSCRIBER_EVENTS=_i,de.SUBSCRIBER_STORAGE_VERSION=ZF,de.Store=Hy,de.Subscriber=Vy,de.TRUSTED_VERIFY_URLS=aU,de.VERIFY_CONTEXT=My,de.VERIFY_FALLBACK_SERVER=Ly,de.VERIFY_SERVER=wl,de.Verify=Qy,de.WALLETCONNECT_CLIENT_ID=JF,de.default=Wy});var _U=D(Be=>{"use strict";h();Object.defineProperty(Be,"__esModule",{value:!0});var un=lU(),Jy=(NS(),_e(CS)),dU=KS(),G=Qh(),gU=Ds(),Dt=za(),qe=(Yh(),_e(Fr));function Sce(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var Ice=Sce(gU),i2="wc",s2=2,o2="client",r1=`${i2}@${s2}:${o2}:`,Xy={name:o2,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},Tce={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},_ce={database:":memory:"},Y_="WALLETCONNECT_DEEPLINK_CHOICE",Cce={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Nce="history",xce="0.3",pU="proposal",Oce=Dt.THIRTY_DAYS,mU="Proposal expired",yU="session",cu=Dt.SEVEN_DAYS,wU="engine",wn={wc_sessionPropose:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Dt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Dt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Dt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Dt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Dt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Dt.ONE_HOUR,prompt:!1,tag:1117}}},Zy={min:Dt.FIVE_MINUTES,max:Dt.SEVEN_DAYS},vs={idle:"IDLE",active:"ACTIVE"},vU="request",AU=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"],EU="wc",Dce=1.5,bU="auth",SU="authKeys",IU="pairingTopics",TU="requests",ud=`${EU}@${1.5}:${bU}:`,ad=`${ud}:PUB_KEY`,Pce=Object.defineProperty,Rce=Object.defineProperties,Bce=Object.getOwnPropertyDescriptors,fU=Object.getOwnPropertySymbols,Mce=Object.prototype.hasOwnProperty,Lce=Object.prototype.propertyIsEnumerable,hU=(t,e,r)=>e in t?Pce(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e)=>{for(var r in e||(e={}))Mce.call(e,r)&&hU(t,r,e[r]);if(fU)for(var r of fU(e))Lce.call(e,r)&&hU(t,r,e[r]);return t},vl=(t,e)=>Rce(t,Bce(e)),J_=class extends dU.IEngine{constructor(e){super(e),this.name=wU,this.events=new Ice.default,this.initialized=!1,this.requestQueue={state:vs.idle,queue:[]},this.sessionRequestQueue={state:vs.idle,queue:[]},this.requestQueueDelay=Dt.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(wn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();let n=vl(br({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);let{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:u,relays:a}=n,c=i,f,d=!1;try{c&&(d=this.client.core.pairing.pairings.get(c).active)}catch(L){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),L}if(!c||!d){let{topic:L,uri:k}=await this.client.core.pairing.create();c=L,f=k}if(!c){let{message:L}=G.getInternalError("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(L)}let w=await this.client.core.crypto.generateKeyPair(),A=wn.wc_sessionPropose.req.ttl||Dt.FIVE_MINUTES,T=G.calcExpiry(A),x=br({requiredNamespaces:s,optionalNamespaces:o,relays:a??[{protocol:un.RELAYER_DEFAULT_PROTOCOL}],proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:T},u&&{sessionProperties:u}),{reject:B,resolve:V,done:U}=G.createDelayedPromise(A,mU);this.events.once(G.engineEvent("session_connect"),async({error:L,session:k})=>{if(L)B(L);else if(k){k.self.publicKey=w;let H=vl(br({},k),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(k.topic,H),await this.setExpiry(k.topic,k.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:k.peer.metadata}),V(H)}});let Q=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:x,throwOnFailedPublish:!0});return await this.setProposal(Q,br({id:Q},x)),{uri:f,approval:U}},this.pair=async r=>{await this.isInitialized();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{await this.isInitialized();try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),U}let{id:n,relayProtocol:i,namespaces:s,sessionProperties:o,sessionConfig:u}=r,a;try{a=this.client.proposal.get(n)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${n}) failed`),U}let{pairingTopic:c,proposer:f,requiredNamespaces:d,optionalNamespaces:w}=a;c=c||"";let A=await this.client.core.crypto.generateKeyPair(),T=f.publicKey,x=await this.client.core.crypto.generateSharedKey(A,T),B=br(br({relay:{protocol:i??"irn"},namespaces:s,pairingTopic:c,controller:{publicKey:A,metadata:this.client.metadata},expiry:G.calcExpiry(cu)},o&&{sessionProperties:o}),u&&{sessionConfig:u});await this.client.core.relayer.subscribe(x);let V=vl(br({},B),{topic:x,requiredNamespaces:d,optionalNamespaces:w,pairingTopic:c,acknowledged:!1,self:B.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:A});await this.client.session.set(x,V);try{await this.sendResult({id:n,topic:c,result:{relay:{protocol:i??"irn"},responderPublicKey:A},throwOnFailedPublish:!0}),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:B,throwOnFailedPublish:!0})}catch(U){throw this.client.logger.error(U),this.client.session.delete(x,G.getSdkError("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),U}return await this.client.core.pairing.updateMetadata({topic:c,metadata:f.metadata}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}),await this.setExpiry(x,G.calcExpiry(cu)),{topic:x,acknowledged:()=>new Promise(U=>setTimeout(()=>U(this.client.session.get(x)),500))}},this.reject=async r=>{await this.isInitialized();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}let{id:n,reason:i}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}let{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:u}=G.createDelayedPromise(),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),f=this.client.session.get(n).namespaces;return this.events.once(G.engineEvent("session_update",a),({error:d})=>{d?u(d):o()}),await this.client.session.update(n,{namespaces:i}),this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:f}),u(d)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}let{topic:n}=r,i=qe.payloadId(),{done:s,resolve:o,reject:u}=G.createDelayedPromise();return this.events.once(G.engineEvent("session_extend",i),({error:a})=>{a?u(a):o()}),await this.setExpiry(n,G.calcExpiry(cu)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(a=>{u(a)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(A){throw this.client.logger.error("request() -> isValidRequest() failed"),A}let{chainId:n,request:i,topic:s,expiry:o=wn.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),a=qe.payloadId(),c=qe.getBigIntRpcId().toString(),{done:f,resolve:d,reject:w}=G.createDelayedPromise(o,"Request expired. Please try again.");return this.events.once(G.engineEvent("session_request",a),({error:A,result:T})=>{A?w(A):d(T)}),await Promise.all([new Promise(async A=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:s,method:"wc_sessionRequest",params:{request:vl(br({},i),{expiryTimestamp:G.calcExpiry(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0}).catch(T=>w(T)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:a}),A()}),new Promise(async A=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){let x=await G.getDeepLink(this.client.core.storage,Y_);G.handleDeeplinkRedirect({id:a,topic:s,wcDeepLink:x})}A()}),f()]).then(A=>A[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);let{topic:n,response:i}=r,{id:s}=i;qe.isJsonRpcResult(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0}):qe.isJsonRpcError(i)&&await this.sendError({id:s,topic:n,error:i.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}let{topic:n}=r;if(this.client.session.keys.includes(n)){let i=qe.payloadId(),s=qe.getBigIntRpcId().toString(),{done:o,resolve:u,reject:a}=G.createDelayedPromise();this.events.once(G.engineEvent("session_ping",i),({error:c})=>{c?a(c):u()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);let{topic:n,event:i,chainId:s}=r,o=qe.getBigIntRpcId().toString();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:G.getSdkError("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:i}=G.getInternalError("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>G.isSessionCompatible(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);let{chains:n,statement:i="",uri:s,domain:o,nonce:u,type:a,exp:c,nbf:f,methods:d=[]}=r,w=[...r.resources||[]],{topic:A,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:T}});let x=await this.client.core.crypto.generateKeyPair(),B=G.hashKey(x);if(await Promise.all([this.client.auth.authKeys.set(ad,{responseTopic:B,publicKey:x}),this.client.auth.pairingTopics.set(B,{topic:B,pairingTopic:A})]),await this.client.core.relayer.subscribe(B),this.client.logger.info(`sending request to new pairing topic: ${A}`),d.length>0){let{namespace:R}=G.parseChainId(n[0]),l=G.createEncodedRecap(R,"request",d);G.getRecapFromResources(w)&&(l=G.mergeEncodedRecaps(l,w.pop())),w.push(l)}let V=G.calcExpiry(wn.wc_sessionPropose.req.ttl),U={authPayload:{type:a??"caip122",chains:n,statement:i,aud:s,domain:o,version:"1",nonce:u,iat:new Date().toISOString(),exp:c,nbf:f,resources:w},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},Q={eip155:{chains:n,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},L={requiredNamespaces:{},optionalNamespaces:Q,relays:[{protocol:"irn"}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:V},{done:k,resolve:H,reject:q}=G.createDelayedPromise(wn.wc_sessionAuthenticate.req.ttl,"Request expired"),v=async({error:R,session:l})=>{if(this.events.off(G.engineEvent("session_request",P),C),R)q(R);else if(l){l.self.publicKey=x,await this.client.session.set(l.topic,l),await this.setExpiry(l.topic,l.expiry),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:l.peer.metadata});let g=this.client.session.get(l.topic);H({session:g})}},C=async R=>{if(R.error){let M=G.getSdkError("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return R.error.code===M.code?void 0:(this.events.off(G.engineEvent("session_connect"),v),q(R.error.message))}this.events.off(G.engineEvent("session_connect"),v);let{cacaos:l,responder:g}=R.result,y=[],E=[];for(let M of l){await G.validateSignedCacao({cacao:M,projectId:this.client.core.projectId})||(this.client.logger.error(M,"Signature verification failed"),q(G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:N}=M,m=G.getRecapFromResources(N.resources),O=[G.getNamespacedDidChainId(N.iss)],Y=G.getDidAddress(N.iss);if(m){let $=G.getMethodsFromRecap(m),b=G.getChainsFromRecap(m);y.push(...$),O.push(...b)}for(let $ of O)E.push(`${$}:${Y}`)}let I=await this.client.core.crypto.generateSharedKey(x,g.publicKey),_;y.length>0&&(_={topic:I,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:g,controller:g.publicKey,expiry:G.calcExpiry(cu),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:G.buildNamespacesFromAuth([...new Set(y)],[...new Set(E)])},await this.client.core.relayer.subscribe(I),await this.client.session.set(I,_),_=this.client.session.get(I)),H({auths:l,session:_})},P=qe.payloadId(),F=qe.payloadId();this.events.once(G.engineEvent("session_connect"),v),this.events.once(G.engineEvent("session_request",P),C);try{await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:L,expiry:wn.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:F})])}catch(R){throw this.events.off(G.engineEvent("session_connect"),v),this.events.off(G.engineEvent("session_request",P),C),R}return await this.setProposal(F,br({id:F},L)),await this.client.auth.requests.set(P,{authPayload:U.authPayload,requester:U.requester,expiryTimestamp:V,id:P,pairingTopic:A,verifyContext:{}}),{uri:T,response:k}},this.approveSessionAuthenticate=async r=>{this.isInitialized();let{id:n,auths:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u},f=[],d=[];for(let T of i){if(!await G.validateSignedCacao({cacao:T,projectId:this.client.core.projectId})){let Q=G.getSdkError("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:a,error:Q,encodeOpts:c}),new Error(Q.message)}let{p:x}=T,B=G.getRecapFromResources(x.resources),V=[G.getNamespacedDidChainId(x.iss)],U=G.getDidAddress(x.iss);if(B){let Q=G.getMethodsFromRecap(B),L=G.getChainsFromRecap(B);f.push(...Q),V.push(...L)}for(let Q of V)d.push(`${Q}:${U}`)}let w=await this.client.core.crypto.generateSharedKey(u,o),A;return f?.length>0&&(A={topic:w,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:o,metadata:s.requester.metadata},controller:o,expiry:G.calcExpiry(cu),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:"",namespaces:G.buildNamespacesFromAuth([...new Set(f)],[...new Set(d)])},await this.client.core.relayer.subscribe(w),await this.client.session.set(w,A)),await this.sendResult({topic:a,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:c,throwOnFailedPublish:!0}),await this.client.auth.requests.delete(n,{message:"fullfilled",code:0}),await this.client.core.pairing.activate({topic:s.pairingTopic}),{session:A}},this.rejectSessionAuthenticate=async r=>{await this.isInitialized();let{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);let o=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),a=G.hashKey(o),c={type:G.TYPE_1,receiverPublicKey:o,senderPublicKey:u};await this.sendError({id:n,topic:a,error:i,encodeOpts:c}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,G.getSdkError("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:i}=r;return G.formatMessage(n,i)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,u;return((o=s.peerMetadata)==null?void 0:o.url)&&((u=s.peerMetadata)==null?void 0:u.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:i=!1,emitEvent:s=!0,id:o=0}=r,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,G.getSdkError("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Y_).catch(a=>this.client.logger.warn(a)),this.getPendingSessionRequests().forEach(a=>{a.topic===n&&this.deletePendingSessionRequest(a.id,G.getSdkError("USER_DISCONNECTED"))}),s&&this.client.events.emit("session_delete",{id:o,topic:n})},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,G.getSdkError("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=vs.idle,this.client.events.emit("session_request_expire",{id:r}))},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,G.calcExpiry(wn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async r=>{let{id:n,topic:i,params:s,verifyContext:o}=r,u=s.request.expiryTimestamp||G.calcExpiry(wn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async r=>{let{topic:n,method:i,params:s,expiry:o,relayRpcId:u,clientRpcId:a,throwOnFailedPublish:c}=r,f=qe.formatJsonRpcRequest(i,s,a);if(G.isBrowser()&&AU.includes(i)){let A=G.hashMessage(JSON.stringify(f));this.client.core.verify.register({attestationId:A})}let d;try{d=await this.client.core.crypto.encode(n,f)}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let w=wn[i].req;return o&&(w.ttl=o),u&&(w.id=u),this.client.core.history.set(n,f),c?(w.internal=vl(br({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(A=>this.client.logger.error(A)),f.id},this.sendResult=async r=>{let{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:u}=r,a=qe.formatJsonRpcResult(n,s),c;try{c=await this.client.core.crypto.encode(i,a,u)}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let f;try{f=await this.client.core.history.get(i,n)}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),w}let d=wn[f.request.method].res;o?(d.internal=vl(br({},d.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,c,d)):this.client.core.relayer.publish(i,c,d).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(a)},this.sendError=async r=>{let{id:n,topic:i,error:s,encodeOpts:o}=r,u=qe.formatJsonRpcError(n,s),a;try{a=await this.client.core.crypto.encode(i,u,o)}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let c;try{c=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}let f=wn[c.request.method].res;this.client.core.relayer.publish(i,a,f),await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;G.isExpired(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{G.isExpired(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===vs.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vs.active;let r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=vs.idle},this.processRequest=r=>{let{topic:n,payload:i}=r,s=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:s}))switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:i}=G.getInternalError("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async(r,n)=>{let{params:i,id:s}=n;try{this.isValidConnect(br({},n.params));let o=i.expiryTimestamp||G.calcExpiry(wn.wc_sessionPropose.req.ttl),u=br({id:s,pairingTopic:r,expiryTimestamp:o},i);await this.setProposal(s,u);let a=G.hashMessage(JSON.stringify(n)),c=await this.getVerifyContext(a,u.proposer.metadata);this.client.events.emit("session_proposal",{id:s,params:u,verifyContext:c})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{let{id:i}=n;if(qe.isJsonRpcResult(n)){let{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});let o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});let u=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});let a=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});let c=await this.client.core.crypto.generateSharedKey(u,a);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:c});let f=await this.client.core.relayer.subscribe(c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(qe.isJsonRpcError(n)){await this.client.proposal.delete(i,G.getSdkError("USER_DISCONNECTED"));let s=G.engineEvent("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners, 954`);this.events.emit(G.engineEvent("session_connect"),{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:o,controller:u,expiry:a,namespaces:c,sessionProperties:f,pairingTopic:d,sessionConfig:w}=n.params,A=br(br({topic:r,relay:o,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:d,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},f&&{sessionProperties:f}),w&&{sessionConfig:w});await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0});let T=G.engineEvent("session_connect");if(this.events.listenerCount(T)===0)throw new Error(`emitting ${T} without any listeners 997`);this.events.emit(G.engineEvent("session_connect"),{session:A}),this.cleanupDuplicatePairings(A)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{let{id:i}=n;qe.isJsonRpcResult(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(G.engineEvent("session_approve",i),{})):qe.isJsonRpcError(n)&&(await this.client.session.delete(r,G.getSdkError("USER_DISCONNECTED")),this.events.emit(G.engineEvent("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:i,id:s}=n;try{let o=`${r}_session_update`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:G.getSdkError("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(br({topic:r},i));try{G.MemoryStore.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){throw G.MemoryStore.delete(o),a}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_update",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,G.calcExpiry(cu)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_extend",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_ping",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_ping",i),{}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(un.RELAYER_EVENTS.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:G.getSdkError("USER_DISCONNECTED")})])}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{let{id:i,params:s}=n;try{await this.isValidRequest(br({topic:r},s));let o=G.hashMessage(JSON.stringify(qe.formatJsonRpcRequest("wc_sessionRequest",s,i))),u=this.client.session.get(r),a=await this.getVerifyContext(o,u.peer.metadata),c={id:i,topic:r,params:s,verifyContext:a};await this.setPendingSessionRequest(c),this.addSessionRequestToSessionRequestQueue(c),this.processSessionRequestQueue()}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{let{id:i}=n,s=G.engineEvent("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:i,params:s}=n;try{let o=`${r}_session_event_${s.event.name}`,u=G.MemoryStore.get(o);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(br({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),G.MemoryStore.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qe.isJsonRpcResult(n)?this.events.emit(G.engineEvent("session_request",i),{result:n.result}):qe.isJsonRpcError(n)&&this.events.emit(G.engineEvent("session_request",i),{error:n.error})},this.onSessionAuthenticateRequest=async(r,n)=>{let{requester:i,authPayload:s,expiryTimestamp:o}=n.params,u=G.hashMessage(JSON.stringify(n)),a=await this.getVerifyContext(u,this.client.metadata),c={requester:i,pairingTopic:r,id:n.id,authPayload:s,verifyContext:a,expiryTimestamp:o};await this.client.auth.requests.set(n.id,c),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id})},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vs.idle,this.processSessionRequestQueue()},Dt.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{let o=s.request.id,u=G.engineEvent("session_request",o);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(G.engineEvent("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===vs.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vs.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,qe.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(a)}let{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:u}=r;if(G.isUndefined(n)||await this.isValidPairingTopic(n),!G.isValidRelays(u,!0)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(a)}!G.isUndefined(i)&&G.isValidObject(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!G.isUndefined(s)&&G.isValidObject(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{let i=G.isValidRequiredNamespaces(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!G.isValidParams(r))throw new Error(G.getInternalError("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let u=this.client.proposal.get(n),a=G.isValidNamespaces(i,"approve()");if(a)throw new Error(a.message);let c=G.isConformingNamespaces(u.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!G.isValidString(s,!0)){let{message:f}=G.getInternalError("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}G.isUndefined(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!G.isValidParams(r)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!G.isValidErrorReason(i)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!G.isValidParams(r)){let{message:c}=G.getInternalError("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(c)}let{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!G.isValidRelay(n)){let{message:c}=G.getInternalError("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}let u=G.isValidController(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);let a=G.isValidNamespaces(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(G.isExpired(o)){let{message:c}=G.getInternalError("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(a)}let{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),o=G.isValidNamespaces(i,"update()");if(o)throw new Error(o.message);let u=G.isConformingNamespaces(s.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!G.isValidParams(r)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(a)}let{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:u}=this.client.session.get(n);if(!G.isValidNamespacesChainId(u,s)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(a)}if(!G.isValidRequest(i)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(a)}if(!G.isValidNamespacesRequest(u,s,i.method)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(a)}if(o&&!G.isValidRequestExpiry(o,Zy)){let{message:a}=G.getInternalError("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Zy.min} and ${Zy.max}`);throw new Error(a)}},this.isValidRespond=async r=>{var n;if(!G.isValidParams(r)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}let{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!G.isValidResponse(s)){let{message:o}=G.getInternalError("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!G.isValidParams(r)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}let{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:o}=this.client.session.get(n);if(!G.isValidNamespacesChainId(o,s)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!G.isValidEvent(i)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!G.isValidNamespacesEvent(o,s,i.name)){let{message:u}=G.getInternalError("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!G.isValidParams(r)){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!G.isValidString(i,!1))throw new Error("uri is required parameter");if(!G.isValidString(s,!1))throw new Error("domain is required parameter");if(!G.isValidString(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(a=>G.parseChainId(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:u}=G.parseChainId(n[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async(r,n)=>{let i={verified:{verifyUrl:n.verifyUrl||un.VERIFY_SERVER,validation:"UNKNOWN",origin:n.url||""}};try{let s=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});s&&(i.verified.origin=s.origin,i.verified.isScam=s.isScam,i.verified.validation=s.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(s){this.client.logger.info(s)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!G.isValidString(i,!1)){let{message:s}=G.getInternalError("MISSING_OR_INVALID",`${n} must be in Record format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0,s=this.recentlyDeletedLimit/2;for(let o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:i}=G.getInternalError("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}}async isInitialized(){if(!this.initialized){let{message:e}=G.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(un.RELAYER_EVENTS.message,async e=>{let{topic:r,message:n}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(ad)?this.client.auth.authKeys.get(ad):{responseTopic:void 0,publicKey:void 0},s=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i});try{qe.isJsonRpcRequest(s)?(this.client.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):qe.isJsonRpcResponse(s)?(await this.client.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.client.core.history.delete(r,s.id)):this.onRelayEventUnknownPayload({topic:r,payload:s})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(un.EXPIRER_EVENTS.expired,async e=>{let{topic:r,id:n}=G.parseExpirerTarget(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,G.getInternalError("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(un.PAIRING_EVENTS.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(un.PAIRING_EVENTS.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.core.pairing.pairings.get(e).expiry)){let{message:r}=G.getInternalError("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!G.isValidString(e,!1)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});let{message:r}=G.getInternalError("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(G.isValidString(e,!1)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{let{message:r}=G.getInternalError("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!G.isValidId(e)){let{message:r}=G.getInternalError("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){let{message:r}=G.getInternalError("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(G.isExpired(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);let{message:r}=G.getInternalError("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}},X_=class extends un.Store{constructor(e,r){super(e,r,pU,r1),this.core=e,this.logger=r}},e1=class extends un.Store{constructor(e,r){super(e,r,yU,r1),this.core=e,this.logger=r}},Z_=class extends un.Store{constructor(e,r){super(e,r,vU,r1,n=>n.id),this.core=e,this.logger=r}},e2=class extends un.Store{constructor(e,r){super(e,r,SU,ud,()=>ad),this.core=e,this.logger=r}},t2=class extends un.Store{constructor(e,r){super(e,r,IU,ud),this.core=e,this.logger=r}},r2=class extends un.Store{constructor(e,r){super(e,r,TU,ud,n=>n.id),this.core=e,this.logger=r}},n2=class{constructor(e,r){this.core=e,this.logger=r,this.authKeys=new e2(this.core,this.logger),this.pairingTopics=new t2(this.core,this.logger),this.requests=new r2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},t1=class t extends dU.ISignClient{constructor(e){super(e),this.protocol=i2,this.version=s2,this.name=Xy.name,this.events=new gU.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async n=>{try{return await this.engine.authenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||Xy.name,this.metadata=e?.metadata||G.getAppMetadata();let r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Jy.pino(Jy.getDefaultLoggerOptions({level:e?.logger||Xy.logger}));this.core=e?.core||new un.Core(e),this.logger=Jy.generateChildLogger(r,this.name),this.session=new e1(this.core,this.logger),this.proposal=new X_(this.core,this.logger),this.pendingRequest=new Z_(this.core,this.logger),this.engine=new J_(this),this.auth=new n2(this.core,this.logger)}static async init(e){let r=new t(e);return await r.initialize(),r}get context(){return Jy.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}},Fce=e1,Uce=t1;Be.AUTH_CONTEXT=bU,Be.AUTH_KEYS_CONTEXT=SU,Be.AUTH_PAIRING_TOPIC_CONTEXT=IU,Be.AUTH_PROTOCOL=EU,Be.AUTH_PUBLIC_KEY_NAME=ad,Be.AUTH_REQUEST_CONTEXT=TU,Be.AUTH_STORAGE_PREFIX=ud,Be.AUTH_VERSION=Dce,Be.ENGINE_CONTEXT=wU,Be.ENGINE_QUEUE_STATES=vs,Be.ENGINE_RPC_OPTS=wn,Be.HISTORY_CONTEXT=Nce,Be.HISTORY_EVENTS=Cce,Be.HISTORY_STORAGE_VERSION=xce,Be.METHODS_TO_VERIFY=AU,Be.PROPOSAL_CONTEXT=pU,Be.PROPOSAL_EXPIRY=Oce,Be.PROPOSAL_EXPIRY_MESSAGE=mU,Be.REQUEST_CONTEXT=vU,Be.SESSION_CONTEXT=yU,Be.SESSION_EXPIRY=cu,Be.SESSION_REQUEST_EXPIRY_BOUNDARIES=Zy,Be.SIGN_CLIENT_CONTEXT=o2,Be.SIGN_CLIENT_DEFAULT=Xy,Be.SIGN_CLIENT_EVENTS=Tce,Be.SIGN_CLIENT_PROTOCOL=i2,Be.SIGN_CLIENT_STORAGE_OPTIONS=_ce,Be.SIGN_CLIENT_STORAGE_PREFIX=r1,Be.SIGN_CLIENT_VERSION=s2,Be.SessionStore=Fce,Be.SignClient=Uce,Be.WALLETCONNECT_DEEPLINK_CHOICE=Y_,Be.default=t1});var n1=D(Yo=>{"use strict";h();Object.defineProperty(Yo,"__esModule",{value:!0});Yo.OptionalOperation=Yo.Operation=void 0;var qce;(function(t){t.SIGN_TRANSACTION="mvx_signTransaction",t.SIGN_TRANSACTIONS="mvx_signTransactions",t.SIGN_MESSAGE="mvx_signMessage"})(qce=Yo.Operation||(Yo.Operation={}));var Vce;(function(t){t.SIGN_LOGIN_TOKEN="mvx_signLoginToken",t.SIGN_NATIVE_AUTH_TOKEN="mvx_signNativeAuthToken",t.CANCEL_ACTION="mvx_cancelAction"})(Vce=Yo.OptionalOperation||(Yo.OptionalOperation={}))});var a2=D(As=>{"use strict";h();Object.defineProperty(As,"__esModule",{value:!0});As.WALLETCONNECT_SIGN_LOGIN_DELAY=As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=As.WALLETCONNECT_MULTIVERSX_METHODS=As.WALLETCONNECT_MULTIVERSX_NAMESPACE=void 0;var CU=n1();As.WALLETCONNECT_MULTIVERSX_NAMESPACE="mvx";As.WALLETCONNECT_MULTIVERSX_METHODS=Object.values(CU.Operation);As.WALLETCONNECT_MULTIVERSX_OPTIONAL_METHODS=Object.values(CU.OptionalOperation);As.WALLETCONNECT_SIGN_LOGIN_DELAY=500});var l2=D(Ci=>{"use strict";h();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WalletConnectV2ProviderErrorMessagesEnum=Ci.ErrBadAddress=Ci.ErrNotImplemented=Ci.Err=void 0;var cd=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ci.Err=cd;var u2=class extends cd{constructor(){super("Method not yet implemented")}};Ci.ErrNotImplemented=u2;var c2=class extends cd{constructor(e,r){super(`Bad address: ${e}`,r)}};Ci.ErrBadAddress=c2;var kce;(function(t){t.unableToInit="WalletConnect is unable to init",t.notInitialized="WalletConnect is not initialized",t.unableToConnect="WalletConnect is unable to connect",t.unableToConnectExisting="WalletConnect is unable to connect to existing pairing",t.unableToSignLoginToken="WalletConnect could not sign login token",t.unableToSign="WalletConnect could not sign the message",t.unableToLogin="WalletConnect is unable to login",t.unableToHandleTopic="WalletConnect: Unable to handle topic update",t.unableToHandleEvent="WalletConnect: Unable to handle events",t.unableToHandleCleanup="WalletConnect: Unable to handle cleanup",t.sessionNotConnected="WalletConnect Session is not connected",t.sessionDeleted="WalletConnect Session Deleted",t.sessionExpired="WalletConnect Session Expired",t.alreadyLoggedOut="WalletConnect: Already logged out",t.pingFailed="WalletConnect Ping Failed",t.invalidAddress="WalletConnect: Invalid address",t.requestDifferentChain="WalletConnect: Request Chain Id different than Connection Chain Id",t.invalidMessageResponse="WalletConnect could not sign the message",t.invalidMessageSignature="WalletConnect: Invalid message signature",t.invalidTransactionResponse="WalletConnect could not sign the transactions. Invalid signatures",t.invalidCustomRequestResponse="WalletConnect could not send the custom request",t.transactionError="Transaction canceled",t.connectionError="WalletConnect could not establish a connection",t.invalidGuardian="WalletConnect: Invalid Guardian"})(kce=Ci.WalletConnectV2ProviderErrorMessagesEnum||(Ci.WalletConnectV2ProviderErrorMessagesEnum={}))});var h2=D(i1=>{"use strict";h();Object.defineProperty(i1,"__esModule",{value:!0});i1.Logger=void 0;var f2=class{static error(e){console.error(e)}static trace(e){console.trace(e)}};i1.Logger=f2});var NU=D(()=>{"use strict";h();global.Buffer||(global.Buffer=io().Buffer)});var p2=D(Al=>{"use strict";h();Object.defineProperty(Al,"__esModule",{value:!0});Al.SmartContractQueryResponse=Al.SmartContractQuery=void 0;var d2=class{constructor(e){this.contract=e.contract,this.caller=e.caller,this.value=e.value,this.function=e.function,this.arguments=e.arguments}};Al.SmartContractQuery=d2;var g2=class{constructor(e){this.function=e.function,this.returnCode=e.returnCode,this.returnMessage=e.returnMessage,this.returnDataParts=e.returnDataParts}};Al.SmartContractQueryResponse=g2});var OU=D(s1=>{"use strict";h();Object.defineProperty(s1,"__esModule",{value:!0});s1.QueryRunnerAdapter=void 0;var xU=Ve(),Hce=p2(),m2=class{constructor(e){this.networkProvider=e.networkProvider}async runQuery(e){let r={address:xU.Address.fromBech32(e.contract),caller:e.caller?xU.Address.fromBech32(e.caller):void 0,func:e.function,value:e.value,getEncodedArguments:()=>e.arguments.map(i=>p.Buffer.from(i).toString("hex"))},n=await this.networkProvider.queryContract(r);return new Hce.SmartContractQueryResponse({function:e.function,returnCode:n.returnCode.toString(),returnMessage:n.returnMessage,returnDataParts:n.getReturnDataParts()})}};s1.QueryRunnerAdapter=m2});var DU=D(lu=>{"use strict";h();var Gce=lu&&lu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),jce=lu&&lu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Gce(e,t,r)};Object.defineProperty(lu,"__esModule",{value:!0});jce(OU(),lu)});var PU=D(fu=>{"use strict";h();var zce=fu&&fu.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Qce=fu&&fu.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&zce(e,t,r)};Object.defineProperty(fu,"__esModule",{value:!0});Qce(XE(),fu)});var BU=D(hu=>{"use strict";h();Object.defineProperty(hu,"__esModule",{value:!0});hu.GasEstimator=hu.DefaultGasConfiguration=void 0;hu.DefaultGasConfiguration={minGasLimit:5e4,gasPerDataByte:1500,gasCostESDTTransfer:2e5,gasCostESDTNFTTransfer:2e5,gasCostESDTNFTMultiTransfer:2e5};var Kce=1e5,RU=8e5,y2=class{constructor(e){this.gasConfiguration=e||hu.DefaultGasConfiguration}forEGLDTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasPerDataByte*e}forESDTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTTransfer+this.gasConfiguration.gasPerDataByte*e+Kce}forESDTNFTTransfer(e){return this.gasConfiguration.minGasLimit+this.gasConfiguration.gasCostESDTNFTTransfer+this.gasConfiguration.gasPerDataByte*e+RU}forMultiESDTNFTTransfer(e,r){return this.gasConfiguration.minGasLimit+(this.gasConfiguration.gasCostESDTNFTMultiTransfer+RU)*r+this.gasConfiguration.gasPerDataByte*e}};hu.GasEstimator=y2});var LU=D(MU=>{"use strict";h();Object.defineProperty(MU,"__esModule",{value:!0})});var UU=D(FU=>{"use strict";h();Object.defineProperty(FU,"__esModule",{value:!0})});var qU=D(o1=>{"use strict";h();Object.defineProperty(o1,"__esModule",{value:!0});o1.RelayedTransactionV1Builder=void 0;var w2=Ve(),Wce=Ie(),$ce=Xr(),Yce=Ms(),Jce=aE(),v2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}setRelayedTransactionVersion(e){return this.relayedTransactionVersion=e,this}setRelayedTransactionOptions(e){return this.relayedTransactionOptions=e,this}setRelayedTransactionGuardian(e){return this.relayedTransactionGuardian=e,this}build(){if(!this.innerTransaction||!this.netConfig||!this.relayerAddress||!this.innerTransaction.getSignature())throw new Wce.ErrInvalidRelayedV1BuilderArguments;let e=this.prepareInnerTransaction(),r=`relayedTx@${p.Buffer.from(e).toString("hex")}`,n=new Yce.TransactionPayload(r),i=this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length()+this.innerTransaction.getGasLimit().valueOf(),s=new $ce.Transaction({nonce:this.relayerNonce,sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:i,data:n,chainID:this.netConfig.ChainID,version:this.relayedTransactionVersion,options:this.relayedTransactionOptions,guardian:this.relayedTransactionGuardian});return this.relayerNonce&&s.setNonce(this.relayerNonce),s}prepareInnerTransaction(){if(!this.innerTransaction)return"";let e={nonce:this.innerTransaction.getNonce().valueOf(),sender:new w2.Address(this.innerTransaction.getSender().bech32()).pubkey().toString("base64"),receiver:new w2.Address(this.innerTransaction.getReceiver().bech32()).pubkey().toString("base64"),value:BigInt(this.innerTransaction.getValue().toString()),gasPrice:this.innerTransaction.getGasPrice().valueOf(),gasLimit:this.innerTransaction.getGasLimit().valueOf(),data:this.innerTransaction.getData().valueOf().toString("base64"),signature:this.innerTransaction.getSignature().toString("base64"),chainID:p.Buffer.from(this.innerTransaction.getChainID().valueOf()).toString("base64"),version:this.innerTransaction.getVersion().valueOf(),options:this.innerTransaction.getOptions().valueOf()==0?void 0:this.innerTransaction.getOptions().valueOf(),guardian:this.innerTransaction.getGuardian().bech32()?new w2.Address(this.innerTransaction.getGuardian().bech32()).pubkey().toString("base64"):void 0,guardianSignature:this.innerTransaction.getGuardianSignature().toString("hex")?this.innerTransaction.getGuardianSignature().toString("base64"):void 0,sndUserName:this.innerTransaction.getSenderUsername()?p.Buffer.from(this.innerTransaction.getSenderUsername()).toString("base64"):void 0,rcvUserName:this.innerTransaction.getReceiverUsername()?p.Buffer.from(this.innerTransaction.getReceiverUsername()).toString("base64"):void 0};return Jce.stringify(e)}};o1.RelayedTransactionV1Builder=v2});var kU=D(a1=>{"use strict";h();Object.defineProperty(a1,"__esModule",{value:!0});a1.RelayedTransactionV2Builder=void 0;var VU=Ie(),ld=qn(),Xce=Xr(),Zce=Ms(),A2=class{setInnerTransaction(e){return this.innerTransaction=e,this}setInnerTransactionGasLimit(e){return this.innerTransactionGasLimit=e,this}setNetworkConfig(e){return this.netConfig=e,this}setRelayerAddress(e){return this.relayerAddress=e,this}setRelayerNonce(e){return this.relayerNonce=e,this}build(){if(!this.innerTransaction||!this.innerTransactionGasLimit||!this.relayerAddress||!this.netConfig||!this.innerTransaction.getSignature())throw new VU.ErrInvalidRelayedV2BuilderArguments;if(this.innerTransaction.getGasLimit()!=0)throw new VU.ErrGasLimitShouldBe0ForInnerTransaction;let{argumentsString:e}=new ld.ArgSerializer().valuesToString([new ld.AddressValue(this.innerTransaction.getReceiver()),new ld.U64Value(this.innerTransaction.getNonce().valueOf()),new ld.BytesValue(this.innerTransaction.getData().valueOf()),new ld.BytesValue(this.innerTransaction.getSignature())]),r=`relayedTxV2@${e}`,n=new Zce.TransactionPayload(r),i=new Xce.Transaction({sender:this.relayerAddress,receiver:this.innerTransaction.getSender(),value:0,gasLimit:this.innerTransactionGasLimit.valueOf()+this.netConfig.MinGasLimit+this.netConfig.GasPerDataByte*n.length(),data:n,chainID:this.netConfig.ChainID,version:this.innerTransaction.getVersion(),options:this.innerTransaction.getOptions()});return this.relayerNonce&&i.setNonce(this.relayerNonce),i}};a1.RelayedTransactionV2Builder=A2});var HU=D(c1=>{"use strict";h();Object.defineProperty(c1,"__esModule",{value:!0});c1.SmartContractQueriesController=void 0;var ele=Ie(),tle=p2(),u1=qn(),E2=class{constructor(e){this.abi=e.abi,this.queryRunner=e.queryRunner,this.legacyResultsParser=new u1.ResultsParser}createQuery(e){let r=this.encodeArguments(e.function,e.arguments);return new tle.SmartContractQuery({contract:e.contract,caller:e.caller,function:e.function,arguments:r,value:e.value})}encodeArguments(e,r){let n=this.abi?.getEndpoint(e);if(n){let i=u1.NativeSerializer.nativeToTypedValues(r,n);return new u1.ArgSerializer().valuesToBuffers(i)}if(this.areArgsOfTypedValue(r))return new u1.ArgSerializer().valuesToBuffers(r);if(this.areArgsBuffers(r))return r.map(i=>p.Buffer.from(i));throw new ele.Err("cannot encode arguments: when ABI is not available, they must be either typed values or buffers")}areArgsOfTypedValue(e){for(let r of e)if(!r.belongsToTypesystem)return!1;return!0}areArgsBuffers(e){for(let r of e)if(!ArrayBuffer.isView(r))return!1;return!0}async runQuery(e){return await this.queryRunner.runQuery(e)}parseQueryResponse(e){if(!this.abi)return e.returnDataParts;let r={returnCode:e.returnCode,returnMessage:e.returnMessage,getReturnDataParts:()=>e.returnDataParts.map(u=>p.Buffer.from(u))},n=e.function,i=this.abi.getEndpoint(n);return this.legacyResultsParser.parseQueryResponse(r,i).values.map(u=>u.valueOf())}};c1.SmartContractQueriesController=E2});var GU=D(ke=>{"use strict";h();var rle=ke&&ke.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pt=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&rle(e,t,r)};Object.defineProperty(ke,"__esModule",{value:!0});NU();Pt(Ic(),ke);Pt(DU(),ke);Pt(Ve(),ke);Pt(Ub(),ke);Pt(PU(),ke);Pt(Ie(),ke);Pt(BU(),ke);Pt(LU(),ke);Pt(UU(),ke);Pt(oo(),ke);Pt(Mb(),ke);Pt($l(),ke);Pt(qU(),ke);Pt(kU(),ke);Pt(V0(),ke);Pt(HU(),ke);Pt(qn(),ke);Pt(Cb(),ke);Pt(_a(),ke);Pt(Xr(),ke);Pt(_0(),ke);Pt(Ms(),ke);Pt(U0(),ke);Pt(f0(),ke);Pt(Pb(),ke);Pt(Rn(),ke)});var $U=D(ur=>{"use strict";h();var nle=ur&&ur.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(ur,"__esModule",{value:!0});ur.sleep=ur.getMetadata=ur.applyTransactionSignature=ur.getAddressFromSession=ur.addressIsValid=ur.getConnectionParams=ur.getCurrentTopic=ur.getCurrentSession=void 0;var QU=GU(),jU=Yf(),ile=Qh(),l1=a2(),to=l2(),b2=h2(),zU=n1();function KU(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=e.find(WU(t)).filter(n=>n.acknowledged);if(r.length>0){let n=r.length-1;return r[n]}if(e.session.length>0){let n=e.session.keys.length-1;return e.session.get(e.session.keys[n])}throw b2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected)}ur.getCurrentSession=KU;function sle(t,e){if(!e)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=KU(t,e);if(!r?.topic)throw new Error(to.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);return r.topic}ur.getCurrentTopic=sle;function WU(t,e){var r,n,i;let s=[...l1.WALLETCONNECT_MULTIVERSX_METHODS,...(r=e?.methods)!==null&&r!==void 0?r:[]];!((n=e?.methods)===null||n===void 0)&&n.includes(zU.OptionalOperation.SIGN_LOGIN_TOKEN)||s.push(zU.OptionalOperation.SIGN_LOGIN_TOKEN);let o=[`${l1.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${t}`],u=(i=e?.events)!==null&&i!==void 0?i:[];return{requiredNamespaces:{[l1.WALLETCONNECT_MULTIVERSX_NAMESPACE]:{methods:s,chains:o,events:u}}}}ur.getConnectionParams=WU;function ole(t){try{return!QU.Address.fromBech32(t).isEmpty()}catch{return!1}}ur.addressIsValid=ole;function ale(t){let e=t.namespaces[l1.WALLETCONNECT_MULTIVERSX_NAMESPACE];if(e&&e.accounts){let r=e.accounts[0],[n,i,s]=r.split(":");return s}return""}ur.getAddressFromSession=ale;function ule({transaction:t,response:e}){if(!e)throw b2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);let{signature:r,guardianSignature:n,version:i,options:s,guardian:o}=e,u=t.getGuardian().bech32();if(u&&u!==o)throw b2.Logger.error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian),new Error(to.WalletConnectV2ProviderErrorMessagesEnum.invalidGuardian);return o&&t.setGuardian(QU.Address.fromBech32(o)),i&&t.setVersion(i),s!=null&&t.setOptions(s),t.applySignature(new jU.Signature(r)),n&&t.applyGuardianSignature(new jU.Signature(n)),t}ur.applyTransactionSignature=ule;function cle(t){if(t)return Object.assign(Object.assign({},t),{url:ile.getAppMetadata().url})}ur.getMetadata=cle;function lle(t){return nle(this,void 0,void 0,function*(){return yield new Promise(e=>setTimeout(()=>{e()},t))})}ur.sleep=lle});var fd=D(cn=>{"use strict";h();var tr=cn&&cn.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},fle=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WalletConnectV2Provider=cn.OptionalOperation=cn.Operation=cn.WalletConnectV2ProviderErrorMessagesEnum=void 0;var hle=Yf(),dle=fle(_U()),S2=Qh(),du=a2(),he=l2();Object.defineProperty(cn,"WalletConnectV2ProviderErrorMessagesEnum",{enumerable:!0,get:function(){return he.WalletConnectV2ProviderErrorMessagesEnum}});var Me=h2(),Jo=n1();Object.defineProperty(cn,"Operation",{enumerable:!0,get:function(){return Jo.Operation}});Object.defineProperty(cn,"OptionalOperation",{enumerable:!0,get:function(){return Jo.OptionalOperation}});var xr=$U(),I2=class{constructor(e,r,n,i,s){this.chainId="",this.address="",this.signature="",this.isInitializing=!1,this.processingTopic="",this.options={},this.onClientConnect=e,this.chainId=r,this.walletConnectV2Relay=n,this.walletConnectV2ProjectId=i,this.options=s}reset(){this.address="",this.signature="",this.walletConnector=void 0,this.session=void 0,this.pairings=void 0}init(){var e,r;return tr(this,void 0,void 0,function*(){if(this.isInitialized())return this.isInitialized();try{if(!this.isInitializing){this.isInitializing=!0,this.reset();let n=!((e=this.options)===null||e===void 0)&&e.metadata?{metadata:xr.getMetadata((r=this.options)===null||r===void 0?void 0:r.metadata)}:{},i=yield dle.default.init(Object.assign(Object.assign(Object.assign({},this.options),{relayUrl:this.walletConnectV2Relay,projectId:this.walletConnectV2ProjectId}),n));this.walletConnector=i,this.isInitializing=!1,yield this.subscribeToEvents(i),yield this.checkPersistedState(i)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToInit)}finally{return this.isInitializing=!1,this.isInitialized()}})}isInitialized(){return!!this.walletConnector&&!this.isInitializing}isConnected(){return new Promise((e,r)=>e(!!(this.isInitialized()&&typeof this.session<"u")))}connect(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);let r=xr.getConnectionParams(this.chainId,e);try{return yield this.walletConnector.connect(Object.assign({pairingTopic:e?.topic},r))}catch{throw this.reset(),Me.Logger.error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect),new Error(e?.topic?he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnectExisting:he.WalletConnectV2ProviderErrorMessagesEnum.unableToConnect)}})}login(e){var r;return tr(this,void 0,void 0,function*(){if(this.isInitializing=!0,typeof this.walletConnector>"u"&&(yield this.connect()),typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session<"u"&&(yield this.logout({topic:(r=this.session)===null||r===void 0?void 0:r.topic}));try{if(e&&e.approval){let n=yield e.approval();if(e.token){yield xr.sleep(du.WALLETCONNECT_SIGN_LOGIN_DELAY);let i=xr.getAddressFromSession(n),o=n.namespaces[du.WALLETCONNECT_MULTIVERSX_NAMESPACE].methods.includes(Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN)?Jo.OptionalOperation.SIGN_NATIVE_AUTH_TOKEN:Jo.OptionalOperation.SIGN_LOGIN_TOKEN,{signature:u}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:n.topic,request:{method:o,params:{token:e.token,address:i}}});if(!u)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSignLoginToken);return yield this.onSessionConnected({session:n,signature:u})}return yield this.onSessionConnected({session:n,signature:""})}}catch{throw this.reset(),Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToLogin)}finally{this.isInitializing=!1}return""})}logout(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{if(this.processingTopic===(e?.topic||xr.getCurrentTopic(this.chainId,this.walletConnector)))return!0;if(e?.topic)this.processingTopic=e.topic,yield this.walletConnector.disconnect({topic:e.topic,reason:S2.getSdkError("USER_DISCONNECTED")});else{let r=xr.getCurrentTopic(this.chainId,this.walletConnector);this.processingTopic=r,yield this.walletConnector.disconnect({topic:r,reason:S2.getSdkError("USER_DISCONNECTED")}),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0})}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.alreadyLoggedOut)}finally{this.processingTopic=""}return!0})}getAddress(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.address})}getSignature(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return this.signature})}getPairings(){var e,r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return(s=(i=(n=(r=(e=this.walletConnector)===null||e===void 0?void 0:e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!0}))!==null&&s!==void 0?s:[]})}signMessage(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let r=yield this.getAddress(),{signature:n}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_MESSAGE,params:{address:r,message:e.message.toString()}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageResponse);try{e.applySignature(new hle.Signature(n))}catch{throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidMessageSignature)}}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToSign)}return e})}signTransaction(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.toPlainObject();if(this.chainId!==e.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);try{let n=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTION,params:{transaction:r}}});return xr.applyTransactionSignature({transaction:e,response:n})}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}signTransactions(e){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);let r=e.map(n=>{if(this.chainId!==n.getChainID().valueOf())throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.requestDifferentChain);return n.toPlainObject()});try{let{signatures:n}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:{method:Jo.Operation.SIGN_TRANSACTIONS,params:{transactions:r}}});if(!n)throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);if(!Array.isArray(n)||e.length!==n.length)throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidTransactionResponse);for(let[i,s]of e.entries()){let o=n[i];xr.applyTransactionSignature({transaction:s,response:o})}return e}catch{throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.transactionError)}})}sendCustomRequest(e){var r;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(typeof this.session>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected),this.onClientConnect.onClientLogout(),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);if(!((r=e?.request)===null||r===void 0)&&r.method){try{let n=Object.assign({},e.request),{method:i}=n,{response:s}=yield this.walletConnector.request({chainId:`${du.WALLETCONNECT_MULTIVERSX_NAMESPACE}:${this.chainId}`,topic:xr.getCurrentTopic(this.chainId,this.walletConnector),request:Object.assign(Object.assign({},n),{method:i})});s||Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.invalidCustomRequestResponse)}return}})}ping(){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized),new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);typeof this.session>"u"&&Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionNotConnected);try{let e=xr.getCurrentTopic(this.chainId,this.walletConnector);return yield this.walletConnector.ping({topic:e}),!0}catch{return Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.pingFailed),!1}})}loginAccount(e){return tr(this,void 0,void 0,function*(){return e?xr.addressIsValid(e.address)?(this.address=e.address,e.signature&&(this.signature=e.signature),this.onClientConnect.onClientLogin(),this.address):(Me.Logger.error(`${he.WalletConnectV2ProviderErrorMessagesEnum.invalidAddress} ${e.address}`),this.walletConnector&&(yield this.logout()),""):""})}onSessionConnected(e){return tr(this,void 0,void 0,function*(){if(!e)return"";this.session=e.session;let r=xr.getAddressFromSession(e.session);return r?(yield this.loginAccount({address:r,signature:e.signature}),r):""})}handleTopicUpdateEvent({topic:e}){return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u"){Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);return}try{let r=yield this.getPairings();if(this.address&&!this.isInitializing&&r)if(r?.length===0)this.onClientConnect.onClientLogout();else{let n=r[r.length-1];n?.topic===e&&this.onClientConnect.onClientLogout()}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleTopic)}finally{this.pairings=yield this.getPairings()}})}handleSessionEvents({topic:e,params:r}){var n;return tr(this,void 0,void 0,function*(){if(typeof this.walletConnector>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.session&&((n=this.session)===null||n===void 0?void 0:n.topic)!==e)return;let{event:i}=r;if(i?.name&&xr.getCurrentTopic(this.chainId,this.walletConnector)===e){let s=i.data;this.onClientConnect.onClientEvent(s)}})}subscribeToEvents(e){var r,n,i,s;return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);try{e.on("session_update",({topic:o,params:u})=>{var a;if(!this.session||((a=this.session)===null||a===void 0?void 0:a.topic)!==o)return;let{namespaces:c}=u,f=e.session.get(o),d=Object.assign(Object.assign({},f),{namespaces:c});this.onSessionConnected({session:d})}),e.on("session_event",this.handleSessionEvents.bind(this)),e.on("session_delete",({topic:o})=>tr(this,void 0,void 0,function*(){var u;this.isInitializing&&(this.onClientConnect.onClientLogout(),this.reset()),!(!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o)&&(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionDeleted),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),e.on("session_expire",({topic:o})=>tr(this,void 0,void 0,function*(){var u;!this.session||((u=this.session)===null||u===void 0?void 0:u.topic)!==o||(Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.sessionExpired),this.onClientConnect.onClientLogout(),this.reset(),yield this.cleanupPendingPairings({deletePairings:!0}))})),(n=(r=e.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0||n.events.on("pairing_delete",this.handleTopicUpdateEvent.bind(this)),(s=(i=e.core)===null||i===void 0?void 0:i.pairing)===null||s===void 0||s.events.on("pairing_expire",this.handleTopicUpdateEvent.bind(this))}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleEvent)}})}checkPersistedState(e){return tr(this,void 0,void 0,function*(){if(typeof e>"u")throw new Error(he.WalletConnectV2ProviderErrorMessagesEnum.notInitialized);if(this.pairings=yield this.getPairings(),!(typeof this.session<"u")&&e.session.length&&!this.address&&!this.isInitializing){let r=xr.getCurrentSession(this.chainId,e);if(r)return yield this.onSessionConnected({session:r}),r}})}cleanupPendingPairings(e={}){var r,n,i,s,o,u,a,c;return tr(this,void 0,void 0,function*(){if(!(typeof this.walletConnector>"u"))try{let f=(i=(n=(r=this.walletConnector.core)===null||r===void 0?void 0:r.pairing)===null||n===void 0?void 0:n.pairings)===null||i===void 0?void 0:i.getAll({active:!1});if(!S2.isValidArray(f))return;for(let d of f)if(e.deletePairings)(o=(s=this.walletConnector.core)===null||s===void 0?void 0:s.expirer)===null||o===void 0||o.set(d.topic,0);else try{yield(c=(a=(u=this.walletConnector.core)===null||u===void 0?void 0:u.relayer)===null||a===void 0?void 0:a.subscriber)===null||c===void 0?void 0:c.unsubscribe(d.topic)}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}}catch{Me.Logger.error(he.WalletConnectV2ProviderErrorMessagesEnum.unableToHandleCleanup)}})}};cn.WalletConnectV2Provider=I2});var JU=D((ZTe,YU)=>{"use strict";h();YU.exports=Error});var ZU=D((t_e,XU)=>{"use strict";h();XU.exports=EvalError});var tq=D((n_e,eq)=>{"use strict";h();eq.exports=RangeError});var nq=D((s_e,rq)=>{"use strict";h();rq.exports=ReferenceError});var T2=D((a_e,iq)=>{"use strict";h();iq.exports=SyntaxError});var El=D((c_e,sq)=>{"use strict";h();sq.exports=TypeError});var aq=D((f_e,oq)=>{"use strict";h();oq.exports=URIError});var cq=D((d_e,uq)=>{"use strict";h();uq.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var hq=D((p_e,fq)=>{"use strict";h();var lq=typeof Symbol<"u"&&Symbol,gle=cq();fq.exports=function(){return typeof lq!="function"||typeof Symbol!="function"||typeof lq("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:gle()}});var gq=D((y_e,dq)=>{"use strict";h();var _2={__proto__:null,foo:{}},ple=Object;dq.exports=function(){return{__proto__:_2}.foo===_2.foo&&!(_2 instanceof ple)}});var yq=D((v_e,mq)=>{"use strict";h();var mle="Function.prototype.bind called on incompatible ",yle=Object.prototype.toString,wle=Math.max,vle="[object Function]",pq=function(e,r){for(var n=[],i=0;i{"use strict";h();var ble=yq();wq.exports=Function.prototype.bind||ble});var Aq=D((S_e,vq)=>{"use strict";h();var Sle=Function.prototype.call,Ile=Object.prototype.hasOwnProperty,Tle=f1();vq.exports=Tle.call(Sle,Ile)});var mu=D((T_e,Tq)=>{"use strict";h();var Re,_le=JU(),Cle=ZU(),Nle=tq(),xle=nq(),Tl=T2(),Il=El(),Ole=aq(),Iq=Function,C2=function(t){try{return Iq('"use strict"; return ('+t+").constructor;")()}catch{}},gu=Object.getOwnPropertyDescriptor;if(gu)try{gu({},"")}catch{gu=null}var N2=function(){throw new Il},Dle=gu?function(){try{return arguments.callee,N2}catch{try{return gu(arguments,"callee").get}catch{return N2}}}():N2,bl=hq()(),Ple=gq()(),Sr=Object.getPrototypeOf||(Ple?function(t){return t.__proto__}:null),Sl={},Rle=typeof Uint8Array>"u"||!Sr?Re:Sr(Uint8Array),pu={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?Re:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Re:ArrayBuffer,"%ArrayIteratorPrototype%":bl&&Sr?Sr([][Symbol.iterator]()):Re,"%AsyncFromSyncIteratorPrototype%":Re,"%AsyncFunction%":Sl,"%AsyncGenerator%":Sl,"%AsyncGeneratorFunction%":Sl,"%AsyncIteratorPrototype%":Sl,"%Atomics%":typeof Atomics>"u"?Re:Atomics,"%BigInt%":typeof BigInt>"u"?Re:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Re:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Re:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Re:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":_le,"%eval%":eval,"%EvalError%":Cle,"%Float32Array%":typeof Float32Array>"u"?Re:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Re:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Re:FinalizationRegistry,"%Function%":Iq,"%GeneratorFunction%":Sl,"%Int8Array%":typeof Int8Array>"u"?Re:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Re:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Re:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":bl&&Sr?Sr(Sr([][Symbol.iterator]())):Re,"%JSON%":typeof JSON=="object"?JSON:Re,"%Map%":typeof Map>"u"?Re:Map,"%MapIteratorPrototype%":typeof Map>"u"||!bl||!Sr?Re:Sr(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Re:Promise,"%Proxy%":typeof Proxy>"u"?Re:Proxy,"%RangeError%":Nle,"%ReferenceError%":xle,"%Reflect%":typeof Reflect>"u"?Re:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Re:Set,"%SetIteratorPrototype%":typeof Set>"u"||!bl||!Sr?Re:Sr(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Re:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":bl&&Sr?Sr(""[Symbol.iterator]()):Re,"%Symbol%":bl?Symbol:Re,"%SyntaxError%":Tl,"%ThrowTypeError%":Dle,"%TypedArray%":Rle,"%TypeError%":Il,"%Uint8Array%":typeof Uint8Array>"u"?Re:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Re:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Re:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Re:Uint32Array,"%URIError%":Ole,"%WeakMap%":typeof WeakMap>"u"?Re:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Re:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Re:WeakSet};if(Sr)try{null.error}catch(t){Eq=Sr(Sr(t)),pu["%Error.prototype%"]=Eq}var Eq,Ble=function t(e){var r;if(e==="%AsyncFunction%")r=C2("async function () {}");else if(e==="%GeneratorFunction%")r=C2("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=C2("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Sr&&(r=Sr(i.prototype))}return pu[e]=r,r},bq={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},hd=f1(),h1=Aq(),Mle=hd.call(Function.call,Array.prototype.concat),Lle=hd.call(Function.apply,Array.prototype.splice),Sq=hd.call(Function.call,String.prototype.replace),d1=hd.call(Function.call,String.prototype.slice),Fle=hd.call(Function.call,RegExp.prototype.exec),Ule=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,qle=/\\(\\)?/g,Vle=function(e){var r=d1(e,0,1),n=d1(e,-1);if(r==="%"&&n!=="%")throw new Tl("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Tl("invalid intrinsic syntax, expected opening `%`");var i=[];return Sq(e,Ule,function(s,o,u,a){i[i.length]=u?Sq(a,qle,"$1"):o||s}),i},kle=function(e,r){var n=e,i;if(h1(bq,n)&&(i=bq[n],n="%"+i[0]+"%"),h1(pu,n)){var s=pu[n];if(s===Sl&&(s=Ble(n)),typeof s>"u"&&!r)throw new Il("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Tl("intrinsic "+e+" does not exist!")};Tq.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Il("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Il('"allowMissing" argument must be a boolean');if(Fle(/^%?[^%]*%?$/,e)===null)throw new Tl("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Vle(e),i=n.length>0?n[0]:"",s=kle("%"+i+"%",r),o=s.name,u=s.value,a=!1,c=s.alias;c&&(i=c[0],Lle(n,Mle([0,1],c)));for(var f=1,d=!0;f=n.length){var x=gu(u,w);d=!!x,d&&"get"in x&&!("originalValue"in x.get)?u=x.get:u=u[w]}else d=h1(u,w),u=u[w];d&&!a&&(pu[o]=u)}}return u}});var p1=D((C_e,_q)=>{"use strict";h();var Hle=mu(),g1=Hle("%Object.defineProperty%",!0)||!1;if(g1)try{g1({},"a",{value:1})}catch{g1=!1}_q.exports=g1});var x2=D((x_e,Cq)=>{"use strict";h();var Gle=mu(),m1=Gle("%Object.getOwnPropertyDescriptor%",!0);if(m1)try{m1([],"length")}catch{m1=null}Cq.exports=m1});var Dq=D((D_e,Oq)=>{"use strict";h();var Nq=p1(),jle=T2(),_l=El(),xq=x2();Oq.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new _l("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new _l("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new _l("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new _l("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new _l("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new _l("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,a=!!xq&&xq(e,r);if(Nq)Nq(e,r,{configurable:o===null&&a?a.configurable:!o,enumerable:i===null&&a?a.enumerable:!i,value:n,writable:s===null&&a?a.writable:!s});else if(u||!i&&!s&&!o)e[r]=n;else throw new jle("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var Bq=D((R_e,Rq)=>{"use strict";h();var O2=p1(),Pq=function(){return!!O2};Pq.hasArrayLengthDefineBug=function(){if(!O2)return null;try{return O2([],"length",{value:1}).length!==1}catch{return!0}};Rq.exports=Pq});var qq=D((M_e,Uq)=>{"use strict";h();var zle=mu(),Mq=Dq(),Qle=Bq()(),Lq=x2(),Fq=El(),Kle=zle("%Math.floor%");Uq.exports=function(e,r){if(typeof e!="function")throw new Fq("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Kle(r)!==r)throw new Fq("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&Lq){var o=Lq(e,"length");o&&!o.configurable&&(i=!1),o&&!o.writable&&(s=!1)}return(i||s||!n)&&(Qle?Mq(e,"length",r,!0,!0):Mq(e,"length",r)),e}});var zq=D((F_e,y1)=>{"use strict";h();var D2=f1(),w1=mu(),Wle=qq(),$le=El(),Hq=w1("%Function.prototype.apply%"),Gq=w1("%Function.prototype.call%"),jq=w1("%Reflect.apply%",!0)||D2.call(Gq,Hq),Vq=p1(),Yle=w1("%Math.max%");y1.exports=function(e){if(typeof e!="function")throw new $le("a function is required");var r=jq(D2,Gq,arguments);return Wle(r,1+Yle(0,e.length-(arguments.length-1)),!0)};var kq=function(){return jq(D2,Hq,arguments)};Vq?Vq(y1.exports,"apply",{value:kq}):y1.exports.apply=kq});var $q=D((q_e,Wq)=>{"use strict";h();var Qq=mu(),Kq=zq(),Jle=Kq(Qq("String.prototype.indexOf"));Wq.exports=function(e,r){var n=Qq(e,!!r);return typeof n=="function"&&Jle(e,".prototype.")>-1?Kq(n):n}});var Yq=D(()=>{h()});var m7=D((j_e,p7)=>{h();var k2=typeof Map=="function"&&Map.prototype,P2=Object.getOwnPropertyDescriptor&&k2?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,A1=k2&&P2&&typeof P2.get=="function"?P2.get:null,Jq=k2&&Map.prototype.forEach,H2=typeof Set=="function"&&Set.prototype,R2=Object.getOwnPropertyDescriptor&&H2?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,E1=H2&&R2&&typeof R2.get=="function"?R2.get:null,Xq=H2&&Set.prototype.forEach,Xle=typeof WeakMap=="function"&&WeakMap.prototype,gd=Xle?WeakMap.prototype.has:null,Zle=typeof WeakSet=="function"&&WeakSet.prototype,pd=Zle?WeakSet.prototype.has:null,efe=typeof WeakRef=="function"&&WeakRef.prototype,Zq=efe?WeakRef.prototype.deref:null,tfe=Boolean.prototype.valueOf,rfe=Object.prototype.toString,nfe=Function.prototype.toString,ife=String.prototype.match,G2=String.prototype.slice,Zo=String.prototype.replace,sfe=String.prototype.toUpperCase,e7=String.prototype.toLowerCase,c7=RegExp.prototype.test,t7=Array.prototype.concat,Es=Array.prototype.join,ofe=Array.prototype.slice,r7=Math.floor,L2=typeof BigInt=="function"?BigInt.prototype.valueOf:null,B2=Object.getOwnPropertySymbols,F2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,Cl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Ur=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Cl||!0)?Symbol.toStringTag:null,l7=Object.prototype.propertyIsEnumerable,n7=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function i7(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||c7.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-r7(-t):r7(t);if(n!==t){var i=String(n),s=G2.call(e,i.length+1);return Zo.call(i,r,"$&_")+"."+Zo.call(Zo.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return Zo.call(e,r,"$&_")}var U2=Yq(),s7=U2.custom,o7=h7(s7)?s7:null;p7.exports=function t(e,r,n,i){var s=r||{};if(Xo(s,"quoteStyle")&&s.quoteStyle!=="single"&&s.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Xo(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=Xo(s,"customInspect")?s.customInspect:!0;if(typeof o!="boolean"&&o!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Xo(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Xo(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var u=s.numericSeparator;if(typeof e>"u")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return g7(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var a=String(e);return u?i7(e,a):a}if(typeof e=="bigint"){var c=String(e)+"n";return u?i7(e,c):c}var f=typeof s.depth>"u"?5:s.depth;if(typeof n>"u"&&(n=0),n>=f&&f>0&&typeof e=="object")return q2(e)?"[Array]":"[Object]";var d=Ife(s,n);if(typeof i>"u")i=[];else if(d7(i,e)>=0)return"[Circular]";function w(l,g,y){if(g&&(i=ofe.call(i),i.push(g)),y){var E={depth:s.depth};return Xo(s,"quoteStyle")&&(E.quoteStyle=s.quoteStyle),t(l,E,n+1,i)}return t(l,s,n+1,i)}if(typeof e=="function"&&!a7(e)){var A=pfe(e),T=v1(e,w);return"[Function"+(A?": "+A:" (anonymous)")+"]"+(T.length>0?" { "+Es.call(T,", ")+" }":"")}if(h7(e)){var x=Cl?Zo.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):F2.call(e);return typeof e=="object"&&!Cl?dd(x):x}if(Efe(e)){for(var B="<"+e7.call(String(e.nodeName)),V=e.attributes||[],U=0;U",B}if(q2(e)){if(e.length===0)return"[]";var Q=v1(e,w);return d&&!Sfe(Q)?"["+V2(Q,d)+"]":"[ "+Es.call(Q,", ")+" ]"}if(cfe(e)){var L=v1(e,w);return!("cause"in Error.prototype)&&"cause"in e&&!l7.call(e,"cause")?"{ ["+String(e)+"] "+Es.call(t7.call("[cause]: "+w(e.cause),L),", ")+" }":L.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+Es.call(L,", ")+" }"}if(typeof e=="object"&&o){if(o7&&typeof e[o7]=="function"&&U2)return U2(e,{depth:f-n});if(o!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(mfe(e)){var k=[];return Jq&&Jq.call(e,function(l,g){k.push(w(g,e,!0)+" => "+w(l,e))}),u7("Map",A1.call(e),k,d)}if(vfe(e)){var H=[];return Xq&&Xq.call(e,function(l){H.push(w(l,e))}),u7("Set",E1.call(e),H,d)}if(yfe(e))return M2("WeakMap");if(Afe(e))return M2("WeakSet");if(wfe(e))return M2("WeakRef");if(ffe(e))return dd(w(Number(e)));if(dfe(e))return dd(w(L2.call(e)));if(hfe(e))return dd(tfe.call(e));if(lfe(e))return dd(w(String(e)));if(typeof window<"u"&&e===window)return"{ [object Window] }";if(e===global)return"{ [object globalThis] }";if(!ufe(e)&&!a7(e)){var q=v1(e,w),v=n7?n7(e)===Object.prototype:e instanceof Object||e.constructor===Object,C=e instanceof Object?"":"null prototype",P=!v&&Ur&&Object(e)===e&&Ur in e?G2.call(ea(e),8,-1):C?"Object":"",F=v||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",R=F+(P||C?"["+Es.call(t7.call([],P||[],C||[]),": ")+"] ":"");return q.length===0?R+"{}":d?R+"{"+V2(q,d)+"}":R+"{ "+Es.call(q,", ")+" }"}return String(e)};function f7(t,e,r){var n=(r.quoteStyle||e)==="double"?'"':"'";return n+t+n}function afe(t){return Zo.call(String(t),/"/g,""")}function q2(t){return ea(t)==="[object Array]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function ufe(t){return ea(t)==="[object Date]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function a7(t){return ea(t)==="[object RegExp]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function cfe(t){return ea(t)==="[object Error]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function lfe(t){return ea(t)==="[object String]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function ffe(t){return ea(t)==="[object Number]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function hfe(t){return ea(t)==="[object Boolean]"&&(!Ur||!(typeof t=="object"&&Ur in t))}function h7(t){if(Cl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!F2)return!1;try{return F2.call(t),!0}catch{}return!1}function dfe(t){if(!t||typeof t!="object"||!L2)return!1;try{return L2.call(t),!0}catch{}return!1}var gfe=Object.prototype.hasOwnProperty||function(t){return t in this};function Xo(t,e){return gfe.call(t,e)}function ea(t){return rfe.call(t)}function pfe(t){if(t.name)return t.name;var e=ife.call(nfe.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function d7(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return g7(G2.call(t,0,e.maxStringLength),e)+n}var i=Zo.call(Zo.call(t,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,bfe);return f7(i,"single",e)}function bfe(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+sfe.call(e.toString(16))}function dd(t){return"Object("+t+")"}function M2(t){return t+" { ? }"}function u7(t,e,r,n){var i=n?V2(r,n):Es.call(r,", ");return t+" ("+e+") {"+i+"}"}function Sfe(t){for(var e=0;e=0)return!1;return!0}function Ife(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=Es.call(Array(t.indent+1)," ");else return null;return{base:r,prev:Es.call(Array(e+1),r)}}function V2(t,e){if(t.length===0)return"";var r=` `+e.prev+e.base;return r+Es.call(t,","+r)+` -`+e.prev}function w1(t,e){var r=q2(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";h();var j2=Xo(),Nl=Mq(),sfe=r7(),ofe=j2("%TypeError%"),E1=j2("%WeakMap%",!0),b1=j2("%Map%",!0),afe=Nl("WeakMap.prototype.get",!0),ufe=Nl("WeakMap.prototype.set",!0),cfe=Nl("WeakMap.prototype.has",!0),lfe=Nl("Map.prototype.get",!0),ffe=Nl("Map.prototype.set",!0),hfe=Nl("Map.prototype.has",!0),z2=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},dfe=function(t,e){var r=z2(t,e);return r&&r.value},gfe=function(t,e,r){var n=z2(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},pfe=function(t,e){return!!z2(t,e)};n7.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new ofe("Side channel does not contain "+sfe(s))},get:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return afe(e,s)}else if(b1){if(r)return lfe(r,s)}else if(n)return dfe(n,s)},has:function(s){if(E1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return cfe(e,s)}else if(b1){if(r)return hfe(r,s)}else if(n)return pfe(n,s);return!1},set:function(s,o){E1&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new E1),ufe(e,s,o)):b1?(r||(r=new b1),ffe(r,s,o)):(n||(n={key:{},next:null}),gfe(n,s,o))}};return i}});var S1=B((h_e,s7)=>{"use strict";h();var mfe=String.prototype.replace,yfe=/%20/g,Q2={RFC1738:"RFC1738",RFC3986:"RFC3986"};s7.exports={default:Q2.RFC3986,formatters:{RFC1738:function(t){return mfe.call(t,yfe,"+")},RFC3986:function(t){return String(t)}},RFC1738:Q2.RFC1738,RFC3986:Q2.RFC3986}});var W2=B((g_e,a7)=>{"use strict";h();var wfe=S1(),K2=Object.prototype.hasOwnProperty,yu=Array.isArray,bs=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),vfe=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(yu(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===wfe.RFC1738&&(c===40||c===41)){u+=o.charAt(a);continue}if(c<128){u=u+bs[c];continue}if(c<2048){u=u+(bs[192|c>>6]+bs[128|c&63]);continue}if(c<55296||c>=57344){u=u+(bs[224|c>>12]+bs[128|c>>6&63]+bs[128|c&63]);continue}a+=1,c=65536+((c&1023)<<10|o.charCodeAt(a)&1023),u+=bs[240|c>>18]+bs[128|c>>12&63]+bs[128|c>>6&63]+bs[128|c&63]}return u},Ife=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";h();var l7=i7(),Y2=W2(),wd=S1(),xfe=Object.prototype.hasOwnProperty,u7={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},wu=Array.isArray,Ofe=String.prototype.split,Dfe=Array.prototype.push,f7=function(t,e){Dfe.apply(t,wu(e)?e:[e])},Pfe=Date.prototype.toISOString,c7=wd.default,Or={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:Y2.encode,encodeValuesOnly:!1,format:c7,formatter:wd.formatters[c7],indices:!1,serializeDate:function(e){return Pfe.call(e)},skipNulls:!1,strictNullHandling:!1},Rfe=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},$2={},Bfe=function t(e,r,n,i,s,o,u,a,c,f,d,w,A,T,x){for(var R=e,V=x,U=0,Q=!1;(V=V.get($2))!==void 0&&!Q;){var L=V.get(e);if(U+=1,typeof L<"u"){if(L===U)throw new RangeError("Cyclic object value");Q=!0}typeof V.get($2)>"u"&&(U=0)}if(typeof u=="function"?R=u(r,R):R instanceof Date?R=f(R):n==="comma"&&wu(R)&&(R=Y2.maybeMap(R,function(S){return S instanceof Date?f(S):S})),R===null){if(i)return o&&!A?o(r,Or.encoder,T,"key",d):r;R=""}if(Rfe(R)||Y2.isBuffer(R)){if(o){var k=A?r:o(r,Or.encoder,T,"key",d);if(n==="comma"&&A){for(var H=Ofe.call(String(R),","),q="",v=0;v"u")return C;var D;if(n==="comma"&&wu(R))D=[{value:R.length>0?R.join(",")||null:void 0}];else if(wu(u))D=u;else{var F=Object.keys(R);D=a?F.sort(a):F}for(var P=0;P"u"?Or.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Or.charsetSentinel,delimiter:typeof e.delimiter>"u"?Or.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Or.encode,encoder:typeof e.encoder=="function"?e.encoder:Or.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Or.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Or.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Or.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Or.strictNullHandling}};h7.exports=function(t,e){var r=t,n=Mfe(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):wu(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var u;e&&e.arrayFormat in u7?u=e.arrayFormat:e&&"indices"in e?u=e.indices?"indices":"repeat":u="indices";var a=u7[u];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=l7(),f=0;f0?A+w:""}});var m7=B((w_e,p7)=>{"use strict";h();var xl=W2(),J2=Object.prototype.hasOwnProperty,Lfe=Array.isArray,Ir={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:xl.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Ffe=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},g7=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},Ufe="utf8=%26%2310003%3B",qfe="utf8=%E2%9C%93",Vfe=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),u=-1,a,c=r.charset;if(r.charsetSentinel)for(a=0;a-1&&(T=Lfe(T)?[T]:T),J2.call(n,A)?n[A]=xl.combine(n[A],T):n[A]=T}return n},kfe=function(t,e,r,n){for(var i=n?e:g7(e,r),s=t.length-1;s>=0;--s){var o,u=t[s];if(u==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var a=u.charAt(0)==="["&&u.charAt(u.length-1)==="]"?u.slice(1,-1):u,c=parseInt(a,10);!r.parseArrays&&a===""?o={0:i}:!isNaN(c)&&u!==a&&String(c)===a&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):a!=="__proto__"&&(o[a]=i)}i=o}return i},Hfe=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,u=/(\[[^[\]]*])/g,a=n.depth>0&&o.exec(s),c=a?s.slice(0,a.index):s,f=[];if(c){if(!n.plainObjects&&J2.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(a=u.exec(s))!==null&&d"u"?Ir.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?Ir.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:Ir.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:Ir.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:Ir.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ir.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:Ir.comma,decoder:typeof e.decoder=="function"?e.decoder:Ir.decoder,delimiter:typeof e.delimiter=="string"||xl.isRegExp(e.delimiter)?e.delimiter:Ir.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:Ir.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:Ir.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:Ir.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:Ir.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ir.strictNullHandling}};p7.exports=function(t,e){var r=Gfe(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?Vfe(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";h();var jfe=d7(),zfe=m7(),Qfe=S1();y7.exports={formats:Qfe,parse:zfe,stringify:jfe}});var X2=B(je=>{"use strict";h();Object.defineProperty(je,"__esModule",{value:!0});je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=je.WALLET_PROVIDER_CALLBACK_PARAM=je.WALLET_PROVIDER_SIGN_MESSAGE_URL=je.WALLET_PROVIDER_GUARD_TRANSACTION_URL=je.WALLET_PROVIDER_SIGN_TRANSACTION_URL=je.WALLET_PROVIDER_SEND_TRANSACTION_URL=je.WALLET_PROVIDER_DISCONNECT_URL=je.WALLET_PROVIDER_CONNECT_URL=je.XALIAS_PROVIDER_TESTNET=je.XALIAS_PROVIDER_DEVNET=je.XALIAS_PROVIDER_MAINNET=je.WALLET_PROVIDER_TESTNET=je.WALLET_PROVIDER_DEVNET=je.WALLET_PROVIDER_MAINNET=void 0;je.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";je.XALIAS_PROVIDER_MAINNET="https://xalias.com";je.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";je.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";je.WALLET_PROVIDER_CONNECT_URL="hook/login";je.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";je.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";je.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";je.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";je.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";je.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var v7=B(Ol=>{"use strict";h();Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrCannotSignedMessage=Ol.ErrCannotGetSignedTransactions=void 0;var Z2=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Ol.ErrCannotGetSignedTransactions=Z2;var eC=class extends Error{constructor(){super("Cannot get signed message")}};Ol.ErrCannotSignedMessage=eC});var A7=B(I1=>{"use strict";h();Object.defineProperty(I1,"__esModule",{value:!0});I1.PlainSignedTransaction=void 0;var tC=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};I1.PlainSignedTransaction=tC});var Dl=B(ia=>{"use strict";h();var ra=ia&&ia.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},Kfe=ia&&ia.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ia,"__esModule",{value:!0});ia.WalletProvider=void 0;var rC=Kfe(w7()),na=X2(),nC=v7(),Wfe=A7(),iC=class t{constructor(e){this.walletUrl=e}login(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return ra(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return ra(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return ra(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return ra(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:na.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=rC.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new nC.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return ra(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(na.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return ra(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(e=window.location.search){let r=rC.default.parse(e.slice(1));return t.isTxSignReturnSuccess(r)?this.getTxSignReturnValue(r):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(na.WALLET_PROVIDER_CALLBACK_PARAM)&&e[na.WALLET_PROVIDER_CALLBACK_PARAM]===na.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new nC.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new nC.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let u=t.prepareWalletTransaction(o);for(let a in u)u.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(i[a]=[]),i[a].push(u[a])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};ia.WalletProvider=iC});var e9=B((O_e,Z7)=>{"use strict";h();function P7(t,e){return function(){return t.apply(e,arguments)}}var{toString:$fe}=Object.prototype,{getPrototypeOf:mC}=Object,N1=(t=>e=>{let r=$fe.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Is=t=>(t=t.toLowerCase(),e=>N1(e)===t),x1=t=>e=>typeof e===t,{isArray:Ml}=Array,Ad=x1("undefined");function Yfe(t){return t!==null&&!Ad(t)&&t.constructor!==null&&!Ad(t.constructor)&&ei(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var R7=Is("ArrayBuffer");function Jfe(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&R7(t.buffer),e}var Xfe=x1("string"),ei=x1("function"),B7=x1("number"),O1=t=>t!==null&&typeof t=="object",Zfe=t=>t===!0||t===!1,T1=t=>{if(N1(t)!=="object")return!1;let e=mC(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ehe=Is("Date"),the=Is("File"),rhe=Is("Blob"),nhe=Is("FileList"),ihe=t=>O1(t)&&ei(t.pipe),she=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ei(t.append)&&((e=N1(t))==="formdata"||e==="object"&&ei(t.toString)&&t.toString()==="[object FormData]"))},ohe=Is("URLSearchParams"),ahe=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ed(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ml(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var L7=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F7=t=>!Ad(t)&&t!==L7;function cC(){let{caseless:t}=F7(this)&&this||{},e={},r=(n,i)=>{let s=t&&M7(e,i)||i;T1(e[s])&&T1(n)?e[s]=cC(e[s],n):T1(n)?e[s]=cC({},n):Ml(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(Ed(e,(i,s)=>{r&&ei(i)?t[s]=P7(i,r):t[s]=i},{allOwnKeys:n}),t),che=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),lhe=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},fhe=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&mC(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},hhe=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},dhe=t=>{if(!t)return null;if(Ml(t))return t;let e=t.length;if(!B7(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},ghe=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&mC(Uint8Array)),phe=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},mhe=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},yhe=Is("HTMLFormElement"),whe=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),E7=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),vhe=Is("RegExp"),U7=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};Ed(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},Ahe=t=>{U7(t,(e,r)=>{if(ei(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(ei(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Ehe=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ml(t)?n(t):n(String(t).split(e)),r},bhe=()=>{},She=(t,e)=>(t=+t,Number.isFinite(t)?t:e),sC="abcdefghijklmnopqrstuvwxyz",b7="0123456789",q7={DIGIT:b7,ALPHA:sC,ALPHA_DIGIT:sC+sC.toUpperCase()+b7},Ihe=(t=16,e=q7.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function The(t){return!!(t&&ei(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var _he=t=>{let e=new Array(10),r=(n,i)=>{if(O1(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ml(n)?[]:{};return Ed(n,(o,u)=>{let a=r(o,i+1);!Ad(a)&&(s[u]=a)}),e[i]=void 0,s}}return n};return r(t,0)},Che=Is("AsyncFunction"),Nhe=t=>t&&(O1(t)||ei(t))&&ei(t.then)&&ei(t.catch),re={isArray:Ml,isArrayBuffer:R7,isBuffer:Yfe,isFormData:she,isArrayBufferView:Jfe,isString:Xfe,isNumber:B7,isBoolean:Zfe,isObject:O1,isPlainObject:T1,isUndefined:Ad,isDate:ehe,isFile:the,isBlob:rhe,isRegExp:vhe,isFunction:ei,isStream:ihe,isURLSearchParams:ohe,isTypedArray:ghe,isFileList:nhe,forEach:Ed,merge:cC,extend:uhe,trim:ahe,stripBOM:che,inherits:lhe,toFlatObject:fhe,kindOf:N1,kindOfTest:Is,endsWith:hhe,toArray:dhe,forEachEntry:phe,matchAll:mhe,isHTMLForm:yhe,hasOwnProperty:E7,hasOwnProp:E7,reduceDescriptors:U7,freezeMethods:Ahe,toObjectSet:Ehe,toCamelCase:whe,noop:bhe,toFiniteNumber:She,findKey:M7,global:L7,isContextDefined:F7,ALPHABET:q7,generateString:Ihe,isSpecCompliantForm:The,toJSONObject:_he,isAsyncFn:Che,isThenable:Nhe};function Le(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}re.inherits(Le,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:re.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var V7=Le.prototype,k7={};["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(t=>{k7[t]={value:t}});Object.defineProperties(Le,k7);Object.defineProperty(V7,"isAxiosError",{value:!0});Le.from=(t,e,r,n,i,s)=>{let o=Object.create(V7);return re.toFlatObject(t,o,function(a){return a!==Error.prototype},u=>u!=="isAxiosError"),Le.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var xhe=null;function lC(t){return re.isPlainObject(t)||re.isArray(t)}function H7(t){return re.endsWith(t,"[]")?t.slice(0,-2):t}function S7(t,e,r){return t?t.concat(e).map(function(i,s){return i=H7(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Ohe(t){return re.isArray(t)&&!t.some(lC)}var Dhe=re.toFlatObject(re,{},null,function(e){return/^is[A-Z]/.test(e)});function D1(t,e,r){if(!re.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=re.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,R){return!re.isUndefined(R[x])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,a=(r.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function c(T){if(T===null)return"";if(re.isDate(T))return T.toISOString();if(!a&&re.isBlob(T))throw new Le("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(T)||re.isTypedArray(T)?a&&typeof Blob=="function"?new Blob([T]):p.Buffer.from(T):T}function f(T,x,R){let V=T;if(T&&!R&&typeof T=="object"){if(re.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=JSON.stringify(T);else if(re.isArray(T)&&Ohe(T)||(re.isFileList(T)||re.endsWith(x,"[]"))&&(V=re.toArray(T)))return x=H7(x),V.forEach(function(Q,L){!(re.isUndefined(Q)||Q===null)&&e.append(o===!0?S7([x],L,s):o===null?x:x+"[]",c(Q))}),!1}return lC(T)?!0:(e.append(S7(R,x,s),c(T)),!1)}let d=[],w=Object.assign(Dhe,{defaultVisitor:f,convertValue:c,isVisitable:lC});function A(T,x){if(!re.isUndefined(T)){if(d.indexOf(T)!==-1)throw Error("Circular reference detected in "+x.join("."));d.push(T),re.forEach(T,function(V,U){(!(re.isUndefined(V)||V===null)&&i.call(e,V,re.isString(U)?U.trim():U,x,w))===!0&&A(V,x?x.concat(U):[U])}),d.pop()}}if(!re.isObject(t))throw new TypeError("data must be an object");return A(t),e}function I7(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function yC(t,e){this._pairs=[],t&&D1(t,this,e)}var G7=yC.prototype;G7.append=function(e,r){this._pairs.push([e,r])};G7.toString=function(e){let r=e?function(n){return e.call(this,n,I7)}:I7;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Phe(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function j7(t,e,r){if(!e)return t;let n=r&&r.encode||Phe,i=r&&r.serialize,s;if(i?s=i(e,r):s=re.isURLSearchParams(e)?e.toString():new yC(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var fC=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(n){n!==null&&e(n)})}},T7=fC,z7={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Rhe=typeof URLSearchParams<"u"?URLSearchParams:yC,Bhe=typeof FormData<"u"?FormData:null,Mhe=typeof Blob<"u"?Blob:null,Lhe={isBrowser:!0,classes:{URLSearchParams:Rhe,FormData:Bhe,Blob:Mhe},protocols:["http","https","file","blob","url","data"]},Q7=typeof window<"u"&&typeof document<"u",Fhe=(t=>Q7&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),Uhe=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",qhe=Object.freeze({__proto__:null,hasBrowserEnv:Q7,hasStandardBrowserWebWorkerEnv:Uhe,hasStandardBrowserEnv:Fhe}),Ss={...qhe,...Lhe};function Vhe(t,e){return D1(t,new Ss.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Ss.isNode&&re.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function khe(t){return re.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Hhe(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&re.isArray(i)?i.length:o,a?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&re.isArray(i[o])&&(i[o]=Hhe(i[o])),!u)}if(re.isFormData(t)&&re.isFunction(t.entries)){let r={};return re.forEachEntry(t,(n,i)=>{e(khe(n),i,r,0)}),r}return null}function Ghe(t,e,r){if(re.isString(t))try{return(e||JSON.parse)(t),re.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var wC={transitional:z7,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=re.isObject(e);if(s&&re.isHTMLForm(e)&&(e=new FormData(e)),re.isFormData(e))return i?JSON.stringify(K7(e)):e;if(re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e))return e;if(re.isArrayBufferView(e))return e.buffer;if(re.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Vhe(e,this.formSerializer).toString();if((u=re.isFileList(e))||n.indexOf("multipart/form-data")>-1){let a=this.env&&this.env.FormData;return D1(u?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Ghe(e)):e}],transformResponse:[function(e){let r=this.transitional||wC.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&re.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?Le.from(u,Le.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ss.classes.FormData,Blob:Ss.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],t=>{wC.headers[t]={}});var vC=wC,jhe=re.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"]),zhe=t=>{let e={},r,n,i;return t&&t.split(` -`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&jhe[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},_7=Symbol("internals");function vd(t){return t&&String(t).trim().toLowerCase()}function _1(t){return t===!1||t==null?t:re.isArray(t)?t.map(_1):String(t)}function Qhe(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var Khe=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function oC(t,e,r,n,i){if(re.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function Whe(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function $he(t,e){let r=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Pl=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,a,c){let f=vd(a);if(!f)throw new Error("header name must be a non-empty string");let d=re.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||a]=_1(u))}let o=(u,a)=>re.forEach(u,(c,f)=>s(c,f,a));return re.isPlainObject(e)||e instanceof this.constructor?o(e,r):re.isString(e)&&(e=e.trim())&&!Khe(e)?o(zhe(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=vd(e),e){let n=re.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return Qhe(i);if(re.isFunction(r))return r.call(this,i,n);if(re.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=vd(e),e){let n=re.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||oC(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=vd(o),o){let u=re.findKey(n,o);u&&(!r||oC(n,n[u],u,r))&&(delete n[u],i=!0)}}return re.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||oC(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return re.forEach(this,(i,s)=>{let o=re.findKey(n,s);if(o){r[o]=_1(i),delete r[s];return}let u=e?Whe(s):String(s).trim();u!==s&&delete r[s],r[u]=_1(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return re.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&re.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[_7]=this[_7]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=vd(o);n[u]||($he(i,o),n[u]=!0)}return re.isArray(e)?e.forEach(s):s(e),this}};Pl.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);re.reduceDescriptors(Pl.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});re.freezeMethods(Pl);var ro=Pl;function aC(t,e){let r=this||vC,n=e||r,i=ro.from(n.headers),s=n.data;return re.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function W7(t){return!!(t&&t.__CANCEL__)}function bd(t,e,r){Le.call(this,t??"canceled",Le.ERR_CANCELED,e,r),this.name="CanceledError"}re.inherits(bd,Le,{__CANCEL__:!0});function Yhe(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Le("Request failed with status code "+r.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var Jhe=Ss.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];re.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),re.isString(n)&&o.push("path="+n),re.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Xhe(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Zhe(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function $7(t,e){return t&&!Xhe(e)?Zhe(t,e):e}var ede=Ss.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=re.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function tde(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function rde(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(a){let c=Date.now(),f=n[s];o||(o=c),r[i]=a,n[i]=c;let d=s,w=0;for(;d!==i;)w+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,a=n(u),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:a||void 0,estimated:a&&o&&c?(o-s)/a:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var nde=typeof XMLHttpRequest<"u",ide=nde&&function(t){return new Promise(function(r,n){let i=t.data,s=ro.from(t.headers).normalize(),{responseType:o,withXSRFToken:u}=t,a;function c(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}let f;if(re.isFormData(i)){if(Ss.hasStandardBrowserEnv||Ss.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[x,...R]=f?f.split(";").map(V=>V.trim()).filter(Boolean):[];s.setContentType([x||"multipart/form-data",...R].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let x=t.auth.username||"",R=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(x+":"+R))}let w=$7(t.baseURL,t.url);d.open(t.method.toUpperCase(),j7(w,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function A(){if(!d)return;let x=ro.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),V={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:x,config:t,request:d};Yhe(function(Q){r(Q),c()},function(Q){n(Q),c()},V),d=null}if("onloadend"in d?d.onloadend=A:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(A)},d.onabort=function(){d&&(n(new Le("Request aborted",Le.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Le("Network Error",Le.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let R=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||z7;t.timeoutErrorMessage&&(R=t.timeoutErrorMessage),n(new Le(R,V.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,t,d)),d=null},Ss.hasStandardBrowserEnv&&(u&&re.isFunction(u)&&(u=u(t)),u||u!==!1&&ede(w))){let x=t.xsrfHeaderName&&t.xsrfCookieName&&Jhe.read(t.xsrfCookieName);x&&s.set(t.xsrfHeaderName,x)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&re.forEach(s.toJSON(),function(R,V){d.setRequestHeader(V,R)}),re.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",C7(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",C7(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=x=>{d&&(n(!x||x.type?new bd(null,t,d):x),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));let T=tde(w);if(T&&Ss.protocols.indexOf(T)===-1){n(new Le("Unsupported protocol "+T+":",Le.ERR_BAD_REQUEST,t));return}d.send(i||null)})},hC={http:xhe,xhr:ide};re.forEach(hC,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var N7=t=>`- ${t}`,sde=t=>re.isFunction(t)||t===null||t===!1,Y7={getAdapter:t=>{t=re.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${u} `+(a===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : -`+s.map(N7).join(` -`):" "+N7(s[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:hC};function uC(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new bd(null,t)}function x7(t){return uC(t),t.headers=ro.from(t.headers),t.data=aC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Y7.getAdapter(t.adapter||vC.adapter)(t).then(function(n){return uC(t),n.data=aC.call(t,t.transformResponse,n),n.headers=ro.from(n.headers),n},function(n){return W7(n)||(uC(t),n&&n.response&&(n.response.data=aC.call(t,t.transformResponse,n.response),n.response.headers=ro.from(n.response.headers))),Promise.reject(n)})}var O7=t=>t instanceof ro?{...t}:t;function Rl(t,e){e=e||{};let r={};function n(c,f,d){return re.isPlainObject(c)&&re.isPlainObject(f)?re.merge.call({caseless:d},c,f):re.isPlainObject(f)?re.merge({},f):re.isArray(f)?f.slice():f}function i(c,f,d){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!re.isUndefined(f))return n(void 0,f)}function o(c,f){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function u(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let 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:u,headers:(c,f)=>i(O7(c),O7(f),!0)};return re.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=a[f]||i,w=d(t[f],e[f],f);re.isUndefined(w)&&d!==u||(r[f]=w)}),r}var J7="1.6.8",AC={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{AC[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var D7={};AC.transitional=function(e,r,n){function i(s,o){return"[Axios v"+J7+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new Le(i(o," has been removed"+(r?" in "+r:"")),Le.ERR_DEPRECATED);return r&&!D7[o]&&(D7[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function ode(t,e,r){if(typeof t!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],a=u===void 0||o(u,s,t);if(a!==!0)throw new Le("option "+s+" must be "+a,Le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}var dC={assertOptions:ode,validators:AC},sa=dC.validators,Bl=class{constructor(e){this.defaults=e,this.interceptors={request:new T7,response:new T7}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` -`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Rl(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&dC.assertOptions(n,{silentJSONParsing:sa.transitional(sa.boolean),forcedJSONParsing:sa.transitional(sa.boolean),clarifyTimeoutError:sa.transitional(sa.boolean)},!1),i!=null&&(re.isFunction(i)?r.paramsSerializer={serialize:i}:dC.assertOptions(i,{encode:sa.function,serialize:sa.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&re.merge(s.common,s[r.method]);s&&re.forEach(["delete","get","head","post","put","patch","common"],T=>{delete s[T]}),r.headers=ro.concat(o,s);let u=[],a=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(r)===!1||(a=a&&x.synchronous,u.unshift(x.fulfilled,x.rejected))});let c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let f,d=0,w;if(!a){let T=[x7.bind(this),void 0];for(T.unshift.apply(T,u),T.push.apply(T,c),w=T.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new bd(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},ade=gC;function ude(t){return function(r){return t.apply(null,r)}}function cde(t){return re.isObject(t)&&t.isAxiosError===!0}var pC={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(pC).forEach(([t,e])=>{pC[e]=t});var lde=pC;function X7(t){let e=new C1(t),r=P7(C1.prototype.request,e);return re.extend(r,C1.prototype,e,{allOwnKeys:!0}),re.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return X7(Rl(t,i))},r}var cr=X7(vC);cr.Axios=C1;cr.CanceledError=bd;cr.CancelToken=ade;cr.isCancel=W7;cr.VERSION=J7;cr.toFormData=D1;cr.AxiosError=Le;cr.Cancel=cr.CanceledError;cr.all=function(e){return Promise.all(e)};cr.spread=ude;cr.isAxiosError=cde;cr.mergeConfig=Rl;cr.AxiosHeaders=ro;cr.formToJSON=t=>K7(re.isHTMLForm(t)?new FormData(t):t);cr.getAdapter=Y7.getAdapter;cr.HttpStatusCode=lde;cr.default=cr;Z7.exports=cr});var t9=B(P1=>{"use strict";h();Object.defineProperty(P1,"__esModule",{value:!0});P1.NativeAuthClientConfig=void 0;var EC=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};P1.NativeAuthClientConfig=EC});var SC=B(Ll=>{"use strict";h();var vu=Ll&&Ll.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.NativeAuthClient=void 0;var fde=e9(),hde=t9(),bC=class{constructor(e){this.config=Object.assign(new hde.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vu(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vu(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vu(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vu(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vu(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vu(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(p.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vu(this,void 0,void 0,function*(){return yield fde.default.get(e,{headers:this.config.extraRequestHeaders})})}};Ll.NativeAuthClient=bC});var s9=B(B1=>{"use strict";h();Object.defineProperty(B1,"__esModule",{value:!0});B1.TransactionStatus=void 0;var TC=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};B1.TransactionStatus=TC});var a9=B(M1=>{"use strict";h();Object.defineProperty(M1,"__esModule",{value:!0});M1.TransactionReceipt=void 0;var o9=_c(),_C=class t{constructor(){this.value="",this.sender=new o9.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new o9.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};M1.TransactionReceipt=_C});var u9=B(Ts=>{"use strict";h();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ErrContractQuery=Ts.ErrNetworkProvider=Ts.ErrUnexpectedCondition=Ts.Err=void 0;var Ul=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ts.Err=Ul;var CC=class extends Ul{constructor(e){super(`Unexpected condition: [${e}]`)}};Ts.ErrUnexpectedCondition=CC;var NC=class extends Ul{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Ts.ErrNetworkProvider=NC;var xC=class extends Ul{constructor(e){super(e.message.replace("executeQuery:",""))}};Ts.ErrContractQuery=xC});var l9=B(oa=>{"use strict";h();Object.defineProperty(oa,"__esModule",{value:!0});oa.TransactionEventTopic=oa.TransactionEventData=oa.TransactionEvent=void 0;var c9=_c(),OC=class t{constructor(e){this.address=new c9.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new ql(p.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new c9.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new L1(n)),r.dataPayload=ql.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(ql.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};oa.TransactionEvent=OC;var ql=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(p.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventData=ql;var L1=class{constructor(e){this.raw=p.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};oa.TransactionEventTopic=L1});var PC=B(F1=>{"use strict";h();Object.defineProperty(F1,"__esModule",{value:!0});F1.TransactionLogs=void 0;var pde=u9(),f9=_c(),mde=l9(),DC=class t{constructor(e){this.address=new f9.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new f9.Address(e.address),r.events=(e.events||[]).map(n=>mde.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new pde.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};F1.TransactionLogs=DC});var d9=B(Vl=>{"use strict";h();Object.defineProperty(Vl,"__esModule",{value:!0});Vl.ContractResultItem=Vl.ContractResults=void 0;var h9=PC(),U1=_c(),RC=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>Sd.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>Sd.fromApiHttpResponse(n));return new t(r)}};Vl.ContractResults=RC;var Sd=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new U1.Address(""),this.sender=new U1.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new h9.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=p.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new U1.Address(e.receiver),r.sender=new U1.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=h9.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Vl.ContractResultItem=Sd});var g9=B(q1=>{"use strict";h();Object.defineProperty(q1,"__esModule",{value:!0});q1.ContractQueryRequest=void 0;var BC=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};q1.ContractQueryRequest=BC});var _9=B((R2e,T9)=>{h();T9.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var aa=B(Eu=>{h();var MC,yde=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Eu.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Eu.getSymbolTotalCodewords=function(e){return yde[e]};Eu.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Eu.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');MC=e};Eu.isKanjiModeEnabled=function(){return typeof MC<"u"};Eu.toSJIS=function(e){return MC(e)}});var G1=B(ti=>{h();ti.L={bit:1};ti.M={bit:0};ti.Q={bit:3};ti.H={bit:2};function wde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ti.L;case"m":case"medium":return ti.M;case"q":case"quartile":return ti.Q;case"h":case"high":return ti.H;default:throw new Error("Unknown EC Level: "+t)}}ti.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ti.from=function(e,r){if(ti.isValid(e))return e;try{return wde(e)}catch{return r}}});var x9=B((q2e,N9)=>{h();function C9(){this.buffer=[],this.length=0}C9.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};N9.exports=C9});var D9=B((k2e,O9)=>{h();function Id(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}Id.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};Id.prototype.get=function(t,e){return this.data[t*this.size+e]};Id.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Id.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};O9.exports=Id});var P9=B(j1=>{h();var vde=aa().getSymbolSize;j1.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=vde(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{h();var Ade=aa().getSymbolSize,R9=7;B9.getPositions=function(e){let r=Ade(e);return[[0,0],[r-R9,0],[0,r-R9]]}});var L9=B(Rt=>{h();Rt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bu={N1:3,N2:3,N3:40,N4:10};Rt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Rt.from=function(e){return Rt.isValid(e)?parseInt(e,10):void 0};Rt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,u=null;for(let a=0;a=5&&(n+=bu.N1+(i-5)),o=f,i=1),f=e.get(c,a),f===u?s++:(s>=5&&(n+=bu.N1+(s-5)),u=f,s=1)}i>=5&&(n+=bu.N1+(i-5)),s>=5&&(n+=bu.N1+(s-5))}return n};Rt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(u,o),u>=10&&(s===1488||s===93)&&n++}return n*bu.N3};Rt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{h();var ua=G1(),z1=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Q1=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];LC.getBlocksCount=function(e,r){switch(r){case ua.L:return z1[(e-1)*4+0];case ua.M:return z1[(e-1)*4+1];case ua.Q:return z1[(e-1)*4+2];case ua.H:return z1[(e-1)*4+3];default:return}};LC.getTotalCodewordsCount=function(e,r){switch(r){case ua.L:return Q1[(e-1)*4+0];case ua.M:return Q1[(e-1)*4+1];case ua.Q:return Q1[(e-1)*4+2];case ua.H:return Q1[(e-1)*4+3];default:return}}});var F9=B(W1=>{h();var Td=new Uint8Array(512),K1=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Td[r]=e,K1[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Td[r]=Td[r-255]})();W1.log=function(e){if(e<1)throw new Error("log("+e+")");return K1[e]};W1.exp=function(e){return Td[e]};W1.mul=function(e,r){return e===0||r===0?0:Td[K1[e]+K1[r]]}});var U9=B(_d=>{h();var UC=F9();_d.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{h();var q9=U9();function qC(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}qC.prototype.initialize=function(e){this.degree=e,this.genPoly=q9.generateECPolynomial(this.degree)};qC.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=q9.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};V9.exports=qC});var VC=B(H9=>{h();H9.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var kC=B(no=>{h();var G9="[0-9]+",bde="[A-Z $%*+\\-./:]+",Cd="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Cd=Cd.replace(/u/g,"\\u");var Sde="(?:(?![A-Z0-9 $%*+\\-./:]|"+Cd+`)(?:.|[\r -]))+`;no.KANJI=new RegExp(Cd,"g");no.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");no.BYTE=new RegExp(Sde,"g");no.NUMERIC=new RegExp(G9,"g");no.ALPHANUMERIC=new RegExp(bde,"g");var Ide=new RegExp("^"+Cd+"$"),Tde=new RegExp("^"+G9+"$"),_de=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");no.testKanji=function(e){return Ide.test(e)};no.testNumeric=function(e){return Tde.test(e)};no.testAlphanumeric=function(e){return _de.test(e)}});var ca=B(lr=>{h();var Cde=VC(),HC=kC();lr.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};lr.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};lr.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};lr.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};lr.MIXED={bit:-1};lr.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Cde.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};lr.getBestModeForData=function(e){return HC.testNumeric(e)?lr.NUMERIC:HC.testAlphanumeric(e)?lr.ALPHANUMERIC:HC.testKanji(e)?lr.KANJI:lr.BYTE};lr.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};lr.isValid=function(e){return e&&e.bit&&e.ccBits};function Nde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return lr.NUMERIC;case"alphanumeric":return lr.ALPHANUMERIC;case"kanji":return lr.KANJI;case"byte":return lr.BYTE;default:throw new Error("Unknown mode: "+t)}}lr.from=function(e,r){if(lr.isValid(e))return e;try{return Nde(e)}catch{return r}}});var W9=B(Su=>{h();var $1=aa(),xde=FC(),j9=G1(),la=ca(),GC=VC(),Q9=7973,z9=$1.getBCHDigit(Q9);function Ode(t,e,r){for(let n=1;n<=40;n++)if(e<=Su.getCapacity(n,r,t))return n}function K9(t,e){return la.getCharCountIndicator(t,e)+4}function Dde(t,e){let r=0;return t.forEach(function(n){let i=K9(n.mode,e);r+=i+n.getBitsLength()}),r}function Pde(t,e){for(let r=1;r<=40;r++)if(Dde(t,r)<=Su.getCapacity(r,e,la.MIXED))return r}Su.from=function(e,r){return GC.isValid(e)?parseInt(e,10):r};Su.getCapacity=function(e,r,n){if(!GC.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=la.BYTE);let i=$1.getSymbolTotalCodewords(e),s=xde.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===la.MIXED)return o;let u=o-K9(n,e);switch(n){case la.NUMERIC:return Math.floor(u/10*3);case la.ALPHANUMERIC:return Math.floor(u/11*2);case la.KANJI:return Math.floor(u/13);case la.BYTE:default:return Math.floor(u/8)}};Su.getBestVersionForData=function(e,r){let n,i=j9.from(r,j9.M);if(Array.isArray(e)){if(e.length>1)return Pde(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Ode(n.mode,n.getLength(),i)};Su.getEncodedBits=function(e){if(!GC.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;$1.getBCHDigit(r)-z9>=0;)r^=Q9<<$1.getBCHDigit(r)-z9;return e<<12|r}});var X9=B(J9=>{h();var jC=aa(),Y9=1335,Rde=21522,$9=jC.getBCHDigit(Y9);J9.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;jC.getBCHDigit(i)-$9>=0;)i^=Y9<{h();var Bde=ca();function Hl(t){this.mode=Bde.NUMERIC,this.data=t.toString()}Hl.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Hl.prototype.getLength=function(){return this.data.length};Hl.prototype.getBitsLength=function(){return Hl.getBitsLength(this.data.length)};Hl.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};Z9.exports=Hl});var rV=B((pCe,tV)=>{h();var Mde=ca(),zC=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Gl(t){this.mode=Mde.ALPHANUMERIC,this.data=t}Gl.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Gl.prototype.getLength=function(){return this.data.length};Gl.prototype.getBitsLength=function(){return Gl.getBitsLength(this.data.length)};Gl.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=zC.indexOf(this.data[r])*45;n+=zC.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(zC.indexOf(this.data[r]),6)};tV.exports=Gl});var iV=B((yCe,nV)=>{"use strict";h();nV.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var oV=B((vCe,sV)=>{h();var Lde=iV(),Fde=ca();function jl(t){this.mode=Fde.BYTE,typeof t=="string"&&(t=Lde(t)),this.data=new Uint8Array(t)}jl.getBitsLength=function(e){return e*8};jl.prototype.getLength=function(){return this.data.length};jl.prototype.getBitsLength=function(){return jl.getBitsLength(this.data.length)};jl.prototype.write=function(t){for(let e=0,r=this.data.length;e{h();var Ude=ca(),qde=aa();function zl(t){this.mode=Ude.KANJI,this.data=t}zl.getBitsLength=function(e){return e*13};zl.prototype.getLength=function(){return this.data.length};zl.prototype.getBitsLength=function(){return zl.getBitsLength(this.data.length)};zl.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` -Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};aV.exports=zl});var cV=B((SCe,QC)=>{"use strict";h();var Nd={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=Nd.PriorityQueue.make();s.push(e,0);for(var o,u,a,c,f,d,w,A,T;!s.empty();){o=s.pop(),u=o.value,c=o.cost,f=t[u]||{};for(a in f)f.hasOwnProperty(a)&&(d=f[a],w=c+d,A=i[a],T=typeof i[a]>"u",(T||A>w)&&(i[a]=w,s.push(a,w),n[a]=u))}if(typeof r<"u"&&typeof i[r]>"u"){var x=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(x)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=Nd.single_source_shortest_paths(t,e,r);return Nd.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Nd.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof QC<"u"&&(QC.exports=Nd)});var yV=B(Ql=>{h();var ze=ca(),hV=eV(),dV=rV(),gV=oV(),pV=uV(),xd=kC(),Y1=aa(),Vde=cV();function lV(t){return unescape(encodeURIComponent(t)).length}function Od(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function mV(t){let e=Od(xd.NUMERIC,ze.NUMERIC,t),r=Od(xd.ALPHANUMERIC,ze.ALPHANUMERIC,t),n,i;return Y1.isKanjiModeEnabled()?(n=Od(xd.BYTE,ze.BYTE,t),i=Od(xd.KANJI,ze.KANJI,t)):(n=Od(xd.BYTE_KANJI,ze.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,u){return o.index-u.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function KC(t,e){switch(e){case ze.NUMERIC:return hV.getBitsLength(t);case ze.ALPHANUMERIC:return dV.getBitsLength(t);case ze.KANJI:return pV.getBitsLength(t);case ze.BYTE:return gV.getBitsLength(t)}}function kde(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Hde(t){let e=[];for(let r=0;r{h();var X1=aa(),WC=G1(),jde=x9(),zde=D9(),Qde=P9(),Kde=M9(),JC=L9(),XC=FC(),Wde=k9(),J1=W9(),$de=X9(),Yde=ca(),$C=yV();function Jde(t,e){let r=t.size,n=Kde.getPositions(e);for(let i=0;i=0&&u<=6&&(a===0||a===6)||a>=0&&a<=6&&(u===0||u===6)||u>=2&&u<=4&&a>=2&&a<=4?t.set(s+u,o+a,!0,!0):t.set(s+u,o+a,!1,!0))}}function Xde(t){let e=t.size;for(let r=8;r>u&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function YC(t,e,r){let n=t.size,i=$de.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function tge(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let u=r-1;u>0;u-=2)for(u===6&&u--;;){for(let a=0;a<2;a++)if(!t.isReserved(i,u-a)){let c=!1;o>>s&1)===1),t.set(i,u-a,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function rge(t,e,r){let n=new jde;r.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),Yde.getCharCountIndicator(a.mode,t)),a.write(n)});let i=X1.getSymbolTotalCodewords(t),s=XC.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let u=(o-n.getLengthInBits())/8;for(let a=0;a{"use strict";h();var y7=mu(),Nl=$q(),Tfe=m7(),_fe=El(),b1=y7("%WeakMap%",!0),S1=y7("%Map%",!0),Cfe=Nl("WeakMap.prototype.get",!0),Nfe=Nl("WeakMap.prototype.set",!0),xfe=Nl("WeakMap.prototype.has",!0),Ofe=Nl("Map.prototype.get",!0),Dfe=Nl("Map.prototype.set",!0),Pfe=Nl("Map.prototype.has",!0),j2=function(t,e){for(var r=t,n;(n=r.next)!==null;r=n)if(n.key===e)return r.next=n.next,n.next=t.next,t.next=n,n},Rfe=function(t,e){var r=j2(t,e);return r&&r.value},Bfe=function(t,e,r){var n=j2(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},Mfe=function(t,e){return!!j2(t,e)};w7.exports=function(){var e,r,n,i={assert:function(s){if(!i.has(s))throw new _fe("Side channel does not contain "+Tfe(s))},get:function(s){if(b1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return Cfe(e,s)}else if(S1){if(r)return Ofe(r,s)}else if(n)return Rfe(n,s)},has:function(s){if(b1&&s&&(typeof s=="object"||typeof s=="function")){if(e)return xfe(e,s)}else if(S1){if(r)return Pfe(r,s)}else if(n)return Mfe(n,s);return!1},set:function(s,o){b1&&s&&(typeof s=="object"||typeof s=="function")?(e||(e=new b1),Nfe(e,s,o)):S1?(r||(r=new S1),Dfe(r,s,o)):(n||(n={key:{},next:null}),Bfe(n,s,o))}};return i}});var I1=D((W_e,A7)=>{"use strict";h();var Lfe=String.prototype.replace,Ffe=/%20/g,z2={RFC1738:"RFC1738",RFC3986:"RFC3986"};A7.exports={default:z2.RFC3986,formatters:{RFC1738:function(t){return Lfe.call(t,Ffe,"+")},RFC3986:function(t){return String(t)}},RFC1738:z2.RFC1738,RFC3986:z2.RFC3986}});var K2=D((Y_e,b7)=>{"use strict";h();var Ufe=I1(),Q2=Object.prototype.hasOwnProperty,yu=Array.isArray,bs=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),qfe=function(e){for(;e.length>1;){var r=e.pop(),n=r.obj[r.prop];if(yu(n)){for(var i=[],s=0;s=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===Ufe.RFC1738&&(c===40||c===41)){u+=o.charAt(a);continue}if(c<128){u=u+bs[c];continue}if(c<2048){u=u+(bs[192|c>>6]+bs[128|c&63]);continue}if(c<55296||c>=57344){u=u+(bs[224|c>>12]+bs[128|c>>6&63]+bs[128|c&63]);continue}a+=1,c=65536+((c&1023)<<10|o.charCodeAt(a)&1023),u+=bs[240|c>>18]+bs[128|c>>12&63]+bs[128|c>>6&63]+bs[128|c&63]}return u},jfe=function(e){for(var r=[{obj:{o:e},prop:"o"}],n=[],i=0;i{"use strict";h();var T7=v7(),$2=K2(),md=I1(),$fe=Object.prototype.hasOwnProperty,S7={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},wu=Array.isArray,Yfe=String.prototype.split,Jfe=Array.prototype.push,_7=function(t,e){Jfe.apply(t,wu(e)?e:[e])},Xfe=Date.prototype.toISOString,I7=md.default,Or={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:$2.encode,encodeValuesOnly:!1,format:I7,formatter:md.formatters[I7],indices:!1,serializeDate:function(e){return Xfe.call(e)},skipNulls:!1,strictNullHandling:!1},Zfe=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},W2={},ehe=function t(e,r,n,i,s,o,u,a,c,f,d,w,A,T,x){for(var B=e,V=x,U=0,Q=!1;(V=V.get(W2))!==void 0&&!Q;){var L=V.get(e);if(U+=1,typeof L<"u"){if(L===U)throw new RangeError("Cyclic object value");Q=!0}typeof V.get(W2)>"u"&&(U=0)}if(typeof u=="function"?B=u(r,B):B instanceof Date?B=f(B):n==="comma"&&wu(B)&&(B=$2.maybeMap(B,function(I){return I instanceof Date?f(I):I})),B===null){if(i)return o&&!A?o(r,Or.encoder,T,"key",d):r;B=""}if(Zfe(B)||$2.isBuffer(B)){if(o){var k=A?r:o(r,Or.encoder,T,"key",d);if(n==="comma"&&A){for(var H=Yfe.call(String(B),","),q="",v=0;v"u")return C;var P;if(n==="comma"&&wu(B))P=[{value:B.length>0?B.join(",")||null:void 0}];else if(wu(u))P=u;else{var F=Object.keys(B);P=a?F.sort(a):F}for(var R=0;R"u"?Or.allowDots:!!e.allowDots,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Or.charsetSentinel,delimiter:typeof e.delimiter>"u"?Or.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Or.encode,encoder:typeof e.encoder=="function"?e.encoder:Or.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Or.encodeValuesOnly,filter:s,format:n,formatter:i,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Or.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Or.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Or.strictNullHandling}};C7.exports=function(t,e){var r=t,n=the(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):wu(n.filter)&&(s=n.filter,i=s);var o=[];if(typeof r!="object"||r===null)return"";var u;e&&e.arrayFormat in S7?u=e.arrayFormat:e&&"indices"in e?u=e.indices?"indices":"repeat":u="indices";var a=S7[u];i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);for(var c=T7(),f=0;f0?A+w:""}});var D7=D((e2e,O7)=>{"use strict";h();var xl=K2(),Y2=Object.prototype.hasOwnProperty,rhe=Array.isArray,Ir={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:xl.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},nhe=function(t){return t.replace(/&#(\d+);/g,function(e,r){return String.fromCharCode(parseInt(r,10))})},x7=function(t,e){return t&&typeof t=="string"&&e.comma&&t.indexOf(",")>-1?t.split(","):t},ihe="utf8=%26%2310003%3B",she="utf8=%E2%9C%93",ohe=function(e,r){var n={},i=r.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=r.parameterLimit===1/0?void 0:r.parameterLimit,o=i.split(r.delimiter,s),u=-1,a,c=r.charset;if(r.charsetSentinel)for(a=0;a-1&&(T=rhe(T)?[T]:T),Y2.call(n,A)?n[A]=xl.combine(n[A],T):n[A]=T}return n},ahe=function(t,e,r,n){for(var i=n?e:x7(e,r),s=t.length-1;s>=0;--s){var o,u=t[s];if(u==="[]"&&r.parseArrays)o=[].concat(i);else{o=r.plainObjects?Object.create(null):{};var a=u.charAt(0)==="["&&u.charAt(u.length-1)==="]"?u.slice(1,-1):u,c=parseInt(a,10);!r.parseArrays&&a===""?o={0:i}:!isNaN(c)&&u!==a&&String(c)===a&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(o=[],o[c]=i):a!=="__proto__"&&(o[a]=i)}i=o}return i},uhe=function(e,r,n,i){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,u=/(\[[^[\]]*])/g,a=n.depth>0&&o.exec(s),c=a?s.slice(0,a.index):s,f=[];if(c){if(!n.plainObjects&&Y2.call(Object.prototype,c)&&!n.allowPrototypes)return;f.push(c)}for(var d=0;n.depth>0&&(a=u.exec(s))!==null&&d"u"?Ir.charset:e.charset;return{allowDots:typeof e.allowDots>"u"?Ir.allowDots:!!e.allowDots,allowPrototypes:typeof e.allowPrototypes=="boolean"?e.allowPrototypes:Ir.allowPrototypes,allowSparse:typeof e.allowSparse=="boolean"?e.allowSparse:Ir.allowSparse,arrayLimit:typeof e.arrayLimit=="number"?e.arrayLimit:Ir.arrayLimit,charset:r,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ir.charsetSentinel,comma:typeof e.comma=="boolean"?e.comma:Ir.comma,decoder:typeof e.decoder=="function"?e.decoder:Ir.decoder,delimiter:typeof e.delimiter=="string"||xl.isRegExp(e.delimiter)?e.delimiter:Ir.delimiter,depth:typeof e.depth=="number"||e.depth===!1?+e.depth:Ir.depth,ignoreQueryPrefix:e.ignoreQueryPrefix===!0,interpretNumericEntities:typeof e.interpretNumericEntities=="boolean"?e.interpretNumericEntities:Ir.interpretNumericEntities,parameterLimit:typeof e.parameterLimit=="number"?e.parameterLimit:Ir.parameterLimit,parseArrays:e.parseArrays!==!1,plainObjects:typeof e.plainObjects=="boolean"?e.plainObjects:Ir.plainObjects,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ir.strictNullHandling}};O7.exports=function(t,e){var r=che(e);if(t===""||t===null||typeof t>"u")return r.plainObjects?Object.create(null):{};for(var n=typeof t=="string"?ohe(t,r):t,i=r.plainObjects?Object.create(null):{},s=Object.keys(n),o=0;o{"use strict";h();var lhe=N7(),fhe=D7(),hhe=I1();P7.exports={formats:hhe,parse:fhe,stringify:lhe}});var J2=D(je=>{"use strict";h();Object.defineProperty(je,"__esModule",{value:!0});je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED=je.WALLET_PROVIDER_CALLBACK_PARAM=je.WALLET_PROVIDER_SIGN_MESSAGE_URL=je.WALLET_PROVIDER_GUARD_TRANSACTION_URL=je.WALLET_PROVIDER_SIGN_TRANSACTION_URL=je.WALLET_PROVIDER_SEND_TRANSACTION_URL=je.WALLET_PROVIDER_DISCONNECT_URL=je.WALLET_PROVIDER_CONNECT_URL=je.XALIAS_PROVIDER_TESTNET=je.XALIAS_PROVIDER_DEVNET=je.XALIAS_PROVIDER_MAINNET=je.WALLET_PROVIDER_TESTNET=je.WALLET_PROVIDER_DEVNET=je.WALLET_PROVIDER_MAINNET=void 0;je.WALLET_PROVIDER_MAINNET="https://wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_DEVNET="https://devnet-wallet.multiversx.com/dapp/init";je.WALLET_PROVIDER_TESTNET="https://testnet-wallet.multiversx.com/dapp/init";je.XALIAS_PROVIDER_MAINNET="https://xalias.com";je.XALIAS_PROVIDER_DEVNET="https://devnet.xalias.com";je.XALIAS_PROVIDER_TESTNET="https://testnet.xalias.com";je.WALLET_PROVIDER_CONNECT_URL="hook/login";je.WALLET_PROVIDER_DISCONNECT_URL="hook/logout";je.WALLET_PROVIDER_SEND_TRANSACTION_URL="hook/transaction";je.WALLET_PROVIDER_SIGN_TRANSACTION_URL="hook/sign";je.WALLET_PROVIDER_GUARD_TRANSACTION_URL="hook/2fa";je.WALLET_PROVIDER_SIGN_MESSAGE_URL="hook/sign-message";je.WALLET_PROVIDER_CALLBACK_PARAM="walletProviderStatus";je.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED="transactionsSigned"});var B7=D(Ol=>{"use strict";h();Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrCannotSignedMessage=Ol.ErrCannotGetSignedTransactions=void 0;var X2=class extends Error{constructor(){super("Cannot get signed transaction(s)")}};Ol.ErrCannotGetSignedTransactions=X2;var Z2=class extends Error{constructor(){super("Cannot get signed message")}};Ol.ErrCannotSignedMessage=Z2});var M7=D(T1=>{"use strict";h();Object.defineProperty(T1,"__esModule",{value:!0});T1.PlainSignedTransaction=void 0;var eC=class{constructor(e){this.nonce=0,this.value="",this.receiver="",this.sender="",this.gasPrice=0,this.gasLimit=0,this.data="",this.chainID="",this.version=0,this.signature="",Object.assign(this,e)}};T1.PlainSignedTransaction=eC});var Dl=D(na=>{"use strict";h();var ta=na&&na.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})},dhe=na&&na.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(na,"__esModule",{value:!0});na.WalletProvider=void 0;var tC=dhe(R7()),ra=J2(),rC=B7(),ghe=M7(),nC=class t{constructor(e){this.walletUrl=e}login(e){return ta(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ra.WALLET_PROVIDER_CONNECT_URL,callbackUrl:e?.callbackUrl,params:{token:e?.token}});return yield this.redirect(r,e?.redirectDelayMilliseconds),r})}redirect(e,r){return ta(this,void 0,void 0,function*(){r?yield this.redirectLater(e,r):this.redirectImmediately(e)})}redirectImmediately(e){window.location.href=e}redirectLater(e,r){return ta(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>{window.location.href=e,n(!0)},r)})})}logout(e){return ta(this,void 0,void 0,function*(){let r=this.buildWalletUrl({endpoint:ra.WALLET_PROVIDER_DISCONNECT_URL,callbackUrl:e?.callbackUrl});return yield this.redirect(r,e?.redirectDelayMilliseconds),!0})}signMessage(e,r){return ta(this,void 0,void 0,function*(){let n=this.buildWalletUrl({endpoint:ra.WALLET_PROVIDER_SIGN_MESSAGE_URL,callbackUrl:r?.callbackUrl,params:{message:e.message.toString()}});return yield this.redirect(n),n})}getMessageSignatureFromWalletUrl(){var e,r;let n=window.location.search.slice(1);console.info("getMessageSignatureFromWalletUrl(), url:",n);let i=tC.default.parse(n);if((((e=i.status)===null||e===void 0?void 0:e.toString())||"")!=="signed")throw new rC.ErrCannotSignedMessage;return((r=i.signature)===null||r===void 0?void 0:r.toString())||""}guardTransactions(e,r){return ta(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ra.WALLET_PROVIDER_GUARD_TRANSACTION_URL,e,r)})}signTransactions(e,r){return ta(this,void 0,void 0,function*(){this.redirectTransactionsToEndpoint(ra.WALLET_PROVIDER_SIGN_TRANSACTION_URL,e,r)})}signTransaction(e,r){return ta(this,void 0,void 0,function*(){yield this.signTransactions([e],r)})}getTransactionsFromWalletUrl(e=window.location.search){let r=tC.default.parse(e.slice(1));return t.isTxSignReturnSuccess(r)?this.getTxSignReturnValue(r):[]}static isTxSignReturnSuccess(e){return e.hasOwnProperty(ra.WALLET_PROVIDER_CALLBACK_PARAM)&&e[ra.WALLET_PROVIDER_CALLBACK_PARAM]===ra.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED}getTxSignReturnValue(e){console.info("getTxSignReturnValue(), urlParams:",e);let r=["nonce","value","receiver","sender","gasPrice","gasLimit","chainID","version","signature"];for(let s of r)if(!e[s]||!Array.isArray(e[s]))throw new rC.ErrCannotGetSignedTransactions;let n=e.nonce.length;for(let s of r)if(e[s].length!==n)throw new rC.ErrCannotGetSignedTransactions;let i=[];for(let s=0;s{let u=t.prepareWalletTransaction(o);for(let a in u)u.hasOwnProperty(a)&&!i.hasOwnProperty(a)&&(i[a]=[]),i[a].push(u[a])});let s=this.buildWalletUrl({endpoint:e,callbackUrl:n?.callbackUrl,params:i});window.location.href=s}};na.WalletProvider=nC});var p9=D((h2e,g9)=>{"use strict";h();function K7(t,e){return function(){return t.apply(e,arguments)}}var{toString:phe}=Object.prototype,{getPrototypeOf:pC}=Object,x1=(t=>e=>{let r=phe.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Is=t=>(t=t.toLowerCase(),e=>x1(e)===t),O1=t=>e=>typeof e===t,{isArray:Ml}=Array,wd=O1("undefined");function mhe(t){return t!==null&&!wd(t)&&t.constructor!==null&&!wd(t.constructor)&&ei(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var W7=Is("ArrayBuffer");function yhe(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&W7(t.buffer),e}var whe=O1("string"),ei=O1("function"),$7=O1("number"),D1=t=>t!==null&&typeof t=="object",vhe=t=>t===!0||t===!1,_1=t=>{if(x1(t)!=="object")return!1;let e=pC(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Ahe=Is("Date"),Ehe=Is("File"),bhe=Is("Blob"),She=Is("FileList"),Ihe=t=>D1(t)&&ei(t.pipe),The=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ei(t.append)&&((e=x1(t))==="formdata"||e==="object"&&ei(t.toString)&&t.toString()==="[object FormData]"))},_he=Is("URLSearchParams"),Che=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function vd(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Ml(t))for(n=0,i=t.length;n0;)if(i=r[n],e===i.toLowerCase())return i;return null}var J7=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,X7=t=>!wd(t)&&t!==J7;function uC(){let{caseless:t}=X7(this)&&this||{},e={},r=(n,i)=>{let s=t&&Y7(e,i)||i;_1(e[s])&&_1(n)?e[s]=uC(e[s],n):_1(n)?e[s]=uC({},n):Ml(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n(vd(e,(i,s)=>{r&&ei(i)?t[s]=K7(i,r):t[s]=i},{allOwnKeys:n}),t),xhe=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ohe=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},Dhe=(t,e,r,n)=>{let i,s,o,u={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!u[o]&&(e[o]=t[o],u[o]=!0);t=r!==!1&&pC(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},Phe=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},Rhe=t=>{if(!t)return null;if(Ml(t))return t;let e=t.length;if(!$7(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Bhe=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&pC(Uint8Array)),Mhe=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),i;for(;(i=n.next())&&!i.done;){let s=i.value;e.call(t,s[0],s[1])}},Lhe=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Fhe=Is("HTMLFormElement"),Uhe=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),L7=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),qhe=Is("RegExp"),Z7=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};vd(r,(i,s)=>{let o;(o=e(i,s,t))!==!1&&(n[s]=o||i)}),Object.defineProperties(t,n)},Vhe=t=>{Z7(t,(e,r)=>{if(ei(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(ei(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},khe=(t,e)=>{let r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Ml(t)?n(t):n(String(t).split(e)),r},Hhe=()=>{},Ghe=(t,e)=>(t=+t,Number.isFinite(t)?t:e),iC="abcdefghijklmnopqrstuvwxyz",F7="0123456789",e9={DIGIT:F7,ALPHA:iC,ALPHA_DIGIT:iC+iC.toUpperCase()+F7},jhe=(t=16,e=e9.ALPHA_DIGIT)=>{let r="",{length:n}=e;for(;t--;)r+=e[Math.random()*n|0];return r};function zhe(t){return!!(t&&ei(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var Qhe=t=>{let e=new Array(10),r=(n,i)=>{if(D1(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;let s=Ml(n)?[]:{};return vd(n,(o,u)=>{let a=r(o,i+1);!wd(a)&&(s[u]=a)}),e[i]=void 0,s}}return n};return r(t,0)},Khe=Is("AsyncFunction"),Whe=t=>t&&(D1(t)||ei(t))&&ei(t.then)&&ei(t.catch),re={isArray:Ml,isArrayBuffer:W7,isBuffer:mhe,isFormData:The,isArrayBufferView:yhe,isString:whe,isNumber:$7,isBoolean:vhe,isObject:D1,isPlainObject:_1,isUndefined:wd,isDate:Ahe,isFile:Ehe,isBlob:bhe,isRegExp:qhe,isFunction:ei,isStream:Ihe,isURLSearchParams:_he,isTypedArray:Bhe,isFileList:She,forEach:vd,merge:uC,extend:Nhe,trim:Che,stripBOM:xhe,inherits:Ohe,toFlatObject:Dhe,kindOf:x1,kindOfTest:Is,endsWith:Phe,toArray:Rhe,forEachEntry:Mhe,matchAll:Lhe,isHTMLForm:Fhe,hasOwnProperty:L7,hasOwnProp:L7,reduceDescriptors:Z7,freezeMethods:Vhe,toObjectSet:khe,toCamelCase:Uhe,noop:Hhe,toFiniteNumber:Ghe,findKey:Y7,global:J7,isContextDefined:X7,ALPHABET:e9,generateString:jhe,isSpecCompliantForm:zhe,toJSONObject:Qhe,isAsyncFn:Khe,isThenable:Whe};function Le(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}re.inherits(Le,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:re.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var t9=Le.prototype,r9={};["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(t=>{r9[t]={value:t}});Object.defineProperties(Le,r9);Object.defineProperty(t9,"isAxiosError",{value:!0});Le.from=(t,e,r,n,i,s)=>{let o=Object.create(t9);return re.toFlatObject(t,o,function(a){return a!==Error.prototype},u=>u!=="isAxiosError"),Le.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var $he=null;function cC(t){return re.isPlainObject(t)||re.isArray(t)}function n9(t){return re.endsWith(t,"[]")?t.slice(0,-2):t}function U7(t,e,r){return t?t.concat(e).map(function(i,s){return i=n9(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function Yhe(t){return re.isArray(t)&&!t.some(cC)}var Jhe=re.toFlatObject(re,{},null,function(e){return/^is[A-Z]/.test(e)});function P1(t,e,r){if(!re.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=re.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,B){return!re.isUndefined(B[x])});let n=r.metaTokens,i=r.visitor||f,s=r.dots,o=r.indexes,a=(r.Blob||typeof Blob<"u"&&Blob)&&re.isSpecCompliantForm(e);if(!re.isFunction(i))throw new TypeError("visitor must be a function");function c(T){if(T===null)return"";if(re.isDate(T))return T.toISOString();if(!a&&re.isBlob(T))throw new Le("Blob is not supported. Use a Buffer instead.");return re.isArrayBuffer(T)||re.isTypedArray(T)?a&&typeof Blob=="function"?new Blob([T]):p.Buffer.from(T):T}function f(T,x,B){let V=T;if(T&&!B&&typeof T=="object"){if(re.endsWith(x,"{}"))x=n?x:x.slice(0,-2),T=JSON.stringify(T);else if(re.isArray(T)&&Yhe(T)||(re.isFileList(T)||re.endsWith(x,"[]"))&&(V=re.toArray(T)))return x=n9(x),V.forEach(function(Q,L){!(re.isUndefined(Q)||Q===null)&&e.append(o===!0?U7([x],L,s):o===null?x:x+"[]",c(Q))}),!1}return cC(T)?!0:(e.append(U7(B,x,s),c(T)),!1)}let d=[],w=Object.assign(Jhe,{defaultVisitor:f,convertValue:c,isVisitable:cC});function A(T,x){if(!re.isUndefined(T)){if(d.indexOf(T)!==-1)throw Error("Circular reference detected in "+x.join("."));d.push(T),re.forEach(T,function(V,U){(!(re.isUndefined(V)||V===null)&&i.call(e,V,re.isString(U)?U.trim():U,x,w))===!0&&A(V,x?x.concat(U):[U])}),d.pop()}}if(!re.isObject(t))throw new TypeError("data must be an object");return A(t),e}function q7(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function mC(t,e){this._pairs=[],t&&P1(t,this,e)}var i9=mC.prototype;i9.append=function(e,r){this._pairs.push([e,r])};i9.toString=function(e){let r=e?function(n){return e.call(this,n,q7)}:q7;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Xhe(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function s9(t,e,r){if(!e)return t;let n=r&&r.encode||Xhe,i=r&&r.serialize,s;if(i?s=i(e,r):s=re.isURLSearchParams(e)?e.toString():new mC(e,r).toString(n),s){let o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}var lC=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){re.forEach(this.handlers,function(n){n!==null&&e(n)})}},V7=lC,o9={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zhe=typeof URLSearchParams<"u"?URLSearchParams:mC,ede=typeof FormData<"u"?FormData:null,tde=typeof Blob<"u"?Blob:null,rde={isBrowser:!0,classes:{URLSearchParams:Zhe,FormData:ede,Blob:tde},protocols:["http","https","file","blob","url","data"]},a9=typeof window<"u"&&typeof document<"u",nde=(t=>a9&&["ReactNative","NativeScript","NS"].indexOf(t)<0)(typeof navigator<"u"&&navigator.product),ide=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sde=Object.freeze({__proto__:null,hasBrowserEnv:a9,hasStandardBrowserWebWorkerEnv:ide,hasStandardBrowserEnv:nde}),Ss={...sde,...rde};function ode(t,e){return P1(t,new Ss.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return Ss.isNode&&re.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function ade(t){return re.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function ude(t){let e={},r=Object.keys(t),n,i=r.length,s;for(n=0;n=r.length;return o=!o&&re.isArray(i)?i.length:o,a?(re.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!u):((!i[o]||!re.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&re.isArray(i[o])&&(i[o]=ude(i[o])),!u)}if(re.isFormData(t)&&re.isFunction(t.entries)){let r={};return re.forEachEntry(t,(n,i)=>{e(ade(n),i,r,0)}),r}return null}function cde(t,e,r){if(re.isString(t))try{return(e||JSON.parse)(t),re.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var yC={transitional:o9,adapter:["xhr","http"],transformRequest:[function(e,r){let n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=re.isObject(e);if(s&&re.isHTMLForm(e)&&(e=new FormData(e)),re.isFormData(e))return i?JSON.stringify(u9(e)):e;if(re.isArrayBuffer(e)||re.isBuffer(e)||re.isStream(e)||re.isFile(e)||re.isBlob(e))return e;if(re.isArrayBufferView(e))return e.buffer;if(re.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let u;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return ode(e,this.formSerializer).toString();if((u=re.isFileList(e))||n.indexOf("multipart/form-data")>-1){let a=this.env&&this.env.FormData;return P1(u?{"files[]":e}:e,a&&new a,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),cde(e)):e}],transformResponse:[function(e){let r=this.transitional||yC.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&re.isString(e)&&(n&&!this.responseType||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(u){if(o)throw u.name==="SyntaxError"?Le.from(u,Le.ERR_BAD_RESPONSE,this,null,this.response):u}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ss.classes.FormData,Blob:Ss.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};re.forEach(["delete","get","head","post","put","patch"],t=>{yC.headers[t]={}});var wC=yC,lde=re.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"]),fde=t=>{let e={},r,n,i;return t&&t.split(` +`).forEach(function(o){i=o.indexOf(":"),r=o.substring(0,i).trim().toLowerCase(),n=o.substring(i+1).trim(),!(!r||e[r]&&lde[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},k7=Symbol("internals");function yd(t){return t&&String(t).trim().toLowerCase()}function C1(t){return t===!1||t==null?t:re.isArray(t)?t.map(C1):String(t)}function hde(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var dde=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function sC(t,e,r,n,i){if(re.isFunction(n))return n.call(this,e,r);if(i&&(e=r),!!re.isString(e)){if(re.isString(n))return e.indexOf(n)!==-1;if(re.isRegExp(n))return n.test(e)}}function gde(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function pde(t,e){let r=re.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(i,s,o){return this[n].call(this,e,i,s,o)},configurable:!0})})}var Pl=class{constructor(e){e&&this.set(e)}set(e,r,n){let i=this;function s(u,a,c){let f=yd(a);if(!f)throw new Error("header name must be a non-empty string");let d=re.findKey(i,f);(!d||i[d]===void 0||c===!0||c===void 0&&i[d]!==!1)&&(i[d||a]=C1(u))}let o=(u,a)=>re.forEach(u,(c,f)=>s(c,f,a));return re.isPlainObject(e)||e instanceof this.constructor?o(e,r):re.isString(e)&&(e=e.trim())&&!dde(e)?o(fde(e),r):e!=null&&s(r,e,n),this}get(e,r){if(e=yd(e),e){let n=re.findKey(this,e);if(n){let i=this[n];if(!r)return i;if(r===!0)return hde(i);if(re.isFunction(r))return r.call(this,i,n);if(re.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=yd(e),e){let n=re.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||sC(this,this[n],n,r)))}return!1}delete(e,r){let n=this,i=!1;function s(o){if(o=yd(o),o){let u=re.findKey(n,o);u&&(!r||sC(n,n[u],u,r))&&(delete n[u],i=!0)}}return re.isArray(e)?e.forEach(s):s(e),i}clear(e){let r=Object.keys(this),n=r.length,i=!1;for(;n--;){let s=r[n];(!e||sC(this,this[s],s,e,!0))&&(delete this[s],i=!0)}return i}normalize(e){let r=this,n={};return re.forEach(this,(i,s)=>{let o=re.findKey(n,s);if(o){r[o]=C1(i),delete r[s];return}let u=e?gde(s):String(s).trim();u!==s&&delete r[s],r[u]=C1(i),n[u]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return re.forEach(this,(n,i)=>{n!=null&&n!==!1&&(r[i]=e&&re.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){let n=(this[k7]=this[k7]={accessors:{}}).accessors,i=this.prototype;function s(o){let u=yd(o);n[u]||(pde(i,o),n[u]=!0)}return re.isArray(e)?e.forEach(s):s(e),this}};Pl.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);re.reduceDescriptors(Pl.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});re.freezeMethods(Pl);var ro=Pl;function oC(t,e){let r=this||wC,n=e||r,i=ro.from(n.headers),s=n.data;return re.forEach(t,function(u){s=u.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function c9(t){return!!(t&&t.__CANCEL__)}function Ad(t,e,r){Le.call(this,t??"canceled",Le.ERR_CANCELED,e,r),this.name="CanceledError"}re.inherits(Ad,Le,{__CANCEL__:!0});function mde(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new Le("Request failed with status code "+r.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}var yde=Ss.hasStandardBrowserEnv?{write(t,e,r,n,i,s){let o=[t+"="+encodeURIComponent(e)];re.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),re.isString(n)&&o.push("path="+n),re.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function wde(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function vde(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function l9(t,e){return t&&!wde(e)?vde(t,e):e}var Ade=Ss.hasStandardBrowserEnv?function(){let e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){let u=re.isString(o)?i(o):o;return u.protocol===n.protocol&&u.host===n.host}}():function(){return function(){return!0}}();function Ede(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function bde(t,e){t=t||10;let r=new Array(t),n=new Array(t),i=0,s=0,o;return e=e!==void 0?e:1e3,function(a){let c=Date.now(),f=n[s];o||(o=c),r[i]=a,n[i]=c;let d=s,w=0;for(;d!==i;)w+=r[d++],d=d%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o{let s=i.loaded,o=i.lengthComputable?i.total:void 0,u=s-r,a=n(u),c=s<=o;r=s;let f={loaded:s,total:o,progress:o?s/o:void 0,bytes:u,rate:a||void 0,estimated:a&&o&&c?(o-s)/a:void 0,event:i};f[e?"download":"upload"]=!0,t(f)}}var Sde=typeof XMLHttpRequest<"u",Ide=Sde&&function(t){return new Promise(function(r,n){let i=t.data,s=ro.from(t.headers).normalize(),{responseType:o,withXSRFToken:u}=t,a;function c(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}let f;if(re.isFormData(i)){if(Ss.hasStandardBrowserEnv||Ss.hasStandardBrowserWebWorkerEnv)s.setContentType(!1);else if((f=s.getContentType())!==!1){let[x,...B]=f?f.split(";").map(V=>V.trim()).filter(Boolean):[];s.setContentType([x||"multipart/form-data",...B].join("; "))}}let d=new XMLHttpRequest;if(t.auth){let x=t.auth.username||"",B=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(x+":"+B))}let w=l9(t.baseURL,t.url);d.open(t.method.toUpperCase(),s9(w,t.params,t.paramsSerializer),!0),d.timeout=t.timeout;function A(){if(!d)return;let x=ro.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),V={data:!o||o==="text"||o==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:x,config:t,request:d};mde(function(Q){r(Q),c()},function(Q){n(Q),c()},V),d=null}if("onloadend"in d?d.onloadend=A:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(A)},d.onabort=function(){d&&(n(new Le("Request aborted",Le.ECONNABORTED,t,d)),d=null)},d.onerror=function(){n(new Le("Network Error",Le.ERR_NETWORK,t,d)),d=null},d.ontimeout=function(){let B=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",V=t.transitional||o9;t.timeoutErrorMessage&&(B=t.timeoutErrorMessage),n(new Le(B,V.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,t,d)),d=null},Ss.hasStandardBrowserEnv&&(u&&re.isFunction(u)&&(u=u(t)),u||u!==!1&&Ade(w))){let x=t.xsrfHeaderName&&t.xsrfCookieName&&yde.read(t.xsrfCookieName);x&&s.set(t.xsrfHeaderName,x)}i===void 0&&s.setContentType(null),"setRequestHeader"in d&&re.forEach(s.toJSON(),function(B,V){d.setRequestHeader(V,B)}),re.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),o&&o!=="json"&&(d.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&d.addEventListener("progress",H7(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",H7(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=x=>{d&&(n(!x||x.type?new Ad(null,t,d):x),d.abort(),d=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));let T=Ede(w);if(T&&Ss.protocols.indexOf(T)===-1){n(new Le("Unsupported protocol "+T+":",Le.ERR_BAD_REQUEST,t));return}d.send(i||null)})},fC={http:$he,xhr:Ide};re.forEach(fC,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var G7=t=>`- ${t}`,Tde=t=>re.isFunction(t)||t===null||t===!1,f9={getAdapter:t=>{t=re.isArray(t)?t:[t];let{length:e}=t,r,n,i={};for(let s=0;s`adapter ${u} `+(a===!1?"is not supported by the environment":"is not available in the build")),o=e?s.length>1?`since : +`+s.map(G7).join(` +`):" "+G7(s[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return n},adapters:fC};function aC(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Ad(null,t)}function j7(t){return aC(t),t.headers=ro.from(t.headers),t.data=oC.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),f9.getAdapter(t.adapter||wC.adapter)(t).then(function(n){return aC(t),n.data=oC.call(t,t.transformResponse,n),n.headers=ro.from(n.headers),n},function(n){return c9(n)||(aC(t),n&&n.response&&(n.response.data=oC.call(t,t.transformResponse,n.response),n.response.headers=ro.from(n.response.headers))),Promise.reject(n)})}var z7=t=>t instanceof ro?{...t}:t;function Rl(t,e){e=e||{};let r={};function n(c,f,d){return re.isPlainObject(c)&&re.isPlainObject(f)?re.merge.call({caseless:d},c,f):re.isPlainObject(f)?re.merge({},f):re.isArray(f)?f.slice():f}function i(c,f,d){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c,d)}else return n(c,f,d)}function s(c,f){if(!re.isUndefined(f))return n(void 0,f)}function o(c,f){if(re.isUndefined(f)){if(!re.isUndefined(c))return n(void 0,c)}else return n(void 0,f)}function u(c,f,d){if(d in e)return n(c,f);if(d in t)return n(void 0,c)}let 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:u,headers:(c,f)=>i(z7(c),z7(f),!0)};return re.forEach(Object.keys(Object.assign({},t,e)),function(f){let d=a[f]||i,w=d(t[f],e[f],f);re.isUndefined(w)&&d!==u||(r[f]=w)}),r}var h9="1.6.8",vC={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{vC[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var Q7={};vC.transitional=function(e,r,n){function i(s,o){return"[Axios v"+h9+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,u)=>{if(e===!1)throw new Le(i(o," has been removed"+(r?" in "+r:"")),Le.ERR_DEPRECATED);return r&&!Q7[o]&&(Q7[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,u):!0}};function _de(t,e,r){if(typeof t!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),i=n.length;for(;i-- >0;){let s=n[i],o=e[s];if(o){let u=t[s],a=u===void 0||o(u,s,t);if(a!==!0)throw new Le("option "+s+" must be "+a,Le.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}var hC={assertOptions:_de,validators:vC},ia=hC.validators,Bl=class{constructor(e){this.defaults=e,this.interceptors={request:new V7,response:new V7}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let i;Error.captureStackTrace?Error.captureStackTrace(i={}):i=new Error;let s=i.stack?i.stack.replace(/^.+\n/,""):"";n.stack?s&&!String(n.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(n.stack+=` +`+s):n.stack=s}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Rl(this.defaults,r);let{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&hC.assertOptions(n,{silentJSONParsing:ia.transitional(ia.boolean),forcedJSONParsing:ia.transitional(ia.boolean),clarifyTimeoutError:ia.transitional(ia.boolean)},!1),i!=null&&(re.isFunction(i)?r.paramsSerializer={serialize:i}:hC.assertOptions(i,{encode:ia.function,serialize:ia.function},!0)),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=s&&re.merge(s.common,s[r.method]);s&&re.forEach(["delete","get","head","post","put","patch","common"],T=>{delete s[T]}),r.headers=ro.concat(o,s);let u=[],a=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(r)===!1||(a=a&&x.synchronous,u.unshift(x.fulfilled,x.rejected))});let c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let f,d=0,w;if(!a){let T=[j7.bind(this),void 0];for(T.unshift.apply(T,u),T.push.apply(T,c),w=T.length,f=Promise.resolve(r);d{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s,o=new Promise(u=>{n.subscribe(u),s=u}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,u){n.reason||(n.reason=new Ad(s,o,u),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},Cde=dC;function Nde(t){return function(r){return t.apply(null,r)}}function xde(t){return re.isObject(t)&&t.isAxiosError===!0}var gC={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(gC).forEach(([t,e])=>{gC[e]=t});var Ode=gC;function d9(t){let e=new N1(t),r=K7(N1.prototype.request,e);return re.extend(r,N1.prototype,e,{allOwnKeys:!0}),re.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return d9(Rl(t,i))},r}var cr=d9(wC);cr.Axios=N1;cr.CanceledError=Ad;cr.CancelToken=Cde;cr.isCancel=c9;cr.VERSION=h9;cr.toFormData=P1;cr.AxiosError=Le;cr.Cancel=cr.CanceledError;cr.all=function(e){return Promise.all(e)};cr.spread=Nde;cr.isAxiosError=xde;cr.mergeConfig=Rl;cr.AxiosHeaders=ro;cr.formToJSON=t=>u9(re.isHTMLForm(t)?new FormData(t):t);cr.getAdapter=f9.getAdapter;cr.HttpStatusCode=Ode;cr.default=cr;g9.exports=cr});var m9=D(R1=>{"use strict";h();Object.defineProperty(R1,"__esModule",{value:!0});R1.NativeAuthClientConfig=void 0;var AC=class{constructor(){this.origin=typeof window<"u"&&typeof window.location<"u"?window.location.hostname:"",this.apiUrl="https://api.multiversx.com",this.expirySeconds=60*60*24}};R1.NativeAuthClientConfig=AC});var bC=D(Ll=>{"use strict";h();var vu=Ll&&Ll.__awaiter||function(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function u(f){try{c(n.next(f))}catch(d){o(d)}}function a(f){try{c(n.throw(f))}catch(d){o(d)}}function c(f){f.done?s(f.value):i(f.value).then(u,a)}c((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ll,"__esModule",{value:!0});Ll.NativeAuthClient=void 0;var Dde=p9(),Pde=m9(),EC=class{constructor(e){this.config=Object.assign(new Pde.NativeAuthClientConfig,e)}getToken(e,r,n){let i=this.encodeValue(e),s=this.encodeValue(r);return`${i}.${s}.${n}`}initialize(e={}){return vu(this,void 0,void 0,function*(){let r=yield this.getCurrentBlockHash(),n=this.encodeValue(JSON.stringify(e));return`${this.encodeValue(this.config.origin)}.${r}.${this.config.expirySeconds}.${n}`})}getCurrentBlockHash(){return vu(this,void 0,void 0,function*(){return this.config.gatewayUrl?yield this.getCurrentBlockHashWithGateway():yield this.getCurrentBlockHashWithApi()})}getCurrentBlockHashWithGateway(){return vu(this,void 0,void 0,function*(){let e=yield this.getCurrentRound(),r=`${this.config.gatewayUrl}/blocks/by-round/${e}`;return(yield this.get(r)).data.data.blocks.filter(o=>o.shard===this.config.blockHashShard)[0].hash})}getCurrentRound(){return vu(this,void 0,void 0,function*(){if(!this.config.gatewayUrl)throw new Error("Gateway URL not set");if(!this.config.blockHashShard)throw new Error("Blockhash shard not set");let e=`${this.config.gatewayUrl}/network/status/${this.config.blockHashShard}`;return(yield this.get(e)).data.data.status.erd_current_round})}getCurrentBlockHashWithApi(){return vu(this,void 0,void 0,function*(){try{let e=`${this.config.apiUrl}/blocks/latest?ttl=${this.config.expirySeconds}&fields=hash`,r=yield this.get(e);if(r.data[0].hash!==void 0)return r.data[0].hash}catch{}return this.getCurrentBlockHashWithApiFallback()})}getCurrentBlockHashWithApiFallback(){return vu(this,void 0,void 0,function*(){let e=`${this.config.apiUrl}/blocks?size=1&fields=hash`;return this.config.blockHashShard!==void 0&&(e+=`&shard=${this.config.blockHashShard}`),(yield this.get(e)).data[0].hash})}encodeValue(e){return this.escape(p.Buffer.from(e,"utf8").toString("base64"))}escape(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}get(e){return vu(this,void 0,void 0,function*(){return yield Dde.default.get(e,{headers:this.config.extraRequestHeaders})})}};Ll.NativeAuthClient=EC});var A9=D(M1=>{"use strict";h();Object.defineProperty(M1,"__esModule",{value:!0});M1.TransactionStatus=void 0;var IC=class t{constructor(e){this.status=(e||"").toLowerCase()}static createUnknown(){return new t("unknown")}isPending(){return this.status=="received"||this.status=="pending"}isExecuted(){return this.isSuccessful()||this.isFailed()||this.isInvalid()}isSuccessful(){return this.status=="executed"||this.status=="success"||this.status=="successful"}isFailed(){return this.status=="fail"||this.status=="failed"||this.status=="unsuccessful"||this.isInvalid()}isInvalid(){return this.status=="invalid"}toString(){return this.status}valueOf(){return this.status}equals(e){return e?this.status==e.status:!1}};M1.TransactionStatus=IC});var b9=D(L1=>{"use strict";h();Object.defineProperty(L1,"__esModule",{value:!0});L1.TransactionReceipt=void 0;var E9=_c(),TC=class t{constructor(){this.value="",this.sender=new E9.Address(""),this.data="",this.hash=""}static fromHttpResponse(e){let r=new t;return r.value=(e.value||0).toString(),r.sender=new E9.Address(e.sender),r.data=e.data,r.hash=e.txHash,r}};L1.TransactionReceipt=TC});var S9=D(Ts=>{"use strict";h();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.ErrContractQuery=Ts.ErrNetworkProvider=Ts.ErrUnexpectedCondition=Ts.Err=void 0;var Ul=class extends Error{constructor(e,r){super(e),this.inner=void 0,this.inner=r}};Ts.Err=Ul;var _C=class extends Ul{constructor(e){super(`Unexpected condition: [${e}]`)}};Ts.ErrUnexpectedCondition=_C;var CC=class extends Ul{constructor(e,r,n){let i=`Request error on url [${e}]: [${r}]`;super(i,n)}};Ts.ErrNetworkProvider=CC;var NC=class extends Ul{constructor(e){super(e.message.replace("executeQuery:",""))}};Ts.ErrContractQuery=NC});var T9=D(sa=>{"use strict";h();Object.defineProperty(sa,"__esModule",{value:!0});sa.TransactionEventTopic=sa.TransactionEventData=sa.TransactionEvent=void 0;var I9=_c(),xC=class t{constructor(e){this.address=new I9.Address(""),this.identifier="",this.topics=[],this.data="",this.dataPayload=new ql(p.Buffer.from("","utf8")),this.additionalData=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new I9.Address(e.address),r.identifier=e.identifier||"",r.topics=(e.topics||[]).map(n=>new F1(n)),r.dataPayload=ql.fromBase64(e.data),r.additionalData=(e.additionalData||[]).map(ql.fromBase64),r.data=r.dataPayload.toString(),r}findFirstOrNoneTopic(e){return this.topics.filter(r=>e(r))[0]}getLastTopic(){return this.topics[this.topics.length-1]}};sa.TransactionEvent=xC;var ql=class t{constructor(e){this.raw=e}static fromBase64(e){return new t(p.Buffer.from(e||"","base64"))}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};sa.TransactionEventData=ql;var F1=class{constructor(e){this.raw=p.Buffer.from(e||"","base64")}toString(){return this.raw.toString("utf8")}hex(){return this.raw.toString("hex")}valueOf(){return this.raw}};sa.TransactionEventTopic=F1});var DC=D(U1=>{"use strict";h();Object.defineProperty(U1,"__esModule",{value:!0});U1.TransactionLogs=void 0;var Mde=S9(),_9=_c(),Lde=T9(),OC=class t{constructor(e){this.address=new _9.Address(""),this.events=[],Object.assign(this,e)}static fromHttpResponse(e){let r=new t;return r.address=new _9.Address(e.address),r.events=(e.events||[]).map(n=>Lde.TransactionEvent.fromHttpResponse(n)),r}findSingleOrNoneEvent(e,r){let n=this.findEvents(e,r);if(n.length>1)throw new Mde.ErrUnexpectedCondition(`more than one event of type ${e}`);return n[0]}findFirstOrNoneEvent(e,r){return this.findEvents(e,r)[0]}findEvents(e,r){let n=this.events.filter(i=>i.identifier==e);return r&&(n=n.filter(i=>r(i))),n}};U1.TransactionLogs=OC});var N9=D(Vl=>{"use strict";h();Object.defineProperty(Vl,"__esModule",{value:!0});Vl.ContractResultItem=Vl.ContractResults=void 0;var C9=DC(),q1=_c(),PC=class t{constructor(e){this.items=e,this.items.sort(function(r,n){return r.nonce.valueOf()-n.nonce.valueOf()})}static fromProxyHttpResponse(e){let r=e.map(n=>Ed.fromProxyHttpResponse(n));return new t(r)}static fromApiHttpResponse(e){let r=e.map(n=>Ed.fromApiHttpResponse(n));return new t(r)}};Vl.ContractResults=PC;var Ed=class t{constructor(e){this.hash="",this.nonce=0,this.value="",this.receiver=new q1.Address(""),this.sender=new q1.Address(""),this.data="",this.previousHash="",this.originalHash="",this.gasLimit=0,this.gasPrice=0,this.callType=0,this.returnMessage="",this.logs=new C9.TransactionLogs,Object.assign(this,e)}static fromProxyHttpResponse(e){return t.fromHttpResponse(e)}static fromApiHttpResponse(e){let r=t.fromHttpResponse(e);return r.data=p.Buffer.from(r.data,"base64").toString(),r.callType=Number(r.callType),r}static fromHttpResponse(e){let r=new t;return r.hash=e.hash,r.nonce=Number(e.nonce||0),r.value=(e.value||0).toString(),r.receiver=new q1.Address(e.receiver),r.sender=new q1.Address(e.sender),r.previousHash=e.prevTxHash,r.originalHash=e.originalTxHash,r.gasLimit=Number(e.gasLimit||0),r.gasPrice=Number(e.gasPrice||0),r.data=e.data||"",r.callType=e.callType,r.returnMessage=e.returnMessage,r.logs=C9.TransactionLogs.fromHttpResponse(e.logs||{}),r}};Vl.ContractResultItem=Ed});var x9=D(V1=>{"use strict";h();Object.defineProperty(V1,"__esModule",{value:!0});V1.ContractQueryRequest=void 0;var RC=class{constructor(e){this.query=e}toHttpRequest(){var e;let r={},n=this.query;return r.scAddress=n.address.bech32(),r.caller=!((e=n.caller)===null||e===void 0)&&e.bech32()?n.caller.bech32():void 0,r.funcName=n.func.toString(),r.value=n.value?n.value.toString():void 0,r.args=n.getEncodedArguments(),r}};V1.ContractQueryRequest=RC});var k9=D((pCe,V9)=>{h();V9.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var oa=D(Eu=>{h();var BC,Fde=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Eu.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Eu.getSymbolTotalCodewords=function(e){return Fde[e]};Eu.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Eu.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');BC=e};Eu.isKanjiModeEnabled=function(){return typeof BC<"u"};Eu.toSJIS=function(e){return BC(e)}});var j1=D(ti=>{h();ti.L={bit:1};ti.M={bit:0};ti.Q={bit:3};ti.H={bit:2};function Ude(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ti.L;case"m":case"medium":return ti.M;case"q":case"quartile":return ti.Q;case"h":case"high":return ti.H;default:throw new Error("Unknown EC Level: "+t)}}ti.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ti.from=function(e,r){if(ti.isValid(e))return e;try{return Ude(e)}catch{return r}}});var j9=D((ECe,G9)=>{h();function H9(){this.buffer=[],this.length=0}H9.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};G9.exports=H9});var Q9=D((SCe,z9)=>{h();function bd(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}bd.prototype.set=function(t,e,r,n){let i=t*this.size+e;this.data[i]=r,n&&(this.reservedBit[i]=!0)};bd.prototype.get=function(t,e){return this.data[t*this.size+e]};bd.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};bd.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};z9.exports=bd});var K9=D(z1=>{h();var qde=oa().getSymbolSize;z1.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=qde(e),i=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let o=1;o{h();var Vde=oa().getSymbolSize,W9=7;$9.getPositions=function(e){let r=Vde(e);return[[0,0],[r-W9,0],[0,r-W9]]}});var J9=D(Rt=>{h();Rt.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bu={N1:3,N2:3,N3:40,N4:10};Rt.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Rt.from=function(e){return Rt.isValid(e)?parseInt(e,10):void 0};Rt.getPenaltyN1=function(e){let r=e.size,n=0,i=0,s=0,o=null,u=null;for(let a=0;a=5&&(n+=bu.N1+(i-5)),o=f,i=1),f=e.get(c,a),f===u?s++:(s>=5&&(n+=bu.N1+(s-5)),u=f,s=1)}i>=5&&(n+=bu.N1+(i-5)),s>=5&&(n+=bu.N1+(s-5))}return n};Rt.getPenaltyN2=function(e){let r=e.size,n=0;for(let i=0;i=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(u,o),u>=10&&(s===1488||s===93)&&n++}return n*bu.N3};Rt.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let s=0;s{h();var aa=j1(),Q1=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],K1=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];MC.getBlocksCount=function(e,r){switch(r){case aa.L:return Q1[(e-1)*4+0];case aa.M:return Q1[(e-1)*4+1];case aa.Q:return Q1[(e-1)*4+2];case aa.H:return Q1[(e-1)*4+3];default:return}};MC.getTotalCodewordsCount=function(e,r){switch(r){case aa.L:return K1[(e-1)*4+0];case aa.M:return K1[(e-1)*4+1];case aa.Q:return K1[(e-1)*4+2];case aa.H:return K1[(e-1)*4+3];default:return}}});var X9=D($1=>{h();var Sd=new Uint8Array(512),W1=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Sd[r]=e,W1[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Sd[r]=Sd[r-255]})();$1.log=function(e){if(e<1)throw new Error("log("+e+")");return W1[e]};$1.exp=function(e){return Sd[e]};$1.mul=function(e,r){return e===0||r===0?0:Sd[W1[e]+W1[r]]}});var Z9=D(Id=>{h();var FC=X9();Id.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let i=0;i=0;){let i=n[0];for(let o=0;o{h();var eV=Z9();function UC(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}UC.prototype.initialize=function(e){this.degree=e,this.genPoly=eV.generateECPolynomial(this.degree)};UC.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=eV.mod(r,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};tV.exports=UC});var qC=D(nV=>{h();nV.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var VC=D(no=>{h();var iV="[0-9]+",Hde="[A-Z $%*+\\-./:]+",Td="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Td=Td.replace(/u/g,"\\u");var Gde="(?:(?![A-Z0-9 $%*+\\-./:]|"+Td+`)(?:.|[\r +]))+`;no.KANJI=new RegExp(Td,"g");no.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");no.BYTE=new RegExp(Gde,"g");no.NUMERIC=new RegExp(iV,"g");no.ALPHANUMERIC=new RegExp(Hde,"g");var jde=new RegExp("^"+Td+"$"),zde=new RegExp("^"+iV+"$"),Qde=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");no.testKanji=function(e){return jde.test(e)};no.testNumeric=function(e){return zde.test(e)};no.testAlphanumeric=function(e){return Qde.test(e)}});var ua=D(lr=>{h();var Kde=qC(),kC=VC();lr.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};lr.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};lr.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};lr.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};lr.MIXED={bit:-1};lr.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Kde.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};lr.getBestModeForData=function(e){return kC.testNumeric(e)?lr.NUMERIC:kC.testAlphanumeric(e)?lr.ALPHANUMERIC:kC.testKanji(e)?lr.KANJI:lr.BYTE};lr.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};lr.isValid=function(e){return e&&e.bit&&e.ccBits};function Wde(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return lr.NUMERIC;case"alphanumeric":return lr.ALPHANUMERIC;case"kanji":return lr.KANJI;case"byte":return lr.BYTE;default:throw new Error("Unknown mode: "+t)}}lr.from=function(e,r){if(lr.isValid(e))return e;try{return Wde(e)}catch{return r}}});var cV=D(Su=>{h();var Y1=oa(),$de=LC(),sV=j1(),ca=ua(),HC=qC(),aV=7973,oV=Y1.getBCHDigit(aV);function Yde(t,e,r){for(let n=1;n<=40;n++)if(e<=Su.getCapacity(n,r,t))return n}function uV(t,e){return ca.getCharCountIndicator(t,e)+4}function Jde(t,e){let r=0;return t.forEach(function(n){let i=uV(n.mode,e);r+=i+n.getBitsLength()}),r}function Xde(t,e){for(let r=1;r<=40;r++)if(Jde(t,r)<=Su.getCapacity(r,e,ca.MIXED))return r}Su.from=function(e,r){return HC.isValid(e)?parseInt(e,10):r};Su.getCapacity=function(e,r,n){if(!HC.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=ca.BYTE);let i=Y1.getSymbolTotalCodewords(e),s=$de.getTotalCodewordsCount(e,r),o=(i-s)*8;if(n===ca.MIXED)return o;let u=o-uV(n,e);switch(n){case ca.NUMERIC:return Math.floor(u/10*3);case ca.ALPHANUMERIC:return Math.floor(u/11*2);case ca.KANJI:return Math.floor(u/13);case ca.BYTE:default:return Math.floor(u/8)}};Su.getBestVersionForData=function(e,r){let n,i=sV.from(r,sV.M);if(Array.isArray(e)){if(e.length>1)return Xde(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Yde(n.mode,n.getLength(),i)};Su.getEncodedBits=function(e){if(!HC.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Y1.getBCHDigit(r)-oV>=0;)r^=aV<{h();var GC=oa(),fV=1335,Zde=21522,lV=GC.getBCHDigit(fV);hV.getEncodedBits=function(e,r){let n=e.bit<<3|r,i=n<<10;for(;GC.getBCHDigit(i)-lV>=0;)i^=fV<{h();var ege=ua();function Hl(t){this.mode=ege.NUMERIC,this.data=t.toString()}Hl.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Hl.prototype.getLength=function(){return this.data.length};Hl.prototype.getBitsLength=function(){return Hl.getBitsLength(this.data.length)};Hl.prototype.write=function(e){let r,n,i;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),i=parseInt(n,10),e.put(i,s*3+1))};gV.exports=Hl});var yV=D((JCe,mV)=>{h();var tge=ua(),jC=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Gl(t){this.mode=tge.ALPHANUMERIC,this.data=t}Gl.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Gl.prototype.getLength=function(){return this.data.length};Gl.prototype.getBitsLength=function(){return Gl.getBitsLength(this.data.length)};Gl.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=jC.indexOf(this.data[r])*45;n+=jC.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(jC.indexOf(this.data[r]),6)};mV.exports=Gl});var vV=D((ZCe,wV)=>{"use strict";h();wV.exports=function(e){for(var r=[],n=e.length,i=0;i=55296&&s<=56319&&n>i+1){var o=e.charCodeAt(i+1);o>=56320&&o<=57343&&(s=(s-55296)*1024+o-56320+65536,i+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var EV=D((t3e,AV)=>{h();var rge=vV(),nge=ua();function jl(t){this.mode=nge.BYTE,typeof t=="string"&&(t=rge(t)),this.data=new Uint8Array(t)}jl.getBitsLength=function(e){return e*8};jl.prototype.getLength=function(){return this.data.length};jl.prototype.getBitsLength=function(){return jl.getBitsLength(this.data.length)};jl.prototype.write=function(t){for(let e=0,r=this.data.length;e{h();var ige=ua(),sge=oa();function zl(t){this.mode=ige.KANJI,this.data=t}zl.getBitsLength=function(e){return e*13};zl.prototype.getLength=function(){return this.data.length};zl.prototype.getBitsLength=function(){return zl.getBitsLength(this.data.length)};zl.prototype.write=function(t){let e;for(e=0;e=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+` +Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};bV.exports=zl});var IV=D((s3e,zC)=>{"use strict";h();var _d={single_source_shortest_paths:function(t,e,r){var n={},i={};i[e]=0;var s=_d.PriorityQueue.make();s.push(e,0);for(var o,u,a,c,f,d,w,A,T;!s.empty();){o=s.pop(),u=o.value,c=o.cost,f=t[u]||{};for(a in f)f.hasOwnProperty(a)&&(d=f[a],w=c+d,A=i[a],T=typeof i[a]>"u",(T||A>w)&&(i[a]=w,s.push(a,w),n[a]=u))}if(typeof r<"u"&&typeof i[r]>"u"){var x=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(x)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,i;n;)r.push(n),i=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=_d.single_source_shortest_paths(t,e,r);return _d.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=_d.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof zC<"u"&&(zC.exports=_d)});var PV=D(Ql=>{h();var ze=ua(),CV=pV(),NV=yV(),xV=EV(),OV=SV(),Cd=VC(),J1=oa(),oge=IV();function TV(t){return unescape(encodeURIComponent(t)).length}function Nd(t,e,r){let n=[],i;for(;(i=t.exec(r))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function DV(t){let e=Nd(Cd.NUMERIC,ze.NUMERIC,t),r=Nd(Cd.ALPHANUMERIC,ze.ALPHANUMERIC,t),n,i;return J1.isKanjiModeEnabled()?(n=Nd(Cd.BYTE,ze.BYTE,t),i=Nd(Cd.KANJI,ze.KANJI,t)):(n=Nd(Cd.BYTE_KANJI,ze.BYTE,t),i=[]),e.concat(r,n,i).sort(function(o,u){return o.index-u.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function QC(t,e){switch(e){case ze.NUMERIC:return CV.getBitsLength(t);case ze.ALPHANUMERIC:return NV.getBitsLength(t);case ze.KANJI:return OV.getBitsLength(t);case ze.BYTE:return xV.getBitsLength(t)}}function age(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function uge(t){let e=[];for(let r=0;r{h();var Z1=oa(),KC=j1(),lge=j9(),fge=Q9(),hge=K9(),dge=Y9(),YC=J9(),JC=LC(),gge=rV(),X1=cV(),pge=dV(),mge=ua(),WC=PV();function yge(t,e){let r=t.size,n=dge.getPositions(e);for(let i=0;i=0&&u<=6&&(a===0||a===6)||a>=0&&a<=6&&(u===0||u===6)||u>=2&&u<=4&&a>=2&&a<=4?t.set(s+u,o+a,!0,!0):t.set(s+u,o+a,!1,!0))}}function wge(t){let e=t.size;for(let r=8;r>u&1)===1,t.set(i,s,o,!0),t.set(s,i,o,!0)}function $C(t,e,r){let n=t.size,i=pge.getEncodedBits(e,r),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(n-15+s,8,o,!0),s<8?t.set(8,n-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(n-8,8,1,!0)}function Ege(t,e){let r=t.size,n=-1,i=r-1,s=7,o=0;for(let u=r-1;u>0;u-=2)for(u===6&&u--;;){for(let a=0;a<2;a++)if(!t.isReserved(i,u-a)){let c=!1;o>>s&1)===1),t.set(i,u-a,c),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||r<=i){i-=n,n=-n;break}}}function bge(t,e,r){let n=new lge;r.forEach(function(a){n.put(a.mode.bit,4),n.put(a.getLength(),mge.getCharCountIndicator(a.mode,t)),a.write(n)});let i=Z1.getSymbolTotalCodewords(t),s=JC.getTotalCodewordsCount(t,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let u=(o-n.getLengthInBits())/8;for(let a=0;a=7&&ege(a,e),tge(a,o),isNaN(n)&&(n=JC.getBestMask(a,YC.bind(null,a,r))),JC.applyMask(n,a),YC(a,r,n),{modules:a,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}wV.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=WC.M,i,s;return typeof r<"u"&&(n=WC.from(r.errorCorrectionLevel,WC.M),i=J1.from(r.version),s=JC.from(r.maskPattern),r.toSJISFunc&&X1.setToSJISFunction(r.toSJISFunc)),ige(e,i,n,s)}});var ZC=B(Iu=>{h();function AV(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Iu.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:AV(e.color.dark||"#000000ff"),light:AV(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Iu.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Iu.getImageWidth=function(e,r){let n=Iu.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Iu.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Iu.getScale(i,n),u=Math.floor((i+n.margin*2)*o),a=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=a&&d>=a&&f{h();var e3=ZC();function sge(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function oge(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Z1.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=oge()),i=e3.getOptions(i);let o=e3.getImageWidth(e.modules.size,i),u=s.getContext("2d"),a=u.createImageData(o,o);return e3.qrToImageData(a.data,e,i),sge(u,s,o),u.putImageData(a,0,0),s};Z1.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=Z1.render(e,r,i),o=i.type||"image/png",u=i.rendererOpts||{};return s.toDataURL(o,u.quality)}});var IV=B(SV=>{h();var age=ZC();function bV(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function t3(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function uge(t,e,r){let n="",i=0,s=!1,o=0;for(let u=0;u0&&a>0&&t[u-1]||(n+=s?t3("M",a+r,.5+c+r):t3("m",i,0),i=0,s=!1),a+1':"",c="',f='viewBox="0 0 '+u+" "+u+'"',w=''+a+c+` -`;return typeof n=="function"&&n(null,w),w}});var _V=B(Dd=>{h();var cge=_9(),r3=vV(),TV=EV(),lge=IV();function n3(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,u=typeof s[o-1]=="function";if(!u&&!cge())throw new Error("Callback required as last argument");if(u){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(a,c){try{let f=r3.create(r,n);a(t(f,e,n))}catch(f){c(f)}})}try{let a=r3.create(r,n);i(null,t(a,e,n))}catch(a){i(a)}}Dd.create=r3.create;Dd.toCanvas=n3.bind(null,TV.render);Dd.toDataURL=n3.bind(null,TV.renderToDataURL);Dd.toString=n3.bind(null,function(t,e,r){return lge.render(t,r)})});var FV=B(fa=>{"use strict";h();var Ege=fa&&fa.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LV=fa&&fa.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ege(e,t,r)};Object.defineProperty(fa,"__esModule",{value:!0});LV(Dl(),fa);LV(X2(),fa)});h();var d3=pe(Ca(),1),g3=pe(_b(),1),fw=pe(d0(),1),p3=pe(Db(),1),_ge=pe(Ve(),1),Cge=pe(Ic(),1),Nge=pe(Xr(),1),xge=pe(N0(),1),sk=pe(Bb(),1),Oge=pe(V0(),1),Dge=pe(H0(),1),ok=pe(po(),1),_s=pe(Mf(),1),ak=pe(yf(),1),uk=pe(Yu(),1),Pge=pe(CE(),1),Rge=pe(jb(),1);h();h();var U8=pe(Kb(),1);h();h();var G0="elvenjs_state",M8="https://devnet-api.multiversx.com";var Po="/dapp/init",j0="devnet",L8="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",F8=["wss://relay.walletconnect.com"],Rr={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var me={get(t){let e=localStorage.getItem(G0);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem(G0,JSON.stringify(r))},clear(){localStorage.removeItem(G0)}};var z0=async()=>{let t=U8.ExtensionProvider.getInstance();try{let e=await t.init(),r=me.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var c3=pe(Kb(),1),l3=pe(fd(),1),f3=pe(Dl(),1),ik=pe(SC(),1),lw=pe(H0(),1);h();var n9=pe(fd(),1);h();h();var ge=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};h();var r9=(U=>(U.onLoginStart="onLoginStart",U.onLoginSuccess="onLoginSuccess",U.onLoginFailure="onLoginFailure",U.onLogoutStart="onLogoutStart",U.onLogoutSuccess="onLogoutSuccess",U.onLogoutFailure="onLogoutFailure",U.onQrPending="onQrPending",U.onQrLoaded="onQrLoaded",U.onTxStart="onTxStart",U.onTxSent="onTxSent",U.onTxFinalized="onTxFinalized",U.onTxFailure="onTxFailure",U.onSignMsgStart="onSignMsgStart",U.onSignMsgFinalized="onSignMsgFinalized",U.onSignMsgFailure="onSignMsgFailure",U.onQueryStart="onQueryStart",U.onQueryFinalized="onQueryFinalized",U.onQueryFailure="onQueryFailure",U))(r9||{}),IC=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(IC||{}),dde=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(dde||{}),gde=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(gde||{});h();var Kt=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Fl=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");ge.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(me.clear(),ge.run("onLogoutSuccess")),e}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to logout the user: ${r}`),ge.run("onLogoutFailure",r)}};h();function R1(t){return t[Math.floor(Math.random()*t.length)]}var i9=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Fl(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=R1(t.initOptions.walletConnectV2RelayAddresses),n=new n9.WalletConnectV2Provider(e,Rr[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};h();var V1=pe(Ve(),1),p9=pe(s9(),1),m9=pe(a9(),1),y9=pe(PC(),1),w9=pe(d9(),1),v9=pe(jb(),1),A9=pe(g9(),1),E9=pe(Wf(),1);var k1=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||j0,this.apiUrl=e||Rr[this.chainType]?.apiAddress,this.apiTimeout=n||Rr[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),u=await o.json();if(!o.ok){let a=u?.error||o.status;return clearTimeout(i),Promise.reject(a)}return clearTimeout(i),u}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let u=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),a=await u.json();if(!u.ok){let c=a?.error||u.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),a}catch(u){this.handleApiError(u,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new V1.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new p9.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new V1.Address(r.sender),receiver:new V1.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:p.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:m9.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:y9.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:w9.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new E9.Query({address:e,func:r,args:n,value:i,caller:s}),u=new A9.ContractQueryRequest(o).toHttpRequest(),a=await this.apiPost("query",u);return v9.ContractQueryResponse.fromHttpResponse(a)}catch(o){this.handleApiError(o,"query")}}};h();h();var kl=()=>new Date().setHours(new Date().getHours()+24),H1=t=>Date.now()>t;h();var b9=pe(Ve(),1),S9=pe(Ic(),1);var Au=async t=>{let e=me.get("address"),r=me.get("expires");if(!(r&&H1(r))&&e&&t.networkProvider){let i=new b9.Address(e),s=new S9.Account(i);try{let o=await t.networkProvider.getAccount(i),u=await t.networkProvider.getGuardianData(i);me.set("address",e),me.set("activeGuardian",u.guarded&&u.activeGuardian?.address?u.activeGuardian.address:""),me.set("nonce",o.nonce.valueOf()),me.set("balance",o.balance.toString()),s.update(o)}catch(o){let u=Kt(o);console.warn(`Something went wrong trying to synchronize the user account: ${u}`)}}};var I9=async(t,e,r,n="/")=>{let i=await z0(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(a){let c=Kt(a);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:u}=i.account;if(me.set("loginToken",e),u&&me.set("signature",u),t.networkProvider&&u)try{let a=await i.getAddress();if(!a)throw new Error("Canceled!");me.set("address",a),me.set("loginMethod","browser-extension"),me.set("expires",kl()),await Au(t);let c=r.getToken(a,e,u);return me.set("accessToken",c),ge.run("onLoginSuccess"),i}catch(a){throw new Error(`Something went wrong trying to synchronize the user account: ${a?.message}`)}};h();h();var CV=pe(_V(),1),NV=pe(fd(),1);var fge=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},hge=t=>{let e=`${L8}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},dge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},gge=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},i3={},pge=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",i3[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:i3[t.topic].signal}),r},ew={},mge=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=pge(t,e);return n.appendChild(s),ew[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:ew[t.topic].signal}),n},yge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},wge=t=>{if(!t)return;document.getElementById(t)?.remove()},vge=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),Age=async t=>t?await CV.default.toString(t,{type:"svg"}):void 0,xV=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await Age(e),o;if(s&&(o=fge(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),vge()&&i.appendChild(hge(e))),i&&r instanceof NV.WalletConnectV2Provider){let u=r.pairings,a=async f=>{try{f&&(await r.logout({topic:f}),wge(f))}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to remove the existing pairing: ${w}`)}finally{ew[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(yge()),await r.login({approval:d,token:n})}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to login the user: ${w}`)}finally{for(let d of Object.values(ew))d?.abort();for(let d of Object.values(i3))d?.abort()}};if(u&&u.length>0){let f=dge();i.appendChild(f);let d=gge();f.appendChild(d);for(let w of u){let A=mge(w,a,c);f.appendChild(A)}}}return i};var tw=pe(fd(),1);var OV=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=R1(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof tw.WalletConnectV2Provider){let a=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();me.set("address",a),me.set("loginMethod","mobile"),me.set("expires",kl()),await Au(t),c&&me.set("signature",c),me.set("loginToken",e);let f=r.getToken(a,e,c);me.set("accessToken",f),ge.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof tw.WalletConnectV2Provider&&await Fl(t)},onClientEvent:a=>{console.log("wc2 session event: ",a)}},u=new tw.WalletConnectV2Provider(o,Rr[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(u){t.dappProvider=u,ge.run("onQrPending"),await u.init();let{uri:a,approval:c}=await u.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${a}&token=${e}`:a;return n&&f&&(s=await xV(n,f,u,e),ge.run("onQrLoaded")),await u.login({approval:c,token:e}),u}}catch(a){let c=Kt(a);console.warn(`Something went wrong trying to login the user: ${c}`),ge.run("onLoginFailure",c)}};h();var DV=pe(Dl(),1);var s3=async(t,e,r,n)=>{let i=new DV.WalletProvider(`${t}${Po}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return me.set("loginMethod",Rr[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),me.set("expires",kl()),me.set("loginToken",e),i}catch(u){let a=Kt(u);console.warn(`Something went wrong trying to login the user: ${a}`),me.set("loginMethod",""),ge.run("onLoginFailure",a)}};h();var ln=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};h();var PV=pe(Dl(),1);var RV=pe(SC(),1),o3=async(t,e)=>{let r=ln("signature"),n=ln("address"),i=me.get("address"),s=me.get("loginToken");if(r&&me.set("signature",r),n||i){n&&(me.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new PV.WalletProvider(`${t}${Po}`);if(r&&e&&n){let a=new RV.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);me.set("accessToken",a)}return o}};h();var BV=pe(Ic(),1),MV=pe(V0(),1);var rw=async(t,e)=>{ge.run("onTxSent",t);let n=await new MV.TransactionWatcher(e).awaitCompleted(t),i=n.sender,s=new BV.Account(i),o=await e.getAccount(i);s.update(o),me.set("address",s.address.bech32()),me.set("balance",s.balance.toString()),ge.run("onTxFinalized",n)};h();var Kl=pe(FV(),1),qV=pe(Xr(),1);h();var UV=pe(Ic(),1);var nw=t=>{let e=t.getSender(),r=new UV.Account(e),n=t.nonce.valueOf();r.incrementNonce(),me.set("nonce",(n+1n).toString())};var VV=async(t,e,r,n)=>{if(ln(Kl.WALLET_PROVIDER_CALLBACK_PARAM)===Kl.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=me.get("activeGuardian"),o=me.get("loginMethod"),u=ln("hasWebWalletGuardianSign"),a;if("getTransactionsFromWalletUrl"in t){if(a=t.getTransactionsFromWalletUrl()?.[0],!a)return;o==="web-wallet"&&(a.data=p.Buffer.from(a.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&u&&(a=new Kl.WalletProvider(`${r}${Po}`).getTransactionsFromWalletUrl()?.[0]);if(a){let c=qV.Transaction.fromPlainObject(a);c.nonce=BigInt(n),nw(c);try{ge.run("onTxStart",c),await e.sendTransaction(c),await rw(c,e)}catch(f){let w=`Getting transaction information failed! ${Kt(f)}`;throw ge.run("onTxFailure",c,w),new Error(w)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};h();var iw=pe($l(),1),kV=pe(Ve(),1),HV=pe(Dl(),1);var GV=t=>{let e=me.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(iw.TransactionVersion.withTxOptions()),t.setOptions(iw.TransactionOptions.withOptions(r)),t.setGuardian(kV.Address.fromBech32(e))}return t},jV=async(t,e)=>{let r=new HV.WalletProvider(`${e}${Po}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},zV=t=>{let e=me.get("activeGuardian");return!(!me.get("address")||!e||t.isGuardedTransaction())};h();var QV=()=>{let t=!ln("walletProviderStatus"),e=ln("status")==="signed",r=ln("message"),n=ln("signature");t&&e&&r&&n&&(ge.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};h();var u3=pe(Xr(),1);h();var KV=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(KV||{}),WV=(u=>(u.handshakeResponse="HANDSHAKE_RESPONSE",u.loginResponse="LOGIN_RESPONSE",u.disconnectResponse="DISCONNECT_RESPONSE",u.cancelResponse="CANCEL_RESPONSE",u.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",u.signMessageResponse="SIGN_MESSAGE_RESPONSE",u.noneResponse="NONE_RESPONSE",u))(WV||{}),a3={...WV,...KV},$V=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))($V||{}),YV=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(YV||{}),Tu={...YV,...$V};h();var JV=typeof window<"u"?window:{},XV=()=>JV.ReactNativeWebView?"reactNative":JV.webkit?"ios":"web",_u=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",sw=t=>Object.prototype.toString.call(t)==="[object String]";h();var ow={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,_u()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t}),_u())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t}),_u())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:Tu.logoutRequest}),_u())}};var aw=XV(),uw="message",ZV=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=_u()&&aw!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(uw,e),window&&window.addEventListener(uw,e)},ha=class{constructor(){}async logout(){return ow.logout[aw](),new Promise(e=>{e(!0)})}async signMessage(e){try{return ow.signMessage[aw](e),await new Promise((n,i)=>{window.signMessageResponse=(o,u)=>{if(u){i(u),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:u,type:a}=o;if(a===a3.signMessageResponse&&u!=null){let{signedMessage:c,error:f}=u;f?i(f):n(c)}document?.removeEventListener(uw,s)}ZV(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return ow.signTransactions[aw](r),await new Promise((i,s)=>{window.transactionsSigned=(u,a)=>{if(u=JSON.parse(u),a){s(a),window.transactionsSigned=null;return}i(u.map(c=>u3.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(u){let{message:a,type:c}=u;if(c===a3.signTransactionsResponse){let{transactions:f,error:d}=a;try{d?s(d):i(f.map(w=>u3.Transaction.fromPlainObject(w)))}catch{s("Unable to sign")}}document&&document.removeEventListener(uw,o)}ZV(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};h();h();h();function Sge(t){try{let e=atob(t),r=btoa(e),n=p.Buffer.from(t,"base64").toString(),i=p.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Wl(t){return Sge(t)?atob(t):t}h();var ek=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Wl(s)),u=Wl(r);return{ttl:Number(i),extraInfo:o,origin:u,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var tk=t=>{if(!t||!sw(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Wl(r),o=Wl(n),u=ek(o);if(!u)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let a={...u,address:s,body:o,signature:i};return u.extraInfo?.timestamp||delete a.extraInfo,a}catch{return null}};function rk(t,e){let r=tk(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(me.set("loginToken",s),me.set("accessToken",t),me.set("signature",n),me.set("address",i),me.set("loginMethod","x-portal-hub"),e.dappProvider=new ha)}h();var nk=t=>{t.onLoginStart&&ge.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&ge.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&ge.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&ge.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&ge.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&ge.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&ge.set("onQrPending",t.onQrPending),t.onQrLoaded&&ge.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&ge.set("onTxStart",t.onTxStart),t.onTxSent&&ge.set("onTxSent",t.onTxSent),t.onTxFinalized&&ge.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&ge.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&ge.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&ge.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&ge.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&ge.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&ge.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&ge.set("onQueryFailure",t.onQueryFailure)};h();var cw=async t=>{ge.run("onLoginStart");try{await t(()=>{ge.run("onLoginSuccess")})}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to login the user: ${r}`),ge.run("onLoginFailure",r)}};var h3=class{static async init(e){let r=me.get();if(r.expires&&H1(r.expires)){me.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:j0,apiUrl:M8,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:F8,...e},this.networkProvider=new k1(this.initOptions),nk(this.initOptions);let n=ln("accessToken");n&&await cw(async s=>{rk(n,this),await Au(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&ln("address"))&&r?.loginMethod&&(await cw(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await z0()),r.loginMethod==="mobile"&&(this.dappProvider=await i9(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new ha),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await o3(Rr[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Au(this),s()}),this.initOptions?.chainType&&(await VV(this.dappProvider,this.networkProvider,Rr[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),QV()))}static async login(e,r){if(!Object.values(IC).includes(e)){let i="Wrong login method!";throw ge.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw ge.run("onLoginFailure",i),new Error(i)}await cw(async()=>{let i=new ik.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await I9(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await OV(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await s3(Rr[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Fl(this);return this.dappProvider=void 0,e}catch(e){let r=Kt(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw ge.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw ge.run("onTxFailure",e,n),new Error(n)}let r=GV(e);try{ge.run("onTxStart",e);let n=me.get();if(e.nonce=n.nonce,this.dappProvider instanceof c3.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof l3.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof ha&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof f3.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=zV(r);if(i||nw(r),i&&this.initOptions?.chainType){await jV(r,Rr[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await rw(r,this.networkProvider)}}catch(n){let i=Kt(n);throw ge.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(ge.run("onSignMsgStart",e),this.dappProvider instanceof c3.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof l3.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof ha&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof f3.WalletProvider){let s=u=>encodeURIComponent(u).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new lw.SignableMessage({message:p.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=me.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&ge.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Kt(i);throw ge.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{ge.run("onQueryStart",o);let u=await this.networkProvider.queryContract(o);return ge.run("onQueryFinalized",u),u}catch(u){let a=Kt(u);throw ge.run("onQueryFinalized",o,a),new Error(`Smart contract query failed! ${a}`)}}static{this.storage=me}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,ge.clear()}}};h();rr();Ou.config({ROUNDING_MODE:Ou.ROUND_FLOOR});var Ige=({amount:t,decimals:e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return BigInt(new Ou(t).shiftedBy(e).toFixed())},Tge=({amount:t,decimals:e,rounding:r=e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return new Ou(t).shiftedBy(-e).decimalPlaces(r).toFixed()};var export_Account=Cge.Account;var export_Address=_ge.Address;var export_AddressType=uk.AddressType;var export_AddressValue=uk.AddressValue;var export_BigUIntType=_s.BigUIntType;var export_BigUIntValue=_s.BigUIntValue;var export_BooleanType=ak.BooleanType;var export_BooleanValue=ak.BooleanValue;var export_BytesType=ok.BytesType;var export_BytesValue=ok.BytesValue;var export_ContractQueryResponse=Rge.ContractQueryResponse;var export_Message=sk.Message;var export_MessageComputer=sk.MessageComputer;var export_QueryArguments=Pge.QueryArguments;var export_SignableMessage=Dge.SignableMessage;var export_SmartContractTransactionsFactory=fw.SmartContractTransactionsFactory;var export_SmartContractTransactionsOutcomeParser=p3.SmartContractTransactionsOutcomeParser;var export_Token=d3.Token;var export_TokenComputer=d3.TokenComputer;var export_TokenManagementTransactionsFactory=fw.TokenManagementTransactionsFactory;var export_TokenManagementTransactionsOutcomeParser=p3.TokenManagementTransactionsOutcomeParser;var export_TokenOperationsFactory=g3.TokenOperationsFactory;var export_TokenOperationsFactoryConfig=g3.TokenOperationsFactoryConfig;var export_TokenOperationsOutcomeParser=g3.TokenOperationsOutcomeParser;var export_TokenTransfer=d3.TokenTransfer;var export_Transaction=Nge.Transaction;var export_TransactionComputer=xge.TransactionComputer;var export_TransactionEventsParser=p3.TransactionEventsParser;var export_TransactionWatcher=Oge.TransactionWatcher;var export_TransactionsFactoryConfig=fw.TransactionsFactoryConfig;var export_TransferTransactionsFactory=fw.TransferTransactionsFactory;var export_U16Type=_s.U16Type;var export_U16Value=_s.U16Value;var export_U32Type=_s.U32Type;var export_U32Value=_s.U32Value;var export_U64Type=_s.U64Type;var export_U64Value=_s.U64Value;var export_U8Type=_s.U8Type;var export_U8Value=_s.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractQueryResponse as ContractQueryResponse,dde as DappCoreWCV2CustomMethodsEnum,h3 as ElvenJS,r9 as EventStoreEvents,IC as LoginMethodsEnum,export_Message as Message,export_MessageComputer as MessageComputer,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContractTransactionsFactory as SmartContractTransactionsFactory,export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser,export_Token as Token,export_TokenComputer as TokenComputer,export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory,export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser,export_TokenOperationsFactory as TokenOperationsFactory,export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig,export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionComputer as TransactionComputer,export_TransactionEventsParser as TransactionEventsParser,export_TransactionWatcher as TransactionWatcher,export_TransactionsFactoryConfig as TransactionsFactoryConfig,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,gde as WebWalletUrlParamsEnum,Tge as formatAmount,Ige as parseAmount}; +`);let o=bge(e,r,i),u=Z1.getSymbolSize(e),a=new fge(u);return yge(a,e),wge(a),vge(a,e),$C(a,r,0),e>=7&&Age(a,e),Ege(a,o),isNaN(n)&&(n=YC.getBestMask(a,$C.bind(null,a,r))),YC.applyMask(n,a),$C(a,r,n),{modules:a,version:e,errorCorrectionLevel:r,maskPattern:n,segments:i}}RV.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=KC.M,i,s;return typeof r<"u"&&(n=KC.from(r.errorCorrectionLevel,KC.M),i=X1.from(r.version),s=YC.from(r.maskPattern),r.toSJISFunc&&Z1.setToSJISFunction(r.toSJISFunc)),Ige(e,i,n,s)}});var XC=D(Iu=>{h();function MV(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}Iu.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:r,color:{dark:MV(e.color.dark||"#000000ff"),light:MV(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Iu.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};Iu.getImageWidth=function(e,r){let n=Iu.getScale(e,r);return Math.floor((e+r.margin*2)*n)};Iu.qrToImageData=function(e,r,n){let i=r.modules.size,s=r.modules.data,o=Iu.getScale(i,n),u=Math.floor((i+n.margin*2)*o),a=n.margin*o,c=[n.color.light,n.color.dark];for(let f=0;f=a&&d>=a&&f{h();var ZC=XC();function Tge(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function _ge(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}ew.render=function(e,r,n){let i=n,s=r;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),r||(s=_ge()),i=ZC.getOptions(i);let o=ZC.getImageWidth(e.modules.size,i),u=s.getContext("2d"),a=u.createImageData(o,o);return ZC.qrToImageData(a.data,e,i),Tge(u,s,o),u.putImageData(a,0,0),s};ew.renderToDataURL=function(e,r,n){let i=n;typeof i>"u"&&(!r||!r.getContext)&&(i=r,r=void 0),i||(i={});let s=ew.render(e,r,i),o=i.type||"image/png",u=i.rendererOpts||{};return s.toDataURL(o,u.quality)}});var qV=D(UV=>{h();var Cge=XC();function FV(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function e3(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function Nge(t,e,r){let n="",i=0,s=!1,o=0;for(let u=0;u0&&a>0&&t[u-1]||(n+=s?e3("M",a+r,.5+c+r):e3("m",i,0),i=0,s=!1),a+1':"",c="',f='viewBox="0 0 '+u+" "+u+'"',w=''+a+c+` +`;return typeof n=="function"&&n(null,w),w}});var kV=D(xd=>{h();var xge=k9(),t3=BV(),VV=LV(),Oge=qV();function r3(t,e,r,n,i){let s=[].slice.call(arguments,1),o=s.length,u=typeof s[o-1]=="function";if(!u&&!xge())throw new Error("Callback required as last argument");if(u){if(o<2)throw new Error("Too few arguments provided");o===2?(i=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(a,c){try{let f=t3.create(r,n);a(t(f,e,n))}catch(f){c(f)}})}try{let a=t3.create(r,n);i(null,t(a,e,n))}catch(a){i(a)}}xd.create=t3.create;xd.toCanvas=r3.bind(null,VV.render);xd.toDataURL=r3.bind(null,VV.renderToDataURL);xd.toString=r3.bind(null,function(t,e,r){return Oge.render(t,r)})});var XV=D(la=>{"use strict";h();var kge=la&&la.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r),Object.defineProperty(t,n,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),JV=la&&la.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&kge(e,t,r)};Object.defineProperty(la,"__esModule",{value:!0});JV(Dl(),la);JV(J2(),la)});h();var h3=pe(_a(),1),d3=pe(Cb(),1),hw=pe(f0(),1),g3=pe(Pb(),1),Qge=pe(Ve(),1),Kge=pe(Ic(),1),Wge=pe(Xr(),1),$ge=pe(_0(),1),Ak=pe(Mb(),1),Yge=pe(U0(),1),Jge=pe(V0(),1),Ek=pe(po(),1),_s=pe(Mf(),1),bk=pe(yf(),1),Sk=pe(Yu(),1),Xge=pe(NE(),1),Zge=pe(zb(),1);h();h();var F8=pe(Wb(),1);h();h();var k0="elvenjs_state",B8="https://devnet-api.multiversx.com";var Po="/dapp/init",H0="devnet",M8="https://maiar.page.link/?apn=com.elrond.maiar.wallet&isi=1519405832&ibi=com.elrond.maiar.wallet&link=https://xportal.com/",L8=["wss://relay.walletconnect.com"],Rr={devnet:{id:"devnet",shortId:"D",name:"Devnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://devnet-wallet.multiversx.com",xAliasAddress:"https://devnet.xalias.com",apiAddress:"https://devnet-api.multiversx.com",explorerAddress:"https://devnet-explorer.multiversx.com",apiTimeout:1e4},testnet:{id:"testnet",shortId:"T",name:"Testnet",egldLabel:"xEGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://testnet-wallet.multiversx.com",xAliasAddress:"https://testnet.xalias.com",apiAddress:"https://testnet-api.multiversx.com",explorerAddress:"https://testnet-explorer.multiversx.com",apiTimeout:1e4},mainnet:{id:"mainnet",shortId:"1",name:"Mainnet",egldLabel:"EGLD",egldDenomination:"18",decimals:"4",gasPerDataByte:"1500",walletAddress:"https://wallet.multiversx.com",xAliasAddress:"https://xalias.com",apiAddress:"https://api.multiversx.com",explorerAddress:"https://explorer.multiversx.com",apiTimeout:1e4}};var me={get(t){let e=localStorage.getItem(k0);if(!e)return{};let r=JSON.parse(e);return t?r[t]:r},set(t,e){let r=this.get();r[t]=e,localStorage.setItem(k0,JSON.stringify(r))},clear(){localStorage.removeItem(k0)}};var G0=async()=>{let t=F8.ExtensionProvider.getInstance();try{let e=await t.init(),r=me.get();if(r?.address&&t.setAddress(r.address),!e){console.warn("Something went wrong when trying to initialize the ExtensionProvider..");return}return t}catch{console.warn("Can't initialize the Dapp Provider!")}};var u3=pe(Wb(),1),c3=pe(fd(),1),l3=pe(Dl(),1),vk=pe(bC(),1),fw=pe(V0(),1);h();var w9=pe(fd(),1);h();h();var ge=class{static set(e,r){if(!e)return;let n={...this.events,[e]:r};this.events=n}static get(e){if(!(!e||!this.events))return this.events[e]}static run(e,...r){!e||!this.events||this.events[e]?.(...r)}static clear(){this.events=void 0}};h();var y9=(U=>(U.onLoginStart="onLoginStart",U.onLoginSuccess="onLoginSuccess",U.onLoginFailure="onLoginFailure",U.onLogoutStart="onLogoutStart",U.onLogoutSuccess="onLogoutSuccess",U.onLogoutFailure="onLogoutFailure",U.onQrPending="onQrPending",U.onQrLoaded="onQrLoaded",U.onTxStart="onTxStart",U.onTxSent="onTxSent",U.onTxFinalized="onTxFinalized",U.onTxFailure="onTxFailure",U.onSignMsgStart="onSignMsgStart",U.onSignMsgFinalized="onSignMsgFinalized",U.onSignMsgFailure="onSignMsgFailure",U.onQueryStart="onQueryStart",U.onQueryFinalized="onQueryFinalized",U.onQueryFailure="onQueryFailure",U))(y9||{}),SC=(o=>(o.ledger="ledger",o.mobile="mobile",o.webWallet="web-wallet",o.browserExtension="browser-extension",o.xAlias="x-alias",o.xPortalHub="x-portal-hub",o))(SC||{}),Rde=(r=>(r.mvx_cancelAction="mvx_cancelAction",r.mvx_signNativeAuthToken="mvx_signNativeAuthToken",r))(Rde||{}),Bde=(e=>(e.hasWebWalletGuardianSign="hasWebWalletGuardianSign",e))(Bde||{});h();var Kt=t=>typeof t=="string"?t.toUpperCase():t instanceof Error?t.message:JSON.stringify(t);var Fl=async t=>{if(!t.dappProvider)throw new Error("Logout failed: There is no active session!");ge.run("onLogoutStart");try{let e=await t.dappProvider.logout();return e&&(me.clear(),ge.run("onLogoutSuccess")),e}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to logout the user: ${r}`),ge.run("onLogoutFailure",r)}};h();function B1(t){return t[Math.floor(Math.random()*t.length)]}var v9=async t=>{if(!t.initOptions.walletConnectV2ProjectId||!t.initOptions.chainType)return;let e={onClientLogin:()=>{},onClientLogout:()=>Fl(t),onClientEvent:i=>{console.log("wc2 session event: ",i)}},r=B1(t.initOptions.walletConnectV2RelayAddresses),n=new w9.WalletConnectV2Provider(e,Rr[t.initOptions.chainType].shortId,r,t.initOptions.walletConnectV2ProjectId);try{return await n.init(),n}catch{console.warn("Can't initialize the Dapp Provider!")}};h();var k1=pe(Ve(),1),O9=pe(A9(),1),D9=pe(b9(),1),P9=pe(DC(),1),R9=pe(N9(),1),B9=pe(zb(),1),M9=pe(x9(),1),L9=pe(Wf(),1);var H1=class{constructor({apiUrl:e,chainType:r,apiTimeout:n}){this.chainType=r||H0,this.apiUrl=e||Rr[this.chainType]?.apiAddress,this.apiTimeout=n||Rr[this.chainType]?.apiTimeout}async apiGet(e,r){if(typeof fetch<"u"){let n=new AbortController,i=setTimeout(()=>n.abort(),this.apiTimeout),s={method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"},signal:n.signal};try{let o=await fetch(this.apiUrl+"/"+e,Object.assign(s,r||{})),u=await o.json();if(!o.ok){let a=u?.error||o.status;return clearTimeout(i),Promise.reject(a)}return clearTimeout(i),u}catch(o){this.handleApiError(o,e)}}}async apiPost(e,r,n){if(typeof fetch<"u"){let i=new AbortController,s=setTimeout(()=>i.abort(),this.apiTimeout),o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r||{}),signal:i.signal};try{let u=await fetch(this.apiUrl+"/"+e,Object.assign(o,n||{})),a=await u.json();if(!u.ok){let c=a?.error||u.status;return clearTimeout(s),Promise.reject(c)}return clearTimeout(s),a}catch(u){this.handleApiError(u,e)}}}handleApiError(e,r){if(!e.response)throw new Error(`Request error on url [${r}]: [${e.toString()}]`);let n=e.response.data,i=n.error||n.message||JSON.stringify(n);throw new Error(i)}async sendTransaction(e){return(await this.apiPost("transactions",e.toSendable())).txHash}async getAccount(e){let r=await this.apiGet(`accounts/${e.bech32()}`);return{address:new k1.Address(r?.address||""),nonce:Number(r?.nonce||0),balance:BigInt(r?.balance||0),code:r?.code||"",userName:r?.username||""}}async getGuardianData(e){let r=await this.apiGet(`address/${e.bech32()}/guardian-data`);return{guarded:r?.data?.guardianData?.guarded||!1,activeGuardian:r?.data?.guardianData?.activeGuardian,pendingGuardian:r?.data?.guardianData?.pendingGuardian}}async getTransaction(e){let r=await this.apiGet(`transactions/${e}`),n=new O9.TransactionStatus(r.status);return{hash:e,type:r.type||"",nonce:r.nonce||0,round:r.round,epoch:r.epoch||0,value:(r.value||0).toString(),sender:new k1.Address(r.sender),receiver:new k1.Address(r.receiver),gasPrice:r.gasPrice||0,gasLimit:r.gasLimit||0,data:p.Buffer.from(r.data||"","base64"),status:n,timestamp:r.timestamp||0,blockNonce:r.blockNonce||0,hyperblockNonce:r.hyperblockNonce||0,hyperblockHash:r.hyperblockHash||"",receipt:D9.TransactionReceipt.fromHttpResponse(r.receipt||{}),logs:P9.TransactionLogs.fromHttpResponse(r.logs||{}),contractResults:R9.ContractResults.fromApiHttpResponse(r.results||[]),isCompleted:!n.isPending()}}async queryContract({address:e,func:r,args:n,value:i,caller:s}){try{let o=new L9.Query({address:e,func:r,args:n,value:i,caller:s}),u=new M9.ContractQueryRequest(o).toHttpRequest(),a=await this.apiPost("query",u);return B9.ContractQueryResponse.fromHttpResponse(a)}catch(o){this.handleApiError(o,"query")}}};h();h();var kl=()=>new Date().setHours(new Date().getHours()+24),G1=t=>Date.now()>t;h();var F9=pe(Ve(),1),U9=pe(Ic(),1);var Au=async t=>{let e=me.get("address"),r=me.get("expires");if(!(r&&G1(r))&&e&&t.networkProvider){let i=new F9.Address(e),s=new U9.Account(i);try{let o=await t.networkProvider.getAccount(i),u=await t.networkProvider.getGuardianData(i);me.set("address",e),me.set("activeGuardian",u.guarded&&u.activeGuardian?.address?u.activeGuardian.address:""),me.set("nonce",o.nonce.valueOf()),me.set("balance",o.balance.toString()),s.update(o)}catch(o){let u=Kt(o);console.warn(`Something went wrong trying to synchronize the user account: ${u}`)}}};var q9=async(t,e,r,n="/")=>{let i=await G0(),o={callbackUrl:encodeURIComponent(`${window.location.origin}${n}`),token:e};try{if(i&&!await i.login(o))throw new Error("There were problems while logging in!")}catch(a){let c=Kt(a);throw new Error(c)}if(!i)throw new Error("There were problems with auth provider initialization!");let{signature:u}=i.account;if(me.set("loginToken",e),u&&me.set("signature",u),t.networkProvider&&u)try{let a=await i.getAddress();if(!a)throw new Error("Canceled!");me.set("address",a),me.set("loginMethod","browser-extension"),me.set("expires",kl()),await Au(t);let c=r.getToken(a,e,u);return me.set("accessToken",c),ge.run("onLoginSuccess"),i}catch(a){throw new Error(`Something went wrong trying to synchronize the user account: ${a?.message}`)}};h();h();var HV=pe(kV(),1),GV=pe(fd(),1);var Dge=t=>{let e=document.createElement("template");return e.innerHTML=t.trim(),e.content.firstChild?.cloneNode(!0)},Pge=t=>{let e=`${M8}?wallet-connect=${encodeURIComponent(t)}`,r=document.createElement("a");return r.setAttribute("href",e),r.setAttribute("rel","noopener noreferrer nofollow"),r.setAttribute("target","_blank"),r.textContent="xPortal login",r.classList.add("elven-qr-code-deep-link"),r},Rge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairings"),t},Bge=()=>{let t=document.createElement("div");return t.textContent="Existing WalletConnect pairings:",t.classList.add("elven-wc-pairings-header"),t},n3={},Mge=(t,e)=>{let r=document.createElement("button");return r.classList.add("elven-wc-pairings-remove-btn"),r.textContent="\u2716",n3[t.topic]=new AbortController,r.addEventListener("click",n=>{n.stopImmediatePropagation(),e(t.topic)},{signal:n3[t.topic].signal}),r},tw={},Lge=(t,e,r)=>{let n=document.createElement("div"),i=document.createElement("div");n.classList.add("elven-wc-pairing-item"),n.setAttribute("id",t.topic),i.classList.add("elven-wc-pairing-item-description"),i.textContent=`${t.peerMetadata?.description} (${t.peerMetadata?.url})`,n.appendChild(i);let s=Mge(t,e);return n.appendChild(s),tw[t.topic]=new AbortController,n.addEventListener("click",()=>r(t.topic),{signal:tw[t.topic].signal}),n},Fge=()=>{let t=document.createElement("div");return t.classList.add("elven-wc-pairing-item-confirm-msessage"),t.setAttribute("id","elven-wc-pairing-item-confirm-msessage"),t.innerText="Confirm on xPortal app!",t},Uge=t=>{if(!t)return;document.getElementById(t)?.remove()},qge=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),Vge=async t=>t?await HV.default.toString(t,{type:"svg"}):void 0,jV=async(t,e,r,n)=>{if(!t)throw new Error("Please provide the QR Code and WalletConnect Pairings container id!");let i=null;typeof t=="string"?i=document.getElementById(t):t instanceof HTMLElement&&(i=t);let s=await Vge(e),o;if(s&&(o=Dge(s)),i&&o&&(i.replaceChildren(),i.appendChild(o),qge()&&i.appendChild(Pge(e))),i&&r instanceof GV.WalletConnectV2Provider){let u=r.pairings,a=async f=>{try{f&&(await r.logout({topic:f}),Uge(f))}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to remove the existing pairing: ${w}`)}finally{tw[f].abort()}},c=async f=>{try{let{approval:d}=await r.connect({topic:f,methods:["mvx_cancelAction","mvx_signNativeAuthToken"]});document.getElementById("elven-wc-pairing-item-confirm-msessage")||document.getElementById(f)?.after(Fge()),await r.login({approval:d,token:n})}catch(d){let w=Kt(d);console.warn(`Something went wrong trying to login the user: ${w}`)}finally{for(let d of Object.values(tw))d?.abort();for(let d of Object.values(n3))d?.abort()}};if(u&&u.length>0){let f=Rge();i.appendChild(f);let d=Bge();f.appendChild(d);for(let w of u){let A=Lge(w,a,c);f.appendChild(A)}}}return i};var rw=pe(fd(),1);var zV=async(t,e,r,n)=>{if(!n)throw new Error("You haven't provided the QR code container DOM element id");let i=B1(t.initOptions.walletConnectV2RelayAddresses);if(!i||!t.networkProvider)throw new Error("Something wen't wrong with the initialization (ApiNetworkProvider or Wallet Connect Bridge address), plese try to refresh the page!");if(!t.initOptions.walletConnectV2ProjectId)throw new Error("Please provide your WalletConnect project id. You can get it here: https://cloud.walletconnect.com)");if(!t.initOptions.chainType)throw new Error("Please provide the chain type in ElvenJS.init function!");let s,o={onClientLogin:async()=>{if(t.dappProvider instanceof rw.WalletConnectV2Provider){let a=await t.dappProvider.getAddress(),c=await t.dappProvider.getSignature();me.set("address",a),me.set("loginMethod","mobile"),me.set("expires",kl()),await Au(t),c&&me.set("signature",c),me.set("loginToken",e);let f=r.getToken(a,e,c);me.set("accessToken",f),ge.run("onLoginSuccess"),s?.replaceChildren()}},onClientLogout:async()=>{t.dappProvider instanceof rw.WalletConnectV2Provider&&await Fl(t)},onClientEvent:a=>{console.log("wc2 session event: ",a)}},u=new rw.WalletConnectV2Provider(o,Rr[t.initOptions.chainType].shortId,i,t.initOptions.walletConnectV2ProjectId);try{if(u){t.dappProvider=u,ge.run("onQrPending"),await u.init();let{uri:a,approval:c}=await u.connect({methods:["mvx_cancelAction","mvx_signNativeAuthToken"]}),f=e?`${a}&token=${e}`:a;return n&&f&&(s=await jV(n,f,u,e),ge.run("onQrLoaded")),await u.login({approval:c,token:e}),u}}catch(a){let c=Kt(a);console.warn(`Something went wrong trying to login the user: ${c}`),ge.run("onLoginFailure",c)}};h();var QV=pe(Dl(),1);var i3=async(t,e,r,n)=>{let i=new QV.WalletProvider(`${t}${Po}`),o={callbackUrl:typeof window<"u"?encodeURIComponent(`${window.location.origin}${n||"/"}`):"/",token:e};try{return me.set("loginMethod",Rr[r].xAliasAddress===t?"x-alias":"web-wallet"),await i.login(o),me.set("expires",kl()),me.set("loginToken",e),i}catch(u){let a=Kt(u);console.warn(`Something went wrong trying to login the user: ${a}`),me.set("loginMethod",""),ge.run("onLoginFailure",a)}};h();var ln=t=>{if(typeof window<"u"){let e=new URL(window.location.href);return new URLSearchParams(e.search).get(t)}};h();var KV=pe(Dl(),1);var WV=pe(bC(),1),s3=async(t,e)=>{let r=ln("signature"),n=ln("address"),i=me.get("address"),s=me.get("loginToken");if(r&&me.set("signature",r),n||i){n&&(me.set("address",n),window.history.replaceState(null,"",window.location.pathname));let o=new KV.WalletProvider(`${t}${Po}`);if(r&&e&&n){let a=new WV.NativeAuthClient({apiUrl:e,origin:window.location.origin}).getToken(n,s,r);me.set("accessToken",a)}return o}};h();var $V=pe(Ic(),1),YV=pe(U0(),1);var nw=async(t,e)=>{ge.run("onTxSent",t);let n=await new YV.TransactionWatcher(e).awaitCompleted(t),i=n.sender,s=new $V.Account(i),o=await e.getAccount(i);s.update(o),me.set("address",s.address.bech32()),me.set("balance",s.balance.toString()),ge.run("onTxFinalized",n)};h();var Kl=pe(XV(),1),ek=pe(Xr(),1);h();var ZV=pe(Ic(),1);var iw=t=>{let e=t.getSender(),r=new ZV.Account(e),n=t.nonce.valueOf();r.incrementNonce(),me.set("nonce",(n+1n).toString())};var tk=async(t,e,r,n)=>{if(ln(Kl.WALLET_PROVIDER_CALLBACK_PARAM)===Kl.WALLET_PROVIDER_CALLBACK_PARAM_TX_SIGNED&&t&&e){let s=me.get("activeGuardian"),o=me.get("loginMethod"),u=ln("hasWebWalletGuardianSign"),a;if("getTransactionsFromWalletUrl"in t){if(a=t.getTransactionsFromWalletUrl()?.[0],!a)return;o==="web-wallet"&&(a.data=p.Buffer.from(a.data).toString("base64"))}else s&&o!=="web-wallet"&&o!=="x-alias"&&u&&(a=new Kl.WalletProvider(`${r}${Po}`).getTransactionsFromWalletUrl()?.[0]);if(a){let c=ek.Transaction.fromPlainObject(a);c.nonce=BigInt(n),iw(c);try{ge.run("onTxStart",c),await e.sendTransaction(c),await nw(c,e)}catch(f){let w=`Getting transaction information failed! ${Kt(f)}`;throw ge.run("onTxFailure",c,w),new Error(w)}finally{window.history.replaceState(null,"",window.location.pathname)}}window.history.replaceState(null,"",window.location.pathname)}};h();var sw=pe($l(),1),rk=pe(Ve(),1),nk=pe(Dl(),1);var ik=t=>{let e=me.get("activeGuardian");if(e){let r={guarded:!0};t.setVersion(sw.TransactionVersion.withTxOptions()),t.setOptions(sw.TransactionOptions.withOptions(r)),t.setGuardian(rk.Address.fromBech32(e))}return t},sk=async(t,e)=>{let r=new nk.WalletProvider(`${e}${Po}`),n=window?.location.href,i=new URL(n);i.searchParams.set("hasWebWalletGuardianSign","true"),await r.guardTransactions([t],{callbackUrl:encodeURIComponent(i.toString())})},ok=t=>{let e=me.get("activeGuardian");return!(!me.get("address")||!e||t.isGuardedTransaction())};h();var ak=()=>{let t=!ln("walletProviderStatus"),e=ln("status")==="signed",r=ln("message"),n=ln("signature");t&&e&&r&&n&&(ge.run("onSignMsgFinalized",r,n),window.history.replaceState(null,"",window.location.pathname))};h();var a3=pe(Xr(),1);h();var uk=(e=>(e.reloginResponse="RELOGIN_RESPONSE",e))(uk||{}),ck=(u=>(u.handshakeResponse="HANDSHAKE_RESPONSE",u.loginResponse="LOGIN_RESPONSE",u.disconnectResponse="DISCONNECT_RESPONSE",u.cancelResponse="CANCEL_RESPONSE",u.signTransactionsResponse="SIGN_TRANSACTIONS_RESPONSE",u.signMessageResponse="SIGN_MESSAGE_RESPONSE",u.noneResponse="NONE_RESPONSE",u))(ck||{}),o3={...ck,...uk},lk=(r=>(r.signTransactionsWithGuardianResponse="SIGN_TRANSACTIONS_WITH_GUARDIAN_RESPONSE",r.reloginRequest="RELOGIN_REQUEST",r))(lk||{}),fk=(o=>(o.signTransactionsRequest="SIGN_TRANSACTIONS_REQUEST",o.signMessageRequest="SIGN_MESSAGE_REQUEST",o.loginRequest="LOGIN_REQUEST",o.logoutRequest="LOGOUT_REQUEST",o.cancelAction="CANCEL_ACTION_REQUEST",o.finalizeHandshakeRequest="FINALIZE_HANDSHAKE_REQUEST",o))(fk||{}),Tu={...fk,...lk};h();var hk=typeof window<"u"?window:{},dk=()=>hk.ReactNativeWebView?"reactNative":hk.webkit?"ios":"web",_u=()=>typeof window<"u"&&typeof window?.location<"u"?window?.parent?.origin??"*":"*",ow=t=>Object.prototype.toString.call(t)==="[object String]";h();var aw={signTransactions:{ios:t=>window.webkit.messageHandlers.signTransactions.postMessage(t,_u()),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signTransactionsRequest,message:t}),_u())},signMessage:{ios:t=>window.webkit.messageHandlers.signMessage.postMessage(t),reactNative:t=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t})),web:t=>window?.postMessage(JSON.stringify({type:Tu.signMessageRequest,message:t}),_u())},logout:{ios:()=>window.webkit.messageHandlers.logout.postMessage(),reactNative:()=>window?.ReactNativeWebView.postMessage(JSON.stringify({type:Tu.logoutRequest})),web:()=>window?.postMessage(JSON.stringify({type:Tu.logoutRequest}),_u())}};var uw=dk(),cw="message",gk=t=>{let e=r=>{let n=r.data;if(!(r.target.origin!=_u()&&uw!="reactNative"))try{n=JSON.parse(n),t(n)}catch{console.error("error parsing response")}};document&&document.addEventListener(cw,e),window&&window.addEventListener(cw,e)},fa=class{constructor(){}async logout(){return aw.logout[uw](),new Promise(e=>{e(!0)})}async signMessage(e){try{return aw.signMessage[uw](e),await new Promise((n,i)=>{window.signMessageResponse=(o,u)=>{if(u){i(u),window.signMessageResponse=null;return}n(o),window.signMessageResponse=null};function s(o){let{message:u,type:a}=o;if(a===o3.signMessageResponse&&u!=null){let{signedMessage:c,error:f}=u;f?i(f):n(c)}document?.removeEventListener(cw,s)}gk(s)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransactions(e){try{let r=e.map(i=>i.toPlainObject());return aw.signTransactions[uw](r),await new Promise((i,s)=>{window.transactionsSigned=(u,a)=>{if(u=JSON.parse(u),a){s(a),window.transactionsSigned=null;return}i(u.map(c=>a3.Transaction.fromPlainObject(c))),window.transactionsSigned=null};function o(u){let{message:a,type:c}=u;if(c===o3.signTransactionsResponse){let{transactions:f,error:d}=a;try{d?s(d):i(f.map(w=>a3.Transaction.fromPlainObject(w)))}catch{s("Unable to sign")}}document&&document.removeEventListener(cw,o)}gk(o)})}catch(r){throw console.error("error sending transaction",r),r}}async signTransaction(e){return(await this.signTransactions([e]))[0]}};h();h();h();function Gge(t){try{let e=atob(t),r=btoa(e),n=p.Buffer.from(t,"base64").toString(),i=p.Buffer.from(n).toString("base64");if(t===r&&t===i||e===n)return!0}catch{return!1}return!1}function Wl(t){return Gge(t)?atob(t):t}h();var pk=t=>{if(!t||!ow(t))return null;let e=t.split(".");if(e.length!==4)return null;try{let[r,n,i,s]=e,o=JSON.parse(Wl(s)),u=Wl(r);return{ttl:Number(i),extraInfo:o,origin:u,blockHash:n}}catch(r){return console.error(`Error trying to decode ${t}:`,r),null}};var mk=t=>{if(!t||!ow(t))return null;let e=t.split(".");if(e.length!==3)return console.error("Invalid nativeAuthToken. You may be trying to decode a loginToken. Try using decodeLoginToken method instead"),null;try{let[r,n,i]=e,s=Wl(r),o=Wl(n),u=pk(o);if(!u)return{address:s,body:o,signature:i,blockHash:"",origin:"",ttl:0};let a={...u,address:s,body:o,signature:i};return u.extraInfo?.timestamp||delete a.extraInfo,a}catch{return null}};function yk(t,e){let r=mk(t);if(r==null)return;let{signature:n,address:i,body:s}=r;n&&t&&i&&(me.set("loginToken",s),me.set("accessToken",t),me.set("signature",n),me.set("address",i),me.set("loginMethod","x-portal-hub"),e.dappProvider=new fa)}h();var wk=t=>{t.onLoginStart&&ge.set("onLoginStart",t.onLoginStart),t.onLoginSuccess&&ge.set("onLoginSuccess",t.onLoginSuccess),t.onLoginFailure&&ge.set("onLoginFailure",t.onLoginFailure),t.onLogoutStart&&ge.set("onLogoutStart",t.onLogoutStart),t.onLogoutSuccess&&ge.set("onLogoutSuccess",t.onLogoutSuccess),t.onLogoutFailure&&ge.set("onLogoutFailure",t.onLogoutFailure),t.onQrPending&&ge.set("onQrPending",t.onQrPending),t.onQrLoaded&&ge.set("onQrLoaded",t.onQrLoaded),t.onTxStart&&ge.set("onTxStart",t.onTxStart),t.onTxSent&&ge.set("onTxSent",t.onTxSent),t.onTxFinalized&&ge.set("onTxFinalized",t.onTxFinalized),t.onTxFailure&&ge.set("onTxFailure",t.onTxFailure),t.onSignMsgStart&&ge.set("onSignMsgStart",t.onSignMsgStart),t.onSignMsgFinalized&&ge.set("onSignMsgFinalized",t.onSignMsgFinalized),t.onSignMsgFailure&&ge.set("onSignMsgFailure",t.onSignMsgFailure),t.onQueryStart&&ge.set("onQueryStart",t.onQueryStart),t.onQueryFinalized&&ge.set("onQueryFinalized",t.onQueryFinalized),t.onQueryFailure&&ge.set("onQueryFailure",t.onQueryFailure)};h();var lw=async t=>{ge.run("onLoginStart");try{await t(()=>{ge.run("onLoginSuccess")})}catch(e){let r=Kt(e);console.warn(`Something went wrong trying to login the user: ${r}`),ge.run("onLoginFailure",r)}};var f3=class{static async init(e){let r=me.get();if(r.expires&&G1(r.expires)){me.clear(),this.dappProvider=void 0;return}this.initOptions={chainType:H0,apiUrl:B8,apiTimeout:1e4,walletConnectV2ProjectId:"",walletConnectV2RelayAddresses:L8,...e},this.networkProvider=new H1(this.initOptions),wk(this.initOptions);let n=ln("accessToken");n&&await lw(async s=>{yk(n,this),await Au(this),s()}),(r?.address||(r.loginMethod==="web-wallet"||r.loginMethod==="x-alias")&&ln("address"))&&r?.loginMethod&&(await lw(async s=>{r.loginMethod==="browser-extension"&&(this.dappProvider=await G0()),r.loginMethod==="mobile"&&(this.dappProvider=await v9(this)),r.loginMethod==="x-portal-hub"&&(this.dappProvider=new fa),r.loginMethod==="web-wallet"&&this.initOptions?.chainType&&(this.dappProvider=await s3(Rr[this.initOptions.chainType].walletAddress,this.initOptions.apiUrl)),r.loginMethod==="x-alias"&&this.initOptions?.chainType&&(this.dappProvider=await s3(Rr[this.initOptions.chainType].xAliasAddress,this.initOptions.apiUrl)),await Au(this),s()}),this.initOptions?.chainType&&(await tk(this.dappProvider,this.networkProvider,Rr[this.initOptions.chainType][r.loginMethod==="x-alias"?"xAliasAddress":"walletAddress"],r.nonce),ak()))}static async login(e,r){if(!Object.values(SC).includes(e)){let i="Wrong login method!";throw ge.run("onLoginFailure",i),new Error(i)}if(!this.networkProvider){let i="Login failed: Use ElvenJs.init() first!";throw ge.run("onLoginFailure",i),new Error(i)}await lw(async()=>{let i=new vk.NativeAuthClient({apiUrl:this.initOptions?.apiUrl,origin:window.location.origin}),s=await i.initialize();if(e==="browser-extension"){let o=await q9(this,s,i,r?.callbackRoute);this.dappProvider=o}if(e==="mobile"){let o=await zV(this,s,i,r?.qrCodeContainer);this.dappProvider=o}if(e==="web-wallet"&&this.initOptions?.chainType){let o=await i3(Rr[this.initOptions.chainType].walletAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}if(e==="x-alias"&&this.initOptions?.chainType){let o=await i3(Rr[this.initOptions.chainType].xAliasAddress,s,this.initOptions?.chainType,r?.callbackRoute);this.dappProvider=o}})}static async logout(){try{let e=await Fl(this);return this.dappProvider=void 0,e}catch(e){let r=Kt(e);console.warn("Something went wrong when logging out: ",r)}}static async signAndSendTransaction(e){if(!this.dappProvider){let n="Transaction signing failed: There is no active session!";throw ge.run("onTxFailure",e,n),new Error(n)}if(!this.networkProvider){let n="Transaction signing failed: There is no active network provider!";throw ge.run("onTxFailure",e,n),new Error(n)}let r=ik(e);try{ge.run("onTxStart",e);let n=me.get();if(e.nonce=n.nonce,this.dappProvider instanceof u3.ExtensionProvider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof c3.WalletConnectV2Provider&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof fa&&(r=await this.dappProvider.signTransaction(e)),this.dappProvider instanceof l3.WalletProvider&&await this.dappProvider.signTransaction(e),n.loginMethod!=="web-wallet"&&n.loginMethod!=="x-alias"){let i=ok(r);if(i||iw(r),i&&this.initOptions?.chainType){await sk(r,Rr[this.initOptions.chainType].walletAddress);return}await this.networkProvider.sendTransaction(r),await nw(r,this.networkProvider)}}catch(n){let i=Kt(n);throw ge.run("onTxFailure",r,`Getting transaction information failed! ${i}`),new Error(`Getting transaction information failed! ${i}`)}return r}static async signMessage(e,r){if(!this.dappProvider){let i="Message signing failed: There is no active session!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}if(!this.networkProvider){let i="Message signing failed: There is no active network provider!";throw ge.run("onSignMsgFailure",e,i),new Error(i)}let n="";try{if(ge.run("onSignMsgStart",e),this.dappProvider instanceof u3.ExtensionProvider&&(n=(await this.dappProvider.signMessage(new fw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof c3.WalletConnectV2Provider&&(n=(await this.dappProvider.signMessage(new fw.SignableMessage({message:p.Buffer.from(e)}))).getSignature().toString("hex")),this.dappProvider instanceof fa&&(n=await this.dappProvider.signMessage(e)),this.dappProvider instanceof l3.WalletProvider){let s=u=>encodeURIComponent(u).replace(/[!'()*]/g,a=>`%${a.charCodeAt(0).toString(16).toUpperCase()}`),o=r?.callbackUrl||window.location.origin;await this.dappProvider.signMessage(new fw.SignableMessage({message:p.Buffer.from(e)}),{callbackUrl:encodeURIComponent(`${o}${o.includes("?")?"&":"?"}message=${s(e)}`)})}let i=me.get();return i.loginMethod!=="web-wallet"&&i.loginMethod!=="x-alias"&&ge.run("onSignMsgFinalized",e,n),{message:e,messageSignature:n}}catch(i){let s=Kt(i);throw ge.run("onSignMsgFailure",e,s),new Error(`Message signing failed! ${s}`)}}static async queryContract({address:e,func:r,args:n=[],value:i=0,caller:s}){if(!this.networkProvider)throw new Error("Query failed: There is no active network provider!");if(!e||!r)throw new Error("Query failed: The Query arguments are not valid! Address and func required");let o={address:e,func:r,args:n,value:i,caller:s};try{ge.run("onQueryStart",o);let u=await this.networkProvider.queryContract(o);return ge.run("onQueryFinalized",u),u}catch(u){let a=Kt(u);throw ge.run("onQueryFinalized",o,a),new Error(`Smart contract query failed! ${a}`)}}static{this.storage=me}static{this.destroy=()=>{this.networkProvider=void 0,this.dappProvider=void 0,this.initOptions=void 0,ge.clear()}}};h();rr();Ou.config({ROUNDING_MODE:Ou.ROUND_FLOOR});var jge=({amount:t,decimals:e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return BigInt(new Ou(t).shiftedBy(e).toFixed())},zge=({amount:t,decimals:e,rounding:r=e})=>{if(e<0)throw new Error("Decimal places shouldn't be negative number!");return new Ou(t).shiftedBy(-e).decimalPlaces(r).toFixed()};var export_Account=Kge.Account;var export_Address=Qge.Address;var export_AddressType=Sk.AddressType;var export_AddressValue=Sk.AddressValue;var export_BigUIntType=_s.BigUIntType;var export_BigUIntValue=_s.BigUIntValue;var export_BooleanType=bk.BooleanType;var export_BooleanValue=bk.BooleanValue;var export_BytesType=Ek.BytesType;var export_BytesValue=Ek.BytesValue;var export_ContractQueryResponse=Zge.ContractQueryResponse;var export_Message=Ak.Message;var export_MessageComputer=Ak.MessageComputer;var export_QueryArguments=Xge.QueryArguments;var export_SignableMessage=Jge.SignableMessage;var export_SmartContractTransactionsFactory=hw.SmartContractTransactionsFactory;var export_SmartContractTransactionsOutcomeParser=g3.SmartContractTransactionsOutcomeParser;var export_Token=h3.Token;var export_TokenComputer=h3.TokenComputer;var export_TokenManagementTransactionsFactory=hw.TokenManagementTransactionsFactory;var export_TokenManagementTransactionsOutcomeParser=g3.TokenManagementTransactionsOutcomeParser;var export_TokenOperationsFactory=d3.TokenOperationsFactory;var export_TokenOperationsFactoryConfig=d3.TokenOperationsFactoryConfig;var export_TokenOperationsOutcomeParser=d3.TokenOperationsOutcomeParser;var export_TokenTransfer=h3.TokenTransfer;var export_Transaction=Wge.Transaction;var export_TransactionComputer=$ge.TransactionComputer;var export_TransactionEventsParser=g3.TransactionEventsParser;var export_TransactionWatcher=Yge.TransactionWatcher;var export_TransactionsFactoryConfig=hw.TransactionsFactoryConfig;var export_TransferTransactionsFactory=hw.TransferTransactionsFactory;var export_U16Type=_s.U16Type;var export_U16Value=_s.U16Value;var export_U32Type=_s.U32Type;var export_U32Value=_s.U32Value;var export_U64Type=_s.U64Type;var export_U64Value=_s.U64Value;var export_U8Type=_s.U8Type;var export_U8Value=_s.U8Value;export{export_Account as Account,export_Address as Address,export_AddressType as AddressType,export_AddressValue as AddressValue,export_BigUIntType as BigUIntType,export_BigUIntValue as BigUIntValue,export_BooleanType as BooleanType,export_BooleanValue as BooleanValue,export_BytesType as BytesType,export_BytesValue as BytesValue,export_ContractQueryResponse as ContractQueryResponse,Rde as DappCoreWCV2CustomMethodsEnum,f3 as ElvenJS,y9 as EventStoreEvents,SC as LoginMethodsEnum,export_Message as Message,export_MessageComputer as MessageComputer,export_QueryArguments as QueryArguments,export_SignableMessage as SignableMessage,export_SmartContractTransactionsFactory as SmartContractTransactionsFactory,export_SmartContractTransactionsOutcomeParser as SmartContractTransactionsOutcomeParser,export_Token as Token,export_TokenComputer as TokenComputer,export_TokenManagementTransactionsFactory as TokenManagementTransactionsFactory,export_TokenManagementTransactionsOutcomeParser as TokenManagementTransactionsOutcomeParser,export_TokenOperationsFactory as TokenOperationsFactory,export_TokenOperationsFactoryConfig as TokenOperationsFactoryConfig,export_TokenOperationsOutcomeParser as TokenOperationsOutcomeParser,export_TokenTransfer as TokenTransfer,export_Transaction as Transaction,export_TransactionComputer as TransactionComputer,export_TransactionEventsParser as TransactionEventsParser,export_TransactionWatcher as TransactionWatcher,export_TransactionsFactoryConfig as TransactionsFactoryConfig,export_TransferTransactionsFactory as TransferTransactionsFactory,export_U16Type as U16Type,export_U16Value as U16Value,export_U32Type as U32Type,export_U32Value as U32Value,export_U64Type as U64Type,export_U64Value as U64Value,export_U8Type as U8Type,export_U8Value as U8Value,Bde as WebWalletUrlParamsEnum,zge as formatAmount,jge as parseAmount}; /*! Bundled license information: ieee754/index.js: diff --git a/package-lock.json b/package-lock.json index d408761..26723d0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,11 +17,10 @@ "@multiversx/sdk-web-wallet-provider": "3.2.1", "@types/qrcode": "1.5.5", "@types/serve-handler": "6.1.4", - "@typescript-eslint/eslint-plugin": "7.7.0", - "@typescript-eslint/parser": "7.7.0", + "@typescript-eslint/eslint-plugin": "7.7.1", + "@typescript-eslint/parser": "7.7.1", "bignumber.js": "9.1.2", "esbuild": "0.20.2", - "esbuild-plugin-alias": "^0.2.1", "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", "eslint-plugin-prettier": "5.1.3", @@ -33,15 +32,6 @@ "typescript": "5.4.5" } }, - "node_modules/@aashutoshrathi/word-wrap": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz", - "integrity": "sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/@esbuild/aix-ppc64": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz", @@ -538,9 +528,9 @@ } }, "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.2.tgz", - "integrity": "sha512-6EwiSjwWYP7pTckG6I5eyFANjPhmPjUX9JRLUSfNPC7FX7zK9gyZAfUEaECL6ALTpGX5AjnBq3C9XmVWPitNpw==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", + "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", "dev": true }, "node_modules/@isaacs/cliui": { @@ -1297,9 +1287,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.11.10", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.10.tgz", - "integrity": "sha512-rZEfe/hJSGYmdfX9tvcPMYeYPW2sNl50nsw4jZmRcaG0HIAb0WYEpsB05GOb53vjqpyE9GUhlDQ4jLSoB5q9kg==", + "version": "20.12.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.7.tgz", + "integrity": "sha512-wq0cICSkRLVaf3UGLMGItu/PtdY7oaXaI/RVU+xliKVOtRna3PRY57ZDfztpDL0n11vfymMUnXv8QwYCO7L1wg==", "dev": true, "dependencies": { "undici-types": "~5.26.4" @@ -1330,16 +1320,16 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.7.0.tgz", - "integrity": "sha512-GJWR0YnfrKnsRoluVO3PRb9r5aMZriiMMM/RHj5nnTrBy1/wIgk76XCtCKcnXGjpZQJQRFtGV9/0JJ6n30uwpQ==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.7.1.tgz", + "integrity": "sha512-KwfdWXJBOviaBVhxO3p5TJiLpNuh2iyXyjmWN0f1nU87pwyvfS0EmjC6ukQVYVFJd/K1+0NWGPDXiyEyQorn0Q==", "dev": true, "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "7.7.0", - "@typescript-eslint/type-utils": "7.7.0", - "@typescript-eslint/utils": "7.7.0", - "@typescript-eslint/visitor-keys": "7.7.0", + "@typescript-eslint/scope-manager": "7.7.1", + "@typescript-eslint/type-utils": "7.7.1", + "@typescript-eslint/utils": "7.7.1", + "@typescript-eslint/visitor-keys": "7.7.1", "debug": "^4.3.4", "graphemer": "^1.4.0", "ignore": "^5.3.1", @@ -1365,15 +1355,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.7.0.tgz", - "integrity": "sha512-fNcDm3wSwVM8QYL4HKVBggdIPAy9Q41vcvC/GtDobw3c4ndVT3K6cqudUmjHPw8EAp4ufax0o58/xvWaP2FmTg==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.7.1.tgz", + "integrity": "sha512-vmPzBOOtz48F6JAGVS/kZYk4EkXao6iGrD838sp1w3NQQC0W8ry/q641KU4PrG7AKNAf56NOcR8GOpH8l9FPCw==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "7.7.0", - "@typescript-eslint/types": "7.7.0", - "@typescript-eslint/typescript-estree": "7.7.0", - "@typescript-eslint/visitor-keys": "7.7.0", + "@typescript-eslint/scope-manager": "7.7.1", + "@typescript-eslint/types": "7.7.1", + "@typescript-eslint/typescript-estree": "7.7.1", + "@typescript-eslint/visitor-keys": "7.7.1", "debug": "^4.3.4" }, "engines": { @@ -1393,13 +1383,13 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.7.0.tgz", - "integrity": "sha512-/8INDn0YLInbe9Wt7dK4cXLDYp0fNHP5xKLHvZl3mOT5X17rK/YShXaiNmorl+/U4VKCVIjJnx4Ri5b0y+HClw==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.7.1.tgz", + "integrity": "sha512-PytBif2SF+9SpEUKynYn5g1RHFddJUcyynGpztX3l/ik7KmZEv19WCMhUBkHXPU9es/VWGD3/zg3wg90+Dh2rA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "7.7.0", - "@typescript-eslint/visitor-keys": "7.7.0" + "@typescript-eslint/types": "7.7.1", + "@typescript-eslint/visitor-keys": "7.7.1" }, "engines": { "node": "^18.18.0 || >=20.0.0" @@ -1410,13 +1400,13 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.7.0.tgz", - "integrity": "sha512-bOp3ejoRYrhAlnT/bozNQi3nio9tIgv3U5C0mVDdZC7cpcQEDZXvq8inrHYghLVwuNABRqrMW5tzAv88Vy77Sg==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.7.1.tgz", + "integrity": "sha512-ZksJLW3WF7o75zaBPScdW1Gbkwhd/lyeXGf1kQCxJaOeITscoSl0MjynVvCzuV5boUz/3fOI06Lz8La55mu29Q==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "7.7.0", - "@typescript-eslint/utils": "7.7.0", + "@typescript-eslint/typescript-estree": "7.7.1", + "@typescript-eslint/utils": "7.7.1", "debug": "^4.3.4", "ts-api-utils": "^1.3.0" }, @@ -1437,9 +1427,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.7.0.tgz", - "integrity": "sha512-G01YPZ1Bd2hn+KPpIbrAhEWOn5lQBrjxkzHkWvP6NucMXFtfXoevK82hzQdpfuQYuhkvFDeQYbzXCjR1z9Z03w==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.7.1.tgz", + "integrity": "sha512-AmPmnGW1ZLTpWa+/2omPrPfR7BcbUU4oha5VIbSbS1a1Tv966bklvLNXxp3mrbc+P2j4MNOTfDffNsk4o0c6/w==", "dev": true, "engines": { "node": "^18.18.0 || >=20.0.0" @@ -1450,13 +1440,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.7.0.tgz", - "integrity": "sha512-8p71HQPE6CbxIBy2kWHqM1KGrC07pk6RJn40n0DSc6bMOBBREZxSDJ+BmRzc8B5OdaMh1ty3mkuWRg4sCFiDQQ==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.7.1.tgz", + "integrity": "sha512-CXe0JHCXru8Fa36dteXqmH2YxngKJjkQLjxzoj6LYwzZ7qZvgsLSc+eqItCrqIop8Vl2UKoAi0StVWu97FQZIQ==", "dev": true, "dependencies": { - "@typescript-eslint/types": "7.7.0", - "@typescript-eslint/visitor-keys": "7.7.0", + "@typescript-eslint/types": "7.7.1", + "@typescript-eslint/visitor-keys": "7.7.1", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -1478,17 +1468,17 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.7.0.tgz", - "integrity": "sha512-LKGAXMPQs8U/zMRFXDZOzmMKgFv3COlxUQ+2NMPhbqgVm6R1w+nU1i4836Pmxu9jZAuIeyySNrN/6Rc657ggig==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.7.1.tgz", + "integrity": "sha512-QUvBxPEaBXf41ZBbaidKICgVL8Hin0p6prQDu6bbetWo39BKbWJxRsErOzMNT1rXvTll+J7ChrbmMCXM9rsvOQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", "@types/json-schema": "^7.0.15", "@types/semver": "^7.5.8", - "@typescript-eslint/scope-manager": "7.7.0", - "@typescript-eslint/types": "7.7.0", - "@typescript-eslint/typescript-estree": "7.7.0", + "@typescript-eslint/scope-manager": "7.7.1", + "@typescript-eslint/types": "7.7.1", + "@typescript-eslint/typescript-estree": "7.7.1", "semver": "^7.6.0" }, "engines": { @@ -1503,12 +1493,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.7.0.tgz", - "integrity": "sha512-h0WHOj8MhdhY8YWkzIF30R379y0NqyOHExI9N9KCzvmu05EgG4FumeYa3ccfKUSphyWkWQE1ybVrgz/Pbam6YA==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.7.1.tgz", + "integrity": "sha512-gBL3Eq25uADw1LQ9kVpf3hRM+DWzs0uZknHYK3hq4jcTPqVCClHGDnB6UUUV2SFeBeA4KWHWbbLqmbGcZ4FYbw==", "dev": true, "dependencies": { - "@typescript-eslint/types": "7.7.0", + "@typescript-eslint/types": "7.7.1", "eslint-visitor-keys": "^3.4.3" }, "engines": { @@ -1856,15 +1846,14 @@ } }, "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", "dev": true, "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" + "minimalistic-assert": "^1.0.0" } }, "node_modules/asn1.js/node_modules/bn.js": { @@ -1902,10 +1891,13 @@ } }, "node_modules/available-typed-arrays": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", - "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", "dev": true, + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, "engines": { "node": ">= 0.4" }, @@ -2086,25 +2078,62 @@ } }, "node_modules/browserify-sign": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.2.tgz", - "integrity": "sha512-1rudGyeYY42Dk6texmv7c4VcQ0EsvVbLwZkA+AQB7SxvXxmcD93jcHie8bzecJ+ChDlmAm2Qyu0+Ccg5uhZXCg==", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.3.tgz", + "integrity": "sha512-JWCZW6SKhfhjJxO8Tyiiy+XYB7cqd2S5/+WeYHsKdNKFlCBhKbblba1A/HN/90YwtxKc8tCErjffZl++UNmGiw==", "dev": true, "dependencies": { "bn.js": "^5.2.1", "browserify-rsa": "^4.1.0", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", - "elliptic": "^6.5.4", + "elliptic": "^6.5.5", + "hash-base": "~3.0", "inherits": "^2.0.4", - "parse-asn1": "^5.1.6", - "readable-stream": "^3.6.2", + "parse-asn1": "^5.1.7", + "readable-stream": "^2.3.8", "safe-buffer": "^5.2.1" }, "engines": { - "node": ">= 4" + "node": ">= 0.12" } }, + "node_modules/browserify-sign/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "node_modules/browserify-sign/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/browserify-sign/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, "node_modules/browserify-zlib": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", @@ -2160,14 +2189,19 @@ } }, "node_modules/call-bind": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", - "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", "dev": true, "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.1", - "set-function-length": "^1.1.1" + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -2402,6 +2436,12 @@ "integrity": "sha512-L2rLOcK0wzWSfSDA33YR+PUHDG10a8px7rUHKWbGLP4YfbsMed2KFUw5fczvDPbT98DDe3LEzviswl810apTEw==", "dev": true }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, "node_modules/create-ecdh": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", @@ -2543,17 +2583,20 @@ "dev": true }, "node_modules/define-data-property": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", - "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", "dev": true, "dependencies": { - "get-intrinsic": "^1.2.1", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.0" + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/define-properties": { @@ -2700,9 +2743,9 @@ "dev": true }, "node_modules/elliptic": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", - "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", + "version": "6.5.5", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.5.tgz", + "integrity": "sha512-7EjbcmUm17NQFu4Pmgmq2olYMj8nwMnpcddByChSUjArp8F5DQWcIcpriwO4ZToLNAJig0yiyjswfyGNje/ixw==", "dev": true, "dependencies": { "bn.js": "^4.11.9", @@ -2741,6 +2784,27 @@ "once": "^1.4.0" } }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "dev": true, + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.2.tgz", @@ -2779,12 +2843,6 @@ "@esbuild/win32-x64": "0.20.2" } }, - "node_modules/esbuild-plugin-alias": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/esbuild-plugin-alias/-/esbuild-plugin-alias-0.2.1.tgz", - "integrity": "sha512-jyfL/pwPqaFXyKnj8lP8iLk6Z0m099uXR45aSN8Av1XD4vhvQutxxPzgA2bTcAwQpa1zCXDcWOlhFgyP3GKqhQ==", - "dev": true - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -3116,9 +3174,9 @@ } }, "node_modules/fastq": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.0.tgz", - "integrity": "sha512-zGygtijUMT7jnk3h26kUms3BkSDp4IfIKjmnqI2tvx6nuBfiF1UqOxbnLfzdv+apBy+53oaImsKtMw/xYbW+1w==", + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", + "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", "dev": true, "dependencies": { "reusify": "^1.0.4" @@ -3245,9 +3303,9 @@ } }, "node_modules/flatted": { - "version": "3.2.9", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz", - "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", + "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", "dev": true }, "node_modules/follow-redirects": { @@ -3348,16 +3406,20 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", - "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", "dev": true, "dependencies": { + "es-errors": "^1.3.0", "function-bind": "^1.1.2", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "hasown": "^2.0.0" }, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -3381,16 +3443,16 @@ } }, "node_modules/glob": { - "version": "10.3.10", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.10.tgz", - "integrity": "sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g==", + "version": "10.3.12", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.12.tgz", + "integrity": "sha512-TCNv8vJ+xz4QiqTpfOJA7HvYv+tNIRHKfUWw/q+v2jdgN4ebz+KY9tGx5J4rHP0o84mNP+ApH66HRX8us3Khqg==", "dev": true, "dependencies": { "foreground-child": "^3.1.0", - "jackspeak": "^2.3.5", + "jackspeak": "^2.3.6", "minimatch": "^9.0.1", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", - "path-scurry": "^1.10.1" + "minipass": "^7.0.4", + "path-scurry": "^1.10.2" }, "bin": { "glob": "dist/esm/bin.mjs" @@ -3495,21 +3557,21 @@ } }, "node_modules/has-property-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", - "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", "dev": true, "dependencies": { - "get-intrinsic": "^1.2.2" + "es-define-property": "^1.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", - "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", "dev": true, "engines": { "node": ">= 0.4" @@ -3531,12 +3593,12 @@ } }, "node_modules/has-tostringtag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", - "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", "dev": true, "dependencies": { - "has-symbols": "^1.0.2" + "has-symbols": "^1.0.3" }, "engines": { "node": ">= 0.4" @@ -3546,14 +3608,13 @@ } }, "node_modules/hash-base": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.0.tgz", - "integrity": "sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha512-EeeoJKjTyt868liAlVmcv2ZsUfGHlE3Q+BICOXcZiwN3osr5Q/zFGYmTJpoIzuaSTAwndFy+GqhEwlU4L3j4Ow==", "dev": true, "dependencies": { - "inherits": "^2.0.4", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" }, "engines": { "node": ">=4" @@ -3570,9 +3631,9 @@ } }, "node_modules/hasown": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", - "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", "dev": true, "dependencies": { "function-bind": "^1.1.2" @@ -3879,12 +3940,12 @@ } }, "node_modules/is-typed-array": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.12.tgz", - "integrity": "sha512-Z14TF2JNG8Lss5/HMqt0//T9JeHXttXy5pH/DBU4vi98ozO2btxzq9MwYDZYnKwU8nRsz/+GVFVRDq3DkVuSPg==", + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", + "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", "dev": true, "dependencies": { - "which-typed-array": "^1.1.11" + "which-typed-array": "^1.1.14" }, "engines": { "node": ">= 0.4" @@ -3923,6 +3984,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -4122,9 +4189,9 @@ "peer": true }, "node_modules/lru-cache": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.0.tgz", - "integrity": "sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q==", + "version": "10.2.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.1.tgz", + "integrity": "sha512-tS24spDe/zXhWbNPErCHs/AGOzbKGHT+ybSBqmdLm8WZ1xXLWvH8Qn71QPAlqVhd0qUTWjy+Kl9JmISgDdEjsA==", "dev": true, "engines": { "node": "14 || >=16.14" @@ -4474,13 +4541,13 @@ } }, "node_modules/object-is": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", - "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz", + "integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==", "dev": true, "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" + "call-bind": "^1.0.7", + "define-properties": "^1.2.1" }, "engines": { "node": ">= 0.4" @@ -4564,17 +4631,17 @@ } }, "node_modules/optionator": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", - "integrity": "sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==", + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, "dependencies": { - "@aashutoshrathi/word-wrap": "^1.2.3", "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", - "type-check": "^0.4.0" + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" }, "engines": { "node": ">= 0.8.0" @@ -4644,16 +4711,20 @@ } }, "node_modules/parse-asn1": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", - "integrity": "sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw==", + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.7.tgz", + "integrity": "sha512-CTM5kuWR3sx9IFamcl5ErfPl6ea/N8IYwiJ+vpeB2g+1iknv7zBl5uPwbMbRVznRVbrNY6lGuDoE5b30grmbqg==", "dev": true, "dependencies": { - "asn1.js": "^5.2.0", - "browserify-aes": "^1.0.0", - "evp_bytestokey": "^1.0.0", - "pbkdf2": "^3.0.3", - "safe-buffer": "^5.1.1" + "asn1.js": "^4.10.1", + "browserify-aes": "^1.2.0", + "evp_bytestokey": "^1.0.3", + "hash-base": "~3.0", + "pbkdf2": "^3.1.2", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.10" } }, "node_modules/path-browserify": { @@ -4702,12 +4773,12 @@ "dev": true }, "node_modules/path-scurry": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.10.1.tgz", - "integrity": "sha512-MkhCqzzBEpPvxxQ71Md0b1Kk51W01lrYvlMzSUaIzNsODdd7mqhiimSZlr+VegAz5Z6Vzt9Xg2ttE//XBhH3EQ==", + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.10.2.tgz", + "integrity": "sha512-7xTavNy5RQXnsjANvVvMkEjvloOinkAjv/Z6Ildz9v2RinZ4SBKTWFOVRbaF8p0vpHnyjV/UwNDdKuUv6M5qcA==", "dev": true, "dependencies": { - "lru-cache": "^9.1.1 || ^10.0.0", + "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" }, "engines": { @@ -4836,6 +4907,15 @@ "node": ">=10.13.0" } }, + "node_modules/possible-typed-array-names": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", + "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "dev": true, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -4881,6 +4961,12 @@ "node": ">= 0.6.0" } }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true + }, "node_modules/process-warning": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-1.0.0.tgz", @@ -5230,12 +5316,6 @@ "node": ">=10" } }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true - }, "node_modules/semver": { "version": "7.6.0", "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", @@ -5329,16 +5409,17 @@ "dev": true }, "node_modules/set-function-length": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.0.tgz", - "integrity": "sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", "dev": true, "dependencies": { - "define-data-property": "^1.1.1", + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.2", + "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.1" + "has-property-descriptors": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -5385,14 +5466,18 @@ } }, "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", "dev": true, "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -5945,12 +6030,12 @@ } }, "node_modules/url/node_modules/qs": { - "version": "6.11.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.2.tgz", - "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==", + "version": "6.12.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.12.1.tgz", + "integrity": "sha512-zWmv4RSuB9r2mYQw3zxQuHWeU+42aKi1wWig/j4ele4ygELZ7PEO6MM7rim9oAQH2A5MWfsAVf/jPvTPgCbvUQ==", "dev": true, "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" @@ -6022,16 +6107,16 @@ "dev": true }, "node_modules/which-typed-array": { - "version": "1.1.13", - "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.13.tgz", - "integrity": "sha512-P5Nra0qjSncduVPEAr7xhoF5guty49ArDTwzJ/yNuPIbZppyRxFQsRCWrocxIY+CnMVG+qfbU2FmDKyvSGClow==", + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", + "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", "dev": true, "dependencies": { - "available-typed-arrays": "^1.0.5", - "call-bind": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", "for-each": "^0.3.3", "gopd": "^1.0.1", - "has-tostringtag": "^1.0.0" + "has-tostringtag": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -6040,6 +6125,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", diff --git a/package.json b/package.json index 42ae351..aaf99dd 100644 --- a/package.json +++ b/package.json @@ -49,11 +49,10 @@ "@multiversx/sdk-web-wallet-provider": "3.2.1", "@types/qrcode": "1.5.5", "@types/serve-handler": "6.1.4", - "@typescript-eslint/eslint-plugin": "7.7.0", - "@typescript-eslint/parser": "7.7.0", + "@typescript-eslint/eslint-plugin": "7.7.1", + "@typescript-eslint/parser": "7.7.1", "bignumber.js": "9.1.2", "esbuild": "0.20.2", - "esbuild-plugin-alias": "^0.2.1", "eslint": "8.57.0", "eslint-config-prettier": "9.1.0", "eslint-plugin-prettier": "5.1.3", From 6332910a195813930261405ab2adf2e31f06b6a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20=C4=86wirko?= Date: Sun, 28 Apr 2024 15:57:30 +0200 Subject: [PATCH 4/5] remove console.log --- example/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/index.html b/example/index.html index 8a8baf1..bf0f3f6 100644 --- a/example/index.html +++ b/example/index.html @@ -202,7 +202,7 @@

Other demos:

// Transaction callbacks onTxStart: (tx) => { uiPending(true); }, onTxSent: (tx) => { const hash = tx.getHash().toString(); hash && updateTxHashContainer(hash, true); }, - onTxFinalized: (tx) => { console.log(tx); tx?.hash && updateTxHashContainer(tx.hash); uiPending(false); }, + onTxFinalized: (tx) => { tx?.hash && updateTxHashContainer(tx.hash); uiPending(false); }, onTxFailure: (tx, error) => { displayError(error); uiPending(false); }, // Qr code callbacks: onQrPending: () => { uiPending(true); }, From 7090846ae76b1e214d679d1df800f68bedd7bf09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20=C4=86wirko?= Date: Sun, 28 Apr 2024 16:48:43 +0200 Subject: [PATCH 5/5] update the demo --- example/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/index.html b/example/index.html index bf0f3f6..d277f02 100644 --- a/example/index.html +++ b/example/index.html @@ -304,7 +304,7 @@

Other demos:

gasLimit, chainID: 'D', data: textEncoder.encode(demoMessage), - value: TokenTransfer.egldFromAmount(0.001), + value: parseAmount({ amount: '0.001', decimals: 18 }), sender: new Address(ElvenJS.storage.get('address')), }); @@ -325,7 +325,7 @@

Other demos:

// You can use the community-based faucet to get the BUILDO-22c0a5 token: https://r3d4.fr/faucet const tokenTransfer = new TokenTransfer({ token: new Token({ identifier: 'BUILDO-22c0a5' }), - amount: 1000000000000000000n, + amount: parseAmount({ amount: '1', decimals: 18 }), }); const factory = new TransferTransactionsFactory({